@volter/twin-standard 1.0.153 → 1.0.155

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.
@@ -360,7 +360,7 @@ export function cliFile(vendor: string, live = false): string {
360
360
  const Name = pascal(vendor);
361
361
  const ingest = live ? `// the RTMP ingest's side port, which the World allocates (the manifest's sidePorts)\nconst ingestPort = Number(optionValue(rest, '--ingest-port', '0')) || undefined;\n` : '';
362
362
  const served = live ? ` process.stdout.write(s.ingestPort ? \`${vendor} twin ingest at rtmp://127.0.0.1:\${s.ingestPort}\\n\` : '${vendor} twin: no RTMP ingest\\n');\n` : '';
363
- return `#!/usr/bin/env node\n// world-${vendor}: serve the ${vendor} twin.\nimport { hasFlag, optionValue } from '@volter/world-core/args';\nimport { keepProcessAlive } from '@volter/world-core/lifecycle';\nimport { create${Name}TwinServer } from './server.ts';\n\nconst [cmd, ...rest] = process.argv.slice(2);\nconst port = Number(optionValue(rest, '--port', '0')) || undefined;\nconst root = optionValue(rest, '--root') || undefined;\nconst readOnly = hasFlag(rest, '--read-only');\n// the World's managed Postgres, which the runtime binds a pack declaring managedDatabase to\nconst database = optionValue(rest, '--database') || undefined;\n// the World's scenario file, for a model vendor's turns\nconst scenarioPath = optionValue(rest, '--scenario') || undefined;\n${ingest}\nif (cmd === 'serve' || cmd === undefined) {\n const s = await create${Name}TwinServer({ readOnly, ...(root ? { root } : {}), ...(port ? { port } : {}), ...(database ? { database } : {}), ...(scenarioPath ? { scenarioPath } : {})${live ? ', ...(ingestPort ? { ingestPort } : {})' : ''} });\n process.stdout.write(\`${vendor} twin\${readOnly ? ' [read-only]' : ''} at http://127.0.0.1:\${s.port}\\n\`);\n${served} await keepProcessAlive();\n} else {\n process.stdout.write('Usage: world-${vendor} serve [--port N] [--root DIR] [--read-only] [--database URL] [--scenario FILE]${live ? ' [--ingest-port N]' : ''}\\n');\n}\n`;
363
+ return `#!/usr/bin/env node\n// world-${vendor}: serve the ${vendor} twin.\nimport { hasFlag, optionValue } from '@volter/world-core/args';\nimport { keepProcessAlive } from '@volter/world-core/lifecycle';\nimport { create${Name}TwinServer } from './server.ts';\n\nconst [cmd, ...rest] = process.argv.slice(2);\nconst port = Number(optionValue(rest, '--port', '0')) || undefined;\nconst root = optionValue(rest, '--root') || undefined;\nconst readOnly = hasFlag(rest, '--read-only');\n// the selected twin's private Postgres, which the runtime binds a pack declaring managedDatabase to\nconst database = optionValue(rest, '--database') || undefined;\n// the World's scenario file, for a model vendor's turns\nconst scenarioPath = optionValue(rest, '--scenario') || undefined;\n${ingest}\nif (cmd === 'serve' || cmd === undefined) {\n const s = await create${Name}TwinServer({ readOnly, ...(root ? { root } : {}), ...(port ? { port } : {}), ...(database ? { database } : {}), ...(scenarioPath ? { scenarioPath } : {})${live ? ', ...(ingestPort ? { ingestPort } : {})' : ''} });\n process.stdout.write(\`${vendor} twin\${readOnly ? ' [read-only]' : ''} at http://127.0.0.1:\${s.port}\\n\`);\n${served} await keepProcessAlive();\n} else {\n process.stdout.write('Usage: world-${vendor} serve [--port N] [--root DIR] [--read-only] [--database URL] [--scenario FILE]${live ? ' [--ingest-port N]' : ''}\\n');\n}\n`;
364
364
  }
365
365
 
366
366
  /** A vendor id as a name in code: `npm-registry` is `NpmRegistry`. */
@@ -414,7 +414,6 @@ Contributor mechanics belong to the [pack procedure](https://world-docs.volter.a
414
414
 
415
415
  export function initFiles(vendor: string): Record<string, string> {
416
416
  const Name = pascal(vendor);
417
- const semantics = `${Name[0]!.toLowerCase()}${Name.slice(1)}Semantics`;
418
417
  return {
419
418
  'package.json': `${JSON.stringify({
420
419
  name: `@volter/twin-${vendor}`, version: '1.0.0', description: `The ${vendor} twin (Protocol 3).`, author: 'Volter (https://github.com/volter-ai)', license: 'Apache-2.0',
@@ -448,8 +447,6 @@ export function initFiles(vendor: string): Record<string, string> {
448
447
  * surface of its own under `<lane>/src`, keeping the vendor's one store and sharing its `src/semantics/shared.ts`, and the
449
448
  * pack's server routing each lane's host to it. */
450
449
  export function laneInitFiles(vendor: string, lanes: string[]): Record<string, string> {
451
- const Name = pascal(vendor);
452
- const camel = (s: string): string => { const p = pascal(s); return `${p[0]!.toLowerCase()}${p.slice(1)}`; };
453
450
  const single = initFiles(vendor);
454
451
  const files: Record<string, string> = {
455
452
  'package.json': single['package.json']!.replace('"spec",', lanes.map((l) => `"${l}",`).join('\n ')),
@@ -0,0 +1,27 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseAllDocuments } from 'yaml';
4
+
5
+ /** The application's selected direct dependency, including the exact installer's integrity. */
6
+ export function dependencyLock(root: string) {
7
+ const pnpm = join(root, 'pnpm-lock.yaml');
8
+ if (existsSync(pnpm)) {
9
+ const bytes = readFileSync(pnpm);
10
+ const documents = parseAllDocuments(bytes.toString());
11
+ for (const doc of documents) if (doc.errors.length) throw doc.errors[0];
12
+ const lock = documents.map(doc => doc.toJS()).find(doc => doc?.importers?.['.'] && !doc.importers['.'].packageManagerDependencies);
13
+ if (!lock) throw new Error('No pnpm application importer');
14
+ return { bytes, file: pnpm, entry(name: string) {
15
+ const importer = lock.importers['.'];
16
+ const selected = importer.dependencies?.[name] ?? importer.devDependencies?.[name] ?? importer.optionalDependencies?.[name];
17
+ if (!selected) return undefined;
18
+ const selectedRef = String(selected.version);
19
+ const ref = lock.packages?.[`${name}@${selectedRef}`] ? selectedRef : selectedRef.replace(/\(.*$/, '');
20
+ const pkg = lock.packages?.[`${name}@${ref}`];
21
+ return { version: pkg?.version ?? ref, integrity: pkg?.resolution?.integrity };
22
+ } };
23
+ }
24
+ const file = join(root, 'package-lock.json'), bytes = readFileSync(file);
25
+ const lock = JSON.parse(bytes.toString());
26
+ return { bytes, file, entry(name: string) { return lock.packages?.[`node_modules/${name}`] as { version?: string; integrity?: string } | undefined; } };
27
+ }
package/src/pack-facts.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Published descriptor compiler. Pack locations are explicit; imports happen only when called by a publisher.
2
2
  import { existsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { PACK_ARCHETYPES, PROTOCOL_VERSION, protocolStanding } from '@volter/world-core/runtime';
4
+ import { PACK_ARCHETYPES, PROTOCOL_VERSION, protocolStanding, type TwinPack } from '@volter/world-core/runtime';
5
5
 
6
6
  export type PackFacts = {
7
7
  /** Explicit vendor-server backing; this entry declares no pack protocol or factory. */
@@ -32,14 +32,14 @@ export type PackFacts = {
32
32
  endpointEnv?: { name: string; templates?: Record<string, string> };
33
33
  endpointEnvNone?: string;
34
34
  /** The door that issues the application a credential the twin accepts (see TwinPack.credentialDoor). */
35
- credentialDoor?: { path: string; body: Record<string, unknown>; fill: Record<string, string> };
35
+ credentialDoor?: TwinPack['credentialDoor'];
36
36
  credentialIssuer?: string;
37
37
  /** The Prisma driver adapter this database twin is reached through (see TwinPack.prismaAdapter). */
38
38
  prismaAdapter?: { adapter: string; export: string; urlEnv: string };
39
39
  /** The managed-infrastructure kind this pack is the World's backing for (architecture.md, "The descriptor"). */
40
40
  managedService?: { kind: 'redis' | 'mongodb' | 'clickhouse'; scheme: string; note: string; configurationArg?: '--configuration'; originalInputs?: { version: 1; manifestArg: '--original-inputs'; rootArg: '--original-root'; digestArg: '--original-inputs-sha256'; paths: string[] } };
41
- /** The World's managed database the runtime binds the twin to (see TwinPack.managedDatabase). */
42
- managedDatabase?: { kind: 'postgres'; arg: string; note: string };
41
+ /** The selected twin's private SQL identity and credential field (see TwinPack.managedDatabase). */
42
+ managedDatabase?: { kind: 'postgres'; arg: string; user: string; database: string; clock: 'wall'; credentialField: string; note: string };
43
43
  /** Listeners the twin opens beside its main port (see TwinPack.sidePorts). */
44
44
  sidePorts?: Array<{ name: string; option: string; flag: string; path?: string; scheme?: string; note: string }>;
45
45
  /** DERIVED, never declared: the pack's `create<Name>TwinServer` factory export — the
@@ -184,9 +184,12 @@ export async function compilePackFacts(dirs: Array<{ vendor: string; dir: string
184
184
  facts.prismaAdapter = pack.prismaAdapter;
185
185
  }
186
186
  if (pack.managedDatabase !== undefined) {
187
- const md = pack.managedDatabase as { kind?: unknown; arg?: unknown; note?: unknown };
188
- if (md.kind !== 'postgres') throw new Error(`pack-facts: ${vendor} declares managedDatabase.kind "${String(md.kind)}"; the runtime binds only the World's managed postgres`);
187
+ const md = pack.managedDatabase as { kind?: unknown; arg?: unknown; user?: unknown; database?: unknown; clock?: unknown; credentialField?: unknown; note?: unknown };
188
+ if (md.kind !== 'postgres') throw new Error(`pack-facts: ${vendor} declares managedDatabase.kind "${String(md.kind)}"; private SQL supports postgres`);
189
189
  if (typeof md.arg !== 'string' || !/^--[a-z][a-z-]*$/.test(md.arg)) throw new Error(`pack-facts: ${vendor} declares managedDatabase.arg "${String(md.arg)}"; it is the serve flag the URL follows (--name)`);
190
+ for (const key of ['user', 'database'] as const) if (typeof md[key] !== 'string' || !md[key] || /[\r\n\0$]/u.test(md[key]) || Buffer.byteLength(md[key], 'utf8') > 63) throw new Error(`pack-facts: ${vendor} private database ${key} must be a literal PostgreSQL identifier of at most 63 bytes`);
191
+ if (md.clock !== 'wall') throw new Error(`pack-facts: ${vendor} private postgres must declare its wall clock`);
192
+ if (typeof md.credentialField !== 'string' || !Object.values(pack.credentialDoor?.fill ?? {}).includes(md.credentialField) || /^(?:file|directory|side):/.test(md.credentialField)) throw new Error(`pack-facts: ${vendor} private database must name its credential door's scalar URL field`);
190
193
  if (typeof md.note !== 'string' || md.note.trim() === '') throw new Error(`pack-facts: ${vendor} declares managedDatabase with no note`);
191
194
  facts.managedDatabase = pack.managedDatabase;
192
195
  }
package/src/published.ts CHANGED
@@ -19,7 +19,7 @@ export const vendorOfPackage = (name: string): string => name.replace(/^@[^/]+\/
19
19
  async function withPublished<T>(spec: string, opts: { registry?: string }, use: (dir: string, tmp: string) => Promise<T>): Promise<T> {
20
20
  const tmp = mkdtempSync(join(tmpdir(), 'twin-standard-'));
21
21
  try {
22
- const pack = spawnSync('npm', ['pack', spec, '--pack-destination', tmp, '--silent', ...(opts.registry ? ['--registry', opts.registry] : [])], { encoding: 'utf8' });
22
+ const pack = spawnSync('npm', ['pack', '--force', spec, '--pack-destination', tmp, '--silent', ...(opts.registry ? ['--registry', opts.registry] : [])], { encoding: 'utf8' });
23
23
  const tarball = readdirSync(tmp).find((f) => f.endsWith('.tgz'));
24
24
  if (pack.status !== 0 || !tarball) throw new Error(`${spec}: the registry gave no tarball (${String(pack.stderr).trim().split('\n').at(-1) ?? ''})`);
25
25
  const untar = spawnSync('tar', ['-xzf', join(tmp, tarball), '-C', tmp], { encoding: 'utf8' });
@@ -66,7 +66,7 @@ export async function conformPublished(spec: string, opts: { registry?: string }
66
66
  const platform = Object.keys(deps).filter((d) => d.startsWith('@volter/'));
67
67
  const others = Object.entries(deps).filter(([d]) => !d.startsWith('@volter/')).map(([d, v]) => `${d}@${v}`);
68
68
  if (others.length) {
69
- const install = spawnSync('npm', ['install', '--no-save', '--omit=dev', '--omit=peer', '--ignore-scripts', '--no-audit', '--no-fund', '--no-package-lock', ...(opts.registry ? ['--registry', opts.registry] : []), ...others], { cwd: dirname(dir), encoding: 'utf8' });
69
+ const install = spawnSync('pnpm', ['add', '--prod', '--config.autoInstallPeers=false', '--package-import-method=hardlink', '--config.nodeLinker=hoisted', '--ignore-scripts', ...(opts.registry ? ['--registry', opts.registry] : []), ...others], { cwd: dirname(dir), encoding: 'utf8' });
70
70
  if (install.status !== 0) throw new Error(`${spec}: its dependencies do not install (${String(install.stderr).trim().split('\n').at(-1) ?? ''})`);
71
71
  }
72
72
  mkdirSync(join(dir, 'node_modules', '@volter'), { recursive: true });
@@ -436,8 +436,8 @@ export const isGit = (step: Step): step is GitStep => 'git' in step;
436
436
  export type WaitStep = { name: string; wait: string };
437
437
  export const isWait = (step: Step): step is WaitStep => 'wait' in step;
438
438
 
439
- /** What an application sends the World's managed database over the database's own wire, not through the vendor's API (a
440
- * pack whose data plane is the World's Postgres, the descriptor's `managedDatabase`): its migrations as its deploy applies
439
+ /** What an application sends the selected twin's database over its SQL wire, not through the vendor's HTTP API (a
440
+ * pack whose descriptor declares a private SQL product (`managedDatabase`)): its migrations as its deploy applies
441
441
  * them and the queries it sends, each on the application's one connection to the walked World's database (world-core
442
442
  * `databaseSession`), so a transaction it begins stays open into its next steps, as on its own connection. `sql` alone is
443
443
  * one simple Query (a migration file, a `BEGIN`); with `values` it is one extended-protocol statement, the values bind
@@ -1,7 +1,7 @@
1
1
  // The standard serves a pack with its declared backing, as the runtime binds it in a World.
2
2
  import { join } from 'node:path';
3
- import { worldNow } from '@volter/world-core/runtime';
4
- import { startPgliteHost, type PgliteHost } from './walk-database.ts';
3
+ import type { TwinPack } from '@volter/world-core/runtime';
4
+ import { startTwinDatabase, type TwinDatabase } from './walk-database.ts';
5
5
 
6
6
  export type ServedPack = {
7
7
  port: number;
@@ -10,13 +10,13 @@ export type ServedPack = {
10
10
  managedDatabaseUrl?: () => Promise<string>;
11
11
  };
12
12
 
13
- export async function servePack(pack: string, options: Record<string, unknown>): Promise<ServedPack> {
13
+ export async function servePack(pack: string, options: { root?: string; scenarioPath?: string }): Promise<ServedPack> {
14
14
  const mod = await import(join(pack, 'src', 'server.ts')) as Record<string, unknown>;
15
15
  const create = Object.entries(mod).find(([name, value]) => /^create\w+TwinServer$/.test(name) && typeof value === 'function')?.[1] as ((options: Record<string, unknown>) => Promise<ServedPack>) | undefined;
16
16
  if (!create) throw new Error('src/server.ts exports no create<Vendor>TwinServer');
17
- const descriptor = (await import(join(pack, 'src', 'index.ts'))).pack as { managedDatabase?: { kind: string } } | undefined;
18
- let database: PgliteHost | undefined;
19
- if (descriptor?.managedDatabase?.kind === 'postgres' && options.database === undefined) database = await startPgliteHost();
17
+ const descriptor = (await import(join(pack, 'src', 'index.ts'))).pack as TwinPack | undefined;
18
+ let database: TwinDatabase | undefined;
19
+ if (descriptor?.managedDatabase?.kind === 'postgres') database = await startTwinDatabase(pack, descriptor);
20
20
  let server: ServedPack;
21
21
  try { server = await create({ port: 0, ...options, ...(database ? { database: database.url } : {}) }); }
22
22
  catch (error) { await database?.stop(); throw error; }
@@ -25,7 +25,7 @@ export async function servePack(pack: string, options: Record<string, unknown>):
25
25
  let stopping: Promise<void> | undefined;
26
26
  return {
27
27
  ...server,
28
- managedDatabaseUrl: async () => { backing.clock(worldNow()); return backing.url; },
28
+ managedDatabaseUrl: async () => backing.url,
29
29
  stop: () => stopping ??= (async () => { await server.stop(); await backing.stop(); })(),
30
30
  };
31
31
  }
@@ -2,8 +2,8 @@
2
2
  // index. What the catalog's walkers drive (behavior journeys, the spec census probe, the invariants)
3
3
  // since the worker render left with the v1 host.
4
4
  import { join } from 'node:path';
5
- import { type PgliteHost, startPgliteHost } from './walk-database.ts';
6
- import { type TwinStream, worldNow } from '@volter/world-core/runtime';
5
+ import { type TwinDatabase, startTwinDatabase } from './walk-database.ts';
6
+ import { type TwinStream, type TwinPack } from '@volter/world-core/runtime';
7
7
  import type { PackFetchOptions } from '@volter/world-core';
8
8
  import { walkPackDirectory } from './pack-directory.ts';
9
9
 
@@ -22,19 +22,19 @@ export async function vendorFetch(twinDir: string, vendor: string, dependenciesF
22
22
  const name = Object.keys(mod).find((k) => /^create\w+?Fetch$/.test(k) && !/TwinFetch$/.test(k) && typeof mod[k] === 'function');
23
23
  if (!name) return undefined;
24
24
  const factory = mod[name] as (options: { root: string; database?: string; scenarioPath?: string; application?: ApplicationStandIn }) => ((request: Request) => Response | Promise<Response>) & Record<string, unknown>;
25
- if (!(mod.pack as { managedDatabase?: unknown } | undefined)?.managedDatabase) return (root: string, options = {}) => factory({ root, ...options });
26
- // A pack whose data plane is the World's managed Postgres is walked over one, as a World binds it: each World (each
27
- // root) its own fresh database, started on its first request and stopped when the walk's process ends, its clock the
28
- // walked World's (set before each request: the walk moves the World clock between steps).
25
+ const descriptor = mod.pack as TwinPack | undefined;
26
+ if (!descriptor?.managedDatabase) return (root: string, options = {}) => factory({ root, ...options });
27
+ // Each walked twin owns a fresh SQL product through the ordinary selected-twin lifecycle.
28
+ // Native SQL uses the descriptor's explicit wall clock; kernel World time is not claimed for it.
29
29
  return (root: string, options = {}) => {
30
30
  const bare = factory({ root, ...options });
31
31
  let bound: Promise<(request: Request) => Response | Promise<Response>> | undefined;
32
- let host: PgliteHost | undefined;
33
- const bind = () => (bound ??= startPgliteHost().then((started) => { host = started; return factory({ root, database: started.url, ...options }); }));
34
- const served = (request: Request) => bind().then((fetch) => { host!.clock(worldNow()); return fetch(request); });
35
- // the World's database itself, for what an application sends it over its own wire (a SQL step: journey-kit.ts)
36
- const managedDatabaseUrl = () => bind().then(() => { host!.clock(worldNow()); return host!.url; });
37
- // the walk's end stops its World's database, so the next World walked declares it at the same port
32
+ let host: TwinDatabase | undefined;
33
+ const bind = () => (bound ??= startTwinDatabase(directory, descriptor).then((started) => { host = started; return factory({ root, database: started.url, ...options }); }));
34
+ const served = (request: Request) => bind().then((fetch) => { return fetch(request); });
35
+ // The twin's SQL product, for what an application sends over its own wire (journey-kit.ts).
36
+ const managedDatabaseUrl = () => bind().then(() => { return host!.url; });
37
+ // The walk's end retires the selected twin's private engine through its World.
38
38
  const stopDatabase = async () => { if (bound === undefined) return; await bound.catch(() => undefined); await host?.stop(); };
39
39
  return Object.assign(served, bare, { managedDatabaseUrl, stopDatabase });
40
40
  };
@@ -1,106 +1,73 @@
1
- // The walker's Postgres is a declared, task-owned World. The runtime supervises its lifetime and backing;
2
- // the walker owns when to use and release it, never the backend's process or data directory.
1
+ // A managed SQL walk selects the pack in a task-owned World. The same private twin
2
+ // engine lifecycle serves both the World and the walker; no infrastructure is assembled here.
3
3
  import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
4
- import { createServer } from 'node:net';
5
- import { tmpdir } from 'node:os';
6
4
  import { createRequire } from 'node:module';
7
- import { dirname, extname, join } from 'node:path';
8
- import { worldNow } from '@volter/world-core/runtime';
5
+ import { dirname, join } from 'node:path';
6
+ import type { TwinPack } from '@volter/world-core/runtime';
9
7
 
10
- // The runtime is this package's optional peer: only a walk over a managed database needs it, so it is loaded here, on
11
- // that walk's first database, and every command that starts none runs with the standard alone installed.
12
8
  type Runtime = typeof import('@volter/world-runtime');
13
- let loaded: Promise<{ runtime: Runtime; infrastructureCli: string }> | undefined;
9
+ let loaded: Promise<Runtime> | undefined;
14
10
  const worldRuntime = () => loaded ??= (async () => {
15
- let entry: string;
16
- try { entry = createRequire(import.meta.url).resolve('@volter/world-runtime'); }
17
- catch { throw new Error('A managed database walk needs @volter/world-runtime installed beside @volter/twin-standard: npm i @volter/world-runtime'); }
18
- return { runtime: await import('@volter/world-runtime'), infrastructureCli: join(dirname(entry), `infra-cli${extname(entry)}`) };
11
+ try { createRequire(import.meta.url).resolve('@volter/world-runtime'); }
12
+ catch { throw new Error('A managed SQL walk needs @volter/world-runtime installed beside @volter/twin-standard'); }
13
+ return import('@volter/world-runtime');
19
14
  })();
20
15
 
21
- async function freePort(): Promise<number> {
22
- return new Promise((done, fail) => {
23
- const server = createServer();
24
- server.once('error', fail);
25
- server.listen(0, '127.0.0.1', () => {
26
- const port = (server.address() as { port: number }).port;
27
- server.close(() => done(port));
28
- });
29
- });
30
- }
31
-
32
- export type PgliteHost = { url: string; port: number; clock: (at: string) => void; stop: () => Promise<void> };
33
-
34
- // Sequential replays declare the same database endpoint. A concurrent walk declares its own port. Only a successful
35
- // runtime teardown releases this slot; unknown cleanup never licenses reusing its port or deleting its state.
36
- let declaredPort: number | undefined;
37
- let declaredHeld = false;
16
+ export type TwinDatabase = { url: string; stop: () => Promise<void> };
38
17
 
39
- export async function startPgliteHost(): Promise<PgliteHost> {
40
- if (!process.env.VOLTER_WORLD) throw new Error('A managed database walk requires its enclosing World');
41
- const { runtime: { runWorld, setWorldClock, worldConfigDocument }, infrastructureCli } = await worldRuntime();
42
- const root = mkdtempSync(join(tmpdir(), 'walk-database-world-'));
43
- const name = 'pack-walk-postgres';
44
- const port = declaredPort !== undefined && !declaredHeld ? declaredPort : await freePort();
45
- declaredPort ??= port;
46
- const holdsDeclared = port === declaredPort;
47
- if (holdsDeclared) declaredHeld = true;
48
- const fake = { user: 'world', database: 'world', password: 'walk-only-fake-password' };
49
- const url = `postgresql://${fake.user}:${fake.password}@127.0.0.1:${port}/${fake.database}`;
18
+ export async function startTwinDatabase(pack: string, descriptor: TwinPack): Promise<TwinDatabase> {
19
+ if (!process.env.VOLTER_WORLD) throw new Error('A managed SQL walk requires its enclosing World');
20
+ const definition = descriptor.managedDatabase, door = descriptor.credentialDoor;
21
+ if (!definition || !door || !definition.credentialField) throw new Error('The selected twin must declare its SQL credential door field');
22
+ const { runWorld, worldConfigDocument } = await worldRuntime();
23
+ // Keep the disposable World on the pack's own volume and package-resolution ancestry.
24
+ const root = mkdtempSync(join(dirname(pack), '.walk-database-'));
25
+ const manifest = JSON.parse(readFileSync(join(pack, 'package.json'), 'utf8')) as { name: string };
50
26
  const config = join(root, 'world.json');
51
- const command = [process.execPath, infrastructureCli];
52
- writeFileSync(join(root, 'world.infrastructure.yml'), JSON.stringify({ services: { postgres: {
53
- image: 'postgres:18-alpine', ports: [`127.0.0.1:${port}:5432`],
54
- environment: { POSTGRES_USER: fake.user, POSTGRES_DB: fake.database, POSTGRES_PASSWORD: fake.password },
55
- } } }, null, 2) + '\n');
56
- writeFileSync(config, JSON.stringify(worldConfigDocument({ id: name,
57
- env: { DATABASE_URL: url, VOLTER_WORLD_INFRA_BACKING: 'pglite' }, network: { egress: [] },
58
- services: [{ id: 'infrastructure', type: 'external', controlPlane: true, external: {
59
- up: [...command, 'up'], status: [...command, 'status'], down: [...command, 'down'],
60
- discover: [{ as: 'DATABASE_URL', jsonPath: 'connections.DATABASE_URL', protocol: 'postgres' }],
61
- readyWhen: { command: command[0], args: [...command.slice(1), 'status'], timeoutMs: 120_000, intervalMs: 500 },
62
- } }],
27
+ writeFileSync(config, JSON.stringify(worldConfigDocument({ id: 'pack-walk-sql', stripEnv: ['*'], network: { egress: [] },
28
+ services: [{ id: descriptor.vendor, type: 'twin', package: manifest.name }],
63
29
  }), null, 2) + '\n');
64
- setWorldClock(name, root, worldNow());
65
30
  const readyFile = join(root, 'ready.json'), releaseFile = join(root, 'release');
66
- // This is the registered consumer held by runWorld, not an infrastructure supervisor. It exposes only its own
67
- // connection env, and exits when the caller's sequence is done. Caller loss belongs to the runtime's run guardian.
31
+ // Ask the selected twin's actual product door. The runtime alone allocates and owns its engine.
68
32
  const hold = `
69
- import { existsSync, renameSync, watch, writeFileSync } from 'node:fs';
33
+ import { existsSync, readFileSync, renameSync, watch, writeFileSync } from 'node:fs';
70
34
  import { dirname } from 'node:path';
71
- const [ready, release] = process.argv.slice(1);
72
- if (!process.env.VOLTER_WORLD || !process.env.DATABASE_URL) throw new Error('Missing held World connection');
35
+ const [ready, release, vendor, path, body, field] = process.argv.slice(1);
36
+ if (!process.env.VOLTER_WORLD_INSTANCE) throw new Error('Missing held World instance');
37
+ const instance = JSON.parse(readFileSync(process.env.VOLTER_WORLD_INSTANCE, 'utf8'));
38
+ const service = instance.services[vendor];
39
+ if (!service?.url) throw new Error('Selected twin has no product endpoint');
40
+ const response = await fetch(new URL(path, service.url), {method:'POST',headers:{'content-type':'application/json'},body});
41
+ if (!response.ok) throw new Error('Selected twin SQL credential door refused: ' + response.status);
42
+ const result = await response.json();
43
+ if (typeof result[field] !== 'string' || !result[field]) throw new Error('SQL credential door omitted its declared field');
73
44
  const done = () => { if (existsSync(release)) process.exit(0); };
74
45
  watch(dirname(release), done);
75
- writeFileSync(ready + '.tmp', JSON.stringify({ url: process.env.DATABASE_URL }));
46
+ writeFileSync(ready + '.tmp', JSON.stringify({ url: result[field] }), {mode:0o600});
76
47
  renameSync(ready + '.tmp', ready);
77
48
  done();`;
78
49
  let finished: { result?: Awaited<ReturnType<Runtime['runWorld']>>; error?: unknown; failed: boolean } | undefined;
79
- const task = runWorld(config, [process.execPath, '--input-type=module', '-e', hold, readyFile, releaseFile], {
80
- root, cwd: root, owner: 'pack-walk-managed-database',
50
+ const task = runWorld(config, [process.execPath, '--input-type=module', '-e', hold, readyFile, releaseFile,
51
+ descriptor.vendor, door.path, JSON.stringify(door.body), definition.credentialField], {
52
+ root, cwd: root, owner: 'pack-walk-twin-private-sql',
81
53
  }).then(result => { finished = { result, failed: false }; return result; }, error => {
82
54
  finished = { error, failed: true }; throw error;
83
55
  });
84
- // Startup and normal stop await this promise; keep an early rejection handled while waiting for readiness.
85
56
  void task.catch(() => undefined);
86
57
  while (!existsSync(readyFile)) {
87
58
  if (finished) {
88
- if (!finished.failed && holdsDeclared) declaredHeld = false;
89
59
  if (finished.failed) throw finished.error;
90
- throw new Error(`Managed database World ended before its consumer was ready (exit ${finished.result!.exitCode}); evidence: ${root}`);
60
+ throw new Error(`Twin SQL World ended before its consumer was ready (exit ${finished.result!.exitCode}); evidence: ${root}`);
91
61
  }
92
62
  await new Promise(resolve => setTimeout(resolve, 100));
93
63
  }
94
64
  const ready = JSON.parse(readFileSync(readyFile, 'utf8')) as { url: string };
95
65
  let stopping: Promise<void> | undefined;
96
- return {
97
- url: ready.url, port: Number(new URL(ready.url).port),
98
- clock: at => setWorldClock(name, root, at),
66
+ return { url: ready.url,
99
67
  stop: () => stopping ??= (async () => {
100
68
  writeFileSync(releaseFile, 'released\n');
101
69
  const result = await task;
102
- if (result.exitCode !== 0) throw new Error(`Managed database World consumer exited ${result.exitCode}; evidence: ${root}`);
103
- if (holdsDeclared) declaredHeld = false;
70
+ if (result.exitCode !== 0) throw new Error(`Twin SQL World consumer exited ${result.exitCode}; evidence: ${root}`);
104
71
  })(),
105
72
  };
106
73
  }