Skip to content

fix(mcp): check the key's role before adding prompts or topics and dismissing - #1762

Merged
gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:fix/mcp-manager-writes
Oct 29, 2026
Merged

gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:fix/mcp-manager-writes

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

MCP and the public REST API now check the caller's team role before writes that add prompts or topics, or that dismiss, the same way the web app and the database's policies already do.

MCP keys previously carried no role (McpAuthContext), and writes run with the service role. As a result:

  • accept_prompt_suggestion let an analyst or agency partner add tracked prompts, which RLS limits to admins and managers;
  • dismissing an opportunity, which RLS also limits to admins and managers, was open to every role.

Changes

  • mcp-auth.ts reads the key owner's role and adds it to McpAuthContext. The in-app agent (lib/agent/auth.ts) reads it too.
  • web/src/lib/mcp/role-gate.ts: requireManager / requireRole. A refused tool says why. REST routes answer 403 { error: 'forbidden', code: 'role_required', message } through failedCallResponse.
  • The checks sit in the data functions (lib/mcp/data.ts), so the MCP tool and its REST twin follow one rule.
Tool / route Who may use it now
accept_prompt_suggestion admin, manager
accept_topic_suggestion, dismiss_topic_suggestion (+ /api/mcp/topic-suggestions/:id/*) admin, manager
dismiss_prompt_suggestion admin, manager, analyst
update_opportunity_status (+ REST PATCH) progress (in progress, done, reviewed) open to all; dismissing, or undoing a dismissal: admin, manager

Stays open to every role: create_content_draft, add_content_source, suggest_content_changes, set_content_draft_ready, update_task_status, run_site_audit. The costly generators (generate_content_brief, create_improve_action) are restricted in a follow-up PR.

Docs: docs/guides/mcp-server.mdx gets a role column and a "Roles" section.

Role model, as decided by the product owner on 2026-10-29:

  • daily work is open to every role;
  • settings, permanent deletes, adding prompts and costly actions are for admins and managers.

Related issue

None.

Type of change

  • fix — Bug fix

How to test

  • cd web && yarn vitest run src/lib/mcp/role-gate.test.ts src/lib/mcp-auth.test.ts 'src/app/api/content-opportunities/[id]/status/route.test.ts'
  • With an analyst's API key, accept_prompt_suggestion is refused with the reason. A manager's key adds the prompt.

Checklist

🤖 Generated with Claude Code

…smissing

The MCP tools write with the service role, so the row rules that keep
analysts from adding prompts never reached them: an analyst's key could
accept a prompt suggestion and add a tracked prompt. The key's role now
comes with the auth context and the data layer checks it, for the tool and
its REST route alike:

- accept_prompt_suggestion, accept_topic_suggestion and
  dismiss_topic_suggestion: admins and managers only.
- dismiss_prompt_suggestion: not agency partners, as the table's rule.
- update_opportunity_status: any member records progress; dismissing, or
  moving a dismissed one back, needs an admin or a manager.

Drafts, briefs, Site Audits, tasks and Improve actions stay open to every
member. A refused tool answers with the reason; the REST routes answer 403
role_required. The MCP guide names the role each write needs.

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

mintlify Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 6aa96c4.

Approve preview

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good, with follow-ups

Reviewed 9e11860, branched from ce9a3dc. Web only, no migration.

What I checked

  • The key carries its role. authenticateMcpRequest and the in-app agent's resolveAgentAuth read profiles.role on every request, alongside organization_id. A role change applies on the next call, and a key never stores a role of its own.
  • The checks are in the data functions. requireManager / requireRole run in lib/mcp/data.ts, so each MCP tool and its REST twin (/api/mcp/topic-suggestions/:id/accept|dismiss, PATCH /api/mcp/content-opportunities/:id/status) follow one rule. The prompt-suggestion tools have no REST twin.
  • Each tool against the table rules:
    • accept_prompt_suggestion: admin, manager, as the prompts insert rule.
    • dismiss_prompt_suggestion: admin, manager, analyst, as the prompt_suggestions update rule.
    • The topic tools: admin, manager, as the Topics page's card shows them (canManage). That is one step stricter than the topic_suggestions update rule, which also allows analysts. It is on purpose, under the role model in the description.
    • update_opportunity_status: progress stays open to every role. Dismissing, or moving a dismissed one back, needs an admin or a manager.
  • Refusals. A tool answers with an error and a message naming the roles allowed. REST answers 403 { error: 'forbidden', code: 'role_required', message } through failedCallResponse, next to its existing 402 subscription_inactive. Every other failure stays a 500 with its message, as before. The topic tools check the role before the lookup, so a refused caller gets the same 403 for any id; nothing is learned about other organizations' ids.
  • Embeds. One changed select: content_opportunities → brands!inner(organization_id) (only status added). One foreign key joins the two tables (content_opportunities_brand_id_fkey), so no hint is needed.
  • The tests catch it. I put main's data.ts, mcp-auth.ts, subscription-guard.ts and the status route back under the PR's tests: 5 tests fail (role-gate, mcp-auth, the status route). With the PR, role-gate, mcp-auth, subscription-gate and the status route pass (31 tests). The whole lib/mcp, api/mcp, api/v1 and lib/agent set and subscription-guard-coverage.test.ts pass at the tip of the stack (#1764): 31 files, 194 tests. Web tsc is clean. Prettier is clean on the touched files.
  • It merges cleanly on ce9a3dc and alongside #1763.

Follow-ups

  1. The Roles section lists briefs as open to every role. The description says generate_content_brief and create_improve_action move to admins and managers in a follow-up PR. That PR isn't open yet. When it lands, update this section in the same PR.
  2. Open MCP PRs type their test auth as McpAuthContext without role: #1728, #1729 and #1733 at least. Once this merges, each needs role: 'admin' (or the role under test) to keep web tsc green.
  3. This conflicts with #1739 in web/src/lib/mcp/data.ts and web/src/lib/subscription-guard.ts. Whichever merges second needs a merge of main.

@gkhngyk
gkhngyk merged commit af34333 into ansvisor:main Oct 29, 2026
5 of 6 checks passed
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 29, 2026
The MCP context has a role since ansvisor#1762; the registry's tests build one
without it, which fails the web typecheck once merged with main.
gkhngyk added a commit that referenced this pull request Oct 29, 2026
* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* test(chat): give the registry tests' MCP context a role

The MCP context has a role since #1762; the registry's tests build one
without it, which fails the web typecheck once merged with main.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* feat(chat): decide each tool call by plan, role, policy and mode

Chat's approval precedence (CHAT-20 §5): before every tool call the
server decides whether the person may run it now, and how: it runs, it
waits on an approval card, it waits on their click, or it is refused
with a reason. Nothing reads it yet; the engine (C3) calls it, behind
CHAT_AGENTIC.

- lib/chat/precedence.ts: decideToolCall and allowedTools, pure. Most
  restrictive first: brand scope; a read-only workspace (402), the demo
  brand and a Never policy refuse; an EXECUTE is at most a click and an
  always_card WRITE at most a card in every mode; then the plan gate,
  the live role, the Admin's policy and switches, the run mode, the
  person's "Don't ask again" and taint. Self-hosted has no plan gates;
  MCP gets no Full auto and no ticks (v1).
- lib/chat/denial.ts: the out-of-permission answer's four parts (what
  was asked, the rule and where it is set, who can by role, what to do
  next), from en.json, naming nothing outside the person's scope.
- lib/chat/plan-facts.ts: the plan's features, limits, trial, Full auto
  and step up, read from config/plans.ts through the organization row.
- lib/chat/precedence-context.ts: reads the live role, the plan, the
  workspace's Chat settings and the person's ticks fresh for every call.
  The demo flag reads false until the demo chain (#1734) merges.
- 00401: chat_settings (tool policy by label key, Full auto for
  non-Admins, "Don't ask again", go-live groups off for Managers;
  members read, the server writes) and chat_auto_choices (a person's
  ticks, theirs to read, add and remove).
- Registry: every EXECUTE row names its go-live group, and saving a
  draft opens to every role (the 2026-10-29 role model: daily work open,
  settings, deleting, prompts and costly work for Admins and Managers).

Tests: a fixture table of cases plus every combination of role, plan,
mode, surface, policy, switches, tick, taint and demo (about 135,000
decisions), one test per §21 criterion it covers.

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

* feat(chat): let analysts dismiss suggestions and run Always tools in Auto

Two decisions of 2026-10-29 for Chat's approval precedence:

- Roles: dismissing a prompt suggestion is open to Admins, Managers and
  Analysts, not Agency partners, as the server (#1763), MCP (#1762) and
  RLS have it. A registry row open to every role may now leave roles out
  (excludeRoles, never an Admin); the catalog carries it, and a denial's
  "who can" names the roles a row allows. Reviewing or dismissing a
  content opportunity stays with Admins and Managers.
- Always: a tool an Admin sets to Always runs without a card in Auto and
  Full auto, on any plan; Ask me first, MCP and untrusted content still
  show the card. CHAT-20 §5 step 5 ("Auto: each WRITE shows a card")
  now holds for tools not set to Always, so Always and "Ask (auto allowed
  in Full auto)" differ. EXECUTE and always_card rows still can't be
  Always.

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

* feat(chat): keep Always behind Full auto's plan lock

An Admin's Always runs a change without a card only where Full auto is
open: on Starter and in the trial it asks as Ask does, with the reason
full_auto_locked, so Always can't get past the plan difference.
policyChoiceLock tells Settings › Chat to show Always and "Ask (auto
allowed in Full auto)" locked there, for the same reason.

Always still doesn't need "Full auto for members": it is the Admin's own
choice for one tool, now said in the code.

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

* fix(chat): find each call's brand, keep unknown surfaces closed and gate MCP by plan

Review of Chat's approval precedence:

- Every registry row says where a call's brand comes from (brandOf): the
  input's brand_id, or the brand of the row an object's id names
  (content_opportunities, prompt_suggestions, prompt_results,
  content_drafts, actions, site_audits). The server finds it in the
  person's workspace (resolveCallBrand checks brands.organization_id, so
  'all' never reaches another workspace's brand), and a brand-bound call
  whose brand isn't found is refused as brand_scope. A run about no
  brand yet still lists the brand-bound rows. The registry test checks
  every row that takes a brand or an id says so.
- A surface other than Chat, or one the code doesn't know, is the closed
  side: its writes always ask. A mode it doesn't know is Ask me first,
  and readPrecedenceContext checks both against CHAT_MODES and
  CHAT_SURFACES.
- MCP's plan gates (CHAT-20 §7, §17): nothing in the trial, reads only on
  Starter, writes and executes from Growth; allowedTools follows.
- decideOrDeny refuses a call without a context (no_access), with its
  denial words. DEFAULT_CHAT_SETTINGS is frozen. A note for the engine:
  an approval or a click decides again before it runs.
- A type test stops compiling once #1734 adds brands.is_demo, so the
  demo flag gets wired then; another checks every lookup table has
  brand_id.
- Tests: Full auto off for members with ticks on, the tick rule against
  role, switch and surface both ways, a detected injection in every
  combination, and rows for an unknown surface and mode.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
…1780)

* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* feat(chat): decide each tool call by plan, role, policy and mode

Chat's approval precedence (CHAT-20 §5): before every tool call the
server decides whether the person may run it now, and how: it runs, it
waits on an approval card, it waits on their click, or it is refused
with a reason. Nothing reads it yet; the engine (C3) calls it, behind
CHAT_AGENTIC.

- lib/chat/precedence.ts: decideToolCall and allowedTools, pure. Most
  restrictive first: brand scope; a read-only workspace (402), the demo
  brand and a Never policy refuse; an EXECUTE is at most a click and an
  always_card WRITE at most a card in every mode; then the plan gate,
  the live role, the Admin's policy and switches, the run mode, the
  person's "Don't ask again" and taint. Self-hosted has no plan gates;
  MCP gets no Full auto and no ticks (v1).
- lib/chat/denial.ts: the out-of-permission answer's four parts (what
  was asked, the rule and where it is set, who can by role, what to do
  next), from en.json, naming nothing outside the person's scope.
- lib/chat/plan-facts.ts: the plan's features, limits, trial, Full auto
  and step up, read from config/plans.ts through the organization row.
- lib/chat/precedence-context.ts: reads the live role, the plan, the
  workspace's Chat settings and the person's ticks fresh for every call.
  The demo flag reads false until the demo chain (#1734) merges.
- 00401: chat_settings (tool policy by label key, Full auto for
  non-Admins, "Don't ask again", go-live groups off for Managers;
  members read, the server writes) and chat_auto_choices (a person's
  ticks, theirs to read, add and remove).
- Registry: every EXECUTE row names its go-live group, and saving a
  draft opens to every role (the 2026-10-29 role model: daily work open,
  settings, deleting, prompts and costly work for Admins and Managers).

Tests: a fixture table of cases plus every combination of role, plan,
mode, surface, policy, switches, tick, taint and demo (about 135,000
decisions), one test per §21 criterion it covers.

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

* feat(chat): let analysts dismiss suggestions and run Always tools in Auto

Two decisions of 2026-10-29 for Chat's approval precedence:

- Roles: dismissing a prompt suggestion is open to Admins, Managers and
  Analysts, not Agency partners, as the server (#1763), MCP (#1762) and
  RLS have it. A registry row open to every role may now leave roles out
  (excludeRoles, never an Admin); the catalog carries it, and a denial's
  "who can" names the roles a row allows. Reviewing or dismissing a
  content opportunity stays with Admins and Managers.
- Always: a tool an Admin sets to Always runs without a card in Auto and
  Full auto, on any plan; Ask me first, MCP and untrusted content still
  show the card. CHAT-20 §5 step 5 ("Auto: each WRITE shows a card")
  now holds for tools not set to Always, so Always and "Ask (auto allowed
  in Full auto)" differ. EXECUTE and always_card rows still can't be
  Always.

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

* feat(chat): keep Always behind Full auto's plan lock

An Admin's Always runs a change without a card only where Full auto is
open: on Starter and in the trial it asks as Ask does, with the reason
full_auto_locked, so Always can't get past the plan difference.
policyChoiceLock tells Settings › Chat to show Always and "Ask (auto
allowed in Full auto)" locked there, for the same reason.

Always still doesn't need "Full auto for members": it is the Admin's own
choice for one tool, now said in the code.

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

* fix(chat): find each call's brand, keep unknown surfaces closed and gate MCP by plan

Review of Chat's approval precedence:

- Every registry row says where a call's brand comes from (brandOf): the
  input's brand_id, or the brand of the row an object's id names
  (content_opportunities, prompt_suggestions, prompt_results,
  content_drafts, actions, site_audits). The server finds it in the
  person's workspace (resolveCallBrand checks brands.organization_id, so
  'all' never reaches another workspace's brand), and a brand-bound call
  whose brand isn't found is refused as brand_scope. A run about no
  brand yet still lists the brand-bound rows. The registry test checks
  every row that takes a brand or an id says so.
- A surface other than Chat, or one the code doesn't know, is the closed
  side: its writes always ask. A mode it doesn't know is Ask me first,
  and readPrecedenceContext checks both against CHAT_MODES and
  CHAT_SURFACES.
- MCP's plan gates (CHAT-20 §7, §17): nothing in the trial, reads only on
  Starter, writes and executes from Growth; allowedTools follows.
- decideOrDeny refuses a call without a context (no_access), with its
  denial words. DEFAULT_CHAT_SETTINGS is frozen. A note for the engine:
  an approval or a click decides again before it runs.
- A type test stops compiling once #1734 adds brands.is_demo, so the
  demo flag gets wired then; another checks every lookup table has
  brand_id.
- Tests: Full auto off for members with ticks on, the tick rule against
  role, switch and surface both ways, a detected injection in every
  combination, and rows for an unknown surface and mode.

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

* feat(chat): show roles and access, your own access, your plan and what Chat can do

Chat P0 B1 (CHAT-20 §4a, §4b, §7a, §8), behind CHAT_AGENTIC: the
dashboard's layout reads the flag on the server and hands the browser
only the answer (ChatAgenticProvider).

- Settings › Roles & access (after Team, everyone reads it): the plan
  card, members with their role, brands, what they do through Chat and
  their last sign-in (e-mails for Admins only), what each role can do in
  the app and through Chat (CHAT-20 §4's matrix), and the Admin switches
  that change a role's rights (Managers going live, Full auto) with who
  set them. Admins change another member's role here as in Team; the
  rest of the team's management stays in Team.
- Settings › Account: a Your access card (role, brands, what Chat may do
  as you, the go-live groups an Admin switched off for Managers), linking
  to Roles & access and to "What Chat can do".
- The sidebar's profile row says the person's role.
- "What Chat can do" (/dashboard/chat/capabilities): the registry by
  area (registryCatalog), with how each change is approved, who may make
  it, and the plan a row needs, searchable and filtered by class. Only
  what the registry has is listed: a capability not in it isn't Chat's.
- Your plan (§7a): plan and price, what it includes and locks ("Needs
  Growth · you're on Starter"), AI usage as a percentage, and what the
  next plan adds from config/plans.ts (more platforms, Full auto, MCP
  writes, the AI limit's multiple; Claude tracking and a contract on
  Enterprise; "After your trial" on the trial). Upgrade for Admins only;
  no upsell or lock lines on Enterprise. No AI budget in dollars.

getChatAccess / listRoleMembers read the facts the approval precedence
checks (readPrecedenceContext), so a page and the server agree.
readMemberAuth gives a member's e-mail and last sign-in from one call.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
#1781)

* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* feat(chat): decide each tool call by plan, role, policy and mode

Chat's approval precedence (CHAT-20 §5): before every tool call the
server decides whether the person may run it now, and how: it runs, it
waits on an approval card, it waits on their click, or it is refused
with a reason. Nothing reads it yet; the engine (C3) calls it, behind
CHAT_AGENTIC.

- lib/chat/precedence.ts: decideToolCall and allowedTools, pure. Most
  restrictive first: brand scope; a read-only workspace (402), the demo
  brand and a Never policy refuse; an EXECUTE is at most a click and an
  always_card WRITE at most a card in every mode; then the plan gate,
  the live role, the Admin's policy and switches, the run mode, the
  person's "Don't ask again" and taint. Self-hosted has no plan gates;
  MCP gets no Full auto and no ticks (v1).
- lib/chat/denial.ts: the out-of-permission answer's four parts (what
  was asked, the rule and where it is set, who can by role, what to do
  next), from en.json, naming nothing outside the person's scope.
- lib/chat/plan-facts.ts: the plan's features, limits, trial, Full auto
  and step up, read from config/plans.ts through the organization row.
- lib/chat/precedence-context.ts: reads the live role, the plan, the
  workspace's Chat settings and the person's ticks fresh for every call.
  The demo flag reads false until the demo chain (#1734) merges.
- 00401: chat_settings (tool policy by label key, Full auto for
  non-Admins, "Don't ask again", go-live groups off for Managers;
  members read, the server writes) and chat_auto_choices (a person's
  ticks, theirs to read, add and remove).
- Registry: every EXECUTE row names its go-live group, and saving a
  draft opens to every role (the 2026-10-29 role model: daily work open,
  settings, deleting, prompts and costly work for Admins and Managers).

Tests: a fixture table of cases plus every combination of role, plan,
mode, surface, policy, switches, tick, taint and demo (about 135,000
decisions), one test per §21 criterion it covers.

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

* feat(chat): let analysts dismiss suggestions and run Always tools in Auto

Two decisions of 2026-10-29 for Chat's approval precedence:

- Roles: dismissing a prompt suggestion is open to Admins, Managers and
  Analysts, not Agency partners, as the server (#1763), MCP (#1762) and
  RLS have it. A registry row open to every role may now leave roles out
  (excludeRoles, never an Admin); the catalog carries it, and a denial's
  "who can" names the roles a row allows. Reviewing or dismissing a
  content opportunity stays with Admins and Managers.
- Always: a tool an Admin sets to Always runs without a card in Auto and
  Full auto, on any plan; Ask me first, MCP and untrusted content still
  show the card. CHAT-20 §5 step 5 ("Auto: each WRITE shows a card")
  now holds for tools not set to Always, so Always and "Ask (auto allowed
  in Full auto)" differ. EXECUTE and always_card rows still can't be
  Always.

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

* feat(chat): keep Always behind Full auto's plan lock

An Admin's Always runs a change without a card only where Full auto is
open: on Starter and in the trial it asks as Ask does, with the reason
full_auto_locked, so Always can't get past the plan difference.
policyChoiceLock tells Settings › Chat to show Always and "Ask (auto
allowed in Full auto)" locked there, for the same reason.

Always still doesn't need "Full auto for members": it is the Admin's own
choice for one tool, now said in the code.

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

* fix(chat): find each call's brand, keep unknown surfaces closed and gate MCP by plan

Review of Chat's approval precedence:

- Every registry row says where a call's brand comes from (brandOf): the
  input's brand_id, or the brand of the row an object's id names
  (content_opportunities, prompt_suggestions, prompt_results,
  content_drafts, actions, site_audits). The server finds it in the
  person's workspace (resolveCallBrand checks brands.organization_id, so
  'all' never reaches another workspace's brand), and a brand-bound call
  whose brand isn't found is refused as brand_scope. A run about no
  brand yet still lists the brand-bound rows. The registry test checks
  every row that takes a brand or an id says so.
- A surface other than Chat, or one the code doesn't know, is the closed
  side: its writes always ask. A mode it doesn't know is Ask me first,
  and readPrecedenceContext checks both against CHAT_MODES and
  CHAT_SURFACES.
- MCP's plan gates (CHAT-20 §7, §17): nothing in the trial, reads only on
  Starter, writes and executes from Growth; allowedTools follows.
- decideOrDeny refuses a call without a context (no_access), with its
  denial words. DEFAULT_CHAT_SETTINGS is frozen. A note for the engine:
  an approval or a click decides again before it runs.
- A type test stops compiling once #1734 adds brands.is_demo, so the
  demo flag gets wired then; another checks every lookup table has
  brand_id.
- Tests: Full auto off for members with ticks on, the tick rule against
  role, switch and surface both ways, a detected injection in every
  combination, and rows for an unknown surface and mode.

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

* feat(chat): show roles and access, your own access, your plan and what Chat can do

Chat P0 B1 (CHAT-20 §4a, §4b, §7a, §8), behind CHAT_AGENTIC: the
dashboard's layout reads the flag on the server and hands the browser
only the answer (ChatAgenticProvider).

- Settings › Roles & access (after Team, everyone reads it): the plan
  card, members with their role, brands, what they do through Chat and
  their last sign-in (e-mails for Admins only), what each role can do in
  the app and through Chat (CHAT-20 §4's matrix), and the Admin switches
  that change a role's rights (Managers going live, Full auto) with who
  set them. Admins change another member's role here as in Team; the
  rest of the team's management stays in Team.
- Settings › Account: a Your access card (role, brands, what Chat may do
  as you, the go-live groups an Admin switched off for Managers), linking
  to Roles & access and to "What Chat can do".
- The sidebar's profile row says the person's role.
- "What Chat can do" (/dashboard/chat/capabilities): the registry by
  area (registryCatalog), with how each change is approved, who may make
  it, and the plan a row needs, searchable and filtered by class. Only
  what the registry has is listed: a capability not in it isn't Chat's.
- Your plan (§7a): plan and price, what it includes and locks ("Needs
  Growth · you're on Starter"), AI usage as a percentage, and what the
  next plan adds from config/plans.ts (more platforms, Full auto, MCP
  writes, the AI limit's multiple; Claude tracking and a contract on
  Enterprise; "After your trial" on the trial). Upgrade for Admins only;
  no upsell or lock lines on Enterprise. No AI budget in dollars.

getChatAccess / listRoleMembers read the facts the approval precedence
checks (readPrecedenceContext), so a page and the server agree.
readMemberAuth gives a member's e-mail and last sign-in from one call.

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

* feat(chat): ask your Admin for access, and record every denial

Chat P0 B2 (CHAT-20 §4c, registry row 80a), behind CHAT_AGENTIC.

- chat_access_requests (00403): what was asked, the rule that refused it
  (role, plan, policy, workspace, brand, demo) and its words, the refused
  tool's label key, the chat it came from and any drafted change; pending
  until an Admin approves or dismisses it (the first to act decides) or
  the person withdraws it. The server writes every row; the requester
  reads their own, the workspace's Admins all of its.
- requestAccess: only by the person's click; Admins have no one to ask;
  at most 10 waiting per person, and the same ask (tool key and words,
  case and spacing aside) once a day; a brand or chat that isn't theirs
  is dropped. withdrawAccessRequest, decideAccessRequest (Admins only),
  listAccessRequests (an Admin's: the workspace's; anyone else's: their
  own; waiting first, then 30 days of decided ones) and the count.
- Registry row request_access ("Ask your Admin"): Ask fixed, always a
  card, every role, no brand; it calls requestAccess, as the buttons do.
- Ask your Admin buttons: on Roles & access' read-only bar and the Your
  access card (a role), and in Upgrade's place on the plan card for
  anyone but an Admin (the next plan), with the person's words editable.
- Roles & access › Requests: an Admin approves or dismisses, anyone else
  withdraws theirs; Settings shows an Admin the waiting count on Roles &
  access.
- recordAccessDenied (lib/chat/access-log.ts): one typed way in for
  every denial (who, the tool's label key and class, surface, the
  reason, brand unless out of scope, chat and run). The server's log
  for now; the Activity log (A4) fills it in without a caller changing.

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

* fix(chat): bound access requests per day and their drafted change, and keep asking open on a read-only workspace

- At most 20 requests a person sends in a UTC day, withdrawn ones too:
  withdrawing frees a pending place, so the pending cap alone didn't
  bound a day's rows. A new daily_limit answer says so.
- A drafted change is at most 8,000 characters of JSON on the server,
  with a 32 KB check in 00403 behind it.
- requestAccess, withdrawAccessRequest and decideAccessRequest are named
  in the read-only coverage list: asking costs nothing and a lapsed plan
  is one of the things to ask about; withdrawing and deciding change no
  one's access.

* fix(chat): give Ask your Admin an Undo that withdraws the request, as every Chat write has one

#1786 logs every WRITE row with an Undo and words for it. request_access
now withdraws the request while it waits (7 days; once an Admin decided
it, it stays), with its summary lines, and the Full auto test skips it:
it's always a card, so only the person's click sends it.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
#1782)

* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* feat(chat): decide each tool call by plan, role, policy and mode

Chat's approval precedence (CHAT-20 §5): before every tool call the
server decides whether the person may run it now, and how: it runs, it
waits on an approval card, it waits on their click, or it is refused
with a reason. Nothing reads it yet; the engine (C3) calls it, behind
CHAT_AGENTIC.

- lib/chat/precedence.ts: decideToolCall and allowedTools, pure. Most
  restrictive first: brand scope; a read-only workspace (402), the demo
  brand and a Never policy refuse; an EXECUTE is at most a click and an
  always_card WRITE at most a card in every mode; then the plan gate,
  the live role, the Admin's policy and switches, the run mode, the
  person's "Don't ask again" and taint. Self-hosted has no plan gates;
  MCP gets no Full auto and no ticks (v1).
- lib/chat/denial.ts: the out-of-permission answer's four parts (what
  was asked, the rule and where it is set, who can by role, what to do
  next), from en.json, naming nothing outside the person's scope.
- lib/chat/plan-facts.ts: the plan's features, limits, trial, Full auto
  and step up, read from config/plans.ts through the organization row.
- lib/chat/precedence-context.ts: reads the live role, the plan, the
  workspace's Chat settings and the person's ticks fresh for every call.
  The demo flag reads false until the demo chain (#1734) merges.
- 00401: chat_settings (tool policy by label key, Full auto for
  non-Admins, "Don't ask again", go-live groups off for Managers;
  members read, the server writes) and chat_auto_choices (a person's
  ticks, theirs to read, add and remove).
- Registry: every EXECUTE row names its go-live group, and saving a
  draft opens to every role (the 2026-10-29 role model: daily work open,
  settings, deleting, prompts and costly work for Admins and Managers).

Tests: a fixture table of cases plus every combination of role, plan,
mode, surface, policy, switches, tick, taint and demo (about 135,000
decisions), one test per §21 criterion it covers.

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

* feat(chat): let analysts dismiss suggestions and run Always tools in Auto

Two decisions of 2026-10-29 for Chat's approval precedence:

- Roles: dismissing a prompt suggestion is open to Admins, Managers and
  Analysts, not Agency partners, as the server (#1763), MCP (#1762) and
  RLS have it. A registry row open to every role may now leave roles out
  (excludeRoles, never an Admin); the catalog carries it, and a denial's
  "who can" names the roles a row allows. Reviewing or dismissing a
  content opportunity stays with Admins and Managers.
- Always: a tool an Admin sets to Always runs without a card in Auto and
  Full auto, on any plan; Ask me first, MCP and untrusted content still
  show the card. CHAT-20 §5 step 5 ("Auto: each WRITE shows a card")
  now holds for tools not set to Always, so Always and "Ask (auto allowed
  in Full auto)" differ. EXECUTE and always_card rows still can't be
  Always.

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

* feat(chat): keep Always behind Full auto's plan lock

An Admin's Always runs a change without a card only where Full auto is
open: on Starter and in the trial it asks as Ask does, with the reason
full_auto_locked, so Always can't get past the plan difference.
policyChoiceLock tells Settings › Chat to show Always and "Ask (auto
allowed in Full auto)" locked there, for the same reason.

Always still doesn't need "Full auto for members": it is the Admin's own
choice for one tool, now said in the code.

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

* fix(chat): find each call's brand, keep unknown surfaces closed and gate MCP by plan

Review of Chat's approval precedence:

- Every registry row says where a call's brand comes from (brandOf): the
  input's brand_id, or the brand of the row an object's id names
  (content_opportunities, prompt_suggestions, prompt_results,
  content_drafts, actions, site_audits). The server finds it in the
  person's workspace (resolveCallBrand checks brands.organization_id, so
  'all' never reaches another workspace's brand), and a brand-bound call
  whose brand isn't found is refused as brand_scope. A run about no
  brand yet still lists the brand-bound rows. The registry test checks
  every row that takes a brand or an id says so.
- A surface other than Chat, or one the code doesn't know, is the closed
  side: its writes always ask. A mode it doesn't know is Ask me first,
  and readPrecedenceContext checks both against CHAT_MODES and
  CHAT_SURFACES.
- MCP's plan gates (CHAT-20 §7, §17): nothing in the trial, reads only on
  Starter, writes and executes from Growth; allowedTools follows.
- decideOrDeny refuses a call without a context (no_access), with its
  denial words. DEFAULT_CHAT_SETTINGS is frozen. A note for the engine:
  an approval or a click decides again before it runs.
- A type test stops compiling once #1734 adds brands.is_demo, so the
  demo flag gets wired then; another checks every lookup table has
  brand_id.
- Tests: Full auto off for members with ticks on, the tick rule against
  role, switch and surface both ways, a detected injection in every
  combination, and rows for an unknown surface and mode.

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

* feat(chat): show roles and access, your own access, your plan and what Chat can do

Chat P0 B1 (CHAT-20 §4a, §4b, §7a, §8), behind CHAT_AGENTIC: the
dashboard's layout reads the flag on the server and hands the browser
only the answer (ChatAgenticProvider).

- Settings › Roles & access (after Team, everyone reads it): the plan
  card, members with their role, brands, what they do through Chat and
  their last sign-in (e-mails for Admins only), what each role can do in
  the app and through Chat (CHAT-20 §4's matrix), and the Admin switches
  that change a role's rights (Managers going live, Full auto) with who
  set them. Admins change another member's role here as in Team; the
  rest of the team's management stays in Team.
- Settings › Account: a Your access card (role, brands, what Chat may do
  as you, the go-live groups an Admin switched off for Managers), linking
  to Roles & access and to "What Chat can do".
- The sidebar's profile row says the person's role.
- "What Chat can do" (/dashboard/chat/capabilities): the registry by
  area (registryCatalog), with how each change is approved, who may make
  it, and the plan a row needs, searchable and filtered by class. Only
  what the registry has is listed: a capability not in it isn't Chat's.
- Your plan (§7a): plan and price, what it includes and locks ("Needs
  Growth · you're on Starter"), AI usage as a percentage, and what the
  next plan adds from config/plans.ts (more platforms, Full auto, MCP
  writes, the AI limit's multiple; Claude tracking and a contract on
  Enterprise; "After your trial" on the trial). Upgrade for Admins only;
  no upsell or lock lines on Enterprise. No AI budget in dollars.

getChatAccess / listRoleMembers read the facts the approval precedence
checks (readPrecedenceContext), so a page and the server agree.
readMemberAuth gives a member's e-mail and last sign-in from one call.

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

* feat(chat): ask your Admin for access, and record every denial

Chat P0 B2 (CHAT-20 §4c, registry row 80a), behind CHAT_AGENTIC.

- chat_access_requests (00403): what was asked, the rule that refused it
  (role, plan, policy, workspace, brand, demo) and its words, the refused
  tool's label key, the chat it came from and any drafted change; pending
  until an Admin approves or dismisses it (the first to act decides) or
  the person withdraws it. The server writes every row; the requester
  reads their own, the workspace's Admins all of its.
- requestAccess: only by the person's click; Admins have no one to ask;
  at most 10 waiting per person, and the same ask (tool key and words,
  case and spacing aside) once a day; a brand or chat that isn't theirs
  is dropped. withdrawAccessRequest, decideAccessRequest (Admins only),
  listAccessRequests (an Admin's: the workspace's; anyone else's: their
  own; waiting first, then 30 days of decided ones) and the count.
- Registry row request_access ("Ask your Admin"): Ask fixed, always a
  card, every role, no brand; it calls requestAccess, as the buttons do.
- Ask your Admin buttons: on Roles & access' read-only bar and the Your
  access card (a role), and in Upgrade's place on the plan card for
  anyone but an Admin (the next plan), with the person's words editable.
- Roles & access › Requests: an Admin approves or dismisses, anyone else
  withdraws theirs; Settings shows an Admin the waiting count on Roles &
  access.
- recordAccessDenied (lib/chat/access-log.ts): one typed way in for
  every denial (who, the tool's label key and class, surface, the
  reason, brand unless out of scope, chat and run). The server's log
  for now; the Activity log (A4) fills it in without a caller changing.

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

* feat(chat): set Chat's tool policy, Full auto and what Managers take live in Settings

Chat P0 B3, part 1 (CHAT-20 §5, §8b; mockup #g-policy), behind
CHAT_AGENTIC: a Settings › Chat section, listed last, for every role.

- Run modes: Full auto for members and "Don't ask again" (Growth and up,
  locked below with "Needs Growth · you're on …"); Full auto over MCP
  (off in v1) and untrusted content (every WRITE asks) as fixed rules.
- Who decides: the six steps of the approval precedence.
- Tool policy by area: every registry row by its label, never its name,
  its class, what applies, and what it does in Full auto. An Admin picks
  among what the row offers (policyChoices: a read only Never where it
  may be switched off, an EXECUTE only Never, a WRITE up to its maximum,
  so never Always on an always-card row), with what the plan locks
  (policyChoiceLock) disabled, or gives it back its default; Reset to
  defaults.
- What Managers may take live: the four go-live groups.
- Your auto changes: the person's own "Don't ask again" ticks, which
  anyone removes, on a read-only workspace too.

lib/actions/chat-settings.ts reads the facts the precedence decides on
and checks every change again on the server (an Admin, an active plan,
the row's choices, the plan's locks). Every action answers { ok } with a
typed failure and never throws (#1777's pattern). The Activity log page
follows A4 (00402).

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

* fix(chat): answer a failed read on the access pages in its result, never by throwing

As #1777: getChatAccess, listRoleMembers, listAccessRequests and
countPendingAccessRequests answer { ok } with `chat_off` or `failed`
instead of throwing when the database doesn't answer, so a page never
shows React's hidden error message.

- Roles & access says it couldn't load, with Retry; the requests list
  says so on its own, apart from the rest of the page.
- "What Chat can do" is not found with Chat off, and says it couldn't
  load, with Retry, on a failed read.
- The Your access card and the Settings count stay hidden on a failure.

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

* test(chat): name why Chat's settings actions stay out of assertWritable

Each one checks the plan itself (asAdmin: ctx.plan.writable) so that a
read-only workspace gets read_only as a result rather than a throw;
removeAutoChoice only takes an auto-approval back. The read-only coverage
test failed without them.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* feat(chat): decide each tool call by plan, role, policy and mode

Chat's approval precedence (CHAT-20 §5): before every tool call the
server decides whether the person may run it now, and how: it runs, it
waits on an approval card, it waits on their click, or it is refused
with a reason. Nothing reads it yet; the engine (C3) calls it, behind
CHAT_AGENTIC.

- lib/chat/precedence.ts: decideToolCall and allowedTools, pure. Most
  restrictive first: brand scope; a read-only workspace (402), the demo
  brand and a Never policy refuse; an EXECUTE is at most a click and an
  always_card WRITE at most a card in every mode; then the plan gate,
  the live role, the Admin's policy and switches, the run mode, the
  person's "Don't ask again" and taint. Self-hosted has no plan gates;
  MCP gets no Full auto and no ticks (v1).
- lib/chat/denial.ts: the out-of-permission answer's four parts (what
  was asked, the rule and where it is set, who can by role, what to do
  next), from en.json, naming nothing outside the person's scope.
- lib/chat/plan-facts.ts: the plan's features, limits, trial, Full auto
  and step up, read from config/plans.ts through the organization row.
- lib/chat/precedence-context.ts: reads the live role, the plan, the
  workspace's Chat settings and the person's ticks fresh for every call.
  The demo flag reads false until the demo chain (#1734) merges.
- 00401: chat_settings (tool policy by label key, Full auto for
  non-Admins, "Don't ask again", go-live groups off for Managers;
  members read, the server writes) and chat_auto_choices (a person's
  ticks, theirs to read, add and remove).
- Registry: every EXECUTE row names its go-live group, and saving a
  draft opens to every role (the 2026-10-29 role model: daily work open,
  settings, deleting, prompts and costly work for Admins and Managers).

Tests: a fixture table of cases plus every combination of role, plan,
mode, surface, policy, switches, tick, taint and demo (about 135,000
decisions), one test per §21 criterion it covers.

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

* feat(chat): let analysts dismiss suggestions and run Always tools in Auto

Two decisions of 2026-10-29 for Chat's approval precedence:

- Roles: dismissing a prompt suggestion is open to Admins, Managers and
  Analysts, not Agency partners, as the server (#1763), MCP (#1762) and
  RLS have it. A registry row open to every role may now leave roles out
  (excludeRoles, never an Admin); the catalog carries it, and a denial's
  "who can" names the roles a row allows. Reviewing or dismissing a
  content opportunity stays with Admins and Managers.
- Always: a tool an Admin sets to Always runs without a card in Auto and
  Full auto, on any plan; Ask me first, MCP and untrusted content still
  show the card. CHAT-20 §5 step 5 ("Auto: each WRITE shows a card")
  now holds for tools not set to Always, so Always and "Ask (auto allowed
  in Full auto)" differ. EXECUTE and always_card rows still can't be
  Always.

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

* feat(chat): keep Always behind Full auto's plan lock

An Admin's Always runs a change without a card only where Full auto is
open: on Starter and in the trial it asks as Ask does, with the reason
full_auto_locked, so Always can't get past the plan difference.
policyChoiceLock tells Settings › Chat to show Always and "Ask (auto
allowed in Full auto)" locked there, for the same reason.

Always still doesn't need "Full auto for members": it is the Admin's own
choice for one tool, now said in the code.

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

* fix(chat): find each call's brand, keep unknown surfaces closed and gate MCP by plan

Review of Chat's approval precedence:

- Every registry row says where a call's brand comes from (brandOf): the
  input's brand_id, or the brand of the row an object's id names
  (content_opportunities, prompt_suggestions, prompt_results,
  content_drafts, actions, site_audits). The server finds it in the
  person's workspace (resolveCallBrand checks brands.organization_id, so
  'all' never reaches another workspace's brand), and a brand-bound call
  whose brand isn't found is refused as brand_scope. A run about no
  brand yet still lists the brand-bound rows. The registry test checks
  every row that takes a brand or an id says so.
- A surface other than Chat, or one the code doesn't know, is the closed
  side: its writes always ask. A mode it doesn't know is Ask me first,
  and readPrecedenceContext checks both against CHAT_MODES and
  CHAT_SURFACES.
- MCP's plan gates (CHAT-20 §7, §17): nothing in the trial, reads only on
  Starter, writes and executes from Growth; allowedTools follows.
- decideOrDeny refuses a call without a context (no_access), with its
  denial words. DEFAULT_CHAT_SETTINGS is frozen. A note for the engine:
  an approval or a click decides again before it runs.
- A type test stops compiling once #1734 adds brands.is_demo, so the
  demo flag gets wired then; another checks every lookup table has
  brand_id.
- Tests: Full auto off for members with ticks on, the tick rule against
  role, switch and surface both ways, a detected injection in every
  combination, and rows for an unknown surface and mode.

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

* feat(chat): show roles and access, your own access, your plan and what Chat can do

Chat P0 B1 (CHAT-20 §4a, §4b, §7a, §8), behind CHAT_AGENTIC: the
dashboard's layout reads the flag on the server and hands the browser
only the answer (ChatAgenticProvider).

- Settings › Roles & access (after Team, everyone reads it): the plan
  card, members with their role, brands, what they do through Chat and
  their last sign-in (e-mails for Admins only), what each role can do in
  the app and through Chat (CHAT-20 §4's matrix), and the Admin switches
  that change a role's rights (Managers going live, Full auto) with who
  set them. Admins change another member's role here as in Team; the
  rest of the team's management stays in Team.
- Settings › Account: a Your access card (role, brands, what Chat may do
  as you, the go-live groups an Admin switched off for Managers), linking
  to Roles & access and to "What Chat can do".
- The sidebar's profile row says the person's role.
- "What Chat can do" (/dashboard/chat/capabilities): the registry by
  area (registryCatalog), with how each change is approved, who may make
  it, and the plan a row needs, searchable and filtered by class. Only
  what the registry has is listed: a capability not in it isn't Chat's.
- Your plan (§7a): plan and price, what it includes and locks ("Needs
  Growth · you're on Starter"), AI usage as a percentage, and what the
  next plan adds from config/plans.ts (more platforms, Full auto, MCP
  writes, the AI limit's multiple; Claude tracking and a contract on
  Enterprise; "After your trial" on the trial). Upgrade for Admins only;
  no upsell or lock lines on Enterprise. No AI budget in dollars.

getChatAccess / listRoleMembers read the facts the approval precedence
checks (readPrecedenceContext), so a page and the server agree.
readMemberAuth gives a member's e-mail and last sign-in from one call.

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

* feat(chat): ask your Admin for access, and record every denial

Chat P0 B2 (CHAT-20 §4c, registry row 80a), behind CHAT_AGENTIC.

- chat_access_requests (00403): what was asked, the rule that refused it
  (role, plan, policy, workspace, brand, demo) and its words, the refused
  tool's label key, the chat it came from and any drafted change; pending
  until an Admin approves or dismisses it (the first to act decides) or
  the person withdraws it. The server writes every row; the requester
  reads their own, the workspace's Admins all of its.
- requestAccess: only by the person's click; Admins have no one to ask;
  at most 10 waiting per person, and the same ask (tool key and words,
  case and spacing aside) once a day; a brand or chat that isn't theirs
  is dropped. withdrawAccessRequest, decideAccessRequest (Admins only),
  listAccessRequests (an Admin's: the workspace's; anyone else's: their
  own; waiting first, then 30 days of decided ones) and the count.
- Registry row request_access ("Ask your Admin"): Ask fixed, always a
  card, every role, no brand; it calls requestAccess, as the buttons do.
- Ask your Admin buttons: on Roles & access' read-only bar and the Your
  access card (a role), and in Upgrade's place on the plan card for
  anyone but an Admin (the next plan), with the person's words editable.
- Roles & access › Requests: an Admin approves or dismisses, anyone else
  withdraws theirs; Settings shows an Admin the waiting count on Roles &
  access.
- recordAccessDenied (lib/chat/access-log.ts): one typed way in for
  every denial (who, the tool's label key and class, surface, the
  reason, brand unless out of scope, chat and run). The server's log
  for now; the Activity log (A4) fills it in without a caller changing.

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

* feat(chat): set Chat's tool policy, Full auto and what Managers take live in Settings

Chat P0 B3, part 1 (CHAT-20 §5, §8b; mockup #g-policy), behind
CHAT_AGENTIC: a Settings › Chat section, listed last, for every role.

- Run modes: Full auto for members and "Don't ask again" (Growth and up,
  locked below with "Needs Growth · you're on …"); Full auto over MCP
  (off in v1) and untrusted content (every WRITE asks) as fixed rules.
- Who decides: the six steps of the approval precedence.
- Tool policy by area: every registry row by its label, never its name,
  its class, what applies, and what it does in Full auto. An Admin picks
  among what the row offers (policyChoices: a read only Never where it
  may be switched off, an EXECUTE only Never, a WRITE up to its maximum,
  so never Always on an always-card row), with what the plan locks
  (policyChoiceLock) disabled, or gives it back its default; Reset to
  defaults.
- What Managers may take live: the four go-live groups.
- Your auto changes: the person's own "Don't ask again" ticks, which
  anyone removes, on a read-only workspace too.

lib/actions/chat-settings.ts reads the facts the precedence decides on
and checks every change again on the server (an Admin, an active plan,
the row's choices, the plan's locks). Every action answers { ok } with a
typed failure and never throws (#1777's pattern). The Activity log page
follows A4 (00402).

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

* fix(chat): answer a failed read on the access pages in its result, never by throwing

As #1777: getChatAccess, listRoleMembers, listAccessRequests and
countPendingAccessRequests answer { ok } with `chat_off` or `failed`
instead of throwing when the database doesn't answer, so a page never
shows React's hidden error message.

- Roles & access says it couldn't load, with Retry; the requests list
  says so on its own, apart from the rest of the page.
- "What Chat can do" is not found with Chat off, and says it couldn't
  load, with Retry, on a failed read.
- The Your access card and the Settings count stay hidden on a failure.

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

* feat(chat): log every change Chat makes, with Undo and no duplicates

Every WRITE Chat runs lands in an Activity log with its mode, how it was
approved and an Undo while its window is open (CHAT-20 §10), and a
double-clicked approval makes one change (§11c). Nothing calls it yet; the
engine (C3) does, behind CHAT_AGENTIC.

- 00402: chat_activity_log, one row per change, Undo or refused call
  (kind change / undo / access.denied): actor, brand, chat, run, step,
  surface, the tool's label key (never its name), class, mode, approval
  (run / ask / click / auto, with auto_via), target, summary (an en.json
  key and its values), Undo data and deadline, status (done / undone /
  undo_conflict), or a denial's reason. A person reads their own rows, an
  Admin the workspace's; undo_json and every write stay with the server.
  chat_idempotency_keys: a key per workspace for 24 hours, with the first
  call's result; server only.
- lib/chat/write.ts runLoggedWrite: runs a change once per approval (the
  run step that asks for it), reads what Undo needs around it, logs it. A
  repeat returns the first result and row; another request on the same
  approval is approval_mismatch; a failure returns failed and frees the key.
- lib/chat/idempotency.ts: claim the key before the change; a second call
  at once waits for the first one's result; stale claims and expired keys
  are taken over.
- lib/chat/undo.ts: an inverse per WRITE row (create_draft archives the
  draft, 30 days; update_opportunity puts back the status and dismiss
  reason, 7 days; dismiss_prompt_suggestion brings it back, 7 days). For
  the actor and Admins, through the same precedence as the tool (brand
  found again with resolveCallBrand), no card; a target changed since is
  a conflict with a link, never overwritten. Never throws: failed.
- lib/chat/activity.ts: logActivity, approvalFor, the summaries, and
  recordActivity({ kind: 'access.denied', ... }) for B2's
  recordAccessDenied.

Tests: the three acceptance criteria, every WRITE row's Undo, conflicts,
expired and repeated Undo, two calls at once on one key, who may undo,
denials, and 00402's grants. RLS checked on the dev database in a
rolled-back transaction.

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

* feat(chat): log every denial and Ask your Admin in the Activity log, with withdraw as its Undo

With the Activity log (A4, 00402) in:

- recordAccessDenied writes the denial's row (recordActivity of
  accessDeniedEvent): the person sees it among their own rows, Admins
  among all. A failed write is logged on the server and never changes
  the answer.
- request_access gets its Undo, as CHAT-20 row 80a has it: withdraw the
  request while it waits (30 days, as long as Requests lists it); one an
  Admin decided since is `changed`. Its summaries: "Asked your Admins:
  “…”" and "Withdrew the request “…”".
- The Full auto log test covers the writes that may run without a card;
  Ask your Admin, a card in every mode, has its own: the Analyst's click
  sends it, it is logged as `ask` with no brand, and Undo withdraws it.

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

* feat(chat): show the Activity log, with filters, Undo and CSV for Admins

Chat P0 B3, part 2 (CHAT-20 §10a; mockup #g-activity), behind
CHAT_AGENTIC: /dashboard/chat/activity, linked from Settings › Chat.

- Every change Chat made, every Undo and every denial
  (chat_activity_log, 00402), newest first, 50 a page with Load more:
  when, who (and the surface), what happened in words
  (chatActivity.summary; a denial's reason under it), its class, how it
  was approved (on its card, a click, or auto by policy Always, Full
  auto or "Don't ask again"), and Undo.
- The person sees their own rows; an Admin sees the workspace's, filters
  by person and exports the filtered rows as CSV (up to 5,000, in words,
  cells escaped by lib/csv). Filters: area, class or the denials, and
  "Auto changes only".
- Undo on a change while its window is open, for its person or an Admin
  (undoChange): Undone, or why not in its words; a change that changed
  since links where to undo it by hand.
- A row goes by its label key and its summary: a tool's name never
  reaches the page, nor does what Undo restores (undo_json).

lib/actions/chat-activity.ts answers { ok } with a typed failure and
never throws (#1777).

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

* test(chat): name why Chat's settings actions stay out of assertWritable

Each one checks the plan itself (asAdmin: ctx.plan.writable) so that a
read-only workspace gets read_only as a result rather than a throw;
removeAutoChoice only takes an auto-approval back. The read-only coverage
test failed without them.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
…1794)

* feat(chat): add Chat's flag, its core tables and the events a run streams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

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

* fix(chat): keep a person's chats when their brand is deleted

A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

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

* fix(chat): mask ids in event text, refuse more tool and money keys, and add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

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

* fix(chat): keep each focus area once and move a chat up Recents on each new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

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

* docs(chat): say when a change to CHAT_AGENTIC applies and where it may be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

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

* feat(chat): list every tool Chat may use in one registry

Chat P0, A2 (CHAT-20 §9): one place that says, for each tool Chat may
call, what it does, who may call it, on which plan and how a call is
approved. The approval flow (A3), the model's tool list (C3), Settings
› Chat and Roles & access (B1, B3) read these rows instead of keeping
their own lists. Nothing calls the registry yet; it sits behind no flag
because it changes nothing on its own.

- lib/chat/registry/define-tool.ts: defineTool and the row fields:
  internal name, class (read / write / execute), min role (TeamRole),
  plan gate (PlanId, plan Feature, or the plan's platforms), default
  and maximum policy, flags (always_card, cost_card, admin may turn a
  read off), cost class, label key, app route, the MCP tool doing the
  same work, its CHAT-20 row and a fixture. defineTool keeps the hard
  rules as rows are defined: a read runs, an execute is always a click,
  and an always_card write never goes past Ask.
- read-tools.ts: 27 READ rows, each calling the MCP data function the
  MCP tool of the same work calls (imported, not changed), so Chat, the
  MCP Server and today's agent read the same numbers.
- write-tools.ts: create_draft, update_opportunity and
  dismiss_prompt_suggestion, calling the server actions the app's own
  buttons call (createContentDraft, updateOpportunityStatus,
  dismissSuggestion), as the signed-in member.
- tools.ts: CHAT_TOOLS, chatTool(name) and registryCatalog(), the rows
  as plain JSON-safe data for the Settings pages. No generated file:
  every reader is in web/ and can call it.
- messages/en.json: chatTools.{key}.name (Settings) and .step (CHAT-03
  step title) per row. The keys don't spell the tool names, since every
  page gets all of en.json and a tool name never reaches a customer.

Tests: every row has its two labels and a fixture its schema takes;
names and labels are unique; routes are pages of the app; each row runs
its own function with the fixture (reads with the member's context,
writes through the app's actions, with the same arguments the pages
pass); an execute is always a click; the catalog is plain data. Against
the MCP Server: every named MCP tool is registered, reads map to reads
and writes to writes, and readOnlyHint agrees wherever a tool states it
(3 tools on main; all once #1732 merges).

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

* feat(chat): keep tool names out of the browser's catalog, and add the mentions reads

- registryCatalog() is now what a browser may get: each row goes by its
  label key (`key`), without its internal name, its MCP tool name or its
  spec row. A tool's name never reaches a customer (CHAT-03 item 22).
  The names stay on the server in CHAT_TOOLS, where the approval checks,
  the run steps' `tool` column and the MCP parity read them, so no
  second, server-side catalog is needed. chatToolByKey() leads a key a
  page sends back (a policy change, say) to its row.
- get_mention, get_mention_competitors and get_mentions_perception: READ
  rows for the Mentions area's reads today's agent (/dashboard/agent)
  has, so Chat answers what it does. Not in CHAT-20 §9 yet; mapped to
  the MCP tools of the same names, with their en.json labels.

Tests: the catalog has no tool name in any value and passes the event
rule chatEvent() applies (clientEventProblems); every key leads back to
its row.

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

* feat(chat): decide each tool call by plan, role, policy and mode

Chat's approval precedence (CHAT-20 §5): before every tool call the
server decides whether the person may run it now, and how: it runs, it
waits on an approval card, it waits on their click, or it is refused
with a reason. Nothing reads it yet; the engine (C3) calls it, behind
CHAT_AGENTIC.

- lib/chat/precedence.ts: decideToolCall and allowedTools, pure. Most
  restrictive first: brand scope; a read-only workspace (402), the demo
  brand and a Never policy refuse; an EXECUTE is at most a click and an
  always_card WRITE at most a card in every mode; then the plan gate,
  the live role, the Admin's policy and switches, the run mode, the
  person's "Don't ask again" and taint. Self-hosted has no plan gates;
  MCP gets no Full auto and no ticks (v1).
- lib/chat/denial.ts: the out-of-permission answer's four parts (what
  was asked, the rule and where it is set, who can by role, what to do
  next), from en.json, naming nothing outside the person's scope.
- lib/chat/plan-facts.ts: the plan's features, limits, trial, Full auto
  and step up, read from config/plans.ts through the organization row.
- lib/chat/precedence-context.ts: reads the live role, the plan, the
  workspace's Chat settings and the person's ticks fresh for every call.
  The demo flag reads false until the demo chain (#1734) merges.
- 00401: chat_settings (tool policy by label key, Full auto for
  non-Admins, "Don't ask again", go-live groups off for Managers;
  members read, the server writes) and chat_auto_choices (a person's
  ticks, theirs to read, add and remove).
- Registry: every EXECUTE row names its go-live group, and saving a
  draft opens to every role (the 2026-10-29 role model: daily work open,
  settings, deleting, prompts and costly work for Admins and Managers).

Tests: a fixture table of cases plus every combination of role, plan,
mode, surface, policy, switches, tick, taint and demo (about 135,000
decisions), one test per §21 criterion it covers.

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

* feat(chat): let analysts dismiss suggestions and run Always tools in Auto

Two decisions of 2026-10-29 for Chat's approval precedence:

- Roles: dismissing a prompt suggestion is open to Admins, Managers and
  Analysts, not Agency partners, as the server (#1763), MCP (#1762) and
  RLS have it. A registry row open to every role may now leave roles out
  (excludeRoles, never an Admin); the catalog carries it, and a denial's
  "who can" names the roles a row allows. Reviewing or dismissing a
  content opportunity stays with Admins and Managers.
- Always: a tool an Admin sets to Always runs without a card in Auto and
  Full auto, on any plan; Ask me first, MCP and untrusted content still
  show the card. CHAT-20 §5 step 5 ("Auto: each WRITE shows a card")
  now holds for tools not set to Always, so Always and "Ask (auto allowed
  in Full auto)" differ. EXECUTE and always_card rows still can't be
  Always.

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

* feat(chat): keep Always behind Full auto's plan lock

An Admin's Always runs a change without a card only where Full auto is
open: on Starter and in the trial it asks as Ask does, with the reason
full_auto_locked, so Always can't get past the plan difference.
policyChoiceLock tells Settings › Chat to show Always and "Ask (auto
allowed in Full auto)" locked there, for the same reason.

Always still doesn't need "Full auto for members": it is the Admin's own
choice for one tool, now said in the code.

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

* fix(chat): find each call's brand, keep unknown surfaces closed and gate MCP by plan

Review of Chat's approval precedence:

- Every registry row says where a call's brand comes from (brandOf): the
  input's brand_id, or the brand of the row an object's id names
  (content_opportunities, prompt_suggestions, prompt_results,
  content_drafts, actions, site_audits). The server finds it in the
  person's workspace (resolveCallBrand checks brands.organization_id, so
  'all' never reaches another workspace's brand), and a brand-bound call
  whose brand isn't found is refused as brand_scope. A run about no
  brand yet still lists the brand-bound rows. The registry test checks
  every row that takes a brand or an id says so.
- A surface other than Chat, or one the code doesn't know, is the closed
  side: its writes always ask. A mode it doesn't know is Ask me first,
  and readPrecedenceContext checks both against CHAT_MODES and
  CHAT_SURFACES.
- MCP's plan gates (CHAT-20 §7, §17): nothing in the trial, reads only on
  Starter, writes and executes from Growth; allowedTools follows.
- decideOrDeny refuses a call without a context (no_access), with its
  denial words. DEFAULT_CHAT_SETTINGS is frozen. A note for the engine:
  an approval or a click decides again before it runs.
- A type test stops compiling once #1734 adds brands.is_demo, so the
  demo flag gets wired then; another checks every lookup table has
  brand_id.
- Tests: Full auto off for members with ticks on, the tick rule against
  role, switch and surface both ways, a detected injection in every
  combination, and rows for an unknown surface and mode.

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

* feat(chat): show roles and access, your own access, your plan and what Chat can do

Chat P0 B1 (CHAT-20 §4a, §4b, §7a, §8), behind CHAT_AGENTIC: the
dashboard's layout reads the flag on the server and hands the browser
only the answer (ChatAgenticProvider).

- Settings › Roles & access (after Team, everyone reads it): the plan
  card, members with their role, brands, what they do through Chat and
  their last sign-in (e-mails for Admins only), what each role can do in
  the app and through Chat (CHAT-20 §4's matrix), and the Admin switches
  that change a role's rights (Managers going live, Full auto) with who
  set them. Admins change another member's role here as in Team; the
  rest of the team's management stays in Team.
- Settings › Account: a Your access card (role, brands, what Chat may do
  as you, the go-live groups an Admin switched off for Managers), linking
  to Roles & access and to "What Chat can do".
- The sidebar's profile row says the person's role.
- "What Chat can do" (/dashboard/chat/capabilities): the registry by
  area (registryCatalog), with how each change is approved, who may make
  it, and the plan a row needs, searchable and filtered by class. Only
  what the registry has is listed: a capability not in it isn't Chat's.
- Your plan (§7a): plan and price, what it includes and locks ("Needs
  Growth · you're on Starter"), AI usage as a percentage, and what the
  next plan adds from config/plans.ts (more platforms, Full auto, MCP
  writes, the AI limit's multiple; Claude tracking and a contract on
  Enterprise; "After your trial" on the trial). Upgrade for Admins only;
  no upsell or lock lines on Enterprise. No AI budget in dollars.

getChatAccess / listRoleMembers read the facts the approval precedence
checks (readPrecedenceContext), so a page and the server agree.
readMemberAuth gives a member's e-mail and last sign-in from one call.

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

* feat(chat): ask your Admin for access, and record every denial

Chat P0 B2 (CHAT-20 §4c, registry row 80a), behind CHAT_AGENTIC.

- chat_access_requests (00403): what was asked, the rule that refused it
  (role, plan, policy, workspace, brand, demo) and its words, the refused
  tool's label key, the chat it came from and any drafted change; pending
  until an Admin approves or dismisses it (the first to act decides) or
  the person withdraws it. The server writes every row; the requester
  reads their own, the workspace's Admins all of its.
- requestAccess: only by the person's click; Admins have no one to ask;
  at most 10 waiting per person, and the same ask (tool key and words,
  case and spacing aside) once a day; a brand or chat that isn't theirs
  is dropped. withdrawAccessRequest, decideAccessRequest (Admins only),
  listAccessRequests (an Admin's: the workspace's; anyone else's: their
  own; waiting first, then 30 days of decided ones) and the count.
- Registry row request_access ("Ask your Admin"): Ask fixed, always a
  card, every role, no brand; it calls requestAccess, as the buttons do.
- Ask your Admin buttons: on Roles & access' read-only bar and the Your
  access card (a role), and in Upgrade's place on the plan card for
  anyone but an Admin (the next plan), with the person's words editable.
- Roles & access › Requests: an Admin approves or dismisses, anyone else
  withdraws theirs; Settings shows an Admin the waiting count on Roles &
  access.
- recordAccessDenied (lib/chat/access-log.ts): one typed way in for
  every denial (who, the tool's label key and class, surface, the
  reason, brand unless out of scope, chat and run). The server's log
  for now; the Activity log (A4) fills it in without a caller changing.

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

* feat(chat): log every change Chat makes, with Undo and no duplicates

Every WRITE Chat runs lands in an Activity log with its mode, how it was
approved and an Undo while its window is open (CHAT-20 §10), and a
double-clicked approval makes one change (§11c). Nothing calls it yet; the
engine (C3) does, behind CHAT_AGENTIC.

- 00402: chat_activity_log, one row per change, Undo or refused call
  (kind change / undo / access.denied): actor, brand, chat, run, step,
  surface, the tool's label key (never its name), class, mode, approval
  (run / ask / click / auto, with auto_via), target, summary (an en.json
  key and its values), Undo data and deadline, status (done / undone /
  undo_conflict), or a denial's reason. A person reads their own rows, an
  Admin the workspace's; undo_json and every write stay with the server.
  chat_idempotency_keys: a key per workspace for 24 hours, with the first
  call's result; server only.
- lib/chat/write.ts runLoggedWrite: runs a change once per approval (the
  run step that asks for it), reads what Undo needs around it, logs it. A
  repeat returns the first result and row; another request on the same
  approval is approval_mismatch; a failure returns failed and frees the key.
- lib/chat/idempotency.ts: claim the key before the change; a second call
  at once waits for the first one's result; stale claims and expired keys
  are taken over.
- lib/chat/undo.ts: an inverse per WRITE row (create_draft archives the
  draft, 30 days; update_opportunity puts back the status and dismiss
  reason, 7 days; dismiss_prompt_suggestion brings it back, 7 days). For
  the actor and Admins, through the same precedence as the tool (brand
  found again with resolveCallBrand), no card; a target changed since is
  a conflict with a link, never overwritten. Never throws: failed.
- lib/chat/activity.ts: logActivity, approvalFor, the summaries, and
  recordActivity({ kind: 'access.denied', ... }) for B2's
  recordAccessDenied.

Tests: the three acceptance criteria, every WRITE row's Undo, conflicts,
expired and repeated Undo, two calls at once on one key, who may undo,
denials, and 00402's grants. RLS checked on the dev database in a
rolled-back transaction.

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

* feat(chat): add the run cards and the runs tray

Chat P0, D2, from the approved Chat v2 mockups (#s-plan, #s-need,
#s-done, #s-denied, #s-failed and the header's runs pill), on D1's
agent pieces:

- Plan card: the steps with how each runs (Auto, Asks you, Auto ·
  logged, Needs your click), what the run uses and connects to, time,
  AI usage and outputs; Edit plan moves or removes steps, Start runs
  the edited plan. A role that can't start runs gets Ask your Admin.
- Approval card: a WRITE's change as before and after, why, sources,
  Skip · Edit · Approve and Save & approve; "Don't ask again" only when
  the precedence allows it (canDontAskAgain). An EXECUTE is the one dark
  "Needs your click" pill and a button naming the effect, off with its
  reason until it can be made. Pending, saving, approved, skipped and
  failed states.
- Result card: "Generated …" and "Data as of …" in absolute time with
  the GMT offset, the steps folded under "Worked for …", counts, files
  whose Open goes only to a path in the app (ChatHref), and the click
  card that waits above it.
- Out-of-permission card: what was asked, why not and where it is set,
  who can by role, and what next; Ask your Admin goes through
  onAskAdmin (B2 wires access.request), then says Sent.
- Failed run: the agent in red, where it stopped and why, and Retry
  from the failed step or the whole run.
- Run steps (CHAT-03): "Working on it" with the step count and clock,
  "Worked for 1m 12s · 7 steps · 4 sources" once done, a one-step run as
  that step's line; each new step said to screen readers (aria-live).
- Every approve, start, retry and request goes through the read-only
  gate (useUpgradeGate().guard). Motion stops with reduced motion.
- Runs tray: the runs pill with the amber needs-you count and the
  "Your runs" list (Review, progress, Open), read again every few
  seconds, not while the tab is hidden. GET /api/chat/runs/tray reads
  the person's own Chat runs (steps by CHAT_RUN_STEP_SELECT) and the
  brand's Content Agent runs, newest first; 404 while CHAT_AGENTIC is
  off; failures come back as { ok: false, failure, error }.
- The preview page (/dashboard/chat/preview) shows every card in every
  state, and the tray, also live.

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

* feat(chat): draw each Chat model step from the workspace's one AI budget

CHAT-04 §C items 11–14 and CHAT-16 items 22, 26 and 28–30 (DECISIONS P),
behind CHAT_AGENTIC. With the flag on, Chat runs on Ansvisor's key and
each model step draws on the monthly AI budget that Improve, the Content
Editor and the task writer already share, at the model's real cost (1x;
the margin stays with purchased AI credits).

- 00405: prompt_improve_usage.feature takes chat, agent, schedule and
  image; own_key, chat_run_id and chat_run_step_id (on delete set null).
  reserve_chat_ai_usage holds a step's worst case under the same
  per-organization lock as reserve_ai_usage, and only while spend, holds
  in flight and that worst case stay within the budget, so parallel runs
  can't pass it. Own-key rows are written but left out of every sum
  (reserve_ai_usage, ai_usage_by_feature, plan-guard's reads).
  organizations.legacy_key_grandfathered marks Starter (and Growth trial)
  workspaces that had a key, guarded as a server column.
- Server: lib/chat-budget.js and /api/internal/chat/budget/{reserve,
  charge,release} (CRON_SECRET, Zod). The server prices every step; the
  web never sends a cost, and no answer carries dollars.
- Web: lib/chat/key.ts picks the key (own key on Growth+, a kept Starter
  key, else Ansvisor's ANTHROPIC_API_KEY); lib/chat/budget.ts reserves,
  then charges, releases or keeps (a Stop's call is still billed). It
  never throws: a refusal comes back typed with its words (chatBudget),
  calls have 5 s limits, a reserve that gets no answer refuses the step,
  and charge/release retry once after a 502.
- Billing: a Chat row in percent, and the "Agent Chat runs on your own AI
  key" line changes while Chat is on. A key saved while Chat is off marks
  the workspace to keep it.

With the flag off nothing changes: Agent Chat keeps the workspace's own
key only, and nothing is held or written.

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

* fix(server): stop counting Chat's budget calls against the API's per-IP limit

Every Chat model step makes two calls to /api/internal/chat/budget, and on
Vercel the web's calls come from a few shared addresses, so the API
limiter's 250-a-quarter-hour IP bucket would stop Chat for every
workspace at once. apiLimiter now skips a request only when it is on that
path and carries the internal secret (CRON_SECRET, compared in constant
time); the same path without it, or the secret on any other path, is
counted as before.

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

* fix(chat): let Ask your Admin be withdrawn from the Activity log, and keep it out of the Full auto checks

The activity log with Undo (#1786) and Ask your Admin (#1781) meet here for
the first time: every WRITE row needs an Undo, and request_access had none.
Its Undo withdraws the request while it is still pending (CHAT-20 row 80a,
"withdraw while pending"); one an Admin already decided is left as it is.
The Full auto check covers the writes that may run without a card, which an
always_card row never does.

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

* feat(chat): run each Chat turn as live steps that pause for approval

Chat's engine (C3), behind CHAT_AGENTIC. A new message starts a run that
streams its events (CHAT-00) and works in the request's background, so a
browser that leaves doesn't stop it.

- Auto: Claude Haiku 5.5 reads (it picks the reads and ends with a native
  structured "ready"), Claude Sonnet 5.5 writes the answer and makes the
  changes. No temperature, top_p or top_k, tools never forced, max_tokens
  always sent (Claude 5.5). The key comes from key.ts; another provider's
  own key runs one model in one phase.
- Every model step is held on the AI budget first (reserve, then charge or
  release; keep on Stop). A refused hold starts nothing: the run pauses at
  the cap, or ends in words.
- Every tool call is decided again on facts read for it (decideOrDeny). A
  read runs; a change runs by itself only where the precedence says so
  (runLoggedWrite); otherwise its card (`confirm.required`) stops the run,
  and an EXECUTE only ever runs on the click. Approve decides once more and
  is bound to the card's arguments (approval_mismatch shows it again). A
  refusal shows the out-of-permission answer and is recorded in the
  Activity log; tools hidden from the model can still be explained.
  request_access passes a read-only workspace and the demo brand.
- Steps go to the browser as toClientStep rows and events through
  chatEvent: no tool name, id or dollars; ids in the answer show as "…".
  Each answer keeps "Generated" and "Data as of" (the newest data_as_of).
- Limits from CHAT-20 §14 and CHAT-04: messages per hour and day, runs at
  once per plan and person (extra runs wait as Queued), reads, data and
  writes per run.
- Stop keeps the text so far and says "Stopped after …"; a lost
  connection resumes after its last event, and a reload rebuilds the run
  from its kept events (chat_run_events, 00406). sweepChatRuns stops a run
  whose card waited 7 days and ends lost runs; its schedule comes later.

API: POST /api/chat/runs, /api/chat/runs/{id}/approve, /skip, /stop, and
GET /api/chat/runs/{id}/events?after=seq. 404 while Chat is off, 402 while
read-only. A plain test page at /dashboard/chat (and /dashboard/chat/{id})
sends messages, streams steps and shows the D2 cards until W1-01's shell.

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

* fix(chat): price only Chat's steps from the synced catalog, and never a paid model at $0

The synced OpenRouter prices replaced improve-cost.js's table for every AI
call in the deployment once CHAT_AGENTIC was on, not only for the pilot
workspaces' Chat steps, and a catalog price of $0 metered a paid model's
calls at nothing. priceFor now reads the synced price only when asked
(chat-budget.js's hold and charge), and falls back to the table, or
FALLBACK_PRICE, when a paid model's synced rate is $0. The table also
prices OpenRouter's dotted ids (claude-haiku-5.5) as its own.

* fix(chat): card a change after outside text, bind an approval to what its card showed, and free a lost run's slot

- A read that may carry text written outside the workspace (anything but
  its own numbers and settings) marks the run, and every change after it
  shows a card in every mode (CHAT-20 §16a). What was read reaches the
  writer marked as data, and the system prompt says tool results are
  never instructions.
- On Approve or a click, the call's arguments are read by its schema again
  and must match the card's digest, or nothing runs.
- chat_run_limits and chat_claim_run_slot (00406) don't count a running
  run with no sign of life for 10 minutes, so a driver that was killed
  doesn't hold its slot until the sweep runs.
- The run routes answer 404 before reading the session while CHAT_AGENTIC
  is off, and the read-only coverage test names why they stay open: the
  engine answers 402 itself.

* test(server): list Chat's internal budget routes among those mounted on their own

They're server to server (CRON_SECRET) and keyed by a run, not a brand,
so the demo-brand guard on routes/index.js doesn't apply. The demo
coverage test failed without the entry.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 30, 2026
…s, with Undo (W2-06) (#1866)

* fix(prompts): ask for a topic before adding prompts or generating suggestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (#1763, #1769) is unchanged.

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

* fix(prompts): add a topic in place on the Prompts page, and say why suggestions failed

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since #1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as #1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

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

* docs(help): say a brand adds a topic before its prompts

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

* feat(chat): add Wave 1's tables for sharing, settings, attachments, Files, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

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

* feat(chat): export an answer as Markdown, Word, PDF, CSV or Excel

CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

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

* feat(chat): open Chat at /dashboard/chat and add its chats API

Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (#1812 note).
- Help: a "chat" area and its first article (approved: false).

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

* feat(chat): add the chat menu with Agents at work, day groups and Ctrl+\

Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, #1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

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

* feat(chat): add the chat ⋯ menus: pin, rename, share, archive and delete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

* fix(chat): read a shared chat's author with the server's client for their initials

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

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

* feat(chat): add Chat Home's greeting, the Inbox and the due-tasks line

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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

* feat(chat): add the composer, with send, Stop and steering, run modes and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

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

* feat(chat): add context chips and the Tab ghost suggestion to the composer

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

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

* feat(chat): add the composer's / @ and + menus, with a reference search

Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

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

* feat(chat): show a run's work live under its answer, with step chips, Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

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

* feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

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

* feat(chat): wire the composer and the live answer into Chat's pages

Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

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

* feat(chat): show the AI usage under Chat's composer, say 80% once, and pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf36).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

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

* feat(chat): copy Agent Chat's conversations into Chat on the first visit

On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

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

* feat(chat): add Search chats, the Ctrl K palette and the All chats page

Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

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

* feat(chat): add Chat Settings › General, Back to Chat and the app rail beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

* feat(chat): add Chat's side panel to every app page with Ask Chat and Ctrl J

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

* test(chat): name why your own chats' routes stay open on a read-only workspace

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

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

* test(chat): name why saving your own Chat menu state stays open on a read-only workspace

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

* test(chat): name why editing your own chat stays open on a read-only workspace

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

* test(chat): name why saving your own Chat settings and rail stays open on a read-only workspace

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

* fix(chat): keep the 80% usage line on the person, once per period on every device

The line above Chat's composer at 80% of the AI usage was kept closed per
browser. It now shows once per person per usage period (CHAT-04 item 16):
the first time it shows, its period goes to chat_user_prefs.usage_notice_period
(00408) through saveUsageNoticePeriod, and the Chat pages read it with the
composer's setup; × still closes it on the page.

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

* feat(chat): show the page's context as chips in the side panel, with Ask about this

The side panel's box starts with chips for what the page shows: its
name (the menu's when the page says nothing), the brand, the date range
and filters (CHAT-01 item 20). They follow the page while the panel is
open; × keeps one off until New chat. Pages tell the panel through
useChatPageContext, which reads a setter-only context so a page never
renders again for the panel. The empty panel offers up to three of the
page's questions, which fill the box unsent (item 21), and Ask about this
opens the panel with a chart or table attached as an @ chip (item 22).
The chips and @ objects go with the message: the engine keeps them on
chat_messages.context_json and gives them to the models as a data block,
the run's default scope (CHAT-04 item 8). Mentions & Sentiment is the
first page with its dates, filters, questions and two Ask about this
icons.

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

* feat(chat): give Brand Visibility, Citations, Prompts, Action Center, Traffic and Content their page context

Each page now tells Chat's side panel what it shows (W1-08's
useChatPageContext): its name, date range and filters as chips, and up to
three questions, one of them from data the page already loaded where it
has some (the platform whose visibility or visits moved most, the source
cited most, a tracked prompt the brand doesn't show up for, the top
action, a high-impact opportunity), without a model call. Ask about this
is on Brand Visibility's platform table and leaderboard, Citations' Top
Sources, Traffic's two tables, each tracked prompt and each Action Center
action; on a row it opens the panel, not the row.

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

* feat(chat): add the side panel's ⋯ menu, Open as full page and Back to the page

Once the panel has a chat, its ⋯ (CHAT-23 panel.more) offers Open as full
page, Open in new window, and for the author Pin, Rename (in the panel's
title), Share with team, Archive and Delete, the chat menus' own actions.
ChatActionsProvider tells a page outside the shell of a chat's new row
and of one archived or deleted, which empties the panel. Open as full
page goes to the chat on Chat's page with ?from= the page and its query;
the full page then shows ↙ Back to {page} (CHAT-22), only for a dashboard
page outside Chat. Back on a page, a panel that was away reads its chat
again, so it shows what happened on the full page.

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

* fix(chat): read the full page's search params at the top of the shell

Calling useSearchParams inside an expression kept the React Compiler from
preserving the shell's memoized callbacks (lint: preserve-manual-memoization).

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

* feat(chat): name the app page a side panel chat started on

A chat the side panel starts now keeps origin 'panel' and the page's path
in origin_page (CHAT-01 data notes); Chat's own page keeps 'page' and
/dashboard/chat. The engine takes origin and originPage with the first
message; a page it can't name is left out and the message still goes.
The path check is shared with POST /api/chat/conversations
(lib/chat/origin.ts).

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

* feat(chat): copy, download or save an answer to Files, and export a chat

Every finished answer gets an icon bar (CHAT-06 items 30–37): Copy (rich
text), Download as Markdown, Word or PDF, and CSV or Excel when it has a
table, rendered on the server from the stored answer with its time line
(GET /api/chat/runs/{id}/export, W1-24's writers), and Save to Files,
once per answer, then "In Files" (POST /api/chat/runs/{id}/file). Filing
goes through fileChatOutput, which run deliverables will use as they are
made: a row in chat_files and its content in chat-files, counted toward
storage, refused once a workspace is full. Storage per plan comes from
the spec: Starter 5 GB, Growth 25 GB, Enterprise 99 GB or its contract
(plan_overrides.maxStorageGb), 1 GB in the free trial, plus active
storage packs; self-host has no cap. Export chat in a chat's ⋯ menu now
downloads the whole chat as Markdown, Word or PDF. The PDF routes carry
public/fonts and keep @react-pdf/renderer outside the server bundle for
Vercel. The time line's words move to lib/chat/stamp for the server.

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

* fix(chat): keep a long answer's PDF from failing past ten pages

With the line height set on the page, react-pdf's page number threw
"unsupported number" once the PDF passed ten pages, so any long answer
failed to export. The line height now sits on the body text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): show what a run made as output cards and open answers in the Content Editor

- A write that makes something (create_draft's page) files it in Files as
  it is made and shows it under the answer as an output card: its type,
  title, "In Files" / "Used in Content draft" or "Not saved to Files ·
  Storage is full", Copy, Download in the formats it offers and Open in
  Content Editor (CHAT-06 items 1-6, 9, 29).
- Open in Content Editor on an answer's bar makes a Content draft of the
  answer in the chat's brand (else the brand open) and opens it.
- Files' pages download as HTML, Markdown, Word and PDF on the server: the
  Content Editor's writers run with a jsdom window (lib/content/server-dom).
- A reopened chat shows its output cards and filed answers again.

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

* fix(chat): keep the focus in the composer when a chip is removed

The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): add the Files page with filters, downloads, Download selected and the storage meter

- /dashboard/chat/files lists the workspace's files newest first, 50 at a
  time with Show more: name and formats ("Used in Content draft"), Made by
  (You, a teammate, Agent, Scheduled), From chat (only chats the person can
  open), and the generated time with "Data as of" (CHAT-06 items 12, 16-17).
- Chips All (with the workspace's count), Drafts, Reports, Code, Tables,
  Images, From me, From agents, and "Filter by name..." over the search
  column; "No files match." with Clear filters.
- Each row has Copy (Markdown), Open (its Content draft) and Download in
  the formats it offers. Picked rows download as one .zip in their main
  formats, up to 50 files and 100 MB (items 18-19).
- The storage meter ("Storage 2.1 of 25 GB", amber from 80%) and a line
  once storage is full, with no Get more until the plan rules are set
  (items 26-29).
- GET /api/chat/files, GET /api/chat/files/{id}, POST /api/chat/files/zip
  (reads only). Files sits under Settings in the chat menu, in the Ctrl K
  palette and in the breadcrumb.
- Help: help/chat/files.md (new).

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

* fix(chat): keep Agents at work to the person's own chats, and read the clock with each list read

A teammate's shared chat that waits on its author's OK no longer shows under
Agents at work or in Home's count. A chat that waits on an OK or is paused no
longer keeps the list on the 5 s pace. A menu left open past midnight now
moves Today's chats to Yesterday on the next list read.

* fix(chat): show a teammate's initials on a shared chat

A person reads only their own profile, so the author's name came back
empty on every teammate's shared chat. Read it on the server, within the
workspace; only the initials leave.

* fix(chat): keep a teammate's shared chat out of the Inbox and Home's count

A shared chat that waits for approval waits on its author, who alone can
answer it. The Inbox, its counts in the menu and the strip, and Home's
"things need you" now count the person's own chats only.

* fix(chat): read a * in the @ search as a space, not a wildcard

PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* style(chat): format the read-only open routes list so the web format check passes

* fix(chat): style answers as the app's other AI answers, take hand-made brand ids, and keep Files' draft line whole

From the W1-25…27 preview:
- A Chat answer's Markdown gets the prose styles the Mentions drawer and
  the response detail use (prose prose-sm dark:prose-invert max-w-none):
  headings, lists and table cells, in both themes.
- Starting a chat with a brand (createInput) and Chat Home's due-actions
  line take the demo brand's id with z.guid(): it is made by hand, not an
  RFC 4122 uuid (as #1849 did for starting a run).
- On Files, "Used in Content draft" has its own line under the formats,
  so a 1024px table no longer cuts it off.

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

* test(chat): check who may do what through the engine, role by class by mode (W1-22)

CHAT-05 test set 27–30 and CHAT-20 §4c, §5 end to end, with a scripted
model and the in-memory database:
- Each role is offered only the changes its role allows, and the
  explainer when something is left out.
- Every role reads in every mode with no card.
- A change waits on its card in Ask me first and Auto. Full auto runs it
  for an Admin, and for a Manager only while members may.
- Full auto stays on Growth and up, paid: Starter and the trial get the
  card, and Enterprise's trial runs.
- An Analyst and an Agency partner get the four-part refusal in every
  mode. Nothing changes, and each refusal is logged with its rule.
- An EXECUTE never runs without the click; a Manager the Admin turned
  publishing off for is refused by policy.
- A role lowered while the card waits refuses the approval.

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

* fix(chat): don't offer Admins the request to the Admins

Admins have no one to ask (CHAT-20 access table: "not needed"): the model
was offered request_access for them, so it could put up a card the server
then turned away. The engine now neither offers it to an Admin nor lists it
among what they can't do. The row keeps every role: defineTool never
leaves an Admin out of a row, by design.

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

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

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

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

* fix(chat): clean the pages Chat files, number output cards by their files, copy as Safari allows

From the pre-push review of W1-25…27:
- create_draft's page goes to Files as the draft keeps it, through
  sanitizeDraftHtml, and Files' HTML download cleans it again: a page Chat
  read can't slip a script or an event handler into a download (CHAT-06:
  no script in exported HTML).
- An output card's file is its place among the run's filed outputs, as
  the server counts them. A card that wasn't filed (storage full, failed)
  no longer shifts the next card onto another page's file.
- Copy on an output card writes a clipboard item within the click, its
  text to come (Safari refuses a write after an await), and says when it
  can't.
- A reopened chat's output cards mask ids in their titles, as the live
  events do.

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

* fix(chat): stream Download selected, copy Files rows as Safari allows, and say what a full workspace keeps

From the pre-push review of W1-25…27:
- Download selected streams the .zip as it is made (fflate's Zip): one
  file read, written and compressed at a time as the reader asks for
  more, so neither the files nor the .zip are held whole, and a .zip past
  a function's body cap still goes out. The limits stay: 50 files, 100 MB
  stored, checked before anything is read.
- Copy on a Files row writes a clipboard item within the click, its text
  to come (Safari refuses a write after an await), and says when it can't.
- Help: with storage full, an output's card can't copy or download it (it
  has no file); the answer above it still can.

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

* fix(chat): keep Data used to "Read …" steps, and plain links in the answer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): send an attachment with its type, and call it ready only when its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): keep a copied Agent Chat thread in its order

Agent Chat wrote a conversation's whole thread again on every turn in one
insert, so its messages share one created_at and their ids don't follow
the order. The copy read them by created_at then id, which shuffled them,
and Chat reads a chat by created_at alone. Read each conversation the way
Agent Chat's own page did (by created_at, no tiebreak) and give the copies
a strictly rising created_at, a millisecond apart where they tied.

Also cut a long title or message without splitting an emoji in half.

* fix(chat): open Full auto in the composer only where the server runs it, and steer only after Stop is taken

The composer's Full auto now follows the same facts the approval check uses:
the plan, and for anyone but an Admin the Admin's Full auto for members
switch. When the switch closes it, the mode says Off by Admin rather than
Needs Growth. Steering sends the new message only once the Stop is taken;
otherwise the text stays in the box.

* fix(chat): find a domain, a number or an email address in Search chats

Each word goes to Postgres quoted, so it splits it the way it split the
text: "nike.com", "4.5" or an address is one token there and is now
found whole, and Postgres lowercases it itself.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): tie a step's hold to its chat's agent run and keep paused runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

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

* test(chat): give the test's EXECUTE row its words, assert approvals before driving, and cover an Admin's request

From the pre-push review of W1-22:
- publish_page, the test's own EXECUTE row, gets its words through a mock
  of the messages (the product has no such tool yet), so no
  MISSING_MESSAGE trace prints. The publishing refusal's "asked" is now
  checked.
- Approvals are asserted before the run is driven on, so a refused one
  fails the test instead of passing quietly. The approve helper returns
  a refusal for its callers to check.
- An Admin's call to request_access, which they aren't offered, is turned
  away: no card, no request. The row's comment says how Admins are kept
  out.

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

* feat(chat): pause a run on a question card and go on with the answer

The write phase can call ask_question: 2-4 options, exactly one
Recommended. The run waits on an `ask` step and its chat_asks row, with no
model call. POST /api/chat/runs/{id}/answer keeps the answer once (409 when
already answered, 400 when it doesn't fit, 402 while read-only) and the run
goes on.

- Skip goes on with the Recommended option.
- Stop keeps open questions as skipped.
- A run asks at most 4.
- Questions asked together show "1 of 2", then "2 of 2".
- A message from the composer answers the question, and the rest of its
  batch.

QuestionCard (number keys, Enter = Next, Other..., multi, read-only gate)
and its folded line; the composer's ghost shows the Recommended option.
Help and the preview page show it.

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

* fix(chat): say when a question card takes several answers

A question with several picks looked like a one-pick question. Its footer
now says "Pick one or more · Press 1–N to pick", in the mockup's words,
and each row has a check box that ticks when picked. Help says the same.

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

* style(chat): format the read-only open actions list so the web format check passes

* wip(chat): next moves (W2-02, in progress)

* fix(chat): keep Chat on at the AI limit on the workspace's own key, and read the usage again after each run

The composer turned off whenever the allowance was used up, but Chat on
the workspace's own key never draws on it (the server's hold writes those
steps unchecked), so a workspace with its own key could not send at all.
The page now reads whether Chat runs on the workspace's own key, as the
server picks it, and keeps the composer on then.

The meter, the 80% line and the pause also read the usage again once a
run stops working, so they follow the chat's own spending without a
page change. One read per run, no timer.

* fix(chat): name the run's own brand in the page context, and keep its block closed

The brand chip a message carries is now the run's own brand (the chat's,
checked against the workspace), not the posted label and id; it goes when
the run has no brand. The page context reaches the models with < and > as
JSON escapes, so a label can't end the block, and a reference's scope is
capped at 8 entries.

* fix(chat): name only a known platform in Traffic's question, and the first Top action in Action Center's

AI Referral Traffic's suggestion now reads the platform the page can name,
as the summary line does, and none over all time, where there is no
previous period and every platform would read as a rise. Action Center's
"How do I finish" names the first of the Top actions as the card ranks
them; the list arrives unordered.

* fix(chat): set up the side panel's composer as Chat's pages set theirs up

The panel's setup read Full auto from the plan alone and left out whether
Chat runs on the workspace's own key. So a member whose Admin turned "Full
auto for members" off could pick a mode that then asks anyway, and the
panel paused at the AI limit on a workspace's own key. The layout now reads
the switch and the key (only with the new Chat on) and builds the setup with
the same composerSetupOf Chat's pages use, moved to lib/chat/composer-setup;
the panel passes fullAutoOffByAdmin and onOwnKey on to the composer.

* perf(chat): load the side panel's code the first time it opens

The layout imported the panel directly, so its thread, composer and run
views came with every app page, Chat on or off. The layout now puts a
small slot there that loads the panel the first time it opens and keeps
it after that.

* fix(chat): keep Back to the page off paths with dot segments

panelReturnOf accepted /dashboard/../… and its %2e form, which resolve
outside the dashboard or into Chat. Refuse a . or .. segment.

* fix(chat): stop a run that waits on a question, and take its answer as the person's

From the review of the question card:

- Stop while a question waits: Stop sits beside Send and Esc stops the run.
  The question is kept skipped and its step reads "Question skipped".
- The answer reaches the model as the person's own (from: 'the person'),
  and the system prompt says to follow it like their message, not as data.
- A change called in the same step as a question doesn't run (not_run).
  The model calls it again with the answer.
- An answer kept while the run stopped meanwhile is let go again (no new
  migration), so the question doesn't stay half answered.
- The question card:
  - Enter on Skip, Add or an option is that button's own.
  - Text in Other... counts without Add, up to 500 characters.
- Answering from the composer:
  - It sends text only: no files, @ data or chips.
  - The box takes up to 500 characters; a 400 says why.
  - The composer is free at once (the answer's stream isn't awaited).
- "1 of N" counts only the questions the run will ask.
- A typed option label matches regardless of case, spacing, accents or
  Turkish i.
- Questions are capped at 200 characters, the step label's length.
- Help: the card section, and "Answer in the box".

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

* feat(chat): suggest next moves under a finished answer, the first as the composer's ghost

This commit and the wip commit before it make up CHAT-07 §C.

- With its final answer, in the same model step, the model calls
  suggest_next_moves. A step with only that call ends the run without
  another model step.
- The moves are picked for the person's role and plan as they are now:
  - an Analyst, an Agency partner or a read-only workspace gets read moves
    only;
  - one move per kind and per prompt, three at most, ids masked.
- They are kept in chat_next_moves (00417) and sent as next_moves before
  run.finished. None after an error, a pause at the cap, a Stop, or while a
  question or a change waits.
- The page shows them as "Next moves" cards under the latest answer only
  (mockup #s-done). A click sends the prompt as the next message.
- The first move shows as the composer's ghost when it continues this run
  (ghost_ok). A teammate's shared chat shows none.
- loadChatThread brings them back after a reload.
- Help ("Next moves") and the preview page show them.

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

* wip(chat): prompt, topic and competitor writes (W2-06, in progress)

* feat(chat): add the agents API: create, version, triggers, lifecycle and Run now (W2-13)

Chat's agents (CHAT-21, CHAT-27 §E) on the server, behind CHAT_AGENTIC:

- /api/chat/agents: list (Mine, Workspace, Paused, Archived, search) and
  create a draft; /{id}: detail, change (a new immutable version whenever
  what the agent does changes; name, visibility, caps and triggers change
  on the agent), delete once archived; /{id}/activate, pause, resume,
  archive, restore, duplicate; /{id}/run (Run now); /{id}/runs.
- Roles as §K: Admins and Managers make and run agents, a Manager changes
  only their own, private agents for their owner and Admins, Analysts and
  Agency partners read; refusals carry the out-of-permission answer
  (CHAT-20 §4c) and an access.denied row. Workspace agents kept to Admins
  and Full auto off follow Settings › Chat.
- Plan gates: Full auto Growth+, engines the plan tracks, active agents
  and agent runs at once per plan (§M, approved as written).
- Triggers: 0–5 schedule, Signal, KPI or watch-rule triggers, validated;
  a schedule's next fire from a dependency-free RRULE subset in its zone.
- Run now queues a run per brand (one per click a minute, at most 3
  waiting), acting as the person; a slot is tried with
  chat_start_next_agent_run only once a driver exists (W2-16), so runs
  wait queued until then.
- AI use as shares only: each agent's share comes from the server's new
  GET /api/internal/chat/budget/agent-shares (chat_agent_usage_shares
  against the budget the server keeps), cached 5 minutes; no dollars reach
  the browser.
- Every write is gated by writeRefusal; every change and Run now goes to
  the Activity log with agent_id and agent_run_id.

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

* fix(chat): open an answer in the Content Editor as the answer shows it

An image in the answer goes into the draft as its alt text, and raw HTML
as its text, as the answer itself shows them; links stay, cleaned by the
draft's own sanitizing.

* fix(chat): show on a next move the text it sends, and keep only the last step's moves

From the review of next moves:

- A card shows the very prompt a click sends, never a label that could say
  something else. A page Chat read could otherwise dress a write up as "See
  the full report".
- Moves belong to the step they came with: they are cleared before each
  writing step, so a question, an answer and a last step without moves
  shows none.
- The tool takes the call whole (up to 6 moves, loose fields) and checks
  each move on its own (validMoves). A move too long or of an unknown kind
  loses only itself.
- A move whose label or prompt names a tool, or reads like one
  (snake_case), is dropped before it is kept.
- loadChatThread logs a failed read of the moves and opens the chat
  without them. A teammate's shared chat doesn't read them.
- In the side panel the cards stand one under another; two or three side by
  side on a page.
- Comment: ghost_ok is the model's word, not checked.
- Tests: moves that can't be kept, an error and a Stop after a step with
  moves.

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

* fix(chat): let a Stop after Approve win, and finish the who-may-do-what matrix

A Stop that comes after Approve, before the approved change runs, now
stops the run: in the same process the change no longer runs, and from
another process the card is closed with run.stopped instead of the run
staying stopped with its step still waiting.

The matrix's test-only EXECUTE row is Admin and Manager work, as in
precedence.test, and the matrix now covers every change row, Analysts'
and Agency partners' own changes in each mode, their refused go-live,
a teammate answering someone else's card, a click refused after the
Admin turned publishing off, and the demo brand for every role.

* fix(chat): show Admins every agent, keep triggers across saves, and add Take over (W2-13)

Review fixes on the agents API:

- Workspace tab: an Admin sees every agent in use, others' private ones
  included (CHAT-21 §K, edge case 1); the counts follow.
- Triggers are matched with their keys sorted (canonicalJson): jsonb's
  key order no longer makes a KPI, Signal or one-off trigger look new, so
  its last fire and cooldown stay.
- Only a new or changed trigger is held to the clock: a one-off that
  already fired can come back with a save.
- Run now claims an idempotency key (agent, brand, person, minute), so two
  clicks at once queue one run; a run counted past the 3 waiting after its
  insert goes again and joins the last.
- POST /api/chat/agents/{id}/take-over: an Admin becomes the owner; an
  agent that is on, or paused because of its owner, passes the activation
  checks under them first and comes back on; logged.
- Duplicate is held to create's checks (mode, engines, brands, topics,
  people).
- The internal budget endpoints compare CRON_SECRET in constant time
  (webhookSecretsMatch).
- Tests for another workspace's or a teammate's private agent (404).

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

* fix(chat): keep a long answer's or chat's PDF within the route's time

react-pdf's layout time grows with the square of the length: 2,000 table
rows took about 60 s and 6,000 rows about 4 minutes, and Export chat joins
every answer of a chat. A PDF now lays out 1,000 rows and blocks at most
and ends with a line saying so (Markdown and Word keep all of it), and
both export routes get maxDuration 300.

Also matches the downloaded body in the answer bar's test by its size:
fetch's Blob is Node's, not the test page's.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): track prompts, topics and competitors from Chat, with Undo

This commit and the wip commit before it make up W2-06 (CHAT-20 §9 rows 20–32).

New WRITE rows, one registry file per area:
- add_prompts: prompts in one of the brand's topics, topic first.
- pause_prompts: the spec's "archive"; the app pauses, history kept.
- add_topic, rename_topic.
- add_competitors, remove_competitor (always a card).

How they run:
- Admins and Managers, as the app (00382, #1762). Others get the
  structured refusal.
- Each calls a thin server action over the app's own:
  - addTopicPrompts runs through importPrompts: the plan's prompt
    locations, duplicates skipped, first run started.
  - pauseBrandPrompts, addBrandTopic, addCompetitors and
    removeBrandCompetitor each check the brand and skip natural-key
    duplicates.
- Every one checks the read-only workspace first.

Undo for each (undo-setup.ts), 7 days, 30 for paused prompts. Anything
changed since is left alone (undo_conflict). Resuming paused prompts checks
the plan's room again.

Registry and engine:
- A row may name its batch: the run's caps count items (50 prompts, 5
  competitors), and more than 5 prompts paused at once always shows a card
  (overBatch).
- A row may name its card's target from the data: the topic, the prompts,
  the competitor.
- A refusal the person can act on (quota_exceeded, duplicate, not_found,
  invalid) shows the action's words on the step and gives the model its
  §11a code.
- An action's { ok: false } refusal is no longer logged as a change.

Help: chat.md "Change what you track".

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

* fix(chat): let a Stop right after an answer win, and keep a question the run never went on with as skipped

The answer branch of resumePending now checks for a Stop before taking the
answer up, as an approved change does. A stopped run's open question is kept
as skipped even when its answer was kept just before the Stop, and an answer
whose run ended before it was taken back is kept as skipped rather than
cleared. Tests: Stop after an answer in this process and in another, the
run-ended-meanwhile case, and a teammate's answer, skip and stop on a shared
chat.

* chore: no changes; push again so GitHub picks up the merged fixes

* fix(chat): start a run from a tainted run's next move tainted, and drop moves that carry a link

* fix(chat): hold a change to someone else's agent to its owner's mode, and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since its triggered runs act as the owner (as Resume
does). A Run now whose insert lan…
gkhngyk added a commit that referenced this pull request Oct 31, 2026
…d start audits (W2-07) (#1868)

* fix(prompts): ask for a topic before adding prompts or generating suggestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (#1763, #1769) is unchanged.

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

* fix(prompts): add a topic in place on the Prompts page, and say why suggestions failed

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since #1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as #1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

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

* docs(help): say a brand adds a topic before its prompts

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

* feat(chat): add Wave 1's tables for sharing, settings, attachments, Files, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

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

* feat(chat): export an answer as Markdown, Word, PDF, CSV or Excel

CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

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

* feat(chat): open Chat at /dashboard/chat and add its chats API

Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (#1812 note).
- Help: a "chat" area and its first article (approved: false).

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

* feat(chat): add the chat menu with Agents at work, day groups and Ctrl+\

Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, #1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

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

* feat(chat): add the chat ⋯ menus: pin, rename, share, archive and delete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

* fix(chat): read a shared chat's author with the server's client for their initials

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

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

* feat(chat): add Chat Home's greeting, the Inbox and the due-tasks line

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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

* feat(chat): add the composer, with send, Stop and steering, run modes and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

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

* feat(chat): add context chips and the Tab ghost suggestion to the composer

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

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

* feat(chat): add the composer's / @ and + menus, with a reference search

Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

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

* feat(chat): show a run's work live under its answer, with step chips, Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

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

* feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

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

* feat(chat): wire the composer and the live answer into Chat's pages

Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

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

* feat(chat): show the AI usage under Chat's composer, say 80% once, and pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf36).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

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

* feat(chat): copy Agent Chat's conversations into Chat on the first visit

On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

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

* feat(chat): add Search chats, the Ctrl K palette and the All chats page

Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

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

* feat(chat): add Chat Settings › General, Back to Chat and the app rail beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

* feat(chat): add Chat's side panel to every app page with Ask Chat and Ctrl J

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

* test(chat): name why your own chats' routes stay open on a read-only workspace

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

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

* test(chat): name why saving your own Chat menu state stays open on a read-only workspace

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

* test(chat): name why editing your own chat stays open on a read-only workspace

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

* test(chat): name why saving your own Chat settings and rail stays open on a read-only workspace

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

* fix(chat): keep the 80% usage line on the person, once per period on every device

The line above Chat's composer at 80% of the AI usage was kept closed per
browser. It now shows once per person per usage period (CHAT-04 item 16):
the first time it shows, its period goes to chat_user_prefs.usage_notice_period
(00408) through saveUsageNoticePeriod, and the Chat pages read it with the
composer's setup; × still closes it on the page.

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

* feat(chat): show the page's context as chips in the side panel, with Ask about this

The side panel's box starts with chips for what the page shows: its
name (the menu's when the page says nothing), the brand, the date range
and filters (CHAT-01 item 20). They follow the page while the panel is
open; × keeps one off until New chat. Pages tell the panel through
useChatPageContext, which reads a setter-only context so a page never
renders again for the panel. The empty panel offers up to three of the
page's questions, which fill the box unsent (item 21), and Ask about this
opens the panel with a chart or table attached as an @ chip (item 22).
The chips and @ objects go with the message: the engine keeps them on
chat_messages.context_json and gives them to the models as a data block,
the run's default scope (CHAT-04 item 8). Mentions & Sentiment is the
first page with its dates, filters, questions and two Ask about this
icons.

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

* feat(chat): give Brand Visibility, Citations, Prompts, Action Center, Traffic and Content their page context

Each page now tells Chat's side panel what it shows (W1-08's
useChatPageContext): its name, date range and filters as chips, and up to
three questions, one of them from data the page already loaded where it
has some (the platform whose visibility or visits moved most, the source
cited most, a tracked prompt the brand doesn't show up for, the top
action, a high-impact opportunity), without a model call. Ask about this
is on Brand Visibility's platform table and leaderboard, Citations' Top
Sources, Traffic's two tables, each tracked prompt and each Action Center
action; on a row it opens the panel, not the row.

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

* feat(chat): add the side panel's ⋯ menu, Open as full page and Back to the page

Once the panel has a chat, its ⋯ (CHAT-23 panel.more) offers Open as full
page, Open in new window, and for the author Pin, Rename (in the panel's
title), Share with team, Archive and Delete, the chat menus' own actions.
ChatActionsProvider tells a page outside the shell of a chat's new row
and of one archived or deleted, which empties the panel. Open as full
page goes to the chat on Chat's page with ?from= the page and its query;
the full page then shows ↙ Back to {page} (CHAT-22), only for a dashboard
page outside Chat. Back on a page, a panel that was away reads its chat
again, so it shows what happened on the full page.

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

* fix(chat): read the full page's search params at the top of the shell

Calling useSearchParams inside an expression kept the React Compiler from
preserving the shell's memoized callbacks (lint: preserve-manual-memoization).

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

* feat(chat): name the app page a side panel chat started on

A chat the side panel starts now keeps origin 'panel' and the page's path
in origin_page (CHAT-01 data notes); Chat's own page keeps 'page' and
/dashboard/chat. The engine takes origin and originPage with the first
message; a page it can't name is left out and the message still goes.
The path check is shared with POST /api/chat/conversations
(lib/chat/origin.ts).

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

* feat(chat): copy, download or save an answer to Files, and export a chat

Every finished answer gets an icon bar (CHAT-06 items 30–37): Copy (rich
text), Download as Markdown, Word or PDF, and CSV or Excel when it has a
table, rendered on the server from the stored answer with its time line
(GET /api/chat/runs/{id}/export, W1-24's writers), and Save to Files,
once per answer, then "In Files" (POST /api/chat/runs/{id}/file). Filing
goes through fileChatOutput, which run deliverables will use as they are
made: a row in chat_files and its content in chat-files, counted toward
storage, refused once a workspace is full. Storage per plan comes from
the spec: Starter 5 GB, Growth 25 GB, Enterprise 99 GB or its contract
(plan_overrides.maxStorageGb), 1 GB in the free trial, plus active
storage packs; self-host has no cap. Export chat in a chat's ⋯ menu now
downloads the whole chat as Markdown, Word or PDF. The PDF routes carry
public/fonts and keep @react-pdf/renderer outside the server bundle for
Vercel. The time line's words move to lib/chat/stamp for the server.

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

* fix(chat): keep a long answer's PDF from failing past ten pages

With the line height set on the page, react-pdf's page number threw
"unsupported number" once the PDF passed ten pages, so any long answer
failed to export. The line height now sits on the body text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): show what a run made as output cards and open answers in the Content Editor

- A write that makes something (create_draft's page) files it in Files as
  it is made and shows it under the answer as an output card: its type,
  title, "In Files" / "Used in Content draft" or "Not saved to Files ·
  Storage is full", Copy, Download in the formats it offers and Open in
  Content Editor (CHAT-06 items 1-6, 9, 29).
- Open in Content Editor on an answer's bar makes a Content draft of the
  answer in the chat's brand (else the brand open) and opens it.
- Files' pages download as HTML, Markdown, Word and PDF on the server: the
  Content Editor's writers run with a jsdom window (lib/content/server-dom).
- A reopened chat shows its output cards and filed answers again.

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

* fix(chat): keep the focus in the composer when a chip is removed

The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): add the Files page with filters, downloads, Download selected and the storage meter

- /dashboard/chat/files lists the workspace's files newest first, 50 at a
  time with Show more: name and formats ("Used in Content draft"), Made by
  (You, a teammate, Agent, Scheduled), From chat (only chats the person can
  open), and the generated time with "Data as of" (CHAT-06 items 12, 16-17).
- Chips All (with the workspace's count), Drafts, Reports, Code, Tables,
  Images, From me, From agents, and "Filter by name..." over the search
  column; "No files match." with Clear filters.
- Each row has Copy (Markdown), Open (its Content draft) and Download in
  the formats it offers. Picked rows download as one .zip in their main
  formats, up to 50 files and 100 MB (items 18-19).
- The storage meter ("Storage 2.1 of 25 GB", amber from 80%) and a line
  once storage is full, with no Get more until the plan rules are set
  (items 26-29).
- GET /api/chat/files, GET /api/chat/files/{id}, POST /api/chat/files/zip
  (reads only). Files sits under Settings in the chat menu, in the Ctrl K
  palette and in the breadcrumb.
- Help: help/chat/files.md (new).

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

* fix(chat): keep Agents at work to the person's own chats, and read the clock with each list read

A teammate's shared chat that waits on its author's OK no longer shows under
Agents at work or in Home's count. A chat that waits on an OK or is paused no
longer keeps the list on the 5 s pace. A menu left open past midnight now
moves Today's chats to Yesterday on the next list read.

* fix(chat): show a teammate's initials on a shared chat

A person reads only their own profile, so the author's name came back
empty on every teammate's shared chat. Read it on the server, within the
workspace; only the initials leave.

* fix(chat): keep a teammate's shared chat out of the Inbox and Home's count

A shared chat that waits for approval waits on its author, who alone can
answer it. The Inbox, its counts in the menu and the strip, and Home's
"things need you" now count the person's own chats only.

* fix(chat): read a * in the @ search as a space, not a wildcard

PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* style(chat): format the read-only open routes list so the web format check passes

* fix(chat): style answers as the app's other AI answers, take hand-made brand ids, and keep Files' draft line whole

From the W1-25…27 preview:
- A Chat answer's Markdown gets the prose styles the Mentions drawer and
  the response detail use (prose prose-sm dark:prose-invert max-w-none):
  headings, lists and table cells, in both themes.
- Starting a chat with a brand (createInput) and Chat Home's due-actions
  line take the demo brand's id with z.guid(): it is made by hand, not an
  RFC 4122 uuid (as #1849 did for starting a run).
- On Files, "Used in Content draft" has its own line under the formats,
  so a 1024px table no longer cuts it off.

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

* test(chat): check who may do what through the engine, role by class by mode (W1-22)

CHAT-05 test set 27–30 and CHAT-20 §4c, §5 end to end, with a scripted
model and the in-memory database:
- Each role is offered only the changes its role allows, and the
  explainer when something is left out.
- Every role reads in every mode with no card.
- A change waits on its card in Ask me first and Auto. Full auto runs it
  for an Admin, and for a Manager only while members may.
- Full auto stays on Growth and up, paid: Starter and the trial get the
  card, and Enterprise's trial runs.
- An Analyst and an Agency partner get the four-part refusal in every
  mode. Nothing changes, and each refusal is logged with its rule.
- An EXECUTE never runs without the click; a Manager the Admin turned
  publishing off for is refused by policy.
- A role lowered while the card waits refuses the approval.

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

* fix(chat): don't offer Admins the request to the Admins

Admins have no one to ask (CHAT-20 access table: "not needed"): the model
was offered request_access for them, so it could put up a card the server
then turned away. The engine now neither offers it to an Admin nor lists it
among what they can't do. The row keeps every role: defineTool never
leaves an Admin out of a row, by design.

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

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

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

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

* fix(chat): clean the pages Chat files, number output cards by their files, copy as Safari allows

From the pre-push review of W1-25…27:
- create_draft's page goes to Files as the draft keeps it, through
  sanitizeDraftHtml, and Files' HTML download cleans it again: a page Chat
  read can't slip a script or an event handler into a download (CHAT-06:
  no script in exported HTML).
- An output card's file is its place among the run's filed outputs, as
  the server counts them. A card that wasn't filed (storage full, failed)
  no longer shifts the next card onto another page's file.
- Copy on an output card writes a clipboard item within the click, its
  text to come (Safari refuses a write after an await), and says when it
  can't.
- A reopened chat's output cards mask ids in their titles, as the live
  events do.

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

* fix(chat): stream Download selected, copy Files rows as Safari allows, and say what a full workspace keeps

From the pre-push review of W1-25…27:
- Download selected streams the .zip as it is made (fflate's Zip): one
  file read, written and compressed at a time as the reader asks for
  more, so neither the files nor the .zip are held whole, and a .zip past
  a function's body cap still goes out. The limits stay: 50 files, 100 MB
  stored, checked before anything is read.
- Copy on a Files row writes a clipboard item within the click, its text
  to come (Safari refuses a write after an await), and says when it can't.
- Help: with storage full, an output's card can't copy or download it (it
  has no file); the answer above it still can.

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

* fix(chat): keep Data used to "Read …" steps, and plain links in the answer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): send an attachment with its type, and call it ready only when its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): keep a copied Agent Chat thread in its order

Agent Chat wrote a conversation's whole thread again on every turn in one
insert, so its messages share one created_at and their ids don't follow
the order. The copy read them by created_at then id, which shuffled them,
and Chat reads a chat by created_at alone. Read each conversation the way
Agent Chat's own page did (by created_at, no tiebreak) and give the copies
a strictly rising created_at, a millisecond apart where they tied.

Also cut a long title or message without splitting an emoji in half.

* fix(chat): open Full auto in the composer only where the server runs it, and steer only after Stop is taken

The composer's Full auto now follows the same facts the approval check uses:
the plan, and for anyone but an Admin the Admin's Full auto for members
switch. When the switch closes it, the mode says Off by Admin rather than
Needs Growth. Steering sends the new message only once the Stop is taken;
otherwise the text stays in the box.

* fix(chat): find a domain, a number or an email address in Search chats

Each word goes to Postgres quoted, so it splits it the way it split the
text: "nike.com", "4.5" or an address is one token there and is now
found whole, and Postgres lowercases it itself.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): tie a step's hold to its chat's agent run and keep paused runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

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

* test(chat): give the test's EXECUTE row its words, assert approvals before driving, and cover an Admin's request

From the pre-push review of W1-22:
- publish_page, the test's own EXECUTE row, gets its words through a mock
  of the messages (the product has no such tool yet), so no
  MISSING_MESSAGE trace prints. The publishing refusal's "asked" is now
  checked.
- Approvals are asserted before the run is driven on, so a refused one
  fails the test instead of passing quietly. The approve helper returns
  a refusal for its callers to check.
- An Admin's call to request_access, which they aren't offered, is turned
  away: no card, no request. The row's comment says how Admins are kept
  out.

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

* feat(chat): pause a run on a question card and go on with the answer

The write phase can call ask_question: 2-4 options, exactly one
Recommended. The run waits on an `ask` step and its chat_asks row, with no
model call. POST /api/chat/runs/{id}/answer keeps the answer once (409 when
already answered, 400 when it doesn't fit, 402 while read-only) and the run
goes on.

- Skip goes on with the Recommended option.
- Stop keeps open questions as skipped.
- A run asks at most 4.
- Questions asked together show "1 of 2", then "2 of 2".
- A message from the composer answers the question, and the rest of its
  batch.

QuestionCard (number keys, Enter = Next, Other..., multi, read-only gate)
and its folded line; the composer's ghost shows the Recommended option.
Help and the preview page show it.

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

* fix(chat): say when a question card takes several answers

A question with several picks looked like a one-pick question. Its footer
now says "Pick one or more · Press 1–N to pick", in the mockup's words,
and each row has a check box that ticks when picked. Help says the same.

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

* style(chat): format the read-only open actions list so the web format check passes

* wip(chat): next moves (W2-02, in progress)

* fix(chat): keep Chat on at the AI limit on the workspace's own key, and read the usage again after each run

The composer turned off whenever the allowance was used up, but Chat on
the workspace's own key never draws on it (the server's hold writes those
steps unchecked), so a workspace with its own key could not send at all.
The page now reads whether Chat runs on the workspace's own key, as the
server picks it, and keeps the composer on then.

The meter, the 80% line and the pause also read the usage again once a
run stops working, so they follow the chat's own spending without a
page change. One read per run, no timer.

* fix(chat): name the run's own brand in the page context, and keep its block closed

The brand chip a message carries is now the run's own brand (the chat's,
checked against the workspace), not the posted label and id; it goes when
the run has no brand. The page context reaches the models with < and > as
JSON escapes, so a label can't end the block, and a reference's scope is
capped at 8 entries.

* fix(chat): name only a known platform in Traffic's question, and the first Top action in Action Center's

AI Referral Traffic's suggestion now reads the platform the page can name,
as the summary line does, and none over all time, where there is no
previous period and every platform would read as a rise. Action Center's
"How do I finish" names the first of the Top actions as the card ranks
them; the list arrives unordered.

* fix(chat): set up the side panel's composer as Chat's pages set theirs up

The panel's setup read Full auto from the plan alone and left out whether
Chat runs on the workspace's own key. So a member whose Admin turned "Full
auto for members" off could pick a mode that then asks anyway, and the
panel paused at the AI limit on a workspace's own key. The layout now reads
the switch and the key (only with the new Chat on) and builds the setup with
the same composerSetupOf Chat's pages use, moved to lib/chat/composer-setup;
the panel passes fullAutoOffByAdmin and onOwnKey on to the composer.

* perf(chat): load the side panel's code the first time it opens

The layout imported the panel directly, so its thread, composer and run
views came with every app page, Chat on or off. The layout now puts a
small slot there that loads the panel the first time it opens and keeps
it after that.

* fix(chat): keep Back to the page off paths with dot segments

panelReturnOf accepted /dashboard/../… and its %2e form, which resolve
outside the dashboard or into Chat. Refuse a . or .. segment.

* fix(chat): stop a run that waits on a question, and take its answer as the person's

From the review of the question card:

- Stop while a question waits: Stop sits beside Send and Esc stops the run.
  The question is kept skipped and its step reads "Question skipped".
- The answer reaches the model as the person's own (from: 'the person'),
  and the system prompt says to follow it like their message, not as data.
- A change called in the same step as a question doesn't run (not_run).
  The model calls it again with the answer.
- An answer kept while the run stopped meanwhile is let go again (no new
  migration), so the question doesn't stay half answered.
- The question card:
  - Enter on Skip, Add or an option is that button's own.
  - Text in Other... counts without Add, up to 500 characters.
- Answering from the composer:
  - It sends text only: no files, @ data or chips.
  - The box takes up to 500 characters; a 400 says why.
  - The composer is free at once (the answer's stream isn't awaited).
- "1 of N" counts only the questions the run will ask.
- A typed option label matches regardless of case, spacing, accents or
  Turkish i.
- Questions are capped at 200 characters, the step label's length.
- Help: the card section, and "Answer in the box".

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

* feat(chat): suggest next moves under a finished answer, the first as the composer's ghost

This commit and the wip commit before it make up CHAT-07 §C.

- With its final answer, in the same model step, the model calls
  suggest_next_moves. A step with only that call ends the run without
  another model step.
- The moves are picked for the person's role and plan as they are now:
  - an Analyst, an Agency partner or a read-only workspace gets read moves
    only;
  - one move per kind and per prompt, three at most, ids masked.
- They are kept in chat_next_moves (00417) and sent as next_moves before
  run.finished. None after an error, a pause at the cap, a Stop, or while a
  question or a change waits.
- The page shows them as "Next moves" cards under the latest answer only
  (mockup #s-done). A click sends the prompt as the next message.
- The first move shows as the composer's ghost when it continues this run
  (ghost_ok). A teammate's shared chat shows none.
- loadChatThread brings them back after a reload.
- Help ("Next moves") and the preview page show them.

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

* wip(chat): prompt, topic and competitor writes (W2-06, in progress)

* feat(chat): add the agents API: create, version, triggers, lifecycle and Run now (W2-13)

Chat's agents (CHAT-21, CHAT-27 §E) on the server, behind CHAT_AGENTIC:

- /api/chat/agents: list (Mine, Workspace, Paused, Archived, search) and
  create a draft; /{id}: detail, change (a new immutable version whenever
  what the agent does changes; name, visibility, caps and triggers change
  on the agent), delete once archived; /{id}/activate, pause, resume,
  archive, restore, duplicate; /{id}/run (Run now); /{id}/runs.
- Roles as §K: Admins and Managers make and run agents, a Manager changes
  only their own, private agents for their owner and Admins, Analysts and
  Agency partners read; refusals carry the out-of-permission answer
  (CHAT-20 §4c) and an access.denied row. Workspace agents kept to Admins
  and Full auto off follow Settings › Chat.
- Plan gates: Full auto Growth+, engines the plan tracks, active agents
  and agent runs at once per plan (§M, approved as written).
- Triggers: 0–5 schedule, Signal, KPI or watch-rule triggers, validated;
  a schedule's next fire from a dependency-free RRULE subset in its zone.
- Run now queues a run per brand (one per click a minute, at most 3
  waiting), acting as the person; a slot is tried with
  chat_start_next_agent_run only once a driver exists (W2-16), so runs
  wait queued until then.
- AI use as shares only: each agent's share comes from the server's new
  GET /api/internal/chat/budget/agent-shares (chat_agent_usage_shares
  against the budget the server keeps), cached 5 minutes; no dollars reach
  the browser.
- Every write is gated by writeRefusal; every change and Run now goes to
  the Activity log with agent_id and agent_run_id.

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

* fix(chat): open an answer in the Content Editor as the answer shows it

An image in the answer goes into the draft as its alt text, and raw HTML
as its text, as the answer itself shows them; links stay, cleaned by the
draft's own sanitizing.

* fix(chat): show on a next move the text it sends, and keep only the last step's moves

From the review of next moves:

- A card shows the very prompt a click sends, never a label that could say
  something else. A page Chat read could otherwise dress a write up as "See
  the full report".
- Moves belong to the step they came with: they are cleared before each
  writing step, so a question, an answer and a last step without moves
  shows none.
- The tool takes the call whole (up to 6 moves, loose fields) and checks
  each move on its own (validMoves). A move too long or of an unknown kind
  loses only itself.
- A move whose label or prompt names a tool, or reads like one
  (snake_case), is dropped before it is kept.
- loadChatThread logs a failed read of the moves and opens the chat
  without them. A teammate's shared chat doesn't read them.
- In the side panel the cards stand one under another; two or three side by
  side on a page.
- Comment: ghost_ok is the model's word, not checked.
- Tests: moves that can't be kept, an error and a Stop after a step with
  moves.

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

* fix(chat): let a Stop after Approve win, and finish the who-may-do-what matrix

A Stop that comes after Approve, before the approved change runs, now
stops the run: in the same process the change no longer runs, and from
another process the card is closed with run.stopped instead of the run
staying stopped with its step still waiting.

The matrix's test-only EXECUTE row is Admin and Manager work, as in
precedence.test, and the matrix now covers every change row, Analysts'
and Agency partners' own changes in each mode, their refused go-live,
a teammate answering someone else's card, a click refused after the
Admin turned publishing off, and the demo brand for every role.

* fix(chat): show Admins every agent, keep triggers across saves, and add Take over (W2-13)

Review fixes on the agents API:

- Workspace tab: an Admin sees every agent in use, others' private ones
  included (CHAT-21 §K, edge case 1); the counts follow.
- Triggers are matched with their keys sorted (canonicalJson): jsonb's
  key order no longer makes a KPI, Signal or one-off trigger look new, so
  its last fire and cooldown stay.
- Only a new or changed trigger is held to the clock: a one-off that
  already fired can come back with a save.
- Run now claims an idempotency key (agent, brand, person, minute), so two
  clicks at once queue one run; a run counted past the 3 waiting after its
  insert goes again and joins the last.
- POST /api/chat/agents/{id}/take-over: an Admin becomes the owner; an
  agent that is on, or paused because of its owner, passes the activation
  checks under them first and comes back on; logged.
- Duplicate is held to create's checks (mode, engines, brands, topics,
  people).
- The internal budget endpoints compare CRON_SECRET in constant time
  (webhookSecretsMatch).
- Tests for another workspace's or a teammate's private agent (404).

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

* fix(chat): keep a long answer's or chat's PDF within the route's time

react-pdf's layout time grows with the square of the length: 2,000 table
rows took about 60 s and 6,000 rows about 4 minutes, and Export chat joins
every answer of a chat. A PDF now lays out 1,000 rows and blocks at most
and ends with a line saying so (Markdown and Word keep all of it), and
both export routes get maxDuration 300.

Also matches the downloaded body in the answer bar's test by its size:
fetch's Blob is Node's, not the test page's.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): track prompts, topics and competitors from Chat, with Undo

This commit and the wip commit before it make up W2-06 (CHAT-20 §9 rows 20–32).

New WRITE rows, one registry file per area:
- add_prompts: prompts in one of the brand's topics, topic first.
- pause_prompts: the spec's "archive"; the app pauses, history kept.
- add_topic, rename_topic.
- add_competitors, remove_competitor (always a card).

How they run:
- Admins and Managers, as the app (00382, #1762). Others get the
  structured refusal.
- Each calls a thin server action over the app's own:
  - addTopicPrompts runs through importPrompts: the plan's prompt
    locations, duplicates skipped, first run started.
  - pauseBrandPrompts, addBrandTopic, addCompetitors and
    removeBrandCompetitor each check the brand and skip natural-key
    duplicates.
- Every one checks the read-only workspace first.

Undo for each (undo-setup.ts), 7 days, 30 for paused prompts. Anything
changed since is left alone (undo_conflict). Resuming paused prompts checks
the plan's room again.

Registry and engine:
- A row may name its batch: the run's caps count items (50 prompts, 5
  competitors), and more than 5 prompts paused at once always shows a card
  (overBatch).
- A row may name its card's target from the data: the topic, the prompts,
  the competitor.
- A refusal the person can act on (quota_exceeded, duplicate, not_found,
  invalid) shows the action's words on the step and gives the model its
  §11a code.
- An action's { ok: false } refusal is no longer logged as a change.

Help: chat.md "Change what you track".

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

* fix(chat): let a Stop right after an answer win, and keep a question the run never went on with as skipped

The answer branch of resumePending now checks for a Stop before taking the
answer up, as an approved change does. A stopped run's open question is kept
as skipped even when its answer was kept just before the Stop, and an answer
whose run ended before it was taken back is kept as skipped rather than
cleared. Tests: Stop after an answer in this process and in another, the
run-ended-meanwhile case, and a teammate's answer, skip and stop on a shared
chat.

* wip(chat): content, report and audit writes (W2-07, in progress)

* chore: no changes; push again so GitHub picks up the merged fixes

* fix(chat): start a run from a tainted run's next move tainted, and drop moves that carry a link

* fix(chat): hold a change to someone else's agent to its owner's mode, and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since its trigge…
gkhngyk added a commit that referenced this pull request Oct 31, 2026
…s, hidden text out (W2-08) (#1877)

* fix(prompts): ask for a topic before adding prompts or generating suggestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (#1763, #1769) is unchanged.

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

* fix(prompts): add a topic in place on the Prompts page, and say why suggestions failed

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since #1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as #1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

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

* docs(help): say a brand adds a topic before its prompts

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

* feat(chat): add Wave 1's tables for sharing, settings, attachments, Files, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

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

* feat(chat): export an answer as Markdown, Word, PDF, CSV or Excel

CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

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

* feat(chat): open Chat at /dashboard/chat and add its chats API

Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (#1812 note).
- Help: a "chat" area and its first article (approved: false).

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

* feat(chat): add the chat menu with Agents at work, day groups and Ctrl+\

Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, #1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

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

* feat(chat): add the chat ⋯ menus: pin, rename, share, archive and delete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

* fix(chat): read a shared chat's author with the server's client for their initials

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

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

* feat(chat): add Chat Home's greeting, the Inbox and the due-tasks line

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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

* feat(chat): add the composer, with send, Stop and steering, run modes and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

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

* feat(chat): add context chips and the Tab ghost suggestion to the composer

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

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

* feat(chat): add the composer's / @ and + menus, with a reference search

Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

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

* feat(chat): show a run's work live under its answer, with step chips, Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

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

* feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

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

* feat(chat): wire the composer and the live answer into Chat's pages

Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

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

* feat(chat): show the AI usage under Chat's composer, say 80% once, and pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf36).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

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

* feat(chat): copy Agent Chat's conversations into Chat on the first visit

On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

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

* feat(chat): add Search chats, the Ctrl K palette and the All chats page

Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

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

* feat(chat): add Chat Settings › General, Back to Chat and the app rail beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

* feat(chat): add Chat's side panel to every app page with Ask Chat and Ctrl J

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

* test(chat): name why your own chats' routes stay open on a read-only workspace

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

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

* test(chat): name why saving your own Chat menu state stays open on a read-only workspace

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

* test(chat): name why editing your own chat stays open on a read-only workspace

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

* test(chat): name why saving your own Chat settings and rail stays open on a read-only workspace

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

* fix(chat): keep the 80% usage line on the person, once per period on every device

The line above Chat's composer at 80% of the AI usage was kept closed per
browser. It now shows once per person per usage period (CHAT-04 item 16):
the first time it shows, its period goes to chat_user_prefs.usage_notice_period
(00408) through saveUsageNoticePeriod, and the Chat pages read it with the
composer's setup; × still closes it on the page.

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

* feat(chat): show the page's context as chips in the side panel, with Ask about this

The side panel's box starts with chips for what the page shows: its
name (the menu's when the page says nothing), the brand, the date range
and filters (CHAT-01 item 20). They follow the page while the panel is
open; × keeps one off until New chat. Pages tell the panel through
useChatPageContext, which reads a setter-only context so a page never
renders again for the panel. The empty panel offers up to three of the
page's questions, which fill the box unsent (item 21), and Ask about this
opens the panel with a chart or table attached as an @ chip (item 22).
The chips and @ objects go with the message: the engine keeps them on
chat_messages.context_json and gives them to the models as a data block,
the run's default scope (CHAT-04 item 8). Mentions & Sentiment is the
first page with its dates, filters, questions and two Ask about this
icons.

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

* feat(chat): give Brand Visibility, Citations, Prompts, Action Center, Traffic and Content their page context

Each page now tells Chat's side panel what it shows (W1-08's
useChatPageContext): its name, date range and filters as chips, and up to
three questions, one of them from data the page already loaded where it
has some (the platform whose visibility or visits moved most, the source
cited most, a tracked prompt the brand doesn't show up for, the top
action, a high-impact opportunity), without a model call. Ask about this
is on Brand Visibility's platform table and leaderboard, Citations' Top
Sources, Traffic's two tables, each tracked prompt and each Action Center
action; on a row it opens the panel, not the row.

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

* feat(chat): add the side panel's ⋯ menu, Open as full page and Back to the page

Once the panel has a chat, its ⋯ (CHAT-23 panel.more) offers Open as full
page, Open in new window, and for the author Pin, Rename (in the panel's
title), Share with team, Archive and Delete, the chat menus' own actions.
ChatActionsProvider tells a page outside the shell of a chat's new row
and of one archived or deleted, which empties the panel. Open as full
page goes to the chat on Chat's page with ?from= the page and its query;
the full page then shows ↙ Back to {page} (CHAT-22), only for a dashboard
page outside Chat. Back on a page, a panel that was away reads its chat
again, so it shows what happened on the full page.

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

* fix(chat): read the full page's search params at the top of the shell

Calling useSearchParams inside an expression kept the React Compiler from
preserving the shell's memoized callbacks (lint: preserve-manual-memoization).

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

* feat(chat): name the app page a side panel chat started on

A chat the side panel starts now keeps origin 'panel' and the page's path
in origin_page (CHAT-01 data notes); Chat's own page keeps 'page' and
/dashboard/chat. The engine takes origin and originPage with the first
message; a page it can't name is left out and the message still goes.
The path check is shared with POST /api/chat/conversations
(lib/chat/origin.ts).

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

* feat(chat): copy, download or save an answer to Files, and export a chat

Every finished answer gets an icon bar (CHAT-06 items 30–37): Copy (rich
text), Download as Markdown, Word or PDF, and CSV or Excel when it has a
table, rendered on the server from the stored answer with its time line
(GET /api/chat/runs/{id}/export, W1-24's writers), and Save to Files,
once per answer, then "In Files" (POST /api/chat/runs/{id}/file). Filing
goes through fileChatOutput, which run deliverables will use as they are
made: a row in chat_files and its content in chat-files, counted toward
storage, refused once a workspace is full. Storage per plan comes from
the spec: Starter 5 GB, Growth 25 GB, Enterprise 99 GB or its contract
(plan_overrides.maxStorageGb), 1 GB in the free trial, plus active
storage packs; self-host has no cap. Export chat in a chat's ⋯ menu now
downloads the whole chat as Markdown, Word or PDF. The PDF routes carry
public/fonts and keep @react-pdf/renderer outside the server bundle for
Vercel. The time line's words move to lib/chat/stamp for the server.

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

* fix(chat): keep a long answer's PDF from failing past ten pages

With the line height set on the page, react-pdf's page number threw
"unsupported number" once the PDF passed ten pages, so any long answer
failed to export. The line height now sits on the body text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): show what a run made as output cards and open answers in the Content Editor

- A write that makes something (create_draft's page) files it in Files as
  it is made and shows it under the answer as an output card: its type,
  title, "In Files" / "Used in Content draft" or "Not saved to Files ·
  Storage is full", Copy, Download in the formats it offers and Open in
  Content Editor (CHAT-06 items 1-6, 9, 29).
- Open in Content Editor on an answer's bar makes a Content draft of the
  answer in the chat's brand (else the brand open) and opens it.
- Files' pages download as HTML, Markdown, Word and PDF on the server: the
  Content Editor's writers run with a jsdom window (lib/content/server-dom).
- A reopened chat shows its output cards and filed answers again.

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

* fix(chat): keep the focus in the composer when a chip is removed

The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): add the Files page with filters, downloads, Download selected and the storage meter

- /dashboard/chat/files lists the workspace's files newest first, 50 at a
  time with Show more: name and formats ("Used in Content draft"), Made by
  (You, a teammate, Agent, Scheduled), From chat (only chats the person can
  open), and the generated time with "Data as of" (CHAT-06 items 12, 16-17).
- Chips All (with the workspace's count), Drafts, Reports, Code, Tables,
  Images, From me, From agents, and "Filter by name..." over the search
  column; "No files match." with Clear filters.
- Each row has Copy (Markdown), Open (its Content draft) and Download in
  the formats it offers. Picked rows download as one .zip in their main
  formats, up to 50 files and 100 MB (items 18-19).
- The storage meter ("Storage 2.1 of 25 GB", amber from 80%) and a line
  once storage is full, with no Get more until the plan rules are set
  (items 26-29).
- GET /api/chat/files, GET /api/chat/files/{id}, POST /api/chat/files/zip
  (reads only). Files sits under Settings in the chat menu, in the Ctrl K
  palette and in the breadcrumb.
- Help: help/chat/files.md (new).

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

* fix(chat): keep Agents at work to the person's own chats, and read the clock with each list read

A teammate's shared chat that waits on its author's OK no longer shows under
Agents at work or in Home's count. A chat that waits on an OK or is paused no
longer keeps the list on the 5 s pace. A menu left open past midnight now
moves Today's chats to Yesterday on the next list read.

* fix(chat): show a teammate's initials on a shared chat

A person reads only their own profile, so the author's name came back
empty on every teammate's shared chat. Read it on the server, within the
workspace; only the initials leave.

* fix(chat): keep a teammate's shared chat out of the Inbox and Home's count

A shared chat that waits for approval waits on its author, who alone can
answer it. The Inbox, its counts in the menu and the strip, and Home's
"things need you" now count the person's own chats only.

* fix(chat): read a * in the @ search as a space, not a wildcard

PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* style(chat): format the read-only open routes list so the web format check passes

* fix(chat): style answers as the app's other AI answers, take hand-made brand ids, and keep Files' draft line whole

From the W1-25…27 preview:
- A Chat answer's Markdown gets the prose styles the Mentions drawer and
  the response detail use (prose prose-sm dark:prose-invert max-w-none):
  headings, lists and table cells, in both themes.
- Starting a chat with a brand (createInput) and Chat Home's due-actions
  line take the demo brand's id with z.guid(): it is made by hand, not an
  RFC 4122 uuid (as #1849 did for starting a run).
- On Files, "Used in Content draft" has its own line under the formats,
  so a 1024px table no longer cuts it off.

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

* test(chat): check who may do what through the engine, role by class by mode (W1-22)

CHAT-05 test set 27–30 and CHAT-20 §4c, §5 end to end, with a scripted
model and the in-memory database:
- Each role is offered only the changes its role allows, and the
  explainer when something is left out.
- Every role reads in every mode with no card.
- A change waits on its card in Ask me first and Auto. Full auto runs it
  for an Admin, and for a Manager only while members may.
- Full auto stays on Growth and up, paid: Starter and the trial get the
  card, and Enterprise's trial runs.
- An Analyst and an Agency partner get the four-part refusal in every
  mode. Nothing changes, and each refusal is logged with its rule.
- An EXECUTE never runs without the click; a Manager the Admin turned
  publishing off for is refused by policy.
- A role lowered while the card waits refuses the approval.

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

* fix(chat): don't offer Admins the request to the Admins

Admins have no one to ask (CHAT-20 access table: "not needed"): the model
was offered request_access for them, so it could put up a card the server
then turned away. The engine now neither offers it to an Admin nor lists it
among what they can't do. The row keeps every role: defineTool never
leaves an Admin out of a row, by design.

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

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

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

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

* fix(chat): clean the pages Chat files, number output cards by their files, copy as Safari allows

From the pre-push review of W1-25…27:
- create_draft's page goes to Files as the draft keeps it, through
  sanitizeDraftHtml, and Files' HTML download cleans it again: a page Chat
  read can't slip a script or an event handler into a download (CHAT-06:
  no script in exported HTML).
- An output card's file is its place among the run's filed outputs, as
  the server counts them. A card that wasn't filed (storage full, failed)
  no longer shifts the next card onto another page's file.
- Copy on an output card writes a clipboard item within the click, its
  text to come (Safari refuses a write after an await), and says when it
  can't.
- A reopened chat's output cards mask ids in their titles, as the live
  events do.

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

* fix(chat): stream Download selected, copy Files rows as Safari allows, and say what a full workspace keeps

From the pre-push review of W1-25…27:
- Download selected streams the .zip as it is made (fflate's Zip): one
  file read, written and compressed at a time as the reader asks for
  more, so neither the files nor the .zip are held whole, and a .zip past
  a function's body cap still goes out. The limits stay: 50 files, 100 MB
  stored, checked before anything is read.
- Copy on a Files row writes a clipboard item within the click, its text
  to come (Safari refuses a write after an await), and says when it can't.
- Help: with storage full, an output's card can't copy or download it (it
  has no file); the answer above it still can.

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

* fix(chat): keep Data used to "Read …" steps, and plain links in the answer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): send an attachment with its type, and call it ready only when its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): keep a copied Agent Chat thread in its order

Agent Chat wrote a conversation's whole thread again on every turn in one
insert, so its messages share one created_at and their ids don't follow
the order. The copy read them by created_at then id, which shuffled them,
and Chat reads a chat by created_at alone. Read each conversation the way
Agent Chat's own page did (by created_at, no tiebreak) and give the copies
a strictly rising created_at, a millisecond apart where they tied.

Also cut a long title or message without splitting an emoji in half.

* fix(chat): open Full auto in the composer only where the server runs it, and steer only after Stop is taken

The composer's Full auto now follows the same facts the approval check uses:
the plan, and for anyone but an Admin the Admin's Full auto for members
switch. When the switch closes it, the mode says Off by Admin rather than
Needs Growth. Steering sends the new message only once the Stop is taken;
otherwise the text stays in the box.

* fix(chat): find a domain, a number or an email address in Search chats

Each word goes to Postgres quoted, so it splits it the way it split the
text: "nike.com", "4.5" or an address is one token there and is now
found whole, and Postgres lowercases it itself.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): tie a step's hold to its chat's agent run and keep paused runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

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

* test(chat): give the test's EXECUTE row its words, assert approvals before driving, and cover an Admin's request

From the pre-push review of W1-22:
- publish_page, the test's own EXECUTE row, gets its words through a mock
  of the messages (the product has no such tool yet), so no
  MISSING_MESSAGE trace prints. The publishing refusal's "asked" is now
  checked.
- Approvals are asserted before the run is driven on, so a refused one
  fails the test instead of passing quietly. The approve helper returns
  a refusal for its callers to check.
- An Admin's call to request_access, which they aren't offered, is turned
  away: no card, no request. The row's comment says how Admins are kept
  out.

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

* feat(chat): pause a run on a question card and go on with the answer

The write phase can call ask_question: 2-4 options, exactly one
Recommended. The run waits on an `ask` step and its chat_asks row, with no
model call. POST /api/chat/runs/{id}/answer keeps the answer once (409 when
already answered, 400 when it doesn't fit, 402 while read-only) and the run
goes on.

- Skip goes on with the Recommended option.
- Stop keeps open questions as skipped.
- A run asks at most 4.
- Questions asked together show "1 of 2", then "2 of 2".
- A message from the composer answers the question, and the rest of its
  batch.

QuestionCard (number keys, Enter = Next, Other..., multi, read-only gate)
and its folded line; the composer's ghost shows the Recommended option.
Help and the preview page show it.

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

* fix(chat): say when a question card takes several answers

A question with several picks looked like a one-pick question. Its footer
now says "Pick one or more · Press 1–N to pick", in the mockup's words,
and each row has a check box that ticks when picked. Help says the same.

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

* style(chat): format the read-only open actions list so the web format check passes

* wip(chat): next moves (W2-02, in progress)

* fix(chat): keep Chat on at the AI limit on the workspace's own key, and read the usage again after each run

The composer turned off whenever the allowance was used up, but Chat on
the workspace's own key never draws on it (the server's hold writes those
steps unchecked), so a workspace with its own key could not send at all.
The page now reads whether Chat runs on the workspace's own key, as the
server picks it, and keeps the composer on then.

The meter, the 80% line and the pause also read the usage again once a
run stops working, so they follow the chat's own spending without a
page change. One read per run, no timer.

* fix(chat): name the run's own brand in the page context, and keep its block closed

The brand chip a message carries is now the run's own brand (the chat's,
checked against the workspace), not the posted label and id; it goes when
the run has no brand. The page context reaches the models with < and > as
JSON escapes, so a label can't end the block, and a reference's scope is
capped at 8 entries.

* fix(chat): name only a known platform in Traffic's question, and the first Top action in Action Center's

AI Referral Traffic's suggestion now reads the platform the page can name,
as the summary line does, and none over all time, where there is no
previous period and every platform would read as a rise. Action Center's
"How do I finish" names the first of the Top actions as the card ranks
them; the list arrives unordered.

* fix(chat): set up the side panel's composer as Chat's pages set theirs up

The panel's setup read Full auto from the plan alone and left out whether
Chat runs on the workspace's own key. So a member whose Admin turned "Full
auto for members" off could pick a mode that then asks anyway, and the
panel paused at the AI limit on a workspace's own key. The layout now reads
the switch and the key (only with the new Chat on) and builds the setup with
the same composerSetupOf Chat's pages use, moved to lib/chat/composer-setup;
the panel passes fullAutoOffByAdmin and onOwnKey on to the composer.

* perf(chat): load the side panel's code the first time it opens

The layout imported the panel directly, so its thread, composer and run
views came with every app page, Chat on or off. The layout now puts a
small slot there that loads the panel the first time it opens and keeps
it after that.

* fix(chat): keep Back to the page off paths with dot segments

panelReturnOf accepted /dashboard/../… and its %2e form, which resolve
outside the dashboard or into Chat. Refuse a . or .. segment.

* fix(chat): stop a run that waits on a question, and take its answer as the person's

From the review of the question card:

- Stop while a question waits: Stop sits beside Send and Esc stops the run.
  The question is kept skipped and its step reads "Question skipped".
- The answer reaches the model as the person's own (from: 'the person'),
  and the system prompt says to follow it like their message, not as data.
- A change called in the same step as a question doesn't run (not_run).
  The model calls it again with the answer.
- An answer kept while the run stopped meanwhile is let go again (no new
  migration), so the question doesn't stay half answered.
- The question card:
  - Enter on Skip, Add or an option is that button's own.
  - Text in Other... counts without Add, up to 500 characters.
- Answering from the composer:
  - It sends text only: no files, @ data or chips.
  - The box takes up to 500 characters; a 400 says why.
  - The composer is free at once (the answer's stream isn't awaited).
- "1 of N" counts only the questions the run will ask.
- A typed option label matches regardless of case, spacing, accents or
  Turkish i.
- Questions are capped at 200 characters, the step label's length.
- Help: the card section, and "Answer in the box".

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

* feat(chat): suggest next moves under a finished answer, the first as the composer's ghost

This commit and the wip commit before it make up CHAT-07 §C.

- With its final answer, in the same model step, the model calls
  suggest_next_moves. A step with only that call ends the run without
  another model step.
- The moves are picked for the person's role and plan as they are now:
  - an Analyst, an Agency partner or a read-only workspace gets read moves
    only;
  - one move per kind and per prompt, three at most, ids masked.
- They are kept in chat_next_moves (00417) and sent as next_moves before
  run.finished. None after an error, a pause at the cap, a Stop, or while a
  question or a change waits.
- The page shows them as "Next moves" cards under the latest answer only
  (mockup #s-done). A click sends the prompt as the next message.
- The first move shows as the composer's ghost when it continues this run
  (ghost_ok). A teammate's shared chat shows none.
- loadChatThread brings them back after a reload.
- Help ("Next moves") and the preview page show them.

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

* wip(chat): prompt, topic and competitor writes (W2-06, in progress)

* feat(chat): add the agents API: create, version, triggers, lifecycle and Run now (W2-13)

Chat's agents (CHAT-21, CHAT-27 §E) on the server, behind CHAT_AGENTIC:

- /api/chat/agents: list (Mine, Workspace, Paused, Archived, search) and
  create a draft; /{id}: detail, change (a new immutable version whenever
  what the agent does changes; name, visibility, caps and triggers change
  on the agent), delete once archived; /{id}/activate, pause, resume,
  archive, restore, duplicate; /{id}/run (Run now); /{id}/runs.
- Roles as §K: Admins and Managers make and run agents, a Manager changes
  only their own, private agents for their owner and Admins, Analysts and
  Agency partners read; refusals carry the out-of-permission answer
  (CHAT-20 §4c) and an access.denied row. Workspace agents kept to Admins
  and Full auto off follow Settings › Chat.
- Plan gates: Full auto Growth+, engines the plan tracks, active agents
  and agent runs at once per plan (§M, approved as written).
- Triggers: 0–5 schedule, Signal, KPI or watch-rule triggers, validated;
  a schedule's next fire from a dependency-free RRULE subset in its zone.
- Run now queues a run per brand (one per click a minute, at most 3
  waiting), acting as the person; a slot is tried with
  chat_start_next_agent_run only once a driver exists (W2-16), so runs
  wait queued until then.
- AI use as shares only: each agent's share comes from the server's new
  GET /api/internal/chat/budget/agent-shares (chat_agent_usage_shares
  against the budget the server keeps), cached 5 minutes; no dollars reach
  the browser.
- Every write is gated by writeRefusal; every change and Run now goes to
  the Activity log with agent_id and agent_run_id.

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

* fix(chat): open an answer in the Content Editor as the answer shows it

An image in the answer goes into the draft as its alt text, and raw HTML
as its text, as the answer itself shows them; links stay, cleaned by the
draft's own sanitizing.

* fix(chat): show on a next move the text it sends, and keep only the last step's moves

From the review of next moves:

- A card shows the very prompt a click sends, never a label that could say
  something else. A page Chat read could otherwise dress a write up as "See
  the full report".
- Moves belong to the step they came with: they are cleared before each
  writing step, so a question, an answer and a last step without moves
  shows none.
- The tool takes the call whole (up to 6 moves, loose fields) and checks
  each move on its own (validMoves). A move too long or of an unknown kind
  loses only itself.
- A move whose label or prompt names a tool, or reads like one
  (snake_case), is dropped before it is kept.
- loadChatThread logs a failed read of the moves and opens the chat
  without them. A teammate's shared chat doesn't read them.
- In the side panel the cards stand one under another; two or three side by
  side on a page.
- Comment: ghost_ok is the model's word, not checked.
- Tests: moves that can't be kept, an error and a Stop after a step with
  moves.

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

* fix(chat): let a Stop after Approve win, and finish the who-may-do-what matrix

A Stop that comes after Approve, before the approved change runs, now
stops the run: in the same process the change no longer runs, and from
another process the card is closed with run.stopped instead of the run
staying stopped with its step still waiting.

The matrix's test-only EXECUTE row is Admin and Manager work, as in
precedence.test, and the matrix now covers every change row, Analysts'
and Agency partners' own changes in each mode, their refused go-live,
a teammate answering someone else's card, a click refused after the
Admin turned publishing off, and the demo brand for every role.

* fix(chat): show Admins every agent, keep triggers across saves, and add Take over (W2-13)

Review fixes on the agents API:

- Workspace tab: an Admin sees every agent in use, others' private ones
  included (CHAT-21 §K, edge case 1); the counts follow.
- Triggers are matched with their keys sorted (canonicalJson): jsonb's
  key order no longer makes a KPI, Signal or one-off trigger look new, so
  its last fire and cooldown stay.
- Only a new or changed trigger is held to the clock: a one-off that
  already fired can come back with a save.
- Run now claims an idempotency key (agent, brand, person, minute), so two
  clicks at once queue one run; a run counted past the 3 waiting after its
  insert goes again and joins the last.
- POST /api/chat/agents/{id}/take-over: an Admin becomes the owner; an
  agent that is on, or paused because of its owner, passes the activation
  checks under them first and comes back on; logged.
- Duplicate is held to create's checks (mode, engines, brands, topics,
  people).
- The internal budget endpoints compare CRON_SECRET in constant time
  (webhookSecretsMatch).
- Tests for another workspace's or a teammate's private agent (404).

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

* fix(chat): keep a long answer's or chat's PDF within the route's time

react-pdf's layout time grows with the square of the length: 2,000 table
rows took about 60 s and 6,000 rows about 4 minutes, and Export chat joins
every answer of a chat. A PDF now lays out 1,000 rows and blocks at most
and ends with a line saying so (Markdown and Word keep all of it), and
both export routes get maxDuration 300.

Also matches the downloaded body in the answer bar's test by its size:
fetch's Blob is Node's, not the test page's.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): track prompts, topics and competitors from Chat, with Undo

This commit and the wip commit before it make up W2-06 (CHAT-20 §9 rows 20–32).

New WRITE rows, one registry file per area:
- add_prompts: prompts in one of the brand's topics, topic first.
- pause_prompts: the spec's "archive"; the app pauses, history kept.
- add_topic, rename_topic.
- add_competitors, remove_competitor (always a card).

How they run:
- Admins and Managers, as the app (00382, #1762). Others get the
  structured refusal.
- Each calls a thin server action over the app's own:
  - addTopicPrompts runs through importPrompts: the plan's prompt
    locations, duplicates skipped, first run started.
  - pauseBrandPrompts, addBrandTopic, addCompetitors and
    removeBrandCompetitor each check the brand and skip natural-key
    duplicates.
- Every one checks the read-only workspace first.

Undo for each (undo-setup.ts), 7 days, 30 for paused prompts. Anything
changed since is left alone (undo_conflict). Resuming paused prompts checks
the plan's room again.

Registry and engine:
- A row may name its batch: the run's caps count items (50 prompts, 5
  competitors), and more than 5 prompts paused at once always shows a card
  (overBatch).
- A row may name its card's target from the data: the topic, the prompts,
  the competitor.
- A refusal the person can act on (quota_exceeded, duplicate, not_found,
  invalid) shows the action's words on the step and gives the model its
  §11a code.
- An action's { ok: false } refusal is no longer logged as a change.

Help: chat.md "Change what you track".

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

* fix(chat): let a Stop right after an answer win, and keep a question the run never went on with as skipped

The answer branch of resumePending now checks for a Stop before taking the
answer up, as an approved change does. A stopped run's open question is kept
as skipped even when its answer was kept just before the Stop, and an answer
whose run ended before it was taken back is kept as skipped rather than
cleared. Tests: Stop after an answer in this process and in another, the
run-ended-meanwhile case, and a teammate's answer, skip and stop on a shared
chat.

* wip(chat): content, report and audit writes (W2-07, in progress)

* chore: no changes; push again so GitHub picks up the merged fixes

* fix(chat): start a run from a tainted run's next move tainted, and drop moves that carry a link

* fix(chat): hold a change to someone else's agent to its owner's mode, and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since its tr…
gkhngyk added a commit that referenced this pull request Oct 31, 2026
… (W2-18) (#1880)

* fix(prompts): ask for a topic before adding prompts or generating suggestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (#1763, #1769) is unchanged.

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

* fix(prompts): add a topic in place on the Prompts page, and say why suggestions failed

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since #1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as #1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

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

* docs(help): say a brand adds a topic before its prompts

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

* feat(chat): add Wave 1's tables for sharing, settings, attachments, Files, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

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

* feat(chat): export an answer as Markdown, Word, PDF, CSV or Excel

CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

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

* feat(chat): open Chat at /dashboard/chat and add its chats API

Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (#1812 note).
- Help: a "chat" area and its first article (approved: false).

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

* feat(chat): add the chat menu with Agents at work, day groups and Ctrl+\

Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, #1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

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

* feat(chat): add the chat ⋯ menus: pin, rename, share, archive and delete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

* fix(chat): read a shared chat's author with the server's client for their initials

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

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

* feat(chat): add Chat Home's greeting, the Inbox and the due-tasks line

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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

* feat(chat): add the composer, with send, Stop and steering, run modes and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

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

* feat(chat): add context chips and the Tab ghost suggestion to the composer

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

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

* feat(chat): add the composer's / @ and + menus, with a reference search

Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

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

* feat(chat): show a run's work live under its answer, with step chips, Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

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

* feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

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

* feat(chat): wire the composer and the live answer into Chat's pages

Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

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

* feat(chat): show the AI usage under Chat's composer, say 80% once, and pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf36).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

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

* feat(chat): copy Agent Chat's conversations into Chat on the first visit

On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

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

* feat(chat): add Search chats, the Ctrl K palette and the All chats page

Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

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

* feat(chat): add Chat Settings › General, Back to Chat and the app rail beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

* feat(chat): add Chat's side panel to every app page with Ask Chat and Ctrl J

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

* test(chat): name why your own chats' routes stay open on a read-only workspace

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

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

* test(chat): name why saving your own Chat menu state stays open on a read-only workspace

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

* test(chat): name why editing your own chat stays open on a read-only workspace

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

* test(chat): name why saving your own Chat settings and rail stays open on a read-only workspace

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

* fix(chat): keep the 80% usage line on the person, once per period on every device

The line above Chat's composer at 80% of the AI usage was kept closed per
browser. It now shows once per person per usage period (CHAT-04 item 16):
the first time it shows, its period goes to chat_user_prefs.usage_notice_period
(00408) through saveUsageNoticePeriod, and the Chat pages read it with the
composer's setup; × still closes it on the page.

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

* feat(chat): show the page's context as chips in the side panel, with Ask about this

The side panel's box starts with chips for what the page shows: its
name (the menu's when the page says nothing), the brand, the date range
and filters (CHAT-01 item 20). They follow the page while the panel is
open; × keeps one off until New chat. Pages tell the panel through
useChatPageContext, which reads a setter-only context so a page never
renders again for the panel. The empty panel offers up to three of the
page's questions, which fill the box unsent (item 21), and Ask about this
opens the panel with a chart or table attached as an @ chip (item 22).
The chips and @ objects go with the message: the engine keeps them on
chat_messages.context_json and gives them to the models as a data block,
the run's default scope (CHAT-04 item 8). Mentions & Sentiment is the
first page with its dates, filters, questions and two Ask about this
icons.

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

* feat(chat): give Brand Visibility, Citations, Prompts, Action Center, Traffic and Content their page context

Each page now tells Chat's side panel what it shows (W1-08's
useChatPageContext): its name, date range and filters as chips, and up to
three questions, one of them from data the page already loaded where it
has some (the platform whose visibility or visits moved most, the source
cited most, a tracked prompt the brand doesn't show up for, the top
action, a high-impact opportunity), without a model call. Ask about this
is on Brand Visibility's platform table and leaderboard, Citations' Top
Sources, Traffic's two tables, each tracked prompt and each Action Center
action; on a row it opens the panel, not the row.

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

* feat(chat): add the side panel's ⋯ menu, Open as full page and Back to the page

Once the panel has a chat, its ⋯ (CHAT-23 panel.more) offers Open as full
page, Open in new window, and for the author Pin, Rename (in the panel's
title), Share with team, Archive and Delete, the chat menus' own actions.
ChatActionsProvider tells a page outside the shell of a chat's new row
and of one archived or deleted, which empties the panel. Open as full
page goes to the chat on Chat's page with ?from= the page and its query;
the full page then shows ↙ Back to {page} (CHAT-22), only for a dashboard
page outside Chat. Back on a page, a panel that was away reads its chat
again, so it shows what happened on the full page.

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

* fix(chat): read the full page's search params at the top of the shell

Calling useSearchParams inside an expression kept the React Compiler from
preserving the shell's memoized callbacks (lint: preserve-manual-memoization).

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

* feat(chat): name the app page a side panel chat started on

A chat the side panel starts now keeps origin 'panel' and the page's path
in origin_page (CHAT-01 data notes); Chat's own page keeps 'page' and
/dashboard/chat. The engine takes origin and originPage with the first
message; a page it can't name is left out and the message still goes.
The path check is shared with POST /api/chat/conversations
(lib/chat/origin.ts).

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

* feat(chat): copy, download or save an answer to Files, and export a chat

Every finished answer gets an icon bar (CHAT-06 items 30–37): Copy (rich
text), Download as Markdown, Word or PDF, and CSV or Excel when it has a
table, rendered on the server from the stored answer with its time line
(GET /api/chat/runs/{id}/export, W1-24's writers), and Save to Files,
once per answer, then "In Files" (POST /api/chat/runs/{id}/file). Filing
goes through fileChatOutput, which run deliverables will use as they are
made: a row in chat_files and its content in chat-files, counted toward
storage, refused once a workspace is full. Storage per plan comes from
the spec: Starter 5 GB, Growth 25 GB, Enterprise 99 GB or its contract
(plan_overrides.maxStorageGb), 1 GB in the free trial, plus active
storage packs; self-host has no cap. Export chat in a chat's ⋯ menu now
downloads the whole chat as Markdown, Word or PDF. The PDF routes carry
public/fonts and keep @react-pdf/renderer outside the server bundle for
Vercel. The time line's words move to lib/chat/stamp for the server.

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

* fix(chat): keep a long answer's PDF from failing past ten pages

With the line height set on the page, react-pdf's page number threw
"unsupported number" once the PDF passed ten pages, so any long answer
failed to export. The line height now sits on the body text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): show what a run made as output cards and open answers in the Content Editor

- A write that makes something (create_draft's page) files it in Files as
  it is made and shows it under the answer as an output card: its type,
  title, "In Files" / "Used in Content draft" or "Not saved to Files ·
  Storage is full", Copy, Download in the formats it offers and Open in
  Content Editor (CHAT-06 items 1-6, 9, 29).
- Open in Content Editor on an answer's bar makes a Content draft of the
  answer in the chat's brand (else the brand open) and opens it.
- Files' pages download as HTML, Markdown, Word and PDF on the server: the
  Content Editor's writers run with a jsdom window (lib/content/server-dom).
- A reopened chat shows its output cards and filed answers again.

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

* fix(chat): keep the focus in the composer when a chip is removed

The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): add the Files page with filters, downloads, Download selected and the storage meter

- /dashboard/chat/files lists the workspace's files newest first, 50 at a
  time with Show more: name and formats ("Used in Content draft"), Made by
  (You, a teammate, Agent, Scheduled), From chat (only chats the person can
  open), and the generated time with "Data as of" (CHAT-06 items 12, 16-17).
- Chips All (with the workspace's count), Drafts, Reports, Code, Tables,
  Images, From me, From agents, and "Filter by name..." over the search
  column; "No files match." with Clear filters.
- Each row has Copy (Markdown), Open (its Content draft) and Download in
  the formats it offers. Picked rows download as one .zip in their main
  formats, up to 50 files and 100 MB (items 18-19).
- The storage meter ("Storage 2.1 of 25 GB", amber from 80%) and a line
  once storage is full, with no Get more until the plan rules are set
  (items 26-29).
- GET /api/chat/files, GET /api/chat/files/{id}, POST /api/chat/files/zip
  (reads only). Files sits under Settings in the chat menu, in the Ctrl K
  palette and in the breadcrumb.
- Help: help/chat/files.md (new).

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

* fix(chat): keep Agents at work to the person's own chats, and read the clock with each list read

A teammate's shared chat that waits on its author's OK no longer shows under
Agents at work or in Home's count. A chat that waits on an OK or is paused no
longer keeps the list on the 5 s pace. A menu left open past midnight now
moves Today's chats to Yesterday on the next list read.

* fix(chat): show a teammate's initials on a shared chat

A person reads only their own profile, so the author's name came back
empty on every teammate's shared chat. Read it on the server, within the
workspace; only the initials leave.

* fix(chat): keep a teammate's shared chat out of the Inbox and Home's count

A shared chat that waits for approval waits on its author, who alone can
answer it. The Inbox, its counts in the menu and the strip, and Home's
"things need you" now count the person's own chats only.

* fix(chat): read a * in the @ search as a space, not a wildcard

PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* style(chat): format the read-only open routes list so the web format check passes

* fix(chat): style answers as the app's other AI answers, take hand-made brand ids, and keep Files' draft line whole

From the W1-25…27 preview:
- A Chat answer's Markdown gets the prose styles the Mentions drawer and
  the response detail use (prose prose-sm dark:prose-invert max-w-none):
  headings, lists and table cells, in both themes.
- Starting a chat with a brand (createInput) and Chat Home's due-actions
  line take the demo brand's id with z.guid(): it is made by hand, not an
  RFC 4122 uuid (as #1849 did for starting a run).
- On Files, "Used in Content draft" has its own line under the formats,
  so a 1024px table no longer cuts it off.

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

* test(chat): check who may do what through the engine, role by class by mode (W1-22)

CHAT-05 test set 27–30 and CHAT-20 §4c, §5 end to end, with a scripted
model and the in-memory database:
- Each role is offered only the changes its role allows, and the
  explainer when something is left out.
- Every role reads in every mode with no card.
- A change waits on its card in Ask me first and Auto. Full auto runs it
  for an Admin, and for a Manager only while members may.
- Full auto stays on Growth and up, paid: Starter and the trial get the
  card, and Enterprise's trial runs.
- An Analyst and an Agency partner get the four-part refusal in every
  mode. Nothing changes, and each refusal is logged with its rule.
- An EXECUTE never runs without the click; a Manager the Admin turned
  publishing off for is refused by policy.
- A role lowered while the card waits refuses the approval.

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

* fix(chat): don't offer Admins the request to the Admins

Admins have no one to ask (CHAT-20 access table: "not needed"): the model
was offered request_access for them, so it could put up a card the server
then turned away. The engine now neither offers it to an Admin nor lists it
among what they can't do. The row keeps every role: defineTool never
leaves an Admin out of a row, by design.

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

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

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

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

* fix(chat): clean the pages Chat files, number output cards by their files, copy as Safari allows

From the pre-push review of W1-25…27:
- create_draft's page goes to Files as the draft keeps it, through
  sanitizeDraftHtml, and Files' HTML download cleans it again: a page Chat
  read can't slip a script or an event handler into a download (CHAT-06:
  no script in exported HTML).
- An output card's file is its place among the run's filed outputs, as
  the server counts them. A card that wasn't filed (storage full, failed)
  no longer shifts the next card onto another page's file.
- Copy on an output card writes a clipboard item within the click, its
  text to come (Safari refuses a write after an await), and says when it
  can't.
- A reopened chat's output cards mask ids in their titles, as the live
  events do.

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

* fix(chat): stream Download selected, copy Files rows as Safari allows, and say what a full workspace keeps

From the pre-push review of W1-25…27:
- Download selected streams the .zip as it is made (fflate's Zip): one
  file read, written and compressed at a time as the reader asks for
  more, so neither the files nor the .zip are held whole, and a .zip past
  a function's body cap still goes out. The limits stay: 50 files, 100 MB
  stored, checked before anything is read.
- Copy on a Files row writes a clipboard item within the click, its text
  to come (Safari refuses a write after an await), and says when it can't.
- Help: with storage full, an output's card can't copy or download it (it
  has no file); the answer above it still can.

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

* fix(chat): keep Data used to "Read …" steps, and plain links in the answer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): send an attachment with its type, and call it ready only when its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): keep a copied Agent Chat thread in its order

Agent Chat wrote a conversation's whole thread again on every turn in one
insert, so its messages share one created_at and their ids don't follow
the order. The copy read them by created_at then id, which shuffled them,
and Chat reads a chat by created_at alone. Read each conversation the way
Agent Chat's own page did (by created_at, no tiebreak) and give the copies
a strictly rising created_at, a millisecond apart where they tied.

Also cut a long title or message without splitting an emoji in half.

* fix(chat): open Full auto in the composer only where the server runs it, and steer only after Stop is taken

The composer's Full auto now follows the same facts the approval check uses:
the plan, and for anyone but an Admin the Admin's Full auto for members
switch. When the switch closes it, the mode says Off by Admin rather than
Needs Growth. Steering sends the new message only once the Stop is taken;
otherwise the text stays in the box.

* fix(chat): find a domain, a number or an email address in Search chats

Each word goes to Postgres quoted, so it splits it the way it split the
text: "nike.com", "4.5" or an address is one token there and is now
found whole, and Postgres lowercases it itself.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): tie a step's hold to its chat's agent run and keep paused runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

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

* test(chat): give the test's EXECUTE row its words, assert approvals before driving, and cover an Admin's request

From the pre-push review of W1-22:
- publish_page, the test's own EXECUTE row, gets its words through a mock
  of the messages (the product has no such tool yet), so no
  MISSING_MESSAGE trace prints. The publishing refusal's "asked" is now
  checked.
- Approvals are asserted before the run is driven on, so a refused one
  fails the test instead of passing quietly. The approve helper returns
  a refusal for its callers to check.
- An Admin's call to request_access, which they aren't offered, is turned
  away: no card, no request. The row's comment says how Admins are kept
  out.

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

* feat(chat): pause a run on a question card and go on with the answer

The write phase can call ask_question: 2-4 options, exactly one
Recommended. The run waits on an `ask` step and its chat_asks row, with no
model call. POST /api/chat/runs/{id}/answer keeps the answer once (409 when
already answered, 400 when it doesn't fit, 402 while read-only) and the run
goes on.

- Skip goes on with the Recommended option.
- Stop keeps open questions as skipped.
- A run asks at most 4.
- Questions asked together show "1 of 2", then "2 of 2".
- A message from the composer answers the question, and the rest of its
  batch.

QuestionCard (number keys, Enter = Next, Other..., multi, read-only gate)
and its folded line; the composer's ghost shows the Recommended option.
Help and the preview page show it.

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

* fix(chat): say when a question card takes several answers

A question with several picks looked like a one-pick question. Its footer
now says "Pick one or more · Press 1–N to pick", in the mockup's words,
and each row has a check box that ticks when picked. Help says the same.

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

* style(chat): format the read-only open actions list so the web format check passes

* wip(chat): next moves (W2-02, in progress)

* fix(chat): keep Chat on at the AI limit on the workspace's own key, and read the usage again after each run

The composer turned off whenever the allowance was used up, but Chat on
the workspace's own key never draws on it (the server's hold writes those
steps unchecked), so a workspace with its own key could not send at all.
The page now reads whether Chat runs on the workspace's own key, as the
server picks it, and keeps the composer on then.

The meter, the 80% line and the pause also read the usage again once a
run stops working, so they follow the chat's own spending without a
page change. One read per run, no timer.

* fix(chat): name the run's own brand in the page context, and keep its block closed

The brand chip a message carries is now the run's own brand (the chat's,
checked against the workspace), not the posted label and id; it goes when
the run has no brand. The page context reaches the models with < and > as
JSON escapes, so a label can't end the block, and a reference's scope is
capped at 8 entries.

* fix(chat): name only a known platform in Traffic's question, and the first Top action in Action Center's

AI Referral Traffic's suggestion now reads the platform the page can name,
as the summary line does, and none over all time, where there is no
previous period and every platform would read as a rise. Action Center's
"How do I finish" names the first of the Top actions as the card ranks
them; the list arrives unordered.

* fix(chat): set up the side panel's composer as Chat's pages set theirs up

The panel's setup read Full auto from the plan alone and left out whether
Chat runs on the workspace's own key. So a member whose Admin turned "Full
auto for members" off could pick a mode that then asks anyway, and the
panel paused at the AI limit on a workspace's own key. The layout now reads
the switch and the key (only with the new Chat on) and builds the setup with
the same composerSetupOf Chat's pages use, moved to lib/chat/composer-setup;
the panel passes fullAutoOffByAdmin and onOwnKey on to the composer.

* perf(chat): load the side panel's code the first time it opens

The layout imported the panel directly, so its thread, composer and run
views came with every app page, Chat on or off. The layout now puts a
small slot there that loads the panel the first time it opens and keeps
it after that.

* fix(chat): keep Back to the page off paths with dot segments

panelReturnOf accepted /dashboard/../… and its %2e form, which resolve
outside the dashboard or into Chat. Refuse a . or .. segment.

* fix(chat): stop a run that waits on a question, and take its answer as the person's

From the review of the question card:

- Stop while a question waits: Stop sits beside Send and Esc stops the run.
  The question is kept skipped and its step reads "Question skipped".
- The answer reaches the model as the person's own (from: 'the person'),
  and the system prompt says to follow it like their message, not as data.
- A change called in the same step as a question doesn't run (not_run).
  The model calls it again with the answer.
- An answer kept while the run stopped meanwhile is let go again (no new
  migration), so the question doesn't stay half answered.
- The question card:
  - Enter on Skip, Add or an option is that button's own.
  - Text in Other... counts without Add, up to 500 characters.
- Answering from the composer:
  - It sends text only: no files, @ data or chips.
  - The box takes up to 500 characters; a 400 says why.
  - The composer is free at once (the answer's stream isn't awaited).
- "1 of N" counts only the questions the run will ask.
- A typed option label matches regardless of case, spacing, accents or
  Turkish i.
- Questions are capped at 200 characters, the step label's length.
- Help: the card section, and "Answer in the box".

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

* feat(chat): suggest next moves under a finished answer, the first as the composer's ghost

This commit and the wip commit before it make up CHAT-07 §C.

- With its final answer, in the same model step, the model calls
  suggest_next_moves. A step with only that call ends the run without
  another model step.
- The moves are picked for the person's role and plan as they are now:
  - an Analyst, an Agency partner or a read-only workspace gets read moves
    only;
  - one move per kind and per prompt, three at most, ids masked.
- They are kept in chat_next_moves (00417) and sent as next_moves before
  run.finished. None after an error, a pause at the cap, a Stop, or while a
  question or a change waits.
- The page shows them as "Next moves" cards under the latest answer only
  (mockup #s-done). A click sends the prompt as the next message.
- The first move shows as the composer's ghost when it continues this run
  (ghost_ok). A teammate's shared chat shows none.
- loadChatThread brings them back after a reload.
- Help ("Next moves") and the preview page show them.

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

* wip(chat): prompt, topic and competitor writes (W2-06, in progress)

* feat(chat): add the agents API: create, version, triggers, lifecycle and Run now (W2-13)

Chat's agents (CHAT-21, CHAT-27 §E) on the server, behind CHAT_AGENTIC:

- /api/chat/agents: list (Mine, Workspace, Paused, Archived, search) and
  create a draft; /{id}: detail, change (a new immutable version whenever
  what the agent does changes; name, visibility, caps and triggers change
  on the agent), delete once archived; /{id}/activate, pause, resume,
  archive, restore, duplicate; /{id}/run (Run now); /{id}/runs.
- Roles as §K: Admins and Managers make and run agents, a Manager changes
  only their own, private agents for their owner and Admins, Analysts and
  Agency partners read; refusals carry the out-of-permission answer
  (CHAT-20 §4c) and an access.denied row. Workspace agents kept to Admins
  and Full auto off follow Settings › Chat.
- Plan gates: Full auto Growth+, engines the plan tracks, active agents
  and agent runs at once per plan (§M, approved as written).
- Triggers: 0–5 schedule, Signal, KPI or watch-rule triggers, validated;
  a schedule's next fire from a dependency-free RRULE subset in its zone.
- Run now queues a run per brand (one per click a minute, at most 3
  waiting), acting as the person; a slot is tried with
  chat_start_next_agent_run only once a driver exists (W2-16), so runs
  wait queued until then.
- AI use as shares only: each agent's share comes from the server's new
  GET /api/internal/chat/budget/agent-shares (chat_agent_usage_shares
  against the budget the server keeps), cached 5 minutes; no dollars reach
  the browser.
- Every write is gated by writeRefusal; every change and Run now goes to
  the Activity log with agent_id and agent_run_id.

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

* fix(chat): open an answer in the Content Editor as the answer shows it

An image in the answer goes into the draft as its alt text, and raw HTML
as its text, as the answer itself shows them; links stay, cleaned by the
draft's own sanitizing.

* fix(chat): show on a next move the text it sends, and keep only the last step's moves

From the review of next moves:

- A card shows the very prompt a click sends, never a label that could say
  something else. A page Chat read could otherwise dress a write up as "See
  the full report".
- Moves belong to the step they came with: they are cleared before each
  writing step, so a question, an answer and a last step without moves
  shows none.
- The tool takes the call whole (up to 6 moves, loose fields) and checks
  each move on its own (validMoves). A move too long or of an unknown kind
  loses only itself.
- A move whose label or prompt names a tool, or reads like one
  (snake_case), is dropped before it is kept.
- loadChatThread logs a failed read of the moves and opens the chat
  without them. A teammate's shared chat doesn't read them.
- In the side panel the cards stand one under another; two or three side by
  side on a page.
- Comment: ghost_ok is the model's word, not checked.
- Tests: moves that can't be kept, an error and a Stop after a step with
  moves.

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

* fix(chat): let a Stop after Approve win, and finish the who-may-do-what matrix

A Stop that comes after Approve, before the approved change runs, now
stops the run: in the same process the change no longer runs, and from
another process the card is closed with run.stopped instead of the run
staying stopped with its step still waiting.

The matrix's test-only EXECUTE row is Admin and Manager work, as in
precedence.test, and the matrix now covers every change row, Analysts'
and Agency partners' own changes in each mode, their refused go-live,
a teammate answering someone else's card, a click refused after the
Admin turned publishing off, and the demo brand for every role.

* fix(chat): show Admins every agent, keep triggers across saves, and add Take over (W2-13)

Review fixes on the agents API:

- Workspace tab: an Admin sees every agent in use, others' private ones
  included (CHAT-21 §K, edge case 1); the counts follow.
- Triggers are matched with their keys sorted (canonicalJson): jsonb's
  key order no longer makes a KPI, Signal or one-off trigger look new, so
  its last fire and cooldown stay.
- Only a new or changed trigger is held to the clock: a one-off that
  already fired can come back with a save.
- Run now claims an idempotency key (agent, brand, person, minute), so two
  clicks at once queue one run; a run counted past the 3 waiting after its
  insert goes again and joins the last.
- POST /api/chat/agents/{id}/take-over: an Admin becomes the owner; an
  agent that is on, or paused because of its owner, passes the activation
  checks under them first and comes back on; logged.
- Duplicate is held to create's checks (mode, engines, brands, topics,
  people).
- The internal budget endpoints compare CRON_SECRET in constant time
  (webhookSecretsMatch).
- Tests for another workspace's or a teammate's private agent (404).

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

* fix(chat): keep a long answer's or chat's PDF within the route's time

react-pdf's layout time grows with the square of the length: 2,000 table
rows took about 60 s and 6,000 rows about 4 minutes, and Export chat joins
every answer of a chat. A PDF now lays out 1,000 rows and blocks at most
and ends with a line saying so (Markdown and Word keep all of it), and
both export routes get maxDuration 300.

Also matches the downloaded body in the answer bar's test by its size:
fetch's Blob is Node's, not the test page's.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): track prompts, topics and competitors from Chat, with Undo

This commit and the wip commit before it make up W2-06 (CHAT-20 §9 rows 20–32).

New WRITE rows, one registry file per area:
- add_prompts: prompts in one of the brand's topics, topic first.
- pause_prompts: the spec's "archive"; the app pauses, history kept.
- add_topic, rename_topic.
- add_competitors, remove_competitor (always a card).

How they run:
- Admins and Managers, as the app (00382, #1762). Others get the
  structured refusal.
- Each calls a thin server action over the app's own:
  - addTopicPrompts runs through importPrompts: the plan's prompt
    locations, duplicates skipped, first run started.
  - pauseBrandPrompts, addBrandTopic, addCompetitors and
    removeBrandCompetitor each check the brand and skip natural-key
    duplicates.
- Every one checks the read-only workspace first.

Undo for each (undo-setup.ts), 7 days, 30 for paused prompts. Anything
changed since is left alone (undo_conflict). Resuming paused prompts checks
the plan's room again.

Registry and engine:
- A row may name its batch: the run's caps count items (50 prompts, 5
  competitors), and more than 5 prompts paused at once always shows a card
  (overBatch).
- A row may name its card's target from the data: the topic, the prompts,
  the competitor.
- A refusal the person can act on (quota_exceeded, duplicate, not_found,
  invalid) shows the action's words on the step and gives the model its
  §11a code.
- An action's { ok: false } refusal is no longer logged as a change.

Help: chat.md "Change what you track".

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

* fix(chat): let a Stop right after an answer win, and keep a question the run never went on with as skipped

The answer branch of resumePending now checks for a Stop before taking the
answer up, as an approved change does. A stopped run's open question is kept
as skipped even when its answer was kept just before the Stop, and an answer
whose run ended before it was taken back is kept as skipped rather than
cleared. Tests: Stop after an answer in this process and in another, the
run-ended-meanwhile case, and a teammate's answer, skip and stop on a shared
chat.

* wip(chat): content, report and audit writes (W2-07, in progress)

* chore: no changes; push again so GitHub picks up the merged fixes

* fix(chat): start a run from a tainted run's next move tainted, and drop moves that carry a link

* fix(chat): hold a change to someone else's agent to its owner's mode, and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since its triggered runs act a…
gkhngyk added a commit that referenced this pull request Oct 31, 2026
…part (#1882)

* fix(prompts): ask for a topic before adding prompts or generating suggestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (#1763, #1769) is unchanged.

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

* fix(prompts): add a topic in place on the Prompts page, and say why suggestions failed

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since #1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as #1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

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

* docs(help): say a brand adds a topic before its prompts

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

* feat(chat): add Wave 1's tables for sharing, settings, attachments, Files, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

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

* feat(chat): export an answer as Markdown, Word, PDF, CSV or Excel

CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

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

* feat(chat): open Chat at /dashboard/chat and add its chats API

Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (#1812 note).
- Help: a "chat" area and its first article (approved: false).

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

* feat(chat): add the chat menu with Agents at work, day groups and Ctrl+\

Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, #1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

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

* feat(chat): add the chat ⋯ menus: pin, rename, share, archive and delete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

* fix(chat): read a shared chat's author with the server's client for their initials

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

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

* feat(chat): add Chat Home's greeting, the Inbox and the due-tasks line

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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

* feat(chat): add the composer, with send, Stop and steering, run modes and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

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

* feat(chat): add context chips and the Tab ghost suggestion to the composer

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

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

* feat(chat): add the composer's / @ and + menus, with a reference search

Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

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

* feat(chat): show a run's work live under its answer, with step chips, Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

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

* feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

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

* feat(chat): wire the composer and the live answer into Chat's pages

Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

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

* feat(chat): show the AI usage under Chat's composer, say 80% once, and pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf36).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

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

* feat(chat): copy Agent Chat's conversations into Chat on the first visit

On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

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

* feat(chat): add Search chats, the Ctrl K palette and the All chats page

Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

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

* feat(chat): add Chat Settings › General, Back to Chat and the app rail beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

* feat(chat): add Chat's side panel to every app page with Ask Chat and Ctrl J

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

* test(chat): name why your own chats' routes stay open on a read-only workspace

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

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

* test(chat): name why saving your own Chat menu state stays open on a read-only workspace

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

* test(chat): name why editing your own chat stays open on a read-only workspace

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

* test(chat): name why saving your own Chat settings and rail stays open on a read-only workspace

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

* fix(chat): keep the 80% usage line on the person, once per period on every device

The line above Chat's composer at 80% of the AI usage was kept closed per
browser. It now shows once per person per usage period (CHAT-04 item 16):
the first time it shows, its period goes to chat_user_prefs.usage_notice_period
(00408) through saveUsageNoticePeriod, and the Chat pages read it with the
composer's setup; × still closes it on the page.

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

* feat(chat): show the page's context as chips in the side panel, with Ask about this

The side panel's box starts with chips for what the page shows: its
name (the menu's when the page says nothing), the brand, the date range
and filters (CHAT-01 item 20). They follow the page while the panel is
open; × keeps one off until New chat. Pages tell the panel through
useChatPageContext, which reads a setter-only context so a page never
renders again for the panel. The empty panel offers up to three of the
page's questions, which fill the box unsent (item 21), and Ask about this
opens the panel with a chart or table attached as an @ chip (item 22).
The chips and @ objects go with the message: the engine keeps them on
chat_messages.context_json and gives them to the models as a data block,
the run's default scope (CHAT-04 item 8). Mentions & Sentiment is the
first page with its dates, filters, questions and two Ask about this
icons.

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

* feat(chat): give Brand Visibility, Citations, Prompts, Action Center, Traffic and Content their page context

Each page now tells Chat's side panel what it shows (W1-08's
useChatPageContext): its name, date range and filters as chips, and up to
three questions, one of them from data the page already loaded where it
has some (the platform whose visibility or visits moved most, the source
cited most, a tracked prompt the brand doesn't show up for, the top
action, a high-impact opportunity), without a model call. Ask about this
is on Brand Visibility's platform table and leaderboard, Citations' Top
Sources, Traffic's two tables, each tracked prompt and each Action Center
action; on a row it opens the panel, not the row.

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

* feat(chat): add the side panel's ⋯ menu, Open as full page and Back to the page

Once the panel has a chat, its ⋯ (CHAT-23 panel.more) offers Open as full
page, Open in new window, and for the author Pin, Rename (in the panel's
title), Share with team, Archive and Delete, the chat menus' own actions.
ChatActionsProvider tells a page outside the shell of a chat's new row
and of one archived or deleted, which empties the panel. Open as full
page goes to the chat on Chat's page with ?from= the page and its query;
the full page then shows ↙ Back to {page} (CHAT-22), only for a dashboard
page outside Chat. Back on a page, a panel that was away reads its chat
again, so it shows what happened on the full page.

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

* fix(chat): read the full page's search params at the top of the shell

Calling useSearchParams inside an expression kept the React Compiler from
preserving the shell's memoized callbacks (lint: preserve-manual-memoization).

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

* feat(chat): name the app page a side panel chat started on

A chat the side panel starts now keeps origin 'panel' and the page's path
in origin_page (CHAT-01 data notes); Chat's own page keeps 'page' and
/dashboard/chat. The engine takes origin and originPage with the first
message; a page it can't name is left out and the message still goes.
The path check is shared with POST /api/chat/conversations
(lib/chat/origin.ts).

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

* feat(chat): copy, download or save an answer to Files, and export a chat

Every finished answer gets an icon bar (CHAT-06 items 30–37): Copy (rich
text), Download as Markdown, Word or PDF, and CSV or Excel when it has a
table, rendered on the server from the stored answer with its time line
(GET /api/chat/runs/{id}/export, W1-24's writers), and Save to Files,
once per answer, then "In Files" (POST /api/chat/runs/{id}/file). Filing
goes through fileChatOutput, which run deliverables will use as they are
made: a row in chat_files and its content in chat-files, counted toward
storage, refused once a workspace is full. Storage per plan comes from
the spec: Starter 5 GB, Growth 25 GB, Enterprise 99 GB or its contract
(plan_overrides.maxStorageGb), 1 GB in the free trial, plus active
storage packs; self-host has no cap. Export chat in a chat's ⋯ menu now
downloads the whole chat as Markdown, Word or PDF. The PDF routes carry
public/fonts and keep @react-pdf/renderer outside the server bundle for
Vercel. The time line's words move to lib/chat/stamp for the server.

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

* fix(chat): keep a long answer's PDF from failing past ten pages

With the line height set on the page, react-pdf's page number threw
"unsupported number" once the PDF passed ten pages, so any long answer
failed to export. The line height now sits on the body text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): show what a run made as output cards and open answers in the Content Editor

- A write that makes something (create_draft's page) files it in Files as
  it is made and shows it under the answer as an output card: its type,
  title, "In Files" / "Used in Content draft" or "Not saved to Files ·
  Storage is full", Copy, Download in the formats it offers and Open in
  Content Editor (CHAT-06 items 1-6, 9, 29).
- Open in Content Editor on an answer's bar makes a Content draft of the
  answer in the chat's brand (else the brand open) and opens it.
- Files' pages download as HTML, Markdown, Word and PDF on the server: the
  Content Editor's writers run with a jsdom window (lib/content/server-dom).
- A reopened chat shows its output cards and filed answers again.

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

* fix(chat): keep the focus in the composer when a chip is removed

The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): add the Files page with filters, downloads, Download selected and the storage meter

- /dashboard/chat/files lists the workspace's files newest first, 50 at a
  time with Show more: name and formats ("Used in Content draft"), Made by
  (You, a teammate, Agent, Scheduled), From chat (only chats the person can
  open), and the generated time with "Data as of" (CHAT-06 items 12, 16-17).
- Chips All (with the workspace's count), Drafts, Reports, Code, Tables,
  Images, From me, From agents, and "Filter by name..." over the search
  column; "No files match." with Clear filters.
- Each row has Copy (Markdown), Open (its Content draft) and Download in
  the formats it offers. Picked rows download as one .zip in their main
  formats, up to 50 files and 100 MB (items 18-19).
- The storage meter ("Storage 2.1 of 25 GB", amber from 80%) and a line
  once storage is full, with no Get more until the plan rules are set
  (items 26-29).
- GET /api/chat/files, GET /api/chat/files/{id}, POST /api/chat/files/zip
  (reads only). Files sits under Settings in the chat menu, in the Ctrl K
  palette and in the breadcrumb.
- Help: help/chat/files.md (new).

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

* fix(chat): keep Agents at work to the person's own chats, and read the clock with each list read

A teammate's shared chat that waits on its author's OK no longer shows under
Agents at work or in Home's count. A chat that waits on an OK or is paused no
longer keeps the list on the 5 s pace. A menu left open past midnight now
moves Today's chats to Yesterday on the next list read.

* fix(chat): show a teammate's initials on a shared chat

A person reads only their own profile, so the author's name came back
empty on every teammate's shared chat. Read it on the server, within the
workspace; only the initials leave.

* fix(chat): keep a teammate's shared chat out of the Inbox and Home's count

A shared chat that waits for approval waits on its author, who alone can
answer it. The Inbox, its counts in the menu and the strip, and Home's
"things need you" now count the person's own chats only.

* fix(chat): read a * in the @ search as a space, not a wildcard

PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* style(chat): format the read-only open routes list so the web format check passes

* fix(chat): style answers as the app's other AI answers, take hand-made brand ids, and keep Files' draft line whole

From the W1-25…27 preview:
- A Chat answer's Markdown gets the prose styles the Mentions drawer and
  the response detail use (prose prose-sm dark:prose-invert max-w-none):
  headings, lists and table cells, in both themes.
- Starting a chat with a brand (createInput) and Chat Home's due-actions
  line take the demo brand's id with z.guid(): it is made by hand, not an
  RFC 4122 uuid (as #1849 did for starting a run).
- On Files, "Used in Content draft" has its own line under the formats,
  so a 1024px table no longer cuts it off.

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

* test(chat): check who may do what through the engine, role by class by mode (W1-22)

CHAT-05 test set 27–30 and CHAT-20 §4c, §5 end to end, with a scripted
model and the in-memory database:
- Each role is offered only the changes its role allows, and the
  explainer when something is left out.
- Every role reads in every mode with no card.
- A change waits on its card in Ask me first and Auto. Full auto runs it
  for an Admin, and for a Manager only while members may.
- Full auto stays on Growth and up, paid: Starter and the trial get the
  card, and Enterprise's trial runs.
- An Analyst and an Agency partner get the four-part refusal in every
  mode. Nothing changes, and each refusal is logged with its rule.
- An EXECUTE never runs without the click; a Manager the Admin turned
  publishing off for is refused by policy.
- A role lowered while the card waits refuses the approval.

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

* fix(chat): don't offer Admins the request to the Admins

Admins have no one to ask (CHAT-20 access table: "not needed"): the model
was offered request_access for them, so it could put up a card the server
then turned away. The engine now neither offers it to an Admin nor lists it
among what they can't do. The row keeps every role: defineTool never
leaves an Admin out of a row, by design.

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

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

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

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

* fix(chat): clean the pages Chat files, number output cards by their files, copy as Safari allows

From the pre-push review of W1-25…27:
- create_draft's page goes to Files as the draft keeps it, through
  sanitizeDraftHtml, and Files' HTML download cleans it again: a page Chat
  read can't slip a script or an event handler into a download (CHAT-06:
  no script in exported HTML).
- An output card's file is its place among the run's filed outputs, as
  the server counts them. A card that wasn't filed (storage full, failed)
  no longer shifts the next card onto another page's file.
- Copy on an output card writes a clipboard item within the click, its
  text to come (Safari refuses a write after an await), and says when it
  can't.
- A reopened chat's output cards mask ids in their titles, as the live
  events do.

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

* fix(chat): stream Download selected, copy Files rows as Safari allows, and say what a full workspace keeps

From the pre-push review of W1-25…27:
- Download selected streams the .zip as it is made (fflate's Zip): one
  file read, written and compressed at a time as the reader asks for
  more, so neither the files nor the .zip are held whole, and a .zip past
  a function's body cap still goes out. The limits stay: 50 files, 100 MB
  stored, checked before anything is read.
- Copy on a Files row writes a clipboard item within the click, its text
  to come (Safari refuses a write after an await), and says when it can't.
- Help: with storage full, an output's card can't copy or download it (it
  has no file); the answer above it still can.

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

* fix(chat): keep Data used to "Read …" steps, and plain links in the answer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): send an attachment with its type, and call it ready only when its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): keep a copied Agent Chat thread in its order

Agent Chat wrote a conversation's whole thread again on every turn in one
insert, so its messages share one created_at and their ids don't follow
the order. The copy read them by created_at then id, which shuffled them,
and Chat reads a chat by created_at alone. Read each conversation the way
Agent Chat's own page did (by created_at, no tiebreak) and give the copies
a strictly rising created_at, a millisecond apart where they tied.

Also cut a long title or message without splitting an emoji in half.

* fix(chat): open Full auto in the composer only where the server runs it, and steer only after Stop is taken

The composer's Full auto now follows the same facts the approval check uses:
the plan, and for anyone but an Admin the Admin's Full auto for members
switch. When the switch closes it, the mode says Off by Admin rather than
Needs Growth. Steering sends the new message only once the Stop is taken;
otherwise the text stays in the box.

* fix(chat): find a domain, a number or an email address in Search chats

Each word goes to Postgres quoted, so it splits it the way it split the
text: "nike.com", "4.5" or an address is one token there and is now
found whole, and Postgres lowercases it itself.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): tie a step's hold to its chat's agent run and keep paused runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

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

* test(chat): give the test's EXECUTE row its words, assert approvals before driving, and cover an Admin's request

From the pre-push review of W1-22:
- publish_page, the test's own EXECUTE row, gets its words through a mock
  of the messages (the product has no such tool yet), so no
  MISSING_MESSAGE trace prints. The publishing refusal's "asked" is now
  checked.
- Approvals are asserted before the run is driven on, so a refused one
  fails the test instead of passing quietly. The approve helper returns
  a refusal for its callers to check.
- An Admin's call to request_access, which they aren't offered, is turned
  away: no card, no request. The row's comment says how Admins are kept
  out.

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

* feat(chat): pause a run on a question card and go on with the answer

The write phase can call ask_question: 2-4 options, exactly one
Recommended. The run waits on an `ask` step and its chat_asks row, with no
model call. POST /api/chat/runs/{id}/answer keeps the answer once (409 when
already answered, 400 when it doesn't fit, 402 while read-only) and the run
goes on.

- Skip goes on with the Recommended option.
- Stop keeps open questions as skipped.
- A run asks at most 4.
- Questions asked together show "1 of 2", then "2 of 2".
- A message from the composer answers the question, and the rest of its
  batch.

QuestionCard (number keys, Enter = Next, Other..., multi, read-only gate)
and its folded line; the composer's ghost shows the Recommended option.
Help and the preview page show it.

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

* fix(chat): say when a question card takes several answers

A question with several picks looked like a one-pick question. Its footer
now says "Pick one or more · Press 1–N to pick", in the mockup's words,
and each row has a check box that ticks when picked. Help says the same.

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

* style(chat): format the read-only open actions list so the web format check passes

* wip(chat): next moves (W2-02, in progress)

* fix(chat): keep Chat on at the AI limit on the workspace's own key, and read the usage again after each run

The composer turned off whenever the allowance was used up, but Chat on
the workspace's own key never draws on it (the server's hold writes those
steps unchecked), so a workspace with its own key could not send at all.
The page now reads whether Chat runs on the workspace's own key, as the
server picks it, and keeps the composer on then.

The meter, the 80% line and the pause also read the usage again once a
run stops working, so they follow the chat's own spending without a
page change. One read per run, no timer.

* fix(chat): name the run's own brand in the page context, and keep its block closed

The brand chip a message carries is now the run's own brand (the chat's,
checked against the workspace), not the posted label and id; it goes when
the run has no brand. The page context reaches the models with < and > as
JSON escapes, so a label can't end the block, and a reference's scope is
capped at 8 entries.

* fix(chat): name only a known platform in Traffic's question, and the first Top action in Action Center's

AI Referral Traffic's suggestion now reads the platform the page can name,
as the summary line does, and none over all time, where there is no
previous period and every platform would read as a rise. Action Center's
"How do I finish" names the first of the Top actions as the card ranks
them; the list arrives unordered.

* fix(chat): set up the side panel's composer as Chat's pages set theirs up

The panel's setup read Full auto from the plan alone and left out whether
Chat runs on the workspace's own key. So a member whose Admin turned "Full
auto for members" off could pick a mode that then asks anyway, and the
panel paused at the AI limit on a workspace's own key. The layout now reads
the switch and the key (only with the new Chat on) and builds the setup with
the same composerSetupOf Chat's pages use, moved to lib/chat/composer-setup;
the panel passes fullAutoOffByAdmin and onOwnKey on to the composer.

* perf(chat): load the side panel's code the first time it opens

The layout imported the panel directly, so its thread, composer and run
views came with every app page, Chat on or off. The layout now puts a
small slot there that loads the panel the first time it opens and keeps
it after that.

* fix(chat): keep Back to the page off paths with dot segments

panelReturnOf accepted /dashboard/../… and its %2e form, which resolve
outside the dashboard or into Chat. Refuse a . or .. segment.

* fix(chat): stop a run that waits on a question, and take its answer as the person's

From the review of the question card:

- Stop while a question waits: Stop sits beside Send and Esc stops the run.
  The question is kept skipped and its step reads "Question skipped".
- The answer reaches the model as the person's own (from: 'the person'),
  and the system prompt says to follow it like their message, not as data.
- A change called in the same step as a question doesn't run (not_run).
  The model calls it again with the answer.
- An answer kept while the run stopped meanwhile is let go again (no new
  migration), so the question doesn't stay half answered.
- The question card:
  - Enter on Skip, Add or an option is that button's own.
  - Text in Other... counts without Add, up to 500 characters.
- Answering from the composer:
  - It sends text only: no files, @ data or chips.
  - The box takes up to 500 characters; a 400 says why.
  - The composer is free at once (the answer's stream isn't awaited).
- "1 of N" counts only the questions the run will ask.
- A typed option label matches regardless of case, spacing, accents or
  Turkish i.
- Questions are capped at 200 characters, the step label's length.
- Help: the card section, and "Answer in the box".

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

* feat(chat): suggest next moves under a finished answer, the first as the composer's ghost

This commit and the wip commit before it make up CHAT-07 §C.

- With its final answer, in the same model step, the model calls
  suggest_next_moves. A step with only that call ends the run without
  another model step.
- The moves are picked for the person's role and plan as they are now:
  - an Analyst, an Agency partner or a read-only workspace gets read moves
    only;
  - one move per kind and per prompt, three at most, ids masked.
- They are kept in chat_next_moves (00417) and sent as next_moves before
  run.finished. None after an error, a pause at the cap, a Stop, or while a
  question or a change waits.
- The page shows them as "Next moves" cards under the latest answer only
  (mockup #s-done). A click sends the prompt as the next message.
- The first move shows as the composer's ghost when it continues this run
  (ghost_ok). A teammate's shared chat shows none.
- loadChatThread brings them back after a reload.
- Help ("Next moves") and the preview page show them.

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

* wip(chat): prompt, topic and competitor writes (W2-06, in progress)

* feat(chat): add the agents API: create, version, triggers, lifecycle and Run now (W2-13)

Chat's agents (CHAT-21, CHAT-27 §E) on the server, behind CHAT_AGENTIC:

- /api/chat/agents: list (Mine, Workspace, Paused, Archived, search) and
  create a draft; /{id}: detail, change (a new immutable version whenever
  what the agent does changes; name, visibility, caps and triggers change
  on the agent), delete once archived; /{id}/activate, pause, resume,
  archive, restore, duplicate; /{id}/run (Run now); /{id}/runs.
- Roles as §K: Admins and Managers make and run agents, a Manager changes
  only their own, private agents for their owner and Admins, Analysts and
  Agency partners read; refusals carry the out-of-permission answer
  (CHAT-20 §4c) and an access.denied row. Workspace agents kept to Admins
  and Full auto off follow Settings › Chat.
- Plan gates: Full auto Growth+, engines the plan tracks, active agents
  and agent runs at once per plan (§M, approved as written).
- Triggers: 0–5 schedule, Signal, KPI or watch-rule triggers, validated;
  a schedule's next fire from a dependency-free RRULE subset in its zone.
- Run now queues a run per brand (one per click a minute, at most 3
  waiting), acting as the person; a slot is tried with
  chat_start_next_agent_run only once a driver exists (W2-16), so runs
  wait queued until then.
- AI use as shares only: each agent's share comes from the server's new
  GET /api/internal/chat/budget/agent-shares (chat_agent_usage_shares
  against the budget the server keeps), cached 5 minutes; no dollars reach
  the browser.
- Every write is gated by writeRefusal; every change and Run now goes to
  the Activity log with agent_id and agent_run_id.

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

* fix(chat): open an answer in the Content Editor as the answer shows it

An image in the answer goes into the draft as its alt text, and raw HTML
as its text, as the answer itself shows them; links stay, cleaned by the
draft's own sanitizing.

* fix(chat): show on a next move the text it sends, and keep only the last step's moves

From the review of next moves:

- A card shows the very prompt a click sends, never a label that could say
  something else. A page Chat read could otherwise dress a write up as "See
  the full report".
- Moves belong to the step they came with: they are cleared before each
  writing step, so a question, an answer and a last step without moves
  shows none.
- The tool takes the call whole (up to 6 moves, loose fields) and checks
  each move on its own (validMoves). A move too long or of an unknown kind
  loses only itself.
- A move whose label or prompt names a tool, or reads like one
  (snake_case), is dropped before it is kept.
- loadChatThread logs a failed read of the moves and opens the chat
  without them. A teammate's shared chat doesn't read them.
- In the side panel the cards stand one under another; two or three side by
  side on a page.
- Comment: ghost_ok is the model's word, not checked.
- Tests: moves that can't be kept, an error and a Stop after a step with
  moves.

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

* fix(chat): let a Stop after Approve win, and finish the who-may-do-what matrix

A Stop that comes after Approve, before the approved change runs, now
stops the run: in the same process the change no longer runs, and from
another process the card is closed with run.stopped instead of the run
staying stopped with its step still waiting.

The matrix's test-only EXECUTE row is Admin and Manager work, as in
precedence.test, and the matrix now covers every change row, Analysts'
and Agency partners' own changes in each mode, their refused go-live,
a teammate answering someone else's card, a click refused after the
Admin turned publishing off, and the demo brand for every role.

* fix(chat): show Admins every agent, keep triggers across saves, and add Take over (W2-13)

Review fixes on the agents API:

- Workspace tab: an Admin sees every agent in use, others' private ones
  included (CHAT-21 §K, edge case 1); the counts follow.
- Triggers are matched with their keys sorted (canonicalJson): jsonb's
  key order no longer makes a KPI, Signal or one-off trigger look new, so
  its last fire and cooldown stay.
- Only a new or changed trigger is held to the clock: a one-off that
  already fired can come back with a save.
- Run now claims an idempotency key (agent, brand, person, minute), so two
  clicks at once queue one run; a run counted past the 3 waiting after its
  insert goes again and joins the last.
- POST /api/chat/agents/{id}/take-over: an Admin becomes the owner; an
  agent that is on, or paused because of its owner, passes the activation
  checks under them first and comes back on; logged.
- Duplicate is held to create's checks (mode, engines, brands, topics,
  people).
- The internal budget endpoints compare CRON_SECRET in constant time
  (webhookSecretsMatch).
- Tests for another workspace's or a teammate's private agent (404).

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

* fix(chat): keep a long answer's or chat's PDF within the route's time

react-pdf's layout time grows with the square of the length: 2,000 table
rows took about 60 s and 6,000 rows about 4 minutes, and Export chat joins
every answer of a chat. A PDF now lays out 1,000 rows and blocks at most
and ends with a line saying so (Markdown and Word keep all of it), and
both export routes get maxDuration 300.

Also matches the downloaded body in the answer bar's test by its size:
fetch's Blob is Node's, not the test page's.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): track prompts, topics and competitors from Chat, with Undo

This commit and the wip commit before it make up W2-06 (CHAT-20 §9 rows 20–32).

New WRITE rows, one registry file per area:
- add_prompts: prompts in one of the brand's topics, topic first.
- pause_prompts: the spec's "archive"; the app pauses, history kept.
- add_topic, rename_topic.
- add_competitors, remove_competitor (always a card).

How they run:
- Admins and Managers, as the app (00382, #1762). Others get the
  structured refusal.
- Each calls a thin server action over the app's own:
  - addTopicPrompts runs through importPrompts: the plan's prompt
    locations, duplicates skipped, first run started.
  - pauseBrandPrompts, addBrandTopic, addCompetitors and
    removeBrandCompetitor each check the brand and skip natural-key
    duplicates.
- Every one checks the read-only workspace first.

Undo for each (undo-setup.ts), 7 days, 30 for paused prompts. Anything
changed since is left alone (undo_conflict). Resuming paused prompts checks
the plan's room again.

Registry and engine:
- A row may name its batch: the run's caps count items (50 prompts, 5
  competitors), and more than 5 prompts paused at once always shows a card
  (overBatch).
- A row may name its card's target from the data: the topic, the prompts,
  the competitor.
- A refusal the person can act on (quota_exceeded, duplicate, not_found,
  invalid) shows the action's words on the step and gives the model its
  §11a code.
- An action's { ok: false } refusal is no longer logged as a change.

Help: chat.md "Change what you track".

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

* fix(chat): let a Stop right after an answer win, and keep a question the run never went on with as skipped

The answer branch of resumePending now checks for a Stop before taking the
answer up, as an approved change does. A stopped run's open question is kept
as skipped even when its answer was kept just before the Stop, and an answer
whose run ended before it was taken back is kept as skipped rather than
cleared. Tests: Stop after an answer in this process and in another, the
run-ended-meanwhile case, and a teammate's answer, skip and stop on a shared
chat.

* wip(chat): content, report and audit writes (W2-07, in progress)

* chore: no changes; push again so GitHub picks up the merged fixes

* fix(chat): start a run from a tainted run's next move tainted, and drop moves that carry a link

* fix(chat): hold a change to someone else's agent to its owner's mode, and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since its triggered runs act as th…
gkhngyk added a commit that referenced this pull request Oct 31, 2026
…hat moved since you left (W2-19) (#1890)

* fix(prompts): ask for a topic before adding prompts or generating suggestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (#1763, #1769) is unchanged.

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

* fix(prompts): add a topic in place on the Prompts page, and say why suggestions failed

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since #1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as #1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

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

* docs(help): say a brand adds a topic before its prompts

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

* feat(chat): add Wave 1's tables for sharing, settings, attachments, Files, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

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

* feat(chat): export an answer as Markdown, Word, PDF, CSV or Excel

CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

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

* feat(chat): open Chat at /dashboard/chat and add its chats API

Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (#1812 note).
- Help: a "chat" area and its first article (approved: false).

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

* feat(chat): add the chat menu with Agents at work, day groups and Ctrl+\

Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, #1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

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

* feat(chat): add the chat ⋯ menus: pin, rename, share, archive and delete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

* fix(chat): read a shared chat's author with the server's client for their initials

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

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

* feat(chat): add Chat Home's greeting, the Inbox and the due-tasks line

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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

* feat(chat): add the composer, with send, Stop and steering, run modes and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

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

* feat(chat): add context chips and the Tab ghost suggestion to the composer

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

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

* feat(chat): add the composer's / @ and + menus, with a reference search

Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

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

* feat(chat): show a run's work live under its answer, with step chips, Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

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

* feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

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

* feat(chat): wire the composer and the live answer into Chat's pages

Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

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

* feat(chat): show the AI usage under Chat's composer, say 80% once, and pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf36).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

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

* feat(chat): copy Agent Chat's conversations into Chat on the first visit

On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

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

* feat(chat): add Search chats, the Ctrl K palette and the All chats page

Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

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

* feat(chat): add Chat Settings › General, Back to Chat and the app rail beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

* feat(chat): add Chat's side panel to every app page with Ask Chat and Ctrl J

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

* test(chat): name why your own chats' routes stay open on a read-only workspace

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

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

* test(chat): name why saving your own Chat menu state stays open on a read-only workspace

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

* test(chat): name why editing your own chat stays open on a read-only workspace

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

* test(chat): name why saving your own Chat settings and rail stays open on a read-only workspace

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

* fix(chat): keep the 80% usage line on the person, once per period on every device

The line above Chat's composer at 80% of the AI usage was kept closed per
browser. It now shows once per person per usage period (CHAT-04 item 16):
the first time it shows, its period goes to chat_user_prefs.usage_notice_period
(00408) through saveUsageNoticePeriod, and the Chat pages read it with the
composer's setup; × still closes it on the page.

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

* feat(chat): show the page's context as chips in the side panel, with Ask about this

The side panel's box starts with chips for what the page shows: its
name (the menu's when the page says nothing), the brand, the date range
and filters (CHAT-01 item 20). They follow the page while the panel is
open; × keeps one off until New chat. Pages tell the panel through
useChatPageContext, which reads a setter-only context so a page never
renders again for the panel. The empty panel offers up to three of the
page's questions, which fill the box unsent (item 21), and Ask about this
opens the panel with a chart or table attached as an @ chip (item 22).
The chips and @ objects go with the message: the engine keeps them on
chat_messages.context_json and gives them to the models as a data block,
the run's default scope (CHAT-04 item 8). Mentions & Sentiment is the
first page with its dates, filters, questions and two Ask about this
icons.

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

* feat(chat): give Brand Visibility, Citations, Prompts, Action Center, Traffic and Content their page context

Each page now tells Chat's side panel what it shows (W1-08's
useChatPageContext): its name, date range and filters as chips, and up to
three questions, one of them from data the page already loaded where it
has some (the platform whose visibility or visits moved most, the source
cited most, a tracked prompt the brand doesn't show up for, the top
action, a high-impact opportunity), without a model call. Ask about this
is on Brand Visibility's platform table and leaderboard, Citations' Top
Sources, Traffic's two tables, each tracked prompt and each Action Center
action; on a row it opens the panel, not the row.

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

* feat(chat): add the side panel's ⋯ menu, Open as full page and Back to the page

Once the panel has a chat, its ⋯ (CHAT-23 panel.more) offers Open as full
page, Open in new window, and for the author Pin, Rename (in the panel's
title), Share with team, Archive and Delete, the chat menus' own actions.
ChatActionsProvider tells a page outside the shell of a chat's new row
and of one archived or deleted, which empties the panel. Open as full
page goes to the chat on Chat's page with ?from= the page and its query;
the full page then shows ↙ Back to {page} (CHAT-22), only for a dashboard
page outside Chat. Back on a page, a panel that was away reads its chat
again, so it shows what happened on the full page.

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

* fix(chat): read the full page's search params at the top of the shell

Calling useSearchParams inside an expression kept the React Compiler from
preserving the shell's memoized callbacks (lint: preserve-manual-memoization).

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

* feat(chat): name the app page a side panel chat started on

A chat the side panel starts now keeps origin 'panel' and the page's path
in origin_page (CHAT-01 data notes); Chat's own page keeps 'page' and
/dashboard/chat. The engine takes origin and originPage with the first
message; a page it can't name is left out and the message still goes.
The path check is shared with POST /api/chat/conversations
(lib/chat/origin.ts).

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

* feat(chat): copy, download or save an answer to Files, and export a chat

Every finished answer gets an icon bar (CHAT-06 items 30–37): Copy (rich
text), Download as Markdown, Word or PDF, and CSV or Excel when it has a
table, rendered on the server from the stored answer with its time line
(GET /api/chat/runs/{id}/export, W1-24's writers), and Save to Files,
once per answer, then "In Files" (POST /api/chat/runs/{id}/file). Filing
goes through fileChatOutput, which run deliverables will use as they are
made: a row in chat_files and its content in chat-files, counted toward
storage, refused once a workspace is full. Storage per plan comes from
the spec: Starter 5 GB, Growth 25 GB, Enterprise 99 GB or its contract
(plan_overrides.maxStorageGb), 1 GB in the free trial, plus active
storage packs; self-host has no cap. Export chat in a chat's ⋯ menu now
downloads the whole chat as Markdown, Word or PDF. The PDF routes carry
public/fonts and keep @react-pdf/renderer outside the server bundle for
Vercel. The time line's words move to lib/chat/stamp for the server.

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

* fix(chat): keep a long answer's PDF from failing past ten pages

With the line height set on the page, react-pdf's page number threw
"unsupported number" once the PDF passed ten pages, so any long answer
failed to export. The line height now sits on the body text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): show what a run made as output cards and open answers in the Content Editor

- A write that makes something (create_draft's page) files it in Files as
  it is made and shows it under the answer as an output card: its type,
  title, "In Files" / "Used in Content draft" or "Not saved to Files ·
  Storage is full", Copy, Download in the formats it offers and Open in
  Content Editor (CHAT-06 items 1-6, 9, 29).
- Open in Content Editor on an answer's bar makes a Content draft of the
  answer in the chat's brand (else the brand open) and opens it.
- Files' pages download as HTML, Markdown, Word and PDF on the server: the
  Content Editor's writers run with a jsdom window (lib/content/server-dom).
- A reopened chat shows its output cards and filed answers again.

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

* fix(chat): keep the focus in the composer when a chip is removed

The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): add the Files page with filters, downloads, Download selected and the storage meter

- /dashboard/chat/files lists the workspace's files newest first, 50 at a
  time with Show more: name and formats ("Used in Content draft"), Made by
  (You, a teammate, Agent, Scheduled), From chat (only chats the person can
  open), and the generated time with "Data as of" (CHAT-06 items 12, 16-17).
- Chips All (with the workspace's count), Drafts, Reports, Code, Tables,
  Images, From me, From agents, and "Filter by name..." over the search
  column; "No files match." with Clear filters.
- Each row has Copy (Markdown), Open (its Content draft) and Download in
  the formats it offers. Picked rows download as one .zip in their main
  formats, up to 50 files and 100 MB (items 18-19).
- The storage meter ("Storage 2.1 of 25 GB", amber from 80%) and a line
  once storage is full, with no Get more until the plan rules are set
  (items 26-29).
- GET /api/chat/files, GET /api/chat/files/{id}, POST /api/chat/files/zip
  (reads only). Files sits under Settings in the chat menu, in the Ctrl K
  palette and in the breadcrumb.
- Help: help/chat/files.md (new).

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

* fix(chat): keep Agents at work to the person's own chats, and read the clock with each list read

A teammate's shared chat that waits on its author's OK no longer shows under
Agents at work or in Home's count. A chat that waits on an OK or is paused no
longer keeps the list on the 5 s pace. A menu left open past midnight now
moves Today's chats to Yesterday on the next list read.

* fix(chat): show a teammate's initials on a shared chat

A person reads only their own profile, so the author's name came back
empty on every teammate's shared chat. Read it on the server, within the
workspace; only the initials leave.

* fix(chat): keep a teammate's shared chat out of the Inbox and Home's count

A shared chat that waits for approval waits on its author, who alone can
answer it. The Inbox, its counts in the menu and the strip, and Home's
"things need you" now count the person's own chats only.

* fix(chat): read a * in the @ search as a space, not a wildcard

PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* style(chat): format the read-only open routes list so the web format check passes

* fix(chat): style answers as the app's other AI answers, take hand-made brand ids, and keep Files' draft line whole

From the W1-25…27 preview:
- A Chat answer's Markdown gets the prose styles the Mentions drawer and
  the response detail use (prose prose-sm dark:prose-invert max-w-none):
  headings, lists and table cells, in both themes.
- Starting a chat with a brand (createInput) and Chat Home's due-actions
  line take the demo brand's id with z.guid(): it is made by hand, not an
  RFC 4122 uuid (as #1849 did for starting a run).
- On Files, "Used in Content draft" has its own line under the formats,
  so a 1024px table no longer cuts it off.

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

* test(chat): check who may do what through the engine, role by class by mode (W1-22)

CHAT-05 test set 27–30 and CHAT-20 §4c, §5 end to end, with a scripted
model and the in-memory database:
- Each role is offered only the changes its role allows, and the
  explainer when something is left out.
- Every role reads in every mode with no card.
- A change waits on its card in Ask me first and Auto. Full auto runs it
  for an Admin, and for a Manager only while members may.
- Full auto stays on Growth and up, paid: Starter and the trial get the
  card, and Enterprise's trial runs.
- An Analyst and an Agency partner get the four-part refusal in every
  mode. Nothing changes, and each refusal is logged with its rule.
- An EXECUTE never runs without the click; a Manager the Admin turned
  publishing off for is refused by policy.
- A role lowered while the card waits refuses the approval.

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

* fix(chat): don't offer Admins the request to the Admins

Admins have no one to ask (CHAT-20 access table: "not needed"): the model
was offered request_access for them, so it could put up a card the server
then turned away. The engine now neither offers it to an Admin nor lists it
among what they can't do. The row keeps every role: defineTool never
leaves an Admin out of a row, by design.

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

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

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

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

* fix(chat): clean the pages Chat files, number output cards by their files, copy as Safari allows

From the pre-push review of W1-25…27:
- create_draft's page goes to Files as the draft keeps it, through
  sanitizeDraftHtml, and Files' HTML download cleans it again: a page Chat
  read can't slip a script or an event handler into a download (CHAT-06:
  no script in exported HTML).
- An output card's file is its place among the run's filed outputs, as
  the server counts them. A card that wasn't filed (storage full, failed)
  no longer shifts the next card onto another page's file.
- Copy on an output card writes a clipboard item within the click, its
  text to come (Safari refuses a write after an await), and says when it
  can't.
- A reopened chat's output cards mask ids in their titles, as the live
  events do.

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

* fix(chat): stream Download selected, copy Files rows as Safari allows, and say what a full workspace keeps

From the pre-push review of W1-25…27:
- Download selected streams the .zip as it is made (fflate's Zip): one
  file read, written and compressed at a time as the reader asks for
  more, so neither the files nor the .zip are held whole, and a .zip past
  a function's body cap still goes out. The limits stay: 50 files, 100 MB
  stored, checked before anything is read.
- Copy on a Files row writes a clipboard item within the click, its text
  to come (Safari refuses a write after an await), and says when it can't.
- Help: with storage full, an output's card can't copy or download it (it
  has no file); the answer above it still can.

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

* fix(chat): keep Data used to "Read …" steps, and plain links in the answer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): send an attachment with its type, and call it ready only when its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): keep a copied Agent Chat thread in its order

Agent Chat wrote a conversation's whole thread again on every turn in one
insert, so its messages share one created_at and their ids don't follow
the order. The copy read them by created_at then id, which shuffled them,
and Chat reads a chat by created_at alone. Read each conversation the way
Agent Chat's own page did (by created_at, no tiebreak) and give the copies
a strictly rising created_at, a millisecond apart where they tied.

Also cut a long title or message without splitting an emoji in half.

* fix(chat): open Full auto in the composer only where the server runs it, and steer only after Stop is taken

The composer's Full auto now follows the same facts the approval check uses:
the plan, and for anyone but an Admin the Admin's Full auto for members
switch. When the switch closes it, the mode says Off by Admin rather than
Needs Growth. Steering sends the new message only once the Stop is taken;
otherwise the text stays in the box.

* fix(chat): find a domain, a number or an email address in Search chats

Each word goes to Postgres quoted, so it splits it the way it split the
text: "nike.com", "4.5" or an address is one token there and is now
found whole, and Postgres lowercases it itself.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* fix(chat): tie a step's hold to its chat's agent run and keep paused runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

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

* test(chat): give the test's EXECUTE row its words, assert approvals before driving, and cover an Admin's request

From the pre-push review of W1-22:
- publish_page, the test's own EXECUTE row, gets its words through a mock
  of the messages (the product has no such tool yet), so no
  MISSING_MESSAGE trace prints. The publishing refusal's "asked" is now
  checked.
- Approvals are asserted before the run is driven on, so a refused one
  fails the test instead of passing quietly. The approve helper returns
  a refusal for its callers to check.
- An Admin's call to request_access, which they aren't offered, is turned
  away: no card, no request. The row's comment says how Admins are kept
  out.

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

* feat(chat): pause a run on a question card and go on with the answer

The write phase can call ask_question: 2-4 options, exactly one
Recommended. The run waits on an `ask` step and its chat_asks row, with no
model call. POST /api/chat/runs/{id}/answer keeps the answer once (409 when
already answered, 400 when it doesn't fit, 402 while read-only) and the run
goes on.

- Skip goes on with the Recommended option.
- Stop keeps open questions as skipped.
- A run asks at most 4.
- Questions asked together show "1 of 2", then "2 of 2".
- A message from the composer answers the question, and the rest of its
  batch.

QuestionCard (number keys, Enter = Next, Other..., multi, read-only gate)
and its folded line; the composer's ghost shows the Recommended option.
Help and the preview page show it.

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

* fix(chat): say when a question card takes several answers

A question with several picks looked like a one-pick question. Its footer
now says "Pick one or more · Press 1–N to pick", in the mockup's words,
and each row has a check box that ticks when picked. Help says the same.

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

* style(chat): format the read-only open actions list so the web format check passes

* wip(chat): next moves (W2-02, in progress)

* fix(chat): keep Chat on at the AI limit on the workspace's own key, and read the usage again after each run

The composer turned off whenever the allowance was used up, but Chat on
the workspace's own key never draws on it (the server's hold writes those
steps unchecked), so a workspace with its own key could not send at all.
The page now reads whether Chat runs on the workspace's own key, as the
server picks it, and keeps the composer on then.

The meter, the 80% line and the pause also read the usage again once a
run stops working, so they follow the chat's own spending without a
page change. One read per run, no timer.

* fix(chat): name the run's own brand in the page context, and keep its block closed

The brand chip a message carries is now the run's own brand (the chat's,
checked against the workspace), not the posted label and id; it goes when
the run has no brand. The page context reaches the models with < and > as
JSON escapes, so a label can't end the block, and a reference's scope is
capped at 8 entries.

* fix(chat): name only a known platform in Traffic's question, and the first Top action in Action Center's

AI Referral Traffic's suggestion now reads the platform the page can name,
as the summary line does, and none over all time, where there is no
previous period and every platform would read as a rise. Action Center's
"How do I finish" names the first of the Top actions as the card ranks
them; the list arrives unordered.

* fix(chat): set up the side panel's composer as Chat's pages set theirs up

The panel's setup read Full auto from the plan alone and left out whether
Chat runs on the workspace's own key. So a member whose Admin turned "Full
auto for members" off could pick a mode that then asks anyway, and the
panel paused at the AI limit on a workspace's own key. The layout now reads
the switch and the key (only with the new Chat on) and builds the setup with
the same composerSetupOf Chat's pages use, moved to lib/chat/composer-setup;
the panel passes fullAutoOffByAdmin and onOwnKey on to the composer.

* perf(chat): load the side panel's code the first time it opens

The layout imported the panel directly, so its thread, composer and run
views came with every app page, Chat on or off. The layout now puts a
small slot there that loads the panel the first time it opens and keeps
it after that.

* fix(chat): keep Back to the page off paths with dot segments

panelReturnOf accepted /dashboard/../… and its %2e form, which resolve
outside the dashboard or into Chat. Refuse a . or .. segment.

* fix(chat): stop a run that waits on a question, and take its answer as the person's

From the review of the question card:

- Stop while a question waits: Stop sits beside Send and Esc stops the run.
  The question is kept skipped and its step reads "Question skipped".
- The answer reaches the model as the person's own (from: 'the person'),
  and the system prompt says to follow it like their message, not as data.
- A change called in the same step as a question doesn't run (not_run).
  The model calls it again with the answer.
- An answer kept while the run stopped meanwhile is let go again (no new
  migration), so the question doesn't stay half answered.
- The question card:
  - Enter on Skip, Add or an option is that button's own.
  - Text in Other... counts without Add, up to 500 characters.
- Answering from the composer:
  - It sends text only: no files, @ data or chips.
  - The box takes up to 500 characters; a 400 says why.
  - The composer is free at once (the answer's stream isn't awaited).
- "1 of N" counts only the questions the run will ask.
- A typed option label matches regardless of case, spacing, accents or
  Turkish i.
- Questions are capped at 200 characters, the step label's length.
- Help: the card section, and "Answer in the box".

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

* feat(chat): suggest next moves under a finished answer, the first as the composer's ghost

This commit and the wip commit before it make up CHAT-07 §C.

- With its final answer, in the same model step, the model calls
  suggest_next_moves. A step with only that call ends the run without
  another model step.
- The moves are picked for the person's role and plan as they are now:
  - an Analyst, an Agency partner or a read-only workspace gets read moves
    only;
  - one move per kind and per prompt, three at most, ids masked.
- They are kept in chat_next_moves (00417) and sent as next_moves before
  run.finished. None after an error, a pause at the cap, a Stop, or while a
  question or a change waits.
- The page shows them as "Next moves" cards under the latest answer only
  (mockup #s-done). A click sends the prompt as the next message.
- The first move shows as the composer's ghost when it continues this run
  (ghost_ok). A teammate's shared chat shows none.
- loadChatThread brings them back after a reload.
- Help ("Next moves") and the preview page show them.

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

* wip(chat): prompt, topic and competitor writes (W2-06, in progress)

* feat(chat): add the agents API: create, version, triggers, lifecycle and Run now (W2-13)

Chat's agents (CHAT-21, CHAT-27 §E) on the server, behind CHAT_AGENTIC:

- /api/chat/agents: list (Mine, Workspace, Paused, Archived, search) and
  create a draft; /{id}: detail, change (a new immutable version whenever
  what the agent does changes; name, visibility, caps and triggers change
  on the agent), delete once archived; /{id}/activate, pause, resume,
  archive, restore, duplicate; /{id}/run (Run now); /{id}/runs.
- Roles as §K: Admins and Managers make and run agents, a Manager changes
  only their own, private agents for their owner and Admins, Analysts and
  Agency partners read; refusals carry the out-of-permission answer
  (CHAT-20 §4c) and an access.denied row. Workspace agents kept to Admins
  and Full auto off follow Settings › Chat.
- Plan gates: Full auto Growth+, engines the plan tracks, active agents
  and agent runs at once per plan (§M, approved as written).
- Triggers: 0–5 schedule, Signal, KPI or watch-rule triggers, validated;
  a schedule's next fire from a dependency-free RRULE subset in its zone.
- Run now queues a run per brand (one per click a minute, at most 3
  waiting), acting as the person; a slot is tried with
  chat_start_next_agent_run only once a driver exists (W2-16), so runs
  wait queued until then.
- AI use as shares only: each agent's share comes from the server's new
  GET /api/internal/chat/budget/agent-shares (chat_agent_usage_shares
  against the budget the server keeps), cached 5 minutes; no dollars reach
  the browser.
- Every write is gated by writeRefusal; every change and Run now goes to
  the Activity log with agent_id and agent_run_id.

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

* fix(chat): open an answer in the Content Editor as the answer shows it

An image in the answer goes into the draft as its alt text, and raw HTML
as its text, as the answer itself shows them; links stay, cleaned by the
draft's own sanitizing.

* fix(chat): show on a next move the text it sends, and keep only the last step's moves

From the review of next moves:

- A card shows the very prompt a click sends, never a label that could say
  something else. A page Chat read could otherwise dress a write up as "See
  the full report".
- Moves belong to the step they came with: they are cleared before each
  writing step, so a question, an answer and a last step without moves
  shows none.
- The tool takes the call whole (up to 6 moves, loose fields) and checks
  each move on its own (validMoves). A move too long or of an unknown kind
  loses only itself.
- A move whose label or prompt names a tool, or reads like one
  (snake_case), is dropped before it is kept.
- loadChatThread logs a failed read of the moves and opens the chat
  without them. A teammate's shared chat doesn't read them.
- In the side panel the cards stand one under another; two or three side by
  side on a page.
- Comment: ghost_ok is the model's word, not checked.
- Tests: moves that can't be kept, an error and a Stop after a step with
  moves.

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

* fix(chat): let a Stop after Approve win, and finish the who-may-do-what matrix

A Stop that comes after Approve, before the approved change runs, now
stops the run: in the same process the change no longer runs, and from
another process the card is closed with run.stopped instead of the run
staying stopped with its step still waiting.

The matrix's test-only EXECUTE row is Admin and Manager work, as in
precedence.test, and the matrix now covers every change row, Analysts'
and Agency partners' own changes in each mode, their refused go-live,
a teammate answering someone else's card, a click refused after the
Admin turned publishing off, and the demo brand for every role.

* fix(chat): show Admins every agent, keep triggers across saves, and add Take over (W2-13)

Review fixes on the agents API:

- Workspace tab: an Admin sees every agent in use, others' private ones
  included (CHAT-21 §K, edge case 1); the counts follow.
- Triggers are matched with their keys sorted (canonicalJson): jsonb's
  key order no longer makes a KPI, Signal or one-off trigger look new, so
  its last fire and cooldown stay.
- Only a new or changed trigger is held to the clock: a one-off that
  already fired can come back with a save.
- Run now claims an idempotency key (agent, brand, person, minute), so two
  clicks at once queue one run; a run counted past the 3 waiting after its
  insert goes again and joins the last.
- POST /api/chat/agents/{id}/take-over: an Admin becomes the owner; an
  agent that is on, or paused because of its owner, passes the activation
  checks under them first and comes back on; logged.
- Duplicate is held to create's checks (mode, engines, brands, topics,
  people).
- The internal budget endpoints compare CRON_SECRET in constant time
  (webhookSecretsMatch).
- Tests for another workspace's or a teammate's private agent (404).

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

* fix(chat): keep a long answer's or chat's PDF within the route's time

react-pdf's layout time grows with the square of the length: 2,000 table
rows took about 60 s and 6,000 rows about 4 minutes, and Export chat joins
every answer of a chat. A PDF now lays out 1,000 rows and blocks at most
and ends with a line saying so (Markdown and Word keep all of it), and
both export routes get maxDuration 300.

Also matches the downloaded body in the answer bar's test by its size:
fetch's Blob is Node's, not the test page's.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

* feat(chat): track prompts, topics and competitors from Chat, with Undo

This commit and the wip commit before it make up W2-06 (CHAT-20 §9 rows 20–32).

New WRITE rows, one registry file per area:
- add_prompts: prompts in one of the brand's topics, topic first.
- pause_prompts: the spec's "archive"; the app pauses, history kept.
- add_topic, rename_topic.
- add_competitors, remove_competitor (always a card).

How they run:
- Admins and Managers, as the app (00382, #1762). Others get the
  structured refusal.
- Each calls a thin server action over the app's own:
  - addTopicPrompts runs through importPrompts: the plan's prompt
    locations, duplicates skipped, first run started.
  - pauseBrandPrompts, addBrandTopic, addCompetitors and
    removeBrandCompetitor each check the brand and skip natural-key
    duplicates.
- Every one checks the read-only workspace first.

Undo for each (undo-setup.ts), 7 days, 30 for paused prompts. Anything
changed since is left alone (undo_conflict). Resuming paused prompts checks
the plan's room again.

Registry and engine:
- A row may name its batch: the run's caps count items (50 prompts, 5
  competitors), and more than 5 prompts paused at once always shows a card
  (overBatch).
- A row may name its card's target from the data: the topic, the prompts,
  the competitor.
- A refusal the person can act on (quota_exceeded, duplicate, not_found,
  invalid) shows the action's words on the step and gives the model its
  §11a code.
- An action's { ok: false } refusal is no longer logged as a change.

Help: chat.md "Change what you track".

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

* fix(chat): let a Stop right after an answer win, and keep a question the run never went on with as skipped

The answer branch of resumePending now checks for a Stop before taking the
answer up, as an approved change does. A stopped run's open question is kept
as skipped even when its answer was kept just before the Stop, and an answer
whose run ended before it was taken back is kept as skipped rather than
cleared. Tests: Stop after an answer in this process and in another, the
run-ended-meanwhile case, and a teammate's answer, skip and stop on a shared
chat.

* wip(chat): content, report and audit writes (W2-07, in progress)

* chore: no changes; push again so GitHub picks up the merged fixes

* fix(chat): start a run from a tainted run's next move tainted, and drop moves that carry a link

* fix(chat): hold a change to someone else's agent to its owner's mode, and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants