Skip to content

feat(chat): pick one daily suggestion per person and brand each morning (W2-24) - #1872

Merged
gkhngyk merged 5 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-daily-suggestion-picker
Oct 31, 2026
Merged

gkhngyk merged 5 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-daily-suggestion-picker

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat W2-24: the job that picks each person's daily suggestion (CHAT-26 §3–§7): one open Action Center action a morning, per person and brand, chosen by rules with no AI call. Server only, behind CHAT_AGENTIC (and CHAT_AGENTIC_ORGS). The Inbox rows and the detail page come in W2-25 and W2-26.

Built on main, but deploy after #1853. The code adds no migration. It reads and writes the tables from 00418, 00419 and 00422 (chat_suggestions, chat_suggestion_feeds, chat_task_state, chat_agent_runs), so it must ship after #1853's migrations. While Chat is off it reads nothing.

When it runs

  • Every hour at :07, started in server.js only when Chat is deployed.
  • It sends when the person's local time is between 07:00 and 12:00, at most once a day per person and brand.
  • The unique (user, brand, day) row is the backstop if the job runs twice.

Time zone order

  1. The zone of the person's latest Chat answer.
  2. Otherwise, the zone most seen in the workspace.
  3. Otherwise, UTC.

Profile and workspace zones come with CHAT-12.

Who gets suggestions (CHAT-26 §6; DECISIONS V)

  • Admins and Managers: their feed turns on by itself.
  • Agency partners: CHAT-26's "members". Their feed turns on when they first open the Inbox (W2-25).
  • Analysts: never.
  • No suggestions at all for:
    • the demo brand (brands.is_demo);
    • paused brands;
    • read-only workspaces.

Candidates

  • The brand's open actions (new, in_progress), unassigned or assigned to the person. Two queries of up to 500 each, so other people's assignments don't fill the window.
  • Skipped:
    • actions suggested in the last 14 days;
    • actions put off with Not now (7 days);
    • removed actions;
    • actions with a "Needs you" approval waiting (an agent run or a Chat task).

Ranking

  • The action's priority score, plus the signal queue's wait lift (1 a day, at most 14).
  • +5 for a "Start now" path.
  • When two scores are within 5 points, an action of another category goes ahead of one in the same category as yesterday's.

What's stored (summary)

  • Structured fields only: the action's kind and title fields, priority score, level and reason, days waiting, the Start now method, page count and "about 4 min a page", and the play when there is one.
  • No ready-made English sentences: W2-25 builds the text in the reader's language from en.json.
  • At most 20,000 bytes, counted with jsonb's extra spaces.

Keeping and pausing

  • Rows older than 14 days are deleted.

  • A feed pauses only when both are true:

    • 30 days have passed since the first suggestion after the person's last use;
    • at least 7 suggestions were sent since that use, and none was used.

    A single suggestion after a long gap never pauses it the next day.

  • A feed created or turned back on today waits until the next morning (§5).

Isolation

  • Each brand is processed in its own try/catch, so one brand's failure doesn't stop the rest.
  • Events are sent once at the end of the run, even after an error.

Events: daily_suggestion_sent and daily_suggestions_paused go to PostHog through a small new server/src/lib/product-events.js (fetch to /batch/, no new package).

  • They carry only ids, category, priority level, booleans and counts, with $geoip_disable: true.
  • With no POSTHOG_KEY, nothing is sent.

Related issue

None. Chat Wave 2 (W2-24, CHAT-26).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Run cd server && npx vitest run src/lib/chat-suggestions src/lib/product-events.test.js. The tests cover:
    • the candidate filters and skip rules;
    • the ranking lifts and variety;
    • the 7-in-7 limit, time zones (DST) and the 14-day delete;
    • the pause rule;
    • the next-morning rule after a new or resumed feed;
    • demo, read-only and Analyst kept out;
    • one brand failing while the others still get theirs;
    • a large summary cut down;
    • nothing read while the flag is off.
  2. On a stack with feat(chat): add Wave 2's tables for questions, tasks, agents, Why, impact and suggestions (00417–00422) #1853's migrations and CHAT_AGENTIC=true, start the server and call the job once (runDailySuggestions). It should write one row per Admin or Manager and brand with open actions, between 07:00 and 12:00 in their zone.

The PostgREST joins (!fk!inner hints, the embed filters) were run read-only against the dev database. They return without errors, and none is ambiguous.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): web isn't touched
  • yarn typecheck passes (run from web/): web isn't touched
  • yarn format:check passes (run from web/): web isn't touched
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change): nothing user-visible yet (W2-25 adds the Inbox and its Help)

Server on this branch (current main + the two commits): npm run format changes nothing, npm run lint is clean, and npm test passes 337 files / 4,639 tests (3 skipped).

For production (@gkhngyk):

  • No separate cron: the job starts inside the server when CHAT_AGENTIC=true. Restart the server after the flag is on.
  • For the events, add POSTHOG_KEY and POSTHOG_HOST to the server environment, with the same values as the web's NEXT_PUBLIC_POSTHOG_*.
  • Several server instances are fine: the unique row stops a second send.

Follow-ups, not in this PR

  • Count the workspace's time zone once per person, not per answer, until CHAT-12 brings profile zones.
  • Product questions for later:
    • Should Remove be permanent? Today, by the spec, it lasts 14 days.
    • An Admin of 20 brands gets up to 20 suggestions a day. Should there be a per-person cap?
  • The Agency partner "shared brands only" rule doesn't exist in the database yet, so the job uses all the workspace's brands.

🤖 Generated with Claude Code

cihan-gyk and others added 4 commits October 30, 2026 22:09
The daily suggestions job (CHAT-26 §3–§7), server only, behind
CHAT_AGENTIC and CHAT_AGENTIC_ORGS. Every hour (node-cron, '7 * * * *')
it picks, by rules and with no AI call, at most one open Action Center
action for each person whose morning it is (07:00–12:00 in their time
zone) and writes it to chat_suggestions (00422). Off, it reads nothing.

- Who: admins and managers get a feed made for them; agency partners
  only once their own feed is on (the Inbox makes it, W2-25); analysts
  never. Never on demo or paused brands, nor in a read-only workspace.
- Candidates: new and in_progress actions, not deleted, unassigned or
  the person's own. Skipped: suggested in the last 14 days, removed, put
  off until a time still ahead, or waiting in Chat's Needs you (an agent
  run needs_you on the action, or a waiting run on one of its tasks).
- Rank: priority score with the candidate queue's capped wait lift
  (scoreCandidate), +5 when Start now opens it in the Content Editor,
  and another category first when yesterday's was the same and the
  scores are within 5.
- At most one a day and 7 in any 7 days; the unique (user, brand,
  sent_on) index makes a second run send nothing twice.
- Summary: structured fields only (kind and the payload keys a title
  reads, priority score/level/reason, wait, Start now method/pages/
  minutes at 4 a page, the play when an action carries one); the web
  writes the words from en.json.
- Rows older than 14 days are deleted; a feed unused for 30 days while
  suggestions kept coming is paused and stays paused.
- Time zone: the person's latest Chat answer's zone, else the one most
  of the workspace reads in, else UTC (no profile zone is stored yet).
- Events daily_suggestion_sent and daily_suggestions_paused go to
  PostHog's batch endpoint from the server (lib/product-events.js), only
  when POSTHOG_KEY is set; logs carry counts and codes only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and keep brands apart

Review fixes for the daily suggestions job (CHAT-26), on top of 9e9f70382.

- Pause: 30 days from the first suggestion since the last use, with at
  least 7 sent since that use and none used. Suggestions are kept only 14
  days, so the job marks the feed (an update; the trigger stamps
  updated_at) when it sends the first one after a use, and counts from
  there. A feed that got one after a long quiet spell isn't paused the
  next day.
- A removed suggestion keeps its action away even when it was put off
  first and its week is over.
- A feed made or turned back on today (created_at or updated_at on the
  person's today) that got none yesterday starts tomorrow morning
  (CHAT-26 §5), with no new column.
- Each brand runs in its own try/catch; the run's events go to PostHog
  once, at its end, whatever failed.
- Candidates: the unassigned open actions and those assigned to the
  people due, 500 of each, so actions assigned to others never take the
  places. People are read page by page.
- Summary size counts a byte per comma and colon (jsonb's text adds a
  space after each), under a 20,000-byte ceiling.
- Server events carry $geoip_disable, as posthog-node does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed what this PR adds: server/src/lib/chat-suggestions/* (job, rules, summary), product-events.js, the server.js start, and the three exports in chat-flag.js and content-published.js. It adds no migration and reads and writes 00418, 00419 and 00422, which are on main. Approving with 87aa37a: a merge of current main and one fix commit, with a test that fails without it.

The fix commit

A cut emoji fails the brand's whole insert. clip in summary.js cuts payload texts with slice(0, max), which counts UTF-16 units. When the 300th (or the 1,000th for why, or the 100th for the play's id) unit is the first half of an emoji, the cut leaves a lone surrogate. JSON.stringify writes it as \ud83d, and Postgres refuses that in jsonb ("Unicode low surrogate must follow a high surrogate"). All of the brand's rows go in one upsert, so nobody in that brand would get a suggestion. The same action would still rank first the next hour and the next day, so it would keep failing.

clip now drops a trailing first half. The new titlePayload test ("never cuts an emoji in half") covers a long prompt text, why and a target label, and checks that a whole emoji before the cut stays. It fails without the fix.

No open action has a text that long today, so this hasn't happened yet. It only needs one long prompt text with an emoji.

What we checked

  • How it starts. server.js calls startDailySuggestions() only inside chatAgenticDeployed(). It's an in-process node-cron at :07 every hour, with no route, so there's no secret to compare. A run still going makes the next tick skip (running), and a crash is logged.

  • Chat off. runDailySuggestions returns before any read without CHAT_AGENTIC=true. loadBrands filters by CHAT_AGENTIC_ORGS in the query (.in('organization_id', …)) and again with chatAgenticEnabled. The 14-day delete runs for every workspace, which is fine because it only removes what's expired.

  • Who's skipped.

    • Demo brands (is_demo = false) and paused brands (is_active) are left out.
    • Read-only workspaces are left out on the cloud with the same isSubscriptionActive rule the web's assertWritable uses.
    • Analysts and unknown roles are left out (roleFeed → never).
    • Agency partners only get suggestions once a feed exists for them, and W2-25 creates it.
    • People come from profiles by the workspace's id. Someone who left keeps a feed row, but it's never matched again.
    • A feed that's off or paused is never sent.
  • One a day.

    • The morning window is 07:00–12:00 local. sent_on is the person's local day.
    • The unique (user_id, brand_id, sent_on) with ignoreDuplicates is the backstop.
    • MIN_GAP_HOURS (12) stops a second one in a morning when the zone changes.
    • Rolling 7 in 7 days.
    • Rows older than 14 days are deleted. A new or turned-back-on feed waits until the next morning.
  • Retries and two servers. Events come only from the rows the upsert actually inserted, so a second run sends no duplicate events. A pause is a conditional update on status = 'on' and the updated_at that was read, so only one run pauses a feed and counts it.

  • Pause. The feed pauses when 30 days have passed since the first suggestion after the last use, and at least 7 unused suggestions are still kept. The updated_at mark keeps the count from restarting when the 14-day delete removes the first row. A feed that gets one suggestion after a long gap isn't paused.

  • No AI call. rules.js and summary.js are pure. Ranking is the priority score, the queue's wait lift, +5 for Start now, and variety within 5 points. The summary holds structured fields only, kept under 20,000 bytes counted as jsonb's text (the check is 32,000).

  • Which actions.

    • The brand's own actions with new/in_progress that aren't deleted.
    • Unassigned ones or the person's own. Assigned ones are read per chunk of the people due, so other people's assignments don't fill the 500.
    • Not ones suggested to that person in the last 14 days, removed, put off for a week, or waiting in Needs you.
    • All roles can read the brand's actions, and agency partners use every brand today.
  • The action is never changed. The job only writes chat_suggestions and chat_suggestion_feeds. It only reads actions, action_tasks, chat_agent_runs and chat_task_state.

  • Bounded work.

    • Brands and profiles are read 1,000 rows a page.
    • Up to 500 candidates per brand, plus 500 per chunk of assigned people.
    • At most 300 recent answers per workspace for time zones.
    • IN lists go through selectInChunks.
    • Only workspaces with someone in their morning read past their profiles.
    • Each workspace and brand has its own try/catch, and events go out once in finally.
  • Time zones. The zone comes from chat_messages.timezone, which the web already validates (validTimezone). It's checked again with Intl. The format cache only grows with real zone names.

  • Events. product-events.js posts to PostHog's /batch/ with a 10 s timeout, 500 a request. It never throws, and it sends nothing without POSTHOG_KEY. Properties are ids, category, level, booleans and counts, with $geoip_disable. The distinct_id is the user id, the same one the web's identify uses.

  • Embeds: three, each with a hint and each over exactly one foreign key:

    • chat_messages → chat_conversations (chat_messages_conversation_id_fkey);
    • chat_task_state → action_tasks (chat_task_state_action_task_id_fkey);
    • chat_task_state → chat_runs (chat_task_state_run_id_fkey).

    The statuses filtered on (needs_you, waiting) are in the tables' checks.

  • Logs: codes and counts only.

Follow-ups (not blocking)

  1. Already on your list: when Agency partners get chosen brands, the job should read the feed's brand against them. Today they use every brand, so nothing to do yet.
  2. Until people have Chat answers, every zone is the workspace's or UTC. At launch everyone starts at 07:00 UTC (10:00 in UTC+3), and it moves to their own zone after their first answer. CHAT-12's profile zone fixes this for good.
  3. The pause count uses updated_at as its mark. Any later feature that updates a feed for another reason (for example, a settings field) would restart the 30 days. A first_unused_at column would make it explicit when one is added.
  4. There's no time limit for a run. At today's size it's a few dozen small queries, and the running guard covers a slow hour. Worth a deadline once there are hundreds of workspaces.

Manual test (third-party: PostHog)

With POSTHOG_KEY/POSTHOG_HOST set on a test server and CHAT_AGENTIC=true for one test workspace, run runDailySuggestions() once in that workspace's morning. Check in PostHog that:

  • daily_suggestion_sent arrives on the person's existing profile (same distinct id as the web);
  • it has no location properties;
  • a second run in the same hour sends nothing.

Without the key, check that the log says nothing was sent and no request goes out.

Tests

On this branch (this PR's head fafa8adcb + current main 703a68600 merged in, clean + the fix):

  • chat-suggestions + product-events: 73 passing. The new test fails without the fix.
  • Full server suite: 337 files, 4,661 passing (3 skipped).
  • Prettier and eslint on the changed server files: clean.
  • plan-row.test.ts: passing. The PR touches no web code.
  • Merging on current main: clean.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.

@gkhngyk
gkhngyk merged commit ef503d6 into ansvisor:main Oct 31, 2026
3 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants