thoughtleaders-cli 0.9.23__py3-none-any.whl → 0.9.25__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: thoughtleaders-cli
3
- Version: 0.9.23
3
+ Version: 0.9.25
4
4
  Summary: ThoughtLeaders CLI — query sponsorship data, channels, brands, and intelligence
5
5
  Project-URL: Homepage, https://thoughtleaders.io
6
6
  Project-URL: Repository, https://github.com/ThoughtLeaders-io/thoughtleaders-cli
@@ -235,6 +235,17 @@ tl describe show sponsorships --filters # Available filters for sponsorships
235
235
  tl balance # Your credit balance
236
236
  ```
237
237
 
238
+ ### Usage resets
239
+
240
+ A usage reset refills your weekly credits to your plan's allotment and restarts your 5-hour session. You get one as a gift from ThoughtLeaders when you sign up, one for each new organization that signs up with your invite link, and a bonus when that organization makes its first proposal or payment. Resets expire 90 days after they're granted, and you spend them only when you choose to.
241
+
242
+ ```bash
243
+ tl resets # Resets you have, recent history, your invite link
244
+ tl resets use # Spend one (asks first; --yes skips the question)
245
+ ```
246
+
247
+ When a query is refused because you're out of credits or at your session limit, the error tells you if you have a reset to spend, and gives your invite link: invite a friend outside your organization and you get a free reset when they join.
248
+
238
249
  `tl db pg` is priced **per-row**: the per-row rate is the **sum of the rates of the tables the query touches** (default 1.0/row; some tables are cheaper or dearer), plus a flat per-row charge for every expensive column read (demographics, channel outreach emails), all times the rows returned. Aggregate queries (`count`/`GROUP BY`) add a surcharge proportional to the rows they aggregate. Run `tl describe show db --json` to see the live `pg_pricing` map, and check `usage.credit_rate` in the response envelope after a query to see what your query was actually charged.
239
250
 
240
251
  To preview a query's cost **before** running it, add `--pricing`: `tl db pg "SELECT … LIMIT 100" --pricing` runs only the planner's `EXPLAIN`, prints the cost breakdown and an upper-bound estimate (at the query's `LIMIT`), and costs a flat **1 credit** — the query itself never executes. Works with `--json` too. `--pricing` is also available on `tl db fb` and `tl db es`; those backends have no per-table or per-column charges, so the estimate is the flat per-row rate at the query's row ceiling (`LIMIT` for Firebolt, `size` — or the aggregation doc cap — for Elasticsearch).
@@ -1,11 +1,11 @@
1
- tl_cli/__init__.py,sha256=O6LBgMbq2lhYDavyT8KJsotoh_iKgHZMOAv7HdT19nA,113
1
+ tl_cli/__init__.py,sha256=FJmx37kfHmnIsBUD1CvOOOkLCvPjoXbgAtI_NqXLP-M,113
2
2
  tl_cli/__main__.py,sha256=-FCBeOBi5Zi0hhZI3FWRilisl2DHxKeszgkY0r9VLR4,444
3
3
  tl_cli/_completions.py,sha256=kOyEUqC26vbYvyXWi513WX8fF73qQLR5WWuRSe_wqyk,164
4
4
  tl_cli/_typer_utils.py,sha256=ZiZsCVmEznPvBw-dYbr3tu3zWZ0iN6kjoQmK3gMqD28,860
5
5
  tl_cli/config.py,sha256=w-_uC8jrHOj5GX2POxL0xUN6J1iy32W6VAlrzNQKs5E,2239
6
6
  tl_cli/filters.py,sha256=Yjj04lONGGmtCAIYN5i6KD12mAnUKEZ7i9heeWtdj7o,2952
7
7
  tl_cli/hints.py,sha256=cT8kuDtkAZqwXkc2RV0Yg_abofK-g9UiXwTTBunX78U,1557
8
- tl_cli/main.py,sha256=M4i6gDCT42ulpnEQJuosb3h-OadrRBE82OpW4OJJ7nQ,6653
8
+ tl_cli/main.py,sha256=SnNazaGCB_J3n3xuIkAJwDK7Odaj7nOiw9grBWStORI,6747
9
9
  tl_cli/query_history.py,sha256=vA5avDU1DBZDWSb-w2ZxEZxV2MD21cqwzfYjXawOWZI,5540
10
10
  tl_cli/self_update.py,sha256=ea4zoNXcWWoMrSxc9zzoy4OM-rxZHCWPquV48k9_gTE,19091
11
11
  tl_cli/skill_registry.py,sha256=slB3K0tI_-mrPT7Eswzq2Sjlo8Wcwk5nDy0w9yQh6mM,11957
@@ -15,7 +15,7 @@ tl_cli/auth/login.py,sha256=BWIGqHF6EMj41G4MeGhGNh2OdF10USCOnylBRV18nYI,14819
15
15
  tl_cli/auth/pkce.py,sha256=4Q6Ip-TeZFNG9c3swXNi4gH7mdMkltKa62gZZNybt8U,658
16
16
  tl_cli/auth/token_store.py,sha256=qX0AIw4RGxCDpoeygc5CoCOkp8L7ppEXTyUVEiIuK9E,3446
17
17
  tl_cli/client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
- tl_cli/client/errors.py,sha256=rZJNpzJnqOJ4oL7VjQcqQlZV2SoU5MbHTIbeCUyMr6I,6000
18
+ tl_cli/client/errors.py,sha256=vkfZB8nX2KFLJcnKNNzOFEuXomuNFL0sVAvbffLBMP0,7270
19
19
  tl_cli/client/http.py,sha256=KMDlHtKsfBCfD7-OiCic7SG5iAgHO0z25COtaQPx0fI,6342
20
20
  tl_cli/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
21
  tl_cli/commands/_comments_common.py,sha256=x91WPSpDdV8AwE8Mwx4VtZQKWXBufsnBnC1lFD0Tzys,4522
@@ -36,6 +36,7 @@ tl_cli/commands/profiles.py,sha256=nnfp96iKFxnj_We73t8NUGgL-1F_x2H2XG2QM0brXy8,2
36
36
  tl_cli/commands/proposals.py,sha256=IXx9DsR7lPWRM4QvKB65t7xKNAK3H6ax9LIlIj8ydEs,2945
37
37
  tl_cli/commands/recommender.py,sha256=oDXcsmcfNgeNMUgxZuEL_UjPTn9UFwDTqb_-EuTlZdM,21394
38
38
  tl_cli/commands/reports.py,sha256=u7vtxcybITYih17iNZKsFN4LZwBSqh9L3iBo27OLubY,30754
39
+ tl_cli/commands/resets.py,sha256=0I1XA5QMQNZwS8L306uiS105AcF97BpXP3k5yEBQBiY,7132
39
40
  tl_cli/commands/schema.py,sha256=rmfg5pvKHa5kQi59YBIHCMzBNawmYPi2tBMcZP7Vrxw,6432
40
41
  tl_cli/commands/setup.py,sha256=1VCU8iURJZA0X_Q6ukGfomS8RfI_yWJiMqpp9qTdW9E,37360
41
42
  tl_cli/commands/skills.py,sha256=4Vg5ph6T7T3WcIqIZc83EJPhtB79FE7fMej9uVhElqc,15884
@@ -47,7 +48,7 @@ tl_cli/commands/workflows.py,sha256=ctduYa--Md6zbs8kQwO6mSyR9o1KB1UpNOaANuupDfU,
47
48
  tl_cli/output/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
48
49
  tl_cli/output/formatter.py,sha256=itNyHcDfRbksJgJ58JLtwJIrlHjqQj9gmK6uc3d9bSM,25692
49
50
  tl_cli/_plugin/.claude-plugin/marketplace.json,sha256=l56PMmyjfGXNGlV30wRyOAe74B6gJNCVNCxgsBbSNxc,446
50
- tl_cli/_plugin/.claude-plugin/plugin.json,sha256=ZhfSI025MJDNUQcVNaUeD2zKCTKiqubs2uaYwbNBxE8,467
51
+ tl_cli/_plugin/.claude-plugin/plugin.json,sha256=uWYFqkkObW0NN0twaFeUo4i703EG0fsmqKzyg8SMc1E,467
51
52
  tl_cli/_plugin/agents/cast-sheet.md,sha256=0owR8XIjR4tbKuK4t3WruiJAjGQ8se2cnOGwzigs4Lk,1224
52
53
  tl_cli/_plugin/agents/gem-classifier.md,sha256=s9kkbhUc-JhJ_be9z6LNaojykQSV16zrOd-QVaKNwxc,1250
53
54
  tl_cli/_plugin/agents/keyword-context-classifier.md,sha256=8Pk6WqJKuF-ERkBh54Aa-9t60CvjdOIH0RurFlG-T7I,4325
@@ -65,7 +66,7 @@ tl_cli/_plugin/skills/connector-impact/SKILL.md,sha256=K4mozNpRSLjTSICRTX8LihnKI
65
66
  tl_cli/_plugin/skills/connector-impact/references/help.md,sha256=Wd8X35OwYAswj-xoFZPnCWctwFIx9EXNZ511FDB2I5c,5831
66
67
  tl_cli/_plugin/skills/connector-impact/references/impact-schema.md,sha256=dlAtA6OwkqgXojaItnaQBEIXVxLoVuavuWsPtQ4Rc_0,10155
67
68
  tl_cli/_plugin/skills/connector-impact/references/impact-to-tl-mapping.md,sha256=58IJ5r1I0aEmIETFm81vMAbd1NxVMol8-fqqvHG3qXY,22122
68
- tl_cli/_plugin/skills/tl/SKILL.md,sha256=C9XAkgeQUB-Or8-CSbZPVwoh9JS184bK0gj1y7nNiJ8,72757
69
+ tl_cli/_plugin/skills/tl/SKILL.md,sha256=W2AhPCr9GZLQjquHkdVjVL3y7z5N8blzbKNYKce_f54,73200
69
70
  tl_cli/_plugin/skills/tl/references/business-glossary.md,sha256=DkM-3DGnI_Dvr8fsB9B00-5erXv9r94umFCMVBGOxEs,20214
70
71
  tl_cli/_plugin/skills/tl/references/elasticsearch-schema.md,sha256=zjuHmJRooTTZvu2GfoQxG8xmRcExcKa33K1jipLAShI,25222
71
72
  tl_cli/_plugin/skills/tl/references/firebolt-schema.md,sha256=yf_elP_qXQePtMJNMshoVUOrI_3CXezF0NOoiYTbMNU,11335
@@ -122,16 +123,16 @@ tl_cli/_plugin/skills/tl-create-workflow/references/creating-in-app.md,sha256=mJ
122
123
  tl_cli/_plugin/skills/tl-create-workflow/references/methodology.md,sha256=oXth-akS6QD7GmSDQRMaenAViTC5tlRgXIq_5uXVQQg,3847
123
124
  tl_cli/_plugin/skills/tl-create-workflow/references/pitfalls.md,sha256=6XBbe7T3o9PQcEs5FGNZ3n6xqVz0ZoNoFttJ9nNDjBU,3289
124
125
  tl_cli/_plugin/skills/tl-create-workflow/references/workflow-model.md,sha256=39cNg6AaSjb5K54neBkkn_RVJa7g9UnfZ_pVSzUsjDI,4591
125
- tl_cli/_plugin/skills/tl-keyword-research/SKILL.md,sha256=wvLvlumbR5fDxL-PZAqRDu7azYl4MXe1A5vOBn8YghE,38264
126
+ tl_cli/_plugin/skills/tl-keyword-research/SKILL.md,sha256=9KtLmWzPr93_i1dqrPnFx5yLC58EVoFGpIZJRG1kf6Y,41630
126
127
  tl_cli/_plugin/skills/tl-keyword-research/references/elasticsearch-content-search.md,sha256=fsXbpI3DPtkOnPEquB11Efur665o963RDN4-WIJCRJs,24263
127
128
  tl_cli/_plugin/skills/tl-keyword-research/references/help.md,sha256=yTmoU-Z6rPDjprbDa09nePoON0jnRSh_FVc7lqu1XGs,6802
128
- tl_cli/_plugin/skills/tl-keyword-research/scripts/build_report.py,sha256=oHCYfhFc006QhAv17R5uahpOMk38N1_YH_Cn6QMhQg4,22136
129
- tl_cli/_plugin/skills/tl-keyword-research/scripts/expand_entities.py,sha256=yYRfGRTl762Kvpv1xH_3nDZfShaX8BHoTRtmHyCsLk8,10886
129
+ tl_cli/_plugin/skills/tl-keyword-research/scripts/build_report.py,sha256=T_3xQ7vo_wdyZD5ObHrH5Lo_T-TcmBDygvXpfK-4P5I,23149
130
+ tl_cli/_plugin/skills/tl-keyword-research/scripts/expand_entities.py,sha256=r60FsvQiOsrCHG9xM1sGbzcN4kQTjWHSoiprVy61Ps4,12940
130
131
  tl_cli/_plugin/skills/tl-keyword-research/scripts/fetch_context.py,sha256=dn4n-WPjz4lib42hrDxrTN_xwqy1GZDpURE-IE6OKkg,6877
131
- tl_cli/_plugin/skills/tl-keyword-research/scripts/probe.py,sha256=eWmN8406QgrAcK_gvxNn63TX_NuF7Qk-X_CYK_MdMdU,28270
132
+ tl_cli/_plugin/skills/tl-keyword-research/scripts/probe.py,sha256=WiDdo39Wd0CXau2kn4Z5l__8dr9Spr2TkN3OCRPdj8o,31755
132
133
  tl_cli/_plugin/skills/tl-keyword-research/scripts/search_channels.py,sha256=qoe70bfpSWujO12eFP-OnfrqwbI7FgWTP_9aWavw3-U,23189
133
134
  tl_cli/_plugin/skills/tl-keyword-research/scripts/search_videos.py,sha256=Q_fYr1BzrMr5nh9wC1ruBJuIQFzNBkkBnYNMmsSEnc4,14568
134
- tl_cli/_plugin/skills/tl-keyword-research/scripts/select_keywords.py,sha256=eiavZfs-i2zAarR4k1_RT5wgqCr21T42S0AmwrXQid8,9359
135
+ tl_cli/_plugin/skills/tl-keyword-research/scripts/select_keywords.py,sha256=yQagYIN_Ql7AS-A02SwrUwOGEMNTyyms8hQYCcDZmPo,12791
135
136
  tl_cli/_plugin/skills/tl-save-report/SKILL.md,sha256=Sf1zIbLaJnCq2-IctIJrQDWWsTXJOTkkNzg4poc-wdo,37550
136
137
  tl_cli/_plugin/skills/tl-save-report/references/columns_brands.md,sha256=H5G308GOzMWvWw6smkPGdb2CBuuxkrojCpJgWS9X4sA,3559
137
138
  tl_cli/_plugin/skills/tl-save-report/references/columns_channels.md,sha256=g57ET_VI611lB7fVrGwYFvTDqMkNB63OmmfrnbMZF1I,4684
@@ -148,8 +149,8 @@ tl_cli/_plugin/skills/tl-top-partnerships/SKILL.md,sha256=jOMMr40XRnAZv-oRLeyKJT
148
149
  tl_cli/_plugin/skills/tl-top-partnerships/scripts/top_partnerships.py,sha256=OqhoyvFe1zrtrStChcam7oPYgFnSbGHC3WAgLhLIC3w,13738
149
150
  tl_cli/_plugin/skills/tl-views-guarantee/SKILL.md,sha256=IH7q1WJDWri9TWJMiga1FMGJO_GKSbWwaDS6CVNZ9c0,9270
150
151
  tl_cli/_plugin/skills/tl-views-guarantee/scripts/vg.py,sha256=5FucKm0WXa16btyUKMyGpdRQ5euVhzKMSoTonuwlm5I,16444
151
- thoughtleaders_cli-0.9.23.dist-info/METADATA,sha256=_tnnKup-PkJxYilQwLfi9lE7-FQVlB2dugCUa_h14qk,22294
152
- thoughtleaders_cli-0.9.23.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
153
- thoughtleaders_cli-0.9.23.dist-info/entry_points.txt,sha256=umZp-1BkGkHDG0bNZXpTXrjwW0HGf9IDFN40eAWuuvg,39
154
- thoughtleaders_cli-0.9.23.dist-info/licenses/LICENSE,sha256=RUfdfLsn6jygiyrnnVUHt6r4IPwr2rbDm9Kixgtu8fo,1071
155
- thoughtleaders_cli-0.9.23.dist-info/RECORD,,
152
+ thoughtleaders_cli-0.9.25.dist-info/METADATA,sha256=I6U7BB-Iuj9jpwZYbvu5xxSNT2xHtPXranq2G-hxmnw,23146
153
+ thoughtleaders_cli-0.9.25.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
154
+ thoughtleaders_cli-0.9.25.dist-info/entry_points.txt,sha256=umZp-1BkGkHDG0bNZXpTXrjwW0HGf9IDFN40eAWuuvg,39
155
+ thoughtleaders_cli-0.9.25.dist-info/licenses/LICENSE,sha256=RUfdfLsn6jygiyrnnVUHt6r4IPwr2rbDm9Kixgtu8fo,1071
156
+ thoughtleaders_cli-0.9.25.dist-info/RECORD,,
tl_cli/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """ThoughtLeaders CLI — query sponsorship data, channels, brands, and intelligence."""
2
2
 
3
- __version__ = "0.9.23"
3
+ __version__ = "0.9.25"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tl-cli",
3
- "version": "0.9.23",
3
+ "version": "0.9.25",
4
4
  "description": "ThoughtLeaders CLI — query sponsorship deals, channels, brands, uploads, and intelligence from the terminal",
5
5
  "author": {
6
6
  "name": "ThoughtLeaders",
@@ -111,7 +111,7 @@ Other key concepts:
111
111
  - **`purchase_date`** — when the sponsorship was purchased (i.e. when the deal was made); These make up bookings.
112
112
  - **`scheduled_date`** — the date the video is/was expected to be published (scheduled)
113
113
  - **`publish_date`** — the date the video was actually published; These make up live ads.
114
- - **Credits** — every data query costs credits; use `tl describe` to see rates. Top up with `tl credits buy --amount-usd N` (free; opens a browser checkout). New accounts get a starter balance on first `tl auth login`; the rate is shown by `tl credits pricing`.
114
+ - **Credits** — every data query costs credits; use `tl describe` to see rates. Top up with `tl credits buy --amount-usd N` (free; opens a browser checkout). New accounts get a starter balance on first `tl auth login`; the rate is shown by `tl credits pricing`. When a credits or session-limit refusal says the user has usage resets, a reset refills their weekly credits and restarts their 5-hour session; `tl resets` lists them. Spending one is the user's call: ask them first, and only then run `tl resets use --yes`.
115
115
 
116
116
  Users see data scoped by their organization and plan:
117
117
  - **Media buyers** see sponsorships where their org is the brand. They see `price` but never `cost`.
@@ -559,6 +559,8 @@ tl balance --json # Credit balance + recent usage (free)
559
559
  tl credits pricing # Current usd-per-credit rate (free, no auth)
560
560
  tl credits buy --amount-usd 10 # Start a top-up; opens browser checkout (free)
561
561
  tl credits history # Recent top-ups for the caller's org (free)
562
+ tl resets --json # Usage resets, invite link, referrals (free)
563
+ tl resets use --yes # Spend a usage reset — only after the user says so (free)
562
564
  tl whoami # Current user, org, brands (free)
563
565
  tl auth status # Auth check (free)
564
566
  tl changelog # Release notes — current version, or current..latest if behind (free)
@@ -23,6 +23,33 @@ description: |
23
23
  common is X". Also invoke for HELP asks about this skill — "help", "how
24
24
  does keyword research work", "what are my options", "describe this skill" —
25
25
  answered free from the built-in guide, no queries run.
26
+ output-schema:
27
+ type: object
28
+ required: [keyword_groups, keyword_operator, assumptions]
29
+ properties:
30
+ keyword_groups:
31
+ type: array
32
+ items:
33
+ type: object
34
+ required: [text]
35
+ properties:
36
+ text: {type: string}
37
+ content_fields:
38
+ type: array
39
+ items: {type: string}
40
+ exclude: {type: boolean}
41
+ keyword_operator: {type: string, enum: [OR, AND]}
42
+ assumptions:
43
+ type: array
44
+ items: {type: string}
45
+ dropped:
46
+ type: array
47
+ items:
48
+ type: object
49
+ required: [text, reason]
50
+ properties:
51
+ text: {type: string}
52
+ reason: {type: string}
26
53
  ---
27
54
 
28
55
  # tl-keyword-research — topic → validated filter set + the results you choose
@@ -69,6 +96,33 @@ verbatim via `search_channels.py --group` / `search_videos.py --group`.
69
96
 
70
97
  `<SKILL_DIR>` below is this skill's directory (the one holding `SKILL.md`).
71
98
 
99
+ ## On the ThoughtLeaders platform
100
+
101
+ The same skill also runs on the ThoughtLeaders platform, when a user starts
102
+ keyword research from their dashboard. You are on the platform when the tools
103
+ `kw_probe` and `kw_validate` are available. The method in this file applies
104
+ unchanged, with these differences:
105
+
106
+ - **No shell and no sub-agents.** Stages that run a script or an agent carry
107
+ an *On the platform* note naming the tool to use instead.
108
+ - **Nobody to ask.** The task gives you the path (quick or deep) and the
109
+ deliverable. Make every scope call yourself and record it in `assumptions`.
110
+ Run the deep path autonomously: no checkpoint after round 3.
111
+ - **Titles and summaries only.** Search the `title` and `summary` fields,
112
+ never `transcript`.
113
+ - **Stop after Stage 4.** The platform builds the trend data, channel tiers,
114
+ report link and previews from your final groups, so skip Stage 5 and the
115
+ scripts in Stage 6.
116
+ - **Decide, don't count.** Finish with `submit_result`, shaped by this
117
+ skill's `output-schema`: the final keyword groups, the operator, your
118
+ assumptions, and the groups you dropped with a reason. Never put counts or
119
+ channel figures in the result.
120
+ - **Narrate with `report_progress`.** Call it at the start of each stage with
121
+ the stage name exactly as the pipeline table writes it (`Set up`, `Expand`,
122
+ `Probe`, `Validate keywords`, `Refine`), instead of messaging the user.
123
+ - **References.** Read `references/elasticsearch-content-search.md` with
124
+ `read_skill_file`.
125
+
72
126
  ## When to invoke / skip
73
127
 
74
128
  Invoke when the user wants **videos or channels by content** (topics, concepts,
@@ -234,6 +288,10 @@ index's samples, and every web-sourced name earns its place through the same
234
288
  probe + validation as any other candidate (no benefit of the doubt; a
235
289
  hallucinated name probes to `count: 0` and drops).
236
290
 
291
+ *On the platform:* use `web_search` (at most two searches) in place of the
292
+ `keyword-entity-resolver` agent, then add each name and its spelling variants
293
+ to your candidates yourself, following Stage 1's rules.
294
+
237
295
  ### Stage 1 — Expand: go wide, go deep, go creative
238
296
 
239
297
  A shallow synonym list is the #1 failure mode. Coverage is won or lost here.
@@ -271,6 +329,11 @@ Rules:
271
329
 
272
330
  ### Stage 2 — Probe (`probe.py`)
273
331
 
332
+ *On the platform:* call `kw_probe` with the candidates and the same options
333
+ `probe.py` takes (`level`, `mode`, `fields`, `samples`, `content_type`,
334
+ `since`, `until`). It returns the counts; the samples stay with the platform
335
+ for `kw_validate`.
336
+
274
337
  One ES query per candidate → counts + samples for validation:
275
338
 
276
339
  ```bash
@@ -322,6 +385,11 @@ surviving variants before delivery.
322
385
  This fixes "the word is there but the topic isn't" — the step that separates
323
386
  this skill from a free YouTube search.
324
387
 
388
+ *On the platform:* call `kw_validate` on the probe with the verbatim intent. It
389
+ runs the relevance check and the strict-majority rule, and returns the kept
390
+ and dropped keywords. Scope calls are yours: decide them and record them in
391
+ `assumptions`.
392
+
325
393
  **Inline (≤ ~15 candidates):** read each keyword's `samples` against the
326
394
  verbatim intent. Drop off-intent keywords, `count: 0`, and redundant
327
395
  `subsumed_by` duplicates.
@@ -448,8 +516,14 @@ then fold the answers into the groups and the validators' TOPIC/NOT lines.
448
516
  run ≥3 rounds, stop when fitness stops improving (sane cap ~6 rounds), note
449
517
  that you ran autonomously.
450
518
 
519
+ *On the platform:* always run autonomously, measuring with `kw_probe` (mode
520
+ `sqs`) and re-validating with `kw_validate`.
521
+
451
522
  ### Stage 5 — Materialize the chosen deliverables
452
523
 
524
+ *On the platform:* skip this stage. The platform builds the deliverables from
525
+ your final groups.
526
+
453
527
  Everything here takes the final filter verbatim via `--group`, so what you
454
528
  deliver is exactly what the filter selects.
455
529
 
@@ -541,6 +615,11 @@ on-topic uploads. Tell the user when one channel dominates and offer
541
615
 
542
616
  ### Stage 6 — Deliver (`build_report.py`)
543
617
 
618
+ *On the platform:* don't run `build_report.py` and don't offer to save. Call
619
+ `submit_result` with the groups in the same shape (`text`, plus
620
+ `content_fields` / `exclude` where needed); the platform prunes them,
621
+ translates them into the report grammar and builds the link.
622
+
544
623
  Hand the validated groups to the builder — start from `select_keywords.py
545
624
  --apply`'s `groups`, adding per-group `content_fields` / `exclude` as needed:
546
625
 
@@ -39,7 +39,15 @@ Input (stdin JSON):
39
39
  }
40
40
 
41
41
  Output (stdout): a single JSON object — see OUTPUT CONTRACT at the bottom.
42
+
43
+ Library use: the file is import-safe (standard library only, nothing runs at import),
44
+ so another Python program can load it by path and call `build(spec, *, app_url=...)`.
45
+ `spec` is the parsed input object above; the return value is the object the command
46
+ prints. `build` leaves `spec` untouched and returns fresh structures. A bad spec raises
47
+ `ReportSpecError` (a `ValueError`). Library functions never print, read stdin or exit.
42
48
  """
49
+ from __future__ import annotations
50
+
43
51
  import argparse
44
52
  import json
45
53
  import re
@@ -116,6 +124,10 @@ DEFAULT_FIELDS = {
116
124
  }
117
125
 
118
126
 
127
+ class ReportSpecError(ValueError):
128
+ """The spec handed to `build` is unusable."""
129
+
130
+
119
131
  def tokens(text):
120
132
  return _TOKEN_RE.findall(text.lower())
121
133
 
@@ -389,33 +401,23 @@ def build_report_config(filter_set, report_type_int, title, description):
389
401
  }
390
402
 
391
403
 
392
- def main():
393
- ap = argparse.ArgumentParser(
394
- description="Build the keyword-research deliverable (filter set + report link) from validated groups."
395
- )
396
- ap.add_argument("--app-url", default=DEFAULT_APP_URL, help=f"App base URL (default {DEFAULT_APP_URL})")
397
- args = ap.parse_args()
398
-
399
- if sys.stdin.isatty():
400
- sys.exit("pipe a JSON spec on stdin (see module docstring)")
401
- try:
402
- spec = json.loads(sys.stdin.read())
403
- except json.JSONDecodeError as exc:
404
- sys.exit(f"invalid JSON on stdin: {exc}")
405
-
406
- operator = (spec.get("operator") or "OR").upper()
404
+ def build(spec, *, app_url=DEFAULT_APP_URL):
405
+ """Build the deliverable (filter set, report link, report config) from a spec; raises ReportSpecError."""
406
+ if not isinstance(spec, dict):
407
+ raise ReportSpecError("spec must be a JSON object")
408
+ operator = str(spec.get("operator") or "OR").upper()
407
409
  if operator not in ("AND", "OR"):
408
- sys.exit("operator must be AND or OR")
409
- report_type = (spec.get("report_type") or "channels").lower()
410
+ raise ReportSpecError("operator must be AND or OR")
411
+ report_type = str(spec.get("report_type") or "channels").lower()
410
412
  if report_type not in REPORT_TYPES:
411
- sys.exit(f"report_type must be one of {sorted(REPORT_TYPES)}")
413
+ raise ReportSpecError(f"report_type must be one of {sorted(REPORT_TYPES)}")
412
414
  slug, report_type_int = REPORT_TYPES[report_type]
413
415
  default_fields = spec.get("default_content_fields") or DEFAULT_FIELDS[report_type]
414
416
 
415
417
  groups = spec.get("groups") or []
416
- groups = [g for g in groups if isinstance(g, dict) and str(g.get("text", "")).strip()]
418
+ groups = [dict(g) for g in groups if isinstance(g, dict) and str(g.get("text", "")).strip()]
417
419
  if not groups:
418
- sys.exit("provide at least one group with non-empty 'text'")
420
+ raise ReportSpecError("provide at least one group with non-empty 'text'")
419
421
  for g in groups:
420
422
  g["text"] = str(g["text"]).strip()
421
423
 
@@ -426,7 +428,7 @@ def main():
426
428
  used_fields.update(g.get("content_fields") or [])
427
429
  unknown = sorted(f for f in used_fields if f not in VALID_CONTENT_FIELDS)
428
430
  if unknown:
429
- sys.exit(
431
+ raise ReportSpecError(
430
432
  f"unknown content_fields {unknown}; use recognized content field names "
431
433
  f"(e.g. title, summary, transcript, channel_description, "
432
434
  f"channel_topic_description) — not raw ES paths. Valid: {sorted(VALID_CONTENT_FIELDS)}"
@@ -443,18 +445,18 @@ def main():
443
445
  try:
444
446
  app_text = sqs_to_app_syntax(g["text"])
445
447
  except ValueError as exc:
446
- sys.exit(f"group {g['text']!r}: {exc}")
448
+ raise ReportSpecError(f"group {g['text']!r}: {exc}")
447
449
  if app_text != g["text"]:
448
450
  translated.append({"from": g["text"], "to": app_text})
449
451
  g["text"] = app_text
450
452
 
451
453
  filter_set = build_filter_set(kept, operator, default_fields)
452
- report_link = build_inline_link(kept, operator, slug, default_fields, args.app_url)
454
+ report_link = build_inline_link(kept, operator, slug, default_fields, app_url)
453
455
  title = spec.get("title") or f"{report_type.title()} — keyword search"
454
456
  description = spec.get("description") or ""
455
457
  report_config = build_report_config(filter_set, report_type_int, title, description)
456
458
 
457
- print(json.dumps({
459
+ return {
458
460
  "report_type": report_type,
459
461
  "operator": operator,
460
462
  "expression": render_expression(kept, operator),
@@ -463,7 +465,28 @@ def main():
463
465
  "report_config": report_config,
464
466
  "pruned": pruned,
465
467
  "translated": translated,
466
- }, ensure_ascii=False, indent=2))
468
+ }
469
+
470
+
471
+ def main():
472
+ ap = argparse.ArgumentParser(
473
+ description="Build the keyword-research deliverable (filter set + report link) from validated groups."
474
+ )
475
+ ap.add_argument("--app-url", default=DEFAULT_APP_URL, help=f"App base URL (default {DEFAULT_APP_URL})")
476
+ args = ap.parse_args()
477
+
478
+ if sys.stdin.isatty():
479
+ sys.exit("pipe a JSON spec on stdin (see module docstring)")
480
+ try:
481
+ spec = json.loads(sys.stdin.read())
482
+ except json.JSONDecodeError as exc:
483
+ sys.exit(f"invalid JSON on stdin: {exc}")
484
+
485
+ try:
486
+ out = build(spec, app_url=args.app_url)
487
+ except ReportSpecError as exc:
488
+ sys.exit(str(exc))
489
+ print(json.dumps(out, ensure_ascii=False, indent=2))
467
490
 
468
491
 
469
492
  # OUTPUT CONTRACT (stdout, single JSON object):
@@ -33,8 +33,19 @@ Usage:
33
33
  python3 expand_entities.py --existing "cannes lions" "advertising awards" < resolver.json > expanded.json
34
34
  # pipe the candidates straight into probe.py:
35
35
  python3 expand_entities.py --probe-batch < resolver.json | python3 probe.py --samples 5
36
+
37
+ Library use: the file is import-safe (standard library only, nothing runs at import),
38
+ so another Python program can load it by path and call `expand(resolver_reply, *,
39
+ existing=None)` (what the default mode prints) or `probe_batch(resolver_reply, *,
40
+ existing=None)` (what `--probe-batch` prints). `resolver_reply` is the parsed resolver
41
+ JSON; `existing` lists the candidates already brainstormed. Both return fresh structures
42
+ that share nothing with the input. Bad input raises `ExpandInputError` (a `ValueError`).
43
+ Library functions never print, read stdin or exit.
36
44
  """
45
+ from __future__ import annotations
46
+
37
47
  import argparse
48
+ import copy
38
49
  import json
39
50
  import re
40
51
  import sys
@@ -80,6 +91,10 @@ def solid(text):
80
91
  return _NONWORD_RE.sub("", text)
81
92
 
82
93
 
94
+ class ExpandInputError(ValueError):
95
+ """The resolver reply or options handed to the expander are unusable."""
96
+
97
+
83
98
  def _norm(text):
84
99
  """Case/space-insensitive key for dedupe."""
85
100
  return re.sub(r"\s+", " ", text.strip().lower())
@@ -156,8 +171,25 @@ def _collect_names(resolver, max_insider):
156
171
  return fams
157
172
 
158
173
 
159
- def expand(resolver, existing, max_insider):
160
- """Build probe candidates + family detail from a resolver JSON object."""
174
+ def check_resolver(resolver_reply):
175
+ """Raise ExpandInputError unless the resolver reply is a JSON object."""
176
+ if not isinstance(resolver_reply, dict):
177
+ raise ExpandInputError("resolver JSON must be an object")
178
+
179
+
180
+ def expand(resolver_reply, *, existing=None, max_insider=MAX_INSIDER_DEFAULT):
181
+ """Build probe candidates + family detail from a resolver JSON object (what the default mode prints).
182
+
183
+ `existing` lists candidates already brainstormed; matching forms are dropped.
184
+ `max_insider` caps the insider terms folded in. Raises ExpandInputError.
185
+ """
186
+ check_resolver(resolver_reply)
187
+ resolver = resolver_reply
188
+ existing = [] if existing is None else existing
189
+ if not isinstance(existing, (list, tuple)) or not all(isinstance(x, str) for x in existing):
190
+ raise ExpandInputError("existing must be a list of strings")
191
+ if max_insider < 0:
192
+ raise ExpandInputError("--max-insider must be >= 0")
161
193
  seen = {_norm(x) for x in existing} # forms already covered → skip
162
194
  deduped = []
163
195
 
@@ -211,7 +243,7 @@ def expand(resolver, existing, max_insider):
211
243
  )
212
244
  collisions = [c for c in (resolver.get("collisions", []) or []) if isinstance(c, dict)]
213
245
 
214
- return {
246
+ result = {
215
247
  "probe_candidates": probe_candidates,
216
248
  "families": families,
217
249
  "aliases": aliases,
@@ -228,6 +260,12 @@ def expand(resolver, existing, max_insider):
228
260
  "deduped": len(deduped),
229
261
  },
230
262
  }
263
+ return copy.deepcopy(result) # the caller's input is never shared with the output
264
+
265
+
266
+ def probe_batch(resolver_reply, *, existing=None, max_insider=MAX_INSIDER_DEFAULT):
267
+ """Just the probe_candidates array (what --probe-batch prints), ready for probe.py."""
268
+ return expand(resolver_reply, existing=existing, max_insider=max_insider)["probe_candidates"]
231
269
 
232
270
 
233
271
  def load_resolver():
@@ -240,8 +278,10 @@ def load_resolver():
240
278
  data = json.loads(raw)
241
279
  except json.JSONDecodeError as exc:
242
280
  sys.exit(f"invalid resolver JSON on stdin: {exc}")
243
- if not isinstance(data, dict):
244
- sys.exit("resolver JSON must be an object")
281
+ try:
282
+ check_resolver(data)
283
+ except ExpandInputError as exc:
284
+ sys.exit(str(exc))
245
285
  return data
246
286
 
247
287
 
@@ -259,7 +299,11 @@ def main():
259
299
  if args.max_insider < 0:
260
300
  sys.exit("--max-insider must be >= 0")
261
301
 
262
- out = expand(load_resolver(), args.existing, args.max_insider)
302
+ resolver = load_resolver()
303
+ try:
304
+ out = expand(resolver, existing=args.existing, max_insider=args.max_insider)
305
+ except ExpandInputError as exc:
306
+ sys.exit(str(exc))
263
307
  if args.probe_batch:
264
308
  print(json.dumps(out["probe_candidates"], ensure_ascii=False))
265
309
  else: