@carrieros/cli-staging 0.0.0-stage → 0.4.1

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 (137) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +26 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +78 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +160 -0
  27. package/dist/commands/update.js +285 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +229 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +364 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +132 -0
  36. package/dist/services/api.js +441 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/auto-update.js +221 -0
  39. package/dist/services/chat-stream.js +168 -0
  40. package/dist/services/checkpoints.js +278 -0
  41. package/dist/services/client-tools.js +356 -0
  42. package/dist/services/code-intel.js +243 -0
  43. package/dist/services/code-symbols.js +94 -0
  44. package/dist/services/coding-workflow.js +554 -0
  45. package/dist/services/command-coordinator.js +273 -0
  46. package/dist/services/command-policy.js +434 -0
  47. package/dist/services/config.js +384 -0
  48. package/dist/services/container-runner.js +254 -0
  49. package/dist/services/container-supervisor.js +38 -0
  50. package/dist/services/context.js +416 -0
  51. package/dist/services/device-auth.js +288 -0
  52. package/dist/services/diff.js +196 -0
  53. package/dist/services/env-policy.js +108 -0
  54. package/dist/services/execution-platform.js +30 -0
  55. package/dist/services/file-detect.js +104 -0
  56. package/dist/services/file-resolver.js +199 -0
  57. package/dist/services/file-upload.js +126 -0
  58. package/dist/services/folder-key.js +22 -0
  59. package/dist/services/git-tools.js +429 -0
  60. package/dist/services/glob-match.js +164 -0
  61. package/dist/services/helper-bin.js +85 -0
  62. package/dist/services/ignore-rules.js +189 -0
  63. package/dist/services/instruction-resolver.js +54 -0
  64. package/dist/services/job-helper.js +328 -0
  65. package/dist/services/local-files.js +639 -0
  66. package/dist/services/local-tools.js +937 -0
  67. package/dist/services/login-flow.js +156 -0
  68. package/dist/services/meta.js +42 -0
  69. package/dist/services/mutation-coordinator.js +327 -0
  70. package/dist/services/mutation-groups.js +309 -0
  71. package/dist/services/mutation-recovery.js +159 -0
  72. package/dist/services/mutations.js +679 -0
  73. package/dist/services/open-url.js +68 -0
  74. package/dist/services/output.js +62 -0
  75. package/dist/services/packaged-update.js +403 -0
  76. package/dist/services/packaged.js +39 -0
  77. package/dist/services/permission-mode.js +78 -0
  78. package/dist/services/process-runner.js +412 -0
  79. package/dist/services/project-context.js +298 -0
  80. package/dist/services/redaction.js +201 -0
  81. package/dist/services/result-reconciliation.js +49 -0
  82. package/dist/services/secure-store.js +217 -0
  83. package/dist/services/session-resolver.js +115 -0
  84. package/dist/services/sia.js +51 -0
  85. package/dist/services/spinner.js +40 -0
  86. package/dist/services/supported-runtime.js +59 -0
  87. package/dist/services/task-context.js +212 -0
  88. package/dist/services/task-snapshot.js +38 -0
  89. package/dist/services/tool-result-outbox.js +195 -0
  90. package/dist/services/update.js +730 -0
  91. package/dist/services/workspace-registry.js +310 -0
  92. package/dist/services/workspace.js +580 -0
  93. package/dist/shell/shell-chat.js +1622 -0
  94. package/dist/shell/shell-commands.js +411 -0
  95. package/dist/shell/shell-prompt.js +110 -0
  96. package/dist/shell/shell-renderer.js +51 -0
  97. package/dist/shell/shell-router.js +37 -0
  98. package/dist/shell/shell.js +414 -0
  99. package/dist/shell/task-context-view.js +40 -0
  100. package/dist/staging.js +5 -0
  101. package/dist/types/index.js +6 -0
  102. package/dist/ui/agent-cards.js +111 -0
  103. package/dist/ui/agent-presentation.js +131 -0
  104. package/dist/ui/approval.js +111 -0
  105. package/dist/ui/banner.js +56 -0
  106. package/dist/ui/btw-overlay.js +230 -0
  107. package/dist/ui/change-review.js +334 -0
  108. package/dist/ui/chat-renderer.js +463 -0
  109. package/dist/ui/code-block.js +52 -0
  110. package/dist/ui/color-picker.js +100 -0
  111. package/dist/ui/colors.js +55 -0
  112. package/dist/ui/command-details.js +11 -0
  113. package/dist/ui/command-filter.js +92 -0
  114. package/dist/ui/command-item.js +6 -0
  115. package/dist/ui/command-palette.js +383 -0
  116. package/dist/ui/command-registry.js +128 -0
  117. package/dist/ui/command-renderer.js +55 -0
  118. package/dist/ui/command-review.js +187 -0
  119. package/dist/ui/composer-layout.js +74 -0
  120. package/dist/ui/conversation.js +450 -0
  121. package/dist/ui/interrupt.js +35 -0
  122. package/dist/ui/live.js +141 -0
  123. package/dist/ui/logo.js +58 -0
  124. package/dist/ui/markdown.js +205 -0
  125. package/dist/ui/message.js +21 -0
  126. package/dist/ui/screen-prompt.js +181 -0
  127. package/dist/ui/screen.js +297 -0
  128. package/dist/ui/select.js +284 -0
  129. package/dist/ui/sia-qa.js +213 -0
  130. package/dist/ui/spinner.js +23 -0
  131. package/dist/ui/sticky-stream.js +64 -0
  132. package/dist/ui/task-context-card.js +99 -0
  133. package/dist/ui/text-prompt.js +74 -0
  134. package/dist/ui/theme.js +80 -0
  135. package/dist/ui/trust.js +88 -0
  136. package/dist/ui/ui.js +101 -0
  137. package/package.json +33 -4
@@ -0,0 +1,429 @@
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
+ }
249
+ // ── History (read-only) ──────────────────────────────────────────────────────
250
+ // log, blame and show answer "when and why did this line change?" — the step a
251
+ // root-cause investigation takes after it has found the function. They are
252
+ // reads with the same hardening as status/diff. Revisions are validated to a
253
+ // closed grammar BEFORE they reach argv, so a model-supplied value can never be
254
+ // read by Git as an option, a ref expression with side effects, or a path; and
255
+ // every path follows a literal `--`. Patches are only ever produced for one
256
+ // path the caller already validated against the read rules (containment,
257
+ // ignore, sensitive names), so history cannot be used to read a credentials
258
+ // file that a current read_file would refuse.
259
+ /** Most commits one git_log returns. */
260
+ export const MAX_LOG_COMMITS = 50;
261
+ /** Most changed paths listed per commit. */
262
+ const MAX_LOG_FILES = 20;
263
+ /** Most lines one git_blame covers. */
264
+ export const MAX_BLAME_LINES = 200;
265
+ /** HEAD, HEAD~n, HEAD^…, or an abbreviated/full object id. Nothing else. */
266
+ const REVISION = /^(?:HEAD(?:~\d{1,4}|\^{1,4})?|[0-9a-fA-F]{4,64})$/;
267
+ export function isSafeRevision(rev) {
268
+ return REVISION.test(rev);
269
+ }
270
+ function requireRevision(rev) {
271
+ if (!isSafeRevision(rev)) {
272
+ throw new GitToolError("INVALID_REVISION", 'A revision must be HEAD, HEAD~n, HEAD^, or a commit hash (4–64 hex characters).');
273
+ }
274
+ return rev;
275
+ }
276
+ const HISTORY_GUARDS = ["--no-color", "--no-ext-diff", "--no-textconv"];
277
+ const FIELD = "\x1f";
278
+ const RECORD = "\x1e";
279
+ function noHistory(reason) {
280
+ return /does not have any commits|unknown revision|bad default revision|ambiguous argument 'HEAD'/i.test(reason ?? "");
281
+ }
282
+ function parseCommits(out, withFiles) {
283
+ const commits = [];
284
+ for (const raw of out.split(RECORD)) {
285
+ const record = raw.replace(/^\r?\n+/, "");
286
+ if (!record.trim())
287
+ continue;
288
+ const [header, ...rest] = record.split(/\r?\n/);
289
+ const [commit, short, author, date, subject] = header.split(FIELD);
290
+ if (!commit)
291
+ continue;
292
+ const entry = { commit, short, author, date, subject: subject ?? "" };
293
+ if (withFiles) {
294
+ const files = rest.map((l) => l.trim()).filter(Boolean);
295
+ entry.files = files.slice(0, MAX_LOG_FILES);
296
+ if (files.length > MAX_LOG_FILES)
297
+ entry.files_truncated = true;
298
+ }
299
+ commits.push(entry);
300
+ }
301
+ return commits;
302
+ }
303
+ /**
304
+ * Recent commits, optionally only those touching one validated path.
305
+ * Metadata and changed-path names only — never patches.
306
+ */
307
+ export function gitLog(root, opts = {}) {
308
+ const limit = Math.min(MAX_LOG_COMMITS, Math.max(1, Math.floor(opts.limit ?? 10)));
309
+ const args = [
310
+ "log",
311
+ ...HISTORY_GUARDS,
312
+ `--max-count=${limit + 1}`,
313
+ `--format=${RECORD}%H${FIELD}%h${FIELD}%an${FIELD}%aI${FIELD}%s`,
314
+ "--name-only"
315
+ ];
316
+ if (opts.path)
317
+ args.push("--follow", "--", opts.path);
318
+ const res = run(root, args, overridesFor(root));
319
+ if (!res.ok) {
320
+ if (noHistory(res.reason))
321
+ return { commits: [], truncated: false };
322
+ throw new GitToolError("GIT_FAILED", res.reason ?? "git log failed.");
323
+ }
324
+ const commits = parseCommits(res.out, true);
325
+ return { commits: commits.slice(0, limit), truncated: commits.length > limit };
326
+ }
327
+ /** Line-by-line authorship for a bounded range of one validated path. */
328
+ export function gitBlame(root, relPath, startLine, endLine) {
329
+ const start = Math.max(1, Math.floor(startLine));
330
+ const end = Math.max(start, Math.floor(endLine));
331
+ if (end - start + 1 > MAX_BLAME_LINES) {
332
+ throw new GitToolError("RANGE_TOO_LARGE", `Blame at most ${MAX_BLAME_LINES} lines at a time.`);
333
+ }
334
+ const res = run(root, ["blame", "--porcelain", "--no-textconv", "-L", `${start},${end}`, "--", relPath], overridesFor(root));
335
+ if (!res.ok) {
336
+ if (noHistory(res.reason) || /no such path .* in HEAD/i.test(res.reason ?? "")) {
337
+ throw new GitToolError("NO_HISTORY", `${relPath} has no committed history yet.`);
338
+ }
339
+ throw new GitToolError("GIT_FAILED", res.reason ?? "git blame failed.");
340
+ }
341
+ const meta = new Map();
342
+ const lines = [];
343
+ let current = null;
344
+ for (const raw of res.out.split("\n")) {
345
+ const head = raw.match(/^([0-9a-f]{40}) \d+ (\d+)(?: \d+)?$/);
346
+ if (head) {
347
+ current = { commit: head[1], final: Number(head[2]) };
348
+ if (!meta.has(head[1]))
349
+ meta.set(head[1], { author: "", time: null, summary: "" });
350
+ continue;
351
+ }
352
+ if (!current)
353
+ continue;
354
+ const m = meta.get(current.commit);
355
+ if (raw.startsWith("author "))
356
+ m.author = raw.slice(7);
357
+ else if (raw.startsWith("author-time "))
358
+ m.time = Number(raw.slice(12)) || null;
359
+ else if (raw.startsWith("summary "))
360
+ m.summary = raw.slice(8);
361
+ else if (raw.startsWith("\t")) {
362
+ const uncommitted = /^0+$/.test(current.commit);
363
+ lines.push({
364
+ line: current.final,
365
+ commit: uncommitted ? "uncommitted" : current.commit.slice(0, 12),
366
+ author: uncommitted ? "Not committed yet" : m.author,
367
+ date: uncommitted || m.time === null ? null : new Date(m.time * 1000).toISOString(),
368
+ summary: uncommitted ? "" : m.summary,
369
+ text: raw.slice(1).replace(/\r$/, ""),
370
+ uncommitted
371
+ });
372
+ current = null;
373
+ }
374
+ }
375
+ return { lines };
376
+ }
377
+ /** One commit: metadata and per-file counts; a bounded patch only for one validated path. */
378
+ export function gitShow(root, revision, relPath) {
379
+ const rev = requireRevision(revision);
380
+ const overrides = overridesFor(root);
381
+ const meta = run(root, ["show", "-s", ...HISTORY_GUARDS, `--format=%H${FIELD}%h${FIELD}%an${FIELD}%aI${FIELD}%s${FIELD}%b`, rev, "--"], overrides);
382
+ if (!meta.ok) {
383
+ if (noHistory(meta.reason) || /bad object|bad revision/i.test(meta.reason ?? "")) {
384
+ throw new GitToolError("UNKNOWN_REVISION", `No commit matches ${rev}.`);
385
+ }
386
+ throw new GitToolError("GIT_FAILED", meta.reason ?? "git show failed.");
387
+ }
388
+ const [commit, short, author, date, subject, ...body] = meta.out.replace(/\n+$/, "").split(FIELD);
389
+ const stat = run(root, ["show", ...HISTORY_GUARDS, "--numstat", "--format=", rev, "--"], overrides);
390
+ if (!stat.ok)
391
+ throw new GitToolError("GIT_FAILED", stat.reason ?? "git show failed.");
392
+ const files = [];
393
+ let filesTruncated = false;
394
+ for (const raw of stat.out.split(/\r?\n/)) {
395
+ if (!raw.trim())
396
+ continue;
397
+ if (files.length >= MAX_FILES) {
398
+ filesTruncated = true;
399
+ break;
400
+ }
401
+ const [add, del, ...name] = raw.split("\t");
402
+ files.push({ path: name.join("\t"), additions: add === "-" ? null : Number(add), deletions: del === "-" ? null : Number(del) });
403
+ }
404
+ const result = {
405
+ commit,
406
+ short,
407
+ author,
408
+ date,
409
+ subject: subject ?? "",
410
+ body: body.join(FIELD).trim().slice(0, 4000),
411
+ files_changed: files,
412
+ files_truncated: filesTruncated,
413
+ truncated: false
414
+ };
415
+ if (relPath) {
416
+ const patch = run(root, ["show", ...HISTORY_GUARDS, "--format=", rev, "--", relPath], overrides);
417
+ if (!patch.ok)
418
+ throw new GitToolError("GIT_FAILED", patch.reason ?? "git show failed.");
419
+ let diff = patch.out;
420
+ if (Buffer.byteLength(diff, "utf8") > MAX_DIFF_BYTES) {
421
+ diff = diff.slice(0, MAX_DIFF_BYTES);
422
+ diff = diff.slice(0, diff.lastIndexOf("\n") + 1) + "… [diff truncated]\n";
423
+ result.truncated = true;
424
+ }
425
+ result.path = relPath;
426
+ result.diff = diff;
427
+ }
428
+ return result;
429
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Glob patterns, compiled to regular expressions.
3
+ *
4
+ * Written here rather than pulled in as a dependency for two reasons. The CLI
5
+ * ships to npm, so every runtime dependency is install weight and supply-chain
6
+ * surface for its users. And the second consumer is `.gitignore`, whose rules
7
+ * are glob-shaped but carry their own semantics — anchoring, negation,
8
+ * directory-only matching — that no glob package implements. A matcher shared
9
+ * by both is less code than a dependency plus the translation layer it would
10
+ * still need.
11
+ *
12
+ * Paths handed to the compiled expressions are always relative and POSIX-
13
+ * separated. Callers normalize before matching, so nothing here has to think
14
+ * about backslashes.
15
+ */
16
+ /** Characters with meaning in a regular expression but not in a glob. */
17
+ function escapeLiteral(ch) {
18
+ return /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
19
+ }
20
+ /**
21
+ * Translate one glob body into regex source.
22
+ *
23
+ * The separator rule is the whole point of a glob and the thing a naive
24
+ * implementation gets wrong: `*` stops at a `/`, `**` crosses them. `**\/` is
25
+ * treated as a unit so that `**\/*.ts` matches `a.ts` at the root as well as
26
+ * `src/a.ts` — without that, the leading `/` would be mandatory and the most
27
+ * common pattern anyone types would quietly miss top-level files.
28
+ */
29
+ function translate(glob) {
30
+ let out = "";
31
+ let i = 0;
32
+ while (i < glob.length) {
33
+ const ch = glob[i];
34
+ if (ch === "*") {
35
+ if (glob[i + 1] === "*") {
36
+ // `**/` — any number of leading directories, including none.
37
+ if (glob[i + 2] === "/") {
38
+ out += "(?:[^/]+/)*";
39
+ i += 3;
40
+ continue;
41
+ }
42
+ out += ".*";
43
+ i += 2;
44
+ continue;
45
+ }
46
+ out += "[^/]*";
47
+ i += 1;
48
+ continue;
49
+ }
50
+ if (ch === "?") {
51
+ out += "[^/]";
52
+ i += 1;
53
+ continue;
54
+ }
55
+ if (ch === "[") {
56
+ const cls = readClass(glob, i);
57
+ if (cls) {
58
+ out += cls.source;
59
+ i = cls.next;
60
+ continue;
61
+ }
62
+ // Unterminated — treat as a literal bracket rather than failing.
63
+ out += "\\[";
64
+ i += 1;
65
+ continue;
66
+ }
67
+ if (ch === "{") {
68
+ const alt = readBraces(glob, i);
69
+ if (alt) {
70
+ out += `(?:${alt.parts.map(translate).join("|")})`;
71
+ i = alt.next;
72
+ continue;
73
+ }
74
+ out += "\\{";
75
+ i += 1;
76
+ continue;
77
+ }
78
+ if (ch === "\\" && i + 1 < glob.length) {
79
+ out += escapeLiteral(glob[i + 1]);
80
+ i += 2;
81
+ continue;
82
+ }
83
+ out += escapeLiteral(ch);
84
+ i += 1;
85
+ }
86
+ return out;
87
+ }
88
+ /** `[abc]`, `[!a-z]`, `[]]` — returns regex source and the index after the class. */
89
+ function readClass(glob, start) {
90
+ let i = start + 1;
91
+ let negated = false;
92
+ if (glob[i] === "!" || glob[i] === "^") {
93
+ negated = true;
94
+ i += 1;
95
+ }
96
+ // A `]` in the first position is a literal, per POSIX.
97
+ let body = "";
98
+ if (glob[i] === "]") {
99
+ body += "\\]";
100
+ i += 1;
101
+ }
102
+ while (i < glob.length && glob[i] !== "]") {
103
+ const ch = glob[i];
104
+ body += ch === "\\" || ch === "^" ? `\\${ch}` : ch;
105
+ i += 1;
106
+ }
107
+ if (glob[i] !== "]")
108
+ return null;
109
+ // A class must never match a separator, or `src/[a-z]*` would cross directories.
110
+ return { source: `(?![/])[${negated ? "^" : ""}${body}]`, next: i + 1 };
111
+ }
112
+ /** `{a,b}` — returns the top-level alternatives and the index after the brace. */
113
+ function readBraces(glob, start) {
114
+ let depth = 0;
115
+ const parts = [];
116
+ let current = "";
117
+ for (let i = start; i < glob.length; i += 1) {
118
+ const ch = glob[i];
119
+ if (ch === "{") {
120
+ depth += 1;
121
+ if (depth === 1)
122
+ continue;
123
+ }
124
+ else if (ch === "}") {
125
+ depth -= 1;
126
+ if (depth === 0) {
127
+ parts.push(current);
128
+ return { parts, next: i + 1 };
129
+ }
130
+ }
131
+ else if (ch === "," && depth === 1) {
132
+ parts.push(current);
133
+ current = "";
134
+ continue;
135
+ }
136
+ current += ch;
137
+ }
138
+ return null;
139
+ }
140
+ /**
141
+ * Windows filesystems are case-insensitive, and so is Git there by default
142
+ * (`core.ignorecase`). Matching case-sensitively would mean `*.TS` files
143
+ * silently escaping a `*.ts` pattern on the platform this CLI targets first.
144
+ */
145
+ const CASE_FLAG = process.platform === "win32" ? "i" : "";
146
+ /** Compile a glob anchored to the whole relative path. */
147
+ export function compileGlob(glob) {
148
+ return new RegExp(`^${translate(glob.replace(/^\.\//, ""))}$`, CASE_FLAG);
149
+ }
150
+ /**
151
+ * Compile a `.gitignore` pattern body.
152
+ *
153
+ * `anchored` reflects Git's rule that a pattern containing a slash anywhere but
154
+ * its end is matched from the directory holding the .gitignore, while a bare
155
+ * name like `*.log` matches at any depth.
156
+ */
157
+ export function compileIgnorePattern(pattern, anchored) {
158
+ const body = translate(pattern);
159
+ return new RegExp(anchored ? `^${body}$` : `^(?:.*/)?${body}$`, CASE_FLAG);
160
+ }
161
+ /** Normalize any path to the relative POSIX form the matchers expect. */
162
+ export function toPosix(p) {
163
+ return p.replace(/\\/g, "/").replace(/^\.\//, "");
164
+ }
@@ -0,0 +1,85 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { isPackaged, PACKAGED_DOWNLOAD_URL } from "./packaged.js";
5
+ export function sha256File(file) {
6
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
7
+ }
8
+ const HEX64 = /^[0-9a-f]{64}$/;
9
+ /**
10
+ * The baked helper hashes, or null when the build carries none or carries
11
+ * something malformed. Null is never "anything goes": in packaged mode it means
12
+ * no helper verifies, so the caller fails closed.
13
+ */
14
+ export function bakedHelperHashes(raw = typeof __HELPER_HASHES__ === "string" ? __HELPER_HASHES__ : undefined) {
15
+ if (typeof raw !== "string" || !raw)
16
+ return null;
17
+ try {
18
+ const parsed = JSON.parse(raw);
19
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
20
+ return null;
21
+ const out = {};
22
+ for (const [name, hash] of Object.entries(parsed)) {
23
+ if (!/^[A-Za-z0-9._-]+\.exe$/.test(name) || typeof hash !== "string" || !HEX64.test(hash))
24
+ return null;
25
+ out[name] = hash;
26
+ }
27
+ return Object.keys(out).length ? out : null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function devCandidateDirs(exeDir, env) {
34
+ const dirs = [];
35
+ if (env.COS_HELPER_DIR)
36
+ dirs.push(env.COS_HELPER_DIR);
37
+ dirs.push(exeDir, path.join(exeDir, "bin"));
38
+ return dirs;
39
+ }
40
+ /**
41
+ * The absolute path to a verified prebuilt `<baseName>.exe`, or null.
42
+ *
43
+ * Packaged: null means the installation is damaged — callers must fail closed.
44
+ * Development: null means "none shipped" — callers may compile from source.
45
+ */
46
+ export function findPrebuiltHelper(baseName, opts = {}) {
47
+ const platform = opts.platform ?? process.platform;
48
+ if (platform !== "win32")
49
+ return null;
50
+ const packaged = opts.packaged ?? isPackaged();
51
+ const exeDir = opts.exeDir ?? path.dirname(process.execPath);
52
+ const file = `${baseName}.exe`;
53
+ if (packaged) {
54
+ const hashes = opts.hashes !== undefined ? opts.hashes : bakedHelperHashes();
55
+ const expected = hashes?.[file];
56
+ if (!expected)
57
+ return null;
58
+ const exe = path.join(exeDir, file);
59
+ try {
60
+ return fs.statSync(exe).isFile() && sha256File(exe) === expected ? exe : null;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ for (const dir of devCandidateDirs(exeDir, opts.env ?? process.env)) {
67
+ const exe = path.join(dir, file);
68
+ const stamp = `${exe}.sha256`;
69
+ try {
70
+ if (!fs.existsSync(exe) || !fs.existsSync(stamp))
71
+ continue;
72
+ const expected = fs.readFileSync(stamp, "utf8").trim();
73
+ if (expected && sha256File(exe) === expected)
74
+ return exe;
75
+ }
76
+ catch {
77
+ /* unreadable candidate — try the next */
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ /** The message every fail-closed packaged path shows. */
83
+ export function damagedInstallMessage(file) {
84
+ return `This Carrier OS installation is missing or has a damaged component (${file}). Reinstall Carrier OS from ${PACKAGED_DOWNLOAD_URL}.`;
85
+ }