rtl-analyzer 0.1.0 → 0.3.0
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/README.md +88 -35
- package/dist/cli.js +18 -1
- package/dist/codemod.js +50 -12
- package/dist/companion-security.js +2 -0
- package/dist/contextual-preview-bridge.js +113 -0
- package/dist/contextual-preview.js +74 -0
- package/dist/controlled-apply.js +222 -0
- package/dist/css-directional.js +60 -0
- package/dist/css-icons.js +51 -0
- package/dist/css-spacing.js +64 -0
- package/dist/dashboard-client.js +57 -40
- package/dist/dashboard-contextual-preview.js +119 -0
- package/dist/dashboard-data.js +1 -1
- package/dist/dashboard-embedded-preview.js +200 -0
- package/dist/dashboard-html.js +11 -10
- package/dist/dashboard-review-details.js +175 -0
- package/dist/dashboard-review-workflow.js +151 -0
- package/dist/directional-properties.js +53 -0
- package/dist/discovery.js +1 -2
- package/dist/eligibility.js +8 -8
- package/dist/evidence-store.js +110 -0
- package/dist/example-preview-mappings.js +98 -0
- package/dist/manual-change-store.js +27 -0
- package/dist/migration-lifecycle.js +19 -0
- package/dist/original-preview-runtime.js +68 -0
- package/dist/output-path.js +65 -0
- package/dist/policy-validation.js +1 -1
- package/dist/preview-cli.js +22 -0
- package/dist/preview-companion.js +621 -0
- package/dist/preview-configuration.js +144 -0
- package/dist/preview-runtime.js +98 -0
- package/dist/project-configuration.js +48 -0
- package/dist/project-root.js +12 -0
- package/dist/react-inline.js +65 -0
- package/dist/report-publisher.js +4 -7
- package/dist/review-approval.js +9 -0
- package/dist/review-session.js +199 -54
- package/dist/review-store.js +175 -0
- package/dist/review-workflow.js +554 -0
- package/dist/rules.js +14 -13
- package/dist/runtime-process.js +35 -0
- package/dist/scan-history.js +35 -0
- package/dist/scan-manifest-store.js +26 -0
- package/dist/scan.js +55 -4
- package/dist/serialization.js +1 -0
- package/dist/source-context.js +93 -0
- package/dist/source-snippets.js +3 -3
- package/dist/standalone-cli.js +91 -9
- package/dist/tailwind.js +3 -1
- package/dist/transformations.js +20 -0
- package/dist/validation.js +71 -0
- package/dist/workflow-validation.js +46 -0
- package/package.json +20 -7
package/dist/review-session.js
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { cp, lstat, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
|
|
3
|
-
import { dirname, isAbsolute, join,
|
|
2
|
+
import { cp, lstat, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { spawnPreviewRuntime, signalOwnedRuntime } from './runtime-process.js';
|
|
6
|
+
import { createServer as createNetServer } from 'node:net';
|
|
7
|
+
import { loadProjectConfiguration, PROJECT_CONFIGURATION } from './project-configuration.js';
|
|
8
|
+
import { loadPreviewConfiguration } from './preview-configuration.js';
|
|
9
|
+
import { writePreviewRuntimeConfig } from './preview-runtime.js';
|
|
7
10
|
export const REVIEW_SOURCE = 'apps/invoicing/src/components/InvoiceTable.tsx';
|
|
8
11
|
export const REVIEW_FINDING_ID = 'RTL.ICON.PROGRESSION:237172da962fe4d0605ddd83';
|
|
9
12
|
export const CANDIDATE_PORT = 4202;
|
|
10
13
|
export const CANDIDATE_ORIGIN = `http://127.0.0.1:${CANDIDATE_PORT}`;
|
|
11
14
|
export function runtimeCacheDir(root, role) { return join(resolve(root), '.rtl-vite-cache', role); }
|
|
12
15
|
const runtimes = new Map();
|
|
16
|
+
const runtimeStates = new Map();
|
|
17
|
+
const runtimeStarts = new Map();
|
|
18
|
+
const reservedPorts = new Set();
|
|
19
|
+
export const CANDIDATE_PORTS = Array.from({ length: 11 }, (_, index) => CANDIDATE_PORT + index);
|
|
13
20
|
const reviewRecords = new Map();
|
|
14
21
|
const digest = (text) => createHash('sha256').update(text).digest('hex');
|
|
15
22
|
const recordKey = (identity) => `${identity.findingId}|${identity.sourcePath}|${identity.inputDigest}|${identity.policyDigest}|${identity.schemaVersion}`;
|
|
@@ -24,8 +31,7 @@ export const reviewStatusTransitions = {
|
|
|
24
31
|
'Rejected': ['Candidate Proposed', 'Needs Manual Investigation'],
|
|
25
32
|
};
|
|
26
33
|
export function reviewRecordKey(identity) { return recordKey(identity); }
|
|
27
|
-
|
|
28
|
-
export function validateReviewIdentity(identity) { if (!identity || typeof identity.findingId !== 'string' || !identity.findingId.trim() || identity.findingId.length > 500 || typeof identity.sourcePath !== 'string' || !validSerializedReviewPath(identity.sourcePath) || identity.schemaVersion !== 2 || !identity.inputDigest || !identity.policyDigest)
|
|
34
|
+
export function validateReviewIdentity(identity) { if (!identity || typeof identity.findingId !== 'string' || !identity.findingId.trim() || identity.findingId.length > 500 || typeof identity.sourcePath !== 'string' || !identity.sourcePath || isAbsolute(identity.sourcePath) || normalize(identity.sourcePath) !== identity.sourcePath || identity.sourcePath.split(/[\\/]/).includes('..') || identity.schemaVersion !== 2 || !identity.inputDigest || !identity.policyDigest)
|
|
29
35
|
throw new Error('INVALID_REVIEW_IDENTITY'); }
|
|
30
36
|
export function validateReviewRecordShape(input) { validateReviewIdentity(input); if (!Object.prototype.hasOwnProperty.call(input, 'status') || !reviewStatusTransitions[input.status])
|
|
31
37
|
throw new Error('INVALID_REVIEW_STATUS'); if (typeof input.reviewerNotes !== 'string' || input.reviewerNotes.length > 4000 || !Array.isArray(input.evidenceReferences) || input.evidenceReferences.length > 50 || input.evidenceReferences.some(reference => typeof reference !== 'string' || reference.length > 500))
|
|
@@ -47,7 +53,7 @@ export function saveReviewRecord(input) {
|
|
|
47
53
|
export function clearReviewRecords() { reviewRecords.clear(); }
|
|
48
54
|
const inside = (root, target) => { const r = relative(root, target); return r === '' || (r !== '..' && !r.startsWith(`..${sep}`) && !isAbsolute(r)); };
|
|
49
55
|
export function validateReviewPath(root, path) {
|
|
50
|
-
if (!
|
|
56
|
+
if (!path || isAbsolute(path) || normalize(path) !== path || path.split(/[\\/]/).includes('..'))
|
|
51
57
|
throw new Error('INVALID_REVIEW_PATH');
|
|
52
58
|
const target = resolve(root, path);
|
|
53
59
|
if (!inside(resolve(root), target) || path !== REVIEW_SOURCE)
|
|
@@ -55,7 +61,7 @@ export function validateReviewPath(root, path) {
|
|
|
55
61
|
return target;
|
|
56
62
|
}
|
|
57
63
|
export async function validateProjectSourcePath(root, path) {
|
|
58
|
-
if (!
|
|
64
|
+
if (!path || isAbsolute(path) || normalize(path) !== path || path.split(/[\\/]/).includes('..'))
|
|
59
65
|
throw new Error('INVALID_REVIEW_PATH');
|
|
60
66
|
const canonicalRoot = await realpath(resolve(root));
|
|
61
67
|
const target = resolve(canonicalRoot, path);
|
|
@@ -82,18 +88,21 @@ export function validatePatch(text, patch) {
|
|
|
82
88
|
if (digest(text.slice(patch.startOffset, patch.endOffset)) !== patch.expectedSha256)
|
|
83
89
|
throw new Error('STALE_REVIEW_SOURCE');
|
|
84
90
|
}
|
|
85
|
-
export async function createReviewSession(root) {
|
|
86
|
-
const source = validateReviewPath(root,
|
|
87
|
-
const sourceStat = await lstat(
|
|
91
|
+
export async function createReviewSession(root, sourcePath = REVIEW_SOURCE) {
|
|
92
|
+
const source = sourcePath === REVIEW_SOURCE ? validateReviewPath(root, sourcePath) : await validateProjectSourcePath(root, sourcePath);
|
|
93
|
+
const sourceStat = await lstat(join(root, sourcePath));
|
|
88
94
|
if (!sourceStat.isFile())
|
|
89
95
|
throw new Error('REVIEW_SOURCE_NOT_REGULAR_FILE');
|
|
90
|
-
const candidateRoot = await mkdtemp(join(tmpdir(), 'rtl-review-'));
|
|
96
|
+
const candidateRoot = await realpath(await mkdtemp(join(tmpdir(), 'rtl-review-')));
|
|
91
97
|
try {
|
|
92
|
-
const
|
|
93
|
-
await
|
|
94
|
-
const
|
|
98
|
+
const project = await loadProjectConfiguration(root);
|
|
99
|
+
const rootConfigs = (await readdir(root)).filter(name => /^(tsconfig.*\.json|(?:vite|vitest|playwright|eslint)(?:\.[\w-]+)*\.config\.[cm]?[jt]s)$/.test(name));
|
|
100
|
+
const allowedTopLevel = new Set(['apps', 'libs', 'tests', 'tools', '.storybook', 'package.json', 'package-lock.json', 'nx.json', 'rtl-scanner.config.json', 'rtl-preview.config.json', PROJECT_CONFIGURATION, ...(project?.copyPaths.map(p => p.split('/')[0]) ?? []), ...rootConfigs]);
|
|
101
|
+
await cp(root, candidateRoot, { recursive: true, dereference: false, filter: (sourcePath) => { const relativePath = sourcePath.slice(root.length + 1); const parts = relativePath.split('/'); const top = parts[0] ?? ''; return relativePath === '' || (allowedTopLevel.has(top) && (!project || [PROJECT_CONFIGURATION, 'rtl-preview.config.json', 'rtl-scanner.config.json', ...rootConfigs, ...project.copyPaths].some(p => relativePath === p || relativePath.startsWith(p + '/') || p.startsWith(relativePath + '/'))) && !parts.some(part => ['node_modules', 'dist', '.nx', '.git', '.rtl-vite-cache'].includes(part))); } });
|
|
102
|
+
await symlink(join(root, 'node_modules'), join(candidateRoot, 'node_modules'), 'dir');
|
|
103
|
+
const copied = await validateProjectSourcePath(candidateRoot, sourcePath);
|
|
95
104
|
const text = await readFile(copied, 'utf8');
|
|
96
|
-
return { id: randomUUID(), root: resolve(root), candidateRoot, sourcePath
|
|
105
|
+
return { id: randomUUID(), root: resolve(root), candidateRoot, sourcePath, state: 'Candidate Proposed', classification: 'Manual', originalSha256: digest(text), createdAt: new Date().toISOString() };
|
|
97
106
|
}
|
|
98
107
|
catch (error) {
|
|
99
108
|
await rm(candidateRoot, { recursive: true, force: true });
|
|
@@ -106,48 +115,184 @@ export async function applyReviewPatch(session, patch) {
|
|
|
106
115
|
validatePatch(text, patch);
|
|
107
116
|
const next = text.slice(0, patch.startOffset) + patch.replacement + text.slice(patch.endOffset);
|
|
108
117
|
await writeFile(target, next, 'utf8');
|
|
109
|
-
return { ...session, state: 'Candidate Proposed', candidateSha256: digest(next) };
|
|
118
|
+
return { ...session, state: 'Candidate Proposed', candidateSha256: digest(next), patch };
|
|
110
119
|
}
|
|
111
|
-
|
|
120
|
+
const locationAt = (text, offset) => {
|
|
121
|
+
const prefix = text.slice(0, offset);
|
|
122
|
+
const line = prefix.split(/\r?\n/).length;
|
|
123
|
+
const lastBreak = Math.max(prefix.lastIndexOf('\n'), prefix.lastIndexOf('\r'));
|
|
124
|
+
return { line, column: offset - lastBreak };
|
|
125
|
+
};
|
|
126
|
+
export async function reviewSessionComparison(session) {
|
|
112
127
|
const original = await readFile(validateReviewPath(session.root, REVIEW_SOURCE), 'utf8');
|
|
113
|
-
const candidate = await readFile(
|
|
114
|
-
if (original
|
|
115
|
-
return '
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
128
|
+
const candidate = await readFile(await validateProjectSourcePath(session.candidateRoot, session.sourcePath), 'utf8');
|
|
129
|
+
if (digest(original) !== session.originalSha256)
|
|
130
|
+
return { state: 'stale', path: REVIEW_SOURCE, diff: '', reason: 'STALE_ORIGINAL_SOURCE' };
|
|
131
|
+
if (session.candidateSha256 && digest(candidate) !== session.candidateSha256)
|
|
132
|
+
return { state: 'stale', path: REVIEW_SOURCE, diff: '', reason: 'STALE_CANDIDATE_SOURCE' };
|
|
133
|
+
if (!session.patch)
|
|
134
|
+
return original === candidate
|
|
135
|
+
? { state: 'unchanged', path: REVIEW_SOURCE, diff: 'No candidate changes applied.' }
|
|
136
|
+
: { state: 'unavailable', path: REVIEW_SOURCE, diff: '', reason: 'PATCH_CORRESPONDENCE_UNAVAILABLE' };
|
|
137
|
+
const patch = session.patch;
|
|
138
|
+
try {
|
|
139
|
+
validatePatch(original, patch);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
return { state: 'stale', path: REVIEW_SOURCE, diff: '', reason: error instanceof Error ? error.message : 'STALE_REVIEW_SOURCE' };
|
|
143
|
+
}
|
|
144
|
+
const expectedCandidate = original.slice(0, patch.startOffset) + patch.replacement + original.slice(patch.endOffset);
|
|
145
|
+
if (expectedCandidate !== candidate)
|
|
146
|
+
return { state: 'unavailable', path: REVIEW_SOURCE, diff: '', reason: 'PATCH_CORRESPONDENCE_UNAVAILABLE' };
|
|
147
|
+
const before = original.slice(patch.startOffset, patch.endOffset);
|
|
148
|
+
const afterStart = patch.startOffset;
|
|
149
|
+
const after = candidate.slice(afterStart, afterStart + patch.replacement.length);
|
|
150
|
+
const beforeLocation = locationAt(original, patch.startOffset);
|
|
151
|
+
const afterLocation = locationAt(candidate, afterStart);
|
|
152
|
+
return { state: 'ready', path: REVIEW_SOURCE, before, after, beforeLocation, afterLocation, diff: `--- ${REVIEW_SOURCE} (original)\n+++ ${REVIEW_SOURCE} (candidate)\n@@ ${beforeLocation.line}:${beforeLocation.column} → ${afterLocation.line}:${afterLocation.column}\n- ${before}\n+ ${after}` };
|
|
153
|
+
}
|
|
154
|
+
export async function reviewSessionDiff(session) {
|
|
155
|
+
const comparison = await reviewSessionComparison(session);
|
|
156
|
+
if (comparison.state === 'ready' || comparison.state === 'unchanged')
|
|
157
|
+
return comparison.diff;
|
|
158
|
+
throw new Error(comparison.reason ?? 'PATCH_CORRESPONDENCE_UNAVAILABLE');
|
|
159
|
+
}
|
|
160
|
+
export async function assertPortAvailable(port = CANDIDATE_PORT) {
|
|
161
|
+
await new Promise((resolvePort, reject) => {
|
|
162
|
+
const probe = createNetServer();
|
|
163
|
+
probe.once('error', () => reject(new Error('CANDIDATE_PORT_OCCUPIED')));
|
|
164
|
+
probe.listen(port, '127.0.0.1', () => probe.close(() => resolvePort()));
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
async function runtimeIdentityHash(session, application) { const app = (await loadPreviewConfiguration(session.candidateRoot)).applications[application]; return digest(await readFile(await validateProjectSourcePath(session.candidateRoot, (application === 'invoicing' ? session.sourcePath : app?.entry) ?? (application === 'procurement' ? 'apps/procurement/src/App.tsx' : session.sourcePath)), 'utf8')); }
|
|
168
|
+
const runtimeKey = (session, application) => session.id + (application === 'invoicing' ? '' : ':' + application);
|
|
169
|
+
export function candidateApplicationRuntime(session, application) { return runtimeStates.get(runtimeKey(session, application))?.runtime; }
|
|
170
|
+
async function ownedRuntimeHealthy(session, application = 'invoicing') {
|
|
171
|
+
const child = runtimes.get(runtimeKey(session, application));
|
|
172
|
+
if (!child || child.exitCode !== null || child.signalCode !== null || !session.runtime)
|
|
173
|
+
return false;
|
|
174
|
+
try {
|
|
175
|
+
const response = await fetch(session.runtime.origin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(1000) });
|
|
176
|
+
const identity = await response.json();
|
|
177
|
+
return response.ok && identity.sessionId === session.id && identity.role === 'candidate' && identity.application === application && identity.sourceSha256 === await runtimeIdentityHash(session, application) && identity.projectRoot === await realpath(session.candidateRoot);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
119
182
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
183
|
+
export async function startCandidateRuntime(session, application) {
|
|
184
|
+
if (Object.values(session.runtimePorts ?? {}).some(port => !CANDIDATE_PORTS.includes(port)))
|
|
185
|
+
throw Error('CANDIDATE_PORT_ASSIGNMENT_INVALID');
|
|
186
|
+
const apps = (await loadPreviewConfiguration(session.candidateRoot)).applications;
|
|
187
|
+
application = application ?? (Object.keys(apps)[0] || 'invoicing');
|
|
188
|
+
if (!apps[application] && !['invoicing', 'procurement'].includes(application))
|
|
189
|
+
throw Error('PREVIEW_APPLICATION_NOT_CONFIGURED');
|
|
190
|
+
const key = runtimeKey(session, application);
|
|
191
|
+
const active = runtimeStarts.get(key);
|
|
192
|
+
if (active) {
|
|
193
|
+
const next = await active;
|
|
194
|
+
return next;
|
|
195
|
+
}
|
|
196
|
+
const operation = startRuntime(session, application);
|
|
197
|
+
runtimeStarts.set(key, operation);
|
|
198
|
+
try {
|
|
199
|
+
const next = await operation;
|
|
200
|
+
return next;
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
runtimeStarts.delete(key);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async function startRuntime(session, application) {
|
|
207
|
+
const key = runtimeKey(session, application);
|
|
208
|
+
const currentHash = digest(await readFile(await validateProjectSourcePath(session.candidateRoot, session.sourcePath), 'utf8'));
|
|
209
|
+
if (session.candidateSha256 && currentHash !== session.candidateSha256)
|
|
210
|
+
throw new Error('STALE_CANDIDATE_SOURCE');
|
|
211
|
+
const existing = runtimeStates.get(key);
|
|
212
|
+
if (existing && await ownedRuntimeHealthy({ ...existing, candidateSha256: session.candidateSha256 }, application))
|
|
213
|
+
return { ...session, runtime: existing.runtime };
|
|
214
|
+
if (existing)
|
|
215
|
+
await stopRuntimeKey(existing, key);
|
|
128
216
|
const dependencyMount = join(session.candidateRoot, 'node_modules');
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const child = spawn(process.execPath, [viteBin, '--config', candidateConfig, '--host', '127.0.0.1', '--port', String(CANDIDATE_PORT), '--strictPort'], { cwd: session.root, env: { ...process.env, NODE_PATH: join(session.root, 'node_modules'), RTL_VITE_CACHE_DIR: runtimeCacheDir(session.candidateRoot, 'candidate') }, shell: false, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
132
|
-
let startupError = '';
|
|
133
|
-
child.stderr?.on('data', chunk => { startupError = `${startupError}${String(chunk)}`.slice(-2000); });
|
|
134
|
-
runtimes.set(session.id, child);
|
|
135
|
-
const starting = { ...session, runtime: { port: CANDIDATE_PORT, origin: CANDIDATE_ORIGIN, status: 'starting' } };
|
|
136
|
-
for (let attempt = 0; attempt < 100; attempt++) {
|
|
137
|
-
if (await health(CANDIDATE_ORIGIN, CANDIDATE_PORT))
|
|
138
|
-
return { ...starting, runtime: { ...starting.runtime, status: 'healthy' } };
|
|
139
|
-
if (child.exitCode !== null)
|
|
140
|
-
break;
|
|
141
|
-
await new Promise(resolveDelay => setTimeout(resolveDelay, 100));
|
|
217
|
+
try {
|
|
218
|
+
await symlink(join(session.root, 'node_modules'), dependencyMount, 'dir');
|
|
142
219
|
}
|
|
143
|
-
|
|
144
|
-
|
|
220
|
+
catch (error) {
|
|
221
|
+
if (error.code !== 'EEXIST' || await realpath(dependencyMount) !== await realpath(join(session.root, 'node_modules')))
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
const sourceSha256 = digest(await readFile(await validateProjectSourcePath(session.candidateRoot, session.sourcePath), 'utf8'));
|
|
225
|
+
if (session.candidateSha256 && sourceSha256 !== session.candidateSha256)
|
|
226
|
+
throw new Error('STALE_CANDIDATE_SOURCE');
|
|
227
|
+
const runtimeSourceHash = await runtimeIdentityHash(session, application);
|
|
228
|
+
const candidateConfig = await writePreviewRuntimeConfig(session.candidateRoot, { role: 'candidate', sessionId: session.id, sourceSha256: runtimeSourceHash }, { application, contextRoot: session.root });
|
|
229
|
+
// Retain per-application origins through composition/restart; a stopped app's URL must not become another app in the same review.
|
|
230
|
+
const assignments = session.runtimePorts ?? (session.runtimePorts = {});
|
|
231
|
+
const preferred = assignments[application];
|
|
232
|
+
const ports = preferred ? [preferred, ...CANDIDATE_PORTS.filter(p => p !== preferred)] : CANDIDATE_PORTS;
|
|
233
|
+
for (const port of ports) {
|
|
234
|
+
if (Object.entries(assignments).some(([app, assigned]) => app !== application && assigned === port))
|
|
235
|
+
continue;
|
|
236
|
+
if (reservedPorts.has(port))
|
|
237
|
+
continue;
|
|
238
|
+
reservedPorts.add(port);
|
|
239
|
+
try {
|
|
240
|
+
await assertPortAvailable(port);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
reservedPorts.delete(port);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
const origin = `http://127.0.0.1:${port}`;
|
|
247
|
+
let child;
|
|
248
|
+
try {
|
|
249
|
+
child = await spawnPreviewRuntime(session.candidateRoot, application, candidateConfig, port, { cwd: session.candidateRoot, env: { ...process.env, NODE_PATH: join(session.root, 'node_modules'), RTL_VITE_CACHE_DIR: runtimeCacheDir(session.candidateRoot, 'candidate') }, shell: false, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
reservedPorts.delete(port);
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
let startupError = '';
|
|
256
|
+
child.stderr?.on('data', chunk => { startupError = `${startupError}${String(chunk)}`.slice(-2000); });
|
|
257
|
+
child.on('error', error => { startupError = error.message; });
|
|
258
|
+
runtimes.set(key, child);
|
|
259
|
+
assignments[application] = port;
|
|
260
|
+
const starting = { ...session, runtimePorts: assignments, candidateSha256: sourceSha256, runtime: { port, origin, status: 'starting' } };
|
|
261
|
+
runtimeStates.set(key, starting);
|
|
262
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
263
|
+
if (await ownedRuntimeHealthy(starting, application)) {
|
|
264
|
+
const healthy = { ...starting, runtime: { ...starting.runtime, status: 'healthy' } };
|
|
265
|
+
runtimeStates.set(key, healthy);
|
|
266
|
+
return healthy;
|
|
267
|
+
}
|
|
268
|
+
if (child.exitCode !== null || startupError.includes('EADDRINUSE'))
|
|
269
|
+
break;
|
|
270
|
+
await new Promise(resolveDelay => setTimeout(resolveDelay, 100));
|
|
271
|
+
}
|
|
272
|
+
await stopRuntimeKey(starting, key);
|
|
273
|
+
if (/EADDRINUSE|already in use/.test(startupError))
|
|
274
|
+
continue;
|
|
275
|
+
return { ...starting, runtime: { ...starting.runtime, status: 'failed', error: startupError.trim() || 'CANDIDATE_IDENTITY_UNAVAILABLE' } };
|
|
276
|
+
}
|
|
277
|
+
throw new Error('CANDIDATE_PORT_POOL_EXHAUSTED');
|
|
278
|
+
}
|
|
279
|
+
async function stopRuntimeKey(session, key) {
|
|
280
|
+
const child = runtimes.get(key);
|
|
281
|
+
if (child && child.exitCode === null && child.signalCode === null) {
|
|
282
|
+
signalOwnedRuntime(child);
|
|
283
|
+
await new Promise(resolveStop => { const timer = setTimeout(() => { if (child.exitCode === null)
|
|
284
|
+
signalOwnedRuntime(child, 'SIGKILL'); resolveStop(); }, 2000); child.once('exit', () => { clearTimeout(timer); resolveStop(); }); });
|
|
285
|
+
}
|
|
286
|
+
const owned = runtimeStates.get(key);
|
|
287
|
+
if (owned?.runtime)
|
|
288
|
+
reservedPorts.delete(owned.runtime.port);
|
|
289
|
+
runtimes.delete(key);
|
|
290
|
+
runtimeStates.delete(key);
|
|
291
|
+
}
|
|
292
|
+
export async function stopCandidateRuntime(session) {
|
|
293
|
+
await Promise.all([...new Set([session.id, ...runtimes.keys(), ...runtimeStates.keys()])].filter(key => key === session.id || key.startsWith(session.id + ':')).map(key => stopRuntimeKey(session, key)));
|
|
294
|
+
return { ...session, runtime: session.runtime ? { ...session.runtime, status: 'stopped' } : undefined };
|
|
145
295
|
}
|
|
146
|
-
export async function
|
|
147
|
-
|
|
148
|
-
await new Promise(resolveStop => { const timer = setTimeout(() => { if (child.exitCode === null)
|
|
149
|
-
child.kill('SIGKILL'); resolveStop(); }, 2000); child.once('exit', () => { clearTimeout(timer); resolveStop(); }); });
|
|
150
|
-
} runtimes.delete(session.id); return { ...session, runtime: session.runtime ? { ...session.runtime, status: 'stopped' } : undefined }; }
|
|
151
|
-
export async function disposeReviewSession(session) { if (!inside(tmpdir(), resolve(session.candidateRoot)))
|
|
152
|
-
throw new Error('INVALID_REVIEW_SESSION_ROOT'); await stopCandidateRuntime(session); await rm(session.candidateRoot, { recursive: true, force: true }); }
|
|
296
|
+
export async function disposeReviewSession(session) { if (!inside(await realpath(tmpdir()), await realpath(session.candidateRoot)))
|
|
297
|
+
throw new Error('INVALID_REVIEW_SESSION_ROOT'); await Promise.all([...runtimeStarts].filter(([key]) => key === session.id || key.startsWith(session.id + ':')).map(([, start]) => start.catch(() => undefined))); await stopCandidateRuntime(session); await rm(session.candidateRoot, { recursive: true, force: true }); }
|
|
153
298
|
export const reviewSourceDirectory = (root) => dirname(validateReviewPath(root, REVIEW_SOURCE));
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { access, mkdir, readFile, rename, lstat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { homedir, tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { reviewRecordKey, reviewStatusTransitions, validateReviewIdentity, validateReviewRecordShape } from './review-session.js';
|
|
6
|
+
export const REVIEW_STORE_VERSION = 1;
|
|
7
|
+
export const DEFAULT_REVIEW_STORE_PATH = process.env.RTL_REVIEW_STORE_PATH || join(homedir(), '.rtl-migration-analyzer', 'review-records-v1.json');
|
|
8
|
+
const inside = (root, target) => { const value = relative(root, target); return value === '' || (value !== '..' && !value.startsWith(`..${sep}`) && !isAbsolute(value)); };
|
|
9
|
+
async function rejectSymlinkPath(path) {
|
|
10
|
+
const absolute = resolve(path);
|
|
11
|
+
const root = parse(absolute).root;
|
|
12
|
+
let cursor = root;
|
|
13
|
+
const trustedAncestors = [resolve(tmpdir()), resolve(homedir())];
|
|
14
|
+
for (const part of absolute.slice(root.length).split(sep).filter(Boolean)) {
|
|
15
|
+
cursor = join(cursor, part);
|
|
16
|
+
try {
|
|
17
|
+
if ((await lstat(cursor)).isSymbolicLink() && !trustedAncestors.some(ancestor => inside(cursor, ancestor)))
|
|
18
|
+
throw new Error('REVIEW_STORE_SYMLINK');
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'ENOENT')
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function validateStorePath(path) { const absolute = resolve(path); if (!isAbsolute(absolute) || !inside(dirname(absolute), absolute) || !absolute.endsWith(`${sep}review-records-v1.json`))
|
|
27
|
+
throw new Error('INVALID_REVIEW_STORE_PATH'); return absolute; }
|
|
28
|
+
function validateStoredRecord(record) {
|
|
29
|
+
if (!record || typeof record !== 'object')
|
|
30
|
+
throw new Error('INVALID_REVIEW_RECORD');
|
|
31
|
+
const value = record;
|
|
32
|
+
validateReviewRecordShape(value);
|
|
33
|
+
if (typeof value.timestamp !== 'string' || !Number.isFinite(Date.parse(value.timestamp)))
|
|
34
|
+
throw new Error('INVALID_REVIEW_TIMESTAMP');
|
|
35
|
+
return { ...value, evidenceReferences: [...value.evidenceReferences] };
|
|
36
|
+
}
|
|
37
|
+
const treatments = ['Automated', 'Assisted', 'Manual'];
|
|
38
|
+
function validateDecisionShape(input) {
|
|
39
|
+
validateReviewIdentity(input);
|
|
40
|
+
if (!/^[a-f0-9]{64}$/.test(input.sourceDigest))
|
|
41
|
+
throw new Error('INVALID_DECISION_SOURCE_DIGEST');
|
|
42
|
+
if (!treatments.includes(input.recommendation) || !treatments.includes(input.selectedTreatment))
|
|
43
|
+
throw new Error('INVALID_MIGRATION_TREATMENT');
|
|
44
|
+
if (typeof input.recommendationRationale !== 'string' || input.recommendationRationale.length > 4000 || !Array.isArray(input.eligibilityConstraints) || input.eligibilityConstraints.some(x => typeof x !== 'string' || x.length > 500) || !Array.isArray(input.blockers) || input.blockers.some(x => typeof x !== 'string' || x.length > 500))
|
|
45
|
+
throw new Error('INVALID_DECISION_METADATA');
|
|
46
|
+
if (input.selectedTreatment !== input.recommendation && (!input.overrideReason || input.overrideReason.trim().length === 0 || input.overrideReason.length > 4000))
|
|
47
|
+
throw new Error('OVERRIDE_REASON_REQUIRED');
|
|
48
|
+
if (input.selectedTreatment === 'Automated' && (input.recommendation !== 'Automated' || input.blockers.length > 0))
|
|
49
|
+
throw new Error('AUTOMATED_TREATMENT_NOT_ELIGIBLE');
|
|
50
|
+
if (input.timestamp !== undefined && !Number.isFinite(Date.parse(input.timestamp)))
|
|
51
|
+
throw new Error('INVALID_DECISION_TIMESTAMP');
|
|
52
|
+
for (const item of input.history ?? [])
|
|
53
|
+
if (!treatments.includes(item.selectedTreatment) || !Number.isFinite(Date.parse(item.timestamp)))
|
|
54
|
+
throw new Error('INVALID_DECISION_HISTORY');
|
|
55
|
+
}
|
|
56
|
+
function validateStoredDecision(decision) { if (!decision || typeof decision !== 'object')
|
|
57
|
+
throw new Error('INVALID_MIGRATION_DECISION'); const value = decision; validateDecisionShape(value); if (typeof value.timestamp !== 'string' || !Number.isFinite(Date.parse(value.timestamp)))
|
|
58
|
+
throw new Error('INVALID_DECISION_TIMESTAMP'); return { ...value, eligibilityConstraints: [...value.eligibilityConstraints], blockers: [...value.blockers], history: [...value.history] }; }
|
|
59
|
+
export class ReviewRecordStore {
|
|
60
|
+
path;
|
|
61
|
+
records = new Map();
|
|
62
|
+
decisions = new Map();
|
|
63
|
+
loaded = false;
|
|
64
|
+
error = null;
|
|
65
|
+
constructor(path = DEFAULT_REVIEW_STORE_PATH) { this.path = validateStorePath(path); }
|
|
66
|
+
get loadError() { return this.error; }
|
|
67
|
+
get isLoaded() { return this.loaded; }
|
|
68
|
+
async load() {
|
|
69
|
+
await rejectSymlinkPath(dirname(this.path));
|
|
70
|
+
try {
|
|
71
|
+
const raw = JSON.parse(await readFile(this.path, 'utf8'));
|
|
72
|
+
if (raw.formatVersion !== REVIEW_STORE_VERSION || !Array.isArray(raw.records) || (raw.decisions !== undefined && !Array.isArray(raw.decisions)))
|
|
73
|
+
throw new Error('INCOMPATIBLE_REVIEW_STORE');
|
|
74
|
+
const next = new Map();
|
|
75
|
+
for (const item of raw.records) {
|
|
76
|
+
const record = validateStoredRecord(item);
|
|
77
|
+
const key = reviewRecordKey(record);
|
|
78
|
+
if (next.has(key))
|
|
79
|
+
throw new Error('DUPLICATE_REVIEW_RECORD');
|
|
80
|
+
next.set(key, record);
|
|
81
|
+
}
|
|
82
|
+
const nextDecisions = new Map();
|
|
83
|
+
for (const item of raw.decisions ?? []) {
|
|
84
|
+
const decision = validateStoredDecision(item);
|
|
85
|
+
const key = reviewRecordKey(decision);
|
|
86
|
+
if (nextDecisions.has(key))
|
|
87
|
+
throw new Error('DUPLICATE_MIGRATION_DECISION');
|
|
88
|
+
nextDecisions.set(key, decision);
|
|
89
|
+
}
|
|
90
|
+
this.records = next;
|
|
91
|
+
this.decisions = nextDecisions;
|
|
92
|
+
this.error = null;
|
|
93
|
+
this.loaded = true;
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
const code = error.code;
|
|
97
|
+
if (code === 'ENOENT') {
|
|
98
|
+
this.records.clear();
|
|
99
|
+
this.error = null;
|
|
100
|
+
this.loaded = true;
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
this.records.clear();
|
|
104
|
+
this.error = error instanceof Error ? error.message : 'REVIEW_STORE_LOAD_FAILED';
|
|
105
|
+
this.loaded = true;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
get(identity) { validateReviewIdentity(identity); return this.records.get(reviewRecordKey(identity)) ?? null; }
|
|
109
|
+
getDecision(identity) { validateReviewIdentity(identity); return this.decisions.get(reviewRecordKey(identity)) ?? null; }
|
|
110
|
+
async saveDecision(input) { if (!this.loaded)
|
|
111
|
+
throw new Error('REVIEW_STORE_NOT_LOADED'); if (this.error)
|
|
112
|
+
throw new Error(`REVIEW_STORE_UNAVAILABLE:${this.error}`); validateDecisionShape(input); const key = reviewRecordKey(input); const previous = this.decisions.get(key); const record = { ...input, timestamp: input.timestamp ?? new Date().toISOString(), history: input.history ? [...input.history] : previous ? [...previous.history, { selectedTreatment: previous.selectedTreatment, ...(previous.overrideReason ? { overrideReason: previous.overrideReason } : {}), timestamp: previous.timestamp }] : [], eligibilityConstraints: [...input.eligibilityConstraints], blockers: [...input.blockers] }; this.decisions.set(key, record); try {
|
|
113
|
+
await this.persist();
|
|
114
|
+
return record;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (previous)
|
|
118
|
+
this.decisions.set(key, previous);
|
|
119
|
+
else
|
|
120
|
+
this.decisions.delete(key);
|
|
121
|
+
throw error;
|
|
122
|
+
} }
|
|
123
|
+
save(input) {
|
|
124
|
+
if (!this.loaded)
|
|
125
|
+
throw new Error('REVIEW_STORE_NOT_LOADED');
|
|
126
|
+
if (this.error)
|
|
127
|
+
throw new Error(`REVIEW_STORE_UNAVAILABLE:${this.error}`);
|
|
128
|
+
validateReviewRecordShape(input);
|
|
129
|
+
const key = reviewRecordKey(input);
|
|
130
|
+
const current = this.records.get(key);
|
|
131
|
+
const previous = current?.status ?? 'Not Reviewed';
|
|
132
|
+
if (input.status !== previous && !reviewStatusTransitions[previous].includes(input.status))
|
|
133
|
+
throw new Error('INVALID_REVIEW_TRANSITION');
|
|
134
|
+
const record = { ...input, timestamp: input.timestamp ?? new Date().toISOString(), evidenceReferences: [...input.evidenceReferences] };
|
|
135
|
+
this.records.set(key, record);
|
|
136
|
+
return record;
|
|
137
|
+
}
|
|
138
|
+
async persist() {
|
|
139
|
+
if (!this.loaded)
|
|
140
|
+
throw new Error('REVIEW_STORE_NOT_LOADED');
|
|
141
|
+
if (this.error)
|
|
142
|
+
throw new Error(`REVIEW_STORE_UNAVAILABLE:${this.error}`);
|
|
143
|
+
const parent = dirname(this.path);
|
|
144
|
+
await rejectSymlinkPath(parent);
|
|
145
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
146
|
+
await rejectSymlinkPath(parent);
|
|
147
|
+
const temporary = join(parent, `.review-records-v1.${process.pid}.${Date.now()}.tmp`);
|
|
148
|
+
const payload = { formatVersion: REVIEW_STORE_VERSION, records: [...this.records.values()], decisions: [...this.decisions.values()] };
|
|
149
|
+
try {
|
|
150
|
+
await writeFile(temporary, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
151
|
+
await rename(temporary, this.path);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
try {
|
|
155
|
+
await access(temporary, constants.F_OK);
|
|
156
|
+
await rename(temporary, `${temporary}.failed`);
|
|
157
|
+
}
|
|
158
|
+
catch { /* preserve the original error */ }
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async saveAndPersist(input) { const key = reviewRecordKey(input); const previous = this.records.get(key); const record = this.save(input); try {
|
|
163
|
+
await this.persist();
|
|
164
|
+
return record;
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (previous)
|
|
168
|
+
this.records.set(key, previous);
|
|
169
|
+
else
|
|
170
|
+
this.records.delete(key);
|
|
171
|
+
throw error;
|
|
172
|
+
} }
|
|
173
|
+
}
|
|
174
|
+
export const reviewStoreIsOutsideRepository = (path, repositoryRoot) => !inside(resolve(repositoryRoot), resolve(path));
|
|
175
|
+
export const reviewStoreTempRoot = tmpdir;
|