@henryqw/pi-pr 4.0.7 → 4.0.9

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.
package/README.md CHANGED
@@ -44,9 +44,12 @@ Run `/pr` in a GitHub checkout. It reads fresh pull request and local state, the
44
44
 
45
45
  For creation, put an optional base branch first. For example, run `/pr --base release/2026 Keep the title concise.` The base is a branch name, not a host or repository. Only creation accepts the base and remaining guidance. Other routes reject them instead of ignoring them.
46
46
 
47
+ Run `/pr --feedback` to explicitly start or resume a feedback sweep. Use it for actionable conversation comments that do not select the sweep automatically. It cannot be combined with a base, other options, or instructions.
48
+
47
49
  | Surface | Type | Purpose |
48
50
  | --- | --- | --- |
49
51
  | `/pr [--base BRANCH] [creation instructions]` | command | Run the current pull request's next safe route. |
52
+ | `/pr --feedback` | command | Explicitly start or resume the guarded feedback sweep. |
50
53
  | Footer | ui | Show a linked `PR #number` and one plain-language status. |
51
54
  | Widget | ui | Show one action hint or transient routing status. |
52
55
 
@@ -64,17 +67,18 @@ Each footer entry is one linked `PR #number` plus one plain-language status: `N
64
67
 
65
68
  | Current condition | `/pr` route |
66
69
  | --- | --- |
67
- | No current-branch pull request, no published matching ref, safe Git push configuration, and a commit ahead of the selected base | Start pull-request creation. |
70
+ | No current-branch pull request, no published matching ref, safe Git push configuration, and a commit or ordinary pending work | Start pull-request creation. |
68
71
  | One open pull request inferred from a published matching ref | Confirm the exact `remote/ref`, then link the local branch. |
69
72
  | Ambiguous or unsafe discovery | Show the blocked reason and do not mutate Git or GitHub. |
70
73
  | Base update required or merge conflict | Update from the base branch's current target when the tree is clean and local HEAD equals the PR head. |
71
74
  | GitHub Actions job failed | Run the CI fix workflow when the same local prerequisite holds. |
72
75
  | External check or commit status failed | Show `CI failed` as a no-action blocker. |
73
76
  | Changes requested or unresolved review threads | Start or resume the package comment sweep when the same local prerequisite holds. |
77
+ | Explicit `/pr --feedback` on an open, configured pull request | Start or resume the sweep when the tree is clean and local HEAD equals the PR head. |
74
78
  | No-action state | Report the state without taking action. |
75
79
  | Merge-ready pull request | Ask for final confirmation, recheck fresh state, and squash-merge if confirmed. |
76
80
 
77
- `pi-pr-create` selects its base in this order: the leading `/pr --base BRANCH`, one `branch.<branch>.gh-merge-base` value, then the default branch of validated `origin`. It captures the selected base OID and merge-base. Creation requires at least one committed change ahead. Dirty work alone does not enable creation. If the current branch is the selected base, pi-pr stays silent because GitHub cannot create a pull request from a ref to itself.
81
+ `pi-pr-create` selects its base in this order: the leading `/pr --base BRANCH`, one `branch.<branch>.gh-merge-base` value, then the default branch of validated `origin`. It captures the selected base OID and merge-base. Creation requires a commit ahead or ordinary pending work, including untracked files. A Git operation in progress does not count as pending work. If the current branch is the selected base, pi-pr stays silent because GitHub cannot create a pull request from a ref to itself.
78
82
 
79
83
  The base always comes from validated `origin`. The head may use that repository or a fork with the same GitHub source. Base and head must use the same GitHub host. Other fork relationships stop before mutation.
80
84
 
@@ -92,6 +96,8 @@ Each helper workflow receives a random run ID and its first action. The run stay
92
96
 
93
97
  For comment sweeps, `/pr` checks the package recovery file without changing it. It selects `start` when recovery is absent. It selects `resume` only when valid recovery matches the fresh route authority. Invalid recovery stays unchanged and blocks dispatch with its path and reason.
94
98
 
99
+ `/pr --feedback` uses the same discovery, reservation, recovery, and guard checks. It can select the sweep even when CI failure or merge readiness would otherwise select another route. Without the flag, route priority stays unchanged.
100
+
95
101
  Direct skill or `pi_pr_*` tool calls cannot create route authority. Run `/pr` to reserve a fresh route.
96
102
 
97
103
  Only one helper run can exist at a time. Most runs expire when the agent settles. A create or branch-update conflict stays available for one user-guided continuation, then expires after that continuation settles. Session replacement and shutdown forget the run without aborting or cleaning a pending merge.
@@ -121,7 +127,7 @@ A missing pull request uses creation. For an existing pull request, the first ma
121
127
  5. Waiting or local safety block: no action.
122
128
  6. Merge-ready: allow clean local HEAD equal to or behind the PR head. Confirm, then merge directly.
123
129
 
124
- Ordinary conversation comments do not trigger a route or block a merge. Changes requested and unresolved review threads can select the package comment sweep.
130
+ Ordinary conversation comments do not trigger a route or block a merge. Changes requested and unresolved review threads can select the package comment sweep. Use `/pr --feedback` when a conversation comment needs action.
125
131
 
126
132
  The comment sweep resolves its bundled helper and references from the installed package skill path. It does not require an external `jq` executable.
127
133
 
@@ -137,7 +143,7 @@ The footer and widget load once at session start. A directory outside a Git work
137
143
 
138
144
  They refresh after local commits, PR creation, pushes, and each dispatched workflow settles. During creation, intermediate refreshes wait until the workflow settles. They also refresh after any successful delegated task settles. There is no periodic presentation refresh, so external changes may leave the footer and widget stale indefinitely. `/pr` reads fresh state before routing or acting and remains authoritative.
139
145
 
140
- The create widget stays hidden until the local branch has a commit beyond its creation point. `/pr` replaces any hint with routing feedback while it selects a route. The feedback clears before route interaction. A dispatched workflow keeps the widget hidden until the agent settles. Direct and no-action routes refresh it after completion. A failed command restores the prior hint and schedules a refresh, except when fresh lookup hits the GitHub API quota: it shows the sanitized message `GitHub API rate limit exhausted; retry after GitHub resets it` and does not immediately retry.
146
+ The create widget stays hidden on a clean branch with no commit ahead. It appears for a commit ahead or ordinary pending work. It stays hidden during a Git operation and when the current branch is the selected base. `/pr` replaces any hint with routing feedback while it selects a route. The feedback clears before route interaction. A dispatched workflow keeps the widget hidden until the agent settles. Direct and no-action routes refresh it after completion. A failed command restores the prior hint and schedules a refresh, except when fresh lookup hits the GitHub API quota: it shows the sanitized message `GitHub API rate limit exhausted; retry after GitHub resets it` and does not immediately retry.
141
147
 
142
148
  Presentation uses route priority, so draft appears before running CI. `/pr` reads fresh state before routing or merging. The command is authoritative for actions.
143
149
 
@@ -151,7 +157,7 @@ The GitHub response must match the observed URL, host, repository, head ref, hea
151
157
 
152
158
  ## Limits and recovery
153
159
 
154
- - `/pr` accepts creation syntax only as a leading `--base BRANCH`, followed by optional creation guidance. It does not open a browser.
160
+ - `/pr` accepts either standalone `--feedback` or creation syntax with leading `--base BRANCH` and optional guidance. It rejects unknown or conflicting options. It does not open a browser.
155
161
  - It does not run `/done` or `/sweep`.
156
162
  - Presentation refreshes do not auto-triage comments or start a workflow. The package comment sweep starts or resumes only when an explicit `/pr` selects it.
157
163
  - It does not enable auto-merge or add a merge queue.
@@ -11,8 +11,11 @@ import {
11
11
  } from "./pr-github.ts";
12
12
  import {
13
13
  deriveNextStep,
14
+ deriveRouteDecision,
15
+ type FeedbackRouteBlocker,
14
16
  type NextStep,
15
17
  type PullRequestTarget,
18
+ type RouteIntent,
16
19
  } from "./pr-routing.ts";
17
20
 
18
21
  export type WorkflowNextStep = Extract<NextStep, "create" | "update-branch" | "sweep" | "fix-ci">;
@@ -61,18 +64,42 @@ export type PrCommandDependencies = {
61
64
 
62
65
  type ParsedPrArguments = {
63
66
  base?: string;
67
+ intent: RouteIntent;
64
68
  instructions: string;
65
69
  };
66
70
 
67
71
  function parsePrArguments(args: string): ParsedPrArguments {
68
72
  const leading = args.trimStart();
73
+ const trimmed = leading.trim();
74
+ if (leading.startsWith("--feedback=")) throw new Error("/pr feedback syntax is --feedback");
75
+ if (/^--feedback(?:\s|$)/.test(leading)) {
76
+ if (trimmed !== "--feedback") throw new Error("/pr --feedback cannot be combined with other options or instructions");
77
+ return { intent: "feedback", instructions: "" };
78
+ }
79
+ if (/(?:^|\s)--feedback(?=\s|=|$)/.test(leading)) {
80
+ throw new Error("/pr --feedback cannot be combined with other options or instructions");
81
+ }
69
82
  if (leading.startsWith("--base=")) throw new Error("/pr base syntax is --base <branch>");
70
- if (!leading.startsWith("--base") || !/^--base(?:\s|$)/.test(leading)) {
71
- return { instructions: args.trim() };
83
+ if (/^--base(?:\s|$)/.test(leading)) {
84
+ const value = /^--base\s+(\S+)/.exec(leading);
85
+ if (!value) throw new Error("/pr --base requires a branch");
86
+ const instructions = leading.slice(value[0].length).trim();
87
+ if (instructions.startsWith("--")) throw new Error(`Unknown /pr option: ${instructions.split(/\s+/, 1)[0]}`);
88
+ return { base: value[1]!, intent: "automatic", instructions };
89
+ }
90
+ if (leading.startsWith("--")) throw new Error(`Unknown /pr option: ${leading.split(/\s+/, 1)[0]}`);
91
+ return { intent: "automatic", instructions: args.trim() };
92
+ }
93
+
94
+ function feedbackBlockerMessage(blocker: FeedbackRouteBlocker): string {
95
+ switch (blocker.kind) {
96
+ case "discovery-blocked": return "/pr --feedback is blocked because pull request discovery is unsafe";
97
+ case "pull-request-unavailable": return "/pr --feedback requires a current pull request";
98
+ case "pull-request-not-open": return "/pr --feedback requires an open pull request";
99
+ case "target-not-configured": return "/pr --feedback requires a configured pull request target; run /pr to link the branch first";
100
+ case "worktree-dirty": return "/pr --feedback is blocked by a dirty worktree";
101
+ case "head-not-equal": return `/pr --feedback is blocked by local HEAD ${blocker.relation}`;
72
102
  }
73
- const value = /^--base\s+(\S+)/.exec(leading);
74
- if (!value) throw new Error("/pr --base requires a branch");
75
- return { base: value[1]!, instructions: leading.slice(value[0].length).trim() };
76
103
  }
77
104
 
78
105
  function workflowReservation(
@@ -257,11 +284,13 @@ export function createPrCommandHandler(
257
284
  const commandInvocation = onRouteResolved && "assertCurrent" in onRouteResolved
258
285
  ? onRouteResolved as PrCommandInvocation
259
286
  : undefined;
260
- const { base, instructions } = parsePrArguments(args);
287
+ const { base, intent, instructions } = parsePrArguments(args);
261
288
  const discovery = await load(pi, ctx, undefined, undefined, base);
262
289
  commandInvocation?.assertCurrent();
263
- const nextStep = deriveNextStep(discovery);
290
+ const decision = deriveRouteDecision(discovery, intent);
291
+ const nextStep = decision.nextStep;
264
292
  onRouteResolved?.(nextStep);
293
+ if (decision.kind === "feedback-blocked") throw new Error(feedbackBlockerMessage(decision.blocker));
265
294
  if (base !== undefined && nextStep !== "create") {
266
295
  throw new Error("/pr --base is accepted only for pull request creation");
267
296
  }
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { lstat, realpath, rm } from "node:fs/promises";
3
- import { join, resolve } from "node:path";
2
+ import { realpath, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
5
  import {
6
6
  extensionConfigDir,
@@ -27,6 +27,7 @@ import {
27
27
  type PullRequestLoadContext,
28
28
  } from "./pr-github.ts";
29
29
  import {
30
+ inspectGitOperation,
30
31
  isAncestor,
31
32
  parseNulPaths,
32
33
  parseStatusSnapshot,
@@ -46,7 +47,6 @@ export const SWEEP_RECOVERY_MAX_BYTES = 1024 * 1024;
46
47
 
47
48
  const STATE_VERSION = 1;
48
49
  const STATE_FILE = "state.json";
49
- const GIT_OPERATION_STATES = ["MERGE_HEAD", "rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "REVERT_HEAD", "sequencer"];
50
50
  const LEDGER_NOTE_MAX_BYTES = 2 * 1024;
51
51
  const CHECK_MAX_COUNT = 32;
52
52
  const CHECK_ARGUMENTS_MAX_BYTES = 32 * 1024;
@@ -640,23 +640,8 @@ export class PullRequestCommentSweep {
640
640
  }
641
641
 
642
642
  private async requireNoGitOperation(): Promise<void> {
643
- const paths = await runChecked(this.exec, "git", [
644
- "rev-parse", ...GIT_OPERATION_STATES.flatMap((state) => ["--git-path", state]),
645
- ], this.options());
646
- const normalized = paths.stdout.replace(/\r\n/g, "\n");
647
- const values = (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
648
- if (values.length !== GIT_OPERATION_STATES.length || values.some((path) => !path)) {
649
- throw new Error("Git operation state path resolution returned invalid output");
650
- }
651
- for (const [index, path] of values.entries()) {
652
- try {
653
- await lstat(resolve(this.cwd, path));
654
- throw new Error(`${GIT_OPERATION_STATES[index]} is in progress`);
655
- } catch (error) {
656
- if (error && typeof error === "object" && (error as NodeJS.ErrnoException).code === "ENOENT") continue;
657
- throw error;
658
- }
659
- }
643
+ const operation = await inspectGitOperation(this.exec, this.options());
644
+ if (operation !== null) throw new Error(`${operation} is in progress`);
660
645
  }
661
646
 
662
647
  private async localPaths(): Promise<string[]> {
@@ -15,7 +15,10 @@ import {
15
15
  type PullRequestLoadContext,
16
16
  type PullRequestPublication,
17
17
  } from "./pr-github.ts";
18
- import type { PullRequestTarget } from "./pr-routing.ts";
18
+ import {
19
+ isPullRequestCreationEligible,
20
+ type PullRequestTarget,
21
+ } from "./pr-routing.ts";
19
22
  import {
20
23
  assertOnlyDeclaredStatusChanged,
21
24
  inspectWorktree,
@@ -221,13 +224,14 @@ export class PullRequestCreator {
221
224
  return { cwd: this.cwd, signal: this.signal ?? new AbortController().signal };
222
225
  }
223
226
 
224
- private async freshNone(): Promise<void> {
227
+ private async freshNone() {
225
228
  const discovery = await this.load(this.pi(), this.context(), undefined, undefined, this.explicitBase);
226
229
  if (discovery.kind !== "none" || !sameTarget(this.target, discovery.creationTarget)) {
227
230
  throw new Error("PR creation cancelled: fresh complete discovery is no longer none");
228
231
  }
229
232
  const branch = line((await runChecked(this.exec, "git", ["branch", "--show-current"], this.options())).stdout, "current branch");
230
233
  if (branch !== this.target.branch) throw new Error("PR creation cancelled: current branch changed");
234
+ return discovery;
231
235
  }
232
236
 
233
237
  private async liveBase(): Promise<string> {
@@ -270,8 +274,11 @@ export class PullRequestCreator {
270
274
  this.target,
271
275
  this.explicitBase,
272
276
  );
273
- if (preflight.ahead === 0) {
274
- throw new Error("PR creation requires at least one commit ahead of the selected base");
277
+ if (preflight.worktree === "operation") {
278
+ throw new Error("PR creation cannot prepare while a Git operation is in progress");
279
+ }
280
+ if (!isPullRequestCreationEligible({ ...preflight, relation: "distinct-ref" })) {
281
+ throw new Error("PR creation requires at least one commit ahead of the selected base or pending work");
275
282
  }
276
283
  const { base } = preflight;
277
284
  this.state.base = {
@@ -286,11 +293,14 @@ export class PullRequestCreator {
286
293
  "fetch", "--no-write-fetch-head", "--no-tags", "--no-recurse-submodules", base.fetchSource, base.oid,
287
294
  ], this.options());
288
295
  await runChecked(this.exec, "git", ["cat-file", "-e", `${base.oid}^{commit}`], this.options());
289
- await this.freshNone();
296
+ const fresh = await this.freshNone();
290
297
  if (await readHead(this.exec, this.options()) !== preflight.head) {
291
298
  throw new Error("PR creation cancelled: local HEAD changed during prepare");
292
299
  }
293
300
  if (await this.liveBase() !== base.oid) throw new Error("PR creation cancelled: base ref moved during prepare");
301
+ if (!isPullRequestCreationEligible(fresh.branch)) {
302
+ throw new Error("PR creation cancelled: branch no longer has a committed change or pending work");
303
+ }
294
304
  this.state.phase = "prepared";
295
305
  return { kind: "prepared", base: { ...this.state.base }, mergeBase: base.mergeBase };
296
306
  }, { agentDir: this.agentDir, signal: this.signal });
@@ -37,6 +37,7 @@ export type ExecOptions = {
37
37
  export type Exec = (command: string, args: string[], options: ExecOptions) => Promise<ExecResult>;
38
38
 
39
39
  export type AttemptState = "none" | "attempting" | "applied" | "blocked" | "unknown";
40
+ export type GitWorktreeState = "clean" | "dirty" | "operation";
40
41
 
41
42
  function positiveInteger(value: number, label: string): number {
42
43
  if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${label} must be a positive safe integer`);
@@ -236,9 +237,8 @@ export async function runChecked(
236
237
  return result;
237
238
  }
238
239
 
239
- /** Inspect both porcelain state and Git operation markers without mutating the repository. */
240
- export async function inspectWorktree(exec: Exec, options: ExecOptions): Promise<"clean" | "dirty"> {
241
- const status = await runChecked(exec, "git", ["status", "--porcelain=v1", "--untracked-files=all"], options);
240
+ /** Return the active Git operation marker without mutating the repository. */
241
+ export async function inspectGitOperation(exec: Exec, options: ExecOptions): Promise<string | null> {
242
242
  const stateOutput = await runChecked(exec, "git", [
243
243
  "rev-parse",
244
244
  ...GIT_OPERATION_STATES.flatMap((state) => ["--git-path", state]),
@@ -251,7 +251,7 @@ export async function inspectWorktree(exec: Exec, options: ExecOptions): Promise
251
251
  for (const [index, path] of statePaths.entries()) {
252
252
  try {
253
253
  await lstat(resolve(options.cwd, path));
254
- return "dirty";
254
+ return GIT_OPERATION_STATES[index]!;
255
255
  } catch (error) {
256
256
  if (error && typeof error === "object" && (error as NodeJS.ErrnoException).code === "ENOENT") continue;
257
257
  const code = error && typeof error === "object" && typeof (error as NodeJS.ErrnoException).code === "string"
@@ -260,9 +260,21 @@ export async function inspectWorktree(exec: Exec, options: ExecOptions): Promise
260
260
  throw new Error(`Git operation state inspection failed for ${GIT_OPERATION_STATES[index]}: ${code}`);
261
261
  }
262
262
  }
263
+ return null;
264
+ }
265
+
266
+ /** Distinguish ordinary pending work from an in-progress Git operation. */
267
+ export async function inspectWorktreeState(exec: Exec, options: ExecOptions): Promise<GitWorktreeState> {
268
+ const status = await runChecked(exec, "git", ["status", "--porcelain=v1", "--untracked-files=all"], options);
269
+ if (await inspectGitOperation(exec, options) !== null) return "operation";
263
270
  return status.stdout === "" ? "clean" : "dirty";
264
271
  }
265
272
 
273
+ /** Inspect both porcelain state and Git operation markers without mutating the repository. */
274
+ export async function inspectWorktree(exec: Exec, options: ExecOptions): Promise<"clean" | "dirty"> {
275
+ return await inspectWorktreeState(exec, options) === "clean" ? "clean" : "dirty";
276
+ }
277
+
266
278
  /** Exclude concurrent PR mutations for one canonical worktree and pi-pr namespace. */
267
279
  export async function withWorktreeLock<T>(
268
280
  cwd: string,
@@ -5,7 +5,11 @@ import type {
5
5
  import { lstatSync } from "node:fs";
6
6
  import { dirname, join, resolve } from "node:path";
7
7
  import { inspectLocalMergeSafety } from "./pr-merge.ts";
8
- import { withWorktreeLock } from "./pr-execution.ts";
8
+ import {
9
+ inspectWorktreeState,
10
+ withWorktreeLock,
11
+ type GitWorktreeState,
12
+ } from "./pr-execution.ts";
9
13
  import type {
10
14
  CiStatus,
11
15
  LocalMergeSafety,
@@ -112,10 +116,11 @@ export type PullRequestCreationPreflight = {
112
116
  mergeBase: string;
113
117
  };
114
118
  ahead: number;
119
+ worktree: GitWorktreeState;
115
120
  };
116
121
 
117
122
  type CreationPreflightResult =
118
- | { kind: "same-ref" }
123
+ | { kind: "same-ref"; worktree: GitWorktreeState }
119
124
  | { kind: "distinct-ref"; preflight: PullRequestCreationPreflight };
120
125
 
121
126
  type CreationIdentity = {
@@ -1158,6 +1163,24 @@ function parseCreationAhead(output: string): number {
1158
1163
  return ahead;
1159
1164
  }
1160
1165
 
1166
+ async function inspectCreationWorktree(
1167
+ pi: Pick<ExtensionAPI, "exec">,
1168
+ context: PullRequestLoadContext,
1169
+ ): Promise<GitWorktreeState> {
1170
+ try {
1171
+ return await inspectWorktreeState(
1172
+ async (command, args) => await invoke(pi, context, "Inspect creation worktree", command, args),
1173
+ { cwd: context.cwd, signal: context.signal },
1174
+ );
1175
+ } catch (error) {
1176
+ if (error instanceof PullRequestLoadError) throw error;
1177
+ return fail(
1178
+ "Inspect creation worktree",
1179
+ error instanceof Error ? error.message : "inspection failed",
1180
+ );
1181
+ }
1182
+ }
1183
+
1161
1184
  async function preflightCreation(
1162
1185
  pi: Pick<ExtensionAPI, "exec">,
1163
1186
  context: PullRequestLoadContext,
@@ -1176,7 +1199,8 @@ async function preflightCreation(
1176
1199
  : await validateCreationRef(pi, context, explicitBaseRef);
1177
1200
  const baseRef = configuredBaseRef ?? await readDefaultCreationBaseRef(pi, context, origin);
1178
1201
  const relation = await inspectCreationRepositoryRelation(pi, context, identity.target, origin, baseRef);
1179
- if (relation === "same-ref") return { kind: relation };
1202
+ const worktree = await inspectCreationWorktree(pi, context);
1203
+ if (relation === "same-ref") return { kind: relation, worktree };
1180
1204
  const trackingRef = `refs/remotes/origin/${baseRef}`;
1181
1205
  await execute(pi, context, "Fetch creation base", "git", [
1182
1206
  "fetch", "--no-write-fetch-head", "--no-tags", "--no-recurse-submodules", "--",
@@ -1208,6 +1232,7 @@ async function preflightCreation(
1208
1232
  mergeBase,
1209
1233
  },
1210
1234
  ahead,
1235
+ worktree,
1211
1236
  },
1212
1237
  };
1213
1238
  }
@@ -1236,7 +1261,9 @@ async function creationDiscovery(
1236
1261
  return {
1237
1262
  kind: "none",
1238
1263
  creationTarget: target,
1239
- branch: { ahead: result.kind === "same-ref" ? 0 : result.preflight.ahead },
1264
+ branch: result.kind === "same-ref"
1265
+ ? { ahead: 0, worktree: result.worktree, relation: result.kind }
1266
+ : { ahead: result.preflight.ahead, worktree: result.preflight.worktree, relation: result.kind },
1240
1267
  };
1241
1268
  }
1242
1269
 
@@ -40,6 +40,8 @@ export type PullRequestTarget = {
40
40
 
41
41
  export type BranchCreationState = {
42
42
  ahead: number;
43
+ worktree: "clean" | "dirty" | "operation";
44
+ relation: "same-ref" | "distinct-ref";
43
45
  };
44
46
 
45
47
  export type DiscoveryIssue =
@@ -59,6 +61,17 @@ export type PullRequestDiscovery<T extends PullRequest = PullRequest> =
59
61
  | { kind: "inactive" };
60
62
 
61
63
  export type NextStep = "create" | "link-branch" | "blocked" | "none" | "update-branch" | "sweep" | "fix-ci" | "merge";
64
+ export type RouteIntent = "automatic" | "feedback";
65
+ export type FeedbackRouteBlocker =
66
+ | { kind: "discovery-blocked" }
67
+ | { kind: "pull-request-unavailable" }
68
+ | { kind: "pull-request-not-open" }
69
+ | { kind: "target-not-configured" }
70
+ | { kind: "worktree-dirty" }
71
+ | { kind: "head-not-equal"; relation: Exclude<LocalHeadRelation, "equal"> };
72
+ export type RouteDecision =
73
+ | { kind: "selected"; nextStep: NextStep }
74
+ | { kind: "feedback-blocked"; nextStep: "blocked"; blocker: FeedbackRouteBlocker };
62
75
 
63
76
  function localMutationSafe(local: LocalMergeSafety): boolean {
64
77
  return local.worktree === "clean" && local.head === "equal";
@@ -88,12 +101,52 @@ export function derivePullRequestNextStep(pullRequest: PullRequest): Exclude<Nex
88
101
  return "merge";
89
102
  }
90
103
 
91
- export function deriveNextStep(discovery: PullRequestDiscovery<PullRequest & { target: PullRequestTarget }>): NextStep {
104
+ export function isPullRequestCreationEligible(branch: BranchCreationState): boolean {
105
+ return branch.relation === "distinct-ref" && branch.worktree !== "operation" &&
106
+ (branch.ahead > 0 || branch.worktree === "dirty");
107
+ }
108
+
109
+ function deriveAutomaticNextStep(discovery: PullRequestDiscovery<PullRequest & { target: PullRequestTarget }>): NextStep {
92
110
  if (discovery.kind === "inactive") return "none";
93
111
  if (discovery.kind === "blocked") return "blocked";
94
- if (discovery.kind === "none") return discovery.branch.ahead > 0 ? "create" : "none";
112
+ if (discovery.kind === "none") return isPullRequestCreationEligible(discovery.branch) ? "create" : "none";
95
113
  if (discovery.pullRequest.target.provenance === "inferred") {
96
114
  return discovery.pullRequest.lifecycle === "open" ? "link-branch" : "none";
97
115
  }
98
116
  return derivePullRequestNextStep(discovery.pullRequest);
99
117
  }
118
+
119
+ export function deriveRouteDecision(
120
+ discovery: PullRequestDiscovery<PullRequest & { target: PullRequestTarget }>,
121
+ intent: RouteIntent = "automatic",
122
+ ): RouteDecision {
123
+ if (intent === "automatic") return { kind: "selected", nextStep: deriveAutomaticNextStep(discovery) };
124
+ if (discovery.kind === "blocked") {
125
+ return { kind: "feedback-blocked", nextStep: "blocked", blocker: { kind: "discovery-blocked" } };
126
+ }
127
+ if (discovery.kind !== "current") {
128
+ return { kind: "feedback-blocked", nextStep: "blocked", blocker: { kind: "pull-request-unavailable" } };
129
+ }
130
+ const pullRequest = discovery.pullRequest;
131
+ if (pullRequest.lifecycle !== "open") {
132
+ return { kind: "feedback-blocked", nextStep: "blocked", blocker: { kind: "pull-request-not-open" } };
133
+ }
134
+ if (pullRequest.target.provenance !== "configured") {
135
+ return { kind: "feedback-blocked", nextStep: "blocked", blocker: { kind: "target-not-configured" } };
136
+ }
137
+ if (pullRequest.local.worktree !== "clean") {
138
+ return { kind: "feedback-blocked", nextStep: "blocked", blocker: { kind: "worktree-dirty" } };
139
+ }
140
+ if (pullRequest.local.head !== "equal") {
141
+ return {
142
+ kind: "feedback-blocked",
143
+ nextStep: "blocked",
144
+ blocker: { kind: "head-not-equal", relation: pullRequest.local.head },
145
+ };
146
+ }
147
+ return { kind: "selected", nextStep: "sweep" };
148
+ }
149
+
150
+ export function deriveNextStep(discovery: PullRequestDiscovery<PullRequest & { target: PullRequestTarget }>): NextStep {
151
+ return deriveRouteDecision(discovery).nextStep;
152
+ }
package/extensions/pr.ts CHANGED
@@ -783,7 +783,7 @@ export default function pullRequestExtension(
783
783
  releaseWorkflow,
784
784
  });
785
785
  pi.registerCommand("pr", {
786
- description: "[--base <branch>] [instructions] — Run the current branch pull request next step",
786
+ description: "[--feedback | --base <branch> [instructions]] — Run the current branch pull request next step",
787
787
  handler: async (args, ctx) => {
788
788
  if (!ctx.hasUI || !context) return;
789
789
  const generation = sessionGeneration;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-pr",
3
- "version": "4.0.7",
3
+ "version": "4.0.9",
4
4
  "description": "Run /pr to safely discover or link the current pull request, then create, update, address feedback, fix CI, or merge when ready.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -7,7 +7,7 @@ description: Prepare and publish the current branch pull request with determinis
7
7
 
8
8
  Use only `pi_pr_create` for base selection, merge, push, upstream, and GitHub work. Do not repeat its Git or GitHub checks with shell tools.
9
9
 
10
- Start with the prompted `prepare` action. It uses the saved branch base: explicit `/pr --base BRANCH`, one `branch.<branch>.gh-merge-base` value, then validated `origin` default. It requires a committed change ahead. Dirty work alone cannot start this route. The base is always `origin`; fork heads must share its GitHub source and host. Apply trailing prompt guidance only to the PR content.
10
+ Start with the prompted `prepare` action. It uses the saved branch base: explicit `/pr --base BRANCH`, one `branch.<branch>.gh-merge-base` value, then validated `origin` default. It requires a committed change ahead or ordinary pending work, including untracked files. It rejects an in-progress Git operation and a head ref equal to the selected base ref. The base is always `origin`; fork heads must share its GitHub source and host. Apply trailing prompt guidance only to the PR content.
11
11
 
12
12
  After `prepare`, inspect the returned base and merge-base. Separate and commit coherent pending work. Preserve coherent staging. Exclude `.context/` and unrelated changes. Stop when separation is unsafe.
13
13