@netgreener/runtime 0.1.10 → 0.1.11

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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog — @netgreener/runtime
2
2
 
3
+ ## [0.1.11] — 2026-10-21
4
+
5
+ ### Fixed
6
+ - Preserve exact retry payloads and isolate newly arriving observations.
7
+ - Allocate process CPU and memory consistently across routes and tenants.
8
+ - Bound tenant buckets and improve tenant inference and diagnostics.
9
+ - Improve service discovery and resource-finding guidance for Node projects.
10
+
3
11
  ## [0.1.10] — 2026-10-19
4
12
 
5
13
  ### Added
@@ -40,6 +40,8 @@ export declare class ServiceRuntimeAggregator {
40
40
  windowSeconds: number;
41
41
  /** Crude window RAM (GiB·h); split by occupancy share when present. */
42
42
  windowRamGbHours?: number | null;
43
+ /** One process-wide CPU delta; per-route values are allocated estimates. */
44
+ windowCpuSeconds?: number | null;
43
45
  occupancy?: {
44
46
  by_unit: Record<string, number>;
45
47
  in_flight_seconds: number;
@@ -1,4 +1,5 @@
1
1
  import { energyKwhToCarbonG } from './carbonLedger.js';
2
+ import { tenantBucketId } from './tenantContext.js';
2
3
  const MAX_UNITS = 500;
3
4
  const MAX_SERVICE_UNIT_LEN = 256;
4
5
  function normalizeServiceUnit(raw) {
@@ -29,10 +30,11 @@ export class ServiceRuntimeAggregator {
29
30
  const key = normalizeServiceUnit(sample.serviceUnit);
30
31
  this.recordIntoMap(this.units, key, sample);
31
32
  if (sample.tenantId) {
32
- let tenantUnits = this.byTenant.get(sample.tenantId);
33
+ const tenantId = tenantBucketId(sample.tenantId, this.byTenant);
34
+ let tenantUnits = this.byTenant.get(tenantId);
33
35
  if (!tenantUnits) {
34
36
  tenantUnits = new Map();
35
- this.byTenant.set(sample.tenantId, tenantUnits);
37
+ this.byTenant.set(tenantId, tenantUnits);
36
38
  }
37
39
  this.recordIntoMap(tenantUnits, key, sample);
38
40
  }
@@ -97,13 +99,16 @@ export class ServiceRuntimeAggregator {
97
99
  : null;
98
100
  const useOccupancy = Boolean(alloc?.useOccupancy);
99
101
  const sorted = list.sort((a, b) => b.durationMsTotal - a.durationMsTotal);
102
+ const totalCalls = list.reduce((sum, unit) => sum + unit.calls, 0);
100
103
  const units = sorted.map((u) => {
101
- const share = equalShare ? 1 / list.length : u.durationMsTotal / totalDuration;
104
+ const share = equalShare ? u.calls / totalCalls : u.durationMsTotal / totalDuration;
102
105
  const energy = energyBudget * share;
103
106
  const avg = u.calls ? u.durationMsTotal / u.calls : 0;
104
- const cpuSeconds = u.cpuMsMeasured
105
- ? u.cpuMsTotal / 1000
106
- : u.durationMsTotal / 1000;
107
+ const cpuSeconds = alloc?.windowCpuSeconds != null
108
+ ? nonNegativeFinite(alloc.windowCpuSeconds) * share
109
+ : u.cpuMsMeasured
110
+ ? u.cpuMsTotal / 1000
111
+ : u.durationMsTotal / 1000;
107
112
  const unit = {
108
113
  service_unit: u.serviceUnit,
109
114
  unit_type: u.unitType,
@@ -248,21 +253,33 @@ export class ServiceRuntimeAggregator {
248
253
  windowSeconds,
249
254
  windowRamGbHours,
250
255
  useOccupancy,
256
+ windowCpuSeconds: opts.windowCpuSeconds,
251
257
  };
252
258
  const units = this.buildUnitsList(this.units, windowEnergyKwh, equalShare, totalDuration, attributedOccMap, unitAlloc);
253
259
  const byTenant = {};
254
260
  const totalBusy = list.reduce((s, u) => s + u.durationMsTotal, 0);
261
+ const totalCalls = list.reduce((s, u) => s + u.calls, 0);
255
262
  for (const [tenantId, tenantMap] of this.byTenant.entries()) {
256
263
  const tenantList = [...tenantMap.values()].filter((u) => u.calls > 0);
257
264
  if (!tenantList.length)
258
265
  continue;
259
266
  const tenantBusy = tenantList.reduce((s, u) => s + u.durationMsTotal, 0);
267
+ const tenantShare = totalBusy > 0 ? tenantBusy / totalBusy
268
+ : tenantList.reduce((sum, unit) => sum + unit.calls, 0) / totalCalls;
260
269
  const tenantEnergy = totalBusy > 0
261
270
  ? windowEnergyKwh * (tenantBusy / totalBusy)
262
- : windowEnergyKwh / Math.max(1, this.byTenant.size);
271
+ : windowEnergyKwh * tenantShare;
263
272
  const tenantDuration = tenantList.reduce((s, u) => s + u.durationMsTotal, 0);
264
273
  const tenantEqual = tenantDuration <= 0;
265
- const tenantUnits = this.buildUnitsList(tenantMap, tenantEnergy, tenantEqual, tenantDuration, attributedOccMap, unitAlloc);
274
+ const tenantUnits = this.buildUnitsList(tenantMap, tenantEnergy, tenantEqual, tenantDuration, attributedOccMap, {
275
+ ...unitAlloc,
276
+ // Route occupancy cannot identify tenants sharing that route.
277
+ useOccupancy: false,
278
+ windowRamGbHours: windowRamGbHours == null ? null
279
+ : windowRamGbHours * tenantShare,
280
+ windowCpuSeconds: opts.windowCpuSeconds == null ? null
281
+ : opts.windowCpuSeconds * tenantShare,
282
+ });
266
283
  if (!tenantUnits.length)
267
284
  continue;
268
285
  byTenant[tenantId] = {
@@ -286,9 +303,11 @@ export class ServiceRuntimeAggregator {
286
303
  else
287
304
  attribution = 'duration_share';
288
305
  const attribution_detail = {
289
- cpu: measuredCpu
290
- ? { method: 'request_process_cpu_time', kind: 'measured' }
291
- : { method: 'request_duration_proxy', kind: 'proxy' },
306
+ cpu: opts.windowCpuSeconds != null
307
+ ? { method: 'process_window_duration_share', kind: 'allocated_estimate' }
308
+ : measuredCpu
309
+ ? { method: 'request_process_cpu_time', kind: 'proxy' }
310
+ : { method: 'request_duration_proxy', kind: 'proxy' },
292
311
  ram: {
293
312
  method: useOccupancy
294
313
  ? 'concurrency_normalized_active_occupancy'
@@ -303,7 +322,7 @@ export class ServiceRuntimeAggregator {
303
322
  },
304
323
  gpu: { method: 'none', kind: 'unavailable' },
305
324
  energy: {
306
- cpu_dynamic: measuredCpu ? 'cpu_time_share_preferred' : 'duration_share',
325
+ cpu_dynamic: 'duration_share',
307
326
  memory: useOccupancy ? 'ram_occupancy_share' : 'unallocated',
308
327
  gpu: 'none',
309
328
  },
@@ -361,7 +380,8 @@ export class ServiceRuntimeAggregator {
361
380
  this.windowStartedAt = Math.min(this.windowStartedAt, snapshot.windowStartedAt);
362
381
  }
363
382
  this.mergeMap(this.units, snapshot.units);
364
- for (const [tenantId, sourceMap] of snapshot.byTenant.entries()) {
383
+ for (const [sourceTenantId, sourceMap] of snapshot.byTenant.entries()) {
384
+ const tenantId = tenantBucketId(sourceTenantId, this.byTenant);
365
385
  let targetMap = this.byTenant.get(tenantId);
366
386
  if (!targetMap) {
367
387
  targetMap = new Map();
@@ -6,7 +6,7 @@
6
6
  import { type DeclaredExternalApiEntry } from './declaredExternalApis.js';
7
7
  import { type ListCandidateSourceFilesOptions } from './projectScan.js';
8
8
  import { type ResourceFindingCandidateV1 } from './resourceFindingCandidate.js';
9
- import type { ServiceManifestV0 } from './serviceDiscovery.js';
9
+ import { type ServiceManifestV0 } from './serviceDiscovery.js';
10
10
  export type BuildResourceFindingsOptions = ListCandidateSourceFilesOptions & {
11
11
  projectId?: string;
12
12
  /** Max candidate findings to return (default 50). */
@@ -9,6 +9,7 @@ import { collectDeclaredExternalApis, dependencyMapFromPackageJson, } from './de
9
9
  import { collectPreferAstHits } from './preferAstDetectors.js';
10
10
  import { buildServiceManifestFromPaths, listCandidateSourceFiles, } from './projectScan.js';
11
11
  import { toResourceFindingCandidate, } from './resourceFindingCandidate.js';
12
+ import { attachServiceUnitsToFindings } from './serviceDiscovery.js';
12
13
  import { filterValidResourceFindings } from './validateResourceFinding.js';
13
14
  import { isTypescriptAnalyzeAvailable } from './loadTypescript.js';
14
15
  function readProjectDependencyMap(projectDir) {
@@ -66,7 +67,8 @@ export function buildResourceAnalyzeResultFromPaths(projectDir, relPaths, opts =
66
67
  continue;
67
68
  }
68
69
  }
69
- const findings = buildResourceFindingsFromSources(sources, opts);
70
+ const manifest = buildServiceManifestFromPaths(projectDir, Object.keys(sources), opts);
71
+ const findings = attachServiceUnitsToFindings(buildResourceFindingsFromSources(sources, opts), manifest);
70
72
  const by_mechanism = {};
71
73
  for (const f of findings) {
72
74
  by_mechanism[f.mechanism_id] = (by_mechanism[f.mechanism_id] || 0) + 1;
@@ -75,7 +77,6 @@ export function buildResourceAnalyzeResultFromPaths(projectDir, relPaths, opts =
75
77
  sources,
76
78
  packageDependencies: readProjectDependencyMap(projectDir),
77
79
  });
78
- const manifest = buildServiceManifestFromPaths(projectDir, Object.keys(sources), opts);
79
80
  return {
80
81
  schema: 'resource_analyze_result_v0',
81
82
  contract_status: 'mp4_scaffold',
@@ -97,6 +98,7 @@ export function buildResourceAnalyzeResultFromPaths(projectDir, relPaths, opts =
97
98
  'Detectors: retry_amplification, external_api_overconsumption, unbounded_parallelism, polling_or_idle_work, repeated_work, process_or_runtime_churn (subprocess + model_load), memory_retention_or_materialization, per_item_instead_of_batch (nested lookup + inference_inside_loop)',
98
99
  `typescript AST available=${isTypescriptAnalyzeAvailable()}`,
99
100
  'Candidates are fail-closed filtered through vendored resource_finding_v1 JSON Schema (Ajv)',
101
+ 'Guidance is optimization.summary (schema-legal); Next App Router / Pages API fill service_manifest endpoints',
100
102
  'Skipped RD0 context-only: http_call_without_timeout; skipped low-energy print_in_loop; skipped ML-only excess_training_work / accelerator_underutilization',
101
103
  ],
102
104
  };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Candidate-safe guidance for Node Analyze findings.
3
+ *
4
+ * resource_finding_v1 forbids extra top-level fields. Guidance belongs on
5
+ * optional ``optimization.{hypothesis_id,summary,risk}`` — never a new property.
6
+ * Does not upload, verify, or claim measured savings.
7
+ */
8
+ export type MechanismGuidance = {
9
+ hypothesis_id: string;
10
+ summary: string;
11
+ risk: 'low' | 'medium' | 'high';
12
+ };
13
+ export declare const MECHANISM_GUIDANCE: Record<string, MechanismGuidance>;
14
+ export declare function optimizationForMechanism(mechanismId: string): MechanismGuidance | null;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Candidate-safe guidance for Node Analyze findings.
3
+ *
4
+ * resource_finding_v1 forbids extra top-level fields. Guidance belongs on
5
+ * optional ``optimization.{hypothesis_id,summary,risk}`` — never a new property.
6
+ * Does not upload, verify, or claim measured savings.
7
+ */
8
+ export const MECHANISM_GUIDANCE = {
9
+ retry_amplification: {
10
+ hypothesis_id: 'cap_retries_jitter',
11
+ summary: 'Cap retry attempts and add exponential backoff with jitter so failed calls do not multiply paid traffic.',
12
+ risk: 'medium',
13
+ },
14
+ external_api_overconsumption: {
15
+ hypothesis_id: 'batch_or_cache_api',
16
+ summary: 'Batch requests, cache stable responses, or move the call outside the hot path so cost does not scale with every item.',
17
+ risk: 'medium',
18
+ },
19
+ unbounded_parallelism: {
20
+ hypothesis_id: 'limit_concurrency',
21
+ summary: 'Bound concurrency with a pool or semaphore so fan-out cannot exhaust sockets, workers, or provider rate limits.',
22
+ risk: 'high',
23
+ },
24
+ polling_or_idle_work: {
25
+ hypothesis_id: 'replace_poll_sleep',
26
+ summary: 'Replace tight poll/sleep loops with a webhook, queue, or backoff so idle wait does not burn CPU and outbound calls.',
27
+ risk: 'medium',
28
+ },
29
+ repeated_work: {
30
+ hypothesis_id: 'reuse_computed_result',
31
+ summary: 'Hoist or cache repeated reads and identical work so the same payload is not fetched or recomputed every iteration.',
32
+ risk: 'low',
33
+ },
34
+ process_or_runtime_churn: {
35
+ hypothesis_id: 'reuse_runtime_process',
36
+ summary: 'Reuse a long-lived process or loaded model instead of spawning or reloading on every request or loop iteration.',
37
+ risk: 'high',
38
+ },
39
+ memory_retention_or_materialization: {
40
+ hypothesis_id: 'stream_or_chunk',
41
+ summary: 'Stream or chunk the dataset instead of materializing the full collection in memory on the hot path.',
42
+ risk: 'medium',
43
+ },
44
+ per_item_instead_of_batch: {
45
+ hypothesis_id: 'batch_per_item_work',
46
+ summary: 'Replace per-item lookups or inference with a batched API or join so work grows with batches, not each row.',
47
+ risk: 'medium',
48
+ },
49
+ };
50
+ export function optimizationForMechanism(mechanismId) {
51
+ return MECHANISM_GUIDANCE[mechanismId] ?? null;
52
+ }
@@ -1,5 +1,6 @@
1
- export { buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, type ServiceEndpointUnit, type ServiceFileExtraction, type ServiceManifestV0, type ServiceTaskUnit, } from './serviceDiscovery.js';
2
- export { buildServiceManifestFromPaths, listCandidateSourceFiles, type ListCandidateSourceFilesOptions, } from './projectScan.js';
1
+ export { attachServiceUnitsToFindings, buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, nextFileRoutePath, type ServiceEndpointUnit, type ServiceFileExtraction, type ServiceManifestV0, type ServiceTaskUnit, } from './serviceDiscovery.js';
2
+ export { DEFAULT_MAX_SOURCE_FILES, buildServiceManifestFromPaths, listCandidateSourceFiles, type ListCandidateSourceFilesOptions, } from './projectScan.js';
3
+ export { MECHANISM_GUIDANCE, optimizationForMechanism, type MechanismGuidance, } from './findingGuidance.js';
3
4
  export { NON_RESOURCE_CATEGORIES, RESOURCE_DOMAINS, admitAnalyzeCandidate, isNonResourceCategory, type AdmissionDecision, type NonResourceCategory, type ResourceDomain, } from './resourceAdmission.js';
4
5
  export { languageForPath, toResourceFindingCandidate, type ResourceCandidateHit, type ResourceFindingCandidateV1, type ResourcePrimaryDomain, } from './resourceFindingCandidate.js';
5
6
  export { detectRetryAmplificationHits } from './retryAmplificationDetector.js';
@@ -1,5 +1,6 @@
1
- export { buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, } from './serviceDiscovery.js';
2
- export { buildServiceManifestFromPaths, listCandidateSourceFiles, } from './projectScan.js';
1
+ export { attachServiceUnitsToFindings, buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, nextFileRoutePath, } from './serviceDiscovery.js';
2
+ export { DEFAULT_MAX_SOURCE_FILES, buildServiceManifestFromPaths, listCandidateSourceFiles, } from './projectScan.js';
3
+ export { MECHANISM_GUIDANCE, optimizationForMechanism, } from './findingGuidance.js';
3
4
  export { NON_RESOURCE_CATEGORIES, RESOURCE_DOMAINS, admitAnalyzeCandidate, isNonResourceCategory, } from './resourceAdmission.js';
4
5
  export { languageForPath, toResourceFindingCandidate, } from './resourceFindingCandidate.js';
5
6
  export { detectRetryAmplificationHits } from './retryAmplificationDetector.js';
@@ -1,6 +1,8 @@
1
1
  import { type ServiceManifestV0 } from './serviceDiscovery.js';
2
+ /** Default Analyze walk cap — large enough for Next App Router trees. */
3
+ export declare const DEFAULT_MAX_SOURCE_FILES = 5000;
2
4
  export type ListCandidateSourceFilesOptions = {
3
- /** Max files to return (default 200). */
5
+ /** Max files to return (default 5000). */
4
6
  maxFiles?: number;
5
7
  /** Max bytes to read per file when building a manifest (default 512 KiB). */
6
8
  maxFileBytes?: number;
@@ -4,7 +4,10 @@
4
4
  */
5
5
  import { readdirSync, readFileSync, statSync } from 'node:fs';
6
6
  import { join, relative, sep } from 'node:path';
7
- import { buildServiceManifest } from './serviceDiscovery.js';
7
+ import { buildServiceManifest, nextFileRoutePath, } from './serviceDiscovery.js';
8
+ /** Default Analyze walk cap — large enough for Next App Router trees. */
9
+ export const DEFAULT_MAX_SOURCE_FILES = 5000;
10
+ const WALK_SAFETY_CAP = 20_000;
8
11
  const DEFAULT_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx']);
9
12
  const DEFAULT_SKIP_DIR_NAMES = new Set([
10
13
  'node_modules',
@@ -20,17 +23,31 @@ const DEFAULT_SKIP_DIR_NAMES = new Set([
20
23
  function normalizeRel(path) {
21
24
  return path.split(sep).join('/');
22
25
  }
26
+ function scanRank(rel) {
27
+ const n = rel.replace(/\\/g, '/');
28
+ if (nextFileRoutePath(n))
29
+ return 0;
30
+ if (n.startsWith('app/') ||
31
+ n.startsWith('src/app/') ||
32
+ n.startsWith('pages/') ||
33
+ n.startsWith('src/pages/')) {
34
+ return 1;
35
+ }
36
+ if (n.startsWith('src/'))
37
+ return 2;
38
+ return 3;
39
+ }
23
40
  /**
24
41
  * List repo-relative JS/TS source paths under ``projectDir`` (bounded).
25
42
  * Never throws — returns [] on errors.
26
43
  */
27
44
  export function listCandidateSourceFiles(projectDir, opts = {}) {
28
- const maxFiles = Math.max(1, opts.maxFiles ?? 200);
45
+ const maxFiles = Math.max(1, opts.maxFiles ?? DEFAULT_MAX_SOURCE_FILES);
29
46
  const extensions = new Set([...(opts.extensions ?? DEFAULT_EXTENSIONS)].map((e) => e.toLowerCase()));
30
47
  const skip = new Set([...(opts.skipDirNames ?? DEFAULT_SKIP_DIR_NAMES)].map((n) => n.toLowerCase()));
31
48
  const out = [];
32
49
  const walk = (absDir) => {
33
- if (out.length >= maxFiles)
50
+ if (out.length >= WALK_SAFETY_CAP)
34
51
  return;
35
52
  let entries;
36
53
  try {
@@ -40,7 +57,7 @@ export function listCandidateSourceFiles(projectDir, opts = {}) {
40
57
  return;
41
58
  }
42
59
  for (const entry of entries) {
43
- if (out.length >= maxFiles)
60
+ if (out.length >= WALK_SAFETY_CAP)
44
61
  return;
45
62
  const name = entry.name;
46
63
  if (name.startsWith('.') && name !== '.env.example') {
@@ -76,7 +93,8 @@ export function listCandidateSourceFiles(projectDir, opts = {}) {
76
93
  return [];
77
94
  }
78
95
  walk(projectDir);
79
- return out.sort();
96
+ out.sort((a, b) => scanRank(a) - scanRank(b) || a.localeCompare(b));
97
+ return out.slice(0, maxFiles);
80
98
  }
81
99
  /**
82
100
  * Read supplied repo-relative paths (or auto-walk) and build ``service_manifest_v0``.
@@ -102,10 +120,15 @@ export function buildServiceManifestFromPaths(projectDir, relPaths, opts = {}) {
102
120
  }
103
121
  }
104
122
  const manifest = buildServiceManifest(sources);
123
+ const scanned = Object.keys(sources).length;
124
+ const maxFiles = Math.max(1, opts.maxFiles ?? DEFAULT_MAX_SOURCE_FILES);
105
125
  manifest.notes = [
106
126
  ...manifest.notes,
107
- `scanned_files=${Object.keys(sources).length}`,
127
+ `scanned_files=${scanned}`,
108
128
  relPaths ? 'paths=explicit' : 'paths=auto_walk',
129
+ ...(!relPaths && scanned >= maxFiles
130
+ ? [`scan_truncated=true max_files=${maxFiles}`]
131
+ : []),
109
132
  ];
110
133
  return manifest;
111
134
  }
@@ -36,6 +36,12 @@ export type ResourceFindingCandidateV1 = {
36
36
  observation_ids: string[];
37
37
  benchmark_result_ids: string[];
38
38
  };
39
+ /** Optional candidate guidance — schema-legal subset of resource_finding_v1.optimization. */
40
+ optimization?: {
41
+ hypothesis_id: string;
42
+ summary: string;
43
+ risk: 'low' | 'medium' | 'high';
44
+ };
39
45
  };
40
46
  export type ResourceCandidateHit = {
41
47
  mechanism_id: string;
@@ -5,6 +5,7 @@
5
5
  * change RunSession, and does not claim Optimize / verified savings.
6
6
  */
7
7
  import { createHash } from 'node:crypto';
8
+ import { optimizationForMechanism } from './findingGuidance.js';
8
9
  import { admitAnalyzeCandidate } from './resourceAdmission.js';
9
10
  const POLICY_VERSION = '0.1.0';
10
11
  function languageFromPath(relPath) {
@@ -36,6 +37,7 @@ export function toResourceFindingCandidate(hit, projectId = 'local') {
36
37
  return null;
37
38
  const language = hit.language || languageFromPath(hit.rel_path);
38
39
  const scopeId = (hit.symbol || hit.rel_path).slice(0, 200);
40
+ const guidance = optimizationForMechanism(hit.mechanism_id);
39
41
  return {
40
42
  schema_version: 'resource_finding_v1',
41
43
  finding_id: stableFindingId(hit, projectId).slice(0, 128),
@@ -68,6 +70,15 @@ export function toResourceFindingCandidate(hit, projectId = 'local') {
68
70
  observation_ids: [],
69
71
  benchmark_result_ids: [],
70
72
  },
73
+ ...(guidance
74
+ ? {
75
+ optimization: {
76
+ hypothesis_id: guidance.hypothesis_id.slice(0, 64),
77
+ summary: guidance.summary.slice(0, 400),
78
+ risk: guidance.risk,
79
+ },
80
+ }
81
+ : {}),
71
82
  };
72
83
  }
73
84
  export function languageForPath(relPath) {
@@ -54,8 +54,13 @@ export type ServiceManifestV0 = {
54
54
  };
55
55
  notes: string[];
56
56
  };
57
+ /**
58
+ * HTTP path implied by a Next.js App Router ``route`` file or Pages ``pages/api`` file.
59
+ * Route groups ``(marketing)`` and parallel slots ``@modal`` are dropped.
60
+ */
61
+ export declare function nextFileRoutePath(relPath: string): string | null;
57
62
  /** Frameworks whose imports / requires appear in ``source``. */
58
- export declare function detectFrameworks(source: string): string[];
63
+ export declare function detectFrameworks(source: string, relPath?: string): string[];
59
64
  /**
60
65
  * Extract service units from one JS/TS source string.
61
66
  * Never throws on bad source — returns empty collections.
@@ -64,3 +69,20 @@ export declare function extractServiceUnits(sourceCode: string, relPath?: string
64
69
  /** Project-level ``service_manifest_v0`` from ``{relPath: source}``. */
65
70
  export declare function buildServiceManifest(fileSources: Record<string, string>): ServiceManifestV0;
66
71
  export declare function isServiceProject(manifest: ServiceManifestV0): boolean;
72
+ type FindingScope = {
73
+ kind: 'function' | 'service_unit' | 'task' | 'script';
74
+ id: string;
75
+ source_locations: Array<{
76
+ path: string;
77
+ start_line: number;
78
+ end_line: number;
79
+ }>;
80
+ };
81
+ /**
82
+ * Attribute a finding to the owning endpoint/task when the file+line is unambiguous.
83
+ * Same rule as Python ``attach_service_units``: innermost span, else sole unit on the file.
84
+ */
85
+ export declare function attachServiceUnitsToFindings<T extends {
86
+ scope: FindingScope;
87
+ }>(findings: T[], manifest: ServiceManifestV0): T[];
88
+ export {};
@@ -22,6 +22,36 @@ const FRAMEWORK_IMPORT_HINTS = [
22
22
  const HTTP_ROUTE = /\b(?:app|router|server|fastify|instance)\.(get|post|put|delete|patch|head|options)\(\s*['"`]([^'"`]+)['"`]/gi;
23
23
  const NEST_MAPPING = /@(Get|Post|Put|Delete|Patch|Head|Options)\(\s*(?:['"`]([^'"`]*)['"`])?\s*\)/g;
24
24
  const BULLMQ_QUEUE_ADD = /\.add\(\s*['"`]([A-Za-z0-9_.:-]+)['"`]/g;
25
+ const NEXT_HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
26
+ const NEXT_EXPORT_FN = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
27
+ const NEXT_EXPORT_CONST = /\bexport\s+const\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s*=/g;
28
+ const NEXT_PAGES_METHOD = /\b(?:req|request)\.method\s*===?\s*['"`](GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)['"`]/gi;
29
+ /**
30
+ * HTTP path implied by a Next.js App Router ``route`` file or Pages ``pages/api`` file.
31
+ * Route groups ``(marketing)`` and parallel slots ``@modal`` are dropped.
32
+ */
33
+ export function nextFileRoutePath(relPath) {
34
+ const n = relPath.replace(/\\/g, '/').replace(/^\.\//, '');
35
+ const app = n.match(/(?:^|\/)(?:src\/)?app\/(.+)\/route\.(?:[cm]?[jt]sx?)$/i);
36
+ if (app) {
37
+ const segs = app[1].split('/').filter((s) => {
38
+ if (!s)
39
+ return false;
40
+ if (s.startsWith('(') && s.endsWith(')'))
41
+ return false;
42
+ if (s.startsWith('@'))
43
+ return false;
44
+ return true;
45
+ });
46
+ return segs.length ? `/${segs.join('/')}` : '/';
47
+ }
48
+ const pages = n.match(/(?:^|\/)(?:src\/)?pages\/api\/(.+)\.(?:[cm]?[jt]sx?)$/i);
49
+ if (pages) {
50
+ const route = pages[1].replace(/\/index$/i, '');
51
+ return route ? `/api/${route}` : '/api';
52
+ }
53
+ return null;
54
+ }
25
55
  function lineOf(source, index) {
26
56
  if (index <= 0)
27
57
  return 1;
@@ -33,7 +63,10 @@ function lineOf(source, index) {
33
63
  return line;
34
64
  }
35
65
  function looksDynamic(path) {
36
- return path.includes(':') || path.includes('*') || path.includes('{');
66
+ return (path.includes(':') ||
67
+ path.includes('*') ||
68
+ path.includes('{') ||
69
+ path.includes('['));
37
70
  }
38
71
  function normalizePath(path) {
39
72
  if (!path)
@@ -41,13 +74,17 @@ function normalizePath(path) {
41
74
  return path.startsWith('/') ? path : `/${path}`;
42
75
  }
43
76
  /** Frameworks whose imports / requires appear in ``source``. */
44
- export function detectFrameworks(source) {
77
+ export function detectFrameworks(source, relPath = '') {
45
78
  const found = [];
46
79
  for (const hint of FRAMEWORK_IMPORT_HINTS) {
80
+ hint.pattern.lastIndex = 0;
47
81
  if (hint.pattern.test(source) && !found.includes(hint.id)) {
48
82
  found.push(hint.id);
49
83
  }
50
84
  }
85
+ if (nextFileRoutePath(relPath) && !found.includes('next')) {
86
+ found.push('next');
87
+ }
51
88
  return found;
52
89
  }
53
90
  function collectHttpRoutes(source, relPath) {
@@ -101,6 +138,64 @@ function collectNestRoutes(source, relPath) {
101
138
  }
102
139
  return endpoints;
103
140
  }
141
+ function collectNextFileRoutes(source, relPath) {
142
+ const routePath = nextFileRoutePath(relPath);
143
+ if (!routePath)
144
+ return [];
145
+ const firstLine = new Map();
146
+ const remember = (method, index) => {
147
+ const key = method.toUpperCase();
148
+ if (!firstLine.has(key))
149
+ firstLine.set(key, lineOf(source, index));
150
+ };
151
+ for (const src of [NEXT_EXPORT_FN, NEXT_EXPORT_CONST]) {
152
+ const re = new RegExp(src.source, 'g');
153
+ let match;
154
+ while ((match = re.exec(source)) !== null) {
155
+ remember(match[1] || 'GET', match.index);
156
+ }
157
+ }
158
+ const reExport = /\bexport\s*\{([^}]+)\}/g;
159
+ let exported;
160
+ while ((exported = reExport.exec(source)) !== null) {
161
+ const body = exported[1] || '';
162
+ for (const method of NEXT_HTTP_METHODS) {
163
+ if (new RegExp(`\\b${method}\\b`).test(body)) {
164
+ remember(method, exported.index);
165
+ }
166
+ }
167
+ }
168
+ const posix = relPath.replace(/\\/g, '/');
169
+ if (firstLine.size === 0 && /(?:^|\/)(?:src\/)?pages\/api\//.test(posix)) {
170
+ const re = new RegExp(NEXT_PAGES_METHOD.source, 'gi');
171
+ let match;
172
+ while ((match = re.exec(source)) !== null) {
173
+ remember(match[1] || 'GET', match.index);
174
+ }
175
+ if (firstLine.size === 0)
176
+ firstLine.set('GET', 1);
177
+ }
178
+ const entries = [...firstLine.entries()].sort((a, b) => a[1] - b[1]);
179
+ const totalLines = source.split(/\r?\n/).length;
180
+ return entries.map(([method, start], i) => {
181
+ const nextStart = entries[i + 1]?.[1];
182
+ const end = nextStart ? nextStart - 1 : totalLines;
183
+ return {
184
+ service_unit: `${method} ${routePath}`,
185
+ unit_type: 'endpoint',
186
+ method,
187
+ path: routePath,
188
+ handler: method,
189
+ file: relPath,
190
+ line: start,
191
+ end_line: Math.max(start, end),
192
+ is_async: true,
193
+ dynamic: looksDynamic(routePath),
194
+ prefix_resolved: true,
195
+ evidence: 'heuristic_source',
196
+ };
197
+ });
198
+ }
104
199
  function collectBullMqTasks(source, relPath) {
105
200
  const tasks = [];
106
201
  const seen = new Set();
@@ -143,10 +238,11 @@ function dedupeUnits(items) {
143
238
  */
144
239
  export function extractServiceUnits(sourceCode, relPath = '<unknown>') {
145
240
  const source = String(sourceCode || '');
146
- const frameworks = detectFrameworks(source);
241
+ const frameworks = detectFrameworks(source, relPath);
147
242
  const endpoints = [
148
243
  ...collectHttpRoutes(source, relPath),
149
244
  ...(frameworks.includes('nest') ? collectNestRoutes(source, relPath) : []),
245
+ ...collectNextFileRoutes(source, relPath),
150
246
  ];
151
247
  const tasks = frameworks.includes('bullmq') || /\bbullmq\b/.test(source)
152
248
  ? collectBullMqTasks(source, relPath)
@@ -175,8 +271,11 @@ export function buildServiceManifest(fileSources) {
175
271
  endpoints.push(...extracted.endpoints);
176
272
  tasks.push(...extracted.tasks);
177
273
  }
274
+ const hasNextUnits = endpoints.some((e) => nextFileRoutePath(e.file));
178
275
  let framework = null;
179
- if (endpoints.length && frameworksDetected.includes('express'))
276
+ if (hasNextUnits)
277
+ framework = 'next';
278
+ else if (endpoints.length && frameworksDetected.includes('express'))
180
279
  framework = 'express';
181
280
  else if (endpoints.length && frameworksDetected.includes('fastify'))
182
281
  framework = 'fastify';
@@ -201,6 +300,7 @@ export function buildServiceManifest(fileSources) {
201
300
  },
202
301
  notes: [
203
302
  'MP4 scaffold: heuristic JS/TS discovery only — not TypeScript AST, not CLI/VSCE wired, not resource findings',
303
+ 'Next App Router / Pages API: file-path route discovery (route.ts / pages/api)',
204
304
  'Does not modify RunSession upload or runtime metering pipelines',
205
305
  ],
206
306
  };
@@ -208,3 +308,63 @@ export function buildServiceManifest(fileSources) {
208
308
  export function isServiceProject(manifest) {
209
309
  return Boolean(manifest.stats.endpoints || manifest.stats.tasks);
210
310
  }
311
+ /**
312
+ * Attribute a finding to the owning endpoint/task when the file+line is unambiguous.
313
+ * Same rule as Python ``attach_service_units``: innermost span, else sole unit on the file.
314
+ */
315
+ export function attachServiceUnitsToFindings(findings, manifest) {
316
+ const index = new Map();
317
+ const add = (file, start, end, id, kind) => {
318
+ const key = file.replace(/\\/g, '/');
319
+ const list = index.get(key) || [];
320
+ list.push({ start, end: Math.max(start, end), id, kind });
321
+ index.set(key, list);
322
+ };
323
+ for (const unit of manifest.endpoints) {
324
+ add(unit.file, unit.line, unit.end_line, unit.service_unit, 'service_unit');
325
+ }
326
+ for (const unit of manifest.tasks) {
327
+ add(unit.file, unit.line, unit.end_line, unit.service_unit, 'task');
328
+ }
329
+ for (const list of index.values()) {
330
+ list.sort((a, b) => a.start - b.start || b.end - a.end);
331
+ }
332
+ const matchFile = (fp) => {
333
+ if (index.has(fp))
334
+ return index.get(fp) || [];
335
+ for (const [key, spans] of index) {
336
+ if (fp.endsWith(key) || key.endsWith(fp))
337
+ return spans;
338
+ }
339
+ return [];
340
+ };
341
+ return findings.map((finding) => {
342
+ const loc = finding.scope.source_locations[0];
343
+ if (!loc)
344
+ return finding;
345
+ const spans = matchFile(loc.path.replace(/\\/g, '/'));
346
+ if (!spans.length)
347
+ return finding;
348
+ const line = loc.start_line;
349
+ const containing = spans.filter((s) => s.start <= line && line <= s.end);
350
+ let chosen = containing.length
351
+ ? containing.reduce((a, b) => (b.end - b.start < a.end - a.start ? b : a))
352
+ : null;
353
+ if (!chosen && spans.length === 1)
354
+ chosen = spans[0] || null;
355
+ if (!chosen && spans.length > 1) {
356
+ const before = spans.filter((s) => s.start <= line).sort((a, b) => b.start - a.start);
357
+ chosen = before[0] || null;
358
+ }
359
+ if (!chosen)
360
+ return finding;
361
+ return {
362
+ ...finding,
363
+ scope: {
364
+ ...finding.scope,
365
+ kind: chosen.kind,
366
+ id: chosen.id.slice(0, 200),
367
+ },
368
+ };
369
+ });
370
+ }
@@ -14,7 +14,7 @@
14
14
  import { AsyncLocalStorage } from 'node:async_hooks';
15
15
  import { activeMcpToolCallId, recordHttpInToolContext } from './mcpToolMeter.js';
16
16
  import { createRequire } from 'node:module';
17
- import { getTenantContext } from './tenantContext.js';
17
+ import { getTenantContext, tenantBucketId } from './tenantContext.js';
18
18
  import { attributionServiceUnit } from './requestContext.js';
19
19
  const requireFromHere = createRequire(import.meta.url);
20
20
  /**
@@ -803,10 +803,11 @@ export class ExternalApiAggregator {
803
803
  model,
804
804
  });
805
805
  if (tenantId) {
806
- let tenantBucket = this.byTenant.get(tenantId);
806
+ const bucketId = tenantBucketId(tenantId, this.byTenant);
807
+ let tenantBucket = this.byTenant.get(bucketId);
807
808
  if (!tenantBucket) {
808
809
  tenantBucket = new Map();
809
- this.byTenant.set(tenantId, tenantBucket);
810
+ this.byTenant.set(bucketId, tenantBucket);
810
811
  }
811
812
  this.recordProvider(tenantBucket, {
812
813
  provider,
@@ -986,7 +987,8 @@ export class ExternalApiAggregator {
986
987
  ExternalApiAggregator.mergeProvider(dst, src);
987
988
  }
988
989
  }
989
- for (const [tenant, srcBucket] of snapshot.byTenant.entries()) {
990
+ for (const [sourceTenant, srcBucket] of snapshot.byTenant.entries()) {
991
+ const tenant = tenantBucketId(sourceTenant, this.byTenant);
990
992
  let dstBucket = this.byTenant.get(tenant);
991
993
  if (!dstBucket) {
992
994
  this.byTenant.set(tenant, srcBucket);
@@ -6,7 +6,8 @@
6
6
  * 2. Point child at ``NETGREENER_EXPORT_MODE=collector`` + endpoint
7
7
  * 3. On child exit: terminate collector (drain)
8
8
  *
9
- * Does **not** flip the package default (unset mode → direct).
9
+ * Unset mode stays direct. BullMQ meters in-process and does not use this
10
+ * switch. Python Celery workers default to managed inside the Python launcher.
10
11
  * Windows: ``tcp://`` only.
11
12
  */
12
13
  import { spawn, type ChildProcess } from 'node:child_process';
@@ -6,7 +6,8 @@
6
6
  * 2. Point child at ``NETGREENER_EXPORT_MODE=collector`` + endpoint
7
7
  * 3. On child exit: terminate collector (drain)
8
8
  *
9
- * Does **not** flip the package default (unset mode → direct).
9
+ * Unset mode stays direct. BullMQ meters in-process and does not use this
10
+ * switch. Python Celery workers default to managed inside the Python launcher.
10
11
  * Windows: ``tcp://`` only.
11
12
  */
12
13
  import { spawn } from 'node:child_process';
package/dist/runtime.d.ts CHANGED
@@ -37,11 +37,9 @@ export declare class NetGreenerRuntime {
37
37
  /** In-flight HTTP/task units — gates ephemeral idle flush. */
38
38
  private inFlight;
39
39
  private invokeFlushScheduled;
40
- /**
41
- * Sticky window id until a successful export — preserves idempotency across
42
- * retry of the same in-memory snapshot (serverless / network retry).
43
- */
44
- private stickyWindowId;
40
+ /** Exact pending window; observations arriving during retries stay separate. */
41
+ private pendingPayload;
42
+ private cpuWindowMark;
45
43
  constructor(opts?: NetGreenerRuntimeOptions);
46
44
  get lifecycle(): ResolvedRuntimeLifecycle['lifecycle'];
47
45
  get enabled(): boolean;
@@ -87,6 +85,7 @@ export declare class NetGreenerRuntime {
87
85
  cpuTimeMs?: number;
88
86
  peakRssKb?: number;
89
87
  }): void;
88
+ private exportPendingWindow;
90
89
  flush(kind?: FlushKind): Promise<UploadResult | null>;
91
90
  shutdown(): Promise<UploadResult | null>;
92
91
  }
package/dist/runtime.js CHANGED
@@ -9,8 +9,7 @@ import { enrichRunContextForAnomaly } from './runContextEnrichment.js';
9
9
  import { getOccupancyTracker } from './occupancyTracker.js';
10
10
  import { getExternalAggregator, getOriginalFetch, installOutboundInstrumentation, } from './externalApiMeter.js';
11
11
  import { buildMcpLatencyV0, getMcpToolLedger, } from './mcpToolMeter.js';
12
- import { CPU_SOURCE_PROCESS, MEMORY_SOURCE_PROCESS, } from './processResources.js';
13
- import { CPU_SOURCE_DURATION_PROXY } from './n4/missingnessInventory.js';
12
+ import { CPU_SOURCE_PROCESS, MEMORY_SOURCE_PROCESS, beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
14
13
  import { buildRuntimeHealthV0, markHooksActive, mergeHealthIntoMetadata, noteExportAttempt, noteExportMode, noteExportResult, noteFlushSkippedInFlight, _resetRuntimeHealthForTests, } from './runtimeHealth.js';
15
14
  import { resolveLifecycle, } from './lifecycle.js';
16
15
  function vercelDeploymentHosts() {
@@ -53,11 +52,9 @@ export class NetGreenerRuntime {
53
52
  /** In-flight HTTP/task units — gates ephemeral idle flush. */
54
53
  inFlight = 0;
55
54
  invokeFlushScheduled = false;
56
- /**
57
- * Sticky window id until a successful export — preserves idempotency across
58
- * retry of the same in-memory snapshot (serverless / network retry).
59
- */
60
- stickyWindowId = null;
55
+ /** Exact pending window; observations arriving during retries stay separate. */
56
+ pendingPayload = null;
57
+ cpuWindowMark = beginProcessResourceSample();
61
58
  constructor(opts = {}) {
62
59
  this.config = opts.config ?? loadRuntimeConfig();
63
60
  this.collector = opts.collector ?? 'express_middleware';
@@ -208,6 +205,28 @@ export class NetGreenerRuntime {
208
205
  ...(sample.peakRssKb !== undefined ? { peakRssKb: sample.peakRssKb } : {}),
209
206
  });
210
207
  }
208
+ async exportPendingWindow() {
209
+ const payload = this.pendingPayload;
210
+ noteExportAttempt(this.exporter.mode);
211
+ let result;
212
+ try {
213
+ result = await this.exporter.exportRunSessionWindow(this.config, structuredClone(payload), this.uploadFetch());
214
+ }
215
+ catch (err) {
216
+ result = { ok: false, error: err instanceof Error ? err.message : String(err) };
217
+ }
218
+ noteExportResult(result.ok, result.ok ? undefined : 'error' in result ? result.error : 'export_failed');
219
+ if (result.ok)
220
+ this.pendingPayload = null;
221
+ // Observers must not mutate a pending retry or turn an ACK into a retry.
222
+ try {
223
+ this.onFlush?.(result, structuredClone(payload));
224
+ }
225
+ catch {
226
+ /* Export state is independent of application observer failures. */
227
+ }
228
+ return result;
229
+ }
211
230
  async flush(kind = 'manual') {
212
231
  if (!this.enabled)
213
232
  return null;
@@ -215,6 +234,15 @@ export class NetGreenerRuntime {
215
234
  noteFlushSkippedInFlight();
216
235
  return null;
217
236
  }
237
+ if (this.pendingPayload) {
238
+ this.flushing = true;
239
+ try {
240
+ return await this.exportPendingWindow();
241
+ }
242
+ finally {
243
+ this.flushing = false;
244
+ }
245
+ }
218
246
  const externalAgg = getExternalAggregator();
219
247
  const hasRuntime = this.aggregator.hasData();
220
248
  const hasExternal = externalAgg.hasData();
@@ -225,17 +253,16 @@ export class NetGreenerRuntime {
225
253
  noteExportMode(this.exporter.mode);
226
254
  const snapshot = hasRuntime ? this.aggregator.takeSnapshot() : null;
227
255
  const externalSnapshot = hasExternal ? externalAgg.takeSnapshot() : null;
256
+ const previousCpuMark = this.cpuWindowMark;
228
257
  try {
229
258
  const windowStartedMs = snapshot
230
259
  ? snapshot.windowStartedMs()
231
260
  : Date.now() - 1000;
232
261
  const windowSeconds = Math.max(0.001, (Date.now() - windowStartedMs) / 1000);
233
- // Crude trend energy: TDP * utilization proxy from request busy time.
234
- const busySeconds = snapshot
235
- ? snapshot.hasMeasuredCpu()
236
- ? snapshot.totalMeasuredCpuMs() / 1000
237
- : snapshot.totalDurationMs() / 1000
238
- : 0;
262
+ const windowCpuSeconds = endProcessResourceSample(this.cpuWindowMark).cpuTimeMs / 1000;
263
+ this.cpuWindowMark = beginProcessResourceSample();
264
+ // Trend energy estimate from one process CPU delta, not overlapping requests.
265
+ const busySeconds = snapshot ? windowCpuSeconds : 0;
239
266
  const util = Math.min(1, busySeconds / Math.max(windowSeconds, 0.001));
240
267
  const windowEnergyKwh = (this.config.estimateTdpWatts * util * windowSeconds) / 1000 / 3600;
241
268
  const occupancy = getOccupancyTracker().takeWindowSnapshot();
@@ -251,6 +278,7 @@ export class NetGreenerRuntime {
251
278
  windowEnergyKwh,
252
279
  windowSeconds,
253
280
  windowRamGbHours,
281
+ windowCpuSeconds,
254
282
  occupancy,
255
283
  })
256
284
  : null;
@@ -271,9 +299,7 @@ export class NetGreenerRuntime {
271
299
  const latencyV0 = buildMcpLatencyV0(mcpV0, externalV0 ?? null, windowSeconds);
272
300
  const end = new Date();
273
301
  const start = new Date(end.getTime() - windowSeconds * 1000);
274
- // Reuse sticky id until success so retries do not mint a new window.
275
- const windowId = this.stickyWindowId ?? newRuntimeWindowId();
276
- this.stickyWindowId = windowId;
302
+ const windowId = newRuntimeWindowId();
277
303
  // Prefer effective RuntimeConfig over ambient process.env.
278
304
  const tenantConfig = tenantConfigFromRuntime(this.config);
279
305
  const runContext = {
@@ -296,7 +322,6 @@ export class NetGreenerRuntime {
296
322
  tenantConfig,
297
323
  activeContext: getTenantContext(),
298
324
  });
299
- const measuredCpu = snapshot?.hasMeasuredCpu() ?? false;
300
325
  const measuredRss = snapshot?.hasMeasuredRss() ?? false;
301
326
  const carbonFactor = carbonFactorDict();
302
327
  const session_metadata = {
@@ -306,11 +331,7 @@ export class NetGreenerRuntime {
306
331
  ...(mcpV0 ? { mcp_tool_v0: mcpV0 } : {}),
307
332
  ...(latencyV0 ? { mcp_latency_v0: latencyV0 } : {}),
308
333
  measurement_provenance: {
309
- cpu_source: runtimeV0
310
- ? measuredCpu
311
- ? CPU_SOURCE_PROCESS
312
- : CPU_SOURCE_DURATION_PROXY
313
- : 'unavailable',
334
+ cpu_source: runtimeV0 ? CPU_SOURCE_PROCESS : 'unavailable',
314
335
  memory_source: measuredRss ? MEMORY_SOURCE_PROCESS : 'unavailable',
315
336
  energy_model: runtimeV0 ? 'tdp_utilization_estimate' : 'unavailable',
316
337
  gpu_scope: 'none',
@@ -348,26 +369,11 @@ export class NetGreenerRuntime {
348
369
  runtime_window_id: windowId,
349
370
  session_metadata,
350
371
  };
351
- noteExportAttempt(this.exporter.mode);
352
- const result = await this.exporter.exportRunSessionWindow(this.config, payload, this.uploadFetch());
353
- noteExportResult(result.ok, result.ok ? undefined : 'error' in result ? result.error : 'export_failed');
354
- mergeHealthIntoMetadata(session_metadata, buildRuntimeHealthV0());
355
- if (!result.ok) {
356
- if (snapshot)
357
- this.aggregator.mergeSnapshot(snapshot);
358
- if (externalSnapshot)
359
- externalAgg.mergeSnapshot(externalSnapshot);
360
- if (mcpSnapshot)
361
- getMcpToolLedger().mergeSnapshot(mcpSnapshot);
362
- // Keep stickyWindowId so the next flush retries the same window id.
363
- }
364
- else {
365
- this.stickyWindowId = null;
366
- }
367
- this.onFlush?.(result, payload);
368
- return result;
372
+ this.pendingPayload = structuredClone(payload);
373
+ return await this.exportPendingWindow();
369
374
  }
370
375
  catch (err) {
376
+ this.cpuWindowMark = previousCpuMark;
371
377
  noteExportResult(false, err instanceof Error ? err.message : String(err));
372
378
  if (snapshot)
373
379
  this.aggregator.mergeSnapshot(snapshot);
@@ -379,13 +385,18 @@ export class NetGreenerRuntime {
379
385
  ok: false,
380
386
  error: err instanceof Error ? err.message : String(err),
381
387
  };
382
- this.onFlush?.(result, {
383
- project_id: this.config.projectId,
384
- start_time: new Date().toISOString(),
385
- end_time: new Date().toISOString(),
386
- runtime_window_id: this.stickyWindowId ?? newRuntimeWindowId(),
387
- session_metadata: {},
388
- });
388
+ try {
389
+ this.onFlush?.(result, {
390
+ project_id: this.config.projectId,
391
+ start_time: new Date().toISOString(),
392
+ end_time: new Date().toISOString(),
393
+ runtime_window_id: newRuntimeWindowId(),
394
+ session_metadata: {},
395
+ });
396
+ }
397
+ catch {
398
+ /* Observer errors must never escape telemetry flush. */
399
+ }
389
400
  return result;
390
401
  }
391
402
  finally {
@@ -394,7 +405,12 @@ export class NetGreenerRuntime {
394
405
  }
395
406
  async shutdown() {
396
407
  this.stop();
397
- return this.flush('shutdown');
408
+ const hadPending = this.pendingPayload !== null;
409
+ const result = await this.flush('shutdown');
410
+ if (hadPending && result?.ok) {
411
+ return (await this.flush('shutdown')) ?? result;
412
+ }
413
+ return result;
398
414
  }
399
415
  }
400
416
  let globalRuntime = null;
@@ -83,7 +83,7 @@ export function buildRuntimeHealthV0() {
83
83
  remediation.push('A flush was skipped while another was in flight — window data is retried on failure merge; reduce flush contention if drops grow.');
84
84
  }
85
85
  if (state.exportFail > 0) {
86
- remediation.push('Inspect prior export errors; failed windows are restored into the aggregator for retry.');
86
+ remediation.push('Inspect prior export errors; the exact pending window is retained in memory for retry. Direct mode does not survive process restart.');
87
87
  }
88
88
  }
89
89
  else if (state.exportOk > 0 || state.hooksActive) {
@@ -5,6 +5,9 @@ export type TenantContext = {
5
5
  tenantSource: string;
6
6
  tenantLabel?: string;
7
7
  };
8
+ export declare const MAX_TENANT_BUCKETS = 200;
9
+ export declare const TENANT_OVERFLOW_ID = "netgreener:tenant-overflow";
10
+ export declare function tenantBucketId(tenantId: string, buckets: ReadonlyMap<string, unknown>): string;
8
11
  /**
9
12
  * Mutable ALS cell so ``setTenantContext`` (manual auth) updates the same
10
13
  * object Express holds for finish/close after the request ALS exits.
@@ -1,14 +1,21 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  const TENANT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
3
+ export const MAX_TENANT_BUCKETS = 200;
4
+ export const TENANT_OVERFLOW_ID = 'netgreener:tenant-overflow';
5
+ export function tenantBucketId(tenantId, buckets) {
6
+ return buckets.has(tenantId) || buckets.size < MAX_TENANT_BUCKETS - 1
7
+ ? tenantId : TENANT_OVERFLOW_ID;
8
+ }
3
9
  const storage = new AsyncLocalStorage();
4
10
  export function normalizeTenantId(value) {
5
11
  if (value === null || value === undefined)
6
12
  return null;
7
13
  const cleaned = String(value).trim();
8
- if (!cleaned || cleaned.includes('@'))
14
+ if (!cleaned || cleaned.includes('@') || cleaned === TENANT_OVERFLOW_ID)
15
+ return null;
16
+ if (cleaned.length > 128)
9
17
  return null;
10
- const clipped = cleaned.length > 128 ? cleaned.slice(0, 128) : cleaned;
11
- return TENANT_ID_RE.test(clipped) ? clipped : null;
18
+ return TENANT_ID_RE.test(cleaned) ? cleaned : null;
12
19
  }
13
20
  function tenantConfigFromSource(fields) {
14
21
  const source = (fields.source || 'none').trim().toLowerCase();
@@ -166,7 +173,19 @@ export function resolveTenantFromTaskData(data, config) {
166
173
  return { tenantId, tenantSource: `task_kwarg:${key}` };
167
174
  }
168
175
  export function runWithTenantContext(ctx, fn) {
169
- return storage.run({ current: ctx }, fn);
176
+ return storage.run({ current: normalizeTenantContext(ctx) }, fn);
177
+ }
178
+ function normalizeTenantContext(ctx) {
179
+ if (!ctx)
180
+ return null;
181
+ const tenantId = normalizeTenantId(ctx.tenantId);
182
+ if (!tenantId)
183
+ return null;
184
+ return {
185
+ tenantId,
186
+ tenantSource: String(ctx.tenantSource || 'manual').slice(0, 128),
187
+ ...(ctx.tenantLabel ? { tenantLabel: String(ctx.tenantLabel).trim().slice(0, 128) } : {}),
188
+ };
170
189
  }
171
190
  /**
172
191
  * Enter a mutable tenant cell for the remainder of this async chain (Fastify
@@ -174,7 +193,7 @@ export function runWithTenantContext(ctx, fn) {
174
193
  * handler runs inside one callback (Express ``next``).
175
194
  */
176
195
  export function enterTenantStore(ctx) {
177
- const store = { current: ctx };
196
+ const store = { current: normalizeTenantContext(ctx) };
178
197
  storage.enterWith(store);
179
198
  return store;
180
199
  }
@@ -191,12 +210,15 @@ export function getTenantContext() {
191
210
  * after the middleware ALS callback returns.
192
211
  */
193
212
  export function setTenantContext(ctx) {
213
+ const normalized = normalizeTenantContext(ctx);
214
+ if (!normalized)
215
+ throw new Error('invalid tenant_id');
194
216
  const store = storage.getStore();
195
217
  if (store) {
196
- store.current = ctx;
218
+ store.current = normalized;
197
219
  return;
198
220
  }
199
- storage.enterWith({ current: ctx });
221
+ storage.enterWith({ current: normalized });
200
222
  }
201
223
  export function collectWindowTenantIds(runtimeV0, externalV0) {
202
224
  const ids = new Set();
@@ -212,14 +234,18 @@ export function collectWindowTenantIds(runtimeV0, externalV0) {
212
234
  }
213
235
  export function attachWindowTenantToRunContext(runContext, opts) {
214
236
  const tenantIds = collectWindowTenantIds(opts.runtimeV0, opts.externalV0);
237
+ if (tenantIds.has(TENANT_OVERFLOW_ID))
238
+ return runContext;
215
239
  if (tenantIds.size !== 1)
216
240
  return runContext;
217
241
  const tenantId = [...tenantIds][0];
218
242
  runContext.tenant_id = tenantId;
219
- const source = configuredTenantSourceLabel(opts.tenantConfig) || opts.activeContext?.tenantSource;
243
+ const activeMatches = opts.activeContext?.tenantId === tenantId;
244
+ const source = (activeMatches ? opts.activeContext?.tenantSource : null)
245
+ || configuredTenantSourceLabel(opts.tenantConfig);
220
246
  if (source)
221
247
  runContext.tenant_source = source;
222
- const label = opts.activeContext?.tenantLabel;
248
+ const label = activeMatches ? opts.activeContext?.tenantLabel : undefined;
223
249
  if (label)
224
250
  runContext.tenant_label = label;
225
251
  return runContext;
@@ -0,0 +1,66 @@
1
+ {
2
+ "version": 1,
3
+ "description": "OP1 canonical git keys — CLI, SDK, Node, and VSCE must agree on every vector.",
4
+ "vectors": [
5
+ {
6
+ "in": "https://github.com/Org/NetGreener.git",
7
+ "out": "github.com/org/netgreener",
8
+ "note": "github https"
9
+ },
10
+ {
11
+ "in": "git@github.com:Org/NetGreener.git",
12
+ "out": "github.com/org/netgreener",
13
+ "note": "github ssh"
14
+ },
15
+ {
16
+ "in": "http://github.com/Org/NetGreener",
17
+ "out": "github.com/org/netgreener",
18
+ "note": "github http upgrade"
19
+ },
20
+ {
21
+ "in": "https://gitlab.com/Group/Sub/Repo.git",
22
+ "out": "gitlab.com/group/sub/repo",
23
+ "note": "gitlab nested path"
24
+ },
25
+ {
26
+ "in": "https://dev.azure.com/Contoso/Payments/_git/payments-api",
27
+ "out": "dev.azure.com/contoso/payments/payments-api",
28
+ "note": "ado https three-part"
29
+ },
30
+ {
31
+ "in": "https://dev.azure.com/Contoso/Payments/_git/payments-api.git",
32
+ "out": "dev.azure.com/contoso/payments/payments-api",
33
+ "note": "ado https with .git"
34
+ },
35
+ {
36
+ "in": "https://user:pat@dev.azure.com/Contoso/Payments/_git/payments-api",
37
+ "out": "dev.azure.com/contoso/payments/payments-api",
38
+ "note": "ado https strip credentials"
39
+ },
40
+ {
41
+ "in": "https://Contoso.visualstudio.com/Payments/_git/payments-api",
42
+ "out": "dev.azure.com/contoso/payments/payments-api",
43
+ "note": "ado visualstudio.com host"
44
+ },
45
+ {
46
+ "in": "git@ssh.dev.azure.com:v3/Contoso/Payments/payments-api",
47
+ "out": "dev.azure.com/contoso/payments/payments-api",
48
+ "note": "ado ssh v3"
49
+ },
50
+ {
51
+ "in": "ssh://git@ssh.dev.azure.com/v3/Contoso/Payments/payments-api",
52
+ "out": "dev.azure.com/contoso/payments/payments-api",
53
+ "note": "ado ssh:// v3"
54
+ },
55
+ {
56
+ "in": "",
57
+ "out": null,
58
+ "note": "empty"
59
+ },
60
+ {
61
+ "in": " ",
62
+ "out": null,
63
+ "note": "whitespace"
64
+ }
65
+ ]
66
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netgreener/runtime",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "NetGreener Node.js Runtime — Express/Fastify/Nest/Next/process adapter uploading RunSessions to api_server.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",