@koda-sl/baker-cli 0.890.0-dev.759c113cf → 0.890.0-dev.fb74d0c04

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.
Files changed (50) hide show
  1. package/README.md +2 -2
  2. package/dist/{ads-55VKXBMM.js → ads-FTIZ2QLC.js} +2 -2
  3. package/dist/{advertisers-X3PJG6Z6.js → advertisers-AKFTZJAL.js} +2 -2
  4. package/dist/{autocomplete-PWMUL7QJ.js → autocomplete-EBTBGCVM.js} +2 -2
  5. package/dist/{brief-4GIXLWHD.js → brief-3IJH6ADD.js} +4 -4
  6. package/dist/{chunk-DUJCU5NO.js → chunk-D6LOQ7X2.js} +2 -2
  7. package/dist/{chunk-52GWXYQ6.js → chunk-RNOWWEA7.js} +3 -3
  8. package/dist/chunk-RNOWWEA7.js.map +1 -0
  9. package/dist/{chunk-ZJBKANBI.js → chunk-S2WLJBUA.js} +9 -8
  10. package/dist/chunk-S2WLJBUA.js.map +1 -0
  11. package/dist/cli.js +3 -3
  12. package/dist/{company-WBA5NN2V.js → company-JFASPEKT.js} +2 -2
  13. package/dist/{creatives-TRNKZBE5.js → creatives-VSSKFV65.js} +2 -2
  14. package/dist/{customers-MKBX6KJ5.js → customers-MGO6LEK7.js} +4 -4
  15. package/dist/{fetch-JVI3AO3Q.js → fetch-YVKQOGKD.js} +2 -2
  16. package/dist/{google-ads-FAAP6HCR.js → google-ads-4QI33CPF.js} +2 -2
  17. package/dist/{insights-PBJODKMY.js → insights-YXWOM5FX.js} +10 -13
  18. package/dist/insights-YXWOM5FX.js.map +1 -0
  19. package/dist/{keyword-metrics-AIOK6XG2.js → keyword-metrics-3CCOTXLY.js} +2 -2
  20. package/dist/{keywords-for-site-WKUQFYDA.js → keywords-for-site-DM4UZBIE.js} +2 -2
  21. package/dist/{linkedin-person-UPJBQUXL.js → linkedin-person-2UWQAMFI.js} +2 -2
  22. package/dist/{meta-OTEBUJM5.js → meta-57E652I4.js} +2 -2
  23. package/dist/{people-QFZI2E7P.js → people-TIUKYSZ4.js} +2 -2
  24. package/dist/{reddit-6A6426JJ.js → reddit-QH2T2OSH.js} +3 -3
  25. package/dist/{research-PUNEJ4WW.js → research-MR7Q47RX.js} +14 -14
  26. package/dist/{transcript-LQD4BQBX.js → transcript-5GXGPNS3.js} +2 -2
  27. package/dist/{web-Q6HMBNRS.js → web-RNU2PMMK.js} +2 -2
  28. package/package.json +1 -1
  29. package/dist/chunk-52GWXYQ6.js.map +0 -1
  30. package/dist/chunk-ZJBKANBI.js.map +0 -1
  31. package/dist/insights-PBJODKMY.js.map +0 -1
  32. /package/dist/{ads-55VKXBMM.js.map → ads-FTIZ2QLC.js.map} +0 -0
  33. /package/dist/{advertisers-X3PJG6Z6.js.map → advertisers-AKFTZJAL.js.map} +0 -0
  34. /package/dist/{autocomplete-PWMUL7QJ.js.map → autocomplete-EBTBGCVM.js.map} +0 -0
  35. /package/dist/{brief-4GIXLWHD.js.map → brief-3IJH6ADD.js.map} +0 -0
  36. /package/dist/{chunk-DUJCU5NO.js.map → chunk-D6LOQ7X2.js.map} +0 -0
  37. /package/dist/{company-WBA5NN2V.js.map → company-JFASPEKT.js.map} +0 -0
  38. /package/dist/{creatives-TRNKZBE5.js.map → creatives-VSSKFV65.js.map} +0 -0
  39. /package/dist/{customers-MKBX6KJ5.js.map → customers-MGO6LEK7.js.map} +0 -0
  40. /package/dist/{fetch-JVI3AO3Q.js.map → fetch-YVKQOGKD.js.map} +0 -0
  41. /package/dist/{google-ads-FAAP6HCR.js.map → google-ads-4QI33CPF.js.map} +0 -0
  42. /package/dist/{keyword-metrics-AIOK6XG2.js.map → keyword-metrics-3CCOTXLY.js.map} +0 -0
  43. /package/dist/{keywords-for-site-WKUQFYDA.js.map → keywords-for-site-DM4UZBIE.js.map} +0 -0
  44. /package/dist/{linkedin-person-UPJBQUXL.js.map → linkedin-person-2UWQAMFI.js.map} +0 -0
  45. /package/dist/{meta-OTEBUJM5.js.map → meta-57E652I4.js.map} +0 -0
  46. /package/dist/{people-QFZI2E7P.js.map → people-TIUKYSZ4.js.map} +0 -0
  47. /package/dist/{reddit-6A6426JJ.js.map → reddit-QH2T2OSH.js.map} +0 -0
  48. /package/dist/{research-PUNEJ4WW.js.map → research-MR7Q47RX.js.map} +0 -0
  49. /package/dist/{transcript-LQD4BQBX.js.map → transcript-5GXGPNS3.js.map} +0 -0
  50. /package/dist/{web-Q6HMBNRS.js.map → web-RNU2PMMK.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../api/src/ads-meta/insightsActions.ts","../../api/src/ads-meta/insightsCompare.ts","../../api/src/ads-meta/insightsPeriod.ts","../../api/src/ads-meta/insightsIntents.ts","../src/commands/ads/meta/insights.ts","../src/commands/ads/meta/placement-delivery.ts"],"sourcesContent":["/**\n * The compact view of Meta's insights action arrays (`actions`,\n * `cost_per_action_type`, `conversions`, …).\n *\n * Meta returns one conversion under up to six names — `complete_registration`,\n * `omni_complete_registration`, `offsite_conversion.fb_pixel_complete_registration`,\n * `onsite_web_…` — with the same count, beside every engagement count the\n * account ever had (likes, saves, unlikes, video views). A one-month revenue\n * read ran to ~35 entries per row and 3.7 KB, and agents cut it with `head -c`\n * past the spend figure (BAKER-855). So by default each alias family becomes one\n * entry under its plain name, and engagement and Meta's combined \"+ 20s calls\" /\n * \"+ Meta leads\" restatements are dropped from the mixed arrays. `--action-types`\n * keeps only the named ones; `--full` skips this module.\n */\n\ntype InsightsRow = Record<string, unknown>;\ntype ActionEntry = Record<string, unknown> & { action_type: string };\n\n/** Arrays that mix every action type; single-purpose arrays (video watch, outbound clicks) are only de-aliased. */\nconst MIXED_ACTION_FIELDS = new Set([\n \"actions\",\n \"unique_actions\",\n \"action_values\",\n \"cost_per_action_type\",\n \"cost_per_unique_action_type\",\n \"conversions\",\n \"conversion_values\",\n \"cost_per_conversion\",\n]);\n\nconst ENGAGEMENT_TYPES = new Set([\n \"page_engagement\",\n \"post_engagement\",\n \"post\",\n \"comment\",\n \"like\",\n \"photo_view\",\n \"video_view\",\n \"post_reaction\",\n \"post_interaction_gross\",\n \"post_interaction_net\",\n]);\n\n/** `onsite_conversion.post_save`, `…post_net_like`, `…post_unlike` and the rest of the post counters. */\nconst ENGAGEMENT_PREFIX = \"onsite_conversion.post_\";\n\n/** Meta's sums of a conversion with another result (`offsite_lead_add_20_s_calls`), each already its own entry. */\nconst COMBINED_TYPE = /_add_(?:\\d+_s_calls|meta_leads)$/;\n\n/** The channel prefixes Meta puts in front of one conversion's name; `omni_` is the cross-channel total. */\nconst ALIAS_PREFIXES = [\n \"omni_\",\n \"offsite_conversion.fb_pixel_\",\n \"onsite_web_app_\",\n \"onsite_web_\",\n \"app_custom_event.fb_mobile_\",\n];\n\n/** On-Facebook lead forms report under their own names; `lead` is the total that includes them. */\nconst LEAD_ALIASES = new Set([\"onsite_conversion.lead_grouped\", \"leadgen_grouped\"]);\n\n/** A custom event (`offsite_conversion.fb_pixel_custom.<Name>`) keeps its full name: it has no alias. */\nfunction canonicalType(type: string): string {\n if (LEAD_ALIASES.has(type)) return \"lead\";\n if (type.startsWith(\"offsite_conversion.fb_pixel_custom\")) return type;\n const prefix = ALIAS_PREFIXES.find((p) => type.startsWith(p));\n return prefix ? type.slice(prefix.length) : type;\n}\n\nfunction isNoise(type: string): boolean {\n return ENGAGEMENT_TYPES.has(type) || type.startsWith(ENGAGEMENT_PREFIX) || COMBINED_TYPE.test(type);\n}\n\nfunction isActionArray(value: unknown): value is ActionEntry[] {\n return (\n Array.isArray(value) &&\n value.every((entry) => typeof entry === \"object\" && entry !== null && typeof entry.action_type === \"string\")\n );\n}\n\n/** The cross-channel `omni_` entry, else the plain name, else the largest alias: never a sum, the aliases overlap. */\nfunction pickOf(canonical: string, family: ActionEntry[]): ActionEntry {\n return (\n family.find((entry) => entry.action_type === `omni_${canonical}`) ??\n family.find((entry) => entry.action_type === canonical) ??\n family.reduce((best, entry) => (Number(entry.value) > Number(best.value) ? entry : best))\n );\n}\n\nfunction representative(canonical: string, family: ActionEntry[]): ActionEntry {\n return { ...pickOf(canonical, family), action_type: canonical };\n}\n\n/** The `--action-breakdowns` dimensions an entry is sliced by (`action_device: \"iphone\"`), beyond its type. */\nfunction sliceOf(entry: ActionEntry): Array<[string, unknown]> {\n return Object.entries(entry).filter(([key]) => key.startsWith(\"action_\") && key !== \"action_type\");\n}\n\n/** One conversion's entries under each of its names, within one breakdown slice. */\nfunction familiesOf(entries: ActionEntry[]): ActionEntry[][] {\n const families = new Map<string, ActionEntry[]>();\n for (const entry of entries) {\n const key = JSON.stringify([canonicalType(entry.action_type), sliceOf(entry)]);\n families.set(key, [...(families.get(key) ?? []), entry]);\n }\n return [...families.values()];\n}\n\n/** Each printed plain name and the raw names compaction printed under it (`purchase` ← `omni_purchase`). */\ntype Folds = Map<string, Set<string>>;\n\n/**\n * Aliases collapse within one breakdown slice: an iPhone and a desktop count of one conversion are two entries.\n * Every raw name printed under its plain name is recorded in `folded`, but one `kept` as its own entry.\n */\nfunction collapse(entries: ActionEntry[], folded: Folds, kept: (raw: string) => boolean = () => false): ActionEntry[] {\n return familiesOf(entries).map((family) => {\n const canonical = canonicalType(family[0]?.action_type ?? \"\");\n for (const { action_type: raw } of family) {\n if (raw !== canonical && !kept(raw)) folded.set(canonical, (folded.get(canonical) ?? new Set()).add(raw));\n }\n return representative(canonical, family);\n });\n}\n\n/** `--action-types`: a plain name (its aliases collapsed), an exact raw name, or a custom event's own name. */\nfunction keepNamed(entries: ActionEntry[], wanted: string[], folded: Folds): ActionEntry[] {\n const raw = entries.filter(\n (entry) =>\n (wanted.includes(entry.action_type) && canonicalType(entry.action_type) !== entry.action_type) ||\n wanted.some((name) => entry.action_type.endsWith(`.${name}`)),\n );\n const named = collapse(\n entries.filter((entry) => wanted.includes(canonicalType(entry.action_type))),\n folded,\n (type) => raw.some((entry) => entry.action_type === type),\n );\n return [...named, ...raw.filter((entry) => !named.some((kept) => kept.action_type === entry.action_type))];\n}\n\n/** An attribution window's figure on an entry: `7d_click`, `1d_view`. */\nconst WINDOW_KEY = /^(\\d+)d_(click|view)$/;\n\n/**\n * Arrays whose figures do not add up across windows: a cost (`cost_per_action_type`),\n * a return (`purchase_roas`), a rate (`website_ctr`) or an average\n * (`video_avg_time_watched_actions`). Every other action array is a count or a value.\n */\nconst UNADDITIVE_FIELD = /^cost_per_|_roas$|_ctr$|_avg_/;\n\n/** The entry's widest click window plus its widest view window — disjoint, so they add up — among `windows` if named. */\nfunction windowSum(entry: ActionEntry, windows?: readonly string[]): number {\n const widest = new Map<string, { days: number; figure: number }>();\n for (const [key, figure] of Object.entries(entry)) {\n const window = WINDOW_KEY.exec(key);\n if (!window || (windows && !windows.includes(key)) || !Number.isFinite(Number(figure))) continue;\n const days = Number(window[1]);\n const seen = widest.get(window[2] ?? \"\");\n if (!seen || days > seen.days) widest.set(window[2] ?? \"\", { days, figure: Number(figure) });\n }\n return [...widest.values()].reduce((sum, { figure }) => sum + figure, 0);\n}\n\n/**\n * The entry's `value`, or when Meta sent none (BAKER-1549, where a script\n * crashed on `KeyError: 'value'`) its click and view windows summed, else 0.\n * A cost, return, rate or average does not add up, so one without a value\n * says null. Every compact entry has one.\n */\nfunction withValue(field: string, entry: ActionEntry): ActionEntry {\n if (entry.value !== undefined) return entry;\n if (UNADDITIVE_FIELD.test(field)) return { ...entry, value: null };\n return { ...entry, value: String(round2(windowSum(entry))) };\n}\n\n/** The keys on an entry beside its type, its total and its breakdown slices: its attribution figures (`7d_click`, `1d_ev`, `dda`). */\nfunction attributionKeys(entry: ActionEntry): string[] {\n return Object.keys(entry).filter((key) => key !== \"action_type\" && key !== \"value\" && !key.startsWith(\"action_\"));\n}\n\n/**\n * Whether a read's figures can be told in its `windows`: click and view\n * windows, which add up as `windowSum` adds them, or one other selector alone\n * (`1d_ev`, `dda`). `default` is Meta's own total, and a mix of models does not\n * add up, so those keep Meta's figures.\n */\nfunction readsInWindows(windows: readonly string[]): boolean {\n if (windows.includes(\"default\")) return false;\n return windows.length === 1 || windows.every((window) => WINDOW_KEY.test(window));\n}\n\n/** A count in `windows`: their click and view figures summed, or the one other selector's figure. */\nfunction countIn(entry: ActionEntry, windows: readonly string[]): number {\n if (windows.every((window) => WINDOW_KEY.test(window))) return windowSum(entry, windows);\n const figure = Number(entry[windows[0] ?? \"\"]);\n return Number.isFinite(figure) ? figure : 0;\n}\n\n/**\n * An entry read in `windows` other than Meta's default: Meta's `value` stays\n * its default-window total (click plus view) whatever was asked, and it leaves\n * out a window that counted nothing (BAKER-2422). So every requested window is\n * set, 0 where Meta split the entry and sent none of them, and `value` is their\n * figure: their sum for a count, the one window's figure for a cost or rate\n * (null across several). An entry Meta did not split at all (`value` alone)\n * may or may not have counted in them, so its figures are null: unknown, not 0.\n */\nfunction inWindows(field: string, entry: ActionEntry, windows: readonly string[]): ActionEntry {\n if (attributionKeys(entry).length === 0) {\n return { ...entry, ...Object.fromEntries(windows.map((window) => [window, null])), value: null };\n }\n const unadditive = UNADDITIVE_FIELD.test(field);\n const figures = Object.fromEntries(windows.map((window) => [window, entry[window] ?? (unadditive ? null : \"0\")]));\n const only = windows.length === 1 ? figures[windows[0] ?? \"\"] : null;\n const value = unadditive ? (only ?? null) : String(round2(countIn(entry, windows)));\n return { ...entry, ...figures, value };\n}\n\n/** An array whose figures depend on the windows: every mixed array, a return (`purchase_roas`), or any array Meta split. */\nfunction isWindowed(field: string, entries: ActionEntry[]): boolean {\n return (\n MIXED_ACTION_FIELDS.has(field) || /_roas$/.test(field) || entries.some((entry) => attributionKeys(entry).length > 0)\n );\n}\n\n/**\n * A row with every action entry's `value` filled, so compaction and its\n * disagreement hints read the same figures; read in `windows` when the read\n * named windows other than Meta's default.\n */\nfunction withValues(row: InsightsRow, windows: readonly string[] | undefined): InsightsRow {\n return Object.fromEntries(\n Object.entries(row).map(([field, value]) => {\n if (!isActionArray(value)) return [field, value];\n if (!windows || !isWindowed(field, value)) return [field, value.map((entry) => withValue(field, entry))];\n return [field, value.map((entry) => inWindows(field, entry, windows))];\n }),\n );\n}\n\nfunction compactArray(\n field: string,\n entries: ActionEntry[],\n wanted: string[] | undefined,\n out: { dropped: Set<string>; folded: Folds },\n) {\n const { dropped, folded } = out;\n if (!MIXED_ACTION_FIELDS.has(field)) return collapse(entries, folded);\n if (wanted) return keepNamed(entries, wanted, folded);\n const kept = entries.filter((entry) => {\n if (!isNoise(entry.action_type)) return true;\n dropped.add(entry.action_type);\n return false;\n });\n return collapse(kept, folded);\n}\n\n/**\n * A conversion whose names count it differently (`lead` 48, `offsite_conversion.fb_pixel_lead` 30):\n * the compact view prints one of them, so it says which and what the others counted (BAKER-2377).\n * Only the count arrays of conversions the compact view prints, its first such row as the example.\n */\nfunction disagreeingCounters(rows: InsightsRow[], wanted: string[] | undefined): string[] {\n const found = new Map<string, { example: string; rows: number }>();\n for (const row of rows) {\n for (const { label, example } of rowDisagreements(row, wanted)) {\n const seen = found.get(label);\n found.set(label, { example: seen?.example ?? example, rows: (seen?.rows ?? 0) + 1 });\n }\n }\n return [...found.entries()].map(\n ([label, { example, rows: count }]) =>\n `Meta's counters for ${label} disagree on ${count} ${count === 1 ? \"row\" : \"rows\"} (${example}); --full returns every counter.`,\n );\n}\n\n/** One row's printed conversions whose counters disagree, each with every counter's value and the one printed. */\nfunction rowDisagreements(row: InsightsRow, wanted: string[] | undefined): Array<{ label: string; example: string }> {\n return Object.entries(row).flatMap(([field, value]) => {\n if (!COUNT_FIELDS.has(field) || !isActionArray(value)) return [];\n return familiesOf(value).flatMap((family) => {\n const canonical = canonicalType(family[0]?.action_type ?? \"\");\n const printed = wanted ? wanted.includes(canonical) : !isNoise(canonical);\n const known = family.filter((entry) => entry.value !== null);\n if (!printed || new Set(known.map((entry) => Number(entry.value))).size < 2) return [];\n const label = columnOf(field, { ...family[0], action_type: canonical });\n const pick = pickOf(canonical, family);\n const counts = family.map((entry) => `${entry.action_type} ${String(entry.value)}`).join(\", \");\n return [{ label, example: `${counts}; ${label} shows ${String(pick.value)}, from ${pick.action_type}` }];\n });\n });\n}\n\n/**\n * The folds for a hint, every one (\"omni_purchase, offsite_conversion.fb_pixel_purchase → purchase; omni_lead → lead\"):\n * a lookup by a raw name finds nothing in the compact rows, so the hint has to say where each went (BAKER-3247).\n * Null when nothing was folded. Each caller names its own way to keep a raw name.\n */\nfunction foldedList(folded: Folds): string | null {\n if (folded.size === 0) return null;\n return [...folded.entries()].map(([canonical, raws]) => `${[...raws].join(\", \")} → ${canonical}`).join(\"; \");\n}\n\n/** Each printed count column whose entry satisfies `test`, and on how many rows. */\nfunction columnsWhere(rows: InsightsRow[], test: (entry: ActionEntry) => boolean): string[] {\n const found = new Map<string, number>();\n for (const row of rows) {\n for (const [field, value] of Object.entries(row)) {\n if (!COUNT_FIELDS.has(field) || !isActionArray(value)) continue;\n for (const entry of value.filter(test))\n found.set(columnOf(field, entry), (found.get(columnOf(field, entry)) ?? 0) + 1);\n }\n }\n return [...found.entries()].map(([column, count]) => `${column} (${count} ${count === 1 ? \"row\" : \"rows\"})`);\n}\n\n/**\n * The hints for the printed count entries a read in `windows` could not give\n * a figure in them: those Meta counted only in other windows, which read 0,\n * and those Meta did not split by window at all, which read null.\n */\nfunction windowHints(rows: InsightsRow[], windows: readonly string[]): string[] {\n const asked = windows.join(\",\");\n const outside = columnsWhere(\n rows,\n (entry) =>\n entry.value !== null &&\n Number(entry.value) === 0 &&\n attributionKeys(entry).some((key) => !windows.includes(key) && Number(entry[key]) > 0),\n );\n const unsplit = columnsWhere(rows, (entry) => entry.value === null);\n return [\n ...(outside.length === 0\n ? []\n : [\n `Meta counted ${outside.join(\", \")} only outside ${asked}, so each reads 0 on those rows: a real 0 in ${asked}, not a missing figure (Meta counted it in another window and none in ${asked}).`,\n ]),\n ...(unsplit.length === 0\n ? []\n : [\n `Meta sent ${unsplit.join(\", \")} as one total with no ${asked} figure, so each reads null on those rows: its count in ${asked} is not known, not 0; --full keeps Meta's own value, its 7d_click,1d_view total.`,\n ]),\n ];\n}\n\n/**\n * Every row with its action arrays compacted, the engagement or combined types\n * that were dropped, the raw names folded into a plain one, the conversions\n * whose counters disagreed, and, for a read in `windows` other than Meta's\n * default, the printed conversions it could not count in them.\n */\nexport function compactInsightsRows(\n rows: InsightsRow[],\n options: { actionTypes?: string[]; windows?: readonly string[] },\n): {\n rows: InsightsRow[];\n dropped: string[];\n folded: string | null;\n disagreements: string[];\n windowHints: string[];\n} {\n const dropped = new Set<string>();\n const folded: Folds = new Map();\n const windows = options.windows && readsInWindows(options.windows) ? options.windows : undefined;\n const valued = rows.map((row) => withValues(row, windows));\n const compacted = valued.map((row) =>\n Object.fromEntries(\n Object.entries(row).map(([field, value]) => [\n field,\n isActionArray(value) ? compactArray(field, value, options.actionTypes, { dropped, folded }) : value,\n ]),\n ),\n );\n return {\n rows: windows ? compacted.map((row) => inAskedWindowsOnly(row, windows)) : compacted,\n dropped: [...dropped],\n folded: foldedList(folded),\n disagreements: disagreeingCounters(valued, options.actionTypes),\n windowHints: windows ? windowHints(compacted, windows) : [],\n };\n}\n\n/** A row whose action entries keep only the asked `windows`' keys: the other windows were read only to tell a 0 from an unsplit total. */\nfunction inAskedWindowsOnly(row: InsightsRow, windows: readonly string[]): InsightsRow {\n return Object.fromEntries(\n Object.entries(row).map(([field, value]) => {\n if (!isActionArray(value)) return [field, value];\n return [\n field,\n value.map((entry) =>\n Object.fromEntries(\n Object.entries(entry).filter(([key]) => !attributionKeys(entry).includes(key) || windows.includes(key)),\n ),\n ),\n ];\n }),\n );\n}\n\n/** Arrays that count actions; their entries can be priced from the row's spend. */\nconst COUNT_FIELDS = new Set([\"actions\", \"unique_actions\", \"conversions\"]);\n\nconst CUSTOM_EVENT_PREFIX = \"offsite_conversion.fb_pixel_custom\";\n\n/** `actions.lead`, or `actions.lead[iphone]` for an `--action-breakdowns` slice. */\nfunction columnOf(field: string, entry: ActionEntry): string {\n const slice = sliceOf(entry).map(([, value]) => String(value));\n return slice.length === 0 ? `${field}.${entry.action_type}` : `${field}.${entry.action_type}[${slice.join(\",\")}]`;\n}\n\nfunction round2(value: number): number {\n return Math.round(value * 100) / 100;\n}\n\n/** Spend over count, for an unsliced count entry that is priced: spend is per row, never per breakdown slice. */\nfunction pricedEntry(field: string, entry: ActionEntry, priceAll: boolean): boolean {\n if (!COUNT_FIELDS.has(field) || sliceOf(entry).length > 0) return false;\n return priceAll || entry.action_type.startsWith(CUSTOM_EVENT_PREFIX);\n}\n\n/**\n * Rows for `--output md|csv`: each action array becomes one `<field>.<action_type>`\n * column holding its total, in place of the array as JSON in one cell. The\n * click/view split stays in `--output json|jsonl`. Meta adds each row's period\n * (`date_start`, `date_stop`) outside the requested fields; it leads the table.\n * A custom event (a CRM stage), or every type `--action-types` named\n * (`priceAll`), gets a `cost_per.<field>.<action_type>` column: the row's spend\n * over that count, in the requested attribution windows.\n */\nexport function insightsTable(\n rows: InsightsRow[],\n fields: string[],\n options: { priceAll?: boolean } = {},\n): { rows: InsightsRow[]; columns: string[] } {\n const priceAll = options.priceAll ?? false;\n const period = [\"date_start\", \"date_stop\"].filter(\n (field) => !fields.includes(field) && rows.some((row) => row[field] !== undefined),\n );\n const columns = [...period, ...fields].flatMap((field) => {\n const counts = new Set<string>();\n const costs = new Set<string>();\n for (const row of rows) {\n const value = row[field];\n if (!isActionArray(value)) continue;\n for (const entry of value) {\n counts.add(columnOf(field, entry));\n if (pricedEntry(field, entry, priceAll) && row.spend !== undefined)\n costs.add(`cost_per.${columnOf(field, entry)}`);\n }\n }\n return counts.size === 0 ? [field] : [...counts, ...costs];\n });\n const flat = rows.map((row) => {\n const out: InsightsRow = {};\n const spend = Number(row.spend);\n for (const [field, value] of Object.entries(row)) {\n if (!isActionArray(value)) {\n out[field] = value;\n continue;\n }\n for (const entry of value) {\n const column = columnOf(field, entry);\n out[column] = entry.value;\n const count = Number(entry.value);\n if (pricedEntry(field, entry, priceAll) && Number.isFinite(spend) && count > 0) {\n out[`cost_per.${column}`] = round2(spend / count);\n }\n }\n }\n return out;\n });\n return { rows: flat, columns };\n}\n\n/** The columns `--intent funnel` adds to every row. */\nconst FUNNEL_COLUMNS = [\"result_type\", \"results\", \"cvr\", \"cost_per_result\"];\n\n/** The conversions a funnel ends in, deepest first: the first one an ad reports is its result. */\nconst RESULT_PRIORITY = [\n \"purchase\",\n \"complete_registration\",\n \"lead\",\n \"submit_application\",\n \"subscribe\",\n \"start_trial\",\n \"schedule\",\n \"contact\",\n \"initiate_checkout\",\n \"add_payment_info\",\n \"add_to_cart\",\n];\n\n/** The count of `type`, null when one of its entries has no known count (a read in windows Meta did not split it by). */\nfunction countOf(actions: ActionEntry[], type: string): number | null {\n const entries = actions.filter((entry) => entry.action_type === type);\n if (entries.some((entry) => entry.value === null)) return null;\n return entries.reduce((sum, entry) => sum + Number(entry.value), 0);\n}\n\nfunction resultTypeOf(actions: ActionEntry[], wanted: string[] | undefined): string | null {\n const present = new Set(actions.map((entry) => entry.action_type));\n const named = (wanted ?? []).find((name) => [...present].some((type) => type === name || type.endsWith(`.${name}`)));\n if (named) return [...present].find((type) => type === named || type.endsWith(`.${named}`)) ?? null;\n const standard = RESULT_PRIORITY.find((type) => present.has(type));\n if (standard) return standard;\n const custom = actions\n .filter((entry) => entry.action_type.startsWith(CUSTOM_EVENT_PREFIX))\n .sort((a, b) => Number(b.value) - Number(a.value));\n return custom[0]?.action_type ?? null;\n}\n\n/**\n * `--intent funnel` rows with the figures the intent exists for: the ad's\n * result (the first `--action-types` name it reports, else its deepest standard\n * conversion, else its largest custom event), `cvr` as the percent of link\n * clicks that became one, and `cost_per_result` as spend over results. Reads\n * compacted rows, where each conversion sits under its plain name.\n */\nexport function withFunnelResults(rows: InsightsRow[], options: { actionTypes?: string[] }): InsightsRow[] {\n return rows.map((row) => {\n const actions = isActionArray(row.actions) ? row.actions : [];\n const resultType = resultTypeOf(actions, options.actionTypes);\n const results = resultType === null ? null : countOf(actions, resultType);\n const linkClicks =\n row.inline_link_clicks !== undefined ? Number(row.inline_link_clicks) : countOf(actions, \"link_click\");\n const spend = Number(row.spend);\n return {\n ...row,\n result_type: resultType,\n results,\n cvr: results !== null && linkClicks !== null && linkClicks > 0 ? round2((results / linkClicks) * 100) : null,\n cost_per_result: results !== null && results > 0 && Number.isFinite(spend) ? round2(spend / results) : null,\n };\n });\n}\n\n/**\n * `--intent leads` rows with `cost_per_lead`: spend over the row's `lead`\n * count, null when it has none. md prices it as `cost_per.actions.lead`; json\n * and the channel engine read the compacted rows, which held no cost at all.\n */\nfunction withLeadCost(rows: InsightsRow[]): InsightsRow[] {\n return rows.map((row) => {\n const leads = countOf(isActionArray(row.actions) ? row.actions : [], \"lead\");\n const spend = Number(row.spend);\n return {\n ...row,\n cost_per_lead: leads !== null && leads > 0 && Number.isFinite(spend) ? round2(spend / leads) : null,\n };\n });\n}\n\n/** Compacted rows with the figures their intents add: the funnel's result, CVR and cost per result; the leads' cost per lead. */\nexport function withIntentFigures(\n rows: InsightsRow[],\n intents: readonly string[],\n options: { actionTypes?: string[] },\n): InsightsRow[] {\n const funnel = intents.includes(\"funnel\") ? withFunnelResults(rows, options) : rows;\n return intents.includes(\"leads\") ? withLeadCost(funnel) : funnel;\n}\n\n/**\n * The columns a read's intents add to every row. A read narrowed to its\n * conversions (`actionTypes`) prices each as `cost_per.actions.<type>`; one\n * that keeps every action (`leads,funnel`) prices none, so it prints\n * `cost_per_lead` itself.\n */\nexport function intentColumns(intents: readonly string[], actionTypes: string[] | undefined): string[] {\n const funnel = intents.includes(\"funnel\") ? FUNNEL_COLUMNS : [];\n return intents.includes(\"leads\") && actionTypes === undefined ? [...funnel, \"cost_per_lead\"] : funnel;\n}\n\n/**\n * Rows a read prints at `--level ad|adset` unless `--limit` names another\n * number: an account runs to hundreds of ads, and one ad-level read printed\n * 269 KB that the agent cut with `head -c` (BAKER-1222). Account and campaign\n * reads stay whole.\n */\nconst SHOWN_ROWS_BY_DEFAULT = 25;\n\n/** How many rows a read prints: `--limit`, else the default for its level; null prints every row read. */\nexport function shownRows(level: string, limit: number | undefined): number | null {\n if (limit !== undefined) return limit > 0 ? limit : null;\n return level === \"ad\" || level === \"adset\" ? SHOWN_ROWS_BY_DEFAULT : null;\n}\n\n/** The first `shown` rows of an ordered read, and what was left out (\"Showing 25 of 312 rows (…)\"), null when nothing was. */\nexport function firstRows(\n rows: InsightsRow[],\n shown: number | null,\n order: string,\n): { rows: InsightsRow[]; leftOut: string | null } {\n if (shown === null || rows.length <= shown) return { rows, leftOut: null };\n return { rows: rows.slice(0, shown), leftOut: `Showing ${shown} of ${rows.length} rows (${order})` };\n}\n\n/** A read by day or month (`--time-increment 1|monthly|<n>`), not one row for the whole period. */\nexport function isTimeSeries(timeIncrement: string | undefined): boolean {\n return timeIncrement !== undefined && timeIncrement !== \"all_days\";\n}\n\n/**\n * Rows in the order they are read: a time series by date, earliest first (by\n * spend within a day), so a daily read is a series and not a ranking of days\n * (BAKER-1660); any other read by spend.\n */\nexport function inReadingOrder(rows: InsightsRow[], timeIncrement: string | undefined): InsightsRow[] {\n const bySpend = bySpendDescending(rows);\n if (!isTimeSeries(timeIncrement)) return bySpend;\n return bySpend.sort((a, b) => String(a.date_start ?? \"\").localeCompare(String(b.date_start ?? \"\")));\n}\n\n/** Rows by spend, most first: a read is scanned for where the money went. */\nfunction bySpendDescending(rows: InsightsRow[]): InsightsRow[] {\n return [...rows].sort((a, b) => {\n const sa = Number(a.spend ?? 0);\n const sb = Number(b.spend ?? 0);\n if (Number.isNaN(sa) || Number.isNaN(sb)) return 0;\n return sb - sa;\n });\n}\n","/**\n * Meta insights `--compare`: the same read over other windows, joined to each\n * printed row with the change of every figure. A week against the week\n * before, or a 3-day read against its 7- and 30-day windows, was one call per\n * window and the arithmetic done by hand (BAKER-928, BAKER-613). The CLI and\n * the engine's conversations read it the same way.\n */\nimport { z } from \"zod\";\nimport { DATE_PRESETS_TAKEN, metaDatePreset } from \"./insightsPeriod\";\n\ntype Row = Record<string, unknown>;\n\n/** A window to compare with: the period just before, a Meta preset, or a date range. */\nexport type CompareWindow =\n | { label: \"previous_period\" }\n | { label: string; datePreset: string }\n | { label: string; since: string; until: string };\n\nconst ISO_DAY = z.iso.date();\nconst DAY_MS = 86_400_000;\n\nfunction isDay(value: string | undefined): value is string {\n return value !== undefined && ISO_DAY.safeParse(value).success;\n}\n\n/** `previous_period,last_30d,2026-08-01..2026-08-27`; a string naming what is wrong for any other spelling. */\nexport function parseCompare(raw: string): CompareWindow[] | string {\n const windows: CompareWindow[] = [];\n for (const token of raw.split(\",\").map((part) => part.trim())) {\n const [since, until, extra] = token.split(\"..\");\n const preset = metaDatePreset(token);\n if (token === \"previous_period\") windows.push({ label: token });\n else if (isDay(since) && isDay(until) && extra === undefined && since <= until)\n windows.push({ label: token, since, until });\n else if (preset) windows.push({ label: token, datePreset: preset });\n else\n return `--compare takes previous_period, YYYY-MM-DD..YYYY-MM-DD or ${DATE_PRESETS_TAKEN}, comma-separated; got \"${token}\"`;\n }\n return windows;\n}\n\nfunction shiftDay(day: string, days: number): string {\n return new Date(Date.parse(`${day}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);\n}\n\n/** As many days as `since..until`, ending the day before it starts. */\nexport function previousPeriod(since: string, until: string): { since: string; until: string } {\n const days = Math.round((Date.parse(until) - Date.parse(since)) / DAY_MS) + 1;\n return { since: shiftDay(since, -days), until: shiftDay(since, -1) };\n}\n\n/**\n * The period a window is read over. The period before a preset is counted from\n * the dates Meta answered it with, which are the account's own days; null when\n * nothing delivered in the read, so there are no dates to count back from.\n */\nexport function windowPeriod(\n window: CompareWindow,\n read: { since?: string; until?: string },\n current: readonly Row[],\n): { datePreset: string } | { since: string; until: string } | null {\n if (\"datePreset\" in window) return { datePreset: window.datePreset };\n if (\"since\" in window) return { since: window.since, until: window.until };\n const since = read.since ?? current[0]?.date_start;\n const until = read.until ?? current[0]?.date_stop;\n return typeof since === \"string\" && typeof until === \"string\" ? previousPeriod(since, until) : null;\n}\n\n/** Said when a window could not be read, and how to read it. */\nexport function unreadWindowHint(label: string): string {\n return `${label} was not read: nothing delivered in this window, so the days before it are unknown; read it by days (since and until) to compare.`;\n}\n\nconst PERIOD_FIELDS = new Set([\"date_start\", \"date_stop\"]);\n\n/** Counts Meta leaves out of a row when they are zero (`actions.complete_registration`). */\nconst COUNT_PREFIXES = [\"actions.\", \"unique_actions.\", \"conversions.\"];\n\nfunction isCount(field: string): boolean {\n return COUNT_PREFIXES.some((prefix) => field.startsWith(prefix));\n}\n\n/** What names a row rather than measuring it: ids, names, its period, and the breakdown values. */\nfunction isLabel(field: string, breakdowns: readonly string[]): boolean {\n return PERIOD_FIELDS.has(field) || field.endsWith(\"_id\") || field.endsWith(\"_name\") || breakdowns.includes(field);\n}\n\n/** One row's place in every window: its ids and breakdown values, never its name, which can change between them. */\nfunction keyOf(row: Row, breakdowns: readonly string[]): string {\n return JSON.stringify(\n Object.keys(row)\n .filter((field) => field.endsWith(\"_id\") || breakdowns.includes(field))\n .sort()\n .map((field) => [field, row[field]]),\n );\n}\n\nfunction numberOf(value: unknown): number | null {\n if (typeof value !== \"number\" && typeof value !== \"string\") return null;\n if (typeof value === \"string\" && value.trim() === \"\") return null;\n const number = Number(value);\n return Number.isFinite(number) ? number : null;\n}\n\n/** Percent change from `before` to `now`, one decimal; null when there was nothing before to change from. */\nfunction changePct(now: unknown, before: unknown): number | null {\n const a = numberOf(now);\n const b = numberOf(before);\n if (a === null || b === null || b === 0) return null;\n return Math.round(((a - b) / Math.abs(b)) * 1000) / 10;\n}\n\n/** The figures of either row: a conversion that stopped, or started, is still compared. */\nfunction figuresOf(row: Row, other: Row, breakdowns: readonly string[]): string[] {\n const fields = new Set([...Object.keys(row), ...Object.keys(other)]);\n return [...fields].filter(\n (field) => !isLabel(field, breakdowns) && (numberOf(row[field]) !== null || numberOf(other[field]) !== null),\n );\n}\n\n/** The figures of `other` beside `row`'s, with the change of each; null when the row did not deliver in that window. */\nfunction comparedTo(row: Row, other: Row | undefined, breakdowns: readonly string[]): Row | null {\n if (other === undefined) return null;\n const figures = figuresOf(row, other, breakdowns);\n const before = Object.fromEntries(figures.map((field) => [field, other[field] ?? null]));\n const change = Object.fromEntries(figures.map((field) => [field, changePct(row[field], other[field])]));\n const period = Object.fromEntries([...PERIOD_FIELDS].filter((f) => f in other).map((f) => [f, other[f]]));\n return { ...period, ...before, change_pct: change };\n}\n\n/** A count the row lacks but a window holds is a zero Meta left out, said as one. */\nfunction withZeroCounts(row: Row, others: ReadonlyArray<Row | undefined>): Row {\n const missing = others.flatMap((other) =>\n Object.keys(other ?? {}).filter((field) => isCount(field) && !(field in row)),\n );\n return missing.length === 0 ? row : { ...row, ...Object.fromEntries(missing.map((field) => [field, 0])) };\n}\n\n/**\n * Each printed row with `compare.<window>`: that window's figures for the same\n * entity and the percent change of each, and a hint counting the entities that\n * delivered in a window but not in the one read. `read` is every row the read\n * returned, the printed ones among them: one a row limit left out still\n * delivered. A window whose rows are null was not read.\n */\nexport function withComparisons(\n rows: Row[],\n windows: Array<{ label: string; rows: Row[] | null }>,\n breakdowns: readonly string[],\n read: readonly Row[] = rows,\n): { rows: Row[]; hints: string[] } {\n const indexed = windows.map(({ label, rows: other }) => ({\n label,\n byKey: other === null ? null : new Map(other.map((row) => [keyOf(row, breakdowns), row])),\n }));\n const compared = rows.map((row) => {\n const others = indexed.map(({ byKey }) => byKey?.get(keyOf(row, breakdowns)));\n const filled = withZeroCounts(row, others);\n return {\n ...filled,\n compare: Object.fromEntries(indexed.map(({ label }, at) => [label, comparedTo(filled, others[at], breakdowns)])),\n };\n });\n const delivered = new Set(read.map((row) => keyOf(row, breakdowns)));\n const hints = indexed.flatMap(({ label, byKey }) => {\n if (byKey === null) return [unreadWindowHint(label)];\n const gone = [...byKey.keys()].filter((key) => !delivered.has(key)).length;\n return gone === 0 ? [] : [`${gone} more delivered in ${label} and not in this window; they are not listed.`];\n });\n if (compared.some((row) => Object.values(row.compare).includes(null))) {\n hints.push(\"compare.<window> is null where that row did not deliver in the window.\");\n }\n return { rows: compared, hints };\n}\n\n/** One window's entry as `compare.<window>.<figure>` cells, its changes as `compare.<window>.change_pct.<figure>`. */\nfunction flatEntry(label: string, entry: Row | null): Row {\n if (entry === null) return {};\n const { change_pct: change, ...figures } = entry;\n return Object.fromEntries([\n ...Object.entries(figures).map(([field, value]) => [`compare.${label}.${field}`, value]),\n ...Object.entries((change ?? {}) as Row).map(([field, pct]) => [`compare.${label}.change_pct.${field}`, pct]),\n ]);\n}\n\n/** `compare.<window>.<figure>` columns for a table, after the row's own and the zero counts the join added. */\nexport function flatComparisons(rows: Row[], columns: string[]): { rows: Row[]; columns: string[] } {\n const flat = rows.map(({ compare, ...row }) => ({\n ...row,\n ...Object.assign(\n {},\n ...Object.entries((compare ?? {}) as Record<string, Row | null>).map(([label, entry]) => flatEntry(label, entry)),\n ),\n }));\n const keys = new Set(flat.flatMap((row) => Object.keys(row).filter((key) => !columns.includes(key))));\n const counts = [...keys].filter(isCount);\n const compared = [...keys].filter((key) => key.startsWith(\"compare.\"));\n return { rows: flat, columns: [...columns, ...counts, ...compared] };\n}\n","/**\n * The period of a Meta insights read, checked before Meta is asked. Meta\n * answers a preset it does not have with a message that names neither the flag\n * nor what it does take (`lifetime` came back as \"not a valid date_preset\",\n * leaving out `maximum`), so the natural spelling is read as Meta's and\n * anything else is refused here, naming the presets (BAKER-3849).\n */\n\n/** Meta's `date_preset` values, from the Insights API reference. */\nexport const META_DATE_PRESETS = [\n \"today\",\n \"yesterday\",\n \"this_month\",\n \"last_month\",\n \"this_quarter\",\n \"maximum\",\n \"data_maximum\",\n \"last_3d\",\n \"last_7d\",\n \"last_14d\",\n \"last_28d\",\n \"last_30d\",\n \"last_90d\",\n \"last_week_mon_sun\",\n \"last_week_sun_sat\",\n \"last_quarter\",\n \"last_year\",\n \"this_week_mon_today\",\n \"this_week_sun_today\",\n \"this_year\",\n] as const;\nexport type MetaDatePreset = (typeof META_DATE_PRESETS)[number];\n\nfunction isPreset(value: string): value is MetaDatePreset {\n return (META_DATE_PRESETS as readonly string[]).includes(value);\n}\n\n/** Meta's preset for `raw` (`lifetime` is `maximum`), or null when Meta has no such preset. */\nexport function metaDatePreset(raw: string): MetaDatePreset | null {\n const value = raw.trim().toLowerCase();\n if (isPreset(value)) return value;\n return value === \"lifetime\" ? \"maximum\" : null;\n}\n\n/** What a date preset may be, said when one is refused. */\nexport const DATE_PRESETS_TAKEN = `one of Meta's presets: ${META_DATE_PRESETS.join(\", \")} (maximum for lifetime)`;\n","/**\n * Insights field bundles. Picked for AI agent ergonomics: small, focused field\n * lists that answer one specific question without forcing the AI to enumerate\n * Meta's 500+ insights fields.\n *\n * Two-axis design:\n * --intent (field bundle, default: baseline) — what data to ask for\n * --level (object granularity, default: account) — at what granularity\n *\n * Intents are independent of level — pass `--intent ranking --level ad` to flag\n * creatives, or `--intent revenue --level campaign` for ROAS by campaign. They\n * combine: `--intent ranking,funnel` reads both bundles in one request, one row\n * per object, so nobody joins two reads by ad_id (BAKER-1549).\n *\n * Identity fields (campaign_name etc.) are appended automatically based on\n * level, `--fields` or not, so the AI can read rows without joining.\n */\n\nexport const INSIGHTS_LEVELS = [\"account\", \"campaign\", \"adset\", \"ad\"] as const;\nexport type InsightsLevel = (typeof INSIGHTS_LEVELS)[number];\n\nexport const INSIGHTS_INTENT_NAMES = [\n \"baseline\",\n \"leads\",\n \"revenue\",\n \"funnel\",\n \"ranking\",\n \"video\",\n \"identity\",\n] as const;\nexport type InsightsIntent = (typeof INSIGHTS_INTENT_NAMES)[number];\n\n/** The attribution windows a read asks for unless told otherwise: the only ones still working as of Jan 2026 (1d_view + 28d_click also valid but rarely used). */\nexport const DEFAULT_ATTRIBUTION_WINDOWS = [\"7d_click\", \"1d_view\"];\n\n/** The filter a read applies unless told otherwise: rows that didn't deliver are left out. Almost always what we want. */\nexport const DEFAULT_FILTERING = [{ field: \"impressions\", operator: \"GREATER_THAN\", value: 0 }];\n\n/** The period a read covers when it names none. */\nexport const DEFAULT_DATE_PRESET = \"last_7d\";\n\ninterface IntentDefinition {\n name: InsightsIntent;\n description: string;\n fields: string[];\n /** Action breakdowns to slice the actions[] array — empty if not needed. */\n actionBreakdowns?: string[];\n /** The conversions the intent counts, unless `--action-types` names others. */\n actionTypes?: string[];\n}\n\nconst INSIGHTS_INTENTS: Record<InsightsIntent, IntentDefinition> = {\n baseline: {\n name: \"baseline\",\n description: \"Spend, impressions, clicks, CTR, CPC, CPM. The default question: 'how is delivery?'\",\n fields: [\"impressions\", \"reach\", \"frequency\", \"spend\", \"clicks\", \"ctr\", \"cpc\", \"cpm\"],\n },\n leads: {\n name: \"leads\",\n description: \"Spend, leads and cost per lead (the `lead` count). 'How many leads, at what cost?'\",\n fields: [\"impressions\", \"clicks\", \"spend\", \"actions\"],\n actionTypes: [\"lead\"],\n },\n revenue: {\n name: \"revenue\",\n description: \"Spend, conversions, action_values, purchase_roas. 'How much money are we making?'\",\n fields: [\"spend\", \"actions\", \"action_values\", \"conversions\", \"conversion_values\", \"purchase_roas\"],\n actionBreakdowns: [\"action_type\"],\n },\n funnel: {\n name: \"funnel\",\n description: \"Impression → click → landing page → action. 'Where do users drop off?'\",\n fields: [\"impressions\", \"clicks\", \"inline_link_clicks\", \"outbound_clicks\", \"actions\", \"spend\"],\n actionBreakdowns: [\"action_type\"],\n },\n ranking: {\n name: \"ranking\",\n description: \"Quality, engagement, conversion-rate rankings. 'Which creatives need a refresh?'\",\n fields: [\"impressions\", \"spend\", \"ctr\", \"quality_ranking\", \"engagement_rate_ranking\", \"conversion_rate_ranking\"],\n },\n video: {\n name: \"video\",\n description: \"Watch funnel, thruplay cost. 'How are video creatives holding attention?'\",\n fields: [\n \"impressions\",\n \"spend\",\n \"video_play_actions\",\n \"video_p25_watched_actions\",\n \"video_p50_watched_actions\",\n \"video_p75_watched_actions\",\n \"video_p100_watched_actions\",\n \"video_thruplay_watched_actions\",\n \"cost_per_thruplay\",\n ],\n },\n identity: {\n name: \"identity\",\n description: \"Just the names + spend — for cheap roll-up summaries.\",\n fields: [\"spend\", \"impressions\"],\n },\n};\n\nconst IDENTITY_FIELDS_BY_LEVEL: Record<InsightsLevel, string[]> = {\n account: [\"account_id\", \"account_name\", \"account_currency\"],\n campaign: [\"campaign_id\", \"campaign_name\", \"objective\"],\n adset: [\"adset_id\", \"adset_name\", \"campaign_id\", \"campaign_name\"],\n ad: [\"ad_id\", \"ad_name\", \"adset_id\", \"adset_name\", \"campaign_id\", \"campaign_name\"],\n};\n\n/** The intents a read names (`ranking,funnel`), each once; baseline when it names none, or the names no intent has. */\nexport function parseIntents(names: readonly string[]): InsightsIntent[] | { unknown: string[] } {\n const unknown = names.filter((name) => getIntent(name) === undefined);\n if (unknown.length > 0) return { unknown };\n return names.length === 0 ? [\"baseline\"] : [...new Set(names as InsightsIntent[])];\n}\n\nfunction asIntents(intents: string | readonly string[] | undefined): IntentDefinition[] {\n const names = intents === undefined ? [\"baseline\"] : typeof intents === \"string\" ? [intents] : intents;\n return names.flatMap((name) => getIntent(name) ?? []);\n}\n\n/**\n * Compose final field list: every intent's metrics, or the `--fields` named in their place, + level-specific\n * identity fields, deduplicated. Named fields keep the identity too: a `--level adset --fields spend` read came\n * back as anonymous rows nobody could tell apart (BAKER-1133).\n */\nexport function composeFields(\n intents: InsightsIntent | readonly InsightsIntent[],\n level: InsightsLevel,\n named?: readonly string[],\n): string[] {\n const intentFields = named ?? asIntents(intents).flatMap((intent) => intent.fields);\n const identity = IDENTITY_FIELDS_BY_LEVEL[level];\n const seen = new Set<string>();\n const out: string[] = [];\n for (const f of [...identity, ...intentFields]) {\n if (!seen.has(f)) {\n seen.add(f);\n out.push(f);\n }\n }\n return out;\n}\n\n/** The arrays `--action-types` filters by count: one of them has to be asked for, or the filter has nothing to keep. */\nconst COUNTED_ACTION_FIELDS = [\"actions\", \"unique_actions\", \"conversions\"];\n\n/**\n * The fields to ask Meta for: naming `--action-types` asks for `actions` when\n * the intent or `--fields` holds no counted action array. The default intent\n * has none, and a filter over a field nobody requested returned rows with no\n * action at all and no word why (BAKER-3479).\n */\nexport function withActionFields(fields: string[], actionTypes: string[] | undefined): string[] {\n if (!actionTypes?.length || fields.some((field) => COUNTED_ACTION_FIELDS.includes(field))) return fields;\n return [...fields, \"actions\"];\n}\n\n/**\n * The fields to ask Meta for: `spend` too, which ranks the rows whatever fields\n * are printed. A `--fields ad_id,ctr` read came back without it, every row tied\n * at 0, and the 25 printed as \"the most spend\" were Meta's first 25.\n */\nexport function withSpendField(fields: string[]): string[] {\n return fields.includes(\"spend\") ? fields : [...fields, \"spend\"];\n}\n\n/**\n * The conversions a read keeps: the ones `--action-types` names, else its\n * intents' own (`leads` → lead) — unless another intent reads every action\n * (`leads,funnel` keeps the funnel's landing-page views).\n */\nexport function intentActionTypes(\n intents: string | readonly string[] | undefined,\n named: string[] | undefined,\n): string[] | undefined {\n if (named) return named;\n const read = asIntents(intents);\n if (read.some((intent) => intent.actionTypes === undefined && intent.fields.includes(\"actions\"))) return undefined;\n const own = read.flatMap((intent) => intent.actionTypes ?? []);\n return own.length === 0 ? undefined : [...new Set(own)];\n}\n\n/** The action breakdowns a read's intents slice actions by (revenue and funnel: action_type), none when none does. */\nexport function intentActionBreakdowns(intents: string | readonly string[] | undefined): string[] | undefined {\n const own = asIntents(intents).flatMap((intent) => intent.actionBreakdowns ?? []);\n return own.length === 0 ? undefined : [...new Set(own)];\n}\n\nfunction getIntent(name: string): IntentDefinition | undefined {\n return INSIGHTS_INTENTS[name as InsightsIntent];\n}\n\nexport function listIntents(): IntentDefinition[] {\n return Object.values(INSIGHTS_INTENTS);\n}\n","import {\n compactInsightsRows,\n firstRows,\n inReadingOrder,\n insightsTable,\n intentColumns,\n isTimeSeries,\n shownRows,\n withIntentFigures,\n} from \"@baker/api/ads-meta/insightsActions\";\nimport {\n type CompareWindow,\n flatComparisons,\n parseCompare,\n windowPeriod,\n withComparisons,\n} from \"@baker/api/ads-meta/insightsCompare\";\nimport {\n composeFields,\n DEFAULT_ATTRIBUTION_WINDOWS,\n DEFAULT_DATE_PRESET,\n DEFAULT_FILTERING,\n type InsightsIntent,\n type InsightsLevel,\n intentActionBreakdowns,\n intentActionTypes,\n listIntents,\n parseIntents,\n withActionFields,\n withSpendField,\n} from \"@baker/api/ads-meta/insightsIntents\";\nimport { DATE_PRESETS_TAKEN, metaDatePreset } from \"@baker/api/ads-meta/insightsPeriod\";\nimport { defineCommand } from \"citty\";\nimport { z } from \"zod\";\nimport { NO_CACHE_ARG } from \"../../../cache-flag.ts\";\nimport { apiGet, apiPost } from \"../../../client.ts\";\nimport { withWindowSpellings } from \"../../../date-window.ts\";\nimport { withEffect } from \"../../../schemas.ts\";\nimport { writeAdsJson, writeAdsOutput, writeJsonEnvelope } from \"../output.ts\";\nimport {\n campaignsAnswered,\n metaBreakdownSyncedHint,\n type SyncedLevel,\n type SyncedRead,\n syncedFirstHint,\n} from \"../synced-first.ts\";\nimport { placementDeliveryHints } from \"./placement-delivery.ts\";\nimport { csvOrJson, getDateRange, handleMetaError, todayIso } from \"./shared.ts\";\n\n/** Rows asked of Meta at least, whatever is printed: the ones printed are the top of the whole read, not Meta's first page. */\nconst ROWS_READ = 1000;\n\nconst POLL_FIRST_MS = 5_000;\nconst POLL_LONGEST_MS = 30_000;\nconst POLL_MAX_MS = 10 * 60_000;\n\n/**\n * The wait before status poll `attempt` (0-based): 5s, growing by half each\n * poll, at most 30s. Every poll is a read from the ad account's hourly Meta\n * budget, and a long report gains nothing from being asked every 5 seconds.\n */\nexport function asyncPollDelayMs(attempt: number): number {\n return Math.min(Math.round(POLL_FIRST_MS * 1.5 ** attempt), POLL_LONGEST_MS);\n}\n\nexport interface InsightsBody {\n object: string;\n level: InsightsLevel;\n fields: string[];\n datePreset?: string;\n since?: string;\n until?: string;\n timeIncrement?: string;\n breakdowns?: string[];\n actionBreakdowns?: string[];\n filtering?: Array<{ field: string; operator: string; value: string | number | string[] }>;\n attributionWindows?: string[];\n useAccountAttributionSetting?: boolean;\n useUnifiedAttributionSetting?: boolean;\n limit?: number;\n skipCache?: boolean;\n}\n\nfunction commaSplit(input: string | undefined): string[] | undefined {\n if (!input) return undefined;\n return input\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n/** The shape Meta's insights route accepts for `filtering`. */\nconst filteringSchema = z.array(\n z.object({\n field: z.string(),\n operator: z.string(),\n value: z.union([z.string(), z.number(), z.array(z.string())]),\n }),\n);\n\nfunction parseFiltering(raw: string | undefined): InsightsBody[\"filtering\"] {\n if (!raw) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n handleMetaError(new Error(\"Invalid --filtering JSON\"));\n }\n const parsed = filteringSchema.safeParse(json);\n if (!parsed.success) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message:\n '--filtering must be a JSON array of {field,operator,value}, e.g. \\'[{\"field\":\"ad.name\",\"operator\":\"CONTAIN\",\"value\":\"SPRING\"}]\\'',\n },\n });\n process.exit(1);\n }\n return parsed.data;\n}\n\n/** `--intent`, one or several comma-separated (`ranking,funnel`); baseline when absent. */\nfunction intentsOf(args: Record<string, unknown>): InsightsIntent[] {\n const intents = parseIntents(commaSplit(args.intent as string | undefined) ?? []);\n if (!(\"unknown\" in intents)) return intents;\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `Unknown --intent: ${intents.unknown.join(\", \")}. Use --list-intents to see options.`,\n },\n });\n process.exit(1);\n}\n\n/** The conversions the read keeps: `--action-types`, else the intents' own. */\nfunction actionTypesOf(args: Record<string, unknown>): string[] | undefined {\n return intentActionTypes(intentsOf(args), commaSplit(args[\"action-types\"] as string | undefined));\n}\n\n/** `--limit`: rows to print, 0 for every row; absent leaves it to the level's default. */\nfunction pickLimit(raw: unknown): number | undefined {\n if (raw === undefined) return undefined;\n const limit = Number(raw);\n if (!Number.isInteger(limit) || limit < 0) {\n handleMetaError(new Error(\"--limit must be a whole number of rows, or 0 for every row\"));\n }\n return limit;\n}\n\nfunction pickLevel(args: Record<string, unknown>): InsightsLevel {\n const raw = args.level as string | undefined;\n if (!raw) return \"account\";\n if (raw !== \"account\" && raw !== \"campaign\" && raw !== \"adset\" && raw !== \"ad\") {\n handleMetaError(new Error(\"--level must be one of: account|campaign|adset|ad\"));\n }\n return raw;\n}\n\n/**\n * Auto-async heuristic. Heavy queries that would time out as sync go async\n * automatically — the user shouldn't have to think about it.\n *\n * - level=ad with breakdowns\n * - >2 breakdowns at any level\n * - explicit time range > 90 days\n * - level=ad over an account-level object with a wide window\n */\nfunction shouldAutoAsync(body: InsightsBody): boolean {\n const breakdownCount = (body.breakdowns ?? []).length;\n if (body.level === \"ad\" && breakdownCount > 0 && body.object.startsWith(\"act_\")) {\n return true;\n }\n if (breakdownCount > 2) {\n return true;\n }\n if (body.since && body.until) {\n const days = (Date.parse(body.until) - Date.parse(body.since)) / 86_400_000;\n if (days > 90) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether to take the async path — three states, not two.\n *\n * citty resolves `--no-async` to `async: false` rather than filling a separate\n * `no-async` arg, so reading `args[\"no-async\"]` (as this did) always saw\n * undefined and the documented refusal never applied: a heavy query went async\n * no matter what the caller asked for.\n */\nexport function wantsAsync(asyncFlag: unknown, body: InsightsBody): boolean {\n if (asyncFlag === true) return true;\n if (asyncFlag === false) return false;\n return shouldAutoAsync(body);\n}\n\n/** A value Meta does not take, refused before Meta is asked, naming the ones it does. */\nfunction refuseValue(flag: string, got: string, taken: string): never {\n const message = `${flag} takes ${taken}; got \"${got}\"`;\n writeAdsJson({\n ok: false,\n error: { code: \"VALIDATION_ERROR\", message, fix: { action: \"reject\", explanation: message }, retryable: false },\n });\n process.exit(1);\n}\n\nconst MAX_INCREMENT_DAYS = 90;\nconst TIME_INCREMENTS_TAKEN = `1 (a row per day), 2 to ${MAX_INCREMENT_DAYS} (a row per that many days), monthly or all_days`;\n\n/** `--time-increment` as Meta spells it (`daily` is 1), refused when Meta does not take it. */\nfunction pickTimeIncrement(raw: unknown): string | undefined {\n if (raw === undefined) return undefined;\n const value = String(raw).trim().toLowerCase();\n if (value === \"monthly\" || value === \"all_days\") return value;\n const spelled = value === \"day\" || value === \"daily\" ? \"1\" : value;\n const days = /^\\d+$/.test(spelled) ? Number(spelled) : 0;\n if (days >= 1 && days <= MAX_INCREMENT_DAYS) return String(days);\n return refuseValue(\"--time-increment\", String(raw), TIME_INCREMENTS_TAKEN);\n}\n\nfunction applyDateRange(body: InsightsBody, args: Record<string, unknown>): void {\n const range = getDateRange(args);\n if (range.datePreset) {\n body.datePreset =\n metaDatePreset(range.datePreset) ?? refuseValue(\"--date-preset\", range.datePreset, DATE_PRESETS_TAKEN);\n }\n if (range.since) body.since = range.since;\n if (range.until) body.until = range.until;\n if (!body.datePreset && !(body.since && body.until)) {\n body.datePreset = DEFAULT_DATE_PRESET;\n }\n}\n\n/** Every `effective_status` Meta reports for a campaign, ad set or ad. */\nconst EVERY_EFFECTIVE_STATUS = [\n \"ACTIVE\",\n \"PAUSED\",\n \"DELETED\",\n \"ARCHIVED\",\n \"PENDING_REVIEW\",\n \"DISAPPROVED\",\n \"PREAPPROVED\",\n \"PENDING_BILLING_INFO\",\n \"CAMPAIGN_PAUSED\",\n \"ADSET_PAUSED\",\n \"IN_PROCESS\",\n \"WITH_ISSUES\",\n];\n\n/**\n * A filter on a campaign's, ad set's or ad's own field (`ad.name`, `campaign.id`)\n * makes Meta leave archived and deleted ones out of the read, so their spend\n * disappears from a history; each such entity gets every status unless the\n * caller filtered its status already.\n */\nfunction withEveryStatus(filtering: NonNullable<InsightsBody[\"filtering\"]>): InsightsBody[\"filtering\"] {\n const unstated = [\"campaign\", \"adset\", \"ad\"].filter(\n (entity) =>\n filtering.some(({ field }) => field.startsWith(`${entity}.`)) &&\n !filtering.some(({ field }) => field === `${entity}.effective_status`),\n );\n return [\n ...filtering,\n ...unstated.map((entity) => ({\n field: `${entity}.effective_status`,\n operator: \"IN\",\n value: EVERY_EFFECTIVE_STATUS,\n })),\n ];\n}\n\nfunction buildFiltering(args: Record<string, unknown>): InsightsBody[\"filtering\"] {\n const explicit = parseFiltering(args.filtering as string | undefined);\n if (explicit) return withEveryStatus(explicit);\n if (args[\"include-undelivered\"]) return undefined;\n return DEFAULT_FILTERING;\n}\n\n/**\n * The windows Meta is asked for. A compact read naming click or view windows asks for Meta's default ones too:\n * Meta leaves out a window that counted nothing and sends no split at all when only that window was asked, so\n * without them a conversion counted 0 in the asked window could not be told from one Meta never splits\n * (BAKER-2422). The compact view prints only the asked windows.\n */\nfunction buildAttributionWindows(args: Record<string, unknown>): string[] | undefined {\n const explicit = commaSplit(args[\"attribution-windows\"] as string | undefined);\n if (!explicit) return DEFAULT_ATTRIBUTION_WINDOWS;\n const named = namedWindows(args);\n if (args.full || !named || !named.every((window) => CLICK_OR_VIEW_WINDOW.test(window))) return explicit;\n return [...new Set([...explicit, ...DEFAULT_ATTRIBUTION_WINDOWS])];\n}\n\nconst CLICK_OR_VIEW_WINDOW = /^\\d+d_(click|view)$/;\n\n/**\n * The windows a read names in place of Meta's default (`--attribution-windows 7d_click`), whose figures each\n * compact `value` then holds; undefined for the default, or when an attribution setting decides instead.\n */\nfunction namedWindows(args: Record<string, unknown>): string[] | undefined {\n if (args[\"use-account-attribution\"] || args[\"use-unified-attribution\"]) return undefined;\n const explicit = commaSplit(args[\"attribution-windows\"] as string | undefined);\n if (!explicit) return undefined;\n const isDefault =\n (explicit.length === 1 && explicit[0] === \"default\") ||\n (explicit.length === DEFAULT_ATTRIBUTION_WINDOWS.length &&\n DEFAULT_ATTRIBUTION_WINDOWS.every((window) => explicit.includes(window)));\n return isDefault ? undefined : explicit;\n}\n\nfunction buildBody(args: Record<string, unknown>): InsightsBody {\n const intents = intentsOf(args);\n const level = pickLevel(args);\n const explicitFields = commaSplit(args.fields as string | undefined);\n const fields = withSpendField(withActionFields(composeFields(intents, level, explicitFields), actionTypesOf(args)));\n const breakdowns = commaSplit(args.breakdowns as string | undefined);\n const actionBreakdowns =\n commaSplit(args[\"action-breakdowns\"] as string | undefined) ?? intentActionBreakdowns(intents);\n\n const body: InsightsBody = {\n object: args.object as string,\n level,\n fields,\n timeIncrement: pickTimeIncrement(args[\"time-increment\"]),\n breakdowns,\n actionBreakdowns,\n filtering: buildFiltering(args),\n attributionWindows: buildAttributionWindows(args),\n useAccountAttributionSetting: Boolean(args[\"use-account-attribution\"]),\n useUnifiedAttributionSetting: Boolean(args[\"use-unified-attribution\"]),\n limit: Math.max(ROWS_READ, pickLimit(args.limit) ?? 0),\n skipCache: Boolean(args[\"no-cache\"]),\n };\n applyDateRange(body, args);\n return body;\n}\n\nasync function pollAsync(reportRunId: string): Promise<void> {\n const start = Date.now();\n for (let attempt = 0; Date.now() - start < POLL_MAX_MS; attempt++) {\n // The status route is a GET reading `report-run-id` from the query string.\n // Posting to it matched no route at all, so every heavy query died on a\n // bare 404 the moment it went async.\n const status = await apiGet<{ async_status?: string; async_percent_completion?: number }>(\n \"/api/ads/meta/insights/async/status\",\n { \"report-run-id\": reportRunId },\n );\n if (status.async_status === \"Job Completed\") return;\n if (status.async_status === \"Job Failed\" || status.async_status === \"Job Skipped\") {\n handleMetaError(new Error(`Async insights job ${status.async_status}`));\n }\n process.stderr.write(\n `Async insights ${status.async_status ?? \"queued\"} (${Math.round(status.async_percent_completion ?? 0)}%)…\\n`,\n );\n await new Promise((resolve) => setTimeout(resolve, asyncPollDelayMs(attempt)));\n }\n handleMetaError(new Error(\"Async insights polling timed out after 10 minutes\"));\n}\n\nasync function runAsync(body: InsightsBody): Promise<Array<Record<string, unknown>>> {\n const submit = await apiPost<{ reportRunId: string }>(\"/api/ads/meta/insights/async\", body);\n process.stderr.write(`Async insights job: ${submit.reportRunId}\\n`);\n await pollAsync(submit.reportRunId);\n return apiPost<Array<Record<string, unknown>>>(\"/api/ads/meta/insights/async/result\", {\n reportRunId: submit.reportRunId,\n fields: body.fields,\n limit: body.limit,\n });\n}\n\nconst META_GRAIN: Record<string, SyncedRead[\"grain\"]> = { \"1\": \"day\", \"7\": \"week\", monthly: \"month\" };\n\n/** The days Meta answered the read with: a calendar preset (last_month, maximum…) is its account's own dates. */\nfunction answeredDays(rows: ReadonlyArray<Record<string, unknown>>): { start: string; end: string } | undefined {\n const starts = rows.map((row) => row.date_start).filter((day): day is string => typeof day === \"string\");\n const ends = rows.map((row) => row.date_stop).filter((day): day is string => typeof day === \"string\");\n if (starts.length === 0 || ends.length === 0) return undefined;\n return { start: starts.reduce((a, b) => (a < b ? a : b)), end: ends.reduce((a, b) => (a > b ? a : b)) };\n}\n\n/**\n * The insights window as the synced copy spells it; null for a read of today alone, or one whose days are unknown:\n * a calendar preset (last_month, maximum…) split into buckets, whose rows name only the days that delivered.\n */\nfunction syncedWindow(\n body: InsightsBody,\n rows: ReadonlyArray<Record<string, unknown>>,\n): NonNullable<SyncedRead[\"window\"]> | null {\n if (body.datePreset === \"today\") return null;\n if (body.datePreset === \"yesterday\") return { days: 1 };\n const days = /^last_(\\d+)d$/.exec(body.datePreset ?? \"\")?.[1];\n if (days !== undefined) return { days: Number(days) };\n const window =\n body.since && body.until\n ? { start: body.since, end: body.until }\n : isTimeSeries(body.timeIncrement)\n ? undefined\n : answeredDays(rows);\n return window === undefined || window.start >= todayIso() ? null : window;\n}\n\n/**\n * The first day of the window in the account's own dates, so seven-day buckets are named as synced weeks only when\n * both start on a Monday: Meta anchors every bucket to it, so any bucket's first day falls on its weekday.\n */\nfunction windowStart(window: NonNullable<SyncedRead[\"window\"]>, rows: ReadonlyArray<Record<string, unknown>>) {\n if (\"start\" in window) return window.start;\n return answeredDays(rows)?.start;\n}\n\n/**\n * The `baker ads performance` read that answers the same insights read; null when the synced copy cannot.\n * `previousPeriod` is true only for a `--compare previous_period`, the one baseline the synced `--compare` reads.\n */\nfunction syncedHintOf(\n body: InsightsBody,\n rows: ReadonlyArray<Record<string, unknown>>,\n previousPeriod: boolean,\n): string | null {\n const window = syncedWindow(body, rows);\n if (window === null) return null;\n const breakdowns = body.breakdowns ?? [];\n if (breakdowns.length > 0) return metaBreakdownSyncedHint(breakdowns, window);\n const level: SyncedLevel = body.level === \"adset\" ? \"ad_group\" : body.level;\n const grain = body.timeIncrement === undefined ? undefined : META_GRAIN[body.timeIncrement];\n if (grain === \"week\") {\n const start = windowStart(window, rows);\n if (start === undefined || new Date(`${start}T00:00:00Z`).getUTCDay() !== 1) return null;\n }\n return syncedFirstHint(\"meta\", level, { window, grain, compare: previousPeriod, campaigns: campaignsAnswered(rows) });\n}\n\n/** `--fields` without spend: it is still read, to rank the rows, and left out of what prints. */\nfunction spendUnasked(args: Record<string, unknown>): boolean {\n const explicit = commaSplit(args.fields as string | undefined);\n return explicit !== undefined && !explicit.includes(\"spend\");\n}\n\n/** The read in its order (by spend, a series by date, or Meta's own with --no-sort), cut to the rows `--limit` prints. */\nfunction rowsToPrint(rows: Array<Record<string, unknown>>, body: InsightsBody, args: Record<string, unknown>) {\n const shown = shownRows(body.level, pickLimit(args.limit));\n if (args[\"no-sort\"]) return firstRows(rows, shown, \"as Meta sent them\");\n const order = isTimeSeries(body.timeIncrement) ? \"the earliest dates first\" : \"the most spend first\";\n return firstRows(inReadingOrder(rows, body.timeIncrement), shown, order);\n}\n\n/** The compact rows, or Meta's own with --full, and the hint naming what the compact view dropped. */\nfunction shapeRows(\n rows: Array<Record<string, unknown>>,\n args: Record<string, unknown>,\n): { rows: Array<Record<string, unknown>>; hints: string[] } {\n if (args.full) return { rows, hints: [] };\n const actionTypes = actionTypesOf(args);\n const {\n rows: compacted,\n dropped,\n folded,\n disagreements,\n windowHints,\n } = compactInsightsRows(rows, {\n actionTypes,\n windows: namedWindows(args),\n });\n const compact = withIntentFigures(compacted, intentsOf(args), { actionTypes });\n const foldHints =\n folded === null\n ? []\n : [\n `Meta's other names for one conversion print under its plain name (${folded}); read it by that name, or --action-types <raw name> keeps Meta's own name in actions, conversions and their values and costs.`,\n ];\n if (dropped.length === 0) return { rows: compact, hints: [...foldHints, ...disagreements, ...windowHints] };\n const named = dropped.slice(0, 4).join(\", \");\n const more = dropped.length > 4 ? ` and ${dropped.length - 4} more` : \"\";\n return {\n rows: compact,\n hints: [\n `Engagement and combined action types were left out (${named}${more}); --action-types <type> keeps one, --full returns every raw action.`,\n ...foldHints,\n ...disagreements,\n ...windowHints,\n ],\n };\n}\n\n/** One read, sync or async as `--async` and the heuristic decide. */\nfunction readRows(body: InsightsBody, asyncFlag: unknown): Promise<Array<Record<string, unknown>>> {\n return wantsAsync(asyncFlag, body)\n ? runAsync(body)\n : apiPost<Array<Record<string, unknown>>>(\"/api/ads/meta/insights\", body);\n}\n\n/** `--compare`, refused for a series: a row per day has no one row to set beside it in another window. */\nfunction pickCompare(raw: unknown, body: InsightsBody): CompareWindow[] | undefined {\n if (raw === undefined || raw === \"\") return undefined;\n const windows = isTimeSeries(body.timeIncrement)\n ? \"--compare sets one window beside another; drop --time-increment, or read the series without it\"\n : parseCompare(String(raw));\n if (typeof windows !== \"string\") return windows;\n writeAdsJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message: windows } });\n process.exit(1);\n}\n\n/**\n * The same read over every `--compare` window, shaped as the printed rows are,\n * with the hints its shaping gave, each naming its window. Rows are null for a\n * window that could not be read.\n */\nfunction readWindows(\n windows: CompareWindow[],\n body: InsightsBody,\n current: Array<Record<string, unknown>>,\n args: Record<string, unknown>,\n): Promise<Array<{ label: string; rows: Array<Record<string, unknown>> | null; hints: string[] }>> {\n const { datePreset: _preset, since: _since, until: _until, ...rest } = body;\n return Promise.all(\n windows.map(async (window) => {\n const period = windowPeriod(window, body, current);\n if (period === null) return { label: window.label, rows: null, hints: [] };\n const shaped = printedRows(await readRows({ ...rest, ...period }, args.async), args);\n return {\n label: window.label,\n rows: flatTable(shaped.rows, body, args).rows,\n hints: shaped.hints.map((hint) => `${window.label}: ${hint}`),\n };\n }),\n );\n}\n\n/** The rows as printed: spend left out where `--fields` did not ask for it, then compacted. */\nfunction printedRows(rows: Array<Record<string, unknown>>, args: Record<string, unknown>) {\n return shapeRows(spendUnasked(args) ? rows.map(({ spend: _spend, ...row }) => row) : rows, args);\n}\n\n/** The fields printed, in order: spend only when asked for, and the columns the intents add. */\nfunction printedFields(body: InsightsBody, args: Record<string, unknown>): string[] {\n const fields = spendUnasked(args) ? body.fields.filter((field) => field !== \"spend\") : body.fields;\n return args.full ? fields : [...fields, ...intentColumns(intentsOf(args), actionTypesOf(args))];\n}\n\n/** Printed rows with one column per action type, as `--output md|csv` shows them. */\nfunction flatTable(rows: Array<Record<string, unknown>>, body: InsightsBody, args: Record<string, unknown>) {\n return insightsTable(rows, printedFields(body, args), { priceAll: actionTypesOf(args) !== undefined });\n}\n\n/**\n * The JSON envelope with its hints ahead of the rows, and the synced read on stderr too, first: a long read cut\n * with `head` or projected to `.data` still shows which read answers it without the rate limit (BAKER-3382).\n */\nfunction writeInsightsJson(data: unknown, lead: string[], hints: string[]): void {\n for (const hint of lead) process.stderr.write(`${hint}\\n`);\n writeJsonEnvelope({ ok: true, hints: [...lead, ...hints], data });\n}\n\n/** The printed rows with every `--compare` window beside them: nested in json, one column per figure otherwise. */\nasync function printCompared(input: {\n windows: CompareWindow[];\n body: InsightsBody;\n args: Record<string, unknown>;\n fmt: string;\n rows: Array<Record<string, unknown>>;\n printed: { rows: Array<Record<string, unknown>>; hints: string[] };\n}): Promise<void> {\n const { body, args } = input;\n const windows = await readWindows(input.windows, body, input.rows, args);\n const table = flatTable(input.printed.rows, body, args);\n const compared = withComparisons(table.rows, windows, body.breakdowns ?? [], input.rows);\n const previousPeriod = input.windows.length === 1 && input.windows[0]?.label === \"previous_period\";\n const synced = syncedHintOf(body, input.rows, previousPeriod);\n const ownHints = new Set(input.printed.hints);\n const windowHints = windows.flatMap((window) =>\n window.hints.filter((hint) => !ownHints.has(hint.slice(window.label.length + 2))),\n );\n const lead = synced === null ? [] : [synced];\n const hints = [...input.printed.hints, ...windowHints, ...compared.hints];\n if (input.fmt === \"json\") {\n writeInsightsJson(compared.rows, lead, [...placementDeliveryHints(input.rows), ...hints]);\n return;\n }\n const flat = flatComparisons(compared.rows, table.columns);\n writeAdsOutput(flat.rows, input.fmt, flat.columns, [...lead, ...hints]);\n}\n\nexport const insightsCommand = withEffect(\n {\n effect: \"read_live\",\n routes: [\n \"POST /api/ads/meta/insights\",\n \"POST /api/ads/meta/insights/async\",\n \"GET /api/ads/meta/insights/async/status\",\n \"POST /api/ads/meta/insights/async/result\",\n ],\n },\n defineCommand({\n meta: {\n name: \"insights\",\n description: `Performance reporting — the main Meta tool for AI agents.\n\nSmart defaults so the AI doesn't have to remember every flag:\n --level account (set --level campaign|adset|ad to drill in)\n --intent baseline (or leads|revenue|funnel|ranking|video|identity)\n --date-preset last_7d (override with --since/--until)\n --attribution-windows 7d_click,1d_view (the only ones still working post Jan 2026)\n filter: impressions > 0 (skip undelivered rows; --include-undelivered to keep)\n sort: spend descending (a --time-increment read: by date, earliest first)\n --limit 25 at --level ad|adset (the top of the whole read; a hint says how many more, --limit 0 prints all)\n auto-async when query is heavy (level=ad + breakdowns, big date ranges, etc.)\n\nIdentity fields (campaign_name, ad_name etc.) are appended automatically based on --level, --fields\ntoo, so rows are self-describing.\n\nExamples — common AI questions:\n # \"How is GreenLeaf doing this week?\"\n baker ads meta insights --object act_123\n\n # \"How many leads, and at what cost?\" — spend, actions.lead and cost_per.actions.lead per row\n baker ads meta insights --object act_123 --intent leads --date-preset last_14d --output md\n\n # \"Which campaigns are profitable?\"\n baker ads meta insights --object act_123 --level campaign --intent revenue --date-preset last_28d\n\n # \"Which creatives need a refresh?\"\n baker ads meta insights --object act_123 --level ad --intent ranking --date-preset last_14d\n\n # \"Registrations and cost per registration, this week vs last?\" — one call; each row gets compare.<window>\n baker ads meta insights --object act_123 --level campaign --since 2026-09-21 --until 2026-09-27 --compare previous_period --action-types complete_registration\n\n # \"Is this ad fatiguing?\" — 3 days against 7 and 30, frequency/CTR/CPM with their % change\n baker ads meta insights --object <adId> --level ad --fields ad_id,frequency,ctr,cpm --date-preset last_3d --compare last_7d,last_30d --output md\n\n # \"Where do users drop off the funnel?\"\n baker ads meta insights --object act_123 --intent funnel\n\n # \"Which ads to keep?\" — intents combine: rankings, delivery and funnel in one row per ad, one call\n baker ads meta insights --object act_123 --level ad --intent ranking,baseline,funnel --output md\n\n # \"Should we shift budget to Instagram?\"\n baker ads meta insights --object act_123 --level adset --breakdowns publisher_platform,platform_position\n\n # \"How many sign-ups and leads per month?\" — one call, one row per month\n baker ads meta insights --object act_123 --intent revenue --action-types complete_registration,lead --time-increment monthly --since 2026-01-01 --until 2026-03-31\n\n # \"Cost per lead per campaign?\" / \"Cost per <custom conversion> per ad?\" (its id from custom-conversions)\n baker ads meta insights --object act_123 --level ad --action-types 1119307438661117 --output md\n\n # \"Daily spend of the ads whose name holds a token?\" — Meta sums only those ads, archived ones included\n baker ads meta insights --object act_123 --time-increment 1 --since 2026-09-28 --until 2026-10-04 --filtering '[{\"field\":\"ad.name\",\"operator\":\"CONTAIN\",\"value\":\"RUBEN\"}]'\n\n # \"Brazil only, by day?\" — one breakdown value, filtered by Meta\n baker ads meta insights --object act_123 --breakdowns country --time-increment 1 --filtering '[{\"field\":\"country\",\"operator\":\"IN\",\"value\":[\"BR\"]}]'\n\n # Custom field set (escape hatch)\n baker ads meta insights --object act_123 --fields impressions,spend,actions\n\nAction arrays (actions, cost_per_action_type, conversions, …) are compact: Meta's aliases of one conversion\n(omni_, offsite_conversion.fb_pixel_, onsite_web_ …) collapse to one entry under its plain name\n(complete_registration, lead, purchase), and engagement counts (likes, saves, video views) are left out. Every\nentry has a value: when Meta sent none, a count's window figures summed, else 0; a cost, ROAS or rate says null.\n--attribution-windows other than the default (7d_click for click-only) makes value those windows alone, every named\nwindow set (0 where Meta counted none, null where it sent one total it did not split): Meta's own value, kept by\n--full, is its 7d_click,1d_view total whatever was asked.\n--action-types keeps only the named types; --full returns Meta's raw arrays. --output md|csv gives each\naction type its own column (actions.lead, cost_per_action_type.lead); a custom event, or every type --action-types\nnames, also gets its cost (cost_per.conversions.<type> = spend / count). --intent funnel adds result_type, results,\ncvr (% of link clicks) and cost_per_result to each row; --action-types <type> picks which action is the result.\n--compare <windows> reads the same thing over each window (previous_period, a preset, or YYYY-MM-DD..YYYY-MM-DD) and\nsets it beside each row as compare.<window>: that window's figures and change_pct, the % change from it to the read.\n\nAsync is automatic for heavy queries; pass --async to force it, or --no-async to refuse fallback.`,\n },\n args: withWindowSpellings({\n object: {\n type: \"string\",\n description: \"Object ID — act_<id> for account, or a campaign/adset/ad ID\",\n },\n level: { type: \"string\", description: \"account|campaign|adset|ad (default: account)\" },\n intent: {\n type: \"string\",\n description:\n \"baseline|leads|revenue|funnel|ranking|video|identity (default: baseline); several comma-separated read together, one row per object (ranking,funnel)\",\n },\n fields: {\n type: \"string\",\n description:\n \"Comma-separated field list (overrides --intent bundle; the --level's ids and names are still added)\",\n },\n \"list-intents\": { type: \"boolean\", description: \"Print available intents and exit\" },\n \"date-preset\": {\n type: \"string\",\n description:\n \"Meta date preset: today, yesterday, last_3d|7d|14d|28d|30d|90d, this_month, last_month, this_year, maximum (lifetime), …; any other is refused with the list\",\n },\n since: { type: \"string\", description: \"Custom start date YYYY-MM-DD\" },\n until: { type: \"string\", description: \"Custom end date YYYY-MM-DD\" },\n \"time-increment\": {\n type: \"string\",\n description: \"1 or daily (a row per day) | 2-90 (a row per that many days) | monthly | all_days\",\n },\n breakdowns: { type: \"string\", description: \"Comma-separated breakdowns (e.g. publisher_platform,age)\" },\n \"action-types\": {\n type: \"string\",\n description:\n \"Keep only these action types in actions/cost_per_action_type/conversions — plain names (complete_registration,lead,purchase), a raw Meta name, a custom event's name, or a custom conversion's id. Works with any intent: it asks for actions when the intent has none.\",\n },\n full: { type: \"boolean\", description: \"Return Meta's raw action arrays: every alias and engagement type\" },\n \"action-breakdowns\": {\n type: \"string\",\n description: \"Slice the actions[] array (default: action_type for revenue/funnel)\",\n },\n filtering: {\n type: \"string\",\n description:\n 'Meta filters the rows before they are sent — JSON array of {field,operator,value}, replacing the default impressions>0 filter. One name token at any level: \\'[{\"field\":\"ad.name\",\"operator\":\"CONTAIN\",\"value\":\"SPRING\"}]\\' (case-insensitive; also campaign.name, adset.name, ad.id IN [...]); archived and deleted entities are kept unless you filter their effective_status. One breakdown value: \\'[{\"field\":\"country\",\"operator\":\"IN\",\"value\":[\"BR\"]}]\\' with --breakdowns country (publisher_platform, platform_position, age, gender too).',\n },\n \"include-undelivered\": { type: \"boolean\", description: \"Keep rows where impressions=0 (off by default)\" },\n \"attribution-windows\": {\n type: \"string\",\n description:\n \"Override default 7d_click,1d_view (only 1d_view, 1d_click, 7d_click, 28d_click work post Jan 2026). Start here for click-only: --attribution-windows 7d_click — each compact value then counts the named windows alone, each window key set (0 where Meta counted none, null where it did not split its total).\",\n },\n \"use-account-attribution\": { type: \"boolean\", description: \"Use account-saved attribution setting\" },\n \"use-unified-attribution\": { type: \"boolean\", description: \"Use ad-set unified attribution setting\" },\n limit: {\n type: \"string\",\n description:\n \"Rows to print (default 25 at --level ad|adset, every row otherwise; 0 prints every row). The rows printed are the top of the whole read, in its order.\",\n },\n // Declaring `no-async` too would be a trap: citty resolves it to `async: false`\n // and never fills an arg of that name, so the declaration reads as supported\n // while nothing consumes it.\n async: { type: \"boolean\", description: \"Force the async submit-and-poll path (--no-async refuses it)\" },\n \"no-sort\": {\n type: \"boolean\",\n description: \"Keep Meta's own row order (default: by spend, or by date with --time-increment)\",\n },\n compare: {\n type: \"string\",\n description:\n \"Set each row beside the same read over other windows, with every figure's change in % (compare.<window>.change_pct): previous_period (as many days just before), a Meta preset (last_30d) or YYYY-MM-DD..YYYY-MM-DD, comma-separated. Rows are flat, one key per action type. Not with --time-increment.\",\n },\n \"no-cache\": NO_CACHE_ARG,\n output: { type: \"string\", description: \"Output format: json|csv|jsonl|md\", default: \"json\" },\n }),\n run: async ({ args }) => {\n if (args[\"list-intents\"]) {\n writeAdsJson({ ok: true, data: listIntents() });\n return;\n }\n\n if (!args.object) {\n writeAdsJson({\n ok: false,\n error: { code: \"VALIDATION_ERROR\", message: \"Missing required argument: --object\" },\n });\n process.exit(1);\n }\n\n const body = buildBody(args);\n const fmt = csvOrJson(args);\n const compare = pickCompare(args.compare, body);\n\n try {\n const rows = await readRows(body, args.async);\n const cut = rowsToPrint(rows, body, args);\n const shaped = printedRows(cut.rows, args);\n const sorted = shaped.rows;\n if (cut.leftOut !== null) shaped.hints.push(`${cut.leftOut}; --limit <n> prints more, --limit 0 every row.`);\n if (compare !== undefined) {\n await printCompared({ windows: compare, body, args, fmt, rows, printed: shaped });\n return;\n }\n\n const synced = syncedHintOf(body, rows, false);\n const lead = synced === null ? [] : [synced];\n if (fmt !== \"json\") {\n const table =\n args.full || fmt === \"jsonl\"\n ? { rows: sorted, columns: printedFields(body, args) }\n : flatTable(sorted, body, args);\n writeAdsOutput(table.rows, fmt, table.columns, [...lead, ...shaped.hints]);\n return;\n }\n writeInsightsJson(sorted, lead, [...placementDeliveryHints(rows), ...shaped.hints]);\n } catch (err) {\n handleMetaError(err);\n }\n },\n }),\n);\n","import { placementFormatNote, previewFormatForPosition } from \"@baker/api/ads-meta\";\n\n/**\n * Reads a placement breakdown the way the question \"why does my video show as a\n * still image?\" actually needs to be answered: with this account's own numbers.\n *\n * The failure this replaces is an agent recalling a list of \"image-only\n * placements\" (most of it wrong) and inventing a mechanism Meta does not\n * document. Impressions against video plays, per placement, is the cheap\n * empirical check — it costs one query the agent already ran, and it is\n * account evidence rather than a rule. So the hints below name a suspect and\n * hand over the command that confirms it; they never conclude.\n */\n\n/**\n * Below this, a placement's play rate is arithmetic on too few impressions to\n * carry a claim. Set against a 90%-ish reference rate, seeing no plays in 20\n * impressions is not something chance produces — so this is low enough to reach\n * the long tail where format problems actually live, and the placements it\n * excludes are the ones nobody could have concluded anything from anyway.\n */\nconst MIN_IMPRESSIONS = 20;\n\n/**\n * How far below the ad's own play rate counts as \"this placement is not playing\".\n *\n * Judged against the ad, not against zero. The account this was built from is\n * the reason: it plays at 93% overall, and the one placement carrying a\n * documented format constraint played at 3.85% — 24x worse, and still above any\n * absolute \"under 2%\" bar. An absolute rule cannot see that at any impression\n * threshold; a relative one calibrates itself per creative and per account.\n */\nconst SILENT_FRACTION_OF_REFERENCE = 0.1;\n\n/** Proof the creative plays at all somewhere, so a flagged placement means something. */\nconst PLAYING_REFERENCE_RATE = 0.5;\n\ninterface PlacementDelivery {\n platform: string;\n position: string;\n impressions: number;\n plays: number;\n playRate: number;\n share: number;\n}\n\nfunction toNumber(value: unknown): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n}\n\n/** Meta returns action metrics as `[{ action_type, value }]`; the total is what matters here. */\nfunction sumActionValues(value: unknown): number {\n if (!Array.isArray(value)) return 0;\n return value.reduce<number>((total, entry) => {\n const item = entry as { value?: unknown };\n return total + toNumber(item?.value);\n }, 0);\n}\n\nfunction aggregate(rows: Array<Record<string, unknown>>): PlacementDelivery[] {\n const byPlacement = new Map<string, PlacementDelivery>();\n let totalImpressions = 0;\n\n for (const row of rows) {\n const position = row.platform_position;\n if (typeof position !== \"string\" || position.length === 0) continue;\n const platform = typeof row.publisher_platform === \"string\" ? row.publisher_platform : \"\";\n const impressions = toNumber(row.impressions);\n totalImpressions += impressions;\n const key = `${platform}/${position}`;\n const current = byPlacement.get(key) ?? { platform, position, impressions: 0, plays: 0, playRate: 0, share: 0 };\n current.impressions += impressions;\n current.plays += sumActionValues(row.video_play_actions);\n byPlacement.set(key, current);\n }\n\n return [...byPlacement.values()].map((placement) => ({\n ...placement,\n playRate: placement.impressions > 0 ? placement.plays / placement.impressions : 0,\n share: totalImpressions > 0 ? placement.impressions / totalImpressions : 0,\n }));\n}\n\nfunction previewCommand(placement: PlacementDelivery): string {\n const format = previewFormatForPosition(placement.position, placement.platform);\n return format\n ? `\\`baker ads meta preview --creative-id <id> --placement ${placement.position} --platform ${placement.platform}\\``\n : `no preview format is known for ${placement.position}, so Meta's renderer cannot confirm it — say the placement is unverified rather than filling the gap`;\n}\n\n/**\n * The play rate only means something when every row describes the same\n * creative. Aggregating placements across ads puts an image ad's impressions in\n * the same bucket as a video's plays, which reads as \"this placement doesn't\n * render video\" when it only means \"an image ad ran there\" — the exact wrong\n * conclusion this module exists to prevent. So a query that does not pin one ad\n * (`--level ad --object <adId>`) gets no hint rather than a confounded one.\n */\nfunction isSingleAdQuery(rows: Array<Record<string, unknown>>): boolean {\n const adIds = new Set<string>();\n for (const row of rows) {\n if (typeof row.ad_id !== \"string\" || row.ad_id.length === 0) return false;\n adIds.add(row.ad_id);\n }\n return adIds.size === 1;\n}\n\n/**\n * Placements this account delivered into without the video ever playing.\n *\n * Silent unless the query carried video metrics AND the creative demonstrably\n * plays somewhere else: without a playing reference, a zero everywhere means\n * \"not a video query\", not \"the placement is broken\".\n */\nexport function placementDeliveryHints(rows: Array<Record<string, unknown>>): string[] {\n const carriesVideoMetrics = rows.some((row) => Array.isArray(row.video_play_actions));\n if (!carriesVideoMetrics || !isSingleAdQuery(rows)) return [];\n\n const placements = aggregate(rows);\n const judgeable = placements.filter((p) => p.impressions >= MIN_IMPRESSIONS);\n const impressions = judgeable.reduce((total, p) => total + p.impressions, 0);\n const reference = impressions > 0 ? judgeable.reduce((total, p) => total + p.plays, 0) / impressions : 0;\n if (reference < PLAYING_REFERENCE_RATE) return [];\n\n const silent = judgeable\n .filter((p) => p.playRate < reference * SILENT_FRACTION_OF_REFERENCE)\n .sort((a, b) => b.impressions - a.impressions);\n\n // Never go quiet on a video placement query. Silence is what the agent fills\n // in with a remembered rule, and \"every placement plays\" is the answer to\n // \"why does it show as a still image\" far more often than a placement is.\n if (silent.length === 0) {\n const worst = [...judgeable].sort((a, b) => a.playRate - b.playRate)[0];\n return [\n `Checked every placement above ${MIN_IMPRESSIONS} impressions against this ad's own play rate (${(reference * 100).toFixed(0)}%): no placement is failing to play the video${worst ? `, the lowest being ${worst.platform}/${worst.position} at ${(worst.playRate * 100).toFixed(0)}%` : \"\"}. So placements do not explain a \"it shows as a still image\" report — rule out autoplay off or data saver in the viewer's own app, which renders every video as its cover frame account-wide.`,\n ];\n }\n\n const hints = silent.map((placement) => {\n const note = placementFormatNote(placement.position);\n const documented = note ? ` Meta documents this placement: ${note.note}` : \"\";\n return `${placement.platform}/${placement.position} delivered ${placement.impressions.toLocaleString(\"en-US\")} impressions (${(placement.share * 100).toFixed(1)}% of the total) and ${placement.plays.toLocaleString(\"en-US\")} video plays — it may not be rendering the video. This is account evidence, not a rule: confirm what Meta renders there with ${previewCommand(placement)} before you say anything about it.${documented}`;\n });\n\n const combinedShare = silent.reduce((total, placement) => total + placement.share, 0) * 100;\n hints.push(\n `Those placements are ${combinedShare.toFixed(1)}% of delivery in this query. State that share before proposing to remove them — and note that removing placements from a live ad set is a targeting change, which Meta counts as a significant edit that re-enters the learning phase.`,\n );\n return hints;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM,oBAAoB;AAG1B,IAAM,gBAAgB;AAGtB,IAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,eAAe,oBAAI,IAAI,CAAC,kCAAkC,iBAAiB,CAAC;AAGlF,SAAS,cAAc,MAAsB;AAC3C,MAAI,aAAa,IAAI,IAAI,EAAG,QAAO;AACnC,MAAI,KAAK,WAAW,oCAAoC,EAAG,QAAO;AAClE,QAAM,SAAS,eAAe,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC;AAC5D,SAAO,SAAS,KAAK,MAAM,OAAO,MAAM,IAAI;AAC9C;AAEA,SAAS,QAAQ,MAAuB;AACtC,SAAO,iBAAiB,IAAI,IAAI,KAAK,KAAK,WAAW,iBAAiB,KAAK,cAAc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I;AACF,cAAM,OAAO,MAAM,SAAS,MAAM,KAAK,KAAK;AAC5C,cAAM,MAAM,YAAY,MAAM,MAAM,IAAI;AACxC,cAAM,SAAS,YAAY,IAAI,MAAM,IAAI;AACzC,cAAM,SAAS,OAAO;AACtB,YAAI,IAAI,YAAY,KAAM,QAAO,MAAM,KAAK,GAAG,IAAI,OAAO,iDAAiD;AAC3G,YAAI,YAAY,QAAW;AACzB,gBAAM,cAAc,EAAE,SAAS,SAAS,MAAM,MAAM,KAAK,MAAM,SAAS,OAAO,CAAC;AAChF;AAAA,QACF;AAEA,cAAM,SAAS,aAAa,MAAM,MAAM,KAAK;AAC7C,cAAM,OAAO,WAAW,OAAO,CAAC,IAAI,CAAC,MAAM;AAC3C,YAAI,QAAQ,QAAQ;AAClB,gBAAM,QACJ,KAAK,QAAQ,QAAQ,UACjB,EAAE,MAAM,QAAQ,SAAS,cAAc,MAAM,IAAI,EAAE,IACnD,UAAU,QAAQ,MAAM,IAAI;AAClC,yBAAe,MAAM,MAAM,KAAK,MAAM,SAAS,CAAC,GAAG,MAAM,GAAG,OAAO,KAAK,CAAC;AACzE;AAAA,QACF;AACA,0BAAkB,QAAQ,MAAM,CAAC,GAAG,uBAAuB,IAAI,GAAG,GAAG,OAAO,KAAK,CAAC;AAAA,MACpF,SAAS,KAAK;AACZ,wBAAgB,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["z","z","previousPeriod","windowHints"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  keywordMetricsHints
3
- } from "./chunk-52GWXYQ6.js";
3
+ } from "./chunk-RNOWWEA7.js";
4
4
  import {
5
5
  RESEARCH_DATA_NOTE,
6
6
  handleResearchError,
@@ -232,4 +232,4 @@ function comparedQueryContext(locations, language) {
232
232
  export {
233
233
  keywordMetricsCommand
234
234
  };
235
- //# sourceMappingURL=keyword-metrics-AIOK6XG2.js.map
235
+ //# sourceMappingURL=keyword-metrics-3CCOTXLY.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  keywordsForSiteHints
3
- } from "./chunk-52GWXYQ6.js";
3
+ } from "./chunk-RNOWWEA7.js";
4
4
  import {
5
5
  RESEARCH_DATA_NOTE,
6
6
  handleResearchError,
@@ -132,4 +132,4 @@ Examples:
132
132
  export {
133
133
  keywordsForSiteCommand
134
134
  };
135
- //# sourceMappingURL=keywords-for-site-WKUQFYDA.js.map
135
+ //# sourceMappingURL=keywords-for-site-DM4UZBIE.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  linkedinPersonHints
3
- } from "./chunk-52GWXYQ6.js";
3
+ } from "./chunk-RNOWWEA7.js";
4
4
  import {
5
5
  handleResearchError,
6
6
  writeResearchJson
@@ -140,4 +140,4 @@ Examples:
140
140
  export {
141
141
  linkedinPersonCommand
142
142
  };
143
- //# sourceMappingURL=linkedin-person-UPJBQUXL.js.map
143
+ //# sourceMappingURL=linkedin-person-2UWQAMFI.js.map
@@ -121,7 +121,7 @@ Full guide: __tooling__/docs/tools/baker/ads-meta.md`
121
121
  "custom-conversions": () => import("./custom-conversions-A2ROWOH6.js").then((m) => m.customConversionsCommand),
122
122
  pixels: () => import("./pixels-I7S5N76B.js").then((m) => m.pixelsCommand),
123
123
  activities: () => import("./activities-YXZ6PLZU.js").then((m) => m.activitiesCommand),
124
- insights: () => import("./insights-PBJODKMY.js").then((m) => m.insightsCommand),
124
+ insights: () => import("./insights-YXWOM5FX.js").then((m) => m.insightsCommand),
125
125
  preview: () => import("./preview-5CK5INGO.js").then((m) => m.previewCommand),
126
126
  videos: () => import("./videos-OF6PAPP2.js").then((m) => m.videosCommand),
127
127
  targeting: () => import("./targeting-U25ZHNG5.js").then((m) => m.targetingCommand),
@@ -149,4 +149,4 @@ Full guide: __tooling__/docs/tools/baker/ads-meta.md`
149
149
  export {
150
150
  metaCommand
151
151
  };
152
- //# sourceMappingURL=meta-OTEBUJM5.js.map
152
+ //# sourceMappingURL=meta-57E652I4.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  peopleHints
3
- } from "./chunk-52GWXYQ6.js";
3
+ } from "./chunk-RNOWWEA7.js";
4
4
  import {
5
5
  handleResearchError,
6
6
  writeResearchJson
@@ -159,4 +159,4 @@ export {
159
159
  peopleCommand,
160
160
  peopleFix
161
161
  };
162
- //# sourceMappingURL=people-QFZI2E7P.js.map
162
+ //# sourceMappingURL=people-TIUKYSZ4.js.map
@@ -3,8 +3,8 @@ import {
3
3
  redditCommand,
4
4
  searchReddit,
5
5
  subredditsFromArgs
6
- } from "./chunk-ZJBKANBI.js";
7
- import "./chunk-52GWXYQ6.js";
6
+ } from "./chunk-S2WLJBUA.js";
7
+ import "./chunk-RNOWWEA7.js";
8
8
  import "./chunk-HU6BAHX5.js";
9
9
  import "./chunk-ERSX3MKH.js";
10
10
  import "./chunk-MWD6GIL6.js";
@@ -28,4 +28,4 @@ export {
28
28
  searchReddit,
29
29
  subredditsFromArgs
30
30
  };
31
- //# sourceMappingURL=reddit-6A6426JJ.js.map
31
+ //# sourceMappingURL=reddit-QH2T2OSH.js.map
@@ -50,22 +50,22 @@ Examples:
50
50
  Full guide: __tooling__/docs/tools/baker/research.md`
51
51
  },
52
52
  subCommands: {
53
- web: () => import("./web-Q6HMBNRS.js").then((m) => m.webCommand),
54
- fetch: () => import("./fetch-JVI3AO3Q.js").then((m) => m.fetchCommand),
53
+ web: () => import("./web-RNU2PMMK.js").then((m) => m.webCommand),
54
+ fetch: () => import("./fetch-YVKQOGKD.js").then((m) => m.fetchCommand),
55
55
  cite: () => import("./cite-7TTHQZJ7.js").then((m) => m.citeCommand),
56
- "linkedin-person": () => import("./linkedin-person-UPJBQUXL.js").then((m) => m.linkedinPersonCommand),
57
- people: () => import("./people-QFZI2E7P.js").then((m) => m.peopleCommand),
58
- transcript: () => import("./transcript-LQD4BQBX.js").then((m) => m.transcriptCommand),
59
- company: () => import("./company-WBA5NN2V.js").then((m) => m.companyCommand),
60
- "google-ads": () => import("./google-ads-FAAP6HCR.js").then((m) => m.googleAdsCommand),
61
- reddit: () => import("./reddit-6A6426JJ.js").then((m) => m.redditCommand),
62
- customers: () => import("./customers-MKBX6KJ5.js").then((m) => m.customersCommand),
63
- advertisers: () => import("./advertisers-X3PJG6Z6.js").then((m) => m.advertisersCommand),
64
- autocomplete: () => import("./autocomplete-PWMUL7QJ.js").then((m) => m.autocompleteCommand),
56
+ "linkedin-person": () => import("./linkedin-person-2UWQAMFI.js").then((m) => m.linkedinPersonCommand),
57
+ people: () => import("./people-TIUKYSZ4.js").then((m) => m.peopleCommand),
58
+ transcript: () => import("./transcript-5GXGPNS3.js").then((m) => m.transcriptCommand),
59
+ company: () => import("./company-JFASPEKT.js").then((m) => m.companyCommand),
60
+ "google-ads": () => import("./google-ads-4QI33CPF.js").then((m) => m.googleAdsCommand),
61
+ reddit: () => import("./reddit-QH2T2OSH.js").then((m) => m.redditCommand),
62
+ customers: () => import("./customers-MGO6LEK7.js").then((m) => m.customersCommand),
63
+ advertisers: () => import("./advertisers-AKFTZJAL.js").then((m) => m.advertisersCommand),
64
+ autocomplete: () => import("./autocomplete-EBTBGCVM.js").then((m) => m.autocompleteCommand),
65
65
  countries: () => import("./countries-YQS5DVJ4.js").then((m) => m.countriesCommand),
66
66
  intent: () => import("./intent-7AY7ISL3.js").then((m) => m.intentCommand),
67
- "keyword-metrics": () => import("./keyword-metrics-AIOK6XG2.js").then((m) => m.keywordMetricsCommand),
68
- "keywords-for-site": () => import("./keywords-for-site-WKUQFYDA.js").then((m) => m.keywordsForSiteCommand),
67
+ "keyword-metrics": () => import("./keyword-metrics-3CCOTXLY.js").then((m) => m.keywordMetricsCommand),
68
+ "keywords-for-site": () => import("./keywords-for-site-DM4UZBIE.js").then((m) => m.keywordsForSiteCommand),
69
69
  "keyword-gap": () => import("./keyword-gap-4LVY3I2W.js").then((m) => m.keywordGapCommand),
70
70
  languages: () => import("./languages-V6BVBBKJ.js").then((m) => m.languagesCommand),
71
71
  lighthouse: () => import("./lighthouse-BD3DOFNM.js").then((m) => m.lighthouseCommand),
@@ -75,4 +75,4 @@ Full guide: __tooling__/docs/tools/baker/research.md`
75
75
  export {
76
76
  researchCommand
77
77
  };
78
- //# sourceMappingURL=research-PUNEJ4WW.js.map
78
+ //# sourceMappingURL=research-MR7Q47RX.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  transcriptHints
3
- } from "./chunk-52GWXYQ6.js";
3
+ } from "./chunk-RNOWWEA7.js";
4
4
  import {
5
5
  handleResearchError,
6
6
  writeResearchJson
@@ -166,4 +166,4 @@ Examples:
166
166
  export {
167
167
  transcriptCommand
168
168
  };
169
- //# sourceMappingURL=transcript-LQD4BQBX.js.map
169
+ //# sourceMappingURL=transcript-5GXGPNS3.js.map
@@ -10,7 +10,7 @@ import {
10
10
  webDepthHints,
11
11
  webSourceHints,
12
12
  webUnverifiedUrlHints
13
- } from "./chunk-52GWXYQ6.js";
13
+ } from "./chunk-RNOWWEA7.js";
14
14
  import {
15
15
  handleResearchError,
16
16
  writeResearchHints,
@@ -231,4 +231,4 @@ export {
231
231
  webCommand,
232
232
  webMarkdown
233
233
  };
234
- //# sourceMappingURL=web-Q6HMBNRS.js.map
234
+ //# sourceMappingURL=web-RNU2PMMK.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koda-sl/baker-cli",
3
- "version": "0.890.0-dev.759c113cf",
3
+ "version": "0.890.0-dev.fb74d0c04",
4
4
  "description": "AI-agent-first CLI for interacting with Baker, including the Baker creative canvas.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/research/hints.ts"],"sourcesContent":["/**\n * The `research` family shipped with no `hints[]` on any command. Everything\n * here is one nudge for one dead end that an audited run actually hit — not a\n * running commentary on healthy results.\n */\n\nimport {\n RESEARCH_GOOGLE_ADS_MAX_COPY,\n type ResearchCompanyHiring,\n type ResearchCompanyIndustry,\n type ResearchRedditSource,\n} from \"@baker/api\";\nimport type { QueryContext } from \"../../geo-context.ts\";\nimport type { ResearchFix } from \"./output.ts\";\n\ntype Depth = \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * `advertisers` is named after advertisers and returns none of their advertising.\n * A run read the name as \"SERP ad creative\", got domain economics, and wrote \"no\n * live paid ad copy captured\" into the client's vault without ever trying the\n * command that does return copy. So this fires on every call, not just empty ones.\n */\nexport const AD_COPY_ROUTE =\n \"This returns competing domains and their SERP economics — no ad copy, no headlines, no creative. \" +\n \"For a competitor's Google ads and their copy: `baker research google-ads <competitor.com> --copy` \" +\n \"(Google's Ads Transparency Center: every ad, how long it has run, and the text ads' headline and description). \" +\n 'For Meta and LinkedIn: `baker winning-ads advertisers \"<brand>\"` → ' +\n '`baker winning-ads search \"<brief>\" --advertiser-id <id>` → `baker winning-ads content <adId>` ' +\n \"(`primary_text` / `headline` / `cta`, plus the spoken transcript and on-screen text for video). \" +\n \"Do not keep querying this command for copy.\";\n\n/**\n * Empty SERP data has two causes and only one is worth a second call: the wrong\n * market. Once the market was explicit, a re-query is waste — say so, because\n * \"no rows\" otherwise reads as \"reword the keyword\".\n */\nexport function noSerpRowsHints(rowCount: number, queryContext: QueryContext): string[] {\n if (rowCount > 0) {\n return [];\n }\n const defaulted = queryContext.location_is_default || queryContext.language_is_default;\n if (defaulted) {\n return [\n `No rows for ${queryContext.location} / ${queryContext.language} — the market you did not set. ` +\n \"Set --location and --language for the client's actual market and re-run once \" +\n \"(`baker research countries` / `baker research languages` for the accepted codes) \" +\n \"before you touch the keyword.\",\n ];\n }\n return [\n `No rows for ${queryContext.location} / ${queryContext.language}, which you set explicitly. ` +\n \"This term has no third-party SERP coverage in that market — move on rather than re-querying it. \" +\n \"For demand signal try `baker research autocomplete`; for a competitor's actual terms, \" +\n \"`baker research keywords-for-site <domain>`.\",\n ];\n}\n\nexport function advertisersHints(rowCount: number, queryContext: QueryContext): string[] {\n return [...noSerpRowsHints(rowCount, queryContext), AD_COPY_ROUTE];\n}\n\n/**\n * \"This competitor buys no paid search\" is a real competitive answer, but it\n * arrives as an empty array that looks like a broken call — so say which it is\n * before the agent re-runs the same query with a different sort.\n */\nexport function keywordsForSiteHints(\n rowCount: number,\n queryContext: QueryContext,\n typeFilter: string | undefined,\n): string[] {\n if (rowCount > 0) {\n return [];\n }\n if (typeFilter === \"paid\" || typeFilter === \"organic\") {\n return [\n `No rows with --type ${typeFilter} in ${queryContext.location} / ${queryContext.language}. ` +\n `A domain with zero ${typeFilter} keywords in a market is itself the finding — record it and move on. ` +\n \"Confirm once with --type all (nothing at all there means the domain has no SERP coverage, \" +\n \"not that it has no ads) instead of re-running with a different --sort or --limit.\",\n ];\n }\n return noSerpRowsHints(rowCount, queryContext);\n}\n\nconst THIN_ANSWER_CHARS = 600;\nconst THIN_SOURCE_COUNT = 2;\n\n// Only `medium` and `high` have somewhere to escalate to; `xhigh` is the ceiling,\n// so a thin answer there is a fact about the web, not a flag the agent forgot.\nconst ESCALATION: Partial<Record<Depth, string>> = {\n medium:\n \"`medium` is a quick lookup, not a search. Re-ask the SAME question once with `--depth high` before \" +\n \"concluding the web has nothing on it.\",\n high:\n \"`high` already thought hard about this. `--depth xhigh` is the only step left and it can run 15 minutes — \" +\n \"take it only if this answer blocks a deliverable; otherwise record the gap and move on.\",\n};\n\n/**\n * Google grounding used to come back as opaque redirect links labelled by domain,\n * and the agent guessed the real paths, 404'd, and invented links. The backend\n * now follows them; this says what to do with the ones it could not, and with\n * an answer that rests on nothing.\n */\nexport function webSourceHints(sources: Array<{ resolved?: boolean }>): string[] {\n if (sources.length === 0) {\n return [\n \"This answer came back with no sources. Treat every claim in it as Synthesis: — no source to cite. \" +\n \"Do not attach a URL to it; to cite a fact, find the page that states it and read it with `baker research fetch`.\",\n ];\n }\n // An older backend sends no `resolved`; only an explicit false is a link we know is opaque.\n const unresolved = sources.filter((s) => s.resolved === false).length;\n if (unresolved > 0) {\n return [\n `${unresolved} of ${sources.length} sources are Google links that could not be followed (resolved: false). ` +\n \"Do not cite them or guess a path from the site name — cite only a resolved URL, or open the claim's page yourself.\",\n ];\n }\n return [];\n}\n\n/**\n * The model writes article addresses into its prose from memory; one run spent\n * eight fetches on such links before learning they did not exist (BAKER-1502).\n * The backend lists every address the answer names that is none of its sources.\n */\nexport function webUnverifiedUrlHints(unverifiedUrls: string[]): string[] {\n if (unverifiedUrls.length === 0) {\n return [];\n }\n return [\n `${unverifiedUrls.length} address(es) in the answer are none of its sources (unverifiedUrls): the model wrote them, nothing read them, and they are often invented. ` +\n \"Do not cite or fetch them — cite the sources, or find the page with another `baker research web` question.\",\n ];\n}\n\n/**\n * The one thing worth saying about a page that came back fine is that you are\n * not looking at all of it — which the content itself cannot tell you.\n */\nexport function fetchHints({\n truncated,\n contentChars,\n shownChars,\n maxChars,\n}: {\n truncated: boolean;\n contentChars: number;\n shownChars: number;\n /** The `--max-chars` bound, when one was passed: it wins over `--full`. */\n maxChars?: number;\n}): string[] {\n const hints: string[] = [];\n\n if (shownChars < contentChars) {\n const more =\n maxChars === undefined\n ? \"Re-run the same command with `--full` for the whole page\"\n : \"Re-run with a larger `--max-chars` for more, or without `--max-chars` and with `--full` for the whole page\";\n hints.push(\n `Showing the first ${shownChars.toLocaleString(\"en-US\")} of ${contentChars.toLocaleString(\"en-US\")} characters. ` +\n `${more}, or \\`--find '<words>'\\` for only the lines you need — the read is cached for 24h, so it costs no extra time and no extra credit.`,\n );\n }\n\n if (truncated) hints.push(TRUNCATED_READ);\n\n return hints;\n}\n\nconst TRUNCATED_READ =\n \"This page is longer than one read returns, so the end of it is missing. \" +\n \"Don't present this as the complete page; if the part you need is further down, fetch the deeper URL directly.\";\n\n/** Where to look next when the page itself did not have it: the chrome left out of a main-content read. */\nconst wholePageNudge = (wholePage: boolean) =>\n wholePage ? \"\" : \" The read is the main content only: add `--whole-page` to include the header, nav and footer.\";\n\n/**\n * `--find` answers from the whole read, so \"no match\" is a finding about the\n * page, not a reason to dump it and grep by hand.\n */\nexport function findHints({\n find,\n matches,\n shownMatches,\n maxChars,\n wholePage,\n truncated,\n}: {\n find: string;\n matches: number;\n /** Matching lines the answer shows: fewer when the passage limit or the character budget cut it short. */\n shownMatches: number;\n /** The `--max-chars` bound, when one was passed. */\n maxChars?: number;\n wholePage: boolean;\n truncated: boolean;\n}): string[] {\n const hints: string[] = [];\n if (matches === 0) {\n hints.push(\n `No line of the page matches \\`${find}\\` (case-insensitive). Try another word the page would use — its language, a currency sign, a digit pattern like '[0-9]+,[0-9]{2}'.${wholePageNudge(wholePage)}`,\n );\n }\n if (shownMatches < matches) {\n const more = maxChars === undefined ? \"\" : \", or raise `--max-chars`\";\n hints.push(\n `${matches - shownMatches} more matching lines are not shown. Narrow \\`--find\\` to the words around what you need${more}.`,\n );\n }\n if (truncated) hints.push(TRUNCATED_READ);\n return hints;\n}\n\ninterface RefCount {\n kept: number;\n total: number;\n}\n\nexport function refsHints({\n links,\n images,\n find,\n wholePage,\n truncated,\n}: {\n links?: RefCount;\n images?: RefCount;\n find?: string;\n wholePage: boolean;\n truncated: boolean;\n}): string[] {\n const hints: string[] = [];\n const empty = (name: string, count: RefCount) => {\n if (count.kept > 0) return;\n hints.push(\n count.total > 0 && find !== undefined\n ? `None of the page's ${count.total} ${name} matches \\`${find}\\`.${wholePageNudge(wholePage)}`\n : `The page references no ${name}.${wholePageNudge(wholePage)}`,\n );\n };\n if (links) empty(\"links\", links);\n if (images) empty(\"images\", images);\n if (truncated) hints.push(TRUNCATED_READ);\n return hints;\n}\n\nexport function webDepthHints({\n answer,\n sourceCount,\n depth,\n}: {\n answer: string;\n sourceCount: number;\n depth: Depth;\n}): string[] {\n const thin = answer.length < THIN_ANSWER_CHARS || sourceCount <= THIN_SOURCE_COUNT;\n const escalation = ESCALATION[depth];\n if (!thin || !escalation) {\n return [];\n }\n return [`Thin answer (${answer.length} chars, ${sourceCount} source(s)). ${escalation}`];\n}\n\n/**\n * The volume DataForSEO returns is Google's own Keyword Planner figure resold,\n * so putting the two side by side validates nothing — a run did exactly that,\n * found all seven rows agreeing to the digit, and reported the agreement as\n * corroboration. This fires on every call rather than on a suspicious one,\n * because by the time the numbers are in a table the provenance is already gone.\n */\nexport function keywordMetricsHints({\n rows,\n asked,\n clickstream,\n queryContext,\n}: {\n rows: Array<{ keyword: string; location?: string; search_volume: number | null }>;\n asked: string[];\n clickstream: boolean;\n queryContext: QueryContext;\n}): string[] {\n if (rows.length === 0) {\n return noSerpRowsHints(0, queryContext);\n }\n\n const provenance =\n \"DataForSEO resells Google's Keyword Planner volume — planner_search_volume here is the SAME number \" +\n \"`baker ads google keywords metrics` returns, not an independent reading of it. Quoting the two as agreeing \" +\n \"sources is not corroboration.\" +\n (clickstream\n ? \" clickstream_search_volume IS independent (DataForSEO's own panels); when the two disagree, say which one you are quoting.\"\n : \" For a genuinely independent estimate of demand, re-run with --clickstream (costs 2x), or use first-party data: \" +\n \"`baker gsc query` for what already reaches the site, or the account's own search terms.\");\n\n const hints = [provenance];\n\n const compared = rows.some((row) => row.location !== undefined);\n const empty = rows\n .filter((row) => row.search_volume === null)\n .map((row) => (row.location === undefined ? row.keyword : `${row.keyword} (${row.location})`));\n if (empty.length > 0) {\n hints.push(\n `${empty.length} of ${compared ? `${rows.length} keyword/market rows` : `${asked.length} keywords`} came back with no data in ${queryContext.location} / ${queryContext.language}: ` +\n `${empty.join(\", \")}. That is missing coverage, NOT zero demand — do not report them as unsearched, and do not ` +\n \"re-query them reworded. `baker research autocomplete` on the head term is the way to find the phrasing that market uses.\",\n );\n }\n\n return hints;\n}\n\n/**\n * The archive keeps a post's words the moment it is written and its points\n * only once it has settled, so a number on something young is not the number\n * Reddit shows. Said once, when it applies, so a count is never quoted as live.\n */\nconst ARCHIVE_NOTE =\n \"Read from the Reddit archive: the words are as posted, but points and comment counts on anything under ~36h old are as first captured — don't quote those numbers as current.\";\n\n/**\n * An empty Reddit search is almost always a phrasing miss, not a silent\n * audience: Reddit matches words, and people write in their own. A run that\n * came back empty on a posts search also never looked at the replies, which is\n * where most of the verbatim voice is.\n */\nexport function redditSearchHints({\n resultCount,\n kind,\n source,\n}: {\n resultCount: number;\n kind: \"posts\" | \"comments\";\n source: ResearchRedditSource;\n}): string[] {\n const hints: string[] = [];\n if (resultCount === 0) {\n hints.push(\n \"Nothing matched. Reddit search matches words, not meaning: try the audience's own phrasing (one distinctive word, \" +\n \"or a seed from `baker research autocomplete`), a longer --since window, or other subreddits — \" +\n '`baker research reddit subreddits \"<topic>\"` finds where the audience actually talks' +\n (kind === \"posts\"\n ? \", and try --kind comments --subreddit <names> — most of the voice is in the replies, and replies are only searched inside named subreddits.\"\n : \".\"),\n );\n } else if (kind === \"posts\") {\n hints.push(\n \"Titles rarely carry the voice. Read the promising threads with `baker research reddit thread <permalink>` \" +\n \"for the replies, or search the replies directly with --kind comments --subreddit <the subreddits these came from>.\",\n );\n }\n if (source === \"archive\" && resultCount > 0) hints.push(ARCHIVE_NOTE);\n return hints;\n}\n\n/** A thread whose replies no source would serve is still the post — but it must not read as a thread nobody answered. */\nexport function redditThreadHints({\n commentsShown,\n commentsAsked,\n commentCount,\n source,\n}: {\n commentsShown: number;\n commentsAsked: number;\n commentCount: number | null;\n source: ResearchRedditSource;\n}): string[] {\n const hints: string[] = [];\n if (commentsAsked > 0 && commentsShown === 0 && (commentCount ?? 0) > 0) {\n hints.push(\n `This thread has ${commentCount} comments but none could be read just now. Quote the post only, and don't describe the replies.`,\n );\n }\n if (source === \"archive\") hints.push(ARCHIVE_NOTE);\n return hints;\n}\n\nconst REDDIT_HOST = /(^|\\.)reddit\\.com$|^redd\\.it$/i;\n\n/**\n * A subreddit's member count is its size, not its pulse. The run that prompted\n * this command mined r/CouriersUK — a real subreddit, with one post in its whole\n * history — and found nothing. One dated search tells a living subreddit from a\n * dead one before it is relied on.\n */\nexport function redditSubredditsHints({ resultCount }: { resultCount: number }): string[] {\n if (resultCount === 0) {\n return [\n 'No subreddits matched. Try the audience\\'s role or the platform they work on (\"amazon flex\", \"deliveroo\", \"nurses\"), one word at a time, or a web search for `site:reddit.com <topic>`.',\n ];\n }\n return [\n 'Members say how big a subreddit is, not how active it is. Before mining one, run `baker research reddit search \"<word>\" --subreddit <name> --since <a recent date>`: nothing back means it is quiet, so pick another. `restricted` can still be read; `private` cannot.',\n ];\n}\n\n/** A Reddit link that does not lead to the words attributed to it. Shared by `reddit thread` and `fetch`. */\nexport const REDDIT_LINK_REJECTED: ResearchFix = {\n action: \"reject\",\n explanation:\n \"Do not quote anything attributed to this link — it does not lead to those words. Find the real thread with `baker research reddit search`, and if you already wrote a quote from it, remove it.\",\n};\n\n/**\n * `research fetch` hands a Reddit URL to the Reddit reader, but its generic\n * remediation was written for ordinary pages: FORBIDDEN reads \"this will not\n * open, carry on without it\" and NOT_FOUND \"carry on\". For Reddit both are the\n * wrong advice. A page the reader will not turn into a thread is one `reddit`\n * command away, and a link that leads nowhere real must not be quoted at all.\n */\nexport function redditPageFix(url: string, code: string): ResearchFix | null {\n let host: string;\n try {\n host = new URL(url).hostname;\n } catch {\n return null;\n }\n if (!REDDIT_HOST.test(host)) return null;\n if (code === \"NOT_FOUND\") return REDDIT_LINK_REJECTED;\n if (code !== \"FORBIDDEN\") return null;\n return {\n action: \"retry_with_changes\",\n explanation:\n 'Read Reddit with its own commands: `baker research reddit search \"<words>\" --subreddit <name>` to find what people said, `baker research reddit thread <url>` for one thread.',\n };\n}\n\n/**\n * `google-ads` replaces a browser trip through Google's Ads Transparency\n * Center, so its hints keep the agent out of one: no ads is an answer, and an\n * ad whose copy Google does not give is shown by its link, never opened.\n */\nexport function googleAdsHints({\n target,\n adCount,\n located,\n textWithoutCopy,\n copyAsked,\n copyUnread,\n visual,\n}: {\n target: string;\n adCount: number;\n located: boolean;\n textWithoutCopy: number;\n copyAsked: boolean;\n copyUnread: number;\n visual: number;\n}): string[] {\n if (adCount === 0) {\n return [\n `No Google ads point to ${target}${located ? \" in that region\" : \"\"} — that is the answer, not a failed call: ` +\n \"this competitor is not advertising on Google there, or its ads point to another domain. \" +\n (located ? \"Re-run once without --location to see every region; then move on. \" : \"Move on. \") +\n `Its paid search terms, if any: \\`baker research keywords-for-site ${target} --type paid\\`.`,\n ];\n }\n const hints: string[] = [];\n if (!copyAsked && textWithoutCopy > 0) {\n hints.push(\n `${textWithoutCopy} text ads came back without their words. Re-run with --copy to read the headline and description of up to ${RESEARCH_GOOGLE_ADS_MAX_COPY} (cached, so only the reading is new).`,\n );\n }\n const pastCap = copyAsked ? textWithoutCopy - copyUnread : 0;\n if (pastCap > 0) {\n hints.push(\n `${pastCap} text ads past the first ${RESEARCH_GOOGLE_ADS_MAX_COPY} were not read — one request reads at most ${RESEARCH_GOOGLE_ADS_MAX_COPY}. ` +\n \"Narrow with --since, --location or --platform google_search and re-run for their words.\",\n );\n }\n if (visual > 0 || copyUnread > 0) {\n const without = [\n visual > 0 ? `${visual} image or video ads (Google gives no text for those)` : \"\",\n copyUnread > 0 ? `${copyUnread} text ads whose image could not be read` : \"\",\n ].filter(Boolean);\n hints.push(\n `No copy for ${without.join(\" and \")}: show those by their \\`transparency_url\\`. ` +\n \"Do not open the Transparency Center in agent-browser to read them — it is the browser load this command exists to avoid.\",\n );\n }\n return hints;\n}\n\n/**\n * A person's profile is read to write one account's ads and pages, and that is\n * all it is for. Said on every read, because the next natural step — saving\n * them to Knowledge, or reading them again next week — is the one we don't take.\n */\nexport const LINKEDIN_PERSON_USE =\n \"For ad and page messaging only; nothing is stored — quote their stated priorities into the creative brief \" +\n \"for this account, and don't save the person to Knowledge or read them again to keep track of them.\";\n\n/**\n * The people a search found are public profiles a decision model checked, not\n * contacts: said on every read, with the one next step that deepens a lead.\n */\nexport function peopleHints({\n found,\n dropped,\n verified,\n}: {\n found: number;\n dropped: number;\n verified: boolean;\n}): string[] {\n if (found === 0) {\n return [\n `Nobody in public LinkedIn results holds this role here${dropped > 0 ? ` (${dropped} profiles were elsewhere now or in another role)` : \"\"}. ` +\n \"Try the name people write on LinkedIn with --name, a broader --seniority, or the client's CRM: `baker hubspot companies contacts <domain>`.\",\n ];\n }\n const hints = [\n verified\n ? \"These are public search results a decision model checked — likely holders of the role, to confirm before anyone reaches out. Brief sales with them; never contact anyone or save them to Knowledge.\"\n : \"The check could not run, so these profiles are unchecked: Google matched the words, not the person. Read each headline before naming anyone.\",\n \"To write to one of them in their own words, read their profile once: `baker research linkedin-person <profile_url>`.\",\n ];\n return hints;\n}\n\nexport function linkedinPersonHints({ isPrivate, postCount }: { isPrivate: boolean; postCount: number }): string[] {\n if (isPrivate) {\n return [\n \"LinkedIn doesn't show this profile publicly, and reading it again won't change that. \" +\n \"Find their own words elsewhere — a keynote, podcast or earnings call through \" +\n \"`baker research transcript <url>`, or an interview through `baker research fetch <url>` — \" +\n \"or write the brief from the account's company-level priorities.\",\n ];\n }\n if (postCount === 0) {\n return [\n LINKEDIN_PERSON_USE,\n \"They have no recent posts, so their `about` is the only first-person line here. \" +\n \"Their priorities are more often said aloud: a keynote, podcast or earnings call through `baker research transcript <url>`.\",\n ];\n }\n return [LINKEDIN_PERSON_USE];\n}\n\n/**\n * A keynote runs to tens of thousands of words, which is why the default is an\n * excerpt; the transcript is cached for a week, so asking again for the rest\n * costs nothing.\n */\nexport function transcriptHints({ excerpted, truncated }: { excerpted: boolean; truncated: boolean }): string[] {\n const hints: string[] = [];\n if (excerpted) {\n hints.push(\n \"This is the opening excerpt. Re-run with `--out <file>` to write the whole text to a file and read the parts you need, \" +\n \"or `--full` to have it all here — the transcript is cached for 7 days, so either costs nothing more.\",\n );\n }\n if (truncated) {\n hints.push(\n \"The recording is longer than one transcript carries, so the end of the recording is missing. \" +\n \"Don't quote this as the whole talk.\",\n );\n }\n return hints;\n}\n\n/** The facts whose absence marks a profile as possibly another company's. */\nexport interface CompanyProfileFacts {\n linkedinUrl: string | null;\n hqCountry: string | null;\n employees: string | null;\n}\n\n/**\n * A profile missing two of its anchor facts, or sized 1-10, is often a namesake\n * on the domain asked for while the company itself runs on another one.\n */\nfunction thinProfileHint(domain: string, profile: CompanyProfileFacts): string | null {\n const missing = [\n profile.linkedinUrl ? null : \"no LinkedIn page\",\n profile.hqCountry ? null : \"no HQ country\",\n profile.employees ? null : \"no employee band\",\n ].filter((gap) => gap !== null);\n const tiny = profile.employees === \"1-10\";\n if (missing.length < 2 && !tiny) return null;\n const why = [...missing, ...(tiny ? [\"1-10 employees\"] : [])].join(\", \");\n return (\n `This profile is thin (${why}). Check ${domain} is the company's main website — companies often run on another ` +\n \"domain (e.g. factorial.es vs factorialhr.com) — before using these facts for tiering.\"\n );\n}\n\n/**\n * Hiring is a signal on top of the profile, so a lookup without it still\n * answers — and says which half is missing, so the agent neither loops on it\n * nor reads \"no openings\" into a gap. A hiring read left out on purpose\n * (`--no-hiring`) says nothing.\n */\nexport function companyHints({\n domain,\n profile,\n hiring,\n}: {\n domain: string;\n profile: CompanyProfileFacts | null;\n hiring: ResearchCompanyHiring;\n}): string[] {\n const hints: string[] = [];\n if (!profile) {\n hints.push(\n \"There's no company profile for this domain, only its hiring. Check it is the company's main website; \" +\n \"otherwise take size, industry and location from its LinkedIn page or its own site.\",\n );\n } else {\n const thin = thinProfileHint(domain, profile);\n if (thin) hints.push(thin);\n }\n if (hiring.status === \"unavailable\" && hiring.reason === \"not_configured\") {\n hints.push(\n \"Hiring signals aren't switched on for this workspace yet, so these are the firmographics alone. \" +\n \"Score the account on them and leave hiring out of the reason.\",\n );\n }\n if (hiring.status === \"unavailable\" && hiring.reason === \"failed\") {\n hints.push(\n \"Hiring signals couldn't be read this time; don't retry in a loop. Use the firmographics and say hiring is unknown for this account.\",\n );\n }\n if (hiring.status === \"not_tracked\") {\n hints.push(\n \"No hiring data is kept for this company — that means unknown, not that it isn't hiring. Don't score it down for it.\",\n );\n }\n return hints;\n}\n\nfunction industryList(industries: readonly ResearchCompanyIndustry[]): string {\n return industries.map(({ slug, companies }) => `${slug} (${companies.toLocaleString(\"en-US\")})`).join(\", \");\n}\n\n/**\n * Neighbouring industries the search left out, so a thin market is widened on\n * purpose rather than guessed at. Each count is the companies it would add.\n */\nfunction relatedIndustriesHint(related: readonly ResearchCompanyIndustry[]): string | null {\n if (related.length === 0) return null;\n return (\n `Related industries not included (companies each adds with your other filters): ${industryList(related)}` +\n \" — add them with --industry a,b to widen.\"\n );\n}\n\nexport function companySearchHints({\n total,\n returned,\n page,\n lastPage,\n related,\n}: {\n total: number;\n returned: number;\n page: number;\n lastPage: number;\n related: readonly ResearchCompanyIndustry[];\n}): string[] {\n const hints: string[] = [];\n if (total === 0) {\n hints.push(\n \"No company matches every filter. Widen one at a time — a neighbouring size band, a related industry, one more country.\",\n );\n } else if (page < lastPage && returned > 0) {\n hints.push(\n `${total} companies match and ${returned} came back (each one returned is billed). ` +\n `Use \\`total\\` to size the market; ask for \\`--page ${page + 1}\\` only if you need the next rows for the list.`,\n );\n }\n const widen = relatedIndustriesHint(related);\n if (widen) hints.push(widen);\n return hints;\n}\n\n/** An industry that is no slug refuses the search before anything is billed; the fix offers the real ones. */\nexport function unknownIndustriesFix(industries: readonly { input: string; closest: ResearchCompanyIndustry[] }[]): {\n action: \"retry_with_changes\";\n explanation: string;\n} {\n const misses = industries.map(({ input, closest }) =>\n closest.length > 0\n ? `\"${input}\" is not an industry. Closest (companies each matches with your other filters): ${industryList(closest)}.`\n : `\"${input}\" is not an industry, and none is named like it — try a broader word (software, logistics, retail).`,\n );\n return {\n action: \"retry_with_changes\",\n explanation: `${misses.join(\" \")} Pass one or several of these slugs with --industry a,b — several widen the search, any of them matching. Nothing was charged.`,\n };\n}\n"],"mappings":";;;;;AAuBO,IAAM,gBACX;AAaK,SAAS,gBAAgB,UAAkB,cAAsC;AACtF,MAAI,WAAW,GAAG;AAChB,WAAO,CAAC;AAAA,EACV;AACA,QAAM,YAAY,aAAa,uBAAuB,aAAa;AACnE,MAAI,WAAW;AACb,WAAO;AAAA,MACL,eAAe,aAAa,QAAQ,MAAM,aAAa,QAAQ;AAAA,IAIjE;AAAA,EACF;AACA,SAAO;AAAA,IACL,eAAe,aAAa,QAAQ,MAAM,aAAa,QAAQ;AAAA,EAIjE;AACF;AAE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