tracehub 0.0.0-stage → 0.5.2

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 (48) hide show
  1. package/README.md +431 -2
  2. package/dist/cli/args.js +28 -0
  3. package/dist/cli/clipboard.js +46 -0
  4. package/dist/cli/commands/context.js +115 -0
  5. package/dist/cli/commands/hook.js +215 -0
  6. package/dist/cli/commands/providers.js +55 -0
  7. package/dist/cli/commands/setup.js +448 -0
  8. package/dist/cli/commands/uninstall.js +156 -0
  9. package/dist/cli/io.js +26 -0
  10. package/dist/cli/remote.js +81 -0
  11. package/dist/cli/repo.js +70 -0
  12. package/dist/cli/signin.js +90 -0
  13. package/dist/cli/ui.js +130 -0
  14. package/dist/cli/usage.js +151 -0
  15. package/dist/cli.js +38 -0
  16. package/dist/client/auth.js +70 -0
  17. package/dist/client/consent.js +94 -0
  18. package/dist/client/errors.js +4 -0
  19. package/dist/client/github.js +129 -0
  20. package/dist/client/registry.js +112 -0
  21. package/dist/client/tracehub.js +98 -0
  22. package/dist/client/upload.js +106 -0
  23. package/dist/client/uploadPolicy.js +60 -0
  24. package/dist/git/git.js +163 -0
  25. package/dist/git/global-hooks.js +221 -0
  26. package/dist/git/hooks.js +67 -0
  27. package/dist/git/markers.js +93 -0
  28. package/dist/git/trailers.js +36 -0
  29. package/dist/local/commitBoundary.js +38 -0
  30. package/dist/local/discover.js +283 -0
  31. package/dist/local/files.js +55 -0
  32. package/dist/local/lines.js +16 -0
  33. package/dist/local/opencode.js +124 -0
  34. package/dist/local/paths.js +51 -0
  35. package/dist/local/providers.js +171 -0
  36. package/dist/local/subagents.js +63 -0
  37. package/dist/protocol/context.js +202 -0
  38. package/dist/protocol/sessionRef.js +24 -0
  39. package/dist/protocol/trace.js +111 -0
  40. package/dist/redact/deny.js +25 -0
  41. package/dist/redact/redact.js +189 -0
  42. package/dist/trace/build.js +256 -0
  43. package/dist/transcript/parseClaude.js +105 -0
  44. package/dist/transcript/parseCodex.js +164 -0
  45. package/dist/transcript/parseOpencode.js +84 -0
  46. package/dist/transcript/title.js +27 -0
  47. package/dist/transcript/transcript.js +120 -0
  48. package/package.json +44 -4
@@ -0,0 +1,448 @@
1
+ import { cancel, confirm, intro, isCancel, log, multiselect, note, outro, select, text, } from "@clack/prompts";
2
+ import { join } from "node:path";
3
+ import { freshAuth, isExpired, readAuth } from "../../client/auth.js";
4
+ import { consentRules, consentScope, ignoredRules, readConsent, removeConsent, scopeKey, setConsent, writeConsent, } from "../../client/consent.js";
5
+ import { markPending, reason, registerConsent, registrationPending, } from "../../client/registry.js";
6
+ import { tracehubUrl } from "../../client/tracehub.js";
7
+ import { originUrl, tryGit } from "../../git/git.js";
8
+ import { hasGlobalHooks, installGlobalHooks, removeGlobalHooks, } from "../../git/global-hooks.js";
9
+ import { configDir, consentFile } from "../../local/paths.js";
10
+ import { Reported, requireTerminal, usageError } from "../io.js";
11
+ import { signIn } from "../signin.js";
12
+ import { bad, bold, dim, done, plural, rows, skipped, step, Stopped, tilde, title, waiting, } from "../ui.js";
13
+ import { commandUsage } from "../usage.js";
14
+ const STEPS = 3;
15
+ // A prompt's answer, or Stopped when the user pressed Ctrl-C or Escape.
16
+ async function answer(prompt) {
17
+ const value = await prompt;
18
+ if (isCancel(value))
19
+ throw new Stopped();
20
+ return value;
21
+ }
22
+ export async function cmdSetup(args, cwd, options = {}) {
23
+ if (args.flags["help"] || args.flags["h"]) {
24
+ process.stdout.write(`${commandUsage("setup")}\n`);
25
+ return;
26
+ }
27
+ if (args.positional.length > 1 || Object.keys(args.flags).length)
28
+ throw usageError("setup", args);
29
+ requireTerminal("setup", options.interactive);
30
+ const io = options.streams ?? {};
31
+ // What is saved so far, for the message when setup stops early.
32
+ const progress = { account: "", rules: "" };
33
+ const saved = () => [progress.account, progress.rules].filter(Boolean).join(", ");
34
+ intro(title("setup"), io);
35
+ log.message(dim("Link the coding-agent sessions behind your commits to your pull requests.\nThree short steps; each is saved as you go."), io);
36
+ try {
37
+ const account = await accountStep(io, options);
38
+ progress.account = `account (${account ?? "not signed in"})`;
39
+ const rules = await rulesStep(io, cwd, () => {
40
+ progress.rules = "your rule changes";
41
+ markPending();
42
+ });
43
+ progress.rules = "permission rules";
44
+ const registry = await registerRules(io, options);
45
+ const hooks = await hooksStep(io, cwd);
46
+ summary(io, account, rules, hooks, registry);
47
+ }
48
+ catch (err) {
49
+ if (err instanceof Stopped) {
50
+ cancel(saved()
51
+ ? `Setup stopped. Saved: ${saved()}.\n Run tracehub setup again to pick up from here.`
52
+ : "Setup stopped. Nothing was changed.", io);
53
+ return;
54
+ }
55
+ log.error(err.message, io);
56
+ cancel(saved()
57
+ ? `Setup stopped. Saved: ${saved()}.`
58
+ : "Setup stopped. Nothing was changed.", io);
59
+ throw new Reported(err.message);
60
+ }
61
+ }
62
+ // Step 1: who the sessions are uploaded as. One account is stored at a time,
63
+ // so switching accounts means signing in again.
64
+ async function accountStep(io, options) {
65
+ step(1, STEPS, "Account", io);
66
+ let auth = readAuth();
67
+ if (auth && isExpired(auth)) {
68
+ log.warn(`Your sign-in as ${auth.login} expired. Sign in again.`, io);
69
+ auth = undefined;
70
+ }
71
+ else if (auth) {
72
+ const current = auth;
73
+ try {
74
+ auth = await waiting("Checking your GitHub sign-in", () => freshAuth(current, process.env, options.fetchFn), io);
75
+ }
76
+ catch (err) {
77
+ // freshAuth forgets a sign-in GitHub refused; anything else is kept.
78
+ if (err instanceof Stopped || readAuth())
79
+ throw err;
80
+ log.warn(err.message, io);
81
+ auth = undefined;
82
+ }
83
+ }
84
+ const choice = await answer(auth
85
+ ? select({
86
+ ...io,
87
+ message: `Signed in to GitHub as ${bold(auth.login)}`,
88
+ options: [
89
+ { value: "keep", label: `Keep ${auth.login}` },
90
+ {
91
+ value: "switch",
92
+ label: "Use another GitHub account",
93
+ hint: "signs in again in the browser",
94
+ },
95
+ ],
96
+ })
97
+ : select({
98
+ ...io,
99
+ message: "Sign in to GitHub",
100
+ options: [
101
+ {
102
+ value: "switch",
103
+ label: "Sign in with GitHub",
104
+ hint: "opens your browser",
105
+ },
106
+ {
107
+ value: "keep",
108
+ label: "Skip for now",
109
+ hint: "nothing uploads until you sign in",
110
+ },
111
+ ],
112
+ }));
113
+ if (choice === "keep")
114
+ return auth?.login;
115
+ if (auth)
116
+ log.info("GitHub signs in whichever account your browser uses;\nswitch accounts on github.com first.", io);
117
+ const signed = await signIn({
118
+ streams: io,
119
+ ...(options.fetchFn ? { fetchFn: options.fetchFn } : {}),
120
+ ...(options.openBrowser ? { openBrowser: options.openBrowser } : {}),
121
+ ...(options.copy ? { copy: options.copy } : {}),
122
+ });
123
+ done(`Signed in as ${bold(signed.login)}`, io);
124
+ return signed.login;
125
+ }
126
+ const SHARING = [
127
+ "· The whole agent conversation, and the changes you push",
128
+ "· Visible to the repository's maintainers (write, maintain or admin)",
129
+ "· Tool calls stay visible to you only",
130
+ "· Secrets are redacted on a best-effort basis: keep private work",
131
+ " in a separate agent session",
132
+ ].join("\n");
133
+ const kindOf = (rule) => rule.kind === "organization" ? "all repositories" : "repository";
134
+ function ruleList(rules) {
135
+ if (!rules.length)
136
+ return dim("None yet: nothing uploads until you allow an\norganization or a repository.");
137
+ const width = Math.max(...rules.map((rule) => rule.scope.length));
138
+ return rules
139
+ .map((rule) => `${rule.scope.padEnd(width)} ${dim(kindOf(rule))}${rule.upload ? "" : ` ${bad("declined")}`}`)
140
+ .join("\n");
141
+ }
142
+ // Step 2: the permission rules. A rule allows uploads for a GitHub
143
+ // organization or for one repository; a repository's rule wins.
144
+ async function rulesStep(io, cwd, changed) {
145
+ step(2, STEPS, "Permission rules", io);
146
+ log.message(dim("Sessions upload only for the organizations and repositories you allow."), io);
147
+ const file = consentFile();
148
+ let store = readConsent(file);
149
+ const ignored = ignoredRules(store);
150
+ if (ignored.length) {
151
+ store = removeConsent(store, ignored);
152
+ writeConsent(file, store);
153
+ changed();
154
+ log.warn(`Removed ${ignored.map((key) => (key === "github.com/*" ? "the consent for every GitHub repository" : `"${key}"`)).join(", ")}:\na rule is for one organization or one repository. Add the ones you want.`, io);
155
+ }
156
+ let shown = false;
157
+ for (;;) {
158
+ const rules = consentRules(store);
159
+ if (!shown)
160
+ note(ruleList(rules), "Your rules", io);
161
+ shown = true;
162
+ const action = await answer(select({
163
+ ...io,
164
+ message: "Change the permission rules?",
165
+ initialValue: rules.length ? "done" : "add",
166
+ options: [
167
+ {
168
+ value: "add",
169
+ label: "Allow an organization or repository",
170
+ },
171
+ ...(rules.length ? [{ value: "revoke", label: "Revoke rules" }] : []),
172
+ {
173
+ value: "done",
174
+ label: "Continue",
175
+ hint: rules.length
176
+ ? "to Git hooks"
177
+ : "without a rule, nothing uploads",
178
+ },
179
+ ],
180
+ }));
181
+ if (action === "done")
182
+ return rules;
183
+ if (action === "revoke") {
184
+ const revoked = await answer(multiselect({
185
+ ...io,
186
+ message: "Revoke which rules?",
187
+ options: rules.map((rule) => ({
188
+ value: rule.key,
189
+ label: rule.scope,
190
+ hint: rule.upload ? kindOf(rule) : `${kindOf(rule)}, declined`,
191
+ })),
192
+ required: false,
193
+ }));
194
+ if (revoked.length) {
195
+ store = removeConsent(store, revoked);
196
+ writeConsent(file, store);
197
+ changed();
198
+ done(`Revoked ${plural(revoked.length, "rule")}`, io);
199
+ shown = false;
200
+ }
201
+ else
202
+ skipped("Nothing revoked", io);
203
+ continue;
204
+ }
205
+ const key = await chooseScope(io, cwd, rules);
206
+ const scope = key.slice("github.com/".length).replace(/\/\*$/, "");
207
+ const organization = key.endsWith("/*");
208
+ note(SHARING, "What an upload shares", io);
209
+ if (await answer(confirm({
210
+ ...io,
211
+ message: `Allow uploads for ${bold(scope)}${organization ? dim(" (all repositories)") : ""}?`,
212
+ initialValue: false,
213
+ }))) {
214
+ store = setConsent(store, key, true);
215
+ writeConsent(file, store);
216
+ changed();
217
+ done(`Allowed ${bold(scope)}`, io);
218
+ shown = false;
219
+ }
220
+ else
221
+ skipped("No rule added", io);
222
+ }
223
+ }
224
+ // The end of step 2: TraceHub gets this machine's rules, for its roster of
225
+ // who consented. Offline or signed out, the rules work here as before and
226
+ // are sent on the next push or setup.
227
+ async function registerRules(io, options) {
228
+ const store = readConsent(consentFile());
229
+ const auth = readAuth();
230
+ if (!auth || isExpired(auth)) {
231
+ if (!registrationPending(store))
232
+ return "nothing";
233
+ markPending();
234
+ log.info("Sign in so TraceHub can register your consent. Your rules work\nhere either way.", io);
235
+ return "signed out";
236
+ }
237
+ try {
238
+ await waiting("Registering your consent with TraceHub", (signal) => registerConsent(tracehubUrl(), auth.accessToken, store, {
239
+ signal,
240
+ ...(options.fetchFn ? { fetchFn: options.fetchFn } : {}),
241
+ }), io);
242
+ }
243
+ catch (err) {
244
+ if (err instanceof Stopped)
245
+ throw err;
246
+ log.warn(`Couldn't register your consent with TraceHub (${reason(err)}).\nYour rules are saved here; they're sent on your next push or setup.`, io);
247
+ return "pending";
248
+ }
249
+ done(consentRules(store).length
250
+ ? "Registered your consent with TraceHub"
251
+ : "TraceHub knows this machine has no rules", io);
252
+ return "registered";
253
+ }
254
+ // What a typed scope is wrong with, if anything. A pasted GitHub URL or
255
+ // clone address works too.
256
+ export function typedScope(value) {
257
+ const typed = value
258
+ .trim()
259
+ .replace(/^(?:https?:\/\/)?(?:www\.)?github\.com[/:]/i, "")
260
+ .replace(/^git@github\.com:/i, "")
261
+ .replace(/\.git$/i, "")
262
+ .replace(/\/+$/, "");
263
+ if (!typed)
264
+ return {
265
+ error: "Type an organization, like acme, or a repository, like acme/web.",
266
+ };
267
+ if (typed.includes("*"))
268
+ return {
269
+ error: "No wildcards: type just the organization to allow all its repositories.",
270
+ };
271
+ const [owner, repo, ...rest] = typed.split("/");
272
+ if (rest.length)
273
+ return { error: "Use owner or owner/repo, with at most one slash." };
274
+ if (!/^[a-z0-9-]+$/i.test(owner ?? ""))
275
+ return {
276
+ error: `"${owner}" isn't a GitHub owner: letters, digits and hyphens only.`,
277
+ };
278
+ const key = scopeKey(typed);
279
+ if (!key || repo === "")
280
+ return { error: `"${repo}" isn't a valid repository name.` };
281
+ return { key };
282
+ }
283
+ // The current repository and its organization are offered first.
284
+ async function chooseScope(io, cwd, rules) {
285
+ const allowed = new Set(rules.filter((rule) => rule.upload).map((rule) => rule.key));
286
+ const origin = originUrl(cwd);
287
+ const repo = origin ? consentScope(origin) : undefined;
288
+ const owner = repo?.split("/")[1];
289
+ const org = owner && `github.com/${owner}/*`;
290
+ const suggestions = repo && org
291
+ ? [
292
+ {
293
+ value: repo,
294
+ label: repo.slice("github.com/".length),
295
+ hint: "this repository",
296
+ },
297
+ {
298
+ value: org,
299
+ label: owner,
300
+ hint: `every repository in ${owner}, now and later`,
301
+ },
302
+ ].filter(
303
+ // A repository is already covered by its allowed organization.
304
+ (option) => !allowed.has(option.value) &&
305
+ !(option.value === repo && allowed.has(org)))
306
+ : [];
307
+ const picked = suggestions.length
308
+ ? await answer(select({
309
+ ...io,
310
+ message: "Allow uploads for",
311
+ options: [
312
+ ...suggestions,
313
+ { value: "other", label: "Another organization or repository…" },
314
+ ],
315
+ }))
316
+ : "other";
317
+ if (picked !== "other")
318
+ return picked;
319
+ const typed = await answer(text({
320
+ ...io,
321
+ message: "Organization or repository",
322
+ placeholder: "owner, or owner/repo",
323
+ validate: (value) => {
324
+ const result = typedScope(value ?? "");
325
+ return "error" in result ? result.error : undefined;
326
+ },
327
+ }));
328
+ return typedScope(typed).key;
329
+ }
330
+ const HOOKS = [
331
+ rows([
332
+ ["prepare-commit-msg", "marks commits made with an agent (Assisted-by)"],
333
+ ["pre-push", "uploads their sessions, redacted, as you push"],
334
+ ]),
335
+ "",
336
+ "They run in every repository, and only act where a rule allows.",
337
+ "Your own hooks still run; a hook never blocks a commit or push.",
338
+ `Skip them once with ${bold("TRACEHUB=0")}, e.g. TRACEHUB=0 git push.`,
339
+ ].join("\n");
340
+ // Step 3: the global Git hooks.
341
+ async function hooksStep(io, cwd) {
342
+ step(3, STEPS, "Git hooks", io);
343
+ note(HOOKS, "What the hooks do", io);
344
+ const local = tryGit(["config", "--local", "core.hooksPath"], { cwd });
345
+ if (local)
346
+ log.warn(`This repository sets its own core.hooksPath (${local}, Husky does),\nso global hooks don't run here.`, io);
347
+ const directory = join(configDir(), "hooks");
348
+ try {
349
+ if (hasGlobalHooks(directory, cwd)) {
350
+ const choice = await answer(select({
351
+ ...io,
352
+ message: "The global Git hooks are installed",
353
+ options: [
354
+ { value: "keep", label: "Keep them" },
355
+ {
356
+ value: "remove",
357
+ label: "Remove them",
358
+ hint: "restores your previous hooks setting",
359
+ },
360
+ ],
361
+ }));
362
+ if (choice === "remove") {
363
+ removeGlobalHooks(directory, cwd);
364
+ done("Removed the global Git hooks", io);
365
+ return "removed";
366
+ }
367
+ // Hooks of another version, or of an earlier release, are brought up
368
+ // to date.
369
+ if (installGlobalHooks(directory, cwd) === "updated") {
370
+ done("Updated the hooks to run this tracehub", io);
371
+ return "updated";
372
+ }
373
+ return "installed";
374
+ }
375
+ const install = await answer(confirm({
376
+ ...io,
377
+ message: "Install the global Git hooks?",
378
+ initialValue: true,
379
+ }));
380
+ if (!install) {
381
+ skipped("Hooks not installed", io);
382
+ return "not installed";
383
+ }
384
+ installGlobalHooks(directory, cwd);
385
+ done(`Installed the global Git hooks ${dim(`in ${tilde(directory)}`)}`, io);
386
+ return "installed";
387
+ }
388
+ catch (err) {
389
+ if (err instanceof Stopped)
390
+ throw err;
391
+ log.error(`Couldn't change the Git hooks, so they were left as they are:\n${err.message}`, io);
392
+ return "unchanged";
393
+ }
394
+ }
395
+ const listed = (items) => items.length > 1
396
+ ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`
397
+ : (items[0] ?? "");
398
+ // A receipt of what setup left, and what to do next.
399
+ function summary(io, account, rules, hooks, registry) {
400
+ const allowed = rules.filter((rule) => rule.upload);
401
+ const hooksOn = hooks === "installed" || hooks === "updated";
402
+ note(rows([
403
+ ["Account", account ?? dim("not signed in")],
404
+ [
405
+ "Uploads",
406
+ allowed.length
407
+ ? allowed
408
+ .map((rule) => rule.kind === "organization"
409
+ ? `${rule.scope} ${dim("(all repos)")}`
410
+ : rule.scope)
411
+ .join(", ")
412
+ : dim("none"),
413
+ ],
414
+ ...(allowed.length || registry === "pending"
415
+ ? [
416
+ [
417
+ "TraceHub",
418
+ {
419
+ registered: "consent registered",
420
+ pending: dim("consent not registered yet; sent on your next push"),
421
+ "signed out": dim("consent not registered; sign in"),
422
+ nothing: dim("consent not registered"),
423
+ }[registry],
424
+ ],
425
+ ]
426
+ : []),
427
+ [
428
+ "Git hooks",
429
+ {
430
+ installed: `installed ${dim(tilde(join(configDir(), "hooks")))}`,
431
+ updated: `updated ${dim(tilde(join(configDir(), "hooks")))}`,
432
+ removed: "removed",
433
+ "not installed": dim("not installed"),
434
+ unchanged: dim("left as they were"),
435
+ }[hooks],
436
+ ],
437
+ ]), "Summary", io);
438
+ const missing = [
439
+ ...(account ? [] : ["sign in"]),
440
+ ...(allowed.length ? [] : ["allow an organization or repository"]),
441
+ ...(hooksOn ? [] : ["install the Git hooks"]),
442
+ ];
443
+ if (!missing.length) {
444
+ outro(`You're all set. Commit and push as usual: commits made with an agent\n get an Assisted-by link, and their sessions upload when you push.`, io);
445
+ return;
446
+ }
447
+ outro(`Saved. Nothing uploads until you ${listed(missing)}:\n run tracehub setup again when you're ready.`, io);
448
+ }
@@ -0,0 +1,156 @@
1
+ import { cancel, confirm, intro, isCancel, log, note, outro, } from "@clack/prompts";
2
+ import { existsSync, rmSync, rmdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { clearAuth, freshAuth, isExpired, readAuth, } from "../../client/auth.js";
5
+ import { clearRegistryState, readRegistryState, reason, revokeRegistration, } from "../../client/registry.js";
6
+ import { tracehubUrl } from "../../client/tracehub.js";
7
+ import { consentRules, readConsent } from "../../client/consent.js";
8
+ import { gitDir } from "../../git/git.js";
9
+ import { removeGlobalHooks } from "../../git/global-hooks.js";
10
+ import { pendingMarkers, readMarkers } from "../../git/markers.js";
11
+ import { configDir, consentFile, GIT_STATE_DIR } from "../../local/paths.js";
12
+ import { denyFile, readDenyList } from "../../redact/deny.js";
13
+ import { Reported, requireTerminal, usageError } from "../io.js";
14
+ import { bold, dim, done, plural, rows, skipped, Stopped, tilde, title, waiting, } from "../ui.js";
15
+ import { commandUsage } from "../usage.js";
16
+ // Removes what setup made: the global hooks, the permission rules and the
17
+ // sign-in. The deny list and this repository's trace state go only when the
18
+ // user says so; other repositories keep theirs.
19
+ export async function cmdUninstall(args, cwd, options = {}) {
20
+ if (args.flags["help"] || args.flags["h"]) {
21
+ process.stdout.write(`${commandUsage("uninstall")}\n`);
22
+ return;
23
+ }
24
+ if (args.positional.length > 1 || Object.keys(args.flags).length)
25
+ throw usageError("uninstall", args);
26
+ requireTerminal("uninstall", options.interactive);
27
+ const io = options.streams ?? {};
28
+ const ask = async (message) => {
29
+ const value = await confirm({ ...io, message, initialValue: false });
30
+ if (isCancel(value))
31
+ throw new Stopped();
32
+ return value;
33
+ };
34
+ intro(title("uninstall"), io);
35
+ const hooks = join(configDir(), "hooks");
36
+ const hooksInstalled = existsSync(join(hooks, "tracehub.json"));
37
+ const rules = consentRules(readConsent(consentFile()));
38
+ const login = readAuth()?.login;
39
+ const git = gitDir(cwd);
40
+ const state = git && join(git, GIT_STATE_DIR);
41
+ const hasState = !!state && existsSync(state);
42
+ const hasDeny = existsSync(denyFile());
43
+ if (!hooksInstalled && !rules.length && !login && !hasDeny && !hasState) {
44
+ outro("Nothing to remove: tracehub isn't set up on this machine.", io);
45
+ return;
46
+ }
47
+ const removes = [];
48
+ if (hooksInstalled)
49
+ removes.push([
50
+ "Git hooks",
51
+ `${tilde(hooks)}, restoring your previous hooks setting`,
52
+ ]);
53
+ if (rules.length)
54
+ removes.push([
55
+ "Rules",
56
+ `${plural(rules.length, "permission rule")} (${rules.map((rule) => rule.scope).join(", ")})`,
57
+ ]);
58
+ if (login)
59
+ removes.push(["Sign-in", `GitHub account ${login}`]);
60
+ let stage = "Nothing was changed.";
61
+ try {
62
+ if (removes.length) {
63
+ note(`${rows(removes)}\n\n${dim("You'll be asked about your deny list and this repository's\ntrace state. Other repositories keep their .git/tracehub.")}`, "This removes", io);
64
+ if (!(await ask("Uninstall tracehub?"))) {
65
+ cancel("Nothing was changed.", io);
66
+ return;
67
+ }
68
+ }
69
+ let failure;
70
+ if (hooksInstalled) {
71
+ try {
72
+ removeGlobalHooks(hooks, cwd);
73
+ rmdirSync(hooks);
74
+ done("Removed the global Git hooks", io);
75
+ }
76
+ catch (err) {
77
+ failure = `The global Git hooks were not removed: ${err.message}`;
78
+ log.error(failure, io);
79
+ }
80
+ }
81
+ if (rules.length || login) {
82
+ if (rules.length || readRegistryState())
83
+ await unregister(io, options);
84
+ clearRegistryState();
85
+ rmSync(consentFile(), { force: true });
86
+ clearAuth();
87
+ done([
88
+ ...(rules.length
89
+ ? [`Removed ${plural(rules.length, "permission rule")}`]
90
+ : []),
91
+ ...(login ? [`signed out ${bold(login)}`] : []),
92
+ ].join(" and "), io);
93
+ }
94
+ stage = "The rest was kept.";
95
+ if (hasDeny) {
96
+ const deny = readDenyList();
97
+ if (await ask(`Also delete your deny list? ${dim(`(${plural(deny.length, "entry", "entries")}, ${tilde(denyFile())})`)}`)) {
98
+ rmSync(denyFile());
99
+ done("Deleted the deny list", io);
100
+ }
101
+ else
102
+ skipped("Kept the deny list", io);
103
+ }
104
+ if (hasState) {
105
+ const pending = pendingMarkers(readMarkers(state)).length;
106
+ if (await ask(`Also delete this repository's trace state?${pending ? dim(` (${plural(pending, "marker")} not uploaded)`) : ""}`)) {
107
+ rmSync(state, { recursive: true, force: true });
108
+ done("Deleted this repository's trace state", io);
109
+ }
110
+ else
111
+ skipped("Kept this repository's trace state", io);
112
+ }
113
+ try {
114
+ rmdirSync(configDir());
115
+ }
116
+ catch {
117
+ // Not empty: the deny list, or files of the user's own, stay.
118
+ }
119
+ if (failure) {
120
+ cancel("Uninstalled, except for the Git hooks.", io);
121
+ throw new Reported(failure);
122
+ }
123
+ outro(`Tracehub is uninstalled. ${dim("Other repositories keep their .git/tracehub;\n delete it by hand if you like.")}`, io);
124
+ }
125
+ catch (err) {
126
+ if (!(err instanceof Stopped))
127
+ throw err;
128
+ cancel(`Uninstall stopped. ${stage}`, io);
129
+ }
130
+ }
131
+ // TraceHub forgets this machine's rules while the sign-in is still there to
132
+ // say who asks. Offline, uninstall goes on and says what TraceHub kept.
133
+ async function unregister(io, options) {
134
+ const stored = readAuth();
135
+ const kept = "TraceHub still lists your consent from this machine;\nto remove it, run tracehub setup, revoke the rules and continue,\nthen uninstall again.";
136
+ if (!stored || isExpired(stored)) {
137
+ if (readRegistryState()?.pending === false)
138
+ log.warn(`You're signed out. ${kept}`, io);
139
+ return;
140
+ }
141
+ try {
142
+ await waiting("Removing your consent from TraceHub", async (signal) => {
143
+ const auth = await freshAuth(stored, process.env, options.fetchFn);
144
+ await revokeRegistration(tracehubUrl(), auth.accessToken, {
145
+ signal,
146
+ ...(options.fetchFn ? { fetchFn: options.fetchFn } : {}),
147
+ });
148
+ }, io);
149
+ done("Removed your consent from TraceHub", io);
150
+ }
151
+ catch (err) {
152
+ if (err instanceof Stopped)
153
+ throw err;
154
+ log.warn(`Couldn't reach TraceHub (${reason(err)}).\n${kept}`, io);
155
+ }
156
+ }
package/dist/cli/io.js ADDED
@@ -0,0 +1,26 @@
1
+ export function fail(msg) {
2
+ process.stderr.write(`tracehub: ${msg}\n`);
3
+ process.exit(1);
4
+ }
5
+ export function warn(msg) {
6
+ process.stderr.write(`tracehub: ${msg}\n`);
7
+ }
8
+ export function out(msg) {
9
+ process.stdout.write(`${msg}\n`);
10
+ }
11
+ // setup and uninstall ask questions; without a terminal they fail with this.
12
+ export function requireTerminal(command, interactive) {
13
+ if (!(interactive ?? (process.stdin.isTTY && process.stdout.isTTY)))
14
+ throw new Error(`${command} asks questions, so it needs an interactive terminal; run "tracehub ${command}" in one.`);
15
+ }
16
+ // An error the form already showed; the CLI exits 1 without repeating it.
17
+ export class Reported extends Error {
18
+ }
19
+ // Wrong arguments: one line, and where to find the right ones.
20
+ export function usageError(command, args) {
21
+ const extra = [
22
+ ...args.positional.slice(1),
23
+ ...Object.keys(args.flags).map((flag) => `--${flag}`),
24
+ ];
25
+ return new Error(`${command} takes no arguments (got ${extra.join(" ")}); see "tracehub ${command} --help".`);
26
+ }