@netgreener/runtime 0.1.0 → 0.1.9

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 (101) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/TUTORIAL.md +120 -29
  3. package/dist/aggregator.d.ts +12 -2
  4. package/dist/aggregator.js +135 -8
  5. package/dist/analyze/buildResourceFindings.d.ts +4 -0
  6. package/dist/analyze/buildResourceFindings.js +17 -0
  7. package/dist/analyze/cli.d.ts +1 -0
  8. package/dist/analyze/cli.js +22 -1
  9. package/dist/analyze/declaredExternalApis.d.ts +31 -0
  10. package/dist/analyze/declaredExternalApis.js +174 -0
  11. package/dist/analyze/index.d.ts +1 -0
  12. package/dist/analyze/index.js +1 -0
  13. package/dist/auto.d.ts +7 -0
  14. package/dist/auto.js +8 -0
  15. package/dist/bullmq.d.ts +2 -2
  16. package/dist/bullmq.js +28 -58
  17. package/dist/carbonLedger.d.ts +28 -0
  18. package/dist/carbonLedger.js +52 -0
  19. package/dist/cgroupV2.d.ts +44 -0
  20. package/dist/cgroupV2.js +174 -0
  21. package/dist/cli/helpText.d.ts +3 -3
  22. package/dist/cli/helpText.js +42 -35
  23. package/dist/cli/netgreener.d.ts +7 -7
  24. package/dist/cli/netgreener.js +23 -16
  25. package/dist/cli/runCli.d.ts +20 -0
  26. package/dist/cli/runCli.js +249 -0
  27. package/dist/cli/runPreload.d.ts +5 -0
  28. package/dist/cli/runPreload.js +43 -0
  29. package/dist/collectorMetadata.d.ts +1 -1
  30. package/dist/collectorMetadata.js +2 -0
  31. package/dist/config.d.ts +2 -0
  32. package/dist/config.js +6 -2
  33. package/dist/exporter.d.ts +7 -2
  34. package/dist/exporter.js +12 -6
  35. package/dist/express.js +17 -6
  36. package/dist/externalApiMeter.d.ts +43 -1
  37. package/dist/externalApiMeter.js +267 -5
  38. package/dist/fastify.js +17 -6
  39. package/dist/index.d.ts +10 -2
  40. package/dist/index.js +9 -1
  41. package/dist/init.d.ts +30 -0
  42. package/dist/init.js +31 -0
  43. package/dist/lifecycle.d.ts +45 -0
  44. package/dist/lifecycle.js +112 -0
  45. package/dist/managedCollectorLauncher.d.ts +37 -0
  46. package/dist/managedCollectorLauncher.js +162 -0
  47. package/dist/n4/deploymentMatrix.d.ts +9 -5
  48. package/dist/n4/deploymentMatrix.js +13 -9
  49. package/dist/n4/missingnessInventory.js +3 -3
  50. package/dist/next.d.ts +61 -0
  51. package/dist/next.js +195 -0
  52. package/dist/occupancyTracker.d.ts +27 -0
  53. package/dist/occupancyTracker.js +87 -0
  54. package/dist/optimize/apply.d.ts +38 -0
  55. package/dist/optimize/apply.js +173 -0
  56. package/dist/optimize/cli.d.ts +26 -0
  57. package/dist/optimize/cli.js +323 -0
  58. package/dist/optimize/index.d.ts +6 -0
  59. package/dist/optimize/index.js +5 -0
  60. package/dist/optimize/llmApply.d.ts +22 -0
  61. package/dist/optimize/llmApply.js +80 -0
  62. package/dist/optimize/llmSession.d.ts +88 -0
  63. package/dist/optimize/llmSession.js +135 -0
  64. package/dist/optimize/provider.d.ts +17 -0
  65. package/dist/optimize/provider.js +119 -0
  66. package/dist/optimize/safePatches.d.ts +18 -0
  67. package/dist/optimize/safePatches.js +247 -0
  68. package/dist/optimize/types.d.ts +79 -0
  69. package/dist/optimize/types.js +6 -0
  70. package/dist/optimize/verification.d.ts +16 -0
  71. package/dist/optimize/verification.js +165 -0
  72. package/dist/processResources.d.ts +5 -0
  73. package/dist/processResources.js +28 -4
  74. package/dist/processRuntime.js +7 -28
  75. package/dist/processTree.d.ts +47 -0
  76. package/dist/processTree.js +148 -0
  77. package/dist/runContextEnrichment.d.ts +11 -0
  78. package/dist/runContextEnrichment.js +92 -0
  79. package/dist/runtime.d.ts +29 -1
  80. package/dist/runtime.js +94 -16
  81. package/dist/sdk/client.d.ts +152 -0
  82. package/dist/sdk/client.js +396 -0
  83. package/dist/sdk/gitUrl.d.ts +6 -0
  84. package/dist/sdk/gitUrl.js +87 -0
  85. package/dist/sdk/index.d.ts +5 -0
  86. package/dist/sdk/index.js +5 -0
  87. package/dist/serverlessHints.d.ts +9 -6
  88. package/dist/serverlessHints.js +10 -7
  89. package/dist/taskMeter.d.ts +14 -0
  90. package/dist/taskMeter.js +53 -0
  91. package/dist/types.d.ts +35 -0
  92. package/examples/aca-container-gate/Dockerfile +20 -0
  93. package/examples/aca-container-gate/azure-container-app.yaml +27 -0
  94. package/examples/aca-container-gate/gate.env +7 -0
  95. package/examples/aca-container-gate/server.mjs +117 -0
  96. package/examples/express-local-live-smoke.mjs +127 -0
  97. package/examples/extractRunId.mjs +11 -0
  98. package/examples/next-pilot-dry-run.mjs +32 -0
  99. package/examples/serverless-thin-gate.mjs +89 -0
  100. package/fixtures/run-smoke/hello.mjs +4 -0
  101. package/package.json +26 -5
package/dist/init.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Single NetGreener init surface — one product, lifecycle-aware delivery.
3
+ *
4
+ * Prefer ``import '@netgreener/runtime/auto'`` or ``NetGreener.init()``.
5
+ * Does not create a separate Vercel/Lambda product.
6
+ */
7
+ import { getRuntime, } from './runtime.js';
8
+ export const NetGreener = {
9
+ /**
10
+ * Initialize (or return) the process singleton and start metering.
11
+ * Safe to call multiple times — subsequent calls reuse the singleton.
12
+ */
13
+ init(opts = {}) {
14
+ const { runtime: mode, ...rest } = opts;
15
+ const instance = getRuntime({
16
+ ...rest,
17
+ ...(mode ? { runtimeMode: mode } : {}),
18
+ });
19
+ instance.start();
20
+ return instance;
21
+ },
22
+ /**
23
+ * Flush at a serverless invoke boundary (Lambda handler finally, etc.).
24
+ * Fail-open: errors are returned, never thrown to the caller by design
25
+ * of ``flush`` (catch returns UploadResult).
26
+ */
27
+ async flushForInvokeEnd() {
28
+ return getRuntime().flushForInvokeEnd();
29
+ },
30
+ };
31
+ export default NetGreener;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Runtime lifecycle resolution (persistent vs ephemeral).
3
+ *
4
+ * Platform (vercel / lambda / …) and lifecycle are separate concepts.
5
+ * Behavior depends primarily on lifecycle. Detection is best-effort;
6
+ * ``NETGREENER_RUNTIME`` / ``init({ runtime })`` always wins.
7
+ *
8
+ * Does not rewrite the persistent collector pipeline. Ephemeral only
9
+ * changes flush timing and prefers thin export when EXPORT_MODE is unset.
10
+ */
11
+ import { type ServerlessPlatformSignal } from './serverlessHints.js';
12
+ export type RuntimeModePreference = 'auto' | 'persistent' | 'ephemeral';
13
+ export type RuntimeLifecycle = 'persistent' | 'ephemeral';
14
+ export type RuntimePlatform = ServerlessPlatformSignal | 'docker' | 'kubernetes' | 'generic';
15
+ export type RuntimeCapabilities = {
16
+ /** Host CPU sampling (cgroup / host meters). Not claimed on serverless. */
17
+ cpu_sampling: boolean;
18
+ gpu_sampling: boolean;
19
+ /** process.cpuUsage / RSS deltas on instrumented hooks. */
20
+ process_cpu_time: boolean;
21
+ periodic_flush: boolean;
22
+ local_durable_spool: boolean;
23
+ };
24
+ export type ResolvedRuntimeLifecycle = {
25
+ /** Requested preference (auto / override). */
26
+ mode: RuntimeModePreference;
27
+ lifecycle: RuntimeLifecycle;
28
+ platform: RuntimePlatform;
29
+ capabilities: RuntimeCapabilities;
30
+ signals: ServerlessPlatformSignal[];
31
+ notes: string[];
32
+ };
33
+ export type ResolveLifecycleOptions = {
34
+ mode?: RuntimeModePreference;
35
+ env?: NodeJS.ProcessEnv;
36
+ };
37
+ /**
38
+ * Resolve lifecycle + platform metadata.
39
+ *
40
+ * Default ``auto``: serverless host signals → ephemeral; otherwise persistent.
41
+ * Docker / Kubernetes signals alone stay **persistent**.
42
+ */
43
+ export declare function resolveLifecycle(opts?: ResolveLifecycleOptions): ResolvedRuntimeLifecycle;
44
+ /** True when resolved lifecycle is ephemeral. */
45
+ export declare function isEphemeralLifecycle(opts?: ResolveLifecycleOptions): boolean;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Runtime lifecycle resolution (persistent vs ephemeral).
3
+ *
4
+ * Platform (vercel / lambda / …) and lifecycle are separate concepts.
5
+ * Behavior depends primarily on lifecycle. Detection is best-effort;
6
+ * ``NETGREENER_RUNTIME`` / ``init({ runtime })`` always wins.
7
+ *
8
+ * Does not rewrite the persistent collector pipeline. Ephemeral only
9
+ * changes flush timing and prefers thin export when EXPORT_MODE is unset.
10
+ */
11
+ import { detectServerlessPlatformSignals, } from './serverlessHints.js';
12
+ function readModePreference(env, override) {
13
+ if (override === 'auto' || override === 'persistent' || override === 'ephemeral') {
14
+ return override;
15
+ }
16
+ const raw = String(env.NETGREENER_RUNTIME || '')
17
+ .trim()
18
+ .toLowerCase();
19
+ if (raw === 'persistent' || raw === 'ephemeral' || raw === 'auto') {
20
+ return raw;
21
+ }
22
+ return 'auto';
23
+ }
24
+ function detectContainerPlatform(env) {
25
+ if (present(env, 'KUBERNETES_SERVICE_HOST'))
26
+ return 'kubernetes';
27
+ // Azure Container Apps — long-lived revision process (not serverless thin).
28
+ if (present(env, 'CONTAINER_APP_NAME') || present(env, 'CONTAINER_APP_REVISION')) {
29
+ return 'docker';
30
+ }
31
+ // Generic container signal — never means serverless by itself.
32
+ if (env.DOTNET_RUNNING_IN_CONTAINER === 'true' || present(env, 'container')) {
33
+ return 'docker';
34
+ }
35
+ if (present(env, 'DOCKER') || env.container === 'docker')
36
+ return 'docker';
37
+ return null;
38
+ }
39
+ function present(env, key) {
40
+ return Boolean(String(env[key] || '').trim());
41
+ }
42
+ function capabilitiesFor(lifecycle) {
43
+ if (lifecycle === 'ephemeral') {
44
+ return {
45
+ cpu_sampling: false,
46
+ gpu_sampling: false,
47
+ process_cpu_time: true,
48
+ periodic_flush: false,
49
+ local_durable_spool: false,
50
+ };
51
+ }
52
+ return {
53
+ cpu_sampling: false, // host/cgroup still not claimed by default
54
+ gpu_sampling: false,
55
+ process_cpu_time: true,
56
+ periodic_flush: true,
57
+ local_durable_spool: true, // available via opt-in collector; not forced
58
+ };
59
+ }
60
+ /**
61
+ * Resolve lifecycle + platform metadata.
62
+ *
63
+ * Default ``auto``: serverless host signals → ephemeral; otherwise persistent.
64
+ * Docker / Kubernetes signals alone stay **persistent**.
65
+ */
66
+ export function resolveLifecycle(opts = {}) {
67
+ const env = opts.env ?? process.env;
68
+ const mode = readModePreference(env, opts.mode);
69
+ const hint = detectServerlessPlatformSignals(env);
70
+ const containerPlatform = detectContainerPlatform(env);
71
+ const notes = [];
72
+ let lifecycle;
73
+ if (mode === 'ephemeral') {
74
+ lifecycle = 'ephemeral';
75
+ notes.push('runtime mode override: ephemeral');
76
+ }
77
+ else if (mode === 'persistent') {
78
+ lifecycle = 'persistent';
79
+ notes.push('runtime mode override: persistent');
80
+ }
81
+ else if (hint.detected) {
82
+ lifecycle = 'ephemeral';
83
+ notes.push('auto: serverless host signal → ephemeral lifecycle (invoke-end flush; no periodic timer)');
84
+ }
85
+ else {
86
+ lifecycle = 'persistent';
87
+ notes.push('auto: no serverless signal → persistent lifecycle');
88
+ }
89
+ let platform = 'generic';
90
+ if (hint.signals.length > 0) {
91
+ platform = hint.signals[0];
92
+ }
93
+ else if (containerPlatform) {
94
+ platform = containerPlatform;
95
+ notes.push(`container/platform signal: ${containerPlatform} (lifecycle remains ${lifecycle})`);
96
+ }
97
+ if (lifecycle === 'ephemeral') {
98
+ notes.push('ephemeral: prefer NETGREENER_EXPORT_MODE=thin when unset; flush at invoke/request idle boundary');
99
+ }
100
+ return {
101
+ mode,
102
+ lifecycle,
103
+ platform,
104
+ capabilities: capabilitiesFor(lifecycle),
105
+ signals: hint.signals,
106
+ notes,
107
+ };
108
+ }
109
+ /** True when resolved lifecycle is ephemeral. */
110
+ export function isEphemeralLifecycle(opts = {}) {
111
+ return resolveLifecycle(opts).lifecycle === 'ephemeral';
112
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Opt-in managed sibling collector launcher (Python ``process_launcher`` twin).
3
+ *
4
+ * When ``NETGREENER_COLLECTOR_MODE=managed``:
5
+ * 1. Start ``python -m netgreener.collector_server``
6
+ * 2. Point child at ``NETGREENER_EXPORT_MODE=collector`` + endpoint
7
+ * 3. On child exit: terminate collector (drain)
8
+ *
9
+ * Does **not** flip the package default (unset mode → direct).
10
+ * Windows: ``tcp://`` only.
11
+ */
12
+ import { spawn, type ChildProcess } from 'node:child_process';
13
+ export type CollectorMode = 'managed' | 'direct' | null;
14
+ export declare function normalizedCollectorMode(env?: NodeJS.ProcessEnv): CollectorMode;
15
+ export declare function reserveTcpEndpoint(): Promise<string>;
16
+ export type ManagedCollectorHandle = {
17
+ endpoint: string;
18
+ spoolDir: string;
19
+ process: ChildProcess;
20
+ stop: () => Promise<void>;
21
+ };
22
+ export type StartManagedCollectorOptions = {
23
+ env?: NodeJS.ProcessEnv;
24
+ pythonCommand?: string;
25
+ /** Injected spawn for tests. */
26
+ spawnImpl?: typeof spawn;
27
+ /** Skip readiness wait (tests). */
28
+ skipReadyWait?: boolean;
29
+ };
30
+ /**
31
+ * Start managed collector if mode is managed; otherwise return null.
32
+ */
33
+ export declare function startManagedCollector(opts?: StartManagedCollectorOptions): Promise<ManagedCollectorHandle | null>;
34
+ /** Env overlay for a Node child that should export via the managed collector. */
35
+ export declare function childEnvForManagedCollector(base: NodeJS.ProcessEnv, endpoint: string, opts?: {
36
+ keepCredentials?: boolean;
37
+ }): NodeJS.ProcessEnv;
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Opt-in managed sibling collector launcher (Python ``process_launcher`` twin).
3
+ *
4
+ * When ``NETGREENER_COLLECTOR_MODE=managed``:
5
+ * 1. Start ``python -m netgreener.collector_server``
6
+ * 2. Point child at ``NETGREENER_EXPORT_MODE=collector`` + endpoint
7
+ * 3. On child exit: terminate collector (drain)
8
+ *
9
+ * Does **not** flip the package default (unset mode → direct).
10
+ * Windows: ``tcp://`` only.
11
+ */
12
+ import { spawn } from 'node:child_process';
13
+ import { createServer, Socket } from 'node:net';
14
+ import { homedir, tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ export function normalizedCollectorMode(env = process.env) {
17
+ const raw = String(env.NETGREENER_COLLECTOR_MODE || '')
18
+ .trim()
19
+ .toLowerCase();
20
+ if (!raw)
21
+ return null;
22
+ if (raw === 'off' || raw === 'disabled' || raw === 'legacy')
23
+ return 'direct';
24
+ if (raw === 'managed' || raw === 'direct')
25
+ return raw;
26
+ return null;
27
+ }
28
+ export async function reserveTcpEndpoint() {
29
+ return new Promise((resolve, reject) => {
30
+ const server = createServer();
31
+ server.listen(0, '127.0.0.1', () => {
32
+ const addr = server.address();
33
+ if (!addr || typeof addr === 'string') {
34
+ server.close();
35
+ reject(new Error('failed to reserve TCP port'));
36
+ return;
37
+ }
38
+ const endpoint = `tcp://127.0.0.1:${addr.port}`;
39
+ server.close(() => resolve(endpoint));
40
+ });
41
+ server.on('error', reject);
42
+ });
43
+ }
44
+ async function waitForTcp(endpoint, child, timeoutMs = 5000) {
45
+ const m = /^tcp:\/\/([^:]+):(\d+)$/i.exec(endpoint.trim());
46
+ if (!m)
47
+ return;
48
+ const host = m[1];
49
+ const port = Number(m[2]);
50
+ const deadline = Date.now() + timeoutMs;
51
+ while (Date.now() < deadline) {
52
+ if (child.exitCode != null) {
53
+ throw new Error('NetGreener collector exited during startup');
54
+ }
55
+ const ok = await new Promise((resolve) => {
56
+ const sock = new Socket();
57
+ sock.setTimeout(100);
58
+ sock.once('connect', () => {
59
+ sock.destroy();
60
+ resolve(true);
61
+ });
62
+ sock.once('error', () => {
63
+ sock.destroy();
64
+ resolve(false);
65
+ });
66
+ sock.once('timeout', () => {
67
+ sock.destroy();
68
+ resolve(false);
69
+ });
70
+ sock.connect(port, host);
71
+ });
72
+ if (ok)
73
+ return;
74
+ await new Promise((r) => setTimeout(r, 50));
75
+ }
76
+ throw new Error('NetGreener collector did not become ready within 5 seconds');
77
+ }
78
+ /**
79
+ * Start managed collector if mode is managed; otherwise return null.
80
+ */
81
+ export async function startManagedCollector(opts = {}) {
82
+ const env = { ...(opts.env ?? process.env) };
83
+ if (normalizedCollectorMode(env) !== 'managed')
84
+ return null;
85
+ let endpoint = String(env.NETGREENER_COLLECTOR_ENDPOINT || '').trim();
86
+ if (!endpoint) {
87
+ endpoint = await reserveTcpEndpoint();
88
+ }
89
+ if (endpoint.startsWith('unix:') && process.platform === 'win32') {
90
+ throw new Error('Windows managed collector requires tcp:// endpoint');
91
+ }
92
+ const spoolDir = String(env.NETGREENER_SPOOL_DIR || '').trim() ||
93
+ join(homedir() || tmpdir(), '.netgreener', 'collector');
94
+ const python = opts.pythonCommand || process.env.NETGREENER_PYTHON || 'python';
95
+ const spawnImpl = opts.spawnImpl ?? spawn;
96
+ const collectorEnv = {
97
+ ...env,
98
+ NETGREENER_RUNTIME_COLLECTOR: '1',
99
+ NETGREENER_COLLECTOR_ENDPOINT: endpoint,
100
+ NETGREENER_SPOOL_DIR: spoolDir,
101
+ };
102
+ const child = spawnImpl(python, [
103
+ '-m',
104
+ 'netgreener.collector_server',
105
+ '--endpoint',
106
+ endpoint,
107
+ '--spool-dir',
108
+ spoolDir,
109
+ ], {
110
+ env: collectorEnv,
111
+ stdio: ['ignore', 'pipe', 'pipe'],
112
+ windowsHide: true,
113
+ });
114
+ if (!opts.skipReadyWait) {
115
+ try {
116
+ await waitForTcp(endpoint, child);
117
+ }
118
+ catch (err) {
119
+ child.kill('SIGTERM');
120
+ throw err;
121
+ }
122
+ }
123
+ const drainSec = Number(env.NETGREENER_COLLECTOR_DRAIN_SECONDS || '10');
124
+ const drainMs = Number.isFinite(drainSec) && drainSec > 0 ? drainSec * 1000 : 10_000;
125
+ return {
126
+ endpoint,
127
+ spoolDir,
128
+ process: child,
129
+ stop: async () => {
130
+ if (child.exitCode != null)
131
+ return;
132
+ child.kill('SIGTERM');
133
+ await new Promise((resolve) => {
134
+ const t = setTimeout(() => {
135
+ if (child.exitCode == null)
136
+ child.kill('SIGKILL');
137
+ resolve();
138
+ }, drainMs);
139
+ child.once('exit', () => {
140
+ clearTimeout(t);
141
+ resolve();
142
+ });
143
+ });
144
+ },
145
+ };
146
+ }
147
+ /** Env overlay for a Node child that should export via the managed collector. */
148
+ export function childEnvForManagedCollector(base, endpoint, opts) {
149
+ const out = {
150
+ ...base,
151
+ NETGREENER_EXPORT_MODE: 'collector',
152
+ NETGREENER_COLLECTOR_ENDPOINT: endpoint,
153
+ NETGREENER_COLLECTOR_MODE: 'managed',
154
+ };
155
+ const keep = opts?.keepCredentials ||
156
+ String(base.NETGREENER_WORKER_KEEP_CREDENTIALS || '').trim() === '1';
157
+ if (!keep) {
158
+ delete out.NETGREENER_TOKEN;
159
+ delete out.NETGREENER_SERVICE_TOKEN;
160
+ }
161
+ return out;
162
+ }
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * CAP-R6 deployment-mode matrix (Node Runtime production scope).
3
3
  *
4
- * Freezes what we **claim** vs **exercise** vs **exclude**. Does not invent
5
- * Kubernetes/container live evidence. Does not flip export defaults.
4
+ * Freezes what we **claim** vs **exercise** vs **exclude**.
5
+ * Honesty pass 2026-10-06: ACA + serverless gates exist as code/dry-run only —
6
+ * not production claims until live run_id evidence is retained.
7
+ * Does not flip export defaults for persistent apps.
6
8
  */
7
9
  export type DeployModeStatus = 'claimed_and_exercised' | 'documented_degraded' | 'not_claimed' | 'open';
8
10
  export type DeployModeEntry = {
@@ -13,10 +15,12 @@ export type DeployModeEntry = {
13
15
  notes: string;
14
16
  };
15
17
  /**
16
- * Production claim scope for Node Runtime (2026-09-24):
17
- * long-running process / VM-like host with default ``direct`` export.
18
- * Container/K8s/CI/serverless are **not** silently included.
18
+ * Production claim scope (honest): long-running process only.
19
+ * ACA container + serverless thin = gate-ready / pilot until live acceptance.
19
20
  */
20
21
  export declare const NODE_DEPLOYMENT_MATRIX: readonly DeployModeEntry[];
21
22
  export declare function claimedDeployModes(): DeployModeEntry[];
23
+ /**
24
+ * Production scope must claim exactly long_running_process until live gates land.
25
+ */
22
26
  export declare function assertProductionScopeIsExplicit(): boolean;
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * CAP-R6 deployment-mode matrix (Node Runtime production scope).
3
3
  *
4
- * Freezes what we **claim** vs **exercise** vs **exclude**. Does not invent
5
- * Kubernetes/container live evidence. Does not flip export defaults.
4
+ * Freezes what we **claim** vs **exercise** vs **exclude**.
5
+ * Honesty pass 2026-10-06: ACA + serverless gates exist as code/dry-run only —
6
+ * not production claims until live run_id evidence is retained.
7
+ * Does not flip export defaults for persistent apps.
6
8
  */
7
9
  /**
8
- * Production claim scope for Node Runtime (2026-09-24):
9
- * long-running process / VM-like host with default ``direct`` export.
10
- * Container/K8s/CI/serverless are **not** silently included.
10
+ * Production claim scope (honest): long-running process only.
11
+ * ACA container + serverless thin = gate-ready / pilot until live acceptance.
11
12
  */
12
13
  export const NODE_DEPLOYMENT_MATRIX = [
13
14
  {
@@ -21,8 +22,8 @@ export const NODE_DEPLOYMENT_MATRIX = [
21
22
  check_id: 'CHK-R6.container',
22
23
  mode: 'container',
23
24
  status: 'not_claimed',
24
- evidence: 'none retained as production gate',
25
- notes: 'May work identically to process; do not claim until dedicated live gate',
25
+ evidence: 'examples/aca-container-gate + artifacts/aca-container-gate (dry-run / ACA-shaped); no live ACA run_id yet',
26
+ notes: 'Gate-ready for Azure Container Apps only. Do not claim until live upload + dashboard run_id retained. AWS/GCP not gated.',
26
27
  },
27
28
  {
28
29
  check_id: 'CHK-R6.kubernetes',
@@ -42,13 +43,16 @@ export const NODE_DEPLOYMENT_MATRIX = [
42
43
  check_id: 'CHK-R6.serverless-degraded',
43
44
  mode: 'serverless_thin',
44
45
  status: 'documented_degraded',
45
- evidence: 'serverlessHints unit tests; EXPORT_MODE=thin explicit only',
46
- notes: 'Best-effort thin flush; no auto-cutover; not durable collector',
46
+ evidence: 'lifecycle + serverlessHints tests; artifacts/serverless-thin-gate dry-run; Next pilot helpers',
47
+ notes: 'Pilot / degraded until live Vercel (or Lambda) run_id. Not durable spool. Explicit EXPORT_MODE / NETGREENER_RUNTIME=persistent win.',
47
48
  },
48
49
  ];
49
50
  export function claimedDeployModes() {
50
51
  return NODE_DEPLOYMENT_MATRIX.filter((e) => e.status === 'claimed_and_exercised');
51
52
  }
53
+ /**
54
+ * Production scope must claim exactly long_running_process until live gates land.
55
+ */
52
56
  export function assertProductionScopeIsExplicit() {
53
57
  const claimed = claimedDeployModes();
54
58
  if (claimed.length !== 1)
@@ -35,17 +35,17 @@ export const NODE_DIRECT_MISSINGNESS_INVENTORY = [
35
35
  signal_id: 'unit.peak_rss_kb_max',
36
36
  status: 'measured',
37
37
  provenance: MEMORY_SOURCE_PROCESS,
38
- notes: 'process.memoryUsage().rss at sample end (KiB)',
38
+ notes: 'process.memoryUsage().rss (KiB); OS read rate-limited (~50ms) — cached values are prior measured samples, never invented',
39
39
  },
40
40
  {
41
41
  signal_id: 'unit.energy_kwh_carbon_g',
42
42
  status: 'derived_estimate',
43
- notes: 'Emitter-side TDP util estimate (prefers measured CPU when present); cloud policy ownership open',
43
+ notes: 'Emitter-side TDP util estimate (prefers measured CPU when present); carbon via netgreener_default_grid (0.276 kg/kWh, Python twin); GPU/RAM/IO energy still open',
44
44
  },
45
45
  {
46
46
  signal_id: 'collector.process_tree_cgroup',
47
47
  status: 'not_measured',
48
- notes: 'Requires shared MP2 collector sampler + Node launcher — still open',
48
+ notes: 'Opt-in: NETGREENER_COLLECTOR_MODE=managed + collector enrich (`collector_resource_sample_v0` via emitter_pid). Direct emitter still process-only; Windows cgroup = honest unavailable',
49
49
  },
50
50
  {
51
51
  signal_id: 'runtime_health_v0',
package/dist/next.d.ts ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Next.js App Router adapter (Wave 3 pilot).
3
+ *
4
+ * Maps into the same Runtime / observation / export path as Express.
5
+ * Not a Vercel production claim — use persistent Node or pilot wording.
6
+ * Does not change NETGREENER_EXPORT_MODE defaults.
7
+ */
8
+ import { type NetGreenerRuntime, type NetGreenerRuntimeOptions } from './runtime.js';
9
+ import type { UploadResult } from './uploader.js';
10
+ export declare const UNKNOWN_NEXT_ROUTE_TEMPLATE = "<unmatched>";
11
+ /** Minimal Next Request-like shape (App Router / Fetch API). */
12
+ export type NextRequestLike = {
13
+ method?: string;
14
+ url?: string;
15
+ nextUrl?: {
16
+ pathname?: string;
17
+ };
18
+ headers?: Headers | Record<string, unknown>;
19
+ };
20
+ export type NextRouteContext = Record<string, unknown>;
21
+ export type NetGreenerNextOptions = NetGreenerRuntimeOptions & {
22
+ /**
23
+ * Static route template override (e.g. ``/api/intake/[id]``).
24
+ * Prefer this over raw pathnames that may embed customer ids.
25
+ */
26
+ routeTemplate?: string;
27
+ };
28
+ /**
29
+ * Call from ``instrumentation.ts`` ``register()`` to start the Runtime singleton.
30
+ *
31
+ * ```ts
32
+ * export async function register() {
33
+ * const { registerNetGreenerNext } = await import('@netgreener/runtime/next')
34
+ * registerNetGreenerNext()
35
+ * }
36
+ * ```
37
+ */
38
+ export declare function registerNetGreenerNext(opts?: NetGreenerNextOptions): NetGreenerRuntime;
39
+ /**
40
+ * Bounded route template for service_unit attribution.
41
+ * Never use query strings; prefer an explicit ``routeTemplate`` option.
42
+ */
43
+ export declare function nextRouteTemplate(req: NextRequestLike, override?: string): string;
44
+ /**
45
+ * Wrap an App Router route handler (``GET``/``POST``/…) with NetGreener metering.
46
+ *
47
+ * ```ts
48
+ * export const POST = withNetGreenerRoute(async (req) => {
49
+ * return Response.json({ ok: true })
50
+ * }, { routeTemplate: '/api/intake' })
51
+ * ```
52
+ */
53
+ export declare function withNetGreenerRoute<TReq extends NextRequestLike, TArgs extends unknown[], TResult>(handler: (req: TReq, ...args: TArgs) => Promise<TResult> | TResult, opts?: NetGreenerNextOptions): (req: TReq, ...args: TArgs) => Promise<TResult>;
54
+ export declare function getNextRuntime(): NetGreenerRuntime;
55
+ /** Explicit flush helper for instrumentation ``onRequestError`` / custom hooks. */
56
+ export declare function flushNetGreenerNext(kind?: 'manual' | 'shutdown' | 'invoke_end'): Promise<UploadResult | null>;
57
+ /**
58
+ * Schedule a best-effort flush after the response (Vercel ``waitUntil`` when present).
59
+ * Fail-open: never throws into the customer path.
60
+ */
61
+ export declare function scheduleNetGreenerFlush(waitUntil?: (promise: Promise<unknown>) => void): void;