@koda-sl/baker-cli 0.895.0 → 0.898.0

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.
package/README.md CHANGED
@@ -1512,8 +1512,8 @@ baker ads meta audiences --account-id act_123
1512
1512
 
1513
1513
  # "Is the pixel firing?"
1514
1514
  baker ads meta pixels --account-id act_123 # id, name, last fired, owner; --full adds the install code
1515
- baker ads meta pixels --pixel-id 9988 --stats --days 7 # events received per day (date, weekday, event, count)
1516
- baker ads meta pixels --pixel-id 9988 --stats --event Lead --by total # one event: count, first and last seen; --full = raw hourly buckets
1515
+ baker ads meta pixels --pixel-id 9988 --stats --days 7 # the 25 most received events: count, first and last seen; --by total = every one
1516
+ baker ads meta pixels --pixel-id 9988 --stats --event Lead # one event per day (date, weekday, event, count); --by day = every event; --full = raw hourly buckets
1517
1517
 
1518
1518
  # "Why isn't it using MY conversions?"
1519
1519
  baker ads meta custom-conversions --account-id act_123 # id, event category, pixel, and the rule as a phrase
@@ -6,10 +6,10 @@ import {
6
6
  readForms,
7
7
  readLandings,
8
8
  readReports
9
- } from "./chunk-ESGANKHR.js";
9
+ } from "./chunk-XJE4JH7C.js";
10
10
  import {
11
11
  rulesView
12
- } from "./chunk-OLIEY4WM.js";
12
+ } from "./chunk-JROQOOUR.js";
13
13
  import {
14
14
  fetchRunRecord
15
15
  } from "./chunk-LDMF7X32.js";
@@ -659,4 +659,4 @@ export {
659
659
  savedHint,
660
660
  widenedRule
661
661
  };
662
- //# sourceMappingURL=add-XRXV4JYO.js.map
662
+ //# sourceMappingURL=add-SK4RUEEM.js.map
@@ -34,7 +34,7 @@ Full guides: __tooling__/docs/tools/baker/ads-<platform>.md (google|meta|linkedi
34
34
  },
35
35
  subCommands: {
36
36
  google: () => import("./google-T63TXQTL.js").then((m) => m.googleCommand),
37
- meta: () => import("./meta-BJDKNWJA.js").then((m) => m.metaCommand),
37
+ meta: () => import("./meta-GOPN63QP.js").then((m) => m.metaCommand),
38
38
  linkedin: () => import("./linkedin-AJMDNPUD.js").then((m) => m.linkedinCommand),
39
39
  x: () => import("./x-WRK34GQD.js").then((m) => m.xCommand),
40
40
  chatgpt: () => import("./chatgpt-2UCND7NY.js").then((m) => m.chatgptCommand),
@@ -45,4 +45,4 @@ Full guides: __tooling__/docs/tools/baker/ads-<platform>.md (google|meta|linkedi
45
45
  export {
46
46
  adsCommand
47
47
  };
48
- //# sourceMappingURL=ads-WMP6S4FN.js.map
48
+ //# sourceMappingURL=ads-MTUBTBJV.js.map
@@ -273,7 +273,11 @@ registerSchema({
273
273
  effect: "read",
274
274
  description: "Inspect one Session's FULL picture of what it changed \u2014 the unified `effects`: git content (landings, creatives, flows, knowledge, brand), plus DB-only effects that never touch the repo \u2014 Actions, Scheduled agents, Tags, Tag Manager, Google Analytics, ad-platform writes, the funnel (`funnel`: which steps it added, changed or removed, and which ways in it added or removed in `triggersAdded`/`triggersRemoved`), what counts as a conversion (`conversions`), conversion sends, event sources, and every other staged or already-applied change (`otherChanges`: A/B tests, recipes, library images) \u2014 each resolved to real detail (names, descriptions, priorities, tag types, ad operations) and, once published, its `outcome`. Also `publish` (what each external surface actually did, with the provider's own error), `activitySummary` (the chat's own timeline counted by action, with its notable rows: status changes, publish start/fail, workspace recoveries, timeouts; the rows whole as `activity` with --full), `usage` (per-thread cost and the Session's token totals), the kickoff (how it was asked), threads, and commits. Effects are `staged` (in-progress draft) or applied. Compact shows at most 25 rows per list; a list cut to fit is named in `truncated` with its total and every row counted by kind and outcome. `activitySummary.capped` true means the Session logged more than 500 timeline rows and the counts cover the newest 500. One surface: `--surface ads.google` returns only that list, every row counted by kind and outcome (`counts`) plus the first 5 rows that did not apply (`notApplied`: staged, failed, skipped, refused); add --full for all of its rows. A completed Session is NOT proof its external changes landed \u2014 read `publish`. Use after `baker chats list` to decide whether to reuse it. Read-only.",
275
275
  args: {
276
- id: { type: "positional", description: "The Session id (from `baker chats list`)", required: true },
276
+ id: {
277
+ type: "positional",
278
+ description: "The Session id (from `baker chats list`) or one of its thread ids (a thread id reads its whole Session)",
279
+ required: true
280
+ },
277
281
  full: {
278
282
  type: "boolean",
279
283
  description: "Every effect row and the whole activity timeline (compact caps each list at 25 and counts the timeline)",
@@ -319,7 +323,11 @@ var viewCommand = defineCommand({
319
323
  description: "Inspect one Session's full effects \u2014 git content + actions/tags/ads, kickoff, commits."
320
324
  },
321
325
  args: {
322
- id: { type: "positional", description: "The Session id", required: true },
326
+ id: {
327
+ type: "positional",
328
+ description: "The Session id or one of its thread ids (a thread id reads its whole Session)",
329
+ required: true
330
+ },
323
331
  full: { type: "boolean", description: "Include full detail", required: false, default: false },
324
332
  surface: { type: "string", description: "One effect list only, e.g. ads.google", required: false }
325
333
  },
@@ -374,7 +382,7 @@ registerSchema({
374
382
  args: {
375
383
  id: {
376
384
  type: "positional",
377
- description: "The Session id (from `baker chats list`). Default: this chat",
385
+ description: "The Session id (from `baker chats list`) or one of its thread ids (a thread id reads its whole Session). Default: this chat",
378
386
  required: false
379
387
  },
380
388
  search: {
@@ -401,7 +409,11 @@ registerSchema({
401
409
  var transcriptCommand = defineCommand({
402
410
  meta: { name: "transcript", description: "Read a Session's conversation \u2014 another one, or this chat's own." },
403
411
  args: {
404
- id: { type: "positional", description: "The Session id (default: this chat)", required: false },
412
+ id: {
413
+ type: "positional",
414
+ description: "The Session id or one of its thread ids (a thread id reads its whole Session). Default: this chat",
415
+ required: false
416
+ },
405
417
  search: {
406
418
  type: "string",
407
419
  description: "Only messages containing this text (repeatable: any of them)",
@@ -462,7 +474,11 @@ registerSchema({
462
474
  command: "chats.diff",
463
475
  description: "See the real file-level changes a Session made (landings, creatives, brand, flows, knowledge). Published Sessions read from git; for an in-progress (unpublished) Session pass --live to read its changes straight from its running workspace. Without --live, an unpublished Session returns available:false \u2014 use `baker chats view` for the staged summary. Compact lists changed files with +/- counts; add --full for the actual diff text. Read-only.",
464
476
  args: {
465
- id: { type: "positional", description: "The Session id", required: true },
477
+ id: {
478
+ type: "positional",
479
+ description: "The Session id or one of its thread ids (a thread id reads its whole Session)",
480
+ required: true
481
+ },
466
482
  surface: {
467
483
  type: "string",
468
484
  description: "Filter to one surface: knowledge|company|brand|landings|flows|creatives",
@@ -485,7 +501,11 @@ registerSchema({
485
501
  var diffCommand = defineCommand({
486
502
  meta: { name: "diff", description: "See a published Session's real file-level changes." },
487
503
  args: {
488
- id: { type: "positional", description: "The Session id", required: true },
504
+ id: {
505
+ type: "positional",
506
+ description: "The Session id or one of its thread ids (a thread id reads its whole Session)",
507
+ required: true
508
+ },
489
509
  surface: {
490
510
  type: "string",
491
511
  description: "Filter: knowledge|company|brand|landings|flows|creatives",
@@ -727,4 +747,4 @@ Full guide: __tooling__/docs/tools/baker/chats.md`
727
747
  export {
728
748
  chatsCommand
729
749
  };
730
- //# sourceMappingURL=chats-EEQXHX4O.js.map
750
+ //# sourceMappingURL=chats-GLAU5X6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/chats/index.ts","../src/commands/chats/carry-files.ts","../src/commands/chats/publish-hints.ts"],"sourcesContent":["import type {\n ChatsDiffResponse,\n ChatsListRequest,\n ChatsListResponse,\n ChatsTranscriptResponse,\n ChatsViewResponse,\n} from \"@baker/api\";\nimport {\n CHAT_IMPORT_SURFACES,\n type ChatSurfaceDetail,\n type ChatsImportResponse,\n EFFECT_LISTS,\n type EffectList,\n} from \"@baker/api/chats\";\n\ntype ChatImportSurface = (typeof CHAT_IMPORT_SURFACES)[number];\n\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { withWindowSpellings } from \"../../date-window.ts\";\nimport { getEnv, requireChatId } from \"../../env.ts\";\nimport { repeatedValues } from \"../../lib/repeatedFlags.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failApi } from \"../actions/shared.ts\";\nimport { applyPatch, patchRefusal, readSourceFiles, revertPatch, type SourceFiles } from \"./carry-files.ts\";\nimport { publishHints, stillPublishingHints } from \"./publish-hints.ts\";\n\nconst STATUS_GROUPS = [\"active\", \"archived\", \"all\"] as const;\nconst DEFAULT_LIST_LIMIT = 20;\nconst REPO_SURFACES = [\"knowledge\", \"company\", \"brand\", \"landings\", \"flows\", \"creatives\"] as const;\n\nfunction parseBoundedInt(raw: string | undefined, name: string, min: number, max: number): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (Number.isNaN(value) || value < min || value > max) {\n throw new Error(`--${name} must be an integer between ${min} and ${max}`);\n }\n return value;\n}\n\nregisterSchema({\n command: \"chats.list\",\n description:\n 'Start here: list other Sessions on this account (newest first) so you can reuse what was done before. Each row shows the Session id, title, status, and a count of what it produced (creatives, landings, actions, flows, ads, reports…). Looking for one? `--search \"PMax Brasil\"` finds the Sessions whose title or conversation holds any of the words, newest first, each with the `match` it was found by; read the match before trusting a row, since more words match more Sessions. A recap of a period (\"what did we change yesterday\", \"what did we publish in September\") is one call: `--since 2026-09-01 --until 2026-09-30 --published --limit 100` returns every Session published in those days with its `publishedAt` and what those Publishes took (add --full for each change by name, and each Task, Scheduled agent, tag or ad change with what its Publish did) — never a `view` per Session. Without --published the days list every Session worked on in them, a Session continued since included. Then drill in with `baker chats view <id>`, `baker chats transcript <id>`, or `baker chats diff <id>`. Read-only.',\n args: {\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions to return, 1-100 (default: 20)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Include each Session's full change list and its effects by name, with each one's Publish outcome\",\n required: false,\n default: false,\n },\n search: {\n type: \"string\",\n description:\n 'Sessions whose title or conversation holds any of these words, newest first, each with its `match` (e.g. --search \"PMax Brasil\")',\n required: false,\n },\n since: {\n type: \"string\",\n description:\n \"First day, YYYY-MM-DD in the company's time zone: Sessions worked on in the days, even if continued since (with --published, published in them)\",\n required: false,\n },\n until: {\n type: \"string\",\n description: \"Last day, inclusive, YYYY-MM-DD (e.g. --since 2026-11-16 --until 2026-11-16 for one day)\",\n required: false,\n },\n published: {\n type: \"boolean\",\n description:\n \"Only Sessions published in the days, newest publish first, each with its publishedAt; each row counts only those Publishes\",\n required: false,\n default: false,\n },\n },\n});\n\ntype ListArgs = {\n search?: string;\n status?: string;\n limit?: string;\n full?: boolean;\n since?: string;\n until?: string;\n published?: boolean;\n};\n\nfunction listRequestBody(args: ListArgs): ChatsListRequest {\n if (args.status !== undefined && !(STATUS_GROUPS as readonly string[]).includes(args.status)) {\n throw new Error(`--status must be one of: ${STATUS_GROUPS.join(\"|\")}`);\n }\n const status = STATUS_GROUPS.find((group) => group === args.status);\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 100);\n // Exclude our own Session so we never list ourselves as a reusable \"other\".\n const selfChatId = getEnv().BAKER_CHAT_ID;\n return {\n ...(args.search ? { search: args.search } : {}),\n ...(status ? { status } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(args.full ? { full: true } : {}),\n ...(args.since ? { since: args.since } : {}),\n ...(args.until ? { until: args.until } : {}),\n ...(args.published ? { published: true } : {}),\n ...(selfChatId ? { excludeChatId: selfChatId } : {}),\n };\n}\n\nfunction emptyListHint(args: ListArgs): string {\n if (args.search) {\n return \"No Session's title or conversation holds any of those words. Try other words (a name, a figure), widen with --status all, or drop --search to list the newest.\";\n }\n if (args.since || args.until) {\n return args.published\n ? \"No Session was published in those days (company time zone). Widen --since/--until, or drop --published to see the Sessions worked on.\"\n : \"No Session was worked on in those days (company time zone). Widen --since/--until.\";\n }\n return \"No Sessions matched. Widen with --status all or a larger --limit.\";\n}\n\nconst INCOMPLETE_LIST_HINT =\n \"Those days hold more work than one call reads, so a Session worked on early in them and continued since may be missing — split the period into shorter --since/--until calls.\";\n\nfunction listHints(args: ListArgs, count: number, limit: number, incomplete: boolean): string[] {\n const hints = periodListHints(args, count, limit);\n return incomplete ? [INCOMPLETE_LIST_HINT, ...hints] : hints;\n}\n\nfunction periodListHints(args: ListArgs, count: number, limit: number): string[] {\n if (count === 0) {\n return [emptyListHint(args)];\n }\n if (!(args.since || args.until)) {\n return [\n \"Drill in: `baker chats view <id>` for outputs, `chats transcript <id>` for the conversation, `chats diff <id>` for the real file changes.\",\n ];\n }\n const what = args.published ? \"what that Session's Publishes in those days took\" : \"what that Session produced\";\n const recap = `These rows are the recap: each one's \\`outputs\\`${args.full ? \", `changes` and `effects` (with each one's Publish `outcome`)\" : \" (add --full for each change by name and what its Publish did)\"} tell ${what}. Answer from them — open a single Session only for a detail the person asks about, never one \\`view\\` per row.`;\n if (count >= limit) {\n return [\n `These are the newest ${count}; the period may hold more — raise --limit (up to 100) or narrow --since/--until.`,\n recap,\n ];\n }\n return [recap];\n}\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List other Sessions on this account, newest first.\" },\n args: withWindowSpellings({\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions (1-100, default 20)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Include each Session's change list and effects by name, with their Publish outcome\",\n required: false,\n default: false,\n },\n search: {\n type: \"string\",\n description: \"Sessions whose title or conversation holds any of these words\",\n required: false,\n },\n since: {\n type: \"string\",\n description: \"First day worked on (or published), YYYY-MM-DD, even if continued since\",\n required: false,\n },\n until: { type: \"string\", description: \"Last day, inclusive, YYYY-MM-DD\", required: false },\n published: {\n type: \"boolean\",\n description: \"Only published Sessions, by publish date\",\n required: false,\n default: false,\n },\n }),\n run: async ({ args }) => {\n try {\n const body = listRequestBody(args);\n const response = await apiPost<ChatsListResponse>(\"/api/chats/list\", body);\n writeJson({\n ok: true,\n ...rowsAsData(response.data, \"chats\"),\n hints: listHints(\n args,\n response.data.chats.length,\n body.limit ?? DEFAULT_LIST_LIMIT,\n response.data.incomplete === true,\n ),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.view\",\n routes: [\"POST /api/chats/view\"],\n effect: \"read\",\n description:\n \"Inspect one Session's FULL picture of what it changed — the unified `effects`: git content (landings, creatives, flows, knowledge, brand), plus DB-only effects that never touch the repo — Actions, Scheduled agents, Tags, Tag Manager, Google Analytics, ad-platform writes, the funnel (`funnel`: which steps it added, changed or removed, and which ways in it added or removed in `triggersAdded`/`triggersRemoved`), what counts as a conversion (`conversions`), conversion sends, event sources, and every other staged or already-applied change (`otherChanges`: A/B tests, recipes, library images) — each resolved to real detail (names, descriptions, priorities, tag types, ad operations) and, once published, its `outcome`. Also `publish` (what each external surface actually did, with the provider's own error), `activitySummary` (the chat's own timeline counted by action, with its notable rows: status changes, publish start/fail, workspace recoveries, timeouts; the rows whole as `activity` with --full), `usage` (per-thread cost and the Session's token totals), the kickoff (how it was asked), threads, and commits. Effects are `staged` (in-progress draft) or applied. Compact shows at most 25 rows per list; a list cut to fit is named in `truncated` with its total and every row counted by kind and outcome. `activitySummary.capped` true means the Session logged more than 500 timeline rows and the counts cover the newest 500. One surface: `--surface ads.google` returns only that list, every row counted by kind and outcome (`counts`) plus the first 5 rows that did not apply (`notApplied`: staged, failed, skipped, refused); add --full for all of its rows. A completed Session is NOT proof its external changes landed — read `publish`. Use after `baker chats list` to decide whether to reuse it. Read-only.\",\n args: {\n id: {\n type: \"positional\",\n description:\n \"The Session id (from `baker chats list`) or one of its thread ids (a thread id reads its whole Session)\",\n required: true,\n },\n full: {\n type: \"boolean\",\n description:\n \"Every effect row and the whole activity timeline (compact caps each list at 25 and counts the timeline)\",\n required: false,\n default: false,\n },\n surface: {\n type: \"string\",\n description: `One effect list only, counted by kind and outcome, with the rows that did not apply: ${EFFECT_LISTS.join(\"|\")}`,\n required: false,\n },\n },\n});\n\nfunction effectListArg(raw: string | undefined): EffectList | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const list = EFFECT_LISTS.find((name) => name === raw);\n if (!list) {\n throw new Error(`--surface must be one of: ${EFFECT_LISTS.join(\"|\")}`);\n }\n return list;\n}\n\nfunction surfaceHints(data: ChatSurfaceDetail, full: boolean): string[] {\n const { list, total, notApplied, notAppliedTotal } = data.surface;\n const hints: string[] = [];\n if (!full && notApplied.length < notAppliedTotal) {\n hints.push(\n `notApplied shows ${notApplied.length} of ${notAppliedTotal} rows that did not apply — \\`counts\\` has every one; read them all with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n if (!full && notApplied.length < total) {\n hints.push(\n `${list} shows ${notApplied.length} of its ${total} rows; read every row with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n hints.push(\"What each platform's Publish did overall, with its errors: `baker chats view <id> --fields publish`.\");\n return hints;\n}\n\nconst viewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Inspect one Session's full effects — git content + actions/tags/ads, kickoff, commits.\",\n },\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id or one of its thread ids (a thread id reads its whole Session)\",\n required: true,\n },\n full: { type: \"boolean\", description: \"Include full detail\", required: false, default: false },\n surface: { type: \"string\", description: \"One effect list only, e.g. ads.google\", required: false },\n },\n run: async ({ args }) => {\n try {\n const surface = effectListArg(args.surface);\n const response = await apiPost<ChatsViewResponse>(\"/api/chats/view\", {\n chatId: args.id,\n ...(args.full ? { full: true } : {}),\n ...(surface ? { surface } : {}),\n });\n if (\"surface\" in response.data) {\n writeJson({ ...response, hints: surfaceHints(response.data, args.full) });\n return;\n }\n const hints: string[] = response.data.publish ? publishHints(response.data.publish) : [];\n for (const cut of response.data.truncated ?? []) {\n hints.push(\n `effects.${cut.list} shows ${cut.shown} of ${cut.total} — \\`truncated\\` counts all ${cut.total} by kind and outcome; read that list alone with \\`baker chats view <id> --surface ${cut.list}\\`.`,\n );\n }\n if (response.data.activitySummary?.capped) {\n hints.push(\n \"activitySummary covers only the Session's newest 500 timeline rows: its total and counts leave the earlier ones out.\",\n );\n }\n if (response.data.diffAvailable) {\n hints.push(\"See the real file-level diff of the git content with `baker chats diff <id> --full`.\");\n } else if (response.data.status === \"in_progress\" || response.data.status === \"publishing\") {\n hints.push(\n \"This Session is still in progress — read its current file changes with `baker chats diff <id> --live`.\",\n );\n }\n hints.push(...stillPublishingHints(response.data.status));\n hints.push(\"Read the conversation with `baker chats transcript <id>`.\");\n writeJson({ ...response, hints });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst TRANSCRIPT_ROLES = [\"user\", \"assistant\"] as const;\n\n/** Every `--search` given (citty keeps only the last): one text as itself, several as a list matched as any of them. */\nfunction transcriptSearch(rawArgs: readonly string[], parsed: unknown): string | string[] | undefined {\n const texts = repeatedValues(rawArgs, \"search\", parsed).filter((text) => text.trim() !== \"\");\n return texts.length > 1 ? texts : texts[0];\n}\n\nregisterSchema({\n command: \"chats.transcript\",\n routes: [\"POST /api/chats/transcript\"],\n effect: \"read\",\n description:\n 'Start here: read a Session\\'s conversation (user + agent turns), the most recent messages last. Leave out the id to read THIS chat — the way to recover its own earlier words after a context summary (never grep the raw logs on disk). `--search \"5.700\"` returns only the messages holding the text, from the whole conversation however long — repeat it for several (`--search lead --search GTM`: the messages holding any of them, in one call, never a loop); `--role user` keeps one side; `--turns` keeps each request and the agent\\'s closing message of that turn (a recap). To recap an earlier Session, start with `--turns --role user` (its requests), then `--turns --role assistant --limit 3` or `--search` for how it went: `--turns` alone returns every closing reply. Compact truncates long messages (around the match when searching); add --full for verbatim text of one message found with `--search \"<distinctive phrase>\" --limit 1` — a whole chat verbatim runs to tens of KB. Read-only.',\n args: {\n id: {\n type: \"positional\",\n description:\n \"The Session id (from `baker chats list`) or one of its thread ids (a thread id reads its whole Session). Default: this chat\",\n required: false,\n },\n search: {\n type: \"string\",\n description:\n 'Only messages containing this text, case-insensitive (e.g. --search \"5.700\"); repeat it for messages holding any of several (--search lead --search GTM)',\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: {\n type: \"boolean\",\n description: \"Only each user message and the agent's closing message of that turn\",\n required: false,\n default: false,\n },\n limit: { type: \"string\", description: \"Max messages to return, 1-1000 (default: 100)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Return verbatim (untruncated) message text\",\n required: false,\n default: false,\n },\n },\n});\n\nconst transcriptCommand = defineCommand({\n meta: { name: \"transcript\", description: \"Read a Session's conversation — another one, or this chat's own.\" },\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id or one of its thread ids (a thread id reads its whole Session). Default: this chat\",\n required: false,\n },\n search: {\n type: \"string\",\n description: \"Only messages containing this text (repeatable: any of them)\",\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: { type: \"boolean\", description: \"Each request + the closing reply\", required: false, default: false },\n limit: { type: \"string\", description: \"Max messages (1-1000, default 100)\", required: false },\n full: { type: \"boolean\", description: \"Verbatim message text\", required: false, default: false },\n },\n run: async ({ args, rawArgs }) => {\n try {\n // No id reads the caller's own chat, so its earlier words survive a context summary.\n const chatId = args.id ?? getEnv().BAKER_CHAT_ID;\n if (!chatId) {\n throw new Error(\"Pass the Session id: `baker chats transcript <id>` (find it with `baker chats list`).\");\n }\n const body: Record<string, unknown> = { chatId };\n const search = transcriptSearch(rawArgs, args.search);\n if (search !== undefined) body.search = search;\n if (args.role) {\n if (!(TRANSCRIPT_ROLES as readonly string[]).includes(args.role)) {\n throw new Error(`--role must be one of: ${TRANSCRIPT_ROLES.join(\"|\")}`);\n }\n body.role = args.role;\n }\n if (args.turns) {\n body.turns = true;\n }\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 1000);\n if (limit !== undefined) {\n body.limit = limit;\n }\n if (args.full) {\n body.full = true;\n }\n const response = await apiPost<ChatsTranscriptResponse>(\"/api/chats/transcript\", body);\n const hints: string[] = [];\n if (response.data.truncated) {\n hints.push(\"Older messages were dropped to fit --limit. Raise --limit, or narrow with --search.\");\n }\n if (response.data.answersNotKept) {\n hints.push(\n \"A question card says `Answer no longer kept`: only the last 10 answers are kept, so no --limit brings it back. Read the user's reply from the messages after it.\",\n );\n }\n if (search !== undefined && response.data.entries.length === 0) {\n hints.push(\n \"No message holds that text. The whole conversation was searched — try a shorter or differently written piece of it.\",\n );\n }\n writeJson({ ...response, meta: { count: response.data.entries.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.diff\",\n description:\n \"See the real file-level changes a Session made (landings, creatives, brand, flows, knowledge). Published Sessions read from git; for an in-progress (unpublished) Session pass --live to read its changes straight from its running workspace. Without --live, an unpublished Session returns available:false — use `baker chats view` for the staged summary. Compact lists changed files with +/- counts; add --full for the actual diff text. Read-only.\",\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id or one of its thread ids (a thread id reads its whole Session)\",\n required: true,\n },\n surface: {\n type: \"string\",\n description: \"Filter to one surface: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description: \"Include the unified-diff patch text per file\",\n required: false,\n default: false,\n },\n live: {\n type: \"boolean\",\n description:\n \"For an in-progress Session, read its changes from the live workspace (slower; resumes the paused Runtime). Ignored for published Sessions.\",\n required: false,\n default: false,\n },\n },\n});\n\nconst diffCommand = defineCommand({\n meta: { name: \"diff\", description: \"See a published Session's real file-level changes.\" },\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id or one of its thread ids (a thread id reads its whole Session)\",\n required: true,\n },\n surface: {\n type: \"string\",\n description: \"Filter: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Include the diff patch text per file\", required: false, default: false },\n live: {\n type: \"boolean\",\n description: \"Read an in-progress Session's changes from its live workspace (slower)\",\n required: false,\n default: false,\n },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = { chatId: args.id };\n if (args.surface) {\n if (!(REPO_SURFACES as readonly string[]).includes(args.surface)) {\n throw new Error(`--surface must be one of: ${REPO_SURFACES.join(\"|\")}`);\n }\n body.surface = args.surface;\n }\n if (args.full) {\n body.full = true;\n }\n if (args.live) {\n body.live = true;\n }\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", body);\n writeJson({\n ...response,\n meta: { count: response.data.files.length },\n ...(!response.data.available && response.data.reason ? { hints: [response.data.reason] } : {}),\n ...(response.data.available && !args.full && response.data.files.length > 0\n ? { hints: [\"Add --full to read the actual diff text for each file.\"] }\n : {}),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst IMPORT_DESCRIPTION = `Bring another chat's unpublished work into this chat, in one call — and take it out of that chat, so publishing both can never apply anything twice.\n\nStart here when the user wants another chat's work brought into this one (\"bring over\", \"merge the two\nchats\", \"its publish keeps failing — carry it over\", \"recover what the discarded chat did\"):\n baker chats import --from-chat <chat-id> # everything: files and staged changes\n baker chats import --from-chat <chat-id> --only meta-ads,tasks # only these staged surfaces, no files\n baker chats import --from-chat <chat-id> --failed # a PUBLISHED chat: the ad changes its publish could not apply\n baker chats import --from-chat $BAKER_CHAT_ID --failed # this chat's own last Publish: its failed ad changes, to fix and publish again\n\nThe other chat may be open, its publish may have failed, or it may be discarded. Its file changes (Knowledge,\npages, Forms, pictures) are applied in this workspace exactly as it made them, and every staged surface moves\nexactly as staged: ads (Google, Meta, LinkedIn, X, ChatGPT), Shopify, Tag Manager, Google Analytics, tracking\ntags, Tasks, scheduled agents, ActiveCampaign, site settings, ad goals, the funnel, conversions, conversion\nsends, event sources and lead routes. When both chats change the same file or the same thing, nothing moves\nand the refusal names each clash — ask the user which version wins. A chat whose publish failed is then closed\nto publishing, so the same work never goes live twice.\n--failed takes the Google Ads, Meta, LinkedIn, X and ChatGPT changes a published chat's publish could not\napply (failed, or skipped because what they needed failed), stages them here as they were — naming what did\napply by its real id — and takes them out of that chat, so its Retry cannot apply them twice. A chat goes on\nafter its Publish: naming this chat itself takes what its own last Publish could not apply into what it stages now.\nA change moved here cannot go back: to leave one behind, ask the user first and use --only (Google Ads alone\ncan pick single changes: \\`baker ads google draft import --from-chat <id> --refs|--exclude\\`).\nFind chat ids with \\`baker chats list\\`; see what one staged with \\`baker chats view <id>\\`.`;\n\nregisterSchema({\n command: \"chats.import\",\n description: IMPORT_DESCRIPTION,\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat — open, publish failed or discarded; published, or this chat itself, with --failed\",\n required: true,\n },\n only: {\n type: \"string\",\n description: `Comma-separated staged surfaces to move, leaving its files there (default: everything): ${CHAT_IMPORT_SURFACES.join(\", \")}`,\n required: false,\n },\n failed: {\n type: \"boolean\",\n description: \"The other chat is published: stage here the ad changes its publish could not apply\",\n required: false,\n default: false,\n },\n },\n});\n\n/** What became of the other chat's files, and of that chat itself. */\nfunction filesHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined): string[] {\n const hints: string[] = [];\n if (files?.kind === \"patch\") {\n hints.push(\n `Its ${files.paths.length} changed file(s) are now in this workspace, exactly as that chat left them: ${files.paths.join(\", \")}. Check them in the preview; never rebuild them by hand.`,\n );\n }\n if (files?.kind === \"stayed\") {\n hints.push(\n `Its file changes (Knowledge, pages, Forms…) did not come along: ${files.reason} Tell the user what is missing; do not rebuild it from memory.`,\n );\n } else if (data.filesStayed > 0) {\n hints.push(\n `Chat ${data.fromChatId} also changed ${data.filesStayed} file(s) (Knowledge, pages, Forms…) that did not come along. Run the import without --only to bring them.`,\n );\n }\n if (data.carried) {\n hints.push(\n \"That chat holds nothing of its own any more and can no longer be published, so the same work never goes live twice. This chat publishes all of it.\",\n );\n } else if (files?.kind === \"patch\") {\n hints.push(\n \"That chat still has its own copy of these files: tell the user to publish only this chat, or the same file changes would go live twice.\",\n );\n }\n return hints;\n}\n\n/** What the agent needs after a move: what stayed behind in the other chat, and what to check next. */\nfunction importHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined, failed: boolean): string[] {\n const hints: string[] = [];\n const moved = data.surfaces.reduce((sum, surface) => sum + surface.moved, 0);\n const stayed = data.surfaces.filter((surface) => surface.left);\n if (moved === 0 && stayed.length === 0 && files?.kind !== \"patch\") {\n hints.push(\n failed\n ? `Every ad change of chat ${data.fromChatId} applied, so there was nothing to bring over.`\n : `Chat ${data.fromChatId} had no unpublished changes, so nothing moved.`,\n );\n }\n for (const surface of stayed) {\n hints.push(\n `${surface.left?.count ? `${surface.left.count} ` : \"\"}${surface.surface} change(s) stayed in chat ${data.fromChatId}: ${surface.left?.reason}`,\n );\n }\n hints.push(...filesHints(data, files));\n if (moved > 0) {\n hints.push(\n \"The moved changes are this chat's now and publish with it; the other chat no longer holds them. Review them with each surface's `draft list` (and `baker ads google draft validate` when Google Ads changes moved).\",\n );\n }\n if (moved > 0 && stayed.length === 0 && !data.carried) {\n hints.push(\n \"Nothing staged stayed in the other chat. Never tell the user to discard it for this: its other work is still there.\",\n );\n }\n if (failed && moved > 0) {\n hints.push(\n \"They failed once for a reason: read each one's error with `baker chats view <id>` (publish) and amend it here before the user publishes, or it can fail the same way.\",\n );\n }\n return hints;\n}\n\ntype OnlyFlag = { surfaces?: ChatImportSurface[] } | { refusal: string };\n\n/** The surfaces `--only` names; absent means every surface, and a list naming none is refused. */\nfunction onlyFlag(value: unknown): OnlyFlag {\n if (typeof value !== \"string\") return {};\n const named = value\n .split(\",\")\n .map((surface) => surface.trim())\n .filter((surface) => surface.length > 0);\n if (named.length === 0) return { refusal: \"--only names no surface\" };\n const unknown = named.filter((surface) => !(CHAT_IMPORT_SURFACES as readonly string[]).includes(surface));\n if (unknown.length > 0) return { refusal: `--only names ${unknown.join(\", \")}, which is not a surface` };\n return { surfaces: named as ChatImportSurface[] };\n}\n\nfunction refuse(message: string, fix: string): never {\n writeJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message, fix } });\n process.exit(1);\n}\n\n/** The other chat's files, applied here before its staged changes move — or why they stay there, or clash. */\nasync function carryFiles(fromChatId: string): Promise<SourceFiles | { kind: \"clash\"; paths: string[] }> {\n const files = await readSourceFiles(fromChatId);\n if (files.kind !== \"patch\") return files;\n const clashes = patchRefusal(files.patch);\n if (clashes) return { kind: \"clash\", paths: clashes };\n applyPatch(files.patch);\n return files;\n}\n\nconst importCommand = defineCommand({\n meta: { name: \"import\", description: IMPORT_DESCRIPTION },\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat whose work comes here — or, with --failed, this chat's own last Publish\",\n },\n only: { type: \"string\", description: \"Comma-separated staged surfaces to move, without files (default: all)\" },\n failed: {\n type: \"boolean\",\n description: \"From a published chat (this one included): the ad changes its publish could not apply\",\n default: false,\n },\n },\n run: async ({ args }) => {\n const fromChatId = typeof args[\"from-chat\"] === \"string\" ? args[\"from-chat\"].trim() : \"\";\n if (!fromChatId) {\n refuse(\n \"--from-chat is required\",\n \"Name the other chat: baker chats import --from-chat <chat-id> (ids from `baker chats list`).\",\n );\n }\n const only = onlyFlag(args.only);\n if (\"refusal\" in only) {\n // A list naming nothing must never widen to \"every surface\": the move takes them out of the other chat.\n refuse(\n only.refusal,\n `Name surfaces from: ${CHAT_IMPORT_SURFACES.join(\", \")} — or leave --only off to move them all.`,\n );\n }\n if (args.failed && only.surfaces) {\n refuse(\"--failed takes every ad platform's failed changes\", \"Leave --only off with --failed.\");\n }\n const chatId = requireChatId();\n let files: Awaited<ReturnType<typeof carryFiles>> | undefined;\n try {\n files = args.failed || only.surfaces ? undefined : await carryFiles(fromChatId);\n } catch (err) {\n failApi(err);\n }\n if (files?.kind === \"clash\") {\n refuse(\n `Nothing moved: these files changed in both chats, differently: ${files.paths.join(\", \")}.`,\n \"Ask the user which version should win. To bring only the other chat's staged changes and leave its files there, run the import again with --only and the surfaces it staged.\",\n );\n }\n try {\n const response = await apiPost<ChatsImportResponse>(\"/api/chats/import\", {\n chatId,\n fromChatId,\n ...(only.surfaces ? { surfaces: only.surfaces } : {}),\n ...(files?.kind === \"patch\" ? { filesCarried: true } : {}),\n ...(args.failed ? { failed: true } : {}),\n });\n writeJson({ ...response, hints: importHints(response.data, files, Boolean(args.failed)) });\n } catch (err) {\n // All or nothing: the files go back out when the staged changes could not come with them.\n if (files?.kind === \"patch\") revertPatch(files.patch);\n failApi(err);\n }\n },\n});\n\nexport const chatsCommand = defineCommand({\n meta: {\n name: \"chats\",\n description: `Inspect other Sessions on this account: list them, view what they produced, read their conversation, and see their real file changes — so you can reuse past work for a new goal. \\`import --from-chat <id>\\` moves another open Session's staged changes into this one.\nFull guide: __tooling__/docs/tools/baker/chats.md`,\n },\n subCommands: {\n list: listCommand,\n view: viewCommand,\n transcript: transcriptCommand,\n diff: diffCommand,\n import: importCommand,\n },\n});\n","/**\n * The file half of `baker chats import`: the other chat's changes to its files (Knowledge, pages,\n * Forms, pictures…), read from its workspace as one patch (`chats diff --live`'s `gitPatch`) and\n * applied here with `git apply` — exactly, or not at all.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport type { ChatsDiffResponse } from \"@baker/api\";\nimport { apiPost } from \"../../client.ts\";\n\nexport type SourceFiles =\n | { kind: \"none\" }\n | { kind: \"patch\"; patch: string; paths: string[] }\n | { kind: \"stayed\"; reason: string };\n\n/** What the other chat changed in its files, as something this workspace can apply — or why not. */\nexport async function readSourceFiles(fromChatId: string): Promise<SourceFiles> {\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", {\n chatId: fromChatId,\n live: true,\n gitPatch: true,\n });\n const { data } = response;\n if (!data.available) {\n return { kind: \"stayed\", reason: data.reason ?? \"its files could not be read.\" };\n }\n if (data.source === \"published\") {\n // Its changes reached the live site already, so there is nothing of them to carry.\n return { kind: \"none\" };\n }\n if (data.files.length === 0) {\n return { kind: \"none\" };\n }\n if (data.gitPatch === undefined) {\n return {\n kind: \"stayed\",\n reason: \"its file changes are too large to bring over in one piece, so none of them came along.\",\n };\n }\n return { kind: \"patch\", patch: data.gitPatch, paths: data.files.map((file) => file.path) };\n}\n\nfunction repoRoot(): string {\n return execFileSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], { encoding: \"utf8\" }).trim();\n}\n\n/** `git apply` of the patch at this workspace's root; `check` changes nothing, `reverse` takes it back out. */\nfunction gitApply(patch: string, mode: \"check\" | \"apply\" | \"reverse\"): void {\n const flags = mode === \"check\" ? [\"--check\"] : mode === \"reverse\" ? [\"--reverse\"] : [];\n execFileSync(\"git\", [\"apply\", \"--whitespace=nowarn\", ...flags, \"-\"], {\n cwd: repoRoot(),\n input: patch,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\n/** The files `git apply --check` named as not applying here, or the whole message when it named none. */\nexport function clashingFiles(stderr: string): string[] {\n const named = [...stderr.matchAll(/^error: ([^:\\n]+): /gm)]\n .map((match) => match[1])\n .filter((path): path is string => path !== undefined && path !== \"patch failed\");\n return named.length > 0 ? [...new Set(named)] : [stderr.trim()];\n}\n\n/** Why the patch cannot apply here — the files this chat also changed — or undefined when it applies cleanly. */\nexport function patchRefusal(patch: string): string[] | undefined {\n try {\n gitApply(patch, \"check\");\n return undefined;\n } catch (error) {\n const stderr = (error as { stderr?: Buffer | string }).stderr;\n return clashingFiles(stderr === undefined ? String(error) : String(stderr));\n }\n}\n\nexport function applyPatch(patch: string): void {\n gitApply(patch, \"apply\");\n}\n\nexport function revertPatch(patch: string): void {\n gitApply(patch, \"reverse\");\n}\n","import type { ChatPublishSummary } from \"@baker/api/chats\";\n\n/**\n * What a reader must not conclude from a completed Session: that it published\n * everything it staged (better than one published draft in three did not), or\n * that every change it sent is now what the platform holds.\n */\nexport function publishHints(publish: ChatPublishSummary): string[] {\n const hints: string[] = [];\n // Not `complete`: a change a person chose not to send leaves the publish complete, and still never went live.\n const failed = publish.failedTotal;\n if (failed > 0) {\n hints.push(\n `This Session's publish left ${failed} change${failed === 1 ? \"\" : \"s\"} behind — see \\`publish.surfaces\\` for why each did not apply. Do not report those changes as live.`,\n );\n }\n const unconfirmed = publish.unconfirmedTotal ?? 0;\n if (unconfirmed > 0) {\n hints.push(\n `${unconfirmed} change${unconfirmed === 1 ? \"\" : \"s\"} went through but could not be confirmed when read back from the platform — \\`publish.surfaces[].unconfirmedChanges\\` says what it shows instead. Check before reporting them as done.`,\n );\n }\n return hints;\n}\n\n/**\n * A Session still publishing is not live yet, and nothing in this chat runs\n * once it is: work that has to wait for it is a Scheduled agent (BAKER-1743).\n */\nexport function stillPublishingHints(status: string): string[] {\n if (status !== \"publishing\") return [];\n return [\n \"This Session is still publishing: its changes are not live yet. Work that has to wait for it (a check on the live page, a test lead) is a Scheduled agent staged now with `baker scheduled-agents create --run-at <time>`, whose brief first checks this Session went live. It exists only once your own chat is published: a page trigger staged now misses this Session's publish, and a `--run-at` that has passed by then is created switched off, so leave hours of headroom, not minutes, and tell the user it runs only once they publish this chat. Never ask the user to come back and tell you when it is done.\",\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAS,qBAAqB;;;ACX9B,SAAS,oBAAoB;AAU7B,eAAsB,gBAAgB,YAA0C;AAC9E,QAAM,WAAW,MAAM,QAA2B,mBAAmB;AAAA,IACnE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAU;AAAA,EACZ,CAAC;AACD,QAAM,EAAE,KAAK,IAAI;AACjB,MAAI,CAAC,KAAK,WAAW;AACnB,WAAO,EAAE,MAAM,UAAU,QAAQ,KAAK,UAAU,+BAA+B;AAAA,EACjF;AACA,MAAI,KAAK,WAAW,aAAa;AAE/B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,MAAM,WAAW,GAAG;AAC3B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,aAAa,QAAW;AAC/B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ;AAAA,IACV;AAAA,EACF;AACA,SAAO,EAAE,MAAM,SAAS,OAAO,KAAK,UAAU,OAAO,KAAK,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE;AAC3F;AAEA,SAAS,WAAmB;AAC1B,SAAO,aAAa,OAAO,CAAC,aAAa,iBAAiB,GAAG,EAAE,UAAU,OAAO,CAAC,EAAE,KAAK;AAC1F;AAGA,SAAS,SAAS,OAAe,MAA2C;AAC1E,QAAM,QAAQ,SAAS,UAAU,CAAC,SAAS,IAAI,SAAS,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YAAY,SAAS,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,EAAE,CAAC;AAAA,IAC3F,SAAS,KAAK;AAEZ,UAAI,OAAO,SAAS,QAAS,aAAY,MAAM,KAAK;AACpD,cAAQ,GAAG;AAAA,IACb;AAAA,EACF;AACF,CAAC;AAEM,IAAM,eAAe,cAAc;AAAA,EACxC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA,EAEf;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,EACV;AACF,CAAC;","names":[]}
@@ -5,8 +5,8 @@ import {
5
5
  checkLandings,
6
6
  checkReports,
7
7
  checkSurface
8
- } from "./chunk-ESGANKHR.js";
9
- import "./chunk-OLIEY4WM.js";
8
+ } from "./chunk-XJE4JH7C.js";
9
+ import "./chunk-JROQOOUR.js";
10
10
  import "./chunk-AQFSRSJ4.js";
11
11
  import "./chunk-DD44EMGP.js";
12
12
  import "./chunk-HJI3W6HQ.js";
@@ -52,4 +52,4 @@ export {
52
52
  checkReports,
53
53
  checkSurface
54
54
  };
55
- //# sourceMappingURL=check-3B4HE6HI.js.map
55
+ //# sourceMappingURL=check-YRRQ5ZEZ.js.map
@@ -65,7 +65,13 @@ async function readCreativeSpecs(root) {
65
65
  );
66
66
  return specs.filter((s) => s !== null);
67
67
  }
68
- function rulesHints(active, waived) {
68
+ var PROMPT_OF = {
69
+ creatives: "ad's",
70
+ landings: "landing's",
71
+ documents: "document's",
72
+ reports: "report's"
73
+ };
74
+ function rulesHints(active, waived, longest) {
69
75
  const hints = [];
70
76
  for (const rule of active) {
71
77
  const times = waived.get(rule.id) ?? 0;
@@ -75,9 +81,9 @@ function rulesHints(active, waived) {
75
81
  );
76
82
  }
77
83
  }
78
- if (active.length > MANY_RULES) {
84
+ if (longest.count > MANY_RULES) {
79
85
  hints.push(
80
- `${active.length} active rules: every prompt carries them all. Ask the person whether some can be retired or merged.`
86
+ `${longest.count} active rules: every ${PROMPT_OF[longest.output]} prompt carries them all. Ask the person whether some can be retired or merged.`
81
87
  );
82
88
  }
83
89
  return hints;
@@ -90,4 +96,4 @@ export {
90
96
  readCreativeSpecs,
91
97
  rulesHints
92
98
  };
93
- //# sourceMappingURL=chunk-OLIEY4WM.js.map
99
+ //# sourceMappingURL=chunk-JROQOOUR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/rules/view.ts"],"sourcesContent":["/**\n * The company's rules as the agent reads them in `baker rules list`: what each is for (creatives, landings, documents, reports or all), each one's id, strength and words, the person's own words when\n * they taught it, and where it came from; and which ones ads keep waiving. Pure, but for the read\n * of the ads' waivers.\n */\nimport { readdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { CreativeRule } from \"../../engine/creative-rules/schema.ts\";\n\nexport const SURFACES = [\"creatives\", \"landings\", \"documents\", \"reports\"] as const;\nexport type Surface = (typeof SURFACES)[number];\n\n/** What `--for` names on the commands that read rules or pieces: one output (`ads` is creatives' old name), {} when left out, null for anything else. Pure. */\nexport function readSurface(value: unknown): { surface?: Surface } | null {\n if (value === undefined) return {};\n const surface = SURFACES.find((s) => s === (value === \"ads\" ? \"creatives\" : value));\n return surface ? { surface } : null;\n}\n\n/** A rule cut to this in the compact view: the whole is behind `--full`. */\nconst RULE_CHARS = 200;\nconst QUOTE_CHARS = 160;\n/** Waived this often, a rule may no longer hold. */\nconst RETIRE_AFTER = 3;\n/** Past this many active rules in one prompt, it carries a long list: worth a look. */\nconst MANY_RULES = 40;\n\nconst cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);\n\n/** Where a rule came from, in a few words. */\nfunction fromOf(rule: CreativeRule): string {\n if (rule.origin === \"declared\") return \"BRAND.md\";\n const when = rule.source.date ? ` ${rule.source.date}` : \"\";\n const where = rule.source.slug ? ` on ${rule.source.slug}` : \"\";\n return `taught${when}${where}`;\n}\n\nexport type RuleView = {\n id: string;\n strength: CreativeRule[\"strength\"];\n /** landings, documents, reports or all; absent, the rule is for creatives. */\n for?: CreativeRule[\"for\"];\n applies: CreativeRule[\"applies\"];\n rule: string;\n their_words?: string;\n from: string;\n /** The words it bans in an ad's words, and the phrases that may still hold them. */\n bans?: string[];\n except?: string[];\n /** Words every ad must say. */\n requires?: string[];\n /** Only real people may appear. */\n people?: \"real\";\n scope?: CreativeRule[\"scope\"];\n status?: \"retired\";\n retired_by?: string;\n};\n\n/** What code checks of a rule, as the agent reads it. Pure. */\nfunction checkView(check: CreativeRule[\"check\"]): Pick<RuleView, \"bans\" | \"except\" | \"requires\" | \"people\"> {\n return {\n ...(check?.forbid ? { bans: check.forbid } : {}),\n ...(check?.allow ? { except: check.allow } : {}),\n ...(check?.require ? { requires: check.require } : {}),\n ...(check?.people ? { people: check.people } : {}),\n };\n}\n\n/** Each rule as the agent reads it. Pure. */\nexport function rulesView(rules: readonly CreativeRule[], opts: { full?: boolean } = {}): RuleView[] {\n const max = opts.full ? Number.POSITIVE_INFINITY : RULE_CHARS;\n const quoteMax = opts.full ? Number.POSITIVE_INFINITY : QUOTE_CHARS;\n return rules.map((r) => ({\n id: r.id,\n strength: r.strength,\n ...(r.for ? { for: r.for } : {}),\n applies: r.applies,\n rule: cut(r.text, max),\n ...(r.source.quote ? { their_words: cut(r.source.quote, quoteMax) } : {}),\n from: fromOf(r),\n ...checkView(r.check),\n ...(Object.keys(r.scope).length > 0 ? { scope: r.scope } : {}),\n ...(r.status === \"retired\" ? { status: \"retired\" as const } : {}),\n ...(r.retiredBy ? { retired_by: r.retiredBy } : {}),\n }));\n}\n\n/** How many ads waive each rule (`waive: [{rule, why}]` in their prompt.json). Pure. */\nexport function waiverCounts(specs: readonly unknown[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const spec of specs) {\n const waive = (spec as { waive?: unknown } | null)?.waive;\n if (!Array.isArray(waive)) continue;\n for (const entry of waive) {\n const id = (entry as { rule?: unknown } | null)?.rule;\n if (typeof id === \"string\" && id) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n }\n return counts;\n}\n\n/** Every creative's prompt.json, parsed; one that cannot be read is left out. */\nexport async function readCreativeSpecs(root: string): Promise<unknown[]> {\n const dir = path.join(root, \"src\", \"creatives\");\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n const specs = await Promise.all(\n entries\n .filter((e) => e.isDirectory() && !e.name.startsWith(\"_\"))\n .map((e) =>\n readFile(path.join(dir, e.name, \"prompt.json\"), \"utf8\")\n .then((raw): unknown => JSON.parse(raw))\n .catch(() => null),\n ),\n );\n return specs.filter((s) => s !== null);\n}\n\n/** What one prompt of each output is called in the count hint. */\nconst PROMPT_OF: Record<Surface, string> = {\n creatives: \"ad's\",\n landings: \"landing's\",\n documents: \"document's\",\n reports: \"report's\",\n};\n\n/**\n * What the rules say to do next: retire one ads keep waiving, look at a list grown long. `longest` is the\n * output whose one prompt carries the most active rules, and how many. Pure.\n */\nexport function rulesHints(\n active: readonly CreativeRule[],\n waived: ReadonlyMap<string, number>,\n longest: { output: Surface; count: number },\n): string[] {\n const hints: string[] = [];\n for (const rule of active) {\n const times = waived.get(rule.id) ?? 0;\n if (times >= RETIRE_AFTER) {\n hints.push(\n `${rule.id} was waived by ${times} ads: ask the person whether it still holds, and \\`baker rules retire ${rule.id}\\` if not.`,\n );\n }\n }\n if (longest.count > MANY_RULES) {\n hints.push(\n `${longest.count} active rules: every ${PROMPT_OF[longest.output]} prompt carries them all. Ask the person whether some can be retired or merged.`,\n );\n }\n return hints;\n}\n"],"mappings":";AAKA,SAAS,SAAS,gBAAgB;AAClC,OAAO,UAAU;AAGV,IAAM,WAAW,CAAC,aAAa,YAAY,aAAa,SAAS;AAIjE,SAAS,YAAY,OAA8C;AACxE,MAAI,UAAU,OAAW,QAAO,CAAC;AACjC,QAAM,UAAU,SAAS,KAAK,CAAC,MAAM,OAAO,UAAU,QAAQ,cAAc,MAAM;AAClF,SAAO,UAAU,EAAE,Q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AW;AAAA,EACX,SAAS;AACX;AAMO,SAAS,WACd,QACA,QACA,SACU;AACV,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,QAAQ;AACzB,UAAM,QAAQ,OAAO,IAAI,KAAK,EAAE,KAAK;AACrC,QAAI,SAAS,cAAc;AACzB,YAAM;AAAA,QACJ,GAAG,KAAK,EAAE,kBAAkB,KAAK,yEAAyE,KAAK,EAAE;AAAA,MACnH;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,QAAQ,YAAY;AAC9B,UAAM;AAAA,MACJ,GAAG,QAAQ,KAAK,wBAAwB,UAAU,QAAQ,MAAM,CAAC;AAAA,IACnE;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  readSurface
3
- } from "./chunk-OLIEY4WM.js";
3
+ } from "./chunk-JROQOOUR.js";
4
4
  import {
5
5
  readAdWords,
6
6
  ruleRefusal
@@ -502,4 +502,4 @@ export {
502
502
  checkSurface,
503
503
  checkCommand
504
504
  };
505
- //# sourceMappingURL=chunk-ESGANKHR.js.map
505
+ //# sourceMappingURL=chunk-XJE4JH7C.js.map
package/dist/cli.js CHANGED
@@ -625,7 +625,7 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
625
625
  capabilities: () => import("./capabilities-AV7CIS6N.js").then((m) => m.capabilitiesCommand),
626
626
  actions: () => import("./actions-DKJPTQWC.js").then((m) => m.actionsCommand),
627
627
  "scheduled-agents": () => import("./scheduled-agents-VT7SYKOC.js").then((m) => m.scheduledAgentsCommand),
628
- ads: () => import("./ads-WMP6S4FN.js").then((m) => m.adsCommand),
628
+ ads: () => import("./ads-MTUBTBJV.js").then((m) => m.adsCommand),
629
629
  brand: () => import("./brand-CMKT6D25.js").then((m) => m.brandCommand),
630
630
  analytics: () => import("./analytics-7NPD2T2W.js").then((m) => m.analyticsCommand),
631
631
  experiment: () => import("./experiment-FMMX57VR.js").then((m) => m.experimentCommand),
@@ -636,7 +636,7 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
636
636
  data: () => import("./data-CIPG3EOP.js").then((m) => m.dataCommand),
637
637
  knowledge: () => import("./knowledge-S6QL4LX5.js").then((m) => m.knowledgeCommand),
638
638
  creatives: () => import("./creatives-U4VUGNQJ.js").then((m) => m.creativesCommand),
639
- rules: () => import("./rules-M5SXLUDN.js").then((m) => m.rulesCommand),
639
+ rules: () => import("./rules-PCGXXGIK.js").then((m) => m.rulesCommand),
640
640
  files: () => import("./files-SPBLE3DV.js").then((m) => m.filesCommand),
641
641
  flows: () => import("./flows-HMIPOFMC.js").then((m) => m.flowsCommand),
642
642
  funnel: () => import("./funnel-UUGNLCXG.js").then((m) => m.funnelCommand),
@@ -649,7 +649,7 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
649
649
  canvas: () => import("./canvas-JM42LLQH.js").then((m) => m.canvasCommand),
650
650
  tags: () => import("./tags-YJX5JCRT.js").then((m) => m.tagsCommand),
651
651
  "tag-manager": () => import("./tag-manager-QO6VW57E.js").then((m) => m.tagManagerCommand),
652
- chats: () => import("./chats-EEQXHX4O.js").then((m) => m.chatsCommand),
652
+ chats: () => import("./chats-GLAU5X6G.js").then((m) => m.chatsCommand),
653
653
  history: () => import("./history-7CJ2WHU5.js").then((m) => m.historyCommand),
654
654
  credentials: () => import("./credentials-U4SKWYKG.js").then((m) => m.credentialsCommand),
655
655
  hubspot: () => import("./hubspot-TW6FWFHP.js").then((m) => m.hubspotCommand),
@@ -119,7 +119,7 @@ Full guide: __tooling__/docs/tools/baker/ads-meta.md`
119
119
  creatives: () => import("./creatives-LW6UNC2G.js").then((m) => m.creativesCommand),
120
120
  audiences: () => import("./audiences-JVKPNJ2W.js").then((m) => m.audiencesCommand),
121
121
  "custom-conversions": () => import("./custom-conversions-WBP2QMW3.js").then((m) => m.customConversionsCommand),
122
- pixels: () => import("./pixels-I7S5N76B.js").then((m) => m.pixelsCommand),
122
+ pixels: () => import("./pixels-VFHS3QIF.js").then((m) => m.pixelsCommand),
123
123
  activities: () => import("./activities-6H2SSVS6.js").then((m) => m.activitiesCommand),
124
124
  insights: () => import("./insights-PBJODKMY.js").then((m) => m.insightsCommand),
125
125
  preview: () => import("./preview-5CK5INGO.js").then((m) => m.previewCommand),
@@ -149,4 +149,4 @@ Full guide: __tooling__/docs/tools/baker/ads-meta.md`
149
149
  export {
150
150
  metaCommand
151
151
  };
152
- //# sourceMappingURL=meta-BJDKNWJA.js.map
152
+ //# sourceMappingURL=meta-GOPN63QP.js.map
@@ -34,13 +34,13 @@ var pixelsCommand = defineCommand({
34
34
 
35
35
  The list prints each pixel's id, name, last_fired_time and owner (unavailable: true when Meta marks it so); --full adds the install code and the setup fields.
36
36
 
37
- --stats prints one row per day per event (date, weekday, event, count) by default, in the ad account's time zone; --by hour or --by total change the grain, --full returns Meta's raw hourly buckets.
37
+ --stats prints each event's total over the window (event, count, first_seen, last_seen) by default, the 25 most received (--by total prints every one); --event narrows it to one row per day per event (date, weekday, event, count), in the ad account's time zone, and --by day|hour|total sets the grain outright. --full returns Meta's raw hourly buckets.
38
38
 
39
39
  Examples:
40
40
  baker ads meta pixels --account-id act_123
41
- baker ads meta pixels --pixel-id 9876 --stats --days 7 # per day per event
42
- baker ads meta pixels --pixel-id 9876 --stats --days 7 --event Lead,Purchase # only those events
43
- baker ads meta pixels --pixel-id 9876 --stats --days 30 --by total # each event's count, first and last seen`
41
+ baker ads meta pixels --pixel-id 9876 --stats --days 7 # each event's count, first and last seen
42
+ baker ads meta pixels --pixel-id 9876 --stats --days 7 --event Lead,Purchase # those events, per day
43
+ baker ads meta pixels --pixel-id 9876 --stats --days 7 --by day # every event, per day`
44
44
  },
45
45
  args: {
46
46
  "account-id": LISTING_ACCOUNT_ARG,
@@ -54,7 +54,7 @@ Examples:
54
54
  days: { type: "string", description: "Lookback days for --stats (default 7)" },
55
55
  by: {
56
56
  type: "string",
57
- description: "--stats grain: day (default; one row per day per value, with its weekday), hour (one row per hour per value), total (one row per value with first_seen/last_seen)"
57
+ description: "--stats grain: total (default without --event; one row per value with first_seen/last_seen), day (default with --event; one row per day per value, with its weekday), hour (one row per hour per value)"
58
58
  },
59
59
  event: {
60
60
  type: "string",
@@ -95,7 +95,8 @@ async function runStats(args) {
95
95
  "end-time": todayIso()
96
96
  };
97
97
  if (args["no-cache"]) params["skip-cache"] = "true";
98
- const by = args.by ?? "day";
98
+ const events = typeof args.event === "string" ? args.event.split(",").map((e) => e.trim()).filter(Boolean) : [];
99
+ const by = args.by ?? (events.length > 0 ? "day" : "total");
99
100
  if (!isStatsGrain(by)) {
100
101
  writeAdsJson({
101
102
  ok: false,
@@ -108,11 +109,25 @@ async function runStats(args) {
108
109
  emit(buckets, args);
109
110
  return;
110
111
  }
111
- const events = typeof args.event === "string" ? args.event.split(",").map((e) => e.trim()).filter(Boolean) : [];
112
112
  const window = { start: `${params["start-time"]}T00:00:00Z`, end: `${params["end-time"]}T00:00:00Z` };
113
- const { rows, hints } = rollUpPixelStats(buckets, { aggregation: params.aggregation ?? "event", by, events, window });
113
+ const aggregation = params.aggregation ?? "event";
114
+ const { rows, hints } = rollUpPixelStats(buckets, { aggregation, by, events, window });
115
+ if (args.by === void 0 && by === "total" && rows.length > 0) {
116
+ const kept = rows.slice(0, DEFAULT_TOTALS_CAP);
117
+ hints.push(defaultTotalsHint(kept.length, rows.length, aggregation));
118
+ writeAdsOutput(kept, csvOrJson(args), void 0, hints);
119
+ return;
120
+ }
114
121
  writeAdsOutput(rows, csvOrJson(args), void 0, hints);
115
122
  }
123
+ function defaultTotalsHint(kept, total, aggregation) {
124
+ if (kept === total) {
125
+ return "Each value's total over the window. For one row per day, add --event <name> (or --by day).";
126
+ }
127
+ const noun = aggregation === "event" ? "events" : `${aggregation} values`;
128
+ return `Each value's total over the window: the ${kept} most received of ${total} ${noun}. For every one, add --by total; for one per day, --event <name>.`;
129
+ }
130
+ var DEFAULT_TOTALS_CAP = 25;
116
131
  var STATS_GRAINS = ["day", "hour", "total"];
117
132
  function isStatsGrain(value) {
118
133
  return STATS_GRAINS.includes(value);
@@ -241,4 +256,4 @@ export {
241
256
  pixelWarnings,
242
257
  pixelsCommand
243
258
  };
244
- //# sourceMappingURL=pixels-I7S5N76B.js.map
259
+ //# sourceMappingURL=pixels-VFHS3QIF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/ads/meta/pixels.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { DateTime } from \"luxon\";\nimport { NO_CACHE_ARG } from \"../../../cache-flag.ts\";\nimport { apiGet } from \"../../../client.ts\";\nimport { writeAdsJson, writeAdsOutput } from \"../output.ts\";\nimport type { AdsWarning } from \"../types.ts\";\nimport {\n accountsInScope,\n csvOrJson,\n daysAgoIso,\n handleMetaError,\n LISTING_ACCOUNT_ARG,\n readEachAccount,\n todayIso,\n withAccountColumn,\n} from \"./shared.ts\";\n\nexport const pixelsCommand = defineCommand({\n meta: {\n name: \"pixels\",\n description: `List Meta Pixels for an ad account, or count what one pixel received — the firing read, not ad-attributed conversions.\n\nThe list prints each pixel's id, name, last_fired_time and owner (unavailable: true when Meta marks it so); --full adds the install code and the setup fields.\n\n--stats prints each event's total over the window (event, count, first_seen, last_seen) by default, the 25 most received (--by total prints every one); --event narrows it to one row per day per event (date, weekday, event, count), in the ad account's time zone, and --by day|hour|total sets the grain outright. --full returns Meta's raw hourly buckets.\n\nExamples:\n baker ads meta pixels --account-id act_123\n baker ads meta pixels --pixel-id 9876 --stats --days 7 # each event's count, first and last seen\n baker ads meta pixels --pixel-id 9876 --stats --days 7 --event Lead,Purchase # those events, per day\n baker ads meta pixels --pixel-id 9876 --stats --days 7 --by day # every event, per day`,\n },\n args: {\n \"account-id\": LISTING_ACCOUNT_ARG,\n \"pixel-id\": { type: \"string\", description: \"Pixel ID for --stats\" },\n stats: { type: \"boolean\", description: \"Fetch firing stats for the pixel\" },\n aggregation: {\n type: \"string\",\n description: \"stats aggregation: event|browser_type|host|pixel_fire\",\n default: \"event\",\n },\n days: { type: \"string\", description: \"Lookback days for --stats (default 7)\" },\n by: {\n type: \"string\",\n description:\n \"--stats grain: total (default without --event; one row per value with first_seen/last_seen), day (default with --event; one row per day per value, with its weekday), hour (one row per hour per value)\",\n },\n event: {\n type: \"string\",\n description: \"--stats: keep only these values, comma-separated and exact (e.g. --event Lead,Purchase)\",\n },\n full: {\n type: \"boolean\",\n description:\n \"The list: every field, the install code included. --stats: Meta's raw hourly buckets, every value, instead of the rows\",\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 try {\n if (args.stats) {\n await runStats(args);\n return;\n }\n await runList(args);\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nasync function runStats(args: Record<string, unknown>): Promise<void> {\n const pixelId = args[\"pixel-id\"] as string | undefined;\n if (!pixelId) {\n handleMetaError(new Error(\"--pixel-id is required when --stats is set\"));\n }\n const days = args.days ? Number(args.days) : 7;\n if (!Number.isInteger(days) || days <= 0 || days > 90) {\n handleMetaError(new Error(\"--days must be a positive integer ≤ 90\"));\n }\n const params: Record<string, string> = {\n \"pixel-id\": pixelId,\n aggregation: (args.aggregation as string) ?? \"event\",\n \"start-time\": daysAgoIso(days),\n \"end-time\": todayIso(),\n };\n if (args[\"no-cache\"]) params[\"skip-cache\"] = \"true\";\n const events =\n typeof args.event === \"string\"\n ? args.event\n .split(\",\")\n .map((e) => e.trim())\n .filter(Boolean)\n : [];\n // Totals unless --event narrows the read: on a pixel shared with an app, a row per day\n // per event grew with every app event (BAKER-4822), and a truncated per-day read left\n // the reader to sum what survived (BAKER-4782).\n const by = (args.by as string | undefined) ?? (events.length > 0 ? \"day\" : \"total\");\n if (!isStatsGrain(by)) {\n writeAdsJson({\n ok: false,\n error: { code: \"INVALID_ARGS\", message: `--by must be one of ${STATS_GRAINS.join(\", \")}` },\n });\n process.exit(1);\n }\n const buckets = await apiGet<PixelStatBucket[]>(\"/api/ads/meta/pixel-stats\", params);\n if (args.full) {\n emit(buckets as Array<Record<string, unknown>>, args);\n return;\n }\n const window = { start: `${params[\"start-time\"]}T00:00:00Z`, end: `${params[\"end-time\"]}T00:00:00Z` };\n const aggregation = params.aggregation ?? \"event\";\n const { rows, hints } = rollUpPixelStats(buckets, { aggregation, by, events, window });\n if (args.by === undefined && by === \"total\" && rows.length > 0) {\n const kept = rows.slice(0, DEFAULT_TOTALS_CAP);\n hints.push(defaultTotalsHint(kept.length, rows.length, aggregation));\n writeAdsOutput(kept, csvOrJson(args), undefined, hints);\n return;\n }\n writeAdsOutput(rows, csvOrJson(args), undefined, hints);\n}\n\nfunction defaultTotalsHint(kept: number, total: number, aggregation: string): string {\n if (kept === total) {\n return \"Each value's total over the window. For one row per day, add --event <name> (or --by day).\";\n }\n const noun = aggregation === \"event\" ? \"events\" : `${aggregation} values`;\n return `Each value's total over the window: the ${kept} most received of ${total} ${noun}. For every one, add --by total; for one per day, --event <name>.`;\n}\n\n/**\n * Rows the default totals read prints, most received first: a pixel shared with\n * an app sends 100+ events, and the default read stays under 5 KB (BAKER-4822).\n */\nconst DEFAULT_TOTALS_CAP = 25;\n\n/** One time bucket as Meta's `/{pixel}/stats` returns it; `start_time` carries the ad account's offset. */\ninterface PixelStatBucket {\n start_time?: string;\n data?: Array<{ value?: string; count?: number }>;\n}\n\nconst STATS_GRAINS = [\"day\", \"hour\", \"total\"] as const;\ntype StatsGrain = (typeof STATS_GRAINS)[number];\n\nfunction isStatsGrain(value: string): value is StatsGrain {\n return (STATS_GRAINS as readonly string[]).includes(value);\n}\n\ninterface RollUp {\n aggregation: string;\n by: StatsGrain;\n events: string[];\n /** The UTC instants the read asked Meta for. */\n window: { start: string; end: string };\n}\n\n/**\n * Meta answers with one bucket per hour, each a nested list of values, so \"how\n * many Leads a day\" was a script over hundreds of rows at every call site. The\n * day is the one Meta wrote on `start_time` — the ad account's own day.\n */\nfunction rollUpPixelStats(\n buckets: PixelStatBucket[],\n { aggregation, by, events, window }: RollUp,\n): { rows: Array<Record<string, string | number>>; hints: string[] } {\n const { folded, seen } = foldBuckets(buckets, by, new Set(events));\n const rows = [...folded.values()]\n .sort((a, b) => a.key.localeCompare(b.key) || b.count - a.count)\n .map((row): Record<string, string | number> => {\n if (by === \"total\") {\n return { [aggregation]: row.value, count: row.count, first_seen: row.first, last_seen: row.last };\n }\n if (by === \"hour\") return { hour: row.key, [aggregation]: row.value, count: row.count };\n return { date: row.key, weekday: accountWeekday(row.first), [aggregation]: row.value, count: row.count };\n });\n const hints: string[] = [];\n const missing = events.filter((event) => !seen.has(event));\n if (missing.length > 0) {\n const received = [...seen].sort().join(\", \") || \"nothing\";\n hints.push(`No ${missing.join(\", \")} received in this window (names are exact). The pixel received: ${received}.`);\n }\n const partialDays = by === \"day\" && rows.length > 0 ? daysCutByWindow(buckets, window) : [];\n if (partialDays.length > 0) {\n hints.push(\n `${partialDays.join(\" and \")} ${partialDays.length === 1 ? \"is a partial day\" : \"are partial days\"}: the read covers ${window.start} → ${window.end}, so compare only the full days between them.`,\n );\n }\n return { rows, hints };\n}\n\ninterface FoldedRow {\n key: string;\n value: string;\n count: number;\n first: string;\n last: string;\n}\n\nconst ROW_KEY: Record<StatsGrain, (time: string) => string> = {\n day: (time) => accountDay(time),\n hour: (time) => time,\n total: () => \"\",\n};\n\nfunction foldBuckets(\n buckets: PixelStatBucket[],\n by: StatsGrain,\n wanted: Set<string>,\n): { folded: Map<string, FoldedRow>; seen: Set<string> } {\n const entries = buckets.flatMap((bucket) =>\n (bucket.data ?? []).map((entry) => ({\n time: bucket.start_time ?? \"\",\n value: entry.value ?? \"(unnamed)\",\n count: entry.count ?? 0,\n })),\n );\n const folded = new Map<string, FoldedRow>();\n for (const { time, value, count } of entries) {\n if (wanted.size > 0 && !wanted.has(value)) continue;\n const key = ROW_KEY[by](time);\n const id = `${key}\\u0000${value}`;\n const row = folded.get(id) ?? { key, value, count: 0, first: time, last: time };\n row.count += count;\n if (instant(time) < instant(row.first)) row.first = time;\n if (instant(time) > instant(row.last)) row.last = time;\n folded.set(id, row);\n }\n return { folded, seen: new Set(entries.map((entry) => entry.value)) };\n}\n\n/** The account-local days the window starts after or ends before, oldest first. */\nfunction daysCutByWindow(buckets: PixelStatBucket[], window: { start: string; end: string }): string[] {\n const cut = new Set<string>();\n for (const { start_time: time } of buckets) {\n if (time && dayOverhangsWindow(time, window)) cut.add(accountDay(time));\n }\n return [...cut].sort();\n}\n\n/** Whether the account-local day `time` falls on starts before or ends after the window read. */\nfunction dayOverhangsWindow(time: string, window: { start: string; end: string }): boolean {\n const dayStart = bucketTime(time).startOf(\"day\");\n if (!dayStart.isValid) return false;\n return dayStart < DateTime.fromISO(window.start) || dayStart.plus({ days: 1 }) > DateTime.fromISO(window.end);\n}\n\n/** A bucket's `start_time` in the offset Meta wrote on it — the ad account's. */\nfunction bucketTime(time: string): DateTime {\n return DateTime.fromISO(time, { setZone: true });\n}\n\nfunction accountDay(time: string): string {\n return bucketTime(time).toISODate() ?? \"\";\n}\n\n/** Written out so a reader never works the weekday out from the date, and gets it wrong. */\nfunction accountWeekday(time: string): string {\n return bucketTime(time).setLocale(\"en-US\").toFormat(\"ccc\");\n}\n\n/** Compared as instants: across a clock change, the same local hour carries two offsets. */\nfunction instant(time: string): number {\n return bucketTime(time).toMillis();\n}\n\nasync function runList(args: Record<string, unknown>): Promise<void> {\n const accounts = await accountsInScope(args);\n const params: Record<string, string> = {};\n if (args[\"no-cache\"]) params[\"skip-cache\"] = \"true\";\n const restricted = new Set<string>();\n const read = await readEachAccount(accounts, async (accountId) => {\n const { pixels, restrictedFields } = await apiGet<{\n pixels: MetaPixel[];\n restrictedFields: string[];\n }>(\"/api/ads/meta/pixels\", { ...params, \"account-id\": accountId });\n for (const field of restrictedFields) restricted.add(field);\n return pixels;\n });\n const rows = args.full ? read.rows : read.rows.map(compactPixel);\n emit(withAccountColumn(rows, read.accountOf), args, pixelWarnings([...restricted]), read.hints);\n}\n\n/** A pixel as the backend lists it; the setup fields are passed through whole under --full. */\ninterface MetaPixel extends Record<string, unknown> {\n id: string;\n name?: string;\n last_fired_time?: string;\n owner_business?: { id?: string; name?: string };\n is_unavailable?: boolean;\n}\n\n/**\n * What picks a pixel and says whether it fires. The install snippet and the\n * setup fields were most of every listing (BAKER-3691) and sit behind --full.\n */\nfunction compactPixel(pixel: MetaPixel): Record<string, unknown> {\n return {\n id: pixel.id,\n name: pixel.name,\n last_fired_time: pixel.last_fired_time,\n ...(pixel.owner_business?.name ? { owner: pixel.owner_business.name } : {}),\n // Kept on every row: the md and csv tables take their columns from the first one.\n unavailable: pixel.is_unavailable ? true : undefined,\n };\n}\n\n/**\n * A listing Meta trimmed is still a listing — IDs, names and firing times are\n * complete. Say which setup fields are missing and how to get them, so the gap\n * reads as a client-side access grant rather than as a pixel that isn't there.\n */\nexport function pixelWarnings(restrictedFields: string[]): AdsWarning[] {\n if (restrictedFields.length === 0) {\n return [];\n }\n return [\n {\n code: \"PIXEL_FIELDS_RESTRICTED\",\n message:\n `Meta withheld ${restrictedFields.join(\", \")} for these pixels — the connected user holds no role in the Business that owns them. ` +\n \"IDs, names, creation and last-fired times are complete; install code and setup details are not. \" +\n \"To get them, the client assigns the pixel to the connected user in Meta Business settings → Data sources → Datasets.\",\n },\n ];\n}\n\nfunction emit(\n data: Array<Record<string, unknown>>,\n args: Record<string, unknown>,\n warnings: AdsWarning[] = [],\n hints: string[] = [],\n): void {\n const fmt = csvOrJson(args);\n if (fmt !== \"json\") {\n writeAdsOutput(data, fmt, undefined, hints);\n return;\n }\n writeAdsJson({\n ok: true,\n data,\n ...(warnings.length > 0 ? { warnings } : {}),\n ...(hints.length > 0 ? { hints } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AAgBlB,IAAM,gBAAgB,cAAc;AAAA,EACzC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA;AAAA;AAAA;A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AAK,KAAK,IAAI,YAAY;AAC/D,OAAK,kBAAkB,MAAM,KAAK,SAAS,GAAG,MAAM,cAAc,CAAC,GAAG,UAAU,CAAC,GAAG,KAAK,KAAK;AAChG;AAeA,SAAS,aAAa,OAA2C;AAC/D,SAAO;AAAA,IACL,IAAI,MAAM;AAAA,IACV,MAAM,MAAM;AAAA,IACZ,iBAAiB,MAAM;AAAA,IACvB,GAAI,MAAM,gBAAgB,OAAO,EAAE,OAAO,MAAM,eAAe,KAAK,IAAI,CAAC;AAAA;AAAA,IAEzE,aAAa,MAAM,iBAAiB,OAAO;AAAA,EAC7C;AACF;AAOO,SAAS,cAAc,kBAA0C;AACtE,MAAI,iBAAiB,WAAW,GAAG;AACjC,WAAO,CAAC;AAAA,EACV;AACA,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,SACE,iBAAiB,iBAAiB,KAAK,IAAI,CAAC;AAAA,IAGhD;AAAA,EACF;AACF;AAEA,SAAS,KACP,MACA,MACA,WAAyB,CAAC,GAC1B,QAAkB,CAAC,GACb;AACN,QAAM,MAAM,UAAU,IAAI;AAC1B,MAAI,QAAQ,QAAQ;AAClB,mBAAe,MAAM,KAAK,QAAW,KAAK;AAC1C;AAAA,EACF;AACA,eAAa;AAAA,IACX,IAAI;AAAA,IACJ;AAAA,IACA,GAAI,SAAS,SAAS,IAAI,EAAE,SAAS,IAAI,CAAC;AAAA,IAC1C,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;AAAA,EACtC,CAAC;AACH;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  rulesHints,
5
5
  rulesView,
6
6
  waiverCounts
7
- } from "./chunk-OLIEY4WM.js";
7
+ } from "./chunk-JROQOOUR.js";
8
8
  import {
9
9
  readAllRules
10
10
  } from "./chunk-XGGKDAE3.js";
@@ -93,6 +93,17 @@ function listedRules(rules, on) {
93
93
  );
94
94
  return [...forCreatives, ...others];
95
95
  }
96
+ function longestPrompt(rules, on) {
97
+ if (on.surface && on.surface !== "creatives") {
98
+ return { output: on.surface, count: rulesForOutput(rules, on.surface).length };
99
+ }
100
+ const creatives = {
101
+ output: "creatives",
102
+ count: selectRules(rules, { ...on.kind ? { kind: on.kind } : {}, ...on.product ? { product: on.product } : {} }).length
103
+ };
104
+ if (on.surface === "creatives" || on.kind || on.product) return creatives;
105
+ return ["landings", "documents", "reports"].map((output) => ({ output, count: rulesForOutput(rules, output).length })).reduce((most, next) => next.count > most.count ? next : most, creatives);
106
+ }
96
107
  function unmovedHints(conflicts) {
97
108
  if (conflicts.length === 0) return [];
98
109
  return [
@@ -119,11 +130,11 @@ var rulesListCommand = defineCommand({
119
130
  const kind = args.kind === "static" || args.kind === "video" ? args.kind : void 0;
120
131
  const product = typeof args.product === "string" && args.product ? args.product : void 0;
121
132
  const [rules, specs] = await Promise.all([readAllRules(root), readCreativeSpecs(root)]);
122
- const forAds = selectRules(rules, { ...kind ? { kind } : {}, ...product ? { product } : {} });
123
- const active = listedRules(rules, { ...target, ...kind ? { kind } : {}, ...product ? { product } : {} });
133
+ const on = { ...target, ...kind ? { kind } : {}, ...product ? { product } : {} };
134
+ const active = listedRules(rules, on);
124
135
  const shown = args.all === true ? rules : active;
125
136
  const hints = [
126
- ...rulesHints(forAds, waiverCounts(specs)),
137
+ ...rulesHints(active, waiverCounts(specs), longestPrompt(rules, on)),
127
138
  ...unmovedHints((await moveLegacyRules(root)).conflicts)
128
139
  ];
129
140
  const meta = { count: shown.length, active: active.length, total: rules.length };
@@ -152,13 +163,13 @@ Full guide: __tooling__/docs/tools/baker/rules.md`
152
163
  subCommands: {
153
164
  // Loaded with the family: `baker rules --for landings` runs it, and its flags are read before it runs.
154
165
  list: rulesListCommand,
155
- add: () => import("./add-XRXV4JYO.js").then((m) => m.rulesAddCommand),
156
- retire: () => import("./add-XRXV4JYO.js").then((m) => m.rulesRetireCommand),
157
- check: () => import("./check-3B4HE6HI.js").then((m) => m.checkCommand)
166
+ add: () => import("./add-SK4RUEEM.js").then((m) => m.rulesAddCommand),
167
+ retire: () => import("./add-SK4RUEEM.js").then((m) => m.rulesRetireCommand),
168
+ check: () => import("./check-YRRQ5ZEZ.js").then((m) => m.checkCommand)
158
169
  },
159
170
  default: "list"
160
171
  });
161
172
  export {
162
173
  rulesCommand
163
174
  };
164
- //# sourceMappingURL=rules-M5SXLUDN.js.map
175
+ //# sourceMappingURL=rules-PCGXXGIK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/rules/index.ts","../src/commands/rules/list.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { rulesListCommand } from \"./list.ts\";\n\nexport const rulesCommand = defineCommand({\n meta: {\n name: \"rules\",\n description: `The company's standing rules: what every creative, landing (forms included), document or report, or all of them, may say or show. The brand's own come from BRAND.md; the ones a person taught are one file each in src/content/rules/, saved only after they said yes. Every ad is made and checked against the ones for creatives; an edit to a page, form, creative, document or report shows its own.\n\nStart here:\n baker rules list [--for creatives|landings|documents|reports]\n baker rules add --for landings --text \"No prices on landings.\" --strength never --applies copy --quote \"<their words>\" # only after the person agreed\n baker rules check [--for creatives|landings|reports] # after a rule changes: which ads, pages or reports already made break it\n baker rules retire <id>\nFull guide: __tooling__/docs/tools/baker/rules.md`,\n },\n subCommands: {\n // Loaded with the family: `baker rules --for landings` runs it, and its flags are read before it runs.\n list: rulesListCommand,\n add: () => import(\"./add.ts\").then((m) => m.rulesAddCommand),\n retire: () => import(\"./add.ts\").then((m) => m.rulesRetireCommand),\n check: () => import(\"./check.ts\").then((m) => m.checkCommand),\n },\n default: \"list\",\n});\n","/** `baker rules list`: the company's standing rules, for creatives, landings, documents, reports or all, as they stand now. */\nimport { defineCommand } from \"citty\";\nimport { readAllRules } from \"../../engine/creative-context/index.ts\";\nimport { moveLegacyRules } from \"../../engine/creative-rules/move-rules.ts\";\nimport type { CreativeRule } from \"../../engine/creative-rules/schema.ts\";\nimport { rulesForOutput, selectRules } from \"../../engine/creative-rules/select.ts\";\nimport { writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { findWorkspaceRoot } from \"../canvas/normalize-paths.ts\";\nimport { readCreativeSpecs, readSurface, rulesHints, rulesView, type Surface, waiverCounts } from \"./view.ts\";\n\nconst LIST_DESCRIPTION = `The company's standing rules for every ad, landing, document and report: the brand's own (BRAND.md) and the ones a person taught, each with its id, strength (never | must | prefer), what it holds for (\\`for\\`: landings, documents, reports or all; absent, creatives), what it is about, its words, the person's own words and where it came from. Read the ones for an output before planning it (\\`--for creatives\\`, \\`--for landings\\`, …); an edit to a page, form, creative, document or report shows that output's.\nStart here: baker rules list\n baker rules list --for creatives # the rules every creative is held to\n baker rules list --for landings # the rules every page and form is held to\n baker rules list --for documents # the rules every document is held to\n baker rules list --kind video --product cubbo-engage # the rules one ad is held to\n baker rules list --all # retired ones and every scope too`;\n\nconst LIST_ARGS = {\n for: {\n type: \"string\",\n description:\n \"creatives | landings | documents | reports: only the rules that output is held to (a form is a landing)\",\n required: false,\n },\n kind: {\n type: \"string\",\n description: \"static | video: only the rules an ad of this kind is held to\",\n required: false,\n },\n product: {\n type: \"string\",\n description: \"A product slug (src/content/products/<slug>.md): only the rules an ad of it is held to\",\n required: false,\n },\n all: {\n type: \"boolean\",\n description: \"Every rule, retired ones and every scope included\",\n required: false,\n default: false,\n },\n full: { type: \"boolean\", description: \"Each rule and the person's words whole\", required: false, default: false },\n} as const;\n\nregisterSchema({ command: \"rules.list\", description: LIST_DESCRIPTION, args: LIST_ARGS });\n\n/**\n * The active rules `rules list` shows: the ones for one output (creatives: one kind or product's when\n * narrowed), or with none named, the creatives' and the ones only for each other output, unless a kind\n * or product names one ad. Pure.\n */\nexport function listedRules(\n rules: readonly CreativeRule[],\n on: { surface?: Surface; kind?: \"static\" | \"video\"; product?: string },\n): CreativeRule[] {\n if (on.surface && on.surface !== \"creatives\") return rulesForOutput(rules, on.surface);\n const forCreatives = selectRules(rules, {\n ...(on.kind ? { kind: on.kind } : {}),\n ...(on.product ? { product: on.product } : {}),\n });\n if (on.surface === \"creatives\" || on.kind || on.product) return forCreatives;\n const others = ([\"landings\", \"documents\", \"reports\"] as const).flatMap((output) =>\n rulesForOutput(rules, output).filter((r) => r.for === output),\n );\n return [...forCreatives, ...others];\n}\n\n/**\n * The output whose one prompt carries the most of the rules `rules list` shows, and how many: the one\n * named, or with none named, the longest of the creatives' and each other output's. Pure.\n */\nexport function longestPrompt(\n rules: readonly CreativeRule[],\n on: { surface?: Surface; kind?: \"static\" | \"video\"; product?: string },\n): { output: Surface; count: number } {\n if (on.surface && on.surface !== \"creatives\") {\n return { output: on.surface, count: rulesForOutput(rules, on.surface).length };\n }\n const creatives = {\n output: \"creatives\" as const,\n count: selectRules(rules, { ...(on.kind ? { kind: on.kind } : {}), ...(on.product ? { product: on.product } : {}) })\n .length,\n };\n if (on.surface === \"creatives\" || on.kind || on.product) return creatives;\n return ([\"landings\", \"documents\", \"reports\"] as const)\n .map((output) => ({ output, count: rulesForOutput(rules, output).length }))\n .reduce((most, next) => (next.count > most.count ? next : most), creatives as { output: Surface; count: number });\n}\n\n/** What stayed in the old rules folder when the rules moved: no ad or page is held to it. Pure. */\nexport function unmovedHints(conflicts: readonly string[]): string[] {\n if (conflicts.length === 0) return [];\n return [\n `Not moved to src/content/rules/, so nothing is held to it: ${conflicts.join(\", \")} (a different rule of the same name is already there, or the company keeps its own rules collection). Never merge them by hand: tell the Baker team with \\`baker feedback report\\`.`,\n ];\n}\n\nexport const rulesListCommand = defineCommand({\n meta: { name: \"list\", description: LIST_DESCRIPTION },\n args: LIST_ARGS,\n async run({ args }) {\n const target = readSurface(args.for);\n if (!target) {\n writeJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `--for: creatives, landings, documents or reports, not \"${String(args.for)}\" (a form counts as a landing).`,\n fix: \"Leave --for out to list the rules for every output together.\",\n },\n });\n process.exit(1);\n }\n const root = findWorkspaceRoot(process.cwd()) ?? process.cwd();\n const kind: \"static\" | \"video\" | undefined =\n args.kind === \"static\" || args.kind === \"video\" ? args.kind : undefined;\n const product = typeof args.product === \"string\" && args.product ? args.product : undefined;\n const [rules, specs] = await Promise.all([readAllRules(root), readCreativeSpecs(root)]);\n const on = { ...target, ...(kind ? { kind } : {}), ...(product ? { product } : {}) };\n const active = listedRules(rules, on);\n const shown = args.all === true ? rules : active;\n const hints = [\n ...rulesHints(active, waiverCounts(specs), longestPrompt(rules, on)),\n ...unmovedHints((await moveLegacyRules(root)).conflicts),\n ];\n const meta = { count: shown.length, active: active.length, total: rules.length };\n writeJson({\n ok: true,\n data: rulesView(shown, { full: args.full === true }),\n meta,\n ...(hints.length > 0 ? { hints } : {}),\n });\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAAA,sBAAqB;;;ACC9B,SAAS,qBAAqB;AAU9B,IAAM,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQzB,IAAM,YAAY;AAAA,EAChB,KAAK;AAAA,IACH,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,EACZ;AAAA,EACA,SAAS;AAAA,IACP,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,EACZ;AAAA,EACA,KAAK;AAAA,IACH,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,SAAS;AAAA,EACX;AAAA,EACA,MAAM,EAAE,MAAM,WAAW,aAAa,0CAA0C,UAAU,OAAO,SAAS,MAAM;AAClH;AAEA,eAAe,EAAE,SAAS,cAAc,aAAa,kBAAkB,MAAM,UAAU,CAAC;AAOjF,SAAS,YACd,OACA,IACgB;AAChB,MAAI,GAAG,WAAW,GAAG,YAAY,YAAa,QAAO,eAAe,OAAO,GAAG,OAAO;AACrF,QAAM,eAAe,YAAY,OAAO;AAAA,I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I,EAAE,MAAM,IAAI,CAAC;AAAA,IACtC,CAAC;AAAA,EACH;AACF,CAAC;;;ADnIM,IAAM,eAAeC,eAAc;AAAA,EACxC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQf;AAAA,EACA,aAAa;AAAA;AAAA,IAEX,MAAM;AAAA,IACN,KAAK,MAAM,OAAO,mBAAU,EAAE,KAAK,CAAC,MAAM,EAAE,eAAe;AAAA,IAC3D,QAAQ,MAAM,OAAO,mBAAU,EAAE,KAAK,CAAC,MAAM,EAAE,kBAAkB;AAAA,IACjE,OAAO,MAAM,OAAO,qBAAY,EAAE,KAAK,CAAC,MAAM,EAAE,YAAY;AAAA,EAC9D;AAAA,EACA,SAAS;AACX,CAAC;","names":["defineCommand","defineCommand"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koda-sl/baker-cli",
3
- "version": "0.895.0",
3
+ "version": "0.898.0",
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/chats/index.ts","../src/commands/chats/carry-files.ts","../src/commands/chats/publish-hints.ts"],"sourcesContent":["import type {\n ChatsDiffResponse,\n ChatsListRequest,\n ChatsListResponse,\n ChatsTranscriptResponse,\n ChatsViewResponse,\n} from \"@baker/api\";\nimport {\n CHAT_IMPORT_SURFACES,\n type ChatSurfaceDetail,\n type ChatsImportResponse,\n EFFECT_LISTS,\n type EffectList,\n} from \"@baker/api/chats\";\n\ntype ChatImportSurface = (typeof CHAT_IMPORT_SURFACES)[number];\n\nimport { defineCommand } from \"citty\";\nimport { apiPost } from \"../../client.ts\";\nimport { withWindowSpellings } from \"../../date-window.ts\";\nimport { getEnv, requireChatId } from \"../../env.ts\";\nimport { repeatedValues } from \"../../lib/repeatedFlags.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failApi } from \"../actions/shared.ts\";\nimport { applyPatch, patchRefusal, readSourceFiles, revertPatch, type SourceFiles } from \"./carry-files.ts\";\nimport { publishHints, stillPublishingHints } from \"./publish-hints.ts\";\n\nconst STATUS_GROUPS = [\"active\", \"archived\", \"all\"] as const;\nconst DEFAULT_LIST_LIMIT = 20;\nconst REPO_SURFACES = [\"knowledge\", \"company\", \"brand\", \"landings\", \"flows\", \"creatives\"] as const;\n\nfunction parseBoundedInt(raw: string | undefined, name: string, min: number, max: number): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (Number.isNaN(value) || value < min || value > max) {\n throw new Error(`--${name} must be an integer between ${min} and ${max}`);\n }\n return value;\n}\n\nregisterSchema({\n command: \"chats.list\",\n description:\n 'Start here: list other Sessions on this account (newest first) so you can reuse what was done before. Each row shows the Session id, title, status, and a count of what it produced (creatives, landings, actions, flows, ads, reports…). Looking for one? `--search \"PMax Brasil\"` finds the Sessions whose title or conversation holds any of the words, newest first, each with the `match` it was found by; read the match before trusting a row, since more words match more Sessions. A recap of a period (\"what did we change yesterday\", \"what did we publish in September\") is one call: `--since 2026-09-01 --until 2026-09-30 --published --limit 100` returns every Session published in those days with its `publishedAt` and what those Publishes took (add --full for each change by name, and each Task, Scheduled agent, tag or ad change with what its Publish did) — never a `view` per Session. Without --published the days list every Session worked on in them, a Session continued since included. Then drill in with `baker chats view <id>`, `baker chats transcript <id>`, or `baker chats diff <id>`. Read-only.',\n args: {\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions to return, 1-100 (default: 20)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Include each Session's full change list and its effects by name, with each one's Publish outcome\",\n required: false,\n default: false,\n },\n search: {\n type: \"string\",\n description:\n 'Sessions whose title or conversation holds any of these words, newest first, each with its `match` (e.g. --search \"PMax Brasil\")',\n required: false,\n },\n since: {\n type: \"string\",\n description:\n \"First day, YYYY-MM-DD in the company's time zone: Sessions worked on in the days, even if continued since (with --published, published in them)\",\n required: false,\n },\n until: {\n type: \"string\",\n description: \"Last day, inclusive, YYYY-MM-DD (e.g. --since 2026-11-16 --until 2026-11-16 for one day)\",\n required: false,\n },\n published: {\n type: \"boolean\",\n description:\n \"Only Sessions published in the days, newest publish first, each with its publishedAt; each row counts only those Publishes\",\n required: false,\n default: false,\n },\n },\n});\n\ntype ListArgs = {\n search?: string;\n status?: string;\n limit?: string;\n full?: boolean;\n since?: string;\n until?: string;\n published?: boolean;\n};\n\nfunction listRequestBody(args: ListArgs): ChatsListRequest {\n if (args.status !== undefined && !(STATUS_GROUPS as readonly string[]).includes(args.status)) {\n throw new Error(`--status must be one of: ${STATUS_GROUPS.join(\"|\")}`);\n }\n const status = STATUS_GROUPS.find((group) => group === args.status);\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 100);\n // Exclude our own Session so we never list ourselves as a reusable \"other\".\n const selfChatId = getEnv().BAKER_CHAT_ID;\n return {\n ...(args.search ? { search: args.search } : {}),\n ...(status ? { status } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(args.full ? { full: true } : {}),\n ...(args.since ? { since: args.since } : {}),\n ...(args.until ? { until: args.until } : {}),\n ...(args.published ? { published: true } : {}),\n ...(selfChatId ? { excludeChatId: selfChatId } : {}),\n };\n}\n\nfunction emptyListHint(args: ListArgs): string {\n if (args.search) {\n return \"No Session's title or conversation holds any of those words. Try other words (a name, a figure), widen with --status all, or drop --search to list the newest.\";\n }\n if (args.since || args.until) {\n return args.published\n ? \"No Session was published in those days (company time zone). Widen --since/--until, or drop --published to see the Sessions worked on.\"\n : \"No Session was worked on in those days (company time zone). Widen --since/--until.\";\n }\n return \"No Sessions matched. Widen with --status all or a larger --limit.\";\n}\n\nconst INCOMPLETE_LIST_HINT =\n \"Those days hold more work than one call reads, so a Session worked on early in them and continued since may be missing — split the period into shorter --since/--until calls.\";\n\nfunction listHints(args: ListArgs, count: number, limit: number, incomplete: boolean): string[] {\n const hints = periodListHints(args, count, limit);\n return incomplete ? [INCOMPLETE_LIST_HINT, ...hints] : hints;\n}\n\nfunction periodListHints(args: ListArgs, count: number, limit: number): string[] {\n if (count === 0) {\n return [emptyListHint(args)];\n }\n if (!(args.since || args.until)) {\n return [\n \"Drill in: `baker chats view <id>` for outputs, `chats transcript <id>` for the conversation, `chats diff <id>` for the real file changes.\",\n ];\n }\n const what = args.published ? \"what that Session's Publishes in those days took\" : \"what that Session produced\";\n const recap = `These rows are the recap: each one's \\`outputs\\`${args.full ? \", `changes` and `effects` (with each one's Publish `outcome`)\" : \" (add --full for each change by name and what its Publish did)\"} tell ${what}. Answer from them — open a single Session only for a detail the person asks about, never one \\`view\\` per row.`;\n if (count >= limit) {\n return [\n `These are the newest ${count}; the period may hold more — raise --limit (up to 100) or narrow --since/--until.`,\n recap,\n ];\n }\n return [recap];\n}\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List other Sessions on this account, newest first.\" },\n args: withWindowSpellings({\n status: { type: \"string\", description: \"Filter: active|archived|all (default: all)\", required: false },\n limit: { type: \"string\", description: \"Max Sessions (1-100, default 20)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Include each Session's change list and effects by name, with their Publish outcome\",\n required: false,\n default: false,\n },\n search: {\n type: \"string\",\n description: \"Sessions whose title or conversation holds any of these words\",\n required: false,\n },\n since: {\n type: \"string\",\n description: \"First day worked on (or published), YYYY-MM-DD, even if continued since\",\n required: false,\n },\n until: { type: \"string\", description: \"Last day, inclusive, YYYY-MM-DD\", required: false },\n published: {\n type: \"boolean\",\n description: \"Only published Sessions, by publish date\",\n required: false,\n default: false,\n },\n }),\n run: async ({ args }) => {\n try {\n const body = listRequestBody(args);\n const response = await apiPost<ChatsListResponse>(\"/api/chats/list\", body);\n writeJson({\n ok: true,\n ...rowsAsData(response.data, \"chats\"),\n hints: listHints(\n args,\n response.data.chats.length,\n body.limit ?? DEFAULT_LIST_LIMIT,\n response.data.incomplete === true,\n ),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.view\",\n routes: [\"POST /api/chats/view\"],\n effect: \"read\",\n description:\n \"Inspect one Session's FULL picture of what it changed — the unified `effects`: git content (landings, creatives, flows, knowledge, brand), plus DB-only effects that never touch the repo — Actions, Scheduled agents, Tags, Tag Manager, Google Analytics, ad-platform writes, the funnel (`funnel`: which steps it added, changed or removed, and which ways in it added or removed in `triggersAdded`/`triggersRemoved`), what counts as a conversion (`conversions`), conversion sends, event sources, and every other staged or already-applied change (`otherChanges`: A/B tests, recipes, library images) — each resolved to real detail (names, descriptions, priorities, tag types, ad operations) and, once published, its `outcome`. Also `publish` (what each external surface actually did, with the provider's own error), `activitySummary` (the chat's own timeline counted by action, with its notable rows: status changes, publish start/fail, workspace recoveries, timeouts; the rows whole as `activity` with --full), `usage` (per-thread cost and the Session's token totals), the kickoff (how it was asked), threads, and commits. Effects are `staged` (in-progress draft) or applied. Compact shows at most 25 rows per list; a list cut to fit is named in `truncated` with its total and every row counted by kind and outcome. `activitySummary.capped` true means the Session logged more than 500 timeline rows and the counts cover the newest 500. One surface: `--surface ads.google` returns only that list, every row counted by kind and outcome (`counts`) plus the first 5 rows that did not apply (`notApplied`: staged, failed, skipped, refused); add --full for all of its rows. A completed Session is NOT proof its external changes landed — read `publish`. Use after `baker chats list` to decide whether to reuse it. Read-only.\",\n args: {\n id: { type: \"positional\", description: \"The Session id (from `baker chats list`)\", required: true },\n full: {\n type: \"boolean\",\n description:\n \"Every effect row and the whole activity timeline (compact caps each list at 25 and counts the timeline)\",\n required: false,\n default: false,\n },\n surface: {\n type: \"string\",\n description: `One effect list only, counted by kind and outcome, with the rows that did not apply: ${EFFECT_LISTS.join(\"|\")}`,\n required: false,\n },\n },\n});\n\nfunction effectListArg(raw: string | undefined): EffectList | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const list = EFFECT_LISTS.find((name) => name === raw);\n if (!list) {\n throw new Error(`--surface must be one of: ${EFFECT_LISTS.join(\"|\")}`);\n }\n return list;\n}\n\nfunction surfaceHints(data: ChatSurfaceDetail, full: boolean): string[] {\n const { list, total, notApplied, notAppliedTotal } = data.surface;\n const hints: string[] = [];\n if (!full && notApplied.length < notAppliedTotal) {\n hints.push(\n `notApplied shows ${notApplied.length} of ${notAppliedTotal} rows that did not apply — \\`counts\\` has every one; read them all with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n if (!full && notApplied.length < total) {\n hints.push(\n `${list} shows ${notApplied.length} of its ${total} rows; read every row with \\`baker chats view <id> --surface ${list} --full\\`.`,\n );\n }\n hints.push(\"What each platform's Publish did overall, with its errors: `baker chats view <id> --fields publish`.\");\n return hints;\n}\n\nconst viewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Inspect one Session's full effects — git content + actions/tags/ads, kickoff, commits.\",\n },\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n full: { type: \"boolean\", description: \"Include full detail\", required: false, default: false },\n surface: { type: \"string\", description: \"One effect list only, e.g. ads.google\", required: false },\n },\n run: async ({ args }) => {\n try {\n const surface = effectListArg(args.surface);\n const response = await apiPost<ChatsViewResponse>(\"/api/chats/view\", {\n chatId: args.id,\n ...(args.full ? { full: true } : {}),\n ...(surface ? { surface } : {}),\n });\n if (\"surface\" in response.data) {\n writeJson({ ...response, hints: surfaceHints(response.data, args.full) });\n return;\n }\n const hints: string[] = response.data.publish ? publishHints(response.data.publish) : [];\n for (const cut of response.data.truncated ?? []) {\n hints.push(\n `effects.${cut.list} shows ${cut.shown} of ${cut.total} — \\`truncated\\` counts all ${cut.total} by kind and outcome; read that list alone with \\`baker chats view <id> --surface ${cut.list}\\`.`,\n );\n }\n if (response.data.activitySummary?.capped) {\n hints.push(\n \"activitySummary covers only the Session's newest 500 timeline rows: its total and counts leave the earlier ones out.\",\n );\n }\n if (response.data.diffAvailable) {\n hints.push(\"See the real file-level diff of the git content with `baker chats diff <id> --full`.\");\n } else if (response.data.status === \"in_progress\" || response.data.status === \"publishing\") {\n hints.push(\n \"This Session is still in progress — read its current file changes with `baker chats diff <id> --live`.\",\n );\n }\n hints.push(...stillPublishingHints(response.data.status));\n hints.push(\"Read the conversation with `baker chats transcript <id>`.\");\n writeJson({ ...response, hints });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst TRANSCRIPT_ROLES = [\"user\", \"assistant\"] as const;\n\n/** Every `--search` given (citty keeps only the last): one text as itself, several as a list matched as any of them. */\nfunction transcriptSearch(rawArgs: readonly string[], parsed: unknown): string | string[] | undefined {\n const texts = repeatedValues(rawArgs, \"search\", parsed).filter((text) => text.trim() !== \"\");\n return texts.length > 1 ? texts : texts[0];\n}\n\nregisterSchema({\n command: \"chats.transcript\",\n routes: [\"POST /api/chats/transcript\"],\n effect: \"read\",\n description:\n 'Start here: read a Session\\'s conversation (user + agent turns), the most recent messages last. Leave out the id to read THIS chat — the way to recover its own earlier words after a context summary (never grep the raw logs on disk). `--search \"5.700\"` returns only the messages holding the text, from the whole conversation however long — repeat it for several (`--search lead --search GTM`: the messages holding any of them, in one call, never a loop); `--role user` keeps one side; `--turns` keeps each request and the agent\\'s closing message of that turn (a recap). To recap an earlier Session, start with `--turns --role user` (its requests), then `--turns --role assistant --limit 3` or `--search` for how it went: `--turns` alone returns every closing reply. Compact truncates long messages (around the match when searching); add --full for verbatim text of one message found with `--search \"<distinctive phrase>\" --limit 1` — a whole chat verbatim runs to tens of KB. Read-only.',\n args: {\n id: {\n type: \"positional\",\n description: \"The Session id (from `baker chats list`). Default: this chat\",\n required: false,\n },\n search: {\n type: \"string\",\n description:\n 'Only messages containing this text, case-insensitive (e.g. --search \"5.700\"); repeat it for messages holding any of several (--search lead --search GTM)',\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: {\n type: \"boolean\",\n description: \"Only each user message and the agent's closing message of that turn\",\n required: false,\n default: false,\n },\n limit: { type: \"string\", description: \"Max messages to return, 1-1000 (default: 100)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Return verbatim (untruncated) message text\",\n required: false,\n default: false,\n },\n },\n});\n\nconst transcriptCommand = defineCommand({\n meta: { name: \"transcript\", description: \"Read a Session's conversation — another one, or this chat's own.\" },\n args: {\n id: { type: \"positional\", description: \"The Session id (default: this chat)\", required: false },\n search: {\n type: \"string\",\n description: \"Only messages containing this text (repeatable: any of them)\",\n required: false,\n },\n role: { type: \"string\", description: \"Only one side: user|assistant\", required: false },\n turns: { type: \"boolean\", description: \"Each request + the closing reply\", required: false, default: false },\n limit: { type: \"string\", description: \"Max messages (1-1000, default 100)\", required: false },\n full: { type: \"boolean\", description: \"Verbatim message text\", required: false, default: false },\n },\n run: async ({ args, rawArgs }) => {\n try {\n // No id reads the caller's own chat, so its earlier words survive a context summary.\n const chatId = args.id ?? getEnv().BAKER_CHAT_ID;\n if (!chatId) {\n throw new Error(\"Pass the Session id: `baker chats transcript <id>` (find it with `baker chats list`).\");\n }\n const body: Record<string, unknown> = { chatId };\n const search = transcriptSearch(rawArgs, args.search);\n if (search !== undefined) body.search = search;\n if (args.role) {\n if (!(TRANSCRIPT_ROLES as readonly string[]).includes(args.role)) {\n throw new Error(`--role must be one of: ${TRANSCRIPT_ROLES.join(\"|\")}`);\n }\n body.role = args.role;\n }\n if (args.turns) {\n body.turns = true;\n }\n const limit = parseBoundedInt(args.limit, \"limit\", 1, 1000);\n if (limit !== undefined) {\n body.limit = limit;\n }\n if (args.full) {\n body.full = true;\n }\n const response = await apiPost<ChatsTranscriptResponse>(\"/api/chats/transcript\", body);\n const hints: string[] = [];\n if (response.data.truncated) {\n hints.push(\"Older messages were dropped to fit --limit. Raise --limit, or narrow with --search.\");\n }\n if (response.data.answersNotKept) {\n hints.push(\n \"A question card says `Answer no longer kept`: only the last 10 answers are kept, so no --limit brings it back. Read the user's reply from the messages after it.\",\n );\n }\n if (search !== undefined && response.data.entries.length === 0) {\n hints.push(\n \"No message holds that text. The whole conversation was searched — try a shorter or differently written piece of it.\",\n );\n }\n writeJson({ ...response, meta: { count: response.data.entries.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nregisterSchema({\n command: \"chats.diff\",\n description:\n \"See the real file-level changes a Session made (landings, creatives, brand, flows, knowledge). Published Sessions read from git; for an in-progress (unpublished) Session pass --live to read its changes straight from its running workspace. Without --live, an unpublished Session returns available:false — use `baker chats view` for the staged summary. Compact lists changed files with +/- counts; add --full for the actual diff text. Read-only.\",\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n surface: {\n type: \"string\",\n description: \"Filter to one surface: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: {\n type: \"boolean\",\n description: \"Include the unified-diff patch text per file\",\n required: false,\n default: false,\n },\n live: {\n type: \"boolean\",\n description:\n \"For an in-progress Session, read its changes from the live workspace (slower; resumes the paused Runtime). Ignored for published Sessions.\",\n required: false,\n default: false,\n },\n },\n});\n\nconst diffCommand = defineCommand({\n meta: { name: \"diff\", description: \"See a published Session's real file-level changes.\" },\n args: {\n id: { type: \"positional\", description: \"The Session id\", required: true },\n surface: {\n type: \"string\",\n description: \"Filter: knowledge|company|brand|landings|flows|creatives\",\n required: false,\n },\n full: { type: \"boolean\", description: \"Include the diff patch text per file\", required: false, default: false },\n live: {\n type: \"boolean\",\n description: \"Read an in-progress Session's changes from its live workspace (slower)\",\n required: false,\n default: false,\n },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = { chatId: args.id };\n if (args.surface) {\n if (!(REPO_SURFACES as readonly string[]).includes(args.surface)) {\n throw new Error(`--surface must be one of: ${REPO_SURFACES.join(\"|\")}`);\n }\n body.surface = args.surface;\n }\n if (args.full) {\n body.full = true;\n }\n if (args.live) {\n body.live = true;\n }\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", body);\n writeJson({\n ...response,\n meta: { count: response.data.files.length },\n ...(!response.data.available && response.data.reason ? { hints: [response.data.reason] } : {}),\n ...(response.data.available && !args.full && response.data.files.length > 0\n ? { hints: [\"Add --full to read the actual diff text for each file.\"] }\n : {}),\n });\n } catch (err) {\n failApi(err);\n }\n },\n});\n\nconst IMPORT_DESCRIPTION = `Bring another chat's unpublished work into this chat, in one call — and take it out of that chat, so publishing both can never apply anything twice.\n\nStart here when the user wants another chat's work brought into this one (\"bring over\", \"merge the two\nchats\", \"its publish keeps failing — carry it over\", \"recover what the discarded chat did\"):\n baker chats import --from-chat <chat-id> # everything: files and staged changes\n baker chats import --from-chat <chat-id> --only meta-ads,tasks # only these staged surfaces, no files\n baker chats import --from-chat <chat-id> --failed # a PUBLISHED chat: the ad changes its publish could not apply\n baker chats import --from-chat $BAKER_CHAT_ID --failed # this chat's own last Publish: its failed ad changes, to fix and publish again\n\nThe other chat may be open, its publish may have failed, or it may be discarded. Its file changes (Knowledge,\npages, Forms, pictures) are applied in this workspace exactly as it made them, and every staged surface moves\nexactly as staged: ads (Google, Meta, LinkedIn, X, ChatGPT), Shopify, Tag Manager, Google Analytics, tracking\ntags, Tasks, scheduled agents, ActiveCampaign, site settings, ad goals, the funnel, conversions, conversion\nsends, event sources and lead routes. When both chats change the same file or the same thing, nothing moves\nand the refusal names each clash — ask the user which version wins. A chat whose publish failed is then closed\nto publishing, so the same work never goes live twice.\n--failed takes the Google Ads, Meta, LinkedIn, X and ChatGPT changes a published chat's publish could not\napply (failed, or skipped because what they needed failed), stages them here as they were — naming what did\napply by its real id — and takes them out of that chat, so its Retry cannot apply them twice. A chat goes on\nafter its Publish: naming this chat itself takes what its own last Publish could not apply into what it stages now.\nA change moved here cannot go back: to leave one behind, ask the user first and use --only (Google Ads alone\ncan pick single changes: \\`baker ads google draft import --from-chat <id> --refs|--exclude\\`).\nFind chat ids with \\`baker chats list\\`; see what one staged with \\`baker chats view <id>\\`.`;\n\nregisterSchema({\n command: \"chats.import\",\n description: IMPORT_DESCRIPTION,\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat — open, publish failed or discarded; published, or this chat itself, with --failed\",\n required: true,\n },\n only: {\n type: \"string\",\n description: `Comma-separated staged surfaces to move, leaving its files there (default: everything): ${CHAT_IMPORT_SURFACES.join(\", \")}`,\n required: false,\n },\n failed: {\n type: \"boolean\",\n description: \"The other chat is published: stage here the ad changes its publish could not apply\",\n required: false,\n default: false,\n },\n },\n});\n\n/** What became of the other chat's files, and of that chat itself. */\nfunction filesHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined): string[] {\n const hints: string[] = [];\n if (files?.kind === \"patch\") {\n hints.push(\n `Its ${files.paths.length} changed file(s) are now in this workspace, exactly as that chat left them: ${files.paths.join(\", \")}. Check them in the preview; never rebuild them by hand.`,\n );\n }\n if (files?.kind === \"stayed\") {\n hints.push(\n `Its file changes (Knowledge, pages, Forms…) did not come along: ${files.reason} Tell the user what is missing; do not rebuild it from memory.`,\n );\n } else if (data.filesStayed > 0) {\n hints.push(\n `Chat ${data.fromChatId} also changed ${data.filesStayed} file(s) (Knowledge, pages, Forms…) that did not come along. Run the import without --only to bring them.`,\n );\n }\n if (data.carried) {\n hints.push(\n \"That chat holds nothing of its own any more and can no longer be published, so the same work never goes live twice. This chat publishes all of it.\",\n );\n } else if (files?.kind === \"patch\") {\n hints.push(\n \"That chat still has its own copy of these files: tell the user to publish only this chat, or the same file changes would go live twice.\",\n );\n }\n return hints;\n}\n\n/** What the agent needs after a move: what stayed behind in the other chat, and what to check next. */\nfunction importHints(data: ChatsImportResponse[\"data\"], files: SourceFiles | undefined, failed: boolean): string[] {\n const hints: string[] = [];\n const moved = data.surfaces.reduce((sum, surface) => sum + surface.moved, 0);\n const stayed = data.surfaces.filter((surface) => surface.left);\n if (moved === 0 && stayed.length === 0 && files?.kind !== \"patch\") {\n hints.push(\n failed\n ? `Every ad change of chat ${data.fromChatId} applied, so there was nothing to bring over.`\n : `Chat ${data.fromChatId} had no unpublished changes, so nothing moved.`,\n );\n }\n for (const surface of stayed) {\n hints.push(\n `${surface.left?.count ? `${surface.left.count} ` : \"\"}${surface.surface} change(s) stayed in chat ${data.fromChatId}: ${surface.left?.reason}`,\n );\n }\n hints.push(...filesHints(data, files));\n if (moved > 0) {\n hints.push(\n \"The moved changes are this chat's now and publish with it; the other chat no longer holds them. Review them with each surface's `draft list` (and `baker ads google draft validate` when Google Ads changes moved).\",\n );\n }\n if (moved > 0 && stayed.length === 0 && !data.carried) {\n hints.push(\n \"Nothing staged stayed in the other chat. Never tell the user to discard it for this: its other work is still there.\",\n );\n }\n if (failed && moved > 0) {\n hints.push(\n \"They failed once for a reason: read each one's error with `baker chats view <id>` (publish) and amend it here before the user publishes, or it can fail the same way.\",\n );\n }\n return hints;\n}\n\ntype OnlyFlag = { surfaces?: ChatImportSurface[] } | { refusal: string };\n\n/** The surfaces `--only` names; absent means every surface, and a list naming none is refused. */\nfunction onlyFlag(value: unknown): OnlyFlag {\n if (typeof value !== \"string\") return {};\n const named = value\n .split(\",\")\n .map((surface) => surface.trim())\n .filter((surface) => surface.length > 0);\n if (named.length === 0) return { refusal: \"--only names no surface\" };\n const unknown = named.filter((surface) => !(CHAT_IMPORT_SURFACES as readonly string[]).includes(surface));\n if (unknown.length > 0) return { refusal: `--only names ${unknown.join(\", \")}, which is not a surface` };\n return { surfaces: named as ChatImportSurface[] };\n}\n\nfunction refuse(message: string, fix: string): never {\n writeJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message, fix } });\n process.exit(1);\n}\n\n/** The other chat's files, applied here before its staged changes move — or why they stay there, or clash. */\nasync function carryFiles(fromChatId: string): Promise<SourceFiles | { kind: \"clash\"; paths: string[] }> {\n const files = await readSourceFiles(fromChatId);\n if (files.kind !== \"patch\") return files;\n const clashes = patchRefusal(files.patch);\n if (clashes) return { kind: \"clash\", paths: clashes };\n applyPatch(files.patch);\n return files;\n}\n\nconst importCommand = defineCommand({\n meta: { name: \"import\", description: IMPORT_DESCRIPTION },\n args: {\n \"from-chat\": {\n type: \"string\",\n description: \"The other chat whose work comes here — or, with --failed, this chat's own last Publish\",\n },\n only: { type: \"string\", description: \"Comma-separated staged surfaces to move, without files (default: all)\" },\n failed: {\n type: \"boolean\",\n description: \"From a published chat (this one included): the ad changes its publish could not apply\",\n default: false,\n },\n },\n run: async ({ args }) => {\n const fromChatId = typeof args[\"from-chat\"] === \"string\" ? args[\"from-chat\"].trim() : \"\";\n if (!fromChatId) {\n refuse(\n \"--from-chat is required\",\n \"Name the other chat: baker chats import --from-chat <chat-id> (ids from `baker chats list`).\",\n );\n }\n const only = onlyFlag(args.only);\n if (\"refusal\" in only) {\n // A list naming nothing must never widen to \"every surface\": the move takes them out of the other chat.\n refuse(\n only.refusal,\n `Name surfaces from: ${CHAT_IMPORT_SURFACES.join(\", \")} — or leave --only off to move them all.`,\n );\n }\n if (args.failed && only.surfaces) {\n refuse(\"--failed takes every ad platform's failed changes\", \"Leave --only off with --failed.\");\n }\n const chatId = requireChatId();\n let files: Awaited<ReturnType<typeof carryFiles>> | undefined;\n try {\n files = args.failed || only.surfaces ? undefined : await carryFiles(fromChatId);\n } catch (err) {\n failApi(err);\n }\n if (files?.kind === \"clash\") {\n refuse(\n `Nothing moved: these files changed in both chats, differently: ${files.paths.join(\", \")}.`,\n \"Ask the user which version should win. To bring only the other chat's staged changes and leave its files there, run the import again with --only and the surfaces it staged.\",\n );\n }\n try {\n const response = await apiPost<ChatsImportResponse>(\"/api/chats/import\", {\n chatId,\n fromChatId,\n ...(only.surfaces ? { surfaces: only.surfaces } : {}),\n ...(files?.kind === \"patch\" ? { filesCarried: true } : {}),\n ...(args.failed ? { failed: true } : {}),\n });\n writeJson({ ...response, hints: importHints(response.data, files, Boolean(args.failed)) });\n } catch (err) {\n // All or nothing: the files go back out when the staged changes could not come with them.\n if (files?.kind === \"patch\") revertPatch(files.patch);\n failApi(err);\n }\n },\n});\n\nexport const chatsCommand = defineCommand({\n meta: {\n name: \"chats\",\n description: `Inspect other Sessions on this account: list them, view what they produced, read their conversation, and see their real file changes — so you can reuse past work for a new goal. \\`import --from-chat <id>\\` moves another open Session's staged changes into this one.\nFull guide: __tooling__/docs/tools/baker/chats.md`,\n },\n subCommands: {\n list: listCommand,\n view: viewCommand,\n transcript: transcriptCommand,\n diff: diffCommand,\n import: importCommand,\n },\n});\n","/**\n * The file half of `baker chats import`: the other chat's changes to its files (Knowledge, pages,\n * Forms, pictures…), read from its workspace as one patch (`chats diff --live`'s `gitPatch`) and\n * applied here with `git apply` — exactly, or not at all.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport type { ChatsDiffResponse } from \"@baker/api\";\nimport { apiPost } from \"../../client.ts\";\n\nexport type SourceFiles =\n | { kind: \"none\" }\n | { kind: \"patch\"; patch: string; paths: string[] }\n | { kind: \"stayed\"; reason: string };\n\n/** What the other chat changed in its files, as something this workspace can apply — or why not. */\nexport async function readSourceFiles(fromChatId: string): Promise<SourceFiles> {\n const response = await apiPost<ChatsDiffResponse>(\"/api/chats/diff\", {\n chatId: fromChatId,\n live: true,\n gitPatch: true,\n });\n const { data } = response;\n if (!data.available) {\n return { kind: \"stayed\", reason: data.reason ?? \"its files could not be read.\" };\n }\n if (data.source === \"published\") {\n // Its changes reached the live site already, so there is nothing of them to carry.\n return { kind: \"none\" };\n }\n if (data.files.length === 0) {\n return { kind: \"none\" };\n }\n if (data.gitPatch === undefined) {\n return {\n kind: \"stayed\",\n reason: \"its file changes are too large to bring over in one piece, so none of them came along.\",\n };\n }\n return { kind: \"patch\", patch: data.gitPatch, paths: data.files.map((file) => file.path) };\n}\n\nfunction repoRoot(): string {\n return execFileSync(\"git\", [\"rev-parse\", \"--show-toplevel\"], { encoding: \"utf8\" }).trim();\n}\n\n/** `git apply` of the patch at this workspace's root; `check` changes nothing, `reverse` takes it back out. */\nfunction gitApply(patch: string, mode: \"check\" | \"apply\" | \"reverse\"): void {\n const flags = mode === \"check\" ? [\"--check\"] : mode === \"reverse\" ? [\"--reverse\"] : [];\n execFileSync(\"git\", [\"apply\", \"--whitespace=nowarn\", ...flags, \"-\"], {\n cwd: repoRoot(),\n input: patch,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\n/** The files `git apply --check` named as not applying here, or the whole message when it named none. */\nexport function clashingFiles(stderr: string): string[] {\n const named = [...stderr.matchAll(/^error: ([^:\\n]+): /gm)]\n .map((match) => match[1])\n .filter((path): path is string => path !== undefined && path !== \"patch failed\");\n return named.length > 0 ? [...new Set(named)] : [stderr.trim()];\n}\n\n/** Why the patch cannot apply here — the files this chat also changed — or undefined when it applies cleanly. */\nexport function patchRefusal(patch: string): string[] | undefined {\n try {\n gitApply(patch, \"check\");\n return undefined;\n } catch (error) {\n const stderr = (error as { stderr?: Buffer | string }).stderr;\n return clashingFiles(stderr === undefined ? String(error) : String(stderr));\n }\n}\n\nexport function applyPatch(patch: string): void {\n gitApply(patch, \"apply\");\n}\n\nexport function revertPatch(patch: string): void {\n gitApply(patch, \"reverse\");\n}\n","import type { ChatPublishSummary } from \"@baker/api/chats\";\n\n/**\n * What a reader must not conclude from a completed Session: that it published\n * everything it staged (better than one published draft in three did not), or\n * that every change it sent is now what the platform holds.\n */\nexport function publishHints(publish: ChatPublishSummary): string[] {\n const hints: string[] = [];\n // Not `complete`: a change a person chose not to send leaves the publish complete, and still never went live.\n const failed = publish.failedTotal;\n if (failed > 0) {\n hints.push(\n `This Session's publish left ${failed} change${failed === 1 ? \"\" : \"s\"} behind — see \\`publish.surfaces\\` for why each did not apply. Do not report those changes as live.`,\n );\n }\n const unconfirmed = publish.unconfirmedTotal ?? 0;\n if (unconfirmed > 0) {\n hints.push(\n `${unconfirmed} change${unconfirmed === 1 ? \"\" : \"s\"} went through but could not be confirmed when read back from the platform — \\`publish.surfaces[].unconfirmedChanges\\` says what it shows instead. Check before reporting them as done.`,\n );\n }\n return hints;\n}\n\n/**\n * A Session still publishing is not live yet, and nothing in this chat runs\n * once it is: work that has to wait for it is a Scheduled agent (BAKER-1743).\n */\nexport function stillPublishingHints(status: string): string[] {\n if (status !== \"publishing\") return [];\n return [\n \"This Session is still publishing: its changes are not live yet. Work that has to wait for it (a check on the live page, a test lead) is a Scheduled agent staged now with `baker scheduled-agents create --run-at <time>`, whose brief first checks this Session went live. It exists only once your own chat is published: a page trigger staged now misses this Session's publish, and a `--run-at` that has passed by then is created switched off, so leave hours of headroom, not minutes, and tell the user it runs only once they publish this chat. Never ask the user to come back and tell you when it is done.\",\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAS,qBAAqB;;;ACX9B,SAAS,oBAAoB;AAU7B,eAAsB,gBAAgB,YAA0C;AAC9E,QAAM,WAAW,MAAM,QAA2B,mBAAmB;AAAA,IACnE,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAU;AAAA,EACZ,CAAC;AACD,QAAM,EAAE,KAAK,IAAI;AACjB,MAAI,CAAC,KAAK,WAAW;AACnB,WAAO,EAAE,MAAM,UAAU,QAAQ,KAAK,UAAU,+BAA+B;AAAA,EACjF;AACA,MAAI,KAAK,WAAW,aAAa;AAE/B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,MAAM,WAAW,GAAG;AAC3B,WAAO,EAAE,MAAM,OAAO;AAAA,EACxB;AACA,MAAI,KAAK,aAAa,QAAW;AAC/B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ;AAAA,IACV;AAAA,EACF;AACA,SAAO,EAAE,MAAM,SAAS,OAAO,KAAK,UAAU,OAAO,KAAK,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE;AAC3F;AAEA,SAAS,WAAmB;AAC1B,SAAO,aAAa,OAAO,CAAC,aAAa,iBAAiB,GAAG,EAAE,UAAU,OAAO,CAAC,EAAE,KAAK;AAC1F;AAGA,SAAS,SAAS,OAAe,MAA2C;AAC1E,QAAM,QAAQ,SAAS,UAAU,CAAC,SAAS,IAAI,SAAS,YAAY,CAAC,WAAW,IAAI,CAAC;AACrF,eAAa,OAAO,CAAC,SAAS,uBAA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Q,GAAG;AAAA,IACb;AAAA,EACF;AACF,CAAC;AAEM,IAAM,eAAe,cAAc;AAAA,EACxC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA,EAEf;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,EACV;AACF,CAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/rules/view.ts"],"sourcesContent":["/**\n * The company's rules as the agent reads them in `baker rules list`: what each is for (creatives, landings, documents, reports or all), each one's id, strength and words, the person's own words when\n * they taught it, and where it came from; and which ones ads keep waiving. Pure, but for the read\n * of the ads' waivers.\n */\nimport { readdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { CreativeRule } from \"../../engine/creative-rules/schema.ts\";\n\nexport const SURFACES = [\"creatives\", \"landings\", \"documents\", \"reports\"] as const;\nexport type Surface = (typeof SURFACES)[number];\n\n/** What `--for` names on the commands that read rules or pieces: one output (`ads` is creatives' old name), {} when left out, null for anything else. Pure. */\nexport function readSurface(value: unknown): { surface?: Surface } | null {\n if (value === undefined) return {};\n const surface = SURFACES.find((s) => s === (value === \"ads\" ? \"creatives\" : value));\n return surface ? { surface } : null;\n}\n\n/** A rule cut to this in the compact view: the whole is behind `--full`. */\nconst RULE_CHARS = 200;\nconst QUOTE_CHARS = 160;\n/** Waived this often, a rule may no longer hold. */\nconst RETIRE_AFTER = 3;\n/** Past this many active rules, every prompt carries a long list: worth a look. */\nconst MANY_RULES = 40;\n\nconst cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);\n\n/** Where a rule came from, in a few words. */\nfunction fromOf(rule: CreativeRule): string {\n if (rule.origin === \"declared\") return \"BRAND.md\";\n const when = rule.source.date ? ` ${rule.source.date}` : \"\";\n const where = rule.source.slug ? ` on ${rule.source.slug}` : \"\";\n return `taught${when}${where}`;\n}\n\nexport type RuleView = {\n id: string;\n strength: CreativeRule[\"strength\"];\n /** landings, documents, reports or all; absent, the rule is for creatives. */\n for?: CreativeRule[\"for\"];\n applies: CreativeRule[\"applies\"];\n rule: string;\n their_words?: string;\n from: string;\n /** The words it bans in an ad's words, and the phrases that may still hold them. */\n bans?: string[];\n except?: string[];\n /** Words every ad must say. */\n requires?: string[];\n /** Only real people may appear. */\n people?: \"real\";\n scope?: CreativeRule[\"scope\"];\n status?: \"retired\";\n retired_by?: string;\n};\n\n/** What code checks of a rule, as the agent reads it. Pure. */\nfunction checkView(check: CreativeRule[\"check\"]): Pick<RuleView, \"bans\" | \"except\" | \"requires\" | \"people\"> {\n return {\n ...(check?.forbid ? { bans: check.forbid } : {}),\n ...(check?.allow ? { except: check.allow } : {}),\n ...(check?.require ? { requires: check.require } : {}),\n ...(check?.people ? { people: check.people } : {}),\n };\n}\n\n/** Each rule as the agent reads it. Pure. */\nexport function rulesView(rules: readonly CreativeRule[], opts: { full?: boolean } = {}): RuleView[] {\n const max = opts.full ? Number.POSITIVE_INFINITY : RULE_CHARS;\n const quoteMax = opts.full ? Number.POSITIVE_INFINITY : QUOTE_CHARS;\n return rules.map((r) => ({\n id: r.id,\n strength: r.strength,\n ...(r.for ? { for: r.for } : {}),\n applies: r.applies,\n rule: cut(r.text, max),\n ...(r.source.quote ? { their_words: cut(r.source.quote, quoteMax) } : {}),\n from: fromOf(r),\n ...checkView(r.check),\n ...(Object.keys(r.scope).length > 0 ? { scope: r.scope } : {}),\n ...(r.status === \"retired\" ? { status: \"retired\" as const } : {}),\n ...(r.retiredBy ? { retired_by: r.retiredBy } : {}),\n }));\n}\n\n/** How many ads waive each rule (`waive: [{rule, why}]` in their prompt.json). Pure. */\nexport function waiverCounts(specs: readonly unknown[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const spec of specs) {\n const waive = (spec as { waive?: unknown } | null)?.waive;\n if (!Array.isArray(waive)) continue;\n for (const entry of waive) {\n const id = (entry as { rule?: unknown } | null)?.rule;\n if (typeof id === \"string\" && id) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n }\n return counts;\n}\n\n/** Every creative's prompt.json, parsed; one that cannot be read is left out. */\nexport async function readCreativeSpecs(root: string): Promise<unknown[]> {\n const dir = path.join(root, \"src\", \"creatives\");\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n const specs = await Promise.all(\n entries\n .filter((e) => e.isDirectory() && !e.name.startsWith(\"_\"))\n .map((e) =>\n readFile(path.join(dir, e.name, \"prompt.json\"), \"utf8\")\n .then((raw): unknown => JSON.parse(raw))\n .catch(() => null),\n ),\n );\n return specs.filter((s) => s !== null);\n}\n\n/** What the rules say to do next: retire one ads keep waiving, look at a list grown long. Pure. */\nexport function rulesHints(active: readonly CreativeRule[], waived: ReadonlyMap<string, number>): string[] {\n const hints: string[] = [];\n for (const rule of active) {\n const times = waived.get(rule.id) ?? 0;\n if (times >= RETIRE_AFTER) {\n hints.push(\n `${rule.id} was waived by ${times} ads: ask the person whether it still holds, and \\`baker rules retire ${rule.id}\\` if not.`,\n );\n }\n }\n if (active.length > MANY_RULES) {\n hints.push(\n `${active.length} active rules: every prompt carries them all. Ask the person whether some can be retired or merged.`,\n );\n }\n return hints;\n}\n"],"mappings":";AAKA,SAAS,SAAS,gBAAgB;AAClC,OAAO,UAAU;AAGV,IAAM,WAAW,CAAC,aAAa,YAAY,aAAa,SAAS;AAIjE,SAAS,YAAY,OAA8C;AACxE,MAAI,UAAU,OAAW,QAAO,CAAC;AACjC,QAAM,UAAU,SAAS,KAAK,CAAC,MAAM,OAAO,UAAU,QAAQ,cAAc,MAAM;AAClF,SAAO,UAAU,EAAE,QAAQ,IAAI;AACjC;AAGA,IAAM,aAAa;AACnB,IAAM,cAAc;AAEpB,IAAM,eAAe;AAErB,IAAM,aAAa;AAEnB,IAAM,MAAM,CAAC,MAAc,QAAiB,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC,WAAM;AAG/F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ACA,MAAI,OAAO,SAAS,YAAY;AAC9B,UAAM;AAAA,MACJ,GAAG,OAAO,MAAM;AAAA,IAClB;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ads/meta/pixels.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { DateTime } from \"luxon\";\nimport { NO_CACHE_ARG } from \"../../../cache-flag.ts\";\nimport { apiGet } from \"../../../client.ts\";\nimport { writeAdsJson, writeAdsOutput } from \"../output.ts\";\nimport type { AdsWarning } from \"../types.ts\";\nimport {\n accountsInScope,\n csvOrJson,\n daysAgoIso,\n handleMetaError,\n LISTING_ACCOUNT_ARG,\n readEachAccount,\n todayIso,\n withAccountColumn,\n} from \"./shared.ts\";\n\nexport const pixelsCommand = defineCommand({\n meta: {\n name: \"pixels\",\n description: `List Meta Pixels for an ad account, or count what one pixel received — the firing read, not ad-attributed conversions.\n\nThe list prints each pixel's id, name, last_fired_time and owner (unavailable: true when Meta marks it so); --full adds the install code and the setup fields.\n\n--stats prints one row per day per event (date, weekday, event, count) by default, in the ad account's time zone; --by hour or --by total change the grain, --full returns Meta's raw hourly buckets.\n\nExamples:\n baker ads meta pixels --account-id act_123\n baker ads meta pixels --pixel-id 9876 --stats --days 7 # per day per event\n baker ads meta pixels --pixel-id 9876 --stats --days 7 --event Lead,Purchase # only those events\n baker ads meta pixels --pixel-id 9876 --stats --days 30 --by total # each event's count, first and last seen`,\n },\n args: {\n \"account-id\": LISTING_ACCOUNT_ARG,\n \"pixel-id\": { type: \"string\", description: \"Pixel ID for --stats\" },\n stats: { type: \"boolean\", description: \"Fetch firing stats for the pixel\" },\n aggregation: {\n type: \"string\",\n description: \"stats aggregation: event|browser_type|host|pixel_fire\",\n default: \"event\",\n },\n days: { type: \"string\", description: \"Lookback days for --stats (default 7)\" },\n by: {\n type: \"string\",\n description:\n \"--stats grain: day (default; one row per day per value, with its weekday), hour (one row per hour per value), total (one row per value with first_seen/last_seen)\",\n },\n event: {\n type: \"string\",\n description: \"--stats: keep only these values, comma-separated and exact (e.g. --event Lead,Purchase)\",\n },\n full: {\n type: \"boolean\",\n description:\n \"The list: every field, the install code included. --stats: Meta's raw hourly buckets, every value, instead of the rows\",\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 try {\n if (args.stats) {\n await runStats(args);\n return;\n }\n await runList(args);\n } catch (err) {\n handleMetaError(err);\n }\n },\n});\n\nasync function runStats(args: Record<string, unknown>): Promise<void> {\n const pixelId = args[\"pixel-id\"] as string | undefined;\n if (!pixelId) {\n handleMetaError(new Error(\"--pixel-id is required when --stats is set\"));\n }\n const days = args.days ? Number(args.days) : 7;\n if (!Number.isInteger(days) || days <= 0 || days > 90) {\n handleMetaError(new Error(\"--days must be a positive integer ≤ 90\"));\n }\n const params: Record<string, string> = {\n \"pixel-id\": pixelId,\n aggregation: (args.aggregation as string) ?? \"event\",\n \"start-time\": daysAgoIso(days),\n \"end-time\": todayIso(),\n };\n if (args[\"no-cache\"]) params[\"skip-cache\"] = \"true\";\n const by = (args.by as string | undefined) ?? \"day\";\n if (!isStatsGrain(by)) {\n writeAdsJson({\n ok: false,\n error: { code: \"INVALID_ARGS\", message: `--by must be one of ${STATS_GRAINS.join(\", \")}` },\n });\n process.exit(1);\n }\n const buckets = await apiGet<PixelStatBucket[]>(\"/api/ads/meta/pixel-stats\", params);\n if (args.full) {\n emit(buckets as Array<Record<string, unknown>>, args);\n return;\n }\n const events =\n typeof args.event === \"string\"\n ? args.event\n .split(\",\")\n .map((e) => e.trim())\n .filter(Boolean)\n : [];\n const window = { start: `${params[\"start-time\"]}T00:00:00Z`, end: `${params[\"end-time\"]}T00:00:00Z` };\n const { rows, hints } = rollUpPixelStats(buckets, { aggregation: params.aggregation ?? \"event\", by, events, window });\n writeAdsOutput(rows, csvOrJson(args), undefined, hints);\n}\n\n/** One time bucket as Meta's `/{pixel}/stats` returns it; `start_time` carries the ad account's offset. */\ninterface PixelStatBucket {\n start_time?: string;\n data?: Array<{ value?: string; count?: number }>;\n}\n\nconst STATS_GRAINS = [\"day\", \"hour\", \"total\"] as const;\ntype StatsGrain = (typeof STATS_GRAINS)[number];\n\nfunction isStatsGrain(value: string): value is StatsGrain {\n return (STATS_GRAINS as readonly string[]).includes(value);\n}\n\ninterface RollUp {\n aggregation: string;\n by: StatsGrain;\n events: string[];\n /** The UTC instants the read asked Meta for. */\n window: { start: string; end: string };\n}\n\n/**\n * Meta answers with one bucket per hour, each a nested list of values, so \"how\n * many Leads a day\" was a script over hundreds of rows at every call site. The\n * day is the one Meta wrote on `start_time` — the ad account's own day.\n */\nfunction rollUpPixelStats(\n buckets: PixelStatBucket[],\n { aggregation, by, events, window }: RollUp,\n): { rows: Array<Record<string, string | number>>; hints: string[] } {\n const { folded, seen } = foldBuckets(buckets, by, new Set(events));\n const rows = [...folded.values()]\n .sort((a, b) => a.key.localeCompare(b.key) || b.count - a.count)\n .map((row): Record<string, string | number> => {\n if (by === \"total\") {\n return { [aggregation]: row.value, count: row.count, first_seen: row.first, last_seen: row.last };\n }\n if (by === \"hour\") return { hour: row.key, [aggregation]: row.value, count: row.count };\n return { date: row.key, weekday: accountWeekday(row.first), [aggregation]: row.value, count: row.count };\n });\n const hints: string[] = [];\n const missing = events.filter((event) => !seen.has(event));\n if (missing.length > 0) {\n const received = [...seen].sort().join(\", \") || \"nothing\";\n hints.push(`No ${missing.join(\", \")} received in this window (names are exact). The pixel received: ${received}.`);\n }\n const partialDays = by === \"day\" && rows.length > 0 ? daysCutByWindow(buckets, window) : [];\n if (partialDays.length > 0) {\n hints.push(\n `${partialDays.join(\" and \")} ${partialDays.length === 1 ? \"is a partial day\" : \"are partial days\"}: the read covers ${window.start} → ${window.end}, so compare only the full days between them.`,\n );\n }\n return { rows, hints };\n}\n\ninterface FoldedRow {\n key: string;\n value: string;\n count: number;\n first: string;\n last: string;\n}\n\nconst ROW_KEY: Record<StatsGrain, (time: string) => string> = {\n day: (time) => accountDay(time),\n hour: (time) => time,\n total: () => \"\",\n};\n\nfunction foldBuckets(\n buckets: PixelStatBucket[],\n by: StatsGrain,\n wanted: Set<string>,\n): { folded: Map<string, FoldedRow>; seen: Set<string> } {\n const entries = buckets.flatMap((bucket) =>\n (bucket.data ?? []).map((entry) => ({\n time: bucket.start_time ?? \"\",\n value: entry.value ?? \"(unnamed)\",\n count: entry.count ?? 0,\n })),\n );\n const folded = new Map<string, FoldedRow>();\n for (const { time, value, count } of entries) {\n if (wanted.size > 0 && !wanted.has(value)) continue;\n const key = ROW_KEY[by](time);\n const id = `${key}\\u0000${value}`;\n const row = folded.get(id) ?? { key, value, count: 0, first: time, last: time };\n row.count += count;\n if (instant(time) < instant(row.first)) row.first = time;\n if (instant(time) > instant(row.last)) row.last = time;\n folded.set(id, row);\n }\n return { folded, seen: new Set(entries.map((entry) => entry.value)) };\n}\n\n/** The account-local days the window starts after or ends before, oldest first. */\nfunction daysCutByWindow(buckets: PixelStatBucket[], window: { start: string; end: string }): string[] {\n const cut = new Set<string>();\n for (const { start_time: time } of buckets) {\n if (time && dayOverhangsWindow(time, window)) cut.add(accountDay(time));\n }\n return [...cut].sort();\n}\n\n/** Whether the account-local day `time` falls on starts before or ends after the window read. */\nfunction dayOverhangsWindow(time: string, window: { start: string; end: string }): boolean {\n const dayStart = bucketTime(time).startOf(\"day\");\n if (!dayStart.isValid) return false;\n return dayStart < DateTime.fromISO(window.start) || dayStart.plus({ days: 1 }) > DateTime.fromISO(window.end);\n}\n\n/** A bucket's `start_time` in the offset Meta wrote on it — the ad account's. */\nfunction bucketTime(time: string): DateTime {\n return DateTime.fromISO(time, { setZone: true });\n}\n\nfunction accountDay(time: string): string {\n return bucketTime(time).toISODate() ?? \"\";\n}\n\n/** Written out so a reader never works the weekday out from the date, and gets it wrong. */\nfunction accountWeekday(time: string): string {\n return bucketTime(time).setLocale(\"en-US\").toFormat(\"ccc\");\n}\n\n/** Compared as instants: across a clock change, the same local hour carries two offsets. */\nfunction instant(time: string): number {\n return bucketTime(time).toMillis();\n}\n\nasync function runList(args: Record<string, unknown>): Promise<void> {\n const accounts = await accountsInScope(args);\n const params: Record<string, string> = {};\n if (args[\"no-cache\"]) params[\"skip-cache\"] = \"true\";\n const restricted = new Set<string>();\n const read = await readEachAccount(accounts, async (accountId) => {\n const { pixels, restrictedFields } = await apiGet<{\n pixels: MetaPixel[];\n restrictedFields: string[];\n }>(\"/api/ads/meta/pixels\", { ...params, \"account-id\": accountId });\n for (const field of restrictedFields) restricted.add(field);\n return pixels;\n });\n const rows = args.full ? read.rows : read.rows.map(compactPixel);\n emit(withAccountColumn(rows, read.accountOf), args, pixelWarnings([...restricted]), read.hints);\n}\n\n/** A pixel as the backend lists it; the setup fields are passed through whole under --full. */\ninterface MetaPixel extends Record<string, unknown> {\n id: string;\n name?: string;\n last_fired_time?: string;\n owner_business?: { id?: string; name?: string };\n is_unavailable?: boolean;\n}\n\n/**\n * What picks a pixel and says whether it fires. The install snippet and the\n * setup fields were most of every listing (BAKER-3691) and sit behind --full.\n */\nfunction compactPixel(pixel: MetaPixel): Record<string, unknown> {\n return {\n id: pixel.id,\n name: pixel.name,\n last_fired_time: pixel.last_fired_time,\n ...(pixel.owner_business?.name ? { owner: pixel.owner_business.name } : {}),\n // Kept on every row: the md and csv tables take their columns from the first one.\n unavailable: pixel.is_unavailable ? true : undefined,\n };\n}\n\n/**\n * A listing Meta trimmed is still a listing — IDs, names and firing times are\n * complete. Say which setup fields are missing and how to get them, so the gap\n * reads as a client-side access grant rather than as a pixel that isn't there.\n */\nexport function pixelWarnings(restrictedFields: string[]): AdsWarning[] {\n if (restrictedFields.length === 0) {\n return [];\n }\n return [\n {\n code: \"PIXEL_FIELDS_RESTRICTED\",\n message:\n `Meta withheld ${restrictedFields.join(\", \")} for these pixels — the connected user holds no role in the Business that owns them. ` +\n \"IDs, names, creation and last-fired times are complete; install code and setup details are not. \" +\n \"To get them, the client assigns the pixel to the connected user in Meta Business settings → Data sources → Datasets.\",\n },\n ];\n}\n\nfunction emit(\n data: Array<Record<string, unknown>>,\n args: Record<string, unknown>,\n warnings: AdsWarning[] = [],\n hints: string[] = [],\n): void {\n const fmt = csvOrJson(args);\n if (fmt !== \"json\") {\n writeAdsOutput(data, fmt, undefined, hints);\n return;\n }\n writeAdsJson({\n ok: true,\n data,\n ...(warnings.length > 0 ? { warnings } : {}),\n ...(hints.length > 0 ? { hints } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AAgBlB,IAAM,gBAAgB,cAAc;AAAA,EACzC,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWf;AAAA,EACA,MAAM;AAAA,IACJ,cAAc;AAAA,IACd,YAAY,EAAE,MAAM,UAAU,aAAa,uBAAuB;AAAA,IAClE,OAAO,EAAE,MAAM,WAAW,aAAa,mCAAmC;AAAA,IAC1E,aAAa;AAAA,MACX,MAAM;AAAA,MACN,aAAa;AAAA,MACb,SAAS;AAAA,IACX;AAAA,IACA,MAAM,EAAE,MAAM,UAAU,aAAa,wCAAwC;AAAA,IAC7E,IAAI;AAAA,MACF,MAAM;AAAA,MACN,aACE;AAAA,IACJ;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,aAAa;AAAA,IACf;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,aACE;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ,QAAQ,EAAE,MAAM,UAAU,aAAa,oCAAoC,SAAS,OAAO;AAAA,EAC7F;AAAA,EACA,KAAK,OAAO,EAAE,KAAK,MAAM;AACvB,QAAI;AACF,UAAI,KAAK,OAAO;AACd,cAAM,SAAS,IAAI;AACnB;AAAA,MACF;AACA,YAAM,QAAQ,IAAI;AA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KAAK,KAAK,IAAI,YAAY;AAC/D,OAAK,kBAAkB,MAAM,KAAK,SAAS,GAAG,MAAM,cAAc,CAAC,GAAG,UAAU,CAAC,GAAG,KAAK,KAAK;AAChG;AAeA,SAAS,aAAa,OAA2C;AAC/D,SAAO;AAAA,IACL,IAAI,MAAM;AAAA,IACV,MAAM,MAAM;AAAA,IACZ,iBAAiB,MAAM;AAAA,IACvB,GAAI,MAAM,gBAAgB,OAAO,EAAE,OAAO,MAAM,eAAe,KAAK,IAAI,CAAC;AAAA;AAAA,IAEzE,aAAa,MAAM,iBAAiB,OAAO;AAAA,EAC7C;AACF;AAOO,SAAS,cAAc,kBAA0C;AACtE,MAAI,iBAAiB,WAAW,GAAG;AACjC,WAAO,CAAC;AAAA,EACV;AACA,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,SACE,iBAAiB,iBAAiB,KAAK,IAAI,CAAC;AAAA,IAGhD;AAAA,EACF;AACF;AAEA,SAAS,KACP,MACA,MACA,WAAyB,CAAC,GAC1B,QAAkB,CAAC,GACb;AACN,QAAM,MAAM,UAAU,IAAI;AAC1B,MAAI,QAAQ,QAAQ;AAClB,mBAAe,MAAM,KAAK,QAAW,KAAK;AAC1C;AAAA,EACF;AACA,eAAa;AAAA,IACX,IAAI;AAAA,IACJ;AAAA,IACA,GAAI,SAAS,SAAS,IAAI,EAAE,SAAS,IAAI,CAAC;AAAA,IAC1C,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;AAAA,EACtC,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/rules/index.ts","../src/commands/rules/list.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { rulesListCommand } from \"./list.ts\";\n\nexport const rulesCommand = defineCommand({\n meta: {\n name: \"rules\",\n description: `The company's standing rules: what every creative, landing (forms included), document or report, or all of them, may say or show. The brand's own come from BRAND.md; the ones a person taught are one file each in src/content/rules/, saved only after they said yes. Every ad is made and checked against the ones for creatives; an edit to a page, form, creative, document or report shows its own.\n\nStart here:\n baker rules list [--for creatives|landings|documents|reports]\n baker rules add --for landings --text \"No prices on landings.\" --strength never --applies copy --quote \"<their words>\" # only after the person agreed\n baker rules check [--for creatives|landings|reports] # after a rule changes: which ads, pages or reports already made break it\n baker rules retire <id>\nFull guide: __tooling__/docs/tools/baker/rules.md`,\n },\n subCommands: {\n // Loaded with the family: `baker rules --for landings` runs it, and its flags are read before it runs.\n list: rulesListCommand,\n add: () => import(\"./add.ts\").then((m) => m.rulesAddCommand),\n retire: () => import(\"./add.ts\").then((m) => m.rulesRetireCommand),\n check: () => import(\"./check.ts\").then((m) => m.checkCommand),\n },\n default: \"list\",\n});\n","/** `baker rules list`: the company's standing rules, for creatives, landings, documents, reports or all, as they stand now. */\nimport { defineCommand } from \"citty\";\nimport { readAllRules } from \"../../engine/creative-context/index.ts\";\nimport { moveLegacyRules } from \"../../engine/creative-rules/move-rules.ts\";\nimport type { CreativeRule } from \"../../engine/creative-rules/schema.ts\";\nimport { rulesForOutput, selectRules } from \"../../engine/creative-rules/select.ts\";\nimport { writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { findWorkspaceRoot } from \"../canvas/normalize-paths.ts\";\nimport { readCreativeSpecs, readSurface, rulesHints, rulesView, type Surface, waiverCounts } from \"./view.ts\";\n\nconst LIST_DESCRIPTION = `The company's standing rules for every ad, landing, document and report: the brand's own (BRAND.md) and the ones a person taught, each with its id, strength (never | must | prefer), what it holds for (\\`for\\`: landings, documents, reports or all; absent, creatives), what it is about, its words, the person's own words and where it came from. Read the ones for an output before planning it (\\`--for creatives\\`, \\`--for landings\\`, …); an edit to a page, form, creative, document or report shows that output's.\nStart here: baker rules list\n baker rules list --for creatives # the rules every creative is held to\n baker rules list --for landings # the rules every page and form is held to\n baker rules list --for documents # the rules every document is held to\n baker rules list --kind video --product cubbo-engage # the rules one ad is held to\n baker rules list --all # retired ones and every scope too`;\n\nconst LIST_ARGS = {\n for: {\n type: \"string\",\n description:\n \"creatives | landings | documents | reports: only the rules that output is held to (a form is a landing)\",\n required: false,\n },\n kind: {\n type: \"string\",\n description: \"static | video: only the rules an ad of this kind is held to\",\n required: false,\n },\n product: {\n type: \"string\",\n description: \"A product slug (src/content/products/<slug>.md): only the rules an ad of it is held to\",\n required: false,\n },\n all: {\n type: \"boolean\",\n description: \"Every rule, retired ones and every scope included\",\n required: false,\n default: false,\n },\n full: { type: \"boolean\", description: \"Each rule and the person's words whole\", required: false, default: false },\n} as const;\n\nregisterSchema({ command: \"rules.list\", description: LIST_DESCRIPTION, args: LIST_ARGS });\n\n/**\n * The active rules `rules list` shows: the ones for one output (creatives: one kind or product's when\n * narrowed), or with none named, the creatives' and the ones only for each other output, unless a kind\n * or product names one ad. Pure.\n */\nexport function listedRules(\n rules: readonly CreativeRule[],\n on: { surface?: Surface; kind?: \"static\" | \"video\"; product?: string },\n): CreativeRule[] {\n if (on.surface && on.surface !== \"creatives\") return rulesForOutput(rules, on.surface);\n const forCreatives = selectRules(rules, {\n ...(on.kind ? { kind: on.kind } : {}),\n ...(on.product ? { product: on.product } : {}),\n });\n if (on.surface === \"creatives\" || on.kind || on.product) return forCreatives;\n const others = ([\"landings\", \"documents\", \"reports\"] as const).flatMap((output) =>\n rulesForOutput(rules, output).filter((r) => r.for === output),\n );\n return [...forCreatives, ...others];\n}\n\n/** What stayed in the old rules folder when the rules moved: no ad or page is held to it. Pure. */\nexport function unmovedHints(conflicts: readonly string[]): string[] {\n if (conflicts.length === 0) return [];\n return [\n `Not moved to src/content/rules/, so nothing is held to it: ${conflicts.join(\", \")} (a different rule of the same name is already there, or the company keeps its own rules collection). Never merge them by hand: tell the Baker team with \\`baker feedback report\\`.`,\n ];\n}\n\nexport const rulesListCommand = defineCommand({\n meta: { name: \"list\", description: LIST_DESCRIPTION },\n args: LIST_ARGS,\n async run({ args }) {\n const target = readSurface(args.for);\n if (!target) {\n writeJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `--for: creatives, landings, documents or reports, not \"${String(args.for)}\" (a form counts as a landing).`,\n fix: \"Leave --for out to list the rules for every output together.\",\n },\n });\n process.exit(1);\n }\n const root = findWorkspaceRoot(process.cwd()) ?? process.cwd();\n const kind = args.kind === \"static\" || args.kind === \"video\" ? args.kind : undefined;\n const product = typeof args.product === \"string\" && args.product ? args.product : undefined;\n const [rules, specs] = await Promise.all([readAllRules(root), readCreativeSpecs(root)]);\n const forAds = selectRules(rules, { ...(kind ? { kind } : {}), ...(product ? { product } : {}) });\n const active = listedRules(rules, { ...target, ...(kind ? { kind } : {}), ...(product ? { product } : {}) });\n const shown = args.all === true ? rules : active;\n const hints = [\n ...rulesHints(forAds, waiverCounts(specs)),\n ...unmovedHints((await moveLegacyRules(root)).conflicts),\n ];\n const meta = { count: shown.length, active: active.length, total: rules.length };\n writeJson({\n ok: true,\n data: rulesView(shown, { full: args.full === true }),\n meta,\n ...(hints.length > 0 ? { hints } : {}),\n });\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAAA,sBAAqB;;;ACC9B,SAAS,qBAAqB;AAU9B,IAAM,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQzB,IAAM,YAAY;AAAA,EAChB,KAAK;AAAA,IACH,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,EACZ;AAAA,EACA,SAAS;AAAA,IACP,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,EACZ;AAAA,EACA,KAAK;AAAA,IACH,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,SAAS;AAAA,EACX;AAAA,EACA,MAAM,EAAE,MAAM,WAAW,aAAa,0CAA0C,UAAU,OAAO,SAAS,MAAM;AAClH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