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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createServerFn } from "@tanstack/react-start";
2
+ import { z } from "zod";
3
+ import { sanitize, restore } from "./branch-debug.functions";
4
+
5
+ // ───────────────────────── Types ─────────────────────────
6
+
7
+ export type VehicleManifest = {
8
+ vehicleId: string;
9
+ commitHash: string;
10
+ branch: string;
11
+ source: "manifest" | "git" | "github" | "manual";
12
+ fetchedAt: number;
13
+ warnings: string[];
14
+ };
15
+
16
+ export type FetchedCode = {
17
+ manifest: VehicleManifest;
18
+ files: { path: string; content: string }[];
19
+ fetchMethod: string;
20
+ warnings: string[];
21
+ };
22
+
23
+ export type Hypothesis = {
24
+ id: string;
25
+ title: string;
26
+ confidence: "High" | "Medium" | "Low";
27
+ mechanism: string;
28
+ code_evidence: string;
29
+ log_signatures: string[];
30
+ eliminates_if: string;
31
+ };
32
+
33
+ export type Stage1Result = {
34
+ stage: 1;
35
+ summary: string;
36
+ critical_path: string[];
37
+ hypotheses: Hypothesis[];
38
+ what_to_grep: string[];
39
+ timeline_question: string;
40
+ unknowns: string[];
41
+ };
42
+
43
+ export type Stage2Result = {
44
+ stage: 2;
45
+ summary: string;
46
+ timeline: { offset: string; event: string; source: string }[];
47
+ hypothesis_verdicts: { id: string; verdict: "CONFIRMED" | "ELIMINATED" | "POSSIBLE"; evidence: string }[];
48
+ root_cause: { function: string; line_hint: string; mechanism: string; confidence: "High" | "Medium" | "Low" };
49
+ what_vehicle_saw: string;
50
+ still_unknown: string[];
51
+ };
52
+
53
+ export type Stage3Result = {
54
+ stage: 3;
55
+ summary: string;
56
+ failure_layer: "SENSING" | "PROCESSING" | "PLANNING" | "CONTROL";
57
+ perception_state: { what_vehicle_saw: string; what_it_should_have_seen: string; discrepancy: string };
58
+ full_chain: { layer: string; input: string; output: string; issue: string }[];
59
+ definitive_cause: { function: string; mechanism: string; confidence: "High" };
60
+ fix: string;
61
+ test_case: string;
62
+ };
63
+
64
+ export type StageResult = Stage1Result | Stage2Result | Stage3Result;
65
+
66
+ // ───────────────────────── Connect / Fetch ─────────────────────────
67
+ //
68
+ // The Worker runtime cannot SSH. Two real fetch strategies work here:
69
+ // 1. Central manifest endpoint (HTTP GET) – vehicles push build info on startup
70
+ // 2. GitHub raw / API (HTTP) – fetch exact files at the manifest commit
71
+ // SSH-into-vehicle is intentionally surfaced as "agent required" to the user.
72
+
73
+ const ConnectSchema = z.object({
74
+ vehicleId: z.string().min(1).max(80),
75
+ manifestUrl: z.string().url().optional().or(z.literal("")),
76
+ githubRepo: z.string().max(160).optional(), // "org/repo"
77
+ githubBranch: z.string().max(80).optional(),
78
+ githubToken: z.string().max(200).optional(),
79
+ });
80
+
81
+ export const testVehicleConnection = createServerFn({ method: "POST" })
82
+ .inputValidator((d: unknown) => ConnectSchema.parse(d))
83
+ .handler(async ({ data }) => {
84
+ const results: Record<string, unknown> = {};
85
+ const t0 = Date.now();
86
+
87
+ if (data.manifestUrl) {
88
+ try {
89
+ const url = `${data.manifestUrl.replace(/\/$/, "")}/vehicles/${encodeURIComponent(data.vehicleId)}/manifest`;
90
+ const res = await fetch(url, { signal: AbortSignal.timeout(8000) });
91
+ results.manifestReachable = res.ok;
92
+ results.manifestStatus = res.status;
93
+ if (res.ok) {
94
+ const m = await res.json().catch(() => null);
95
+ if (m && typeof m === "object") {
96
+ results.deployedCommit = (m as any).commit ?? null;
97
+ results.branch = (m as any).branch ?? null;
98
+ }
99
+ }
100
+ } catch (e) {
101
+ results.manifestReachable = false;
102
+ results.manifestError = (e as Error).message;
103
+ }
104
+ }
105
+
106
+ if (data.githubRepo) {
107
+ try {
108
+ const headers: Record<string, string> = { Accept: "application/vnd.github+json" };
109
+ if (data.githubToken) headers.Authorization = `Bearer ${data.githubToken}`;
110
+ const r = await fetch(`https://api.github.com/repos/${data.githubRepo}`, {
111
+ headers,
112
+ signal: AbortSignal.timeout(8000),
113
+ });
114
+ results.githubReachable = r.ok;
115
+ results.githubStatus = r.status;
116
+ } catch (e) {
117
+ results.githubReachable = false;
118
+ results.githubError = (e as Error).message;
119
+ }
120
+ }
121
+
122
+ results.latencyMs = Date.now() - t0;
123
+ return { vehicleId: data.vehicleId, results };
124
+ });
125
+
126
+ const FetchSchema = z.object({
127
+ vehicleId: z.string().min(1).max(80),
128
+ targetFiles: z.array(z.string().min(1).max(300)).min(1).max(20),
129
+ manifestUrl: z.string().optional(),
130
+ githubRepo: z.string().optional(), // "org/repo"
131
+ githubBranch: z.string().optional().default("main"),
132
+ githubToken: z.string().optional(),
133
+ manualCommit: z.string().optional(), // override commit when no manifest
134
+ });
135
+
136
+ export const fetchVehicleCode = createServerFn({ method: "POST" })
137
+ .inputValidator((d: unknown) => FetchSchema.parse(d))
138
+ .handler(async ({ data }): Promise<FetchedCode> => {
139
+ const warnings: string[] = [];
140
+ let commit = data.manualCommit?.trim() || "";
141
+ let branch = data.githubBranch || "main";
142
+ let source: VehicleManifest["source"] = "manual";
143
+
144
+ // Strategy 1: manifest endpoint
145
+ if (!commit && data.manifestUrl) {
146
+ try {
147
+ const url = `${data.manifestUrl.replace(/\/$/, "")}/vehicles/${encodeURIComponent(data.vehicleId)}/manifest`;
148
+ const r = await fetch(url, { signal: AbortSignal.timeout(8000) });
149
+ if (r.ok) {
150
+ const m = (await r.json()) as { commit?: string; branch?: string };
151
+ if (m.commit) {
152
+ commit = m.commit;
153
+ branch = m.branch || branch;
154
+ source = "manifest";
155
+ }
156
+ } else {
157
+ warnings.push(`Manifest endpoint returned ${r.status}`);
158
+ }
159
+ } catch (e) {
160
+ warnings.push(`Manifest fetch failed: ${(e as Error).message}`);
161
+ }
162
+ }
163
+
164
+ // If still no commit, fall back to branch HEAD via GitHub
165
+ if (!commit && data.githubRepo) {
166
+ try {
167
+ const headers: Record<string, string> = { Accept: "application/vnd.github+json" };
168
+ if (data.githubToken) headers.Authorization = `Bearer ${data.githubToken}`;
169
+ const r = await fetch(
170
+ `https://api.github.com/repos/${data.githubRepo}/commits/${encodeURIComponent(branch)}`,
171
+ { headers, signal: AbortSignal.timeout(8000) },
172
+ );
173
+ if (r.ok) {
174
+ const j = (await r.json()) as { sha?: string };
175
+ if (j.sha) {
176
+ commit = j.sha;
177
+ source = "github";
178
+ warnings.push(`No manifest — fell back to ${branch} HEAD on GitHub`);
179
+ }
180
+ }
181
+ } catch (e) {
182
+ warnings.push(`GitHub HEAD lookup failed: ${(e as Error).message}`);
183
+ }
184
+ }
185
+
186
+ if (!commit) {
187
+ throw new Error(
188
+ "Could not determine deployed commit. Provide a manifest URL, a GitHub repo, or paste the commit hash manually. (Direct SSH-into-vehicle is not available from this serverless runtime — use a manifest endpoint or git mirror.)",
189
+ );
190
+ }
191
+
192
+ // Fetch each file from GitHub raw at that commit
193
+ if (!data.githubRepo) {
194
+ throw new Error("GitHub repo (org/repo) is required to fetch the file contents at the resolved commit.");
195
+ }
196
+ const files: { path: string; content: string }[] = [];
197
+ const headers: Record<string, string> = {};
198
+ if (data.githubToken) headers.Authorization = `Bearer ${data.githubToken}`;
199
+ for (const path of data.targetFiles) {
200
+ const url = `https://raw.githubusercontent.com/${data.githubRepo}/${commit}/${path}`;
201
+ try {
202
+ const r = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
203
+ if (r.ok) {
204
+ const content = await r.text();
205
+ files.push({ path, content: content.slice(0, 80_000) });
206
+ } else {
207
+ warnings.push(`${path}: HTTP ${r.status}`);
208
+ }
209
+ } catch (e) {
210
+ warnings.push(`${path}: ${(e as Error).message}`);
211
+ }
212
+ }
213
+
214
+ if (files.length === 0) {
215
+ throw new Error(`Could not fetch any of the requested files at commit ${commit.slice(0, 8)}.`);
216
+ }
217
+
218
+ return {
219
+ manifest: {
220
+ vehicleId: data.vehicleId,
221
+ commitHash: commit,
222
+ branch,
223
+ source,
224
+ fetchedAt: Date.now(),
225
+ warnings,
226
+ },
227
+ files,
228
+ fetchMethod: source === "manifest" ? "manifest+github" : source === "github" ? "github-head" : "manual+github",
229
+ warnings,
230
+ };
231
+ });
232
+
233
+ // ───────────────────────── Stage analysis ─────────────────────────
234
+
235
+ const STAGE_PROMPTS: Record<1 | 2 | 3, string> = {
236
+ 1: `You are an expert AV engineer specializing in post-deployment forensic debugging.
237
+ Inputs: deployed vehicle code (identifiers anonymized as fn_NNNN) and a failure description.
238
+ Logs are NOT yet available. Analyze the code statically. Generate ranked hypotheses and predict log signatures.
239
+ Always call submit_stage1.`,
240
+ 2: `You are an expert AV engineer. You have anonymized deployed code, a failure description, AND system logs.
241
+ Correlate log evidence against the prior hypotheses (passed in). Reconstruct the timeline. Find the root cause.
242
+ Always call submit_stage2.`,
243
+ 3: `You are an expert AV engineer. You have anonymized code, logs, AND ROS bag / sensor data excerpts.
244
+ Trace the full perception → planning → control chain. Determine the failure layer and the definitive root cause.
245
+ Always call submit_stage3.`,
246
+ };
247
+
248
+ const stage1Tool = {
249
+ type: "function" as const,
250
+ function: {
251
+ name: "submit_stage1",
252
+ description: "Submit Stage 1 hypotheses.",
253
+ parameters: {
254
+ type: "object",
255
+ properties: {
256
+ summary: { type: "string" },
257
+ critical_path: { type: "array", items: { type: "string" } },
258
+ hypotheses: {
259
+ type: "array",
260
+ minItems: 1,
261
+ items: {
262
+ type: "object",
263
+ properties: {
264
+ id: { type: "string" },
265
+ title: { type: "string" },
266
+ confidence: { type: "string", enum: ["High", "Medium", "Low"] },
267
+ mechanism: { type: "string" },
268
+ code_evidence: { type: "string" },
269
+ log_signatures: { type: "array", items: { type: "string" } },
270
+ eliminates_if: { type: "string" },
271
+ },
272
+ required: ["id", "title", "confidence", "mechanism", "code_evidence", "log_signatures", "eliminates_if"],
273
+ additionalProperties: false,
274
+ },
275
+ },
276
+ what_to_grep: { type: "array", items: { type: "string" } },
277
+ timeline_question: { type: "string" },
278
+ unknowns: { type: "array", items: { type: "string" } },
279
+ },
280
+ required: ["summary", "critical_path", "hypotheses", "what_to_grep", "timeline_question", "unknowns"],
281
+ additionalProperties: false,
282
+ },
283
+ },
284
+ };
285
+
286
+ const stage2Tool = {
287
+ type: "function" as const,
288
+ function: {
289
+ name: "submit_stage2",
290
+ description: "Submit Stage 2 root cause from code + logs.",
291
+ parameters: {
292
+ type: "object",
293
+ properties: {
294
+ summary: { type: "string" },
295
+ timeline: {
296
+ type: "array",
297
+ items: {
298
+ type: "object",
299
+ properties: {
300
+ offset: { type: "string" },
301
+ event: { type: "string" },
302
+ source: { type: "string" },
303
+ },
304
+ required: ["offset", "event", "source"],
305
+ additionalProperties: false,
306
+ },
307
+ },
308
+ hypothesis_verdicts: {
309
+ type: "array",
310
+ items: {
311
+ type: "object",
312
+ properties: {
313
+ id: { type: "string" },
314
+ verdict: { type: "string", enum: ["CONFIRMED", "ELIMINATED", "POSSIBLE"] },
315
+ evidence: { type: "string" },
316
+ },
317
+ required: ["id", "verdict", "evidence"],
318
+ additionalProperties: false,
319
+ },
320
+ },
321
+ root_cause: {
322
+ type: "object",
323
+ properties: {
324
+ function: { type: "string" },
325
+ line_hint: { type: "string" },
326
+ mechanism: { type: "string" },
327
+ confidence: { type: "string", enum: ["High", "Medium", "Low"] },
328
+ },
329
+ required: ["function", "line_hint", "mechanism", "confidence"],
330
+ additionalProperties: false,
331
+ },
332
+ what_vehicle_saw: { type: "string" },
333
+ still_unknown: { type: "array", items: { type: "string" } },
334
+ },
335
+ required: ["summary", "timeline", "hypothesis_verdicts", "root_cause", "what_vehicle_saw", "still_unknown"],
336
+ additionalProperties: false,
337
+ },
338
+ },
339
+ };
340
+
341
+ const stage3Tool = {
342
+ type: "function" as const,
343
+ function: {
344
+ name: "submit_stage3",
345
+ description: "Submit Stage 3 definitive cause from code + logs + sensor data.",
346
+ parameters: {
347
+ type: "object",
348
+ properties: {
349
+ summary: { type: "string" },
350
+ failure_layer: { type: "string", enum: ["SENSING", "PROCESSING", "PLANNING", "CONTROL"] },
351
+ perception_state: {
352
+ type: "object",
353
+ properties: {
354
+ what_vehicle_saw: { type: "string" },
355
+ what_it_should_have_seen: { type: "string" },
356
+ discrepancy: { type: "string" },
357
+ },
358
+ required: ["what_vehicle_saw", "what_it_should_have_seen", "discrepancy"],
359
+ additionalProperties: false,
360
+ },
361
+ full_chain: {
362
+ type: "array",
363
+ items: {
364
+ type: "object",
365
+ properties: {
366
+ layer: { type: "string" },
367
+ input: { type: "string" },
368
+ output: { type: "string" },
369
+ issue: { type: "string" },
370
+ },
371
+ required: ["layer", "input", "output", "issue"],
372
+ additionalProperties: false,
373
+ },
374
+ },
375
+ definitive_cause: {
376
+ type: "object",
377
+ properties: {
378
+ function: { type: "string" },
379
+ mechanism: { type: "string" },
380
+ confidence: { type: "string", enum: ["High"] },
381
+ },
382
+ required: ["function", "mechanism", "confidence"],
383
+ additionalProperties: false,
384
+ },
385
+ fix: { type: "string" },
386
+ test_case: { type: "string" },
387
+ },
388
+ required: ["summary", "failure_layer", "perception_state", "full_chain", "definitive_cause", "fix", "test_case"],
389
+ additionalProperties: false,
390
+ },
391
+ },
392
+ };
393
+
394
+ const StageInput = z.object({
395
+ stage: z.union([z.literal(1), z.literal(2), z.literal(3)]),
396
+ code: z.string().min(1).max(200_000),
397
+ failureDescription: z.string().min(1).max(5_000),
398
+ logs: z.string().max(120_000).optional(),
399
+ bagData: z.string().max(120_000).optional(),
400
+ priorStage1: z.unknown().optional(),
401
+ priorStage2: z.unknown().optional(),
402
+ });
403
+
404
+ function deepRestore(value: any, rev: Map<string, string>): any {
405
+ if (typeof value === "string") return restore(value, rev);
406
+ if (Array.isArray(value)) return value.map((v) => deepRestore(v, rev));
407
+ if (value && typeof value === "object") {
408
+ const out: any = {};
409
+ for (const [k, v] of Object.entries(value)) out[k] = deepRestore(v, rev);
410
+ return out;
411
+ }
412
+ return value;
413
+ }
414
+
415
+ export const runForensicStage = createServerFn({ method: "POST" })
416
+ .inputValidator((d: unknown) => StageInput.parse(d))
417
+ .handler(async ({ data }): Promise<{ result: StageResult; sanitizationStats: { identifiersTokenized: number; commentsStripped: number; secretsBlocked: number } }> => {
418
+ const apiKey = process.env.LOVABLE_API_KEY;
419
+ if (!apiKey) throw new Error("LOVABLE_API_KEY not configured");
420
+
421
+ const codeS = sanitize(data.code);
422
+ const failureS = sanitize(data.failureDescription);
423
+ const logsS = data.logs ? sanitize(data.logs) : null;
424
+ const bagS = data.bagData ? sanitize(data.bagData) : null;
425
+
426
+ // Combine reverse maps so restore() works on AI output that references any token
427
+ const reverse = new Map<string, string>();
428
+ for (const m of [codeS.reverseMap, failureS.reverseMap, logsS?.reverseMap, bagS?.reverseMap]) {
429
+ if (m) for (const [k, v] of m.entries()) reverse.set(k, v);
430
+ }
431
+
432
+ const tools = [stage1Tool, stage2Tool, stage3Tool];
433
+ const toolName = `submit_stage${data.stage}` as const;
434
+
435
+ const userParts: string[] = [
436
+ `DEPLOYED CODE (anonymized):\n${codeS.sanitized.slice(0, 50_000)}`,
437
+ `\n\nFAILURE DESCRIPTION:\n${failureS.sanitized}`,
438
+ ];
439
+ if (data.priorStage1) userParts.push(`\n\nSTAGE 1 HYPOTHESES:\n${JSON.stringify(data.priorStage1)}`);
440
+ if (data.priorStage2) userParts.push(`\n\nSTAGE 2 ROOT CAUSE:\n${JSON.stringify(data.priorStage2)}`);
441
+ if (logsS) userParts.push(`\n\nSYSTEM LOGS (anonymized):\n${logsS.sanitized.slice(0, 40_000)}`);
442
+ if (bagS) userParts.push(`\n\nROS BAG / SENSOR DATA (anonymized):\n${bagS.sanitized.slice(0, 40_000)}`);
443
+
444
+ const resp = await fetch("https://ai.gateway.lovable.dev/v1/chat/completions", {
445
+ method: "POST",
446
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
447
+ body: JSON.stringify({
448
+ model: "google/gemini-2.5-flash",
449
+ messages: [
450
+ { role: "system", content: STAGE_PROMPTS[data.stage] },
451
+ { role: "user", content: userParts.join("") },
452
+ ],
453
+ tools,
454
+ tool_choice: { type: "function", function: { name: toolName } },
455
+ }),
456
+ });
457
+
458
+ if (!resp.ok) {
459
+ const text = await resp.text();
460
+ if (resp.status === 429) throw new Error("Rate limit reached. Try again shortly.");
461
+ if (resp.status === 402) throw new Error("AI credits exhausted. Add credits in Workspace > Usage.");
462
+ throw new Error(`AI gateway error ${resp.status}: ${text.slice(0, 300)}`);
463
+ }
464
+
465
+ const json = await resp.json();
466
+ const toolCall = json.choices?.[0]?.message?.tool_calls?.[0];
467
+ if (!toolCall?.function?.arguments) throw new Error("AI did not return structured analysis.");
468
+
469
+ const parsedRaw = JSON.parse(toolCall.function.arguments);
470
+ const restored = deepRestore(parsedRaw, reverse) as StageResult;
471
+ restored.stage = data.stage as any;
472
+
473
+ return {
474
+ result: restored,
475
+ sanitizationStats: {
476
+ identifiersTokenized:
477
+ codeS.stats.identifiersTokenized +
478
+ failureS.stats.identifiersTokenized +
479
+ (logsS?.stats.identifiersTokenized ?? 0) +
480
+ (bagS?.stats.identifiersTokenized ?? 0),
481
+ commentsStripped:
482
+ codeS.stats.commentsStripped +
483
+ (logsS?.stats.commentsStripped ?? 0) +
484
+ (bagS?.stats.commentsStripped ?? 0),
485
+ secretsBlocked:
486
+ codeS.stats.secretsBlocked +
487
+ failureS.stats.secretsBlocked +
488
+ (logsS?.stats.secretsBlocked ?? 0) +
489
+ (bagS?.stats.secretsBlocked ?? 0),
490
+ },
491
+ };
492
+ });