@bli-cockpit/telemetry-core 0.1.111 → 0.1.112

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 (35) hide show
  1. package/dist/collector-heartbeat.d.ts +17 -0
  2. package/dist/evidence-upload.d.ts +16 -0
  3. package/dist/evidence-upload.js +16 -0
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.js +3 -0
  6. package/dist/log-digest/log-projects.d.ts +1 -0
  7. package/dist/log-digest/log-projects.js +10 -3
  8. package/dist/log-digest/sources/collector.d.ts +2 -6
  9. package/dist/log-digest/sources/collector.js +70 -30
  10. package/dist/log-digest/sources/types.d.ts +1 -0
  11. package/dist/log-digest/sources/vercel-query.d.ts +17 -0
  12. package/dist/log-digest/sources/vercel-query.js +86 -0
  13. package/dist/log-digest/sources/vercel.d.ts +1 -1
  14. package/dist/log-digest/sources/vercel.js +77 -13
  15. package/dist/log-digest/tagged.d.ts +0 -1
  16. package/dist/log-digest/tagged.js +2 -4
  17. package/dist/log-digest/tower-classes.js +9 -1
  18. package/dist/mail-time.d.ts +1 -0
  19. package/dist/mail-time.js +24 -0
  20. package/dist/memory-hook-hours.d.ts +1 -0
  21. package/dist/memory-hook-hours.js +2 -1
  22. package/dist/memory-install-receipt.d.ts +18 -0
  23. package/dist/memory-install-receipt.js +12 -0
  24. package/dist/newest-check-runs.d.ts +21 -0
  25. package/dist/newest-check-runs.js +20 -0
  26. package/dist/provider-billing.d.ts +5 -0
  27. package/dist/provider-billing.js +70 -0
  28. package/dist/session-facts-text.js +3 -0
  29. package/dist/session-facts.d.ts +2 -1
  30. package/dist/session-facts.js +10 -3
  31. package/dist/session-git-refs.d.ts +41 -0
  32. package/dist/session-git-refs.js +362 -0
  33. package/dist/work-project-reference.d.ts +7 -0
  34. package/dist/work-project-reference.js +8 -0
  35. package/package.json +17 -2
@@ -0,0 +1,362 @@
1
+ /**
2
+ * BLI-27624: every branch, commit and pull request a coding session touched, read from its transcript lines.
3
+ *
4
+ * A session often starts on main and creates its branch partway through, so the one branch the collector records
5
+ * cannot match a pull request's head branch. The transcript says what really happened: Claude stamps every record
6
+ * with the branch it was on, a "git checkout -b" or "git push" names the branch, "git commit" and "git push" print the
7
+ * new commit, and "gh pr create" prints the pull request address.
8
+ *
9
+ * Streaming and allowlisted: only branch names, commit hashes and "owner/repo#number" pairs leave the text. No prompt, reply, command
10
+ * or file is kept. The collector runs it while it reads a file (the same pass as the session facts) and the server runs
11
+ * it over stored evidence, so both sides agree on what a session touched.
12
+ */
13
+ export const GIT_REFS_BRANCH_LIMIT = 50;
14
+ export const GIT_REFS_SHA_LIMIT = 200;
15
+ export const GIT_REFS_PULL_REQUEST_LIMIT = 30;
16
+ const NOT_A_BRANCH = new Set(["head", "main", "master", "unknown", "develop", "trunk", "origin", "upstream", "-", ""]);
17
+ const BRANCH_NAME = /^[A-Za-z0-9._\-/+@#]{1,200}$/;
18
+ const SHORT_OR_FULL_SHA = /^[0-9a-f]{7,40}$/;
19
+ const PULL_REQUEST_URL = /https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/g;
20
+ const COMMIT_LINE = /^\[([^\]\s]+)(?: \([^)]*\))? ([0-9a-f]{7,40})\]/gm;
21
+ const PUSH_LINE = /^\s*(?:\+\s+|\*\s+)?(?:\[new branch\]|\[new tag\]|[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40}))\s+(\S+)\s+->\s+(\S+)\s*$/gm;
22
+ const GITBRANCH_KEY = '"gitBranch":"';
23
+ const LONG_RESULT_SLICE = 30_000;
24
+ export function extractSessionGitRefs(content) {
25
+ const accumulator = createGitRefsAccumulator();
26
+ for (const line of content.split("\n"))
27
+ accumulator.observeLine(line);
28
+ return accumulator.finalize();
29
+ }
30
+ export function hasGitRefs(refs) {
31
+ return refs.branches.length + refs.commit_shas.length + refs.pull_requests.length > 0;
32
+ }
33
+ export function emptyGitRefs() {
34
+ return { branches: [], commit_shas: [], pull_requests: [] };
35
+ }
36
+ export function createGitRefsAccumulator() {
37
+ const branches = new Set();
38
+ const shas = new Set();
39
+ const pullRequests = new Map();
40
+ const pullRequestCreateCalls = new Set();
41
+ const addBranch = (name) => {
42
+ const branch = cleanBranch(name);
43
+ if (branch && branches.size < GIT_REFS_BRANCH_LIMIT)
44
+ branches.add(branch);
45
+ };
46
+ const addSha = (sha) => {
47
+ const lower = sha?.toLowerCase();
48
+ if (lower && SHORT_OR_FULL_SHA.test(lower) && shas.size < GIT_REFS_SHA_LIMIT)
49
+ shas.add(lower);
50
+ };
51
+ const addPullRequest = (repo, number) => {
52
+ const key = repo.toLowerCase() + "#" + number;
53
+ if (!pullRequests.has(key) && pullRequests.size < GIT_REFS_PULL_REQUEST_LIMIT && Number.isSafeInteger(number) && number > 0) {
54
+ pullRequests.set(key, { repo: repo.toLowerCase(), number });
55
+ }
56
+ };
57
+ const addPullRequestUrls = (text) => {
58
+ for (const match of text.matchAll(PULL_REQUEST_URL))
59
+ addPullRequest(match[1] + "/" + match[2], Number(match[3]));
60
+ };
61
+ const readPrintedGit = (text) => {
62
+ const slice = text.length > 2 * LONG_RESULT_SLICE ? text.slice(0, LONG_RESULT_SLICE) + "\n" + text.slice(-LONG_RESULT_SLICE) : text;
63
+ for (const match of slice.matchAll(COMMIT_LINE)) {
64
+ addBranch(match[1]);
65
+ addSha(match[2]);
66
+ }
67
+ for (const match of slice.matchAll(PUSH_LINE)) {
68
+ if (match[2] !== match[3])
69
+ continue;
70
+ addBranch(match[3]);
71
+ addSha(match[1]);
72
+ }
73
+ };
74
+ const observeRecord = (record) => {
75
+ if (typeof record["gitBranch"] === "string")
76
+ addBranch(record["gitBranch"]);
77
+ if (record["type"] === "pr-link") {
78
+ const repository = typeof record["prRepository"] === "string" ? record["prRepository"].replace(/^https?:\/\/github\.com\//i, "") : null;
79
+ if (repository && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository))
80
+ addPullRequest(repository, Number(record["prNumber"]));
81
+ else if (typeof record["prUrl"] === "string")
82
+ addPullRequestUrls(record["prUrl"]);
83
+ }
84
+ if (record["type"] === "session_meta")
85
+ addBranch(codexMetaBranch(record));
86
+ const executed = commandExecution(record);
87
+ if (executed) {
88
+ const parsed = readCommand(executed.command);
89
+ for (const branch of parsed.branches)
90
+ addBranch(branch);
91
+ readPrintedGit(executed.output);
92
+ if (parsed.createsPullRequest)
93
+ addPullRequestUrls(executed.output);
94
+ }
95
+ for (const call of commandCalls(record)) {
96
+ const parsed = readCommand(call.command);
97
+ for (const branch of parsed.branches)
98
+ addBranch(branch);
99
+ if (parsed.createsPullRequest && call.id)
100
+ pullRequestCreateCalls.add(call.id);
101
+ }
102
+ for (const result of commandResults(record)) {
103
+ readPrintedGit(result.text);
104
+ if (result.id && pullRequestCreateCalls.has(result.id))
105
+ addPullRequestUrls(result.text);
106
+ }
107
+ };
108
+ return {
109
+ observeRecord,
110
+ observeLine(line) {
111
+ const keyAt = line.indexOf(GITBRANCH_KEY);
112
+ if (keyAt !== -1) {
113
+ const start = keyAt + GITBRANCH_KEY.length;
114
+ const end = line.indexOf('"', start);
115
+ if (end !== -1 && end - start <= 200)
116
+ addBranch(line.slice(start, end));
117
+ }
118
+ const isCall = line.includes('"type":"tool_use"') || line.includes('"type":"function_call"') || line.includes('"type":"local_shell_call"') || line.includes('"type":"custom_tool_call"');
119
+ const isResult = line.includes('"type":"tool_result"') || line.includes('"type":"function_call_output"') || line.includes('"type":"custom_tool_call_output"');
120
+ const isCommandExecution = line.includes('"type":"CommandExecution"');
121
+ const isOther = line.includes('"pr-link"') || line.includes('"session_meta"');
122
+ if (!isCall && !isResult && !isCommandExecution && !isOther)
123
+ return;
124
+ if (isCall && !isResult && !isCommandExecution && !isOther && !(line.includes("git") || line.includes("gh")))
125
+ return;
126
+ if (isResult && !isCommandExecution && !isOther && !mayCarryGitOutput(line, pullRequestCreateCalls))
127
+ return;
128
+ if (isCommandExecution && !isOther && !(line.includes("git") || line.includes("gh")))
129
+ return;
130
+ const record = parseObject(line);
131
+ if (record)
132
+ observeRecord(record);
133
+ },
134
+ finalize() {
135
+ return { branches: [...branches], commit_shas: [...shas], pull_requests: [...pullRequests.values()] };
136
+ },
137
+ };
138
+ }
139
+ function mayCarryGitOutput(line, pending) {
140
+ for (const id of pending)
141
+ if (line.includes(id))
142
+ return true;
143
+ if (line.includes(" -> ") || line.includes("(root-commit)"))
144
+ return true;
145
+ return /\[[^\]\s"\\]+ (?:\([^)]*\) )?[0-9a-f]{7,40}\]/.test(line.length > 200_000 ? line.slice(0, 200_000) : line);
146
+ }
147
+ function parseObject(line) {
148
+ try {
149
+ const value = JSON.parse(line);
150
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
151
+ }
152
+ catch {
153
+ return null;
154
+ }
155
+ }
156
+ function asRecord(value) {
157
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
158
+ }
159
+ /** Codex "CommandExecution" items carry the command and what it printed together. */
160
+ function commandExecution(record) {
161
+ const item = asRecord(asRecord(record["payload"])?.["item"]);
162
+ if (item?.["type"] !== "CommandExecution" || typeof item["command"] !== "string")
163
+ return null;
164
+ return { command: item["command"], output: typeof item["aggregated_output"] === "string" ? item["aggregated_output"] : "" };
165
+ }
166
+ function codexMetaBranch(record) {
167
+ const git = asRecord(asRecord(record["payload"])?.["git"]);
168
+ return typeof git?.["branch"] === "string" ? git["branch"] : null;
169
+ }
170
+ /** Claude "tool_use" blocks and Codex "function_call" items: the shell text each one ran. */
171
+ function commandCalls(record) {
172
+ const calls = [];
173
+ const message = asRecord(record["message"]);
174
+ const blocks = Array.isArray(message?.["content"]) ? message["content"] : [];
175
+ for (const block of blocks) {
176
+ const item = asRecord(block);
177
+ if (item?.["type"] !== "tool_use")
178
+ continue;
179
+ const command = shellText(asRecord(item["input"]));
180
+ if (command)
181
+ calls.push({ id: typeof item["id"] === "string" ? item["id"] : null, command });
182
+ }
183
+ const payload = asRecord(record["payload"]);
184
+ const kind = payload?.["type"];
185
+ if (payload && (kind === "function_call" || kind === "local_shell_call" || kind === "custom_tool_call")) {
186
+ const raw = payload["arguments"] ?? payload["input"] ?? payload["action"];
187
+ const args = typeof raw === "string" ? parseObject(raw) : asRecord(raw);
188
+ const command = shellText(args) ?? (typeof raw === "string" && raw.includes("git ") ? raw : null);
189
+ const id = typeof payload["call_id"] === "string" ? payload["call_id"] : typeof payload["id"] === "string" ? payload["id"] : null;
190
+ if (command)
191
+ calls.push({ id, command });
192
+ }
193
+ return calls;
194
+ }
195
+ function shellText(input) {
196
+ const value = input?.["command"] ?? input?.["cmd"];
197
+ if (typeof value === "string")
198
+ return value;
199
+ if (Array.isArray(value) && value.every((part) => typeof part === "string")) {
200
+ const parts = value;
201
+ if (parts.length >= 3 && /(?:^|\/)(?:ba|z)?sh$/.test(parts[0]) && /^-\w*c$/.test(parts[1]))
202
+ return parts[2];
203
+ return parts.join(" ");
204
+ }
205
+ return null;
206
+ }
207
+ /** Claude "tool_result" blocks and Codex "function_call_output" items: the text each one printed. */
208
+ function commandResults(record) {
209
+ const results = [];
210
+ const message = asRecord(record["message"]);
211
+ const blocks = Array.isArray(message?.["content"]) ? message["content"] : [];
212
+ for (const block of blocks) {
213
+ const item = asRecord(block);
214
+ if (item?.["type"] !== "tool_result")
215
+ continue;
216
+ const text = resultText(item["content"]);
217
+ if (text)
218
+ results.push({ id: typeof item["tool_use_id"] === "string" ? item["tool_use_id"] : null, text });
219
+ }
220
+ const payload = asRecord(record["payload"]);
221
+ if (payload?.["type"] === "function_call_output" || payload?.["type"] === "custom_tool_call_output") {
222
+ const text = resultText(payload["output"]);
223
+ if (text)
224
+ results.push({ id: typeof payload["call_id"] === "string" ? payload["call_id"] : null, text });
225
+ }
226
+ return results;
227
+ }
228
+ function resultText(value) {
229
+ if (typeof value === "string") {
230
+ if (value.startsWith("{")) {
231
+ const inner = asRecord(parseObject(value));
232
+ if (inner && typeof inner["output"] === "string")
233
+ return inner["output"];
234
+ }
235
+ return value;
236
+ }
237
+ if (Array.isArray(value))
238
+ return value.map((part) => (asRecord(part) && typeof asRecord(part)["text"] === "string" ? asRecord(part)["text"] : "")).join("\n");
239
+ return "";
240
+ }
241
+ function cleanBranch(name) {
242
+ if (typeof name !== "string")
243
+ return null;
244
+ let branch = name.trim().replace(/^refs\/heads\//, "").replace(/^refs\/remotes\/origin\//, "");
245
+ const colon = branch.indexOf(":");
246
+ if (colon !== -1 && !branch.startsWith("detached:"))
247
+ branch = branch.slice(colon + 1).replace(/^refs\/heads\//, "");
248
+ if (!BRANCH_NAME.test(branch) || branch.startsWith("-") || branch.startsWith("/") || branch.endsWith("/") || branch.includes(".."))
249
+ return null;
250
+ if (NOT_A_BRANCH.has(branch.toLowerCase()) || /^[0-9a-f]{40}$/.test(branch) || branch.startsWith("detached"))
251
+ return null;
252
+ return branch;
253
+ }
254
+ /** The branches a shell command creates or pushes and whether it opens a pull request. Variables and substitutions are skipped, never guessed. */
255
+ export function readCommand(rawCommand) {
256
+ const branches = [];
257
+ let createsPullRequest = false;
258
+ const wrapped = /^\S*(?:ba|z)?sh\s+-\w*c\s+(['"])([\s\S]*)\1\s*$/.exec(rawCommand.trim());
259
+ const command = wrapped ? wrapped[2] : rawCommand;
260
+ for (const segment of command.split(/&&|\|\||;|\||\r?\n/)) {
261
+ if (segment.includes("$(") || segment.includes("`"))
262
+ continue;
263
+ const words = shellWords(segment);
264
+ const first = words.findIndex((word) => word === "git" || word.endsWith("/git") || word === "gh");
265
+ if (first === -1)
266
+ continue;
267
+ if (words[first].endsWith("gh")) {
268
+ if (words[first + 1] === "pr" && words[first + 2] === "create") {
269
+ createsPullRequest = true;
270
+ const head = flagValue(words.slice(first + 3), ["--head", "-H"]);
271
+ if (head)
272
+ branches.push(head);
273
+ }
274
+ continue;
275
+ }
276
+ let at = first + 1;
277
+ while (at < words.length && words[at].startsWith("-"))
278
+ at += ["-C", "-c", "--git-dir", "--work-tree", "--namespace"].includes(words[at]) ? 2 : 1;
279
+ const subcommand = words[at];
280
+ const rest = words.slice(at + 1);
281
+ if (subcommand === "checkout")
282
+ branches.push(...flagValues(rest, ["-b", "-B", "--orphan"]));
283
+ else if (subcommand === "switch")
284
+ branches.push(...flagValues(rest, ["-c", "-C", "--create", "--force-create"]));
285
+ else if (subcommand === "worktree" && rest[0] === "add")
286
+ branches.push(...flagValues(rest, ["-b", "-B"]));
287
+ else if (subcommand === "branch")
288
+ branches.push(...createdBranch(rest));
289
+ else if (subcommand === "push")
290
+ branches.push(...pushedBranches(rest));
291
+ }
292
+ return { branches: branches.filter((branch) => !/[$`()*{}]/.test(branch)), createsPullRequest };
293
+ }
294
+ function flagValue(words, flags) {
295
+ return flagValues(words, flags)[0] ?? null;
296
+ }
297
+ function flagValues(words, flags) {
298
+ const values = [];
299
+ for (let index = 0; index < words.length; index += 1) {
300
+ const word = words[index];
301
+ const equals = word.indexOf("=");
302
+ if (flags.includes(word) && words[index + 1])
303
+ values.push(words[index + 1]);
304
+ else if (equals > 0 && flags.includes(word.slice(0, equals)))
305
+ values.push(word.slice(equals + 1));
306
+ }
307
+ return values;
308
+ }
309
+ function createdBranch(words) {
310
+ if (words.some((word) => /^-(?:d|D|m|M|r|a|v|vv|u|-delete|-move|-list|-show-current|-unset-upstream|-set-upstream-to.*)$/.test(word)))
311
+ return [];
312
+ const positional = words.filter((word) => !word.startsWith("-"));
313
+ return positional.length > 0 ? [positional[0]] : [];
314
+ }
315
+ function pushedBranches(words) {
316
+ if (words.some((word) => word === "--delete" || word === "-d" || word === "--tags" || word === "--all" || word === "--mirror"))
317
+ return [];
318
+ const positional = words.filter((word) => !word.startsWith("-"));
319
+ return positional.slice(1).map((refspec) => {
320
+ const target = refspec.includes(":") ? refspec.slice(refspec.indexOf(":") + 1) : refspec;
321
+ return target.replace(/^\+/, "").replace(/^refs\/heads\//, "");
322
+ });
323
+ }
324
+ /** Whitespace split that keeps quoted text together and drops the quotes. */
325
+ function shellWords(segment) {
326
+ const words = [];
327
+ let current = "";
328
+ let quote = null;
329
+ let started = false;
330
+ for (let index = 0; index < segment.length; index += 1) {
331
+ const char = segment[index];
332
+ if (quote) {
333
+ if (char === quote)
334
+ quote = null;
335
+ else if (char === "\\" && quote === '"' && index + 1 < segment.length)
336
+ current += segment[++index];
337
+ else
338
+ current += char;
339
+ }
340
+ else if (char === '"' || char === "'") {
341
+ quote = char;
342
+ started = true;
343
+ }
344
+ else if (/\s/.test(char)) {
345
+ if (started || current)
346
+ words.push(current);
347
+ current = "";
348
+ started = false;
349
+ }
350
+ else if (char === "\\" && index + 1 < segment.length) {
351
+ current += segment[++index];
352
+ started = true;
353
+ }
354
+ else {
355
+ current += char;
356
+ started = true;
357
+ }
358
+ }
359
+ if (started || current)
360
+ words.push(current);
361
+ return words;
362
+ }
@@ -0,0 +1,7 @@
1
+ interface VisibleWorkProject {
2
+ id: string;
3
+ name: string;
4
+ archived_at?: string | null;
5
+ }
6
+ export declare function matchWorkProject<Project extends VisibleWorkProject>(projects: readonly Project[], reference: string): Project | undefined;
7
+ export {};
@@ -0,0 +1,8 @@
1
+ export function matchWorkProject(projects, reference) {
2
+ const wanted = reference.trim().toLowerCase();
3
+ const exact = projects.find((project) => project.id.toLowerCase() === wanted || project.name.toLowerCase() === wanted);
4
+ if (exact || wanted !== "tower")
5
+ return exact;
6
+ const canonical = projects.filter((project) => !project.archived_at && project.name.toLowerCase() === "bli cockpit");
7
+ return canonical.length === 1 ? canonical[0] : undefined;
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.111",
3
+ "version": "0.1.112",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -50,6 +50,11 @@
50
50
  "import": "./dist/node-read-cache.js",
51
51
  "default": "./dist/node-read-cache.js"
52
52
  },
53
+ "./newest-check-runs": {
54
+ "types": "./dist/newest-check-runs.d.ts",
55
+ "import": "./dist/newest-check-runs.js",
56
+ "default": "./dist/newest-check-runs.js"
57
+ },
53
58
  "./github-app-token": {
54
59
  "types": "./dist/github-app-token.d.ts",
55
60
  "import": "./dist/github-app-token.js",
@@ -59,6 +64,16 @@
59
64
  "types": "./dist/gated-paths.d.ts",
60
65
  "import": "./dist/gated-paths.js",
61
66
  "default": "./dist/gated-paths.js"
67
+ },
68
+ "./work-next-order": {
69
+ "types": "./dist/work-next-order.d.ts",
70
+ "import": "./dist/work-next-order.js",
71
+ "default": "./dist/work-next-order.js"
72
+ },
73
+ "./provider-billing": {
74
+ "types": "./dist/provider-billing.d.ts",
75
+ "import": "./dist/provider-billing.js",
76
+ "default": "./dist/provider-billing.js"
62
77
  }
63
78
  },
64
79
  "publishConfig": {
@@ -69,7 +84,7 @@
69
84
  },
70
85
  "scripts": {
71
86
  "build": "tsc",
72
- "prepack": "rm -rf dist && tsc",
87
+ "prepack": "node ../../scripts/clean-package-build.mjs && tsc",
73
88
  "typecheck": "tsc --noEmit",
74
89
  "test": "vitest run"
75
90
  },