@nathanstephenson/flow 0.1.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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,743 @@
1
+ import { localStack, localStacks } from "./stack-metadata.js";
2
+ import { access } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { gh, repositoryTarget } from "./publish.js";
6
+ import { head, run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
7
+ import { stackDisplayGraph } from "../protocol/stack.js";
8
+ async function git(scope, args, write = false) {
9
+ const result = await run(scope, args, write ? GIT_WRITE_TIMEOUT_MS : GIT_READ_TIMEOUT_MS);
10
+ if (!result.ok)
11
+ throw new Error(result.failure.message);
12
+ return result.value;
13
+ }
14
+ export function parseStack(raw) {
15
+ const value = JSON.parse(raw);
16
+ if (!value || typeof value.trunk !== "string" || typeof value.currentBranch !== "string" || !Array.isArray(value.branches) || value.branches.some((branch) => !branch || typeof branch.name !== "string" || [branch.isCurrent, branch.isMerged, branch.isQueued, branch.needsRebase].some((flag) => typeof flag !== "boolean") ||
17
+ (branch.pr !== undefined && (!branch.pr || !Number.isInteger(branch.pr.number) || typeof branch.pr.state !== "string"))))
18
+ throw new Error("Invalid gh stack view JSON.");
19
+ return value;
20
+ }
21
+ // Project each API page to one compact JSON line. gh forbids combining --slurp and
22
+ // --jq, while --paginate applies the jq expression separately to every page.
23
+ const pullProjection = "map({number,title,html_url,state,merged_at,head:{ref:.head.ref,repo:(.head.repo|if . then {node_id,id} else null end)},base:{ref:.base.ref,repo:(.base.repo|if . then {node_id,id} else null end)}}) | @json";
24
+ const nativeProjection = "map({id,base:{ref:.base.ref},pull_requests:(.pull_requests|map({number,state,merged_at,head:{ref:.head.ref}}))}) | @json";
25
+ function message(error) {
26
+ return error instanceof Error ? error.message : String(error);
27
+ }
28
+ function pages(raw, label) {
29
+ try {
30
+ const parsed = raw.trim().split("\n").filter(Boolean).map(line => JSON.parse(line));
31
+ if (parsed.some(page => !Array.isArray(page) || page.some(Array.isArray)))
32
+ throw new Error();
33
+ return parsed.flat();
34
+ }
35
+ catch {
36
+ throw new Error(`GitHub returned invalid ${label} data.`);
37
+ }
38
+ }
39
+ function pullRequest(pr) {
40
+ return {
41
+ number: pr.number,
42
+ state: pr.merged_at ? "MERGED" : pr.state.toUpperCase(),
43
+ ...(pr.title && pr.html_url ? { title: pr.title, url: pr.html_url } : {}),
44
+ };
45
+ }
46
+ function validPull(pr) {
47
+ return Number.isInteger(pr?.number) && typeof pr?.head?.ref === "string" && typeof pr?.base?.ref === "string" &&
48
+ ["open", "closed"].includes(pr.state) && (pr.merged_at === null || typeof pr.merged_at === "string");
49
+ }
50
+ function sameRepository(pr, id) {
51
+ const identity = (repo) => repo?.node_id ?? (repo?.id === undefined ? undefined : String(repo.id));
52
+ return identity(pr.head.repo) === id && identity(pr.base.repo) === id;
53
+ }
54
+ async function loadPullRequests(scope, github, destination, current, localEdges = new Map(), explicitEdges = new Map(), blocked = new Set(), trunk = destination.defaultBranch) {
55
+ const warnings = [];
56
+ const load = async (query) => {
57
+ const loaded = pages(await github(scope, ["api", "--paginate", "--jq", pullProjection, `repos/${destination.repo}/pulls?${query}&per_page=100`]), "pull request");
58
+ if (loaded.some(pr => !validPull(pr)))
59
+ addWarning(warnings, "Some invalid pull request relationships were ignored.");
60
+ return loaded.filter(pr => validPull(pr) && sameRepository(pr, String(destination.id)));
61
+ };
62
+ const prs = await load("state=open");
63
+ const component = new Set([current]);
64
+ const queried = new Set();
65
+ for (;;) {
66
+ let changed = false;
67
+ for (const pr of prs) {
68
+ if (pr.head.ref === trunk || explicitEdges.has(pr.head.ref) || blocked.has(pr.head.ref))
69
+ continue;
70
+ if (component.has(pr.head.ref) || (pr.base.ref !== trunk && component.has(pr.base.ref))) {
71
+ for (const branch of [pr.head.ref, pr.base.ref])
72
+ if (branch !== trunk && !component.has(branch)) {
73
+ component.add(branch);
74
+ changed = true;
75
+ }
76
+ }
77
+ }
78
+ for (const [child, edge] of new Map([...localEdges, ...explicitEdges])) {
79
+ if (blocked.has(child) || (!explicitEdges.has(child) && prs.some(pr => pr.head.ref === child)) || edge.parent === trunk)
80
+ continue;
81
+ if (component.has(child) || component.has(edge.parent)) {
82
+ for (const name of [child, edge.parent])
83
+ if (!component.has(name)) {
84
+ component.add(name);
85
+ changed = true;
86
+ }
87
+ }
88
+ }
89
+ if (changed)
90
+ continue;
91
+ const branch = [...component].find(name => name !== trunk && !queried.has(name) && !prs.some(pr => pr.head.ref === name && pr.state === "open"));
92
+ if (!branch)
93
+ break;
94
+ queried.add(branch);
95
+ try {
96
+ const history = await load(`state=closed&head=${encodeURIComponent(`${destination.repo.split("/")[0]}:${branch}`)}`);
97
+ prs.push(...history.filter(pr => pr.head.ref === branch && Boolean(pr.merged_at)));
98
+ }
99
+ catch (error) {
100
+ addWarning(warnings, `Pull request ancestors for ${branch} could not be read: ${message(error)}`);
101
+ }
102
+ }
103
+ return { prs, warnings };
104
+ }
105
+ async function refs(scope) {
106
+ const result = { local: new Map(), remote: new Map() };
107
+ const raw = await git(scope, ["for-each-ref", "--format=%(refname) %(objectname)", "refs/heads", "refs/remotes"]);
108
+ for (const line of raw.trim().split("\n").filter(Boolean)) {
109
+ const space = line.lastIndexOf(" ");
110
+ if (space < 0)
111
+ continue;
112
+ const ref = line.slice(0, space);
113
+ const oid = line.slice(space + 1);
114
+ if (ref.startsWith("refs/heads/"))
115
+ result.local.set(ref.slice("refs/heads/".length), { oid });
116
+ else if (ref.startsWith("refs/remotes/") && !ref.endsWith("/HEAD")) {
117
+ const short = ref.slice("refs/remotes/".length);
118
+ const slash = short.indexOf("/");
119
+ if (slash >= 0 && !result.remote.has(short.slice(slash + 1)))
120
+ result.remote.set(short.slice(slash + 1), { oid });
121
+ }
122
+ }
123
+ const remotes = (await git(scope, ["remote"])).trim().split("\n").filter(Boolean);
124
+ if (remotes.length === 1) {
125
+ result.remoteName = remotes[0];
126
+ try {
127
+ const target = (await git(scope, ["symbolic-ref", "--quiet", `refs/remotes/${remotes[0]}/HEAD`])).trim();
128
+ const prefix = `refs/remotes/${remotes[0]}/`;
129
+ if (target.startsWith(prefix))
130
+ result.remoteHead = target.slice(prefix.length);
131
+ }
132
+ catch { /* A remote without an existing HEAD is not an error. */ }
133
+ }
134
+ return result;
135
+ }
136
+ function expectedNativeUnavailable(error) {
137
+ return /(?:HTTP 404|not found|stacked pull requests (?:are )?not (?:enabled|available))/i.test(message(error));
138
+ }
139
+ function addWarning(warnings, value) {
140
+ if (value && !warnings.includes(value))
141
+ warnings.push(value);
142
+ }
143
+ async function ancestry(scope, tips) {
144
+ const unique = [...new Set(tips)];
145
+ const merged = new Map();
146
+ // Ask Git to walk each tip, but emit only matching refs. Unlike rev-list this keeps output
147
+ // bounded by the number of refs rather than by repository history.
148
+ const next = unique.values();
149
+ const worker = async () => {
150
+ for (let item = next.next(); !item.done; item = next.next()) {
151
+ const descendant = item.value;
152
+ const raw = await git(scope, ["for-each-ref", `--merged=${descendant}`, "--format=%(objectname)", "refs/heads", "refs/remotes"]);
153
+ merged.set(descendant, new Set(raw.trim().split("\n").filter(Boolean)));
154
+ }
155
+ };
156
+ await Promise.all(Array.from({ length: Math.min(4, unique.length) }, worker));
157
+ return (ancestor, descendant) => ancestor === descendant || Boolean(merged.get(descendant)?.has(ancestor));
158
+ }
159
+ /**
160
+ * Read-only discovery for the current branch. It deliberately uses only inspection commands:
161
+ * no fetch, import, registration, checkout, rebase, or push is performed here.
162
+ */
163
+ export async function discoverStackGraph(scope, github = gh) {
164
+ const warnings = [];
165
+ const branchWarnings = [];
166
+ const warnBranch = (branch, text) => branchWarnings.push({ branches: [branch], text });
167
+ const scopedWarnings = (component) => [...warnings, ...branchWarnings.filter(warning => warning.branches.some(branch => component.has(branch))).map(warning => warning.text)];
168
+ const currentResult = await head(scope);
169
+ if (!currentResult.ok)
170
+ return { warnings: [currentResult.failure.message] };
171
+ if (currentResult.value.detached)
172
+ return { warnings };
173
+ const current = currentResult.value.name;
174
+ let reference;
175
+ try {
176
+ reference = await refs(scope);
177
+ }
178
+ catch (error) {
179
+ return { warnings: [message(error)] };
180
+ }
181
+ let stacks = [];
182
+ try {
183
+ stacks = await localStacks(scope);
184
+ }
185
+ catch (error) {
186
+ addWarning(warnings, `Local stack metadata could not be read: ${message(error)}`);
187
+ }
188
+ const localMatches = stacks.filter(stack => stack.branches.some(branch => branch.branch === current));
189
+ let destination;
190
+ let prs = [];
191
+ let pullsComplete = false;
192
+ let nativeStacks = [];
193
+ if (reference.remoteName) {
194
+ try {
195
+ destination = await repositoryTarget(scope, github);
196
+ }
197
+ catch (error) {
198
+ addWarning(warnings, `GitHub stack discovery failed: ${message(error)}`);
199
+ }
200
+ if (destination) {
201
+ const [nativeResult] = await Promise.allSettled([
202
+ github(scope, ["api", "--paginate", "--jq", nativeProjection, `repos/${destination.repo}/stacks?per_page=100`]),
203
+ ]);
204
+ if (nativeResult.status === "fulfilled") {
205
+ try {
206
+ const loaded = pages(nativeResult.value, "native stack");
207
+ nativeStacks = loaded.filter(stack => Number.isInteger(stack?.id) && typeof stack?.base?.ref === "string" && Array.isArray(stack.pull_requests) && stack.pull_requests.every(pr => Number.isInteger(pr?.number) && typeof pr?.head?.ref === "string" && ["open", "closed"].includes(pr.state) && (pr.merged_at === null || typeof pr.merged_at === "string")));
208
+ if (nativeStacks.length !== loaded.length)
209
+ addWarning(warnings, "Some invalid native stack data was ignored.");
210
+ }
211
+ catch (error) {
212
+ addWarning(warnings, `Native GitHub stack data could not be parsed: ${message(error)}`);
213
+ }
214
+ }
215
+ else if (!expectedNativeUnavailable(nativeResult.reason))
216
+ addWarning(warnings, `Native GitHub stacks could not be read: ${message(nativeResult.reason)}`);
217
+ }
218
+ }
219
+ const nodes = new Set();
220
+ const prsByBranch = new Map();
221
+ const edges = new Map();
222
+ const claimed = new Set();
223
+ const explicitMembers = new Set();
224
+ const blocked = new Set();
225
+ const explicitEdges = new Map();
226
+ const explicitTrunks = new Set();
227
+ const offerExplicit = (child, parent, relation) => {
228
+ nodes.add(child);
229
+ explicitMembers.add(child);
230
+ const choices = explicitEdges.get(child) ?? [];
231
+ choices.push({ parent, relation });
232
+ explicitEdges.set(child, choices);
233
+ };
234
+ for (const stack of localMatches) {
235
+ explicitTrunks.add(stack.trunk.branch);
236
+ let parent = stack.trunk.branch;
237
+ for (const branch of stack.branches) {
238
+ offerExplicit(branch.branch, parent, "local");
239
+ if (branch.pullRequest)
240
+ prsByBranch.set(branch.branch, { number: branch.pullRequest.number, state: branch.pullRequest.merged ? "MERGED" : "OPEN" });
241
+ parent = branch.branch;
242
+ }
243
+ }
244
+ for (const stack of nativeStacks.filter(stack => stack.pull_requests.some(pr => pr.head.ref === current))) {
245
+ const topOpen = stack.pull_requests.reduce((last, pr, index) => pr.state === "open" ? index : last, -1);
246
+ if (topOpen < 0)
247
+ continue;
248
+ explicitTrunks.add(stack.base.ref);
249
+ let parent = stack.base.ref;
250
+ for (let index = 0; index <= topOpen; index++) {
251
+ const pr = stack.pull_requests[index];
252
+ if (pr.state === "closed" && !pr.merged_at) {
253
+ // Do not let a closed-unmerged member connect the members around it.
254
+ parent = undefined;
255
+ continue;
256
+ }
257
+ if (parent)
258
+ offerExplicit(pr.head.ref, parent, "native");
259
+ else {
260
+ nodes.add(pr.head.ref);
261
+ explicitMembers.add(pr.head.ref);
262
+ claimed.add(pr.head.ref);
263
+ blocked.add(pr.head.ref);
264
+ addWarning(warnings, `A closed-unmerged native stack member precedes ${pr.head.ref}; its parent was omitted.`);
265
+ }
266
+ prsByBranch.set(pr.head.ref, pullRequest(pr));
267
+ parent = pr.head.ref;
268
+ }
269
+ }
270
+ for (const [child, choices] of explicitEdges) {
271
+ const parents = [...new Set(choices.map(choice => choice.parent))];
272
+ claimed.add(child);
273
+ if (parents.length !== 1) {
274
+ blocked.add(child);
275
+ addWarning(warnings, `Conflicting explicit stack parents for ${child}; its parent was omitted.`);
276
+ continue;
277
+ }
278
+ edges.set(child, { parent: parents[0], relation: choices.some(choice => choice.relation === "native") ? "native" : "local" });
279
+ }
280
+ let trunk;
281
+ if (explicitTrunks.size === 1)
282
+ trunk = [...explicitTrunks][0];
283
+ else if (explicitTrunks.size > 1)
284
+ addWarning(warnings, "Conflicting explicit stack trunks were found; the trunk was left unknown.");
285
+ else
286
+ trunk = destination?.defaultBranch ?? reference.remoteHead;
287
+ const localParents = new Map();
288
+ const ambiguousParents = new Set();
289
+ const trunkValues = trunk ? [reference.local.get(trunk), reference.remote.get(trunk)].filter((value) => Boolean(value)) : [];
290
+ const trunkValue = trunkValues[0];
291
+ if (trunk && trunkValue) {
292
+ try {
293
+ const isAncestor = await ancestry(scope, [...reference.local.values(), ...trunkValues].map(value => value.oid));
294
+ const usable = [...reference.local].filter(([branch, value]) => branch !== trunk &&
295
+ !trunkValues.some(tip => isAncestor(value.oid, tip.oid)) && trunkValues.some(tip => isAncestor(tip.oid, value.oid)));
296
+ for (const [child, childRef] of usable) {
297
+ const ancestors = usable.filter(([parent, parentRef]) => parent !== child && parentRef.oid !== childRef.oid && isAncestor(parentRef.oid, childRef.oid));
298
+ const nearest = ancestors.filter(([, candidate]) => !ancestors.some(([, other]) => candidate.oid !== other.oid && isAncestor(candidate.oid, other.oid)));
299
+ if (nearest.length > 1)
300
+ ambiguousParents.add(child);
301
+ else
302
+ localParents.set(child, { parent: nearest[0]?.[0] ?? trunk, relation: "ancestry" });
303
+ }
304
+ }
305
+ catch (error) {
306
+ addWarning(warnings, `Local ancestry could not be read: ${message(error)}`);
307
+ }
308
+ }
309
+ if (destination) {
310
+ try {
311
+ const loaded = await loadPullRequests(scope, github, destination, current, localParents, edges, blocked, trunk);
312
+ prs = loaded.prs;
313
+ pullsComplete = !loaded.warnings.length;
314
+ for (const warning of loaded.warnings)
315
+ addWarning(warnings, warning);
316
+ }
317
+ catch (error) {
318
+ addWarning(warnings, `Pull request relationships could not be read: ${message(error)}`);
319
+ }
320
+ }
321
+ const snapshot = { current, reference, stacks, ...(destination ? { destination } : {}), prs, pullsComplete };
322
+ const byHead = new Map();
323
+ for (const pr of prs) {
324
+ const list = byHead.get(pr.head.ref) ?? [];
325
+ list.push(pr);
326
+ byHead.set(pr.head.ref, list);
327
+ }
328
+ const selected = new Map();
329
+ for (const [branch, branchPRs] of byHead) {
330
+ const open = branchPRs.filter(pr => pr.state === "open");
331
+ if (open.length === 1)
332
+ selected.set(branch, open[0]);
333
+ else if (open.length > 1) {
334
+ claimed.add(branch);
335
+ blocked.add(branch);
336
+ warnBranch(branch, `Multiple open pull requests describe ${branch}; its parent was omitted.`);
337
+ }
338
+ }
339
+ // A merged PR only participates when it is needed to connect an active descendant.
340
+ const queue = [...selected.values()].map(pr => pr.base.ref);
341
+ const visitedBases = new Set();
342
+ while (queue.length) {
343
+ const branch = queue.shift();
344
+ if (branch === trunk || visitedBases.has(branch) || selected.has(branch))
345
+ continue;
346
+ visitedBases.add(branch);
347
+ const merged = (byHead.get(branch) ?? []).filter(pr => Boolean(pr.merged_at));
348
+ if (!merged.length)
349
+ continue;
350
+ const parents = [...new Set(merged.map(pr => pr.base.ref))];
351
+ if (parents.length !== 1) {
352
+ claimed.add(branch);
353
+ blocked.add(branch);
354
+ warnBranch(branch, `Historical pull requests disagree about the parent of ${branch}; its parent was omitted.`);
355
+ continue;
356
+ }
357
+ // GitHub lists newest PRs first. Equivalent historical relationships do not compete.
358
+ selected.set(branch, merged[0]);
359
+ queue.push(merged[0].base.ref);
360
+ }
361
+ for (const [child, pr] of selected) {
362
+ nodes.add(child);
363
+ if (pr.base.ref !== trunk)
364
+ nodes.add(pr.base.ref);
365
+ prsByBranch.set(child, pullRequest(pr));
366
+ claimed.add(child);
367
+ if (!edges.has(child) && !blocked.has(child))
368
+ edges.set(child, { parent: pr.base.ref, relation: "pull-request" });
369
+ }
370
+ for (const [child, edge] of localParents) {
371
+ if (claimed.has(child) || blocked.has(child) || edges.has(child))
372
+ continue;
373
+ nodes.add(child);
374
+ if (edge.parent !== trunk)
375
+ nodes.add(edge.parent);
376
+ edges.set(child, edge);
377
+ }
378
+ for (const child of ambiguousParents) {
379
+ if (claimed.has(child) || blocked.has(child) || edges.has(child))
380
+ continue;
381
+ blocked.add(child);
382
+ warnBranch(child, `Local history has multiple equally near parents for ${child}; its parent was omitted.`);
383
+ }
384
+ if (!trunk && new Set([...reference.local.values()].map(value => value.oid)).size >= 2 && !explicitMembers.size && !selected.size) {
385
+ addWarning(warnings, "The trunk branch is unknown, so local branch relationships could not be inferred.");
386
+ }
387
+ else if (trunk && !trunkValue && new Set([...reference.local.values()].map(value => value.oid)).size >= 2 && !explicitMembers.size && !selected.size) {
388
+ addWarning(warnings, `The trunk ${trunk} is not available in local refs, so local branch relationships could not be inferred.`);
389
+ }
390
+ // A parent map cannot safely contain a cycle. Remove every edge in each cycle rather than
391
+ // selecting an arbitrary edge to break it.
392
+ const checked = new Set();
393
+ for (const start of edges.keys()) {
394
+ if (checked.has(start))
395
+ continue;
396
+ const path = [];
397
+ const position = new Map();
398
+ let branch = start;
399
+ while (branch && edges.has(branch) && !checked.has(branch)) {
400
+ const seen = position.get(branch);
401
+ if (seen !== undefined) {
402
+ const cycle = path.slice(seen);
403
+ for (const member of cycle) {
404
+ edges.delete(member);
405
+ blocked.add(member);
406
+ }
407
+ branchWarnings.push({ branches: cycle, text: `A stack relationship cycle involving ${[...cycle].sort().join(", ")} was omitted.` });
408
+ break;
409
+ }
410
+ position.set(branch, path.length);
411
+ path.push(branch);
412
+ branch = edges.get(branch)?.parent;
413
+ }
414
+ for (const member of path)
415
+ checked.add(member);
416
+ }
417
+ if (current === trunk || !nodes.has(current))
418
+ return { warnings: scopedWarnings(new Set([current])), snapshot };
419
+ // Scope through non-trunk edges only. Trunk is a boundary, not a hub joining unrelated stacks.
420
+ const adjacent = new Map();
421
+ const join = (a, b) => {
422
+ const aSet = adjacent.get(a) ?? new Set();
423
+ aSet.add(b);
424
+ adjacent.set(a, aSet);
425
+ const bSet = adjacent.get(b) ?? new Set();
426
+ bSet.add(a);
427
+ adjacent.set(b, bSet);
428
+ };
429
+ for (const [child, edge] of edges)
430
+ if (edge.parent !== trunk && nodes.has(edge.parent))
431
+ join(child, edge.parent);
432
+ const component = new Set([current]);
433
+ const pending = [current];
434
+ while (pending.length)
435
+ for (const next of adjacent.get(pending.shift()) ?? [])
436
+ if (!component.has(next)) {
437
+ component.add(next);
438
+ pending.push(next);
439
+ }
440
+ const explicit = [...component].some(branch => explicitMembers.has(branch));
441
+ const related = [...component].some(branch => {
442
+ const parent = edges.get(branch)?.parent;
443
+ return parent !== undefined && parent !== trunk && component.has(parent);
444
+ });
445
+ if (!explicit && (component.size < 2 || !related))
446
+ return { warnings: scopedWarnings(component), snapshot };
447
+ const children = new Map();
448
+ for (const branch of component) {
449
+ const parent = edges.get(branch)?.parent;
450
+ if (!parent || !component.has(parent))
451
+ continue;
452
+ const list = children.get(parent) ?? [];
453
+ list.push(branch);
454
+ children.set(parent, list);
455
+ }
456
+ for (const list of children.values())
457
+ list.sort((a, b) => a.localeCompare(b));
458
+ const roots = [...component].filter(branch => !component.has(edges.get(branch)?.parent ?? "")).sort((a, b) => a.localeCompare(b));
459
+ const order = [];
460
+ const append = (branch) => { order.push(branch); for (const child of children.get(branch) ?? [])
461
+ append(child); };
462
+ for (const root of roots)
463
+ append(root);
464
+ const branches = order.map(name => {
465
+ const edge = edges.get(name);
466
+ return {
467
+ name,
468
+ ...(edge ? { parent: edge.parent, relation: edge.relation } : {}),
469
+ isCurrent: name === current,
470
+ availability: reference.local.has(name) ? "local" : "remote",
471
+ ...(prsByBranch.has(name) ? { pr: prsByBranch.get(name) } : {}),
472
+ };
473
+ });
474
+ return { graph: { ...(trunk ? { trunk } : {}), currentBranch: current, branches, explicit }, warnings: scopedWarnings(component), snapshot };
475
+ }
476
+ function indexPullRequests(pullRequests) {
477
+ const byHead = new Map();
478
+ const openByBase = new Map();
479
+ for (const pr of pullRequests) {
480
+ const heads = byHead.get(pr.head.ref) ?? [];
481
+ heads.push(pr);
482
+ byHead.set(pr.head.ref, heads);
483
+ if (pr.state === "open") {
484
+ const children = openByBase.get(pr.base.ref) ?? [];
485
+ children.push(pr);
486
+ openByBase.set(pr.base.ref, children);
487
+ }
488
+ }
489
+ return { byHead, openByBase };
490
+ }
491
+ function candidateFromSnapshot(snapshot) {
492
+ const { current, reference, stacks, destination } = snapshot;
493
+ const { byHead, openByBase } = indexPullRequests(snapshot.prs);
494
+ if (!destination?.id || current === destination.defaultBranch)
495
+ return;
496
+ const tracked = new Set(stacks.flatMap(stack => [stack.trunk.branch, ...stack.branches.map(branch => branch.branch)]));
497
+ if (stacks.some(stack => stack.branches.some(branch => branch.branch === current)))
498
+ return;
499
+ const localRefs = [...reference.local].map(([name, value]) => [name, value.oid]);
500
+ const trunk = destination.defaultBranch;
501
+ const base = localRefs.find(([name]) => name === trunk);
502
+ if (!base)
503
+ return;
504
+ const choose = (branch, merged) => {
505
+ const matching = byHead.get(branch) ?? [];
506
+ const open = matching.filter(pr => pr.state === "open");
507
+ if (open.length === 1)
508
+ return open[0];
509
+ if (open.length > 1 || !merged)
510
+ return;
511
+ const history = matching.filter(pr => Boolean(pr.merged_at));
512
+ return new Set(history.map(pr => pr.base.ref)).size === 1 ? history[0] : undefined;
513
+ };
514
+ const chain = [];
515
+ const seen = new Set();
516
+ let branch = current;
517
+ while (branch !== trunk) {
518
+ if (seen.has(branch))
519
+ return;
520
+ seen.add(branch);
521
+ const parent = choose(branch, true);
522
+ if (!parent)
523
+ return;
524
+ chain.unshift(parent);
525
+ branch = parent.base.ref;
526
+ }
527
+ branch = current;
528
+ while (true) {
529
+ const children = openByBase.get(branch) ?? [];
530
+ if (!children.length)
531
+ break;
532
+ if (children.length !== 1 || seen.has(children[0].head.ref))
533
+ return;
534
+ chain.push(children[0]);
535
+ branch = children[0].head.ref;
536
+ seen.add(branch);
537
+ }
538
+ if (chain.length < 2 || !chain.some(pr => pr.state === "open"))
539
+ return;
540
+ for (const pr of chain)
541
+ if (pr.head.ref === trunk || tracked.has(pr.head.ref) || !reference.local.has(pr.head.ref))
542
+ return;
543
+ for (const pr of chain)
544
+ if ((openByBase.get(pr.head.ref)?.length ?? 0) > (pr === chain.at(-1) ? 0 : 1))
545
+ return;
546
+ return {
547
+ trunk,
548
+ branches: chain.map(pr => pr.head.ref),
549
+ pullRequests: chain.map(pr => ({ branch: pr.head.ref, ...pullRequest(pr) })),
550
+ fingerprint: createHash("sha256").update(JSON.stringify({ destination, base, chain, localRefs, current })).digest("hex"),
551
+ };
552
+ }
553
+ export async function discoverStack(scope, github = gh) {
554
+ try {
555
+ const current = await head(scope);
556
+ if (!current.ok || current.value.detached)
557
+ return;
558
+ const [reference, stacks, destination] = await Promise.all([refs(scope), localStacks(scope), repositoryTarget(scope, github)]);
559
+ const { prs, warnings } = await loadPullRequests(scope, github, destination, current.value.name);
560
+ if (warnings.length || !destination.id)
561
+ return;
562
+ return candidateFromSnapshot({ current: current.value.name, reference, stacks, destination, prs });
563
+ }
564
+ catch {
565
+ return;
566
+ }
567
+ }
568
+ export async function actionStackStatus(scope, github = gh) {
569
+ const status = { available: false, conflicts: [], rebasing: false };
570
+ try {
571
+ await github(scope, ["stack", "--help"]);
572
+ status.available = true;
573
+ }
574
+ catch {
575
+ status.problem = "Install GitHub CLI, then run gh extension install github/gh-stack on the Session Host to manage this stack. Viewing does not require the extension. Run gh auth login if needed.";
576
+ status.problemKind = "action";
577
+ }
578
+ try {
579
+ status.conflicts = (await git(scope, ["diff", "--name-only", "--diff-filter=U", "-z"])).split("\0").filter(Boolean);
580
+ const path = (await git(scope, ["rev-parse", "--git-path", "gh-stack-rebase-state"])).trim();
581
+ status.rebasing = await access(resolve(scope, path)).then(() => true, () => false);
582
+ }
583
+ catch (error) {
584
+ status.problem = message(error);
585
+ status.problemKind = "discovery";
586
+ }
587
+ if (status.available) {
588
+ try {
589
+ status.view = parseStack(await github(scope, ["stack", "view", "--json"]));
590
+ }
591
+ catch (error) {
592
+ if (/current branch .+ (?:is not|not) (?:a )?part of (?:a |any )?stack/i.test(message(error))) {
593
+ status.warnings = ["gh-stack reports that the current branch is not part of a managed stack."];
594
+ }
595
+ else
596
+ status.warnings = [`Managed stack details could not be read: ${message(error)}`];
597
+ }
598
+ }
599
+ return status;
600
+ }
601
+ export async function stackStatus(scope, github = gh) {
602
+ const status = await actionStackStatus(scope, github);
603
+ const actionProblem = status.problemKind === "action" ? status.problem : undefined;
604
+ if (actionProblem) {
605
+ delete status.problem;
606
+ delete status.problemKind;
607
+ }
608
+ const notManagedWarning = "gh-stack reports that the current branch is not part of a managed stack.";
609
+ const warnings = [...(status.warnings ?? [])];
610
+ delete status.warnings;
611
+ let discovery;
612
+ try {
613
+ discovery = await discoverStackGraph(scope, github);
614
+ if (discovery.graph)
615
+ status.graph = discovery.graph;
616
+ if (status.view && discovery.snapshot) {
617
+ const details = new Map(discovery.snapshot.prs.map(pr => [pr.number, pr]));
618
+ for (const branch of status.view.branches) {
619
+ if (!branch.pr)
620
+ continue;
621
+ const found = details.get(branch.pr.number);
622
+ if (found?.title && found.html_url)
623
+ Object.assign(branch.pr, { title: found.title, url: found.html_url });
624
+ }
625
+ }
626
+ for (const warning of discovery.warnings)
627
+ addWarning(warnings, warning);
628
+ if (!discovery.snapshot?.stacks.some(stack => stack.branches.some(branch => branch.branch === discovery.snapshot.current))) {
629
+ const index = warnings.indexOf(notManagedWarning);
630
+ if (index >= 0)
631
+ warnings.splice(index, 1);
632
+ }
633
+ }
634
+ catch (error) {
635
+ addWarning(warnings, `Stack discovery failed: ${message(error)}`);
636
+ }
637
+ if (!status.view && !status.rebasing) {
638
+ try {
639
+ const candidate = discovery?.snapshot?.pullsComplete ? candidateFromSnapshot(discovery.snapshot) : undefined;
640
+ if (candidate)
641
+ status.candidate = candidate;
642
+ }
643
+ catch (error) {
644
+ // Broad discovery may still have produced a useful graph. Candidate failure only removes Init.
645
+ if (status.graph)
646
+ addWarning(warnings, `This graph is read-only because registration eligibility could not be verified: ${message(error)}`);
647
+ }
648
+ }
649
+ const displayGraph = stackDisplayGraph(status);
650
+ if (displayGraph)
651
+ status.graph = displayGraph;
652
+ else
653
+ delete status.graph;
654
+ if (warnings.length)
655
+ status.warnings = warnings;
656
+ const hasDisplay = Boolean(status.graph || status.rebasing);
657
+ if (!status.problem && warnings.length && !hasDisplay) {
658
+ status.problem = warnings.shift();
659
+ status.problemKind = "discovery";
660
+ if (warnings.length)
661
+ status.warnings = warnings;
662
+ else
663
+ delete status.warnings;
664
+ }
665
+ else if (!status.problem && actionProblem) {
666
+ status.problem = actionProblem;
667
+ status.problemKind = "action";
668
+ }
669
+ return status;
670
+ }
671
+ export async function cleanStack(scope) {
672
+ if ((await git(scope, ["status", "--porcelain=v1", "-z", "--untracked-files=all"])).length)
673
+ throw new Error("This Scope has uncommitted changes. Use Publish or commit them first. Stack operations never stash changes.");
674
+ for (const operation of ["rebase-merge", "rebase-apply", "sequencer", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "gh-stack-rebase-state"]) {
675
+ const path = (await git(scope, ["rev-parse", "--git-path", operation])).trim();
676
+ if (await access(resolve(scope, path)).then(() => true, () => false))
677
+ throw new Error("Finish or abort the current Git operation first.");
678
+ }
679
+ }
680
+ export async function stackFingerprint(scope, view, sync = false, github = gh) {
681
+ let membership;
682
+ if (sync) {
683
+ if (view.currentBranch === view.trunk)
684
+ throw new Error("Switch to a branch in the stack before reviewing Sync.");
685
+ const stack = await localStack(scope, view.currentBranch);
686
+ if (stack?.id) {
687
+ const remote = JSON.parse(await github(scope, ["api", `repos/{owner}/{repo}/stacks/${stack.id}`, "--jq", "{id,pull_requests:(.pull_requests|map({number,head:{ref:.head.ref}}))}"]));
688
+ if (!remote || !Number.isInteger(remote.id))
689
+ throw new Error("Cannot verify remote stack membership.");
690
+ membership = remote;
691
+ if (remote && (!Array.isArray(remote.pull_requests) || JSON.stringify(remote.pull_requests.map(pr => [pr.head?.ref, pr.number])) !== JSON.stringify(stack.branches.filter(b => b.pullRequest).map(b => [b.branch, b.pullRequest.number]))))
692
+ throw new Error("Remote stack membership differs from the local stack. Review and import remote branches with gh stack outside Flow, then review Sync again.");
693
+ }
694
+ }
695
+ const refs = await git(scope, ["show-ref", "--head"]);
696
+ const config = await git(scope, ["config", "--local", "--list"]);
697
+ return createHash("sha256").update(JSON.stringify({ view, refs, config, membership })).digest("hex");
698
+ }
699
+ export async function changeStack(scope, input, github = gh) {
700
+ const { action } = input;
701
+ if (!["init", "add", "checkout", "rebase", "continue", "abort", "submit", "sync"].includes(action))
702
+ throw new Error("Unknown Stack action.");
703
+ if (action === "continue" || action === "abort") {
704
+ const state = await actionStackStatus(scope, github);
705
+ if (!state.rebasing)
706
+ throw new Error("No Stack rebase is in progress.");
707
+ if (action === "continue" && state.conflicts.length)
708
+ throw new Error("Resolve and stage all conflict files before continuing.");
709
+ }
710
+ else
711
+ await cleanStack(scope);
712
+ const args = ["stack", action];
713
+ if (action === "init") {
714
+ const candidate = await discoverStack(scope, github);
715
+ if (!candidate || input.fingerprint !== candidate.fingerprint || JSON.stringify(input.branches) !== JSON.stringify(candidate.branches))
716
+ throw new Error("The existing branch chain changed or is not eligible. Refresh Stack and review it again.");
717
+ args.push("--base", candidate.trunk);
718
+ }
719
+ if (action === "init" || action === "add" || action === "checkout") {
720
+ if (!Array.isArray(input.branches) || !input.branches.length || (action !== "init" && input.branches.length !== 1))
721
+ throw new Error("Enter a branch name.");
722
+ for (const branch of input.branches) {
723
+ if (typeof branch !== "string" || branch.startsWith("-") || !branch.trim())
724
+ throw new Error("Invalid branch name.");
725
+ await git(scope, ["check-ref-format", "--branch", branch]);
726
+ }
727
+ if (action === "checkout") {
728
+ const state = await actionStackStatus(scope, github);
729
+ const branch = input.branches[0];
730
+ if (!state.view?.branches.some(b => b.name === branch))
731
+ throw new Error("Choose a branch in the current local stack.");
732
+ await git(scope, ["show-ref", "--verify", `refs/heads/${branch}`]);
733
+ return git(scope, ["switch", "--no-guess", "--", branch], true);
734
+ }
735
+ args.push(...input.branches);
736
+ }
737
+ if (action === "continue" || action === "abort")
738
+ args.splice(1, 1, "rebase", `--${action}`);
739
+ if (action === "submit")
740
+ args.push("--auto");
741
+ return github(scope, args);
742
+ }
743
+ export const stackConflictMessage = "Resolve the current gh stack rebase conflicts in this Scope. Inspect the Stack rebase state and conflict files first. Preserve the intended changes and stage only resolved files. Run gh stack rebase --continue only after git diff --name-only --diff-filter=U is empty and all conflicts are resolved. Repeat for further conflicts; stop and report if the intended resolution is unclear. This request permits local conflict repair and Stack rebase continuation only. Do not push, publish, submit, sync, merge, or restructure the stack. Report the result so I can review it before any separate Sync confirmation.";