tracehub 0.0.0-stage → 0.5.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 (48) hide show
  1. package/README.md +424 -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 +209 -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 +65 -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 +166 -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 +46 -4
@@ -0,0 +1,94 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ // "git@github.com:Owner/Repo.git", "https://github.com/owner/repo/" and
4
+ // "ssh://git@github.com/owner/repo" all normalize to "github.com/owner/repo".
5
+ export function normalizeRemote(url) {
6
+ let s = url.trim();
7
+ const scp = /^[^@/]+@([^:]+):(.+)$/.exec(s);
8
+ if (scp)
9
+ s = `${scp[1]}/${scp[2]}`;
10
+ else
11
+ s = s.replace(/^[a-z+]+:\/\//i, "").replace(/^[^@]+@/, "");
12
+ s = s.replace(/:\d+\//, "/");
13
+ s = s.replace(/\/+$/, "").replace(/\.git$/, "");
14
+ return s.toLowerCase();
15
+ }
16
+ export function readConsent(file) {
17
+ try {
18
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
19
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
20
+ return parsed;
21
+ }
22
+ }
23
+ catch {
24
+ /* missing or malformed: treated as no consent recorded */
25
+ }
26
+ return {};
27
+ }
28
+ export function writeConsent(file, store) {
29
+ mkdirSync(dirname(file), { recursive: true });
30
+ writeFileSync(file, `${JSON.stringify(store, null, 2)}\n`);
31
+ }
32
+ // A repository's rule wins over its organization's. Any other key, such as
33
+ // the "github.com/*" of older versions, is ignored.
34
+ export function getConsent(store, remote) {
35
+ const key = consentScope(remote);
36
+ if (!key || key.endsWith("/*"))
37
+ return undefined;
38
+ const owner = key.split("/")[1];
39
+ for (const scope of [key, `github.com/${owner}/*`]) {
40
+ const value = store[scope]?.upload;
41
+ if (typeof value === "boolean")
42
+ return value;
43
+ }
44
+ return undefined;
45
+ }
46
+ // The consent key of a GitHub remote URL, "github.com/owner/repo" or
47
+ // "github.com/owner/*"; undefined for anything else.
48
+ export function consentScope(remote) {
49
+ if (!/^(?:github\.com\/|git@github\.com:|https:\/\/(?:[^/@]+@)?github\.com(?::443)?\/|ssh:\/\/git@github\.com\/)/i.test(remote.trim()))
50
+ return undefined;
51
+ const key = normalizeRemote(remote);
52
+ return /^github\.com\/[a-z0-9-]+\/(?:\*|[a-z0-9_.-]+)$/.test(key) &&
53
+ ![".", ".."].includes(key.split("/")[2] ?? "")
54
+ ? key
55
+ : undefined;
56
+ }
57
+ // "owner" or "owner/repo", as typed in setup, as a consent key.
58
+ export function scopeKey(scope) {
59
+ const value = scope.trim();
60
+ if (!value || /[:*]/.test(value) || value.startsWith("github.com/"))
61
+ return undefined;
62
+ return consentScope(`github.com/${value.includes("/") ? value : `${value}/*`}`);
63
+ }
64
+ export function consentRules(store) {
65
+ return Object.entries(store)
66
+ .filter(([key, entry]) => consentScope(key) === key && typeof entry?.upload === "boolean")
67
+ .map(([key, entry]) => {
68
+ const organization = key.endsWith("/*");
69
+ return {
70
+ key,
71
+ scope: key.slice("github.com/".length, organization ? -2 : undefined),
72
+ kind: organization ? "organization" : "repository",
73
+ upload: entry.upload,
74
+ };
75
+ })
76
+ .sort((a, b) => a.scope.localeCompare(b.scope));
77
+ }
78
+ // The keys getConsent ignores: "github.com/*" and anything malformed.
79
+ export function ignoredRules(store) {
80
+ const kept = new Set(consentRules(store).map((rule) => rule.key));
81
+ return Object.keys(store).filter((key) => !kept.has(key));
82
+ }
83
+ export function setConsent(store, remote, upload, now = new Date()) {
84
+ const scope = consentScope(remote);
85
+ if (!scope)
86
+ throw new Error("Consent requires a GitHub organization or repository.");
87
+ return {
88
+ ...store,
89
+ [scope]: { upload, ts: now.toISOString() },
90
+ };
91
+ }
92
+ export function removeConsent(store, keys) {
93
+ return Object.fromEntries(Object.entries(store).filter(([key]) => !keys.includes(key)));
94
+ }
@@ -0,0 +1,4 @@
1
+ // An error's message without the detail that follows its first line.
2
+ export function firstLine(err) {
3
+ return err.message.split("\n")[0];
4
+ }
@@ -0,0 +1,129 @@
1
+ const GITHUB = "https://github.com";
2
+ const GITHUB_API = "https://api.github.com";
3
+ // The client of the GitHub App tracehub, which is no secret.
4
+ const CLIENT_ID_DEFAULT = "Iv23limQrRDTbi0xJG3f";
5
+ const ENV_CLIENT_ID = "TRACEHUB_GITHUB_CLIENT_ID";
6
+ const REQUEST_TIMEOUT_MS = 15_000;
7
+ // How long GitHub lets a user's access token live.
8
+ const ACCESS_TOKEN_LIFE_S = 8 * 3600;
9
+ const SLOW_DOWN_S = 5;
10
+ export function clientId(env = process.env) {
11
+ return env[ENV_CLIENT_ID] || CLIENT_ID_DEFAULT;
12
+ }
13
+ // GitHub refused: the code is its "error".
14
+ export class GitHubRefusal extends Error {
15
+ code;
16
+ constructor(code, description) {
17
+ super(`${code} ${description}`.trim());
18
+ this.code = code;
19
+ }
20
+ }
21
+ export function githubClient(env = process.env, fetchFn = fetch) {
22
+ return { clientId: clientId(env), fetchFn };
23
+ }
24
+ async function answerOf(res) {
25
+ let answer = {};
26
+ try {
27
+ answer = (await res.json());
28
+ }
29
+ catch {
30
+ // An answer that is not JSON has the status as its reason.
31
+ }
32
+ // GitHub refuses with a 200.
33
+ if (typeof answer["error"] === "string") {
34
+ const description = answer["error_description"];
35
+ throw new GitHubRefusal(answer["error"], typeof description === "string" ? description : "");
36
+ }
37
+ if (!res.ok)
38
+ throw new Error(`GitHub answered ${res.status}`);
39
+ return answer;
40
+ }
41
+ async function post(client, path, form) {
42
+ const body = new URLSearchParams({ client_id: client.clientId, ...form });
43
+ const res = await client.fetchFn(`${GITHUB}${path}`, {
44
+ method: "POST",
45
+ headers: {
46
+ accept: "application/json",
47
+ "content-type": "application/x-www-form-urlencoded",
48
+ "user-agent": "tracehub-cli",
49
+ },
50
+ body: body.toString(),
51
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
52
+ });
53
+ return answerOf(res);
54
+ }
55
+ function tokensOf(answer) {
56
+ const { access_token, refresh_token, expires_in } = answer;
57
+ if (typeof access_token !== "string") {
58
+ throw new Error("GitHub sent no access token");
59
+ }
60
+ const life = typeof expires_in === "number" ? expires_in : ACCESS_TOKEN_LIFE_S;
61
+ return {
62
+ accessToken: access_token,
63
+ refreshToken: typeof refresh_token === "string" ? refresh_token : null,
64
+ expiresAt: Date.now() + life * 1000,
65
+ };
66
+ }
67
+ // Starts the device flow: GitHub hands out the code the user confirms.
68
+ export async function startDeviceLogin(client) {
69
+ const answer = await post(client, "/login/device/code", {});
70
+ const { device_code, user_code, verification_uri, interval, expires_in } = answer;
71
+ if (typeof device_code !== "string" ||
72
+ typeof user_code !== "string" ||
73
+ typeof verification_uri !== "string" ||
74
+ typeof expires_in !== "number") {
75
+ throw new Error("GitHub sent no device code");
76
+ }
77
+ return {
78
+ deviceCode: device_code,
79
+ userCode: user_code,
80
+ verificationUri: verification_uri,
81
+ intervalS: typeof interval === "number" ? interval : SLOW_DOWN_S,
82
+ expiresAt: Date.now() + expires_in * 1000,
83
+ };
84
+ }
85
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
86
+ // Asks GitHub for the tokens until the user has confirmed the code, or the
87
+ // code has expired.
88
+ export async function awaitTokens(client, device, wait = sleep) {
89
+ const form = {
90
+ device_code: device.deviceCode,
91
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
92
+ };
93
+ let intervalS = device.intervalS;
94
+ while (Date.now() < device.expiresAt) {
95
+ await wait(intervalS * 1000);
96
+ try {
97
+ return tokensOf(await post(client, "/login/oauth/access_token", form));
98
+ }
99
+ catch (err) {
100
+ if (!(err instanceof GitHubRefusal))
101
+ throw err;
102
+ if (err.code === "slow_down")
103
+ intervalS += SLOW_DOWN_S;
104
+ else if (err.code !== "authorization_pending")
105
+ throw err;
106
+ }
107
+ }
108
+ throw new GitHubRefusal("expired_token", "");
109
+ }
110
+ // A sign-in of the device flow is refreshed without a secret.
111
+ export async function refreshTokens(client, refreshToken) {
112
+ const form = { grant_type: "refresh_token", refresh_token: refreshToken };
113
+ return tokensOf(await post(client, "/login/oauth/access_token", form));
114
+ }
115
+ // The login of the user the token stands for.
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
+ });
125
+ const { login } = await answerOf(res);
126
+ if (typeof login !== "string")
127
+ throw new Error("GitHub named no user");
128
+ return login;
129
+ }
@@ -0,0 +1,112 @@
1
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { readJsonObject } from "../local/files.js";
4
+ import { configDir } from "../local/paths.js";
5
+ import { consentRules } from "./consent.js";
6
+ import { errorOf, TracehubError } from "./tracehub.js";
7
+ // TraceHub's copy of the permission rules: its roster says who allowed a
8
+ // repository or an organization. consent.json stays the truth; the
9
+ // registry is sent all of it, so sending again is harmless.
10
+ //
11
+ // consent-sync.json names this machine for TraceHub (each machine sends its
12
+ // own rules, so one without rules takes nothing away from another) and
13
+ // says whether TraceHub has the rules as they are now: `pending` after a
14
+ // change TraceHub has not heard of (offline, signed out), not after it has.
15
+ // Without the file, rules of a version from before the registry have never
16
+ // been sent.
17
+ const TIMEOUT_MS = 10_000;
18
+ export function registryFile() {
19
+ return join(configDir(), "consent-sync.json");
20
+ }
21
+ const MACHINE = /^[a-z0-9]{8,64}$/;
22
+ export function readRegistryState() {
23
+ if (!existsSync(registryFile()))
24
+ return undefined;
25
+ const { machine, pending, at, error } = readJsonObject(registryFile());
26
+ if (typeof machine !== "string" || !MACHINE.test(machine))
27
+ return undefined;
28
+ return {
29
+ machine,
30
+ pending: pending !== false,
31
+ ...(typeof at === "string" ? { at } : {}),
32
+ ...(typeof error === "string" ? { error } : {}),
33
+ };
34
+ }
35
+ function writeState(state) {
36
+ const machine = readRegistryState()?.machine ??
37
+ Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) => b.toString(16).padStart(2, "0")).join("");
38
+ const next = { machine, ...state };
39
+ mkdirSync(dirname(registryFile()), { recursive: true });
40
+ writeFileSync(registryFile(), `${JSON.stringify(next, null, 2)}\n`);
41
+ return next;
42
+ }
43
+ export function markPending(error) {
44
+ writeState({
45
+ pending: true,
46
+ at: new Date().toISOString(),
47
+ ...(error ? { error } : {}),
48
+ });
49
+ }
50
+ // This machine's name for TraceHub, made on first use.
51
+ function machineId() {
52
+ return readRegistryState()?.machine ?? writeState({ pending: true }).machine;
53
+ }
54
+ export function clearRegistryState() {
55
+ rmSync(registryFile(), { force: true });
56
+ }
57
+ // Whether TraceHub may not have the rules as they are on this machine.
58
+ export function registrationPending(store) {
59
+ const state = readRegistryState();
60
+ return state ? state.pending : consentRules(store).length > 0;
61
+ }
62
+ // The rules as TraceHub takes them: `owner` or `owner/repo`.
63
+ export function registryRules(store) {
64
+ return consentRules(store).map((rule) => ({
65
+ scope: rule.scope,
66
+ upload: rule.upload,
67
+ at: store[rule.key]?.ts ?? new Date().toISOString(),
68
+ }));
69
+ }
70
+ async function send(baseUrl, token, rules, options) {
71
+ const fetchFn = options.fetchFn ?? fetch;
72
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS);
73
+ const res = await fetchFn(`${baseUrl}/consent`, {
74
+ method: "PUT",
75
+ headers: {
76
+ "user-agent": "tracehub-cli",
77
+ authorization: `Bearer ${token}`,
78
+ "content-type": "application/json",
79
+ },
80
+ body: JSON.stringify({ machine: machineId(), rules }),
81
+ signal: options.signal
82
+ ? AbortSignal.any([timeout, options.signal])
83
+ : timeout,
84
+ });
85
+ if (!res.ok)
86
+ throw await errorOf(res);
87
+ }
88
+ // Sends every rule of the machine; on any failure the change stays pending
89
+ // and the error is thrown.
90
+ export async function registerConsent(baseUrl, token, store, options = {}) {
91
+ try {
92
+ await send(baseUrl, token, registryRules(store), options);
93
+ }
94
+ catch (err) {
95
+ markPending(reason(err));
96
+ throw err;
97
+ }
98
+ writeState({ pending: false, at: new Date().toISOString() });
99
+ }
100
+ // Uninstall: TraceHub forgets this machine's rules.
101
+ export async function revokeRegistration(baseUrl, token, options = {}) {
102
+ await send(baseUrl, token, [], options);
103
+ }
104
+ // Why a request failed, in a few words.
105
+ export function reason(err) {
106
+ if (err instanceof TracehubError)
107
+ return err.message;
108
+ const error = err;
109
+ if (error?.name === "TimeoutError")
110
+ return "TraceHub did not answer in time";
111
+ return (error?.cause?.code ?? error?.cause?.message ?? error?.message ?? String(err));
112
+ }
@@ -0,0 +1,98 @@
1
+ import { verifyUploadOwnership } from "./uploadPolicy.js";
2
+ export const DEFAULT_TRACEHUB_URL = "https://assisted-by.aui.dev";
3
+ export const ENV_TRACEHUB = "TRACEHUB_URL";
4
+ const REQUEST_TIMEOUT_MS = 15_000;
5
+ export function tracehubUrl(env = process.env) {
6
+ return (env[ENV_TRACEHUB] || DEFAULT_TRACEHUB_URL).replace(/\/+$/, "");
7
+ }
8
+ export class TracehubError extends Error {
9
+ status;
10
+ body;
11
+ constructor(status, message, body = {}) {
12
+ super(message);
13
+ this.status = status;
14
+ this.body = body;
15
+ }
16
+ }
17
+ export async function errorOf(res) {
18
+ let body = {};
19
+ try {
20
+ body = (await res.json());
21
+ }
22
+ catch {
23
+ /* non-JSON error body */
24
+ }
25
+ const message = typeof body["error"] === "string"
26
+ ? body["error"]
27
+ : `${res.status} ${res.statusText}`;
28
+ return new TracehubError(res.status, message, body);
29
+ }
30
+ export class TracehubClient {
31
+ baseUrl;
32
+ token;
33
+ deadline;
34
+ verified = new Map();
35
+ constructor(baseUrl, token, opts = {}) {
36
+ this.baseUrl = baseUrl;
37
+ this.token = token;
38
+ this.deadline = opts.deadline;
39
+ }
40
+ timeLeft() {
41
+ if (this.deadline === undefined)
42
+ return REQUEST_TIMEOUT_MS;
43
+ return Math.min(REQUEST_TIMEOUT_MS, this.deadline - Date.now());
44
+ }
45
+ verifyTarget(target) {
46
+ const key = `${target.owner}/${target.repo}`;
47
+ let verified = this.verified.get(key);
48
+ if (!verified) {
49
+ verified = verifyUploadOwnership(target, this.token, this.timeLeft());
50
+ this.verified.set(key, verified);
51
+ }
52
+ return verified;
53
+ }
54
+ async request(method, path, body) {
55
+ const timeLeft = this.timeLeft();
56
+ if (timeLeft <= 0)
57
+ throw new TracehubError(0, "upload budget exhausted");
58
+ const res = await fetch(`${this.baseUrl}${path}`, {
59
+ method,
60
+ headers: {
61
+ "user-agent": "tracehub-cli",
62
+ authorization: `Bearer ${this.token}`,
63
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
64
+ },
65
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
66
+ signal: AbortSignal.timeout(timeLeft),
67
+ });
68
+ if (!res.ok)
69
+ throw await errorOf(res);
70
+ return res;
71
+ }
72
+ // Replaces what the trace holds of the session.
73
+ async putTrace(target, traceId, name, upload) {
74
+ await this.verifyTarget(target);
75
+ const repo = `/repos/${target.owner}/${target.repo}`;
76
+ const res = await this.request("PUT", `${repo}/traces/${traceId}/sessions/${name}`, upload);
77
+ return (await res.json());
78
+ }
79
+ // Adds context conversations to the pull request, merged by conversation
80
+ // and message id.
81
+ async putContext(target, number, context) {
82
+ await this.verifyTarget(target);
83
+ const repo = `/repos/${target.owner}/${target.repo}`;
84
+ const res = await this.request("PUT", `${repo}/pulls/${number}/context`, {
85
+ context,
86
+ });
87
+ return (await res.json());
88
+ }
89
+ // Detaches context conversations from the pull request, whoever attached
90
+ // them; answers the refs that were attached. A 404 when none was.
91
+ async deleteContext(target, number, refs) {
92
+ await this.verifyTarget(target);
93
+ const repo = `/repos/${target.owner}/${target.repo}`;
94
+ const query = refs.map((ref) => `ref=${encodeURIComponent(ref)}`).join("&");
95
+ const res = await this.request("DELETE", `${repo}/pulls/${number}/context?${query}`);
96
+ return (await res.json());
97
+ }
98
+ }
@@ -0,0 +1,106 @@
1
+ import { addedLines, commitOfTrace } from "../git/git.js";
2
+ import { pendingMarkers, saveUploaded, } from "../git/markers.js";
3
+ import { findSessionFile, isClaudeSubagent } from "../local/discover.js";
4
+ import { sessionLines } from "../local/lines.js";
5
+ import { fetchAll, readProviders } from "../local/providers.js";
6
+ import { claudeSubagentLabel, listSubagents } from "../local/subagents.js";
7
+ import { formatSessionRef, parseSessionRef, sessionName, } from "../protocol/sessionRef.js";
8
+ import { redactValue, } from "../redact/redact.js";
9
+ import { buildTrace } from "../trace/build.js";
10
+ import { firstLine } from "./errors.js";
11
+ function subagentsOf(ref, file) {
12
+ if (isClaudeSubagent(ref))
13
+ return [];
14
+ return listSubagents(ref, file).map((subagent) => ({
15
+ id: subagent.id,
16
+ kind: subagent.kind,
17
+ toolUseId: subagent.toolUseId,
18
+ lines: sessionLines({ agent: ref.agent, id: subagent.id }, subagent.file),
19
+ }));
20
+ }
21
+ // Uploads the trace of each pending marker: the session's turns up to the
22
+ // commit, the sourcemap of the lines the commit adds, and the context
23
+ // conversations its marker and briefs name. `contextAllowed` is the
24
+ // repository's permission rule: without it no provider runs.
25
+ export async function uploadMarkers(client, target, stateDir, cwd, root, markers, opts = {}, contextAllowed = false) {
26
+ const pending = pendingMarkers(markers);
27
+ const result = {
28
+ uploaded: [],
29
+ skipped: [],
30
+ masked: [],
31
+ missing: [],
32
+ outside: [],
33
+ contextFailed: [],
34
+ failed: undefined,
35
+ };
36
+ const missing = new Set();
37
+ const providers = readProviders();
38
+ const fetched = new Map();
39
+ const failedRefs = new Set();
40
+ const reportRef = (ref, reason) => {
41
+ if (failedRefs.has(ref))
42
+ return;
43
+ failedRefs.add(ref);
44
+ result.contextFailed.push({ ref, reason });
45
+ };
46
+ for (const marker of pending) {
47
+ const ref = parseSessionRef(marker.session);
48
+ const file = ref ? findSessionFile(ref) : undefined;
49
+ if (!ref || !file) {
50
+ if (ref && !missing.has(marker.session))
51
+ result.missing.push(ref);
52
+ missing.add(marker.session);
53
+ continue;
54
+ }
55
+ try {
56
+ const sha = commitOfTrace(cwd, marker.traceId);
57
+ const built = buildTrace({
58
+ agent: ref.agent,
59
+ id: ref.id,
60
+ lines: sessionLines(ref, file),
61
+ cut: marker.line,
62
+ committedAt: marker.ts,
63
+ subagents: subagentsOf(ref, file),
64
+ root,
65
+ added: sha ? addedLines(cwd, sha) : new Map(),
66
+ ...(isClaudeSubagent(ref)
67
+ ? { subagent: { label: claudeSubagentLabel(file) } }
68
+ : {}),
69
+ providers: Object.keys(providers),
70
+ }, opts);
71
+ if (!built) {
72
+ // Ran outside the repository and changed nothing in it: nothing to
73
+ // share, and nothing to retry.
74
+ saveUploaded(stateDir, [marker]);
75
+ result.outside.push(marker);
76
+ continue;
77
+ }
78
+ const refs = [...new Set([...(marker.context ?? []), ...built.refs])];
79
+ const context = await fetchAll(refs, contextAllowed, fetched, reportRef, providers);
80
+ const findings = [...built.findings];
81
+ if (context.length) {
82
+ const redacted = redactValue(context, opts);
83
+ built.upload.context = redacted.value;
84
+ findings.push(...redacted.findings);
85
+ }
86
+ const stored = await client.putTrace(target, marker.traceId, sessionName(ref), built.upload);
87
+ result.uploaded.push(marker);
88
+ saveUploaded(stateDir, [marker]);
89
+ if (findings.length || stored.withheld)
90
+ result.masked.push({
91
+ session: formatSessionRef(ref),
92
+ findings,
93
+ withheld: stored.withheld,
94
+ });
95
+ }
96
+ catch (err) {
97
+ result.failed = {
98
+ what: `trace ${marker.traceId} ${marker.session}`,
99
+ error: firstLine(err),
100
+ };
101
+ break;
102
+ }
103
+ }
104
+ result.skipped = pending.filter((marker) => !result.uploaded.includes(marker));
105
+ return result;
106
+ }
@@ -0,0 +1,60 @@
1
+ export const UPLOAD_OWNER = "assistant-ui";
2
+ export const UPLOAD_POLICY_ERROR = "trace uploads require one unambiguous GitHub repository owned by assistant-ui; nothing was uploaded";
3
+ // Only the real GitHub host and conventional Git transports are accepted.
4
+ // Do not use consent's permissive URL normalization as a security boundary.
5
+ export function parseUploadRemote(remote) {
6
+ const match = /^(?:git@github\.com:|https:\/\/github\.com\/|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/i.exec(remote);
7
+ if (!match || match[1].toLowerCase() !== UPLOAD_OWNER)
8
+ return undefined;
9
+ const repo = match[2].toLowerCase();
10
+ if (repo === "." || repo === "..")
11
+ return undefined;
12
+ return { owner: UPLOAD_OWNER, repo };
13
+ }
14
+ export function sameTarget(a, b) {
15
+ return a.owner === b.owner && a.repo === b.repo;
16
+ }
17
+ // Every effective fetch/push URL must identify the same org-owned repository.
18
+ // A personal fork plus an org upstream is ambiguous, so it cannot upload.
19
+ export function targetOfUploadRemotes(remotes) {
20
+ if (!remotes.length)
21
+ return undefined;
22
+ const targets = remotes.map(parseUploadRemote);
23
+ const first = targets[0];
24
+ return first && targets.every((target) => target && sameTarget(first, target))
25
+ ? first
26
+ : undefined;
27
+ }
28
+ // No trace contents are sent to GitHub. Verify fresh on every upload run,
29
+ // without following redirects after a transfer or rename. No positive disk cache.
30
+ export async function verifyUploadOwnership(target, token, timeoutMs, fetchFn = fetch) {
31
+ const parsed = parseUploadRemote(`https://github.com/${target.owner}/${target.repo}`);
32
+ if (!parsed || !sameTarget(parsed, target))
33
+ throw new Error(UPLOAD_POLICY_ERROR);
34
+ if (timeoutMs <= 0)
35
+ throw new Error("upload budget exhausted; nothing was uploaded");
36
+ let response;
37
+ try {
38
+ response = await fetchFn(`https://api.github.com/repos/${target.owner}/${target.repo}`, {
39
+ headers: {
40
+ accept: "application/vnd.github+json",
41
+ authorization: `Bearer ${token}`,
42
+ "user-agent": "tracehub-cli",
43
+ "x-github-api-version": "2022-11-28",
44
+ },
45
+ redirect: "error",
46
+ signal: AbortSignal.timeout(timeoutMs),
47
+ });
48
+ }
49
+ catch {
50
+ throw new Error("GitHub could not verify repository ownership; nothing was uploaded");
51
+ }
52
+ if (!response.ok) {
53
+ throw new Error(`GitHub ownership check answered ${response.status}; nothing was uploaded`);
54
+ }
55
+ const data = (await response.json());
56
+ if (data?.owner?.type !== "Organization" ||
57
+ data.owner.login?.toLowerCase() !== UPLOAD_OWNER ||
58
+ data.full_name?.toLowerCase() !== `${target.owner}/${target.repo}`)
59
+ throw new Error(UPLOAD_POLICY_ERROR);
60
+ }