Repository navigation
Expand file tree
/
Copy pathdev.ts
More file actions
1265 lines (1215 loc) · 67.4 KB
/
Copy pathdev.ts
File metadata and controls
1265 lines (1215 loc) · 67.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import chalk from 'chalk';
import { spawnSync, spawn } from 'child_process';
import dotenvFlow from 'dotenv-flow';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { printHeader, printKV, printStep, printError } from '../utils/format.js';
import { redactConnectionUrl } from '../utils/connection-display.js';
import { databaseDriverFlag } from '../utils/database-driver-flag.js';
import {
DEV_WATCH_IGNORED,
ServeRestartCoordinator,
assessArtifactStaleness,
formatMtimeGap,
} from '../utils/dev-restart.js';
import {
isOrganizationOwnershipRequiredMessage,
upgradeDevelopmentDatabase,
type DevelopmentUpgradeResult,
} from '../utils/dev-organization-ownership-upgrade.js';
import { childEnvWithResolvedArtifact } from '../utils/internal-artifact-channel.js';
import { devCompilesAtBoot } from '../utils/dev-compile-at-boot.js';
import { makeDirectorySync } from '../utils/make-directory.js';
// THE artifact precedence, written once (#21501) — shared with `start`, and
// with the `serve` child this command spawns. ⛔ No rung of it is restated here.
import {
CONVENTIONAL_ARTIFACT_RELATIVE_PATH,
cwdConfigJoinsBoot,
isRemoteArtifact,
resolveArtifactBootSource,
} from '../utils/artifact-precedence.js';
import { artifactObjectNames } from '../utils/stack-collections.js';
import { readEnvWithDeprecation, isMcpServerEnabled } from '@objectstack/types';
import { OBJECTSTACK_MCP_SERVER_NAME } from '@objectstack/mcp';
// The ONE port contract, shared with `start` and with the `serve` child this
// command spawns (#12673). ⛔ Nothing about ports is declared in this file —
// no range, no reader, no wording; a second copy of the bound is exactly what
// #12620 and #12662 protected against.
import { describePortSource, parseRequestedPort, formatInvalidPortNotice, portFlagEnv } from '../utils/port-contract.js';
import { applyCryptoKeyFileChannel } from '../utils/internal-crypto-key-file-channel.js';
// The ONE dev-TLS contract, shared with the `serve` child this command spawns
// (#16804). ⛔ Nothing about certificates is declared in this file, and ⛔ no
// certificate is ever generated — the developer brings their own.
import {
devTlsCertFlag,
devTlsKeyFlag,
resolveDevTlsIntent,
listenerProtocol,
devTlsChildArgs,
colorizeDevTlsNotice,
type ListenerProtocol,
} from '../utils/dev-tls-contract.js';
// The auth base-URL precedence chain, borrowed from the command that owns it
// (#16734). ⛔ `dev` declares no chain of its own — see printMcpConnectHint.
// The development auto-shift and its notice, borrowed from the command that owns
// them (#26270): this process runs the same walk before it compiles, so the
// config reads the port the `serve` child will bind.
import { resolveAuthBaseUrl, getAvailablePort, formatDevPortShiftNotice } from './serve.js';
import type { ResolvedProjectDatabaseUrl } from '@objectstack/runtime';
/**
* Resolve the database URL for `objectstack dev` — dev's flag surface mapped
* onto the ONE shared resolution (`resolveProjectDatabaseUrl`, #6469) that
* `os start` and `os migrate` resolve through too. Priority: `--database` /
* `--fresh`'s ephemeral file → `OS_DATABASE_URL` / `DATABASE_URL` /
* `TURSO_DATABASE_URL` → the config-declared default datasource → the unified
* default `<state dir>/data/objectstack.db` (legacy `dev.db` / `standalone.db`
* still compat-read, with the loud `notice` line). The in-memory (mingo)
* engine is no longer a boot store: `--database-driver memory` is refused by
* the flag's allowlist, and `OS_DATABASE_DRIVER=memory` by the shared
* resolution ahead of every rung — so this seam never hands `dev` a Database
* row for a store its serve child would refuse. `--fresh` (a throwaway file)
* and `--database :memory:` (SQLite's own in-memory database) replace it.
*
* `dev` keeps a persistent default on purpose — the historical serve default
* of `:memory:` wipes all data (and AI-authored metadata) on every restart,
* which makes local app-building unusable.
*
* This wrapper is dev's ONE resolution seam (pinned, together with start's and
* migrate's, by `unified-db-resolution.pin.test.ts`): it maps inputs, it never
* re-implements any fallback. The runtime import is lazy so oclif's
* import-every-command startup (#5726) does not pay for the runtime graph.
*/
export async function resolveDevDatabase(opts: {
databaseFlag?: string;
freshDbUrl?: string;
databaseDriverFlag?: string;
env: Record<string, string | undefined>;
cwd: string;
artifactPath?: string;
}): Promise<ResolvedProjectDatabaseUrl> {
const { resolveProjectDatabaseUrl } = await import('@objectstack/runtime');
return resolveProjectDatabaseUrl({
explicitUrl: opts.databaseFlag ?? opts.freshDbUrl,
explicitDriver: opts.databaseDriverFlag,
env: opts.env,
projectRoot: opts.cwd,
artifactPath: opts.artifactPath,
});
}
/**
* Make the directory of `os dev`'s unified-default SQLite database
* (`<state dir>/data/`), bounded — or throw at once, naming the database
* file, the directory and the operating system's code (#23737).
*
* Only the `unified-default` source is prepared here; every other source is
* the serve child's to open (and its standalone host prepares the directory
* with the same bounded walk).
*
* ## Why not `fs.mkdirSync(dir, { recursive: true })`
*
* Node's recursive mkdir (v22.22.0, measured; sync and async alike) never
* returns when a level answers `ENOENT` although its parent exists. Under
* `OS_HOME=/proc/os-23737` this command looped `mkdir("/proc/os-23737")` ↔
* `mkdir("/proc")` in its own process (64,440 failing calls in 25 s) and never
* reached its next line.
*
* The walk is this package's {@link makeDirectorySync}: `EEXIST` on a created
* level is accepted only when a directory stands there. A dangling symlink in
* the path answers `EEXIST` to `mkdir` and `ENOENT` to `stat`, so it is refused
* here, at once, naming the link (#24090). Accepting any `EEXIST` let it
* through to the serve child, whose boot then failed seconds later with a
* plugin-start error that named neither the file nor the directory.
*/
export function prepareDevDatabaseDirectory(
resolved: Pick<ResolvedProjectDatabaseUrl, 'url' | 'source'>,
): void {
if (resolved.source !== 'unified-default') return;
const filename = resolved.url.replace(/^file:/, '');
const directory = path.resolve(path.dirname(filename));
try {
makeDirectorySync(directory);
} catch (e) {
const code = (e as { code?: unknown } | null)?.code;
const reason = e instanceof Error ? e.message : String(e);
throw Object.assign(
new Error(
`The default database '${filename}' cannot be created: its directory '${directory}' could not be made: ${reason}`,
),
{ code: typeof code === 'string' ? code : undefined, filename, directory, cause: e },
);
}
}
/**
* The `os dev` MCP connect hint — the three lines a reader PASTES (#3167,
* #16734).
*
* ## The origin these lines carry is the one an MCP client can REACH
*
* `Connect` is a COMMAND, not documentation: whatever address it names is the
* address `claude mcp add` registers. So the block has to print the origin the
* deployment is reachable on — which is exactly what the ready banner the
* serve child prints in the same boot output already carries, resolved through
* {@link resolveAuthBaseUrl} (`OS_AUTH_URL` → legacy `BETTER_AUTH_URL` →
* `OS_BASE_URL` → `http://localhost:<port>`).
*
* It used to be built from the child's `objectstack:listening` `url`, which is
* the socket the child BOUND, by construction. `OS_AUTH_URL` never entered
* that expression, so behind anything at all — a TLS reverse proxy, a compose
* stack that only `expose`s the app port — one boot printed two origins.
* MEASURED with `objectstack dev -p 4001` under
* `OS_AUTH_URL=https://localhost:4443`: the banner's `➜ MCP:` row said
* `https://localhost:4443/…` and this block said `http://localhost:4001/…`.
* Pasting the latter registers an MCP entry against an origin discovery never
* advertises and the proxy never exposes — and makes the correct row look
* like the typo.
*
* ⛔ The chain is NOT re-derived here: this calls the same function `serve`
* calls, with the port the child ACTUALLY bound. That is also why the ordinary
* local case needs no fallback of its own — with none of the three variables
* set, the resolver's own built-in tail answers `http://localhost:<boundPort>`,
* dev's auto-shifted port (3000 busy → 3001) included.
*
* ## `null` means print nothing, never guess
*
* `baseOrigin` is `null` when the chain produced a value that will not parse —
* a set-but-empty `OS_AUTH_URL=` (which does NOT fall through to the rest of
* the chain), or a value with no scheme. The banner's rule for that case is to
* print the paths with no origin in front of them and name the variable that
* fixes it. A connect COMMAND has no paths-only form, so the honest output
* here is no block at all: falling back to the bound socket would reprint, on
* the same screen, the exact address the banner just refused to print.
*
* ## The server name is not this process's to choose
*
* ⛔ The `Connect` row names the server {@link OBJECTSTACK_MCP_SERVER_NAME},
* the same constant the served `SKILL.md` (`GET /api/v1/mcp/skill`) reads. It
* used to be the current folder's basename, so one endpoint was registered as
* the folder's name from the banner and as `objectstack` from the skill and
* the console: two entries for one server in the agent's config.
*/
export function printMcpConnectHint(
opts: { boundPort: number | string; boundProtocol?: ListenerProtocol },
): void {
const { baseOrigin } = resolveAuthBaseUrl(opts.boundPort, opts.boundProtocol ?? 'http');
if (baseOrigin === null) return;
console.log();
console.log(chalk.cyan(' 🤖 MCP server — connect a coding agent:'));
console.log(` Endpoint ${baseOrigin}/api/v1/mcp`);
console.log(` Skill ${baseOrigin}/api/v1/mcp/skill`);
console.log(chalk.dim(` Connect claude mcp add --transport http ${OBJECTSTACK_MCP_SERVER_NAME} ${baseOrigin}/api/v1/mcp`));
console.log(chalk.dim(' Disable OS_MCP_SERVER_ENABLED=false'));
}
/**
* The hop outward: relay the `serve` child's `objectstack:seed-settled`
* announcement to `os dev`'s OWN parent (#17329).
*
* ## Why the hop exists at all
*
* `os dev` is a spawner. It runs `serve --dev` over
* `stdio: ['inherit','inherit','inherit','ipc']`, so the child's settle
* announcement lands HERE and stops — while the consumer that needs it (a demo
* script, a test harness, anything that spawns `os dev` and wants to print one
* line after the boot) holds a channel to `os dev`, not to a grandchild process
* it did not start and cannot name. One hop is the whole of the missing piece:
* the producer already exists, and the child already announces.
*
* ## Relayed verbatim, deliberately
*
* ⛔ Nothing here re-derives, re-summarises or re-grades the message. The child
* read the settlement tally off the kernel that did the seeding; this process
* has no kernel and could only guess. Passing the object through means `os
* dev`'s parent and the `serve` child can never be made to say two different
* things about one boot — the same rule the `MCP:` row above follows for the
* origin, and for the same reason.
*
* ## An IPC channel stays OPTIONAL for this command
*
* ⛔ A parent that holds no channel must be unaffected, and is: `process.send`
* is `undefined` under an ordinary terminal `os dev`, so this returns having
* done nothing, printed nothing, and changed no byte of that transcript. The
* `serve` child's own `announceListening` is best-effort for exactly this
* reason and this is its mirror — ⛔ this message does not make an IPC channel
* a requirement of running a published command.
*
* @returns `true` when the message was a settle announcement (handled here, and
* the caller should stop) — `false` for every other message, which the
* caller's own branches still own.
*/
export function forwardSeedSettledToParent(msg: unknown): boolean {
if ((msg as { type?: unknown } | null | undefined)?.type !== 'objectstack:seed-settled') return false;
try {
if (typeof process.send === 'function') process.send(msg);
} catch { /* the parent's channel closed — best-effort, exactly like the child's */ }
return true;
}
/**
* The internal channel `@objectstack/cloud-connection` reads as
* `FRESH_HOME_CHANNEL_ENV` (#30217): the ephemeral `OS_HOME` a `--fresh` run
* created. Spelled here rather than imported because oclif loads every command
* module on every invocation; `dev-fresh-home-channel.test.ts` holds the two
* spellings equal.
*/
export const FRESH_HOME_CHANNEL_ENV = 'OS_INTERNAL_FRESH_HOME';
/**
* Set or clear {@link FRESH_HOME_CHANNEL_ENV} on the serve child's env
* (#30217). Under `--fresh` it names the run's ephemeral `OS_HOME`, so the
* install ledger there adopts nothing from the project's working-directory
* ledger — a fresh run starts without an earlier run's installs. Otherwise it is
* removed: the parent owns the variable, so an inherited copy never speaks for
* a home this run did not create. Not an operator setting.
*/
export function applyFreshHomeChannel(childEnv: NodeJS.ProcessEnv, freshHome: string | undefined): void {
if (freshHome) childEnv[FRESH_HOME_CHANNEL_ENV] = freshHome;
else delete childEnv[FRESH_HOME_CHANNEL_ENV];
}
/**
* Whether this `os dev` boot runs the watch-recompile loop (#20681).
*
* Off when the operator passed `--no-watch`, when the boot serves an artifact
* `os dev` does not build — `--artifact`, or the reference `OS_ARTIFACT_URL`
* (#21501) — since a rebuild would change nothing that is served, or when the
* cwd has no `objectstack.config.ts`. The one decision both the loop and the
* stale-artifact remedy line read, exported so `dev-no-watch.pin.test.ts` can
* drive it with what oclif actually parsed.
*/
export function devWatchActive(opts: { watch: boolean; artifact?: string; configExists: boolean }): boolean {
return opts.watch && !opts.artifact && opts.configExists;
}
/**
* What `os dev` prints when the organization-ownership boot guard refused its
* `serve` child, and the upgrade it then runs (ADR-0131 D10, development
* exception; `utils/dev-organization-ownership-upgrade.ts`). The coordinator's
* `recover` calls this once per session; `upgrade` copies the development
* database, runs the ceremony on it and answers its verdict.
*
* ⛔ The first line names no origin for the database. Every refusal the guard
* throws reaches this path — a marker absent, unverified, unreadable or from an
* older shape generation, a shape read that failed, a birth write that failed —
* and only the absent marker means "17.x or an 18.0 pre-release created it". The
* guard's own refusal, printed just above this line by the failed boot, already
* names what it found, so this line points at it rather than carrying a second
* copy of that wording, which would be wrong for the other five.
*
* The copy's path is printed by the verdict lines below, from the upgrade's own
* result.
*
* @returns whether the upgrade finished and the server may boot again.
*/
export async function upgradeRefusedDevelopmentDatabase(io: {
/** Writes one line for the developer. */
print: (line: string) => void;
/** Copies the development database, then plans and applies the ceremony on it. */
upgrade: () => Promise<DevelopmentUpgradeResult>;
}): Promise<boolean> {
io.print(chalk.yellow(
' ⟳ The organization-ownership boot guard refused this development database (the refusal above), so '
+ 'os dev upgrades it in place, keeping a copy first…',
));
const result = await io.upgrade();
for (const warning of result.warnings) io.print(chalk.yellow(` ⚠ ${warning}`));
for (const line of result.lines) io.print(result.ok ? chalk.green(` ✓ ${line}`) : chalk.red(` ✗ ${line}`));
return result.ok;
}
export default class Dev extends Command {
static override description =
'Start development mode — watch sources, rebuild the artifact, and restart the server on change';
static override args = {
package: Args.string({ description: 'Package name or filter pattern', default: 'all', required: false }),
};
static override flags = {
// `allowNo` is what makes the off branch below (`devWatchActive`, the
// watch-recompile loop) reachable at all: without it `--no-watch` is a
// "Nonexistent flag", and `--watch=false` is not a boolean spelling oclif
// reads — it parses as `--watch` plus the PACKAGE positional `false`
// (#20681). Same declaration as the sibling `compile` / `restart` /
// `seed-admin` switches.
watch: Flags.boolean({
char: 'w',
description: 'Watch objectstack.config.ts and src/, rebuilding on change (default: on). Disable with --no-watch.',
default: true,
allowNo: true,
}),
ui: Flags.boolean({ description: 'Enable the bundled Console portal at /_console/' }),
verbose: Flags.boolean({ char: 'v', description: 'Verbose output (shortcut for --log-level debug)' }),
'log-level': Flags.string({
description: 'Kernel logger level forwarded to `serve` (overrides $OS_LOG_LEVEL / $LOG_LEVEL; default `warn`). One of: debug | info | warn | error | fatal | silent.',
options: ['debug', 'info', 'warn', 'error', 'fatal', 'silent'],
}),
port: Flags.string({ char: 'p', description: 'Server port (overrides $OS_PORT; $PORT is the legacy alias)' }),
// #16804 — developer-supplied TLS, forwarded to the `serve` child. Declared
// through the shared contract so the two commands cannot drift on the flag
// names, the prose, or what half a pair means.
cert: devTlsCertFlag(),
key: devTlsKeyFlag(),
preset: Flags.string({
description: 'Plugin tier preset forwarded to `serve`: minimal | default | full',
}),
// Default ON (#26130): see `devCompilesAtBoot` for why a dev boot over an
// artifact it builds always rebuilds it first.
compile: Flags.boolean({
description: 'Compile objectstack.config.ts to dist/objectstack.json before starting, under this boot\'s environment (default: on). --no-compile boots the existing artifact as built (still compiled when it is missing). Ignored when --artifact is set.',
default: true,
allowNo: true,
}),
restart: Flags.boolean({
description:
'Restart the server after each successful rebuild so the running server always matches dist/objectstack.json. With --no-restart the watcher only rebuilds the artifact — the running server keeps the build it booted with until you restart it yourself, and every rebuild says so.',
default: true,
allowNo: true,
}),
// ── Runtime overrides (mirror `os start`) ────────────────────────
// These let `os dev` consume a pre-built artifact and arbitrary
// storage/auth without an `objectstack.config.ts` in the cwd. When
// `--artifact` is set the auto-compile path is skipped — there's no
// source to compile from. All flags override the matching env var.
artifact: Flags.string({
char: 'a',
description: 'Path or http(s):// URL to a compiled objectstack.json (skips auto-compile; overrides $OS_ARTIFACT_URL, $OS_ARTIFACT_PATH and a cwd objectstack.config.ts)',
}),
'environment-id': Flags.string({
description: 'Environment identifier (overrides $OS_ENVIRONMENT_ID, default env_local)',
}),
database: Flags.string({
char: 'd',
description: 'Database URL: file:./db.sqlite | :memory: | libsql://... | postgres://... | mongodb://... (overrides $OS_DATABASE_URL)',
}),
// Enforced allowlist, not a help string — see `utils/database-driver-flag.ts`.
// Both the choices and the enumerated list in the description come from the
// shared driver table (#6969), so this declaration and `start.ts`'s cannot
// drift from each other or from the table; `database-driver-allowlist.pin.test.ts`
// (#6860) still pins the agreement with `resolveStorageDefinition`.
'database-driver': databaseDriverFlag('Force driver kind'),
'database-auth-token': Flags.string({
description: 'Auth token for libsql/Turso connections (overrides $OS_DATABASE_AUTH_TOKEN / $TURSO_AUTH_TOKEN)',
}),
'auth-secret': Flags.string({
description: 'Secret for @objectstack/plugin-auth (overrides $AUTH_SECRET; dev mode injects an insecure default if neither is set)',
}),
// ── Ephemeral / fresh-environment helpers ────────────────────────
// `--fresh` creates an isolated tempdir for OS_HOME / DB / uploads, so
// every run starts from a clean slate for the OS_HOME-keyed state the
// CLI itself places (see the block in `run()` for the exact covered
// surface, and for what an app-declared relative path escapes — #5594).
// Combine with `--seed-admin`
// (default-on when --fresh) to also provision a logged-in admin
// account, so backend debugging never blocks on first-run wizards.
// The seeded admin uses FIXED, well-known credentials by default
// (admin@objectos.ai / admin123) so tooling never has to guess them —
// override with --admin-email / --admin-password when needed.
fresh: Flags.boolean({
description: 'Start with an ephemeral OS_HOME under the OS tempdir — clean DB, uploads root and other OS_HOME-keyed state for this run, auto-deleted on exit. State an app reaches by its own cwd-relative path (e.g. a datasource `filename: .objectstack/...`) is NOT covered and survives exit. Implies --seed-admin (admin@objectos.ai / admin123) unless --no-seed-admin is given.',
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
description: 'Email for the seeded admin account.',
default: 'admin@objectos.ai',
}),
'admin-password': Flags.string({
description: 'Password for the seeded admin account (min 8 chars).',
default: 'admin123',
}),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Dev);
const packageName = args.package;
// ── The TLS pair, read ONCE, ahead of every child and every printer ──
// Refused here rather than one process later so half a pair is named under
// the spelling the operator typed, and resolved before the connect hint
// below so the parent's derived origin and the child's bound socket come
// from the same answer (#16804). ⛔ This reads no certificate — the child
// binds the socket, so the child owns the refusal for an unusable file.
const tlsIntent = resolveDevTlsIntent(flags);
if (tlsIntent.kind === 'incomplete') {
console.error(colorizeDevTlsNotice(tlsIntent.notice));
process.exit(1);
}
const boundProtocol: ListenerProtocol = listenerProtocol(tlsIntent);
// Load .env files following Vite/Next.js convention (mirrors `serve`).
// `dev` is always development mode, so prefer `.env.development*` over
// `.env.production*`. Loaded BEFORE any env lookups.
dotenvFlow.config({ node_env: 'development', silent: true });
printHeader('Development Mode');
// ── Single-Environment Mode ──────────────────────────────────────────────────
const configPath = path.resolve(process.cwd(), 'objectstack.config.ts');
const configExists = fs.existsSync(configPath);
// `--artifact` lets `os dev` boot a pre-built artifact without any
// local config — semantically the same as `os start` but with the
// dev conveniences (NODE_ENV=development, dev-fallback AUTH_SECRET,
// --ui default-on, dev-mode error formatting).
//
// Resolved through THE precedence (`utils/artifact-precedence.ts`, #21501),
// the one `start` resolves through — `dev` used to carry its own copy with
// no `OS_ARTIFACT_URL` rung, so the reference beat `--artifact` in the
// child. The answer is printed, handed down and served as one value: the
// `serve` child boots it even beside a cwd `objectstack.config.ts`.
const bootSource = resolveArtifactBootSource({ flag: flags.artifact, env: process.env, cwd: process.cwd() });
// `OS_ARTIFACT_URL` drives the boot: the child resolves it, as under `start`.
const artifactUrl = bootSource.kind === 'reference' ? bootSource.url : undefined;
// The artifact this boot serves — or, when no artifact rung answered, the
// conventional path the cwd config compiles to (the precedence's last rung).
const artifactPath = bootSource.kind === 'resolved'
? bootSource.path
: path.resolve(process.cwd(), CONVENTIONAL_ARTIFACT_RELATIVE_PATH);
// An artifact this command does not build from the cwd sources: the flag,
// the reference, or a remote `OS_ARTIFACT_PATH`. Nothing is compiled into
// it, watched for it, or judged stale against it.
const pinnedArtifact = flags.artifact ?? artifactUrl
?? (isRemoteArtifact(artifactPath) ? artifactPath : undefined);
// Where THIS command compiles the cwd config: the artifact it builds, which
// is `<cwd>/dist/objectstack.json` or the operator's local
// `OS_ARTIFACT_PATH` (#21501, as triage ruled). That file is the config's
// own compiled output wherever it lives, so the config joins the boot that
// serves it, and the child is told the path so it recognises it too.
const configCompiledTo = pinnedArtifact || !configExists ? undefined : artifactPath;
if (packageName === 'all' && (configExists || flags.artifact)) {
// `Config:` only when the cwd config takes part in this boot — the same
// predicate the `serve` child loads it by (#21501).
const configJoins = cwdConfigJoinsBoot({
configExists,
configPath,
artifact: artifactUrl ? { kind: 'reference' } : { kind: 'path', path: artifactPath, configCompiledTo },
});
if (configJoins) {
printKV('Config', configPath, '📂');
}
let port = flags.port ?? readEnvWithDeprecation('OS_PORT', 'PORT', { silent: true });
// ── dev's own door on the ONE port contract (#12673) ──────────────
// Everything about the port — the range, the reader, the refusal prose —
// is imported from `utils/port-contract.ts`; this command declares none
// of it. That is the point of the card: `os dev` had no port validation
// at all, so an impossible value travelled to the `serve` child, which
// refused it under the name of the CHANNEL it arrived on. Measured on
// `origin/main` before this door existed: `PORT=abc os dev` and
// `OS_PORT=abc os dev` were both refused as `--port "abc"` — the one
// spelling the operator had not used, because the forwarding below
// renames every source to `--port`.
//
// ⭐ Placement: ahead of the compile below, which is the first child this
// command starts and the first process that evaluates the config, so a
// refused port starts nothing and a valid one is exported (below) before
// anything reads it. The refusal covers exactly the text this command
// FORWARDS: the `port ? …` guard in the spawn argv reads this same
// variable, so the two cannot drift.
//
// ⛔ The `if (port)` is load-bearing, and MEASURED rather than assumed:
// `os dev --port ""` boots today. An empty string is falsy, so the guard
// below drops it and the child resolves its own default — so a door that
// refused every non-parsing text would refuse a value that starts a
// server, narrowing a published command's accept set, which this card is
// forbidden to do. (`PORT=""` reaches the child by inheritance instead,
// and `serve` refuses it there naming `PORT` — correctly, since that IS
// the spelling the operator set.)
if (port) {
// `flags.port === undefined` answers the same question oclif's
// `setFromDefault` answers for `serve`: did this come from argv? This
// flag carries no `default`, so there is no oclif metadata to read —
// and none to trust either, since oclif runs neither a flag `parse`
// nor an integer `min`/`max` over a default (measured; see the
// `describePortSource` docblock).
const portSource = describePortSource(flags.port === undefined);
if (parseRequestedPort(port) === null) {
// stderr, like `serve`'s refusal and for the same #7915 reason: this
// command's stdout is the fd the child's stdio MCP transport writes
// JSON-RPC frames to.
process.stderr.write(`${formatInvalidPortNotice(port, portSource)}\n`);
process.exit(1);
}
// ── The flag's port is the port the config reads (#26243) ──────────
// A config reads `OS_PORT`/`PORT` at module evaluation (the showcase's
// self URL does), and it is evaluated in the compile below, the watch
// recompiles and the `serve` child, which all run in THIS process's
// environment. The flag reached none of them before: it travelled on
// argv alone, so `os dev -p 41302` served and dispatched
// `http://127.0.0.1:3000`. Exported here as `os start` hands it down
// (`portFlagEnv`), so the flag overrides an inherited `OS_PORT` for the
// config exactly as it does for the listener. With no flag, the
// operator's own variables stay as they are.
if (flags.port !== undefined) Object.assign(process.env, portFlagEnv(parseRequestedPort(port) ?? undefined));
}
const requestedPort = port ?? '3000';
// ── The port the server will bind is the port the config reads (#26270) ──
// The `serve` child shifts off a busy port, but it did so after the
// compile below and its own config load had both read the requested
// port. Measured on the showcase with 41310 held: `os dev -p 41310`
// served on 41311 while `/api/v1/meta/connector/showcase_status_api`
// named 41310 and the self-ping flow answered `400 FLOW_FAILED`.
//
// So this process runs the child's walk (`getAvailablePort`, from the
// same requested port) ahead of the first config evaluation. On a shift
// it says so in the child's words, exports the port on the one channel a
// config reads (`portFlagEnv`, for the compile, the watch recompiles and
// the child), and forwards it as the child's `--port`, so the child binds
// it without walking again and every restart keeps it.
//
// ⚠️ The probe releases the port before the child binds it. A port taken
// in that window makes the child shift once more: it says so, and exports
// its own port for the config it loads (`serve.ts`), but the artifact
// compiled here keeps this port until the next recompile. An exhausted
// walk is left to the child, which repeats it and prints why.
const askedFor = parseRequestedPort(requestedPort);
if (askedFor !== null) {
let bound = askedFor;
try {
bound = await getAvailablePort(askedFor);
} catch {
// The child's own walk reports this (`formatExhaustedPortSearchNotice`).
}
if (bound !== askedFor) {
// stderr, for the #7915 reason the port refusal above gives.
process.stderr.write(`${formatDevPortShiftNotice(askedFor, bound)}\n`);
Object.assign(process.env, portFlagEnv(bound));
port = String(bound);
}
}
// Compile only when the boot's artifact is one this command builds — a
// pinned artifact means "use this, don't rebuild" — and then by default
// (#26130, `devCompilesAtBoot`).
const needsCompile = devCompilesAtBoot({
compile: flags.compile,
pinned: Boolean(pinnedArtifact),
configExists,
artifactExists: fs.existsSync(artifactPath),
});
if (needsCompile) {
if (!configExists) {
printError('No objectstack.config.ts and no --artifact given — nothing to start.');
console.error(chalk.yellow(' Run `objectstack init`, `objectstack build`, or pass `--artifact <path|url>`.'));
process.exit(1);
}
printStep('Compiling objectstack.config.ts → dist/objectstack.json...');
const binPath = process.argv[1];
// NOTE: Do NOT set NODE_ENV='development' on this child — the same rule
// the serve spawn below carries, for a second, independently measured
// reason. Oclif's tsx-based TypeScript source loader is activated when
// NODE_ENV is 'test' or 'development', and tsx honours the *cwd*
// tsconfig's `paths`. Example apps map workspace packages to their
// TypeScript SOURCE there — `@objectstack/formula` →
// `../../packages/formula/src/index.ts` — so a loader-activating child
// resolves a CJS package to `.ts`, after which Node's CJS resolver
// walks that file's siblings and knows nothing about `.ts`:
// `Cannot find module './registry'`, and `os dev` dies before the
// server starts. Measured: the failures map 1:1 onto each app's `paths`
// entries — app-showcase (formula + plugin-email) fails on both,
// app-crm (formula only) on one, app-todo (no `paths` block) on none.
// The import SPELLING was never the variable: plugin-email already
// ships the explicit `./email-plugin.js` extension and fails
// identically. This is a TYPE-resolution directive leaking into RUNTIME
// resolution, so it is fixed on the side that leaks it. `compile` reads
// NODE_ENV nowhere, and the artifact is byte-identical either way apart
// from the `/runtimeModule` hash, which differs run-to-run regardless
// (the bundle embeds `builtAt`). Pinned by
// child-env-source-loader.pin.test.ts.
//
// ⚠️ WHAT THIS RULE NO LONGER CARRIES, so the next reader does not
// re-derive it: the CONSEQUENCE above was never conditional on a child
// being handed the variable. Writing no `NODE_ENV` here leaves the
// child inheriting whatever the parent has, so an operator who merely
// EXPORTED `NODE_ENV=development` reproduced every word of it — and on
// a direct `os serve --dev` or `os start`, which has no parent to scrub
// at all. That class is closed one level down, where it is actually
// decided: `bin/run.js` declares `settings.enableAutoTranspile = false`,
// so the built entry resolves its commands from `dist/` whatever
// `NODE_ENV` says (#12271 — its docblock carries the measurement).
// ⛔ This rule stays anyway and is not redundant: it keeps the CLI's own
// sources from ASSERTING a loader-activating value, which is a
// different claim from the entry refusing to act on one, and it is the
// half `child-env-source-loader.pin.test.ts` can see.
const compileResult = spawnSync(
process.execPath,
[binPath, 'compile', '--output', artifactPath],
{ stdio: 'inherit' },
);
if (compileResult.status !== 0) {
printError('Compile failed — fix errors above before starting dev server');
process.exit(1);
}
}
// ── Startup staleness warning (#5148 startup variant) ───────────
// With --no-compile, `os dev` boots whatever dist/objectstack.json
// holds (#26130 made compiling the default). When the sources are NEWER than the artifact (edited while
// the server was down, stale checkout), the boot silently serves the
// old build — measured in #5148: the config had gained a capability
// and dev still printed `Plugins: 38 loaded` until a manual build.
// Warn loudly and name the remedy; never gate the boot (per triage:
// remove the silence, not the start).
const watchActive = devWatchActive({ watch: flags.watch, artifact: pinnedArtifact, configExists });
if (!needsCompile && !pinnedArtifact && configExists) {
const stale = assessArtifactStaleness({
artifactPath,
configPath,
srcDir: path.resolve(process.cwd(), 'src'),
});
if (stale) {
const relArtifact = path.relative(process.cwd(), artifactPath);
const relSource = path.relative(process.cwd(), stale.newestSourcePath);
const gap = formatMtimeGap(stale.newestSourceMtimeMs - stale.artifactMtimeMs);
console.log(chalk.yellow.bold(` ⚠ ${relArtifact} is OLDER than your sources — this boot serves the STALE build.`));
console.log(chalk.yellow(` newest source: ${relSource} (${gap} newer than the artifact)`));
console.log(chalk.yellow(
' fix: run `objectstack build` or start with `--compile`'
+ (watchActive ? ', or save a watched file to trigger a rebuild' + (flags.restart ? ' + restart' : '') : '')
+ '.',
));
}
}
printStep('Starting dev server (local mode)...');
const environmentId = flags['environment-id'] ?? process.env.OS_ENVIRONMENT_ID ?? 'env_local';
// ── --fresh: ephemeral OS_HOME under the OS tempdir ─────────────
// Creates a unique scratch dir that owns the state this command can
// actually place, and nothing more. What it covers, exactly:
// - the dev SQLite DB the CLI resolves for the run
// (OS_HOME → <home>/data/objectstack.db, published as OS_DATABASE_URL),
// - the storage-service uploads root, published on the settings
// service's own env name OS_STORAGE_LOCAL_ROOT (#4968),
// - the install-local ledger, which follows OS_HOME (#30217); the
// child is told this home is ephemeral (applyFreshHomeChannel), so
// it adopts nothing from the project's working-directory ledger,
// - any other state a plugin keys off OS_HOME.
// In one sentence: framework-owned, OS_HOME-keyed state plus the env
// channels this block publishes below. Auto-deleted on exit.
//
// NOT covered — state reached by an app-declared RELATIVE path (#5594).
// Such a path is resolved by its own consumer against the process cwd,
// which `--fresh` does not move, so it is written into the project tree
// and survives exit. The live specimen is deliberate authoring, not a
// bug: examples/app-showcase's `showcase-external` datasource declares
// `filename: '.objectstack/data/showcase_external.db'` and says in its
// own comment that the path resolves against the project cwd — so a
// `--fresh` run of the showcase leaves that file (+ -wal/-shm) behind.
// Re-anchoring app-declared relative paths on OS_HOME would be a
// behaviour change resting on an open contract question ("relative to
// cwd" vs "relative to this run's home"); it is deliberately NOT taken
// here, and this comment states the covered surface instead of an
// unqualified promise a reader would rely on for isolation.
//
// The uploads root MUST be published under the name the settings
// service derives for it — `envKeyOf('storage','local_root')` (#4968).
// Under the CLI's old private spelling (`OS_STORAGE_ROOT`) the settings
// side saw no env value, fell back to the manifest default, and swapped
// the adapter to `./.objectstack/data/uploads` at kernel:ready — so
// `--fresh` uploads landed in the PROJECT CWD and outlived the run,
// which is the opposite of what this block promises.
let freshHome: string | undefined;
let freshDbUrl: string | undefined;
let freshStorageRoot: string | undefined;
if (flags.fresh) {
freshHome = fs.mkdtempSync(path.join(os.tmpdir(), 'objectstack-dev-'));
fs.mkdirSync(path.join(freshHome, 'data'), { recursive: true });
// The unified default filename (#6469) — the same name every command
// resolves, just anchored on this run's ephemeral OS_HOME.
freshDbUrl = `file:${path.join(freshHome, 'data', 'objectstack.db')}`;
freshStorageRoot = path.join(freshHome, 'uploads');
fs.mkdirSync(freshStorageRoot, { recursive: true });
printKV('Fresh OS_HOME', freshHome, '🧪');
const cleanup = () => {
try { fs.rmSync(freshHome!, { recursive: true, force: true }); } catch { /* noop */ }
};
process.on('exit', cleanup);
process.on('SIGINT', () => { cleanup(); process.exit(130); });
process.on('SIGTERM', () => { cleanup(); process.exit(143); });
}
// NOTE: Do NOT set NODE_ENV='development' here. Oclif's tsx-based
// TypeScript source loader (activated when NODE_ENV is 'test' or
// 'development') currently mis-handles `.json` requires inside
// CommonJS deps (e.g. dotenv's `require('../package.json')` is
// transformed as JS, then JSON.parse fails) — which causes the
// child process to report `command serve not found`. The `--dev`
// flag below already opts the serve command into dev semantics,
// and serve.ts will set NODE_ENV='development' internally before
// any runtime modules are imported.
//
// The rule is not local to this spawn: it holds for EVERY child this
// command starts, and the compile spawn above states the second reason
// (a `paths`-carrying cwd redirecting CJS packages to `.ts` source).
// That spawn carried NODE_ENV='development' for months while this one
// did not, which is exactly how `os dev` came to fail on any example app
// whose tsconfig had gained a `paths` block. Adding a third child?
// Neither reason is about serve or compile in particular — leave the
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;
// Resolve the database through the ONE shared resolution (#6469) —
// `os dev`, `os start` and `os migrate` all land on the same URL for the
// same project directory. `dev` keeps a PERSISTENT default on purpose:
// the historical serve default is `:memory:`, which silently wipes
// everything on every restart — fine for throwaway demos, but it makes
// local app-building unusable (build an app, restart, it's gone). See
// {@link resolveDevDatabase} for the priority ladder.
const resolvedDb = await resolveDevDatabase({
databaseFlag: flags.database,
freshDbUrl,
databaseDriverFlag: flags['database-driver'],
env: process.env,
cwd: process.cwd(),
// The reference's bytes are the child's to fetch; a local file the
// reference outranks must not choose this boot's datasource (as `start`).
artifactPath: artifactUrl ? undefined : artifactPath,
});
if (resolvedDb.notice) {
// Legacy-file compat-read — one loud line naming the file being read
// and how to converge on the unified default. Never an interactive
// prompt (CI-safe), never silent (#6469).
console.log(chalk.yellow(` ⚠ ${resolvedDb.notice}`));
}
// Bounded, and refused at once when the directory cannot be made (#23737).
try {
prepareDevDatabaseDirectory(resolvedDb);
} catch (error: any) {
printError(error?.message ?? String(error));
console.error(chalk.yellow(
' Point OS_HOME at a directory that can be created, or choose the database with --database.',
));
process.exit(1);
}
const effectiveDb = resolvedDb.url;
// `dev` has a resolved artifact by this point (it compiled one, or was
// handed one, or is pointing at the canonical
// `<cwd>/dist/objectstack.json`) — UNLESS `OS_ARTIFACT_URL` drives the
// boot, in which case it resolves nothing and the child resolves the
// reference, exactly as under `start` (#21501). The resolved path
// travels on the CLI's own `OS_INTERNAL_ARTIFACT_PATH`, so an
// `OS_ARTIFACT_PATH` seen by a downstream `objectstack.config.ts` means
// an operator set it; a `resolved` answer also removes an outranked
// `OS_ARTIFACT_URL` (`--artifact` over env).
const localEnv: NodeJS.ProcessEnv = {
...childEnvWithResolvedArtifact(
process.env,
artifactUrl ? { kind: 'reference' } : { kind: 'resolved', path: artifactPath, configCompiledTo },
),
OS_ENVIRONMENT_ID: environmentId,
OS_SEED_ADMIN: seedAdmin ? '1' : '0',
...(seedAdmin && flags['admin-email'] ? { OS_SEED_ADMIN_EMAIL: flags['admin-email'] } : {}),
...(seedAdmin && flags['admin-password'] ? { OS_SEED_ADMIN_PASSWORD: flags['admin-password'] } : {}),
...(freshHome ? { OS_HOME: freshHome } : {}),
...(freshStorageRoot ? { OS_STORAGE_LOCAL_ROOT: freshStorageRoot } : {}),
OS_DATABASE_URL: effectiveDb,
...(flags['database-driver'] ? { OS_DATABASE_DRIVER: flags['database-driver'] } : {}),
...(flags['database-auth-token'] ? { OS_DATABASE_AUTH_TOKEN: flags['database-auth-token'] } : {}),
...(flags['auth-secret'] ? { OS_AUTH_SECRET: flags['auth-secret'] } : {}),
};
applyFreshHomeChannel(localEnv, freshHome);
// The data key's file: the ONE answer `os start` takes too (#29934), so a
// secret saved here reads back under `os start` over the same project —
// and the file an earlier `os start` kept in the project is still read.
const keyFileNotice = await applyCryptoKeyFileChannel(localEnv, {
env: freshHome ? { ...process.env, OS_HOME: freshHome } : process.env,
cwd: process.cwd(),
hasProjectConfig: configExists,
});
if (keyFileNotice) console.log(chalk.yellow(` ⚠ ${keyFileNotice}`));
printKV('Environment ID', environmentId, '🎯');
if (artifactUrl) {
// Redacted: the reference may be a pre-signed URL whose query string IS
// the credential — the same row `start` prints for it.
const { redactArtifactUrl } = await import('@objectstack/runtime');
printKV('Artifact', `${redactArtifactUrl(artifactUrl)} (OS_ARTIFACT_URL)`, '📦');
} else {
printKV('Artifact', isRemoteArtifact(artifactPath) ? artifactPath : path.relative(process.cwd(), artifactPath), '📦');
}
printKV('Database', redactConnectionUrl(effectiveDb), '🗄️');
const binPath = process.argv[1];
// ── Serve child under restart supervision (#5148) ───────────────
// The watcher below rebuilds dist/objectstack.json, but a running
// server only PARTIALLY receives a rebuilt artifact: MetadataPlugin's
// own artifact watcher re-ingests the registry, syncs DDL + seeds for
// new objects and broadcasts the SSE HMR event — while hook bodies
// and already-registered view metadata from the compiled bundle are
// applied at boot only (#5148 measured both staying stale). Boot-time
// load is the one path that applies the whole artifact, so the
// coordinator restarts the serve child after each successful rebuild
// (nodemon-style, default-on; opt out with --no-restart).
// [ADR-0131 D10, development exception] A serve child the
// organization-ownership boot guard refused says so before it exits; the
// coordinator then asks `recover` below, which copies the development
// database, runs the ceremony on it and boots the server again — once
// per session (`utils/dev-organization-ownership-upgrade.ts`,
// `upgradeRefusedDevelopmentDatabase` above for what it prints).
let ownershipUpgrade: 'none' | 'pending' | 'attempted' = 'none';
let upgradedBoot = false;
const spawnServeChild = (info: { restartIndex: number }) => {
const child = spawn(
process.execPath,
[
binPath,
'serve',
'--dev',
...(port ? ['--port', port] : []),
// The PATHS, not the bytes: the child binds the socket, so it is
// the process that must fail when the certificate is unusable
// (#16804). One reader of the file, one owner of that refusal.
...devTlsChildArgs(tlsIntent),
...(flags.ui ? ['--ui'] : []),
...(flags.verbose ? ['--verbose'] : []),
...(flags['log-level'] ? ['--log-level', flags['log-level']] : []),
...(flags.preset ? ['--preset', flags.preset] : []),
],
// 'ipc' adds a message channel so the serve child can report the
// port it ACTUALLY bound (dev auto-shifts off a busy port). Without
// this, the parent only knows the requested port.
{ stdio: ['inherit', 'inherit', 'inherit', 'ipc'], env: localEnv },
);
// ── Learn the actually-bound port from the serve child ────────
// The child emits `{ type: 'objectstack:listening', port, url }` once
// its HTTP server is up. We surface it so the printed URL is correct
// even when the port was auto-shifted (e.g. 3000 busy → 3001).
child.on('message', (msg: any) => {
// #17329 — the hop outward. Handled first and exclusively: a settle
// announcement carries no port and has nothing to do with the block
// below. See {@link forwardSeedSettledToParent}.
if (forwardSeedSettledToParent(msg)) return;
if (isOrganizationOwnershipRequiredMessage(msg)) {
if (ownershipUpgrade === 'none') ownershipUpgrade = 'pending';
return;
}
if (msg?.type === 'objectstack:listening' && msg.port) {
const actual = String(msg.port);
if (actual !== requestedPort) {
console.log(chalk.dim(` ↪ server bound to port ${actual} (requested ${requestedPort})`));
}
if (upgradedBoot) {
// The first child to listen after the upgrade: the boot the
// developer started, so it gets the initial boot's hint below.
upgradedBoot = false;
console.log(chalk.green(' ✓ server started on the upgraded database'));
} else if (info.restartIndex > 0) {
// A restarted child is listening — the running server matches
// dist/objectstack.json again. The MCP hint below is boot
// noise on a restart, so it prints on the initial boot only.
console.log(chalk.green(' ✓ server restarted — the new build is live'));
return;
}
// ── MCP connect hint (#3167) ────────────────────────────────
// The app IS an MCP server: the dispatcher serves /api/v1/mcp
// per-request, default-on (isMcpServerEnabled). Print how a
// coding agent (Claude Code, Cursor, any MCP client) attaches so
// the "AI builds the app it's running" loop is discoverable at the
// moment it's most useful — dev boot. An opted-out deployment
// (OS_MCP_SERVER_ENABLED=false) advertises nothing, mirroring the
// connect-UI / discovery gates that follow the same switch.
if (isMcpServerEnabled()) {
// ⛔ The ACTUALLY BOUND port, never the child's listen URL: the
// origin these lines carry is resolved from the runtime's own
// precedence chain inside the printer, so the banner the child
// prints and this block cannot name two different deployments.
printMcpConnectHint({
boundPort: actual,
// ⭐ From THIS process's own flags, which are the same flags it
// forwarded to the child — so the scheme the hint prints and the
// scheme the child bound cannot part company (#16804).
boundProtocol,
});
}
}
});
return child;
};
const coordinator = new ServeRestartCoordinator({
spawnChild: spawnServeChild,
exitParent: (code) => process.exit(code),
recover: async () => {
if (ownershipUpgrade !== 'pending') return false;
ownershipUpgrade = 'attempted';
const ok = await upgradeRefusedDevelopmentDatabase({
print: (line) => console.log(line),
upgrade: async () => {
const { resolveStandaloneDatabase } = await import('@objectstack/runtime');
let sqliteFile: string | null = null;
try {
sqliteFile = resolveStandaloneDatabase({ projectRoot: process.cwd(), databaseUrl: effectiveDb }).sqliteFile;
} catch {
sqliteFile = null;
}
return upgradeDevelopmentDatabase({
binPath,
databaseUrl: effectiveDb,
sqliteFile,
env: localEnv,
cwd: process.cwd(),
announce: (line) => console.log(chalk.yellow(` ⚠ ${line}`)),
});
},
});
if (ok) upgradedBoot = true;
return ok;
},
log: (line) => {
const trimmed = line.trimStart();
if (trimmed.startsWith('✗')) console.log(chalk.red(line));
else if (trimmed.startsWith('⚠')) console.log(chalk.yellow(line));
else console.log(chalk.dim(line));
},
});
// Forward parent signals to the child (covers non-TTY parents where no
// process group delivers Ctrl-C to the child for us), and never leave
// an orphaned serve child behind whatever path ends the parent — e.g.
// --fresh's SIGINT handler calls process.exit before later SIGINT
// listeners run, but 'exit' listeners still do.
process.on('SIGINT', () => coordinator.beginShutdown('SIGINT'));
process.on('SIGTERM', () => coordinator.beginShutdown('SIGTERM'));