install-context.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #!/usr/bin/env node
  2. /**
  3. * install-context.js
  4. * Downloads OAC context files to .claude/context/ in the current project.
  5. *
  6. * Requirements: node, git (nothing else to install)
  7. *
  8. * Run from project root:
  9. * node install-context.js [--profile=standard] [--force] [--dry-run]
  10. */
  11. const { execSync } = require('child_process');
  12. const { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, mkdtempSync } = require('fs');
  13. const { join } = require('path');
  14. const os = require('os');
  15. // Configuration
  16. const GITHUB_REPO = 'darrenhinde/OpenAgentsControl';
  17. const GITHUB_BRANCH = 'main';
  18. const CONTEXT_SOURCE_PATH = '.opencode/context';
  19. // Roots resolved after parsing --global flag in main()
  20. const PROJECT_ROOT = process.cwd();
  21. const GLOBAL_ROOT = join(os.homedir(), '.claude');
  22. // Installation profiles
  23. const PROFILES = {
  24. core: {
  25. categories: ['core', 'openagents-repo'],
  26. },
  27. full: {
  28. categories: [
  29. 'core',
  30. 'openagents-repo',
  31. 'development',
  32. 'ui',
  33. 'content-creation',
  34. 'data',
  35. 'product',
  36. 'learning',
  37. 'project',
  38. 'project-intelligence',
  39. ],
  40. },
  41. };
  42. // Map user-facing profile names → internal profile names
  43. const PROFILE_MAP = {
  44. 'essential': 'core',
  45. 'standard': 'core',
  46. 'extended': 'full',
  47. 'specialized': 'full',
  48. 'all': 'full',
  49. 'core': 'core',
  50. 'full': 'full',
  51. };
  52. // Colors
  53. const c = {
  54. reset: '\x1b[0m',
  55. red: '\x1b[31m',
  56. green: '\x1b[32m',
  57. yellow: '\x1b[33m',
  58. blue: '\x1b[34m',
  59. };
  60. const log = {
  61. info: (msg) => console.log(`${c.blue}ℹ${c.reset} ${msg}`),
  62. success: (msg) => console.log(`${c.green}✓${c.reset} ${msg}`),
  63. warning: (msg) => console.log(`${c.yellow}⚠${c.reset} ${msg}`),
  64. error: (msg) => console.error(`${c.red}✗${c.reset} ${msg}`),
  65. };
  66. function checkDependencies() {
  67. try {
  68. execSync('command -v git', { stdio: 'ignore' });
  69. } catch {
  70. log.error('git is required but not found.');
  71. log.info('Install: brew install git (Mac) or sudo apt install git (Linux)');
  72. process.exit(1);
  73. }
  74. }
  75. /**
  76. * Download context via git sparse-checkout.
  77. * Returns the commit SHA of the downloaded content.
  78. */
  79. function downloadContext(categories, contextDir) {
  80. const tempDir = mkdtempSync(join(os.tmpdir(), 'oac-context-'));
  81. try {
  82. log.info(`Downloading from ${GITHUB_REPO}...`);
  83. log.info('Cloning repository...');
  84. execSync(
  85. `git clone --depth 1 --filter=blob:none --sparse https://github.com/${GITHUB_REPO}.git "${tempDir}"`,
  86. { stdio: 'pipe' }
  87. );
  88. const commitSha = execSync(`git -C "${tempDir}" rev-parse HEAD`, { encoding: 'utf-8' }).trim();
  89. log.info('Configuring sparse checkout...');
  90. const sparsePaths = [
  91. ...categories.map(cat => `${CONTEXT_SOURCE_PATH}/${cat}`),
  92. `${CONTEXT_SOURCE_PATH}/navigation.md`,
  93. ];
  94. execSync(
  95. `git -C "${tempDir}" sparse-checkout set --skip-checks ${sparsePaths.join(' ')}`,
  96. { stdio: 'pipe' }
  97. );
  98. log.info('Copying context files...');
  99. mkdirSync(contextDir, { recursive: true });
  100. const sourceDir = join(tempDir, CONTEXT_SOURCE_PATH);
  101. if (!existsSync(sourceDir)) {
  102. throw new Error('Context directory not found in repository');
  103. }
  104. execSync(`cp -r "${sourceDir}/"* "${contextDir}/"`, { stdio: 'pipe' });
  105. const fileCount = execSync(`find "${contextDir}" -type f | wc -l`, { encoding: 'utf-8' }).trim();
  106. log.success(`Downloaded ${fileCount.trim()} files`);
  107. return commitSha;
  108. } catch (error) {
  109. log.error('Failed to download context');
  110. if (error instanceof Error) log.error(error.message);
  111. process.exit(1);
  112. } finally {
  113. rmSync(tempDir, { recursive: true, force: true });
  114. }
  115. }
  116. function createManifest(profile, categories, commitSha, contextDir, manifestFile) {
  117. const files = {};
  118. for (const category of categories) {
  119. const categoryPath = join(contextDir, category);
  120. if (existsSync(categoryPath)) {
  121. files[category] = parseInt(
  122. execSync(`find "${categoryPath}" -type f | wc -l`, { encoding: 'utf-8' }).trim(),
  123. 10
  124. );
  125. }
  126. }
  127. const manifest = {
  128. version: '1.0.0',
  129. profile,
  130. source: {
  131. repository: GITHUB_REPO,
  132. branch: GITHUB_BRANCH,
  133. commit: commitSha,
  134. downloaded_at: new Date().toISOString(),
  135. },
  136. categories,
  137. files,
  138. };
  139. mkdirSync(join(manifestFile, '..'), { recursive: true });
  140. writeFileSync(manifestFile, JSON.stringify(manifest, null, 2));
  141. log.success(`Manifest created: ${manifestFile}`);
  142. }
  143. function showUsage() {
  144. console.log(`
  145. Usage: node install-context.js [OPTIONS]
  146. Downloads OAC context files. Requirements: node, git (nothing else to install)
  147. Works on Mac, Linux, and Windows.
  148. OPTIONS:
  149. --profile=NAME Profile: essential, standard, extended, all (default: standard)
  150. --global Install to ~/.claude/context/ (all projects share it)
  151. --force Re-download even if already installed
  152. --dry-run Show what would be installed without downloading
  153. --help Show this help
  154. PROFILES:
  155. essential/standard Core context (core + openagents-repo)
  156. extended/all Full context (all categories)
  157. SCOPE:
  158. default (no flag) Installs to .claude/context/ in the current project
  159. --global Installs to ~/.claude/context/ for all projects
  160. `);
  161. }
  162. function main() {
  163. const args = process.argv.slice(2);
  164. let profileName = 'standard';
  165. let customCategories = [];
  166. let isGlobal = false;
  167. let force = false;
  168. let dryRun = false;
  169. for (const arg of args) {
  170. if (arg === '--help' || arg === '-h') {
  171. showUsage();
  172. process.exit(0);
  173. } else if (arg === '--force') {
  174. force = true;
  175. } else if (arg === '--dry-run') {
  176. dryRun = true;
  177. } else if (arg === '--global') {
  178. isGlobal = true;
  179. } else if (arg.startsWith('--profile=')) {
  180. profileName = arg.split('=')[1];
  181. if (!PROFILE_MAP[profileName]) {
  182. log.error(`Unknown profile: ${profileName}`);
  183. log.info(`Valid profiles: ${Object.keys(PROFILE_MAP).join(', ')}`);
  184. process.exit(1);
  185. }
  186. } else if (arg.startsWith('--category=')) {
  187. customCategories.push(arg.split('=')[1]);
  188. } else if (PROFILE_MAP[arg]) {
  189. profileName = arg;
  190. } else {
  191. log.error(`Unknown argument: ${arg}`);
  192. showUsage();
  193. process.exit(1);
  194. }
  195. }
  196. // Resolve install targets based on scope
  197. const installRoot = isGlobal ? GLOBAL_ROOT : join(PROJECT_ROOT, '.claude');
  198. const CONTEXT_DIR = join(installRoot, 'context');
  199. const MANIFEST_FILE = join(installRoot, '.context-manifest.json');
  200. const scopeLabel = isGlobal ? 'global (~/.claude/context)' : 'project (.claude/context)';
  201. const categories = customCategories.length > 0
  202. ? (profileName = 'custom', customCategories)
  203. : PROFILES[PROFILE_MAP[profileName] || 'core'].categories;
  204. // Already installed?
  205. if (existsSync(MANIFEST_FILE) && !force) {
  206. log.warning(`Context already installed at ${scopeLabel}. Use --force to reinstall.`);
  207. try {
  208. const manifest = JSON.parse(readFileSync(MANIFEST_FILE, 'utf-8'));
  209. log.info(`Profile: ${manifest.profile}, installed: ${manifest.source?.downloaded_at?.slice(0, 10)}`);
  210. } catch { /* ignore */ }
  211. process.exit(0);
  212. }
  213. checkDependencies();
  214. console.log('');
  215. log.info(`Scope: ${scopeLabel}`);
  216. log.info(`Profile: ${profileName}`);
  217. log.info(`Categories: ${categories.join(', ')}`);
  218. log.info(`Target: ${CONTEXT_DIR}`);
  219. console.log('');
  220. if (dryRun) {
  221. log.info('Dry run — no files downloaded');
  222. return;
  223. }
  224. const commitSha = downloadContext(categories, CONTEXT_DIR);
  225. createManifest(profileName, categories, commitSha, CONTEXT_DIR, MANIFEST_FILE);
  226. if (isGlobal) {
  227. log.info('Global install — no .oac.json needed (discovery chain finds ~/.claude/context automatically)');
  228. } else {
  229. const oacJson = join(PROJECT_ROOT, '.oac.json');
  230. if (!existsSync(oacJson)) {
  231. writeFileSync(oacJson, JSON.stringify({ version: '1', context: { root: '.claude/context' } }, null, 2));
  232. log.success('.oac.json created at project root');
  233. } else {
  234. log.info('.oac.json already exists — skipping');
  235. }
  236. }
  237. console.log('');
  238. log.success('Context installation complete!');
  239. log.info(`Scope: ${scopeLabel}`);
  240. log.info(`Context: ${CONTEXT_DIR}`);
  241. log.info(`Manifest: ${MANIFEST_FILE}`);
  242. console.log('');
  243. }
  244. main();