wishforge-ide/scripts/setup-local-poc.ts
eust-w 90a76f2d59 🐛 Make the local POC setup safe to rerun
- It allowed every IPv4 address of the en* interfaces as a web origin,
  public ones included; it now takes only private LAN addresses, as
  npm run local:network does.
- It rewrote .env.local in place, where a crash lost the generated
  secrets, and missed `export` assignments; the file is now replaced
  atomically through scripts/env-file.mjs.
- A binding file it could not read made it create a second project
  and environment; only a missing one means a first setup now.
- A runner registered for a replaced environment is registered again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:33:30 +08:00

186 lines
7.5 KiB
TypeScript

/** Explicit local operator bootstrap; no wish, Git push, build or POC deployment is started here. */
import { mkdir, readFile, writeFile, chmod } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
import { parseEnv } from 'node:util';
import { lanAddresses } from './configure-local-network.mjs';
import { replaceEnvFile, setEnvValues } from './env-file.mjs';
import { PgStore } from '../apps/api/src/db/store.js';
import { ControlPlane, touch } from '../apps/api/src/domain/control-plane.js';
import { Releases } from '../apps/api/src/domain/releases.js';
import { RunnerBroker } from '../apps/api/src/domain/runner-broker.js';
import { loadPocProfile, localPocBindingSchema } from '../packages/runtime/src/index.js';
import type { Actor, Environment, Project } from '../packages/contracts/src/index.js';
process.loadEnvFile('.env.local');
if (process.env.WF_DEPLOYMENT_MODE !== 'development') throw Error('Explicit development mode required');
const root = process.cwd(),
directory = path.join(root, '.wishforge', 'local-poc');
const bindingFile = path.join(directory, 'project.json');
const profileFile = path.join(homedir(), '.config/wishforge/poc-profile.json');
await loadPocProfile(profileFile);
await mkdir(directory, { recursive: true, mode: 0o700 });
const env = {
...process.env,
WF_CLAUDE_BIN: '/opt/homebrew/bin/claude',
WF_CLAUDE_LOCAL_AUTH_HOME: homedir(),
WF_PROVISIONER_BACKEND: 'local',
WF_LOCAL_RUN_ROOT: path.join(homedir(), '.local/share/wishforge/runs'),
};
delete env.WF_LOCAL_POC_BINDING_FILE;
const store = new PgStore(env.DATABASE_URL!);
const actor: Actor = { tenantId: 'demo', userId: '11111111-1111-4111-8111-111111111111', kind: 'human', role: 'owner' };
try {
await store.assertSafeRole();
if (!(await store.read(actor.tenantId, tx => tx.membership(actor.userId))))
throw Error('Run db:seed before this bootstrap');
const control = new ControlPlane(store, env),
releases = new Releases(store, env);
// Only a missing binding means a first setup; an unreadable one must not create a second project.
const existing = await readFile(bindingFile, 'utf8').then(
text => localPocBindingSchema.parse(JSON.parse(text)),
(error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return undefined;
throw error;
},
);
let project = existing
? await control.projects(actor).then(items => items.find(p => p.id === existing.projectId))
: undefined;
if (!project)
project = await control.createProject(actor, {
name: 'DroboticFlow POC · Claude 本机',
repositoryUrl: 'https://gitea.d-robotics.cc/longtao.wu/droboticflow.git',
targetBranch: 'poc',
});
let target = existing ? (await releases.environments(actor)).find(e => e.id === existing.environmentId) : undefined;
if (!target)
target = await releases.createEnvironment(actor, {
projectId: project.id,
name: '现有 POC · droboticflow',
type: 'kubernetes',
production: false,
autoDeploy: true,
architecture: 'linux/amd64',
configVersion: 'adopt-existing-v1',
secretVersionRefs: [],
});
const binding = localPocBindingSchema.parse({
schemaVersion: 1,
tenantId: actor.tenantId,
projectId: project.id,
environmentId: target.id,
repositoryUrl: project.repositoryUrl,
targetBranch: 'poc',
profileFile,
stateDirectory: path.join(homedir(), '.local/share/wishforge/poc'),
gitHome: homedir(),
});
await writeFile(bindingFile, JSON.stringify(binding, null, 2) + '\n', { mode: 0o600 });
env.WF_LOCAL_POC_BINDING_FILE = bindingFile;
await new Releases(store, env).updateApplicationUrl(actor, target.id, { applicationUrl: 'http://120.48.164.19' });
const checkScript = path.join(root, 'scripts/poc-project-check.mjs');
await store.transaction(actor.tenantId, async tx => {
const p = await tx.get<Project>('project', project!.id);
if (!p) throw Error('Project disappeared');
if (p.repositoryUrl !== binding.repositoryUrl || p.targetBranch !== 'poc')
throw Error('Existing project repository changed');
p.installCommands = [[process.execPath, checkScript, 'install']];
p.verificationCommands = [[process.execPath, checkScript, 'verify']];
p.autoDeploy = true;
p.deliveryConfig = {
environmentId: target!.id,
imageRepository: 'ccr-29eug8s3-pub.cnc.bj.baidubce.com/dataflow-poc/droboticflow-api',
architecture: 'linux/amd64',
dockerfile: 'Dockerfile.api',
sourceContext: '.',
containerPort: 3001,
healthPath: '/api/health',
smokeChecks: [
{ path: '/api/ready', expectedStatus: 200, bodyIncludes: '"ready":true' },
{ path: '/', expectedStatus: 200, bodyIncludes: '<div id="root">' },
],
};
await tx.put('project', touch(p));
});
const runnerFile = path.join(directory, 'runner.env'),
keysFile = path.join(directory, 'runner-public.json');
// A runner registered for an environment that was since replaced is registered again.
const configuredRunner = await readFile(runnerFile, 'utf8').then(
text => parseEnv(text).WF_ENVIRONMENT_ID === target.id,
(error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return false;
throw error;
},
);
if (!configuredRunner) {
const registration = await new RunnerBroker(store, new Releases(store, env), env).register(actor, target.id);
await writeFile(keysFile, JSON.stringify(registration.publicKeys, null, 2) + '\n', { mode: 0o600 });
const values = {
WF_DEPLOYMENT_MODE: 'development',
WF_CONTROL_PLANE_URL: 'http://127.0.0.1:4000',
WF_RUNNER_ALLOW_LOCAL_HTTP: 'true',
WF_RUNNER_TOKEN: registration.token,
WF_TENANT_ID: actor.tenantId,
WF_ENVIRONMENT_ID: target.id,
WF_RUNNER_PUBLIC_KEYS: keysFile,
WF_RUNNER_STATE_DIR: path.join(directory, 'runner-state'),
WF_POC_PROFILE_FILE: profileFile,
WF_RUNNER_EXECUTE: 'true',
};
await writeFile(
runnerFile,
Object.entries(values)
.map(([k, v]) => `${k}=${v}`)
.join('\n') + '\n',
{ mode: 0o600 },
);
}
// Private LAN addresses only, like npm run local:network: no public address becomes an entry.
const addresses = lanAddresses().map(entry => entry.address);
const origins = [
'http://localhost:3000',
'http://127.0.0.1:3000',
...addresses.map(address => `http://${address}:3000`),
];
const settings = {
WF_DEPLOYMENT_MODE: 'development',
WF_PROVISIONER_BACKEND: 'local',
WF_LOCAL_RUN_ROOT: path.join(homedir(), '.local/share/wishforge/runs'),
WF_TENANT_ID: 'demo',
WF_CLAUDE_BIN: '/opt/homebrew/bin/claude',
WF_CLAUDE_LOCAL_AUTH_HOME: homedir(),
WF_LOCAL_POC_BINDING_FILE: bindingFile,
WF_WEB_HOST: '0.0.0.0',
WF_WEB_PORT: '3000',
WF_WEB_SERVE_MODE: 'production',
WF_LOCAL_ACCESS: 'true',
WF_LOCAL_ACCESS_FILE: path.join(root, '.wishforge/local-access.json'),
WF_LOCAL_ALLOWED_ORIGINS: origins.join(','),
HOST: '127.0.0.1',
};
const old = await readFile('.env.local', 'utf8');
await replaceEnvFile(path.join(root, '.env.local'), old, setEnvValues(old, settings));
await chmod('.env.local', 0o600);
console.log(
JSON.stringify(
{
status: 'configured',
projectId: project.id,
environmentId: target.id,
branch: 'poc',
provider: 'claude-code',
webOrigins: origins,
bindingFile,
runnerConfigFile: runnerFile,
credentialsFile: settings.WF_LOCAL_ACCESS_FILE,
started: false,
},
null,
2,
),
);
} finally {
await store.close();
}