wishforge-ide/scripts/setup-local-poc.ts
eust-w 4e5ab1719c ✨ Enable local Claude delivery to Gitea and POC
Add authenticated LAN access, native Claude execution, checkpoint and budget recovery, and signed POC build/deploy/rollback contracts. Include local service management, regression coverage, and evidence from the completed POC delivery.
2026-10-22 16:21:33 +08:00

180 lines
7.2 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, networkInterfaces } from 'node:os';
import path from 'node:path';
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);
const existing = await readFile(bindingFile, 'utf8')
.then(text => localPocBindingSchema.parse(JSON.parse(text)))
.catch(() => undefined);
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');
const configuredRunner = await readFile(runnerFile, 'utf8')
.then(() => true)
.catch(() => false);
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 },
);
}
const addresses = Object.entries(networkInterfaces())
.filter(([name]) => /^en\d+$/.test(name))
.flatMap(([, items]) => (items ?? []).filter(i => i.family === 'IPv4' && !i.internal).map(i => i.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');
let lines = old.split('\n');
for (const [k, v] of Object.entries(settings)) {
const i = lines.findIndex(line => line.startsWith(k + '='));
if (i < 0) lines.push(`${k}=${v}`);
else lines[i] = `${k}=${v}`;
}
await writeFile('.env.local', lines.join('\n') + '\n', { mode: 0o600 });
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();
}