[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CAWQ6QY8D2HH1WD424MSDB":3,"skill-same:01M6CAWQ6QY8D2HH1WD424MSDB":127},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":17,"categories":18,"keywords":29,"publishedAt":59,"linkOnly":60,"markdownContent":61,"markdownBody":62,"frontMatter":63,"refName":70,"commitSha":71,"skillDirectory":72,"forksCount":73,"repositoryHtmlUrl":74,"repositoryHomepageUrl":13,"ownerHtmlUrl":75,"ownerBlogUrl":13,"ownerDescription":13,"updatedAt":76,"install":77,"resources":90},"01M6CAWQ6QY8D2HH1WD424MSDB","wa-campaign-content-analysis","战役内容分析与诊断","Analyze existing Your Project campaigns in place to diagnose prompt, agent, or quality issues — without copying or exporting. Per-scene content classification with agent attribution via debug_info.agent_name. Use when the user asks 'why is the LLM doing X in my campaigns', 'do a regression review across the last N campaigns', 'audit dialog\u002FNPC behavior', 'compare heavy-dialog vs story-mode scenes', or wants prompt-side root-cause diagnosis. Distinct from download-campaign (which exports to disk) and wa-prod-data-query (which analyzes real-user activity).","就地分析现有 Your Project 战役，诊断提示词、智能体或质量问题——不进行复制或导出。通过 debug_info.agent_name 进行带有智能体归属的逐场景内容分类。当用户询问 '为什么 LLM 在我的战役中做 X'、'对最近 N 个战役做回归审查'、'审计对话\u002FNPC 行为'、'比较重对话与故事模式场景'，或希望进行提示词侧的根因诊断时使用。区别于 download-campaign（导出到磁盘）和 wa-prod-data-query（分析真实用户活动）。","jleechanorg\u002Fjleechan-skills","jleechanorg","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F221404966?v=4","01M6C1VJ99XG950X1DWPEBCBGX",null,"01M6C1VJDK5YVDNT3362RT5WSB",6,"MIT","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002FSKILL.md",[19,24],{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师","PROFESSION","适用职业",{"categoryNo":25,"categoryName":26,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8C7EDVFXM320A73X49K3FEZ","提示词分析与优化","SCENARIO","使用场景",[30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58],"content analysis","content","analysis","wa campaign content analysis","campaign","dialog","when","mode","which","retention","filter","project","across","query","reports","repro","use","review","prompt","regression","analyze","disk","classification","attribution","audit","file","issues","diagnose","debug","2026-11-10 10:12:30",false,"---\nname: wa-campaign-content-analysis\ndescription: \"Analyze existing Your Project campaigns in place to diagnose prompt, agent, or quality issues — without copying or exporting. Per-scene content classification with agent attribution via debug_info.agent_name. Use when the user asks 'why is the LLM doing X in my campaigns', 'do a regression review across the last N campaigns', 'audit dialog\u002FNPC behavior', 'compare heavy-dialog vs story-mode scenes', or wants prompt-side root-cause diagnosis. Distinct from download-campaign (which exports to disk) and wa-prod-data-query (which analyzes real-user activity).\"\nwhen_to_use: \"Use when the user says: analyze the last N campaigns, review dialog quality, audit NPC behavior, regression review, per-scene analysis, agent attribution, why does the LLM X in my campaigns, do all the dialog scenes have Y, find scenes where Z is missing, per-agent breakdown. Do NOT use for: downloading\u002Fexporting single campaigns (use download-campaign); real-user activity\u002Fretention reports (use wa-prod-data-query); single-bug repros (use repro).\"\narguments:\n  - query\n  - campaign_filter\nargument-hint: \"[\u003Canalysis target>] [--last N] [--min-entries M] [--since-days D]\"\ncontext: inline\nallowed-tools: terminal, file\n---\n\n# wa-campaign-content-analysis — analyze existing WA campaigns in place\n\nCanonical home for the \"look at content already in Firestore and tell me what's happening\" workflow. Differs from `download-campaign` (which exports to disk) and `wa-prod-data-query` (which analyzes user activity, not scene content). This skill is for **prompt \u002F agent \u002F content quality analysis** across many existing campaigns without copying or mutating anything.\n\nWhen to use this skill vs others:\n\n| Question class | Skill |\n|---|---|\n| \"Why does the LLM do X in my campaigns?\" | **THIS SKILL** |\n| \"Pull this campaign so I can read it\" | `download-campaign` |\n| \"How many real users touched WA last week?\" | `wa-prod-data-query` |\n| \"This specific scene has a bug\" | `repro` |\n| \"What changed in the prompt last week?\" | read git log of `$PROJECT_ROOT\u002Fprompts\u002F` directly |\n\n## When to fire this skill\n\nTriggers (any one):\n\n- User asks \"review the last N campaigns with M+ scenes\" or similar cross-campaign content review\n- User asks \"do all my dialog scenes have Y\" \u002F \"audit NPC behavior\" \u002F \"is X actually being applied\"\n- User asks \"compare heavy-dialog vs story-mode scenes\" \u002F per-agent breakdown\n- User asks \"why are NPCs silent\" \u002F \"why does the PC not speak\" \u002F \"which agent is generating the response\"\n- After a prompt change — \"verify the change actually lands in new scenes\"\n- **User names a specific campaign or setting (\"the Danerys campaign in Meereen\", \"the Bran campaign\", \"the second Visenya run\")** — see Phase 8 for the user-named-campaign lookup recipe. This is the most common intake shape and the one most likely to mis-route on a literal-name lookup. Do NOT skip to a literal `.where(\"name\", \"==\", ...)` query; users often describe by setting\u002Fcharacter rather than exact title.\n\n## Phase 1 — Confirm environment (reuse `download-campaign` phases 1-3)\n\nSame venv + auth + clock-skew setup as `download-campaign`. **Do not duplicate it here** — read `~\u002F.hermes\u002Fskills\u002Fdownload-campaign\u002FSKILL.md` Phases 1-3 verbatim and execute them. The firestore connection, `WORLDAI_DEV_MODE=true`, `apply_clock_skew_patch()`, and `auth.get_user_by_email(\"$USER@gmail.com\")` boilerplate are identical.\n\nKey environment facts:\n\n- Project ID: `worldarchitecture-ai` (with `-ture-`), NOT `worldarchitect-ai`\n- Service account: `~\u002FserviceAccountKey.json`\n- UID for $USER: `vnLp2G3m21PJL6kxcuAqmWSOtm73`\n- Subcollection name is **`story`**, NOT `story_entries` (Pitfall from `download-campaign`)\n\n## Phase 2 — Build the candidate campaign list\n\nFor \"last N campaigns with ≥M scenes\":\n\n```python\ndb = firestore.client()\ncamps = db.collection(\"users\").document(uid).collection(\"campaigns\").stream()\ncamp_list = []\nfor c in camps:\n    cid = c.id\n    cd = c.to_dict() or {}\n    name = cd.get(\"name\") or cd.get(\"title\") or \"Untitled\"\n    # Aggregation count is the cheap+correct path; .limit(2000).stream() caps at 2000\n    agg = db.collection(\"users\").document(uid).collection(\"campaigns\").document(cid).collection(\"story\").count().get()\n    entry_count = int(agg[0][0].value)\n    if entry_count \u003C MIN_ENTRIES:\n        continue\n    # Fetch last activity timestamp for sorting\n    q = (db.collection(\"users\").document(uid).collection(\"campaigns\").document(cid)\n         .collection(\"story\").order_by(\"timestamp\", direction=firestore.Query.DESCENDING).limit(1).stream())\n    docs = list(q)\n    last_ts_raw = None\n    if docs:\n        d = docs[0].to_dict() or {}\n        last_ts_raw = d.get(\"timestamp\") or d.get(\"created_at\")\n    camp_list.append({\"id\": cid, \"name\": name, \"entries\": entry_count, \"last_ts\": norm(last_ts_raw)})\n\ncamp_list.sort(key=lambda c: c[\"last_ts\"], reverse=True)\nlast_n = camp_list[:N]\n```\n\n**`norm()` helper — Firestore timestamps are mixed types** in this DB. Some docs store `DatetimeWithNanoseconds`, others store epoch seconds as int\u002Ffloat. Handle both:\n\n```python\ndef norm(v):\n    if v is None: return 0.0\n    if hasattr(v, \"timestamp\"):\n        try: return float(v.timestamp())\n        except Exception: pass\n    if isinstance(v, (int, float)):\n        if v > 1e12: return float(v) \u002F 1000.0  # millis → seconds\n        return float(v)\n    return 0.0\n```\n\nDon't sort directly on raw values — `TypeError: '\u003C' not supported between instances of 'int' and 'DatetimeWithNanoseconds'` fires.\n\n**De-duplication note**: titles alone are not unique (e.g. \"Bran the broken\" vs \"Bran the broken (ignore directive)\" — these are *intentional* distinct campaigns the user is running, not copies). Only de-duplicate on `campaign_id`. The `download-campaign` Pitfall #6 (slug collision on duplicate titles) applies — but for in-place analysis you don't need to worry about it, since you're reading live data.\n\n## Phase 3 — Per-scene extraction (the schema insight)\n\n**Critical schema facts (verified 2026-07-13 from 2,464 gemini scenes across 10 campaigns):**\n\n| Field | Meaning | Example values |\n|---|---|---|\n| `actor` | Who authored this doc | `\"user\"`, `\"gemini\"` (LLM), sometimes `\"system\"` |\n| `mode` | **USER INTENT mode** — what the player typed | `\"character\"`, `\"god\"`, `\"think\"`, `\"(unset)\"` |\n| `text` | Scene content (markdown narrative + quoted speech) | `\"[CHARACTER CREATION - Review]\\n\\nVisenya...\"` |\n| `debug_info.agent_name` | **THE ACTUAL AGENT that produced the scene** | `\"HeavyDialogAgent\"`, `\"DialogAgent\"`, `\"StoryModeAgent\"`, `\"GodModeAgent\"`, `\"CombatAgent\"`, `\"LevelUpAgent\"`, `\"CharacterCreationAgent\"`, `\"PlanningAgent\"`, `\"FactionManagementAgent\"`, `\"RewardsAgent\"`, `\"InfoAgent\"`, `\"SpicyModeAgent\"`, `\"CampaignUpgradeAgent\"` |\n| `debug_info.llm_model` | LLM model identifier | `\"gemini-3.8-flash\"` |\n| `debug_info.system_instruction_files` | Which prompt files were loaded | (list of file basenames) |\n| `full_state_updates` | State changes emitted this turn | nested dict |\n| `planning_block` | Choices offered to the player | nested dict |\n\n**THE TRAP**: `mode` field is **NOT** which agent wrote the scene. It records what *intent mode* the user's input triggered. Across 2,464 scenes in 10 long campaigns, only 3 distinct `mode` values appeared: `character` (73%), `god` (19%), `think` (7%). **Zero** scenes have `mode=dialog` or `mode=heavydialog` even though 38% of all scenes are written by `DialogAgent` or `HeavyDialogAgent`.\n\n**Always attribute by `debug_info.agent_name`, not `mode`.** This is the single most important rule for any cross-campaign analysis.\n\n**Schema-zero case (verified 2026-07-26 on Visenya v9, `qoQtHsU7DxZnR24VNU9w`, 412 scenes):** Some campaigns return story docs with `debug_info = {}` (empty dict — no `agent_name`, no `llm_model`, no `system_instruction_files`) AND `full_state_updates = {}` (empty dict). Symptom: every per-scene `debug_info.agent_name` lookup returns `None`, every per-agent histogram collapses to \"unknown\", and the typical agent distribution table is meaningless. The narrative quality is fine — the schema fields simply were never written.\n\nDetection before per-agent analysis (cheap, mandatory):\n\n```python\nsample = next(camp.collection(\"story\").limit(5).stream()).to_dict() or {}\nhas_agent_tracking = bool((sample.get(\"debug_info\") or {}).get(\"agent_name\"))\nhas_state_updates = bool(sample.get(\"full_state_updates\"))\nif not has_agent_tracking:\n    print(\"WARN: empty debug_info — per-agent attribution unavailable\")\n    print(\"Fallback: analyze raw .txt export at ~\u002Fllm_wiki\u002Fraw\u002Fcampaigns\u002F\u003Cid8>\u002F\")\nif not has_state_updates:\n    print(\"WARN: empty full_state_updates — level \u002F NPC timeline unavailable\")\n    print(\"Fallback: parse `Status: Lvl N` headers from raw .txt scenes\")\n```\n\nWhen either is empty, **do not pretend per-agent findings are real.** Report \"schema-zero: per-agent attribution unavailable; analyzing raw text export instead.\" The fallback chain is detailed in `references\u002Fvisenya-v9-raw-text-analyzer.md` and the regex patterns in `references\u002Fpersonal-scale-challenge-pattern.md`.\n\n## Phase 4 — Content classifiers\n\nCommon per-scene metrics:\n\n### Quoted-speech attribution (PC vs NPC)\n\n```python\nDIALOG_PATTERNS = [\n    re.compile(r'\"([^\"\\n]{2,500})\"'),   # straight double\n    re.compile(r\"'([^'\\n]{2,500})'\"),   # straight single\n    re.compile(r'\"([^\"\\n]{2,500})\"'),   # curly double\n    re.compile(r\"'([^'\\n]{2,500})'\"),   # curly single\n]\nVERB_DIALOG_RE = re.compile(\n    r\"\\b([A-Z][a-zA-Z'\\-]+(?:\\s+[A-Z][a-zA-Z'\\-]+)?)\\s+\"\n    r\"(?:said|asked|replied|shouted|whispered|cried|answered|murmured|muttered|stated|declared|\"\n    r\"exclaimed|gasped|snapped|hissed|sneered|smiled|laughed|grumbled|rejoined|added|continued|noted|\"\n    r\"remarked|observed|responded|countered|suggested|insisted|protested|begged|pleaded|warned|\"\n    r\"told|commanded|ordered|demanded|inquired|queried|wondered|breathed|sighed|drawled|babbled)\\b\"\n    r\"[^.!?\\n]{0,80}\",\n    flags=re.MULTILINE,\n)\nNAME_COLON_RE = re.compile(r\"^\\s*([A-Z][a-zA-Z'\\-]+(?:\\s+[A-Z][a-zA-Z'\\-]+)?)\\s*:\\s*([^\\n]{2,500})\",\n                            flags=re.MULTILINE)\nFIRST_PERSON_RE = re.compile(r\"^(I |I'm |I've |I'll |I'd |My |We |Our |Me |Im |Ive |Ill |Id )\",\n                              re.IGNORECASE)\n\ndef count_dialog(text, pc_name, npc_names_set):\n    \"\"\"Return (pc_lines, npc_lines, speakers_list) for a single scene text.\"\"\"\n    if not text:\n        return 0, 0, []\n    pc_lines = npc_lines = 0\n    speakers = []\n    MECHANIC_LABELS = {\"Intelligence Check\",\"Wisdom Check\",\"Charisma Check\",\"Persuasion Check\",\n                       \"Deception Check\",\"Intimidation Check\",\"Performance Check\",\"Insight Check\",\n                       \"Social HP\",\"Resistance\",\"Objective\",\"Outcome\",\"IMMUNITIES\",\"DISSONANCE\",\n                       \"IDENTITY\",\"DIVINE BONUSES\",\"LEVEL\",\"DIVINE LEVERAGE\",\"XP\",\n                       \"Administrative Log\",\"Strategic Note\",\"Session Summary\"}\n    # 1. Quoted speech (dedupe straight+curly overlap)\n    seen = set()\n    quoted = []\n    for pat in DIALOG_PATTERNS:\n        for m in pat.finditer(text):\n            line = m.group(1).strip()\n            key = line[:50]\n            if key in seen: continue\n            seen.add(key); quoted.append(line)\n    for q in quoted:\n        if FIRST_PERSON_RE.match(q):\n            pc_lines += 1\n        else:\n            npc_lines += 1\n    # 2. Name-prefixed dialog (\"Name: '...'\")\n    for m in NAME_COLON_RE.finditer(text):\n        sn = m.group(1).strip()\n        line_text = m.group(2).strip().strip(\"'\\\"\")\n        if not line_text: continue\n        if sn in MECHANIC_LABELS: continue\n        if pc_name and sn.lower() == pc_name.lower():\n            pc_lines += 1\n        else:\n            npc_lines += 1\n            speakers.append(sn)\n    # 3. Indirect speech (\"Name said that...\")\n    for m in VERB_DIALOG_RE.finditer(text):\n        sn = m.group(1).strip()\n        if sn in MECHANIC_LABELS: continue\n        if pc_name and sn.lower() == pc_name.lower():\n            pc_lines += 1\n        else:\n            npc_lines += 1\n            speakers.append(sn)\n    return pc_lines, npc_lines, list(set(speakers))\n```\n\n**Limitations** of this classifier (verified 2026-07-13):\n\n- Misses *paraphrased* NPC speech (no quotes, no `Name said`). For PC-silent analysis this is fine (NPC paraphrases still get attributed via verb patterns and NAME_COLON).\n- First-person quoted lines are heuristic-PC. False positives: third-person narration with self-quoted thought (\"My mother always said, 'Don't trust X'\"). False negatives: PC speaks in third person (\"Bran Stark replies, 'I am the Three-Eyed Raven'\"). For long-campaign diagnosis the false-positive rate is acceptable (median PC=0 stays 0 in any case).\n- Per-game-state `pc_name` resolution is needed for NAME_COLON\u002FVERB_DIALOG attribution. Pull from `users\u002F{uid}\u002Fcampaigns\u002F{cid}\u002Fgame_states\u002Fcurrent_state.player_character_data.name`.\n\n### Other useful per-scene metrics\n\n- **Word count** — `len(text.split())`. Median words\u002Fscene per agent reveals scene depth (Combat ~345, HeavyDialog ~436, PlanningAgent ~50).\n- **Distinct NPC speakers** — count unique values in `speakers` list. 0 = pure narration, 1 = single-NPC reply, 3+ = roundtable.\n- **Quoted-line density** — `(pc_lines + npc_lines) \u002F words` × 100. Low = action-only; high = dialog-heavy.\n- **Scene-bucket histograms** — bucket by NPC line count `[(0,0),(1,1),(2,3),(4,7),(8,15),(16,31),(32,63),(64+)]`.\n\n## Phase 5 — Per-agent aggregation\n\nGroup scenes by `debug_info.agent_name` (not `mode`):\n\n```python\nfrom collections import defaultdict\nimport statistics\n\nby_agent = defaultdict(list)\nfor s in all_scenes:\n    by_agent[s[\"agent\"]].append(s)\n\nfor agent, sl in sorted(by_agent.items(), key=lambda kv: -len(kv[1])):\n    if len(sl) \u003C 10: continue\n    n = len(sl)\n    print(f\"{agent}: scenes={n}  med_pc={statistics.median([s['pc_lines'] for s in sl])}  \"\n          f\"med_npc={statistics.median([s['npc_lines'] for s in sl])}  \"\n          f\"%pc_silent={100*sum(1 for s in sl if s['pc_lines']==0)\u002Fn:.1f}%  \"\n          f\"%two_way={100*sum(1 for s in sl if s['pc_lines']>=1 and s['npc_lines']>=1)\u002Fn:.1f}%\")\n```\n\nTypical distribution across long campaigns:\n\n| Agent | % of scenes | Notes |\n|---|---:|---|\n| HeavyDialogAgent | 25-30% | \"high-stakes conversations\" — should have 2-way dialog; rarely does |\n| GodModeAgent | 18-22% | Directive queries; 99%+ PC-silent (player asks, AI answers) |\n| StoryModeAgent | 12-16% | Default narrative mode |\n| DialogAgent | 10-14% | Active dialog turns (routed via `matches_game_state` or `MODE_DIALOG`) |\n| LevelUpAgent | 6-10% | Level-up modal — minimal dialog |\n| PlanningAgent | 5-8% | Choice generation only — 100% PC-silent, \u003C100 words |\n| CharacterCreationAgent | 3-5% | First scene only |\n| CombatAgent | 2-4% | Combat — short scenes, NPC monologue for villain banter |\n| FactionManagementAgent | 3-4% | Faction minigame |\n\n**Diagnostic pattern**: if a \"dialog agent\" has % PC-silent > 50%, the prompt is biased toward NPC monologue and needs fixing (see `references\u002Fpc-silent-prompt-diagnosis.md`).\n\n## Phase 6 — Verify a previously-shipped fix actually took effect\n\nWhen the user asks \"is the dialog fix working?\" \u002F \"let me check after deploy\" \u002F \"is X actually being applied\" AFTER a prompt-fix PR has merged, run this verification phase BEFORE assuming the fix worked. The full verification recipe (with regex tightening, pre\u002Fpost comparison, and 5-cause taxonomy) lives in `references\u002Fprompt-fix-effectiveness-verification.md`. Summary:\n\n1. Find the merge SHA timestamp from `git log` of the changed prompt file.\n2. Locate the user's most-recent campaign via `users\u002F{uid}\u002Fcampaigns` subcollection (NOT top-level `campaigns` — that's test fixtures only, per `wa-prod-data-query` Pitfall #1).\n3. Stream `story` subcollection and split by merge time. Use the same `actor=gemini + mode=\u003Crelevant>` filter for both sides.\n4. Compute NPC-attributed direct quotes (requires `\"...\"` AFTER speech verb within 80 chars — NOT just \"Name said\" paraphrase, which inflates counts).\n5. Read 2-3 sample scenes verbatim to confirm the classifier isn't fooled by italicized action (`*Florent swallows...*`) or HUD panels.\n6. If pre\u002Fpost are statistically indistinguishable, the prompt fix landed but the LLM isn't following. Five causes, in priority order: wrong place in prompt, structural panels crowd, model capacity, wrong bug class fixed, cache miss on prompt update.\n7. Report findings as a pre\u002Fpost delta + the cause list as options for the user to choose from.\n\n**Class-level lesson**: prompt-fix-shipped-but-LLM-ignores-it is a distinct bug class from prompt-bug-detected. Verification ≠ detection. The earlier recipe (`references\u002Fpc-silent-prompt-diagnosis.md`) covered detection; this phase covers verification.\n\n## Phase 7 — Root-cause diagnosis → prompt files\n\nWhen per-agent analysis reveals a content-quality regression (e.g. \"PC is silent in 70% of dialog scenes\"), the cause is almost always in one of three prompt files:\n\n1. **`$PROJECT_ROOT\u002Fprompts\u002Fdialog_system_instruction.md`** — dialog-specific guidance. Check for NPC-only bias. Search for `player character`, `speak as the PC`, `PC voice`, `on behalf of the player` — if all zero hits, the prompt never instructs the LLM to put words in the PC's mouth.\n2. **`$PROJECT_ROOT\u002Fprompts\u002Fnarrative_system_instruction.md`** (L60-80) and **`narrative_lite_system_instruction.md`** (L65-80) — look for \"Narrative Authority\" \u002F \"Player describes \u002F GM describes\" blocks. If the GM side reserves NPC reactions without explicitly granting PC dialogue, the LLM defaults to PC-silent.\n3. **`$PROJECT_ROOT\u002Fagents.py`** — check each agent's `REQUIRED_PROMPT_ORDER` for whether any PC-voice prompt slot exists. HeavyDialogAgent at L2686-2697 has none.\n\n**Don't add backend enforcement.** Per `root-cause-first` skill discipline, fix the prompt layer first. Adding a server-side \"PC must speak N times\" re-prompt loop is a tail-risk: it doubles token cost on every dialog scene and the LLM will eventually find a way to bypass.\n\n## Phase 7 — Persist findings\n\nThree artifacts to produce:\n\n1. **Per-scene JSONL dump** at `~\u002F.hermes\u002F\u003Ctopic>_\u003Cdate>\u002Fall_scenes_by_agent.jsonl` — one row per scene with campaign_id, agent, pc_lines, npc_lines, speakers, word count.\n2. **Per-agent summary JSON** at `~\u002F.hermes\u002F\u003Ctopic>_\u003Cdate>\u002Fagent_summary.json` — aggregated medians + % silent + % two-way.\n3. **Wiki source page** at `~\u002Fllm_wiki\u002Fwiki\u002Fsources\u002F\u003Ctopic>-\u003Cdate>.md` — YAML frontmatter + diagnosis + verbatim sample scenes + prompt citations. Future agents can search this.\n\nAlso open a follow-up bead:\n\n```bash\ncd $HOME\u002Fyour-project.com && br create \"\u003Cone-line summary>\" \\\n  --type bug --priority 2 --description \"\u003Cfile paths + line numbers + link to wiki page>\"\n```\n\n## Pitfalls (this list IS the skill — review before running)\n\n10. **Don't de-duplicate by title** — \"Bran the broken\" and \"Bran the broken (ignore directive)\" are intentionally distinct campaigns the user is running. De-dup only on `campaign_id`.\n11. **Campaign doc `name` vs `title`** — the campaign-level document uses `title` (not `name`) for real-user campaigns. A `.where(\"name\", \"==\", ...)` query returns 0 hits even when the campaign exists. See `references\u002Fcampaign-doc-field-naming.md` and always read `cd.get(\"title\") or cd.get(\"name\")`. Verified 2026-07-15, $USER's account.\n12. **User-named lookup ≠ literal title** — \"the Danerys campaign in Meereen\" is almost never a literal title match; use the Phase 8 three-step recipe (title pre-filter → scene-level keyword confirmation → opening-scene verification). Don't burn a clarifying menu on the user when the top match is 95% likely correct.\n2. **Mixed timestamp types** — `DatetimeWithNanoseconds` vs `int` epoch vs `float` epoch-millis. Normalize via the `norm()` helper before sorting. Sorting raw fails with `TypeError: '\u003C' not supported`.\n3. **`\u002Ftmp` is sandbox-scoped per `execute_code` call** — write artifacts to `~\u002F.hermes\u002F\u003Ctopic>_\u003Cdate>\u002F` or `~\u002Fllm_wiki\u002Fwiki\u002Fsources\u002F` instead. Path returned by one execute_code call is gone in the next.\n4. **f-string `{VAR}` in `execute_code`** — the sandbox f-string parser doesn't handle braces inside strings used inside an f-string literal. Write the wiki content via `write_file` (cleanest) or escape `{{`\u002F`}}` everywhere.\n5. **Per-campaign PC name resolution** — for accurate NAME_COLON\u002FVERB_DIALOG attribution you need `player_character_data.name` from each campaign's `game_states\u002Fcurrent_state`. Without it, all NAME_COLON lines fall to NPC counter and inflate the npc count. Some campaigns have None for pc_name; fall back to \"unknown PC\" and accept the inflated NPC count.\n6. **First-person PC classifier misses third-person PC speech** — fine for PC-silent analysis (median stays 0), bad for quantifying how much PC *does* speak. If you need precise PC speech counts, sample 10-20 scenes manually.\n7. **Test users pollute the data** — same as `wa-prod-data-query` Pitfall 3. For $USER's account this is mostly fine (we filter by `uid`), but if you ever broaden to multi-uid scans, apply the test-user filter (emails containing `test`, `anon`, `dev-runner`, `example.com`, `jleechantest`).\n8. **Schema field drift** — story-doc schema has evolved over time. Older campaigns may use `narrative_text` instead of `text`, `created_at` instead of `timestamp`, `part` instead of `id`. Normalize field reads: `text = d.get(\"scene_text\") or d.get(\"narrative_text\") or d.get(\"text\") or d.get(\"content\")`. Same fallback chain for timestamps.\n9. **User-intent \"mode\" vs agent \"mode\"** — these are TWO DIFFERENT FIELDS with the same name. `story_doc.mode` is user intent. `agents.py` also uses `MODE` class constant for agent identity. Don't conflate them.\n10. **Don't de-duplicate by title** — \"Bran the broken\" and \"Bran the broken (ignore directive)\" are intentionally distinct campaigns the user is running. De-dup only on `campaign_id`.\n\n13. **Schema-zero story docs (`debug_info = {}`, `full_state_updates = {}`)** — verified 2026-07-26 on Visenya v9. Per-agent attribution falls back to \"unknown\" for *every* scene; per-agent histograms and per-agent percentages become meaningless. **Detection**: run a 5-doc sample probe before the full per-agent aggregation — if `(sample.get(\"debug_info\") or {}).get(\"agent_name\")` returns `None` for all 5, the campaign is schema-zero. **Fallback**: analyze the raw `.txt` export at `~\u002Fllm_wiki\u002Fraw\u002Fcampaigns\u002F\u003Cid8>\u002F\u003Ctitle>_\u003Cid8>.txt` (use `download-campaign` first). The raw text has `====== SCENE N ======` delimiters and `Status: Lvl N ...` headers per scene. Patterns documented in `references\u002Fpersonal-scale-challenge-pattern.md`. Reporting fabricated per-agent percentages (e.g. \"HeavyDialogAgent: 25-30%\") when the underlying `debug_info` is empty is dishonest analysis, not a number to summarize.\n\n## Sample driver script\n\nSee `scripts\u002Fper_scene_dialog_audit.py` (in this skill) for a working end-to-end implementation:\n\n- Pulls last N campaigns ≥ M scenes\n- Streams `story` subcollection per campaign in ASC timestamp order\n- Classifies each gemini scene via `count_dialog()`\n- Aggregates per-agent\n- Writes summary JSON + JSONL dump\n\n## Related\n\n- `download-campaign` — exports a single campaign (or batch) to disk. Use when the user wants to *read* campaign content; this skill is for *analyzing* content in place.\n- `wa-prod-data-query` — real-user engagement\u002Fretention reports. Wrong domain (user activity, not scene content).\n- `repro` — single-bug repro for one specific user-reported scene. This skill is the cross-campaign version.\n- `references\u002Fpc-silent-prompt-diagnosis.md` — worked example of taking a per-agent breakdown (\"PC silent 67%\") and tracing it to specific prompt lines.\n- `references\u002Fprompt-fix-effectiveness-verification.md` — verification recipe for AFTER a prompt fix has shipped: pre\u002Fpost comparison, regex tightening (NPC-attributed quotes require `\"...\"` AFTER speech verb), and 5-cause taxonomy for \"PR merged but LLM still not following.\"\n- `references\u002Fpersonal-scale-challenge-pattern.md` — when the LLM auto-escalates to mythic-tier antagonists as the PC scales past the parity band; prompt-only fixes to preserve personal-scale challenge at high tier. Includes the five-prompt-edit recipe (Tier Compression, Consequence-Hiding Heuristic, mythic-NPC personhood, Force-a-Trade, anti-creep on major events) and the regex patterns for measuring personal-scale challenge density from raw text.\n- `references\u002Fvisenya-v9-raw-text-analyzer.md` — pipeline reference for analyzing a campaign whose `debug_info` is empty; walks through `\u002Ftmp\u002Fanalyze_visenya_v9_v2.py` style implementation against the `download-campaign` raw `.txt` export.\n\n## Tests\n\n- `tests\u002Ftest_dialog_classifier.py` — quote \u002F name-colon \u002F verb-indirect attribution, dedupe, first-person PC classification, mechanic-label skip.\n- `tests\u002Ftest_agent_attribution.py` — verify `debug_info.agent_name` precedence over `mode` field.\n- `scripts\u002Ftest_user_named_campaign_lookup.py` — Phase 8 three-step recipe (`get_campaign_title`, `title_prefilter`, `keyword_scan`, `confirm_opening_scene`) + the campaign-level `name` vs `title` field fallback + the \"guess and verify, no clarification menu\" output contract.\n\nRun: `cd ~\u002F.hermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis && python3 -m unittest discover -s tests && python3 scripts\u002Ftest_user_named_campaign_lookup.py`\n\nRun: `cd ~\u002F.hermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis && python3 -m unittest discover -s tests`","# wa-campaign-content-analysis — analyze existing WA campaigns in place\n\nCanonical home for the \"look at content already in Firestore and tell me what's happening\" workflow. Differs from `download-campaign` (which exports to disk) and `wa-prod-data-query` (which analyzes user activity, not scene content). This skill is for **prompt \u002F agent \u002F content quality analysis** across many existing campaigns without copying or mutating anything.\n\nWhen to use this skill vs others:\n\n| Question class | Skill |\n|---|---|\n| \"Why does the LLM do X in my campaigns?\" | **THIS SKILL** |\n| \"Pull this campaign so I can read it\" | `download-campaign` |\n| \"How many real users touched WA last week?\" | `wa-prod-data-query` |\n| \"This specific scene has a bug\" | `repro` |\n| \"What changed in the prompt last week?\" | read git log of `$PROJECT_ROOT\u002Fprompts\u002F` directly |\n\n## When to fire this skill\n\nTriggers (any one):\n\n- User asks \"review the last N campaigns with M+ scenes\" or similar cross-campaign content review\n- User asks \"do all my dialog scenes have Y\" \u002F \"audit NPC behavior\" \u002F \"is X actually being applied\"\n- User asks \"compare heavy-dialog vs story-mode scenes\" \u002F per-agent breakdown\n- User asks \"why are NPCs silent\" \u002F \"why does the PC not speak\" \u002F \"which agent is generating the response\"\n- After a prompt change — \"verify the change actually lands in new scenes\"\n- **User names a specific campaign or setting (\"the Danerys campaign in Meereen\", \"the Bran campaign\", \"the second Visenya run\")** — see Phase 8 for the user-named-campaign lookup recipe. This is the most common intake shape and the one most likely to mis-route on a literal-name lookup. Do NOT skip to a literal `.where(\"name\", \"==\", ...)` query; users often describe by setting\u002Fcharacter rather than exact title.\n\n## Phase 1 — Confirm environment (reuse `download-campaign` phases 1-3)\n\nSame venv + auth + clock-skew setup as `download-campaign`. **Do not duplicate it here** — read `~\u002F.hermes\u002Fskills\u002Fdownload-campaign\u002FSKILL.md` Phases 1-3 verbatim and execute them. The firestore connection, `WORLDAI_DEV_MODE=true`, `apply_clock_skew_patch()`, and `auth.get_user_by_email(\"$USER@gmail.com\")` boilerplate are identical.\n\nKey environment facts:\n\n- Project ID: `worldarchitecture-ai` (with `-ture-`), NOT `worldarchitect-ai`\n- Service account: `~\u002FserviceAccountKey.json`\n- UID for $USER: `vnLp2G3m21PJL6kxcuAqmWSOtm73`\n- Subcollection name is **`story`**, NOT `story_entries` (Pitfall from `download-campaign`)\n\n## Phase 2 — Build the candidate campaign list\n\nFor \"last N campaigns with ≥M scenes\":\n\n```python\ndb = firestore.client()\ncamps = db.collection(\"users\").document(uid).collection(\"campaigns\").stream()\ncamp_list = []\nfor c in camps:\n    cid = c.id\n    cd = c.to_dict() or {}\n    name = cd.get(\"name\") or cd.get(\"title\") or \"Untitled\"\n    # Aggregation count is the cheap+correct path; .limit(2000).stream() caps at 2000\n    agg = db.collection(\"users\").document(uid).collection(\"campaigns\").document(cid).collection(\"story\").count().get()\n    entry_count = int(agg[0][0].value)\n    if entry_count \u003C MIN_ENTRIES:\n        continue\n    # Fetch last activity timestamp for sorting\n    q = (db.collection(\"users\").document(uid).collection(\"campaigns\").document(cid)\n         .collection(\"story\").order_by(\"timestamp\", direction=firestore.Query.DESCENDING).limit(1).stream())\n    docs = list(q)\n    last_ts_raw = None\n    if docs:\n        d = docs[0].to_dict() or {}\n        last_ts_raw = d.get(\"timestamp\") or d.get(\"created_at\")\n    camp_list.append({\"id\": cid, \"name\": name, \"entries\": entry_count, \"last_ts\": norm(last_ts_raw)})\n\ncamp_list.sort(key=lambda c: c[\"last_ts\"], reverse=True)\nlast_n = camp_list[:N]\n```\n\n**`norm()` helper — Firestore timestamps are mixed types** in this DB. Some docs store `DatetimeWithNanoseconds`, others store epoch seconds as int\u002Ffloat. Handle both:\n\n```python\ndef norm(v):\n    if v is None: return 0.0\n    if hasattr(v, \"timestamp\"):\n        try: return float(v.timestamp())\n        except Exception: pass\n    if isinstance(v, (int, float)):\n        if v > 1e12: return float(v) \u002F 1000.0  # millis → seconds\n        return float(v)\n    return 0.0\n```\n\nDon't sort directly on raw values — `TypeError: '\u003C' not supported between instances of 'int' and 'DatetimeWithNanoseconds'` fires.\n\n**De-duplication note**: titles alone are not unique (e.g. \"Bran the broken\" vs \"Bran the broken (ignore directive)\" — these are *intentional* distinct campaigns the user is running, not copies). Only de-duplicate on `campaign_id`. The `download-campaign` Pitfall #6 (slug collision on duplicate titles) applies — but for in-place analysis you don't need to worry about it, since you're reading live data.\n\n## Phase 3 — Per-scene extraction (the schema insight)\n\n**Critical schema facts (verified 2026-07-13 from 2,464 gemini scenes across 10 campaigns):**\n\n| Field | Meaning | Example values |\n|---|---|---|\n| `actor` | Who authored this doc | `\"user\"`, `\"gemini\"` (LLM), sometimes `\"system\"` |\n| `mode` | **USER INTENT mode** — what the player typed | `\"character\"`, `\"god\"`, `\"think\"`, `\"(unset)\"` |\n| `text` | Scene content (markdown narrative + quoted speech) | `\"[CHARACTER CREATION - Review]\\n\\nVisenya...\"` |\n| `debug_info.agent_name` | **THE ACTUAL AGENT that produced the scene** | `\"HeavyDialogAgent\"`, `\"DialogAgent\"`, `\"StoryModeAgent\"`, `\"GodModeAgent\"`, `\"CombatAgent\"`, `\"LevelUpAgent\"`, `\"CharacterCreationAgent\"`, `\"PlanningAgent\"`, `\"FactionManagementAgent\"`, `\"RewardsAgent\"`, `\"InfoAgent\"`, `\"SpicyModeAgent\"`, `\"CampaignUpgradeAgent\"` |\n| `debug_info.llm_model` | LLM model identifier | `\"gemini-3.8-flash\"` |\n| `debug_info.system_instruction_files` | Which prompt files were loaded | (list of file basenames) |\n| `full_state_updates` | State changes emitted this turn | nested dict |\n| `planning_block` | Choices offered to the player | nested dict |\n\n**THE TRAP**: `mode` field is **NOT** which agent wrote the scene. It records what *intent mode* the user's input triggered. Across 2,464 scenes in 10 long campaigns, only 3 distinct `mode` values appeared: `character` (73%), `god` (19%), `think` (7%). **Zero** scenes have `mode=dialog` or `mode=heavydialog` even though 38% of all scenes are written by `DialogAgent` or `HeavyDialogAgent`.\n\n**Always attribute by `debug_info.agent_name`, not `mode`.** This is the single most important rule for any cross-campaign analysis.\n\n**Schema-zero case (verified 2026-07-26 on Visenya v9, `qoQtHsU7DxZnR24VNU9w`, 412 scenes):** Some campaigns return story docs with `debug_info = {}` (empty dict — no `agent_name`, no `llm_model`, no `system_instruction_files`) AND `full_state_updates = {}` (empty dict). Symptom: every per-scene `debug_info.agent_name` lookup returns `None`, every per-agent histogram collapses to \"unknown\", and the typical agent distribution table is meaningless. The narrative quality is fine — the schema fields simply were never written.\n\nDetection before per-agent analysis (cheap, mandatory):\n\n```python\nsample = next(camp.collection(\"story\").limit(5).stream()).to_dict() or {}\nhas_agent_tracking = bool((sample.get(\"debug_info\") or {}).get(\"agent_name\"))\nhas_state_updates = bool(sample.get(\"full_state_updates\"))\nif not has_agent_tracking:\n    print(\"WARN: empty debug_info — per-agent attribution unavailable\")\n    print(\"Fallback: analyze raw .txt export at ~\u002Fllm_wiki\u002Fraw\u002Fcampaigns\u002F\u003Cid8>\u002F\")\nif not has_state_updates:\n    print(\"WARN: empty full_state_updates — level \u002F NPC timeline unavailable\")\n    print(\"Fallback: parse `Status: Lvl N` headers from raw .txt scenes\")\n```\n\nWhen either is empty, **do not pretend per-agent findings are real.** Report \"schema-zero: per-agent attribution unavailable; analyzing raw text export instead.\" The fallback chain is detailed in `references\u002Fvisenya-v9-raw-text-analyzer.md` and the regex patterns in `references\u002Fpersonal-scale-challenge-pattern.md`.\n\n## Phase 4 — Content classifiers\n\nCommon per-scene metrics:\n\n### Quoted-speech attribution (PC vs NPC)\n\n```python\nDIALOG_PATTERNS = [\n    re.compile(r'\"([^\"\\n]{2,500})\"'),   # straight double\n    re.compile(r\"'([^'\\n]{2,500})'\"),   # straight single\n    re.compile(r'\"([^\"\\n]{2,500})\"'),   # curly double\n    re.compile(r\"'([^'\\n]{2,500})'\"),   # curly single\n]\nVERB_DIALOG_RE = re.compile(\n    r\"\\b([A-Z][a-zA-Z'\\-]+(?:\\s+[A-Z][a-zA-Z'\\-]+)?)\\s+\"\n    r\"(?:said|asked|replied|shouted|whispered|cried|answered|murmured|muttered|stated|declared|\"\n    r\"exclaimed|gasped|snapped|hissed|sneered|smiled|laughed|grumbled|rejoined|added|continued|noted|\"\n    r\"remarked|observed|responded|countered|suggested|insisted|protested|begged|pleaded|warned|\"\n    r\"told|commanded|ordered|demanded|inquired|queried|wondered|breathed|sighed|drawled|babbled)\\b\"\n    r\"[^.!?\\n]{0,80}\",\n    flags=re.MULTILINE,\n)\nNAME_COLON_RE = re.compile(r\"^\\s*([A-Z][a-zA-Z'\\-]+(?:\\s+[A-Z][a-zA-Z'\\-]+)?)\\s*:\\s*([^\\n]{2,500})\",\n                            flags=re.MULTILINE)\nFIRST_PERSON_RE = re.compile(r\"^(I |I'm |I've |I'll |I'd |My |We |Our |Me |Im |Ive |Ill |Id )\",\n                              re.IGNORECASE)\n\ndef count_dialog(text, pc_name, npc_names_set):\n    \"\"\"Return (pc_lines, npc_lines, speakers_list) for a single scene text.\"\"\"\n    if not text:\n        return 0, 0, []\n    pc_lines = npc_lines = 0\n    speakers = []\n    MECHANIC_LABELS = {\"Intelligence Check\",\"Wisdom Check\",\"Charisma Check\",\"Persuasion Check\",\n                       \"Deception Check\",\"Intimidation Check\",\"Performance Check\",\"Insight Check\",\n                       \"Social HP\",\"Resistance\",\"Objective\",\"Outcome\",\"IMMUNITIES\",\"DISSONANCE\",\n                       \"IDENTITY\",\"DIVINE BONUSES\",\"LEVEL\",\"DIVINE LEVERAGE\",\"XP\",\n                       \"Administrative Log\",\"Strategic Note\",\"Session Summary\"}\n    # 1. Quoted speech (dedupe straight+curly overlap)\n    seen = set()\n    quoted = []\n    for pat in DIALOG_PATTERNS:\n        for m in pat.finditer(text):\n            line = m.group(1).strip()\n            key = line[:50]\n            if key in seen: continue\n            seen.add(key); quoted.append(line)\n    for q in quoted:\n        if FIRST_PERSON_RE.match(q):\n            pc_lines += 1\n        else:\n            npc_lines += 1\n    # 2. Name-prefixed dialog (\"Name: '...'\")\n    for m in NAME_COLON_RE.finditer(text):\n        sn = m.group(1).strip()\n        line_text = m.group(2).strip().strip(\"'\\\"\")\n        if not line_text: continue\n        if sn in MECHANIC_LABELS: continue\n        if pc_name and sn.lower() == pc_name.lower():\n            pc_lines += 1\n        else:\n            npc_lines += 1\n            speakers.append(sn)\n    # 3. Indirect speech (\"Name said that...\")\n    for m in VERB_DIALOG_RE.finditer(text):\n        sn = m.group(1).strip()\n        if sn in MECHANIC_LABELS: continue\n        if pc_name and sn.lower() == pc_name.lower():\n            pc_lines += 1\n        else:\n            npc_lines += 1\n            speakers.append(sn)\n    return pc_lines, npc_lines, list(set(speakers))\n```\n\n**Limitations** of this classifier (verified 2026-07-13):\n\n- Misses *paraphrased* NPC speech (no quotes, no `Name said`). For PC-silent analysis this is fine (NPC paraphrases still get attributed via verb patterns and NAME_COLON).\n- First-person quoted lines are heuristic-PC. False positives: third-person narration with self-quoted thought (\"My mother always said, 'Don't trust X'\"). False negatives: PC speaks in third person (\"Bran Stark replies, 'I am the Three-Eyed Raven'\"). For long-campaign diagnosis the false-positive rate is acceptable (median PC=0 stays 0 in any case).\n- Per-game-state `pc_name` resolution is needed for NAME_COLON\u002FVERB_DIALOG attribution. Pull from `users\u002F{uid}\u002Fcampaigns\u002F{cid}\u002Fgame_states\u002Fcurrent_state.player_character_data.name`.\n\n### Other useful per-scene metrics\n\n- **Word count** — `len(text.split())`. Median words\u002Fscene per agent reveals scene depth (Combat ~345, HeavyDialog ~436, PlanningAgent ~50).\n- **Distinct NPC speakers** — count unique values in `speakers` list. 0 = pure narration, 1 = single-NPC reply, 3+ = roundtable.\n- **Quoted-line density** — `(pc_lines + npc_lines) \u002F words` × 100. Low = action-only; high = dialog-heavy.\n- **Scene-bucket histograms** — bucket by NPC line count `[(0,0),(1,1),(2,3),(4,7),(8,15),(16,31),(32,63),(64+)]`.\n\n## Phase 5 — Per-agent aggregation\n\nGroup scenes by `debug_info.agent_name` (not `mode`):\n\n```python\nfrom collections import defaultdict\nimport statistics\n\nby_agent = defaultdict(list)\nfor s in all_scenes:\n    by_agent[s[\"agent\"]].append(s)\n\nfor agent, sl in sorted(by_agent.items(), key=lambda kv: -len(kv[1])):\n    if len(sl) \u003C 10: continue\n    n = len(sl)\n    print(f\"{agent}: scenes={n}  med_pc={statistics.median([s['pc_lines'] for s in sl])}  \"\n          f\"med_npc={statistics.median([s['npc_lines'] for s in sl])}  \"\n          f\"%pc_silent={100*sum(1 for s in sl if s['pc_lines']==0)\u002Fn:.1f}%  \"\n          f\"%two_way={100*sum(1 for s in sl if s['pc_lines']>=1 and s['npc_lines']>=1)\u002Fn:.1f}%\")\n```\n\nTypical distribution across long campaigns:\n\n| Agent | % of scenes | Notes |\n|---|---:|---|\n| HeavyDialogAgent | 25-30% | \"high-stakes conversations\" — should have 2-way dialog; rarely does |\n| GodModeAgent | 18-22% | Directive queries; 99%+ PC-silent (player asks, AI answers) |\n| StoryModeAgent | 12-16% | Default narrative mode |\n| DialogAgent | 10-14% | Active dialog turns (routed via `matches_game_state` or `MODE_DIALOG`) |\n| LevelUpAgent | 6-10% | Level-up modal — minimal dialog |\n| PlanningAgent | 5-8% | Choice generation only — 100% PC-silent, \u003C100 words |\n| CharacterCreationAgent | 3-5% | First scene only |\n| CombatAgent | 2-4% | Combat — short scenes, NPC monologue for villain banter |\n| FactionManagementAgent | 3-4% | Faction minigame |\n\n**Diagnostic pattern**: if a \"dialog agent\" has % PC-silent > 50%, the prompt is biased toward NPC monologue and needs fixing (see `references\u002Fpc-silent-prompt-diagnosis.md`).\n\n## Phase 6 — Verify a previously-shipped fix actually took effect\n\nWhen the user asks \"is the dialog fix working?\" \u002F \"let me check after deploy\" \u002F \"is X actually being applied\" AFTER a prompt-fix PR has merged, run this verification phase BEFORE assuming the fix worked. The full verification recipe (with regex tightening, pre\u002Fpost comparison, and 5-cause taxonomy) lives in `references\u002Fprompt-fix-effectiveness-verification.md`. Summary:\n\n1. Find the merge SHA timestamp from `git log` of the changed prompt file.\n2. Locate the user's most-recent campaign via `users\u002F{uid}\u002Fcampaigns` subcollection (NOT top-level `campaigns` — that's test fixtures only, per `wa-prod-data-query` Pitfall #1).\n3. Stream `story` subcollection and split by merge time. Use the same `actor=gemini + mode=\u003Crelevant>` filter for both sides.\n4. Compute NPC-attributed direct quotes (requires `\"...\"` AFTER speech verb within 80 chars — NOT just \"Name said\" paraphrase, which inflates counts).\n5. Read 2-3 sample scenes verbatim to confirm the classifier isn't fooled by italicized action (`*Florent swallows...*`) or HUD panels.\n6. If pre\u002Fpost are statistically indistinguishable, the prompt fix landed but the LLM isn't following. Five causes, in priority order: wrong place in prompt, structural panels crowd, model capacity, wrong bug class fixed, cache miss on prompt update.\n7. Report findings as a pre\u002Fpost delta + the cause list as options for the user to choose from.\n\n**Class-level lesson**: prompt-fix-shipped-but-LLM-ignores-it is a distinct bug class from prompt-bug-detected. Verification ≠ detection. The earlier recipe (`references\u002Fpc-silent-prompt-diagnosis.md`) covered detection; this phase covers verification.\n\n## Phase 7 — Root-cause diagnosis → prompt files\n\nWhen per-agent analysis reveals a content-quality regression (e.g. \"PC is silent in 70% of dialog scenes\"), the cause is almost always in one of three prompt files:\n\n1. **`$PROJECT_ROOT\u002Fprompts\u002Fdialog_system_instruction.md`** — dialog-specific guidance. Check for NPC-only bias. Search for `player character`, `speak as the PC`, `PC voice`, `on behalf of the player` — if all zero hits, the prompt never instructs the LLM to put words in the PC's mouth.\n2. **`$PROJECT_ROOT\u002Fprompts\u002Fnarrative_system_instruction.md`** (L60-80) and **`narrative_lite_system_instruction.md`** (L65-80) — look for \"Narrative Authority\" \u002F \"Player describes \u002F GM describes\" blocks. If the GM side reserves NPC reactions without explicitly granting PC dialogue, the LLM defaults to PC-silent.\n3. **`$PROJECT_ROOT\u002Fagents.py`** — check each agent's `REQUIRED_PROMPT_ORDER` for whether any PC-voice prompt slot exists. HeavyDialogAgent at L2686-2697 has none.\n\n**Don't add backend enforcement.** Per `root-cause-first` skill discipline, fix the prompt layer first. Adding a server-side \"PC must speak N times\" re-prompt loop is a tail-risk: it doubles token cost on every dialog scene and the LLM will eventually find a way to bypass.\n\n## Phase 7 — Persist findings\n\nThree artifacts to produce:\n\n1. **Per-scene JSONL dump** at `~\u002F.hermes\u002F\u003Ctopic>_\u003Cdate>\u002Fall_scenes_by_agent.jsonl` — one row per scene with campaign_id, agent, pc_lines, npc_lines, speakers, word count.\n2. **Per-agent summary JSON** at `~\u002F.hermes\u002F\u003Ctopic>_\u003Cdate>\u002Fagent_summary.json` — aggregated medians + % silent + % two-way.\n3. **Wiki source page** at `~\u002Fllm_wiki\u002Fwiki\u002Fsources\u002F\u003Ctopic>-\u003Cdate>.md` — YAML frontmatter + diagnosis + verbatim sample scenes + prompt citations. Future agents can search this.\n\nAlso open a follow-up bead:\n\n```bash\ncd $HOME\u002Fyour-project.com && br create \"\u003Cone-line summary>\" \\\n  --type bug --priority 2 --description \"\u003Cfile paths + line numbers + link to wiki page>\"\n```\n\n## Pitfalls (this list IS the skill — review before running)\n\n10. **Don't de-duplicate by title** — \"Bran the broken\" and \"Bran the broken (ignore directive)\" are intentionally distinct campaigns the user is running. De-dup only on `campaign_id`.\n11. **Campaign doc `name` vs `title`** — the campaign-level document uses `title` (not `name`) for real-user campaigns. A `.where(\"name\", \"==\", ...)` query returns 0 hits even when the campaign exists. See `references\u002Fcampaign-doc-field-naming.md` and always read `cd.get(\"title\") or cd.get(\"name\")`. Verified 2026-07-15, $USER's account.\n12. **User-named lookup ≠ literal title** — \"the Danerys campaign in Meereen\" is almost never a literal title match; use the Phase 8 three-step recipe (title pre-filter → scene-level keyword confirmation → opening-scene verification). Don't burn a clarifying menu on the user when the top match is 95% likely correct.\n2. **Mixed timestamp types** — `DatetimeWithNanoseconds` vs `int` epoch vs `float` epoch-millis. Normalize via the `norm()` helper before sorting. Sorting raw fails with `TypeError: '\u003C' not supported`.\n3. **`\u002Ftmp` is sandbox-scoped per `execute_code` call** — write artifacts to `~\u002F.hermes\u002F\u003Ctopic>_\u003Cdate>\u002F` or `~\u002Fllm_wiki\u002Fwiki\u002Fsources\u002F` instead. Path returned by one execute_code call is gone in the next.\n4. **f-string `{VAR}` in `execute_code`** — the sandbox f-string parser doesn't handle braces inside strings used inside an f-string literal. Write the wiki content via `write_file` (cleanest) or escape `{{`\u002F`}}` everywhere.\n5. **Per-campaign PC name resolution** — for accurate NAME_COLON\u002FVERB_DIALOG attribution you need `player_character_data.name` from each campaign's `game_states\u002Fcurrent_state`. Without it, all NAME_COLON lines fall to NPC counter and inflate the npc count. Some campaigns have None for pc_name; fall back to \"unknown PC\" and accept the inflated NPC count.\n6. **First-person PC classifier misses third-person PC speech** — fine for PC-silent analysis (median stays 0), bad for quantifying how much PC *does* speak. If you need precise PC speech counts, sample 10-20 scenes manually.\n7. **Test users pollute the data** — same as `wa-prod-data-query` Pitfall 3. For $USER's account this is mostly fine (we filter by `uid`), but if you ever broaden to multi-uid scans, apply the test-user filter (emails containing `test`, `anon`, `dev-runner`, `example.com`, `jleechantest`).\n8. **Schema field drift** — story-doc schema has evolved over time. Older campaigns may use `narrative_text` instead of `text`, `created_at` instead of `timestamp`, `part` instead of `id`. Normalize field reads: `text = d.get(\"scene_text\") or d.get(\"narrative_text\") or d.get(\"text\") or d.get(\"content\")`. Same fallback chain for timestamps.\n9. **User-intent \"mode\" vs agent \"mode\"** — these are TWO DIFFERENT FIELDS with the same name. `story_doc.mode` is user intent. `agents.py` also uses `MODE` class constant for agent identity. Don't conflate them.\n10. **Don't de-duplicate by title** — \"Bran the broken\" and \"Bran the broken (ignore directive)\" are intentionally distinct campaigns the user is running. De-dup only on `campaign_id`.\n\n13. **Schema-zero story docs (`debug_info = {}`, `full_state_updates = {}`)** — verified 2026-07-26 on Visenya v9. Per-agent attribution falls back to \"unknown\" for *every* scene; per-agent histograms and per-agent percentages become meaningless. **Detection**: run a 5-doc sample probe before the full per-agent aggregation — if `(sample.get(\"debug_info\") or {}).get(\"agent_name\")` returns `None` for all 5, the campaign is schema-zero. **Fallback**: analyze the raw `.txt` export at `~\u002Fllm_wiki\u002Fraw\u002Fcampaigns\u002F\u003Cid8>\u002F\u003Ctitle>_\u003Cid8>.txt` (use `download-campaign` first). The raw text has `====== SCENE N ======` delimiters and `Status: Lvl N ...` headers per scene. Patterns documented in `references\u002Fpersonal-scale-challenge-pattern.md`. Reporting fabricated per-agent percentages (e.g. \"HeavyDialogAgent: 25-30%\") when the underlying `debug_info` is empty is dishonest analysis, not a number to summarize.\n\n## Sample driver script\n\nSee `scripts\u002Fper_scene_dialog_audit.py` (in this skill) for a working end-to-end implementation:\n\n- Pulls last N campaigns ≥ M scenes\n- Streams `story` subcollection per campaign in ASC timestamp order\n- Classifies each gemini scene via `count_dialog()`\n- Aggregates per-agent\n- Writes summary JSON + JSONL dump\n\n## Related\n\n- `download-campaign` — exports a single campaign (or batch) to disk. Use when the user wants to *read* campaign content; this skill is for *analyzing* content in place.\n- `wa-prod-data-query` — real-user engagement\u002Fretention reports. Wrong domain (user activity, not scene content).\n- `repro` — single-bug repro for one specific user-reported scene. This skill is the cross-campaign version.\n- `references\u002Fpc-silent-prompt-diagnosis.md` — worked example of taking a per-agent breakdown (\"PC silent 67%\") and tracing it to specific prompt lines.\n- `references\u002Fprompt-fix-effectiveness-verification.md` — verification recipe for AFTER a prompt fix has shipped: pre\u002Fpost comparison, regex tightening (NPC-attributed quotes require `\"...\"` AFTER speech verb), and 5-cause taxonomy for \"PR merged but LLM still not following.\"\n- `references\u002Fpersonal-scale-challenge-pattern.md` — when the LLM auto-escalates to mythic-tier antagonists as the PC scales past the parity band; prompt-only fixes to preserve personal-scale challenge at high tier. Includes the five-prompt-edit recipe (Tier Compression, Consequence-Hiding Heuristic, mythic-NPC personhood, Force-a-Trade, anti-creep on major events) and the regex patterns for measuring personal-scale challenge density from raw text.\n- `references\u002Fvisenya-v9-raw-text-analyzer.md` — pipeline reference for analyzing a campaign whose `debug_info` is empty; walks through `\u002Ftmp\u002Fanalyze_visenya_v9_v2.py` style implementation against the `download-campaign` raw `.txt` export.\n\n## Tests\n\n- `tests\u002Ftest_dialog_classifier.py` — quote \u002F name-colon \u002F verb-indirect attribution, dedupe, first-person PC classification, mechanic-label skip.\n- `tests\u002Ftest_agent_attribution.py` — verify `debug_info.agent_name` precedence over `mode` field.\n- `scripts\u002Ftest_user_named_campaign_lookup.py` — Phase 8 three-step recipe (`get_campaign_title`, `title_prefilter`, `keyword_scan`, `confirm_opening_scene`) + the campaign-level `name` vs `title` field fallback + the \"guess and verify, no clarification menu\" output contract.\n\nRun: `cd ~\u002F.hermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis && python3 -m unittest discover -s tests && python3 scripts\u002Ftest_user_named_campaign_lookup.py`\n\nRun: `cd ~\u002F.hermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis && python3 -m unittest discover -s tests`",{"name":5,"context":64,"arguments":65,"description":7,"when_to_use":67,"allowed-tools":68,"argument-hint":69},"inline",[43,66],"campaign_filter","Use when the user says: analyze the last N campaigns, review dialog quality, audit NPC behavior, regression review, per-scene analysis, agent attribution, why does the LLM X in my campaigns, do all the dialog scenes have Y, find scenes where Z is missing, per-agent breakdown. Do NOT use for: downloading\u002Fexporting single campaigns (use download-campaign); real-user activity\u002Fretention reports (use wa-prod-data-query); single-bug repros (use repro).","terminal, file","[\u003Canalysis target>] [--last N] [--min-entries M] [--since-days D]","main","05df7380981a2c4af868ce0fa57962ae0eea62a9","hermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis",0,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills","https:\u002F\u002Fgithub.com\u002Fjleechanorg","2026-11-14 14:55:35",{"source":9,"skillName":5,"commands":78,"prompt":88,"zipAvailable":89},[79,82,85],{"tool":80,"command":81},"npx","npx skills add jleechanorg\u002Fjleechan-skills --skill wa-campaign-content-analysis",{"tool":83,"command":84},"bunx","bunx skills add jleechanorg\u002Fjleechan-skills --skill wa-campaign-content-analysis",{"tool":86,"command":87},"pnpm","pnpm dlx skills add jleechanorg\u002Fjleechan-skills --skill wa-campaign-content-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002FSKILL.md",true,[91,97,101,105,109,113,117,123],{"path":92,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":95,"sourceHtmlUrl":96},"references\u002Fcampaign-doc-field-naming.md","REFERENCE","参考文档",3618,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Freferences\u002Fcampaign-doc-field-naming.md",{"path":98,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":99,"sourceHtmlUrl":100},"references\u002Fpc-silent-prompt-diagnosis.md",7500,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Freferences\u002Fpc-silent-prompt-diagnosis.md",{"path":102,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":103,"sourceHtmlUrl":104},"references\u002Fpersonal-scale-challenge-pattern.md",14474,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Freferences\u002Fpersonal-scale-challenge-pattern.md",{"path":106,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":107,"sourceHtmlUrl":108},"references\u002Fprompt-fix-effectiveness-verification.md",11800,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Freferences\u002Fprompt-fix-effectiveness-verification.md",{"path":110,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":111,"sourceHtmlUrl":112},"references\u002Fstory-doc-schema.md",6353,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Freferences\u002Fstory-doc-schema.md",{"path":114,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":115,"sourceHtmlUrl":116},"references\u002Fvisenya-v9-raw-text-analyzer.md",8666,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Freferences\u002Fvisenya-v9-raw-text-analyzer.md",{"path":118,"resourceType":119,"resourceTypeDesc":120,"sizeBytes":121,"sourceHtmlUrl":122},"scripts\u002Fper_scene_dialog_audit.py","SCRIPT","脚本",11824,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Fscripts\u002Fper_scene_dialog_audit.py",{"path":124,"resourceType":119,"resourceTypeDesc":120,"sizeBytes":125,"sourceHtmlUrl":126},"scripts\u002Ftest_user_named_campaign_lookup.py",5992,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fworldarchitect\u002Fwa-campaign-content-analysis\u002Fscripts\u002Ftest_user_named_campaign_lookup.py",[128,136,143,151,159,168],{"skillNo":129,"name":130,"nameZh":13,"description":131,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":132,"categories":133,"keywords":134,"publishedAt":135},"01M7DRVZXXMGY4G81K5GVF4V20","disk-reclaim-playbook","Use Disk Magician to diagnose disk growth or qualify cleanup on macOS or Linux.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdisk-reclaim-playbook\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":137,"name":138,"nameZh":13,"description":139,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":140,"categories":141,"keywords":142,"publishedAt":135},"01M7B63PNTT2TY78RFKHD8SP3X","claudea-bench","Compare `claudea` and normal `claude` on a fair split of comparable work by default; use `--strict` for duplicate runs of the exact same task.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fclaudea-bench\u002FSKILL.md",[],[],{"skillNo":144,"name":145,"nameZh":13,"description":146,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":150},"01M7622KQJ32AV4K5BXEMVSSEB","pr","Alias for the canonical pr-lifecycle PR workflow skill (\u002Fpr-workflow, \u002Fprw).","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"skillNo":152,"name":153,"nameZh":13,"description":154,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":155,"categories":156,"keywords":157,"publishedAt":158},"01M7432W92AKC4D1TKJ00VCMMT","whisper","OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fwhisper\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":160,"name":161,"nameZh":13,"description":162,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":163,"licenseFileUrl":164,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":158},"01M7432T6BN1A9SHB8RBQR5EMP","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":169,"name":170,"nameZh":13,"description":171,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":172,"categories":173,"keywords":174,"publishedAt":158},"01M7432NDC7S6C6MX7M6RW8CTT","pr-report","This skill should be used when the user asks for a PR report, PR audit, PR delta analysis, \u002Fpr-report, or wants per-PR summary with delta files\u002Flines. Generates a structured report for one or more open PRs covering purpose, files changed, +\u002F− line counts, \u002Fcode-standards + \u002Fthermo review findings, \u002Fponytail simplification opportunities, file-overlap combination candidates, and \u002Fgreen status per pr-green-definition. Output: machine-readable JSONL + human-readable markdown. Read-only by default; can apply simplifications if user opts in.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fpr-report\u002FSKILL.md",[],[]]