claude-code-voc-intelligence-suite.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const os = require('os');
  5. const { spawnSync } = require('child_process');
  6. const qiniu = require('qiniu');
  7. const PROJECT_ROOT = path.resolve(__dirname, '..', '..');
  8. const SUITE_DIR = path.join(PROJECT_ROOT, 'claude-code', 'claude-code-voc-intelligence');
  9. const MANIFEST_PATH = path.join(SUITE_DIR, 'skill-package-manifest.json');
  10. const DIST_DIR = path.join(PROJECT_ROOT, 'dist');
  11. const PACKAGE_ID = 'claude-code-voc-intelligence';
  12. const NPM_PACKAGE_NAME = '@vocmarket/voc-skill';
  13. const PACKAGE_ZIP = path.join(DIST_DIR, `${PACKAGE_ID}.zip`);
  14. const DIST_MANIFEST = path.join(DIST_DIR, `${PACKAGE_ID}-suite-manifest.json`);
  15. const TEMP_ROOT = path.join(os.tmpdir(), 'claude-code-voc-pkg', PACKAGE_ID);
  16. const TEST_ROOT = path.join(os.tmpdir(), 'claude-code-voc-pkg-test', PACKAGE_ID);
  17. const CDN_PREFIX = 'x/claude-code-skills/packages';
  18. const CDN_KEY = `${CDN_PREFIX}/${PACKAGE_ID}.zip`;
  19. const CDN_DOMAIN = 'https://repos.fmode.cn';
  20. const BUCKET = 'nova-repos';
  21. const REQUIRED_FILES = [
  22. '.claude-plugin/plugin.json',
  23. '.mcp.json',
  24. 'bin/claude-voc.js',
  25. 'install.js',
  26. 'README.md',
  27. 'docs/customer-quickstart.md',
  28. 'docs/demo-runbook.md',
  29. 'docs/npm-packaging-notes.md',
  30. 'package.json',
  31. 'package-lock.json',
  32. 'skill-package-manifest.json',
  33. 'memory-templates/xiaohongshu-trend-profile.json',
  34. 'mcp/src/server.js',
  35. 'mcp/src/core/credentials.js',
  36. 'mcp/src/core/memory-store.js',
  37. 'mcp/src/core/result-envelope.js',
  38. 'mcp/src/features/xiaohongshu-trend/live-collector.js',
  39. 'mcp/src/features/xiaohongshu-trend/preference-memory.js',
  40. 'mcp/src/features/xiaohongshu-trend/report.js',
  41. 'mcp/src/features/xiaohongshu-trend/sample-data.js',
  42. 'mcp/src/features/douyin-trend/live-collector.js',
  43. 'mcp/src/features/douyin-trend/preference-memory.js',
  44. 'mcp/src/features/douyin-trend/report.js',
  45. 'mcp/src/features/douyin-trend/sample-data.js',
  46. 'mcp/src/features/voc-problem-deep-dive/deep-dive.js',
  47. 'mcp/src/providers/xiaohongshu-api.js',
  48. 'mcp/src/providers/douyin-api.js',
  49. 'mcp/src/tools/xiaohongshu-preference-update.js',
  50. 'mcp/src/tools/xiaohongshu-trend-run.js',
  51. 'mcp/src/tools/douyin-preference-update.js',
  52. 'mcp/src/tools/douyin-trend-run.js',
  53. 'mcp/src/tools/voc-problem-deep-dive-run.js',
  54. 'scripts/smoke-mcp.js',
  55. 'scripts/smoke-package.js',
  56. 'skills/xiaohongshu-trend-intelligence/SKILL.md',
  57. 'skills/douyin-trend-intelligence/SKILL.md',
  58. 'skills/voc-problem-deep-dive/SKILL.md',
  59. 'skills/xiaohongshu-trend-intelligence/references/user-workflow.md',
  60. 'skills/xiaohongshu-trend-intelligence/references/output-format.md',
  61. 'skills/xiaohongshu-trend-intelligence/references/live-mode.md'
  62. ];
  63. const EXCLUDED_DIRS = new Set([
  64. 'node_modules',
  65. 'memory',
  66. 'outputs',
  67. '.npm-cache-acceptance',
  68. '.tmp',
  69. '.git',
  70. '.claude'
  71. ]);
  72. const EXCLUDED_FILES = new Set([
  73. '.env',
  74. '.env.local',
  75. '.npmrc'
  76. ]);
  77. function parseArgs(argv) {
  78. const opts = {
  79. validate: false,
  80. build: false,
  81. testPackage: false,
  82. upload: false,
  83. help: false
  84. };
  85. for (const token of argv) {
  86. if (token === '--validate') opts.validate = true;
  87. else if (token === '--build') opts.build = true;
  88. else if (token === '--test-package') opts.testPackage = true;
  89. else if (token === '--upload') opts.upload = true;
  90. else if (token === '--all') {
  91. opts.validate = true;
  92. opts.build = true;
  93. opts.testPackage = true;
  94. } else if (token === '--help' || token === '-h') {
  95. opts.help = true;
  96. }
  97. }
  98. if (!opts.validate && !opts.build && !opts.testPackage && !opts.upload && !opts.help) {
  99. opts.validate = true;
  100. opts.build = true;
  101. opts.testPackage = true;
  102. }
  103. return opts;
  104. }
  105. function usage() {
  106. return [
  107. 'Usage:',
  108. ' node scripts/deploy/claude-code-voc-intelligence-suite.js',
  109. ' node scripts/deploy/claude-code-voc-intelligence-suite.js --validate',
  110. ' node scripts/deploy/claude-code-voc-intelligence-suite.js --build --test-package',
  111. ' node scripts/deploy/claude-code-voc-intelligence-suite.js --build --upload',
  112. '',
  113. 'Default mode is --validate --build --test-package without upload.',
  114. 'Upload requires QINIU_AK and QINIU_SK environment variables.'
  115. ].join('\n');
  116. }
  117. function ensureDir(dirPath) {
  118. fs.mkdirSync(dirPath, { recursive: true });
  119. }
  120. function readJson(filePath) {
  121. return JSON.parse(fs.readFileSync(filePath, 'utf8'));
  122. }
  123. function copyDirRecursive(srcDir, destDir) {
  124. ensureDir(destDir);
  125. let count = 0;
  126. for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
  127. if (entry.isDirectory() && EXCLUDED_DIRS.has(entry.name)) continue;
  128. if (entry.isFile() && EXCLUDED_FILES.has(entry.name)) continue;
  129. const src = path.join(srcDir, entry.name);
  130. const dest = path.join(destDir, entry.name);
  131. if (entry.isDirectory()) {
  132. count += copyDirRecursive(src, dest);
  133. } else if (entry.isFile()) {
  134. ensureDir(path.dirname(dest));
  135. fs.copyFileSync(src, dest);
  136. count++;
  137. }
  138. }
  139. return count;
  140. }
  141. function run(command, args, cwd) {
  142. const useCmd = process.platform === 'win32' && command === 'npm';
  143. const executable = useCmd ? 'cmd.exe' : command;
  144. const finalArgs = useCmd ? ['/d', '/s', '/c', 'npm', ...args] : args;
  145. const child = spawnSync(executable, finalArgs, {
  146. cwd,
  147. encoding: 'utf8',
  148. maxBuffer: 1024 * 1024 * 100
  149. });
  150. if (child.stdout) process.stdout.write(child.stdout);
  151. if (child.stderr) process.stderr.write(child.stderr);
  152. if (child.status !== 0) {
  153. const detail = child.error ? `: ${child.error.message}` : '';
  154. throw new Error(`${command} ${args.join(' ')} failed with exit ${child.status}${detail}`);
  155. }
  156. }
  157. function validateSuite() {
  158. console.log('[validate] claude-code-voc-intelligence suite');
  159. const missing = [];
  160. for (const rel of REQUIRED_FILES) {
  161. if (!fs.existsSync(path.join(SUITE_DIR, rel))) missing.push(rel);
  162. }
  163. const packageJson = readJson(path.join(SUITE_DIR, 'package.json'));
  164. const pluginJson = readJson(path.join(SUITE_DIR, '.claude-plugin', 'plugin.json'));
  165. const manifest = readJson(MANIFEST_PATH);
  166. const mcpJson = readJson(path.join(SUITE_DIR, '.mcp.json'));
  167. if (packageJson.name !== NPM_PACKAGE_NAME) missing.push('package.json:name mismatch');
  168. if (pluginJson.name !== 'voc-intelligence') missing.push('.claude-plugin/plugin.json:name mismatch');
  169. if (!manifest.skills.includes('xiaohongshu-trend-intelligence')) missing.push('manifest missing xiaohongshu-trend-intelligence');
  170. if (!mcpJson.mcpServers || !(mcpJson.mcpServers.voc || mcpJson.mcpServers['voc-intelligence'])) {
  171. missing.push('.mcp.json missing VOC MCP server');
  172. }
  173. if (missing.length) {
  174. throw new Error(`Suite validation failed:\n${missing.map(item => ` - ${item}`).join('\n')}`);
  175. }
  176. console.log(` ok: ${manifest.skills.length} skill, ${manifest.mcpTools.length} MCP tools`);
  177. }
  178. function buildSuite() {
  179. console.log('[build] dist/claude-code-voc-intelligence.zip');
  180. ensureDir(DIST_DIR);
  181. if (fs.existsSync(TEMP_ROOT)) fs.rmSync(TEMP_ROOT, { recursive: true, force: true });
  182. ensureDir(TEMP_ROOT);
  183. const copied = copyDirRecursive(SUITE_DIR, TEMP_ROOT);
  184. if (fs.existsSync(PACKAGE_ZIP)) fs.unlinkSync(PACKAGE_ZIP);
  185. run('powershell', [
  186. '-NoProfile',
  187. '-Command',
  188. `Compress-Archive -Path '${TEMP_ROOT}\\*' -DestinationPath '${PACKAGE_ZIP}' -Force`
  189. ], PROJECT_ROOT);
  190. writeDistManifest({ uploaded: false, copiedFiles: copied });
  191. const size = fs.statSync(PACKAGE_ZIP).size;
  192. console.log(` ok: ${PACKAGE_ZIP} (${(size / 1024).toFixed(0)} KB, ${copied} files)`);
  193. }
  194. function testPackage() {
  195. console.log('[test-package] unzip + install.js smoke');
  196. if (!fs.existsSync(PACKAGE_ZIP)) throw new Error(`Package zip not found: ${PACKAGE_ZIP}`);
  197. if (fs.existsSync(TEST_ROOT)) fs.rmSync(TEST_ROOT, { recursive: true, force: true });
  198. ensureDir(TEST_ROOT);
  199. run('powershell', [
  200. '-NoProfile',
  201. '-Command',
  202. `Expand-Archive -Path '${PACKAGE_ZIP}' -DestinationPath '${TEST_ROOT}' -Force`
  203. ], PROJECT_ROOT);
  204. run(process.execPath, ['install.js', '--smoke'], TEST_ROOT);
  205. console.log(' ok: extracted package can run install.js and sample/preference/MCP smoke');
  206. }
  207. function uploadFile(localFile, cdnKey) {
  208. return new Promise((resolve, reject) => {
  209. const accessKey = process.env.QINIU_AK;
  210. const secretKey = process.env.QINIU_SK;
  211. if (!accessKey || !secretKey) {
  212. return reject(new Error('Missing QINIU_AK or QINIU_SK environment variable'));
  213. }
  214. const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  215. const putPolicy = new qiniu.rs.PutPolicy({ scope: `${BUCKET}:${cdnKey}`, expires: 3600 });
  216. const token = putPolicy.uploadToken(mac);
  217. const config = new qiniu.conf.Config({ zone: qiniu.zone.Zone_z2 });
  218. const formUploader = new qiniu.form_up.FormUploader(config);
  219. const putExtra = new qiniu.form_up.PutExtra();
  220. formUploader.putFile(token, cdnKey, localFile, putExtra, (err, body, info) => {
  221. if (err) return reject(err);
  222. if (info.statusCode === 200) return resolve({ key: body.key, url: `${CDN_DOMAIN}/${body.key}` });
  223. reject(new Error(`Upload failed: ${info.statusCode} ${JSON.stringify(body)}`));
  224. });
  225. });
  226. }
  227. async function uploadSuite() {
  228. console.log('[upload] qiniu nova-repos');
  229. if (!fs.existsSync(PACKAGE_ZIP)) throw new Error(`Package zip not found: ${PACKAGE_ZIP}`);
  230. const result = await uploadFile(PACKAGE_ZIP, CDN_KEY);
  231. writeDistManifest({ uploaded: true, downloadUrl: result.url });
  232. const urlsPath = path.join(DIST_DIR, 'download-urls.json');
  233. const urls = fs.existsSync(urlsPath) ? readJson(urlsPath) : {};
  234. urls[PACKAGE_ID] = result.url;
  235. fs.writeFileSync(urlsPath, `${JSON.stringify(urls, null, 2)}\n`, 'utf8');
  236. console.log(` ok: ${result.url}`);
  237. }
  238. function writeDistManifest(extra = {}) {
  239. const manifest = readJson(MANIFEST_PATH);
  240. const stat = fs.existsSync(PACKAGE_ZIP) ? fs.statSync(PACKAGE_ZIP) : undefined;
  241. const output = {
  242. name: PACKAGE_ID,
  243. version: manifest.version,
  244. generatedAt: new Date().toISOString(),
  245. packageZip: fs.existsSync(PACKAGE_ZIP) ? path.relative(PROJECT_ROOT, PACKAGE_ZIP).replace(/\\/g, '/') : '',
  246. packageZipBytes: stat ? stat.size : 0,
  247. plugin: manifest.plugin,
  248. skills: manifest.skills,
  249. mcpTools: manifest.mcpTools,
  250. installHint: manifest.installHint,
  251. installCommand: manifest.installCommand,
  252. npmInstallCommand: manifest.npmInstallCommand,
  253. npxInstallCommand: manifest.npxInstallCommand,
  254. workspaceInstallCommand: manifest.workspaceInstallCommand,
  255. workspaceInstallTarget: manifest.workspaceInstallTarget,
  256. buildCommand: 'node scripts/deploy/claude-code-voc-intelligence-suite.js --validate --build --test-package',
  257. uploadCommand: 'node scripts/deploy/claude-code-voc-intelligence-suite.js --validate --build --test-package --upload',
  258. ...extra
  259. };
  260. fs.writeFileSync(DIST_MANIFEST, `${JSON.stringify(output, null, 2)}\n`, 'utf8');
  261. console.log(`[manifest] ${path.relative(PROJECT_ROOT, DIST_MANIFEST)}`);
  262. }
  263. async function main() {
  264. const opts = parseArgs(process.argv.slice(2));
  265. if (opts.help) {
  266. console.log(usage());
  267. return;
  268. }
  269. if (opts.validate) validateSuite();
  270. if (opts.build) buildSuite();
  271. if (opts.testPackage) testPackage();
  272. if (opts.upload) await uploadSuite();
  273. if (!opts.build) writeDistManifest({ uploaded: false });
  274. console.log('[done] claude-code-voc-intelligence suite is ready');
  275. }
  276. main().catch(error => {
  277. console.error(`[error] ${error.message}`);
  278. process.exit(1);
  279. });