fraim-framework 2.0.35 → 2.0.37

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 (159) hide show
  1. package/dist/registry/scripts/cleanup-branch.js +62 -33
  2. package/dist/registry/scripts/generate-engagement-emails.js +119 -44
  3. package/dist/registry/scripts/newsletter-helpers.js +208 -268
  4. package/dist/registry/scripts/profile-server.js +387 -0
  5. package/dist/scripts/build-stub-registry.js +108 -0
  6. package/dist/src/cli/commands/doctor.js +5 -5
  7. package/dist/src/cli/commands/sync.js +33 -19
  8. package/dist/tests/test-client-scripts-validation.js +133 -0
  9. package/dist/tests/test-package-size.js +88 -0
  10. package/dist/tests/test-script-location-independence.js +76 -28
  11. package/dist/tests/test-stub-registry.js +120 -0
  12. package/dist/tests/test-sync-stubs.js +143 -0
  13. package/package.json +7 -9
  14. package/registry/scripts/cleanup-branch.ts +341 -0
  15. package/registry/scripts/generate-engagement-emails.ts +830 -0
  16. package/registry/scripts/markdown-to-pdf.js +7 -3
  17. package/registry/scripts/newsletter-helpers.ts +777 -0
  18. package/registry/scripts/profile-server.ts +424 -0
  19. package/registry/scripts/run-thank-you-workflow.ts +122 -0
  20. package/registry/scripts/send-newsletter-simple.ts +102 -0
  21. package/registry/scripts/send-thank-you-emails.ts +57 -0
  22. package/registry/stubs/workflows/bootstrap/create-architecture.md +11 -0
  23. package/registry/stubs/workflows/bootstrap/detect-broken-windows.md +11 -0
  24. package/registry/stubs/workflows/bootstrap/evaluate-code-quality.md +11 -0
  25. package/registry/stubs/workflows/bootstrap/verify-test-coverage.md +11 -0
  26. package/registry/stubs/workflows/business-development/create-business-plan.md +11 -0
  27. package/registry/stubs/workflows/business-development/ideate-business-opportunity.md +11 -0
  28. package/registry/stubs/workflows/business-development/price-product.md +18 -0
  29. package/registry/stubs/workflows/convert-to-pdf.md +11 -0
  30. package/registry/stubs/workflows/customer-development/insight-analysis.md +11 -0
  31. package/registry/stubs/workflows/customer-development/insight-triage.md +11 -0
  32. package/registry/stubs/workflows/customer-development/interview-preparation.md +11 -0
  33. package/registry/stubs/workflows/customer-development/linkedin-outreach.md +11 -0
  34. package/registry/stubs/workflows/customer-development/strategic-brainstorming.md +11 -0
  35. package/registry/stubs/workflows/customer-development/thank-customers.md +11 -0
  36. package/registry/stubs/workflows/customer-development/weekly-newsletter.md +11 -0
  37. package/registry/stubs/workflows/deploy/cloud-deployment.md +11 -0
  38. package/registry/stubs/workflows/improve-fraim/contribute.md +11 -0
  39. package/registry/stubs/workflows/improve-fraim/file-issue.md +11 -0
  40. package/registry/stubs/workflows/marketing/content-creation.md +11 -0
  41. package/registry/stubs/workflows/marketing/hbr-article.md +11 -0
  42. package/registry/stubs/workflows/marketing/launch-checklist.md +11 -0
  43. package/registry/stubs/workflows/marketing/marketing-strategy.md +11 -0
  44. package/registry/stubs/workflows/marketing/storytelling.md +11 -0
  45. package/registry/stubs/workflows/performance/analyze-performance.md +11 -0
  46. package/registry/stubs/workflows/product-building/design.md +11 -0
  47. package/registry/stubs/workflows/product-building/implement.md +12 -0
  48. package/registry/stubs/workflows/product-building/iterate-on-pr-comments.md +11 -0
  49. package/registry/stubs/workflows/product-building/prep-issue.md +11 -0
  50. package/registry/stubs/workflows/product-building/prototype.md +11 -0
  51. package/registry/stubs/workflows/product-building/resolve.md +11 -0
  52. package/registry/stubs/workflows/product-building/retrospect.md +11 -0
  53. package/registry/stubs/workflows/product-building/spec.md +11 -0
  54. package/registry/stubs/workflows/product-building/test.md +11 -0
  55. package/registry/stubs/workflows/quality-assurance/browser-validation.md +11 -0
  56. package/registry/stubs/workflows/quality-assurance/iterative-improvement-cycle.md +11 -0
  57. package/registry/stubs/workflows/replicate/replicate-discovery.md +11 -0
  58. package/registry/stubs/workflows/replicate/replicate-to-issues.md +11 -0
  59. package/registry/stubs/workflows/reviewer/review-implementation-vs-design-spec.md +11 -0
  60. package/registry/stubs/workflows/reviewer/review-implementation-vs-feature-spec.md +11 -0
  61. package/registry/stubs/workflows/startup-credits/aws-activate-application.md +11 -0
  62. package/registry/stubs/workflows/startup-credits/google-cloud-application.md +11 -0
  63. package/registry/stubs/workflows/startup-credits/microsoft-azure-application.md +11 -0
  64. package/.github/workflows/ci.yml +0 -65
  65. package/.github/workflows/deploy-fraim.yml +0 -87
  66. package/.github/workflows/phase-change.yml +0 -251
  67. package/.github/workflows/status-change.yml +0 -68
  68. package/.github/workflows/sync-on-pr-review.yml +0 -66
  69. package/examples/simple-webapp/TESTING.md +0 -62
  70. package/examples/simple-webapp/example-test.ts +0 -186
  71. package/registry/github/workflows/ci.yml +0 -51
  72. package/registry/github/workflows/phase-change.yml +0 -251
  73. package/registry/github/workflows/status-change.yml +0 -68
  74. package/registry/github/workflows/sync-on-pr-review.yml +0 -66
  75. package/registry/mcp-template.jsonc +0 -29
  76. package/registry/rules/agent-success-criteria.md +0 -52
  77. package/registry/rules/agent-testing-guidelines.md +0 -502
  78. package/registry/rules/architecture.md +0 -52
  79. package/registry/rules/communication.md +0 -122
  80. package/registry/rules/continuous-learning.md +0 -55
  81. package/registry/rules/debugging-multitenancy-issues.md +0 -85
  82. package/registry/rules/ephemeral-execution.md +0 -57
  83. package/registry/rules/git-safe-commands.md +0 -34
  84. package/registry/rules/hitl-ppe-record-analysis.md +0 -302
  85. package/registry/rules/integrity-and-test-ethics.md +0 -275
  86. package/registry/rules/local-development.md +0 -254
  87. package/registry/rules/merge-requirements.md +0 -231
  88. package/registry/rules/simplicity.md +0 -118
  89. package/registry/rules/software-development-lifecycle.md +0 -105
  90. package/registry/rules/spike-first-development.md +0 -205
  91. package/registry/rules/successful-debugging-patterns.md +0 -491
  92. package/registry/rules/telemetry.md +0 -67
  93. package/registry/templates/bootstrap/ARCHITECTURE-TEMPLATE.md +0 -53
  94. package/registry/templates/bootstrap/CODE-QUALITY-REPORT-TEMPLATE.md +0 -37
  95. package/registry/templates/bootstrap/TEST-COVERAGE-REPORT-TEMPLATE.md +0 -35
  96. package/registry/templates/business-development/IDEATION-REPORT-TEMPLATE.md +0 -29
  97. package/registry/templates/business-development/PRICING-STRATEGY-TEMPLATE.md +0 -126
  98. package/registry/templates/customer-development/customer-interview-template.md +0 -99
  99. package/registry/templates/customer-development/follow-up-email-templates.md +0 -132
  100. package/registry/templates/customer-development/insight-analysis-template.md +0 -74
  101. package/registry/templates/customer-development/strategic-recommendations-template.md +0 -53
  102. package/registry/templates/customer-development/thank-you-email-template.html +0 -124
  103. package/registry/templates/customer-development/thank-you-note-template.md +0 -16
  104. package/registry/templates/customer-development/triage-log-template.md +0 -278
  105. package/registry/templates/customer-development/weekly-newsletter-template.html +0 -204
  106. package/registry/templates/evidence/Design-Evidence.md +0 -30
  107. package/registry/templates/evidence/Implementation-BugEvidence.md +0 -86
  108. package/registry/templates/evidence/Implementation-FeatureEvidence.md +0 -121
  109. package/registry/templates/evidence/Spec-Evidence.md +0 -19
  110. package/registry/templates/help/HelpNeeded.md +0 -14
  111. package/registry/templates/marketing/HBR-ARTICLE-TEMPLATE.md +0 -66
  112. package/registry/templates/marketing/STORYTELLING-TEMPLATE.md +0 -130
  113. package/registry/templates/replicate/implementation-checklist.md +0 -39
  114. package/registry/templates/replicate/use-cases-template.md +0 -88
  115. package/registry/templates/retrospective/RETROSPECTIVE-TEMPLATE.md +0 -55
  116. package/registry/templates/specs/BUGSPEC-TEMPLATE.md +0 -37
  117. package/registry/templates/specs/FEATURESPEC-TEMPLATE.md +0 -29
  118. package/registry/templates/specs/TECHSPEC-TEMPLATE.md +0 -39
  119. package/registry/workflows/bootstrap/create-architecture.md +0 -38
  120. package/registry/workflows/bootstrap/evaluate-code-quality.md +0 -36
  121. package/registry/workflows/bootstrap/verify-test-coverage.md +0 -37
  122. package/registry/workflows/business-development/create-business-plan.md +0 -737
  123. package/registry/workflows/business-development/ideate-business-opportunity.md +0 -55
  124. package/registry/workflows/business-development/price-product.md +0 -325
  125. package/registry/workflows/convert-to-pdf.md +0 -235
  126. package/registry/workflows/customer-development/insight-analysis.md +0 -156
  127. package/registry/workflows/customer-development/insight-triage.md +0 -933
  128. package/registry/workflows/customer-development/interview-preparation.md +0 -421
  129. package/registry/workflows/customer-development/linkedin-outreach.md +0 -593
  130. package/registry/workflows/customer-development/strategic-brainstorming.md +0 -146
  131. package/registry/workflows/customer-development/thank-customers.md +0 -203
  132. package/registry/workflows/customer-development/weekly-newsletter.md +0 -366
  133. package/registry/workflows/deploy/cloud-deployment.md +0 -310
  134. package/registry/workflows/improve-fraim/contribute.md +0 -32
  135. package/registry/workflows/improve-fraim/file-issue.md +0 -32
  136. package/registry/workflows/marketing/content-creation.md +0 -37
  137. package/registry/workflows/marketing/hbr-article.md +0 -73
  138. package/registry/workflows/marketing/launch-checklist.md +0 -37
  139. package/registry/workflows/marketing/marketing-strategy.md +0 -45
  140. package/registry/workflows/marketing/storytelling.md +0 -65
  141. package/registry/workflows/performance/analyze-performance.md +0 -65
  142. package/registry/workflows/product-building/design.md +0 -130
  143. package/registry/workflows/product-building/implement.md +0 -315
  144. package/registry/workflows/product-building/iterate-on-pr-comments.md +0 -70
  145. package/registry/workflows/product-building/prep-issue.md +0 -43
  146. package/registry/workflows/product-building/prototype.md +0 -60
  147. package/registry/workflows/product-building/resolve.md +0 -164
  148. package/registry/workflows/product-building/retrospect.md +0 -86
  149. package/registry/workflows/product-building/spec.md +0 -117
  150. package/registry/workflows/product-building/test.md +0 -120
  151. package/registry/workflows/quality-assurance/browser-validation.md +0 -221
  152. package/registry/workflows/quality-assurance/iterative-improvement-cycle.md +0 -562
  153. package/registry/workflows/replicate/replicate-discovery.md +0 -336
  154. package/registry/workflows/replicate/replicate-to-issues.md +0 -319
  155. package/registry/workflows/reviewer/review-implementation-vs-design-spec.md +0 -632
  156. package/registry/workflows/reviewer/review-implementation-vs-feature-spec.md +0 -669
  157. package/registry/workflows/startup-credits/aws-activate-application.md +0 -535
  158. package/registry/workflows/startup-credits/google-cloud-application.md +0 -647
  159. package/registry/workflows/startup-credits/microsoft-azure-application.md +0 -538
@@ -0,0 +1,424 @@
1
+ #!/usr/bin/env npx tsx
2
+
3
+ import { execSync } from 'child_process';
4
+ import { readFileSync, existsSync } from 'fs';
5
+ import { join } from 'path';
6
+
7
+ /**
8
+ * Production Server Profiler
9
+ * Automates the analysis of Azure App Service performance for coding agents.
10
+ *
11
+ * Usage: npx tsx profile-server.ts [--prod|--preprod|--local] [--logs]
12
+ *
13
+ * Self-contained script - reads configuration from .fraim/config.json
14
+ * Requires: Azure CLI (az) installed and authenticated
15
+ */
16
+
17
+ // Self-contained configuration loading
18
+ interface FraimConfig {
19
+ persona: { name: string };
20
+ azure?: {
21
+ prodAppName?: string;
22
+ prodResourceGroup?: string;
23
+ preprodAppName?: string;
24
+ preprodResourceGroup?: string;
25
+ localAppName?: string;
26
+ localResourceGroup?: string;
27
+ };
28
+ }
29
+
30
+ function loadClientConfig(): FraimConfig {
31
+ const configPath = join(process.cwd(), '.fraim', 'config.json');
32
+ if (!existsSync(configPath)) {
33
+ throw new Error('.fraim/config.json not found. Run fraim init first.');
34
+ }
35
+ return JSON.parse(readFileSync(configPath, 'utf-8'));
36
+ }
37
+
38
+ function getEnvOr(keys: string[], fallback: string): string {
39
+ for (const key of keys) {
40
+ const value = process.env[key];
41
+ if (value && value.length) return value;
42
+ }
43
+ return fallback;
44
+ }
45
+
46
+ interface ProfilingConfig {
47
+ env: 'prod' | 'preprod' | 'local';
48
+ appName: string;
49
+ resourceGroup: string;
50
+ }
51
+
52
+ function checkAzureCLI(): boolean {
53
+ try {
54
+ execSync('az --version', { stdio: 'pipe' });
55
+ return true;
56
+ } catch (error) {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ function checkAzureAuth(): boolean {
62
+ try {
63
+ execSync('az account show', { stdio: 'pipe' });
64
+ return true;
65
+ } catch (error) {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ async function getAppServicePlanMetrics(appName: string, resourceGroup: string): Promise<void> {
71
+ try {
72
+ console.log('\n--- ā˜ļø App Service Plan Metrics ---');
73
+
74
+ // Get App Service Plan ID
75
+ const planIdCmd = `az webapp show --name ${appName} --resource-group ${resourceGroup} --query "appServicePlanId" -o tsv`;
76
+ const planId = execSync(planIdCmd, { encoding: 'utf8' }).trim();
77
+ const planName = planId.split('/').pop();
78
+ console.log(`šŸ“‹ Plan: ${planName}`);
79
+
80
+ // Get CPU and Memory metrics for last 5 minutes
81
+ console.log('šŸ“Š Fetching CPU and Memory metrics (last 5 minutes)...');
82
+ const metricsCmd = `az monitor metrics list --resource "${planId}" --metrics CpuPercentage MemoryPercentage --interval PT1M --query "value[].{name:name.value, data:timeseries[0].data}" -o json`;
83
+
84
+ const metricsOutput = execSync(metricsCmd, { encoding: 'utf8' });
85
+ const metrics = JSON.parse(metricsOutput);
86
+
87
+ for (const metric of metrics) {
88
+ const latestData = metric.data[metric.data.length - 1];
89
+ const value = latestData?.average || latestData?.total || 'N/A';
90
+ console.log(` ${metric.name}: ${typeof value === 'number' ? value.toFixed(2) + '%' : value}`);
91
+ }
92
+ } catch (error: any) {
93
+ console.log(`āš ļø Could not fetch App Service Plan metrics: ${error.message.split('\n')[0]}`);
94
+ }
95
+ }
96
+
97
+ async function getAppServiceMetrics(appName: string, resourceGroup: string): Promise<void> {
98
+ try {
99
+ console.log('\n--- šŸ–„ļø App Service Metrics ---');
100
+
101
+ // Get subscription ID
102
+ const subscriptionId = execSync('az account show --query id -o tsv', { encoding: 'utf8' }).trim();
103
+
104
+ // Get app-level metrics using Azure CLI
105
+ console.log('šŸ“Š Fetching App Service metrics (last 5 minutes)...');
106
+ const appResourceId = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Web/sites/${appName}`;
107
+
108
+ const appMetricsCmd = `az monitor metrics list --resource "${appResourceId}" --metrics CpuTime Requests Http2xx Http4xx Http5xx --interval PT1M --query "value[].{name:name.value, data:timeseries[0].data}" -o json`;
109
+
110
+ const appMetricsOutput = execSync(appMetricsCmd, { encoding: 'utf8' });
111
+ const appMetrics = JSON.parse(appMetricsOutput);
112
+
113
+ for (const metric of appMetrics) {
114
+ const latestData = metric.data[metric.data.length - 1];
115
+ const value = latestData?.total || latestData?.average || 'N/A';
116
+ let displayValue = value;
117
+
118
+ if (typeof value === 'number') {
119
+ if (metric.name === 'CpuTime') {
120
+ displayValue = `${value.toFixed(2)}s`;
121
+ } else {
122
+ displayValue = value.toString();
123
+ }
124
+ }
125
+
126
+ console.log(` ${metric.name}: ${displayValue}`);
127
+ }
128
+ } catch (error: any) {
129
+ console.log(`āš ļø Could not fetch App Service metrics: ${error.message.split('\n')[0]}`);
130
+ }
131
+ }
132
+
133
+ async function getProcessInformation(appName: string): Promise<void> {
134
+ try {
135
+ console.log('\n--- āš™ļø Process Information (Kudu API) ---');
136
+
137
+ // Get access token for Kudu API
138
+ const token = execSync('az account get-access-token --resource https://management.azure.com/ --query accessToken -o tsv', { encoding: 'utf8' }).trim();
139
+
140
+ // Import axios dynamically
141
+ const axios = (await import('axios')).default;
142
+
143
+ // Get process list from Kudu
144
+ console.log('šŸ“‹ Fetching running processes...');
145
+ const processResponse = await axios.get(`https://${appName}.scm.azurewebsites.net/api/processes`, {
146
+ headers: { Authorization: `Bearer ${token}` },
147
+ timeout: 10000
148
+ });
149
+
150
+ const processes = processResponse.data;
151
+
152
+ // Sort by CPU usage and show top processes
153
+ const sortedProcesses = processes
154
+ .filter((p: any) => p.cpu_usage !== undefined)
155
+ .sort((a: any, b: any) => (b.cpu_usage || 0) - (a.cpu_usage || 0))
156
+ .slice(0, 10);
157
+
158
+ console.log('\nšŸ”„ Top 10 Processes by CPU Usage:');
159
+ console.log('PID\tCPU%\tMemory(MB)\tName');
160
+ console.log('---\t----\t---------\t----');
161
+
162
+ for (const process of sortedProcesses) {
163
+ const pid = process.id || 'N/A';
164
+ const cpu = process.cpu_usage ? process.cpu_usage.toFixed(2) : '0.00';
165
+ const memory = process.working_set ? (process.working_set / 1024 / 1024).toFixed(1) : 'N/A';
166
+ const name = process.name || 'Unknown';
167
+
168
+ console.log(`${pid}\t${cpu}\t${memory}\t\t${name.substring(0, 30)}`);
169
+ }
170
+
171
+ } catch (error: any) {
172
+ console.log(`āš ļø Could not fetch process information: ${error.message.split('\n')[0]}`);
173
+ console.log(' This might be due to authentication issues or Kudu API being unavailable.');
174
+ }
175
+ }
176
+
177
+ async function getSystemInformation(appName: string): Promise<void> {
178
+ try {
179
+ console.log('\n--- šŸ–„ļø System Information ---');
180
+
181
+ const token = execSync('az account get-access-token --resource https://management.azure.com/ --query accessToken -o tsv', { encoding: 'utf8' }).trim();
182
+ const axios = (await import('axios')).default;
183
+
184
+ // Get system info using Kudu command API
185
+ console.log('šŸ“Š Fetching system information...');
186
+
187
+ const commands = [
188
+ { name: 'Memory Info', cmd: 'cat /proc/meminfo | head -10' },
189
+ { name: 'CPU Info', cmd: 'cat /proc/cpuinfo | grep "model name" | head -1' },
190
+ { name: 'Disk Usage', cmd: 'df -h | head -5' },
191
+ { name: 'Load Average', cmd: 'uptime' }
192
+ ];
193
+
194
+ for (const command of commands) {
195
+ try {
196
+ const response = await axios.post(`https://${appName}.scm.azurewebsites.net/api/command`, {
197
+ command: command.cmd,
198
+ dir: '/home'
199
+ }, {
200
+ headers: { Authorization: `Bearer ${token}` },
201
+ timeout: 5000
202
+ });
203
+
204
+ console.log(`\n${command.name}:`);
205
+ const output = response.data.Output || response.data.Error || 'No output';
206
+ console.log(output.split('\n').map((line: string) => ` ${line}`).join('\n'));
207
+
208
+ } catch (cmdError: any) {
209
+ console.log(`\n${command.name}: Could not retrieve (${cmdError.message.split('\n')[0]})`);
210
+ }
211
+ }
212
+
213
+ } catch (error: any) {
214
+ console.log(`āš ļø Could not fetch system information: ${error.message.split('\n')[0]}`);
215
+ }
216
+ }
217
+
218
+ async function getApplicationLogs(appName: string, resourceGroup: string): Promise<void> {
219
+ try {
220
+ console.log('\n--- šŸ“‹ Recent Application Logs ---');
221
+
222
+ // Get recent logs using Azure CLI
223
+ console.log('šŸ“„ Fetching recent application logs...');
224
+ const logsCmd = `az webapp log tail --name ${appName} --resource-group ${resourceGroup} --provider application --timeout 5`;
225
+
226
+ try {
227
+ const logs = execSync(logsCmd, { encoding: 'utf8', timeout: 10000 });
228
+ console.log('Recent logs:');
229
+ console.log(logs.split('\n').slice(-20).map(line => ` ${line}`).join('\n'));
230
+ } catch (logError) {
231
+ console.log('āš ļø Could not fetch logs - they may not be enabled or available');
232
+ console.log(' Enable application logging in Azure portal for better diagnostics');
233
+ }
234
+
235
+ } catch (error: any) {
236
+ console.log(`āš ļø Could not fetch application logs: ${error.message.split('\n')[0]}`);
237
+ }
238
+ }
239
+
240
+ async function profileLocalEnvironment(): Promise<void> {
241
+ console.log('\n--- šŸ  Local Environment Profiling ---');
242
+
243
+ try {
244
+ // Basic system information
245
+ console.log('šŸ’» System Information:');
246
+
247
+ if (process.platform === 'win32') {
248
+ try {
249
+ const systemInfo = execSync('systeminfo | findstr /C:"Total Physical Memory" /C:"Available Physical Memory" /C:"Processor"', { encoding: 'utf8' });
250
+ console.log(systemInfo.split('\n').map(line => ` ${line.trim()}`).filter(line => line).join('\n'));
251
+ } catch {
252
+ console.log(' Could not retrieve Windows system info');
253
+ }
254
+ } else {
255
+ try {
256
+ const memInfo = execSync('free -h', { encoding: 'utf8' });
257
+ const cpuInfo = execSync('cat /proc/cpuinfo | grep "model name" | head -1', { encoding: 'utf8' });
258
+ console.log(' Memory:');
259
+ console.log(memInfo.split('\n').map(line => ` ${line}`).join('\n'));
260
+ console.log(' CPU:');
261
+ console.log(` ${cpuInfo.trim()}`);
262
+ } catch {
263
+ console.log(' Could not retrieve Linux system info');
264
+ }
265
+ }
266
+
267
+ // Node.js process information
268
+ console.log('\n🟢 Node.js Process Information:');
269
+ console.log(` Node Version: ${process.version}`);
270
+ console.log(` Platform: ${process.platform}`);
271
+ console.log(` Architecture: ${process.arch}`);
272
+ console.log(` Memory Usage:`);
273
+ const memUsage = process.memoryUsage();
274
+ console.log(` RSS: ${(memUsage.rss / 1024 / 1024).toFixed(2)} MB`);
275
+ console.log(` Heap Used: ${(memUsage.heapUsed / 1024 / 1024).toFixed(2)} MB`);
276
+ console.log(` Heap Total: ${(memUsage.heapTotal / 1024 / 1024).toFixed(2)} MB`);
277
+ console.log(` External: ${(memUsage.external / 1024 / 1024).toFixed(2)} MB`);
278
+
279
+ } catch (error: any) {
280
+ console.log(`āš ļø Error profiling local environment: ${error.message}`);
281
+ }
282
+ }
283
+
284
+ async function main() {
285
+ const config = loadClientConfig();
286
+
287
+ // Azure configuration with environment variable fallbacks
288
+ const azureConfig = {
289
+ prodAppName: config.azure?.prodAppName || getEnvOr(['FRAIM_AZURE_PROD_APP_NAME'], 'fraim-app-prod'),
290
+ prodResourceGroup: config.azure?.prodResourceGroup || getEnvOr(['FRAIM_AZURE_PROD_RESOURCE_GROUP'], 'fraim-prod-rg'),
291
+ preprodAppName: config.azure?.preprodAppName || getEnvOr(['FRAIM_AZURE_PREPROD_APP_NAME'], 'fraim-app-pre-prod'),
292
+ preprodResourceGroup: config.azure?.preprodResourceGroup || getEnvOr(['FRAIM_AZURE_PREPROD_RESOURCE_GROUP'], 'fraim-pre-prod-rg'),
293
+ localAppName: config.azure?.localAppName || getEnvOr(['FRAIM_AZURE_LOCAL_APP_NAME'], 'local'),
294
+ localResourceGroup: config.azure?.localResourceGroup || getEnvOr(['FRAIM_AZURE_LOCAL_RESOURCE_GROUP'], 'local')
295
+ };
296
+
297
+ const CONFIGS: Record<string, ProfilingConfig> = {
298
+ prod: {
299
+ env: 'prod',
300
+ appName: azureConfig.prodAppName,
301
+ resourceGroup: azureConfig.prodResourceGroup
302
+ },
303
+ preprod: {
304
+ env: 'preprod',
305
+ appName: azureConfig.preprodAppName,
306
+ resourceGroup: azureConfig.preprodResourceGroup
307
+ },
308
+ local: {
309
+ env: 'local',
310
+ appName: azureConfig.localAppName,
311
+ resourceGroup: azureConfig.localResourceGroup
312
+ }
313
+ };
314
+
315
+ const args = process.argv.slice(2);
316
+ let profileConfig: ProfilingConfig = CONFIGS.local;
317
+ const includeLogs = args.includes('--logs');
318
+
319
+ if (args.includes('--help') || args.includes('-h')) {
320
+ console.log(`
321
+ šŸ” Azure App Service Profiler
322
+
323
+ Usage:
324
+ npx tsx profile-server.ts [options]
325
+
326
+ Options:
327
+ --prod Profile production environment
328
+ --preprod Profile pre-production environment
329
+ --local Profile local environment (default)
330
+ --logs Include application logs in analysis
331
+ --help, -h Show this help message
332
+
333
+ Examples:
334
+ # Profile production server
335
+ npx tsx profile-server.ts --prod
336
+
337
+ # Profile with logs
338
+ npx tsx profile-server.ts --prod --logs
339
+
340
+ # Profile local environment
341
+ npx tsx profile-server.ts --local
342
+
343
+ Requirements:
344
+ - Azure CLI (az) installed and authenticated
345
+ - Proper permissions to access App Service resources
346
+ - For Kudu API access: Contributor role on the App Service
347
+
348
+ Configuration:
349
+ Reads Azure settings from .fraim/config.json or environment variables:
350
+ - FRAIM_AZURE_PROD_APP_NAME
351
+ - FRAIM_AZURE_PROD_RESOURCE_GROUP
352
+ - FRAIM_AZURE_PREPROD_APP_NAME
353
+ - FRAIM_AZURE_PREPROD_RESOURCE_GROUP
354
+ `);
355
+ return;
356
+ }
357
+
358
+ if (args.includes('--prod')) profileConfig = CONFIGS.prod;
359
+ else if (args.includes('--preprod')) profileConfig = CONFIGS.preprod;
360
+ else if (args.includes('--local')) profileConfig = CONFIGS.local;
361
+
362
+ console.log(`\nšŸš€ Starting Server Profiling`);
363
+ console.log(`šŸ“Š Environment: ${profileConfig.env.toUpperCase()}`);
364
+ console.log(`šŸ·ļø App: ${profileConfig.appName}`);
365
+ console.log(`šŸ“ Resource Group: ${profileConfig.resourceGroup}`);
366
+
367
+ if (profileConfig.env === 'local') {
368
+ await profileLocalEnvironment();
369
+ console.log('\nāœ… Local profiling completed');
370
+ return;
371
+ }
372
+
373
+ // Check prerequisites for Azure profiling
374
+ console.log('\nšŸ” Checking prerequisites...');
375
+
376
+ if (!checkAzureCLI()) {
377
+ console.error('āŒ Azure CLI not found. Please install Azure CLI first.');
378
+ console.error(' Download from: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli');
379
+ process.exit(1);
380
+ }
381
+ console.log('āœ… Azure CLI found');
382
+
383
+ if (!checkAzureAuth()) {
384
+ console.error('āŒ Not authenticated with Azure. Please run: az login');
385
+ process.exit(1);
386
+ }
387
+ console.log('āœ… Azure authentication verified');
388
+
389
+ try {
390
+ // Verify app exists
391
+ console.log(`\nšŸ” Verifying App Service: ${profileConfig.appName}`);
392
+ execSync(`az webapp show --name ${profileConfig.appName} --resource-group ${profileConfig.resourceGroup} --query name -o tsv`, { stdio: 'pipe' });
393
+ console.log('āœ… App Service found');
394
+
395
+ // Run profiling analysis
396
+ await getAppServicePlanMetrics(profileConfig.appName, profileConfig.resourceGroup);
397
+ await getAppServiceMetrics(profileConfig.appName, profileConfig.resourceGroup);
398
+ await getProcessInformation(profileConfig.appName);
399
+ await getSystemInformation(profileConfig.appName);
400
+
401
+ if (includeLogs) {
402
+ await getApplicationLogs(profileConfig.appName, profileConfig.resourceGroup);
403
+ }
404
+
405
+ console.log('\nāœ… Server profiling completed successfully');
406
+ console.log('\nšŸ’” Tips:');
407
+ console.log(' - Use --logs flag to include application logs');
408
+ console.log(' - High CPU usage may indicate performance bottlenecks');
409
+ console.log(' - High memory usage may indicate memory leaks');
410
+ console.log(' - Check process list for unexpected or resource-heavy processes');
411
+
412
+ } catch (error: any) {
413
+ console.error(`\nāŒ Profiling failed: ${error.message}`);
414
+ console.error('\nTroubleshooting:');
415
+ console.error(' - Verify app name and resource group are correct');
416
+ console.error(' - Ensure you have proper permissions (Contributor role)');
417
+ console.error(' - Check if the App Service is running');
418
+ console.error(' - Try: az webapp list --query "[].{name:name, resourceGroup:resourceGroup}"');
419
+ process.exit(1);
420
+ }
421
+ }
422
+
423
+ // Run the main function
424
+ main().catch(console.error);
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env tsx
2
+
3
+ /**
4
+ * Runner script for thank-you email workflow
5
+ * Called by AI agents to generate thank-you emails
6
+ */
7
+
8
+ import { getResolvedIssues, findExecutiveByEmail, getPersonaEmailForExecutive } from './generate-engagement-emails';
9
+ import { writeFileSync, mkdirSync } from 'fs';
10
+ import { join } from 'path';
11
+
12
+ interface CustomerData {
13
+ email: string;
14
+ name: string;
15
+ issues: Array<{
16
+ number: number;
17
+ title: string;
18
+ body: string;
19
+ }>;
20
+ executiveId?: string;
21
+ executiveName?: string;
22
+ personaEmail?: string;
23
+ }
24
+
25
+ async function main() {
26
+ console.log('šŸŽÆ Starting thank-you email generation workflow...\n');
27
+
28
+ // Step 1: Get resolved issues
29
+ console.log('šŸ“‹ Step 1: Retrieving resolved issues...');
30
+ const issues = await getResolvedIssues();
31
+
32
+ console.log(`\nāœ… Found ${issues.length} resolved issues\n`);
33
+
34
+ // Step 2: Extract customer information
35
+ console.log('šŸ“§ Step 2: Extracting customer information...\n');
36
+
37
+ const customerMap = new Map<string, CustomerData>();
38
+
39
+ for (const issue of issues) {
40
+ // Extract email and name from issue body or title
41
+ let customerEmail: string | null = null;
42
+ let customerName: string | null = null;
43
+
44
+ // Try to extract from body first
45
+ const bodyEmailMatch = issue.body?.match(/\*\*Reported by:\*\*\s+(.+?)\s+\((.+?)\)/);
46
+ if (bodyEmailMatch) {
47
+ customerName = bodyEmailMatch[1].trim();
48
+ customerEmail = bodyEmailMatch[2].trim();
49
+ }
50
+
51
+ // Try to extract from title (format: "email: summary")
52
+ if (!customerEmail) {
53
+ const titleEmailMatch = issue.title.match(/^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}):/);
54
+ if (titleEmailMatch) {
55
+ customerEmail = titleEmailMatch[1];
56
+ }
57
+ }
58
+
59
+ if (!customerEmail) {
60
+ console.log(`āš ļø Issue #${issue.number}: Could not extract customer email, skipping`);
61
+ continue;
62
+ }
63
+
64
+ // Normalize email to lowercase for consistent matching
65
+ const normalizedEmail = customerEmail.toLowerCase();
66
+
67
+ // Add or update customer data
68
+ if (!customerMap.has(normalizedEmail)) {
69
+ customerMap.set(normalizedEmail, {
70
+ email: normalizedEmail,
71
+ name: customerName || 'Valued Customer',
72
+ issues: []
73
+ });
74
+ }
75
+
76
+ const customerData = customerMap.get(normalizedEmail)!;
77
+ customerData.issues.push({
78
+ number: issue.number,
79
+ title: issue.title,
80
+ body: issue.body || ''
81
+ });
82
+ }
83
+
84
+ console.log(`šŸ“Š Found ${customerMap.size} unique customers\n`);
85
+
86
+ // Step 3: Lookup executive data for each customer
87
+ console.log('šŸ” Step 3: Looking up executive data...\n');
88
+
89
+ const entries = Array.from(customerMap.entries());
90
+ for (const [email, customerData] of entries) {
91
+ try {
92
+ const executive = await findExecutiveByEmail(email);
93
+
94
+ if (executive) {
95
+ customerData.executiveId = executive.id;
96
+ customerData.executiveName = executive.name;
97
+
98
+ if (executive.id) {
99
+ const personaEmail = await getPersonaEmailForExecutive(executive.id);
100
+ customerData.personaEmail = personaEmail;
101
+ console.log(`āœ… ${email}: Found executive ${executive.name} (${executive.id}), Persona email: ${personaEmail}`);
102
+ } else {
103
+ console.log(`āš ļø ${email}: Found executive ${executive.name} but no ID`);
104
+ }
105
+ } else {
106
+ console.log(`āš ļø ${email}: No executive record found in database`);
107
+ }
108
+ } catch (error) {
109
+ console.error(`āŒ ${email}: Error looking up executive:`, error);
110
+ }
111
+ }
112
+
113
+ console.log('\nšŸ“ Customer Data Summary:\n');
114
+ console.log(JSON.stringify(Array.from(customerMap.values()), null, 2));
115
+
116
+ // Save to temp file for AI agent to process
117
+ const outputPath = join(process.cwd(), 'temp-customer-data.json');
118
+ writeFileSync(outputPath, JSON.stringify(Array.from(customerMap.values()), null, 2));
119
+ console.log(`\nšŸ’¾ Customer data saved to: ${outputPath}`);
120
+ }
121
+
122
+ main().catch(console.error);
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env tsx
2
+
3
+ /**
4
+ * Send Newsletter - Deterministic Script
5
+ *
6
+ * Simple script that users run after approving newsletter JSON.
7
+ * No decisions, just sends the newsletter.
8
+ *
9
+ * Usage:
10
+ * npm run send-newsletter # Send to all executives and potential customers
11
+ * npm run send-newsletter -- --showonly # List recipients without sending
12
+ * npm run send-newsletter -- --no-potential-customers # Send only to active executives
13
+ * npm run send-newsletter -- --only-potential-customers # Send only to potential customers
14
+ * npm run send-newsletter -- --email=user@example.com # Send to specific email
15
+ * npm run send-newsletter -- exec-XXX exec-YYY # Send to specific executive IDs
16
+ */
17
+
18
+ import { sendNewsletterToExecutives } from './newsletter-helpers';
19
+ import { readdirSync, existsSync } from 'fs';
20
+ import { join } from 'path';
21
+
22
+ async function main() {
23
+ console.log('šŸ“§ Weekly Newsletter Sender\n');
24
+
25
+ // Parse command line arguments
26
+ const args = process.argv.slice(2);
27
+ const showOnly = args.includes('--showonly');
28
+ const excludePotentialCustomers = args.includes('--no-potential-customers');
29
+ const onlyPotentialCustomers = args.includes('--only-potential-customers');
30
+ const filterEmails: string[] = [];
31
+ const filterExecIds: string[] = [];
32
+
33
+ // Parse email filters (--email=address)
34
+ args.forEach(arg => {
35
+ if (arg.startsWith('--email=')) {
36
+ filterEmails.push(arg.substring(8));
37
+ } else if (arg.startsWith('exec-')) {
38
+ filterExecIds.push(arg);
39
+ }
40
+ });
41
+
42
+ // Find the most recent newsletter
43
+ const newslettersDir = join(process.cwd(), 'docs', 'customer-development', 'newsletters');
44
+
45
+ if (!existsSync(newslettersDir)) {
46
+ console.error('āŒ Error: No newsletters directory found');
47
+ console.error(' Expected: docs/customer-development/newsletters/');
48
+ console.error(' Generate a newsletter first using the AI agent workflow');
49
+ process.exit(1);
50
+ }
51
+
52
+ const files = readdirSync(newslettersDir)
53
+ .filter(f => f.startsWith('newsletter-') && f.endsWith('.json'))
54
+ .sort()
55
+ .reverse(); // Most recent first
56
+
57
+ if (files.length === 0) {
58
+ console.error('āŒ Error: No newsletter files found');
59
+ console.error(' Generate a newsletter first using the AI agent workflow');
60
+ process.exit(1);
61
+ }
62
+
63
+ const latestNewsletter = files[0];
64
+ const newsletterPath = join(newslettersDir, latestNewsletter);
65
+
66
+ console.log(`šŸ“„ Found newsletter: ${latestNewsletter}`);
67
+
68
+ if (showOnly) {
69
+ console.log(`šŸ“‹ Listing recipients (--showonly mode - no emails will be sent)...\n`);
70
+ } else if (filterEmails.length > 0 || filterExecIds.length > 0) {
71
+ console.log(`šŸ“§ Sending to filtered recipients...\n`);
72
+ console.log(`āš ļø This will send real emails. Make sure the newsletter is approved!`);
73
+ } else {
74
+ if (onlyPotentialCustomers) {
75
+ console.log(`šŸ“§ Sending to potential customers only...\n`);
76
+ } else {
77
+ console.log(`šŸ“§ Sending to all active executives${excludePotentialCustomers ? '' : ' and potential customers'}...\n`);
78
+ }
79
+ console.log(`āš ļø This will send real emails. Make sure the newsletter is approved!`);
80
+ }
81
+
82
+ console.log(` Preview: ${newsletterPath.replace('.json', '.html')}\n`);
83
+
84
+ // Determine what to include based on flags
85
+ const includePotentialCustomers = onlyPotentialCustomers || !excludePotentialCustomers;
86
+ const includeExecutives = !onlyPotentialCustomers;
87
+
88
+ // Send newsletter (or show only)
89
+ await sendNewsletterToExecutives(
90
+ newsletterPath,
91
+ filterEmails.length > 0 ? filterEmails : undefined,
92
+ filterExecIds.length > 0 ? filterExecIds : undefined,
93
+ includePotentialCustomers,
94
+ showOnly,
95
+ includeExecutives
96
+ );
97
+ }
98
+
99
+ main().catch(error => {
100
+ console.error('āŒ Error:', error.message);
101
+ process.exit(1);
102
+ });