@codetelemetry/mcp 0.4.1 → 0.6.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.6.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.1 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.1 import --workspace <name> --preview
71
+ # Choose numbers from that preview; no session content uploads until confirmation:
72
+ npx -y @codetelemetry/connect@0.3.1 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
@@ -162,6 +204,10 @@ contexts use the established scope-v1 device flow.
162
204
  | `seed_grader_config` | Inspect local agent instructions, selected skills, and project task files; return source text and command-check candidates for the user's requested grading focus. Reads files without running commands or uploading them. |
163
205
  | `publish_grader_config` | Publish the reviewed draft as a new policy version using its exact revision. Completes setup through MCP; historical scores remain unchanged. |
164
206
  | `write_grader_config_artifact` | Write selected checks as Terraform JSON or a standalone Pulumi YAML program, choosing the format from repository context. Refuses overwrites; runs no commands. |
207
+ | `discover_grader_checks` | Discover common checks from recorded repository history; returns an asynchronous run ID. |
208
+ | `backtest_grader_checks` | Backtest candidate IDs or saved draft checks using pinned evidence and the live evaluator. |
209
+ | `get_grader_run` | Read progress, coverage, candidates and paged results, plus the current draft revision. |
210
+ | `save_grader_draft` | Save selected backtested candidates with revision protection; preserves unrelated checks and does not publish. |
165
211
  | `get_grader_config` | Read a page of the workspace's Grader draft, its revision, and published version. |
166
212
  | `update_grader_config` | Add, update, or remove selected draft checks while preserving others. Records the user's requested instruction features and rejects stale revisions. Use publish_grader_config with the returned revision to apply it to future scoring. |
167
213
  | `get_github_pr_gate` | Read the workspace's GitHub PR gate as its settings page shows it: the policy, trusted repositories, the GitHub Actions workflow file to commit, the check to require, outstanding steps, and recent decisions. |
@@ -177,6 +223,27 @@ the user merges) → once it has run, the user requires
177
223
  `codetelemetry/validation` from GitHub Actions on the default branch (`howTo`
178
224
  gives the `gh api` ruleset command to run with their permission).
179
225
 
226
+ ## Discover and backtest the Grader
227
+
228
+ For history-based setup, call `discover_grader_checks` with the recorded
229
+ `repository` label and requested `features`. The service defaults to 30 days of
230
+ PR-producing sessions; `cohort: "substantive"` includes all observed work.
231
+ Poll `get_grader_run`, follow `nextCursor`, and review candidate IDs, package
232
+ scope, ambiguities and coverage. Call `backtest_grader_checks` with the discovery
233
+ ID and selected candidate IDs, then poll the new run. Completion and final
234
+ edit-to-push timing are separate verdicts. Unknown and partial evidence remain
235
+ explicit. To backtest existing configuration, follow `draftChecksCursor` from
236
+ `get_grader_run` for saved check IDs/names and the current `draftRevision`, then
237
+ pass that revision, selected `checkIds` and `repository` to `backtest_grader_checks`.
238
+
239
+ Save selected candidates with `save_grader_draft`, passing the backtest ID and
240
+ current `draftRevision` from `get_grader_run` as `expectedRevision`. Saving
241
+ preserves unrelated checks and does not publish or change enforcement. Runs
242
+ expire after 24 hours. Scans, normalization and evaluation run on the service;
243
+ this workflow needs no checkout, shell, custom scripts or client matcher JSON.
244
+ The backend must support the Grader history routes before these tools can run.
245
+ Existing local seeding and direct configuration remain available below.
246
+
180
247
  ## Seed and update the Grader
181
248
 
182
249
  Ask, for example: **"Use AGENTS.md and our security-review skill to grade unit
@@ -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.1 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
+ }>;