Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
fix(marketing): google-ads provision chosen_customer unbound var + customer-id-hint (#348)
Aurora Capital6bbc82c39762
diff --git a/claude-ops/bin/ops-marketing-provision b/claude-ops/bin/ops-marketing-provisionindex 6df97dc4..6428afdc 100755--- a/claude-ops/bin/ops-marketing-provision+++ b/claude-ops/bin/ops-marketing-provision@@ -6,7 +6,7 @@# [--display-name <name>] [--industry SHOPPING|TECHNOLOGY]# provision-gsc --project <key> [--site sc-domain:<d>|https://<d>/]# provision-instagram --project <key> [--force]-# provision-google-ads --project <key> [--skip-if-pending]+# provision-google-ads --project <key> [--skip-if-pending] [--customer-id <id>|--customer-name <pattern>]# provision-all --project <key> | --all-projects# status --project <key> [--json]# --help@@ -772,12 +772,14 @@ gads_scan_credential() {# Step D: customer ID resolution (auto-MCC detection)# ---------------------------------------------------------------------------cmd_provision_google_ads() {- local project="" skip_if_pending=0+ local project="" skip_if_pending=0 arg_customer_id="" arg_customer_name=""while [ $# -gt 0 ]; docase "$1" in--project) project="${2:-}"; shift ;;--skip-if-pending) skip_if_pending=1 ;;+ --customer-id) arg_customer_id="${2:-}"; shift ;;+ --customer-name) arg_customer_name="${2:-}"; shift ;;*) die "Unknown argument to provision-google-ads: $1" ;;esacshift@@ -919,13 +921,52 @@ cmd_provision_google_ads() {resource_names=$(printf '%s' "$accessible" | jq -r '.resourceNames[]? // empty' 2>/dev/null)[ -n "$resource_names" ] || die "No accessible customers — $(printf '%s' "$accessible" | jq -r '.error.message // "unknown error"')"- # Single account: auto-select. Multiple: log all and pick first non-manager.- local customer_count chosen_customer login_customer=""+ # Single account: auto-select. Multiple: prefer flag/hint, else prompt or pick first non-manager.+ # IMPORTANT: init chosen_customer="" — required by `set -u` since downstream `[ -z "$chosen_customer" ]`+ # checks fire before any assignment in the multi-account loop (e.g. when all accounts are managers).+ local customer_count chosen_customer="" login_customer=""customer_count=$(printf '%s\n' "$resource_names" | wc -l | tr -d ' ')log "Accessible customers ($customer_count):"printf '%s\n' "$resource_names" | sed 's/^/ - /' >&2- if [ "$customer_count" = "1" ]; then+ # Resolve hint from prefs (cron-safe: set once, run unattended thereafter)+ local hint=""+ hint=$(prefs_get_project_field "$project" "google_ads" "customer_id_hint" 2>/dev/null || true)+ [ "$hint" = "null" ] && hint=""+ # CLI flag wins over prefs hint+ [ -n "$arg_customer_name" ] && [ -z "$arg_customer_id" ] && hint=""+ [ -n "$arg_customer_id" ] && hint="$arg_customer_id"+ # Explicit --customer-id must match accessible accounts (prefs hint may be stale and may fall through)+ if [ -n "$arg_customer_id" ] && ! printf '%s\n' "$resource_names" | grep -qx "customers/${arg_customer_id}"; then+ die "--customer-id ${arg_customer_id} is not in the accessible customers list"+ fi++ # Direct ID hint: verify it's in the accessible list, accept it.+ if [ -n "$hint" ] && printf '%s\n' "$resource_names" | grep -qx "customers/${hint}"; then+ chosen_customer="$hint"+ log "Using customer ID from hint/flag: $chosen_customer"+ fi++ # Name pattern (flag): substring match on descriptive_name across accessible accounts.+ if [ -z "$chosen_customer" ] && [ -n "$arg_customer_name" ]; then+ while IFS= read -r rn; do+ [ -z "$rn" ] && continue+ local cid_n info_n name_n+ cid_n="${rn##customers/}"+ info_n=$(gads_get_customer_info "$cid_n" "$access_token" "$dev_token" 2>/dev/null || echo "{}")+ name_n=$(printf '%s' "$info_n" | jq -r '.results[0].customer.descriptiveName // ""' 2>/dev/null)+ if printf '%s' "$name_n" | grep -qiF -- "$arg_customer_name"; then+ chosen_customer="$cid_n"+ log "Name match \"$arg_customer_name\" -> $name_n ($cid_n)"+ break+ fi+ done <<< "$resource_names"+ [ -z "$chosen_customer" ] && die "No accessible customer matched name pattern: $arg_customer_name"+ fi++ if [ -n "$chosen_customer" ]; then+ : # already resolved; skip auto/interactive selection below+ elif [ "$customer_count" = "1" ]; thenlocal rn_single cid_single info_resp_single is_manager_singlern_single=$(printf '%s\n' "$resource_names" | head -n1)cid_single="${rn_single##customers/}"@@ -937,21 +978,64 @@ cmd_provision_google_ads() {fichosen_customer="$cid_single"else- # Walk accounts, find first non-manager. Manager accounts become login_customer_id.+ # Walk accounts: classify manager vs non-manager, capture first MCC as login_customer.+ local non_manager_ids=()while IFS= read -r rn; do[ -z "$rn" ] && continue- local cid info_resp is_manager+ local cid info_resp is_manager name_dcid="${rn##customers/}"info_resp=$(gads_get_customer_info "$cid" "$access_token" "$dev_token" 2>/dev/null || echo "{}")is_manager=$(printf '%s' "$info_resp" | jq -r '.results[0].customer.manager // false' 2>/dev/null)- if [ "$is_manager" = "true" ] && [ -z "$login_customer" ]; then- login_customer="$cid"- log " (MCC manager: $cid)"- elif [ "$is_manager" = "false" ] && [ -z "$chosen_customer" ]; then- chosen_customer="$cid"+ name_d=$(printf '%s' "$info_resp" | jq -r '.results[0].customer.descriptiveName // "(unknown)"' 2>/dev/null)+ if [ "$is_manager" = "true" ]; then+ [ -z "$login_customer" ] && login_customer="$cid"+ log " [manager] $cid — $name_d"+ else+ non_manager_ids+=("$cid")+ log " [account] $cid — $name_d"fidone <<< "$resource_names"- [ -z "$chosen_customer" ] && chosen_customer=$(printf '%s\n' "$resource_names" | head -n1 | sed 's#^customers/##')++ if [ "${#non_manager_ids[@]}" = "1" ]; then+ chosen_customer="${non_manager_ids[0]}"+ elif [ -t 0 ] && [ -t 2 ] && [ "$OPS_MARKETING_BACKGROUND" != "1" ]; then+ # Interactive: prompt Sam to pick by ID+ printf 'Enter customer ID to use: ' >&2+ local picked=""+ read -r picked </dev/tty+ if [ -n "$picked" ] && printf '%s\n' "$resource_names" | grep -qx "customers/${picked}"; then+ chosen_customer="$picked"+ else+ die "Invalid selection: $picked (not in accessible list)"+ fi+ else+ die "Multiple accessible customers and no --customer-id / --customer-name / prefs hint set. Re-run with --customer-id <id> or set marketing.projects.${project}.google_ads.customer_id_hint in prefs."+ fi+ fi++ # Hint/name resolution skips the walk that discovers MCC login_customer — infer it here.+ if [ -n "$chosen_customer" ] && [ -z "$login_customer" ]; then+ if [ "$customer_count" = "1" ]; then+ local info_hint_path is_manager_hint_path+ info_hint_path=$(gads_get_customer_info "$chosen_customer" "$access_token" "$dev_token" 2>/dev/null || echo "{}")+ is_manager_hint_path=$(printf '%s' "$info_hint_path" | jq -r '.results[0].customer.manager // false' 2>/dev/null)+ if [ "$is_manager_hint_path" = "true" ]; then+ login_customer="$chosen_customer"+ log " (sole accessible account is MCC manager: $chosen_customer)"+ fi+ else+ while IFS= read -r rn; do+ [ -z "$rn" ] && continue+ local cid_lc info_lc is_manager_lc+ cid_lc="${rn##customers/}"+ info_lc=$(gads_get_customer_info "$cid_lc" "$access_token" "$dev_token" 2>/dev/null || echo "{}")+ is_manager_lc=$(printf '%s' "$info_lc" | jq -r '.results[0].customer.manager // false' 2>/dev/null)+ if [ "$is_manager_lc" = "true" ]; then+ login_customer="$cid_lc"+ break+ fi+ done <<< "$resource_names"+ fifilog "Selected customer: $chosen_customer${login_customer:+ (login-customer-id: $login_customer)}"diff --git a/claude-ops/skills/ops-social-planner/lib/planner.mjs b/claude-ops/skills/ops-social-planner/lib/planner.mjsindex f5373382..34cd9d85 100644--- a/claude-ops/skills/ops-social-planner/lib/planner.mjs+++ b/claude-ops/skills/ops-social-planner/lib/planner.mjs@@ -9,16 +9,18 @@ import { fileURLToPath } from 'url';import crypto from 'crypto';const __dirname = path.dirname(fileURLToPath(import.meta.url));const HOME = os.homedir();-const PREFS_PATH = process.env.PREFS_PATH ||- path.join(HOME, '.claude/plugins/data/ops-ops-marketplace/preferences.json');-const OPS_DATA_DIR = process.env.OPS_DATA_DIR ||- path.join(HOME, '.claude/plugins/data/ops-ops-marketplace');+const PREFS_PATH =+ process.env.PREFS_PATH || path.join(HOME, '.claude/plugins/data/ops-ops-marketplace/preferences.json');+const OPS_DATA_DIR = process.env.OPS_DATA_DIR || path.join(HOME, '.claude/plugins/data/ops-ops-marketplace');const UI_DIR = path.join(__dirname, '..', 'ui');const OUT_DIR = path.join(OPS_DATA_DIR, 'social-planner');const args = process.argv.slice(2);const collectOnly = args.includes('--collect-only');-const cmd = (args[0] && !args[0].startsWith('-')) ? args[0] : 'all';-const flag = (n, d) => { const i = args.indexOf(n); return i >= 0 ? (args[i + 1] || true) : d; };+const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'all';+const flag = (n, d) => {+ const i = args.indexOf(n);+ return i >= 0 ? args[i + 1] || true : d;+};const PORT = Number(flag('--port', process.env.OPS_PLANNER_PORT || 7937));const OUT = flag('--out', path.join(OUT_DIR, 'state.json'));@@ -26,7 +28,8 @@ const OUT = flag('--out', path.join(OUT_DIR, 'state.json'));const readJSON = (p) => JSON.parse(fs.readFileSync(p, 'utf8'));const log = (...a) => console.error('[planner]', ...a);function resolveTypefullySocialSetId(p, prefs) {- if (p.typefully_social_set_id != null && String(p.typefully_social_set_id).trim() !== '') return String(p.typefully_social_set_id);+ if (p.typefully_social_set_id != null && String(p.typefully_social_set_id).trim() !== '')+ return String(p.typefully_social_set_id);const fromPrefs = prefs.typefully && prefs.typefully.default_social_set_id;if (fromPrefs != null && String(fromPrefs).trim() !== '') return String(fromPrefs);const cfgPath = path.join(HOME, '.config/typefully/config.json');@@ -35,7 +38,9 @@ function resolveTypefullySocialSetId(p, prefs) {const j = readJSON(cfgPath);const d = j.default_social_set ?? j.defaultSocialSet;if (d != null && String(d).trim() !== '') return String(d);- } catch { /* ignore */ }+ } catch {+ /* ignore */+ }return null;}const URL_RE = /(https?:\/\/[^\s)]+)/g;@@ -49,9 +54,15 @@ function resolveSecret(ref) {const [project, config, ...rest] = ref.slice(8).split('/');const name = rest.join('/');try {- return execSync(`doppler secrets get ${name} --project ${project} --config ${config} --plain`,- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;- } catch { return process.env[name] || null; }+ return (+ execSync(`doppler secrets get ${name} --project ${project} --config ${config} --plain`, {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ }).trim() || null+ );+ } catch {+ return process.env[name] || null;+ }}return process.env[ref] || ref; // raw env name or literal}@@ -60,25 +71,32 @@ function resolveSecret(ref) {function deriveRationale(channel, copy, scheduledAt) {const hour = new Date(scheduledAt).getUTCHours();const slot =- hour < 9 ? 'Morning authority slot — high feed reach before the workday (EU midday / US-east pre-open).' :- hour < 12 ? 'Late-morning build-in-public slot — steady weekday browsing.' :- hour < 14 ? 'Midday window — peak US-morning engagement.' :- hour < 17 ? 'Afternoon professional window — best for LinkedIn long-form.' :- 'Evening casual window — conversational/Threads-friendly.';- const norm = {- x: 'X: hook-first, thread if it earns it.',- linkedin: 'LinkedIn: long-form authority + soft CTA.',- threads: 'Threads: casual, conversational, low-polish.',- instagram: 'Instagram: visual-first, link-in-bio CTA.',- reddit: 'Reddit: value-first, no hard sell.',- youtube: 'YouTube: SEO title + descriptive copy.',- google_business: 'Google Business: local discovery, plain CTA.',- facebook: 'Facebook: brand page, broad reach.',- }[channel] || `${channel}: platform-native.`;+ hour < 9+ ? 'Morning authority slot — high feed reach before the workday (EU midday / US-east pre-open).'+ : hour < 12+ ? 'Late-morning build-in-public slot — steady weekday browsing.'+ : hour < 14+ ? 'Midday window — peak US-morning engagement.'+ : hour < 17+ ? 'Afternoon professional window — best for LinkedIn long-form.'+ : 'Evening casual window — conversational/Threads-friendly.';+ const norm =+ {+ x: 'X: hook-first, thread if it earns it.',+ linkedin: 'LinkedIn: long-form authority + soft CTA.',+ threads: 'Threads: casual, conversational, low-polish.',+ instagram: 'Instagram: visual-first, link-in-bio CTA.',+ reddit: 'Reddit: value-first, no hard sell.',+ youtube: 'YouTube: SEO title + descriptive copy.',+ google_business: 'Google Business: local discovery, plain CTA.',+ facebook: 'Facebook: brand page, broad reach.',+ }[channel] || `${channel}: platform-native.`;const t = (copy || '').toLowerCase();- const seq = /(almost here|this week|coming|👀|something worth)/.test(t) ? 'Pre-launch teaser — builds anticipation ahead of the drop.'- : /(it'?s here|is here|is live|now live|download|link in bio|on the app store)/.test(t) ? 'Launch beat — conversion-focused, drives the install.'- : 'Education/credibility beat — deepens trust between launch pushes.';+ const seq = /(almost here|this week|coming|👀|something worth)/.test(t)+ ? 'Pre-launch teaser — builds anticipation ahead of the drop.'+ : /(it'?s here|is here|is live|now live|download|link in bio|on the app store)/.test(t)+ ? 'Launch beat — conversion-focused, drives the install.'+ : 'Education/credibility beat — deepens trust between launch pushes.';return `${seq} ${slot} ${norm}`;}@@ -89,25 +107,36 @@ async function fetchTypefully(setId) {const key = readJSON(cfgPath).apiKey;const base = process.env.TYPEFULLY_API_BASE || 'https://api.typefully.com/v2';const H = { Authorization: `Bearer ${key}` };- const list = await fetch(`${base}/social-sets/${setId}/drafts?status=scheduled&limit=50&order_by=scheduled_date`, { headers: H });+ const list = await fetch(`${base}/social-sets/${setId}/drafts?status=scheduled&limit=50&order_by=scheduled_date`, {+ headers: H,+ });if (!list.ok) return { ok: false, reason: `HTTP ${list.status}`, items: [] };const drafts = (await list.json()).results || [];const items = [];for (const d of drafts) {let full = d;- try { const r = await fetch(`${base}/social-sets/${setId}/drafts/${d.id}?exclude_comment_markers=true`, { headers: H }); if (r.ok) full = await r.json(); } catch {}+ try {+ const r = await fetch(`${base}/social-sets/${setId}/drafts/${d.id}?exclude_comment_markers=true`, { headers: H });+ if (r.ok) full = await r.json();+ } catch {}const plats = full.platforms || {};for (const [channel, p] of Object.entries(plats)) {if (!p || !p.enabled) continue;- const posts = (p.posts || []).map(x => x.text).filter(Boolean);+ const posts = (p.posts || []).map((x) => x.text).filter(Boolean);if (!posts.length) continue;const copy = posts.join('\n\n———\n\n');items.push({- id: `tf-${d.id}-${channel}`, channel, kind: 'post',+ id: `tf-${d.id}-${channel}`,+ channel,+ kind: 'post',type: posts.length > 1 ? 'thread' : 'text',- scheduled_at: d.scheduled_date, copy, thread: posts.length > 1 ? posts : undefined,+ scheduled_at: d.scheduled_date,+ copy,+ thread: posts.length > 1 ? posts : undefined,rationale: deriveRationale(channel, copy, d.scheduled_date),- media: [], links: extractLinks(copy), char_count: copy.length,+ media: [],+ links: extractLinks(copy),+ char_count: copy.length,title: d.draft_title || null,source: { engine: 'typefully', ref: String(d.id), edit_url: d.private_url || null },});@@ -118,23 +147,43 @@ async function fetchTypefully(setId) {async function fetchUploadPost(profile, key) {if (!key) return { ok: false, reason: 'no api key', items: [] };- const r = await fetch('https://api.upload-post.com/api/uploadposts/schedule', { headers: { Authorization: `Apikey ${key}` } });+ const r = await fetch('https://api.upload-post.com/api/uploadposts/schedule', {+ headers: { Authorization: `Apikey ${key}` },+ });if (!r.ok) return { ok: false, reason: `HTTP ${r.status}`, items: [] };const data = await r.json();- const posts = (data.scheduled_posts || []).filter(p => !profile || p.profile_username === profile);- const items = posts.flatMap(p => (p.platforms || []).map(channel => {- const pc = (p.platform_content || {})[channel] || {};- const copy = [pc.title || p.title, pc.caption || p.caption, pc.description || p.description].filter(Boolean).join('\n\n');- const isVid = p.post_type === 'video';- return {- id: `up-${p.job_id}-${channel}`, channel, kind: 'post', type: p.post_type || 'photo',- scheduled_at: p.original_scheduled_str || p.scheduled_date, copy,- rationale: deriveRationale(channel, copy, p.original_scheduled_str || p.scheduled_date),- media: p.preview_url ? [{ type: isVid ? 'video' : 'image', url: p.preview_url, thumb: p.thumbnail_url || (isVid ? null : p.preview_url) }] : [],- links: extractLinks(copy), char_count: copy.length, title: null,- source: { engine: 'upload-post', ref: p.job_id },- };- }));+ const posts = (data.scheduled_posts || []).filter((p) => !profile || p.profile_username === profile);+ const items = posts.flatMap((p) =>+ (p.platforms || []).map((channel) => {+ const pc = (p.platform_content || {})[channel] || {};+ const copy = [pc.title || p.title, pc.caption || p.caption, pc.description || p.description]+ .filter(Boolean)+ .join('\n\n');+ const isVid = p.post_type === 'video';+ return {+ id: `up-${p.job_id}-${channel}`,+ channel,+ kind: 'post',+ type: p.post_type || 'photo',+ scheduled_at: p.original_scheduled_str || p.scheduled_date,+ copy,+ rationale: deriveRationale(channel, copy, p.original_scheduled_str || p.scheduled_date),+ media: p.preview_url+ ? [+ {+ type: isVid ? 'video' : 'image',+ url: p.preview_url,+ thumb: p.thumbnail_url || (isVid ? null : p.preview_url),+ },+ ]+ : [],+ links: extractLinks(copy),+ char_count: copy.length,+ title: null,+ source: { engine: 'upload-post', ref: p.job_id },+ };+ }),+ );return { ok: true, count: items.length, items };}@@ -149,28 +198,48 @@ async function fetchMetaAds(cfg) {const secret = resolveSecret(m.app_secret);const proof = secret ? crypto.createHmac('sha256', secret).update(token).digest('hex') : null;const u = new URL(`https://graph.facebook.com/v21.0/${adAccountId}/ads`);- u.searchParams.set('fields', 'name,effective_status,created_time,creative{title,body,thumbnail_url},adset{daily_budget,targeting{publisher_platforms}}');+ u.searchParams.set(+ 'fields',+ 'name,effective_status,created_time,creative{title,body,thumbnail_url},adset{daily_budget,targeting{publisher_platforms}}',+ );u.searchParams.set('limit', '50');u.searchParams.set('access_token', token);if (proof) u.searchParams.set('appsecret_proof', proof);let r;- try { r = await fetch(u, { signal: AbortSignal.timeout(15000) }); }- catch (e) { return { ok: false, reason: e.message, items: [] }; }- if (!r.ok) { let msg = `HTTP ${r.status}`; try { msg = (await r.json()).error?.message || msg; } catch {} return { ok: false, reason: msg, items: [] }; }+ try {+ r = await fetch(u, { signal: AbortSignal.timeout(15000) });+ } catch (e) {+ return { ok: false, reason: e.message, items: [] };+ }+ if (!r.ok) {+ let msg = `HTTP ${r.status}`;+ try {+ msg = (await r.json()).error?.message || msg;+ } catch {}+ return { ok: false, reason: msg, items: [] };+ }const ads = (await r.json()).data || [];- const items = ads.map(a => {+ const items = ads.map((a) => {const cr = a.creative || {};const pp = a.adset?.targeting?.publisher_platforms || [];- let channel = pp.includes('instagram') && !pp.includes('facebook') ? 'instagram' : (pp[0] || 'facebook');+ let channel = pp.includes('instagram') && !pp.includes('facebook') ? 'instagram' : pp[0] || 'facebook';if (channel === 'audience_network' || channel === 'messenger') channel = 'meta';const budget = a.adset?.daily_budget ? ' · $' + (a.adset.daily_budget / 100).toFixed(0) + '/day' : '';const copy = [cr.title, cr.body].filter(Boolean).join('\n\n') || a.name;return {- id: 'meta-' + a.id, channel, kind: 'ad', type: 'ad', scheduled_at: a.created_time || null,- ad_status: a.effective_status, copy,+ id: 'meta-' + a.id,+ channel,+ kind: 'ad',+ type: 'ad',+ scheduled_at: a.created_time || null,+ ad_status: a.effective_status,+ copy,rationale: 'Meta ad · ' + a.effective_status + budget + ' · placement: ' + (pp.join(', ') || 'auto') + '.',media: cr.thumbnail_url ? [{ type: 'image', url: cr.thumbnail_url, thumb: cr.thumbnail_url }] : [],- links: [], char_count: copy.length, title: a.name, source: { engine: 'meta-ads', ref: a.id },+ links: [],+ char_count: copy.length,+ title: a.name,+ source: { engine: 'meta-ads', ref: a.id },};});return { ok: true, count: items.length, items };@@ -180,44 +249,80 @@ async function fetchGoogleAds(cfg) {if (!g.customer_id) return { ok: false, reason: 'not configured', items: [] };const custResolved = resolveSecret(g.customer_id);if (!custResolved) return { ok: false, reason: 'not configured', items: [] };- const devToken = resolveSecret(g.developer_token), cid = resolveSecret(g.client_id),- csec = resolveSecret(g.client_secret), refresh = resolveSecret(g.refresh_token);+ const devToken = resolveSecret(g.developer_token),+ cid = resolveSecret(g.client_id),+ csec = resolveSecret(g.client_secret),+ refresh = resolveSecret(g.refresh_token);if (!devToken || !cid || !csec || !refresh) return { ok: false, reason: 'missing oauth creds', items: [] };let access;try {const tr = await fetch('https://oauth2.googleapis.com/token', {- method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },- body: new URLSearchParams({ client_id: cid, client_secret: csec, refresh_token: refresh, grant_type: 'refresh_token' }),+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ client_id: cid,+ client_secret: csec,+ refresh_token: refresh,+ grant_type: 'refresh_token',+ }),signal: AbortSignal.timeout(15000),});if (!tr.ok) return { ok: false, reason: 'oauth HTTP ' + tr.status, items: [] };access = (await tr.json()).access_token;- } catch (e) { return { ok: false, reason: e.message, items: [] }; }+ } catch (e) {+ return { ok: false, reason: e.message, items: [] };+ }const cust = String(custResolved).replace(/-/g, '');- const headers = { Authorization: 'Bearer ' + access, 'developer-token': devToken, 'Content-Type': 'application/json' };+ const headers = {+ Authorization: 'Bearer ' + access,+ 'developer-token': devToken,+ 'Content-Type': 'application/json',+ };if (g.login_customer_id) {const loginCust = resolveSecret(g.login_customer_id);if (loginCust) headers['login-customer-id'] = String(loginCust).replace(/-/g, '');}- const query = "SELECT campaign.name, campaign.status, ad_group_ad.ad.responsive_search_ad.headlines, ad_group_ad.ad.final_urls FROM ad_group_ad WHERE campaign.status != 'REMOVED' LIMIT 50";+ const query =+ "SELECT campaign.name, campaign.status, ad_group_ad.ad.responsive_search_ad.headlines, ad_group_ad.ad.final_urls FROM ad_group_ad WHERE campaign.status != 'REMOVED' LIMIT 50";let rows = [];try {const r = await fetch('https://googleads.googleapis.com/v20/customers/' + cust + '/googleAds:searchStream', {- method: 'POST', headers, body: JSON.stringify({ query }), signal: AbortSignal.timeout(20000),+ method: 'POST',+ headers,+ body: JSON.stringify({ query }),+ signal: AbortSignal.timeout(20000),});- if (!r.ok) { let msg = 'HTTP ' + r.status; try { const j = await r.json(); msg = (j.error?.message || JSON.stringify(j)).slice(0, 160); } catch {} return { ok: false, reason: msg, items: [] }; }+ if (!r.ok) {+ let msg = 'HTTP ' + r.status;+ try {+ const j = await r.json();+ msg = (j.error?.message || JSON.stringify(j)).slice(0, 160);+ } catch {}+ return { ok: false, reason: msg, items: [] };+ }const data = await r.json();- rows = (Array.isArray(data) ? data : [data]).flatMap(b => b.results || []);- } catch (e) { return { ok: false, reason: e.message, items: [] }; }+ rows = (Array.isArray(data) ? data : [data]).flatMap((b) => b.results || []);+ } catch (e) {+ return { ok: false, reason: e.message, items: [] };+ }const items = rows.map((row, i) => {const ad = row.adGroupAd?.ad || {};- const heads = (ad.responsiveSearchAd?.headlines || []).map(h => h.text).filter(Boolean);+ const heads = (ad.responsiveSearchAd?.headlines || []).map((h) => h.text).filter(Boolean);const copy = heads.join(' · ') || row.campaign?.name || 'ad';return {- id: 'gads-' + i, channel: 'google-search', kind: 'ad', type: 'ad', scheduled_at: null,- ad_status: row.campaign?.status, copy,+ id: 'gads-' + i,+ channel: 'google-search',+ kind: 'ad',+ type: 'ad',+ scheduled_at: null,+ ad_status: row.campaign?.status,+ copy,rationale: 'Google Ads · "' + (row.campaign?.name || '') + '" · ' + (row.campaign?.status || '') + '.',- media: [], links: ad.finalUrls || [], char_count: copy.length, title: row.campaign?.name, source: { engine: 'google-ads', ref: String(i) },+ media: [],+ links: ad.finalUrls || [],+ char_count: copy.length,+ title: row.campaign?.name,+ source: { engine: 'google-ads', ref: String(i) },};});return { ok: true, count: items.length, items };@@ -229,7 +334,13 @@ async function collect() {const mk = prefs.marketing || {};const engineStatus = {};const identities = [];- const note = (eng, res) => { const s = engineStatus[eng] || { ok: false, count: 0 }; s.ok = s.ok || res.ok; s.count += res.count || 0; if (res.reason) s.reason = res.reason; engineStatus[eng] = s; };+ const note = (eng, res) => {+ const s = engineStatus[eng] || { ok: false, count: 0 };+ s.ok = s.ok || res.ok;+ s.count += res.count || 0;+ if (res.reason) s.reason = res.reason;+ engineStatus[eng] = s;+ };// personal identitiesfor (const [id, p] of Object.entries((mk.social_identities && mk.social_identities.personal) || {})) {@@ -241,13 +352,21 @@ async function collect() {}const engKey = engine === 'typefully' ? 'typefully' : engine;note(engKey, res);- identities.push({ id, label: (p.aka && p.aka.join(' / ')) || id, kind: 'personal', engine,- status: res.ok ? 'ok' : (res.reason || 'error'), channels: [...new Set(res.items.map(i => i.channel))].sort(), items: res.items });+ identities.push({+ id,+ label: (p.aka && p.aka.join(' / ')) || id,+ kind: 'personal',+ engine,+ status: res.ok ? 'ok' : res.reason || 'error',+ channels: [...new Set(res.items.map((i) => i.channel))].sort(),+ items: res.items,+ });}// project brands — organic posts (social.engine) + paid ads (meta/google, independent of organic engine)for (const [proj, cfg] of Object.entries(mk.projects || {})) {- const s = cfg.social || {}; const eng = (s.engine && s.engine.primary) || null;+ const s = cfg.social || {};+ const eng = (s.engine && s.engine.primary) || null;let postRes = { ok: false, items: [], status: s.engine && s.engine.status };if (eng === 'upload-post') {const up = s.engine.upload_post || {};@@ -256,19 +375,32 @@ async function collect() {postRes = await fetchTypefully(s.typefully_social_set_id);}if (eng) note(eng, postRes);- const meta = await fetchMetaAds(cfg); if (cfg.meta && cfg.meta.ad_account_id) note('meta-ads', meta);- const gads = await fetchGoogleAds(cfg); if (cfg.google_ads && cfg.google_ads.customer_id) note('google-ads', gads);+ const meta = await fetchMetaAds(cfg);+ if (cfg.meta && cfg.meta.ad_account_id) note('meta-ads', meta);+ const gads = await fetchGoogleAds(cfg);+ if (cfg.google_ads && cfg.google_ads.customer_id) note('google-ads', gads);const items = [...postRes.items, ...meta.items, ...gads.items];identities.push({- id: proj, label: proj, kind: 'project', engine: eng,- status: eng ? (postRes.ok ? 'ok' : (postRes.status || postRes.reason || 'error')) : 'unprovisioned',- ad_status: { 'meta-ads': meta.ok ? String(meta.count) : (meta.reason || '-'), 'google-ads': gads.ok ? String(gads.count) : (gads.reason || '-') },- channels: [...new Set(items.map(i => i.channel))].sort(), items,+ id: proj,+ label: proj,+ kind: 'project',+ engine: eng,+ status: eng ? (postRes.ok ? 'ok' : postRes.status || postRes.reason || 'error') : 'unprovisioned',+ ad_status: {+ 'meta-ads': meta.ok ? String(meta.count) : meta.reason || '-',+ 'google-ads': gads.ok ? String(gads.count) : gads.reason || '-',+ },+ channels: [...new Set(items.map((i) => i.channel))].sort(),+ items,});}- const state = { generated_at: new Date().toISOString(), timezone: prefs.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,- engine_status: engineStatus, identities };+ const state = {+ generated_at: new Date().toISOString(),+ timezone: prefs.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,+ engine_status: engineStatus,+ identities,+ };fs.mkdirSync(path.dirname(OUT), { recursive: true });fs.writeFileSync(OUT, JSON.stringify(state, null, 2));const total = identities.reduce((n, i) => n + i.items.length, 0);@@ -277,7 +409,13 @@ async function collect() {}/* ---------- serve ---------- */-const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml' };+const MIME = {+ '.html': 'text/html',+ '.js': 'text/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.svg': 'image/svg+xml',+};function serve() {const srv = http.createServer((req, res) => {let url = decodeURIComponent(req.url.split('?')[0]);@@ -286,11 +424,20 @@ function serve() {if (url === '/state.json') {file = fs.existsSync(OUT) ? OUT : path.join(UI_DIR, 'state.sample.json');} else {- const rel = path.normalize(url).replace(/^(\.\.[/\\])+/, '').replace(/^[/\\]+/, '');+ const rel = path+ .normalize(url)+ .replace(/^(\.\.[/\\])+/, '')+ .replace(/^[/\\]+/, '');file = path.join(UI_DIR, rel);}- if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { res.writeHead(404); return res.end('not found'); }- res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' });+ if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {+ res.writeHead(404);+ return res.end('not found');+ }+ res.writeHead(200, {+ 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream',+ 'Cache-Control': 'no-store',+ });fs.createReadStream(file).pipe(res);});srv.listen(PORT, '127.0.0.1', () => {@@ -298,7 +445,9 @@ function serve() {log(`serving ${u}`);console.log(u);if (cmd !== 'serve' && flag('--no-open', false) === false) {- try { spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [u], { stdio: 'ignore', detached: true }).unref(); } catch {}+ try {+ spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [u], { stdio: 'ignore', detached: true }).unref();+ } catch {}}});}@@ -308,5 +457,8 @@ function serve() {if (cmd === 'collect' || cmd === 'all' || collectOnly) await collect();if (!collectOnly && (cmd === 'serve' || cmd === 'open' || cmd === 'all')) serve();else if (!collectOnly) process.exit(0);- } catch (e) { log('ERROR', e.message); process.exit(1); }+ } catch (e) {+ log('ERROR', e.message);+ process.exit(1);+ }})();diff --git a/claude-ops/skills/ops-social-planner/ui/app.js b/claude-ops/skills/ops-social-planner/ui/app.jsindex 68257b29..84a0a08b 100644--- a/claude-ops/skills/ops-social-planner/ui/app.js+++ b/claude-ops/skills/ops-social-planner/ui/app.js@@ -1,116 +1,341 @@// ops-social-planner UI — fetch normalized state, render per identity → channel → time.// Zero deps. State lives in the URL hash so views are shareable.const $ = (s, r = document) => r.querySelector(s);-const el = (t, p = {}, ...kids) => { const n = Object.assign(document.createElement(t), p); for (const k of kids) n.append(k?.nodeType ? k : document.createTextNode(k ?? '')); return n; };-const CH_ICON = { x:'𝕏', twitter:'𝕏', linkedin:'in', threads:'@', instagram:'◎', facebook:'f', reddit:'r/', youtube:'▶', google_business:'📍', tiktok:'♪', bluesky:'🦋', mastodon:'🐘' };-const fmtDate = (iso, tz) => { const d = new Date(iso); return { date: d.toLocaleDateString(undefined,{weekday:'short',month:'short',day:'numeric',timeZone:tz}), time: d.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit',timeZone:tz}), rel: relTime(d) }; };-function relTime(d){ const s=(d-Date.now())/1000, a=Math.abs(s), f=new Intl.RelativeTimeFormat(undefined,{numeric:'auto'}); if(a<3600)return f.format(Math.round(s/60),'minute'); if(a<86400)return f.format(Math.round(s/3600),'hour'); return f.format(Math.round(s/86400),'day'); }+const el = (t, p = {}, ...kids) => {+ const n = Object.assign(document.createElement(t), p);+ for (const k of kids) n.append(k?.nodeType ? k : document.createTextNode(k ?? ''));+ return n;+};+const CH_ICON = {+ x: '𝕏',+ twitter: '𝕏',+ linkedin: 'in',+ threads: '@',+ instagram: '◎',+ facebook: 'f',+ reddit: 'r/',+ youtube: '▶',+ google_business: '📍',+ tiktok: '♪',+ bluesky: '🦋',+ mastodon: '🐘',+};+const fmtDate = (iso, tz) => {+ const d = new Date(iso);+ return {+ date: d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', timeZone: tz }),+ time: d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', timeZone: tz }),+ rel: relTime(d),+ };+};+function relTime(d) {+ const s = (d - Date.now()) / 1000,+ a = Math.abs(s),+ f = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });+ if (a < 3600) return f.format(Math.round(s / 60), 'minute');+ if (a < 86400) return f.format(Math.round(s / 3600), 'hour');+ return f.format(Math.round(s / 86400), 'day');+}-const state = { data:null, id:null, view:'posts', channel:null, q:'' };+const state = { data: null, id: null, view: 'posts', channel: null, q: '' };-function readHash(){ const h=new URLSearchParams(location.hash.slice(1)); state.id=h.get('id')||state.id; state.view=h.get('view')||state.view; state.channel=h.get('channel')||null; state.q=h.get('q')||''; }-function writeHash(){ const h=new URLSearchParams(); if(state.id)h.set('id',state.id); h.set('view',state.view); if(state.channel)h.set('channel',state.channel); if(state.q)h.set('q',state.q); history.replaceState(null,'',`#${h}`); }+function readHash() {+ const h = new URLSearchParams(location.hash.slice(1));+ state.id = h.get('id') || state.id;+ state.view = h.get('view') || state.view;+ state.channel = h.get('channel') || null;+ state.q = h.get('q') || '';+}+function writeHash() {+ const h = new URLSearchParams();+ if (state.id) h.set('id', state.id);+ h.set('view', state.view);+ if (state.channel) h.set('channel', state.channel);+ if (state.q) h.set('q', state.q);+ history.replaceState(null, '', `#${h}`);+}-async function load(){- const r = await fetch('./state.json',{cache:'no-store'});+async function load() {+ const r = await fetch('./state.json', { cache: 'no-store' });state.data = await r.json();- const ids = state.data.identities||[];- if(!state.id || !ids.find(i=>i.id===state.id)) state.id = (ids.find(i=>i.items.length)||ids[0]||{}).id;- renderMeta(); renderIdentities(); renderChannels(); render();+ const ids = state.data.identities || [];+ if (!state.id || !ids.find((i) => i.id === state.id)) state.id = (ids.find((i) => i.items.length) || ids[0] || {}).id;+ renderMeta();+ renderIdentities();+ renderChannels();+ render();}-function curIdentity(){ return (state.data.identities||[]).find(i=>i.id===state.id) || {items:[]}; }-function visibleItems(){- let it = (curIdentity().items||[]).filter(i => (i.kind||'post') === (state.view==='ads'?'ad':'post'));- if(state.channel) it = it.filter(i=>i.channel===state.channel);- if(state.q){ const q=state.q.toLowerCase(); it = it.filter(i => (i.copy||'').toLowerCase().includes(q) || (i.title||'').toLowerCase().includes(q)); }- return it.sort((a,b)=>new Date(a.scheduled_at)-new Date(b.scheduled_at));+function curIdentity() {+ return (state.data.identities || []).find((i) => i.id === state.id) || { items: [] };+}+function visibleItems() {+ let it = (curIdentity().items || []).filter((i) => (i.kind || 'post') === (state.view === 'ads' ? 'ad' : 'post'));+ if (state.channel) it = it.filter((i) => i.channel === state.channel);+ if (state.q) {+ const q = state.q.toLowerCase();+ it = it.filter((i) => (i.copy || '').toLowerCase().includes(q) || (i.title || '').toLowerCase().includes(q));+ }+ return it.sort((a, b) => new Date(a.scheduled_at) - new Date(b.scheduled_at));}-function renderMeta(){- const d=state.data; $('#sub').textContent = `${(d.identities||[]).length} accounts · ${d.timezone||''}`;+function renderMeta() {+ const d = state.data;+ $('#sub').textContent = `${(d.identities || []).length} accounts · ${d.timezone || ''}`;const gen = d.generated_at ? `updated ${relTime(new Date(d.generated_at))}` : '';- const es = Object.entries(d.engine_status||{}).map(([k,v])=>{ const cls=v.ok?'ok':(v.reason==='hook-pending'?'idle':'bad'); return el('span',{},Object.assign(document.createElement('span'),{className:`dot ${cls}`}), `${k}${v.reason&&!v.ok?` (${v.reason})`:''}`); });- const m=$('#meta'); m.innerHTML=''; es.forEach(x=>m.append(x)); if(gen) m.append(el('span',{},gen));+ const es = Object.entries(d.engine_status || {}).map(([k, v]) => {+ const cls = v.ok ? 'ok' : v.reason === 'hook-pending' ? 'idle' : 'bad';+ return el(+ 'span',+ {},+ Object.assign(document.createElement('span'), { className: `dot ${cls}` }),+ `${k}${v.reason && !v.ok ? ` (${v.reason})` : ''}`,+ );+ });+ const m = $('#meta');+ m.innerHTML = '';+ es.forEach((x) => m.append(x));+ if (gen) m.append(el('span', {}, gen));}-function renderIdentities(){- const box=$('#identities'); box.innerHTML='';- for(const i of state.data.identities||[]){- const b=el('button',{onclick:()=>{state.id=i.id; state.channel=null; writeHash(); renderIdentities(); renderChannels(); render();}});- b.setAttribute('aria-pressed', i.id===state.id);- b.append(el('span',{className:`kind-tag kind-${i.kind||'project'}`}, i.kind==='personal'?'personal':'brand'), i.label);- b.append(el('span',{className:'pill'}, String(i.items.length)));+function renderIdentities() {+ const box = $('#identities');+ box.innerHTML = '';+ for (const i of state.data.identities || []) {+ const b = el('button', {+ onclick: () => {+ state.id = i.id;+ state.channel = null;+ writeHash();+ renderIdentities();+ renderChannels();+ render();+ },+ });+ b.setAttribute('aria-pressed', i.id === state.id);+ b.append(+ el('span', { className: `kind-tag kind-${i.kind || 'project'}` }, i.kind === 'personal' ? 'personal' : 'brand'),+ i.label,+ );+ b.append(el('span', { className: 'pill' }, String(i.items.length)));box.append(b);}- const posts=(curIdentity().items||[]).filter(i=>(i.kind||'post')==='post').length;- const ads=(curIdentity().items||[]).filter(i=>i.kind==='ad').length;- $('#n-posts').textContent=posts; $('#n-ads').textContent=ads;+ const posts = (curIdentity().items || []).filter((i) => (i.kind || 'post') === 'post').length;+ const ads = (curIdentity().items || []).filter((i) => i.kind === 'ad').length;+ $('#n-posts').textContent = posts;+ $('#n-ads').textContent = ads;}-function renderChannels(){- const box=$('#channels'); box.innerHTML='';- const items=(curIdentity().items||[]).filter(i=>(i.kind||'post')===(state.view==='ads'?'ad':'post'));- const counts={}; items.forEach(i=>counts[i.channel]=(counts[i.channel]||0)+1);- const all=el('button',{className:'chip',onclick:()=>{state.channel=null;writeHash();renderChannels();render();}}); all.setAttribute('aria-pressed',!state.channel); all.append('All ', el('span',{className:'n'},String(items.length)));+function renderChannels() {+ const box = $('#channels');+ box.innerHTML = '';+ const items = (curIdentity().items || []).filter(+ (i) => (i.kind || 'post') === (state.view === 'ads' ? 'ad' : 'post'),+ );+ const counts = {};+ items.forEach((i) => (counts[i.channel] = (counts[i.channel] || 0) + 1));+ const all = el('button', {+ className: 'chip',+ onclick: () => {+ state.channel = null;+ writeHash();+ renderChannels();+ render();+ },+ });+ all.setAttribute('aria-pressed', !state.channel);+ all.append('All ', el('span', { className: 'n' }, String(items.length)));box.append(all);- for(const ch of Object.keys(counts).sort()){- const c=el('button',{className:'chip',onclick:()=>{state.channel=ch;writeHash();renderChannels();render();}}); c.setAttribute('aria-pressed',state.channel===ch);- c.append(el('span',{},CH_ICON[ch]||'•'),' ',ch.replace('_',' '),' ',el('span',{className:'n'},String(counts[ch]))); box.append(c);+ for (const ch of Object.keys(counts).sort()) {+ const c = el('button', {+ className: 'chip',+ onclick: () => {+ state.channel = ch;+ writeHash();+ renderChannels();+ render();+ },+ });+ c.setAttribute('aria-pressed', state.channel === ch);+ c.append(+ el('span', {}, CH_ICON[ch] || '•'),+ ' ',+ ch.replace('_', ' '),+ ' ',+ el('span', { className: 'n' }, String(counts[ch])),+ );+ box.append(c);}}-function card(i,tz){- const c=el('div',{className:'card'});- const w=i.scheduled_at?fmtDate(i.scheduled_at,tz):null;- const when=el('div',{className:'when'}, el('span',{className:'date'}, w?w.date:(i.ad_status||'active')), el('span',{className:'rel'}, w?`${w.time} · ${w.rel}`:'ongoing'), el('span',{className:`badge ${i.kind==='ad'?'video':(i.type||'')}`}, i.kind==='ad'?(i.ad_status||'ad'):(i.type||'post')));+function card(i, tz) {+ const c = el('div', { className: 'card' });+ const w = i.scheduled_at ? fmtDate(i.scheduled_at, tz) : null;+ const when = el(+ 'div',+ { className: 'when' },+ el('span', { className: 'date' }, w ? w.date : i.ad_status || 'active'),+ el('span', { className: 'rel' }, w ? `${w.time} · ${w.rel}` : 'ongoing'),+ el(+ 'span',+ { className: `badge ${i.kind === 'ad' ? 'video' : i.type || ''}` },+ i.kind === 'ad' ? i.ad_status || 'ad' : i.type || 'post',+ ),+ );c.append(when);- if(i.title) c.append(el('div',{className:'title'}, i.title));- if(i.media&&i.media.length){ const m=i.media[0]; const md=el('div',{className:'media'}); if(m.thumb||m.url) md.append(el('img',{src:m.thumb||m.url,loading:'lazy',alt:''})); if(m.type==='video') md.append(el('span',{className:'vid-badge'},'▶ video')); c.append(md); }- const copy=el('div',{className:'copy'}, i.copy||''); c.append(copy);- requestAnimationFrame(()=>{ if(copy.scrollHeight>copy.clientHeight+4){ copy.classList.add('clamped'); const more=el('button',{className:'more'},'Show more'); more.onclick=()=>{const e=copy.classList.toggle('expanded'); more.textContent=e?'Show less':'Show more';}; copy.after(more);} });- if(i.rationale) c.append(el('div',{className:'rationale'}, el('b',{},'Why this slot — '), i.rationale));- if(i.links&&i.links.length){ const lk=el('div',{className:'links'}); i.links.forEach(u=>lk.append(el('a',{className:'link-chip',href:u,target:'_blank',rel:'noopener'},u.replace(/^https?:\/\//,'')))); c.append(lk); }- const src=(i.source&&i.source.engine)||i.engine||'';- const foot=el('div',{className:'foot'}, el('span',{className:'src'},src));- if(i.source&&i.source.edit_url) foot.append(el('a',{href:i.source.edit_url,target:'_blank',rel:'noopener'},'open'));- foot.append(el('span',{className:'cc'}, `${i.char_count||(i.copy||'').length} chars`));- c.append(foot); return c;+ if (i.title) c.append(el('div', { className: 'title' }, i.title));+ if (i.media && i.media.length) {+ const m = i.media[0];+ const md = el('div', { className: 'media' });+ if (m.thumb || m.url) md.append(el('img', { src: m.thumb || m.url, loading: 'lazy', alt: '' }));+ if (m.type === 'video') md.append(el('span', { className: 'vid-badge' }, '▶ video'));+ c.append(md);+ }+ const copy = el('div', { className: 'copy' }, i.copy || '');+ c.append(copy);+ requestAnimationFrame(() => {+ if (copy.scrollHeight > copy.clientHeight + 4) {+ copy.classList.add('clamped');+ const more = el('button', { className: 'more' }, 'Show more');+ more.onclick = () => {+ const e = copy.classList.toggle('expanded');+ more.textContent = e ? 'Show less' : 'Show more';+ };+ copy.after(more);+ }+ });+ if (i.rationale) c.append(el('div', { className: 'rationale' }, el('b', {}, 'Why this slot — '), i.rationale));+ if (i.links && i.links.length) {+ const lk = el('div', { className: 'links' });+ i.links.forEach((u) =>+ lk.append(+ el('a', { className: 'link-chip', href: u, target: '_blank', rel: 'noopener' }, u.replace(/^https?:\/\//, '')),+ ),+ );+ c.append(lk);+ }+ const src = (i.source && i.source.engine) || i.engine || '';+ const foot = el('div', { className: 'foot' }, el('span', { className: 'src' }, src));+ if (i.source && i.source.edit_url)+ foot.append(el('a', { href: i.source.edit_url, target: '_blank', rel: 'noopener' }, 'open'));+ foot.append(el('span', { className: 'cc' }, `${i.char_count || (i.copy || '').length} chars`));+ c.append(foot);+ return c;}-function render(){+function render() {writeHash();- for(const b of $('#views').children) b.setAttribute('aria-pressed', b.dataset.view===state.view);- const board=$('#board'); board.innerHTML='';- const ident=curIdentity(), tz=state.data.timezone;- if(state.view==='ads'){- if(ident.status==='unprovisioned'){ board.append(stateMsg('🔒','Fail-closed — no engine registered',`${ident.label} has no social publishing engine. It will not post until one is registered (own upload-post profile or first-party Meta Graph).`)); return; }- const st=state.data.engine_status||{}; const pend=ident.engine && (st[ident.engine]||{}).reason==='hook-pending';- const adsItems=visibleItems();- if(!adsItems.length){- if(state.q||state.channel){ board.append(stateMsg('📣','Nothing here',state.q?'No ads match your search.':'No ads match this channel.')); return; }- board.append(stateMsg('📣', ident.items.some(i=>i.kind==='ad')?'':'No ads collected', pend?'Ad collectors (Meta / Google Ads) are scaffolded — the live fetch hook is pending. Posts are fully wired today.':'No paid campaigns for this account.'));+ for (const b of $('#views').children) b.setAttribute('aria-pressed', b.dataset.view === state.view);+ const board = $('#board');+ board.innerHTML = '';+ const ident = curIdentity(),+ tz = state.data.timezone;+ if (state.view === 'ads') {+ if (ident.status === 'unprovisioned') {+ board.append(+ stateMsg(+ '🔒',+ 'Fail-closed — no engine registered',+ `${ident.label} has no social publishing engine. It will not post until one is registered (own upload-post profile or first-party Meta Graph).`,+ ),+ );+ return;+ }+ const st = state.data.engine_status || {};+ const pend = ident.engine && (st[ident.engine] || {}).reason === 'hook-pending';+ const adsItems = visibleItems();+ if (!adsItems.length) {+ if (state.q || state.channel) {+ board.append(+ stateMsg('📣', 'Nothing here', state.q ? 'No ads match your search.' : 'No ads match this channel.'),+ );+ return;+ }+ board.append(+ stateMsg(+ '📣',+ ident.items.some((i) => i.kind === 'ad') ? '' : 'No ads collected',+ pend+ ? 'Ad collectors (Meta / Google Ads) are scaffolded — the live fetch hook is pending. Posts are fully wired today.'+ : 'No paid campaigns for this account.',+ ),+ );return;}}- if(state.view!=='ads' && ident.status==='unprovisioned'){ board.append(stateMsg('🔒','Fail-closed — no engine registered',`${ident.label} has no social publishing engine. It will not post until one is registered (own upload-post profile or first-party Meta Graph).`)); return; }- const items=visibleItems();- if(!items.length){ board.append(stateMsg('🗓️','Nothing scheduled here',state.q?'No posts match your search.':'No scheduled posts for this view.')); return; }- const byCh={}; items.forEach(i=>(byCh[i.channel]=byCh[i.channel]||[]).push(i));+ if (state.view !== 'ads' && ident.status === 'unprovisioned') {+ board.append(+ stateMsg(+ '🔒',+ 'Fail-closed — no engine registered',+ `${ident.label} has no social publishing engine. It will not post until one is registered (own upload-post profile or first-party Meta Graph).`,+ ),+ );+ return;+ }+ const items = visibleItems();+ if (!items.length) {+ board.append(+ stateMsg(+ '🗓️',+ 'Nothing scheduled here',+ state.q ? 'No posts match your search.' : 'No scheduled posts for this view.',+ ),+ );+ return;+ }+ const byCh = {};+ items.forEach((i) => (byCh[i.channel] = byCh[i.channel] || []).push(i));const order = state.channel ? [state.channel] : Object.keys(byCh).sort();- for(const ch of order){- const col=el('div',{className:'col'});- col.append(el('div',{className:'col-head'}, el('span',{className:'ch-icon'},CH_ICON[ch]||'•'), el('span',{className:'ch-name'},ch.replace('_',' ')), el('span',{className:'ch-count'},`${byCh[ch].length}`)));- const body=el('div',{className:'col-body'}); byCh[ch].forEach(i=>body.append(card(i,tz))); col.append(body); board.append(col);+ for (const ch of order) {+ const col = el('div', { className: 'col' });+ col.append(+ el(+ 'div',+ { className: 'col-head' },+ el('span', { className: 'ch-icon' }, CH_ICON[ch] || '•'),+ el('span', { className: 'ch-name' }, ch.replace('_', ' ')),+ el('span', { className: 'ch-count' }, `${byCh[ch].length}`),+ ),+ );+ const body = el('div', { className: 'col-body' });+ byCh[ch].forEach((i) => body.append(card(i, tz)));+ col.append(body);+ board.append(col);}}-function stateMsg(big,h,p){ return el('div',{className:'state-msg'}, el('div',{className:'big'},big), el('h2',{},h), el('p',{},p)); }+function stateMsg(big, h, p) {+ return el('div', { className: 'state-msg' }, el('div', { className: 'big' }, big), el('h2', {}, h), el('p', {}, p));+}// theme-const themeKey='ops-planner-theme';-function applyTheme(t){ document.documentElement.dataset.theme=t; localStorage.setItem(themeKey,t); }-$('#theme').onclick=()=>applyTheme(document.documentElement.dataset.theme==='dark'?'light':'dark');-applyTheme(localStorage.getItem(themeKey)|| (matchMedia('(prefers-color-scheme: light)').matches?'light':'dark'));-$('#refresh').onclick=()=>load();-$('#search').oninput=e=>{state.q=e.target.value; render();};-for(const b of $('#views').children) b.onclick=()=>{state.view=b.dataset.view; state.channel=null; renderIdentities(); renderChannels(); render();};+const themeKey = 'ops-planner-theme';+function applyTheme(t) {+ document.documentElement.dataset.theme = t;+ localStorage.setItem(themeKey, t);+}+$('#theme').onclick = () => applyTheme(document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark');+applyTheme(localStorage.getItem(themeKey) || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));+$('#refresh').onclick = () => load();+$('#search').oninput = (e) => {+ state.q = e.target.value;+ render();+};+for (const b of $('#views').children)+ b.onclick = () => {+ state.view = b.dataset.view;+ state.channel = null;+ renderIdentities();+ renderChannels();+ render();+ };-readHash(); $('#search').value=state.q;-addEventListener('hashchange',()=>{ const prev=state.q; readHash(); if(state.q!==prev)$('#search').value=state.q; renderIdentities(); renderChannels(); render(); });-load().catch(e=>{ $('#board').append(stateMsg('⚠️','Could not load state',String(e.message))); });+readHash();+$('#search').value = state.q;+addEventListener('hashchange', () => {+ const prev = state.q;+ readHash();+ if (state.q !== prev) $('#search').value = state.q;+ renderIdentities();+ renderChannels();+ render();+});+load().catch((e) => {+ $('#board').append(stateMsg('⚠️', 'Could not load state', String(e.message)));+});diff --git a/claude-ops/skills/ops-social-planner/ui/state.sample.json b/claude-ops/skills/ops-social-planner/ui/state.sample.jsonindex f7398dc5..ed9cd306 100644--- a/claude-ops/skills/ops-social-planner/ui/state.sample.json+++ b/claude-ops/skills/ops-social-planner/ui/state.sample.json@@ -9,27 +9,138 @@},"identities": [{- "id": "founder", "label": "Founder (personal)", "kind": "personal", "engine": "typefully", "status": "ok",+ "id": "founder",+ "label": "Founder (personal)",+ "kind": "personal",+ "engine": "typefully",+ "status": "ok","channels": ["linkedin", "threads", "x"],"items": [- { "id":"s1","channel":"x","kind":"post","type":"text","scheduled_at":"2026-01-02T07:00:00Z","title":"Build-in-public note","copy":"shipped a thing today. the hard part was never the code — it was deciding what to leave out.","rationale":"Education/credibility beat. Morning authority slot. X: hook-first.","media":[],"links":[],"char_count":98,"source":{"engine":"typefully","ref":"0","edit_url":"https://example.com/"} },- { "id":"s2","channel":"linkedin","kind":"post","type":"text","scheduled_at":"2026-01-02T15:00:00Z","title":"Long-form thesis","copy":"Everyone is racing to hire engineers. The best founders of the next decade won't be engineers at all — they'll be the people with taste.","rationale":"Education beat. Afternoon professional window. LinkedIn: long-form authority + soft CTA.","media":[],"links":[],"char_count":136,"source":{"engine":"typefully","ref":"0"} },- { "id":"s3","channel":"threads","kind":"post","type":"thread","scheduled_at":"2026-01-03T17:30:00Z","copy":"weird week.\n\n———\n\nanyone else living a double life right now?","rationale":"Education beat. Evening casual window. Threads: conversational.","media":[],"links":[],"char_count":58,"source":{"engine":"typefully","ref":"0"} }+ {+ "id": "s1",+ "channel": "x",+ "kind": "post",+ "type": "text",+ "scheduled_at": "2026-01-02T07:00:00Z",+ "title": "Build-in-public note",+ "copy": "shipped a thing today. the hard part was never the code — it was deciding what to leave out.",+ "rationale": "Education/credibility beat. Morning authority slot. X: hook-first.",+ "media": [],+ "links": [],+ "char_count": 98,+ "source": { "engine": "typefully", "ref": "0", "edit_url": "https://example.com/" }+ },+ {+ "id": "s2",+ "channel": "linkedin",+ "kind": "post",+ "type": "text",+ "scheduled_at": "2026-01-02T15:00:00Z",+ "title": "Long-form thesis",+ "copy": "Everyone is racing to hire engineers. The best founders of the next decade won't be engineers at all — they'll be the people with taste.",+ "rationale": "Education beat. Afternoon professional window. LinkedIn: long-form authority + soft CTA.",+ "media": [],+ "links": [],+ "char_count": 136,+ "source": { "engine": "typefully", "ref": "0" }+ },+ {+ "id": "s3",+ "channel": "threads",+ "kind": "post",+ "type": "thread",+ "scheduled_at": "2026-01-03T17:30:00Z",+ "copy": "weird week.\n\n———\n\nanyone else living a double life right now?",+ "rationale": "Education beat. Evening casual window. Threads: conversational.",+ "media": [],+ "links": [],+ "char_count": 58,+ "source": { "engine": "typefully", "ref": "0" }+ }]},{- "id": "my-app", "label": "my-app", "kind": "project", "engine": "upload-post", "status": "ok",+ "id": "my-app",+ "label": "my-app",+ "kind": "project",+ "engine": "upload-post",+ "status": "ok","channels": ["instagram", "linkedin", "threads", "x"],"items": [- { "id":"a1","channel":"instagram","kind":"post","type":"photo","scheduled_at":"2026-01-02T13:00:00Z","copy":"Something worth your attention is almost here. 🧡","rationale":"Pre-launch teaser. Midday window. Instagram: visual-first, link-in-bio.","media":[{"type":"image","url":"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='240'%3E%3Crect width='400' height='240' fill='%23161a23'/%3E%3Ctext x='50%25' y='50%25' fill='%239aa6b8' font-family='sans-serif' font-size='18' text-anchor='middle'%3Eteaser creative%3C/text%3E%3C/svg%3E","thumb":null}],"links":[],"char_count":47,"source":{"engine":"upload-post","ref":"job1"} },- { "id":"a2","channel":"x","kind":"post","type":"photo","scheduled_at":"2026-01-02T15:00:00Z","copy":"this week, that gap gets a whole lot smaller. 👀","rationale":"Pre-launch teaser. Afternoon window. X: hook-first.","media":[],"links":[],"char_count":47,"source":{"engine":"upload-post","ref":"job2"} },- { "id":"a3","channel":"instagram","kind":"post","type":"video","scheduled_at":"2026-01-04T13:00:00Z","copy":"It's here. Download now — link in bio.","rationale":"Launch beat. Midday window. Instagram: visual-first.","media":[{"type":"video","url":"","thumb":"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='240'%3E%3Crect width='400' height='240' fill='%2312151c'/%3E%3Ctext x='50%25' y='50%25' fill='%239aa6b8' font-family='sans-serif' font-size='18' text-anchor='middle'%3Elaunch reel%3C/text%3E%3C/svg%3E"}],"links":[],"char_count":38,"source":{"engine":"upload-post","ref":"job3"} },- { "id":"a4","channel":"linkedin","kind":"post","type":"text","scheduled_at":"2026-01-04T16:00:00Z","copy":"my-app is live. Stop guessing. Start understanding.\n\nhttps://example.com/app","rationale":"Launch beat. Afternoon professional window. LinkedIn: long-form.","media":[],"links":["https://example.com/app"],"char_count":74,"source":{"engine":"upload-post","ref":"job4"} }+ {+ "id": "a1",+ "channel": "instagram",+ "kind": "post",+ "type": "photo",+ "scheduled_at": "2026-01-02T13:00:00Z",+ "copy": "Something worth your attention is almost here. 🧡",+ "rationale": "Pre-launch teaser. Midday window. Instagram: visual-first, link-in-bio.",+ "media": [+ {+ "type": "image",+ "url": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='240'%3E%3Crect width='400' height='240' fill='%23161a23'/%3E%3Ctext x='50%25' y='50%25' fill='%239aa6b8' font-family='sans-serif' font-size='18' text-anchor='middle'%3Eteaser creative%3C/text%3E%3C/svg%3E",+ "thumb": null+ }+ ],+ "links": [],+ "char_count": 47,+ "source": { "engine": "upload-post", "ref": "job1" }+ },+ {+ "id": "a2",+ "channel": "x",+ "kind": "post",+ "type": "photo",+ "scheduled_at": "2026-01-02T15:00:00Z",+ "copy": "this week, that gap gets a whole lot smaller. 👀",+ "rationale": "Pre-launch teaser. Afternoon window. X: hook-first.",+ "media": [],+ "links": [],+ "char_count": 47,+ "source": { "engine": "upload-post", "ref": "job2" }+ },+ {+ "id": "a3",+ "channel": "instagram",+ "kind": "post",+ "type": "video",+ "scheduled_at": "2026-01-04T13:00:00Z",+ "copy": "It's here. Download now — link in bio.",+ "rationale": "Launch beat. Midday window. Instagram: visual-first.",+ "media": [+ {+ "type": "video",+ "url": "",+ "thumb": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='240'%3E%3Crect width='400' height='240' fill='%2312151c'/%3E%3Ctext x='50%25' y='50%25' fill='%239aa6b8' font-family='sans-serif' font-size='18' text-anchor='middle'%3Elaunch reel%3C/text%3E%3C/svg%3E"+ }+ ],+ "links": [],+ "char_count": 38,+ "source": { "engine": "upload-post", "ref": "job3" }+ },+ {+ "id": "a4",+ "channel": "linkedin",+ "kind": "post",+ "type": "text",+ "scheduled_at": "2026-01-04T16:00:00Z",+ "copy": "my-app is live. Stop guessing. Start understanding.\n\nhttps://example.com/app",+ "rationale": "Launch beat. Afternoon professional window. LinkedIn: long-form.",+ "media": [],+ "links": ["https://example.com/app"],+ "char_count": 74,+ "source": { "engine": "upload-post", "ref": "job4" }+ }]},{- "id": "other-project", "label": "other-project", "kind": "project", "engine": null, "status": "unprovisioned",- "channels": [], "items": []+ "id": "other-project",+ "label": "other-project",+ "kind": "project",+ "engine": null,+ "status": "unprovisioned",+ "channels": [],+ "items": []}]}