@memberjunction/schema-engine 6.2.0-edge.5 → 6.2.0-edge.7

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.
@@ -11,21 +11,73 @@
11
11
  import { BaseSingleton } from '@memberjunction/global';
12
12
  import { LogError, Metadata, RunView, } from '@memberjunction/core';
13
13
  import { Octokit } from '@octokit/rest';
14
+ import { MintInstallationToken, ReadGitHubAppCredentials } from './GitHubAppAuth.js';
14
15
  import { RSUMetrics } from './RSUMetrics.js';
15
16
  import { GetDialect } from './DDLGenerator.js';
16
17
  import * as nodePath from 'node:path';
17
18
  import { appendFileSync } from 'node:fs';
18
19
  import * as childProcess from 'node:child_process';
20
+ import * as nodeOS from 'node:os';
19
21
  /** Signal string used to detect lock-held condition in database messages. */
20
22
  const RSU_LOCK_HELD_SIGNAL = 'RSU_LOCK_HELD';
23
+ // ─── Child-process heap containment ──────────────────────────────
24
+ //
25
+ // CodeGen and the TypeScript compile run as SEPARATE node processes while THIS process is
26
+ // still resident holding its own V8 heap. `NODE_OPTIONS` is an environment variable, so a
27
+ // child inherits it -- including `--max-old-space-size`. A deployer who sizes the API's
28
+ // ceiling to leave room for exactly this child then watches the child be handed the API's
29
+ // ceiling as well, and nothing enforces the sum.
30
+ //
31
+ // Observed 2026-09-14 on a 2 vCPU / 4 GB workspace compiling 364 new entities: the API was
32
+ // started with `--max-old-space-size=1964` (the deployer's arithmetic, reserving 1024 MB for
33
+ // the OS and this very child), the compile inherited the same 1964, and 1964 + 1964 > 3830.
34
+ // The kernel arbitrated by killing the largest RSS -- the API -- mid-step, taking the
35
+ // pipeline with it. No V8 abort, no JS error, nothing in any log but `dmesg`.
36
+ /** Share of currently-free memory a build child may claim as V8 old space. */
37
+ const CHILD_HEAP_FREE_FRACTION = 0.6;
38
+ /**
39
+ * Floor for a derived child ceiling. Going below this buys nothing: a child that cannot
40
+ * compile aborts either way, and an explicit small ceiling at least aborts DIAGNOSABLY,
41
+ * with V8 naming itself, instead of inheriting a large one and being killed by the kernel.
42
+ */
43
+ const MIN_CHILD_HEAP_MB = 512;
44
+ /** Cap for a derived child ceiling. A build does not need more, and the API still has to live. */
45
+ const MAX_CHILD_HEAP_MB = 4096;
21
46
  // ─── Typed RSU Configuration ─────────────────────────────────────────
47
+ /** File name RSU uses for additionalSchemaInfo when neither the env nor the server sets a path. */
48
+ export const DEFAULT_ADDITIONAL_SCHEMA_INFO_FILE = 'additionalSchemaInfo.json';
49
+ /**
50
+ * Resolves the absolute additionalSchemaInfo path RSU writes, stages and hands to CodeGen (#5858).
51
+ *
52
+ * Order matches CodeGen's `ResolveAdditionalSchemaInfoPath`: the `RSU_ADDITIONAL_SCHEMA_INFO_PATH`
53
+ * env override, then the path the server injected from mj.config (already absolute — resolved
54
+ * against the config file's directory), then {@link DEFAULT_ADDITIONAL_SCHEMA_INFO_FILE}.
55
+ * Relative values resolve against `workDir`; absolute values are kept as-is.
56
+ */
57
+ export function ResolveRSUAdditionalSchemaInfoPath(workDir, injectedPath, envOverride) {
58
+ const chosen = envOverride?.trim() || injectedPath?.trim() || DEFAULT_ADDITIONAL_SCHEMA_INFO_FILE;
59
+ return nodePath.resolve(workDir, chosen);
60
+ }
61
+ /**
62
+ * Returns the affected tables (`schema.table`) that have no entity in `entities`. Matching is
63
+ * case-insensitive; a name without a schema matches on table name alone.
64
+ */
65
+ export function FindTablesWithoutEntities(affectedTables, entities) {
66
+ const known = new Set(entities.map((e) => `${e.SchemaName}.${e.BaseTable}`.toLowerCase()));
67
+ const knownTables = new Set(entities.map((e) => e.BaseTable.toLowerCase()));
68
+ return [...new Set(affectedTables)].filter((t) => {
69
+ const key = t.toLowerCase();
70
+ return key.includes('.') ? !known.has(key) : !knownTables.has(key);
71
+ });
72
+ }
22
73
  /** Centralized, typed access to all RSU environment variables with defaults. */
23
74
  class RSUConfig {
24
75
  get MigrationsPath() {
25
76
  return process.env.RSU_MIGRATIONS_PATH || 'migrations/rsu';
26
77
  }
27
- get AdditionalSchemaInfoPath() {
28
- return process.env.RSU_ADDITIONAL_SCHEMA_INFO_PATH || 'additionalSchemaInfo.json';
78
+ /** The `RSU_ADDITIONAL_SCHEMA_INFO_PATH` override, or undefined when unset. */
79
+ get AdditionalSchemaInfoPathOverride() {
80
+ return process.env.RSU_ADDITIONAL_SCHEMA_INFO_PATH?.trim() || undefined;
29
81
  }
30
82
  get DefaultSchema() {
31
83
  return process.env.RSU_DEFAULT_SCHEMA || '__mj';
@@ -49,9 +101,46 @@ class RSUConfig {
49
101
  get CompileCommand() {
50
102
  return process.env.RSU_COMPILE_COMMAND;
51
103
  }
104
+ /**
105
+ * How many packages the compile builds at once. ONE by default, deliberately.
106
+ *
107
+ * `turbo build` with no `--concurrency` fans out one `tsc` per filtered package — three of them on
108
+ * a 2 vCPU / 4 GB instance that is also serving the API, beside a heap that has just finished
109
+ * CodeGen. On the sandbox that took the whole workspace off the air for the duration of the compile
110
+ * (MJ-RUN-33). A slower compile that leaves the API answering beats a faster one that does not.
111
+ */
112
+ get CompileConcurrency() {
113
+ return process.env.RSU_COMPILE_CONCURRENCY || '1';
114
+ }
115
+ /** How often the compile reports that it is still alive. */
116
+ get CompileHeartbeatMs() {
117
+ return parseInt(process.env.RSU_COMPILE_HEARTBEAT_MS || '30000', 10);
118
+ }
119
+ /**
120
+ * Grace between SIGTERM and SIGKILL when a command has to be killed for exceeding its timeout.
121
+ * Small on purpose: the command is already over budget, and the point of the kill is that the box
122
+ * gets its CPU back.
123
+ */
124
+ get CommandKillGraceMs() {
125
+ return parseInt(process.env.RSU_COMMAND_KILL_GRACE_MS || '5000', 10);
126
+ }
52
127
  get CompilePackages() {
53
128
  return process.env.RSU_COMPILE_PACKAGES;
54
129
  }
130
+ /**
131
+ * V8 old-space ceiling, in MB, for the CodeGen and compile CHILD processes.
132
+ *
133
+ * Unset means "derive one from the memory actually free when the step runs", which is almost
134
+ * always the right answer -- see {@link RuntimeSchemaManager.resolveChildHeapMB}. Set it only
135
+ * to pin a number a particular host is known to need.
136
+ */
137
+ get CompileHeapMB() {
138
+ const raw = process.env.RSU_COMPILE_HEAP_MB;
139
+ if (!raw)
140
+ return undefined;
141
+ const parsed = parseInt(raw, 10);
142
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
143
+ }
55
144
  get RestartCommand() {
56
145
  return process.env.RSU_RESTART_COMMAND;
57
146
  }
@@ -145,6 +234,16 @@ export class RuntimeSchemaManager extends BaseSingleton {
145
234
  super();
146
235
  // ─── State ───────────────────────────────────────────────────────
147
236
  this._isRunning = false;
237
+ /**
238
+ * True from the moment RunPipelineBatch begins until its outer `finally` — the whole pipeline,
239
+ * not just the DB-mutation window. `_isRunning` is the concurrency MUTEX and is deliberately
240
+ * released right after ExecuteMigration (the database is consistent from then on), which means
241
+ * it is false for WriteAdditionalSchemaInfo, RunCodeGen, CompileTypeScript, GitCommitAndPR and
242
+ * RestartMJAPI — roughly 95% of the pipeline's wall clock. Reporting the mutex as "running" made
243
+ * the API say no RSU was running while CodeGen was ten minutes in (sandbox, 2026-09-11), and every
244
+ * consumer that trusted it misjudged the build. Status reports THIS flag; the mutex stays a mutex.
245
+ */
246
+ this._pipelineActive = false;
148
247
  this._ddlProvider = null;
149
248
  this._codeGenRunner = null;
150
249
  this._codeGenOutputPaths = [];
@@ -213,12 +312,12 @@ export class RuntimeSchemaManager extends BaseSingleton {
213
312
  this._additionalSchemaInfoPath = configuredPath;
214
313
  }
215
314
  /**
216
- * The additionalSchemaInfo path RSU writes to, relative to WorkDir. Prefers the
217
- * CodeGen-configured path (injected at startup) so writer and reader agree; falls
218
- * back to the env/default only when nothing was injected.
315
+ * The absolute additionalSchemaInfo path RSU writes, stages and hands to CodeGen. Callers
316
+ * that build RSU input (resolvers, SchemaBuilder) read it here so they merge into the same
317
+ * file. See {@link ResolveRSUAdditionalSchemaInfoPath} for the resolution order.
219
318
  */
220
- get additionalSchemaInfoPath() {
221
- return this._additionalSchemaInfoPath ?? rsuConfig.AdditionalSchemaInfoPath;
319
+ get AdditionalSchemaInfoPath() {
320
+ return ResolveRSUAdditionalSchemaInfoPath(rsuConfig.WorkDir, this._additionalSchemaInfoPath, rsuConfig.AdditionalSchemaInfoPathOverride);
222
321
  }
223
322
  // ─── Pending Work (post-restart tasks) ─────────────────────────
224
323
  /**
@@ -476,7 +575,8 @@ export class RuntimeSchemaManager extends BaseSingleton {
476
575
  GetStatus() {
477
576
  return {
478
577
  Enabled: this.IsEnabled,
479
- Running: this.IsRunning,
578
+ // The pipeline, not the mutex — see _pipelineActive. Either is enough to be "running".
579
+ Running: this.IsRunning || this._pipelineActive,
480
580
  OutOfSync: this.IsOutOfSync,
481
581
  OutOfSyncSince: this._outOfSyncSince,
482
582
  LastRunAt: this._lastRunAt,
@@ -495,15 +595,51 @@ export class RuntimeSchemaManager extends BaseSingleton {
495
595
  */
496
596
  static { this.EXPECTED_STEPS_SHARED_PRE = ['ValidateEnvironment', 'ValidateSQL', 'AcquireLock']; }
497
597
  static { this.EXPECTED_STEPS_PER_ITEM = ['WriteMigrationFile', 'ExecuteMigration']; }
498
- static { this.EXPECTED_STEPS_SHARED_POST = ['WriteAdditionalSchemaInfo', 'RunCodeGen', 'CompileTypeScript', 'GitCommitAndPR', 'RestartMJAPI']; }
598
+ static { this.EXPECTED_STEPS_SHARED_POST = [
599
+ 'WriteAdditionalSchemaInfo',
600
+ 'RunCodeGen',
601
+ 'CompileTypeScript',
602
+ 'GitCommitAndPR',
603
+ 'RestartMJAPI',
604
+ ]; }
605
+ /**
606
+ * The steps that run AFTER the pipeline restarts the API on itself, in order.
607
+ *
608
+ * They belong to the same run — the setup journey the user is watching is not finished until the
609
+ * sync starts — but they execute in a DIFFERENT PROCESS, so nothing in this class ever runs them.
610
+ * They are declared here because this is where the run's shape is defined: they count towards
611
+ * {@link ExpectedStepTotal}, so the determinate progress bar does not reach 100% and then sit
612
+ * there while the connector is still not live, and they are named here so the post-restart
613
+ * consumer and this pipeline cannot drift apart on what the remaining steps are called.
614
+ */
615
+ static { this.EXPECTED_STEPS_POST_RESTART = ['CreateEntityMaps', 'StartSync']; }
616
+ /**
617
+ * The full expected step sequence for a batch of `itemCount` migrations, in execution order —
618
+ * including the two that run after the restart.
619
+ *
620
+ * Public and static so the arithmetic is directly assertable without a live pipeline; the number
621
+ * it produces is the denominator every progress UI divides by.
622
+ */
623
+ static ExpectedSteps(itemCount) {
624
+ const perItem = [];
625
+ for (let i = 0; i < itemCount; i++)
626
+ perItem.push(...RuntimeSchemaManager.EXPECTED_STEPS_PER_ITEM);
627
+ return [
628
+ ...RuntimeSchemaManager.EXPECTED_STEPS_SHARED_PRE,
629
+ ...perItem,
630
+ ...RuntimeSchemaManager.EXPECTED_STEPS_SHARED_POST,
631
+ ...RuntimeSchemaManager.EXPECTED_STEPS_POST_RESTART,
632
+ ];
633
+ }
634
+ /** Expected total steps for a batch of `itemCount` migrations. See {@link ExpectedSteps}. */
635
+ static ExpectedStepTotal(itemCount) {
636
+ return RuntimeSchemaManager.ExpectedSteps(itemCount).length;
637
+ }
499
638
  /** Arms the U11 step counter for a run of `itemCount` migrations. */
500
639
  beginStepTracking(itemCount) {
501
640
  this._currentStepIndex = 0;
502
641
  this._currentStepName = null;
503
- this._stepTotal =
504
- RuntimeSchemaManager.EXPECTED_STEPS_SHARED_PRE.length +
505
- itemCount * RuntimeSchemaManager.EXPECTED_STEPS_PER_ITEM.length +
506
- RuntimeSchemaManager.EXPECTED_STEPS_SHARED_POST.length;
642
+ this._stepTotal = RuntimeSchemaManager.ExpectedStepTotal(itemCount);
507
643
  }
508
644
  /** Clears the U11 step counter when the run finishes (status returns to idle). */
509
645
  endStepTracking() {
@@ -511,19 +647,102 @@ export class RuntimeSchemaManager extends BaseSingleton {
511
647
  this._currentStepIndex = null;
512
648
  this._stepTotal = null;
513
649
  }
650
+ /**
651
+ * How long the pipeline will wait for an observer to make a `restart.pending` event durable.
652
+ *
653
+ * Bounded on purpose. The wait exists because the process is seconds from being killed, but an
654
+ * observer that hangs must not wedge a schema migration — the invariant "progress reporting can
655
+ * never break a migration" outranks the checkpoint. Five seconds is orders of magnitude more than
656
+ * appending a few lines to a local file needs, and far less than the restart path's own timeouts.
657
+ */
658
+ static { this.OBSERVER_DURABLE_TIMEOUT_MS = 5_000; }
514
659
  /** Delivers an event to {@link PipelineObserver}, swallowing (but logging) any throw. */
515
660
  notifyObserver(event) {
516
661
  const observer = this.PipelineObserver;
517
662
  if (!observer)
518
663
  return;
519
664
  try {
520
- observer(event);
665
+ const maybePromise = observer(event);
666
+ // An observer may return a promise; for every event but `restart.pending` we do not wait on
667
+ // it. Attach a catch so a rejection is logged rather than surfacing as an unhandled rejection
668
+ // (which, depending on the Node flags, can take the process down mid-migration).
669
+ if (maybePromise && typeof maybePromise.then === 'function') {
670
+ void maybePromise.catch((error) => this.rsuLog(`Pipeline observer rejected on ${event.Kind} (ignored): ${error instanceof Error ? error.message : String(error)}`));
671
+ }
521
672
  }
522
673
  catch (error) {
523
674
  // Progress reporting must never break a schema migration.
524
675
  this.rsuLog(`Pipeline observer threw on ${event.Kind} (ignored): ${error instanceof Error ? error.message : String(error)}`);
525
676
  }
526
677
  }
678
+ /**
679
+ * Delivers an event and WAITS for the observer to finish with it, bounded by
680
+ * {@link OBSERVER_DURABLE_TIMEOUT_MS}. Used for exactly one event: `restart.pending`.
681
+ *
682
+ * The ordinary fire-and-forget path is wrong there. The observer's durable write is asynchronous,
683
+ * and the very next thing the pipeline does is issue a command that kills this process — so a
684
+ * queued-but-unflushed checkpoint is simply lost, and the whole point of the checkpoint is that it
685
+ * survives the kill. Errors and timeouts are swallowed exactly as they are on the sync path.
686
+ */
687
+ async notifyObserverDurable(event) {
688
+ const observer = this.PipelineObserver;
689
+ if (!observer)
690
+ return;
691
+ try {
692
+ const maybePromise = observer(event);
693
+ if (!maybePromise || typeof maybePromise.then !== 'function')
694
+ return;
695
+ let timer;
696
+ const timeout = new Promise((resolve) => {
697
+ timer = setTimeout(() => {
698
+ this.rsuLog(`Pipeline observer did not settle ${event.Kind} within ${RuntimeSchemaManager.OBSERVER_DURABLE_TIMEOUT_MS}ms — continuing`);
699
+ resolve();
700
+ }, RuntimeSchemaManager.OBSERVER_DURABLE_TIMEOUT_MS);
701
+ timer.unref?.();
702
+ });
703
+ try {
704
+ await Promise.race([maybePromise, timeout]);
705
+ }
706
+ finally {
707
+ if (timer)
708
+ clearTimeout(timer);
709
+ }
710
+ }
711
+ catch (error) {
712
+ this.rsuLog(`Pipeline observer failed on ${event.Kind} (ignored): ${error instanceof Error ? error.message : String(error)}`);
713
+ }
714
+ }
715
+ /**
716
+ * The de-duplicated set of connections a batch touches, in input order.
717
+ *
718
+ * Resolution order per input: the explicit {@link RSUPipelineInput.CompanyIntegrationID} first,
719
+ * then the `CompanyIntegrationID` of any {@link RSUPipelineInput.PendingWork} entry. The fallback
720
+ * is not a convenience — it is the compatibility path that gives EVERY production caller today an
721
+ * identity without changing a single call site, because every one of them registers post-restart
722
+ * work against a connection. An input with neither contributes nothing, and a batch where no
723
+ * input has either yields an empty set: that run stays unreadable through the per-connection
724
+ * endpoints, which is the conservative answer, not a bug.
725
+ *
726
+ * Public and static so the identity rule is assertable on its own.
727
+ */
728
+ static CollectCompanyIntegrationIDs(inputs) {
729
+ const seen = new Set();
730
+ const ordered = [];
731
+ const add = (id) => {
732
+ if (!id)
733
+ return;
734
+ if (seen.has(id))
735
+ return;
736
+ seen.add(id);
737
+ ordered.push(id);
738
+ };
739
+ for (const input of inputs) {
740
+ add(input.CompanyIntegrationID);
741
+ for (const work of input.PendingWork ?? [])
742
+ add(work.CompanyIntegrationID);
743
+ }
744
+ return ordered;
745
+ }
527
746
  /**
528
747
  * Records a completed step onto `steps` AND publishes it to the observer, so a step is never
529
748
  * visible in the result but absent from the event stream. Every step recording goes through
@@ -613,12 +832,14 @@ export class RuntimeSchemaManager extends BaseSingleton {
613
832
  const sharedSteps = [];
614
833
  // U11 — arm the determinate step counter (index of expected total) for this run.
615
834
  this.beginStepTracking(inputs.length);
835
+ this._pipelineActive = true;
616
836
  this.notifyObserver({
617
837
  Kind: 'run.start',
618
838
  ItemCount: inputs.length,
619
839
  Descriptions: inputs.map((i) => i.Description),
620
840
  AffectedTables: [...new Set(inputs.flatMap((i) => i.AffectedTables))],
621
841
  StepTotal: this._stepTotal ?? 0,
842
+ CompanyIntegrationIDs: RuntimeSchemaManager.CollectCompanyIntegrationIDs(inputs),
622
843
  });
623
844
  // Captured so the `finally` can publish the terminal run boundary on EVERY exit path —
624
845
  // early validation failure, normal completion, or a throw (which leaves it undefined).
@@ -641,6 +862,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
641
862
  }
642
863
  finally {
643
864
  this.endStepTracking();
865
+ this._pipelineActive = false;
644
866
  this.notifyRunEnd(batchResult, inputs.length);
645
867
  }
646
868
  }
@@ -706,8 +928,33 @@ export class RuntimeSchemaManager extends BaseSingleton {
706
928
  const result = { ApiRestarted: false, GitCommitSuccess: false };
707
929
  if (successfulItems.length === 0)
708
930
  return result;
931
+ const successfulInputs = successfulItems.map((r) => r.Input);
932
+ // Register durable pending work BEFORE CodeGen and the compile, not after.
933
+ //
934
+ // The work becomes OWED the moment the migrations succeed: the tables exist, and nothing but
935
+ // these rows records that they still need entity maps. Registering after the compile left the
936
+ // two longest and most memory-hungry steps of the pipeline inside the window where a crash
937
+ // loses the work SILENTLY -- which is precisely where crashes land. Observed 2026-09-14: a
938
+ // kernel OOM kill during CompileTypeScript left 364 tables built, zero entity maps, no
939
+ // pending-work row and no error anywhere, because the only process that could have reported
940
+ // it was the one that died.
941
+ //
942
+ // Rows stay Pending until the post-restart consumer completes them, so moving this earlier
943
+ // only widens the window in which a crash is RECOVERABLE. A run that now fails before the
944
+ // restart leaves visible, resumable work instead of silence.
945
+ const pendingWork = await this.registerPendingWork(successfulInputs);
946
+ result.PendingWorkIDs = pendingWork.IDs;
947
+ result.PendingWorkErrors = pendingWork.Errors;
709
948
  await this.runStep('WriteAdditionalSchemaInfo', () => this.writeAdditionalSchemaInfo(successfulItems.map((r) => r.Input)), sharedSteps);
710
- const codegenOk = await this.runStep('RunCodeGen', () => this.runCodeGen(), sharedSteps);
949
+ const affectedTables = [...new Set(successfulItems.flatMap((r) => r.Input.AffectedTables))];
950
+ const codegenOk = await this.runStep('RunCodeGen', async () => {
951
+ await this.runCodeGen();
952
+ // CodeGen can succeed while creating no entity for a table (e.g. it read an
953
+ // additionalSchemaInfo without the table's soft primary key). Fail the step and name
954
+ // the tables, or every later sync silently skips them (#5858).
955
+ await this.verifyEntitiesExist(affectedTables);
956
+ return true;
957
+ }, sharedSteps);
711
958
  // Thread the CodeGen success/failure into the post-migration result. A migration
712
959
  // can ExecuteMigration:success yet leave its entity with NO spCreate/spUpdate procs
713
960
  // if RunCodeGen failed — after which a sync silently skips the entity with
@@ -721,9 +968,26 @@ export class RuntimeSchemaManager extends BaseSingleton {
721
968
  }
722
969
  if (codegenOk) {
723
970
  const compileOk = await this.runStep('CompileTypeScript', () => this.compileTypeScript(), sharedSteps);
971
+ result.CompileSucceeded = !!compileOk;
724
972
  if (compileOk) {
725
973
  this.ClearOutOfSync();
726
974
  }
975
+ else {
976
+ // STOP HERE. Everything below assumes the tree on disk matches the migrated database, and a
977
+ // failed compile is exactly the case where it does not:
978
+ // - GitCommitAndPR would publish a migration whose generated code never built (its only
979
+ // guard was SkipGitCommit, so it ran regardless);
980
+ // - RestartMJAPI would bring the API back up on an UNCOMPILED tree.
981
+ // On the sandbox that combination presented as a 40-minute outage behind a pipeline that
982
+ // reported itself complete (MJ-RUN-33). The API stays flagged out-of-sync, the pending work
983
+ // registered above stays Pending (visible and resumable, not consumed until a restart onto a
984
+ // tree that built), and the caller's result names the step.
985
+ result.CompileError =
986
+ sharedSteps.find((s) => s.Name === 'CompileTypeScript' && s.Status === 'failed')?.Message ??
987
+ 'TypeScript compile failed after CodeGen — the API code on disk does not match the migrated database';
988
+ this.rsuLog(`Compile failed — NOT committing and NOT restarting: ${result.CompileError}`);
989
+ return result;
990
+ }
727
991
  }
728
992
  // Git commit + PR before restart — PM2 restart kills this process
729
993
  if (!inputs.every((i) => i.SkipGitCommit)) {
@@ -738,16 +1002,25 @@ export class RuntimeSchemaManager extends BaseSingleton {
738
1002
  }
739
1003
  // Write caller-provided PostRestartFiles ONLY for successful migrations.
740
1004
  // Failed migrations should not trigger post-restart entity maps or syncs.
741
- const successfulInputs = successfulItems.map(r => r.Input);
742
1005
  await this.writePostRestartFiles(successfulInputs);
743
- // Register durable pending work for successful migrations. Rows stay Pending
744
- // until the post-restart consumer completes them, so a crash between here and
745
- // consumption leaves the work visible instead of losing it.
746
- const pendingWork = await this.registerPendingWork(successfulInputs);
747
- result.PendingWorkIDs = pendingWork.IDs;
748
- result.PendingWorkErrors = pendingWork.Errors;
749
1006
  // Restart LAST — PM2 restart kills this process, nothing runs after this
750
1007
  if (!inputs.every((i) => i.SkipRestart)) {
1008
+ // Publish the restart boundary BEFORE issuing it. `runStep('RestartMJAPI', ...)` will emit a
1009
+ // step.start and then never emit a step.end, because pm2 kills us inside restartMJAPI() — so
1010
+ // this is the last chance to tell an observer that the pipeline reached the restart in good
1011
+ // order, and to hand the process on the other side what it needs to pick the run back up.
1012
+ // Awaited (not fire-and-forget) precisely because we are about to be killed.
1013
+ await this.notifyObserverDurable({
1014
+ Kind: 'restart.pending',
1015
+ RemainingSteps: [...RuntimeSchemaManager.EXPECTED_STEPS_POST_RESTART],
1016
+ // +1: the RestartMJAPI step is issued next and its own increment happens inside runStep.
1017
+ StepIndex: this._currentStepIndex === null ? undefined : this._currentStepIndex + 1,
1018
+ StepTotal: this._stepTotal ?? undefined,
1019
+ CompanyIntegrationIDs: RuntimeSchemaManager.CollectCompanyIntegrationIDs(successfulInputs),
1020
+ PendingWorkIDs: [...new Set([...(result.PendingWorkIDs?.values() ?? [])].flat())],
1021
+ TotalCount: inputs.length,
1022
+ SuccessCount: successfulItems.length,
1023
+ });
751
1024
  const restartOk = await this.runStep('RestartMJAPI', () => this.restartMJAPI(), sharedSteps);
752
1025
  if (restartOk)
753
1026
  result.ApiRestarted = true;
@@ -760,19 +1033,23 @@ export class RuntimeSchemaManager extends BaseSingleton {
760
1033
  // A run-wide CodeGen failure means the migrations applied but the entities may have
761
1034
  // no stored procedures — treat the run as failed, not success.
762
1035
  const codeGenFailed = postResult.CodeGenSucceeded === false;
763
- this._lastRunResult = successfulItems.length > 0 && !codeGenFailed ? 'success' : 'failed';
1036
+ // A failed compile is the same class of failure one step later: the DDL is committed, the entity
1037
+ // classes were generated, and nothing built them — so the running API cannot use them.
1038
+ const compileFailed = postResult.CompileSucceeded === false;
1039
+ this._lastRunResult = successfulItems.length > 0 && !codeGenFailed && !compileFailed ? 'success' : 'failed';
764
1040
  const results = itemResults.map((item) => {
765
1041
  const allSteps = [...sharedSteps, ...item.Steps];
766
1042
  // A migration that executed but whose run-wide CodeGen failed is NOT a success —
767
1043
  // the entity may have no spCreate/spUpdate procs and would silently skip on sync.
768
1044
  const codeGenFailedThisCaller = codeGenFailed && item.Success;
1045
+ const compileFailedThisCaller = compileFailed && item.Success;
769
1046
  // Same reasoning as the CodeGen case above: the migration ran, but work the caller
770
1047
  // asked to happen after the restart was never persisted, so the restart drops it.
771
1048
  // Reporting success here would tell the caller their sync is coming when it is not.
772
1049
  const pendingWorkErrors = postResult.PendingWorkErrors?.get(item.Input) ?? [];
773
1050
  const pendingWorkFailedThisCaller = pendingWorkErrors.length > 0 && item.Success;
774
1051
  const result = {
775
- Success: item.Success && successfulItems.length > 0 && !codeGenFailed && !pendingWorkFailedThisCaller,
1052
+ Success: item.Success && successfulItems.length > 0 && !codeGenFailed && !compileFailed && !pendingWorkFailedThisCaller,
776
1053
  MigrationFilePath: item.FilePath,
777
1054
  APIRestarted: postResult.ApiRestarted,
778
1055
  GitCommitSuccess: postResult.GitCommitSuccess,
@@ -780,16 +1057,20 @@ export class RuntimeSchemaManager extends BaseSingleton {
780
1057
  Steps: allSteps,
781
1058
  ErrorMessage: codeGenFailedThisCaller
782
1059
  ? postResult.CodeGenError ?? item.Error
783
- : pendingWorkFailedThisCaller
784
- ? pendingWorkErrors.join('; ')
785
- : item.Error,
1060
+ : compileFailedThisCaller
1061
+ ? postResult.CompileError ?? item.Error
1062
+ : pendingWorkFailedThisCaller
1063
+ ? pendingWorkErrors.join('; ')
1064
+ : item.Error,
786
1065
  ErrorStep: codeGenFailedThisCaller
787
1066
  ? 'RunCodeGen'
788
- : pendingWorkFailedThisCaller
789
- ? 'RegisterPendingWork'
790
- : item.Error
791
- ? item.Steps.find((s) => s.Status === 'failed')?.Name
792
- : undefined,
1067
+ : compileFailedThisCaller
1068
+ ? 'CompileTypeScript'
1069
+ : pendingWorkFailedThisCaller
1070
+ ? 'RegisterPendingWork'
1071
+ : item.Error
1072
+ ? item.Steps.find((s) => s.Status === 'failed')?.Name
1073
+ : undefined,
793
1074
  PendingWorkIDs: postResult.PendingWorkIDs?.get(item.Input),
794
1075
  };
795
1076
  this.writeAuditLog(item.Input, result).catch((err) => LogError(`[RSU] Audit log failed: ${err instanceof Error ? err.message : String(err)}`));
@@ -960,7 +1241,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
960
1241
  const workDir = rsuConfig.WorkDir;
961
1242
  const directoriesToCheck = [
962
1243
  nodePath.join(workDir, rsuConfig.MigrationsPath),
963
- dirname(nodePath.join(workDir, this.additionalSchemaInfoPath)),
1244
+ dirname(this.AdditionalSchemaInfoPath),
964
1245
  rsuConfig.CodeGenDir,
965
1246
  workDir, // pipeline log
966
1247
  ];
@@ -1058,7 +1339,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
1058
1339
  }
1059
1340
  /**
1060
1341
  * Write/merge AdditionalSchemaInfo (soft PK/FK config) to disk so CodeGen can find it.
1061
- * Path comes from RSU_ADDITIONAL_SCHEMA_INFO_PATH config, resolved relative to WorkDir.
1342
+ * Path comes from {@link AdditionalSchemaInfoPath} — the same file CodeGen reads.
1062
1343
  */
1063
1344
  async writeAdditionalSchemaInfo(inputs) {
1064
1345
  const contents = inputs
@@ -1067,8 +1348,8 @@ export class RuntimeSchemaManager extends BaseSingleton {
1067
1348
  if (contents.length === 0)
1068
1349
  return true;
1069
1350
  const { readFileSync, writeFileSync, existsSync, mkdirSync } = await import('node:fs');
1070
- const { join, dirname } = await import('node:path');
1071
- const configFilePath = join(rsuConfig.WorkDir, this.additionalSchemaInfoPath);
1351
+ const { dirname } = await import('node:path');
1352
+ const configFilePath = this.AdditionalSchemaInfoPath;
1072
1353
  // Load existing config or start fresh
1073
1354
  // Format: { schemaName: [ { TableName, PrimaryKey?, ForeignKeys? }, ... ], ... }
1074
1355
  let existing = {};
@@ -1205,9 +1486,12 @@ export class RuntimeSchemaManager extends BaseSingleton {
1205
1486
  const { writeFileSync, unlinkSync } = await import('node:fs');
1206
1487
  const codegenDir = rsuConfig.CodeGenDir;
1207
1488
  const timeoutMs = rsuConfig.CodeGenTimeoutMs;
1489
+ // The child resolves additionalSchemaInfo on its own, from its own cwd. Pin it to the file
1490
+ // this process just wrote so the two cannot diverge (#5858).
1491
+ const childEnv = { ...this.buildChildEnv(), RSU_ADDITIONAL_SCHEMA_INFO_PATH: this.AdditionalSchemaInfoPath };
1208
1492
  const customCmd = rsuConfig.CodeGenCommand;
1209
1493
  if (customCmd) {
1210
- await execAsync(`cd "${codegenDir}" && ${customCmd}`, { timeout: timeoutMs });
1494
+ await execAsync(`cd "${codegenDir}" && ${customCmd}`, { timeout: timeoutMs, env: childEnv });
1211
1495
  return true;
1212
1496
  }
1213
1497
  // Write a temp .mjs script inside the codegen dir so Node module resolution
@@ -1223,7 +1507,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
1223
1507
  writeFileSync(tmpScript, scriptContent, 'utf-8');
1224
1508
  try {
1225
1509
  // Exit code 0 = success. No stdout string matching needed.
1226
- await execAsync(`cd "${codegenDir}" && node "${tmpScript}"`, { timeout: timeoutMs });
1510
+ await execAsync(`cd "${codegenDir}" && node "${tmpScript}"`, { timeout: timeoutMs, env: childEnv });
1227
1511
  return true;
1228
1512
  }
1229
1513
  catch (err) {
@@ -1242,6 +1526,29 @@ export class RuntimeSchemaManager extends BaseSingleton {
1242
1526
  }
1243
1527
  }
1244
1528
  }
1529
+ /**
1530
+ * Throws when any affected table has no entity after CodeGen, listing the missing tables.
1531
+ * Reads the Entity table directly: the in-memory metadata is not refreshed until restart.
1532
+ */
1533
+ async verifyEntitiesExist(affectedTables) {
1534
+ if (affectedTables.length === 0)
1535
+ return;
1536
+ const provider = this.getDBProvider();
1537
+ const d = this.dialect;
1538
+ const schemas = [...new Set(affectedTables.filter((t) => t.includes('.')).map((t) => t.split('.')[0]))];
1539
+ const schemaFilter = schemas.length > 0
1540
+ ? ` WHERE ${d.QuoteIdentifier('SchemaName')} IN (${schemas.map((_, i) => d.ParameterPlaceholder(i)).join(', ')})`
1541
+ : '';
1542
+ const sql = `SELECT ${d.QuoteIdentifier('SchemaName')}, ${d.QuoteIdentifier('BaseTable')} ` +
1543
+ `FROM ${d.QuoteSchema(provider.MJCoreSchemaName, 'Entity')}${schemaFilter}`;
1544
+ const rows = await provider.ExecuteSQL(sql, schemas.length > 0 ? schemas : undefined, { description: 'RSU post-CodeGen entity check' });
1545
+ const missing = FindTablesWithoutEntities(affectedTables, rows);
1546
+ if (missing.length > 0) {
1547
+ throw new RSUError('CODEGEN_NO_ENTITIES', `CodeGen completed but created no entity for ${missing.length} of ${affectedTables.length} table(s): ${missing.join(', ')}. ` +
1548
+ `Check that additionalSchemaInfo (${this.AdditionalSchemaInfoPath}) declares a primary key for each table and that CodeGen reads the same file.`);
1549
+ }
1550
+ this.rsuLog(`Verified an entity exists for all ${affectedTables.length} affected table(s)`);
1551
+ }
1245
1552
  /**
1246
1553
  * Compile affected TypeScript packages after CodeGen.
1247
1554
  *
@@ -1254,27 +1561,161 @@ export class RuntimeSchemaManager extends BaseSingleton {
1254
1561
  * Set RSU_COMPILE_COMMAND to override the entire build command (e.g. for
1255
1562
  * environments without turbo).
1256
1563
  */
1564
+ /**
1565
+ * V8 old-space ceiling to hand a build child, in MB.
1566
+ *
1567
+ * Derived from the memory free AT THE MOMENT THE STEP RUNS, which beats any constant chosen
1568
+ * at deploy time: by this point the API's real usage is a measurement rather than a guess,
1569
+ * and it is the API's real usage that decides what is left for the child.
1570
+ */
1571
+ resolveChildHeapMB() {
1572
+ const configured = rsuConfig.CompileHeapMB;
1573
+ if (configured)
1574
+ return configured;
1575
+ const freeMB = Math.floor(nodeOS.freemem() / (1024 * 1024));
1576
+ const candidate = Math.floor(freeMB * CHILD_HEAP_FREE_FRACTION);
1577
+ return Math.min(MAX_CHILD_HEAP_MB, Math.max(MIN_CHILD_HEAP_MB, candidate));
1578
+ }
1579
+ /**
1580
+ * Environment for a CodeGen or compile child, with THIS process's heap ceiling replaced by one
1581
+ * sized for a process that runs ALONGSIDE it rather than instead of it. See the
1582
+ * child-heap-containment note at the top of this file for what inheriting it costs.
1583
+ *
1584
+ * Only `--max-old-space-size` is rewritten; every other `NODE_OPTIONS` flag the host set is
1585
+ * preserved, because some of them (module resolution, loaders) are load-bearing for the build.
1586
+ */
1587
+ buildChildEnv() {
1588
+ const heapMB = this.resolveChildHeapMB();
1589
+ const inherited = process.env.NODE_OPTIONS ?? '';
1590
+ const withoutHeap = inherited.replace(/--max-old-space-size=\d+/g, '').replace(/\s+/g, ' ').trim();
1591
+ const nodeOptions = `${withoutHeap} --max-old-space-size=${heapMB}`.trim();
1592
+ this.rsuLog(`[RSU] build child heap ceiling: ${heapMB} MB (inherited NODE_OPTIONS: "${inherited || '(unset)'}")`);
1593
+ return { ...process.env, NODE_OPTIONS: nodeOptions };
1594
+ }
1257
1595
  async compileTypeScript() {
1258
- const { execAsync } = await this.getExecAsync();
1259
1596
  const codegenDir = rsuConfig.CodeGenDir;
1260
1597
  const timeoutMs = rsuConfig.CompileTimeoutMs;
1261
- // Allow full command override
1262
- const compileCmd = rsuConfig.CompileCommand;
1263
- if (compileCmd) {
1264
- await execAsync(`cd "${codegenDir}" && ${compileCmd}`, { timeout: timeoutMs });
1598
+ const startedAt = Date.now();
1599
+ const elapsedSec = () => Math.round((Date.now() - startedAt) / 1000);
1600
+ // A compile is minutes of silence from a process that is also the API. Say so, with the elapsed
1601
+ // time against the budget, so the pm2 log an incident gets read from can distinguish "compiling"
1602
+ // from "hung" — on the sandbox the only record of a 40-minute compile was its failure line.
1603
+ const heartbeat = setInterval(() => this.rsuLog(`CompileTypeScript still running — ${elapsedSec()}s elapsed of a ${Math.round(timeoutMs / 1000)}s budget`), rsuConfig.CompileHeartbeatMs);
1604
+ heartbeat.unref?.();
1605
+ try {
1606
+ // A full-command override is honoured as-is, but it goes through the same killable runner: the
1607
+ // override exists precisely because the default command was starving small boxes, and the
1608
+ // replacement must be no harder to stop.
1609
+ const compileCmd = rsuConfig.CompileCommand ?? this.defaultCompileCommand();
1610
+ await this.runCommandInOwnProcessGroup(`cd "${codegenDir}" && ${compileCmd}`, { timeoutMs, env: this.buildChildEnv() });
1611
+ this.rsuLog(`CompileTypeScript completed in ${elapsedSec()}s`);
1265
1612
  return true;
1266
1613
  }
1267
- // Build using turbo with --filter for each package
1614
+ finally {
1615
+ clearInterval(heartbeat);
1616
+ }
1617
+ }
1618
+ /**
1619
+ * The turbo invocation the compile step uses when nothing overrides it.
1620
+ *
1621
+ * `--concurrency` is the load-bearing part: without it turbo builds every filtered package at once,
1622
+ * which is three `tsc` processes on a 2 vCPU / 4 GB instance that is simultaneously serving the API.
1623
+ * See {@link RSUConfig.CompileConcurrency}.
1624
+ */
1625
+ defaultCompileCommand() {
1268
1626
  const defaultPackages = '@memberjunction/core-entities,@memberjunction/server,mj_api';
1269
1627
  const envPackages = rsuConfig.CompilePackages;
1270
1628
  const rawPackages = envPackages !== undefined ? envPackages : defaultPackages;
1271
- const packageNames = rawPackages
1629
+ const filterArgs = rawPackages
1272
1630
  .split(',')
1273
- .map((p) => p.trim())
1274
- .filter((p) => p.length > 0);
1275
- const filterArgs = packageNames.map((p) => `--filter="${p}"`).join(' ');
1276
- await execAsync(`cd "${codegenDir}" && npx turbo build ${filterArgs}`, { timeout: timeoutMs });
1277
- return true;
1631
+ .map((pkg) => pkg.trim())
1632
+ .filter((pkg) => pkg.length > 0)
1633
+ .map((pkg) => `--filter="${pkg}"`)
1634
+ .join(' ');
1635
+ return `npx turbo build ${filterArgs} --concurrency=${rsuConfig.CompileConcurrency}`;
1636
+ }
1637
+ /**
1638
+ * Runs a shell command in its OWN process group, and kills the whole group if it exceeds its
1639
+ * timeout.
1640
+ *
1641
+ * Why this exists rather than `execAsync(cmd, { timeout })`: `promisify(exec)`'s timeout signals the
1642
+ * `/bin/sh` it spawned, NOT the process tree beneath it, and the promise it returns does not settle
1643
+ * until every pipe closes. A `turbo build` that outran its timeout therefore kept its `tsc` children
1644
+ * alive AND left the pipeline awaiting a promise that would never resolve — a 300-second budget that
1645
+ * ran for 40 minutes and ended only when a deploy replaced the release directory underneath it
1646
+ * (MJ-RUN-33). The timeout was decorative.
1647
+ *
1648
+ * Three properties make it real:
1649
+ * - `detached: true` puts the child in a new process group whose id IS the child's pid, so
1650
+ * `process.kill(-pid, …)` reaches every descendant — the shell, turbo, and each `tsc`.
1651
+ * - SIGTERM first, SIGKILL after {@link RSUConfig.CommandKillGraceMs}, so a child that ignores the
1652
+ * polite signal still loses the CPU.
1653
+ * - the promise REJECTS as soon as the kill is issued, rather than waiting for pipes that a wedged
1654
+ * child may never close. Not settling was half the defect.
1655
+ *
1656
+ * Windows has no process groups in this sense; there the child is killed directly.
1657
+ */
1658
+ runCommandInOwnProcessGroup(command, opts) {
1659
+ const maxBuffer = opts.maxBuffer ?? 50 * 1024 * 1024; // 50 MB — build output is verbose
1660
+ const posix = process.platform !== 'win32';
1661
+ return new Promise((resolve, reject) => {
1662
+ const child = childProcess.spawn(command, {
1663
+ shell: true,
1664
+ detached: posix,
1665
+ stdio: ['ignore', 'pipe', 'pipe'],
1666
+ // The per-child heap ceiling (buildChildEnv) — a compile run through this runner must not lose it.
1667
+ env: opts.env ?? process.env,
1668
+ });
1669
+ let stdout = '';
1670
+ let stderr = '';
1671
+ let settled = false;
1672
+ child.stdout?.on('data', (chunk) => {
1673
+ if (stdout.length < maxBuffer)
1674
+ stdout += String(chunk);
1675
+ });
1676
+ child.stderr?.on('data', (chunk) => {
1677
+ if (stderr.length < maxBuffer)
1678
+ stderr += String(chunk);
1679
+ });
1680
+ const killGroup = (signal) => {
1681
+ try {
1682
+ if (posix && child.pid !== undefined)
1683
+ process.kill(-child.pid, signal);
1684
+ else
1685
+ child.kill(signal);
1686
+ }
1687
+ catch {
1688
+ /* already gone — nothing to signal */
1689
+ }
1690
+ };
1691
+ const settle = (fn) => {
1692
+ if (settled)
1693
+ return;
1694
+ settled = true;
1695
+ clearTimeout(timer);
1696
+ fn();
1697
+ };
1698
+ // The SIGKILL escalation, armed only when the timeout fires; cleared once the child has
1699
+ // actually closed so it never fires at a process group that is already gone.
1700
+ let hardKill;
1701
+ const timer = setTimeout(() => {
1702
+ killGroup('SIGTERM');
1703
+ hardKill = setTimeout(() => killGroup('SIGKILL'), rsuConfig.CommandKillGraceMs);
1704
+ hardKill.unref?.();
1705
+ settle(() => reject(new RSUError('COMMAND_TIMEOUT', `Command exceeded its ${opts.timeoutMs}ms timeout and its process group was killed: ${command}` +
1706
+ (stderr ? ` — last stderr: ${stderr.slice(-500)}` : ''))));
1707
+ }, opts.timeoutMs);
1708
+ timer.unref?.();
1709
+ child.on('error', (err) => settle(() => reject(err)));
1710
+ child.on('close', (code, signal) => {
1711
+ if (hardKill)
1712
+ clearTimeout(hardKill);
1713
+ if (code === 0)
1714
+ settle(() => resolve({ stdout, stderr }));
1715
+ else
1716
+ settle(() => reject(new RSUError('COMMAND_FAILED', `Command failed (exit ${code ?? signal}): ${command}\n${stderr.slice(-2000)}`)));
1717
+ });
1718
+ });
1278
1719
  }
1279
1720
  /**
1280
1721
  * Restart MJAPI via PM2.
@@ -1388,7 +1829,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
1388
1829
  * For Docker/CI environments without a local `.git` directory.
1389
1830
  */
1390
1831
  async gitCommitAndPRViaAPI(migrationFilePaths, affectedTables, description) {
1391
- const octokit = this.createOctokit();
1832
+ const octokit = await this.createOctokit();
1392
1833
  const { owner, repo } = this.resolveGitHubOwnerRepo();
1393
1834
  const branchName = this.generateBranchName(affectedTables);
1394
1835
  const baseBranch = rsuConfig.GitTargetBranch;
@@ -1523,7 +1964,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
1523
1964
  }
1524
1965
  }
1525
1966
  // AdditionalSchemaInfo
1526
- const schemaInfoPath = resolve(workDir, rsuConfig.AdditionalSchemaInfoPath);
1967
+ const schemaInfoPath = this.AdditionalSchemaInfoPath;
1527
1968
  if (existsSync(schemaInfoPath)) {
1528
1969
  files.push({ repoPath: this.toRepoRelativePath(schemaInfoPath, workDir), absolutePath: schemaInfoPath });
1529
1970
  }
@@ -1586,13 +2027,27 @@ export class RuntimeSchemaManager extends BaseSingleton {
1586
2027
  'Runtime Schema Update (RSU) pipeline — auto-generated PR.',
1587
2028
  ].join('\n');
1588
2029
  }
1589
- /** Create an authenticated Octokit instance from environment token. */
1590
- createOctokit() {
2030
+ /**
2031
+ * An authenticated Octokit instance: a plain token when one is set, otherwise a token minted from
2032
+ * the GitHub App the process was deployed with (GITHUB_APP_ID / _INSTALLATION_ID / _PRIVATE_KEY —
2033
+ * the same names the feedback resolver reads), scoped to the one repository this pipeline commits
2034
+ * to. Until this fallback existed every App-deployed workspace ended this step with "GitHub token
2035
+ * not found", and because the step is non-fatal the migration and generated code it had just
2036
+ * produced lived only on the box, where the next deploy discarded them.
2037
+ */
2038
+ async createOctokit() {
1591
2039
  const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
1592
- if (!token) {
1593
- throw new RSUError('GIT', 'GitHub token not found. Set GITHUB_TOKEN or GH_TOKEN environment variable for PR creation.');
2040
+ if (token) {
2041
+ return new Octokit({ auth: token });
2042
+ }
2043
+ const app = ReadGitHubAppCredentials();
2044
+ if (!app) {
2045
+ throw new RSUError('GIT', 'GitHub credentials not found. Set GITHUB_TOKEN/GH_TOKEN, or GITHUB_APP_ID + GITHUB_APP_INSTALLATION_ID + GITHUB_APP_PRIVATE_KEY (the App the deploy installs) for PR creation.');
1594
2046
  }
1595
- return new Octokit({ auth: token });
2047
+ const { repo } = this.resolveGitHubOwnerRepo();
2048
+ const installationToken = await MintInstallationToken(new Octokit(), app, repo);
2049
+ this.rsuLog(`GitHub App ${app.AppId}: minted an installation token scoped to "${repo}"`);
2050
+ return new Octokit({ auth: installationToken });
1596
2051
  }
1597
2052
  /**
1598
2053
  * Generate a branch name from affected table names.
@@ -1846,6 +2301,9 @@ export class RuntimeSchemaManager extends BaseSingleton {
1846
2301
  execAsync: (cmd, opts) => execAsync(cmd, {
1847
2302
  timeout: opts?.timeout ?? 60_000,
1848
2303
  maxBuffer: opts?.maxBuffer ?? 50 * 1024 * 1024, // 50 MB (CodeGen is verbose)
2304
+ // Only forwarded when the caller supplies one; omitted, the child inherits
2305
+ // process.env exactly as before.
2306
+ ...(opts?.env ? { env: opts.env } : {}),
1849
2307
  }),
1850
2308
  };
1851
2309
  }