tracehub 0.0.0-stage → 0.5.0

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.
Files changed (48) hide show
  1. package/README.md +424 -2
  2. package/dist/cli/args.js +28 -0
  3. package/dist/cli/clipboard.js +46 -0
  4. package/dist/cli/commands/context.js +115 -0
  5. package/dist/cli/commands/hook.js +209 -0
  6. package/dist/cli/commands/providers.js +55 -0
  7. package/dist/cli/commands/setup.js +448 -0
  8. package/dist/cli/commands/uninstall.js +156 -0
  9. package/dist/cli/io.js +26 -0
  10. package/dist/cli/remote.js +81 -0
  11. package/dist/cli/repo.js +65 -0
  12. package/dist/cli/signin.js +90 -0
  13. package/dist/cli/ui.js +130 -0
  14. package/dist/cli/usage.js +151 -0
  15. package/dist/cli.js +38 -0
  16. package/dist/client/auth.js +70 -0
  17. package/dist/client/consent.js +94 -0
  18. package/dist/client/errors.js +4 -0
  19. package/dist/client/github.js +129 -0
  20. package/dist/client/registry.js +112 -0
  21. package/dist/client/tracehub.js +98 -0
  22. package/dist/client/upload.js +106 -0
  23. package/dist/client/uploadPolicy.js +60 -0
  24. package/dist/git/git.js +166 -0
  25. package/dist/git/global-hooks.js +221 -0
  26. package/dist/git/hooks.js +67 -0
  27. package/dist/git/markers.js +93 -0
  28. package/dist/git/trailers.js +36 -0
  29. package/dist/local/commitBoundary.js +38 -0
  30. package/dist/local/discover.js +283 -0
  31. package/dist/local/files.js +55 -0
  32. package/dist/local/lines.js +16 -0
  33. package/dist/local/opencode.js +124 -0
  34. package/dist/local/paths.js +51 -0
  35. package/dist/local/providers.js +171 -0
  36. package/dist/local/subagents.js +63 -0
  37. package/dist/protocol/context.js +202 -0
  38. package/dist/protocol/sessionRef.js +24 -0
  39. package/dist/protocol/trace.js +111 -0
  40. package/dist/redact/deny.js +25 -0
  41. package/dist/redact/redact.js +189 -0
  42. package/dist/trace/build.js +256 -0
  43. package/dist/transcript/parseClaude.js +105 -0
  44. package/dist/transcript/parseCodex.js +164 -0
  45. package/dist/transcript/parseOpencode.js +84 -0
  46. package/dist/transcript/title.js +27 -0
  47. package/dist/transcript/transcript.js +120 -0
  48. package/package.json +46 -4
package/README.md CHANGED
@@ -1,3 +1,425 @@
1
- # Temporary Holding Version
1
+ # Tracehub CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tracehub has four parts: the **Tracehub CLI** (this package, the `tracehub` command), the **Tracehub API** (a Cloudflare Worker that stores the traces), the **Tracehub web app** (`https://tracehub.aui.dev`, a static preview of the traces behind a commit or pull request, with `.json` twins) and the **Tracehub GitHub App**.
4
+
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
+
7
+ A commit made while an agent session is active gets an `Assisted-by: https://tracehub.aui.dev/t/<owner>/<repo>/<trace id>` trailer: a link to its trace, under a random trace id that says nothing about the session. The commit also records where each session stood when it was made. On push, the CLI turns each session into its trace at that commit, fetches the context conversations the session names from their providers, redacts everything and uploads it; TraceHub keeps one self-contained document per commit.
8
+
9
+ `SPEC.md` describes the whole system in detail.
10
+
11
+ ## Design
12
+
13
+ A trace is everything that produced one commit, in one JSON document:
14
+
15
+ 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).
16
+ 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.
17
+ 3. **A sourcemap** (optional). For each line the commit adds, the turn that last wrote it, blame-style.
18
+
19
+ 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.
20
+
21
+ | piece | where |
22
+ | --- | --- |
23
+ | upload | `PUT /repos/:owner/:repo/traces/:trace/sessions/:name`, one session of a commit with its context conversations, replaced on re-upload |
24
+ | trace document | R2 `<owner>/<repo>/commits/<trace id>.json`: the commit's context conversations and sessions, rebuilt from the uploaded sessions on every upload |
25
+ | pull request context | `PUT` (attach) and `DELETE` (detach) `/repos/:owner/:repo/pulls/:number/context`, R2 `<owner>/<repo>/context/<number>/<user id>`, merged by conversation and message id |
26
+ | audience | the uploader and maintainers (GitHub write, maintain or admin); everyone else sees nothing |
27
+
28
+ ### The trace document
29
+
30
+ ```json
31
+ {
32
+ "version": 1,
33
+ "owner": "assistant-ui",
34
+ "repo": "tracehub",
35
+ "traceId": "0123456789abcdef",
36
+ "updatedAt": "2026-10-28T08:00:00.000Z",
37
+ "context": [
38
+ {
39
+ "ref": "nomos:t_16da1c327635",
40
+ "title": "S3 attachment backend and setup guide",
41
+ "url": "https://home.simonfarshid.com/?thread=t_16da1c327635",
42
+ "sessions": ["claude-agent-a1b2.jsonl"],
43
+ "messages": [
44
+ { "id": "nomos:t_16da1c327635:m_1", "author": "Simon", "text": "…", "at": "2026-10-28T06:48:09.441Z" }
45
+ ]
46
+ }
47
+ ],
48
+ "sessions": [
49
+ {
50
+ "name": "claude-agent-a1b2.jsonl",
51
+ "agent": "claude",
52
+ "id": "agent-a1b2",
53
+ "title": "…",
54
+ "model": "…",
55
+ "committedAt": "…",
56
+ "uploader": { "id": "1", "login": "simon", "name": "Simon" },
57
+ "uploadedAt": "…",
58
+ "turns": [{ "at": "…", "messages": [{ "role": "user", "at": "…", "text": "…" }], "changes": [{ "path": "src/a.ts", "added": 3, "removed": 1 }], "runs": [] }],
59
+ "sourcemap": { "src/a.ts": { "<line hash>": "0" } }
60
+ }
61
+ ]
62
+ }
63
+ ```
64
+
65
+ - `context`: each conversation once, its messages deduplicated by id and in time order; `sessions` names the sessions that attached it, so a reader shows a conversation to who may see one of them. A message `withheld: true` has an empty text (see Privacy); a message has its own `url` only when it differs from the conversation's.
66
+ - `sessions`: each a session of the commit, as uploaded; the uploader's identity decides who sees it.
67
+
68
+ ### The sourcemap
69
+
70
+ `{ "<path>": { "<line hash>": "<turn path>" } }`, for the lines the commit adds (`git show` of the commit against its first parent).
71
+
72
+ - 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.
73
+ - The turn path is the turn's index in the session, `"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.
74
+ - 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.
75
+ - 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.
76
+ - A trace page's **Line map** lists, per file, the prompts that wrote the commit's lines and how many.
77
+
78
+ ## Install
79
+
80
+ Set it up once with `setup` (the other commands are under [Commands](#commands)). Run it in your terminal:
81
+
82
+ ```sh
83
+ npx --yes tracehub@0.5.0 setup
84
+ ```
85
+
86
+ 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.
87
+
88
+ 1. **Account.** Shows whether you're signed in to GitHub and as whom. Keep that account, or sign in with another one: setup shows a one-time code, and Enter copies it to the clipboard and opens GitHub's device sign-in in the browser (without a clipboard tool, `pbcopy`, `clip`, `wl-copy`, `xclip` or `xsel`, you type the code). A spinner shows while GitHub waits for you; Ctrl-C stops it. GitHub signs in the account your browser is signed in to, so switch accounts on github.com first. One account is stored at a time. Signed out, you can sign in or skip the step.
89
+ 2. **Permission rules.** Lists your rules, then lets you add or revoke them. A rule allows uploads for a GitHub organization (`owner`, every repository of it, including future ones) or for one repository (`owner/repo`). Inside a clone, setup offers the current repository and its organization; any other owner or `owner/repo` can be typed, or a pasted GitHub URL. Before a rule is added, setup shows what an upload shares and asks to confirm.
90
+ 3. **Git hooks.** Explains the global Git hooks, then installs them, or, when they are installed, keeps or removes them.
91
+
92
+ 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.
93
+
94
+ To skip npx on every commit, install it globally instead: `npm install -g tracehub@0.5.0`, then `tracehub setup`.
95
+
96
+ ### Git hooks
97
+
98
+ 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.
99
+
100
+ | hook | does |
101
+ | --- | --- |
102
+ | `prepare-commit-msg` | in an allowed repository, adds the trailer and records a marker per session |
103
+ | `pre-push` | uploads the traces of pushed commits (15 s budget, then the rest in the background), and retries the traces an earlier push left pending |
104
+
105
+ - A hook command always exits 0. It never blocks a commit or a push, and never prompts.
106
+ - A hook command does nothing without a permission rule for the repository, with `TRACEHUB=0`, or outside a repository.
107
+ - A repository, worktree or command that sets its own `core.hooksPath` (Husky does) skips the global hooks, so it gets no traces. Setup warns when the current repository does.
108
+ - Setup refuses conflicting files, a global setting another tool changed, and global or system `include`/`includeIf` configuration, whose hook paths can vary across checkouts, instead of overwriting them.
109
+ - A hook that can't run tracehub (a deleted checkout, npx offline) prints one line, `tracehub: … run "tracehub setup" to repair the hooks`, and lets the commit or push go on.
110
+ - Running setup again and keeping the hooks points them at the tracehub that runs it, rewriting hooks of another version or of earlier releases, which always ran npx.
111
+
112
+ ### Uninstall
113
+
114
+ ```sh
115
+ npx --yes tracehub@0.5.0 uninstall
116
+ ```
117
+
118
+ 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.
119
+
120
+ ### Upload scope
121
+
122
+ Uploads are restricted to repositories verified as owned by the GitHub organization **`assistant-ui`** (CLI 0.4.0 and later).
123
+
124
+ - All effective fetch and push remote URLs must name the same repository on `github.com`, with the exact owner `assistant-ui` (case insensitive). HTTPS, GitHub SSH URLs and `git@github.com:…` are accepted. Missing, unknown or conflicting remotes block uploads. A personal fork with an organization upstream is blocked. Duplicate remotes to the same repository are allowed.
125
+ - Git's URL rewrites are resolved, and pre-push also checks the destination URL Git passes to the hook. The hooks forward `"$@"` and Git's stdin ref updates; missing arguments or ref input block upload, even if the configured origin is eligible. The commit hook skips trace markers for ineligible remotes; it makes no network request.
126
+ - Before sending any trace or marker, the upload run asks GitHub for the canonical repository owner using the signed-in user's token. The returned owner must be the `assistant-ui` organization and the canonical repository name must match the remotes. Redirects, transfers, renames, missing fields, access failures and network failures block uploads. Update remotes after a rename. An organization-owned fork remains eligible; a fork owned elsewhere does not.
127
+ - This applies to every upload of the pre-push hook, including previously pending markers. Upload methods also verify ownership themselves. A refused hook still exits 0, preserving pending work for a later push.
128
+ - A permission rule and a sign-in remain required. This check does not grant access, change trace visibility, or send traces to GitHub; it runs fresh at upload time.
129
+
130
+ ## Sign in
131
+
132
+ Setup's first step signs you in with the device flow of GitHub.
133
+
134
+ - The credentials go to `~/.config/tracehub/auth.json` (mode `0600`). A replacement is saved only after GitHub confirms the new account; cancelling keeps the current one. The access token is refreshed when needed; a refresh that GitHub refuses removes the file.
135
+ - The GitHub App TraceHub Bot (`tracehub-bot`, formerly `assisted-by-bot`) must be installed. Uploads require current push access and verified `assistant-ui` organization ownership. Reading traces uses the audience policy below; maintainers have current GitHub write, maintain or admin access to the repository.
136
+ - A hook that finds no sign-in leaves its work pending and says so; the first push after signing in uploads it.
137
+
138
+ | setting | environment | default |
139
+ | --- | --- | --- |
140
+ | The Tracehub API | `TRACEHUB_URL` | `https://assisted-by.aui.dev` |
141
+ | client id of the GitHub App | `TRACEHUB_GITHUB_CLIENT_ID` | `Iv23limQrRDTbi0xJG3f` |
142
+
143
+ ## Permission rules
144
+
145
+ Nothing is attached until a permission rule allows the repository. Setup's second step adds and revokes the rules; a rule is scoped to a GitHub organization or to one repository, nothing else.
146
+
147
+ An allowed repository means: the traces of the agent sessions that ran in it (their messages, per-turn changes and sourcemaps; never tool calls, results or thinking) are uploaded, redacted, to Tracehub, for you and the repository's maintainers with GitHub write, maintain or admin access; everyone else sees nothing. On the way in, the Tracehub API sends the redacted messages to TypeSafe's Jev model to find what the patterns missed (see Privacy).
148
+
149
+ 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.
150
+
151
+ - **Older consents.** A consent for all GitHub repositories (`github.com/*`, from `consent --all`) no longer allows anything: the hooks ignore it, and setup removes it from the file and says so. Add an organization or repository rule instead. A repository refusal from `consent --no` still blocks that repository; setup lists it as declined, and revoking it removes it.
152
+ - 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.
153
+
154
+ | rule for the repository | a commit with an active session |
155
+ | --- | --- |
156
+ | allowed | gets the trailer and markers |
157
+ | declined (older consents) | is left alone |
158
+ | none | is left alone, with a hint to run `tracehub setup` |
159
+
160
+ ### Consent registry
161
+
162
+ TraceHub keeps a copy of your rules (`_consent/users/<your id>`).
163
+
164
+ - At the end of step 2, setup sends this machine's rules, all of them, as `{machine, rules: [{scope, upload, at}]}` to `PUT /consent`, signed in as you. Sending the same rules again changes nothing, so every setup sends them, and rules from before the registry are registered on the next setup or push. Revoking a rule and continuing sends the rest.
165
+ - Each machine has its own id in `~/.config/tracehub/consent-sync.json`; TraceHub merges the machines, so a second machine without rules takes nothing away. A scope one machine allows counts as allowed.
166
+ - Offline, signed out, or refused: the rules still work on this machine. Setup says the registration is pending, and `consent-sync.json` keeps it pending until a push (which tries again quietly, for 5 seconds) or the next setup sends it.
167
+ - `uninstall` sends an empty set for this machine before it signs out. Offline, TraceHub keeps the machine's rules; run setup, revoke them and continue to remove them.
168
+
169
+ ## How it works
170
+
171
+ 1. **Commit.** `prepare-commit-msg` finds the sessions of the commit (see Discovery). If the message has no `Assisted-by` trailer yet, it adds one with a new 16-hex trace id. For each session it appends a marker to `.git/tracehub/markers.jsonl` (in the repository's common git directory, so a linked worktree's markers outlive the worktree): `{traceId, session, line, ts, context?, uploaded}`, where `line` is the number of complete lines the session file had and `context` the references of `TRACEHUB_CONTEXT`. Merge and squash commits are skipped.
172
+ 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.
173
+ 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`.
174
+ 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 start of the description, between `<!-- tracehub:start -->` and `<!-- tracehub:end -->`: a small icon in the top right corner. A pull request with attached context gets the link too.
175
+ 5. **Reading.** The icon links to `/pr/<owner>/<repo>/<number>`: the intent and effort at a glance (first prompt, wall-clock time, prompts, commits, agents), then one timeline of the context conversations and the sessions of its commits, each message clamped to three lines, subagent runs folded to one line. A trace is at `/t/<owner>/<repo>/<trace id>`, a commit's traces at `/c/<owner>/<repo>/<sha>`. Add `.json` to any of them for the data (sign-in cookie or `Authorization: Bearer <GitHub token>`). The pages are rendered when their data changes and served from the cache.
176
+ 6. **Without a pull request.** A push prints a link per commit it marked, `/t/<owner>/<repo>/<trace id>`.
177
+
178
+ ### What a trace holds
179
+
180
+ The trace of a session at a commit, built from the session's file up to the marker's line:
181
+
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.
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.
184
+ - **Runs.** A subagent (a Claude Code subagent, a Codex sub-thread, an OpenCode task) is a run under the turn whose call launched it, else under the last turn that started before it did. A run has its own turns: the prompt the parent gave it, its replies and its changes.
185
+ - **The sourcemap** of the commit's added lines (see [The sourcemap](#the-sourcemap)).
186
+ - **Context conversations** the session's first message, its subagents' briefs or the marker name (see [Context conversations](#context-conversations)).
187
+ - The title Claude Code gave the session, the model, and when the commit was made.
188
+
189
+ Nothing else leaves the machine: no tool calls or results, no thinking, no token counts or timings, no working directory or other local paths, no subagent internals beyond their messages.
190
+
191
+ The upload replaces the trace of that commit and session, and the API rebuilds the commit's trace document from its sessions; sending it again changes nothing. Only who uploaded a trace may replace it.
192
+
193
+ ## Discovery
194
+
195
+ The sessions of a commit, by precedence:
196
+
197
+ 1. `TRACEHUB_ID=<claude|codex|opencode>:<id>` in the environment (comma-separated for several).
198
+ 2. Recently active sessions with an open agent tool call executing `git commit`. This preserves several sessions when several commit calls are active.
199
+ 3. If no committing session is found, the sessions of the repository written to since the last commit (the last 24 hours in a repository without a commit). This fallback preserves sessions for commits made manually.
200
+
201
+ A session belongs to the repository only when its working directory is inside the repository's checkout: discovery never attaches a session that ran elsewhere, for example a coordinator agent in `~/.nomos/coordinator` whose subagents commit in a worktree. A session named by `TRACEHUB_ID` that ran outside the repository (or one of its worktrees) shares nothing of its own: its trace holds only the subagent runs that changed files of the repository, without the parent's messages or title, and when no subagent changed any, nothing is uploaded and the marker is settled.
202
+
203
+ 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):
204
+
205
+ - 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);
206
+ - for rule 3, an edit of a file in the checkout since the last commit, or a `cwd` inside it.
207
+
208
+ 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.
209
+
210
+ Where the sessions are:
211
+
212
+ - 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.
213
+ - Codex: `~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl`. The first line (`session_meta`) has the `cwd`, which has to be inside the repository. A sub-thread names its parent in `parent_thread_id`.
214
+ - 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.
215
+
216
+ ## Commands
217
+
218
+ | command | does |
219
+ | --- | --- |
220
+ | `setup` | the form: account, permission rules, Git hooks |
221
+ | `uninstall` | removes the global Git hooks, the permission rules and the sign-in; asks about local data |
222
+ | `providers add <name> [--timeout <ms>] -- <command> … {id} …` | registers a context provider |
223
+ | `providers list` | prints the registered providers |
224
+ | `providers remove <name>` | removes a provider |
225
+ | `context add --pr <n> (<provider>:<id> … \| --from <file\|->) [--dry-run]` | attaches context conversations to a pull request |
226
+ | `context remove --pr <n> <provider>:<id>…` | detaches context conversations from a pull request |
227
+
228
+ The hooks run `tracehub hook prepare-commit-msg` and `tracehub hook pre-push`, an internal entry point that `--help` leaves out. `docs/pages/cli-reference.mdx` renders the reference from `src/cli/usage.ts`, as `--help` does.
229
+
230
+ ## Context conversations
231
+
232
+ A context conversation is what asked for the work. TraceHub gets it from a provider, by reference: `<provider>:<id>`, for example `nomos:t_16da1c327635`.
233
+
234
+ ### Providers
235
+
236
+ A provider is a local command that prints the messages of a conversation. Providers are registered in `~/.config/tracehub/providers.json`:
237
+
238
+ ```json
239
+ { "nomos": { "command": ["nomos", "thread", "export", "{id}", "--format", "tracehub"], "timeoutMs": 10000 } }
240
+ ```
241
+
242
+ ```sh
243
+ tracehub providers add nomos -- nomos thread export {id} --format tracehub
244
+ ```
245
+
246
+ - `command` is an argv array, run without a shell; every `{id}` in it is replaced by the conversation's id. A provider name is `[a-z][a-z0-9-]*`; an id is up to 200 characters of `[A-Za-z0-9._:/#@-]` and does not start with `-`.
247
+ - `timeoutMs` (default 10 000) bounds a run; the process is killed after it. Output over 8 MB is refused.
248
+ - It prints a JSON list of messages, oldest first, at most 1000:
249
+
250
+ ```json
251
+ [
252
+ {
253
+ "id": "nomos:t_1:m_1",
254
+ "author": "Simon",
255
+ "text": "Let agents attach the thread to the trace",
256
+ "at": "2026-10-28T05:43:42.843Z",
257
+ "source": { "kind": "nomos", "url": "https://…/?thread=t_1", "label": "Thread title" }
258
+ }
259
+ ]
260
+ ```
261
+
262
+ `id` is optional (without one, an id is made from the author, time, text and url); `source.kind` is a name like a provider's, `url` (http or https) and `label` are optional. The conversation takes its title and url from its first message's `label` and `url`.
263
+ - A provider runs only for a repository a permission rule allows, on upload (and for `context add`), never at commit. Its output is redacted like everything else (the detectors, the deny list, the home directory), then checked by the API's sensitivity model.
264
+ - A provider that fails, times out or prints something invalid is reported in one line (`tracehub: context nomos:t_1: …`); the trace is uploaded without that conversation, and the commit or push goes on. Each conversation is fetched once per upload run.
265
+
266
+ ### Naming the conversation
267
+
268
+ - **In a brief.** `tracehub-context: <provider>:<id>` (several separated by commas) anywhere in the first user message of a session or of a subagent (the prompt its parent gave it), or `<provider>-thread: <id>` for a registered provider, names a conversation. Later messages are not read for tags, and a coordinator that ran outside the repository contributes only its subagents' briefs. A coordinator that spawns a subagent for a thread's work puts the line into the brief; the subagent's trace then carries the thread.
269
+ - **At commit.** `TRACEHUB_CONTEXT=<provider>:<id>[,…]` in the commit's environment names conversations for every session of the commit; the marker keeps them until the push.
270
+ - A reference to an unregistered provider is reported and skipped.
271
+
272
+ ### Attaching to a pull request
273
+
274
+ `tracehub context add --pr <n> nomos:t_1` fetches the conversation from its provider and attaches it to the pull request of the current clone's repository. `--from <file|->` reads the messages, in a provider's format, from a file or stdin instead. Attaching needs the same sign-in, permission rule and `assistant-ui` ownership checks as traces, and push access. Each uploader's are kept apart, merged by conversation and message id, so running the same command again changes nothing. `--dry-run` checks the permission rule, fetches and redacts, prints what would be attached and sends nothing.
275
+
276
+ `tracehub context remove --pr <n> <provider>:<id>…` detaches conversations from the pull request, whoever attached them (a pasted one's ref is `manual:<id>`; the pull request's `.json` lists them), and the page renders again without them. It needs a sign-in with push access to the repository, as attaching does (so the uploader or any maintainer), but no permission rule: nothing is fetched or sent. A ref that is not attached is reported; when none is, it fails.
277
+
278
+ ### nomOS
279
+
280
+ nomOS registers itself as the provider `nomos` (`nomos thread export <thread> --format tracehub` prints all messages of a thread), and nom puts `tracehub-context: nomos:<thread id>` into the brief of each subagent it spawns for a thread's work. A subagent's commits then carry the whole thread.
281
+
282
+ ## Privacy
283
+
284
+ What leaves the machine, for each trace:
285
+
286
+ 1. Only messages and changes: the user's and the agent's text, per-turn file paths with added/removed counts, line hashes (see What a trace holds), and the messages of the context conversations the providers returned.
287
+ 2. Every string is run through the detectors below; a match becomes `[redacted]`.
288
+ 3. The home directory becomes `~`.
289
+
290
+ The agent's own file is never changed. The `pre-push` hook reports what it masked on stderr: `tracehub: claude:<id>: masked 3 findings (high_entropy ×2, long_hex ×1) before upload`.
291
+
292
+ | detector | matches |
293
+ | --- | --- |
294
+ | `deny_list` | a literal of the deny list |
295
+ | `url_credentials` | the password in `scheme://user:password@host` |
296
+ | `pem_block` | `-----BEGIN …-----` to its end, or to the end of the text |
297
+ | `openai_key`, `stripe_key`, `webhook_secret`, `github_token`, `gitlab_token`, `aws_key`, `slack_token`, `google_api_key`, `neon_key`, `pat_token`, `square_token`, `dotted_token` | the token formats of those services, by prefix |
298
+ | `jwt` | `eyJ….….…` |
299
+ | `authorization_header`, `bearer_token`, `basic_auth` | what follows `Authorization:`, `Bearer`, `Basic` |
300
+ | `keyed_assignment` | the value of `<name>_key=`, `token:`, `password=`, `SECRET=` and the like |
301
+ | `long_hex` | 64 or more hex characters |
302
+ | `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 |
303
+ | `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 |
304
+
305
+ ### What the Tracehub API does with a trace or context
306
+
307
+ 1. It runs the detectors once more, and anonymizes home directories (`/Users/alice`, `/home/bob`, `C:\Users\carol`) to `~`.
308
+ 2. It asks [Jev](https://typesafe.ai), TypeSafe's decision model, whether each message holds a secret or personal data that the patterns cannot see: a password in a sentence, a person's address, a company secret.
309
+ 3. A message Jev finds sensitive is stored empty and marked withheld. The hook says how many: `tracehub: claude:<id>: tracehub withheld 2 message(s) that look sensitive`.
310
+ 4. When Jev cannot be reached, the Tracehub API stores nothing and answers 503; the next push tries again.
311
+
312
+ 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.
313
+
314
+ ### Deny list
315
+
316
+ 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.
317
+
318
+ ## Tracehub API
319
+
320
+ `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.
321
+
322
+ | route | does |
323
+ | --- | --- |
324
+ | `PUT /repos/:owner/:repo/traces/:trace/sessions/:name` | stores a session's trace at a commit, replacing the one there |
325
+ | `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 |
326
+ | `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 |
327
+ | `PUT /consent` | registers a machine's permission rules for the signed-in user; `rules: []` forgets the machine |
328
+ | `GET /login`, `/logout`, `/api/auth/callback` | browser sign-in (through the web app) |
329
+ | `POST /github/webhook` | the GitHub App's webhook |
330
+ | `GET /healthz` | `{ok: true}` |
331
+
332
+ 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).
333
+
334
+ 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.
335
+
336
+ The `PUT` routes take `Authorization: Bearer <access token of the GitHub user>` with push access to the repository. The web app's pages (`/t`, `/c`, `/pr`, each with a `.json` twin) take the cookie of the browser sign-in or a bearer GitHub token, and send a signed-out browser to `/login`; `tracehub/README.md` has the page list and the JSON schemas.
337
+
338
+ ### GitHub App (once)
339
+
340
+ The App of the deployed Tracehub API exists; the Tracehub API reads its key from the bucket, `_config/github-app.json` (`{appId, pem, webhookSecret}`).
341
+
342
+ For another deployment, create an App in the GitHub organization:
343
+
344
+ - Permissions: pull requests: write, checks: write (the TraceHub traces check), contents: read, metadata: read. Events: pull request, push. Webhook `<tracehub>/github/webhook`.
345
+ - Callback URL `<tracehub>/api/auth/callback`, for the browser sign-in.
346
+ - Device flow enabled, for the sign-in of `tracehub setup`.
347
+ - A client secret, for the browser sign-in.
348
+
349
+ Install it on the repositories, 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:
350
+
351
+ ```sh
352
+ cd tracehub
353
+ npx wrangler secret put GITHUB_CLIENT_SECRET
354
+ printf %s "<app id>" | npx wrangler secret put GITHUB_APP_ID
355
+ npx wrangler secret put GITHUB_APP_PRIVATE_KEY < <app>.private-key.pem
356
+ printf %s "<webhook secret>" | npx wrangler secret put GITHUB_WEBHOOK_SECRET
357
+ ```
358
+
359
+ ### The TraceHub traces check
360
+
361
+ The App reports a check run named **TraceHub traces** on commits of `assistant-ui` repositories that have a known trace, that is an uploaded session marked by a trace id the commit message names. It is always a success; where there is no known trace, nothing is reported.
362
+
363
+ - A pull request's head commit gets it when at least one of the pull request's current commits has a known trace; the output lists the traces of all of them.
364
+ - Any other commit gets it when it has a known trace itself: on a push, and when a trace upload attaches a trace to a commit TraceHub has seen.
365
+ - The output lists each attached trace with a link to its TraceHub page, its agent and its number of sessions; the run's details link goes to the pull request's (or the trace's) TraceHub page.
366
+ - A trace attached later, by an upload, posts the check then, on the pull request heads and commits the index knows for the trace.
367
+ - An unchanged check is not written again; a changed one updates the same check run. A check run already on a commit without a known trace is left as it is.
368
+
369
+ The check can be required, in the repository's (or the organization's) **Settings → Rules → Rulesets**: a branch ruleset for the default branch with **Require status checks to pass** and the check **TraceHub traces** (pick the TraceHub App as its source), or with classic branch protection, **Settings → Branches → Branch protection rule → Require status checks to pass before merging → TraceHub traces**. Then only pull requests with a known trace can be merged: one without never gets the check, so it stays waiting for it. The check must have run once on the repository before GitHub offers it.
370
+
371
+ ## Trying it end to end
372
+
373
+ Do not try it with the session you are working in: what is uploaded stays in the bucket. Use a throwaway session and force it:
374
+
375
+ ```sh
376
+ gh repo create assistant-ui/tracehub-playground --private --clone && cd tracehub-playground
377
+ npx --yes tracehub@0.5.0 setup # allow this repository, install the hooks
378
+
379
+ # open a fresh agent session in this directory, ask it for something harmless
380
+ export TRACEHUB_ID=claude:<throwaway session id>
381
+
382
+ git commit --allow-empty -m "trial"
383
+ git push -u origin main # uploads the trace
384
+ unset TRACEHUB_ID
385
+ ```
386
+
387
+ ## Why a random trailer
388
+
389
+ - A sha changes under amend, rebase and squash-merge, and a squash-merge happens on GitHub, where no hook runs.
390
+ - A session id is stable, but it would publish which session each contributor ran, and one session spans several commits.
391
+ - A random id is stable, says nothing, and git carries it along in the message.
392
+
393
+ ## Develop
394
+
395
+ 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.
396
+
397
+ ```sh
398
+ npm run format:fix && npm run typecheck && npm test
399
+ cd tracehub && npm test
400
+ ```
401
+
402
+ Tests are in `test/` and `tracehub/test/`, fixtures in `fixtures/`. The end-to-end tests run the built CLI against the real Tracehub API over an in-memory bucket (`test/support/fakeTracehub.ts`); nothing in the tests reads a real session.
403
+
404
+ 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.
405
+
406
+ A release is a tag:
407
+
408
+ 1. Set the version in `package.json` (`npm version <x.y.z> --no-git-tag-version`), and the `tracehub@<version>` commands in this README.
409
+ 2. Commit and push to `main`, and wait for CI.
410
+ 3. `git tag v<version> && git push origin v<version>`.
411
+
412
+ `.github/workflows/npm-publish.yaml` checks that the tag matches `package.json`, runs the tests, packs the tarball and publishes it with provenance as the package's trusted publisher (GitHub OIDC, no npm token), from the `npm` environment. Optionally add release notes: `gh release create v<version> --generate-notes`. On npmjs.com the package's trusted publisher is GitHub Actions, organization `assistant-ui`, repository `tracehub`, workflow `npm-publish.yaml`, environment `npm`.
413
+
414
+ ## Audiences and data handling
415
+
416
+ A trace and the context of a pull request are for their uploader and the repository's maintainers: current GitHub **write, maintain or admin** access to the exact repository, including outside collaborators. Organization membership alone and read/triage access do not qualify; everyone else, signed in or not, sees nothing. Tracehub asks GitHub, as its App, for the repository's collaborators with push access; that list is cached for a minute (served up to 10 minutes while it refreshes), and lookup errors fail closed.
417
+
418
+ | Destination | Sent | Omitted / protected |
419
+ | --- | --- | --- |
420
+ | GitHub | Ordinary pushed commits/code, random `Assisted-by` trace ID trailer, bot PR-link block, authentication/access requests | No trace or prompt is sent to GitHub; GitHub still contains the actual committed code |
421
+ | Tracehub storage | Redacted messages per turn, per-turn file paths and counts, subagent runs' messages and changes, line-hash sourcemaps, context conversations from providers | Tool calls and results, thinking, metrics, local paths, the parent of a session that ran outside the repository; detected secrets masked, sensitive messages withheld |
422
+ | Maintainers | Messages, changes, context conversations, the line map | Nothing else is stored to show |
423
+ | TypeSafe sensitivity service, when configured | Already pattern-redacted messages and context messages | Its retention/access terms need operational review |
424
+
425
+ Secret detection is best effort, not a guarantee. Never put credentials into a conversation an agent commits from; masking cannot protect every unknown format or personal detail. Stored traces have no deletion UI yet.
@@ -0,0 +1,28 @@
1
+ // Flags that take a value: `--pr 12` or `--pr=12`.
2
+ const VALUE_FLAGS = new Set(["pr", "from", "timeout"]);
3
+ export function parseArgs(argv) {
4
+ const positional = [];
5
+ const flags = {};
6
+ for (let i = 0; i < argv.length; i++) {
7
+ const arg = argv[i];
8
+ if (arg === "--")
9
+ return { positional, flags, rest: argv.slice(i + 1) };
10
+ if (!arg.startsWith("--")) {
11
+ positional.push(arg);
12
+ continue;
13
+ }
14
+ const [name, value] = arg.slice(2).split(/=(.*)/s, 2);
15
+ if (value !== undefined)
16
+ flags[name] = value;
17
+ else if (VALUE_FLAGS.has(name) && i + 1 < argv.length)
18
+ flags[name] = argv[++i];
19
+ else
20
+ flags[name] = true;
21
+ }
22
+ return { positional, flags, rest: [] };
23
+ }
24
+ // A flag's value, when it was given one.
25
+ export function flagValue(args, name) {
26
+ const value = args.flags[name];
27
+ return typeof value === "string" ? value : undefined;
28
+ }
@@ -0,0 +1,46 @@
1
+ import { spawn } from "node:child_process";
2
+ import { ENV_TEST } from "../local/paths.js";
3
+ // The commands that put stdin on the clipboard, in the order tried.
4
+ function candidates() {
5
+ if (process.platform === "darwin")
6
+ return [["pbcopy", []]];
7
+ if (process.platform === "win32")
8
+ return [["clip", []]];
9
+ return [
10
+ ...(process.env["WAYLAND_DISPLAY"]
11
+ ? [["wl-copy", []]]
12
+ : []),
13
+ ["xclip", ["-selection", "clipboard"]],
14
+ ["xsel", ["--clipboard", "--input"]],
15
+ ];
16
+ }
17
+ function run(command, args, text) {
18
+ return new Promise((resolve) => {
19
+ const child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] });
20
+ const timer = setTimeout(() => {
21
+ child.kill();
22
+ resolve(false);
23
+ }, 2000);
24
+ child.on("error", () => {
25
+ clearTimeout(timer);
26
+ resolve(false);
27
+ });
28
+ child.on("exit", (code) => {
29
+ clearTimeout(timer);
30
+ resolve(code === 0);
31
+ });
32
+ child.stdin.on("error", () => { });
33
+ child.stdin.end(text);
34
+ });
35
+ }
36
+ // Copies `text` to the clipboard; false when no clipboard command worked.
37
+ // Never under the test runner, which must not touch the user's clipboard.
38
+ export async function copyToClipboard(text) {
39
+ if (process.env[ENV_TEST] !== undefined ||
40
+ process.env["NODE_TEST_CONTEXT"] !== undefined)
41
+ return false;
42
+ for (const [command, args] of candidates())
43
+ if (await run(command, args, text))
44
+ return true;
45
+ return false;
46
+ }
@@ -0,0 +1,115 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { freshAuth } from "../../client/auth.js";
3
+ import { tracehubUrl } from "../../client/tracehub.js";
4
+ import { UPLOAD_POLICY_ERROR } from "../../client/uploadPolicy.js";
5
+ import { fetchContext, manualConversations } from "../../local/providers.js";
6
+ import { mergeConversations, parseContextRef, } from "../../protocol/context.js";
7
+ import { formatFindings, redactValue } from "../../redact/redact.js";
8
+ import { flagValue } from "../args.js";
9
+ import { out, warn } from "../io.js";
10
+ import { clientFor, redactOptions, usableAuth } from "../remote.js";
11
+ import { consentFor, uploadTargetFor } from "../repo.js";
12
+ import { commandUsage } from "../usage.js";
13
+ // stdin read as a stream: a pipe can be non-blocking, which readFileSync(0)
14
+ // answers with EAGAIN.
15
+ async function readStdin() {
16
+ const chunks = [];
17
+ for await (const chunk of process.stdin)
18
+ chunks.push(chunk);
19
+ return Buffer.concat(chunks).toString("utf8");
20
+ }
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
+ // The conversations to attach: from their providers or the file, merged,
28
+ // redacted.
29
+ async function conversationsOf(args, allowed) {
30
+ const refs = args.positional.slice(2);
31
+ const from = flagValue(args, "from");
32
+ if (!refs.length && !from)
33
+ throw new Error('name a conversation (<provider>:<id>) or --from <file|->; "-" reads stdin');
34
+ const lists = [];
35
+ if (from) {
36
+ const text = from === "-" ? await readStdin() : readFileSync(from, "utf8");
37
+ lists.push(manualConversations(text));
38
+ }
39
+ for (const ref of refs) {
40
+ try {
41
+ lists.push([await fetchContext(ref, allowed)]);
42
+ }
43
+ catch (err) {
44
+ throw new Error(`context ${ref}: ${err.message}`);
45
+ }
46
+ }
47
+ return mergeConversations(lists);
48
+ }
49
+ async function add(args, cwd) {
50
+ const pr = prOf(args);
51
+ const target = uploadTargetFor(cwd);
52
+ if (!target)
53
+ throw new Error(UPLOAD_POLICY_ERROR);
54
+ // The rule comes first: no provider runs for a repository without one.
55
+ if (consentFor(cwd) !== true)
56
+ throw new Error(`no permission rule allows uploads for ${target.owner}/${target.repo}; run "tracehub setup"`);
57
+ const redacted = redactValue(await conversationsOf(args, true), redactOptions());
58
+ const context = redacted.value;
59
+ if (redacted.findings.length)
60
+ warn(`masked ${formatFindings(redacted.findings)} before upload`);
61
+ const where = `${target.owner}/${target.repo}#${pr}`;
62
+ const count = context.reduce((n, c) => n + c.messages.length, 0);
63
+ if (args.flags["dry-run"]) {
64
+ out(`would attach ${context.length} conversation(s), ${count} message(s), to ${where}:`);
65
+ out(JSON.stringify(context, null, 2));
66
+ return;
67
+ }
68
+ const stored = usableAuth();
69
+ if (!stored)
70
+ throw new Error('not signed in; run "tracehub setup"');
71
+ const client = clientFor(await freshAuth(stored));
72
+ const result = await client.putContext(target, pr, context);
73
+ if (result.withheld)
74
+ warn(`tracehub withheld ${result.withheld} message(s) that look sensitive`);
75
+ out(`attached ${context.length} conversation(s), ${count} message(s), to ${where}`);
76
+ out(`${tracehubUrl()}/pr/${target.owner}/${target.repo}/${pr}`);
77
+ }
78
+ // Detaches conversations from the pull request: the uploader's or, for a
79
+ // maintainer, anyone's. Nothing is fetched or uploaded, so no permission
80
+ // rule is needed; the API checks push access as it does for add.
81
+ async function remove(args, cwd) {
82
+ const pr = prOf(args);
83
+ const refs = [...new Set(args.positional.slice(2))];
84
+ if (!refs.length)
85
+ throw new Error("name a conversation to remove (<provider>:<id>)");
86
+ for (const ref of refs)
87
+ if (!parseContextRef(ref))
88
+ throw new Error(`"${ref}" is not a conversation (<provider>:<id>)`);
89
+ const target = uploadTargetFor(cwd);
90
+ if (!target)
91
+ throw new Error(UPLOAD_POLICY_ERROR);
92
+ const where = `${target.owner}/${target.repo}#${pr}`;
93
+ const stored = usableAuth();
94
+ if (!stored)
95
+ throw new Error('not signed in; run "tracehub setup"');
96
+ const client = clientFor(await freshAuth(stored));
97
+ const { removed } = await client.deleteContext(target, pr, refs);
98
+ for (const ref of refs)
99
+ if (!removed.includes(ref))
100
+ warn(`${ref} is not attached to ${where}`);
101
+ out(`removed ${removed.length} conversation(s) from ${where}`);
102
+ out(`${tracehubUrl()}/pr/${target.owner}/${target.repo}/${pr}`);
103
+ }
104
+ export async function cmdContext(args, cwd) {
105
+ const sub = args.positional[1];
106
+ if (args.flags["help"] || args.flags["h"] || !sub) {
107
+ out(commandUsage("context"));
108
+ return;
109
+ }
110
+ if (sub === "add")
111
+ return add(args, cwd);
112
+ if (sub === "remove")
113
+ return remove(args, cwd);
114
+ throw new Error(`unknown context command "${sub}"; use add or remove`);
115
+ }