send-to-paseo 1.3.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.
package/server/git.ts ADDED
@@ -0,0 +1,298 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { isAbsolute, join, resolve as resolvePath } from "node:path";
3
+ import { INSTALL_HINT, findGit, runProcess } from "./deps";
4
+ import { BridgeError } from "../shared/contracts";
5
+ import { setBoundedCache } from "./cache";
6
+
7
+ /**
8
+ * Branch and remote reads for workspace directories.
9
+ *
10
+ * Every call goes through `execFile` with an argv array and no shell (see
11
+ * `server/deps`), so nothing here can be influenced by the user's shell
12
+ * functions, aliases or `$PATH` ordering surprises.
13
+ *
14
+ * Most reads never spawn anything: `server/resolve` prefers the branch the
15
+ * daemon already reports on each workspace descriptor and only falls back to
16
+ * this module when that field is missing. When it does spawn, results are
17
+ * cached against the mtime of the worktree's `HEAD`, so repeated popover opens
18
+ * are free until the branch actually moves.
19
+ *
20
+ * `git` missing is not a case this module reports: every read here is a
21
+ * fallback, so it degrades to "branch unknown". The one place a missing `git`
22
+ * is fatal — creating a worktree — asks `requireGit()` for a message that names
23
+ * the dependency, and the startup self-check says so in the log regardless.
24
+ *
25
+ * EVERYTHING HERE IS READ-ONLY, and that is a hard rule rather than a
26
+ * coincidence. `/v1/resolve` runs while the user is typing in a browser, and
27
+ * the directories it reads are the candidate *workspaces* — each on its own
28
+ * branch, quite possibly with an agent working in it. So: no `fetch`, no
29
+ * checkout, no ref writes, nothing that takes a lock. The ancestry read below
30
+ * is the one that makes this tempting to break (a `git fetch` would make it
31
+ * answer more often), and it must not be.
32
+ */
33
+
34
+ const REMOTE_TTL_MS = 5 * 60_000;
35
+ /** Trunk and ancestry are both derived from refs that already exist locally. */
36
+ const TRUNK_TTL_MS = 30 * 60_000;
37
+ const MAX_WORKSPACE_CACHE_ENTRIES = 512;
38
+ /**
39
+ * `git branch --contains` walks every ref in the repository, so unlike the
40
+ * branch reads it is not O(1). Bounded like every other spawn in the plugin;
41
+ * the caller degrades to "no ancestry answer" if it trips.
42
+ */
43
+ const ANCESTRY_TIMEOUT_MS = 5_000;
44
+
45
+ /**
46
+ * The `git` executable, or a failure that names the dependency.
47
+ *
48
+ * Used only on paths where a missing `git` genuinely stops the work; the branch
49
+ * reads below swallow it and return null instead.
50
+ */
51
+ export async function requireGit(): Promise<string> {
52
+ const found = await findGit();
53
+ if (found === null) {
54
+ throw new BridgeError(
55
+ "workspace_create_failed",
56
+ "git was not found on this machine, and Paseo needs it to check a pull request out into a worktree.",
57
+ INSTALL_HINT.git,
58
+ );
59
+ }
60
+ return found;
61
+ }
62
+
63
+ async function git(
64
+ cwd: string,
65
+ args: readonly string[],
66
+ options: { timeoutMs?: number } = {},
67
+ ): Promise<string> {
68
+ const bin = await findGit();
69
+ if (bin === null) throw new Error("git was not found");
70
+ const { stdout } = await runProcess(bin, ["-C", cwd, ...args], options);
71
+ return stdout.trim();
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Branch reads
76
+ // ---------------------------------------------------------------------------
77
+
78
+ /** cwd -> the `HEAD` file that actually moves when the branch changes. */
79
+ const headPathCache = new Map<string, string | null>();
80
+ /** cwd -> the branch we read, valid while `HEAD`'s mtime is unchanged. */
81
+ const branchCache = new Map<string, { mtimeMs: number | null; branch: string | null }>();
82
+
83
+ /**
84
+ * Locates the `HEAD` that tracks this directory's branch.
85
+ *
86
+ * A linked worktree's `.git` is a *file* pointing at
87
+ * `<repo>/.git/worktrees/<name>`, and that directory has its own `HEAD`. Using
88
+ * the main repository's `HEAD` would cache every worktree against the wrong
89
+ * file and hand back a stale branch.
90
+ */
91
+ async function resolveHeadPath(cwd: string): Promise<string | null> {
92
+ const cachedHead = headPathCache.get(cwd);
93
+ if (cachedHead !== undefined) return cachedHead;
94
+
95
+ let head: string | null = null;
96
+ try {
97
+ const dotGit = join(cwd, ".git");
98
+ const info = await stat(dotGit);
99
+ if (info.isDirectory()) {
100
+ head = join(dotGit, "HEAD");
101
+ } else {
102
+ const contents = await readFile(dotGit, "utf8");
103
+ const match = /^gitdir:\s*(.+)$/m.exec(contents);
104
+ if (match?.[1] !== undefined) {
105
+ const gitDir = match[1].trim();
106
+ head = join(isAbsolute(gitDir) ? gitDir : resolvePath(cwd, gitDir), "HEAD");
107
+ }
108
+ }
109
+ } catch {
110
+ head = null;
111
+ }
112
+ setBoundedCache(headPathCache, cwd, head, { maxEntries: MAX_WORKSPACE_CACHE_ENTRIES });
113
+ return head;
114
+ }
115
+
116
+ async function headMtime(cwd: string): Promise<number | null> {
117
+ const head = await resolveHeadPath(cwd);
118
+ if (head === null) return null;
119
+ try {
120
+ return (await stat(head)).mtimeMs;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Current branch of a working directory, or null when it is detached, is not a
128
+ * git repository, or no longer exists on disk. Never throws: a broken worktree
129
+ * must not take down a resolve.
130
+ */
131
+ export async function readBranch(cwd: string): Promise<string | null> {
132
+ const mtimeMs = await headMtime(cwd);
133
+ const hit = branchCache.get(cwd);
134
+ if (hit !== undefined && hit.mtimeMs === mtimeMs && mtimeMs !== null) return hit.branch;
135
+
136
+ let branch: string | null = null;
137
+ try {
138
+ const value = await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
139
+ // `HEAD` means detached, which is not a branch we can match a PR against.
140
+ branch = value === "" || value === "HEAD" ? null : value;
141
+ } catch {
142
+ branch = null;
143
+ }
144
+ setBoundedCache(branchCache, cwd, { mtimeMs, branch }, {
145
+ maxEntries: MAX_WORKSPACE_CACHE_ENTRIES,
146
+ });
147
+ return branch;
148
+ }
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // Remote reads
152
+ // ---------------------------------------------------------------------------
153
+
154
+ const remoteCache = new Map<string, { at: number; ownerRepo: OwnerRepo | null }>();
155
+
156
+ export interface OwnerRepo {
157
+ owner: string;
158
+ repo: string;
159
+ }
160
+
161
+ /**
162
+ * Extracts `owner/repo` from any GitHub remote spelling: HTTPS, `git@` scp
163
+ * syntax, `ssh://`, with or without a `.git` suffix.
164
+ */
165
+ export function parseGithubRemote(url: string): OwnerRepo | null {
166
+ const trimmed = url.trim();
167
+ if (trimmed === "") return null;
168
+ const patterns = [
169
+ /^(?:https?:\/\/)(?:[^@/]+@)?github\.com\/([^/]+)\/(.+?)(?:\.git)?\/?$/i,
170
+ /^(?:ssh:\/\/)?(?:[^@/]+@)?github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i,
171
+ ];
172
+ for (const pattern of patterns) {
173
+ const match = pattern.exec(trimmed);
174
+ const owner = match?.[1];
175
+ const repo = match?.[2];
176
+ if (owner !== undefined && repo !== undefined && !repo.includes("/")) {
177
+ return { owner, repo };
178
+ }
179
+ }
180
+ return null;
181
+ }
182
+
183
+ /**
184
+ * `owner/repo` of a directory's `origin`. Used to match a Paseo project that
185
+ * carries a local id rather than the `remote:github.com/...` form.
186
+ */
187
+ export async function readOriginOwnerRepo(cwd: string): Promise<OwnerRepo | null> {
188
+ const hit = remoteCache.get(cwd);
189
+ if (hit !== undefined && Date.now() - hit.at < REMOTE_TTL_MS) return hit.ownerRepo;
190
+ let ownerRepo: OwnerRepo | null = null;
191
+ try {
192
+ ownerRepo = parseGithubRemote(await git(cwd, ["config", "--get", "remote.origin.url"]));
193
+ } catch {
194
+ ownerRepo = null;
195
+ }
196
+ setBoundedCache(remoteCache, cwd, { at: Date.now(), ownerRepo }, {
197
+ maxEntries: MAX_WORKSPACE_CACHE_ENTRIES,
198
+ expired: (value) => Date.now() - value.at >= REMOTE_TTL_MS,
199
+ });
200
+ return ownerRepo;
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // Trunk and ancestry
205
+ // ---------------------------------------------------------------------------
206
+
207
+ const trunkCache = new Map<string, { at: number; branch: string | null }>();
208
+
209
+ /**
210
+ * A ref name safe to hand to `git` as an option's value.
211
+ *
212
+ * Nothing here can become shell syntax — every spawn is `execFile` with an argv
213
+ * array — but a name starting with `-` could still be parsed by git as a flag,
214
+ * so it is rejected rather than passed. Branch names reaching this module come
215
+ * from git itself, so this is hygiene, not a live hole.
216
+ */
217
+ function looksLikeRefName(name: string): boolean {
218
+ return name !== "" && !name.startsWith("-") && !/[\s~^:?*[\\]/.test(name);
219
+ }
220
+
221
+ /**
222
+ * The repository's trunk branch, from local refs only — no network.
223
+ *
224
+ * `git clone` writes `refs/remotes/origin/HEAD`, so in a normal clone this is a
225
+ * single local ref read. Measured across this machine's Paseo projects on
226
+ * 2026-09-02: 2 of 3 git projects had it, the third did not (the ref can be
227
+ * missing after a `git init` + `git remote add`, or after some mirror/partial
228
+ * clone flows). So callers must handle `null`, and `server/gh` has a
229
+ * `gh repo view` fallback for exactly that case.
230
+ *
231
+ * Trunk matters because widening stack discovery to merged pull requests makes
232
+ * trunk reachable as a *head* branch: measured in a public repository,
233
+ * `vercel/turborepo` PR #13875 is MERGED with `headRefName: "main"` (a release
234
+ * back-merge). Without a trunk name to exclude, that one row fuses every PR
235
+ * based on `main` into a single false "stack".
236
+ */
237
+ export async function readTrunkBranch(root: string): Promise<string | null> {
238
+ const hit = trunkCache.get(root);
239
+ if (hit !== undefined && Date.now() - hit.at < TRUNK_TTL_MS) return hit.branch;
240
+ let branch: string | null = null;
241
+ try {
242
+ // `--short` gives "origin/main"; the remote prefix is stripped so the
243
+ // answer is a branch name comparable with a PR's `baseRefName`.
244
+ const value = await git(root, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
245
+ branch = value.startsWith("origin/") ? value.slice("origin/".length) : value;
246
+ if (branch === "") branch = null;
247
+ } catch {
248
+ branch = null;
249
+ }
250
+ setBoundedCache(trunkCache, root, { at: Date.now(), branch }, {
251
+ maxEntries: MAX_WORKSPACE_CACHE_ENTRIES,
252
+ expired: (value) => Date.now() - value.at >= TRUNK_TTL_MS,
253
+ });
254
+ return branch;
255
+ }
256
+
257
+ /**
258
+ * Branch names — local and remote-tracking — whose tip has `branch` in its
259
+ * history, i.e. every branch `branch` has been merged into or rebased under.
260
+ *
261
+ * `refs/heads/x` comes back as `x` and `refs/remotes/origin/x` as `origin/x`,
262
+ * so a caller comparing against a set of stack branches must consider both
263
+ * spellings. `--format` is used instead of parsing `git branch`'s output
264
+ * because that output carries `* ` markers and `(HEAD detached at …)` rows.
265
+ *
266
+ * Returns null — never throws — when git is missing, the ref is unknown, the
267
+ * directory is not a repository, or the walk times out. That is the whole
268
+ * degradation story for the ancestry mechanism: it answers or it does not, and
269
+ * a resolve is still correct without it.
270
+ */
271
+ export async function branchesContaining(
272
+ root: string,
273
+ branch: string,
274
+ ): Promise<Set<string> | null> {
275
+ if (!looksLikeRefName(branch)) return null;
276
+ let output: string;
277
+ try {
278
+ output = await git(root, ["branch", "-a", "--contains", branch, "--format=%(refname)"], {
279
+ timeoutMs: ANCESTRY_TIMEOUT_MS,
280
+ });
281
+ } catch {
282
+ return null;
283
+ }
284
+ const names = new Set<string>();
285
+ for (const line of output.split("\n")) {
286
+ const ref = line.trim();
287
+ if (ref.startsWith("refs/heads/")) names.add(ref.slice("refs/heads/".length));
288
+ else if (ref.startsWith("refs/remotes/")) names.add(ref.slice("refs/remotes/".length));
289
+ }
290
+ return names;
291
+ }
292
+
293
+ export function clearGitCaches(): void {
294
+ headPathCache.clear();
295
+ branchCache.clear();
296
+ remoteCache.clear();
297
+ trunkCache.clear();
298
+ }
@@ -0,0 +1,110 @@
1
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
+
3
+ type PaseoApi = PluginHandlerContext["paseo"];
4
+ export type ListedAgent = Awaited<ReturnType<PaseoApi["agents"]["list"]>>["entries"][number]["agent"];
5
+
6
+ const PARENT_AGENT_LABEL = "paseo.parent-agent-id";
7
+ const OPEN_TAB_PREFIX = "paseo.open-agent-tab.";
8
+ const PAGE_SIZE = 200;
9
+ const MAX_PAGES = 10;
10
+
11
+ function timestamp(value: string | null | undefined): number {
12
+ if (!value) return 0;
13
+ const parsed = Date.parse(value);
14
+ return Number.isNaN(parsed) ? 0 : parsed;
15
+ }
16
+
17
+ function isRoot(agent: ListedAgent): boolean {
18
+ return !(agent.labels[PARENT_AGENT_LABEL] ?? "").trim();
19
+ }
20
+
21
+ function hasOpenTab(agent: ListedAgent): boolean {
22
+ return Object.entries(agent.labels).some(
23
+ ([key, value]) => key.startsWith(OPEN_TAB_PREFIX) && value === "true",
24
+ );
25
+ }
26
+
27
+ function titleIsMain(agent: ListedAgent): boolean {
28
+ return /^(main|main agent)$/i.test(agent.title?.trim() ?? "");
29
+ }
30
+
31
+ function liveRank(agent: ListedAgent): number {
32
+ switch (agent.status) {
33
+ case "running":
34
+ return 4;
35
+ case "idle":
36
+ return 3;
37
+ case "initializing":
38
+ return 2;
39
+ case "closed":
40
+ return 1;
41
+ default:
42
+ return 0;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Pick the workspace's main agent from durable Paseo metadata.
48
+ *
49
+ * "Main" means a root agent, not merely the newest record: delegated agents
50
+ * carry `paseo.parent-agent-id` and are never eligible. An explicit Main title
51
+ * is the strongest user signal, followed by an agent open in a Paseo tab, then
52
+ * a live runtime and recent user activity. The final id comparison makes the
53
+ * result deterministic when old records have identical timestamps.
54
+ */
55
+ export function selectMainAgent(
56
+ agents: readonly ListedAgent[],
57
+ workspaceId: string,
58
+ ): ListedAgent | null {
59
+ const eligible = agents.filter(
60
+ (agent) =>
61
+ agent.workspaceId === workspaceId &&
62
+ agent.archivedAt == null &&
63
+ isRoot(agent),
64
+ );
65
+ eligible.sort((left, right) => {
66
+ const priorities = [
67
+ Number(titleIsMain(right)) - Number(titleIsMain(left)),
68
+ Number(hasOpenTab(right)) - Number(hasOpenTab(left)),
69
+ liveRank(right) - liveRank(left),
70
+ timestamp(right.lastUserMessageAt) - timestamp(left.lastUserMessageAt),
71
+ timestamp(right.updatedAt) - timestamp(left.updatedAt),
72
+ timestamp(right.createdAt) - timestamp(left.createdAt),
73
+ ];
74
+ for (const difference of priorities) if (difference !== 0) return difference;
75
+ return left.id.localeCompare(right.id);
76
+ });
77
+ return eligible[0] ?? null;
78
+ }
79
+
80
+ /**
81
+ * Fetch active agents in the project, following pagination rather than
82
+ * assuming the daemon's first page contains this workspace's older main agent.
83
+ */
84
+ export async function listProjectAgents(
85
+ paseo: PaseoApi,
86
+ projectId: string,
87
+ ): Promise<ListedAgent[]> {
88
+ const agents: ListedAgent[] = [];
89
+ let cursor: string | undefined;
90
+ for (let page = 0; page < MAX_PAGES; page += 1) {
91
+ const result = await paseo.agents.list({
92
+ filter: { includeArchived: false, projectKeys: [projectId] },
93
+ sort: [{ key: "updated_at", direction: "desc" }],
94
+ page: { limit: PAGE_SIZE, ...(cursor === undefined ? {} : { cursor }) },
95
+ });
96
+ for (const entry of result.entries) agents.push(entry.agent);
97
+ cursor = result.pageInfo.nextCursor ?? undefined;
98
+ if (!result.pageInfo.hasMore || cursor === undefined) break;
99
+ }
100
+ return agents;
101
+ }
102
+
103
+ export function agentDisplayTitle(agent: ListedAgent): string {
104
+ const title = agent.title?.trim();
105
+ return title ? title : `Agent ${agent.id.slice(0, 7)}`;
106
+ }
107
+
108
+ export function agentProvider(agent: ListedAgent): string {
109
+ return agent.model ? `${agent.provider}/${agent.model}` : agent.provider;
110
+ }