tracehub 0.5.3 → 0.5.5

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.
@@ -17,7 +17,7 @@ import { formatSessionRef } from "../../protocol/sessionRef.js";
17
17
  import { ENV_CONTEXT, ENV_SESSION_ID } from "../../local/paths.js";
18
18
  import { warn } from "../io.js";
19
19
  import { BACKGROUND_BUDGET_MS, clientFor, commitCount, pushBudgetMs, ranOutOfTime, reportUpload, redactOptions, usableAuth, } from "../remote.js";
20
- import { consentFor, hooksDisabled, resolveSessions, stateDir, uploadTargetFor, } from "../repo.js";
20
+ import { consentFor, hooksDisabled, pushTargetFor, resolveSessions, stateDir, uploadTargetFor, } from "../repo.js";
21
21
  // The trailer names the commit's sessions on tracehub, so a message that
22
22
  // already carries one (amend, rebase, cherry-pick, a squash folding earlier
23
23
  // messages) keeps it, and the markers recorded under it stay with the commit.
@@ -37,21 +37,25 @@ function hookPrepareCommitMsg(args, cwd) {
37
37
  const consent = consentFor(cwd);
38
38
  if (consent === false)
39
39
  return;
40
- const { refs } = resolveSessions(cwd, root);
41
- if (!refs.length)
40
+ const { sessions } = resolveSessions(cwd, root);
41
+ if (!sessions.length)
42
42
  return;
43
43
  if (consent === undefined) {
44
- warn(`${refs.length} agent session(s) could have been attached to this commit; run "tracehub setup" to allow uploads for this repository or its organization`);
44
+ warn(`${sessions.length} agent session(s) could have been attached to this commit; run "tracehub setup" to allow uploads for this repository or its organization`);
45
45
  return;
46
46
  }
47
- let id = traceIds(readFileSync(messageFile, "utf8")).at(-1);
48
- if (!id) {
49
- id = newTraceId();
50
- git(interpretTrailersArgs(target, id, messageFile), { cwd });
51
- }
52
- for (const ref of recordMarkers(stateDir(cwd), id, refs, new Date(), envContextRefs())) {
47
+ const kept = traceIds(readFileSync(messageFile, "utf8")).at(-1);
48
+ const id = kept ?? newTraceId();
49
+ const missing = recordMarkers(stateDir(cwd), id, sessions, new Date(), envContextRefs());
50
+ for (const ref of missing)
53
51
  warn(`session ${formatSessionRef(ref)} not found on this machine; no marker recorded`);
54
- }
52
+ if (kept)
53
+ return;
54
+ // A trailer without a marker would link to a trace nothing ever uploads.
55
+ if (missing.length < sessions.length)
56
+ git(interpretTrailersArgs(target, id, messageFile), { cwd });
57
+ else
58
+ warn("no trace attached to this commit");
55
59
  }
56
60
  // The context refs of TRACEHUB_CONTEXT; one that is not a ref is reported.
57
61
  function envContextRefs() {
@@ -75,14 +79,15 @@ async function hookPrePush(args, cwd) {
75
79
  warn('pre-push requires Git\'s destination arguments; forward "$@" from the hook; nothing was uploaded');
76
80
  return;
77
81
  }
78
- const target = uploadTargetFor(cwd, {
82
+ const push = pushTargetFor(cwd, {
79
83
  remote: args.positional[2],
80
84
  url: pushedUrl,
81
85
  });
82
- if (!target) {
86
+ if (!push) {
83
87
  warn(UPLOAD_POLICY_ERROR);
84
88
  return;
85
89
  }
90
+ const { target } = push;
86
91
  const dir = stateDir(cwd);
87
92
  const input = process.stdin.isTTY ? "" : readFileSync(0, "utf8");
88
93
  if (!input.trim()) {
@@ -115,7 +120,7 @@ async function hookPrePush(args, cwd) {
115
120
  const auth = await freshAuth(stored);
116
121
  await retryRegistration(auth.accessToken);
117
122
  const client = clientFor(auth, pushBudgetMs());
118
- await client.verifyTarget(target);
123
+ await client.verifyPush(push);
119
124
  const result = await uploadMarkers(client, target, dir, cwd, repoRoot(cwd) ?? cwd, markers, redactOptions(), consentFor(cwd) === true);
120
125
  // A big session can take longer than a push waits. The rest goes on in
121
126
  // the background, so a commit whose branch is never pushed again (a
@@ -154,11 +159,12 @@ async function hookUpload(args, cwd) {
154
159
  const [pushedUrl, ...ids] = args.positional.slice(2);
155
160
  if (!pushedUrl || !ids.length)
156
161
  return;
157
- const target = uploadTargetFor(cwd, { url: pushedUrl });
158
- if (!target) {
162
+ const push = pushTargetFor(cwd, { url: pushedUrl });
163
+ if (!push) {
159
164
  warn(UPLOAD_POLICY_ERROR);
160
165
  return;
161
166
  }
167
+ const { target } = push;
162
168
  const dir = stateDir(cwd);
163
169
  const markers = readMarkers(dir).filter((marker) => ids.includes(marker.traceId));
164
170
  if (!pendingMarkers(markers).length)
@@ -171,7 +177,7 @@ async function hookUpload(args, cwd) {
171
177
  try {
172
178
  const auth = await freshAuth(stored);
173
179
  const client = clientFor(auth, BACKGROUND_BUDGET_MS);
174
- await client.verifyTarget(target);
180
+ await client.verifyPush(push);
175
181
  const result = await uploadMarkers(client, target, dir, cwd, repoRoot(cwd) ?? cwd, markers, redactOptions(), consentFor(cwd) === true);
176
182
  reportUpload(result, target, warn);
177
183
  }
package/dist/cli/repo.js CHANGED
@@ -2,13 +2,16 @@ import { mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { getConsent, readConsent } from "../client/consent.js";
4
4
  import { gitDir, headTimestampMs, originUrl, remoteUrls } from "../git/git.js";
5
- import { sameTarget, targetOfUploadRemotes } from "../client/uploadPolicy.js";
6
- import { pendingCommitCall } from "../local/commitBoundary.js";
5
+ import { repositoryOfRemotes, sameTarget, targetOfUploadRemotes, } from "../client/uploadPolicy.js";
6
+ import { openCommitCalls, pendingCommitCall } from "../local/commitBoundary.js";
7
+ import { firstLineOf } from "../local/files.js";
7
8
  import { sessionLines } from "../local/lines.js";
8
9
  import { opencodePendingCommitCall } from "../local/opencode.js";
9
- import { discoverActiveSessions, ROOT_COMMIT_WINDOW_MS, } from "../local/discover.js";
10
- import { consentFile, ENV_DISABLE, ENV_SESSION_ID, GIT_STATE_DIR, } from "../local/paths.js";
11
- import { parseSessionRef, uniqueRefs, } from "../protocol/sessionRef.js";
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";
12
+ import { listClaudeSubagents } from "../local/subagents.js";
13
+ import { formatSessionRef, parseSessionRef, } from "../protocol/sessionRef.js";
14
+ import { codexSessionMeta } from "../transcript/parseCodex.js";
12
15
  import { fail } from "./io.js";
13
16
  export function hooksDisabled() {
14
17
  return process.env[ENV_DISABLE] === "0";
@@ -29,23 +32,86 @@ function forcedSessions() {
29
32
  .map((s) => parseSessionRef(s))
30
33
  .filter((ref) => ref !== undefined);
31
34
  }
32
- // The sessions a commit made now would attach: the ones the environment
33
- // forces, else the ones active since the last commit.
35
+ // The subagents of a Claude Code session with an open `git commit` call:
36
+ // the ones whose call is in this checkout, else the only one there is.
37
+ function committingSubagents(file, root) {
38
+ const open = listClaudeSubagents(file)
39
+ .map((sub) => ({
40
+ sub,
41
+ lines: sessionLines({ agent: "claude", id: sub.id }, sub.file),
42
+ }))
43
+ .filter(({ lines }) => openCommitCalls("claude", lines, true).length);
44
+ const here = open.filter(({ lines }) => subagentWork(lines, root, -Infinity).committing);
45
+ const chosen = here.length ? here : open.length === 1 ? open : [];
46
+ return chosen.map(({ sub }) => ({
47
+ agent: "claude",
48
+ id: `${CLAUDE_SUBAGENT_PREFIX}${sub.id}`,
49
+ file: sub.file,
50
+ }));
51
+ }
52
+ function sessionCwd(ref, file) {
53
+ return ref.agent === "claude"
54
+ ? claudeCwd(file)
55
+ : (codexSessionMeta(firstLineOf(file))?.cwd ?? "");
56
+ }
57
+ // The sessions the commit's environment names: Claude Code and Codex give
58
+ // every command the id of the session it runs in. A session that has the
59
+ // open `git commit` call made the commit, wherever it ran. When one of a
60
+ // Claude Code session's subagents has it instead (their commands carry the
61
+ // parent's id), the parent is attached if it ran in the repository, with
62
+ // the subagent as a run, else the subagent alone. A named session that did
63
+ // neither attaches only when it ran in the repository.
64
+ export function environmentSessions(root) {
65
+ const named = [
66
+ parseSessionRef(`claude:${process.env[ENV_CLAUDE_SESSION] ?? ""}`),
67
+ parseSessionRef(`codex:${process.env[ENV_CODEX_THREAD] ?? ""}`),
68
+ ].filter((ref) => ref !== undefined);
69
+ const found = [];
70
+ for (const ref of named) {
71
+ const file = findSessionFile(ref);
72
+ if (!file)
73
+ continue;
74
+ if (pendingCommitCall(ref.agent, sessionLines(ref, file))) {
75
+ found.push({ ...ref, file, committer: true });
76
+ continue;
77
+ }
78
+ const cwd = sessionCwd(ref, file);
79
+ if (cwd && ranInside(cwd, root))
80
+ found.push({ ...ref, file });
81
+ else if (ref.agent === "claude")
82
+ found.push(...committingSubagents(file, root));
83
+ }
84
+ return found;
85
+ }
86
+ function unique(sessions) {
87
+ const byKey = new Map(sessions.map((s) => [formatSessionRef(s), s]));
88
+ return [...byKey.values()];
89
+ }
90
+ // The sessions a commit made now would attach: the ones TRACEHUB_ID names,
91
+ // else the ones the agent's environment names, else the ones active since
92
+ // the last commit.
34
93
  export function resolveSessions(cwd, root) {
35
94
  const forced = forcedSessions();
36
95
  if (forced.length)
37
- return { refs: forced, source: `env ${ENV_SESSION_ID}` };
96
+ return { sessions: forced, source: `env ${ENV_SESSION_ID}` };
97
+ const named = environmentSessions(root);
98
+ if (named.length)
99
+ return { sessions: unique(named), source: "agent environment" };
38
100
  const since = headTimestampMs(cwd) ?? Date.now() - ROOT_COMMIT_WINDOW_MS;
39
101
  const found = discoverActiveSessions(root, since);
40
102
  const committing = found.filter((ref) => ref.committing ??
41
103
  (ref.agent === "opencode"
42
104
  ? opencodePendingCommitCall(ref.id)
43
105
  : pendingCommitCall(ref.agent, sessionLines(ref, ref.file))));
44
- const refs = uniqueRefs((committing.length ? committing : found).map((f) => ({
106
+ const sessions = unique((committing.length ? committing : found).map((f) => ({
45
107
  agent: f.agent,
46
108
  id: f.id,
109
+ file: f.file,
47
110
  })));
48
- return { refs, source: committing.length ? "active commit" : "discovery" };
111
+ return {
112
+ sessions,
113
+ source: committing.length ? "active commit" : "discovery",
114
+ };
49
115
  }
50
116
  export function consentFor(cwd) {
51
117
  const remote = originUrl(cwd);
@@ -55,16 +121,25 @@ export function consentFor(cwd) {
55
121
  }
56
122
  // The repository traces upload to is origin's: every effective fetch/push
57
123
  // URL of origin must name it. Other remotes (contributors' forks kept for
58
- // review) play no part. A push must go to that same repository: the URLs of
59
- // the remote being pushed to, when it is a configured remote, and the URL Git
60
- // passes to the hook.
61
- export function uploadTargetFor(cwd, push) {
62
- const target = targetOfUploadRemotes(remoteUrls(cwd, "origin"));
63
- if (!target || !push)
64
- return target;
124
+ // review) play no part.
125
+ export function uploadTargetFor(cwd) {
126
+ return targetOfUploadRemotes(remoteUrls(cwd, "origin"));
127
+ }
128
+ // A push uploads when it goes to origin's repository or to a fork of it,
129
+ // which the upload run confirms with GitHub. The destination is the URL Git
130
+ // passes to the hook and, when it is a configured remote, the pushed remote's
131
+ // own URLs, all naming one GitHub repository.
132
+ export function pushTargetFor(cwd, push) {
133
+ const target = uploadTargetFor(cwd);
134
+ if (!target)
135
+ return undefined;
65
136
  const pushed = [push.url];
66
137
  if (push.remote && push.remote !== push.url)
67
138
  pushed.push(...remoteUrls(cwd, push.remote));
68
- const destination = targetOfUploadRemotes(pushed);
69
- return destination && sameTarget(destination, target) ? target : undefined;
139
+ const destination = repositoryOfRemotes(pushed);
140
+ if (!destination)
141
+ return undefined;
142
+ return sameTarget(destination, target)
143
+ ? { target }
144
+ : { target, fork: destination };
70
145
  }
package/dist/cli/usage.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // `tracehub hook prepare-commit-msg|pre-push`, is internal and left out.
5
5
  import { styleText } from "node:util";
6
6
  import { ENV_TRACEHUB } from "../client/tracehub.js";
7
- import { ENV_CONTEXT, ENV_DISABLE, ENV_SESSION_ID } from "../local/paths.js";
7
+ import { ENV_CLAUDE_CONFIG_DIR, ENV_CODEX_HOME, ENV_CONTEXT, ENV_DISABLE, ENV_SESSION_ID, } from "../local/paths.js";
8
8
  export const COMMANDS = [
9
9
  {
10
10
  name: "setup",
@@ -56,6 +56,18 @@ export const COMMANDS = [
56
56
  "tracehub context remove --pr 12 manual:5f2de08703b94d2b",
57
57
  ],
58
58
  },
59
+ {
60
+ name: "backfill",
61
+ usage: "backfill (--pr <n> | <commit>…) [--dry-run]",
62
+ summary: "find and upload the agent sessions behind commits made before tracing",
63
+ about: "For each commit of your pull request (or each commit named) that has no trace on TraceHub, merges aside, scores the Claude Code, Codex and OpenCode sessions on this machine by what they left: git commit output naming the commit, a git commit call with its subject, a cwd or edit in a checkout of the repository, the pull request's URL, its branch, edits of the commit's files and of the lines it adds, all before the commit's time. It prints the evidence per commit and uploads, through the normal upload path (redacted, cut at the commit), each session of high confidence that is tied to this repository, links its trace to the commit and asks TraceHub to check the pull request again. --session <agent:id>[,…] only considers those sessions and also uploads them at medium confidence. --dry-run prints the matches and uploads nothing. Run it in a clone of the repository, on the machine where the agent ran. It needs a sign-in, a permission rule for the repository and, with --pr, a pull request you opened. --repo <owner/repo> confirms the clone.",
64
+ examples: [
65
+ "tracehub backfill --pr 386 --dry-run",
66
+ "tracehub backfill --pr 386",
67
+ "tracehub backfill --pr 386 --session claude:agent-a27592ec8a99c1afd",
68
+ "tracehub backfill 1a2b3c4d",
69
+ ],
70
+ },
59
71
  ];
60
72
  export const ENV = [
61
73
  {
@@ -63,6 +75,16 @@ export const ENV = [
63
75
  value: "<claude|codex|opencode>:<id>",
64
76
  description: "attach this session to the commit",
65
77
  },
78
+ {
79
+ name: ENV_CLAUDE_CONFIG_DIR,
80
+ value: "<dir>",
81
+ description: "read Claude Code's sessions from <dir>/projects, not ~/.claude",
82
+ },
83
+ {
84
+ name: ENV_CODEX_HOME,
85
+ value: "<dir>",
86
+ description: "read Codex's sessions from <dir>/sessions, not ~/.codex",
87
+ },
66
88
  {
67
89
  name: ENV_CONTEXT,
68
90
  value: "<provider>:<id>",
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from "./cli/args.js";
3
+ import { cmdBackfill } from "./cli/commands/backfill.js";
3
4
  import { cmdHook } from "./cli/commands/hook.js";
4
5
  import { cmdContext } from "./cli/commands/context.js";
5
6
  import { cmdProviders } from "./cli/commands/providers.js";
@@ -12,13 +13,21 @@ const COMMAND_HANDLERS = {
12
13
  uninstall: cmdUninstall,
13
14
  providers: cmdProviders,
14
15
  context: cmdContext,
16
+ backfill: cmdBackfill,
15
17
  };
16
18
  async function main() {
17
19
  const args = parseArgs(process.argv.slice(2));
18
20
  const name = args.positional[0];
19
21
  // What the Git hooks run; internal, so not in the usage.
20
- if (name === "hook")
22
+ if (name === "hook") {
23
+ // Hooks that ran npx from the home directory name the repository.
24
+ const repo = process.env["TRACEHUB_REPO"];
25
+ if (repo) {
26
+ process.chdir(repo);
27
+ delete process.env["TRACEHUB_REPO"];
28
+ }
21
29
  return cmdHook(args, process.cwd());
30
+ }
22
31
  if (name && Object.hasOwn(COMMAND_HANDLERS, name)) {
23
32
  await COMMAND_HANDLERS[name](args, process.cwd());
24
33
  return;
@@ -127,3 +127,39 @@ export async function loginOf(client, token) {
127
127
  throw new Error("GitHub named no user");
128
128
  return login;
129
129
  }
130
+ 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
+ });
140
+ if (!res.ok)
141
+ throw new Error(`GitHub answered ${res.status} for ${path}`);
142
+ return res.json();
143
+ }
144
+ export async function pullCommits(repo, number, token) {
145
+ const base = `/repos/${repo.owner}/${repo.repo}/pulls/${number}`;
146
+ const pull = (await githubGet(base, token));
147
+ const commits = [];
148
+ for (let page = 1; page <= 3; page++) {
149
+ const listed = (await githubGet(`${base}/commits?per_page=100&page=${page}`, token));
150
+ for (const c of listed)
151
+ commits.push({
152
+ sha: c.sha,
153
+ message: c.commit?.message ?? "",
154
+ authorAt: c.commit?.author?.date ?? "",
155
+ committedAt: c.commit?.committer?.date ?? "",
156
+ });
157
+ if (listed.length < 100)
158
+ break;
159
+ }
160
+ return {
161
+ author: pull.user?.login ?? "",
162
+ head: pull.head?.ref ?? "",
163
+ commits,
164
+ };
165
+ }
@@ -1,4 +1,5 @@
1
- import { verifyUploadOwnership } from "./uploadPolicy.js";
1
+ import { DASHBOARD_URL } from "../git/trailers.js";
2
+ import { verifyFork, verifyUploadOwnership, } from "./uploadPolicy.js";
2
3
  export const DEFAULT_TRACEHUB_URL = "https://assisted-by.aui.dev";
3
4
  export const ENV_TRACEHUB = "TRACEHUB_URL";
4
5
  const REQUEST_TIMEOUT_MS = 15_000;
@@ -51,6 +52,11 @@ export class TracehubClient {
51
52
  }
52
53
  return verified;
53
54
  }
55
+ async verifyPush(push) {
56
+ await this.verifyTarget(push.target);
57
+ if (push.fork)
58
+ await verifyFork(push.fork, push.target, this.token, this.timeLeft());
59
+ }
54
60
  async request(method, path, body) {
55
61
  const timeLeft = this.timeLeft();
56
62
  if (timeLeft <= 0)
@@ -76,6 +82,20 @@ export class TracehubClient {
76
82
  const res = await this.request("PUT", `${repo}/traces/${traceId}/sessions/${name}`, upload);
77
83
  return (await res.json());
78
84
  }
85
+ // Links a trace to a commit whose message does not name it (a backfill).
86
+ // Answers the pull requests tracehub knows the commit in.
87
+ async linkCommit(target, sha, traceId) {
88
+ await this.verifyTarget(target);
89
+ const repo = `/repos/${target.owner}/${target.repo}`;
90
+ const res = await this.request("PUT", `${repo}/commits/${sha}/traces/${traceId}`);
91
+ return (await res.json());
92
+ }
93
+ // Recomputes the "TraceHub traces" check on the pull request's head.
94
+ async checkPull(target, number) {
95
+ await this.verifyTarget(target);
96
+ const repo = `/repos/${target.owner}/${target.repo}`;
97
+ await this.request("POST", `${repo}/pulls/${number}/check`);
98
+ }
79
99
  // Adds context conversations to the pull request, merged by conversation
80
100
  // and message id.
81
101
  async putContext(target, number, context) {
@@ -96,3 +116,20 @@ export class TracehubClient {
96
116
  return (await res.json());
97
117
  }
98
118
  }
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`, {
123
+ headers: {
124
+ authorization: `Bearer ${token}`,
125
+ "user-agent": "tracehub-cli",
126
+ },
127
+ redirect: "manual",
128
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
129
+ });
130
+ if (res.status === 404)
131
+ return false;
132
+ if (res.ok)
133
+ return true;
134
+ throw new Error(`TraceHub answered ${res.status}`);
135
+ }
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { addedLines, commitOfTrace } from "../git/git.js";
2
3
  import { pendingMarkers, saveUploaded, } from "../git/markers.js";
3
4
  import { findSessionFile, isClaudeSubagent } from "../local/discover.js";
@@ -18,6 +19,13 @@ function subagentsOf(ref, file) {
18
19
  lines: sessionLines({ agent: ref.agent, id: subagent.id }, subagent.file),
19
20
  }));
20
21
  }
22
+ // The file the commit found the session in, else wherever this
23
+ // environment keeps it.
24
+ function sessionFileOf(marker, ref) {
25
+ return marker.file && existsSync(marker.file)
26
+ ? marker.file
27
+ : findSessionFile(ref);
28
+ }
21
29
  // Uploads the trace of each pending marker: the session's turns up to the
22
30
  // commit, the sourcemap of the lines the commit adds, and the context
23
31
  // conversations its marker and briefs name. `contextAllowed` is the
@@ -45,7 +53,7 @@ export async function uploadMarkers(client, target, stateDir, cwd, root, markers
45
53
  };
46
54
  for (const marker of pending) {
47
55
  const ref = parseSessionRef(marker.session);
48
- const file = ref ? findSessionFile(ref) : undefined;
56
+ const file = ref ? sessionFileOf(marker, ref) : undefined;
49
57
  if (!ref || !file) {
50
58
  if (ref && !missing.has(marker.session))
51
59
  result.missing.push(ref);
@@ -53,7 +61,7 @@ export async function uploadMarkers(client, target, stateDir, cwd, root, markers
53
61
  continue;
54
62
  }
55
63
  try {
56
- const sha = commitOfTrace(cwd, marker.traceId);
64
+ const sha = marker.commit ?? commitOfTrace(cwd, marker.traceId);
57
65
  const built = buildTrace({
58
66
  agent: ref.agent,
59
67
  id: ref.id,
@@ -66,6 +74,7 @@ export async function uploadMarkers(client, target, stateDir, cwd, root, markers
66
74
  ...(isClaudeSubagent(ref)
67
75
  ? { subagent: { label: claudeSubagentLabel(file) } }
68
76
  : {}),
77
+ ...(marker.committer ? { committer: true } : {}),
69
78
  providers: Object.keys(providers),
70
79
  }, opts);
71
80
  if (!built) {
@@ -2,40 +2,41 @@ export const UPLOAD_OWNER = "assistant-ui";
2
2
  export const UPLOAD_POLICY_ERROR = "trace uploads require one unambiguous GitHub repository owned by assistant-ui; nothing was uploaded";
3
3
  // Only the real GitHub host and conventional Git transports are accepted.
4
4
  // Do not use consent's permissive URL normalization as a security boundary.
5
- export function parseUploadRemote(remote) {
5
+ function parseGitHubRemote(remote) {
6
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)
7
+ if (!match)
8
8
  return undefined;
9
9
  const repo = match[2].toLowerCase();
10
10
  if (repo === "." || repo === "..")
11
11
  return undefined;
12
- return { owner: UPLOAD_OWNER, repo };
12
+ return { owner: match[1].toLowerCase(), repo };
13
+ }
14
+ export function parseUploadRemote(remote) {
15
+ const target = parseGitHubRemote(remote);
16
+ return target?.owner === UPLOAD_OWNER ? target : undefined;
13
17
  }
14
18
  export function sameTarget(a, b) {
15
19
  return a.owner === b.owner && a.repo === b.repo;
16
20
  }
17
- // Every given URL (one remote's effective fetch/push URLs, a push
18
- // destination) must identify the same org-owned repository.
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))
21
+ // The one GitHub repository every given URL (one remote's effective
22
+ // fetch/push URLs, a push destination) names.
23
+ export function repositoryOfRemotes(remotes) {
24
+ const repos = remotes.map(parseGitHubRemote);
25
+ const first = repos[0];
26
+ return first && repos.every((repo) => repo && sameTarget(first, repo))
25
27
  ? first
26
28
  : undefined;
27
29
  }
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);
30
+ export function targetOfUploadRemotes(remotes) {
31
+ const repo = repositoryOfRemotes(remotes);
32
+ return repo?.owner === UPLOAD_OWNER ? repo : undefined;
33
+ }
34
+ async function githubRepository(repo, token, timeoutMs, fetchFn, check) {
34
35
  if (timeoutMs <= 0)
35
36
  throw new Error("upload budget exhausted; nothing was uploaded");
36
37
  let response;
37
38
  try {
38
- response = await fetchFn(`https://api.github.com/repos/${target.owner}/${target.repo}`, {
39
+ response = await fetchFn(`https://api.github.com/repos/${repo.owner}/${repo.repo}`, {
39
40
  headers: {
40
41
  accept: "application/vnd.github+json",
41
42
  authorization: `Bearer ${token}`,
@@ -47,14 +48,32 @@ export async function verifyUploadOwnership(target, token, timeoutMs, fetchFn =
47
48
  });
48
49
  }
49
50
  catch {
50
- throw new Error("GitHub could not verify repository ownership; nothing was uploaded");
51
+ throw new Error(`GitHub could not verify ${check}; nothing was uploaded`);
51
52
  }
52
53
  if (!response.ok) {
53
- throw new Error(`GitHub ownership check answered ${response.status}; nothing was uploaded`);
54
+ throw new Error(`GitHub answered ${response.status} when verifying ${check}; nothing was uploaded`);
54
55
  }
55
- const data = (await response.json());
56
+ return response.json();
57
+ }
58
+ // No trace contents are sent to GitHub. Verify fresh on every upload run,
59
+ // without following redirects after a transfer or rename. No positive disk cache.
60
+ export async function verifyUploadOwnership(target, token, timeoutMs, fetchFn = fetch) {
61
+ const parsed = parseUploadRemote(`https://github.com/${target.owner}/${target.repo}`);
62
+ if (!parsed || !sameTarget(parsed, target))
63
+ throw new Error(UPLOAD_POLICY_ERROR);
64
+ const data = (await githubRepository(target, token, timeoutMs, fetchFn, "repository ownership"));
56
65
  if (data?.owner?.type !== "Organization" ||
57
66
  data.owner.login?.toLowerCase() !== UPLOAD_OWNER ||
58
67
  data.full_name?.toLowerCase() !== `${target.owner}/${target.repo}`)
59
68
  throw new Error(UPLOAD_POLICY_ERROR);
60
69
  }
70
+ // A push to a fork of the target uploads too: a maintainer's commits on a
71
+ // contributor's pull request branch. GitHub must name the target as the
72
+ // fork's parent.
73
+ export async function verifyFork(fork, target, token, timeoutMs, fetchFn = fetch) {
74
+ const data = (await githubRepository(fork, token, timeoutMs, fetchFn, "the fork's parent"));
75
+ if (data?.fork !== true ||
76
+ data.full_name?.toLowerCase() !== `${fork.owner}/${fork.repo}` ||
77
+ data.parent?.full_name?.toLowerCase() !== `${target.owner}/${target.repo}`)
78
+ throw new Error(`${fork.owner}/${fork.repo} is not a fork of ${target.owner}/${target.repo}; nothing was uploaded`);
79
+ }
package/dist/git/hooks.js CHANGED
@@ -3,6 +3,7 @@ import { dirname, join, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  const START = "# tracehub:start";
5
5
  const END = "# tracehub:end";
6
+ export const NPM_REGISTRY = "https://registry.npmjs.org";
6
7
  const VERSION = /^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i;
7
8
  export function hookVersion() {
8
9
  let directory = dirname(fileURLToPath(import.meta.url));
@@ -32,8 +33,11 @@ const warning = (text) => `printf '%s\\n' ${quote(`tracehub: ${text}`)} >&2`;
32
33
  function invocation(hook, version, runner, stdin) {
33
34
  const repair = 'run "tracehub setup" to repair the hooks';
34
35
  if (!runner)
36
+ // npx runs from the home directory against the public registry, so a
37
+ // repository's .npmrc or node_modules cannot choose what runs; the CLI
38
+ // then moves back into the repository (TRACEHUB_REPO).
35
39
  // --prefer-offline: a cached tracehub runs without asking the registry.
36
- return `npx --yes --prefer-offline tracehub@${version} hook ${hook} "$@" ${stdin} || ${warning(`the ${hook} hook could not run tracehub@${version}; ${repair}`)}`;
40
+ return `tracehub_repo=$(pwd) && (cd "\${HOME:-/}" && TRACEHUB_REPO="$tracehub_repo" exec npx --yes --prefer-offline --registry=${NPM_REGISTRY} tracehub@${version} hook ${hook} "$@") ${stdin} || ${warning(`the ${hook} hook could not run tracehub@${version}; ${repair}`)}`;
37
41
  return [
38
42
  `tracehub_node=${quote(runner.node)}`,
39
43
  `[ -x "$tracehub_node" ] || tracehub_node=node`,
@@ -1,5 +1,5 @@
1
1
  import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
2
- import { join } from "node:path";
2
+ import { isAbsolute, join } from "node:path";
3
3
  import { findSessionFile } from "../local/discover.js";
4
4
  import { sessionLines } from "../local/lines.js";
5
5
  import { parseContextRef } from "../protocol/context.js";
@@ -30,6 +30,13 @@ function parseMarker(line) {
30
30
  line: at,
31
31
  ts,
32
32
  ...(context.length ? { context } : {}),
33
+ ...(typeof m.file === "string" && isAbsolute(m.file)
34
+ ? { file: m.file }
35
+ : {}),
36
+ ...(m.committer === true ? { committer: true } : {}),
37
+ ...(typeof m.commit === "string" && /^[0-9a-f]{40}$/.test(m.commit)
38
+ ? { commit: m.commit }
39
+ : {}),
33
40
  uploaded: m.uploaded === true,
34
41
  };
35
42
  }
@@ -73,8 +80,9 @@ export function saveUploaded(stateDir, done) {
73
80
  export function recordMarkers(stateDir, traceId, sessions, now = new Date(), context = []) {
74
81
  const missing = [];
75
82
  mkdirSync(stateDir, { recursive: true });
76
- for (const ref of sessions) {
77
- const file = findSessionFile(ref);
83
+ for (const session of sessions) {
84
+ const ref = { agent: session.agent, id: session.id };
85
+ const file = session.file ?? findSessionFile(ref);
78
86
  if (!file) {
79
87
  missing.push(ref);
80
88
  continue;
@@ -85,9 +93,18 @@ export function recordMarkers(stateDir, traceId, sessions, now = new Date(), con
85
93
  line: sessionLines(ref, file).length,
86
94
  ts: now.toISOString(),
87
95
  ...(context.length ? { context } : {}),
96
+ file,
97
+ ...(session.committer ? { committer: true } : {}),
88
98
  uploaded: false,
89
99
  };
90
100
  appendFileSync(markersFile(stateDir), `${JSON.stringify(marker)}\n`);
91
101
  }
92
102
  return missing;
93
103
  }
104
+ // Appends markers as they are, for a backfill that knows its commits.
105
+ export function appendMarkers(stateDir, markers) {
106
+ if (!markers.length)
107
+ return;
108
+ mkdirSync(stateDir, { recursive: true });
109
+ appendFileSync(markersFile(stateDir), serializeMarkers(markers));
110
+ }
@@ -1,6 +1,6 @@
1
1
  const TRAILER_KEY = "Assisted-by";
2
2
  // The dashboard, where a trailer links to its trace.
3
- const DASHBOARD_URL = "https://tracehub.aui.dev";
3
+ export const DASHBOARD_URL = "https://tracehub.aui.dev";
4
4
  const ID = /^[0-9a-f]{16}$/;
5
5
  // The trailer's value is the trace's URL, or the bare trace id.
6
6
  const LINE = /^[ \t]*Assisted-by:[ \t]*(?:\S*\/)?([0-9a-f]{16})[ \t]*$/gm;