tracehub 0.5.9 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -78,7 +78,7 @@ Everything is computed on the developer's machine, redacted there, checked again
78
78
  Set it up once with `setup` (the other commands are under [Commands](#commands)). Run it in your terminal:
79
79
 
80
80
  ```sh
81
- npx --yes tracehub@0.5.9 setup
81
+ npx --yes tracehub@0.5.10 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.9`, then `tracehub setup`.
92
+ To skip npx on every commit, install it globally instead: `npm install -g tracehub@0.5.10`, 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.9 uninstall
113
+ npx --yes tracehub@0.5.10 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.
@@ -231,6 +231,7 @@ Where the sessions are, read where the agent of the commit's environment writes
231
231
  | `context remove --pr <n> <provider>:<id>…` | detaches context conversations from a pull request |
232
232
  | `backfill --pr <n> [--repo <owner/repo>] [--session <agent:id>,…] [--dry-run]` | finds and uploads the agent sessions behind a pull request's untraced commits |
233
233
  | `backfill <commit>… [--session <agent:id>,…] [--dry-run]` | the same for commits named |
234
+ | `show (<commit> \| <path>:<line> \| --pr <n> \| <url>) [--json]` | prints the conversations behind a commit, a pull request or a trace, or the prompt that wrote a line |
234
235
 
235
236
  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.
236
237
 
@@ -264,6 +265,8 @@ An upload is a normal one: the session cut where the commit was made, redacted o
264
265
 
265
266
  ### For coding agents
266
267
 
268
+ Before changing a line, read the prompt that wrote it with `npx --yes tracehub show <path>:<line>`, or the conversations behind a commit with `npx --yes tracehub show <commit>`.
269
+
267
270
  Asked to "upload traces for these PRs":
268
271
 
269
272
  1. In a clone of the repository, run `npx --yes tracehub backfill --pr <n> --dry-run` for each pull request.
@@ -368,7 +371,7 @@ Do not try it with the session you are working in: what is uploaded stays in the
368
371
 
369
372
  ```sh
370
373
  gh repo create assistant-ui/tracehub-playground --private --clone && cd tracehub-playground
371
- npx --yes tracehub@0.5.9 setup # allow this repository, install the hooks
374
+ npx --yes tracehub@0.5.10 setup # allow this repository, install the hooks
372
375
 
373
376
  # open a fresh agent session in this directory, ask it for something harmless
374
377
  export TRACEHUB_ID=claude:<throwaway session id>
@@ -0,0 +1,262 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { readPage, webUrl } from "../../client/tracehub.js";
4
+ import { repoRoot, tryGit } from "../../git/git.js";
5
+ import { lineHash } from "../../protocol/trace.js";
6
+ import { isTraceId } from "../../protocol/trailers.js";
7
+ import { prOf } from "../args.js";
8
+ import { out } from "../io.js";
9
+ import { signedInClient } from "../remote.js";
10
+ import { uploadTargetFor } from "../repo.js";
11
+ function pagePath(raw) {
12
+ let url;
13
+ try {
14
+ url = new URL(raw);
15
+ }
16
+ catch {
17
+ throw new Error("invalid TraceHub page URL");
18
+ }
19
+ if (url.origin !== new URL(webUrl()).origin)
20
+ throw new Error(`page URL must be on ${new URL(webUrl()).origin}`);
21
+ const match = /^\/(t|c|pr)\/([A-Za-z0-9._-]{1,100})\/([A-Za-z0-9._-]{1,100})\/([A-Za-z0-9]{1,40})(\.json|\/json)?\/?$/.exec(url.pathname);
22
+ if (match) {
23
+ const [, kind, owner, repo, rawId] = match;
24
+ const id = kind === "c" ? rawId.toLowerCase() : rawId;
25
+ if (![owner, repo].some((s) => s === "." || s === "..") &&
26
+ (kind === "t"
27
+ ? isTraceId(id)
28
+ : kind === "c"
29
+ ? /^[0-9a-f]{7,40}$/.test(id)
30
+ : /^[1-9]\d{0,9}$/.test(id)))
31
+ return `/${kind}/${owner.toLowerCase()}/${repo.toLowerCase()}/${id}`;
32
+ }
33
+ throw new Error("URL must name a TraceHub trace, commit or pull request page");
34
+ }
35
+ const time = (iso) => `${new Date(iso).toISOString().slice(0, 16).replace("T", " ")} UTC`;
36
+ function blameLine(raw, cwd, root) {
37
+ const match = /^(.+):([1-9]\d*)$/.exec(raw);
38
+ if (!match || isAbsolute(match[1]))
39
+ return undefined;
40
+ const file = resolve(cwd, match[1]);
41
+ const path = relative(root, file);
42
+ if (path === ".." || path.startsWith(`..${sep}`))
43
+ return undefined;
44
+ const stat = statSync(file, { throwIfNoEntry: false });
45
+ if (!stat)
46
+ throw new Error(`file "${match[1]}" does not exist`);
47
+ if (!stat.isFile())
48
+ return undefined;
49
+ const line = Number(match[2]);
50
+ const contents = readFileSync(file, "utf8");
51
+ const count = contents
52
+ ? contents.split("\n").length - Number(contents.endsWith("\n"))
53
+ : 0;
54
+ if (!Number.isSafeInteger(line) || line > count)
55
+ throw new Error(`${raw} is past the end of the file`);
56
+ const blame = tryGit([
57
+ "-c",
58
+ "core.quotePath=false",
59
+ "blame",
60
+ "--porcelain",
61
+ "-L",
62
+ `${line},${line}`,
63
+ "--",
64
+ path,
65
+ ], { cwd: root });
66
+ if (!blame) {
67
+ if (!tryGit(["ls-files", "--error-unmatch", "--", path], { cwd: root }) ||
68
+ !tryGit(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: root }))
69
+ throw new Error(`${raw} is not yet committed`);
70
+ throw new Error(`could not blame ${raw}`);
71
+ }
72
+ const commit = blame.split(" ", 1)[0];
73
+ if (/^0+$/.test(commit))
74
+ throw new Error(`${raw} is not yet committed`);
75
+ const filename = /^filename (.+)$/m.exec(blame)?.[1];
76
+ const text = /^\t(.*)$/m.exec(blame)?.[1] ?? "";
77
+ if (!filename)
78
+ throw new Error(`could not read the filename for ${raw}`);
79
+ return {
80
+ commit,
81
+ path: filename.startsWith('"')
82
+ ? JSON.parse(filename)
83
+ : filename,
84
+ line,
85
+ text,
86
+ };
87
+ }
88
+ export function renderTurnPath(path) {
89
+ return path
90
+ .split(".")
91
+ .map((index, depth) => {
92
+ const number = Number(index) + 1;
93
+ return depth === 0
94
+ ? String(number)
95
+ : `${depth % 2 ? "run" : "turn"} ${number}`;
96
+ })
97
+ .join(" › ");
98
+ }
99
+ function messageBody(message, level) {
100
+ const indent = " ".repeat(level);
101
+ const lines = (message.withheld ? "[withheld: looked sensitive]" : message.text)
102
+ .split(/\r?\n/)
103
+ .map((line) => indent + line);
104
+ if (message.translation) {
105
+ lines.push(`${indent}in English (from ${message.translation.from}):`);
106
+ lines.push(...message.translation.text
107
+ .split(/\r?\n/)
108
+ .map((line) => `${indent} ${line}`));
109
+ }
110
+ return lines.join("\n");
111
+ }
112
+ function contextText(context, login) {
113
+ return [
114
+ `Context ${context.ref}${context.title ? ` · ${context.title}` : ""}${login ? ` · attached by @${login}` : ""}`,
115
+ ...(context.url ? [context.url] : []),
116
+ ...context.messages.map((message) => ` ${message.author} · ${time(message.at)}\n${messageBody(message, 2)}`),
117
+ ].join("\n");
118
+ }
119
+ function turnText(turn, index, level = 0) {
120
+ const indent = " ".repeat(level);
121
+ return [
122
+ `${indent}Turn ${index + 1} · ${time(turn.at)}`,
123
+ ...turn.messages.map((message) => `${indent} ${message.role} · ${time(message.at)}\n${messageBody(message, level + 2)}`),
124
+ ...(turn.changes.length
125
+ ? [
126
+ `${indent} changed ${turn.changes.map((change) => `${change.path} +${change.added} -${change.removed}`).join(", ")}`,
127
+ ]
128
+ : []),
129
+ ...turn.runs.map((run, runIndex) => [
130
+ `${indent} Run ${runIndex + 1} · ${run.label}${run.agent ? ` · ${run.agent}` : ""}`,
131
+ ...(run.turns.length ? [turnsText(run.turns, level + 2)] : []),
132
+ ].join("\n")),
133
+ ].join("\n");
134
+ }
135
+ function turnsText(turns, level = 0) {
136
+ return turns.map((turn, index) => turnText(turn, index, level)).join("\n\n");
137
+ }
138
+ function sessionHeader(session) {
139
+ return `Session ${session.agent}${session.title ? ` · ${session.title}` : ""}${session.model ? ` · ${session.model}` : ""}${session.uploader.login ? ` · @${session.uploader.login}` : ""}`;
140
+ }
141
+ function documentBlocks(doc) {
142
+ return [
143
+ ...doc.context.map((context) => contextText(context)),
144
+ ...doc.sessions.map((session) => [
145
+ sessionHeader(session),
146
+ ...(session.turns.length ? [turnsText(session.turns)] : []),
147
+ ].join("\n")),
148
+ ];
149
+ }
150
+ export function renderShow(doc, path) {
151
+ const repo = `${doc.owner}/${doc.repo}`;
152
+ const title = "number" in doc
153
+ ? `${repo}#${doc.number}${doc.title ? ` ${doc.title}` : ""}`
154
+ : "sha" in doc
155
+ ? `${repo}@${doc.sha.slice(0, 7)}`
156
+ : `${repo} trace ${doc.traceId}`;
157
+ const blocks = [`${title}\n${webUrl()}${path}`];
158
+ if ("traceId" in doc)
159
+ blocks.push(...documentBlocks(doc));
160
+ else {
161
+ const commits = "number" in doc
162
+ ? doc.commits
163
+ : [
164
+ {
165
+ sha: doc.sha,
166
+ traceIds: doc.traces.map((trace) => trace.traceId),
167
+ },
168
+ ];
169
+ if (!commits.some((commit) => doc.traces.some((trace) => commit.traceIds.includes(trace.traceId))))
170
+ blocks.push("no traces");
171
+ if ("number" in doc)
172
+ for (const attached of doc.context)
173
+ blocks.push(...attached.context.map((context) => contextText(context, attached.uploader.login)));
174
+ for (const commit of commits) {
175
+ const traces = commit.traceIds.flatMap((id) => doc.traces.filter((trace) => trace.traceId === id));
176
+ if (!traces.length) {
177
+ if ("number" in doc)
178
+ blocks.push(`Commit ${commit.sha.slice(0, 7)} · no trace`);
179
+ continue;
180
+ }
181
+ for (const trace of traces) {
182
+ blocks.push(`Commit ${commit.sha.slice(0, 7)} · trace ${trace.traceId}\n${webUrl()}/t/${doc.owner}/${doc.repo}/${trace.traceId}`, ...documentBlocks(trace));
183
+ }
184
+ }
185
+ }
186
+ return blocks.join("\n\n");
187
+ }
188
+ export async function cmdShow(args, cwd) {
189
+ const hasPr = args.flags["pr"] !== undefined;
190
+ const positional = args.positional.slice(1);
191
+ if (positional.length !== (hasPr ? 0 : 1) ||
192
+ (hasPr && typeof args.flags["pr"] !== "string") ||
193
+ args.rest?.length ||
194
+ Object.keys(args.flags).some((flag) => flag !== "pr" && flag !== "json") ||
195
+ (args.flags["json"] !== undefined && args.flags["json"] !== true))
196
+ throw new Error('name exactly one commit, <path>:<line>, --pr <n> or page URL; see "tracehub show --help"');
197
+ const pr = prOf(args);
198
+ const revision = positional[0];
199
+ let path;
200
+ let line;
201
+ if (revision && /^https?:\/\//.test(revision))
202
+ path = pagePath(revision);
203
+ else {
204
+ const root = repoRoot(cwd);
205
+ if (!root)
206
+ throw new Error("not a git repository; run it in a clone of the repository");
207
+ const target = uploadTargetFor(cwd);
208
+ if (!target)
209
+ throw new Error("this clone's origin is not a repository TraceHub serves (assistant-ui)");
210
+ line = revision ? blameLine(revision, cwd, root) : undefined;
211
+ const sha = line?.commit ??
212
+ (pr === undefined
213
+ ? tryGit([
214
+ "rev-parse",
215
+ "--verify",
216
+ "--quiet",
217
+ "--end-of-options",
218
+ `${revision}^{commit}`,
219
+ ], { cwd })
220
+ : undefined);
221
+ if (pr === undefined && !sha)
222
+ throw new Error(`unknown commit revision "${revision}"`);
223
+ path = `/${pr === undefined ? "c" : "pr"}/${target.owner}/${target.repo}/${pr ?? sha}`;
224
+ }
225
+ const { auth } = await signedInClient();
226
+ const doc = await readPage(path, auth.accessToken);
227
+ if (line) {
228
+ if (!("sha" in doc))
229
+ throw new Error("expected a commit page");
230
+ const hash = lineHash(line.text);
231
+ const matches = doc.traces.flatMap((trace) => trace.sessions.flatMap((session) => {
232
+ const turn = hash ? session.sourcemap[line.path]?.[hash] : undefined;
233
+ return turn === undefined
234
+ ? []
235
+ : [{ traceId: trace.traceId, session, turn }];
236
+ }));
237
+ if (args.flags["json"])
238
+ out(JSON.stringify({
239
+ commit: line.commit,
240
+ path: line.path,
241
+ line: line.line,
242
+ matches: matches.map(({ traceId, session, turn }) => ({
243
+ traceId,
244
+ session: session.name,
245
+ turn,
246
+ })),
247
+ page: doc,
248
+ }, null, 2));
249
+ else if (matches.length)
250
+ out([
251
+ `${doc.owner}/${doc.repo}@${line.commit.slice(0, 7)}\n${webUrl()}${path}`,
252
+ ...matches.map(({ traceId, session, turn }) => {
253
+ const index = Number(turn.split(".", 1)[0]);
254
+ return `${revision} was written in ${traceId} · ${sessionHeader(session)} · turn ${renderTurnPath(turn)}\n${turnText(session.turns[index], index)}`;
255
+ }),
256
+ ].join("\n\n"));
257
+ else
258
+ out(`${revision} is not attributed to a turn; the commit's conversations follow\n\n${renderShow(doc, path)}`);
259
+ return;
260
+ }
261
+ out(args.flags["json"] ? JSON.stringify(doc, null, 2) : renderShow(doc, path));
262
+ }
package/dist/cli/usage.js CHANGED
@@ -68,6 +68,19 @@ export const COMMANDS = [
68
68
  "tracehub backfill 1a2b3c4d",
69
69
  ],
70
70
  },
71
+ {
72
+ name: "show",
73
+ usage: "show (<commit> | <path>:<line> | --pr <n> | <url>) [--json]",
74
+ summary: "print the conversations behind a commit, a pull request or a trace",
75
+ about: "A commit reads the conversations behind that revision in this clone; --pr <n> reads those behind a pull request of this clone's repository. <path>:<line> finds the prompt that wrote a committed line in this clone, or shows the commit's conversations when the line is unattributed. A TraceHub page URL reads a trace, commit or pull request, even outside a clone. Needs a sign-in and shows only what the web page would show you. --json prints the page's document as served, with the commit, historical path, line and matches for a line lookup.",
76
+ examples: [
77
+ "tracehub show HEAD",
78
+ "tracehub show src/cli/commands/show.ts:42",
79
+ "tracehub show --pr 52",
80
+ "tracehub show https://tracehub.aui.dev/t/assistant-ui/tracehub/0123456789abcdef",
81
+ "tracehub show HEAD --json",
82
+ ],
83
+ },
71
84
  ];
72
85
  export const ENV = [
73
86
  {
package/dist/cli.js CHANGED
@@ -5,6 +5,7 @@ import { cmdHook } from "./cli/commands/hook.js";
5
5
  import { cmdContext } from "./cli/commands/context.js";
6
6
  import { cmdProviders } from "./cli/commands/providers.js";
7
7
  import { cmdSetup } from "./cli/commands/setup.js";
8
+ import { cmdShow } from "./cli/commands/show.js";
8
9
  import { cmdUninstall } from "./cli/commands/uninstall.js";
9
10
  import { fail, Reported } from "./cli/io.js";
10
11
  import { commandUsage, usage } from "./cli/usage.js";
@@ -14,6 +15,7 @@ const COMMAND_HANDLERS = {
14
15
  providers: cmdProviders,
15
16
  context: cmdContext,
16
17
  backfill: cmdBackfill,
18
+ show: cmdShow,
17
19
  };
18
20
  async function main() {
19
21
  const args = parseArgs(process.argv.slice(2));
@@ -119,10 +119,12 @@ export class TracehubClient {
119
119
  return (await res.json());
120
120
  }
121
121
  }
122
- // Whether TraceHub has any session of the trace, asked of the site's
123
- // `.json` page with the user's GitHub token.
124
- export async function traceUploaded(target, traceId, token) {
125
- const res = await fetch(`${webUrl()}/t/${target.owner}/${target.repo}/${traceId}.json`, {
122
+ export async function readPage(path, token) {
123
+ const origin = new URL(webUrl()).origin;
124
+ const url = new URL(`${webUrl()}${path}.json`);
125
+ if (url.origin !== origin)
126
+ throw new Error(`page URL must be on ${origin}`);
127
+ const res = await fetch(url.href, {
126
128
  headers: {
127
129
  authorization: `Bearer ${token}`,
128
130
  "user-agent": "tracehub-cli",
@@ -130,9 +132,20 @@ export async function traceUploaded(target, traceId, token) {
130
132
  redirect: "manual",
131
133
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
132
134
  });
133
- if (res.status === 404)
134
- return false;
135
- if (res.ok)
135
+ if (!res.ok)
136
+ throw await errorOf(res);
137
+ return (await res.json());
138
+ }
139
+ // Whether TraceHub has any session of the trace, asked of the site's
140
+ // `.json` page with the user's GitHub token.
141
+ export async function traceUploaded(target, traceId, token) {
142
+ try {
143
+ await readPage(`/t/${target.owner}/${target.repo}/${traceId}`, token);
136
144
  return true;
137
- throw new Error(`TraceHub answered ${res.status}`);
145
+ }
146
+ catch (err) {
147
+ if (err instanceof TracehubError && err.status === 404)
148
+ return false;
149
+ throw err;
150
+ }
138
151
  }
package/dist/git/git.js CHANGED
@@ -1,12 +1,26 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { traceIds } from "../protocol/trailers.js";
3
3
  const MAX_BUFFER = 256 * 1024 * 1024;
4
+ // A hook inherits the variables that pin git to the repository it runs for
5
+ // (GIT_DIR in a linked worktree); with them, any other directory reads as
6
+ // that repository's checkout.
7
+ let localEnvVars;
4
8
  export function git(args, opts = {}) {
9
+ localEnvVars ??= execFileSync("git", ["rev-parse", "--local-env-vars"], {
10
+ encoding: "utf8",
11
+ stdio: ["ignore", "pipe", "pipe"],
12
+ })
13
+ .trim()
14
+ .split("\n");
15
+ const env = { ...(opts.env ?? process.env) };
16
+ for (const name of localEnvVars)
17
+ delete env[name];
5
18
  const out = execFileSync("git", args, {
6
19
  encoding: "utf8",
7
20
  stdio: ["ignore", "pipe", "pipe"],
8
21
  maxBuffer: MAX_BUFFER,
9
22
  ...opts,
23
+ env,
10
24
  });
11
25
  return out.toString().trimEnd();
12
26
  }
@@ -0,0 +1,56 @@
1
+ // Text an agent's harness wrote into the user's side of a session: a CI
2
+ // event, a task notification, a reminder, a command's output. It is not
3
+ // what the person typed, so it reads as the system's. A message counts
4
+ // only when it starts with one of these wrappers, closed; a tag a person
5
+ // wrote mid-text leaves the message theirs.
6
+ const LABELS = {
7
+ "ci-monitor-event": "CI monitor",
8
+ "task-notification": "Task notification",
9
+ "system-reminder": "System reminder",
10
+ "command-name": "Command",
11
+ "command-message": "Command",
12
+ "command-args": "Command",
13
+ "local-command-stdout": "Command output",
14
+ "local-command-stderr": "Command output",
15
+ "local-command-caveat": "Command output",
16
+ "bash-input": "Shell",
17
+ "bash-stdout": "Shell output",
18
+ "bash-stderr": "Shell output",
19
+ "user-prompt-submit-hook": "Hook",
20
+ };
21
+ const WRAPPER = /^\s*<([a-z]+(?:-[a-z]+)+)(?:\s[^>]*)?>/;
22
+ const INTERRUPT = /^\s*\[Request interrupted by user[^\]]*\]\s*$/;
23
+ const HOOK = /^\s*(Stop|SubagentStop|PreToolUse|PostToolUse|UserPromptSubmit|SessionStart|PreCompact|Notification) hook (?:feedback|blocking error)[^:\n]*:/;
24
+ const oneLine = (text) => text
25
+ .replace(/<[^>]+>/g, " ")
26
+ .split("\n")
27
+ .map((l) => l.replace(/\s+/g, " ").trim())
28
+ .find(Boolean) ?? "";
29
+ const inner = (text, tag) => new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`).exec(text)?.[1];
30
+ function summaryOf(tag, text) {
31
+ if (tag === "task-notification")
32
+ return oneLine(inner(text, "summary") ?? inner(text, "status") ?? "");
33
+ if (tag.startsWith("command-")) {
34
+ const name = inner(text, "command-name")?.trim();
35
+ const args = inner(text, "command-args")?.trim();
36
+ if (name)
37
+ return [name, args].filter(Boolean).join(" ");
38
+ }
39
+ return oneLine(inner(text, tag) ?? text);
40
+ }
41
+ // The event a user message is, when the harness wrote it.
42
+ export function harnessEvent(text) {
43
+ if (INTERRUPT.test(text))
44
+ return { label: "Interrupted", summary: "Request interrupted by user" };
45
+ const hook = HOOK.exec(text);
46
+ if (hook)
47
+ return {
48
+ label: "Hook",
49
+ summary: oneLine(text.slice(hook[0].length)) || `${hook[1]} hook`,
50
+ };
51
+ const tag = WRAPPER.exec(text)?.[1];
52
+ const label = tag && LABELS[tag];
53
+ if (!tag || !label || !text.includes(`</${tag}>`))
54
+ return undefined;
55
+ return { label, summary: summaryOf(tag, text) };
56
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,5 @@
1
1
  import { parseContext } from "./context.js";
2
+ import { harnessEvent } from "./harness.js";
2
3
  import { AGENTS } from "./sessionRef.js";
3
4
  // FNV-1a 64 of the trimmed line, as 16 hex characters; blank lines have none.
4
5
  export function lineHash(line) {
@@ -25,10 +26,26 @@ function parseMessage(raw) {
25
26
  if (!isObject(raw))
26
27
  return undefined;
27
28
  const { role, at, text } = raw;
28
- if ((role !== "user" && role !== "agent") || !isTime(at) || !isString(text))
29
+ if ((role !== "user" && role !== "agent" && role !== "system") ||
30
+ !isTime(at) ||
31
+ !isString(text))
29
32
  return undefined;
30
33
  return { role, at, text: text.slice(0, MAX_TEXT) };
31
34
  }
35
+ // The turns with each user message the harness wrote as the system's, for
36
+ // traces uploaded before the CLI told them apart.
37
+ export function withSystemMessages(turns) {
38
+ return turns.map((turn) => ({
39
+ ...turn,
40
+ messages: turn.messages.map((m) => m.role === "user" && harnessEvent(m.text)
41
+ ? { ...m, role: "system" }
42
+ : m),
43
+ runs: turn.runs.map((run) => ({
44
+ ...run,
45
+ turns: withSystemMessages(run.turns),
46
+ })),
47
+ }));
48
+ }
32
49
  function parseChange(raw) {
33
50
  if (!isObject(raw))
34
51
  return undefined;
@@ -80,28 +80,40 @@ function turnsOf(events, cwd, prefix, ctx, children) {
80
80
  for (const event of events) {
81
81
  if (event.kind === "tool_result")
82
82
  continue;
83
- const opens = event.kind === "user" && !event.steering;
83
+ const opens = (event.kind === "user" && !event.steering) || event.kind === "system";
84
84
  if (opens || !turns.length)
85
85
  turns.push({ at: event.ts, messages: [], changes: [], runs: [] });
86
86
  const turn = turns.at(-1);
87
87
  const index = turns.length - 1;
88
88
  eventTurn.set(event, index);
89
- if (event.kind === "user")
90
- turn.messages.push({ role: "user", at: event.ts, text: event.text });
89
+ if (event.kind === "user" || event.kind === "system")
90
+ turn.messages.push({ role: event.kind, at: event.ts, text: event.text });
91
91
  else if (event.kind === "assistant")
92
92
  turn.messages.push({ role: "agent", at: event.ts, text: event.text });
93
93
  else {
94
94
  if (event.callId)
95
95
  callTurn.set(event.callId, index);
96
96
  for (const edit of event.edits ?? []) {
97
- const abs = isAbsolute(edit.path) ? edit.path : resolve(cwd, edit.path);
98
- const path = repoPath(abs, cwd, ctx.roots(dirname(abs)));
99
- if (!path)
97
+ const file = ctx.file(edit.path, cwd);
98
+ if (!file)
100
99
  continue;
101
- addChange(turn, path, edit.added.length, edit.removed.length);
100
+ const { path, home } = file;
101
+ const change = {
102
+ turn,
103
+ added: edit.added.length,
104
+ removed: edit.removed.length,
105
+ };
106
+ if (home)
107
+ addChange(turn, path, change.added, change.removed);
102
108
  const hashes = new Set(edit.added.map(lineHash).filter((h) => h !== undefined));
103
109
  const ts = Date.parse(event.ts);
104
- ctx.written.push({ turn: `${prefix}${index}`, ts, path, hashes });
110
+ ctx.written.push({
111
+ turn: `${prefix}${index}`,
112
+ ts,
113
+ path,
114
+ hashes,
115
+ ...(!home ? { change } : {}),
116
+ });
105
117
  }
106
118
  }
107
119
  }
@@ -123,6 +135,7 @@ function turnsOf(events, cwd, prefix, ctx, children) {
123
135
  continue;
124
136
  const runPrefix = `${prefix}${index}.${turn.runs.length}.`;
125
137
  const childCwd = child.transcript.cwd || cwd;
138
+ const start = ctx.written.length;
126
139
  const runTurns = turnsOf(child.transcript.events, childCwd, runPrefix, ctx, child.children);
127
140
  const first = runTurns[0];
128
141
  if (child.prompt && !first?.messages.some((m) => m.role === "user")) {
@@ -147,6 +160,9 @@ function turnsOf(events, cwd, prefix, ctx, children) {
147
160
  .filter((ms) => !Number.isNaN(ms));
148
161
  if (times.length)
149
162
  ctx.ends.set(run, Math.max(...times));
163
+ const written = ctx.written.slice(start);
164
+ if (written.length && written.every((w) => w.change))
165
+ ctx.foreignOnly.add(run);
150
166
  turn.runs.push(run);
151
167
  }
152
168
  return turns;
@@ -161,6 +177,7 @@ function sourcemapOf(written, added) {
161
177
  for (const w of ordered)
162
178
  byPath.set(w.path, [...(byPath.get(w.path) ?? []), w]);
163
179
  const map = {};
180
+ const attributed = new Set();
164
181
  for (const [path, lines] of added) {
165
182
  const edits = byPath.get(path);
166
183
  if (!edits)
@@ -170,10 +187,15 @@ function sourcemapOf(written, added) {
170
187
  if (!hash)
171
188
  continue;
172
189
  const last = [...edits].reverse().find((w) => w.hashes.has(hash));
173
- if (last)
190
+ if (last) {
174
191
  (map[path] ??= {})[hash] = last.turn;
192
+ attributed.add(last);
193
+ }
175
194
  }
176
195
  }
196
+ for (const { path, change } of attributed)
197
+ if (change)
198
+ addChange(change.turn, path, change.added, change.removed);
177
199
  return map;
178
200
  }
179
201
  // The part of a session that made one commit, so a long session that
@@ -181,38 +203,75 @@ function sourcemapOf(written, added) {
181
203
  // that wrote the commit's lines, and the turns with messages since the
182
204
  // session's previous commit. A turn kept only for a run keeps its prompt
183
205
  // and its messages since that commit. Without attributed lines, the runs
184
- // active since that commit stay. The sourcemap's turn paths follow the
185
- // kept turns.
186
- function scopeToCommit(turns, sourcemap, sinceMs, ends) {
206
+ // active since that commit stay, except those that only worked in another
207
+ // checkout. A kept prompt keeps the reply it answers, the last agent message
208
+ // of the turn before, in a turn of its own when that turn is out of scope.
209
+ // The sourcemap's turn paths follow the kept turns.
210
+ function scopeToCommit(turns, sourcemap, sinceMs, ends, foreignOnly) {
187
211
  const hits = new Set(Object.values(sourcemap).flatMap((lines) => Object.values(lines)));
188
- const paths = new Map();
189
- const kept = [];
190
- turns.forEach((turn, i) => {
212
+ const decisions = turns.map((turn, i) => {
191
213
  const own = hits.has(`${i}`);
192
214
  const recent = i === turns.length - 1 ||
193
215
  [turn.at, ...turn.messages.map((m) => m.at)].some((at) => Date.parse(at) >= sinceMs);
194
- const runs = [];
195
- turn.runs.forEach((run, j) => {
216
+ const runs = turn.runs.flatMap((run, j) => {
196
217
  const prefix = `${i}.${j}.`;
197
218
  const wrote = [...hits].filter((h) => h.startsWith(prefix));
198
219
  if (!wrote.length &&
199
- (hits.size > 0 || !((ends.get(run) ?? -Infinity) > sinceMs)))
200
- return;
201
- for (const h of wrote)
202
- paths.set(h, `${kept.length}.${runs.length}.${h.slice(prefix.length)}`);
203
- runs.push(run);
220
+ (hits.size > 0 ||
221
+ foreignOnly.has(run) ||
222
+ !((ends.get(run) ?? -Infinity) > sinceMs)))
223
+ return [];
224
+ return [{ run, index: j, wrote }];
204
225
  });
205
226
  if (!own && !recent && !runs.length)
227
+ return undefined;
228
+ return {
229
+ own,
230
+ recent,
231
+ messages: own
232
+ ? turn.messages
233
+ : turn.messages.filter((m, k) => (k === 0 && m.role !== "agent") || Date.parse(m.at) >= sinceMs),
234
+ runs,
235
+ };
236
+ });
237
+ decisions.forEach((decision, i) => {
238
+ if (!decision || i === 0 || decision.messages[0]?.role !== "user")
206
239
  return;
207
- if (own)
240
+ const previous = turns[i - 1];
241
+ const reply = [...previous.messages]
242
+ .reverse()
243
+ .find((m) => m.role === "agent");
244
+ if (!reply)
245
+ return;
246
+ const prior = decisions[i - 1];
247
+ if (prior)
248
+ prior.messages = previous.messages.filter((m) => m === reply || prior.messages.includes(m));
249
+ else
250
+ decisions[i - 1] = {
251
+ own: false,
252
+ recent: false,
253
+ messages: [reply],
254
+ runs: [],
255
+ };
256
+ });
257
+ const paths = new Map();
258
+ const kept = [];
259
+ decisions.forEach((decision, i) => {
260
+ if (!decision)
261
+ return;
262
+ const turn = turns[i];
263
+ if (decision.own)
208
264
  paths.set(`${i}`, `${kept.length}`);
265
+ decision.runs.forEach(({ index, wrote }, j) => {
266
+ const prefix = `${i}.${index}.`;
267
+ for (const h of wrote)
268
+ paths.set(h, `${kept.length}.${j}.${h.slice(prefix.length)}`);
269
+ });
209
270
  kept.push({
210
271
  at: turn.at,
211
- messages: own
212
- ? turn.messages
213
- : turn.messages.filter((m, k) => (k === 0 && m.role === "user") || Date.parse(m.at) >= sinceMs),
214
- changes: own || recent ? turn.changes : [],
215
- runs,
272
+ messages: decision.messages,
273
+ changes: decision.own || decision.recent ? turn.changes : [],
274
+ runs: decision.runs.map(({ run }) => run),
216
275
  });
217
276
  });
218
277
  const scoped = {};
@@ -246,7 +305,7 @@ export function buildTrace(input, opts = {}) {
246
305
  const before = parseSessionLines(agent, id, lines.slice(0, cut), sidechain);
247
306
  const events = [...before.events];
248
307
  for (const event of whole.events.slice(before.events.length)) {
249
- if (event.kind === "user" && !event.steering)
308
+ if ((event.kind === "user" && !event.steering) || event.kind === "system")
250
309
  break;
251
310
  if (event.kind === "assistant")
252
311
  events.push(event);
@@ -329,8 +388,24 @@ export function buildTrace(input, opts = {}) {
329
388
  }
330
389
  }
331
390
  };
332
- const roots = (dir) => [nearest(dir), input.root, realOrSelf(input.root)].filter((r) => !!r);
333
- const ctx = { roots, written: [], ends: new Map() };
391
+ const commitRoot = realOrSelf(input.root);
392
+ const ctx = {
393
+ file: (path, cwd) => {
394
+ const abs = isAbsolute(path) ? path : resolve(cwd, path);
395
+ const checkout = nearest(dirname(abs));
396
+ const roots = [checkout, input.root, commitRoot].filter((r) => !!r);
397
+ const relative = repoPath(abs, cwd, roots);
398
+ return relative
399
+ ? {
400
+ path: relative,
401
+ home: !checkout || realOrSelf(checkout) === commitRoot,
402
+ }
403
+ : undefined;
404
+ },
405
+ written: [],
406
+ ends: new Map(),
407
+ foreignOnly: new Set(),
408
+ };
334
409
  const cwd = before.cwd || input.root;
335
410
  let turns = turnsOf(events, cwd, "", ctx, children.filter((c) => c.transcript.events.length));
336
411
  // A session that ran outside the repository (a coordinator whose
@@ -340,6 +415,9 @@ export function buildTrace(input, opts = {}) {
340
415
  // whatever cwd its lines carry over from its parent, and so does a
341
416
  // session that made the commit itself (`cd <checkout> && git commit`).
342
417
  const outside = !sidechain && !input.committer && !ownCheckout(cwd);
418
+ if (outside)
419
+ ctx.written = ctx.written.filter((w) => w.turn.includes("."));
420
+ const sourcemap = sourcemapOf(ctx.written, input.added);
343
421
  if (outside) {
344
422
  turns = turns.map((turn) => ({
345
423
  at: turn.at,
@@ -350,7 +428,6 @@ export function buildTrace(input, opts = {}) {
350
428
  // its label: the label is the coordinator's own description.
351
429
  changed(run.turns) ? run : { label: "", turns: [] }),
352
430
  }));
353
- ctx.written = ctx.written.filter((w) => w.turn.includes("."));
354
431
  if (!turns.some((turn) => turn.runs.some((run) => run.turns.length)))
355
432
  return undefined;
356
433
  }
@@ -360,7 +437,7 @@ export function buildTrace(input, opts = {}) {
360
437
  ? sessionTitle(lines.slice(0, cut))
361
438
  : undefined;
362
439
  const since = Date.parse(input.since ?? "");
363
- const scoped = scopeToCommit(turns, sourcemapOf(ctx.written, input.added), Number.isNaN(since) ? -Infinity : since, ctx.ends);
440
+ const scoped = scopeToCommit(turns, sourcemap, Number.isNaN(since) ? -Infinity : since, ctx.ends, ctx.foreignOnly);
364
441
  // The session's first message names its conversation even when its turn
365
442
  // is out of scope; a run's brief counts only for the runs in scope.
366
443
  const first = turns[0]?.messages.find((m) => m.role === "user");
@@ -1,5 +1,8 @@
1
+ import { harnessEvent } from "../protocol/harness.js";
1
2
  import { editsOf, firstArg, parseJsonl, } from "./transcript.js";
2
- const INJECTED_PREFIX = /^\s*<(command-message|command-name|local-command-stdout|local-command-caveat|system-reminder|task-notification|bash-input|bash-stdout)/;
3
+ // What the harness injected that stays on the machine: local output and
4
+ // reminders. Other harness text (a CI event) is uploaded as the system's.
5
+ const INJECTED_PREFIX = /^\s*<(command-message|command-name|command-args|local-command-stdout|local-command-stderr|local-command-caveat|system-reminder|task-notification|bash-input|bash-stdout|bash-stderr|user-prompt-submit-hook)/;
3
6
  function cleanUserText(text) {
4
7
  return text
5
8
  .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "")
@@ -35,9 +38,9 @@ function readUserLine(t, line) {
35
38
  t.events.push({ kind: "tool_result", ts, callId, text });
36
39
  }
37
40
  const text = cleanUserText(blockText(content));
38
- if (text && !INJECTED_PREFIX.test(text)) {
39
- t.events.push({ kind: "user", ts, text });
40
- }
41
+ if (!text || INJECTED_PREFIX.test(text))
42
+ return;
43
+ t.events.push({ kind: harnessEvent(text) ? "system" : "user", ts, text });
41
44
  }
42
45
  const SPAWN_TOOLS = ["Task", "Agent"];
43
46
  function readToolCall(t, block, ts, turnId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tracehub",
3
- "version": "0.5.9",
3
+ "version": "0.5.10",
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",