agentplane 0.3.10 → 0.3.11

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 (228) hide show
  1. package/assets/policy/governance.md +3 -4
  2. package/assets/policy/incidents.md +19 -88
  3. package/assets/policy/workflow.branch_pr.md +1 -1
  4. package/assets/policy/workflow.direct.md +2 -2
  5. package/bin/agentplane.js +56 -1
  6. package/bin/runtime-watch.js +1 -0
  7. package/bin/stale-dist-policy.d.ts +1 -1
  8. package/bin/stale-dist-policy.js +13 -0
  9. package/dist/.build-manifest.json +219 -154
  10. package/dist/cli/bootstrap-guide.d.ts.map +1 -1
  11. package/dist/cli/bootstrap-guide.js +3 -2
  12. package/dist/cli/command-guide.d.ts.map +1 -1
  13. package/dist/cli/command-guide.js +2 -1
  14. package/dist/cli/command-invocations.d.ts.map +1 -1
  15. package/dist/cli/command-invocations.js +4 -1
  16. package/dist/cli/run-cli/command-catalog/project.d.ts +1 -1
  17. package/dist/cli/run-cli/command-catalog/project.d.ts.map +1 -1
  18. package/dist/cli/run-cli/command-catalog/project.js +3 -1
  19. package/dist/cli/run-cli/command-catalog/task.d.ts +1 -1
  20. package/dist/cli/run-cli/command-catalog/task.d.ts.map +1 -1
  21. package/dist/cli/run-cli/command-catalog/task.js +10 -0
  22. package/dist/cli/run-cli/command-catalog.d.ts +1 -1
  23. package/dist/cli/run-cli/command-catalog.d.ts.map +1 -1
  24. package/dist/cli/run-cli/commands/core/preflight.d.ts.map +1 -1
  25. package/dist/cli/run-cli/commands/core/preflight.js +44 -1
  26. package/dist/cli/run-cli.test-helpers.d.ts.map +1 -1
  27. package/dist/cli/run-cli.test-helpers.js +12 -0
  28. package/dist/commands/branch/cleanup-merged.d.ts +2 -0
  29. package/dist/commands/branch/cleanup-merged.d.ts.map +1 -1
  30. package/dist/commands/branch/cleanup-merged.js +132 -28
  31. package/dist/commands/branch/work-start.d.ts.map +1 -1
  32. package/dist/commands/branch/work-start.js +60 -1
  33. package/dist/commands/cleanup/merged.command.d.ts +2 -0
  34. package/dist/commands/cleanup/merged.command.d.ts.map +1 -1
  35. package/dist/commands/cleanup/merged.command.js +24 -0
  36. package/dist/commands/doctor/branch-pr.d.ts +4 -0
  37. package/dist/commands/doctor/branch-pr.d.ts.map +1 -0
  38. package/dist/commands/doctor/branch-pr.js +96 -0
  39. package/dist/commands/doctor/fixes.d.ts +5 -0
  40. package/dist/commands/doctor/fixes.d.ts.map +1 -1
  41. package/dist/commands/doctor/fixes.js +70 -0
  42. package/dist/commands/doctor.run.d.ts.map +1 -1
  43. package/dist/commands/doctor.run.js +6 -1
  44. package/dist/commands/finish.run.d.ts.map +1 -1
  45. package/dist/commands/finish.run.js +11 -0
  46. package/dist/commands/finish.spec.d.ts +11 -0
  47. package/dist/commands/finish.spec.d.ts.map +1 -1
  48. package/dist/commands/finish.spec.js +51 -0
  49. package/dist/commands/guard/impl/close-message.d.ts.map +1 -1
  50. package/dist/commands/guard/impl/close-message.js +23 -6
  51. package/dist/commands/guard/impl/commands.d.ts.map +1 -1
  52. package/dist/commands/guard/impl/commands.js +24 -2
  53. package/dist/commands/guard/impl/env.d.ts +1 -0
  54. package/dist/commands/guard/impl/env.d.ts.map +1 -1
  55. package/dist/commands/guard/impl/env.js +1 -0
  56. package/dist/commands/hooks/index.d.ts.map +1 -1
  57. package/dist/commands/hooks/index.js +98 -1
  58. package/dist/commands/incidents/collect.command.d.ts.map +1 -1
  59. package/dist/commands/incidents/collect.command.js +12 -7
  60. package/dist/commands/incidents/incidents.command.js +1 -1
  61. package/dist/commands/incidents/shared.d.ts +34 -0
  62. package/dist/commands/incidents/shared.d.ts.map +1 -1
  63. package/dist/commands/incidents/shared.js +166 -12
  64. package/dist/commands/pr/check.d.ts.map +1 -1
  65. package/dist/commands/pr/check.js +238 -135
  66. package/dist/commands/pr/close-superseded.d.ts +9 -0
  67. package/dist/commands/pr/close-superseded.d.ts.map +1 -0
  68. package/dist/commands/pr/close-superseded.js +129 -0
  69. package/dist/commands/pr/close.d.ts +11 -0
  70. package/dist/commands/pr/close.d.ts.map +1 -0
  71. package/dist/commands/pr/close.js +116 -0
  72. package/dist/commands/pr/index.d.ts +2 -0
  73. package/dist/commands/pr/index.d.ts.map +1 -1
  74. package/dist/commands/pr/index.js +2 -0
  75. package/dist/commands/pr/integrate/artifacts.d.ts +7 -0
  76. package/dist/commands/pr/integrate/artifacts.d.ts.map +1 -1
  77. package/dist/commands/pr/integrate/artifacts.js +66 -1
  78. package/dist/commands/pr/integrate/cmd.d.ts.map +1 -1
  79. package/dist/commands/pr/integrate/cmd.js +16 -0
  80. package/dist/commands/pr/integrate/internal/bootstrap-guidance.d.ts +8 -0
  81. package/dist/commands/pr/integrate/internal/bootstrap-guidance.d.ts.map +1 -0
  82. package/dist/commands/pr/integrate/internal/bootstrap-guidance.js +59 -0
  83. package/dist/commands/pr/integrate/internal/finalize.d.ts.map +1 -1
  84. package/dist/commands/pr/integrate/internal/finalize.js +40 -12
  85. package/dist/commands/pr/integrate/internal/merge.d.ts.map +1 -1
  86. package/dist/commands/pr/integrate/internal/merge.js +36 -13
  87. package/dist/commands/pr/integrate/internal/post-integrate-bootstrap.d.ts +13 -0
  88. package/dist/commands/pr/integrate/internal/post-integrate-bootstrap.d.ts.map +1 -0
  89. package/dist/commands/pr/integrate/internal/post-integrate-bootstrap.js +25 -0
  90. package/dist/commands/pr/integrate/internal/prepare.d.ts +3 -2
  91. package/dist/commands/pr/integrate/internal/prepare.d.ts.map +1 -1
  92. package/dist/commands/pr/integrate/internal/prepare.js +101 -38
  93. package/dist/commands/pr/internal/freshness.d.ts +20 -0
  94. package/dist/commands/pr/internal/freshness.d.ts.map +1 -0
  95. package/dist/commands/pr/internal/freshness.js +50 -0
  96. package/dist/commands/pr/internal/gh-api.d.ts +6 -0
  97. package/dist/commands/pr/internal/gh-api.d.ts.map +1 -0
  98. package/dist/commands/pr/internal/gh-api.js +80 -0
  99. package/dist/commands/pr/internal/pr-paths.d.ts +10 -0
  100. package/dist/commands/pr/internal/pr-paths.d.ts.map +1 -1
  101. package/dist/commands/pr/internal/pr-paths.js +10 -0
  102. package/dist/commands/pr/internal/review-template.d.ts.map +1 -1
  103. package/dist/commands/pr/internal/review-template.js +37 -4
  104. package/dist/commands/pr/internal/sync.d.ts +9 -0
  105. package/dist/commands/pr/internal/sync.d.ts.map +1 -1
  106. package/dist/commands/pr/internal/sync.js +462 -122
  107. package/dist/commands/pr/open.d.ts +1 -0
  108. package/dist/commands/pr/open.d.ts.map +1 -1
  109. package/dist/commands/pr/open.js +13 -2
  110. package/dist/commands/pr/pr.command.d.ts +15 -0
  111. package/dist/commands/pr/pr.command.d.ts.map +1 -1
  112. package/dist/commands/pr/pr.command.js +118 -2
  113. package/dist/commands/pr/update.d.ts.map +1 -1
  114. package/dist/commands/pr/update.js +59 -1
  115. package/dist/commands/release/apply.command.d.ts.map +1 -1
  116. package/dist/commands/release/apply.command.js +3 -17
  117. package/dist/commands/release/apply.preflight.d.ts.map +1 -1
  118. package/dist/commands/release/apply.preflight.js +1 -1
  119. package/dist/commands/shared/gh-transport.d.ts +16 -0
  120. package/dist/commands/shared/gh-transport.d.ts.map +1 -0
  121. package/dist/commands/shared/gh-transport.js +71 -0
  122. package/dist/commands/shared/git-diff.d.ts +3 -1
  123. package/dist/commands/shared/git-diff.d.ts.map +1 -1
  124. package/dist/commands/shared/git-diff.js +10 -2
  125. package/dist/commands/shared/git-ops.d.ts +1 -0
  126. package/dist/commands/shared/git-ops.d.ts.map +1 -1
  127. package/dist/commands/shared/git-ops.js +15 -0
  128. package/dist/commands/shared/git-worktree.d.ts +2 -0
  129. package/dist/commands/shared/git-worktree.d.ts.map +1 -1
  130. package/dist/commands/shared/git-worktree.js +22 -2
  131. package/dist/commands/shared/post-commit-pr-artifacts.d.ts +9 -0
  132. package/dist/commands/shared/post-commit-pr-artifacts.d.ts.map +1 -0
  133. package/dist/commands/shared/post-commit-pr-artifacts.js +22 -0
  134. package/dist/commands/shared/pr-meta.d.ts +20 -0
  135. package/dist/commands/shared/pr-meta.d.ts.map +1 -1
  136. package/dist/commands/shared/pr-meta.js +125 -0
  137. package/dist/commands/shared/task-backend.d.ts +7 -0
  138. package/dist/commands/shared/task-backend.d.ts.map +1 -1
  139. package/dist/commands/shared/task-backend.js +34 -22
  140. package/dist/commands/task/close-duplicate.d.ts.map +1 -1
  141. package/dist/commands/task/close-duplicate.js +34 -1
  142. package/dist/commands/task/derive.js +1 -1
  143. package/dist/commands/task/doc-template.d.ts.map +1 -1
  144. package/dist/commands/task/doc-template.js +7 -11
  145. package/dist/commands/task/findings-add.command.d.ts +20 -0
  146. package/dist/commands/task/findings-add.command.d.ts.map +1 -0
  147. package/dist/commands/task/findings-add.command.js +165 -0
  148. package/dist/commands/task/findings.command.d.ts +7 -0
  149. package/dist/commands/task/findings.command.d.ts.map +1 -0
  150. package/dist/commands/task/findings.command.js +20 -0
  151. package/dist/commands/task/findings.d.ts +63 -0
  152. package/dist/commands/task/findings.d.ts.map +1 -0
  153. package/dist/commands/task/findings.js +188 -0
  154. package/dist/commands/task/finish-shared.d.ts +1 -0
  155. package/dist/commands/task/finish-shared.d.ts.map +1 -1
  156. package/dist/commands/task/finish-shared.js +55 -1
  157. package/dist/commands/task/finish.d.ts +10 -0
  158. package/dist/commands/task/finish.d.ts.map +1 -1
  159. package/dist/commands/task/finish.js +125 -6
  160. package/dist/commands/task/hosted-close-pr.command.d.ts +11 -0
  161. package/dist/commands/task/hosted-close-pr.command.d.ts.map +1 -0
  162. package/dist/commands/task/hosted-close-pr.command.js +414 -0
  163. package/dist/commands/task/hosted-close.command.d.ts.map +1 -1
  164. package/dist/commands/task/hosted-close.command.js +49 -1
  165. package/dist/commands/task/hosted-merge-sync.d.ts +38 -0
  166. package/dist/commands/task/hosted-merge-sync.d.ts.map +1 -1
  167. package/dist/commands/task/hosted-merge-sync.js +249 -17
  168. package/dist/commands/task/index.d.ts +1 -0
  169. package/dist/commands/task/index.d.ts.map +1 -1
  170. package/dist/commands/task/index.js +1 -0
  171. package/dist/commands/task/new.d.ts +1 -0
  172. package/dist/commands/task/new.d.ts.map +1 -1
  173. package/dist/commands/task/new.js +71 -1
  174. package/dist/commands/task/new.spec.d.ts.map +1 -1
  175. package/dist/commands/task/new.spec.js +7 -0
  176. package/dist/commands/task/normalize.command.d.ts +2 -0
  177. package/dist/commands/task/normalize.command.d.ts.map +1 -1
  178. package/dist/commands/task/normalize.command.js +45 -0
  179. package/dist/commands/task/normalize.d.ts +2 -0
  180. package/dist/commands/task/normalize.d.ts.map +1 -1
  181. package/dist/commands/task/normalize.js +85 -8
  182. package/dist/commands/task/plan.d.ts.map +1 -1
  183. package/dist/commands/task/plan.js +7 -10
  184. package/dist/commands/task/shared/docs.d.ts +6 -0
  185. package/dist/commands/task/shared/docs.d.ts.map +1 -1
  186. package/dist/commands/task/shared/docs.js +14 -0
  187. package/dist/commands/task/shared/transitions.d.ts.map +1 -1
  188. package/dist/commands/task/shared/transitions.js +11 -1
  189. package/dist/commands/task/shared.d.ts +1 -1
  190. package/dist/commands/task/shared.d.ts.map +1 -1
  191. package/dist/commands/task/shared.js +1 -1
  192. package/dist/commands/task/start-ready.d.ts.map +1 -1
  193. package/dist/commands/task/start-ready.js +86 -0
  194. package/dist/commands/task/start.d.ts.map +1 -1
  195. package/dist/commands/task/start.js +7 -10
  196. package/dist/commands/task/task.command.d.ts.map +1 -1
  197. package/dist/commands/task/task.command.js +4 -0
  198. package/dist/commands/task/verify-command-shared.d.ts +19 -0
  199. package/dist/commands/task/verify-command-shared.d.ts.map +1 -1
  200. package/dist/commands/task/verify-command-shared.js +152 -1
  201. package/dist/commands/task/verify-ok.command.d.ts.map +1 -1
  202. package/dist/commands/task/verify-ok.command.js +15 -2
  203. package/dist/commands/task/verify-record.d.ts +36 -0
  204. package/dist/commands/task/verify-record.d.ts.map +1 -1
  205. package/dist/commands/task/verify-record.js +166 -11
  206. package/dist/commands/task/verify-rework.command.d.ts.map +1 -1
  207. package/dist/commands/task/verify-rework.command.js +15 -2
  208. package/dist/commands/task/verify-show.command.d.ts +1 -1
  209. package/dist/commands/task/verify-show.command.d.ts.map +1 -1
  210. package/dist/commands/task/verify-show.command.js +28 -1
  211. package/dist/commands/verify.run.d.ts.map +1 -1
  212. package/dist/commands/verify.run.js +12 -0
  213. package/dist/commands/verify.spec.d.ts +2 -6
  214. package/dist/commands/verify.spec.d.ts.map +1 -1
  215. package/dist/commands/verify.spec.js +30 -3
  216. package/dist/runtime/incidents/index.d.ts +1 -1
  217. package/dist/runtime/incidents/index.d.ts.map +1 -1
  218. package/dist/runtime/incidents/resolve.d.ts.map +1 -1
  219. package/dist/runtime/incidents/resolve.js +319 -73
  220. package/dist/runtime/incidents/types.d.ts +14 -2
  221. package/dist/runtime/incidents/types.d.ts.map +1 -1
  222. package/dist/shared/env.d.ts +1 -0
  223. package/dist/shared/env.d.ts.map +1 -1
  224. package/dist/shared/env.js +22 -1
  225. package/dist/shared/protected-paths.d.ts +1 -1
  226. package/dist/shared/protected-paths.d.ts.map +1 -1
  227. package/dist/shared/protected-paths.js +4 -0
  228. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { mkdir, readFile } from "node:fs/promises";
1
+ import { mkdir, readFile, rm } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { resolveBaseBranch } from "@agentplaneorg/core";
4
4
  import { mapBackendError } from "../../../cli/error-map.js";
@@ -8,19 +8,230 @@ import { workflowModeMessage } from "../../../cli/output.js";
8
8
  import { CliError } from "../../../shared/errors.js";
9
9
  import { writeJsonStableIfChanged, writeTextIfChanged } from "../../../shared/write-if-changed.js";
10
10
  import { execFileAsync, gitEnv } from "../../shared/git.js";
11
+ import { gitDiffStat } from "../../shared/git-diff.js";
11
12
  import { gitCurrentBranch } from "../../shared/git-ops.js";
12
13
  import { parseTaskIdFromBranch } from "../../shared/git-worktree.js";
13
- import { buildOpenedPrMeta, buildUpdatedPrMeta, parsePrMeta, } from "../../shared/pr-meta.js";
14
+ import { isTransientGhTransportError, normalizeGhTransportError, withGhTransportRetry, } from "../../shared/gh-transport.js";
15
+ import { INCIDENTS_POLICY_PATH } from "../../incidents/shared.js";
16
+ import { buildObservedGithubPrMeta, buildOpenedPrMeta, resolvePrArtifactHeadSha, buildUpdatedPrMeta, parsePrMeta, } from "../../shared/pr-meta.js";
14
17
  import { loadBackendTask, loadCommandContext, } from "../../shared/task-backend.js";
18
+ import { isTaskLocalOnlyAdvance } from "../../shared/task-local-freshness.js";
15
19
  import { resolvePrPaths } from "./pr-paths.js";
16
20
  import { readPrHandoffNotes } from "./note-store.js";
21
+ import { ghEnv } from "./gh-api.js";
17
22
  import { buildGithubPrTitle, renderGithubPrBody, renderPrAutoSummary, renderPrReviewDocument, } from "./review-template.js";
18
23
  function nowIso() {
19
24
  return new Date().toISOString();
20
25
  }
26
+ async function readTextIfExists(filePath) {
27
+ try {
28
+ return await readFile(filePath, "utf8");
29
+ }
30
+ catch (err) {
31
+ const code = err?.code;
32
+ if (code === "ENOENT")
33
+ return null;
34
+ throw err;
35
+ }
36
+ }
37
+ async function restoreIncidentRegistryIfNeeded(opts) {
38
+ const incidentsPath = path.join(opts.gitRoot, INCIDENTS_POLICY_PATH);
39
+ const nextText = await readTextIfExists(incidentsPath);
40
+ if (nextText === opts.previousText)
41
+ return;
42
+ if (opts.previousText === null) {
43
+ await rm(incidentsPath, { force: true });
44
+ return;
45
+ }
46
+ await writeTextIfChanged(incidentsPath, opts.previousText);
47
+ }
21
48
  function isUnknownRevisionError(err) {
22
49
  const message = err instanceof Error ? err.message : String(err);
23
- return /unknown revision or path not in the working tree/i.test(message);
50
+ return (/unknown revision or path not in the working tree/i.test(message) ||
51
+ /bad revision/i.test(message) ||
52
+ /ambiguous argument/i.test(message));
53
+ }
54
+ function parseGithubRepoFromRemoteUrl(remoteUrl) {
55
+ const trimmed = remoteUrl.trim();
56
+ if (!trimmed)
57
+ return null;
58
+ const httpsMatch = /^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(trimmed);
59
+ if (httpsMatch)
60
+ return `${httpsMatch[1]}/${httpsMatch[2]}`;
61
+ const sshMatch = /^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/.exec(trimmed);
62
+ if (sshMatch)
63
+ return `${sshMatch[1]}/${sshMatch[2]}`;
64
+ return null;
65
+ }
66
+ async function resolveGithubRepoFromOrigin(gitRoot) {
67
+ try {
68
+ const { stdout } = await execFileAsync("git", ["remote", "get-url", "origin"], {
69
+ cwd: gitRoot,
70
+ env: gitEnv(),
71
+ });
72
+ return parseGithubRepoFromRemoteUrl(stdout);
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ function normalizeObservedGithubPr(record) {
79
+ const number = Number(record.number);
80
+ if (!Number.isInteger(number) || number <= 0)
81
+ return null;
82
+ const state = record.state?.trim().toLowerCase() ?? "";
83
+ const mergedAt = record.merged_at?.trim() ?? null;
84
+ const status = mergedAt && mergedAt.length > 0
85
+ ? "MERGED"
86
+ : state === "open"
87
+ ? "OPEN"
88
+ : state === "closed"
89
+ ? "CLOSED"
90
+ : null;
91
+ if (!status)
92
+ return null;
93
+ const prUrl = record.html_url?.trim() ?? null;
94
+ const mergeCommit = record.merge_commit_sha?.trim() ?? null;
95
+ const base = record.base?.ref?.trim() ?? null;
96
+ const headSha = record.head?.sha?.trim() ?? null;
97
+ return {
98
+ prNumber: number,
99
+ prUrl,
100
+ status,
101
+ mergedAt,
102
+ mergeCommit,
103
+ base,
104
+ headSha,
105
+ };
106
+ }
107
+ async function tryLookupExistingGithubPrByBranch(opts) {
108
+ const repo = await resolveGithubRepoFromOrigin(opts.gitRoot);
109
+ if (!repo)
110
+ return null;
111
+ const owner = repo.split("/")[0]?.trim() ?? "";
112
+ if (!owner)
113
+ return null;
114
+ const query = new URLSearchParams({ state: "all", head: `${owner}:${opts.branch}` });
115
+ const baseBranch = opts.baseBranch?.trim() ?? "";
116
+ if (baseBranch)
117
+ query.set("base", baseBranch);
118
+ const endpoint = `repos/${repo}/pulls?${query.toString()}`;
119
+ try {
120
+ const { stdout } = await withGhTransportRetry(() => execFileAsync("gh", ["api", endpoint], {
121
+ cwd: opts.gitRoot,
122
+ env: ghEnv(),
123
+ maxBuffer: 10 * 1024 * 1024,
124
+ }), { label: `running gh api ${endpoint}` });
125
+ const parsed = JSON.parse(stdout);
126
+ if (!Array.isArray(parsed) || parsed.length === 0)
127
+ return null;
128
+ for (const record of parsed) {
129
+ const observed = normalizeObservedGithubPr(record);
130
+ if (observed)
131
+ return observed;
132
+ }
133
+ return null;
134
+ }
135
+ catch (err) {
136
+ const code = err?.code;
137
+ if (code === "ENOENT")
138
+ return null;
139
+ const message = normalizeGhTransportError(err);
140
+ if (message.trim().length > 0)
141
+ return null;
142
+ return null;
143
+ }
144
+ }
145
+ function formatGithubPrLink(prNumber, prUrl, verb) {
146
+ return prUrl?.trim()
147
+ ? `${verb} GitHub PR #${prNumber}: ${prUrl.trim()}`
148
+ : `${verb} GitHub PR #${prNumber}`;
149
+ }
150
+ function formatUnpublishedRemoteHeadReason(branch) {
151
+ return (`task branch ${branch} is not yet published on origin; push it with ` +
152
+ `\`git push -u origin ${branch}\` and rerun \`agentplane pr open\``);
153
+ }
154
+ function isMissingRemoteHeadCreateError(err) {
155
+ const text = normalizeGhTransportError(err);
156
+ if (!/\b422\b/i.test(text))
157
+ return false;
158
+ return (/head sha/i.test(text) ||
159
+ /head ref/i.test(text) ||
160
+ /head.*must be a branch/i.test(text) ||
161
+ /head.*not found/i.test(text) ||
162
+ /field["']?\s*:\s*["']head["']/i.test(text) ||
163
+ /field\s+head\b/i.test(text) ||
164
+ /no commits between/i.test(text));
165
+ }
166
+ function summarizeGithubPrCreateFailure(err) {
167
+ const text = normalizeGhTransportError(err);
168
+ if (err?.code === "ENOENT") {
169
+ return "gh CLI is unavailable";
170
+ }
171
+ if (/authentication required/i.test(text) ||
172
+ /not logged into github/i.test(text) ||
173
+ /bad credentials/i.test(text) ||
174
+ /permission denied/i.test(text) ||
175
+ /\b401\b/i.test(text) ||
176
+ /\b403\b/i.test(text)) {
177
+ return "GitHub auth or permissions unavailable";
178
+ }
179
+ if (isTransientGhTransportError(err)) {
180
+ return "GitHub transport failed; retry `agentplane pr open`";
181
+ }
182
+ return "GitHub PR creation failed";
183
+ }
184
+ async function tryCreateGithubPr(opts) {
185
+ const repo = await resolveGithubRepoFromOrigin(opts.gitRoot);
186
+ if (!repo) {
187
+ return {
188
+ observed: null,
189
+ stagedReason: "GitHub origin repo unavailable",
190
+ };
191
+ }
192
+ const baseBranch = opts.baseBranch?.trim() ?? "";
193
+ if (!baseBranch) {
194
+ return {
195
+ observed: null,
196
+ stagedReason: "base branch unresolved",
197
+ };
198
+ }
199
+ try {
200
+ const { stdout } = await withGhTransportRetry(() => execFileAsync("gh", [
201
+ "api",
202
+ `repos/${repo}/pulls`,
203
+ "-X",
204
+ "POST",
205
+ "-f",
206
+ `title=${opts.title}`,
207
+ "-f",
208
+ `body=${opts.body}`,
209
+ "-f",
210
+ `head=${opts.branch}`,
211
+ "-f",
212
+ `base=${baseBranch}`,
213
+ ], {
214
+ cwd: opts.gitRoot,
215
+ env: ghEnv(),
216
+ maxBuffer: 10 * 1024 * 1024,
217
+ }), { label: `running gh api repos/${repo}/pulls` });
218
+ return {
219
+ observed: normalizeObservedGithubPr(JSON.parse(stdout)),
220
+ stagedReason: null,
221
+ };
222
+ }
223
+ catch (err) {
224
+ if (isMissingRemoteHeadCreateError(err)) {
225
+ return {
226
+ observed: null,
227
+ stagedReason: formatUnpublishedRemoteHeadReason(opts.branch),
228
+ };
229
+ }
230
+ return {
231
+ observed: null,
232
+ stagedReason: summarizeGithubPrCreateFailure(err),
233
+ };
234
+ }
24
235
  }
25
236
  async function resolveBranchHeadSha(opts) {
26
237
  try {
@@ -36,6 +247,18 @@ async function resolveBranchHeadSha(opts) {
36
247
  return null;
37
248
  }
38
249
  }
250
+ async function computePrDiffstat(opts) {
251
+ try {
252
+ return await gitDiffStat(opts.gitRoot, opts.baseBranch, opts.branch, {
253
+ excludePaths: [path.relative(opts.gitRoot, opts.prDir)],
254
+ });
255
+ }
256
+ catch (err) {
257
+ if (!isUnknownRevisionError(err))
258
+ throw err;
259
+ return "";
260
+ }
261
+ }
39
262
  async function resolvePrSyncBranch(opts) {
40
263
  const explicitBranch = opts.branch?.trim() ?? "";
41
264
  if (explicitBranch) {
@@ -57,7 +280,7 @@ async function resolvePrSyncBranch(opts) {
57
280
  export async function ensurePrArtifactsSynced(opts) {
58
281
  const ctx = opts.ctx ??
59
282
  (await loadCommandContext({ cwd: opts.cwd, rootOverride: opts.rootOverride ?? null }));
60
- const { resolved, config, metaPath } = await resolvePrPaths({ ...opts, ctx });
283
+ const { resolved, config, prDir, metaPath } = await resolvePrPaths({ ...opts, ctx });
61
284
  if (config.workflow_mode !== "branch_pr")
62
285
  return null;
63
286
  const resolvedBranch = await resolvePrSyncBranch({
@@ -82,13 +305,18 @@ export async function ensurePrArtifactsSynced(opts) {
82
305
  if (resolvedBranch.source === "current" && baseBranch && branch === baseBranch) {
83
306
  return null;
84
307
  }
85
- await syncPrArtifacts({
86
- ...opts,
87
- ctx,
88
- mode: "open",
89
- author: opts.author,
90
- branch,
91
- });
308
+ const reviewPath = path.join(prDir, "review.md");
309
+ const artifactsExist = (await fileExists(metaPath)) && (await fileExists(reviewPath));
310
+ if (!artifactsExist) {
311
+ await syncPrArtifacts({
312
+ ...opts,
313
+ ctx,
314
+ mode: "open",
315
+ author: opts.author,
316
+ branch,
317
+ remoteMode: "sync-only",
318
+ });
319
+ }
92
320
  const result = await syncPrArtifacts({
93
321
  ...opts,
94
322
  ctx,
@@ -108,73 +336,235 @@ export async function syncPrArtifacts(opts) {
108
336
  taskId: opts.taskId,
109
337
  });
110
338
  const { resolved, config, prDir, metaPath, diffstatPath, notesPath, verifyLogPath, reviewPath, githubTitlePath, githubBodyPath, } = await resolvePrPaths({ ...opts, ctx });
111
- if (config.workflow_mode !== "branch_pr") {
112
- throw new CliError({
113
- exitCode: exitCodeForError("E_USAGE"),
114
- code: "E_USAGE",
115
- message: workflowModeMessage(config.workflow_mode, "branch_pr"),
339
+ const incidentsTextBefore = await readTextIfExists(path.join(resolved.gitRoot, INCIDENTS_POLICY_PATH));
340
+ try {
341
+ if (config.workflow_mode !== "branch_pr") {
342
+ throw new CliError({
343
+ exitCode: exitCodeForError("E_USAGE"),
344
+ code: "E_USAGE",
345
+ message: workflowModeMessage(config.workflow_mode, "branch_pr"),
346
+ });
347
+ }
348
+ const resolvedBranch = await resolvePrSyncBranch({
349
+ resolved,
350
+ metaPath,
351
+ taskId: task.id,
352
+ branch: opts.branch,
116
353
  });
117
- }
118
- const resolvedBranch = await resolvePrSyncBranch({
119
- resolved,
120
- metaPath,
121
- taskId: task.id,
122
- branch: opts.branch,
123
- });
124
- const branch = resolvedBranch.branch?.trim() ?? "";
125
- if (!branch) {
126
- throw new CliError({
127
- exitCode: exitCodeForError("E_USAGE"),
128
- code: "E_USAGE",
129
- message: "Branch could not be resolved (use --branch).",
354
+ const branch = resolvedBranch.branch?.trim() ?? "";
355
+ if (!branch) {
356
+ throw new CliError({
357
+ exitCode: exitCodeForError("E_USAGE"),
358
+ code: "E_USAGE",
359
+ message: "Branch could not be resolved (use --branch).",
360
+ });
361
+ }
362
+ const metaExists = await fileExists(metaPath);
363
+ const reviewExists = await fileExists(reviewPath);
364
+ if (opts.mode === "update" && (!metaExists || !reviewExists)) {
365
+ const missing = [];
366
+ if (!metaExists)
367
+ missing.push(path.relative(resolved.gitRoot, metaPath));
368
+ if (!reviewExists)
369
+ missing.push(path.relative(resolved.gitRoot, reviewPath));
370
+ throw new CliError({
371
+ exitCode: exitCodeForError("E_VALIDATION"),
372
+ code: "E_VALIDATION",
373
+ message: `PR artifacts missing: ${missing.join(", ")} (run \`agentplane pr open\`)`,
374
+ });
375
+ }
376
+ await mkdir(prDir, { recursive: true });
377
+ const existingMeta = metaExists && (await fileExists(metaPath))
378
+ ? parsePrMeta(await readFile(metaPath, "utf8"), task.id)
379
+ : null;
380
+ const handoffNotes = await readPrHandoffNotes(notesPath);
381
+ const now = nowIso();
382
+ const createdAt = existingMeta?.created_at ?? now;
383
+ const baseBranch = await resolveBaseBranch({
384
+ cwd: opts.cwd,
385
+ rootOverride: opts.rootOverride ?? null,
386
+ cliBaseOpt: null,
387
+ mode: config.workflow_mode,
130
388
  });
131
- }
132
- const metaExists = await fileExists(metaPath);
133
- const reviewExists = await fileExists(reviewPath);
134
- if (opts.mode === "update" && (!metaExists || !reviewExists)) {
135
- const missing = [];
136
- if (!metaExists)
137
- missing.push(path.relative(resolved.gitRoot, metaPath));
138
- if (!reviewExists)
139
- missing.push(path.relative(resolved.gitRoot, reviewPath));
140
- throw new CliError({
141
- exitCode: exitCodeForError("E_VALIDATION"),
142
- code: "E_VALIDATION",
143
- message: `PR artifacts missing: ${missing.join(", ")} (run \`agentplane pr open\`)`,
389
+ const headSha = await resolveBranchHeadSha({ gitRoot: resolved.gitRoot, branch });
390
+ const preservePreviousHead = Boolean(existingMeta?.head_sha) &&
391
+ Boolean(headSha) &&
392
+ (await isTaskLocalOnlyAdvance({
393
+ gitRoot: resolved.gitRoot,
394
+ workflowDir: config.paths.workflow_dir,
395
+ taskId: task.id,
396
+ fromRef: existingMeta?.head_sha ?? null,
397
+ toRef: headSha,
398
+ }));
399
+ const renderedHeadSha = resolvePrArtifactHeadSha({
400
+ previousHeadSha: existingMeta?.head_sha ?? null,
401
+ currentHeadSha: headSha,
402
+ preservePrevious: preservePreviousHead,
144
403
  });
145
- }
146
- await mkdir(prDir, { recursive: true });
147
- const existingMeta = metaExists && (await fileExists(metaPath))
148
- ? parsePrMeta(await readFile(metaPath, "utf8"), task.id)
149
- : null;
150
- const handoffNotes = await readPrHandoffNotes(notesPath);
151
- const now = nowIso();
152
- const createdAt = existingMeta?.created_at ?? now;
153
- const baseBranch = await resolveBaseBranch({
154
- cwd: opts.cwd,
155
- rootOverride: opts.rootOverride ?? null,
156
- cliBaseOpt: null,
157
- mode: config.workflow_mode,
158
- });
159
- const headSha = await resolveBranchHeadSha({ gitRoot: resolved.gitRoot, branch });
160
- if (opts.mode === "open") {
161
- const nextMeta = buildOpenedPrMeta({
162
- taskId: task.id,
404
+ const preservedRenderUpdatedAt = existingMeta &&
405
+ (existingMeta.branch ?? null) === branch &&
406
+ (existingMeta.base ?? null) === (baseBranch ?? null) &&
407
+ (existingMeta.head_sha ?? null) === (renderedHeadSha ?? null)
408
+ ? existingMeta.updated_at
409
+ : null;
410
+ const renderUpdatedAt = preservedRenderUpdatedAt ?? now;
411
+ if (opts.mode === "open") {
412
+ const remoteMode = opts.remoteMode ?? "auto";
413
+ const diffstat = baseBranch
414
+ ? await computePrDiffstat({
415
+ gitRoot: resolved.gitRoot,
416
+ baseBranch,
417
+ branch,
418
+ prDir,
419
+ })
420
+ : "";
421
+ const renderedSummaryHeadSha = renderedHeadSha ?? headSha;
422
+ let nextMeta = buildOpenedPrMeta({
423
+ taskId: task.id,
424
+ branch,
425
+ at: now,
426
+ previousMeta: existingMeta,
427
+ base: baseBranch,
428
+ headSha: renderedHeadSha,
429
+ });
430
+ const linkedExistingOutcome = typeof nextMeta.pr_number === "number" && nextMeta.pr_number > 0
431
+ ? {
432
+ action: "linked-existing",
433
+ message: formatGithubPrLink(nextMeta.pr_number, nextMeta.pr_url ?? null, "linked to"),
434
+ }
435
+ : null;
436
+ let openOutcome;
437
+ const githubTitle = buildGithubPrTitle(task);
438
+ const githubBody = renderGithubPrBody({
439
+ task,
440
+ handoffNotes,
441
+ autoSummary: renderPrAutoSummary({
442
+ updatedAt: renderUpdatedAt,
443
+ branch,
444
+ headSha: renderedSummaryHeadSha,
445
+ diffstat,
446
+ }),
447
+ });
448
+ const observedGithubPr = await tryLookupExistingGithubPrByBranch({
449
+ gitRoot: resolved.gitRoot,
450
+ branch,
451
+ baseBranch,
452
+ });
453
+ if (observedGithubPr) {
454
+ nextMeta = buildObservedGithubPrMeta({
455
+ meta: nextMeta,
456
+ observed: observedGithubPr,
457
+ at: now,
458
+ });
459
+ openOutcome = {
460
+ action: "linked-existing",
461
+ message: formatGithubPrLink(observedGithubPr.prNumber, observedGithubPr.prUrl, "linked to"),
462
+ };
463
+ }
464
+ else if (remoteMode === "sync-only") {
465
+ openOutcome = linkedExistingOutcome ?? {
466
+ action: "sync-only",
467
+ message: "local PR artifacts synced; remote PR creation skipped (--sync-only)",
468
+ };
469
+ }
470
+ else {
471
+ const createdGithubPr = await tryCreateGithubPr({
472
+ gitRoot: resolved.gitRoot,
473
+ branch,
474
+ baseBranch,
475
+ title: githubTitle,
476
+ body: githubBody,
477
+ });
478
+ if (createdGithubPr.observed) {
479
+ nextMeta = buildObservedGithubPrMeta({
480
+ meta: nextMeta,
481
+ observed: createdGithubPr.observed,
482
+ at: now,
483
+ });
484
+ openOutcome = {
485
+ action: "created",
486
+ message: formatGithubPrLink(createdGithubPr.observed.prNumber, createdGithubPr.observed.prUrl, "created"),
487
+ };
488
+ }
489
+ else {
490
+ openOutcome = linkedExistingOutcome ?? {
491
+ action: "staged",
492
+ message: `local PR artifacts synced; remote PR creation staged (${createdGithubPr.stagedReason ?? "remote creation unavailable"})`,
493
+ };
494
+ }
495
+ }
496
+ const nextAutoSummary = renderPrAutoSummary({
497
+ updatedAt: renderUpdatedAt,
498
+ branch,
499
+ headSha: renderedSummaryHeadSha,
500
+ diffstat,
501
+ });
502
+ const nextReview = renderPrReviewDocument({
503
+ task,
504
+ author: opts.author,
505
+ createdAt,
506
+ branch,
507
+ handoffNotes,
508
+ autoSummary: nextAutoSummary,
509
+ });
510
+ const nextGithubBody = renderGithubPrBody({
511
+ task,
512
+ handoffNotes,
513
+ autoSummary: nextAutoSummary,
514
+ });
515
+ await writeJsonStableIfChanged(metaPath, nextMeta);
516
+ await writeTextIfChanged(diffstatPath, diffstat ? `${diffstat}\n` : "");
517
+ if (!(await fileExists(notesPath))) {
518
+ await writeTextIfChanged(notesPath, "");
519
+ }
520
+ if (!(await fileExists(verifyLogPath))) {
521
+ await writeTextIfChanged(verifyLogPath, "");
522
+ }
523
+ await writeTextIfChanged(reviewPath, nextReview);
524
+ await writeTextIfChanged(githubTitlePath, `${githubTitle}\n`);
525
+ await writeTextIfChanged(githubBodyPath, nextGithubBody);
526
+ return { meta: nextMeta, prDir, resolved, openOutcome };
527
+ }
528
+ if (!baseBranch) {
529
+ throw new CliError({
530
+ exitCode: exitCodeForError("E_USAGE"),
531
+ code: "E_USAGE",
532
+ message: "Base branch could not be resolved (use `agentplane branch base set`).",
533
+ });
534
+ }
535
+ const diffstat = await computePrDiffstat({
536
+ gitRoot: resolved.gitRoot,
537
+ baseBranch,
538
+ branch,
539
+ prDir,
540
+ });
541
+ let nextMeta = buildUpdatedPrMeta({
542
+ meta: existingMeta,
163
543
  branch,
164
544
  at: now,
165
- previousMeta: existingMeta,
166
545
  base: baseBranch,
167
- headSha,
546
+ headSha: renderedHeadSha,
168
547
  });
548
+ const observedGithubPr = await tryLookupExistingGithubPrByBranch({
549
+ gitRoot: resolved.gitRoot,
550
+ branch,
551
+ baseBranch,
552
+ });
553
+ if (observedGithubPr) {
554
+ nextMeta = buildObservedGithubPrMeta({
555
+ meta: nextMeta,
556
+ observed: observedGithubPr,
557
+ at: now,
558
+ });
559
+ }
169
560
  const nextAutoSummary = renderPrAutoSummary({
170
561
  updatedAt: nextMeta.updated_at,
171
562
  branch,
172
- headSha,
173
- diffstat: "",
563
+ headSha: nextMeta.head_sha ?? renderedHeadSha ?? headSha,
564
+ diffstat,
174
565
  });
175
566
  const nextReview = renderPrReviewDocument({
176
567
  task,
177
- author: opts.author,
178
568
  createdAt,
179
569
  branch,
180
570
  handoffNotes,
@@ -186,69 +576,19 @@ export async function syncPrArtifacts(opts) {
186
576
  handoffNotes,
187
577
  autoSummary: nextAutoSummary,
188
578
  });
189
- await writeJsonStableIfChanged(metaPath, nextMeta);
190
- if (!(await fileExists(diffstatPath))) {
191
- await writeTextIfChanged(diffstatPath, "");
192
- }
193
- if (!(await fileExists(notesPath))) {
194
- await writeTextIfChanged(notesPath, "");
195
- }
196
- if (!(await fileExists(verifyLogPath))) {
197
- await writeTextIfChanged(verifyLogPath, "");
198
- }
579
+ await writeTextIfChanged(diffstatPath, diffstat ? `${diffstat}\n` : "");
199
580
  await writeTextIfChanged(reviewPath, nextReview);
200
581
  await writeTextIfChanged(githubTitlePath, `${githubTitle}\n`);
201
582
  await writeTextIfChanged(githubBodyPath, githubBody);
202
- return { prDir, resolved };
583
+ await writeJsonStableIfChanged(metaPath, nextMeta);
584
+ return { meta: nextMeta, prDir, resolved };
203
585
  }
204
- if (!baseBranch) {
205
- throw new CliError({
206
- exitCode: exitCodeForError("E_USAGE"),
207
- code: "E_USAGE",
208
- message: "Base branch could not be resolved (use `agentplane branch base set`).",
586
+ finally {
587
+ await restoreIncidentRegistryIfNeeded({
588
+ gitRoot: resolved.gitRoot,
589
+ previousText: incidentsTextBefore,
209
590
  });
210
591
  }
211
- let diffstat = "";
212
- try {
213
- const { stdout: diffStatOut } = await execFileAsync("git", ["diff", "--stat", `${baseBranch}...${branch}`], { cwd: resolved.gitRoot, env: gitEnv() });
214
- diffstat = diffStatOut.trimEnd();
215
- }
216
- catch (err) {
217
- if (!isUnknownRevisionError(err))
218
- throw err;
219
- }
220
- const nextMeta = buildUpdatedPrMeta({
221
- meta: existingMeta,
222
- branch,
223
- at: now,
224
- base: baseBranch,
225
- headSha,
226
- });
227
- const nextAutoSummary = renderPrAutoSummary({
228
- updatedAt: nextMeta.updated_at,
229
- branch,
230
- headSha,
231
- diffstat,
232
- });
233
- const nextReview = renderPrReviewDocument({
234
- task,
235
- createdAt,
236
- branch,
237
- handoffNotes,
238
- autoSummary: nextAutoSummary,
239
- });
240
- const githubTitle = buildGithubPrTitle(task);
241
- const githubBody = renderGithubPrBody({
242
- task,
243
- handoffNotes,
244
- autoSummary: nextAutoSummary,
245
- });
246
- await writeTextIfChanged(diffstatPath, diffstat ? `${diffstat}\n` : "");
247
- await writeTextIfChanged(reviewPath, nextReview);
248
- await writeTextIfChanged(githubTitlePath, `${githubTitle}\n`);
249
- await writeTextIfChanged(githubBodyPath, githubBody);
250
- await writeJsonStableIfChanged(metaPath, nextMeta);
251
- return { prDir, resolved };
252
592
  }
253
593
  catch (err) {
254
594
  if (err instanceof CliError)
@@ -6,5 +6,6 @@ export declare function cmdPrOpen(opts: {
6
6
  taskId: string;
7
7
  author: string;
8
8
  branch?: string;
9
+ syncOnly?: boolean;
9
10
  }): Promise<number>;
10
11
  //# sourceMappingURL=open.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"open.d.ts","sourceRoot":"","sources":["../../../src/commands/pr/open.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAIhE,wBAAsB,SAAS,CAAC,IAAI,EAAE;IACpC,GAAG,CAAC,EAAE,cAAc,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,MAAM,CAAC,CA4BlB"}
1
+ {"version":3,"file":"open.d.ts","sourceRoot":"","sources":["../../../src/commands/pr/open.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAiBhE,wBAAsB,SAAS,CAAC,IAAI,EAAE;IACpC,GAAG,CAAC,EAAE,cAAc,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,GAAG,OAAO,CAAC,MAAM,CAAC,CAiClB"}