Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): read and keep the brief's version 2 through Edit brief (brief rules PR 3) (#1539)
Cihan4efa1501e2e9
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 7a3b9cbe5..114e458cc 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4318,7 +4318,8 @@"save": "Save brief","cancel": "Cancel","saved": "Brief saved",- "failed": "Couldn't save the brief. Try again."+ "failed": "Couldn't save the brief. Try again.",+ "tooLong": "The brief is too long to save. Shorten its sections or key points."}},"export": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsxindex 9ca7b15fd..d8cdc262b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx@@ -291,6 +291,53 @@ describe('the Brief tab', () => {expect(toast.success).toHaveBeenCalledWith('Brief saved');});+ it('keeps what Edit brief doesn’t show: version 2’s answer, format, facts and page plan', async () => {+ saveDraftBrief.mockImplementation(async (_id, next: DraftBrief) => ({ ...next }));+ const planned: DraftBrief = {+ ...brief,+ version: 2,+ tldr: 'The page’s essentials.',+ proof: [{ kind: 'data', what: 'Our own shot times' }],+ outline: brief.outline.map((section, i) =>+ i === 0+ ? {+ ...section,+ answer: 'Under $500, a single boiler with a PID.',+ format: 'table' as const,+ facts: [{ claim: 'Average price', sourceType: 'statistic' as const, source: null }],+ }+ : section,+ ),+ };+ await render({ status: 'ready', brief: planned });+ await act(async () => button('Edit brief').click());+ await act(async () => button('Save brief').click());+ const saved = saveDraftBrief.mock.calls[0][1] as DraftBrief;+ expect(saved).toMatchObject({+ version: 2,+ tldr: 'The page’s essentials.',+ proof: planned.proof,+ });+ expect(saved.outline[0]).toMatchObject({+ answer: 'Under $500, a single boiler with a PID.',+ format: 'table',+ facts: [{ claim: 'Average price', sourceType: 'statistic', source: null }],+ });+ // The editor's own field stays its own.+ expect(saved.outline[0]).not.toHaveProperty('points');+ });++ it('says a brief too long to save is too long', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ saveDraftBrief.mockRejectedValue(new Error('too_long'));+ await render({ status: 'ready', brief });+ await act(async () => button('Edit brief').click());+ await act(async () => button('Save brief').click());+ expect(toast.error).toHaveBeenCalledWith(+ 'The brief is too long to save. Shorten its sections or key points.',+ );+ });+it('keeps the edit open when saving fails', async () => {vi.spyOn(console, 'error').mockImplementation(() => {});saveDraftBrief.mockRejectedValue(new Error('boom'));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsxindex 1ab194203..4f483a92c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx@@ -362,16 +362,16 @@ function BriefEditor({...brief,goal: goal.trim(),audience: audience.trim(),+ // What Edit brief doesn't show (version 2's answer, format, facts) is kept.outline: sections.filter((s) => s.heading.trim())- .map((s) => ({+ .map(({ points, ...s }) => ({+ ...s,heading: s.heading.trim(),- keyPoints: s.points+ keyPoints: points.split('\n').map((p) => p.trim()).filter(Boolean),- fanout: s.fanout,- platform: s.platform,})),keywords: [...new Set(@@ -386,7 +386,7 @@ function BriefEditor({onSaved(saved);} catch (err) {console.error('Failed to save the brief:', err);- toast.error(t('failed'));+ toast.error(t(err instanceof Error && err.message === 'too_long' ? 'tooLong' : 'failed'));} finally {setSaving(false);}diff --git a/web/src/lib/actions/content-drafts-brief.test.ts b/web/src/lib/actions/content-drafts-brief.test.tsindex aefcb0072..a6aac5325 100644--- a/web/src/lib/actions/content-drafts-brief.test.ts+++ b/web/src/lib/actions/content-drafts-brief.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { DraftBrief, RebuildSources } from '@/lib/content/brief';+import v2 from '@/lib/content/__fixtures__/brief-v2.json';/** The Brief tab (CE-007): read, edit and rebuild a draft's brief. */@@ -107,6 +108,26 @@ describe('getDraftBrief', () => {reads.content_drafts = null;expect(await getDraftBrief(DRAFT)).toBeNull();});++ it('reads a brief of version 2 whole', async () => {+ reads.content_drafts = { brief: v2, opportunity_id: null };+ expect(await getDraftBrief(DRAFT)).toEqual({ brief: v2 });+ });++ it('says a brief of its own it can’t read as a failed read, never as the opportunity’s', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ reads.content_drafts = { brief: { goal: 42 }, opportunity_id: 'o1' };+ reads.content_opportunities = {+ brief: { outline: [{ heading: 'Why', keyPoints: [] }], targetKeywords: [] },+ };+ // So Edit brief, which shows on a read brief only, can't write over it.+ expect(await getDraftBrief(DRAFT)).toBeNull();+ expect(error).toHaveBeenCalled();+ } finally {+ error.mockRestore();+ }+ });});describe('saveDraftBrief', () => {@@ -122,6 +143,31 @@ describe('saveDraftBrief', () => {});});+ it('keeps version 2 through an edit, as the person’s', async () => {+ reads['content_drafts:update'] = { id: DRAFT };+ const saved = await saveDraftBrief(DRAFT, v2 as DraftBrief);+ expect(saved).toMatchObject({ origin: 'edit', version: 2, tldr: v2.tldr });+ expect(saved.outline[0].facts).toEqual(v2.outline[0].facts);+ });++ it('says a brief past the column’s 64 KB is too long', async () => {+ const long = {+ ...v2,+ outline: Array.from({ length: 12 }, () => ({+ heading: 'h'.repeat(300),+ keyPoints: Array(8).fill('k'.repeat(500)),+ fanout: null,+ platform: null,+ answer: 'a'.repeat(600),+ })),+ leftOut: Array(20).fill('l'.repeat(300)),+ } as DraftBrief;+ reads['content_drafts:update'] = { id: DRAFT };+ await expect(saveDraftBrief(DRAFT, long)).rejects.toThrow('too_long');+ // Nothing written.+ expect(calls).toEqual([]);+ });+it('refuses a brief over its limits, and says when the draft isn’t found', async () => {await expect(saveDraftBrief(DRAFT, { ...brief, goal: 'x'.repeat(501) })).rejects.toThrow('invalid',diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 905b9ed99..4a066e3fb 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -59,11 +59,13 @@ import {type SavedRuleSet,} from '@/lib/content/rules';import {+ MAX_BRIEF_BYTES,briefFromOpportunity,draftBriefSchema,type DraftBrief,type RebuildSources,} from '@/lib/content/brief';+import { jsonbBytes } from '@/lib/content/draft-inputs';import type { ContentBrief } from '@/types';import {CITED_DAYS,@@ -2152,6 +2154,12 @@ export async function getDraftBrief(id: string): Promise<{ brief: DraftBrief | nif (!draft) return null;const own = draftBriefSchema.safeParse(draft.brief);if (own.success) return { brief: own.data };+ // A brief of its own this editor can't read: said as a failed read, never+ // as the opportunity's or none, so Edit brief can't write over it.+ if (draft.brief != null) {+ console.error('The draft brief can’t be read:', own.error.issues.slice(0, 3));+ return null;+ }if (!draft.opportunity_id) return { brief: null };const { data: opportunity, error: oppError } = await supabase.from('content_opportunities')@@ -2167,6 +2175,8 @@ export async function getDraftBrief(id: string): Promise<{ brief: DraftBrief | nexport async function saveDraftBrief(id: string, brief: DraftBrief): Promise<DraftBrief> {const parsed = draftBriefSchema.safeParse({ ...brief, origin: 'edit' });if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');+ // The column's 64 KB (00212): said, not a failed save.+ if (jsonbBytes(parsed.data) > MAX_BRIEF_BYTES) throw new Error('too_long');const supabase = await createClient();const { data, error } = await supabase.from('content_drafts')diff --git a/web/src/lib/content/__fixtures__/brief-v2.json b/web/src/lib/content/__fixtures__/brief-v2.jsonnew file mode 100644index 000000000..67bd62cc9--- /dev/null+++ b/web/src/lib/content/__fixtures__/brief-v2.json@@ -0,0 +1,108 @@+{+ "goal": "Show finance leads how a rolling 13-week cash forecast works in Ledgerly.",+ "audience": "Finance leads at small companies who forecast in spreadsheets today.",+ "outline": [+ {+ "heading": "What a rolling 13-week cash forecast is",+ "keyPoints": [+ "How it moves forward one week every week",+ "What goes in it"+ ],+ "fanout": "13 week cash flow forecast template",+ "platform": "chatgpt",+ "answer": "A 13-week forecast of cash in and out that adds a week as each week ends.",+ "format": "paragraphs",+ "facts": [+ {+ "claim": "How far static forecasts drift in a quarter",+ "sourceType": "study",+ "source": null+ },+ {+ "claim": "Ledgerly customers' average forecast error",+ "sourceType": "statistic",+ "source": {+ "kind": "input",+ "ref": "data:1",+ "label": "Forecast error by month"+ }+ }+ ]+ },+ {+ "heading": "Rolling forecast vs static budget",+ "keyPoints": [+ "Update cadence",+ "Accuracy",+ "Effort"+ ],+ "fanout": null,+ "platform": null,+ "answer": "A rolling forecast is updated weekly; a budget is set once a year.",+ "format": "table",+ "facts": []+ }+ ],+ "keywords": [+ "rolling cash forecast",+ "13 week cash flow model"+ ],+ "origin": "rebuild",+ "builtAt": "2026-10-26T10:00:00Z",+ "builtFrom": {+ "prompts": 2,+ "fanouts": 4,+ "pages": 1,+ "queries": 2+ },+ "citedLength": {+ "characters": 6200,+ "pages": 2+ },+ "version": 2,+ "tldr": "A rolling 13-week forecast keeps cash visible; Ledgerly updates it from your bank weekly.",+ "angle": "Ledgerly's own variance data across its customers, not a template.",+ "proof": [+ {+ "kind": "data",+ "what": "Average forecast error before and after switching"+ },+ {+ "kind": "case",+ "what": "A customer who caught a shortfall six weeks out"+ }+ ],+ "leftOut": [+ "how to read a cash flow statement"+ ],+ "freshness": {+ "datedPoint": "The forecast error figure, with its month",+ "updatedLine": true,+ "yearInTitle": false+ },+ "entities": {+ "brand": "Ledgerly",+ "products": [+ "Ledgerly Forecast"+ ],+ "competitors": [+ "Cashwise"+ ]+ },+ "links": {+ "internal": [+ {+ "url": "https://ledgerly.example/pricing",+ "anchor": "Ledgerly pricing",+ "section": "Rolling forecast vs static budget"+ }+ ],+ "outbound": [+ {+ "url": "https://www.reddit.com/r/FPandA/comments/abc",+ "anchor": "what finance teams say",+ "section": null+ }+ ]+ }+}diff --git a/web/src/lib/content/brief.test.ts b/web/src/lib/content/brief.test.tsindex 8189ef5f8..0afa6bb51 100644--- a/web/src/lib/content/brief.test.ts+++ b/web/src/lib/content/brief.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ BRIEF_V2_LIMITS,briefFromOpportunity,builtFromCount,draftBriefSchema,@@ -7,6 +8,7 @@ import {type DraftBrief,} from './brief';import type { DraftSourcesData } from './sources';+import v2 from './__fixtures__/brief-v2.json';const data: DraftSourcesData = {prompts: [@@ -115,6 +117,58 @@ describe('the brief', () => {).toBe(false);});+ it('reads version 2 as the server writes it, and a brief from before it as it was (brief-v2.json)', () => {+ const read = draftBriefSchema.parse(v2);+ // Every field kept: the server's sample, as it's tested there too.+ expect(read).toEqual(v2);+ expect(read.outline[0]).toMatchObject({ format: 'paragraphs', facts: expect.any(Array) });+ const before = draftBriefSchema.parse(brief);+ expect(before.version).toBeUndefined();+ expect(before.outline[0].facts).toBeUndefined();+ });++ it('reads what a newer server may write without hiding the brief', () => {+ const read = (change: Record<string, unknown>) =>+ draftBriefSchema.safeParse({ ...v2, ...change });+ const section = v2.outline[0];+ // A later version, an unknown format: the brief shows, the value reads as none.+ expect(read({ version: 3 })).toMatchObject({ success: true, data: { version: undefined } });+ const unknownFormat = read({ outline: [{ ...section, format: 'carousel' }] });+ expect(unknownFormat.success && unknownFormat.data.outline[0].format).toBeNull();+ // An item of a kind it doesn't know goes; the rest stay, up to the limit.+ const fact = section.facts[0];+ const facts = read({+ outline: [+ {+ ...section,+ facts: [+ { ...fact, sourceType: 'rumour' },+ ...Array(BRIEF_V2_LIMITS.facts + 1).fill(fact),+ ],+ },+ ],+ });+ expect(facts.success && facts.data.outline[0].facts).toHaveLength(BRIEF_V2_LIMITS.facts);+ const proof = read({ proof: [{ kind: 'screenshot', what: 'x' }, v2.proof[0]] });+ expect(proof.success && proof.data.proof).toEqual([v2.proof[0]]);+ // A long text is cut; none reads as none.+ const long = read({ tldr: 'x'.repeat(BRIEF_V2_LIMITS.tldr + 50), angle: null });+ expect(long.success && long.data.tldr).toHaveLength(BRIEF_V2_LIMITS.tldr);+ expect(long.success && long.data.angle).toBeNull();+ expect(read({ freshness: null, entities: null, links: null }).success).toBe(true);+ });++ it('keeps a link to an http(s) address only', () => {+ const links = (url: string) =>+ draftBriefSchema.parse({+ ...v2,+ links: { internal: [{ url, anchor: 'x', section: null }], outbound: [] },+ }).links?.internal;+ expect(links('https://ledgerly.example/pricing')).toHaveLength(1);+ expect(links('javascript:alert(1)')).toEqual([]);+ expect(links('ftp://ledgerly.example/x')).toEqual([]);+ });+it('reads an opportunity’s brief until the draft has its own', () => {expect(briefFromOpportunity({diff --git a/web/src/lib/content/brief.ts b/web/src/lib/content/brief.tsindex 6aee1ae34..22650c054 100644--- a/web/src/lib/content/brief.ts+++ b/web/src/lib/content/brief.ts@@ -1,11 +1,13 @@import { z } from 'zod';import type { ContentBrief } from '@/types';import {+ SUGGESTION_SOURCE_KINDS,buildSourceGroups,readDraftDoc,type DraftSourceChoice,type DraftSourcesData,} from '@/lib/content/sources';+import type { SuggestionSource } from '@/lib/content/suggestions';/*** The editor's Brief tab (Content Editor CE-007, spec §10): what the page@@ -19,6 +21,48 @@ import {export const BRIEF_ORIGINS = ['rebuild', 'edit', 'opportunity'] as const;export type BriefOrigin = (typeof BRIEF_ORIGINS)[number];+// The brief rules (2026) a brief plans with, from its version 2 (server+// content-brief.js, behind CONTENT_BRIEF_RULES): each optional, so a brief+// from before them reads as it was, and Edit brief keeps them. A value this+// editor doesn't know yet, from a newer server, reads as none rather than+// hiding the brief: a new one is added here, and shipped, before the server+// writes it.++/**+ * How a section is best shown: a table for a comparison, steps for a how-to.+ * A "faq" section's key points are its questions.+ */+export const BRIEF_FORMATS = ['paragraphs', 'list', 'steps', 'table', 'faq'] as const;+export type BriefFormat = (typeof BRIEF_FORMATS)[number];+/** The kind of source a fact to state needs. */+export const FACT_SOURCES = ['statistic', 'study', 'quote', 'example', 'official'] as const;+export type FactSource = (typeof FACT_SOURCES)[number];+/**+ * Proof to gather: the brand's own, which AI can't find elsewhere, as Brief ›+ * Your input takes it (experience, data, quotes; a case or a test as+ * experience).+ */+export const PROOF_KINDS = ['experience', 'data', 'case', 'test', 'quote'] as const;+export type ProofKind = (typeof PROOF_KINDS)[number];++/**+ * A fact a section states: what, the kind of source it needs, and the source+ * it was given for it, kept as a suggestion keeps its (00248): by kind and+ * ref, with its name, never its number in one run (S1…).+ */+export interface BriefFact {+ claim: string;+ sourceType: FactSource;+ source: SuggestionSource | null;+}++/** A page to link to: its address, the words to link, the section it goes in (null: anywhere). */+export interface BriefLink {+ url: string;+ anchor: string;+ section: string | null;+}+export interface BriefSection {heading: string;keyPoints: string[];@@ -26,6 +70,10 @@ export interface BriefSection {fanout: string | null;/** The platform key that ran it (perplexity-web, copilot-web…). */platform: string | null;+ /** What the section's first, direct answer must say: a note to the writer, not the answer. */+ answer?: string | null;+ format?: BriefFormat | null;+ facts?: BriefFact[];}export interface DraftBrief {@@ -44,12 +92,88 @@ export interface DraftBrief {* none could be.*/citedLength?: { characters: number; pages: number } | null;+ /** 2 once it plans with the brief rules (2026); absent before. */+ version?: 2;+ /** The page's essentials, for its top. */+ tldr?: string | null;+ /** What the page says that commodity pages don't. */+ angle?: string | null;+ /**+ * The brand's own proof to gather. Whether Brief › Your input has it is read+ * from Your input when shown, never kept here: it changes after a rebuild.+ */+ proof?: { kind: ProofKind; what: string }[];+ /** Fan-outs kept out: another topic, for another page. */+ leftOut?: string[];+ /** A dated point to give, an "Updated" line, the year in the title. */+ freshness?: { datedPoint: string | null; updatedLine: boolean; yearInTitle: boolean } | null;+ /** Names as they are written: the brand, its products, the competitors given. */+ entities?: { brand: string; products: string[]; competitors: string[] } | null;+ links?: { internal: BriefLink[]; outbound: BriefLink[] } | null;}/** Limits a brief keeps to, the server's (content-brief.js) and the column's (00212). */export const MAX_BRIEF_SECTIONS = 12;+/** content_drafts.brief's check (00212), as jsonb writes it as text. */+export const MAX_BRIEF_BYTES = 65_536;const text = (max: number) => z.string().trim().max(max);+/**+ * Version 2's limits: the server cuts its brief to them (content-brief.js),+ * and the editor reads past them by cutting too, so a newer server's brief+ * still shows. __fixtures__/brief-v2.json is the sample both sides test; the+ * server's test reads this file for the limits and the kinds.+ */+export const BRIEF_V2_LIMITS = {+ answer: 600,+ facts: 4,+ claim: 300,+ tldr: 500,+ angle: 500,+ proof: 6,+ proofWhat: 300,+ leftOut: 20,+ leftOutQuery: 300,+ datedPoint: 300,+ entity: 120,+ entities: 10,+ internalLinks: 8,+ outboundLinks: 5,+ url: 2048,+ anchor: 120,+ linkSection: 300,+} as const;+const L = BRIEF_V2_LIMITS;++/** A text of version 2: cut to its limit, null or absent for none. */+const v2text = (max: number) =>+ z.preprocess(+ (value) => (typeof value === 'string' ? value.trim().slice(0, max) : value),+ z.string().nullish(),+ );+/**+ * A list of version 2: the items this editor reads, up to its limit; one it+ * can't (a kind from a newer server, an address that isn't http) is left+ * out, not the whole brief.+ */+const v2list = <T extends z.ZodType>(item: T, max: number) =>+ z.preprocess(+ (value) =>+ Array.isArray(value) ? value.filter((v) => item.safeParse(v).success).slice(0, max) : value,+ z.array(item).max(max).optional(),+ );+/** An http(s) address only: a link the Brief tab shows is never "javascript:…". */+const address = z+ .string()+ .trim()+ .max(L.url)+ .pipe(z.url({ protocol: /^https?$/ }));+const linkSchema = z.object({+ url: address,+ anchor: text(L.anchor),+ section: text(L.linkSection).nullable(),+});+export const draftBriefSchema = z.object({goal: text(500),audience: text(500),@@ -60,6 +184,22 @@ export const draftBriefSchema = z.object({keyPoints: z.array(text(500).min(1)).max(8),fanout: text(300).nullable(),platform: text(60).nullable(),+ answer: v2text(L.answer),+ format: z.enum(BRIEF_FORMATS).nullish().catch(null),+ facts: v2list(+ z.object({+ claim: text(L.claim).min(1),+ sourceType: z.enum(FACT_SOURCES),+ source: z+ .object({+ kind: z.enum(SUGGESTION_SOURCE_KINDS),+ ref: text(L.url).min(1),+ label: text(L.claim).min(1),+ })+ .nullable(),+ }),+ L.facts,+ ),}),).max(MAX_BRIEF_SECTIONS),@@ -81,6 +221,35 @@ export const draftBriefSchema = z.object({}).nullable().optional(),+ // A later version reads as the rules it shares with this one.+ version: z.literal(2).optional().catch(undefined),+ tldr: v2text(L.tldr),+ angle: v2text(L.angle),+ proof: v2list(z.object({ kind: z.enum(PROOF_KINDS), what: text(L.proofWhat).min(1) }), L.proof),+ leftOut: v2list(text(L.leftOutQuery).min(1), L.leftOut),+ freshness: z+ .object({+ datedPoint: v2text(L.datedPoint).transform((v) => v ?? null),+ updatedLine: z.boolean(),+ yearInTitle: z.boolean(),+ })+ .nullish()+ .catch(null),+ entities: z+ .object({+ brand: v2text(L.entity).transform((v) => v ?? ''),+ products: v2list(text(L.entity).min(1), L.entities).transform((v) => v ?? []),+ competitors: v2list(text(L.entity).min(1), L.entities).transform((v) => v ?? []),+ })+ .nullish()+ .catch(null),+ links: z+ .object({+ internal: v2list(linkSchema, L.internalLinks).transform((v) => v ?? []),+ outbound: v2list(linkSchema, L.outboundLinks).transform((v) => v ?? []),+ })+ .nullish()+ .catch(null),});/** The brief of the opportunity a draft started from, until the draft has its own. */