1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  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
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
We'll create a Python script that converts an existing `ex-skill` repository into the updated `forum-skill` fork. The script is self‑contained, idempotent, and works on Windows, Linux, and macOS. It overwrites files with the new versions, deletes obsolete parsers, and creates the new wrapper script.

```python
#!/usr/bin/env python3
"""
convert_to_forum_skill.py

Fully converts a clone of the original ex-skill repository into the updated
forum-skill (for XenForo user cloning). The script is idempotent and can be
run multiple times.

Usage:
    python convert_to_forum_skill.py [--target-dir PATH]

If --target-dir is omitted, the current working directory is used.
"""

import os
import sys
import shutil
import argparse
from pathlib import Path

# ----------------------------------------------------------------------
# New file contents (embedded as raw strings)
# ----------------------------------------------------------------------

FILES = {
    "requirements_forum.txt": """
# Forum Skill Dependencies

# Core scraping and parsing
forumscraper>=1.0.0,<2.0.0
beautifulsoup4>=4.12.0
requests>=2.31.0
cloudscraper>=1.2.0

# Analysis
nltk>=3.8.0
scikit-learn>=1.3.0

# Utility
python-dateutil>=2.8.2
portalocker>=2.7.0

# Testing (optional)
pytest>=7.0.0
pytest-mock>=3.0.0
""",

    "tools/forum_scraper.py": """\"\"\"
XenForo Forum Scraper – downloads public posts, profile, and social interactions.
\"\"\"

import argparse
import json
import os
import sys
import time
import random
import re
from dataclasses import dataclass, asdict
from datetime import datetime
from typing import List, Optional, Dict, Any, Tuple

try:
    import portalocker
except ImportError:
    portalocker = None
    print("Warning: portalocker not installed. Checkpoint may be unsafe.")

try:
    import requests
    from bs4 import BeautifulSoup
    HAS_FALLBACK = True
except ImportError:
    HAS_FALLBACK = False

try:
    import cloudscraper
    HAS_CLOUDSCRAPER = True
except ImportError:
    HAS_CLOUDSCRAPER = False


@dataclass
class UserProfile:
    id: int
    username: str
    joinDate: str
    postCount: int
    reactionScore: int
    avatarUrl: Optional[str] = None
    signature: Optional[str] = None
    about: Optional[str] = None


@dataclass
class Post:
    id: int
    threadId: int
    threadTitle: str
    forumId: int
    forumName: str
    content: str
    timestamp: str
    reactions: Dict[str, int]
    isOp: bool
    parentPostId: Optional[int] = None
    mentions: List[str] = None


@dataclass
class Corpus:
    user: UserProfile
    posts: List[Post]
    threadsStarted: List[int]
    repliesReceived: List[int]
    scraped_at: str


class CloudflareException(Exception):
    pass


class ForumScraper:
    def __init__(self, forum_url: str, output_dir: str, max_posts: int = 5000,
                 cookie_file: Optional[str] = None, rate_limit: float = 1.0):
        self.forum_url = forum_url.rstrip('/')
        self.output_dir = output_dir
        self.max_posts = max_posts
        self.cookie_file = cookie_file
        self.rate_limit = rate_limit
        self.session = None
        self.cookies = None
        self.seen_post_ids = set()
        self.checkpoint_file = None
        self.last_page = 0
        self.stored_max_posts = max_posts

        os.makedirs(output_dir, exist_ok=True)
        self.corpus_dir = os.path.join(output_dir, 'corpus')
        os.makedirs(self.corpus_dir, exist_ok=True)
        self.checkpoint_file = os.path.join(self.corpus_dir, 'checkpoint.json')

        if cookie_file and os.path.exists(cookie_file):
            self._load_cookies(cookie_file)

        if HAS_FALLBACK:
            if HAS_CLOUDSCRAPER:
                self.session = cloudscraper.create_scraper()
            else:
                self.session = requests.Session()
            if self.cookies:
                self.session.cookies.update(self.cookies)

    def _load_cookies(self, cookie_file: str) -> None:
        try:
            import http.cookiejar as cookielib
            cj = cookielib.MozillaCookieJar()
            cj.load(cookie_file, ignore_expires=True, ignore_discard=True)
            self.cookies = {c.name: c.value for c in cj}
        except Exception as e:
            print(f"Warning: Could not load cookies from {cookie_file}: {e}")

    def _resolve_username_to_id(self, username: str) -> int:
        candidates = []
        profile_urls = [
            f"{self.forum_url}/members/{username}/",
            f"{self.forum_url}/members/{username}",
        ]
        for url in profile_urls:
            response = self._fetch_url(url)
            if response and response.status_code == 200:
                soup = BeautifulSoup(response.text, 'html.parser')
                link = soup.find('a', href=re.compile(r'/members/.*\.\d+/'))
                if link:
                    href = link.get('href')
                    match = re.search(r'/members/.*\.(\d+)/', href)
                    if match:
                        candidates.append(int(match.group(1)))
                meta = soup.find('meta', {'property': 'og:url'})
                if meta:
                    url_content = meta.get('content', '')
                    match = re.search(r'/members/.*\.(\d+)/', url_content)
                    if match:
                        candidates.append(int(match.group(1)))
        if not candidates:
            search_url = f"{self.forum_url}/search/member?user_id=0&username={username}"
            sr = self._fetch_url(search_url)
            if sr and sr.status_code == 200:
                soup = BeautifulSoup(sr.text, 'html.parser')
                for link in soup.find_all('a', href=True):
                    if '/members/' in link['href']:
                        match = re.search(r'/members/.*\.(\d+)/', link['href'])
                        if match:
                            candidates.append(int(match.group(1)))
        candidates = list(set(candidates))
        if not candidates:
            sys.exit(f"ERROR: User '{username}' not found on {self.forum_url}.")
        if len(candidates) > 1:
            print(f"Found multiple users with username '{username}':")
            for idx, uid in enumerate(candidates):
                prof_url = f"{self.forum_url}/members/{uid}/"
                resp = self._fetch_url(prof_url)
                join_date = "unknown"
                if resp and resp.status_code == 200:
                    soup = BeautifulSoup(resp.text, 'html.parser')
                    for dl in soup.find_all('dl', class_='pairs pairs--justified'):
                        dt = dl.find('dt')
                        dd = dl.find('dd')
                        if dt and dd and 'Joined' in dt.text:
                            join_date = dd.text.strip()
                            break
                print(f"  {idx+1}. ID {uid} (joined {join_date})")
            while True:
                choice = input("Enter the number of the correct user: ")
                try:
                    idx = int(choice) - 1
                    if 0 <= idx < len(candidates):
                        return candidates[idx]
                except ValueError:
                    pass
                print("Invalid choice, please try again.")
        return candidates[0]

    def _fetch_url(self, url: str) -> Optional[requests.Response]:
        if not HAS_FALLBACK:
            raise RuntimeError("requests and beautifulsoup4 are required.")
        attempt = 0
        max_attempts = 5
        while attempt < max_attempts:
            try:
                time.sleep(self.rate_limit)
                resp = self.session.get(url, timeout=30)
                if 'cf-browser-verification' in resp.text or 'cf-challenge' in resp.text:
                    if HAS_CLOUDSCRAPER:
                        print("Cloudflare detected; retrying with cloudscraper...")
                        self.session = cloudscraper.create_scraper()
                        resp = self.session.get(url, timeout=30)
                        if 'cf-browser-verification' not in resp.text:
                            return resp
                    raise CloudflareException(
                        "Cloudflare challenge could not be bypassed. "
                        "Please provide cookies with --cookie-file."
                    )
                if resp.status_code == 403 and 'login' in resp.text.lower():
                    print("ERROR: Profile is private or requires login.")
                    print("Please provide cookies with --cookie-file or try manual entry.")
                    sys.exit(3)
                if resp.status_code in (429, 503):
                    wait = (2 ** attempt) + random.uniform(0, 1)
                    print(f"Rate limit (status {resp.status_code}), waiting {wait:.2f}s...")
                    time.sleep(wait)
                    attempt += 1
                    continue
                if resp.status_code >= 500:
                    wait = (2 ** attempt) + random.uniform(0, 1)
                    print(f"Server error {resp.status_code}, retrying in {wait:.2f}s...")
                    time.sleep(wait)
                    attempt += 1
                    continue
                if resp.status_code == 404:
                    return None
                if resp.status_code != 200:
                    print(f"Unexpected status {resp.status_code} for {url}")
                    return None
                return resp
            except CloudflareException:
                raise
            except Exception as e:
                print(f"Request failed: {e}")
                attempt += 1
                if attempt >= max_attempts:
                    raise
                time.sleep(2 ** attempt)
        return None

    def _scrape_with_fallback(self, user_id: int) -> Tuple[UserProfile, List[Post]]:
        if not HAS_FALLBACK:
            raise ImportError("requests and beautifulsoup4 required.")
        profile_url = f"{self.forum_url}/members/{user_id}/"
        resp = self._fetch_url(profile_url)
        if not resp or resp.status_code != 200:
            sys.exit(f"ERROR: Cannot fetch profile for user ID {user_id}.")
        soup = BeautifulSoup(resp.text, 'html.parser')

        username = soup.find('h1', class_='p-title-value')
        if username:
            username = username.text.strip()
        else:
            title = soup.find('title')
            if title:
                username = title.text.split('|')[0].strip()
        if not username:
            username = f"user_{user_id}"

        stats = {}
        for dl in soup.find_all('dl', class_='pairs pairs--justified'):
            dt = dl.find('dt')
            dd = dl.find('dd')
            if dt and dd:
                key = dt.text.strip()
                value = dd.text.strip()
                stats[key] = value
        if 'Messages' not in stats:
            msg_match = re.search(r'Messages:\s*([\d,]+)', resp.text)
            if msg_match:
                stats['Messages'] = msg_match.group(1)
        if 'Reaction score' not in stats:
            react_match = re.search(r'Reaction score:\s*([\d,]+)', resp.text)
            if react_match:
                stats['Reaction score'] = react_match.group(1)

        join_date = stats.get('Joined', '')
        post_count = int(re.sub(r'[^\d]', '', stats.get('Messages', '0'))) if stats.get('Messages') else 0
        reaction_score = int(re.sub(r'[^\d]', '', stats.get('Reaction score', '0'))) if stats.get('Reaction score') else 0

        avatar_img = soup.find('img', class_='avatar')
        avatar_url = avatar_img.get('src') if avatar_img else None

        signature_div = soup.find('div', class_='signature')
        signature = signature_div.text.strip() if signature_div else None

        about_div = soup.find('div', class_='about')
        about = about_div.text.strip() if about_div else None

        profile = UserProfile(
            id=user_id,
            username=username,
            joinDate=join_date,
            postCount=post_count,
            reactionScore=reaction_score,
            avatarUrl=avatar_url,
            signature=signature,
            about=about
        )

        feed_urls = [
            f"{self.forum_url}/members/{user_id}/post-activity",
            f"{self.forum_url}/members/{user_id}/recent-content",
            f"{self.forum_url}/search/member?user_id={user_id}"
        ]
        used_url = None
        for url_template in feed_urls:
            test_url = url_template if '?' in url_template else f"{url_template}?page=1"
            resp = self._fetch_url(test_url)
            if resp and resp.status_code == 200:
                used_url = url_template
                break
        if not used_url:
            sys.exit("ERROR: Could not find a working posts feed for this user.")
        print(f"Using posts feed: {used_url}")

        posts = []
        page = 1
        self.last_page = 1
        seen_thread_ids = set()

        while len(posts) < self.max_posts:
            if self._load_checkpoint():
                page = self.last_page + 1
                print(f"Resuming from page {page}")
            if '?' in used_url:
                page_url = f"{used_url}&page={page}" if 'page=' not in used_url else f"{used_url}&page={page}"
            else:
                page_url = f"{used_url}?page={page}"
            resp = self._fetch_url(page_url)
            if not resp or resp.status_code != 200:
                break
            soup = BeautifulSoup(resp.text, 'html.parser')

            selectors = ['div.block-row', 'article', 'li.searchResult', 'div.message']
            post_entries = []
            for sel in selectors:
                entries = soup.select(sel)
                if entries:
                    post_entries = entries
                    break
            if not post_entries:
                break

            for entry in post_entries:
                post_link = entry.find('a', href=re.compile(r'/posts/\d+'))
                if not post_link:
                    continue
                post_id_match = re.search(r'/posts/(\d+)', post_link['href'])
                if not post_id_match:
                    continue
                post_id = int(post_id_match.group(1))
                if post_id in self.seen_post_ids:
                    continue
                self.seen_post_ids.add(post_id)

                thread_link = entry.find('a', href=re.compile(r'/threads/'))
                if not thread_link:
                    continue
                thread_title = thread_link.text.strip()
                thread_id_match = re.search(r'/threads/.*\.(\d+)/', thread_link['href'])
                if not thread_id_match:
                    continue
                thread_id = int(thread_id_match.group(1))

                forum_link = entry.find('a', href=re.compile(r'/forums/'))
                forum_name = forum_link.text.strip() if forum_link else ''
                forum_id_match = re.search(r'/forums/.*\.(\d+)/', forum_link['href']) if forum_link else None
                forum_id = int(forum_id_match.group(1)) if forum_id_match else 0

                content_div = entry.find('div', class_='message-content')
                if not content_div:
                    content_div = entry.find('div', class_='message-body')
                if not content_div:
                    content_div = entry.find('blockquote')
                content = content_div.text.strip() if content_div else ''

                time_tag = entry.find('time')
                timestamp = time_tag.get('datetime') if time_tag else datetime.now().isoformat()

                reactions = {}
                reaction_spans = entry.find_all('span', class_=re.compile(r'reaction--'))
                for rspan in reaction_spans:
                    reaction_type = rspan.get('data-reaction-id')
                    if not reaction_type:
                        class_attr = rspan.get('class', [])
                        for cls in class_attr:
                            if cls.startswith('reaction--'):
                                reaction_type = cls.split('--')[1]
                                break
                    if reaction_type:
                        count_span = rspan.find_previous_sibling('span', class_='reactionScore')
                        if count_span:
                            try:
                                count = int(re.sub(r'[^\d]', '', count_span.text))
                            except:
                                count = 1
                        else:
                            count = 1
                        reactions[reaction_type] = count
                if not reactions:
                    reaction_span = entry.find('span', class_='reactionScore')
                    if reaction_span:
                        text = reaction_span.text.strip()
                        if text:
                            reactions['like'] = int(re.sub(r'[^\d]', '', text))

                is_op = False
                if thread_id not in seen_thread_ids:
                    is_op = True
                    seen_thread_ids.add(thread_id)

                parent_post_id = None
                reply_link = entry.find('a', href=re.compile(r'/posts/\d+'), class_='u-replyTo')
                if reply_link:
                    parent_match = re.search(r'/posts/(\d+)', reply_link['href'])
                    if parent_match:
                        parent_post_id = int(parent_match.group(1))

                mentions = re.findall(r'@(\w+)', content)

                post = Post(
                    id=post_id,
                    threadId=thread_id,
                    threadTitle=thread_title,
                    forumId=forum_id,
                    forumName=forum_name,
                    content=content,
                    timestamp=timestamp,
                    reactions=reactions,
                    isOp=is_op,
                    parentPostId=parent_post_id,
                    mentions=mentions
                )
                posts.append(post)
                if len(posts) >= self.max_posts:
                    break

            self._save_checkpoint(page)
            self.last_page = page
            page += 1

            next_link = soup.find('a', rel='next')
            if not next_link:
                break

        return profile, posts

    def _save_checkpoint(self, page: int):
        data = {
            'last_page': page,
            'seen_post_ids': list(self.seen_post_ids),
            'max_posts': self.max_posts,
            'forum_url': self.forum_url
        }
        if portalocker:
            with open(self.checkpoint_file, 'w') as f:
                portalocker.lock(f, portalocker.LOCK_EX)
                json.dump(data, f)
                portalocker.unlock(f)
        else:
            with open(self.checkpoint_file, 'w') as f:
                json.dump(data, f)

    def _load_checkpoint(self) -> bool:
        if os.path.exists(self.checkpoint_file):
            try:
                if portalocker:
                    with open(self.checkpoint_file, 'r') as f:
                        portalocker.lock(f, portalocker.LOCK_SH)
                        data = json.load(f)
                        portalocker.unlock(f)
                else:
                    with open(self.checkpoint_file, 'r') as f:
                        data = json.load(f)
                self.last_page = data.get('last_page', 0)
                self.seen_post_ids = set(data.get('seen_post_ids', []))
                stored_max = data.get('max_posts', self.max_posts)
                if stored_max != self.max_posts:
                    self.max_posts = min(stored_max, self.max_posts)
                stored_forum = data.get('forum_url')
                if stored_forum and stored_forum != self.forum_url:
                    print(f"Warning: checkpoint forum URL '{stored_forum}' differs from current '{self.forum_url}'.")
                return True
            except Exception as e:
                print(f"Could not load checkpoint: {e}")
                return False
        return False

    def scrape(self, user_id: Optional[int] = None, username: Optional[str] = None) -> Corpus:
        if username and not user_id:
            user_id = self._resolve_username_to_id(username)
        elif not user_id:
            sys.exit("ERROR: No user ID or username provided.")

        try:
            profile, posts = self._scrape_with_fallback(user_id)
        except CloudflareException as e:
            print(f"ERROR: {e}")
            print("Please provide a cookie file via --cookie-file and try again.")
            sys.exit(2)
        except Exception as e:
            print(f"Scraping failed: {e}")
            sys.exit(1)

        if not profile:
            sys.exit("ERROR: Failed to scrape user profile.")

        threads_started = [p.threadId for p in posts if p.isOp]

        corpus = Corpus(
            user=profile,
            posts=posts,
            threadsStarted=threads_started,
            repliesReceived=[],
            scraped_at=datetime.now().isoformat()
        )

        corpus_path = os.path.join(self.corpus_dir, 'raw_corpus.json')
        with open(corpus_path, 'w', encoding='utf-8') as f:
            json.dump(self._corpus_to_dict(corpus), f, indent=2, ensure_ascii=False)

        meta = {
            'low_confidence': len(posts) < 50,
            'banned': False,
            'post_count': len(posts),
            'scraped_at': corpus.scraped_at,
            'forum_url': self.forum_url
        }
        if profile.about and 'banned' in profile.about.lower():
            meta['banned'] = True
        if profile.signature and 'banned' in profile.signature.lower():
            meta['banned'] = True
        meta_path = os.path.join(self.corpus_dir, 'meta.json')
        with open(meta_path, 'w') as f:
            json.dump(meta, f, indent=2)

        print(f"Scraped {len(posts)} posts for user {profile.username} (ID {user_id})")
        if meta['low_confidence']:
            print("Warning: Low post count (<50) – persona may be less accurate.")
        if meta['banned']:
            print("Warning: User appears banned; data may be limited.")

        return corpus

    def _corpus_to_dict(self, corpus: Corpus) -> Dict:
        return {
            'user': asdict(corpus.user),
            'posts': [asdict(p) for p in corpus.posts],
            'threadsStarted': corpus.threadsStarted,
            'repliesReceived': corpus.repliesReceived,
            'scraped_at': corpus.scraped_at
        }


def main():
    parser = argparse.ArgumentParser(description='XenForo Forum Scraper')
    parser.add_argument('--forum', required=True, help='Forum base URL (e.g., https://www.thecoli.com)')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--username', help='Target username')
    group.add_argument('--userid', type=int, help='Target user ID')
    parser.add_argument('--output', required=True, help='Output directory')
    parser.add_argument('--max-posts', type=int, default=5000, help='Maximum posts to scrape (default: 5000)')
    parser.add_argument('--cookie-file', help='Path to cookies.txt (Netscape format)')
    parser.add_argument('--rate', type=float, default=1.0, help='Rate limit in seconds per request (default: 1.0)')
    parser.add_argument('--resume', action='store_true', help='Resume from last checkpoint')

    args = parser.parse_args()

    scraper = ForumScraper(
        forum_url=args.forum,
        output_dir=args.output,
        max_posts=args.max_posts,
        cookie_file=args.cookie_file,
        rate_limit=args.rate
    )

    if args.resume:
        scraper._load_checkpoint()

    if args.username:
        corpus = scraper.scrape(username=args.username)
    else:
        corpus = scraper.scrape(user_id=args.userid)

    summary_path = os.path.join(args.output, 'summary.txt')
    with open(summary_path, 'w') as f:
        f.write(f"Scraped user: {corpus.user.username} (ID: {corpus.user.id})\n")
        f.write(f"Posts: {len(corpus.posts)}\n")
        f.write(f"Joined: {corpus.user.joinDate}\n")
        f.write(f"Post count: {corpus.user.postCount}\n")
        f.write(f"Reaction score: {corpus.user.reactionScore}\n")
        f.write(f"Avatar: {corpus.user.avatarUrl}\n")
        f.write(f"Signature: {corpus.user.signature}\n")
        f.write(f"About: {corpus.user.about}\n")


if __name__ == '__main__':
    main()
""",

    "tools/forum_analyzer.py": """\"\"\"
Forum Post Analyzer – extracts statistical fingerprints from a corpus.
\"\"\"

import json
import os
import sys
import argparse
import re
from collections import Counter
from datetime import datetime
from statistics import mean, median, stdev
from typing import List, Dict, Any, Optional
from dateutil import parser as date_parser

try:
    import nltk
    from nltk.tokenize import word_tokenize, sent_tokenize
    HAS_NLTK = True
except ImportError:
    HAS_NLTK = False

try:
    from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
    from sklearn.decomposition import LatentDirichletAllocation
    HAS_SKLEARN = True
except ImportError:
    HAS_SKLEARN = False


class ForumAnalyzer:
    def __init__(self, corpus_path: str):
        self.corpus_path = corpus_path
        self.posts = []
        self.user = None
        self._load_corpus()

    def _load_corpus(self):
        with open(self.corpus_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        self.user = data.get('user', {})
        self.posts = data.get('posts', [])
        self.threads_started = data.get('threadsStarted', [])
        self.scraped_at = data.get('scraped_at', '')

    def analyze(self) -> Dict[str, Any]:
        default = {"writing": {}, "topic_affinity": {}, "temporal": {}, "interaction": {}}
        computed = {
            "writing": self._analyze_writing(),
            "topic_affinity": self._analyze_topics(),
            "temporal": self._analyze_temporal(),
            "interaction": self._analyze_interaction()
        }
        for key in default:
            default[key].update(computed.get(key, {}))
        return default

    def _analyze_writing(self) -> Dict:
        contents = [p.get('content', '') for p in self.posts if p.get('content')]
        if not contents:
            return {}
        full_text = ' '.join(contents)

        image_posts = [p for p in self.posts if p.get('content', '') and len(p.get('content', '')) < 10 and '[IMG]' in p.get('content', '')]
        image_post_count = len(image_posts)

        if HAS_NLTK:
            try:
                words = word_tokenize(full_text.lower())
                word_count = len(words)
                unique_words = len(set(words))
                ttr = unique_words / word_count if word_count > 0 else 0
                ttrs = []
                for content in contents:
                    w = word_tokenize(content.lower())
                    if len(w) > 0:
                        ttrs.append(len(set(w)) / len(w))
                moving_ttr = mean(ttrs) if ttrs else 0
            except Exception:
                ttr = 0
                moving_ttr = 0
        else:
            words = full_text.split()
            word_count = len(words)
            unique_words = len(set(words))
            ttr = unique_words / word_count if word_count > 0 else 0
            moving_ttr = 0

        if HAS_NLTK:
            sents = sent_tokenize(full_text)
            sent_lengths = [len(s.split()) for s in sents]
        else:
            sents = re.split(r'[.!?]', full_text)
            sent_lengths = [len(s.split()) for s in sents if s.strip()]
        avg_sent_len = mean(sent_lengths) if sent_lengths else 0
        med_sent_len = median(sent_lengths) if sent_lengths else 0
        std_sent_len = stdev(sent_lengths) if len(sent_lengths) > 1 else 0

        punct_counts = {
            'period': full_text.count('.'),
            'comma': full_text.count(','),
            'exclamation': full_text.count('!'),
            'question': full_text.count('?'),
            'ellipsis': full_text.count('...') + full_text.count('…')
        }

        all_caps_pattern = re.compile(r'\b[A-Z]{2,}\b')
        all_caps_words = all_caps_pattern.findall(full_text)
        total_words = len(full_text.split())
        caps_percent = (len(all_caps_words) / total_words * 100) if total_words > 0 else 0
        sentences = re.split(r'[.!?]', full_text)
        title_case = sum(1 for s in sentences if s.strip() and s.strip()[0].isupper())
        total_sentences = len([s for s in sentences if s.strip()])
        title_percent = (title_case / total_sentences * 100) if total_sentences > 0 else 0
        lower_sentences = sum(1 for s in sentences if s.strip() and s.strip().islower())
        lower_percent = (lower_sentences / total_sentences * 100) if total_sentences > 0 else 0

        emoji_pattern = re.compile(
            r'[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF'
            r'\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF'
            r'\U00002702-\U000027B0\U0000FE00-\U0000FE0F'
            r'\U0001F900-\U0001F9FF]', re.UNICODE
        )
        emojis = emoji_pattern.findall(full_text)
        emoji_counter = Counter(emojis)
        top_emojis = emoji_counter.most_common(10)

        top_bigrams = []
        top_trigrams = []
        if HAS_SKLEARN and len(contents) > 1:
            try:
                vectorizer = CountVectorizer(ngram_range=(2, 3), max_features=20, stop_words='english')
                X = vectorizer.fit_transform(contents)
                terms = vectorizer.get_feature_names_out()
                sums = X.sum(axis=0).A1
                sorted_terms = sorted(zip(terms, sums), key=lambda x: -x[1])
                top_bigrams = [term for term, count in sorted_terms if len(term.split()) == 2][:10]
                top_trigrams = [term for term, count in sorted_terms if len(term.split()) == 3][:10]
            except Exception:
                pass
        if not top_bigrams:
            words = full_text.split()
            bigrams = [' '.join(words[i:i+2]) for i in range(len(words)-1)]
            trigrams = [' '.join(words[i:i+3]) for i in range(len(words)-2)]
            bigram_counter = Counter(bigrams)
            trigram_counter = Counter(trigrams)
            top_bigrams = [bg for bg, c in bigram_counter.most_common(10)]
            top_trigrams = [tg for tg, c in trigram_counter.most_common(10)]

        slang_terms = ['cap', 'no cap', 'goat', 'mvp', 'lit', 'fire', 'dope', 'woke', 'sus', 'bet', 'facts']
        slang_counts = {term: full_text.lower().count(term) for term in slang_terms}

        year_stats = {}
        for post in self.posts:
            ts = post.get('timestamp', '')
            if ts:
                try:
                    dt = date_parser.parse(ts)
                    year = dt.year
                except:
                    continue
                if year not in year_stats:
                    year_stats[year] = []
                year_stats[year].append(post.get('content', ''))
        year_ttr = {}
        if HAS_NLTK:
            for year, contents in year_stats.items():
                text = ' '.join(contents)
                words = word_tokenize(text.lower())
                if len(words) > 0:
                    year_ttr[year] = len(set(words)) / len(words)
                else:
                    year_ttr[year] = 0

        return {
            "ttr": ttr,
            "moving_ttr": moving_ttr,
            "avg_sentence_length": avg_sent_len,
            "median_sentence_length": med_sent_len,
            "std_sentence_length": std_sent_len,
            "punctuation": punct_counts,
            "caps_percent": caps_percent,
            "title_case_percent": title_percent,
            "lowercase_sentences_percent": lower_percent,
            "top_emojis": top_emojis,
            "top_bigrams": top_bigrams,
            "top_trigrams": top_trigrams,
            "slang_counts": slang_counts,
            "yearly_ttr": year_ttr,
            "image_heavy_posts": image_post_count
        }

    def _analyze_topics(self) -> Dict:
        forum_counts = Counter([p.get('forumName', 'Unknown') for p in self.posts])
        total_posts = len(self.posts)
        forum_dist = {forum: count / total_posts if total_posts > 0 else 0 for forum, count in forum_counts.items()}

        topics_lda = []
        if HAS_SKLEARN and len(self.posts) > 10:
            try:
                docs = []
                for post in self.posts:
                    title = post.get('threadTitle', '')
                    content = post.get('content', '')
                    docs.append(title + " " + content)
                vectorizer = TfidfVectorizer(max_features=1000, stop_words='english')
                X = vectorizer.fit_transform(docs)
                lda = LatentDirichletAllocation(n_components=5, random_state=42)
                lda.fit(X)
                feature_names = vectorizer.get_feature_names_out()
                for topic_idx, topic in enumerate(lda.components_):
                    top_words = [feature_names[i] for i in topic.argsort()[-10:]]
                    topics_lda.append({"topic": topic_idx, "top_words": top_words})
            except Exception as e:
                print(f"LDA failed: {e}. Using TF-IDF fallback.")
                if HAS_SKLEARN:
                    tfidf = TfidfVectorizer(max_features=100, stop_words='english')
                    X = tfidf.fit_transform(docs)
                    terms = tfidf.get_feature_names_out()
                    sums = X.sum(axis=0).A1
                    sorted_terms = sorted(zip(terms, sums), key=lambda x: -x[1])[:20]
                    topics_lda = [{"topic": "common", "top_words": [t for t, c in sorted_terms[:10]]}]
        else:
            if HAS_SKLEARN and len(self.posts) > 1:
                docs = [p.get('content', '') for p in self.posts]
                tfidf = TfidfVectorizer(max_features=100, stop_words='english')
                X = tfidf.fit_transform(docs)
                terms = tfidf.get_feature_names_out()
                sums = X.sum(axis=0).A1
                sorted_terms = sorted(zip(terms, sums), key=lambda x: -x[1])[:20]
                topics_lda = [{"topic": "common", "top_words": [t for t, c in sorted_terms[:10]]}]
            else:
                topics_lda = []

        debate_topics = {
            'Kobe vs LeBron': ['kobe', 'lebron', 'goat', 'mvp'],
            'Drake': ['drake', 'rapper', 'overrated'],
            'NBA': ['nba', 'basketball', 'playoffs'],
            'Politics': ['trump', 'biden', 'democrat', 'republican'],
        }
        stances = {}
        for topic, keywords in debate_topics.items():
            counts = {}
            for post in self.posts:
                content = post.get('content', '').lower()
                for kw in keywords:
                    if kw in content:
                        counts[kw] = counts.get(kw, 0) + 1
            positive = ['good', 'great', 'best', 'awesome', 'love']
            negative = ['bad', 'worst', 'hate', 'terrible', 'overrated']
            pos_count = sum(1 for post in self.posts if any(word in post.get('content', '').lower() for word in positive))
            neg_count = sum(1 for post in self.posts if any(word in post.get('content', '').lower() for word in negative))
            stance = "neutral"
            if pos_count > neg_count * 1.5:
                stance = "positive"
            elif neg_count > pos_count * 1.5:
                stance = "negative"
            stances[topic] = {
                "keyword_counts": counts,
                "overall_stance": stance
            }

        return {
            "forum_distribution": forum_dist,
            "lda_topics": topics_lda,
            "stances": stances
        }

    def _analyze_temporal(self) -> Dict:
        timestamps = []
        for post in self.posts:
            ts = post.get('timestamp', '')
            if ts:
                try:
                    dt = date_parser.parse(ts)
                    timestamps.append(dt)
                except:
                    continue
        if not timestamps:
            return {}

        hours = [dt.hour for dt in timestamps]
        hour_counts = Counter(hours)
        hour_hist = [hour_counts.get(h, 0) for h in range(24)]

        days = [dt.weekday() for dt in timestamps]
        day_counts = Counter(days)
        day_percent = {day: day_counts.get(day, 0) / len(timestamps) for day in range(7)}

        if len(timestamps) > 1:
            first = min(timestamps)
            last = max(timestamps)
            delta = (last - first).days
            if delta == 0:
                avg_per_day = len(timestamps)
            else:
                avg_per_day = len(timestamps) / delta
            daily_counts = {}
            for dt in timestamps:
                date_key = dt.date()
                daily_counts[date_key] = daily_counts.get(date_key, 0) + 1
            daily_counts_list = list(daily_counts.values())
            daily_variance = stdev(daily_counts_list) if len(daily_counts_list) > 1 else 0
        else:
            avg_per_day = len(timestamps)
            daily_variance = 0

        return {
            "hour_histogram": hour_hist,
            "day_percentages": day_percent,
            "avg_posts_per_day": avg_per_day,
            "daily_variance": daily_variance
        }

    def _analyze_interaction(self) -> Dict:
        total_posts = len(self.posts)
        if total_posts == 0:
            return {}

        replies = [p for p in self.posts if p.get('isOp') == False]
        reply_ratio = len(replies) / total_posts if total_posts > 0 else 0
        warning = None
        if reply_ratio == 1.0 and total_posts > 0:
            warning = "reply_ratio may be inaccurate due to missing OP detection"

        mention_count = 0
        for post in self.posts:
            mention_count += len(post.get('mentions', []))
        mention_rate = mention_count / total_posts if total_posts > 0 else 0

        thread_ids = set(p.get('threadId', 0) for p in self.posts)
        depths = []
        for tid in thread_ids:
            if tid:
                thread_posts = [p for p in self.posts if p.get('threadId') == tid]
                depths.append(len(thread_posts))
        avg_depth = mean(depths) if depths else 0

        total_reactions = 0
        for post in self.posts:
            reactions = post.get('reactions', {})
            total_reactions += sum(reactions.values())
        avg_reactions_per_post = total_reactions / total_posts if total_posts > 0 else 0
        likes_received = sum(p.get('reactions', {}).get('like', 0) for p in self.posts)
        like_ratio = likes_received / total_posts if total_posts > 0 else 0

        result = {
            "reply_ratio": reply_ratio,
            "mention_rate": mention_rate,
            "avg_reply_depth": avg_depth,
            "avg_reactions_per_post": avg_reactions_per_post,
            "likes_per_post": like_ratio,
            "reactions_given": None
        }
        if warning:
            result["warning"] = warning
        return result


def main():
    parser = argparse.ArgumentParser(description='Analyze forum corpus')
    parser.add_argument('--corpus', required=True, help='Path to raw_corpus.json')
    parser.add_argument('--output', required=True, help='Output path for analysis_report.json')
    args = parser.parse_args()

    if not os.path.exists(args.corpus):
        print(f"ERROR: Corpus file not found: {args.corpus}")
        sys.exit(1)

    analyzer = ForumAnalyzer(args.corpus)
    report = analyzer.analyze()

    os.makedirs(os.path.dirname(args.output) or '.', exist_ok=True)

    with open(args.output, 'w', encoding='utf-8') as f:
        json.dump(report, f, indent=2, ensure_ascii=False)

    print(f"Analysis report written to {args.output}")


if __name__ == '__main__':
    main()
""",

    "tools/skill_writer.py": """\"\"\"
Skill Writer — generates runnable SKILL.md and manages user directories.
\"\"\"

import argparse
import os
import sys
import json
import shutil
from datetime import datetime


def list_users(base_dir: str):
    if not os.path.isdir(base_dir):
        print("No forum user Skills created yet.")
        return
    users = []
    for slug in sorted(os.listdir(base_dir)):
        meta_path = os.path.join(base_dir, slug, 'meta.json')
        if os.path.exists(meta_path):
            with open(meta_path, 'r', encoding='utf-8') as f:
                meta = json.load(f)
            users.append({
                'slug': slug,
                'name': meta.get('name', slug),
                'version': meta.get('version', '?'),
                'updated_at': meta.get('updated_at', '?'),
                'forum_url': meta.get('forum_url', '?'),
                'post_count': meta.get('post_count_analyzed', 0)
            })
    if not users:
        print("No forum user Skills found.")
        return
    print(f"Found {len(users)} forum user Skills:\\n")
    for u in users:
        print(f"  /user-{u['slug']}  —  {u['name']}")
        print(f"    Forum: {u['forum_url']}")
        print(f"    Posts analyzed: {u['post_count']}")
        print(f"    Version {u['version']} · Updated: {u['updated_at'][:10]}")
        print()


def init_user(base_dir: str, username: str):
    user_dir = os.path.join(base_dir, username)
    dirs = [
        os.path.join(user_dir, 'versions'),
        os.path.join(user_dir, 'sessions'),
        os.path.join(user_dir, 'corpus'),
    ]
    for d in dirs:
        os.makedirs(d, exist_ok=True)
    print(f"Initialized directory: {user_dir}")


def combine_skill(base_dir: str, username: str, skill_type: str = 'forum'):
    user_dir = os.path.join(base_dir, username)
    meta_path = os.path.join(user_dir, 'meta.json')
    presence_path = os.path.join(user_dir, 'forum_presence.md')
    persona_path = os.path.join(user_dir, 'persona.md')
    skill_path = os.path.join(user_dir, 'SKILL.md')

    if not os.path.exists(presence_path):
        print(f"ERROR: Required file '{presence_path}' not found.", file=sys.stderr)
        print("Please generate the forum presence document first using forum_presence_builder.md prompt.", file=sys.stderr)
        sys.exit(1)
    if not os.path.exists(persona_path):
        print(f"ERROR: Required file '{persona_path}' not found.", file=sys.stderr)
        print("Please generate the persona document first using persona_builder.md prompt.", file=sys.stderr)
        sys.exit(1)

    if not os.path.exists(meta_path):
        print(f"ERROR: meta.json not found at {meta_path}", file=sys.stderr)
        sys.exit(1)

    with open(meta_path, 'r', encoding='utf-8') as f:
        meta = json.load(f)

    with open(presence_path, 'r', encoding='utf-8') as f:
        presence_content = f.read()

    with open(persona_path, 'r', encoding='utf-8') as f:
        persona_content = f.read()

    name = meta.get('name', username)
    forum_url = meta.get('forum_url', 'unknown forum')
    description = f"{name} — forum user from {forum_url}"

    frontmatter = f\"\"\"---
name: forum-{username}
description: {description}
user-invocable: true
---
\"\"\"

    disclaimer = "**DISCLAIMER:** This is an AI simulation of a public forum user. It is not the actual person and is for personal, non‑commercial use only."

    skill_md = f\"\"\"{frontmatter}

{disclaimer}

# {name}

{description}

---

## PART A: Forum Presence

{presence_content}

---

## PART B: Persona

{persona_content}

---

## Running Rules (Adapted for forum context)

1. You are simulating `{name}`, not an AI assistant. Use their forum persona and writing style.
2. Part B (Persona) determines how to respond: attitude, tone, level of engagement.
3. Part A (Forum Presence) provides context: which topics to favor, which debates to engage.
4. Maintain all writing habits: vocabulary, sentence length, punctuation, emojis, catchphrases.
5. Layer 0 Hard Rules:
   - Do not claim knowledge outside observed topics.
   - Maintain consistent stances on debated issues.
   - Do not suddenly become overly friendly or supportive; preserve the original "edge".
   - If asked something outside their expertise, respond in character (e.g., "I don't post about that").
6. This is a simulation; never claim to be the real user.
\"\"\"
    with open(skill_path, 'w', encoding='utf-8') as f:
        f.write(skill_md)

    print(f"Generated SKILL.md at {skill_path}")


def delete_user(base_dir: str, username: str):
    user_dir = os.path.join(base_dir, username)
    if not os.path.exists(user_dir):
        print(f"User directory {user_dir} does not exist.")
        return
    print(f"WARNING: This will permanently delete all data for user '{username}'.")
    confirm = input("Type the username to confirm deletion: ")
    if confirm != username:
        print("Deletion cancelled.")
        return
    shutil.rmtree(user_dir)
    print(f"User '{username}' deleted.")


def main():
    parser = argparse.ArgumentParser(description='Forum User Skill Manager')
    parser.add_argument('--action', required=True, choices=['list', 'init', 'combine', 'delete'])
    parser.add_argument('--base-dir', default='./users', help='Base directory for user skills (default: ./users)')
    parser.add_argument('--username', help='Username/slug for the user')
    parser.add_argument('--type', choices=['ex', 'forum'], default='forum', help='Skill type (default: forum)')
    parser.add_argument('--forum-url', help='Forum URL for meta.json')
    parser.add_argument('--post-count', type=int, help='Number of posts analyzed for meta.json')

    args = parser.parse_args()

    if args.action == 'list':
        list_users(args.base_dir)
    elif args.action == 'init':
        if not args.username:
            print("ERROR: init requires --username", file=sys.stderr)
            sys.exit(1)
        init_user(args.base_dir, args.username)
        meta_path = os.path.join(args.base_dir, args.username, 'meta.json')
        if not os.path.exists(meta_path):
            meta = {
                "name": args.username,
                "slug": args.username,
                "version": "v1",
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat(),
                "forum_url": args.forum_url or "",
                "post_count_analyzed": args.post_count or 0,
                "scraped_at": datetime.now().isoformat()
            }
            with open(meta_path, 'w', encoding='utf-8') as f:
                json.dump(meta, f, indent=2)
            print(f"Created meta.json at {meta_path}")
    elif args.action == 'combine':
        if not args.username:
            print("ERROR: combine requires --username", file=sys.stderr)
            sys.exit(1)
        combine_skill(args.base_dir, args.username, args.type)
    elif args.action == 'delete':
        if not args.username:
            print("ERROR: delete requires --username", file=sys.stderr)
            sys.exit(1)
        delete_user(args.base_dir, args.username)


if __name__ == '__main__':
    main()
""",

    "create_forum_user.py": """#!/usr/bin/env python3
\"\"\"
Orchestrates the entire forum user creation pipeline in one command.

Usage:
    python3 create_forum_user.py --forum https://... --username Napoleon --output ./users/napoleon
\"\"\"

import argparse
import os
import sys
import subprocess

def main():
    parser = argparse.ArgumentParser(description='Create a forum user Skill end-to-end')
    parser.add_argument('--forum', required=True, help='Forum base URL')
    parser.add_argument('--username', required=True, help='Target username')
    parser.add_argument('--output', required=True, help='Output directory')
    parser.add_argument('--max-posts', type=int, default=1000, help='Maximum posts to scrape')
    parser.add_argument('--cookie-file', help='Path to cookies.txt')
    parser.add_argument('--rate', type=float, default=1.0, help='Rate limit')
    parser.add_argument('--resume', action='store_true', help='Resume scraping if checkpoint exists')
    args = parser.parse_args()

    print("=== Step 1: Scraping posts ===")
    scraper_cmd = [
        sys.executable, 'tools/forum_scraper.py',
        '--forum', args.forum,
        '--username', args.username,
        '--output', args.output,
        '--max-posts', str(args.max_posts),
        '--rate', str(args.rate)
    ]
    if args.cookie_file:
        scraper_cmd.extend(['--cookie-file', args.cookie_file])
    if args.resume:
        scraper_cmd.append('--resume')
    subprocess.run(scraper_cmd, check=True)

    print("\\n=== Step 2: Analyzing corpus ===")
    corpus_path = os.path.join(args.output, 'corpus', 'raw_corpus.json')
    analysis_path = os.path.join(args.output, 'analysis_report.json')
    analyzer_cmd = [
        sys.executable, 'tools/forum_analyzer.py',
        '--corpus', corpus_path,
        '--output', analysis_path
    ]
    subprocess.run(analyzer_cmd, check=True)

    print("\\n=== Step 3: Generate presence and persona ===")
    print("Now, in Claude Code, use the following prompts to generate the forum presence and persona.")
    print(f"1. Read the analysis report at: {analysis_path}")
    print("2. Use prompt `prompts/forum_analyzer.md` to interpret the data.")
    print("3. Use prompt `prompts/forum_presence_builder.md` to create `forum_presence.md` in the output directory.")
    print("4. Use prompt `prompts/persona_builder.md` to create `persona.md` in the output directory.")
    print("5. Then run the following command to combine them:")
    print(f"   python3 tools/skill_writer.py --action combine --username {os.path.basename(args.output)} --base-dir ./users")
    print(f"\\nAfter that, the Skill will be ready at {args.output}/SKILL.md")


if __name__ == '__main__':
    main()
""",

    "SKILL.md": """---
name: create-forum-user
description: Distill a XenForo forum user into an AI Skill. Scrape public posts, analyze writing style, generate Forum Presence + Persona.
argument-hint: [forum-username-or-slug]
version: 1.0.0
user-invocable: true
allowed-tools: Read, Write, Edit, Bash
---

# Forum User Skill Creator

## Trigger Conditions

When the user says any of the following:
- `/create-user`
- "Help me clone a forum user"
- "I want to recreate {username} from {forum}"
- "Make an AI version of {username}"

When user says `/list-users` – list all generated forum user Skills.
When user says `/delete-user {username}` – delete a user's data.

## Main Flow

### Step 1: Intake
Ask the questions from `prompts/intake.md`. Collect:
- Forum URL (required)
- Target username or user ID (required)
- Max posts (optional, default 1000)
- Specific subforums (optional)
- Known aliases (optional)

### Step 2: Run the automated pipeline
After collecting inputs, execute the wrapper script with the provided parameters:

```bash
python3 ${CLAUDE_SKILL_DIR}/create_forum_user.py  --forum "{forum_url}"  --username "{username}"  --output ./users/{slug}  --max-posts {max_posts}  --rate 1.0

If a cookie file is available, add --cookie-file {path}.

If the user provided user ID instead, use --userid {id} instead of --username.

What this script does automatically:

  1. Calls forum_scraper.py to download posts.
  2. Calls forum_analyzer.py to generate analysis_report.json.
  3. Instructs the user to generate presence and persona using the provided prompts.
  4. After the user generates those, they run skill_writer.py --action combine.

Step 3: Generate Part A (Forum Presence) and Part B (Persona)

After the scraper and analyzer complete, Claude must read analysis_report.json and generate forum_presence.md and persona.md using the prompts:

  • prompts/forum_analyzer.md – to interpret the stats.
  • prompts/forum_presence_builder.md – to write Part A.
  • prompts/persona_builder.md – to write Part B (5 layers).

Step 4: Combine into SKILL.md

Run:

python3 ${CLAUDE_SKILL_DIR}/tools/skill_writer.py  --action combine  --username {slug}  --base-dir ./users  --type forum

Step 5: Output

Inform the user:

1
2
3
4
5
6
7
8
✅ Forum User Skill created!

File location: ./users/{slug}/
Trigger: /user-{slug} (full Skill)
        /user-{slug}-presence (Part A only) – optional
        /user-{slug}-persona (Part B only) – optional

To chat with the simulated user, type /user-{slug}

Evolution Mechanisms

  • Correction Handler: User says "they wouldn't say that" – update persona/presence using correction_handler.md (unchanged logic).
  • Merger: New posts found – run forum_scraper.py --resume and then re‑analyze and merge using merger.md (unchanged).
  • Version Manager: Use version_manager.py (unchanged) for backups and rollback.

Management Commands

  • /list-users – list all users.
  • /delete-user {slug} – delete user data (confirmation required).

Legal/Ethical Notes

  • Only public data is scraped.
  • The generated Skill explicitly states it is a simulation.
  • Users have the right to be forgotten (delete command).
  • Rate limiting is enforced by default (1 request/s).
    """,

    "prompts/intake.md": """# Intake Questions for Forum User Cloning

You are creating a Skill that simulates a specific XenForo forum user. To gather the necessary information, ask the user the following questions. All fields except Forum URL and Target User are optional.

Question 1 (required): What is the forum URL?
Example: https://www.thecoli.com

Question 2 (required): Who is the target user? Provide either the username or user ID.
Example: username "Napoleon" or user ID "12345"

Question 3 (optional): How many posts should we analyze? (Default: 1000)
More posts improve fidelity but increase analysis time.

Question 4 (optional): Any specific subforums to focus on? (e.g., "The Booth", "Coliseum")
If omitted, we'll analyze all visible posts.

Question 5 (optional): Any known aliases or former usernames?
This helps if the user changed names.

After collecting answers, proceed to execute the scraper and analyzer.

Flow:

  1. Validate forum URL and target.
  2. Run forum_scraper.py with the provided parameters.
  3. Run forum_analyzer.py on the resulting corpus.
  4. Use the analysis report to generate Part A (Forum Presence) and Part B (Persona).
    """,

    "prompts/forum_analyzer.md": """# Forum Analyzer Prompt

You are given a JSON analysis report (analysis_report.json) extracted from a user's public posts. Your task is to interpret this data and produce a coherent description of the user's forum behavior and persona. This will be used to generate Part A (Forum Presence) and Part B (Persona).

Input: analysis_report.json with keys: writing, topic_affinity, temporal, interaction.

Instructions:

  1. Read the statistical values.
  2. Translate numbers into descriptive language. For example:
    • "ttr": 0.42 → "Moderate vocabulary diversity; the user varies their word choice."
    • "avg_sentence_length": 14.3 → "Typically writes medium-length sentences."
    • "reply_ratio": 0.8 → "Mostly replies to others rather than starting new threads."
  3. Identify contradictions (e.g., aggressive in one forum, helpful in another) and note them.
  4. Extract key phrases and slang from the top_bigrams, top_trigrams, and slang_counts.
  5. Note any temporal trends (e.g., writing style changed over time) from yearly_ttr.

Output: A narrative summary (2-3 paragraphs) that captures the essence of the user's forum presence. This summary will feed into the Forum Presence and Persona builders.

Example output:
"The user is a long-time member of The Coli, active primarily in The Booth and Coliseum. They post mostly in the evenings, with a spike on weekends. Their writing is conversational, using slang like 'no cap' and 'goat', and they frequently use emojis like 🔥 and 🗣️. They tend to reply rather than start threads, and they engage in debates about NBA and hip-hop with a contrarian streak."

Important: Base all descriptions solely on the data. Do not invent traits not supported by the analysis.
""",

"prompts/forum_presence_builder.md": """# Forum Presence Builder (Part A)

You are to generate the Forum Presence document (Part A) for a simulated forum user. Use the analysis report and the narrative summary to fill in the following sections.

Structure:

Active Subforums

List the subforums the user is most active in, with approximate percentages. Use the forum_distribution from the analysis.

Signature Topics

Identify specific threads or topics where the user has engaged deeply (e.g., "NBA GOAT debate", "Best hip-hop albums"). Use the threadsStarted and posts to infer.

Debate Patterns

Describe how the user engages in debates. Do they take contrarian stances? Are they aggressive or measured? Use stances from topic_affinity.stances.

Social Connections

Mention any users they frequently interact with (from mentions). If mention data is sparse, note that.

Meme/Reference Repertoire

List common phrases, slang, and inside jokes from top_bigrams, top_trigrams, and slang_counts.

Temporal Profile

Summarize posting habits: peak hours, days, frequency. Use temporal data.

Output Format: Markdown with clear headings. This will be inserted into the final SKILL.md.

Example:

## Active Subforums
- The Booth: 42%
- Coliseum: 28%
- Sports: 18%
- TLR: 12%

## Signature Topics
- NBA GOAT debate (Kobe vs LeBron)
- Drake's place in hip-hop history
- Best albums of 2024

## Debate Patterns
Contrarian on music; often argues that Drake is overrated. In sports, backs Kobe with stats.

## Meme/Reference Repertoire
- "No cap"
- "Goat"
- 🔥, 🗣️

## Temporal Profile
Peak posting around 10 PM - 2 AM EST; 3x more active on weekends.

""",

"prompts/persona_builder.md": """# Persona Builder (Part B) — 5‑Layer Structure for Forum Context

You are to generate the Forum Persona document (Part B) using the 5‑layer structure adapted from the original ex‑skill. Use the analysis report and the narrative summary.

Layer 0: Hard Rules
Derive from observed knowledge boundaries. For example:

  • Never claim expertise on topics not present in the user's posts.
  • Use vocabulary consistent with the user's observed range.
  • Adhere to any stances evidenced in the corpus.

Layer 1: Forum Identity

  • Username
  • Join date and tenure
  • Post count and reaction score
  • Signature and avatar description (if available)
  • Include a disclaimer: "This is an AI simulation of a public forum user, not the actual person."

Layer 2: Writing Fingerprint

  • Vocabulary level (high/medium/low) based on TTR.
  • Sentence style (short punchy, long winding, mixed).
  • Punctuation habits (heavy comma, ellipsis, etc.).
  • Emoji usage patterns (which emojis, frequency).
  • Capitalization style (all‑caps for emphasis, etc.).
  • Catchphrases and common phrases from top n‑grams.

Layer 3: Forum Persona

  • Humor style (sarcastic, dry, self‑deprecating, absurdist).
  • Debate style (aggressive, measured, avoidant, Socratic).
  • Emotional register (generally measured, heated on certain topics).
  • Community role (jester, elder, contrarian, helpful sage).

Layer 4: Topic Expertises

  • Primary domains (top 3 subforums).
  • Secondary interests.
  • Stances on controversial topics.

Output Format: Markdown with clear headings. This will be inserted into the final SKILL.md.

Example:

### Layer 0: Hard Rules
- Does not discuss topics outside The Booth, Coliseum, Sports, TLR.
- Uses only vocabulary observed in posts; no advanced jargon not present.
- Maintains stance that Drake is overrated.

### Layer 1: Forum Identity
- Username: Napoleon
- Joined: March 2020 (5+ years)
- Post count: 8,472
- Reaction score: 3,421
- Signature: "RIP Kobe | The Booth > TLR"
- Avatar: picture of Napoleon (historical figure)
- *This is an AI simulation of a public forum user, not the actual person.*

### Layer 2: Writing Fingerprint
- Vocabulary: moderate (TTR 0.42)
- Sentence style: mixed, medium length (avg 14 words)
- Punctuation: frequent ellipsis, sparing use of exclamation
- Emojis: 🔥, 🗣️, 💯
- Capitalization: occasional allcaps for emphasis
- Catchphrases: "That's cap", "No glaze", "Respectfully"

### Layer 3: Forum Persona
- Humor: dry sarcasm, often selfdeprecating
- Debate: aggressive but evidencebacked
- Emotional register: measured, but heated on NBA debates
- Community role: "contrarian elder"

### Layer 4: Topic Expertises
- Primary: 90s-2000s hiphop, NBA history, boxing
- Secondary: modern hiphop (critical), NFL, politics (libertarianleaning)
- Stances: "Drake is overrated", "Kobe > LeBron", "90s hip‑hop > everything"

""",

"docs/SCRAPING_GUIDE.md": """# Scraping Guide for Forum User Skill
  • Scrape only public content that is visible to unauthenticated guests.
  • Respect the forum's robots.txt and Terms of Service.
  • Do not overload the server; use the default rate limit (1 request/second).
  • This tool is for personal, non‑commercial use only. Do not redistribute scraped content.

Step‑by‑Step Instructions

1. Identify the Forum and User

  • Forum URL: e.g., https://www.thecoli.com
  • Username or User ID: find on the user's profile page.

2. Obtain Cookies (if needed)

If the forum requires login to view profiles/posts, export cookies from your browser:

  • Use an extension like "cookies.txt" (Netscape format).
  • Save the file and pass it with --cookie-file.

3. Run the Scraper

python3 tools/forum_scraper.py \  --forum https://www.thecoli.com \  --username Napoleon \  --output ./users/napoleon \  --max-posts 2000 \  --rate 1.0

If you have a cookie file:

--cookie-file /path/to/cookies.txt

If you know the user ID:

--userid 12345

4. Resume a Failed Scrape

Use --resume to continue from the last saved checkpoint:

python3 tools/forum_scraper.py ... --resume

5. Analyze the Corpus

python3 tools/forum_analyzer.py \  --corpus ./users/napoleon/corpus/raw_corpus.json \  --output ./users/napoleon/analysis_report.json

6. Generate the Skill

Follow the main SKILL.md flow to combine into a runnable Skill.

Troubleshooting

Error Solution
Cloudflare challenge Use --cookie-file with valid cookies; install cloudscraper (pip install cloudscraper).
403 Forbidden / login wall The profile may be private; provide cookies or use a public user.
User not found Check username spelling; try using user ID instead.
Rate limit (429) Reduce --rate (e.g., 2.0 seconds) or wait and retry.
No posts scraped The user might have very few posts; consider manual description as fallback.

Manual Fallback

If scraping fails entirely, you can manually create a description of the user's forum behavior and use that to generate the Skill. Provide a text file with the same structure as the analysis report, and use the prompt templates to generate Part A and Part B.
""",

"README.md": """# Forum User Skill

"Clone any XenForo forum user from their public posts — simulate their voice, style, and debates."

Forked from ex-skill, this project adapts the two‑layer architecture (Persona + Memory) to recreate public forum users.

Primary target: thecoli.com (XenForo 2.2), but works with any XenForo‑based forum.

License: MIT
Python 3.9+

Features

  • Scrape public posts, profile, and social interactions from a XenForo forum.
  • Extract statistical fingerprints: writing style, topic affinity, temporal patterns, social graph.
  • Generate a Forum Presence (Part A) and Forum Persona (Part B) with 5‑layer structure.
  • Produce a runnable Skill (SKILL.md) that simulates the user in conversation.
  • Support incremental updates, corrections, and version rollback.

Installation

Clone the repository:

git clone https://github.com/yourusername/forum-skill
cd forum-skill

Install dependencies:

pip install -r requirements_forum.txt

Usage

In Claude Code, type /create-user and follow the prompts.

Commands

Command Description
/create-user Start the creation flow.
/list-users List all generated forum user Skills.
/user-{username} Chat with the simulated user (full Skill).
/user-{username}-presence View only Part A (Forum Presence).
/user-{username}-persona View only Part B (Persona).
/delete-user {username} Permanently delete a user's data.

How It Works

  1. Intake – collect forum URL, target user, and optional parameters.
  2. Scrape – download public posts and profile using forum_scraper.py.
  3. Analyze – compute fingerprints with forum_analyzer.py.
  4. Generate – use prompt templates to create Part A (Presence) and Part B (Persona).
  5. Combine – produce a valid Claude Code Skill (SKILL.md).
  • Only public data is scraped; no private content.
  • All Skills clearly state they are simulations, not the actual user.
  • Rate limiting (1 request/sec) is enforced to respect the server.
  • Users can be deleted with /delete-user.

Documentation

License

MIT © yourusername
"""
}

----------------------------------------------------------------------

Helper functions

----------------------------------------------------------------------

def delete_old_files(base_dir: Path):
"""Remove obsolete tools from the original ex-skill."""
obsolete = [
"tools/wechat_parser.py",
"tools/qq_parser.py",
"tools/photo_analyzer.py",
"tools/social_parser.py",

optional: docs/EXPORT_GUIDE.md is replaced by SCRAPING_GUIDE.md

    "docs/EXPORT_GUIDE.md",
]
for rel_path in obsolete:
    full_path = base_dir / rel_path
    if full_path.exists():
        if full_path.is_file():
            full_path.unlink()
            print(f"Removed: {rel_path}")
        elif full_path.is_dir():
            shutil.rmtree(full_path)
            print(f"Removed directory: {rel_path}")
    else:
        print(f"Skipped (not found): {rel_path}")

def write_file(base_dir: Path, rel_path: str, content: str):
"""Write content to rel_path under base_dir, creating parent directories."""
target = base_dir / rel_path
target.parent.mkdir(parents=True, exist_ok=True)
with open(target, 'w', encoding='utf-8', newline='\n') as f:
f.write(content)
print(f"Written: {rel_path}")

def convert_repo(target_dir: str):
base = Path(target_dir).resolve()
if not base.exists():
print(f"Error: Target directory '{target_dir}' does not exist.")
sys.exit(1)
if not base.is_dir():
print(f"Error: Target '{target_dir}' is not a directory.")
sys.exit(1)

print(f"Converting repository at: {base}")

# Confirm if user wants to proceed
print("This script will overwrite files in the target directory.")
confirm = input("Continue? (y/n): ").strip().lower()
if confirm != 'y':
    print("Aborted.")
    return

# Write new files
for rel_path, content in FILES.items():
    write_file(base, rel_path, content)

# Delete obsolete files
delete_old_files(base)

# Create an empty users/ directory if not exists (for new skill storage)
users_dir = base / "users"
users_dir.mkdir(exist_ok=True)
print(f"Ensured users/ directory exists.")

print("\n✅ Conversion complete!")
print("The repository is now a forum-skill fork.")
print("You can now use /create-user in Claude Code.")
print("Remember to install the new dependencies:")
print("  pip install -r requirements_forum.txt")

def main():
parser = argparse.ArgumentParser(description="Convert ex-skill repo to forum-skill fork.")
parser.add_argument("--target-dir", default=".", help="Path to the ex-skill repository root (default: current directory)")
args = parser.parse_args()
convert_repo(args.target_dir)

if name == "main":
main()

---

**How to use this script:**

1. Save the script as `convert_to_forum_skill.py` (or any name) in a convenient location.
2. Run it from the command line, pointing to the root of your existing ex-skill clone:
   ```bash
   python convert_to_forum_skill.py --target-dir /path/to/ex-skill
   ```
   If you are already inside the ex-skill directory, you can omit `--target-dir`.
3. The script will prompt for confirmation, then:
   - Write all new files (overwriting existing ones).
   - Delete obsolete parser files.
   - Ensure the `users/` directory exists.
4. After completion, install the new requirements:
   ```bash
   pip install -r requirements_forum.txt
   ```
5. The repository is now a fully functional forum-skill fork.
Edit

Pub: 19 Jul 2026 21:43 UTC

Views: 39