@sixb/cli 0.1.7 → 0.1.9

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.
package/README.md CHANGED
@@ -65,6 +65,29 @@ bun add @sixb/cli
65
65
 
66
66
  Scaffold a new project without installing the CLI first with `bun create sixb <name>`.
67
67
 
68
+ ### Development reload
69
+
70
+ `sixb dev` watches source and configuration files under the config module's directory.
71
+ Changes to ontology, actions, pipelines, other discovered definitions, shared helpers, or
72
+ configuration restart the local dev stack in a fresh process and regenerate project types.
73
+ File additions and deletions are picked up too. Custom `app/` edits use frontend HMR once
74
+ the app server is running; adding the first route starts it automatically.
75
+
76
+ Native file events trigger targeted checks. An asynchronous source scan every five seconds
77
+ recovers missed events without scanning the running frontend's files. A missed native event
78
+ can therefore take a few seconds to reload. Hidden browser tabs pause reload polling and
79
+ check again when visible; disconnected tabs back off retries until the server returns.
80
+
81
+ Backend restarts stop the old workers before starting replacements and reload connected
82
+ browser pages when the new stack is ready. In-memory state resets; persisted state remains.
83
+ Startup errors are displayed and the watcher stays alive so the next save can recover.
84
+ Generated `.sixb/` files, dependencies, build output, and non-source storage files are ignored.
85
+ Source outside the project root is not watched. Environment-file changes require restarting
86
+ `sixb dev`, because Bun loads them into the supervisor's environment at launch.
87
+ Stop the supervisor and its child with Ctrl+C.
88
+ On macOS/Linux, the dev child also enforces its own ten-second cleanup deadline if the
89
+ supervisor disappears, so a stuck startup cannot leave its process group running indefinitely.
90
+
68
91
  ## Options
69
92
 
70
93
  | Flag | Applies to | Default | Description |
@@ -184,6 +207,18 @@ cd my-project && bun install && sixb dev
184
207
  sixb init .
185
208
  ```
186
209
 
210
+ ## Production builds
211
+
212
+ `sixb build` bundles the config and all convention-discovered backend modules together. Configured
213
+ tools and discovered definitions share the same module instances. Production discovery uses this
214
+ built inventory, so the original `ontology/`, `connectors/`, and other discovery directories are
215
+ not required at startup. Rebuild to include added or changed definitions.
216
+
217
+ The runtime entry remains `.sixb/dist/sixb.config.js` (or the configured `--outdir`). Installed
218
+ package dependencies and any files your application reads at runtime must still be deployed.
219
+ Both top-level host exports and config factories are supported. Run production commands from the
220
+ deployed project root; an explicit `createSixb({ projectRoot })` must resolve to that same root.
221
+
187
222
  ## Profiles and remote commands
188
223
 
189
224
  Login validates `/api/project`, saves the profile in `~/.config/sixb/config.json`, and selects it.
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/commands/api.tsx"],"names":[],"mappings":"AAUA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,wBAAsB,MAAM,CAAC,OAAO,GAAE,UAAe,iBA6FpD"}
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/commands/api.tsx"],"names":[],"mappings":"AAUA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,wBAAsB,MAAM,CAAC,OAAO,GAAE,UAAe,iBA2FpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../../src/commands/app.tsx"],"names":[],"mappings":"AASA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,wBAAsB,MAAM,CAAC,OAAO,GAAE,UAAe,iBAyEpD"}
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../../src/commands/app.tsx"],"names":[],"mappings":"AAOA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,wBAAsB,MAAM,CAAC,OAAO,GAAE,UAAe,iBAqEpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/commands/build.tsx"],"names":[],"mappings":"AAOA,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,wBAAsB,QAAQ,CAAC,OAAO,GAAE,YAAiB,iBA6ExD"}
1
+ {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/commands/build.tsx"],"names":[],"mappings":"AAQA,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,wBAAsB,QAAQ,CAAC,OAAO,GAAE,YAAiB,iBAoExD"}
@@ -0,0 +1,14 @@
1
+ export interface DevOptions {
2
+ entry?: string;
3
+ port?: string;
4
+ host?: string;
5
+ apiPort?: string;
6
+ apiHost?: string;
7
+ apiPublicOrigin?: string;
8
+ atlasPublicOrigin?: string;
9
+ appPublicOrigin?: string;
10
+ agentTurnTimeout?: string;
11
+ concurrency?: readonly string[];
12
+ }
13
+ export declare function runDevRuntime(options?: DevOptions): Promise<void>;
14
+ //# sourceMappingURL=dev-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-runner.d.ts","sourceRoot":"","sources":["../../src/commands/dev-runner.tsx"],"names":[],"mappings":"AAYA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAChC;AAED,wBAAsB,aAAa,CAAC,OAAO,GAAE,UAAe,iBA2J3D"}
@@ -1,14 +1,4 @@
1
- export interface DevOptions {
2
- entry?: string;
3
- port?: string;
4
- host?: string;
5
- apiPort?: string;
6
- apiHost?: string;
7
- apiPublicOrigin?: string;
8
- atlasPublicOrigin?: string;
9
- appPublicOrigin?: string;
10
- agentTurnTimeout?: string;
11
- concurrency?: readonly string[];
12
- }
1
+ import type { DevOptions } from "./dev-runner";
2
+ export type { DevOptions } from "./dev-runner";
13
3
  export declare function runDev(options?: DevOptions): Promise<void>;
14
4
  //# sourceMappingURL=dev.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../../src/commands/dev.tsx"],"names":[],"mappings":"AAYA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAChC;AAED,wBAAsB,MAAM,CAAC,OAAO,GAAE,UAAe,iBAyIpD"}
1
+ {"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../../src/commands/dev.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAE9C,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAE9C,wBAAsB,MAAM,CAAC,OAAO,GAAE,UAAe,iBA2BpD"}
@@ -0,0 +1,3 @@
1
+ /** Bundle a project, including modules reachable only through convention-based discovery. */
2
+ export declare function buildRuntime(entry: string, outdir: string): Promise<Bun.BuildOutput>;
3
+ //# sourceMappingURL=build-runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-runtime.d.ts","sourceRoot":"","sources":["../../src/lib/build-runtime.ts"],"names":[],"mappings":"AAIA,6FAA6F;AAC7F,wBAAsB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAmC1F"}
@@ -0,0 +1,4 @@
1
+ import type { DevOptions } from "../commands/dev-runner";
2
+ /** The parent never imports project modules: every generation gets a fresh module graph. */
3
+ export declare function runDevSupervisor(options: DevOptions): Promise<void>;
4
+ //# sourceMappingURL=dev-supervisor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-supervisor.d.ts","sourceRoot":"","sources":["../../src/lib/dev-supervisor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAGxD,4FAA4F;AAC5F,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAmKzE"}
@@ -0,0 +1,7 @@
1
+ /** Targeted native checks, with a bounded-concurrency async scan for missed events. */
2
+ export declare function watchDevSource(root: string, hasCustomApp: () => boolean, onChange: (path: string) => void, onError: (error: unknown) => void): {
3
+ ready: Promise<void>;
4
+ refresh: () => Promise<void>;
5
+ close(): Promise<void>;
6
+ };
7
+ //# sourceMappingURL=dev-watch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-watch.d.ts","sourceRoot":"","sources":["../../src/lib/dev-watch.ts"],"names":[],"mappings":"AAqCA,uFAAuF;AACvF,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,YAAY,EAAE,MAAM,OAAO,EAC3B,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAChC,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI;;;;EA6JlC"}
@@ -25,5 +25,6 @@ export declare function loadProductionSixb(options: ProductionRuntimeOptions): P
25
25
  export declare function resolveProductionPaths(entry: string): Promise<ProductionPaths>;
26
26
  export declare function resolveProjectRoot(entry: string): string;
27
27
  export declare function builtAppOutdir(buildOutdir: string): string;
28
+ export declare function hasBuiltCustomApp(appOutdir: string): Promise<boolean>;
28
29
  export declare function builtAtlasOutdir(buildOutdir: string): string;
29
30
  //# sourceMappingURL=production.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"production.d.ts","sourceRoot":"","sources":["../../src/lib/production.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,cAAc,EAAqB,MAAM,YAAY,CAAA;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAGxD,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,wBAAyB,SAAQ,mBAAmB;IACnE;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;CAC9B;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;CAC7B;AAED,wBAAsB,mBAAmB,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,MAAM,CAAC,CAU5F;AAED,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,cAAc,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CAY5F;AAED,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAepF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAUxD;AAED,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE5D"}
1
+ {"version":3,"file":"production.d.ts","sourceRoot":"","sources":["../../src/lib/production.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,cAAc,EAAqB,MAAM,YAAY,CAAA;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAGxD,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,wBAAyB,SAAQ,mBAAmB;IACnE;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;CAC9B;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;CAC7B;AAED,wBAAsB,mBAAmB,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,MAAM,CAAC,CAU5F;AAED,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,cAAc,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CAY5F;AAED,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAepF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAUxD;AAED,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED,wBAAsB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAS3E;AAED,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE5D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sixb/cli",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Command-line interface for Sixb projects",
5
5
  "keywords": [
6
6
  "sixb",
@@ -25,25 +25,25 @@
25
25
  "build": "bun ../../scripts/build-package.ts",
26
26
  "typecheck": "tsc --noEmit",
27
27
  "test": "bun test",
28
- "test:e2e": "bun test ./tests/build.e2e.ts && bun test ./tests/prod-roles.e2e.ts && bun test ./tests/worker-group.e2e.ts",
28
+ "test:e2e": "bun test ./tests/build.e2e.ts && bun test ./tests/prod-roles.e2e.ts && bun test ./tests/worker-group.e2e.ts && bun test ./tests/dev-reload.e2e.ts",
29
29
  "prepack": "bun run build"
30
30
  },
31
31
  "dependencies": {
32
- "@sixb/action-worker": "0.1.7",
33
- "@sixb/agent-worker": "0.1.7",
34
- "@sixb/app": "^0.1.5",
35
- "@sixb/atlas": "^0.1.6",
36
- "@sixb/client": "^0.1.7",
37
- "@sixb/core": "0.1.7",
38
- "@sixb/cli-core": "^0.1.4",
39
- "@sixb/orchestrator": "0.1.7",
40
- "@sixb/pipeline-worker": "0.1.7",
41
- "@sixb/projection-worker": "0.1.7",
42
- "@sixb/rules-worker": "0.1.7",
43
- "@sixb/server": "0.1.7",
44
- "@sixb/sync-worker": "0.1.7",
45
- "@sixb/workflow-worker": "0.1.7",
46
- "create-sixb": "^0.1.2",
32
+ "@sixb/action-worker": "0.1.9",
33
+ "@sixb/agent-worker": "0.1.9",
34
+ "@sixb/app": "^0.1.7",
35
+ "@sixb/atlas": "^0.1.8",
36
+ "@sixb/client": "^0.1.9",
37
+ "@sixb/core": "0.1.9",
38
+ "@sixb/cli-core": "^0.1.5",
39
+ "@sixb/orchestrator": "0.1.9",
40
+ "@sixb/pipeline-worker": "0.1.9",
41
+ "@sixb/projection-worker": "0.1.9",
42
+ "@sixb/rules-worker": "0.1.9",
43
+ "@sixb/server": "0.1.9",
44
+ "@sixb/sync-worker": "0.1.9",
45
+ "@sixb/workflow-worker": "0.1.9",
46
+ "create-sixb": "^0.1.3",
47
47
  "ink": "^6.0.0",
48
48
  "react": "^19.0.0",
49
49
  "react-devtools-core": "^4.19.1"
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "license": "MIT",
57
57
  "engines": {
58
- "bun": ">=1.3.0"
58
+ "bun": ">=1.4.2"
59
59
  },
60
60
  "publishConfig": {
61
61
  "access": "public"
@@ -3,7 +3,7 @@ import { resolve } from "node:path"
3
3
  import { createSixbServer, type SixbServer } from "@sixb/server"
4
4
  import { apiDocsUrl, apiEventsUrl, apiUrl, resolveBrowserTopology } from "../lib/browser-topology"
5
5
  import type { LoadedSixbHost } from "../lib/loadSixb"
6
- import { builtAppOutdir, loadProductionSixb } from "../lib/production"
6
+ import { builtAppOutdir, hasBuiltCustomApp, loadProductionSixb } from "../lib/production"
7
7
  import { runUntilSignal, stopQuietly, stopSixbProviders } from "../lib/runtime"
8
8
  import { migrateStorageForRole } from "../lib/storage-migration"
9
9
  import { LoadingView, RoleView, renderCliError, renderPersistent } from "../ui"
@@ -49,9 +49,7 @@ export async function runApi(options: ApiOptions = {}) {
49
49
  })
50
50
 
51
51
  const appOutdir = builtAppOutdir(loaded.buildOutdir)
52
- const hasBuiltCustomApp = await stat(resolve(appOutdir, "index.html"))
53
- .then(() => true)
54
- .catch(() => false)
52
+ const hasCustomApp = await hasBuiltCustomApp(appOutdir)
55
53
  const authExperienceOutdir = resolve(appOutdir, "auth")
56
54
  const hasAuthExperience = await stat(resolve(authExperienceOutdir, "index.html"))
57
55
  .then(() => true)
@@ -65,7 +63,7 @@ export async function runApi(options: ApiOptions = {}) {
65
63
  apiPublicOrigin: options.apiPublicOrigin,
66
64
  atlasPublicOrigin: options.atlasPublicOrigin,
67
65
  appPublicOrigin: options.appPublicOrigin,
68
- hasCustomApp: hasBuiltCustomApp,
66
+ hasCustomApp,
69
67
  })
70
68
 
71
69
  server = createSixbServer({
@@ -1,9 +1,7 @@
1
- import { stat } from "node:fs/promises"
2
- import { resolve } from "node:path"
3
1
  import { type CustomAppDevServer, createCustomApp } from "@sixb/app"
4
2
  import { resolveBrowserTopology, servedUrl } from "../lib/browser-topology"
5
3
  import type { LoadedSixbHost } from "../lib/loadSixb"
6
- import { builtAppOutdir, loadProductionSixb } from "../lib/production"
4
+ import { builtAppOutdir, hasBuiltCustomApp, loadProductionSixb } from "../lib/production"
7
5
  import { runUntilSignal, stopQuietly, stopSixbProviders } from "../lib/runtime"
8
6
  import { LoadingView, RoleView, renderCliError, renderPersistent } from "../ui"
9
7
 
@@ -28,11 +26,7 @@ export async function runApp(options: AppOptions = {}) {
28
26
 
29
27
  try {
30
28
  const appOutdir = builtAppOutdir(loaded.buildOutdir)
31
- const hasBuiltCustomApp = await stat(resolve(appOutdir, "index.html"))
32
- .then(() => true)
33
- .catch(() => false)
34
-
35
- if (!hasBuiltCustomApp) {
29
+ if (!(await hasBuiltCustomApp(appOutdir))) {
36
30
  throw new Error(
37
31
  `[SixbCustomApp] No built app found in ${appOutdir}. Run \`sixb build\` before \`sixb app\`.`
38
32
  )
@@ -2,6 +2,7 @@ import { mkdir } from "node:fs/promises"
2
2
  import { dirname, join, resolve } from "node:path"
3
3
  import { createCustomApp } from "@sixb/app"
4
4
  import { buildAtlasAssets } from "@sixb/atlas"
5
+ import { buildRuntime } from "../lib/build-runtime"
5
6
  import { generateProjectTypes } from "../lib/typegen"
6
7
  import { BuildView, ErrorView, renderStatic } from "../ui"
7
8
 
@@ -18,16 +19,7 @@ export async function runBuild(options: BuildOptions = {}) {
18
19
  await generateProjectTypes({ entry })
19
20
  await mkdir(outdir, { recursive: true })
20
21
 
21
- // Build sixb.config.ts
22
- const result = await Bun.build({
23
- entrypoints: [entry],
24
- outdir,
25
- target: "bun",
26
- sourcemap: "external",
27
- minify: false,
28
- packages: "external",
29
- external: ["@sixb/*"],
30
- })
22
+ const result = await buildRuntime(entry, outdir)
31
23
 
32
24
  if (!result.success) {
33
25
  const details = result.logs.map(String)
@@ -0,0 +1,181 @@
1
+ import { dirname, resolve } from "node:path"
2
+ import { type CustomAppDevServer, createCustomApp } from "@sixb/app"
3
+ import { type AtlasAppServer, createAtlasApp } from "@sixb/atlas"
4
+ import { createSixbServer, type SixbServer } from "@sixb/server"
5
+ import { resolveAgentTurnTimeoutMs } from "../lib/agent-turn-timeout"
6
+ import { apiDocsUrl, apiEventsUrl, apiUrl, resolveBrowserTopology } from "../lib/browser-topology"
7
+ import { type LoadedSixbHost, loadSixbFromEntry } from "../lib/loadSixb"
8
+ import { startSixbRuntime, stopQuietly, stopSixbProviders } from "../lib/runtime"
9
+ import { generateProjectTypes } from "../lib/typegen"
10
+ import { resolveWorkerConcurrency } from "../lib/worker-concurrency"
11
+ import { DevView, LoadingView, renderCliError, renderPersistent } from "../ui"
12
+
13
+ export interface DevOptions {
14
+ entry?: string
15
+ port?: string
16
+ host?: string
17
+ apiPort?: string
18
+ apiHost?: string
19
+ apiPublicOrigin?: string
20
+ atlasPublicOrigin?: string
21
+ appPublicOrigin?: string
22
+ agentTurnTimeout?: string
23
+ concurrency?: readonly string[]
24
+ }
25
+
26
+ export async function runDevRuntime(options: DevOptions = {}) {
27
+ process.env.NODE_ENV = "development"
28
+
29
+ const agentTurnTimeoutMs = resolveAgentTurnTimeoutMs(options.agentTurnTimeout)
30
+ const workerConcurrency = resolveWorkerConcurrency(options.concurrency)
31
+ const entry = resolve(options.entry ?? "sixb.config.ts")
32
+
33
+ const app = renderPersistent(
34
+ <LoadingView title="Starting sixb" subtitle={entry} status="Loading runtime" />
35
+ )
36
+
37
+ let server: SixbServer | null = null
38
+ let atlasServer: AtlasAppServer | null = null
39
+ let customAppServer: CustomAppDevServer | null = null
40
+ let sixb: LoadedSixbHost | null = null
41
+ let runtime: Awaited<ReturnType<typeof startSixbRuntime>> | null = null
42
+ let runtimeOwnsProviders = false
43
+ const abort = new AbortController()
44
+ const stopped = new Promise<void>((resolve) => {
45
+ abort.signal.addEventListener("abort", () => resolve(), { once: true })
46
+ })
47
+ const requestShutdown = () => abort.abort()
48
+ process.on("SIGINT", requestShutdown)
49
+ process.on("SIGTERM", requestShutdown)
50
+
51
+ try {
52
+ await generateProjectTypes({ entry })
53
+ abort.signal.throwIfAborted()
54
+ const host: LoadedSixbHost = await loadSixbFromEntry(entry)
55
+ sixb = host
56
+ abort.signal.throwIfAborted()
57
+ const projectRoot = dirname(resolve(entry))
58
+
59
+ const customAppProbe = await createCustomApp({ rootDir: projectRoot })
60
+ const hasCustomApp = await customAppProbe.hasRoutes()
61
+ const topology = resolveBrowserTopology({
62
+ role: "dev",
63
+ host: options.host,
64
+ apiHost: options.apiHost,
65
+ port: options.port,
66
+ apiPort: options.apiPort,
67
+ apiPublicOrigin: options.apiPublicOrigin,
68
+ atlasPublicOrigin: options.atlasPublicOrigin,
69
+ appPublicOrigin: options.appPublicOrigin,
70
+ hasCustomApp,
71
+ })
72
+ const customApp = await createCustomApp({
73
+ rootDir: projectRoot,
74
+ apiBaseUrl: topology.apiPublicOrigin,
75
+ audience: "app",
76
+ authEnabled: host.auth.isEnabled(),
77
+ })
78
+ const authExperience = hasCustomApp
79
+ ? ((await customApp.prepareAuthExperience()) ?? {
80
+ outdir: resolve(projectRoot, ".sixb", "generated", "auth"),
81
+ })
82
+ : null
83
+
84
+ abort.signal.throwIfAborted()
85
+ runtimeOwnsProviders = true
86
+ runtime = await startSixbRuntime(host, {
87
+ cohostWorkers: true,
88
+ agentApiBaseUrl: topology.apiPublicOrigin,
89
+ agentTurnTimeoutMs,
90
+ workerConcurrency,
91
+ })
92
+ abort.signal.throwIfAborted()
93
+ const authEnabled = host.auth.isEnabled()
94
+
95
+ app.rerender(<LoadingView title="Starting sixb" subtitle={entry} status="Starting server" />)
96
+
97
+ server = createSixbServer({
98
+ host: sixb,
99
+ port: topology.apiPort,
100
+ hostname: topology.apiHost,
101
+ quiet: true,
102
+ browser: {
103
+ publicOrigin: topology.apiPublicOrigin,
104
+ allowedOrigins: topology.allowedBrowserOrigins,
105
+ },
106
+ ...(authExperience ? { authExperience } : {}),
107
+ })
108
+ await server.start()
109
+ abort.signal.throwIfAborted()
110
+
111
+ const atlas = createAtlasApp({
112
+ apiBaseUrl: topology.apiPublicOrigin,
113
+ audience: "atlas",
114
+ authEnabled,
115
+ })
116
+ atlasServer = await atlas.start({
117
+ host: topology.host,
118
+ port: topology.atlasPort,
119
+ development: true,
120
+ })
121
+ abort.signal.throwIfAborted()
122
+
123
+ let appUrl: string | null = null
124
+ if (hasCustomApp) {
125
+ app.rerender(
126
+ <LoadingView title="Starting sixb" subtitle={entry} status="Starting custom app" />
127
+ )
128
+
129
+ customAppServer = await customApp.dev({
130
+ host: topology.host,
131
+ port: topology.appPort,
132
+ })
133
+ appUrl = topology.appPublicOrigin
134
+ }
135
+ abort.signal.throwIfAborted()
136
+
137
+ app.rerender(
138
+ <DevView
139
+ name={sixb.id}
140
+ apiUrl={apiUrl(topology)}
141
+ apiDocsUrl={apiDocsUrl(topology)}
142
+ wsUrl={apiEventsUrl(topology)}
143
+ uiUrl={topology.atlasPublicOrigin}
144
+ appUrl={appUrl}
145
+ workers={[
146
+ { type: "action", worker: runtime.actionWorker },
147
+ { type: "agent", worker: runtime.agentWorker },
148
+ { type: "projection", worker: runtime.projectionWorker },
149
+ { type: "pipeline", worker: runtime.pipelineWorker },
150
+ { type: "workflow", worker: runtime.workflowWorker },
151
+ { type: "sync", worker: runtime.syncWorker },
152
+ ].flatMap(({ type, worker }) =>
153
+ worker ? [{ type, concurrency: worker.concurrency }] : []
154
+ )}
155
+ warnings={runtime.warnings}
156
+ />
157
+ )
158
+
159
+ process.env.SIXB_DEV_READY = "1"
160
+ process.send?.({ type: "ready", hasCustomApp })
161
+
162
+ await Promise.race([stopped, runtime.waitForWorkerFailure()])
163
+ } catch (error) {
164
+ if (!abort.signal.aborted) {
165
+ process.send?.({ type: "startup-error" })
166
+ app.unmount()
167
+ await renderCliError(error)
168
+ process.exitCode = 1
169
+ }
170
+ } finally {
171
+ process.env.SIXB_DEV_READY = ""
172
+ app.unmount()
173
+ await stopQuietly(() => customAppServer?.stop() ?? Promise.resolve())
174
+ await stopQuietly(() => atlasServer?.stop() ?? Promise.resolve())
175
+ await stopQuietly(() => server?.stop() ?? Promise.resolve())
176
+ await stopQuietly(() => runtime?.stop() ?? Promise.resolve())
177
+ if (sixb && !runtimeOwnsProviders) await stopSixbProviders(sixb)
178
+ process.off("SIGINT", requestShutdown)
179
+ process.off("SIGTERM", requestShutdown)
180
+ }
181
+ }
@@ -1,163 +1,33 @@
1
- import { dirname, resolve } from "node:path"
2
- import { type CustomAppDevServer, createCustomApp } from "@sixb/app"
3
- import { type AtlasAppServer, createAtlasApp } from "@sixb/atlas"
4
- import { createSixbServer, type SixbServer } from "@sixb/server"
5
- import { resolveAgentTurnTimeoutMs } from "../lib/agent-turn-timeout"
6
- import { apiDocsUrl, apiEventsUrl, apiUrl, resolveBrowserTopology } from "../lib/browser-topology"
7
- import { type LoadedSixbHost, loadSixbFromEntry } from "../lib/loadSixb"
8
- import { runUntilSignal, startSixbRuntime, stopQuietly } from "../lib/runtime"
9
- import { generateProjectTypes } from "../lib/typegen"
10
- import { resolveWorkerConcurrency } from "../lib/worker-concurrency"
11
- import { DevView, LoadingView, renderCliError, renderPersistent } from "../ui"
1
+ import { runDevSupervisor } from "../lib/dev-supervisor"
2
+ import type { DevOptions } from "./dev-runner"
12
3
 
13
- export interface DevOptions {
14
- entry?: string
15
- port?: string
16
- host?: string
17
- apiPort?: string
18
- apiHost?: string
19
- apiPublicOrigin?: string
20
- atlasPublicOrigin?: string
21
- appPublicOrigin?: string
22
- agentTurnTimeout?: string
23
- concurrency?: readonly string[]
24
- }
4
+ export type { DevOptions } from "./dev-runner"
25
5
 
26
6
  export async function runDev(options: DevOptions = {}) {
27
- process.env.NODE_ENV = "development"
28
-
29
- const agentTurnTimeoutMs = resolveAgentTurnTimeoutMs(options.agentTurnTimeout)
30
- const workerConcurrency = resolveWorkerConcurrency(options.concurrency)
31
- const entry = resolve(options.entry ?? "sixb.config.ts")
32
-
33
- const app = renderPersistent(
34
- <LoadingView title="Starting sixb" subtitle={entry} status="Loading runtime" />
35
- )
36
-
37
- let server: SixbServer | null = null
38
- let atlasServer: AtlasAppServer | null = null
39
- let customAppServer: CustomAppDevServer | null = null
40
- let sixb: LoadedSixbHost | null = null
41
- let runtime: Awaited<ReturnType<typeof startSixbRuntime>> | null = null
42
-
43
- try {
44
- await generateProjectTypes({ entry })
45
- const host: LoadedSixbHost = await loadSixbFromEntry(entry)
46
- sixb = host
47
- const projectRoot = dirname(resolve(entry))
48
-
49
- const customAppProbe = await createCustomApp({ rootDir: projectRoot })
50
- const hasCustomApp = await customAppProbe.hasRoutes()
51
- const topology = resolveBrowserTopology({
52
- role: "dev",
53
- host: options.host,
54
- apiHost: options.apiHost,
55
- port: options.port,
56
- apiPort: options.apiPort,
57
- apiPublicOrigin: options.apiPublicOrigin,
58
- atlasPublicOrigin: options.atlasPublicOrigin,
59
- appPublicOrigin: options.appPublicOrigin,
60
- hasCustomApp,
61
- })
62
- const customApp = await createCustomApp({
63
- rootDir: projectRoot,
64
- apiBaseUrl: topology.apiPublicOrigin,
65
- audience: "app",
66
- authEnabled: host.auth.isEnabled(),
67
- })
68
- const authExperience = hasCustomApp
69
- ? ((await customApp.prepareAuthExperience()) ?? {
70
- outdir: resolve(projectRoot, ".sixb", "generated", "auth"),
71
- })
72
- : null
73
-
74
- runtime = await startSixbRuntime(host, {
75
- cohostWorkers: true,
76
- agentApiBaseUrl: topology.apiPublicOrigin,
77
- agentTurnTimeoutMs,
78
- workerConcurrency,
79
- })
80
- const authEnabled = host.auth.isEnabled()
81
-
82
- app.rerender(<LoadingView title="Starting sixb" subtitle={entry} status="Starting server" />)
83
-
84
- server = createSixbServer({
85
- host: sixb,
86
- port: topology.apiPort,
87
- hostname: topology.apiHost,
88
- quiet: true,
89
- browser: {
90
- publicOrigin: topology.apiPublicOrigin,
91
- allowedOrigins: topology.allowedBrowserOrigins,
92
- },
93
- ...(authExperience ? { authExperience } : {}),
94
- })
95
- await server.start()
96
-
97
- const atlas = createAtlasApp({
98
- apiBaseUrl: topology.apiPublicOrigin,
99
- audience: "atlas",
100
- authEnabled,
101
- })
102
- atlasServer = await atlas.start({
103
- host: topology.host,
104
- port: topology.atlasPort,
105
- development: true,
106
- })
107
-
108
- let appUrl: string | null = null
109
- if (hasCustomApp) {
110
- app.rerender(
111
- <LoadingView title="Starting sixb" subtitle={entry} status="Starting custom app" />
112
- )
113
-
114
- customAppServer = await customApp.dev({
115
- host: topology.host,
116
- port: topology.appPort,
117
- })
118
- appUrl = topology.appPublicOrigin
7
+ if (process.env.SIXB_DEV_CHILD === "1" && process.send) {
8
+ // The parent cannot enforce its deadline after it dies. Arm our own before
9
+ // importing the runner so a stuck import/startup also has a shutdown bound.
10
+ let deadline: ReturnType<typeof setTimeout> | undefined
11
+ const forceExit = () => {
12
+ if (process.platform !== "win32") process.kill(-process.pid, "SIGKILL")
13
+ else process.exit(1)
119
14
  }
120
-
121
- app.rerender(
122
- <DevView
123
- name={sixb.id}
124
- apiUrl={apiUrl(topology)}
125
- apiDocsUrl={apiDocsUrl(topology)}
126
- wsUrl={apiEventsUrl(topology)}
127
- uiUrl={topology.atlasPublicOrigin}
128
- appUrl={appUrl}
129
- workers={[
130
- { type: "action", worker: runtime.actionWorker },
131
- { type: "agent", worker: runtime.agentWorker },
132
- { type: "projection", worker: runtime.projectionWorker },
133
- { type: "pipeline", worker: runtime.pipelineWorker },
134
- { type: "workflow", worker: runtime.workflowWorker },
135
- { type: "sync", worker: runtime.syncWorker },
136
- ].flatMap(({ type, worker }) =>
137
- worker ? [{ type, concurrency: worker.concurrency }] : []
138
- )}
139
- warnings={runtime.warnings}
140
- />
141
- )
142
-
143
- await Promise.race([
144
- runUntilSignal(async () => {
145
- app.unmount()
146
- console.log("\nShutting down...")
147
- await stopQuietly(() => customAppServer?.stop() ?? Promise.resolve())
148
- await stopQuietly(() => atlasServer?.stop() ?? Promise.resolve())
149
- await stopQuietly(() => server?.stop() ?? Promise.resolve())
150
- await stopQuietly(() => runtime?.stop() ?? Promise.resolve())
151
- }),
152
- runtime.waitForWorkerFailure(),
153
- ])
154
- } catch (error) {
155
- app.unmount()
156
- await stopQuietly(() => customAppServer?.stop() ?? Promise.resolve())
157
- await stopQuietly(() => atlasServer?.stop() ?? Promise.resolve())
158
- await stopQuietly(() => server?.stop() ?? Promise.resolve())
159
- await stopQuietly(() => runtime?.stop() ?? Promise.resolve())
160
- await renderCliError(error)
161
- process.exit(1)
15
+ const disconnected = () => {
16
+ deadline ??= setTimeout(forceExit, 10_000)
17
+ process.kill(process.pid, "SIGTERM")
18
+ }
19
+ process.once("disconnect", disconnected)
20
+ try {
21
+ const { runDevRuntime } = await import("./dev-runner")
22
+ await runDevRuntime(options)
23
+ } finally {
24
+ process.off("disconnect", disconnected)
25
+ clearTimeout(deadline)
26
+ // Graceful cleanup can finish while unowned compiler/sandbox descendants
27
+ // remain. With no parent, this process must reap its isolated group itself.
28
+ if (!process.connected) forceExit()
29
+ }
30
+ process.exit(process.exitCode ?? 0)
162
31
  }
32
+ await runDevSupervisor(options)
163
33
  }
package/src/index.tsx CHANGED
@@ -21,7 +21,7 @@ const args = process.argv.slice(2)
21
21
  * `bun install` only warns about `engines`, so without this check an older Bun fails later on
22
22
  * whichever API it happens to be missing, far from the cause.
23
23
  */
24
- const MINIMUM_BUN_VERSION = "1.3.0"
24
+ const MINIMUM_BUN_VERSION = "1.4.2"
25
25
 
26
26
  assertSupportedBunVersion()
27
27
 
@@ -0,0 +1,41 @@
1
+ import { mkdir, writeFile } from "node:fs/promises"
2
+ import { basename, dirname, join, resolve } from "node:path"
3
+ import { listProjectModules } from "@sixb/core/internal/bootstrap"
4
+
5
+ /** Bundle a project, including modules reachable only through convention-based discovery. */
6
+ export async function buildRuntime(entry: string, outdir: string): Promise<Bun.BuildOutput> {
7
+ const projectRoot = dirname(entry)
8
+ const modules = await listProjectModules(projectRoot)
9
+ const generatedEntry = join(projectRoot, ".sixb", "build", "backend", basename(entry))
10
+ const imports = modules.map(
11
+ (module) =>
12
+ `{ path: ${JSON.stringify(module.path)}, kind: ${JSON.stringify(module.kind)}, ` +
13
+ `load: () => import(${JSON.stringify(resolve(projectRoot, module.path))}) }`
14
+ )
15
+
16
+ await mkdir(dirname(generatedEntry), { recursive: true })
17
+ await writeFile(
18
+ generatedEntry,
19
+ `import { withProjectModules } from "@sixb/core/internal/bootstrap"
20
+
21
+ const projectRoot = process.cwd()
22
+ const modules = [${imports.join(",\n")}]
23
+ const config = await withProjectModules(projectRoot, modules, () => import(${JSON.stringify(entry)}))
24
+ const candidate = config.sixb ?? config.default
25
+ export const sixb = typeof candidate === "function"
26
+ ? () => withProjectModules(projectRoot, modules, candidate)
27
+ : candidate
28
+ export default sixb
29
+ `
30
+ )
31
+
32
+ return Bun.build({
33
+ entrypoints: [generatedEntry],
34
+ outdir,
35
+ target: "bun",
36
+ sourcemap: "external",
37
+ minify: false,
38
+ packages: "external",
39
+ external: ["@sixb/*"],
40
+ })
41
+ }
@@ -0,0 +1,170 @@
1
+ import { spawn } from "node:child_process"
2
+ import { dirname, resolve } from "node:path"
3
+ import type { DevOptions } from "../commands/dev-runner"
4
+ import { watchDevSource } from "./dev-watch"
5
+
6
+ /** The parent never imports project modules: every generation gets a fresh module graph. */
7
+ export async function runDevSupervisor(options: DevOptions): Promise<void> {
8
+ const root = dirname(resolve(options.entry ?? "sixb.config.ts"))
9
+ let child: { process: ReturnType<typeof spawn>; exited: Promise<number | null> } | null = null
10
+ let stopping = false
11
+ let restarting = false
12
+ let pending = false
13
+ let hasCustomApp = false
14
+ let started = false
15
+ let timer: ReturnType<typeof setTimeout> | undefined
16
+ let startupTimer: ReturnType<typeof setTimeout> | undefined
17
+ let complete!: () => void
18
+ const finished = new Promise<void>((resolve) => {
19
+ complete = resolve
20
+ })
21
+ function terminate(current: NonNullable<typeof child>, signal: NodeJS.Signals) {
22
+ try {
23
+ if (process.platform !== "win32" && current.process.pid) {
24
+ process.kill(-current.process.pid, signal)
25
+ } else {
26
+ current.process.kill(signal)
27
+ }
28
+ } catch (error) {
29
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ESRCH") {
30
+ throw error
31
+ }
32
+ }
33
+ }
34
+
35
+ async function stopChild() {
36
+ clearTimeout(startupTimer)
37
+ const current = child
38
+ if (!current) return
39
+ // Give the runtime ownership of graceful shutdown. Kill the isolated process group
40
+ // only on the deadline (or after exit) to reap any compiler/sandbox descendants too.
41
+ current.process.kill("SIGTERM")
42
+ const deadline = setTimeout(() => {
43
+ console.error("[SixbDev] Shutdown timed out; terminating the dev process.")
44
+ terminate(current, "SIGKILL")
45
+ }, 10_000)
46
+ try {
47
+ await current.exited
48
+ } finally {
49
+ clearTimeout(deadline)
50
+ if (child === current) child = null
51
+ }
52
+ }
53
+
54
+ async function restart() {
55
+ if (stopping || restarting) return
56
+ restarting = true
57
+ try {
58
+ while (pending && !stopping) {
59
+ await stopChild()
60
+ if (stopping) break
61
+ hasCustomApp = false
62
+ if (started) await watcher.refresh()
63
+ else await watcher.ready
64
+ if (stopping) break
65
+ started = true
66
+ // All saves before this spawn are already in its fresh module graph.
67
+ pending = false
68
+ clearTimeout(timer)
69
+ const proc = spawn(process.execPath, [...process.execArgv, ...process.argv.slice(1)], {
70
+ env: {
71
+ ...process.env,
72
+ SIXB_DEV_CHILD: "1",
73
+ SIXB_DEV_GENERATION: crypto.randomUUID(),
74
+ SIXB_DEV_READY: "",
75
+ },
76
+ detached: process.platform !== "win32",
77
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
78
+ })
79
+ const current = {
80
+ process: proc,
81
+ exited: new Promise<number | null>((resolve, reject) => {
82
+ proc.once("exit", resolve)
83
+ proc.once("error", reject)
84
+ }),
85
+ }
86
+ proc.on("message", (message: unknown) => {
87
+ if (child !== current || !message || typeof message !== "object") return
88
+ if ("type" in message && message.type === "ready") {
89
+ clearTimeout(startupTimer)
90
+ hasCustomApp = "hasCustomApp" in message && message.hasCustomApp === true
91
+ console.log(`[SixbDev] Ready (pid ${proc.pid}). Watching ${root}`)
92
+ } else if ("type" in message && message.type === "startup-error") {
93
+ hasCustomApp = false
94
+ }
95
+ })
96
+ child = current
97
+ startupTimer = setTimeout(() => {
98
+ if (child === current) {
99
+ console.error("[SixbDev] Startup timed out. Edit a source file to retry.")
100
+ terminate(current, "SIGKILL")
101
+ }
102
+ }, 60_000)
103
+ void current.exited
104
+ .then((code) => {
105
+ terminate(current, "SIGKILL")
106
+ if (child !== current) return
107
+ clearTimeout(startupTimer)
108
+ child = null
109
+ hasCustomApp = false
110
+ if (!stopping && !restarting) {
111
+ console.error(`[SixbDev] Dev process exited (${code}). Waiting for source changes.`)
112
+ }
113
+ })
114
+ .catch(fail)
115
+ }
116
+ } finally {
117
+ restarting = false
118
+ }
119
+ }
120
+
121
+ const watcher = watchDevSource(
122
+ root,
123
+ () => hasCustomApp,
124
+ (filename) => {
125
+ if (stopping) return
126
+ pending = true
127
+ clearTimeout(timer)
128
+ timer = setTimeout(() => {
129
+ console.log(`[SixbDev] Source changed${filename ? `: ${filename}` : ""}. Restarting…`)
130
+ void restart().catch(fail)
131
+ }, 150)
132
+ },
133
+ fail
134
+ )
135
+
136
+ async function shutdown() {
137
+ if (stopping) return
138
+ stopping = true
139
+ clearTimeout(timer)
140
+ try {
141
+ await watcher.close()
142
+ await stopChild()
143
+ } finally {
144
+ complete()
145
+ }
146
+ }
147
+
148
+ function fail(error: unknown) {
149
+ console.error("[SixbDev]", error)
150
+ process.exitCode = 1
151
+ void shutdown().catch((shutdownError) =>
152
+ console.error("[SixbDev] Shutdown failed:", shutdownError)
153
+ )
154
+ }
155
+
156
+ const requestShutdown = () => {
157
+ void shutdown().catch(fail)
158
+ }
159
+ process.on("SIGINT", requestShutdown)
160
+ process.on("SIGTERM", requestShutdown)
161
+ try {
162
+ pending = true
163
+ await restart()
164
+ await finished
165
+ } finally {
166
+ process.off("SIGINT", requestShutdown)
167
+ process.off("SIGTERM", requestShutdown)
168
+ await shutdown()
169
+ }
170
+ }
@@ -0,0 +1,200 @@
1
+ import { type Dirent, watch } from "node:fs"
2
+ import { lstat, readdir } from "node:fs/promises"
3
+ import { join, resolve, sep } from "node:path"
4
+
5
+ const ignoredDirectories = new Set([
6
+ ".sixb",
7
+ ".git",
8
+ "node_modules",
9
+ "dist",
10
+ "build",
11
+ "coverage",
12
+ ".next",
13
+ ".local",
14
+ ])
15
+ const isAppSource = (path: string) => path.startsWith(`app${sep}`)
16
+ const isSource = (path: string) =>
17
+ /\.(?:[cm]?[jt]sx?|json|ya?ml|toml|css)$/.test(path) || path === "bun.lock"
18
+ const ignored = (path: string) => path.split(sep).some((part) => ignoredDirectories.has(part))
19
+
20
+ function missing(error: unknown): boolean {
21
+ return (
22
+ !!error &&
23
+ typeof error === "object" &&
24
+ "code" in error &&
25
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
26
+ )
27
+ }
28
+
29
+ async function statPath(path: string) {
30
+ try {
31
+ return await lstat(path)
32
+ } catch (error) {
33
+ if (missing(error)) return undefined
34
+ throw error
35
+ }
36
+ }
37
+
38
+ /** Targeted native checks, with a bounded-concurrency async scan for missed events. */
39
+ export function watchDevSource(
40
+ root: string,
41
+ hasCustomApp: () => boolean,
42
+ onChange: (path: string) => void,
43
+ onError: (error: unknown) => void
44
+ ) {
45
+ const previous = new Map<string, string>()
46
+ const dirty = new Set<string>()
47
+ let closed = false
48
+ let fullCheck = false
49
+ let nativeQueued = false
50
+ let debounce: ReturnType<typeof setTimeout> | undefined
51
+ let fallback: ReturnType<typeof setTimeout> | undefined
52
+ let chain: Promise<void> = Promise.resolve()
53
+
54
+ async function snapshot(directory: string, skipApp: boolean): Promise<Map<string, string>> {
55
+ const files = new Map<string, string>()
56
+ async function scan(path: string) {
57
+ if (closed || ignored(path) || (skipApp && isAppSource(path))) return
58
+ // Dirents avoid stat'ing non-source files or following directory symlinks.
59
+ let children: Dirent[]
60
+ try {
61
+ children = await readdir(resolve(root, path), { withFileTypes: true })
62
+ } catch (error) {
63
+ if (missing(error)) return
64
+ throw error
65
+ }
66
+ if (path === "app") {
67
+ const stat = await statPath(resolve(root, path))
68
+ if (stat && !stat.isSymbolicLink()) files.set(path, String(stat.ino))
69
+ if (skipApp) return
70
+ }
71
+ for (let offset = 0; offset < children.length && !closed; offset += 32) {
72
+ const batch = children.slice(offset, offset + 32)
73
+ await Promise.all(
74
+ batch
75
+ .filter((entry) => entry.isFile() && isSource(join(path, entry.name)))
76
+ .map(async (entry) => {
77
+ const file = join(path, entry.name)
78
+ if (ignored(file)) return
79
+ const stat = await statPath(resolve(root, file))
80
+ if (stat?.isFile()) files.set(file, fingerprint(stat))
81
+ })
82
+ )
83
+ // Recurse serially: nested directories cannot multiply the IO concurrency.
84
+ for (const entry of batch) if (entry.isDirectory()) await scan(join(path, entry.name))
85
+ }
86
+ }
87
+ await scan(directory)
88
+ return files
89
+ }
90
+
91
+ function fingerprint(stat: NonNullable<Awaited<ReturnType<typeof statPath>>>): string {
92
+ return `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`
93
+ }
94
+
95
+ function apply(next: Map<string, string>, directory: string, skipApp: boolean, notify: boolean) {
96
+ if (closed) return
97
+ let changed: string | undefined
98
+ const markChanged = (path: string) => {
99
+ if (!(hasCustomApp() && isAppSource(path))) changed ??= path
100
+ }
101
+ const inScope = (path: string) =>
102
+ (!directory || path === directory || path.startsWith(`${directory}${sep}`)) &&
103
+ !(skipApp && isAppSource(path))
104
+ for (const [path, value] of next) {
105
+ if (previous.get(path) !== value) markChanged(path)
106
+ previous.set(path, value)
107
+ }
108
+ for (const path of previous.keys()) {
109
+ if (inScope(path) && !next.has(path)) {
110
+ markChanged(path)
111
+ previous.delete(path)
112
+ }
113
+ }
114
+ if (notify && changed) onChange(changed)
115
+ }
116
+
117
+ async function reconcile(notify = true) {
118
+ const skipApp = hasCustomApp()
119
+ apply(await snapshot("", skipApp), "", skipApp, notify)
120
+ }
121
+
122
+ async function checkPath(path: string) {
123
+ if (closed || ignored(path) || (hasCustomApp() && isAppSource(path))) return
124
+ const stat = await statPath(resolve(root, path))
125
+ if (stat?.isDirectory()) {
126
+ const skipApp = hasCustomApp()
127
+ apply(await snapshot(path, skipApp), path, skipApp, true)
128
+ } else if (stat?.isFile() && isSource(path)) {
129
+ const value = fingerprint(stat)
130
+ if (!closed && previous.get(path) !== value) {
131
+ previous.set(path, value)
132
+ if (!(hasCustomApp() && isAppSource(path))) onChange(path)
133
+ }
134
+ } else if (!stat || stat.isSymbolicLink()) {
135
+ apply(new Map(), path, hasCustomApp(), true)
136
+ }
137
+ }
138
+
139
+ function enqueue(work: () => Promise<void>): Promise<void> {
140
+ const result = chain.then(async () => {
141
+ if (!closed) await work()
142
+ })
143
+ chain = result.catch((error) => {
144
+ if (!closed) onError(error)
145
+ })
146
+ return result
147
+ }
148
+
149
+ const watcher = watch(root, { recursive: true }, (_event, filename) => {
150
+ if (closed) return
151
+ if (filename) {
152
+ const path = String(filename)
153
+ if (ignored(path) || (hasCustomApp() && isAppSource(path))) return
154
+ dirty.add(path)
155
+ } else fullCheck = true
156
+ clearTimeout(debounce)
157
+ debounce = setTimeout(() => {
158
+ if (nativeQueued || closed) return
159
+ nativeQueued = true
160
+ void enqueue(async () => {
161
+ nativeQueued = false
162
+ const paths = [...dirty]
163
+ dirty.clear()
164
+ const full = fullCheck
165
+ fullCheck = false
166
+ if (full) await reconcile()
167
+ else for (const path of paths) await checkPath(path)
168
+ }).catch(() => {}) // enqueue reports failures and keeps the queue usable.
169
+ }, 100)
170
+ })
171
+ watcher.on("error", onError)
172
+
173
+ function scheduleFallback() {
174
+ if (closed) return
175
+ fallback = setTimeout(() => {
176
+ // Bun 1.3.14/macOS can omit recursive events. Keep recovery, but never queue
177
+ // overlapping scans or block the event loop with synchronous filesystem IO.
178
+ void enqueue(() => reconcile())
179
+ .catch(() => {})
180
+ .finally(scheduleFallback)
181
+ }, 5000)
182
+ }
183
+ const ready = enqueue(() => reconcile(false))
184
+ scheduleFallback()
185
+ return {
186
+ ready,
187
+ // Rebase before spawning: saves during shutdown are included in the next child,
188
+ // and app fingerprints are refreshed before handing its edits back to HMR.
189
+ refresh: () => enqueue(() => reconcile(false)),
190
+ async close() {
191
+ closed = true
192
+ clearTimeout(debounce)
193
+ clearTimeout(fallback)
194
+ watcher.close()
195
+ dirty.clear()
196
+ await chain
197
+ previous.clear()
198
+ },
199
+ }
200
+ }
@@ -83,6 +83,17 @@ export function builtAppOutdir(buildOutdir: string): string {
83
83
  return resolve(buildOutdir, "app")
84
84
  }
85
85
 
86
+ export async function hasBuiltCustomApp(appOutdir: string): Promise<boolean> {
87
+ const shells = await Promise.all(
88
+ ["index.html", "shared-index.html"].map((file) =>
89
+ stat(resolve(appOutdir, file))
90
+ .then((info) => info.isFile())
91
+ .catch(() => false)
92
+ )
93
+ )
94
+ return shells.every(Boolean)
95
+ }
96
+
86
97
  export function builtAtlasOutdir(buildOutdir: string): string {
87
98
  return resolve(buildOutdir, "atlas")
88
99
  }
@@ -204,9 +204,6 @@ export async function startSixbRuntime(
204
204
  sixb: LoadedSixbHost,
205
205
  options: StartSixbRuntimeOptions = {}
206
206
  ): Promise<RunningSixbRuntime> {
207
- await migrateRuntimeStorage(sixb)
208
- await checkRuntimeLakeDefinitions(sixb)
209
-
210
207
  let rulesRuntime: RunningRulesRuntime | null = null
211
208
  let schedulerRuntime: RunningSchedulerRuntime | null = null
212
209
  let orchestratorRuntime: RunningOrchestratorRuntime | null = null
@@ -234,6 +231,9 @@ export async function startSixbRuntime(
234
231
  }
235
232
 
236
233
  try {
234
+ // Own providers from the first startup phase, including preflight failures.
235
+ await migrateRuntimeStorage(sixb)
236
+ await checkRuntimeLakeDefinitions(sixb)
237
237
  rulesRuntime = await startRulesRuntime(sixb)
238
238
  rulesWorker = rulesRuntime.rulesWorker
239
239