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

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