Skip to content

feat(chat): add Wave 2's tables for questions, tasks, agents, Why, impact and suggestions (00417–00422) - #1853

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w2-db
Oct 30, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w2-db

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

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.

Migration What
00417 chat_asks, chat_next_moves, chat_messages.shortcut_id Question cards (CHAT-07): at most 4 a run, 2–4 options with exactly one Recommended (chat_ask_options_valid()), answered once. Next moves 1–4 (≤ 80 chars, class, ghost allowed). Read where the run is read.
00418 chat_task_state The /tasks strip (CHAT-09): Chat's own state of an Action Center task (queued / writing / ready_for_review / done), its run and file. action_tasks is untouched.
00419 agents + CHAT-27 chat_agents (draft → active ⇄ paused → archived, owner, private/workspace, case-insensitive unique name, max_run_share 0.10 within 0.01–0.50, max_month_share), immutable chat_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 + origin agent. chat_activity_log.agent_id / agent_run_id; chat_settings.agent_run_share_default, agents_full_auto, workspace_agents_admins_only.
00420 chat_why_analyses, chat_user_prefs.home_seen_at "Why did it move" analyses (metric, scope, both periods, result); "Since you left".
00421 ship_events, impact_measurements, impact_control_sets The impact ledger (CHAT-22): one measurement per shipped change, one outcome vocabulary, 7/14/30/90-day checkpoints, a control set per checkpoint.
00422 chat_suggestion_feeds, chat_suggestions Daily suggestions (CHAT-26): at most one per person, brand and day; each person reads only their own.

CHAT-27 (sub-agents and agent budgets), all in 00419:

  • chat_runs.parent_run_id and subtask_title. message_id may 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.
  • Spend rows (prompt_improve_usage) get agent_id, agent_run_id and parent_run_id.
  • reserve_chat_ai_usage gets two optional arguments, p_agent_run_id and p_run_cap.
    • The run cap is checked under the same per-organization lock, so parallel subtasks can't pass it.
    • The agent run is read from the chat (chat_conversations.agent_run_id), so a subtask's step counts toward its parent; a p_agent_run_id that isn't the chat's is refused.
    • The old 9-argument signature is dropped first; the server's current named call (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)

  • The hold reads the agent run from the chat, as described above; 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;
    • starts a triggered run only while its agent is active. Run now and Run agent may also start a paused or draft agent.
  • A run paused at its cap (paused_cap) keeps its agent and brand place, so an Admin's Continue can't collide with the next run.
  • New column ship_events.agent_run_id, for an agent run's Outcome.

No Action Center table changes. source = chat, the agent and its run go in actions.payload and action_events.data, whose event is free text. "Ready for review" lives in chat_task_state.

Related issue

None. Chat Wave 2 (Drive Chat specs CHAT-07, 09, 21, 22, 26, 27).

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. Apply 00417–00422 in order, each file in one transaction (psql -1 -f …). 00419 drops and re-creates reserve_chat_ai_usage, and must not be split.
  2. Check that the 13 new tables have RLS on and no insert, update or delete policy.
  3. As service role, select public.chat_start_next_agent_run('<org>', null) raises "a workspace limit is needed".
  4. reserve_chat_ai_usage with an unknown run raises "chat run not found".
  5. A Chat step on the dev stack still holds and charges as before (chat-budget.js is unchanged).
  6. Run 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

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes
  • yarn typecheck passes
  • yarn format:check passes
  • Changes are focused — one concern per PR

supabase/schema.sql was rebuilt with build-schema.sh. Server: coverage.test.js and write-guard.test.js pass; the demo-coverage list names the five new brand tables as skipped.

For production (@gkhngyk):

  • Apply 00417–00422 in order, each in one transaction.
  • No new bucket or cron in this PR.
  • Wave 2's code PRs will need 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:

  • The subtask code PR must handle a null chat_runs.message_id. engine-store.ts and engine.ts (saveAnswer, readHistory, the sweep) assume it is set, and thread and tray reads should skip parent_run_id rows.
  • The count guards (5 triggers, 10 subtasks) can be passed by concurrent inserts. Lock the parent row before counting.
  • 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.
  • Agency partners read workspace agents and runs for every brand. Narrow it when per-brand sharing lands (CHAT-21 §K 51).
  • Open in the specs:
    • a step kind for "Working on N parts" (CHAT-27);
    • CHAT-07 question 5;
    • a next move kind column (CHAT-07 C.6, still a suggestion).

🤖 Generated with Claude Code

cihan-gyk and others added 3 commits October 30, 2026 01:12
…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]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 30, 2026
gkhngyk
gkhngyk previously approved these changes Oct 30, 2026

@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 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_usage and chat_agent_usage_shares are security definer with search_path = '', and only service_role can 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_cap run 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, and prompt_improve_usage has 51 rows. The new columns are nullable or use constant defaults.

  • Rest of the repo. schema.sql matches a fresh build-schema.sh. Demo coverage and the write guard pass: no new brand table is member-writable. The PR merges cleanly on current main.

Optional, not blocking

  • chat_asks.step_id isn't tied to run_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_id isn'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 to chat_agents.owner_id, which nothing ties to the workspace.
  • prompt_improve_usage now has two foreign keys to chat_runs (chat_run_id and parent_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_run doesn't look at brands.is_demo. The server's checks keep demo runs out, but and 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 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 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.

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

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants