tracehub 0.0.0-stage → 0.5.2
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 +431 -2
- package/dist/cli/args.js +28 -0
- package/dist/cli/clipboard.js +46 -0
- package/dist/cli/commands/context.js +115 -0
- package/dist/cli/commands/hook.js +215 -0
- package/dist/cli/commands/providers.js +55 -0
- package/dist/cli/commands/setup.js +448 -0
- package/dist/cli/commands/uninstall.js +156 -0
- package/dist/cli/io.js +26 -0
- package/dist/cli/remote.js +81 -0
- package/dist/cli/repo.js +70 -0
- package/dist/cli/signin.js +90 -0
- package/dist/cli/ui.js +130 -0
- package/dist/cli/usage.js +151 -0
- package/dist/cli.js +38 -0
- package/dist/client/auth.js +70 -0
- package/dist/client/consent.js +94 -0
- package/dist/client/errors.js +4 -0
- package/dist/client/github.js +129 -0
- package/dist/client/registry.js +112 -0
- package/dist/client/tracehub.js +98 -0
- package/dist/client/upload.js +106 -0
- package/dist/client/uploadPolicy.js +60 -0
- package/dist/git/git.js +163 -0
- package/dist/git/global-hooks.js +221 -0
- package/dist/git/hooks.js +67 -0
- package/dist/git/markers.js +93 -0
- package/dist/git/trailers.js +36 -0
- package/dist/local/commitBoundary.js +38 -0
- package/dist/local/discover.js +283 -0
- package/dist/local/files.js +55 -0
- package/dist/local/lines.js +16 -0
- package/dist/local/opencode.js +124 -0
- package/dist/local/paths.js +51 -0
- package/dist/local/providers.js +171 -0
- package/dist/local/subagents.js +63 -0
- package/dist/protocol/context.js +202 -0
- package/dist/protocol/sessionRef.js +24 -0
- package/dist/protocol/trace.js +111 -0
- package/dist/redact/deny.js +25 -0
- package/dist/redact/redact.js +189 -0
- package/dist/trace/build.js +256 -0
- package/dist/transcript/parseClaude.js +105 -0
- package/dist/transcript/parseCodex.js +164 -0
- package/dist/transcript/parseOpencode.js +84 -0
- package/dist/transcript/title.js +27 -0
- package/dist/transcript/transcript.js +120 -0
- package/package.json +44 -4
package/dist/git/git.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { traceIds } from "./trailers.js";
|
|
3
|
+
const MAX_BUFFER = 256 * 1024 * 1024;
|
|
4
|
+
export function git(args, opts = {}) {
|
|
5
|
+
const out = execFileSync("git", args, {
|
|
6
|
+
encoding: "utf8",
|
|
7
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
8
|
+
maxBuffer: MAX_BUFFER,
|
|
9
|
+
...opts,
|
|
10
|
+
});
|
|
11
|
+
return out.toString().trimEnd();
|
|
12
|
+
}
|
|
13
|
+
export function tryGit(args, opts = {}) {
|
|
14
|
+
try {
|
|
15
|
+
return git(args, opts);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function repoRoot(cwd = process.cwd()) {
|
|
22
|
+
return tryGit(["rev-parse", "--show-toplevel"], { cwd });
|
|
23
|
+
}
|
|
24
|
+
// The repository's own git directory, shared by all its worktrees, so the
|
|
25
|
+
// state of a commit made in a linked worktree outlives the worktree.
|
|
26
|
+
export function gitDir(cwd = process.cwd()) {
|
|
27
|
+
return tryGit(["rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
28
|
+
cwd,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
export function headTimestampMs(cwd) {
|
|
32
|
+
const seconds = Number(tryGit(["log", "-1", "--format=%ct", "HEAD"], { cwd }));
|
|
33
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined;
|
|
34
|
+
}
|
|
35
|
+
export function originUrl(cwd) {
|
|
36
|
+
return tryGit(["remote", "get-url", "origin"], { cwd }) || undefined;
|
|
37
|
+
}
|
|
38
|
+
// One remote's effective fetch and push URLs: get-url expands
|
|
39
|
+
// insteadOf/pushInsteadOf and includes every configured URL. Empty when the
|
|
40
|
+
// remote does not exist.
|
|
41
|
+
export function remoteUrls(cwd, name) {
|
|
42
|
+
const urls = [];
|
|
43
|
+
for (const mode of [[], ["--push"]]) {
|
|
44
|
+
const found = tryGit(["remote", "get-url", ...mode, "--all", name], {
|
|
45
|
+
cwd,
|
|
46
|
+
});
|
|
47
|
+
if (!found)
|
|
48
|
+
return [];
|
|
49
|
+
urls.push(...found.split("\n"));
|
|
50
|
+
}
|
|
51
|
+
return urls;
|
|
52
|
+
}
|
|
53
|
+
// Git's pre-push input: one "<local ref> <local sha> <remote ref> <remote sha>"
|
|
54
|
+
// line per ref.
|
|
55
|
+
function pushedRefs(input) {
|
|
56
|
+
return input
|
|
57
|
+
.split("\n")
|
|
58
|
+
.filter(Boolean)
|
|
59
|
+
.map((line) => {
|
|
60
|
+
const fields = line.trim().split(/\s+/);
|
|
61
|
+
const [, local, , previous] = fields;
|
|
62
|
+
if (fields.length !== 4 ||
|
|
63
|
+
!local ||
|
|
64
|
+
!previous ||
|
|
65
|
+
!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(local) ||
|
|
66
|
+
!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(previous))
|
|
67
|
+
throw new Error("invalid pre-push input; traces stay pending until the next push");
|
|
68
|
+
return { local, previous };
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
// The trace ids of the commits a push sends.
|
|
72
|
+
export function pushedTraceIds(cwd, remote, input) {
|
|
73
|
+
const ids = new Set();
|
|
74
|
+
for (const { local, previous } of pushedRefs(input)) {
|
|
75
|
+
if (/^0+$/.test(local))
|
|
76
|
+
continue;
|
|
77
|
+
const args = ["log", "--format=%B", local];
|
|
78
|
+
if (!/^0+$/.test(previous)) {
|
|
79
|
+
if (!tryGit(["rev-parse", "--verify", `${previous}^{commit}`], { cwd }))
|
|
80
|
+
throw new Error("remote base commit is not available locally; traces stay pending until the next push");
|
|
81
|
+
args.push(`^${previous}`);
|
|
82
|
+
}
|
|
83
|
+
else if (tryGit(["remote"], { cwd })?.split("\n").includes(remote))
|
|
84
|
+
args.push("--not", `--remotes=${remote}`);
|
|
85
|
+
for (const id of traceIds(git(args, { cwd })))
|
|
86
|
+
ids.add(id);
|
|
87
|
+
}
|
|
88
|
+
return ids;
|
|
89
|
+
}
|
|
90
|
+
// Which of `wanted` are trace ids of commits in the history of the pushed
|
|
91
|
+
// refs, including commits pushed before: their traces may still be pending.
|
|
92
|
+
export function tracesInPushedHistory(cwd, input, wanted) {
|
|
93
|
+
const locals = pushedRefs(input)
|
|
94
|
+
.map((ref) => ref.local)
|
|
95
|
+
.filter((local) => !/^0+$/.test(local));
|
|
96
|
+
if (!wanted.length || !locals.length)
|
|
97
|
+
return new Set();
|
|
98
|
+
const messages = git([
|
|
99
|
+
"log",
|
|
100
|
+
"--format=%B",
|
|
101
|
+
"--fixed-strings",
|
|
102
|
+
...wanted.map((id) => `--grep=${id}`),
|
|
103
|
+
...locals,
|
|
104
|
+
], { cwd });
|
|
105
|
+
return new Set(traceIds(messages).filter((id) => wanted.includes(id)));
|
|
106
|
+
}
|
|
107
|
+
// The newest commit whose message names the trace id.
|
|
108
|
+
export function commitOfTrace(cwd, traceId) {
|
|
109
|
+
return (tryGit([
|
|
110
|
+
"log",
|
|
111
|
+
"--all",
|
|
112
|
+
"--fixed-strings",
|
|
113
|
+
`--grep=${traceId}`,
|
|
114
|
+
"--format=%H",
|
|
115
|
+
"-n",
|
|
116
|
+
"1",
|
|
117
|
+
], { cwd }) || undefined);
|
|
118
|
+
}
|
|
119
|
+
// The lines a commit adds, per path, against its first parent.
|
|
120
|
+
export function addedLines(cwd, sha) {
|
|
121
|
+
const diff = tryGit([
|
|
122
|
+
"-c",
|
|
123
|
+
"core.quotePath=false",
|
|
124
|
+
"show",
|
|
125
|
+
"--first-parent",
|
|
126
|
+
"--format=",
|
|
127
|
+
"--no-color",
|
|
128
|
+
"--no-ext-diff",
|
|
129
|
+
"--unified=0",
|
|
130
|
+
sha,
|
|
131
|
+
], { cwd }) ?? "";
|
|
132
|
+
const added = new Map();
|
|
133
|
+
let lines;
|
|
134
|
+
let inHunk = false;
|
|
135
|
+
for (const line of diff.split("\n")) {
|
|
136
|
+
if (line.startsWith("diff --git ")) {
|
|
137
|
+
inHunk = false;
|
|
138
|
+
lines = undefined;
|
|
139
|
+
}
|
|
140
|
+
else if (!inHunk && line.startsWith("+++ ")) {
|
|
141
|
+
let path = line.slice(4).replace(/\t$/, "");
|
|
142
|
+
if (path.startsWith('"')) {
|
|
143
|
+
try {
|
|
144
|
+
path = JSON.parse(path);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
/* left as it is */
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
lines = undefined;
|
|
151
|
+
if (path.startsWith("b/")) {
|
|
152
|
+
const file = path.slice(2);
|
|
153
|
+
lines = added.get(file) ?? [];
|
|
154
|
+
added.set(file, lines);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
else if (line.startsWith("@@"))
|
|
158
|
+
inHunk = true;
|
|
159
|
+
else if (inHunk && line.startsWith("+"))
|
|
160
|
+
lines?.push(line.slice(1));
|
|
161
|
+
}
|
|
162
|
+
return added;
|
|
163
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
2
|
+
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { hookBlock, hookRunner, hookVersion, legacyHookBlock, sameRunner, } from "./hooks.js";
|
|
5
|
+
const HOOKS = [
|
|
6
|
+
"applypatch-msg",
|
|
7
|
+
"pre-applypatch",
|
|
8
|
+
"post-applypatch",
|
|
9
|
+
"pre-commit",
|
|
10
|
+
"pre-merge-commit",
|
|
11
|
+
"prepare-commit-msg",
|
|
12
|
+
"commit-msg",
|
|
13
|
+
"post-commit",
|
|
14
|
+
"pre-rebase",
|
|
15
|
+
"post-checkout",
|
|
16
|
+
"post-merge",
|
|
17
|
+
"pre-push",
|
|
18
|
+
"pre-receive",
|
|
19
|
+
"update",
|
|
20
|
+
"proc-receive",
|
|
21
|
+
"post-receive",
|
|
22
|
+
"post-update",
|
|
23
|
+
"reference-transaction",
|
|
24
|
+
"push-to-checkout",
|
|
25
|
+
"pre-auto-gc",
|
|
26
|
+
"post-rewrite",
|
|
27
|
+
"sendemail-validate",
|
|
28
|
+
"fsmonitor-watchman",
|
|
29
|
+
"p4-changelist",
|
|
30
|
+
"p4-prepare-changelist",
|
|
31
|
+
"p4-post-changelist",
|
|
32
|
+
"p4-pre-submit",
|
|
33
|
+
"post-index-change",
|
|
34
|
+
];
|
|
35
|
+
const MANIFEST = "tracehub.json";
|
|
36
|
+
const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
37
|
+
const canonical = (path) => existsSync(path)
|
|
38
|
+
? realpathSync(path)
|
|
39
|
+
: join(canonical(dirname(path)), basename(path));
|
|
40
|
+
function checkIncludes(cwd, env) {
|
|
41
|
+
const result = spawnSync("git", ["config", "--show-scope", "--get-regexp", "^include(if\\..*)?\\.path$"], { cwd, env, encoding: "utf8" });
|
|
42
|
+
if (result.status !== 0 && result.status !== 1)
|
|
43
|
+
throw new Error("Cannot inspect Git configuration includes.");
|
|
44
|
+
if (result.stdout.split("\n").some((line) => /^(?:global|system)\t/.test(line)))
|
|
45
|
+
throw new Error("Global or system Git configuration includes (include.path or includeIf) can change core.hooksPath, so tracehub cannot install global hooks safely; remove the includes or set up the hooks by hand.");
|
|
46
|
+
}
|
|
47
|
+
function globalPath(cwd, env, expand = false) {
|
|
48
|
+
const result = spawnSync("git", [
|
|
49
|
+
"config",
|
|
50
|
+
"--global",
|
|
51
|
+
...(expand ? ["--path"] : []),
|
|
52
|
+
"--get-all",
|
|
53
|
+
"core.hooksPath",
|
|
54
|
+
], { cwd, env, encoding: "utf8" });
|
|
55
|
+
if (result.status === 1)
|
|
56
|
+
return null;
|
|
57
|
+
if (result.status !== 0)
|
|
58
|
+
throw new Error(result.stderr.trim() || "Cannot read global Git hooks configuration.");
|
|
59
|
+
const paths = result.stdout.replace(/\n$/, "").split("\n");
|
|
60
|
+
if (paths.length !== 1)
|
|
61
|
+
throw new Error("Multiple global core.hooksPath values require manual setup.");
|
|
62
|
+
return paths[0];
|
|
63
|
+
}
|
|
64
|
+
function source(hook, manifest) {
|
|
65
|
+
const delegated = manifest.delegate === null
|
|
66
|
+
? 'tracehub_hooks="$(git rev-parse --path-format=absolute --git-common-dir)/hooks"'
|
|
67
|
+
: `tracehub_hooks=${quote(manifest.delegate)}`;
|
|
68
|
+
const block = hook === "prepare-commit-msg" || hook === "pre-push"
|
|
69
|
+
? manifest.runner === undefined
|
|
70
|
+
? legacyHookBlock(hook, manifest.cliVersion)
|
|
71
|
+
: hookBlock(hook, manifest.cliVersion, manifest.runner)
|
|
72
|
+
: "";
|
|
73
|
+
// An installed push-to-checkout hook replaces Git's built-in updateInstead behavior.
|
|
74
|
+
const fallback = hook === "push-to-checkout"
|
|
75
|
+
? 'cd "$GIT_WORK_TREE" || exit 1\ngit update-index -q --ignore-submodules --refresh || exit 1\ngit diff-files --quiet --ignore-submodules -- || exit 1\ngit diff --cached --quiet --ignore-submodules -- || exit 1\nexec git read-tree -u -m "$1"\n'
|
|
76
|
+
: hook === "fsmonitor-watchman" || hook === "proc-receive"
|
|
77
|
+
? "exit 1\n"
|
|
78
|
+
: "";
|
|
79
|
+
return `#!/bin/sh\n# tracehub global dispatcher\n${block}${delegated}\nif [ "$tracehub_hooks/${hook}" -ef "$0" ]; then\n printf '%s\\n' 'tracehub: recursive hook delegation skipped; review core.hooksPath' >&2\nelif [ -x "$tracehub_hooks/${hook}" ]; then\n exec "$tracehub_hooks/${hook}" "$@"\nfi\n${fallback}`;
|
|
80
|
+
}
|
|
81
|
+
function inheritedSystemPath(cwd, env) {
|
|
82
|
+
const result = spawnSync("git", ["config", "--show-scope", "--path", "--get-all", "core.hooksPath"], { cwd, env, encoding: "utf8" });
|
|
83
|
+
if (result.status === 1)
|
|
84
|
+
return null;
|
|
85
|
+
if (result.status !== 0)
|
|
86
|
+
throw new Error("Cannot read inherited Git hooks configuration.");
|
|
87
|
+
return (result.stdout
|
|
88
|
+
.replace(/\n$/, "")
|
|
89
|
+
.split("\n")
|
|
90
|
+
.filter((line) => line.startsWith("system\t"))
|
|
91
|
+
.at(-1)
|
|
92
|
+
?.slice(7) ?? null);
|
|
93
|
+
}
|
|
94
|
+
function readManifest(directory) {
|
|
95
|
+
if (existsSync(directory) &&
|
|
96
|
+
(!lstatSync(directory).isDirectory() ||
|
|
97
|
+
lstatSync(directory).isSymbolicLink()))
|
|
98
|
+
throw new Error("Global hook directory must be a regular directory, not a symlink.");
|
|
99
|
+
const path = join(directory, MANIFEST);
|
|
100
|
+
if (!existsSync(path))
|
|
101
|
+
return undefined;
|
|
102
|
+
if (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink())
|
|
103
|
+
throw new Error("Global hook manifest must be a regular file.");
|
|
104
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
105
|
+
if (value.version !== 1 ||
|
|
106
|
+
typeof value.cliVersion !== "string" ||
|
|
107
|
+
!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(value.cliVersion) ||
|
|
108
|
+
!(value.previous === null || typeof value.previous === "string") ||
|
|
109
|
+
!(value.delegate === null || typeof value.delegate === "string") ||
|
|
110
|
+
!(value.runner === undefined ||
|
|
111
|
+
value.runner === null ||
|
|
112
|
+
(typeof value.runner?.node === "string" &&
|
|
113
|
+
typeof value.runner.cli === "string")))
|
|
114
|
+
throw new Error("Invalid tracehub global hook manifest.");
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
function verifyFiles(directory, manifest) {
|
|
118
|
+
for (const hook of HOOKS) {
|
|
119
|
+
const path = join(directory, hook);
|
|
120
|
+
if (!existsSync(path) ||
|
|
121
|
+
!lstatSync(path).isFile() ||
|
|
122
|
+
lstatSync(path).isSymbolicLink() ||
|
|
123
|
+
(lstatSync(path).mode & 0o777) !== 0o755 ||
|
|
124
|
+
readFileSync(path, "utf8") !== source(hook, manifest))
|
|
125
|
+
throw new Error(`Global dispatcher changed; preserve it and repair manually: ${path}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export function hasGlobalHooks(directory, cwd) {
|
|
129
|
+
const manifest = readManifest(directory);
|
|
130
|
+
if (!manifest || globalPath(cwd, process.env) !== directory)
|
|
131
|
+
return false;
|
|
132
|
+
verifyFiles(directory, manifest);
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
export function planGlobalHooks(directory, cwd, env = process.env) {
|
|
136
|
+
directory = resolve(directory);
|
|
137
|
+
checkIncludes(cwd, env);
|
|
138
|
+
const previous = globalPath(cwd, env);
|
|
139
|
+
const manifest = readManifest(directory);
|
|
140
|
+
if (manifest) {
|
|
141
|
+
if (previous !== directory)
|
|
142
|
+
throw new Error("Global hook configuration changed; remove or review the previous tracehub setup first.");
|
|
143
|
+
verifyFiles(directory, manifest);
|
|
144
|
+
return { directory, manifest, existing: true };
|
|
145
|
+
}
|
|
146
|
+
if (previous === directory)
|
|
147
|
+
throw new Error("Global tracehub hooks have no recovery manifest; repair manually.");
|
|
148
|
+
if (existsSync(directory) &&
|
|
149
|
+
(!lstatSync(directory).isDirectory() ||
|
|
150
|
+
lstatSync(directory).isSymbolicLink() ||
|
|
151
|
+
readdirSync(directory).length))
|
|
152
|
+
throw new Error(`Global hook directory must be empty and not a symlink: ${directory}`);
|
|
153
|
+
const next = {
|
|
154
|
+
version: 1,
|
|
155
|
+
previous,
|
|
156
|
+
delegate: globalPath(cwd, env, true) ?? inheritedSystemPath(cwd, env),
|
|
157
|
+
cliVersion: hookVersion(),
|
|
158
|
+
};
|
|
159
|
+
if (next.delegate !== null &&
|
|
160
|
+
canonical(resolve(cwd, next.delegate)) === canonical(directory))
|
|
161
|
+
throw new Error("Previous Git hook directory resolves to the tracehub dispatcher; choose a different directory.");
|
|
162
|
+
if (globalPath(cwd, env) !== previous)
|
|
163
|
+
throw new Error("Global Git hooks configuration changed during setup.");
|
|
164
|
+
return { directory, manifest: next, existing: false };
|
|
165
|
+
}
|
|
166
|
+
// Installs the hooks, or rewrites installed ones that run another version
|
|
167
|
+
// or another tracehub than this one.
|
|
168
|
+
export function installGlobalHooks(directory, cwd, env = process.env, runner = hookRunner()) {
|
|
169
|
+
const plan = planGlobalHooks(directory, cwd, env);
|
|
170
|
+
directory = plan.directory;
|
|
171
|
+
const next = { ...plan.manifest, runner };
|
|
172
|
+
if (plan.existing) {
|
|
173
|
+
const current = plan.manifest;
|
|
174
|
+
next.cliVersion = hookVersion();
|
|
175
|
+
if (current.cliVersion === next.cliVersion &&
|
|
176
|
+
current.runner !== undefined &&
|
|
177
|
+
sameRunner(current.runner, runner))
|
|
178
|
+
return "unchanged";
|
|
179
|
+
for (const hook of HOOKS)
|
|
180
|
+
writeFileSync(join(directory, hook), source(hook, next));
|
|
181
|
+
writeFileSync(join(directory, MANIFEST), JSON.stringify(next));
|
|
182
|
+
return "updated";
|
|
183
|
+
}
|
|
184
|
+
mkdirSync(directory, { recursive: true });
|
|
185
|
+
for (const hook of HOOKS) {
|
|
186
|
+
const path = join(directory, hook);
|
|
187
|
+
writeFileSync(path, source(hook, next), { flag: "wx", mode: 0o755 });
|
|
188
|
+
chmodSync(path, 0o755);
|
|
189
|
+
}
|
|
190
|
+
writeFileSync(join(directory, MANIFEST), JSON.stringify(next), {
|
|
191
|
+
flag: "wx",
|
|
192
|
+
mode: 0o600,
|
|
193
|
+
});
|
|
194
|
+
if (globalPath(cwd, env) !== next.previous)
|
|
195
|
+
throw new Error("Global Git hooks configuration changed during setup; no Git configuration was changed.");
|
|
196
|
+
execFileSync("git", ["config", "--global", "core.hooksPath", directory], {
|
|
197
|
+
cwd,
|
|
198
|
+
env,
|
|
199
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
200
|
+
});
|
|
201
|
+
return "installed";
|
|
202
|
+
}
|
|
203
|
+
export function removeGlobalHooks(directory, cwd, env = process.env) {
|
|
204
|
+
directory = resolve(directory);
|
|
205
|
+
const manifest = readManifest(directory);
|
|
206
|
+
if (!manifest)
|
|
207
|
+
throw new Error("No tracehub global hook installation found.");
|
|
208
|
+
if (globalPath(cwd, env) !== directory)
|
|
209
|
+
throw new Error("Global hook configuration changed; it will not be overwritten.");
|
|
210
|
+
verifyFiles(directory, manifest);
|
|
211
|
+
execFileSync("git", [
|
|
212
|
+
"config",
|
|
213
|
+
"--global",
|
|
214
|
+
...(manifest.previous === null
|
|
215
|
+
? ["--unset-all", "core.hooksPath"]
|
|
216
|
+
: ["core.hooksPath", manifest.previous]),
|
|
217
|
+
], { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
|
|
218
|
+
for (const hook of HOOKS)
|
|
219
|
+
unlinkSync(join(directory, hook));
|
|
220
|
+
unlinkSync(join(directory, MANIFEST));
|
|
221
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { dirname, join, sep } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
const START = "# tracehub:start";
|
|
5
|
+
const END = "# tracehub:end";
|
|
6
|
+
const VERSION = /^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i;
|
|
7
|
+
export function hookVersion() {
|
|
8
|
+
let directory = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
while (dirname(directory) !== directory) {
|
|
10
|
+
const file = join(directory, "package.json");
|
|
11
|
+
if (existsSync(file)) {
|
|
12
|
+
const pkg = JSON.parse(readFileSync(file, "utf8"));
|
|
13
|
+
if (pkg.name === "tracehub" && pkg.version) {
|
|
14
|
+
return pkg.version;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
directory = dirname(directory);
|
|
18
|
+
}
|
|
19
|
+
throw new Error("Cannot determine the tracehub hook version.");
|
|
20
|
+
}
|
|
21
|
+
export function hookRunner() {
|
|
22
|
+
const cli = realpathSync(fileURLToPath(new URL("../cli.js", import.meta.url)));
|
|
23
|
+
if (cli.split(sep).includes("_npx"))
|
|
24
|
+
return null;
|
|
25
|
+
return { node: process.execPath, cli };
|
|
26
|
+
}
|
|
27
|
+
export const sameRunner = (a, b) => a === b || (!!a && !!b && a.node === b.node && a.cli === b.cli);
|
|
28
|
+
const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
29
|
+
// One short line on stderr when the CLI could not run; the commit or push
|
|
30
|
+
// goes on.
|
|
31
|
+
const warning = (text) => `printf '%s\\n' ${quote(`tracehub: ${text}`)} >&2`;
|
|
32
|
+
function invocation(hook, version, runner, stdin) {
|
|
33
|
+
const repair = 'run "tracehub setup" to repair the hooks';
|
|
34
|
+
if (!runner)
|
|
35
|
+
// --prefer-offline: a cached tracehub runs without asking the registry.
|
|
36
|
+
return `npx --yes --prefer-offline tracehub@${version} hook ${hook} "$@" ${stdin} || ${warning(`the ${hook} hook could not run tracehub@${version}; ${repair}`)}`;
|
|
37
|
+
return [
|
|
38
|
+
`tracehub_node=${quote(runner.node)}`,
|
|
39
|
+
`[ -x "$tracehub_node" ] || tracehub_node=node`,
|
|
40
|
+
`if [ -f ${quote(runner.cli)} ]; then`,
|
|
41
|
+
` "$tracehub_node" ${quote(runner.cli)} hook ${hook} "$@" ${stdin} || ${warning(`the ${hook} hook failed; ${repair}`)}`,
|
|
42
|
+
`else`,
|
|
43
|
+
` ${warning(`${runner.cli} is missing; ${repair}`)}`,
|
|
44
|
+
`fi`,
|
|
45
|
+
].join("\n");
|
|
46
|
+
}
|
|
47
|
+
export function hookBlock(hook, version = hookVersion(), runner = hookRunner()) {
|
|
48
|
+
if (!VERSION.test(version))
|
|
49
|
+
throw new Error("Invalid tracehub hook version.");
|
|
50
|
+
const body = hook === "pre-push"
|
|
51
|
+
? `if tracehub_input=$(mktemp); then\n if cat > "$tracehub_input"; then\n${indent(invocation(hook, version, runner, '< "$tracehub_input"'), 4)}\n else\n printf '%s\\n' 'tracehub: unable to preserve push input; trace upload skipped' >&2\n fi\n exec < "$tracehub_input"\n rm -f "$tracehub_input"\nelse\n printf '%s\\n' 'tracehub: unable to preserve push input; trace upload skipped' >&2\nfi`
|
|
52
|
+
: invocation(hook, version, runner, "</dev/null");
|
|
53
|
+
return `${START}\n${body}\n${END}\n`;
|
|
54
|
+
}
|
|
55
|
+
const indent = (text, n) => text
|
|
56
|
+
.split("\n")
|
|
57
|
+
.map((line) => " ".repeat(n) + line)
|
|
58
|
+
.join("\n");
|
|
59
|
+
// The block of earlier releases, which always ran npx and hid its failures:
|
|
60
|
+
// recognized so the next setup can rewrite it.
|
|
61
|
+
export function legacyHookBlock(hook, version) {
|
|
62
|
+
const command = `npx --yes tracehub@${version} hook ${hook} "$@"`;
|
|
63
|
+
const body = hook === "pre-push"
|
|
64
|
+
? `if tracehub_input=$(mktemp); then\n if cat > "$tracehub_input"; then\n ${command} < "$tracehub_input" || true\n else\n printf '%s\\n' 'tracehub: unable to preserve push input; trace upload skipped' >&2\n fi\n exec < "$tracehub_input"\n rm -f "$tracehub_input"\nelse\n printf '%s\\n' 'tracehub: unable to preserve push input; trace upload skipped' >&2\nfi`
|
|
65
|
+
: `${command} </dev/null || true`;
|
|
66
|
+
return `${START}\n${body}\n${END}\n`;
|
|
67
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { findSessionFile } from "../local/discover.js";
|
|
4
|
+
import { sessionLines } from "../local/lines.js";
|
|
5
|
+
import { parseContextRef } from "../protocol/context.js";
|
|
6
|
+
import { formatSessionRef } from "../protocol/sessionRef.js";
|
|
7
|
+
function keyOf(marker) {
|
|
8
|
+
return `${marker.traceId} ${marker.session}`;
|
|
9
|
+
}
|
|
10
|
+
function parseMarker(line) {
|
|
11
|
+
let m;
|
|
12
|
+
try {
|
|
13
|
+
m = JSON.parse(line);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
const { traceId, session, line: at, ts } = m;
|
|
19
|
+
if (typeof traceId !== "string" || typeof session !== "string") {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
if (typeof at !== "number" || typeof ts !== "string")
|
|
23
|
+
return undefined;
|
|
24
|
+
const context = Array.isArray(m.context)
|
|
25
|
+
? m.context.filter((r) => typeof r === "string" && parseContextRef(r))
|
|
26
|
+
: [];
|
|
27
|
+
return {
|
|
28
|
+
traceId,
|
|
29
|
+
session,
|
|
30
|
+
line: at,
|
|
31
|
+
ts,
|
|
32
|
+
...(context.length ? { context } : {}),
|
|
33
|
+
uploaded: m.uploaded === true,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
// The file is a log: the last line per trace id and session wins, so a
|
|
37
|
+
// commit that is amended replaces its marker by appending a new one.
|
|
38
|
+
export function parseMarkers(text) {
|
|
39
|
+
const byKey = new Map();
|
|
40
|
+
for (const line of text.split("\n")) {
|
|
41
|
+
const marker = line.trim() ? parseMarker(line) : undefined;
|
|
42
|
+
if (marker)
|
|
43
|
+
byKey.set(keyOf(marker), marker);
|
|
44
|
+
}
|
|
45
|
+
return [...byKey.values()];
|
|
46
|
+
}
|
|
47
|
+
export function serializeMarkers(markers) {
|
|
48
|
+
return markers.map((m) => `${JSON.stringify(m)}\n`).join("");
|
|
49
|
+
}
|
|
50
|
+
function markersFile(stateDir) {
|
|
51
|
+
return join(stateDir, "markers.jsonl");
|
|
52
|
+
}
|
|
53
|
+
export function readMarkers(stateDir) {
|
|
54
|
+
const file = markersFile(stateDir);
|
|
55
|
+
return existsSync(file) ? parseMarkers(readFileSync(file, "utf8")) : [];
|
|
56
|
+
}
|
|
57
|
+
export function pendingMarkers(markers) {
|
|
58
|
+
return markers.filter((m) => !m.uploaded);
|
|
59
|
+
}
|
|
60
|
+
export function markUploaded(markers, done) {
|
|
61
|
+
const keys = new Set(done.map(keyOf));
|
|
62
|
+
return markers.map((m) => keys.has(keyOf(m)) ? { ...m, uploaded: true } : m);
|
|
63
|
+
}
|
|
64
|
+
export function saveUploaded(stateDir, done) {
|
|
65
|
+
if (!done.length)
|
|
66
|
+
return;
|
|
67
|
+
const markers = markUploaded(readMarkers(stateDir), done);
|
|
68
|
+
writeFileSync(markersFile(stateDir), serializeMarkers(markers));
|
|
69
|
+
}
|
|
70
|
+
// A commit marks where each of its sessions stood when it was made: the
|
|
71
|
+
// session's line count at that moment, which tracehub turns into a slice.
|
|
72
|
+
// Returns the sessions whose file is not on this machine.
|
|
73
|
+
export function recordMarkers(stateDir, traceId, sessions, now = new Date(), context = []) {
|
|
74
|
+
const missing = [];
|
|
75
|
+
mkdirSync(stateDir, { recursive: true });
|
|
76
|
+
for (const ref of sessions) {
|
|
77
|
+
const file = findSessionFile(ref);
|
|
78
|
+
if (!file) {
|
|
79
|
+
missing.push(ref);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const marker = {
|
|
83
|
+
traceId,
|
|
84
|
+
session: formatSessionRef(ref),
|
|
85
|
+
line: sessionLines(ref, file).length,
|
|
86
|
+
ts: now.toISOString(),
|
|
87
|
+
...(context.length ? { context } : {}),
|
|
88
|
+
uploaded: false,
|
|
89
|
+
};
|
|
90
|
+
appendFileSync(markersFile(stateDir), `${JSON.stringify(marker)}\n`);
|
|
91
|
+
}
|
|
92
|
+
return missing;
|
|
93
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const TRAILER_KEY = "Assisted-by";
|
|
2
|
+
// The dashboard, where a trailer links to its trace.
|
|
3
|
+
const DASHBOARD_URL = "https://tracehub.aui.dev";
|
|
4
|
+
const ID = /^[0-9a-f]{16}$/;
|
|
5
|
+
// The trailer's value is the trace's URL, or the bare trace id.
|
|
6
|
+
const LINE = /^[ \t]*Assisted-by:[ \t]*(?:\S*\/)?([0-9a-f]{16})[ \t]*$/gm;
|
|
7
|
+
export function isTraceId(s) {
|
|
8
|
+
return ID.test(s);
|
|
9
|
+
}
|
|
10
|
+
export function newTraceId() {
|
|
11
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
12
|
+
}
|
|
13
|
+
// The trace's page on the dashboard, so GitHub links the trailer.
|
|
14
|
+
export function traceUrl(target, id) {
|
|
15
|
+
return `${DASHBOARD_URL}/t/${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${id}`;
|
|
16
|
+
}
|
|
17
|
+
// Every "Assisted-by: <id or URL>" line anywhere in the message, in order: a squash
|
|
18
|
+
// (git's, indented, or GitHub's) folds the trailers of the squashed commits
|
|
19
|
+
// into the body, where git's own trailer parser no longer sees them.
|
|
20
|
+
export function traceIds(message) {
|
|
21
|
+
return [...new Set([...message.matchAll(LINE)].map((m) => m[1]))];
|
|
22
|
+
}
|
|
23
|
+
export function interpretTrailersArgs(target, id, messageFile) {
|
|
24
|
+
return [
|
|
25
|
+
"interpret-trailers",
|
|
26
|
+
"--in-place",
|
|
27
|
+
"--trailer",
|
|
28
|
+
`${TRAILER_KEY}: ${traceUrl(target, id)}`,
|
|
29
|
+
messageFile,
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
export function shouldSkipCommit(source, env) {
|
|
33
|
+
if (env["TRACEHUB"] === "0")
|
|
34
|
+
return true;
|
|
35
|
+
return source === "merge" || source === "squash";
|
|
36
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { parseClaude } from "../transcript/parseClaude.js";
|
|
2
|
+
import { parseCodex } from "../transcript/parseCodex.js";
|
|
3
|
+
import { parseOpencode } from "../transcript/parseOpencode.js";
|
|
4
|
+
export function isCommitCommand(command) {
|
|
5
|
+
return /\bgit(?:\s+-[Cc]\s+(?:"[^"]*"|'[^']*'|[^\s;]+)|\s+--[a-z-]+(?:=[^\s;]+)?)*\s+commit\b/.test(command);
|
|
6
|
+
}
|
|
7
|
+
const EXECUTION_TOOL = /(?:^|[._])(?:bash|shell|terminal|exec|exec_command|execute_command|run_command|run_shell_command|run_terminal_cmd)$/i;
|
|
8
|
+
function eventsOf(agent, line, sidechain) {
|
|
9
|
+
switch (agent) {
|
|
10
|
+
case "claude":
|
|
11
|
+
return parseClaude(line, "", { sidechain }).events;
|
|
12
|
+
case "codex":
|
|
13
|
+
return parseCodex(line, "").events;
|
|
14
|
+
case "opencode":
|
|
15
|
+
return parseOpencode(line, "").events;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
// The `git commit` calls of a transcript that have no result yet. The
|
|
19
|
+
// command running Git cannot have a result in its agent's transcript until
|
|
20
|
+
// Git exits, so its identity is retained instead of guessing a time window.
|
|
21
|
+
// `sidechain` reads a Claude Code subagent's own transcript.
|
|
22
|
+
export function openCommitCalls(agent, lines, sidechain = false) {
|
|
23
|
+
const pending = new Map();
|
|
24
|
+
for (const line of lines) {
|
|
25
|
+
for (const event of eventsOf(agent, line, sidechain)) {
|
|
26
|
+
if (event.kind === "tool_call" &&
|
|
27
|
+
EXECUTION_TOOL.test(event.name) &&
|
|
28
|
+
isCommitCommand(event.arg))
|
|
29
|
+
pending.set(event.callId, event.arg);
|
|
30
|
+
if (event.kind === "tool_result")
|
|
31
|
+
pending.delete(event.callId);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return [...pending].map(([callId, command]) => ({ callId, command }));
|
|
35
|
+
}
|
|
36
|
+
export function pendingCommitCall(agent, lines) {
|
|
37
|
+
return openCommitCalls(agent, lines).at(-1)?.callId || undefined;
|
|
38
|
+
}
|