Repository navigation
feat(chat): add Wave 2's tables for questions, tasks, agents, Why, impact and suggestions (00417–00422) - #1853
Conversation
…iles, Help and add-on packs Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC: nothing reads or writes them while the flag is off. Tables, types and the demo's coverage only; the code that uses them comes in the Wave 1 PRs. - 00407: chat_conversations gets shared_at (Share with team: every member of the workspace reads it), last_read_at (unread results), deleted_at (Delete with Undo; deleted chats are hidden from every member) and a title search column; chat_messages gets context_json (what a person's message was scoped to) and a text search column. 'simple' text search, so a chat in any language is found. The author policy now leaves deleted chats out, and a shared policy reads shared ones. - 00408: chat_user_prefs gets the rest of Settings › General and the one-time notices: rail_open, panel_size, default_mode, answer_language, notify_via, show_thought, panel_on_pages, focus_prompted_at, usage_notice_period, legacy_imported_at. - 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file, the composer's 11 types, 5 a message (a trigger backs the server's check), kept 90 days. - 00410: chat_tool_cache (a chat's read results by tool and scope, server only) and each step's and model call's measure: latency, cache hit, truncation, result tokens on chat_run_steps (never granted to members), prompt cache read/write tokens and latency on the ledger. - 00411: chat_files (filed deliverables and saved answers, the workspace's, kept a year, searchable by title, summary and tags), chat_file_task_links, chat_storage_usage kept by a trigger, and the private bucket chat-files. - 00412: help_answer_cache and help_gaps (server only, no workspace or person ids). - 00413: add_on_products seeded with the owner's packs (AI credits $10, $50, $250, $1,000 at half their price in budget, 12 months; storage +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked), add_on_purchases (Admins read), ai_credit_grants and storage_grants (server only), and prompt_improve_usage.grant_id. Members only ever read; every write is the server's. Tool names, tool results and dollars stay server only. web/src/types/supabase.ts carries the new tables and columns; schema.test.ts checks the policies, the server-only tables, the limits and the seeded packs from the SQL; steps.test.ts keeps the step measure out of the member columns. The demo coverage skips chat_files and chat_tool_cache (a person's own Chat work). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pact and suggestions (00417–00422) Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC: nothing reads or writes them while the flag is off. Tables, types, tests and the demo's coverage only; the code that uses them comes in the Wave 2 PRs. Every new table has row level security on; members only ever read, and every write is the server's. - 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options with exactly one Recommended, checked by chat_ask_options_valid; the answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80 characters, each with its action class and a ghost_ok mark); both readable where their run is. chat_messages.shortcut_id on a person's message only (CHAT-08). - 00418: chat_task_state, the task strip: Chat's own status per Action Center task (queued, writing, ready_for_review, done), the run and the deliverable. action_tasks is not changed. - 00419: chat_agents (status, pause reason, owner, private or workspace visibility, current version, caps per run and month as shares of the AI limit), chat_agent_versions (immutable: skills, instructions, mode, connections, model, scope), chat_agent_triggers (schedule, Signal, KPI, watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger evidence, acting person, brand, action, outcome, cap and use as shares). One run at a time per agent and brand; chat_start_next_agent_run() starts the next queued one under the workspace's limit, Run now and Run agent first. An agent run's chat (chat_conversations.agent_run_id, origin agent) is readable with the run. Agent ids on the Activity log, and the agent settings in chat_settings. CHAT-27: subtasks as child runs (chat_runs.parent_run_id, subtask_title; no message of their own; one level, at most 10), agent_id / agent_run_id / parent_run_id on the ledger, reserve_chat_ai_usage taking the agent run and its cap (old calls still match), and chat_agent_usage_shares() returning shares only (server only, since the budget is its argument). - 00420: chat_why_analyses (the explain_change result per analysis, readable where its chat is) and chat_user_prefs.home_seen_at for "Since you left". - 00421: the impact ledger: ship_events, impact_measurements (one per ship event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and impact_control_sets (per checkpoint). Every member reads them. - 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day per person and brand, own rows only. web/src/types/supabase.ts carries the new tables, columns and functions; schema.test.ts checks the Wave 2 policies, limits, vocabularies and the server-only functions from the SQL. The demo coverage skips the five new brand-scoped tables (a demo brand runs no agent, ships nothing and gets no suggestions). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…runs' places Review fixes for Wave 2's tables, before they ship: - reserve_chat_ai_usage reads the agent run from the chat (chat_conversations.agent_run_id), so a subtask's step counts toward its parent's run; a p_agent_run_id that isn't the chat's is refused, and p_run_cap is always the whole run's cap. search_path is now ''. - chat_start_next_agent_run needs a workspace limit, never starts a run of an archived agent or a deleted brand, and starts a triggered run only while its agent is active (Run now and Run agent also on a paused or draft one). - A run paused at its AI cap keeps its agent and brand place, so an Admin's Continue can't collide with the next run. - ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43). Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
left a comment
There was a problem hiding this comment.
I reviewed 00417–00422 against main's schema. I also ran them in a rolled-back transaction, after this PR's base (00407–00413), and checked reads as the chat's author, a teammate (Analyst), an Admin, a member of another workspace and an anonymous caller. Approving.
What I checked
-
Policies. Each of the 13 new tables has RLS on and only a select policy. Members can't insert, update or delete in any of them, and the anonymous role gets permission denied on all 13.
- Questions, next moves, the task strip and Why analyses follow their chat.
- A private agent is visible to its owner and the workspace's Admins. A workspace agent is visible to every member, and not to other workspaces. Versions and triggers follow their agent.
- An agent run follows its agent. The person it acted as and the Admins keep seeing it after the agent is deleted.
- An agent run's chat is readable by whoever reads the run. A deleted one is readable by nobody.
- The impact ledger is visible to the workspace's members only.
- Suggestions and feeds are visible only to their person, and only in the workspace they belong to now.
-
Server-only writes. Members can't create or change an agent, a version, a trigger or a run, so they can't take ownership, raise a run's cap or change who it acts as. They also can't write the impact ledger, answer a question card, set a chat's
agent_run_id, or change the new Settings › Chat agent switches.chat_start_next_agent_run,reserve_chat_ai_usageandchat_agent_usage_sharesare security definer withsearch_path = '', and onlyservice_rolecan execute them. A member or anon caller gets permission denied. -
Hold and cap. These calls are refused with the error you described:
- an unknown run, or another workspace's run
- an agent run that isn't the chat's
- a run cap on a plain chat
A subtask's step is named with its parent and the parent's agent run, and counts toward the cap, own-key steps included. A step that would pass the cap gets null. The server's current 9-argument named call still matches, and only the new signature is left.
-
Starting runs. Without a limit the function raises. Run now comes first, a draft agent's Run now starts, and a queued run waits while its agent and brand have one running. Archived agents' runs and paused agents' triggered runs never start, and nothing starts once the limit is reached. A
paused_caprun next to a running one for the same agent and brand is refused. -
Limits. The database refuses:
- a 6th trigger, an 11th subtask, a subtask of a subtask, and a subtask in another chat
- a run with neither a message nor a parent
- two Recommended options, a single option, and a 5th question
- an answer without
answered_at - a shortcut on an assistant message
- a duplicate agent name in another case, a paused agent with no reason, and a 0.6 run share
- 4 skills
- a second suggestion the same day
- an "improved" verdict with no confidence
- overlapping Why periods
-
Idempotent. Re-running the
add column if not exists … check, constraint and policy statements leaves the same constraint, policy, index and trigger counts. -
No locks or rewrites to worry about. The altered tables (the Chat tables,
chat_settings,chat_activity_log) are empty on production, andprompt_improve_usagehas 51 rows. The new columns are nullable or use constant defaults. -
Rest of the repo.
schema.sqlmatches a freshbuild-schema.sh. Demo coverage and the write guard pass: no new brand table is member-writable. The PR merges cleanly on currentmain.
Optional, not blocking
chat_asks.step_idisn't tied torun_id. The database accepts a step from another run (your follow-up list has this). A composite FK on(step_id, run_id)→chat_run_steps (id, run_id)would close it.chat_agent_runs.organization_idisn't tied to its agent's workspace. A composite FK(agent_id, organization_id)→chat_agents (id, organization_id)would make a mismatch impossible. The same idea applies tochat_agents.owner_id, which nothing ties to the workspace.prompt_improve_usagenow has two foreign keys tochat_runs(chat_run_idandparent_run_id). Any later embed between the two needs an FK hint, e.g.chat_runs!prompt_improve_usage_chat_run_id_fkey(...). Nothing embeds it today.chat_start_next_agent_rundoesn't look atbrands.is_demo. The server's checks keep demo runs out, butand not exists (select 1 from public.brands b where b.id = q.brand_id and b.is_demo)in the pick would be a cheap backstop.
Numbering: 00417–00422 are in the Chat block, used only by this PR and #1863, which is stacked on it. 00414 is #1851's, and 00415/00416 are unused.
Tests run: src/lib/chat/schema.test.ts (43), src/lib/guards/plan-row.test.ts, web tsc --noEmit, and server src/lib/demo plus chat-budget.test.js (129). All pass.
Deploy: apply 00407 → 00413 (#1812) first, then 00417 → 00422, each file in one transaction. 00419 drops and re-creates reserve_chat_ai_usage, and the server's current call keeps working across it.
gkhngyk
left a comment
There was a problem hiding this comment.
Merging in order with the other approved Chat PRs. This head merges current main; where they overlapped, both sides are kept. Its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build. Chat stays behind CHAT_AGENTIC. Migrations 00417–00422 are applied on production just before this merge.
Summary
Wave 2's one database PR (the plan: one DB PR per wave). Stacked on #1812 (Wave 1's tables, 00407–00413); everything stays behind
CHAT_AGENTIC. Nothing reads or writes these tables yet: the Wave 2 code PRs do.In every new table RLS is on, members only read, and only the server (service role) writes, so cost, status and time columns can't be set from a browser. Private rows (a person's suggestions, a private agent, a private chat) are their owner's.
chat_asks,chat_next_moves,chat_messages.shortcut_idchat_ask_options_valid()), answered once. Next moves 1–4 (≤ 80 chars, class, ghost allowed). Read where the run is read.chat_task_statequeued/writing/ready_for_review/done), its run and file.action_tasksis untouched.chat_agents(draft → active ⇄ paused → archived, owner, private/workspace, case-insensitive unique name,max_run_share0.10 within 0.01–0.50,max_month_share), immutablechat_agent_versions(1–3 skills, instructions, mode, connections, model, scope — no key fields),chat_agent_triggers(≤ 5 per agent),chat_agent_runs(8 statuses, skip / stop reasons, trigger evidence, acting user, brand, action, outcome, use as shares only). One run at a time per agent and brand;chat_start_next_agent_run()starts the next queued run under the workspace limit (Run now / Run agent first). An agent run's chat:chat_conversations.agent_run_id+ originagent.chat_activity_log.agent_id/agent_run_id;chat_settings.agent_run_share_default,agents_full_auto,workspace_agents_admins_only.chat_why_analyses,chat_user_prefs.home_seen_atship_events,impact_measurements,impact_control_setschat_suggestion_feeds,chat_suggestionsCHAT-27 (sub-agents and agent budgets), all in 00419:
chat_runs.parent_run_idandsubtask_title.message_idmay now be null, because a subtask has no message of its own. A trigger keeps it to one level and at most 10 subtasks per run.prompt_improve_usage) getagent_id,agent_run_idandparent_run_id.reserve_chat_ai_usagegets two optional arguments,p_agent_run_idandp_run_cap.chat_conversations.agent_run_id), so a subtask's step counts toward its parent; ap_agent_run_idthat isn't the chat's is refused.chat-budget.js) still matches the new one.chat_agent_usage_shares()returns shares only, never dollars, and is server only. This is a deliberate departure from CHAT-27 item 30 (members reading through RLS): the budget is an argument, and a member passing their own could turn shares back into dollars. The server's API gives members the shares.Review fixes (second commit)
search_pathis now''.chat_start_next_agent_run:paused_cap) keeps its agent and brand place, so an Admin's Continue can't collide with the next run.ship_events.agent_run_id, for an agent run's Outcome.No Action Center table changes.
source = chat, the agent and its run go inactions.payloadandaction_events.data, whoseeventis free text. "Ready for review" lives inchat_task_state.Related issue
None. Chat Wave 2 (Drive Chat specs CHAT-07, 09, 21, 22, 26, 27).
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
psql -1 -f …). 00419 drops and re-createsreserve_chat_ai_usage, and must not be split.select public.chat_start_next_agent_run('<org>', null)raises "a workspace limit is needed".reserve_chat_ai_usagewith an unknown run raises "chat run not found".chat-budget.jsis unchanged).yarn vitest run src/lib/chat/schema.test.ts(43 tests).Applied on the dev database (all six, each in one transaction). The 13 tables have RLS on, the old signature is gone, and the functions refuse as above.
Checklist
yarn lintpassesyarn typecheckpassesyarn format:checkpassessupabase/schema.sqlwas rebuilt withbuild-schema.sh. Server:coverage.test.jsandwrite-guard.test.jspass; the demo-coverage list names the five new brand tables as skipped.For production (@gkhngyk):
CHAT_INTERNAL_SECRET, the agent trigger runner, the nightly suggestion picker, the 14-day suggestion cleanup and the impact measurement job.Follow-ups, not in this PR:
chat_runs.message_id.engine-store.tsandengine.ts(saveAnswer,readHistory, the sweep) assume it is set, and thread and tray reads should skipparent_run_idrows.chat_asks: the step should belong to the same run, and an answer should be written only once. Today the API enforces both; the database could too.kindcolumn (CHAT-07 C.6, still a suggestion).🤖 Generated with Claude Code