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
@@ -0,0 +1,283 @@
1
+ import { closeSync, existsSync, openSync, readFileSync, readSync, realpathSync, } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { parseClaude } from "../transcript/parseClaude.js";
4
+ import { codexSessionMeta } from "../transcript/parseCodex.js";
5
+ import { openCommitCalls } from "./commitBoundary.js";
6
+ import { fileEntry, firstLineOf, listDir } from "./files.js";
7
+ import { completeLines } from "./lines.js";
8
+ import { hasOpencodeSession, listOpencodeSessions, } from "./opencode.js";
9
+ import { claudeProjectsDir, codexSessionsDir, encodeClaudeCwd, home, opencodeDb, } from "./paths.js";
10
+ const DAY_MS = 24 * 60 * 60 * 1000;
11
+ // How far back a repository without a commit looks for sessions.
12
+ export const ROOT_COMMIT_WINDOW_MS = DAY_MS;
13
+ const UUID = "[0-9a-f-]{36}";
14
+ const CLAUDE_FILE = new RegExp(`(${UUID})\\.jsonl$`, "i");
15
+ export function claudeIdFromFile(file) {
16
+ return CLAUDE_FILE.exec(file)?.[1];
17
+ }
18
+ export function isUnderRoot(cwd, root) {
19
+ const base = root.replace(/\/+$/, "");
20
+ return cwd === base || cwd.startsWith(`${base}/`);
21
+ }
22
+ function real(path) {
23
+ try {
24
+ return realpathSync(path);
25
+ }
26
+ catch {
27
+ return path;
28
+ }
29
+ }
30
+ // Whether a session's working directory is inside the repository. A
31
+ // session that ran elsewhere (a coordinator whose subagents commit in a
32
+ // worktree) is never attached by discovery; TRACEHUB_ID still can.
33
+ export function ranInside(cwd, root) {
34
+ return isUnderRoot(cwd, root) || isUnderRoot(real(cwd), real(root));
35
+ }
36
+ // The sessions written to since the last commit, newest first. A session
37
+ // belongs to the repository when it ran inside it.
38
+ export function selectActiveSessions(input) {
39
+ const { repoRoot, sinceMs } = input;
40
+ const active = [];
41
+ for (const { file, mtimeMs, cwd } of input.claudeFiles) {
42
+ const id = claudeIdFromFile(file);
43
+ if (id && mtimeMs > sinceMs && (!cwd || ranInside(cwd, repoRoot))) {
44
+ active.push({ agent: "claude", id, file, mtimeMs });
45
+ }
46
+ }
47
+ for (const sub of input.claudeSubagents) {
48
+ if (sub.mtimeMs > sinceMs && (sub.committing || sub.wrote)) {
49
+ const { id, file, mtimeMs, committing } = sub;
50
+ active.push({ agent: "claude", id, file, mtimeMs, committing });
51
+ }
52
+ }
53
+ for (const { file, mtimeMs, id, cwd } of input.codexFiles) {
54
+ if (mtimeMs > sinceMs && ranInside(cwd, repoRoot)) {
55
+ active.push({ agent: "codex", id, file, mtimeMs });
56
+ }
57
+ }
58
+ for (const { id, cwd, mtimeMs } of input.opencodeSessions) {
59
+ if (mtimeMs > sinceMs && ranInside(cwd, repoRoot)) {
60
+ active.push({ agent: "opencode", id, file: opencodeDb(), mtimeMs });
61
+ }
62
+ }
63
+ return active.sort((a, b) => b.mtimeMs - a.mtimeMs);
64
+ }
65
+ // The cwd of the first line of a Claude Code session that has one.
66
+ export function claudeCwd(file) {
67
+ let head = "";
68
+ try {
69
+ const fd = openSync(file, "r");
70
+ try {
71
+ const chunk = Buffer.alloc(256 * 1024);
72
+ head = chunk
73
+ .subarray(0, readSync(fd, chunk, 0, chunk.length, 0))
74
+ .toString("utf8");
75
+ }
76
+ finally {
77
+ closeSync(fd);
78
+ }
79
+ }
80
+ catch {
81
+ return "";
82
+ }
83
+ for (const line of head.split("\n")) {
84
+ if (!line.includes('"cwd"'))
85
+ continue;
86
+ try {
87
+ const cwd = JSON.parse(line).cwd;
88
+ if (typeof cwd === "string" && cwd)
89
+ return cwd;
90
+ }
91
+ catch {
92
+ continue;
93
+ }
94
+ }
95
+ return "";
96
+ }
97
+ // ~/.claude/projects/<encoded cwd>/<session id>.jsonl
98
+ function listClaudeFiles(repoRoot) {
99
+ const dir = join(claudeProjectsDir(), encodeClaudeCwd(repoRoot));
100
+ return listDir(dir)
101
+ .filter((name) => name.endsWith(".jsonl"))
102
+ .map((name) => fileEntry(join(dir, name)))
103
+ .filter((entry) => entry !== undefined)
104
+ .map((entry) => ({ ...entry, cwd: claudeCwd(entry.file) }));
105
+ }
106
+ // A Claude Code subagent's transcript is filed under the project of the
107
+ // session that launched it, in <project>/<session id>/subagents/, and
108
+ // its own lines keep that session's cwd. A coordinator in one directory
109
+ // whose subagents work and commit in another repository's worktree is
110
+ // the case: the subagent is found by what it did there.
111
+ export const CLAUDE_SUBAGENT_PREFIX = "agent-";
112
+ export function isClaudeSubagent(ref) {
113
+ return ref.agent === "claude" && ref.id.startsWith(CLAUDE_SUBAGENT_PREFIX);
114
+ }
115
+ // ~/.claude/projects/*/<session id>/subagents/agent-<id>.jsonl, for the
116
+ // files written to since sinceMs.
117
+ function* walkClaudeSubagentFiles(sinceMs) {
118
+ const base = claudeProjectsDir();
119
+ for (const project of listDir(base)) {
120
+ for (const session of listDir(join(base, project))) {
121
+ if (session.endsWith(".jsonl"))
122
+ continue;
123
+ const dir = join(base, project, session, "subagents");
124
+ for (const name of listDir(dir)) {
125
+ if (!/^agent-[A-Za-z0-9_-]+\.jsonl$/.test(name))
126
+ continue;
127
+ const entry = fileEntry(join(dir, name));
128
+ if (!entry || entry.mtimeMs <= sinceMs)
129
+ continue;
130
+ const parent = join(base, project, `${session}.jsonl`);
131
+ yield { ...entry, id: name.slice(0, -".jsonl".length), parent };
132
+ }
133
+ }
134
+ }
135
+ }
136
+ // The ways a command can name the repository's checkout.
137
+ function spellings(root) {
138
+ const forms = new Set([root, real(root)]);
139
+ const h = home();
140
+ for (const form of [...forms])
141
+ if (form.startsWith(`${h}/`))
142
+ forms.add(`~${form.slice(h.length)}`);
143
+ return [...forms];
144
+ }
145
+ // Whether a text names the checkout or a path in it.
146
+ function mentions(text, root) {
147
+ return spellings(root).some((form) => {
148
+ for (let at = text.indexOf(form); at !== -1; at = text.indexOf(form, at + 1)) {
149
+ const next = text[at + form.length];
150
+ if (next === undefined || /[\s/"';&|)]/.test(next))
151
+ return true;
152
+ }
153
+ return false;
154
+ });
155
+ }
156
+ // A command that runs somewhere other than the agent's cwd.
157
+ const CHANGES_DIR = /(?:^|[\s;&|(])(?:cd|pushd)\s|\s-C\s/;
158
+ // What a subagent's transcript did in the repository. Its commit call runs
159
+ // in the repository when its command names the checkout, or changes no
160
+ // directory and the subagent runs inside it (a worktree-isolated agent).
161
+ export function subagentWork(lines, root, sinceMs) {
162
+ const t = parseClaude(lines, "", { sidechain: true });
163
+ const inside = !!t.cwd && ranInside(t.cwd, root);
164
+ const committing = openCommitCalls("claude", lines, true).some(({ command }) => mentions(command, root) || (inside && !CHANGES_DIR.test(command)));
165
+ const wrote = inside ||
166
+ t.events.some((e) => e.kind === "tool_call" &&
167
+ !(Date.parse(e.ts) <= sinceMs) &&
168
+ (e.edits ?? []).some((edit) => isAbsolute(edit.path) && ranInside(edit.path, root)));
169
+ return { committing, wrote };
170
+ }
171
+ // How far back subagents filed under other projects are read: they are
172
+ // read whole, so only the recent ones.
173
+ export const SUBAGENT_WINDOW_MS = DAY_MS;
174
+ // The subagents of sessions that ran outside the repository, written to
175
+ // recently, that name the repository somewhere. A subagent of a session
176
+ // inside it is a run of that session's trace instead.
177
+ function listClaudeSubagents(repoRoot, sinceMs) {
178
+ const from = Math.max(sinceMs, Date.now() - SUBAGENT_WINDOW_MS);
179
+ const parents = new Map();
180
+ const found = [];
181
+ for (const entry of walkClaudeSubagentFiles(from)) {
182
+ if (!parents.has(entry.parent)) {
183
+ const cwd = claudeCwd(entry.parent);
184
+ parents.set(entry.parent, !!cwd && ranInside(cwd, repoRoot));
185
+ }
186
+ if (parents.get(entry.parent))
187
+ continue;
188
+ let text;
189
+ try {
190
+ text = readFileSync(entry.file, "utf8");
191
+ }
192
+ catch {
193
+ continue;
194
+ }
195
+ if (!mentions(text, repoRoot))
196
+ continue;
197
+ const work = subagentWork(completeLines(text), repoRoot, sinceMs);
198
+ found.push({
199
+ file: entry.file,
200
+ mtimeMs: entry.mtimeMs,
201
+ id: entry.id,
202
+ ...work,
203
+ });
204
+ }
205
+ return found;
206
+ }
207
+ // "2026/09/04", which sorts like the date it names.
208
+ function dayKey(ms) {
209
+ return new Date(ms).toISOString().slice(0, 10).replaceAll("-", "/");
210
+ }
211
+ // ~/.codex/sessions/<yyyy>/<mm>/<dd>/rollout-<time>-<session id>.jsonl, for
212
+ // the files written to since sinceMs. A session is filed under the day it
213
+ // started, so the day before is walked too.
214
+ export function* walkCodexFiles(sinceMs) {
215
+ const base = codexSessionsDir();
216
+ const firstDay = dayKey(Math.max(0, sinceMs - DAY_MS));
217
+ for (const year of listDir(base)) {
218
+ for (const month of listDir(join(base, year))) {
219
+ for (const day of listDir(join(base, year, month))) {
220
+ if (`${year}/${month}/${day}` < firstDay)
221
+ continue;
222
+ const dir = join(base, year, month, day);
223
+ for (const name of listDir(dir)) {
224
+ const isRollout = /^rollout-.*\.jsonl$/.test(name);
225
+ if (!isRollout)
226
+ continue;
227
+ const entry = fileEntry(join(dir, name));
228
+ if (entry && entry.mtimeMs > sinceMs)
229
+ yield entry;
230
+ }
231
+ }
232
+ }
233
+ }
234
+ }
235
+ function listCodexFiles(sinceMs) {
236
+ const files = [];
237
+ for (const entry of walkCodexFiles(sinceMs)) {
238
+ const meta = codexSessionMeta(firstLineOf(entry.file));
239
+ if (meta)
240
+ files.push({ ...entry, id: meta.id, cwd: meta.cwd });
241
+ }
242
+ return files;
243
+ }
244
+ export function discoverActiveSessions(repoRoot, sinceMs) {
245
+ return selectActiveSessions({
246
+ repoRoot,
247
+ sinceMs,
248
+ claudeFiles: listClaudeFiles(repoRoot),
249
+ claudeSubagents: listClaudeSubagents(repoRoot, sinceMs),
250
+ codexFiles: listCodexFiles(sinceMs),
251
+ opencodeSessions: listOpencodeSessions(sinceMs),
252
+ });
253
+ }
254
+ function findClaudeFile(id) {
255
+ if (id.startsWith(CLAUDE_SUBAGENT_PREFIX)) {
256
+ for (const entry of walkClaudeSubagentFiles(-Infinity))
257
+ if (entry.id === id)
258
+ return entry.file;
259
+ return undefined;
260
+ }
261
+ const base = claudeProjectsDir();
262
+ return listDir(base)
263
+ .map((project) => join(base, project, `${id}.jsonl`))
264
+ .find((file) => existsSync(file));
265
+ }
266
+ function findCodexFile(id) {
267
+ for (const { file } of walkCodexFiles(0)) {
268
+ if (file.endsWith(`-${id}.jsonl`))
269
+ return file;
270
+ }
271
+ return undefined;
272
+ }
273
+ // The file a session is kept in; nothing when it is not on this machine.
274
+ export function findSessionFile(ref) {
275
+ switch (ref.agent) {
276
+ case "claude":
277
+ return findClaudeFile(ref.id);
278
+ case "codex":
279
+ return findCodexFile(ref.id);
280
+ case "opencode":
281
+ return hasOpencodeSession(ref.id) ? opencodeDb() : undefined;
282
+ }
283
+ }
@@ -0,0 +1,55 @@
1
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync, } from "node:fs";
2
+ // A JSON object read from a file; anything else (missing, malformed, an
3
+ // array) reads as an empty object.
4
+ export function readJsonObject(file) {
5
+ if (!existsSync(file))
6
+ return {};
7
+ try {
8
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
9
+ const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
10
+ return isObject ? parsed : {};
11
+ }
12
+ catch {
13
+ return {};
14
+ }
15
+ }
16
+ // The names in a directory; none when it is missing or unreadable.
17
+ export function listDir(dir) {
18
+ try {
19
+ return readdirSync(dir);
20
+ }
21
+ catch {
22
+ return [];
23
+ }
24
+ }
25
+ // The file with its modification time; nothing when it is gone or not a file.
26
+ export function fileEntry(file) {
27
+ try {
28
+ const stat = statSync(file);
29
+ return stat.isFile() ? { file, mtimeMs: stat.mtimeMs } : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ const NEWLINE = 10;
36
+ // The first line without reading the rest, since session files grow large.
37
+ export function firstLineOf(file) {
38
+ const fd = openSync(file, "r");
39
+ try {
40
+ const chunk = Buffer.alloc(64 * 1024);
41
+ const parts = [];
42
+ for (;;) {
43
+ const read = readSync(fd, chunk, 0, chunk.length, null);
44
+ const bytes = chunk.subarray(0, read);
45
+ const end = bytes.indexOf(NEWLINE);
46
+ parts.push(Buffer.from(end === -1 ? bytes : bytes.subarray(0, end)));
47
+ if (read === 0 || end !== -1)
48
+ break;
49
+ }
50
+ return Buffer.concat(parts).toString("utf8");
51
+ }
52
+ finally {
53
+ closeSync(fd);
54
+ }
55
+ }
@@ -0,0 +1,16 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { opencodeLines } from "./opencode.js";
3
+ // Claude Code and Codex keep a session in a file of its own; OpenCode keeps
4
+ // all of them in one database.
5
+ // The lines of a session that are complete.
6
+ export function sessionLines(ref, file) {
7
+ if (ref.agent === "opencode")
8
+ return opencodeLines(ref.id);
9
+ return completeLines(readFileSync(file, "utf8"));
10
+ }
11
+ // Only lines the agent finished writing count: a torn trailing line waits
12
+ // for the next look.
13
+ export function completeLines(text) {
14
+ const end = text.lastIndexOf("\n");
15
+ return end === -1 ? [] : text.slice(0, end).split("\n");
16
+ }
@@ -0,0 +1,124 @@
1
+ import { existsSync } from "node:fs";
2
+ import { opencodeDb } from "./paths.js";
3
+ import { isCommitCommand } from "./commitBoundary.js";
4
+ // The rows a query finds in OpenCode's database; none without a database.
5
+ // SQLite is loaded on first use, so only a machine with OpenCode loads it.
6
+ function query(sql, ...params) {
7
+ const file = opencodeDb();
8
+ if (!existsSync(file))
9
+ return [];
10
+ const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
11
+ const db = new DatabaseSync(file, { readOnly: true });
12
+ try {
13
+ return db.prepare(sql).all(...params);
14
+ }
15
+ finally {
16
+ db.close();
17
+ }
18
+ }
19
+ // The sessions a human started that were written to since sinceMs. The
20
+ // database is one file, so the time of a session is that of its newest part.
21
+ export function listOpencodeSessions(sinceMs) {
22
+ const rows = query(`select s.id, s.directory, max(p.time_updated) as written
23
+ from part p join session s on s.id = p.session_id
24
+ where p.time_updated > ? and s.parent_id is null
25
+ group by s.id`, sinceMs);
26
+ return rows.map((row) => ({
27
+ id: String(row["id"]),
28
+ cwd: String(row["directory"]),
29
+ mtimeMs: Number(row["written"]),
30
+ }));
31
+ }
32
+ export function hasOpencodeSession(id) {
33
+ return query("select id from session where id = ?", id).length > 0;
34
+ }
35
+ // Running parts are omitted from the stable JSONL prefix, but the commit
36
+ // hook still needs the identity of the tool whose result will follow it.
37
+ export function opencodePendingCommitCall(id) {
38
+ const parts = query(`select data from part where session_id = ?
39
+ and json_extract(data, '$.type') = 'tool'
40
+ and json_extract(data, '$.state.status') in ('pending', 'running')
41
+ order by id desc`, id);
42
+ for (const row of parts) {
43
+ const part = parse(row["data"]);
44
+ const command = part.state?.input?.command;
45
+ if (typeof command === "string" && isCommitCommand(command))
46
+ return part.callID;
47
+ }
48
+ return undefined;
49
+ }
50
+ function parse(data) {
51
+ return JSON.parse(String(data));
52
+ }
53
+ // A part that OpenCode is still writing: a tool call that has not ended, or
54
+ // text that is still streaming.
55
+ function isOpen(part) {
56
+ if (part["type"] === "tool") {
57
+ const state = part["state"];
58
+ return state?.status === "pending" || state?.status === "running";
59
+ }
60
+ const time = part["time"];
61
+ return time?.start !== undefined && time.end === undefined;
62
+ }
63
+ // What of a message never changes once it is written.
64
+ const MESSAGE_KEYS = ["role", "agent", "model", "modelID", "providerID"];
65
+ function messageLine(row) {
66
+ const data = parse(row["data"]);
67
+ const kept = MESSAGE_KEYS.filter((key) => key in data);
68
+ return {
69
+ type: "message",
70
+ id: row["id"],
71
+ time: row["time_created"],
72
+ ...Object.fromEntries(kept.map((key) => [key, data[key]])),
73
+ };
74
+ }
75
+ // A session as lines, in the order it was written: the session, then each
76
+ // message followed by its parts. The lines end before the first part of the
77
+ // last message that OpenCode is still writing, so a line stays as it is
78
+ // once it is there.
79
+ export function opencodeLines(id) {
80
+ const [session] = query("select id, parent_id, directory, time_created from session where id = ?", id);
81
+ if (!session)
82
+ return [];
83
+ const messages = query("select id, time_created, data from message where session_id = ? order by id", id);
84
+ const parts = query("select id, message_id, data from part where session_id = ? order by id", id);
85
+ const lastMessage = messages.at(-1)?.["id"];
86
+ const lines = [
87
+ {
88
+ type: "session",
89
+ id: session["id"],
90
+ cwd: session["directory"],
91
+ time: session["time_created"],
92
+ ...(session["parent_id"] ? { parent: session["parent_id"] } : {}),
93
+ },
94
+ ];
95
+ read: for (const message of messages) {
96
+ lines.push(messageLine(message));
97
+ for (const row of parts) {
98
+ if (row["message_id"] !== message["id"])
99
+ continue;
100
+ const part = parse(row["data"]);
101
+ if (message["id"] === lastMessage && isOpen(part))
102
+ break read;
103
+ lines.push({ ...part, id: row["id"], message: message["id"] });
104
+ }
105
+ }
106
+ return lines.map((line) => JSON.stringify(line));
107
+ }
108
+ // The sessions a session launched with its task tool. The part of the call
109
+ // names the session it started and the kind of agent it asked for.
110
+ export function listOpencodeSubagents(id) {
111
+ const tasks = query(`select data from part
112
+ where session_id = ? and json_extract(data, '$.tool') = 'task'`, id).map((row) => parse(row["data"]));
113
+ const children = query("select id from session where parent_id = ? order by id", id);
114
+ return children.map((row) => {
115
+ const child = String(row["id"]);
116
+ const task = tasks.find((t) => t.state?.metadata?.sessionId === child);
117
+ return {
118
+ id: child,
119
+ kind: task?.state?.input?.subagent_type ?? "subagent",
120
+ file: opencodeDb(),
121
+ ...(task?.callID ? { toolUseId: task.callID } : {}),
122
+ };
123
+ });
124
+ }
@@ -0,0 +1,51 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ export const GIT_STATE_DIR = "tracehub";
4
+ export const ENV_SESSION_ID = "TRACEHUB_ID";
5
+ export const ENV_DISABLE = "TRACEHUB";
6
+ // Context refs for every session of a commit: `<provider>:<id>[,…]`.
7
+ export const ENV_CONTEXT = "TRACEHUB_CONTEXT";
8
+ export const ENV_TEST = "TRACEHUB_TEST";
9
+ // Under ENV_TEST only: how long a push waits for its upload, in ms.
10
+ export const ENV_TEST_PUSH_BUDGET = "TRACEHUB_TEST_PUSH_BUDGET_MS";
11
+ // Under the test runner every path that could reach the user's own files
12
+ // must come from an override, so a test that drops one fails loudly instead
13
+ // of reading or deleting a real login.
14
+ function override(name) {
15
+ const value = process.env[name];
16
+ if (value === undefined &&
17
+ (process.env[ENV_TEST] !== undefined ||
18
+ process.env["NODE_TEST_CONTEXT"] !== undefined)) {
19
+ throw new Error(`${name} must be set while ${ENV_TEST} or NODE_TEST_CONTEXT is`);
20
+ }
21
+ return value;
22
+ }
23
+ export function home() {
24
+ return override("TRACEHUB_HOME") ?? homedir();
25
+ }
26
+ export function claudeProjectsDir() {
27
+ return join(home(), ".claude", "projects");
28
+ }
29
+ export function codexSessionsDir() {
30
+ return join(home(), ".codex", "sessions");
31
+ }
32
+ // OpenCode keeps every session in one SQLite database.
33
+ export function opencodeDb() {
34
+ return join(home(), ".local", "share", "opencode", "opencode.db");
35
+ }
36
+ export function configDir() {
37
+ const base = override("XDG_CONFIG_HOME") ?? join(home(), ".config");
38
+ return join(base, "tracehub");
39
+ }
40
+ export function consentFile() {
41
+ return join(configDir(), "consent.json");
42
+ }
43
+ export function providersFile() {
44
+ return join(configDir(), "providers.json");
45
+ }
46
+ // Claude Code names a project directory after its cwd with every character
47
+ // outside [A-Za-z0-9-] replaced by "-" ("/", "." and "_" included), so
48
+ // "/Users/me/my.app_v2" becomes "-Users-me-my-app-v2".
49
+ export function encodeClaudeCwd(cwd) {
50
+ return cwd.replace(/[^A-Za-z0-9-]/g, "-");
51
+ }