Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(chat): decide each tool call by plan, role, policy and mode (#1776)
Cihan3b7611cd8838
diff --git a/supabase/migrations/00401_chat_settings.sql b/supabase/migrations/00401_chat_settings.sqlnew file mode 100644index 000000000..6369373d9--- /dev/null+++ b/supabase/migrations/00401_chat_settings.sql@@ -0,0 +1,153 @@+-- ============================================================================+-- 00401: Chat's settings — each workspace's tool policy and switches, and+-- each person's "Don't ask again" choices+-- ============================================================================+-- The approval precedence (CHAT-20 §5; web lib/chat/precedence.ts) reads both+-- before every tool call Chat makes, behind CHAT_AGENTIC: nothing reads them+-- while the flag is off.+--+-- * chat_settings: one row per workspace (Settings › Chat). Members read+-- it, since Settings › Chat and "What Chat can do" show it to every role;+-- the server writes it (service role), for an Admin. No row = the+-- defaults below: every tool at its registry default, Full auto open to+-- every role the plan allows, "Don't ask again" offered, Managers able to+-- go live after their click.+-- - tool_policies: an Admin's policy per tool, keyed by the tool's+-- label key (the key the browser knows a tool by: a tool's name never+-- reaches a member, CHAT-03 item 22). never · ask · ask_full_auto ·+-- always; the server keeps each within its tool's maximum, so an+-- EXECUTE or an always-card tool is never "always".+-- - full_auto_for_members: people other than Admins may use Full auto+-- (CHAT-23 policy.toggleFullAutoForManagers). The plan decides first:+-- Full auto is Growth and up.+-- - dont_ask_again: "Don't ask again" is offered and the ticks count.+-- Off, everyone's ticks stop at once; they are kept, not deleted.+-- - manager_execute_off: the go-live groups an Admin turned off for+-- Managers (CHAT-20 §4): publishing, email_outreach, code_prs, feeds.+-- * chat_auto_choices: a person's "Don't ask again" ticks, by tool label+-- key, in their workspace. Theirs to read, add and remove (Settings ›+-- Chat › "Your auto changes"). A tick counts only inside what the plan,+-- the role, the policy and the switches allow (precedence step 6), so a+-- row by itself never lets anything run without a card.++-- Whether every value of a tool policy map is a policy, keyed by a label key.+create or replace function public.chat_tool_policies_valid(p_policies jsonb)+returns boolean+language sql+immutable+set search_path = ''+as $$+ select case+ when jsonb_typeof(p_policies) <> 'object' then false+ else coalesce(+ (+ select bool_and(+ e.key ~ '^[a-z][A-Za-z0-9]{1,63}$'+ and e.value in ('never', 'ask', 'ask_full_auto', 'always')+ )+ from jsonb_each_text(p_policies) as e(key, value)+ ),+ true+ )+ end;+$$;++-- ─── A workspace's Chat settings ────────────────────────────────────────────++create table if not exists public.chat_settings (+ organization_id uuid primary key references public.organizations(id) on delete cascade,+ tool_policies jsonb not null default '{}'::jsonb+ check (public.chat_tool_policies_valid(tool_policies)),+ full_auto_for_members boolean not null default true,+ dont_ask_again boolean not null default true,+ manager_execute_off text[] not null default '{}' check (+ manager_execute_off <@ array['publishing', 'email_outreach', 'code_prs', 'feeds']::text[]+ and public.chat_text_array_distinct(manager_execute_off)+ ),+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now()+);++drop trigger if exists trg_chat_settings_updated_at on public.chat_settings;+create trigger trg_chat_settings_updated_at+ before update on public.chat_settings+ for each row execute function public.handle_updated_at();++comment on table public.chat_settings is+ 'Chat (00401): a workspace''s Chat settings (Settings › Chat): tool policies by label key, Full auto for non-Admins, "Don''t ask again", go-live groups off for Managers. Members read; the server writes for an Admin. No row = the defaults.';+comment on column public.chat_settings.tool_policies is+ 'An Admin''s policy per tool, keyed by the tool''s label key (never its name): never, ask, ask_full_auto or always. Held within each tool''s maximum by the server.';++-- ─── A person's "Don't ask again" ticks ─────────────────────────────────────++create table if not exists public.chat_auto_choices (+ user_id uuid not null references auth.users(id) on delete cascade,+ organization_id uuid not null references public.organizations(id) on delete cascade,+ -- The tool's label key, as in chat_settings.tool_policies.+ tool_key text not null check (tool_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ created_at timestamptz not null default now(),+ primary key (user_id, organization_id, tool_key)+);++create index if not exists chat_auto_choices_organization_idx+ on public.chat_auto_choices (organization_id);++comment on table public.chat_auto_choices is+ 'Chat (00401): a person''s "Don''t ask again" ticks, by tool label key, in their workspace. Theirs to read, add and remove; a tick counts only where the plan, role, policy and switches allow Full auto.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_settings enable row level security;+alter table public.chat_auto_choices enable row level security;++revoke all on table public.chat_settings from anon, authenticated;+revoke all on table public.chat_auto_choices from anon, authenticated;++grant select on table public.chat_settings to authenticated;+grant select, insert, delete on table public.chat_auto_choices to authenticated;++grant all on table public.chat_settings to service_role;+grant all on table public.chat_auto_choices to service_role;++-- Members of the workspace read its settings; the server writes them.+drop policy if exists "chat_settings: member select" on public.chat_settings;+create policy "chat_settings: member select"+ on public.chat_settings+ for select+ using (+ organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++-- A person's own ticks, in the workspace they belong to now: one who moved+-- to another workspace doesn't carry them there.+drop policy if exists "chat_auto_choices: own select" on public.chat_auto_choices;+create policy "chat_auto_choices: own select"+ on public.chat_auto_choices+ for select+ using (+ user_id = auth.uid()+ and organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++drop policy if exists "chat_auto_choices: own insert" on public.chat_auto_choices;+create policy "chat_auto_choices: own insert"+ on public.chat_auto_choices+ for insert+ with check (+ user_id = auth.uid()+ and organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++drop policy if exists "chat_auto_choices: own delete" on public.chat_auto_choices;+create policy "chat_auto_choices: own delete"+ on public.chat_auto_choices+ for delete+ using (user_id = auth.uid());++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 12ccd9670..e7fac9278 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -44043,6 +44043,163 @@ create policy "chat_user_prefs: own update"notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00401_chat_settings.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00401: Chat's settings — each workspace's tool policy and switches, and+-- each person's "Don't ask again" choices+-- ============================================================================+-- The approval precedence (CHAT-20 §5; web lib/chat/precedence.ts) reads both+-- before every tool call Chat makes, behind CHAT_AGENTIC: nothing reads them+-- while the flag is off.+--+-- * chat_settings: one row per workspace (Settings › Chat). Members read+-- it, since Settings › Chat and "What Chat can do" show it to every role;+-- the server writes it (service role), for an Admin. No row = the+-- defaults below: every tool at its registry default, Full auto open to+-- every role the plan allows, "Don't ask again" offered, Managers able to+-- go live after their click.+-- - tool_policies: an Admin's policy per tool, keyed by the tool's+-- label key (the key the browser knows a tool by: a tool's name never+-- reaches a member, CHAT-03 item 22). never · ask · ask_full_auto ·+-- always; the server keeps each within its tool's maximum, so an+-- EXECUTE or an always-card tool is never "always".+-- - full_auto_for_members: people other than Admins may use Full auto+-- (CHAT-23 policy.toggleFullAutoForManagers). The plan decides first:+-- Full auto is Growth and up.+-- - dont_ask_again: "Don't ask again" is offered and the ticks count.+-- Off, everyone's ticks stop at once; they are kept, not deleted.+-- - manager_execute_off: the go-live groups an Admin turned off for+-- Managers (CHAT-20 §4): publishing, email_outreach, code_prs, feeds.+-- * chat_auto_choices: a person's "Don't ask again" ticks, by tool label+-- key, in their workspace. Theirs to read, add and remove (Settings ›+-- Chat › "Your auto changes"). A tick counts only inside what the plan,+-- the role, the policy and the switches allow (precedence step 6), so a+-- row by itself never lets anything run without a card.++-- Whether every value of a tool policy map is a policy, keyed by a label key.+create or replace function public.chat_tool_policies_valid(p_policies jsonb)+returns boolean+language sql+immutable+set search_path = ''+as $$+ select case+ when jsonb_typeof(p_policies) <> 'object' then false+ else coalesce(+ (+ select bool_and(+ e.key ~ '^[a-z][A-Za-z0-9]{1,63}$'+ and e.value in ('never', 'ask', 'ask_full_auto', 'always')+ )+ from jsonb_each_text(p_policies) as e(key, value)+ ),+ true+ )+ end;+$$;++-- ─── A workspace's Chat settings ────────────────────────────────────────────++create table if not exists public.chat_settings (+ organization_id uuid primary key references public.organizations(id) on delete cascade,+ tool_policies jsonb not null default '{}'::jsonb+ check (public.chat_tool_policies_valid(tool_policies)),+ full_auto_for_members boolean not null default true,+ dont_ask_again boolean not null default true,+ manager_execute_off text[] not null default '{}' check (+ manager_execute_off <@ array['publishing', 'email_outreach', 'code_prs', 'feeds']::text[]+ and public.chat_text_array_distinct(manager_execute_off)+ ),+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now()+);++drop trigger if exists trg_chat_settings_updated_at on public.chat_settings;+create trigger trg_chat_settings_updated_at+ before update on public.chat_settings+ for each row execute function public.handle_updated_at();++comment on table public.chat_settings is+ 'Chat (00401): a workspace''s Chat settings (Settings › Chat): tool policies by label key, Full auto for non-Admins, "Don''t ask again", go-live groups off for Managers. Members read; the server writes for an Admin. No row = the defaults.';+comment on column public.chat_settings.tool_policies is+ 'An Admin''s policy per tool, keyed by the tool''s label key (never its name): never, ask, ask_full_auto or always. Held within each tool''s maximum by the server.';++-- ─── A person's "Don't ask again" ticks ─────────────────────────────────────++create table if not exists public.chat_auto_choices (+ user_id uuid not null references auth.users(id) on delete cascade,+ organization_id uuid not null references public.organizations(id) on delete cascade,+ -- The tool's label key, as in chat_settings.tool_policies.+ tool_key text not null check (tool_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ created_at timestamptz not null default now(),+ primary key (user_id, organization_id, tool_key)+);++create index if not exists chat_auto_choices_organization_idx+ on public.chat_auto_choices (organization_id);++comment on table public.chat_auto_choices is+ 'Chat (00401): a person''s "Don''t ask again" ticks, by tool label key, in their workspace. Theirs to read, add and remove; a tick counts only where the plan, role, policy and switches allow Full auto.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_settings enable row level security;+alter table public.chat_auto_choices enable row level security;++revoke all on table public.chat_settings from anon, authenticated;+revoke all on table public.chat_auto_choices from anon, authenticated;++grant select on table public.chat_settings to authenticated;+grant select, insert, delete on table public.chat_auto_choices to authenticated;++grant all on table public.chat_settings to service_role;+grant all on table public.chat_auto_choices to service_role;++-- Members of the workspace read its settings; the server writes them.+drop policy if exists "chat_settings: member select" on public.chat_settings;+create policy "chat_settings: member select"+ on public.chat_settings+ for select+ using (+ organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++-- A person's own ticks, in the workspace they belong to now: one who moved+-- to another workspace doesn't carry them there.+drop policy if exists "chat_auto_choices: own select" on public.chat_auto_choices;+create policy "chat_auto_choices: own select"+ on public.chat_auto_choices+ for select+ using (+ user_id = auth.uid()+ and organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++drop policy if exists "chat_auto_choices: own insert" on public.chat_auto_choices;+create policy "chat_auto_choices: own insert"+ on public.chat_auto_choices+ for insert+ with check (+ user_id = auth.uid()+ and organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++drop policy if exists "chat_auto_choices: own delete" on public.chat_auto_choices;+create policy "chat_auto_choices: own delete"+ on public.chat_auto_choices+ for delete+ using (user_id = auth.uid());++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00404_chat_model_prices.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex a2f2f64d9..768c42ae9 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3180,6 +3180,39 @@"tickPop": "Pops in once"}},+ "chatDenial": {+ "asked": "You asked: {action}.",+ "askedTarget": "You asked: {action} · {target}.",+ "rule": {+ "no_access": "You're not a member of this workspace now, so I can't act in it.",+ "brand_scope": "I can only see the brands shared with you.",+ "subscription_inactive": "This workspace's plan isn't active, so it's read-only: reading still works, but nothing can be changed, run or generated.",+ "demo_brand": "This is the demo brand: its data is sample data, so it can't be changed or run. Make the change on your own brand.",+ "policy_never": "An Admin turned “{action}” off for Chat.",+ "execute_off": "An Admin turned {group, select, publishing {publishing} email_outreach {email and outreach} code_prs {pull requests} other {feed pushes}} off for Managers.",+ "plan_locked": "This needs the {needs} plan. You're on {current}.",+ "plan_locked_trial": "This isn't in the trial. It needs the {needs} plan.",+ "forbidden_role": "Your role is {roleName}, and {rolePlural} can't do this."+ },+ "rolesPlural": {+ "admin": "Admins",+ "manager": "Managers",+ "analyst": "Analysts",+ "agency_partner": "Agency Partners"+ },+ "source": {+ "roles": "Settings › Team › Roles & access",+ "chat": "Settings › Chat",+ "billing": "Settings › Billing"+ },+ "whoCan": {+ "roles": "{roles} can do this.",+ "brands": "Admins can share more brands with you.",+ "noAccess": "Its Admins can add you to it.",+ "choosePlan": "Admins can choose a plan.",+ "demo": "No one: the demo brand keeps its sample data."+ }+ },"audit": {"title": "Site Audit","description": "Score any page against the 48-signal AEO/GEO",diff --git a/web/src/lib/chat/denial.test.ts b/web/src/lib/chat/denial.test.tsnew file mode 100644index 000000000..23b4b3304--- /dev/null+++ b/web/src/lib/chat/denial.test.ts@@ -0,0 +1,257 @@+// @vitest-environment node+import { z } from 'zod';+import { describe, expect, it, vi } from 'vitest';+import type { TeamRole } from '@/components/providers/role-provider';+import { buildDenial, type ChatDenial } from './denial';+import { planFactsFromOrgRow, type OrgPlanRow, type PlanFacts } from './plan-facts';+import { TEAM_ROLES, type ToolDenial } from './precedence';+import { defineTool, type ChatTool, type ToolDefinition } from './registry/define-tool';++/**+ * The out-of-permission answer (CHAT-20 §4c): four parts built on the+ * server, the words from en.json, nothing outside the person's scope.+ */++const base = {+ area: 'content' as const,+ description: 'fixture',+ planGate: null,+ brandOf: null,+ costClass: 'C1' as const,+ route: null,+ mcpTool: null,+ specRow: '0',+ inputSchema: z.object({}),+ run: async () => null,+ fixture: { input: {} },+};+type Def = ToolDefinition<z.ZodObject>;+// Label keys from en.json, so "what was asked" reads as the app names the tool.+const dismiss = defineTool({+ ...base,+ name: 'dismiss_prompt_suggestion',+ labelKey: 'dismissSuggestion',+ class: 'write',+ minRole: 'manager',+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+} as Def);+const draft = defineTool({+ ...base,+ name: 'create_draft',+ labelKey: 'saveDraft',+ class: 'write',+ minRole: 'analyst',+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+} as Def);+const memory = defineTool({+ ...base,+ name: 'workspace_memory',+ labelKey: 'saveDraft',+ class: 'write',+ minRole: 'admin',+ defaultPolicy: 'ask',+ maxPolicy: 'ask',+ flags: { alwaysCard: true },+} as Def);++function factsFor(row: OrgPlanRow): PlanFacts {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ try {+ return planFactsFromOrgRow(row);+ } finally {+ vi.unstubAllEnvs();+ }+}+const STARTER = factsFor({ plan: 'starter', subscription_status: 'active' });+const GROWTH = factsFor({ plan: 'growth', subscription_status: 'active' });+const TRIAL = factsFor({ plan: 'growth', subscription_status: 'trialing' });+const ENDED = factsFor({ plan: 'growth', subscription_status: 'canceled' });++const build = (+ denial: ToolDenial,+ role: TeamRole,+ opts: { tool?: ChatTool; plan?: PlanFacts; target?: string } = {},+): ChatDenial =>+ buildDenial(denial, {+ tool: opts.tool ?? dismiss,+ role,+ plan: opts.plan ?? GROWTH,+ target: opts.target,+ });++const ALL_DENIALS: ToolDenial[] = [+ { code: 'no_access' },+ { code: 'brand_scope' },+ { code: 'subscription_inactive' },+ { code: 'demo_brand' },+ { code: 'policy_never' },+ { code: 'plan_locked', needs: 'growth' },+ { code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] },+ { code: 'execute_off', group: 'publishing' },+];++describe('buildDenial', () => {+ it("answers an Analyst's change with all four parts (§21: forbidden_role)", () => {+ expect(+ build({ code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] }, 'analyst', {+ target: 'Pricing prompts',+ }),+ ).toEqual({+ code: 'forbidden_role',+ status: 403,+ asked: 'You asked: Dismiss prompt suggestions · Pricing prompts.',+ rule: {+ kind: 'role',+ detail: "Your role is Analyst, and Analysts can't do this.",+ source: 'Settings › Team › Roles & access',+ },+ whoCanRoles: ['admin', 'manager'],+ whoCan: 'Admins and Managers can do this.',+ nextActions: ['ask_admin', 'see_access'],+ });+ const partner = build(+ { code: 'forbidden_role', role: 'agency_partner', roles: ['admin', 'manager'] },+ 'agency_partner',+ );+ expect(partner.rule.detail).toBe(+ "Your role is Agency Partner, and Agency Partners can't do this.",+ );+ expect(partner.asked).toBe('You asked: Dismiss prompt suggestions.');+ });++ it('names the roles a row allows, when it leaves one out', () => {+ const denial = build(+ { code: 'forbidden_role', role: 'agency_partner', roles: ['admin', 'manager', 'analyst'] },+ 'agency_partner',+ );+ expect(denial.whoCanRoles).toEqual(['admin', 'manager', 'analyst']);+ expect(denial.whoCan).toBe('Admins, Managers, and Analysts can do this.');+ });++ it('names Admins alone for an Admin-only change', () => {+ const denial = build({ code: 'forbidden_role', role: 'manager', roles: ['admin'] }, 'manager', {+ tool: memory,+ });+ expect(denial.whoCanRoles).toEqual(['admin']);+ expect(denial.whoCan).toBe('Admins can do this.');+ expect(denial.rule.detail).toBe("Your role is Manager, and Managers can't do this.");+ });++ it('words a plan gate against the current plan, with the step up (§7a)', () => {+ const member = build({ code: 'plan_locked', needs: 'growth' }, 'manager', { plan: STARTER });+ expect(member).toMatchObject({+ code: 'plan_locked',+ status: 403,+ rule: {+ kind: 'plan',+ detail: "This needs the Growth plan. You're on Starter.",+ source: 'Settings › Billing',+ },+ whoCanRoles: ['admin'],+ whoCan: 'Admins can do this.',+ nextActions: ['ask_admin', 'compare_plans'],+ plan: {+ needs: 'growth',+ current: 'starter',+ isTrial: false,+ nextPlan: { id: 'growth', name: 'Growth', priceMonthly: 249, priceDiff: 200 },+ },+ });+ const admin = build({ code: 'plan_locked', needs: 'growth' }, 'admin', { plan: STARTER });+ expect(admin.nextActions).toEqual(['upgrade', 'compare_plans']);++ const trial = build({ code: 'plan_locked', needs: 'growth' }, 'admin', { plan: TRIAL });+ expect(trial.rule.detail).toBe("This isn't in the trial. It needs the Growth plan.");+ expect(trial.nextActions).toEqual(['choose_plan', 'compare_plans']);+ expect(trial.plan?.nextPlan).toMatchObject({ id: 'growth', afterTrial: true });+ });++ it('names the policy and says Admins can change it', () => {+ const member = build({ code: 'policy_never' }, 'manager', { tool: draft });+ expect(member.rule).toEqual({+ kind: 'policy',+ detail: 'An Admin turned “Save drafts in Content” off for Chat.',+ source: 'Settings › Chat',+ });+ expect(member.whoCan).toBe('Admins can do this.');+ expect(member.nextActions).toEqual(['ask_admin', 'see_access']);+ expect(build({ code: 'policy_never' }, 'admin').nextActions).toEqual(['open_policy']);++ expect(build({ code: 'execute_off', group: 'publishing' }, 'manager').rule.detail).toBe(+ 'An Admin turned publishing off for Managers.',+ );+ expect(build({ code: 'execute_off', group: 'feeds' }, 'manager').rule.detail).toBe(+ 'An Admin turned feed pushes off for Managers.',+ );+ });++ it('answers a read-only workspace and the demo brand with 402', () => {+ const ended = build({ code: 'subscription_inactive' }, 'analyst', { plan: ENDED });+ expect(ended).toMatchObject({+ status: 402,+ rule: { kind: 'workspace', source: 'Settings › Billing' },+ whoCanRoles: ['admin'],+ whoCan: 'Admins can choose a plan.',+ nextActions: ['ask_admin'],+ });+ expect(build({ code: 'subscription_inactive' }, 'admin').nextActions).toEqual(['choose_plan']);++ expect(build({ code: 'demo_brand' }, 'admin', { target: 'Brewline Coffee' })).toMatchObject({+ status: 402,+ asked: 'You asked: Dismiss prompt suggestions · Brewline Coffee.',+ rule: { kind: 'demo', source: null },+ whoCanRoles: [],+ nextActions: [],+ });+ });++ it('answers a person who is not a member now, without a role or a plan', () => {+ const denial = buildDenial({ code: 'no_access' }, { tool: dismiss, role: null, plan: null });+ expect(denial).toEqual({+ code: 'no_access',+ status: 403,+ asked: 'You asked: Dismiss prompt suggestions.',+ rule: {+ kind: 'workspace',+ detail: "You're not a member of this workspace now, so I can't act in it.",+ source: null,+ },+ whoCanRoles: ['admin'],+ whoCan: 'Its Admins can add you to it.',+ nextActions: [],+ });+ });++ it("names nothing of a brand outside the person's scope", () => {+ const denial = build({ code: 'brand_scope' }, 'agency_partner', {+ target: 'Northwind CRM · Pricing FAQ',+ });+ expect(denial).toEqual({+ code: 'brand_scope',+ status: 403,+ asked: 'You asked: Dismiss prompt suggestions.',+ rule: { kind: 'brand', detail: 'I can only see the brands shared with you.', source: null },+ whoCanRoles: ['admin'],+ whoCan: 'Admins can share more brands with you.',+ nextActions: ['ask_admin', 'see_access'],+ });+ expect(JSON.stringify(denial)).not.toMatch(/Northwind|Pricing FAQ/);+ });++ it('builds every denial for every role in plain words, offering Admins no "Ask your Admin"', () => {+ for (const denial of ALL_DENIALS) {+ for (const role of TEAM_ROLES) {+ const built = build(denial, role, { plan: STARTER });+ for (const text of [built.asked, built.rule.detail, built.whoCan]) {+ expect(text.trim()).not.toBe('');+ // A key en.json lacks comes back as its path; a value left out keeps its braces.+ expect(text).not.toMatch(/chatDenial\.|chatTools\.|[{}]/);+ }+ if (role === 'admin') expect(built.nextActions).not.toContain('ask_admin');+ expect(built.whoCanRoles.every((r) => TEAM_ROLES.includes(r))).toBe(true);+ }+ }+ });+});diff --git a/web/src/lib/chat/denial.ts b/web/src/lib/chat/denial.tsnew file mode 100644index 000000000..bc7780ebd--- /dev/null+++ b/web/src/lib/chat/denial.ts@@ -0,0 +1,205 @@+import { createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import type { TeamRole } from '@/components/providers/role-provider';+import { PLANS, type PlanId } from '@/config/plans';+import type { NextPlan, PlanFacts } from './plan-facts';+import type { ToolDenial } from './precedence';+import type { ChatTool } from './registry/define-tool';++/**+ * The out-of-permission answer (CHAT-20 §4c), built on the server from the+ * precedence's denial, never by the model, which only puts the parts into a+ * sentence. Four parts: what was asked, why not (the rule and where it is+ * set), who can (by role, never a person), and what to do next. MCP and+ * email hosts get the same structure.+ *+ * It names nothing outside the person's scope: a brand they can't access+ * gets "I can only see the brands shared with you", without the brand's+ * name, the call's target or a word on whether it exists. Words from+ * messages/en.json, in English as the rest of what the server writes.+ */++/** The rule behind a denial: §4c's role, plan and policy, and the workspace's own states. */+export type DenialRuleKind = 'brand' | 'workspace' | 'demo' | 'policy' | 'plan' | 'role';++/** The next steps a denial offers, as buttons (§4c part 4). */+export type DenialNextAction =+ | 'ask_admin'+ | 'see_access'+ | 'upgrade'+ | 'choose_plan'+ | 'compare_plans'+ | 'open_policy';++export interface ChatDenial {+ code: ToolDenial['code'];+ /** 402 for a read-only workspace and the demo brand, as the app's own writes answer; else 403. */+ status: 402 | 403;+ /** 1. What was asked: the tool's words, and its target unless that is out of scope. */+ asked: string;+ /** 2. Why not, and where the rule is set (null: nowhere to change it). */+ rule: { kind: DenialRuleKind; detail: string; source: string | null };+ /** 3. Who can, by role. */+ whoCanRoles: TeamRole[];+ whoCan: string;+ /** 4. What to do next. */+ nextActions: DenialNextAction[];+ /** For a plan gate: the plan it needs and the step up (§7a); none on Enterprise. */+ plan?: { needs: PlanId; current: PlanId; isTrial: boolean; nextPlan: NextPlan | null };+}++export interface DenialInput {+ tool: ChatTool;+ /** The person's live role, the one the precedence decided with; null without a context (no_access). */+ role: TeamRole | null;+ /** Null without a context (no_access). */+ plan: PlanFacts | null;+ /** What the call was about, in names the person can see ("Pricing FAQ"). */+ target?: string | null;+}++const t = createTranslator({ locale: 'en', messages, namespace: 'chatDenial' });+const toolT = createTranslator({ locale: 'en', messages, namespace: 'chatTools' });+const roleT = createTranslator({ locale: 'en', messages, namespace: 'settings' });++const roleName = (role: TeamRole) => roleT(`team_role_${role}`);+const planName = (id: PlanId) => PLANS[id].name;++/** Admins never get "Ask your Admin"; everyone else does. */+const askOrOwn = (role: TeamRole | null, own: DenialNextAction[]): DenialNextAction[] =>+ role === 'admin' ? own : ['ask_admin', ...own];++const roleList = new Intl.ListFormat('en-US', { type: 'conjunction' });++/** "Admins can do this.", "Admins and Managers can do this." */+function whoCanText(roles: TeamRole[]): string {+ return t('whoCan.roles', { roles: roleList.format(roles.map((r) => t(`rolesPlural.${r}`))) });+}++/** The four parts of a denial, for the person whose call it refused. */+export function buildDenial(denial: ToolDenial, input: DenialInput): ChatDenial {+ const { tool, role, plan } = input;+ // Every row has its label: the registry's test fails one without.+ const action = toolT(`${tool.labelKey}.name` as never);+ // Out of scope, the target may name the brand: only the tool's own words stay.+ const target = denial.code === 'brand_scope' ? null : input.target?.trim() || null;+ const asked = target ? t('askedTarget', { action, target }) : t('asked', { action });+ const base = { code: denial.code, asked };++ switch (denial.code) {+ case 'no_access':+ return {+ ...base,+ status: 403,+ rule: { kind: 'workspace', detail: t('rule.no_access'), source: null },+ whoCanRoles: ['admin'],+ whoCan: t('whoCan.noAccess'),+ nextActions: [],+ };+ case 'brand_scope':+ return {+ ...base,+ status: 403,+ rule: { kind: 'brand', detail: t('rule.brand_scope'), source: null },+ whoCanRoles: ['admin'],+ whoCan: t('whoCan.brands'),+ nextActions: askOrOwn(role, ['see_access']),+ };+ case 'subscription_inactive':+ return {+ ...base,+ status: 402,+ rule: {+ kind: 'workspace',+ detail: t('rule.subscription_inactive'),+ source: t('source.billing'),+ },+ whoCanRoles: ['admin'],+ whoCan: t('whoCan.choosePlan'),+ nextActions: role === 'admin' ? ['choose_plan'] : ['ask_admin'],+ };+ case 'demo_brand':+ return {+ ...base,+ status: 402,+ rule: { kind: 'demo', detail: t('rule.demo_brand'), source: null },+ whoCanRoles: [],+ whoCan: t('whoCan.demo'),+ nextActions: [],+ };+ case 'policy_never':+ return {+ ...base,+ status: 403,+ rule: {+ kind: 'policy',+ detail: t('rule.policy_never', { action }),+ source: t('source.chat'),+ },+ whoCanRoles: ['admin'],+ whoCan: whoCanText(['admin']),+ nextActions: role === 'admin' ? ['open_policy'] : ['ask_admin', 'see_access'],+ };+ case 'execute_off':+ return {+ ...base,+ status: 403,+ rule: {+ kind: 'policy',+ detail: t('rule.execute_off', { group: denial.group }),+ source: t('source.chat'),+ },+ whoCanRoles: ['admin'],+ whoCan: whoCanText(['admin']),+ nextActions: askOrOwn(role, ['see_access']),+ };+ case 'plan_locked': {+ // A plan gate is only decided with a context, which has the plan.+ if (!plan) throw new Error('A plan gate is refused with the plan it was decided on');+ const needs = planName(denial.needs);+ return {+ ...base,+ status: 403,+ rule: {+ kind: 'plan',+ detail: plan.isTrial+ ? t('rule.plan_locked_trial', { needs })+ : t('rule.plan_locked', { needs, current: plan.planName }),+ source: t('source.billing'),+ },+ whoCanRoles: ['admin'],+ whoCan: whoCanText(['admin']),+ nextActions: askOrOwn(role, [+ ...(role === 'admin'+ ? [plan.isTrial ? ('choose_plan' as const) : ('upgrade' as const)]+ : []),+ 'compare_plans',+ ]),+ plan: {+ needs: denial.needs,+ current: plan.planId,+ isTrial: plan.isTrial,+ nextPlan: plan.nextPlan,+ },+ };+ }+ case 'forbidden_role': {+ const whoCanRoles = [...denial.roles];+ return {+ ...base,+ status: 403,+ rule: {+ kind: 'role',+ detail: t('rule.forbidden_role', {+ roleName: roleName(denial.role),+ rolePlural: t(`rolesPlural.${denial.role}`),+ }),+ source: t('source.roles'),+ },+ whoCanRoles,+ whoCan: whoCanText(whoCanRoles),+ nextActions: askOrOwn(role, ['see_access']),+ };+ }+ }+}diff --git a/web/src/lib/chat/plan-facts.test.ts b/web/src/lib/chat/plan-facts.test.tsnew file mode 100644index 000000000..e780e8d46--- /dev/null+++ b/web/src/lib/chat/plan-facts.test.ts@@ -0,0 +1,106 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { PLANS } from '@/config/plans';+import { planFactsFromOrgRow, planGateLock } from './plan-facts';++/** The plan facts Chat's precedence and denials read (CHAT-20 §7, §20), from config/plans.ts. */++describe('planFactsFromOrgRow on the cloud', () => {+ beforeEach(() => vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true'));+ afterEach(() => vi.unstubAllEnvs());++ it('gives Starter its features, no Full auto, and Growth as the step up', () => {+ const facts = planFactsFromOrgRow({ plan: 'starter', subscription_status: 'active' });+ expect(facts).toMatchObject({+ planId: 'starter',+ planName: 'Starter',+ selfHosted: false,+ isTrial: false,+ writable: true,+ fullAuto: false,+ nextPlan: {+ id: 'growth',+ name: 'Growth',+ priceMonthly: 249,+ priceDiff: 200,+ afterTrial: false,+ },+ });+ expect(facts.features).toEqual(PLANS.starter.limits.features);+ expect(planGateLock(facts, { feature: 'shopping_analytics' })).toBe('growth');+ expect(planGateLock(facts, { minPlan: 'growth' })).toBe('growth');+ expect(planGateLock(facts, { platforms: true })).toBeNull();+ expect(planGateLock(facts, { feature: 'prompt_volumes' })).toBeNull();+ expect(planGateLock(facts, null)).toBeNull();+ });++ it('opens Full auto on Growth, with Enterprise next at a contract price', () => {+ const facts = planFactsFromOrgRow({ plan: 'growth', subscription_status: 'active' });+ expect(facts).toMatchObject({ planId: 'growth', fullAuto: true, writable: true });+ expect(facts.nextPlan).toEqual({+ id: 'enterprise',+ name: 'Enterprise',+ priceMonthly: null,+ priceDiff: null,+ afterTrial: false,+ });+ expect(planGateLock(facts, { minPlan: 'growth' })).toBeNull();+ expect(planGateLock(facts, { minPlan: 'enterprise' })).toBe('enterprise');+ });++ it("keeps the trial to its plan's features, without Full auto or a plan-ranked gate", () => {+ const facts = planFactsFromOrgRow({ plan: 'growth', subscription_status: 'trialing' });+ expect(facts).toMatchObject({+ planId: 'growth',+ isTrial: true,+ writable: true,+ fullAuto: false,+ });+ expect(planGateLock(facts, { feature: 'shopping_analytics' })).toBeNull();+ expect(planGateLock(facts, { minPlan: 'starter' })).toBe('starter');+ expect(facts.nextPlan).toMatchObject({ id: 'growth', priceMonthly: 249, afterTrial: true });+ });++ it('shows no step up on Enterprise, whose trial is a deal and not the trial', () => {+ const facts = planFactsFromOrgRow({ plan: 'enterprise', subscription_status: 'trialing' });+ expect(facts).toMatchObject({ isTrial: false, fullAuto: true, nextPlan: null });+ const overridden = planFactsFromOrgRow({+ plan: 'enterprise',+ subscription_status: 'active',+ plan_overrides: { maxPrompts: 900 },+ });+ expect(overridden.limits.maxPrompts).toBe(900);+ });++ it("marks a plan that isn't active read-only, entitled to Starter's features", () => {+ for (const status of ['canceled', 'past_due', 'incomplete', null]) {+ const facts = planFactsFromOrgRow({ plan: 'growth', subscription_status: status });+ expect(facts).toMatchObject({ planId: 'growth', writable: false, fullAuto: false });+ expect(facts.features).toEqual(PLANS.starter.limits.features);+ }+ });++ it('reads an unknown plan as Starter', () => {+ expect(planFactsFromOrgRow({ plan: 'pro', subscription_status: 'active' }).planId).toBe(+ 'starter',+ );+ });+});++describe('planFactsFromOrgRow self-hosted', () => {+ beforeEach(() => vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false'));+ afterEach(() => vi.unstubAllEnvs());++ it('gates nothing: every feature, Full auto, never read-only, no upsell', () => {+ const facts = planFactsFromOrgRow({ plan: 'starter', subscription_status: 'canceled' });+ expect(facts).toMatchObject({+ planId: 'self_hosted',+ selfHosted: true,+ writable: true,+ fullAuto: true,+ nextPlan: null,+ });+ expect(planGateLock(facts, { minPlan: 'enterprise' })).toBeNull();+ expect(planGateLock(facts, { feature: 'sso_saml' })).toBeNull();+ });+});diff --git a/web/src/lib/chat/plan-facts.ts b/web/src/lib/chat/plan-facts.tsnew file mode 100644index 000000000..9aead6a6f--- /dev/null+++ b/web/src/lib/chat/plan-facts.ts@@ -0,0 +1,142 @@+import {+ PLANS,+ PLAN_ORDER,+ getMinimumPlanForFeature,+ getPlan,+ isCloud,+ isSubscriptionActive,+ type Feature,+ type PlanId,+ type PlanLimits,+} from '@/config/plans';+import { planFromOrgRow } from '@/lib/guards/plan-guard';+import type { PlanGate } from './registry/define-tool';++/**+ * What Chat knows about the workspace's plan (CHAT-20 §7, §20), from one+ * place: config/plans.ts through the organization's row, as the rest of the+ * app reads it (planFromOrgRow: a plan that isn't active gets Starter's+ * limits, Enterprise its overrides). The approval precedence takes its plan+ * gates from here and the denial its plan wording. Self-hosted has no plan+ * gates: every feature, Full auto, never read-only.+ *+ * Server only: the limits hold the AI budgets in dollars, which never reach+ * a browser (DECISIONS R).+ */++/** The step up from the current plan, for a plan gate's "With … you'd also get" (§7a). */+export interface NextPlan {+ id: PlanId;+ name: string;+ /** Its monthly price in dollars; null when set per contract (Enterprise). */+ priceMonthly: number | null;+ /** What it costs a month more than the current plan; null when either price isn't listed. */+ priceDiff: number | null;+ /** On the trial: paying for the trial's own plan is the next step ("After your trial"). */+ afterTrial: boolean;+}++export interface PlanFacts {+ /** The plan the workspace's row names; `self_hosted` off the cloud. */+ planId: PlanId;+ planName: string;+ selfHosted: boolean;+ /** In the free trial. An Enterprise trial is a deal's and keeps its plan, as the server's AI budget has it. */+ isTrial: boolean;+ /** False while the plan isn't active (trial ended, canceled, payment failed): the read-only workspace. */+ writable: boolean;+ /** What the workspace is entitled to: while not active, Starter's. */+ features: readonly Feature[];+ limits: PlanLimits;+ /** Full auto and "Don't ask again" (§7): Growth and up, paid, active. */+ fullAuto: boolean;+ /** Null on Enterprise and self-hosted: no upsell (§7a). */+ nextPlan: NextPlan | null;+}++/** The organization columns the facts read (plan-guard's ORG_PLAN_COLUMNS). */+export type OrgPlanRow = {+ plan?: unknown;+ subscription_status?: unknown;+ plan_overrides?: unknown;+} | null;++const rank = (id: PlanId) => PLAN_ORDER.indexOf(id);++function nextPlanOf(id: PlanId, isTrial: boolean): NextPlan | null {+ const own = PLANS[id];+ if (isTrial) {+ return {+ id,+ name: own.name,+ priceMonthly: own.pricing?.monthly ?? null,+ priceDiff: null,+ afterTrial: true,+ };+ }+ const nextId = PLAN_ORDER[rank(id) + 1];+ if (rank(id) < 0 || !nextId) return null;+ const next = PLANS[nextId];+ const ownPrice = own.pricing?.monthly;+ const nextPrice = next.pricing?.monthly;+ return {+ id: nextId,+ name: next.name,+ priceMonthly: nextPrice ?? null,+ priceDiff: ownPrice !== undefined && nextPrice !== undefined ? nextPrice - ownPrice : null,+ afterTrial: false,+ };+}++/** The facts for an organization row with its plan columns (plan-guard's ORG_PLAN_COLUMNS). */+export function planFactsFromOrgRow(row: OrgPlanRow): PlanFacts {+ if (!isCloud()) {+ const plan = PLANS.self_hosted;+ return {+ planId: plan.id,+ planName: plan.name,+ selfHosted: true,+ isTrial: false,+ writable: true,+ features: plan.limits.features,+ limits: plan.limits,+ fullAuto: true,+ nextPlan: null,+ };+ }+ const status = row?.subscription_status as string | null | undefined;+ const own = getPlan(row?.plan as string | null | undefined);+ const entitled = planFromOrgRow(row);+ const writable = isSubscriptionActive(status);+ const isTrial = status === 'trialing' && own.id !== 'enterprise';+ return {+ planId: own.id,+ planName: own.name,+ selfHosted: false,+ isTrial,+ writable,+ features: entitled.limits.features,+ limits: entitled.limits,+ fullAuto: writable && !isTrial && rank(own.id) >= rank('growth'),+ nextPlan: nextPlanOf(own.id, isTrial),+ };+}++/**+ * The plan a tool's gate needs that the workspace doesn't have, or null when+ * it passes. A feature gate follows the entitled plan's features (the trial+ * has its plan's); a plan-ranked gate needs that plan paid, so the trial+ * doesn't open it (§7: Full auto, own keys, MCP and Open pull request are+ * locked in the trial). A platforms gate is open on every plan: the data+ * covers the plan's platforms.+ */+export function planGateLock(facts: PlanFacts, gate: PlanGate | null): PlanId | null {+ if (!gate || facts.selfHosted) return null;+ if (gate.feature && !facts.features.includes(gate.feature)) {+ return getMinimumPlanForFeature(gate.feature);+ }+ if (gate.minPlan && (facts.isTrial || rank(facts.planId) < rank(gate.minPlan))) {+ return gate.minPlan;+ }+ return null;+}diff --git a/web/src/lib/chat/precedence-context.test.ts b/web/src/lib/chat/precedence-context.test.tsnew file mode 100644index 000000000..2b65576f4--- /dev/null+++ b/web/src/lib/chat/precedence-context.test.ts@@ -0,0 +1,281 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { Database } from '@/types/supabase';+import type { BrandLookupTable } from './registry/define-tool';++/**+ * The precedence's facts, read fresh for every call with the service role:+ * the live role above all (CHAT-20 §4, §21), the plan, the workspace's Chat+ * settings and the person's ticks.+ */++const ORG = '11111111-1111-4111-8111-111111111111';+const OTHER_ORG = '33333333-3333-4333-8333-333333333333';+const USER = 'user-1';++type Result = { data: unknown; error: { message: string } | null };+type Filters = [string, unknown][];+const db = vi.hoisted(() => ({+ /** A table's rows, or a function of the read's filters for one that answers per id. */+ tables: {} as Record<string, unknown>,+ errors: {} as Record<string, string>,+ reads: [] as { table: string; filters: [string, unknown][] }[],+}));++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from(table: string) {+ const read = { table, filters: [] as [string, unknown][] };+ db.reads.push(read);+ const rows = () => {+ const value = db.tables[table];+ return typeof value === 'function'+ ? (value as (f: Filters) => unknown)(read.filters)+ : value;+ };+ const result = (): Result => ({+ data: rows() ?? null,+ error: db.errors[table] ? { message: db.errors[table] } : null,+ });+ const builder = {+ select: () => builder,+ eq: (column: string, value: unknown) => {+ read.filters.push([column, value]);+ return builder;+ },+ maybeSingle: async () => result(),+ then: (resolve: (r: Result) => unknown) =>+ resolve({ ...result(), data: (rows() as unknown[]) ?? [] }),+ };+ return builder;+ },+ },+}));++const {+ readPrecedenceContext,+ readToolCall,+ resolveCallBrand,+ parseChatSettings,+ readBrandIsDemo,+} = await import('./precedence-context');+const { decideToolCall, DEFAULT_CHAT_SETTINGS } = await import('./precedence');+const { defineTool } = await import('./registry/define-tool');+const { z } = await import('zod');++const addPrompts = defineTool({+ name: 'add_prompts',+ class: 'write',+ area: 'prompts',+ description: 'fixture',+ minRole: 'manager',+ planGate: null,+ brandOf: null,+ costClass: 'C1',+ labelKey: 'addPrompts',+ route: null,+ mcpTool: null,+ specRow: '20',+ inputSchema: z.object({}),+ run: async () => null,+ fixture: { input: {} },+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+});++const request = {+ userId: USER,+ organizationId: ORG,+ mode: 'auto' as const,+ surface: 'chat' as const,+};++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ db.tables = {+ profiles: { role: 'manager', organization_id: ORG },+ organizations: { plan: 'growth', subscription_status: 'active', plan_overrides: null },+ chat_settings: null,+ chat_auto_choices: [],+ };+ db.errors = {};+ db.reads = [];+});+afterEach(() => vi.unstubAllEnvs());++describe('readPrecedenceContext', () => {+ it("reads the person's role again for every call: a role changed mid-run counts at once", async () => {+ const first = await readPrecedenceContext(request);+ expect(first?.role).toBe('manager');+ expect(+ decideToolCall(addPrompts, first!, { brandId: null, brandIsDemo: false, tainted: false }),+ ).toMatchObject({ kind: 'ask' });++ // An Admin makes them an Analyst while the run goes on.+ db.tables.profiles = { role: 'analyst', organization_id: ORG };+ const next = await readPrecedenceContext(request);+ expect(next?.role).toBe('analyst');+ expect(+ decideToolCall(addPrompts, next!, { brandId: null, brandIsDemo: false, tainted: false }),+ ).toEqual({+ kind: 'deny',+ denial: { code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] },+ });+ // From the profile, by the person's id, each time.+ const profileReads = db.reads.filter((read) => read.table === 'profiles');+ expect(profileReads).toHaveLength(2);+ expect(profileReads[1].filters).toEqual([['id', USER]]);+ });++ it('acts with live roles only, and only in the workspace the person belongs to now', async () => {+ for (const role of ['owner', 'editor', 'viewer', null]) {+ db.tables.profiles = { role, organization_id: ORG };+ expect(await readPrecedenceContext(request)).toBeNull();+ }+ db.tables.profiles = { role: 'admin', organization_id: OTHER_ORG };+ expect(await readPrecedenceContext(request)).toBeNull();+ db.tables.profiles = null;+ expect(await readPrecedenceContext(request)).toBeNull();+ });++ it('reads the plan, the settings and the ticks of this person in this workspace', async () => {+ db.tables.organizations = { plan: 'starter', subscription_status: 'active' };+ db.tables.chat_settings = {+ tool_policies: { saveDraft: 'always', addPrompts: 'never', brands: 'click' },+ full_auto_for_members: false,+ dont_ask_again: false,+ manager_execute_off: ['publishing', 'merging'],+ };+ db.tables.chat_auto_choices = [{ tool_key: 'saveDraft' }];+ const context = await readPrecedenceContext({ ...request, injectionDetected: true });+ expect(context).toMatchObject({+ role: 'manager',+ plan: { planId: 'starter', fullAuto: false },+ settings: {+ toolPolicies: { saveDraft: 'always', addPrompts: 'never' },+ fullAutoForMembers: false,+ dontAskAgain: false,+ managerExecuteOff: ['publishing'],+ },+ mode: 'auto',+ surface: 'chat',+ brandAccess: 'all',+ injectionDetected: true,+ });+ expect([...context!.autoChoices]).toEqual(['saveDraft']);+ const choices = db.reads.find((read) => read.table === 'chat_auto_choices');+ expect(choices?.filters).toEqual([+ ['user_id', USER],+ ['organization_id', ORG],+ ]);+ });++ it('reads a mode or a surface it does not know as the closed side', async () => {+ const context = await readPrecedenceContext({+ ...request,+ mode: 'yolo' as never,+ surface: 'email' as never,+ });+ expect(context).toMatchObject({ organizationId: ORG, mode: 'ask_first', surface: 'mcp' });+ expect(+ await readPrecedenceContext({ ...request, mode: 'full_auto', surface: 'mcp' }),+ ).toMatchObject({ mode: 'full_auto', surface: 'mcp' });+ });++ it('decides on the defaults when the workspace has no settings row', async () => {+ const context = await readPrecedenceContext(request);+ expect(context?.settings).toEqual(DEFAULT_CHAT_SETTINGS);+ expect(parseChatSettings(null)).toBe(DEFAULT_CHAT_SETTINGS);+ });++ it('decides nothing on a read that failed', async () => {+ db.errors.chat_settings = 'timeout';+ await expect(readPrecedenceContext(request)).rejects.toThrow(/timeout/);+ });+});++// The demo chain (#1734, 00380) adds brands.is_demo. This stops compiling then, so the demo+// flag gets wired to it (readBrandIsDemo) in the same change.+type BrandRow = Database['public']['Tables']['brands']['Row'];+const demoColumnNotYetThere: 'is_demo' extends keyof BrandRow ? never : true = true;++// Every table a row looks its brand up in has brand_id; a new one that lacks it doesn't compile.+type Tables = Database['public']['Tables'];+const lookupTablesNameTheirBrand: {+ [T in BrandLookupTable]: 'brand_id' extends keyof Tables[T]['Row'] ? true : never;+} = {+ actions: true,+ content_drafts: true,+ content_opportunities: true,+ prompt_results: true,+ prompt_suggestions: true,+ site_audits: true,+};++const BRAND_A = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const BRAND_ELSEWHERE = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';+const OPPORTUNITY = '44444444-4444-4444-8444-444444444444';++/** brands: found only for brand A, in ORG. content_opportunities: the opportunity's brand. */+function seedBrands(opportunityBrand: string | null = BRAND_A) {+ const filter = (filters: Filters, column: string) => filters.find(([c]) => c === column)?.[1];+ db.tables.brands = (filters: Filters) =>+ filter(filters, 'id') === BRAND_A && filter(filters, 'organization_id') === ORG+ ? { id: BRAND_A }+ : null;+ db.tables.content_opportunities = (filters: Filters) =>+ filter(filters, 'id') === OPPORTUNITY && opportunityBrand+ ? { brand_id: opportunityBrand }+ : null;+}++const byInput = { brandOf: { input: 'brand_id' } as const };+const byLookup = {+ brandOf: { lookup: 'content_opportunities', idField: 'opportunity_id' } as const,+};++describe("a call's brand", () => {+ beforeEach(() => seedBrands());++ it("is the input's brand_id, found in the person's workspace", async () => {+ expect(await resolveCallBrand(byInput, { brand_id: BRAND_A }, ORG)).toBe(BRAND_A);+ // Another workspace's brand id doesn't pass for 'all'.+ expect(await resolveCallBrand(byInput, { brand_id: BRAND_ELSEWHERE }, ORG)).toBeNull();+ expect(await resolveCallBrand(byInput, { brand_id: BRAND_A }, OTHER_ORG)).toBeNull();+ expect(await resolveCallBrand(byInput, {}, ORG)).toBeNull();+ expect(await resolveCallBrand({ brandOf: null }, { brand_id: BRAND_A }, ORG)).toBeNull();+ });++ it("is the brand of the row an id names, for a row that takes an object's id", async () => {+ expect(await resolveCallBrand(byLookup, { opportunity_id: OPPORTUNITY }, ORG)).toBe(BRAND_A);+ const lookup = db.reads.find((read) => read.table === 'content_opportunities');+ expect(lookup?.filters).toEqual([['id', OPPORTUNITY]]);+ expect(await resolveCallBrand(byLookup, { opportunity_id: BRAND_ELSEWHERE }, ORG)).toBeNull();+ seedBrands(BRAND_ELSEWHERE);+ expect(await resolveCallBrand(byLookup, { opportunity_id: OPPORTUNITY }, ORG)).toBeNull();+ });++ it("is refused when it isn't found: an object of another workspace stays out of reach", async () => {+ const context = (await readPrecedenceContext({ ...request }))!;+ seedBrands(BRAND_ELSEWHERE);+ const toolCall = await readToolCall(context, byLookup, { opportunity_id: OPPORTUNITY }, false);+ expect(toolCall).toEqual({ brandId: null, brandIsDemo: false, tainted: false });+ const updateOpportunity = { ...addPrompts, ...byLookup };+ expect(decideToolCall(updateOpportunity, context, toolCall)).toEqual({+ kind: 'deny',+ denial: { code: 'brand_scope' },+ });+ });++ it('reads the demo flag, false until the demo chain merges', async () => {+ expect(demoColumnNotYetThere).toBe(true);+ expect(Object.values(lookupTablesNameTheirBrand).every(Boolean)).toBe(true);+ expect(await readBrandIsDemo(BRAND_A)).toBe(false);+ const context = (await readPrecedenceContext(request))!;+ expect(await readToolCall(context, byInput, { brand_id: BRAND_A }, true)).toEqual({+ brandId: BRAND_A,+ brandIsDemo: false,+ tainted: true,+ });+ });+});diff --git a/web/src/lib/chat/precedence-context.ts b/web/src/lib/chat/precedence-context.tsnew file mode 100644index 000000000..280c99927--- /dev/null+++ b/web/src/lib/chat/precedence-context.ts@@ -0,0 +1,202 @@+import { ORG_PLAN_COLUMNS } from '@/lib/guards/plan-guard';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { Database } from '@/types/supabase';+import { planFactsFromOrgRow } from './plan-facts';+import {+ ADMIN_POLICIES,+ CHAT_MODES,+ CHAT_SURFACES,+ DEFAULT_CHAT_SETTINGS,+ parseTeamRole,+ type AdminPolicy,+ type ChatMode,+ type ChatSettings,+ type ChatSurface,+ type PrecedenceContext,+ type ToolCall,+} from './precedence';+import { EXECUTE_GROUPS, type ChatTool, type ExecuteGroup } from './registry/define-tool';++/**+ * What the approval precedence decides on, read fresh for each tool call:+ * the person's live role, the workspace's plan, its Chat settings and the+ * person's "Don't ask again" ticks. Nothing is kept between calls, so a role,+ * a plan or a setting changed mid-run counts from the next call (CHAT-20 §4).+ * Read with the service role: these are the server's facts, and a scheduled+ * run has no session (CHAT-12). Server only.+ */++export interface PrecedenceRequest {+ userId: string;+ organizationId: string;+ /** Checked against CHAT_MODES: one it doesn't know is Ask me first. */+ mode: ChatMode;+ /** Checked against CHAT_SURFACES: one it doesn't know is MCP's, the closed side. */+ surface: ChatSurface;+ /** An injection attempt was found earlier in the run. */+ injectionDetected?: boolean;+}++type SettingsRow = Pick<+ Database['public']['Tables']['chat_settings']['Row'],+ 'tool_policies' | 'full_auto_for_members' | 'dont_ask_again' | 'manager_execute_off'+>;++/** A chat_settings row as the precedence reads it; no row, the defaults. Unknown values are dropped. */+export function parseChatSettings(row: SettingsRow | null): ChatSettings {+ if (!row) return DEFAULT_CHAT_SETTINGS;+ const toolPolicies: Record<string, AdminPolicy> = {};+ const raw = row.tool_policies;+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {+ for (const [key, value] of Object.entries(raw)) {+ const policy = ADMIN_POLICIES.find((p) => p === value);+ if (policy) toolPolicies[key] = policy;+ }+ }+ return {+ toolPolicies,+ fullAutoForMembers: row.full_auto_for_members,+ dontAskAgain: row.dont_ask_again,+ managerExecuteOff: row.manager_execute_off.filter((group): group is ExecuteGroup =>+ EXECUTE_GROUPS.some((known) => known === group),+ ),+ };+}++/**+ * The brands a person may use. Every member uses every brand of their+ * workspace today, as the app does: sharing chosen brands with an Agency+ * partner is a Team feature of Wave 2, and until then they act as Analysts.+ */+export async function readBrandAccess(+ userId: string,+ organizationId: string,+): Promise<PrecedenceContext['brandAccess']> {+ void userId;+ void organizationId;+ return 'all';+}++/**+ * Whether a brand is the demo brand of sample data. Always false for now:+ * TODO wire to brands.is_demo when #1734 merges (the demo chain, 00380),+ * as the server's demo guard reads it.+ */+export async function readBrandIsDemo(brandId: string): Promise<boolean> {+ void brandId;+ return false;+}++/**+ * The context for one call, or null when the person can't act in that+ * workspace now: no profile, a profile in another workspace (removed or+ * moved), or a role that isn't a live one. A read that fails throws, so no+ * call is decided on missing facts.+ */+export async function readPrecedenceContext(+ req: PrecedenceRequest,+): Promise<PrecedenceContext | null> {+ const [profile, org, settings, choices, brandAccess] = await Promise.all([+ supabaseAdmin+ .from('profiles')+ .select('role, organization_id')+ .eq('id', req.userId)+ .maybeSingle(),+ supabaseAdmin+ .from('organizations')+ .select(ORG_PLAN_COLUMNS)+ .eq('id', req.organizationId)+ .maybeSingle(),+ supabaseAdmin+ .from('chat_settings')+ .select('tool_policies, full_auto_for_members, dont_ask_again, manager_execute_off')+ .eq('organization_id', req.organizationId)+ .maybeSingle(),+ supabaseAdmin+ .from('chat_auto_choices')+ .select('tool_key')+ .eq('user_id', req.userId)+ .eq('organization_id', req.organizationId),+ readBrandAccess(req.userId, req.organizationId),+ ]);+ for (const result of [profile, org, settings, choices]) {+ if (result.error) throw new Error(`Could not read Chat's permissions: ${result.error.message}`);+ }++ const role = parseTeamRole(profile.data?.role);+ if (!role || profile.data?.organization_id !== req.organizationId || !org.data) return null;++ return {+ organizationId: req.organizationId,+ role,+ plan: planFactsFromOrgRow(org.data),+ settings: parseChatSettings(settings.data),+ mode: CHAT_MODES.find((mode) => mode === req.mode) ?? 'ask_first',+ surface: CHAT_SURFACES.find((surface) => surface === req.surface) ?? 'mcp',+ autoChoices: new Set((choices.data ?? []).map((row) => row.tool_key)),+ brandAccess,+ injectionDetected: req.injectionDetected ?? false,+ };+}++/**+ * The brand a call is about, found in the person's workspace: the input's+ * brand_id, or the brand of the row its id names (the row's brandOf). Null+ * when the row is about no brand, when the input names none, or when the+ * brand isn't one of this workspace's, an id of another workspace's object+ * included: the precedence refuses a brand-bound call without one+ * (brand_scope), so 'all' never reaches past the workspace.+ */+export async function resolveCallBrand(+ tool: Pick<ChatTool, 'brandOf'>,+ input: Record<string, unknown>,+ organizationId: string,+): Promise<string | null> {+ const brandOf = tool.brandOf;+ if (!brandOf) return null;+ let brandId: unknown;+ if ('input' in brandOf) {+ brandId = input[brandOf.input];+ } else {+ const id = input[brandOf.idField];+ if (typeof id !== 'string' || !id) return null;+ // Every lookup table has brand_id; the client's types take one table at a time.+ const { data, error } = await supabaseAdmin+ .from(brandOf.lookup as 'actions')+ .select('brand_id')+ .eq('id', id)+ .maybeSingle();+ if (error) throw new Error(`Could not read the call's brand: ${error.message}`);+ brandId = data?.brand_id;+ }+ if (typeof brandId !== 'string' || !brandId) return null;+ const { data, error } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', organizationId)+ .maybeSingle();+ if (error) throw new Error(`Could not read the call's brand: ${error.message}`);+ return data ? brandId : null;+}++/**+ * A call as the precedence takes it: its brand found in the workspace, and+ * that brand's demo flag, read only for a brand in the person's scope (one+ * outside it is refused before its state matters).+ */+export async function readToolCall(+ ctx: PrecedenceContext,+ tool: Pick<ChatTool, 'brandOf'>,+ input: Record<string, unknown>,+ tainted: boolean,+): Promise<ToolCall> {+ const brandId = await resolveCallBrand(tool, input, ctx.organizationId);+ const inScope =+ brandId !== null && (ctx.brandAccess === 'all' || ctx.brandAccess.includes(brandId));+ return {+ brandId,+ brandIsDemo: inScope ? await readBrandIsDemo(brandId) : false,+ tainted,+ };+}diff --git a/web/src/lib/chat/precedence.test.ts b/web/src/lib/chat/precedence.test.tsnew file mode 100644index 000000000..cb086699a--- /dev/null+++ b/web/src/lib/chat/precedence.test.ts@@ -0,0 +1,1306 @@+// @vitest-environment node+import { z } from 'zod';+import { describe, expect, it, vi } from 'vitest';+import type { TeamRole } from '@/components/providers/role-provider';+import { planFactsFromOrgRow, type OrgPlanRow, type PlanFacts } from './plan-facts';+import {+ CHAT_MODES,+ CHAT_SURFACES,+ DEFAULT_CHAT_SETTINGS,+ TEAM_ROLES,+ allowedTools,+ decideOrDeny,+ decideToolCall,+ effectivePolicy,+ parseTeamRole,+ policyChoiceLock,+ policyChoices,+ roleAllowed,+ type AdminPolicy,+ type ChatSettings,+ type PrecedenceContext,+ type ToolCall,+ type ToolDecision,+} from './precedence';+import { defineTool, type ChatTool, type ToolDefinition } from './registry/define-tool';++/**+ * The approval precedence (CHAT-20 §5) against a fixture table of rows, one+ * per kind of tool, and every combination of role, plan, mode, surface,+ * policy, tick, taint and brand state: permission correctness is 100% or+ * nothing (§19). One test per acceptance criterion of §21 it covers.+ */++// ─── Fixture rows ───────────────────────────────────────────────────────────++const base = {+ area: 'content' as const,+ description: 'fixture',+ planGate: null,+ costClass: 'C1' as const,+ route: null,+ mcpTool: null,+ specRow: '0',+ // Most rows are about a brand, named in the input (the registry's usual brandOf).+ brandOf: { input: 'brand_id' as const },+ inputSchema: z.object({ brand_id: z.string() }),+ run: async () => null,+ fixture: { input: { brand_id: 'brand' } },+};++type Def = ToolDefinition<z.ZodObject>;+const row = (name: string, def: Partial<Def> & Pick<Def, 'class'>): ChatTool =>+ defineTool({ ...base, name, labelKey: name, minRole: 'analyst', ...def } as Def);++const ROWS = {+ // About no brand: the person or the workspace (a profile, usage).+ read: row('read', { class: 'read', brandOf: null }),+ readOff: row('readOff', { class: 'read', flags: { adminMayTurnOff: true } }),+ readSpends: row('readSpends', { class: 'read', minRole: 'manager', costClass: 'C2' }),+ readShopping: row('readShopping', {+ class: 'read',+ planGate: { feature: 'shopping_analytics' },+ }),+ readPlatforms: row('readPlatforms', { class: 'read', planGate: { platforms: true } }),+ // Daily work: open to every role (the role model of 2026-10-29).+ draft: row('draft', {+ class: 'write',+ costClass: 'C2',+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+ }),+ // Daily work the server refuses Agency partners (#1762, #1763).+ dismiss: row('dismiss', {+ class: 'write',+ excludeRoles: ['agency_partner'],+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+ }),+ addPrompts: row('addPrompts', {+ class: 'write',+ minRole: 'manager',+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+ }),+ schedule: row('schedule', {+ class: 'write',+ minRole: 'manager',+ defaultPolicy: 'ask',+ maxPolicy: 'ask',+ }),+ removeCompetitor: row('removeCompetitor', {+ class: 'write',+ minRole: 'manager',+ defaultPolicy: 'ask',+ maxPolicy: 'ask',+ flags: { alwaysCard: true },+ }),+ workspaceMemory: row('workspaceMemory', {+ class: 'write',+ minRole: 'admin',+ defaultPolicy: 'ask',+ maxPolicy: 'ask',+ flags: { alwaysCard: true },+ }),+ growthWrite: row('growthWrite', {+ class: 'write',+ minRole: 'manager',+ planGate: { minPlan: 'growth' },+ defaultPolicy: 'ask_full_auto',+ maxPolicy: 'always',+ }),+ publish: row('publish', { class: 'execute', minRole: 'manager', executeGroup: 'publishing' }),+ openPr: row('openPr', {+ class: 'execute',+ minRole: 'manager',+ executeGroup: 'code_prs',+ planGate: { minPlan: 'growth' },+ }),+} satisfies Record<string, ChatTool>;+const ALL_ROWS: ChatTool[] = Object.values(ROWS);++// ─── Plans and contexts ─────────────────────────────────────────────────────++function factsFor(orgRow: OrgPlanRow, cloud = true): PlanFacts {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', cloud ? 'true' : 'false');+ try {+ return planFactsFromOrgRow(orgRow);+ } finally {+ vi.unstubAllEnvs();+ }+}++const PLAN = {+ starter: factsFor({ plan: 'starter', subscription_status: 'active' }),+ growth: factsFor({ plan: 'growth', subscription_status: 'active' }),+ enterprise: factsFor({ plan: 'enterprise', subscription_status: 'active' }),+ trial: factsFor({ plan: 'growth', subscription_status: 'trialing' }),+ readOnly: factsFor({ plan: 'growth', subscription_status: 'canceled' }),+ selfHosted: factsFor(null, false),+};+type PlanKey = keyof typeof PLAN;++function ctx(over: Partial<PrecedenceContext> & { planKey?: PlanKey } = {}): PrecedenceContext {+ const { planKey = 'growth', ...rest } = over;+ return {+ organizationId: 'org-1',+ role: 'manager',+ plan: PLAN[planKey],+ settings: DEFAULT_CHAT_SETTINGS,+ mode: 'auto',+ surface: 'chat',+ autoChoices: new Set(),+ brandAccess: 'all',+ injectionDetected: false,+ ...rest,+ };+}++const settings = (over: Partial<ChatSettings>): ChatSettings => ({+ ...DEFAULT_CHAT_SETTINGS,+ ...over,+});++const BRAND_A = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const BRAND_B = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+const call = (over: Partial<ToolCall> = {}): ToolCall => ({+ brandId: BRAND_A,+ brandIsDemo: false,+ tainted: false,+ ...over,+});++const RUN_READ: ToolDecision = { kind: 'run', via: 'read' };+const CLICK: ToolDecision = { kind: 'click' };+const ask = (reason: string, offerDontAskAgain = false): ToolDecision =>+ ({ kind: 'ask', reason, offerDontAskAgain }) as ToolDecision;+const deny = (denial: object): ToolDecision => ({ kind: 'deny', denial }) as ToolDecision;++// ─── The fixture table ──────────────────────────────────────────────────────++const TABLE: [string, ChatTool, PrecedenceContext, ToolCall, ToolDecision][] = [+ // Reads+ ['a read runs for every role', ROWS.read, ctx({ role: 'agency_partner' }), call(), RUN_READ],+ ['a read runs on Starter', ROWS.read, ctx({ planKey: 'starter' }), call(), RUN_READ],+ ['a read runs while read-only', ROWS.read, ctx({ planKey: 'readOnly' }), call(), RUN_READ],+ ['a read runs on the demo brand', ROWS.read, ctx(), call({ brandIsDemo: true }), RUN_READ],+ [+ 'a platforms read is open on Starter',+ ROWS.readPlatforms,+ ctx({ planKey: 'starter' }),+ call(),+ RUN_READ,+ ],+ [+ 'a read an Admin turned off is refused',+ ROWS.readOff,+ ctx({ settings: settings({ toolPolicies: { readOff: 'never' } }) }),+ call(),+ deny({ code: 'policy_never' }),+ ],+ [+ 'a read an Admin may not turn off keeps running',+ ROWS.read,+ ctx({ settings: settings({ toolPolicies: { read: 'never' } }) }),+ call(),+ RUN_READ,+ ],+ [+ 'a feature read is locked on Starter',+ ROWS.readShopping,+ ctx({ planKey: 'starter' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'a feature read follows the trial plan',+ ROWS.readShopping,+ ctx({ planKey: 'trial' }),+ call(),+ RUN_READ,+ ],+ [+ 'a read that spends is refused while read-only',+ ROWS.readSpends,+ ctx({ planKey: 'readOnly' }),+ call(),+ deny({ code: 'subscription_inactive' }),+ ],+ [+ 'a read that spends is refused on the demo brand',+ ROWS.readSpends,+ ctx(),+ call({ brandIsDemo: true }),+ deny({ code: 'demo_brand' }),+ ],+ [+ 'a manager read is refused to an Analyst',+ ROWS.readSpends,+ ctx({ role: 'analyst' }),+ call(),+ deny({ code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] }),+ ],+ // Writes: modes+ ['Auto asks before a change, offering the tick', ROWS.draft, ctx(), call(), ask('mode', true)],+ [+ 'Ask me first asks, without the tick',+ ROWS.draft,+ ctx({ mode: 'ask_first' }),+ call(),+ ask('mode'),+ ],+ [+ 'Full auto runs a routine change',+ ROWS.draft,+ ctx({ mode: 'full_auto' }),+ call(),+ { kind: 'run', via: 'full_auto' },+ ],+ // Always (decision of 2026-10-29): no card in Auto or Full auto; Ask me first still asks.+ [+ 'Full auto runs a policy Always change',+ ROWS.addPrompts,+ ctx({ mode: 'full_auto', settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ { kind: 'run', via: 'always' },+ ],+ [+ 'Auto runs a policy Always change without a card',+ ROWS.addPrompts,+ ctx({ settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ { kind: 'run', via: 'always' },+ ],+ [+ 'Ask me first asks even for a policy Always change',+ ROWS.addPrompts,+ ctx({ mode: 'ask_first', settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ ask('mode'),+ ],+ [+ "Always asks on Starter, under Full auto's plan lock",+ ROWS.addPrompts,+ ctx({ planKey: 'starter', settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ ask('full_auto_locked'),+ ],+ [+ 'Always asks in the trial',+ ROWS.addPrompts,+ ctx({+ planKey: 'trial',+ mode: 'full_auto',+ settings: settings({ toolPolicies: { addPrompts: 'always' } }),+ }),+ call(),+ ask('full_auto_locked'),+ ],+ [+ "MCP's plan gate refuses an Always write on Starter",+ ROWS.addPrompts,+ ctx({+ planKey: 'starter',+ surface: 'mcp',+ settings: settings({ toolPolicies: { addPrompts: 'always' } }),+ }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'Always runs on self-hosted',+ ROWS.addPrompts,+ ctx({ planKey: 'selfHosted', settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ { kind: 'run', via: 'always' },+ ],+ [+ 'Always runs for a Manager with Full auto off for members',+ ROWS.addPrompts,+ ctx({+ settings: settings({ toolPolicies: { addPrompts: 'always' }, fullAutoForMembers: false }),+ }),+ call(),+ { kind: 'run', via: 'always' },+ ],+ [+ 'an MCP write set to Always asks',+ ROWS.addPrompts,+ ctx({ surface: 'mcp', settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ ask('mcp'),+ ],+ [+ 'a tainted write set to Always asks',+ ROWS.addPrompts,+ ctx({ settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call({ tainted: true }),+ ask('tainted'),+ ],+ [+ "Full auto asks where the Admin's policy is Ask",+ ROWS.addPrompts,+ ctx({ mode: 'full_auto', settings: settings({ toolPolicies: { addPrompts: 'ask' } }) }),+ call(),+ ask('policy'),+ ],+ [+ 'a tool fixed at Ask asks in Full auto',+ ROWS.schedule,+ ctx({ mode: 'full_auto' }),+ call(),+ ask('policy'),+ ],+ [+ 'Full auto is locked on Starter (§5a example 2)',+ ROWS.addPrompts,+ ctx({ planKey: 'starter', mode: 'full_auto' }),+ call(),+ ask('full_auto_locked'),+ ],+ [+ 'Full auto is locked in the trial',+ ROWS.addPrompts,+ ctx({ planKey: 'trial', mode: 'full_auto' }),+ call(),+ ask('full_auto_locked'),+ ],+ [+ 'Full auto runs for an Admin with Full auto off for members',+ ROWS.addPrompts,+ ctx({ role: 'admin', mode: 'full_auto', settings: settings({ fullAutoForMembers: false }) }),+ call(),+ { kind: 'run', via: 'full_auto' },+ ],+ [+ 'Full auto asks a Manager when an Admin turned it off for members',+ ROWS.addPrompts,+ ctx({ mode: 'full_auto', settings: settings({ fullAutoForMembers: false }) }),+ call(),+ ask('full_auto_off'),+ ],+ // Writes: "Don't ask again"+ [+ 'a tick runs the change in Auto (§5a example 6)',+ ROWS.draft,+ ctx({ autoChoices: new Set(['draft']) }),+ call(),+ { kind: 'run', via: 'dont_ask_again' },+ ],+ [+ 'a tick counts for nothing in Ask me first',+ ROWS.draft,+ ctx({ mode: 'ask_first', autoChoices: new Set(['draft']) }),+ call(),+ ask('mode'),+ ],+ [+ 'a tick stops once an Admin turns the option off',+ ROWS.draft,+ ctx({ autoChoices: new Set(['draft']), settings: settings({ dontAskAgain: false }) }),+ call(),+ ask('dont_ask_again_off'),+ ],+ [+ 'no tick is offered once an Admin turns the option off',+ ROWS.draft,+ ctx({ settings: settings({ dontAskAgain: false }) }),+ call(),+ ask('mode'),+ ],+ [+ 'a tick left from Growth counts for nothing on Starter',+ ROWS.draft,+ ctx({ planKey: 'starter', autoChoices: new Set(['draft']) }),+ call(),+ ask('full_auto_locked'),+ ],+ ['no tick is offered on Starter', ROWS.draft, ctx({ planKey: 'starter' }), call(), ask('mode')],+ // Writes: taint and MCP+ [+ 'a tainted change asks in Full auto (§5a example 10)',+ ROWS.draft,+ ctx({ mode: 'full_auto' }),+ call({ tainted: true }),+ ask('tainted'),+ ],+ [+ 'a tainted change asks under a tick',+ ROWS.draft,+ ctx({ autoChoices: new Set(['draft']) }),+ call({ tainted: true }),+ ask('tainted'),+ ],+ [+ 'a detected injection makes the rest of the run ask',+ ROWS.draft,+ ctx({ mode: 'full_auto', injectionDetected: true }),+ call(),+ ask('tainted'),+ ],+ [+ 'an MCP write asks on Growth in Full auto (§5a example 15)',+ ROWS.addPrompts,+ ctx({ surface: 'mcp', mode: 'full_auto' }),+ call(),+ ask('mcp'),+ ],+ [+ 'an MCP write asks under a tick',+ ROWS.addPrompts,+ ctx({ surface: 'mcp', autoChoices: new Set(['addPrompts']) }),+ call(),+ ask('mcp'),+ ],+ // Writes: hard rules, plan and role+ [+ 'an always_card write asks in Full auto (§5a example 7)',+ ROWS.removeCompetitor,+ ctx({ mode: 'full_auto' }),+ call(),+ ask('always_card'),+ ],+ [+ 'a stored Always never lifts an always_card write',+ ROWS.removeCompetitor,+ ctx({+ mode: 'full_auto',+ settings: settings({ toolPolicies: { removeCompetitor: 'always' } }),+ }),+ call(),+ ask('always_card'),+ ],+ [+ 'a write an Admin set to Never is refused',+ ROWS.draft,+ ctx({ settings: settings({ toolPolicies: { draft: 'never' } }) }),+ call(),+ deny({ code: 'policy_never' }),+ ],+ [+ 'an Analyst may save a draft (daily work)',+ ROWS.draft,+ ctx({ role: 'analyst' }),+ call(),+ ask('mode', true),+ ],+ [+ 'an Analyst may dismiss a prompt suggestion',+ ROWS.dismiss,+ ctx({ role: 'analyst' }),+ call(),+ ask('mode', true),+ ],+ [+ "an Agency partner's dismissal is forbidden_role, as the server has it",+ ROWS.dismiss,+ ctx({ role: 'agency_partner', mode: 'full_auto' }),+ call(),+ deny({+ code: 'forbidden_role',+ role: 'agency_partner',+ roles: ['admin', 'manager', 'analyst'],+ }),+ ],+ [+ "an Analyst's prompt change is forbidden_role (§5a example 3)",+ ROWS.addPrompts,+ ctx({ role: 'analyst' }),+ call(),+ deny({ code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] }),+ ],+ [+ "an Agency partner's prompt change is forbidden_role",+ ROWS.addPrompts,+ ctx({ role: 'agency_partner', mode: 'full_auto' }),+ call(),+ deny({ code: 'forbidden_role', role: 'agency_partner', roles: ['admin', 'manager'] }),+ ],+ [+ "a Manager's workspace memory is forbidden_role",+ ROWS.workspaceMemory,+ ctx(),+ call(),+ deny({ code: 'forbidden_role', role: 'manager', roles: ['admin'] }),+ ],+ [+ 'a Growth write is locked on Starter',+ ROWS.growthWrite,+ ctx({ planKey: 'starter' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'a Growth write is locked in the Growth trial',+ ROWS.growthWrite,+ ctx({ planKey: 'trial' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'the plan gate comes before the role',+ ROWS.growthWrite,+ ctx({ planKey: 'starter', role: 'analyst' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'Never comes before the plan gate',+ ROWS.growthWrite,+ ctx({ planKey: 'starter', settings: settings({ toolPolicies: { growthWrite: 'never' } }) }),+ call(),+ deny({ code: 'policy_never' }),+ ],+ [+ 'a write is refused while read-only, before its policy',+ ROWS.draft,+ ctx({ planKey: 'readOnly', settings: settings({ toolPolicies: { draft: 'never' } }) }),+ call(),+ deny({ code: 'subscription_inactive' }),+ ],+ [+ 'a write is refused on the demo brand',+ ROWS.draft,+ ctx({ role: 'admin', mode: 'full_auto' }),+ call({ brandIsDemo: true }),+ deny({ code: 'demo_brand' }),+ ],+ // Executes+ [+ 'a publish waits on the click in Full auto (§5a example 5)',+ ROWS.publish,+ ctx({ mode: 'full_auto' }),+ call(),+ CLICK,+ ],+ [+ 'a publish waits on the click over MCP (§5a example 14)',+ ROWS.publish,+ ctx({ surface: 'mcp' }),+ call(),+ CLICK,+ ],+ [+ 'a stored Always leaves an execute at the click',+ ROWS.publish,+ ctx({ mode: 'full_auto', settings: settings({ toolPolicies: { publish: 'always' } }) }),+ call(),+ CLICK,+ ],+ [+ 'an execute an Admin set to Never is refused',+ ROWS.publish,+ ctx({ settings: settings({ toolPolicies: { publish: 'never' } }) }),+ call(),+ deny({ code: 'policy_never' }),+ ],+ [+ "a Manager's publish is refused with publishing off for Managers (§5a example 11)",+ ROWS.publish,+ ctx({ settings: settings({ managerExecuteOff: ['publishing'] }) }),+ call(),+ deny({ code: 'execute_off', group: 'publishing' }),+ ],+ [+ "an Admin's publish still waits on the click with publishing off for Managers",+ ROWS.publish,+ ctx({ role: 'admin', settings: settings({ managerExecuteOff: ['publishing'] }) }),+ call(),+ CLICK,+ ],+ [+ 'another group off leaves the publish at the click',+ ROWS.publish,+ ctx({ settings: settings({ managerExecuteOff: ['feeds', 'code_prs'] }) }),+ call(),+ CLICK,+ ],+ [+ "an Analyst's publish is forbidden_role",+ ROWS.publish,+ ctx({ role: 'analyst' }),+ call(),+ deny({ code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] }),+ ],+ [+ 'opening a pull request is locked on Starter (§5a example 3b)',+ ROWS.openPr,+ ctx({ planKey: 'starter' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'opening a pull request is locked in the trial',+ ROWS.openPr,+ ctx({ planKey: 'trial', role: 'admin' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ ['opening a pull request waits on the click on Growth', ROWS.openPr, ctx(), call(), CLICK],+ [+ 'an execute is refused on the demo brand',+ ROWS.publish,+ ctx(),+ call({ brandIsDemo: true }),+ deny({ code: 'demo_brand' }),+ ],+ // Brand scope+ [+ 'a brand out of scope is refused before anything else',+ ROWS.draft,+ ctx({ planKey: 'readOnly', brandAccess: [BRAND_A] }),+ call({ brandId: BRAND_B, brandIsDemo: true }),+ deny({ code: 'brand_scope' }),+ ],+ [+ 'a shared brand is in scope',+ ROWS.read,+ ctx({ role: 'agency_partner', brandAccess: [BRAND_A] }),+ call(),+ RUN_READ,+ ],+ [+ 'a call about no brand is in scope',+ ROWS.read,+ ctx({ brandAccess: [] }),+ call({ brandId: null }),+ RUN_READ,+ ],+ [+ "a brand-bound call whose brand wasn't found in the workspace is refused",+ ROWS.draft,+ ctx({ role: 'admin', mode: 'full_auto' }),+ call({ brandId: null }),+ deny({ code: 'brand_scope' }),+ ],+ [+ "a brand-bound read whose brand wasn't found is refused, with access to every brand",+ ROWS.readPlatforms,+ ctx({ role: 'admin' }),+ call({ brandId: null }),+ deny({ code: 'brand_scope' }),+ ],+ // MCP (§7, §17): not in the trial, reads on Starter, the rest from Growth+ [+ 'MCP is not in the trial, reads included',+ ROWS.read,+ ctx({ planKey: 'trial', surface: 'mcp', role: 'admin' }),+ call(),+ deny({ code: 'plan_locked', needs: 'starter' }),+ ],+ [+ 'MCP writes are not in the trial',+ ROWS.draft,+ ctx({ planKey: 'trial', surface: 'mcp' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'MCP reads run on Starter',+ ROWS.readPlatforms,+ ctx({ planKey: 'starter', surface: 'mcp' }),+ call(),+ RUN_READ,+ ],+ [+ 'MCP writes need Growth',+ ROWS.draft,+ ctx({ planKey: 'starter', surface: 'mcp' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'MCP executes need Growth',+ ROWS.publish,+ ctx({ planKey: 'starter', surface: 'mcp' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'an MCP write on self-hosted asks in Full auto',+ ROWS.draft,+ ctx({ planKey: 'selfHosted', surface: 'mcp', mode: 'full_auto' }),+ call(),+ ask('mcp'),+ ],+ // A surface or a mode this code doesn't know is the closed side+ [+ 'a write from an unknown surface asks, even in Full auto',+ ROWS.draft,+ ctx({ surface: 'email' as never, mode: 'full_auto' }),+ call(),+ ask('mcp'),+ ],+ [+ 'an Always write from an unknown surface asks',+ ROWS.addPrompts,+ ctx({+ surface: 'email' as never,+ settings: settings({ toolPolicies: { addPrompts: 'always' } }),+ }),+ call(),+ ask('mcp'),+ ],+ [+ "an unknown surface gets MCP's plan gates",+ ROWS.draft,+ ctx({ surface: 'email' as never, planKey: 'starter' }),+ call(),+ deny({ code: 'plan_locked', needs: 'growth' }),+ ],+ [+ 'an unknown mode asks first, even for an Always write',+ ROWS.addPrompts,+ ctx({ mode: 'yolo' as never, settings: settings({ toolPolicies: { addPrompts: 'always' } }) }),+ call(),+ ask('mode'),+ ],+ [+ 'an unknown mode counts no tick and offers none',+ ROWS.draft,+ ctx({ mode: 'yolo' as never, autoChoices: new Set(['draft']) }),+ call(),+ ask('mode'),+ ],+ // Self-hosted+ ['self-hosted has no plan gate', ROWS.openPr, ctx({ planKey: 'selfHosted' }), call(), CLICK],+ [+ 'self-hosted runs Full auto',+ ROWS.growthWrite,+ ctx({ planKey: 'selfHosted', mode: 'full_auto' }),+ call(),+ { kind: 'run', via: 'full_auto' },+ ],+];++describe('the approval precedence, case by case', () => {+ it.each(TABLE)('%s', (_name, tool, context, toolCall, expected) => {+ expect(decideToolCall(tool, context, toolCall)).toEqual(expected);+ });+});++// ─── Every combination ──────────────────────────────────────────────────────++const LABELS = ALL_ROWS.map((tool) => tool.labelKey);+// A stored Ask is covered by the rows fixed at Ask and by the table.+const STORED: (AdminPolicy | undefined)[] = [undefined, 'never', 'always'];+// The Admin's switches: as they come, the ticks off, Full auto off for members (ticks on),+// and everything off.+const SWITCHES: Partial<ChatSettings>[] = [+ {},+ { dontAskAgain: false },+ { fullAutoForMembers: false },+ { fullAutoForMembers: false, dontAskAgain: false, managerExecuteOff: ['publishing', 'code_prs'] },+];+// Enterprise decides as Growth does here; the table covers it.+const LOOP_PLANS: PlanKey[] = ['starter', 'growth', 'trial', 'readOnly', 'selfHosted'];++interface Variant {+ ctx: PrecedenceContext;+ /** The policy stored for every row, or none. */+ stored: AdminPolicy | undefined;+ /** "Don't ask again" ticked on every row. */+ ticked: boolean;+}++/**+ * Every context, shared by the rows: role × plan × mode × surface × policy ×+ * switches × tick × a detected injection.+ */+const VARIANTS: Variant[] = [];+for (const role of TEAM_ROLES)+ for (const planKey of LOOP_PLANS)+ for (const mode of CHAT_MODES)+ for (const surface of CHAT_SURFACES)+ for (const stored of STORED)+ for (const switches of SWITCHES)+ for (const ticked of [false, true])+ for (const injectionDetected of [false, true]) {+ const context = ctx({+ role,+ planKey,+ mode,+ surface,+ injectionDetected,+ autoChoices: new Set(ticked ? LABELS : []),+ settings: settings({+ toolPolicies: stored+ ? Object.fromEntries(LABELS.map((key) => [key, stored]))+ : {},+ ...switches,+ }),+ });+ VARIANTS.push({ ctx: context, stored, ticked });+ }++// On brand A, on the demo brand, with untrusted content, and with a brand not found.+const CALLS = [+ call(),+ call({ brandIsDemo: true }),+ call({ tainted: true }),+ call({ brandId: null }),+];++/** Every combination's decision, decided once for the tests below. */+const DECIDED = VARIANTS.flatMap((variant) =>+ CALLS.flatMap((toolCall) =>+ ALL_ROWS.map((tool) => ({+ ...variant,+ tool,+ call: toolCall,+ decision: decideToolCall(tool, variant.ctx, toolCall),+ })),+ ),+);+type Decided = (typeof DECIDED)[number];++/** The call's brand was found, or the row is about no brand. */+const resolved = (d: Decided) => d.call.brandId !== null || d.tool.brandOf === null;++const failures = (keep: (d: Decided) => boolean) =>+ DECIDED.filter(keep).map(+ (d) =>+ `${d.tool.name} · ${d.ctx.role} · ${d.ctx.plan.planId}${d.ctx.plan.isTrial ? ' trial' : ''}` ++ ` · ${d.ctx.mode} · ${d.ctx.surface} → ${JSON.stringify(d.decision)}`,+ );++describe('CHAT-20 §21 acceptance criteria', () => {+ it("gives the model exactly the rows the person's role, plan, brand access and policy allow", () => {+ expect(DECIDED.length).toBeGreaterThan(100_000);+ // The list for a run is every row a call on the run's brand wouldn't refuse…+ for (const { ctx: context } of VARIANTS) {+ for (const brandIsDemo of [false, true]) {+ const scope = { brandId: BRAND_A, brandIsDemo };+ const listed = allowedTools(ALL_ROWS, context, scope).map((t) => t.name);+ const allowed = ALL_ROWS.filter(+ (t) => decideToolCall(t, context, { ...scope, tainted: false }).kind !== 'deny',+ ).map((t) => t.name);+ expect(listed).toEqual(allowed);+ }+ // A run about no brand yet lists what one on an accessible, ordinary brand does.+ expect(allowedTools(ALL_ROWS, context, { brandId: null, brandIsDemo: false })).toEqual(+ allowedTools(ALL_ROWS, context, { brandId: BRAND_A, brandIsDemo: false }),+ );+ }+ // Over MCP: nothing in the trial, reads only on Starter, everything from Growth.+ const overMcp = (planKey: PlanKey) =>+ allowedTools(ALL_ROWS, ctx({ role: 'admin', planKey, surface: 'mcp' }), call()).map(+ (t) => t.name,+ );+ expect(overMcp('trial')).toEqual([]);+ expect(overMcp('starter')).toEqual(['read', 'readOff', 'readSpends', 'readPlatforms']);+ expect(overMcp('growth')).toEqual(ALL_ROWS.map((t) => t.name));+ // …so for an Analyst on Starter, the reads its plan opens and daily work, and nothing else.+ expect(+ allowedTools(ALL_ROWS, ctx({ role: 'analyst', planKey: 'starter' }), call()).map(+ (t) => t.name,+ ),+ ).toEqual(['read', 'readOff', 'readPlatforms', 'draft', 'dismiss']);+ expect(+ allowedTools(ALL_ROWS, ctx({ role: 'manager', planKey: 'growth' }), call()).map(+ (t) => t.name,+ ),+ ).toEqual(ALL_ROWS.filter((t) => t.name !== 'workspaceMemory').map((t) => t.name));+ });++ it('decides with the live roles only, Admin and Manager over Analyst and Agency partner', () => {+ expect(TEAM_ROLES).toEqual(['admin', 'manager', 'analyst', 'agency_partner']);+ for (const old of ['owner', 'editor', 'viewer', 'Admin', '', null, undefined]) {+ expect(parseTeamRole(old)).toBeNull();+ }+ for (const role of TEAM_ROLES) expect(parseTeamRole(role)).toBe(role);+ // An Agency partner is decided as an Analyst (P0), except on a row that leaves them out.+ const as = (role: TeamRole) =>+ DECIDED.filter((d) => d.ctx.role === role && d.tool.excludeRoles.length === 0).map((d) =>+ JSON.stringify(d.decision).replace(role, '·'),+ );+ expect(as('agency_partner')).toEqual(as('analyst'));+ expect(roleAllowed(ROWS.dismiss, 'analyst')).toBe(true);+ expect(roleAllowed(ROWS.dismiss, 'agency_partner')).toBe(false);+ // The role a call is decided with is the context's, nothing kept: a changed role counts at once.+ expect(decideToolCall(ROWS.addPrompts, ctx({ role: 'manager' }), call()).kind).toBe('ask');+ expect(decideToolCall(ROWS.addPrompts, ctx({ role: 'analyst' }), call()).kind).toBe('deny');+ });++ it('never runs an EXECUTE without the click, in any mode, policy, role, tick or surface', () => {+ expect(+ failures(+ (d) =>+ d.tool.class === 'execute' && d.decision.kind !== 'click' && d.decision.kind !== 'deny',+ ),+ ).toEqual([]);+ const clicks = DECIDED.filter((d) => d.tool.class === 'execute' && d.decision.kind === 'click');+ expect(clicks.some((d) => d.ctx.mode === 'full_auto' && d.ticked)).toBe(true);+ expect(clicks.some((d) => d.ctx.surface === 'mcp')).toBe(true);+ });++ it('shows the card for an always_card WRITE in Full auto, whatever its stored policy', () => {+ expect(failures((d) => d.tool.flags.alwaysCard && d.decision.kind === 'run')).toEqual([]);+ const fullAuto = DECIDED.filter(+ (d) => d.tool.flags.alwaysCard && d.ctx.mode === 'full_auto' && d.decision.kind === 'ask',+ );+ expect(fullAuto.length).toBeGreaterThan(0);+ expect(+ fullAuto.every((d) => d.decision.kind === 'ask' && d.decision.reason === 'always_card'),+ ).toBe(true);+ });++ it('offers no Always for an EXECUTE or an always_card WRITE in Settings › Chat', () => {+ expect(policyChoices(ROWS.publish)).toEqual(['never']);+ expect(policyChoices(ROWS.removeCompetitor)).toEqual(['never', 'ask']);+ expect(policyChoices(ROWS.schedule)).toEqual(['never', 'ask']);+ expect(policyChoices(ROWS.draft)).toEqual(['never', 'ask', 'ask_full_auto', 'always']);+ expect(policyChoices(ROWS.read)).toEqual([]);+ expect(policyChoices(ROWS.readOff)).toEqual(['never']);+ // A stored value it doesn't offer is held at what it does.+ const stored = (tool: ChatTool, policy: AdminPolicy) =>+ effectivePolicy(tool, settings({ toolPolicies: { [tool.labelKey]: policy } }));+ expect(stored(ROWS.publish, 'always')).toBe('click');+ expect(stored(ROWS.removeCompetitor, 'always')).toBe('ask');+ expect(stored(ROWS.read, 'never')).toBe('on');+ expect(stored(ROWS.draft, 'ask')).toBe('ask');+ });++ it('locks Full auto and "Don\'t ask again" on Starter and in the trial', () => {+ const locked = (d: Decided) => d.ctx.plan.planId === 'starter' || d.ctx.plan.isTrial;+ // Nothing runs a change there without a card: not Full auto, a tick or an Admin's Always.+ expect(+ failures((d) => locked(d) && d.tool.class === 'write' && d.decision.kind === 'run'),+ ).toEqual([]);+ // Settings › Chat shows Always and auto-in-Full-auto locked there, for the same reason.+ for (const key of ['starter', 'trial'] as const) {+ expect(policyChoiceLock(PLAN[key], 'always')).toBe('full_auto_locked');+ expect(policyChoiceLock(PLAN[key], 'ask_full_auto')).toBe('full_auto_locked');+ expect(policyChoiceLock(PLAN[key], 'ask')).toBeNull();+ expect(policyChoiceLock(PLAN[key], 'never')).toBeNull();+ }+ for (const key of ['growth', 'enterprise', 'selfHosted'] as const) {+ expect(policyChoiceLock(PLAN[key], 'always')).toBeNull();+ }+ expect(+ failures((d) => locked(d) && d.decision.kind === 'ask' && d.decision.offerDontAskAgain),+ ).toEqual([]);+ // On Growth the same change runs.+ expect(decideToolCall(ROWS.addPrompts, ctx({ mode: 'full_auto' }), call()).kind).toBe('run');+ });++ it("refuses an Analyst's or Agency partner's change outside daily work with forbidden_role", () => {+ const readOnlyRoles = (d: Decided) =>+ resolved(d) &&+ (d.ctx.role === 'analyst' || d.ctx.role === 'agency_partner') &&+ d.tool.class !== 'read' &&+ !roleAllowed(d.tool, d.ctx.role);+ // Never a card, a click or a run: the refusal, or an earlier hard rule's.+ expect(failures((d) => readOnlyRoles(d) && d.decision.kind !== 'deny')).toEqual([]);+ const refusals = DECIDED.filter(readOnlyRoles).map((d) =>+ d.decision.kind === 'deny' ? d.decision.denial.code : d.decision.kind,+ );+ expect(new Set(refusals)).toEqual(+ new Set([+ 'forbidden_role',+ 'plan_locked',+ 'policy_never',+ 'subscription_inactive',+ 'demo_brand',+ ]),+ );+ expect(decideToolCall(ROWS.addPrompts, ctx({ role: 'analyst' }), call())).toEqual(+ deny({ code: 'forbidden_role', role: 'analyst', roles: ['admin', 'manager'] }),+ );+ });++ it('gives a person without access to brand B nothing from brand B', () => {+ const scoped = ctx({ role: 'agency_partner', brandAccess: [BRAND_A] });+ for (const tool of ALL_ROWS) {+ for (const brandIsDemo of [false, true]) {+ expect(decideToolCall(tool, scoped, call({ brandId: BRAND_B, brandIsDemo }))).toEqual(+ deny({ code: 'brand_scope' }),+ );+ }+ }+ expect(allowedTools(ALL_ROWS, scoped, { brandId: BRAND_B, brandIsDemo: false })).toEqual([]);+ expect(allowedTools(ALL_ROWS, scoped, { brandId: BRAND_A, brandIsDemo: false }).length).toBe(5);+ // Even an Admin's or a self-hosted scope: a brand outside it doesn't exist for Chat.+ const admin = ctx({ role: 'admin', planKey: 'selfHosted', brandAccess: [BRAND_A] });+ expect(decideToolCall(ROWS.read, admin, call({ brandId: BRAND_B }))).toEqual(+ deny({ code: 'brand_scope' }),+ );+ });++ it("refuses every brand-bound call whose brand wasn't found in the workspace", () => {+ expect(+ failures(+ (d) =>+ !resolved(d) && !(d.decision.kind === 'deny' && d.decision.denial.code === 'brand_scope'),+ ),+ ).toEqual([]);+ expect(+ failures(+ (d) =>+ d.tool.brandOf === null &&+ d.decision.kind === 'deny' &&+ d.decision.denial.code === 'brand_scope',+ ),+ ).toEqual([]);+ });++ it('keeps a read-only workspace to reading: 402 subscription_inactive for the rest', () => {+ const readOnly = (d: Decided) => !d.ctx.plan.writable && resolved(d);+ expect(+ failures(+ (d) =>+ readOnly(d) &&+ (d.tool.class !== 'read' || d.tool.costClass === 'C2') &&+ !(d.decision.kind === 'deny' && d.decision.denial.code === 'subscription_inactive'),+ ),+ ).toEqual([]);+ expect(+ allowedTools(ALL_ROWS, ctx({ role: 'admin', planKey: 'readOnly' }), call()).map(+ (t) => t.name,+ ),+ ).toEqual(['read', 'readOff', 'readPlatforms']);+ });++ it('keeps the demo brand to reading: demo_brand for every change', () => {+ expect(+ failures(+ (d) =>+ d.call.brandIsDemo &&+ d.ctx.plan.writable &&+ (d.tool.class !== 'read' || d.tool.costClass === 'C2') &&+ !(d.decision.kind === 'deny' && d.decision.denial.code === 'demo_brand'),+ ),+ ).toEqual([]);+ expect(+ allowedTools(ALL_ROWS, ctx({ role: 'admin', mode: 'full_auto' }), {+ brandId: BRAND_A,+ brandIsDemo: true,+ }).map((t) => t.name),+ ).toEqual(['read', 'readOff', 'readShopping', 'readPlatforms']);+ });++ it('gates nothing by plan on self-hosted', () => {+ expect(+ failures(+ (d) =>+ d.ctx.plan.selfHosted &&+ d.decision.kind === 'deny' &&+ ['plan_locked', 'subscription_inactive'].includes(d.decision.denial.code),+ ),+ ).toEqual([]);+ expect(+ failures(+ (d) =>+ d.ctx.plan.selfHosted &&+ d.decision.kind === 'ask' &&+ d.decision.reason === 'full_auto_locked',+ ),+ ).toEqual([]);+ });++ it('shows a card in Full auto for a WRITE whose target came from untrusted content', () => {+ expect(+ failures((d) => d.call.tainted && d.tool.class === 'write' && d.decision.kind === 'run'),+ ).toEqual([]);+ expect(+ failures((d) => d.call.tainted && d.decision.kind === 'ask' && d.decision.offerDontAskAgain),+ ).toEqual([]);+ });++ it('never runs an MCP WRITE without an approval click, on any plan, policy or tick', () => {+ expect(+ failures(+ (d) => d.ctx.surface === 'mcp' && d.tool.class !== 'read' && d.decision.kind === 'run',+ ),+ ).toEqual([]);+ expect(+ failures(+ (d) => d.ctx.surface === 'mcp' && d.decision.kind === 'ask' && d.decision.offerDontAskAgain,+ ),+ ).toEqual([]);+ });+});++describe('MCP and the surfaces (§7, §17)', () => {+ it('keeps MCP out of the trial and to reads on Starter', () => {+ const mcp = (d: Decided) => d.ctx.surface === 'mcp' && resolved(d) && !d.ctx.plan.selfHosted;+ expect(failures((d) => mcp(d) && d.ctx.plan.isTrial && d.decision.kind !== 'deny')).toEqual([]);+ expect(+ failures(+ (d) =>+ mcp(d) &&+ d.ctx.plan.planId === 'starter' &&+ d.ctx.plan.writable &&+ d.tool.class !== 'read' &&+ d.decision.kind !== 'deny',+ ),+ ).toEqual([]);+ // Where nothing else refuses it, the refusal is the plan's.+ expect(+ decideToolCall(ROWS.addPrompts, ctx({ planKey: 'starter', surface: 'mcp' }), call()),+ ).toEqual(deny({ code: 'plan_locked', needs: 'growth' }));+ });+});++describe('the rest of the precedence', () => {+ it('runs a tick exactly where every rule it depends on allows it', () => {+ const counts = (d: Decided) =>+ d.ctx.mode === 'auto' &&+ d.ticked &&+ d.ctx.surface === 'chat' &&+ (d.ctx.role === 'admin' || d.ctx.settings.fullAutoForMembers) &&+ d.ctx.plan.fullAuto &&+ d.ctx.settings.dontAskAgain &&+ effectivePolicy(d.tool, d.ctx.settings) === 'ask_full_auto' &&+ !d.tool.flags.alwaysCard &&+ !d.call.tainted &&+ !d.ctx.injectionDetected;+ const viaTick = (d: Decided) =>+ d.decision.kind === 'run' && d.decision.via === 'dont_ask_again';+ expect(failures((d) => viaTick(d) && !counts(d))).toEqual([]);+ // …and wherever it counts, a WRITE the earlier steps allow runs by it.+ expect(+ failures(+ (d) => counts(d) && d.tool.class === 'write' && d.decision.kind !== 'deny' && !viaTick(d),+ ),+ ).toEqual([]);+ expect(DECIDED.some((d) => viaTick(d) && d.ctx.role !== 'admin')).toBe(true);+ });++ it('runs no WRITE by itself for the rest of a run that met an injection attempt', () => {+ expect(+ failures(+ (d) => d.ctx.injectionDetected && d.tool.class === 'write' && d.decision.kind === 'run',+ ),+ ).toEqual([]);+ });++ it('decides nothing but a refusal without a context', () => {+ for (const tool of ALL_ROWS) {+ expect(decideOrDeny(tool, null, call())).toEqual(deny({ code: 'no_access' }));+ }+ expect(decideOrDeny(ROWS.read, ctx(), call())).toEqual(RUN_READ);+ });++ it("shares frozen defaults, which a workspace can't change for another", () => {+ expect(Object.isFrozen(DEFAULT_CHAT_SETTINGS)).toBe(true);+ expect(Object.isFrozen(DEFAULT_CHAT_SETTINGS.toolPolicies)).toBe(true);+ expect(Object.isFrozen(DEFAULT_CHAT_SETTINGS.managerExecuteOff)).toBe(true);+ });++ it('runs a WRITE without a card only under Always, in Full auto or under a counted tick', () => {+ expect(+ failures(+ (d) =>+ d.decision.kind === 'run' &&+ d.tool.class === 'write' &&+ !(+ d.ctx.mode === 'full_auto' ||+ (d.ctx.mode === 'auto' && d.ticked) ||+ (d.ctx.mode === 'auto' && effectivePolicy(d.tool, d.ctx.settings) === 'always')+ ),+ ),+ ).toEqual([]);+ // A tick counts only where Full auto could run the change, and the option is on.+ expect(+ failures(+ (d) =>+ d.decision.kind === 'run' &&+ d.decision.via === 'dont_ask_again' &&+ !(+ d.ctx.plan.fullAuto &&+ d.ctx.settings.dontAskAgain &&+ effectivePolicy(d.tool, d.ctx.settings) === 'ask_full_auto' &&+ !d.tool.flags.alwaysCard+ ),+ ),+ ).toEqual([]);+ });++ it('runs an Always change in Auto and Full auto, and never in Ask me first, over MCP or tainted', () => {+ const always = (d: Decided) =>+ d.tool.class === 'write' && effectivePolicy(d.tool, d.ctx.settings) === 'always';+ expect(+ failures(+ (d) =>+ d.decision.kind === 'run' &&+ d.decision.via === 'always' &&+ (!always(d) ||+ d.ctx.mode === 'ask_first' ||+ d.ctx.surface !== 'chat' ||+ d.call.tainted ||+ d.ctx.injectionDetected),+ ),+ ).toEqual([]);+ // Wherever nothing else stops it, it runs: a card only for the person's mode, the plan+ // lock, MCP or taint. "Full auto for members" off doesn't stop it: the Admin chose Always.+ expect(+ failures(+ (d) =>+ always(d) &&+ d.ctx.mode !== 'ask_first' &&+ d.ctx.plan.fullAuto &&+ d.ctx.surface === 'chat' &&+ !d.call.tainted &&+ !d.ctx.injectionDetected &&+ d.decision.kind === 'ask',+ ),+ ).toEqual([]);+ expect(+ DECIDED.some(+ (d) =>+ !d.ctx.settings.fullAutoForMembers &&+ d.ctx.role !== 'admin' &&+ d.decision.kind === 'run' &&+ d.decision.via === 'always',+ ),+ ).toBe(true);+ // Below Growth it asks as Ask does, for the plan.+ expect(+ failures(+ (d) =>+ always(d) &&+ !d.ctx.plan.fullAuto &&+ d.ctx.mode !== 'ask_first' &&+ d.decision.kind !== 'deny' &&+ !(d.decision.kind === 'ask' && d.decision.reason === 'full_auto_locked'),+ ),+ ).toEqual([]);+ expect(+ DECIDED.some(+ (d) => d.ctx.mode === 'auto' && d.decision.kind === 'run' && d.decision.via === 'always',+ ),+ ).toBe(true);+ });++ it('offers the tick only on a card in Auto that the tick would lift', () => {+ for (const d of DECIDED) {+ if (d.decision.kind !== 'ask' || !d.decision.offerDontAskAgain) continue;+ const ticked = decideToolCall(+ d.tool,+ { ...d.ctx, autoChoices: new Set([d.tool.labelKey]) },+ d.call,+ );+ expect(ticked).toEqual({ kind: 'run', via: 'dont_ask_again' });+ }+ });++ it('refuses with policy_never only where the Admin set it and the row offers it', () => {+ expect(+ failures(+ (d) =>+ d.decision.kind === 'deny' &&+ d.decision.denial.code === 'policy_never' &&+ !(d.stored === 'never' && policyChoices(d.tool).includes('never')),+ ),+ ).toEqual([]);+ });++ it('switches a go-live group off for Managers only', () => {+ const off = DECIDED.filter(+ (d) => d.decision.kind === 'deny' && d.decision.denial.code === 'execute_off',+ );+ expect(off.length).toBeGreaterThan(0);+ expect(off.every((d) => d.ctx.role === 'manager' && d.tool.class === 'execute')).toBe(true);+ });+});diff --git a/web/src/lib/chat/precedence.ts b/web/src/lib/chat/precedence.tsnew file mode 100644index 000000000..8aa37c862--- /dev/null+++ b/web/src/lib/chat/precedence.ts@@ -0,0 +1,421 @@+import type { TeamRole } from '@/components/providers/role-provider';+import type { PlanId } from '@/config/plans';+import { planGateLock, type PlanFacts } from './plan-facts';+import {+ WRITE_POLICIES,+ type ChatTool,+ type ExecuteGroup,+ type PlanGate,+ type ToolPolicy,+ type WritePolicy,+} from './registry/define-tool';++/**+ * Whether a person may run a tool now, and how: the approval precedence+ * (CHAT-20 §5). Pure: before every call the server reads what it decides on+ * fresh (precedence-context.ts: the live role, the plan, the workspace's+ * Chat settings, the person's "Don't ask again" choices) and the tool+ * endpoint acts on the answer. The model never decides it (§2 principle 3),+ * and only sees the tools allowedTools() leaves.+ *+ * Most restrictive wins, top to bottom; a step only takes options away:+ *+ * 0. Brand scope: a brand the person can't access doesn't exist for Chat+ * (§15b), so it's refused before anything about it is used, its demo+ * flag included, and the refusal names nothing. So is a call on a+ * brand-bound row whose brand wasn't found in the workspace (an id of+ * another workspace's object, or of none).+ * 1. Hard rules: a read-only workspace refuses what changes, goes live or+ * spends (402); the demo brand's sample data the same; a tool an Admin+ * set to Never is refused; an EXECUTE is at most a click and an+ * always_card WRITE at most a card, in every mode.+ * 2. Plan gates (§7): the tool's own; Full auto, "Don't ask again" and an+ * Admin's Always are Growth and up, paid (below it they ask, as Ask+ * does). MCP (§17): not in the trial, reads only on Starter, the rest+ * from Growth. None on self-hosted.+ * 3. The live role (§4), against the row's minRole and the roles it+ * leaves out. The roles follow the role model of 2026-10-29: daily work+ * (drafts, tasks, audits, reports) open to every role; settings,+ * deleting, adding prompts and costly work to Admins and Managers.+ * Agency partners act as Analysts until brand sharing (Wave 2), except+ * where a row leaves them out as the server does.+ * 4. The Admin's policy: the tool's level (Ask, Ask with auto in Full+ * auto, Always), Full auto for people other than Admins (which Always+ * doesn't need), and the go-live groups switched off for Managers.+ * 5. The run mode: Ask me first shows a card for every WRITE. Auto shows+ * one too, except for a tool whose policy is Always, which runs in Auto+ * and Full auto alike. Full auto also runs "Ask (auto allowed in Full+ * auto)". No WRITE runs by itself anywhere but Chat: over MCP (v1), or+ * from a surface this code doesn't know. A mode it doesn't know is Ask+ * me first.+ * Differs from §5 step 5 as written ("Auto: each WRITE shows a card"),+ * by decision of 2026-10-29: otherwise Always and "Ask (auto allowed in+ * Full auto)" would do the same. Step 5's card in Auto holds for every+ * tool not set to Always; EXECUTE and always_card rows can't be Always.+ * 6. "Don't ask again": in Auto, the person's tick runs that WRITE as Full+ * auto would, and only where Full auto could.+ * 7. Taint (§16a): a WRITE whose target or text came from untrusted content+ * shows a card in every mode; a detected injection does the same for+ * the rest of the run.+ */++export const TEAM_ROLES = [+ 'admin',+ 'manager',+ 'analyst',+ 'agency_partner',+] as const satisfies readonly TeamRole[];++/** A live role from the database, or null for anything else (no Owner, Editor or Viewer, §4). */+export function parseTeamRole(value: unknown): TeamRole | null {+ return TEAM_ROLES.find((role) => role === value) ?? null;+}++// Analyst and Agency partner rank the same: "Analyst" in a row's minRole means every role (§20).+const ROLE_RANK: Record<TeamRole, number> = { admin: 2, manager: 1, analyst: 0, agency_partner: 0 };++/** Whether a role is at or above minRole. */+export function roleMeets(role: TeamRole, minRole: TeamRole): boolean {+ return ROLE_RANK[role] >= ROLE_RANK[minRole];+}++/** Whether a role may call a row: at or above its minRole, and not one it leaves out. */+export function roleAllowed(tool: Pick<ChatTool, 'minRole' | 'excludeRoles'>, role: TeamRole) {+ return roleMeets(role, tool.minRole) && !tool.excludeRoles.includes(role);+}++/** The roles that may call a row: a denial's "who can", by role, never by person (§4c). */+export function allowedRoles(tool: Pick<ChatTool, 'minRole' | 'excludeRoles'>): TeamRole[] {+ return TEAM_ROLES.filter((role) => roleAllowed(tool, role));+}++/** The run modes of the composer (CHAT-02): Ask me first · Auto, ask before changes · Full auto. */+export const CHAT_MODES = ['ask_first', 'auto', 'full_auto'] as const;+export type ChatMode = (typeof CHAT_MODES)[number];++/** Where a call comes from. MCP has no Full auto and no "Don't ask again" in v1 (§17). */+export const CHAT_SURFACES = ['chat', 'mcp'] as const;+export type ChatSurface = (typeof CHAT_SURFACES)[number];++/** What an Admin may set a tool to in Settings › Chat (chat_settings.tool_policies, 00401). */+export const ADMIN_POLICIES = ['never', 'ask', 'ask_full_auto', 'always'] as const;+export type AdminPolicy = (typeof ADMIN_POLICIES)[number];++/** A workspace's Chat settings (chat_settings, 00401). */+export interface ChatSettings {+ /** An Admin's policy per tool, by label key; a tool not named keeps its row's default. */+ toolPolicies: Readonly<Record<string, AdminPolicy>>;+ /** People other than Admins may use Full auto (CHAT-23 policy.toggleFullAutoForManagers). */+ fullAutoForMembers: boolean;+ /** "Don't ask again" is offered, and the ticks count; off, they stop at once. */+ dontAskAgain: boolean;+ /** The go-live groups Managers can't click through. */+ managerExecuteOff: readonly ExecuteGroup[];+}++/** A workspace without a chat_settings row. Frozen: every such workspace shares it. */+export const DEFAULT_CHAT_SETTINGS: ChatSettings = Object.freeze({+ toolPolicies: Object.freeze({}),+ fullAutoForMembers: true,+ dontAskAgain: true,+ managerExecuteOff: Object.freeze([]),+});++/** Everything a call is decided on but the call itself. */+export interface PrecedenceContext {+ /** The workspace the person acts in: a call's brand must belong to it. */+ organizationId: string;+ /** Read for this call: never a role kept from earlier in the run (§4 "Role change mid-run"). */+ role: TeamRole;+ plan: PlanFacts;+ settings: ChatSettings;+ /** The mode the run is in, as the person picked it. */+ mode: ChatMode;+ surface: ChatSurface;+ /** Label keys of the tools the person ticked "Don't ask again" on. */+ autoChoices: ReadonlySet<string>;+ /** The brands the person may use: all of the workspace's, or the ones shared with them. */+ brandAccess: 'all' | readonly string[];+ /** An injection attempt was found in this run (§16a rule 3). */+ injectionDetected: boolean;+}++/** What a call is about. */+export interface ToolCall {+ /**+ * The brand it reads or changes, found in the person's workspace+ * (precedence-context.ts readToolCall). Null: none, which a brand-bound+ * row is refused for, since its brand wasn't found.+ */+ brandId: string | null;+ /** That brand is the demo brand (brands.is_demo). */+ brandIsDemo: boolean;+ /** Its target or text came from untrusted content in this run: a page, an upload, an AI answer… */+ tainted: boolean;+}++/** Why a call is refused, with what the denial says (denial.ts). Codes as §11a's where it has one. */+export type ToolDenial =+ /** No context: the person isn't a member of the workspace now (decideOrDeny). */+ | { code: 'no_access' }+ | { code: 'brand_scope' }+ | { code: 'subscription_inactive' }+ | { code: 'demo_brand' }+ | { code: 'policy_never' }+ | { code: 'plan_locked'; needs: PlanId }+ /** roles: the ones that may call it. */+ | { code: 'forbidden_role'; role: TeamRole; roles: TeamRole[] }+ | { code: 'execute_off'; group: ExecuteGroup };++/** Why a WRITE stops at a card: the first step that kept it from running by itself. */+export type AskReason =+ | 'always_card'+ | 'mode'+ | 'full_auto_locked'+ | 'policy'+ | 'full_auto_off'+ | 'mcp'+ | 'dont_ask_again_off'+ | 'tainted';++export type ToolDecision =+ /** It runs now: a READ, or a WRITE set to Always, in Full auto, or under the person's tick. */+ | { kind: 'run'; via: 'read' | 'always' | 'full_auto' | 'dont_ask_again' }+ /** An approval card; offerDontAskAgain: the card may offer the tick (§6). */+ | { kind: 'ask'; reason: AskReason; offerDontAskAgain: boolean }+ /** An EXECUTE: only the person's click runs it. */+ | { kind: 'click' }+ | { kind: 'deny'; denial: ToolDenial };++const writeRank = (policy: WritePolicy) => WRITE_POLICIES.indexOf(policy);++/**+ * What Settings › Chat offers for a row (§5 step 4): a read only Never, when+ * an Admin may switch it off; an EXECUTE only Never (otherwise a click); a+ * WRITE Never and the levels up to its maximum, so never Always for an+ * always_card row.+ */+export function policyChoices(tool: ChatTool): AdminPolicy[] {+ if (tool.class === 'read') return tool.flags.adminMayTurnOff ? ['never'] : [];+ if (tool.class === 'execute') return ['never'];+ const max = writeRank(tool.maxPolicy as WritePolicy);+ return ['never', ...WRITE_POLICIES.filter((policy) => writeRank(policy) <= max)];+}++/**+ * Why Settings › Chat shows a policy locked on this plan, or null when it+ * may be picked: below Growth (Starter, the trial) Always and "Ask (auto+ * allowed in Full auto)" only act as Ask, since both run without a card+ * only where Full auto is open (CHAT-23 policy.toggleAutoInFullAuto). The+ * same reason the precedence gives a call: full_auto_locked.+ */+export function policyChoiceLock(plan: PlanFacts, policy: AdminPolicy): 'full_auto_locked' | null {+ return !plan.fullAuto && (policy === 'always' || policy === 'ask_full_auto')+ ? 'full_auto_locked'+ : null;+}++/**+ * A row's policy in this workspace: the Admin's choice where the row offers+ * it, else the row's default. A choice past the row's maximum is held at the+ * maximum, so a stored "Always" never lifts an always_card WRITE.+ */+export function effectivePolicy(tool: ChatTool, settings: ChatSettings): ToolPolicy {+ const set = settings.toolPolicies[tool.labelKey];+ if (set === 'never') return policyChoices(tool).includes('never') ? 'never' : tool.defaultPolicy;+ if (tool.class !== 'write' || !isWritePolicy(set)) return tool.defaultPolicy;+ return writeRank(set) > writeRank(tool.maxPolicy as WritePolicy) ? tool.maxPolicy : set;+}++function isWritePolicy(value: unknown): value is WritePolicy {+ return WRITE_POLICIES.some((policy) => policy === value);+}++function canAccessBrand(access: PrecedenceContext['brandAccess'], brandId: string): boolean {+ return access === 'all' || access.includes(brandId);+}++const deny = (denial: ToolDenial): ToolDecision => ({ kind: 'deny', denial });++/**+ * What a surface other than Chat needs of the plan (§7, §17): MCP isn't in+ * the trial, its reads are Starter and up, its writes and executes Growth+ * and up. A surface this code doesn't know gets MCP's, the closed side.+ */+function surfaceGate(ctx: PrecedenceContext, tool: ChatTool): PlanGate | null {+ if (ctx.surface === 'chat') return null;+ return { minPlan: tool.class === 'read' ? 'starter' : 'growth' };+}++/**+ * The decision for one call. Run it before every tool call, with a context+ * read for that call: a role, a plan or a setting changed mid-run counts+ * from the next call.+ *+ * For the engine (C3): an `ask` or a `click` is not a permission kept for+ * later. When the person approves the card or clicks, read the context and+ * the call again and decide again; run only if that answer still lets it+ * (the approval stands for the card, a `click` for the click). A role, a+ * plan, a policy or the brand that changed while the card waited wins.+ */+export function decideToolCall(+ tool: ChatTool,+ ctx: PrecedenceContext,+ call: ToolCall,+): ToolDecision {+ return decide(tool, ctx, call, false);+}++/**+ * decideToolCall for a context that may be missing: readPrecedenceContext+ * returns null when the person isn't a member of the workspace now (no+ * profile, another workspace, no live role), and then nothing runs.+ */+export function decideOrDeny(+ tool: ChatTool,+ ctx: PrecedenceContext | null,+ call: ToolCall,+): ToolDecision {+ return ctx ? decideToolCall(tool, ctx, call) : deny({ code: 'no_access' });+}++/** listing: for the model's tool list, where a run may not have named its brand yet. */+function decide(+ tool: ChatTool,+ ctx: PrecedenceContext,+ call: ToolCall,+ listing: boolean,+): ToolDecision {+ // 0. A brand outside the person's scope doesn't exist for Chat, nor one not found in the+ // workspace. A list for a run without a brand keeps the brand-bound rows: each call+ // names its own, and is decided with it.+ if (call.brandId === null) {+ if (tool.brandOf && !listing) return deny({ code: 'brand_scope' });+ } else if (!canAccessBrand(ctx.brandAccess, call.brandId)) {+ return deny({ code: 'brand_scope' });+ }++ // 1. Hard rules.+ const changes = tool.class !== 'read';+ // A read that runs a model (C2, C3) spends the AI budget, which a read-only workspace can't.+ const spends = tool.costClass === 'C2' || tool.costClass === 'C3';+ if (!ctx.plan.writable && (changes || spends)) return deny({ code: 'subscription_inactive' });+ if (call.brandIsDemo && (changes || spends)) return deny({ code: 'demo_brand' });+ const policy = effectivePolicy(tool, ctx.settings);+ if (policy === 'never') return deny({ code: 'policy_never' });++ // 2. The plan, the tool's and its surface's. While read-only, choosing a plan is what+ // opens it, whatever it needs.+ const needs =+ planGateLock(ctx.plan, tool.planGate) ?? planGateLock(ctx.plan, surfaceGate(ctx, tool));+ if (needs) {+ return deny(+ ctx.plan.writable ? { code: 'plan_locked', needs } : { code: 'subscription_inactive' },+ );+ }++ // 3. The live role.+ if (!roleAllowed(tool, ctx.role)) {+ return deny({ code: 'forbidden_role', role: ctx.role, roles: allowedRoles(tool) });+ }++ if (tool.class === 'read') return { kind: 'run', via: 'read' };++ if (tool.class === 'execute') {+ // 4. The Admin's switch for Managers; then the hard rule: a click, whatever the mode.+ const group = tool.executeGroup;+ if (ctx.role === 'manager' && group && ctx.settings.managerExecuteOff.includes(group)) {+ return deny({ code: 'execute_off', group });+ }+ return { kind: 'click' };+ }++ return decideWrite(tool, ctx, call, policy as WritePolicy);+}++/** Steps 1 and 2, 4–7 for a WRITE the plan and the role allow. */+function decideWrite(+ tool: ChatTool,+ ctx: PrecedenceContext,+ call: ToolCall,+ policy: WritePolicy,+): ToolDecision {+ const tainted = call.tainted || ctx.injectionDetected;+ // A mode this code doesn't know is the most careful one.+ const mode: ChatMode = ctx.mode === 'auto' || ctx.mode === 'full_auto' ? ctx.mode : 'ask_first';+ const ask = (reason: AskReason): ToolDecision => ({+ kind: 'ask',+ reason,+ // The tick is offered only where it would count (§6): in Auto, for a change Full auto could run.+ offerDontAskAgain:+ reason === 'mode' && mode === 'auto' && !tainted && tickWouldCount(tool, ctx, policy),+ });++ // 1. A card in every mode.+ if (tool.flags.alwaysCard) return ask('always_card');+ // 5. The person asked to be asked first: their mode wins over every policy.+ if (mode === 'ask_first') return ask('mode');+ // 4–5. Set to Always by an Admin: runs in Auto and Full auto (see the header).+ if (policy === 'always') {+ // 2. Under Full auto's plan lock: Always mustn't get past the plan difference (Starter, trial).+ if (!ctx.plan.fullAuto) return ask('full_auto_locked');+ // Not under "Full auto for members": Always is the Admin's own choice for this one tool,+ // so it runs for every role it allows even with that switch off.+ if (ctx.surface !== 'chat') return ask('mcp');+ if (tainted) return ask('tainted');+ return { kind: 'run', via: 'always' };+ }+ // 5–6. What the person asked for: Full auto, or in Auto their tick on this tool.+ const via =+ mode === 'full_auto'+ ? 'full_auto'+ : ctx.autoChoices.has(tool.labelKey)+ ? 'dont_ask_again'+ : null;+ if (!via) return ask('mode');+ // 2. Full auto and "Don't ask again" are Growth+, paid.+ if (!ctx.plan.fullAuto) return ask('full_auto_locked');+ // 4. The Admin's policy.+ if (policy === 'ask') return ask('policy');+ if (ctx.role !== 'admin' && !ctx.settings.fullAutoForMembers) return ask('full_auto_off');+ // 5. Writes asked for from MCP (v1), or from a surface this code doesn't know, always ask.+ if (ctx.surface !== 'chat') return ask('mcp');+ // 6. An Admin switched "Don't ask again" off: the ticks stop at once.+ if (via === 'dont_ask_again' && !ctx.settings.dontAskAgain) return ask('dont_ask_again_off');+ // 7. Untrusted content chose the target or the text.+ if (tainted) return ask('tainted');+ return { kind: 'run', via };+}++/**+ * Whether a "Don't ask again" tick would run this WRITE: where Full auto+ * could, with the option on. An Always tool runs without one.+ */+function tickWouldCount(tool: ChatTool, ctx: PrecedenceContext, policy: WritePolicy): boolean {+ return (+ !tool.flags.alwaysCard &&+ ctx.plan.fullAuto &&+ policy === 'ask_full_auto' &&+ (ctx.role === 'admin' || ctx.settings.fullAutoForMembers) &&+ ctx.surface === 'chat' &&+ ctx.settings.dontAskAgain+ );+}++/**+ * The tools the model gets for a run (§9: its list equals the rows the+ * person's role, plan, brand access and policy allow): every row whose call+ * on the run's brand wouldn't be refused. A tool that only asks or waits on+ * a click stays: the card or the click is how it runs. A run about no brand+ * yet (brandId null) keeps the brand-bound rows; each call is decided with+ * the brand it names.+ */+export function allowedTools<T extends ChatTool>(+ tools: readonly T[],+ ctx: PrecedenceContext,+ scope: { brandId: string | null; brandIsDemo: boolean },+): T[] {+ return tools.filter(+ (tool) => decide(tool, ctx, { ...scope, tainted: false }, true).kind !== 'deny',+ );+}diff --git a/web/src/lib/chat/registry/define-tool.ts b/web/src/lib/chat/registry/define-tool.tsindex 7759e9342..8e7a97c64 100644--- a/web/src/lib/chat/registry/define-tool.ts+++ b/web/src/lib/chat/registry/define-tool.ts@@ -12,7 +12,8 @@ import type { McpAuthContext } from '@/lib/mcp-auth';* no class here: it is simply no row.** A row only describes; the approval precedence that reads it (plan, role,- * policy, mode) is checked on the server when a run calls the tool.+ * policy, mode) is checked on the server when a run calls the tool+ * (lib/chat/precedence.ts).*//** What a call does (CHAT-20 §3): reads, changes data in Ansvisor, or goes live / leaves it. */@@ -33,6 +34,33 @@ export type ToolPolicy = (typeof TOOL_POLICIES)[number];export const WRITE_POLICIES = ['ask', 'ask_full_auto', 'always'] as const;export type WritePolicy = (typeof WRITE_POLICIES)[number];+/**+ * The go-live groups an Admin may switch off for Managers (CHAT-20 §4+ * refinements): publishing, email and outreach, code and pull requests,+ * product feeds. Every EXECUTE row is in one.+ */+export const EXECUTE_GROUPS = ['publishing', 'email_outreach', 'code_prs', 'feeds'] as const;+export type ExecuteGroup = (typeof EXECUTE_GROUPS)[number];++/** The tables whose rows name their brand, for a row whose input names an object, not a brand. */+export const BRAND_LOOKUP_TABLES = [+ 'actions',+ 'content_drafts',+ 'content_opportunities',+ 'prompt_results',+ 'prompt_suggestions',+ 'site_audits',+] as const;+export type BrandLookupTable = (typeof BRAND_LOOKUP_TABLES)[number];++/**+ * Where a call's brand comes from, so the brand scope and the demo rule see+ * it (CHAT-20 §15b): the input's brand_id, or the brand of the row the+ * input's id names. A row about the person or the workspace (a profile,+ * usage, the brand list) has none: brandOf null.+ */+export type BrandOf = { input: 'brand_id' } | { lookup: BrandLookupTable; idField: string };+/** CHAT-20 §9 cost: C0 no model, C1 a scoped read, C2 a model writing step, C3 heavy. */export type CostClass = 'C0' | 'C1' | 'C2' | 'C3';@@ -90,7 +118,15 @@ interface ToolFields<S extends z.ZodObject> {description: string;/** The lowest role that may call it: `analyst` means every role (CHAT-20 §20). */minRole: TeamRole;+ /**+ * Roles left out of a row open to every role, where the server and the+ * database refuse them (an Agency partner dismissing a prompt suggestion).+ * Never an Admin.+ */+ excludeRoles?: readonly TeamRole[];planGate: PlanGate | null;+ /** Where a call's brand comes from; null for a row about no brand. */+ brandOf: BrandOf | null;costClass: CostClass;/*** The key under `chatTools` in messages/en.json (`name` for Settings, `step`@@ -117,15 +153,24 @@ type ClassFields =maxPolicy: WritePolicy;flags?: Partial<Pick<ToolFlags, 'alwaysCard' | 'costCard'>>;}- | { class: 'execute'; flags?: Partial<Pick<ToolFlags, 'costCard'>> };+ | {+ class: 'execute';+ /** Its go-live group, which the Manager switch in Settings › Chat covers. */+ executeGroup: ExecuteGroup;+ flags?: Partial<Pick<ToolFlags, 'costCard'>>;+ };export type ToolDefinition<S extends z.ZodObject> = ToolFields<S> & ClassFields;-export type ChatTool<S extends z.ZodObject = z.ZodObject> = ToolFields<S> & {+export type ChatTool<S extends z.ZodObject = z.ZodObject> = Omit<ToolFields<S>, 'excludeRoles'> & {+ /** Roles left out of the row; empty for most. */+ excludeRoles: readonly TeamRole[];class: ToolClass;defaultPolicy: ToolPolicy;maxPolicy: ToolPolicy;flags: ToolFlags;+ /** An EXECUTE's go-live group; null on a read or a write. */+ executeGroup: ExecuteGroup | null;};/** Ids for the rows' fixtures: any 8-4-4-4-12 hex id passes the inputs' uuid check. */@@ -148,9 +193,26 @@ export function defineTool<S extends z.ZodObject>(def: ToolDefinition<S>): ChatTadminMayTurnOff: false,...def.flags,};+ if (def.brandOf) {+ const field = 'input' in def.brandOf ? def.brandOf.input : def.brandOf.idField;+ if (!(field in def.inputSchema.shape)) {+ throw new Error(`${def.name}: its brand comes from ${field}, which its input lacks`);+ }+ }+ const excludeRoles = [...(def.excludeRoles ?? [])];+ if (excludeRoles.length > 0 && (def.minRole !== 'analyst' || excludeRoles.includes('admin'))) {+ throw new Error(`${def.name}: only a row open to every role leaves roles out, never an Admin`);+ }if (def.class === 'read') {if (flags.alwaysCard) throw new Error(`${def.name}: a read has no approval card`);- return { ...def, defaultPolicy: 'on', maxPolicy: 'on', flags };+ return {+ ...def,+ defaultPolicy: 'on',+ maxPolicy: 'on',+ flags,+ excludeRoles,+ executeGroup: null,+ };}if (flags.adminMayTurnOff) throw new Error(`${def.name}: only a read is switched off`);if (def.class === 'execute') {@@ -162,7 +224,10 @@ export function defineTool<S extends z.ZodObject>(def: ToolDefinition<S>): ChatT) {throw new Error(`${def.name}: an execute always needs the user's click`);}- return { ...def, defaultPolicy: 'click', maxPolicy: 'click', flags };+ if (!EXECUTE_GROUPS.includes(def.executeGroup)) {+ throw new Error(`${def.name}: an execute belongs to a go-live group`);+ }+ return { ...def, defaultPolicy: 'click', maxPolicy: 'click', flags, excludeRoles };}if (def.class !== 'write') throw new Error('A tool is a read, a write or an execute');if (!WRITE_POLICIES.includes(def.defaultPolicy) || !WRITE_POLICIES.includes(def.maxPolicy)) {@@ -174,5 +239,5 @@ export function defineTool<S extends z.ZodObject>(def: ToolDefinition<S>): ChatTif (flags.alwaysCard && def.maxPolicy !== 'ask') {throw new Error(`${def.name}: an always_card write never runs without a card`);}- return { ...def, flags };+ return { ...def, flags, excludeRoles, executeGroup: null };}diff --git a/web/src/lib/chat/registry/read-tools.ts b/web/src/lib/chat/registry/read-tools.tsindex fffa2cfce..777bb0c55 100644--- a/web/src/lib/chat/registry/read-tools.ts+++ b/web/src/lib/chat/registry/read-tools.ts@@ -85,6 +85,7 @@ export const READ_TOOLS = ['Who the user is: their id, email, organization, role (admin, manager, analyst or agency_partner) and work areas. Read it before suggesting something only an admin or a manager may do.',minRole: 'analyst',planGate: null,+ brandOf: null,costClass: 'C0',labelKey: 'profile',route: '/dashboard/settings/account',@@ -102,6 +103,7 @@ export const READ_TOOLS = ["How much of the workspace's monthly AI limit is used this period, as a percent, with each feature's share, the plan and the renewal date. No dollar amounts.",minRole: 'analyst',planGate: null,+ brandOf: null,costClass: 'C0',labelKey: 'aiUsage',route: '/dashboard/settings/billing',@@ -119,6 +121,7 @@ export const READ_TOOLS = ['The brands the user can access: id, name, slug, industry, region. Call it first when the user has not named a brand.',minRole: 'analyst',planGate: null,+ brandOf: null,costClass: 'C1',labelKey: 'brands',route: '/dashboard/brands',@@ -136,6 +139,7 @@ export const READ_TOOLS = ['A brand\'s visibility over a period: results, average visibility (0–100), mentions, citations and the top competitors. For "how is my brand doing" questions.',minRole: 'analyst',planGate: { platforms: true },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'visibility',route: '/dashboard/insights',@@ -166,6 +170,7 @@ export const READ_TOOLS = ["A brand's visibility, mentions and citations over time, by day or week. For trend questions and charts.",minRole: 'analyst',planGate: { platforms: true },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'visibilityTrend',route: '/dashboard/insights',@@ -200,6 +205,7 @@ export const READ_TOOLS = ['The prompts tracked for a brand, with topic, platforms, regions and whether each is active; newest first. Filter by topic or active state.',minRole: 'analyst',planGate: { platforms: true },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'trackedPrompts',route: '/dashboard/prompts/tracked',@@ -228,6 +234,7 @@ export const READ_TOOLS = ['Visibility, mentions, citations and appearances per prompt over a period, sorted. For "which prompts do best" or "which dropped this week".',minRole: 'analyst',planGate: { platforms: true },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'promptPerformance',route: '/dashboard/prompts/tracked',@@ -266,6 +273,7 @@ export const READ_TOOLS = ["The brand's pending prompt suggestions with topic, reason and an estimated volume. The volume is an AI guess, low confidence: say so when quoting it.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'promptSuggestions',route: '/dashboard/prompts/suggestions',@@ -283,6 +291,7 @@ export const READ_TOOLS = ["Each tracked prompt's estimated AI searches a month, with its range and confidence. An estimate, not a measurement.",minRole: 'analyst',planGate: { feature: 'prompt_volumes' },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'promptVolumes',route: '/dashboard/prompts/tracked',@@ -302,6 +311,7 @@ export const READ_TOOLS = [description: "The brand's topics, each with its number of prompts.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'topics',route: '/dashboard/prompts/topics',@@ -319,6 +329,7 @@ export const READ_TOOLS = ['How often AI answers name the brand and how they speak of it, against the period before: mention rate, net sentiment (−100…+100) and the sentiment split. Under 20 mentions it is a low sample: say so.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'mentionsSummary',route: '/dashboard/mentions',@@ -336,6 +347,7 @@ export const READ_TOOLS = ['The AI answers naming the brand, 100 a page: prompt, platform, sentiment, position, competitors named alongside and an excerpt.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'mentions',route: '/dashboard/mentions',@@ -371,6 +383,7 @@ export const READ_TOOLS = ['One AI answer naming the brand, in full: its text, citations, the competitors it names, its sentiment and any correction to it.',minRole: 'analyst',planGate: null,+ brandOf: { lookup: 'prompt_results', idField: 'id' },costClass: 'C1',labelKey: 'mention',route: '/dashboard/mentions',@@ -388,6 +401,7 @@ export const READ_TOOLS = ["How often AI answers name each competitor in the brand's tracked answers (count, share, change against the period before) and how often alongside the brand.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'mentionCompetitors',route: '/dashboard/mentions',@@ -405,6 +419,7 @@ export const READ_TOOLS = ['What AI associates with the brand: the terms next to it, now and before, the attributes that set it apart from its top competitors, and the biggest gap a competitor leads. Found by rule, no model.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'mentionsPerception',route: '/dashboard/mentions',@@ -422,6 +437,7 @@ export const READ_TOOLS = ['The domains and pages AI answers cite for the brand over a period, owned, competitor or external.',minRole: 'analyst',planGate: { platforms: true },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'citations',route: '/dashboard/citations',@@ -457,6 +473,7 @@ export const READ_TOOLS = [description: 'The competitors set up for the brand: id, name and domain. Not a ranking.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'competitors',route: '/dashboard/competitors',@@ -474,6 +491,7 @@ export const READ_TOOLS = ['The brand against each competitor over a period: visibility, mentions, citations and share of voice, also per platform.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'competitorComparison',route: '/dashboard/competitors',@@ -506,6 +524,7 @@ export const READ_TOOLS = ["One product's appearances in AI shopping results: by platform, region and date, its rating, reviews and the merchants selling it.",minRole: 'analyst',planGate: { feature: 'shopping_analytics' },+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'productVisibility',route: '/dashboard/shopping',@@ -530,6 +549,7 @@ export const READ_TOOLS = ["Visits AI assistants sent to the brand's site over a period: total, by platform, top pages and countries.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'aiReferralTraffic',route: '/dashboard/traffic',@@ -552,6 +572,7 @@ export const READ_TOOLS = ["The brand's recent Site Audits, newest first: page, status, score and date. Read one with its issues through list_site_audit_issues.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'siteAudits',route: '/dashboard/audit',@@ -568,6 +589,7 @@ export const READ_TOOLS = [description: 'One Site Audit in full: its score and every check, passed or failed.',minRole: 'analyst',planGate: null,+ brandOf: { lookup: 'site_audits', idField: 'audit_id' },costClass: 'C1',labelKey: 'siteAuditIssues',route: '/dashboard/audit',@@ -587,6 +609,7 @@ export const READ_TOOLS = ["The brand's Action Center actions, highest priority first: category, impact, priority, status, assignee, due date and task progress.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'actions',route: '/dashboard/action-center/actions',@@ -617,6 +640,7 @@ export const READ_TOOLS = ['One Action Center action in full: what it is about, why, its priority, signals, tasks (What, Where, Why, How, Done when) and outcome.',minRole: 'analyst',planGate: null,+ brandOf: { lookup: 'actions', idField: 'action_id' },costClass: 'C1',labelKey: 'action',route: '/dashboard/action-center/actions',@@ -636,6 +660,7 @@ export const READ_TOOLS = ['The changes the Action Center detected for the brand, newest first: what moved, by how much, where, and the actions built on each.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'signals',route: '/dashboard/action-center/signals',@@ -664,6 +689,7 @@ export const READ_TOOLS = ['Closed actions with their measured outcome, latest first. An outcome before day 30 is a reading so far, and a change is never claimed as caused by the action.',minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'actionHistory',route: '/dashboard/action-center/history',@@ -684,6 +710,7 @@ export const READ_TOOLS = ["The brand's content opportunities, highest score first: the prompts where it loses visibility and the page that would win them.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'contentOpportunities',route: '/dashboard/content',@@ -716,6 +743,7 @@ export const READ_TOOLS = ["The brand's Content Library drafts, latest changed first: title, status, method, page type and author.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'drafts',route: '/dashboard/content/library',@@ -733,6 +761,7 @@ export const READ_TOOLS = ['One draft: its HTML passage by passage, where it is live, and the suggestions waiting for review. Passages AI answers quote are locked.',minRole: 'analyst',planGate: null,+ brandOf: { lookup: 'content_drafts', idField: 'draft_id' },costClass: 'C1',labelKey: 'draft',route: '/dashboard/content/library',@@ -749,6 +778,7 @@ export const READ_TOOLS = [description: "The brand's saved reports, newest first: title, template and date range.",minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C1',labelKey: 'reports',route: '/dashboard/reports',diff --git a/web/src/lib/chat/registry/tools.test.ts b/web/src/lib/chat/registry/tools.test.tsindex 8302d2003..d33511e17 100644--- a/web/src/lib/chat/registry/tools.test.ts+++ b/web/src/lib/chat/registry/tools.test.ts@@ -4,6 +4,7 @@ import path from 'node:path';import { z } from 'zod';import { beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../messages/en.json';+import type { TeamRole } from '@/components/providers/role-provider';import type { ChatTool } from './define-tool';import { clientEventProblems, type ChatEvent } from '../events';@@ -58,7 +59,9 @@ vi.mock('@/lib/actions/prompt-suggestions', () => ({}));const { CHAT_TOOLS, chatTool, chatToolByKey, registryCatalog } = await import('./tools');-const { FIXTURE_IDS, defineTool } = await import('./define-tool');+const { BRAND_LOOKUP_TABLES, FIXTURE_IDS, defineTool } = await import('./define-tool');+const { DEFAULT_CHAT_SETTINGS, allowedRoles, allowedTools } = await import('../precedence');+const { planFactsFromOrgRow } = await import('../plan-facts');const ctx = {userId: 'user-1',@@ -109,6 +112,7 @@ const readRow = {description: 'test',minRole: 'analyst' as const,planGate: null,+ brandOf: null,costClass: 'C0' as const,labelKey: 'brands',route: null,@@ -264,18 +268,76 @@ describe('approval policies', () => {expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['on', 'on']);} else if (tool.class === 'write') {expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['ask_full_auto', 'always']);- // Analysts and Agency partners are read-only (CHAT-20 §4).- expect(['admin', 'manager']).toContain(tool.minRole);}}});+ it('opens daily work to every role and keeps the rest with Admins and Managers', () => {+ // The role model of 2026-10-29, as the server (#1763), MCP (#1762) and RLS have each write.+ const writes = CHAT_TOOLS.filter((t) => t.class !== 'read');+ expect(Object.fromEntries(writes.map((t) => [t.name, allowedRoles(t)]))).toEqual({+ create_draft: ['admin', 'manager', 'analyst', 'agency_partner'],+ update_opportunity: ['admin', 'manager'],+ dismiss_prompt_suggestion: ['admin', 'manager', 'analyst'],+ });+ for (const tool of CHAT_TOOLS.filter((t) => t.class === 'read')) {+ expect(allowedRoles(tool)).toEqual(['admin', 'manager', 'analyst', 'agency_partner']);+ }+ });++ it('says where every row that takes a brand or an object finds its brand', () => {+ const problems = CHAT_TOOLS.flatMap((tool) => {+ const fields = Object.keys(tool.inputSchema.shape);+ const ids = fields.filter((field) => field === 'id' || field.endsWith('_id'));+ const brandOf = tool.brandOf;+ if (fields.includes('brand_id')) {+ return brandOf && 'input' in brandOf ? [] : [`${tool.name}: takes brand_id`];+ }+ if (ids.length > 0) {+ return brandOf && 'lookup' in brandOf && ids.includes(brandOf.idField)+ ? []+ : [`${tool.name}: takes ${ids.join(', ')}, so its brand is looked up`];+ }+ return brandOf === null ? [] : [`${tool.name}: names no brand or object`];+ });+ expect(problems).toEqual([]);+ for (const tool of CHAT_TOOLS) {+ if (tool.brandOf && 'lookup' in tool.brandOf) {+ expect(BRAND_LOOKUP_TABLES).toContain(tool.brandOf.lookup);+ }+ }+ // A row can't name a field its input lacks.+ expect(() => defineTool({ ...readRow, brandOf: { input: 'brand_id' } })).toThrow(+ /brand_id, which its input lacks/,+ );+ });++ it('leaves roles out only of a row open to every role, and never an Admin', () => {+ const write = { ...readRow, class: 'write' as const, defaultPolicy: 'ask', maxPolicy: 'ask' };+ expect(+ defineTool({ ...write, excludeRoles: ['agency_partner'] } as never).excludeRoles,+ ).toEqual(['agency_partner']);+ expect(defineTool(readRow).excludeRoles).toEqual([]);+ expect(() =>+ defineTool({ ...write, minRole: 'manager', excludeRoles: ['analyst'] } as never),+ ).toThrow(/every role/);+ expect(() => defineTool({ ...write, excludeRoles: ['admin'] } as never)).toThrow(/Admin/);+ });+it('keeps every execute at a click', () => {for (const tool of CHAT_TOOLS.filter((t) => t.class === 'execute')) {expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['click', 'click']);}- const execute = defineTool({ ...readRow, name: 'publish_test', class: 'execute' });+ const execute = defineTool({+ ...readRow,+ name: 'publish_test',+ class: 'execute',+ executeGroup: 'publishing',+ });expect([execute.defaultPolicy, execute.maxPolicy]).toEqual(['click', 'click']);+ expect(execute.executeGroup).toBe('publishing');+ // Every execute is in a go-live group, so the Managers' switch covers it.+ expect(() => defineTool({ ...readRow, class: 'execute' } as never)).toThrow(/go-live group/);// A row that asks for less than a click isn't defined at all.expect(() =>defineTool({ ...readRow, class: 'execute', defaultPolicy: 'always' } as never),@@ -321,6 +383,7 @@ describe('registryCatalog', () => {'class','costClass','defaultPolicy',+ 'excludeRoles','flags','key','maxPolicy',@@ -366,3 +429,72 @@ describe('registryCatalog', () => {expect(entry.flags).not.toBe(row.flags);});});++describe("the model's tool list on the registry's rows", () => {+ // CHAT-20 §21: the list equals the rows the role, plan, brand access and policy allow.+ const facts = (row: Parameters<typeof planFactsFromOrgRow>[0], cloud = true) => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', cloud ? 'true' : 'false');+ try {+ return planFactsFromOrgRow(row);+ } finally {+ vi.unstubAllEnvs();+ }+ };+ const list = (+ role: TeamRole,+ plan: ReturnType<typeof facts>,+ scope = { brandId: FIXTURE_IDS.brand as string | null, brandIsDemo: false },+ brandAccess: 'all' | string[] = 'all',+ ) =>+ allowedTools(+ CHAT_TOOLS,+ {+ organizationId: 'org-1',+ role,+ plan,+ settings: DEFAULT_CHAT_SETTINGS,+ mode: 'full_auto',+ surface: 'chat',+ autoChoices: new Set(),+ brandAccess,+ injectionDetected: false,+ },+ scope,+ ).map((tool) => tool.name);++ const reads = CHAT_TOOLS.filter((tool) => tool.class === 'read').map((tool) => tool.name);+ const writes = CHAT_TOOLS.filter((tool) => tool.class === 'write').map((tool) => tool.name);+ const starter = facts({ plan: 'starter', subscription_status: 'active' });+ const growth = facts({ plan: 'growth', subscription_status: 'active' });+ const withoutShopping = reads.filter((name) => name !== 'get_shopping_visibility');++ it('gives every role the reads its plan opens, and Analysts and Agency partners daily work only', () => {+ expect(list('analyst', starter)).toEqual([+ ...withoutShopping,+ 'create_draft',+ 'dismiss_prompt_suggestion',+ ]);+ expect(list('agency_partner', growth)).toEqual([...reads, 'create_draft']);+ expect(list('manager', starter)).toEqual([...withoutShopping, ...writes]);+ expect(list('admin', growth)).toEqual([...reads, ...writes]);+ expect(list('analyst', facts(null, false))).toEqual([+ ...reads,+ 'create_draft',+ 'dismiss_prompt_suggestion',+ ]);+ });++ it('lists reads only on a read-only workspace and on the demo brand', () => {+ const ended = facts({ plan: 'growth', subscription_status: 'canceled' });+ expect(list('admin', ended)).toEqual(withoutShopping);+ expect(list('admin', growth, { brandId: FIXTURE_IDS.brand, brandIsDemo: true })).toEqual(reads);+ });++ it("lists nothing for a brand outside the person's scope", () => {+ expect(list('agency_partner', growth, undefined, [])).toEqual([]);+ expect(list('agency_partner', growth, undefined, [FIXTURE_IDS.brand])).toEqual([+ ...reads,+ 'create_draft',+ ]);+ });+});diff --git a/web/src/lib/chat/registry/tools.ts b/web/src/lib/chat/registry/tools.tsindex f06985b36..8c4843ff1 100644--- a/web/src/lib/chat/registry/tools.ts+++ b/web/src/lib/chat/registry/tools.ts@@ -1,3 +1,4 @@+import type { TeamRole } from '@/components/providers/role-provider';import type { ChatTool, PlanGate, ToolFlags } from './define-tool';import { READ_TOOLS } from './read-tools';import { WRITE_TOOLS } from './write-tools';@@ -36,6 +37,8 @@ export type ToolCatalogEntry = Pick<key: string;flags: ToolFlags;planGate: PlanGate | null;+ /** Roles left out of a row open to every role. */+ excludeRoles: TeamRole[];};/**@@ -56,6 +59,7 @@ export function registryCatalog(tools: readonly ChatTool[] = CHAT_TOOLS): ToolCamaxPolicy: tool.maxPolicy,flags: { ...tool.flags },minRole: tool.minRole,+ excludeRoles: [...tool.excludeRoles],planGate: tool.planGate ? { ...tool.planGate } : null,costClass: tool.costClass,route: tool.route,diff --git a/web/src/lib/chat/registry/write-tools.ts b/web/src/lib/chat/registry/write-tools.tsindex 4d1040b83..cc96bd1d6 100644--- a/web/src/lib/chat/registry/write-tools.ts+++ b/web/src/lib/chat/registry/write-tools.ts@@ -14,6 +14,11 @@ import { FIXTURE_IDS, defineTool } from './define-tool';* through their session, with the read-only workspace check those actions* already run. They need that session: a run with no request behind it* (a schedule, CHAT-12) can't call them as they are.+ *+ * minRole follows the role model of 2026-10-29: daily work (drafts, tasks,+ * audits, reports) is open to every role; settings, deleting, adding prompts+ * and costly work stay with Admins and Managers. Where the server leaves a+ * role out of daily work, excludeRoles says so.*/const BRAND = FIXTURE_IDS.brand;@@ -28,8 +33,10 @@ export const WRITE_TOOLS = ["Save a page as a new draft in the brand's Content Library, as New content does: its title, page type, what it starts from (an opportunity, a tracked prompt, a topic, or content to optimize) and, when there is one, its HTML.",defaultPolicy: 'ask_full_auto',maxPolicy: 'always',- minRole: 'manager',+ // A draft is daily work; every member may already save one (content_drafts: member insert).+ minRole: 'analyst',planGate: null,+ brandOf: { input: 'brand_id' },costClass: 'C2',labelKey: 'saveDraft',route: '/dashboard/content/library',@@ -84,8 +91,10 @@ export const WRITE_TOOLS = ['Mark a content opportunity reviewed, or dismiss it, optionally saying why (not relevant, or the wrong angle).',defaultPolicy: 'ask_full_auto',maxPolicy: 'always',+ // Dismissing is Admin and Manager work, as the server's content routes and RLS have it.minRole: 'manager',planGate: null,+ brandOf: { lookup: 'content_opportunities', idField: 'opportunity_id' },costClass: 'C0',labelKey: 'opportunityStatus',route: '/dashboard/content',@@ -115,8 +124,11 @@ export const WRITE_TOOLS = ['Dismiss a pending prompt suggestion so it leaves the suggestion list. Only when the user asked for that suggestion to go.',defaultPolicy: 'ask_full_auto',maxPolicy: 'always',- minRole: 'manager',+ // Admins, Managers and Analysts, as the server (#1763), MCP (#1762) and RLS allow.+ minRole: 'analyst',+ excludeRoles: ['agency_partner'],planGate: null,+ brandOf: { lookup: 'prompt_suggestions', idField: 'suggestion_id' },costClass: 'C0',labelKey: 'dismissSuggestion',route: '/dashboard/prompts/suggestions',diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 16d3275cb..ed110140c 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1370,6 +1370,35 @@ export type Database = {},]}+ chat_auto_choices: {+ Row: {+ created_at: string+ organization_id: string+ tool_key: string+ user_id: string+ }+ Insert: {+ created_at?: string+ organization_id: string+ tool_key: string+ user_id: string+ }+ Update: {+ created_at?: string+ organization_id?: string+ tool_key?: string+ user_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "chat_auto_choices_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ ]+ }chat_conversations: {Row: {archived_at: string | null@@ -1584,6 +1613,44 @@ export type Database = {},]}+ chat_settings: {+ Row: {+ dont_ask_again: boolean+ full_auto_for_members: boolean+ manager_execute_off: string[]+ organization_id: string+ tool_policies: Json+ updated_at: string+ updated_by: string | null+ }+ Insert: {+ dont_ask_again?: boolean+ full_auto_for_members?: boolean+ manager_execute_off?: string[]+ organization_id: string+ tool_policies?: Json+ updated_at?: string+ updated_by?: string | null+ }+ Update: {+ dont_ask_again?: boolean+ full_auto_for_members?: boolean+ manager_execute_off?: string[]+ organization_id?: string+ tool_policies?: Json+ updated_at?: string+ updated_by?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "chat_settings_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: true+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ ]+ }chat_step_kinds: {Row: {kind: string@@ -5231,6 +5298,10 @@ export type Database = {Args: { p_values: string[] }Returns: boolean}+ chat_tool_policies_valid: {+ Args: { p_policies: Json }+ Returns: boolean+ }citation_competitor_sources: {Args: {p_brand_domains: string[]