tracehub 0.5.8 → 0.5.10

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.
@@ -0,0 +1,262 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { readPage, webUrl } from "../../client/tracehub.js";
4
+ import { repoRoot, tryGit } from "../../git/git.js";
5
+ import { lineHash } from "../../protocol/trace.js";
6
+ import { isTraceId } from "../../protocol/trailers.js";
7
+ import { prOf } from "../args.js";
8
+ import { out } from "../io.js";
9
+ import { signedInClient } from "../remote.js";
10
+ import { uploadTargetFor } from "../repo.js";
11
+ function pagePath(raw) {
12
+ let url;
13
+ try {
14
+ url = new URL(raw);
15
+ }
16
+ catch {
17
+ throw new Error("invalid TraceHub page URL");
18
+ }
19
+ if (url.origin !== new URL(webUrl()).origin)
20
+ throw new Error(`page URL must be on ${new URL(webUrl()).origin}`);
21
+ const match = /^\/(t|c|pr)\/([A-Za-z0-9._-]{1,100})\/([A-Za-z0-9._-]{1,100})\/([A-Za-z0-9]{1,40})(\.json|\/json)?\/?$/.exec(url.pathname);
22
+ if (match) {
23
+ const [, kind, owner, repo, rawId] = match;
24
+ const id = kind === "c" ? rawId.toLowerCase() : rawId;
25
+ if (![owner, repo].some((s) => s === "." || s === "..") &&
26
+ (kind === "t"
27
+ ? isTraceId(id)
28
+ : kind === "c"
29
+ ? /^[0-9a-f]{7,40}$/.test(id)
30
+ : /^[1-9]\d{0,9}$/.test(id)))
31
+ return `/${kind}/${owner.toLowerCase()}/${repo.toLowerCase()}/${id}`;
32
+ }
33
+ throw new Error("URL must name a TraceHub trace, commit or pull request page");
34
+ }
35
+ const time = (iso) => `${new Date(iso).toISOString().slice(0, 16).replace("T", " ")} UTC`;
36
+ function blameLine(raw, cwd, root) {
37
+ const match = /^(.+):([1-9]\d*)$/.exec(raw);
38
+ if (!match || isAbsolute(match[1]))
39
+ return undefined;
40
+ const file = resolve(cwd, match[1]);
41
+ const path = relative(root, file);
42
+ if (path === ".." || path.startsWith(`..${sep}`))
43
+ return undefined;
44
+ const stat = statSync(file, { throwIfNoEntry: false });
45
+ if (!stat)
46
+ throw new Error(`file "${match[1]}" does not exist`);
47
+ if (!stat.isFile())
48
+ return undefined;
49
+ const line = Number(match[2]);
50
+ const contents = readFileSync(file, "utf8");
51
+ const count = contents
52
+ ? contents.split("\n").length - Number(contents.endsWith("\n"))
53
+ : 0;
54
+ if (!Number.isSafeInteger(line) || line > count)
55
+ throw new Error(`${raw} is past the end of the file`);
56
+ const blame = tryGit([
57
+ "-c",
58
+ "core.quotePath=false",
59
+ "blame",
60
+ "--porcelain",
61
+ "-L",
62
+ `${line},${line}`,
63
+ "--",
64
+ path,
65
+ ], { cwd: root });
66
+ if (!blame) {
67
+ if (!tryGit(["ls-files", "--error-unmatch", "--", path], { cwd: root }) ||
68
+ !tryGit(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: root }))
69
+ throw new Error(`${raw} is not yet committed`);
70
+ throw new Error(`could not blame ${raw}`);
71
+ }
72
+ const commit = blame.split(" ", 1)[0];
73
+ if (/^0+$/.test(commit))
74
+ throw new Error(`${raw} is not yet committed`);
75
+ const filename = /^filename (.+)$/m.exec(blame)?.[1];
76
+ const text = /^\t(.*)$/m.exec(blame)?.[1] ?? "";
77
+ if (!filename)
78
+ throw new Error(`could not read the filename for ${raw}`);
79
+ return {
80
+ commit,
81
+ path: filename.startsWith('"')
82
+ ? JSON.parse(filename)
83
+ : filename,
84
+ line,
85
+ text,
86
+ };
87
+ }
88
+ export function renderTurnPath(path) {
89
+ return path
90
+ .split(".")
91
+ .map((index, depth) => {
92
+ const number = Number(index) + 1;
93
+ return depth === 0
94
+ ? String(number)
95
+ : `${depth % 2 ? "run" : "turn"} ${number}`;
96
+ })
97
+ .join(" › ");
98
+ }
99
+ function messageBody(message, level) {
100
+ const indent = " ".repeat(level);
101
+ const lines = (message.withheld ? "[withheld: looked sensitive]" : message.text)
102
+ .split(/\r?\n/)
103
+ .map((line) => indent + line);
104
+ if (message.translation) {
105
+ lines.push(`${indent}in English (from ${message.translation.from}):`);
106
+ lines.push(...message.translation.text
107
+ .split(/\r?\n/)
108
+ .map((line) => `${indent} ${line}`));
109
+ }
110
+ return lines.join("\n");
111
+ }
112
+ function contextText(context, login) {
113
+ return [
114
+ `Context ${context.ref}${context.title ? ` · ${context.title}` : ""}${login ? ` · attached by @${login}` : ""}`,
115
+ ...(context.url ? [context.url] : []),
116
+ ...context.messages.map((message) => ` ${message.author} · ${time(message.at)}\n${messageBody(message, 2)}`),
117
+ ].join("\n");
118
+ }
119
+ function turnText(turn, index, level = 0) {
120
+ const indent = " ".repeat(level);
121
+ return [
122
+ `${indent}Turn ${index + 1} · ${time(turn.at)}`,
123
+ ...turn.messages.map((message) => `${indent} ${message.role} · ${time(message.at)}\n${messageBody(message, level + 2)}`),
124
+ ...(turn.changes.length
125
+ ? [
126
+ `${indent} changed ${turn.changes.map((change) => `${change.path} +${change.added} -${change.removed}`).join(", ")}`,
127
+ ]
128
+ : []),
129
+ ...turn.runs.map((run, runIndex) => [
130
+ `${indent} Run ${runIndex + 1} · ${run.label}${run.agent ? ` · ${run.agent}` : ""}`,
131
+ ...(run.turns.length ? [turnsText(run.turns, level + 2)] : []),
132
+ ].join("\n")),
133
+ ].join("\n");
134
+ }
135
+ function turnsText(turns, level = 0) {
136
+ return turns.map((turn, index) => turnText(turn, index, level)).join("\n\n");
137
+ }
138
+ function sessionHeader(session) {
139
+ return `Session ${session.agent}${session.title ? ` · ${session.title}` : ""}${session.model ? ` · ${session.model}` : ""}${session.uploader.login ? ` · @${session.uploader.login}` : ""}`;
140
+ }
141
+ function documentBlocks(doc) {
142
+ return [
143
+ ...doc.context.map((context) => contextText(context)),
144
+ ...doc.sessions.map((session) => [
145
+ sessionHeader(session),
146
+ ...(session.turns.length ? [turnsText(session.turns)] : []),
147
+ ].join("\n")),
148
+ ];
149
+ }
150
+ export function renderShow(doc, path) {
151
+ const repo = `${doc.owner}/${doc.repo}`;
152
+ const title = "number" in doc
153
+ ? `${repo}#${doc.number}${doc.title ? ` ${doc.title}` : ""}`
154
+ : "sha" in doc
155
+ ? `${repo}@${doc.sha.slice(0, 7)}`
156
+ : `${repo} trace ${doc.traceId}`;
157
+ const blocks = [`${title}\n${webUrl()}${path}`];
158
+ if ("traceId" in doc)
159
+ blocks.push(...documentBlocks(doc));
160
+ else {
161
+ const commits = "number" in doc
162
+ ? doc.commits
163
+ : [
164
+ {
165
+ sha: doc.sha,
166
+ traceIds: doc.traces.map((trace) => trace.traceId),
167
+ },
168
+ ];
169
+ if (!commits.some((commit) => doc.traces.some((trace) => commit.traceIds.includes(trace.traceId))))
170
+ blocks.push("no traces");
171
+ if ("number" in doc)
172
+ for (const attached of doc.context)
173
+ blocks.push(...attached.context.map((context) => contextText(context, attached.uploader.login)));
174
+ for (const commit of commits) {
175
+ const traces = commit.traceIds.flatMap((id) => doc.traces.filter((trace) => trace.traceId === id));
176
+ if (!traces.length) {
177
+ if ("number" in doc)
178
+ blocks.push(`Commit ${commit.sha.slice(0, 7)} · no trace`);
179
+ continue;
180
+ }
181
+ for (const trace of traces) {
182
+ blocks.push(`Commit ${commit.sha.slice(0, 7)} · trace ${trace.traceId}\n${webUrl()}/t/${doc.owner}/${doc.repo}/${trace.traceId}`, ...documentBlocks(trace));
183
+ }
184
+ }
185
+ }
186
+ return blocks.join("\n\n");
187
+ }
188
+ export async function cmdShow(args, cwd) {
189
+ const hasPr = args.flags["pr"] !== undefined;
190
+ const positional = args.positional.slice(1);
191
+ if (positional.length !== (hasPr ? 0 : 1) ||
192
+ (hasPr && typeof args.flags["pr"] !== "string") ||
193
+ args.rest?.length ||
194
+ Object.keys(args.flags).some((flag) => flag !== "pr" && flag !== "json") ||
195
+ (args.flags["json"] !== undefined && args.flags["json"] !== true))
196
+ throw new Error('name exactly one commit, <path>:<line>, --pr <n> or page URL; see "tracehub show --help"');
197
+ const pr = prOf(args);
198
+ const revision = positional[0];
199
+ let path;
200
+ let line;
201
+ if (revision && /^https?:\/\//.test(revision))
202
+ path = pagePath(revision);
203
+ else {
204
+ const root = repoRoot(cwd);
205
+ if (!root)
206
+ throw new Error("not a git repository; run it in a clone of the repository");
207
+ const target = uploadTargetFor(cwd);
208
+ if (!target)
209
+ throw new Error("this clone's origin is not a repository TraceHub serves (assistant-ui)");
210
+ line = revision ? blameLine(revision, cwd, root) : undefined;
211
+ const sha = line?.commit ??
212
+ (pr === undefined
213
+ ? tryGit([
214
+ "rev-parse",
215
+ "--verify",
216
+ "--quiet",
217
+ "--end-of-options",
218
+ `${revision}^{commit}`,
219
+ ], { cwd })
220
+ : undefined);
221
+ if (pr === undefined && !sha)
222
+ throw new Error(`unknown commit revision "${revision}"`);
223
+ path = `/${pr === undefined ? "c" : "pr"}/${target.owner}/${target.repo}/${pr ?? sha}`;
224
+ }
225
+ const { auth } = await signedInClient();
226
+ const doc = await readPage(path, auth.accessToken);
227
+ if (line) {
228
+ if (!("sha" in doc))
229
+ throw new Error("expected a commit page");
230
+ const hash = lineHash(line.text);
231
+ const matches = doc.traces.flatMap((trace) => trace.sessions.flatMap((session) => {
232
+ const turn = hash ? session.sourcemap[line.path]?.[hash] : undefined;
233
+ return turn === undefined
234
+ ? []
235
+ : [{ traceId: trace.traceId, session, turn }];
236
+ }));
237
+ if (args.flags["json"])
238
+ out(JSON.stringify({
239
+ commit: line.commit,
240
+ path: line.path,
241
+ line: line.line,
242
+ matches: matches.map(({ traceId, session, turn }) => ({
243
+ traceId,
244
+ session: session.name,
245
+ turn,
246
+ })),
247
+ page: doc,
248
+ }, null, 2));
249
+ else if (matches.length)
250
+ out([
251
+ `${doc.owner}/${doc.repo}@${line.commit.slice(0, 7)}\n${webUrl()}${path}`,
252
+ ...matches.map(({ traceId, session, turn }) => {
253
+ const index = Number(turn.split(".", 1)[0]);
254
+ return `${revision} was written in ${traceId} · ${sessionHeader(session)} · turn ${renderTurnPath(turn)}\n${turnText(session.turns[index], index)}`;
255
+ }),
256
+ ].join("\n\n"));
257
+ else
258
+ out(`${revision} is not attributed to a turn; the commit's conversations follow\n\n${renderShow(doc, path)}`);
259
+ return;
260
+ }
261
+ out(args.flags["json"] ? JSON.stringify(doc, null, 2) : renderShow(doc, path));
262
+ }
@@ -12,15 +12,10 @@ import { configDir, consentFile, GIT_STATE_DIR } from "../../local/paths.js";
12
12
  import { denyFile, readDenyList } from "../../redact/deny.js";
13
13
  import { Reported, requireTerminal, usageError } from "../io.js";
14
14
  import { bold, dim, done, plural, rows, skipped, Stopped, tilde, title, waiting, } from "../ui.js";
15
- import { commandUsage } from "../usage.js";
16
15
  // Removes what setup made: the global hooks, the permission rules and the
17
16
  // sign-in. The deny list and this repository's trace state go only when the
18
17
  // user says so; other repositories keep theirs.
19
18
  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
19
  if (args.positional.length > 1 || Object.keys(args.flags).length)
25
20
  throw usageError("uninstall", args);
26
21
  requireTerminal("uninstall", options.interactive);
@@ -1,11 +1,11 @@
1
- import { isExpired, readAuth } from "../client/auth.js";
2
- import { TracehubClient, tracehubUrl, } from "../client/tracehub.js";
1
+ import { freshAuth, isExpired, readAuth } from "../client/auth.js";
2
+ import { TracehubClient, tracehubUrl, webUrl, } from "../client/tracehub.js";
3
3
  import { ENV_TEST, ENV_TEST_PUSH_BUDGET, home } from "../local/paths.js";
4
4
  import { formatSessionRef } from "../protocol/sessionRef.js";
5
5
  import { readDenyList } from "../redact/deny.js";
6
6
  import { formatFindings } from "../redact/redact.js";
7
7
  import { warn } from "./io.js";
8
- export const UPLOAD_BUDGET_MS = 15_000;
8
+ const UPLOAD_BUDGET_MS = 15_000;
9
9
  // What a push leaves unfinished goes on in the background, for this long.
10
10
  export const BACKGROUND_BUDGET_MS = 10 * 60_000;
11
11
  // How long a push waits for its upload. Tests shorten it.
@@ -52,7 +52,7 @@ function describeUpload(result) {
52
52
  }
53
53
  // Where tracehub shows the sessions of a commit.
54
54
  function traceUrls(target, markers) {
55
- const repo = `${tracehubUrl()}/t/${target.owner}/${target.repo}`;
55
+ const repo = `${webUrl()}/t/${target.owner}/${target.repo}`;
56
56
  return [...new Set(markers.map((m) => `${repo}/${m.traceId}`))];
57
57
  }
58
58
  // A failure that only means the time ran out: the rest can go on later.
@@ -79,3 +79,10 @@ export function reportUpload(result, target, emit, background) {
79
79
  for (const url of traceUrls(target, result.uploaded))
80
80
  emit(url);
81
81
  }
82
+ export async function signedInClient() {
83
+ const stored = usableAuth();
84
+ if (!stored)
85
+ throw new Error('not signed in; run "tracehub setup"');
86
+ const auth = await freshAuth(stored);
87
+ return { client: clientFor(auth), auth };
88
+ }
package/dist/cli/repo.js CHANGED
@@ -8,14 +8,11 @@ import { firstLineOf } from "../local/files.js";
8
8
  import { sessionLines } from "../local/lines.js";
9
9
  import { opencodePendingCommitCall } from "../local/opencode.js";
10
10
  import { CLAUDE_SUBAGENT_PREFIX, claudeCwd, discoverActiveSessions, findSessionFile, ranInside, ROOT_COMMIT_WINDOW_MS, subagentWork, } from "../local/discover.js";
11
- import { consentFile, ENV_CLAUDE_SESSION, ENV_CODEX_THREAD, ENV_DISABLE, ENV_SESSION_ID, GIT_STATE_DIR, } from "../local/paths.js";
11
+ import { consentFile, ENV_CLAUDE_SESSION, ENV_CODEX_THREAD, ENV_SESSION_ID, GIT_STATE_DIR, } from "../local/paths.js";
12
12
  import { listClaudeSubagents } from "../local/subagents.js";
13
13
  import { formatSessionRef, parseSessionRef, } from "../protocol/sessionRef.js";
14
14
  import { codexSessionMeta } from "../transcript/parseCodex.js";
15
15
  import { fail } from "./io.js";
16
- export function hooksDisabled() {
17
- return process.env[ENV_DISABLE] === "0";
18
- }
19
16
  // Where the CLI keeps its per-repository state: .git/tracehub.
20
17
  export function stateDir(cwd) {
21
18
  const git = gitDir(cwd);
@@ -61,7 +58,7 @@ function sessionCwd(ref, file) {
61
58
  // parent's id), the parent is attached if it ran in the repository, with
62
59
  // the subagent as a run, else the subagent alone. A named session that did
63
60
  // neither attaches only when it ran in the repository.
64
- export function environmentSessions(root) {
61
+ function environmentSessions(root) {
65
62
  const named = [
66
63
  parseSessionRef(`claude:${process.env[ENV_CLAUDE_SESSION] ?? ""}`),
67
64
  parseSessionRef(`codex:${process.env[ENV_CODEX_THREAD] ?? ""}`),
@@ -93,10 +90,10 @@ function unique(sessions) {
93
90
  export function resolveSessions(cwd, root) {
94
91
  const forced = forcedSessions();
95
92
  if (forced.length)
96
- return { sessions: forced, source: `env ${ENV_SESSION_ID}` };
93
+ return { sessions: forced };
97
94
  const named = environmentSessions(root);
98
95
  if (named.length)
99
- return { sessions: unique(named), source: "agent environment" };
96
+ return { sessions: unique(named) };
100
97
  const since = headTimestampMs(cwd) ?? Date.now() - ROOT_COMMIT_WINDOW_MS;
101
98
  const found = discoverActiveSessions(root, since);
102
99
  const committing = found.filter((ref) => ref.committing ??
@@ -110,7 +107,6 @@ export function resolveSessions(cwd, root) {
110
107
  })));
111
108
  return {
112
109
  sessions,
113
- source: committing.length ? "active commit" : "discovery",
114
110
  };
115
111
  }
116
112
  export function consentFor(cwd) {
@@ -143,3 +139,7 @@ export function pushTargetFor(cwd, push) {
143
139
  ? { target }
144
140
  : { target, fork: destination };
145
141
  }
142
+ export function requireConsent(cwd, target) {
143
+ if (consentFor(cwd) !== true)
144
+ throw new Error(`no permission rule allows uploads for ${target.owner}/${target.repo}; run "tracehub setup"`);
145
+ }
package/dist/cli/ui.js CHANGED
@@ -13,7 +13,7 @@ const paint = (style) => (text) => text
13
13
  export const bold = paint("bold");
14
14
  export const dim = paint("dim");
15
15
  export const accent = paint("cyan");
16
- export const good = paint("green");
16
+ const good = paint("green");
17
17
  export const bad = paint("red");
18
18
  const S_DONE = unicodeOr("✓", "√");
19
19
  const S_STEP = unicodeOr("●", "*");
package/dist/cli/usage.js CHANGED
@@ -68,6 +68,19 @@ export const COMMANDS = [
68
68
  "tracehub backfill 1a2b3c4d",
69
69
  ],
70
70
  },
71
+ {
72
+ name: "show",
73
+ usage: "show (<commit> | <path>:<line> | --pr <n> | <url>) [--json]",
74
+ summary: "print the conversations behind a commit, a pull request or a trace",
75
+ about: "A commit reads the conversations behind that revision in this clone; --pr <n> reads those behind a pull request of this clone's repository. <path>:<line> finds the prompt that wrote a committed line in this clone, or shows the commit's conversations when the line is unattributed. A TraceHub page URL reads a trace, commit or pull request, even outside a clone. Needs a sign-in and shows only what the web page would show you. --json prints the page's document as served, with the commit, historical path, line and matches for a line lookup.",
76
+ examples: [
77
+ "tracehub show HEAD",
78
+ "tracehub show src/cli/commands/show.ts:42",
79
+ "tracehub show --pr 52",
80
+ "tracehub show https://tracehub.aui.dev/t/assistant-ui/tracehub/0123456789abcdef",
81
+ "tracehub show HEAD --json",
82
+ ],
83
+ },
71
84
  ];
72
85
  export const ENV = [
73
86
  {
@@ -100,6 +113,11 @@ export const ENV = [
100
113
  value: "<url>",
101
114
  description: "use another Tracehub server",
102
115
  },
116
+ {
117
+ name: "TRACEHUB_GITHUB_CLIENT_ID",
118
+ value: "<id>",
119
+ description: "use another GitHub App client ID for sign-in",
120
+ },
103
121
  ];
104
122
  const WIDTH = 80;
105
123
  /** `text` wrapped to WIDTH, every line after the first indented by `indent` spaces. */
package/dist/cli.js CHANGED
@@ -5,19 +5,28 @@ import { cmdHook } from "./cli/commands/hook.js";
5
5
  import { cmdContext } from "./cli/commands/context.js";
6
6
  import { cmdProviders } from "./cli/commands/providers.js";
7
7
  import { cmdSetup } from "./cli/commands/setup.js";
8
+ import { cmdShow } from "./cli/commands/show.js";
8
9
  import { cmdUninstall } from "./cli/commands/uninstall.js";
9
10
  import { fail, Reported } from "./cli/io.js";
10
- import { usage } from "./cli/usage.js";
11
+ import { commandUsage, usage } from "./cli/usage.js";
11
12
  const COMMAND_HANDLERS = {
12
13
  setup: cmdSetup,
13
14
  uninstall: cmdUninstall,
14
15
  providers: cmdProviders,
15
16
  context: cmdContext,
16
17
  backfill: cmdBackfill,
18
+ show: cmdShow,
17
19
  };
18
20
  async function main() {
19
21
  const args = parseArgs(process.argv.slice(2));
20
22
  const name = args.positional[0];
23
+ if (args.flags["help"] ||
24
+ ((name === "context" || name === "providers") && !args.positional[1])) {
25
+ process.stdout.write(name && Object.hasOwn(COMMAND_HANDLERS, name)
26
+ ? `${commandUsage(name)}\n`
27
+ : usage(true));
28
+ return;
29
+ }
21
30
  // What the Git hooks run; internal, so not in the usage.
22
31
  if (name === "hook") {
23
32
  // Hooks that ran npx from the home directory name the repository.
@@ -33,7 +42,7 @@ async function main() {
33
42
  return;
34
43
  }
35
44
  process.stdout.write(usage(true));
36
- if (name && !args.flags["help"] && !args.flags["h"] && name !== "help") {
45
+ if (name && name !== "help") {
37
46
  process.stderr.write(`\ntracehub: unknown command "${name}"\n`);
38
47
  process.exit(1);
39
48
  }
@@ -114,29 +114,14 @@ export async function refreshTokens(client, refreshToken) {
114
114
  }
115
115
  // The login of the user the token stands for.
116
116
  export async function loginOf(client, token) {
117
- const res = await client.fetchFn(`${GITHUB_API}/user`, {
118
- headers: {
119
- accept: "application/vnd.github+json",
120
- authorization: `Bearer ${token}`,
121
- "user-agent": "tracehub-cli",
122
- },
123
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
124
- });
117
+ const res = await githubResponse("/user", token, REQUEST_TIMEOUT_MS, client.fetchFn);
125
118
  const { login } = await answerOf(res);
126
119
  if (typeof login !== "string")
127
120
  throw new Error("GitHub named no user");
128
121
  return login;
129
122
  }
130
123
  async function githubGet(path, token) {
131
- const res = await fetch(`${GITHUB_API}${path}`, {
132
- headers: {
133
- accept: "application/vnd.github+json",
134
- authorization: `Bearer ${token}`,
135
- "user-agent": "tracehub-cli",
136
- "x-github-api-version": "2022-11-28",
137
- },
138
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
139
- });
124
+ const res = await githubResponse(path, token);
140
125
  if (!res.ok)
141
126
  throw new Error(`GitHub answered ${res.status} for ${path}`);
142
127
  return res.json();
@@ -163,3 +148,15 @@ export async function pullCommits(repo, number, token) {
163
148
  commits,
164
149
  };
165
150
  }
151
+ export function githubResponse(path, token, timeoutMs = REQUEST_TIMEOUT_MS, fetchFn = fetch, redirect) {
152
+ return fetchFn(`${GITHUB_API}${path}`, {
153
+ headers: {
154
+ accept: "application/vnd.github+json",
155
+ authorization: `Bearer ${token}`,
156
+ "user-agent": "tracehub-cli",
157
+ "x-github-api-version": "2022-11-28",
158
+ },
159
+ ...(redirect ? { redirect } : {}),
160
+ signal: AbortSignal.timeout(timeoutMs),
161
+ });
162
+ }
@@ -1,4 +1,4 @@
1
- import { DASHBOARD_URL } from "../git/trailers.js";
1
+ import { WEB_URL } from "../protocol/trailers.js";
2
2
  import { verifyFork, verifyUploadOwnership, } from "./uploadPolicy.js";
3
3
  export const DEFAULT_TRACEHUB_URL = "https://assisted-by.aui.dev";
4
4
  export const ENV_TRACEHUB = "TRACEHUB_URL";
@@ -6,6 +6,9 @@ const REQUEST_TIMEOUT_MS = 15_000;
6
6
  export function tracehubUrl(env = process.env) {
7
7
  return (env[ENV_TRACEHUB] || DEFAULT_TRACEHUB_URL).replace(/\/+$/, "");
8
8
  }
9
+ export function webUrl(env = process.env) {
10
+ return (env[ENV_TRACEHUB] || WEB_URL).replace(/\/+$/, "");
11
+ }
9
12
  export class TracehubError extends Error {
10
13
  status;
11
14
  body;
@@ -116,10 +119,12 @@ export class TracehubClient {
116
119
  return (await res.json());
117
120
  }
118
121
  }
119
- // Whether TraceHub has any session of the trace, asked of the dashboard's
120
- // `.json` page with the user's GitHub token.
121
- export async function traceUploaded(target, traceId, token) {
122
- const res = await fetch(`${DASHBOARD_URL}/t/${target.owner}/${target.repo}/${traceId}.json`, {
122
+ export async function readPage(path, token) {
123
+ const origin = new URL(webUrl()).origin;
124
+ const url = new URL(`${webUrl()}${path}.json`);
125
+ if (url.origin !== origin)
126
+ throw new Error(`page URL must be on ${origin}`);
127
+ const res = await fetch(url.href, {
123
128
  headers: {
124
129
  authorization: `Bearer ${token}`,
125
130
  "user-agent": "tracehub-cli",
@@ -127,9 +132,20 @@ export async function traceUploaded(target, traceId, token) {
127
132
  redirect: "manual",
128
133
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
129
134
  });
130
- if (res.status === 404)
131
- return false;
132
- if (res.ok)
135
+ if (!res.ok)
136
+ throw await errorOf(res);
137
+ return (await res.json());
138
+ }
139
+ // Whether TraceHub has any session of the trace, asked of the site's
140
+ // `.json` page with the user's GitHub token.
141
+ export async function traceUploaded(target, traceId, token) {
142
+ try {
143
+ await readPage(`/t/${target.owner}/${target.repo}/${traceId}`, token);
133
144
  return true;
134
- throw new Error(`TraceHub answered ${res.status}`);
145
+ }
146
+ catch (err) {
147
+ if (err instanceof TracehubError && err.status === 404)
148
+ return false;
149
+ throw err;
150
+ }
135
151
  }
@@ -1,3 +1,4 @@
1
+ import { githubResponse } from "./github.js";
1
2
  export const UPLOAD_OWNER = "assistant-ui";
2
3
  export const UPLOAD_POLICY_ERROR = "trace uploads require one unambiguous GitHub repository owned by assistant-ui; nothing was uploaded";
3
4
  // Only the real GitHub host and conventional Git transports are accepted.
@@ -36,16 +37,7 @@ async function githubRepository(repo, token, timeoutMs, fetchFn, check) {
36
37
  throw new Error("upload budget exhausted; nothing was uploaded");
37
38
  let response;
38
39
  try {
39
- response = await fetchFn(`https://api.github.com/repos/${repo.owner}/${repo.repo}`, {
40
- headers: {
41
- accept: "application/vnd.github+json",
42
- authorization: `Bearer ${token}`,
43
- "user-agent": "tracehub-cli",
44
- "x-github-api-version": "2022-11-28",
45
- },
46
- redirect: "error",
47
- signal: AbortSignal.timeout(timeoutMs),
48
- });
40
+ response = await githubResponse(`/repos/${repo.owner}/${repo.repo}`, token, timeoutMs, fetchFn, "error");
49
41
  }
50
42
  catch {
51
43
  throw new Error(`GitHub could not verify ${check}; nothing was uploaded`);
package/dist/git/git.js CHANGED
@@ -1,12 +1,26 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { traceIds } from "./trailers.js";
2
+ import { traceIds } from "../protocol/trailers.js";
3
3
  const MAX_BUFFER = 256 * 1024 * 1024;
4
+ // A hook inherits the variables that pin git to the repository it runs for
5
+ // (GIT_DIR in a linked worktree); with them, any other directory reads as
6
+ // that repository's checkout.
7
+ let localEnvVars;
4
8
  export function git(args, opts = {}) {
9
+ localEnvVars ??= execFileSync("git", ["rev-parse", "--local-env-vars"], {
10
+ encoding: "utf8",
11
+ stdio: ["ignore", "pipe", "pipe"],
12
+ })
13
+ .trim()
14
+ .split("\n");
15
+ const env = { ...(opts.env ?? process.env) };
16
+ for (const name of localEnvVars)
17
+ delete env[name];
5
18
  const out = execFileSync("git", args, {
6
19
  encoding: "utf8",
7
20
  stdio: ["ignore", "pipe", "pipe"],
8
21
  maxBuffer: MAX_BUFFER,
9
22
  ...opts,
23
+ env,
10
24
  });
11
25
  return out.toString().trimEnd();
12
26
  }
@@ -1,36 +1,23 @@
1
+ import { ENV_DISABLE } from "../local/paths.js";
2
+ import { traceUrl, WEB_URL } from "../protocol/trailers.js";
1
3
  const TRAILER_KEY = "Assisted-by";
2
- // The dashboard, where a trailer links to its trace.
3
- export const DASHBOARD_URL = "https://tracehub.aui.dev";
4
- const ID = /^[0-9a-f]{16}$/;
5
- // The trailer's value is the trace's URL, or the bare trace id.
6
- const LINE = /^[ \t]*Assisted-by:[ \t]*(?:\S*\/)?([0-9a-f]{16})[ \t]*$/gm;
7
- export function isTraceId(s) {
8
- return ID.test(s);
9
- }
10
4
  export function newTraceId() {
11
5
  return Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) => b.toString(16).padStart(2, "0")).join("");
12
6
  }
13
- // The trace's page on the dashboard, so GitHub links the trailer.
14
- export function traceUrl(target, id) {
15
- return `${DASHBOARD_URL}/t/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${id}`;
16
- }
17
- // Every "Assisted-by: <id or URL>" line anywhere in the message, in order: a squash
18
- // (git's, indented, or GitHub's) folds the trailers of the squashed commits
19
- // into the body, where git's own trailer parser no longer sees them.
20
- export function traceIds(message) {
21
- return [...new Set([...message.matchAll(LINE)].map((m) => m[1]))];
22
- }
23
- export function interpretTrailersArgs(target, id, messageFile) {
7
+ export function interpretTrailersArgs(target, id, messageFile, base = WEB_URL) {
24
8
  return [
25
9
  "interpret-trailers",
26
10
  "--in-place",
27
11
  "--trailer",
28
- `${TRAILER_KEY}: ${traceUrl(target, id)}`,
12
+ `${TRAILER_KEY}: ${traceUrl(target, id, base)}`,
29
13
  messageFile,
30
14
  ];
31
15
  }
32
16
  export function shouldSkipCommit(source, env) {
33
- if (env["TRACEHUB"] === "0")
17
+ if (hooksDisabled(env))
34
18
  return true;
35
19
  return source === "merge" || source === "squash";
36
20
  }
21
+ export function hooksDisabled(env = process.env) {
22
+ return env[ENV_DISABLE] === "0";
23
+ }