@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,317 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join } from "node:path";
4
+ // The `.git` test now answers two questions and gives the same answer to both, so it lives with
5
+ // the rest of git (`src/daemon/git.ts`). The rule about a repository being a *leaf* stays here,
6
+ // because it is about this walk rather than about git.
7
+ import { isRepository } from "./git.js";
8
+ /**
9
+ * Finding directories: the Projects that are opted in, the repositories worth suggesting, and the
10
+ * two searches that help someone opt in.
11
+ *
12
+ * **`projects.include` is the Projects list.** `includedProjects` resolves it, and nothing else
13
+ * here produces a Project a client will offer. Everything else exists to make that list easy to
14
+ * write (ADR 0011).
15
+ *
16
+ * `discoverProjects` supplies *candidates*: a directory holding a `.git` beneath the Project Root,
17
+ * with the folders above it as a heading. A repository is a **leaf** — recorded, never looked
18
+ * inside — which prunes `node_modules` and build output without a name blacklist. Its cost is that
19
+ * a monorepo suggests only itself, and `searchDirectories` is the answer to that: it deliberately
20
+ * does *not* stop at repositories, so `<root>/monorepo/packages/api` can be found and opted in.
21
+ * That is the one place a blacklist is unavoidable, and `NEVER_OFFERED` is it.
22
+ *
23
+ * Nothing here throws, and nothing follows a symlink. A directory that is absent or unreadable
24
+ * contributes nothing: a mistyped Project Root yields no candidates, which the Settings page reports
25
+ * as a count — more use to its reader than an error on a save they already committed to.
26
+ */
27
+ /** How far below the Project Root a Project may sit. `<root>/kind/team/repo` is the deepest. */
28
+ export const MAX_DEPTH = 3;
29
+ /**
30
+ * How many directories one walk may look at.
31
+ *
32
+ * A backstop against a Project Root of `/`, which `MAX_DEPTH` alone does not bound usefully — three
33
+ * levels below the filesystem root is tens of thousands of directories. This is what makes the
34
+ * synchronous `fs` below safe rather than merely conventional: the walk runs inside a request
35
+ * handler, so its cost has to be bounded by something other than good intentions.
36
+ */
37
+ export const MAX_VISITS = 2000;
38
+ /**
39
+ * `~/workspace` as an absolute path.
40
+ *
41
+ * The Project Root is stored and reported as the string a person typed — the same round trip a
42
+ * duration makes (src/protocol/settings.ts) — so the tilde survives into config.json and back into
43
+ * the Settings page, and is resolved only here, at the point of use.
44
+ */
45
+ export function expandHome(path) {
46
+ if (path === "~")
47
+ return homedir();
48
+ if (path.startsWith("~/"))
49
+ return join(homedir(), path.slice(2));
50
+ return path;
51
+ }
52
+ /**
53
+ * Every Project beneath `root`, sorted by group and then by name.
54
+ *
55
+ * Sorted because `readdirSync` order is not guaranteed, and a dropdown that reshuffles between page
56
+ * loads is a bug rather than a cosmetic complaint.
57
+ */
58
+ export function discoverProjects(root) {
59
+ if (root === undefined)
60
+ return [];
61
+ const absolute = expandHome(root);
62
+ if (!isAbsolute(absolute))
63
+ return [];
64
+ if (!isDirectory(absolute))
65
+ return [];
66
+ const found = [];
67
+ // A budget rather than a counter per level: the pathological tree is wide, not deep.
68
+ const budget = { left: MAX_VISITS };
69
+ // A Project Root that is itself a repository is the one Project it offers. Without this, pointing
70
+ // the root at a single checkout reports nothing at all — every repository beneath it is inside
71
+ // it, and so is never visited.
72
+ if (isRepository(absolute)) {
73
+ return [{ path: absolute, name: basename(absolute) }];
74
+ }
75
+ descend(absolute, undefined, 1, found, budget);
76
+ return found.sort((left, right) => (left.group ?? "").localeCompare(right.group ?? "") || left.name.localeCompare(right.name));
77
+ }
78
+ function descend(directory, group, depth, found, budget) {
79
+ if (depth > MAX_DEPTH || budget.left <= 0)
80
+ return;
81
+ let entries;
82
+ try {
83
+ entries = readdirSync(directory, { withFileTypes: true });
84
+ }
85
+ catch {
86
+ // Unreadable — a directory this user cannot enter is not an error worth failing a page load
87
+ // over, and there is nothing useful to say about it.
88
+ return;
89
+ }
90
+ for (const entry of entries) {
91
+ if (budget.left <= 0)
92
+ return;
93
+ // `isDirectory()` is false for a symlink, which is how a symlink loop is refused: following one
94
+ // is the only way this walk could fail to terminate.
95
+ if (!entry.isDirectory())
96
+ continue;
97
+ // A dotted directory is infrastructure, not a Project — `.git`, `.cache`, `.config`.
98
+ if (entry.name.startsWith("."))
99
+ continue;
100
+ budget.left -= 1;
101
+ const path = join(directory, entry.name);
102
+ if (isRepository(path)) {
103
+ found.push({ path, name: entry.name, ...(group === undefined ? {} : { group }) });
104
+ // Deliberately not descending. See the header: this is the whole pruning rule.
105
+ continue;
106
+ }
107
+ descend(path, group === undefined ? entry.name : `${group}/${entry.name}`, depth + 1, found, budget);
108
+ }
109
+ }
110
+ function isDirectory(path) {
111
+ return statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false;
112
+ }
113
+ /** The last segment, without pulling in `node:path`'s trailing-slash behaviour. */
114
+ function basename(path) {
115
+ const segments = path.split("/").filter((segment) => segment !== "");
116
+ return segments[segments.length - 1] ?? path;
117
+ }
118
+ /**
119
+ * The opted-in Projects, in the order they were configured.
120
+ *
121
+ * Configured order, deliberately not sorted: this list was curated by hand, so its order is a
122
+ * decision someone made and re-alphabetising it would overrule them. That is the opposite of
123
+ * `discoverProjects`, which sorts because `readdirSync` order is arbitrary and nobody chose it.
124
+ *
125
+ * An entry may be relative or absolute. Relative resolves against the Project Root, which is what
126
+ * makes a hand-written `["work/api", "e2e"]` read well and survive the root being moved; absolute
127
+ * is how a Project outside the root is named at all. A missing directory is reported rather than
128
+ * dropped — see `Project.missing`.
129
+ */
130
+ export function includedProjects(root, include) {
131
+ const base = root === undefined ? undefined : expandHome(root);
132
+ const seen = new Set();
133
+ const projects = [];
134
+ for (const entry of include) {
135
+ const path = resolveEntry(base, entry);
136
+ // A duplicate is a no-op rather than a second row. The Settings page will not create one, but a
137
+ // hand-edited file can, and two identical rows in a dropdown is not a useful thing to render.
138
+ if (path === undefined || seen.has(path))
139
+ continue;
140
+ seen.add(path);
141
+ projects.push({
142
+ path,
143
+ name: basename(path),
144
+ ...groupOf(base, path),
145
+ ...(isDirectory(path) ? {} : { missing: true }),
146
+ });
147
+ }
148
+ return projects;
149
+ }
150
+ /** An entry as an absolute path, or undefined if it cannot be made into one. */
151
+ function resolveEntry(base, entry) {
152
+ const trimmed = entry.trim();
153
+ if (trimmed === "")
154
+ return undefined;
155
+ const expanded = expandHome(trimmed);
156
+ if (isAbsolute(expanded))
157
+ return normalisePath(expanded);
158
+ // Relative, so it needs a root to be relative *to*. Without one it names nothing.
159
+ if (base === undefined)
160
+ return undefined;
161
+ return normalisePath(join(base, expanded));
162
+ }
163
+ /**
164
+ * The heading an opted-in Project sits under: the folders between the Project Root and it.
165
+ *
166
+ * Derived from the path rather than stored, so it agrees with what `discoverProjects` produces for
167
+ * the same directory. A Project outside the root gets none — there is nothing to be relative to,
168
+ * and inventing "elsewhere" would name a folder nobody made.
169
+ */
170
+ function groupOf(base, path) {
171
+ if (base === undefined)
172
+ return {};
173
+ const prefix = `${normalisePath(base)}/`;
174
+ if (!path.startsWith(prefix))
175
+ return {};
176
+ const segments = path.slice(prefix.length).split("/");
177
+ segments.pop();
178
+ return segments.length === 0 ? {} : { group: segments.join("/") };
179
+ }
180
+ /** Trailing slashes and `.` segments removed, so two spellings of one directory compare equal. */
181
+ function normalisePath(path) {
182
+ const cleaned = path.replace(/\/+$/, "").replace(/\/\.(?=\/|$)/g, "");
183
+ return cleaned === "" ? "/" : cleaned;
184
+ }
185
+ /**
186
+ * How many matches one search answers with before it says "keep typing".
187
+ *
188
+ * A cap rather than a page: this feeds a dropdown someone is typing into, and the answer to "too
189
+ * many matches" is a narrower query, not a second request.
190
+ */
191
+ export const MAX_MATCHES = 40;
192
+ /**
193
+ * How deep a *search* goes, as opposed to a Project walk.
194
+ *
195
+ * Deeper than `MAX_DEPTH` because this one does not stop at repositories, and the directory most
196
+ * worth finding this way is the one a Project walk refuses to offer — `monorepo/packages/api`,
197
+ * which is already three levels down before the interesting part.
198
+ */
199
+ export const MAX_SEARCH_DEPTH = 5;
200
+ /**
201
+ * Directory names never worth offering, and the reason this list has to exist at all.
202
+ *
203
+ * `discoverProjects` needs no blacklist because stopping at a repository prunes everything inside
204
+ * it. A search deliberately does not stop there — reaching inside a monorepo is the point — so the
205
+ * pruning has to be done by name after all. Kept deliberately short: these are the directories that
206
+ * are *machine* output in every ecosystem, not merely uninteresting ones.
207
+ */
208
+ const NEVER_OFFERED = new Set([
209
+ "node_modules",
210
+ "dist",
211
+ "build",
212
+ "out",
213
+ "target",
214
+ "vendor",
215
+ "coverage",
216
+ "__pycache__",
217
+ ]);
218
+ /**
219
+ * Directories matching `query`, as either a completion or a search.
220
+ *
221
+ * The first character decides which (see `DirectoryMatches`): `/` or `~` means the reader is typing
222
+ * a path and wants its siblings; anything else means they are naming a directory and want it found.
223
+ * A completion reaches the whole machine, which is not a privilege escalation — ADR 0004 already
224
+ * has it that anything able to reach this daemon can run commands as its user — but it is a
225
+ * filesystem the caller can enumerate, so it is worth saying out loud.
226
+ */
227
+ export function searchDirectories(root, query) {
228
+ const trimmed = query.trim();
229
+ if (trimmed.startsWith("/") || trimmed.startsWith("~")) {
230
+ return complete(trimmed);
231
+ }
232
+ return search(root, trimmed);
233
+ }
234
+ /**
235
+ * Path completion: the child directories of the deepest ancestor that exists.
236
+ *
237
+ * One `readdirSync` and no walking at all, which is what makes reaching the whole machine cheap
238
+ * enough to do on a keystroke. `/home/node/wo` lists `/home/node`'s children beginning "wo";
239
+ * `/home/node/` lists all of them.
240
+ */
241
+ function complete(query) {
242
+ const expanded = expandHome(query);
243
+ const cut = expanded.lastIndexOf("/");
244
+ // No slash cannot happen — the caller only routes here for a leading `/` or `~`, and `~` expands
245
+ // to an absolute path — but the parent has to come from somewhere, so this is not left implicit.
246
+ const parent = cut <= 0 ? "/" : expanded.slice(0, cut);
247
+ const fragment = expanded.slice(cut + 1).toLowerCase();
248
+ const names = childDirectories(parent)
249
+ .filter((name) => name.toLowerCase().startsWith(fragment))
250
+ .sort((left, right) => left.localeCompare(right));
251
+ return {
252
+ query,
253
+ kind: "completion",
254
+ paths: names.slice(0, MAX_MATCHES).map((name) => join(parent, name)),
255
+ ...(names.length > MAX_MATCHES ? { truncated: true } : {}),
256
+ };
257
+ }
258
+ /**
259
+ * Fuzzy search beneath the Project Root, repositories included rather than stopped at.
260
+ *
261
+ * What a query is matched against depends on whether it contains a slash, because the two spellings
262
+ * mean different things. `api` is a *name*, and matching it against the relative path would drag in
263
+ * every descendant of a hit — `work/api/packages` contains "api" only by inheritance, which is
264
+ * noise. `work/api` is a *subtree*, and there matching the whole relative path is exactly right,
265
+ * descendants included.
266
+ *
267
+ * Ranked shallowest-first: a directory nearer the root is more likely to be the one meant, and depth
268
+ * is the only signal available that does not require guessing at intent.
269
+ */
270
+ function search(root, query) {
271
+ if (root === undefined || query === "")
272
+ return { query, kind: "search", paths: [] };
273
+ const base = expandHome(root);
274
+ if (!isAbsolute(base) || !isDirectory(base))
275
+ return { query, kind: "search", paths: [] };
276
+ const needle = query.toLowerCase();
277
+ // A slash makes the query a subtree rather than a name — see the note above.
278
+ const againstPath = needle.includes("/");
279
+ const matches = [];
280
+ const budget = { left: MAX_VISITS };
281
+ const walk = (directory, relative, depth) => {
282
+ if (depth > MAX_SEARCH_DEPTH || budget.left <= 0)
283
+ return;
284
+ for (const name of childDirectories(directory)) {
285
+ if (budget.left <= 0)
286
+ return;
287
+ if (name.startsWith(".") || NEVER_OFFERED.has(name))
288
+ continue;
289
+ budget.left -= 1;
290
+ const path = join(directory, name);
291
+ const nextRelative = relative === "" ? name : `${relative}/${name}`;
292
+ const against = againstPath ? nextRelative : name;
293
+ if (against.toLowerCase().includes(needle))
294
+ matches.push({ path, depth });
295
+ walk(path, nextRelative, depth + 1);
296
+ }
297
+ };
298
+ walk(base, "", 1);
299
+ matches.sort((left, right) => left.depth - right.depth || left.path.localeCompare(right.path));
300
+ return {
301
+ query,
302
+ kind: "search",
303
+ paths: matches.slice(0, MAX_MATCHES).map((match) => match.path),
304
+ ...(matches.length > MAX_MATCHES ? { truncated: true } : {}),
305
+ };
306
+ }
307
+ /** The directory names directly inside `path`. Unreadable or absent contributes nothing. */
308
+ function childDirectories(path) {
309
+ try {
310
+ return readdirSync(path, { withFileTypes: true })
311
+ .filter((entry) => entry.isDirectory())
312
+ .map((entry) => entry.name);
313
+ }
314
+ catch {
315
+ return [];
316
+ }
317
+ }
@@ -0,0 +1,289 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { lstat, readlink, access } from "node:fs/promises";
4
+ import { createReadStream } from "node:fs";
5
+ import { resolve } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { head, isRepository, run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
8
+ import { localStack, localStacks } from "./stack-metadata.js";
9
+ const exec = promisify(execFile);
10
+ export const gh = async (scope, args) => {
11
+ try {
12
+ return (await exec("gh", args, {
13
+ cwd: scope,
14
+ timeout: GIT_WRITE_TIMEOUT_MS,
15
+ maxBuffer: 2 << 20,
16
+ env: { ...process.env, GH_PROMPT_DISABLED: "1", GIT_TERMINAL_PROMPT: "0", ...(args[0] === "stack" ? { GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" } : {}) },
17
+ })).stdout;
18
+ }
19
+ catch (error) {
20
+ const failure = error;
21
+ if (failure.code === "ENOENT")
22
+ throw new Error("GitHub CLI is missing. Install gh on the Session Host.");
23
+ const detail = (args[0] === "stack" ? [failure.stdout, failure.stderr].filter(Boolean).join("\n").trim() : failure.stderr?.trim()) || failure.message || "Unknown error";
24
+ const requestFailed = /HTTP (?:429|5\d\d)|connection|timed? out|network|TLS|certificate|could not resolve/i.test(detail);
25
+ if ((failure.code === 4 && args[0] !== "stack") || (args[0] === "auth" && !requestFailed)) {
26
+ throw new Error(`GitHub authentication failed. Run gh auth login on the Session Host. ${detail}`);
27
+ }
28
+ throw new Error(`GitHub request failed: ${detail}`);
29
+ }
30
+ };
31
+ async function git(scope, args, write = false) {
32
+ const result = await run(scope, args, write ? GIT_WRITE_TIMEOUT_MS : GIT_READ_TIMEOUT_MS);
33
+ if (!result.ok) {
34
+ if (result.failure.message.includes("ENOENT"))
35
+ throw new Error("Git is missing. Install git on the Session Host.");
36
+ throw new Error(`Git ${result.failure.attempted} failed: ${result.failure.message}`);
37
+ }
38
+ return result.value;
39
+ }
40
+ async function files(scope) {
41
+ const raw = await git(scope, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]);
42
+ return raw.split("\0").filter(Boolean).map((line) => ({ status: line.slice(0, 2), path: line.slice(3) }));
43
+ }
44
+ export async function snapshot(scope) {
45
+ if (!isRepository(scope))
46
+ throw new Error("This Scope is not a Git repository.");
47
+ const branch = await head(scope);
48
+ if (!branch.ok)
49
+ throw new Error(branch.failure.message.includes("ENOENT") ? "Git is missing. Install git on the Session Host." : branch.failure.message);
50
+ if (branch.value.detached)
51
+ throw new Error("HEAD is detached. Switch to a branch before publishing.");
52
+ const commit = await run(scope, ["rev-parse", "--verify", "HEAD"], GIT_READ_TIMEOUT_MS);
53
+ if (!commit.ok)
54
+ throw new Error("This branch has no commits. Make the first commit before publishing.");
55
+ const changed = await files(scope);
56
+ if (changed.some((file) => file.status.includes("U") || ["AA", "DD"].includes(file.status))) {
57
+ throw new Error("Resolve merge conflicts before publishing.");
58
+ }
59
+ const index = await git(scope, ["ls-files", "--stage", "-z"]);
60
+ if (index.split("\0").some((entry) => entry.startsWith("160000 "))) {
61
+ throw new Error("Publishing repositories with submodules is not supported. Use Git directly.");
62
+ }
63
+ for (const operation of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"]) {
64
+ const active = await run(scope, ["rev-parse", "--verify", "-q", operation], GIT_READ_TIMEOUT_MS);
65
+ if (active.ok)
66
+ throw new Error("Finish the current Git operation before publishing.");
67
+ }
68
+ for (const operation of ["rebase-merge", "rebase-apply", "sequencer"]) {
69
+ const path = (await git(scope, ["rev-parse", "--git-path", operation])).trim();
70
+ const active = await access(resolve(scope, path)).then(() => true, () => false);
71
+ if (active)
72
+ throw new Error("Finish the current Git operation before publishing.");
73
+ }
74
+ const staged = await git(scope, ["diff", "--cached", "--binary", "--no-ext-diff", "--no-textconv"]);
75
+ const working = await git(scope, ["diff", "--binary", "--no-ext-diff", "--no-textconv"]);
76
+ const content = createHash("sha256");
77
+ let untracked = "";
78
+ for (const file of [...changed].sort((a, b) => a.path.localeCompare(b.path))) {
79
+ const path = resolve(scope, file.path);
80
+ const stat = await lstat(path).catch((error) => {
81
+ if (error.code === "ENOENT" || error.code === "ENOTDIR")
82
+ return undefined;
83
+ throw error;
84
+ });
85
+ content.update(JSON.stringify({ path: file.path, mode: stat?.mode, size: stat?.size }));
86
+ if (!stat)
87
+ continue;
88
+ if (!stat.isFile() && !stat.isSymbolicLink())
89
+ throw new Error(`Cannot publish this file type: ${file.path}`);
90
+ if (stat.isSymbolicLink())
91
+ content.update(await readlink(path));
92
+ else {
93
+ let preview = "";
94
+ for await (const chunk of createReadStream(path)) {
95
+ content.update(chunk);
96
+ if (file.status === "??" && preview.length < 4_000 && untracked.length < 8_000)
97
+ preview += chunk.toString("utf8").slice(0, 4_000 - preview.length);
98
+ }
99
+ if (preview && !preview.includes("\0"))
100
+ untracked += `\nUntracked ${JSON.stringify(file.path)}:\n${preview}`.slice(0, 8_000 - untracked.length);
101
+ }
102
+ }
103
+ const contentFingerprint = content.digest("hex");
104
+ const fingerprint = createHash("sha256").update(JSON.stringify({ commit: commit.value, changed, index, staged, working, contentFingerprint })).digest("hex");
105
+ return {
106
+ fingerprint, contentFingerprint, unstaged: working !== "", files: changed, branch: branch.value.name, commit: commit.value.trim(),
107
+ input: `${JSON.stringify(changed)}\n${staged}\n${working}\n${untracked}`,
108
+ };
109
+ }
110
+ export async function repositoryTarget(scope, github = gh) {
111
+ const remotes = (await git(scope, ["remote"])).trim().split("\n").filter(Boolean);
112
+ if (remotes.length === 0)
113
+ throw new Error("No remote is configured. Add a GitHub remote before publishing.");
114
+ if (remotes.length !== 1)
115
+ throw new Error("Publish requires exactly one remote. Select and publish the remote with Git directly.");
116
+ const remote = remotes[0];
117
+ const urls = (await git(scope, ["remote", "get-url", "--all", remote])).trim().split("\n");
118
+ const pushes = (await git(scope, ["remote", "get-url", "--push", "--all", remote])).trim().split("\n");
119
+ if (urls.length !== 1 || pushes.length !== 1 || pushes[0] !== urls[0]) {
120
+ throw new Error("Fetch and push remotes differ or are ambiguous. Publish with Git directly.");
121
+ }
122
+ const url = urls[0];
123
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(url);
124
+ if (!match)
125
+ throw new Error("This remote is not a supported github.com repository URL.");
126
+ const repo = match[1];
127
+ await github(scope, ["auth", "status", "--hostname", "github.com"]);
128
+ const info = JSON.parse(await github(scope, ["repo", "view", repo, "--json", "id,defaultBranchRef,isFork"]));
129
+ if (info.isFork)
130
+ throw new Error("Fork publishing is not supported. Publish with gh directly to select the base repository.");
131
+ if (!info.defaultBranchRef?.name)
132
+ throw new Error("GitHub has no default branch. Create it before publishing.");
133
+ return { remote, url, repo, defaultBranch: info.defaultBranchRef.name, id: info.id };
134
+ }
135
+ export async function target(scope, branch, github = gh) {
136
+ const { remote, url, repo, defaultBranch, id } = await repositoryTarget(scope, github);
137
+ const prs = JSON.parse(await github(scope, ["pr", "list", "--repo", repo, "--head", branch, "--state", "open", "--json", "number,url,title,isDraft,reviewDecision,statusCheckRollup,headRepository"]));
138
+ if (prs.length > 1)
139
+ throw new Error("More than one pull request matches this branch. Publish with gh directly.");
140
+ const pr = prs[0];
141
+ if (pr && branch === defaultBranch)
142
+ throw new Error("The default branch already heads a pull request. Publish with gh directly to select the intended branch.");
143
+ if (pr)
144
+ pr.statusCheckRollup ??= [];
145
+ if (pr && (!id || !pr.headRepository?.id)) {
146
+ throw new Error("Cannot verify PR source: GitHub did not return repository IDs. Publish with gh directly.");
147
+ }
148
+ if (pr && pr.headRepository?.id !== id) {
149
+ throw new Error("The pull request uses a different head repository. Publish with gh directly.");
150
+ }
151
+ const stack = await localStack(scope, branch);
152
+ let baseBranch;
153
+ if (stack) {
154
+ try {
155
+ await github(scope, ["stack", "--help"]);
156
+ }
157
+ catch (error) {
158
+ throw new Error(`This branch belongs to a stack. Install gh stack on the Session Host before publishing. ${error instanceof Error ? error.message : String(error)}`);
159
+ }
160
+ const index = stack.branches.findIndex(b => b.branch === branch);
161
+ baseBranch = stack.branches.slice(0, index).filter(b => !b.pullRequest?.merged).at(-1)?.branch ?? stack.trunk.branch;
162
+ }
163
+ return { remote, url, repo, defaultBranch, ...(baseBranch ? { baseBranch } : {}), ...(pr ? { pr } : {}) };
164
+ }
165
+ async function remoteBranchExists(scope, destination, branch, github) {
166
+ const refs = JSON.parse(await github(scope, ["api", `repos/${destination.repo}/git/matching-refs/heads/${branch.split("/").map(encodeURIComponent).join("/")}`]));
167
+ return refs.some(ref => ref.ref === `refs/heads/${branch}`);
168
+ }
169
+ export async function canNameBranch(scope, branch, destination, github = gh) {
170
+ if (branch === destination.defaultBranch)
171
+ return true;
172
+ if (destination.pr || (await localStacks(scope)).some(stack => stack.trunk.branch === branch || stack.branches.some(item => item.branch === branch)))
173
+ return false;
174
+ const tracked = await run(scope, ["show-ref", "--verify", "--quiet", `refs/remotes/${destination.remote}/${branch}`], GIT_READ_TIMEOUT_MS);
175
+ if (tracked.ok || await remoteBranchExists(scope, destination, branch, github))
176
+ return false;
177
+ const prs = JSON.parse(await github(scope, ["pr", "list", "--repo", destination.repo, "--head", branch, "--state", "all", "--json", "number"]));
178
+ return prs.length === 0;
179
+ }
180
+ export async function branchChanges(scope, destination) {
181
+ let base = destination.baseBranch ? `refs/heads/${destination.baseBranch}` : `refs/remotes/${destination.remote}/${destination.defaultBranch}`;
182
+ const remote = await run(scope, ["rev-parse", "--verify", base], GIT_READ_TIMEOUT_MS);
183
+ if (!remote.ok)
184
+ base = destination.baseBranch ? `refs/remotes/${destination.remote}/${destination.baseBranch}` : `refs/heads/${destination.defaultBranch}`;
185
+ const known = await run(scope, ["rev-parse", "--verify", base], GIT_READ_TIMEOUT_MS);
186
+ if (!known.ok)
187
+ throw new Error(`Fetch the ${destination.baseBranch ? "stack parent" : "default"} branch before publishing so its changes can be reviewed.`);
188
+ const range = `${base}...HEAD`;
189
+ const raw = (await git(scope, ["diff", "--name-status", "-z", "--no-renames", range, "--"])).split("\0").filter(Boolean);
190
+ const files = [];
191
+ for (let index = 0; index < raw.length; index += 2)
192
+ files.push({ status: raw[index], path: raw[index + 1] });
193
+ const commits = (await git(scope, ["log", "--format=%h %s", `${base}..HEAD`, "--"])).trim().split("\n").filter(Boolean);
194
+ const diff = await git(scope, ["diff", "--binary", "--no-ext-diff", "--no-textconv", range, "--"]);
195
+ return { files, commits, input: `${commits.join("\n")}\n${diff}` };
196
+ }
197
+ export async function gitStatus(scope, github = gh) {
198
+ if (!isRepository(scope))
199
+ return { repository: false, files: [] };
200
+ const status = { repository: true, files: [] };
201
+ try {
202
+ status.files = await files(scope);
203
+ const branch = await head(scope);
204
+ if (!branch.ok)
205
+ throw new Error(branch.failure.message);
206
+ status.branch = branch.value;
207
+ if (branch.value.detached)
208
+ throw new Error("HEAD is detached. Switch to a branch before publishing.");
209
+ const destination = await target(scope, branch.value.name, github);
210
+ if (destination.pr)
211
+ status.pr = destination.pr;
212
+ }
213
+ catch (error) {
214
+ status.problem = error instanceof Error ? error.message : String(error);
215
+ }
216
+ return status;
217
+ }
218
+ export async function publish(scope, reviewed, destination, input, github = gh) {
219
+ const result = { pushed: false };
220
+ try {
221
+ const current = await snapshot(scope);
222
+ if (current.branch !== reviewed.branch || current.fingerprint !== reviewed.fingerprint)
223
+ throw new Error("Reviewed changes have changed. Open Publish again.");
224
+ const freshTarget = await target(scope, current.branch, github);
225
+ if (freshTarget.remote !== destination.remote || freshTarget.url !== destination.url || freshTarget.repo !== destination.repo || freshTarget.defaultBranch !== destination.defaultBranch || freshTarget.baseBranch !== destination.baseBranch || freshTarget.pr?.number !== destination.pr?.number)
226
+ throw new Error("The remote, base branch, or pull request has changed. Open Publish again.");
227
+ if (typeof input.commitMessage !== "string" || typeof input.title !== "string" || typeof input.body !== "string" || !input.title.trim() || (current.files.length > 0 && !input.commitMessage.trim())) {
228
+ throw new Error("A commit message and pull request title are required.");
229
+ }
230
+ const checked = await snapshot(scope);
231
+ if (checked.branch !== current.branch || checked.fingerprint !== current.fingerprint)
232
+ throw new Error("Reviewed changes have changed. Open Publish again.");
233
+ let branch = current.branch;
234
+ const requestedBranch = typeof input.branch === "string" ? input.branch.trim() : "";
235
+ const creating = branch === destination.defaultBranch;
236
+ if (creating || (requestedBranch && requestedBranch !== branch)) {
237
+ if (!requestedBranch || requestedBranch.startsWith("-") || requestedBranch === destination.defaultBranch || requestedBranch.includes("@{")) {
238
+ throw new Error("Enter a valid new feature branch name before publishing.");
239
+ }
240
+ if (!await canNameBranch(scope, branch, freshTarget, github))
241
+ throw new Error("This branch has a pull request, remote ref, or stack registration and cannot be renamed.");
242
+ await git(scope, ["check-ref-format", "--branch", requestedBranch]);
243
+ const local = await run(scope, ["show-ref", "--verify", "--quiet", `refs/heads/${requestedBranch}`], GIT_READ_TIMEOUT_MS);
244
+ if (local.ok)
245
+ throw new Error("That feature branch already exists locally. Choose a new branch name.");
246
+ if (await remoteBranchExists(scope, destination, requestedBranch, github))
247
+ throw new Error("That feature branch already exists on GitHub. Choose a new branch name or switch to the existing branch before publishing.");
248
+ const beforeSwitch = await snapshot(scope);
249
+ if (beforeSwitch.branch !== reviewed.branch || beforeSwitch.fingerprint !== reviewed.fingerprint)
250
+ throw new Error("Reviewed changes have changed. Open Publish again.");
251
+ await git(scope, creating ? ["switch", "-c", requestedBranch] : ["branch", "-m", requestedBranch], true);
252
+ branch = requestedBranch;
253
+ result.branch = branch;
254
+ const afterSwitch = await snapshot(scope);
255
+ if (afterSwitch.branch !== branch || afterSwitch.fingerprint !== reviewed.fingerprint) {
256
+ throw new Error(`The branch was ${creating ? "created" : "renamed"}, but its changes differ after checkout hooks. Open Publish again.`);
257
+ }
258
+ }
259
+ if (current.files.length > 0) {
260
+ await git(scope, ["add", "--all", "--", "."], true);
261
+ const tree = (await git(scope, ["write-tree"])).trim();
262
+ const staged = await snapshot(scope);
263
+ if (staged.unstaged || staged.contentFingerprint !== reviewed.contentFingerprint || staged.branch !== branch || staged.commit !== reviewed.commit)
264
+ throw new Error("Changes moved while staging. Review the index and open Publish again.");
265
+ await git(scope, ["commit", "-m", input.commitMessage], true);
266
+ result.committed = (await git(scope, ["rev-parse", "HEAD"])).trim();
267
+ if ((await git(scope, ["rev-parse", `${result.committed}^{tree}`])).trim() !== tree)
268
+ throw new Error("Commit hooks changed the committed files. Review the commit before pushing.");
269
+ if ((await git(scope, ["show", "--no-patch", "--format=%P", result.committed])).trim() !== reviewed.commit)
270
+ throw new Error("The commit parents changed. Review the commit before pushing.");
271
+ if ((await files(scope)).length > 0)
272
+ throw new Error("Commit completed, but hooks or another process left changes. Review them before pushing.");
273
+ }
274
+ const finalHead = await head(scope);
275
+ if (!finalHead.ok || finalHead.value.detached || finalHead.value.name !== branch)
276
+ throw new Error("The branch changed before pushing. Open Publish again.");
277
+ await git(scope, ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "push", "--no-follow-tags", destination.url, `${result.committed ?? reviewed.commit}:refs/heads/${branch}`], true);
278
+ result.pushed = true;
279
+ if (destination.pr)
280
+ result.url = destination.pr.url;
281
+ else {
282
+ result.url = (await github(scope, ["pr", "create", "--repo", destination.repo, "--base", destination.baseBranch ?? destination.defaultBranch, "--head", branch, "--title", input.title, "--body", input.body, ...(input.ready === true ? [] : ["--draft"])])).trim();
283
+ }
284
+ }
285
+ catch (error) {
286
+ result.error = error instanceof Error ? error.message : String(error);
287
+ }
288
+ return result;
289
+ }