@carrieros/cli 0.2.0 → 0.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.
Files changed (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,199 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { LocalFileError, isInside, isPathIgnored, resolveInside, walkRepository } from "./local-files.js";
4
+ import { isSensitiveName } from "./local-tools.js";
5
+ import { activeRepository, isWildcardSelector, listRepositories, repositoryForPath, repositoryTrust, resolveRepository } from "./workspace-registry.js";
6
+ /** Cap on how many repositories/entries a fuzzy search will examine. */
7
+ const MAX_CANDIDATES = 10;
8
+ const posix = (p) => p.split(path.sep).join("/");
9
+ function trustedRepositories() {
10
+ return listRepositories().filter((r) => repositoryTrust(r) === "trusted");
11
+ }
12
+ /**
13
+ * A resolved entry IF `rel` exists inside `repo` and passes containment. Returns
14
+ * null when it does not exist or is excluded; throws nothing — a bad path is
15
+ * simply "no match here".
16
+ */
17
+ function tryExact(repo, rel, kind) {
18
+ let abs;
19
+ try {
20
+ abs = resolveInside(rel, repo.root);
21
+ }
22
+ catch {
23
+ return null; // outside the repo, or a link that leaves it
24
+ }
25
+ let st;
26
+ try {
27
+ st = fs.statSync(abs);
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ const isDir = st.isDirectory();
33
+ if (kind === "file" && isDir)
34
+ return null;
35
+ if (kind === "directory" && !isDir)
36
+ return null;
37
+ const relOut = posix(path.relative(repo.root, abs));
38
+ if (!relOut || relOut.startsWith(".."))
39
+ return null;
40
+ if (isPathIgnored(relOut, repo.root))
41
+ return null;
42
+ if (!isDir && isSensitiveName(path.basename(abs)))
43
+ return null;
44
+ return {
45
+ repositoryId: repo.id,
46
+ repositoryName: repo.name,
47
+ relativePath: relOut,
48
+ absolutePath: abs,
49
+ isDirectory: isDir,
50
+ matchType: "exact_repo_relative",
51
+ confidence: "high"
52
+ };
53
+ }
54
+ /** The registered repo a reference is qualified with, plus the remaining path. */
55
+ function splitRepoQualified(reference) {
56
+ const norm = reference.replace(/\\/g, "/").replace(/^\.\//, "");
57
+ const slash = norm.indexOf("/");
58
+ if (slash <= 0)
59
+ return null;
60
+ const head = norm.slice(0, slash);
61
+ const rest = norm.slice(slash + 1);
62
+ if (!rest)
63
+ return null;
64
+ const wanted = head.toLowerCase();
65
+ const repo = listRepositories().find((r) => r.id === wanted || r.name.toLowerCase() === wanted);
66
+ return repo ? { repo, rest } : null;
67
+ }
68
+ /**
69
+ * Fuzzy match by basename (a bare name like `user.js` or `hooks`) or by path
70
+ * suffix (`routes/user.js`) across the trusted repositories. Uses the contained
71
+ * walker, so ignore rules and symlink-skipping already apply. Bounded.
72
+ */
73
+ function searchByName(reference, kind, repos) {
74
+ const norm = reference.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
75
+ const wantBasename = norm.split("/").pop() ?? norm;
76
+ const hasSlash = norm.includes("/");
77
+ const out = [];
78
+ for (const repo of repos) {
79
+ const walk = walkRepository({ root: repo.root, includeDirectories: true });
80
+ for (const e of walk.entries) {
81
+ if (out.length >= MAX_CANDIDATES)
82
+ break;
83
+ const isDir = e.type === "dir";
84
+ if (kind === "file" && isDir)
85
+ continue;
86
+ if (kind === "directory" && !isDir)
87
+ continue;
88
+ const base = e.path.split("/").pop() ?? e.path;
89
+ // A path-like reference matches by suffix; a bare name matches basename.
90
+ const matches = hasSlash
91
+ ? e.path === norm || e.path.endsWith("/" + norm)
92
+ : base === wantBasename;
93
+ if (!matches)
94
+ continue;
95
+ if (!isDir && isSensitiveName(base))
96
+ continue;
97
+ out.push({
98
+ repositoryId: repo.id,
99
+ repositoryName: repo.name,
100
+ relativePath: e.path,
101
+ absolutePath: path.join(repo.root, e.path),
102
+ isDirectory: isDir,
103
+ matchType: isDir ? "directory" : hasSlash ? "exact_filename" : "basename",
104
+ confidence: "medium"
105
+ });
106
+ }
107
+ if (out.length >= MAX_CANDIDATES)
108
+ break;
109
+ }
110
+ return out;
111
+ }
112
+ /**
113
+ * Resolve one reference. See the module comment for the guarantees. The order
114
+ * is deterministic; a tie among repositories is returned as candidates.
115
+ */
116
+ export function resolveWorkspaceFile(input) {
117
+ const reference = typeof input.reference === "string" ? input.reference.trim() : "";
118
+ const kind = input.kind ?? "either";
119
+ if (!reference)
120
+ return { status: "error", error: { code: "INVALID_REFERENCE", message: "A file reference is required." } };
121
+ if (isWildcardSelector(reference)) {
122
+ return { status: "error", error: { code: "INVALID_REFERENCE", message: 'A file reference cannot be "*".' } };
123
+ }
124
+ const trusted = trustedRepositories();
125
+ if (trusted.length === 0) {
126
+ return { status: "error", error: { code: "NO_TRUSTED_REPOSITORY", message: "No trusted repository to resolve against. Trust one first." } };
127
+ }
128
+ let active = null;
129
+ try {
130
+ active = input.activeRepository ? resolveRepository(input.activeRepository) : activeRepository();
131
+ }
132
+ catch {
133
+ active = activeRepository();
134
+ }
135
+ const isTrusted = (r) => repositoryTrust(r) === "trusted";
136
+ // 1. Repository-qualified: "api.carrieros.ai/src/routes/user.js".
137
+ const qualified = splitRepoQualified(reference);
138
+ if (qualified) {
139
+ if (!isTrusted(qualified.repo)) {
140
+ return { status: "error", error: { code: "REPOSITORY_NOT_TRUSTED", message: `${qualified.repo.name} is not a trusted repository.` } };
141
+ }
142
+ const hit = tryExact(qualified.repo, qualified.rest, kind);
143
+ if (hit)
144
+ return { status: "resolved", match: { ...hit, matchType: "repo_qualified", confidence: "high" } };
145
+ // A named repo whose path is absent is a miss, not a fall-through to fuzzy —
146
+ // the user was specific.
147
+ return { status: "not_found", error: { code: "NOT_FOUND", message: `${qualified.rest} is not in ${qualified.repo.name}.` } };
148
+ }
149
+ // 2. Absolute path that lands inside a registered, trusted repository.
150
+ if (path.isAbsolute(reference) || /^[a-zA-Z]:[\\/]/.test(reference) || reference.startsWith("\\\\")) {
151
+ const repo = repositoryForPath(reference);
152
+ if (!repo) {
153
+ return { status: "error", error: { code: "OUTSIDE_WORKSPACE", message: "That path is outside every registered repository." } };
154
+ }
155
+ if (!isTrusted(repo)) {
156
+ return { status: "error", error: { code: "REPOSITORY_NOT_TRUSTED", message: `${repo.name} is not a trusted repository.` } };
157
+ }
158
+ const rel = path.relative(repo.root, path.resolve(reference));
159
+ const hit = tryExact(repo, rel, kind);
160
+ if (hit)
161
+ return { status: "resolved", match: { ...hit, matchType: "absolute_workspace_path" } };
162
+ return { status: "not_found", error: { code: "NOT_FOUND", message: "No such file in that repository." } };
163
+ }
164
+ // A traversal reference is refused outright — never allowed to climb out.
165
+ if (reference.replace(/\\/g, "/").split("/").includes("..")) {
166
+ return { status: "error", error: { code: "OUTSIDE_WORKSPACE", message: "A reference may not contain '..'." } };
167
+ }
168
+ // 3. Exact path in the active repository.
169
+ if (active && isTrusted(active)) {
170
+ const hit = tryExact(active, reference, kind);
171
+ if (hit)
172
+ return { status: "resolved", match: hit };
173
+ }
174
+ // 4. Exact path in another trusted repository.
175
+ const others = trusted.filter((r) => r.id !== active?.id);
176
+ const exactElsewhere = [];
177
+ for (const repo of others) {
178
+ const hit = tryExact(repo, reference, kind);
179
+ if (hit)
180
+ exactElsewhere.push({ ...hit, matchType: "exact_path_other_repo" });
181
+ }
182
+ if (exactElsewhere.length === 1)
183
+ return { status: "resolved", match: exactElsewhere[0] };
184
+ if (exactElsewhere.length > 1)
185
+ return { status: "ambiguous", candidates: exactElsewhere };
186
+ // 5. Filename / basename / directory match across trusted repos (active first).
187
+ const ordered = active && isTrusted(active) ? [active, ...others] : trusted;
188
+ const found = searchByName(reference, kind, ordered);
189
+ if (found.length === 1)
190
+ return { status: "resolved", match: found[0] };
191
+ if (found.length > 1)
192
+ return { status: "ambiguous", candidates: found };
193
+ return {
194
+ status: "not_found",
195
+ error: { code: "NOT_FOUND", message: `Could not find "${reference}" in any trusted repository.` }
196
+ };
197
+ }
198
+ /** Exported for the tool executor to keep error mapping in one place. */
199
+ export { LocalFileError, isInside };
@@ -0,0 +1,126 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { ApiError } from "./api.js";
4
+ const SUPPORTED = "PDF, DOCX, TXT, CSV, JSON, Markdown, Images";
5
+ /** A friendly, already-formatted, user-facing upload error. */
6
+ export class UploadError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "UploadError";
10
+ }
11
+ }
12
+ /** A short human file-type label from the extension (e.g. "PDF", "CSV"). */
13
+ export function fileTypeLabel(name) {
14
+ const ext = path.extname(name).replace(".", "").toUpperCase();
15
+ return ext || "FILE";
16
+ }
17
+ /** Human size — "812 KB" / "2.3 MB". */
18
+ export function formatSize(bytes) {
19
+ if (bytes >= 1024 * 1024)
20
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
21
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
22
+ }
23
+ /** Reuse an already-uploaded, unchanged local file (same path + size + mtime). */
24
+ function findDuplicate(ctx, absPath, size, mtime) {
25
+ const uploads = ctx.config.get("uploads") ?? [];
26
+ const hit = uploads.find((u) => u.local_path === absPath && u.size === size && u.mtime === mtime);
27
+ return hit?.file_id ?? null;
28
+ }
29
+ /** Filenames for the currently-attached file ids (for the footer / listings). */
30
+ export function attachedFilenames(ctx) {
31
+ const uploads = ctx.config.get("uploads") ?? [];
32
+ return ctx.attachedFileIds.map((id) => uploads.find((u) => u.file_id === id)?.filename ?? id);
33
+ }
34
+ /**
35
+ * Upload a local file (POST /v1/files) and, unless disabled, kick off indexing
36
+ * (POST /v1/files/:id/process). Reuses the existing file_id if the same unchanged
37
+ * file was already uploaded from this machine (no re-upload). Does NOT attach —
38
+ * the caller decides that (the shell auto-attaches; standalone asks). Throws
39
+ * UploadError with a friendly, ready-to-print message on any failure.
40
+ *
41
+ * Thin client only: no parsing, no indexing — the backend owns all of that.
42
+ */
43
+ export async function ensureUploaded(ctx, client, filePath, hooks = {}) {
44
+ const absPath = path.resolve(filePath);
45
+ const name = path.basename(absPath);
46
+ let stat;
47
+ try {
48
+ stat = fs.statSync(absPath);
49
+ }
50
+ catch {
51
+ throw new UploadError(`Couldn't find that file.\n Check the path and try again: ${filePath}`);
52
+ }
53
+ if (stat.isDirectory()) {
54
+ throw new UploadError(`That's a folder, not a file: ${filePath}`);
55
+ }
56
+ // Dedup — reuse the existing upload for the same unchanged file.
57
+ const dupId = findDuplicate(ctx, absPath, stat.size, Math.floor(stat.mtimeMs));
58
+ if (dupId) {
59
+ return {
60
+ fileId: dupId,
61
+ filename: name,
62
+ bytes: stat.size,
63
+ status: "existing",
64
+ wasAttached: ctx.attachedFileIds.includes(dupId)
65
+ };
66
+ }
67
+ hooks.onUploading?.();
68
+ let uploaded;
69
+ try {
70
+ uploaded = await client.uploadFile(absPath);
71
+ }
72
+ catch (err) {
73
+ throw new UploadError(friendlyUploadError(err));
74
+ }
75
+ ctx.config.addUpload({
76
+ file_id: uploaded.file_id,
77
+ filename: uploaded.filename,
78
+ file_type: uploaded.file_type,
79
+ uploaded_at: new Date().toISOString(),
80
+ local_path: absPath,
81
+ size: stat.size,
82
+ mtime: Math.floor(stat.mtimeMs)
83
+ });
84
+ hooks.onUploaded?.(uploaded.filename);
85
+ if (hooks.process !== false) {
86
+ hooks.onProcessing?.();
87
+ try {
88
+ await client.processFile(uploaded.file_id);
89
+ }
90
+ catch {
91
+ // Indexing is best-effort — the file is still usable once ready.
92
+ }
93
+ }
94
+ return {
95
+ fileId: uploaded.file_id,
96
+ filename: uploaded.filename,
97
+ bytes: stat.size,
98
+ status: "uploaded",
99
+ wasAttached: false
100
+ };
101
+ }
102
+ /** ensureUploaded + attach (the shell/auto flow — attaching is expected there). */
103
+ export async function uploadAndAttach(ctx, client, filePath, hooks = {}) {
104
+ const r = await ensureUploaded(ctx, client, filePath, hooks);
105
+ ctx.attachFile(r.fileId);
106
+ return r;
107
+ }
108
+ /** Map an API/local error to a friendly, actionable message. */
109
+ export function friendlyUploadError(err) {
110
+ if (err instanceof ApiError) {
111
+ switch (err.code) {
112
+ case "UNSUPPORTED_FILE_TYPE":
113
+ return `Carrier OS can't upload this file type.\n Supported: ${SUPPORTED}`;
114
+ case "FILE_TOO_LARGE":
115
+ return "This file exceeds the 25 MB upload limit.";
116
+ case "NO_ACCOUNT":
117
+ return "This account can't upload files — try `cos login` again.";
118
+ default:
119
+ return err.message || "Upload failed.";
120
+ }
121
+ }
122
+ if (err?.code === "ENOENT") {
123
+ return "Couldn't find that file. Check the path and try again.";
124
+ }
125
+ return err?.message || "Upload failed.";
126
+ }
@@ -0,0 +1,248 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { HARDENED_GIT_OPTIONS, hardenedGitEnv, neutralizingOverrides } from "./workspace.js";
3
+ /**
4
+ * Read-only Git for the developer tools `git_status` and `git_diff`.
5
+ *
6
+ * These are READS, like read_file — not commands. They never need
7
+ * `run_command` enabled, never prompt for approval, and never mutate. What they
8
+ * do need is the same hardening every Git call in this CLI uses, because a
9
+ * repository's own `.git/config` is attacker-controlled: cloning or unzipping a
10
+ * project is enough to plant a `filter`, an `fsmonitor` hook or an external
11
+ * diff driver that Git would otherwise run while reading the tree.
12
+ *
13
+ * So every call here goes through the shared hardening — global `-c` overrides,
14
+ * the per-repository program-key neutralization, and the no-prompt/no-lock
15
+ * environment — with argv arrays and no shell, exactly as workspace.ts does.
16
+ * The containment boundary is unchanged; this module only adds two read shapes
17
+ * on top of it. The caller resolves WHICH repository (name → trusted handle →
18
+ * root) before anything here runs; `root` is always a repository root.
19
+ */
20
+ const GIT_TIMEOUT_MS = 10_000;
21
+ /** A diff a person cannot read on a terminal is not one a model should hold either. */
22
+ const MAX_DIFF_BYTES = 120 * 1024;
23
+ /** Enough file entries to describe a change set; more is noise. */
24
+ const MAX_FILES = 1000;
25
+ export class GitToolError extends Error {
26
+ code;
27
+ constructor(code, message) {
28
+ super(message);
29
+ this.code = code;
30
+ this.name = "GitToolError";
31
+ }
32
+ }
33
+ /**
34
+ * One hardened Git invocation. `diffSafe` adds the per-command diff guards
35
+ * (`--no-ext-diff`, `--no-textconv`, `--no-color`) that `status` rejects but
36
+ * `diff` needs, so a diff never runs a repository-chosen textconv program.
37
+ */
38
+ function run(root, args, overrides) {
39
+ try {
40
+ const out = execFileSync("git", [...HARDENED_GIT_OPTIONS, ...overrides, ...args], {
41
+ cwd: root,
42
+ timeout: GIT_TIMEOUT_MS,
43
+ windowsHide: true,
44
+ encoding: "utf8",
45
+ env: hardenedGitEnv(),
46
+ stdio: ["ignore", "pipe", "pipe"],
47
+ maxBuffer: 16 * 1024 * 1024
48
+ });
49
+ return { ok: true, out: String(out) };
50
+ }
51
+ catch (err) {
52
+ const e = err;
53
+ const stderr = e.stderr ? String(e.stderr).trim() : "";
54
+ const reason = e.code === "ENOENT"
55
+ ? "Git is not installed."
56
+ : e.code === "ETIMEDOUT"
57
+ ? "Git timed out."
58
+ : (stderr.split(/\r?\n/).find((l) => l.trim()) ?? e.message ?? "Git failed.").replace(/^fatal:\s*/i, "");
59
+ return { ok: false, out: "", code: e.status, reason };
60
+ }
61
+ }
62
+ /**
63
+ * The program-key overrides for this repository, or throw.
64
+ *
65
+ * Throwing rather than proceeding is the safe default the descriptor uses too:
66
+ * if we cannot read the config to know which filter/diff-driver names to
67
+ * neutralize, we do not run the calls that would honour them.
68
+ */
69
+ function overridesFor(root) {
70
+ const overrides = neutralizingOverrides(root);
71
+ if (overrides === null) {
72
+ throw new GitToolError("GIT_UNAVAILABLE", "The repository's Git configuration could not be read safely.");
73
+ }
74
+ return overrides;
75
+ }
76
+ /**
77
+ * `git status --porcelain=v2 --branch`, parsed into structured state.
78
+ *
79
+ * porcelain v2 is stable and machine-first: each entry names its staged (X) and
80
+ * unstaged (Y) state, so "modified but not added" and "staged" are
81
+ * distinguishable — which the next phase's review needs. Submodules are ignored
82
+ * (each has its own config these overrides never saw).
83
+ */
84
+ export function gitStatus(root) {
85
+ const res = run(root, ["status", "--porcelain=v2", "--branch", "--ignore-submodules=all"], overridesFor(root));
86
+ if (!res.ok)
87
+ throw new GitToolError("GIT_FAILED", res.reason ?? "git status failed.");
88
+ const s = {
89
+ branch: null,
90
+ detached: false,
91
+ head: null,
92
+ upstream: null,
93
+ ahead: 0,
94
+ behind: 0,
95
+ clean: true,
96
+ hasCommits: false,
97
+ staged: [],
98
+ unstaged: [],
99
+ untracked: [],
100
+ renamed: [],
101
+ deleted: [],
102
+ truncated: false
103
+ };
104
+ let changes = 0;
105
+ let oid = null;
106
+ const push = (list, value) => {
107
+ if (list.length < MAX_FILES)
108
+ list.push(value);
109
+ else
110
+ s.truncated = true;
111
+ };
112
+ for (const raw of res.out.split(/\r?\n/)) {
113
+ if (!raw)
114
+ continue;
115
+ if (raw.startsWith("#")) {
116
+ const m = raw.match(/^# branch\.(oid|head|upstream|ab) (.+)$/);
117
+ if (!m)
118
+ continue;
119
+ if (m[1] === "oid") {
120
+ oid = m[2].trim();
121
+ s.hasCommits = oid !== "(initial)";
122
+ }
123
+ else if (m[1] === "head") {
124
+ const head = m[2].trim();
125
+ if (head === "(detached)")
126
+ s.detached = true;
127
+ else
128
+ s.branch = head;
129
+ }
130
+ else if (m[1] === "upstream")
131
+ s.upstream = m[2].trim();
132
+ else if (m[1] === "ab") {
133
+ const ab = m[2].match(/\+(\d+)\s+-(\d+)/);
134
+ if (ab) {
135
+ s.ahead = Number(ab[1]);
136
+ s.behind = Number(ab[2]);
137
+ }
138
+ }
139
+ continue;
140
+ }
141
+ // ? untracked
142
+ if (raw.startsWith("? ")) {
143
+ push(s.untracked, raw.slice(2));
144
+ changes += 1;
145
+ continue;
146
+ }
147
+ // 1 <XY> ... <path> changed (X = staged state, Y = unstaged state)
148
+ if (raw.startsWith("1 ")) {
149
+ const xy = raw.split(" ")[1] ?? "..";
150
+ const file = fieldAfter(raw, 8);
151
+ if (xy[0] !== ".")
152
+ push(s.staged, file);
153
+ if (xy[1] !== ".")
154
+ push(s.unstaged, file);
155
+ if (xy.includes("D"))
156
+ push(s.deleted, file);
157
+ changes += 1;
158
+ continue;
159
+ }
160
+ // 2 <XY> ... <path>\t<origPath> renamed/copied
161
+ if (raw.startsWith("2 ")) {
162
+ const xy = raw.split(" ")[1] ?? "..";
163
+ const tail = fieldAfter(raw, 9);
164
+ const [to, from] = tail.split("\t");
165
+ s.renamed.length < MAX_FILES ? s.renamed.push({ from: from ?? "", to: to ?? "" }) : (s.truncated = true);
166
+ if (xy[0] !== ".")
167
+ push(s.staged, to ?? "");
168
+ changes += 1;
169
+ continue;
170
+ }
171
+ // u ... unmerged (a conflict is a change)
172
+ if (raw.startsWith("u ")) {
173
+ push(s.unstaged, fieldAfter(raw, 10));
174
+ changes += 1;
175
+ }
176
+ }
177
+ // A detached HEAD has no branch name; the short commit is what identifies it.
178
+ if (s.detached && oid && s.hasCommits)
179
+ s.head = oid.slice(0, 7);
180
+ s.clean = changes === 0;
181
+ return s;
182
+ }
183
+ /**
184
+ * The Nth space-separated field to end of line — porcelain v2 paths are the
185
+ * last field and may contain spaces, so everything from field N on is the path.
186
+ */
187
+ function fieldAfter(line, n) {
188
+ let i = 0;
189
+ let field = 0;
190
+ while (field < n && i < line.length) {
191
+ if (line[i] === " ")
192
+ field += 1;
193
+ i += 1;
194
+ }
195
+ return line.slice(i);
196
+ }
197
+ /** The diff args for a scope. `both` is staged + unstaged, i.e. against HEAD. */
198
+ function diffArgs(scope) {
199
+ const guards = ["--no-color", "--no-ext-diff", "--no-textconv"];
200
+ if (scope === "staged")
201
+ return ["diff", "--cached", ...guards];
202
+ if (scope === "both")
203
+ return ["diff", "HEAD", ...guards];
204
+ return ["diff", ...guards];
205
+ }
206
+ /**
207
+ * A bounded, hardened diff for one repository.
208
+ *
209
+ * Counts come from `--numstat` (cheap, parseable); the patch text is captured
210
+ * separately and trimmed to MAX_DIFF_BYTES so a huge change set cannot swamp a
211
+ * turn. No approval, no mutation — it is a read.
212
+ */
213
+ export function gitDiff(root, scope = "working_tree") {
214
+ const overrides = overridesFor(root);
215
+ const stat = run(root, [...diffArgs(scope), "--numstat"], overrides);
216
+ if (!stat.ok) {
217
+ // A fresh repository has no HEAD, so `diff HEAD`/`both` cannot resolve one.
218
+ if (scope === "both" && /ambiguous argument 'HEAD'|unknown revision/i.test(stat.reason ?? "")) {
219
+ return gitDiff(root, "staged");
220
+ }
221
+ throw new GitToolError("GIT_FAILED", stat.reason ?? "git diff failed.");
222
+ }
223
+ let filesChanged = 0;
224
+ let additions = 0;
225
+ let deletions = 0;
226
+ for (const raw of stat.out.split(/\r?\n/)) {
227
+ if (!raw.trim())
228
+ continue;
229
+ filesChanged += 1;
230
+ const [add, del] = raw.split("\t");
231
+ if (add !== "-")
232
+ additions += Number(add) || 0;
233
+ if (del !== "-")
234
+ deletions += Number(del) || 0;
235
+ }
236
+ const patch = run(root, diffArgs(scope), overrides);
237
+ if (!patch.ok)
238
+ throw new GitToolError("GIT_FAILED", patch.reason ?? "git diff failed.");
239
+ let diff = patch.out;
240
+ let truncated = false;
241
+ if (Buffer.byteLength(diff, "utf8") > MAX_DIFF_BYTES) {
242
+ diff = diff.slice(0, MAX_DIFF_BYTES);
243
+ // Do not end mid-line — drop the partial last line.
244
+ diff = diff.slice(0, diff.lastIndexOf("\n") + 1) + "… [diff truncated]\n";
245
+ truncated = true;
246
+ }
247
+ return { scope, files_changed: filesChanged, additions, deletions, diff, truncated };
248
+ }