@codetelemetry/mcp 0.4.1 → 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.
package/README.md CHANGED
@@ -31,13 +31,55 @@ deterministic (see [Releases & discovery](#releases--discovery)):
31
31
  ```json
32
32
  {
33
33
  "mcpServers": {
34
- "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.4.1", "codetelemetry-mcp"] }
34
+ "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.5.0", "codetelemetry-mcp"] }
35
35
  }
36
36
  }
37
37
  ```
38
38
 
39
39
  Then just ask the agent: **"Connect me to CodeTelemetry."**
40
40
 
41
+ ## Join an existing organization
42
+
43
+ After accepting an invitation, choose **Explore the team’s work** to review existing
44
+ sessions without local setup, or **Connect my coding tool** to record your own work.
45
+ Run the project connection command from the repository you choose:
46
+
47
+ ```sh
48
+ npx -y @codetelemetry/connect@0.3.0 join --organization-id tm_example --client codex --project .
49
+ # For Claude Code, use --client claude.
50
+ ```
51
+
52
+ Join uses the existing organization's ID and your own device approval. It resumes
53
+ a saved connection after interruption, enables prompt/tool capture and repository
54
+ observation for new connections, and preserves existing capture choices. Pass
55
+ `--no-enrich` when making a new connection to opt out. It never creates an organization,
56
+ purchases credits/seats, or executes optional Grader, Terraform or GitHub steps from
57
+ an older bootstrap plan. A conflicting project destination is an error.
58
+
59
+ Setup prints a saved workspace name and its launch instructions. Claude uses local
60
+ project settings; Codex uses `connect run <name>` to select its named config-file
61
+ profile. An already-open client does not adopt that profile automatically. The
62
+ browser progress link checks your real session, captured prompt, and project
63
+ identity separately from the connection test. Imported history cannot satisfy live
64
+ verification. **My sessions** is scoped to your authenticated ingest ownership;
65
+ **Team sessions** shows the selected organization's activity.
66
+
67
+ Optional history import uses the saved project and credentials, without a key argument:
68
+
69
+ ```sh
70
+ npx -y @codetelemetry/connect@0.3.0 import --workspace <name> --preview
71
+ # Choose numbers from that preview; no session content uploads until confirmation:
72
+ npx -y @codetelemetry/connect@0.3.0 import --workspace <name> --select 1,2 --confirm
73
+ ```
74
+
75
+ Preview is local-only and defaults to the last 30 days. It keeps at most 100 session
76
+ plans in a private file bounded to 64 KiB and valid for 24 hours. Discovery examines
77
+ at most 10,000 directory entries, parsing reads at most 128 MiB with 64 MiB per session,
78
+ and one scan is bounded to two minutes. Import rechecks destination and exact selected
79
+ plans before uploading, preserves the saved content choice, and reuses deduplication
80
+ and resumable delivery. Narrow `--since` and preview again if a bound is reached.
81
+ Preview files contain identifiers and counts, never credentials or session content.
82
+
41
83
  ## Persistent organization workspaces
42
84
 
43
85
  Ask the agent: **Create a Acme workspace for this repository and configure its Grader.**
@@ -73,8 +115,8 @@ member visibility during creation, and administrators can change it in settings.
73
115
  `--plan file.json` supplies the same bootstrap fields as the MCP tool, including
74
116
  selected Grader checks. CLI exit 2 means setup is waiting for the returned action;
75
117
  exit 0 means the requested checks completed. Funding is checked before client
76
- configuration. No credits or seats are purchased. Content and repository observation
77
- remain separate explicit opt-ins.
118
+ configuration. No credits or seats are purchased. Capture follows the saved choice;
119
+ repository observation remains a separate setup option (enabled by project join).
78
120
 
79
121
  Credentials are private version-1 JSON files under
80
122
  `$CODETELEMETRY_CONTEXT_HOME/<name>.json`, defaulting to
@@ -19,6 +19,7 @@ export declare function bootstrapWorkspace(options: BootstrapOptions, environmen
19
19
  apiBase?: string;
20
20
  fetchImpl?: FetchLike;
21
21
  timeoutMs?: number;
22
+ connectionOnly?: boolean;
22
23
  }): Promise<{
23
24
  nextAction?: string | undefined;
24
25
  ok: boolean;
@@ -333,7 +333,7 @@ export async function bootstrapWorkspace(options, environment = {}) {
333
333
  state.steps.scope = "verified";
334
334
  delete state.steps.funding;
335
335
  delete state.steps.telemetry;
336
- bindWorkspace(state.plan.repositoryPath, context);
336
+ bindWorkspace(state.plan.repositoryPath, context, state.plan.client);
337
337
  state.steps.repository = "bound";
338
338
  checkpoint();
339
339
  if (verified.state === "budget_exhausted")
@@ -434,6 +434,7 @@ export async function bootstrapWorkspace(options, environment = {}) {
434
434
  state.probe.key !== keyHash(context.ingestKey) ||
435
435
  Date.now() - state.probe.at > 3_000_000) {
436
436
  const sent = await sendTestEvent({
437
+ context: { project: state.plan.repositoryPath, client: state.plan.client },
437
438
  key: context.ingestKey,
438
439
  ingestEndpoint: context.ingestEndpoint,
439
440
  fetchImpl,
@@ -460,6 +461,10 @@ export async function bootstrapWorkspace(options, environment = {}) {
460
461
  return result("ingestion_pending", `Telemetry verification returned ${landed.state}; resume to check the same probe.`);
461
462
  state.steps.telemetry = "verified";
462
463
  checkpoint();
464
+ if (environment.connectionOnly)
465
+ return result("ready", undefined, {
466
+ scope: context.scope, binding: bindingOf(context), verification: { ingestion: true, liveSession: "not_verified" },
467
+ });
463
468
  if (state.plan.checks?.length) {
464
469
  const checks = [];
465
470
  let config = {};
@@ -1,4 +1,6 @@
1
1
  import fs from "node:fs";
2
+ import { joinOrganization, workspaceProject } from "./join.js";
3
+ import { importWorkspaceHistory } from "./workspaceImport.js";
2
4
  import { bootstrapWorkspace } from "./bootstrap.js";
3
5
  import { listWorkspaces, loadWorkspace, bindWorkspace, bindingOf, findWorkspaceBinding, sameWorkspace, writeCodexWorkspaceProfile } from "./workspaces.js";
4
6
  import { runKiroCommand } from "./kiro/command.js";
@@ -44,6 +46,12 @@ function parse(argv) {
44
46
  const HELP = `codetelemetry-connect — wire Claude Code, OpenAI Codex or pi into CodeTelemetry
45
47
 
46
48
  Usage:
49
+ codetelemetry-connect join --organization-id ID --client claude|codex [--project PATH]
50
+ Connect this project; resume the same command after interruption.
51
+ codetelemetry-connect import --workspace NAME --preview
52
+ Preview this project's past sessions locally; nothing uploads.
53
+ codetelemetry-connect import --workspace NAME --select 1,2 --confirm
54
+ Import selected sessions from the latest preview.
47
55
  codetelemetry-connect <cot_key> [options] Write config, send a test event, confirm it landed
48
56
  codetelemetry-connect run <name> -- <coding-client arguments>
49
57
  Start the coding client with this context and isolated telemetry.
@@ -395,7 +403,7 @@ async function runImportCommand(positional, flags, endpoints, settingsOpts, clie
395
403
  export async function run(argv) {
396
404
  if (argv[0] === "run") {
397
405
  const context = loadWorkspace(argv[1]);
398
- const binding = findWorkspaceBinding();
406
+ const binding = findWorkspaceBinding(process.cwd(), context.name);
399
407
  if (binding && !sameWorkspace(binding, context))
400
408
  throw new Error("Selected context conflicts with this repository.");
401
409
  const verified = await verifyScope({ key: context.ingestKey, connectivityUrl: resolveEndpoints({ apiBase: context.apiBase }).connectivityUrl, expected: context.scope });
@@ -405,7 +413,9 @@ export async function run(argv) {
405
413
  const args = argv.slice(argv[2] === "--" ? 3 : 2);
406
414
  if (client === "codex")
407
415
  writeCodexWorkspaceProfile(context, context.clientConfig);
408
- const child = spawn(client, client === "codex" ? ["--profile", `codetelemetry-${context.name}`, ...args] : args, { stdio: "inherit", env: { ...process.env, CODETELEMETRY_WORKSPACE: context.name } });
416
+ if (args.some(arg => arg === "-C" || arg === "--cd" || arg.startsWith("--cd=")))
417
+ throw new Error("Run uses the saved project directory; connect a different project before changing it.");
418
+ const child = spawn(client, client === "codex" ? ["--profile", `codetelemetry-${context.name}`, ...args] : args, { cwd: workspaceProject(context), stdio: "inherit", env: { ...process.env, CODETELEMETRY_WORKSPACE: context.name } });
409
419
  return await new Promise((resolve, reject) => { child.once("error", () => reject(new Error("Coding client could not start; check its installation."))); child.once("exit", code => resolve(code ?? 1)); });
410
420
  }
411
421
  const { _, flags } = parse(argv);
@@ -414,6 +424,51 @@ export async function run(argv) {
414
424
  out(HELP);
415
425
  return 0;
416
426
  }
427
+ if (cmd === "join") {
428
+ const rogue = unknownFlag(flags, new Set(["organization-id", "client", "project", "enrich", "reauthorize", "open", "json", "api-base"]));
429
+ if (rogue)
430
+ throw new Error(`Unknown join option --${rogue}.`);
431
+ if (typeof flags["organization-id"] !== "string" || (flags.client !== "claude" && flags.client !== "codex") ||
432
+ (flags.project !== undefined && typeof flags.project !== "string") ||
433
+ (flags.enrich !== undefined && typeof flags.enrich !== "boolean") ||
434
+ (flags.reauthorize !== undefined && typeof flags.reauthorize !== "boolean"))
435
+ throw new Error("Use join --organization-id ID --client claude|codex [--project PATH].");
436
+ const result = await joinOrganization({ organizationId: flags["organization-id"], client: flags.client,
437
+ repositoryPath: typeof flags.project === "string" ? flags.project : undefined,
438
+ enrich: typeof flags.enrich === "boolean" ? flags.enrich : undefined,
439
+ reauthorize: flags.reauthorize === true, apiBase: typeof flags["api-base"] === "string" ? flags["api-base"] : undefined }, { interactive: !flags.json, log: flags.json ? undefined : out,
440
+ open: flags.open !== false && !flags.json ? url => { openBrowser(url); } : undefined });
441
+ if (flags.json)
442
+ out(JSON.stringify(result, null, 2));
443
+ return result.ok ? 0 : 2;
444
+ }
445
+ if (cmd === "import" && flags.workspace !== undefined) {
446
+ const rogue = unknownFlag(flags, new Set(["workspace", "preview", "select", "confirm", "since", "json"]));
447
+ if (rogue)
448
+ throw new Error(`Unknown workspace-import option --${rogue}; destination and content come from the saved workspace.`);
449
+ if (typeof flags.workspace !== "string" || (flags.preview !== undefined && typeof flags.preview !== "boolean") ||
450
+ (flags.confirm !== undefined && typeof flags.confirm !== "boolean") ||
451
+ (flags.select !== undefined && (typeof flags.select !== "string" || !/^\d+(,\d+)*$/.test(flags.select) || flags.select.length > 400)))
452
+ throw new Error("Use import --workspace NAME --preview, or --select 1,2 --confirm.");
453
+ const since = typeof flags.since === "string" ? parseWhen(flags.since, Date.now()) : undefined;
454
+ if (since === null || (flags.since !== undefined && typeof flags.since !== "string"))
455
+ throw new Error("--since takes days, hours, or an ISO date.");
456
+ const result = await importWorkspaceHistory({ name: flags.workspace, preview: flags.preview === true,
457
+ confirm: flags.confirm === true, selections: typeof flags.select === "string" ? flags.select.split(",").map(Number) : undefined,
458
+ sinceMs: since });
459
+ if (flags.json)
460
+ out(JSON.stringify(result, null, 2));
461
+ else if (result.previewSessions) {
462
+ out(`Local preview for ${flags.workspace}: ${result.previewSessions.length} sessions. Nothing uploaded.`);
463
+ result.previewSessions.forEach((session, i) => out(`${i + 1}. ${session.source} ${session.sessionId} · ${new Date(session.endMs).toISOString()} · ${session.events} events`));
464
+ if (result.remaining)
465
+ out(`${result.remaining} additional sessions remain; narrow --since for another preview.`);
466
+ out(`Import selected numbers: npx -y @codetelemetry/connect@0.3.0 import --workspace ${flags.workspace} --select 1,2 --confirm`);
467
+ }
468
+ else
469
+ out(`Imported ${result.totals.sessions} sessions; ${result.remaining} remain. ${result.errors.slice(0, 3).join(" ")}`);
470
+ return result.ok ? 0 : 1;
471
+ }
417
472
  if (cmd === "workspace") {
418
473
  if (_[1] === "list") {
419
474
  out(JSON.stringify(listWorkspaces(), null, 2));
@@ -33,6 +33,14 @@ export type ImportSourceSummary = {
33
33
  };
34
34
  export type StopReason = "budget" | "auth" | "busy" | "time_limit" | "status_unavailable";
35
35
  export type ImportRunResult = {
36
+ previewSessions?: Array<{
37
+ source: ImportSource;
38
+ sessionId: string;
39
+ planId: string;
40
+ startMs: number;
41
+ endMs: number;
42
+ events: number;
43
+ }>;
36
44
  ok: boolean;
37
45
  run: string;
38
46
  dryRun: boolean;
@@ -15,6 +15,9 @@ export type ImportRunOptions = {
15
15
  email?: string;
16
16
  content?: Partial<ContentBySource>;
17
17
  dryRun?: boolean;
18
+ previewOnly?: boolean;
19
+ selectedPlans?: Readonly<Record<string, string>>;
20
+ boundedDiscovery?: boolean;
18
21
  maxSessions?: number;
19
22
  ratePerMinute?: number;
20
23
  timeLimitMs?: number;
@@ -2,8 +2,8 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { assertKey, keyHash, mask } from "../keys.js";
3
3
  import { resolveEndpoints } from "../config.js";
4
4
  import { sessionKeyOf } from "./model.js";
5
- import { ACTIVE_GRACE_MS, bump, contentOrDefault, emptySummary, importPrepared, prepareSession, resolveWindow, } from "./core.js";
6
- import { defaultClaudeProjectsDir, defaultCodexSessionsDir, parseCandidate, scanClaudeSessions, scanCodexSessions, } from "./sources/files.js";
5
+ import { ACTIVE_GRACE_MS, bump, contentOrDefault, emptySummary, importPrepared, prepareSession, resolveWindow, underProject, } from "./core.js";
6
+ import { defaultClaudeProjectsDir, defaultCodexSessionsDir, parseCandidate, candidateProjectDirectory, scanClaudeSessions, scanCodexSessions, } from "./sources/files.js";
7
7
  import { LedgerStore, resolveLedgerPath } from "./ledger.js";
8
8
  export { RETENTION_DAYS, DEFAULT_SINCE_DAYS, ACTIVE_GRACE_MS, IMPORT_VERSION, DEFAULT_RATE_PER_MINUTE, MAX_RATE_PER_MINUTE, DEFAULT_TIME_LIMIT_MS, } from "./core.js";
9
9
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
@@ -13,7 +13,7 @@ export async function runImport(opts) {
13
13
  const endpoints = resolveEndpoints(opts.endpoints);
14
14
  const now = opts.nowMs ?? Date.now();
15
15
  const clock = () => (opts.nowMs === undefined ? Date.now() : opts.nowMs);
16
- const dryRun = !!opts.dryRun;
16
+ const dryRun = !!opts.dryRun || !!opts.previewOnly;
17
17
  const warnings = [];
18
18
  const content = contentOrDefault(opts.content);
19
19
  const window = resolveWindow(now, opts.sinceMs, opts.untilMs);
@@ -26,17 +26,21 @@ export async function runImport(opts) {
26
26
  const wantCodex = !opts.source || opts.source === "all" || opts.source === "codex";
27
27
  const summaries = new Map();
28
28
  const found = [];
29
+ const boundedSelection = Boolean(opts.previewOnly || opts.selectedPlans || opts.boundedDiscovery);
30
+ const scanBudget = boundedSelection ? { remainingEntries: 10_000, deadline: Date.now() + 120_000 } : undefined;
31
+ const readBudget = scanBudget ? { remainingBytes: 128 * 1024 * 1024, deadline: scanBudget.deadline } : undefined;
32
+ const parseLimits = scanBudget ? { deadline: scanBudget.deadline, maxBytes: 64 * 1024 * 1024, budget: readBudget } : undefined;
29
33
  if (wantClaude) {
30
34
  const s = emptySummary("claude-code");
31
35
  summaries.set("claude-code", s);
32
- const files = scanClaudeSessions(opts.claudeDir ?? defaultClaudeProjectsDir());
36
+ const files = scanClaudeSessions(opts.claudeDir ?? defaultClaudeProjectsDir(), scanBudget);
33
37
  s.filesFound = files.length;
34
38
  found.push(...files);
35
39
  }
36
40
  if (wantCodex) {
37
41
  const s = emptySummary("codex");
38
42
  summaries.set("codex", s);
39
- const files = scanCodexSessions(opts.codexDir ?? defaultCodexSessionsDir());
43
+ const files = scanCodexSessions(opts.codexDir ?? defaultCodexSessionsDir(), scanBudget);
40
44
  s.filesFound = files.length;
41
45
  found.push(...files);
42
46
  }
@@ -52,6 +56,8 @@ export async function runImport(opts) {
52
56
  sha256Hex,
53
57
  };
54
58
  for (const c of found) {
59
+ if ((opts.previewOnly || opts.selectedPlans) && clock() - now > 120_000)
60
+ throw new Error("History scan reached its two-minute bound; narrow the date window and preview again.");
55
61
  const s = summaries.get(c.source);
56
62
  if (c.mtimeMs < window.sinceMs) {
57
63
  bump(s, "older");
@@ -61,7 +67,14 @@ export async function runImport(opts) {
61
67
  bump(s, "active");
62
68
  continue;
63
69
  }
64
- const parsed = await parseCandidate(c, content[c.source]);
70
+ if (readBudget && opts.project) {
71
+ const cwd = candidateProjectDirectory(c, readBudget);
72
+ if (cwd && !underProject(cwd, opts.project, prepareOpts.caseInsensitivePaths)) {
73
+ bump(s, "filtered");
74
+ continue;
75
+ }
76
+ }
77
+ const parsed = await parseCandidate(c, content[c.source], parseLimits);
65
78
  if (!parsed.ok) {
66
79
  bump(s, parsed.reason);
67
80
  warnings.push(`${c.source} ${c.file}: ${parsed.detail}; not imported`);
@@ -73,13 +86,15 @@ export async function runImport(opts) {
73
86
  }
74
87
  s.sessionsParsed++;
75
88
  const sessionKey = sessionKeyOf(parsed.session.source, parsed.session.sessionId);
89
+ if (opts.selectedPlans && !Object.prototype.hasOwnProperty.call(opts.selectedPlans, sessionKey))
90
+ continue;
76
91
  const done = ledger.get(hash, sessionKey);
77
92
  if (done && done.state === "complete" && done.fileSig === c.fileSig) {
78
93
  bump(s, "ledger");
79
94
  continue;
80
95
  }
81
96
  const reload = async () => {
82
- const again = await parseCandidate(c, content[c.source]);
97
+ const again = await parseCandidate(c, content[c.source], parseLimits);
83
98
  return again.ok ? again.session : null;
84
99
  };
85
100
  const p = await prepareSession(parsed.session, c.fileSig, reload, prepareOpts);
@@ -87,6 +102,8 @@ export async function runImport(opts) {
87
102
  bump(s, p);
88
103
  continue;
89
104
  }
105
+ if (opts.selectedPlans && opts.selectedPlans[sessionKey] !== p.plan.id)
106
+ throw new Error("A selected session changed since preview. Preview it again before importing.");
90
107
  if (seen.has(sessionKey)) {
91
108
  warnings.push(`${sessionKey} appears in more than one file; only the first is imported`);
92
109
  continue;
@@ -95,6 +112,19 @@ export async function runImport(opts) {
95
112
  s.candidates++;
96
113
  prepared.push(p);
97
114
  }
115
+ if (opts.previewOnly) {
116
+ const selected = prepared.sort((a, b) => b.endMs - a.endMs).slice(0, 100);
117
+ return {
118
+ ok: true, run: randomUUID(), dryRun: true, key: { masked: mask(key), keyHash: hash },
119
+ window: { sinceIso: new Date(window.sinceMs).toISOString(), untilIso: new Date(window.untilMs).toISOString(), clamped: window.clamped },
120
+ content, sources: [...summaries.values()],
121
+ totals: { sessions: selected.length, events: selected.reduce((n, p) => n + p.plan.events, 0),
122
+ metricPoints: selected.reduce((n, p) => n + p.plan.metricPoints, 0) },
123
+ remaining: Math.max(0, prepared.length - selected.length), stoppedBy: null, cleanup: [], warnings, errors: [],
124
+ previewSessions: selected.map(p => ({ source: p.source, sessionId: p.sessionId, planId: p.plan.id,
125
+ startMs: p.startMs, endMs: p.endMs, events: p.plan.events })),
126
+ };
127
+ }
98
128
  try {
99
129
  return await importPrepared(prepared, {
100
130
  ...prepareOpts,
@@ -11,8 +11,19 @@ export type SessionCandidate = {
11
11
  };
12
12
  export declare function defaultClaudeProjectsDir(home?: string): string;
13
13
  export declare function defaultCodexSessionsDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
- export declare function scanClaudeSessions(projectsDir: string): SessionCandidate[];
15
- export declare function scanCodexSessions(sessionsDir: string): SessionCandidate[];
14
+ export type ScanBudget = {
15
+ remainingEntries: number;
16
+ deadline: number;
17
+ };
18
+ export type HistoryReadBudget = {
19
+ remainingBytes: number;
20
+ deadline: number;
21
+ };
22
+ export declare class HistoryReadBudgetError extends Error {
23
+ }
24
+ export declare function candidateProjectDirectory(c: SessionCandidate, budget: HistoryReadBudget): string | null;
25
+ export declare function scanClaudeSessions(projectsDir: string, budget?: ScanBudget): SessionCandidate[];
26
+ export declare function scanCodexSessions(sessionsDir: string, budget?: ScanBudget): SessionCandidate[];
16
27
  export type ParseOutcome = {
17
28
  ok: true;
18
29
  session: ImportedSession | null;
@@ -21,4 +32,8 @@ export type ParseOutcome = {
21
32
  reason: "too_large" | "too_many_events" | "unreadable";
22
33
  detail: string;
23
34
  };
24
- export declare function parseCandidate(c: SessionCandidate, keep: ContentPolicy): Promise<ParseOutcome>;
35
+ export declare function parseCandidate(c: SessionCandidate, keep: ContentPolicy, limits?: {
36
+ deadline: number;
37
+ maxBytes: number;
38
+ budget?: HistoryReadBudget;
39
+ }): Promise<ParseOutcome>;
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import readline from "node:readline";
5
+ import { StringDecoder } from "node:string_decoder";
5
6
  import { ClaudeSessionAccumulator } from "./claudeCodeText.js";
6
7
  import { CodexSessionAccumulator, codexSessionIdFromName } from "./codexText.js";
7
8
  export const MAX_SESSION_FILE_BYTES = 512 * 1024 * 1024;
@@ -22,7 +23,80 @@ const statOrNull = (p) => {
22
23
  return null;
23
24
  }
24
25
  };
25
- const readDir = (dir) => {
26
+ export class HistoryReadBudgetError extends Error {
27
+ }
28
+ export function candidateProjectDirectory(c, budget) {
29
+ const decoder = new StringDecoder("utf8");
30
+ const buffer = Buffer.allocUnsafe(4096);
31
+ let pending = "", consumed = 0;
32
+ const cwdOf = (line) => {
33
+ try {
34
+ const row = JSON.parse(line);
35
+ const cwd = c.source === "claude-code" ? row?.cwd
36
+ : row?.type === "session_meta" || row?.type === "turn_context" ? row?.payload?.cwd : null;
37
+ return typeof cwd === "string" && cwd ? cwd : null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ };
43
+ let fd;
44
+ try {
45
+ fd = fs.openSync(c.file, "r");
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ try {
51
+ while (consumed < Math.min(c.bytes, 256 * 1024)) {
52
+ if (Date.now() >= budget.deadline)
53
+ throw new HistoryReadBudgetError("History discovery reached its time bound; narrow --since and preview again.");
54
+ if (budget.remainingBytes <= 0)
55
+ throw new HistoryReadBudgetError("History preview reached its 128 MiB read bound; narrow --since and preview again.");
56
+ const take = Math.min(buffer.length, c.bytes - consumed, 256 * 1024 - consumed, budget.remainingBytes);
57
+ const count = fs.readSync(fd, buffer, 0, take, consumed);
58
+ if (!count)
59
+ break;
60
+ consumed += count;
61
+ budget.remainingBytes -= count;
62
+ pending += decoder.write(buffer.subarray(0, count));
63
+ let end;
64
+ while ((end = pending.indexOf("\n")) >= 0) {
65
+ const cwd = cwdOf(pending.slice(0, end));
66
+ pending = pending.slice(end + 1);
67
+ if (cwd)
68
+ return cwd;
69
+ }
70
+ }
71
+ return cwdOf(pending + decoder.end());
72
+ }
73
+ finally {
74
+ fs.closeSync(fd);
75
+ }
76
+ }
77
+ const readDir = (dir, budget) => {
78
+ if (budget) {
79
+ let handle;
80
+ try {
81
+ handle = fs.opendirSync(dir);
82
+ }
83
+ catch {
84
+ return [];
85
+ }
86
+ const rows = [];
87
+ try {
88
+ let entry;
89
+ while ((entry = handle.readSync())) {
90
+ if (--budget.remainingEntries < 0 || Date.now() >= budget.deadline)
91
+ throw new Error("History discovery reached its file/time bound; narrow the local history directory and preview again.");
92
+ rows.push(entry);
93
+ }
94
+ }
95
+ finally {
96
+ handle.closeSync();
97
+ }
98
+ return rows;
99
+ }
26
100
  try {
27
101
  return fs.readdirSync(dir, { withFileTypes: true });
28
102
  }
@@ -47,17 +121,17 @@ function describe(source, file, extraFiles) {
47
121
  }
48
122
  return { source, file, extraFiles: kept, mtimeMs, bytes, fileSig: `${bytes}:${mtimeMs}:${kept.length}` };
49
123
  }
50
- export function scanClaudeSessions(projectsDir) {
124
+ export function scanClaudeSessions(projectsDir, budget) {
51
125
  const out = [];
52
- for (const project of readDir(projectsDir)) {
126
+ for (const project of readDir(projectsDir, budget)) {
53
127
  if (!project.isDirectory())
54
128
  continue;
55
129
  const dir = path.join(projectsDir, project.name);
56
- for (const entry of readDir(dir)) {
130
+ for (const entry of readDir(dir, budget)) {
57
131
  if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
58
132
  continue;
59
133
  const sessionDir = path.join(dir, entry.name.slice(0, -".jsonl".length), "subagents");
60
- const extras = readDir(sessionDir)
134
+ const extras = readDir(sessionDir, budget)
61
135
  .filter((e) => e.isFile() && e.name.endsWith(".jsonl"))
62
136
  .map((e) => path.join(sessionDir, e.name))
63
137
  .sort()
@@ -69,12 +143,12 @@ export function scanClaudeSessions(projectsDir) {
69
143
  }
70
144
  return out.sort((a, b) => a.file.localeCompare(b.file));
71
145
  }
72
- export function scanCodexSessions(sessionsDir) {
146
+ export function scanCodexSessions(sessionsDir, budget) {
73
147
  const out = [];
74
148
  const walk = (dir, depth) => {
75
149
  if (depth > 4)
76
150
  return;
77
- for (const e of readDir(dir)) {
151
+ for (const e of readDir(dir, budget)) {
78
152
  const full = path.join(dir, e.name);
79
153
  if (e.isDirectory())
80
154
  walk(full, depth + 1);
@@ -88,31 +162,51 @@ export function scanCodexSessions(sessionsDir) {
88
162
  walk(sessionsDir, 0);
89
163
  return out.sort((a, b) => a.file.localeCompare(b.file));
90
164
  }
91
- async function feedLines(file, onLine) {
92
- const stream = fs.createReadStream(file, { encoding: "utf8" });
165
+ async function feedLines(file, onLine, remaining, limits) {
166
+ const stream = fs.createReadStream(file, { highWaterMark: 16 * 1024,
167
+ end: Math.min(remaining.bytes, limits?.budget?.remainingBytes ?? remaining.bytes) });
168
+ stream.on("data", (chunk) => {
169
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.length;
170
+ remaining.bytes -= bytes;
171
+ if (limits?.budget)
172
+ limits.budget.remainingBytes -= bytes;
173
+ if (limits?.budget && limits.budget.remainingBytes < 0)
174
+ stream.destroy(new HistoryReadBudgetError("History preview reached its 128 MiB read bound; narrow --since and preview again."));
175
+ else if (remaining.bytes < 0)
176
+ stream.destroy(new Error("Session grew beyond its byte bound; preview it again."));
177
+ else if (limits && Date.now() >= limits.deadline)
178
+ stream.destroy(new HistoryReadBudgetError("History parsing reached its time bound; narrow --since and preview again."));
179
+ });
93
180
  const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
94
181
  try {
95
- for await (const line of rl)
182
+ for await (const line of rl) {
183
+ if (limits && Date.now() >= limits.deadline)
184
+ throw new HistoryReadBudgetError("History parsing reached its time bound.");
96
185
  onLine(line);
186
+ }
97
187
  }
98
188
  finally {
99
189
  rl.close();
100
190
  stream.destroy();
101
191
  }
102
192
  }
103
- export async function parseCandidate(c, keep) {
104
- if (c.bytes > MAX_SESSION_FILE_BYTES) {
105
- return { ok: false, reason: "too_large", detail: `${c.bytes} bytes exceeds the ${MAX_SESSION_FILE_BYTES}-byte session bound` };
193
+ export async function parseCandidate(c, keep, limits) {
194
+ const byteLimit = Math.min(MAX_SESSION_FILE_BYTES, limits?.maxBytes ?? MAX_SESSION_FILE_BYTES);
195
+ if (c.bytes > byteLimit) {
196
+ return { ok: false, reason: "too_large", detail: `${c.bytes} bytes exceeds the ${byteLimit}-byte session bound` };
106
197
  }
107
198
  const acc = c.source === "claude-code" ? new ClaudeSessionAccumulator({ keep }) : new CodexSessionAccumulator({ keep });
199
+ const remaining = { bytes: byteLimit };
108
200
  try {
109
201
  for (const f of [c.file, ...c.extraFiles]) {
110
- await feedLines(f, (line) => acc.line(line));
202
+ await feedLines(f, (line) => acc.line(line), remaining, limits);
111
203
  if (acc.overflowed)
112
204
  break;
113
205
  }
114
206
  }
115
207
  catch (err) {
208
+ if (err instanceof HistoryReadBudgetError)
209
+ throw err;
116
210
  return { ok: false, reason: "unreadable", detail: err instanceof Error ? err.message : String(err) };
117
211
  }
118
212
  if (acc.overflowed)
@@ -0,0 +1,35 @@
1
+ import { type BootstrapOptions } from "./bootstrap.ts";
2
+ import { type WorkspaceContext } from "./workspaces.ts";
3
+ import type { FetchLike } from "./otlp.ts";
4
+ export type JoinOptions = {
5
+ organizationId: string;
6
+ repositoryPath?: string;
7
+ client: "claude" | "codex";
8
+ enrich?: boolean;
9
+ reauthorize?: boolean;
10
+ apiBase?: string;
11
+ };
12
+ export declare function joinPlan(options: JoinOptions): BootstrapOptions;
13
+ export declare function workspaceProject(context: WorkspaceContext): string;
14
+ export declare function joinOrganization(options: JoinOptions, environment?: {
15
+ fetchImpl?: FetchLike;
16
+ interactive?: boolean;
17
+ open?: (url: string) => void;
18
+ log?: (message: string) => void;
19
+ timeoutMs?: number;
20
+ sleep?: (ms: number) => Promise<void>;
21
+ }): Promise<{
22
+ nextAction?: string | undefined;
23
+ ok: boolean;
24
+ status: string;
25
+ workspace: string;
26
+ steps: Record<string, string>;
27
+ } | {
28
+ progressUrl: string;
29
+ liveSessionVerified: boolean;
30
+ nextAction?: string | undefined;
31
+ ok: boolean;
32
+ status: string;
33
+ workspace: string;
34
+ steps: Record<string, string>;
35
+ }>;
@@ -0,0 +1,99 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { createHash } from "node:crypto";
5
+ import { bootstrapWorkspace } from "./bootstrap.js";
6
+ import { contextPath, findWorkspaceBinding, loadWorkspace, readWorkspaceFile, sameWorkspace, workspaceHome, workspaceOrigin } from "./workspaces.js";
7
+ export function joinPlan(options) {
8
+ if (!/^tm_[a-zA-Z0-9_-]{1,128}$/.test(options.organizationId))
9
+ throw new Error("Choose a valid existing organization ID.");
10
+ if (options.client !== "claude" && options.client !== "codex")
11
+ throw new Error("Choose Claude Code or Codex.");
12
+ const repositoryPath = fs.realpathSync(options.repositoryPath ?? process.cwd());
13
+ if (!fs.statSync(repositoryPath).isDirectory() || repositoryPath === os.homedir() || repositoryPath === path.parse(repositoryPath).root)
14
+ throw new Error("Choose a project directory, rather than your home or filesystem root.");
15
+ const binding = findWorkspaceBinding(repositoryPath);
16
+ if (binding && (binding.scope.teamId !== options.organizationId ||
17
+ (options.apiBase && binding.apiBase !== workspaceOrigin(options.apiBase))))
18
+ throw new Error("This project is connected to another destination; its connection was preserved.");
19
+ const digest = createHash("sha256").update(JSON.stringify([options.organizationId, repositoryPath, options.client])).digest("hex").slice(0, 12);
20
+ const slug = path.basename(repositoryPath).toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, 36) || "project";
21
+ let name = `project-${slug}-${digest}`;
22
+ if (binding) {
23
+ const context = loadWorkspace(binding.name);
24
+ if (context.clientConfig?.client === options.client)
25
+ name = binding.name;
26
+ }
27
+ const selected = findWorkspaceBinding(repositoryPath, name);
28
+ if (selected?.name === name) {
29
+ const saved = loadWorkspace(name);
30
+ if (!sameWorkspace(saved, selected))
31
+ throw new Error("The project's saved destination has changed.");
32
+ }
33
+ const checkpoint = path.join(workspaceHome(), `${name}.bootstrap.json`);
34
+ if (fs.existsSync(checkpoint)) {
35
+ const saved = readWorkspaceFile(checkpoint);
36
+ if (saved.plan?.repositoryPath !== repositoryPath || saved.plan?.client !== options.client ||
37
+ (saved.plan.organizationId && saved.plan.organizationId !== options.organizationId))
38
+ throw new Error("The saved connection does not match this project and coding tool.");
39
+ if (options.enrich !== undefined && saved.plan.enrich !== options.enrich)
40
+ throw new Error("This connection has a saved capture choice. Resume without a capture flag to preserve it.");
41
+ return { name, ...(options.reauthorize ? { reauthorize: true } : {}) };
42
+ }
43
+ if (fs.existsSync(contextPath(name)) && loadWorkspace(name).scope.teamId !== options.organizationId)
44
+ throw new Error("Saved connection belongs to another organization.");
45
+ return { name, organizationId: options.organizationId, repositoryPath, client: options.client,
46
+ repositoryObservation: true, ...(options.enrich === undefined ? {} : { enrich: options.enrich }),
47
+ ...(options.reauthorize ? { reauthorize: true } : {}) };
48
+ }
49
+ export function workspaceProject(context) {
50
+ const checkpoint = path.join(workspaceHome(), `${context.name}.bootstrap.json`);
51
+ const state = readWorkspaceFile(checkpoint);
52
+ if (typeof state.plan?.repositoryPath !== "string")
53
+ throw new Error("This workspace has no saved project; connect it with join first.");
54
+ const project = fs.realpathSync(state.plan.repositoryPath);
55
+ const binding = findWorkspaceBinding(project, context.name);
56
+ if (!binding || !sameWorkspace(binding, context))
57
+ throw new Error("The saved project binding differs from this workspace.");
58
+ return project;
59
+ }
60
+ export async function joinOrganization(options, environment = {}) {
61
+ let plan = joinPlan(options);
62
+ const deadline = Date.now() + Math.min(600_000, environment.timeoutMs ?? 600_000);
63
+ const since = Date.now();
64
+ let opened = "";
65
+ let lastState = "";
66
+ while (true) {
67
+ const result = await bootstrapWorkspace(plan, { apiBase: options.apiBase, fetchImpl: environment.fetchImpl, connectionOnly: true,
68
+ timeoutMs: Math.min(45_000, Math.max(1, deadline - Date.now())) });
69
+ plan = { name: plan.name };
70
+ const authorizationUrl = result.authorizationUrl;
71
+ if (authorizationUrl && authorizationUrl !== opened) {
72
+ opened = authorizationUrl;
73
+ environment.log?.(`Approve your connection to ${options.organizationId}:\n${authorizationUrl}`);
74
+ environment.open?.(authorizationUrl);
75
+ }
76
+ if (result.status !== lastState) {
77
+ lastState = result.status;
78
+ if (result.status.startsWith("authorization_"))
79
+ environment.log?.("Waiting for browser approval. You can interrupt and run the same join command to resume.");
80
+ else if (result.nextAction)
81
+ environment.log?.(result.nextAction);
82
+ }
83
+ if (result.status === "ready") {
84
+ const context = loadWorkspace(plan.name);
85
+ if (context.scope.teamId !== options.organizationId)
86
+ throw new Error("Connected destination differs from the requested organization.");
87
+ const project = workspaceProject(context);
88
+ const progress = new URL(`/app/teams/${encodeURIComponent(options.organizationId)}/connect`, context.apiBase);
89
+ progress.search = new URLSearchParams({ client: options.client, project, workspace: context.name, since: String(since) }).toString();
90
+ environment.log?.(`Connection test received. Saved workspace: ${context.name}\n${result.steps.clientLaunch}\nRecord a real session to finish verification:\n${progress}`);
91
+ environment.open?.(String(progress));
92
+ return { ...result, progressUrl: String(progress), liveSessionVerified: false };
93
+ }
94
+ if (!environment.interactive || Date.now() >= deadline ||
95
+ !["authorization_required", "authorization_pending", "ingestion_pending"].includes(result.status))
96
+ return result;
97
+ await (environment.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(Math.min(5_000, Math.max(1, deadline - Date.now())));
98
+ }
99
+ }
@@ -2,13 +2,20 @@ export type FetchLike = typeof fetch;
2
2
  export declare const PROBE_ATTR = "codetelemetry.probe.id";
3
3
  export declare const PROBE_EVENT = "codetelemetry_probe";
4
4
  export declare const PROBE_SERVICE = "codetelemetry-connect";
5
- export declare function buildProbeLog(probeId: string, nowMs?: number): unknown;
5
+ export declare function buildProbeLog(probeId: string, nowMs?: number, context?: {
6
+ project: string;
7
+ client: "claude" | "codex";
8
+ }): unknown;
6
9
  export type SendTestResult = {
7
10
  probeId: string;
8
11
  httpStatus: number;
9
12
  ok: boolean;
10
13
  };
11
14
  export type SendTestOptions = {
15
+ context?: {
16
+ project: string;
17
+ client: "claude" | "codex";
18
+ };
12
19
  key: string;
13
20
  ingestEndpoint: string;
14
21
  probeId?: string;
@@ -3,7 +3,7 @@ import { assertKey } from "./keys.js";
3
3
  export const PROBE_ATTR = "codetelemetry.probe.id";
4
4
  export const PROBE_EVENT = "codetelemetry_probe";
5
5
  export const PROBE_SERVICE = "codetelemetry-connect";
6
- export function buildProbeLog(probeId, nowMs = Date.now()) {
6
+ export function buildProbeLog(probeId, nowMs = Date.now(), context) {
7
7
  const nano = String(BigInt(Math.floor(nowMs)) * 1000000n);
8
8
  return {
9
9
  resourceLogs: [
@@ -11,6 +11,7 @@ export function buildProbeLog(probeId, nowMs = Date.now()) {
11
11
  resource: {
12
12
  attributes: [
13
13
  { key: "service.name", value: { stringValue: PROBE_SERVICE } },
14
+ ...(context ? [{ key: "project.path", value: { stringValue: context.project } }] : []),
14
15
  ],
15
16
  },
16
17
  scopeLogs: [
@@ -26,6 +27,7 @@ export function buildProbeLog(probeId, nowMs = Date.now()) {
26
27
  attributes: [
27
28
  { key: "event.name", value: { stringValue: PROBE_EVENT } },
28
29
  { key: PROBE_ATTR, value: { stringValue: probeId } },
30
+ ...(context ? [{ key: "codetelemetry.probe.client", value: { stringValue: context.client } }] : []),
29
31
  ],
30
32
  },
31
33
  ],
@@ -49,7 +51,7 @@ export async function sendTestEvent(opts) {
49
51
  "content-type": "application/json",
50
52
  authorization: `Bearer ${key}`,
51
53
  },
52
- body: JSON.stringify(buildProbeLog(probeId)),
54
+ body: JSON.stringify(buildProbeLog(probeId, Date.now(), opts.context)),
53
55
  signal: ac.signal,
54
56
  });
55
57
  return { probeId, httpStatus: res.status, ok: res.status >= 200 && res.status < 300 };
@@ -0,0 +1,9 @@
1
+ import { type ImportRunOptions } from "./import/run.ts";
2
+ import type { ImportRunResult } from "./import/core.ts";
3
+ export declare function importWorkspaceHistory(options: {
4
+ name: string;
5
+ preview?: boolean;
6
+ confirm?: boolean;
7
+ selections?: number[];
8
+ sinceMs?: number;
9
+ }, deps?: Pick<ImportRunOptions, "fetchImpl" | "claudeDir" | "codexDir" | "ledgerPath" | "nowMs" | "sleep">): Promise<ImportRunResult>;
@@ -0,0 +1,56 @@
1
+ import path from "node:path";
2
+ import { loadWorkspace, workspaceHome, writeWorkspaceFile, readWorkspaceFile, workspaceCaptureDefault } from "./workspaces.js";
3
+ import { workspaceProject } from "./join.js";
4
+ import { keyHash } from "./keys.js";
5
+ import { verifyScope } from "./connectivity.js";
6
+ import { resolveEndpoints } from "./config.js";
7
+ import { runImport } from "./import/run.js";
8
+ import { sessionKeyOf } from "./import/model.js";
9
+ export async function importWorkspaceHistory(options, deps = {}) {
10
+ const context = loadWorkspace(options.name);
11
+ if (!context.scope.teamId || !context.clientConfig)
12
+ throw new Error("Choose a connected organization workspace.");
13
+ const project = workspaceProject(context);
14
+ const endpoints = { apiBase: context.apiBase, ingestEndpoint: context.ingestEndpoint };
15
+ const expected = context.scope;
16
+ const previewFile = path.join(workspaceHome(), `${context.name}.import-preview.json`);
17
+ const source = context.clientConfig.client === "claude" ? "claude-code" : "codex";
18
+ if (options.preview) {
19
+ if (options.confirm || options.selections)
20
+ throw new Error("Preview and import confirmation are separate actions.");
21
+ const capture = workspaceCaptureDefault(context);
22
+ const content = { prompts: capture, toolDetails: capture };
23
+ const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
24
+ sinceMs: options.sinceMs, content: { "claude-code": content, codex: content }, previewOnly: true });
25
+ const preview = { version: 1, workspace: context.name, keyHash: keyHash(context.ingestKey),
26
+ project, createdAt: Date.now(), scope: expected, window: result.window, content: result.content,
27
+ sessions: result.previewSessions ?? [] };
28
+ writeWorkspaceFile(previewFile, preview);
29
+ return result;
30
+ }
31
+ if (!options.confirm || !options.selections?.length || options.selections.length > 100 ||
32
+ options.sinceMs !== undefined)
33
+ throw new Error("Preview first, then use --select 1,2,… --confirm to import only those sessions.");
34
+ const preview = readWorkspaceFile(previewFile);
35
+ if (preview.version !== 1 || preview.workspace !== context.name || preview.keyHash !== keyHash(context.ingestKey) ||
36
+ preview.project !== project || JSON.stringify(preview.scope) !== JSON.stringify(expected) ||
37
+ !Number.isFinite(preview.createdAt) || Date.now() - preview.createdAt > 24 * 60 * 60_000 ||
38
+ !Array.isArray(preview.sessions) || preview.sessions.length > 100)
39
+ throw new Error("The preview expired or its destination changed. Preview again.");
40
+ const selectedPlans = Object.create(null);
41
+ for (const index of options.selections) {
42
+ if (!Number.isInteger(index) || index < 1 || index > preview.sessions.length)
43
+ throw new Error("Choose session numbers from the latest preview.");
44
+ const item = preview.sessions[index - 1];
45
+ if ((item.source !== "codex" && item.source !== "claude-code") || typeof item.sessionId !== "string" || item.sessionId.length > 512 || !/^[a-f0-9]{32}$/.test(item.planId))
46
+ throw new Error("Invalid preview; generate it again.");
47
+ selectedPlans[sessionKeyOf(item.source, item.sessionId)] = item.planId;
48
+ }
49
+ const verified = await verifyScope({ key: context.ingestKey, expected,
50
+ connectivityUrl: resolveEndpoints(endpoints).connectivityUrl, fetchImpl: deps.fetchImpl });
51
+ if (verified.state !== "scope_verified")
52
+ throw new Error(`Workspace is unavailable: ${verified.state}. No history was uploaded.`);
53
+ return runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
54
+ sinceMs: Date.parse(preview.window.sinceIso), untilMs: Date.parse(preview.window.untilIso),
55
+ content: preview.content, selectedPlans, maxSessions: 100, timeLimitMs: 120_000 });
56
+ }
@@ -1,5 +1,5 @@
1
1
  import type { KeyScope } from "./connectivity.ts";
2
- export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.4.1";
2
+ export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.5.0";
3
3
  export declare const MAX_WORKSPACE_BYTES: number;
4
4
  export declare const MAX_WORKSPACES = 64;
5
5
  export type WorkspaceBinding = {
@@ -41,5 +41,5 @@ export declare function contextPath(name: string): string;
41
41
  export declare function loadWorkspace(name: string): WorkspaceContext;
42
42
  export declare function saveWorkspace(context: WorkspaceContext): void;
43
43
  export declare function listWorkspaces(): WorkspaceBinding[];
44
- export declare function findWorkspaceBinding(start?: string): WorkspaceBinding | null;
45
- export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding): string;
44
+ export declare function findWorkspaceBinding(start?: string, selectedName?: string | undefined): WorkspaceBinding | null;
45
+ export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding, client?: "claude" | "codex"): string;
@@ -5,7 +5,7 @@ import { createHash, randomBytes } from "node:crypto";
5
5
  import { buildOtelSection } from "./codexConfig.js";
6
6
  import { repositoryHookSource, quotedCommand, REPOSITORY_HOOK_FILE } from "./repositoryHook.js";
7
7
  import { looksLikeKey } from "./keys.js";
8
- export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.4.1";
8
+ export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.5.0";
9
9
  export const MAX_WORKSPACE_BYTES = 64 * 1024;
10
10
  export const MAX_WORKSPACES = 64;
11
11
  export function workspaceName(value) {
@@ -357,28 +357,67 @@ export function listWorkspaces() {
357
357
  .sort()
358
358
  .map((file) => bindingOf(loadWorkspace(file.slice(0, -5))));
359
359
  }
360
- export function findWorkspaceBinding(start = process.cwd()) {
360
+ export function findWorkspaceBinding(start = process.cwd(), selectedName = process.env.CODETELEMETRY_WORKSPACE) {
361
361
  let dir = path.resolve(start);
362
362
  for (let depth = 0; depth < 64; depth++) {
363
363
  const file = path.join(dir, ".codetelemetry", "workspace.json");
364
- if (fs.existsSync(file))
365
- return bindingOf(readWorkspaceFile(file, false));
364
+ if (fs.existsSync(file)) {
365
+ const raw = readWorkspaceFile(file, false);
366
+ const primary = bindingOf(raw);
367
+ if (selectedName && primary.name !== selectedName) {
368
+ const clients = raw.clientBindings;
369
+ if (clients && typeof clients === "object" && !Array.isArray(clients)) {
370
+ for (const client of ["claude", "codex"]) {
371
+ if (clients[client]) {
372
+ const candidate = bindingOf(clients[client]);
373
+ if (candidate.name === selectedName)
374
+ return candidate;
375
+ }
376
+ }
377
+ }
378
+ }
379
+ return primary;
380
+ }
366
381
  if (fs.existsSync(path.join(dir, ".git")) || path.dirname(dir) === dir)
367
382
  return null;
368
383
  dir = path.dirname(dir);
369
384
  }
370
385
  throw new Error("Workspace binding search exceeded 64 parents.");
371
386
  }
372
- export function bindWorkspace(repositoryPath, context) {
387
+ export function bindWorkspace(repositoryPath, context, client) {
373
388
  const root = fs.realpathSync(repositoryPath);
374
389
  if (!fs.statSync(root).isDirectory() ||
375
390
  root === os.homedir() ||
376
391
  root === path.parse(root).root)
377
392
  throw new Error("Choose a repository directory.");
378
393
  const file = path.join(root, ".codetelemetry", "workspace.json");
379
- if (fs.existsSync(file) &&
380
- !sameWorkspace(bindingOf(readWorkspaceFile(file, false)), context))
381
- throw new Error("Repository is bound to another workspace; remove its binding explicitly before switching.");
382
- writeWorkspaceFile(file, bindingOf(context));
383
- return file;
394
+ noLinks(file);
395
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
396
+ const releaseBinding = workspaceLock(".store");
397
+ try {
398
+ const existing = fs.existsSync(file) ? readWorkspaceFile(file, false) : null;
399
+ const primary = existing ? bindingOf(existing) : null;
400
+ const sameDestination = primary && primary.apiBase === context.apiBase &&
401
+ JSON.stringify(primary.scope) === JSON.stringify(context.scope);
402
+ const rawClients = existing?.clientBindings;
403
+ const clientBindings = {};
404
+ if (rawClients !== undefined) {
405
+ if (!rawClients || typeof rawClients !== "object" || Array.isArray(rawClients) ||
406
+ Object.keys(rawClients).some(key => key !== "claude" && key !== "codex"))
407
+ throw new Error("Invalid repository client bindings.");
408
+ for (const [key, value] of Object.entries(rawClients))
409
+ clientBindings[key] = bindingOf(value);
410
+ }
411
+ if (primary && !sameWorkspace(primary, context) && (!client || !sameDestination ||
412
+ (clientBindings[client] && !sameWorkspace(clientBindings[client], context))))
413
+ throw new Error("Repository is bound to another workspace; remove its binding explicitly before switching.");
414
+ if (client)
415
+ clientBindings[client] = bindingOf(context);
416
+ writeWorkspaceFile(file, { ...(primary ?? bindingOf(context)),
417
+ ...(Object.keys(clientBindings).length ? { clientBindings } : {}) });
418
+ return file;
419
+ }
420
+ finally {
421
+ releaseBinding();
422
+ }
384
423
  }
@@ -1,4 +1,4 @@
1
- import type { WorkspaceBinding } from "./client/workspaces.ts";
1
+ import { type WorkspaceBinding } from "./client/workspaces.ts";
2
2
  import path from "node:path";
3
3
  import { type FetchLike, type OnboardClient } from "./client/index.ts";
4
4
  import { OnboardingSession } from "./session.ts";
package/dist/src/tools.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { workspaceTools, restoreWorkspace } from "./workspaceRuntime.js";
2
+ import { loadWorkspace } from "./client/workspaces.js";
3
+ import { workspaceProject } from "./client/join.js";
2
4
  import fs from "node:fs";
3
5
  import os from "node:os";
4
6
  import path from "node:path";
@@ -1724,6 +1726,7 @@ export const TOOLS = [
1724
1726
  "It reads ~/.claude/projects and ~/.codex/sessions on this machine and sends them through the normal ingest under the session's key, tagged as imported. " +
1725
1727
  "ALWAYS call it first with dryRun true (the default) and show the user the summary — sessions, tokens, what is skipped and the content setting — then ask before calling again with dryRun false. " +
1726
1728
  "Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. " +
1729
+ "A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. " +
1727
1730
  "Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. " +
1728
1731
  "content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
1729
1732
  inputSchema: obj({
@@ -1770,6 +1773,7 @@ export const TOOLS = [
1770
1773
  codexConfig: ctx.configPathsOverride?.codex ?? CLIENTS.codex.resolveConfigPath({}),
1771
1774
  }),
1772
1775
  dryRun: args.dryRun !== false,
1776
+ boundedDiscovery: Boolean(ctx.workspace),
1773
1777
  maxSessions,
1774
1778
  timeLimitMs: IMPORT_TIME_LIMIT_MS,
1775
1779
  importTool: "mcp",
@@ -1809,6 +1813,17 @@ export async function callTool(name, args, ctx) {
1809
1813
  }) } : ctx;
1810
1814
  if (ctx.workspaceClient && ["status", "onboard", "write_local_config"].includes(name) && args.client === undefined)
1811
1815
  args = { ...args, client: ctx.workspaceClient };
1816
+ if (ctx.workspace && name === "import_history") {
1817
+ const saved = loadWorkspace(ctx.workspace.name);
1818
+ const project = workspaceProject(saved);
1819
+ const selected = typeof args.project === "string" ? path.resolve(args.project) : project;
1820
+ if (selected !== project && !selected.startsWith(project + path.sep))
1821
+ throw new Error("History import must stay inside this workspace's selected project.");
1822
+ const source = saved.clientConfig?.client === "claude" ? "claude-code" : "codex";
1823
+ if (args.source !== undefined && args.source !== source)
1824
+ throw new Error("Choose the workspace for that coding client before importing its history.");
1825
+ args = { ...args, project: selected, source };
1826
+ }
1812
1827
  const result = await tool.handler(args ?? {}, delegate);
1813
1828
  if (name === "status")
1814
1829
  result.workspace = ctx.workspace ?? null;
@@ -1,2 +1,2 @@
1
1
  export declare const MCP_SERVER_NAME = "codetelemetry";
2
- export declare const MCP_SERVER_VERSION = "0.4.1";
2
+ export declare const MCP_SERVER_VERSION = "0.5.0";
@@ -1,2 +1,2 @@
1
1
  export const MCP_SERVER_NAME = "codetelemetry";
2
- export const MCP_SERVER_VERSION = "0.4.1";
2
+ export const MCP_SERVER_VERSION = "0.5.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codetelemetry/mcp",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "CodeTelemetry MCP server \u2014 lets a coding agent onboard a user end to end: authenticate (device code), obtain an ingest key, write the Claude Code OTEL config, send a test event, and confirm telemetry landed \u2014 then search, read, interpret and compare the user's own coding sessions, plan the next one, and size tasks, plans and Linear issues from that history. The plaintext key never enters the model's context.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "serverName": "codetelemetry",
3
- "serverVersion": "0.4.1",
4
- "registryHash": "217ada41e87180ec24e8e8d96108a2e52dfc5eae0c4007aa313eac6a11b7ece8",
3
+ "serverVersion": "0.5.0",
4
+ "registryHash": "02a9df0bc3beeaca326034cb7ed4584556d52b76746506ad0ecc3ee2193554ab",
5
5
  "toolCount": 30,
6
6
  "tools": [
7
7
  {
@@ -1703,7 +1703,7 @@
1703
1703
  {
1704
1704
  "name": "import_history",
1705
1705
  "title": "Import past Claude Code / Codex sessions",
1706
- "description": "Use this when the user wants their EXISTING local Claude Code or Codex history (sessions from before CodeTelemetry was set up) to show in CodeTelemetry. It reads ~/.claude/projects and ~/.codex/sessions on this machine and sends them through the normal ingest under the session's key, tagged as imported. ALWAYS call it first with dryRun true (the default) and show the user the summary — sessions, tokens, what is skipped and the content setting — then ask before calling again with dryRun false. Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
1706
+ "description": "Use this when the user wants their EXISTING local Claude Code or Codex history (sessions from before CodeTelemetry was set up) to show in CodeTelemetry. It reads ~/.claude/projects and ~/.codex/sessions on this machine and sends them through the normal ingest under the session's key, tagged as imported. ALWAYS call it first with dryRun true (the default) and show the user the summary — sessions, tokens, what is skipped and the content setting — then ask before calling again with dryRun false. Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
1707
1707
  "inputSchema": {
1708
1708
  "type": "object",
1709
1709
  "properties": {