docs
    contracts: Overview and contracts
    v2.30.0.md

    @sonordev/contracts

    The rules Sonor's sites, APIs and dashboard have to agree on, as one package. Pure functions and types: no dependencies, no DOM, no network.

    The editorial-media placement resolver recognizes an image's canonical data-sk-editorial-source as well as its displayed src. Responsive image delivery can change URLs without inserting the same approved photo twice.

    pnpm add @sonordev/contracts
    EntryWhat it decidesWho reads it
    @sonordev/contracts/websiteA site's design tokens and what a popup is made of (blocks, limits, the text sanitizer)site-kit renders them, the Sonor API validates every write, the dashboard previews them, Signal's agents send them
    @sonordev/contracts/colorReading a CSS color, WCAG luminance and contrastwebsite, site-kit's brand extraction
    @sonordev/contracts/sitesThe canonical shape of a site host (the multi-site site dimension)every ingest and read that filters by site
    @sonordev/contracts/seo-pagesWhich seo_pages row a path resolves to on a multi-site projectthe Sonor API, Signal, site-kit's sitemap sync
    @sonordev/contracts/seo-metaWhether a title or description is fit to shipsite-kit, Signal's SEO gate
    @sonordev/contracts/llmsllms.txt sanitizers, the word-safe cut they use (clipAtWordBoundary), what each page line says (pickLlmsPageDescription: summary, curated meta, served meta, schema description, then a cleaned scrape; llmsPageTitle, isLlmsListablePage, groupLlmsPages, selectLlmsPages) and the contract versionsite-kit, the Sonor API, Signal's schema validation
    @sonordev/contracts/formsShared form validation helperssite-kit forms, the Sonor API's form intake
    @sonordev/contracts/fleetThe fleet heartbeat's wire shapesite-kit, the Sonor API
    @sonordev/contracts/slotsSlot payload signing, contract v2 (HMAC; Node only). Signs and verifies v1 for older site-kit releasesthe Sonor API, site-kit on the server
    @sonordev/contracts/slot-contentWhat a slot of each kind may hold (normalizeSlotValue), safe links, the rich-text parser. No crypto, so browsers can import itthe Sonor API, site-kit, the dashboard editor
    @sonordev/contracts/site-cacheThe cache tags a site's Sonor fetches carry and the revalidation route's path, payload and pingsite-kit tags and serves the route, the Sonor API calls it
    @sonordev/contracts/site-editEdit on page: the messages between a framed site and the dashboard, trusted origins, how a slot is found on the pagesite-kit's overlay, the dashboard's visual editor
    @sonordev/contracts/portfolioThe case study arc: every section type, the stage each belongs to, the reading order, the narrative that opens each stage and the thread from a challenge to the phase that cleared it and the result that proves it. The verification, the proof for a build a Lighthouse run can't score: checks that each state what they don't cover. Also where a portfolio number comes from and which may headline, and the live-frame messagethe Sonor API, Signal's case-study writer, the dashboard's editor, agency-site-kit
    @sonordev/contracts/proposal-sitemapHow a proposal's site plan counts its pages, when its before-and-after comparison may show, and whether the page counts stated elsewhere in the proposal add upthe Sonor API, Signal's proposal writer, the dashboard's proposal pages
    @sonordev/contracts/voiceThe house voice's contraction rule. findUncontracted and contractText find and apply full forms that should be contractions; findContracted finds the contractions a question-form heading should expandanything that checks or rewrites copy: Sonor's APIs and dashboard
    @sonordev/contracts/error-pageWhether stored text is a rendered error page rather than a page's content, and whether generated copy says the page itself is missinganything that stores page text or writes page copy from it: the Sonor API's page-view and sitemap writers, Signal's metadata generators
    @sonordev/contracts/schema-placeholdersWhether stored JSON-LD carries a template's unfilled slots (example.com URLs, an Organization named "Example", a placeholder phone, [Resident Name], {plan.name}), and the value without themsite-kit's schema output, the Sonor API's schema reads and writes
    @sonordev/contracts/sentencesWhere prose splits into sentences, without dropping a word or ending one at "p.m." (splitSentences)anything that cuts an excerpt, a social slide or a summary out of an article: the Sonor API's carousels, Signal's article pipeline
    @sonordev/contracts/knowledgeWhich Sonor records Signal reads into a project's knowledge, the address each one's knowledge is stored under (portfolio://<id>), and the limits of the call that tells Signal a site's pages changedthe Sonor API sends those calls and Signal answers them
    @sonordev/contracts/business-claimsWhat an outbound email or text may say about a business (checkOutboundCopy), the stored review of what it claimed and when that review is settled, and whether a sent email arrived intact (readBackVerdict)the Sonor API checks again on the bytes it sends, Signal checks what its writers and agents file
    @sonordev/contracts/outreachWhat a segment of outreach is (pitch, sending mailbox, prospect industry), who may turn one on, what a turned-on segment covers, and what a drip's ledger row means for its leadSignal writes and reads segment grants, the Sonor API checks the same grant before it sends
    @sonordev/contracts/page-titlesA page's own name: its title without the brand (titleHead), a readable label from a slug (slugLabel), whether a value is a route placeholder like :slug (isRoutePlaceholder), whether a value is a page's address and not its name (isPageAddress), and whether a stored title is a name when every piece between its pipes is judged (isPageName)Signal's site-architecture writer, the agency site kit's portfolio components
    @sonordev/contracts/broadcast-layoutsWhich Broadcast card layouts are drawn (centered headline, low anchor), which retired IDs still read and what each draws as (normalizeArticleCoverLayout), the Broadcast styles, and the review compositions with the frozen draw that gives each review its own (reviewCardVariationFromDigest)the Sonor API's card renderers and settings, Signal's agent tools, the dashboard's pickers
    @sonordev/contracts/publication-brandingWhat a publication's branding may hold and what a change may set (createPublicationBrandingValidator), how a change merges, the editorial charter, and safe font stacksthe Sonor API stores and resolves it, Signal checks an agent's change before filing it, the dashboard edits it
    @sonordev/contracts/public-url-hostWhich literal hosts are refused as public fetch destinations (isBlockedPublicUrlHost)the Sonor API and Signal's URL validators and network fetchers
    @sonordev/contracts/funnelsIncomplete drafts, launch definitions, command/readiness/receipt schemas, bounded public pages and presentation-only brand overridesSites, APIs, UI and agent adapters share the same rules
    @sonordev/contracts/inboxWhich inbox cards are decisions a bulk action leaves alone (isDecisionCard, DECISION_INSIGHT_TYPES)Signal's inbox decides what "Mark all read" and "Dismiss all" may touch, the dashboard previews the same result before the write
    @sonordev/contracts/crm-dispositionWhat a rep's call outcome (positive, negative or left voicemail) changes on a prospect: the call's outcome and sentiment, the contact's stage, the company's status, today's reminder and outreach (dispositionTransitions), and the reasons a negative outcome carriesthe Sonor API applies an outcome, the dashboard's calling screen offers the same three buttons and reasons, the sales extension stops flipping a company on dial
    @sonordev/contracts/decision-rolesThe part a job title says a person plays in a buying decision (DECISION_ROLES: owner, decision maker, influencer, gatekeeper), read from the title alone by decisionRoleForTitlethe Sonor API's site-people scan and Signal's site-people scout read the same map
    @sonordev/contracts/resonanceCampaign, consent, measurement, plan, mandate and command parsers, types and JSON schemasSites, APIs and the dashboard share the same wire rules
    @sonordev/contracts/resonance-constantsSmall browser-safe measurement wire constantsBrowser readers that don't need campaign schemas
    @sonordev/contracts/signal-experimentsShared Signal experiment create and update validationAPIs and the dashboard use one experiment boundary
    @sonordev/contracts/booking-intakeWhat a booking may ask a guest about their business: whether a type asks, how a company name and a website are cleaned and when they're refused, the guest-facing error text, and the one reader a host sees the answers throughThe booking widget, the Sonor app's booking page, the booking API and everything that shows a booking to a host

    Focus closing artwork

    publication-branding accepts editorial.focusClosingBackground at publication and platform levels. planned_photo keeps the planned closing image; article_atmosphere reuses the article's saved atmosphere with its real author portrait. Omitting the field keeps existing behavior. A patch value of null clears the override and restores inheritance. The article-atmosphere mode requires both saved sources; it doesn't invent a portrait or substitute unrelated artwork.

    Public URL hosts

    isBlockedPublicUrlHost(host) shares the APIs' loopback, private IPv4, link-local, carrier-grade NAT, multicast/reserved IPv4, private IPv6 and local hostname checks. It checks IPv4-mapped and IPv4-compatible IPv6 destinations too, with or without brackets. It uses the standard URL parser, with no Node, DNS or network dependencies. Scoped IPv6 addresses are refused.

    Pass the parsed URL.hostname, so alternate IPv4 spellings such as 127.1 and 0x7f000001 are normalized first, or pass a DNS result's address. This predicate doesn't validate a URL or trim a raw string. A false result isn't proof a destination is public: the fetcher still validates the protocol, credentials and port, checks the DNS addresses it connects to, and applies its redirect policy on each hop. Those network protections stay in the APIs.

    Inbox decisions

    "Mark all read" and "Dismiss all" never touch a decision, so clearing a backlog of notices can't bury an approval waiting on a yes. isDecisionCard(card) is that rule: the Signal API follows it when it writes, and the dashboard follows it to show the result before the write, so the two can't drift apart.

    A card is a decision when it is:

    • an approval (insight type approval_needed, APPROVAL_NEEDED_INSIGHT_TYPE);
    • the ledger's unconfirmed-action card (ledger_unconfirmed_action, LEDGER_UNCONFIRMED_INSIGHT_TYPE): Signal started something it never saw finish, so a person has to check it. It's raised once per claim, so a bulk dismissal that took it would leave nobody told. It carries no proposal, so there's nothing to approve or reject on it; or
    • any card carrying a ledger proposal (data.proposal_id set).

    DECISION_INSIGHT_TYPES is the first two, for the callers that need them as a list (a database filter that leaves them out of a bulk write, for one). isDecisionCard takes any object with an insight_type string and an optional data object, so a stored row and the dashboard's inbox item both fit. It reads data.proposal_id the way the database reads data->>proposal_id: a missing key, a JSON null and a null data mean no proposal, and any other value, an empty string included, means one.

    Call dispositions

    After a sales call a rep taps one of three outcomes. What each one changes on the prospect is written here once, so the API that applies it, the calling screen that offers it and the browser extension that dials from a list can't disagree about what "negative" moves.

    import { dispositionProblem, dispositionTransitions } from '@sonordev/contracts/crm-disposition'
    
    dispositionProblem('negative', { reason: undefined })
    // 'A negative outcome needs a reason: not_a_fit, no_budget, has_agency, wrong_number, do_not_call.'
    
    dispositionTransitions('negative', { reason: 'do_not_call' })
    // {
    //   outcomeType: 'connected', sentiment: 'negative',
    //   contactStage: 'lost', companyStatus: 'not_a_fit',
    //   reminder: 'complete', stopsOutreach: false, suppresses: true,
    // }
    OutcomeCallContact stageCompany statusToday's reminderOutreach
    positiveconnected, positivecontactedcontactedcompletethe drip stops (stopsOutreach)
    negativeconnected, negativelostnot_a_fitcompletenothing, unless the reason is do_not_call (suppresses)
    voicemailleft_voicemail, no sentimentunchangedunchangedsnooze_next_business_daynothing
    • The contract names the moves; the caller makes them. contactStage is a meaning (contacted or lost), not a project's stage key. reminder: 'snooze_next_business_day' leaves the instant to the caller, who knows the project's time zone. A null in any field means leave that thing as it is. A stage a rep picks by hand afterwards, such as qualified, is a separate move that no outcome makes.
    • A voicemail isn't a conversation. It leaves the contact and company alone, and a company only moves to contacted when someone answered. Dialing a number moves nothing either; the outcome does.
    • A negative outcome needs a reason. NEGATIVE_REASONS is the five, in the order a screen offers them: not_a_fit, no_budget, has_agency, wrong_number and do_not_call. NEGATIVE_REASON_LABELS and SALES_DISPOSITION_LABELS say what each button reads.
    • suppresses is for do_not_call only. It means write a suppression for the prospect, which blocks every send on its own. It's separate from stopsOutreach, which stops a drip the prospect is enrolled in, so a caller that wants both for an "asked not to call" outcome stops the drip as well.
    • Check an untrusted outcome first. dispositionProblem(disposition, { reason }) returns one sentence about why an outcome can't be applied, or null: a word that isn't one of the three, a negative outcome with no reason or one that isn't a listed reason, or a reason on an outcome that takes none. isSalesDisposition and isNegativeReason are the plain guards. dispositionTransitions throws a RangeError for something that isn't a disposition, and ignores a reason on any outcome but a negative one.
    • Fresh each time. dispositionTransitions returns a new object per call, so changing one caller's copy never changes the next.

    CRM_DISPOSITION_CONTRACT_VERSION is bumped when an outcome's transitions change incompatibly. The wire values (the three outcomes and five reasons) are stored and sent, so they don't change.

    Decision roles

    When a company's website lists its people, what each job title says about a buying decision has to be read the same way wherever the list is built. decisionRoleForTitle is that rule, written once, so a person can't be an influencer in one scan and an owner in another. The role comes from the title the page gives and never from a model's opinion: a model can find the people, and code decides the role.

    import { DECISION_ROLES, decisionRoleForTitle } from '@sonordev/contracts/decision-roles'
    
    DECISION_ROLES                                          // ['owner', 'decision_maker', 'influencer', 'gatekeeper']
    decisionRoleForTitle('Vice President of Sales')         // 'decision_maker'
    decisionRoleForTitle('Executive Assistant to the CEO')  // 'gatekeeper'
    decisionRoleForTitle('Marketing Coordinator')           // 'influencer'
    decisionRoleForTitle('Principal Engineer')              // null

    The first rule that matches the title decides, in this order:

    OrderThe title saysRole
    1an executive, administrative, office or personal assistant, "assistant to", secretary, receptionist, front deskgatekeeper
    2vice president (VP, SVP, EVP, AVP)decision_maker
    3owner, co-owner, founder, co-founder, proprietor, president, CEO, chief executive, managing, senior, name or equity partner, a lone "Partner", or "Principal" that isn't a jobowner
    4a chief of something else (COO, CFO, CTO, CMO, "Chief ... Officer")decision_maker
    5general manager (or GM), director, operations manager, estimator, estimating manager, project manager, superintendentdecision_maker
    6office manager, administrator, administrative, admingatekeeper
    7marketing, HR, human resources, recruiting, talent acquisition, sales, business developmentinfluencer
    8coordinatorgatekeeper
    • Order is the meaning. "Vice President of Sales" is a decision maker, not an owner because it says president and not an influencer because it says sales. "Marketing Director" is a decision maker, because director comes before marketing. "Marketing Coordinator" is an influencer, because marketing comes before coordinator. "Executive Assistant to the CEO" is a gatekeeper, because the assistant rule comes before the CEO rule.
    • "Principal" is an owner unless it names a job. "Principal" alone is an owner. "Principal Engineer", "Principal Architect", "Principal Consultant", "Principal Designer", "Principal Developer" and "Principal Analyst" say nothing about ownership, so they have no role.
    • A title is read whole. A title that names two jobs isn't split, and the strongest role doesn't win; the first rule above that matches does. "Owner & Office Manager" is an owner. "Receptionist & Owner" is a gatekeeper.
    • "Assistant" alone isn't a gatekeeper. "Assistant Project Manager" and "Assistant General Manager" are decision makers, as the manager rules read them. "Assistant to the Project Manager" is a gatekeeper.
    • No title or no match is null. "Technician", a bare "Manager", "Accounting Manager", an empty string, whitespace, null, undefined and anything that isn't a string all say no role. The map doesn't guess.
    • Case, & and periods don't matter. "C.E.O.", "FOUNDER & CEO" and "Vice-President" read the same as their plain spellings.
    • Only the start of a title is read. Titles come off scraped pages, so the first 200 characters decide and the rest is ignored.

    The four role values are stored and sent, so they don't change. DECISION_ROLES lists them strongest first, which is the order a screen should rank them in.

    Schema placeholders

    schema-placeholders finds the parts of a JSON-LD value that a template left unfilled, so a site never publishes them as the business's identity. Schema extracted from a site's source, where the base URL was a variable, comes back as https://example.com; a template filled in by hand or by an AI can leave "Example", +1-000-000-0000, [Resident Name], {plan.name}, or an object that's only a note about what goes there.

    import { withoutSchemaPlaceholders, describeSchemaPlaceholder } from '@sonordev/contracts/schema-placeholders'
    
    const { value, dropped } = withoutSchemaPlaceholders(storedJsonLd)
    // value: the JSON-LD without its placeholder nodes (the same reference when
    // nothing was found, null when nothing real is left)
    dropped.map(describeSchemaPlaceholder)
    // ['Organization at $: name "Example" is a placeholder name']
    • The unit is the node. The innermost object with an @type or @id (or a top-level or @graph member) whose own values hold the placeholder is dropped whole. Its real siblings, and a real parent it hangs off, stay. A node left with nothing but JSON-LD keywords once its placeholder children are gone goes too.
    • Conservative on purpose. A false positive removes real schema from a live site, so names match whole values only ("Example Plumbing Co" is a real name), domains are only the reserved example domains, phones are only all-zero, sequential, XXX and the 555-0100 to 555-0199 fiction range, and a URI template's {search_term_string} is how schema.org spells a SearchAction, never a finding.
    • Notes. An AI's note key on a real node isn't schema.org vocabulary: it's stripped and the node stays. An object that's only a note is dropped.
    • Pure. The input is never mutated.

    The voice contract

    voice is the contraction rule for written copy, so every app that checks or rewrites it agrees. It's the rule Sonor's article checker has always applied, moved here so it exists once.

    • What it finds. Full forms that should be contractions: "do not" becomes "don't", "it is" becomes "it's", "let us look" becomes "let's look". The first letter's case is kept ("DO NOT" gives "Don't"), and the suggestion always uses a straight apostrophe. There are 36 pairs, and a negation wins an overlap ("we would not" gives "we wouldn't", not "we'd not").
    • What it leaves alone. A pronoun and verb ("it is", "we are", "you will") at the end of a clause ("until it is."), or before "and", "or", "but" or "nor" ("what it is and why"). Negations skip that guard: "We do not." still becomes "We don't.". "can not" before "only" ("it can not only save time"). "what is" when the next ".", "!" or "?" after it turns out to be a "?", and "What Is" at the start of a line when you mark the text as a heading. "let us" unless it starts a sentence and the next word is one of look, start, begin, consider, turn, see, review, compare, break, dig, recap, unpack, explore, examine, revisit, focus, go, talk, move, "get started", "step back" or "zoom out" ("let us know" and "let us help" mean "allow us"). "have" and "has" on their own ("we have a team") are never touched, though "have not" and "has not" still contract ("haven't", "hasn't").
    • Lines. Text is read one line at a time: split on "\n". A "\r" right before a "\n", or at the very end of the text, is part of the line ending; any other "\r" is ordinary text. If you've already split the text into lines yourself and a line keeps a final "\r" you want read as text, replace it with VOICE_MASK first. Nothing matches across a line break, and the end of a line ends a clause. Every hit's index is an offset into the whole string you passed in.
    • The other direction. findContracted finds the contractions a question-form heading or FAQ question should spell out ("What's" becomes "What is"). It only reports; whether a text is a question is the caller's call, and a caller shouldn't apply these blindly.

    What the caller does:

    • Mask what isn't prose. Code, quotations and link destinations shouldn't be rewritten. Pass their [start, end) positions as protectedRanges, or replace them with VOICE_MASK yourself. Every protected character is masked except "\n" and "\r", which stay as they are, so a protected line break still ends its line. A masked span separates words, can't sit inside a phrase, and counts as text that follows. Ranges can arrive in any order, and overlap or touch. An infinite bound clamps to the start or end of the text, and an empty or out-of-text range is ignored. A malformed range (NaN, not a number, start after end), or a truthy value that isn't an array, protects the whole text, so a bad range never causes code to be rewritten. A falsy value means no ranges.
    • Pass a string. Anything else (a number, an object, null) is read as no text: nothing is found and contractText hands it back unchanged.
    • Pass a bare heading. Set titleLike for a heading or title, with the # and list markers already blanked to spaces.
    import { contractText, findUncontracted } from '@sonordev/contracts/voice'
    
    contractText('We do not ship on Sundays.')
    // "We don't ship on Sundays."
    
    findUncontracted('We do not ship on Sundays.')
    // [{ index: 3, length: 6, match: 'do not', suggestion: "don't" }]

    Known limits

    The rule is plain on purpose, and these are what it does today. Each one is pinned by a test, so changing it later is a visible change.

    • "not" before "only". Only "can not only" stays full. "You must not only wait" becomes "You mustn't only wait", "will not only rise" becomes "won't only rise", and "cannot only" becomes "can't only", which reads differently.
    • "need" as a noun. "The need not being met" becomes "The needn't being met", and "must not" and "need not" contract wherever they appear.
    • "let us" by position, not meaning. "Let us look at your account, please" becomes "Let's look at your account, please". "Let us try again", "let us walk through the plan" and any sentence that opens with a bracket, a quote or a dash ("(Let us look at it.)") stay full.
    • Question detection is the first "." "!" or "?" on the line. A decimal, a domain or an initial hides the "?": "what is 3.5 percent?" becomes "what's 3.5 percent?". Only "what is" has a question guard: "Who is on the team?" becomes "Who's on the team?". A question that wraps onto the next line isn't seen.
    • A line break ends a clause. In a hard-wrapped paragraph, "we think it is" at the end of a line stays full.
    • A clause end is an inventory of characters. ".", ",", ";", ":", "!", "?", ")", "]", "}", a straight double quote, a curly closing double or single quote, an ellipsis, an em dash, an en dash and "-" end a clause; a straight apostrophe doesn't, so "Say 'it is' now." becomes "Say 'it's' now.", and a hyphen inside a word counts ("it is-fine" stays full).
    • A masked "]" reads as text that follows. A link whose anchor text ends a clause is contracted when you protect the whole "](destination)": "Meet who we are." becomes "Meet who we're.".
    • Only spaces and tabs join the words of a pair. A non-breaking space between "do" and "not", or a line break, keeps the pair from matching.
    • The other direction is plain suffix rules. findContracted always expands "'s" to "is" ("It's been" suggests "It is", not "It has"), "'d" to "would" ("She'd left" suggests "She would", not "She had"), and "ain't" like any other "n't" word ("ai not"). Only the first letter's case carries over ("WHY IT'S" suggests "IT is"). Treat its suggestions as prompts for a person, not as edits to apply.
    • Case. Only the first letter's case carries over: "IT IS FINE." becomes "It's FINE.".
    • The heading rule is first-on-the-line. "What Is" keeps its form only when nothing but spaces, "*", "_" and masked text comes before it on its line, and only when titleLike is set and the markers are already blanked. The check is on the "what is" pair in any case, so "what is local seo" is kept too.
    • "let us" opens a sentence after a full stop, "!", "?" or ":". Spaces, "*", "_" and masked text before it are skipped, so "Now: let us look at it." contracts.

    The proposal-sitemap contract

    A website proposal's site plan lists the pages a build delivers: core pages (Home, About, Contact), top-level pages, and the pages under them. Its numbers are what a buyer reads first, so they're computed here and never taken from prose.

    • countSitemapPlan(plan) returns core, architecture (the plan's own pages), articles (existing posts re-published with the build), full (all three), existing (pages carried over) and added (new pages). Each address counts once: core pages first, then each top-level page and the pages under it. A row without a slug always counts.
    • sitemapTransformation(plan) returns the before-and-after comparison to show ({ before, after }), or null. It shows only when the plan states today's count and the build is bigger. A rebuild that keeps the same pages isn't a before and after, so an after-count of zero, or one no bigger than today's, hides it.
    • normalizeSitemapLabels(labels) keeps the words a plan may use for its own pages when they aren't services sold to industries: architecture (the heading), pillar (a top-level page) and child (a page under one). Each is one line of 1 to 40 characters.
    • proposalPageCountIssues(sections) lists the page and URL counts a proposal states in its headline, summary, pricing and plan copy that match nothing the plan or its measured evidence adds up to. describePageCountIssue(issue) puts one in a sentence for the person reviewing it.
    import { countSitemapPlan, proposalPageCountIssues } from '@sonordev/contracts/proposal-sitemap'
    
    countSitemapPlan({
      corePages: [{ slug: '/' }, { slug: '/about/' }, { slug: '/locations/' }],
      pages: [{ slug: '/locations/', children: [{ name: 'Springfield' }, { name: 'Shelbyville' }] }],
    }).full
    // 5: the top-level /locations/ page is the core one, counted once
    
    proposalPageCountIssues([
      { type: 'GlassHero', props: { stats: [{ value: '12', label: 'pages rebuilt' }] } },
      { type: 'SitemapPlan', props: { pages: [{ slug: '/' }, { slug: '/about/' }] } },
    ])
    // [{ section: 'GlassHero', field: 'stats[0]', claimed: 12, unit: 'page', text: '12 pages', planned: 2 }]

    It reads "N pages", "an N-page site", "N existing URLs" and up to three words between the number and "page" or "URL". A count written in words ("five pages") isn't read, and a count of pages that aren't in the plan (say, a competitor's) is reported like any other; the issues are for a person to look at, not edits to apply.

    The error-page contract

    A page's stored text is whatever a browser or crawler rendered. Visit a URL while it's briefly broken and the error page's words become that page's content, and any title, description or summary written from that content describes a working page as broken. error-page is how writers refuse both halves of that.

    • looksLikeErrorPage(text, wordCount?) is true when the text is a rendered error page: a 404 in its common wordings ("404", "This page could not be found", "Page not found"), a framework error ("a client-side exception has occurred", "This page couldn't load", "Internal Server Error", "Cannot GET /x"), a status page ("502 Bad Gateway", "HTTP Status 404"), a "something went wrong" or "temporarily unavailable" screen, or a maintenance notice. It reads how the text opens (the first 300 characters), decodes HTML entities, and doesn't depend on word boundaries, because scraped text runs elements together ("404This page could not be found."). Text up to 120 words is checked for every wording, though the loosest ones (a 404 glued to its copy, "refresh the page and try again", a route's " not found") only read the first 60 or 40 words; up to 400 words only the check for how it opens after a meta description and skip link applies; beyond that it's prose. A phone number, room number or street address that starts with 404 isn't an error page, and neither is a help page that only describes an error ("how to fix a 404 error", "if something went wrong"). Pass the word count of the text itself, never a whole page's count (a browser's includes the navigation and footer and can hide a short error state): a supplied count can only raise the count the check uses.
    • usablePageText(text, wordCount?) returns the text, or null when it's an error page. It's what a model should be shown as "the page's content".
    • findErrorPageClaim(copy, pageText?) returns the phrase in generated copy that says the page itself is missing or unavailable ("Page Not Found", "the pricing page is currently unavailable", "returns a 404", "a page-not-found message"), or null. Copy about something unavailable on a working page ("the patio is closed on Mondays", "tours are paused for winter") isn't a claim about the page. Pass the page's own text and a phrase the page really says is allowed, so a guide to fixing "page not found" errors can be titled that way; the text of an error page is never accepted as that exemption. describesErrorPage is the boolean form.
    • findPageCopyClaim(fields, pageText?) runs findErrorPageClaim over every string in a set of fields (a title, a description, keywords, a JSON-LD object; any object or class instance) and returns the first { field, phrase }, or null. It's how a writer or a reader judges a whole draft in one call. It reads at most 2,000 strings, 8 levels deep and 100,000 characters in all, and each string's first 5,000 characters, so a hostile record can't make it slow.
    import { describesErrorPage, findPageCopyClaim, usablePageText } from '@sonordev/contracts/error-page'
    
    usablePageText('404This page could not be found.') // null: don't generate from it
    usablePageText('Weekly mowing for property managers.') // the text
    
    describesErrorPage('Commercial Mowing Page Not Found | Example Co') // true: don't ship it
    describesErrorPage('Seasonal tours are paused until April.') // false
    
    findPageCopyClaim({
      title: 'Commercial Mowing | Example Co',
      schema: { '@type': 'WebPage', description: 'This URL currently returns a 404.' },
    })
    // { field: 'schema', phrase: 'returns a 404' }

    A text-only check can't prove a page failed. Where you observed the HTTP status, require 400 or more as well and use this as the fallback; the header of src/contracts/error-page.ts lists the other known limits.

    The sentences contract

    Cutting an excerpt, a slide or a summary out of an article starts with finding where its sentences end, and the usual one-liners for that get it wrong. text.match(/[^.!?]+[.!?]+(?=\s|$)/g) can't end a match at the first period of "9 p.m.", so it skips ahead and drops every word before the next match: "We open at 9 p.m. daily." comes back as "m." and " daily.". Without the lookahead, text.match(/[^.!?]+[.!?]+/g) cuts "9 p.m." into "9 p." and "m.". Both also drop any text after the last full stop. splitSentences is the one splitter to use instead.

    • Lossless. Joining the result with spaces gives back every word of the input, in order. Nothing is dropped, added or reordered, and each sentence comes back trimmed and non-empty.
    • Where a sentence ends. At ., ! or ? (and any closing ", ', ”, ’, ) or ] after it) followed by whitespace and then A to Z or 0 to 9, optionally after one opening ", ', “, ‘, ( or [. Never before a lowercase word or a symbol. Only ASCII capitals count: a sentence that opens with an accented, Greek or Cyrillic capital, a currency sign, #, @ or an emoji stays joined to the one before it.
    • Where it doesn't. After a dotted abbreviation made of letters ("p.m.", "U.S.", "e.g.", "Ph.D."), a single letter of either case (an initial like "J.", but also "Plan A."), or a short form on its list: titles, company suffixes, months, street suffixes and days of the week ("Dr.", "Inc.", "Sept.", "Ave.", "Mon."). A few of those only count when capitalized, because the lowercase word ends sentences too ("Mon." is a day, "the sun." isn't). A label with a number after it stays together ("No. 5", "Fig. 2", "Ste. 200"), while "No." before anything else ends a sentence. A list number ("1.", "Step 2.", "Do three things: 1.") stays with its item.
    • ! and ?. An abbreviation only holds back a period. "Open until 9 p.m.? Yes!" is two sentences, under the same start-of-sentence rule as above.
    • Prices, versions and web addresses ("$4.50", "v2.1", "example.com", "info@example.com") aren't abbreviations: a sentence can end after them.
    • Never a bare mark. A piece with no letter in it ("...", "?!", "1.") isn't a sentence. It joins the next one.
    • Prose, not layout. A newline or a list marker doesn't start a new sentence by itself. If lines or paragraphs matter, split on those first and call splitSentences on each one.
    • Empty is []. Empty, whitespace-only, null and undefined input all give an empty array, never null, so callers can iterate without a guard.
    • Linear time. One pass over the text. A megabyte takes milliseconds, however many abbreviations, stops or quotes it holds.
    import { splitSentences } from '@sonordev/contracts/sentences'
    
    splitSentences('We open at 9 a.m. daily. Walk-ins are welcome.')
    // ['We open at 9 a.m. daily.', 'Walk-ins are welcome.']
    
    splitSentences(excerptSource).slice(0, 2).join(' ')
    // the first two sentences, whole

    Known limits. Where it can't be sure it leans toward joining, because a sentence that runs long costs less than a lost word, and a caller that caps length should cut at a word. It can't tell an abbreviation that ends a sentence from one that doesn't ("Contact Acme Inc. Our team ..." and "... in Washington, D.C. Residents ..." each stay in one piece), it only knows English short forms (a period after one it doesn't know ends a sentence, so "Sra. García" splits after "Sra."), and the next sentence has to start with A to Z or a digit.

    The knowledge contract

    Signal answers questions about a business from what it has read: the passages of the site's live pages, and the business's own records in Sonor. The Sonor API tells Signal when either changes, and Signal indexes it. Both have to agree on which records count, how a stored row says which record it came from, and how big a page sync may be. If they don't, a record the API announces is refused, or a row Signal wrote reads as a page. Anything that shows what Signal has read, like the dashboard's view of it, reads stored addresses by the same rules.

    • Record kinds. KNOWLEDGE_RECORD_KINDS is portfolio (case studies), proof (proof records), faq (managed FAQs), review, article and offering (commerce offerings), in the order the dashboard lists them. isKnowledgeRecordKind(value) is true only for one of them, spelled exactly.
    • Addresses. A record's knowledge is stored under <kind>://<id>, and any further chunk under <kind>://<id>#<anchor> (an article indexed in full is split by heading). knowledgeRecordSourceUrl(kind, id, anchor?) builds one and knowledgeRecordPrefix(kind) gives the <kind>:// every address of that kind starts with. The id is the record's UUID, and the caller checks it: one holding #, ?, / or whitespace can't be read back. A page's passages are stored under the page's https URL instead, so the scheme alone tells a record's rows apart. The content type can't: an article's record has the same type as the page passages beside it, because a live article is a page on the site.
    • Reading an address. knowledgeRecordKindOf(url) is the kind by scheme alone, or null for a page passage, an older page summary or a note. It's the test for whether a row belongs to a record. knowledgeRecordRefOf(url) is { kind, id } for the record an address names, or null when it names none; the id runs to the first #, ?, / or whitespace. Both ignore the scheme's case and surrounding whitespace.
    • The legacy offering address. Offerings were once stored under commerce://offering/<id> (legacyOfferingSourceUrl(id)). Nothing writes it now, and Signal switches each such row off the next time its offering syncs. Until then knowledgeRecordRefOf names the offering, while knowledgeRecordKindOf doesn't count the row as a record's.
    • A page sync. One call names at most KNOWLEDGE_SYNC_MAX_PAGES (500) pages, each a KnowledgePageChange ({ site?, path, removed? }) with a path of at most KNOWLEDGE_SYNC_PATH_MAX_LENGTH (2048) characters and a host of at most KNOWLEDGE_SYNC_SITE_MAX_LENGTH (253). Signal refuses a longer list, path or host outright, so a sender keeps within them before it calls. Signal applies every removal in the call, then reads the changed pages in the order given, as many as it reads in one call; the rest wait for its nightly sweep. So put removals first, then the pages that matter most, and cut the list after ordering it.
    import {
      KNOWLEDGE_SYNC_MAX_PAGES,
      knowledgeRecordRefOf,
      knowledgeRecordSourceUrl,
    } from '@sonordev/contracts/knowledge'
    
    knowledgeRecordSourceUrl('faq', id)
    // 'faq://<id>'
    
    knowledgeRecordRefOf('article://<id>#part-2')
    // { kind: 'article', id: '<id>' }
    
    const batch = [...removed, ...changed].slice(0, KNOWLEDGE_SYNC_MAX_PAGES)
    // removals first, so the cut drops changed pages before any removal

    The business-claims contract

    An email that goes out under a business's name can't promise what the business never said. Every writer (a model, an agent, a person's own template) and every sender checks copy with the same function, so a sentence refused where it's written is refused again where it's sent.

    import { checkOutboundCopy } from '@sonordev/contracts/business-claims'
    
    const check = checkOutboundCopy(
      { subject: 'A quick idea for your site', body, format: 'text', channel: 'email' },
      { author: 'signal', rules, claims },
    )
    check.blocking // refused outright
    check.flags    // needs a person's look before it sends
    check.style    // house style, never blocks
    check.plain    // the body as the reader sees it
    • Who wrote it. author is 'signal' (copy a model wrote), 'agent' (an agent's own copy, the strictest set) or 'operator' (a person's fixed template). Operator copy gets the blocking set only. An author it doesn't know is checked as an agent.
    • Blocking. An empty subject or body, a merge tag that never rendered ({{first_name}}, [Company]), a claim no business may make (PLATFORM_BANNED_CLAIMS: guaranteed rankings, top-3 or map pack spots or results, "#1 on Google", "risk free", fake scarcity, implied Google endorsement, and any promise that they'll pay nothing or get their money back), the business's own banned claims and the pitch's forbidden phrases, a price that matches none the business publishes, and a word that mixes alphabets. An agent's own copy is also refused for dashes and for unsafe HTML.
    • Flags. A price it can't verify, a number nothing backs, a citation that doesn't match what it cites, a banned claim that a negation takes back, a note the writer left to itself, and a number an agent took from its research. Research about the recipient backs a number only in a sentence about the recipient (claimSubjectOf). It never backs one about the sender. A clause that names nobody ("the measured performance score is 61") counts as the recipient's only when their research carries that number, and a subject line may repeat a number the body backs that way.
    • Rules come from the caller. rules carries the business's published prices, banned claims, forbidden phrases, verified facts and its own names, resolved before the call, so no business data lives in the package. Price and banned-claim rules run only when rules is set.
    • Findings are stable. Each finding's id is a hash of its code, its sentence and the match (outboundFindingId), so a person's acknowledgement of one sentence never carries over to a rewritten one.
    • The stored review. OutboundClaimReview is what was checked, against which rules, and which flags a person acknowledged. readOutboundClaimReview(value) reads a stored one defensively, and unsettledFlags(review) lists the flags nobody has settled yet. A sender refuses while that list isn't empty.
    • The refusal. outboundRefusalMessage(findings) is the one wording for what's wrong and how to fix it, numbered and plain.
    • Read-back. readBackVerdict(intended, read) compares the email a mailbox says it sent with the one that was meant: verified only when the whole intended text arrived (a footer added after it is fine), otherwise empty, mismatch or unreadable.
    • Shared helpers. The same normalizers the checker uses are exported for anything that grounds a quote, price or number in a source (normalizeForQuote, quoteFoundIn, checkQuotedPrice, numbersGrounded), plus decodeHtmlEntities, removeDashes, outboundPlainText and isWriterNote.

    BUSINESS_CLAIMS_CONTRACT_VERSION is bumped when the stored review's shape changes incompatibly.

    The outreach contract

    Outreach earns the right to send on its own one segment at a time. A segment is one pitch, sent from one mailbox, to one kind of business. Both the API that writes outreach and the one that sends it read segments by these rules, so they can't disagree about what a person turned on.

    • Segment keys. outreachSegment({ source, narrativeId, mailboxId, industry }) builds one: drip:<pitch id>@<mailbox id>|<industry> for a drip, or mcp:-|<industry> for an agent's one-off email, which is counted but never turned on. parseOutreachSegmentKey(key) reads a key strictly and returns null for anything else, so a caller-chosen key never reaches storage. isGrantableSegmentKey(key) is true only for a drip segment with a known industry. outreachSegmentLabel is the one human label.
    • Industry. prospectIndustry(prospect) picks the prospect's industry and normalizeIndustry(value) folds it to one key ("Roofing Contractors" and "roofing" are the same segment). A prospect with none is UNSPECIFIED_INDUSTRY, and those always wait for a person.
    • The pitch's fingerprint. narrativeFingerprint(narrative) hashes the pitch fields only (NARRATIVE_PITCH_FIELDS). Rewriting the pitch changes it and lapses the segment. Renaming it, switching it off and on, or tightening its forbidden phrases doesn't.
    • States. SEGMENT_STATES is ungranted, granted, paused (it stopped itself), lapsed (the pitch changed) and revoked.
    • Grants. SegmentGrant is a person's standing approval of one segment, either from approving its first email unedited (first_email) or by accepting it once the segment earned it (earned). readSegmentGrants(settings) and activeSegmentGrant(settings, key) read them. segmentGrantCovers(grant, row) says whether a grant covers one email: not when it's revoked or paused, names someone else, was written before the grant, has a different pitch fingerprint or sends from another mailbox.
    • Evidence. grantEvidenceRefusal(grant, rows, scope) checks the approvals a grant stands on and returns why it can't be trusted, or null. A grant that fails counts as no grant, so one written into settings by hand never sends anything.
    • The bar. GRADUATION_BAR is the one track record that earns sending without a click per email: at least 5 measured, at least 70% of them won, and none that went wrong without being undone. An earned grant needs GRADUATION_BAR.minMeasured approvals on record.
    • Who may turn one on. segmentGranterEligible(roles): never an agent; otherwise an owner or admin of the project, its organization or the agency that manages it.
    • Company domains. PUBLIC_MAILBOX_DOMAINS and isPublicMailboxDomain(value): free mailbox providers, which never count as a company's domain.
    • A drip's row. dripRowDisposition(row) says what a drip's ledger row means for its lead: live, sent, retire, declined or refile. A status it doesn't know reads as live, so a lead is never written to twice.

    OUTREACH_CONTRACT_VERSION is bumped when a grant's shape or the segment key changes incompatibly.

    The page-titles contract

    A page's title is its own name followed by the brand: "AC Repair | Example HVAC". A list of pages, a sitemap or a case study wants the name alone, and the usual shortcuts get it wrong. Capitalizing each word of a slug turns "ac-replacement" into "Ac Replacement", "faq" into "Faq" and "smith-and-smith" into "Smith And Smith". A title with a stray second pipe ships as "Loans | | Brand". A title that is really the page's path ships as a page name. titleHead, slugLabel, isRoutePlaceholder, isPageAddress and isPageName are the one set of rules, so every list reads the same.

    import { isPageAddress, isPageName, isRoutePlaceholder, slugLabel, titleHead } from '@sonordev/contracts/page-titles'
    
    titleHead('FHA Home Loans | | Example Mortgage')           // 'FHA Home Loans'
    slugLabel('/services/hvac-repair/')                         // 'HVAC Repair'
    isRoutePlaceholder('/floor-plans/:slug')                    // true
    isPageAddress('services/ac-repair', '/services/ac-repair')  // true
    isPageAddress('AC Repair', '/services/ac-repair')           // false
    isPageName('1 Bedroom | 1BR 1BA', '/floor-plans/one-bed')   // true
    isPageName('Studio | /floor-plans/studio', '/floor-plans/studio') // false
    • titleHead(title) is the title without its trailing " | Brand". Only the last " | " segment is the brand, so "1 Bedroom | 1BR 1BA | Example Apartments" is "1 Bedroom | 1BR 1BA". The cut is the one seo-meta's stripTitleSuffix makes.

    • Stray pipes are repaired first. A run of pipes with only whitespace between them is one separator ("Roof Repair | | Example Roofing" reads as "Roof Repair | Example Roofing"), and a leading or trailing pipe is dropped ("Pricing |" is "Pricing"). Whitespace is trimmed and collapsed.

    • No separator, no cut. A title without one comes back as written. It can't tell a brand from a name, so a title that's only a brand stays that brand, and a dash ("AC Repair - Example HVAC") isn't a brand separator. Empty, whitespace-only, null and undefined input give "".

    • Apply it once. A title with two or more separators loses one segment per call, so the output of titleHead isn't a title to run it on again.

    • slugLabel(input) is for the rare label that has to come from a slug, a file name or a path because the page has no title. Prefer titleHead: a title is what the page was written with, and a slug is a guess at it.

    • Which part it reads. The last non-empty path segment, after dropping a https://host origin, a query or a hash, and a trailing .html, .htm, .php or .aspx. %-escapes are decoded without ever throwing: a malformed one stays as written. Words split on -, _, + and whitespace.

    • How each word is cased, by the first rule that fits:

      • an acronym is upper case: ac, ai, aeo, api, cms, crm, faq, fsbo, hvac, jl, llc, llp, mls, pdf, pllc, ppc, roi, seo, ui, ux and usa. The plural faqs is "FAQs";
      • a stand-alone two-letter US state or DC code is upper case ("covington-ky" is "Covington KY"). Codes that are ordinary words as often as not stay words: in, or, me, hi, id, la, ma, pa, al, de and co. mt goes by its position: as the last word it's Montana ("billings-mt" is "Billings MT"), and with a word after it it's Mount ("mt-adams" is "Mt Adams", "academy-of-mt-adams" is "Academy of Mt Adams"). us isn't a state: "about-us" is "About Us";
      • a word with a digit keeps its case, and gains a capital only when it starts with a letter: "c1" is "C1", "075ct" and "1003" stay;
      • a small word is lower case unless it's first: a, an, and, at, by, for, in, of, on, or, the, to, vs, with;
      • anything else gets a capital first letter and lower case after it. The first word of a label is always capitalized, and an acronym stays upper case there.
    • Nothing to label gives "". "", "/", "?x=1" and a bare origin all give an empty string. Naming the home page is the caller's job.

    • Stable. Running a label back through slugLabel gives the same label, as long as its words follow the rules above. A brand's own capitalization ("DeWalt") is the exception.

    • isRoutePlaceholder(value) is true when the value, or any "/"-separated segment of it, is a framework route placeholder: :slug, :Slug, :id?, [slug], [...rest] or [[...rest]]. A placeholder is a single token with no spaces, so ordinary text that contains a colon or a bracket isn't one ("Update: new hours", "FAQ / [draft] notes"). Nullish and empty values are false.

    • isPageAddress(value, path?) is true when the value is a page's address and not its name. That's what a title becomes when a writer saved the path where the title belonged. It's true for:

      • a path, or anything that starts with a slash ("/services/ac-repair", "//example.com/services");
      • an absolute URL ("https://example.com/services");
      • a host and a path with no scheme and no spaces ("example.com/services", "www.example.co.uk/floor-plans/", "example.com:8080/x"). A browser shows an untitled page's address this way. A bare host ("example.com") isn't an address, and neither is text that has a slash in it ("Heating/Cooling", "24/7 Emergency Service") or a number that looks like a host ("4.5/5", "v2.10/changelog"), because a host ends in a letters-only domain;
      • a route placeholder, the way isRoutePlaceholder reads one;
      • the page's own path written without its slashes, when you pass path: "services/ac-repair" and "services/ac-repair/" for "/services/ac-repair", "faq" for "/faq". Leading and trailing slashes come off both sides, and the comparison is exact: "ac-repair" isn't the address of "/services/ac-repair", and "Pricing" for "/pricing" is a name where "pricing" is the path.

      The value is trimmed first. Empty, whitespace-only, nullish and non-string values are false: they're nothing, not an address, and what an empty title means is the caller's to say. It judges one string, so cut a brand tail first and ask about what's left: isPageAddress(titleHead(title), path).

    • isPageName(title, path?) is true when a stored title is a real name for the page: something is left once the pipes are set aside, and no piece between them is a page's address, as isPageAddress reads one (given the page's path). It's the rule for a title that's printed whole. A writer that stores a name and a reader that prints it both ask it, so they can't disagree about a path, a URL or a placeholder behind a pipe.

      • Every piece is judged, the first and the last included. "Floor Plans | /floor-plans/studio", "Floor Plans | :slug", ":slug | Example Apartments" and "Floor Plans | example.com/floor-plans/studio" aren't names, and neither is the unspaced "Floor Plans|/floor-plans/studio", because it prints with its path in it. The split is on the bare |, and the empty pieces of a stray pipe ("| Studio |", "Studio | | Example Apartments") are left out.
      • A name with a pipe in it stays a name while every piece is text: "1 Bedroom | 1BR 1BA", "Heating/Cooling | Update: new hours".
      • Nothing left isn't a name. A title that's only pipes, an empty or whitespace-only title, null, undefined and a non-string are all false.
      • Cut the brand tail first. It judges the title it's given, tail included. A writer asks about what it stores: isPageName(titleHead(title), path). A path that's only in the cut tail isn't stored, so it doesn't count against the page.

    Known limits. A slug carries no capitalization or punctuation, so "DeWalt" reads "Dewalt", "joes-pizza" reads "Joes Pizza", and an index.html reads "Index". A slug with mt anywhere but last reads it as Mount ("billings-mt-homes" reads "Billings Mt Homes"), since position is all that tells Montana from Mount. A bare [draft] is a placeholder, because nothing tells it from [slug]. Only the pipe is a brand separator, the way stripTitleSuffix has it.

    The broadcast-layouts contract

    A Broadcast post is centered or low, never top-aligned. The title-on-top composition was retired, but posts and settings saved before that still name it, so there are two lists: every ID a stored row may carry, and the IDs that are drawn. A retired ID keeps validating and draws as its replacement.

    import { createHash } from 'node:crypto'
    import {
      ARTICLE_COVER_LAYOUTS, CARD_LAYOUTS, isCardLayoutId, normalizeArticleCoverLayout,
      normalizeReviewCardVariation, reviewCardVariationFromDigest, reviewCompositionSeed,
      REVIEW_PHOTO_PRESENTATIONS, isReviewPhotoPresentation,
    } from '@sonordev/contracts/broadcast-layouts'
    
    CARD_LAYOUTS                                // ['stacked', 'headline', 'split', 'anchor']
    ARTICLE_COVER_LAYOUTS                       // ['headline', 'anchor']
    isCardLayoutId('stacked')                   // true: an old post still reads
    normalizeArticleCoverLayout('stacked')      // 'anchor'
    normalizeArticleCoverLayout('split')        // 'headline'
    normalizeReviewCardVariation('spotlight')   // 'signature'
    REVIEW_PHOTO_PRESENTATIONS                 // ['background']
    isReviewPhotoPresentation('background')    // true
    isReviewPhotoPresentation(null)            // false: a clear operation is handled by the caller
    
    // On the server: a review's composition, stable for its identity.
    const digest = createHash('sha256').update(reviewCompositionSeed(projectId, reviewId)).digest()
    reviewCardVariationFromDigest(digest)       // 'signature' or 'frame'
    • CARD_LAYOUTS is every layout ID a stored row, a saved setting or a request may carry, retired ones included. ARTICLE_COVER_LAYOUTS is what's drawn and offered. Both orders are part of the contract: rotation picks by index, and a refusal lists the IDs in order.
    • RETIRED_CARD_LAYOUTS maps each retired ID to what it draws as (stacked to anchor, split to headline). normalizeArticleCoverLayout applies it and returns anything else as it came, so a caller still checks isCardLayoutId (or passes auto) before rendering. Only an own key of the map is retired, so "toString" isn't.
    • CARD_LAYOUT_LABELS names the drawn layouts and CARD_LAYOUT_OPTIONS serves them Anchor first.
    • PUBLICATION_CARD_LAYOUTS is what a publication-branding change may choose (auto or a drawn layout). SAVED_PUBLICATION_CARD_LAYOUTS is what a saved profile may carry (auto or any readable ID).
    • BROADCAST_STYLES is the shared look for article, review and generated post artwork (glass by default).
    • REVIEW_CARD_VARIATIONS is the review compositions drawn, Signature and Framed. normalizeReviewCardVariation draws a retired spotlight as Signature and anything unknown as the default, Signature. isReviewCardVariation is the strict check for a request that must name a drawn one.
    • REVIEW_PHOTO_PRESENTATIONS lists explicit per-review photo choices: background places the primary photo behind the review text. The ReviewPhotoPresentation type and isReviewPhotoPresentation guard share that supported set. The guard accepts explicit values only; input consumers handle omission (preserve a saved choice) and null (clear it to automatic) separately. Existing records without a choice keep their deterministic composition; presentation doesn't change the seed or variation draw.
    • A review's composition never moves. It's drawn from the SHA-256 of reviewCompositionSeed(projectId, reviewId), never from anything a person can edit. reviewCardVariationFromDigest reads the first four bytes against the frozen v1 list (REVIEW_CARD_VARIATION_V1_DRAW); a review that drew the retired Spotlight redraws between the drawn two from the next four bytes, so no other review changes. The hash stays with the caller, so the contract needs no crypto.

    Changing a list's order or the v1 draw list reshuffles stored posts, so treat both as a breaking change and bump BROADCAST_LAYOUTS_CONTRACT_VERSION.

    The publication-branding contract

    A project's publication branding is one stored profile: identity (names, publisher, logos), colors, type, editorial direction (the Broadcast style, the card layout, the charter) and newsletter settings, each of which a channel (email, social, a single network) can override. The API that saves it and the agent tools that propose changes to it have to agree exactly on what's valid, so the validator lives here once.

    import { createPublicationBrandingValidator } from '@sonordev/contracts/publication-branding'
    import { isBlockedPublicUrlHost } from '@sonordev/contracts/public-url-host'
    
    // Bind it once to the same literal-host policy both APIs use.
    const branding = createPublicationBrandingValidator({ isBlockedHost: isBlockedPublicUrlHost })
    
    branding.validatePublicationBrandingPatch({ colors: { primary: '#ABC' } })
    // { colors: { primary: '#aabbcc' } }
    branding.validatePublicationBrandingPatch({ editorial: { cardLayout: 'stacked' } })
    // throws: publication_branding.editorial.cardLayout: choose auto, headline, anchor
    branding.mergePublicationBrandingPatch(saved, { identity: { logos: { dark: null } } })
    // saved, minus that one override
    • createPublicationBrandingValidator({ isBlockedHost }) returns the validator. A URL leaf must be a public HTTPS URL without credentials; whether its host is private (loopback, a LAN range, link-local, localhost) uses the injected guard. Both APIs pass the shared public-url-host predicate, which doesn't need Node. It gets new URL(value).hostname, so IPv6 keeps its brackets. DNS and connection checks remain the responsibility of the fetcher.
    • validatePublicationBranding reads a whole saved profile. validatePublicationBrandingPatch reads a change: a leaf set to null clears that override, and a card layout must be one that's drawn today. A saved profile may still name a retired layout.
    • mergePublicationBrandingPatch(saved, change) applies a change leaf by leaf and prunes containers it empties. No saved profile reads as { version: 1 }, and a change that sets nothing returns the profile as it was. mergePublicationBrandingLayers is the same leaf-wise merge for resolving layers.
    • Publication logo roles are optional identity.squareLogoUrl and identity.fullLogoUrl. Use the first for a square publication mark and the second for its full/display logo. Both follow the same URL policy as other logo fields. Set either leaf to null in a patch to clear that override and restore inheritance. identity.logos.default/light/dark remain theme variants, identity.wordmark stays text, and publisherLogoUrl is publisher attribution. Omitting the new leaves preserves existing profiles; the validator doesn't infer a square mark or select an effective display logo.
    • Refusals name the field. A PublicationBrandingValidationError carries the path (publication_branding.platforms.email.colors.primary) and says what's allowed. A charter set on a channel override is a plain Error: a charter belongs to the publication or a site.
    • The editorial charter (parsePublicationCharter, parseSiteCharters, publicationCharterFor, publicationCharterContext) is data-only direction: who the publication is for, what they're deciding, the proof it holds itself to. It's never evidence of expertise.
    • safeFontStack keeps a font stack as data ("'Brand Display',serif"), never a stylesheet fragment, and EMAIL_SAFE_FONTS is what an email fallback may name.

    The stored shape's version is PUBLICATION_BRANDING_VERSION. Resolving a profile against a project's own colors and its measured site design stays in the Sonor API.

    The portfolio contract: the case study arc

    Every case study tells the same four-beat story, whatever an agency calls the beats: what was wrong, what we built, how we proved it holds up, and what it's doing for the client now. @sonordev/contracts/portfolio is where that story's structure lives, once, for the generator that writes it, the dashboard that edits it and every site that renders it.

    • CASE_STUDY_STAGES is the four beats in order: problem, build, proof, outcome. The ids are deliberately plain; an agency's renderer maps them to its own words. CASE_STUDY_STAGE_COPY gives each a generic name and the question its sections answer.
    • PORTFOLIO_SECTION_TYPES is every section a case study can hold, in canonical reading order: the hero, then each stage's sections, then the SEO metadata and the closing CTA. SECTION_STAGE says which stage each type belongs to (null for the hero, SEO and CTA, which sit outside the story) and sectionStage(type) reads it for a string. Both are typed over every section type, so a new type without a stage is a compile error.
    • orderSections(sections, { sectionsOrdered }) is the reading order. The arc always wins: hero, problem, build, proof, outcome, CTA. Within a stage the agency's stored order is kept once it has reordered in the dashboard; otherwise the canonical order. groupSectionsByStage returns the beats the case study actually has, numbered in order, each with its sections; a stage with nothing in it is left out.
    • caseStudyStageStatus(sections) reports all four stages, complete only when the stage's core section (STAGE_CORE_SECTION: challenges, strategy, performance, results) or a stand-in for it (STAGE_CORE_ALTERNATES: a verification completes the proof stage) is present, with one sentence on what's missing. A stand-in counts only when its data holds something a page can show, so pass each section's data along with its sectionType. stageCoreSections(stage) lists the core and its stand-ins. The dashboard shows the status beside the editor.
    • Stage names. The ids are fixed; what people see isn't. A site names the four stages in the dashboard ("Heat", "Shape", "Temper", "Finish"), per project like the rest of its branding, and CaseStudyStageNames carries that map to the editor, the public portfolio config and the site. stageName(names, stage) reads it with the generic name as the fallback; stageNamesProblems validates it and STAGE_NAME_MAX_CHARS caps each name.
    • CaseStudyNarrative is what the story says above its sections: one thesis and one lede per stage, written for this project. Signal writes it from the evidence it was given and the agency edits it; narrativeProblems validates one and CASE_STUDY_NARRATIVE_JSON_SCHEMA is the same rule as a schema. An absent narrative passes, so renderers fall back to house copy for older case studies.
    • The thread. A challenge carries an id (challengeId(n) mints "c1", "c2"…), a strategy phase says which challenges it resolves, a result says which it proves. caseStudyFlowProblems({ challenges, phases, results }) names every challenge nothing resolves or proves and every dangling reference. It judges links only where ids were written, so content from before the thread passes.
    • isRealDay(value) is the one rule for whether a string is a day: a real calendar day written YYYY-MM-DD. 2026-02-31 isn't one, and neither is a year under 100. A verification's date and a reported number's reportedBy.date both ask it, and so can anything else that stores a day.

    The verification

    A Lighthouse run can only score what a browser reaches without signing in. For an app whose screens sit behind a login, that's the sign-in page, and a score for the door reads as a score for the app. The portfolioVerification section is the proof stage for that build: a short list of checks (one to VERIFICATION_MAX_CHECKS, eight), each stating what it covers and, required, what it doesn't.

    import {
      readVerificationChecks,
      verificationLink,
      verificationProblems,
      type PortfolioVerificationData,
    } from '@sonordev/contracts/portfolio'
    
    const data: PortfolioVerificationData = {
      checks: [
        {
          label: 'Sign-in page, mobile speed',
          result: 'Performance 89',
          measured: 'The Lighthouse performance score of the page a visitor sees before signing in',
          where: 'https://example.com/login',
          method: 'Lighthouse 13, mobile preset, median of 3 runs',
          date: '2026-10-20',
          scope: 'The sign-in page only; the screens behind it were not measured.',
        },
      ],
    }
    
    verificationProblems(data) // []
    readVerificationChecks(data) // the checks a page may print
    verificationLink(data.checks[0].where) // 'https://example.com/login'
    • Every field is required, and each is one line of plain text within its limit (VERIFICATION_FIELD_MAX_CHARS): no line break, tab or other control character, and no zero-width or direction mark. date is a real day, YYYY-MM-DD, no earlier than VERIFICATION_EARLIEST_DAY (2000-01-01) and no later than latestVerificationDay(), which is tomorrow in UTC. That lets a check run today in a time zone ahead of your server through and refuses one that hasn't happened. verificationProblems and readVerificationChecks both apply it without being asked; pass { latestDay } to fix the clock.
    • where points somewhere a reader can go or look. A public web address, or a screen or file named in words ("the migrations in the repository") or as a path. A placeholder ("n/a", "here"; isPlaceholderText is the test), one plain word, a username or password in an address, and localhost or a private network are refused. One thing no rule can catch is a view link with a token in its path or query: if the link works for whoever holds it, don't put it here.
    • scope states a limit. It's what the check does not cover, written as a sentence with a word that marks where coverage stops: "only", "not", "except", "without", or a contraction like "weren't". A placeholder ("N/A", "none", "TBD"), a coverage claim ("All screens", "Fully tested") and a denied limit ("No restrictions") are refused (isVacuousScope). "Desktop only" and "Counted, not exercised" pass. Write what the check leaves out: "Counted from the migrations; no query ran as a signed-in user." The test reads English, and it can see that a limit was written, not that it's true, so a person still reads the scope before a case study goes live.
    • verificationProblems(data, options) names every problem with the check's position (checks[1].scope is required: say what the check does not cover), and refuses a field a check doesn't have. Whatever stores a verification should run it first. Nothing calls it for you, and until a write path does, stored data can hold anything, which is why readVerificationChecks checks again before a page prints.
    • readVerificationChecks(data) is what a page prints: the checks that pass, trimmed and in order, up to the limit. A check that fails is left out, so one with no scope line, or a placeholder for one, doesn't print, and a field a newer writer added is ignored.
    • verificationLink(where) returns the address when where is exactly one http or https URL with no credentials in it and a public host, and null for a screen name, a file path, localhost or anything else, so only a real public address becomes a link.
    • Every check is something you ran. There's no source on a check. A figure the client gave you stays in Results as a reported number, with the person behind it.
    • PORTFOLIO_VERIFICATION_JSON_SCHEMA is the same shape for agents. What a scope or a where says, and whether a date is a real day in range, are verificationProblems' job; a schema can't express them.

    It completes the proof stage on its own (STAGE_CORE_ALTERNATES), once it has at least one check readVerificationChecks would show. An empty verification, which is what an editor's Add button creates, leaves the stage incomplete and says why; caseStudyStageStatus reads that from each section's data, and a caller that passes only sectionType sees a verification as empty. Any project can use it. The status doesn't know the kind of project, so nothing is gated on it; a site that wants a Lighthouse score for a public site keeps writing a Performance section.

    Why it exists

    A rule that lives in several copies is how two of them end up disagreeing. This package means there's one: the source is src/contracts/ in the site-kit repo, site-kit bundles it into its own */contract entries, and this package publishes the same files for everyone else.

    Loading it

    CommonJS and ESM both. require('@sonordev/contracts/website') works in a CommonJS Nest API (including moduleResolution: "node", through typesVersions); import works everywhere else. slots imports Node's crypto, so keep it out of browser code; browser code reads slot-content.

    Changing a rule

    Edit src/contracts/<entry>.ts in the site-kit repo, run pnpm test:contracts, and bump this package's version. A breaking change to a shape bumps the major and that contract's own *_VERSION constant. pnpm build:contracts builds it and checks every entry loads both ways.

    Editorial media

    @sonordev/contracts/editorial-media exports resolveArticlePhotoPlacements(html, photos), returning section targets and a status/offset for each explicit placement. Both the editor and article renderer use this contract; a heading with no eligible prose is reported as no_paragraph, and missing/ambiguous anchors never drift to another section. editorialTextId creates content identities for explicit takeaway assignments. Source-image format, size and completed-art exclusions are shared by the picker and resolver.

    The funnels contract

    Import from @sonordev/contracts/funnels. createFunnelDraft(template) provides neutral defaults for newsletter, requested_guide and inquiry. parseFunnelDraftDefinition accepts bounded incomplete drafts so each setup step can save. parseFunnelDefinition requires a launch-ready structural definition. Resource ownership, current permission, route installation and launch authorization remain server checks.

    Use parseFunnelCreateArgs, parseFunnelUpdateArgs, parseFunnelRevisionArgs, parseFunnelLaunchArgs, parseFunnelLifecycleArgs and parseFunnelRetryArgs at command boundaries. parseFunnelDraftArgs(value, mode) requires an explicit create/update mode. Rollback uses parseFunnelLifecycleArgs(value, 'rollback'). Matching exported JSON schemas describe the closed structural shapes; runtime parsers also enforce semantic checks such as matching form references and managed paths.

    applyFunnelBrandOverride takes an already resolved brand, an allowlisted presentation patch and an API-authorized asset map. Null leaves restore inheritance. It returns the resulting brand, overridden field paths and asset references. It doesn't fetch assets, resolve business precedence or calculate authoritative hashes. parseFunnelBrandSnapshot validates the captured presentation and provenance.

    parsePublishedFunnelPage refuses private definition fields and unsafe asset URLs. It supports bounded text paragraphs and bullet lists, with a managed form slug and canonical campaign identity. managedFunnelPath reserves /f/:slug; a consuming site must opt in and verify its actual routes.

    parseFunnelReadiness, parseFunnelOperationReceipt and the detail/catalog/preview parsers validate bounded response envelopes. Operation receipts bind the exact command target and approved action, and always report zero messages sent by the configuration command. Preview and published-version detail parsers preserve the exact launch or rollback evidence.

    Authoring Funnel experiments in 2.21.0

    Managed Funnel definitions can optionally save page.experiment:

    import { parseFunnelExperimentAuthoring } from '@sonordev/contracts/funnels'
    
    const experiment = parseFunnelExperimentAuthoring({
      experimentId: '11111111-1111-4111-8111-111111111111',
      experimentRevision: 3,
      controlVariantKey: 'control',
      variants: [
        { variantKey: 'control', content: { headline: 'Workshop news', body: [] } },
        { variantKey: 'alternative', content: { headline: 'Ideas from the workshop', body: [] } },
      ],
    })

    This closed author input selects an experiment and supplies keyed headline/body copy. It accepts 2–50 unique variant keys, including the selected control. Keys use the existing 80-character bound; headlines use 160 UTF-16 code units. Bodies use the existing paragraph/bullet limits and 12,000-character aggregate limit per variant. Draft create/update parsers allow blank copy while saving, just like base page copy. parseFunnelDefinition and parseFunnelExperimentAuthoring require complete copy. The field is supported only on managed pages. Omit it to remove authored experimentation; null isn't accepted. Plain Funnel documents and createFunnelDraft defaults stay unchanged.

    The authored object accepts only experimentId, experimentRevision, controlVariantKey and variants. Each variant accepts only variantKey and content; content accepts only headline and body. The base definition keeps one fixed form, offer, brand, route and tracking identity. This input doesn't accept a content digest, goal authority, instance reference or approval flag.

    The native service must resolve the selected real experiment and linked campaign under the current project, site and Full Signal revision, verify the complete native variant set and control, derive the goal from that campaign, and hash each effective full content including the fixed offer. It then produces the existing PublishedFunnelPage.experimentContent manifest during normal preview creation. Authored selection is untrusted input; successful parsing grants no readiness, publication, assignment or execution authority. Save, preview, review and publish continue through the existing Funnel lifecycle and approvals. The editor must show every effective variant before review. Lifecycle rebuilds use the saved definition as their content source.

    Matching structural schemas are exported through FUNNEL_EXPERIMENT_AUTHORING_JSON_SCHEMA, FUNNEL_DEFINITION_JSON_SCHEMA, FUNNEL_DRAFT_DEFINITION_JSON_SCHEMA and the existing create/update schemas. Runtime parsers additionally check unique keys, control membership, aggregate body length and managed-page applicability.

    Deploy compatible contracts, parsers, native producer, renderer and editor consumers together before exposing the field. Older strict definition parsers reject page.experiment even though the field is optional in 2.21.0. A package upgrade alone doesn't implement native production or authorize publication.

    Adopting 2.20.0

    Use the same contracts version in every application that exchanges Resonance payloads. This release includes the 2.19 review-photo presentation exports and adds the Resonance and Signal experiment entries. Existing package subpaths stay available. Import a specific entry rather than the package root.

    import { parseMoney } from '@sonordev/contracts/resonance'
    
    const budget = parseMoney({ currency: 'USD', amountMicros: '1250000' })

    The parsers validate wire data. They don't approve a campaign, authorize spending or confirm provider delivery. Keep those checks in the application that owns the action. Deploy accepting server parsers before enabling new browser fields.

    The resonance contract

    Import pure parsers, types and JSON schemas from @sonordev/contracts/resonance. parseResonanceCampaignDraft accepts bounded incomplete setup; parseResonanceCampaignDefinition requires resolved goals, resources, destinations, channels and budget. Existing funnel, Broadcast, Outreach, Files, brand and experiment records retain ownership. Nested references must match the campaign's project and owned-site scope. Server lookups must still validate ownership, current revisions, policy and actual permission.

    Money is { currency: 'USD', amountMicros: '1250000' }, exactly 1.25 USD. parseMoney, addMoney, moneyToProviderUnits and moneyFromProviderUnits use integer arithmetic. Never pass amounts through Number or assume every currency uses cents. Conversion requires the verified provider/account exponent (0, 2, 3 or 6) and native limit; fractional units, overflow and currency mismatch fail. Supported currency codes are exported as RESONANCE_CURRENCIES; actual advertiser eligibility, minimum budgets and delivery semantics remain provider checks.

    The initial paid profiles are google_search and meta_retargeting, distinct from provider IDs google_ads and meta_ads. They are closed plans, not arbitrary provider JSON or a claim to support every campaign type. Prepared plans bind exact ordered creative copy/media/crop references, destinations, budgets, goal/policy revisions and server-owned compiled manifest references. resonancePlanIssues reports blocked, missing or stale capabilities without turning them into success.

    parseResonanceMandateApprovalPayload(value, target) validates the exact business payload and project/campaign target. It doesn't approve anything. Resolve original principal and approval provenance through the existing Action Ledger; compute and verify the server digest over resonanceMandateDigestInput before admitting effects. The command digest input similarly canonicalizes only parsed command fields. Launch/update/resume and optimization require exact plan/mandate lookups. Safety pause/finish/reconcile commands require root revision and idempotency identity but no fresh creative approval, so stale creative evidence cannot prevent a stop.

    An immutable PreparedPlan is stored as an existing campaign version; it is review evidence, not approval authority. Receipt state and unresolved exposure remain separate from approval. An uncertain provider admission requires reconciliation before retry; it must not release liability or repeat creation automatically.

    Metric observations distinguish observed zero from unknown, insufficient, delayed and unavailable values, retain window/timezone and native-unit evidence, and use exact counts/money/ratios. Consent and conversion parsers validate scoped evidence; a browser cannot mint a trusted lead by passing validation. Accepted source rows, current consent/withdrawal and experiment exposure must be verified server-side. No scripts, credentials, cookies or customer personal data belong in these DTOs.

    The save/binding/accept command parsers use the same strict wire rules. Updates require an expected root revision; root creation can omit it. Account bindings select existing provider resources, never credentials. Optimizer evidence and immutable decisions have separate parsers: they retain unknown tracking/power checks, exact before/after allocations and remote snapshot identities. Resolve minimum evidence, lag, cooldown and mandate coverage from the referenced frozen policy on the server. Parsed metrics or an actionable decision alone never grant spending authority. A blocked or no-op decision cannot carry allocation effects.

    Public measurement configuration is a separate closed DTO. It carries only typed Google Ads tag/Meta pixel identifiers, permitted resource rules and basic consent policy. A measurement occurrence is a view, explicit interest or experiment exposure; it cannot declare an accepted conversion. Consent updates preserve unknown, denied and withdrawn states. These parsers don't load any tags, collect browser data or turn a reported grant into server-verified permission. The browser runtime and server evidence/withdrawal checks must implement those controls.

    Page-view occurrences can include optional clickIdentifiers, with exactly one closed shape: { gclid: string }, { gbraid: string } or { wbraid: string }. parseResonanceClickIdentifiers, ResonanceClickIdentifiers and RESONANCE_CLICK_IDENTIFIERS_JSON_SCHEMA share that boundary. Values contain 1 to 1024 characters, with no whitespace or control characters. This is the application's transport bound. Other occurrence kinds reject the field. The browser reads the current URL only after the required advertising grants and scoped proof are available. An observed identifier doesn't authenticate a paid click. The server must verify the same subject, site, current consent and actual form occurrence before using it for conversion matching. Identifiers don't belong in public configuration, receipts, results or logs. Deploy the accepting server parser before enabling browser emission.

    Initial acceptance uses only { expectedRevision, ledgerActionId }. The server loads the approved native payload and current kill state and returns the canonical mandate reference. Clients must never guess a kill revision to construct authority.

    Managed definitions contain the closed optimization.policy; prepared plans freeze an identical resolvedEvidencePolicy. Initial inline policies have sourceRef: null. A genuine existing source can supply optional provenance, but a new campaign doesn't need a synthetic experiment, self-referencing plan or new policy table. The first algorithm is explicitly observational qualified-lead CPQL allocation with approved maturity, coverage, uncertainty, attribution, lag and cooldown values. Executable allocation and current source/mandate admission remain server-owned.

    Finite preapproved Meta candidates

    The optimization policy also supports the closed finite_meta_candidates_v1 branch with decisionKind: 'preapproved_candidate_operation'. One policy variant belongs to each original plan. The existing mature allocation branch keeps its meaning and shape.

    The finite policy uses candidateChannelIds to reference original Meta channels in the same definition. Their existing creatives, account, site, independent adset lifetime cap and original budget flight remain authoritative. The policy doesn't copy those inputs or contain compiled graph hashes. It records an exact reviewed order and schedule, one activation per candidate, concurrency, allowed actions, a typed exploration ceiling, tracking requirements and hard stops. performanceDecisionPolicy is explicitly null: this profile supports fixed exploration and approved safety stops, with no measured winner, adaptive pruning, budget increase, promotion or causal A/B claim.

    Preparation resolves the original graphs and binds them with the policy in the existing review digest. The existing mandate seals that review. Later evidence and decisions reference the resulting graph identities; their hashes never feed back into the definition policy. No new policy registry or mandate field is used.

    ResonanceFiniteMetaCandidatePolicy, ResonanceFiniteMetaCandidateEvidence and ResonancePreapprovedCandidateOperationDecision narrow the existing generic types. Their parsers, JSON Schemas and digest helpers share the existing resonance entry. Cold lifecycle evidence records unobserved measurement as null, with no borrowed donor outcomes or invented mature zero. An actionable decision carries exactly one materialize_and_activate, activate_held or pause_candidate action. Blocked and no-op decisions carry none. These decisions don't carry mature adjustments or a fabricated zero-to-cap transfer.

    Pass the actual prepared plan as the optional second argument to parseResonanceOptimizationEvidence to check original public scope, manifest, cap and flight. Pass actual evidence and, when available, that plan as the second and third arguments to parseResonanceOptimizationDecision to check policy, action, fixed order, freshness and commitment-reference consistency. Parsing a standalone object checks its closed shape; it can't authenticate referenced rows or establish approval. Servers must load and verify the actual accepted plan, native claim, current permission and protected evidence before admission.

    The API and database reserve the full independent cap before the first create. Activating an already paused candidate adds no new exposure only when its exact original physical commitment is already fully held. Resource presence or a reference alone doesn't prove that condition. Pause and donor decreases don't release old holds; uncertain effects retain their original key and reconcile. The public optimize command and existing Ledger workflow are unchanged.

    Provider spend, clicks and impressions retain their own provider_aggregate counting unit and provider_reported attribution. First-party qualified-cohort observations keep the original objective's counting unit and attribution model. They aren't interchangeable evidence, and neither enables a performance decision in this fixed profile.

    Ordinary optimize actions, including an explicitly allowed candidate pause, remain inside the current policy and mandate expiry. At or after expiry, creation and activation stop; any needed pause uses the existing current-owner safety pause or escalation path. This contract doesn't create post-expiry permission or a second stop-validity clock.

    Public measurement transport uses the dedicated X-Sonor-Resonance-Subject header. Config reads do not issue identity. Only an explicit preference action can receive subjectProof, expiresAt, currentConsentRevision and the four purpose receipts. This is an opaque scoped proof, kept in browser memory. Proof expiry isn't consent expiry and must not force recurring consent prompts. Valid current CMP state may support scoped proof renewal/resumption through the authoritative API; until a valid proof is available, exports stay off. Config itself never bootstraps identity. expectedConsentRevision atomically fences the complete subject preference batch. The browser must discard stale grant replies, stop immediately on withdrawal, and never replay pre-consent events or bootstrap identity on config/page load. These contracts describe evidence, not an implemented transport or real-person identity.

    Tracking-only legacy campaign views retain revision zero; managed campaigns require at least revision one. Creation can adopt a tracking root at zero, but updates need a managed revision. Unknown admission in any child forces reconciliation and cannot be hidden by a failed root label or retry advice. Known reconciled/rejected work may still retry the same original operation when the server authorizes it.

    parseResonanceSubjectRenewCommand accepts only current consent/config/policy revisions. Renewal rotates a proof without granting or changing consent. It requires the scoped subject transport and current server/CMP checks; it isn't permission to bootstrap identity from a config read or recover someone else's receipt.

    Public renewal includes schema version and the asserted project/site envelope as well as current revisions; the server resolves and verifies that scope from proof and credential. Finite allocation horizons carry verified UTC start/end, timezone and source revision, so eligible total/lifetime budgets can be compared on the same actual period without relabeling daily averages as hard lifetime caps.

    cpqlMissingOutcomeBound computes the named observational sensitivity method from trusted unique-contact totals: eligible n, fully resolved attribution/dedupe/final qualification intersection c, and qualified subset k. It returns the ceiling of 10000*(n-c)/(2*k+n-c), or unknown when no positive source universe exists. This isn't statistical confidence, causal lift or permission to inject counts from a browser. API source producers must verify the complete universe and spend period; without that witness, the evidence bound remains unknown. Coverage stays separate.

    Successor management and attribution fields

    Added in 2.20.0, @sonordev/contracts/signal-experiments is the single parser for the existing Signal create/update payload. It exports parseSignalExperimentCreate, parseSignalExperimentUpdate, their types and JSON Schemas. Both operations check unique variant keys and the existing weight-sum tolerance of 0.01. Percentages must be finite and within 0 to 100. Optional allocation and targeting defaults remain the existing service's job. Parsing doesn't grant access or select a variant.

    /resonance adds audience draft save and experiment create/update, lifecycle, complete and link command parsers. Each managed experiment command requires expectedRevision and idempotencyKey. Audience drafts reference the current measurement config's resource rule IDs. The server resolves their scope and provider retention limit. Saving a draft uploads no people or audiences.

    Public source markers use the sonor_source parameter and bounded rsm1.<claims>.<signature> format. A prepared channel preview can carry an attributionMarker; its destination URL must contain exactly that reviewed marker. An occurrence can carry the bounded sourceMarker value. The pure parser checks format and URL coherence. The server verifies the signature, purpose, accepted immutable plan and actual resource scope.

    first_party_last_touch_marker_v1 describes server-recorded first-party source mapping under the reviewed attribution window. It doesn't establish a paid click, a human visit or a causal effect. Unresolved source linkage stays unallocated. The existing resource, audience-rule and experiment-reference readers are also exported so owner projections can use the same validators.

    Qualified-lead prepared plans require a non-null resolvedQualificationRule. Other objectives carry an explicit null. The objective keeps the selected qualificationRule; the prepared projection shows its actual CRM project ref, crmVariant, native ladderSnapshot, eligible form and cohort boundaries. semantic_key and native preset stage IDs can be null. The parser preserves those native values and never manufactures a stage UUID or infers qualification from a stage's position or won/lost flag.

    The three selected stage partitions must be disjoint and exhaust the resolved native ladder. The public projection must match the selected partitions, native ref, source form, counting unit and maturity delay. API persistence resolves one canonical witness and uses that same object for internal resource evidence and public review. The server must verify its actual source and digest. These shape checks don't establish that a caller supplied genuine database rows.

    PreparedPlan.expiresAt is an initial acceptance freshness deadline. Continuing an already accepted campaign uses its current native mandate and budget limits, with current resource and capability checks. The pure initial-readiness helper doesn't replace those authority checks.

    Preparing a campaign command

    parseResonanceCommandPrepareRequest reads only expectedRevision and idempotencyKey. The API resolves the accepted plan, current resources and authority for launch, update or resume. parseResonanceCommandPrepareResponse reads { command, covered, approvalRequirement, reasonCodes }, where command may be null and approvalRequirement is existing_mandate, current_owner or null. A covered command still needs its required native approval and claim. Resume after a pause requires the current owner's approval through the existing action ledger.

    @sonordev/contracts/resonance-constants exports RESONANCE_SUBJECT_HEADER, RESONANCE_SOURCE_MARKER_PARAMETER and RESONANCE_ATTRIBUTION_MODEL without loading campaign schemas. The main Resonance entry re-exports these same literals. Browser adapters can use the constants entry when they don't need a parser.

    Use parseResonancePreparationLookupRequest and parseResonancePreparationLookupResponse for an original preparation read. The closed selector carries the saved expectedRevision and idempotencyKey. It rejects additional preparation input. The response keeps confirmed absence, current work, required recovery and terminal outcomes distinct. A completed plan must match the original request and operation. A recovery hint describes the observed state. The owner still checks authority before resuming through the existing preparation path.

    Preparation operation.createdAt uses the same lossless native timestamp reader for both key-based and UUID reads. It retains numeric offsets and all six fractional digits. Other authority observation instants retain their existing UTC format.

    parseResonancePreparationRetireRequest reads the explicit cancellation input { expectedRevision, reason: 'retain_unpublished_artifacts' }. parseResonancePreparationRetireResponse reads the original cancellation receipt and separates retained artifacts from unrecorded slots. Their total is bounded to 512. The native owner verifies eligibility and preserves those artifacts through its compare-and-set operation. A lookup never retires work.

    parseResonanceOriginalRequestsResponse reads the passive RESONANCE_ORIGINAL_REQUESTS_ROUTE response. The GET accepts no query or body. It returns scope IDs, items and hasMore, with at most 100 preparation originals and 100 operating policy originals. Each item has kind and its real operation or action ID. Preparations come first. Timestamps preserve the native literal, including offsets and microseconds. A proposed action remains proposed. These descriptors establish no approval, relationship between originals or permission to recover. A failed read is unavailable; only a successful scoped query can confirm an empty list.

    parseResonancePreparationOriginalByIdResponse reads one preparation through RESONANCE_PREPARATION_ORIGINAL_BY_ID_ROUTE. Missing originals return 404. The response shares the existing sanitized operation and readiness fields, adding advisory canRetire. It omits the original key, request and prepared plan. An explicit POST to RESONANCE_PREPARATION_RETIRE_BY_ID_ROUTE uses the existing retirement request and receipt contracts. The server derives the original selector privately and repeats every mutation check. A GET never retires or resumes work.

    Interactive Google campaign diagnostics

    parseResonanceGoogleCampaignDiagnosticsRequest reads the exact HTTP body: { channelId, startDate, endDate, sections, directive }. The directive must contain text, the dates span one to 31 calendar days, and sections are a nonempty unique selection from RESONANCE_GOOGLE_DIAGNOSTICS_SECTIONS. The native owner checks that the dates are completed days in the account's timezone. parseResonanceGoogleCampaignDiagnosticsPayload reads the stored business payload, adding schemaVersion: 1, campaignId, expectedRevision, accountBindingId, site and idempotencyKey. Native admission checks these values against the original action. Callers cannot supply an execution deadline or authorization proof through either shape.

    parseResonanceGoogleCampaignDiagnosticsReport validates a bounded report for one owned campaign and channel over up to 31 completed advertiser-local days. Campaign configuration, totals, daily metrics, keywords, disclosed search terms, conversion goals and upload diagnostics have separate section states. Unavailable values stay null. Spend uses integer micros strings, while provider-attributed conversions retain decimal strings.

    Provider-authored text travels under providerAuthored, keyed to the rows it describes. Keyword text uses the complete adGroupId and criterionId pair. Treat it as untrusted data when displaying it to an agent. Search-term coverage can include an integer remainder only when compatible campaign totals and all disclosed rows are available. Conversion remainders stay null.

    The API authorizes a one-off read from the current delegated session and the submitted directive, with explicit sections, scope and deadline. The report parser validates data shape. It supplies no read authority. The ordinary daily reporting grant keeps its existing scope.

    Direct commands under delegated authority

    @sonordev/contracts/delegated-command defines the owner-controlled AgentExecutionPolicy, its compare-and-set update, a safe authority summary and native delegation attribution. It initially covers four named families: resonance.mandate, resonance.operating_policy, resonance.optimize and resonance.diagnostics. Other existing actions keep their native controls. delegatedCommandFamilyForAction classifies these families from the stored kind and payload. Unknown actions return null. Classification isn't admission.

    parseAgentExecutionPolicy reads explicit project, account binding and site lists, campaign selection, named families, validity, campaign and outstanding spend ceilings, currency, change limits, flight limits and a maximum operation count. The campaign selection is { mode: 'selected', campaignIds: uuid[] } or { mode: 'all_in_projects' }. Selected empty IDs grant nothing. The explicit all_in_projects branch includes current and future campaigns within the selected projects, sites and accounts. Owners can choose this preset once without selecting each new campaign. All target dimensions intersect, and empty project, site or account lists grant nothing. Native checks must cover every affected target and intersect the policy with current membership, accepted limits, campaign state and kill controls.

    parseAgentExecutionPolicyUpdate reads { expectedRevision, policy }. Revision zero means no saved policy. A null policy requests revocation. Only an authenticated native owner control can save this update. Existing tokens without a policy gain no new direct authority.

    parseDelegatedCommandAuthoritySummary reads a native observation with the actual agent, its human principal, policy state and revision, and one capability for each family. Each capability reports direct, propose_only or unavailable, closed reasons and its effective limits. Operation usage is counted once per original action and effect key over the policy revision's lifetime. Uncertain work keeps its reservation. Policy rotation doesn't erase existing financial exposure. The native owner rechecks live authority before claiming and before each effect or provider request.

    parseDelegatedCommandApproval reads the native stored attribution: { by, via: 'mcp', at, basis: 'delegated_agent', delegation }. Here by is the actual agent. The delegation reference contains schemaVersion: 1, tokenId, policyRevision, ledgerActionId and payloadDigest. A native immutable admission must bind that reference to the full original action, authenticated identities, complete target set and effect key. A parser-valid reference supplied by a caller grants no authority. Keep it private.

    An explicitly requested command within current delegated authority can execute without another per-action human confirmation. The receipt records the agent's action on behalf of its principal. It doesn't invent a human reviewer or grant unattended execution. These parsers define transport shapes. Native admission, atomic reservations, revocation and effect checks remain required.

    The native claim route is DELEGATED_COMMAND_CLAIM_ROUTE: /agents/me/execution-actions/:ledgerId/claim. Its POST body is read by parseDelegatedCommandClaimRequest: { projectId, expectedUpdatedAt, expectedPolicyRevision }. parseNativeCasTimestamp is shared with the recovery request and exported from both resonance and delegated-command. It accepts strict RFC3339 UTC or numeric-offset timestamps with up to six fractional digits and returns the exact input. Forward the original database updated_at unchanged. Converting it through Date.toISOString() would lose microseconds. Ordinary authority observation instants keep their UTC format.

    parseDelegatedCommandAdmission reads the native admission observation, including all affected channel and account binding IDs and sites. Its proof reference must match its original action, token, policy revision and digest. parseDelegatedCommandClaimResponse(value, parseNativeAction) reads { action, admission, replayed } using the supplied native Ledger row parser. Only the POST winner with explicit replayed: false may enter execution. Read-only GET and replay responses never dispatch. Admission may be null for an unadmitted original read. A lost claim reply requires that original read, without redispatching the effect. The native owner must bind the action row and admission to the current authenticated request.

    The separate RESONANCE_OPERATING_POLICY_RECOVERY_ROUTE identifies recovery of an original failed policy action whose human review is preserved. parseResonanceOperatingPolicyRecoveryRequest reads only { expectedUpdatedAt }. Current token, original revision and policy authority come from the native authenticated request. Its admission uses basis: 'human_review_recovery' and originalReview: { reviewerContactId, reviewedAt, approvalDigest }, binding the unchanged original human approval. An agent recovery has executorKind: 'agent' and retains its exact token, policy revision and proof reference. An actual human owner recovery has executorKind: 'human', equal actor and principal, and null token, policy revision and proof. Native authenticated identity selects this branch. Recovery requires native proof of non-effect and the current predecessor. It uses the same response envelope and winner-only dispatch rule, without turning the original review into a new agent approval. Fresh OrgAgents claims remain separate from this recovery.

    RESONANCE_ORIGINAL_REVIEW_RECOVERY_REASONS and parseResonanceOriginalReviewRecoveryReason define the fixed ORIGINAL_REVIEW_NOT_ELIGIBLE and ORIGINAL_PREPARATION_OWNER_ACTION_REQUIRED reasons. Native owners emit them only after checking the exact original review and any real blocking preparation. A reporting approval doesn't authorize retiring a separate preparation whose relationship to that review hasn't been established.

    An already human-reviewed reporting-only policy can use the distinct native exact_person_review_recovery admission. It records the current named agent and credential, null standing policyRevision and proof, the preserved originalReview and a real nativePolicyReceiptId. Native checks bind the original filer and reviewed agent to the same principal and current scope. They require the sole active credential to have been created and activated before review, with no configured standing policy or prior denial history. This records current credential binding. It makes no claim about which token was used during the human review.

    The native transaction verifies and applies only that original reporting effect once. A separate preparation proved noninterfering may remain unchanged. Private artifact evidence stays native. New ad, budget or other business changes still need their own intentional authority.

    parseResonanceExactReviewRecoveryResponse reads the strict public result: scope and action IDs, nativePolicyReceiptId, replayed, the actual agent and principal, and the original reviewer's ID and review time. Its effectState: 'applied' describes the policy effect. ledgerStatus separately reports approved, applied or failed for the original activity record. projectResonanceExactReviewRecoveryResponse projects a verified private admission and the actual original record state into this public shape. Tokens, proofs, private digests, claims and action payloads are excluded.

    This basis must never enter the ordinary apply executor: the native effect has already happened. The consumer verifies its native receipt and acknowledges the same original record idempotently. Replays cannot activate it again, and passive reads remain read-only. A receipt UUID supplies no acknowledgment authority. The native owner rechecks identity and the exact original binding.

    parseResonanceOperatingPolicyRecoveryResponse lets an updated consumer read either this safe public result or the older response envelope. It rejects a private exact-review admission on the public path. Deploy compatible readers and native verification before enabling the new origin; older strict readers reject its shape. The specialized POST body remains only { expectedUpdatedAt }.

    Standing Google Search content policy

    A Resonance mandate can include an operatingPolicy naming its agent and verified human principal. Use parseResonanceOperatingPolicySelection for draft input and parseResonanceOperatingPolicy for the resolved policy. Each entry names an existing channel, ad group and ad. It carries up to 20 owned phrase negatives to remove, up to 20 exact keywords to add, and an optional full set of RSA headlines and descriptions with their creative reference. The policy sets a cooldown that applies to these changes.

    Pass googleContentUpdate with the target keys to prepare an update. The prepared command adds the exact bounded change, operating policy receipt and prior content fingerprint. Targeting terms are normalized and sorted for canonical identity. Headline and description order is preserved. Sonor checks current authority, scope, cooldown and provider state at dispatch.

    An operating policy activation uses the existing mandate approval. Its operatingPolicyBase binds the accepted campaign and the previous policy receipt. The first activation uses a null predecessor. An absent operatingPolicy preserves the original mandate's wire shape.

    For operating policy filing and recovery, hash the exact UTF-8 output of resonanceOperatingPolicyActionDigestInput({ mandateDigest, operatingPolicyBase }) with SHA-256 and use its lowercase hex digest. The same approved terms and base produce the same action key. Repeating those terms after a different policy receipt produces a new key. Legacy mandate lookup and policy receipts still use the original mandate digest.

    Delivering a qualified Google conversion

    The existing ResonanceCommand union adds operation: 'deliver_conversion'. It requires the usual schema version, campaign, prepared plan, review digest, expected revision, idempotency key and mandate reference, plus channelIds with exactly one original Google channel and conversionId for the persisted canonical qualified fact. The command carries no click identifiers, personal data, provider payload, values, timestamps, native destination or approval flags.

    The original mandate must explicitly include deliver_conversion in allowedOperations. A launch-only grant doesn't gain delivery permission. The existing original review binds the goal, source, qualification witness and Google configuration; there's no second delivery policy object. The initial profile is qualified_at_observation_v1 for one managed-form qualified source and one destination. Existing goals with multiple actions are rejected for delivery. Cross-account action ownership remains unsupported.

    parseResonanceCommand(value, { preparedPlan, mandate, now }) optionally checks those actual parsed objects for original scope and prepared definition revision, goal, budget, account, site, single-action Google profile and the original dispatch window. The one-argument call remains shape validation. An accepted plan's initial freshness deadline doesn't create a reporting tail: new dispatch must remain within its original mandate and budget window. Ordinary delivery stops after expiry; read-only receipt reconciliation doesn't resend it.

    These checks don't authenticate a persisted fact, current principal, kill or finish state, qualification, consent continuity, native claim or export deduplication. The server must verify the protected same-root goal-installation receipt and current native ownership. Setup intent only binds the reviewed local action and strategy; actual destination resolution requires its original successful native setup receipts. Missing or stale provenance blocks delivery. Parsing neither proves that setup ran nor authorizes a provider request. Accepted provider ingestion doesn't establish attribution or bidding success.

    Google campaign configuration

    parseResonanceGoogleConfigurationSaveCommand reads a strict draft request with schemaVersion: 1, expectedCampaignRevision, expectedRevision, idempotencyKey, the required signalSemantics, declaration: { statement, category } and one top-level mode:

    • existing: nativeGoal: { externalId, actionIds }, using full native Google resource names. The unique action set is sorted by the parser.
    • admitted_setup: setupIntent: { requestedGoalName, requestedActionName }. These are intended display names, bounded to 160 characters, not purported native resources. The server derives the complete setup specification.

    Revision 0 expects no saved configuration. The server checks the campaign and configuration revisions and recovers the original operation by its key. Parsing doesn't save, approve or spend anything. Save the campaign and channel first, retain their IDs, then save their configuration. The configuration response supplies the resulting campaignRevision, configuration revision, operationId and replayed. Retry an uncertain save with its original key and body before starting another operation. Re-read the actual campaign after an uncertain initial draft save; its stable ID may now have a later revision.

    The required signalSemantics is qualified_at_observation_v1 for both modes and the setup specification. It describes an explicitly reviewed historical provider bid signal, distinct from Sonor's unchanged current_at_observation qualified counts. It doesn't promise equal counts or provider count retraction. Existing and new setup profiles currently support only qualified_lead with unique_qualified_contact and a 1–90 day window. Actual producer eligibility, permanent contact/destination deduplication and delivery remain server checks. Other goal profiles are unsupported.

    A qualified-lead goal can also count contacts who book. Its reviewed objective names up to 100 eligibleBookingTypeIds beside the one managed form, and the native witness (resolvedQualificationRule) must name exactly the same booking types, in any order or letter case. A witness that adds or drops a type, a duplicate or empty list, and booking types on any other goal source are refused, and a witness still names exactly one form. The field belongs to the reviewed objective, so the mandate and the Google delivery command bind it the way they bind the form. A goal that omits it parses and serializes exactly as before, with its existing digest. Which bookings qualify stays a server check.

    The declaration's explicit statement is DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING; its category is general, housing, employment or financial_products_services. The server binds it to actual source, account, creative, copy, destination and region scope, with the actual declarant UUID, timestamp and original declaredForCampaignRevision. No permanent statement is inferred from a brand or site. These fields aren't approval identities. The exact statement and resource effects are reviewed within the same campaign mandate.

    parseResonanceGoogleConfigurationSnapshot reads the canonical public snapshot with configurationRevision and configurationDigest. Its top-level mode remains explicit. Existing-mode native goal name and revision may be null when draft evidence is unavailable; a real empty provider label stays empty. parseResonanceGoogleConfigurationReview requires actual name and SHA-256 revision for existing mode.

    Setup mode contains setupSpec and setupDigest, with no nativeGoal or purported native ID/revision. ResonanceGoogleUploadClicksCustomGoalSpec has one singular action, one matching goalActionKey, fixed local dependency keys, requested names and exclusive_custom_goal_v1. There are no actions[] or goalActionKeys[] aliases. The bounded first setup profile is qualified_lead with unique_qualified_contact, an UPLOAD_CLICKS action, QUALIFIED_LEAD, ONE_PER_CLICK, primaryForGoal: false, and the exact objective attribution window from 1 through 90 days. Other new setup pairs are unsupported; longer windows aren't clamped. Actual contact deduplication and delivery identity remain upstream responsibilities. Native per-click counting doesn't implement global contact deduplication. Canonical outcomes and provider reports remain separate.

    projectResonanceGoogleConfiguration(snapshot, { ready, activationReadiness, reasonCodes }) is the one public view/review projection. The view renames configurationRevision to revision and adds fresh resolver metadata. ready means reviewable, not activated: planned setup uses pending_setup, unready configuration uses blocked, and existing setup requires final verification or verified native evidence. An unready view returns review: null. The corresponding view/save-response parsers validate these shapes without granting authority.

    resonanceGoogleSetupDigestInput and resonanceGoogleConfigurationDigestInput return canonical JSON for the server hash function. The configuration input omits only its self configurationDigest; initial content needs no placeholder. Private eligibility or authorization evidence doesn't belong in this public snapshot. RESONANCE_GOOGLE_SOURCE_CATEGORIES and googleConversionActionSemantics share native vocabulary with explicit counting and window inputs; vocabulary membership grants no broader setup eligibility. googleUploadClicksSetupSemantics({ source, countingUnit, attributionWindowDays }) is the shared narrow policy check. It doesn't establish an actual source producer or delivery identity.

    Every prepared preview requires googleConfiguration: a strict existing or setup review for Google Search, explicit null for other channel kinds. Project, campaign, channel, site, account binding, source, measurement, counting, window and regions must match the enclosing plan. Preparing setup performs no provider mutation. After the same native mandate and admission, actual receipts resolve local keys to native IDs without rewriting the accepted public plan. Activation still needs current native eligibility, source, consent and authority checks. No parser proves those checks occurred.

    Original Meta website-visit feed

    ResonanceMandateScope accepts an optional websiteVisitFeed with the profile sonor_sdk_page_view_fresh_v1 and a channels list. Each entry selects an original Meta channel, a measurementConfigRef, resourceRuleRefs and a matchingProfileRef. Account, dataset and site come from that same channel in the reviewed plan. The matching-profile reference identifies the protected configuration-save receipt, its positive integer CAS revision and its digest. No feed is granted when the field is absent. A launch permission, measurement setting or visitor consent alone doesn't grant this feed.

    RESONANCE_WEBSITE_VISIT_PROFILE is the fixed, immutable local policy. resonanceWebsiteVisitProfileDigestInput() returns its canonical bytes for the server to hash. resonanceMeasurementConfigDigestInput(config) parses the measurement config and returns canonical semantic bytes, excluding only expiresAt. Current expiry still needs a separate check at capture and every dispatch. Renewal changes no original grant window; a semantic change at the same revision changes the digest. Both helpers retain approved list order and use the same canonical serializer as the existing mandate and command digests.

    The existing command union adds deliver_website_visit for the protected native operation path. It carries one original Meta channel and an internal occurrenceId, alongside the existing plan, review, revision, idempotency and mandate references. It carries no matching values, timestamps, dataset or provider body. parseResonanceCommand(value, { preparedPlan, mandate, now }) checks original public grant consistency; it can't establish a protected producer, native claim or permission to send. Manual, public API and MCP entry points must reject attempts to originate this command. Native consumers must use the existing action ledger, standing approval and durable admission path.

    Measurement occurrences gain optional pagePath and metaCookieObservation fields on page_view only. The cookie observation has source sdk_reported_first_party_cookie and one or both actual reported fbp/fbc values. Each value is limited to 1–1024 characters with no whitespace or controls. Matching requires the path and existing resource reference on that same occurrence and navigation. The API must verify the owned site and exact approved rule/path/resource. A separate-origin API can't infer the site's first-party cookies from its own Cookie header. Raw matching belongs only in protected capture persistence, never ledger payloads, operation requests, results, receipts, public configuration or read responses.

    This is an SDK-reported observation. It doesn't prove that a person rendered a page or create a qualified lead or business conversion. The server-only event ID is the internal occurrence UUID; browser/server pairing is unsupported when the browser uses its different public event ID.

    resonanceWebsiteVisitEventTime({ occurredAt, receivedAt }, { mandate, approvedAt, now }) checks the local time arithmetic and returns epoch seconds from the original reported occurredAt. The first receipt and final attempt must each be within 300,000 milliseconds of that original time, inclusive, with zero future allowance. Both original times must follow the original accepted feed approval and stay within its original window. It never substitutes receipt, retry or regrant time. This is Sonor's conservative policy, not a Meta age limit or acceptance guarantee. An authenticated exact-body replay must return its original stored identity and first receipt before new-capture age checks, without insertion, enrichment, queueing or resend. Current consent epochs, grant, kill, claim and global dedupe checks remain native owner responsibilities.

    These pure contracts don't install capture, a protected configuration writer, a matching-profile producer or native delivery. Those owners must implement and verify the actual preparation, original-delivery and terminal non-effect response boundaries before adoption. Parsing a valid payload doesn't make a provider ready or prove delivery.

    Original Meta age selection

    An original Meta channel accepts optional ageConstraint: { mode: 'bounded', min, max } | { mode: 'omitted' } | { mode: 'provider_managed' }. The provider-managed intent has separate native observation requirements described below. Bounded values are integers from 1 to 120 with min <= max; these are local transport bounds, not country, category or provider policy. An absent field preserves legacy bytes and leaves new preparation unresolved. It doesn't select a default. Explicit omission or bounds require an actual current policy witness, and native readback must account for any source-backed normalization. Adapters must block unknown policy rather than ignore the selection or invent ages. This representation doesn't establish that a compiler, account or provider supports it.

    Native measurement bootstrap and Meta configuration

    The pure setup contracts describe native owner inputs and saved projections. They don't create provider resources, grant visitor consent, approve spend, or enable the website-visit feed. Native API, SQL, preparation, approval and provider owners must adopt and verify them separately.

    ResonanceMeasurementConfigurationSaveCommand selects actual native pages using {pageId, observedRevision, observedDigest}. Its closed input also includes schemaVersion: 1, site, expectedCampaignRevision, expectedConfigurationRevision, idempotencyKey, enabled and the basic consent-purpose requirements. It accepts no caller path, rule ID, resource reference, expiry or readiness flag. The three advertising purpose requirements are mandatory; a requirement doesn't grant that purpose to a visitor.

    The native sequence starts with a managed draft and its owned sites; channels can be absent or empty. Measurement bootstrap uses that real draft as an operation audit home. It creates no complete advertising channel. After saving real page rules, the existing audience owner can create logical rules, and the campaign owner can save a complete Meta channel with those returned references. Meta configuration then maps those same logical rules to existing native audiences or admitted creation intent. A present channel still requires its complete original fields.

    Measurement configuration CAS is scoped to project/site. Zero expects actual absence; a legacy or malformed row without protected provenance must block. An audit campaign's revision check doesn't partition the site configuration or advance that campaign's review revision. projectResonanceMeasurementConfiguration(command, context) accepts an authorized project, protected current projection, reloaded safe page facts and a native transport expiry. It derives one rule per actual page UUID, sorted by page ID. The page resource revision is canonical UTC milliseconds; the rule revision is the existing full native evidence digest. This preserves distinctions between source updates within one millisecond. Native SQL must independently validate the facts and recompute CAS decisions under its locks.

    A page resource rule can carry metaEligible. It is set by a person with owner or admin standing, absent means false, and the browser never decides it. A Meta destination can carry browserWitness, the server's capability witness for the browser pixel loader (controlsRevision, policyRevision, witnessId, assertedAt), and tagManagerAttested for a site whose approved configuration states that its tag manager installs no Meta pixel. All three are optional, so earlier configurations still parse, and a configuration without a witness loads no Meta browser code.

    Native semantic configRevision and policyRevision are positive decimal strings. Identical semantics and a new cache expiry preserve them. Page evidence, selected rules or enabled-state changes advance the configuration revision; only consent-policy changes advance the policy revision. Initial provider destinations are []; updates preserve explicitly configured destinations. The helper returns the configuration, friendly page projections and configurationDigestInput from the existing resonanceMeasurementConfigDigestInput. Hash that exact string once. The save-request digest helper retains original request array order, while derived semantic pages and purposes are sorted.

    Measurement Current distinguishes actual unconfigured revision zero from a saved configured projection with current reasons. Snapshot contains the original audit campaign, operation, configuration and friendly page evidence. SaveResponse adds replayed. The native owner must return an exact original same-key result before fresh CAS/source checks, while enforcing current read permission; a changed request conflicts. No parser proves native provenance.

    The agreed native freshness model is one read-only current-configuration resolver. It checks actual current ownership, protected saved provenance, native page evidence, configuration and policy, then issues a 300-second cache envelope from the database clock. All native purpose, consent, intake, audience, attribution and feed gates must use that same resolver. Reads must not mutate settings, create renewal operations or change original saved bytes. The cache envelope never extends consent, capability, mandate, feed, flight or kill authority. Source drift requires an explicit protected save. This is an adoption requirement, not a claim that those native ports are implemented by this package.

    ResonanceMetaConfigurationSaveCommand contains the expected campaign/configuration revisions, schema version, idempotency key and exact original logical audience mappings:

    { audienceRuleId, mode: 'existing', nativeAudienceRef: { externalId, revision } }
    // or
    { audienceRuleId, mode: 'admitted_setup' }

    The original channel remains the editable account, dataset, Page, Instagram, country, category, age, budget, creative and destination definition. Save accepts no duplicate channel, provider request, created audience ID for setup intent, matching data or approval flag. The existing native audience reference uses its actual numeric external ID and source evidence revision.

    ResonanceMetaConfigurationSnapshot freezes the original channel, root/configuration revisions, reviewed definition digest, saved operation UUID, advertiser and nullable native names, measurement/profile references, friendly rules and resolved audiences. Each audience row is {audienceRuleRef, name, resourceRuleRef, excludedResourceRuleRefs, selection}. Its logical name is separate from selection.nativeAudienceName; its positive rule is separate from exclusions. Existing selection carries the native reference/name. Admitted selection carries setup: {kind: 'meta_website_audience_v1', localOutputKey, specDigest}. The local key is the original SDK audience:<id>:<revision> key; specDigest identifies the existing SDK audience input. Native HTTP request and compiled graph identities remain distinct private preparation evidence.

    The matching-profile ID is the actual persisted save operation UUID. Its revision is the positive integer configuration CAS; measurement configuration/policy strings are different fields. Native save must atomically persist the real operation, settings and snapshot before exposing that reference. A new explicit Meta save advances its configuration CAS and campaign review revision; the snapshot carries the resulting root revision. A replay advances neither. Draft metadata receipts don't require fabricated prepared versions or operational channel rows.

    resonanceMetaConfigurationDigestInput omits only its self digest and preserves all original material, including friendly labels. projectResonanceMetaConfiguration(snapshot, currentMetadata) returns {view, review}. Metadata contains currentCampaignRevision, native-owner-derived currentDefinitionDigest, observedAt, nullable expiresAt, reasonCodes and pendingRequirements. readyForReview is derived output: no blockers, a current root revision at least as new as the saved audit revision, an exact match between the current semantic definition digest and the saved reviewed definition digest, and a nonexpired observation horizon. Metadata-only root revision bumps can therefore preserve multiple unchanged channel configurations; original snapshots keep their real save revisions. Native owners must still verify the exact original channel, configuration CAS, saved operation, configuration digest and current source/resource/account/policy facts. A matching campaign digest never substitutes for those checks. The review is the unchanged original snapshot when those prerequisites hold, otherwise null. Pending native creation, validation or age observation never grants execution. Pure timestamp ordering doesn't prove freshness when a cached view is consumed; the actual owner and UI must withdraw stale reviewability.

    Explicit feed selection and original review

    parseResonanceMandateDraftRequest preserves the existing {expectedRevision, allowedOperations, expiresAt} request and accepts an optional minimal selection:

    websiteVisitFeedSelection: {
      channels: [{ channelId, expectedConfigurationRevision, resourceRuleRefs: [{ id, revision }] }]
    }

    Absent selection preserves no-feed behavior. Empty lists, duplicate selectors, full editable grants and copied destination/profile/readiness fields are rejected. The native owner resolves the exact saved configuration, profile receipt and positive rule versions through the existing mandate authority. An excluded-only page can't become a selected feed permission.

    The existing mandate-draft response remains the raw ResonanceMandateApprovalPayload. Before acceptance, reviewers use that original payload with exact immutable configuration review snapshots; mismatched refs, digests, revisions or plan material block review. Latest labels must not replace original reviewed labels. Actual native approval can use the existing legitimate member or invited delegated-agent authority.

    ResonanceWebsiteVisitFeedReview is a separate post-acceptance projection: {schemaVersion: 1, approval, mandateRef, configurations, current}. It requires a genuine nonnull accepted mandate reference. Before acceptance, the native read returns its typed unavailable/not-found result. Original historical snapshots remain readable under current authorized scope when current state is invalidated or unavailable. eligible describes current review observation and grants no execution authority. No-feed requires not_enabled and an empty configuration list. The saved configuration audit revision can precede the exact original approval/plan revision, but can never follow it. The optional original prepared-plan context checks exact approval/plan revision, matching channel material and definition digest. Native original reads must supply the actual stored plan and verify the selected original configuration identities. Preparation, approval, claim and acceptance still require the exact current native root revision; this configuration review rule does not relax those fences. Actual approval provenance, hashes, source facts, consent and admission remain native checks.

    Native owners plan separate original configuration and accepted feed-review reads under the existing protected configuration/mandate owners. This package adds no endpoint, approval surface or provider client. Public, manual and MCP entry points must continue to reject internal deliver_website_visit before filing; a parser or service label never proves protected origin.

    Provider-managed age intent

    The additional closed original Meta intent is {mode: 'provider_managed'}. It accepts no bounds, default flag or observed native values and never replaces absent, omitted or bounded intent. Its review promise is: “Use Meta age settings; record the initial observed configuration before activation.”

    Native create and validation requests must omit both age keys. Before activation, the first genuine same-root PAUSED AdSet creator receipt and complete scoped read must seal initial age values and key presence once in the existing protected operation. Activation must compare that unchanged observation and every independent non-age, consent, authority and budget gate. Later changes block. This intent makes no claim about exclusive default authorship, unlimited ages, legality or serving. Existing three-mode consumers need explicit preservation, editing and review support before adopting this branch.

    Reported-cost SQL clock

    The explicit reported_cpql_conserved_transfer_v1 policy requires costBasis: 'provider_reported_snapshot_v1', costRevisionRisk: 'accepted_provisional', readClockKind: 'sql_before_provider_read_lower_bound_v1' and the existing observational allocation thresholds. This is the sole reported-cost policy in this candidate. Earlier unpublished no-clock draft policy/evidence is rejected. Existing mature, finite and default profiles keep their meanings. Adoption requires compatible consumers and this exact policy in the original prepared plan, review and accepted mandate; parsing never grants authority.

    The evidence discriminator is reported_cpql_sql_clock_v1. It retains allocation/channel fields, replacing the legacy uncertaintySource with two required closed objects:

    • channelReportedCost: basis, protected immutable observationId, sourceEvidenceDigest, reportedSpend, exact queriedFrom/queriedThrough, actual firstReceivedAt/receivedAt, native recordedAt, required readClock, providerFinality unknown and correctionsPossible true.
    • outcomeSource: method observational_cpql_missing_outcome_bound_v1, eligibleContacts, fullyResolvedContacts, qualifiedContacts, native sourceRevision, original qualificationRuleRef and universeComplete true.

    The exact readClock is {kind: 'sql_before_provider_read_lower_bound_v1', notBeforeAt}. The trusted native producer must await the actual scoped SQL reply before any provider HTTP and bind its unaltered returned lower bound to the same run, target, query and protected immutable source receipt. Caller-supplied, post-read, cached or rebound clocks are invalid. A SQL-generated conservative millisecond lower bound remains a lower bound, never exact HTTP time. The readClock field preserves the actual returned UTC string in evidence/digests, accepting Z or +00:00 with up to six fractional digits; ordinary legacy wire instant formats are unchanged.

    Operational completion, age and decision expiry use SQL chronology: windowEnd <= notBeforeAt <= recordedAt <= observedAt. Raw first/final HTTP receipts remain finite and ordered within their own clock, without numeric comparisons to SQL. Millisecond arithmetic floors any finer native precision conservatively. The native SQL owner must enforce exact retained chronology and current freshness at final claim and every dispatch, together with original mandate/flight limits, actor, kill revision, source and funding guards.

    Keep one exact nonfinal provider spend observation and independent first-party qualified_goals, genuine CRM coverage and channel maturity. Common query windows require completed advertiser-local days with zero milliseconds. Equivalent UTC timestamp representations compare as instants. Query coverage never sets global/channel/provider dataThrough, verifiedSpend or spendPeriodComplete. Passing the actual prepared plan also checks its exact policy/objective, channel/account/site/timezone and frozen qualified cohort.

    reportedCpqlMissingOutcomeBound shares the integer outcome sensitivity arithmetic, conditional on reportedSpend. It does not bound cost corrections, establish financial finality, prove causal lift or guarantee cost ordering. Zero cost or no qualified contacts leaves it unavailable. Existing canonical digest functions bind clock kind, immutable cost and independent outcome provenance. Decisions retain observational_allocation/reduce_then_increase, include cost observation IDs and qualification source revisions, and expire by the conservative SQL anchor deadline.

    No new approval surface or engine is introduced. Native budget actions retain their supported original graph and period restrictions. Reported cost releases no donor hold or recipient funding; genuine incremental headroom above reserve remains required. Unknown donor effect stops recipient execution, unsupported funding stays unavailable, and corrections create new immutable history. Parser/schema/source checks cannot authenticate a provider exchange, prove native run binding, grant an action or replace those native checks.

    Public observation pages

    parseResonanceObservationsPage reads the existing {items, nextCursor, observedAt, support} envelope. Each public item adds four flat native identities to the existing metric: observationId, channelId, versionId and accountBindingId. parseResonancePublicObservationMetric extracts those identities and validates the remaining closed metric through the unchanged generic parser. parseResonanceObservationSupport validates the closed support union; the page parser then checks cross-object alignment. Matching TypeScript types and JSON schemas are exported from the same Resonance entry. Structural schemas alone do not enforce all semantic relationships.

    Every item has exactly one support entry at the same index, matching all four identities, source, account currency where present, asOf/fetchedAt and dataThrough meaning. A native provider observation may yield spend, impressions and clicks with the same row ID and repeated support; the unique key is observationId plus metric name. Genuine first-party qualified outcomes retain their native row identity and independent qualification sourceRef. Never derive observation identity from that qualification revision or insert contact counts as exposure counts.

    Provider support requires explicit nullable firstReceivedAt, receivedAt, recordedAt and readClock, plus providerFinality unknown, correctionsPossible true and coverageBasis closed_query_snapshot or not_established. Missing required flags fail parsing. First-party support forbids those provider-only fields. A complete closed query remains revisable and does not establish financial finality. Individual clicks or impressions may still be unknown even when row-level query coverage is complete; their value stays null and their metric reason remains separate from the support reason. Legacy/unestablished reporting stays explicit and supplies no operational freshness authority. Raw first/final HTTP timestamps are compared only within their own clock; native readClock bytes retain the final SQL-clock format without restamping.

    Pagination follows native-row UUID order, with at most 100 native rows and 500 expanded metrics per page (spend, impressions, clicks, reach and results). A non-null cursor references the last native row, never a metric offset. To display the latest snapshot, group by channel, exact window and metric, then compare support.fetchedAt, which must equal item.asOf as an instant. Do not sum repeated snapshots, turn unknown into zero or infer finality from coverage. The parser preserves reporting data; native API scope, protected producer lineage, original authority, current freshness and funding remain separate requirements.

    Original read-only provider reporting grant

    The existing mandate draft request accepts optional providerReporting: {agentContactId, channelIds}. This closed selector contains only the selected invited agent and explicit channels. It rejects purpose, organization, project, principal and approval fields. Absence stays omitted; null and the superseded Selection-suffix field are invalid. The server must derive the actual organization, project and current invited-agent acts-for principal, never a default agent or the reviewer identity.

    The resolved original mandate has optional providerReporting: {purpose: 'provider_reporting_refresh', orgId, projectId, agentContactId, principalContactId, channelIds}. All six binding fields are required when present. Channels are a unique nonempty UUID list with a maximum of 100. The agent and human principal remain distinct. The grant project must equal the parent mandate project. The original mandate, review payload and canonical digest include the exact resolved binding. Omitted fields stay out of the digest for older mandates.

    The server can add a signed reportingUntil UTC deadline to the resolved grant. It derives the deadline from the original flight end, the approved attribution window and two elapsed days for provider processing, with a maximum of 92 elapsed days after the flight. Reads stop at the deadline. The mandate's finance expiry still applies to spend and provider changes. Grants without a deadline keep their original reporting expiry.

    ResonanceProviderReportingSelection and ResonanceProviderReportingGrant have separate parser/schema exports. Existing mandate request/scope/approval parsers remain the entry points. Passing the actual prepared plan as the optional second argument to parseResonanceMandateScope also checks original plan/review/goal/flight identity and the selected paid channels within mandate sites/accounts and expiry. A public prepared plan has no organization field: exact parent organization equality and real current identities must be established by the protected native owner, not inferred from a project string or parser result.

    This purpose permits read-only report collection and persistence only. It adds no operation, budget mutation, optimization approval, send or child authority. Observation queries must stay within the actual original flight/policy bounds and current native authority. Adding or changing an agent/principal/scope/channel binding requires actual person review through the existing mandate surface; budget-only dominance cannot admit it. The service executor, invited agent and human authorizer remain distinct native actors.

    The existing review surface should display actual named agent, principal and selected scope from the native API projection. Parsing UUIDs is not proof of membership, an invitation, a token, a live acts-for relation or an accepted job claim. Native owners must verify the exact accepted parent grant, organization/project, current job/own claim, actor/principal, kill revision, policy/window, expiry and protected read/write admission before HTTP and persistence. Old mandates without this grant have no scheduled reporting authority. No new approval surface, grant store or bearer retrieval is introduced.

    Observed provider values require complete closed-query support. This is one-way: individual metrics may remain unknown when native query coverage is complete; legacy unknown/null reporting remains readable. It grants no finality, freshness or native authority.

    Retargeting several properties from one campaign

    A campaign can retarget visitors of several pages, one property each, without sharing audiences or creative between them. Each property is one Meta channel with its own audience, destination, creative and allocation, and the channels carry a shared channelGroup ({ key, label }). A channel names its property ({ key, label }) and may name a tier ({ label }) when one property has several recency tiers. Every one of these fields is optional, so a definition that uses none of them parses and serializes exactly as before.

    checkChannelGroups is the one rule for a group. Its channels must share site, account, dataset, Page, special categories, countries, objective and optimization; channels for one property share one destination and channels for different properties don't; no two channels share a property and tier; tiers of one property can't overlap in time; and a group holds at most RESONANCE_MAX_CHANNELS_PER_GROUP (20) channels. A channel in a group with a special category must use provider-managed age. When a definition uses groups, the paid allocations can't add up to more than the campaign total less its reserve.

    splitBudget(total, weights, quantumMicros) divides a total across whole weights in whole provider quanta, largest remainder first, ties to the lower index, so the shares add up to the total exactly. suggestPropertyWeights(visitors, { floorBasisPoints, ceilingBasisPoints }) proposes weights in basis points from each property's unique visitors, 10 percent floor and 40 percent ceiling by default. It's a suggestion: equal weights are the default and a person approves any other split. expandPropertyChannels(definition, groupKey, additions, { quantumMicros, weights }) returns the new channels for properties not yet in the group, built from the group's first channel, with ids derived from the project, campaign slug, group and property so expanding twice changes nothing. It also returns the group's new allocations and the reasons a person still has to act, such as property_creative_required:<key>. It never sets a creative, a converter acknowledgement (convertersAcknowledged) or an approval. The measurement rule, audience version and destination for a property are native objects you create first and pass in.

    An audience reference can carry minDaysSinceVisit (1 to 179), a recency band that keeps only people whose latest visit is at least that many days old. checkAudienceBand(ref, provider) requires the band to be shorter than the retention window, caps a Meta window at META_WEBSITE_AUDIENCE_MAX_RETENTION_DAYS (180) and a Meta audience at ten rules, and refuses a band on Google. The recency, window and rule checks run on a definition only for a Meta channel that uses a group or a band.

    metaExclusionPolicy(channel, { targetingLevel, inRule }) answers whether an exclusion is allowed. Under a special category a targeting-level custom-audience exclusion is refused with meta_exclusion_targeting_blocked_special_category while META_SAC_CUSTOM_AUDIENCE_EXCLUSION_VERIFIED is false, and an in-rule exclusion or band is allowed only when Meta's own eligibility readback for that audience says so. META_CALL_TO_ACTIONS lists the call-to-action values a Meta ad accepts, and primaryText (up to 2200 characters) is the ad's main text, separate from the first card's description.

    Provider metrics gain reach (unique people, counting unit provider_unique_reach) and results. Reach is never added across channels or windows. deriveProviderRatios(items) is the one place the ratios are computed, from provider-sourced, observed items that share one observation, channel and window. Frequency is impressions over reach, and cost per result is spend over results rounded half to even at one micro. Zero reach, zero results, a missing input or mixed inputs give an unknown result with a reason, never zero and never a guess.

    Explicit Meta reporting queries

    The existing report selector and resolved grant accept optional metaQueries. Each row contains exactly channelId, attributionWindow (1d_click, 7d_click or 1d_view), actionReportTime: 'conversion' and basis: 'explicit_query'. A present list contains 1–100 rows, has unique channel identities and stays within the selected channelIds. UUID identity comparisons ignore case; parsers preserve the supplied text and order. The exported RESONANCE_META_QUERY_ATTRIBUTION_WINDOWS is the shared window list.

    Omitting the field preserves legacy payloads and digest material. It doesn't upgrade a historical grant to permission for fresh automatic Meta reporting. The native owner checks actual Meta channel coverage, account/site/version membership and original human review. Human manual reporting and passive history keep their existing authorization rules. These are requested report queries; they don't describe configured attribution or claim parity with Ads Manager. Review and adopt the same contracts version across producers and consumers before sending the extended shape to an older strict parser.

    Explicit audience readiness checks

    parseResonanceMetaRetargetingReadiness, its matching type and RESONANCE_META_RETARGETING_READINESS_JSON_SCHEMA describe one scoped public response. It contains the current campaign/channel/account identity, the existing configuration view and per-rule inclusion/exclusion page references. An audience check is either not_checked with a bounded reason, or observed with the existing classifier verdict/reasons, actual native audience ID and nullable estimated bounds. RESONANCE_META_AUDIENCE_VERDICTS and RESONANCE_META_AUDIENCE_REASONS define the shared public vocabulary; provider classification stays with the API owner.

    An observed check's observedAt identifies the actual completed owner check. It doesn't date an estimated audience sample. sizeObservedAt and sizeExpiresAt are explicitly null in this version, and the current producer has no audience expiry to supply. Missing size stays null, independently of an observed status. Consumers mustn't add bounds across rules or infer fresh sample data from configuration expiry. A source/revision drift, denied scope or provider failure is a transport error, not a fabricated readiness result. The parser checks the closed response and its public scope relationships; actual native ownership, provider checks, launch and delivery remain separate.

    Guided Meta audience setup

    Use @sonordev/contracts/resonance to review audience setup for a saved draft before you add creative or budget. For example, a fictional bike shop could select an existing dataset and review an audience for visits to its repair page.

    • Use parseResonanceMetaDatasetSelectionRequest for existing selection and parseResonanceMetaDatasetSelectionWitness for the verified dataset ID, resource revision, and observation time. For dataset creation, use the parseResonanceMetaDatasetSetupPrepareRequest, parseResonanceMetaDatasetSetupReview, and parseResonanceMetaDatasetSetupReceipt contracts. Prepare and intent share parseResonanceMetaDatasetName, which limits trimmed names to 160 UTF-16 code units.
    • Use parseResonanceMetaAudienceSetupPrepareRequest to select one saved audience rule and an exact dataset revision. The owner resolves the reviewed scope in parseResonanceMetaAudienceSetupReview. Choose feed: { kind: 'off' } or explicitly opt in with feed: { kind: 'enable', expiresAt }. Opt-in lets the native owner activate a separate revocable grant after it verifies the exact approved audience. A later enablement or scope change needs fresh review.
    • Use parseResonanceMetaAudienceSetupStatus for the provider receipt and any linked grant. The receipt preserves the first provider outcome separately from verified readback. Use parseResonanceMetaAudienceSetupReadiness to read accepted visits and provider audience readiness as separate observations. A null observation means the corresponding evidence is unavailable. Use parseResonanceMetaAudienceSetupList to restore saved operations after reload, with up to 25 items and a UUID or null cursor.

    Only eligible visits from the active grant window can be considered for delivery. The native owner checks approval, current scope and consent before dispatch. The parsers validate wire shape and consistency. Campaign launch and spend require their own authorization.

    Positioning preview

    Use parseResonancePositioningPreviewRequest to select a saved draft revision, site and exact Meta, Google Search or Broadcast target. A destination or offer can be absent while you're exploring. Applying a ready suggestion requires a current verified destination and any selected offer.

    parseResonancePositioningPreview separates the buyer rationale, source references and suggested copy. A fictional bike shop might use a verified booking page to support a draft about choosing a drop-off location, while keeping its guess about walk-in demand labeled as a hypothesis. Provisional and no-fit results carry reasons and no application token.

    parseResonancePositioningApplyRequest accepts the owner's application token. The owner rechecks the original scope and current evidence before updating a draft or passing the selected text to native Broadcast preparation. Publication and campaign launch follow their existing approval paths.

    Property interest analytics

    Use @sonordev/contracts/property-interest for property exposure and deliberate-action events. parsePropertyInterestEvent accepts the reserved category real_estate_interest and a native listing UUID, surface, and optional display ordinal. The API resolves the listing against the site's scope before admitting the event.

    parsePropertyInterestReportForRequest(response, request) checks the site, time window and exact selected listing set. A broad report uses UUID pagination with at most 50 properties per page. Each property's collection and detail cohorts keep exposure sessions, eligible action sessions, unmatched action sessions and events without a session distinct. propertyInterestRateBps returns a rounded basis-point rate or null when there are no exposure sessions.

    Accepted tour inquiries have explicit source availability. A verified zero remains different from unavailable evidence. These reports describe site activity. They establish no advertising audience, booking, qualified buyer or causal result.

    Budget approved on a person's word

    Added in 2.27.0: @sonordev/contracts/resonance-confirmation is the one wire contract between the agent side (Signal) and Sonor's API for the emailed code behind a budget a person approves in chat. @sonordev/contracts/quote-screen is the one screen for the quote that approval carries. Both are dependency-free.

    import {
      confirmationRequestPath,
      confirmationRedeemPath,
      parseConfirmationRedeemRequest,
      parseOnTheirWordEvidence,
      confirmationFailureOf,
    } from '@sonordev/contracts/resonance-confirmation'
    import { refuseQuote } from '@sonordev/contracts/quote-screen'
    
    refuseQuote('Yes, go ahead with Q4-BRAND-SEARCH-2026') // null: a campaign name is not a secret
    refuseQuote('yes, the Stripe key is sk_live_abcdefghijklmnop') // 'secret'

    Two routes carry the whole flow: ask for a code (confirmationRequestPath), then redeem it for the exact request the agent filed (confirmationRedeemPath). The code goes to the person's verified login email and never back to the agent. The redeem body is exactly confirmationId, ledgerActionId and code. The evidence the Ledger keeps has six keys (agent, quote, mandate_digest, review_digest, channel, confirmation). parseOnTheirWordEvidence reads its shape only. Whether the code was really redeemed for that request is the database's word, and a stored quote is never screened again. CONFIRMATION_REFUSALS holds every refusal code with its status and words, and confirmationFailureOf turns any answer into one of them (anything unknown reads as unavailable, which approves nothing). The confirmation mail carries a subject tag and an X-Sonor-Confirmation header (isConfirmationMail), so a mailbox reader can keep it out of anything an agent reads.

    refuseQuote checks the length first (1,000 characters, in constant time) and then reads the quote. It refuses provider keys, tokens, logins, passwords, PINs, payment card numbers, IBANs and bank or social security numbers. A campaign name written with words, abbreviations, capitals or separators passes. A single unbroken run of 24 or more letters and digits with no separator looks like a token and is refused; QUOTE_KNOWN_LIMITS lists examples, and the agent asks for the name with separators or its id instead.

    Booking intake

    Added in 2.27.0, @sonordev/contracts/booking-intake is the one rule for the "About your business" step a booking type can put between the guest picking a time and their contact details. It asks for a company name and, optionally, a website.

    A type's step is off, optional or required. parseBookingBusinessStep reads anything unknown, null or missing as off, so an old row or an API that predates the column asks nothing. optional and required describe the company; the website is always optional, and a guest who ticks "we don't have a website yet" sends noWebsite: true, which wins over any website sent with it. The three wire fields are company, website and noWebsite (BOOKING_GUEST_BUSINESS_FIELDS), and BOOKING_INTAKE_JSON_SCHEMA describes them for an agent.

    checkBookingBusinessAnswers(step, { company, website, noWebsite }, { source, verifiedMember }) is the check the widget, the app's booking page and the API all run, and the API runs it again on the server. It always cleans what it's given, whatever the step:

    • normalizeBookingCompany turns runs of whitespace into one space (the next-line control and the Unicode spaces included) and removes control and format characters (bidi overrides, zero-width marks, a byte-order mark) and lone surrogates, because the name ends up in a host's email, a calendar description and Echo's text. It never truncates; more than 120 characters is too_long.
    • normalizeGuestWebsite turns what a guest typed into { ok: true, url, host }: https:// when there's no scheme, no query, fragment, port or credentials, the path kept as the URL parser writes it, and www. kept in the url and dropped from the host when two or more labels remain. It's null when the box was empty and { ok: false, reason } when it isn't an address. reason is too_long for more than 300 characters, or when the cleaned address is longer than the 300 characters a booking stores (an international host or a non-ASCII path grows when it's encoded), and invalid for everything else: another scheme, credentials, a port, an IP address, a host with no dot or no real top-level domain, and the literal local names localhost, .local and .internal. It never says why a host was refused. It runs no DNS and fetches nothing, so a name that only resolves to a private address passes: anything that later fetches the address, such as a site review, must resolve it and run its own DNS-pinned check first. The url is text a guest typed, so HTML-escape it wherever it's rendered, attributes included, and don't decode it.

    It refuses (ok: false, with errors per field) whenever the type asks (optional or required), unless the caller is exempt. A required type refuses a missing company. The only exemption is portal, a Sonor member's or Echo's booking made for someone else, and only when the caller also passes verifiedMember: true (bookingBusinessExempt). A source is a string any caller can send, so the API sets verifiedMember from its authenticated context (the signed-in member or the service key) and never from the request body. A missing, empty or unknown source is held to the answers like any other. Where the type doesn't ask, or the caller is exempt, a value that doesn't fit is left out and reported in value.dropped, so a booking nobody asked a question on is never failed by a long CRM company or a malformed CRM website. BOOKING_BUSINESS_ERROR_TEXT holds the words a guest is told, and describeBookingBusinessErrors maps a refusal to them, so the widget, the app and the API's 400 say the same thing.

    bookingBusinessDetails(row, contact) is the one reader for every surface a host sees the answers on. The booking row wins and the CRM contact only fills what the row lacks; a contact's website is read again and dropped if it isn't an address, and a guest who said they have no website is never contradicted by one the CRM has. from says where the answers came from.

    The browser-safe part (the normalizers, the check and the error text) is its own module, booking-intake-normalize, so the booking widget doesn't bundle the agent schema or the host reader. Everything is also exported from @sonordev/contracts/booking-intake. The hold length and which hosts a site review skips are decisions of the API, not part of this contract.

    Sales call preparation

    Added in 2.24.0, @sonordev/contracts/sales-call-prep provides pure request, content, context, version, use and learning-summary parsers, matching types and JSON schemas. It adds no network, storage, hashing or browser Node dependency.

    import {
      parseSalesCallPrepRequest,
      salesCallPrepRequestDigestInput,
      SALES_CALL_PREP_STYLE_POLICY_VERSION,
    } from '@sonordev/contracts/sales-call-prep'
    
    const request = parseSalesCallPrepRequest({
      schemaVersion: 1,
      requestId: '00000000-0000-4000-8000-000000000001',
      projectId: '00000000-0000-4000-8000-000000000002',
      selectedContactId: null,
      objective: 'qualify',
      style: 33,
      stylePolicyVersion: SALES_CALL_PREP_STYLE_POLICY_VERSION,
      callNotes: '',
      regenerate: false,
    })
    const canonicalRequest = salesCallPrepRequestDigestInput(request)

    Objectives are qualify, book, follow_up and advance. Style is an integer from 0 to 100, with anchors Professional (0), Conversational (33), Bold (67) and Wild (100). The selected number and policy version stay explicit. A style setting doesn't authorize invented facts, promises or consent. callNotes holds at most 4,000 characters. The request carries no organization, actor or offer authority; the authenticated owner resolves those relationships.

    parseSalesCallPrepContent keeps the compatible camelCase briefing fields and adds one closed callGuide. Its main opener must match recommendedOpening. The guide separates observations, cited source IDs, hypotheses and unknowns, with distinct interested, busy, existing-provider, send-information and not-a-fit responses. needs_context identifies what is missing and has no ready opener. Source observation dates may be unknown; they aren't filled with the current time. Supply actual resolved source references to check citation metadata, or use parseSalesCallPrepContentForContext to also check saved-voice availability. Shape validation alone doesn't establish factual truth or source permission. The guide can cite at most 30 sources; the actual resolved witness can retain up to 100, so bounded history and seller guidance don't need to be discarded.

    The context and witness parsers accept a closed, server-resolved projection of actual private bindings, source revisions, Brain/voice availability, history, approved-guidance references and prompt/schema versions. Private notes stay outside that witness. salesCallPrepNotesDigestInput serializes the exact note as a JSON string, including whitespace. The server hashes its UTF-8 bytes and supplies notesDigest in the context. Context, witness and content have their own *DigestInput serializers. Object keys are sorted; witness reference sets sort by ID; meaningful content list order stays unchanged. These functions don't create hashes or native IDs.

    parseSalesCallPrepVersion describes an actual persisted immutable version. Human edits name their parent and expected head/context. A cached version keeps its original request and version identities; a later cache request doesn't rewrite them. parseSalesCallPrepGenerateResult keeps the current operation's requestId and reused flag outside the original version receipt. A model result or legacy unversioned briefing isn't a saved version. Native owners must validate digests, current context, access, idempotency and fencing before returning a saved receipt.

    parseSalesCallPrepConfirmUseRequest requires an actual attemptId, the final versionId, confirmedUsed: true, and a callId or manualEventId. Generated, shown, copied, dialed and transcript-inferred activity cannot enter that confirmed-use command. Native owners validate the selected person and actual source. Corrections and retractions append to the use chain. A retraction retains its source snapshot without a confirmed-use assertion. Current source eligibility and manual-event ambiguity are separate from the immutable receipt. parseSalesCallPrepScriptUseResult can report a missing use link and a retry even when the surrounding disposition was saved.

    Learning summaries remain principal-private and observational. Generated, confirmed, inferred, connected, qualified, booked, held, won, lost and unknown counts stay separate. Booked doesn't mean held; missing doesn't mean failed. Bounded eligible-use references aren't a whole-cohort denominator. The summary serializer omits only its self snapshotDigest; the server computes it. Only the existing human-reviewed ledger owner can supply eligible generalized principles. Parsing a principle or proposal receipt neither approves it nor makes private scripts, notes or transcripts shareable. Existing ledger review and revert controls remain authoritative.

    Packed import, require and declaration checks are package proof; each application's native joins, permissions and behavior still need its own verification before a release.