@osfactory/otel-hook 0.14.0 → 0.14.1

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 (37) hide show
  1. package/README.md +17 -3
  2. package/dist/{adapter-D5R8lhfl.d.ts → adapter-But5fFCk.d.ts} +8 -1
  3. package/dist/cli.js +210 -45
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{export-destinations-DvoH4QOe.d.ts → export-destinations-8tNkIC8a.d.ts} +12 -4
  6. package/dist/{filesystem-store-B3CpiIRl.d.ts → filesystem-store-Z8XgDtFj.d.ts} +1 -1
  7. package/dist/{hook-DVK8Don-.d.ts → hook-D7XABd4f.d.ts} +17 -3
  8. package/dist/index.d.ts +10 -10
  9. package/dist/index.js +211 -45
  10. package/dist/index.js.map +1 -1
  11. package/dist/install.d.ts +3 -3
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +6 -6
  14. package/dist/integration.js +188 -40
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +1 -1
  17. package/dist/lifecycle.js +1 -1
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-B3r6sZtC.d.ts → memory-gipZUiXP.d.ts} +1 -1
  20. package/dist/{payload-D4r71EL-.d.ts → payload-DWdx9yk3.d.ts} +1 -1
  21. package/dist/{ports-DhpSDIkp.d.ts → ports-qZTwK-z2.d.ts} +22 -2
  22. package/dist/providers.d.ts +7 -7
  23. package/dist/providers.js +22 -5
  24. package/dist/providers.js.map +1 -1
  25. package/dist/{registry-DOJh9mzB.d.ts → registry-D9rmMYxw.d.ts} +1 -1
  26. package/dist/runtime.d.ts +22 -7
  27. package/dist/runtime.js +154 -28
  28. package/dist/runtime.js.map +1 -1
  29. package/dist/state.d.ts +3 -3
  30. package/dist/state.js.map +1 -1
  31. package/dist/telemetry.d.ts +2 -2
  32. package/dist/telemetry.js +26 -9
  33. package/dist/telemetry.js.map +1 -1
  34. package/dist/testing.d.ts +6 -6
  35. package/dist/testing.js +57 -8
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +1 -1
package/README.md CHANGED
@@ -1148,9 +1148,23 @@ that should see two repositories, one of them without content:
1148
1148
  | `contentMode` | `omit`, `mask`, `redact` or `raw`. Lowers the disclosure `privacy.contentMode` produced, for this destination only; never raises it (`exporter.logs.includeContent` still gates log bodies). |
1149
1149
  | `includeSessionId` | `false` leaves `session.id` off this destination's metric points for these repositories (cumulative series are then kept across sessions). Default true; cannot turn on what `exporter.metrics.includeSessionId` turned off. |
1150
1150
 
1151
- A record's repository is its `vcs.repository.url.full`: the session context
1152
- stamp (`sessionContext.dir`) for the event, else the exporter Resource
1153
- (`--resource-attr` / `OTEL_RESOURCE_ATTRIBUTES`). The **first** scope listing it
1151
+ A record's repository is, in order: its `vcs.repository.url.full` session
1152
+ context stamp (`sessionContext.dir`); else the `origin` remote of the git
1153
+ repository the session's own directory is in (read from that repository's
1154
+ `.git/config`, no `git` process); else the exporter Resource
1155
+ (`--resource-attr` / `OTEL_RESOURCE_ATTRIBUTES`). So a session's first records
1156
+ (its start and first prompt) reach the destination scoped to the repository it
1157
+ runs in even before any session context exists. A local-path, missing or
1158
+ unparsable remote names no repository. A record a scoped destination takes by
1159
+ the session directory's remote or the Resource, with no stamp of its own, is
1160
+ sent to that destination with `vcs.repository.url.full` set to `https://<key>`:
1161
+ the normalized host and path the scope matched, never the remote as written, so
1162
+ no credential, port or local path can appear. The destination already names
1163
+ that repository in its own scope and the session's later records carry it, so
1164
+ this discloses nothing new; it lets the receiver file the session's first
1165
+ records under the repository it was opted in for. A record's own stamp is never
1166
+ changed, and what an unscoped destination receives does not change. The
1167
+ **first** scope listing it
1154
1168
  decides; a record that names no repository, or one no scope lists, is **not
1155
1169
  sent** to a scoped destination. A span is judged by its end edge when the end is
1156
1170
  in the same batch. Metric points are filtered point by point, so one callback's
@@ -5,7 +5,7 @@ import { I as IdentityClaim, d as InvocationIdentity } from './identity-BrVBs901
5
5
  import { R as ResolvedProviderId, g as ProviderId, h as SourceTransport, d as EventId } from './primitives-CJ8-rn-f.js';
6
6
  import { e as PrivacyLimits } from './policy-CimmCfRp.js';
7
7
  import { P as PrivacyService } from './service-DySC7KQM.js';
8
- import { C as Clock, I as IdGenerator, d as Logger } from './ports-DhpSDIkp.js';
8
+ import { C as Clock, I as IdGenerator, d as Logger } from './ports-qZTwK-z2.js';
9
9
  import { A as AttributionOutcome, a as AttributionReason } from './taxonomy-DwhTtuWd.js';
10
10
 
11
11
  /** Raw input offered to adapters. `payload` is `unknown` on purpose. */
@@ -208,6 +208,13 @@ type ProviderParseResult = {
208
208
  * the event's `target` and discards it. Use `EventFactory.targetHints()`.
209
209
  */
210
210
  readonly targetHints?: ReadonlyMap<EventId, TargetHint>;
211
+ /**
212
+ * The session's own directory (the payload's `cwd` or single workspace
213
+ * root), absolute. **A local path, in-process only**: the core reads the
214
+ * `origin` remote of the repository it sits in to route records without a
215
+ * context stamp to scoped destinations, then discards it. Never exported.
216
+ */
217
+ readonly workspaceDirectory?: string;
211
218
  }
212
219
  /** The input was recognized but carries no telemetry. Not an error. */
213
220
  | {
package/dist/cli.js CHANGED
@@ -4330,7 +4330,12 @@ var createAntigravityAdapter = (options = {}) => {
4330
4330
  reason: payload.fullyIdle ? "Stop signals execution/turn completion (fullyIdle=true) but exposes no session or generation identity, so it cannot become session.end or generation.end without inventing one" : "Stop received while the agent is not fully idle; the conversation continues and the hook exposes no lifecycle fact the canonical model can represent"
4331
4331
  };
4332
4332
  }
4333
- return { status: "parsed", events: factory.events() };
4333
+ const [onlyWorkspacePath, ...otherWorkspacePaths] = payload.workspacePaths;
4334
+ return {
4335
+ status: "parsed",
4336
+ events: factory.events(),
4337
+ ...onlyWorkspacePath === void 0 || onlyWorkspacePath.length === 0 || otherWorkspacePaths.length > 0 ? {} : { workspaceDirectory: onlyWorkspacePath }
4338
+ };
4334
4339
  };
4335
4340
  const hookResponse2 = () => SILENT_HOOK_RESPONSE;
4336
4341
  return {
@@ -5397,7 +5402,8 @@ var parseClaudeCode = (input, context) => {
5397
5402
  status: "parsed",
5398
5403
  events: factory.events(),
5399
5404
  ...warnings.length === 0 ? {} : { warnings },
5400
- ...targetHints.size === 0 ? {} : { targetHints }
5405
+ ...targetHints.size === 0 ? {} : { targetHints },
5406
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
5401
5407
  };
5402
5408
  };
5403
5409
 
@@ -6059,7 +6065,8 @@ var parse = (input, context) => {
6059
6065
  status: "parsed",
6060
6066
  events: factory.events(),
6061
6067
  ...warnings.length === 0 ? {} : { warnings },
6062
- ...targetHints.size === 0 ? {} : { targetHints }
6068
+ ...targetHints.size === 0 ? {} : { targetHints },
6069
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
6063
6070
  };
6064
6071
  };
6065
6072
  var hookResponse = () => SILENT_HOOK_RESPONSE;
@@ -6546,6 +6553,13 @@ var deriveWorkspace = (context, payload) => {
6546
6553
  }
6547
6554
  return void 0;
6548
6555
  };
6556
+ var workspaceDirectoryOf = (payload) => {
6557
+ const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);
6558
+ if (roots.length > 0) {
6559
+ return roots.length === 1 ? roots[0] : void 0;
6560
+ }
6561
+ return payload.cwd !== void 0 && payload.cwd.length > 0 ? payload.cwd : void 0;
6562
+ };
6549
6563
  var invocationDiscriminator = (payload) => {
6550
6564
  switch (payload.hook_event_name) {
6551
6565
  case "sessionStart":
@@ -7005,11 +7019,13 @@ var createCursorAdapter = (options = {}) => {
7005
7019
  }
7006
7020
  }
7007
7021
  const targetHints = factory.targetHints();
7022
+ const workspaceDirectory = workspaceDirectoryOf(payload);
7008
7023
  return {
7009
7024
  status: "parsed",
7010
7025
  events: factory.events(),
7011
7026
  ...warnings.length === 0 ? {} : { warnings },
7012
- ...targetHints.size === 0 ? {} : { targetHints }
7027
+ ...targetHints.size === 0 ? {} : { targetHints },
7028
+ ...workspaceDirectory === void 0 ? {} : { workspaceDirectory }
7013
7029
  };
7014
7030
  };
7015
7031
  const hookResponse2 = (input) => {
@@ -7663,7 +7679,8 @@ var createGeminiCliAdapter = (options = {}) => {
7663
7679
  return {
7664
7680
  status: "parsed",
7665
7681
  events: factory.events(),
7666
- ...warnings.length === 0 ? {} : { warnings }
7682
+ ...warnings.length === 0 ? {} : { warnings },
7683
+ ...payload.cwd === void 0 || payload.cwd.length === 0 ? {} : { workspaceDirectory: payload.cwd }
7667
7684
  };
7668
7685
  };
7669
7686
  const hookResponse2 = () => SILENT_HOOK_RESPONSE;
@@ -9335,7 +9352,7 @@ import {
9335
9352
  } from "@opentelemetry/semantic-conventions/incubating";
9336
9353
 
9337
9354
  // src/version.ts
9338
- var VERSION = "0.14.0";
9355
+ var VERSION = "0.14.1";
9339
9356
 
9340
9357
  // src/telemetry/semconv.ts
9341
9358
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -11387,6 +11404,12 @@ var omitRestrictedContent = (fact, mode) => {
11387
11404
  };
11388
11405
  var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
11389
11406
  var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
11407
+ var repositoryUrlForKey = (key) => `https://${key}`;
11408
+ var hasOwnStamp = (attributes) => attributes?.[ATTR_VCS_REPOSITORY_URL_FULL] !== void 0;
11409
+ var withRoutedRepository = (event3, key) => hasOwnStamp(event3.contextAttributes) ? event3 : {
11410
+ ...event3,
11411
+ contextAttributes: { ...event3.contextAttributes, [ATTR_VCS_REPOSITORY_URL_FULL]: repositoryUrlForKey(key) }
11412
+ };
11390
11413
  var eventRepositoryKey = (event3, fallbackKey) => {
11391
11414
  const stamped = event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
11392
11415
  return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
@@ -11420,19 +11443,21 @@ var restrictEventContent = (event3, mode, restrict) => {
11420
11443
  };
11421
11444
  var routeEventsToScopes = (events, scopes, options) => {
11422
11445
  const ends = spanEndEdgesOf(events);
11446
+ const fallbackKey = options.workspaceRepositoryKey ?? options.resourceRepositoryKey;
11423
11447
  const traces = [];
11424
11448
  const logs = [];
11425
11449
  let unchanged = true;
11426
11450
  for (const event3 of events) {
11427
11451
  const anchor = ends.get(event3.eventId) ?? event3;
11428
- const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
11452
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, fallbackKey));
11429
11453
  if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
11430
11454
  unchanged = false;
11431
11455
  }
11432
11456
  if (scope === void 0) {
11433
11457
  continue;
11434
11458
  }
11435
- const restricted = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
11459
+ const lowered = scope.contentMode === void 0 ? event3 : restrictEventContent(event3, scope.contentMode, options.restrict);
11460
+ const restricted = hasOwnStamp(anchor.contextAttributes) || fallbackKey === void 0 ? lowered : withRoutedRepository(lowered, fallbackKey);
11436
11461
  if (restricted !== event3) {
11437
11462
  unchanged = false;
11438
11463
  }
@@ -11455,7 +11480,15 @@ var routePointsToScopes = (scopes, pointsFor, options) => {
11455
11480
  for (const point of pointsFor(variant) ?? []) {
11456
11481
  const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
11457
11482
  if (scope?.signals.metrics === true && effective(scope) === variant) {
11458
- kept.push(point);
11483
+ kept.push(
11484
+ hasOwnStamp(point.attributes) || options.fallbackKey === void 0 ? point : {
11485
+ ...point,
11486
+ attributes: {
11487
+ ...point.attributes,
11488
+ [ATTR_VCS_REPOSITORY_URL_FULL]: repositoryUrlForKey(options.fallbackKey)
11489
+ }
11490
+ }
11491
+ );
11459
11492
  }
11460
11493
  }
11461
11494
  }
@@ -11673,8 +11706,9 @@ var createExportDestinationSinks = (options) => {
11673
11706
  ...metricSpool === void 0 ? {} : { metricSpool },
11674
11707
  ...destination.scopes === void 0 ? {} : {
11675
11708
  scopes: destination.scopes,
11676
- route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
11709
+ route: (events, workspaceRepositoryKey) => routeEventsToScopes(events, destination.scopes ?? [], {
11677
11710
  ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
11711
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey },
11678
11712
  restrict
11679
11713
  })
11680
11714
  }
@@ -11691,8 +11725,8 @@ var createScopedFanout = (destination, correlate) => {
11691
11725
  const none2 = { accepted: 0, rejected: 0, errors: [] };
11692
11726
  return {
11693
11727
  ...unscoped,
11694
- emit: async (events) => {
11695
- const batch = route(events);
11728
+ emit: async (events, emitOptions) => {
11729
+ const batch = route(events, emitOptions?.workspaceRepositoryKey);
11696
11730
  if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
11697
11731
  await correlate(events);
11698
11732
  correlate.alias(batch.traces, events);
@@ -11718,10 +11752,10 @@ var createDestinationFanout = (destinations, options = {}) => {
11718
11752
  if (only !== void 0) {
11719
11753
  return only.sink;
11720
11754
  }
11721
- const emit = async (events) => {
11755
+ const emit = async (events, emitOptions) => {
11722
11756
  const results = await Promise.all(
11723
11757
  fanouts.map(
11724
- (fanout) => fanout.sink.emit(events).catch(
11758
+ (fanout) => fanout.sink.emit(events, emitOptions).catch(
11725
11759
  (thrown) => ({
11726
11760
  accepted: 0,
11727
11761
  rejected: events.length,
@@ -15543,6 +15577,28 @@ var classifyDurability = (input) => {
15543
15577
  };
15544
15578
  var isCommittable = (durability) => durability !== "lost";
15545
15579
  var MAX_ERROR_EVENTS = 8;
15580
+ var resolveWorkspaceRepositoryKey = async (locator, directory, budgetMillis) => {
15581
+ if (locator?.originRepositoryKey === void 0) {
15582
+ return void 0;
15583
+ }
15584
+ let timer;
15585
+ const deadline = new Promise((resolve8) => {
15586
+ timer = setTimeout(() => resolve8(void 0), Math.max(0, budgetMillis));
15587
+ timer.unref?.();
15588
+ });
15589
+ try {
15590
+ return await Promise.race([
15591
+ locator.originRepositoryKey(directory).catch(() => void 0),
15592
+ deadline
15593
+ ]);
15594
+ } catch {
15595
+ return void 0;
15596
+ } finally {
15597
+ if (timer !== void 0) {
15598
+ clearTimeout(timer);
15599
+ }
15600
+ }
15601
+ };
15546
15602
  var collectContentFacts = (event3) => {
15547
15603
  const facts = [];
15548
15604
  const push = (fact) => {
@@ -16186,7 +16242,8 @@ var createOtelHook = (deps) => {
16186
16242
  kind: "ready",
16187
16243
  batch: batch2,
16188
16244
  dropped: screened.dropped,
16189
- ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
16245
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints },
16246
+ ...parsed.workspaceDirectory === void 0 ? {} : { workspaceDirectory: parsed.workspaceDirectory }
16190
16247
  };
16191
16248
  };
16192
16249
  let prepared;
@@ -16254,11 +16311,19 @@ var createOtelHook = (deps) => {
16254
16311
  batch,
16255
16312
  !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
16256
16313
  );
16314
+ const workspaceRepositoryKey = !suppress && batch.length > 0 && deps.routeByWorkspaceRepository === true && prepared.workspaceDirectory !== void 0 ? await resolveWorkspaceRepositoryKey(
16315
+ deps.worktreeLocator,
16316
+ prepared.workspaceDirectory,
16317
+ deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
16318
+ ) : void 0;
16257
16319
  let emitted = 0;
16258
16320
  let exportRejected = 0;
16259
16321
  if (!suppress && batch.length > 0) {
16260
16322
  try {
16261
- const result = await deps.sink.emit(batch);
16323
+ const result = await deps.sink.emit(
16324
+ batch,
16325
+ workspaceRepositoryKey === void 0 ? void 0 : { workspaceRepositoryKey }
16326
+ );
16262
16327
  emitted = result.accepted;
16263
16328
  exportRejected = result.rejected;
16264
16329
  diagnostics.push(...result.errors);
@@ -16317,7 +16382,8 @@ var createOtelHook = (deps) => {
16317
16382
  durability,
16318
16383
  dropped,
16319
16384
  hookResponse: hookResponseFor(adapter, detection, "attributed", void 0, emitted, diagnostics),
16320
- diagnostics
16385
+ diagnostics,
16386
+ ...workspaceRepositoryKey === void 0 ? {} : { workspaceRepositoryKey }
16321
16387
  };
16322
16388
  } catch (thrown) {
16323
16389
  const info = errorInfoFromThrown(thrown, { code: "internal-error", phase: "parsing" });
@@ -16416,15 +16482,16 @@ var MAX_WORKTREE_WALK_DEPTH = 128;
16416
16482
  var MAX_GIT_FILE_BYTES = 4096;
16417
16483
  var MAX_CACHE_ENTRIES = 1024;
16418
16484
  var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
16485
+ var MAX_GIT_CONFIG_BYTES = 64 * 1024;
16419
16486
  var MAX_BRANCH_NAME_LENGTH = 255;
16420
16487
  var ABSENT = Object.freeze({ kind: "absent" });
16421
16488
  var INVALID = Object.freeze({ kind: "invalid" });
16422
- var readBounded2 = async (filePath) => {
16489
+ var readBounded2 = async (filePath, maxBytes = MAX_GIT_FILE_BYTES) => {
16423
16490
  let handle;
16424
16491
  try {
16425
16492
  handle = await open8(filePath, "r");
16426
- const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
16427
- const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
16493
+ const buffer = Buffer.alloc(maxBytes);
16494
+ const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
16428
16495
  return buffer.subarray(0, bytesRead).toString("utf8");
16429
16496
  } catch {
16430
16497
  return void 0;
@@ -16452,6 +16519,60 @@ var parseGitDirFile = (content, worktreeRoot) => {
16452
16519
  );
16453
16520
  };
16454
16521
  var parseCommonDirFile = (content, gitDir) => resolveGitPath(firstLine(content), gitDir);
16522
+ var unquoteConfigValue = (raw) => {
16523
+ let value = "";
16524
+ let quoted = false;
16525
+ for (let index = 0; index < raw.length; index += 1) {
16526
+ const char = raw[index];
16527
+ if (char === "\\") {
16528
+ const next = raw[index + 1];
16529
+ if (next === void 0) {
16530
+ return void 0;
16531
+ }
16532
+ value += next === "n" ? "\n" : next === "t" ? " " : next;
16533
+ index += 1;
16534
+ } else if (char === '"') {
16535
+ quoted = !quoted;
16536
+ } else if (!quoted && (char === "#" || char === ";")) {
16537
+ break;
16538
+ } else {
16539
+ value += char;
16540
+ }
16541
+ }
16542
+ return quoted ? void 0 : value.trim();
16543
+ };
16544
+ var parseOriginRemoteUrl = (content) => {
16545
+ const lines = content.split(/\r?\n/);
16546
+ if (!content.endsWith("\n")) {
16547
+ lines.pop();
16548
+ }
16549
+ let inOrigin = false;
16550
+ for (const rawLine of lines) {
16551
+ const line = rawLine.trim();
16552
+ if (line.startsWith("[")) {
16553
+ const close = line.indexOf("]");
16554
+ const header = close === -1 ? "" : line.slice(1, close).trim();
16555
+ const rest = close === -1 ? "" : line.slice(close + 1).trim();
16556
+ inOrigin = /^remote\s+"origin"$/i.test(header) && header.endsWith('"origin"') || header.toLowerCase() === "remote.origin";
16557
+ if (!inOrigin || rest.length === 0 || rest.startsWith("#") || rest.startsWith(";")) {
16558
+ continue;
16559
+ }
16560
+ const entry2 = /^url\s*=(.*)$/i.exec(rest);
16561
+ if (entry2 !== null) {
16562
+ return unquoteConfigValue(entry2[1] ?? "");
16563
+ }
16564
+ continue;
16565
+ }
16566
+ if (!inOrigin) {
16567
+ continue;
16568
+ }
16569
+ const entry = /^url\s*=(.*)$/i.exec(line);
16570
+ if (entry !== null) {
16571
+ return unquoteConfigValue(entry[1] ?? "");
16572
+ }
16573
+ }
16574
+ return void 0;
16575
+ };
16455
16576
  var isMissing = async (filePath) => {
16456
16577
  try {
16457
16578
  await lstat(filePath);
@@ -16472,11 +16593,15 @@ var repositoryOf = async (worktreeRoot, gitDir) => {
16472
16593
  const commonDirFile = path15.join(gitDir, "commondir");
16473
16594
  const content = await readBounded2(commonDirFile);
16474
16595
  if (content === void 0) {
16475
- return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
16596
+ return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot, configDir: gitDir } : { kind: "linked" };
16476
16597
  }
16477
16598
  const commonDir = parseCommonDirFile(content, gitDir);
16478
16599
  const mainRoot = commonDir !== void 0 && path15.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path15.dirname(commonDir) : void 0;
16479
- return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
16600
+ return {
16601
+ kind: "linked",
16602
+ ...mainRoot === void 0 ? {} : { mainRoot },
16603
+ ...commonDir === void 0 ? {} : { configDir: commonDir }
16604
+ };
16480
16605
  };
16481
16606
  var probeDirectory = async (directory) => {
16482
16607
  const dotGit = path15.join(directory, ".git");
@@ -16501,12 +16626,21 @@ var probeDirectory = async (directory) => {
16501
16626
  return INVALID;
16502
16627
  }
16503
16628
  const branch = parseHeadBranch(head);
16504
- const repository = info.isDirectory() ? { kind: "main", mainRoot: directory } : await repositoryOf(directory, gitDir);
16629
+ const { configDir, ...repository } = info.isDirectory() ? { kind: "main", mainRoot: directory, configDir: gitDir } : await repositoryOf(directory, gitDir);
16505
16630
  return {
16506
16631
  kind: "worktree",
16507
- located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository }
16632
+ located: { root: directory, ...branch === void 0 ? {} : { branch }, ...repository },
16633
+ configDir: configDir ?? ""
16508
16634
  };
16509
16635
  };
16636
+ var readOriginRepositoryKey = async (configDir) => {
16637
+ if (configDir.length === 0) {
16638
+ return void 0;
16639
+ }
16640
+ const content = await readBounded2(path15.join(configDir, "config"), MAX_GIT_CONFIG_BYTES);
16641
+ const url = content === void 0 ? void 0 : parseOriginRemoteUrl(content);
16642
+ return url === void 0 ? void 0 : normalizeRepositoryKey(url);
16643
+ };
16510
16644
  var createFilesystemWorktreeLocator = (options = {}) => {
16511
16645
  const now = options.monotonicMillis ?? (() => performance.now());
16512
16646
  const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
@@ -16524,32 +16658,57 @@ var createFilesystemWorktreeLocator = (options = {}) => {
16524
16658
  cache.set(directory, { at, probe });
16525
16659
  return probe;
16526
16660
  };
16527
- const locate = async (absolutePath) => {
16528
- try {
16529
- if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16661
+ const remoteCache = /* @__PURE__ */ new Map();
16662
+ const cachedOriginKey = (configDir) => {
16663
+ const hit = remoteCache.get(configDir);
16664
+ const at = now();
16665
+ if (hit !== void 0 && at - hit.at <= ttl) {
16666
+ return hit.key;
16667
+ }
16668
+ if (remoteCache.size >= MAX_CACHE_ENTRIES) {
16669
+ remoteCache.clear();
16670
+ }
16671
+ const key = readOriginRepositoryKey(configDir).catch(() => void 0);
16672
+ remoteCache.set(configDir, { at, key });
16673
+ return key;
16674
+ };
16675
+ const findWorktree = async (absolutePath) => {
16676
+ if (!path15.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
16677
+ return void 0;
16678
+ }
16679
+ let directory = path15.resolve(absolutePath);
16680
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
16681
+ const probe = await cachedProbe(directory);
16682
+ if (probe.kind === "worktree") {
16683
+ return probe;
16684
+ }
16685
+ if (probe.kind === "invalid") {
16530
16686
  return void 0;
16531
16687
  }
16532
- let directory = path15.resolve(absolutePath);
16533
- for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
16534
- const probe = await cachedProbe(directory);
16535
- if (probe.kind === "worktree") {
16536
- return probe.located;
16537
- }
16538
- if (probe.kind === "invalid") {
16539
- return void 0;
16540
- }
16541
- const parent = path15.dirname(directory);
16542
- if (parent === directory) {
16543
- return void 0;
16544
- }
16545
- directory = parent;
16688
+ const parent = path15.dirname(directory);
16689
+ if (parent === directory) {
16690
+ return void 0;
16546
16691
  }
16692
+ directory = parent;
16693
+ }
16694
+ return void 0;
16695
+ };
16696
+ const locate = async (absolutePath) => {
16697
+ try {
16698
+ return (await findWorktree(absolutePath))?.located;
16699
+ } catch {
16547
16700
  return void 0;
16701
+ }
16702
+ };
16703
+ const originRepositoryKey = async (absolutePath) => {
16704
+ try {
16705
+ const probe = await findWorktree(absolutePath);
16706
+ return probe === void 0 ? void 0 : await cachedOriginKey(probe.configDir);
16548
16707
  } catch {
16549
16708
  return void 0;
16550
16709
  }
16551
16710
  };
16552
- return { locate };
16711
+ return { locate, originRepositoryKey };
16553
16712
  };
16554
16713
 
16555
16714
  // src/integration/hook-runtime.ts
@@ -16685,7 +16844,12 @@ var createHookRuntime = (options) => {
16685
16844
  })(),
16686
16845
  ...options.worktreeLocator === null ? {} : {
16687
16846
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
16688
- }
16847
+ },
16848
+ // Only a scoped destination routes by repository, so only then is the session
16849
+ // directory's remote read at all.
16850
+ routeByWorkspaceRepository: exportDestinations.destinations.some(
16851
+ (destination) => destination.scopes !== void 0
16852
+ )
16689
16853
  };
16690
16854
  const hook = createOtelHook({ ...hookDeps, sink });
16691
16855
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
@@ -16763,9 +16927,10 @@ var createHookRuntime = (options) => {
16763
16927
  turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
16764
16928
  }
16765
16929
  }
16766
- const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
16930
+ const resourceFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
16931
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : ingest.workspaceRepositoryKey ?? resourceFallback;
16767
16932
  const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
16768
- const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
16933
+ const metricEvents = resourceFallback === void 0 || ingest.workspaceRepositoryKey !== void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
16769
16934
  (event3) => event3.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
16770
16935
  ...event3,
16771
16936
  contextAttributes: {