File size: 45,652 Bytes
0eb2e78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Keyword coding of collected threads (no paid APIs, no LLM).

Input : raw/threads.jsonl (from collect.py)
Output: raw/coded_kw.jsonl  (all metadata + kw_* coded columns + private excerpt)
Usage : python3 -I scripts/code.py [threads.jsonl] [out.jsonl] [--drop-removed]
        --drop-removed skips the repos removed after the full-build review (SkyPilot, replicate/cog)
Rules are ordered: first match wins for single-valued columns; list columns join
up to 3 matches with ';'. See codebook.md for definitions.
"""
import json, os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import filters  # noqa: E402

ROOT = os.path.dirname(HERE)
I = re.I | re.A  # ASCII \b so that "netlify现在" still matches


def rx(s):
    return re.compile(s, I)


HOSTS = [  # (label, regex) — order = priority when counts tie
    ("hf_inference_endpoints", rx(r"inference endpoints?\b|ui\.endpoints\.huggingface|dedicated endpoint")),
    ("hf_spaces", rx(r"hugging ?face spaces?|\bhf spaces?|\b(on|to|in) (a |the |my )?(hf |hugging ?face )?spaces?\b|spaces? (sdk|hardware|build|container)|huggingface\.co/spaces|hf\.space")),
    ("streamlit_cloud", rx(r"streamlit (community )?cloud|share\.streamlit|streamlit\.app\b")),
    ("vercel", rx(r"\bvercel\b(?!/ai)(?! ai sdk)")),
    ("netlify", rx(r"\bnetlify\b")),
    ("cloudflare", rx(r"\bcloudflare|\bworkers?\.dev|wrangler|\bpages\.dev")),
    ("fly", rx(r"\bfly\.io\b|\bflyctl\b|\bfly deploy\b|fly\.toml")),
    ("railway", rx(r"\brailway\b")),
    ("render", rx(r"\brender\.com\b|\bon render\b|\bto render\b|onrender\.com|render\.yaml")),
    ("heroku", rx(r"\bheroku\b")),
    ("supabase", rx(r"\bsupabase\b")),
    ("langgraph_platform", rx(r"langgraph (platform|cloud)|langsmith deploy|langgraph deploy|langgraph-api|langgraph up")),
    ("azure", rx(r"\bazure\b|\bazd\b|app service|container apps|\baks\b")),
    ("gcp", rx(r"cloud ?run\b|\bgcp\b|google cloud|app engine|\bgke\b|vertex|cloud functions|firebase")),
    ("aws", rx(r"\baws\b|aws lambda|\b(on|to|in|via) lambda\b|lambda (deploy\w*|layers?|cold start|timeouts?|function url|@edge)|sagemaker|\becs\b|\beks\b|\bec2\b|amplify|bedrock|fargate|elastic beanstalk|apprunner|app runner")),
    ("digitalocean", rx(r"digital ?ocean|\bdroplet")),
    ("runpod", rx(r"\brunpod\b")),
    ("modal", rx(r"\bmodal\.com\b|\bmodal (deploy|serve|labs)\b|on modal\b")),
    ("replicate", rx(r"\breplicate\.com\b|\bcog push\b|on replicate\b|to replicate\b")),
    ("kubernetes", rx(r"kubernetes|\bk8s\b|\bhelm\b|openshift")),
    ("posit_connect", rx(r"posit connect|rstudio connect")),
    ("vps_docker", rx(r"\bvps\b|docker[- ]compose|\bdocker\b|self[- ]host\w*|nginx|own server|ubuntu server|coolify|easypanel|dokploy|caprover")),
]
REPO_HOST = {"vercel/vercel": "vercel", "netlify/cli": "netlify", "superfly/flyctl": "fly",
             "railwayapp/cli": "railway", "Azure-Samples/azure-search-openai-demo": "azure",
             "Azure-Samples/chat-with-your-data-solution-accelerator": "azure",
             "microsoft/sample-app-aoai-chatGPT": "azure", "GoogleCloudPlatform/generative-ai": "gcp", "GoogleCloudPlatform/agent-starter-pack": "gcp",
             "Azure-Samples/contoso-chat": "azure", "Azure-Samples/rag-postgres-openai-python": "azure",
             "replicate/cog": "replicate"}

FRAMEWORKS = [
    ("streamlit", rx(r"\bstreamlit\b")), ("gradio", rx(r"\bgradio\b")), ("chainlit", rx(r"\bchainlit\b")),
    ("nextjs", rx(r"next\.?js|\bnext (13|14|15|16)\b|app router|\bnext build\b")),
    ("remix", rx(r"\bremix\b")), ("sveltekit", rx(r"svelte")), ("nuxt", rx(r"\bnuxt")),
    ("vite_react", rx(r"\bvite\b")), ("astro", rx(r"\bastro\b")),
    ("fastapi", rx(r"fastapi|uvicorn")), ("flask", rx(r"\bflask\b")), ("django", rx(r"\bdjango\b")),
    ("express_node", rx(r"\bexpress\b|node\.?js")), ("hono", rx(r"\bhono\b")),
    ("langgraph", rx(r"langgraph")), ("langchain", rx(r"langchain")), ("llamaindex", rx(r"llama_?index|llama-index")),
    ("vercel_ai_sdk", rx(r"ai[- ]sdk|vercel/ai|@ai-sdk|useChat|streamText")),
    ("flowise", rx(r"flowise")), ("langflow", rx(r"langflow")), ("open_webui", rx(r"open[- ]?webui")),
    ("nextchat", rx(r"nextchat|chatgpt-next-web")), ("chatbot_ui", rx(r"chatbot[- ]ui")),
    ("cog", rx(r"\bcog (push|predict|build)\b|cog\.yaml")), ("tgi", rx(r"text-generation-inference|\btgi\b")), ("ollama", rx(r"\bollama\b")),
    ("vllm", rx(r"\bvllm\b")), ("dify", rx(r"\bdify\b")), ("ragflow", rx(r"ragflow")), ("anythingllm", rx(r"anything-?llm")),
    ("litellm", rx(r"litellm")), ("mastra", rx(r"\bmastra\b")), ("google_adk", rx(r"\badk\b|agent development kit")),
    ("crewai", rx(r"crew ?ai")), ("agno", rx(r"\bagno\b")), ("skypilot", rx(r"skypilot|\bsky (serve|launch)")),
]
REPO_FRAMEWORK = {"streamlit/streamlit": "streamlit", "gradio-app/gradio": "gradio", "Chainlit/chainlit": "chainlit",
                  "langchain-ai/langchain": "langchain", "langchain-ai/langchainjs": "langchain",
                  "langchain-ai/langgraph": "langgraph", "vercel/ai": "vercel_ai_sdk", "ollama/ollama": "ollama",
                  "ChatGPTNextWeb/NextChat": "nextchat", "mckaywrigley/chatbot-ui": "chatbot_ui",
                  "FlowiseAI/Flowise": "flowise", "langflow-ai/langflow": "langflow",
                  "run-llama/llama_index": "llamaindex", "open-webui/open-webui": "open_webui",
                  "huggingface/text-generation-inference": "tgi", "replicate/cog": "cog",
                  "stackblitz-labs/bolt.diy": "vite_react", "microsoft/sample-app-aoai-chatGPT": "flask",
                  "langgenius/dify": "dify", "infiniflow/ragflow": "ragflow", "Mintplex-Labs/anything-llm": "anythingllm",
                  "huggingface/chat-ui": "hf_chat_ui", "vercel/chatbot": "nextjs", "BerriAI/litellm": "litellm",
                  "vllm-project/vllm": "vllm", "mastra-ai/mastra": "mastra", "google/adk-python": "google_adk",
                  "crewAIInc/crewAI": "crewai", "agno-agi/agno": "agno", "skypilot-org/skypilot": "skypilot",
                  "Azure-Samples/rag-postgres-openai-python": "fastapi", "Azure-Samples/contoso-chat": "prompty"}

PROVIDERS = [
    ("azure_openai", rx(r"azure[ _-]?open ?ai|\baoai\b")), ("openai", rx(r"\bopen ?ai\b|\bgpt-?[345o]|chatgpt")),
    ("anthropic", rx(r"anthropic|\bclaude\b(?![- ]code)(?! made| told| deployed| concludes)")), ("google", rx(r"gemini|vertex ?ai|palm\b")),
    ("aws_bedrock", rx(r"bedrock")), ("local_ollama", rx(r"\bollama\b|llama\.cpp|lm studio|\bgguf\b")),
    ("huggingface", rx(r"hugging ?face|transformers|\bhf_|inference endpoint|\btgi\b")),
    ("mistral", rx(r"mistral")), ("deepseek", rx(r"deepseek")), ("groq", rx(r"\bgroq\b")),
    ("openrouter", rx(r"openrouter")), ("replicate", rx(r"replicate")), ("cohere", rx(r"cohere")),
]
REPO_PROVIDER = {"Azure-Samples/azure-search-openai-demo": "azure_openai",
                 "Azure-Samples/chat-with-your-data-solution-accelerator": "azure_openai",
                 "microsoft/sample-app-aoai-chatGPT": "azure_openai", "GoogleCloudPlatform/generative-ai": "google",
                 "GoogleCloudPlatform/agent-starter-pack": "google", "Azure-Samples/contoso-chat": "azure_openai",
                 "Azure-Samples/rag-postgres-openai-python": "azure_openai",
                 "ollama/ollama": "local_ollama", "huggingface/text-generation-inference": "huggingface"}

# credential words for secret_exposed; "token" alone is not one here (LLM tokens), it needs a qualifier
_CRED = (r"(secrets?\b|credentials?|api[_ -]?keys?|(access|auth|bearer|github|gh|hf|hugging ?face|personal access|oauth|refresh|session|jwt|api|secret)[_ -]?tokens?\b|"
         r"passwords?|\.env\b|\.dev\.vars|private[_ -]?keys?|sensitive (files?|data|values?|info\w*))")
_SEC_ACT = r"(?<!avoid )(?<!not )(?<!never )(\bleak\w*|\bexpos(ed|es|ing)\b|(deployed|deploys|published|publishes|uploaded|uploads) |(in |as )?plain ?text)"
_SEC_ACT_AFTER = r"(\bleak\w*|\bexpos\w*|(in|as) plain ?text|publicly|made public|(is|are|was|were|now) public\b|(in|to|into) (a |the |my )?public (repo\w*|github|bundle|url))"
ERRORS = [  # error_type
    ("oom", rx(r"memory leak\w*|leak\w* memory|memory (usage|use|consumption) (keeps|continues|grows|growing|increas\w*)|ram growth|out of memory|\boom\b|oomkill|memory limit|heap out|killed.*memory|cuda out of memory|exceeded memory")),
    ("size_limit", rx(r"(volume|disk|storage).{0,25}(capacity|full|space|running low)|(size|bundle|function|slug|image|payload|body).{0,25}(limit|too large|exceed)|250 ?mb|50 ?mb|exceeds the maximum|too big|request entity too large|\b413\b")),
    ("timeout", rx(r"timed? ?out\b|timeout (error|exceeded|after)|\b504\b|deadline exceeded|maxduration|max duration|took too long|\d+ ?(s|sec|seconds|minutes) (limit|timeout)")),
    ("missing_env_var", rx(r"env(ironment)? ?var\w*.{0,40}(not|missing|undefined|empty)|(missing|undefined|not set|not found).{0,30}(api[_ ]?key|env|secret|token)|api[_ ]?key.{0,30}(missing|not (set|found|provided)|undefined|invalid|incorrect)|\.env\b")),
    # credentials deployed/published by mistake: a credential word must sit next to the leak/expose/publish word
    # ("memory leak", "exposed port", "context leaking" fall through to oom, port_binding, ...)
    ("secret_exposed", rx(_SEC_ACT + r"(?:(?!\. )[^\n]){0,30}" + _CRED + "|" + _CRED + r"(?:(?!\. )[^\n]){0,40}" + _SEC_ACT_AFTER)),
    ("iac_template_error", rx(r"invalidtemplate|template (deployment|validation)|bicep|terraform|arm template|deploymentfailed|resourcedeploymentfailure|failing invoking action .provision|error deploying infrastructure|cloudformation")),
    ("quota_billing", rx(r"quota|billing|payment|insufficient (funds|credits)|rate limit|\b429\b|credit card|\bcapacity\b|usage limit|limit of number")),
    ("permission_rbac", rx(r"permission denied|forbidden|\b403\b|unauthori[sz]ed|\b401\b|role assignment|rbac|authorizationfailed|not authorized|access denied")),
    ("port_binding", rx(r"\bport\b.{0,30}(\d{2,5}|bind|listen|expos)|\b(port|host) 0\.0\.0\.0|0\.0\.0\.0|failed to listen|listen(ing)? on port|health ?check|127\.0\.0\.1")),
    ("module_dependency", rx(r"module not found|cannot find module|modulenotfound|no module named|could not resolve|importerror|import error|dependency|peer dep|requirements\.txt|pip install|not compatible|incompatible|edge runtime")),
    ("build_failure", rx(r"build (fail|error)|failed to build|failed during stage .building|build script returned|npm run build|next build|exit code [1-9]|compil\w* (error|fail)|type (error|issue)s?|lockfile|frozen-lockfile")),
    ("cors_network", rx(r"\bcors\b|network error|econnrefused|connection refused|ssl|certificate|dns|websocket|\bwss?\b|proxy")),
    ("streaming", rx(r"stream(ing)?.{0,40}(not|doesn|broken|buffer|stuck|all at once|cut)|buffer(ed|ing)|(responses?|output) (are |is )?cut off")),
    ("not_found_routing", rx(r"\b404\b|page not found|routing|blank page|white (page|screen)|root[- ]path|sub ?path|base ?path|redirect")),
    ("server_error_5xx", rx(r"\b50[0-3]\b|internal ?server ?error|bad gateway|crash\w*|exited with|segmentation fault|application error|server-side exception")),
]

CATEGORY_OF_ERROR = {"secret_exposed": "secrets_api_keys", "iac_template_error": "provisioning_iac", "oom": "memory_model_size", "size_limit": "memory_model_size", "timeout": "timeouts",
                     "missing_env_var": "secrets_api_keys", "quota_billing": "costs_quota",
                     "permission_rbac": "auth_permissions", "port_binding": "networking",
                     "module_dependency": "runtime_dependencies", "build_failure": "build",
                     "cors_network": "networking", "streaming": "streaming",
                     "not_found_routing": "routing_config", "server_error_5xx": "other"}
CATEGORY_EXTRA = [
    ("gpu", rx(r"\bgpu|cuda|nvidia|a100|h100|\bt4\b|\bl4\b")),
    ("cold_start", rx(r"cold start|spin(s|ning)? (up|down)|sleep(ing)? (mode|after)|scale to zero|wake")),
    ("database", rx(r"database|postgres|mysql|sqlite|redis|mongo|vector (db|store)|cosmos|pgvector|chroma|pinecone|supabase")),
    ("auth_permissions", rx(r"\boauth|login|sign[- ]?in|\bsso\b|entra|easy auth|authentication")),
    ("costs_quota", rx(r"\bcosts?\b|pricing|expensive|\bbill(ed|ing)?\b|hobby plan|pro plan")),
]

# Topics added 2026-10-30, used ONLY when the rules above give "other" (existing topics always win).
# agent_behavior: a coding/deploy agent itself causes the problem. Needs an agent context (the claude-code
# repo, or the text names an agent); the subtype regex is tried on the title first, then the body.
AGENT_CTX = rx(r"\bclaude\b|\bthe (ai|agent|model|assistant)\b|coding agent|\bai agent|\bcodex\b|copilot|\bcursor\b|windsurf|auto[- ]?mode")
_DEP = r"(deploy\w*|push\w*|production|prod\b|merge\w*|release\w*)"
AGENT_ERRORS = [  # (error_type, regex); order = priority
    ("agent_wrong_target", rx(r"deploy\w* (\w+ )?to (the |a )?wrong|wrong (\w+ ){0,2}(project|environment|account|repo\w*|server|cluster|org\w*|vm|region|branch)\b")),
    ("agent_false_success", rx(r"false (completion|success)|(claim\w*|report\w*)[^.\n]{0,25}(unverified|untested) deploy|claim\w* (to (have )?)?deploy|"
                               r"report\w* (broken|failed) \w+ as (working|success\w*)|checks? pass\w* incorrectly|"
                               r"(claim\w*|report\w*|said|says|told)[^.\n]{0,40}(deploy\w*|production)[^.\n]{0,30}(work\w*|succe\w*|verified|live|fixed)[^.\n]{0,40}(but|when|while|although)|"
                               r"reported what a deploy|told [^.\n]{0,40}deploy[^.\n]{0,60}without (checking|verifying)")),
    ("agent_deployed_unasked", rx(_DEP + r"[^.\n]{0,40}(without (asking (for |me )?|any |explicit |user |prior |my )?(permission|confirmation|authori[sz]ation|approval|consent|being asked))|"
                                  r"(autonomously|immediately|unilaterally) " + _DEP + r"|deploy\w*[^.\n]{0,20}(proceeded )?despite (explicit )?(non-deployment|instructions)|"
                                  r"unintended deploy\w*|unreviewed deploy\w*|unasked deploy\w*|deploy\w* (proceeded|happened) despite")),
    ("agent_blocked_refused", rx(r"(auto[- ]?mode|classifier|safety (filter|flag|check)\w*|false positive)[^.\n]{0,60}(block\w*|den(y|ies|ied|ial)\w*|refus\w*|flag\w*)|"
                                 r"(block\w*|refus\w*|den(y|ies|ied))[^.\n]{0,40}(" + _DEP[1:-1] + r")[^.\n]{0,40}(user[- ](authori[sz]ed|requested|approv\w*)|explicit\w*|valid|legitimate|approv\w*|authori[sz]\w*)|"
                                 r"refus\w* [^.\n]{0,35}(merge|deploy)|false positive[^.\n]{0,40}(deploy|production)|flag\w*[^.\n]{0,40}blocks? (the )?deploy")),
]
# observability: monitoring/tracing/telemetry tools and terms (never bare "log"/"logs").
# The body regexes are stricter (bodies paste templates such as "Telemetry ID", and stack traces) and run on the
# cleaned first 1,500 characters of the body (no code blocks); OpenTelemetry and Application Insights count in the
# title only (in bodies they are mostly module paths in stack traces and Azure template resources).
OBSERVABILITY = rx(r"langfuse|langsmith (trac\w*|observab\w*|monitor\w*)|opentelemetry|\botel\b|\botlp\b|telemetry|\btracing\b|(?<!stack )\btraces\b|\btracer\b|dd-trace|"
                   r"\bsentry\b|prometheus|grafana|datadog|servicemonitor|observability|\bmonitoring\b|\bmetrics\b|helicone|\barize\b|new relic|application insights")
OBSERVABILITY_BODY = rx(r"langfuse|\botlp\b|\btracing\b(?! (the|this|it|back|down))|prometheus|grafana|datadog|\bsentry\b|servicemonitor|"
                        r"observability|helicone|\barize\b")
# performance_scaling: slowness, latency, throughput, concurrency, scaling out
PERFORMANCE = rx(r"\bslow(ly|ness|er|s)?\b|latency|throughput|concurren\w*|auto-?scal\w*|horizontal\w* scal\w*|scale (out|horizontally)|"
                 r"multi-?replicas?|\breplicas\b|single (api )?replica|in parallel|parallel (requests|agents|workers)|requests per second|tokens?/s\b|"
                 r"\[performance\]|performance (issue|problem|degrad\w*)|load balancing|high load|under load")
PERFORMANCE_BODY = rx(r"auto-?scal(ing|er)\b|horizontal\w* scal\w*|scale (out|horizontally)|multiple (replicas|workers)|multi-?replicas?|"
                      r"high(ly)? availab\w*|load balancing|throughput|concurrent (requests|users)|requests per second|tokens?/s\b|"
                      r"(very|extremely|too|really|painfully) slow|slow (responses?|startup|start|inference|performance)|high latency|latency (spikes?|increase\w*)")


def new_topic(repo, title, body):
    """(topic, agent error_type or None) for a thread whose topic is otherwise 'other', or (None, None).
    Title first, then body (body = the first 3,000 raw characters, as for error_type)."""
    agent_ok = repo == "anthropics/claude-code" or AGENT_CTX.search(title + "\n" + body)
    e = agent_ok and first(AGENT_ERRORS, title)
    if e:
        return "agent_behavior", e
    if OBSERVABILITY.search(title):
        return "observability", None
    if PERFORMANCE.search(title):
        return "performance_scaling", None
    e = agent_ok and first(AGENT_ERRORS, body)
    if e:
        return "agent_behavior", e
    short = clean(body)[:1500]
    if OBSERVABILITY_BODY.search(short):
        return "observability", None
    if PERFORMANCE_BODY.search(short):
        return "performance_scaling", None
    return None, None


AI_TOOLS = [("lovable", rx(r"lovable")), ("bolt", rx(r"\bbolt(\.new|\.diy)?\b")), ("v0", rx(r"v0\.dev|\bv0 (by vercel|app|generated)|(with|in|using|from) v0\b(?!\.)")),
            ("cursor", rx(r"\bcursor\b")), ("claude_code", rx(r"claude[- ]code")), ("replit", rx(r"replit")),
            ("copilot", rx(r"copilot")), ("windsurf", rx(r"windsurf")), ("dyad", rx(r"\bdyad\b")),
            ("codex", rx(r"\bcodex\b"))]
REPO_AI_TOOL = {"stackblitz-labs/bolt.diy": "bolt", "dyad-sh/dyad": "dyad", "anthropics/claude-code": "claude_code"}

REMOTE = rx(r"vercel|netlify|cloudflare|fly\.io|flyctl|railway|render|heroku|azure|azd|cloud ?run|gcp|google cloud|aws|lambda|"
            r"sagemaker|ecs|kubernetes|k8s|spaces|streamlit cloud|production|prod\b|server|hosted|vps|digitalocean|runpod|modal|"
            r"replicate|supabase|langgraph (platform|cloud)|deployed|deployment|serverless")


def clean(t):
    t = re.sub(r"<!--.*?-->", " ", t or "", flags=re.S)
    t = re.sub(r"```.*?```", " ", t, flags=re.S)
    t = re.sub(r"`[^`]*`", " ", t)
    t = re.sub(r"https?://\S+", "<url>", t)
    t = re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "<email>", t)
    t = re.sub(r"@[\w-]+", "@<user>", t)
    t = re.sub(r"^\s*(#+.*|[-*] \[[ x]\].*|\*\*[^*]+\*\*:?\s*)$", " ", t, flags=re.M)
    t = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", t)
    return re.sub(r"\s+", " ", t).strip()


def excerpt(body, n=30):
    w = clean(body).split()
    return " ".join(w[:n])


def first(rules, text):
    for lab, r in rules:
        if r.search(text):
            return lab
    return None


def multi(rules, text, k=3):
    return ";".join([lab for lab, r in rules if r.search(text)][:k]) or None


# relevance rules learned from the pilot's manual judgement (see report.md)
NOT_DEPLOY = rx(r"deployment[_ ]?name|\bptu\b|serverless (api )?endpoint|bedrock marketplace|"
                r"(model|llm|embedding)s? (deployed|hosted) (via|with|by|in|on) (vllm|xinference|azure|tgi|ollama)|"
                r"(locally|local(ly)?[- ]deployed|my own) (model|llm|embedding)|deployed (embedding|chat|llm) model|"
                r"use (a |my )?(remote|locally) deployed")
LOCAL = rx(r"\blocal(ly)? deploy\w*|\blocal(ly)? (docker|private|offline|intranet )?(docker |compose )?(deploy\w*|setup|install\w*)|docker local|docker desktop|\bwsl2?\b|truenas|langgraph dev\b|\bon my (mac|laptop|pc|machine)|desktop app|\.exe\b|"
           r"windows 1[01]\b.{0,40}(server|local)|test(ing)? (it |your agent )?locally|errors when testing locally")
PITCH = rx(r"we('re| are) building|our (open-source )?platform|open-source platform for|happy to (help|contribute)|"
           r"\bwithdrawn\b|marketplace where agents|we have implemented")
FEATURE = rx(r"^\s*(\[?feat(ure)?( request)?\]?[:\s]|add (support|a |an )|support (for )?|idea:|enhance|request:|"
             r"allow |make .* (easier|friendly)|proposal)")
CLASSIFIER = rx(r"classifier|\baup\b|usage[- ]policy|safeguard|flag(s|ged)? .{0,30}(malicious|policy)|prompt[- ]injection")
REMOTE_T = rx(r"vercel|netlify|cloudflare|fly\.io|flyctl|railway|render\b|heroku|azure|azd|cloud ?run|gcp|google cloud|aws|"
              r"lambda|sagemaker|ecs|eks|aks|gke|kubernetes|k8s|helm|spaces|streamlit cloud|production|prod\b|server|hosted|"
              r"vps|digitalocean|runpod|modal|replicate|supabase|langgraph (platform|cloud)|reasoning engine|agent engine|"
              r"inference endpoint|app service|container app|coolify|amplify|fargate|deploy\w*|serverless|edge")
BUILDER_SELF = rx(r"(deploy\w*|host\w*|run\w*|install\w*) (the |custom |costum |own )?(bolt|blot)(\.diy)?\b|"
                  r"\bbolt(\.diy)? (on|to|in) |bolt\.diy (is|on)|coolify|easypanel|docker|cloudflare runtime")


# v3 (after the full-build sample): a generic cloud/vendor name in the title is not enough
HOSTING_T = rx(r"vercel|netlify|railway|render\.com|onrender|\b(on|to) render\b(?!ing)(?! (the|a|an|it|html|markdown|text|images?)\b)|render (deploy\w*|blueprint|service)\b|"
               r"heroku|fly\.io|flyctl|cloud ?run|app service|container apps?|"
               r"aws lambda|\b(on|to|in|via) lambda\b|lambda (deploy\w*|layers?|cold start|timeouts?|function url|@edge|runtime)|"
               r"ecs\b|fargate|\beks\b|\bgke\b|\baks\b|kubernetes|\bk8s?\b|\bk3s\b|helm|openshift|hugging ?face spaces?|hf spaces?|"
               r"\b(on|to|in) (hf |hugging ?face |a |the |my )?spaces?\b(?! (between|in|and|before|after|at|around|instead|characters?|key))|\bspaces? (sdk|hardware|build|container|secrets|app|demo)|zerogpu|"
               r"sagemaker (deploy\w*|endpoint deploy\w*)|deploy\w* .{0,40}sagemaker|\b(on|in|to) (an? |the )?(aws|azure|gcp|google cloud|ec2|sagemaker)\b|"
               r"runpod|modal\.com|\bon modal\b|modal (deploy|serve|labs)|cloudformation|reverse proxy|nginx|traefik|ingress|cloudflared?[ -]tunnels?|\[serve\]|agent ?engine|reasoning engine|langgraph (platform|cloud)|"
               r"langsmith deploy|mastra cloud|supabase (edge )?functions?|cloudflare (workers?|pages)|workers?\.dev|amplify|"
               r"elastic beanstalk|app engine|digital ?ocean|coolify|docker[- ]compose|\bdocker\b|podman|\bvps\b|ec2|azd\b|streamlit (community )?cloud|"
               r"inference endpoints?|posit connect|sky serve|skyserve|firebase hosting|firebase (app|functions)|"
               r"(remote|cloud|linux|ubuntu|production|prod|company|shared|dedicated) (server|vm|instance|host|gpu)s?|\bon (a |the |my )?(remote )?(server|vm)\b")
DEPLOY_VERB_T = rx(r"\bdeploy\w*|\bhosting\b|\bhosted\b|self[- ]host\w*|\bredeploy\w*|\bprovision\w*|\bpublish\w*|go(ing)? live|"
                   r"\b(in|on|for|to) (the )?(production|prod)\b(?![- ](grade|ready|use|code|systems?|quality|patterns?))|production (only|server|environment|build|deployment|mode|setup)|(prod|production) (env|build)\b|"
                   r"\bon (the )?server\b|\bazd up\b")
NOT_DEPLOY_SENSE = rx(r"router|load ?balanc\w* (between|across) (models|deployments)|model deployment(?! (to|on|in) )|deployment[_ ]?(name|id)s?\b|"
                      r"custom[- ]priced|cost map|\[usage\]|"
                      r"deploy\w* (the )?(new |latest )?version|after (deploying|upgrading) (to )?(v|version)|gpu deployment|deployment (thinking|defaults|settings)|"
                      r"(ios|macos|android) deployment|deployment target (too|for ios|version)|publish(ing)? (to )?(npm|pypi|the package|package)|published (package|version)|npm publish")
# Rule 7: a cloud's managed AI API used as a client, not an app deployed on a host
MANAGED_API_T = rx(r"vertex ?ai(?! agent ?engine)|bedrock|azure ?open ?ai|\baoai\b|ai foundry|azure ai (services|inference)|batch (prediction|api|inference|job)|"
                   r"gemini api|openai api|workers ai|ai gateway|sagemaker(?! deploy)|\bvercel_ai_gateway|\bsagemaker_|"
                   r"(serverless|provisioned|ptu|global|standard) (api |model )?(endpoint|deployment|throughput)")
APP_HOST_T = rx(r"vercel(?! ai gateway)(?!_ai)|netlify|railway|render\.com|heroku|fly\.io|cloud ?run|app service|container apps?|lambda\b|ecs\b|fargate|eks|gke|aks|"
                r"kubernetes|k8s|helm|openshift|spaces?\b|(on|to|in) sagemaker|deploy\w* .{0,40}sagemaker|agent ?engine|reasoning engine|docker|vps|\bazd\b|app engine|cloudflare (workers?|pages)(?! ai)|"
                r"deploy\w* (my |the |our |a |an )?(app|agent|server|proxy|litellm|chatbot|bot|application|site|frontend|backend|ui)|"
                r"deploy\w* (a |the )?(model|llm|endpoint) (to|on|in) (azure ml|azure machine learning|sagemaker|vertex ai endpoint)|managed online endpoint")
# Rule 9: CI / tests of a framework's cloud integration
CI_T = rx(r"\bci\b|\[ci\]|^ci[:(]|github actions?|gh actions?|workflows? (fail\w*|run|broken)|\be2e\b|end[- ]to[- ]end tests?|integration tests?|unit tests?|"
          r"smoke ?tests?|regression tests?|flaky|\btests? (fail\w*|for|of|against|on|broken)|^\[?tests?\]?[:(]|ci[- ]failure|release (pipeline|workflow|job)")
# Rule 6: app behaviour bugs; they need a link to the host (deploy, config, runtime) to stay in
APP_BUG_T = rx(r"\b(ui|button|display\w*|markdown|chat history|hallucinat\w*|infinite loop|loops? forever|repeat(s|ing|ed)? (itself|the|output|answer)|"
               r"output (is )?(wrong|garbled|empty|incorrect)|answers?|citations?|i18n|translation|dark mode|theme|layout|css|font|style|"
               r"tool[- ]call\w*|function[- ]call\w*|structured output|tokeni[sz]\w*|accuracy|quality|reasoning (text|content)|thinking (text|content)|"
               r"cost tracking|spend|usage (data|tracking)|logs? (clutter|spam)|telemetry|metrics?|cach(e|ed|ing) tokens?|prompt_tokens)\b")
HOST_LINK = rx(r"\b(deploy\w* (fail\w*|error\w*|broken|stuck|crash\w*|times? out)|fail\w* (to|when|while|after|on|in) (deploy\w*|start\w*|boot|run(ning)? (on|in))|"
               r"(cannot|can'?t|unable to|won'?t|doesn'?t|does not|not) (deploy|start|boot|connect|reach|access|load|run)|works? (fine )?locally|local(ly)? (works|fine)|"
               r"but not (on|in|when|after)|only (on|in|when) (deploy\w*|production|prod|spaces|vercel|k8s|kubernetes|docker|server)|"
               r"env\w*|config\w*|port|proxy|https?\b|ssl|tls|cors|domain|subpath|root[_ ]path|base[_ ]?path|timeout|timed out|memory|oom|ram|disk|volume|storage|"
               r"startup|start(s|ing)?|crash\w*|restart\w*|container|image|helm|chart|ingress|install\w*|permission|forbidden|40[134]|50[0234]|auth\w*|login|oauth|"
               r"secret|keys?|database|postgres|redis|network\w*|dns|websocket|stream\w*|cold start|scal\w*|replica\w*|pod|node|gpu|cuda|nccl|driver|build\w*|"
               r"read[- ]only|non[- ]?root|filesystem|mount\w*|bucket|s3|gcs|blob|iframe|static files?|assets?|routing|redirect\w*|404|session)\b")
CC_NOISE = rx(r"browser pane|built-in browser|in-app browser|desktop|warp\b|oauth|connector|plugin|email|turnstile|challenge page|sub-?agents?|cowork|msix|"
              r"auto-?updat\w*|managed[- ](settings|mcp|config)|deployment (mode|surface|store|mount)|third-party deployment|custom-3p|org(anization)?[- ]skill|"
              r"skills? (deploy|publish)|marketplace|remote control|voice mode|install\.sh|binarydeployment|ssh remote|deployment target|ios|"
              r"model deployed instead|driver deployment|deployed instead of|56-agent|deploy(ed|s)? .{0,20}(sub-?)?agents\b")
# Rule 4: an agent that deploys and hits its own limits (classifier, permission denied, false "it's deployed")
CC_DEPLOY = rx(r"deploy\w*|production|\bprod\b|publish\w*|go live|vercel|netlify|cloudflare (workers?|pages)|firebase|railway|supabase|heroku|"
               r"fly\.io|cloud ?run|kubernetes|k8s|nginx|\bvps\b|\bserver\b|\bdomain\b|website|\bsite\b|\bhosting\b")
CC_LIMIT = rx(r"classifier|auto[- ]?mode|blocked|blocks|denied|deny|refus\w*|flag\w*|false (positive|completion)|claim\w*|reported .{0,40}(success|working|deployed)|"
              r"without (asking|confirmation|permission|authori[sz]ation|warning)|unauthori[sz]ed|unrequested|unprompted|autonomous\w*|"
              r"(deployed|published|uploaded) .{0,40}(secret|credential|\.env|\.dev\.vars|sensitive)|secret|credential|wrong (project|account|repo)|destroy\w*|took down|broke")
GENERIC_RE = filters.GENERIC_REPOS
SERVING_REPOS = {"vllm-project/vllm", "ollama/ollama", "huggingface/text-generation-inference", "skypilot-org/skypilot", "replicate/cog"}
AGENT_DEPLOY_REPOS = {"google/adk-python", "GoogleCloudPlatform/agent-starter-pack", "langchain-ai/langgraph", "mastra-ai/mastra", "crewAIInc/crewAI", "agno-agi/agno"}


def relevance(t, title, text, alltext):
    """Rules v4 (owner decisions 2026-10-28). Returns (yes|no, unsure_reason or '').
    unsure_reason marks rows the keywords cannot settle; they are judged by the reviewer."""
    g, repo = t["group"], t["repo"]
    generic = g in ("host", "framework_generic") or repo in GENERIC_RE
    tclean = re.sub(r"vercel ai sdk|ai sdk|sandbox-vercel|@vercel/\S+|vercel/ai\b|vercel[_ ]ai[_ ]gateway|ai gateway", " ", title, flags=I)
    hosting, verb = bool(HOSTING_T.search(tclean)), bool(DEPLOY_VERB_T.search(tclean))
    # rule 8: general frameworks and host CLIs need AI evidence in the thread itself (title, body, comments)
    if generic and not filters.AI_EVIDENCE.search(re.sub(r"gradio|streamlit|vercel|next\.?js|netlify", " ", alltext, flags=I)):
        return "no", ""
    if PITCH.search(text[:1500]):
        return "no", ""
    if repo == "anthropics/claude-code":
        if CC_NOISE.search(title) or NOT_DEPLOY_SENSE.search(title):
            return "no", ""
        if not CC_DEPLOY.search(title):
            return "no", ""
        # rule 4: the agent deploying (or claiming to) and hitting limits; rule 2: local docker build is not a host
        if re.search(r"local `?docker build|locally", title, I):
            return "no", ""
        if CC_LIMIT.search(title) or re.search(r"deploy\w*", title, I):
            return "yes", "" if CC_LIMIT.search(title) and re.search(r"deploy\w*|production|prod\b|publish", title, I) else "cc:deploy_context_unclear"
        return "no", "cc:host_word_only"
    if CLASSIFIER.search(title):
        return "no", ""
    if NOT_DEPLOY.search(text) and not re.search(r"deploy\w* (to|on|in) (vercel|netlify|azure|aws|gcp|cloud|render|railway|k8s|kubernetes|hugging)", title, I):
        return "no", ""
    remote = bool(HOSTING_T.search(re.sub(r"docker[- ]?(compose)?|podman", " ", tclean, flags=I)))
    if LOCAL.search(title) and not remote or LOCAL.search(text[:2500]) and not hosting:
        return "no", ""      # rule 2: laptop, WSL, local GPU, "local docker deployment"
    if not remote and re.search(r"\b(macos|mac (intel|m[1-4])|windows(?!\.net)|apple silicon|rtx \d{4}|jetson|raspberry|offline (device|machine)|local (gpu|machine|computer))\b", title, I) \
            and not re.search(r"works? (fine )?(on|in) (the |my )?local|locally|\bbut\b|\b(adk|mastra|azd|az|gcloud|vercel|wrangler|langgraph|flowise) (deploy|build|up|webapp)\b|deploy\w* (to|on) (?!(the |my |a )?(mac|windows|jetson|raspberry))|agent_engine|gh actions", title, I):
        return "no", ""      # rule 2: a local machine named in the title
    if not (g in ("framework", "sample", "builder") or filters.AI.search(text)):
        return "no", ""
    if not (hosting or verb):
        return "no", ""      # e.g. "Azure provider does not support ...", "AWS Bedrock ... structured output"
    # rule 7: managed AI API as a client
    own_host = g == "sample" or repo in SERVING_REPOS or repo in AGENT_DEPLOY_REPOS
    if MANAGED_API_T.search(title) and not APP_HOST_T.search(tclean):
        if own_host and (verb or re.search(r"\b(on|to|in) (gcp |google )?(vertex ai|sagemaker)\b", title, I)):
            pass             # rule 3 / sample apps: the repo's own app or model server deployed on that cloud
        elif verb and re.search(r"deploy\w*", tclean, I):
            return "yes", "managed_api:deploy_word"
        else:
            return "no", ""
    if NOT_DEPLOY_SENSE.search(title) and not hosting:
        return "no", ""
    ci = bool(CI_T.search(title)) or any(re.search(r"ci[- ]failure|^ci$|area:ci|testing", l, I) for l in t["labels"])
    if ci:               # rule 9: CI/tests of a cloud integration are in; other CI is out
        return ("yes", "") if hosting else ("no", "ci:no_cloud_named" if verb else "")
    if repo == "BerriAI/litellm" and not (hosting or re.search(r"deploy\w* (litellm|the proxy|proxy)|docker|helm", title, I)):
        return "no", ""      # LiteLLM "deployment" = a model entry in the router
    if repo in SERVING_REPOS and not hosting:
        # rules 2+3: model serving counts on a remote host only; "deploy a model" often means a local run
        if re.search(r"\b(server|production|prod|cluster|multi[- ]node|remote|cloud|container|docker|instance|api access|concurren\w*)\b", text[:2500], I):
            return "yes", "serving:host_not_named"
        return "no", ""
    if g == "host" and re.search(r"agent", title, I) and not re.search(r"app|deploy\w* (my|a|the)", title, I):
        return "no", "host:agent_tooling"
    if not hosting and not re.search(r"deploy\w*|hosting|hosted|self[- ]host|provision|publish|go(ing)? live|on (the )?server|azd up", tclean, I):
        return "yes", "production_only"   # only "in production": a host is implied, the link may be weak
    # rule 6: an app bug seen on a server, with no link to the deploy, config or host runtime
    if APP_BUG_T.search(re.sub(r"chat-ui|open[- ]?webui|chatbot[- ]ui", " ", title, flags=I)) and not HOST_LINK.search(title):
        return "yes", "app_bug:host_link_unclear"
    return "yes", ""


# thread_type (rule 5): what the thread is
TT_PREFIX = [("pr_ci", rx(r"^\s*(\[(ci|test|tests|chore|build)\]|(ci|test|tests|chore)(\(\w+\))?:)")),
             ("docs", rx(r"^\s*(\[(docs?|documentation)\]|docs?(\(\w+\))?:|documentation:)")),
             ("feature", rx(r"^\s*(\[(feat(ure)?( request)?|enhancement|rfc|proposal|idea|request)\]|(feat|feature|feature request|enhancement|rfc|proposal|idea|request)(\(\w+\))?:)")),
             ("question", rx(r"^\s*(\[(question|usage|help|support|discussion)\]|(question|usage|help)(\(\w+\))?:)")),
             ("problem", rx(r"^\s*(\[(bug|bug report|installation|regression|model|refund)\]|bug(\(\w+\))?:)"))]
ERRORISH = rx(r"\b(errors?|fail\w*|broken|break(s|ing)?|crash\w*|not work\w*|doesn'?t work|does not work|isn'?t working|cannot|can'?t|unable|won'?t|stuck|"
              r"timeouts?|timed out|exception|bug|wrong|incorrect|invalid|denied|refused|rejected|blocked|undefined|not found|hang(s|ing)?|freez\w*|"
              r"[45]\d\d|missing|issue with|problem with|no longer|regression|leak\w*|ignor\w*|without (asking|confirmation|permission))\b")
FEATURE_T = rx(r"^\s*(add(ing)?|support(ing)?|allow|enable|provide|implement|introduce|make|expose|offer|create|let)\b|feature request|\bplease add\b|would be (nice|great|good|helpful)|"
               r"\bsupport for\b|\bproposal\b|\bshould (support|allow|be able)|\bwish\b|\bability to\b|\boption (to|for)\b|\bconfigurable\b")
DOCS_T = rx(r"\bdocs?\b|documentation|readme|\bguide\b|tutorial|instructions?|\bexamples? (for|of|on)\b|recipe|cookbook|how-?to guide")
QUESTION_T = rx(r"^\s*(how|what|which|why|where|when|is|are|can|could|does|do|should|any)\b|\?\s*$|\bhow (to|do|can|should)\b|is it possible|is there a way|"
                r"best (way|practice)|recommend\w*|guidance|help needed|need help|question")
FEATURE_L = rx(r"enhancement|feature|rfc|proposal|integration request|idea")
DOCS_L = rx(r"documentation|\bdocs?\b")
QUESTION_L = rx(r"question|support|usage|answered|help wanted(?!.)|discussion")
BUG_L = rx(r"\bbug\b|regression|crash|has repro|possible bug|🐞")
CI_L = rx(r"ci[- ]failure|^ci$|area:ci|\btests?\b|flaky")


def thread_type(t, title):
    labels = [l.lower() for l in t["labels"]]
    for lab, r in TT_PREFIX:
        if r.search(title):
            if lab == "docs" and re.search(r"(fail|error|broken|not working|outdated|wrong|incorrect)", title, I) and not DOCS_T.search(title):
                return "problem"
            return lab
    if CI_T.search(title) or any(CI_L.search(l) for l in labels):
        return "pr_ci"
    err = bool(ERRORISH.search(title))
    if DOCS_T.search(title) and not err:
        return "docs"
    if any(DOCS_L.search(l) for l in labels) and not any(BUG_L.search(l) for l in labels):
        return "docs"
    if any(FEATURE_L.search(l) for l in labels) and not err:
        return "feature"
    if FEATURE_T.search(title) and not err:
        return "feature"
    if err or any(BUG_L.search(l) for l in labels):
        return "problem"
    if QUESTION_T.search(title) or any(QUESTION_L.search(l) for l in labels):
        return "question"
    if ERRORISH.search(t.get("body", "")[:1500]):
        return "problem"
    return "other"


def code(t):
    title, body = t["title"], t["body"]
    others_c = [c for c in t["comments"] if not c["by_author"] and not c["is_bot"]]
    coms = " ".join(c["body"] for c in t["comments"])
    text = title + "\n" + body
    repo, g = t["repo"], t["group"]
    out = {}
    alltext = text + "\n" + coms
    out["kw_relevant"], out["kw_unsure"] = relevance(t, title, text, alltext)
    out["kw_thread_type"] = thread_type(t, title)
    builder_self = g == "builder" and repo == "stackblitz-labs/bolt.diy" and bool(BUILDER_SELF.search(text[:2000]))
    # host: title first, then body, then repo default
    out["kw_target_host"] = first(HOSTS, title) or first(HOSTS, body) or REPO_HOST.get(repo) or "unspecified"
    # app type
    data_cue = re.search(r"\brag\b|retriev|vector|embedding|knowledge base|ai search|cognitive ?search|own data|your data|index(es)? ", text, I)
    if g == "builder" and not builder_self:
        at = "ai_generated_web_app"
    elif re.search(r"\bagents?\b|langgraph|crew|reasoning engine|agent engine|adk\b", text, I) or repo in ("langchain-ai/langgraph", "mastra-ai/mastra", "google/adk-python", "crewAIInc/crewAI", "agno-agi/agno", "GoogleCloudPlatform/agent-starter-pack"):
        at = "agent"
    elif repo in ("Azure-Samples/azure-search-openai-demo", "Azure-Samples/chat-with-your-data-solution-accelerator", "infiniflow/ragflow", "Mintplex-Labs/anything-llm", "Azure-Samples/rag-postgres-openai-python", "Azure-Samples/contoso-chat") or data_cue:
        at = "rag"
    elif repo in ("huggingface/text-generation-inference", "replicate/cog", "ollama/ollama", "vllm-project/vllm", "BerriAI/litellm", "skypilot-org/skypilot") or re.search(r"serv(e|ing) (the |a )?model|inference (server|endpoint)|model serving|sagemaker endpoint", text, I):
        at = "model_serving"
    elif repo in ("ChatGPTNextWeb/NextChat", "mckaywrigley/chatbot-ui", "huggingface/chat-ui", "vercel/chatbot", "Chainlit/chainlit", "open-webui/open-webui", "microsoft/sample-app-aoai-chatGPT") or re.search(r"chat ?bot|\bchat\b", text, I):
        at = "chatbot"
    else:
        at = "other"
    out["kw_app_type"] = at
    fw_default = "remix" if builder_self else (None if g == "builder" else REPO_FRAMEWORK.get(repo))
    out["kw_framework"] = fw_default or first(FRAMEWORKS, text) or "unspecified"
    stack = [fw_default] + [lab for lab, r in FRAMEWORKS if r.search(text)]
    out["kw_stack"] = ";".join(dict.fromkeys(s for s in stack if s)) or None
    prov_text = text if repo != "anthropics/claude-code" else re.sub(r"claude|anthropic", " ", text, flags=I)
    out["kw_model_provider"] = multi(PROVIDERS, prov_text) or REPO_PROVIDER.get(repo) or "unspecified"
    # error type and category: title evidence first, then body
    err_t, err_b = first(ERRORS, title), first(ERRORS, body[:3000])
    extra_t = first(CATEGORY_EXTRA, title)
    if err_t == "iac_template_error":  # provisioning failures: prefer the inner cause when stated
        inner = first([e for e in ERRORS if e[0] in ("quota_billing", "permission_rbac")], body[:3000])
        err_t = inner or err_t
    if err_t:
        cat, conf = CATEGORY_OF_ERROR[err_t], "title"
    elif extra_t:
        cat, conf = extra_t, "title"
    elif err_t:
        cat, conf = CATEGORY_OF_ERROR[err_t], "title"
    elif err_b:
        cat, conf = CATEGORY_OF_ERROR[err_b], "body"
    else:
        cat, conf = "other", "none"
    err = err_t or err_b or "other_unknown"
    if cat == "other":  # topics added 2026-10-30; never replace an existing topic
        nt, agent_err = new_topic(repo, title, body[:3000])
        if nt:
            cat = nt
            # the agent subtype replaces other_unknown, or a server_error_5xx found only in the body;
            # a 5xx seen in the title is kept. coding_confidence is left as is: it describes the evidence
            # for error_type and the 14 original topics, not for the three topics added 2026-10-30
            if agent_err and (err == "other_unknown" or (err == "server_error_5xx" and conf == "body")):
                err = agent_err
    out["kw_error_type"] = err
    out["kw_topic"] = cat
    out["coding_confidence"] = conf
    # AI-generated app
    tool = first(AI_TOOLS, text) if re.search(r"(built|made|generated|created|wrote|written|vibe)[^.]{0,40}(with|by|using)|vibe.?cod", text, I) else None
    tool = REPO_AI_TOOL.get(repo) or tool
    if builder_self:
        out["kw_ai_generated_app"], out["kw_ai_tool"] = "no", None
    else:
        out["kw_ai_generated_app"] = "yes" if tool else "unknown"
        out["kw_ai_tool"] = tool
    # thread outcome
    maint = [c for c in others_c if c.get("assoc") in ("OWNER", "MEMBER", "COLLABORATOR")]
    out["maintainer_replied"] = "yes" if maint else "no"
    stale = any(re.search(r"stale|inactiv|auto-?clos", l, I) for l in t["labels"]) or any(
        re.search(r"stale|inactiv|automatically closed|no activity|closing (this|due)", c["body"], I) for c in t["comments"] if c["is_bot"] or not c["by_author"])
    fix_words = r"(it )?works now|that (worked|fixed)|solved|resolved|fixed it|found (the|a) (fix|solution|problem|issue)|the (problem|issue) was|turns out|was related to|i fixed it|managed to"
    author_ok = any(c["by_author"] and re.search(fix_words + r"|thank(s| you).{0,40}(work|fix|help)", c["body"], I) for c in t["comments"]) \
        or bool(re.search(r"i fixed it|update: .{0,40}(fixed|solved)", body, I))
    dup = any(re.search(r"duplicate", l, I) for l in t["labels"]) or t.get("state_reason") == "duplicate"
    if t["state"] == "open":
        resolved = "yes" if author_ok else "no"
    else:
        resolved = "yes" if (t.get("state_reason") == "completed" and not stale) or author_ok else "no"
    out["resolved"] = resolved
    ocoms = " ".join(c["body"] for c in others_c)
    if dup:
        rt = "duplicate"
    elif not others_c:
        rt = "self_resolved" if author_ok else ("stale_closed" if stale and t["state"] == "closed" else "unanswered")
    elif re.search(r"not (intended|designed|supported|possible|planned)|limitation|by design|won'?t fix|out of scope|isn'?t supported|is not an? (actual )?(bug|flowise error)", ocoms, I) and t["state"] == "closed":
        rt = "platform_limit_no_fix" if not re.search(r"your (deployment )?environment|not a \w+ error", ocoms, I) else "user_error_config"
    elif re.search(r"fixed in|released in|(upgrade|update) to (the latest|v?\d)|new (version|release)|latest (version|release)|beta release|now fixed|merged a fix|merging a fix", ocoms, I):
        rt = "version_upgrade"
    elif re.search(r"downgrad|pin(ned)? to|roll(ed)? back to", coms, I):
        rt = "version_downgrade"
    elif re.search(r"workaround|work around|in the meantime|temporar|stopgap", coms, I):
        rt = "workaround"
    elif re.search(r"my (bad|mistake|fault)|typo|you forgot|user error|misconfig|your (deployment )?environment", coms, I):
        rt = "user_error_config"
    elif author_ok and re.search(r"\bset\b|config|setting|env(ironment)? var|--host|0\.0\.0\.0|add(ing)? .{0,20}to (your|the)|change", coms, I):
        rt = "config_fix"
    elif author_ok:
        rt = "self_resolved"
    elif stale and t["state"] == "closed":
        rt = "stale_closed"
    elif t["state"] == "open":
        rt = "open_unresolved"
    else:
        rt = "closed_unclear"
    out["kw_resolution_type"] = rt
    return out


# repos removed after the full-build review (see repos_full.json _doc); kept in the pilot file
DROPPED_REPOS = set()


def main():
    src = sys.argv[1] if len(sys.argv) > 1 else os.path.join(ROOT, "raw", "threads.jsonl")
    dst = sys.argv[2] if len(sys.argv) > 2 else os.path.join(ROOT, "raw", "coded_kw.jsonl")
    if "--drop-removed" in sys.argv:
        DROPPED_REPOS.update({"skypilot-org/skypilot", "replicate/cog"})
    with open(dst, "w") as f:
        for line in open(src):
            t = json.loads(line)
            if t["repo"] in DROPPED_REPOS:
                continue
            if t["repo"] in filters.GENERIC_REPOS and t["group"] == "framework":
                t["group"] = "framework_generic"   # rule 8: Gradio counts as a general framework
            rec = {k: v for k, v in t.items() if k not in ("body", "comments")}
            rec.update(code(t))
            rec["excerpt_private"] = excerpt(t["body"])
            f.write(json.dumps(rec) + "\n")


if __name__ == "__main__":
    main()