@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.10
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 +52 -22
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
- package/build/backend-worker.mjs +69 -122
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +188 -25
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +118 -20
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +1 -1
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +42 -8
- package/dist/backend/worker/index.js +131 -15
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +940 -119
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +12 -9
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +400 -311
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +127 -11
- package/dist/workflows/recovery.js +38 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +367 -96
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-api-BfExddae.js +0 -6
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
- /package/dist/protocol/{publish.js → imports.js} +0 -0
package/dist/daemon/stack.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { localStack, localStacks } from "./stack-metadata.js";
|
|
1
|
+
import { commonGitPath, localStack, localStacks } from "./stack-metadata.js";
|
|
2
2
|
import { access } from "node:fs/promises";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
5
|
+
import { localRepository, mergeMethods, mergeSettingsFields, resolveRepository } from "./repository.js";
|
|
6
|
+
import { api, gh } from "./github.js";
|
|
7
|
+
import { head, localBranches, run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
|
|
8
|
+
import { stackMergeBlock } from "../protocol/stack.js";
|
|
8
9
|
async function git(scope, args, write = false) {
|
|
9
10
|
const result = await run(scope, args, write ? GIT_WRITE_TIMEOUT_MS : GIT_READ_TIMEOUT_MS);
|
|
10
11
|
if (!result.ok)
|
|
@@ -18,664 +19,140 @@ export function parseStack(raw) {
|
|
|
18
19
|
throw new Error("Invalid gh stack view JSON.");
|
|
19
20
|
return value;
|
|
20
21
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
function
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
22
|
+
const install = "Install gh-stack on the Session Host: gh extension install github/gh-stack. Run gh auth login if needed.";
|
|
23
|
+
const notInStack = /is not part of a stack/i;
|
|
24
|
+
export const otherWorktreeRebase = "A stack rebase is in progress in another worktree.";
|
|
25
|
+
const queues = new Map();
|
|
26
|
+
async function runStack(scope, args, github) {
|
|
27
|
+
const key = await commonGitPath(scope, ".");
|
|
28
|
+
const run = (queues.get(key) ?? Promise.resolve()).catch(() => undefined).then(() => github(scope, ["stack", ...args]));
|
|
29
|
+
queues.set(key, run);
|
|
29
30
|
try {
|
|
30
|
-
|
|
31
|
-
if (parsed.some(page => !Array.isArray(page) || page.some(Array.isArray)))
|
|
32
|
-
throw new Error();
|
|
33
|
-
return parsed.flat();
|
|
31
|
+
return await run;
|
|
34
32
|
}
|
|
35
|
-
|
|
36
|
-
|
|
33
|
+
finally {
|
|
34
|
+
if (queues.get(key) === run)
|
|
35
|
+
queues.delete(key);
|
|
37
36
|
}
|
|
38
37
|
}
|
|
39
|
-
function
|
|
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 };
|
|
38
|
+
async function gitPathExists(scope, name) {
|
|
39
|
+
return access(resolve(scope, (await git(scope, ["rev-parse", "--git-path", name])).trim())).then(() => true, () => false);
|
|
104
40
|
}
|
|
105
|
-
async function
|
|
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) {
|
|
41
|
+
export async function stackStatus(scope, github = gh) {
|
|
554
42
|
try {
|
|
555
|
-
|
|
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 });
|
|
43
|
+
await runStack(scope, ["--help"], github);
|
|
563
44
|
}
|
|
564
45
|
catch {
|
|
565
|
-
return;
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
const
|
|
46
|
+
return { available: false, conflicts: [], rebasing: false };
|
|
47
|
+
}
|
|
48
|
+
const conflicts = (await git(scope, ["diff", "--name-only", "--diff-filter=U", "-z"])).split("\0").filter(Boolean);
|
|
49
|
+
const stackRebase = await access(await commonGitPath(scope, "gh-stack-rebase-state")).then(() => true, () => false);
|
|
50
|
+
const rebasing = stackRebase && (await gitPathExists(scope, "rebase-merge") || await gitPathExists(scope, "rebase-apply"));
|
|
51
|
+
const status = { available: true, conflicts, rebasing };
|
|
52
|
+
if (rebasing)
|
|
53
|
+
return status;
|
|
54
|
+
if (stackRebase)
|
|
55
|
+
return { ...status, notice: otherWorktreeRebase };
|
|
56
|
+
const current = await head(scope);
|
|
57
|
+
if (!current.ok)
|
|
58
|
+
throw new Error(current.failure.message);
|
|
59
|
+
if (current.value.detached)
|
|
60
|
+
return { ...status, notice: "HEAD is detached. Switch to a branch to see its stack." };
|
|
61
|
+
const branch = current.value.name;
|
|
62
|
+
const [listed, stacks] = await Promise.all([localBranches(scope), localStacks(scope)]);
|
|
63
|
+
if (!listed.ok)
|
|
64
|
+
throw new Error(listed.failure.message);
|
|
65
|
+
if (!listed.value.includes(branch))
|
|
66
|
+
return { ...status, notice: "This branch has no commits yet. Commit first to create a stack." };
|
|
67
|
+
const trunkNotice = `${branch} is a trunk. Switch to another branch to create a stack.`;
|
|
68
|
+
if (stacks.some(stack => stack.trunk.branch === branch))
|
|
69
|
+
return { ...status, notice: trunkNotice };
|
|
570
70
|
try {
|
|
571
|
-
await
|
|
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);
|
|
71
|
+
return { ...status, view: await withTracking(scope, parseStack(await runStack(scope, ["view", "--json"], github))) };
|
|
582
72
|
}
|
|
583
73
|
catch (error) {
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
74
|
+
if (!notInStack.test(String(error)))
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
const trunk = (await localRepository(scope, branch))?.defaultBranches.find(name => listed.value.includes(name));
|
|
78
|
+
if (branch === trunk)
|
|
79
|
+
return { ...status, notice: trunkNotice };
|
|
80
|
+
const stacked = new Set(stacks.flatMap(stack => stack.branches.map(member => member.branch)));
|
|
81
|
+
return { ...status, create: { current: branch, ...(trunk ? { trunk } : {}), branches: listed.value, unstacked: listed.value.filter(name => !stacked.has(name)) } };
|
|
82
|
+
}
|
|
83
|
+
async function withTracking(scope, view) {
|
|
84
|
+
const tracking = new Map((await git(scope, ["for-each-ref", "--format=%(refname:short)%00%(upstream)%00%(upstream:track,nobracket)", "refs/heads"])).split("\n").map(line => line.split("\0")).map(([name, upstream, track]) => [name, upstream ? track ?? "" : undefined]));
|
|
85
|
+
for (const branch of view.branches) {
|
|
86
|
+
const track = tracking.get(branch.name);
|
|
87
|
+
if (track === undefined || track === "gone")
|
|
88
|
+
continue;
|
|
89
|
+
branch.ahead = Number(/ahead (\d+)/.exec(track)?.[1] ?? 0);
|
|
90
|
+
branch.behind = Number(/behind (\d+)/.exec(track)?.[1] ?? 0);
|
|
91
|
+
}
|
|
92
|
+
return view;
|
|
93
|
+
}
|
|
94
|
+
export async function stackMergeMethods(scope, view, github = gh) {
|
|
95
|
+
const [owner, name] = (await resolveRepository(scope, view.currentBranch, github)).base.repo.split("/");
|
|
96
|
+
const { repository } = await api(scope, github, `query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${mergeSettingsFields}}}`, { owner: owner, name: name });
|
|
97
|
+
return mergeMethods(repository);
|
|
98
|
+
}
|
|
99
|
+
const mergeFlags = { MERGE: "--merge", SQUASH: "--squash", REBASE: "--rebase" };
|
|
100
|
+
export async function mergeableStack(scope, github = gh) {
|
|
101
|
+
const { view, notice } = await stackStatus(scope, github);
|
|
102
|
+
if (!view)
|
|
103
|
+
throw new Error(notice ?? "This branch is not in a stack.");
|
|
104
|
+
await stackTitles(scope, view, github);
|
|
105
|
+
const block = stackMergeBlock(view);
|
|
106
|
+
if (block)
|
|
107
|
+
throw new Error(block);
|
|
108
|
+
return view;
|
|
109
|
+
}
|
|
110
|
+
const titles = new Map();
|
|
111
|
+
async function readTitles(scope, branch, numbers, github) {
|
|
112
|
+
const [owner, name] = (await resolveRepository(scope, branch, github)).base.repo.split("/");
|
|
113
|
+
const query = (list) => api(scope, github, `query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${list.map(number => `pr${number}:pullRequest(number:${number}){title isDraft}`).join(" ")}}}`, { owner: owner, name: name });
|
|
114
|
+
let wanted = numbers;
|
|
115
|
+
let data;
|
|
612
116
|
try {
|
|
613
|
-
|
|
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
|
-
}
|
|
117
|
+
data = await query(wanted);
|
|
633
118
|
}
|
|
634
119
|
catch (error) {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
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;
|
|
120
|
+
const missing = [...String(error).matchAll(/number of (\d+)/g)].map(match => Number(match[1]));
|
|
121
|
+
wanted = numbers.filter(number => !missing.includes(number));
|
|
122
|
+
if (!missing.length || !wanted.length)
|
|
123
|
+
throw error;
|
|
124
|
+
data = await query(wanted);
|
|
125
|
+
}
|
|
126
|
+
return new Map(wanted.flatMap(number => data.repository[`pr${number}`] ? [[number, data.repository[`pr${number}`]]] : []));
|
|
127
|
+
}
|
|
128
|
+
export async function stackTitles(scope, view, github = gh) {
|
|
129
|
+
for (const [cachedScope, entry] of titles)
|
|
130
|
+
if (entry.expires <= Date.now())
|
|
131
|
+
titles.delete(cachedScope);
|
|
132
|
+
const numbers = view.branches.flatMap(branch => branch.pr ? [branch.pr.number] : []);
|
|
133
|
+
if (!numbers.length)
|
|
134
|
+
return true;
|
|
135
|
+
const key = JSON.stringify(view.branches.map(branch => branch.pr && [branch.pr.number, branch.pr.state]));
|
|
136
|
+
const cached = titles.get(scope);
|
|
137
|
+
let found = cached?.key === key ? cached.found : undefined;
|
|
138
|
+
if (!found) {
|
|
139
|
+
found = await readTitles(scope, view.currentBranch, numbers, github).catch(() => new Map());
|
|
140
|
+
titles.set(scope, { key, expires: Date.now() + 5 * 60_000, found });
|
|
141
|
+
}
|
|
142
|
+
for (const branch of view.branches)
|
|
143
|
+
if (branch.pr && found.has(branch.pr.number))
|
|
144
|
+
Object.assign(branch.pr, found.get(branch.pr.number));
|
|
145
|
+
return numbers.every(number => found.has(number));
|
|
670
146
|
}
|
|
671
147
|
export async function cleanStack(scope) {
|
|
672
148
|
if ((await git(scope, ["status", "--porcelain=v1", "-z", "--untracked-files=all"])).length)
|
|
673
|
-
throw new Error("This Scope has uncommitted changes.
|
|
674
|
-
for (const operation of ["rebase-merge", "rebase-apply", "sequencer", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"
|
|
675
|
-
|
|
676
|
-
if (await access(resolve(scope, path)).then(() => true, () => false))
|
|
149
|
+
throw new Error("This Scope has uncommitted changes. Commit them first. Stack operations never stash changes.");
|
|
150
|
+
for (const operation of ["rebase-merge", "rebase-apply", "sequencer", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"]) {
|
|
151
|
+
if (await gitPathExists(scope, operation))
|
|
677
152
|
throw new Error("Finish or abort the current Git operation first.");
|
|
678
153
|
}
|
|
154
|
+
if (await access(await commonGitPath(scope, "gh-stack-rebase-state")).then(() => true, () => false))
|
|
155
|
+
throw new Error("A stack rebase is in progress in this or another worktree. Finish or abort it first.");
|
|
679
156
|
}
|
|
680
157
|
export async function stackFingerprint(scope, view, sync = false, github = gh) {
|
|
681
158
|
let membership;
|
|
@@ -696,26 +173,44 @@ export async function stackFingerprint(scope, view, sync = false, github = gh) {
|
|
|
696
173
|
const config = await git(scope, ["config", "--local", "--list"]);
|
|
697
174
|
return createHash("sha256").update(JSON.stringify({ view, refs, config, membership })).digest("hex");
|
|
698
175
|
}
|
|
176
|
+
async function validateInit(scope, trunk, branches, github) {
|
|
177
|
+
try {
|
|
178
|
+
await runStack(scope, ["--help"], github);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
throw new Error(install);
|
|
182
|
+
}
|
|
183
|
+
const listed = await localBranches(scope);
|
|
184
|
+
if (!listed.ok)
|
|
185
|
+
throw new Error(listed.failure.message);
|
|
186
|
+
if (typeof trunk !== "string" || !listed.value.includes(trunk))
|
|
187
|
+
throw new Error(`${String(trunk)} is not a local branch.`);
|
|
188
|
+
const stacked = new Set((await localStacks(scope)).flatMap(stack => stack.branches.map(member => member.branch)));
|
|
189
|
+
for (const [index, branch] of branches.entries()) {
|
|
190
|
+
if (!listed.value.includes(branch))
|
|
191
|
+
throw new Error(`${branch} is not a local branch.`);
|
|
192
|
+
if (branch === trunk)
|
|
193
|
+
throw new Error(`${branch} is the trunk. Choose it only as the trunk.`);
|
|
194
|
+
if (branches.indexOf(branch) !== index)
|
|
195
|
+
throw new Error(`${branch} is listed twice.`);
|
|
196
|
+
if (stacked.has(branch))
|
|
197
|
+
throw new Error(`${branch} is already in a stack.`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
699
200
|
export async function changeStack(scope, input, github = gh) {
|
|
700
201
|
const { action } = input;
|
|
701
|
-
if (!["init", "add", "checkout", "rebase", "continue", "abort", "submit", "sync"].includes(action))
|
|
202
|
+
if (!["init", "add", "checkout", "rebase", "continue", "abort", "submit", "sync", "merge"].includes(action))
|
|
702
203
|
throw new Error("Unknown Stack action.");
|
|
703
204
|
if (action === "continue" || action === "abort") {
|
|
704
|
-
const state = await
|
|
205
|
+
const state = await stackStatus(scope, github);
|
|
705
206
|
if (!state.rebasing)
|
|
706
|
-
throw new Error("No Stack rebase is in progress.");
|
|
207
|
+
throw new Error(state.notice === otherWorktreeRebase ? otherWorktreeRebase : "No Stack rebase is in progress.");
|
|
707
208
|
if (action === "continue" && state.conflicts.length)
|
|
708
209
|
throw new Error("Resolve and stage all conflict files before continuing.");
|
|
709
210
|
}
|
|
710
211
|
else
|
|
711
212
|
await cleanStack(scope);
|
|
712
|
-
const args = [
|
|
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
|
-
}
|
|
213
|
+
const args = [action];
|
|
719
214
|
if (action === "init" || action === "add" || action === "checkout") {
|
|
720
215
|
if (!Array.isArray(input.branches) || !input.branches.length || (action !== "init" && input.branches.length !== 1))
|
|
721
216
|
throw new Error("Enter a branch name.");
|
|
@@ -724,8 +219,12 @@ export async function changeStack(scope, input, github = gh) {
|
|
|
724
219
|
throw new Error("Invalid branch name.");
|
|
725
220
|
await git(scope, ["check-ref-format", "--branch", branch]);
|
|
726
221
|
}
|
|
222
|
+
if (action === "init") {
|
|
223
|
+
await validateInit(scope, input.trunk, input.branches, github);
|
|
224
|
+
args.push("--base", input.trunk);
|
|
225
|
+
}
|
|
727
226
|
if (action === "checkout") {
|
|
728
|
-
const state = await
|
|
227
|
+
const state = await stackStatus(scope, github);
|
|
729
228
|
const branch = input.branches[0];
|
|
730
229
|
if (!state.view?.branches.some(b => b.name === branch))
|
|
731
230
|
throw new Error("Choose a branch in the current local stack.");
|
|
@@ -735,9 +234,15 @@ export async function changeStack(scope, input, github = gh) {
|
|
|
735
234
|
args.push(...input.branches);
|
|
736
235
|
}
|
|
737
236
|
if (action === "continue" || action === "abort")
|
|
738
|
-
args.splice(
|
|
237
|
+
args.splice(0, 1, "rebase", `--${action}`);
|
|
739
238
|
if (action === "submit")
|
|
740
239
|
args.push("--auto");
|
|
741
|
-
|
|
240
|
+
if (action === "merge") {
|
|
241
|
+
if (!input.method || !Object.hasOwn(mergeFlags, input.method))
|
|
242
|
+
throw new Error("Invalid merge method.");
|
|
243
|
+
await mergeableStack(scope, github);
|
|
244
|
+
args.push("--yes", mergeFlags[input.method]);
|
|
245
|
+
}
|
|
246
|
+
return runStack(scope, args, github);
|
|
742
247
|
}
|
|
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,
|
|
248
|
+
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, submit, sync, merge, or restructure the stack. Report the result so I can review it before any separate Sync confirmation.";
|