tracehub 0.5.7 → 0.5.9

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.
@@ -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
@@ -100,6 +100,11 @@ export const ENV = [
100
100
  value: "<url>",
101
101
  description: "use another Tracehub server",
102
102
  },
103
+ {
104
+ name: "TRACEHUB_GITHUB_CLIENT_ID",
105
+ value: "<id>",
106
+ description: "use another GitHub App client ID for sign-in",
107
+ },
103
108
  ];
104
109
  const WIDTH = 80;
105
110
  /** `text` wrapped to WIDTH, every line after the first indented by `indent` spaces. */
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ import { cmdProviders } from "./cli/commands/providers.js";
7
7
  import { cmdSetup } from "./cli/commands/setup.js";
8
8
  import { cmdUninstall } from "./cli/commands/uninstall.js";
9
9
  import { fail, Reported } from "./cli/io.js";
10
- import { usage } from "./cli/usage.js";
10
+ import { commandUsage, usage } from "./cli/usage.js";
11
11
  const COMMAND_HANDLERS = {
12
12
  setup: cmdSetup,
13
13
  uninstall: cmdUninstall,
@@ -18,6 +18,13 @@ const COMMAND_HANDLERS = {
18
18
  async function main() {
19
19
  const args = parseArgs(process.argv.slice(2));
20
20
  const name = args.positional[0];
21
+ if (args.flags["help"] ||
22
+ ((name === "context" || name === "providers") && !args.positional[1])) {
23
+ process.stdout.write(name && Object.hasOwn(COMMAND_HANDLERS, name)
24
+ ? `${commandUsage(name)}\n`
25
+ : usage(true));
26
+ return;
27
+ }
21
28
  // What the Git hooks run; internal, so not in the usage.
22
29
  if (name === "hook") {
23
30
  // Hooks that ran npx from the home directory name the repository.
@@ -33,7 +40,7 @@ async function main() {
33
40
  return;
34
41
  }
35
42
  process.stdout.write(usage(true));
36
- if (name && !args.flags["help"] && !args.flags["h"] && name !== "help") {
43
+ if (name && name !== "help") {
37
44
  process.stderr.write(`\ntracehub: unknown command "${name}"\n`);
38
45
  process.exit(1);
39
46
  }
@@ -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,10 @@ 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
122
+ // Whether TraceHub has any session of the trace, asked of the site's
120
123
  // `.json` page with the user's GitHub token.
121
124
  export async function traceUploaded(target, traceId, token) {
122
- const res = await fetch(`${DASHBOARD_URL}/t/${target.owner}/${target.repo}/${traceId}.json`, {
125
+ const res = await fetch(`${webUrl()}/t/${target.owner}/${target.repo}/${traceId}.json`, {
123
126
  headers: {
124
127
  authorization: `Bearer ${token}`,
125
128
  "user-agent": "tracehub-cli",
@@ -7,7 +7,7 @@ import { fetchAll, readProviders } from "../local/providers.js";
7
7
  import { claudeSubagentLabel, listSubagents } from "../local/subagents.js";
8
8
  import { formatSessionRef, parseSessionRef, sessionName, } from "../protocol/sessionRef.js";
9
9
  import { redactValue, } from "../redact/redact.js";
10
- import { buildTrace } from "../trace/build.js";
10
+ import { buildTrace, namedSessions, parseSessionLines, } from "../trace/build.js";
11
11
  import { firstLine } from "./errors.js";
12
12
  function subagentsOf(ref, file) {
13
13
  if (isClaudeSubagent(ref))
@@ -73,14 +73,30 @@ export async function uploadMarkers(client, target, stateDir, cwd, root, markers
73
73
  }
74
74
  try {
75
75
  const sha = marker.commit ?? commitOfTrace(cwd, marker.traceId);
76
+ const lines = sessionLines(ref, file);
77
+ const subagents = subagentsOf(ref, file);
78
+ const transcripts = [
79
+ parseSessionLines(ref.agent, ref.id, lines, isClaudeSubagent(ref)),
80
+ ...subagents.map((s) => parseSessionLines(ref.agent, s.id, s.lines, true)),
81
+ ];
82
+ const named = new Map(transcripts
83
+ .flatMap((t) => namedSessions(t))
84
+ .map((r) => [formatSessionRef(r), r]));
85
+ const delegated = [];
86
+ for (const session of named.values()) {
87
+ const file = findSessionFile(session);
88
+ if (file)
89
+ delegated.push({ ...session, lines: sessionLines(session, file) });
90
+ }
76
91
  const built = buildTrace({
77
92
  agent: ref.agent,
78
93
  id: ref.id,
79
- lines: sessionLines(ref, file),
94
+ lines,
80
95
  cut: marker.line,
81
96
  committedAt: marker.ts,
82
97
  since: previousCommit(all, marker),
83
- subagents: subagentsOf(ref, file),
98
+ subagents,
99
+ delegated,
84
100
  root,
85
101
  added: sha ? addedLines(cwd, sha) : new Map(),
86
102
  ...(isClaudeSubagent(ref)
@@ -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,5 +1,5 @@
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
4
  export function git(args, opts = {}) {
5
5
  const out = execFileSync("git", args, {
@@ -73,17 +73,28 @@ function blocks(hook, manifest) {
73
73
  return [hookBlock(hook, version, null), repoNpxHookBlock(hook, version)];
74
74
  return [hookBlock(hook, version, manifest.runner)];
75
75
  }
76
- function source(hook, manifest, block = blocks(hook, manifest)[0]) {
77
- const delegated = manifest.delegate === null
78
- ? 'tracehub_hooks="$(git rev-parse --path-format=absolute --git-common-dir)/hooks"'
79
- : `tracehub_hooks=${quote(manifest.delegate)}`;
76
+ // The lines that find the hooks to delegate to and open the delegation, the
77
+ // form this release writes first. Without a repository (git init runs
78
+ // reference-transaction before it has one) there is nothing to delegate to.
79
+ function lookups(hook, manifest) {
80
+ const recursive = `[ "$tracehub_hooks/${hook}" -ef "$0" ]`;
81
+ if (manifest.delegate !== null)
82
+ return [
83
+ `tracehub_hooks=${quote(manifest.delegate)}\nif ${recursive}; then`,
84
+ ];
85
+ return [
86
+ `tracehub_hooks=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && tracehub_hooks="$tracehub_hooks/hooks"\nif [ -z "$tracehub_hooks" ]; then\n :\nelif ${recursive}; then`,
87
+ `tracehub_hooks="$(git rev-parse --path-format=absolute --git-common-dir)/hooks"\nif ${recursive}; then`,
88
+ ];
89
+ }
90
+ function source(hook, manifest, block = blocks(hook, manifest)[0], lookup = lookups(hook, manifest)[0]) {
80
91
  // An installed push-to-checkout hook replaces Git's built-in updateInstead behavior.
81
92
  const fallback = hook === "push-to-checkout"
82
93
  ? 'cd "$GIT_WORK_TREE" || exit 1\ngit update-index -q --ignore-submodules --refresh || exit 1\ngit diff-files --quiet --ignore-submodules -- || exit 1\ngit diff --cached --quiet --ignore-submodules -- || exit 1\nexec git read-tree -u -m "$1"\n'
83
94
  : hook === "fsmonitor-watchman" || hook === "proc-receive"
84
95
  ? "exit 1\n"
85
96
  : "";
86
- return `#!/bin/sh\n# tracehub global dispatcher\n${block}${delegated}\nif [ "$tracehub_hooks/${hook}" -ef "$0" ]; then\n printf '%s\\n' 'tracehub: recursive hook delegation skipped; review core.hooksPath' >&2\nelif [ -x "$tracehub_hooks/${hook}" ]; then\n exec "$tracehub_hooks/${hook}" "$@"\nfi\n${fallback}`;
97
+ return `#!/bin/sh\n# tracehub global dispatcher\n${block}${lookup}\n printf '%s\\n' 'tracehub: recursive hook delegation skipped; review core.hooksPath' >&2\nelif [ -x "$tracehub_hooks/${hook}" ]; then\n exec "$tracehub_hooks/${hook}" "$@"\nfi\n${fallback}`;
87
98
  }
88
99
  function inheritedSystemPath(cwd, env) {
89
100
  const result = spawnSync("git", ["config", "--show-scope", "--path", "--get-all", "core.hooksPath"], { cwd, env, encoding: "utf8" });
@@ -128,7 +139,8 @@ function verifyFiles(directory, manifest) {
128
139
  !lstatSync(path).isFile() ||
129
140
  lstatSync(path).isSymbolicLink() ||
130
141
  (lstatSync(path).mode & 0o777) !== 0o755 ||
131
- !blocks(hook, manifest).some((block) => readFileSync(path, "utf8") === source(hook, manifest, block)))
142
+ !blocks(hook, manifest).some((block) => lookups(hook, manifest).some((lookup) => readFileSync(path, "utf8") ===
143
+ source(hook, manifest, block, lookup))))
132
144
  throw new Error(`Global dispatcher changed; preserve it and repair manually: ${path}`);
133
145
  }
134
146
  }
@@ -181,7 +193,8 @@ export function installGlobalHooks(directory, cwd, env = process.env, runner = h
181
193
  next.cliVersion = hookVersion();
182
194
  if (current.cliVersion === next.cliVersion &&
183
195
  current.runner !== undefined &&
184
- sameRunner(current.runner, runner))
196
+ sameRunner(current.runner, runner) &&
197
+ HOOKS.every((hook) => readFileSync(join(directory, hook), "utf8") === source(hook, next)))
185
198
  return "unchanged";
186
199
  for (const hook of HOOKS)
187
200
  writeFileSync(join(directory, hook), source(hook, next));
@@ -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
+ }
@@ -18,8 +18,8 @@ export function checkoutsNamed(command, home = "") {
18
18
  const LOOKBACK_MS = 7 * 24 * 3600_000;
19
19
  // The commit's time is in whole seconds, its session's in milliseconds.
20
20
  const SLACK_MS = 60_000;
21
- export const HIGH = 7;
22
- export const MEDIUM = 4;
21
+ const HIGH = 7;
22
+ const MEDIUM = 4;
23
23
  // The session's events with the line each one came from; parsed one line at
24
24
  // a time, as commitBoundary reads them.
25
25
  export function candidateOf(ref, file, lines, opts = {}) {
@@ -76,7 +76,7 @@ function editedPath(path, cwd, files) {
76
76
  return files.find((f) => full === f || full.endsWith(`/${f}`));
77
77
  }
78
78
  const TRUNK = new Set(["main", "master", "HEAD", "develop"]);
79
- export function confidenceOf(score, tied) {
79
+ function confidenceOf(score, tied) {
80
80
  if (tied && score >= HIGH)
81
81
  return "high";
82
82
  if (score >= MEDIUM)
@@ -3,7 +3,7 @@ import { isAbsolute, join } from "node:path";
3
3
  import { parseClaude } from "../transcript/parseClaude.js";
4
4
  import { codexSessionMeta } from "../transcript/parseCodex.js";
5
5
  import { openCommitCalls } from "./commitBoundary.js";
6
- import { fileEntry, firstLineOf, listDir } from "./files.js";
6
+ import { fileEntry, firstLineOf, listDir, walkClaudeTranscripts, } from "./files.js";
7
7
  import { completeLines } from "./lines.js";
8
8
  import { hasOpencodeSession, listOpencodeSessions, } from "./opencode.js";
9
9
  import { claudeProjectsDir, codexSessionsDir, encodeClaudeCwd, home, opencodeDb, } from "./paths.js";
@@ -116,22 +116,9 @@ export function isClaudeSubagent(ref) {
116
116
  // ~/.claude/projects/*/<session id>/subagents/agent-<id>.jsonl, for the
117
117
  // files written to since sinceMs.
118
118
  function* walkClaudeSubagentFiles(sinceMs) {
119
- const base = claudeProjectsDir();
120
- for (const project of listDir(base)) {
121
- for (const session of listDir(join(base, project))) {
122
- if (session.endsWith(".jsonl"))
123
- continue;
124
- const dir = join(base, project, session, "subagents");
125
- for (const name of listDir(dir)) {
126
- if (!/^agent-[A-Za-z0-9_-]+\.jsonl$/.test(name))
127
- continue;
128
- const entry = fileEntry(join(dir, name));
129
- if (!entry || entry.mtimeMs <= sinceMs)
130
- continue;
131
- const parent = join(base, project, `${session}.jsonl`);
132
- yield { ...entry, id: name.slice(0, -".jsonl".length), parent };
133
- }
134
- }
119
+ for (const entry of walkClaudeTranscripts(claudeProjectsDir())) {
120
+ if (entry.parent && entry.mtimeMs > sinceMs)
121
+ yield { ...entry, parent: entry.parent };
135
122
  }
136
123
  }
137
124
  // The ways a command can name the repository's checkout.
@@ -171,11 +158,11 @@ export function subagentWork(lines, root, sinceMs) {
171
158
  }
172
159
  // How far back subagents filed under other projects are read: they are
173
160
  // read whole, so only the recent ones.
174
- export const SUBAGENT_WINDOW_MS = DAY_MS;
161
+ const SUBAGENT_WINDOW_MS = DAY_MS;
175
162
  // The subagents of sessions that ran outside the repository, written to
176
163
  // recently, that name the repository somewhere. A subagent of a session
177
164
  // inside it is a run of that session's trace instead.
178
- function listClaudeSubagents(repoRoot, sinceMs) {
165
+ function discoverClaudeSubagents(repoRoot, sinceMs) {
179
166
  const from = Math.max(sinceMs, Date.now() - SUBAGENT_WINDOW_MS);
180
167
  const parents = new Map();
181
168
  const found = [];
@@ -246,7 +233,7 @@ export function discoverActiveSessions(repoRoot, sinceMs) {
246
233
  repoRoot,
247
234
  sinceMs,
248
235
  claudeFiles: listClaudeFiles(repoRoot),
249
- claudeSubagents: listClaudeSubagents(repoRoot, sinceMs),
236
+ claudeSubagents: discoverClaudeSubagents(repoRoot, sinceMs),
250
237
  codexFiles: listCodexFiles(sinceMs),
251
238
  opencodeSessions: listOpencodeSessions(sinceMs),
252
239
  });
@@ -1,3 +1,4 @@
1
+ import { basename, join } from "node:path";
1
2
  import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync, } from "node:fs";
2
3
  // A JSON object read from a file; anything else (missing, malformed, an
3
4
  // array) reads as an empty object.
@@ -53,3 +54,25 @@ export function firstLineOf(file) {
53
54
  closeSync(fd);
54
55
  }
55
56
  }
57
+ export function* walkClaudeTranscripts(projectsDir, sessionFile) {
58
+ const sessions = sessionFile
59
+ ? [sessionFile]
60
+ : listDir(projectsDir).flatMap((project) => listDir(join(projectsDir, project)).map((name) => join(projectsDir, project, name)));
61
+ for (const path of sessions) {
62
+ if (!sessionFile && path.endsWith(".jsonl")) {
63
+ const entry = fileEntry(path);
64
+ if (entry)
65
+ yield { ...entry, id: basename(path, ".jsonl") };
66
+ continue;
67
+ }
68
+ const parent = sessionFile ?? `${path}.jsonl`;
69
+ const dir = join(sessionFile ? sessionFile.replace(/\.jsonl$/, "") : path, "subagents");
70
+ for (const name of listDir(dir).sort()) {
71
+ if (!/^agent-[A-Za-z0-9_-]+\.jsonl$/.test(name))
72
+ continue;
73
+ const entry = fileEntry(join(dir, name));
74
+ if (entry)
75
+ yield { ...entry, id: basename(name, ".jsonl"), parent };
76
+ }
77
+ }
78
+ }
@@ -1,7 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
4
- import { writeFileSync } from "node:fs";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
5
4
  import { dirname } from "node:path";
6
5
  import { conversationOf, parseContextEntries, parseContextRef, PROVIDER_NAME, } from "../protocol/context.js";
7
6
  import { providersFile } from "./paths.js";
@@ -53,7 +52,7 @@ export function providerArgv(provider, id) {
53
52
  }
54
53
  // An entry without an id is named by its content, so attaching it twice
55
54
  // replaces it rather than adding it again.
56
- export function contentId(entry) {
55
+ function contentId(entry) {
57
56
  const key = JSON.stringify([
58
57
  entry.author,
59
58
  entry.at,
@@ -1,7 +1,7 @@
1
1
  import { basename, dirname, join } from "node:path";
2
2
  import { codexSessionMeta } from "../transcript/parseCodex.js";
3
3
  import { walkCodexFiles } from "./discover.js";
4
- import { firstLineOf, listDir, readJsonObject } from "./files.js";
4
+ import { firstLineOf, walkClaudeTranscripts, readJsonObject } from "./files.js";
5
5
  import { listOpencodeSubagents } from "./opencode.js";
6
6
  const DEFAULT_KIND = "subagent";
7
7
  // Claude Code keeps subagent transcripts beside the parent session file, in
@@ -21,18 +21,15 @@ export function claudeSubagentLabel(file) {
21
21
  }
22
22
  // An optional agent-<id>.meta.json says how the parent launched the subagent.
23
23
  export function listClaudeSubagents(sessionFile) {
24
- const dir = claudeSubagentDir(sessionFile);
25
24
  const subagents = [];
26
- for (const name of listDir(dir).sort()) {
27
- const id = /^agent-([A-Za-z0-9_-]+)\.jsonl$/.exec(name)?.[1];
28
- if (!id)
29
- continue;
30
- const meta = readJsonObject(join(dir, `agent-${id}.meta.json`));
25
+ for (const entry of walkClaudeTranscripts("", sessionFile)) {
26
+ const id = entry.id.slice("agent-".length);
27
+ const meta = readJsonObject(entry.file.replace(/\.jsonl$/, ".meta.json"));
31
28
  const toolUseId = stringField(meta, "toolUseId");
32
29
  subagents.push({
33
30
  id,
34
31
  kind: stringField(meta, "agentType") ?? DEFAULT_KIND,
35
- file: join(dir, name),
32
+ file: entry.file,
36
33
  ...(toolUseId ? { toolUseId } : {}),
37
34
  });
38
35
  }
@@ -61,7 +61,14 @@ function parseRun(raw, depth) {
61
61
  if (!isObject(raw) || !isString(raw["label"]))
62
62
  return undefined;
63
63
  const turns = all(raw["turns"], (t) => parseTurn(t, depth));
64
- return turns ? { label: raw["label"].slice(0, 200), turns } : undefined;
64
+ const agent = raw["agent"];
65
+ return turns
66
+ ? {
67
+ label: raw["label"].slice(0, 200),
68
+ turns,
69
+ ...(AGENTS.includes(agent) ? { agent } : {}),
70
+ }
71
+ : undefined;
65
72
  }
66
73
  function parseSourcemap(raw) {
67
74
  if (!isObject(raw))
@@ -0,0 +1,26 @@
1
+ export const WEB_URL = "https://tracehub.aui.dev";
2
+ const ID = /^[0-9a-f]{16}$/;
3
+ const LINE = /^[ \t]*Assisted-by:[ \t]*(?:\S*\/)?([0-9a-f]{16})[ \t]*$/gm;
4
+ const PULL = /^[ \t]*Assisted-by:[ \t]*\S*\/pr\/([\w.-]+)\/([\w.-]+)\/([1-9]\d{0,9})[ \t]*$/gm;
5
+ export function isTraceId(s) {
6
+ return ID.test(s);
7
+ }
8
+ export function traceUrl(target, id, base = WEB_URL) {
9
+ return `${base}/t/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${id}`;
10
+ }
11
+ // Squashed commits put trailers in the body, where git's trailer parser no longer sees them.
12
+ export function traceIds(message) {
13
+ return [...new Set([...message.matchAll(LINE)].map((m) => m[1]))];
14
+ }
15
+ export function pullUrl(target, number, base = WEB_URL) {
16
+ return `${base}/pr/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${number}`;
17
+ }
18
+ // The pull requests of the repository a message links to: a squash merge
19
+ // names its pull request once instead of each squashed commit's trace.
20
+ export function pullNumbers(message, target) {
21
+ const numbers = [...message.matchAll(PULL)]
22
+ .filter((m) => m[1].toLowerCase() === target.owner.toLowerCase() &&
23
+ m[2].toLowerCase() === target.repo.toLowerCase())
24
+ .map((m) => Number(m[3]));
25
+ return [...new Set(numbers)];
26
+ }
@@ -3,11 +3,11 @@ import { join } from "node:path";
3
3
  import { configDir } from "../local/paths.js";
4
4
  // The deny list is edited by hand: one literal per line. A shorter line would
5
5
  // mask ordinary words, so it is ignored.
6
- export const DENY_MIN_LENGTH = 6;
6
+ const DENY_MIN_LENGTH = 6;
7
7
  export function denyFile() {
8
8
  return join(configDir(), "deny.txt");
9
9
  }
10
- export function parseDenyList(text) {
10
+ function parseDenyList(text) {
11
11
  return [
12
12
  ...new Set(text
13
13
  .split("\n")