@netgreener/runtime 0.1.8 → 0.1.10

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 (114) hide show
  1. package/CHANGELOG.md +12 -0
  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 +51 -2
  37. package/dist/externalApiMeter.js +379 -26
  38. package/dist/fastify.js +17 -6
  39. package/dist/index.d.ts +12 -2
  40. package/dist/index.js +11 -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/mcpToolMeter.d.ts +101 -0
  48. package/dist/mcpToolMeter.js +496 -0
  49. package/dist/n4/deploymentMatrix.d.ts +9 -5
  50. package/dist/n4/deploymentMatrix.js +13 -9
  51. package/dist/n4/missingnessInventory.js +3 -3
  52. package/dist/next.d.ts +89 -0
  53. package/dist/next.js +328 -0
  54. package/dist/nextConfig.d.ts +34 -0
  55. package/dist/nextConfig.js +73 -0
  56. package/dist/nextEntryTransform.d.ts +9 -0
  57. package/dist/nextEntryTransform.js +181 -0
  58. package/dist/occupancyTracker.d.ts +27 -0
  59. package/dist/occupancyTracker.js +87 -0
  60. package/dist/optimize/apply.d.ts +38 -0
  61. package/dist/optimize/apply.js +173 -0
  62. package/dist/optimize/cli.d.ts +26 -0
  63. package/dist/optimize/cli.js +323 -0
  64. package/dist/optimize/index.d.ts +6 -0
  65. package/dist/optimize/index.js +5 -0
  66. package/dist/optimize/llmApply.d.ts +22 -0
  67. package/dist/optimize/llmApply.js +80 -0
  68. package/dist/optimize/llmSession.d.ts +88 -0
  69. package/dist/optimize/llmSession.js +135 -0
  70. package/dist/optimize/provider.d.ts +17 -0
  71. package/dist/optimize/provider.js +119 -0
  72. package/dist/optimize/safePatches.d.ts +18 -0
  73. package/dist/optimize/safePatches.js +247 -0
  74. package/dist/optimize/types.d.ts +79 -0
  75. package/dist/optimize/types.js +6 -0
  76. package/dist/optimize/verification.d.ts +16 -0
  77. package/dist/optimize/verification.js +165 -0
  78. package/dist/processResources.d.ts +5 -0
  79. package/dist/processResources.js +28 -4
  80. package/dist/processRuntime.js +7 -28
  81. package/dist/processTree.d.ts +47 -0
  82. package/dist/processTree.js +148 -0
  83. package/dist/runContextEnrichment.d.ts +11 -0
  84. package/dist/runContextEnrichment.js +92 -0
  85. package/dist/runtime.d.ts +36 -1
  86. package/dist/runtime.js +140 -17
  87. package/dist/sdk/client.d.ts +152 -0
  88. package/dist/sdk/client.js +396 -0
  89. package/dist/sdk/gitUrl.d.ts +6 -0
  90. package/dist/sdk/gitUrl.js +87 -0
  91. package/dist/sdk/index.d.ts +5 -0
  92. package/dist/sdk/index.js +5 -0
  93. package/dist/serverlessHints.d.ts +9 -6
  94. package/dist/serverlessHints.js +10 -7
  95. package/dist/taskMeter.d.ts +14 -0
  96. package/dist/taskMeter.js +53 -0
  97. package/dist/types.d.ts +43 -0
  98. package/examples/aca-container-gate/Dockerfile +20 -0
  99. package/examples/aca-container-gate/azure-container-app.yaml +27 -0
  100. package/examples/aca-container-gate/gate.env +7 -0
  101. package/examples/aca-container-gate/server.mjs +117 -0
  102. package/examples/azure-functions-gate/.funcignore +6 -0
  103. package/examples/azure-functions-gate/README.md +25 -0
  104. package/examples/azure-functions-gate/host.json +15 -0
  105. package/examples/azure-functions-gate/package-lock.json +161 -0
  106. package/examples/azure-functions-gate/package.json +14 -0
  107. package/examples/azure-functions-gate/src/functions/health.js +27 -0
  108. package/examples/express-local-live-smoke.mjs +127 -0
  109. package/examples/extractRunId.mjs +11 -0
  110. package/examples/next-pilot-dry-run.mjs +32 -0
  111. package/examples/serverless-thin-gate.mjs +89 -0
  112. package/fixtures/run-smoke/hello.mjs +4 -0
  113. package/loaders/next-entry-loader.cjs +14 -0
  114. package/package.json +25 -2
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Deterministic safe patch rules for Node Optimize.
3
+ *
4
+ * Only exact, local transforms — no LLM, no api_server /optimize/*.
5
+ */
6
+ import { readFileSync, existsSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ function patchOf(relPath, new_content, rule_id, summary, reason) {
9
+ return {
10
+ patch: {
11
+ schema: 'optimize_patch_v0',
12
+ path: relPath,
13
+ new_content,
14
+ rule_id,
15
+ summary,
16
+ },
17
+ reason,
18
+ };
19
+ }
20
+ /**
21
+ * Promise.all(arr.map(x => fetch(x))) and async variants → sequential awaits.
22
+ * Also matches leading ``return`` / ``await``.
23
+ */
24
+ function tryPromiseAllFetchMap(source, relPath) {
25
+ const re = /(return\s+|await\s+)?Promise\.all\(\s*(\w+)\.map\(\s*(?:async\s*)?\(\s*(\w+)\s*\)\s*=>\s*fetch\(\s*\3\s*\)\s*\)\s*\)/;
26
+ const m = source.match(re);
27
+ if (!m)
28
+ return null;
29
+ const prefix = (m[1] || '').trim();
30
+ const arr = m[2];
31
+ const item = m[3];
32
+ let replacement;
33
+ if (prefix === 'await') {
34
+ replacement =
35
+ `await (async () => {\n` +
36
+ ` const __ng_out: Response[] = []\n` +
37
+ ` for (const ${item} of ${arr}) {\n` +
38
+ ` __ng_out.push(await fetch(${item}))\n` +
39
+ ` }\n` +
40
+ ` return __ng_out\n` +
41
+ ` })()`;
42
+ }
43
+ else {
44
+ // return … or bare expression used as return body
45
+ replacement =
46
+ `const __ng_out: Response[] = []\n` +
47
+ ` for (const ${item} of ${arr}) {\n` +
48
+ ` __ng_out.push(await fetch(${item}))\n` +
49
+ ` }\n` +
50
+ ` return __ng_out`;
51
+ }
52
+ const new_content = source.replace(re, replacement);
53
+ if (new_content === source)
54
+ return null;
55
+ return patchOf(relPath, new_content, 'promise_all_fetch_map_to_sequential', 'Replace unbounded Promise.all(fetch map) with sequential awaits (no new deps).', 'unbounded_parallelism / external_api_overconsumption safe rewrite');
56
+ }
57
+ /** Hoist ``new RegExp(...)`` out of for-of when args ignore the loop variable. */
58
+ function tryHoistRegExpInForLoop(source, relPath) {
59
+ const re = /for\s*\(\s*const\s+(\w+)\s+of\s+(\w+)\s*\)\s*\{\s*\r?\n(\s*)const\s+(\w+)\s*=\s*new\s+RegExp\(([^)]+)\)\s*\r?\n/;
60
+ const m = source.match(re);
61
+ if (!m)
62
+ return null;
63
+ const loopVar = m[1];
64
+ const indent = m[3];
65
+ const reVar = m[4];
66
+ const reArgs = m[5];
67
+ if (new RegExp(`\\b${loopVar}\\b`).test(reArgs))
68
+ return null;
69
+ const forOpen = `for (const ${loopVar} of ${m[2]}) {\n`;
70
+ const new_content = source.replace(re, `${indent}const ${reVar} = new RegExp(${reArgs})\n${forOpen}`);
71
+ if (new_content === source)
72
+ return null;
73
+ return patchOf(relPath, new_content, 'hoist_regexp_out_of_loop', 'Hoist RegExp compile out of for-loop (repeated_work).', 'repeated_work safe rewrite');
74
+ }
75
+ /**
76
+ * Retry loop with fetch: insert capped exponential backoff before attempts > 0.
77
+ * Only when the body does not already contain setTimeout/backoff.
78
+ */
79
+ function tryRetryFetchAddBackoff(source, relPath) {
80
+ if (/setTimeout|backoff|AbortSignal\.timeout/i.test(source))
81
+ return null;
82
+ const re = /for\s*\(\s*let\s+(\w+)\s*=\s*0\s*;\s*\1\s*<\s*(\d+)\s*;\s*\1\+\+\s*\)\s*\{\r?\n(\s*)const\s+(\w+)\s*=\s*await\s+fetch\(/;
83
+ const m = source.match(re);
84
+ if (!m || m.index == null)
85
+ return null;
86
+ const attempt = m[1];
87
+ const limit = m[2];
88
+ const indent = m[3];
89
+ const resVar = m[4];
90
+ const head = `for (let ${attempt} = 0; ${attempt} < ${limit}; ${attempt}++) {\n`;
91
+ const injected = head +
92
+ `${indent}if (${attempt} > 0) {\n` +
93
+ `${indent} await new Promise((r) => setTimeout(r, Math.min(1000, 50 * 2 ** (${attempt} - 1))))\n` +
94
+ `${indent}}\n` +
95
+ `${indent}const ${resVar} = await fetch(`;
96
+ const new_content = source.slice(0, m.index) + injected + source.slice(m.index + m[0].length);
97
+ if (new_content === source)
98
+ return null;
99
+ return patchOf(relPath, new_content, 'retry_fetch_add_backoff', 'Add capped exponential backoff between fetch retries (retry_amplification).', 'retry_amplification safe rewrite');
100
+ }
101
+ /**
102
+ * Nested ``arr.find(x => x.id === outer.id)`` → Set.has (O(n) → O(1) membership).
103
+ */
104
+ function tryNestedFindToSet(source, relPath) {
105
+ // for (const a of left) { ... right.find((x) => x.id === a.id)
106
+ const findRe = /(\w+)\.find\(\s*\(\s*(\w+)\s*\)\s*=>\s*\2\.id\s*===\s*(\w+)\.id\s*\)/;
107
+ const m = source.match(findRe);
108
+ if (!m)
109
+ return null;
110
+ const arr = m[1];
111
+ const outer = m[3];
112
+ // Require an enclosing for-of over ``outer``.
113
+ const forRe = new RegExp(`for\\s*\\(\\s*const\\s+${outer}\\s+of\\s+(\\w+)\\s*\\)`);
114
+ if (!forRe.test(source))
115
+ return null;
116
+ const setName = `__ng_${arr}_ids`;
117
+ if (source.includes(setName))
118
+ return null;
119
+ // Insert Set before the first for that uses outer, and replace find calls.
120
+ const forMatch = source.match(forRe);
121
+ if (!forMatch || forMatch.index == null)
122
+ return null;
123
+ const insertAt = forMatch.index;
124
+ const insert = `const ${setName} = new Set(${arr}.map((x) => x.id))\n`;
125
+ let new_content = source.slice(0, insertAt) + insert + source.slice(insertAt);
126
+ new_content = new_content.replace(new RegExp(`${arr}\\.find\\(\\s*\\(\\s*(\\w+)\\s*\\)\\s*=>\\s*\\1\\.id\\s*===\\s*${outer}\\.id\\s*\\)`, 'g'), `${setName}.has(${outer}.id)`);
127
+ if (new_content === source)
128
+ return null;
129
+ return patchOf(relPath, new_content, 'nested_array_find_to_set', 'Replace nested array.find(id) with Set.has for membership checks.', 'per_item_instead_of_batch / repeated_work safe rewrite');
130
+ }
131
+ /**
132
+ * ``JSON.parse(readFileSync(path, 'utf8'))`` stays one-shot — no change.
133
+ * ``while (!check()) { setTimeout(() => {}, N) }`` busy-poll → await sleep (async).
134
+ * Only rewrite when the function is already ``async``.
135
+ */
136
+ function tryBusyPollToAwaitSleep(source, relPath) {
137
+ if (!/\basync\s+function\b/.test(source) && !/\basync\s*\(/.test(source)) {
138
+ // Only safe if we can await — require async in file near the while.
139
+ // Conservative: require `export async function` or `async function` in source.
140
+ return null;
141
+ }
142
+ const re = /while\s*\(\s*!\s*(\w+)\(\)\s*\)\s*\{\s*\r?\n\s*setTimeout\(\s*\(\)\s*=>\s*\{\s*\}\s*,\s*(\d+)\s*\)\s*\r?\n\s*\}/;
143
+ const m = source.match(re);
144
+ if (!m)
145
+ return null;
146
+ // Without making the enclosing function async, await is invalid.
147
+ // Only apply when the match sits inside an async function (heuristic: previous 200 chars).
148
+ const idx = source.search(re);
149
+ if (idx < 0)
150
+ return null;
151
+ const window = source.slice(Math.max(0, idx - 200), idx);
152
+ if (!/\basync\s+function\b|\basync\s*\(/.test(window))
153
+ return null;
154
+ const check = m[1];
155
+ const ms = m[2];
156
+ const replacement = `while (!${check}()) {\n` +
157
+ ` await new Promise((r) => setTimeout(r, ${ms}))\n` +
158
+ ` }`;
159
+ const new_content = source.replace(re, replacement);
160
+ if (new_content === source)
161
+ return null;
162
+ return patchOf(relPath, new_content, 'busy_poll_settimeout_to_await_sleep', 'Replace fire-and-forget setTimeout busy-poll with awaited sleep (polling_or_idle_work).', 'polling_or_idle_work safe rewrite');
163
+ }
164
+ /**
165
+ * ``for (const x of xs) { out.push(await fetch(x)) }`` already sequential — no op.
166
+ * Cap ``Promise.all(xs.map(...))`` with non-fetch body stays guidance-only.
167
+ *
168
+ * ``readFileSync`` in loop: cache identical path reads within the function.
169
+ */
170
+ function tryCacheReadFileSyncInLoop(source, relPath) {
171
+ // for (const p of paths) { ... readFileSync(p, 'utf8')
172
+ const re = /for\s*\(\s*const\s+(\w+)\s+of\s+(\w+)\s*\)\s*\{([\s\S]*?)readFileSync\(\s*\1\s*,\s*['"]utf-?8['"]\s*\)/;
173
+ const m = source.match(re);
174
+ if (!m)
175
+ return null;
176
+ if (/__ng_read_cache/.test(source))
177
+ return null;
178
+ const item = m[1];
179
+ const arr = m[2];
180
+ // Insert cache + helper read before the for-loop; replace readFileSync(item, 'utf8').
181
+ const forRe = new RegExp(`for\\s*\\(\\s*const\\s+${item}\\s+of\\s+${arr}\\s*\\)`);
182
+ const forMatch = source.match(forRe);
183
+ if (!forMatch || forMatch.index == null)
184
+ return null;
185
+ const insert = `const __ng_read_cache = new Map<string, string>()\n` +
186
+ ` const __ng_read = (p: string) => {\n` +
187
+ ` let v = __ng_read_cache.get(p)\n` +
188
+ ` if (v === undefined) {\n` +
189
+ ` v = readFileSync(p, 'utf8')\n` +
190
+ ` __ng_read_cache.set(p, v)\n` +
191
+ ` }\n` +
192
+ ` return v\n` +
193
+ ` }\n `;
194
+ let new_content = source.slice(0, forMatch.index) + insert + source.slice(forMatch.index);
195
+ new_content = new_content.replace(new RegExp(`readFileSync\\(\\s*${item}\\s*,\\s*['"]utf-?8['"]\\s*\\)`, 'g'), `__ng_read(${item})`);
196
+ if (new_content === source)
197
+ return null;
198
+ return patchOf(relPath, new_content, 'cache_readfilesync_in_loop', 'Cache readFileSync(utf8) results across loop iterations (repeated_work / io).', 'repeated_work / memory_retention safe rewrite');
199
+ }
200
+ const MECHANISM_RULES = {
201
+ unbounded_parallelism: [tryPromiseAllFetchMap],
202
+ external_api_overconsumption: [tryPromiseAllFetchMap, tryRetryFetchAddBackoff],
203
+ repeated_work: [
204
+ tryHoistRegExpInForLoop,
205
+ tryNestedFindToSet,
206
+ tryCacheReadFileSyncInLoop,
207
+ ],
208
+ retry_amplification: [tryRetryFetchAddBackoff],
209
+ per_item_instead_of_batch: [tryNestedFindToSet],
210
+ polling_or_idle_work: [tryBusyPollToAwaitSleep],
211
+ memory_retention_or_materialization: [tryCacheReadFileSyncInLoop],
212
+ };
213
+ /** Exported for unit tests — apply rules without a finding. */
214
+ export function trySafePatchRulesOnSource(source, relPath, mechanismId) {
215
+ const rules = MECHANISM_RULES[mechanismId] || [];
216
+ for (const rule of rules) {
217
+ const hit = rule(source, relPath);
218
+ if (hit)
219
+ return hit;
220
+ }
221
+ return null;
222
+ }
223
+ /**
224
+ * Attempt a deterministic safe patch for one admitted finding.
225
+ * Returns null when no rule matches (proposal stays guidance-only).
226
+ */
227
+ export function tryBuildSafePatch(finding, projectDir) {
228
+ const loc = finding.scope.source_locations[0];
229
+ if (!loc?.path)
230
+ return null;
231
+ const rel = loc.path.replace(/\\/g, '/');
232
+ if (/(^|\/)(node_modules|dist|build|out|\.git|vendor)(\/|$)/i.test(rel) ||
233
+ rel.includes('..')) {
234
+ return null;
235
+ }
236
+ const abs = join(projectDir, rel);
237
+ if (!existsSync(abs))
238
+ return null;
239
+ let source;
240
+ try {
241
+ source = readFileSync(abs, 'utf8');
242
+ }
243
+ catch {
244
+ return null;
245
+ }
246
+ return trySafePatchRulesOnSource(source, rel, finding.mechanism_id);
247
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Optimize / verify IR for local JS/TS MP4 providers.
3
+ *
4
+ * Does not call api_server /optimize/*, does not invent measured savings.
5
+ */
6
+ import type { ResourceFindingCandidateV1 } from '../analyze/resourceFindingCandidate.js';
7
+ export type OptimizeActionKind = 'review_and_limit' | 'batch_or_debounce' | 'cache_or_memoize' | 'stream_or_bound' | 'backoff_or_cap' | 'idle_or_event' | 'manual_review';
8
+ export type OptimizePatchV0 = {
9
+ schema: 'optimize_patch_v0';
10
+ path: string;
11
+ /** Full file content after the safe transform (not a unified diff). */
12
+ new_content: string;
13
+ /** Short description of the mechanical rule applied. */
14
+ rule_id: string;
15
+ summary: string;
16
+ };
17
+ export type OptimizeProposalV0 = {
18
+ schema: 'optimize_proposal_v0';
19
+ proposal_id: string;
20
+ finding_id: string;
21
+ mechanism_id: string;
22
+ primary_domain: string;
23
+ title: string;
24
+ action_kind: OptimizeActionKind;
25
+ guidance: string;
26
+ scope: ResourceFindingCandidateV1['scope'];
27
+ /** True only when a deterministic safe patch rule matched. */
28
+ auto_apply_safe: boolean;
29
+ patch: OptimizePatchV0 | null;
30
+ };
31
+ export type OptimizeResultV0 = {
32
+ schema: 'optimize_result_v0';
33
+ contract_status: 'optimizer_provider_local_v0';
34
+ project_id: string;
35
+ project_dir: string;
36
+ findings_considered: number;
37
+ proposals: OptimizeProposalV0[];
38
+ stats: {
39
+ proposals: number;
40
+ auto_apply_safe: number;
41
+ by_mechanism: Record<string, number>;
42
+ by_action_kind: Record<string, number>;
43
+ };
44
+ notes: string[];
45
+ verification?: VerificationResultV0;
46
+ apply?: OptimizeApplyResultV0;
47
+ };
48
+ export type VerifyGateId = 'syntax' | 'typecheck' | 'test' | 'build';
49
+ export type VerifyGateOutcome = {
50
+ gate: VerifyGateId;
51
+ status: 'pass' | 'fail' | 'skipped' | 'not_applicable';
52
+ detail: string;
53
+ command?: string;
54
+ duration_ms?: number;
55
+ };
56
+ export type VerificationResultV0 = {
57
+ schema: 'verification_result_v0';
58
+ provider_id: string;
59
+ provider_version: string;
60
+ project_dir: string;
61
+ ok: boolean;
62
+ gates: VerifyGateOutcome[];
63
+ notes: string[];
64
+ };
65
+ export type OptimizeApplyResultV0 = {
66
+ schema: 'optimize_apply_result_v0';
67
+ applied: Array<{
68
+ proposal_id: string;
69
+ path: string;
70
+ rule_id: string;
71
+ }>;
72
+ skipped: Array<{
73
+ proposal_id: string;
74
+ reason: string;
75
+ }>;
76
+ rolled_back: boolean;
77
+ verification_before_ok: boolean;
78
+ verification_after_ok: boolean | null;
79
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Optimize / verify IR for local JS/TS MP4 providers.
3
+ *
4
+ * Does not call api_server /optimize/*, does not invent measured savings.
5
+ */
6
+ export {};
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Local JS/TS VerificationProvider — formatter/typecheck/test gates (MP4).
3
+ *
4
+ * Never invents energy/cost savings. Missing scripts → not_applicable (not fail).
5
+ */
6
+ import type { VerificationResultV0 } from './types.js';
7
+ export type VerificationProvider = {
8
+ readonly id: string;
9
+ readonly version: string;
10
+ verify(projectDir: string, opts?: {
11
+ paths?: string[];
12
+ skipTest?: boolean;
13
+ skipBuild?: boolean;
14
+ }): VerificationResultV0;
15
+ };
16
+ export declare function createLocalJsTsVerificationProvider(): VerificationProvider;
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Local JS/TS VerificationProvider — formatter/typecheck/test gates (MP4).
3
+ *
4
+ * Never invents energy/cost savings. Missing scripts → not_applicable (not fail).
5
+ */
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ function readPackageJson(projectDir) {
10
+ const p = join(projectDir, 'package.json');
11
+ if (!existsSync(p))
12
+ return null;
13
+ try {
14
+ return JSON.parse(readFileSync(p, 'utf8'));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ function runCmd(command, args, cwd) {
21
+ const started = Date.now();
22
+ const r = spawnSync(command, args, {
23
+ cwd,
24
+ encoding: 'utf8',
25
+ shell: false,
26
+ env: process.env,
27
+ });
28
+ const duration_ms = Date.now() - started;
29
+ const detail = ((r.stderr || '') + (r.stdout || '')).trim().slice(0, 2000);
30
+ return { status: r.status ?? 1, detail: detail || `exit ${r.status ?? 1}`, duration_ms };
31
+ }
32
+ function syntaxGate(projectDir, paths) {
33
+ const targets = (paths || []).filter((p) => /\.(m?js|cjs)$/i.test(p));
34
+ if (targets.length === 0) {
35
+ // TS-only / no JS touch — syntax gate N/A (typecheck covers when present).
36
+ return {
37
+ gate: 'syntax',
38
+ status: 'not_applicable',
39
+ detail: 'No .js/.mjs/.cjs paths to syntax-check',
40
+ };
41
+ }
42
+ for (const rel of targets) {
43
+ const abs = join(projectDir, rel);
44
+ if (!existsSync(abs)) {
45
+ return {
46
+ gate: 'syntax',
47
+ status: 'fail',
48
+ detail: `Missing file: ${rel}`,
49
+ command: `node --check ${rel}`,
50
+ };
51
+ }
52
+ const r = runCmd(process.execPath, ['--check', abs], projectDir);
53
+ if (r.status !== 0) {
54
+ return {
55
+ gate: 'syntax',
56
+ status: 'fail',
57
+ detail: `${rel}: ${r.detail}`,
58
+ command: `node --check ${rel}`,
59
+ duration_ms: r.duration_ms,
60
+ };
61
+ }
62
+ }
63
+ return {
64
+ gate: 'syntax',
65
+ status: 'pass',
66
+ detail: `node --check ok (${targets.length} file(s))`,
67
+ command: 'node --check <paths>',
68
+ };
69
+ }
70
+ function scriptGate(gate, projectDir, pkg, scriptNames, skip) {
71
+ if (skip) {
72
+ return { gate, status: 'skipped', detail: 'Skipped by flag' };
73
+ }
74
+ if (!pkg?.scripts) {
75
+ return {
76
+ gate,
77
+ status: 'not_applicable',
78
+ detail: 'No package.json scripts',
79
+ };
80
+ }
81
+ const name = scriptNames.find((n) => typeof pkg.scripts?.[n] === 'string');
82
+ if (!name) {
83
+ return {
84
+ gate,
85
+ status: 'not_applicable',
86
+ detail: `No ${scriptNames.join('/')} script`,
87
+ };
88
+ }
89
+ const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
90
+ const r = runCmd(npmCmd, ['run', name, '--silent'], projectDir);
91
+ return {
92
+ gate,
93
+ status: r.status === 0 ? 'pass' : 'fail',
94
+ detail: r.detail || `npm run ${name}`,
95
+ command: `npm run ${name}`,
96
+ duration_ms: r.duration_ms,
97
+ };
98
+ }
99
+ /**
100
+ * Prefer package.json typecheck; else `tsc --noEmit` when tsconfig exists and tsc is resolvable.
101
+ */
102
+ function typecheckGate(projectDir, pkg) {
103
+ const fromScript = scriptGate('typecheck', projectDir, pkg, [
104
+ 'typecheck',
105
+ 'type-check',
106
+ 'tsc',
107
+ ]);
108
+ if (fromScript.status !== 'not_applicable')
109
+ return fromScript;
110
+ const tsconfig = existsSync(join(projectDir, 'tsconfig.json'));
111
+ if (!tsconfig) {
112
+ return {
113
+ gate: 'typecheck',
114
+ status: 'not_applicable',
115
+ detail: 'No typecheck script and no tsconfig.json',
116
+ };
117
+ }
118
+ const tscLocal = join(projectDir, 'node_modules', 'typescript', 'bin', 'tsc');
119
+ const tscCmd = existsSync(tscLocal) ? process.execPath : null;
120
+ if (tscCmd) {
121
+ const r = runCmd(tscCmd, [tscLocal, '--noEmit', '-p', 'tsconfig.json'], projectDir);
122
+ return {
123
+ gate: 'typecheck',
124
+ status: r.status === 0 ? 'pass' : 'fail',
125
+ detail: r.detail,
126
+ command: 'node node_modules/typescript/bin/tsc --noEmit',
127
+ duration_ms: r.duration_ms,
128
+ };
129
+ }
130
+ return {
131
+ gate: 'typecheck',
132
+ status: 'not_applicable',
133
+ detail: 'tsconfig.json present but local typescript/tsc not installed',
134
+ };
135
+ }
136
+ export function createLocalJsTsVerificationProvider() {
137
+ return {
138
+ id: 'local_js_ts_verification_v0',
139
+ version: '0.1.0',
140
+ verify(projectDir, opts = {}) {
141
+ const pkg = readPackageJson(projectDir);
142
+ const gates = [
143
+ syntaxGate(projectDir, opts.paths),
144
+ typecheckGate(projectDir, pkg),
145
+ scriptGate('test', projectDir, pkg, ['test'], opts.skipTest),
146
+ scriptGate('build', projectDir, pkg, ['build'], opts.skipBuild ?? true),
147
+ ];
148
+ const hardFail = gates.some((g) => g.status === 'fail');
149
+ const notes = [
150
+ 'VerificationProvider (local JS/TS) — no measured savings claimed.',
151
+ 'fail fails the gate; not_applicable/skipped do not.',
152
+ 'Default: skip build (opt-in later); test runs when npm script exists.',
153
+ ];
154
+ return {
155
+ schema: 'verification_result_v0',
156
+ provider_id: 'local_js_ts_verification_v0',
157
+ provider_version: '0.1.0',
158
+ project_dir: projectDir,
159
+ ok: !hardFail,
160
+ gates,
161
+ notes,
162
+ };
163
+ },
164
+ };
165
+ }
@@ -4,6 +4,9 @@
4
4
  * Mirrors Python ASGI middleware: ``time.process_time()`` + ``psutil`` RSS.
5
5
  * Uses Node ``process.cpuUsage`` / ``process.memoryUsage().rss`` only —
6
6
  * never invents cgroup or process-tree values.
7
+ *
8
+ * RSS OS reads are rate-limited (still measured, never fabricated). Peak RSS
9
+ * aggregation stays honest: a cached sample is a real prior ``memoryUsage().rss``.
7
10
  */
8
11
  export declare const CPU_SOURCE_PROCESS = "node_process_cpu_usage";
9
12
  export declare const MEMORY_SOURCE_PROCESS = "node_process_memory_rss";
@@ -26,3 +29,5 @@ export declare function beginProcessResourceSample(): ProcessResourceMark;
26
29
  export declare function endProcessResourceSample(mark: ProcessResourceMark): ProcessResourceSample;
27
30
  /** Point-in-time RSS (KiB) when no interval mark is available. */
28
31
  export declare function currentRssKb(): number;
32
+ /** Test helper — clear RSS cache. */
33
+ export declare function _resetRssSampleCacheForTests(): void;
@@ -4,13 +4,34 @@
4
4
  * Mirrors Python ASGI middleware: ``time.process_time()`` + ``psutil`` RSS.
5
5
  * Uses Node ``process.cpuUsage`` / ``process.memoryUsage().rss`` only —
6
6
  * never invents cgroup or process-tree values.
7
+ *
8
+ * RSS OS reads are rate-limited (still measured, never fabricated). Peak RSS
9
+ * aggregation stays honest: a cached sample is a real prior ``memoryUsage().rss``.
7
10
  */
8
11
  export const CPU_SOURCE_PROCESS = 'node_process_cpu_usage';
9
12
  export const MEMORY_SOURCE_PROCESS = 'node_process_memory_rss';
13
+ /** Min gap between ``memoryUsage()`` RSS reads (ms). Override via env for tests. */
14
+ const RSS_MIN_INTERVAL_MS = Number(process.env.NETGREENER_RSS_SAMPLE_INTERVAL_MS || 50);
15
+ let lastRssKb = 0;
16
+ let lastRssAtMs = 0;
10
17
  /** Start a CPU interval (call at request/task entry). */
11
18
  export function beginProcessResourceSample() {
12
19
  return { cpuStart: process.cpuUsage() };
13
20
  }
21
+ function readRssKb(force = false) {
22
+ const now = performance.now();
23
+ if (!force &&
24
+ lastRssAtMs > 0 &&
25
+ now - lastRssAtMs < RSS_MIN_INTERVAL_MS &&
26
+ lastRssKb > 0) {
27
+ return lastRssKb;
28
+ }
29
+ const rssKb = Math.round(process.memoryUsage().rss / 1024);
30
+ const safe = Number.isFinite(rssKb) && rssKb >= 0 ? rssKb : 0;
31
+ lastRssKb = safe;
32
+ lastRssAtMs = now;
33
+ return safe;
34
+ }
14
35
  /**
15
36
  * End a CPU interval and read current RSS.
16
37
  * ``cpuUsage(previous)`` returns user+system microseconds since ``previous``.
@@ -18,14 +39,17 @@ export function beginProcessResourceSample() {
18
39
  export function endProcessResourceSample(mark) {
19
40
  const delta = process.cpuUsage(mark.cpuStart);
20
41
  const cpuTimeMs = (delta.user + delta.system) / 1000;
21
- const rssKb = Math.round(process.memoryUsage().rss / 1024);
22
42
  return {
23
43
  cpuTimeMs: Number.isFinite(cpuTimeMs) && cpuTimeMs >= 0 ? cpuTimeMs : 0,
24
- rssKb: Number.isFinite(rssKb) && rssKb >= 0 ? rssKb : 0,
44
+ rssKb: readRssKb(false),
25
45
  };
26
46
  }
27
47
  /** Point-in-time RSS (KiB) when no interval mark is available. */
28
48
  export function currentRssKb() {
29
- const rssKb = Math.round(process.memoryUsage().rss / 1024);
30
- return Number.isFinite(rssKb) && rssKb >= 0 ? rssKb : 0;
49
+ return readRssKb(true);
50
+ }
51
+ /** Test helper — clear RSS cache. */
52
+ export function _resetRssSampleCacheForTests() {
53
+ lastRssKb = 0;
54
+ lastRssAtMs = 0;
31
55
  }
@@ -6,7 +6,7 @@
6
6
  import { getRuntime, } from './runtime.js';
7
7
  import { normalizeTenantId, runWithTenantContext, setTenantContext, } from './tenantContext.js';
8
8
  import { runWithRequestAttribution } from './requestContext.js';
9
- import { beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
9
+ import { recordMeteredTask } from './taskMeter.js';
10
10
  let signalsInstalled = false;
11
11
  /**
12
12
  * Enable NetGreener runtime for a long-lived Node process (cron worker, script).
@@ -19,7 +19,7 @@ export function startProcessRuntime(opts = {}) {
19
19
  ...opts,
20
20
  });
21
21
  runtime.start();
22
- if (!signalsInstalled) {
22
+ if (!signalsInstalled && runtime.lifecycle === 'persistent') {
23
23
  signalsInstalled = true;
24
24
  const shutdown = () => {
25
25
  void runtime.shutdown();
@@ -45,32 +45,11 @@ export async function runWithProcessTenant(tenantId, fn, opts) {
45
45
  ...(opts?.label ? { tenantLabel: opts.label.slice(0, 128) } : {}),
46
46
  };
47
47
  const serviceUnit = opts?.serviceUnit || 'task:process';
48
- const started = performance.now();
49
- const resourceMark = beginProcessResourceSample();
50
- let error = false;
51
- const run = async () => {
52
- try {
53
- return await fn();
54
- }
55
- catch (err) {
56
- error = true;
57
- throw err;
58
- }
59
- finally {
60
- if (runtime.enabled) {
61
- const resources = endProcessResourceSample(resourceMark);
62
- runtime.recordTask({
63
- serviceUnit,
64
- durationMs: performance.now() - started,
65
- error,
66
- tenantId: normalized,
67
- cpuTimeMs: resources.cpuTimeMs,
68
- peakRssKb: resources.rssKb,
69
- });
70
- }
71
- }
72
- };
73
- return runWithTenantContext(ctx, () => runWithRequestAttribution({ serviceUnit }, () => run()));
48
+ return runWithTenantContext(ctx, () => runWithRequestAttribution({ serviceUnit }, () => recordMeteredTask(runtime, {
49
+ serviceUnit,
50
+ tenantId: normalized,
51
+ fn,
52
+ })));
74
53
  }
75
54
  /**
76
55
  * Convenience: set tenant for the rest of the current async chain (enterWith).