tracehub 0.5.4 → 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.
package/README.md CHANGED
@@ -78,7 +78,7 @@ Everything is computed on the developer's machine, redacted there, checked again
78
78
  Set it up once with `setup` (the other commands are under [Commands](#commands)). Run it in your terminal:
79
79
 
80
80
  ```sh
81
- npx --yes tracehub@0.5.4 setup
81
+ npx --yes tracehub@0.5.5 setup
82
82
  ```
83
83
 
84
84
  Setup is a form of three steps. Each step saves what you chose before the next one starts; cancelling (Ctrl-C) keeps the steps already done.
@@ -89,11 +89,11 @@ Setup is a form of three steps. Each step saves what you chose before the next o
89
89
 
90
90
  It ends with a summary of the account, the allowed rules and the hooks, and what is left to do. Setup needs an interactive terminal; without one it exits 1.
91
91
 
92
- To skip npx on every commit, install it globally instead: `npm install -g tracehub@0.5.4`, then `tracehub setup`.
92
+ To skip npx on every commit, install it globally instead: `npm install -g tracehub@0.5.5`, then `tracehub setup`.
93
93
 
94
94
  ### Git hooks
95
95
 
96
- Setup installs global Git hooks: it points the global `core.hooksPath` at `~/.config/tracehub/hooks`, which holds a dispatcher for every standard Git hook. Two of them run the CLI: the same Node and `cli.js` that ran setup, by absolute path, so a global install or `npm link` needs no network on commit. A setup run through npx installs hooks that run `npx --yes --prefer-offline tracehub@<version> hook …`, pinned to that published version. Every dispatcher then runs the hook you had before: from your previous global or inherited system hooks directory, or else the repository's own `.git/hooks`. Hook files, arguments, pre-push input, failure status and warnings are preserved.
96
+ Setup installs global Git hooks: it points the global `core.hooksPath` at `~/.config/tracehub/hooks`, which holds a dispatcher for every standard Git hook. Two of them run the CLI: the same Node and `cli.js` that ran setup, by absolute path, so a global install or `npm link` needs no network on commit. A setup run through npx installs hooks that run `npx --yes --prefer-offline --registry=https://registry.npmjs.org tracehub@<version> hook …`, pinned to that published version. They run npx from your home directory, so a repository's own `.npmrc` or `node_modules` never decides what runs. Every dispatcher then runs the hook you had before: from your previous global or inherited system hooks directory, or else the repository's own `.git/hooks`. Hook files, arguments, pre-push input, failure status and warnings are preserved.
97
97
 
98
98
  | hook | does |
99
99
  | --- | --- |
@@ -110,7 +110,7 @@ Setup installs global Git hooks: it points the global `core.hooksPath` at `~/.co
110
110
  ### Uninstall
111
111
 
112
112
  ```sh
113
- npx --yes tracehub@0.5.4 uninstall
113
+ npx --yes tracehub@0.5.5 uninstall
114
114
  ```
115
115
 
116
116
  Lists what it removes and asks first (default no); with nothing set up it says so and asks nothing. Then it removes the global Git hooks and restores your previous global `core.hooksPath` setting, deletes the permission rules (`consent.json`) and signs you out (`auth.json`). It asks before deleting the deny list and the current repository's `.git/tracehub` (its markers, including ones not uploaded yet). Other repositories keep their `.git/tracehub`; delete it by hand if you want. Before signing out it asks TraceHub to forget this machine's rules (see [Consent registry](#consent-registry)); when TraceHub can't be reached it says that TraceHub still lists them, and goes on. If the global hooks setting was changed by another tool since setup, uninstall leaves the hooks alone, still removes the rest, and exits 1.
@@ -166,11 +166,11 @@ TraceHub keeps a copy of your rules (`_consent/users/<your id>`).
166
166
 
167
167
  ## How it works
168
168
 
169
- 1. **Commit.** `prepare-commit-msg` finds the sessions of the commit (see Discovery). If the message has no `Assisted-by` trailer yet, it uses a new 16-hex trace id and adds the trailer once at least one session's marker is recorded; a commit whose sessions are all missing from this machine gets no trailer. For each session found it appends a marker to `.git/tracehub/markers.jsonl` (in the repository's common git directory, so a linked worktree's markers outlive the worktree): `{traceId, session, line, ts, context?, uploaded}`, where `line` is the number of complete lines the session file had and `context` the references of `TRACEHUB_CONTEXT`. Merge and squash commits are skipped.
169
+ 1. **Commit.** `prepare-commit-msg` finds the sessions of the commit (see Discovery). If the message has no `Assisted-by` trailer yet, it uses a new 16-hex trace id and adds the trailer once at least one session's marker is recorded; a commit whose sessions are all missing from this machine gets no trailer. For each session found it appends a marker to `.git/tracehub/markers.jsonl` (in the repository's common git directory, so a linked worktree's markers outlive the worktree): `{traceId, session, line, ts, context?, file, committer?, uploaded}`, where `line` is the number of complete lines the session file had, `context` the references of `TRACEHUB_CONTEXT`, `file` the session file it was found in, and `committer` that the session made the commit with a call of its own (see Discovery). The marker never leaves the machine. Merge and squash commits are skipped.
170
170
  2. **Amend, rebase, squash.** The message keeps its trailer, so the commit keeps its trace id. A new marker for the same trace id and session replaces the old one.
171
- 3. **Push.** `pre-push` reads Git's ref updates and uploads only the traces of commits being pushed. New branches exclude commits already known on that remote. Deletions upload nothing; an unavailable remote base leaves traces pending with a recovery warning. For each pending marker the CLI builds the trace (below), fetches its context conversations from their providers and `PUT`s it; each success is recorded before the next. A later push also retries the pending traces of earlier commits in its history. When the 15 s run out, the push says so and a detached `tracehub hook upload` goes on with the same traces for up to 10 minutes, writing to `.git/tracehub/upload.log`.
171
+ 3. **Push.** `pre-push` reads Git's ref updates and uploads only the traces of commits being pushed. New branches exclude commits already known on that remote. Deletions upload nothing; an unavailable remote base leaves traces pending with a recovery warning. For each pending marker the CLI builds the trace (below) from the marker's `file`, or the session's file wherever the push's environment keeps it when that one is gone, so a push from a plain terminal uploads what an agent with its own `CLAUDE_CONFIG_DIR` committed; fetches its context conversations from their providers and `PUT`s it; each success is recorded before the next. A later push also retries the pending traces of earlier commits in its history. When the 15 s run out, the push says so and a detached `tracehub hook upload` goes on with the same traces for up to 10 minutes, writing to `.git/tracehub/upload.log`.
172
172
  4. **Pull request.** The GitHub App receives the `pull_request` event, reads the trace ids from the commit messages, and writes a link at the bottom of the description, between `<!-- tracehub:start -->` and `<!-- tracehub:end -->`: an "Agent traces" badge, next to Rupic's "Track in Rupic" badge when there is one. A pull request with attached context gets the link too.
173
- 5. **Reading.** The badge links to `/pr/<owner>/<repo>/<number>`: the intent and effort at a glance (first prompt, wall-clock time, prompts, commits, agents), then one timeline of the context conversations and the sessions of its commits, each message clamped to three lines, subagent runs folded to one line. A trace is at `/t/<owner>/<repo>/<trace id>`, a commit's traces at `/c/<owner>/<repo>/<sha>`. Add `.json` to any of them for the data (sign-in cookie or `Authorization: Bearer <GitHub token>`). The pages are rendered when their data changes and served from the cache.
173
+ 5. **Reading.** The badge links to `/pr/<owner>/<repo>/<number>`: the intent and effort at a glance (first prompt, wall-clock time, prompts, commits, agents), then one timeline of the context conversations and the sessions of its commits, each message clamped to three lines, subagent runs folded to one line. A trace is at `/t/<owner>/<repo>/<trace id>`, a commit's traces at `/c/<owner>/<repo>/<sha>`. Add `.json` to any of them for the data (sign-in cookie or `Authorization: Bearer <token>` with the token `tracehub setup` keeps). The pages are rendered when their data changes and served from the cache.
174
174
  6. **Without a pull request.** A push prints a link per commit it marked, `/t/<owner>/<repo>/<trace id>`.
175
175
 
176
176
  ### What a trace holds
@@ -193,22 +193,26 @@ The upload replaces the trace of that commit and session, and the API rebuilds t
193
193
  The sessions of a commit, by precedence:
194
194
 
195
195
  1. `TRACEHUB_ID=<claude|codex|opencode>:<id>` in the environment (comma-separated for several).
196
- 2. Recently active sessions with an open agent tool call executing `git commit`. This preserves several sessions when several commit calls are active.
197
- 3. If no committing session is found, the sessions of the repository written to since the last commit (the last 24 hours in a repository without a commit). This fallback preserves sessions for commits made manually.
196
+ 2. The session the agent's own environment names. Claude Code gives every command it runs `CLAUDE_CODE_SESSION_ID`, Codex `CODEX_THREAD_ID`, so the hook of a commit an agent makes inherits the id of the session making it. Each one whose file is on this machine is attached:
197
+ - when it has the open `git commit` call, as the session that made the commit, wherever it ran (an app that runs its threads in a project's directory and commits with `cd <worktree> && git commit`);
198
+ - else, for Claude Code, when one of its subagents has the open call (a subagent's commands carry its parent's id): the parent when it ran in the repository, with the subagent as a run of its trace, else the subagent alone (as below). Of several subagents with an open call, those whose call names this checkout;
199
+ - else only when it ran in the repository, like discovery. A session elsewhere that commits nothing (a terminal that inherited the id) leaves the commit to the next rule.
200
+ 3. Recently active sessions with an open agent tool call executing `git commit`. This preserves several sessions when several commit calls are active.
201
+ 4. If no committing session is found, the sessions of the repository written to since the last commit (the last 24 hours in a repository without a commit). This fallback preserves sessions for commits made manually.
198
202
 
199
- A session belongs to the repository only when its working directory is inside the repository's checkout: discovery never attaches a session that ran elsewhere, for example a coordinator agent in `~/.nomos/coordinator` whose subagents commit in a worktree. A session named by `TRACEHUB_ID` that ran outside the repository (or one of its worktrees) shares nothing of its own: its trace holds only the subagent runs that changed files of the repository, without the parent's messages or title, and when no subagent changed any, nothing is uploaded and the marker is settled.
203
+ A session belongs to the repository only when its working directory is inside the repository's checkout: discovery never attaches a session that ran elsewhere, for example a coordinator agent in `~/.nomos/coordinator` whose subagents commit in a worktree. A session that ran outside the repository (or one of its worktrees), even one named by `TRACEHUB_ID`, shares nothing of its own: its trace holds only the subagent runs that changed files of the repository, without the parent's messages or title, and when no subagent changed any, nothing is uploaded and the marker is settled. The one exception is the session rule 2 found making the commit: it shares its own turns as a session in the repository would.
200
204
 
201
- Such a coordinator's subagents are found on their own. Claude Code files a subagent's transcript under its parent's project, and its lines carry the parent's `cwd`, so discovery also reads the subagent transcripts of the last 24 hours (and since the last commit) under `~/.claude/projects/*/*/subagents/` whose parent ran outside the repository, and tells by what each one did whether it worked in the checkout being committed (the worktree, when the commit is in one):
205
+ Such a coordinator's subagents are found on their own. Claude Code files a subagent's transcript under its parent's project, and its lines carry the parent's `cwd`, so discovery also reads the subagent transcripts of the last 24 hours (and since the last commit) under `~/.claude/projects/*/*/subagents/` (or `$CLAUDE_CONFIG_DIR/projects/*/*/subagents/`) whose parent ran outside the repository, and tells by what each one did whether it worked in the checkout being committed (the worktree, when the commit is in one):
202
206
 
203
207
  - for rule 2, an open `git commit` call whose command names the checkout (`cd <checkout> && git commit`, `git -C <checkout> commit`, `~/…` spellings included), or a plain `git commit` from a subagent whose own `cwd` is inside it (a worktree-isolated agent);
204
208
  - for rule 3, an edit of a file in the checkout since the last commit, or a `cwd` inside it.
205
209
 
206
210
  Such a subagent is attached as `claude:agent-<id>` and uploaded alone: the prompt its parent gave it as its first message, its text replies, its per-turn changes and its sourcemap, titled with the description from its `agent-<id>.meta.json`, redacted like any trace. Its parent's messages and title, and its sibling subagents that didn't work in the checkout, are never read into it. A subagent of a session inside the repository stays a run of that session's trace. Codex sub-threads are sessions of their own with their own `cwd`, so the usual rule finds them when they ran in the repository; an OpenCode task's session shares its parent's `directory` and is not found on its own.
207
211
 
208
- Where the sessions are:
212
+ Where the sessions are, read where the agent of the commit's environment writes them:
209
213
 
210
- - Claude Code: `~/.claude/projects/<encoded cwd>/<session id>.jsonl`. The cwd is encoded by replacing every character outside `[A-Za-z0-9-]` with `-`. The `cwd` of its first line that has one has to be inside the repository. Subagents are in `<session id>/subagents/agent-<id>.jsonl`, with an optional `agent-<id>.meta.json`; one found on its own is `claude:agent-<id>`, and `TRACEHUB_ID` can name it so too.
211
- - Codex: `~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl`. The first line (`session_meta`) has the `cwd`, which has to be inside the repository. A sub-thread names its parent in `parent_thread_id`.
214
+ - Claude Code: `~/.claude/projects/<encoded cwd>/<session id>.jsonl`, or `$CLAUDE_CONFIG_DIR/projects/…` when `CLAUDE_CONFIG_DIR` is set. Claude Code then writes nothing to `~/.claude`, so only that directory is read: an app that runs one Claude Code per account (T3 Code gives each provider instance its own) is read by the commits its agents make, and a commit from a plain terminal reads `~/.claude`. The cwd is encoded by replacing every character outside `[A-Za-z0-9-]` with `-`. The `cwd` of its first line that has one has to be inside the repository. Subagents are in `<session id>/subagents/agent-<id>.jsonl`, with an optional `agent-<id>.meta.json`; one found on its own is `claude:agent-<id>`, and `TRACEHUB_ID` can name it so too.
215
+ - Codex: `~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl`, or under `$CODEX_HOME/sessions` when `CODEX_HOME` is set. The first line (`session_meta`) has the `cwd`, which has to be inside the repository. A sub-thread names its parent in `parent_thread_id`.
212
216
  - OpenCode: the database `~/.local/share/opencode/opencode.db`. A session has the `directory` it was started in, which has to be inside the repository. The session a task started names its parent in `parent_id`. The CLI reads the database with `node:sqlite`, so it needs Node 22.13 or newer.
213
217
 
214
218
  ## Commands
@@ -381,7 +385,7 @@ Bucket keys: `<owner>/<repo>/traces/<trace id>/<session name>` (an uploaded sess
381
385
 
382
386
  A trace or context is shown to who uploaded it and to the repository's maintainers (GitHub write, maintain or admin access); everyone else sees nothing.
383
387
 
384
- The `PUT` routes and the pull request's `/check` route take `Authorization: Bearer <access token of the GitHub user>` with push access to the repository. The web app's pages (`/t`, `/c`, `/pr`, each with a `.json` twin) take the cookie of the browser sign-in or a bearer GitHub token, and send a signed-out browser to `/login`; `tracehub/README.md` has the page list and the JSON schemas.
388
+ The `PUT` routes and the pull request's `/check` route take `Authorization: Bearer <access token of the GitHub user>` with push access to the repository. The web app's pages (`/t`, `/c`, `/pr`, each with a `.json` twin) take the cookie of the browser sign-in or a bearer token GitHub issued to TraceHub's App, and send a signed-out browser to `/login`; `tracehub/README.md` has the page list and the JSON schemas.
385
389
 
386
390
  ### GitHub App (once)
387
391
 
@@ -430,7 +434,7 @@ Do not try it with the session you are working in: what is uploaded stays in the
430
434
 
431
435
  ```sh
432
436
  gh repo create assistant-ui/tracehub-playground --private --clone && cd tracehub-playground
433
- npx --yes tracehub@0.5.4 setup # allow this repository, install the hooks
437
+ npx --yes tracehub@0.5.5 setup # allow this repository, install the hooks
434
438
 
435
439
  # open a fresh agent session in this directory, ask it for something harmless
436
440
  export TRACEHUB_ID=claude:<throwaway session id>
@@ -448,6 +452,8 @@ unset TRACEHUB_ID
448
452
 
449
453
  ## Develop
450
454
 
455
+ Needs Node.js 26.13.0 (pinned in `.node-version`).
456
+
451
457
  Development on `main` is allowed; feature branches and pull requests are optional. Preserve other contributors' changes and validate before pushing. Use a separate checkout when the working tree contains unrelated edits.
452
458
 
453
459
  ```sh
@@ -455,7 +461,7 @@ npm run format:fix && npm run typecheck && npm test
455
461
  cd tracehub && npm test
456
462
  ```
457
463
 
458
- Tests are in `test/` and `tracehub/test/`, fixtures in `fixtures/`. The end-to-end tests run the built CLI against the real Tracehub API over an in-memory bucket (`test/support/fakeTracehub.ts`); nothing in the tests reads a real session.
464
+ Tests are in `test/` and `tracehub/test/`, fixtures in `fixtures/`, and run on Vitest; `npm run test:coverage` also checks the coverage thresholds in `vitest.config.ts`. The end-to-end tests run the built CLI against the real Tracehub API over an in-memory bucket (`test/support/fakeTracehub.ts`); nothing in the tests reads a real session. The CLI and the fake Tracehub run outside Vitest, so `npm test` compiles them to `dist-test` first. The test setup file clears the agent variables (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`, `TRACEHUB_ID`) a suite run by an agent inherits.
459
465
 
460
466
  The CLI is published to npm as [`tracehub`](https://www.npmjs.com/package/tracehub). `npm pack` builds a fresh `dist` (`prepack`) and ships only `dist`, `README.md` and `package.json`. A clone needs `npm run build` after pulling; `npm install` doesn't build.
461
467
 
@@ -37,7 +37,7 @@ function run(command, args, text) {
37
37
  // Never under the test runner, which must not touch the user's clipboard.
38
38
  export async function copyToClipboard(text) {
39
39
  if (process.env[ENV_TEST] !== undefined ||
40
- process.env["NODE_TEST_CONTEXT"] !== undefined)
40
+ process.env["VITEST"] !== undefined)
41
41
  return false;
42
42
  for (const [command, args] of candidates())
43
43
  if (await run(command, args, text))
@@ -37,22 +37,22 @@ 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
47
  const kept = traceIds(readFileSync(messageFile, "utf8")).at(-1);
48
48
  const id = kept ?? newTraceId();
49
- const missing = recordMarkers(stateDir(cwd), id, refs, new Date(), envContextRefs());
49
+ const missing = recordMarkers(stateDir(cwd), id, sessions, new Date(), envContextRefs());
50
50
  for (const ref of missing)
51
51
  warn(`session ${formatSessionRef(ref)} not found on this machine; no marker recorded`);
52
52
  if (kept)
53
53
  return;
54
54
  // A trailer without a marker would link to a trace nothing ever uploads.
55
- if (missing.length < refs.length)
55
+ if (missing.length < sessions.length)
56
56
  git(interpretTrailersArgs(target, id, messageFile), { cwd });
57
57
  else
58
58
  warn("no trace attached to this commit");
package/dist/cli/repo.js CHANGED
@@ -3,12 +3,15 @@ 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
5
  import { repositoryOfRemotes, sameTarget, targetOfUploadRemotes, } from "../client/uploadPolicy.js";
6
- import { pendingCommitCall } from "../local/commitBoundary.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);
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",
@@ -75,6 +75,16 @@ export const ENV = [
75
75
  value: "<claude|codex|opencode>:<id>",
76
76
  description: "attach this session to the commit",
77
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
+ },
78
88
  {
79
89
  name: ENV_CONTEXT,
80
90
  value: "<provider>:<id>",
package/dist/cli.js CHANGED
@@ -19,8 +19,15 @@ async function main() {
19
19
  const args = parseArgs(process.argv.slice(2));
20
20
  const name = args.positional[0];
21
21
  // What the Git hooks run; internal, so not in the usage.
22
- 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
+ }
23
29
  return cmdHook(args, process.cwd());
30
+ }
24
31
  if (name && Object.hasOwn(COMMAND_HANDLERS, name)) {
25
32
  await COMMAND_HANDLERS[name](args, process.cwd());
26
33
  return;
@@ -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);
@@ -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) {
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,10 @@ 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 } : {}),
33
37
  ...(typeof m.commit === "string" && /^[0-9a-f]{40}$/.test(m.commit)
34
38
  ? { commit: m.commit }
35
39
  : {}),
@@ -76,8 +80,9 @@ export function saveUploaded(stateDir, done) {
76
80
  export function recordMarkers(stateDir, traceId, sessions, now = new Date(), context = []) {
77
81
  const missing = [];
78
82
  mkdirSync(stateDir, { recursive: true });
79
- for (const ref of sessions) {
80
- 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);
81
86
  if (!file) {
82
87
  missing.push(ref);
83
88
  continue;
@@ -88,6 +93,8 @@ export function recordMarkers(stateDir, traceId, sessions, now = new Date(), con
88
93
  line: sessionLines(ref, file).length,
89
94
  ts: now.toISOString(),
90
95
  ...(context.length ? { context } : {}),
96
+ file,
97
+ ...(session.committer ? { committer: true } : {}),
91
98
  uploaded: false,
92
99
  };
93
100
  appendFileSync(markersFile(stateDir), `${JSON.stringify(marker)}\n`);
@@ -94,7 +94,8 @@ export function claudeCwd(file) {
94
94
  }
95
95
  return "";
96
96
  }
97
- // ~/.claude/projects/<encoded cwd>/<session id>.jsonl
97
+ // ~/.claude/projects/<encoded cwd>/<session id>.jsonl, or under
98
+ // $CLAUDE_CONFIG_DIR/projects.
98
99
  function listClaudeFiles(repoRoot) {
99
100
  const dir = join(claudeProjectsDir(), encodeClaudeCwd(repoRoot));
100
101
  return listDir(dir)
@@ -211,8 +212,7 @@ function dayKey(ms) {
211
212
  // ~/.codex/sessions/<yyyy>/<mm>/<dd>/rollout-<time>-<session id>.jsonl, for
212
213
  // the files written to since sinceMs. A session is filed under the day it
213
214
  // started, so the day before is walked too.
214
- export function* walkCodexFiles(sinceMs) {
215
- const base = codexSessionsDir();
215
+ export function* walkCodexFiles(sinceMs, base = codexSessionsDir()) {
216
216
  const firstDay = dayKey(Math.max(0, sinceMs - DAY_MS));
217
217
  for (const year of listDir(base)) {
218
218
  for (const month of listDir(join(base, year))) {
@@ -5,6 +5,13 @@ export const ENV_SESSION_ID = "TRACEHUB_ID";
5
5
  export const ENV_DISABLE = "TRACEHUB";
6
6
  // Context refs for every session of a commit: `<provider>:<id>[,…]`.
7
7
  export const ENV_CONTEXT = "TRACEHUB_CONTEXT";
8
+ // Set by the agents themselves: where they keep their sessions, and the
9
+ // session a command of theirs runs in (a Claude Code subagent's commands
10
+ // carry its parent's).
11
+ export const ENV_CLAUDE_CONFIG_DIR = "CLAUDE_CONFIG_DIR";
12
+ export const ENV_CODEX_HOME = "CODEX_HOME";
13
+ export const ENV_CLAUDE_SESSION = "CLAUDE_CODE_SESSION_ID";
14
+ export const ENV_CODEX_THREAD = "CODEX_THREAD_ID";
8
15
  export const ENV_TEST = "TRACEHUB_TEST";
9
16
  // Under ENV_TEST only: how long a push waits for its upload, in ms.
10
17
  export const ENV_TEST_PUSH_BUDGET = "TRACEHUB_TEST_PUSH_BUDGET_MS";
@@ -14,20 +21,26 @@ export const ENV_TEST_PUSH_BUDGET = "TRACEHUB_TEST_PUSH_BUDGET_MS";
14
21
  function override(name) {
15
22
  const value = process.env[name];
16
23
  if (value === undefined &&
17
- (process.env[ENV_TEST] !== undefined ||
18
- process.env["NODE_TEST_CONTEXT"] !== undefined)) {
19
- throw new Error(`${name} must be set while ${ENV_TEST} or NODE_TEST_CONTEXT is`);
24
+ (process.env[ENV_TEST] !== undefined || process.env["VITEST"] !== undefined)) {
25
+ throw new Error(`${name} must be set while ${ENV_TEST} or VITEST is`);
20
26
  }
21
27
  return value;
22
28
  }
23
29
  export function home() {
24
30
  return override("TRACEHUB_HOME") ?? homedir();
25
31
  }
32
+ // The directory an agent keeps its state in: the one its environment
33
+ // variable names, as the agent itself reads it, else its default. A Claude
34
+ // Code with CLAUDE_CONFIG_DIR set (an app running one per account) writes
35
+ // nothing to ~/.claude, so only its own directory is read.
36
+ function agentDir(variable, fallback) {
37
+ return process.env[variable] || join(home(), fallback);
38
+ }
26
39
  export function claudeProjectsDir() {
27
- return join(home(), ".claude", "projects");
40
+ return join(agentDir(ENV_CLAUDE_CONFIG_DIR, ".claude"), "projects");
28
41
  }
29
42
  export function codexSessionsDir() {
30
- return join(home(), ".codex", "sessions");
43
+ return join(agentDir(ENV_CODEX_HOME, ".codex"), "sessions");
31
44
  }
32
45
  // OpenCode keeps every session in one SQLite database.
33
46
  export function opencodeDb() {
@@ -55,7 +55,9 @@ export function listSubagents(ref, sessionFile) {
55
55
  return listClaudeSubagents(sessionFile);
56
56
  if (ref.agent === "opencode")
57
57
  return listOpencodeSubagents(ref.id);
58
- const files = [...walkCodexFiles(0)].map(({ file }) => ({
58
+ // The sessions directory the parent's file is in, <base>/yyyy/mm/dd/.
59
+ const base = dirname(dirname(dirname(dirname(sessionFile))));
60
+ const files = [...walkCodexFiles(0, base)].map(({ file }) => ({
59
61
  file,
60
62
  firstLine: firstLineOf(file),
61
63
  }));
@@ -18,7 +18,3 @@ export function parseSessionName(name) {
18
18
  export function sessionName(ref) {
19
19
  return `${ref.agent}-${ref.id}.jsonl`;
20
20
  }
21
- export function uniqueRefs(refs) {
22
- const byKey = new Map(refs.map((ref) => [formatSessionRef(ref), ref]));
23
- return [...byKey.values()];
24
- }
@@ -84,7 +84,9 @@ const DETECTORS = [
84
84
  return out;
85
85
  },
86
86
  },
87
- keepPrefix("url_credentials", /(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@"'`]+:)[^\s/@"'`]+(?=@)/gi),
87
+ // The password runs to the last `@` (it may hold `/` and `@`), unless it
88
+ // is a port and path (`host:3000/@user`).
89
+ keepPrefix("url_credentials", /(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@"'`]+:)(?!\d{1,5}[/?#])[^\s"'`]+(?=@)/gi),
88
90
  whole("pem_block", /-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g),
89
91
  whole("pem_block", /-----BEGIN [A-Z ]+-----[\s\S]*$/gm),
90
92
  whole("openai_key", /\bsk-[A-Za-z0-9_-]{8,}\b/g),
@@ -104,9 +106,10 @@ const DETECTORS = [
104
106
  keepPrefix("authorization_header", /(\bauthorization\s*[:=]\s*)(?:(?:bearer|basic|token)\s+)?\S+/gi),
105
107
  keepPrefix("bearer_token", /(\bBearer\s+)[A-Za-z0-9._~+/=-]{8,}/g),
106
108
  keepPrefix("basic_auth", /(\bBasic\s+)[A-Za-z0-9+/]{8,}={0,2}/g),
107
- keepPrefix("keyed_assignment", /(\b(?:(?:[A-Za-z0-9]+[_-])+(?:key|token|secret|password|passwd|pwd)|password|passwd|pwd|secret|token|credentials?)\s*[=:]\s*["']?)[^\s"'&,;]+/gi),
108
- keepPrefix("keyed_assignment", /(\b(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD)\s*[=:]\s*["']?)[^\s"'&,;]+/g),
109
- keepPrefix("json_secret_assignment", /(\b(?:[a-z0-9_\-]*(?:password|passwd|secret|token|api_key|apikey|private_key|credentials?))["']\s*:\s*["'])[^"'\r\n]+/gi),
109
+ // A quoted value runs to its closing quote, spaces, commas and all.
110
+ keepPrefix("keyed_assignment", /(\b(?:(?:[A-Za-z0-9]+[_-])+(?:key|token|secret|password|passwd|pwd)|password|passwd|pwd|secret|token|credentials?)\s*[=:]\s*["']?)(?:(?<=")(?:\\.|[^"\\\r\n])+|(?<=')(?:\\.|[^'\\\r\n])+|[^\s"'&,;]+)/gi),
111
+ keepPrefix("keyed_assignment", /(\b(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD)\s*[=:]\s*["']?)(?:(?<=")(?:\\.|[^"\\\r\n])+|(?<=')(?:\\.|[^'\\\r\n])+|[^\s"'&,;]+)/g),
112
+ keepPrefix("json_secret_assignment", /(\b(?:[a-z0-9_\-]*(?:password|passwd|secret|token|api_key|apikey|private_key|credentials?))["']\s*:\s*["'])(?:(?<=")(?:\\.|[^"\\\r\n])+|(?<=')(?:\\.|[^'\\\r\n])+)/gi),
110
113
  whole("long_hex", /\b[0-9a-fA-F]{64,}\b/g),
111
114
  {
112
115
  type: "keyed_hex",
@@ -222,14 +222,18 @@ export function buildTrace(input, opts = {}) {
222
222
  // subagents work in a worktree) shares nothing of its own: only the
223
223
  // subagent runs that changed the repository's files.
224
224
  // A subagent found by what it did in the repository counts as inside it,
225
- // whatever cwd its lines carry over from its parent.
226
- const outside = !sidechain && !ownCheckout(cwd);
225
+ // whatever cwd its lines carry over from its parent, and so does a
226
+ // session that made the commit itself (`cd <checkout> && git commit`).
227
+ const outside = !sidechain && !input.committer && !ownCheckout(cwd);
227
228
  if (outside) {
228
229
  turns = turns.map((turn) => ({
229
230
  at: turn.at,
230
231
  messages: [],
231
232
  changes: [],
232
- runs: turn.runs.map((run) => changed(run.turns) ? run : { label: run.label, turns: [] }),
233
+ runs: turn.runs.map((run) =>
234
+ // An unrelated run keeps its place (turn paths count runs), not
235
+ // its label: the label is the coordinator's own description.
236
+ changed(run.turns) ? run : { label: "", turns: [] }),
233
237
  }));
234
238
  ctx.written = ctx.written.filter((w) => w.turn.includes("."));
235
239
  if (!turns.some((turn) => turn.runs.some((run) => run.turns.length)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tracehub",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Attach coding-agent sessions (Claude Code, Codex, OpenCode) to git commits and pull requests, redacted.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -19,15 +19,18 @@
19
19
  "typecheck": "tsc --noEmit -p tsconfig.test.json",
20
20
  "format": "oxfmt --check",
21
21
  "format:fix": "oxfmt",
22
- "test": "tsc -p tsconfig.test.json && node --test --import ./dist-test/test/support/testEnv.js dist-test/test/*.test.js",
22
+ "test": "tsc -p tsconfig.test.json && vitest run",
23
+ "test:coverage": "tsc -p tsconfig.test.json && vitest run --coverage --coverage.reporter=text --coverage.reporter=html --coverage.reporter=json-summary",
23
24
  "prepack": "npm run build",
24
25
  "docs:install": "pnpm --dir docs install",
25
26
  "docs:dev": "pnpm --dir docs dev"
26
27
  },
27
28
  "devDependencies": {
28
29
  "@types/node": "^26.6.6",
30
+ "@vitest/coverage-v8": "^5.0.5",
29
31
  "oxfmt": "^0.74.0",
30
- "typescript": "^7.0.2"
32
+ "typescript": "^7.0.2",
33
+ "vitest": "^5.0.5"
31
34
  },
32
35
  "repository": {
33
36
  "type": "git",
@@ -42,5 +45,15 @@
42
45
  },
43
46
  "dependencies": {
44
47
  "@clack/prompts": "^1.8.1"
48
+ },
49
+ "allowScripts": {
50
+ "fsevents@2.3.3": true
51
+ },
52
+ "devEngines": {
53
+ "packageManager": {
54
+ "name": "npm",
55
+ "version": ">=11.17.0",
56
+ "onFail": "error"
57
+ }
45
58
  }
46
59
  }