@netgreener/runtime 0.1.8 → 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 (100) hide show
  1. package/TUTORIAL.md +120 -29
  2. package/dist/aggregator.d.ts +12 -2
  3. package/dist/aggregator.js +135 -8
  4. package/dist/analyze/buildResourceFindings.d.ts +4 -0
  5. package/dist/analyze/buildResourceFindings.js +17 -0
  6. package/dist/analyze/cli.d.ts +1 -0
  7. package/dist/analyze/cli.js +22 -1
  8. package/dist/analyze/declaredExternalApis.d.ts +31 -0
  9. package/dist/analyze/declaredExternalApis.js +174 -0
  10. package/dist/analyze/index.d.ts +1 -0
  11. package/dist/analyze/index.js +1 -0
  12. package/dist/auto.d.ts +7 -0
  13. package/dist/auto.js +8 -0
  14. package/dist/bullmq.d.ts +2 -2
  15. package/dist/bullmq.js +28 -58
  16. package/dist/carbonLedger.d.ts +28 -0
  17. package/dist/carbonLedger.js +52 -0
  18. package/dist/cgroupV2.d.ts +44 -0
  19. package/dist/cgroupV2.js +174 -0
  20. package/dist/cli/helpText.d.ts +3 -3
  21. package/dist/cli/helpText.js +42 -35
  22. package/dist/cli/netgreener.d.ts +7 -7
  23. package/dist/cli/netgreener.js +23 -16
  24. package/dist/cli/runCli.d.ts +20 -0
  25. package/dist/cli/runCli.js +249 -0
  26. package/dist/cli/runPreload.d.ts +5 -0
  27. package/dist/cli/runPreload.js +43 -0
  28. package/dist/collectorMetadata.d.ts +1 -1
  29. package/dist/collectorMetadata.js +2 -0
  30. package/dist/config.d.ts +2 -0
  31. package/dist/config.js +6 -2
  32. package/dist/exporter.d.ts +7 -2
  33. package/dist/exporter.js +12 -6
  34. package/dist/express.js +17 -6
  35. package/dist/externalApiMeter.d.ts +43 -1
  36. package/dist/externalApiMeter.js +267 -5
  37. package/dist/fastify.js +17 -6
  38. package/dist/index.d.ts +10 -2
  39. package/dist/index.js +9 -1
  40. package/dist/init.d.ts +30 -0
  41. package/dist/init.js +31 -0
  42. package/dist/lifecycle.d.ts +45 -0
  43. package/dist/lifecycle.js +112 -0
  44. package/dist/managedCollectorLauncher.d.ts +37 -0
  45. package/dist/managedCollectorLauncher.js +162 -0
  46. package/dist/n4/deploymentMatrix.d.ts +9 -5
  47. package/dist/n4/deploymentMatrix.js +13 -9
  48. package/dist/n4/missingnessInventory.js +3 -3
  49. package/dist/next.d.ts +61 -0
  50. package/dist/next.js +195 -0
  51. package/dist/occupancyTracker.d.ts +27 -0
  52. package/dist/occupancyTracker.js +87 -0
  53. package/dist/optimize/apply.d.ts +38 -0
  54. package/dist/optimize/apply.js +173 -0
  55. package/dist/optimize/cli.d.ts +26 -0
  56. package/dist/optimize/cli.js +323 -0
  57. package/dist/optimize/index.d.ts +6 -0
  58. package/dist/optimize/index.js +5 -0
  59. package/dist/optimize/llmApply.d.ts +22 -0
  60. package/dist/optimize/llmApply.js +80 -0
  61. package/dist/optimize/llmSession.d.ts +88 -0
  62. package/dist/optimize/llmSession.js +135 -0
  63. package/dist/optimize/provider.d.ts +17 -0
  64. package/dist/optimize/provider.js +119 -0
  65. package/dist/optimize/safePatches.d.ts +18 -0
  66. package/dist/optimize/safePatches.js +247 -0
  67. package/dist/optimize/types.d.ts +79 -0
  68. package/dist/optimize/types.js +6 -0
  69. package/dist/optimize/verification.d.ts +16 -0
  70. package/dist/optimize/verification.js +165 -0
  71. package/dist/processResources.d.ts +5 -0
  72. package/dist/processResources.js +28 -4
  73. package/dist/processRuntime.js +7 -28
  74. package/dist/processTree.d.ts +47 -0
  75. package/dist/processTree.js +148 -0
  76. package/dist/runContextEnrichment.d.ts +11 -0
  77. package/dist/runContextEnrichment.js +92 -0
  78. package/dist/runtime.d.ts +29 -1
  79. package/dist/runtime.js +94 -16
  80. package/dist/sdk/client.d.ts +152 -0
  81. package/dist/sdk/client.js +396 -0
  82. package/dist/sdk/gitUrl.d.ts +6 -0
  83. package/dist/sdk/gitUrl.js +87 -0
  84. package/dist/sdk/index.d.ts +5 -0
  85. package/dist/sdk/index.js +5 -0
  86. package/dist/serverlessHints.d.ts +9 -6
  87. package/dist/serverlessHints.js +10 -7
  88. package/dist/taskMeter.d.ts +14 -0
  89. package/dist/taskMeter.js +53 -0
  90. package/dist/types.d.ts +35 -0
  91. package/examples/aca-container-gate/Dockerfile +20 -0
  92. package/examples/aca-container-gate/azure-container-app.yaml +27 -0
  93. package/examples/aca-container-gate/gate.env +7 -0
  94. package/examples/aca-container-gate/server.mjs +117 -0
  95. package/examples/express-local-live-smoke.mjs +127 -0
  96. package/examples/extractRunId.mjs +11 -0
  97. package/examples/next-pilot-dry-run.mjs +32 -0
  98. package/examples/serverless-thin-gate.mjs +89 -0
  99. package/fixtures/run-smoke/hello.mjs +4 -0
  100. package/package.json +23 -2
@@ -0,0 +1,323 @@
1
+ /**
2
+ * ``netgreener optimize <projectDir>`` — local OptimizerProvider + VerificationProvider.
3
+ *
4
+ * Default: local proposals (no LLM).
5
+ * ``--llm``: opt-in shared api_server ``POST /optimize/function`` (owner OK 2026-10-02).
6
+ * ``--apply``: only auto_apply_safe local patches (not LLM results).
7
+ * ``--llm --apply-verified``: LLM splice writes gated by VerificationProvider (owner OK).
8
+ * Does not invent measured savings. Does not flip EXPORT_MODE.
9
+ */
10
+ import { accessSync, constants, statSync } from 'node:fs';
11
+ import { resolve } from 'node:path';
12
+ import { buildResourceAnalyzeResultFromPaths } from '../analyze/buildResourceFindings.js';
13
+ import { applySafeProposals, applyVerifiedPatches } from './apply.js';
14
+ import { buildVerifiedPatchesFromLlmSession } from './llmApply.js';
15
+ import { runLlmOptimizeSession } from './llmSession.js';
16
+ import { createLocalJsTsOptimizerProvider } from './provider.js';
17
+ import { createLocalJsTsVerificationProvider } from './verification.js';
18
+ export function formatOptimizeHelp() {
19
+ return `Usage: netgreener optimize <projectDir> [options]
20
+
21
+ Local JS/TS OptimizerProvider + VerificationProvider (default):
22
+ 1. Run Analyze (upload=never) for resource_finding_v1 candidates
23
+ 2. Emit optimize_result_v0 proposals (guidance; some may include safe patches)
24
+ 3. Optional --apply: write only auto_apply_safe patches after verify gates
25
+
26
+ LLM session (opt-in, same api_server brain as Python/VSCE):
27
+ --llm Call POST /optimize/function for top candidates
28
+ Requires NETGREENER_TOKEN + numeric --project-id
29
+ --llm --apply-verified
30
+ After LLM session: splice reviewed code, VerificationProvider
31
+ before+after, rollback on fail (NOT the same as --apply)
32
+
33
+ Does NOT:
34
+ • invent measured energy/cost savings
35
+ • flip NETGREENER_EXPORT_MODE
36
+ • apply LLM patches via --apply (use --apply-verified with --llm)
37
+
38
+ Options:
39
+ --project-id <id> Stamp project_id (default: local; required numeric for --llm)
40
+ --paths a,b Explicit repo-relative paths (skip auto-walk)
41
+ --apply Apply auto_apply_safe patches (verify before+after; rollback on fail)
42
+ --apply-verified With --llm only: apply LLM splices via VerificationProvider
43
+ --verify Run VerificationProvider only (no proposals apply)
44
+ --llm Shared LLM optimize session (api_server)
45
+ --max-llm <n> Max findings for --llm (default 5, max 20)
46
+ --skip-test Do not run npm test during verification
47
+ --quiet Suppress stderr status lines
48
+ -h, --help Show this help
49
+
50
+ Env (--llm):
51
+ NETGREENER_TOKEN / NETGREENER_SERVICE_TOKEN
52
+ NETGREENER_API_URL (optional)
53
+ NETGREENER_PROJECT_ID (optional alias for --project-id)
54
+
55
+ Examples:
56
+ netgreener optimize ./fixtures/analyze-sample
57
+ netgreener optimize ./my-app --verify
58
+ netgreener optimize ./my-app --apply --skip-test
59
+ netgreener optimize ./my-app --llm --project-id 97
60
+ netgreener optimize ./my-app --llm --apply-verified --project-id 97 --skip-test
61
+
62
+ See OPTIMIZE_STUB.md for MP4 boundaries.
63
+ `;
64
+ }
65
+ export function parseOptimizeArgs(argv) {
66
+ const flags = {
67
+ projectDir: '',
68
+ projectId: 'local',
69
+ paths: null,
70
+ apply: false,
71
+ applyVerified: false,
72
+ verifyOnly: false,
73
+ skipTest: false,
74
+ quiet: false,
75
+ help: false,
76
+ llm: false,
77
+ maxLlm: 5,
78
+ };
79
+ const positionals = [];
80
+ for (let i = 0; i < argv.length; i += 1) {
81
+ const arg = argv[i] ?? '';
82
+ if (arg === '-h' || arg === '--help') {
83
+ flags.help = true;
84
+ continue;
85
+ }
86
+ if (arg === '--quiet') {
87
+ flags.quiet = true;
88
+ continue;
89
+ }
90
+ if (arg === '--apply') {
91
+ flags.apply = true;
92
+ continue;
93
+ }
94
+ if (arg === '--apply-verified') {
95
+ flags.applyVerified = true;
96
+ continue;
97
+ }
98
+ if (arg === '--verify') {
99
+ flags.verifyOnly = true;
100
+ continue;
101
+ }
102
+ if (arg === '--llm') {
103
+ flags.llm = true;
104
+ continue;
105
+ }
106
+ if (arg === '--skip-test') {
107
+ flags.skipTest = true;
108
+ continue;
109
+ }
110
+ if (arg === '--max-llm') {
111
+ const n = Number(argv[++i] || '5');
112
+ flags.maxLlm = Number.isFinite(n) ? n : 5;
113
+ continue;
114
+ }
115
+ if (arg.startsWith('--max-llm=')) {
116
+ const n = Number(arg.slice('--max-llm='.length) || '5');
117
+ flags.maxLlm = Number.isFinite(n) ? n : 5;
118
+ continue;
119
+ }
120
+ if (arg === '--project-id') {
121
+ flags.projectId = String(argv[++i] || 'local');
122
+ continue;
123
+ }
124
+ if (arg.startsWith('--project-id=')) {
125
+ flags.projectId = arg.slice('--project-id='.length) || 'local';
126
+ continue;
127
+ }
128
+ if (arg === '--paths') {
129
+ const raw = String(argv[++i] || '');
130
+ flags.paths = raw
131
+ .split(',')
132
+ .map((p) => p.trim())
133
+ .filter(Boolean);
134
+ continue;
135
+ }
136
+ if (arg.startsWith('--paths=')) {
137
+ flags.paths = arg
138
+ .slice('--paths='.length)
139
+ .split(',')
140
+ .map((p) => p.trim())
141
+ .filter(Boolean);
142
+ continue;
143
+ }
144
+ if (arg.startsWith('-')) {
145
+ throw new Error(`Unknown optimize option: ${arg}`);
146
+ }
147
+ positionals.push(arg);
148
+ }
149
+ flags.projectDir = positionals[0] || '';
150
+ return flags;
151
+ }
152
+ export function runOptimizeCli(argv) {
153
+ let flags;
154
+ try {
155
+ flags = parseOptimizeArgs(argv);
156
+ }
157
+ catch (err) {
158
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
159
+ process.stderr.write(formatOptimizeHelp());
160
+ return 2;
161
+ }
162
+ if (flags.help || !flags.projectDir) {
163
+ process.stdout.write(formatOptimizeHelp());
164
+ return flags.help ? 0 : 2;
165
+ }
166
+ if (flags.llm && flags.apply) {
167
+ process.stderr.write('netgreener optimize: --llm cannot be combined with --apply ' +
168
+ '(local safe rules only). Use --llm --apply-verified for VerificationProvider LLM writes.\n');
169
+ return 2;
170
+ }
171
+ if (flags.applyVerified && !flags.llm) {
172
+ process.stderr.write('netgreener optimize: --apply-verified requires --llm ' +
173
+ '(for local safe rules use --apply).\n');
174
+ return 2;
175
+ }
176
+ const projectDir = resolve(flags.projectDir);
177
+ try {
178
+ accessSync(projectDir, constants.R_OK);
179
+ if (!statSync(projectDir).isDirectory()) {
180
+ process.stderr.write(`Not a directory: ${projectDir}\n`);
181
+ return 2;
182
+ }
183
+ }
184
+ catch {
185
+ process.stderr.write(`Cannot read projectDir: ${projectDir}\n`);
186
+ return 2;
187
+ }
188
+ if (flags.verifyOnly) {
189
+ if (!flags.quiet) {
190
+ process.stderr.write(`netgreener optimize --verify: ${projectDir}\n`);
191
+ }
192
+ const verification = createLocalJsTsVerificationProvider().verify(projectDir, {
193
+ skipTest: flags.skipTest,
194
+ skipBuild: true,
195
+ });
196
+ process.stdout.write(`${JSON.stringify(verification, null, 2)}\n`);
197
+ return verification.ok ? 0 : 1;
198
+ }
199
+ if (flags.llm) {
200
+ return runLlmOptimizeCli(projectDir, flags);
201
+ }
202
+ if (!flags.quiet) {
203
+ process.stderr.write(`netgreener optimize: Analyze + local proposals for ${projectDir} (upload=never)…\n`);
204
+ }
205
+ const analyze = buildResourceAnalyzeResultFromPaths(projectDir, flags.paths, { projectId: flags.projectId });
206
+ const provider = createLocalJsTsOptimizerProvider();
207
+ const result = provider.proposeFromFindings(analyze.findings, {
208
+ projectId: flags.projectId,
209
+ projectDir,
210
+ });
211
+ if (flags.apply) {
212
+ if (!flags.quiet) {
213
+ process.stderr.write(`netgreener optimize --apply: ${result.stats.auto_apply_safe} safe patch(es); verifying…\n`);
214
+ }
215
+ const { apply, verification_before, verification_after } = applySafeProposals(projectDir, result.proposals, { skipTest: flags.skipTest, skipBuild: true });
216
+ result.verification = verification_after || verification_before;
217
+ result.notes = [
218
+ ...result.notes,
219
+ apply.rolled_back
220
+ ? 'Apply rolled back after verification_after failure.'
221
+ : apply.applied.length
222
+ ? `Applied ${apply.applied.length} safe patch(es).`
223
+ : 'No safe patches applied.',
224
+ ];
225
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
226
+ if (!flags.quiet) {
227
+ process.stderr.write(`netgreener optimize --apply: applied=${apply.applied.length} ` +
228
+ `rolled_back=${apply.rolled_back} verify_ok=${result.verification?.ok}\n`);
229
+ }
230
+ if (!apply.verification_before_ok)
231
+ return 1;
232
+ if (apply.rolled_back)
233
+ return 1;
234
+ return 0;
235
+ }
236
+ result.verification = createLocalJsTsVerificationProvider().verify(projectDir, {
237
+ skipTest: true,
238
+ skipBuild: true,
239
+ });
240
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
241
+ if (!flags.quiet) {
242
+ process.stderr.write(`netgreener optimize: ${result.stats.proposals} proposal(s), ` +
243
+ `${result.stats.auto_apply_safe} auto_apply_safe — no patches applied ` +
244
+ `(use --apply).\n`);
245
+ }
246
+ return 0;
247
+ }
248
+ async function runLlmOptimizeCli(projectDir, flags) {
249
+ const token = (process.env.NETGREENER_TOKEN ||
250
+ process.env.NETGREENER_SERVICE_TOKEN ||
251
+ '').trim();
252
+ if (!token) {
253
+ process.stderr.write('netgreener optimize --llm: set NETGREENER_TOKEN (or NETGREENER_SERVICE_TOKEN).\n');
254
+ return 2;
255
+ }
256
+ const projectIdRaw = flags.projectId !== 'local'
257
+ ? flags.projectId
258
+ : (process.env.NETGREENER_PROJECT_ID || '').trim();
259
+ const projectId = Number(projectIdRaw);
260
+ if (!Number.isSafeInteger(projectId) || projectId <= 0) {
261
+ process.stderr.write('netgreener optimize --llm: require numeric --project-id or NETGREENER_PROJECT_ID.\n');
262
+ return 2;
263
+ }
264
+ if (!flags.quiet) {
265
+ process.stderr.write(`netgreener optimize --llm: Analyze + api_server /optimize/function ` +
266
+ `(project=${projectId}, max=${flags.maxLlm})…\n`);
267
+ }
268
+ const analyze = buildResourceAnalyzeResultFromPaths(projectDir, flags.paths, {
269
+ projectId: String(projectId),
270
+ });
271
+ const apiUrl = (process.env.NETGREENER_API_URL || '').trim() || undefined;
272
+ const session = await runLlmOptimizeSession({
273
+ projectDir,
274
+ projectId,
275
+ findings: analyze.findings,
276
+ token,
277
+ apiUrl,
278
+ maxFindings: flags.maxLlm,
279
+ byok: {
280
+ provider: process.env.NETGREENER_LLM_PROVIDER || undefined,
281
+ key: process.env.NETGREENER_LLM_KEY || undefined,
282
+ endpoint: process.env.NETGREENER_LLM_ENDPOINT || undefined,
283
+ model: process.env.NETGREENER_LLM_MODEL || undefined,
284
+ },
285
+ });
286
+ if (!flags.applyVerified) {
287
+ process.stdout.write(`${JSON.stringify(session, null, 2)}\n`);
288
+ const okCount = session.items.filter((i) => i.ok).length;
289
+ if (!flags.quiet) {
290
+ process.stderr.write(`netgreener optimize --llm: ${okCount}/${session.items.length} ok ` +
291
+ `(of ${session.candidates_considered} candidates). Review JSON; ` +
292
+ `or re-run with --apply-verified.\n`);
293
+ }
294
+ return session.items.length === 0 || okCount > 0 ? 0 : 1;
295
+ }
296
+ if (!flags.quiet) {
297
+ process.stderr.write('netgreener optimize --llm --apply-verified: splicing reviewed items; verifying…\n');
298
+ }
299
+ const { patches, skipped } = buildVerifiedPatchesFromLlmSession(projectDir, session);
300
+ const { apply, verification_before, verification_after } = applyVerifiedPatches(projectDir, patches, { skipTest: flags.skipTest, skipBuild: true, preSkipped: skipped });
301
+ const out = {
302
+ schema: 'optimize_llm_apply_verified_v0',
303
+ session,
304
+ apply,
305
+ verification_before,
306
+ verification_after,
307
+ notes: [
308
+ 'LLM splices applied only when review_passed/apply_recommended allow.',
309
+ 'VerificationProvider before+after; rollback on fail.',
310
+ 'Not auto_apply_safe. No measured savings claimed.',
311
+ ],
312
+ };
313
+ process.stdout.write(`${JSON.stringify(out, null, 2)}\n`);
314
+ if (!flags.quiet) {
315
+ process.stderr.write(`netgreener optimize --llm --apply-verified: applied=${apply.applied.length} ` +
316
+ `skipped=${apply.skipped.length} rolled_back=${apply.rolled_back}\n`);
317
+ }
318
+ if (!apply.verification_before_ok)
319
+ return 1;
320
+ if (apply.rolled_back)
321
+ return 1;
322
+ return apply.applied.length > 0 || patches.length === 0 ? 0 : 1;
323
+ }
@@ -0,0 +1,6 @@
1
+ export type { OptimizeActionKind, OptimizeApplyResultV0, OptimizePatchV0, OptimizeProposalV0, OptimizeResultV0, VerificationResultV0, VerifyGateId, VerifyGateOutcome, } from './types.js';
2
+ export { createLocalJsTsOptimizerProvider, type OptimizerProvider, } from './provider.js';
3
+ export { createLocalJsTsVerificationProvider, type VerificationProvider, } from './verification.js';
4
+ export { tryBuildSafePatch, trySafePatchRulesOnSource, type SafePatchMatch } from './safePatches.js';
5
+ export { applySafeProposals } from './apply.js';
6
+ export { formatOptimizeHelp, parseOptimizeArgs, runOptimizeCli, type OptimizeCliFlags, } from './cli.js';
@@ -0,0 +1,5 @@
1
+ export { createLocalJsTsOptimizerProvider, } from './provider.js';
2
+ export { createLocalJsTsVerificationProvider, } from './verification.js';
3
+ export { tryBuildSafePatch, trySafePatchRulesOnSource } from './safePatches.js';
4
+ export { applySafeProposals } from './apply.js';
5
+ export { formatOptimizeHelp, parseOptimizeArgs, runOptimizeCli, } from './cli.js';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Build VerificationProvider-gated writes from an LLM optimize session.
3
+ *
4
+ * Owner OK 2026-10-02 (LLM) + apply-verified OK (chat).
5
+ * Does NOT mark patches auto_apply_safe. Does not invent savings.
6
+ */
7
+ import type { VerifiedPatchWrite } from './apply.js';
8
+ import type { LlmOptimizeSessionItem, LlmOptimizeSessionV0 } from './llmSession.js';
9
+ export declare function spliceSnippetIntoFile(fullText: string, lineStart: number, lineEnd: number, newSnippet: string): string;
10
+ export declare function llmItemEligibleForVerifiedApply(item: LlmOptimizeSessionItem): {
11
+ ok: true;
12
+ } | {
13
+ ok: false;
14
+ reason: string;
15
+ };
16
+ export declare function buildVerifiedPatchesFromLlmSession(projectDir: string, session: LlmOptimizeSessionV0): {
17
+ patches: VerifiedPatchWrite[];
18
+ skipped: Array<{
19
+ proposal_id: string;
20
+ reason: string;
21
+ }>;
22
+ };
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Build VerificationProvider-gated writes from an LLM optimize session.
3
+ *
4
+ * Owner OK 2026-10-02 (LLM) + apply-verified OK (chat).
5
+ * Does NOT mark patches auto_apply_safe. Does not invent savings.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ export function spliceSnippetIntoFile(fullText, lineStart, lineEnd, newSnippet) {
10
+ const lines = fullText.split(/\r?\n/);
11
+ const start = Math.max(1, Math.floor(lineStart));
12
+ const end = Math.max(start, Math.floor(lineEnd));
13
+ const before = lines.slice(0, start - 1);
14
+ const after = lines.slice(end);
15
+ const mid = newSnippet.replace(/\r\n/g, '\n').split('\n');
16
+ // Preserve trailing newline style of original when file ended with \n.
17
+ const joined = [...before, ...mid, ...after].join('\n');
18
+ if (fullText.endsWith('\n') && !joined.endsWith('\n'))
19
+ return `${joined}\n`;
20
+ return joined;
21
+ }
22
+ export function llmItemEligibleForVerifiedApply(item) {
23
+ if (!item.ok || !item.result) {
24
+ return { ok: false, reason: item.error || 'llm call failed' };
25
+ }
26
+ const r = item.result;
27
+ if (r.no_change_needed) {
28
+ return { ok: false, reason: 'no_change_needed' };
29
+ }
30
+ if (r.review_passed === false) {
31
+ return { ok: false, reason: 'review_passed=false' };
32
+ }
33
+ if (r.apply_recommended === false) {
34
+ return { ok: false, reason: 'apply_recommended=false' };
35
+ }
36
+ if (!String(r.optimized_code || '').trim()) {
37
+ return { ok: false, reason: 'empty optimized_code' };
38
+ }
39
+ if (!item.line_start || !item.line_end) {
40
+ return { ok: false, reason: 'missing snippet line range' };
41
+ }
42
+ return { ok: true };
43
+ }
44
+ export function buildVerifiedPatchesFromLlmSession(projectDir, session) {
45
+ const patches = [];
46
+ const skipped = [];
47
+ // Last eligible write wins per path.
48
+ const byPath = new Map();
49
+ for (const item of session.items) {
50
+ const proposalId = `llm:${item.finding_id}`;
51
+ const gate = llmItemEligibleForVerifiedApply(item);
52
+ if (!gate.ok) {
53
+ skipped.push({ proposal_id: proposalId, reason: gate.reason });
54
+ continue;
55
+ }
56
+ const rel = item.file_path.replace(/\\/g, '/');
57
+ let full;
58
+ try {
59
+ full = readFileSync(join(projectDir, rel), 'utf8');
60
+ }
61
+ catch {
62
+ skipped.push({ proposal_id: proposalId, reason: 'file unreadable' });
63
+ continue;
64
+ }
65
+ const newContent = spliceSnippetIntoFile(full, item.line_start, item.line_end, item.result.optimized_code);
66
+ if (newContent === full) {
67
+ skipped.push({ proposal_id: proposalId, reason: 'splice produced no change' });
68
+ continue;
69
+ }
70
+ byPath.set(rel, {
71
+ proposal_id: proposalId,
72
+ path: rel,
73
+ new_content: newContent,
74
+ rule_id: 'llm_optimize_function',
75
+ });
76
+ }
77
+ for (const p of byPath.values())
78
+ patches.push(p);
79
+ return { patches, skipped };
80
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Opt-in LLM optimize via shared api_server ``POST /optimize/function``.
3
+ *
4
+ * Owner OK 2026-10-02. Default ``netgreener optimize`` stays local (no LLM).
5
+ * ``--llm`` calls the same brain as Python/VSCE — does not invent savings,
6
+ * does not flip EXPORT_MODE. Opt-in ``--apply-verified`` writes via
7
+ * VerificationProvider (see llmApply.ts) — never via local ``--apply``.
8
+ */
9
+ import type { ResourceFindingCandidateV1 } from '../analyze/resourceFindingCandidate.js';
10
+ export type OptimizeLlmRequest = {
11
+ project_id: number;
12
+ file_path: string;
13
+ function_code: string;
14
+ language?: string;
15
+ issue_type?: string;
16
+ severity?: string;
17
+ description?: string;
18
+ focus_line?: number;
19
+ line_start?: number;
20
+ finding_id?: number;
21
+ force?: boolean;
22
+ user_llm_provider?: string;
23
+ user_llm_key?: string;
24
+ user_llm_endpoint?: string;
25
+ user_llm_model?: string;
26
+ };
27
+ export type OptimizeLlmResult = {
28
+ optimized_code: string;
29
+ explanation: string;
30
+ energy_note: string;
31
+ confidence: string;
32
+ model: string;
33
+ no_change_needed?: boolean;
34
+ review_passed?: boolean;
35
+ review_notes?: string;
36
+ apply_recommended?: boolean;
37
+ patch?: string | null;
38
+ };
39
+ export type LlmOptimizeSessionItem = {
40
+ finding_id: string;
41
+ mechanism_id: string;
42
+ file_path: string;
43
+ focus_line: number;
44
+ /** 1-based inclusive snippet range used for /optimize/function (for verified apply). */
45
+ line_start?: number;
46
+ line_end?: number;
47
+ ok: boolean;
48
+ error?: string;
49
+ result?: OptimizeLlmResult;
50
+ };
51
+ export type LlmOptimizeSessionV0 = {
52
+ schema: 'optimize_llm_session_v0';
53
+ project_id: number;
54
+ project_dir: string;
55
+ candidates_considered: number;
56
+ items: LlmOptimizeSessionItem[];
57
+ notes: string[];
58
+ };
59
+ export declare function extractSnippetFromFinding(projectDir: string, finding: ResourceFindingCandidateV1, opts?: {
60
+ padLines?: number;
61
+ }): {
62
+ path: string;
63
+ code: string;
64
+ focusLine: number;
65
+ lineStart: number;
66
+ lineEnd: number;
67
+ } | null;
68
+ export type RunLlmOptimizeSessionOptions = {
69
+ projectDir: string;
70
+ projectId: number;
71
+ findings: ResourceFindingCandidateV1[];
72
+ token: string;
73
+ apiUrl?: string;
74
+ maxFindings?: number;
75
+ fetchImpl?: typeof fetch;
76
+ /** Optional BYOK — same fields as OptimizeFunctionRequest. */
77
+ byok?: {
78
+ provider?: string;
79
+ key?: string;
80
+ endpoint?: string;
81
+ model?: string;
82
+ };
83
+ };
84
+ /**
85
+ * Call api_server /optimize/function for up to N local Node candidates.
86
+ * Never writes files. Never claims measured savings.
87
+ */
88
+ export declare function runLlmOptimizeSession(opts: RunLlmOptimizeSessionOptions): Promise<LlmOptimizeSessionV0>;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Opt-in LLM optimize via shared api_server ``POST /optimize/function``.
3
+ *
4
+ * Owner OK 2026-10-02. Default ``netgreener optimize`` stays local (no LLM).
5
+ * ``--llm`` calls the same brain as Python/VSCE — does not invent savings,
6
+ * does not flip EXPORT_MODE. Opt-in ``--apply-verified`` writes via
7
+ * VerificationProvider (see llmApply.ts) — never via local ``--apply``.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { NetGreenerClient, ApiError } from '../sdk/client.js';
12
+ const MAX_SNIPPET_CHARS = 24_000;
13
+ const DEFAULT_MAX_FINDINGS = 5;
14
+ export function extractSnippetFromFinding(projectDir, finding, opts) {
15
+ const loc = finding.scope?.source_locations?.[0];
16
+ if (!loc?.path || !loc.start_line)
17
+ return null;
18
+ const abs = join(projectDir, loc.path);
19
+ let text;
20
+ try {
21
+ text = readFileSync(abs, 'utf8');
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ const lines = text.split(/\r?\n/);
27
+ const pad = opts?.padLines ?? 2;
28
+ const start = Math.max(1, loc.start_line - pad);
29
+ const end = Math.min(lines.length, Math.max(loc.end_line || loc.start_line, loc.start_line) + pad);
30
+ const code = lines.slice(start - 1, end).join('\n');
31
+ if (!code.trim())
32
+ return null;
33
+ const clipped = code.length > MAX_SNIPPET_CHARS
34
+ ? `${code.slice(0, MAX_SNIPPET_CHARS)}\n/* …truncated… */`
35
+ : code;
36
+ return {
37
+ path: loc.path.replace(/\\/g, '/'),
38
+ code: clipped,
39
+ focusLine: loc.start_line,
40
+ lineStart: start,
41
+ lineEnd: end,
42
+ };
43
+ }
44
+ /**
45
+ * Call api_server /optimize/function for up to N local Node candidates.
46
+ * Never writes files. Never claims measured savings.
47
+ */
48
+ export async function runLlmOptimizeSession(opts) {
49
+ const max = Math.max(1, Math.min(opts.maxFindings ?? DEFAULT_MAX_FINDINGS, 20));
50
+ const client = new NetGreenerClient({
51
+ token: opts.token,
52
+ baseUrl: opts.apiUrl,
53
+ fetchImpl: opts.fetchImpl,
54
+ });
55
+ const items = [];
56
+ const notes = [
57
+ 'LLM optimize uses shared api_server POST /optimize/function (same brain as Python/VSCE).',
58
+ 'No measured energy/cost savings claimed.',
59
+ 'Default: review-only JSON. Opt-in write: --llm --apply-verified (VerificationProvider).',
60
+ 'Default netgreener optimize (without --llm) remains local deterministic proposals only.',
61
+ ];
62
+ const batch = opts.findings.slice(0, max);
63
+ for (const finding of batch) {
64
+ const snippet = extractSnippetFromFinding(opts.projectDir, finding);
65
+ const loc = finding.scope?.source_locations?.[0];
66
+ const filePath = loc?.path || finding.scope?.id || 'unknown';
67
+ if (!snippet) {
68
+ items.push({
69
+ finding_id: finding.finding_id,
70
+ mechanism_id: finding.mechanism_id,
71
+ file_path: filePath,
72
+ focus_line: loc?.start_line || 0,
73
+ ok: false,
74
+ error: 'Could not read source snippet',
75
+ });
76
+ continue;
77
+ }
78
+ try {
79
+ const result = (await client.optimizeFunction({
80
+ project_id: opts.projectId,
81
+ file_path: snippet.path,
82
+ function_code: snippet.code,
83
+ language: finding.scope.language === 'typescript' ? 'typescript' : 'javascript',
84
+ issue_type: finding.mechanism_id,
85
+ description: finding.title,
86
+ focus_line: snippet.focusLine,
87
+ line_start: snippet.lineStart,
88
+ force: true,
89
+ ...(opts.byok?.provider
90
+ ? {
91
+ user_llm_provider: opts.byok.provider,
92
+ user_llm_key: opts.byok.key,
93
+ user_llm_endpoint: opts.byok.endpoint,
94
+ user_llm_model: opts.byok.model,
95
+ }
96
+ : {}),
97
+ }));
98
+ items.push({
99
+ finding_id: finding.finding_id,
100
+ mechanism_id: finding.mechanism_id,
101
+ file_path: snippet.path,
102
+ focus_line: snippet.focusLine,
103
+ line_start: snippet.lineStart,
104
+ line_end: snippet.lineEnd,
105
+ ok: true,
106
+ result,
107
+ });
108
+ }
109
+ catch (err) {
110
+ const msg = err instanceof ApiError
111
+ ? `HTTP ${err.statusCode}: ${err.detail}`
112
+ : err instanceof Error
113
+ ? err.message
114
+ : String(err);
115
+ items.push({
116
+ finding_id: finding.finding_id,
117
+ mechanism_id: finding.mechanism_id,
118
+ file_path: snippet.path,
119
+ focus_line: snippet.focusLine,
120
+ line_start: snippet.lineStart,
121
+ line_end: snippet.lineEnd,
122
+ ok: false,
123
+ error: msg,
124
+ });
125
+ }
126
+ }
127
+ return {
128
+ schema: 'optimize_llm_session_v0',
129
+ project_id: opts.projectId,
130
+ project_dir: opts.projectDir,
131
+ candidates_considered: opts.findings.length,
132
+ items,
133
+ notes,
134
+ };
135
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Local JS/TS OptimizerProvider — proposals + optional deterministic safe patches.
3
+ *
4
+ * Authority: OPTIMIZE_STUB.md / MULTI_LANGUAGE_PLATFORM_PLAN MP4.
5
+ * Explicit non-goals: LLM /optimize/function, silent patches without VerificationProvider.
6
+ */
7
+ import type { ResourceFindingCandidateV1 } from '../analyze/resourceFindingCandidate.js';
8
+ import type { OptimizeResultV0 } from './types.js';
9
+ export type OptimizerProvider = {
10
+ readonly id: string;
11
+ readonly version: string;
12
+ proposeFromFindings(findings: ResourceFindingCandidateV1[], opts: {
13
+ projectId: string;
14
+ projectDir: string;
15
+ }): OptimizeResultV0;
16
+ };
17
+ export declare function createLocalJsTsOptimizerProvider(): OptimizerProvider;