@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.
- package/CHANGELOG.md +12 -0
- package/TUTORIAL.md +120 -29
- package/dist/aggregator.d.ts +12 -2
- package/dist/aggregator.js +135 -8
- package/dist/analyze/buildResourceFindings.d.ts +4 -0
- package/dist/analyze/buildResourceFindings.js +17 -0
- package/dist/analyze/cli.d.ts +1 -0
- package/dist/analyze/cli.js +22 -1
- package/dist/analyze/declaredExternalApis.d.ts +31 -0
- package/dist/analyze/declaredExternalApis.js +174 -0
- package/dist/analyze/index.d.ts +1 -0
- package/dist/analyze/index.js +1 -0
- package/dist/auto.d.ts +7 -0
- package/dist/auto.js +8 -0
- package/dist/bullmq.d.ts +2 -2
- package/dist/bullmq.js +28 -58
- package/dist/carbonLedger.d.ts +28 -0
- package/dist/carbonLedger.js +52 -0
- package/dist/cgroupV2.d.ts +44 -0
- package/dist/cgroupV2.js +174 -0
- package/dist/cli/helpText.d.ts +3 -3
- package/dist/cli/helpText.js +42 -35
- package/dist/cli/netgreener.d.ts +7 -7
- package/dist/cli/netgreener.js +23 -16
- package/dist/cli/runCli.d.ts +20 -0
- package/dist/cli/runCli.js +249 -0
- package/dist/cli/runPreload.d.ts +5 -0
- package/dist/cli/runPreload.js +43 -0
- package/dist/collectorMetadata.d.ts +1 -1
- package/dist/collectorMetadata.js +2 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +6 -2
- package/dist/exporter.d.ts +7 -2
- package/dist/exporter.js +12 -6
- package/dist/express.js +17 -6
- package/dist/externalApiMeter.d.ts +51 -2
- package/dist/externalApiMeter.js +379 -26
- package/dist/fastify.js +17 -6
- package/dist/index.d.ts +12 -2
- package/dist/index.js +11 -1
- package/dist/init.d.ts +30 -0
- package/dist/init.js +31 -0
- package/dist/lifecycle.d.ts +45 -0
- package/dist/lifecycle.js +112 -0
- package/dist/managedCollectorLauncher.d.ts +37 -0
- package/dist/managedCollectorLauncher.js +162 -0
- package/dist/mcpToolMeter.d.ts +101 -0
- package/dist/mcpToolMeter.js +496 -0
- package/dist/n4/deploymentMatrix.d.ts +9 -5
- package/dist/n4/deploymentMatrix.js +13 -9
- package/dist/n4/missingnessInventory.js +3 -3
- package/dist/next.d.ts +89 -0
- package/dist/next.js +328 -0
- package/dist/nextConfig.d.ts +34 -0
- package/dist/nextConfig.js +73 -0
- package/dist/nextEntryTransform.d.ts +9 -0
- package/dist/nextEntryTransform.js +181 -0
- package/dist/occupancyTracker.d.ts +27 -0
- package/dist/occupancyTracker.js +87 -0
- package/dist/optimize/apply.d.ts +38 -0
- package/dist/optimize/apply.js +173 -0
- package/dist/optimize/cli.d.ts +26 -0
- package/dist/optimize/cli.js +323 -0
- package/dist/optimize/index.d.ts +6 -0
- package/dist/optimize/index.js +5 -0
- package/dist/optimize/llmApply.d.ts +22 -0
- package/dist/optimize/llmApply.js +80 -0
- package/dist/optimize/llmSession.d.ts +88 -0
- package/dist/optimize/llmSession.js +135 -0
- package/dist/optimize/provider.d.ts +17 -0
- package/dist/optimize/provider.js +119 -0
- package/dist/optimize/safePatches.d.ts +18 -0
- package/dist/optimize/safePatches.js +247 -0
- package/dist/optimize/types.d.ts +79 -0
- package/dist/optimize/types.js +6 -0
- package/dist/optimize/verification.d.ts +16 -0
- package/dist/optimize/verification.js +165 -0
- package/dist/processResources.d.ts +5 -0
- package/dist/processResources.js +28 -4
- package/dist/processRuntime.js +7 -28
- package/dist/processTree.d.ts +47 -0
- package/dist/processTree.js +148 -0
- package/dist/runContextEnrichment.d.ts +11 -0
- package/dist/runContextEnrichment.js +92 -0
- package/dist/runtime.d.ts +36 -1
- package/dist/runtime.js +140 -17
- package/dist/sdk/client.d.ts +152 -0
- package/dist/sdk/client.js +396 -0
- package/dist/sdk/gitUrl.d.ts +6 -0
- package/dist/sdk/gitUrl.js +87 -0
- package/dist/sdk/index.d.ts +5 -0
- package/dist/sdk/index.js +5 -0
- package/dist/serverlessHints.d.ts +9 -6
- package/dist/serverlessHints.js +10 -7
- package/dist/taskMeter.d.ts +14 -0
- package/dist/taskMeter.js +53 -0
- package/dist/types.d.ts +43 -0
- package/examples/aca-container-gate/Dockerfile +20 -0
- package/examples/aca-container-gate/azure-container-app.yaml +27 -0
- package/examples/aca-container-gate/gate.env +7 -0
- package/examples/aca-container-gate/server.mjs +117 -0
- package/examples/azure-functions-gate/.funcignore +6 -0
- package/examples/azure-functions-gate/README.md +25 -0
- package/examples/azure-functions-gate/host.json +15 -0
- package/examples/azure-functions-gate/package-lock.json +161 -0
- package/examples/azure-functions-gate/package.json +14 -0
- package/examples/azure-functions-gate/src/functions/health.js +27 -0
- package/examples/express-local-live-smoke.mjs +127 -0
- package/examples/extractRunId.mjs +11 -0
- package/examples/next-pilot-dry-run.mjs +32 -0
- package/examples/serverless-thin-gate.mjs +89 -0
- package/fixtures/run-smoke/hello.mjs +4 -0
- package/loaders/next-entry-loader.cjs +14 -0
- package/package.json +25 -2
|
@@ -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;
|
|
@@ -0,0 +1,119 @@
|
|
|
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 { createHash } from 'node:crypto';
|
|
8
|
+
import { tryBuildSafePatch } from './safePatches.js';
|
|
9
|
+
const GUIDANCE = {
|
|
10
|
+
unbounded_parallelism: {
|
|
11
|
+
action: 'review_and_limit',
|
|
12
|
+
text: 'Cap concurrency (p-limit / Promise pool / worker count). Prefer bounded ' +
|
|
13
|
+
'queues over unbounded Promise.all on large collections.',
|
|
14
|
+
},
|
|
15
|
+
retry_amplification: {
|
|
16
|
+
action: 'backoff_or_cap',
|
|
17
|
+
text: 'Add exponential backoff, jitter, and a hard retry ceiling. Avoid nested ' +
|
|
18
|
+
'retries that multiply outbound calls under failure.',
|
|
19
|
+
},
|
|
20
|
+
external_api_overconsumption: {
|
|
21
|
+
action: 'batch_or_debounce',
|
|
22
|
+
text: 'Batch or debounce outbound calls, reuse connections, and cache idempotent ' +
|
|
23
|
+
'reads. Prefer one request per logical unit of work.',
|
|
24
|
+
},
|
|
25
|
+
per_item_instead_of_batch: {
|
|
26
|
+
action: 'batch_or_debounce',
|
|
27
|
+
text: 'Replace per-item remote/DB work with a batch API or a single query. ' +
|
|
28
|
+
'Keep N+1 patterns out of hot paths.',
|
|
29
|
+
},
|
|
30
|
+
repeated_work: {
|
|
31
|
+
action: 'cache_or_memoize',
|
|
32
|
+
text: 'Memoize or cache repeated pure/expensive work within the request/task ' +
|
|
33
|
+
'scope. Deduplicate identical lookups.',
|
|
34
|
+
},
|
|
35
|
+
polling_or_idle_work: {
|
|
36
|
+
action: 'idle_or_event',
|
|
37
|
+
text: 'Replace tight polling with event-driven waits, longer intervals, or ' +
|
|
38
|
+
'backoff when idle. Avoid busy-spin loops.',
|
|
39
|
+
},
|
|
40
|
+
memory_retention_or_materialization: {
|
|
41
|
+
action: 'stream_or_bound',
|
|
42
|
+
text: 'Stream or page large payloads instead of materializing full arrays. ' +
|
|
43
|
+
'Bound caches and clear references after use.',
|
|
44
|
+
},
|
|
45
|
+
process_or_runtime_churn: {
|
|
46
|
+
action: 'manual_review',
|
|
47
|
+
text: 'Reduce process spawn / worker churn — reuse long-lived workers or pool ' +
|
|
48
|
+
'them. Confirm the spawn is required per unit of work.',
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
function proposalId(findingId, mechanism) {
|
|
52
|
+
return createHash('sha256')
|
|
53
|
+
.update(`opt:${findingId}:${mechanism}`)
|
|
54
|
+
.digest('hex')
|
|
55
|
+
.slice(0, 16);
|
|
56
|
+
}
|
|
57
|
+
function guidanceFor(mechanismId) {
|
|
58
|
+
return (GUIDANCE[mechanismId] || {
|
|
59
|
+
action: 'manual_review',
|
|
60
|
+
text: 'Admitted resource candidate — review the indicated scope and apply a ' +
|
|
61
|
+
'bounded resource fix. Automatic patches require a matching safe rule + VerificationProvider.',
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
export function createLocalJsTsOptimizerProvider() {
|
|
65
|
+
return {
|
|
66
|
+
id: 'local_js_ts_optimizer_v0',
|
|
67
|
+
version: '0.2.0',
|
|
68
|
+
proposeFromFindings(findings, opts) {
|
|
69
|
+
const proposals = [];
|
|
70
|
+
const by_mechanism = {};
|
|
71
|
+
const by_action_kind = {};
|
|
72
|
+
let auto_apply_safe = 0;
|
|
73
|
+
for (const f of findings) {
|
|
74
|
+
if (f.evidence_state !== 'candidate')
|
|
75
|
+
continue;
|
|
76
|
+
const g = guidanceFor(f.mechanism_id);
|
|
77
|
+
const safe = tryBuildSafePatch(f, opts.projectDir);
|
|
78
|
+
const proposal = {
|
|
79
|
+
schema: 'optimize_proposal_v0',
|
|
80
|
+
proposal_id: proposalId(f.finding_id, f.mechanism_id),
|
|
81
|
+
finding_id: f.finding_id,
|
|
82
|
+
mechanism_id: f.mechanism_id,
|
|
83
|
+
primary_domain: f.primary_domain,
|
|
84
|
+
title: f.title,
|
|
85
|
+
action_kind: g.action,
|
|
86
|
+
guidance: g.text,
|
|
87
|
+
scope: f.scope,
|
|
88
|
+
auto_apply_safe: Boolean(safe),
|
|
89
|
+
patch: safe?.patch ?? null,
|
|
90
|
+
};
|
|
91
|
+
if (safe)
|
|
92
|
+
auto_apply_safe += 1;
|
|
93
|
+
proposals.push(proposal);
|
|
94
|
+
by_mechanism[f.mechanism_id] = (by_mechanism[f.mechanism_id] || 0) + 1;
|
|
95
|
+
by_action_kind[g.action] = (by_action_kind[g.action] || 0) + 1;
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
schema: 'optimize_result_v0',
|
|
99
|
+
contract_status: 'optimizer_provider_local_v0',
|
|
100
|
+
project_id: opts.projectId,
|
|
101
|
+
project_dir: opts.projectDir,
|
|
102
|
+
findings_considered: findings.length,
|
|
103
|
+
proposals,
|
|
104
|
+
stats: {
|
|
105
|
+
proposals: proposals.length,
|
|
106
|
+
auto_apply_safe,
|
|
107
|
+
by_mechanism,
|
|
108
|
+
by_action_kind,
|
|
109
|
+
},
|
|
110
|
+
notes: [
|
|
111
|
+
'Local JS/TS OptimizerProvider — guidance for all admitted candidates.',
|
|
112
|
+
'auto_apply_safe patches are deterministic only (no LLM / no /optimize/*).',
|
|
113
|
+
'File writes require --apply + VerificationProvider gates.',
|
|
114
|
+
'No measured energy/cost savings claimed.',
|
|
115
|
+
],
|
|
116
|
+
};
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic safe patch rules for Node Optimize.
|
|
3
|
+
*
|
|
4
|
+
* Only exact, local transforms — no LLM, no api_server /optimize/*.
|
|
5
|
+
*/
|
|
6
|
+
import type { ResourceFindingCandidateV1 } from '../analyze/resourceFindingCandidate.js';
|
|
7
|
+
import type { OptimizePatchV0 } from './types.js';
|
|
8
|
+
export type SafePatchMatch = {
|
|
9
|
+
patch: OptimizePatchV0;
|
|
10
|
+
reason: string;
|
|
11
|
+
};
|
|
12
|
+
/** Exported for unit tests — apply rules without a finding. */
|
|
13
|
+
export declare function trySafePatchRulesOnSource(source: string, relPath: string, mechanismId: string): SafePatchMatch | null;
|
|
14
|
+
/**
|
|
15
|
+
* Attempt a deterministic safe patch for one admitted finding.
|
|
16
|
+
* Returns null when no rule matches (proposal stays guidance-only).
|
|
17
|
+
*/
|
|
18
|
+
export declare function tryBuildSafePatch(finding: ResourceFindingCandidateV1, projectDir: string): SafePatchMatch | null;
|