@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/next.js ADDED
@@ -0,0 +1,195 @@
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 { randomUUID } from 'node:crypto';
9
+ import { getRuntime, } from './runtime.js';
10
+ import { getTenantStore, resolveTenantFromHttpRequest, runWithTenantContext, tenantConfigFromRuntime, } from './tenantContext.js';
11
+ import { runWithRequestAttribution } from './requestContext.js';
12
+ import { beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
13
+ import { getOccupancyTracker } from './occupancyTracker.js';
14
+ export const UNKNOWN_NEXT_ROUTE_TEMPLATE = '<unmatched>';
15
+ const MAX_ROUTE_TEMPLATE_LEN = 512;
16
+ /**
17
+ * Call from ``instrumentation.ts`` ``register()`` to start the Runtime singleton.
18
+ *
19
+ * ```ts
20
+ * export async function register() {
21
+ * const { registerNetGreenerNext } = await import('@netgreener/runtime/next')
22
+ * registerNetGreenerNext()
23
+ * }
24
+ * ```
25
+ */
26
+ export function registerNetGreenerNext(opts = {}) {
27
+ const runtime = getRuntime({
28
+ collector: 'next_app_router',
29
+ framework: 'next',
30
+ ...opts,
31
+ });
32
+ runtime.start();
33
+ if (runtime.lifecycle === 'persistent') {
34
+ const onSignal = () => {
35
+ void runtime.shutdown();
36
+ };
37
+ process.once('beforeExit', onSignal);
38
+ process.once('SIGINT', onSignal);
39
+ process.once('SIGTERM', onSignal);
40
+ }
41
+ return runtime;
42
+ }
43
+ /**
44
+ * Bounded route template for service_unit attribution.
45
+ * Never use query strings; prefer an explicit ``routeTemplate`` option.
46
+ */
47
+ export function nextRouteTemplate(req, override) {
48
+ if (typeof override === 'string') {
49
+ const t = override.trim();
50
+ if (t &&
51
+ t.length <= MAX_ROUTE_TEMPLATE_LEN &&
52
+ !t.includes('?') &&
53
+ !t.includes('#')) {
54
+ return t;
55
+ }
56
+ }
57
+ const pathname = req.nextUrl?.pathname ||
58
+ (typeof req.url === 'string' ? safePathname(req.url) : '');
59
+ const template = (pathname || '').trim();
60
+ if (!template ||
61
+ template.length > MAX_ROUTE_TEMPLATE_LEN ||
62
+ template.includes('?') ||
63
+ template.includes('#')) {
64
+ return UNKNOWN_NEXT_ROUTE_TEMPLATE;
65
+ }
66
+ return template;
67
+ }
68
+ function safePathname(url) {
69
+ try {
70
+ return new URL(url, 'http://local').pathname;
71
+ }
72
+ catch {
73
+ return url.split('?')[0] || '';
74
+ }
75
+ }
76
+ function headersAsRecord(headers) {
77
+ if (!headers)
78
+ return {};
79
+ if (typeof headers.get === 'function') {
80
+ const out = {};
81
+ headers.forEach((value, key) => {
82
+ out[key] = value;
83
+ });
84
+ return out;
85
+ }
86
+ return headers;
87
+ }
88
+ /**
89
+ * Wrap an App Router route handler (``GET``/``POST``/…) with NetGreener metering.
90
+ *
91
+ * ```ts
92
+ * export const POST = withNetGreenerRoute(async (req) => {
93
+ * return Response.json({ ok: true })
94
+ * }, { routeTemplate: '/api/intake' })
95
+ * ```
96
+ */
97
+ export function withNetGreenerRoute(handler, opts = {}) {
98
+ const runtime = getRuntime({
99
+ collector: 'next_app_router',
100
+ framework: 'next',
101
+ ...opts,
102
+ });
103
+ runtime.start();
104
+ const tenantConfig = tenantConfigFromRuntime(runtime.config);
105
+ return async function netgreenerNextHandler(req, ...args) {
106
+ if (!runtime.enabled) {
107
+ return handler(req, ...args);
108
+ }
109
+ const method = (req.method || 'GET').toUpperCase();
110
+ const path = nextRouteTemplate(req, opts.routeTemplate);
111
+ const resolveServiceUnit = () => `${method} ${path}`;
112
+ const fakeHttpReq = {
113
+ method,
114
+ headers: headersAsRecord(req.headers),
115
+ };
116
+ const entryTenant = resolveTenantFromHttpRequest(fakeHttpReq, tenantConfig);
117
+ return runWithTenantContext(entryTenant, () => runWithRequestAttribution({
118
+ resolveServiceUnit,
119
+ serviceUnit: resolveServiceUnit(),
120
+ }, async () => {
121
+ const tenantStore = getTenantStore() ?? {
122
+ current: entryTenant,
123
+ };
124
+ const started = process.hrtime.bigint();
125
+ const resourceMark = beginProcessResourceSample();
126
+ const requestId = randomUUID();
127
+ getOccupancyTracker().begin(requestId);
128
+ runtime.beginRequest();
129
+ let statusCode = 200;
130
+ try {
131
+ const result = await handler(req, ...args);
132
+ statusCode = statusFromResult(result);
133
+ return result;
134
+ }
135
+ catch (err) {
136
+ statusCode = 500;
137
+ throw err;
138
+ }
139
+ finally {
140
+ const ended = process.hrtime.bigint();
141
+ const durationMs = Number(ended - started) / 1e6;
142
+ const resources = endProcessResourceSample(resourceMark);
143
+ const serviceUnit = resolveServiceUnit();
144
+ getOccupancyTracker().end(requestId, serviceUnit);
145
+ runWithTenantContext(tenantStore.current, () => {
146
+ runtime.recordHttp({
147
+ method,
148
+ path,
149
+ statusCode,
150
+ durationMs,
151
+ cpuTimeMs: resources.cpuTimeMs,
152
+ peakRssKb: resources.rssKb,
153
+ });
154
+ });
155
+ runtime.endRequest();
156
+ if (runtime.lifecycle === 'ephemeral') {
157
+ void runtime.flushForInvokeEnd();
158
+ }
159
+ }
160
+ }));
161
+ };
162
+ }
163
+ function statusFromResult(result) {
164
+ if (result &&
165
+ typeof result === 'object' &&
166
+ 'status' in result &&
167
+ typeof result.status === 'number') {
168
+ return result.status;
169
+ }
170
+ return 200;
171
+ }
172
+ export function getNextRuntime() {
173
+ return getRuntime({ collector: 'next_app_router', framework: 'next' });
174
+ }
175
+ /** Explicit flush helper for instrumentation ``onRequestError`` / custom hooks. */
176
+ export async function flushNetGreenerNext(kind = 'manual') {
177
+ const runtime = getNextRuntime();
178
+ if (kind === 'shutdown')
179
+ return runtime.shutdown();
180
+ if (kind === 'invoke_end')
181
+ return runtime.flushForInvokeEnd();
182
+ return runtime.flush(kind);
183
+ }
184
+ /**
185
+ * Schedule a best-effort flush after the response (Vercel ``waitUntil`` when present).
186
+ * Fail-open: never throws into the customer path.
187
+ */
188
+ export function scheduleNetGreenerFlush(waitUntil) {
189
+ const p = flushNetGreenerNext('invoke_end').catch(() => null);
190
+ if (typeof waitUntil === 'function') {
191
+ waitUntil(p);
192
+ return;
193
+ }
194
+ void p;
195
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Concurrency-normalized request occupancy (Python OccupancyTracker twin).
3
+ *
4
+ * Accrues ``dt / N`` to each active request id while N > 0. On end, share moves
5
+ * to the service unit. Window snapshots leave in-flight as unattributed.
6
+ * Additive for anomaly evidence — does not change EXPORT_MODE.
7
+ */
8
+ export type OccupancyWindowSnapshot = {
9
+ by_unit: Record<string, number>;
10
+ in_flight_seconds: number;
11
+ idle_seconds: number;
12
+ };
13
+ export declare class OccupancyTracker {
14
+ private activeIds;
15
+ private occById;
16
+ private occByUnit;
17
+ private idleSeconds;
18
+ private lastMono;
19
+ begin(requestId: string): void;
20
+ end(requestId: string, serviceUnit: string): void;
21
+ private accrue;
22
+ /** Snapshot closed-window occupancy; keep in-flight ids active with zeroed accrual. */
23
+ takeWindowSnapshot(): OccupancyWindowSnapshot;
24
+ }
25
+ export declare function getOccupancyTracker(): OccupancyTracker;
26
+ /** Test helper — swap in a fresh tracker. */
27
+ export declare function _resetOccupancyTrackerForTests(): void;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Concurrency-normalized request occupancy (Python OccupancyTracker twin).
3
+ *
4
+ * Accrues ``dt / N`` to each active request id while N > 0. On end, share moves
5
+ * to the service unit. Window snapshots leave in-flight as unattributed.
6
+ * Additive for anomaly evidence — does not change EXPORT_MODE.
7
+ */
8
+ export class OccupancyTracker {
9
+ activeIds = new Set();
10
+ occById = new Map();
11
+ occByUnit = new Map();
12
+ idleSeconds = 0;
13
+ lastMono = null;
14
+ begin(requestId) {
15
+ if (!requestId)
16
+ return;
17
+ this.accrue(nowMono());
18
+ this.activeIds.add(requestId);
19
+ if (!this.occById.has(requestId))
20
+ this.occById.set(requestId, 0);
21
+ }
22
+ end(requestId, serviceUnit) {
23
+ if (!requestId)
24
+ return;
25
+ this.accrue(nowMono());
26
+ this.activeIds.delete(requestId);
27
+ const share = this.occById.get(requestId) || 0;
28
+ this.occById.delete(requestId);
29
+ const unit = String(serviceUnit || '').trim();
30
+ if (unit && share > 0) {
31
+ this.occByUnit.set(unit, (this.occByUnit.get(unit) || 0) + share);
32
+ }
33
+ }
34
+ accrue(now) {
35
+ if (this.lastMono == null) {
36
+ this.lastMono = now;
37
+ return;
38
+ }
39
+ const dt = Math.max(0, now - this.lastMono);
40
+ this.lastMono = now;
41
+ if (dt <= 0)
42
+ return;
43
+ const n = this.activeIds.size;
44
+ if (n <= 0) {
45
+ this.idleSeconds += dt;
46
+ return;
47
+ }
48
+ const per = dt / n;
49
+ for (const rid of this.activeIds) {
50
+ this.occById.set(rid, (this.occById.get(rid) || 0) + per);
51
+ }
52
+ }
53
+ /** Snapshot closed-window occupancy; keep in-flight ids active with zeroed accrual. */
54
+ takeWindowSnapshot() {
55
+ this.accrue(nowMono());
56
+ const by_unit = {};
57
+ for (const [k, v] of this.occByUnit) {
58
+ if (v > 0)
59
+ by_unit[k] = Math.round(v * 1e6) / 1e6;
60
+ }
61
+ let inFlight = 0;
62
+ for (const v of this.occById.values())
63
+ inFlight += v;
64
+ const idle = this.idleSeconds;
65
+ this.occByUnit.clear();
66
+ for (const rid of this.occById.keys())
67
+ this.occById.set(rid, 0);
68
+ this.idleSeconds = 0;
69
+ return {
70
+ by_unit,
71
+ in_flight_seconds: Math.round(inFlight * 1e6) / 1e6,
72
+ idle_seconds: Math.round(idle * 1e6) / 1e6,
73
+ };
74
+ }
75
+ }
76
+ function nowMono() {
77
+ const t = process.hrtime.bigint();
78
+ return Number(t) / 1e9;
79
+ }
80
+ let globalTracker = new OccupancyTracker();
81
+ export function getOccupancyTracker() {
82
+ return globalTracker;
83
+ }
84
+ /** Test helper — swap in a fresh tracker. */
85
+ export function _resetOccupancyTrackerForTests() {
86
+ globalTracker = new OccupancyTracker();
87
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Apply verified full-file patches with VerificationProvider gates + rollback.
3
+ *
4
+ * Used by:
5
+ * - ``--apply`` (local auto_apply_safe only)
6
+ * - ``--llm --apply-verified`` (owner-OK LLM splice; not marked auto_apply_safe)
7
+ *
8
+ * Never uploads. Does not flip EXPORT_MODE. Does not invent savings.
9
+ */
10
+ import type { OptimizeApplyResultV0, OptimizeProposalV0, VerificationResultV0 } from './types.js';
11
+ export type VerifiedPatchWrite = {
12
+ proposal_id: string;
13
+ path: string;
14
+ new_content: string;
15
+ rule_id: string;
16
+ };
17
+ /**
18
+ * Verify → backup → write → verify-after → rollback on fail.
19
+ * Callers decide which patches are eligible (safe rules vs LLM-gated).
20
+ */
21
+ export declare function applyVerifiedPatches(projectDir: string, patches: VerifiedPatchWrite[], opts?: {
22
+ skipTest?: boolean;
23
+ skipBuild?: boolean;
24
+ /** Already-skipped rows to include in the result. */
25
+ preSkipped?: OptimizeApplyResultV0['skipped'];
26
+ }): {
27
+ apply: OptimizeApplyResultV0;
28
+ verification_before: VerificationResultV0;
29
+ verification_after: VerificationResultV0 | null;
30
+ };
31
+ export declare function applySafeProposals(projectDir: string, proposals: OptimizeProposalV0[], opts?: {
32
+ skipTest?: boolean;
33
+ skipBuild?: boolean;
34
+ }): {
35
+ apply: OptimizeApplyResultV0;
36
+ verification_before: VerificationResultV0;
37
+ verification_after: VerificationResultV0 | null;
38
+ };
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Apply verified full-file patches with VerificationProvider gates + rollback.
3
+ *
4
+ * Used by:
5
+ * - ``--apply`` (local auto_apply_safe only)
6
+ * - ``--llm --apply-verified`` (owner-OK LLM splice; not marked auto_apply_safe)
7
+ *
8
+ * Never uploads. Does not flip EXPORT_MODE. Does not invent savings.
9
+ */
10
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { dirname, join } from 'node:path';
12
+ import { createLocalJsTsVerificationProvider } from './verification.js';
13
+ function backupRoot(projectDir) {
14
+ return join(projectDir, '.netgreener', 'optimize-backup');
15
+ }
16
+ function writeWithDirs(abs, content) {
17
+ mkdirSync(dirname(abs), { recursive: true });
18
+ writeFileSync(abs, content, 'utf8');
19
+ }
20
+ /**
21
+ * Verify → backup → write → verify-after → rollback on fail.
22
+ * Callers decide which patches are eligible (safe rules vs LLM-gated).
23
+ */
24
+ export function applyVerifiedPatches(projectDir, patches, opts) {
25
+ const verifier = createLocalJsTsVerificationProvider();
26
+ const skipped = [...(opts?.preSkipped || [])];
27
+ const touched = [...new Set(patches.map((p) => p.path))];
28
+ const verification_before = verifier.verify(projectDir, {
29
+ paths: touched,
30
+ skipTest: opts?.skipTest,
31
+ skipBuild: opts?.skipBuild ?? true,
32
+ });
33
+ const applied = [];
34
+ if (!verification_before.ok) {
35
+ return {
36
+ apply: {
37
+ schema: 'optimize_apply_result_v0',
38
+ applied: [],
39
+ skipped: [
40
+ ...skipped,
41
+ ...patches.map((p) => ({
42
+ proposal_id: p.proposal_id,
43
+ reason: 'verification_before failed',
44
+ })),
45
+ ],
46
+ rolled_back: false,
47
+ verification_before_ok: false,
48
+ verification_after_ok: null,
49
+ },
50
+ verification_before,
51
+ verification_after: null,
52
+ };
53
+ }
54
+ if (patches.length === 0) {
55
+ return {
56
+ apply: {
57
+ schema: 'optimize_apply_result_v0',
58
+ applied: [],
59
+ skipped,
60
+ rolled_back: false,
61
+ verification_before_ok: true,
62
+ verification_after_ok: null,
63
+ },
64
+ verification_before,
65
+ verification_after: null,
66
+ };
67
+ }
68
+ const bakDir = backupRoot(projectDir);
69
+ mkdirSync(bakDir, { recursive: true });
70
+ const backups = [];
71
+ try {
72
+ // One file may appear in multiple patches — last write wins by path.
73
+ const byPath = new Map();
74
+ for (const p of patches) {
75
+ byPath.set(p.path, p);
76
+ }
77
+ for (const p of byPath.values()) {
78
+ const rel = p.path;
79
+ const abs = join(projectDir, rel);
80
+ const bak = join(bakDir, rel.replace(/[\\/]/g, '__'));
81
+ const prev = readFileSync(abs, 'utf8');
82
+ writeWithDirs(bak, prev);
83
+ backups.push({ abs, bak });
84
+ writeFileSync(abs, p.new_content, 'utf8');
85
+ applied.push({
86
+ proposal_id: p.proposal_id,
87
+ path: rel,
88
+ rule_id: p.rule_id,
89
+ });
90
+ }
91
+ const verification_after = verifier.verify(projectDir, {
92
+ paths: touched,
93
+ skipTest: opts?.skipTest,
94
+ skipBuild: opts?.skipBuild ?? true,
95
+ });
96
+ if (!verification_after.ok) {
97
+ for (const { abs, bak } of backups) {
98
+ renameSync(bak, abs);
99
+ }
100
+ try {
101
+ rmSync(bakDir, { recursive: true, force: true });
102
+ }
103
+ catch {
104
+ /* ignore */
105
+ }
106
+ return {
107
+ apply: {
108
+ schema: 'optimize_apply_result_v0',
109
+ applied: [],
110
+ skipped: [
111
+ ...skipped,
112
+ ...applied.map((a) => ({
113
+ proposal_id: a.proposal_id,
114
+ reason: 'rolled back: verification_after failed',
115
+ })),
116
+ ],
117
+ rolled_back: true,
118
+ verification_before_ok: true,
119
+ verification_after_ok: false,
120
+ },
121
+ verification_before,
122
+ verification_after,
123
+ };
124
+ }
125
+ try {
126
+ rmSync(bakDir, { recursive: true, force: true });
127
+ }
128
+ catch {
129
+ /* ignore */
130
+ }
131
+ return {
132
+ apply: {
133
+ schema: 'optimize_apply_result_v0',
134
+ applied,
135
+ skipped,
136
+ rolled_back: false,
137
+ verification_before_ok: true,
138
+ verification_after_ok: true,
139
+ },
140
+ verification_before,
141
+ verification_after,
142
+ };
143
+ }
144
+ catch (err) {
145
+ for (const { abs, bak } of backups) {
146
+ try {
147
+ renameSync(bak, abs);
148
+ }
149
+ catch {
150
+ /* ignore */
151
+ }
152
+ }
153
+ throw err;
154
+ }
155
+ }
156
+ export function applySafeProposals(projectDir, proposals, opts) {
157
+ const safe = proposals.filter((p) => p.auto_apply_safe && p.patch);
158
+ const preSkipped = [];
159
+ for (const p of proposals) {
160
+ if (!p.auto_apply_safe || !p.patch) {
161
+ preSkipped.push({
162
+ proposal_id: p.proposal_id,
163
+ reason: 'not auto_apply_safe (guidance-only)',
164
+ });
165
+ }
166
+ }
167
+ return applyVerifiedPatches(projectDir, safe.map((p) => ({
168
+ proposal_id: p.proposal_id,
169
+ path: p.patch.path,
170
+ new_content: p.patch.new_content,
171
+ rule_id: p.patch.rule_id,
172
+ })), { ...opts, preSkipped });
173
+ }
@@ -0,0 +1,26 @@
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
+ export type OptimizeCliFlags = {
11
+ projectDir: string;
12
+ projectId: string;
13
+ paths: string[] | null;
14
+ apply: boolean;
15
+ /** LLM-only: write reviewed splices via VerificationProvider. */
16
+ applyVerified: boolean;
17
+ verifyOnly: boolean;
18
+ skipTest: boolean;
19
+ quiet: boolean;
20
+ help: boolean;
21
+ llm: boolean;
22
+ maxLlm: number;
23
+ };
24
+ export declare function formatOptimizeHelp(): string;
25
+ export declare function parseOptimizeArgs(argv: string[]): OptimizeCliFlags;
26
+ export declare function runOptimizeCli(argv: string[]): number | Promise<number>;