tracehub 0.5.4 → 0.5.6
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 +28 -20
- package/dist/cli/clipboard.js +1 -1
- package/dist/cli/commands/hook.js +5 -5
- package/dist/cli/repo.js +75 -9
- package/dist/cli/usage.js +11 -1
- package/dist/cli.js +8 -1
- package/dist/client/upload.js +27 -6
- package/dist/git/hooks.js +5 -1
- package/dist/git/markers.js +10 -3
- package/dist/local/discover.js +3 -3
- package/dist/local/paths.js +18 -5
- package/dist/local/subagents.js +3 -1
- package/dist/protocol/sessionRef.js +0 -4
- package/dist/redact/redact.js +7 -4
- package/dist/trace/build.js +77 -15
- package/package.json +16 -3
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ A commit made while an agent session is active gets an `Assisted-by: https://tra
|
|
|
11
11
|
A trace is everything that produced one commit, in one JSON document:
|
|
12
12
|
|
|
13
13
|
1. **Context conversations.** The conversations that asked for the work: a nomOS thread, a Slack thread, an issue, pasted prompts. A **provider** (a local command registered with `tracehub providers add`) returns all messages of a conversation by its id. A session names its conversation with a `tracehub-context: <provider>:<id>` line in its first message (an agent's brief to a subagent), or the commit with `TRACEHUB_CONTEXT=<provider>:<id>`; `tracehub context add --pr <n>` attaches one to a pull request by hand. See [Context conversations](#context-conversations).
|
|
14
|
-
2. **Sessions.** For each agent session attached to the commit: the user's messages and the agent's text replies, grouped into turns (a turn starts at a user prompt). Each turn lists the files it changed (`path`, lines added, lines removed). A subagent the turn launched is a **run** nested under it, with its own turns: the prompt the parent gave it, its replies, its changes. Tool calls, tool results, thinking, token metrics and local paths never leave the machine.
|
|
14
|
+
2. **Sessions.** For each agent session attached to the commit, the part of it that made the commit (see [What a trace holds](#what-a-trace-holds)): the user's messages and the agent's text replies, grouped into turns (a turn starts at a user prompt). Each turn lists the files it changed (`path`, lines added, lines removed). A subagent the turn launched is a **run** nested under it, with its own turns: the prompt the parent gave it, its replies, its changes. Tool calls, tool results, thinking, token metrics and local paths never leave the machine.
|
|
15
15
|
3. **A sourcemap** (optional). For each line the commit adds, the turn that last wrote it, blame-style.
|
|
16
16
|
|
|
17
17
|
Everything is computed on the developer's machine, redacted there, checked again by the API (detectors and the sensitivity model), and shown only to the uploader and the repository's maintainers.
|
|
@@ -68,7 +68,7 @@ Everything is computed on the developer's machine, redacted there, checked again
|
|
|
68
68
|
`{ "<path>": { "<line hash>": "<turn path>" } }`, for the lines the commit adds (`git show` of the commit against its first parent).
|
|
69
69
|
|
|
70
70
|
- The line hash is FNV-1a 64 of the line with surrounding whitespace removed, as 16 hex characters; blank lines are left out. Hashes, not text, so the map says nothing the diff doesn't.
|
|
71
|
-
- The turn path is the turn's index in the
|
|
71
|
+
- The turn path is the turn's index in the trace, `"3"`; a subagent's turn adds the run and its turn, `"3.0.1"` (turn 3, its first run, that run's second turn), so the deepest turn that wrote a line is named, with the path up to the user's prompt.
|
|
72
72
|
- A line is attributed to the last edit, by time, whose new text contains it: Claude Code's `Write`, `Edit` and `MultiEdit`, Codex's `apply_patch` and OpenCode's `write`, `edit` and `patch`, parsed from the transcript up to the commit. Edits from before the session's previous commits count too, since a line written in turn 2 can be committed in turn 5.
|
|
73
73
|
- Why tool inputs and not snapshots of the working tree: the hooks only run at commit and push, so there is no snapshot of the tree at each turn boundary to diff, while every edit tool records exactly what it wrote and when. Lines no edit tool wrote (a formatter, a shell command, a hand edit) stay unattributed.
|
|
74
74
|
- A trace page's **Line map** lists, per file, the prompts that wrote the commit's lines and how many.
|
|
@@ -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.
|
|
81
|
+
npx --yes tracehub@0.5.6 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.
|
|
92
|
+
To skip npx on every commit, install it globally instead: `npm install -g tracehub@0.5.6`, 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.
|
|
113
|
+
npx --yes tracehub@0.5.6 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,16 +166,18 @@ 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
|
|
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 <
|
|
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
|
|
177
177
|
|
|
178
|
-
The trace of a session at a commit, built from the session's file up to the marker's line:
|
|
178
|
+
The trace of a session at a commit, built from the session's file up to the marker's line and scoped to that commit, so a session that commits many times (a coordinator working through several pull requests) shows each commit its own part:
|
|
179
|
+
|
|
180
|
+
- **Scope.** A turn is kept when it or one of its runs wrote a line the commit adds (by the sourcemap), or when it has messages since the session's previous commit in the repository; the commit's turn is always kept. A run is kept when it wrote one of the commit's lines; when no line is attributed, the runs active since the previous commit are kept instead. A turn kept only for a run keeps its prompt and its messages since the previous commit. A session's first commit has no previous one, so every turn before it is in scope; its runs still follow the rule above.
|
|
179
181
|
|
|
180
182
|
- **Turns.** A turn starts at each user prompt; its messages are the user's (the prompt, then any steering) and the agent's text replies. The replies after the commit that finish the commit's turn are included; the next prompt is not.
|
|
181
183
|
- **Changes.** Each turn lists the files its edit tools changed, as paths in the repository with lines added and removed. Edits outside the repository are left out.
|
|
@@ -193,22 +195,26 @@ The upload replaces the trace of that commit and session, and the API rebuilds t
|
|
|
193
195
|
The sessions of a commit, by precedence:
|
|
194
196
|
|
|
195
197
|
1. `TRACEHUB_ID=<claude|codex|opencode>:<id>` in the environment (comma-separated for several).
|
|
196
|
-
2.
|
|
197
|
-
|
|
198
|
+
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:
|
|
199
|
+
- 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`);
|
|
200
|
+
- 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;
|
|
201
|
+
- 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.
|
|
202
|
+
3. Recently active sessions with an open agent tool call executing `git commit`. This preserves several sessions when several commit calls are active.
|
|
203
|
+
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
204
|
|
|
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
|
|
205
|
+
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
206
|
|
|
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):
|
|
207
|
+
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
208
|
|
|
203
209
|
- 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
210
|
- for rule 3, an edit of a file in the checkout since the last commit, or a `cwd` inside it.
|
|
205
211
|
|
|
206
212
|
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
213
|
|
|
208
|
-
Where the sessions are:
|
|
214
|
+
Where the sessions are, read where the agent of the commit's environment writes them:
|
|
209
215
|
|
|
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
|
|
216
|
+
- 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.
|
|
217
|
+
- 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
218
|
- 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
219
|
|
|
214
220
|
## Commands
|
|
@@ -381,7 +387,7 @@ Bucket keys: `<owner>/<repo>/traces/<trace id>/<session name>` (an uploaded sess
|
|
|
381
387
|
|
|
382
388
|
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
389
|
|
|
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
|
|
390
|
+
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
391
|
|
|
386
392
|
### GitHub App (once)
|
|
387
393
|
|
|
@@ -430,7 +436,7 @@ Do not try it with the session you are working in: what is uploaded stays in the
|
|
|
430
436
|
|
|
431
437
|
```sh
|
|
432
438
|
gh repo create assistant-ui/tracehub-playground --private --clone && cd tracehub-playground
|
|
433
|
-
npx --yes tracehub@0.5.
|
|
439
|
+
npx --yes tracehub@0.5.6 setup # allow this repository, install the hooks
|
|
434
440
|
|
|
435
441
|
# open a fresh agent session in this directory, ask it for something harmless
|
|
436
442
|
export TRACEHUB_ID=claude:<throwaway session id>
|
|
@@ -448,6 +454,8 @@ unset TRACEHUB_ID
|
|
|
448
454
|
|
|
449
455
|
## Develop
|
|
450
456
|
|
|
457
|
+
Needs Node.js 26.13.0 (pinned in `.node-version`).
|
|
458
|
+
|
|
451
459
|
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
460
|
|
|
453
461
|
```sh
|
|
@@ -455,7 +463,7 @@ npm run format:fix && npm run typecheck && npm test
|
|
|
455
463
|
cd tracehub && npm test
|
|
456
464
|
```
|
|
457
465
|
|
|
458
|
-
Tests are in `test/` and `tracehub/test/`, fixtures in `fixtures
|
|
466
|
+
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
467
|
|
|
460
468
|
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
469
|
|
package/dist/cli/clipboard.js
CHANGED
|
@@ -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["
|
|
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 {
|
|
41
|
-
if (!
|
|
40
|
+
const { sessions } = resolveSessions(cwd, root);
|
|
41
|
+
if (!sessions.length)
|
|
42
42
|
return;
|
|
43
43
|
if (consent === undefined) {
|
|
44
|
-
warn(`${
|
|
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,
|
|
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 <
|
|
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 {
|
|
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
|
|
33
|
-
//
|
|
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 {
|
|
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
|
|
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 {
|
|
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;
|
package/dist/client/upload.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { addedLines, commitOfTrace } from "../git/git.js";
|
|
2
|
-
import { pendingMarkers, saveUploaded, } from "../git/markers.js";
|
|
3
|
+
import { pendingMarkers, readMarkers, saveUploaded, } from "../git/markers.js";
|
|
3
4
|
import { findSessionFile, isClaudeSubagent } from "../local/discover.js";
|
|
4
5
|
import { sessionLines } from "../local/lines.js";
|
|
5
6
|
import { fetchAll, readProviders } from "../local/providers.js";
|
|
@@ -18,12 +19,30 @@ function subagentsOf(ref, file) {
|
|
|
18
19
|
lines: sessionLines({ agent: ref.agent, id: subagent.id }, subagent.file),
|
|
19
20
|
}));
|
|
20
21
|
}
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
|
|
24
|
-
|
|
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
|
+
}
|
|
29
|
+
// When the session of a marker made its previous commit in the repository.
|
|
30
|
+
function previousCommit(all, marker) {
|
|
31
|
+
const earlier = all
|
|
32
|
+
.filter((m) => m.session === marker.session)
|
|
33
|
+
.map((m) => Date.parse(m.ts))
|
|
34
|
+
.filter((ms) => ms < Date.parse(marker.ts));
|
|
35
|
+
return earlier.length
|
|
36
|
+
? new Date(Math.max(...earlier)).toISOString()
|
|
37
|
+
: undefined;
|
|
38
|
+
}
|
|
39
|
+
// Uploads the trace of each pending marker: the session's part of the
|
|
40
|
+
// turns up to the commit, the sourcemap of the lines the commit adds, and
|
|
41
|
+
// the context conversations its marker and briefs name. `contextAllowed`
|
|
42
|
+
// is the repository's permission rule: without it no provider runs.
|
|
25
43
|
export async function uploadMarkers(client, target, stateDir, cwd, root, markers, opts = {}, contextAllowed = false) {
|
|
26
44
|
const pending = pendingMarkers(markers);
|
|
45
|
+
const all = readMarkers(stateDir);
|
|
27
46
|
const result = {
|
|
28
47
|
uploaded: [],
|
|
29
48
|
skipped: [],
|
|
@@ -45,7 +64,7 @@ export async function uploadMarkers(client, target, stateDir, cwd, root, markers
|
|
|
45
64
|
};
|
|
46
65
|
for (const marker of pending) {
|
|
47
66
|
const ref = parseSessionRef(marker.session);
|
|
48
|
-
const file = ref ?
|
|
67
|
+
const file = ref ? sessionFileOf(marker, ref) : undefined;
|
|
49
68
|
if (!ref || !file) {
|
|
50
69
|
if (ref && !missing.has(marker.session))
|
|
51
70
|
result.missing.push(ref);
|
|
@@ -60,12 +79,14 @@ export async function uploadMarkers(client, target, stateDir, cwd, root, markers
|
|
|
60
79
|
lines: sessionLines(ref, file),
|
|
61
80
|
cut: marker.line,
|
|
62
81
|
committedAt: marker.ts,
|
|
82
|
+
since: previousCommit(all, marker),
|
|
63
83
|
subagents: subagentsOf(ref, file),
|
|
64
84
|
root,
|
|
65
85
|
added: sha ? addedLines(cwd, sha) : new Map(),
|
|
66
86
|
...(isClaudeSubagent(ref)
|
|
67
87
|
? { subagent: { label: claudeSubagentLabel(file) } }
|
|
68
88
|
: {}),
|
|
89
|
+
...(marker.committer ? { committer: true } : {}),
|
|
69
90
|
providers: Object.keys(providers),
|
|
70
91
|
}, opts);
|
|
71
92
|
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`,
|
package/dist/git/markers.js
CHANGED
|
@@ -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
|
|
80
|
-
const
|
|
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`);
|
package/dist/local/discover.js
CHANGED
|
@@ -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))) {
|
package/dist/local/paths.js
CHANGED
|
@@ -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
|
-
|
|
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(
|
|
40
|
+
return join(agentDir(ENV_CLAUDE_CONFIG_DIR, ".claude"), "projects");
|
|
28
41
|
}
|
|
29
42
|
export function codexSessionsDir() {
|
|
30
|
-
return join(
|
|
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() {
|
package/dist/local/subagents.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
}
|
package/dist/redact/redact.js
CHANGED
|
@@ -84,7 +84,9 @@ const DETECTORS = [
|
|
|
84
84
|
return out;
|
|
85
85
|
},
|
|
86
86
|
},
|
|
87
|
-
|
|
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
|
-
|
|
108
|
-
keepPrefix("keyed_assignment", /(\b(?:
|
|
109
|
-
keepPrefix("
|
|
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",
|
package/dist/trace/build.js
CHANGED
|
@@ -115,7 +115,13 @@ function turnsOf(events, cwd, prefix, ctx, children) {
|
|
|
115
115
|
runs: [],
|
|
116
116
|
});
|
|
117
117
|
}
|
|
118
|
-
|
|
118
|
+
const run = { label: child.label, turns: runTurns };
|
|
119
|
+
const times = child.transcript.events
|
|
120
|
+
.map((e) => Date.parse(e.ts))
|
|
121
|
+
.filter((ms) => !Number.isNaN(ms));
|
|
122
|
+
if (times.length)
|
|
123
|
+
ctx.ends.set(run, Math.max(...times));
|
|
124
|
+
turn.runs.push(run);
|
|
119
125
|
}
|
|
120
126
|
return turns;
|
|
121
127
|
}
|
|
@@ -144,6 +150,50 @@ function sourcemapOf(written, added) {
|
|
|
144
150
|
}
|
|
145
151
|
return map;
|
|
146
152
|
}
|
|
153
|
+
// The part of a session that made one commit, so a long session that
|
|
154
|
+
// commits many times shows each commit its own work: the turns and runs
|
|
155
|
+
// that wrote the commit's lines, and the turns with messages since the
|
|
156
|
+
// session's previous commit. A turn kept only for a run keeps its prompt
|
|
157
|
+
// and its messages since that commit. Without attributed lines, the runs
|
|
158
|
+
// active since that commit stay. The sourcemap's turn paths follow the
|
|
159
|
+
// kept turns.
|
|
160
|
+
function scopeToCommit(turns, sourcemap, sinceMs, ends) {
|
|
161
|
+
const hits = new Set(Object.values(sourcemap).flatMap((lines) => Object.values(lines)));
|
|
162
|
+
const paths = new Map();
|
|
163
|
+
const kept = [];
|
|
164
|
+
turns.forEach((turn, i) => {
|
|
165
|
+
const own = hits.has(`${i}`);
|
|
166
|
+
const recent = i === turns.length - 1 ||
|
|
167
|
+
[turn.at, ...turn.messages.map((m) => m.at)].some((at) => Date.parse(at) >= sinceMs);
|
|
168
|
+
const runs = [];
|
|
169
|
+
turn.runs.forEach((run, j) => {
|
|
170
|
+
const prefix = `${i}.${j}.`;
|
|
171
|
+
const wrote = [...hits].filter((h) => h.startsWith(prefix));
|
|
172
|
+
if (!wrote.length &&
|
|
173
|
+
(hits.size > 0 || !((ends.get(run) ?? -Infinity) > sinceMs)))
|
|
174
|
+
return;
|
|
175
|
+
for (const h of wrote)
|
|
176
|
+
paths.set(h, `${kept.length}.${runs.length}.${h.slice(prefix.length)}`);
|
|
177
|
+
runs.push(run);
|
|
178
|
+
});
|
|
179
|
+
if (!own && !recent && !runs.length)
|
|
180
|
+
return;
|
|
181
|
+
if (own)
|
|
182
|
+
paths.set(`${i}`, `${kept.length}`);
|
|
183
|
+
kept.push({
|
|
184
|
+
at: turn.at,
|
|
185
|
+
messages: own
|
|
186
|
+
? turn.messages
|
|
187
|
+
: turn.messages.filter((m, k) => (k === 0 && m.role === "user") || Date.parse(m.at) >= sinceMs),
|
|
188
|
+
changes: own || recent ? turn.changes : [],
|
|
189
|
+
runs,
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
const scoped = {};
|
|
193
|
+
for (const [path, lines] of Object.entries(sourcemap))
|
|
194
|
+
scoped[path] = Object.fromEntries(Object.entries(lines).map(([hash, turn]) => [hash, paths.get(turn)]));
|
|
195
|
+
return { turns: kept, sourcemap: scoped };
|
|
196
|
+
}
|
|
147
197
|
// The first user message of the session and of each run: the briefs, where
|
|
148
198
|
// a coordinator names the conversation the work is for.
|
|
149
199
|
function briefsOf(turns) {
|
|
@@ -153,15 +203,15 @@ function briefsOf(turns) {
|
|
|
153
203
|
...turns.flatMap((t) => t.runs.flatMap((r) => briefsOf(r.turns))),
|
|
154
204
|
];
|
|
155
205
|
}
|
|
156
|
-
// What leaves the machine for one session at one commit: the turns up to
|
|
157
|
-
// the commit (and the agent's replies that finish the commit's turn), the
|
|
158
|
-
// changes of each turn and the sourcemap of the commit's lines, redacted.
|
|
159
206
|
// Whether any of the turns, or their runs, changed a file.
|
|
160
207
|
function changed(turns) {
|
|
161
208
|
return turns.some((t) => t.changes.length > 0 || t.runs.some((r) => changed(r.turns)));
|
|
162
209
|
}
|
|
163
|
-
//
|
|
164
|
-
//
|
|
210
|
+
// What leaves the machine for one session at one commit: its part of the
|
|
211
|
+
// turns up to the commit (and the agent's replies that finish the commit's
|
|
212
|
+
// turn), the changes of each turn and the sourcemap of the commit's lines,
|
|
213
|
+
// redacted. Undefined when there is nothing to share: a session that ran
|
|
214
|
+
// outside the repository and whose subagents changed none of its files.
|
|
165
215
|
export function buildTrace(input, opts = {}) {
|
|
166
216
|
const { agent, id, lines, cut, committedAt } = input;
|
|
167
217
|
const cutoffMs = Date.parse(committedAt);
|
|
@@ -215,21 +265,25 @@ export function buildTrace(input, opts = {}) {
|
|
|
215
265
|
}
|
|
216
266
|
};
|
|
217
267
|
const roots = (dir) => [input.root, realOrSelf(input.root), nearest(dir)].filter((r) => !!r);
|
|
218
|
-
const ctx = { roots, written: [] };
|
|
268
|
+
const ctx = { roots, written: [], ends: new Map() };
|
|
219
269
|
const cwd = before.cwd || input.root;
|
|
220
270
|
let turns = turnsOf(events, cwd, "", ctx, children.filter((c) => c.transcript.events.length));
|
|
221
271
|
// A session that ran outside the repository (a coordinator whose
|
|
222
272
|
// subagents work in a worktree) shares nothing of its own: only the
|
|
223
273
|
// subagent runs that changed the repository's files.
|
|
224
274
|
// 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
|
-
|
|
275
|
+
// whatever cwd its lines carry over from its parent, and so does a
|
|
276
|
+
// session that made the commit itself (`cd <checkout> && git commit`).
|
|
277
|
+
const outside = !sidechain && !input.committer && !ownCheckout(cwd);
|
|
227
278
|
if (outside) {
|
|
228
279
|
turns = turns.map((turn) => ({
|
|
229
280
|
at: turn.at,
|
|
230
281
|
messages: [],
|
|
231
282
|
changes: [],
|
|
232
|
-
runs: turn.runs.map((run) =>
|
|
283
|
+
runs: turn.runs.map((run) =>
|
|
284
|
+
// An unrelated run keeps its place (turn paths count runs), not
|
|
285
|
+
// its label: the label is the coordinator's own description.
|
|
286
|
+
changed(run.turns) ? run : { label: "", turns: [] }),
|
|
233
287
|
}));
|
|
234
288
|
ctx.written = ctx.written.filter((w) => w.turn.includes("."));
|
|
235
289
|
if (!turns.some((turn) => turn.runs.some((run) => run.turns.length)))
|
|
@@ -240,17 +294,25 @@ export function buildTrace(input, opts = {}) {
|
|
|
240
294
|
: agent === "claude" && !outside
|
|
241
295
|
? sessionTitle(lines.slice(0, cut))
|
|
242
296
|
: undefined;
|
|
297
|
+
const since = Date.parse(input.since ?? "");
|
|
298
|
+
const scoped = scopeToCommit(turns, sourcemapOf(ctx.written, input.added), Number.isNaN(since) ? -Infinity : since, ctx.ends);
|
|
299
|
+
// The session's first message names its conversation even when its turn
|
|
300
|
+
// is out of scope; a run's brief counts only for the runs in scope.
|
|
301
|
+
const first = turns[0]?.messages.find((m) => m.role === "user");
|
|
302
|
+
const briefs = [
|
|
303
|
+
...(first ? [first.text] : []),
|
|
304
|
+
...scoped.turns.flatMap((t) => t.runs.flatMap((r) => briefsOf(r.turns))),
|
|
305
|
+
];
|
|
306
|
+
const refs = [
|
|
307
|
+
...new Set(briefs.flatMap((t) => contextRefsIn(t, input.providers ?? []))),
|
|
308
|
+
];
|
|
243
309
|
const upload = {
|
|
244
310
|
agent,
|
|
245
311
|
...(title ? { title } : {}),
|
|
246
312
|
...(whole.model ? { model: whole.model } : {}),
|
|
247
313
|
committedAt,
|
|
248
|
-
|
|
249
|
-
sourcemap: sourcemapOf(ctx.written, input.added),
|
|
314
|
+
...scoped,
|
|
250
315
|
};
|
|
251
|
-
const refs = [
|
|
252
|
-
...new Set(briefsOf(turns).flatMap((t) => contextRefsIn(t, input.providers ?? []))),
|
|
253
|
-
];
|
|
254
316
|
const redacted = redactValue(upload, opts);
|
|
255
317
|
return { upload: redacted.value, findings: redacted.findings, refs };
|
|
256
318
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tracehub",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.6",
|
|
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 &&
|
|
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
|
}
|