fraim-framework 2.0.27 → 2.0.30

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 (98) hide show
  1. package/.github/workflows/deploy-fraim.yml +1 -1
  2. package/dist/registry/scripts/build-scripts-generator.js +205 -0
  3. package/dist/registry/scripts/cleanup-branch.js +258 -0
  4. package/dist/registry/scripts/evaluate-code-quality.js +66 -0
  5. package/dist/registry/scripts/exec-with-timeout.js +142 -0
  6. package/dist/registry/scripts/fraim-config.js +61 -0
  7. package/dist/registry/scripts/generate-engagement-emails.js +630 -0
  8. package/dist/registry/scripts/generic-issues-api.js +100 -0
  9. package/dist/registry/scripts/newsletter-helpers.js +731 -0
  10. package/dist/registry/scripts/openapi-generator.js +664 -0
  11. package/dist/registry/scripts/performance/profile-server.js +390 -0
  12. package/dist/registry/scripts/run-thank-you-workflow.js +92 -0
  13. package/dist/registry/scripts/send-newsletter-simple.js +85 -0
  14. package/dist/registry/scripts/send-thank-you-emails.js +54 -0
  15. package/dist/registry/scripts/validate-openapi-limits.js +311 -0
  16. package/dist/registry/scripts/validate-test-coverage.js +262 -0
  17. package/dist/registry/scripts/verify-test-coverage.js +66 -0
  18. package/dist/src/cli/commands/init.js +14 -14
  19. package/dist/src/cli/commands/sync.js +4 -4
  20. package/dist/src/cli/fraim.js +24 -22
  21. package/dist/src/cli/setup/first-run.js +13 -6
  22. package/dist/src/fraim/db-service.js +26 -15
  23. package/dist/src/fraim/issues.js +67 -0
  24. package/dist/src/fraim-mcp-server.js +272 -18
  25. package/dist/src/utils/git-utils.js +1 -1
  26. package/dist/tests/debug-tools.js +79 -0
  27. package/dist/tests/esm-compat.js +11 -0
  28. package/dist/tests/test-chalk-esm-issue.js +159 -0
  29. package/dist/tests/test-chalk-real-world.js +265 -0
  30. package/dist/tests/test-chalk-regression.js +327 -0
  31. package/dist/tests/test-chalk-resolution-issue.js +304 -0
  32. package/dist/tests/test-fraim-install-chalk-issue.js +254 -0
  33. package/dist/tests/test-fraim-issues.js +59 -0
  34. package/dist/tests/test-genericization.js +1 -1
  35. package/dist/tests/test-mcp-connection.js +166 -0
  36. package/dist/tests/test-mcp-issue-integration.js +144 -0
  37. package/dist/tests/test-mcp-lifecycle-methods.js +312 -0
  38. package/dist/tests/test-node-compatibility.js +71 -0
  39. package/dist/tests/test-npm-install.js +66 -0
  40. package/dist/tests/test-npm-resolution-diagnostic.js +140 -0
  41. package/dist/tests/test-session-rehydration.js +145 -0
  42. package/dist/tests/test-standalone.js +2 -8
  43. package/dist/tests/test-telemetry.js +190 -0
  44. package/package.json +10 -8
  45. package/registry/agent-guardrails.md +62 -54
  46. package/registry/rules/agent-success-criteria.md +52 -0
  47. package/registry/rules/agent-testing-guidelines.md +502 -502
  48. package/registry/rules/communication.md +121 -121
  49. package/registry/rules/continuous-learning.md +54 -54
  50. package/registry/rules/ephemeral-execution.md +10 -5
  51. package/registry/rules/hitl-ppe-record-analysis.md +302 -302
  52. package/registry/rules/local-development.md +251 -251
  53. package/registry/rules/software-development-lifecycle.md +104 -104
  54. package/registry/rules/successful-debugging-patterns.md +482 -478
  55. package/registry/rules/telemetry.md +67 -0
  56. package/registry/scripts/build-scripts-generator.ts +216 -215
  57. package/registry/scripts/cleanup-branch.ts +303 -284
  58. package/registry/scripts/code-quality-check.sh +559 -559
  59. package/registry/scripts/detect-tautological-tests.sh +38 -38
  60. package/registry/scripts/evaluate-code-quality.ts +1 -1
  61. package/registry/scripts/generate-engagement-emails.ts +744 -744
  62. package/registry/scripts/generic-issues-api.ts +110 -150
  63. package/registry/scripts/newsletter-helpers.ts +874 -874
  64. package/registry/scripts/openapi-generator.ts +695 -693
  65. package/registry/scripts/performance/profile-server.ts +5 -3
  66. package/registry/scripts/prep-issue.sh +468 -455
  67. package/registry/scripts/validate-openapi-limits.ts +366 -365
  68. package/registry/scripts/validate-test-coverage.ts +280 -280
  69. package/registry/scripts/verify-pr-comments.sh +70 -70
  70. package/registry/scripts/verify-test-coverage.ts +1 -1
  71. package/registry/templates/bootstrap/ARCHITECTURE-TEMPLATE.md +53 -53
  72. package/registry/templates/evidence/Implementation-BugEvidence.md +85 -85
  73. package/registry/templates/evidence/Implementation-FeatureEvidence.md +120 -120
  74. package/registry/templates/marketing/HBR-ARTICLE-TEMPLATE.md +66 -0
  75. package/registry/workflows/bootstrap/create-architecture.md +2 -2
  76. package/registry/workflows/bootstrap/evaluate-code-quality.md +3 -3
  77. package/registry/workflows/bootstrap/verify-test-coverage.md +2 -2
  78. package/registry/workflows/customer-development/insight-analysis.md +156 -156
  79. package/registry/workflows/customer-development/interview-preparation.md +421 -421
  80. package/registry/workflows/customer-development/strategic-brainstorming.md +146 -146
  81. package/registry/workflows/customer-development/thank-customers.md +193 -191
  82. package/registry/workflows/customer-development/weekly-newsletter.md +362 -352
  83. package/registry/workflows/improve-fraim/contribute.md +32 -0
  84. package/registry/workflows/improve-fraim/file-issue.md +32 -0
  85. package/registry/workflows/marketing/hbr-article.md +73 -0
  86. package/registry/workflows/performance/analyze-performance.md +63 -59
  87. package/registry/workflows/product-building/design.md +3 -2
  88. package/registry/workflows/product-building/implement.md +4 -3
  89. package/registry/workflows/product-building/prep-issue.md +28 -17
  90. package/registry/workflows/product-building/resolve.md +3 -2
  91. package/registry/workflows/product-building/retrospect.md +3 -2
  92. package/registry/workflows/product-building/spec.md +5 -4
  93. package/registry/workflows/product-building/test.md +3 -2
  94. package/registry/workflows/quality-assurance/iterative-improvement-cycle.md +562 -562
  95. package/registry/workflows/replicate/website-discovery-analysis.md +3 -3
  96. package/registry/workflows/reviewer/review-implementation-vs-design-spec.md +632 -632
  97. package/registry/workflows/reviewer/review-implementation-vs-feature-spec.md +669 -669
  98. package/tsconfig.json +2 -1
@@ -0,0 +1,630 @@
1
+ #!/usr/bin/env tsx
2
+ "use strict";
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
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.getLatestThankYouDate = getLatestThankYouDate;
44
+ exports.getResolvedIssues = getResolvedIssues;
45
+ exports.findExecutiveByEmail = findExecutiveByEmail;
46
+ exports.getPersonaEmailForExecutive = getPersonaEmailForExecutive;
47
+ exports.sendCustomerMail = sendCustomerMail;
48
+ const child_process_1 = require("child_process");
49
+ const fs_1 = require("fs");
50
+ const mongodb_1 = require("mongodb");
51
+ const path_1 = require("path");
52
+ const git_utils_js_1 = require("../../src/utils/git-utils.js");
53
+ const fraim_config_1 = require("./fraim-config");
54
+ // Get template path (relative to script location)
55
+ function getTemplatePath() {
56
+ // Script is at <this-path>
57
+ // Template is at templates/customer-development/thank-you-email-template.html (Retrieve via get_fraim_file)
58
+ // Or generic path? Let's keep existing path logic but relative to process.cwd() as before
59
+ return (0, path_1.join)(process.cwd(), 'registry', 'templates', 'customer-development', 'thank-you-email-template.html');
60
+ }
61
+ /**
62
+ * Get the latest date from existing thank-you candidates files
63
+ * Returns the most recent date when thank-you emails were sent, or null if no files exist
64
+ */
65
+ function getLatestThankYouDate() {
66
+ const notesDir = 'docs/customer-development/thank-you-notes';
67
+ if (!(0, fs_1.existsSync)(notesDir)) {
68
+ return null;
69
+ }
70
+ const files = (0, fs_1.readdirSync)(notesDir).filter(f => f.startsWith('thank-you-candidates-') && f.endsWith('.json'));
71
+ if (files.length === 0) {
72
+ return null;
73
+ }
74
+ // Extract dates from filenames (e.g., thank-you-candidates-2025-10-29.json)
75
+ const dates = [];
76
+ for (const file of files) {
77
+ const dateMatch = file.match(/thank-you-candidates-(\d{4}-\d{2}-\d{2})\.json/);
78
+ if (dateMatch) {
79
+ const filePath = (0, path_1.join)(notesDir, file);
80
+ try {
81
+ const content = (0, fs_1.readFileSync)(filePath, 'utf-8');
82
+ const json = JSON.parse(content);
83
+ // Check if any candidates have status "sent"
84
+ const hasSentEmails = json.candidates?.some((c) => c.status === 'sent');
85
+ if (hasSentEmails) {
86
+ dates.push(dateMatch[1]);
87
+ }
88
+ }
89
+ catch (error) {
90
+ // Skip invalid JSON files
91
+ console.warn(`⚠️ Could not parse ${file}:`, error);
92
+ }
93
+ }
94
+ }
95
+ if (dates.length === 0) {
96
+ return null;
97
+ }
98
+ // Return the most recent date
99
+ dates.sort();
100
+ const latestDate = dates[dates.length - 1];
101
+ console.log(`📅 Latest thank-you date found: ${latestDate}`);
102
+ return latestDate;
103
+ }
104
+ /**
105
+ * Get resolved issues since a specified date (or latest thank-you date if not provided)
106
+ * AI agents call this to retrieve issues that were resolved
107
+ * @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.
108
+ */
109
+ async function getResolvedIssues(date) {
110
+ if (!date) {
111
+ // Try to get the latest thank-you date
112
+ const latestThankYouDate = getLatestThankYouDate();
113
+ if (latestThankYouDate) {
114
+ date = latestThankYouDate;
115
+ console.log(`📋 Using latest thank-you date as starting point: ${date}`);
116
+ }
117
+ else {
118
+ // Fallback to last 14 days if no thank-you files exist
119
+ const fallbackDate = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
120
+ date = fallbackDate;
121
+ console.log(`📋 No previous thank-you files found, using last 14 days: ${date}`);
122
+ }
123
+ }
124
+ // Use ">YYYY-MM-DD" format to get issues updated AFTER the date (not on the date)
125
+ // GitHub CLI requires quotes around the comparison operator
126
+ const command = `gh search issues --repo=${fraim_config_1.fraimConfig.repoOwner}/${fraim_config_1.fraimConfig.repoName} --state=closed --updated=">${date}" --label=user-reported --json number,title,body,labels,closedAt,author`;
127
+ const output = (0, child_process_1.execSync)(command, { encoding: 'utf-8' });
128
+ return JSON.parse(output);
129
+ }
130
+ function getProductionDatabase() {
131
+ const mongoUrl = process.env.PROD_MONGO_DATABASE_URL || process.env.MONGO_DATABASE_URL;
132
+ if (!mongoUrl) {
133
+ throw new Error('PROD_MONGO_DATABASE_URL or MONGO_DATABASE_URL environment variable is required');
134
+ }
135
+ return new mongodb_1.MongoClient(mongoUrl);
136
+ }
137
+ /**
138
+ * Get database name, defaulting to production
139
+ */
140
+ function getDatabaseName() {
141
+ const env = process.env.NODE_ENV || process.env.ENVIRONMENT;
142
+ // If explicitly set to ppe/staging, use that; otherwise default to prod
143
+ if (env === 'ppe' || env === 'staging') {
144
+ return (0, git_utils_js_1.determineDatabaseName)();
145
+ }
146
+ // Default to production
147
+ return process.env.MONGO_DB_NAME || 'fraim_prod';
148
+ }
149
+ /**
150
+ * Get collection name with schema prefix (defaults to prod schema)
151
+ */
152
+ function getCollectionName(baseName) {
153
+ const env = process.env.NODE_ENV || process.env.ENVIRONMENT;
154
+ // If explicitly set to ppe/staging, use that schema; otherwise default to prod
155
+ if (env === 'ppe' || env === 'staging') {
156
+ const schema = (0, git_utils_js_1.determineSchema)((0, git_utils_js_1.getCurrentGitBranch)());
157
+ return `${schema}_${baseName}`;
158
+ }
159
+ // Default to prod schema
160
+ return `prod_${baseName}`;
161
+ }
162
+ /**
163
+ * Find executive by email in database (defaults to production)
164
+ * AI agents call this to get executive info for database lookups
165
+ */
166
+ async function findExecutiveByEmail(email) {
167
+ const client = getProductionDatabase();
168
+ try {
169
+ await client.connect();
170
+ const dbName = getDatabaseName();
171
+ const db = client.db(dbName);
172
+ const executive = await db.collection(getCollectionName('Executive')).findOne({ email: email.toLowerCase() });
173
+ return executive;
174
+ }
175
+ finally {
176
+ await client.close();
177
+ }
178
+ }
179
+ /**
180
+ * Get the persona email for an executive from the identity collection
181
+ * AI agents call this to get tokens or contact info for the executive's assistant
182
+ */
183
+ async function getPersonaEmailForExecutive(executiveId) {
184
+ const { MongoClient } = await Promise.resolve().then(() => __importStar(require('mongodb')));
185
+ const mongoUrl = process.env.PROD_MONGO_DATABASE_URL || process.env.MONGO_DATABASE_URL;
186
+ if (!mongoUrl) {
187
+ console.warn(`⚠️ PROD_MONGO_DATABASE_URL not set, using default ${fraim_config_1.fraimConfig.personaName} email`);
188
+ return fraim_config_1.fraimConfig.defaultEmail;
189
+ }
190
+ const client = new MongoClient(mongoUrl);
191
+ try {
192
+ await client.connect();
193
+ const dbName = getDatabaseName();
194
+ const db = client.db(dbName);
195
+ const collectionName = getCollectionName(fraim_config_1.fraimConfig.identityCollection);
196
+ // Query the identity collection (defaults to prod)
197
+ let identity = await db.collection(collectionName).findOne({
198
+ executive_id: executiveId,
199
+ status: 'active'
200
+ });
201
+ if (!identity) {
202
+ identity = await db.collection(collectionName).findOne({
203
+ executive_id: executiveId
204
+ });
205
+ }
206
+ if (identity && identity.email) {
207
+ return identity.email;
208
+ }
209
+ return fraim_config_1.fraimConfig.defaultEmail;
210
+ }
211
+ catch (error) {
212
+ console.warn(`⚠️ Could not get ${fraim_config_1.fraimConfig.personaName} email for executive ${executiveId}:`, error);
213
+ return fraim_config_1.fraimConfig.defaultEmail;
214
+ }
215
+ finally {
216
+ await client.close();
217
+ }
218
+ }
219
+ /**
220
+ * Send emails from candidates file (JSON format)
221
+ * AI agents call this after user review to send all emails
222
+ * @param candidatesFilePath Path to the JSON candidates file
223
+ * @param executiveId Optional executive ID to filter emails to specific executive only
224
+ */
225
+ async function sendCustomerMail(candidatesFilePath, executiveId) {
226
+ if (!(0, fs_1.existsSync)(candidatesFilePath)) {
227
+ throw new Error(`Candidates file not found: ${candidatesFilePath}`);
228
+ }
229
+ console.log(`📧 Sending emails from candidates file: ${candidatesFilePath}`);
230
+ if (executiveId) {
231
+ console.log(`🎯 Filtering to executive ID: ${executiveId}`);
232
+ }
233
+ const content = (0, fs_1.readFileSync)(candidatesFilePath, 'utf-8');
234
+ const candidatesFile = JSON.parse(content);
235
+ console.log(`📊 Found ${candidatesFile.candidates.length} candidates (${candidatesFile.metadata.totalCustomers} customers)`);
236
+ // Filter candidates if executiveId is provided
237
+ let candidatesToSend = candidatesFile.candidates;
238
+ if (executiveId) {
239
+ candidatesToSend = candidatesFile.candidates.filter(candidate => candidate.executive.id === executiveId);
240
+ console.log(`🔍 Filtered to ${candidatesToSend.length} candidate(s) for executive ${executiveId}`);
241
+ if (candidatesToSend.length === 0) {
242
+ console.log(`⚠️ No candidates found for executive ID: ${executiveId}`);
243
+ return;
244
+ }
245
+ }
246
+ // Update file with results as we send
247
+ const updatedCandidates = [...candidatesFile.candidates];
248
+ for (let i = 0; i < updatedCandidates.length; i++) {
249
+ const candidate = updatedCandidates[i];
250
+ // Skip if filtering by executive ID and this candidate doesn't match
251
+ if (executiveId && candidate.executive.id !== executiveId) {
252
+ continue;
253
+ }
254
+ if (candidate.status !== 'pending') {
255
+ console.log(`⏭️ Skipping ${candidate.customer.email} (status: ${candidate.status})`);
256
+ continue;
257
+ }
258
+ try {
259
+ console.log(`📧 Sending email to ${candidate.customer.email}...`);
260
+ // Get executive from database if we have their email
261
+ const executive = await findExecutiveByEmail(candidate.customer.email);
262
+ // Get persona tokens from identity collection if the executive is known
263
+ let personaTokens = null;
264
+ if (candidate.executive.id) {
265
+ try {
266
+ const client = getProductionDatabase();
267
+ try {
268
+ await client.connect();
269
+ const dbName = getDatabaseName();
270
+ const db = client.db(dbName);
271
+ const collectionName = getCollectionName(fraim_config_1.fraimConfig.identityCollection);
272
+ const identity = await db.collection(collectionName).findOne({
273
+ executive_id: candidate.executive.id,
274
+ status: 'active'
275
+ }) || await db.collection(collectionName).findOne({
276
+ executive_id: candidate.executive.id
277
+ });
278
+ if (identity && identity.access_token && identity.refresh_token) {
279
+ personaTokens = {
280
+ access_token: identity.access_token,
281
+ refresh_token: identity.refresh_token
282
+ };
283
+ console.log(`Found ${fraim_config_1.fraimConfig.personaName} tokens in ${dbName} database for ${candidate.from.email}`);
284
+ }
285
+ else {
286
+ console.warn(`No ${fraim_config_1.fraimConfig.personaName} tokens found in ${dbName} database for executive ${candidate.executive.id}`);
287
+ }
288
+ }
289
+ finally {
290
+ await client.close();
291
+ }
292
+ }
293
+ catch (error) {
294
+ console.warn(`Could not get ${fraim_config_1.fraimConfig.personaName} tokens from database for executive ${candidate.executive.id}:`, error);
295
+ }
296
+ }
297
+ // Generate plain text body for fallback (from structured format if available)
298
+ const plainTextBody = generatePlainTextBody(candidate);
299
+ await sendSingleEmail({
300
+ to: candidate.to,
301
+ subject: candidate.subject,
302
+ body: plainTextBody,
303
+ fromEmail: candidate.from.email,
304
+ fromDisplayName: candidate.from.displayName,
305
+ candidate // Pass full candidate for HTML generation
306
+ }, executive, personaTokens);
307
+ console.log(`✅ Email sent to ${candidate.customer.email}`);
308
+ updatedCandidates[i].status = 'sent';
309
+ // Update file after each successful send
310
+ const updatedFile = {
311
+ ...candidatesFile,
312
+ candidates: updatedCandidates
313
+ };
314
+ (0, fs_1.writeFileSync)(candidatesFilePath, JSON.stringify(updatedFile, null, 2));
315
+ }
316
+ catch (error) {
317
+ console.error(`❌ Failed to send email to ${candidate.customer.email}:`, error);
318
+ updatedCandidates[i].status = 'failed';
319
+ // Update file with failure status
320
+ const updatedFile = {
321
+ ...candidatesFile,
322
+ candidates: updatedCandidates
323
+ };
324
+ (0, fs_1.writeFileSync)(candidatesFilePath, JSON.stringify(updatedFile, null, 2));
325
+ }
326
+ }
327
+ console.log(`\n✅ Email sending complete. Status updated in ${candidatesFilePath}`);
328
+ // Exit cleanly to prevent hanging
329
+ process.exit(0);
330
+ }
331
+ async function sendSingleEmail(params, executive, personaTokens) {
332
+ const { to, subject, body, fromEmail, fromDisplayName } = params;
333
+ // Get Persona's tokens - prioritize identity tokens, then executive tokens, then default
334
+ let accessToken;
335
+ let refreshToken;
336
+ if (personaTokens?.access_token && personaTokens?.refresh_token) {
337
+ // Use persona identity tokens (preferred - ensures correct From address)
338
+ console.log(`🔑 Using ${fraim_config_1.fraimConfig.personaName} identity tokens for ${fromEmail}`);
339
+ accessToken = personaTokens.access_token;
340
+ refreshToken = personaTokens.refresh_token;
341
+ }
342
+ else if (executive?.personaAccessToken && executive?.personaRefreshToken) {
343
+ // Fallback to executive-specific tokens
344
+ console.log(`🔑 Using executive persona tokens as fallback`);
345
+ accessToken = executive.personaAccessToken;
346
+ refreshToken = executive.personaRefreshToken;
347
+ }
348
+ else {
349
+ // Use default persona tokens as last resort
350
+ console.log(`🔑 Using default ${fraim_config_1.fraimConfig.personaName} tokens as fallback`);
351
+ accessToken = fraim_config_1.fraimConfig.defaultAccessToken;
352
+ refreshToken = fraim_config_1.fraimConfig.defaultRefreshToken;
353
+ if (!accessToken || !refreshToken) {
354
+ throw new Error(`${fraim_config_1.fraimConfig.personaName} Gmail tokens not found. Need either identity tokens, executive tokens, or default tokens in environment variables.`);
355
+ }
356
+ }
357
+ // Verify the From email matches the authenticated account (Gmail requirement)
358
+ // For plus addressing, the base email should match
359
+ const fromBaseEmail = fromEmail.includes('+')
360
+ ? fromEmail.split('+')[0] + '@' + fromEmail.split('@')[1]
361
+ : fromEmail;
362
+ console.log(`📧 Sending from: "${fromDisplayName}" <${fromEmail}>`);
363
+ // Generate HTML email from template (use structured format if available)
364
+ const greeting = params.candidate?.greeting || 'Hi there,';
365
+ const htmlBody = generateHtmlEmail({
366
+ displayName: extractFirstName(greeting) || extractFirstName(body) || extractFirstName(fromDisplayName) || 'there',
367
+ greeting: greeting,
368
+ opening: params.candidate?.opening
369
+ ? convertTextToHtml(params.candidate.opening)
370
+ : convertBodyToHtml(body), // Fallback to legacy body
371
+ improvements: params.candidate?.improvements || [],
372
+ closing: params.candidate?.closing || '',
373
+ executiveName: extractExecutiveName(fromDisplayName),
374
+ fromEmail
375
+ });
376
+ // Create multipart email message (plain text + HTML)
377
+ const boundary = `boundary_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
378
+ const emailMessage = [
379
+ `To: ${to}`,
380
+ `From: ${fromDisplayName} <${fromEmail}>`,
381
+ `Subject: ${subject}`,
382
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
383
+ `MIME-Version: 1.0`,
384
+ ``,
385
+ `--${boundary}`,
386
+ `Content-Type: text/plain; charset=utf-8`,
387
+ `Content-Transfer-Encoding: 7bit`,
388
+ ``,
389
+ body,
390
+ ``,
391
+ `--${boundary}`,
392
+ `Content-Type: text/html; charset=utf-8`,
393
+ `Content-Transfer-Encoding: 7bit`,
394
+ ``,
395
+ htmlBody,
396
+ ``,
397
+ `--${boundary}--`
398
+ ].join('\r\n');
399
+ // Send email using Gmail API
400
+ const url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages/send';
401
+ const requestBody = {
402
+ raw: Buffer.from(emailMessage).toString('base64')
403
+ .replace(/\+/g, '-')
404
+ .replace(/\//g, '_')
405
+ .replace(/=+$/, '')
406
+ };
407
+ const response = await fetch(url, {
408
+ method: 'POST',
409
+ headers: {
410
+ 'Authorization': `Bearer ${accessToken}`,
411
+ 'Content-Type': 'application/json',
412
+ },
413
+ body: JSON.stringify(requestBody)
414
+ });
415
+ if (!response.ok) {
416
+ if (response.status === 401) {
417
+ console.log('🔄 Access token expired, refreshing...');
418
+ // Refresh the access token
419
+ const clientId = fraim_config_1.fraimConfig.defaultOAuthClientId || process.env.FRAIM_DEFAULT_OAUTH_CLIENT_ID || process.env.PERSONA_DEFAULT_OAUTH_CLIENT_ID;
420
+ const clientSecret = fraim_config_1.fraimConfig.defaultOAuthClientSecret || process.env.FRAIM_DEFAULT_OAUTH_CLIENT_SECRET || process.env.PERSONA_DEFAULT_OAUTH_CLIENT_SECRET;
421
+ if (!clientId || !clientSecret) {
422
+ throw new Error('FRAIM_DEFAULT_OAUTH_CLIENT_ID and FRAIM_DEFAULT_OAUTH_CLIENT_SECRET environment variables are required for token refresh');
423
+ }
424
+ console.log('🔄 Refreshing token...');
425
+ const refreshResponse = await fetch('https://oauth2.googleapis.com/token', {
426
+ method: 'POST',
427
+ headers: {
428
+ 'Content-Type': 'application/x-www-form-urlencoded',
429
+ },
430
+ body: new URLSearchParams({
431
+ client_id: clientId,
432
+ client_secret: clientSecret,
433
+ refresh_token: refreshToken,
434
+ grant_type: 'refresh_token'
435
+ })
436
+ });
437
+ if (!refreshResponse.ok) {
438
+ const errorText = await refreshResponse.text();
439
+ console.error('❌ Token refresh failed:', refreshResponse.status, errorText);
440
+ throw new Error(`Failed to refresh access token: ${refreshResponse.status} - ${errorText}`);
441
+ }
442
+ const tokenData = await refreshResponse.json();
443
+ const newAccessToken = tokenData.access_token;
444
+ console.log('✅ Token refreshed, retrying email send...');
445
+ // Retry with new token
446
+ const retryResponse = await fetch(url, {
447
+ method: 'POST',
448
+ headers: {
449
+ 'Authorization': `Bearer ${newAccessToken}`,
450
+ 'Content-Type': 'application/json',
451
+ },
452
+ body: JSON.stringify(requestBody)
453
+ });
454
+ if (!retryResponse.ok) {
455
+ const errorText = await retryResponse.text();
456
+ throw new Error(`Gmail API error after refresh: ${retryResponse.status} - ${errorText}`);
457
+ }
458
+ const result = await retryResponse.json();
459
+ console.log(`✅ Email sent successfully to ${to}`);
460
+ console.log(`📧 Email ID: ${result.id}`);
461
+ return;
462
+ }
463
+ const errorText = await response.text();
464
+ throw new Error(`Gmail API error: ${response.status} - ${errorText}`);
465
+ }
466
+ const result = await response.json();
467
+ console.log(`✅ Email sent successfully to ${to}`);
468
+ console.log(`📧 Email ID: ${result.id}`);
469
+ }
470
+ /**
471
+ * Generate HTML email from template
472
+ */
473
+ function generateHtmlEmail(params) {
474
+ const templatePath = getTemplatePath();
475
+ let template = (0, fs_1.readFileSync)(templatePath, 'utf-8');
476
+ // Replace simple template variables
477
+ template = template.replace(/\{\{displayName\}\}/g, escapeHtml(params.displayName));
478
+ template = template.replace(/\{\{executiveName\}\}/g, escapeHtml(params.executiveName));
479
+ template = template.replace(/\{\{personaName\}\}/g, escapeHtml(fraim_config_1.fraimConfig.personaName));
480
+ template = template.replace(/\{\{chatUrl\}\}/g, escapeHtml(fraim_config_1.fraimConfig.chatUrl || '#'));
481
+ template = template.replace(/\{\{webAppUrl\}\}/g, escapeHtml(fraim_config_1.fraimConfig.webAppUrl || '#'));
482
+ template = template.replace(/\{\{fromEmail\}\}/g, escapeHtml(params.fromEmail));
483
+ template = template.replace(/\{\{greeting\}\}/g, escapeHtml(params.greeting));
484
+ template = template.replace(/\{\{opening\}\}/g, params.opening);
485
+ // Generate improvements list HTML
486
+ const hasImprovements = params.improvements && params.improvements.length > 0;
487
+ if (hasImprovements) {
488
+ const improvementsHtml = params.improvements.map((improvement, index) => {
489
+ 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'};">`;
490
+ html += `<div style="font-size: 16px; font-weight: 600; color: #333333; margin-bottom: 8px;">${escapeHtml(improvement.title)}</div>`;
491
+ html += `<div style="font-size: 15px; color: #555555; line-height: 1.7; margin-bottom: ${improvement.verification ? '10px' : '0'};">${convertTextToHtml(improvement.description)}</div>`;
492
+ if (improvement.verification) {
493
+ 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>`;
494
+ }
495
+ html += `</div>`;
496
+ return html;
497
+ }).join('');
498
+ const improvementsSection = `
499
+ <tr>
500
+ <td style="padding: 0 30px 20px 30px;">
501
+ <div style="background-color: #f8f9fa; border-left: 4px solid #667eea; border-radius: 6px; padding: 20px; margin: 20px 0;">
502
+ <div style="font-size: 18px; font-weight: 600; color: #333333; margin-bottom: 16px;">
503
+ ✨ What's Fixed
504
+ </div>
505
+ ${improvementsHtml}
506
+ </div>
507
+ </td>
508
+ </tr>`;
509
+ template = template.replace(/\{\{#if hasImprovements\}\}[\s\S]*?\{\{\/if\}\}/, improvementsSection);
510
+ }
511
+ else {
512
+ // Remove conditional block if no improvements
513
+ template = template.replace(/\{\{#if hasImprovements\}\}[\s\S]*?\{\{\/if\}\}/, '');
514
+ }
515
+ // Replace closing paragraph
516
+ if (params.closing) {
517
+ template = template.replace(/\{\{#if closing\}\}[\s\S]*?\{\{\/if\}\}/, `
518
+ <tr>
519
+ <td style="padding: 0 30px 20px 30px;">
520
+ <div style="font-size: 16px; color: #555555; line-height: 1.8;">
521
+ ${convertTextToHtml(params.closing)}
522
+ </div>
523
+ </td>
524
+ </tr>`);
525
+ }
526
+ else {
527
+ template = template.replace(/\{\{#if closing\}\}[\s\S]*?\{\{\/if\}\}/, '');
528
+ }
529
+ return template;
530
+ }
531
+ /**
532
+ * Generate plain text body from candidate (supports both structured and legacy formats)
533
+ */
534
+ function generatePlainTextBody(candidate) {
535
+ // If structured format exists, use it
536
+ if (candidate.greeting && candidate.opening) {
537
+ let body = `${candidate.greeting}\n\n${candidate.opening}\n\n`;
538
+ if (candidate.improvements && candidate.improvements.length > 0) {
539
+ body += `**What was improved:**\n\n`;
540
+ candidate.improvements.forEach((improvement, index) => {
541
+ body += `${index + 1}. ${improvement.title}: ${improvement.description}`;
542
+ if (improvement.verification) {
543
+ body += `\n **How to verify:** ${improvement.verification}`;
544
+ }
545
+ body += `\n\n`;
546
+ });
547
+ }
548
+ if (candidate.closing) {
549
+ body += `${candidate.closing}\n\n`;
550
+ }
551
+ body += (0, fraim_config_1.formatPersonaSignature)();
552
+ return body;
553
+ }
554
+ // Fallback to legacy body format
555
+ return candidate.body || '';
556
+ }
557
+ /**
558
+ * Extract first name from text
559
+ */
560
+ function extractFirstName(text) {
561
+ // Try to find "Hi [Name]" pattern
562
+ const hiMatch = text.match(/\b[Hh]i\s+([A-Z][a-z]+)/);
563
+ if (hiMatch) {
564
+ return hiMatch[1];
565
+ }
566
+ // Try to find comma after greeting
567
+ const commaMatch = text.match(/^[Hh]i\s+([^,]+),/);
568
+ if (commaMatch) {
569
+ return commaMatch[1].trim().split(' ')[0];
570
+ }
571
+ return null;
572
+ }
573
+ /**
574
+ * Extract executive name from display name
575
+ */
576
+ function extractExecutiveName(displayName) {
577
+ // "{Persona} - [Name]'s AI Executive Assistant"
578
+ // We need to match based on the configured pattern
579
+ const pattern = fraim_config_1.fraimConfig.personaDisplayNamePattern.replace('{executiveName}', '(.+?)');
580
+ try {
581
+ // If pattern contains regex characters, they need expanding or escaping?
582
+ // This is simple pattern matching.
583
+ // Example: "Persona - {executiveName}'s AI Executive Assistant"
584
+ // Regex: /Persona - (.+?)'s AI Executive Assistant/
585
+ // We escape special chars except the group we added
586
+ const escapedPattern = pattern
587
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // Escape regex chars
588
+ .replace('\\(\\.+\\?\\)', '(.+?)'); // Restore capture group
589
+ const match = displayName.match(new RegExp(escapedPattern));
590
+ return match ? match[1] : 'Your';
591
+ }
592
+ catch (e) {
593
+ return 'Your';
594
+ }
595
+ }
596
+ /**
597
+ * Convert plain text to HTML (for legacy body format)
598
+ */
599
+ function convertBodyToHtml(body) {
600
+ return convertTextToHtml(body);
601
+ }
602
+ /**
603
+ * Convert text to HTML (preserves markdown-style formatting)
604
+ */
605
+ function convertTextToHtml(text) {
606
+ if (!text)
607
+ return '';
608
+ let html = text;
609
+ // Convert markdown-style bold **text** to <strong>text</strong>
610
+ html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
611
+ // Convert line breaks to paragraphs
612
+ html = html.replace(/\n\n+/g, '</p><p style="margin: 12px 0;">');
613
+ html = html.replace(/\n/g, '<br>');
614
+ // Wrap in paragraph tags
615
+ html = `<p style="margin: 0 0 12px 0;">${html}</p>`;
616
+ // Clean up empty paragraphs
617
+ html = html.replace(/<p[^>]*><\/p>/g, '');
618
+ return html;
619
+ }
620
+ /**
621
+ * Escape HTML special characters
622
+ */
623
+ function escapeHtml(text) {
624
+ return text
625
+ .replace(/&/g, '&amp;')
626
+ .replace(/</g, '&lt;')
627
+ .replace(/>/g, '&gt;')
628
+ .replace(/"/g, '&quot;')
629
+ .replace(/'/g, '&#039;');
630
+ }