fraim-framework 2.0.34 → 2.0.36

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 (49) hide show
  1. package/bin/fraim.js +52 -5
  2. package/dist/registry/scripts/cleanup-branch.js +62 -33
  3. package/dist/registry/scripts/generate-engagement-emails.js +119 -44
  4. package/dist/registry/scripts/newsletter-helpers.js +208 -268
  5. package/dist/registry/scripts/profile-server.js +387 -0
  6. package/dist/tests/test-chalk-regression.js +18 -2
  7. package/dist/tests/test-client-scripts-validation.js +133 -0
  8. package/dist/tests/test-markdown-to-pdf.js +454 -0
  9. package/dist/tests/test-script-location-independence.js +76 -28
  10. package/package.json +5 -2
  11. package/registry/agent-guardrails.md +62 -62
  12. package/registry/rules/communication.md +121 -121
  13. package/registry/rules/continuous-learning.md +54 -54
  14. package/registry/rules/hitl-ppe-record-analysis.md +302 -302
  15. package/registry/rules/software-development-lifecycle.md +104 -104
  16. package/registry/scripts/cleanup-branch.ts +341 -0
  17. package/registry/scripts/code-quality-check.sh +559 -559
  18. package/registry/scripts/detect-tautological-tests.sh +38 -38
  19. package/registry/scripts/generate-engagement-emails.ts +830 -0
  20. package/registry/scripts/markdown-to-pdf.js +395 -0
  21. package/registry/scripts/newsletter-helpers.ts +777 -0
  22. package/registry/scripts/profile-server.ts +424 -0
  23. package/registry/scripts/run-thank-you-workflow.ts +122 -0
  24. package/registry/scripts/send-newsletter-simple.ts +102 -0
  25. package/registry/scripts/send-thank-you-emails.ts +57 -0
  26. package/registry/scripts/validate-openapi-limits.ts +366 -366
  27. package/registry/scripts/validate-test-coverage.ts +280 -280
  28. package/registry/scripts/verify-pr-comments.sh +70 -70
  29. package/registry/templates/bootstrap/ARCHITECTURE-TEMPLATE.md +53 -53
  30. package/registry/templates/evidence/Implementation-BugEvidence.md +85 -85
  31. package/registry/templates/evidence/Implementation-FeatureEvidence.md +120 -120
  32. package/registry/workflows/convert-to-pdf.md +235 -0
  33. package/registry/workflows/customer-development/insight-analysis.md +156 -156
  34. package/registry/workflows/customer-development/interview-preparation.md +421 -421
  35. package/registry/workflows/customer-development/strategic-brainstorming.md +146 -146
  36. package/registry/workflows/quality-assurance/iterative-improvement-cycle.md +562 -562
  37. package/registry/workflows/reviewer/review-implementation-vs-feature-spec.md +669 -669
  38. package/dist/registry/scripts/build-scripts-generator.js +0 -205
  39. package/dist/registry/scripts/fraim-config.js +0 -61
  40. package/dist/registry/scripts/generic-issues-api.js +0 -100
  41. package/dist/registry/scripts/openapi-generator.js +0 -664
  42. package/dist/registry/scripts/performance/profile-server.js +0 -390
  43. package/dist/test-utils.js +0 -96
  44. package/dist/tests/esm-compat.js +0 -11
  45. package/dist/tests/test-chalk-esm-issue.js +0 -159
  46. package/dist/tests/test-chalk-real-world.js +0 -265
  47. package/dist/tests/test-chalk-resolution-issue.js +0 -304
  48. package/dist/tests/test-fraim-install-chalk-issue.js +0 -254
  49. package/dist/tests/test-npm-resolution-diagnostic.js +0 -140
@@ -0,0 +1,830 @@
1
+ #!/usr/bin/env tsx
2
+
3
+ /**
4
+ * Engagement Email Functions for AI Agents
5
+ *
6
+ * Helper functions for AI agents to use in customer engagement workflows.
7
+ * Provides deterministic functions for issue retrieval, database lookup, and email sending.
8
+ */
9
+
10
+ import { execSync } from 'child_process';
11
+ import { readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
12
+ import { MongoClient } from 'mongodb';
13
+ import { join } from 'path';
14
+
15
+ // Self-contained utility functions (no FRAIM internal imports)
16
+ function determineDatabaseName(): string {
17
+ const env = process.env.NODE_ENV || process.env.ENVIRONMENT;
18
+ // If explicitly set to ppe/staging, use that; otherwise default to prod
19
+ if (env === 'ppe' || env === 'staging') {
20
+ return 'fraim_ppe';
21
+ }
22
+ // Default to production
23
+ return process.env.MONGO_DB_NAME || 'fraim_prod';
24
+ }
25
+
26
+ function determineSchema(branchName: string): string {
27
+ if (branchName.includes('ppe') || branchName.includes('staging')) return 'ppe';
28
+ return 'prod';
29
+ }
30
+
31
+ function getCurrentGitBranch(): string {
32
+ try {
33
+ return execSync('git branch --show-current', { encoding: 'utf8' }).trim();
34
+ } catch (error) {
35
+ return 'master';
36
+ }
37
+ }
38
+
39
+ interface FraimConfig {
40
+ persona: { name: string; displayNamePattern: string; emailSignature: string };
41
+ git: { repoOwner: string; repoName: string };
42
+ database: { identityCollection: string; executiveCollection: string };
43
+ marketing: { websiteUrl?: string; chatUrl?: string };
44
+ }
45
+
46
+ function loadClientConfig(): FraimConfig {
47
+ const configPath = join(process.cwd(), '.fraim', 'config.json');
48
+ if (!existsSync(configPath)) {
49
+ throw new Error('.fraim/config.json not found. Run fraim init first.');
50
+ }
51
+ return JSON.parse(readFileSync(configPath, 'utf-8'));
52
+ }
53
+
54
+ function getEnvOr(keys: string[], fallback: string): string {
55
+ for (const key of keys) {
56
+ const value = process.env[key];
57
+ if (value && value.length) return value;
58
+ }
59
+ return fallback;
60
+ }
61
+
62
+ // Load configuration
63
+ const config = loadClientConfig();
64
+ const personaName = config.persona.name;
65
+ const personaDisplayNameDefault = config.persona.displayNamePattern.replace('{executiveName}', 'Your');
66
+
67
+ const fraimConfig = {
68
+ repoOwner: config.git.repoOwner || 'mathursrus',
69
+ repoName: config.git.repoName || 'fraim-repo',
70
+ projectName: 'FRAIM',
71
+ personaName,
72
+ personaPronouns: getEnvOr(['FRAIM_PERSONA_PRONOUNS'], 'they/them'),
73
+ personaDisplayName: getEnvOr(['FRAIM_PERSONA_DISPLAY_NAME'], personaDisplayNameDefault),
74
+ personaDisplayNamePattern: config.persona.displayNamePattern,
75
+ personaThankYouSignature: config.persona.emailSignature,
76
+ defaultEmail: getEnvOr(['FRAIM_DEFAULT_EMAIL'], 'agent@example.com'),
77
+ prodDefaultEmail: getEnvOr(['PROD_FRAIM_DEFAULT_EMAIL'], 'agent@example.com'),
78
+ defaultAccessToken: getEnvOr(['FRAIM_DEFAULT_ACCESS_TOKEN'], ''),
79
+ defaultRefreshToken: getEnvOr(['FRAIM_DEFAULT_REFRESH_TOKEN'], ''),
80
+ prodAccessToken: getEnvOr(['PROD_FRAIM_DEFAULT_ACCESS_TOKEN'], ''),
81
+ prodRefreshToken: getEnvOr(['PROD_FRAIM_DEFAULT_REFRESH_TOKEN'], ''),
82
+ defaultOAuthClientId: getEnvOr(['FRAIM_DEFAULT_OAUTH_CLIENT_ID'], ''),
83
+ defaultOAuthClientSecret: getEnvOr(['FRAIM_DEFAULT_OAUTH_CLIENT_SECRET'], ''),
84
+ prodOAuthClientId: getEnvOr(['PROD_FRAIM_DEFAULT_OAUTH_CLIENT_ID'], ''),
85
+ prodOAuthClientSecret: getEnvOr(['PROD_FRAIM_DEFAULT_OAUTH_CLIENT_SECRET'], ''),
86
+ identityCollection: config.database?.identityCollection || 'Identity',
87
+ executiveCollection: config.database?.executiveCollection || 'Executive',
88
+ newsletterTitle: 'Weekly Update',
89
+ newsletterCtaText: 'Learn More',
90
+ newsletterUrl: getEnvOr(['FRAIM_NEWSLETTER_URL'], ''),
91
+ issueRepoUrl: `https://github.com/${config.git.repoOwner}/${config.git.repoName}.git`,
92
+ identityTokensCollection: 'Tokens',
93
+ webAppUrl: config.marketing?.websiteUrl || getEnvOr(['FRAIM_WEB_APP_URL'], 'http://localhost:3000'),
94
+ chatUrl: config.marketing?.chatUrl || getEnvOr(['FRAIM_CHAT_URL'], ''),
95
+ };
96
+
97
+ function formatExecutiveDisplayName(executiveName: string): string {
98
+ return config.persona.displayNamePattern.replace('{executiveName}', executiveName);
99
+ }
100
+
101
+ function formatPersonaSignature(): string {
102
+ return `With gratitude,\n${fraimConfig.personaThankYouSignature}\n${personaName} - Your AI Executive Assistant\n\n`;
103
+ }
104
+
105
+ // Get template path (relative to script location)
106
+ function getTemplatePath(): string {
107
+ // Script is at <this-path>
108
+ // Template is at templates/customer-development/thank-you-email-template.html (Retrieve via get_fraim_file)
109
+ // Or generic path? Let's keep existing path logic but relative to process.cwd() as before
110
+ return join(process.cwd(), 'registry', 'templates', 'customer-development', 'thank-you-email-template.html');
111
+ }
112
+
113
+ interface ResolvedIssue {
114
+ number: number;
115
+ title: string;
116
+ body: string;
117
+ closed_at: string;
118
+ user: {
119
+ login: string;
120
+ };
121
+ labels: Array<{
122
+ name: string;
123
+ }>;
124
+ }
125
+
126
+ interface Executive {
127
+ id?: string; // Executive ID (used in the identity collection)
128
+ _id?: string | any; // MongoDB ObjectId (may be present but we use 'id')
129
+ email: string;
130
+ name: string;
131
+ personaAccessToken?: string;
132
+ personaRefreshToken?: string;
133
+ }
134
+
135
+ /**
136
+ * Get the latest date from existing thank-you candidates files
137
+ * Returns the most recent date when thank-you emails were sent, or null if no files exist
138
+ */
139
+ export function getLatestThankYouDate(): string | null {
140
+ const notesDir = 'docs/customer-development/thank-you-notes';
141
+ if (!existsSync(notesDir)) {
142
+ return null;
143
+ }
144
+
145
+ const files = readdirSync(notesDir).filter(f => f.startsWith('thank-you-candidates-') && f.endsWith('.json'));
146
+ if (files.length === 0) {
147
+ return null;
148
+ }
149
+
150
+ // Extract dates from filenames (e.g., thank-you-candidates-2025-10-29.json)
151
+ const dates: string[] = [];
152
+ for (const file of files) {
153
+ const dateMatch = file.match(/thank-you-candidates-(\d{4}-\d{2}-\d{2})\.json/);
154
+ if (dateMatch) {
155
+ const filePath = join(notesDir, file);
156
+ try {
157
+ const content = readFileSync(filePath, 'utf-8');
158
+ const json = JSON.parse(content);
159
+
160
+ // Check if any candidates have status "sent"
161
+ const hasSentEmails = json.candidates?.some((c: any) => c.status === 'sent');
162
+ if (hasSentEmails) {
163
+ dates.push(dateMatch[1]);
164
+ }
165
+ } catch (error) {
166
+ // Skip invalid JSON files
167
+ console.warn(`⚠️ Could not parse ${file}:`, error);
168
+ }
169
+ }
170
+ }
171
+
172
+ if (dates.length === 0) {
173
+ return null;
174
+ }
175
+
176
+ // Return the most recent date
177
+ dates.sort();
178
+ const latestDate = dates[dates.length - 1];
179
+ console.log(`📅 Latest thank-you date found: ${latestDate}`);
180
+ return latestDate;
181
+ }
182
+
183
+ /**
184
+ * Get resolved issues since a specified date (or latest thank-you date if not provided)
185
+ * AI agents call this to retrieve issues that were resolved
186
+ * @param date Optional date string (YYYY-MM-DD). If not provided, uses latest thank-you date. If no thank-you files exist, uses last 14 days.
187
+ */
188
+ export async function getResolvedIssues(date?: string): Promise<ResolvedIssue[]> {
189
+ if (!date) {
190
+ // Try to get the latest thank-you date
191
+ const latestThankYouDate = getLatestThankYouDate();
192
+ if (latestThankYouDate) {
193
+ date = latestThankYouDate;
194
+ console.log(`📋 Using latest thank-you date as starting point: ${date}`);
195
+ } else {
196
+ // Fallback to last 14 days if no thank-you files exist
197
+ const fallbackDate = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
198
+ date = fallbackDate;
199
+ console.log(`📋 No previous thank-you files found, using last 14 days: ${date}`);
200
+ }
201
+ }
202
+
203
+ // Use ">YYYY-MM-DD" format to get issues updated AFTER the date (not on the date)
204
+ // GitHub CLI requires quotes around the comparison operator
205
+ const command = `gh search issues --repo=${fraimConfig.repoOwner}/${fraimConfig.repoName} --state=closed --updated=">${date}" --label=user-reported --json number,title,body,labels,closedAt,author`;
206
+ const output = execSync(command, { encoding: 'utf-8' });
207
+ return JSON.parse(output);
208
+ }
209
+
210
+ function getProductionDatabase() {
211
+ const mongoUrl = process.env.PROD_MONGO_DATABASE_URL || process.env.MONGO_DATABASE_URL;
212
+ if (!mongoUrl) {
213
+ throw new Error('PROD_MONGO_DATABASE_URL or MONGO_DATABASE_URL environment variable is required');
214
+ }
215
+ return new MongoClient(mongoUrl);
216
+ }
217
+
218
+ /**
219
+ * Get database name, defaulting to production
220
+ */
221
+ function getDatabaseName(): string {
222
+ const env = process.env.NODE_ENV || process.env.ENVIRONMENT;
223
+ // If explicitly set to ppe/staging, use that; otherwise default to prod
224
+ if (env === 'ppe' || env === 'staging') {
225
+ return determineDatabaseName();
226
+ }
227
+ // Default to production
228
+ return process.env.MONGO_DB_NAME || 'fraim_prod';
229
+ }
230
+
231
+ /**
232
+ * Get collection name with schema prefix (defaults to prod schema)
233
+ */
234
+ function getCollectionName(baseName: string): string {
235
+ const env = process.env.NODE_ENV || process.env.ENVIRONMENT;
236
+ // If explicitly set to ppe/staging, use that schema; otherwise default to prod
237
+ if (env === 'ppe' || env === 'staging') {
238
+ const schema = determineSchema(getCurrentGitBranch());
239
+ return `${schema}_${baseName}`;
240
+ }
241
+ // Default to prod schema
242
+ return `prod_${baseName}`;
243
+ }
244
+
245
+ /**
246
+ * Find executive by email in database (defaults to production)
247
+ * AI agents call this to get executive info for database lookups
248
+ */
249
+ export async function findExecutiveByEmail(email: string): Promise<Executive | null> {
250
+ const client = getProductionDatabase();
251
+ try {
252
+ await client.connect();
253
+ const dbName = getDatabaseName();
254
+ const db = client.db(dbName);
255
+ const executive = await db.collection(getCollectionName('Executive')).findOne({ email: email.toLowerCase() });
256
+ return executive as unknown as Executive;
257
+ } finally {
258
+ await client.close();
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Get the persona email for an executive from the identity collection
264
+ * AI agents call this to get tokens or contact info for the executive's assistant
265
+ */
266
+ export async function getPersonaEmailForExecutive(executiveId: string): Promise<string> {
267
+ const { MongoClient } = await import('mongodb');
268
+ const mongoUrl = process.env.PROD_MONGO_DATABASE_URL || process.env.MONGO_DATABASE_URL;
269
+ if (!mongoUrl) {
270
+ console.warn(`⚠️ PROD_MONGO_DATABASE_URL not set, using default ${fraimConfig.personaName} email`);
271
+ return fraimConfig.defaultEmail;
272
+ }
273
+
274
+ const client = new MongoClient(mongoUrl);
275
+ try {
276
+ await client.connect();
277
+ const dbName = getDatabaseName();
278
+ const db = client.db(dbName);
279
+ const collectionName = getCollectionName(fraimConfig.identityCollection);
280
+
281
+ // Query the identity collection (defaults to prod)
282
+ let identity = await db.collection(collectionName).findOne({
283
+ executive_id: executiveId,
284
+ status: 'active'
285
+ });
286
+
287
+ if (!identity) {
288
+ identity = await db.collection(collectionName).findOne({
289
+ executive_id: executiveId
290
+ });
291
+ }
292
+
293
+ if (identity && identity.email) {
294
+ return identity.email;
295
+ }
296
+
297
+ return fraimConfig.defaultEmail;
298
+ } catch (error) {
299
+ console.warn(`⚠️ Could not get ${fraimConfig.personaName} email for executive ${executiveId}:`, error);
300
+ return fraimConfig.defaultEmail;
301
+ } finally {
302
+ await client.close();
303
+ }
304
+ }
305
+
306
+ interface Improvement {
307
+ title: string;
308
+ description: string;
309
+ verification?: string;
310
+ }
311
+
312
+ interface Candidate {
313
+ customer: { name: string; email: string };
314
+ executive: { name: string; id?: string };
315
+ status: 'pending' | 'sent' | 'failed';
316
+ from: { displayName: string; email: string };
317
+ to: string;
318
+ subject: string;
319
+ // Structured format (preferred)
320
+ greeting?: string;
321
+ opening?: string;
322
+ improvements?: Improvement[];
323
+ closing?: string;
324
+ // Legacy format (fallback for backward compatibility)
325
+ body?: string;
326
+ }
327
+
328
+ interface CandidatesFile {
329
+ metadata: {
330
+ generatedOn: string;
331
+ issuesResolvedSince: string;
332
+ totalCustomers: number;
333
+ totalIssues: number;
334
+ };
335
+ candidates: Candidate[];
336
+ }
337
+ /**
338
+ * Send emails from candidates file (JSON format)
339
+ * AI agents call this after user review to send all emails
340
+ * @param candidatesFilePath Path to the JSON candidates file
341
+ * @param executiveId Optional executive ID to filter emails to specific executive only
342
+ */
343
+ export async function sendCustomerMail(candidatesFilePath: string, executiveId?: string): Promise<void> {
344
+ if (!existsSync(candidatesFilePath)) {
345
+ throw new Error(`Candidates file not found: ${candidatesFilePath}`);
346
+ }
347
+
348
+ console.log(`📧 Sending emails from candidates file: ${candidatesFilePath}`);
349
+ if (executiveId) {
350
+ console.log(`🎯 Filtering to executive ID: ${executiveId}`);
351
+ }
352
+
353
+ const content = readFileSync(candidatesFilePath, 'utf-8');
354
+ const candidatesFile: CandidatesFile = JSON.parse(content);
355
+
356
+ console.log(`📊 Found ${candidatesFile.candidates.length} candidates (${candidatesFile.metadata.totalCustomers} customers)`);
357
+
358
+ // Filter candidates if executiveId is provided
359
+ let candidatesToSend = candidatesFile.candidates;
360
+ if (executiveId) {
361
+ candidatesToSend = candidatesFile.candidates.filter(candidate =>
362
+ candidate.executive.id === executiveId
363
+ );
364
+ console.log(`🔍 Filtered to ${candidatesToSend.length} candidate(s) for executive ${executiveId}`);
365
+
366
+ if (candidatesToSend.length === 0) {
367
+ console.log(`⚠️ No candidates found for executive ID: ${executiveId}`);
368
+ return;
369
+ }
370
+ }
371
+
372
+ // Update file with results as we send
373
+ const updatedCandidates = [...candidatesFile.candidates];
374
+
375
+ for (let i = 0; i < updatedCandidates.length; i++) {
376
+ const candidate = updatedCandidates[i];
377
+
378
+ // Skip if filtering by executive ID and this candidate doesn't match
379
+ if (executiveId && candidate.executive.id !== executiveId) {
380
+ continue;
381
+ }
382
+
383
+ if (candidate.status !== 'pending') {
384
+ console.log(`⏭️ Skipping ${candidate.customer.email} (status: ${candidate.status})`);
385
+ continue;
386
+ }
387
+
388
+ try {
389
+ console.log(`📧 Sending email to ${candidate.customer.email}...`);
390
+
391
+ // Get executive from database if we have their email
392
+ const executive = await findExecutiveByEmail(candidate.customer.email);
393
+
394
+ // Get persona tokens from identity collection if the executive is known
395
+ let personaTokens: { access_token?: string; refresh_token?: string } | null = null;
396
+ if (candidate.executive.id) {
397
+ try {
398
+ const client = getProductionDatabase();
399
+ try {
400
+ await client.connect();
401
+ const dbName = getDatabaseName();
402
+ const db = client.db(dbName);
403
+ const collectionName = getCollectionName(fraimConfig.identityCollection);
404
+
405
+ const identity = await db.collection(collectionName).findOne({
406
+ executive_id: candidate.executive.id,
407
+ status: 'active'
408
+ }) || await db.collection(collectionName).findOne({
409
+ executive_id: candidate.executive.id
410
+ });
411
+
412
+ if (identity && identity.access_token && identity.refresh_token) {
413
+ personaTokens = {
414
+ access_token: identity.access_token,
415
+ refresh_token: identity.refresh_token
416
+ };
417
+ console.log(`Found ${fraimConfig.personaName} tokens in ${dbName} database for ${candidate.from.email}`);
418
+ } else {
419
+ console.warn(`No ${fraimConfig.personaName} tokens found in ${dbName} database for executive ${candidate.executive.id}`);
420
+ }
421
+ } finally {
422
+ await client.close();
423
+ }
424
+ } catch (error) {
425
+ console.warn(`Could not get ${fraimConfig.personaName} tokens from database for executive ${candidate.executive.id}:`, error);
426
+ }
427
+ }
428
+ // Generate plain text body for fallback (from structured format if available)
429
+ const plainTextBody = generatePlainTextBody(candidate);
430
+
431
+ await sendSingleEmail({
432
+ to: candidate.to,
433
+ subject: candidate.subject,
434
+ body: plainTextBody,
435
+ fromEmail: candidate.from.email,
436
+ fromDisplayName: candidate.from.displayName,
437
+ candidate // Pass full candidate for HTML generation
438
+ }, executive, personaTokens);
439
+
440
+ console.log(`✅ Email sent to ${candidate.customer.email}`);
441
+ updatedCandidates[i].status = 'sent';
442
+
443
+ // Update file after each successful send
444
+ const updatedFile: CandidatesFile = {
445
+ ...candidatesFile,
446
+ candidates: updatedCandidates
447
+ };
448
+ writeFileSync(candidatesFilePath, JSON.stringify(updatedFile, null, 2));
449
+
450
+ } catch (error) {
451
+ console.error(`❌ Failed to send email to ${candidate.customer.email}:`, error);
452
+ updatedCandidates[i].status = 'failed';
453
+
454
+ // Update file with failure status
455
+ const updatedFile: CandidatesFile = {
456
+ ...candidatesFile,
457
+ candidates: updatedCandidates
458
+ };
459
+ writeFileSync(candidatesFilePath, JSON.stringify(updatedFile, null, 2));
460
+ }
461
+ }
462
+
463
+ console.log(`\n✅ Email sending complete. Status updated in ${candidatesFilePath}`);
464
+
465
+ // Exit cleanly to prevent hanging
466
+ process.exit(0);
467
+ }
468
+
469
+ interface SendEmailParams {
470
+ to: string;
471
+ subject: string;
472
+ body: string;
473
+ fromEmail: string;
474
+ fromDisplayName: string;
475
+ candidate?: Candidate; // Optional: for structured HTML generation
476
+ }
477
+
478
+ async function sendSingleEmail(
479
+ params: SendEmailParams,
480
+ executive?: Executive | null,
481
+ personaTokens?: { access_token?: string; refresh_token?: string } | null
482
+ ): Promise<void> {
483
+ const { to, subject, body, fromEmail, fromDisplayName } = params;
484
+
485
+ // Get Persona's tokens - prioritize identity tokens, then executive tokens, then default
486
+ let accessToken: string;
487
+ let refreshToken: string;
488
+
489
+ if (personaTokens?.access_token && personaTokens?.refresh_token) {
490
+ // Use persona identity tokens (preferred - ensures correct From address)
491
+ console.log(`🔑 Using ${fraimConfig.personaName} identity tokens for ${fromEmail}`);
492
+ accessToken = personaTokens.access_token;
493
+ refreshToken = personaTokens.refresh_token;
494
+ } else if (executive?.personaAccessToken && executive?.personaRefreshToken) {
495
+ // Fallback to executive-specific tokens
496
+ console.log(`🔑 Using executive persona tokens as fallback`);
497
+ accessToken = executive.personaAccessToken;
498
+ refreshToken = executive.personaRefreshToken;
499
+ } else {
500
+ // Use default persona tokens as last resort
501
+ console.log(`🔑 Using default ${fraimConfig.personaName} tokens as fallback`);
502
+ accessToken = fraimConfig.defaultAccessToken;
503
+ refreshToken = fraimConfig.defaultRefreshToken;
504
+
505
+ if (!accessToken || !refreshToken) {
506
+ throw new Error(`${fraimConfig.personaName} Gmail tokens not found. Need either identity tokens, executive tokens, or default tokens in environment variables.`);
507
+ }
508
+ }
509
+
510
+ // Verify the From email matches the authenticated account (Gmail requirement)
511
+ // For plus addressing, the base email should match
512
+ const fromBaseEmail = fromEmail.includes('+')
513
+ ? fromEmail.split('+')[0] + '@' + fromEmail.split('@')[1]
514
+ : fromEmail;
515
+
516
+ console.log(`📧 Sending from: "${fromDisplayName}" <${fromEmail}>`);
517
+
518
+ // Generate HTML email from template (use structured format if available)
519
+ const greeting = params.candidate?.greeting || 'Hi there,';
520
+ const htmlBody = generateHtmlEmail({
521
+ displayName: extractFirstName(greeting) || extractFirstName(body) || extractFirstName(fromDisplayName) || 'there',
522
+ greeting: greeting,
523
+ opening: params.candidate?.opening
524
+ ? convertTextToHtml(params.candidate.opening)
525
+ : convertBodyToHtml(body), // Fallback to legacy body
526
+ improvements: params.candidate?.improvements || [],
527
+ closing: params.candidate?.closing || '',
528
+ executiveName: extractExecutiveName(fromDisplayName),
529
+ fromEmail
530
+ });
531
+
532
+ // Create multipart email message (plain text + HTML)
533
+ const boundary = `boundary_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
534
+ const emailMessage = [
535
+ `To: ${to}`,
536
+ `From: ${fromDisplayName} <${fromEmail}>`,
537
+ `Subject: ${subject}`,
538
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
539
+ `MIME-Version: 1.0`,
540
+ ``,
541
+ `--${boundary}`,
542
+ `Content-Type: text/plain; charset=utf-8`,
543
+ `Content-Transfer-Encoding: 7bit`,
544
+ ``,
545
+ body,
546
+ ``,
547
+ `--${boundary}`,
548
+ `Content-Type: text/html; charset=utf-8`,
549
+ `Content-Transfer-Encoding: 7bit`,
550
+ ``,
551
+ htmlBody,
552
+ ``,
553
+ `--${boundary}--`
554
+ ].join('\r\n');
555
+
556
+ // Send email using Gmail API
557
+ const url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages/send';
558
+ const requestBody = {
559
+ raw: Buffer.from(emailMessage).toString('base64')
560
+ .replace(/\+/g, '-')
561
+ .replace(/\//g, '_')
562
+ .replace(/=+$/, '')
563
+ };
564
+
565
+ const response = await fetch(url, {
566
+ method: 'POST',
567
+ headers: {
568
+ 'Authorization': `Bearer ${accessToken}`,
569
+ 'Content-Type': 'application/json',
570
+ },
571
+ body: JSON.stringify(requestBody)
572
+ });
573
+
574
+ if (!response.ok) {
575
+ if (response.status === 401) {
576
+ console.log('🔄 Access token expired, refreshing...');
577
+
578
+ // Refresh the access token
579
+ const clientId = fraimConfig.defaultOAuthClientId || process.env.FRAIM_DEFAULT_OAUTH_CLIENT_ID || process.env.PERSONA_DEFAULT_OAUTH_CLIENT_ID;
580
+ const clientSecret = fraimConfig.defaultOAuthClientSecret || process.env.FRAIM_DEFAULT_OAUTH_CLIENT_SECRET || process.env.PERSONA_DEFAULT_OAUTH_CLIENT_SECRET;
581
+
582
+ if (!clientId || !clientSecret) {
583
+ throw new Error('FRAIM_DEFAULT_OAUTH_CLIENT_ID and FRAIM_DEFAULT_OAUTH_CLIENT_SECRET environment variables are required for token refresh');
584
+ }
585
+
586
+ console.log('🔄 Refreshing token...');
587
+
588
+ const refreshResponse = await fetch('https://oauth2.googleapis.com/token', {
589
+ method: 'POST',
590
+ headers: {
591
+ 'Content-Type': 'application/x-www-form-urlencoded',
592
+ },
593
+ body: new URLSearchParams({
594
+ client_id: clientId,
595
+ client_secret: clientSecret,
596
+ refresh_token: refreshToken,
597
+ grant_type: 'refresh_token'
598
+ })
599
+ });
600
+
601
+ if (!refreshResponse.ok) {
602
+ const errorText = await refreshResponse.text();
603
+ console.error('❌ Token refresh failed:', refreshResponse.status, errorText);
604
+ throw new Error(`Failed to refresh access token: ${refreshResponse.status} - ${errorText}`);
605
+ }
606
+
607
+ const tokenData = await refreshResponse.json() as any;
608
+ const newAccessToken = tokenData.access_token;
609
+
610
+ console.log('✅ Token refreshed, retrying email send...');
611
+
612
+ // Retry with new token
613
+ const retryResponse = await fetch(url, {
614
+ method: 'POST',
615
+ headers: {
616
+ 'Authorization': `Bearer ${newAccessToken}`,
617
+ 'Content-Type': 'application/json',
618
+ },
619
+ body: JSON.stringify(requestBody)
620
+ });
621
+
622
+ if (!retryResponse.ok) {
623
+ const errorText = await retryResponse.text();
624
+ throw new Error(`Gmail API error after refresh: ${retryResponse.status} - ${errorText}`);
625
+ }
626
+
627
+ const result = await retryResponse.json() as any;
628
+ console.log(`✅ Email sent successfully to ${to}`);
629
+ console.log(`📧 Email ID: ${result.id}`);
630
+ return;
631
+ }
632
+ const errorText = await response.text();
633
+ throw new Error(`Gmail API error: ${response.status} - ${errorText}`);
634
+ }
635
+
636
+ const result = await response.json() as any;
637
+ console.log(`✅ Email sent successfully to ${to}`);
638
+ console.log(`📧 Email ID: ${result.id}`);
639
+ }
640
+ /**
641
+ * Generate HTML email from template
642
+ */
643
+ function generateHtmlEmail(params: {
644
+ displayName: string;
645
+ greeting: string;
646
+ opening: string;
647
+ improvements: Improvement[];
648
+ closing: string;
649
+ executiveName: string;
650
+ fromEmail: string;
651
+ }): string {
652
+ const templatePath = getTemplatePath();
653
+ let template = readFileSync(templatePath, 'utf-8');
654
+
655
+ // Replace simple template variables
656
+ template = template.replace(/\{\{displayName\}\}/g, escapeHtml(params.displayName));
657
+ template = template.replace(/\{\{executiveName\}\}/g, escapeHtml(params.executiveName));
658
+ template = template.replace(/\{\{personaName\}\}/g, escapeHtml(fraimConfig.personaName));
659
+ template = template.replace(/\{\{chatUrl\}\}/g, escapeHtml(fraimConfig.chatUrl || '#'));
660
+ template = template.replace(/\{\{webAppUrl\}\}/g, escapeHtml(fraimConfig.webAppUrl || '#'));
661
+ template = template.replace(/\{\{fromEmail\}\}/g, escapeHtml(params.fromEmail));
662
+ template = template.replace(/\{\{greeting\}\}/g, escapeHtml(params.greeting));
663
+ template = template.replace(/\{\{opening\}\}/g, params.opening);
664
+
665
+ // Generate improvements list HTML
666
+ const hasImprovements = params.improvements && params.improvements.length > 0;
667
+ if (hasImprovements) {
668
+ const improvementsHtml = params.improvements.map((improvement, index) => {
669
+ let html = `<div style="margin-bottom: ${index < params.improvements.length - 1 ? '20px' : '0'}; padding-bottom: ${index < params.improvements.length - 1 ? '20px' : '0'}; border-bottom: ${index < params.improvements.length - 1 ? '1px solid #e9ecef' : 'none'};">`;
670
+ html += `<div style="font-size: 16px; font-weight: 600; color: #333333; margin-bottom: 8px;">${escapeHtml(improvement.title)}</div>`;
671
+ html += `<div style="font-size: 15px; color: #555555; line-height: 1.7; margin-bottom: ${improvement.verification ? '10px' : '0'};">${convertTextToHtml(improvement.description)}</div>`;
672
+ if (improvement.verification) {
673
+ html += `<div style="font-size: 14px; color: #667eea; font-style: italic; padding-top: 8px; border-top: 1px solid #e9ecef; margin-top: 8px;">💡 <strong>How to verify:</strong> ${convertTextToHtml(improvement.verification)}</div>`;
674
+ }
675
+ html += `</div>`;
676
+ return html;
677
+ }).join('');
678
+
679
+ const improvementsSection = `
680
+ <tr>
681
+ <td style="padding: 0 30px 20px 30px;">
682
+ <div style="background-color: #f8f9fa; border-left: 4px solid #667eea; border-radius: 6px; padding: 20px; margin: 20px 0;">
683
+ <div style="font-size: 18px; font-weight: 600; color: #333333; margin-bottom: 16px;">
684
+ ✨ What's Fixed
685
+ </div>
686
+ ${improvementsHtml}
687
+ </div>
688
+ </td>
689
+ </tr>`;
690
+ template = template.replace(/\{\{#if hasImprovements\}\}[\s\S]*?\{\{\/if\}\}/, improvementsSection);
691
+ } else {
692
+ // Remove conditional block if no improvements
693
+ template = template.replace(/\{\{#if hasImprovements\}\}[\s\S]*?\{\{\/if\}\}/, '');
694
+ }
695
+
696
+ // Replace closing paragraph
697
+ if (params.closing) {
698
+ template = template.replace(/\{\{#if closing\}\}[\s\S]*?\{\{\/if\}\}/, `
699
+ <tr>
700
+ <td style="padding: 0 30px 20px 30px;">
701
+ <div style="font-size: 16px; color: #555555; line-height: 1.8;">
702
+ ${convertTextToHtml(params.closing)}
703
+ </div>
704
+ </td>
705
+ </tr>`);
706
+ } else {
707
+ template = template.replace(/\{\{#if closing\}\}[\s\S]*?\{\{\/if\}\}/, '');
708
+ }
709
+
710
+ return template;
711
+ }
712
+
713
+ /**
714
+ * Generate plain text body from candidate (supports both structured and legacy formats)
715
+ */
716
+ function generatePlainTextBody(candidate: Candidate): string {
717
+ // If structured format exists, use it
718
+ if (candidate.greeting && candidate.opening) {
719
+ let body = `${candidate.greeting}\n\n${candidate.opening}\n\n`;
720
+
721
+ if (candidate.improvements && candidate.improvements.length > 0) {
722
+ body += `**What was improved:**\n\n`;
723
+ candidate.improvements.forEach((improvement, index) => {
724
+ body += `${index + 1}. ${improvement.title}: ${improvement.description}`;
725
+ if (improvement.verification) {
726
+ body += `\n **How to verify:** ${improvement.verification}`;
727
+ }
728
+ body += `\n\n`;
729
+ });
730
+ }
731
+
732
+ if (candidate.closing) {
733
+ body += `${candidate.closing}\n\n`;
734
+ }
735
+
736
+ body += formatPersonaSignature();
737
+
738
+ return body;
739
+ }
740
+
741
+ // Fallback to legacy body format
742
+ return candidate.body || '';
743
+ }
744
+
745
+ /**
746
+ * Extract first name from text
747
+ */
748
+ function extractFirstName(text: string): string | null {
749
+ // Try to find "Hi [Name]" pattern
750
+ const hiMatch = text.match(/\b[Hh]i\s+([A-Z][a-z]+)/);
751
+ if (hiMatch) {
752
+ return hiMatch[1];
753
+ }
754
+
755
+ // Try to find comma after greeting
756
+ const commaMatch = text.match(/^[Hh]i\s+([^,]+),/);
757
+ if (commaMatch) {
758
+ return commaMatch[1].trim().split(' ')[0];
759
+ }
760
+
761
+ return null;
762
+ }
763
+
764
+ /**
765
+ * Extract executive name from display name
766
+ */
767
+ function extractExecutiveName(displayName: string): string {
768
+ // "{Persona} - [Name]'s AI Executive Assistant"
769
+ // We need to match based on the configured pattern
770
+ const pattern = fraimConfig.personaDisplayNamePattern.replace('{executiveName}', '(.+?)');
771
+
772
+ try {
773
+ // If pattern contains regex characters, they need expanding or escaping?
774
+ // This is simple pattern matching.
775
+ // Example: "Persona - {executiveName}'s AI Executive Assistant"
776
+ // Regex: /Persona - (.+?)'s AI Executive Assistant/
777
+ // We escape special chars except the group we added
778
+ const escapedPattern = pattern
779
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // Escape regex chars
780
+ .replace('\\(\\.+\\?\\)', '(.+?)'); // Restore capture group
781
+
782
+ const match = displayName.match(new RegExp(escapedPattern));
783
+ return match ? match[1] : 'Your';
784
+ } catch (e) {
785
+ return 'Your';
786
+ }
787
+ }
788
+
789
+ /**
790
+ * Convert plain text to HTML (for legacy body format)
791
+ */
792
+ function convertBodyToHtml(body: string): string {
793
+ return convertTextToHtml(body);
794
+ }
795
+
796
+ /**
797
+ * Convert text to HTML (preserves markdown-style formatting)
798
+ */
799
+ function convertTextToHtml(text: string): string {
800
+ if (!text) return '';
801
+
802
+ let html = text;
803
+
804
+ // Convert markdown-style bold **text** to <strong>text</strong>
805
+ html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
806
+
807
+ // Convert line breaks to paragraphs
808
+ html = html.replace(/\n\n+/g, '</p><p style="margin: 12px 0;">');
809
+ html = html.replace(/\n/g, '<br>');
810
+
811
+ // Wrap in paragraph tags
812
+ html = `<p style="margin: 0 0 12px 0;">${html}</p>`;
813
+
814
+ // Clean up empty paragraphs
815
+ html = html.replace(/<p[^>]*><\/p>/g, '');
816
+
817
+ return html;
818
+ }
819
+
820
+ /**
821
+ * Escape HTML special characters
822
+ */
823
+ function escapeHtml(text: string): string {
824
+ return text
825
+ .replace(/&/g, '&amp;')
826
+ .replace(/</g, '&lt;')
827
+ .replace(/>/g, '&gt;')
828
+ .replace(/"/g, '&quot;')
829
+ .replace(/'/g, '&#039;');
830
+ }