@memberjunction/cli 6.3.0-edge.2 → 6.3.0-edge.3

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 (61) hide show
  1. package/README.md +6 -1
  2. package/dist/commands/agent/init.d.ts +3 -0
  3. package/dist/commands/agent/init.d.ts.map +1 -1
  4. package/dist/commands/agent/init.js +102 -46
  5. package/dist/commands/agent/init.js.map +1 -1
  6. package/dist/commands/ai/actions/list.d.ts.map +1 -1
  7. package/dist/commands/ai/actions/list.js +18 -14
  8. package/dist/commands/ai/actions/list.js.map +1 -1
  9. package/dist/commands/ai/actions/run.d.ts.map +1 -1
  10. package/dist/commands/ai/actions/run.js +15 -8
  11. package/dist/commands/ai/actions/run.js.map +1 -1
  12. package/dist/commands/ai/agents/list.d.ts.map +1 -1
  13. package/dist/commands/ai/agents/list.js +18 -14
  14. package/dist/commands/ai/agents/list.js.map +1 -1
  15. package/dist/commands/ai/agents/run.d.ts.map +1 -1
  16. package/dist/commands/ai/agents/run.js +19 -8
  17. package/dist/commands/ai/agents/run.js.map +1 -1
  18. package/dist/commands/ai/audit/agent-run.d.ts.map +1 -1
  19. package/dist/commands/ai/audit/agent-run.js +62 -56
  20. package/dist/commands/ai/audit/agent-run.js.map +1 -1
  21. package/dist/commands/ai/prompts/list.d.ts.map +1 -1
  22. package/dist/commands/ai/prompts/list.js +6 -3
  23. package/dist/commands/ai/prompts/list.js.map +1 -1
  24. package/dist/commands/ai/prompts/run.d.ts.map +1 -1
  25. package/dist/commands/ai/prompts/run.js +17 -10
  26. package/dist/commands/ai/prompts/run.js.map +1 -1
  27. package/dist/commands/app/install.d.ts +4 -0
  28. package/dist/commands/app/install.d.ts.map +1 -1
  29. package/dist/commands/app/install.js +36 -1
  30. package/dist/commands/app/install.js.map +1 -1
  31. package/dist/commands/app/upgrade.d.ts +1 -0
  32. package/dist/commands/app/upgrade.d.ts.map +1 -1
  33. package/dist/commands/app/upgrade.js +9 -0
  34. package/dist/commands/app/upgrade.js.map +1 -1
  35. package/dist/commands/migrate/index.js +1 -1
  36. package/dist/commands/migrate/index.js.map +1 -1
  37. package/dist/config.d.ts +2 -4
  38. package/dist/config.d.ts.map +1 -1
  39. package/dist/config.js +7 -5
  40. package/dist/config.js.map +1 -1
  41. package/dist/init-templates/citizen-builder/.agents/skills/package-agent/SKILL.md +12 -2
  42. package/dist/init-templates/citizen-builder/.agents/skills/test-agent/SKILL.md +1 -1
  43. package/dist/init-templates/citizen-builder/.claude/skills/package-agent/SKILL.md +12 -2
  44. package/dist/init-templates/citizen-builder/.claude/skills/test-agent/SKILL.md +1 -1
  45. package/dist/init-templates/citizen-builder/.env.example +13 -2
  46. package/dist/init-templates/citizen-builder/AGENTS.md +5 -2
  47. package/dist/init-templates/citizen-builder/CAPABILITIES.md +9 -0
  48. package/dist/init-templates/citizen-builder/README.md +29 -15
  49. package/dist/init-templates/citizen-builder/docker-compose.yml +11 -0
  50. package/dist/init-templates/citizen-builder/docs/PROMOTION_GUIDE.md +5 -2
  51. package/dist/init-templates/citizen-builder/scripts/docker-entrypoint.sh +288 -32
  52. package/dist/init-templates/citizen-builder/scripts/generate-capabilities.sh +148 -41
  53. package/dist/tsconfig.tsbuildinfo +1 -1
  54. package/dist/utils/dependencies-from-head.d.ts +4 -0
  55. package/dist/utils/dependencies-from-head.d.ts.map +1 -0
  56. package/dist/utils/dependencies-from-head.js +5 -0
  57. package/dist/utils/dependencies-from-head.js.map +1 -0
  58. package/dist/utils/open-app-context.js +1 -1
  59. package/dist/utils/open-app-context.js.map +1 -1
  60. package/oclif.manifest.json +62 -6
  61. package/package.json +33 -33
@@ -33,12 +33,102 @@ echo "SQL Server is reachable!"
33
33
 
34
34
  cd /workspace
35
35
 
36
+ # Ensure /workspace/.npmrc has shamefully-hoist=true so Vite in apps/MJExplorer
37
+ # resolves all transitive @memberjunction/*, luxon, rrule, etc. dependencies of
38
+ # installed OpenApps.
39
+ ensure_npmrc_shamefully_hoist() {
40
+ if [ ! -f /workspace/.npmrc ]; then
41
+ printf 'shamefully-hoist=true\n' > /workspace/.npmrc
42
+ elif ! grep -Eq '^[[:space:]]*shamefully-hoist[[:space:]]*=' /workspace/.npmrc; then
43
+ printf '\nshamefully-hoist=true\n' >> /workspace/.npmrc
44
+ else
45
+ node -e "
46
+ const fs = require('fs');
47
+ const p = '/workspace/.npmrc';
48
+ const content = fs.readFileSync(p, 'utf8');
49
+ const updated = content.replace(/^[ \t]*shamefully-hoist[ \t]*=.*$/gm, 'shamefully-hoist=true');
50
+ if (updated !== content) {
51
+ fs.writeFileSync(p, updated);
52
+ }
53
+ "
54
+ fi
55
+ }
56
+
57
+ # Compute a hash of the provisioning-relevant environment configuration so a
58
+ # failed provisioning run can enter a diagnostic hold instead of tight-looping
59
+ # and exhausting GitHub's 60/hr anonymous API rate limit.
60
+ compute_provisioning_env_hash() {
61
+ node -e "
62
+ const crypto = require('crypto');
63
+ const payload = [
64
+ process.env.MJ_VERSION || '',
65
+ process.env.OPEN_APP_INSTALL_URL || '',
66
+ process.env.OPEN_APP_VERSION || '',
67
+ process.env.OPEN_APP_DEPS_FROM_HEAD || '',
68
+ process.env.GITHUB_TOKEN || ''
69
+ ].join('|');
70
+ process.stdout.write(crypto.createHash('sha256').update(payload).digest('hex'));
71
+ "
72
+ }
73
+
74
+ print_provisioning_failure_banner() {
75
+ local step_label="$1"
76
+ local log_file="$2"
77
+ echo "" >&2
78
+ echo "========================================================================" >&2
79
+ echo " ERROR: Citizen Builder provisioning failed during: $step_label" >&2
80
+ echo "========================================================================" >&2
81
+ if [ -f "$log_file" ]; then
82
+ echo " Preserved root-cause output ($log_file):" >&2
83
+ echo "------------------------------------------------------------------------" >&2
84
+ tail -n 60 "$log_file" >&2
85
+ echo "------------------------------------------------------------------------" >&2
86
+ fi
87
+ echo "" >&2
88
+ echo " Remediation steps:" >&2
89
+ echo " 1. If you see a GitHub 403 / API rate limit exceeded error, add a" >&2
90
+ echo " read-only GITHUB_TOKEN to your .env file (even a token with zero" >&2
91
+ echo " private repo scopes raises the limit from 60/hr to 5,000/hr)." >&2
92
+ echo " 2. Verify MJ_VERSION, OPEN_APP_INSTALL_URL, and OPEN_APP_VERSION" >&2
93
+ echo " (if set) in your .env file." >&2
94
+ echo " 3. Apply your updated .env and retry cleanly:" >&2
95
+ echo " docker compose up -d --force-recreate mj" >&2
96
+ echo " (Note: 'docker compose up -d' reloads .env changes; if .env did not" >&2
97
+ echo " change, clear $STATE_DIR/failed-env-hash before 'docker compose restart mj'.)" >&2
98
+ echo "" >&2
99
+ echo " Container is now in diagnostic hold so Docker restart loops do not" >&2
100
+ echo " re-hammer GitHub API rate limits. Update .env and recreate/restart mj." >&2
101
+ echo "========================================================================" >&2
102
+ }
103
+
104
+ hold_until_reconfigured() {
105
+ trap 'exit 0' TERM INT
106
+ while true; do
107
+ sleep 5 &
108
+ wait $! || true
109
+ done
110
+ }
111
+
112
+ run_provisioning_cmd() {
113
+ local step_label="$1"
114
+ shift
115
+ local log_file="$STATE_DIR/last-provisioning-error.log"
116
+ set +e
117
+ "$@" 2>&1 | tee "$log_file"
118
+ local rc=${PIPESTATUS[0]}
119
+ set -e
120
+ if [ "$rc" -ne 0 ]; then
121
+ printf '%s' "$CURRENT_ENV_HASH" > "$STATE_DIR/failed-env-hash"
122
+ print_provisioning_failure_banner "$step_label" "$log_file"
123
+ hold_until_reconfigured
124
+ fi
125
+ }
126
+
36
127
  # 2. Provisioning. State lives on the workspace volume so it survives restarts, and each step
37
128
  # that must not run twice records its own completion: `mj app install` of an app that is
38
129
  # already installed is an error, so a failure in a LATER step has to be retried on restart
39
- # without re-running an earlier one. Failures are not masked. With `set -e` a failed step
40
- # exits the container loudly (see `docker compose logs mj`), `restart: unless-stopped`
41
- # retries it, and nothing reports success until every step has actually succeeded.
130
+ # without re-running an earlier one. Failures are preserved and held on unchanged env so
131
+ # restart: unless-stopped does not burn GitHub's anonymous 60/hr API rate limit.
42
132
  STATE_DIR="/workspace/.citizen-builder"
43
133
 
44
134
  # A workspace provisioned by an earlier version of this script kept no state. Its package.json
@@ -51,6 +141,18 @@ fi
51
141
  mkdir -p "$STATE_DIR"
52
142
 
53
143
  if [ ! -f "$STATE_DIR/provisioned" ]; then
144
+ CURRENT_ENV_HASH="$(compute_provisioning_env_hash)"
145
+ if [ -f "$STATE_DIR/failed-env-hash" ]; then
146
+ FAILED_ENV_HASH="$(cat "$STATE_DIR/failed-env-hash" 2>/dev/null || true)"
147
+ if [ "$FAILED_ENV_HASH" = "$CURRENT_ENV_HASH" ]; then
148
+ print_provisioning_failure_banner "previous provisioning attempt (unchanged environment)" "$STATE_DIR/last-provisioning-error.log"
149
+ hold_until_reconfigured
150
+ else
151
+ echo "Provisioning environment configuration changed; clearing previous failure hold and retrying..."
152
+ rm -f "$STATE_DIR/failed-env-hash" "$STATE_DIR/last-provisioning-error.log"
153
+ fi
154
+ fi
155
+
54
156
  echo ""
55
157
  echo "========================================================================"
56
158
  echo " First-Time Setup: Installing MemberJunction via 'mj install'..."
@@ -101,19 +203,43 @@ if [ ! -f "$STATE_DIR/provisioned" ]; then
101
203
  fi
102
204
 
103
205
  # Execute headless install. Safe to retry: the installer checkpoints completed phases.
104
- mj install --yes --fast --config /tmp/install.config.json --dir /workspace "${INSTALL_TAG_ARGS[@]}"
206
+ run_provisioning_cmd "mj install" mj install --yes --fast --config /tmp/install.config.json --dir /workspace "${INSTALL_TAG_ARGS[@]}"
105
207
  rm -f /tmp/install.config.json
208
+ ensure_npmrc_shamefully_hoist
106
209
  touch "$STATE_DIR/core-installed"
107
210
  pnpm add -w @angular/compiler@21.2.22 2>/dev/null || true
108
211
  fi
109
212
 
213
+ # Ensure shamefully-hoist=true is present before `mj app install` installs OpenApp dependencies
214
+ ensure_npmrc_shamefully_hoist
215
+
110
216
  # Install Open App business context (More Cheese default or custom enterprise app)
111
217
  # Note: GITHUB_TOKEN is read directly from the environment by OpenAppEngine's GitHubClient
112
218
  if [ ! -f "$STATE_DIR/app-installed" ]; then
113
219
  APP_URL="${OPEN_APP_INSTALL_URL:-https://github.com/MemberJunction/more-cheese}"
220
+ APP_INSTALL_ARGS=(--non-interactive)
221
+ if [ -n "${OPEN_APP_VERSION:-}" ]; then
222
+ APP_INSTALL_ARGS+=(--version "$OPEN_APP_VERSION")
223
+ fi
224
+ if [ -n "${OPEN_APP_DEPS_FROM_HEAD:-}" ]; then
225
+ APP_INSTALL_ARGS+=(--dependencies-from-head "$OPEN_APP_DEPS_FROM_HEAD")
226
+ fi
114
227
  echo "Installing business context Open App: $APP_URL..."
115
- mj app install "$APP_URL"
228
+ run_provisioning_cmd "mj app install ($APP_URL)" mj app install "$APP_URL" "${APP_INSTALL_ARGS[@]}"
116
229
  touch "$STATE_DIR/app-installed"
230
+
231
+ # Wire Open App client bootstrap into MJExplorer's class manifest (best-effort;
232
+ # MJExplorer prestart also runs this). Never run full `mj codegen` in Citizen Builder.
233
+ for explorerDir in /workspace/apps/MJExplorer /workspace/packages/MJExplorer; do
234
+ if [ -d "$explorerDir" ]; then
235
+ mj codegen manifest \
236
+ --appDir "$explorerDir" \
237
+ --output "$explorerDir/src/app/generated/class-registrations-manifest.ts" \
238
+ --exclude-packages @memberjunction \
239
+ --open-app-client-bootstrap || true
240
+ break
241
+ fi
242
+ done
117
243
  fi
118
244
 
119
245
  # Generate capabilities catalog. Useful to the coding agent but not needed for a running
@@ -129,6 +255,7 @@ if [ ! -f "$STATE_DIR/provisioned" ]; then
129
255
  mj sync push --dir /work/metadata --ci
130
256
  fi
131
257
 
258
+ rm -f "$STATE_DIR/failed-env-hash" "$STATE_DIR/last-provisioning-error.log"
132
259
  touch "$STATE_DIR/provisioned"
133
260
  echo "MemberJunction installation and provisioning complete!"
134
261
  else
@@ -137,7 +264,105 @@ else
137
264
  mj migrate
138
265
  fi
139
266
 
140
- # Configure MJExplorer host binding and compiler alignment
267
+ # Ensure shamefully-hoist=true is present on every boot
268
+ ensure_npmrc_shamefully_hoist
269
+
270
+ # Provision out-of-the-box read-only SQL login for Run Ad-hoc Query in Explorer Chat.
271
+ # Runs idempotently on every boot so DB_READ_ONLY_USERNAME / DB_READ_ONLY_PASSWORD are
272
+ # always valid and strictly read-only across all schemas (including OpenApp schemas).
273
+ RO_USER="${DB_READ_ONLY_USERNAME:-mj_readonly}"
274
+ RO_PASS_FILE="$STATE_DIR/readonly-db-password"
275
+ if [ -n "${DB_READ_ONLY_PASSWORD:-}" ]; then
276
+ RO_PASS="$DB_READ_ONLY_PASSWORD"
277
+ elif [ -s "$RO_PASS_FILE" ]; then
278
+ RO_PASS="$(cat "$RO_PASS_FILE")"
279
+ else
280
+ RO_PASS="$(node -e "process.stdout.write(require('crypto').randomBytes(24).toString('base64url') + 'A1!')")"
281
+ node -e "
282
+ const fs = require('fs');
283
+ fs.writeFileSync(process.argv[1], process.argv[2], { mode: 0o600 });
284
+ fs.chmodSync(process.argv[1], 0o600);
285
+ " "$RO_PASS_FILE" "$RO_PASS"
286
+ fi
287
+
288
+ echo "Ensuring read-only SQL login '$RO_USER' exists in '$DB_DATABASE'..."
289
+ RO_USER="$RO_USER" RO_PASS="$RO_PASS" node -e "
290
+ const resolveMssql = () => {
291
+ for (const candidate of [
292
+ '/workspace/node_modules/mssql',
293
+ '/workspace/apps/MJAPI/node_modules/mssql',
294
+ '/workspace/packages/MJAPI/node_modules/mssql',
295
+ ]) {
296
+ try { return require(candidate); } catch {}
297
+ }
298
+ throw new Error('Could not locate mssql module in /workspace');
299
+ };
300
+ const sql = resolveMssql();
301
+ (async () => {
302
+ const roUser = process.env.RO_USER;
303
+ const roPass = process.env.RO_PASS;
304
+ const dbName = process.env.DB_DATABASE || 'MemberJunction';
305
+ const pool = await sql.connect({
306
+ server: process.env.DB_HOST || 'sqlserver',
307
+ port: Number(process.env.DB_PORT || 1433),
308
+ database: dbName,
309
+ user: 'sa',
310
+ password: process.env.DB_PASSWORD || 'TestPassword123!',
311
+ options: {
312
+ encrypt: true,
313
+ trustServerCertificate: true,
314
+ },
315
+ });
316
+ try {
317
+ const req = pool.request();
318
+ req.input('roUser', sql.NVarChar(128), roUser);
319
+ req.input('roPass', sql.NVarChar(256), roPass);
320
+ req.input('dbName', sql.NVarChar(128), dbName);
321
+ await req.query(\`
322
+ DECLARE @quotedLogin NVARCHAR(260) = QUOTENAME(@roUser);
323
+ DECLARE @escapedPass NVARCHAR(512) = REPLACE(@roPass, '''', '''''');
324
+ DECLARE @sql NVARCHAR(MAX);
325
+
326
+ IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = @roUser)
327
+ BEGIN
328
+ SET @sql = N'CREATE LOGIN ' + @quotedLogin + N' WITH PASSWORD = ''' + @escapedPass + N''', CHECK_POLICY = OFF, DEFAULT_DATABASE = ' + QUOTENAME(@dbName) + N';';
329
+ EXEC sp_executesql @sql;
330
+ END
331
+ ELSE
332
+ BEGIN
333
+ SET @sql = N'ALTER LOGIN ' + @quotedLogin + N' WITH PASSWORD = ''' + @escapedPass + N''', CHECK_POLICY = OFF;';
334
+ EXEC sp_executesql @sql;
335
+ END
336
+
337
+ IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = @roUser)
338
+ BEGIN
339
+ SET @sql = N'CREATE USER ' + @quotedLogin + N' FOR LOGIN ' + @quotedLogin + N';';
340
+ EXEC sp_executesql @sql;
341
+ END
342
+ ELSE
343
+ BEGIN
344
+ SET @sql = N'ALTER USER ' + @quotedLogin + N' WITH LOGIN = ' + @quotedLogin + N';';
345
+ EXEC sp_executesql @sql;
346
+ END
347
+
348
+ SET @sql = N'ALTER ROLE [db_datareader] ADD MEMBER ' + @quotedLogin + N';';
349
+ EXEC sp_executesql @sql;
350
+
351
+ SET @sql = N'ALTER ROLE [db_denydatawriter] ADD MEMBER ' + @quotedLogin + N';';
352
+ EXEC sp_executesql @sql;
353
+ \`);
354
+ } finally {
355
+ await pool.close();
356
+ }
357
+ })().catch((err) => {
358
+ console.error('Failed to provision read-only SQL login:', err);
359
+ process.exit(1);
360
+ });
361
+ "
362
+ export DB_READ_ONLY_USERNAME="$RO_USER"
363
+ export DB_READ_ONLY_PASSWORD="$RO_PASS"
364
+
365
+ # Configure MJExplorer host binding, compiler alignment, and Cache-Control: no-cache
141
366
  if [ -f "apps/MJExplorer/package.json" ]; then
142
367
  node -e "
143
368
  const fs = require('fs');
@@ -159,6 +384,31 @@ if [ -f "apps/MJExplorer/package.json" ]; then
159
384
  "
160
385
  fi
161
386
 
387
+ node -e "
388
+ const fs = require('fs');
389
+ for (const ngJson of ['apps/MJExplorer/angular.json', 'packages/MJExplorer/angular.json']) {
390
+ if (!fs.existsSync(ngJson)) continue;
391
+ const cfg = JSON.parse(fs.readFileSync(ngJson, 'utf8'));
392
+ let changed = false;
393
+ if (cfg.projects && typeof cfg.projects === 'object') {
394
+ for (const proj of Object.values(cfg.projects)) {
395
+ const serve = proj && proj.architect && proj.architect.serve;
396
+ if (serve) {
397
+ serve.options = serve.options || {};
398
+ serve.options.headers = serve.options.headers || {};
399
+ if (serve.options.headers['Cache-Control'] !== 'no-cache') {
400
+ serve.options.headers['Cache-Control'] = 'no-cache';
401
+ changed = true;
402
+ }
403
+ }
404
+ }
405
+ }
406
+ if (changed) {
407
+ fs.writeFileSync(ngJson, JSON.stringify(cfg, null, 2) + '\n');
408
+ }
409
+ }
410
+ "
411
+
162
412
  # Ensure turbo.json passes through AI vendor API keys, DB settings, and MJ_DEV_AUTH_ENABLED to child processes
163
413
  if [ -f "turbo.json" ]; then
164
414
  node -e "
@@ -183,7 +433,7 @@ if [ -f "turbo.json" ]; then
183
433
  "
184
434
  fi
185
435
 
186
- # Sync container environment variables (API keys, encryption key, DB_USER, local dev auth) into workspace .env files
436
+ # Sync container environment variables (API keys, encryption key, DB_USER, read-only DB creds, local dev auth) into workspace .env files
187
437
  [ -z "${MJ_ARTIFACT_COLLAB_HMAC_SECRET:-}" ] && unset MJ_ARTIFACT_COLLAB_HMAC_SECRET
188
438
  [ -z "${MJ_COLLABORATION_TICKET_SECRET:-}" ] && unset MJ_COLLABORATION_TICKET_SECRET
189
439
  [ -z "${MJ_FROZEN_BLOCK_HMAC_SECRET:-}" ] && unset MJ_FROZEN_BLOCK_HMAC_SECRET
@@ -201,6 +451,7 @@ node -e "
201
451
  const crypto = require('crypto');
202
452
  const keysToSync = [
203
453
  'DB_HOST', 'DB_PORT', 'DB_DATABASE', 'DB_USERNAME', 'DB_PASSWORD',
454
+ 'DB_READ_ONLY_USERNAME', 'DB_READ_ONLY_PASSWORD',
204
455
  'MJ_BASE_ENCRYPTION_KEY',
205
456
  'MJ_ARTIFACT_COLLAB_HMAC_SECRET', 'MJ_COLLABORATION_TICKET_SECRET',
206
457
  'MJ_FROZEN_BLOCK_HMAC_SECRET', 'MJ_FROZEN_SNAPSHOT_SECRET',
@@ -309,36 +560,41 @@ if [ -f "mj.config.cjs" ]; then
309
560
  "
310
561
  fi
311
562
 
312
- # 3. Start MJAPI and MJExplorer services via PM2
313
- echo "Starting MJAPI and MJExplorer services..."
314
- pm2 delete all 2>/dev/null || true
315
-
316
- # Start API service directly in apps/MJAPI (avoids turbo wrapper masking OOM exits in pm2)
317
- if [ -d "apps/MJAPI" ]; then
318
- pm2 start npm --name mjapi --cwd /workspace/apps/MJAPI -- start
319
- elif [ -d "packages/MJAPI" ]; then
320
- pm2 start npm --name mjapi --cwd /workspace/packages/MJAPI -- start
321
- elif [ -f "package.json" ] && grep -q "start:api" package.json; then
322
- pm2 start "npm run start:api" --name mjapi
323
- else
324
- pm2 start "npm start" --name mjapi
325
- fi
563
+ # 3. Start MJAPI and MJExplorer services via pm2-runtime (PID 1 supervision)
564
+ echo "Starting MJAPI and MJExplorer services via pm2-runtime..."
565
+ node -e "
566
+ const fs = require('fs');
567
+ const apps = [];
326
568
 
327
- # Start Explorer service directly in apps/MJExplorer
328
- if [ -d "apps/MJExplorer" ]; then
329
- pm2 start npm --name mjexplorer --cwd /workspace/apps/MJExplorer -- start
330
- elif [ -d "packages/MJExplorer" ]; then
331
- pm2 start npm --name mjexplorer --cwd /workspace/packages/MJExplorer -- start
332
- elif [ -f "package.json" ] && grep -q "start:explorer" package.json; then
333
- pm2 start "npm run start:explorer" --name mjexplorer
334
- fi
569
+ if (fs.existsSync('/workspace/apps/MJAPI')) {
570
+ apps.push({ name: 'mjapi', cwd: '/workspace/apps/MJAPI', script: 'npm', args: 'start', autorestart: true, max_restarts: 10, min_uptime: '5s' });
571
+ } else if (fs.existsSync('/workspace/packages/MJAPI')) {
572
+ apps.push({ name: 'mjapi', cwd: '/workspace/packages/MJAPI', script: 'npm', args: 'start', autorestart: true, max_restarts: 10, min_uptime: '5s' });
573
+ } else if (fs.existsSync('/workspace/package.json')) {
574
+ const rootPkg = JSON.parse(fs.readFileSync('/workspace/package.json', 'utf8'));
575
+ const hasStartApi = !!(rootPkg.scripts && rootPkg.scripts['start:api']);
576
+ apps.push({ name: 'mjapi', cwd: '/workspace', script: 'npm', args: hasStartApi ? 'run start:api' : 'start', autorestart: true, max_restarts: 10, min_uptime: '5s' });
577
+ }
578
+
579
+ if (fs.existsSync('/workspace/apps/MJExplorer')) {
580
+ apps.push({ name: 'mjexplorer', cwd: '/workspace/apps/MJExplorer', script: 'npm', args: 'start', autorestart: true, max_restarts: 10, min_uptime: '5s' });
581
+ } else if (fs.existsSync('/workspace/packages/MJExplorer')) {
582
+ apps.push({ name: 'mjexplorer', cwd: '/workspace/packages/MJExplorer', script: 'npm', args: 'start', autorestart: true, max_restarts: 10, min_uptime: '5s' });
583
+ } else if (fs.existsSync('/workspace/package.json')) {
584
+ const rootPkg = JSON.parse(fs.readFileSync('/workspace/package.json', 'utf8'));
585
+ if (rootPkg.scripts && rootPkg.scripts['start:explorer']) {
586
+ apps.push({ name: 'mjexplorer', cwd: '/workspace', script: 'npm', args: 'run start:explorer', autorestart: true, max_restarts: 10, min_uptime: '5s' });
587
+ }
588
+ }
589
+
590
+ fs.writeFileSync('/tmp/ecosystem.config.cjs', 'module.exports = ' + JSON.stringify({ apps }, null, 2) + ';\n');
591
+ "
335
592
 
336
593
  echo "========================================================================"
337
- echo " 🎉 MemberJunction Stack is Running!"
594
+ echo " MemberJunction Stack Starting (PID 1 pm2-runtime)"
338
595
  echo " MJAPI: http://localhost:${API_PORT:-4000} (GraphQL & API)"
339
596
  echo " MJExplorer: http://localhost:${EXPLORER_PORT:-4202} (Web Interface — Zero-Config Local Dev Auth active)"
340
597
  echo " Database: localhost:$DB_PORT (DB: $DB_DATABASE)"
341
598
  echo "========================================================================"
342
599
 
343
- # Keep container running and stream logs
344
- exec pm2 logs
600
+ exec pm2-runtime start /tmp/ecosystem.config.cjs
@@ -2,12 +2,17 @@
2
2
  # ==============================================================================
3
3
  # Citizen Agent Builder - Capabilities Catalog Generator
4
4
  # Queries the local MemberJunction database and outputs an updated CAPABILITIES.md
5
- # so the local coding agent has an exact catalog of entities, actions, and agents.
5
+ # so the local coding agent has an exact catalog of entities, views, fields,
6
+ # actions, and sub-agents. Works both inside the `mj` container and on the host.
6
7
  # ==============================================================================
7
8
  set -e
8
9
 
9
10
  DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
10
11
  OUTPUT_FILE="$DIR/CAPABILITIES.md"
12
+ STDOUT_MODE=false
13
+ if [ "${1:-}" = "--stdout" ]; then
14
+ STDOUT_MODE=true
15
+ fi
11
16
 
12
17
  if [ -f "$DIR/.env" ]; then
13
18
  set -a
@@ -15,47 +20,149 @@ if [ -f "$DIR/.env" ]; then
15
20
  set +a
16
21
  fi
17
22
 
23
+ DB_HOST="${DB_HOST:-sqlserver}"
24
+ DB_PORT="${DB_PORT:-1433}"
25
+ DB_DATABASE="${DB_DATABASE:-MemberJunction}"
26
+ DB_USERNAME="${DB_USERNAME:-sa}"
18
27
  DB_PASSWORD="${DB_PASSWORD:-TestPassword123!}"
19
28
 
20
- echo "Generating CAPABILITIES.md from database catalog..."
29
+ generate_inside_container() {
30
+ local target_file="/work/CAPABILITIES.md"
31
+ if [ ! -d "/work" ]; then
32
+ target_file="$OUTPUT_FILE"
33
+ fi
34
+
35
+ local content
36
+ content="$(node -e "
37
+ const resolveMssql = () => {
38
+ for (const candidate of [
39
+ '/workspace/node_modules/mssql',
40
+ '/workspace/apps/MJAPI/node_modules/mssql',
41
+ '/workspace/packages/MJAPI/node_modules/mssql',
42
+ ]) {
43
+ try { return require(candidate); } catch {}
44
+ }
45
+ throw new Error('Could not locate mssql module in /workspace');
46
+ };
47
+ const sql = resolveMssql();
48
+ const clean = (val, fallback = 'No description') => {
49
+ const text = (val === null || val === undefined || String(val).trim() === '') ? fallback : String(val);
50
+ return text.replace(/[\r\n]+/g, ' ').replace(/\|/g, '\\\\|').trim();
51
+ };
52
+ (async () => {
53
+ const pool = await sql.connect({
54
+ server: process.env.DB_HOST || 'sqlserver',
55
+ port: Number(process.env.DB_PORT || 1433),
56
+ database: process.env.DB_DATABASE || 'MemberJunction',
57
+ user: process.env.DB_USERNAME || 'sa',
58
+ password: process.env.DB_PASSWORD || 'TestPassword123!',
59
+ options: {
60
+ encrypt: true,
61
+ trustServerCertificate: true,
62
+ },
63
+ });
64
+ try {
65
+ const [entitiesRes, fieldsRes, actionsRes, agentsRes] = await Promise.all([
66
+ pool.request().query(\`
67
+ SELECT ID, Name, SchemaName, BaseView, Description
68
+ FROM [__mj].[vwEntities]
69
+ WHERE VirtualEntity = 0
70
+ ORDER BY Name ASC
71
+ \`),
72
+ pool.request().query(\`
73
+ SELECT EntityID, Name, Type
74
+ FROM [__mj].[vwEntityFields]
75
+ WHERE Name NOT LIKE '__mj[_]%'
76
+ ORDER BY EntityID ASC, Sequence ASC, Name ASC
77
+ \`),
78
+ pool.request().query(\`
79
+ SELECT Name, Description
80
+ FROM [__mj].[vwActions]
81
+ ORDER BY Name ASC
82
+ \`),
83
+ pool.request().query(\`
84
+ SELECT Name, Type, Description
85
+ FROM [__mj].[vwAIAgents]
86
+ ORDER BY Name ASC
87
+ \`),
88
+ ]);
21
89
 
22
- SQL_QUERY="
23
- SET NOCOUNT ON;
24
- PRINT '# System Capabilities Catalog';
25
- PRINT '';
26
- PRINT 'This catalog reflects the real entities, actions, and agents available in this MemberJunction instance.';
27
- PRINT 'Use these exact names when authoring agent steps, action bindings, and prompt templates.';
28
- PRINT '';
29
- PRINT '## 1. Available Entities';
30
- PRINT '| Entity Name | Description |';
31
- PRINT '|---|---|';
32
- SELECT '| \`' + Name + '\` | ' + REPLACE(REPLACE(COALESCE(Description, 'No description'), CHAR(13), ' '), CHAR(10), ' ') + ' |'
33
- FROM [__mj].[vwEntities]
34
- WHERE VirtualEntity = 0
35
- ORDER BY Name ASC;
90
+ const fieldsByEntity = new Map();
91
+ for (const f of fieldsRes.recordset) {
92
+ const list = fieldsByEntity.get(f.EntityID) || [];
93
+ list.push(f.Name + ' (' + f.Type + ')');
94
+ fieldsByEntity.set(f.EntityID, list);
95
+ }
36
96
 
37
- PRINT '';
38
- PRINT '## 2. Available Actions (Tools)';
39
- PRINT '| Action Name | Description |';
40
- PRINT '|---|---|';
41
- SELECT '| \`' + Name + '\` | ' + REPLACE(REPLACE(COALESCE(Description, 'No description'), CHAR(13), ' '), CHAR(10), ' ') + ' |'
42
- FROM [__mj].[vwActions]
43
- ORDER BY Name ASC;
97
+ const lines = [];
98
+ lines.push('# System Capabilities Catalog');
99
+ lines.push('');
100
+ lines.push('This catalog reflects the real entities, views, fields, actions, and agents available in this MemberJunction instance.');
101
+ lines.push('Use these exact names when authoring agent steps, action bindings, `Run Ad-hoc Query` SQL, and prompt templates.');
102
+ lines.push('');
103
+ lines.push('## 1. Available Entities');
104
+ lines.push('| Entity Name | View | Description | Fields |');
105
+ lines.push('|---|---|---|---|');
106
+ for (const e of entitiesRes.recordset) {
107
+ const viewRef = '[' + e.SchemaName + '].[' + e.BaseView + ']';
108
+ const fields = fieldsByEntity.get(e.ID) || [];
109
+ const fieldsStr = clean(fields.join(', '), 'None');
110
+ lines.push('| \`' + clean(e.Name, '') + '\` | \`' + viewRef + '\` | ' + clean(e.Description) + ' | ' + fieldsStr + ' |');
111
+ }
112
+ lines.push('');
113
+ lines.push('## 2. Available Actions (Tools)');
114
+ lines.push('| Action Name | Description |');
115
+ lines.push('|---|---|');
116
+ for (const a of actionsRes.recordset) {
117
+ lines.push('| \`' + clean(a.Name, '') + '\` | ' + clean(a.Description) + ' |');
118
+ }
119
+ lines.push('');
120
+ lines.push('## 3. Available Sub-Agents');
121
+ lines.push('| Agent Name | Type | Description |');
122
+ lines.push('|---|---|---|');
123
+ for (const ag of agentsRes.recordset) {
124
+ lines.push('| \`' + clean(ag.Name, '') + '\` | ' + clean(ag.Type, '') + ' | ' + clean(ag.Description) + ' |');
125
+ }
126
+ lines.push('');
127
+ process.stdout.write(lines.join('\n'));
128
+ } finally {
129
+ await pool.close();
130
+ }
131
+ })().catch((err) => {
132
+ console.error('Capabilities query failed:', err);
133
+ process.exit(1);
134
+ });
135
+ ")"
44
136
 
45
- PRINT '';
46
- PRINT '## 3. Available Sub-Agents';
47
- PRINT '| Agent Name | Type | Description |';
48
- PRINT '|---|---|---|';
49
- SELECT '| \`' + Name + '\` | ' + Type + ' | ' + REPLACE(REPLACE(COALESCE(Description, 'No description'), CHAR(13), ' '), CHAR(10), ' ') + ' |'
50
- FROM [__mj].[vwAIAgents]
51
- ORDER BY Name ASC;
52
- "
137
+ if [ "$STDOUT_MODE" = true ]; then
138
+ printf '%s\n' "$content"
139
+ else
140
+ printf '%s\n' "$content" > "$target_file"
141
+ echo "Capabilities catalog updated at: $target_file"
142
+ fi
143
+ }
144
+
145
+ if [ -d "/workspace/node_modules/mssql" ] || [ -d "/workspace/apps/MJAPI/node_modules/mssql" ] || [ -d "/workspace/packages/MJAPI/node_modules/mssql" ]; then
146
+ generate_inside_container
147
+ exit 0
148
+ fi
53
149
 
54
- docker compose exec -T sqlserver /opt/mssql-tools18/bin/sqlcmd \
55
- -S localhost -U sa -P "$DB_PASSWORD" -d MemberJunction -C -No -W -w 200 \
56
- -Q "$SQL_QUERY" > "$OUTPUT_FILE" 2>/dev/null || {
57
- echo "Notice: Database not yet initialized; creating baseline CAPABILITIES.md"
58
- cat << 'EOF' > "$OUTPUT_FILE"
150
+ # Running on the host: delegate into the running `mj` container
151
+ cd "$DIR"
152
+ echo "Generating CAPABILITIES.md from database catalog..."
153
+
154
+ if docker compose ps --status running --format "{{.Service}}" 2>/dev/null | grep -qx "mj"; then
155
+ if grep -q "CAPABILITIES.md" "$DIR/docker-compose.yml" 2>/dev/null; then
156
+ docker compose exec -T -w /workspace mj bash /work/scripts/generate-capabilities.sh
157
+ else
158
+ TMP_FILE="${OUTPUT_FILE}.tmp"
159
+ docker compose exec -T -w /workspace mj bash /work/scripts/generate-capabilities.sh --stdout > "$TMP_FILE"
160
+ mv "$TMP_FILE" "$OUTPUT_FILE"
161
+ fi
162
+ echo "Capabilities catalog updated at: $OUTPUT_FILE"
163
+ else
164
+ echo "Notice: MemberJunction container ('mj') is not running; creating baseline CAPABILITIES.md"
165
+ cat << 'EOF' > "$OUTPUT_FILE"
59
166
  # System Capabilities Catalog
60
167
 
61
168
  *This catalog is automatically populated once your local database is booted and bootstrapped.*
@@ -64,11 +171,11 @@ docker compose exec -T sqlserver /opt/mssql-tools18/bin/sqlcmd \
64
171
  * `Send Email` - Send notification or transactional emails
65
172
  * `Create Record` - Insert a new record into any permitted entity
66
173
  * `Update Record` - Update an existing record by ID
67
- * `Run Query` - Execute a dynamic query against entities
174
+ * `Run Ad-hoc Query` - Execute a dynamic read-only query against entity views
175
+ * `Run Stored Query` - Execute a saved query by name or ID
68
176
  * `Get Record` - Fetch a record by primary key
69
177
 
70
- Run `./scripts/bootstrap.sh` to populate the complete catalog from your installed Open App.
178
+ Start the stack with `docker compose up -d` and re-run `./scripts/generate-capabilities.sh` to populate the complete catalog from your installed Open App.
71
179
  EOF
72
- }
73
-
74
- echo "Capabilities catalog updated at: $OUTPUT_FILE"
180
+ echo "Capabilities catalog updated at: $OUTPUT_FILE"
181
+ fi