tracehub 0.5.8 → 0.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -84
- package/dist/cli/args.js +15 -0
- package/dist/cli/commands/backfill.js +24 -58
- package/dist/cli/commands/context.js +11 -30
- package/dist/cli/commands/hook.js +24 -33
- package/dist/cli/commands/providers.js +0 -5
- package/dist/cli/commands/setup.js +0 -5
- package/dist/cli/commands/uninstall.js +0 -5
- package/dist/cli/remote.js +11 -4
- package/dist/cli/repo.js +8 -8
- package/dist/cli/ui.js +1 -1
- package/dist/cli/usage.js +5 -0
- package/dist/cli.js +9 -2
- package/dist/client/github.js +14 -17
- package/dist/client/tracehub.js +6 -3
- package/dist/client/uploadPolicy.js +2 -10
- package/dist/git/git.js +1 -1
- package/dist/git/trailers.js +8 -21
- package/dist/local/backfill.js +3 -3
- package/dist/local/discover.js +7 -20
- package/dist/local/files.js +23 -0
- package/dist/local/providers.js +2 -3
- package/dist/local/subagents.js +5 -8
- package/dist/protocol/trailers.js +26 -0
- package/dist/redact/deny.js +2 -2
- package/package.json +13 -18
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Tracehub CLI
|
|
2
2
|
|
|
3
|
-
Tracehub has
|
|
3
|
+
Tracehub has three parts: the **Tracehub CLI** (this package, the `tracehub` command), the **Tracehub Worker** (the API and web pages, with `.json` twins) and the **Tracehub GitHub App**. One Cloudflare Worker serves the API on `https://assisted-by.aui.dev` and pages on `https://tracehub.aui.dev`, reading storage on every authorized request with no page cache between uploads and reads.
|
|
4
4
|
|
|
5
5
|
Attach the conversations behind coding-agent work (Claude Code, Codex, OpenCode) to git commits: the conversation that asked for the work, the user's and the agent's messages, the files each turn changed, and which turn wrote each line of the diff.
|
|
6
6
|
|
|
@@ -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.9 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,7 +89,7 @@ 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.9`, then `tracehub setup`.
|
|
93
93
|
|
|
94
94
|
### Git hooks
|
|
95
95
|
|
|
@@ -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.9 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.
|
|
@@ -146,7 +146,7 @@ An allowed repository means: the traces of the agent sessions that ran in it (th
|
|
|
146
146
|
|
|
147
147
|
The rules are kept in `~/.config/tracehub/consent.json` under normalized GitHub keys: `github.com/owner/*` for an organization, `github.com/owner/repo` for a repository. Every clone and worktree shares them; filesystem paths never identify a rule. A repository's rule wins over its organization's.
|
|
148
148
|
|
|
149
|
-
-
|
|
149
|
+
- A rule for all GitHub repositories (`github.com/*`) allows no uploads; setup removes it from the file. Add an organization or repository rule instead. A repository refusal blocks that repository until it is revoked in setup.
|
|
150
150
|
- Rules are separate from upload eligibility and the hooks. A rule does not authorize non-GitHub origins or bypass the current **assistant-ui-only** ownership policy, GitHub App installation, repository access, or sign-in checks. A rule for another organization is stored but uploads nothing in this release. It does not make traces public.
|
|
151
151
|
|
|
152
152
|
| rule for the repository | a commit with an active session |
|
|
@@ -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?, file
|
|
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.
|
|
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?, commit?, 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, `committer` that the session made the commit with a call of its own, and `commit` the SHA of a backfilled commit whose message does not name the trace (see Discovery). The marker never leaves the machine. Merge and squash commits are skipped.
|
|
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. A squash merge on GitHub runs no hook and keeps no trailer by itself; whoever merges writes the body. One line, `Assisted-by: https://tracehub.aui.dev/pr/<owner>/<repo>/<number>`, stands for every trace of the pull request's commits: the commit's page and its check resolve it through the pull request.
|
|
171
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
|
|
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 its context conversations and the sessions of its commits, listed in a rail and read one at a time, each in time order with the commits it made; each message is clamped to three lines and subagent runs fold 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). Each authorized request renders the page from storage.
|
|
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
|
|
@@ -342,6 +342,7 @@ The agent's own file is never changed. The `pre-push` hook reports what it maske
|
|
|
342
342
|
| `jwt` | `eyJ….….…` |
|
|
343
343
|
| `authorization_header`, `bearer_token`, `basic_auth` | what follows `Authorization:`, `Bearer`, `Basic` |
|
|
344
344
|
| `keyed_assignment` | the value of `<name>_key=`, `token:`, `password=`, `SECRET=` and the like |
|
|
345
|
+
| `json_secret_assignment` | the quoted value of a JSON property whose name contains `password`, `secret`, `token`, `api_key`, `apikey`, `private_key` or `credential` |
|
|
345
346
|
| `long_hex` | 64 or more hex characters |
|
|
346
347
|
| `keyed_hex` | 32 to 63 hex characters with `token`, `secret`, `key`, `password`, `bearer`, `auth` or `api` in the 40 characters before them; a bare git sha is left alone |
|
|
347
348
|
| `high_entropy` | 32 or more characters of `[A-Za-z0-9_\-+/=.]` with two digits or more, two character classes or more, and an entropy above 3.8 bits per character; not hex, a UUID, a hostname or a path |
|
|
@@ -355,81 +356,11 @@ The agent's own file is never changed. The `pre-push` hook reports what it maske
|
|
|
355
356
|
|
|
356
357
|
Messages are asked in windows of 4000 characters; a window that is sensitive is asked again message by message. The redacted messages leave the Tracehub API for TypeSafe's API. Without `TYPESAFE_API_KEY` the Tracehub API skips steps 2 to 4.
|
|
357
358
|
|
|
358
|
-
### Translation
|
|
359
|
-
|
|
360
|
-
Pages show a message written in another language in English, with "Translated from <language> · Show original" to read it as written. The stored trace and context keep the original; the `.json` twins carry both (`translation: { from, text }` beside `text`).
|
|
361
|
-
|
|
362
|
-
- Which messages: a count of the prose's letters by script (code, links, paths and identifiers left out). A message mostly in Han, kana, Hangul, Cyrillic, Arabic, Hebrew, Greek, Thai or Devanagari is translated; English never reaches the model. Latin-script languages (Spanish, German…) are not detected.
|
|
363
|
-
- How: Cloudflare Workers AI (`@cf/qwen/qwen3.8-27b`), called by the Tracehub API Worker on the messages it already stores, after the redaction and the sensitivity check above; withheld messages are never sent. Code blocks, inline code, URLs, paths and identifiers are replaced by tokens before the model sees the text and put back after; a translation that loses one is dropped.
|
|
364
|
-
- When: as a page's data is read for rendering (after each upload, and for traces stored before translation existed, on their next render). Each text is translated once and cached in the bucket under `_translations/<sha256 of model and text>`; a changed message is translated again.
|
|
365
|
-
- Limits: messages over 8000 characters are not translated; at most 100 model calls per read, 4 at a time.
|
|
366
|
-
|
|
367
359
|
### Deny list
|
|
368
360
|
|
|
369
361
|
Literals in `~/.config/tracehub/deny.txt`, one per line, are always redacted. Edit the file by hand (keep it mode `0600`); lines under 6 characters are ignored. The file holds the literals themselves, so treat it like the secrets.
|
|
370
362
|
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
`tracehub/` is a Cloudflare Worker over an R2 bucket; `tracehub/README.md` says how to deploy it. GitHub signs the users in and says who may push to a repository.
|
|
374
|
-
|
|
375
|
-
| route | does |
|
|
376
|
-
| --- | --- |
|
|
377
|
-
| `PUT /repos/:owner/:repo/traces/:trace/sessions/:name` | stores a session's trace at a commit, replacing the one there |
|
|
378
|
-
| `PUT /repos/:owner/:repo/pulls/:number/context` | attaches context conversations to a pull request (`{context: [...]}`), merged into the uploader's by conversation and message id |
|
|
379
|
-
| `DELETE /repos/:owner/:repo/pulls/:number/context?ref=<provider>:<id>` | detaches the conversations (`ref` repeated) from every uploader's document; answers `{removed}`, 404 when none was attached |
|
|
380
|
-
| `PUT /repos/:owner/:repo/commits/:sha/traces/:trace` | links an uploaded trace to a commit whose message does not name it (a backfill); only who uploaded one of its sessions may; answers `{sha, traceId, pulls}`, 404 without a session, 503 when the GitHub App is not configured |
|
|
381
|
-
| `POST /repos/:owner/:repo/pulls/:number/check` | recomputes the pull request's head check; answers `{submitted: true}` (bearer, push access), 503 when the GitHub App is not configured |
|
|
382
|
-
| `PUT /consent` | registers a machine's permission rules for the signed-in user; `rules: []` forgets the machine |
|
|
383
|
-
| `GET /login`, `/logout`, `/api/auth/callback` | browser sign-in (through the web app) |
|
|
384
|
-
| `POST /github/webhook` | the GitHub App's webhook |
|
|
385
|
-
| `GET /healthz` | `{ok: true}` |
|
|
386
|
-
|
|
387
|
-
Bucket keys: `<owner>/<repo>/traces/<trace id>/<session name>` (an uploaded session, JSON), `<owner>/<repo>/commits/<trace id>.json` (the trace document) and `<owner>/<repo>/context/<number>/<user id>` (one uploader's context conversations for a pull request, JSON).
|
|
388
|
-
|
|
389
|
-
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.
|
|
390
|
-
|
|
391
|
-
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.
|
|
392
|
-
|
|
393
|
-
### GitHub App (once)
|
|
394
|
-
|
|
395
|
-
The App of the deployed Tracehub API exists; the Tracehub API reads its key from the bucket, `_config/github-app.json` (`{appId, pem, webhookSecret}`).
|
|
396
|
-
|
|
397
|
-
For another deployment, create an App in the GitHub organization:
|
|
398
|
-
|
|
399
|
-
- Permissions: Pull requests: write, Checks: write (the TraceHub traces check), Contents: read, Metadata: read, Merge queues: read. Events: Pull request, Push, Merge group, Check run, Check suite. Webhook `<tracehub>/github/webhook`.
|
|
400
|
-
- Callback URL `<tracehub>/api/auth/callback`, for the browser sign-in.
|
|
401
|
-
- Device flow enabled, for the sign-in of `tracehub setup`.
|
|
402
|
-
- A client secret, for the browser sign-in.
|
|
403
|
-
|
|
404
|
-
Install it on the repositories. An existing App installation must accept the new Merge queues: read permission. Set its client id as `GITHUB_CLIENT_ID` in `tracehub/wrangler.jsonc` and as `TRACEHUB_GITHUB_CLIENT_ID` for the CLI, and store its values as secrets; the three of the key win over the bucket:
|
|
405
|
-
|
|
406
|
-
```sh
|
|
407
|
-
cd tracehub
|
|
408
|
-
npx wrangler secret put GITHUB_CLIENT_SECRET
|
|
409
|
-
printf %s "<app id>" | npx wrangler secret put GITHUB_APP_ID
|
|
410
|
-
npx wrangler secret put GITHUB_APP_PRIVATE_KEY < <app>.private-key.pem
|
|
411
|
-
printf %s "<webhook secret>" | npx wrangler secret put GITHUB_WEBHOOK_SECRET
|
|
412
|
-
```
|
|
413
|
-
|
|
414
|
-
### The TraceHub traces check
|
|
415
|
-
|
|
416
|
-
The App reports a check run named **TraceHub traces** on the head of every pull request of `assistant-ui` repositories, and on commits that have a known trace (an uploaded session marked by a trace id the commit message names, or linked to the commit by `tracehub backfill`).
|
|
417
|
-
|
|
418
|
-
- First party: the pull request's author is an organization member or collaborator, or has write access. Bots (`[bot]` logins, `type: Bot`) and outside contributors are exempt.
|
|
419
|
-
- **Success** when at least one of the pull request's current commits has a known trace with content: a session that shows at least one prompt or reply with text, in its turns or a subagent's. A session whose messages are all empty or withheld is empty, and a trace of only empty sessions does not count. The output lists each trace with content with a link to its TraceHub page, its agents and its number of sessions with content; the details link goes to the pull request's TraceHub page.
|
|
420
|
-
- **Success** also when no commit has one but the pull request has context fetched from a provider attached (`tracehub context add --pr <n> <provider>:<id>`): at least one conversation with at least one message with text, from any uploader; withheld messages do not count. Conversations pasted from a file (`--from`, ref `manual:…`) stay on the page but never pass the check alone. The output says it passed on the attached context, with the number of conversations and a link to the pull request's TraceHub page, which the details link also opens.
|
|
421
|
-
- **Skipped** when every pull request headed at the commit is exempt and has neither a trace nor context. GitHub treats this as passing for a required check.
|
|
422
|
-
- **Failure** when a first-party pull request has neither. The title says what was found: `No trace found`, `<n> traces found, all empty` (the summary lists them), or `Only pasted context found`. The output links to the public npm package and says how to fix it: run `npx --yes tracehub setup`, then push a new commit made in an agent session (Claude Code, Codex, OpenCode), or, for commits made before that, run `npx --yes tracehub backfill --pr <n>` (see Backfill). A pull request without agent work passes once the conversation that asked for it is attached from its provider with `npx --yes tracehub context add --pr <n> <provider>:<id>`. No comment is posted.
|
|
423
|
-
- Any other commit gets a success when it has a known trace with content itself: on a push, and when an upload attaches a trace to a commit TraceHub has seen.
|
|
424
|
-
- A trace uploaded later updates the check on the pull request heads and commits the index knows for the trace, so a failure turns into a success.
|
|
425
|
-
- Attaching context (`PUT …/pulls/<n>/context`) or detaching it (`DELETE`) runs the check on the pull request's head again right away: a failure turns into a success, and detaching the last conversation can turn it back into a failure.
|
|
426
|
-
- An unchanged check is not written again; a changed one updates the same check run.
|
|
427
|
-
- **Re-run** on GitHub (`check_run` or `check_suite` with action `rerequested`) lists the pull request's commits again and writes a new check run on the head, changed or not.
|
|
428
|
-
- R2 calls it turns away for a moment (10058 too many reads or writes of one object, 10001, 10043) are tried again a few times with a short backoff, so a busy object does not drop the job that updates the check.
|
|
429
|
-
- On `merge_group` with action `checks_requested`, the App refreshes the pull request named by the queue ref and mirrors its stored head check onto the merge-group commit, including its conclusion, title, summary and details link. Queue branch pushes are ignored. A missing stored output is logged and no queue check is written.
|
|
430
|
-
- `POST /repos/:owner/:repo/pulls/:number/check` recomputes the head check for a pull request opened before the App handled it. Push access is required.
|
|
431
|
-
|
|
432
|
-
To require the check, add **TraceHub traces** from the **TraceHub App** as a required status check in the branch's ruleset. The `merge_group` mirror covers the merge queue, including squash merges.
|
|
363
|
+
For Worker routes, GitHub App setup, check behavior and translation, see [the Worker documentation](tracehub/README.md).
|
|
433
364
|
|
|
434
365
|
## Trying it end to end
|
|
435
366
|
|
|
@@ -437,7 +368,7 @@ Do not try it with the session you are working in: what is uploaded stays in the
|
|
|
437
368
|
|
|
438
369
|
```sh
|
|
439
370
|
gh repo create assistant-ui/tracehub-playground --private --clone && cd tracehub-playground
|
|
440
|
-
npx --yes tracehub@0.5.
|
|
371
|
+
npx --yes tracehub@0.5.9 setup # allow this repository, install the hooks
|
|
441
372
|
|
|
442
373
|
# open a fresh agent session in this directory, ask it for something harmless
|
|
443
374
|
export TRACEHUB_ID=claude:<throwaway session id>
|
|
@@ -460,13 +391,14 @@ Needs Node.js 26.13.0 (pinned in `.node-version`).
|
|
|
460
391
|
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.
|
|
461
392
|
|
|
462
393
|
```sh
|
|
463
|
-
|
|
464
|
-
|
|
394
|
+
pnpm install
|
|
395
|
+
pnpm run format:fix && pnpm run typecheck && pnpm test
|
|
396
|
+
cd tracehub && pnpm test
|
|
465
397
|
```
|
|
466
398
|
|
|
467
|
-
Tests are in `test/` and `tracehub/test/`, fixtures in `fixtures/`, and run on Vitest; `
|
|
399
|
+
Tests are in `test/` and `tracehub/test/`, fixtures in `fixtures/`, and run on Vitest; `pnpm 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 `pnpm 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.
|
|
468
400
|
|
|
469
|
-
The CLI is published to npm as [`tracehub`](https://www.npmjs.com/package/tracehub). `
|
|
401
|
+
The CLI is published to npm as [`tracehub`](https://www.npmjs.com/package/tracehub). `pnpm pack` builds a fresh `dist` (`prepack`) and ships only `dist`, `README.md` and `package.json`. A clone needs `pnpm run build` after pulling; `pnpm install` doesn't build.
|
|
470
402
|
|
|
471
403
|
A release is a tag:
|
|
472
404
|
|
package/dist/cli/args.js
CHANGED
|
@@ -7,6 +7,10 @@ export function parseArgs(argv) {
|
|
|
7
7
|
const arg = argv[i];
|
|
8
8
|
if (arg === "--")
|
|
9
9
|
return { positional, flags, rest: argv.slice(i + 1) };
|
|
10
|
+
if (arg === "-h") {
|
|
11
|
+
flags["help"] = true;
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
10
14
|
if (!arg.startsWith("--")) {
|
|
11
15
|
positional.push(arg);
|
|
12
16
|
continue;
|
|
@@ -26,3 +30,14 @@ export function flagValue(args, name) {
|
|
|
26
30
|
const value = args.flags[name];
|
|
27
31
|
return typeof value === "string" ? value : undefined;
|
|
28
32
|
}
|
|
33
|
+
export function prOf(args, required = false) {
|
|
34
|
+
const raw = flagValue(args, "pr");
|
|
35
|
+
if (raw === undefined && !required)
|
|
36
|
+
return undefined;
|
|
37
|
+
const pr = Number(raw);
|
|
38
|
+
if (!Number.isSafeInteger(pr) || pr < 1)
|
|
39
|
+
throw new Error(required
|
|
40
|
+
? '--pr <number> is required; see "tracehub context --help"'
|
|
41
|
+
: "--pr <number> must be a pull request number");
|
|
42
|
+
return pr;
|
|
43
|
+
}
|
|
@@ -1,36 +1,26 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
-
import { basename, dirname
|
|
3
|
-
import { freshAuth } from "../../client/auth.js";
|
|
2
|
+
import { basename, dirname } from "node:path";
|
|
4
3
|
import { pullCommits } from "../../client/github.js";
|
|
5
|
-
import { traceUploaded,
|
|
4
|
+
import { traceUploaded, webUrl } from "../../client/tracehub.js";
|
|
6
5
|
import { uploadMarkers } from "../../client/upload.js";
|
|
7
6
|
import { sameTarget, targetOfUploadRemotes, UPLOAD_POLICY_ERROR, } from "../../client/uploadPolicy.js";
|
|
8
7
|
import { addedLines, git, remoteUrls, repoRoot, tryGit, } from "../../git/git.js";
|
|
9
8
|
import { appendMarkers, readMarkers, } from "../../git/markers.js";
|
|
10
|
-
import { newTraceId
|
|
9
|
+
import { newTraceId } from "../../git/trailers.js";
|
|
10
|
+
import { traceIds } from "../../protocol/trailers.js";
|
|
11
11
|
import { candidateOf, chosen, commitTimeMs, rankMatches, } from "../../local/backfill.js";
|
|
12
12
|
import { claudeIdFromFile, ranInside, walkCodexFiles, } from "../../local/discover.js";
|
|
13
|
-
import {
|
|
13
|
+
import { firstLineOf, walkClaudeTranscripts } from "../../local/files.js";
|
|
14
14
|
import { completeLines } from "../../local/lines.js";
|
|
15
15
|
import { listOpencodeSessions, opencodeLines } from "../../local/opencode.js";
|
|
16
16
|
import { claudeProjectsDir, home, opencodeDb } from "../../local/paths.js";
|
|
17
17
|
import { formatSessionRef, parseSessionRef, } from "../../protocol/sessionRef.js";
|
|
18
18
|
import { codexSessionMeta } from "../../transcript/parseCodex.js";
|
|
19
|
-
import { flagValue } from "../args.js";
|
|
19
|
+
import { flagValue, prOf } from "../args.js";
|
|
20
20
|
import { out, warn } from "../io.js";
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import { commandUsage } from "../usage.js";
|
|
21
|
+
import { signedInClient, redactOptions, reportUpload } from "../remote.js";
|
|
22
|
+
import { requireConsent, stateDir, uploadTargetFor } from "../repo.js";
|
|
24
23
|
const HOUR_MS = 3600_000;
|
|
25
|
-
function prOf(args) {
|
|
26
|
-
const raw = flagValue(args, "pr");
|
|
27
|
-
if (raw === undefined)
|
|
28
|
-
return undefined;
|
|
29
|
-
const pr = Number(raw);
|
|
30
|
-
if (!Number.isSafeInteger(pr) || pr < 1)
|
|
31
|
-
throw new Error("--pr <number> must be a pull request number");
|
|
32
|
-
return pr;
|
|
33
|
-
}
|
|
34
24
|
// The commit as git has it; undefined when this clone does not have it.
|
|
35
25
|
function commitFacts(cwd, sha) {
|
|
36
26
|
const head = tryGit(["show", "-s", "--format=%H%x00%P%x00%s%x00%at%x00%ct", sha], { cwd });
|
|
@@ -112,35 +102,19 @@ function candidates(sinceMs, hints) {
|
|
|
112
102
|
return "";
|
|
113
103
|
}
|
|
114
104
|
};
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
continue;
|
|
127
|
-
found.push(candidateOf({ agent: "claude", id }, path, completeLines(text)));
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
const dir = join(path, "subagents");
|
|
131
|
-
for (const sub of listDir(dir)) {
|
|
132
|
-
if (!/^agent-[A-Za-z0-9_-]+\.jsonl$/.test(sub))
|
|
133
|
-
continue;
|
|
134
|
-
const file = join(dir, sub);
|
|
135
|
-
const entry = fileEntry(file);
|
|
136
|
-
if (!entry || entry.mtimeMs < sinceMs)
|
|
137
|
-
continue;
|
|
138
|
-
const text = read(file);
|
|
139
|
-
if (!mentions(text))
|
|
140
|
-
continue;
|
|
141
|
-
found.push(candidateOf({ agent: "claude", id: basename(sub, ".jsonl") }, file, completeLines(text), { sidechain: true, parent: `claude:${name}` }));
|
|
105
|
+
for (const entry of walkClaudeTranscripts(claudeProjectsDir())) {
|
|
106
|
+
const id = entry.parent ? entry.id : claudeIdFromFile(entry.file);
|
|
107
|
+
if (!id || entry.mtimeMs < sinceMs)
|
|
108
|
+
continue;
|
|
109
|
+
const text = read(entry.file);
|
|
110
|
+
if (!mentions(text))
|
|
111
|
+
continue;
|
|
112
|
+
found.push(candidateOf({ agent: "claude", id }, entry.file, completeLines(text), entry.parent
|
|
113
|
+
? {
|
|
114
|
+
sidechain: true,
|
|
115
|
+
parent: `claude:${basename(entry.parent, ".jsonl")}`,
|
|
142
116
|
}
|
|
143
|
-
|
|
117
|
+
: {}));
|
|
144
118
|
}
|
|
145
119
|
for (const { file } of walkCodexFiles(sinceMs)) {
|
|
146
120
|
const meta = codexSessionMeta(firstLineOf(file));
|
|
@@ -189,12 +163,9 @@ async function backfill(args, cwd) {
|
|
|
189
163
|
throw new Error(`--session: "${s}" is not <claude|codex|opencode>:<id>`);
|
|
190
164
|
return formatSessionRef(ref);
|
|
191
165
|
});
|
|
192
|
-
if (!dryRun
|
|
193
|
-
|
|
194
|
-
const
|
|
195
|
-
if (!stored)
|
|
196
|
-
throw new Error('not signed in; run "tracehub setup"');
|
|
197
|
-
const auth = await freshAuth(stored);
|
|
166
|
+
if (!dryRun)
|
|
167
|
+
requireConsent(cwd, target);
|
|
168
|
+
const { client, auth } = await signedInClient();
|
|
198
169
|
// The commits and their messages, and the pull request's head branch.
|
|
199
170
|
let branch;
|
|
200
171
|
let listed;
|
|
@@ -293,7 +264,6 @@ async function backfill(args, cwd) {
|
|
|
293
264
|
return;
|
|
294
265
|
}
|
|
295
266
|
appendMarkers(dir, markers);
|
|
296
|
-
const client = clientFor(auth);
|
|
297
267
|
const result = await uploadMarkers(client, target, dir, cwd, root, markers, redactOptions(), true);
|
|
298
268
|
reportUpload(result, target, out);
|
|
299
269
|
const linked = new Map();
|
|
@@ -306,15 +276,11 @@ async function backfill(args, cwd) {
|
|
|
306
276
|
if (pr && linked.size) {
|
|
307
277
|
await client.checkPull(target, pr);
|
|
308
278
|
out(`asked TraceHub to check ${target.owner}/${target.repo}#${pr} again`);
|
|
309
|
-
out(`${
|
|
279
|
+
out(`${webUrl()}/pr/${target.owner}/${target.repo}/${pr}`);
|
|
310
280
|
}
|
|
311
281
|
if (result.failed)
|
|
312
282
|
throw new Error(`upload incomplete: ${result.failed.error}`);
|
|
313
283
|
}
|
|
314
284
|
export async function cmdBackfill(args, cwd) {
|
|
315
|
-
if (args.flags["help"] || args.flags["h"]) {
|
|
316
|
-
out(commandUsage("backfill"));
|
|
317
|
-
return;
|
|
318
|
-
}
|
|
319
285
|
await backfill(args, cwd);
|
|
320
286
|
}
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
|
-
import {
|
|
3
|
-
import { tracehubUrl } from "../../client/tracehub.js";
|
|
2
|
+
import { webUrl } from "../../client/tracehub.js";
|
|
4
3
|
import { UPLOAD_POLICY_ERROR } from "../../client/uploadPolicy.js";
|
|
5
4
|
import { fetchContext, manualConversations } from "../../local/providers.js";
|
|
6
5
|
import { mergeConversations, parseContextRef, } from "../../protocol/context.js";
|
|
7
6
|
import { formatFindings, redactValue } from "../../redact/redact.js";
|
|
8
|
-
import { flagValue } from "../args.js";
|
|
7
|
+
import { flagValue, prOf } from "../args.js";
|
|
9
8
|
import { out, warn } from "../io.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { commandUsage } from "../usage.js";
|
|
9
|
+
import { signedInClient, redactOptions } from "../remote.js";
|
|
10
|
+
import { requireConsent, uploadTargetFor } from "../repo.js";
|
|
13
11
|
// stdin read as a stream: a pipe can be non-blocking, which readFileSync(0)
|
|
14
12
|
// answers with EAGAIN.
|
|
15
13
|
async function readStdin() {
|
|
@@ -18,12 +16,6 @@ async function readStdin() {
|
|
|
18
16
|
chunks.push(chunk);
|
|
19
17
|
return Buffer.concat(chunks).toString("utf8");
|
|
20
18
|
}
|
|
21
|
-
function prOf(args) {
|
|
22
|
-
const pr = Number(flagValue(args, "pr"));
|
|
23
|
-
if (!Number.isSafeInteger(pr) || pr < 1)
|
|
24
|
-
throw new Error('--pr <number> is required; see "tracehub context --help"');
|
|
25
|
-
return pr;
|
|
26
|
-
}
|
|
27
19
|
// The conversations to attach: from their providers or the file, merged,
|
|
28
20
|
// redacted.
|
|
29
21
|
async function conversationsOf(args, allowed) {
|
|
@@ -47,13 +39,12 @@ async function conversationsOf(args, allowed) {
|
|
|
47
39
|
return mergeConversations(lists);
|
|
48
40
|
}
|
|
49
41
|
async function add(args, cwd) {
|
|
50
|
-
const pr = prOf(args);
|
|
42
|
+
const pr = prOf(args, true);
|
|
51
43
|
const target = uploadTargetFor(cwd);
|
|
52
44
|
if (!target)
|
|
53
45
|
throw new Error(UPLOAD_POLICY_ERROR);
|
|
54
46
|
// The rule comes first: no provider runs for a repository without one.
|
|
55
|
-
|
|
56
|
-
throw new Error(`no permission rule allows uploads for ${target.owner}/${target.repo}; run "tracehub setup"`);
|
|
47
|
+
requireConsent(cwd, target);
|
|
57
48
|
const redacted = redactValue(await conversationsOf(args, true), redactOptions());
|
|
58
49
|
const context = redacted.value;
|
|
59
50
|
if (redacted.findings.length)
|
|
@@ -65,21 +56,18 @@ async function add(args, cwd) {
|
|
|
65
56
|
out(JSON.stringify(context, null, 2));
|
|
66
57
|
return;
|
|
67
58
|
}
|
|
68
|
-
const
|
|
69
|
-
if (!stored)
|
|
70
|
-
throw new Error('not signed in; run "tracehub setup"');
|
|
71
|
-
const client = clientFor(await freshAuth(stored));
|
|
59
|
+
const { client } = await signedInClient();
|
|
72
60
|
const result = await client.putContext(target, pr, context);
|
|
73
61
|
if (result.withheld)
|
|
74
62
|
warn(`tracehub withheld ${result.withheld} message(s) that look sensitive`);
|
|
75
63
|
out(`attached ${context.length} conversation(s), ${count} message(s), to ${where}`);
|
|
76
|
-
out(`${
|
|
64
|
+
out(`${webUrl()}/pr/${target.owner}/${target.repo}/${pr}`);
|
|
77
65
|
}
|
|
78
66
|
// Detaches conversations from the pull request: the uploader's or, for a
|
|
79
67
|
// maintainer, anyone's. Nothing is fetched or uploaded, so no permission
|
|
80
68
|
// rule is needed; the API checks push access as it does for add.
|
|
81
69
|
async function remove(args, cwd) {
|
|
82
|
-
const pr = prOf(args);
|
|
70
|
+
const pr = prOf(args, true);
|
|
83
71
|
const refs = [...new Set(args.positional.slice(2))];
|
|
84
72
|
if (!refs.length)
|
|
85
73
|
throw new Error("name a conversation to remove (<provider>:<id>)");
|
|
@@ -90,23 +78,16 @@ async function remove(args, cwd) {
|
|
|
90
78
|
if (!target)
|
|
91
79
|
throw new Error(UPLOAD_POLICY_ERROR);
|
|
92
80
|
const where = `${target.owner}/${target.repo}#${pr}`;
|
|
93
|
-
const
|
|
94
|
-
if (!stored)
|
|
95
|
-
throw new Error('not signed in; run "tracehub setup"');
|
|
96
|
-
const client = clientFor(await freshAuth(stored));
|
|
81
|
+
const { client } = await signedInClient();
|
|
97
82
|
const { removed } = await client.deleteContext(target, pr, refs);
|
|
98
83
|
for (const ref of refs)
|
|
99
84
|
if (!removed.includes(ref))
|
|
100
85
|
warn(`${ref} is not attached to ${where}`);
|
|
101
86
|
out(`removed ${removed.length} conversation(s) from ${where}`);
|
|
102
|
-
out(`${
|
|
87
|
+
out(`${webUrl()}/pr/${target.owner}/${target.repo}/${pr}`);
|
|
103
88
|
}
|
|
104
89
|
export async function cmdContext(args, cwd) {
|
|
105
90
|
const sub = args.positional[1];
|
|
106
|
-
if (args.flags["help"] || args.flags["h"] || !sub) {
|
|
107
|
-
out(commandUsage("context"));
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
91
|
if (sub === "add")
|
|
111
92
|
return add(args, cwd);
|
|
112
93
|
if (sub === "remove")
|
|
@@ -4,20 +4,21 @@ import { join } from "node:path";
|
|
|
4
4
|
import { freshAuth } from "../../client/auth.js";
|
|
5
5
|
import { readConsent } from "../../client/consent.js";
|
|
6
6
|
import { registerConsent, registrationPending } from "../../client/registry.js";
|
|
7
|
-
import { tracehubUrl } from "../../client/tracehub.js";
|
|
7
|
+
import { tracehubUrl, webUrl } from "../../client/tracehub.js";
|
|
8
8
|
import { consentFile } from "../../local/paths.js";
|
|
9
9
|
import { firstLine } from "../../client/errors.js";
|
|
10
10
|
import { uploadMarkers } from "../../client/upload.js";
|
|
11
11
|
import { UPLOAD_OWNER, UPLOAD_POLICY_ERROR, } from "../../client/uploadPolicy.js";
|
|
12
12
|
import { git, pushedTraceIds, repoRoot, tracesInPushedHistory, } from "../../git/git.js";
|
|
13
13
|
import { pendingMarkers, readMarkers, recordMarkers, } from "../../git/markers.js";
|
|
14
|
-
import { interpretTrailersArgs, newTraceId, shouldSkipCommit,
|
|
14
|
+
import { interpretTrailersArgs, hooksDisabled, newTraceId, shouldSkipCommit, } from "../../git/trailers.js";
|
|
15
|
+
import { traceIds } from "../../protocol/trailers.js";
|
|
15
16
|
import { formatContextRef, parseContextRef } from "../../protocol/context.js";
|
|
16
17
|
import { formatSessionRef } from "../../protocol/sessionRef.js";
|
|
17
18
|
import { ENV_CONTEXT, ENV_SESSION_ID } from "../../local/paths.js";
|
|
18
19
|
import { warn } from "../io.js";
|
|
19
20
|
import { BACKGROUND_BUDGET_MS, clientFor, commitCount, pushBudgetMs, ranOutOfTime, reportUpload, redactOptions, usableAuth, } from "../remote.js";
|
|
20
|
-
import { consentFor,
|
|
21
|
+
import { consentFor, pushTargetFor, resolveSessions, stateDir, uploadTargetFor, } from "../repo.js";
|
|
21
22
|
// The trailer names the commit's sessions on tracehub, so a message that
|
|
22
23
|
// already carries one (amend, rebase, cherry-pick, a squash folding earlier
|
|
23
24
|
// messages) keeps it, and the markers recorded under it stay with the commit.
|
|
@@ -53,7 +54,7 @@ function hookPrepareCommitMsg(args, cwd) {
|
|
|
53
54
|
return;
|
|
54
55
|
// A trailer without a marker would link to a trace nothing ever uploads.
|
|
55
56
|
if (missing.length < sessions.length)
|
|
56
|
-
git(interpretTrailersArgs(target, id, messageFile), { cwd });
|
|
57
|
+
git(interpretTrailersArgs(target, id, messageFile, webUrl()), { cwd });
|
|
57
58
|
else
|
|
58
59
|
warn("no trace attached to this commit");
|
|
59
60
|
}
|
|
@@ -87,7 +88,6 @@ async function hookPrePush(args, cwd) {
|
|
|
87
88
|
warn(UPLOAD_POLICY_ERROR);
|
|
88
89
|
return;
|
|
89
90
|
}
|
|
90
|
-
const { target } = push;
|
|
91
91
|
const dir = stateDir(cwd);
|
|
92
92
|
const input = process.stdin.isTTY ? "" : readFileSync(0, "utf8");
|
|
93
93
|
if (!input.trim()) {
|
|
@@ -116,23 +116,7 @@ async function hookPrePush(args, cwd) {
|
|
|
116
116
|
}
|
|
117
117
|
return;
|
|
118
118
|
}
|
|
119
|
-
|
|
120
|
-
const auth = await freshAuth(stored);
|
|
121
|
-
await retryRegistration(auth.accessToken);
|
|
122
|
-
const client = clientFor(auth, pushBudgetMs());
|
|
123
|
-
await client.verifyPush(push);
|
|
124
|
-
const result = await uploadMarkers(client, target, dir, cwd, repoRoot(cwd) ?? cwd, markers, redactOptions(), consentFor(cwd) === true);
|
|
125
|
-
// A big session can take longer than a push waits. The rest goes on in
|
|
126
|
-
// the background, so a commit whose branch is never pushed again (a
|
|
127
|
-
// squash-merged pull request) still gets its trace.
|
|
128
|
-
const log = ranOutOfTime(result)
|
|
129
|
-
? continueInBackground(cwd, dir, pushedUrl, result.skipped)
|
|
130
|
-
: undefined;
|
|
131
|
-
reportUpload(result, target, warn, log);
|
|
132
|
-
}
|
|
133
|
-
catch (err) {
|
|
134
|
-
warn(`upload failed, left pending for the next push: ${firstLine(err)}`);
|
|
135
|
-
}
|
|
119
|
+
await uploadPush(cwd, dir, push, markers, stored, pushBudgetMs(), pushedUrl);
|
|
136
120
|
}
|
|
137
121
|
const UPLOAD_LOG = "upload.log";
|
|
138
122
|
// Starts `tracehub hook upload` for the traces of these markers, detached,
|
|
@@ -164,7 +148,6 @@ async function hookUpload(args, cwd) {
|
|
|
164
148
|
warn(UPLOAD_POLICY_ERROR);
|
|
165
149
|
return;
|
|
166
150
|
}
|
|
167
|
-
const { target } = push;
|
|
168
151
|
const dir = stateDir(cwd);
|
|
169
152
|
const markers = readMarkers(dir).filter((marker) => ids.includes(marker.traceId));
|
|
170
153
|
if (!pendingMarkers(markers).length)
|
|
@@ -174,16 +157,7 @@ async function hookUpload(args, cwd) {
|
|
|
174
157
|
warn("not signed in; the markers stay pending");
|
|
175
158
|
return;
|
|
176
159
|
}
|
|
177
|
-
|
|
178
|
-
const auth = await freshAuth(stored);
|
|
179
|
-
const client = clientFor(auth, BACKGROUND_BUDGET_MS);
|
|
180
|
-
await client.verifyPush(push);
|
|
181
|
-
const result = await uploadMarkers(client, target, dir, cwd, repoRoot(cwd) ?? cwd, markers, redactOptions(), consentFor(cwd) === true);
|
|
182
|
-
reportUpload(result, target, warn);
|
|
183
|
-
}
|
|
184
|
-
catch (err) {
|
|
185
|
-
warn(`upload failed, left pending for the next push: ${firstLine(err)}`);
|
|
186
|
-
}
|
|
160
|
+
await uploadPush(cwd, dir, push, markers, stored, BACKGROUND_BUDGET_MS);
|
|
187
161
|
}
|
|
188
162
|
const REGISTRY_TIMEOUT_MS = 5_000;
|
|
189
163
|
// Rules TraceHub has not heard of yet (setup was offline, or they are from
|
|
@@ -219,3 +193,20 @@ export async function cmdHook(args, cwd) {
|
|
|
219
193
|
warn(`hook error ignored: ${firstLine(err)}`);
|
|
220
194
|
}
|
|
221
195
|
}
|
|
196
|
+
async function uploadPush(cwd, dir, push, markers, stored, budgetMs, pushedUrl) {
|
|
197
|
+
try {
|
|
198
|
+
const auth = await freshAuth(stored);
|
|
199
|
+
if (pushedUrl)
|
|
200
|
+
await retryRegistration(auth.accessToken);
|
|
201
|
+
const client = clientFor(auth, budgetMs);
|
|
202
|
+
await client.verifyPush(push);
|
|
203
|
+
const result = await uploadMarkers(client, push.target, dir, cwd, repoRoot(cwd) ?? cwd, markers, redactOptions(), true);
|
|
204
|
+
const log = pushedUrl && ranOutOfTime(result)
|
|
205
|
+
? continueInBackground(cwd, dir, pushedUrl, result.skipped)
|
|
206
|
+
: undefined;
|
|
207
|
+
reportUpload(result, push.target, warn, log);
|
|
208
|
+
}
|
|
209
|
+
catch (err) {
|
|
210
|
+
warn(`upload failed, left pending for the next push: ${firstLine(err)}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
@@ -2,7 +2,6 @@ import { DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, readProviders, writeProviders, } fr
|
|
|
2
2
|
import { PROVIDER_NAME } from "../../protocol/context.js";
|
|
3
3
|
import { flagValue } from "../args.js";
|
|
4
4
|
import { out } from "../io.js";
|
|
5
|
-
import { commandUsage } from "../usage.js";
|
|
6
5
|
function add(args) {
|
|
7
6
|
const name = args.positional[2];
|
|
8
7
|
if (!name || !PROVIDER_NAME.test(name))
|
|
@@ -41,10 +40,6 @@ function remove(args) {
|
|
|
41
40
|
}
|
|
42
41
|
export function cmdProviders(args) {
|
|
43
42
|
const sub = args.positional[1];
|
|
44
|
-
if (args.flags["help"] || args.flags["h"] || !sub) {
|
|
45
|
-
out(commandUsage("providers"));
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
43
|
if (sub === "add")
|
|
49
44
|
return add(args);
|
|
50
45
|
if (sub === "list")
|
|
@@ -10,7 +10,6 @@ import { configDir, consentFile } from "../../local/paths.js";
|
|
|
10
10
|
import { Reported, requireTerminal, usageError } from "../io.js";
|
|
11
11
|
import { signIn } from "../signin.js";
|
|
12
12
|
import { bad, bold, dim, done, plural, rows, skipped, step, Stopped, tilde, title, waiting, } from "../ui.js";
|
|
13
|
-
import { commandUsage } from "../usage.js";
|
|
14
13
|
const STEPS = 3;
|
|
15
14
|
// A prompt's answer, or Stopped when the user pressed Ctrl-C or Escape.
|
|
16
15
|
async function answer(prompt) {
|
|
@@ -20,10 +19,6 @@ async function answer(prompt) {
|
|
|
20
19
|
return value;
|
|
21
20
|
}
|
|
22
21
|
export async function cmdSetup(args, cwd, options = {}) {
|
|
23
|
-
if (args.flags["help"] || args.flags["h"]) {
|
|
24
|
-
process.stdout.write(`${commandUsage("setup")}\n`);
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
22
|
if (args.positional.length > 1 || Object.keys(args.flags).length)
|
|
28
23
|
throw usageError("setup", args);
|
|
29
24
|
requireTerminal("setup", options.interactive);
|
|
@@ -12,15 +12,10 @@ import { configDir, consentFile, GIT_STATE_DIR } from "../../local/paths.js";
|
|
|
12
12
|
import { denyFile, readDenyList } from "../../redact/deny.js";
|
|
13
13
|
import { Reported, requireTerminal, usageError } from "../io.js";
|
|
14
14
|
import { bold, dim, done, plural, rows, skipped, Stopped, tilde, title, waiting, } from "../ui.js";
|
|
15
|
-
import { commandUsage } from "../usage.js";
|
|
16
15
|
// Removes what setup made: the global hooks, the permission rules and the
|
|
17
16
|
// sign-in. The deny list and this repository's trace state go only when the
|
|
18
17
|
// user says so; other repositories keep theirs.
|
|
19
18
|
export async function cmdUninstall(args, cwd, options = {}) {
|
|
20
|
-
if (args.flags["help"] || args.flags["h"]) {
|
|
21
|
-
process.stdout.write(`${commandUsage("uninstall")}\n`);
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
19
|
if (args.positional.length > 1 || Object.keys(args.flags).length)
|
|
25
20
|
throw usageError("uninstall", args);
|
|
26
21
|
requireTerminal("uninstall", options.interactive);
|
package/dist/cli/remote.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { isExpired, readAuth } from "../client/auth.js";
|
|
2
|
-
import { TracehubClient, tracehubUrl, } from "../client/tracehub.js";
|
|
1
|
+
import { freshAuth, isExpired, readAuth } from "../client/auth.js";
|
|
2
|
+
import { TracehubClient, tracehubUrl, webUrl, } from "../client/tracehub.js";
|
|
3
3
|
import { ENV_TEST, ENV_TEST_PUSH_BUDGET, home } from "../local/paths.js";
|
|
4
4
|
import { formatSessionRef } from "../protocol/sessionRef.js";
|
|
5
5
|
import { readDenyList } from "../redact/deny.js";
|
|
6
6
|
import { formatFindings } from "../redact/redact.js";
|
|
7
7
|
import { warn } from "./io.js";
|
|
8
|
-
|
|
8
|
+
const UPLOAD_BUDGET_MS = 15_000;
|
|
9
9
|
// What a push leaves unfinished goes on in the background, for this long.
|
|
10
10
|
export const BACKGROUND_BUDGET_MS = 10 * 60_000;
|
|
11
11
|
// How long a push waits for its upload. Tests shorten it.
|
|
@@ -52,7 +52,7 @@ function describeUpload(result) {
|
|
|
52
52
|
}
|
|
53
53
|
// Where tracehub shows the sessions of a commit.
|
|
54
54
|
function traceUrls(target, markers) {
|
|
55
|
-
const repo = `${
|
|
55
|
+
const repo = `${webUrl()}/t/${target.owner}/${target.repo}`;
|
|
56
56
|
return [...new Set(markers.map((m) => `${repo}/${m.traceId}`))];
|
|
57
57
|
}
|
|
58
58
|
// A failure that only means the time ran out: the rest can go on later.
|
|
@@ -79,3 +79,10 @@ export function reportUpload(result, target, emit, background) {
|
|
|
79
79
|
for (const url of traceUrls(target, result.uploaded))
|
|
80
80
|
emit(url);
|
|
81
81
|
}
|
|
82
|
+
export async function signedInClient() {
|
|
83
|
+
const stored = usableAuth();
|
|
84
|
+
if (!stored)
|
|
85
|
+
throw new Error('not signed in; run "tracehub setup"');
|
|
86
|
+
const auth = await freshAuth(stored);
|
|
87
|
+
return { client: clientFor(auth), auth };
|
|
88
|
+
}
|
package/dist/cli/repo.js
CHANGED
|
@@ -8,14 +8,11 @@ import { firstLineOf } from "../local/files.js";
|
|
|
8
8
|
import { sessionLines } from "../local/lines.js";
|
|
9
9
|
import { opencodePendingCommitCall } from "../local/opencode.js";
|
|
10
10
|
import { CLAUDE_SUBAGENT_PREFIX, claudeCwd, discoverActiveSessions, findSessionFile, ranInside, ROOT_COMMIT_WINDOW_MS, subagentWork, } from "../local/discover.js";
|
|
11
|
-
import { consentFile, ENV_CLAUDE_SESSION, ENV_CODEX_THREAD,
|
|
11
|
+
import { consentFile, ENV_CLAUDE_SESSION, ENV_CODEX_THREAD, ENV_SESSION_ID, GIT_STATE_DIR, } from "../local/paths.js";
|
|
12
12
|
import { listClaudeSubagents } from "../local/subagents.js";
|
|
13
13
|
import { formatSessionRef, parseSessionRef, } from "../protocol/sessionRef.js";
|
|
14
14
|
import { codexSessionMeta } from "../transcript/parseCodex.js";
|
|
15
15
|
import { fail } from "./io.js";
|
|
16
|
-
export function hooksDisabled() {
|
|
17
|
-
return process.env[ENV_DISABLE] === "0";
|
|
18
|
-
}
|
|
19
16
|
// Where the CLI keeps its per-repository state: .git/tracehub.
|
|
20
17
|
export function stateDir(cwd) {
|
|
21
18
|
const git = gitDir(cwd);
|
|
@@ -61,7 +58,7 @@ function sessionCwd(ref, file) {
|
|
|
61
58
|
// parent's id), the parent is attached if it ran in the repository, with
|
|
62
59
|
// the subagent as a run, else the subagent alone. A named session that did
|
|
63
60
|
// neither attaches only when it ran in the repository.
|
|
64
|
-
|
|
61
|
+
function environmentSessions(root) {
|
|
65
62
|
const named = [
|
|
66
63
|
parseSessionRef(`claude:${process.env[ENV_CLAUDE_SESSION] ?? ""}`),
|
|
67
64
|
parseSessionRef(`codex:${process.env[ENV_CODEX_THREAD] ?? ""}`),
|
|
@@ -93,10 +90,10 @@ function unique(sessions) {
|
|
|
93
90
|
export function resolveSessions(cwd, root) {
|
|
94
91
|
const forced = forcedSessions();
|
|
95
92
|
if (forced.length)
|
|
96
|
-
return { sessions: forced
|
|
93
|
+
return { sessions: forced };
|
|
97
94
|
const named = environmentSessions(root);
|
|
98
95
|
if (named.length)
|
|
99
|
-
return { sessions: unique(named)
|
|
96
|
+
return { sessions: unique(named) };
|
|
100
97
|
const since = headTimestampMs(cwd) ?? Date.now() - ROOT_COMMIT_WINDOW_MS;
|
|
101
98
|
const found = discoverActiveSessions(root, since);
|
|
102
99
|
const committing = found.filter((ref) => ref.committing ??
|
|
@@ -110,7 +107,6 @@ export function resolveSessions(cwd, root) {
|
|
|
110
107
|
})));
|
|
111
108
|
return {
|
|
112
109
|
sessions,
|
|
113
|
-
source: committing.length ? "active commit" : "discovery",
|
|
114
110
|
};
|
|
115
111
|
}
|
|
116
112
|
export function consentFor(cwd) {
|
|
@@ -143,3 +139,7 @@ export function pushTargetFor(cwd, push) {
|
|
|
143
139
|
? { target }
|
|
144
140
|
: { target, fork: destination };
|
|
145
141
|
}
|
|
142
|
+
export function requireConsent(cwd, target) {
|
|
143
|
+
if (consentFor(cwd) !== true)
|
|
144
|
+
throw new Error(`no permission rule allows uploads for ${target.owner}/${target.repo}; run "tracehub setup"`);
|
|
145
|
+
}
|
package/dist/cli/ui.js
CHANGED
|
@@ -13,7 +13,7 @@ const paint = (style) => (text) => text
|
|
|
13
13
|
export const bold = paint("bold");
|
|
14
14
|
export const dim = paint("dim");
|
|
15
15
|
export const accent = paint("cyan");
|
|
16
|
-
|
|
16
|
+
const good = paint("green");
|
|
17
17
|
export const bad = paint("red");
|
|
18
18
|
const S_DONE = unicodeOr("✓", "√");
|
|
19
19
|
const S_STEP = unicodeOr("●", "*");
|
package/dist/cli/usage.js
CHANGED
|
@@ -100,6 +100,11 @@ export const ENV = [
|
|
|
100
100
|
value: "<url>",
|
|
101
101
|
description: "use another Tracehub server",
|
|
102
102
|
},
|
|
103
|
+
{
|
|
104
|
+
name: "TRACEHUB_GITHUB_CLIENT_ID",
|
|
105
|
+
value: "<id>",
|
|
106
|
+
description: "use another GitHub App client ID for sign-in",
|
|
107
|
+
},
|
|
103
108
|
];
|
|
104
109
|
const WIDTH = 80;
|
|
105
110
|
/** `text` wrapped to WIDTH, every line after the first indented by `indent` spaces. */
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,7 @@ import { cmdProviders } from "./cli/commands/providers.js";
|
|
|
7
7
|
import { cmdSetup } from "./cli/commands/setup.js";
|
|
8
8
|
import { cmdUninstall } from "./cli/commands/uninstall.js";
|
|
9
9
|
import { fail, Reported } from "./cli/io.js";
|
|
10
|
-
import { usage } from "./cli/usage.js";
|
|
10
|
+
import { commandUsage, usage } from "./cli/usage.js";
|
|
11
11
|
const COMMAND_HANDLERS = {
|
|
12
12
|
setup: cmdSetup,
|
|
13
13
|
uninstall: cmdUninstall,
|
|
@@ -18,6 +18,13 @@ const COMMAND_HANDLERS = {
|
|
|
18
18
|
async function main() {
|
|
19
19
|
const args = parseArgs(process.argv.slice(2));
|
|
20
20
|
const name = args.positional[0];
|
|
21
|
+
if (args.flags["help"] ||
|
|
22
|
+
((name === "context" || name === "providers") && !args.positional[1])) {
|
|
23
|
+
process.stdout.write(name && Object.hasOwn(COMMAND_HANDLERS, name)
|
|
24
|
+
? `${commandUsage(name)}\n`
|
|
25
|
+
: usage(true));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
21
28
|
// What the Git hooks run; internal, so not in the usage.
|
|
22
29
|
if (name === "hook") {
|
|
23
30
|
// Hooks that ran npx from the home directory name the repository.
|
|
@@ -33,7 +40,7 @@ async function main() {
|
|
|
33
40
|
return;
|
|
34
41
|
}
|
|
35
42
|
process.stdout.write(usage(true));
|
|
36
|
-
if (name &&
|
|
43
|
+
if (name && name !== "help") {
|
|
37
44
|
process.stderr.write(`\ntracehub: unknown command "${name}"\n`);
|
|
38
45
|
process.exit(1);
|
|
39
46
|
}
|
package/dist/client/github.js
CHANGED
|
@@ -114,29 +114,14 @@ export async function refreshTokens(client, refreshToken) {
|
|
|
114
114
|
}
|
|
115
115
|
// The login of the user the token stands for.
|
|
116
116
|
export async function loginOf(client, token) {
|
|
117
|
-
const res = await
|
|
118
|
-
headers: {
|
|
119
|
-
accept: "application/vnd.github+json",
|
|
120
|
-
authorization: `Bearer ${token}`,
|
|
121
|
-
"user-agent": "tracehub-cli",
|
|
122
|
-
},
|
|
123
|
-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
124
|
-
});
|
|
117
|
+
const res = await githubResponse("/user", token, REQUEST_TIMEOUT_MS, client.fetchFn);
|
|
125
118
|
const { login } = await answerOf(res);
|
|
126
119
|
if (typeof login !== "string")
|
|
127
120
|
throw new Error("GitHub named no user");
|
|
128
121
|
return login;
|
|
129
122
|
}
|
|
130
123
|
async function githubGet(path, token) {
|
|
131
|
-
const res = await
|
|
132
|
-
headers: {
|
|
133
|
-
accept: "application/vnd.github+json",
|
|
134
|
-
authorization: `Bearer ${token}`,
|
|
135
|
-
"user-agent": "tracehub-cli",
|
|
136
|
-
"x-github-api-version": "2022-11-28",
|
|
137
|
-
},
|
|
138
|
-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
139
|
-
});
|
|
124
|
+
const res = await githubResponse(path, token);
|
|
140
125
|
if (!res.ok)
|
|
141
126
|
throw new Error(`GitHub answered ${res.status} for ${path}`);
|
|
142
127
|
return res.json();
|
|
@@ -163,3 +148,15 @@ export async function pullCommits(repo, number, token) {
|
|
|
163
148
|
commits,
|
|
164
149
|
};
|
|
165
150
|
}
|
|
151
|
+
export function githubResponse(path, token, timeoutMs = REQUEST_TIMEOUT_MS, fetchFn = fetch, redirect) {
|
|
152
|
+
return fetchFn(`${GITHUB_API}${path}`, {
|
|
153
|
+
headers: {
|
|
154
|
+
accept: "application/vnd.github+json",
|
|
155
|
+
authorization: `Bearer ${token}`,
|
|
156
|
+
"user-agent": "tracehub-cli",
|
|
157
|
+
"x-github-api-version": "2022-11-28",
|
|
158
|
+
},
|
|
159
|
+
...(redirect ? { redirect } : {}),
|
|
160
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
161
|
+
});
|
|
162
|
+
}
|
package/dist/client/tracehub.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { WEB_URL } from "../protocol/trailers.js";
|
|
2
2
|
import { verifyFork, verifyUploadOwnership, } from "./uploadPolicy.js";
|
|
3
3
|
export const DEFAULT_TRACEHUB_URL = "https://assisted-by.aui.dev";
|
|
4
4
|
export const ENV_TRACEHUB = "TRACEHUB_URL";
|
|
@@ -6,6 +6,9 @@ const REQUEST_TIMEOUT_MS = 15_000;
|
|
|
6
6
|
export function tracehubUrl(env = process.env) {
|
|
7
7
|
return (env[ENV_TRACEHUB] || DEFAULT_TRACEHUB_URL).replace(/\/+$/, "");
|
|
8
8
|
}
|
|
9
|
+
export function webUrl(env = process.env) {
|
|
10
|
+
return (env[ENV_TRACEHUB] || WEB_URL).replace(/\/+$/, "");
|
|
11
|
+
}
|
|
9
12
|
export class TracehubError extends Error {
|
|
10
13
|
status;
|
|
11
14
|
body;
|
|
@@ -116,10 +119,10 @@ export class TracehubClient {
|
|
|
116
119
|
return (await res.json());
|
|
117
120
|
}
|
|
118
121
|
}
|
|
119
|
-
// Whether TraceHub has any session of the trace, asked of the
|
|
122
|
+
// Whether TraceHub has any session of the trace, asked of the site's
|
|
120
123
|
// `.json` page with the user's GitHub token.
|
|
121
124
|
export async function traceUploaded(target, traceId, token) {
|
|
122
|
-
const res = await fetch(`${
|
|
125
|
+
const res = await fetch(`${webUrl()}/t/${target.owner}/${target.repo}/${traceId}.json`, {
|
|
123
126
|
headers: {
|
|
124
127
|
authorization: `Bearer ${token}`,
|
|
125
128
|
"user-agent": "tracehub-cli",
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { githubResponse } from "./github.js";
|
|
1
2
|
export const UPLOAD_OWNER = "assistant-ui";
|
|
2
3
|
export const UPLOAD_POLICY_ERROR = "trace uploads require one unambiguous GitHub repository owned by assistant-ui; nothing was uploaded";
|
|
3
4
|
// Only the real GitHub host and conventional Git transports are accepted.
|
|
@@ -36,16 +37,7 @@ async function githubRepository(repo, token, timeoutMs, fetchFn, check) {
|
|
|
36
37
|
throw new Error("upload budget exhausted; nothing was uploaded");
|
|
37
38
|
let response;
|
|
38
39
|
try {
|
|
39
|
-
response = await
|
|
40
|
-
headers: {
|
|
41
|
-
accept: "application/vnd.github+json",
|
|
42
|
-
authorization: `Bearer ${token}`,
|
|
43
|
-
"user-agent": "tracehub-cli",
|
|
44
|
-
"x-github-api-version": "2022-11-28",
|
|
45
|
-
},
|
|
46
|
-
redirect: "error",
|
|
47
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
48
|
-
});
|
|
40
|
+
response = await githubResponse(`/repos/${repo.owner}/${repo.repo}`, token, timeoutMs, fetchFn, "error");
|
|
49
41
|
}
|
|
50
42
|
catch {
|
|
51
43
|
throw new Error(`GitHub could not verify ${check}; nothing was uploaded`);
|
package/dist/git/git.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
|
-
import { traceIds } from "
|
|
2
|
+
import { traceIds } from "../protocol/trailers.js";
|
|
3
3
|
const MAX_BUFFER = 256 * 1024 * 1024;
|
|
4
4
|
export function git(args, opts = {}) {
|
|
5
5
|
const out = execFileSync("git", args, {
|
package/dist/git/trailers.js
CHANGED
|
@@ -1,36 +1,23 @@
|
|
|
1
|
+
import { ENV_DISABLE } from "../local/paths.js";
|
|
2
|
+
import { traceUrl, WEB_URL } from "../protocol/trailers.js";
|
|
1
3
|
const TRAILER_KEY = "Assisted-by";
|
|
2
|
-
// The dashboard, where a trailer links to its trace.
|
|
3
|
-
export const DASHBOARD_URL = "https://tracehub.aui.dev";
|
|
4
|
-
const ID = /^[0-9a-f]{16}$/;
|
|
5
|
-
// The trailer's value is the trace's URL, or the bare trace id.
|
|
6
|
-
const LINE = /^[ \t]*Assisted-by:[ \t]*(?:\S*\/)?([0-9a-f]{16})[ \t]*$/gm;
|
|
7
|
-
export function isTraceId(s) {
|
|
8
|
-
return ID.test(s);
|
|
9
|
-
}
|
|
10
4
|
export function newTraceId() {
|
|
11
5
|
return Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
12
6
|
}
|
|
13
|
-
|
|
14
|
-
export function traceUrl(target, id) {
|
|
15
|
-
return `${DASHBOARD_URL}/t/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${id}`;
|
|
16
|
-
}
|
|
17
|
-
// Every "Assisted-by: <id or URL>" line anywhere in the message, in order: a squash
|
|
18
|
-
// (git's, indented, or GitHub's) folds the trailers of the squashed commits
|
|
19
|
-
// into the body, where git's own trailer parser no longer sees them.
|
|
20
|
-
export function traceIds(message) {
|
|
21
|
-
return [...new Set([...message.matchAll(LINE)].map((m) => m[1]))];
|
|
22
|
-
}
|
|
23
|
-
export function interpretTrailersArgs(target, id, messageFile) {
|
|
7
|
+
export function interpretTrailersArgs(target, id, messageFile, base = WEB_URL) {
|
|
24
8
|
return [
|
|
25
9
|
"interpret-trailers",
|
|
26
10
|
"--in-place",
|
|
27
11
|
"--trailer",
|
|
28
|
-
`${TRAILER_KEY}: ${traceUrl(target, id)}`,
|
|
12
|
+
`${TRAILER_KEY}: ${traceUrl(target, id, base)}`,
|
|
29
13
|
messageFile,
|
|
30
14
|
];
|
|
31
15
|
}
|
|
32
16
|
export function shouldSkipCommit(source, env) {
|
|
33
|
-
if (env
|
|
17
|
+
if (hooksDisabled(env))
|
|
34
18
|
return true;
|
|
35
19
|
return source === "merge" || source === "squash";
|
|
36
20
|
}
|
|
21
|
+
export function hooksDisabled(env = process.env) {
|
|
22
|
+
return env[ENV_DISABLE] === "0";
|
|
23
|
+
}
|
package/dist/local/backfill.js
CHANGED
|
@@ -18,8 +18,8 @@ export function checkoutsNamed(command, home = "") {
|
|
|
18
18
|
const LOOKBACK_MS = 7 * 24 * 3600_000;
|
|
19
19
|
// The commit's time is in whole seconds, its session's in milliseconds.
|
|
20
20
|
const SLACK_MS = 60_000;
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
const HIGH = 7;
|
|
22
|
+
const MEDIUM = 4;
|
|
23
23
|
// The session's events with the line each one came from; parsed one line at
|
|
24
24
|
// a time, as commitBoundary reads them.
|
|
25
25
|
export function candidateOf(ref, file, lines, opts = {}) {
|
|
@@ -76,7 +76,7 @@ function editedPath(path, cwd, files) {
|
|
|
76
76
|
return files.find((f) => full === f || full.endsWith(`/${f}`));
|
|
77
77
|
}
|
|
78
78
|
const TRUNK = new Set(["main", "master", "HEAD", "develop"]);
|
|
79
|
-
|
|
79
|
+
function confidenceOf(score, tied) {
|
|
80
80
|
if (tied && score >= HIGH)
|
|
81
81
|
return "high";
|
|
82
82
|
if (score >= MEDIUM)
|
package/dist/local/discover.js
CHANGED
|
@@ -3,7 +3,7 @@ import { isAbsolute, join } from "node:path";
|
|
|
3
3
|
import { parseClaude } from "../transcript/parseClaude.js";
|
|
4
4
|
import { codexSessionMeta } from "../transcript/parseCodex.js";
|
|
5
5
|
import { openCommitCalls } from "./commitBoundary.js";
|
|
6
|
-
import { fileEntry, firstLineOf, listDir } from "./files.js";
|
|
6
|
+
import { fileEntry, firstLineOf, listDir, walkClaudeTranscripts, } from "./files.js";
|
|
7
7
|
import { completeLines } from "./lines.js";
|
|
8
8
|
import { hasOpencodeSession, listOpencodeSessions, } from "./opencode.js";
|
|
9
9
|
import { claudeProjectsDir, codexSessionsDir, encodeClaudeCwd, home, opencodeDb, } from "./paths.js";
|
|
@@ -116,22 +116,9 @@ export function isClaudeSubagent(ref) {
|
|
|
116
116
|
// ~/.claude/projects/*/<session id>/subagents/agent-<id>.jsonl, for the
|
|
117
117
|
// files written to since sinceMs.
|
|
118
118
|
function* walkClaudeSubagentFiles(sinceMs) {
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
if (session.endsWith(".jsonl"))
|
|
123
|
-
continue;
|
|
124
|
-
const dir = join(base, project, session, "subagents");
|
|
125
|
-
for (const name of listDir(dir)) {
|
|
126
|
-
if (!/^agent-[A-Za-z0-9_-]+\.jsonl$/.test(name))
|
|
127
|
-
continue;
|
|
128
|
-
const entry = fileEntry(join(dir, name));
|
|
129
|
-
if (!entry || entry.mtimeMs <= sinceMs)
|
|
130
|
-
continue;
|
|
131
|
-
const parent = join(base, project, `${session}.jsonl`);
|
|
132
|
-
yield { ...entry, id: name.slice(0, -".jsonl".length), parent };
|
|
133
|
-
}
|
|
134
|
-
}
|
|
119
|
+
for (const entry of walkClaudeTranscripts(claudeProjectsDir())) {
|
|
120
|
+
if (entry.parent && entry.mtimeMs > sinceMs)
|
|
121
|
+
yield { ...entry, parent: entry.parent };
|
|
135
122
|
}
|
|
136
123
|
}
|
|
137
124
|
// The ways a command can name the repository's checkout.
|
|
@@ -171,11 +158,11 @@ export function subagentWork(lines, root, sinceMs) {
|
|
|
171
158
|
}
|
|
172
159
|
// How far back subagents filed under other projects are read: they are
|
|
173
160
|
// read whole, so only the recent ones.
|
|
174
|
-
|
|
161
|
+
const SUBAGENT_WINDOW_MS = DAY_MS;
|
|
175
162
|
// The subagents of sessions that ran outside the repository, written to
|
|
176
163
|
// recently, that name the repository somewhere. A subagent of a session
|
|
177
164
|
// inside it is a run of that session's trace instead.
|
|
178
|
-
function
|
|
165
|
+
function discoverClaudeSubagents(repoRoot, sinceMs) {
|
|
179
166
|
const from = Math.max(sinceMs, Date.now() - SUBAGENT_WINDOW_MS);
|
|
180
167
|
const parents = new Map();
|
|
181
168
|
const found = [];
|
|
@@ -246,7 +233,7 @@ export function discoverActiveSessions(repoRoot, sinceMs) {
|
|
|
246
233
|
repoRoot,
|
|
247
234
|
sinceMs,
|
|
248
235
|
claudeFiles: listClaudeFiles(repoRoot),
|
|
249
|
-
claudeSubagents:
|
|
236
|
+
claudeSubagents: discoverClaudeSubagents(repoRoot, sinceMs),
|
|
250
237
|
codexFiles: listCodexFiles(sinceMs),
|
|
251
238
|
opencodeSessions: listOpencodeSessions(sinceMs),
|
|
252
239
|
});
|
package/dist/local/files.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { basename, join } from "node:path";
|
|
1
2
|
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync, } from "node:fs";
|
|
2
3
|
// A JSON object read from a file; anything else (missing, malformed, an
|
|
3
4
|
// array) reads as an empty object.
|
|
@@ -53,3 +54,25 @@ export function firstLineOf(file) {
|
|
|
53
54
|
closeSync(fd);
|
|
54
55
|
}
|
|
55
56
|
}
|
|
57
|
+
export function* walkClaudeTranscripts(projectsDir, sessionFile) {
|
|
58
|
+
const sessions = sessionFile
|
|
59
|
+
? [sessionFile]
|
|
60
|
+
: listDir(projectsDir).flatMap((project) => listDir(join(projectsDir, project)).map((name) => join(projectsDir, project, name)));
|
|
61
|
+
for (const path of sessions) {
|
|
62
|
+
if (!sessionFile && path.endsWith(".jsonl")) {
|
|
63
|
+
const entry = fileEntry(path);
|
|
64
|
+
if (entry)
|
|
65
|
+
yield { ...entry, id: basename(path, ".jsonl") };
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const parent = sessionFile ?? `${path}.jsonl`;
|
|
69
|
+
const dir = join(sessionFile ? sessionFile.replace(/\.jsonl$/, "") : path, "subagents");
|
|
70
|
+
for (const name of listDir(dir).sort()) {
|
|
71
|
+
if (!/^agent-[A-Za-z0-9_-]+\.jsonl$/.test(name))
|
|
72
|
+
continue;
|
|
73
|
+
const entry = fileEntry(join(dir, name));
|
|
74
|
+
if (entry)
|
|
75
|
+
yield { ...entry, id: basename(name, ".jsonl"), parent };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
package/dist/local/providers.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
4
|
-
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
|
|
5
4
|
import { dirname } from "node:path";
|
|
6
5
|
import { conversationOf, parseContextEntries, parseContextRef, PROVIDER_NAME, } from "../protocol/context.js";
|
|
7
6
|
import { providersFile } from "./paths.js";
|
|
@@ -53,7 +52,7 @@ export function providerArgv(provider, id) {
|
|
|
53
52
|
}
|
|
54
53
|
// An entry without an id is named by its content, so attaching it twice
|
|
55
54
|
// replaces it rather than adding it again.
|
|
56
|
-
|
|
55
|
+
function contentId(entry) {
|
|
57
56
|
const key = JSON.stringify([
|
|
58
57
|
entry.author,
|
|
59
58
|
entry.at,
|
package/dist/local/subagents.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { basename, dirname, join } from "node:path";
|
|
2
2
|
import { codexSessionMeta } from "../transcript/parseCodex.js";
|
|
3
3
|
import { walkCodexFiles } from "./discover.js";
|
|
4
|
-
import { firstLineOf,
|
|
4
|
+
import { firstLineOf, walkClaudeTranscripts, readJsonObject } from "./files.js";
|
|
5
5
|
import { listOpencodeSubagents } from "./opencode.js";
|
|
6
6
|
const DEFAULT_KIND = "subagent";
|
|
7
7
|
// Claude Code keeps subagent transcripts beside the parent session file, in
|
|
@@ -21,18 +21,15 @@ export function claudeSubagentLabel(file) {
|
|
|
21
21
|
}
|
|
22
22
|
// An optional agent-<id>.meta.json says how the parent launched the subagent.
|
|
23
23
|
export function listClaudeSubagents(sessionFile) {
|
|
24
|
-
const dir = claudeSubagentDir(sessionFile);
|
|
25
24
|
const subagents = [];
|
|
26
|
-
for (const
|
|
27
|
-
const id =
|
|
28
|
-
|
|
29
|
-
continue;
|
|
30
|
-
const meta = readJsonObject(join(dir, `agent-${id}.meta.json`));
|
|
25
|
+
for (const entry of walkClaudeTranscripts("", sessionFile)) {
|
|
26
|
+
const id = entry.id.slice("agent-".length);
|
|
27
|
+
const meta = readJsonObject(entry.file.replace(/\.jsonl$/, ".meta.json"));
|
|
31
28
|
const toolUseId = stringField(meta, "toolUseId");
|
|
32
29
|
subagents.push({
|
|
33
30
|
id,
|
|
34
31
|
kind: stringField(meta, "agentType") ?? DEFAULT_KIND,
|
|
35
|
-
file:
|
|
32
|
+
file: entry.file,
|
|
36
33
|
...(toolUseId ? { toolUseId } : {}),
|
|
37
34
|
});
|
|
38
35
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export const WEB_URL = "https://tracehub.aui.dev";
|
|
2
|
+
const ID = /^[0-9a-f]{16}$/;
|
|
3
|
+
const LINE = /^[ \t]*Assisted-by:[ \t]*(?:\S*\/)?([0-9a-f]{16})[ \t]*$/gm;
|
|
4
|
+
const PULL = /^[ \t]*Assisted-by:[ \t]*\S*\/pr\/([\w.-]+)\/([\w.-]+)\/([1-9]\d{0,9})[ \t]*$/gm;
|
|
5
|
+
export function isTraceId(s) {
|
|
6
|
+
return ID.test(s);
|
|
7
|
+
}
|
|
8
|
+
export function traceUrl(target, id, base = WEB_URL) {
|
|
9
|
+
return `${base}/t/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${id}`;
|
|
10
|
+
}
|
|
11
|
+
// Squashed commits put trailers in the body, where git's trailer parser no longer sees them.
|
|
12
|
+
export function traceIds(message) {
|
|
13
|
+
return [...new Set([...message.matchAll(LINE)].map((m) => m[1]))];
|
|
14
|
+
}
|
|
15
|
+
export function pullUrl(target, number, base = WEB_URL) {
|
|
16
|
+
return `${base}/pr/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${number}`;
|
|
17
|
+
}
|
|
18
|
+
// The pull requests of the repository a message links to: a squash merge
|
|
19
|
+
// names its pull request once instead of each squashed commit's trace.
|
|
20
|
+
export function pullNumbers(message, target) {
|
|
21
|
+
const numbers = [...message.matchAll(PULL)]
|
|
22
|
+
.filter((m) => m[1].toLowerCase() === target.owner.toLowerCase() &&
|
|
23
|
+
m[2].toLowerCase() === target.repo.toLowerCase())
|
|
24
|
+
.map((m) => Number(m[3]));
|
|
25
|
+
return [...new Set(numbers)];
|
|
26
|
+
}
|
package/dist/redact/deny.js
CHANGED
|
@@ -3,11 +3,11 @@ import { join } from "node:path";
|
|
|
3
3
|
import { configDir } from "../local/paths.js";
|
|
4
4
|
// The deny list is edited by hand: one literal per line. A shorter line would
|
|
5
5
|
// mask ordinary words, so it is ignored.
|
|
6
|
-
|
|
6
|
+
const DENY_MIN_LENGTH = 6;
|
|
7
7
|
export function denyFile() {
|
|
8
8
|
return join(configDir(), "deny.txt");
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
function parseDenyList(text) {
|
|
11
11
|
return [
|
|
12
12
|
...new Set(text
|
|
13
13
|
.split("\n")
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tracehub",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.9",
|
|
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",
|
|
@@ -14,17 +14,6 @@
|
|
|
14
14
|
"dist",
|
|
15
15
|
"README.md"
|
|
16
16
|
],
|
|
17
|
-
"scripts": {
|
|
18
|
-
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc && chmod +x dist/cli.js",
|
|
19
|
-
"typecheck": "tsc --noEmit -p tsconfig.test.json",
|
|
20
|
-
"format": "oxfmt --check",
|
|
21
|
-
"format:fix": "oxfmt",
|
|
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",
|
|
24
|
-
"prepack": "npm run build",
|
|
25
|
-
"docs:install": "pnpm --dir docs install",
|
|
26
|
-
"docs:dev": "pnpm --dir docs dev"
|
|
27
|
-
},
|
|
28
17
|
"devDependencies": {
|
|
29
18
|
"@types/node": "^26.6.6",
|
|
30
19
|
"@vitest/coverage-v8": "^5.0.5",
|
|
@@ -46,14 +35,20 @@
|
|
|
46
35
|
"dependencies": {
|
|
47
36
|
"@clack/prompts": "^1.8.1"
|
|
48
37
|
},
|
|
49
|
-
"allowScripts": {
|
|
50
|
-
"fsevents@2.3.3": true
|
|
51
|
-
},
|
|
52
38
|
"devEngines": {
|
|
53
39
|
"packageManager": {
|
|
54
|
-
"name": "
|
|
55
|
-
"version": ">=
|
|
40
|
+
"name": "pnpm",
|
|
41
|
+
"version": ">=12",
|
|
56
42
|
"onFail": "error"
|
|
57
43
|
}
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc && chmod +x dist/cli.js",
|
|
47
|
+
"typecheck": "tsc --noEmit -p tsconfig.test.json && tsc -p tsconfig.shared.json",
|
|
48
|
+
"format": "oxfmt --check",
|
|
49
|
+
"format:fix": "oxfmt",
|
|
50
|
+
"test": "tsc -p tsconfig.test.json && vitest run",
|
|
51
|
+
"test:coverage": "tsc -p tsconfig.test.json && vitest run --coverage --coverage.reporter=text --coverage.reporter=html --coverage.reporter=json-summary",
|
|
52
|
+
"docs:dev": "pnpm --filter tracehub-docs dev"
|
|
58
53
|
}
|
|
59
|
-
}
|
|
54
|
+
}
|