@phren/cli 0.3.37 → 0.3.40

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 (96) hide show
  1. package/dist/bridge/account-failover.d.ts +4 -0
  2. package/dist/bridge/account-failover.js +12 -4
  3. package/dist/bridge/account-usage.d.ts +5 -2
  4. package/dist/bridge/account-usage.js +36 -6
  5. package/dist/bridge/agent-hooks.js +2 -0
  6. package/dist/bridge/changes.d.ts +5 -0
  7. package/dist/bridge/changes.js +4 -0
  8. package/dist/bridge/claude-accounts.d.ts +15 -4
  9. package/dist/bridge/claude-accounts.js +31 -16
  10. package/dist/bridge/claude-credits.d.ts +43 -0
  11. package/dist/bridge/claude-credits.js +236 -0
  12. package/dist/bridge/claude-question-dialog.js +6 -2
  13. package/dist/bridge/command.js +64 -3
  14. package/dist/bridge/conductor-sets.d.ts +5 -0
  15. package/dist/bridge/conductor-sets.js +23 -3
  16. package/dist/bridge/device-enroll.d.ts +34 -0
  17. package/dist/bridge/device-enroll.js +57 -0
  18. package/dist/bridge/dispatch-command.d.ts +2 -0
  19. package/dist/bridge/dispatch-command.js +25 -1
  20. package/dist/bridge/dispatch-returns.d.ts +7 -0
  21. package/dist/bridge/dispatch-returns.js +56 -6
  22. package/dist/bridge/dispatch.d.ts +52 -0
  23. package/dist/bridge/dispatch.js +14 -0
  24. package/dist/bridge/enroll.js +22 -4
  25. package/dist/bridge/file-range.d.ts +3 -0
  26. package/dist/bridge/file-range.js +5 -4
  27. package/dist/bridge/file-search.d.ts +37 -0
  28. package/dist/bridge/file-search.js +87 -0
  29. package/dist/bridge/file-write.d.ts +6 -0
  30. package/dist/bridge/file-write.js +120 -0
  31. package/dist/bridge/git-host-auth.d.ts +31 -0
  32. package/dist/bridge/git-host-auth.js +110 -0
  33. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  34. package/dist/bridge/git-host-gitboy.js +296 -0
  35. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  36. package/dist/bridge/git-host-gitlab.js +229 -0
  37. package/dist/bridge/git-host-http.d.ts +33 -0
  38. package/dist/bridge/git-host-http.js +70 -0
  39. package/dist/bridge/git-hosts.d.ts +92 -0
  40. package/dist/bridge/git-hosts.js +244 -0
  41. package/dist/bridge/git-publish.d.ts +15 -5
  42. package/dist/bridge/git-publish.js +69 -21
  43. package/dist/bridge/git-review.d.ts +23 -0
  44. package/dist/bridge/git-review.js +170 -0
  45. package/dist/bridge/git-sync.d.ts +14 -0
  46. package/dist/bridge/git-sync.js +143 -0
  47. package/dist/bridge/git.d.ts +20 -7
  48. package/dist/bridge/git.js +87 -68
  49. package/dist/bridge/gitboy-contract.d.ts +32 -0
  50. package/dist/bridge/gitboy-contract.js +46 -0
  51. package/dist/bridge/hand-off.d.ts +52 -2
  52. package/dist/bridge/hand-off.js +77 -24
  53. package/dist/bridge/health.d.ts +1 -1
  54. package/dist/bridge/health.js +5 -3
  55. package/dist/bridge/install.d.ts +14 -0
  56. package/dist/bridge/install.js +40 -1
  57. package/dist/bridge/memory-store.d.ts +8 -0
  58. package/dist/bridge/memory-store.js +80 -2
  59. package/dist/bridge/pair.d.ts +6 -1
  60. package/dist/bridge/pair.js +74 -2
  61. package/dist/bridge/project-memory.d.ts +94 -0
  62. package/dist/bridge/project-memory.js +235 -0
  63. package/dist/bridge/push.d.ts +15 -0
  64. package/dist/bridge/push.js +39 -0
  65. package/dist/bridge/scoped-gateway.d.ts +29 -0
  66. package/dist/bridge/scoped-gateway.js +239 -0
  67. package/dist/bridge/server-launch.d.ts +12 -0
  68. package/dist/bridge/server-launch.js +17 -10
  69. package/dist/bridge/server-pane-routes.js +54 -3
  70. package/dist/bridge/server-routes.d.ts +13 -0
  71. package/dist/bridge/server-routes.js +63 -5
  72. package/dist/bridge/server.js +44 -5
  73. package/dist/bridge/session-move.d.ts +288 -0
  74. package/dist/bridge/session-move.js +600 -0
  75. package/dist/bridge/subscription.d.ts +15 -0
  76. package/dist/bridge/subscription.js +23 -0
  77. package/dist/bridge/transport.js +21 -1
  78. package/dist/bridge/usage.d.ts +20 -3
  79. package/dist/bridge/usage.js +61 -11
  80. package/dist/bridge-hook.mjs +12822 -3248
  81. package/dist/cli-registry.js +10 -4
  82. package/dist/computers/command.js +3 -1
  83. package/dist/computers/read.d.ts +3 -0
  84. package/dist/computers/read.js +6 -0
  85. package/dist/content/summarize.d.ts +21 -0
  86. package/dist/content/summarize.js +56 -18
  87. package/dist/modules/registry.js +14 -14
  88. package/dist/project-config.d.ts +12 -0
  89. package/dist/project-config.js +29 -0
  90. package/dist/shared/retrieval.d.ts +1 -0
  91. package/dist/shared/retrieval.js +1 -1
  92. package/dist/sync/conflict-resolve.js +5 -6
  93. package/dist/tools/dispatch.js +18 -1
  94. package/dist/tools/finding.d.ts +25 -0
  95. package/dist/tools/finding.js +2 -1
  96. package/package.json +57 -1
@@ -0,0 +1,170 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { BridgeError } from "./protocol.js";
5
+ import { git, gitRoot, withGitReadDeadline } from "./projects.js";
6
+ import { invalidateTree, repositoryPath } from "./git.js";
7
+ /** What a review screen needs beyond status and patches: a file's text at
8
+ * HEAD, in the index or at a commit (so a real diff editor can compare whole
9
+ * files), staging or unstaging single hunks, and the edits one agent session
10
+ * made. */
11
+ const MAX_FILE = 2_000_000;
12
+ const MAX_PATCH = 2_000_000;
13
+ async function repository(cwd) {
14
+ const root = await gitRoot(cwd);
15
+ if (!root)
16
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
17
+ return root;
18
+ }
19
+ /** `HEAD`, `INDEX` (stage 0) or a commit hash. */
20
+ function revision(raw) {
21
+ if (raw === "HEAD" || raw === "INDEX")
22
+ return raw;
23
+ if (typeof raw === "string" && /^[0-9a-fA-F]{4,64}$/.test(raw))
24
+ return raw;
25
+ throw new BridgeError(400, "Name HEAD, INDEX or a commit hash.");
26
+ }
27
+ /** One file's text at HEAD, in the index or at a commit. A path the tree does
28
+ * not hold answers `missing: true` (an added or deleted side), a file larger
29
+ * than 2 MB `tooLarge: true`, and bytes with a NUL `binary: true`, each with
30
+ * no text. */
31
+ export function gitFile(cwd, ref, rawPath) {
32
+ return withGitReadDeadline(async () => {
33
+ const root = await repository(cwd);
34
+ const rev = revision(ref);
35
+ const file = await repositoryPath(root, rawPath);
36
+ let spec;
37
+ if (rev === "INDEX")
38
+ spec = `:0:${file}`;
39
+ else {
40
+ let commit;
41
+ try {
42
+ commit = (await git(root, "rev-parse", "--verify", "--end-of-options", `${rev}^{commit}`)).trim();
43
+ }
44
+ catch {
45
+ throw new BridgeError(404, "This repository has no such commit.", { code: "git-unknown-commit" });
46
+ }
47
+ spec = `${commit}:${file}`;
48
+ }
49
+ const kind = await git(root, "cat-file", "-t", spec).then(out => out.trim(), () => "");
50
+ if (!kind)
51
+ return { path: file, ref: rev, missing: true, text: "" };
52
+ if (kind !== "blob")
53
+ return { path: file, ref: rev, missing: true, text: "", kindOf: kind };
54
+ const size = Number((await git(root, "cat-file", "-s", spec)).trim()) || 0;
55
+ if (size > MAX_FILE)
56
+ return { path: file, ref: rev, size, tooLarge: true, text: "" };
57
+ const text = await git(root, "cat-file", "blob", spec);
58
+ if (text.slice(0, 8000).includes("\0"))
59
+ return { path: file, ref: rev, size, binary: true, text: "" };
60
+ return { path: file, ref: rev, size, text };
61
+ });
62
+ }
63
+ /** A name in a patch header: `a/x` or a C-quoted `"a/x\ty"`. */
64
+ function headerName(raw) {
65
+ let name = raw.trim();
66
+ if (name === "/dev/null")
67
+ return null;
68
+ if (name.startsWith("\"")) {
69
+ try {
70
+ name = JSON.parse(name);
71
+ }
72
+ catch {
73
+ throw new BridgeError(400, "This patch names a file Phren cannot read.");
74
+ }
75
+ }
76
+ if (!/^[ab]\//.test(name))
77
+ throw new BridgeError(400, "This patch is not a Git patch.");
78
+ return name.slice(2);
79
+ }
80
+ /** The files a patch touches, from its `---`/`+++` lines. Rename, mode and
81
+ * binary patches are refused: only text hunks are staged one at a time. */
82
+ export function patchFiles(patch) {
83
+ const files = new Set();
84
+ let hunks = 0;
85
+ for (const line of patch.split("\n")) {
86
+ if (/^(?:rename|copy) (?:from|to) |^(?:old|new|deleted file|new file) mode |^GIT binary patch|^Binary files /.test(line)) {
87
+ throw new BridgeError(400, "Only text hunks can be staged one at a time. Stage the whole file instead.");
88
+ }
89
+ if (line.startsWith("--- ") || line.startsWith("+++ ")) {
90
+ const name = headerName(line.slice(4).replace(/\t.*$/, ""));
91
+ if (name)
92
+ files.add(name);
93
+ }
94
+ if (line.startsWith("@@ "))
95
+ hunks++;
96
+ }
97
+ if (!files.size || !hunks)
98
+ throw new BridgeError(400, "This patch has no hunks.");
99
+ if (files.size > 1)
100
+ throw new BridgeError(400, "Stage hunks of one file at a time.");
101
+ return [...files];
102
+ }
103
+ /** Apply a patch of one file's hunks to the index only: staging them, or with
104
+ * `reverse` unstaging them. The working tree is never touched. Git checks the
105
+ * patch first; a hunk that no longer applies (the file moved on) is Git's
106
+ * refusal as `{ ok: false, output }`. */
107
+ export async function gitApply(cwd, rawPatch, reverse) {
108
+ if (typeof rawPatch !== "string" || !rawPatch.trim())
109
+ throw new BridgeError(400, "Choose a hunk to stage.");
110
+ if (rawPatch.length > MAX_PATCH || rawPatch.includes("\0"))
111
+ throw new BridgeError(400, "This patch is too large.");
112
+ const root = await repository(cwd);
113
+ const [file] = patchFiles(rawPatch);
114
+ await repositoryPath(root, file);
115
+ const scratch = await mkdtemp(path.join(tmpdir(), "phren-apply-"));
116
+ const patchFile = path.join(scratch, "hunk.patch");
117
+ try {
118
+ await writeFile(patchFile, rawPatch.endsWith("\n") ? rawPatch : rawPatch + "\n", { mode: 0o600 });
119
+ const args = ["apply", "--cached", "--whitespace=nowarn", ...(reverse === true ? ["-R"] : []), "--", patchFile];
120
+ invalidateTree(root);
121
+ try {
122
+ await git(root, "apply", "--check", ...args.slice(1));
123
+ }
124
+ catch (error) {
125
+ return { ok: false, output: error instanceof BridgeError ? error.message.replace(/^Git apply failed: /, "") : "git apply refused this hunk." };
126
+ }
127
+ await git(root, ...args);
128
+ return { ok: true, path: file, staged: reverse !== true };
129
+ }
130
+ finally {
131
+ invalidateTree(root);
132
+ await rm(scratch, { recursive: true, force: true });
133
+ }
134
+ }
135
+ /** One session's recorded edits, oldest first, folded by file: how often each
136
+ * file changed, the lines added and removed across those edits, and each
137
+ * edit's patch. Only edits inside `root` (the session's repository) count;
138
+ * `others` says how many touched other repositories. */
139
+ export function sessionChanges(root, history) {
140
+ const files = new Map();
141
+ let others = 0, calls = 0;
142
+ for (const row of history) {
143
+ let counted = false;
144
+ for (const change of row.files) {
145
+ if (change.root !== root) {
146
+ others++;
147
+ continue;
148
+ }
149
+ counted = true;
150
+ const entry = files.get(change.path) ?? { path: change.path, status: change.status, added: 0, removed: 0, edits: [], redacted: false, binary: false };
151
+ entry.added += change.added;
152
+ entry.removed += change.removed;
153
+ entry.redacted ||= change.redacted === true;
154
+ entry.binary ||= change.binary === true;
155
+ // The first edit's status says whether the session added the file.
156
+ if (entry.edits.length && change.status === "D")
157
+ entry.status = "D";
158
+ if (entry.edits.length < 50)
159
+ entry.edits.push({ toolUseId: row.toolUseId, status: change.status, added: change.added, removed: change.removed,
160
+ patch: change.patch.slice(0, 200_000), ...(change.patch.length > 200_000 || change.truncated ? { truncated: true } : {}) });
161
+ files.delete(change.path);
162
+ files.set(change.path, entry);
163
+ }
164
+ if (counted)
165
+ calls++;
166
+ }
167
+ const list = [...files.values()].reverse().slice(0, 300);
168
+ return { root, calls, files: list, totalFiles: files.size, others,
169
+ additions: list.reduce((n, f) => n + f.added, 0), deletions: list.reduce((n, f) => n + f.removed, 0) };
170
+ }
@@ -0,0 +1,14 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** Switch to a local branch, or create one (from `startPoint`, a branch or
3
+ * remote-tracking branch, else HEAD) and switch to it. A remote-tracking
4
+ * start point sets it as the upstream. Uncommitted tracked edits travel with
5
+ * a switch in Git; the phone must say it knows (`carryChanges`), and Git
6
+ * still refuses whatever would be overwritten. */
7
+ export declare function gitCheckout(cwd: string, body: Json): Promise<Json>;
8
+ /** Fetch the upstream's remote (else `origin`) and prune what it deleted, so
9
+ * ahead/behind counts and remote branches are current. Tags are not fetched. */
10
+ export declare function gitFetch(cwd: string): Promise<Json>;
11
+ /** Fetch, then fast-forward the current branch to its upstream. Never a merge
12
+ * commit or a rebase: a branch that has diverged is refused by Git and the
13
+ * phone shows why. */
14
+ export declare function gitPull(cwd: string): Promise<Json>;
@@ -0,0 +1,143 @@
1
+ import { BridgeError } from "./protocol.js";
2
+ import { git, gitRoot } from "./projects.js";
3
+ import { countGit } from "./metrics.js";
4
+ import { invalidateTree } from "./git.js";
5
+ import { runCombined } from "./git-publish.js";
6
+ /** Moving the checkout from the phone: switch or create a branch, fetch the
7
+ * upstream remote, fast-forward to it. Like commit and push, a refusal from
8
+ * Git itself is a normal `{ ok: false, output }` answer with its own words.
9
+ * Nothing here rewrites history, forces, resets or stashes. */
10
+ const SYNC_TIMEOUT_MS = 110_000;
11
+ const SWITCH_TIMEOUT_MS = 60_000;
12
+ async function repository(cwd) {
13
+ const root = await gitRoot(cwd);
14
+ if (!root)
15
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
16
+ return root;
17
+ }
18
+ function refused(run, command, timeout) {
19
+ return { ok: false, output: run.timedOut ? `${run.output}\n[${command} did not finish within ${timeout / 1000} seconds]`.trim() : run.output || `${command} failed.` };
20
+ }
21
+ /** A branch name Git itself accepts, never an option. */
22
+ async function branchName(root, raw) {
23
+ if (typeof raw !== "string" || !raw || raw.length > 250 || raw.startsWith("-") || /[\x00-\x1f\x7f\s]/.test(raw))
24
+ throw new BridgeError(400, "Enter a valid branch name.");
25
+ try {
26
+ await git(root, "check-ref-format", "--branch", raw);
27
+ }
28
+ catch {
29
+ throw new BridgeError(400, `${raw} is not a valid branch name.`);
30
+ }
31
+ return raw;
32
+ }
33
+ async function exists(root, ref) {
34
+ return git(root, "show-ref", "--verify", "--quiet", ref).then(() => true, () => false);
35
+ }
36
+ /** Tracked files with staged or unstaged edits. Untracked files never block a
37
+ * switch unless Git itself refuses to overwrite one. */
38
+ async function trackedChanges(root) {
39
+ const rows = (await git(root, "status", "--porcelain=v1", "-z", "--untracked-files=no")).split("\0");
40
+ let count = 0;
41
+ for (let index = 0; index < rows.length; index++) {
42
+ const row = rows[index];
43
+ if (!row)
44
+ continue;
45
+ count++;
46
+ if (/[RC]/.test(row.slice(0, 2)))
47
+ index++;
48
+ }
49
+ return count;
50
+ }
51
+ /** Switch to a local branch, or create one (from `startPoint`, a branch or
52
+ * remote-tracking branch, else HEAD) and switch to it. A remote-tracking
53
+ * start point sets it as the upstream. Uncommitted tracked edits travel with
54
+ * a switch in Git; the phone must say it knows (`carryChanges`), and Git
55
+ * still refuses whatever would be overwritten. */
56
+ export async function gitCheckout(cwd, body) {
57
+ const root = await repository(cwd);
58
+ const branch = await branchName(root, body.branch);
59
+ const create = body.create === true;
60
+ let startPoint, track = false;
61
+ if (body.startPoint !== undefined && body.startPoint !== null) {
62
+ if (!create)
63
+ throw new BridgeError(400, "A start point only applies to a new branch.");
64
+ const raw = body.startPoint;
65
+ if (typeof raw !== "string" || !raw || raw.length > 512 || raw.startsWith("-") || /[\x00-\x1f\x7f\s]/.test(raw))
66
+ throw new BridgeError(400, "Enter a valid start point.");
67
+ if (await exists(root, `refs/heads/${raw}`))
68
+ startPoint = `refs/heads/${raw}`;
69
+ else if (await exists(root, `refs/remotes/${raw}`)) {
70
+ startPoint = `refs/remotes/${raw}`;
71
+ track = true;
72
+ }
73
+ else
74
+ throw new BridgeError(404, `There is no branch named ${raw}.`, { code: "git-unknown-ref" });
75
+ }
76
+ const local = await exists(root, `refs/heads/${branch}`);
77
+ if (create && local)
78
+ throw new BridgeError(409, `A branch named ${branch} already exists.`, { code: "git-branch-exists" });
79
+ if (!create && !local)
80
+ throw new BridgeError(404, `There is no local branch named ${branch}.`, { code: "git-unknown-ref" });
81
+ const previous = (await git(root, "branch", "--show-current")).trim();
82
+ if (!create && previous === branch)
83
+ return { ok: true, branch, previous, changed: false };
84
+ const dirty = await trackedChanges(root);
85
+ if (dirty > 0 && body.carryChanges !== true) {
86
+ throw new BridgeError(409, `${dirty === 1 ? "1 file has" : `${dirty} files have`} uncommitted changes that would move to ${branch}. Confirm to carry them.`, { code: "git-dirty", changes: dirty });
87
+ }
88
+ const args = ["-C", root, "--no-pager", "switch", "--no-guess", ...(create ? [...(track ? ["--track"] : ["--no-track"]), "-c", branch, ...(startPoint ? [startPoint] : [])] : [branch])];
89
+ invalidateTree(root);
90
+ countGit("projects");
91
+ const run = await runCombined("git", args, root, SWITCH_TIMEOUT_MS);
92
+ invalidateTree(root);
93
+ if (run.code !== 0)
94
+ return refused(run, "git switch", SWITCH_TIMEOUT_MS);
95
+ const upstream = (await git(root, "for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`)).trim();
96
+ return { ok: true, branch, previous, changed: true, created: create, ...(upstream ? { upstream } : {}), carried: dirty };
97
+ }
98
+ /** The current branch's upstream, as remote and `refs/heads/…` merge ref. */
99
+ async function upstreamOf(root) {
100
+ const branch = (await git(root, "branch", "--show-current")).trim();
101
+ if (!branch)
102
+ return { branch };
103
+ const remote = (await git(root, "config", "--get", `branch.${branch}.remote`).catch(() => "")).trim();
104
+ const merge = (await git(root, "config", "--get", `branch.${branch}.merge`).catch(() => "")).trim();
105
+ return remote && remote !== "." && merge.startsWith("refs/heads/") ? { branch, remote, merge } : { branch };
106
+ }
107
+ /** Fetch the upstream's remote (else `origin`) and prune what it deleted, so
108
+ * ahead/behind counts and remote branches are current. Tags are not fetched. */
109
+ export async function gitFetch(cwd) {
110
+ const root = await repository(cwd);
111
+ const { remote: upstreamRemote } = await upstreamOf(root);
112
+ const remotes = (await git(root, "remote")).split("\n").map(line => line.trim()).filter(Boolean);
113
+ const remote = upstreamRemote ?? (remotes.includes("origin") ? "origin" : remotes[0]);
114
+ if (!remote || !remotes.includes(remote))
115
+ throw new BridgeError(409, "This repository has no remote to fetch from.", { code: "git-no-remote" });
116
+ countGit("projects");
117
+ const run = await runCombined("git", ["-C", root, "--no-pager", "fetch", "--prune", "--no-tags", "--quiet", remote], root, SYNC_TIMEOUT_MS);
118
+ invalidateTree(root);
119
+ if (run.code !== 0)
120
+ return refused(run, "git fetch", SYNC_TIMEOUT_MS);
121
+ return { ok: true, remote, ...(run.output ? { output: run.output } : {}) };
122
+ }
123
+ /** Fetch, then fast-forward the current branch to its upstream. Never a merge
124
+ * commit or a rebase: a branch that has diverged is refused by Git and the
125
+ * phone shows why. */
126
+ export async function gitPull(cwd) {
127
+ const root = await repository(cwd);
128
+ const { branch, remote, merge } = await upstreamOf(root);
129
+ if (!branch)
130
+ throw new BridgeError(409, "HEAD is detached. Check out a branch on the computer first.", { code: "git-detached" });
131
+ if (!remote || !merge)
132
+ throw new BridgeError(409, `${branch} has no upstream to pull from. Push it first.`, { code: "git-no-upstream" });
133
+ const before = (await git(root, "rev-parse", "HEAD")).trim();
134
+ countGit("projects");
135
+ invalidateTree(root);
136
+ const run = await runCombined("git", ["-C", root, "--no-pager", "pull", "--ff-only", "--no-rebase", "--no-tags", "--quiet", remote, merge], root, SYNC_TIMEOUT_MS);
137
+ invalidateTree(root);
138
+ if (run.code !== 0)
139
+ return refused(run, "git pull", SYNC_TIMEOUT_MS);
140
+ const after = (await git(root, "rev-parse", "HEAD")).trim();
141
+ const commits = before === after ? 0 : Number((await git(root, "rev-list", "--count", `${before}..${after}`)).trim()) || 0;
142
+ return { ok: true, branch, upstream: `${remote}/${merge.slice("refs/heads/".length)}`, commits, ...(run.output ? { output: run.output } : {}) };
143
+ }
@@ -1,4 +1,13 @@
1
1
  import { type Json } from "./protocol.js";
2
+ export { checkRollup, checkRuns } from "./git-hosts.js";
3
+ interface Counts {
4
+ additions: number;
5
+ deletions: number;
6
+ binary: boolean;
7
+ countsComplete: boolean;
8
+ }
9
+ /** NUL records preserve tabs/newlines in names and both sides of renames. */
10
+ export declare function parseNumstat(out: string): Map<string, Counts>;
2
11
  /** The remote's default branch as its `HEAD` records it. With no recorded
3
12
  * `HEAD`, `main` and `master` are treated as default so the guard errs on the
4
13
  * side of asking. */
@@ -39,14 +48,13 @@ export declare function gitStatus(cwd: string, untrackedPath?: string): Promise<
39
48
  export declare function gitLog(cwd: string, limit?: number, ref?: string): Promise<Json>;
40
49
  /** Local branches with their upstream and ahead/behind counts, and remote refs. */
41
50
  export declare function gitBranches(cwd: string): Promise<Json>;
42
- /** A check rollup as one word: any failure fails, anything unfinished is
43
- * pending, and only finished successes (or skips) pass. No checks is null. */
44
- export declare function checkRollup(items: unknown): "passing" | "failing" | "pending" | null;
45
- /** Open pull requests through `gh`, or `{ available: false }` when the tool is
46
- * missing or not signed in. A failure is a normal answer, never an error.
47
- * `current` is the checked-out branch's own pull request in any state (open,
48
- * draft, merged or closed) with its checks, which the session card shows. */
51
+ /** Open pull or merge requests and the checked-out branch's own (any state)
52
+ * with its checks, from whichever host the remote is on (git-hosts.ts). A
53
+ * host that cannot answer (a missing CLI, a stubbed provider, an unknown
54
+ * domain) is `{ available: false, reason, message }`, never an error. */
49
55
  export declare function gitPulls(cwd: string): Promise<Json>;
56
+ /** A repo-relative tree path, or the repository root for `""`. */
57
+ export declare function repositoryPath(root: string, raw: unknown, allowRoot?: boolean): Promise<string>;
50
58
  /** Drop the cached tree after a write (commit, push) outside this module. */
51
59
  export declare function invalidateTree(root: string): void;
52
60
  /** One lazy directory response from a bounded repo/HEAD/status-hash snapshot.
@@ -60,3 +68,8 @@ export declare function gitUnstage(cwd: string, paths: unknown): Promise<Json>;
60
68
  /** Destructive: tracked files go back to the index, untracked files are
61
69
  * removed. The phone confirms first; no `-d` (directories) and no `-x`. */
62
70
  export declare function gitDiscard(cwd: string, paths: unknown): Promise<Json>;
71
+ /** One commit as the phone's commit screen shows it: message, author and
72
+ * committer, parents and refs, and every file it changed against its first
73
+ * parent (what GitHub shows for a merge) with counts and a bounded patch in
74
+ * the same section shape `/v1/diff` uses. */
75
+ export declare function gitShow(cwd: string, sha: unknown): Promise<Json>;
@@ -1,11 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
- import { execFile } from "node:child_process";
3
2
  import { lstat, open, readdir, realpath } from "node:fs/promises";
4
3
  import path from "node:path";
5
- import { promisify } from "node:util";
6
4
  import { BridgeError } from "./protocol.js";
7
5
  import { git, gitHead, gitRoot, withGitReadDeadline } from "./projects.js";
8
- const exec = promisify(execFile);
6
+ import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
7
+ export { checkRollup, checkRuns } from "./git-hosts.js";
9
8
  /** A status code from `--name-status`: the letter alone, with `T` (type change)
10
9
  * shown as an edit and anything unrecognized treated as one. */
11
10
  function statusLetter(code) {
@@ -13,7 +12,7 @@ function statusLetter(code) {
13
12
  return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
14
13
  }
15
14
  /** NUL records preserve tabs/newlines in names and both sides of renames. */
16
- function parseNumstat(out) {
15
+ export function parseNumstat(out) {
17
16
  const map = new Map();
18
17
  const tokens = out.split("\0");
19
18
  for (let index = 0; index < tokens.length; index++) {
@@ -260,75 +259,20 @@ export async function gitBranches(cwd) {
260
259
  }
261
260
  return { current, local, remote };
262
261
  }
263
- const ghEnv = () => ({ ...process.env, GIT_CONFIG_NOSYSTEM: "1", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1" });
264
- /** A check rollup as one word: any failure fails, anything unfinished is
265
- * pending, and only finished successes (or skips) pass. No checks is null. */
266
- export function checkRollup(items) {
267
- if (!Array.isArray(items) || !items.length)
268
- return null;
269
- let pending = false;
270
- for (const raw of items) {
271
- const item = raw && typeof raw === "object" ? raw : {};
272
- const conclusion = String(item.conclusion ?? "").toUpperCase(), state = String(item.state ?? "").toUpperCase();
273
- const status = String(item.status ?? "").toUpperCase();
274
- if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"].includes(conclusion) || ["FAILURE", "ERROR"].includes(state))
275
- return "failing";
276
- // A commit status has a state; a check run has a status and, once
277
- // completed, a conclusion.
278
- if (state && !status) {
279
- if (state !== "SUCCESS")
280
- pending = true;
281
- }
282
- else if (status !== "COMPLETED")
283
- pending = true;
284
- }
285
- return pending ? "pending" : "passing";
286
- }
287
- /** The checked-out branch's pull request in any state, with its checks, or
288
- * null when the branch has none (or gh cannot say). */
289
- async function currentPull(root, branch) {
290
- try {
291
- const { stdout } = await exec("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
292
- cwd: root, timeout: 15_000, maxBuffer: 4_194_304, env: ghEnv(),
293
- });
294
- const pull = JSON.parse(stdout || "null");
295
- if (!pull || typeof pull !== "object" || typeof pull.number !== "number" || pull.headRefName !== branch)
296
- return null;
297
- return { number: pull.number, title: String(pull.title ?? ""), url: String(pull.url ?? ""), head: branch,
298
- base: String(pull.baseRefName ?? ""), draft: pull.isDraft === true, state: String(pull.state ?? ""), checks: checkRollup(pull.statusCheckRollup) };
299
- }
300
- catch {
301
- return null;
302
- }
303
- }
304
- /** Open pull requests through `gh`, or `{ available: false }` when the tool is
305
- * missing or not signed in. A failure is a normal answer, never an error.
306
- * `current` is the checked-out branch's own pull request in any state (open,
307
- * draft, merged or closed) with its checks, which the session card shows. */
262
+ /** Open pull or merge requests and the checked-out branch's own (any state)
263
+ * with its checks, from whichever host the remote is on (git-hosts.ts). A
264
+ * host that cannot answer (a missing CLI, a stubbed provider, an unknown
265
+ * domain) is `{ available: false, reason, message }`, never an error. */
308
266
  export async function gitPulls(cwd) {
309
267
  const root = await repository(cwd);
310
268
  const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
311
- try {
312
- const [{ stdout }, current] = await Promise.all([
313
- exec("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
314
- cwd: root, timeout: 15_000, maxBuffer: 4_194_304, env: ghEnv(),
315
- }),
316
- branch ? currentPull(root, branch) : Promise.resolve(null),
317
- ]);
318
- const parsed = JSON.parse(stdout || "[]");
319
- const pulls = (Array.isArray(parsed) ? parsed : []).map((pull) => {
320
- const author = pull.author && typeof pull.author === "object" ? pull.author : {};
321
- return { number: pull.number, title: pull.title, head: pull.headRefName, base: pull.baseRefName,
322
- author: String(author.login ?? author.name ?? ""), url: pull.url, draft: pull.isDraft === true, state: pull.state, updated: pull.updatedAt };
323
- });
324
- return { available: true, pulls, branch: branch || null, current };
325
- }
326
- catch {
327
- return { available: false, pulls: [], branch: branch || null, current: null };
328
- }
269
+ const host = await detectHost(root, branch);
270
+ const provider = providerFor(host);
271
+ const list = provider ? await provider.list(root, branch, host) : unknownHost(host);
272
+ return { ...list, branch: branch || null, host };
329
273
  }
330
274
  /** A repo-relative tree path, or the repository root for `""`. */
331
- async function repositoryPath(root, raw, allowRoot = false) {
275
+ export async function repositoryPath(root, raw, allowRoot = false) {
332
276
  if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path.isAbsolute(raw) || path.win32.isAbsolute(raw) || raw.startsWith("\\"))
333
277
  throw new BridgeError(400, "Invalid path.");
334
278
  const segments = raw.split(/[\\/]/);
@@ -591,3 +535,78 @@ export async function gitDiscard(cwd, paths) {
591
535
  treeCache.delete(root);
592
536
  }
593
537
  }
538
+ /** The empty tree's id in this repository's hash, the parent a root commit is
539
+ * compared with. */
540
+ async function emptyTree(root) {
541
+ return (await git(root, "hash-object", "-t", "tree", "/dev/null")).trim();
542
+ }
543
+ const MAX_SHOW_FILES = 300, MAX_SHOW_PATCH = 1_000_000, MAX_FILE_PATCH = 200_000;
544
+ /** One commit as the phone's commit screen shows it: message, author and
545
+ * committer, parents and refs, and every file it changed against its first
546
+ * parent (what GitHub shows for a merge) with counts and a bounded patch in
547
+ * the same section shape `/v1/diff` uses. */
548
+ export function gitShow(cwd, sha) {
549
+ return withGitReadDeadline(() => readGitShow(cwd, sha));
550
+ }
551
+ async function readGitShow(cwd, sha) {
552
+ if (typeof sha !== "string" || !/^[0-9a-fA-F]{4,64}$/.test(sha))
553
+ throw new BridgeError(400, "Name a commit by its hash.");
554
+ const root = await repository(cwd);
555
+ let commit;
556
+ try {
557
+ commit = (await git(root, "rev-parse", "--verify", "--end-of-options", `${sha}^{commit}`)).trim();
558
+ }
559
+ catch {
560
+ throw new BridgeError(404, "This repository has no such commit.", { code: "git-unknown-commit" });
561
+ }
562
+ const meta = await git(root, "show", "-s", "--decorate=short", "--format=%H%x00%h%x00%an%x00%ae%x00%aI%x00%cn%x00%cI%x00%P%x00%D%x00%B", commit);
563
+ const [full, short, author, authorEmail, date, committer, committed, parentList, spec, ...message] = meta.split("\0");
564
+ const body = message.join("\0").replace(/\n+$/, "");
565
+ const newline = body.indexOf("\n");
566
+ const subject = newline < 0 ? body : body.slice(0, newline);
567
+ const parents = (parentList ?? "").split(" ").filter(Boolean);
568
+ const base = parents[0] ?? await emptyTree(root);
569
+ const range = [base, commit];
570
+ const [names, counts] = await Promise.all([
571
+ git(root, "diff-tree", "-r", "-z", "-M", "--no-commit-id", "--name-status", ...range),
572
+ git(root, "diff-tree", "-r", "-z", "-M", "--no-commit-id", "--numstat", ...range),
573
+ ]);
574
+ const stats = parseNumstat(counts);
575
+ const tokens = names.split("\0");
576
+ const files = [];
577
+ let totalFiles = 0, truncated = false, remaining = MAX_SHOW_PATCH, additions = 0, deletions = 0;
578
+ for (let index = 0; index < tokens.length; index++) {
579
+ const code = tokens[index];
580
+ if (!code)
581
+ continue;
582
+ const renamed = /^[RC]/.test(code);
583
+ const oldPath = renamed ? tokens[++index] : undefined, file = tokens[++index];
584
+ if (!file)
585
+ break;
586
+ totalFiles++;
587
+ const count = stats.get(file) ?? { additions: 0, deletions: 0, binary: false, countsComplete: false };
588
+ additions += count.additions;
589
+ deletions += count.deletions;
590
+ if (files.length >= MAX_SHOW_FILES) {
591
+ truncated = true;
592
+ continue;
593
+ }
594
+ const status = statusLetter(code);
595
+ let section;
596
+ if (remaining <= 0 || count.binary) {
597
+ section = { id: `commit:${file}`, kind: "commit", binary: count.binary, loadState: "loaded", patch: "", truncated: !count.binary };
598
+ truncated ||= !count.binary;
599
+ }
600
+ else {
601
+ const patch = await git(root, ...NO_DIFF, "-M", ...range, "--", ...[file, ...(oldPath ? [oldPath] : [])].map(name => `:(literal)${name}`));
602
+ const limit = Math.min(MAX_FILE_PATCH, remaining), clipped = patch.length > limit;
603
+ section = { id: `commit:${file}`, kind: "commit", binary: /^(?:Binary files |GIT binary patch)/m.test(patch), loadState: "loaded", patch: patch.slice(0, limit), truncated: clipped };
604
+ remaining -= Math.min(patch.length, limit);
605
+ truncated ||= clipped;
606
+ }
607
+ files.push({ path: file, ...(oldPath ? { oldPath } : {}), status, additions: count.additions, deletions: count.deletions,
608
+ binary: count.binary, countsComplete: count.countsComplete, sections: [section] });
609
+ }
610
+ return { sha: full, short, subject, body: newline < 0 ? "" : body.slice(newline + 1).replace(/^\n+/, ""), author, authorEmail, date,
611
+ committer, committed, parents, refs: refEntries(spec ?? "", await remotes(root)), files, totalFiles, additions, deletions, truncated };
612
+ }
@@ -0,0 +1,32 @@
1
+ import { z } from "zod";
2
+ export declare const PROJECT_NAME: RegExp;
3
+ export declare const FINDING_TYPE_VALUES: readonly ["decision", "pitfall", "pattern", "bug"];
4
+ export declare const MAX_FILE_PATHS = 500;
5
+ export declare const MAX_SEARCH_QUERY = 1000;
6
+ export declare const MAX_SEARCH_LIMIT = 20;
7
+ export declare const MAX_FINDING_BODY = 8192;
8
+ export declare const MAX_FINDING_TEXT = 5000;
9
+ /** A repository-relative path: `/`-separated segments of ordinary file-name
10
+ * characters, no empty, `.` or `..` segment, no leading `/`, at most 1024. */
11
+ export declare function isRepoPath(value: string): boolean;
12
+ /** A branch as git allows it, narrowed: no `..`, `@{`, leading `-` or `/`,
13
+ * trailing `/`, `.lock` or `.`, at most 200 characters. */
14
+ export declare function isBranchName(value: string): boolean;
15
+ /** Search text: an error excerpt may carry tabs and newlines, nothing else below space. */
16
+ export declare function isSearchText(value: string): boolean;
17
+ export declare const findingWriteSchema: z.ZodObject<{
18
+ text: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
19
+ type: z.ZodOptional<z.ZodEnum<{
20
+ bug: "bug";
21
+ decision: "decision";
22
+ pattern: "pattern";
23
+ pitfall: "pitfall";
24
+ }>>;
25
+ citation: z.ZodOptional<z.ZodObject<{
26
+ file: z.ZodOptional<z.ZodString>;
27
+ line: z.ZodOptional<z.ZodNumber>;
28
+ commit: z.ZodOptional<z.ZodString>;
29
+ name: z.ZodOptional<z.ZodString>;
30
+ }, z.core.$strict>>;
31
+ }, z.core.$strict>;
32
+ export type FindingWrite = z.infer<typeof findingWriteSchema>;
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ // The grammar gitboy's routes accept, shared by the scoped SSH gateway (which
3
+ // refuses anything else before the Hook sees it) and the Hook routes (which
4
+ // apply it again for every other caller). Kept free of node and store imports
5
+ // so the gateway stays cheap to start.
6
+ export const PROJECT_NAME = /^[a-z0-9][a-z0-9_-]{0,99}$/;
7
+ export const FINDING_TYPE_VALUES = ["decision", "pitfall", "pattern", "bug"];
8
+ export const MAX_FILE_PATHS = 500;
9
+ export const MAX_SEARCH_QUERY = 1000;
10
+ export const MAX_SEARCH_LIMIT = 20;
11
+ export const MAX_FINDING_BODY = 8192;
12
+ export const MAX_FINDING_TEXT = 5000;
13
+ /** A repository-relative path: `/`-separated segments of ordinary file-name
14
+ * characters, no empty, `.` or `..` segment, no leading `/`, at most 1024. */
15
+ export function isRepoPath(value) {
16
+ if (value.length < 1 || value.length > 1024)
17
+ return false;
18
+ if (!/^[A-Za-z0-9 ._@+~,=()[\]{}#!$&'-]+(?:\/[A-Za-z0-9 ._@+~,=()[\]{}#!$&'-]+)*$/.test(value))
19
+ return false;
20
+ return value.split("/").every(segment => segment !== "." && segment !== ".." && segment.trim() === segment);
21
+ }
22
+ /** A branch as git allows it, narrowed: no `..`, `@{`, leading `-` or `/`,
23
+ * trailing `/`, `.lock` or `.`, at most 200 characters. */
24
+ export function isBranchName(value) {
25
+ if (!/^[A-Za-z0-9._\/+-]{1,200}$/.test(value))
26
+ return false;
27
+ if (value.startsWith("-") || value.startsWith("/") || value.endsWith("/") || value.endsWith(".") || value.endsWith(".lock"))
28
+ return false;
29
+ return !value.includes("..") && !value.includes("//") && !value.split("/").some(part => part.startsWith("."));
30
+ }
31
+ /** Search text: an error excerpt may carry tabs and newlines, nothing else below space. */
32
+ export function isSearchText(value) {
33
+ return value.trim().length > 0 && value.length <= MAX_SEARCH_QUERY && !/[\x00-\x08\x0b-\x1f\x7f]/.test(value);
34
+ }
35
+ const noControls = (value) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value);
36
+ export const findingWriteSchema = z.object({
37
+ text: z.string().max(MAX_FINDING_TEXT).refine(noControls, "Text may contain tabs and newlines but no other control characters.")
38
+ .transform(value => value.replace(/\s+/g, " ").trim()).refine(value => value.length > 0, "Text is empty."),
39
+ type: z.enum(FINDING_TYPE_VALUES).optional(),
40
+ citation: z.object({
41
+ file: z.string().refine(isRepoPath, "citation.file must be a repository-relative path.").optional(),
42
+ line: z.number().int().min(1).max(10_000_000).optional(),
43
+ commit: z.string().regex(/^[0-9a-fA-F]{7,64}$/).optional(),
44
+ name: z.string().min(1).max(200).refine(value => !/[\x00-\x1f\x7f]/.test(value)).optional(),
45
+ }).strict().optional(),
46
+ }).strict();