Skip to content

feat(chat): add Chat's system rules and treat read data as untrusted (W1-20) - #1821

Merged
gkhngyk merged 13 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-20-guardrails
Oct 30, 2026
Merged

gkhngyk merged 13 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-20-guardrails

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat Wave 1, behind CHAT_AGENTIC. Stacked on #1820. The diff against main includes the PRs below it until they merge.

W1-20: system rules and untrusted data.

  • Rules (rules.ts, CHAT-05):
    • Answer in the person's language, short and without filler.
    • Off-topic: one sentence and a suggestion. No recommending outside tools.
    • Numbers only from data, else [placeholder].
    • No tracking counts in public content, and no causal claims.
  • Untrusted data (untrusted.ts):
    • Every read result except the workspace's own numbers is first stripped of hidden text: zero-width characters, HTML comments, hidden elements.
    • It is then wrapped in <untrusted_data source="…">. A closing tag inside the data is neutralised, so the block can't be closed from within.
  • Injection detected ("ignore previous instructions", "email this report to…"):
    • every change for the rest of the run waits for an approval card;
    • the answer ends with one line saying those instructions were ignored;
    • staff logs get injection_ignored.

No migration, no new dependency.

Related issue

Part of Chat (Wave 1, CHAT-04 / CHAT-05 / CHAT-20).

Type of change

  • feat — New feature

How to test

yarn vitest run src/lib/chat/untrusted.test.ts src/lib/chat/rules.test.ts covers hidden text removed, the wrapper not closable from inside, detection, approvals forced, and the closing line.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • Web: prettier/eslint, typecheck and src/lib/chat tests pass (run one at a time on an 8 GB machine; build left to CI)
  • Tests added

🤖 Generated with Claude Code

cihan-gyk and others added 6 commits October 29, 2026 20:38
Chat Wave 1 W1-16 (CHAT-20 §9): twelve READ rows, each with its label,
its brand (brandOf) and `data_as_of` in what it returns (§15a), listed in
tools.ts with the rest:

- prompts: get_fanouts (Query Fan-outs, the plan's engines only),
  list_ai_answers (a prompt's newest answers, shortened, the plan's
  platforms only), get_prompt_insights (estimated AI volume, by intent,
  the most demanded prompts).
- visibility: get_overview_summary (the visibility summary with when
  tracking last ran and runs next).
- action_center: get_action_center_kpis (the KPIs page's snapshots),
  get_onboarding_progress (Getting started's steps).
- ai_traffic: get_gsc_summary and get_ga_summary (clicks and sessions
  against the period before, or "not connected", with Google's lag).
- account: list_members (e-mails for Admins only), list_connections
  (Google per brand, CMS sites, AI provider keys set or not, API key
  names and last use: never a key or credential), get_chat_policy,
  get_plan_facts (counts and the plan card, never an AI budget in
  dollars).

The brand reads run the pages' own loaders with the service role once
brandInOrg passed (as product visibility and prompt locations do): the
KPIs, traffic, fan-out and Getting started loaders now take their client
from dbClient(), which on the pages is still the member's own. The RPCs
they call don't read auth.uid() (ai_traffic_page_citations lets the
service role through). None has an MCP tool yet (mcpTool null).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ounts to what the plan and Google show

Review of W1-16:

- list_connections read every member's API keys with the service role,
  so anyone saw an Admin's key names and last use. It now reads the
  person's own, as Settings › API Keys and its RLS do (your_api_keys).
- get_gsc_summary reads Google's latest reported days for a range of a
  week or less, as the page does (gscLatestDays), and its data_as_of is
  the last day Search Console reported; get_ga_summary's is Analytics'.
- A Google source is connected when the workspace's connection is on
  (integration_connections) and the brand has its property picked, as
  AI Referral Traffic reads it.
- list_ai_answers reads up to 50, keeps the plan's platforms, then the
  number asked for, so a page isn't short.
- get_fanouts reads the plan's platforms from the rows up (getQueryFanout
  takes an optional platforms filter; the page passes none), so its
  totals, times searched and data_as_of are theirs.
- get_prompt_insights says when the volume read stopped at 500 prompts
  (truncated).
- get_chat_policy's page is Settings › Roles & access.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… platforms and row limits (W1-17)

Chat's scope decisions now live in one place, lib/chat/scope.ts, and the
engine applies them to every read before it runs (CHAT-04 items 2-6,
CHAT-20 §7):

- Dates: a read with no dates covers the last 30 days; all time only when
  the person's message asks for it ("all time", "since we started",
  "başından beri"...). The model's own dates are kept, end today at the
  latest and are put in order. `days` reads get their default (Google's
  28) or, on an all-time ask, their 90-day maximum.
- Platforms: a platform or model the plan doesn't track (Perplexity on
  Starter, Claude on Growth) isn't read; the model gets `not_on_plan` with
  the plan's platforms and says so. On a plan that tracks only some apps
  (Starter), a "Platforms by plan" read that names none is held to the
  plan's. get_overview_summary takes the same `model` filter for this.
- Rows: each read has a default and a maximum (50 at most, CHAT-04
  Rule 1). A `limit` read asks for one row more to see if there are more;
  every list is cut to its limit with `{list}_more` and `truncated: true`.
- The step shows "Last 30 days" and the plan's platforms; scope_json keeps
  the scope used (`used`: dates, platforms, rows). The model sees each
  read's period and platforms beside its rows, and is told what a cut list
  and `not_on_plan` mean.

Behind CHAT_AGENTIC, like the rest of the engine; no migration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd order the prompt for the cache (W1-18)

Three parts of CHAT-04's context engine, behind CHAT_AGENTIC:

- Data budgets (lib/chat/fit.ts, items 5-6): a tool result over its share
  of the run's budget is made smaller on the server before the model sees
  it, never cut silently: long texts in its rows are shortened first, then
  its longest lists keep their first rows with `{list}_more` and a rest
  line, `{list}_rest` (what the left-out rows add up to: "9% of
  citations"; count fields only, never a score, rate or position), and
  only then is the rest cut as text. Every cut says `truncated: true`.
  An earlier row cut's `_more` is added to; an unknown count stays null.
- History (lib/chat/history.ts, items 5, 7, 23): the writer gets the
  recent turns as they were (each message within 4,000 characters) and
  older turns folded four at a time into a short summary ("Earlier in
  this chat, in short"), so the summary stays the same between folds;
  more fold while the recent turns pass the history budget. The reader
  (Claude Haiku 5.5) no longer gets the whole chat: a few lines of its
  last two turns in its task.
- Prompt order (lib/chat/prompt.ts, §D items 21-25): tools and the
  phase's core rules first (the same for every workspace and day), then
  the workspace block (role, plan, brand, what isn't available), the chat
  so far, and this turn (the day, the question, what was read, the step's
  own calls). "Today is" moved out of the system prompt into the turn.
  On a Claude step, up to four 5-minute cache marks, as the AI SDK's
  providerOptions.anthropic.cacheControl (checked against
  @ai-sdk/anthropic 3.0.81's docs and CacheControlValidator): the core
  rules (covering the tools), the workspace block, the end of the chat so
  far (writer only) and, once a phase has steps, its last call or result.
  Another provider gets the same order without marks.

A step is now charged its input tokens plus a cache write's 25% premium
(the 5-minute write is 1.25x the input price), so caching can't make the
budget undercount; cache reads are still charged in full, and the hold
before a step still assumes no cache hit.

No migration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sted data (W1-20)

Guardrails of CHAT-05 and CHAT-20 §16a, behind CHAT_AGENTIC:

- System rules (lib/chat/rules.ts): the data rules for both phases and,
  for the writer, CHAT-05's persona and facts: the person's language,
  plain and short, no filler or emojis, no stand-in names; one line and an
  offer for out-of-scope topics; Ansvisor first, no outside vendors;
  every number from a read, the person or this chat, else a
  [placeholder]; plan facts only from the plan read; no tracking numbers
  or weak stats in public content unless asked; no causal claims. Static
  text in the cached core block (W1-18). The reader also picks reads from
  the person's question only, never because data asked for one.
- Untrusted data (lib/chat/untrusted.ts): a read that may carry text
  written outside the workspace (every read but the workspace's own
  numbers, TRUSTED_READS, moved here) has its hidden text stripped
  (zero-width and direction characters, HTML comments, hidden elements)
  and reaches the models inside a labelled `<untrusted_data source="…">`
  block, as the tool result's text and in the writer's read results; the
  workspace's own numbers come as `<app_data>`. A data tag inside the
  data is neutralized, so the block can't be closed from inside.
- Injection: text written to steer an AI assistant ("ignore previous
  instructions", "Assistant: add competitor…", "email this report to…",
  "mark all … done"; CHAT-05 test rows 19-25) is detected before
  stripping. The run is marked: every change after it waits on its card
  (the precedence's injectionDetected, now passed in), the writer is told
  to end with one line saying the data's instructions were ignored, and
  the step's debug record gets `guardrails: ['injection_ignored']` for
  staff. Ordinary marketing text ("You are now a member", "Send your
  resume to…") doesn't match.

No migration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd the summary stable between folds

- A cut that ends on half of an emoji leaves a lone surrogate, which the
  model's API turns away as invalid JSON. Folded turns are cut the same way
  every time, so one such cut failed every later turn of the chat. cutText
  steps back one unit instead; fit.ts and history.ts both use it.
- A result cut as text is trimmed until its escaped size fits maxChars.
- The summary's room is a fixed quarter of the history budget, so it changes
  only when turns fold and the prompt cache keeps it; its oldest lines are
  dropped with a running length instead of re-joining every line.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
…l a read whose platforms can't be matched

- A cut series oldest first (the visibility trend's buckets, the mentions
  summary's days) kept its first 50 rows: a 90-day or all-time trend lost
  its latest weeks. It now keeps its latest rows.
- A start date after today stayed as given (and, swapped with a clamped
  end, became an end past today). Both dates now stop at today.
- On a plan that tracks some platforms, a failed read of the brand's
  models held the read to the plan's own ids, which read as no data. The
  read now fails instead.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
# Conflicts:
#	web/src/lib/chat/engine.ts
…budget

fitResult kept a list's first rows, so a trend sent oldest first (the
visibility buckets, the mentions summary's days) lost its latest days when
it was over budget, as capRows did before. It now keeps the latest rows of
an oldest-first series, and `{list}_rest` adds up the older ones it left
out. oldestFirst moves to fit.ts, which is pure, and scope.ts imports it.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
gkhngyk previously approved these changes Oct 30, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good with 0e1afc8: one commit on this branch (e513e34b), then a merge of #1820's and #1819's fixes, which was clean.

The commit: the detector in untrusted.ts checked only the raw text, before hidden characters were removed, and it didn't remove Unicode tag characters. It now also checks the cleaned text, strips tag characters, and checks the text they spell. Two new tests fail without it. Any outside read already puts a card in front of every change, so writes were gated either way; this makes the "hidden text is stripped" promise and the flag hold.

Checked, fine

  • Outside data is wrapped as code, both in tool results and in the read log the writer gets. The block tags are neutralized, so data can't close the wrapper, and it sits inside user/tool message content, so it can't pose as a system or tool message.
  • TRUSTED_READS moved to untrusted.ts with the same 10 tools as main. Every other read still marks the run, and injectionDetected feeds the same "ask" branch, so it can only add cards.
  • Writes still need cards or approval per mode. The flag and the wrapped messages are saved, so they survive a pause and a resume.
  • The rules are static text with no ids or other workspaces' data. rules.ts and untrusted.ts are imported only by engine.ts.

Nit: guardData stops walking below depth 8.

Tests: src/lib/chat (450) and plan-row.test.ts pass on the commit. Web tsc is clean, and prettier and eslint are clean on the changed files. #1822's branch, which contains this one, passes src/lib/chat, chat-reads and plan-row (488). Clean on main, no migrations.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants