@juanem1/pi-git 0.0.0-stage → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## [0.2.0]
4
+
5
+ - Add `--git-allow` / `PI_GIT_ALLOW` to pre-authorize specific mutations
6
+ (`commit`, `push`, `worktree_add`, `worktree_remove`, `worktree_prune`) for
7
+ RPC and CI runs. Nothing is pre-authorized by default, and invalid values block
8
+ mutations.
9
+ - In RPC mode, a refused confirmation now says that the user may have declined or
10
+ the client may have dismissed the dialog without asking anyone. It also
11
+ points to `--git-allow` and sends a `notify` warning to the client.
12
+
13
+ ## [0.1.0]
14
+
15
+ - Initial release: `git_status`, `git_diff`, `git_log`, `git_show`, `git_commit`,
16
+ `git_push`, and `git_worktree_*` tools, with confirmation for every mutation.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 juanem1
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,132 @@
1
- # Temporary Holding Version
1
+ # Package pi-git
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Pi package for Git, with no npm dependencies or installation scripts.
4
+ Commits, pushes, and worktree changes require individual confirmation, unless
5
+ the person running Pi pre-authorizes them (see [Runs without a person](#runs-without-a-person-rpc-and-ci)).
6
+ It does not add co-authors or impose a commit message format.
7
+
8
+ ## Requirements
9
+
10
+ - [Pi](https://pi.dev)
11
+ - Git
12
+ - Node.js 22 or later
13
+
14
+ ## Install in Pi
15
+
16
+ Install from npm:
17
+
18
+ ```sh
19
+ pi install npm:@juanem1/pi-git
20
+ ```
21
+
22
+ Or from a local clone:
23
+
24
+ ```sh
25
+ git clone https://github.com/juanem1/pi-git.git
26
+ pi install ./pi-git
27
+ ```
28
+
29
+ Add `-l` to install it only for the current project (`.pi/settings.json`).
30
+ Restart Pi or run `/reload` if it is already open.
31
+
32
+ To try it without installing, from a local clone:
33
+
34
+ ```sh
35
+ pi -e ./pi-git
36
+ ```
37
+
38
+ To update or uninstall:
39
+
40
+ ```sh
41
+ pi update npm:@juanem1/pi-git
42
+ pi remove npm:@juanem1/pi-git
43
+ ```
44
+
45
+ ## Tools
46
+
47
+ | Tool | Behavior |
48
+ |---|---|
49
+ | `git_status` | Branch, staged, modified, and new files. |
50
+ | `git_diff` | Local or staged diff, or diff against a revision; optional literal paths. |
51
+ | `git_log` | Up to 200 commits; 20 by default. |
52
+ | `git_show` | Commit message and diff. |
53
+ | `git_commit` | Confirms the message, branch, and files; commits only those complete files, without pushing. |
54
+ | `git_push` | Confirms the remote, destination, branch, and commit; pushes only the current branch. |
55
+ | `git_worktree_list` | Lists existing worktrees. |
56
+ | `git_worktree_add` | Confirms a new path and branch; does not change the current worktree's branch. |
57
+ | `git_worktree_remove` | Confirms removal of a clean worktree; preserves its branch. |
58
+ | `git_worktree_prune` | Previews and confirms cleanup of metadata for missing worktrees. |
59
+
60
+ File paths are relative to the root of the current repository. Commit does not
61
+ accept directories: list individual files and both paths of a renamed file.
62
+ If a file is partially staged, its entire working tree content is committed.
63
+ Other already-staged files are excluded from the commit.
64
+
65
+ ## Security limits
66
+
67
+ - Runs only `git`, with separate arguments and no shell. It does not use `eval`,
68
+ downloads, cleanup commands, or background processes.
69
+ - Does not offer reset, discarding changes, rebase, amend, force push, branch
70
+ deletion, or forced worktree removal.
71
+ - Refuses to remove worktrees with modified, new, or ignored files, as well as
72
+ the main, current, or locked worktrees.
73
+ - Push requires an explicit remote with a single HTTPS/SSH URL. It does not
74
+ accept local paths, remote helpers, tags, or refspecs from the model.
75
+ - Mutations are rejected without a Pi confirmation interface, unless they are
76
+ pre-authorized with `--git-allow` or `PI_GIT_ALLOW`. Nothing is pre-authorized
77
+ by default.
78
+ - In RPC mode (`pi --mode rpc`) Pi reports an interface and sends each
79
+ confirmation to the client as an `extension_ui_request` (`method: "confirm"`).
80
+ Pi turns a `cancelled: true` response into the same `false` as an explicit
81
+ "No", so the extension cannot tell them apart. In RPC mode a refusal says so,
82
+ and the client also gets a `notify` warning.
83
+ - Does not disable hooks or configured signing. Git hooks, filters, and transports
84
+ can run programs from the repository or environment: use trusted repositories
85
+ and Git configurations.
86
+
87
+ ### Runs without a person (RPC and CI)
88
+
89
+ A client with nobody to answer the dialogs can pre-authorize specific mutations
90
+ for the whole run, with a comma-separated list:
91
+
92
+ ```sh
93
+ pi --mode rpc --git-allow commit
94
+ PI_GIT_ALLOW=commit,push pi -p "..."
95
+ ```
96
+
97
+ Accepted values: `commit`, `push`, `worktree_add`, `worktree_remove`,
98
+ `worktree_prune`. There is no `all`. An unknown value, or `--git-allow` without
99
+ a value, blocks every mutation with an error. If both are set, `--git-allow`
100
+ wins over `PI_GIT_ALLOW`, so `--git-allow ""` turns the variable off.
101
+ Authorizing `commit` does not authorize `push` or any worktree change.
102
+
103
+ Pre-authorization only skips the dialog. Every other check still runs: explicit
104
+ files, branch rechecks, HTTPS/SSH remotes only, and clean worktrees only. When
105
+ there is an interface, each pre-authorized mutation sends an `info`
106
+ notification with the same details as the dialog. The model cannot turn it on
107
+ from the session: the flag and the environment variable are read from the Pi
108
+ process. A variable left in your shell profile also applies to interactive
109
+ sessions.
110
+
111
+ This **is not a sandbox** and does not block Pi's general Bash access or other
112
+ extensions. Queries disable external diff, textconv, and signature verification.
113
+ Large outputs are explicitly limited; a process that exceeds 120 seconds or
114
+ 4 MiB of output fails. If a mutation fails, check the status before retrying.
115
+
116
+ ## Development
117
+
118
+ No `npm install` is needed.
119
+
120
+ ```sh
121
+ npm test
122
+ ```
123
+
124
+ ## Release
125
+
126
+ Publishing runs in GitHub Actions with npm trusted publishing when a `v*` tag is
127
+ pushed. Add the version's entry to `CHANGELOG.md`, then:
128
+
129
+ ```sh
130
+ npm version patch # or minor / major; commits and tags vX.Y.Z
131
+ git push --follow-tags
132
+ ```
@@ -0,0 +1,112 @@
1
+ import { AUTHORIZABLE, createGitOperations, parseAuthorizations, runGit } from "../src/git.js";
2
+
3
+ const string = (description) => ({ type: "string", minLength: 1, description });
4
+ const paths = {
5
+ type: "array",
6
+ items: string("Literal path relative to the repository root, not a glob."),
7
+ minItems: 1,
8
+ uniqueItems: true,
9
+ };
10
+ const ref = string("Git revision or range, never a command-line option.");
11
+
12
+ export default function (pi) {
13
+ pi.registerFlag("git-allow", {
14
+ type: "string",
15
+ description: `Pre-authorize Git mutations without confirmation, comma-separated: ${AUTHORIZABLE.join(", ")}. Overrides PI_GIT_ALLOW.`,
16
+ });
17
+ // Read on every mutation so an invalid value fails that mutation loudly instead of loading silently.
18
+ const operations = createGitOperations(runGit, () => parseAuthorizations(
19
+ pi.getFlag("git-allow") ?? process.env.PI_GIT_ALLOW,
20
+ ));
21
+ const register = (name, description, properties = {}, required = [], mutating = false) => {
22
+ pi.registerTool({
23
+ name,
24
+ label: name.replaceAll("_", " "),
25
+ description,
26
+ promptSnippet: description,
27
+ annotations: {
28
+ readOnlyHint: !mutating,
29
+ destructiveHint: name === "git_worktree_remove" || name === "git_worktree_prune",
30
+ idempotentHint: !mutating,
31
+ openWorldHint: name === "git_push",
32
+ },
33
+ executionMode: mutating ? "sequential" : "parallel",
34
+ parameters: { type: "object", properties, required, additionalProperties: false },
35
+ async execute(_id, params, signal, _update, ctx) {
36
+ const output = await operations[name](params, ctx, signal);
37
+ const limit = 40_000;
38
+ const truncated = output.length > limit;
39
+ return {
40
+ content: [{
41
+ type: "text",
42
+ text: truncated
43
+ ? `${output.slice(0, limit)}\n[Output truncated; narrow the paths, revision or count.]`
44
+ : output || "No output.",
45
+ }],
46
+ details: { truncated },
47
+ };
48
+ },
49
+ });
50
+ };
51
+
52
+ register("git_status", "Read the current repository's branch and staged, unstaged, and untracked paths.");
53
+ register("git_diff", "Read a diff of the working tree, index, or a revision; external diff programs are disabled.", {
54
+ staged: { type: "boolean", description: "Compare the index instead of the working tree." },
55
+ base: ref,
56
+ paths,
57
+ stat: { type: "boolean", description: "Show only the diffstat." },
58
+ });
59
+ register("git_log", "Read recent commits without running signature verification.", {
60
+ ref,
61
+ count: { type: "integer", minimum: 1, maximum: 200, description: "Maximum commits; default 20." },
62
+ paths,
63
+ });
64
+ register("git_show", "Read one commit's message and diff without external diff programs or text conversion.", {
65
+ ref: string("One commit or tag; default HEAD."),
66
+ paths,
67
+ stat: { type: "boolean", description: "Show metadata and diffstat, without the patch." },
68
+ });
69
+ register(
70
+ "git_commit",
71
+ "After user confirmation, stage and commit only explicitly named files on the current branch. Never push or append coauthors. Include both paths of a rename.",
72
+ {
73
+ message: string("Complete commit message, passed verbatim without automatic attribution."),
74
+ paths,
75
+ },
76
+ ["message", "paths"],
77
+ true,
78
+ );
79
+ register(
80
+ "git_push",
81
+ "After separate user confirmation, push only the current branch to one named HTTPS/SSH remote. Never force, delete, mirror, or push tags.",
82
+ { remote: string("Existing remote name, for example origin. No URL or command.") },
83
+ ["remote"],
84
+ true,
85
+ );
86
+ register("git_worktree_list", "Read this repository's worktrees without changing them.");
87
+ register(
88
+ "git_worktree_add",
89
+ "After user confirmation, create a worktree at an explicit path without switching the current worktree's branch or overwriting files.",
90
+ {
91
+ branch: string("Branch to create or check out in the new worktree."),
92
+ path: string("Destination directory, absolute or relative to the repository root."),
93
+ base: string("Starting commit for a new branch; default HEAD. Omit for an existing branch."),
94
+ },
95
+ ["branch", "path"],
96
+ true,
97
+ );
98
+ register(
99
+ "git_worktree_remove",
100
+ "After user confirmation, remove only a clean linked worktree. Refuse modified, untracked, ignored, locked, main, or current worktrees. Keep the branch.",
101
+ { path: string("Worktree directory, absolute or relative to the repository root.") },
102
+ ["path"],
103
+ true,
104
+ );
105
+ register(
106
+ "git_worktree_prune",
107
+ "Preview stale worktree metadata, then ask for confirmation before pruning it. Never delete worktree directories.",
108
+ {},
109
+ [],
110
+ true,
111
+ );
112
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@juanem1/pi-git",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Focused Git tools for Pi with explicit confirmation for mutations.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "juanem1",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/juanem1/pi-git.git"
11
+ },
12
+ "homepage": "https://github.com/juanem1/pi-git#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/juanem1/pi-git/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi",
19
+ "git"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "files": [
25
+ "extensions",
26
+ "src",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE"
30
+ ],
31
+ "pi": {
32
+ "extensions": [
33
+ "./extensions/git.js"
34
+ ]
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "registry": "https://registry.npmjs.org/"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test"
42
+ }
43
+ }
package/src/git.js ADDED
@@ -0,0 +1,416 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstat, realpath } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, normalize, relative, resolve, sep } from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const exec = promisify(execFile);
7
+
8
+ export async function runGit(args, cwd, signal, includeStderr = false) {
9
+ const env = {
10
+ ...process.env,
11
+ GIT_TERMINAL_PROMPT: "0",
12
+ GIT_PAGER: "cat",
13
+ GIT_EDITOR: "true",
14
+ GIT_SEQUENCE_EDITOR: "true",
15
+ GIT_OPTIONAL_LOCKS: "0",
16
+ GIT_NO_LAZY_FETCH: "1",
17
+ LC_ALL: "C",
18
+ };
19
+ for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE",
20
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE"]) {
21
+ delete env[key];
22
+ }
23
+ try {
24
+ const result = await exec("git", [
25
+ "--no-pager", "--literal-pathspecs", "-c", "core.fsmonitor=false", ...args,
26
+ ], { cwd, env, signal, timeout: 120_000, maxBuffer: 4 * 1024 * 1024, shell: false });
27
+ return result.stdout + (includeStderr ? result.stderr : "");
28
+ } catch (error) {
29
+ const detail = error.stderr?.trim() || error.message;
30
+ throw Object.assign(new Error(`Git failed: ${detail}`, { cause: error }), { code: error.code });
31
+ }
32
+ }
33
+
34
+ function text(value, label) {
35
+ if (typeof value !== "string" || !value.trim() || /[\x00-\x1f\x7f]/.test(value)) {
36
+ throw new Error(`${label} must be nonempty and contain no control characters.`);
37
+ }
38
+ return value;
39
+ }
40
+
41
+ function revision(value) {
42
+ text(value, "Revision");
43
+ if (value.startsWith("-") || value !== value.trim()) {
44
+ throw new Error("Revision must not be an option or contain surrounding whitespace.");
45
+ }
46
+ return value;
47
+ }
48
+
49
+ function literalPaths(values, required = false) {
50
+ if (values === undefined && !required) {
51
+ return [];
52
+ }
53
+ if (!Array.isArray(values) || !values.length) {
54
+ throw new Error("Name at least one explicit file.");
55
+ }
56
+ return values.map((value) => {
57
+ text(value, "Path");
58
+ if (isAbsolute(value) || value.startsWith("-") || value.startsWith(":")
59
+ || value.split(/[\\/]/).some((part) => part === ".." || part.toLowerCase() === ".git")
60
+ || !value.split("/").some((part) => part && part !== ".")
61
+ || value === "*" || value === "**") {
62
+ throw new Error(`Not an explicit repository-relative path: ${JSON.stringify(value)}`);
63
+ }
64
+ return normalize(value);
65
+ });
66
+ }
67
+
68
+ async function validateFiles(selected, cwd, signal, run) {
69
+ for (const path of selected) {
70
+ const parent = await canonicalPath(dirname(resolve(cwd, path)));
71
+ if (!inside(parent, cwd)) {
72
+ throw new Error("File parent resolves outside the repository.");
73
+ }
74
+ try {
75
+ if ((await lstat(resolve(cwd, path))).isDirectory()) {
76
+ throw new Error("Name individual files, not directories.");
77
+ }
78
+ } catch (error) {
79
+ if (error.code !== "ENOENT") {
80
+ throw error;
81
+ }
82
+ }
83
+ const tracked = (await run(["ls-files", "-z", "--", path], cwd, signal)).split("\0").filter(Boolean);
84
+ if (tracked.some((entry) => entry !== path)) {
85
+ throw new Error("Name individual files, not deleted directories.");
86
+ }
87
+ }
88
+ }
89
+
90
+ async function canonicalPath(path) {
91
+ const missing = [];
92
+ while (true) {
93
+ try {
94
+ return resolve(await realpath(path), ...missing);
95
+ } catch (error) {
96
+ if (error.code !== "ENOENT") {
97
+ throw error;
98
+ }
99
+ missing.unshift(basename(path));
100
+ path = dirname(path);
101
+ }
102
+ }
103
+ }
104
+
105
+ export function parseWorktrees(output) {
106
+ return output.split("\0\0").filter(Boolean).map((record) => {
107
+ const fields = record.split("\0");
108
+ return {
109
+ path: fields.find((field) => field.startsWith("worktree "))?.slice(9),
110
+ locked: fields.some((field) => field === "locked" || field.startsWith("locked ")),
111
+ bare: fields.includes("bare"),
112
+ };
113
+ });
114
+ }
115
+
116
+ function inside(path, parent) {
117
+ const rest = relative(parent, path);
118
+ return !rest || (!isAbsolute(rest) && rest !== ".." && !rest.startsWith(`..${sep}`));
119
+ }
120
+
121
+ export const AUTHORIZABLE = ["commit", "push", "worktree_add", "worktree_remove", "worktree_prune"];
122
+
123
+ // Parses the --git-allow / PI_GIT_ALLOW value: a comma-separated list of AUTHORIZABLE operations.
124
+ // Anything else (including a bare flag without a value) is an error, so a typo never widens access.
125
+ export function parseAuthorizations(value) {
126
+ if (value === undefined || value === null || value === "") {
127
+ return new Set();
128
+ }
129
+ if (typeof value !== "string") {
130
+ throw new Error(`--git-allow needs a value: a comma-separated list of ${AUTHORIZABLE.join(", ")}.`);
131
+ }
132
+ const items = value.split(",").map((item) => item.trim()).filter(Boolean);
133
+ for (const item of items) {
134
+ if (!AUTHORIZABLE.includes(item)) {
135
+ throw new Error(
136
+ `Unknown --git-allow operation ${JSON.stringify(item)}; use a comma-separated list of ${AUTHORIZABLE.join(", ")}. No changes were made.`,
137
+ );
138
+ }
139
+ }
140
+ return new Set(items);
141
+ }
142
+
143
+ async function confirm(ctx, signal, authorizations, operation, title, description) {
144
+ signal?.throwIfAborted();
145
+ if (authorizations().has(operation)) {
146
+ if (ctx.hasUI) {
147
+ ctx.ui.notify?.(`${title}: pre-authorized by --git-allow ${operation}.\n${description}`, "info");
148
+ }
149
+ return;
150
+ }
151
+ const hint = `A run without a person to answer can pre-authorize it with --git-allow ${operation}.`;
152
+ if (!ctx.hasUI) {
153
+ throw new Error(`Interactive confirmation is required; no changes were made. ${hint}`);
154
+ }
155
+ if (!await ctx.ui.confirm(title, description)) {
156
+ if (ctx.mode === "rpc") {
157
+ // Pi maps an RPC client's `cancelled` response to `false`, the same as an explicit "No".
158
+ ctx.ui.notify?.(`pi-git: "${title}" was not confirmed; nothing changed. ${hint}`, "warning");
159
+ throw new Error(
160
+ "Not confirmed: the user declined, or the RPC client dismissed the dialog without asking anyone; "
161
+ + `no changes were made. ${hint}`,
162
+ );
163
+ }
164
+ throw new Error("Cancelled; no changes were made.");
165
+ }
166
+ signal?.throwIfAborted();
167
+ }
168
+
169
+ export function createGitOperations(run = runGit, authorizations = () => new Set()) {
170
+ const root = async (ctx, signal) => realpath(
171
+ (await run(["rev-parse", "--show-toplevel"], ctx.cwd, signal)).replace(/\r?\n$/, ""),
172
+ );
173
+ const branch = async (cwd, signal) => {
174
+ let ref;
175
+ try {
176
+ ref = (await run(["symbolic-ref", "--quiet", "HEAD"], cwd, signal)).trim();
177
+ } catch (error) {
178
+ if (error.code !== 1) {
179
+ throw error;
180
+ }
181
+ throw new Error("Not on a branch (detached HEAD); commit and push need a branch.", { cause: error });
182
+ }
183
+ if (!ref.startsWith("refs/heads/")) {
184
+ throw new Error("Not on a branch; commit and push need a branch.");
185
+ }
186
+ return revision(ref.slice("refs/heads/".length));
187
+ };
188
+ const commitId = async (ref, cwd, signal) => {
189
+ const sha = (await run(
190
+ ["rev-parse", "--verify", "--end-of-options", `${revision(ref)}^{commit}`], cwd, signal,
191
+ )).trim();
192
+ if (!/^[a-f0-9]{40,64}$/.test(sha)) {
193
+ throw new Error("Git returned an invalid commit ID.");
194
+ }
195
+ return sha;
196
+ };
197
+ const unchangedBranch = async (expected, cwd, signal) => {
198
+ if (await branch(cwd, signal) !== expected) {
199
+ throw new Error("The current branch changed during confirmation. Review and retry.");
200
+ }
201
+ };
202
+ const entries = async (cwd, signal) => parseWorktrees(
203
+ await run(["worktree", "list", "--porcelain", "-z"], cwd, signal),
204
+ );
205
+
206
+ async function removable(target, cwd, ctx, signal) {
207
+ const list = await entries(cwd, signal);
208
+ const entry = list.find((item) => item.path === target);
209
+ if (!entry || entry === list[0] || entry.bare || entry.locked) {
210
+ throw new Error("Refusing to remove an unknown, main, bare, or locked worktree.");
211
+ }
212
+ if (inside(await realpath(ctx.cwd), target) || inside(cwd, target)) {
213
+ throw new Error("Refusing to remove the current worktree or a parent directory.");
214
+ }
215
+ const status = await run([
216
+ "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching",
217
+ "--ignore-submodules=none",
218
+ ], target, signal);
219
+ if (status) {
220
+ throw new Error("Worktree contains modified, untracked, or ignored files; nothing was removed.");
221
+ }
222
+ }
223
+
224
+ async function pushUrl(remote, cwd, signal) {
225
+ if (typeof remote !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote)) {
226
+ throw new Error("Use an existing remote name, not a URL, option, or command.");
227
+ }
228
+ const urls = (await run(["remote", "get-url", "--push", "--all", remote], cwd, signal))
229
+ .replace(/\r?\n$/, "").split("\n");
230
+ if (urls.length !== 1) {
231
+ throw new Error("Remote must have exactly one push URL.");
232
+ }
233
+ const url = text(urls[0], "Push URL");
234
+ if (!/^(?:https|ssh):\/\/[^/\s]+\/\S+$/.test(url)
235
+ && !/^[^@\s/:]+@[^@\s/:]+:(?!:|\/\/)\S+$/.test(url)) {
236
+ throw new Error("Only HTTPS and SSH remotes are supported; no local paths or remote helpers.");
237
+ }
238
+ return url;
239
+ }
240
+
241
+ return {
242
+ async git_status(_params, ctx, signal) {
243
+ return run(["status", "--short", "--branch", "--untracked-files=all"], await root(ctx, signal), signal);
244
+ },
245
+
246
+ async git_diff(params, ctx, signal) {
247
+ const selected = literalPaths(params.paths);
248
+ return run([
249
+ "diff", "--no-color", "--no-ext-diff", "--no-textconv",
250
+ ...(params.staged ? ["--cached"] : []),
251
+ ...(params.stat ? ["--stat"] : []),
252
+ ...(params.base === undefined ? [] : ["--end-of-options", revision(params.base)]),
253
+ "--", ...selected,
254
+ ], await root(ctx, signal), signal);
255
+ },
256
+
257
+ async git_log(params, ctx, signal) {
258
+ const count = params.count ?? 20;
259
+ if (!Number.isInteger(count) || count < 1 || count > 200) {
260
+ throw new Error("Count must be between 1 and 200.");
261
+ }
262
+ return run([
263
+ "log", "--no-color", "--no-show-signature", `--max-count=${count}`,
264
+ "--format=%h %aI %an: %s",
265
+ ...(params.ref === undefined ? [] : ["--end-of-options", revision(params.ref)]),
266
+ "--", ...literalPaths(params.paths),
267
+ ], await root(ctx, signal), signal);
268
+ },
269
+
270
+ async git_show(params, ctx, signal) {
271
+ const cwd = await root(ctx, signal);
272
+ const sha = await commitId(params.ref ?? "HEAD", cwd, signal);
273
+ return run([
274
+ "show", "--no-color", "--no-ext-diff", "--no-textconv", "--no-show-signature",
275
+ "--format=fuller", "--stat", ...(params.stat ? [] : ["--patch"]),
276
+ "--end-of-options", sha, "--", ...literalPaths(params.paths),
277
+ ], cwd, signal);
278
+ },
279
+
280
+ async git_commit(params, ctx, signal) {
281
+ const selected = literalPaths(params.paths, true);
282
+ if (typeof params.message !== "string" || !params.message.trim()
283
+ || /[\x00-\x08\x0b-\x1f\x7f]/.test(params.message)) {
284
+ throw new Error("Provide a nonempty commit message without control characters other than tabs/newlines.");
285
+ }
286
+ const cwd = await root(ctx, signal);
287
+ const expected = await branch(cwd, signal);
288
+ await validateFiles(selected, cwd, signal, run);
289
+ await confirm(ctx, signal, authorizations, "commit", "Confirm Git commit",
290
+ `Repository: ${JSON.stringify(cwd)}\nBranch: ${JSON.stringify(expected)}\n`
291
+ + `Files: ${JSON.stringify(selected)}\nMessage: ${JSON.stringify(params.message)}\n\n`
292
+ + "Commit the complete working-tree contents of these files only. No push or automatic coauthors.\n"
293
+ + "Hooks and configured signing will run. A failure may leave these files staged.");
294
+ await unchangedBranch(expected, cwd, signal);
295
+ await validateFiles(selected, cwd, signal, run);
296
+ const deleted = new Set((await run(
297
+ ["diff", "--cached", "--name-only", "--diff-filter=D", "-z", "--", ...selected], cwd, signal,
298
+ )).split("\0"));
299
+ const toAdd = selected.filter((path) => !deleted.has(path));
300
+ try {
301
+ if (toAdd.length) {
302
+ await run(["add", "--", ...toAdd], cwd, signal);
303
+ }
304
+ await unchangedBranch(expected, cwd, signal);
305
+ const output = await run([
306
+ "commit", "--only", "--cleanup=verbatim", "-m", params.message, "--", ...selected,
307
+ ], cwd, signal);
308
+ return `${output.trimEnd()}\nCommit completed. No push performed.`;
309
+ } catch (error) {
310
+ throw new Error(
311
+ `${error.message}\nThe index may contain the selected files. Inspect git_status and git_log before retrying; do not assume no commit was created.`,
312
+ { cause: error },
313
+ );
314
+ }
315
+ },
316
+
317
+ async git_push(params, ctx, signal) {
318
+ const cwd = await root(ctx, signal);
319
+ const expected = await branch(cwd, signal);
320
+ const sha = await commitId("HEAD", cwd, signal);
321
+ const url = await pushUrl(params.remote, cwd, signal);
322
+ await confirm(ctx, signal, authorizations, "push", "Confirm Git push",
323
+ `Repository: ${JSON.stringify(cwd)}\nRemote: ${JSON.stringify(params.remote)}\n`
324
+ + `Destination: ${JSON.stringify(url)}\nBranch: ${JSON.stringify(expected)}\nCommit: ${sha}\n\n`
325
+ + "Publish only this commit to the same branch name. No force, tags, deletion, or upstream changes.");
326
+ await unchangedBranch(expected, cwd, signal);
327
+ if (await commitId("HEAD", cwd, signal) !== sha || await pushUrl(params.remote, cwd, signal) !== url) {
328
+ throw new Error("HEAD or the push destination changed during confirmation. Review and retry.");
329
+ }
330
+ return run([
331
+ "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "protocol.ssh.allow=always",
332
+ "push", "--porcelain", "--no-force", "--no-mirror", "--no-follow-tags", "--recurse-submodules=no",
333
+ params.remote, `${sha}:refs/heads/${expected}`,
334
+ ], cwd, signal);
335
+ },
336
+
337
+ async git_worktree_list(_params, ctx, signal) {
338
+ return run(["worktree", "list"], await root(ctx, signal), signal);
339
+ },
340
+
341
+ async git_worktree_add(params, ctx, signal) {
342
+ const name = revision(params.branch);
343
+ text(params.path, "Worktree path");
344
+ const cwd = await root(ctx, signal);
345
+ await run(["check-ref-format", `refs/heads/${name}`], cwd, signal);
346
+ const target = await canonicalPath(resolve(cwd, params.path));
347
+ const main = (await entries(cwd, signal))[0]?.path ?? cwd;
348
+ if ([cwd, main].some((repo) => inside(repo, target) || inside(target, repo))) {
349
+ throw new Error("New worktree must be outside the current and main repository.");
350
+ }
351
+ try {
352
+ await lstat(target);
353
+ throw new Error("Destination already exists; choose a new directory.");
354
+ } catch (error) {
355
+ if (error.code !== "ENOENT") {
356
+ throw error;
357
+ }
358
+ }
359
+ let exists = true;
360
+ try {
361
+ await run(["show-ref", "--verify", "--quiet", `refs/heads/${name}`], cwd, signal);
362
+ } catch (error) {
363
+ if (error.code !== 1) {
364
+ throw error;
365
+ }
366
+ exists = false;
367
+ }
368
+ if (exists && params.base !== undefined) {
369
+ throw new Error("Branch already exists; omit base.");
370
+ }
371
+ const base = exists ? undefined : await commitId(params.base ?? "HEAD", cwd, signal);
372
+ await confirm(ctx, signal, authorizations, "worktree_add", "Confirm worktree creation",
373
+ `Repository: ${JSON.stringify(cwd)}\nDestination: ${JSON.stringify(target)}\n`
374
+ + `Branch: ${JSON.stringify(name)} (${exists ? "existing" : `new from ${base}`})\n\n`
375
+ + "Create a separate worktree. The current worktree stays on its current branch.");
376
+ if (await canonicalPath(resolve(cwd, params.path)) !== target) {
377
+ throw new Error("Worktree destination changed during confirmation. Review and retry.");
378
+ }
379
+ await run([
380
+ "worktree", "add", "--no-guess-remote", ...(exists ? [] : ["-b", name]),
381
+ "--", target, exists ? name : base,
382
+ ], cwd, signal);
383
+ return `Created worktree at ${JSON.stringify(target)} on ${JSON.stringify(name)}.`;
384
+ },
385
+
386
+ async git_worktree_remove(params, ctx, signal) {
387
+ text(params.path, "Worktree path");
388
+ const cwd = await root(ctx, signal);
389
+ const target = await realpath(resolve(cwd, params.path));
390
+ await removable(target, cwd, ctx, signal);
391
+ await confirm(ctx, signal, authorizations, "worktree_remove", "Confirm worktree removal",
392
+ `Repository: ${JSON.stringify(cwd)}\nWorktree: ${JSON.stringify(target)}\n\n`
393
+ + "Remove this clean worktree directory. Keep its branch. Never force removal.");
394
+ await removable(target, cwd, ctx, signal);
395
+ await run(["worktree", "remove", "--", target], cwd, signal);
396
+ return `Removed worktree at ${JSON.stringify(target)}. Its branch was kept.`;
397
+ },
398
+
399
+ async git_worktree_prune(_params, ctx, signal) {
400
+ const cwd = await root(ctx, signal);
401
+ const dryRun = () => run(["worktree", "prune", "--dry-run", "--verbose"], cwd, signal, true);
402
+ const preview = await dryRun();
403
+ if (!preview.trim()) {
404
+ return "No stale worktree metadata to prune.";
405
+ }
406
+ await confirm(ctx, signal, authorizations, "worktree_prune", "Confirm worktree metadata pruning",
407
+ `Repository: ${JSON.stringify(cwd)}\nPreview: ${JSON.stringify(preview)}\n\n`
408
+ + "Remove stale administrative records only, using Git's default expiration. No directory deletion.");
409
+ if (await dryRun() !== preview) {
410
+ throw new Error("Prune candidates changed during confirmation. Review and retry.");
411
+ }
412
+ await run(["worktree", "prune", "--verbose"], cwd, signal);
413
+ return "Stale worktree metadata pruned. No worktree directories were deleted.";
414
+ },
415
+ };
416
+ }