@clue-ai/cli 0.0.8 → 0.0.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.
@@ -1,7 +1,12 @@
1
1
  import { readFile, writeFile } from "node:fs/promises";
2
- import { isAbsolute, relative, resolve } from "node:path";
2
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { callJsonAiProvider, resolveAiProviderConfig } from "./ai-provider.mjs";
4
- import { findLifecycleGuardViolations } from "./lifecycle-guard.mjs";
4
+ import {
5
+ extractExecutableModuleStatements,
6
+ findLifecycleCallApiNames,
7
+ findLifecycleGuardViolations,
8
+ stripSourceNoise,
9
+ } from "./lifecycle-guard.mjs";
5
10
  import { listAllowedSourceFiles } from "./path-policy.mjs";
6
11
 
7
12
  const API_NAMES = new Set([
@@ -15,6 +20,10 @@ const SOURCE_EXTENSIONS = [".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
15
20
  const MAX_CONTEXT_FILES = 180;
16
21
  const MAX_FILE_CHARS = 12_000;
17
22
  const MAX_TOTAL_CHARS = 360_000;
23
+ const FRONTEND_SDK_PACKAGE = "@clue-ai/browser-sdk";
24
+ const WRONG_FRONTEND_SDK_PACKAGES = ["clue-js-sdk", "@clue/browser-sdk"];
25
+ const CLUE_SETUP_ADDITION_PATTERN =
26
+ /\b(?:ClueInit|ClueIdentify|ClueSetAccount|ClueLogout|clue_init_fastapi|clue_init_django|clue-fastapi-sdk|clue-django-sdk|CLUE_[A-Z0-9_]+|browserTokenProvider|clue[-_])|@clue-ai\/browser-sdk/i;
18
27
 
19
28
  const nonEmpty = (value, field) => {
20
29
  if (typeof value !== "string" || value.trim() === "") {
@@ -47,13 +56,35 @@ const assertNoForbiddenInstrumentation = (replacement) => {
47
56
  if (/data-clue-(id|key)/i.test(replacement)) {
48
57
  throw new Error("init tool must not add data-clue-id or data-clue-key");
49
58
  }
59
+ const wrongSdkPackage = WRONG_FRONTEND_SDK_PACKAGES.find((packageName) =>
60
+ replacement.includes(packageName),
61
+ );
62
+ if (wrongSdkPackage) {
63
+ throw new Error(
64
+ `init tool must not use wrong frontend SDK package: ${wrongSdkPackage}`,
65
+ );
66
+ }
50
67
  };
51
68
 
52
- const assertLifecycleCallsAreGuarded = (replacement) => {
69
+ const assertLifecycleCallsAreNonBlocking = (replacement) => {
53
70
  const violations = findLifecycleGuardViolations(replacement);
54
71
  if (violations.length > 0) {
55
72
  throw new Error(
56
- `Clue lifecycle calls must be failure-isolated with try/catch, try/except, or an explicit safe Clue helper: ${JSON.stringify(violations)}`,
73
+ `Clue lifecycle calls must not be awaited or block host service behavior: ${JSON.stringify(violations)}`,
74
+ );
75
+ }
76
+ };
77
+
78
+ const assertClueSetupOnlyEdit = (edit) => {
79
+ if (!edit.replace.includes(edit.find)) {
80
+ throw new Error(
81
+ `Clue lifecycle edits must be additive and preserve existing source in ${edit.file_path}`,
82
+ );
83
+ }
84
+ const addedText = edit.replace.split(edit.find).join("");
85
+ if (!CLUE_SETUP_ADDITION_PATTERN.test(addedText)) {
86
+ throw new Error(
87
+ `Clue lifecycle edits must add only Clue setup related code in ${edit.file_path}`,
57
88
  );
58
89
  }
59
90
  };
@@ -65,10 +96,34 @@ const normalizeLifecycleInsertion = (input) => ({
65
96
  reason: nonEmpty(input.reason, "reason"),
66
97
  });
67
98
 
99
+ const normalizeBlocker = (input) => {
100
+ if (typeof input === "string") {
101
+ return { reason: nonEmpty(input, "blocker.reason") };
102
+ }
103
+ if (!input || typeof input !== "object") {
104
+ throw new Error("blocker must be a string or object");
105
+ }
106
+ const blocker = {
107
+ reason: nonEmpty(input.reason, "blocker.reason"),
108
+ };
109
+ if (typeof input.evidence === "string" && input.evidence.trim()) {
110
+ blocker.evidence = input.evidence.trim();
111
+ }
112
+ return blocker;
113
+ };
114
+
68
115
  const normalizePlan = (input) => {
69
116
  if (!input || typeof input !== "object") {
70
117
  throw new Error("AI lifecycle plan must be an object");
71
118
  }
119
+ if (
120
+ input.status !== undefined &&
121
+ input.status !== "ready" &&
122
+ input.status !== "blocked"
123
+ ) {
124
+ throw new Error("AI lifecycle plan status must be ready or blocked");
125
+ }
126
+ const status = input.status === "blocked" ? "blocked" : "ready";
72
127
  if (!Array.isArray(input.edits)) {
73
128
  throw new Error("AI lifecycle plan must include edits");
74
129
  }
@@ -80,9 +135,25 @@ const normalizePlan = (input) => {
80
135
  const lifecycleInsertions = Array.isArray(input.lifecycle_insertions)
81
136
  ? input.lifecycle_insertions.map(normalizeLifecycleInsertion)
82
137
  : [];
138
+ const blockers = Array.isArray(input.blockers)
139
+ ? input.blockers.map(normalizeBlocker)
140
+ : [];
141
+ if (status === "blocked") {
142
+ if (edits.length > 0 || lifecycleInsertions.length > 0) {
143
+ throw new Error("blocked lifecycle plan must not include edits");
144
+ }
145
+ if (blockers.length === 0) {
146
+ throw new Error("blocked lifecycle plan must include blockers");
147
+ }
148
+ }
149
+ if (status === "ready" && blockers.length > 0) {
150
+ throw new Error("ready lifecycle plan must not include blockers");
151
+ }
83
152
  return {
153
+ status,
84
154
  edits,
85
155
  lifecycleInsertions,
156
+ blockers,
86
157
  warnings: Array.isArray(input.warnings)
87
158
  ? input.warnings
88
159
  .filter((warning) => typeof warning === "string" && warning.trim())
@@ -91,24 +162,352 @@ const normalizePlan = (input) => {
91
162
  };
92
163
  };
93
164
 
165
+ const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
166
+
167
+ const sourceImportsFrontendSdk = (text) =>
168
+ extractExecutableModuleStatements(text).some((statement) =>
169
+ new RegExp(
170
+ `(?:from\\s*["']${escapeRegex(FRONTEND_SDK_PACKAGE)}["']|import\\s*["']${escapeRegex(FRONTEND_SDK_PACKAGE)}["'])`,
171
+ ).test(statement),
172
+ );
173
+
174
+ const parseNamedSpecifiers = (specifiers) =>
175
+ specifiers
176
+ .split(",")
177
+ .map((specifier) => specifier.trim())
178
+ .filter(Boolean)
179
+ .map((specifier) => {
180
+ const match = /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(
181
+ specifier,
182
+ );
183
+ if (!match) return null;
184
+ return {
185
+ imported: match[1],
186
+ local: match[2] ?? match[1],
187
+ exported: match[2] ?? match[1],
188
+ };
189
+ })
190
+ .filter(Boolean);
191
+
192
+ const sourceDirectlyProvidesApiFromFrontendSdk = (text, apiName) => {
193
+ const statements = extractExecutableModuleStatements(text).join("\n");
194
+ for (const match of statements.matchAll(
195
+ /import\s*{([^}]+)}\s*from\s*["']([^"']+)["']/g,
196
+ )) {
197
+ if (match[2] !== FRONTEND_SDK_PACKAGE) continue;
198
+ if (
199
+ parseNamedSpecifiers(match[1]).some(
200
+ (specifier) =>
201
+ specifier.imported === apiName && specifier.local === apiName,
202
+ )
203
+ ) {
204
+ return true;
205
+ }
206
+ }
207
+ for (const match of statements.matchAll(
208
+ /export\s*{([^}]+)}\s*from\s*["']([^"']+)["']/g,
209
+ )) {
210
+ if (match[2] !== FRONTEND_SDK_PACKAGE) continue;
211
+ if (
212
+ parseNamedSpecifiers(match[1]).some(
213
+ (specifier) =>
214
+ specifier.imported === apiName && specifier.exported === apiName,
215
+ )
216
+ ) {
217
+ return true;
218
+ }
219
+ }
220
+ return false;
221
+ };
222
+
223
+ const frontendSdkImportedLocalsForApi = (text, apiName) => {
224
+ const locals = [];
225
+ for (const match of extractExecutableModuleStatements(text)
226
+ .join("\n")
227
+ .matchAll(/import\s*{([^}]+)}\s*from\s*["']([^"']+)["']/g)) {
228
+ if (match[2] !== FRONTEND_SDK_PACKAGE) continue;
229
+ for (const specifier of parseNamedSpecifiers(match[1])) {
230
+ if (specifier.imported === apiName) {
231
+ locals.push(specifier.local);
232
+ }
233
+ }
234
+ }
235
+ return locals;
236
+ };
237
+
238
+ const frontendSdkNamespaces = (text) =>
239
+ [
240
+ ...extractExecutableModuleStatements(text)
241
+ .join("\n")
242
+ .matchAll(
243
+ /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']([^"']+)["']/g,
244
+ ),
245
+ ]
246
+ .filter((match) => match[2] === FRONTEND_SDK_PACKAGE)
247
+ .map((match) => match[1]);
248
+
249
+ const sourceExportsLocalAsApi = (text, localName, apiName) => {
250
+ const statements = extractExecutableModuleStatements(text).join("\n");
251
+ for (const match of statements.matchAll(
252
+ /export\s*{([^}]+)}(?:\s*from\s*["'][^"']+["'])?/g,
253
+ )) {
254
+ if (match[0].includes(" from ")) continue;
255
+ if (
256
+ parseNamedSpecifiers(match[1]).some(
257
+ (specifier) =>
258
+ specifier.imported === localName && specifier.exported === apiName,
259
+ )
260
+ ) {
261
+ return true;
262
+ }
263
+ }
264
+ return new RegExp(
265
+ `export\\s+const\\s+${escapeRegex(apiName)}\\s*=\\s*${escapeRegex(localName)}\\b`,
266
+ ).test(statements);
267
+ };
268
+
269
+ const sourceForwardsFrontendSdkApi = (source, apiName) => {
270
+ const text = source.text;
271
+ if (sourceDirectlyProvidesApiFromFrontendSdk(text, apiName)) return true;
272
+ const importedLocals = frontendSdkImportedLocalsForApi(text, apiName);
273
+ if (
274
+ importedLocals.some((localName) =>
275
+ sourceExportsLocalAsApi(text, localName, apiName),
276
+ )
277
+ ) {
278
+ return true;
279
+ }
280
+ return frontendSdkNamespaces(text).some((namespaceName) =>
281
+ new RegExp(
282
+ `export\\s+const\\s+${escapeRegex(apiName)}\\s*=\\s*${escapeRegex(namespaceName)}\\.${escapeRegex(apiName)}\\b`,
283
+ ).test(text),
284
+ );
285
+ };
286
+
287
+ const localImportSpecifiersForApi = (text, apiName) =>
288
+ [
289
+ ...extractExecutableModuleStatements(text)
290
+ .join("\n")
291
+ .matchAll(/import\s*{([^}]+)}\s*from\s*["']([^"']+)["']/g),
292
+ ]
293
+ .filter((match) => match[2].startsWith(".") || match[2].startsWith("@/"))
294
+ .flatMap((match) =>
295
+ parseNamedSpecifiers(match[1])
296
+ .filter(
297
+ (specifier) =>
298
+ specifier.imported === apiName && specifier.local === apiName,
299
+ )
300
+ .map(() => match[2]),
301
+ );
302
+
303
+ const importSpecifiers = (text) =>
304
+ [
305
+ ...extractExecutableModuleStatements(text)
306
+ .join("\n")
307
+ .matchAll(/import\s+(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g),
308
+ ]
309
+ .map((match) => match[1] ?? match[2])
310
+ .filter(Boolean);
311
+
312
+ const candidateSourcePaths = (basePath) => [
313
+ basePath,
314
+ ...SOURCE_EXTENSIONS.map((extension) => `${basePath}${extension}`),
315
+ ...SOURCE_EXTENSIONS.map((extension) => join(basePath, `index${extension}`)),
316
+ ];
317
+
318
+ const localImportCandidatePaths = ({ importerPath, specifier }) => {
319
+ const candidates = [];
320
+ if (specifier.startsWith(".")) {
321
+ candidates.push(
322
+ ...candidateSourcePaths(join(dirname(importerPath), specifier)),
323
+ );
324
+ }
325
+ if (specifier.startsWith("@/")) {
326
+ const srcIndex = importerPath.lastIndexOf("/src/");
327
+ if (srcIndex >= 0) {
328
+ candidates.push(
329
+ ...candidateSourcePaths(
330
+ join(
331
+ importerPath.slice(0, srcIndex + "/src".length),
332
+ specifier.slice(2),
333
+ ),
334
+ ),
335
+ );
336
+ }
337
+ for (const root of [
338
+ "src",
339
+ "frontend/src",
340
+ "apps/web/src",
341
+ "apps/admin/src",
342
+ "apps/visitor/src",
343
+ ]) {
344
+ candidates.push(...candidateSourcePaths(join(root, specifier.slice(2))));
345
+ }
346
+ }
347
+ return candidates;
348
+ };
349
+
350
+ const resolveLocalSource = ({ importerPath, sourceByPath, specifier }) => {
351
+ const candidates = localImportCandidatePaths({ importerPath, specifier });
352
+ return candidates
353
+ .map((candidate) => sourceByPath.get(candidate))
354
+ .find(Boolean);
355
+ };
356
+
357
+ const fileLooksFrontend = (filePath) =>
358
+ /\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(filePath);
359
+
360
+ const hasVerifiedFrontendSdkAccess = ({ apiName, source, sourceByPath }) => {
361
+ if (sourceDirectlyProvidesApiFromFrontendSdk(source.text, apiName))
362
+ return true;
363
+ return localImportSpecifiersForApi(source.text, apiName).some((specifier) => {
364
+ const importedSource = resolveLocalSource({
365
+ importerPath: source.file_path,
366
+ sourceByPath,
367
+ specifier,
368
+ });
369
+ return importedSource
370
+ ? sourceForwardsFrontendSdkApi(importedSource, apiName)
371
+ : false;
372
+ });
373
+ };
374
+
375
+ const assertLifecycleInsertionEvidence = async ({
376
+ insertion,
377
+ source,
378
+ sourceByPath,
379
+ }) => {
380
+ const executableSource = stripSourceNoise(source.text, {
381
+ stripStrings: true,
382
+ });
383
+ if (
384
+ !findLifecycleCallApiNames(executableSource).includes(insertion.api_name)
385
+ ) {
386
+ throw new Error(
387
+ `lifecycle insertion evidence missing ${insertion.api_name} call in ${insertion.file_path}`,
388
+ );
389
+ }
390
+ const blocking = findLifecycleGuardViolations(executableSource).filter(
391
+ (violation) => violation.api_name === insertion.api_name,
392
+ );
393
+ if (blocking.length > 0) {
394
+ throw new Error(
395
+ `lifecycle insertion evidence contains blocking ${insertion.api_name} call in ${insertion.file_path}`,
396
+ );
397
+ }
398
+ if (
399
+ fileLooksFrontend(insertion.file_path) &&
400
+ !hasVerifiedFrontendSdkAccess({
401
+ apiName: insertion.api_name,
402
+ source,
403
+ sourceByPath,
404
+ })
405
+ ) {
406
+ throw new Error(
407
+ `lifecycle insertion evidence for ${insertion.api_name} in ${insertion.file_path} does not resolve to ${FRONTEND_SDK_PACKAGE}`,
408
+ );
409
+ }
410
+ };
411
+
412
+ const loadSourceIntoMap = async ({ repoRoot, sourceByPath, filePath }) => {
413
+ if (sourceByPath.has(filePath)) return;
414
+ const { absolutePath, relativePath } = safeRelativePath(repoRoot, filePath);
415
+ sourceByPath.set(relativePath, {
416
+ file_path: relativePath,
417
+ text: await readFile(absolutePath, "utf8"),
418
+ });
419
+ };
420
+
421
+ const buildLifecycleEvidenceSourceMap = async ({
422
+ repoRoot,
423
+ plan,
424
+ sourceByPath = new Map(),
425
+ }) => {
426
+ for (const filePath of [
427
+ ...new Set([
428
+ ...plan.edits.map((edit) => edit.file_path),
429
+ ...plan.lifecycleInsertions.map((insertion) => insertion.file_path),
430
+ ]),
431
+ ]) {
432
+ await loadSourceIntoMap({ repoRoot, sourceByPath, filePath });
433
+ }
434
+ for (const source of [...sourceByPath.values()]) {
435
+ for (const specifier of importSpecifiers(source.text)) {
436
+ for (const candidate of localImportCandidatePaths({
437
+ importerPath: source.file_path,
438
+ specifier,
439
+ })) {
440
+ try {
441
+ await loadSourceIntoMap({
442
+ repoRoot,
443
+ sourceByPath,
444
+ filePath: candidate,
445
+ });
446
+ break;
447
+ } catch (error) {
448
+ if (error?.code !== "ENOENT") throw error;
449
+ }
450
+ }
451
+ }
452
+ }
453
+ return sourceByPath;
454
+ };
455
+
94
456
  export const applyLifecyclePlan = async ({ repoRoot, plan: rawPlan }) => {
95
457
  const plan = normalizePlan(rawPlan);
458
+ if (plan.status === "blocked") {
459
+ throw new Error(
460
+ `AI lifecycle plan blocked: ${plan.blockers
461
+ .map((blocker) =>
462
+ blocker.evidence
463
+ ? `${blocker.reason} (${blocker.evidence})`
464
+ : blocker.reason,
465
+ )
466
+ .join("; ")}`,
467
+ );
468
+ }
469
+ const sourceByPath = new Map();
470
+ const pendingWrites = new Map();
96
471
  for (const edit of plan.edits) {
97
- const { absolutePath } = safeRelativePath(repoRoot, edit.file_path);
472
+ const { absolutePath, relativePath } = safeRelativePath(
473
+ repoRoot,
474
+ edit.file_path,
475
+ );
98
476
  assertNoForbiddenInstrumentation(edit.replace);
99
- const current = await readFile(absolutePath, "utf8");
477
+ const current =
478
+ sourceByPath.get(relativePath)?.text ??
479
+ (await readFile(absolutePath, "utf8"));
100
480
  const occurrences = current.split(edit.find).length - 1;
101
481
  if (occurrences !== 1) {
102
482
  throw new Error(
103
483
  `edit.find must match exactly once in ${edit.file_path}; matched ${occurrences}`,
104
484
  );
105
485
  }
106
- assertLifecycleCallsAreGuarded(edit.replace);
107
- await writeFile(
108
- absolutePath,
109
- current.replace(edit.find, edit.replace),
110
- "utf8",
111
- );
486
+ assertClueSetupOnlyEdit(edit);
487
+ assertLifecycleCallsAreNonBlocking(edit.replace);
488
+ const next = current.replace(edit.find, edit.replace);
489
+ sourceByPath.set(relativePath, {
490
+ file_path: relativePath,
491
+ text: next,
492
+ });
493
+ pendingWrites.set(relativePath, { absolutePath, text: next });
494
+ }
495
+ await buildLifecycleEvidenceSourceMap({ repoRoot, plan, sourceByPath });
496
+ for (const insertion of plan.lifecycleInsertions) {
497
+ const source = sourceByPath.get(insertion.file_path);
498
+ if (!source) {
499
+ throw new Error(
500
+ `lifecycle insertion evidence file missing: ${insertion.file_path}`,
501
+ );
502
+ }
503
+ await assertLifecycleInsertionEvidence({
504
+ insertion,
505
+ source,
506
+ sourceByPath,
507
+ });
508
+ }
509
+ for (const write of pendingWrites.values()) {
510
+ await writeFile(write.absolutePath, write.text, "utf8");
112
511
  }
113
512
  return {
114
513
  lifecycleInsertions: plan.lifecycleInsertions,
@@ -148,16 +547,19 @@ const buildLifecyclePrompt = ({ request, files }) =>
148
547
  "Return JSON only.",
149
548
  "Use only exact replacements. Each find string must be copied exactly from source.",
150
549
  "Add ClueInit, ClueIdentify, ClueSetAccount, and ClueLogout where repository code has clear lifecycle points.",
151
- "Every Clue lifecycle call must be failure-isolated. If Clue fails, the host service must continue without throwing, rejecting, or blocking login/API behavior.",
152
- "Use a small safe Clue helper, local try/catch/try/except wrapper, or direct .catch handler around Clue lifecycle calls.",
550
+ "Official Clue SDK public lifecycle APIs are no-throw and own SDK failure isolation.",
551
+ "Do not add per-call try/catch, try/except, .catch, or custom safe wrappers solely around official Clue SDK public lifecycle calls.",
552
+ "Do not create no-op wrappers, placeholder lifecycle functions, fake SDK modules, window.Clue* shims, or helpers that swallow calls without forwarding them to a real Clue SDK import.",
553
+ "Custom repository adapters are allowed only when they demonstrably forward to the real Clue SDK.",
153
554
  "Never await a Clue lifecycle call in a way that can block login, logout, account selection, request handling, page rendering, or API responses.",
154
555
  "Find all clear login success paths and add ClueIdentify to every one of them. Do not stop after the first login flow.",
155
556
  "Find all clear account, workspace, organization, or tenant resolution paths and add ClueSetAccount to every one of them.",
156
557
  "Find all clear logout or session reset paths and add ClueLogout to every one of them.",
157
558
  "Inspect backend lifecycle points as carefully as frontend lifecycle points. Backend login/session/account code is especially important.",
559
+ "For frontend code, add or use the real @clue-ai/browser-sdk dependency. Do not invent clue-js-sdk, @clue/browser-sdk, local SDK modules, global window.Clue APIs, or dynamic imports that hide a missing SDK.",
158
560
  "For FastAPI backends, add the clue-fastapi-sdk dependency when missing, import clue_init_fastapi plus ClueIdentify/ClueSetAccount/ClueLogout where needed, and initialize the SDK at FastAPI app creation.",
159
- "For Django backends, add the clue-django-sdk dependency when missing, import the Django SDK lifecycle helpers where needed, and initialize the SDK in the Django integration point.",
160
- "For other backend frameworks, use the matching Clue backend SDK if one exists; if no backend SDK exists, report a blocker instead of silently frontend-only setup.",
561
+ "For Django backends, use clue-django-sdk only after dependency or registry verification confirms it is installable. If it cannot be verified, report a blocker instead of adding guessed imports or dependencies.",
562
+ "For other backend frameworks, treat SDK existence as unverified unless present in dependency files or verified through package-manager/official documentation. If no backend SDK exists or verification is impossible, report a blocker instead of silently frontend-only setup.",
161
563
  "Do not add broad ClueTrack instrumentation.",
162
564
  "Do not add data-clue-id, data-clue-key, or similar DOM tags.",
163
565
  "Do not create route semantics files or layer files.",
@@ -166,9 +568,15 @@ const buildLifecyclePrompt = ({ request, files }) =>
166
568
  "Prefer stable ids and non-PII booleans/counts for ClueIdentify and ClueSetAccount traits.",
167
569
  "Use environment variable names for Clue configuration values.",
168
570
  "For Python/FastAPI code, read CLUE_PROJECT_KEY, CLUE_ENVIRONMENT, CLUE_API_KEY, and CLUE_INGEST_ENDPOINT from environment variables.",
169
- "For browser code, read CLUE_PROJECT_KEY, CLUE_ENVIRONMENT, and CLUE_INGEST_ENDPOINT from environment variables through the target framework's safe client config mechanism. Do not hard-code a Next.js-only prefix.",
571
+ "For browser code, read CLUE_PROJECT_KEY, CLUE_ENVIRONMENT, CLUE_SERVICE_KEY, and CLUE_INGEST_ENDPOINT from environment variables through the target framework's safe client config mechanism. Do not hard-code a Next.js-only prefix.",
572
+ "Never place CLUE_API_KEY in frontend code, frontend env files, browser bundles, or client-readable config.",
573
+ "When browser SDK ingest is configured, implement a backend-owned browser token endpoint that reads server-side CLUE_API_KEY and requests POST /api/v1/ingest/browser-tokens from Clue.",
574
+ "Configure frontend ClueInit with browserTokenProvider that calls the local backend token endpoint and returns the token string.",
575
+ "The browser token request must include project key, environment, service key, and the current browser origin; the backend must attach x-clue-api-key server-side when calling Clue.",
170
576
  "Prefer minimal edits that engineers can review in one PR.",
171
577
  "If a lifecycle point is unclear, skip that edit and include a warning.",
578
+ "Return status ready only when edits are safe to apply. Return status blocked when required SDKs or lifecycle points cannot be verified.",
579
+ "If status is blocked, return no edits and no lifecycle_insertions, and list blockers. Do not encode blockers as warnings.",
172
580
  ],
173
581
  repository_context: {
174
582
  target_tool: request.target_tool,
@@ -180,9 +588,12 @@ const buildLifecyclePrompt = ({ request, files }) =>
180
588
  clue_api_base_url_env: "CLUE_API_BASE_URL",
181
589
  clue_ingest_endpoint_env: "CLUE_INGEST_ENDPOINT",
182
590
  browser_ingest_endpoint_env: "CLUE_INGEST_ENDPOINT",
591
+ browser_token_endpoint_path: "/api/v1/ingest/browser-tokens",
183
592
  service_key: request.service_key,
184
593
  },
185
594
  output_shape: {
595
+ status: "ready",
596
+ blockers: [],
186
597
  edits: [
187
598
  {
188
599
  file_path: "app/main.py",
@@ -76,6 +76,10 @@ const clueInitToolReportSchema = zod_1.z.object({
76
76
  semantic_generation_timing: zod_1.z.literal("after_merge_ci"),
77
77
  semantic_preview_generated: zod_1.z.literal(false),
78
78
  client_repo_generated_files_committed: zod_1.z.literal(false),
79
+ frontend_api_key_exposed: zod_1.z.literal(false),
80
+ browser_token_endpoint_required: zod_1.z.literal(true),
81
+ browser_token_provider_required: zod_1.z.literal(true),
82
+ browser_token_endpoint_path: nonEmptyStringSchema,
79
83
  clue_track_inserted: zod_1.z.literal(false),
80
84
  clue_dom_tag_inserted: zod_1.z.literal(false),
81
85
  allowed_source_paths: zod_1.z.array(nonEmptyStringSchema),
@@ -1,3 +1,5 @@
1
+ import { clueCliCommand } from "./cli-invocation.mjs";
2
+
1
3
  export const SEMANTIC_AGENT_RUNNER_VERSION = "semantic-agent-runner-v1";
2
4
 
3
5
  export const SEMANTIC_AGENT_ROLE_IDS = {
@@ -14,7 +16,7 @@ const requiredRoleIds = new Set(Object.values(SEMANTIC_AGENT_ROLE_IDS));
14
16
  export const semanticAgentSkillBundle = () => ({
15
17
  runner_version: SEMANTIC_AGENT_RUNNER_VERSION,
16
18
  execution_model: "ci_semantic_agent_runner",
17
- ci_entrypoint: "clue-ai semantic-gen",
19
+ ci_entrypoint: clueCliCommand("semantic-gen"),
18
20
  rules: [
19
21
  "GitHub Actions runs only the CLI; the CLI owns route coverage, AI role orchestration, schema validation, and upload.",
20
22
  "Mechanically scan every route before any AI call.",