Skip to content
Back to search

benai-skills

MarketplaceWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/BenAIOS/benai-skills with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/BenAIOS/benai-skills'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/naveedharri--benai-skills/badge.svg)](/listings/naveedharri--benai-skills)

HTML

<a href="/listings/naveedharri--benai-skills"><img src="/api/listings/naveedharri--benai-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# Add marketplace
/plugin marketplace add BenAIOS/benai-skills

# Install a department plugin
/plugin install marketing@benai-skills
/plugin install sales@benai-skills
/plugin install operations@benai-skills
/plugin install creative@benai-skills
/plugin install product@benai-skills
/plugin install youtube@benai-skills

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 506 lines
  1. {
  2. "name": "benai-skills",
  3. "owner": {
  4. "name": "BenAIOS"
  5. },
  6. "metadata": {
  7. "description": "Expert automation plugins that turn Claude into a specialist for your team. Install by department to get skills for marketing, sales, operations, creative, and product workflows.",
  8. "version": "1.23.2"
  9. },
  10. "plugins": [
  11. {
  12. "name": "benai-marketing",
  13. "displayName": "BenAI Marketing",
  14. "source": "./plugins/benai-marketing",
  15. "description": "The BenAI marketing OS as skills: research, copywriting in Ben's voice, design systems, carousels, thumbnails, video editing, and analytics. competitor-radar and analytics-dashboard are schedule-ready.",
  16. "version": "1.5.5",
  17. "author": {
  18. "name": "BenAI"
  19. },
  20. "keywords": [
  21. "marketing",
  22. "content-research",
  23. "market-intelligence-report",
  24. "competitor-radar",
  25. "voice-builder",
  26. "bens-voice",
  27. "linkedin",
  28. "newsletter",
  29. "design-system",
  30. "carousel",
  31. "thumbnail",
  32. "video-editor",
  33. "analytics-dashboard"
  34. ]
  35. },
  36. {
  37. "name": "benai-sales",
  38. "displayName": "BenAI Sales",
  39. "source": "./plugins/benai-sales",
  40. "description": "The BenAI sales OS as skills: lead generation, qualification and research, CRM mining, LinkedIn engagers, email personalization, call prep, one-pagers, pipeline reviews, post-disco proposals, rep grading, win/loss analysis, and sales assets.",
  41. "version": "1.1.1",
  42. "author": {
  43. "name": "BenAI",
  44. "url": "https://benai.co"
  45. },
  46. "keywords": [
  47. "sales",
  48. "lead-generation",
  49. "outreach",
  50. "crm",
  51. "call-prep",
  52. "pipeline",
  53. "proposals"
  54. ]
  55. },
  56. {
  57. "name": "all-skills",
  58. "displayName": "All Skills",
  59. "source": "./plugins/all-skills",
  60. "description": "Every BenAI skill in one install. All 130 skills across marketing, sales, SEO, ads, design, YouTube, creative, operations, second-brain OS, Baalda OS, Marketing OS, and general productivity. Add this one plugin to get the complete library.",
  61. "version": "1.21.2",
  62. "author": {
  63. "name": "BenAI"
  64. },
  65. "keywords": [
  66. "all",
  67. "everything",
  68. "complete",
  69. "bundle",
  70. "marketing",
  71. "sales",
  72. "seo",
  73. "ads",
  74. "design",
  75. "youtube",
  76. "productivity",
  77. "second-brain",
  78. "baalda"
  79. ]
  80. },
  81. {
  82. "name": "content",
  83. "displayName": "Content",
  84. "source": "./plugins/content",
  85. "description": "A modular content engine, one skill per job: /research a topic, turn it into a /linkedin post and a /newsletter in Ben's voice, then generate on-brand /visual graphics to match.",
  86. "version": "1.0.3",
  87. "author": {
  88. "name": "BenAI"
  89. },
  90. "keywords": [
  91. "content",
  92. "research",
  93. "linkedin",
  94. "newsletter",
  95. "visual",
  96. "infographic",
  97. "repurpose",
  98. "pipeline",
  99. "writing"
  100. ]
  101. },
  102. {
  103. "name": "marketing",
  104. "source": "./plugins/marketing",
  105. "description": "Rank higher and grow organic traffic with programmatic SEO, technical audits, and Search Console optimization. Create email sequences that convert, build compelling case studies, and generate professional infographics. Repurpose YouTube content into LinkedIn posts, newsletters, GIFs, and visual diagrams.",
  106. "version": "1.0.4",
  107. "author": {
  108. "name": "BenAI"
  109. },
  110. "keywords": [
  111. "seo",
  112. "email",
  113. "marketing",
  114. "content",
  115. "case-study",
  116. "infographic",
  117. "youtube",
  118. "linkedin",
  119. "newsletter",
  120. "repurpose",
  121. "gif"
  122. ]
  123. },
  124. {
  125. "name": "managed-agents",
  126. "source": "./plugins/managed-agents",
  127. "description": "Create and run Anthropic Managed Agents from Claude Code. Walks through the lifecycle via the REST API: agent, environment, vault, MCP OAuth credentials, session, first message. Generic builder, no preset template.",
  128. "version": "1.0.2",
  129. "author": {
  130. "name": "BenAI"
  131. },
  132. "keywords": [
  133. "managed-agents",
  134. "anthropic",
  135. "agents-api",
  136. "mcp",
  137. "autonomous-agent",
  138. "session",
  139. "vault",
  140. "environment"
  141. ]
  142. },
  143. {
  144. "name": "operations",
  145. "source": "./plugins/operations",
  146. "description": "Build, test, and deploy n8n workflows through incremental REST API automation. Convert discovery call transcripts into implementation-ready automation blueprints.",
  147. "version": "1.0.1",
  148. "author": {
  149. "name": "BenAI"
  150. },
  151. "keywords": [
  152. "n8n",
  153. "workflow",
  154. "automation",
  155. "operations"
  156. ]
  157. },
  158. {
  159. "name": "creative",
  160. "source": "./plugins/creative",
  161. "description": "Edit and render videos with FFmpeg and Remotion, from stitching and transitions to captions and teasers. Design presentations in Excalidraw and generate AI-powered infographics.",
  162. "version": "1.0.1",
  163. "author": {
  164. "name": "BenAI"
  165. },
  166. "keywords": [
  167. "video",
  168. "excalidraw",
  169. "infographic",
  170. "creative",
  171. "design"
  172. ]
  173. },
  174. {
  175. "name": "product",
  176. "source": "./plugins/product",
  177. "description": "Design presentations, pitch decks, and process diagrams collaboratively in Excalidraw. Turn discovery call transcripts into structured automation blueprints your team can implement.",
  178. "version": "1.0.1",
  179. "author": {
  180. "name": "BenAI"
  181. },
  182. "keywords": [
  183. "excalidraw",
  184. "product",
  185. "blueprint",
  186. "automation"
  187. ]
  188. },
  189. {
  190. "name": "youtube",
  191. "source": "./plugins/youtube",
  192. "description": "Plan, brief, and prepare YouTube videos from idea to filming-ready. Create video briefs, generate topic ideas, optimize titles and thumbnails, build structured outlines, write scripts, and design on-screen excalidraw visuals.",
  193. "version": "1.1.9",
  194. "author": {
  195. "name": "BenAI"
  196. },
  197. "keywords": [
  198. "youtube",
  199. "video",
  200. "brief",
  201. "ideation",
  202. "scripting",
  203. "thumbnail",
  204. "title",
  205. "excalidraw",
  206. "content"
  207. ]
  208. },
  209. {
  210. "name": "youtube-publishing",
  211. "displayName": "YouTube Publishing",
  212. "source": "./plugins/youtube-publishing",
  213. "description": "The Ben AI YouTube pipeline after the edit: Studio wizard to Unlisted, UTM links, Bitly import, chapters and tags, description, then repurposing into LinkedIn, newsletter, Circle post or course, and clips.",
  214. "version": "4.0.2",
  215. "author": {
  216. "name": "BenAI"
  217. },
  218. "keywords": [
  219. "youtube",
  220. "publishing",
  221. "utm",
  222. "bitly",
  223. "chapters",
  224. "tags",
  225. "repurposing",
  226. "linkedin",
  227. "newsletter",
  228. "circle",
  229. "clips"
  230. ]
  231. },
  232. {
  233. "name": "seo",
  234. "source": "./plugins/seo",
  235. "description": "Complete SEO toolkit via /seo command: full site audits with parallel subagents, technical SEO, E-E-A-T content quality, schema, sitemaps, image optimization, AI search/GEO, programmatic SEO, competitor pages, hreflang, and Search Console optimization.",
  236. "version": "1.0.1",
  237. "author": {
  238. "name": "BenAI"
  239. },
  240. "keywords": [
  241. "seo",
  242. "audit",
  243. "schema",
  244. "e-e-a-t",
  245. "geo",
  246. "programmatic-seo",
  247. "hreflang",
  248. "gsc",
  249. "core-web-vitals",
  250. "technical-seo",
  251. "content-quality"
  252. ]
  253. },
  254. {
  255. "name": "ads",
  256. "source": "./plugins/ads",
  257. "description": "Paid ads toolkit (14 skills + 6 audit subagents). Covers Google, Meta, LinkedIn, TikTok, YouTube, and Microsoft Ads. Includes audits, budget allocation (70/20/10), creative + brand context, landing pages, strategic planning, and competitive intel.",
  258. "version": "1.1.1",
  259. "author": {
  260. "name": "BenAI"
  261. },
  262. "keywords": [
  263. "ads",
  264. "ppc",
  265. "google-ads",
  266. "meta-ads",
  267. "facebook-ads",
  268. "linkedin-ads",
  269. "tiktok-ads",
  270. "youtube-ads",
  271. "microsoft-ads",
  272. "audit",
  273. "budget",
  274. "creative",
  275. "landing-page",
  276. "competitor",
  277. "brand-context",
  278. "infographic"
  279. ]
  280. },
  281. {
  282. "name": "design",
  283. "source": "./plugins/design",
  284. "description": "Premium frontend design skills that override default AI design biases. Includes a configurable design system with anti-slop rules for React/Next.js/Tailwind, aesthetic variants (soft, minimalist, brutalist), project redesign auditing, Google Stitch integration, and full-output enforcement.",
  285. "version": "1.0.1",
  286. "author": {
  287. "name": "BenAI"
  288. },
  289. "keywords": [
  290. "design",
  291. "frontend",
  292. "ui",
  293. "ux",
  294. "tailwind",
  295. "react",
  296. "nextjs",
  297. "framer-motion",
  298. "redesign",
  299. "brutalist",
  300. "minimalist",
  301. "anti-slop"
  302. ]
  303. },
  304. {
  305. "name": "higgsfield",
  306. "source": "./plugins/higgsfield",
  307. "description": "Generate on-brand YouTube thumbnails and in-video visuals (slides) using Higgsfield via reference images. Includes youtube-thumbnail-generate (creative ideation across variants, locked Ben face) and generate-visual (single slides or progressive-disclosure sequences for tutorial videos).",
  308. "version": "2.1.1",
  309. "author": {
  310. "name": "BenAI"
  311. },
  312. "keywords": [
  313. "higgsfield",
  314. "youtube",
  315. "thumbnail",
  316. "image-generation",
  317. "ben-van-sprundel",
  318. "nano-banana"
  319. ]
  320. },
  321. {
  322. "name": "agentic-os",
  323. "displayName": "Agentic OS",
  324. "source": "./plugins/agentic-os",
  325. "description": "Set up an agentic OS \u2014 inside an Obsidian vault (command-center dashboard + bundled plugins) or as a standalone Next.js web dashboard with live MCP integrations and optional Railway deploy. Includes /os-mcp to self-host the Relay MCP server.",
  326. "version": "1.0.1",
  327. "author": {
  328. "name": "BenAI"
  329. },
  330. "keywords": [
  331. "agentic-os",
  332. "dashboard",
  333. "command-center",
  334. "obsidian",
  335. "nextjs",
  336. "mcp",
  337. "railway",
  338. "second-brain",
  339. "relay"
  340. ]
  341. },
  342. {
  343. "name": "obsidian",
  344. "source": "./plugins/obsidian",
  345. "description": "Turn any folder into an AI-powered second brain. Includes /os-setup, /agentic-os-setup (command-center dashboard inside Obsidian OR standalone Next.js web app), /os-optimizer (10-framework audit, now including F10 Claude 5 rule rewriting), /os-operator, /os-mcp, and /team-os.",
  346. "version": "3.11.3",
  347. "author": {
  348. "name": "BenAI"
  349. },
  350. "keywords": [
  351. "personal-assistant",
  352. "business-os",
  353. "team-os",
  354. "second-brain",
  355. "obsidian",
  356. "memory",
  357. "tasks",
  358. "meetings",
  359. "daily-review",
  360. "output-styles",
  361. "session-management",
  362. "productivity",
  363. "vault-audit",
  364. "scheduling"
  365. ]
  366. },
  367. {
  368. "name": "baalda-os",
  369. "displayName": "Baalda OS",
  370. "source": "./plugins/baalda-os",
  371. "description": "Turn a Baalda vault into an AI-operated second brain. Four skills: /setup bootstraps the structure and runs onboarding, /optimizer runs a 10-framework audit including Claude 5 rule rewriting, /operator builds and schedules the agent that keeps the vault current, and /baalda-guide answers any question about Baalda in plain language. Setup, optimizer and operator keep every note's doc_id intact.",
  372. "version": "2.1.2",
  373. "author": {
  374. "name": "BenAI"
  375. },
  376. "keywords": [
  377. "baalda",
  378. "second-brain",
  379. "baalda-os",
  380. "markdown",
  381. "local-first",
  382. "vault-audit",
  383. "productivity",
  384. "product-guide",
  385. "faq"
  386. ]
  387. },
  388. {
  389. "name": "autoresearch",
  390. "source": "./plugins/autoresearch",
  391. "description": "Autonomous optimization loop \u2014 iterates on prompts, skills, templates, or code overnight. Two evaluation modes: deterministic (eval.py with proxy heuristics) for mechanical checks, or AI judge (LLM rubric scoring) for creative/subjective quality. Uses 4-way agent separation for unbiased evaluation.",
  392. "version": "1.0.1",
  393. "author": {
  394. "name": "BenAI"
  395. },
  396. "keywords": [
  397. "autoresearch",
  398. "optimization",
  399. "eval",
  400. "iteration",
  401. "prompt-engineering",
  402. "self-improving",
  403. "overnight",
  404. "assertions"
  405. ]
  406. },
  407. {
  408. "name": "aios",
  409. "displayName": "AIOS",
  410. "source": "./plugins/aios",
  411. "description": "Set up an AI OS at the tier that fits \u2014 Skill OS (your entire second brain inside one Claude skill, zero infra) or Cloud OS (synced via Google Drive, OneDrive, iCloud, or Dropbox). Shares one folder structure with the Local OS (Obsidian) tier so you can graduate between them.",
  412. "version": "1.0.2",
  413. "author": {
  414. "name": "BenAI"
  415. },
  416. "keywords": [
  417. "ai-os",
  418. "aios",
  419. "skill-os",
  420. "cloud-os",
  421. "second-brain",
  422. "google-drive",
  423. "onedrive",
  424. "icloud",
  425. "dropbox",
  426. "sync"
  427. ]
  428. },
  429. {
  430. "name": "meta",
  431. "source": "./plugins/meta",
  432. "description": "General-purpose AI productivity toolkit: browser automation, audio transcription, deep research, decision frameworks, fact-checking, file organization, prompt engineering, MCP server building, and more. 17 community skills in one install.",
  433. "version": "1.6.3",
  434. "author": {
  435. "name": "Community"
  436. },
  437. "keywords": [
  438. "browser-automation",
  439. "transcription",
  440. "deep-research",
  441. "decision-making",
  442. "fact-checking",
  443. "file-organization",
  444. "prompt-engineering",
  445. "humanizer",
  446. "mcp",
  447. "openrouter",
  448. "productivity"
  449. ]
  450. },
  451. {
  452. "name": "marketing-os",
  453. "displayName": "Marketing OS",
  454. "source": "./plugins/marketing-os",
  455. "description": "Set up and operate a Marketing OS: a markdown second brain that is the single source of truth every marketing skill reads, so the ICP, offer and voice live in one place. Four OS-native skills sit on top: newsletter, carousel, market intel and research.",
  456. "version": "1.3.2",
  457. "author": {
  458. "name": "BenAI"
  459. },
  460. "keywords": [
  461. "marketing-os",
  462. "second-brain",
  463. "marketing-operations",
  464. "content-operations",
  465. "routines",
  466. "scheduled-tasks",
  467. "dashboard",
  468. "brand-voice",
  469. "icp",
  470. "single-source-of-truth",
  471. "repurposing",
  472. "analytics"
  473. ]
  474. },
  475. {
  476. "name": "local-ai",
  477. "displayName": "Local AI",
  478. "source": "./plugins/local-ai",
  479. "description": "From nothing to a working AI setup you own. Scans the machine for models that fit, installs and wires up the right app with consent at every download, shares it over a private URL, and rents a cloud GPU when a model is too big. Needs shell access.",
  480. "version": "1.6.3",
  481. "author": {
  482. "name": "BenAI"
  483. },
  484. "keywords": [
  485. "local-ai",
  486. "local-llm",
  487. "ollama",
  488. "open-webui",
  489. "lm-studio",
  490. "goose",
  491. "anythingllm",
  492. "mcp",
  493. "skills",
  494. "hardware-scan",
  495. "vram",
  496. "privacy",
  497. "offline-ai",
  498. "claude-code",
  499. "ngrok",
  500. "tunnel",
  501. "share-local-ai",
  502. "team-access"
  503. ]
  504. }
  505. ]
  506. }
README.md · README · 314 lines
  1. # BenAI Skills
  2. Expert automation skills for Claude Code, organized by department.
  3. ## Installation
  4. ```bash
  5. # Add marketplace
  6. /plugin marketplace add BenAIOS/benai-skills
  7. # Install a department plugin
  8. /plugin install marketing@benai-skills
  9. /plugin install sales@benai-skills
  10. /plugin install operations@benai-skills
  11. /plugin install creative@benai-skills
  12. /plugin install product@benai-skills
  13. /plugin install youtube@benai-skills
  14. ```
  15. ## Setup
  16. Some skills require API keys. Create a `.env` file in your project directory:
  17. ```bash
  18. # Quick setup
  19. curl -O https://raw.githubusercontent.com/BenAIOS/benai-skills/develop/.env.example
  20. mv .env.example .env
  21. # Edit .env and add your API keys
  22. ```
  23. Or copy from this repo's `.env.example` and fill in your keys.
  24. ### Required API Keys by Plugin
  25. | Plugin | Required Keys | Get Keys | Used By |
  26. |--------|---------------|----------|---------|
  27. | **Marketing** | `GEMINI_API_KEY`<br>`APIFY_TOKEN` | [Gemini](https://aistudio.google.com/apikey)<br>[Apify](https://console.apify.com) | `/infographic`<br>`/seo-audit`, `/programmatic-seo` |
  28. | **Creative** | `GEMINI_API_KEY` | [Gemini](https://aistudio.google.com/apikey) | `/infographic` |
  29. | **Operations** | `N8N_API_URL`<br>`N8N_API_KEY` | Your n8n instance | `/n8n` |
  30. **Important:** Add `.env` to your `.gitignore` to keep your API keys secure.
  31. ## Available Departments
  32. ### Marketing (11 skills)
  33. | Skill | Command | Purpose |
  34. |-------|---------|---------|
  35. | Programmatic SEO | `/programmatic-seo` | SEO-optimized pages at scale |
  36. | SEO Optimizing | `/seo-optimizing` | Data-driven SEO via Search Console |
  37. | SEO Audit | `/seo-audit` | Technical SEO audits (148 rules) |
  38. | Email Sequence | `/email-sequence` | Email sequences & drip campaigns |
  39. | Case Study | `/case-study` | Data-driven case studies |
  40. | Infographic | `/infographic` | AI-generated infographics |
  41. | LinkedIn Writer | `/linkedin-writer` | LinkedIn posts & carousels from content |
  42. | Newsletter Writer | `/newsletter-writer` | Newsletter editions from content |
  43. | Title Generation | `/title-generation` | Optimized YouTube video titles |
  44. | GIF Creator | `/gif-creator` | GIFs from video clips |
  45. | Excalidraw | `/excalidraw` | Presentations & diagrams |
  46. **Commands:** `/marketing` (skill overview), `/repurpose` (content repurposing workflow)
  47. ### BenAI Sales (14 skills)
  48. | Skill | Command | Purpose |
  49. |-------|---------|---------|
  50. | Lead Generation | `/lead-generation` | Source, qualify, enrich, and research B2B leads end to end |
  51. | CRM Prospect Mining | `/crm-prospect-mining` | Mine prospects from CRM lost/stalled stages |
  52. | LinkedIn Post Engagers | `/linkedin-post-engagers` | Scrape LinkedIn post commenters/reactors into a warm list |
  53. | Call Prep | `/call-prep` | Prep calls into a live BenAI-branded instant-ui dashboard |
  54. | Client One-Pager | `/client-onepager` | Personalize and deploy the client one-pager from the template |
  55. | Pipeline Review | `/pipeline-review` | Read-only pipeline stage review delivered to Slack |
  56. | Post-Disco Followup | `/post-disco-followup` | Post-discovery recap email + proposal from the transcript |
  57. | Setup Post-Disco | `/setup-post-disco` | One-time interactive setup for post-disco-followup |
  58. | Sales Rep Analyzer | `/sales-rep-analyzer` | Grade sales call performance with an instant-ui report |
  59. | Create an Asset | `/create-an-asset` | Tailored sales asset (landing page, deck, one-pager, demo) |
  60. | Email Personalization | `/email-personalization` | Hyper-personalized email icebreakers |
  61. | Lead Intelligence | `/lead-intelligence` | Deep-research leads via web & LinkedIn |
  62. | Lead Qualification | `/lead-qualification` | Qualify & score leads against ICP |
  63. | Win/Loss Analysis | `/win-loss-analysis` | Analyze won vs lost deal patterns |
  64. **Agents:** `lead-qualifier`, `lead-researcher`, `icebreaker-writer`, `linkedin-scraper`
  65. ### Operations (2 skills)
  66. | Skill | Command | Purpose |
  67. |-------|---------|---------|
  68. | n8n Automation | `/n8n` | n8n workflow automation |
  69. | n8n Blueprint Generator | `/n8n-prd-generator` | Automation blueprints from calls |
  70. **Commands:** `/operations` (skill overview)
  71. ### Creative (3 skills)
  72. | Skill | Command | Purpose |
  73. |-------|---------|---------|
  74. | Video | `/video` | Video editing (FFmpeg/Remotion) |
  75. | Excalidraw | `/excalidraw` | Presentations & diagrams |
  76. | Infographic | `/infographic` | AI-generated infographics |
  77. **Commands:** `/creative` (skill overview)
  78. ### Product (2 skills)
  79. | Skill | Command | Purpose |
  80. |-------|---------|---------|
  81. | Excalidraw | `/excalidraw` | Presentations & diagrams |
  82. | n8n Blueprint Generator | `/n8n-prd-generator` | Automation blueprints from calls |
  83. **Commands:** `/product` (skill overview)
  84. ### YouTube (7 skills)
  85. | Skill | Command | Purpose |
  86. |-------|---------|---------|
  87. | YouTube Brief | `/youtube-brief` | Structured video briefs |
  88. | YouTube Ideation | `/youtube-ideation` | Video topic generation |
  89. | YouTube Packaging | `/youtube-packaging` | Titles & thumbnails for CTR |
  90. | YouTube Outline | `/youtube-outline` | Video structure & visual planning |
  91. | YouTube Scripting | `/youtube-scripting` | Scripts & bullet points for filming |
  92. | YouTube Excalidraw | `/youtube-excalidraw` | On-screen excalidraw visuals |
  93. | Title Generation | `/title-generation` | Optimized YouTube video titles |
  94. **Commands:** `/youtube` (skill overview)
  95. ### YouTube Publishing (14 skills)
  96. | Skill | Command | Purpose |
  97. |-------|---------|---------|
  98. | youtube-ship | `/youtube-ship` | Runs the whole publishing chain for one video, in order, from a Ship Brief |
  99. | youtube-studio-setup | `/youtube-studio-setup` | Stage 1: Studio draft to saved Unlisted video (title, thumbnails, A/B test, wizard) |
  100. | benai-utm-creator | `/benai-utm-creator` | Stage 2: six UTM links, Bitly backhalfs, campaign code, Bitly import CSV |
  101. | youtube-link-setup | `/youtube-link-setup` | Stage 3: Bitly import, Kit lead-magnet page, n8n registration, link verification |
  102. | youtube-chapters-tags | `/youtube-chapters-tags` | Stage 4: chapters with accurate timestamps plus the tag string |
  103. | youtube-description | `/youtube-description` | Stage 5: description from template into Studio, Notion card to Ready to publish |
  104. | yt-ingestion | `/yt-ingestion` | Fetch a video's raw artifacts: file, transcript, word timings, thumbnail |
  105. | video-cutter | `/video-cutter` | Sentence-aligned clips at silence-midpoint boundaries |
  106. | yt-to-community | `/yt-to-community` | Circle community announcement draft in Ben's voice |
  107. | yt-to-course | `/yt-to-course` | Structured Circle course package with lesson clips |
  108. | linkedin-writer | `/linkedin-writer` | LinkedIn posts & carousels from content |
  109. | newsletter-writer | `/newsletter-writer` | Newsletter editions from content |
  110. | video-repurposing | `/video-repurposing` | Captioned platform-ready clips with FFmpeg and Remotion |
  111. | humanizer | `/humanizer` | Remove signs of AI-generated writing |
  112. **Agents:** `video-cutter-agent`, `yt-ingestion-agent`
  113. Everything after the edit: five publish-prep stages with four human checkpoints, then repurposing every published video. Uses Claude in Chrome for every YouTube Studio read and write. One-time operator setup lives in `youtube-ship/references/SETUP.md`.
  114. ### Marketing OS (8 skills)
  115. | Skill | Command | Purpose |
  116. |-------|---------|---------|
  117. | Marketing OS Setup | `/marketing-os-setup` | Build the Marketing OS end to end |
  118. | Marketing OS Routines | `/marketing-os-routines` | Register the routines, audit for silent failure |
  119. | Marketing OS Dashboard | `/marketing-os-dashboard` | Rebuild and deploy the control center |
  120. | OS Optimizer | `/os-optimizer` | Framework audit of the vault |
  121. | OS Operator | `/os-operator` | Recurring Operator prompt |
  122. | OS MCP | `/os-mcp` | Relay MCP on your own Railway account |
  123. | Team OS | `/team-os` | BenAI Relay fork for a shared OS |
  124. | Instant UI | `/instant-ui` | Renders the OS and its reports as BenAI-branded HTML |
  125. The OS layer, not the marketing skills. Those live in the Marketing, Content, YouTube, SEO, and Ads plugins.
  126. `/marketing-os-setup` builds a markdown second brain that becomes the single source of truth every marketing skill reads. The problem it solves is concrete and measurable in this repo: `icp-ideal-customer-profile.md` and `what-we-do-offer.md` exist as five separate physical copies across the marketing plugins, plus three more inside the newsletter writers. Update one and seven go stale.
  127. Ten folders (Context, Channels, Content, Campaigns, Intelligence, Analytics, Resources, Daily, Dashboard, Routines), ten routine prompts that keep it current, and a self-contained six-tab dashboard. Setup walks five pillars in order: connectors, Context, structure, routines, dashboard. It is idempotent and safe to re-run.
  128. ---
  129. ### Baalda OS (3 skills)
  130. | Skill | Command | Purpose |
  131. |-------|---------|---------|
  132. | Baalda Setup | `/baalda-setup` | Bootstrap the second-brain structure inside a Baalda vault |
  133. | Baalda Optimizer | `/baalda-optimizer` | 9-framework vault audit — checkpoints first, keeps note identity |
  134. | Baalda Guide | `/baalda-guide` | Plain-language answers about Baalda — features, file formats, sync, sharing, AI/MCP, pricing |
  135. The second-brain OS for [Baalda](https://baalda.com), where notes are plain `.md` files on disk that
  136. teammates edit together in real time and an AI edits directly. Sharing, real-time collaboration and
  137. the MCP endpoint are product features with their own UI, so setup and optimizer cover what the app can't
  138. decide for you: how the vault is structured, and keeping it clean as it grows. The guide answers
  139. "does Baalda do X?" questions for non-technical teammates from checked reference notes.
  140. ---
  141. ### n8n Automation
  142. Build, test, and deploy n8n workflows via REST API with incremental testing. Includes node references for 40+ common nodes, JavaScript/Python Code node patterns, expression syntax, and credential management. Also includes the **n8n Blueprint Generator** (`/n8n-prd-generator`) for converting discovery call transcripts into n8n automation blueprints.
  143. **Requires:** `N8N_API_URL`, `N8N_API_KEY`, and `N8N_CREDENTIALS_TEMPLATE_URL` in your `.env` file (see Setup section above).
  144. ### Video Editing
  145. Video editing pipeline with FFmpeg and Remotion. Supports stitching, transitions, TikTok-style captions, teasers, transcription, title cards, and graphics generation.
  146. ### Excalidraw
  147. Create visual presentations, slide decks, and diagrams in Excalidraw. Supports generating `.excalidraw` JSON files or injecting slides directly into excalidraw.com via Chrome browser automation.
  148. ### Email Sequence
  149. Design email sequences including welcome/onboarding, lead nurture, re-engagement, post-purchase, and sales sequences. Includes copy guidelines and sequence templates.
  150. ### SEO Suite
  151. Three complementary SEO plugins:
  152. | Plugin | Role | Data Source |
  153. |--------|------|-------------|
  154. | **seo-audit** | Technical diagnosis — what's broken | seomator CLI |
  155. | **seo-optimizing** | Data-driven strategy — what to DO | Google Search Console API |
  156. | **programmatic-seo** | Scale content creation | Templates + data sources |
  157. **seo-audit** runs comprehensive technical SEO audits covering 16 categories and 148 rules using seomator CLI. Requires `@seomator/seo-audit` (installed automatically on first use).
  158. **seo-optimizing** uses real Google Search Console data to find striking-distance keywords, fix low-CTR pages, detect keyword cannibalization, and execute content optimizations. Three data paths:
  159. - **API path:** Service account + GSC API (up to 25,000 rows)
  160. - **Browser path:** Claude Code browser extension navigates GSC directly (zero setup)
  161. - **CSV path:** Manual export from GSC web UI
  162. **programmatic-seo** generates SEO-optimized pages at scale using templates and data sources with Webflow CMS integration.
  163. ### Infographic
  164. Generate professional infographics and visual content using Gemini AI image generation. Supports visual metaphors, brand guidelines, series creation, and iterative refinement.
  165. ### Content Repurposing
  166. Repurpose content into multiple formats via the `/repurpose` command in the Marketing plugin. **LinkedIn Writer** (`/linkedin-writer`) creates posts and carousels from existing content. **Newsletter Writer** (`/newsletter-writer`) transforms content into engaging newsletter editions. **Title Generation** (`/title-generation`) generates optimized YouTube video titles using proven CTR formulas. **GIF Creator** (`/gif-creator`) extracts and optimizes GIFs from video clips for social media sharing.
  167. ### Outbound Pipeline
  168. The BenAI Sales plugin includes a full B2B outbound pipeline (`/lead-generation`) that orchestrates four sub-agents in parallel: **lead-qualifier** scores leads against your ICP, **lead-researcher** gathers deep company intelligence, **linkedin-scraper** pulls LinkedIn profiles and posts via Apify, and **icebreaker-writer** generates hyper-personalized email openers from the collected intelligence.
  169. ## Project Structure
  170. ```
  171. benai-skills/
  172. ├── .claude-plugin/
  173. │ ├── marketplace.json
  174. │ └── skills-map.json # Defines which departments get which skills
  175. ├── shared-skills/ # Single source of truth for all skills
  176. │ ├── programmatic-seo/
  177. │ ├── seo-optimizing/
  178. │ ├── seo-audit/
  179. │ ├── email-sequence/
  180. │ ├── case-study/
  181. │ ├── infographic/
  182. │ ├── lead-research-assistant/
  183. │ ├── email-personalization/
  184. │ ├── lead-intelligence/
  185. │ ├── lead-qualification/
  186. │ ├── n8n-prd-generator/
  187. │ ├── n8n/
  188. │ ├── video/
  189. │ ├── excalidraw/
  190. │ ├── linkedin-writer/
  191. │ ├── newsletter-writer/
  192. │ ├── title-generation/
  193. │ └── gif-creator/
  194. ├── agents/ # Sub-agent definitions for orchestrated pipelines
  195. │ ├── lead-qualifier.md
  196. │ ├── lead-researcher.md
  197. │ ├── icebreaker-writer.md
  198. │ └── linkedin-scraper.md
  199. ├── commands/ # Static command .md files mapped in skills-map.json
  200. │ ├── marketing.md
  201. │ ├── sales.md
  202. │ ├── operations.md
  203. │ ├── creative.md
  204. │ ├── product.md
  205. │ ├── repurpose.md
  206. │ ├── outbound-pipeline.md
  207. │ └── youtube.md
  208. ├── plugins/ # Generated by sync-skills.sh — do not edit directly
  209. │ ├── marketing/
  210. │ ├── sales/
  211. │ ├── operations/
  212. │ ├── creative/
  213. │ ├── product/
  214. │ └── youtube/
  215. ├── sync-skills.sh # Generates plugins/ from shared-skills/ + skills-map.json
  216. ├── build-zips.sh # Builds distributable zips (runs sync first)
  217. ├── CLAUDE.md
  218. └── README.md
  219. ```
  220. Each department plugin follows the same structure:
  221. ```
  222. plugins/<department>/
  223. ├── .claude-plugin/
  224. │ └── plugin.json
  225. ├── commands/
  226. │ └── <command>.md # Mapped from commands/ via skills-map.json
  227. └── skills/ # Populated by sync-skills.sh
  228. └── <skill-name>/
  229. ├── SKILL.md
  230. └── references/
  231. ```
  232. ## Adding New Skills
  233. 1. Create the skill directory in `shared-skills/` with `SKILL.md` and optional `references/`
  234. 2. Add the skill to the relevant departments in `.claude-plugin/skills-map.json`
  235. 3. If needed, add command `.md` files in `commands/` and map them in `skills-map.json`
  236. 4. Run `./sync-skills.sh` to generate department plugins
  237. ## Editing Existing Skills
  238. 1. Edit the skill in `shared-skills/<skill>/` (never in `plugins/*/skills/`)
  239. 2. Run `./sync-skills.sh` to propagate changes
  240. **Before every push**, run `./sync-skills.sh` to ensure departments are in sync.
  241. ## Building Distributable Zips
  242. Run `./build-zips.sh` to generate downloadable zip files in `dist/`. The script runs `sync-skills.sh` first, then reads `marketplace.json` and creates:
  243. - One zip per department (standalone, installable individually)
  244. - `benai-skills-marketplace.zip` (all departments in one package)
  245. ## License
  246. BenAI
plugins/agentic-os/skills/agentic-os-obsidian/references/obsidian/dashboard-template.js · Bundled script · 3,580 lines · 3 findings marked
  1. /* eslint-disable */
  2. /**
  3. * Command-Center Dashboard — shared rendering module (CustomJS).
  4. * Installer substitutes values inside CONFIG. Do NOT edit code outside this.constructor.CONFIG
  5. * unless you know what you're doing; the renderer expects every config key.
  6. *
  7. * customJS class: `dashboard` (filename = class name).
  8. * Each dashboard .md does:
  9. * const { dashboard } = customJS;
  10. * await dashboard.render(dv, { scope: "team" | "profile" | "overview", name: "Alex" });
  11. */
  12. class dashboard {
  13. // ==================================================================
  14. // this.constructor.CONFIG — installer substitutes the __PLACEHOLDER__ values
  15. // ==================================================================
  16. static CONFIG = {
  17. ORG_NAME: "__ORG_NAME__",
  18. BRAND_LABEL: "__BRAND_LABEL__",
  19. BRAND_SUB: "__BRAND_SUB__",
  20. BRAND_MARK_PATH: "__BRAND_MARK_PATH__", // empty string to hide
  21. PROFILES: __PROFILES_JSON__, // ["Alex","Sam"]
  22. DEFAULT_PROFILE: "__DEFAULT_PROFILE__",
  23. PROFILE_FOLDER_PATTERN: "__PROFILE_FOLDER_PATTERN__", // e.g. "Team/{ORG}/Profiles/{name}"
  24. DAILY_SUBPATH: "__DAILY_SUBPATH__", // e.g. "Daily" — joined to profile folder
  25. TASKS_SUBPATH: "__TASKS_SUBPATH__", // e.g. "task-list" or "" to disable
  26. SNAPSHOTS_SUBPATH: "__SNAPSHOTS_SUBPATH__", // e.g. "snapshots"
  27. ROOT_DAILY_PATH: "__ROOT_DAILY_PATH__", // e.g. "Daily"
  28. OVERVIEW_FOLDERS: __OVERVIEW_FOLDERS_JSON__, // [["Projects/", "what it is", "Projects/CLAUDE"], ...]
  29. // Per-scope button registries. Each entry: { key, label, icon (emoji), cmd? OR prompt? }
  30. // cmd: Obsidian command id (e.g. "app:reload" or "obsidian-shellcommands:shell-command-<alias>")
  31. // prompt: Claude prompt string. Installer registers a shell-commands alias and wires the cmd.
  32. BUTTONS: __BUTTONS_JSON__,
  33. // Optional custom Claude-prompt actions wired to the in-app prompt-runner UI
  34. // (these are NOT the same as BUTTONS — these power the "Run prompt" sheet).
  35. CLAUDE_PROMPTS: __CLAUDE_PROMPTS_JSON__,
  36. // Vault Overview optional content (all default empty — fill in installer)
  37. SKILLS_FOLDER: "__SKILLS_FOLDER__", // e.g. "Plugins/skills" — empty hides Skills section
  38. SKILL_GROUPS: __SKILL_GROUPS_JSON__, // {"Group": ["skill-name", ...]}
  39. PROJECT_CATEGORIES:__PROJECT_CATEGORIES_JSON__, // ["Agency", "Content", ...] — empty hides Projects section
  40. CONNECTORS: __CONNECTORS_JSON__, // [["MCP name", "what it does"], ...]
  41. CHEATSHEET: __CHEATSHEET_JSON__, // [["label", "path or pattern"], ...]
  42. };
  43. // ===================================================================
  44. // this.constructor.CONFIG-DRIVEN PATH HELPERS
  45. // ===================================================================
  46. cfg() { return this.constructor.CONFIG; }
  47. profilePath(name) {
  48. return this.constructor.CONFIG.PROFILE_FOLDER_PATTERN
  49. .replace("{ORG}", this.constructor.CONFIG.ORG_NAME)
  50. .replace("{name}", name);
  51. }
  52. profileDailyPath(name) { return this.constructor.CONFIG.DAILY_SUBPATH ? `${this.profilePath(name)}/${this.constructor.CONFIG.DAILY_SUBPATH}` : ""; }
  53. profileTasksPath(name) { return this.constructor.CONFIG.TASKS_SUBPATH ? `${this.profilePath(name)}/${this.constructor.CONFIG.TASKS_SUBPATH}` : ""; }
  54. profileSnapshotsPath(name) { return this.constructor.CONFIG.SNAPSHOTS_SUBPATH ? `${this.profilePath(name)}/${this.constructor.CONFIG.SNAPSHOTS_SUBPATH}` : ""; }
  55. profileRunsPath(name) { return `${this.profilePath(name)}/runs.json`; }
  56. // ===================================================================
  57. // ENTRY
  58. // ===================================================================
  59. async render(dv, opts = {}) {
  60. const scope = opts.scope || "profile";
  61. const name = opts.name || this.constructor.CONFIG.DEFAULT_PROFILE;
  62. // Mount loading shell immediately so the canvas pre-load overlay
  63. // can hand off seamlessly to the JS loader.
  64. const root = dv.el("div", "", { cls: "cc-root cc-loading" });
  65. root.innerHTML = `
  66. <div class="cc-loader-shell">
  67. <div class="cc-loader-spinner"></div>
  68. <div class="cc-loader-text">Loading your agentic OS…</div>
  69. </div>`;
  70. try {
  71. // Load Frappe Charts in parallel with data queries
  72. const frappeReady = this.ensureFrappe();
  73. // Build dashboard
  74. let html;
  75. if (scope === "team") html = await this.buildTeamHTML(dv);
  76. else if (scope === "profile") html = await this.buildProfileHTML(dv, name);
  77. else if (scope === "overview")html = await this.buildOverviewHTML(dv);
  78. else throw new Error(`Unknown scope: ${scope}`);
  79. await frappeReady;
  80. root.innerHTML = html;
  81. root.classList.remove("cc-loading");
  82. this.wire(root);
  83. this.mountCharts(root);
  84. } catch (err) {
  85. console.error("[dashboard] render failed:", err);
  86. root.classList.remove("cc-loading");
  87. root.innerHTML = `
  88. <div style="padding:48px;font-family:'Space Grotesk',sans-serif;">
  89. <h2 style="margin:0 0 12px;color:#020309;">Dashboard error</h2>
  90. <p style="color:#020309;opacity:0.7;margin:0 0 16px;font-size:14px;">Something broke while rendering. Open the developer console (Cmd+Opt+I) for the full trace.</p>
  91. <pre style="background:#FAF3E3;border:2px solid #020309;border-radius:8px;padding:14px;font-size:12px;color:#020309;overflow:auto;white-space:pre-wrap;">${this.esc(err && err.stack || String(err))}</pre>
  92. </div>`;
  93. }
  94. }
  95. /** Lazy-load Frappe Charts (≈67KB) once per session. */
  96. async ensureFrappe() {
  97. if (window.frappe?.Chart) return window.frappe;
  98. if (window.__ccFrappeLoading) return window.__ccFrappeLoading;
  99. window.__ccFrappeLoading = (async () => {
  100. try {
  101. const code = await app.vault.adapter.read("Dashboard/lib/frappe-charts.min.js");
  102. new Function(code).call(window);
  103. } catch (e) {
  104. console.warn("[dashboard] Failed to load Frappe Charts:", e);
  105. }
  106. return window.frappe;
  107. })();
  108. return window.__ccFrappeLoading;
  109. }
  110. /** Find every [data-chart] element and instantiate the right Frappe chart. */
  111. mountCharts(root) {
  112. if (!window.frappe?.Chart) return;
  113. const BRAND = {
  114. dark: "#020309", canvas: "#FAF3E3", surface: "#FFFFFF",
  115. neutral: "#E5F5F9", primary: "#D2ECD0", accent: "#FDEEC4",
  116. alert: "#F3C1C0", green2: "#7FBE7C",
  117. };
  118. root.querySelectorAll("[data-chart]").forEach(el => {
  119. const kind = el.dataset.chart;
  120. let payload;
  121. try { payload = JSON.parse(el.dataset.payload || "{}"); } catch { payload = {}; }
  122. try {
  123. if (kind === "bar") {
  124. new window.frappe.Chart(el, {
  125. type: "bar",
  126. data: { labels: payload.labels, datasets: payload.datasets || [{ name: payload.name || "Files", values: payload.values }] },
  127. colors: payload.colors || [BRAND.dark],
  128. height: payload.height || 220,
  129. axisOptions: { xAxisMode: "tick", yAxisMode: "tick" },
  130. barOptions: { spaceRatio: 0.4, stacked: payload.stacked ? 1 : 0 },
  131. truncateLegends: true,
  132. animate: false,
  133. });
  134. } else if (kind === "line") {
  135. new window.frappe.Chart(el, {
  136. type: "line",
  137. data: { labels: payload.labels, datasets: payload.datasets || [{ name: payload.name || "Series", values: payload.values }] },
  138. colors: payload.colors || [BRAND.dark, BRAND.green2],
  139. height: payload.height || 220,
  140. lineOptions: { regionFill: 1, hideDots: 0, dotSize: 4, spline: payload.spline ? 1 : 0 },
  141. axisOptions: { xAxisMode: "tick" },
  142. animate: false,
  143. });
  144. } else if (kind === "sparkline") {
  145. new window.frappe.Chart(el, {
  146. type: "line",
  147. data: { labels: (payload.values || []).map(() => ""), datasets: [{ name: "", values: payload.values }] },
  148. colors: [payload.color || BRAND.dark],
  149. height: 70,
  150. lineOptions: { hideDots: 1, regionFill: 1, spline: 1 },
  151. axisOptions: { xAxisMode: "tick", yAxisMode: "tick" },
  152. animate: false,
  153. });
  154. } else if (kind === "heatmap") {
  155. new window.frappe.Chart(el, {
  156. type: "heatmap",
  157. data: { dataPoints: payload.dataPoints, start: new Date(payload.start), end: new Date(payload.end) },
  158. countLabel: payload.countLabel || "edits",
  159. colors: [BRAND.accent, BRAND.primary, BRAND.green2, BRAND.dark],
  160. discreteDomains: 0,
  161. });
  162. } else if (kind === "donut") {
  163. // Frappe pie chart with custom palette → reads as a donut/ring
  164. new window.frappe.Chart(el, {
  165. type: "donut",
  166. data: {
  167. labels: payload.labels || ["Done", "Remaining"],
  168. datasets: [{ values: payload.values }]
  169. },
  170. colors: payload.colors || [BRAND.dark, "rgba(2,3,9,0.10)"],
  171. height: payload.height || 160,
  172. maxSlices: payload.maxSlices || 6,
  173. animate: false,
  174. });
  175. } else if (kind === "pie") {
  176. new window.frappe.Chart(el, {
  177. type: "pie",
  178. data: {
  179. labels: payload.labels,
  180. datasets: [{ values: payload.values }]
  181. },
  182. colors: payload.colors || [BRAND.primary, BRAND.accent, BRAND.neutral, BRAND.alert, BRAND.green2, BRAND.dark],
  183. height: payload.height || 200,
  184. maxSlices: payload.maxSlices || 6,
  185. animate: false,
  186. });
  187. } else if (kind === "percentage") {
  188. new window.frappe.Chart(el, {
  189. type: "percentage",
  190. data: {
  191. labels: payload.labels,
  192. datasets: [{ values: payload.values }]
  193. },
  194. colors: payload.colors || [BRAND.primary, BRAND.accent, BRAND.neutral, BRAND.alert, BRAND.green2, BRAND.dark],
  195. height: payload.height || 80,
  196. barOptions: { height: 26, depth: 1 },
  197. animate: false,
  198. });
  199. }
  200. } catch (e) {
  201. console.warn("[dashboard] Frappe chart failed for", kind, e);
  202. }
  203. });
  204. }
  205. /** Execute an Obsidian command id with diagnostics + fallbacks.
  206. * Plugin updates sometimes change command-id formats; this tries the
  207. * canonical id first, then known variants, then a hard-coded fallback
  208. * (e.g. spawn `claude --dangerously-skip-permissions` directly for the
  209. * Launch Claude button). All steps log to the dev console so you can see
  210. * exactly what fired. */
  211. executeCommandSafe(cmd) {
  212. const registry = app?.commands?.commands || {};
  213. // Try the canonical id first
  214. if (registry[cmd]) {
  215. console.log("[dashboard] executing command:", cmd);
  216. return app.commands.executeCommandById(cmd);
  217. }
  218. console.warn(`[dashboard] command id "${cmd}" not registered. Trying variants…`);
  219. // Variant search: same suffix, any matching prefix
  220. const suffix = cmd.split(":").slice(1).join(":") || cmd;
  221. const variantId = Object.keys(registry).find(k => k.endsWith(suffix) || k.endsWith(cmd.replace(/^[^:]+:/, "")));
  222. if (variantId) {
  223. console.log("[dashboard] firing variant id:", variantId);
  224. return app.commands.executeCommandById(variantId);
  225. }
  226. // Launch Claude — must open INSIDE Obsidian (integrated terminal), never
  227. // a system Terminal.app window. Strategy: (1) find any registered terminal
  228. // command that mentions the "claude" profile and fire it; (2) fall back to
  229. // the terminal plugin's API to spawn the "claude" profile directly at the
  230. // vault root; (3) as a final fallback, open any integrated terminal at
  231. // vault root and tell the user to run claude manually.
  232. if (cmd.includes("claude")) {
  233. const claudeCmdId = Object.keys(registry).find(k =>
  234. k.startsWith("terminal:") && /claude/i.test(k)
  235. );
  236. if (claudeCmdId) {
  237. console.log("[dashboard] firing claude terminal command:", claudeCmdId);
  238. return app.commands.executeCommandById(claudeCmdId);
  239. }
  240. const termPlugin = app?.plugins?.plugins?.terminal;
  241. const cwd = this.vaultBasePath();
  242. try {
  243. if (termPlugin?.openTerminal && cwd) {
  244. console.log("[dashboard] calling terminal plugin openTerminal with claude profile");
  245. termPlugin.openTerminal({ profile: "claude", cwd });
  246. return;
  247. }
  248. const profiles = termPlugin?.settings?.value?.profiles || termPlugin?.settings?.profiles;
  249. if (profiles?.claude && termPlugin?.spawnTerminal) {
  250. console.log("[dashboard] calling terminal plugin spawnTerminal with claude profile");
  251. termPlugin.spawnTerminal(profiles.claude, cwd);
  252. return;
  253. }
  254. } catch (e) {
  255. console.error("[dashboard] terminal plugin API call failed", e);
  256. }
  257. // Last resort: open an integrated terminal at vault root inside Obsidian
  258. // and show a notice. Never switch to system Terminal.app.
  259. const integratedId = Object.keys(registry).find(k =>
  260. /^terminal:open-terminal\..*(integrated|integratedDefault|darwinIntegratedDefault).*\.root$/.test(k)
  261. ) || Object.keys(registry).find(k =>
  262. k.startsWith("terminal:open-terminal.") && k.endsWith(".root")
  263. );
  264. if (integratedId) {
  265. console.log("[dashboard] integrated terminal fallback:", integratedId);
  266. app.commands.executeCommandById(integratedId);
  267. new Notice("Run: claude --dangerously-skip-permissions", 6000);
  268. return;
  269. }
  270. new Notice("Terminal plugin not available. Enable it in Settings → Community plugins.", 6000);
  271. console.error("[dashboard] no terminal command found. registry:", Object.keys(registry).filter(k => k.startsWith("terminal:")));
  272. return;
  273. }
  274. console.error("[dashboard] command not found and no fallback:", cmd, "— available terminal commands:", Object.keys(registry).filter(k => k.startsWith("terminal:")));
  275. }
  276. /** Map ONLY long-running shell commands to loader labels. Instant
  277. * commands (open terminal, reload, settings, navigation) return null
  278. * and skip the loader. */
  279. cmdLabel(cmd) {
  280. const map = {
  281. "obsidian-shellcommands:shell-command-morning-brief": "Generating morning brief…",
  282. "obsidian-shellcommands:shell-command-daily-scan": "Running daily scan…",
  283. "obsidian-shellcommands:shell-command-new-daily": "Creating today's daily note…",
  284. "obsidian-shellcommands:shell-command-video-research": "Running video research…",
  285. };
  286. return map[cmd] || null;
  287. }
  288. /** Show a blocking overlay for long-running actions. Auto-dismisses or click-to-dismiss. */
  289. showActionLoader(label, sub) {
  290. document.querySelectorAll(".cc-action-loader").forEach(e => e.remove());
  291. const el = document.createElement("div");
  292. el.className = "cc-action-loader";
  293. el.innerHTML = `
  294. <div class="cc-loader-card">
  295. <div class="cc-loader-spinner"></div>
  296. <div class="cc-loader-title">${this.esc(label)}</div>
  297. <div class="cc-loader-sub">${this.esc(sub || "Output will land in your vault. You can dismiss this and keep working.")}</div>
  298. <button class="cc-loader-close">Dismiss</button>
  299. </div>`;
  300. document.body.appendChild(el);
  301. const close = () => el.remove();
  302. el.querySelector(".cc-loader-close").addEventListener("click", close);
  303. el.addEventListener("click", (e) => { if (e.target === el) close(); });
  304. setTimeout(close, 60_000); // 60s safety auto-hide
  305. }
  306. // ===================================================================
  307. // HELPERS
  308. // ===================================================================
  309. esc(s) { return String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c])); }
  310. fmt(d) { return d ? d.toFormat("MMM dd · HH:mm") : ""; }
  311. rel(d, today) {
  312. if (!d) return "—";
  313. const days = Math.round(today.diff(d, "days").days);
  314. if (days === 0) return "today";
  315. if (days === 1) return "1d ago";
  316. if (days < 7) return `${days}d ago`;
  317. if (days < 30) return `${Math.round(days/7)}w ago`;
  318. return d.toFormat("MMM d");
  319. }
  320. link(p) { return `<a class="cc-link" data-href="${this.esc(p.file.path)}">${this.esc(p.file.name)}</a>`; }
  321. /** Pull the first YYYY-MM-DD date out of a Task Board emoji task line.
  322. * Priority: 📅 due → ⏳ scheduled → 🛫 start → plain ISO date. Returns "" if none. */
  323. extractTaskDate(text) {
  324. const m = String(text).match(/(?:📅|⏳|🛫)\s*(\d{4}-\d{2}-\d{2})/) || String(text).match(/\b(\d{4}-\d{2}-\d{2})\b/);
  325. return m ? m[1] : "";
  326. }
  327. /** Strip task metadata emojis/dates from display text. */
  328. stripTaskMeta(text) {
  329. return String(text)
  330. .replace(/(?:📅|⏳|🛫|✅)\s*\d{4}-\d{2}-\d{2}/g, "")
  331. .replace(/[🔺🔼🔽]/g, "")
  332. .replace(/\s+/g, " ")
  333. .trim();
  334. }
  335. /** Convert minimal markdown → safe HTML for dashboard rendering. */
  336. md(s) {
  337. if (s == null) return "";
  338. let out = String(s);
  339. // wikilinks with alias [[path|display]]
  340. out = out.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, (_, p, d) => `<a class="cc-link" data-href="${p.trim()}">${d.trim()}</a>`);
  341. // wikilinks plain [[path]]
  342. out = out.replace(/\[\[([^\]]+)\]\]/g, (_, p) => {
  343. const trimmed = p.trim();
  344. const display = trimmed.split("/").pop();
  345. return `<a class="cc-link" data-href="${trimmed}">${display}</a>`;
  346. });
  347. // inline code
  348. out = out.replace(/`([^`]+)`/g, '<code class="cc-code">$1</code>');
  349. // bold **x**
  350. out = out.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
  351. // italic *x*
  352. out = out.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>");
  353. return out;
  354. }
  355. tableHTML(cols, rows, emptyMsg) {
  356. if (!rows.length) return `<div class="cc-empty">${emptyMsg}</div>`;
  357. return `<table class="cc-table"><thead><tr>${cols.map(c => `<th>${c}</th>`).join("")}</tr></thead><tbody>${rows.map(r => `<tr>${r.map(c => `<td>${c}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
  358. }
  359. // ===================================================================
  360. // LUCIDE-STYLE ICONS (inline SVG)
  361. // ===================================================================
  362. icon(name) {
  363. const paths = {
  364. home: '<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>',
  365. users: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
  366. check: '<polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>',
  367. calendar:'<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>',
  368. chart: '<line x1="12" y1="20" x2="12" y2="10"/><line x1="18" y1="20" x2="18" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/>',
  369. zap: '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>',
  370. gear: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>',
  371. refresh:'<polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>',
  372. back: '<line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/>',
  373. flame: '<path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>',
  374. file: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>',
  375. book: '<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>',
  376. };
  377. return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="cc-icon">${paths[name] || ""}</svg>`;
  378. }
  379. // ===================================================================
  380. // SVG PRIMITIVES (sparkline / bar / heatmap / ring / delta)
  381. // ===================================================================
  382. /** Resolve a vault path to a browser-loadable resource URL. Returns null if missing/error. */
  383. resourceUrl(path) {
  384. try {
  385. const f = app.vault.getAbstractFileByPath(path);
  386. if (f && f.path && !f.children) {
  387. if (typeof app.vault.getResourcePath === "function") return app.vault.getResourcePath(f);
  388. if (app.vault.adapter && typeof app.vault.adapter.getResourcePath === "function") return app.vault.adapter.getResourcePath(path);
  389. }
  390. } catch (e) {
  391. console.warn("[dashboard] resourceUrl failed for", path, e);
  392. }
  393. return null;
  394. }
  395. /** Resolve a profile's avatar (Slack export). */
  396. avatarFor(name) {
  397. const base = this.profilePath(name);
  398. return this.resourceUrl(`${base}/avatar.png`)
  399. || this.resourceUrl(`${base}/avatar.jpg`)
  400. || this.resourceUrl(`${base}/avatar.jpeg`);
  401. }
  402. /** Resolve the configured brand mark image, if any. */
  403. brandMark() {
  404. return this.constructor.CONFIG.BRAND_MARK_PATH ? this.resourceUrl(this.constructor.CONFIG.BRAND_MARK_PATH) : "";
  405. }
  406. /** Detect series that's empty, all zeros, or completely flat — no point rendering. */
  407. isFlat(data) {
  408. if (!Array.isArray(data) || !data.length) return true;
  409. const nums = data.map(Number).filter(n => !isNaN(n));
  410. if (!nums.length) return true;
  411. if (nums.every(v => v === 0)) return true;
  412. return Math.min(...nums) === Math.max(...nums);
  413. }
  414. isFlatMulti(datasets) {
  415. return datasets.every(d => this.isFlat(d.values));
  416. }
  417. /** Frappe sparkline (tiny line chart) for KPI cards. */
  418. sparkline(data, color = "#020309") {
  419. if (this.isFlat(data)) return `<div class="cc-empty cc-empty-mini">— no data —</div>`;
  420. const payload = { values: data, color };
  421. return `<div class="cc-chart-mount cc-spark-mount" data-chart="sparkline" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  422. }
  423. /** Frappe donut for goal progress / loops / single-value indicators. */
  424. ring(pct, _size, color = "#020309") {
  425. const payload = {
  426. values: [pct, 100 - pct],
  427. labels: ["Done", "Remaining"],
  428. colors: [color, "rgba(2,3,9,0.10)"],
  429. height: 140,
  430. };
  431. return `<div class="cc-chart-mount cc-ring-mount" data-chart="donut" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  432. }
  433. /** Frappe pie chart. */
  434. pie(labels, values, opts = {}) {
  435. if (!values.length) return "";
  436. const payload = { labels, values, colors: opts.colors, height: opts.height || 200, maxSlices: opts.maxSlices };
  437. return `<div class="cc-chart-mount cc-pie-mount" data-chart="pie" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  438. }
  439. /** Frappe horizontal percentage bar — replaces folder-bars row stack. */
  440. percentage(labels, values, opts = {}) {
  441. if (!values.length) return "";
  442. const payload = { labels, values, colors: opts.colors, height: opts.height || 80 };
  443. return `<div class="cc-chart-mount cc-pct-mount" data-chart="percentage" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  444. }
  445. /** Frappe bar chart container. Mounted in mountCharts() after innerHTML set. */
  446. barChart(data, name = "Files") {
  447. if (!data.length) return "";
  448. const payload = {
  449. labels: data.map(d => d.label),
  450. values: data.map(d => d.value),
  451. name,
  452. };
  453. return `<div class="cc-chart-mount" data-chart="bar" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  454. }
  455. /** Frappe heatmap container. */
  456. heatmap(days /*, heatMax */) {
  457. if (!days.length) return "";
  458. const dataPoints = {};
  459. for (const d of days) {
  460. const unix = Math.floor(d.date.toSeconds());
  461. dataPoints[unix] = d.count;
  462. }
  463. const payload = {
  464. dataPoints,
  465. start: days[0].date.toISO(),
  466. end: days[days.length - 1].date.toISO(),
  467. countLabel: "edits",
  468. };
  469. return `<div class="cc-chart-mount cc-chart-heatmap" data-chart="heatmap" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  470. }
  471. /** Frappe line chart for trend series (used for Circle/Slack pulse, etc.). */
  472. lineChart(values, labels, name = "Series") {
  473. if (!values.length) return "";
  474. const payload = {
  475. labels: labels || values.map((_, i) => String(i + 1)),
  476. values,
  477. name,
  478. };
  479. return `<div class="cc-chart-mount" data-chart="line" data-payload='${this.esc(JSON.stringify(payload))}'></div>`;
  480. }
  481. ring(pct, size = 80, color = "#020309") {
  482. const r = (size - 10) / 2;
  483. const c = 2 * Math.PI * r;
  484. const off = c * (1 - pct / 100);
  485. return `<svg viewBox="0 0 ${size} ${size}" class="cc-ring">
  486. <circle cx="${size/2}" cy="${size/2}" r="${r}" fill="none" stroke="rgba(2,3,9,0.10)" stroke-width="7"/>
  487. <circle cx="${size/2}" cy="${size/2}" r="${r}" fill="none" stroke="${color}" stroke-width="7" stroke-dasharray="${c.toFixed(2)}" stroke-dashoffset="${off.toFixed(2)}" stroke-linecap="round" transform="rotate(-90 ${size/2} ${size/2})"/>
  488. <text x="${size/2}" y="${size/2 + 6}" text-anchor="middle" font-size="17" font-weight="800" font-family="Space Grotesk" fill="var(--dark)">${pct}%</text>
  489. </svg>`;
  490. }
  491. deltaPill(delta, suffix = "%") {
  492. const pos = delta >= 0;
  493. const arrow = pos ? "▲" : "▼";
  494. const cls = pos ? "cc-delta-pos" : "cc-delta-neg";
  495. return `<span class="cc-delta ${cls}">${arrow} ${Math.abs(delta)}${suffix}</span>`;
  496. }
  497. // ===================================================================
  498. // DATA UTILS
  499. // ===================================================================
  500. activityFor(date, files) {
  501. return files.where(p => p.file.mtime && p.file.mtime.hasSame(date, "day")).length;
  502. }
  503. last7Days(dv) { const t = dv.date("today"); return [...Array(7)].map((_, i) => t.minus({ days: 6 - i })); }
  504. last30Days(dv) { const t = dv.date("today"); return [...Array(30)].map((_, i) => t.minus({ days: 29 - i })); }
  505. dayLabel(d) { return ["S","M","T","W","T","F","S"][d.weekday % 7]; }
  506. /** Extract bulleted items under a heading from a markdown file. */
  507. async extractBullets(dv, filePath, headingRegex, limit = 10) {
  508. try {
  509. const raw = await dv.io.load(filePath);
  510. const lines = (raw || "").split("\n");
  511. const start = lines.findIndex(l => headingRegex.test(l));
  512. if (start === -1) return [];
  513. const items = [];
  514. for (let i = start + 1; i < lines.length && items.length < limit; i++) {
  515. const l = lines[i];
  516. if (/^## /.test(l)) break;
  517. const m = l.match(/^\s*[-*]\s+(.+)$/);
  518. if (m) items.push(m[1].trim());
  519. }
  520. return items;
  521. } catch (e) { return []; }
  522. }
  523. // ===================================================================
  524. // SHELL (sidebar + topbar + views container)
  525. // ===================================================================
  526. shellHTML({ title, eyebrow, sidebarItems, topActions, viewsHTML, backHref, brandLabel, brandSub, avatar }) {
  527. const _brandLabel = brandLabel || this.constructor.CONFIG.BRAND_LABEL;
  528. const _brandSub = brandSub || "Agentic OS";
  529. const _markHTML = avatar
  530. ? `<img src="${avatar}" alt="${this.esc(_brandLabel)}"/>`
  531. : "B";
  532. const sidebarHTML = sidebarItems.map(item => {
  533. if (item.divider) return `<div class="cc-nav-divider"></div>`;
  534. const attrs = item.view ? `data-view="${item.view}"` : (item.cmd ? `data-cmd="${item.cmd}"` : `data-href="${this.esc(item.href || "")}"`);
  535. return `<button class="cc-nav-btn ${item.active ? "active" : ""}" ${attrs} title="${this.esc(item.label)}" aria-label="${this.esc(item.label)}">
  536. ${this.icon(item.icon)}
  537. <span class="cc-nav-label">${this.esc(item.label)}</span>
  538. </button>`;
  539. }).join("");
  540. const topHTML = topActions.map(a => `
  541. <button class="cc-btn ${a.variant ? `cc-btn-${a.variant}` : ""}" data-cmd="${a.cmd}">
  542. <span class="cc-btn-ico">${a.icon}</span><span>${this.esc(a.label)}</span>
  543. </button>
  544. `).join("");
  545. return `
  546. <div class="cc-app">
  547. <aside class="cc-sidebar">
  548. <div class="cc-brand" title="${this.esc(_brandLabel)} · ${this.esc(_brandSub)}">
  549. <div class="cc-brand-mark">${_markHTML}</div>
  550. <div>
  551. <div class="cc-brand-text">${this.esc(_brandLabel)}</div>
  552. <div class="cc-brand-sub">${this.esc(_brandSub)}</div>
  553. </div>
  554. </div>
  555. ${backHref ? `<button class="cc-nav-btn cc-nav-back" data-href="${this.esc(backHref)}" title="Back to Home">${this.icon("back")}<span class="cc-nav-label">Back to Home</span></button>` : ""}
  556. <div class="cc-nav-section">Navigate</div>
  557. <nav class="cc-nav">${sidebarHTML}</nav>
  558. <div class="cc-nav-spacer"></div>
  559. <div class="cc-nav-section">System</div>
  560. <div class="cc-nav-footer">
  561. <button class="cc-nav-btn" data-cmd="app:open-settings" title="Settings">${this.icon("gear")}<span class="cc-nav-label">Settings</span></button>
  562. <button class="cc-nav-btn" data-cmd="app:reload" title="Reload">${this.icon("refresh")}<span class="cc-nav-label">Reload</span></button>
  563. </div>
  564. </aside>
  565. <div class="cc-shell">
  566. <header class="cc-topbar">
  567. <div class="cc-title-group">
  568. <div class="cc-eyebrow">${this.esc(eyebrow)}</div>
  569. <h1 class="cc-title">${this.esc(title)}</h1>
  570. </div>
  571. <div class="cc-top-actions">${topHTML}</div>
  572. </header>
  573. <main class="cc-main">${viewsHTML}</main>
  574. </div>
  575. </div>`;
  576. }
  577. // ===================================================================
  578. // WIRE INTERACTIONS
  579. // ===================================================================
  580. wire(root) {
  581. root.querySelectorAll(".cc-nav-btn[data-view]").forEach(btn => {
  582. btn.addEventListener("click", () => {
  583. root.querySelectorAll(".cc-view").forEach(v => v.hidden = v.dataset.view !== btn.dataset.view);
  584. root.querySelectorAll(".cc-nav-btn[data-view]").forEach(b => b.classList.toggle("active", b === btn));
  585. root.querySelector(".cc-shell")?.scrollTo?.({ top: 0, behavior: "smooth" });
  586. });
  587. });
  588. root.querySelectorAll("[data-cmd]").forEach(btn => {
  589. btn.addEventListener("click", e => {
  590. e.preventDefault();
  591. const cmd = btn.dataset.cmd;
  592. const label = this.cmdLabel(cmd);
  593. if (label) this.showActionLoader(label);
  594. this.executeCommandSafe(cmd);
  595. });
  596. });
  597. root.querySelectorAll(".cc-claude-run").forEach(btn => {
  598. btn.addEventListener("click", () => {
  599. const ctx = { profile: btn.dataset.profile || "" };
  600. this.runClaude(btn.dataset.promptKey, root, ctx);
  601. // Auto-switch to the Runs view so the user sees streaming output.
  602. const runsNavBtn = root.querySelector('.cc-nav-btn[data-view="runs"]');
  603. if (runsNavBtn) runsNavBtn.click();
  604. });
  605. });
  606. root.querySelectorAll(".cc-escalate-btn").forEach(btn => {
  607. btn.addEventListener("click", (e) => {
  608. e.stopPropagation();
  609. try {
  610. const payload = JSON.parse(decodeURIComponent(escape(atob(btn.dataset.escalate))));
  611. this.openEscalateModal(payload);
  612. } catch (err) { console.error("[dashboard] escalate parse failed", err); }
  613. });
  614. });
  615. // Restore any in-flight or finished runs from this session
  616. this.restoreRunHistory(root);
  617. // Initial paint of "ran X ago" labels next to each action button.
  618. this.refreshLastRunLabels(root);
  619. // Live tick so "running · Ns" and "ran 5m ago" stay current.
  620. if (window._ccLastRunTicker) clearInterval(window._ccLastRunTicker);
  621. window._ccLastRunTicker = setInterval(() => this.refreshLastRunLabels(document), 15000);
  622. root.querySelectorAll("[data-href]").forEach(el => {
  623. el.addEventListener("click", async e => {
  624. e.preventDefault();
  625. this.showNavLoader();
  626. await app.workspace.openLinkText(el.dataset.href, "", false, {
  627. state: { mode: "preview" },
  628. eState: { mode: "preview" },
  629. });
  630. // Some plugins (e.g. dataview, customjs dashboards) override the view
  631. // mode after open. Force preview on the active leaf as a follow-up.
  632. const leaf = app.workspace.getMostRecentLeaf?.() || app.workspace.activeLeaf;
  633. const view = leaf?.view;
  634. if (view?.getViewType?.() === "markdown") {
  635. const state = leaf.getViewState();
  636. if (state?.state?.mode !== "preview") {
  637. state.state = { ...(state.state || {}), mode: "preview", source: false };
  638. await leaf.setViewState(state, { focus: true });
  639. }
  640. }
  641. });
  642. });
  643. }
  644. /** Show a fullscreen loader during dashboard-to-dashboard navigation.
  645. * Removes itself once a fresh .cc-root mounts in the new page. */
  646. showNavLoader() {
  647. document.querySelectorAll(".cc-nav-loader").forEach(n => n.remove());
  648. const el = document.createElement("div");
  649. el.className = "cc-nav-loader";
  650. el.innerHTML = `
  651. <div class="cc-loader-shell">
  652. <div class="cc-loader-spinner"></div>
  653. <div class="cc-loader-text">Loading your agentic OS…</div>
  654. </div>`;
  655. document.body.appendChild(el);
  656. // The .cc-root currently visible belongs to the OLD page. We need to
  657. // detect a NEW one appearing. Mark the old one as outgoing first.
  658. document.querySelectorAll(".cc-root").forEach(r => r.classList.add("cc-outgoing"));
  659. const cleanup = () => { try { el.classList.add("cc-fading"); setTimeout(() => el.remove(), 220); } catch {} };
  660. const observer = new MutationObserver(() => {
  661. const fresh = document.querySelector(".cc-root:not(.cc-outgoing):not(.cc-loading)");
  662. if (fresh) { observer.disconnect(); cleanup(); }
  663. });
  664. observer.observe(document.body, { childList: true, subtree: true });
  665. // Safety fallback in case render fails or takes too long
  666. setTimeout(() => { observer.disconnect(); cleanup(); }, 12_000);
  667. }
  668. // ===================================================================
  669. // TEAM DASHBOARD (Home.md) — returns HTML string
  670. // ===================================================================
  671. async buildTeamHTML(dv) {
  672. const today = dv.date("today");
  673. const allFiles = dv.pages();
  674. const profiles = this.constructor.CONFIG.PROFILES;
  675. // -------- Velocity ----------
  676. const last7 = this.last7Days(dv);
  677. const prev7 = [...Array(7)].map((_, i) => today.minus({ days: 13 - i }));
  678. const activity7 = last7.map(d => ({ date: d, value: this.activityFor(d, allFiles), label: this.dayLabel(d) }));
  679. const totalThis = activity7.reduce((a, b) => a + b.value, 0);
  680. const totalPrev = prev7.reduce((a, b) => a + this.activityFor(b, allFiles), 0);
  681. const deltaPct = totalPrev ? Math.round(((totalThis - totalPrev) / totalPrev) * 100) : (totalThis > 0 ? 100 : 0);
  682. // -------- Root dailies ----------
  683. const rootDailies = dv.pages('"Daily"').sort(p => p.file.name, "desc");
  684. const today7Dailies = last7.map(d => rootDailies.find(p => p.file.name === d.toFormat("yyyy-MM-dd")));
  685. const sumF = f => today7Dailies.reduce((s, p) => s + (p && typeof p[f] === "number" ? p[f] : 0), 0);
  686. const meetingsWeek = sumF("meetings");
  687. const slackWeek = sumF("slack_messages");
  688. const circleWeek = sumF("circle_posts");
  689. const todayDaily = rootDailies.find(p => p.file.name === today.toFormat("yyyy-MM-dd"));
  690. // Aggregate every daily across root + per-profile folders, by date.
  691. // dayCounts[YYYY-MM-DD] = number of dailies that exist for that day
  692. const dayCounts = {};
  693. const addDates = (pages) => pages.forEach(p => {
  694. const k = p.file.name;
  695. if (/^\d{4}-\d{2}-\d{2}$/.test(k)) dayCounts[k] = (dayCounts[k] || 0) + 1;
  696. });
  697. addDates(rootDailies);
  698. profiles.forEach(name => addDates(dv.pages(`"${this.profileDailyPath(name)}"`)));
  699. const rootNames = Object.keys(dayCounts);
  700. // Streak = consecutive recent days with at least one daily anywhere
  701. let streak = 0;
  702. for (let i = 0; i < 365; i++) {
  703. const d = today.minus({ days: i });
  704. if (dayCounts[d.toFormat("yyyy-MM-dd")]) streak++;
  705. else if (i > 0) break;
  706. }
  707. // -------- 30-day team heatmap ----------
  708. const last30 = this.last30Days(dv);
  709. const heat = last30.map(d => ({ date: d, count: this.activityFor(d, allFiles) }));
  710. const heatMax = Math.max(...heat.map(d => d.count), 1);
  711. // -------- Circle/Slack 14d pulses ----------
  712. const last14 = [...Array(14)].map((_, i) => today.minus({ days: 13 - i }));
  713. const pulseSlack = last14.map(d => rootDailies.find(p => p.file.name === d.toFormat("yyyy-MM-dd"))?.slack_messages ?? 0);
  714. const pulseCircle = last14.map(d => rootDailies.find(p => p.file.name === d.toFormat("yyyy-MM-dd"))?.circle_posts ?? 0);
  715. // -------- Profile cards data ----------
  716. const profileCards = profiles.map(name => {
  717. const pDailies = dv.pages(`"${this.profileDailyPath(name)}"`).sort(p => p.file.name, "desc");
  718. const todayP = pDailies.find(p => p.file.name === today.toFormat("yyyy-MM-dd"));
  719. const last = pDailies.first();
  720. const profileFiles = dv.pages(`"${this.profilePath(name)}"`);
  721. const weekTouched = last7.reduce((a, d) => a + this.activityFor(d, profileFiles), 0);
  722. return {
  723. name,
  724. focus: todayP?.focus ?? null,
  725. energy: todayP?.energy ?? null,
  726. wins: todayP?.wins_today ?? null,
  727. loops: todayP?.open_loops ?? null,
  728. lastSeen: last?.file?.mtime ?? null,
  729. weekTouched,
  730. avatar: this.avatarFor(name),
  731. };
  732. });
  733. // -------- Escalations from today's root daily ----------
  734. let escalationItems = [];
  735. if (todayDaily) {
  736. escalationItems = await this.extractBullets(dv, todayDaily.file.path, /^## Critical Escalations/i, 12);
  737. }
  738. // KPI: prefer frontmatter count, fall back to parsed bullets count
  739. const escalationsOpen = (typeof todayDaily?.escalations_open === "number")
  740. ? todayDaily.escalations_open
  741. : escalationItems.length;
  742. // -------- Cross-team active tasks (sorted by due date desc) ------
  743. const allTasks = [];
  744. for (const name of profiles) {
  745. const tasksPage = dv.pages(`"${this.profileTasksPath(name)}"`).find(p => p.file.name === "Tasks");
  746. if (!tasksPage) continue;
  747. try {
  748. const raw = await dv.io.load(tasksPage.file.path);
  749. const lines = (raw || "").split("\n");
  750. for (const l of lines) {
  751. if (/^\s*- \[ \] /.test(l)) {
  752. const text = l.replace(/^\s*- \[ \] /, "").trim();
  753. const due = this.extractTaskDate(text);
  754. allTasks.push({ profile: name, text, due });
  755. }
  756. }
  757. } catch (e) {}
  758. }
  759. allTasks.sort((a, b) => {
  760. // Latest due first; tasks without dates sink to the bottom
  761. if (a.due && b.due) return b.due.localeCompare(a.due);
  762. if (a.due) return -1;
  763. if (b.due) return 1;
  764. return 0;
  765. });
  766. allTasks.splice(40); // cap to 40
  767. // -------- Recent root team dailies only (latest → oldest) --------
  768. // Per-profile dailies belong on their profile dashboard, not the team home.
  769. const recentDailies = Array.from(rootDailies)
  770. .filter(p => /^\d{4}-\d{2}-\d{2}$/.test(p.file.name))
  771. .sort((a, b) => b.file.name.localeCompare(a.file.name))
  772. .slice(0, 30)
  773. .map(p => ({ p }));
  774. // ccusage — local machine Claude usage. Fire background refresh, render cached.
  775. const ccusageAgg = await this.loadCCUsage();
  776. this.refreshCCUsageIfStale();
  777. // -------- Build views ----------
  778. const overviewHTML = `
  779. <section class="cc-view" data-view="overview">
  780. ${this.ccusageStripHTML(ccusageAgg)}
  781. <div class="cc-kpis">
  782. <div class="cc-kpi cc-kpi-primary">
  783. <div class="cc-kpi-head"><span class="cc-kpi-label">Team velocity</span>${this.deltaPill(deltaPct)}</div>
  784. <div class="cc-kpi-value">${totalThis}</div>
  785. <div class="cc-kpi-foot">files touched this week</div>
  786. </div>
  787. <div class="cc-kpi">
  788. <div class="cc-kpi-head"><span class="cc-kpi-label">Meetings</span></div>
  789. <div class="cc-kpi-value">${meetingsWeek}</div>
  790. <div class="cc-kpi-foot">logged this week</div>
  791. </div>
  792. <div class="cc-kpi">
  793. <div class="cc-kpi-head"><span class="cc-kpi-label">Team streak</span></div>
  794. <div class="cc-kpi-value">${streak}<span class="cc-kpi-unit">d</span></div>
  795. <div class="cc-kpi-dots">${last7.map(d => {
  796. const hit = rootNames.includes(d.toFormat("yyyy-MM-dd"));
  797. return `<span class="cc-dot ${hit ? "cc-dot-on" : ""}" title="${d.toFormat("MMM dd")}"></span>`;
  798. }).join("")}</div>
  799. <div class="cc-kpi-foot">consecutive team dailies</div>
  800. </div>
  801. <div class="cc-kpi cc-kpi-alert">
  802. <div class="cc-kpi-head"><span class="cc-kpi-label">Open escalations</span></div>
  803. <div class="cc-kpi-value">${escalationsOpen}</div>
  804. <div class="cc-kpi-foot">across team today</div>
  805. </div>
  806. </div>
  807. <div class="cc-card cc-card-wide">
  808. <div class="cc-card-head"><h3>Today's escalations</h3><span class="cc-tag cc-chip-alert">${escalationItems.length}</span></div>
  809. <div class="cc-card-body">
  810. ${escalationItems.length
  811. ? `<ul class="cc-md-list">${escalationItems.map(e => `<li>${this.md(e)}</li>`).join("")}</ul>`
  812. : `<div class="cc-empty">No escalations parsed from today's root daily.</div>`}
  813. </div>
  814. </div>
  815. <div class="cc-card cc-card-wide cc-card-chart">
  816. <div class="cc-card-head"><h3>Weekly team velocity</h3><span class="cc-tag">${totalThis} files · 7d</span></div>
  817. <div class="cc-card-body">${this.barChart(activity7)}</div>
  818. </div>
  819. </section>`;
  820. const teamHTML = `
  821. <section class="cc-view" data-view="team" hidden>
  822. <div class="cc-card cc-card-wide">
  823. <div class="cc-card-head"><h3>Team — who's on what</h3><span class="cc-tag">${profileCards.length}</span></div>
  824. <div class="cc-card-body cc-team-grid">
  825. ${profileCards.map(p => `
  826. <a class="cc-person-card" data-href="Dashboard/${p.name}">
  827. <div class="cc-person-head">
  828. <div class="cc-person-avatar">${
  829. p.avatar
  830. ? `<img src="${p.avatar}" alt="${this.esc(p.name)}"/>`
  831. : this.esc(p.name[0])
  832. }</div>
  833. <div class="cc-person-id">
  834. <div class="cc-person-name">${this.esc(p.name)}</div>
  835. <div class="cc-person-meta">${p.lastSeen ? "active " + this.rel(p.lastSeen, today) : "no daily yet"}</div>
  836. </div>
  837. </div>
  838. ${p.focus ? `<div class="cc-person-focus">${this.esc(p.focus)}</div>` : ""}
  839. <div class="cc-person-chips">
  840. ${p.energy != null ? `<span class="cc-chip cc-chip-primary">⚡ ${p.energy}/10</span>` : ""}
  841. ${p.wins != null && p.wins !== 0 ? `<span class="cc-chip cc-chip-accent">🏆 ${p.wins}</span>` : ""}
  842. ${p.loops != null && p.loops !== 0 ? `<span class="cc-chip cc-chip-alert">🔁 ${p.loops}</span>` : ""}
  843. <span class="cc-chip">${p.weekTouched} files / 7d</span>
  844. </div>
  845. </a>`).join("")}
  846. </div>
  847. </div>
  848. </section>`;
  849. const tasksHTML = `
  850. <section class="cc-view" data-view="tasks" hidden>
  851. <div class="cc-card cc-card-wide">
  852. <div class="cc-card-head"><h3>Active tasks across team</h3><span class="cc-tag">${allTasks.length}</span></div>
  853. <div class="cc-card-body">
  854. ${allTasks.length
  855. ? `<table class="cc-table cc-table-tasks">
  856. <thead><tr><th style="width:90px">Owner</th><th style="width:110px">Due</th><th>Task</th></tr></thead>
  857. <tbody>${allTasks.map(t => `<tr>
  858. <td><span class="cc-chip cc-chip-primary">${this.esc(t.profile)}</span></td>
  859. <td>${t.due ? `<span class="cc-chip-date">${this.esc(t.due)}</span>` : `<span class="cc-muted">—</span>`}</td>
  860. <td>${this.md(this.stripTaskMeta(t.text))}</td>
  861. </tr>`).join("")}</tbody>
  862. </table>`
  863. : `<div class="cc-empty">No active tasks found in any profile's task-list/Tasks.md.</div>`}
  864. </div>
  865. </div>
  866. </section>`;
  867. const dailyHTML = `
  868. <section class="cc-view" data-view="daily" hidden>
  869. <div class="cc-card cc-card-wide">
  870. <div class="cc-card-head"><h3>Team dailies</h3><span class="cc-tag">${recentDailies.length}</span></div>
  871. <div class="cc-card-body">
  872. ${recentDailies.length
  873. ? `<table class="cc-table">
  874. <thead><tr><th>Date</th><th style="width:140px">Updated</th></tr></thead>
  875. <tbody>${recentDailies.slice(0, 30).map(({p}) => `<tr><td>${this.link(p)}</td><td>${this.rel(p.file.mtime, today)}</td></tr>`).join("")}</tbody>
  876. </table>`
  877. : `<div class="cc-empty">No team dailies in <code>Daily/</code> yet.</div>`}
  878. </div>
  879. </div>
  880. </section>`;
  881. // Top folders across the whole vault (last 7 days)
  882. const vaultFolderCounts = {};
  883. for (const p of allFiles.where(f => f.file.mtime > today.minus({ days: 7 }))) {
  884. const root = (p.file.folder.split("/")[0] || "(root)").trim() || "(root)";
  885. vaultFolderCounts[root] = (vaultFolderCounts[root] || 0) + 1;
  886. }
  887. const topFoldersAll = Object.entries(vaultFolderCounts).sort((a,b) => b[1] - a[1]).slice(0, 6);
  888. // Channel mix donut (Meetings vs Slack vs Circle)
  889. const channelTotal = meetingsWeek + slackWeek + circleWeek;
  890. // Per-profile activity (stacked bar)
  891. const profileActivity = profiles.map(name => ({
  892. name,
  893. values: last7.map(d => this.activityFor(d, dv.pages(`"${this.profilePath(name)}"`))),
  894. }));
  895. const profileActivityFlat = this.isFlatMulti(profileActivity);
  896. // Day-of-week buckets (Mon → Sun)
  897. const dowBuckets = [0,0,0,0,0,0,0];
  898. last30.forEach(d => { dowBuckets[(d.weekday + 6) % 7] += this.activityFor(d, allFiles); });
  899. const pulseFlat = this.isFlatMulti([
  900. { values: pulseCircle },
  901. { values: pulseSlack },
  902. ]);
  903. const analyticsHTML = `
  904. <section class="cc-view" data-view="analytics" hidden>
  905. <div class="cc-grid cc-grid-2">
  906. <div class="cc-card cc-card-chart">
  907. <div class="cc-card-head"><h3>Velocity — 7d</h3><span class="cc-tag">${totalThis} files</span></div>
  908. <div class="cc-card-body">${this.barChart(activity7)}</div>
  909. </div>
  910. <div class="cc-card cc-card-chart">
  911. <div class="cc-card-head"><h3>Activity — 30d</h3><span class="cc-tag">${heat.reduce((a,b)=>a+b.count,0)} edits</span></div>
  912. <div class="cc-card-body cc-heat-body">
  913. ${this.heatmap(heat)}
  914. </div>
  915. </div>
  916. <div class="cc-card cc-card-chart">
  917. <div class="cc-card-head"><h3>Top folders · 7d</h3><span class="cc-tag">${topFoldersAll.length}</span></div>
  918. <div class="cc-card-body">
  919. ${topFoldersAll.length
  920. ? this.pie(topFoldersAll.map(f => f[0]), topFoldersAll.map(f => f[1]), { height: 240 })
  921. : `<div class="cc-empty">No folder activity yet.</div>`}
  922. </div>
  923. </div>
  924. <div class="cc-card cc-card-chart">
  925. <div class="cc-card-head"><h3>Channel mix · this week</h3><span class="cc-tag">${channelTotal}</span></div>
  926. <div class="cc-card-body">
  927. ${channelTotal > 0
  928. ? this.percentage(
  929. ["Meetings", "Slack", "Circle"],
  930. [meetingsWeek, slackWeek, circleWeek],
  931. { colors: ["#020309", "#7FBE7C", "#FDEEC4"], height: 120 }
  932. )
  933. : `<div class="cc-empty">No channel activity logged yet.</div>`}
  934. <div class="cc-channel-rows">
  935. <div class="cc-channel-row"><span class="cc-channel-dot" style="background:#020309"></span><span class="cc-channel-label">Meetings</span><span class="cc-channel-val">${meetingsWeek}</span></div>
  936. <div class="cc-channel-row"><span class="cc-channel-dot" style="background:#7FBE7C"></span><span class="cc-channel-label">Slack</span><span class="cc-channel-val">${slackWeek}</span></div>
  937. <div class="cc-channel-row"><span class="cc-channel-dot" style="background:#FDEEC4"></span><span class="cc-channel-label">Circle</span><span class="cc-channel-val">${circleWeek}</span></div>
  938. </div>
  939. </div>
  940. </div>
  941. <div class="cc-card cc-card-chart">
  942. <div class="cc-card-head"><h3>Circle / Slack pulse · 14d</h3><span class="cc-tag">${circleWeek + slackWeek}</span></div>
  943. <div class="cc-card-body">
  944. ${pulseFlat
  945. ? `<div class="cc-empty">No Circle or Slack activity logged in the last 14 days.</div>`
  946. : `<div class="cc-chart-mount" data-chart="line" data-payload='${this.esc(JSON.stringify({
  947. labels: last14.map(d => d.toFormat("MMM d")),
  948. datasets: [
  949. { name: "Circle", values: pulseCircle },
  950. { name: "Slack", values: pulseSlack },
  951. ],
  952. colors: ["#020309", "#7FBE7C"],
  953. height: 220,
  954. spline: 1,
  955. }))}'></div>`}
  956. </div>
  957. </div>
  958. <div class="cc-card cc-card-chart">
  959. <div class="cc-card-head"><h3>Activity by profile · 7d</h3><span class="cc-tag">team</span></div>
  960. <div class="cc-card-body">
  961. ${profileActivityFlat
  962. ? `<div class="cc-empty">No per-profile activity to plot yet.</div>`
  963. : `<div class="cc-chart-mount" data-chart="bar" data-payload='${this.esc(JSON.stringify({
  964. labels: activity7.map(a => a.label),
  965. datasets: profileActivity,
  966. colors: ["#020309", "#7FBE7C", "#D2ECD0", "#FDEEC4", "#F3C1C0"],
  967. stacked: true,
  968. height: 240,
  969. }))}'></div>`}
  970. </div>
  971. </div>
  972. <div class="cc-card cc-card-chart">
  973. <div class="cc-card-head"><h3>Day-of-week productivity</h3><span class="cc-tag">30d</span></div>
  974. <div class="cc-card-body">
  975. ${this.isFlat(dowBuckets)
  976. ? `<div class="cc-empty">No weekday data yet.</div>`
  977. : `<div class="cc-chart-mount" data-chart="bar" data-payload='${this.esc(JSON.stringify({
  978. labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  979. values: dowBuckets,
  980. name: "Edits",
  981. colors: ["#020309"],
  982. height: 240,
  983. }))}'></div>`}
  984. </div>
  985. </div>
  986. <div class="cc-card">
  987. <div class="cc-card-head"><h3>Weekly aggregates</h3></div>
  988. <div class="cc-card-body cc-agg-list">
  989. <div class="cc-agg-row"><span class="cc-agg-label">Meetings</span><span class="cc-agg-val">${meetingsWeek}</span></div>
  990. <div class="cc-agg-row"><span class="cc-agg-label">Slack messages</span><span class="cc-agg-val">${slackWeek}</span></div>
  991. <div class="cc-agg-row"><span class="cc-agg-label">Circle posts</span><span class="cc-agg-val">${circleWeek}</span></div>
  992. <div class="cc-agg-row"><span class="cc-agg-label">Team streak</span><span class="cc-agg-val">${streak}d</span></div>
  993. </div>
  994. </div>
  995. </div>
  996. </section>`;
  997. const actionsHTML = `
  998. <section class="cc-view" data-view="actions" hidden>
  999. <div class="cc-grid cc-grid-3">
  1000. <div class="cc-card">
  1001. <div class="cc-card-head"><h3>Daily</h3></div>
  1002. <div class="cc-card-body cc-action-list">
  1003. <button class="cc-btn cc-btn-primary cc-btn-block" data-cmd="obsidian-shellcommands:shell-command-morning-brief">🌅 Morning brief</button>
  1004. <button class="cc-btn cc-btn-block" data-cmd="obsidian-shellcommands:shell-command-new-daily">📝 New daily note</button>
  1005. <button class="cc-btn cc-btn-block" data-cmd="obsidian-shellcommands:shell-command-daily-scan">🔍 Daily scan</button>
  1006. </div>
  1007. </div>
  1008. <div class="cc-card">
  1009. <div class="cc-card-head"><h3>Research</h3></div>
  1010. <div class="cc-card-body cc-action-list">
  1011. <button class="cc-btn cc-btn-accent cc-btn-block" data-cmd="obsidian-shellcommands:shell-command-video-research">🎥 Video research</button>
  1012. <button class="cc-btn cc-btn-dark cc-btn-block" data-cmd="terminal:open-terminal.claude.root">💬 Open Claude</button>
  1013. </div>
  1014. </div>
  1015. <div class="cc-card">
  1016. <div class="cc-card-head"><h3>System</h3></div>
  1017. <div class="cc-card-body cc-action-list">
  1018. <button class="cc-btn cc-btn-block" data-cmd="app:reload">♻️ Reload Obsidian</button>
  1019. <button class="cc-btn cc-btn-block" data-cmd="app:open-settings">⚙️ Settings</button>
  1020. </div>
  1021. </div>
  1022. </div>
  1023. </section>`;
  1024. const viewsHTML = overviewHTML + teamHTML + tasksHTML + dailyHTML + analyticsHTML + actionsHTML;
  1025. return this.shellHTML({
  1026. title: `${this.constructor.CONFIG.BRAND_LABEL} ${this.constructor.CONFIG.BRAND_SUB}`.trim(),
  1027. eyebrow: `TEAM · ${today.toFormat("EEEE, MMM d")}`,
  1028. avatar: this.brandMark(),
  1029. sidebarItems: [
  1030. { icon: "home", label: "Home", view: "overview", active: true },
  1031. { icon: "chart", label: "Analytics", view: "analytics" },
  1032. { icon: "users", label: "Team", view: "team" },
  1033. { icon: "calendar", label: "Daily", view: "daily" },
  1034. { icon: "check", label: "Tasks", view: "tasks" },
  1035. { icon: "zap", label: "Actions", view: "actions" },
  1036. { icon: "book", label: "Vault Overview", href: "Dashboard/Vault-Overview" },
  1037. ],
  1038. topActions: [
  1039. { icon: "🌅", label: "Morning brief", variant: "primary", cmd: "obsidian-shellcommands:shell-command-morning-brief" },
  1040. { icon: "🔍", label: "Daily scan", cmd: "obsidian-shellcommands:shell-command-daily-scan" },
  1041. { icon: "💬", label: "Launch Claude", variant: "dark", cmd: "terminal:open-terminal.claude.root" },
  1042. ],
  1043. viewsHTML,
  1044. });
  1045. }
  1046. // Derive a YouTube thumbnail URL from any YouTube video URL.
  1047. // Supports: youtube.com/watch?v=ID, youtu.be/ID, youtube.com/shorts/ID,
  1048. // youtube.com/embed/ID. Returns null if no ID found.
  1049. youtubeThumbFromUrl(url) {
  1050. if (!url) return null;
  1051. const patterns = [
  1052. /[?&]v=([A-Za-z0-9_-]{6,})/, // watch?v=ID
  1053. /youtu\.be\/([A-Za-z0-9_-]{6,})/, // youtu.be/ID
  1054. /\/shorts\/([A-Za-z0-9_-]{6,})/, // shorts/ID
  1055. /\/embed\/([A-Za-z0-9_-]{6,})/, // embed/ID
  1056. /\/live\/([A-Za-z0-9_-]{6,})/, // live/ID
  1057. ];
  1058. for (const re of patterns) {
  1059. const m = url.match(re);
  1060. if (m) return `https://i.ytimg.com/vi/${m[1]}/hqdefault.jpg`;
  1061. }
  1062. return null;
  1063. }
  1064. // Synthesis list item with proper alignment: title on the left (flexible),
  1065. // small meta chips on the right (right-aligned, wraps to a new row at narrow widths),
  1066. // optional sub-line beneath.
  1067. // Arguments:
  1068. // title string — main text
  1069. // titleHref string optional — make title a clickable link
  1070. // chipsHTML string optional — pre-rendered chip spans (use sourceChip/priorityChip etc.)
  1071. // sub string optional — secondary line (escaped/HTML pre-prepared)
  1072. // subIsHTML bool — true if sub already contains HTML; else it's plain text and gets escaped
  1073. listItem({ title, titleHref, chipsHTML, sub, subIsHTML }) {
  1074. const titleEl = titleHref
  1075. ? `<a class="cc-link" href="${this.esc(titleHref)}" target="_blank">${this.esc(title||"")}</a>`
  1076. : this.esc(title||"");
  1077. const subEl = sub
  1078. ? `<div class="cc-muted" style="font-size:12px;line-height:1.5;margin-top:4px;">${subIsHTML ? sub : this.esc(sub)}</div>`
  1079. : "";
  1080. return `
  1081. <div style="display:flex;flex-direction:column;gap:0;padding:10px 0;border-bottom:1px solid rgba(2,3,9,0.08);">
  1082. <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;">
  1083. <strong style="flex:1 1 240px;line-height:1.35;font-size:13px;">${titleEl}</strong>
  1084. ${chipsHTML ? `<div style="display:flex;gap:4px;flex-wrap:wrap;justify-content:flex-end;flex-shrink:0;align-items:center;">${chipsHTML}</div>` : ""}
  1085. </div>
  1086. ${subEl}
  1087. </div>`;
  1088. }
  1089. // Small uniform chip — used for sentiment/trend/severity meta tags inside list items.
  1090. // `tone` ∈ "neutral" | "positive" | "negative" | "alert" | "primary".
  1091. metaChip(label, tone) {
  1092. const map = {
  1093. neutral: { bg: "#f1f1f1", border: "#020309" },
  1094. positive: { bg: "#bbf7d0", border: "#14532d" },
  1095. negative: { bg: "#fca5a5", border: "#7f1d1d" },
  1096. alert: { bg: "#fca5a5", border: "#7f1d1d" },
  1097. primary: { bg: "#fde68a", border: "#78350f" },
  1098. count: { bg: "#ffffff", border: "#020309" },
  1099. };
  1100. const m = map[tone] || map.neutral;
  1101. return `<span style="display:inline-flex;align-items:center;padding:2px 8px;font-size:11px;font-weight:600;line-height:1.4;border:1px solid ${m.border};border-radius:999px;background:${m.bg};color:#020309;white-space:nowrap;">${this.esc(label)}</span>`;
  1102. }
  1103. // Helper to map trend/sentiment/severity strings to a tone for metaChip.
  1104. toneFor(value, kind) {
  1105. const v = String(value || "").toLowerCase();
  1106. if (kind === "trend") return v === "rising" ? "primary" : v === "fading" ? "neutral" : "neutral";
  1107. if (kind === "sentiment") return v === "positive" ? "positive" : v === "negative" ? "negative" : "neutral";
  1108. if (kind === "severity") return v === "high" ? "alert" : v === "medium" ? "primary" : "positive";
  1109. return "neutral";
  1110. }
  1111. // Human-friendly relative time (compact: "3s", "12m", "2h", "5d ago").
  1112. shortAgo(ms) {
  1113. const s = Math.max(0, Math.round(ms / 1000));
  1114. if (s < 60) return `${s}s ago`;
  1115. const m = Math.round(s / 60);
  1116. if (m < 60) return `${m}m ago`;
  1117. const h = Math.round(m / 60);
  1118. if (h < 24) return `${h}h ago`;
  1119. return `${Math.round(h / 24)}d ago`;
  1120. }
  1121. // Action button + "ran X ago" freshness label to the RIGHT of it.
  1122. // `key` = prompt key; `opts.profile` = scope for the run; `opts.variant` = "primary"|"" etc.
  1123. actionButton(key, label, opts = {}) {
  1124. const profile = opts.profile || "";
  1125. const variant = opts.variant || "";
  1126. return `
  1127. <div style="display:inline-flex;align-items:center;gap:8px;padding:4px 10px 4px 4px;border:1px solid var(--background-modifier-border,#020309);border-radius:999px;background:rgba(255,255,255,0.5);">
  1128. <button class="cc-btn ${variant ? `cc-btn-${variant}` : ""} cc-claude-run" data-prompt-key="${this.esc(key)}"${profile ? ` data-profile="${this.esc(profile)}"` : ""}>${this.esc(label)}</button>
  1129. <span class="cc-last-run" data-key="${this.esc(key)}" data-profile="${this.esc(profile)}" style="font-size:11px;font-weight:500;color:#020309;opacity:0.55;line-height:1.2;white-space:nowrap;">—</span>
  1130. </div>`;
  1131. }
  1132. refreshLastRunLabels(root) {
  1133. const store = this.runStore();
  1134. (root || document).querySelectorAll(".cc-last-run").forEach(el => {
  1135. const key = el.dataset.key;
  1136. const profile = el.dataset.profile || "";
  1137. const scope = profile || "global";
  1138. const matches = store.filter(r =>
  1139. r.key === key &&
  1140. ((r.scope || "global") === scope) &&
  1141. (r.status === "completed" || r.status === "running")
  1142. );
  1143. const latest = matches.sort((a, b) => (b.endedAt || b.startedAt || 0) - (a.endedAt || a.startedAt || 0))[0];
  1144. // Reset to default styling, then apply state-specific styles
  1145. el.style.color = "#020309";
  1146. el.style.opacity = "0.55";
  1147. el.style.fontWeight = "500";
  1148. el.style.background = "transparent";
  1149. el.style.padding = "0";
  1150. el.style.borderRadius = "0";
  1151. if (!latest) {
  1152. el.textContent = "never run";
  1153. return;
  1154. }
  1155. if (latest.status === "running") {
  1156. const elapsed = Math.round((Date.now() - latest.startedAt) / 1000);
  1157. el.textContent = `⚡ ${elapsed}s`;
  1158. el.style.color = "#020309";
  1159. el.style.opacity = "1";
  1160. el.style.fontWeight = "600";
  1161. el.style.background = "#fde68a";
  1162. el.style.padding = "2px 8px";
  1163. el.style.borderRadius = "999px";
  1164. return;
  1165. }
  1166. const ago = Date.now() - (latest.endedAt || latest.startedAt);
  1167. el.textContent = `${this.shortAgo(ago)}`;
  1168. });
  1169. }
  1170. // Compact, color-coded source/priority chip used in synthesis tables.
  1171. sourceChip(name) {
  1172. const k = String(name || "").toLowerCase();
  1173. const map = {
  1174. community: { icon: "👥", bg: "#fff3d6", fg: "#020309", border: "#020309" },
  1175. youtube: { icon: "▶️", bg: "#ffd7d7", fg: "#020309", border: "#020309" },
  1176. meetings: { icon: "📅", bg: "#d6e8ff", fg: "#020309", border: "#020309" },
  1177. comms: { icon: "💬", bg: "#d7ffe0", fg: "#020309", border: "#020309" },
  1178. email: { icon: "📧", bg: "#d7ffe0", fg: "#020309", border: "#020309" },
  1179. linkedin: { icon: "💼", bg: "#d7eaff", fg: "#020309", border: "#020309" },
  1180. twitter: { icon: "🐦", bg: "#d6ecff", fg: "#020309", border: "#020309" },
  1181. circle: { icon: "🔵", bg: "#e9d7ff", fg: "#020309", border: "#020309" },
  1182. research: { icon: "🔍", bg: "#f0e6ff", fg: "#020309", border: "#020309" },
  1183. intelligence: { icon: "🧠", bg: "#fce5cd", fg: "#020309", border: "#020309" },
  1184. };
  1185. const m = map[k] || { icon: "•", bg: "#f0f0f0", fg: "#020309", border: "#020309" };
  1186. return `<span style="display:inline-flex;align-items:center;gap:4px;padding:2px 7px;font-size:11px;font-weight:600;line-height:1.4;border:1px solid ${m.border};border-radius:999px;background:${m.bg};color:${m.fg};white-space:nowrap;">${m.icon} ${this.esc(name||"")}</span>`;
  1187. }
  1188. priorityChip(p) {
  1189. const k = String(p || "").toLowerCase();
  1190. const map = {
  1191. p0: { label: "P0", bg: "#fca5a5", fg: "#7f1d1d" },
  1192. p1: { label: "P1", bg: "#fde68a", fg: "#78350f" },
  1193. p2: { label: "P2", bg: "#bbf7d0", fg: "#14532d" },
  1194. high: { label: "high", bg: "#fca5a5", fg: "#7f1d1d" },
  1195. medium: { label: "med", bg: "#fde68a", fg: "#78350f" },
  1196. low: { label: "low", bg: "#bbf7d0", fg: "#14532d" },
  1197. };
  1198. const m = map[k] || { label: p||"—", bg: "#e5e7eb", fg: "#020309" };
  1199. return `<span style="display:inline-flex;align-items:center;justify-content:center;min-width:28px;padding:2px 8px;font-size:11px;font-weight:700;line-height:1.4;border:1px solid #020309;border-radius:999px;background:${m.bg};color:${m.fg};white-space:nowrap;">${m.label}</span>`;
  1200. }
  1201. // ===================================================================
  1202. // ESCALATE TO TEAM (Slack) — small button + modal
  1203. // ===================================================================
  1204. slackIcon(size = 14) {
  1205. return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" style="vertical-align:-2px;flex-shrink:0;display:inline-block;" aria-hidden="true">
  1206. <path d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52z" fill="#36C5F0"/>
  1207. <path d="M6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z" fill="#36C5F0"/>
  1208. <path d="M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834z" fill="#ECB22E"/>
  1209. <path d="M8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z" fill="#ECB22E"/>
  1210. <path d="M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834z" fill="#2EB67D"/>
  1211. <path d="M17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z" fill="#2EB67D"/>
  1212. <path d="M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52z" fill="#E01E5A"/>
  1213. <path d="M15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z" fill="#E01E5A"/>
  1214. </svg>`;
  1215. }
  1216. escalateButton(item, opts = {}) {
  1217. const payload = {
  1218. item: String(item || "").slice(0, 600),
  1219. context: String(opts.context || "").slice(0, 600),
  1220. source: opts.source || "",
  1221. url: opts.url || "",
  1222. profile: opts.profile || "",
  1223. };
  1224. const b64 = btoa(unescape(encodeURIComponent(JSON.stringify(payload))));
  1225. return `<button class="cc-btn cc-escalate-btn" data-escalate="${b64}" title="Escalate to #team-chat on Slack" style="padding:3px 8px;font-size:11px;display:inline-flex;align-items:center;gap:5px;">${this.slackIcon(13)}<span>Escalate</span></button>`;
  1226. }
  1227. openEscalateModal(payload) {
  1228. // Tear down any prior modal
  1229. document.querySelectorAll(".cc-escalate-modal").forEach(n => n.remove());
  1230. const wrap = document.createElement("div");
  1231. wrap.className = "cc-escalate-modal";
  1232. wrap.style.cssText = "position:fixed;inset:0;background:rgba(2,3,9,0.55);z-index:9999;display:flex;align-items:center;justify-content:center;padding:24px;";
  1233. wrap.innerHTML = `
  1234. <div style="background:#fffaf0;color:#020309;border:2px solid #020309;border-radius:14px;max-width:560px;width:100%;padding:20px;box-shadow:0 8px 32px rgba(0,0,0,0.4);">
  1235. <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
  1236. <strong style="font-size:16px;display:flex;align-items:center;gap:8px;">${this.slackIcon(20)} Escalate to #team-chat</strong>
  1237. <button class="cc-esc-cancel cc-btn" style="padding:3px 10px;font-size:12px;">✕</button>
  1238. </div>
  1239. <div style="margin-bottom:12px;">
  1240. <div style="font-size:11px;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;margin-bottom:6px;">Action item</div>
  1241. <div style="padding:10px;background:#f6f1e1;border:1px solid #020309;border-radius:6px;font-size:13px;white-space:pre-wrap;">${this.esc(payload.item)}</div>
  1242. </div>
  1243. ${payload.context ? `
  1244. <div style="margin-bottom:12px;">
  1245. <div style="font-size:11px;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;margin-bottom:6px;">Context</div>
  1246. <div style="padding:10px;background:#fff;border:1px solid #020309;border-radius:6px;font-size:12px;white-space:pre-wrap;">${this.esc(payload.context)}</div>
  1247. </div>` : ""}
  1248. ${payload.url ? `<div style="margin-bottom:12px;font-size:12px;"><strong>Link:</strong> <a class="cc-link" href="${this.esc(payload.url)}" target="_blank">${this.esc(payload.url)}</a></div>` : ""}
  1249. <div style="margin-bottom:12px;">
  1250. <label style="font-size:11px;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;display:block;margin-bottom:6px;">Notes for the team (optional)</label>
  1251. <textarea class="cc-esc-notes" rows="4" placeholder="Why this needs the team's attention, what you want them to do, etc." style="width:100%;padding:10px;background:#fff;border:1px solid #020309;border-radius:6px;font-size:13px;font-family:inherit;resize:vertical;color:#020309;"></textarea>
  1252. </div>
  1253. <div style="display:flex;gap:8px;justify-content:flex-end;">
  1254. <button class="cc-esc-cancel cc-btn">Cancel</button>
  1255. <button class="cc-esc-send cc-btn cc-btn-primary" style="display:inline-flex;align-items:center;gap:6px;">${this.slackIcon(14)} Send to #team-chat</button>
  1256. </div>
  1257. </div>`;
  1258. document.body.appendChild(wrap);
  1259. const close = () => wrap.remove();
  1260. wrap.addEventListener("click", e => { if (e.target === wrap) close(); });
  1261. wrap.querySelectorAll(".cc-esc-cancel").forEach(b => b.addEventListener("click", close));
  1262. wrap.querySelector(".cc-esc-send").addEventListener("click", () => {
  1263. const notes = wrap.querySelector(".cc-esc-notes").value.trim() || "(none)";
  1264. close();
  1265. const ctx = {
  1266. profile: payload.profile || this.constructor.CONFIG.DEFAULT_PROFILE,
  1267. item: payload.item,
  1268. context: payload.context || "(no extra context)",
  1269. source: payload.source || "dashboard",
  1270. notes,
  1271. };
  1272. const root = document.querySelector(".cc-root:not(.cc-loading)") || document;
  1273. this.runClaude("escalateSlack", root, ctx);
  1274. // Switch to the runs view so the user sees the streaming result.
  1275. const runsNavBtn = root.querySelector?.('.cc-nav-btn[data-view="runs"]');
  1276. if (runsNavBtn) runsNavBtn.click();
  1277. });
  1278. }
  1279. // ===================================================================
  1280. // ccusage — local Claude Code token + cost usage (this machine only)
  1281. // ===================================================================
  1282. ccusageSnapshotPath() { return "Dashboard/snapshots/ccusage.json"; }
  1283. async loadCCUsage() {
  1284. try {
  1285. const adapter = app.vault.adapter;
  1286. const path = this.ccusageSnapshotPath();
  1287. if (!(await adapter.exists(path))) return null;
  1288. const raw = await adapter.read(path);
  1289. return JSON.parse(raw);
  1290. } catch (e) {
  1291. console.warn("[dashboard] loadCCUsage failed", e);
  1292. return null;
  1293. }
  1294. }
  1295. async refreshCCUsageIfStale(maxAgeMs = 60 * 60 * 1000) {
  1296. if (window._ccUsageRefreshing) return;
  1297. const existing = await this.loadCCUsage();
  1298. if (existing?.fetched_at && (Date.now() - existing.fetched_at) < maxAgeMs) return;
  1299. window._ccUsageRefreshing = true;
  1300. try {
  1301. let spawn;
  1302. try { spawn = require("child_process").spawn; } catch { return; }
  1303. const shellPath = process.env.SHELL || "/bin/zsh";
  1304. const cwd = this.vaultBasePath();
  1305. const child = spawn(shellPath, ["-l", "-c", "npx -y ccusage@latest monthly --json"], {
  1306. cwd, env: { ...process.env, NO_COLOR: "1" }, detached: true,
  1307. });
  1308. let out = "";
  1309. child.stdout.on("data", c => out += c.toString());
  1310. child.stderr.on("data", () => {}); // npx is noisy on stderr, ignore
  1311. child.on("close", async (code) => {
  1312. window._ccUsageRefreshing = false;
  1313. if (code !== 0) return;
  1314. try {
  1315. const parsed = JSON.parse(out);
  1316. const agg = this.aggregateCCUsage(parsed);
  1317. agg.fetched_at = Date.now();
  1318. const adapter = app.vault.adapter;
  1319. if (!(await adapter.exists("Dashboard/snapshots"))) {
  1320. try { await adapter.mkdir("Dashboard/snapshots"); } catch {}
  1321. }
  1322. await adapter.write(this.ccusageSnapshotPath(), JSON.stringify(agg, null, 2));
  1323. // Re-render usage strip in place
  1324. this.renderCCUsageStrips(agg);
  1325. } catch (e) {
  1326. console.warn("[dashboard] ccusage parse/write failed", e);
  1327. }
  1328. });
  1329. child.on("error", () => { window._ccUsageRefreshing = false; });
  1330. } catch (e) {
  1331. window._ccUsageRefreshing = false;
  1332. console.warn("[dashboard] refreshCCUsage spawn failed", e);
  1333. }
  1334. }
  1335. aggregateCCUsage(parsed) {
  1336. const months = parsed?.monthly || [];
  1337. const byModel = {};
  1338. let totalCost = 0, totalTokens = 0, totalInput = 0, totalOutput = 0, totalCacheRead = 0, totalCacheCreate = 0;
  1339. let firstPeriod = null, lastPeriod = null;
  1340. for (const m of months) {
  1341. totalCost += m.totalCost || 0;
  1342. totalTokens += m.totalTokens || 0;
  1343. totalInput += m.inputTokens || 0;
  1344. totalOutput += m.outputTokens || 0;
  1345. totalCacheRead += m.cacheReadTokens || 0;
  1346. totalCacheCreate += m.cacheCreationTokens || 0;
  1347. if (!firstPeriod || m.period < firstPeriod) firstPeriod = m.period;
  1348. if (!lastPeriod || m.period > lastPeriod) lastPeriod = m.period;
  1349. for (const mb of (m.modelBreakdowns || [])) {
  1350. const k = mb.modelName || "unknown";
  1351. if (!byModel[k]) byModel[k] = { model: k, cost: 0, tokens: 0, input: 0, output: 0, cacheRead: 0, cacheCreate: 0 };
  1352. byModel[k].cost += mb.cost || 0;
  1353. byModel[k].input += mb.inputTokens || 0;
  1354. byModel[k].output += mb.outputTokens || 0;
  1355. byModel[k].cacheRead += mb.cacheReadTokens || 0;
  1356. byModel[k].cacheCreate += mb.cacheCreationTokens || 0;
  1357. byModel[k].tokens += (mb.inputTokens||0) + (mb.outputTokens||0) + (mb.cacheReadTokens||0) + (mb.cacheCreationTokens||0);
  1358. }
  1359. }
  1360. const models = Object.values(byModel).sort((a, b) => b.cost - a.cost);
  1361. // Current month
  1362. const nowYM = new Date().toISOString().slice(0, 7);
  1363. const currentMonth = months.find(m => m.period === nowYM);
  1364. return {
  1365. total: { cost: totalCost, tokens: totalTokens, input: totalInput, output: totalOutput, cacheRead: totalCacheRead, cacheCreate: totalCacheCreate },
  1366. current_month: currentMonth ? {
  1367. period: currentMonth.period,
  1368. cost: currentMonth.totalCost || 0,
  1369. tokens: currentMonth.totalTokens || 0,
  1370. } : null,
  1371. models, // sorted by cost desc
  1372. firstPeriod, lastPeriod,
  1373. };
  1374. }
  1375. fmtBigNumber(n) {
  1376. if (n == null) return "—";
  1377. n = Number(n) || 0;
  1378. if (n >= 1e9) return (n / 1e9).toFixed(2) + "B";
  1379. if (n >= 1e6) return (n / 1e6).toFixed(1) + "M";
  1380. if (n >= 1e3) return (n / 1e3).toFixed(1) + "K";
  1381. return String(Math.round(n));
  1382. }
  1383. fmtCost(n) {
  1384. n = Number(n) || 0;
  1385. if (n >= 1000) return "$" + (n / 1000).toFixed(2) + "k";
  1386. if (n >= 100) return "$" + n.toFixed(0);
  1387. return "$" + n.toFixed(2);
  1388. }
  1389. modelShortLabel(m) {
  1390. // Strip the "[1m]" suffix and date stamps for compactness
  1391. return String(m || "")
  1392. .replace(/\[\d+m\]/g, "")
  1393. .replace(/-\d{8}$/, "")
  1394. .replace(/^claude-/, "");
  1395. }
  1396. ccusageStripHTML(agg) {
  1397. if (!agg) {
  1398. return `
  1399. <div class="cc-usage-strip" data-ccu-strip style="display:flex;align-items:center;gap:12px;padding:10px 14px;margin-bottom:12px;border:1px solid var(--background-modifier-border,#020309);border-radius:10px;background:#fff;color:#020309;font-size:12px;">
  1400. <strong style="font-size:13px;">Claude usage</strong>
  1401. <span style="opacity:0.65;">No ccusage snapshot yet. Fetching in background…</span>
  1402. </div>`;
  1403. }
  1404. const ageSec = agg.fetched_at ? Math.round((Date.now() - agg.fetched_at) / 1000) : null;
  1405. const ageLabel = ageSec == null ? ""
  1406. : ageSec < 60 ? `${ageSec}s ago`
  1407. : ageSec < 3600 ? `${Math.round(ageSec/60)}m ago`
  1408. : `${Math.round(ageSec/3600)}h ago`;
  1409. const topModels = (agg.models || []).slice(0, 4);
  1410. const monthChip = agg.current_month
  1411. ? `<span class="cc-chip cc-chip-primary">${this.esc(agg.current_month.period)} · ${this.fmtCost(agg.current_month.cost)}</span>`
  1412. : "";
  1413. return `
  1414. <div class="cc-usage-strip" data-ccu-strip style="display:flex;align-items:center;gap:14px;padding:10px 14px;margin-bottom:12px;border:1px solid #020309;border-radius:10px;background:#fff;color:#020309;flex-wrap:wrap;">
  1415. <strong style="font-size:13px;letter-spacing:0.3px;">Claude usage</strong>
  1416. <span style="display:flex;flex-direction:column;align-items:flex-start;">
  1417. <span style="font-size:11px;opacity:0.55;text-transform:uppercase;letter-spacing:0.5px;">Lifetime cost</span>
  1418. <span style="font-size:18px;font-weight:700;line-height:1;">${this.fmtCost(agg.total.cost)}</span>
  1419. </span>
  1420. <span style="display:flex;flex-direction:column;align-items:flex-start;">
  1421. <span style="font-size:11px;opacity:0.55;text-transform:uppercase;letter-spacing:0.5px;">Lifetime tokens</span>
  1422. <span style="font-size:18px;font-weight:700;line-height:1;">${this.fmtBigNumber(agg.total.tokens)}</span>
  1423. </span>
  1424. ${monthChip}
  1425. <span style="flex:1;display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end;">
  1426. ${topModels.map(m => `<span class="cc-chip" title="${this.esc(m.model)} — ${this.fmtBigNumber(m.tokens)} tokens">${this.esc(this.modelShortLabel(m.model))} · ${this.fmtCost(m.cost)}</span>`).join("")}
  1427. </span>
  1428. <span style="font-size:11px;opacity:0.5;">${this.esc(ageLabel)} · ccusage (local)</span>
  1429. </div>`;
  1430. }
  1431. renderCCUsageStrips(agg) {
  1432. document.querySelectorAll("[data-ccu-strip]").forEach(el => {
  1433. const tmp = document.createElement("div");
  1434. tmp.innerHTML = this.ccusageStripHTML(agg);
  1435. el.replaceWith(tmp.firstElementChild);
  1436. });
  1437. }
  1438. // Read a JSON snapshot from a profile's snapshots/ folder. Returns null if missing.
  1439. // Sorts every embedded array newest→oldest by the first detectable date field,
  1440. // so all downstream renderers display latest first without per-list sorting.
  1441. async readSnapshot(name, kind) {
  1442. try {
  1443. const path = `${this.profileSnapshotsPath(name)}/${kind}.json`;
  1444. const adapter = app.vault.adapter;
  1445. if (!(await adapter.exists(path))) return null;
  1446. const raw = await adapter.read(path);
  1447. const parsed = JSON.parse(raw);
  1448. this.sortSnapshotNewestFirst(parsed);
  1449. return parsed;
  1450. } catch (e) {
  1451. console.warn(`[dashboard] readSnapshot(${name}, ${kind}) failed`, e);
  1452. return null;
  1453. }
  1454. }
  1455. // Recursively sort arrays of objects newest-first by the first present date-like key.
  1456. // Mutates in place. Arrays with no detectable date field are left untouched.
  1457. sortSnapshotNewestFirst(node) {
  1458. const DATE_KEYS = ["date_iso", "received_at", "published_at", "posted_at", "last_meeting_iso", "first_seen_iso", "last_call_iso", "due_iso", "date", "created_at"];
  1459. const getDate = (item) => {
  1460. if (!item || typeof item !== "object") return null;
  1461. for (const k of DATE_KEYS) {
  1462. if (item[k]) {
  1463. const t = Date.parse(item[k]);
  1464. if (!isNaN(t)) return t;
  1465. }
  1466. }
  1467. return null;
  1468. };
  1469. const walk = (n) => {
  1470. if (Array.isArray(n)) {
  1471. if (n.length && n.some(it => getDate(it) !== null)) {
  1472. n.sort((a, b) => (getDate(b) ?? -Infinity) - (getDate(a) ?? -Infinity));
  1473. }
  1474. n.forEach(walk);
  1475. } else if (n && typeof n === "object") {
  1476. Object.values(n).forEach(walk);
  1477. }
  1478. };
  1479. walk(node);
  1480. }
  1481. // ===================================================================
  1482. // PROFILE DASHBOARD ({Name}.md) — returns HTML string
  1483. // ===================================================================
  1484. async buildProfileHTML(dv, name) {
  1485. const today = dv.date("today");
  1486. const profileFolder = `${this.profilePath(name)}`;
  1487. const profileFiles = dv.pages(`"${profileFolder}"`);
  1488. const profileDailies = dv.pages(`"${profileFolder}/Daily"`).sort(p => p.file.name, "desc");
  1489. const todayDaily = profileDailies.find(p => p.file.name === today.toFormat("yyyy-MM-dd"));
  1490. const energy = todayDaily?.energy ?? "—";
  1491. const focus = todayDaily?.focus ?? "—";
  1492. const wins = todayDaily?.wins_today ?? 0;
  1493. const loops = todayDaily?.open_loops ?? 0;
  1494. const meetings = todayDaily?.meetings_attended ?? 0;
  1495. const last7 = this.last7Days(dv);
  1496. const prev7 = [...Array(7)].map((_, i) => today.minus({ days: 13 - i }));
  1497. const activity7 = last7.map(d => ({ date: d, value: this.activityFor(d, profileFiles), label: this.dayLabel(d) }));
  1498. const totalThis = activity7.reduce((a, b) => a + b.value, 0);
  1499. const totalPrev = prev7.reduce((a, b) => a + this.activityFor(b, profileFiles), 0);
  1500. const deltaPct = totalPrev ? Math.round(((totalThis - totalPrev) / totalPrev) * 100) : (totalThis > 0 ? 100 : 0);
  1501. const energyHist = last7.map(d => profileDailies.find(p => p.file.name === d.toFormat("yyyy-MM-dd"))?.energy ?? null).filter(v => v !== null);
  1502. const energyAvg = energyHist.length ? Math.round(energyHist.reduce((a, b) => a + b, 0) / energyHist.length * 10) / 10 : 0;
  1503. const energyDelta = energyHist.length >= 2 ? (energyHist[energyHist.length - 1] - energyHist[0]) : 0;
  1504. const dailyNames = Array.from(profileDailies).map(p => p.file.name);
  1505. let streak = 0;
  1506. for (let i = 0; i < 365; i++) {
  1507. const d = today.minus({ days: i });
  1508. if (dailyNames.includes(d.toFormat("yyyy-MM-dd"))) streak++;
  1509. else if (i > 0) break;
  1510. }
  1511. const last30 = this.last30Days(dv);
  1512. const heat = last30.map(d => ({ date: d, count: this.activityFor(d, profileFiles) }));
  1513. const heatMax = Math.max(...heat.map(d => d.count), 1);
  1514. const recentFiles = profileFiles.where(p => p.file.mtime > today.minus({ days: 7 }));
  1515. const folderCounts = {};
  1516. for (const p of recentFiles) {
  1517. const parts = p.file.folder.split("/");
  1518. const key = parts.slice(3, 5).join("/") || "(root)";
  1519. folderCounts[key] = (folderCounts[key] || 0) + 1;
  1520. }
  1521. const topFolders = Object.entries(folderCounts).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([n, c]) => ({ name: n, count: c }));
  1522. const folderMax = Math.max(...topFolders.map(f => f.count), 1);
  1523. const goals = dv.pages("#goal")
  1524. .where(p => p.status !== "done" && p.status !== "archived")
  1525. .where(p => !p.profile || String(p.profile).toLowerCase() === name.toLowerCase())
  1526. .sort(p => p.priority ?? 99, "asc");
  1527. const goalsWithPct = goals.map(g => ({ link: g, name: g.file.name, pct: Math.max(0, Math.min(100, Number(g.progress ?? 0))) }));
  1528. const avgGoalProgress = goalsWithPct.length ? Math.round(goalsWithPct.reduce((a, b) => a + b.pct, 0) / goalsWithPct.length) : 0;
  1529. // Active tasks (sorted by due date desc)
  1530. let activeTasks = [];
  1531. try {
  1532. const tasksPage = dv.pages(`"${profileFolder}/task-list"`).find(p => p.file.name === "Tasks");
  1533. if (tasksPage) {
  1534. const raw = await dv.io.load(tasksPage.file.path);
  1535. const lines = (raw || "").split("\n");
  1536. for (const l of lines) {
  1537. if (/^\s*- \[ \] /.test(l)) {
  1538. const text = l.replace(/^\s*- \[ \] /, "").trim();
  1539. activeTasks.push({ text, due: this.extractTaskDate(text) });
  1540. }
  1541. }
  1542. }
  1543. } catch (e) {}
  1544. activeTasks.sort((a, b) => {
  1545. if (a.due && b.due) return b.due.localeCompare(a.due);
  1546. if (a.due) return -1;
  1547. if (b.due) return 1;
  1548. return 0;
  1549. });
  1550. activeTasks = activeTasks.slice(0, 20);
  1551. const outputs = profileDailies.slice(0, 10);
  1552. const outRows = outputs.map(p => [this.link(p), this.rel(p.file.mtime, today)]);
  1553. // Snapshot reads happen up front so the synthesis overview can use them.
  1554. const communitySnap = await this.readSnapshot(name, "community");
  1555. const youtubeSnap = await this.readSnapshot(name, "youtube");
  1556. const commsSnap = await this.readSnapshot(name, "comms");
  1557. const meetingsSnap = await this.readSnapshot(name, "meetings");
  1558. const intelSnap = await this.readSnapshot(name, "intelligence");
  1559. const researchSnap = await this.readSnapshot(name, "research");
  1560. const fmtAge = (iso) => {
  1561. if (!iso) return "—";
  1562. try { return this.rel(dv.luxon.DateTime.fromISO(iso), today); } catch { return "—"; }
  1563. };
  1564. const stale = (iso, hours = 24) => {
  1565. if (!iso) return true;
  1566. try { return dv.luxon.DateTime.fromISO(iso) < today.minus({ hours }); } catch { return true; }
  1567. };
  1568. const refreshButton = (key, label) => this.actionButton(key, `🔄 ${label}`, { profile: name, variant: "primary" });
  1569. const updatedTag = (snap) => snap?.updated_at
  1570. ? `<span class="cc-tag ${stale(snap.updated_at) ? "cc-chip-alert" : ""}">updated ${this.esc(fmtAge(snap.updated_at))}</span>`
  1571. : `<span class="cc-tag cc-chip-alert">no snapshot</span>`;
  1572. // Derived numbers for synthesis overview
  1573. const urgentCount = commsSnap?.urgent?.length ?? 0;
  1574. const needsReply = commsSnap?.needs_reply?.length ?? 0;
  1575. const subs = youtubeSnap?.channel?.subscribers ?? null;
  1576. const subsDelta = youtubeSnap?.channel?.subscribers_delta_7d ?? null;
  1577. const subsDeltaPct = (subs && subsDelta) ? Math.round((subsDelta / Math.max(1, subs - subsDelta)) * 100) : null;
  1578. const members = communitySnap?.stats?.total_members ?? null;
  1579. const activeToday = communitySnap?.stats?.active_today ?? null;
  1580. const mentions = communitySnap?.mentions?.length ?? 0;
  1581. const unreadDMs = (communitySnap?.dms || []).filter(d => d.unread).length;
  1582. const recentVideo = (youtubeSnap?.recent_videos || [])[0];
  1583. const topUrgent = (commsSnap?.urgent || [])[0];
  1584. const topNeedsReply = (commsSnap?.needs_reply || [])[0];
  1585. const recentPost = (communitySnap?.recent_posts || [])[0];
  1586. const topMention = (communitySnap?.mentions || [])[0];
  1587. // Intelligence-surface signals for the Overview header strip
  1588. const topBrief = (intelSnap?.opportunity_briefs || [])[0];
  1589. const topCrossTheme = (intelSnap?.cross_validated_themes || []).find(t => t.priority === "p0")
  1590. || (intelSnap?.cross_validated_themes || [])[0];
  1591. const decisionsToDoc = (intelSnap?.decisions_to_document || []).length;
  1592. const churnSignals = (intelSnap?.churn_signals || []).length;
  1593. // ccusage — local machine usage strip
  1594. const ccusageAgg = await this.loadCCUsage();
  1595. this.refreshCCUsageIfStale();
  1596. const overviewHTML = `
  1597. <section class="cc-view" data-view="overview">
  1598. ${this.ccusageStripHTML(ccusageAgg)}
  1599. <div class="cc-kpis">
  1600. <div class="cc-kpi cc-kpi-primary">
  1601. <div class="cc-kpi-head"><span class="cc-kpi-label">YouTube subscribers</span>${subsDeltaPct != null ? this.deltaPill(subsDeltaPct) : ""}</div>
  1602. <div class="cc-kpi-value">${subs != null ? subs.toLocaleString() : "—"}</div>
  1603. <div class="cc-kpi-foot">${subsDelta != null ? `+${subsDelta.toLocaleString()} past 7d` : "click Refresh on YouTube"}</div>
  1604. </div>
  1605. <div class="cc-kpi">
  1606. <div class="cc-kpi-head"><span class="cc-kpi-label">Community</span></div>
  1607. <div class="cc-kpi-value">${members != null ? members.toLocaleString() : "—"}</div>
  1608. <div class="cc-kpi-foot">${activeToday != null ? `${activeToday} active today` : "members"}</div>
  1609. </div>
  1610. <div class="cc-kpi ${urgentCount ? "cc-kpi-alert" : ""}">
  1611. <div class="cc-kpi-head"><span class="cc-kpi-label">Urgent inbox</span></div>
  1612. <div class="cc-kpi-value">${urgentCount}</div>
  1613. <div class="cc-kpi-foot">${needsReply} need a reply</div>
  1614. </div>
  1615. <div class="cc-kpi">
  1616. <div class="cc-kpi-head"><span class="cc-kpi-label">Active tasks</span></div>
  1617. <div class="cc-kpi-value">${activeTasks.length}</div>
  1618. <div class="cc-kpi-foot">${(activeTasks.filter(t => t.due).length)} with a due date</div>
  1619. </div>
  1620. </div>
  1621. ${intelSnap ? `
  1622. <div class="cc-card cc-card-wide">
  1623. <div class="cc-card-head">
  1624. <h3>Top intelligence</h3>
  1625. <a class="cc-tag cc-nav-btn" data-view="intelligence" style="cursor:pointer;">See all →</a>
  1626. </div>
  1627. <div class="cc-card-body">
  1628. <div style="display:flex;gap:14px;flex-wrap:wrap;">
  1629. ${topBrief ? `
  1630. <div style="flex:1;min-width:280px;border-left:3px solid #020309;padding:8px 12px;background:#f6f1e1;">
  1631. <span class="cc-chip cc-chip-primary">brief</span>
  1632. <strong style="display:block;margin:6px 0 4px;">${this.esc(topBrief.title||"")}</strong>
  1633. <p style="margin:0 0 6px;font-size:13px;">${this.esc((topBrief.summary||"").slice(0,200))}</p>
  1634. <p style="margin:0;font-size:12px;"><strong>Next:</strong> ${this.esc((topBrief.recommended_next_action||"").slice(0,160))}</p>
  1635. </div>` : ""}
  1636. ${topCrossTheme ? `
  1637. <div style="flex:1;min-width:240px;border-left:3px solid #020309;padding:8px 12px;background:#fff;">
  1638. <div style="display:flex;align-items:center;gap:6px;margin-bottom:6px;">${this.priorityChip(topCrossTheme.priority)} <span class="cc-muted" style="font-size:11px;">cross-validated</span></div>
  1639. <strong style="display:block;margin:0 0 4px;">${this.esc(topCrossTheme.theme||"")}</strong>
  1640. <div style="display:flex;gap:4px;flex-wrap:wrap;align-items:center;margin:0 0 6px;font-size:12px;">${(topCrossTheme.sources||[]).map(s => this.sourceChip(s)).join("")} <span class="cc-muted">${topCrossTheme.combined_mention_count||0}× combined</span></div>
  1641. <p style="margin:0;font-size:12px;color:#020309;opacity:0.7;">${this.esc((topCrossTheme.why||"").slice(0,160))}</p>
  1642. </div>` : ""}
  1643. </div>
  1644. ${(decisionsToDoc || churnSignals) ? `
  1645. <div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;font-size:12px;">
  1646. ${decisionsToDoc ? `<span class="cc-chip cc-chip-alert">${decisionsToDoc} decisions to document</span>` : ""}
  1647. ${churnSignals ? `<span class="cc-chip cc-chip-alert">${churnSignals} churn signals</span>` : ""}
  1648. <span class="cc-muted">→ <a class="cc-nav-btn" data-view="intelligence" style="cursor:pointer;text-decoration:underline;">Intelligence</a></span>
  1649. </div>` : ""}
  1650. </div>
  1651. </div>` : ""}
  1652. <div class="cc-card cc-card-wide">
  1653. <div class="cc-card-head"><h3>Top of the inbox</h3>${updatedTag(commsSnap)}</div>
  1654. <div class="cc-card-body">
  1655. ${topUrgent || topNeedsReply
  1656. ? `<div style="display:flex;flex-direction:column;gap:10px;">
  1657. ${topUrgent ? `<div><span class="cc-chip cc-chip-alert">urgent</span> <span class="cc-chip">${this.esc(topUrgent.source||"—")}</span><br><strong>${this.esc(topUrgent.from||"—")}</strong> · ${this.esc((topUrgent.subject||"").slice(0,80))}<br><span class="cc-muted" style="font-size:12px;">${this.esc((topUrgent.suggested_action||"").slice(0,140))}</span></div>` : ""}
  1658. ${topNeedsReply ? `<div><span class="cc-chip cc-chip-primary">needs reply</span> <span class="cc-chip">${this.esc(topNeedsReply.source||"—")}</span><br><strong>${this.esc(topNeedsReply.from||"—")}</strong> · ${this.esc((topNeedsReply.subject||"").slice(0,80))}<br><span class="cc-muted" style="font-size:12px;">${this.esc((topNeedsReply.suggested_action||"").slice(0,140))}</span></div>` : ""}
  1659. </div>`
  1660. : `<div class="cc-empty">No comms snapshot. Visit Comms to refresh.</div>`}
  1661. </div>
  1662. </div>
  1663. <div class="cc-card cc-card-wide">
  1664. <div class="cc-card-head"><h3>Latest video</h3>${updatedTag(youtubeSnap)}</div>
  1665. <div class="cc-card-body">
  1666. ${recentVideo ? (() => {
  1667. const ytPerf = (youtubeSnap?.video_performance || []).find(p => (p.url && p.url === recentVideo.url) || (p.title && p.title === recentVideo.title));
  1668. const ytAllComments = youtubeSnap?.recent_comments || [];
  1669. const norm = (s) => String(s||"").toLowerCase().trim();
  1670. let ytTopComments = ytAllComments.filter(c =>
  1671. (c.video_url && recentVideo.url && c.video_url === recentVideo.url) ||
  1672. (c.video_title && norm(c.video_title) === norm(recentVideo.title))
  1673. ).slice(0, 3);
  1674. let ytFallback = false;
  1675. if (!ytTopComments.length && ytAllComments.length) { ytTopComments = ytAllComments.slice(0, 3); ytFallback = true; }
  1676. const v = Number(recentVideo.views) || 0;
  1677. const l = Number(recentVideo.likes) || 0;
  1678. const eng = v > 0 ? Math.round((l / v) * 10000) / 100 : null;
  1679. const pct = ytPerf?.vs_channel_avg_pct;
  1680. const perfCls = pct == null ? "" : pct > 20 ? "cc-chip-accent" : pct < -20 ? "cc-chip-alert" : "cc-chip-primary";
  1681. const perfSign = pct > 0 ? "+" : "";
  1682. return `
  1683. <div style="display:flex;gap:14px;flex-wrap:wrap;align-items:flex-start;">
  1684. ${(() => { const thumb = recentVideo.thumbnail || this.youtubeThumbFromUrl(recentVideo.url); return thumb ? `<a href="${this.esc(recentVideo.url||"#")}" target="_blank" style="flex-shrink:0;display:block;width:200px;border-radius:8px;overflow:hidden;border:1px solid #020309;"><img src="${this.esc(thumb)}" alt="" style="width:100%;display:block;" onerror="this.parentElement.style.display='none'"/></a>` : ""; })()}
  1685. <div style="flex:1;min-width:260px;">
  1686. <strong style="font-size:14px;line-height:1.3;display:block;margin-bottom:6px;">${recentVideo.url ? `<a class="cc-link" href="${this.esc(recentVideo.url)}" target="_blank">${this.esc(recentVideo.title||"")}</a>` : this.esc(recentVideo.title||"")}</strong>
  1687. <span class="cc-muted" style="font-size:12px;">${this.esc(fmtAge(recentVideo.published_at))}</span>
  1688. <div style="display:flex;gap:12px;flex-wrap:wrap;margin:10px 0;">
  1689. <div><div style="font-size:16px;font-weight:700;line-height:1;">${v.toLocaleString()}</div><div style="font-size:10px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Views</div></div>
  1690. <div><div style="font-size:16px;font-weight:700;line-height:1;">${l.toLocaleString()}</div><div style="font-size:10px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Likes</div></div>
  1691. <div><div style="font-size:16px;font-weight:700;line-height:1;">${(Number(recentVideo.comments)||0).toLocaleString()}</div><div style="font-size:10px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Comments</div></div>
  1692. ${eng != null ? `<div><div style="font-size:16px;font-weight:700;line-height:1;">${eng}%</div><div style="font-size:10px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Like rate</div></div>` : ""}
  1693. </div>
  1694. ${pct != null ? `<div style="margin-bottom:8px;font-size:12px;"><span class="cc-chip ${perfCls}">${perfSign}${pct}% vs channel avg</span></div>` : ""}
  1695. ${ytTopComments.length ? `
  1696. <div style="font-size:11px;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;margin:6px 0;">${ytFallback ? "Recent comments" : "Top comments"}</div>
  1697. <ul class="cc-md-list" style="margin:0;font-size:12px;">${ytTopComments.map(c => { const body = c.text || c.snippet || c.comment || c.body || ""; return `<li><strong>${this.esc(c.author||"—")}</strong>: ${this.esc(body.slice(0,160))}</li>`; }).join("")}</ul>` : ""}
  1698. </div>
  1699. </div>`;
  1700. })() : `<div class="cc-empty">No YouTube snapshot. Visit YouTube to refresh.</div>`}
  1701. </div>
  1702. </div>
  1703. <div class="cc-card cc-card-wide">
  1704. <div class="cc-card-head"><h3>Community pulse</h3>${updatedTag(communitySnap)}</div>
  1705. <div class="cc-card-body">
  1706. ${communitySnap ? (() => {
  1707. const themes = communitySnap.themes || [];
  1708. const pains = communitySnap.pain_points || [];
  1709. const stuck = (communitySnap.stuck_members || []).length;
  1710. const needsReply = (communitySnap.needs_my_reply || []).length;
  1711. const power = (communitySnap.power_users || [])[0];
  1712. const topTheme = [...themes].sort((a,b)=> (b.frequency_4w||0) - (a.frequency_4w||0))[0];
  1713. const topPain = [...pains].sort((a,b)=> (b.frequency||0) - (a.frequency||0))[0];
  1714. const trendVerb = (t) => t?.trend === "rising" ? "is heating up" : t?.trend === "fading" ? "is cooling off" : "is the steady drumbeat";
  1715. const sentenceParts = [];
  1716. if (topTheme) sentenceParts.push(`<strong>${this.esc(topTheme.name||"")}</strong> ${trendVerb(topTheme)} — surfaced ${topTheme.frequency_4w||0}× in the last 4 weeks${topTheme.sentiment ? ` with ${this.esc(topTheme.sentiment)} sentiment` : ""}.`);
  1717. if (topPain) sentenceParts.push(`The loudest pain point is <strong>${this.esc(topPain.name||"")}</strong> (${this.esc(topPain.severity||"medium")} severity, mentioned ${topPain.frequency||0}×).`);
  1718. if (topMention) sentenceParts.push(`Most recent mention of you: <strong>${this.esc(topMention.author||"")}</strong> — "${this.esc((topMention.context||"").slice(0,140))}"${topMention.url ? ` <a class="cc-link" href="${this.esc(topMention.url)}" target="_blank">(view)</a>` : ""}.`);
  1719. if (recentPost) sentenceParts.push(`Latest post: ${recentPost.url ? `<a class="cc-link" href="${this.esc(recentPost.url)}" target="_blank"><strong>${this.esc(recentPost.title||"")}</strong></a>` : `<strong>${this.esc(recentPost.title||"")}</strong>`} by ${this.esc(recentPost.author||"someone")} (${recentPost.comments||0} comments, ${recentPost.likes||0} likes).`);
  1720. if (needsReply || stuck) sentenceParts.push(`${needsReply ? `<strong>${needsReply}</strong> ${needsReply===1?"item needs":"items need"} your personal reply` : ""}${needsReply && stuck ? " and " : ""}${stuck ? `<strong>${stuck}</strong> ${stuck===1?"member is":"members are"} stuck` : ""}.`);
  1721. if (power) sentenceParts.push(`⭐ <strong>${this.esc(power.name||"")}</strong> is leading contributions with ${power.contribution_count_4w||0} this month — a natural ambassador.`);
  1722. if (!sentenceParts.length) sentenceParts.push("Snapshot loaded but the synthesis fields are empty. Refresh the community snapshot to populate themes, pain points, and mentions.");
  1723. return `<p style="margin:0;line-height:1.55;font-size:13px;">${sentenceParts.join(" ")}</p>`;
  1724. })() : `<div class="cc-empty">No community snapshot. Visit Community to refresh.</div>`}
  1725. </div>
  1726. </div>
  1727. </section>`;
  1728. const tasksHTML = `
  1729. <section class="cc-view" data-view="tasks" hidden>
  1730. <div class="cc-card cc-card-wide">
  1731. <div class="cc-card-head"><h3>${name}'s active tasks</h3><span class="cc-tag">${activeTasks.length}</span></div>
  1732. <div class="cc-card-body">
  1733. ${activeTasks.length
  1734. ? `<table class="cc-table cc-table-tasks">
  1735. <thead><tr><th style="width:110px">Due</th><th>Task</th></tr></thead>
  1736. <tbody>${activeTasks.map(t => `<tr>
  1737. <td>${t.due ? `<span class="cc-chip-date">${this.esc(t.due)}</span>` : `<span class="cc-muted">—</span>`}</td>
  1738. <td>${this.md(this.stripTaskMeta(t.text))}</td>
  1739. </tr>`).join("")}</tbody>
  1740. </table>`
  1741. : `<div class="cc-empty">No active tasks in <code>${profileFolder}/task-list/Tasks.md</code>.</div>`}
  1742. </div>
  1743. </div>
  1744. </section>`;
  1745. const dailyHTML = `
  1746. <section class="cc-view" data-view="daily" hidden>
  1747. <div class="cc-card cc-card-wide">
  1748. <div class="cc-card-head"><h3>Recent dailies</h3><span class="cc-tag">${outputs.length}</span></div>
  1749. <div class="cc-card-body">${this.tableHTML(["File", "Updated"], outRows, "No recent dailies.")}</div>
  1750. </div>
  1751. </section>`;
  1752. const communityHTML = `
  1753. <section class="cc-view" data-view="community" hidden>
  1754. <div class="cc-card cc-card-wide">
  1755. <div class="cc-card-head">
  1756. <h3>Community pulse</h3>
  1757. ${updatedTag(communitySnap)}
  1758. </div>
  1759. <div class="cc-card-body">
  1760. <div style="margin-bottom:12px;">${refreshButton("refreshCommunity", "Refresh community")}</div>
  1761. ${communitySnap ? (() => {
  1762. const needsReplyCount = (communitySnap.needs_my_reply || []).length;
  1763. const stuckCount = (communitySnap.stuck_members || []).length;
  1764. const mentionsCount = (communitySnap.mentions || []).length;
  1765. const painCount = (communitySnap.pain_points || []).length;
  1766. const themesCount = (communitySnap.themes || []).length;
  1767. const topTheme = (communitySnap.themes || []).sort((a,b) => (b.frequency_4w||0) - (a.frequency_4w||0))[0];
  1768. const topPower = (communitySnap.power_users || []).sort((a,b) => (b.contribution_count_4w||0) - (a.contribution_count_4w||0))[0];
  1769. return `
  1770. <div class="cc-kpis" style="margin-bottom:12px;">
  1771. <div class="cc-kpi cc-kpi-primary">
  1772. <div class="cc-kpi-head"><span class="cc-kpi-label">Members</span></div>
  1773. <div class="cc-kpi-value">${(communitySnap.stats?.total_members ?? 0).toLocaleString()}</div>
  1774. <div class="cc-kpi-foot">${communitySnap.stats?.active_today != null ? `${communitySnap.stats.active_today} active today` : "in the community"}</div>
  1775. </div>
  1776. <div class="cc-kpi ${needsReplyCount ? "cc-kpi-alert" : ""}">
  1777. <div class="cc-kpi-head"><span class="cc-kpi-label">Needs my reply</span></div>
  1778. <div class="cc-kpi-value">${needsReplyCount}</div>
  1779. <div class="cc-kpi-foot">${mentionsCount} mentions tracked</div>
  1780. </div>
  1781. <div class="cc-kpi ${stuckCount ? "cc-kpi-alert" : ""}">
  1782. <div class="cc-kpi-head"><span class="cc-kpi-label">Stuck members</span></div>
  1783. <div class="cc-kpi-value">${stuckCount}</div>
  1784. <div class="cc-kpi-foot">${painCount} pain points open</div>
  1785. </div>
  1786. <div class="cc-kpi">
  1787. <div class="cc-kpi-head"><span class="cc-kpi-label">Top theme · 4w</span></div>
  1788. <div class="cc-kpi-value" style="font-size:15px;line-height:1.2;font-weight:700;min-height:32px;">${topTheme ? this.esc((topTheme.name||"").slice(0,42)) : "—"}</div>
  1789. <div class="cc-kpi-foot">${topTheme ? `${topTheme.frequency_4w||0}× · ${this.esc(topTheme.trend||"steady")}` : `${themesCount} themes tracked`}</div>
  1790. </div>
  1791. </div>
  1792. ${topPower ? `<div style="margin-bottom:12px;font-size:12px;opacity:0.75;">⭐ <strong>${this.esc(topPower.name||"")}</strong> is your top contributor this month with ${topPower.contribution_count_4w||0} contributions.</div>` : ""}`;
  1793. })() : `<div class="cc-empty">No community snapshot yet. Click <strong>Refresh community</strong> above to fetch via Circle MCP.</div>`}
  1794. </div>
  1795. </div>
  1796. ${communitySnap ? `
  1797. <div class="cc-grid cc-grid-2">
  1798. <div class="cc-card">
  1799. <div class="cc-card-head"><h3>Recent posts</h3><span class="cc-tag">${(communitySnap.recent_posts||[]).length}</span></div>
  1800. <div class="cc-card-body">
  1801. ${(communitySnap.recent_posts||[]).length
  1802. ? `<table class="cc-table"><thead><tr><th>Post</th><th style="width:90px">Author</th><th style="width:60px">💬</th><th style="width:60px">❤️</th></tr></thead>
  1803. <tbody>${(communitySnap.recent_posts||[]).slice(0,10).map(p => `<tr>
  1804. <td>${p.url ? `<a class="cc-link" href="${this.esc(p.url)}" target="_blank">${this.esc(p.title || "(untitled)")}</a>` : this.esc(p.title || "(untitled)")}</td>
  1805. <td>${this.esc(p.author || "—")}</td>
  1806. <td>${p.comments ?? "—"}</td>
  1807. <td>${p.likes ?? "—"}</td>
  1808. </tr>`).join("")}</tbody></table>`
  1809. : `<div class="cc-empty">None.</div>`}
  1810. </div>
  1811. </div>
  1812. <div class="cc-card">
  1813. <div class="cc-card-head"><h3>Recent comments</h3><span class="cc-tag">${(communitySnap.recent_comments||[]).length}</span></div>
  1814. <div class="cc-card-body">
  1815. ${(communitySnap.recent_comments||[]).length
  1816. ? `<ul class="cc-md-list">${(communitySnap.recent_comments||[]).slice(0,10).map(c => { const body = c.text || c.snippet || c.comment || c.body || c.content || ""; return `<li><strong>${this.esc(c.author||"—")}</strong> on <em>${this.esc(c.post_title||"")}</em>: ${this.esc(body.slice(0,160))}</li>`; }).join("")}</ul>`
  1817. : `<div class="cc-empty">None.</div>`}
  1818. </div>
  1819. </div>
  1820. <div class="cc-card">
  1821. <div class="cc-card-head"><h3>Mentions of ${this.esc(name)}</h3><span class="cc-tag">${(communitySnap.mentions||[]).length}</span></div>
  1822. <div class="cc-card-body">
  1823. ${(communitySnap.mentions||[]).length
  1824. ? `<ul class="cc-md-list">${(communitySnap.mentions||[]).slice(0,10).map(m => `<li><strong>${this.esc(m.author||"—")}</strong>: ${this.esc((m.context||"").slice(0,160))} <span class="cc-muted">${this.esc(fmtAge(m.posted_at))}</span></li>`).join("")}</ul>`
  1825. : `<div class="cc-empty">None.</div>`}
  1826. </div>
  1827. </div>
  1828. <div class="cc-card">
  1829. <div class="cc-card-head"><h3>Replies to me</h3><span class="cc-tag">${(communitySnap.replies_to_me||[]).length}</span></div>
  1830. <div class="cc-card-body">
  1831. ${(communitySnap.replies_to_me||[]).length
  1832. ? `<ul class="cc-md-list">${(communitySnap.replies_to_me||[]).slice(0,10).map(r => `<li><strong>${this.esc(r.author||"—")}</strong> on <em>${this.esc(r.post_title||"")}</em>: ${this.esc((r.snippet||"").slice(0,140))}</li>`).join("")}</ul>`
  1833. : `<div class="cc-empty">None.</div>`}
  1834. </div>
  1835. </div>
  1836. </div>
  1837. <div class="cc-card cc-card-wide">
  1838. <div class="cc-card-head"><h3>Needs my reply</h3><span class="cc-tag cc-chip-primary">${(communitySnap.needs_my_reply||[]).length}</span></div>
  1839. <div class="cc-card-body">
  1840. ${(communitySnap.needs_my_reply||[]).length
  1841. ? `<table class="cc-table"><thead><tr><th style="width:90px">Urgency</th><th style="width:140px">From</th><th>Context</th><th>Suggested angle</th><th style="width:100px"></th></tr></thead>
  1842. <tbody>${(communitySnap.needs_my_reply||[]).map(r => `<tr>
  1843. <td><span class="cc-chip ${r.urgency==='high'?'cc-chip-alert':r.urgency==='medium'?'cc-chip-primary':''}">${this.esc(r.urgency||"—")}</span></td>
  1844. <td><strong>${this.esc(r.from||"—")}</strong></td>
  1845. <td>${r.url ? `<a class="cc-link" href="${this.esc(r.url)}" target="_blank">${this.esc((r.context||"").slice(0,180))}</a>` : this.esc((r.context||"").slice(0,180))}</td>
  1846. <td><span class="cc-muted">${this.esc((r.suggested_response_angle||"").slice(0,140))}</span></td>
  1847. <td>${this.escalateButton(`${r.from||"unknown"} needs my reply: ${r.context||""}`, { context: r.suggested_response_angle, source: `community · ${name}`, url: r.url, profile: name })}</td>
  1848. </tr>`).join("")}</tbody></table>`
  1849. : `<div class="cc-empty">Nothing flagged for personal reply.</div>`}
  1850. </div>
  1851. </div>
  1852. <div class="cc-grid cc-grid-2">
  1853. <div class="cc-card">
  1854. <div class="cc-card-head"><h3>Recurring themes</h3><span class="cc-tag">${(communitySnap.themes||[]).length} · last 4w</span></div>
  1855. <div class="cc-card-body">
  1856. ${(communitySnap.themes||[]).length
  1857. ? `<div>${(communitySnap.themes||[]).map(t => this.listItem({
  1858. title: t.name || "",
  1859. chipsHTML: [
  1860. this.metaChip(t.trend || "steady", this.toneFor(t.trend, "trend")),
  1861. this.metaChip(`${t.frequency_4w||0}×`, "count"),
  1862. this.metaChip(t.sentiment || "neutral", this.toneFor(t.sentiment, "sentiment")),
  1863. ].join(""),
  1864. sub: (t.sample_quotes||[]).length ? `"${(t.sample_quotes[0]||"").slice(0,160)}"` : null,
  1865. })).join("")}</div>`
  1866. : `<div class="cc-empty">None.</div>`}
  1867. </div>
  1868. </div>
  1869. <div class="cc-card">
  1870. <div class="cc-card-head"><h3>Pain points</h3><span class="cc-tag cc-chip-alert">${(communitySnap.pain_points||[]).length}</span></div>
  1871. <div class="cc-card-body">
  1872. ${(communitySnap.pain_points||[]).length
  1873. ? `<div>${(communitySnap.pain_points||[]).map(p => this.listItem({
  1874. title: p.name || "",
  1875. chipsHTML: [
  1876. this.metaChip(p.severity || "medium", this.toneFor(p.severity, "severity")),
  1877. this.metaChip(`${p.frequency||0}×`, "count"),
  1878. ].join(""),
  1879. sub: (p.examples||[]).length ? `"${(p.examples[0]||"").slice(0,160)}"` : null,
  1880. })).join("")}</div>`
  1881. : `<div class="cc-empty">None.</div>`}
  1882. </div>
  1883. </div>
  1884. </div>
  1885. <div class="cc-grid cc-grid-2">
  1886. <div class="cc-card">
  1887. <div class="cc-card-head"><h3>Stuck members</h3><span class="cc-tag cc-chip-alert">${(communitySnap.stuck_members||[]).length}</span></div>
  1888. <div class="cc-card-body">
  1889. ${(communitySnap.stuck_members||[]).length
  1890. ? `<div>${(communitySnap.stuck_members||[]).map(m => this.listItem({
  1891. title: m.name || "",
  1892. titleHref: m.url || null,
  1893. chipsHTML: [
  1894. this.metaChip(`${m.days_stuck||"?"}d stuck`, "alert"),
  1895. this.escalateButton(`${m.name||"member"} is stuck (${m.days_stuck||"?"}d)`, { context: `${m.reason||""}${m.last_unanswered_question ? " · Question: " + m.last_unanswered_question : ""}`, source: `community · ${name}`, url: m.url, profile: name }),
  1896. ].join(""),
  1897. sub: `${this.esc((m.reason||"").slice(0,140))}${m.last_unanswered_question ? ` · "${this.esc((m.last_unanswered_question||"").slice(0,120))}"` : ""}`,
  1898. subIsHTML: true,
  1899. })).join("")}</div>`
  1900. : `<div class="cc-empty">No one stuck. 🎉</div>`}
  1901. </div>
  1902. </div>
  1903. <div class="cc-card">
  1904. <div class="cc-card-head"><h3>Power users</h3><span class="cc-tag cc-chip-accent">${(communitySnap.power_users||[]).length}</span></div>
  1905. <div class="cc-card-body">
  1906. ${(communitySnap.power_users||[]).length
  1907. ? `<div>${(communitySnap.power_users||[]).map(u => this.listItem({
  1908. title: u.name || "",
  1909. titleHref: u.url || null,
  1910. chipsHTML: this.metaChip(`${u.contribution_count_4w||0} contributions`, "count"),
  1911. sub: u.notes ? u.notes.slice(0,140) : null,
  1912. })).join("")}</div>`
  1913. : `<div class="cc-empty">None.</div>`}
  1914. </div>
  1915. </div>
  1916. </div>
  1917. <div class="cc-card cc-card-wide">
  1918. <div class="cc-card-head"><h3>Content gaps</h3><span class="cc-tag">${(communitySnap.content_gaps||[]).length}</span></div>
  1919. <div class="cc-card-body">
  1920. ${(communitySnap.content_gaps||[]).length
  1921. ? `<table class="cc-table"><thead><tr><th>Question</th><th style="width:70px">Asks</th><th style="width:90px">Format</th><th style="width:80px">Source</th></tr></thead>
  1922. <tbody>${(communitySnap.content_gaps||[]).map(g => `<tr>
  1923. <td><strong>${this.esc(g.question||"")}</strong></td>
  1924. <td>${g.ask_count||0}×</td>
  1925. <td><span class="cc-chip">${this.esc(g.suggested_format||"—")}</span></td>
  1926. <td>${g.best_source_post_url ? `<a class="cc-link" href="${this.esc(g.best_source_post_url)}" target="_blank">link</a>` : "—"}</td>
  1927. </tr>`).join("")}</tbody></table>`
  1928. : `<div class="cc-empty">None.</div>`}
  1929. </div>
  1930. </div>
  1931. <div class="cc-card cc-card-wide">
  1932. <div class="cc-card-head"><h3>DMs</h3><span class="cc-tag">${(communitySnap.dms||[]).length}</span></div>
  1933. <div class="cc-card-body">
  1934. ${(communitySnap.dms||[]).length
  1935. ? `<table class="cc-table"><thead><tr><th style="width:180px">From</th><th>Message</th><th style="width:110px">When</th></tr></thead>
  1936. <tbody>${(communitySnap.dms||[]).slice(0,15).map(d => `<tr>
  1937. <td><div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;"><strong>${this.esc(d.from||"—")}</strong>${d.unread ? '<span class="cc-chip cc-chip-alert" style="flex-shrink:0;">new</span>' : ''}</div></td>
  1938. <td>${this.esc((d.snippet||"").slice(0,200))}</td>
  1939. <td>${this.esc(fmtAge(d.received_at))}</td>
  1940. </tr>`).join("")}</tbody></table>`
  1941. : `<div class="cc-empty">No DMs.</div>`}
  1942. </div>
  1943. </div>` : ``}
  1944. </section>`;
  1945. const youtubeHTML = `
  1946. <section class="cc-view" data-view="youtube" hidden>
  1947. <div class="cc-card cc-card-wide">
  1948. <div class="cc-card-head">
  1949. <h3>YouTube pulse</h3>
  1950. ${updatedTag(youtubeSnap)}
  1951. </div>
  1952. <div class="cc-card-body">
  1953. <div style="margin-bottom:12px;">${refreshButton("refreshYouTube", "Refresh YouTube")}</div>
  1954. ${youtubeSnap ? `
  1955. <div class="cc-kpis" style="margin-bottom:12px;">
  1956. <div class="cc-kpi cc-kpi-primary">
  1957. <div class="cc-kpi-head"><span class="cc-kpi-label">Subscribers</span>${youtubeSnap.channel?.subscribers_delta_7d != null ? this.deltaPill(Math.round((youtubeSnap.channel.subscribers_delta_7d / Math.max(1, (youtubeSnap.channel.subscribers || 1) - youtubeSnap.channel.subscribers_delta_7d)) * 100)) : ""}</div>
  1958. <div class="cc-kpi-value">${youtubeSnap.channel?.subscribers?.toLocaleString() ?? "—"}</div>
  1959. <div class="cc-kpi-foot">${youtubeSnap.channel?.subscribers_delta_7d != null ? `+${youtubeSnap.channel.subscribers_delta_7d.toLocaleString()} · 7d` : "channel total"}</div>
  1960. </div>
  1961. <div class="cc-kpi">
  1962. <div class="cc-kpi-head"><span class="cc-kpi-label">Total views</span></div>
  1963. <div class="cc-kpi-value">${youtubeSnap.channel?.total_views?.toLocaleString() ?? "—"}</div>
  1964. <div class="cc-kpi-foot">${youtubeSnap.channel?.views_delta_7d != null ? `+${youtubeSnap.channel.views_delta_7d.toLocaleString()} · 7d` : "lifetime"}</div>
  1965. </div>
  1966. <div class="cc-kpi">
  1967. <div class="cc-kpi-head"><span class="cc-kpi-label">Videos</span></div>
  1968. <div class="cc-kpi-value">${youtubeSnap.channel?.video_count ?? "—"}</div>
  1969. <div class="cc-kpi-foot">published</div>
  1970. </div>
  1971. </div>` : `<div class="cc-empty">No YouTube snapshot yet. Click <strong>Refresh YouTube</strong> above to fetch via YouTube + vidiq MCPs.</div>`}
  1972. </div>
  1973. </div>
  1974. ${youtubeSnap ? (() => {
  1975. const latest = (youtubeSnap.recent_videos || [])[0];
  1976. if (!latest) return "";
  1977. const norm = (s) => String(s||"").toLowerCase().trim();
  1978. const latestId = latest.url && (latest.url.match(/[?&]v=([^&]+)/)?.[1] || latest.url.match(/youtu\.be\/([^?]+)/)?.[1]);
  1979. const perf = (youtubeSnap.video_performance || []).find(p =>
  1980. (p.url && latest.url && p.url === latest.url) ||
  1981. (p.title && norm(p.title) === norm(latest.title))
  1982. );
  1983. const allComments = youtubeSnap.recent_comments || [];
  1984. let latestComments = allComments.filter(c => {
  1985. if (c.video_url && latest.url && c.video_url === latest.url) return true;
  1986. if (c.video_id && latestId && c.video_id === latestId) return true;
  1987. if (c.video_title && norm(c.video_title) === norm(latest.title)) return true;
  1988. // partial title match (truncations are common in scraped data)
  1989. if (c.video_title && latest.title && norm(c.video_title).startsWith(norm(latest.title).slice(0, 25))) return true;
  1990. return false;
  1991. }).slice(0, 4);
  1992. // Fallback: if nothing matched but comments exist, show the top 4 globally
  1993. // (recent_comments is already sorted newest-first by the refresh prompt).
  1994. let commentsAreFallback = false;
  1995. if (latestComments.length === 0 && allComments.length > 0) {
  1996. latestComments = allComments.slice(0, 4);
  1997. commentsAreFallback = true;
  1998. }
  1999. const views = Number(latest.views) || 0;
  2000. const likes = Number(latest.likes) || 0;
  2001. const engagement = views > 0 ? Math.round((likes / views) * 10000) / 100 : null;
  2002. const pct = perf?.vs_channel_avg_pct;
  2003. const perfCls = pct == null ? "" : pct > 20 ? "cc-chip-accent" : pct < -20 ? "cc-chip-alert" : "cc-chip-primary";
  2004. const perfSign = pct > 0 ? "+" : "";
  2005. return `
  2006. <div class="cc-card cc-card-wide">
  2007. <div class="cc-card-head">
  2008. <h3>Latest upload</h3>
  2009. <span class="cc-tag">${this.esc(fmtAge(latest.published_at))}</span>
  2010. </div>
  2011. <div class="cc-card-body">
  2012. <div style="display:flex;gap:16px;flex-wrap:wrap;align-items:flex-start;">
  2013. ${(() => { const thumb = latest.thumbnail || this.youtubeThumbFromUrl(latest.url); return thumb ? `<a href="${this.esc(latest.url||"#")}" target="_blank" style="flex-shrink:0;display:block;width:240px;border-radius:8px;overflow:hidden;border:1px solid #020309;"><img src="${this.esc(thumb)}" alt="" style="width:100%;display:block;" onerror="this.parentElement.style.display='none'"/></a>` : ""; })()}
  2014. <div style="flex:1;min-width:280px;">
  2015. <h2 style="margin:0 0 8px;font-size:18px;line-height:1.25;">${latest.url ? `<a class="cc-link" href="${this.esc(latest.url)}" target="_blank">${this.esc(latest.title||"")}</a>` : this.esc(latest.title||"")}</h2>
  2016. <div style="display:flex;gap:16px;flex-wrap:wrap;margin:10px 0 12px;">
  2017. <div><div style="font-size:20px;font-weight:700;line-height:1;">${views.toLocaleString()}</div><div style="font-size:11px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Views</div></div>
  2018. <div><div style="font-size:20px;font-weight:700;line-height:1;">${likes.toLocaleString()}</div><div style="font-size:11px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Likes</div></div>
  2019. <div><div style="font-size:20px;font-weight:700;line-height:1;">${(Number(latest.comments)||0).toLocaleString()}</div><div style="font-size:11px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Comments</div></div>
  2020. ${engagement != null ? `<div><div style="font-size:20px;font-weight:700;line-height:1;">${engagement}%</div><div style="font-size:11px;opacity:0.6;text-transform:uppercase;letter-spacing:0.5px;">Like rate</div></div>` : ""}
  2021. </div>
  2022. <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;font-size:12px;">
  2023. ${pct != null ? `<span class="cc-chip ${perfCls}">${perfSign}${pct}% vs channel avg</span>` : ""}
  2024. ${perf?.reason_hypothesis ? `<span class="cc-muted">${this.esc(perf.reason_hypothesis.slice(0,200))}</span>` : ""}
  2025. </div>
  2026. ${latestComments.length ? `
  2027. <div style="margin-top:14px;">
  2028. <div style="font-size:11px;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;margin-bottom:6px;">${commentsAreFallback ? "Recent comments (channel-wide)" : "Top comments on this video"}</div>
  2029. <ul class="cc-md-list" style="margin:0;font-size:12px;">${latestComments.map(c => {
  2030. const body = c.text || c.snippet || c.comment || c.body || c.content || "";
  2031. return `<li><strong>${this.esc(c.author||"—")}</strong>${c.video_title && commentsAreFallback ? ` <span class="cc-muted">on ${this.esc((c.video_title||"").slice(0,40))}</span>` : ""}: ${this.esc(body.slice(0,200))}${c.likes ? ` <span class="cc-muted">· ${this.esc(String(c.likes))} likes</span>` : ""}</li>`;
  2032. }).join("")}</ul>
  2033. </div>` : ""}
  2034. </div>
  2035. </div>
  2036. </div>
  2037. </div>`;
  2038. })() : ""}
  2039. ${youtubeSnap ? `
  2040. <div class="cc-card cc-card-wide">
  2041. <div class="cc-card-head"><h3>Trending in your niche</h3><span class="cc-tag">${(youtubeSnap.trending||[]).length}</span></div>
  2042. <div class="cc-card-body">
  2043. ${(youtubeSnap.trending||[]).length
  2044. ? `<div style="display:flex;flex-direction:column;gap:10px;">${(youtubeSnap.trending||[]).slice(0,8).map(t => {
  2045. // Accept multiple velocity shapes from vidiq:
  2046. // velocity ("5x baseline"), velocity_vph (number), breakout_score (number)
  2047. let velocityLabel = "";
  2048. if (t.velocity) velocityLabel = String(t.velocity);
  2049. else if (t.velocity_vph != null) velocityLabel = `${Math.round(Number(t.velocity_vph)).toLocaleString()} v/h`;
  2050. else if (t.breakout_score != null) velocityLabel = `breakout ${Math.round(Number(t.breakout_score))}`;
  2051. const thumb = t.thumbnail_url || this.youtubeThumbFromUrl(t.url);
  2052. return `
  2053. <div style="display:flex;gap:12px;padding:8px;border:1px solid #020309;border-radius:8px;background:#fff;align-items:flex-start;">
  2054. ${thumb ? `<a href="${this.esc(t.url||"#")}" target="_blank" style="flex-shrink:0;display:block;width:144px;aspect-ratio:16/9;border-radius:6px;overflow:hidden;border:1px solid #020309;background:#020309;"><img src="${this.esc(thumb)}" alt="" style="width:100%;height:100%;object-fit:cover;display:block;" onerror="this.style.display='none'"/></a>` : ""}
  2055. <div style="flex:1;min-width:0;">
  2056. <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px;">
  2057. <strong style="font-size:13px;line-height:1.3;flex:1;">${t.url ? `<a class="cc-link" href="${this.esc(t.url)}" target="_blank">${this.esc(t.title||"")}</a>` : this.esc(t.title||"")}</strong>
  2058. ${velocityLabel ? `<span style="flex-shrink:0;padding:2px 8px;font-size:11px;font-weight:600;border:1px solid #020309;border-radius:999px;background:#bbf7d0;white-space:nowrap;">${this.esc(velocityLabel)}</span>` : ""}
  2059. </div>
  2060. <div class="cc-muted" style="font-size:11px;margin-bottom:6px;">${this.esc(t.channel||"—")} · ${t.views?.toLocaleString?.() || t.views || "—"} views</div>
  2061. ${t.summary ? `<p style="margin:0;font-size:12px;line-height:1.45;color:#020309;opacity:0.8;">${this.esc(t.summary.slice(0,160))}</p>` : ""}
  2062. </div>
  2063. </div>`;
  2064. }).join("")}</div>`
  2065. : `<div class="cc-empty">None.</div>`}
  2066. </div>
  2067. </div>
  2068. <div class="cc-card cc-card-wide">
  2069. <div class="cc-card-head"><h3>Recent comments</h3><span class="cc-tag">${(youtubeSnap.recent_comments||[]).length}</span></div>
  2070. <div class="cc-card-body">
  2071. ${(youtubeSnap.recent_comments||[]).length
  2072. ? `<ul class="cc-md-list">${(youtubeSnap.recent_comments||[]).slice(0,10).map(c => { const body = c.text || c.snippet || c.comment || c.body || c.content || ""; return `<li><strong>${this.esc(c.author||"—")}</strong>${c.video_title ? ` on <em>${this.esc(c.video_title)}</em>` : ""}: ${this.esc(body.slice(0,160))}${c.likes ? ` <span class="cc-muted">· ${this.esc(String(c.likes))} likes</span>` : ""}</li>`; }).join("")}</ul>`
  2073. : `<div class="cc-empty">None.</div>`}
  2074. </div>
  2075. </div>
  2076. <div class="cc-card cc-card-wide">
  2077. <div class="cc-card-head"><h3>Top questions in comments</h3><span class="cc-tag">${(youtubeSnap.top_questions_in_comments||[]).length}</span></div>
  2078. <div class="cc-card-body">
  2079. ${(youtubeSnap.top_questions_in_comments||[]).length
  2080. ? `<table class="cc-table"><thead><tr><th>Question</th><th style="width:70px">Asks</th><th style="width:70px">Likes</th><th>From video</th></tr></thead>
  2081. <tbody>${(youtubeSnap.top_questions_in_comments||[]).map(q => `<tr>
  2082. <td><strong>${this.esc(q.question||"")}</strong></td>
  2083. <td>${q.ask_count||1}×</td>
  2084. <td>${q.like_count||0}</td>
  2085. <td>${q.video_url ? `<a class="cc-link" href="${this.esc(q.video_url)}" target="_blank">${this.esc((q.video_title||"").slice(0,60))}</a>` : this.esc((q.video_title||""))}</td>
  2086. </tr>`).join("")}</tbody></table>`
  2087. : `<div class="cc-empty">Not populated yet — click <strong>Refresh YouTube</strong> to extract questions from comments.</div>`}
  2088. </div>
  2089. </div>
  2090. <div class="cc-grid cc-grid-2">
  2091. <div class="cc-card">
  2092. <div class="cc-card-head"><h3>Audience themes</h3><span class="cc-tag">${(youtubeSnap.audience_themes||[]).length}</span></div>
  2093. <div class="cc-card-body">
  2094. ${(youtubeSnap.audience_themes||[]).length
  2095. ? `<div>${(youtubeSnap.audience_themes||[]).map(t => this.listItem({
  2096. title: t.theme || "",
  2097. chipsHTML: [
  2098. this.metaChip(`${t.mention_count||0}×`, "count"),
  2099. this.metaChip(t.sentiment || "neutral", this.toneFor(t.sentiment, "sentiment")),
  2100. ].join(""),
  2101. sub: t.representative_comment ? `"${(t.representative_comment||"").slice(0,160)}"` : null,
  2102. })).join("")}</div>`
  2103. : `<div class="cc-empty">Not populated yet — click <strong>Refresh YouTube</strong>.</div>`}
  2104. </div>
  2105. </div>
  2106. <div class="cc-card">
  2107. <div class="cc-card-head"><h3>Performance vs avg</h3><span class="cc-tag">${(youtubeSnap.video_performance||[]).length}</span></div>
  2108. <div class="cc-card-body">
  2109. ${(youtubeSnap.video_performance||[]).length
  2110. ? `<div>${(youtubeSnap.video_performance||[]).map(p => {
  2111. const pct = p.vs_channel_avg_pct;
  2112. const tone = pct == null ? "neutral" : pct > 20 ? "positive" : pct < -20 ? "alert" : "primary";
  2113. const sign = pct > 0 ? "+" : "";
  2114. return this.listItem({
  2115. title: p.title || "",
  2116. titleHref: p.url || null,
  2117. chipsHTML: this.metaChip(`${sign}${pct||0}%`, tone),
  2118. sub: p.reason_hypothesis || null,
  2119. });
  2120. }).join("")}</div>`
  2121. : `<div class="cc-empty">Not populated yet — click <strong>Refresh YouTube</strong>.</div>`}
  2122. </div>
  2123. </div>
  2124. </div>
  2125. <div class="cc-card cc-card-wide">
  2126. <div class="cc-card-head"><h3>Recent videos</h3><span class="cc-tag">${(youtubeSnap.recent_videos||[]).length}</span></div>
  2127. <div class="cc-card-body">
  2128. ${(youtubeSnap.recent_videos||[]).length
  2129. ? `<table class="cc-table"><thead><tr><th>Video</th><th style="width:90px">Views</th><th style="width:70px">Likes</th><th style="width:70px">💬</th><th style="width:110px">Published</th></tr></thead>
  2130. <tbody>${(youtubeSnap.recent_videos||[]).slice(0,10).map(v => `<tr>
  2131. <td>${v.url ? `<a class="cc-link" href="${this.esc(v.url)}" target="_blank">${this.esc(v.title || "")}</a>` : this.esc(v.title || "")}</td>
  2132. <td>${v.views?.toLocaleString() ?? "—"}</td>
  2133. <td>${v.likes?.toLocaleString() ?? "—"}</td>
  2134. <td>${v.comments ?? "—"}</td>
  2135. <td>${this.esc(fmtAge(v.published_at))}</td>
  2136. </tr>`).join("")}</tbody></table>`
  2137. : `<div class="cc-empty">None.</div>`}
  2138. </div>
  2139. </div>` : ``}
  2140. </section>`;
  2141. // Channel grouping: collect every item across urgent/needs_reply/fyi
  2142. // bucketed by source so the page reads as "what's in each inbox".
  2143. const commsBuckets = (() => {
  2144. if (!commsSnap) return null;
  2145. const byChannel = { linkedin: [], email: [], youtube: [], circle: [], other: [] };
  2146. const urgencyOrder = { urgent: 0, needs_reply: 1, fyi: 2 };
  2147. for (const bucket of ["urgent", "needs_reply", "fyi"]) {
  2148. for (const it of (commsSnap[bucket] || [])) {
  2149. const src = (it.source || "").toLowerCase();
  2150. const channel = byChannel[src] !== undefined ? src : "other";
  2151. byChannel[channel].push({ ...it, _bucket: bucket });
  2152. }
  2153. }
  2154. for (const ch of Object.keys(byChannel)) {
  2155. byChannel[ch].sort((a, b) => urgencyOrder[a._bucket] - urgencyOrder[b._bucket]);
  2156. }
  2157. return byChannel;
  2158. })();
  2159. const channelMeta = [
  2160. { key: "linkedin", label: "LinkedIn", icon: "💼", totalKey: "linkedin_dms", empty: "No LinkedIn DMs. Check that the Unipile MCP is authenticated for LinkedIn." },
  2161. { key: "email", label: "Email", icon: "📧", totalKey: "emails_unread", empty: "Inbox is clear." },
  2162. { key: "youtube", label: "YouTube", icon: "▶️", totalKey: "youtube_comments", empty: "No YouTube comments flagged." },
  2163. { key: "circle", label: "Circle DMs", icon: "💬", totalKey: "circle_dms", empty: "No Circle DMs flagged." },
  2164. ];
  2165. const bucketChip = (b) => {
  2166. const cls = { urgent: "cc-chip-alert", needs_reply: "cc-chip-primary", fyi: "" }[b] || "";
  2167. const lab = { urgent: "urgent", needs_reply: "reply", fyi: "fyi" }[b] || b;
  2168. return `<span class="cc-chip ${cls}">${lab}</span>`;
  2169. };
  2170. const renderChannelCard = (m) => {
  2171. const items = commsBuckets ? commsBuckets[m.key] || [] : [];
  2172. const total = commsSnap?.totals?.[m.totalKey] ?? items.length;
  2173. const urgentCount = items.filter(i => i._bucket === "urgent").length;
  2174. const replyCount = items.filter(i => i._bucket === "needs_reply").length;
  2175. return `
  2176. <div class="cc-card">
  2177. <div class="cc-card-head">
  2178. <h3>${m.icon} ${m.label}</h3>
  2179. <span class="cc-tag ${urgentCount ? "cc-chip-alert" : ""}">${total}</span>
  2180. </div>
  2181. <div class="cc-card-body">
  2182. ${(urgentCount || replyCount) ? `<div style="margin-bottom:10px;font-size:12px;display:flex;gap:6px;flex-wrap:wrap;">${urgentCount ? `<span class="cc-chip cc-chip-alert">${urgentCount} urgent</span>` : ""}${replyCount ? `<span class="cc-chip cc-chip-primary">${replyCount} need reply</span>` : ""}</div>` : ""}
  2183. ${items.length
  2184. ? `<div style="display:flex;flex-direction:column;gap:10px;">${items.slice(0,12).map(it => `
  2185. <div style="padding:10px;border:1px solid var(--background-modifier-border,#020309);border-radius:6px;background:#fff;">
  2186. <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:4px;">
  2187. ${bucketChip(it._bucket)}
  2188. <strong>${this.esc(it.from||"—")}</strong>
  2189. <span class="cc-muted" style="font-size:11px;">${this.esc(fmtAge(it.received_at))}</span>
  2190. </div>
  2191. ${it.subject ? `<div style="margin-bottom:4px;font-size:13px;">${it.url ? `<a class="cc-link" href="${this.esc(it.url)}" target="_blank">${this.esc(it.subject)}</a>` : this.esc(it.subject)}</div>` : ""}
  2192. ${it.snippet ? `<div class="cc-muted" style="font-size:12px;margin-bottom:4px;">${this.esc(it.snippet.slice(0,220))}</div>` : ""}
  2193. <div style="display:flex;justify-content:space-between;align-items:flex-end;gap:8px;margin-top:6px;">
  2194. <span class="cc-muted" style="font-size:11px;flex:1;">${it.suggested_action ? `→ ${this.esc(it.suggested_action.slice(0,140))}` : ""}</span>
  2195. ${this.escalateButton(`[${m.label}] ${it.from||"unknown"} · ${it.subject||"(no subject)"}`, { context: `${it.snippet||""}${it.suggested_action ? "\n\nSuggested: " + it.suggested_action : ""}`, source: `comms · ${m.label.toLowerCase()} · ${name}`, url: it.url, profile: name })}
  2196. </div>
  2197. </div>`).join("")}</div>`
  2198. : `<div class="cc-empty">${m.empty}</div>`}
  2199. </div>
  2200. </div>`;
  2201. };
  2202. const commsHTML = `
  2203. <section class="cc-view" data-view="comms" hidden>
  2204. <div class="cc-card cc-card-wide">
  2205. <div class="cc-card-head">
  2206. <h3>Inbox triage</h3>
  2207. ${updatedTag(commsSnap)}
  2208. </div>
  2209. <div class="cc-card-body">
  2210. <div style="margin-bottom:12px;">${refreshButton("refreshComms", "Refresh comms")}</div>
  2211. ${commsSnap ? `
  2212. <div class="cc-kpis" style="margin-bottom:8px;">
  2213. ${channelMeta.map(m => {
  2214. const items = commsBuckets ? commsBuckets[m.key] || [] : [];
  2215. const total = commsSnap.totals?.[m.totalKey] ?? items.length;
  2216. const urgent = items.filter(i => i._bucket === "urgent").length;
  2217. return `
  2218. <div class="cc-kpi ${urgent ? "cc-kpi-alert" : ""}">
  2219. <div class="cc-kpi-head"><span class="cc-kpi-label">${m.icon} ${m.label}</span></div>
  2220. <div class="cc-kpi-value">${total}</div>
  2221. <div class="cc-kpi-foot">${urgent ? `${urgent} urgent` : `${items.length} flagged`}</div>
  2222. </div>`;
  2223. }).join("")}
  2224. </div>` : `<div class="cc-empty">No comms snapshot yet. Click <strong>Refresh comms</strong> to triage your cross-channel inbox.</div>`}
  2225. </div>
  2226. </div>
  2227. ${commsSnap ? `
  2228. <div class="cc-grid cc-grid-2">
  2229. ${renderChannelCard(channelMeta[0])}
  2230. ${renderChannelCard(channelMeta[1])}
  2231. </div>
  2232. <div class="cc-grid cc-grid-2">
  2233. ${renderChannelCard(channelMeta[2])}
  2234. ${renderChannelCard(channelMeta[3])}
  2235. </div>
  2236. ${commsSnap.notes ? `
  2237. <div class="cc-card cc-card-wide">
  2238. <div class="cc-card-head"><h3>Refresh notes</h3><span class="cc-tag cc-chip-alert">!</span></div>
  2239. <div class="cc-card-body">
  2240. <pre style="margin:0;padding:10px;background:#fff;border:1px solid var(--background-modifier-border,#020309);border-radius:6px;font-size:12px;white-space:pre-wrap;color:#020309;">${this.esc(typeof commsSnap.notes === "string" ? commsSnap.notes : JSON.stringify(commsSnap.notes, null, 2))}</pre>
  2241. </div>
  2242. </div>` : ""}
  2243. ${(commsSnap.recurring_senders||[]).length ? `
  2244. <div class="cc-card cc-card-wide">
  2245. <div class="cc-card-head"><h3>Recurring senders · last 7d</h3><span class="cc-tag">${(commsSnap.recurring_senders||[]).length}</span></div>
  2246. <div class="cc-card-body">
  2247. <table class="cc-table"><thead><tr><th style="width:160px">From</th><th style="width:90px">Source</th><th style="width:80px">Messages</th><th>Topics</th></tr></thead>
  2248. <tbody>${(commsSnap.recurring_senders||[]).map(r => `<tr>
  2249. <td><strong>${this.esc(r.from||"—")}</strong></td>
  2250. <td><span class="cc-chip">${this.esc(r.source||"—")}</span></td>
  2251. <td>${r.message_count||0}</td>
  2252. <td><span class="cc-muted" style="font-size:12px;">${(r.topics||[]).map(t => this.esc(t)).join(" · ")}</span></td>
  2253. </tr>`).join("")}</tbody></table>
  2254. </div>
  2255. </div>` : ""}
  2256. ` : ""}
  2257. </section>`;
  2258. // ---------- Meetings view (Fireflies) ----------
  2259. const meetingsHTML = `
  2260. <section class="cc-view" data-view="meetings" hidden>
  2261. <div class="cc-card cc-card-wide">
  2262. <div class="cc-card-head">
  2263. <h3>Meeting intelligence</h3>
  2264. ${updatedTag(meetingsSnap)}
  2265. </div>
  2266. <div class="cc-card-body">
  2267. <div style="margin-bottom:12px;">${refreshButton("refreshMeetings", "Refresh meetings")}</div>
  2268. ${meetingsSnap ? `
  2269. <div class="cc-kpis" style="margin-bottom:12px;">
  2270. <div class="cc-kpi cc-kpi-primary">
  2271. <div class="cc-kpi-head"><span class="cc-kpi-label">Meetings · 7d</span></div>
  2272. <div class="cc-kpi-value">${meetingsSnap.rollup?.meetings_count_7d ?? "—"}</div>
  2273. <div class="cc-kpi-foot">${meetingsSnap.rollup?.total_hours_7d != null ? meetingsSnap.rollup.total_hours_7d + "h total" : "this week"}</div>
  2274. </div>
  2275. <div class="cc-kpi">
  2276. <div class="cc-kpi-head"><span class="cc-kpi-label">Talk-time ratio</span></div>
  2277. <div class="cc-kpi-value">${meetingsSnap.rollup?.avg_talk_time_ratio != null ? meetingsSnap.rollup.avg_talk_time_ratio + "%" : "—"}</div>
  2278. <div class="cc-kpi-foot">${this.esc(name)}'s share (target ~40-50)</div>
  2279. </div>
  2280. <div class="cc-kpi">
  2281. <div class="cc-kpi-head"><span class="cc-kpi-label">Questions asked</span></div>
  2282. <div class="cc-kpi-value">${meetingsSnap.rollup?.questions_asked_7d ?? "—"}</div>
  2283. <div class="cc-kpi-foot">consultative signal</div>
  2284. </div>
  2285. <div class="cc-kpi cc-kpi-alert">
  2286. <div class="cc-kpi-head"><span class="cc-kpi-label">Open action items</span></div>
  2287. <div class="cc-kpi-value">${(meetingsSnap.action_items||[]).filter(a => a.status !== 'done').length}</div>
  2288. <div class="cc-kpi-foot">${(meetingsSnap.action_items||[]).filter(a => a.status === 'overdue').length} overdue</div>
  2289. </div>
  2290. </div>` : `<div class="cc-empty">No meetings snapshot. Click <strong>Refresh meetings</strong> above to pull from Fireflies.</div>`}
  2291. </div>
  2292. </div>
  2293. ${meetingsSnap ? `
  2294. <div class="cc-card cc-card-wide">
  2295. <div class="cc-card-head"><h3>Client signals</h3><span class="cc-tag">${(meetingsSnap.client_signals||[]).length}</span></div>
  2296. <div class="cc-card-body">
  2297. ${(meetingsSnap.client_signals||[]).length
  2298. ? `<table class="cc-table"><thead><tr><th style="width:160px">Company</th><th style="width:140px">Person</th><th style="width:80px">Stage</th><th style="width:100px">Last call</th><th>Next action</th></tr></thead>
  2299. <tbody>${(meetingsSnap.client_signals||[]).map(c => {
  2300. const stageClass = { hot: "cc-chip-alert", warm: "cc-chip-primary", cool: "", cold: "" }[c.stage] || "";
  2301. return `<tr>
  2302. <td><strong>${this.esc(c.company||"—")}</strong></td>
  2303. <td>${this.esc(c.person||"—")}</td>
  2304. <td><span class="cc-chip ${stageClass}">${this.esc(c.stage||"—")}</span></td>
  2305. <td>${this.esc(fmtAge(c.last_meeting_iso))}</td>
  2306. <td>${this.esc((c.next_action||"").slice(0,160))}${c.sentiment_trend ? `<br><span class="cc-muted" style="font-size:12px;">${this.esc(c.sentiment_trend)}</span>` : ""}</td>
  2307. </tr>`;
  2308. }).join("")}</tbody></table>`
  2309. : `<div class="cc-empty">No client signals yet.</div>`}
  2310. </div>
  2311. </div>
  2312. <div class="cc-card cc-card-wide">
  2313. <div class="cc-card-head"><h3>Recent meetings</h3><span class="cc-tag">${(meetingsSnap.recent||[]).length}</span></div>
  2314. <div class="cc-card-body">
  2315. ${(meetingsSnap.recent||[]).length
  2316. ? `<table class="cc-table"><thead><tr><th>Meeting</th><th style="width:90px">Type</th><th style="width:90px">Duration</th><th style="width:200px">Attendees</th><th style="width:100px">When</th></tr></thead>
  2317. <tbody>${(meetingsSnap.recent||[]).map(m => `<tr>
  2318. <td>${m.url ? `<a class="cc-link" href="${this.esc(m.url)}" target="_blank">${this.esc(m.title||"")}</a>` : this.esc(m.title||"")}</td>
  2319. <td><span class="cc-chip">${this.esc(m.type||"—")}</span></td>
  2320. <td>${m.duration_minutes||"—"}m</td>
  2321. <td><span class="cc-muted" style="font-size:12px;">${this.esc((m.attendees||[]).slice(0,3).join(", "))}${(m.attendees||[]).length > 3 ? ` +${(m.attendees||[]).length-3}` : ""}</span></td>
  2322. <td>${this.esc(fmtAge(m.date_iso))}</td>
  2323. </tr>`).join("")}</tbody></table>`
  2324. : `<div class="cc-empty">No recent meetings.</div>`}
  2325. </div>
  2326. </div>
  2327. <div class="cc-grid cc-grid-2">
  2328. <div class="cc-card">
  2329. <div class="cc-card-head"><h3>Action items</h3><span class="cc-tag">${(meetingsSnap.action_items||[]).length}</span></div>
  2330. <div class="cc-card-body">
  2331. ${(meetingsSnap.action_items||[]).length
  2332. ? `<ul class="cc-md-list">${(meetingsSnap.action_items||[]).map(a => `<li><div style="display:flex;align-items:flex-start;gap:10px;"><div style="flex:1;min-width:0;">${a.status === 'overdue' ? '<span class="cc-chip cc-chip-alert">overdue</span> ' : ''}${a.in_task_list ? '<span class="cc-chip cc-chip-accent">in tasks</span> ' : '<span class="cc-chip cc-chip-alert">not in tasks</span> '}<strong>${this.esc(a.text||"")}</strong><br><span class="cc-muted" style="font-size:12px;">${this.esc(a.owner||"—")} · ${a.source_meeting_url ? `<a class="cc-link" href="${this.esc(a.source_meeting_url)}" target="_blank">${this.esc(a.source_meeting_title||"meeting")}</a>` : this.esc(a.source_meeting_title||"")}</span></div><div style="flex-shrink:0;">${this.escalateButton(a.text||"", { context: `Owner: ${a.owner||"—"}${a.source_meeting_title ? " · From: " + a.source_meeting_title : ""}${a.status ? " · Status: " + a.status : ""}`, source: `meetings · ${name}`, url: a.source_meeting_url, profile: name })}</div></div></li>`).join("")}</ul>`
  2333. : `<div class="cc-empty">None.</div>`}
  2334. </div>
  2335. </div>
  2336. <div class="cc-card">
  2337. <div class="cc-card-head"><h3>Decisions</h3><span class="cc-tag">${(meetingsSnap.decisions||[]).length}</span></div>
  2338. <div class="cc-card-body">
  2339. ${(meetingsSnap.decisions||[]).length
  2340. ? `<ul class="cc-md-list">${(meetingsSnap.decisions||[]).map(d => `<li>${d.documented ? '<span class="cc-chip cc-chip-accent">documented</span> ' : '<span class="cc-chip cc-chip-alert">not documented</span> '}<strong>${this.esc(d.decision||"")}</strong><br><span class="cc-muted" style="font-size:12px;">${this.esc((d.context||"").slice(0,120))}${d.source_meeting_url ? ` · <a class="cc-link" href="${this.esc(d.source_meeting_url)}" target="_blank">${this.esc(d.source_meeting_title||"meeting")}</a>` : ""}</span></li>`).join("")}</ul>`
  2341. : `<div class="cc-empty">None.</div>`}
  2342. </div>
  2343. </div>
  2344. </div>
  2345. <div class="cc-grid cc-grid-2">
  2346. <div class="cc-card">
  2347. <div class="cc-card-head"><h3>Themes in calls</h3><span class="cc-tag">${(meetingsSnap.themes_in_calls||[]).length}</span></div>
  2348. <div class="cc-card-body">
  2349. ${(meetingsSnap.themes_in_calls||[]).length
  2350. ? `<ul class="cc-md-list">${(meetingsSnap.themes_in_calls||[]).map(t => `<li><strong>${this.esc(t.theme||"")}</strong> <span class="cc-chip">${t.mention_count||0}× across calls</span>${t.representative_quote ? `<br><span class="cc-muted" style="font-size:12px;">"${this.esc((t.representative_quote||"").slice(0,160))}"</span>` : ""}</li>`).join("")}</ul>`
  2351. : `<div class="cc-empty">None.</div>`}
  2352. </div>
  2353. </div>
  2354. <div class="cc-card">
  2355. <div class="cc-card-head"><h3>Prospect language</h3><span class="cc-tag">${(meetingsSnap.prospect_language||[]).length}</span></div>
  2356. <div class="cc-card-body">
  2357. ${(meetingsSnap.prospect_language||[]).length
  2358. ? `<ul class="cc-md-list">${(meetingsSnap.prospect_language||[]).map(p => `<li>"${this.esc((p.phrase||"").slice(0,140))}"${p.source_meeting_url ? ` · <a class="cc-link" href="${this.esc(p.source_meeting_url)}" target="_blank">source</a>` : ""}${p.context ? `<br><span class="cc-muted" style="font-size:12px;">${this.esc((p.context||"").slice(0,140))}</span>` : ""}</li>`).join("")}</ul>`
  2359. : `<div class="cc-empty">None.</div>`}
  2360. </div>
  2361. </div>
  2362. </div>` : ``}
  2363. </section>`;
  2364. // ---------- Intelligence view (cross-stream synthesis) ----------
  2365. const intelligenceHTML = `
  2366. <section class="cc-view" data-view="intelligence" hidden>
  2367. <div class="cc-card cc-card-wide">
  2368. <div class="cc-card-head">
  2369. <h3>Cross-stream intelligence</h3>
  2370. ${updatedTag(intelSnap)}
  2371. </div>
  2372. <div class="cc-card-body">
  2373. <div style="margin-bottom:12px;display:flex;gap:8px;flex-wrap:wrap;">
  2374. ${refreshButton("refreshIntelligence", "Refresh intelligence")}
  2375. <span class="cc-muted" style="font-size:12px;align-self:center;">Joins community + meetings + youtube + comms snapshots. Refresh each source first for best results.</span>
  2376. </div>
  2377. ${!intelSnap ? `<div class="cc-empty">No intelligence snapshot yet. Refresh the source pages first (Community, YouTube, Comms, Meetings), then click <strong>Refresh intelligence</strong>.</div>` : ""}
  2378. </div>
  2379. </div>
  2380. ${intelSnap ? `
  2381. ${(intelSnap.opportunity_briefs||[]).length ? `
  2382. <div class="cc-card cc-card-wide">
  2383. <div class="cc-card-head"><h3>Opportunity briefs</h3><span class="cc-tag cc-chip-primary">${(intelSnap.opportunity_briefs||[]).length}</span></div>
  2384. <div class="cc-card-body">
  2385. ${(intelSnap.opportunity_briefs||[]).map(b => `
  2386. <div style="border-left:3px solid #020309;padding:8px 12px;margin-bottom:10px;background:#f6f1e1;">
  2387. <strong>${this.esc(b.title||"")}</strong>
  2388. <p style="margin:6px 0;">${this.esc(b.summary||"")}</p>
  2389. <p style="margin:0;font-size:12px;"><strong>Next:</strong> ${this.esc(b.recommended_next_action||"")}</p>
  2390. </div>
  2391. `).join("")}
  2392. </div>
  2393. </div>` : ""}
  2394. <div class="cc-card cc-card-wide">
  2395. <div class="cc-card-head"><h3>Cross-validated themes</h3><span class="cc-tag">${(intelSnap.cross_validated_themes||[]).length}</span></div>
  2396. <div class="cc-card-body">
  2397. ${(intelSnap.cross_validated_themes||[]).length
  2398. ? `<table class="cc-table"><thead><tr><th style="width:48px">P</th><th>Theme</th><th style="width:200px">Sources</th><th style="width:80px">Mentions</th><th>Why</th></tr></thead>
  2399. <tbody>${(intelSnap.cross_validated_themes||[]).map(t => `<tr>
  2400. <td>${this.priorityChip(t.priority)}</td>
  2401. <td><strong>${this.esc(t.theme||"")}</strong></td>
  2402. <td><div style="display:flex;gap:4px;flex-wrap:wrap;">${(t.sources||[]).map(s => this.sourceChip(s)).join("")}</div></td>
  2403. <td><strong>${t.combined_mention_count||0}×</strong></td>
  2404. <td><span class="cc-muted" style="font-size:12px;line-height:1.45;">${this.esc((t.why||"").slice(0,200))}</span></td>
  2405. </tr>`).join("")}</tbody></table>`
  2406. : `<div class="cc-empty">No themes appear in 2+ streams yet.</div>`}
  2407. </div>
  2408. </div>
  2409. <div class="cc-card cc-card-wide">
  2410. <div class="cc-card-head"><h3>Unified action items</h3><span class="cc-tag">${(intelSnap.unified_action_items||[]).length}</span></div>
  2411. <div class="cc-card-body">
  2412. ${(intelSnap.unified_action_items||[]).length
  2413. ? `<table class="cc-table"><thead><tr><th style="width:48px">P</th><th style="width:140px">Source</th><th>Action</th><th style="width:90px">Due</th><th style="width:100px"></th></tr></thead>
  2414. <tbody>${(intelSnap.unified_action_items||[]).map(a => `<tr>
  2415. <td>${this.priorityChip(a.urgency)}</td>
  2416. <td>${this.sourceChip(a.source||"—")}</td>
  2417. <td>${a.url ? `<a class="cc-link" href="${this.esc(a.url)}" target="_blank"><strong>${this.esc((a.text||"").slice(0,200))}</strong></a>` : `<strong>${this.esc((a.text||"").slice(0,200))}</strong>`}</td>
  2418. <td>${this.esc(fmtAge(a.due_iso))}</td>
  2419. <td>${this.escalateButton(a.text||"", { context: `Priority: ${a.urgency||"—"} · Origin: ${a.source||"—"}${a.due_iso ? " · Due: " + a.due_iso : ""}`, source: `intelligence · ${name}`, url: a.url, profile: name })}</td>
  2420. </tr>`).join("")}</tbody></table>`
  2421. : `<div class="cc-empty">Nothing to act on.</div>`}
  2422. </div>
  2423. </div>
  2424. <div class="cc-grid cc-grid-2">
  2425. <div class="cc-card">
  2426. <div class="cc-card-head"><h3>Decisions to document</h3><span class="cc-tag cc-chip-alert">${(intelSnap.decisions_to_document||[]).length}</span></div>
  2427. <div class="cc-card-body">
  2428. ${(intelSnap.decisions_to_document||[]).length
  2429. ? `<ul class="cc-md-list">${(intelSnap.decisions_to_document||[]).map(d => `<li><div style="display:flex;align-items:flex-start;gap:10px;"><div style="flex:1;min-width:0;"><strong>${this.esc(d.decision||"")}</strong><br><span class="cc-muted" style="font-size:12px;">${d.source_meeting_url ? `<a class="cc-link" href="${this.esc(d.source_meeting_url)}" target="_blank">source</a> · ` : ""}suggested: <code>${this.esc(d.suggested_filename||"")}</code></span></div><div style="flex-shrink:0;">${this.escalateButton(`Decision needs documentation: ${d.decision||""}`, { context: `Suggested filename: ${d.suggested_filename||""}`, source: `intelligence · ${name}`, url: d.source_meeting_url, profile: name })}</div></div></li>`).join("")}</ul>`
  2430. : `<div class="cc-empty">All decisions documented. 🎉</div>`}
  2431. </div>
  2432. </div>
  2433. <div class="cc-card">
  2434. <div class="cc-card-head"><h3>Churn signals</h3><span class="cc-tag cc-chip-alert">${(intelSnap.churn_signals||[]).length}</span></div>
  2435. <div class="cc-card-body">
  2436. ${(intelSnap.churn_signals||[]).length
  2437. ? `<ul class="cc-md-list">${(intelSnap.churn_signals||[]).map(c => `<li><div style="display:flex;align-items:flex-start;gap:10px;"><div style="flex:1;min-width:0;"><strong>${this.esc(c.name||"")}</strong> <span class="cc-chip cc-chip-alert">${c.days_stuck||"?"}d</span><br><span class="cc-muted" style="font-size:12px;">${this.esc((c.recommended_outreach||"").slice(0,160))}${c.community_url ? ` · <a class="cc-link" href="${this.esc(c.community_url)}" target="_blank">community</a>` : ""}${c.last_meeting_url ? ` · <a class="cc-link" href="${this.esc(c.last_meeting_url)}" target="_blank">last meeting</a>` : ""}</span></div><div style="flex-shrink:0;">${this.escalateButton(`Churn risk: ${c.name||""}`, { context: c.recommended_outreach||"", source: `intelligence · ${name}`, url: c.community_url || c.last_meeting_url, profile: name })}</div></div></li>`).join("")}</ul>`
  2438. : `<div class="cc-empty">None.</div>`}
  2439. </div>
  2440. </div>
  2441. </div>
  2442. <div class="cc-card cc-card-wide">
  2443. <div class="cc-card-head"><h3>Content opportunities</h3><span class="cc-tag">${(intelSnap.content_opportunities||[]).length}</span></div>
  2444. <div class="cc-card-body">
  2445. ${(intelSnap.content_opportunities||[]).length
  2446. ? `<table class="cc-table"><thead><tr><th style="width:48px">P</th><th>Question</th><th style="width:180px">Format</th><th style="width:200px">Evidence</th><th style="width:100px"></th></tr></thead>
  2447. <tbody>${(intelSnap.content_opportunities||[]).map(o => {
  2448. const fmt = String(o.suggested_format || "—");
  2449. let short, detail;
  2450. if (o.format_detail) {
  2451. // New schema: format_detail explicitly provided
  2452. short = fmt.length > 18 ? fmt.slice(0, 18) : fmt;
  2453. detail = o.format_detail;
  2454. } else {
  2455. // Back-compat: parse short label from prose
  2456. const m = fmt.match(/^([^:]{1,18})(?::\s*(.+))?$/);
  2457. short = m ? m[1].trim() : fmt.slice(0, 18);
  2458. detail = m && m[2] ? m[2].trim() : (fmt.length > 18 ? fmt : "");
  2459. }
  2460. return `<tr>
  2461. <td>${this.priorityChip(o.priority)}</td>
  2462. <td><strong>${this.esc(o.question||"")}</strong></td>
  2463. <td>
  2464. <span style="display:inline-block;padding:2px 8px;font-size:11px;font-weight:600;border:1px solid #020309;border-radius:6px;background:#fef3c7;color:#020309;line-height:1.4;">${this.esc(short)}</span>
  2465. ${detail ? `<div class="cc-muted" style="margin-top:4px;font-size:11px;line-height:1.4;">${this.esc(detail)}</div>` : ""}
  2466. </td>
  2467. <td><div style="display:flex;gap:4px;flex-wrap:wrap;align-items:center;">${(o.evidence||[]).map(e => `${this.sourceChip(e.source)}${e.ask_count ? `<span class="cc-muted" style="font-size:11px;">×${e.ask_count}</span>` : ""}${e.url ? ` <a class="cc-link" href="${this.esc(e.url)}" target="_blank" style="font-size:11px;">↗</a>` : ""}`).join('<span style="opacity:0.3;font-size:11px;">·</span>')}</div></td>
  2468. <td>${this.escalateButton(`Content opportunity: ${o.question||""}`, { context: `Priority: ${o.priority||"—"} · Format: ${o.suggested_format||"—"} · Evidence: ${(o.evidence||[]).map(e => `${e.source}${e.ask_count?" ×"+e.ask_count:""}`).join(", ")}`, source: `intelligence · ${name}`, profile: name })}</td>
  2469. </tr>`;
  2470. }).join("")}</tbody></table>`
  2471. : `<div class="cc-empty">None yet.</div>`}
  2472. </div>
  2473. </div>` : ""}
  2474. </section>`;
  2475. // ---------- Research view ----------
  2476. const researchHTML = `
  2477. <section class="cc-view" data-view="research" hidden>
  2478. <div class="cc-card cc-card-wide">
  2479. <div class="cc-card-head">
  2480. <h3>Research · last 48h</h3>
  2481. ${updatedTag(researchSnap)}
  2482. </div>
  2483. <div class="cc-card-body">
  2484. <div style="margin-bottom:12px;">${refreshButton("refreshResearch", "Refresh research")}</div>
  2485. ${researchSnap?.synthesis?.headline_signal ? `
  2486. <div style="border-left:3px solid #020309;padding:8px 12px;background:#f6f1e1;margin-bottom:8px;">
  2487. <span class="cc-chip cc-chip-primary">headline</span>
  2488. <p style="margin:6px 0 0;font-size:14px;font-weight:600;">${this.esc(researchSnap.synthesis.headline_signal)}</p>
  2489. </div>` : ""}
  2490. ${!researchSnap ? `<div class="cc-empty">No research snapshot. Click <strong>Refresh research</strong> to scan Anthropic, YouTube, Twitter, and competitors for the last 48 hours.</div>` : ""}
  2491. </div>
  2492. </div>
  2493. ${researchSnap ? `
  2494. <div class="cc-card cc-card-wide">
  2495. <div class="cc-card-head"><h3>Anthropic updates</h3><span class="cc-tag">${(researchSnap.anthropic_updates||[]).length}</span></div>
  2496. <div class="cc-card-body">
  2497. ${(researchSnap.anthropic_updates||[]).length
  2498. ? `<div style="display:flex;flex-direction:column;gap:12px;">
  2499. ${(researchSnap.anthropic_updates||[]).map(u => `
  2500. <div style="display:flex;gap:14px;padding:12px;border:1px solid #020309;border-radius:8px;background:#fff;align-items:flex-start;">
  2501. ${u.image_url ? `<a href="${this.esc(u.url||"#")}" target="_blank" style="flex-shrink:0;display:block;width:180px;border-radius:6px;overflow:hidden;border:1px solid #020309;"><img src="${this.esc(u.image_url)}" alt="" style="width:100%;display:block;" onerror="this.parentElement.style.display='none'"/></a>` : ""}
  2502. <div style="flex:1;min-width:240px;">
  2503. <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:6px;">
  2504. <span class="cc-chip">${this.esc(u.type||"—")}</span>
  2505. <span class="cc-muted" style="font-size:11px;">${this.esc(fmtAge(u.published_at))}</span>
  2506. </div>
  2507. <strong style="font-size:14px;display:block;margin-bottom:6px;">${u.url ? `<a class="cc-link" href="${this.esc(u.url)}" target="_blank">${this.esc(u.title||"")}</a>` : this.esc(u.title||"")}</strong>
  2508. <p style="margin:0 0 6px;font-size:13px;line-height:1.45;">${this.esc((u.summary||"").slice(0,260))}</p>
  2509. ${u.what_it_means_for_us ? `<p style="margin:0;font-size:12px;color:#020309;opacity:0.7;"><strong>For us:</strong> ${this.esc(u.what_it_means_for_us.slice(0,200))}</p>` : ""}
  2510. </div>
  2511. </div>`).join("")}
  2512. </div>`
  2513. : `<div class="cc-empty">No Anthropic updates in the last 48h.</div>`}
  2514. </div>
  2515. </div>
  2516. <div class="cc-card cc-card-wide">
  2517. <div class="cc-card-head"><h3>YouTube trends in your niche</h3><span class="cc-tag">${(researchSnap.youtube_trends||[]).length}</span></div>
  2518. <div class="cc-card-body">
  2519. ${(researchSnap.youtube_trends||[]).length
  2520. ? `<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;">
  2521. ${(researchSnap.youtube_trends||[]).map(t => `
  2522. <div style="border:1px solid #020309;border-radius:8px;background:#fff;overflow:hidden;display:flex;flex-direction:column;">
  2523. ${(() => { const thumb = t.thumbnail_url || this.youtubeThumbFromUrl(t.url); return thumb ? `<a href="${this.esc(t.url||"#")}" target="_blank" style="display:block;aspect-ratio:16/9;background:#020309;"><img src="${this.esc(thumb)}" alt="" style="width:100%;height:100%;object-fit:cover;display:block;" onerror="this.parentElement.style.display='none'"/></a>` : ""; })()}
  2524. <div style="padding:10px;">
  2525. <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px;">
  2526. ${(() => {
  2527. const v = t.velocity;
  2528. if (v == null || v === "") return "";
  2529. const num = Number(v);
  2530. const label = !isNaN(num) && typeof v !== "string"
  2531. ? `${num.toLocaleString(undefined,{maximumFractionDigits:1})} views/hr`
  2532. : String(v);
  2533. return `<span class="cc-chip cc-chip-accent" title="Views per hour since publish (vidiq velocity)">${this.esc(label)}</span>`;
  2534. })()}
  2535. ${t.topic_cluster ? `<span class="cc-chip" style="font-size:10px;">${this.esc(t.topic_cluster)}</span>` : ""}
  2536. </div>
  2537. <strong style="font-size:13px;line-height:1.3;display:block;margin-bottom:4px;">${t.url ? `<a class="cc-link" href="${this.esc(t.url)}" target="_blank">${this.esc((t.title||"").slice(0,90))}</a>` : this.esc((t.title||"").slice(0,90))}</strong>
  2538. <div class="cc-muted" style="font-size:11px;margin-bottom:6px;">${this.esc(t.channel||"—")} · ${t.views?.toLocaleString?.() || t.views || "—"} views${t.published_at ? ` · ${this.esc(fmtAge(t.published_at))}` : ""}</div>
  2539. ${t.key_insight ? `<p style="margin:0;font-size:12px;line-height:1.45;">${this.esc((t.key_insight||"").slice(0,180))}</p>` : ""}
  2540. ${t.transcript_highlight ? `<p style="margin:6px 0 0;font-size:11px;color:#020309;opacity:0.65;font-style:italic;">"${this.esc((t.transcript_highlight||"").slice(0,140))}"</p>` : ""}
  2541. </div>
  2542. </div>`).join("")}
  2543. </div>`
  2544. : `<div class="cc-empty">No YouTube trends captured.</div>`}
  2545. </div>
  2546. </div>
  2547. <div class="cc-card cc-card-wide">
  2548. <div class="cc-card-head"><h3>Twitter signals</h3><span class="cc-tag">${(researchSnap.twitter_signals||[]).length}</span></div>
  2549. <div class="cc-card-body">
  2550. ${(researchSnap.twitter_signals||[]).length
  2551. ? (researchSnap.twitter_signals||[]).map(s => `
  2552. <div style="padding:10px;margin-bottom:10px;border:1px solid #020309;border-radius:6px;background:#fff;">
  2553. <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:6px;">
  2554. <strong>${this.esc(s.topic||"")}</strong>
  2555. <span class="cc-chip ${s.trend_direction==='hot'||s.trend_direction==='rising'?'cc-chip-alert':s.trend_direction==='fading'?'':'cc-chip-primary'}">${this.esc(s.trend_direction||"—")}</span>
  2556. <span class="cc-chip">${s.tweets_count||0} tweets</span>
  2557. </div>
  2558. <div class="cc-muted" style="font-size:12px;margin-bottom:6px;">${this.esc((s.why_it_matters||"").slice(0,200))}</div>
  2559. ${(s.representative_tweets||[]).length ? `<div style="display:flex;flex-direction:column;gap:8px;">${(s.representative_tweets||[]).slice(0,3).map(t => `
  2560. <div style="display:flex;gap:10px;padding:8px;background:#f6f1e1;border-radius:6px;">
  2561. ${t.author_avatar_url ? `<img src="${this.esc(t.author_avatar_url)}" alt="" style="width:32px;height:32px;border-radius:50%;flex-shrink:0;object-fit:cover;" onerror="this.style.display='none'"/>` : ""}
  2562. <div style="flex:1;min-width:0;">
  2563. <div style="font-size:12px;margin-bottom:4px;"><strong>${this.esc(t.author||"—")}</strong>${t.posted_at ? ` <span class="cc-muted">· ${this.esc(fmtAge(t.posted_at))}</span>` : ""}${t.engagement != null ? ` <span class="cc-muted">· ${this.esc(String(t.engagement))} engagements</span>` : ""}${t.url ? ` · <a class="cc-link" href="${this.esc(t.url)}" target="_blank">view</a>` : ""}</div>
  2564. <div style="font-size:12px;line-height:1.45;">${this.esc((t.text||"").slice(0,240))}</div>
  2565. ${(t.media_urls||[]).length ? `<div style="display:flex;gap:6px;margin-top:6px;flex-wrap:wrap;">${(t.media_urls||[]).slice(0,3).map(m => `<a href="${this.esc(m)}" target="_blank" style="display:block;width:120px;border-radius:4px;overflow:hidden;border:1px solid #020309;"><img src="${this.esc(m)}" alt="" style="width:100%;display:block;" onerror="this.parentElement.style.display='none'"/></a>`).join("")}</div>` : ""}
  2566. </div>
  2567. </div>`).join("")}</div>` : ""}
  2568. </div>`).join("")
  2569. : `<div class="cc-empty">No Twitter signals captured.</div>`}
  2570. </div>
  2571. </div>
  2572. <div class="cc-card cc-card-wide">
  2573. <div class="cc-card-head"><h3>Competitor activity</h3><span class="cc-tag">${(researchSnap.competitor_activity||[]).length}</span></div>
  2574. <div class="cc-card-body">
  2575. ${(researchSnap.competitor_activity||[]).length
  2576. ? `<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px;">
  2577. ${(researchSnap.competitor_activity||[]).map(c => {
  2578. const pct = c.performance_vs_their_avg_pct;
  2579. const cls = pct > 20 ? "cc-chip-accent" : pct < -20 ? "cc-chip-alert" : "";
  2580. const sign = pct > 0 ? "+" : "";
  2581. return `
  2582. <div style="border:1px solid #020309;border-radius:8px;background:#fff;overflow:hidden;display:flex;flex-direction:column;">
  2583. ${(() => { const thumb = c.thumbnail_url || this.youtubeThumbFromUrl(c.video_url); return thumb ? `<a href="${this.esc(c.video_url||"#")}" target="_blank" style="display:block;aspect-ratio:16/9;background:#020309;"><img src="${this.esc(thumb)}" alt="" style="width:100%;height:100%;object-fit:cover;display:block;" onerror="this.parentElement.style.display='none'"/></a>` : ""; })()}
  2584. <div style="padding:10px;">
  2585. <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px;align-items:center;">
  2586. ${pct != null ? `<span class="cc-chip ${cls}">${sign}${pct}%</span>` : ""}
  2587. <span class="cc-muted" style="font-size:11px;">${this.esc(fmtAge(c.published_at))}</span>
  2588. ${c.topic ? `<span class="cc-chip" style="font-size:10px;">${this.esc(c.topic)}</span>` : ""}
  2589. </div>
  2590. <strong style="font-size:13px;line-height:1.3;display:block;margin-bottom:4px;">${c.video_url ? `<a class="cc-link" href="${this.esc(c.video_url)}" target="_blank">${this.esc((c.video_title||"").slice(0,90))}</a>` : this.esc((c.video_title||"").slice(0,90))}</strong>
  2591. <div class="cc-muted" style="font-size:11px;margin-bottom:6px;">${c.channel_url ? `<a class="cc-link" href="${this.esc(c.channel_url)}" target="_blank">${this.esc(c.channel||"—")}</a>` : this.esc(c.channel||"—")} · ${c.views?.toLocaleString?.() || c.views || "—"} views</div>
  2592. ${c.angle_summary ? `<p style="margin:0;font-size:12px;line-height:1.45;">${this.esc((c.angle_summary||"").slice(0,180))}</p>` : ""}
  2593. </div>
  2594. </div>`;
  2595. }).join("")}
  2596. </div>`
  2597. : `<div class="cc-empty">No competitor videos in the last 48h.</div>`}
  2598. </div>
  2599. </div>
  2600. ${(researchSnap.synthesis?.content_opportunities?.length || researchSnap.synthesis?.trends_to_watch?.length) ? `
  2601. <div class="cc-grid cc-grid-2">
  2602. ${researchSnap.synthesis?.content_opportunities?.length ? `
  2603. <div class="cc-card">
  2604. <div class="cc-card-head"><h3>Content opportunities</h3><span class="cc-tag">${researchSnap.synthesis.content_opportunities.length}</span></div>
  2605. <div class="cc-card-body">
  2606. <ul class="cc-md-list">${researchSnap.synthesis.content_opportunities.map(o => `<li>${this.esc(o)}</li>`).join("")}</ul>
  2607. </div>
  2608. </div>` : ""}
  2609. ${researchSnap.synthesis?.trends_to_watch?.length ? `
  2610. <div class="cc-card">
  2611. <div class="cc-card-head"><h3>Trends to watch</h3><span class="cc-tag">${researchSnap.synthesis.trends_to_watch.length}</span></div>
  2612. <div class="cc-card-body">
  2613. <ul class="cc-md-list">${researchSnap.synthesis.trends_to_watch.map(t => `<li>${this.esc(t)}</li>`).join("")}</ul>
  2614. </div>
  2615. </div>` : ""}
  2616. </div>` : ""}
  2617. ` : ""}
  2618. </section>`;
  2619. // ---------- Per-profile runs view ----------
  2620. const profileRunsHTML = `
  2621. <section class="cc-view" data-view="runs" hidden>
  2622. <div class="cc-card cc-card-wide">
  2623. <div class="cc-card-head"><h3>${this.esc(name)}'s background runs</h3><span class="cc-tag">claude -p · history</span></div>
  2624. <div class="cc-card-body">
  2625. <p style="margin:0 0 8px;opacity:0.7;font-size:13px;">Every refresh launched from ${this.esc(name)}'s pages lands here. Persists to <code>${this.esc(this.profileRunsPath(name))}</code>.</p>
  2626. <div id="cc-claude-runs-profile" class="cc-claude-runs" data-runs-scope="${this.esc(name)}"></div>
  2627. </div>
  2628. </div>
  2629. </section>`;
  2630. // Hydrate persisted runs once per session so the runs view fills.
  2631. this.hydrateRunsOnce().then(() => {
  2632. const r = document.querySelector(".cc-root:not(.cc-loading)");
  2633. if (r) this.restoreRunHistory(r);
  2634. this.refreshLastRunLabels(document);
  2635. });
  2636. const viewsHTML = overviewHTML + intelligenceHTML + researchHTML + communityHTML + youtubeHTML + commsHTML + meetingsHTML + profileRunsHTML;
  2637. return this.shellHTML({
  2638. title: `${name} · Agentic OS`,
  2639. eyebrow: `PROFILE · ${today.toFormat("EEEE, MMM d")}`,
  2640. backHref: "Dashboard/Home",
  2641. brandLabel: name,
  2642. brandSub: "Agentic OS",
  2643. avatar: this.avatarFor(name),
  2644. sidebarItems: [
  2645. { icon: "home", label: "Overview", view: "overview", active: true },
  2646. { icon: "flame", label: "Intelligence", view: "intelligence" },
  2647. { icon: "zap", label: "Research", view: "research" },
  2648. { icon: "users", label: "Community", view: "community" },
  2649. { icon: "chart", label: "YouTube", view: "youtube" },
  2650. { icon: "users", label: "Comms", view: "comms" },
  2651. { icon: "calendar", label: "Meetings", view: "meetings" },
  2652. { icon: "refresh", label: "Runs", view: "runs" },
  2653. { icon: "book", label: "Vault Overview", href: "Dashboard/Vault-Overview" },
  2654. ],
  2655. topActions: [
  2656. { icon: "🌅", label: "Morning brief", variant: "primary", cmd: "obsidian-shellcommands:shell-command-morning-brief" },
  2657. { icon: "📝", label: "New daily", cmd: "obsidian-shellcommands:shell-command-new-daily" },
  2658. { icon: "💬", label: "Launch Claude", variant: "dark", cmd: "terminal:open-terminal.claude.root" },
  2659. ],
  2660. viewsHTML,
  2661. });
  2662. }
  2663. // ===================================================================
  2664. // CLAUDE -p BACKGROUND RUNS (Operator actions)
  2665. // ===================================================================
  2666. claudePrompts() {
  2667. // Installer writes prompts into this.constructor.CONFIG.CLAUDE_PROMPTS. Pattern per entry:
  2668. // key: { label, prompt }
  2669. // Use {profile} in the prompt to interpolate the current profile name.
  2670. return this.constructor.CONFIG.CLAUDE_PROMPTS || {};
  2671. }
  2672. runStore() {
  2673. if (!window._ccClaudeRuns) window._ccClaudeRuns = [];
  2674. return window._ccClaudeRuns;
  2675. }
  2676. vaultBasePath() {
  2677. return app.vault.adapter?.basePath || app.vault.adapter?.getBasePath?.() || "";
  2678. }
  2679. runCardHTML(run) {
  2680. const statusClass = {
  2681. running: "cc-chip-primary",
  2682. completed: "cc-chip-accent",
  2683. error: "cc-chip-alert",
  2684. }[run.status] || "";
  2685. const elapsed = run.endedAt
  2686. ? Math.round((run.endedAt - run.startedAt) / 1000)
  2687. : Math.round((Date.now() - run.startedAt) / 1000);
  2688. const summary = run.summary || `${elapsed}s`;
  2689. // Auto-open the output while running, collapse when completed.
  2690. const outputOpen = run.status === "running" ? "open" : "";
  2691. return `
  2692. <div class="cc-card cc-run-card" data-run-id="${this.esc(run.id)}" style="margin-top:10px;padding:14px;border:1px solid #020309;border-radius:10px;background:#fff;color:#020309;">
  2693. <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px;">
  2694. <div style="display:flex;align-items:center;gap:8px;">
  2695. <strong style="font-size:13px;color:#020309;">${this.esc(run.label)}</strong>
  2696. <span class="cc-chip ${statusClass}">${run.status}</span>
  2697. <span class="cc-run-elapsed" style="font-size:11px;color:#020309;opacity:0.55;">${this.esc(summary)}</span>
  2698. </div>
  2699. <div class="cc-run-actions" style="display:flex;gap:6px;">
  2700. ${run.status === "running"
  2701. ? `<button class="cc-btn cc-run-stop" data-run-id="${this.esc(run.id)}">stop</button>`
  2702. : `<button class="cc-btn cc-run-clear" data-run-id="${this.esc(run.id)}">clear</button>`}
  2703. </div>
  2704. </div>
  2705. <details style="margin-bottom:10px;">
  2706. <summary style="cursor:pointer;font-size:11px;color:#020309;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;">Prompt</summary>
  2707. <div style="margin-top:6px;padding:10px;background:#f6f1e1;border:1px solid #020309;border-radius:6px;font-size:12px;line-height:1.5;color:#020309;white-space:pre-wrap;font-family:var(--font-monospace);">${this.esc(run.prompt)}</div>
  2708. </details>
  2709. <details class="cc-run-output-wrap" ${outputOpen}>
  2710. <summary style="cursor:pointer;font-size:11px;color:#020309;opacity:0.65;text-transform:uppercase;letter-spacing:0.5px;font-weight:600;">Output</summary>
  2711. <div class="cc-run-output" style="margin-top:6px;max-height:320px;min-height:60px;overflow:auto;padding:10px;background:#020309;color:#e8f0c9;border-radius:6px;font-size:11px;line-height:1.5;white-space:pre-wrap;word-break:break-word;font-family:var(--font-monospace);">${this.esc(run.output || "(waiting for output…)")}</div>
  2712. </details>
  2713. </div>`;
  2714. }
  2715. refreshRun(root, run) {
  2716. // Only update containers whose scope matches this run.
  2717. // A container declares its scope via data-runs-scope ("global" or a profile name).
  2718. document.querySelectorAll("[data-runs-scope]").forEach(container => {
  2719. if (container.dataset.runsScope !== (run.scope || "global")) return;
  2720. let card = container.querySelector(`[data-run-id="${run.id}"]`);
  2721. if (!card) {
  2722. container.insertAdjacentHTML("afterbegin", this.runCardHTML(run));
  2723. card = container.querySelector(`[data-run-id="${run.id}"]`);
  2724. this.wireRunCard(root, card);
  2725. return;
  2726. }
  2727. // In-place updates so user-set scroll on the <pre> is preserved.
  2728. const statusPill = card.querySelector(".cc-chip");
  2729. if (statusPill) {
  2730. statusPill.textContent = run.status;
  2731. statusPill.className = "cc-chip " + ({
  2732. running: "cc-chip-primary", completed: "cc-chip-accent", error: "cc-chip-alert",
  2733. }[run.status] || "");
  2734. }
  2735. const elapsedEl = card.querySelector(".cc-run-elapsed");
  2736. if (elapsedEl) {
  2737. const elapsed = run.endedAt
  2738. ? Math.round((run.endedAt - run.startedAt) / 1000)
  2739. : Math.round((Date.now() - run.startedAt) / 1000);
  2740. elapsedEl.textContent = run.summary || `${elapsed}s`;
  2741. }
  2742. const out = card.querySelector(".cc-run-output");
  2743. if (out) {
  2744. const wasAtBottom = (out.scrollHeight - out.scrollTop - out.clientHeight) < 40;
  2745. out.textContent = run.output || "(waiting for output…)";
  2746. if (wasAtBottom) out.scrollTop = out.scrollHeight;
  2747. }
  2748. // Auto-collapse the output drawer once the run transitions to completed.
  2749. const wrap = card.querySelector(".cc-run-output-wrap");
  2750. if (wrap) {
  2751. if (run.status === "running" && !wrap.hasAttribute("open")) wrap.setAttribute("open", "");
  2752. if (run.status !== "running" && wrap.hasAttribute("open") && !card.dataset.collapsed) {
  2753. wrap.removeAttribute("open");
  2754. card.dataset.collapsed = "1"; // collapse once, don't fight user re-opening it
  2755. }
  2756. }
  2757. // Toggle stop/clear button
  2758. const btnWrap = card.querySelector(".cc-run-actions");
  2759. if (btnWrap) {
  2760. btnWrap.innerHTML = run.status === "running"
  2761. ? `<button class="cc-btn cc-run-stop" data-run-id="${this.esc(run.id)}">stop</button>`
  2762. : `<button class="cc-btn cc-run-clear" data-run-id="${this.esc(run.id)}">clear</button>`;
  2763. this.wireRunCard(root, card);
  2764. }
  2765. });
  2766. }
  2767. wireRunCard(root, card) {
  2768. card.querySelectorAll(".cc-run-stop").forEach(b => {
  2769. b.addEventListener("click", () => {
  2770. const run = this.runStore().find(r => r.id === b.dataset.runId);
  2771. if (!run?.child) return;
  2772. const pid = run.child.pid;
  2773. // Signal the process group (claude + any children it spawned).
  2774. // SIGTERM first, then SIGKILL after 2s if still alive.
  2775. const sig = (s) => { try { process.kill(-pid, s); } catch { try { run.child.kill(s); } catch {} } };
  2776. sig("SIGTERM");
  2777. setTimeout(() => { if (run.status === "running") sig("SIGKILL"); }, 2000);
  2778. run.output += "\n[stopped by user]\n";
  2779. this.refreshRun(document.querySelector(".cc-root"), run);
  2780. });
  2781. });
  2782. card.querySelectorAll(".cc-run-clear").forEach(b => {
  2783. b.addEventListener("click", () => {
  2784. const store = this.runStore();
  2785. const i = store.findIndex(r => r.id === b.dataset.runId);
  2786. if (i >= 0) store.splice(i, 1);
  2787. card.remove();
  2788. });
  2789. });
  2790. }
  2791. restoreRunHistory(root) {
  2792. // Render runs into whichever scoped container is on this page.
  2793. // refreshRun prepends each card via insertAdjacentHTML("afterbegin"), so
  2794. // we iterate OLDEST-FIRST to leave the newest card at the top.
  2795. const containers = root.querySelectorAll("[data-runs-scope]");
  2796. if (!containers.length) return;
  2797. const runs = this.runStore();
  2798. containers.forEach(container => {
  2799. const scope = container.dataset.runsScope;
  2800. container.innerHTML = "";
  2801. runs
  2802. .filter(r => (r.scope || "global") === scope)
  2803. .slice()
  2804. .sort((a, b) => (a.startedAt || 0) - (b.startedAt || 0)) // oldest first
  2805. .forEach(r => this.refreshRun(root, r));
  2806. });
  2807. }
  2808. runClaude(key, root, ctx = {}) {
  2809. const def = this.claudePrompts()[key];
  2810. if (!def) return;
  2811. const cwd = this.vaultBasePath();
  2812. if (!cwd) { console.error("[dashboard] vault base path not resolvable"); return; }
  2813. let spawn;
  2814. try {
  2815. spawn = require("child_process").spawn;
  2816. } catch (e) {
  2817. console.error("[dashboard] child_process unavailable", e);
  2818. return;
  2819. }
  2820. const substitute = (s) => String(s || "").replace(/\{(\w+)\}/g, (_, k) => ctx[k] ?? `{${k}}`);
  2821. const finalPrompt = substitute(def.prompt || "");
  2822. const finalRaw = def.raw ? substitute(def.raw) : null;
  2823. const shellPath = process.env.SHELL || "/bin/zsh";
  2824. const isRaw = !!def.raw;
  2825. const shellCmd = isRaw
  2826. ? finalRaw
  2827. : `exec claude -p '${finalPrompt.replace(/'/g, "'\\''")}' --output-format stream-json --verbose --dangerously-skip-permissions`;
  2828. const id = `${key}-${Date.now()}`;
  2829. const scope = ctx.profile || "global";
  2830. const labelSuffix = ctx.profile ? ` · ${ctx.profile}` : "";
  2831. const run = {
  2832. id, key, scope,
  2833. label: (def.label || key) + labelSuffix,
  2834. prompt: finalPrompt || finalRaw || "",
  2835. status: "running",
  2836. output: "",
  2837. summary: null,
  2838. startedAt: Date.now(),
  2839. endedAt: null,
  2840. child: null,
  2841. isRaw,
  2842. };
  2843. this.runStore().unshift(run);
  2844. this.refreshRun(root, run);
  2845. this.refreshLastRunLabels(document);
  2846. console.log("[dashboard] spawning", { shellPath, cwd, shellCmd });
  2847. let child;
  2848. try {
  2849. child = spawn(
  2850. shellPath,
  2851. ["-l", "-c", shellCmd],
  2852. { cwd, env: { ...process.env }, detached: true }
  2853. );
  2854. } catch (err) {
  2855. run.status = "error";
  2856. run.output = `Failed to spawn claude: ${err.message}\n\nIs the claude CLI on PATH? Try: which claude`;
  2857. run.endedAt = Date.now();
  2858. this.refreshRun(root, run);
  2859. return;
  2860. }
  2861. run.child = child;
  2862. run._buf = ""; // partial-line buffer for JSON parsing
  2863. run.output = "Launching claude…\n";
  2864. this.refreshRun(root, run);
  2865. console.log("[dashboard] spawned pid=", child.pid);
  2866. const appendText = (s) => {
  2867. run.output += s;
  2868. this.refreshRun(root, run);
  2869. };
  2870. const describeTool = (name, input) => {
  2871. input = input || {};
  2872. switch (name) {
  2873. case "Read": return `Reading ${input.file_path || ""}`;
  2874. case "Write": return `Writing ${input.file_path || ""}`;
  2875. case "Edit": return `Editing ${input.file_path || ""}`;
  2876. case "Glob": return `Searching for ${input.pattern || ""}${input.path ? " in " + input.path : ""}`;
  2877. case "Grep": return `Grep "${(input.pattern || "").slice(0,60)}"${input.path ? " in " + input.path : ""}`;
  2878. case "Bash": return `Bash: ${(input.command || "").slice(0,100)}`;
  2879. case "WebFetch": return `Fetching ${input.url || ""}`;
  2880. case "WebSearch": return `Web search: ${input.query || ""}`;
  2881. case "TodoWrite": return `Updating todo list (${(input.todos || []).length} items)`;
  2882. case "Task": return `Subagent: ${input.description || input.subagent_type || ""}`;
  2883. default: {
  2884. const summary = Object.entries(input).slice(0, 2)
  2885. .map(([k, v]) => `${k}=${String(v).slice(0, 60)}`).join(" ");
  2886. return `${name}${summary ? " · " + summary : ""}`;
  2887. }
  2888. }
  2889. };
  2890. const handleEvent = (ev) => {
  2891. try {
  2892. if (ev.type === "system" && ev.subtype === "init") {
  2893. appendText(`Starting (${ev.model || "claude"})\n`);
  2894. } else if (ev.type === "assistant" && ev.message?.content) {
  2895. for (const c of ev.message.content) {
  2896. if (c.type === "text" && c.text) appendText(c.text);
  2897. else if (c.type === "tool_use") appendText(`\n→ ${describeTool(c.name, c.input)}\n`);
  2898. // thinking blocks are internal — skip
  2899. }
  2900. } else if (ev.type === "user" && ev.message?.content) {
  2901. // tool results would be too noisy in the live view — skip
  2902. } else if (ev.type === "result") {
  2903. const cost = ev.total_cost_usd ?? ev.cost_usd ?? 0;
  2904. const secs = Math.round((ev.duration_ms || 0) / 100) / 10;
  2905. run.summary = `${secs}s · $${cost.toFixed(3)}`;
  2906. }
  2907. } catch (e) {
  2908. // ignore malformed events
  2909. }
  2910. };
  2911. const onStdout = (chunk) => {
  2912. const s = chunk.toString();
  2913. console.log("[dashboard] stdout chunk", s.length, "bytes");
  2914. if (run.isRaw) { appendText(s); return; }
  2915. run._buf += s;
  2916. const lines = run._buf.split("\n");
  2917. run._buf = lines.pop(); // keep last partial line
  2918. for (const line of lines) {
  2919. const trimmed = line.trim();
  2920. if (!trimmed) continue;
  2921. if (trimmed.startsWith("{")) {
  2922. try { handleEvent(JSON.parse(trimmed)); continue; } catch {}
  2923. }
  2924. appendText(trimmed + "\n");
  2925. }
  2926. };
  2927. const onStderr = (chunk) => {
  2928. const s = chunk.toString();
  2929. run.stderr = (run.stderr || "") + s;
  2930. // Filter known harmless warnings from the user-visible output.
  2931. if (/no stdin data received/i.test(s)) return;
  2932. appendText(s);
  2933. };
  2934. child.stdout.on("data", onStdout);
  2935. child.stderr.on("data", onStderr);
  2936. child.on("error", (err) => {
  2937. run.status = "error";
  2938. run.output += `\n[error] ${err.message}\n`;
  2939. run.endedAt = Date.now();
  2940. this.refreshRun(root, run);
  2941. this.persistRuns();
  2942. });
  2943. child.on("close", (code) => {
  2944. // flush any trailing buffer
  2945. if (run._buf) { appendText(run._buf); run._buf = ""; }
  2946. run.status = code === 0 ? "completed" : "error";
  2947. if (code !== 0) run.output += `\n[exit code ${code}]`;
  2948. run.endedAt = Date.now();
  2949. run.child = null;
  2950. this.refreshRun(root, run);
  2951. this.refreshLastRunLabels(document);
  2952. this.persistRuns();
  2953. });
  2954. }
  2955. // -------------------------------------------------------------------
  2956. // Run persistence (survives Obsidian reloads)
  2957. // Global runs → Dashboard/runs.json
  2958. // Profile runs → <profile-folder>/runs.json
  2959. // -------------------------------------------------------------------
  2960. runsPathFor(scope) {
  2961. return scope === "global"
  2962. ? "Dashboard/runs.json"
  2963. : `${this.profileRunsPath(scope)}`;
  2964. }
  2965. slimRun(r) {
  2966. return {
  2967. id: r.id, key: r.key, scope: r.scope || "global",
  2968. label: r.label, prompt: r.prompt,
  2969. status: r.status, output: r.output, summary: r.summary,
  2970. startedAt: r.startedAt, endedAt: r.endedAt,
  2971. };
  2972. }
  2973. async persistRuns() {
  2974. try {
  2975. const adapter = app.vault.adapter;
  2976. const store = this.runStore().filter(r => r.status !== "running");
  2977. const byScope = {};
  2978. for (const r of store) {
  2979. const s = r.scope || "global";
  2980. (byScope[s] = byScope[s] || []).push(this.slimRun(r));
  2981. }
  2982. for (const [scope, runs] of Object.entries(byScope)) {
  2983. const path = this.runsPathFor(scope);
  2984. // ensure parent folder exists for profile paths
  2985. if (scope !== "global") {
  2986. const folder = path.split("/").slice(0, -1).join("/");
  2987. if (!(await adapter.exists(folder))) {
  2988. try { await adapter.mkdir(folder); } catch {}
  2989. }
  2990. }
  2991. await adapter.write(path, JSON.stringify(runs.slice(0, 50), null, 2));
  2992. }
  2993. } catch (e) {
  2994. console.warn("[dashboard] persistRuns failed", e);
  2995. }
  2996. }
  2997. async loadPersistedRuns() {
  2998. const adapter = app.vault.adapter;
  2999. const all = [];
  3000. // Global
  3001. try {
  3002. if (await adapter.exists("Dashboard/runs.json")) {
  3003. const raw = await adapter.read("Dashboard/runs.json");
  3004. const parsed = JSON.parse(raw) || [];
  3005. for (const r of parsed) all.push({ ...r, scope: r.scope || "global" });
  3006. }
  3007. } catch (e) { /* ignore */ }
  3008. // Per-profile
  3009. try {
  3010. const profilesFolder = app.vault.getAbstractFileByPath(this.constructor.CONFIG.PROFILE_FOLDER_PATTERN.replace("{ORG}", this.constructor.CONFIG.ORG_NAME).replace("/{name}", ""));
  3011. if (profilesFolder?.children) {
  3012. for (const p of profilesFolder.children) {
  3013. if (!p.children) continue;
  3014. const path = `${this.profileRunsPath(p.name)}`;
  3015. if (!(await adapter.exists(path))) continue;
  3016. try {
  3017. const raw = await adapter.read(path);
  3018. const parsed = JSON.parse(raw) || [];
  3019. for (const r of parsed) all.push({ ...r, scope: r.scope || p.name });
  3020. } catch (e) { /* ignore */ }
  3021. }
  3022. }
  3023. } catch (e) { /* ignore */ }
  3024. return all;
  3025. }
  3026. async hydrateRunsOnce() {
  3027. if (window._ccRunsHydrated) return;
  3028. window._ccRunsHydrated = true;
  3029. const persisted = await this.loadPersistedRuns();
  3030. const store = this.runStore();
  3031. const existingIds = new Set(store.map(r => r.id));
  3032. for (const r of persisted) {
  3033. if (!existingIds.has(r.id)) store.push(r);
  3034. }
  3035. store.sort((a, b) => b.startedAt - a.startedAt);
  3036. }
  3037. // ===================================================================
  3038. // VAULT OVERVIEW (Vault-Overview.md) — returns HTML string
  3039. // OS schematic: folders, rules, skills, profiles, operator, pipelines.
  3040. // ===================================================================
  3041. async buildOverviewHTML(dv) {
  3042. const today = dv.luxon.DateTime.now();
  3043. const all = app.vault.getAllLoadedFiles();
  3044. const md = all.filter(f => f.extension === "md" && !f.path.startsWith(".trash"));
  3045. const claudeFiles = md.filter(f => f.name === "CLAUDE.md");
  3046. const skillsFolder = this.constructor.CONFIG.SKILLS_FOLDER ? all.find(f => f.path === this.constructor.CONFIG.SKILLS_FOLDER && f.children) : null;
  3047. const skillNames = skillsFolder ? skillsFolder.children.filter(x => x.children).map(x => x.name).sort() : [];
  3048. const profilesFolder = all.find(f => f.path === this.constructor.CONFIG.PROFILE_FOLDER_PATTERN.replace("{ORG}", this.constructor.CONFIG.ORG_NAME).replace("/{name}", "") && f.children);
  3049. const profiles = profilesFolder ? profilesFolder.children.filter(x => x.children).map(x => x.name) : [];
  3050. const depts = all.filter(f => f.path?.startsWith("Departments/") && f.children && f.path.split("/").length === 2).map(f => f.name);
  3051. const dailies = md.filter(f => f.path.startsWith("Daily/")).length;
  3052. const meetings = md.filter(f => f.path.startsWith("Intelligence/meetings/")).length;
  3053. const decisions = md.filter(f => f.path.startsWith("Intelligence/decisions/")).length;
  3054. const folderRows = (this.constructor.CONFIG.OVERVIEW_FOLDERS && this.constructor.CONFIG.OVERVIEW_FOLDERS.length)
  3055. ? this.constructor.CONFIG.OVERVIEW_FOLDERS
  3056. : (all.filter(f => f.children && !f.path.startsWith(".")).slice(0, 12)
  3057. .map(f => [f.path + "/", "Top-level folder", null]));
  3058. const rulebook = [
  3059. { p: "CLAUDE", l: "Root" },
  3060. { p: "Dashboard/CLAUDE", l: "Dashboard" },
  3061. ...(this.constructor.CONFIG.OVERVIEW_FOLDERS || []).map(([path, _, claude]) => ({ p: claude || (path + "CLAUDE"), l: path.replace(/\/$/, "") })),
  3062. ].filter(r => r.p);
  3063. const skillGroups = this.constructor.CONFIG.SKILL_GROUPS || {};
  3064. const projectCats = (this.constructor.CONFIG.PROJECT_CATEGORIES || []).map(c => {
  3065. const folder = app.vault.getAbstractFileByPath(`Projects/${c}`);
  3066. const n = folder?.children?.filter(x => x.children).length ?? 0;
  3067. return { c, n };
  3068. });
  3069. const connectors = this.constructor.CONFIG.CONNECTORS || [];
  3070. const cheatsheet = this.constructor.CONFIG.CHEATSHEET || [];
  3071. const today_str = today.toFormat("yyyy-MM-dd");
  3072. const todayDaily = app.vault.getAbstractFileByPath(`Daily/${today_str}.md`);
  3073. const fm = todayDaily ? (app.metadataCache.getFileCache(todayDaily)?.frontmatter || {}) : {};
  3074. const operatorFields = ["meetings","slack_messages","circle_posts","tasks_created","tasks_completed","escalations_open"];
  3075. const recent = md
  3076. .sort((a,b) => b.stat.mtime - a.stat.mtime)
  3077. .slice(0, 12);
  3078. // ---------- Build view ----------
  3079. const overviewHTML = `
  3080. <section class="cc-view" data-view="overview">
  3081. <div class="cc-kpis">
  3082. <div class="cc-kpi cc-kpi-primary">
  3083. <div class="cc-kpi-head"><span class="cc-kpi-label">Markdown files</span></div>
  3084. <div class="cc-kpi-value">${md.length}</div>
  3085. <div class="cc-kpi-foot">total in vault</div>
  3086. </div>
  3087. <div class="cc-kpi">
  3088. <div class="cc-kpi-head"><span class="cc-kpi-label">CLAUDE.md rules</span></div>
  3089. <div class="cc-kpi-value">${claudeFiles.length}</div>
  3090. <div class="cc-kpi-foot">cascading instruction files</div>
  3091. </div>
  3092. <div class="cc-kpi">
  3093. <div class="cc-kpi-head"><span class="cc-kpi-label">Skills</span></div>
  3094. <div class="cc-kpi-value">${skillNames.length}</div>
  3095. <div class="cc-kpi-foot">${this.constructor.CONFIG.SKILLS_FOLDER ? "in " + this.constructor.CONFIG.SKILLS_FOLDER.split("/").pop() : "(none configured)"}</div>
  3096. </div>
  3097. <div class="cc-kpi">
  3098. <div class="cc-kpi-head"><span class="cc-kpi-label">Profiles</span></div>
  3099. <div class="cc-kpi-value">${profiles.length}</div>
  3100. <div class="cc-kpi-foot">${depts.length} departments · ${dailies} root dailies</div>
  3101. </div>
  3102. </div>
  3103. <div class="cc-card cc-card-wide">
  3104. <div class="cc-card-head">
  3105. <h3>Actions</h3>
  3106. <a class="cc-tag cc-nav-btn" data-view="runs" style="cursor:pointer;">View run history →</a>
  3107. </div>
  3108. <div class="cc-card-body">
  3109. <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-start;">
  3110. ${this.actionButton("optimizer", "⚙️ OS Optimizer", { variant: "primary" })}
  3111. ${this.actionButton("lint", "🧹 Lint", {})}
  3112. ${this.actionButton("checkProfile", "👤 Check profile", {})}
  3113. ${this.actionButton("auditDailies", "📅 Audit dailies", {})}
  3114. ${this.actionButton("operatorRun", "📊 Operator refresh",{})}
  3115. ${this.actionButton("linkHealth", "🔗 Link health", {})}
  3116. </div>
  3117. <p style="margin:10px 0 0;font-size:12px;opacity:0.65;">Output streams to <a class="cc-nav-btn" data-view="runs" style="cursor:pointer;text-decoration:underline;">Runs</a>. History persists across reloads.</p>
  3118. </div>
  3119. </div>
  3120. <div class="cc-card cc-card-wide">
  3121. <div class="cc-card-head"><h3>Vault map</h3><span class="cc-tag">${folderRows.length} folders</span></div>
  3122. <div class="cc-card-body">
  3123. <table class="cc-table">
  3124. <thead><tr><th style="width:180px">Folder</th><th>What lives here</th><th style="width:80px">Rules</th></tr></thead>
  3125. <tbody>
  3126. ${folderRows.map(([folder, desc, rulePath]) => `
  3127. <tr>
  3128. <td><code>${this.esc(folder)}</code></td>
  3129. <td>${this.esc(desc)}</td>
  3130. <td>${rulePath ? `<a class="cc-link" data-href="${this.esc(rulePath)}">→</a>` : `<span class="cc-muted">·</span>`}</td>
  3131. </tr>`).join("")}
  3132. </tbody>
  3133. </table>
  3134. </div>
  3135. </div>
  3136. <div class="cc-card cc-card-wide">
  3137. <div class="cc-card-head"><h3>Rulebook · CLAUDE.md cascade</h3><span class="cc-tag">${rulebook.length}</span></div>
  3138. <div class="cc-card-body">
  3139. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;">
  3140. ${rulebook.map(r => `<a class="cc-chip cc-link" data-href="${this.esc(r.p)}">${this.esc(r.l)}</a>`).join("")}
  3141. </div>
  3142. </div>
  3143. </div>
  3144. </section>`;
  3145. const skillsHTML = `
  3146. <section class="cc-view" data-view="skills" hidden>
  3147. ${Object.entries(skillGroups).map(([group, list]) => `
  3148. <div class="cc-card cc-card-wide">
  3149. <div class="cc-card-head"><h3>${this.esc(group)}</h3><span class="cc-tag">${list.length}</span></div>
  3150. <div class="cc-card-body">
  3151. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;">
  3152. ${list.map(s => `<a class="cc-chip cc-link" data-href="${this.constructor.CONFIG.SKILLS_FOLDER}/${s}">${this.esc(s)}</a>`).join("")}
  3153. </div>
  3154. </div>
  3155. </div>`).join("")}
  3156. <div class="cc-card cc-card-wide">
  3157. <div class="cc-card-head"><h3>Full skill registry</h3><span class="cc-tag">${skillNames.length}</span></div>
  3158. <div class="cc-card-body">
  3159. <p style="margin:0 0 8px;opacity:0.7;font-size:13px;">Every folder under <code>${this.constructor.CONFIG.SKILLS_FOLDER || "(no skills folder configured)"}/</code>.</p>
  3160. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;">
  3161. ${skillNames.map(s => `<a class="cc-chip cc-link" data-href="${this.constructor.CONFIG.SKILLS_FOLDER}/${s}">${this.esc(s)}</a>`).join("")}
  3162. </div>
  3163. </div>
  3164. </div>
  3165. </section>`;
  3166. const operatorHTML = `
  3167. <section class="cc-view" data-view="operator" hidden>
  3168. <div class="cc-card cc-card-wide">
  3169. <div class="cc-card-head"><h3>Vault Operator</h3><span class="cc-tag">ETL · hourly</span></div>
  3170. <div class="cc-card-body">
  3171. <p style="margin:0 0 12px;">The ETL layer between raw vault activity and the dashboards. Dashboard is read-only. The Operator writes the frontmatter the dashboards consume.</p>
  3172. <div class="cc-person-chips" style="gap:6px;"> </div>
  3173. </div>
  3174. </div>
  3175. <div class="cc-grid cc-grid-2">
  3176. <div class="cc-card">
  3177. <div class="cc-card-head"><h3>Root daily fields</h3></div>
  3178. <div class="cc-card-body">
  3179. <div class="cc-person-chips" style="gap:4px;flex-wrap:wrap;">
  3180. ${["meetings","meeting_minutes","slack_messages","slack_threads","circle_posts","circle_replies","escalations_open","escalations_resolved","tasks_created","tasks_completed","active_team"].map(k => `<span class="cc-chip">${k}</span>`).join("")}
  3181. </div>
  3182. </div>
  3183. </div>
  3184. <div class="cc-card">
  3185. <div class="cc-card-head"><h3>Profile daily fields</h3></div>
  3186. <div class="cc-card-body">
  3187. <div class="cc-person-chips" style="gap:4px;flex-wrap:wrap;">
  3188. ${["energy","focus","wins_today","open_loops","meetings_attended","outputs_published"].map(k => `<span class="cc-chip">${k}</span>`).join("")}
  3189. </div>
  3190. </div>
  3191. </div>
  3192. </div>
  3193. <div class="cc-card cc-card-wide">
  3194. <div class="cc-card-head"><h3>Today's Operator output</h3><span class="cc-tag">${today_str}</span></div>
  3195. <div class="cc-card-body">
  3196. ${todayDaily
  3197. ? `<table class="cc-table">
  3198. <thead><tr><th style="width:200px">Field</th><th>Value</th></tr></thead>
  3199. <tbody>${operatorFields.map(k => `<tr><td><code>${k}</code></td><td>${fm[k] != null ? this.esc(String(fm[k])) : `<span class="cc-muted">·</span>`}</td></tr>`).join("")}</tbody>
  3200. </table>`
  3201. : `<div class="cc-empty">No root daily for ${today_str} yet.</div>`}
  3202. </div>
  3203. </div>
  3204. </section>`;
  3205. const atlasHTML = `
  3206. <section class="cc-view" data-view="atlas" hidden>
  3207. <div class="cc-card cc-card-wide">
  3208. <div class="cc-card-head"><h3>Dashboards</h3><span class="cc-tag">${this.constructor.CONFIG.PROFILES.length + 3}</span></div>
  3209. <div class="cc-card-body">
  3210. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;">
  3211. <a class="cc-chip cc-chip-primary cc-link" data-href="Dashboard/Home">Home</a>
  3212. ${this.constructor.CONFIG.PROFILES.map(n => `<a class="cc-chip cc-link" data-href="Dashboard/${n}">${this.esc(n)}</a>`).join("")}
  3213. <a class="cc-chip cc-link" data-href="Dashboard/Vault-Overview">Vault Overview</a>
  3214. <a class="cc-chip cc-link" data-href="Dashboard/Setup">Setup</a>
  3215. </div>
  3216. </div>
  3217. </div>
  3218. <div class="cc-grid cc-grid-2">
  3219. <div class="cc-card">
  3220. <div class="cc-card-head"><h3>Profiles</h3><span class="cc-tag">${profiles.length}</span></div>
  3221. <div class="cc-card-body">
  3222. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;">
  3223. ${profiles.map(n => `<a class="cc-chip cc-link" data-href="${this.profilePath(n)}/${n}">${this.esc(n)}</a>`).join("")}
  3224. </div>
  3225. </div>
  3226. </div>
  3227. <div class="cc-card">
  3228. <div class="cc-card-head"><h3>Departments</h3><span class="cc-tag">${depts.length}</span></div>
  3229. <div class="cc-card-body">
  3230. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;">
  3231. ${depts.map(d => `<a class="cc-chip cc-link" data-href="Departments/${d}/CLAUDE">${this.esc(d)}</a>`).join("")}
  3232. </div>
  3233. </div>
  3234. </div>
  3235. </div>
  3236. <div class="cc-card cc-card-wide">
  3237. <div class="cc-card-head"><h3>Project categories</h3><span class="cc-tag">${projectCats.reduce((a,b)=>a+b.n,0)} active</span></div>
  3238. <div class="cc-card-body">
  3239. <table class="cc-table">
  3240. <thead><tr><th style="width:200px">Category</th><th>Active projects</th></tr></thead>
  3241. <tbody>
  3242. ${projectCats.map(({c,n}) => `<tr><td><a class="cc-link" data-href="Projects/${c}/CLAUDE">${this.esc(c)}</a></td><td>${n}</td></tr>`).join("")}
  3243. </tbody>
  3244. </table>
  3245. </div>
  3246. </div>
  3247. <div class="cc-card cc-card-wide">
  3248. <div class="cc-card-head"><h3>Connectors and MCPs</h3><span class="cc-tag">${connectors.length}</span></div>
  3249. <div class="cc-card-body">
  3250. <table class="cc-table">
  3251. <thead><tr><th style="width:220px">Connector</th><th>Purpose</th></tr></thead>
  3252. <tbody>${connectors.map(([n,p]) => `<tr><td><strong>${this.esc(n)}</strong></td><td>${this.esc(p)}</td></tr>`).join("")}</tbody>
  3253. </table>
  3254. </div>
  3255. </div>
  3256. <div class="cc-card cc-card-wide">
  3257. <div class="cc-card-head"><h3>Daily flow</h3></div>
  3258. <div class="cc-card-body">
  3259. <p style="margin:0;">Team works in vault → Vault Operator hourly ETL → frontmatter populated → Dashboard renders.</p>
  3260. </div>
  3261. </div>
  3262. <div class="cc-card cc-card-wide">
  3263. <div class="cc-card-head"><h3>Content pipeline</h3></div>
  3264. <div class="cc-card-body">
  3265. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;align-items:center;">
  3266. ${["video-research","video-outline","video-slide-plan","video-slide-visuals","repurposing","yt-to-community","yt-to-course"].map((s,i,a) => `<span class="cc-chip">${s}</span>${i<a.length-1?'<span style="opacity:0.4">→</span>':''}`).join("")}
  3267. </div>
  3268. </div>
  3269. </div>
  3270. <div class="cc-card cc-card-wide">
  3271. <div class="cc-card-head"><h3>Sales pipeline</h3></div>
  3272. <div class="cc-card-body">
  3273. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;align-items:center;">
  3274. ${["email-triage","email-sales-copy","failed-payment-recovery","churn-recovery-daily","weekly-report"].map((s,i,a) => `<span class="cc-chip">${s}</span>${i<a.length-1?'<span style="opacity:0.4">→</span>':''}`).join("")}
  3275. </div>
  3276. </div>
  3277. </div>
  3278. <div class="cc-card cc-card-wide">
  3279. <div class="cc-card-head"><h3>Community pipeline</h3></div>
  3280. <div class="cc-card-body">
  3281. <div class="cc-person-chips" style="gap:6px;flex-wrap:wrap;align-items:center;">
  3282. ${["community-responder","dm-responder","community","weekly-report"].map((s,i,a) => `<span class="cc-chip">${s}</span>${i<a.length-1?'<span style="opacity:0.4">→</span>':''}`).join("")}
  3283. </div>
  3284. </div>
  3285. </div>
  3286. <div class="cc-card cc-card-wide">
  3287. <div class="cc-card-head"><h3>Where do I put X</h3></div>
  3288. <div class="cc-card-body">
  3289. <table class="cc-table">
  3290. <thead><tr><th style="width:280px">Thing</th><th>Goes in</th></tr></thead>
  3291. <tbody>${cheatsheet.map(([t,p]) => `<tr><td><strong>${this.esc(t)}</strong></td><td><code>${this.esc(p)}</code></td></tr>`).join("")}</tbody>
  3292. </table>
  3293. </div>
  3294. </div>
  3295. <div class="cc-card cc-card-wide">
  3296. <div class="cc-card-head"><h3>Anti-patterns</h3></div>
  3297. <div class="cc-card-body">
  3298. <ul class="cc-md-list">
  3299. <li>Creating files in the vault root. Everything lives in an existing folder.</li>
  3300. <li>Orphan notes with no wikilink from anywhere else.</li>
  3301. <li>Writing dashboard logic into markdown shells. It belongs in <code>dashboard.js</code>.</li>
  3302. <li>Stuffing all project info into one README. Route to subdirs.</li>
  3303. <li>Using em dashes anywhere in the vault.</li>
  3304. <li>Vault Operator writing fields the dashboard never reads (drift).</li>
  3305. </ul>
  3306. </div>
  3307. </div>
  3308. <div class="cc-card cc-card-wide">
  3309. <div class="cc-card-head"><h3>Recently updated</h3><span class="cc-tag">${recent.length}</span></div>
  3310. <div class="cc-card-body">
  3311. <table class="cc-table">
  3312. <thead><tr><th>File</th><th style="width:140px">Updated</th></tr></thead>
  3313. <tbody>${recent.map(f => `<tr><td><a class="cc-link" data-href="${this.esc(f.path)}">${this.esc(f.basename)}</a></td><td>${this.rel(dv.luxon.DateTime.fromMillis(f.stat.mtime), today)}</td></tr>`).join("")}</tbody>
  3314. </table>
  3315. </div>
  3316. </div>
  3317. </section>`;
  3318. // Hydrate persisted runs (one-shot per session) so the Runs view shows
  3319. // history from previous sessions. Fire-and-forget, runs are rendered
  3320. // by wire()'s restoreRunHistory once hydration completes.
  3321. this.hydrateRunsOnce().then(() => {
  3322. const r = document.querySelector(".cc-root:not(.cc-loading)");
  3323. if (r) this.restoreRunHistory(r);
  3324. this.refreshLastRunLabels(document);
  3325. });
  3326. const runsHTML = `
  3327. <section class="cc-view" data-view="runs" hidden>
  3328. <div class="cc-card cc-card-wide">
  3329. <div class="cc-card-head"><h3>Background runs</h3><span class="cc-tag">claude -p · history</span></div>
  3330. <div class="cc-card-body">
  3331. <p style="margin:0 0 8px;opacity:0.7;font-size:13px;">History of every action launched from the Overview. Persists across reloads.</p>
  3332. <div id="cc-claude-runs-all" class="cc-claude-runs" data-runs-scope="global"></div>
  3333. </div>
  3334. </div>
  3335. </section>`;
  3336. const viewsHTML = overviewHTML + skillsHTML + operatorHTML + runsHTML + atlasHTML;
  3337. return this.shellHTML({
  3338. title: "Vault Overview",
  3339. eyebrow: `OS SCHEMATIC · ${today.toFormat("EEEE, MMM d")}`,
  3340. avatar: this.brandMark(),
  3341. backHref: "Dashboard/Home",
  3342. sidebarItems: [
  3343. { icon: "home", label: "Overview", view: "overview", active: true },
  3344. { icon: "zap", label: "Skills", view: "skills" },
  3345. { icon: "refresh", label: "Operator", view: "operator" },
  3346. { icon: "flame", label: "Runs", view: "runs" },
  3347. { icon: "book", label: "Atlas", view: "atlas" },
  3348. ],
  3349. topActions: [
  3350. { icon: "💬", label: "Launch Claude", variant: "dark", cmd: "terminal:open-terminal.claude.root" },
  3351. ],
  3352. viewsHTML,
  3353. });
  3354. }
  3355. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.