/** 本地试用容器实测;只操作本轮记录的独立 Docker 名称,不删除旧资产。 */ import { recordProgress } from './lib/project-recovery.mjs'; import fs from 'node:fs'; import path from 'node:path'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { validatedPromptInputs } from './lib/onboarding-input.mjs'; const arg = (name, fallback) => process.argv.find(x => x.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback; const stage = arg('stage', 'status'); const out = path.resolve(arg('out', 'test-results/new-account-20261128')); const privateDir = path.resolve(arg('private-dir', '.local-backup/new-account-20261128')); const packageRoot = path.resolve(arg('package-dir', path.join(out, 'onboarding-package'))); const file = path.join(out, 'state.json'); let state, env; const lockFile = path.join(out, 'runner.lock'); const lock = fs.openSync(lockFile, 'wx'); fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage: `docker-${stage}`, at: new Date().toISOString() })); const save = () => { fs.writeFileSync(file + '.next', JSON.stringify(state, null, 2) + '\n'); fs.renameSync(file + '.next', file); }; const note = text => recordProgress(process.cwd(), `[${out}] ${text}`); const docker = (args, input, allowFailure = false) => { const r = spawnSync('docker', args, { input, encoding: 'utf8', timeout: 90000, maxBuffer: 4 * 1024 * 1024 }); if (!allowFailure && (r.error || r.status !== 0)) throw Error(`Docker ${args[0]} 失败,exit=${r.status}:${r.stderr?.slice(-600) ?? r.error?.message}`); return r; }; const redact = text => ['MATRIX_PASSWORD', 'FMODE_SESSION_TOKEN'].reduce((text, key) => env?.[key] ? text.split(env[key]).join(`<${key}>`) : text, text); const snapshot = name => { const r = docker(['inspect', name], undefined, true); if (r.status !== 0) return { exists: false, name }; const data = JSON.parse(r.stdout)[0]; const result = { exists: true, name, id: data.Id, state: data.State, image: data.Image, mounts: data.Mounts.map(x => ({ name: x.Name, destination: x.Destination })), configuredEnvKeys: data.Config.Env.map(x => x.split('=')[0]) }; const logs = docker(['logs', '--tail', '200', name], undefined, true); const suffix = stage === 'resume-candidate' ? '-resume-20261129' : ''; fs.writeFileSync(path.join(privateDir, `${name}${suffix}.raw.log`), logs.stdout + logs.stderr); fs.writeFileSync(path.join(out, `${name}${suffix}.log`), redact(logs.stdout + logs.stderr)); fs.writeFileSync(path.join(out, `${name}${suffix}.inspect.json`), JSON.stringify(result, null, 2)); return result; }; try { state = JSON.parse(fs.readFileSync(file)); env = JSON.parse(fs.readFileSync(path.join(privateDir, 'trial-env.json'))); assert.equal(env.AGENT_ID, state.trial?.agentId, '提示词身份与本轮账本不一致'); if (stage === 'status') { const names = Object.values(state.actions).filter(a => a.kind === 'trial-local').map(a => a.target); for (const name of names) console.log(JSON.stringify(snapshot(name), null, 2)); } else if (stage === 'prompt-fresh') { assert.ok(!state.actions.localPromptFresh?.attempted, '新版提示词从零安装已有动作记录,先只读核实,禁止重复建卷或启动'); assert.ok(state.actions.trialPromptRefresh?.confirmedAt && state.actions.cloudPrompt?.confirmedAt, '先完成部署后APK真实提示词回验'); const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json')); assert.equal(state.trial.updatedInstruction.bundleSha256, bundle.sha256); const instruction = fs.readFileSync(path.join(privateDir, 'trial-instruction-updated.md'), 'utf8'); const savedEnv = JSON.parse(fs.readFileSync(path.join(privateDir, 'trial-env-updated.json'))); const captured = validatedPromptInputs(instruction, state.trial.updatedInstruction, savedEnv, bundle); const installScript = captured.script; env = captured.env; assert.equal(env.AGENT_ID, state.trial.agentId); assert.equal(env.MATRIX_USER_ID, state.trial.agentMxId); const source = state.actions.localCandidate; const before = snapshot(source.target); assert.equal(before.id, source.containerId, '只能停止本轮原候选'); assert.equal(snapshot(state.actions.localRaw.target).state.Running, false, '原raw必须保持停止'); const name = 'fmode-trial-prompt-' + env.AGENT_ID.replace(/^agent-node-app-/, '') + '-' + bundle.sha256.slice(0, 8); const volume = name + '-data'; assert.equal(docker(['ps', '-a', '--filter', `name=^/${name}$`, '--format', '{{.Names}}']).stdout.trim(), ''); assert.notEqual(docker(['volume', 'inspect', volume], undefined, true).status, 0); const modelFile = path.join(privateDir, 'test-model-config.yaml'); assert.ok(fs.existsSync(modelFile), '缺少显式可用模型前提,不能用额外补丁代替'); const runtimeEnv = Object.fromEntries(Object.entries(env).filter(([key]) => /^(HERMES_|MATRIX_|AGENT_|FMODE_)/.test(key) || ['TZ', 'RES_OPTIONS'].includes(key))); for (const [key, value] of Object.entries(runtimeEnv)) assert.ok(/^[A-Z][A-Z0-9_]*$/.test(key) && typeof value === 'string' && value && !/[\r\n]/.test(value)); const envText = Object.entries(runtimeEnv).map(([key, value]) => key + '=' + value).join('\n') + '\n'; const envFile = path.join(privateDir, 'trial-prompt-fresh-runtime.env'); fs.writeFileSync(envFile, envText, { flag: 'wx' }); state.actions.localPromptFresh = { attempted: true, at: new Date().toISOString(), kind: 'trial-local', target: name, volume, agentId: env.AGENT_ID, bundleSha256: bundle.sha256, sourceCandidate: source.target, originalCandidateId: before.id, phase: 'before-original-stop-and-volume-create', instructionSha256: state.trial.updatedInstruction.instructionSha256, modelPrerequisite: 'private test-model-config.yaml; not included in bundle' }; save(); note(`准备停止原候选${source.target}并保留原卷;新隔离卷${volume},新实例${name}。严格执行APK捕获的下载/校验/安装Python程序,模型为显式前提,连续安装两次仅验证幂等,不同时运行相同Matrix身份。`); if (before.state.Running) docker(['stop', '--time', '15', source.target]); assert.equal(snapshot(source.target).state.Running, false); state.actions.localPromptFresh.phase = 'original-stopped-before-volume-create'; save(); docker(['volume', 'create', volume]); state.actions.localPromptFresh.phase = 'fresh-volume-before-real-prompt-install'; save(); const setup = "import os,shutil,base64\nfrom pathlib import Path\np=Path('/opt/data')\nassert not (p/'config.yaml').exists(), 'fresh volume must not contain a prior config'\nshutil.copyfile('/tmp/test-model.yaml',p/'config.yaml')\nos.chown(p/'config.yaml',10000,10000)\n(p/'.fmode-onboarding.env').write_bytes(base64.b64decode('" + Buffer.from(envText).toString('base64') + "'))\nos.chmod(p/'.fmode-onboarding.env',0o600)\nos.chown(p/'.fmode-onboarding.env',10000,10000)\n"; const installed = docker(['run', '--rm', '-i', '--name', name + '-install', '--env-file', envFile, '--mount', `type=volume,source=${volume},target=/opt/data`, '--mount', `type=bind,source=${modelFile},target=/tmp/test-model.yaml,readonly`, '--entrypoint', '/opt/hermes/.venv/bin/python', bundle.image, '-B', '-'], setup + installScript + '\n' + installScript + '\n'); fs.writeFileSync(path.join(out, 'prompt-fresh-install-v101.log'), installed.stdout + installed.stderr, { flag: 'wx' }); const installs = installed.stdout.split(/\r?\n/).filter(line => line.startsWith('{')).map(line => JSON.parse(line)); assert.equal(installs.length, 2, '必须有首次安装及重复安装两个真实回执'); assert.equal(installs[0].version, bundle.version); assert.equal(installs[1].version, bundle.version); assert.deepEqual(installs[1].changed, [], '相同提示词重复安装仍有变更,幂等未通过'); state.actions.localPromptFresh.installReceipts = installs; state.actions.localPromptFresh.phase = 'prompt-installed-twice-before-start'; save(); const started = docker(['run', '-d', '--name', name, '--hostname', env.AGENT_ID, '--env-file', envFile, '--mount', `type=volume,source=${volume},target=/opt/data`, '--memory', '1536m', '--cpus', '1.5', '--pids-limit', '512', '--restart', 'no', '--entrypoint', '/opt/data/.fmode-media-patch/entry.sh', bundle.image, 'gateway', 'run']); state.actions.localPromptFresh.containerId = started.stdout.trim(); state.actions.localPromptFresh.phase = 'started-awaiting-platform-verification'; state.assets.push({ kind: 'local-docker-container', name, volume, agentId: env.AGENT_ID, owner: state.userId }); save(); await new Promise(resolve => setTimeout(resolve, 8000)); const after = snapshot(name); assert.equal(after.state.Running, true); assert.equal(after.id, state.actions.localPromptFresh.containerId); state.actions.localPromptFresh.confirmedAt = new Date().toISOString(); state.actions.localPromptFresh.receipt = { id: after.id, state: after.state, mounts: after.mounts, installs }; save(); note(`真实APK提示词已在新隔离卷首次安装并幂等复验成功,${name}运行;原候选与raw停止、旧卷保留。此回执只确认安装/启动,后续真实首报/通信/成果另验。`); console.log(JSON.stringify({ name, volume, version: bundle.version, secondInstallChanges: installs[1].changed, running: after.state.Running })); } else if (stage === 'resume-candidate') { const source = state.actions.localCandidate; assert.ok(source?.containerId && source.target, '缺少原候选实例回执,不能新建冒充恢复'); const key = 'candidateResume_20261129'; assert.ok(!state.actions[key]?.attempted, '恢复启动已有动作,先只读核实,不盲重试'); const before = snapshot(source.target); assert.equal(before.id, source.containerId, '候选实例 ID 与原回执不符'); assert.equal(before.state.Running, false, '实例已经运行,无需再次启动'); const raw = snapshot(state.actions.localRaw.target); assert.equal(raw.state.Running, false, '原始实例必须保持停止,禁止同身份并发'); const expectedVolume = source.volume; assert.ok(before.mounts.some(x => x.name === expectedVolume && x.destination === '/opt/data'), '原数据卷挂载不符'); state.actions[key] = { attempted: true, at: new Date().toISOString(), target: source.target, containerId: before.id, volume: expectedVolume, phase: 'before-start' }; save(); note(`准备仅恢复原候选实例 ${source.target},ID 与原数据卷已核对;原始实例保持停止,不创建新资产。`); docker(['start', source.target]); state.actions[key].phase = 'started-awaiting-inspection'; save(); await new Promise(resolve => setTimeout(resolve, 8000)); const after = snapshot(source.target); assert.equal(after.id, source.containerId); assert.equal(after.state.Running, true); state.actions[key].confirmedAt = new Date().toISOString(); state.actions[key].receipt = { id: after.id, state: after.state, mounts: after.mounts }; save(); note('原候选实例已恢复 running,原数据卷未重建;尚须核对真实心跳、消息与历史。'); console.log(JSON.stringify(state.actions[key].receipt)); } else if (stage === 'update-candidate') { const source = state.actions.localCandidate; assert.ok(source?.containerId && source.target, '候选实例缺少创建回执'); const receipt = JSON.parse(fs.readFileSync(path.join(packageRoot, 'receipt.json'))); const key = 'candidateUpdate_' + receipt.sha256.slice(0, 16); assert.ok(!state.actions[key]?.attempted, '该版本更新已有记录,先 status 核实'); const before = snapshot(source.target); assert.equal(before.id, source.containerId, '候选实例身份发生变化'); state.actions[key] = { attempted: true, at: new Date().toISOString(), target: source.target, bundleSha256: receipt.sha256, phase: 'before-stop' }; save(); note(`准备仅更新候选实例 ${source.target} 至接入包 ${receipt.sha256};先停止,再在离线初始化进程中安装,保留模型和历史。`); if (before.state.Running) docker(['stop', '--time', '15', source.target]); state.actions[key].phase = 'stopped-before-install'; save(); const packageDir = path.join(packageRoot, 'package'); const modelFile = path.join(privateDir, 'test-model-config.yaml'); const bootstrap = "import os,sys,json,yaml;from pathlib import Path;p=Path('/opt/data/config.yaml');cfg=yaml.safe_load(p.read_text());fixture=yaml.safe_load(Path('/tmp/test-model.yaml').read_text());assert cfg['model']==fixture['model'],'test model configuration unexpectedly changed';cfg.setdefault('_config_version',fixture['_config_version']);p.write_text(yaml.safe_dump(cfg,allow_unicode=True));os.chown(p,10000,10000);sys.path.insert(0,'/candidate');from install import install;print(json.dumps(install(Path('/candidate'),Path('/opt/data'),dict(os.environ)),ensure_ascii=False))"; const installed = docker(['run', '--rm', '--name', source.target + '-update', '--network', 'none', '--env-file', path.join(privateDir, 'trial-runtime.env'), '--mount', `type=volume,source=${source.volume},target=/opt/data`, '--mount', `type=bind,source=${packageDir},target=/candidate,readonly`, '--mount', `type=bind,source=${modelFile},target=/tmp/test-model.yaml,readonly`, '--entrypoint', '/opt/hermes/.venv/bin/python', 'fmode/agent-node:0.21.3', '-B', '-c', bootstrap]); fs.writeFileSync(path.join(out, `${key}-install.json`), installed.stdout); state.actions[key].phase = 'installed-before-start'; save(); docker(['start', source.target]); state.actions[key].phase = 'restarted-awaiting-inspection'; save(); await new Promise(resolve => setTimeout(resolve, 8000)); const result = snapshot(source.target); state.actions[key].confirmedAt = new Date().toISOString(); state.actions[key].receipt = result.state; state.actions.localCandidate.bundleSha256 = receipt.sha256; save(); note(`候选实例更新后状态 ${result.state.Status};指定成果 hooks 已登记许可,图文合并组件已纳入启用清单;继续真实消息和文件验收。`); console.log(JSON.stringify({ name: source.target, updated: receipt.sha256, state: result.state }, null, 2)); } else if (stage === 'candidate') { assert.ok(!state.actions.localCandidate?.attempted, '修复版容器已有创建记录,先 status 核实'); assert.equal(snapshot(state.actions.localRaw.target).state.Running, false, '原始实例必须先停止,避免相同 Matrix 身份并发'); const name = 'fmode-trial-local-' + env.AGENT_ID.replace(/^agent-node-app-/, '') + '-candidate'; const volume = name + '-data'; const packageDir = path.join(packageRoot, 'package'); const modelFile = path.join(privateDir, 'test-model-config.yaml'); assert.ok(fs.existsSync(modelFile), '本地测试需先准备明确的模型前提配置'); assert.equal(docker(['ps', '-a', '--filter', `name=^/${name}$`, '--format', '{{.Names}}']).stdout.trim(), ''); assert.notEqual(docker(['volume', 'inspect', volume], undefined, true).status, 0); const receipt = JSON.parse(fs.readFileSync(path.join(packageRoot, 'receipt.json'))); state.actions.localCandidate = { attempted: true, at: new Date().toISOString(), kind: 'trial-local', target: name, volume, agentId: env.AGENT_ID, phase: 'before-volume-create', bundleSha256: receipt.sha256, modelPrerequisite: 'private test-model-config.yaml, not distributed' }; save(); note(`准备创建隔离候选实例 ${name} 与卷 ${volume},使用接入包 ${receipt.sha256};模型配置是显式测试前提,仅在私有目录,不进入接入包。原试用实例已停止。`); const completeEnv = { ...env, HERMES_HOME: '/opt/data', HERMES_DASHBOARD: '0', TZ: 'Asia/Shanghai', RES_OPTIONS: 'single-request' }; const envFile = path.join(privateDir, 'trial-runtime.env'); fs.writeFileSync(envFile, Object.entries(completeEnv).map(([k, v]) => `${k}=${v}`).join('\n') + '\n'); docker(['volume', 'create', volume]); state.actions.localCandidate.phase = 'volume-created-before-model-and-bridge-install'; save(); const bootstrap = "import os,shutil,sys,json;from pathlib import Path;shutil.copyfile('/tmp/test-model.yaml','/opt/data/config.yaml');os.chown('/opt/data/config.yaml',10000,10000);sys.path.insert(0,'/candidate');from install import install;print(json.dumps(install(Path('/candidate'),Path('/opt/data'),dict(os.environ)),ensure_ascii=False))"; const installed = docker(['run', '--rm', '--name', name + '-install', '--network', 'none', '--env-file', envFile, '--mount', `type=volume,source=${volume},target=/opt/data`, '--mount', `type=bind,source=${packageDir},target=/candidate,readonly`, '--mount', `type=bind,source=${modelFile},target=/tmp/test-model.yaml,readonly`, '--entrypoint', '/opt/hermes/.venv/bin/python', 'fmode/agent-node:0.21.3', '-B', '-c', bootstrap]); fs.writeFileSync(path.join(out, 'candidate-install.json'), installed.stdout); state.actions.localCandidate.phase = 'model-prerequisite-and-bridge-installed'; save(); const started = docker(['run', '-d', '--name', name, '--hostname', env.AGENT_ID, '--env-file', envFile, '--mount', `type=volume,source=${volume},target=/opt/data`, '--memory', '1536m', '--cpus', '1.5', '--pids-limit', '512', '--restart', 'no', '--entrypoint', '/opt/data/.fmode-media-patch/entry.sh', 'fmode/agent-node:0.21.3', 'gateway', 'run']); state.actions.localCandidate.containerId = started.stdout.trim(); state.actions.localCandidate.phase = 'started-awaiting-inspection'; save(); state.assets.push({ kind: 'local-docker-container', name, volume, agentId: env.AGENT_ID, owner: state.userId }); save(); await new Promise(resolve => setTimeout(resolve, 8000)); const result = snapshot(name); state.actions.localCandidate.confirmedAt = new Date().toISOString(); state.actions.localCandidate.receipt = result; save(); note(`候选接入包已安装并启动,Docker 实际状态 ${result.state.Status};待核实插件加载、真实平台首报和 App 使用,不按 running 判成功。`); console.log(JSON.stringify({ name, state: result.state, bundleSha256: receipt.sha256 }, null, 2)); } else if (stage === 'stop-raw') { const source = state.actions.localRaw; assert.ok(source?.containerId && source?.target, '缺少本轮原始实测容器回执'); assert.ok(!state.actions.localRawStop?.attempted, '停止动作已有记录,先 status 核实'); const before = snapshot(source.target); assert.equal(before.id, source.containerId, '目标实例不是本轮创建的容器'); state.actions.localRawStop = { attempted: true, at: new Date().toISOString(), target: source.target, before: before.state.Status }; save(); note(`准备停止本轮原始实测容器 ${source.target},保留容器、数据卷与日志;不操作既有容器。`); docker(['stop', '--time', '15', source.target]); const result = snapshot(source.target); assert.equal(result.state.Running, false); state.actions.localRawStop.confirmedAt = new Date().toISOString(); state.actions.localRawStop.receipt = result.state; save(); note(`原始实测容器已停止;已确认提示词未提供接入插件,平台无该容器心跳;默认仪表盘认证失败反复重启。原日志及数据保留,接下来只修独立接入路径。`); console.log(JSON.stringify({ stopped: source.target, running: result.state.Running })); } else if (stage === 'raw') { assert.ok(!state.actions.localRaw?.attempted, '原提示词实测已登记,先 status 核实,不能重复启动'); const name = 'fmode-trial-local-' + env.AGENT_ID.replace(/^agent-node-app-/, '') + '-raw'; const volume = name + '-data'; assert.equal(docker(['ps', '-a', '--filter', `name=^/${name}$`, '--format', '{{.Names}}']).stdout.trim(), '', '同名容器已存在'); assert.notEqual(docker(['volume', 'inspect', volume], undefined, true).status, 0, '同名数据卷已存在'); state.actions.localRaw = { attempted: true, at: new Date().toISOString(), kind: 'trial-local', target: name, volume, agentId: env.AGENT_ID, phase: 'before-volume-create', prompt: 'original' }; save(); note(`准备按原提示词的 .env + Docker 环境变量方式启动 ${name},新数据卷 ${volume};仅使用本轮试用身份,可能产生网关上线事件。`); const envText = Object.entries(env).map(([key, value]) => { assert.match(key, /^[A-Z][A-Z0-9_]*$/); assert.ok(!/[\r\n]/.test(value)); return `${key}=${value}`; }).join('\n') + '\n'; const envFile = path.join(privateDir, 'trial-original.env'); fs.writeFileSync(envFile, envText); docker(['volume', 'create', volume]); state.actions.localRaw.phase = 'volume-created'; save(); docker(['run', '--rm', '-i', '--name', name + '-write-env', '--network', 'none', '--mount', `type=volume,source=${volume},target=/opt/data`, '--entrypoint', '/bin/sh', 'fmode/agent-node:0.21.3', '-c', 'umask 077; cat > /opt/data/.env; chown 10000:10000 /opt/data/.env'], envText); state.actions.localRaw.phase = 'env-written-before-start'; save(); const run = docker(['run', '-d', '--name', name, '--hostname', env.AGENT_ID, '--env-file', envFile, '--mount', `type=volume,source=${volume},target=/opt/data`, '--memory', '1536m', '--cpus', '1.5', '--pids-limit', '512', '--restart', 'no', 'fmode/agent-node:0.21.3', 'gateway', 'run']); state.actions.localRaw.containerId = run.stdout.trim(); state.actions.localRaw.phase = 'started-awaiting-inspection'; save(); await new Promise(resolve => setTimeout(resolve, 7000)); const result = snapshot(name); state.actions.localRaw.confirmedAt = new Date().toISOString(); state.actions.localRaw.receipt = result; save(); state.assets.push({ kind: 'local-docker-container', name, volume, agentId: env.AGENT_ID, owner: state.userId }); save(); note(`原提示词实测容器已创建并回读:${result.state.Status},退出码 ${result.state.ExitCode};日志 ${path.relative(process.cwd(), out)}/${name}.log;此记录仅确认实际动作,不表示接入通过。`); console.log(JSON.stringify({ name, state: result.state, log: `${name}.log` }, null, 2)); } else throw Error('未知本地试用阶段:' + stage); } catch (error) { if (state) { state.lastFailure = { stage: 'docker-' + stage, message: redact(error.message), at: new Date().toISOString() }; save(); } note(`未完成:${redact(error.message)};先只读检查,不重复创建。`); throw error; } finally { fs.closeSync(lock); fs.unlinkSync(lockFile); }