@apotech-os/support-kit 10.1.1 → 10.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/{chunk-G3Q4P4OA.js → chunk-ZKFQ3DIY.js} +418 -228
- package/dist/chunk-ZKFQ3DIY.js.map +1 -0
- package/dist/index.cjs +1297 -490
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +132 -68
- package/dist/index.d.ts +132 -68
- package/dist/index.js +763 -106
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +334 -60
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +213 -52
- package/dist/ui/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-G3Q4P4OA.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/domain/classification.ts","../src/domain/profile.ts","../src/domain/publication.ts","../src/domain/evaluation-verdict.ts","../src/domain/origin.ts","../src/graph/state.ts","../src/graph/ports.ts","../src/guardrails/constants.ts","../src/guardrails/text.ts","../src/guardrails/channel-pre-gates.ts","../src/guardrails/raw-ticket.ts","../src/guardrails/run-guardrails.ts","../src/graph/nodes/guardrails.ts","../src/guardrails/verify-reply.ts","../src/adapters/conversation-mapping.ts","../src/guardrails/reconstruct-hold.ts","../src/verdict/policy.ts","../src/graph/nodes/fetch-context.ts","../src/graph/nodes/triage.ts","../src/graph/nodes/escalate.ts","../src/graph/nodes/authorize.ts","../src/graph/tools/read-tools.ts","../src/graph/tools/registry.ts","../src/graph/draft.ts","../src/graph/nodes/shared.ts","../src/graph/nodes/draft.ts","../src/graph/nodes/evaluate.ts","../src/graph/revise.ts","../src/graph/nodes/revise.ts","../src/graph/markdown-to-html.ts","../src/graph/nodes/act.ts","../src/graph/run-ticket.ts","../src/status/machine.ts","../src/prompts/slots.ts","../src/records/ids.ts","../src/records/agent.ts","../src/settings/conversation-end.ts","../src/settings/fields.ts","../src/settings/validate.ts","../src/settings/warnings.ts","../src/settings/to-profile.ts","../src/domain/dashboard-stats.ts","../src/domain/reply-timing.ts","../src/functions/records.ts","../src/domain/dashboard-queries.ts","../src/settings/delivery-policy.ts","../src/functions/response-comparison-diff.ts","../src/functions/followup-webhook-install.ts","../src/domain/tool-input-error.ts","../src/domain/period.ts","../src/domain/timeline.ts"],"names":["answerableChannels","customerChannelAddress","accountChannelAddress","firstCustomerMessage","isInternalNoteChannel","fallback","trimmed","draft","hasDiverged","outcome","finish","step","triage","evaluate","failed","i","j"],"mappings":";;;AAQO,IAAM,iBAAA,GAAoB;;;ACI1B,IAAM,mBAAA,GAAsB;AAa5B,IAAM,cAAA,GAAiB,CAAC,eAAA,EAAiB,YAAA,EAAc,YAAY;AASnE,IAAM,qBAAA,GAAsC;AA6B5C,IAAM,gBAAA,GAAmB;AAAA,EAC9B,OAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA,cAAA;AAAA,EACA,0BAAA;AAAA,EACA,mBAAA;AAAA,EACA,mBAAA;AAAA,EACA,sBAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF;AAoBO,IAAM,0BAAA,GAA+C;AAAA,EAC1D,OAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF;AAQO,SAAS,8BAA8B,YAAA,EAAiD;AAC7F,EAAA,OAAQ,YAAA,IAAgB,OAAQ,eAAA,GAAkB,YAAA;AACpD;AAQO,IAAM,4BAAA,GAA+B;AACrC,IAAM,+BAAA,GAAkC;;;AChFxC,SAAS,gBAAgB,YAAA,EAA2D;AACzF,EAAA,IAAI,CAAC,cAAc,OAAO,IAAA;AAC1B,EAAA,MAAM,UAAU,YAAA,CAAa,aAAA;AAC7B,EAAA,IAAI,OAAA,KAAY,YAAY,OAAO,eAAA;AAKnC,EAAA,IAAI,YAAY,OAAA,EAAS,OAAO,YAAA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ification field in the graph\n * (`Classification.reasoning`, `escalate`'s own reasoning, `Verdict.reason`)\n * — one domain rule, one constant, so `triage`/`escalate`/`evaluate` stop\n * each declaring their own `280` under a different local name.\n */\nexport const REASONING_MAX_LEN = 280;\n\nexport interface Classification {\n /** The `tag_name` of the profile's Category referential, never a channel tag. */\n category: string;\n confidence: 'high' | 'low';\n /** Written justification, ≤ 280 chars — NOT the model's reasoning effort/trace. */\n reasoning: string;\n /** True when triage failed and this is the `unknown_tag` fallback decision (I1). */\n isFallback: boolean;\n}\n","// Spec: architecture_agent_graphe.md §5.3\n\nimport type { ActionDecision } from './action';\nimport type { ChannelKind } from './channel';\nimport type { NodeKey } from './cost';\nimport type { ReasoningEffort } from './reasoning';\n\n/**\n * Key of the single tenant that exists before any second profile is created.\n * Named once here so every scoped collection shares one source of truth\n * instead of repeating the literal `'customer'`.\n */\nexport const DEFAULT_PROFILE_KEY = 'customer';\n\n/**\n * Per-tenant WhatsApp authorisation (whatsapp spec §9.1), replacing the old\n * `whatsappEscalateOnly` boolean:\n * - `escalate_only` — today's behaviour (and the default/rollback state):\n * the `whatsapp` guardrail holds every WhatsApp ticket for a human.\n * - `draft_only` — the channel rules apply and a draft is produced\n * (`ready`), but it is NEVER auto-sent — a human publishes it.\n * - `auto_reply` — reserved for a later lot (note-chevron publishing).\n * Settable ahead of time, but nothing gives it any effect beyond what\n * `draft_only` already does until the WhatsApp send path exists.\n */\nexport const WHATSAPP_MODES = ['escalate_only', 'draft_only', 'auto_reply'] as const;\nexport type WhatsappMode = (typeof WHATSAPP_MODES)[number];\n\n/**\n * The fail-safe reading everywhere a `whatsapp_mode` field might be absent\n * (a document that predates it) — the gate must never be silently open\n * (§9.1). One constant so every fallback site agrees, instead of copies of\n * the string literal.\n */\nexport const DEFAULT_WHATSAPP_MODE: WhatsappMode = 'escalate_only';\n\n/**\n * The Gorgias channels a ticket can arrive on, as `Conversation.sourceChannel`\n * reports them (`isWhatsappTicket(raw) ? 'whatsapp' : raw.channel`).\n *\n * Exists so an operator can say WHERE auto-send applies instead of\n * discovering the answer in a hold — `act` used to decide publication with a\n * binary (WhatsApp, or else email) in a world that has more than two\n * channels.\n *\n * Census of a live Gorgias account, 28/09/2026, 3 000 most recent tickets\n * (count / of which carry an email address):\n * instagram-comment 1858/0 · email 643/643 · instagram-direct-message\n * 202/0 · whatsapp 141/133 · phone 113/86 · chat 19/19 ·\n * instagram-mention 13/0 · facebook 7/0 · facebook-messenger 2/0 ·\n * instagram-ad-comment 1/0 · internal-note 1/1.\n *\n * Listed in that order, so the Réglages checkboxes read in the order an\n * operator meets them. `sms` and `contact-form` are Gorgias channels this\n * account has never seen; they are kept because an allowlist that omits a\n * channel turns it into a silent non-send — the very failure the census was\n * run to avoid, after a first draft of this list missed `instagram-comment`\n * (41 % of the account's volume).\n *\n * A channel this list does not name is deliberately NOT restricted — see\n * `isAutoSendChannel` in `verdict/policy.ts`. The list can only take away\n * what an operator can see and give back.\n */\nexport const SUPPORT_CHANNELS = [\n 'email',\n 'whatsapp',\n 'phone',\n 'chat',\n 'sms',\n 'contact-form',\n 'instagram-direct-message',\n 'instagram-comment',\n 'instagram-mention',\n 'instagram-ad-comment',\n 'facebook',\n 'facebook-messenger',\n] as const;\n\nexport type SupportChannel = (typeof SUPPORT_CHANNELS)[number];\n\n/**\n * Exactly the channels that were auto-sending BEFORE this setting existed —\n * every one that reaches a customer through the email path, plus WhatsApp.\n *\n * Two defaults were wrong before this one. `['email', 'whatsapp']` would\n * have switched off `chat` (census: 19/19 carry an address) and `phone`\n * (86/113), both auto-sending in production (tickets 597912560, 597887833).\n * The whole catalogue would have been right while no social channel COULD\n * publish — but `domain/publication.ts` now gives Instagram and Facebook a\n * real path, so leaving them checked would start auto-replying there the day\n * this deploys, on a payload shape nobody has validated against the live API\n * (`replyOnChannel`'s own doc).\n *\n * So the social channels ship OFF. Turning one on is an operator's explicit\n * act, after a test ticket has proved the send works.\n */\nexport const DEFAULT_AUTO_SEND_CHANNELS: SupportChannel[] = [\n 'email',\n 'whatsapp',\n 'phone',\n 'chat',\n 'sms',\n 'contact-form',\n];\n\n/**\n * Iso-behaviour mapping (§9.1) from the old boolean to the new mode:\n * `true → escalate_only`, `false → draft_only`. `auto_reply` is never\n * produced by this function — reaching it is an explicit operator opt-in,\n * never something derived on anyone's behalf.\n */\nexport function whatsappModeFromLegacyBoolean(escalateOnly: boolean | undefined): WhatsappMode {\n return (escalateOnly ?? true) ? 'escalate_only' : 'draft_only';\n}\n\n/**\n * Per-tenant channel prompt names (replaces the `/whatsapp` sibling prompt\n * mechanism): just the NAME of the Langfuse text prompt whose content is\n * substituted for `{{channel_prompt}}` in the agent's own prompt, one per\n * channel.\n */\nexport const DEFAULT_CHANNEL_PROMPT_EMAIL = 'shared/style-email';\nexport const DEFAULT_CHANNEL_PROMPT_WHATSAPP = 'shared/style-whatsapp';\n\n/**\n * Langfuse prompt reference carried by a profile — name + label + fallback\n * body (§5.3 \"nom Langfuse + label + fallback (I16)\").\n */\nexport interface PromptRef {\n name: string;\n label: string;\n /** Prompt body served when Langfuse is unreachable or unconfigured (I16). */\n fallback?: string;\n}\n\n/**\n * A timestamped run outcome. Mirrors the legacy `*_last_run_started_at` /\n * `_completed_at` / `_status` field triples, nested once per profile.\n */\nexport interface RunStamp {\n startedAt: Date | null;\n completedAt: Date | null;\n status: string | null;\n}\n\nexport interface TriageNodeConfig {\n model: string;\n provider: string;\n reasoning: ReasoningEffort;\n}\n\n/**\n * No `skipsFastResponse` (B3): the legacy's per-profile \"escalate but still\n * pre-generate\" switch has no meaning here — `graph/run-ticket.ts` finishes\n * unconditionally on `escalated`, so nothing downstream could act on it.\n */\nexport interface EscalateNodeConfig {\n model: string;\n provider: string;\n reasoning: ReasoningEffort;\n}\n\nexport interface DraftNodeConfig {\n model: string;\n provider: string;\n reasoning: ReasoningEffort;\n maxToolCalls: number;\n}\n\nexport interface EvaluateNodeConfig {\n model: string;\n provider: string;\n reasoning: ReasoningEffort;\n minConfidence: number;\n escalationEnabled: boolean;\n}\n\nexport interface ReviseNodeConfig {\n model: string;\n provider: string;\n reasoning: ReasoningEffort;\n}\n\n/**\n * The steps with a Langfuse prompt of their own — every LLM step except\n * `revise`, which re-runs the writer with a fixed correction turn\n * (`graph/revise.ts`) and so speaks with `prompts.draft`, never a prompt of\n * its own.\n */\nexport type PromptTableKey = Exclude<NodeKey, 'revise'>;\n\nexport interface AgentProfile {\n /** 'customer' | 'partner' | 'social' … — the tenant identifier. */\n key: string;\n /** At most one profile; serves the public surfaces. */\n isDefault: boolean;\n enabled: boolean;\n /**\n * Tenant colour for the admin UI chrome. Optional — absent/`null` falls\n * back to a deterministic hash of `key`, so a profile needs no\n * configuration to get a stable colour across sessions.\n */\n color?: string | null;\n source: { channel: ChannelKind; viewOrTag: string };\n schedule: {\n triageIntervalMinutes: number;\n triageBatchLimit: number;\n triageConcurrency: number;\n fastResponseIntervalSeconds: number;\n fastResponseBatchLimit: number;\n fastResponseConcurrency: number;\n fastResponseTtlMinutes: number;\n };\n /**\n * Each optional step is nullable; `null` = step absent for this tenant.\n * Real modes: `draft: null` = tenant \"triage only\"; `evaluate: null` =\n * generation without evaluation (always `ready`, auto-send impossible).\n * `model`/`provider` are authoritative: the resolved Langfuse prompt's\n * model config never overrides them.\n */\n nodes: {\n triage: TriageNodeConfig;\n escalate: EscalateNodeConfig | null;\n draft: DraftNodeConfig | null;\n evaluate: EvaluateNodeConfig | null;\n revise: ReviseNodeConfig | null;\n };\n prompts: Record<PromptTableKey, PromptRef>;\n /** Tool names resolved against the registry (§6.2). */\n tools: string[];\n guardrails: {\n /** Rules active among the catalogue (§6.5, I7). */\n active: string[];\n /**\n * NB: `UNCERTAINTY_MARKERS` stays a code constant, deliberately NOT\n * configurable per profile — the sole exception to \"params are per\n * tenant\" (§6.5).\n */\n params: {\n noreplySenders: string[];\n blocklist: string[];\n whatsappMode: WhatsappMode;\n judgemeEscalateOnly: boolean;\n /** Langfuse prompt NAME substituted for `{{channel_prompt}}`, per channel. */\n channelPromptEmail: string;\n channelPromptWhatsapp: string;\n };\n };\n /** Per action kind (P3). */\n authorization: Record<string, ActionDecision>;\n /** Materialisation tags (I20). */\n audit: {\n unknownTag: string;\n handledTag: string;\n escalationTag: string;\n sentTag: string;\n needsHumanTag: string;\n followupTag: string;\n /** This app's ownership mark on every ticket its triage sees — empty stamps nothing. */\n appScopeTag: string;\n };\n autoSend: {\n enabled: boolean;\n senderEmail: string | null;\n minConfidence: number;\n requireHighTriage: boolean;\n /** Where auto-send applies (`SUPPORT_CHANNELS`). An allowlist: a channel absent from it never sends. */\n channels: string[];\n };\n rename: { enabled: boolean; from: string; to: string } | null;\n /** Execution state PER TENANT (I13). */\n runtime: {\n triageLock: { acquiredAt: Date | null; owner: string | null };\n fastResponseLock: { acquiredAt: Date | null; owner: string | null };\n triageLastRun: RunStamp;\n fastResponseLastRun: RunStamp;\n lastAutoSendDecisionAt: Date | null;\n };\n}\n","/**\n * HOW a reply can be published on a conversation — the one question `act`\n * used to answer with a binary (WhatsApp, or else email).\n *\n * That binary sent every Instagram and Facebook thread down the email\n * branch, where the contact has no address, and killed it there\n * (`customer_email_missing`, tickets 597737746/597892224). The mistake was\n * not the missing address: it was treating \"an email address\" as the\n * universal recipient. A Gorgias ticket says otherwise — it carries\n * `reply_options`, naming the channels it can be answered on, and the\n * customer carries one address PER channel (an Instagram id, a Facebook id,\n * an email).\n *\n * So the address requirement belongs to the EMAIL path alone, and every\n * other channel is publishable exactly when Gorgias says it is and both\n * endpoints of the conversation are known.\n */\nimport type { Conversation } from './conversation';\n\n/**\n * - `whatsapp_note` — the chevron-prefixed internal note the WhatsApp bridge\n * forwards; needs no recipient address of any kind.\n * - `email` — an outbound email; needs the customer's email address.\n * - `channel` — a reply posted on the ticket's own channel (Instagram DM,\n * Facebook Messenger…), addressed by the two channel ids.\n */\nexport type PublicationMode = 'whatsapp_note' | 'email' | 'channel';\n\n/**\n * The mode a reply would go out on, or `null` when this conversation cannot\n * be answered automatically at all.\n *\n * Order matters and is deliberately conservative:\n * 1. WhatsApp keeps its note path, unchanged.\n * 2. A customer WITH an email address keeps the email path, unchanged —\n * that is how `chat` and `phone` tickets have been auto-answering all\n * along (census 28/09/2026: chat 19/19 and phone 86/113 carry one), and\n * this is not the change to start rerouting them.\n * 3. Only then, a channel Gorgias declares answerable and whose two\n * endpoints are known. This is the new path, and the only one it opens\n * is for contacts that had no address at all.\n */\nexport function publicationMode(conversation: Conversation | null): PublicationMode | null {\n if (!conversation) return null;\n const channel = conversation.sourceChannel;\n if (channel === 'whatsapp') return 'whatsapp_note';\n // An email ticket has exactly one path, and it needs the address. Falling\n // through to the channel path would be absurd here — `reply_options` does\n // list `email` as answerable, and the contact does carry an `email` entry\n // in `customer.channels[]`, so without this the two would compete.\n if (channel === 'email') return conversation.customer.email ? 'email' : null;\n if (conversation.customer.email) return 'email';\n return canPublishOnOwnChannel(conversation) ? 'channel' : null;\n}\n\n/**\n * Gorgias says the channel is answerable, and we know both ends of the\n * conversation on it: the customer's address (`customer.channels[]`) and our\n * own (the inbound message's `source.to`). Missing either one means a\n * payload we cannot address a reply with, whatever Gorgias allows.\n */\nfunction canPublishOnOwnChannel(conversation: Conversation): boolean {\n const { sourceChannel, answerableChannels, customerChannelAddress, accountChannelAddress } = conversation;\n if (!sourceChannel) return false;\n return (\n answerableChannels.includes(sourceChannel) && customerChannelAddress !== null && accountChannelAddress !== null\n );\n}\n","// Ported unchanged from legacy `src/utils/evaluationVerdict.ts` (agent 4) —\n// the single source of truth shared by the FastResponse schema, the\n// structured-output schema, the worker, the auto-send guard and the\n// admin/API routes. Kept free of any other import so consumers never pull a\n// model in just to read a verdict.\n//\n// Spec: escalade_avec_reponse_attente.md §4.1 (legacy); ported per\n// spec-migration-gorgias-backoffice-v1.md §3.3 (\"`verdict/policy.ts` —\n// `predicates.ts`\" depends on this vocabulary, hence its place in `domain/`).\n\nexport const EVALUATION_VERDICTS = ['send', 'send_and_escalate', 'hold'] as const;\n\nexport type EvaluationVerdict = (typeof EVALUATION_VERDICTS)[number];\n\nexport function isEvaluationVerdict(value: unknown): value is EvaluationVerdict {\n return EVALUATION_VERDICTS.includes(value as EvaluationVerdict);\n}\n\n/** Verdicts whose reply may go out — the follow-up one included (spec §4.3). */\nexport function isSendableVerdict(verdict: EvaluationVerdict | null): boolean {\n return verdict === 'send' || verdict === 'send_and_escalate';\n}\n\n/** True when the reply is sendable but owes the customer a human follow-up. */\nexport function requiresFollowup(verdict: EvaluationVerdict | null): boolean {\n return verdict === 'send_and_escalate';\n}\n","/**\n * `origin` — which pass of the pipeline produced a `triage-decision` /\n * `generated-response` row (spec-gorgias-followup-webhook-v1 §7.2).\n *\n * `'triage'` is the cron's first pass over a ticket; `'followup'` is a reply\n * drafted for a SUBSEQUENT customer message, opened by the Gorgias webhook.\n * The distinction is load-bearing, not decorative: §7.3 picks WHICH\n * auto-reply flag of the category governs the send from it.\n *\n * Stored as TEXT with a `'triage'` default rather than a SELECT (§7.2), so\n * the vocabulary lives here, in code, and every pre-existing row reads as a\n * first pass with no data migration. `toDecisionOrigin` is the boundary that\n * makes that safe: JSONB the platform hands back can carry anything, and a\n * value outside the vocabulary must degrade to `'triage'` — the pass that\n * grants the FEWER rights — never to `'followup'`.\n */\nexport const DECISION_ORIGINS = ['triage', 'followup'] as const;\n\nexport type DecisionOrigin = (typeof DECISION_ORIGINS)[number];\n\nexport const DEFAULT_DECISION_ORIGIN: DecisionOrigin = 'triage';\n\n/** The `description` both record definitions carry — one sentence, one place. */\nexport const ORIGIN_DESCRIPTION =\n \"Which pass wrote this row: 'triage' (the cron's first pass) or 'followup' (a reply to a subsequent customer message, spec-gorgias-followup-webhook-v1 §7.2).\";\n\nexport function isDecisionOrigin(value: unknown): value is DecisionOrigin {\n return typeof value === 'string' && (DECISION_ORIGINS as readonly string[]).includes(value);\n}\n\n/** Reads an untrusted stored value, falling back to the least-privileged origin. */\nexport function toDecisionOrigin(value: unknown): DecisionOrigin {\n return isDecisionOrigin(value) ? value : DEFAULT_DECISION_ORIGIN;\n}\n","// Spec: architecture_agent_graphe.md §6.1 (legacy `agent/state.ts`); ported\n// per spec-migration-gorgias-backoffice-v1.md §3.1, §3.3.\n//\n// The graph's state and the contract every node conforms to. `NodeDeps` is\n// deliberately narrow (§1's invariant): a node reaches the outside world\n// ONLY through these fields — no network/DB import inside a node — which is\n// what keeps every node testable against the in-memory fakes in\n// `../testing/fakes`.\nimport type {\n AgentProfile,\n Classification,\n Conversation,\n ConversationRef,\n Draft,\n ProposedAction,\n Verdict,\n} from '../domain';\nimport type { Budget } from './budget';\nimport type {\n ClockPort,\n ConversationPort,\n LlmPort,\n PromptPort,\n ReplyPort,\n StatePort,\n ToolContext,\n} from './ports';\n\n/**\n * A runtime list, not just a union, because `outcome` is PERSISTED on\n * `generated-response` (21/09/2026) and therefore crosses two boundaries a\n * bare type cannot guard: the record's `SELECT` options, and the untrusted\n * JSONB a row written by another kit version reaches the UI as. Same shape\n * and same reason as `status/machine.ts`'s `GENERATED_RESPONSE_STATUSES`.\n */\nexport const OUTCOMES = [\n 'sent', // reply posted to the customer\n 'ready', // servable to the extension, NO tag (nominal path)\n 'needs_human', // unsendable verdict → ready + needs-review tag\n 'guardrail_hold', // a guardrail fired → ready + escalation tag\n 'awaiting_approval', // an action awaits human sign-off (P3)\n 'escalated', // escalated upstream, no generation happened\n 'triaged_only', // tenant/ticket has no draft step to run\n 'no_reply_needed', // the end-of-conversation step judged the thread finished — set on response rows, never returned by runTicket\n 'failed',\n] as const;\n\nexport type Outcome = (typeof OUTCOMES)[number] | null;\n\n/** `outcome` reaches the UI as untrusted JSONB — parse at that boundary. */\nexport function isOutcome(value: unknown): value is NonNullable<Outcome> {\n return typeof value === 'string' && (OUTCOMES as readonly string[]).includes(value);\n}\n\n/** Why a run that could otherwise have sent did not. `null` when the question never arose. */\nexport type IneligibleReason = 'no_publication_path' | null;\n\nexport interface TicketRunState {\n conversation: Conversation | null;\n classification: Classification | null;\n escalated: boolean;\n draft: Draft | null;\n verdict: Verdict | null;\n reviseCount: 0 | 1;\n guardrailHits: string[];\n /**\n * Why auto-send was inapplicable, when the run knew a FACT the stored\n * settings cannot express (28/09/2026). Today's only value: nothing could\n * have published a reply on this conversation — Gorgias did not declare\n * the channel answerable, or an email-mode contact had no address. The\n * ticket timeline reads it rather than re-deriving it, because nothing it\n * can see says what a customer's addresses were six weeks ago.\n */\n ineligibleReason: IneligibleReason;\n proposedActions: ProposedAction[];\n outcome: Outcome;\n}\n\nexport function initialState(): TicketRunState {\n return {\n conversation: null,\n classification: null,\n escalated: false,\n draft: null,\n verdict: null,\n reviseCount: 0,\n guardrailHits: [],\n ineligibleReason: null,\n proposedActions: [],\n outcome: null,\n };\n}\n\n/**\n * The category-level auto-reply policy for this ticket — resolved by the\n * caller from the `category` record, which a node may not touch (§1).\n */\nexport interface CategoryPolicy {\n autoReplyEnabled: boolean;\n /**\n * Per-category override of the auto-send confidence threshold. Carried\n * here because the caller resolves it, but deliberately UNUSED by\n * `isSendable`/`isAutoSendEligible` (`verdict/policy.ts`, T16) — the\n * legacy's assumed simplification drops the second confidence check this\n * used to feed.\n */\n minConfidence: number | null;\n}\n\n/**\n * One entry of the profile's Category referential (§3.7's `{{categories}}`\n * substitution) — the taxonomy `triage` shows the model so it classifies\n * against the tenant's real Gorgias categories instead of inventing a tag.\n * Rendered by the caller and handed down, like `CategoryPolicy` above: a\n * node may not reach the referential itself (§1).\n */\nexport interface CategoryReferentialEntry {\n /** Human label shown alongside `tag` — the classifier's output display name. */\n name?: string;\n /** The real Gorgias tag. */\n tag: string;\n desc: string;\n examples?: string;\n}\n\nexport interface NodeDeps {\n ref: ConversationRef;\n profile: AgentProfile;\n ports: {\n conversation: ConversationPort;\n reply: ReplyPort;\n llm: LlmPort;\n prompt: PromptPort;\n state: StatePort;\n clock: ClockPort;\n /**\n * The judge's own gateway. `evaluate` may run on a different provider\n * than the writer, which means a different API key and a different\n * Langfuse prompt link — sharing `llm` silently fails every verdict as\n * soon as the two providers differ. Absent means \"same gateway as the\n * writer\", today's single-provider install.\n */\n evaluator?: LlmPort;\n };\n toolContext: ToolContext;\n /**\n * Bounds THIS run's tool calls/time and measures its cost (I15). Nothing\n * on `TicketRunState` mirrors `budget.ledger()` — the ledger it accumulates\n * IS the run's cost record; a caller who needs it after the run reads\n * `budget.ledger()`/`budget.total()` directly rather than through a second,\n * separately-populated copy on the state.\n */\n budget: Budget;\n category: CategoryPolicy;\n categories: CategoryReferentialEntry[];\n log: (msg: string) => void;\n /**\n * Claim → post → commit persistence seam (I9). A node may never touch a\n * database directly (§1), so the state machine that makes send-once safe\n * under concurrency lives behind this pair, gated by an explicit `mode`\n * rather than by whether the fields happen to be set.\n *\n * `{mode: 'none'}` is \"no persistence layer\" — `act` treats the run as its\n * own uncontested claim, as every node test does today. It is a REQUIRED\n * field, not an optional one left unset (post-T14 review, C7): the legacy\n * shape (`claim?`/`commit?` as bare optional `NodeDeps` fields) let an\n * assembly forget to wire persistence and silently degrade to\n * send-once-safety-off, with no compile error — and the same omission\n * would have been invisible to T21's dry-run assertion (\"not a single\n * write port was called\"), since fields outside `ports` are nothing a\n * recording wrapper walking `ports` would ever see. Requiring the choice\n * turns that silent omission into a decision every assembly site states\n * out loud, without forcing a node test that does not care about\n * persistence to implement one (`{mode: 'none'}` is a one-line literal,\n * not a persistence layer).\n *\n * Everything the run produced travels WITH the claim so the claiming write\n * can persist it in the same atomic operation: a crash between claim and\n * commit then leaves a complete record for the sweep to escalate, never a\n * lost generation.\n */\n send:\n | { mode: 'none' }\n | {\n mode: 'claimed';\n claim: (run: { draft: Draft; verdict: Verdict | null }) => Promise<boolean>;\n commit: (messageId: string) => Promise<void>;\n };\n /**\n * When this run was queued. `act` compares an agent reply against it to\n * catch one that landed before generation started (I8's window gap), which\n * the divergence count cannot see. Null means \"unknown\" and makes `act`\n * treat any agent reply as disqualifying.\n */\n queuedAt?: Date | null;\n /**\n * Step observer for the admin's graph debugger. Absent in production — the\n * caller pays nothing for it (`run-ticket.ts` calls the node directly when\n * there is no observer). Never a control point: it observes, it cannot\n * change the sequence, which is what keeps the debugged run the SAME run\n * as production.\n */\n trace?: (step: NodeStep) => void;\n}\n\n/** The nodes `runTicket` can call, in the order the diagram draws them. */\nexport const NODE_NAMES = [\n 'fetchContext', 'triage', 'escalate', 'draft',\n 'evaluate', 'revise', 'guardrails', 'authorize', 'act',\n] as const;\n\nexport type NodeName = (typeof NODE_NAMES)[number];\n\n/**\n * One executed node. A node the graph decided NOT to call emits nothing —\n * \"skipped\" is derived by the reader from `NODE_NAMES` minus what it saw,\n * so the graph never has to announce its own omissions.\n *\n * `evaluate` legitimately appears twice: once on the first draft, once after\n * `revise` (the revision loop).\n */\nexport interface NodeStep {\n node: NodeName;\n /** The state patch the node produced — empty when it threw. */\n patch: Partial<TicketRunState>;\n durationMs: number;\n /** Present only when the node threw; the throw itself still propagates. */\n error?: string;\n}\n\n/**\n * The contract every node conforms to (§6.1): a pure transition from state\n * to state-patch over injected ports, never a direct side effect on a\n * database or the network.\n */\nexport type Node = (state: Readonly<TicketRunState>, deps: NodeDeps) => Promise<Partial<TicketRunState>>;\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// Port interfaces for the graph engine. A node reaches the outside world\n// ONLY through these — no network/DB import inside a node (§1's invariant).\n//\n// Mapping from the legacy `agent/state.ts` `NodeDeps.ports` / `ports/*.ts`\n// (this comment is the reference T17/T21 should read instead of re-deriving\n// it from the legacy source):\n//\n// legacy → kit port → why\n// ---------------------------------------------------------------------\n// ports.source (ConversationSource) → ConversationPort same surface,\n// renamed only.\n// ports.reply (ReplyChannel) → ReplyPort same surface,\n// renamed only.\n// ports.llm (LlmGateway) → LlmPort same surface,\n// renamed only;\n// `ports.evaluator?`\n// stays a second,\n// optional LlmPort.\n// ports.sink (ClassificationSink) → StatePort merged: §3.3 says\n// ports.meta (ConversationMeta) (record/rename/flag) this port is\n// implemented \"sur\n// records\" in\n// adapters/ctx-\n// ports.ts (T21).\n// Grouping the\n// decision write\n// (`record`) with\n// the audit-trail\n// writes\n// (`rename`/`flag`)\n// keeps every write\n// that MATERIALISES\n// A DECISION behind\n// one seam, distinct\n// from ReplyPort's\n// customer-facing\n// publication.\n// Method names are\n// unchanged.\n//\n// Naming/scope decision (post-T14 review, tracked as C7): §3.3's own table\n// assigns the name \"StatePort\" to exactly this port, but its actual traffic\n// — `record`/`rename`/`flag` — is Gorgias tag and rename calls, i.e. S1\n// integration traffic, not \"state\" in any sense distinct from ReplyPort's\n// own channel writes. That is a mismatch in the SPEC's naming, inherited\n// here rather than introduced. Decision taken: KEEP the name `StatePort`\n// (renaming now would ripple through every task from T15 to T24 before a\n// single real adapter exists, for a purely cosmetic gain) and instead close\n// the structural gap this mismatch was hiding — see `NodeDeps.send` below,\n// which replaces the old bare optional `claim`/`commit` fields precisely so\n// a missing persistence choice can no longer be a silent omission.\n//\n// NodeDeps.clock (bare field) → ClockPort promoted from a\n// bare field to a\n// full port so all\n// six live under\n// `NodeDeps.ports`,\n// none of them\n// special.\n// (none — new) → PromptPort the legacy read\n// `AgentProfile.\n// prompts.<node>.\n// fallback` directly,\n// pre-resolved by\n// the worker before\n// a node ever ran.\n// This port lets\n// T19 own the\n// 3-level fallback\n// (§3.7) without any\n// node changing.\n//\n// `ToolContext` (the read tools, §6.2) and `Budget` (§6.3's tool-call/cost\n// bounding, `graph/budget.ts`) are NOT among the spec's six named ports —\n// they stay direct `NodeDeps` fields, ported unchanged.\n//\n// `claim`/`commit` (the claim→post→commit send seam, I9) stay OUT of\n// StatePort — the spec's six ports do not mention them, and folding them in\n// would force every node test to provide a persistence layer even when it\n// does not care about one. They are not, however, the old bare *optional*\n// `NodeDeps` fields either: legacy's \"absent means uncontested claim\" default\n// was a silent one — an assembly that forgot to wire `claim` degraded to\n// send-once-safety-off with no compile error, and the same omission would\n// have been invisible to T21's planned dry-run assertion (\"not a single\n// write port was called\"), since a bare optional field outside `ports` is\n// nothing a recording wrapper walking `ports` would ever see.\n//\n// `NodeDeps.send` (see `graph/state.ts`) replaces them: a REQUIRED,\n// discriminated field — `{mode:'none'}` or `{mode:'claimed', claim, commit}`\n// — so every assembly site states its choice explicitly. A node test that\n// does not care about persistence still writes only `{mode:'none'}`, not a\n// persistence layer, so the original goal (no test forced to implement one)\n// holds; what changes is that \"none\" is now a decision on record instead of\n// an absence nobody chose.\n\nimport type { Classification, Conversation, ConversationRef, ReasoningEffort, Usage } from '../domain';\nimport type { PromptRef } from '../domain/profile';\n\n// --- ConversationPort ------------------------------------------------------\n\nexport interface SourceDescriptor {\n viewOrTag: string;\n}\n\nexport interface ConversationPort {\n /**\n * The adapter receives the source descriptor, never the profile: it stays\n * profile-agnostic. Resolving profile → source belongs to the caller.\n */\n listPending(source: SourceDescriptor, limit: number): Promise<ConversationRef[]>;\n read(ref: ConversationRef): Promise<Conversation>;\n}\n\n// --- ReplyPort ---------------------------------------------------------------\n\n/**\n * What `ReplyPort.post` needs to publish a reply — modelled on the legacy\n * `sendReply` for `mode: 'email'`.\n *\n * `mode: 'whatsapp_note'` (whatsapp spec §4.1) is a second publication shape\n * on the SAME adapter, not a new channel: the reply becomes a chevron-note\n * on Gorgias, raw text, no email envelope.\n *\n * A discriminated union, not one interface with optional email fields: the\n * envelope (`bodyHtml`/`subject`/`fromAddress`/`receiverEmail`) is REQUIRED\n * whenever `mode: 'email'`, so a caller that forgets one fails to compile\n * instead of silently posting an empty address.\n */\nexport type OutboundReply =\n | {\n mode: 'email';\n bodyText: string;\n bodyHtml: string;\n subject: string | null;\n /** Outbound address shown to the customer (a channel email/sender integration). */\n fromAddress: string;\n receiverName: string | null;\n receiverEmail: string;\n /** Forwarded to channels that support it, as defence in depth only — see guarantee below. */\n idempotencyKey: string;\n }\n | {\n mode: 'whatsapp_note';\n bodyText: string;\n /** Forwarded to channels that support it, as defence in depth only — see guarantee below. */\n idempotencyKey: string;\n }\n | {\n /** A reply on the ticket's OWN channel — Instagram DM, Facebook Messenger. */\n mode: 'channel';\n channel: string;\n bodyText: string;\n bodyHtml: string;\n /** The customer's address on that channel, not an email (`domain/publication.ts`). */\n toAddress: string;\n /** The brand's own address on that channel. */\n fromAddress: string;\n receiverName: string | null;\n /** Forwarded to channels that support it, as defence in depth only — see guarantee below. */\n idempotencyKey: string;\n };\n\nexport interface ReplyPort {\n /**\n * Publishes the reply. Guarantee: AT-MOST-ONCE, obtained by the caller's\n * claim → post → commit state machine (I9), NOT by channel idempotence —\n * Gorgias has no idempotency key. On an unknown outcome (timeout/5xx), the\n * caller NEVER calls post again; the job stays `sending` for the sweep.\n * `idempotencyKey` is forwarded to channels that support it, as defence in\n * depth only.\n */\n post(ref: ConversationRef, reply: OutboundReply): Promise<{ messageId: string }>;\n}\n\n// --- LlmPort -------------------------------------------------------------\n\n/**\n * Generic JSON value shape. `responseSchema`/`ToolSpec.inputSchema` need to\n * describe arbitrary structured-output/tool schemas without hand-modelling\n * the full JSON Schema grammar — a recursive JSON-value type is precise\n * enough for that and keeps this file free of `any`.\n */\nexport type JsonSchema = string | number | boolean | null | JsonSchema[] | { [key: string]: JsonSchema };\n\nexport type ChatMessage =\n | { role: 'system'; content: string }\n | { role: 'user'; content: string }\n | { role: 'assistant'; content: string | null; toolCalls?: ToolCallRequest[] }\n /** Tool result fed back into the conversation for the next completion (§6.2 tool loop). */\n | { role: 'tool'; toolCallId: string; content: string };\n\n/**\n * Tool exposed to the model for one completion — no handler, unlike a\n * registry `ToolDefinition`: execution is the caller's job, gated by the\n * node's tool policy (§6.2).\n */\nexport interface ToolSpec {\n name: string;\n description: string;\n inputSchema: JsonSchema;\n}\n\nexport interface ToolCallRequest {\n id: string;\n name: string;\n arguments: Record<string, unknown>;\n}\n\nexport interface CompletionRequest {\n /** Langfuse generation name (I17). */\n label: string;\n model: string;\n reasoning: ReasoningEffort;\n messages: ChatMessage[];\n tools?: ToolSpec[];\n /** Structured output strict schema. */\n responseSchema?: JsonSchema;\n /** Run deadline (I14). */\n signal?: AbortSignal;\n /**\n * Links this generation to the prompt version that produced `messages`\n * (S2's `ctx.api.llm.complete` v2 already accepts this field verbatim), so\n * Langfuse's generation↔prompt-version attribution — the link S7's\n * experiments and reviews are built on — survives prompt resolution having\n * moved inside the node (T19 resolves `PromptPort` itself now, not the\n * worker). Absent means no linked prompt (e.g. the node built its messages\n * without going through `PromptPort`).\n *\n * `resolve: false` is set by every caller in this package (D-LF follow-up,\n * link-only mode): the kit always resolves its own prompt via `PromptPort`\n * before building `messages`, so it never wants the platform to resolve\n * `promptRef` again — only to link the trace to the prompt that already\n * produced the system message. See `app-integrations.controller.ts`'s\n * `llmComplete` JSDoc for the full contract; `resolve: false` skips the\n * `manifest.prompts[]` declaration gate that would otherwise 403 every one\n * of these calls under D-LF (`manifest.prompts[]` stays permanently empty).\n */\n promptRef?: { name: string; version?: number; label?: string; resolve?: boolean };\n /**\n * The `vars` the node handed `PromptPort.resolve` for this prompt,\n * forwarded to `ctx.api.llm.complete` so the platform records them on the\n * generation (spec MCP §5.4.3: `explain_ticket` shows them). Absent when\n * the prompt was resolved without variables.\n */\n promptVariables?: Record<string, string>;\n /** Forwarded verbatim to `ctx.api.llm.complete` v2's `trace` (S2). */\n trace?: { sessionId?: string; tags?: string[]; metadata?: Record<string, string> };\n}\n\nexport interface CompletionResult {\n text: string | null;\n toolCalls: ToolCallRequest[];\n usage: Usage;\n /**\n * Langfuse ids of THIS completion (I17), absent when tracing is off or the\n * gateway is a fake. Carried per-result rather than read back from the\n * gateway afterwards: a run makes several calls, and \"the last trace\" is\n * whichever one happened to finish last.\n */\n traceId?: string;\n observationId?: string;\n}\n\nexport interface LlmPort {\n /**\n * One completion call. `reasoning` is translated to the provider's native\n * parameter; an invalid (model, effort) pair is refused AT PROFILE LOAD\n * TIME, never silently ignored.\n */\n complete(req: CompletionRequest): Promise<CompletionResult>;\n}\n\n// --- PromptPort ------------------------------------------------------------\n\nexport interface ResolvedPrompt {\n /** Prompt name actually served — normally `ref.name`, carried here too so a caller never has to hold onto the ref just to build `CompletionRequest.promptRef`. */\n name: string;\n text: string;\n /**\n * The Langfuse prompt version actually served. The in-code fallback (§3.7\n * level 3) reports `0`, per spec — never `null` (C6): this value flows\n * into T19's `prompt-cache` mirror and onto a UI page, and a fallback\n * silently reporting a different \"no version\" shape than the spec's `0`\n * would make those two surfaces disagree.\n */\n version: number;\n /**\n * Model config carried by the resolved Langfuse prompt, when it declares\n * one. Informational only: no graph node or kit function calls the LLM\n * with it — the model stored in the OS (`AgentProfile.nodes.<node>.model`,\n * `agent.modelId`) always wins.\n */\n config?: { model: string; temperature?: number } | null;\n}\n\n/**\n * Resolves rendered prompt text for one node's prompt reference (§3.7's\n * three-level fallback: Langfuse → prompt-cache mirror → in-code default). A\n * node calls this instead of reading `AgentProfile.prompts` directly (the\n * legacy shortcut), which is what lets T19 change the resolution strategy\n * without a single node changing.\n *\n * `vars` are substituted into the resolved text ONCE, at this boundary\n * (§3.7: `{{categories}}`, `{{channel_prompt}}`, `{{agent_name}}`) — a node\n * never substitutes for itself, which is what keeps a raw\n * `@@@langfusePrompt:…@@@` composition tag from ever being able to reach the\n * LLM (T19's stated guarantee): the one place substitution happens is also\n * the one place the composition tag gets resolved.\n *\n * Contract (C5, amended): `resolve` rejects with `MissingPromptError` — and\n * ONLY with that — when every level of the ladder comes up empty. It used to\n * never reject at all, returning empty text at version 0; that made a step\n * with no usable prompt indistinguishable from a step whose prompt happened\n * to say nothing, and let a run reach the model with an empty system\n * message. A step with no prompt is a broken install, not a degraded one.\n *\n * The reason the old contract existed still stands, and is now the caller's\n * duty instead of this port's: resolution happens INSIDE the node, so a\n * rejection would otherwise be absorbed by that node's own error policy —\n * `escalate`'s fail-open would read it as \"nothing to escalate\",\n * `evaluate`'s fail-safe as a hold, both silently. Every node therefore\n * resolves OUTSIDE its own try/catch, so a missing prompt fails the run\n * instead of quietly changing its outcome.\n *\n * Levels 1-2 failing on their own still degrade rather than reject: a\n * Langfuse outage served from the `prompt-cache` mirror, or from the ref's\n * in-code fallback, is a real prompt and a legitimate run.\n */\nexport interface PromptPort {\n resolve(ref: PromptRef, vars?: Record<string, string>): Promise<ResolvedPrompt>;\n}\n\n/**\n * Thrown by `PromptPort.resolve` when no level of the ladder yields any\n * prompt text: the name resolves to nothing in Langfuse, the `prompt-cache`\n * mirror holds nothing for it, and the ref carries no in-code fallback.\n *\n * Carries the ref that failed so the run's error names the step's prompt\n * rather than reporting an empty system message that an operator would have\n * to go looking for.\n */\nexport class MissingPromptError extends Error {\n constructor(\n readonly promptName: string,\n readonly label: string,\n ) {\n super(`No prompt content resolved for \"${promptName}\" (label \"${label}\") — Langfuse, the prompt-cache mirror and the in-code fallback are all empty.`);\n this.name = 'MissingPromptError';\n }\n}\n\n// --- StatePort ---------------------------------------------------------------\n\n/**\n * Tag names used to materialise pipeline decisions on the channel (I20).\n * \"Tag\" does not exist in the domain — it is the channel's rendering of a\n * `Classification` or outcome, and these are the exact strings a profile's\n * `audit` config resolves per tenant.\n */\nexport interface AuditTags {\n unknownTag: string;\n handledTag: string;\n escalationTag: string;\n sentTag: string;\n needsHumanTag: string;\n followupTag: string;\n /**\n * The app's ownership mark, applied to every ticket its triage sees rather\n * than to an outcome — empty when unconfigured, which stamps nothing.\n */\n appScopeTag: string;\n}\n\nexport interface StatePort {\n /** Materialises the triage decision (ex `ClassificationSink.record`). */\n record(ref: ConversationRef, classification: Classification, audit: AuditTags): Promise<void>;\n /** ex `ConversationMeta.rename`. */\n rename(ref: ConversationRef, subject: string): Promise<void>;\n /** Audit tag application (I20) — not a triage classification. ex `ConversationMeta.flag`. */\n flag(ref: ConversationRef, tag: string): Promise<void>;\n}\n\n// --- ClockPort ---------------------------------------------------------------\n\nexport interface ClockPort {\n now(): Date;\n}\n\n// --- PortName --------------------------------------------------------------\n\n/**\n * The spec's six named ports (§3.3), as a closed union. `testing/fakes`'s\n * `PORT_SURFACES` types its map off THIS, rather than the other way around\n * (C4): a hand-written literal typing its own input is invisible to the\n * compiler when it drifts — `PromptPort` was once silently absent from\n * `PORT_SURFACES` and every contract test still passed. Typing the map\n * `Record<PortName, …>` makes a missing port a compile error, and\n * `satisfies readonly (keyof ThatPort)[]` on each entry makes a renamed\n * method one too.\n */\nexport type PortName = 'ConversationPort' | 'ReplyPort' | 'LlmPort' | 'PromptPort' | 'StatePort' | 'ClockPort';\n\n// --- ToolContext (read tools, §6.2 — not one of the six named ports) -------\n\n/**\n * What the read tools of §6.2 look things up in. A real adapter reads\n * Shopify/order data off the ticket payload and platform records; the node\n * itself only ever sees this interface, never a network call or a DB import\n * (§1's invariant).\n *\n * `searchKnowledge` is a seam on purpose — the choice of knowledge base and\n * its indexing is a separate decision; a node only has to consume it behind\n * this method.\n */\nexport interface ToolContext {\n getOrder(orderId: string): Promise<OrderSummary | null>;\n getTracking(orderId: string): Promise<TrackingSummary | null>;\n searchKnowledge(query: string): Promise<KnowledgeHit[]>;\n findSimilarTickets(query: string, limit: number): Promise<SimilarTicket[]>;\n}\n\n/** What a resolved tool may be used for (§6.2). */\nexport type ToolPolicy = 'read' | 'requires_approval' | 'forbidden';\n\nexport interface CatalogueTool {\n name: string;\n policy: ToolPolicy;\n}\n\n/**\n * `name → policy` map for the four read tools above (§6.2) — ported\n * verbatim from legacy `agent/profile/catalogue.ts`'s `AGENT_TOOLS` (T15\n * review E2). `AgentProfile.tools` (`domain/profile.ts`) is a bare\n * `string[]` \"resolved against the registry\"; this is that registry.\n *\n * Ported now, not deferred to T17, because T17's `draft` node needs it for\n * two things nothing else in this kit provides: building the `ToolSpec[]`\n * to hand the model, and gating actual execution by policy — a node cannot\n * do either from `ToolContext` alone, which only says WHAT the four methods\n * return, not whether a given profile may call them.\n *\n * `gorgias.rename_conversation` and the other write tools are absent ON\n * PURPOSE: §6.2 states the write tools are never exposed to the model — the\n * rename stays a code step of the worker. Nothing here grows into a write\n * tool by editing a policy value; a `forbidden`/`requires_approval` tool\n * would need its own catalogue entry, added deliberately.\n *\n * `supportsReasoning` (the model-family check next to `AGENT_TOOLS` in the\n * legacy catalogue) is deliberately NOT ported alongside it — the API\n * package already owns it, a provider concern outside this kit.\n */\nexport const AGENT_TOOLS: Record<string, CatalogueTool> = {\n get_order: { name: 'get_order', policy: 'read' },\n get_tracking: { name: 'get_tracking', policy: 'read' },\n search_knowledge: { name: 'search_knowledge', policy: 'read' },\n find_similar_tickets: { name: 'find_similar_tickets', policy: 'read' },\n};\n\nexport interface OrderSummary {\n id: string;\n status: string;\n /** ISO date string — omitted when the source data doesn't carry one. */\n placedAt?: string;\n}\n\nexport interface TrackingSummary {\n orderId: string;\n carrier: string;\n trackingNumber: string;\n status: string;\n url: string | null;\n}\n\nexport interface KnowledgeHit {\n id: string;\n title: string;\n content: string;\n url?: string | null;\n}\n\nexport interface SimilarTicket {\n id: string;\n excerpt: string;\n category: string;\n resolution?: string | null;\n}\n","// Frozen catalogue data (§3.9, I7): the exhaustive list of configurable\n// guardrail ids, and the two phrase lists a profile can never override.\n//\n// Ported from legacy `src/services/autoReplyGuard.ts` (`CANDIDATE_MIN_LENGTH`,\n// `UNCERTAINTY_MARKERS`), `src/agent/nodes/guardrails.ts` (`STOP_PHRASES`) and\n// `src/agent/profile/catalogue.ts` (`AGENT_GUARDRAILS`).\n\n/** `short_answer` fires under this length (candidate answer, trimmed). */\nexport const CANDIDATE_MIN_LENGTH = 20;\n\n/** Gorgias clock (created_datetime) vs Mongo clock (job.createdAt) skew margin. */\nexport const CLOCK_SKEW_MARGIN_MS = 60_000;\n\n/**\n * Uncertainty phrases that should trigger a hold. A code constant,\n * deliberately NOT configurable per profile — the sole exception to \"params\n * are per tenant\" (§6.5 legacy / §3.9).\n *\n * Genuinely frozen (T15 review C), not just documented as such: `as const` +\n * `Object.freeze` so a consumer's stray `.push(...)` is both a compile error\n * (readonly array — no `push` method) and, should it slip past the compiler\n * (`as any`), a runtime `TypeError` instead of a silent per-process mutation\n * of a guardrail meant to be identical for every tenant.\n */\nexport const UNCERTAINTY_MARKERS: readonly string[] = Object.freeze([\n 'je ne suis pas sur', // normalised form of \"je ne suis pas sûr\"\n 'je ne peux pas',\n 'contactez le service',\n \"malheureusement je n'ai pas\",\n] as const);\n\n/**\n * STOP opt-out phrases (whatsapp spec §5.1) — frozen in code, not\n * configurable per profile (\"liste exacte à figer en implémentation, courte\n * et non configurable dans un premier temps\"). Each entry is the French\n * SMS/WhatsApp regulatory opt-out convention (a lone \"STOP\" keyword,\n * optionally suffixed).\n *\n * Typed `ReadonlySet<string>` (T15 review C): only `.has` is ever called\n * against it, and this type has no `add`/`delete` at all, so a consumer\n * calling either is a compile error. `Object.freeze` would not add anything\n * here — a `Set`'s `add`/`delete` are prototype methods a frozen instance\n * still runs — so the type is the real guard, same as it is for every other\n * live-object port in this package.\n */\nexport const STOP_PHRASES: ReadonlySet<string> = new Set([\n 'stop', // the bare, universal opt-out keyword\n 'stop sms', // the regulated French premium-SMS opt-out (\"STOP SMS\")\n 'stop pub', // its marketing-specific variant (\"STOP PUB\")\n 'stop tout', // \"stop everything\" — a customer opting out of all contact\n]);\n\n/**\n * Exhaustive guardrail identifiers (§3.9, I7) — verified one by one against\n * what `runGuardrails`/`channelPreGates`/`verifyReply` actually push into\n * `guardrailHits`, so this list cannot drift from the runtime behaviour it\n * names:\n * - `whatsapp`, `whatsapp_stop`, `not_customer_turn`, `judgeme`,\n * `noreply_sender` — channel/sender pre-gates.\n * - `triage_not_high`, `escalated` — upstream pre-gates.\n * - `blocklist` — the FAMILY name. The runtime hit is `blocklist:<term>`\n * (one per matched term, see `guardrailBucket`); a profile enables/\n * disables the rule as a whole, never a single term.\n * - `attachment`, `short_answer`, `uncertainty_marker` — content rules.\n * - `evaluation_missing` — verdict gate.\n *\n * Two things are intentionally NOT here (§3.9 draws the line explicitly):\n * - `ticket_closed`, `agent_replied`, `diverged`, `run_deadline`,\n * `customer_email_missing` — pure code inside `act`'s claim→post→commit\n * anti-collision check (T17), never profile-configurable.\n * - `UNCERTAINTY_MARKERS`/`STOP_PHRASES` themselves stay code constants —\n * the identifier is toggleable per profile, the phrase list it matches\n * against is not.\n */\nexport const AGENT_GUARDRAILS = [\n 'whatsapp',\n 'whatsapp_stop',\n 'not_customer_turn',\n 'judgeme',\n 'noreply_sender',\n 'triage_not_high',\n 'escalated',\n 'blocklist',\n 'attachment',\n 'short_answer',\n 'uncertainty_marker',\n 'evaluation_missing',\n] as const;\n\nexport type GuardrailId = (typeof AGENT_GUARDRAILS)[number];\n\n/**\n * The OTHER half of the catalogue: `act`'s send-time anti-collision checks\n * (I8), which land in the same `guardrailHits` as the list above but are\n * NEVER profile-configurable — hence a separate constant rather than more\n * entries in `AGENT_GUARDRAILS`, whose whole contract is \"what a tenant can\n * toggle\" (see that list's own doc, which draws this line explicitly).\n *\n * Declared here anyway, and not left as bare literals in `act.ts`, because\n * two readers need the names: `ui/tickets/guardrail-labels.ts` (a hit with\n * no label renders as a raw identifier to an operator) and\n * `ui/test/verdict-summary.ts` (which splits collision hits from content\n * hits). Both used to carry their own copy; a sixth check added to `act`\n * silently missed them.\n *\n * Order matches `act`'s own evaluation order, which I8 freezes.\n */\nexport const COLLISION_GUARDRAILS = [\n 'customer_email_missing',\n 'ticket_closed',\n 'agent_replied',\n 'diverged',\n 'run_deadline',\n] as const;\n\nexport type CollisionGuardrailId = (typeof COLLISION_GUARDRAILS)[number];\n","// Ported unchanged from legacy `src/utils/text.ts`. Shared by every rule in\n// this module (blocklist, uncertainty markers, the whatsapp pre-gates) so\n// they all treat accents/case the same way.\n//\n// Spec: spec-migration-gorgias-backoffice-v1.md §3.9.\n\n/** Accent/case-insensitive normalisation — strips diacritics then lowercases. */\nexport function normalise(s: string): string {\n return s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();\n}\n","// Ported from legacy `src/agent/nodes/guardrails.ts` (`stopOptOut`,\n// `channelPreGates`) and legacy `src/agent/nodes/shared.ts`\n// (`isJudgemeConversation`, `isAutomatedSenderEmail`) — the PURE,\n// `Conversation`-based part only. The legacy `guardrails.ts` file also\n// exports an async `guardrails` graph `Node` that combines these with\n// `profile`/`state` (whatsapp mode, active-list filtering, the content\n// rules). That combination is graph wiring, out of scope here — it is T17's\n// job, built on top of the pure functions this module exports.\n//\n// `isJudgemeConversation`/`isAutomatedSenderEmail` are the `Conversation`\n// twins of `raw-ticket.ts`'s `isJudgemeTicket`/`isAutomatedSenderTicket` (a\n// node may never see the raw Gorgias payload those read, §9) — the two\n// modules share one implementation per rule where the legacy variants agree\n// (`isJudgemeTicket` wraps this file's `isJudgemeConversation`); see\n// `isAutomatedSenderEmail`'s own doc for the one rule where they don't.\n//\n// Spec: spec-migration-gorgias-backoffice-v1.md §3.9; whatsapp spec §5.1/§5.3.\nimport type { Conversation } from '../domain';\nimport { STOP_PHRASES } from './constants';\nimport { normalise } from './text';\n\n/**\n * Whole-message match, not substring: a message merely CONTAINING \"stop\"\n * (e.g. \"le stop and go de ma voiture\") must not opt the customer out — only\n * a message that reduces to one of the frozen phrases once every leading and\n * trailing non-letter character (spaces, punctuation, quotes, guillemets —\n * \"Stop !\", \"STOP,\", \"« STOP »\") is stripped and internal whitespace is\n * collapsed (\"STOP SMS\"). The strip runs BEFORE any trim: trimming first\n * would leave a French typographic space (\"Stop !\" → \"stop \" ) sitting right\n * next to the punctuation it precedes, and miss it.\n */\nfunction isStopMessage(message: string): boolean {\n const cleaned = normalise(message)\n .replace(/^[^\\p{L}\\d]+|[^\\p{L}\\d]+$/gu, '')\n .replace(/\\s+/g, ' ');\n return STOP_PHRASES.has(cleaned);\n}\n\n/**\n * A turn whose ENTIRE content is `@wopilo/gorgias-client`'s attachment\n * marker — the synthetic line its extraction renders for a message the\n * customer sent as photos alone, so the writer stops asking for files that\n * are already attached. It carries no words of the customer's, so every\n * prerequisite built on \"what the customer SAID\" (the blocklist scan, the\n * Judge.me match, the STOP opt-out, triage) must look past it, exactly as it\n * did when such a message produced no turn at all.\n *\n * Hand-synced with that package's `attachmentMarker` (this one may not\n * import `@wopilo/*` — `dependency-allowlist.spec.ts`), same precedent as\n * `raw-ticket.ts`'s copy of `isInternalNoteChannel`. The client side pins\n * the two together at runtime (`raw-ticket-compat.spec.ts`), and a drift\n * that slipped past it degrades to today's behaviour — the marker read as\n * the customer's message — never to a crash.\n */\nexport const ATTACHMENT_MARKER_ONLY = /^\\[Pièces? jointes? : \\d+ fichiers?\\]$/;\n\n/**\n * Exported (spec-gorgias-followup-webhook-v1 §6): the follow-up webhook's G8\n * asks the same question of the LAST extracted turn — \"is this the customer,\n * and did they actually say something?\" — and must ask it with this exact\n * rule, not a second copy that could drift on the attachment marker.\n */\nexport function isCustomerTurnWithWords(message: { role: string; content: string }): boolean {\n return message.role === 'user' && !ATTACHMENT_MARKER_ONLY.test(message.content.trim());\n}\n\n/**\n * First customer turn in a conversation, or `null` when there is none. The\n * blocklist input, and the `subject`/first-message pair `isJudgemeConversation`\n * matches against.\n *\n * Ported from legacy `agent/nodes/shared.ts`, exported from here rather than\n * from `raw-ticket.ts` (where a differently-shaped `extractFirstCustomerMessage`\n * used to live, over bare `Message[]`): T17's nodes only ever hold a\n * `Conversation`, and this module is already where its sibling\n * `lastCustomerMessage` lives — one entry shape, one home, for both halves\n * of the same prerequisite.\n */\nexport function firstCustomerMessage(conversation: Conversation): string | null {\n return conversation.messages.find(isCustomerTurnWithWords)?.content ?? null;\n}\n\n/**\n * Last customer turn in a conversation, or `null` when there is none — the\n * mirror of `firstCustomerMessage`, walking from the end (a plain backward\n * index loop rather than `[...].reverse().find()`, so a caller that already\n * runs this once per conversation does not copy the whole array to read one\n * element). Exported (T15 review E1): legacy documents this as a shared\n * prerequisite of the whatsapp pre-gates AND of `triage` (T17's first\n * consumer), so declaring it module-private here would force T17 to\n * redeclare it.\n */\nexport function lastCustomerMessage(conversation: Conversation): string | null {\n const { messages } = conversation;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message && isCustomerTurnWithWords(message)) return message.content;\n }\n return null;\n}\n\n/**\n * Whatsapp spec §5.1 alone — deterministic, no LLM: the customer asked to\n * never be contacted again. Matched against the LAST customer message (the\n * opt-out can arrive at any point of a multi-turn thread, not just the\n * opening one).\n *\n * Split out from `channelPreGates` because the graph evaluates it EARLIER\n * than its sibling: a STOP has to outrank every quiet exit (and the\n * end-of-conversation step), which would leave the opt-out no trace\n * (T17/T18's concern).\n */\nexport function stopOptOut(conversation: Conversation): string[] {\n if (conversation.sourceChannel !== 'whatsapp') return [];\n const last = lastCustomerMessage(conversation);\n return last !== null && isStopMessage(last) ? ['whatsapp_stop'] : [];\n}\n\n/**\n * The whatsapp spec §5.1/§5.3 pre-gates, pure over `Conversation` alone (no\n * profile params: unlike `whatsapp`, neither is configurable). Both evaluate\n * only in WhatsApp and both return at most one hit each, in a fixed order\n * (`whatsapp_stop` before `not_customer_turn`).\n */\nexport function channelPreGates(conversation: Conversation): string[] {\n if (conversation.sourceChannel !== 'whatsapp') return [];\n\n const hits: string[] = [...stopOptOut(conversation)];\n\n // §5.3 — \"le dernier mot est-il au client ?\": if the last datable message\n // of the thread is OURS, we would be replying to ourselves. `>=`, not `>`,\n // is deliberate: an agent reply and the last customer message sharing the\n // exact same timestamp (a synchronous system, or second-precision\n // truncation) must still read as \"we already have the last word\" — the\n // guardrail is the belt, not the braces, so it errs toward holding.\n const lastIsOurs =\n conversation.lastAgentReplyAt !== null &&\n conversation.lastMessageAt !== null &&\n conversation.lastAgentReplyAt.getTime() >= conversation.lastMessageAt.getTime();\n if (lastIsOurs) hits.push('not_customer_turn');\n\n return hits;\n}\n\n/**\n * Judge.me review-notification detector — the same two patterns as\n * `isJudgemeTicket` (`raw-ticket.ts`), adapted to take domain data (subject +\n * first customer message) instead of a raw Gorgias ticket, which a node may\n * never read (§9). Ported verbatim from legacy `agent/nodes/shared.ts`.\n */\nexport function isJudgemeConversation(subject: string | null, firstMessage: string | null): boolean {\n if (/a ecrit un avis \\d+ etoile/.test(normalise(subject ?? ''))) return true;\n const first = normalise(firstMessage ?? '');\n return first.includes('judge.me') && /avis \\d+ etoile/.test(first);\n}\n\n/**\n * No-reply sender detector — the same three match forms (exact / `@domain`\n * suffix / `local@` prefix) as `isAutomatedSenderTicket` (`raw-ticket.ts`),\n * adapted to a plain email string instead of a raw ticket. Ported verbatim\n * from legacy `agent/nodes/shared.ts`.\n *\n * NOT a thin wrapper over `isAutomatedSenderTicket`, and vice versa: the two\n * already disagreed in the legacy codebase for a malformed entry like a bare\n * `'@'`. This function picks ONE match form per entry and returns as soon as\n * it does (`if (e.startsWith('@')) return …`) — if that form doesn't match,\n * the entry is done, even though the OTHER forms might. `isAutomatedSenderTicket`\n * instead falls through to try the next form when the current one fails. For\n * entry `'@'` and an email itself starting with `@`, that difference flips\n * the result. Ported as-is rather than silently reconciled — reconciling\n * would have to pick a winner the legacy code never did.\n */\nexport function isAutomatedSenderEmail(email: string | null, senders: string[]): boolean {\n const normalisedEmail = normalise(email ?? '').trim();\n if (!normalisedEmail) return false;\n return senders.some((entry) => {\n const e = normalise(entry).trim();\n if (!e) return false;\n if (e.startsWith('@')) return normalisedEmail.endsWith(e);\n if (e.endsWith('@')) return normalisedEmail.startsWith(e);\n return normalisedEmail === e;\n });\n}\n","// Detectors ported unchanged from legacy `src/services/autoReplyGuard.ts`\n// and `src/tools/gorgias/client.ts` (`isWhatsappChevronNote`).\n//\n// DELIBERATE CHOICE: these detectors take the RAW Gorgias ticket payload,\n// not the kit's `Conversation` domain type. `Conversation` (T14) only\n// carries aggregated facts (`hasCustomerAttachment`, `sourceChannel`,\n// `lastAgentReplyAt`, `isClosed`) — it has already thrown away the\n// per-message shape (`channel`, `from_agent`, `body_text`, `attachments`,\n// `created_datetime`) these detectors need. A node may never see that raw\n// shape (§9 of the graph spec), so these functions are for T21's adapter\n// layer: it computes `Conversation`'s aggregated fields FROM these, before a\n// node ever runs. The `Conversation`-based equivalents used by the graph's\n// `guardrails` node (`isJudgemeConversation`, `isAutomatedSenderEmail`, the\n// whatsapp channel pre-gates) live in `channel-pre-gates.ts` and are T17's\n// concern to wire up; `isJudgemeTicket` below is a thin wrapper over\n// `isJudgemeConversation` so the two entry shapes share one implementation.\n//\n// Spec: spec-migration-gorgias-backoffice-v1.md §3.9; anti-collision spec §3.1\n// (`isTicketClosed`, `hasAgentReplySince`).\nimport { isJudgemeConversation } from './channel-pre-gates';\nimport { CLOCK_SKEW_MARGIN_MS } from './constants';\nimport { normalise } from './text';\n\n/**\n * Superset-compatible with `@wopilo/gorgias-client`'s `RawGorgiasTicketPayload`\n * (B1): this package may not import `@wopilo/*` (dependency-allowlist.spec.ts),\n * so this is a local, structural declaration rather than an import — but\n * every field the client actually returns must still be ASSIGNABLE here, or\n * T21's adapter/T24's `ext-*` functions (both of which hold a real client\n * payload) hit `strict: true` compile errors and reach for `as unknown as`,\n * which defeats the point of a typed shape. Pinned by an assignability\n * assertion in `packages/gorgias-client` so the two cannot silently drift\n * apart again.\n */\ninterface RawTicketMessage {\n /** Names the customer turn a `reply-timing` row measures (spec-delais-de-reponse-v1 §3). */\n id?: number | string | null;\n /** How Gorgias received the message: `api` (us), `helpdesk` (an agent), `rule` (an automation)… — spec-delais-de-reponse-v1 §4. */\n via?: string | null;\n channel?: string | null;\n from_agent?: boolean;\n body_text?: string | null;\n /**\n * HTML/stripped variants (T3-review-A5 parity, `conversation-mapping.ts`'s\n * `countableMessages`): a message whose sole content is HTML has a blank\n * `body_text`, so a text-presence check reading `body_text` alone misses a\n * real customer turn. Declared here — not converted to text, just checked\n * for non-blank presence — so this package can detect that case without\n * porting `htmlToText`.\n */\n body_html?: string | null;\n stripped_text?: string | null;\n stripped_html?: string | null;\n attachments?: unknown[];\n created_datetime?: string | null;\n /**\n * `type` feeds `isInternalNoteChannel` (B2). `to` is read for one thing\n * only: OUR address on a social channel, which appears nowhere else in the\n * payload — the inbound message is addressed to the brand's own channel id\n * (`domain/publication.ts`).\n */\n source?: { type?: string; to?: Array<{ address?: string | null }> | null } | null;\n}\n\n/** One of `customer.channels[]` — the customer's address on a given channel. */\ninterface RawTicketCustomerChannel {\n type?: string | null;\n address?: string | null;\n preferred?: boolean;\n}\n\nexport interface RawTicket {\n channel?: string | null;\n subject?: string | null;\n status?: string | null;\n customer?: { email?: string | null; channels?: RawTicketCustomerChannel[] | null } | null;\n /**\n * Gorgias' own answer to \"where can this ticket be replied to\", keyed by\n * channel. Authoritative and per-ticket, which is why nothing here guesses\n * it from the channel name (`domain/publication.ts`).\n */\n reply_options?: Record<string, { answerable?: boolean } | null> | null;\n messages?: RawTicketMessage[];\n}\n\n/** Channels `reply_options` marks answerable. Empty when the payload has no such key. */\nexport function answerableChannels(raw: RawTicket | null | undefined): string[] {\n const options = raw?.reply_options;\n if (!options) return [];\n return Object.entries(options)\n .filter(([, value]) => value?.answerable === true)\n .map(([channel]) => channel);\n}\n\n/**\n * The customer's address on `channel`, preferring the entry Gorgias marks\n * `preferred` — a contact can carry several (an Instagram DM id AND an\n * Instagram handle, on the same ticket).\n */\nexport function customerChannelAddress(raw: RawTicket | null | undefined, channel: string | null): string | null {\n if (!channel) return null;\n const matches = (raw?.customer?.channels ?? []).filter((entry) => entry.type === channel && !!entry.address);\n const chosen = matches.find((entry) => entry.preferred) ?? matches[0];\n return chosen?.address ?? null;\n}\n\n/**\n * Our own address on `channel`: the destination of the customer's own\n * message. Read off the FIRST inbound message on that channel — the brand's\n * channel id does not change mid-thread, and a later agent message would\n * have it as the sender instead.\n */\nexport function accountChannelAddress(raw: RawTicket | null | undefined, channel: string | null): string | null {\n if (!channel) return null;\n for (const message of raw?.messages ?? []) {\n if (message.from_agent === true) continue;\n if (message.channel !== channel) continue;\n const address = message.source?.to?.[0]?.address;\n if (address) return address;\n }\n return null;\n}\n\nexport const WHATSAPP_NOTE_CHEVRON = '>';\n\n/**\n * True for an internal note, whether Gorgias routed it there via `channel`\n * OR via `source.type` (B2). Testing `channel === 'internal-note'` alone —\n * as this module used to, at every call site below — is exactly the drift\n * `@wopilo/gorgias-client`'s own `isInternalNoteChannel` was introduced to\n * fix (that package's T3 review, \"A6\"): a note routed via `source.type`\n * would silently read here as an ordinary customer/agent message instead of\n * a note, mis-firing `attachment`/anti-collision guardrails. Kept in sync\n * with the client's version by hand — this package cannot import it.\n */\nfunction isInternalNoteChannel(message: RawTicketMessage): boolean {\n return message.channel === 'internal-note' || message.source?.type === 'internal-note';\n}\n\n/**\n * True for a `from_agent` internal note whose body starts with the\n * chevron — the note Gorgias' WhatsApp integration turns into an outbound\n * message (whatsapp spec §7/§8.2, unfavourable case). An ordinary internal\n * note (no chevron) is deliberately NOT matched, and `isWhatsappConversation`\n * must be true for anything to match — quoting a customer in a note is a\n * normal habit on EMAIL tickets and must not be caught here.\n */\nexport function isWhatsappChevronNote(message: RawTicketMessage, isWhatsappConversation: boolean): boolean {\n if (!isWhatsappConversation) return false;\n return (\n isInternalNoteChannel(message) &&\n message?.from_agent === true &&\n typeof message?.body_text === 'string' &&\n message.body_text.startsWith(WHATSAPP_NOTE_CHEVRON)\n );\n}\n\n/**\n * True when a CUSTOMER message carries an attachment. Agent messages and\n * internal notes must not trigger the `attachment` guardrail — an agent\n * uploading a return label is not a reason to hold the reply.\n */\nexport function hasCustomerAttachment(rawTicket: RawTicket | null | undefined): boolean {\n return (rawTicket?.messages ?? []).some(\n (m) => !isInternalNoteChannel(m) && !m.from_agent && (m.attachments?.length ?? 0) > 0,\n );\n}\n\n/**\n * True when the ticket is a WhatsApp conversation — the ticket channel is\n * whatsapp, or any message came through the whatsapp channel.\n */\nexport function isWhatsappTicket(rawTicket: RawTicket | null | undefined): boolean {\n if (rawTicket?.channel === 'whatsapp') return true;\n return (rawTicket?.messages ?? []).some((m) => m.channel === 'whatsapp');\n}\n\n/**\n * True when the ticket is a Judge.me review-notification email. Deterministic,\n * no LLM: matches the ticket subject, or the first customer message body.\n * Judge.me puts the customer in From/Reply-To, so the sender is unusable — we\n * key off the subject and body markers instead.\n *\n * Thin wrapper over `isJudgemeConversation` (`channel-pre-gates.ts`): the two\n * differ only in HOW they get to (subject, first customer message) — this one\n * reads it off the raw ticket's messages, the other takes it pre-resolved\n * from a `Conversation`. The matching logic itself lives in exactly one\n * place.\n */\nexport function isJudgemeTicket(rawTicket: RawTicket | null | undefined): boolean {\n // Skip internal notes, agent messages and empty bodies — a later message\n // quoting the notification must not requalify an ordinary ticket.\n const firstCustomer = (rawTicket?.messages ?? []).find(\n (m) => !isInternalNoteChannel(m) && !m.from_agent && (m.body_text ?? '').trim().length > 0,\n );\n return isJudgemeConversation(rawTicket?.subject ?? null, firstCustomer?.body_text ?? null);\n}\n\n/**\n * True when the ticket customer email matches an entry of `senders`.\n * Deterministic, no LLM: unlike Judge.me, an automated no-reply sender (e.g.\n * Bigblue) does not usurp the customer field, so matching the sender email\n * is reliable. Pure — the caller resolves the configured list.\n *\n * Each entry supports three forms: an exact address (strict equality), a\n * `@domain` suffix (endsWith), or a `local@` prefix (startsWith). Empty/blank\n * entries are skipped — they must never match everything.\n *\n * NOT a thin wrapper over `isAutomatedSenderEmail` (`channel-pre-gates.ts`),\n * and vice versa: for a malformed entry like a bare `'@'`, this function\n * tries EVERY form for an entry before giving up on it (three separate\n * `if`s), while `isAutomatedSenderEmail` commits to the first matching form\n * and returns whatever it decides. The two already disagreed here in the\n * legacy codebase — see that function's doc for the concrete case. Ported\n * as-is rather than silently reconciled.\n */\nexport function isAutomatedSenderTicket(rawTicket: RawTicket | null | undefined, senders: string[]): boolean {\n const email = normalise(rawTicket?.customer?.email ?? '').trim();\n if (!email) return false;\n\n for (const entry of senders) {\n const e = normalise(entry).trim();\n if (!e) continue;\n if (e.startsWith('@') && email.endsWith(e)) return true;\n if (e.endsWith('@') && email.startsWith(e)) return true;\n if (email === e) return true;\n }\n\n return false;\n}\n\n/**\n * True when the Gorgias ticket is explicitly closed. Absent/unknown status\n * counts as open — never block every send on an API schema drift.\n */\nexport function isTicketClosed(rawTicket: RawTicket | null | undefined): boolean {\n return rawTicket?.status === 'closed';\n}\n\n/**\n * True when any public agent message (human or our own auto-reply — both make\n * sending redundant/colliding) was created after `since`, modulo the clock-skew\n * margin. Internal notes excluded — EXCEPT, on a WhatsApp ticket, a\n * chevron-prefixed one, which IS our WhatsApp reply: with no other trace of\n * the send on the ticket, a second run must still see it and hold. An\n * ordinary internal note (no chevron) stays excluded, and so does a\n * chevron-shaped note on an EMAIL ticket (`isWhatsappTicket` gates it) —\n * quoting a customer in a note is a normal habit there and must not suppress\n * a sendable auto-reply. Messages without a `created_datetime` are ignored:\n * undatable, so only the divergence check can catch them.\n *\n * NOTE (ported as-is): this function has no production caller in the legacy\n * codebase — the graph-based worker's own anti-collision check (T17's `act`)\n * is what is actually used at runtime. Kept here, exercised only by tests,\n * because the anti-collision spec asks for it \"tant que le chemin legacy\n * vit\" — not this lot's to delete.\n */\nexport function hasAgentReplySince(rawTicket: RawTicket | null | undefined, since: Date): boolean {\n const isWhatsapp = isWhatsappTicket(rawTicket);\n return (rawTicket?.messages ?? []).some(\n (m) =>\n m?.from_agent === true &&\n (!isInternalNoteChannel(m) || isWhatsappChevronNote(m, isWhatsapp)) &&\n m?.created_datetime &&\n new Date(m.created_datetime).getTime() > since.getTime() - CLOCK_SKEW_MARGIN_MS,\n );\n}\n","// Ported unchanged from legacy `src/services/autoReplyGuard.ts`.\n//\n// Spec: spec-migration-gorgias-backoffice-v1.md §3.9.\nimport { CANDIDATE_MIN_LENGTH, UNCERTAINTY_MARKERS } from './constants';\nimport { normalise } from './text';\n\nexport interface RunGuardrailsInput {\n firstCustomerMessage: string;\n candidateAnswer: string;\n hasAttachment: boolean;\n blocklist: string[];\n}\n\n/**\n * Run all deterministic content guardrails and return the list of hits, in\n * their exact evaluation order (§3.9):\n * 1. Blocklist — accent/case-insensitive substring match against the FIRST\n * customer message (not the draft), one hit per matched term.\n * 2. Attachment.\n * 3. Short answer (`candidateAnswer.trim().length < CANDIDATE_MIN_LENGTH`).\n * 4. Uncertainty markers — first match only.\n */\nexport function runGuardrails(input: RunGuardrailsInput): string[] {\n const hits: string[] = [];\n const { firstCustomerMessage, candidateAnswer, hasAttachment, blocklist } = input;\n\n // 1. Blocklist — accent/case-insensitive substring match\n const normalisedMessage = normalise(firstCustomerMessage);\n for (const term of blocklist) {\n if (normalisedMessage.includes(normalise(term))) {\n hits.push(`blocklist:${term}`);\n }\n }\n\n // 2. Attachment\n if (hasAttachment) {\n hits.push('attachment');\n }\n\n // 3. Short answer\n if (candidateAnswer.trim().length < CANDIDATE_MIN_LENGTH) {\n hits.push('short_answer');\n }\n\n // 4. Uncertainty markers\n const normalisedAnswer = normalise(candidateAnswer);\n for (const marker of UNCERTAINTY_MARKERS) {\n if (normalisedAnswer.includes(marker)) {\n hits.push('uncertainty_marker');\n break;\n }\n }\n\n return hits;\n}\n\n/**\n * Reason bucket of a guardrail hit — `blocklist:<term>` all collapse into\n * `blocklist`. Lives here because this module owns the hit encoding.\n */\nexport function guardrailBucket(hit: string): string {\n // `split(':')` on a string always yields at least one element, so `?? hit`\n // is unreachable — it exists only to satisfy `noUncheckedIndexedAccess`,\n // not as a semantic fallback.\n return hit.split(':')[0] ?? hit;\n}\n","// Spec: architecture_agent_graphe.md §6.1, §6.5 (guardrail catalogue), I7;\n// ported per spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// The deterministic catalogue gating every auto-send. The content rules\n// (blocklist/attachment/short_answer/uncertainty_marker) are `runGuardrails`,\n// reused verbatim (I7: \"identique au caractère près\") rather than\n// duplicated. The channel/sender and triage pre-gates are re-derived from\n// domain data — `escalated` is not checked here because the graph already\n// exits on it before this node ever runs.\n//\n// CRITICAL ordering/filtering asymmetry (pinned by this file's own spec):\n// `channelPreGates` (whatsapp_stop/not_customer_turn), then `whatsapp`, then\n// `judgeme`, then `noreply_sender`, then `triage_not_high` are ALL\n// UNCONDITIONAL — never filtered through `active`. Only the `runGuardrails`\n// content hits are filtered by `active.includes(guardrailBucket(hit))`.\nimport {\n channelPreGates,\n firstCustomerMessage,\n isAutomatedSenderEmail,\n isJudgemeConversation,\n} from '../../guardrails/channel-pre-gates';\nimport { guardrailBucket, runGuardrails } from '../../guardrails/run-guardrails';\nimport type { AgentProfile, Classification, Conversation } from '../../domain';\nimport type { Node } from '../state';\n\n/**\n * The rule itself, over the four things it actually reads — extracted from\n * the `Node` below so the hold-reason reconstruction\n * (`guardrails/reconstruct-hold.ts`) can replay THIS code on an old record\n * instead of a second copy of it that could disagree with production about\n * why a reply was held.\n */\nexport function collectGuardrailHits(\n conversation: Conversation,\n draftText: string,\n classification: Classification | null,\n profile: Pick<AgentProfile, 'guardrails' | 'autoSend'>,\n): string[] {\n const { params, active } = profile.guardrails;\n const hits: string[] = [...channelPreGates(conversation)];\n\n if (params.whatsappMode === 'escalate_only' && conversation.sourceChannel === 'whatsapp') hits.push('whatsapp');\n\n if (params.judgemeEscalateOnly && isJudgemeConversation(conversation.subject, firstCustomerMessage(conversation))) {\n hits.push('judgeme');\n }\n if (isAutomatedSenderEmail(conversation.customer.email, params.noreplySenders)) hits.push('noreply_sender');\n if (profile.autoSend.requireHighTriage && classification?.confidence !== 'high') hits.push('triage_not_high');\n\n // Content rules: only the ones this profile activated count (§6.5). The\n // blocklist scans the CUSTOMER's OPENING message, not our draft — the\n // admin list is written against that meaning, scanning the draft instead\n // would silently redefine every configured term.\n const contentHits = runGuardrails({\n firstCustomerMessage: firstCustomerMessage(conversation) ?? '',\n candidateAnswer: draftText,\n hasAttachment: conversation.hasCustomerAttachment,\n blocklist: params.blocklist,\n }).filter((hit) => active.includes(guardrailBucket(hit)));\n\n return [...hits, ...contentHits];\n}\n\nexport const guardrails: Node = async (state, deps) => {\n const conversation = state.conversation;\n if (!conversation || !state.draft) return { guardrailHits: [] };\n return { guardrailHits: collectGuardrailHits(conversation, state.draft.text, state.classification, deps.profile) };\n};\n","// Ported unchanged from legacy `src/services/autoReplyGuard.ts`.\n//\n// This is the single-function guard that backed the legacy fast-response\n// worker directly. It is kept exactly as it was — legacy field names\n// (`auto_reply_*`, snake_case) included — because that worker's settings\n// document is what it was written against; a future lot may retire it once\n// nothing calls it, but T15 ports it verbatim rather than reconciling it\n// with the kit's new `AgentProfile.guardrails.params` shape (that\n// reconciliation is the graph `guardrails` node's job, T17, over the pure\n// `runGuardrails`/`guardrailBucket`/detectors this module also exports).\n//\n// Spec: spec-migration-gorgias-backoffice-v1.md §3.9.\nimport { DEFAULT_WHATSAPP_MODE, isSendableVerdict, type EvaluationVerdict, type WhatsappMode } from '../domain';\nimport { runGuardrails } from './run-guardrails';\n\n/**\n * A judged candidate reply, as produced by the evaluation agent (agent 4).\n * @deprecated Legacy `verifyReply` vocabulary — see this module's header\n * comment. New code reads `AgentProfile.guardrails.params` and the graph\n * `guardrails` node (T17) instead.\n */\nexport interface JudgedReply {\n verdict: EvaluationVerdict;\n confidence: number;\n reason: string;\n}\n\n/**\n * The subset of the legacy settings document `verifyReply` reads. Field\n * names are the legacy `auto_reply_*` ones on purpose (see module comment).\n * @deprecated Legacy `verifyReply` vocabulary — see this module's header\n * comment. New code reads `AgentProfile.guardrails.params` and the graph\n * `guardrails` node (T17) instead.\n */\nexport interface AutoReplyGuardSettings {\n auto_reply_whatsapp_mode?: WhatsappMode;\n auto_reply_judgeme_escalate_only?: boolean;\n auto_reply_require_high_triage?: boolean;\n auto_reply_blocklist?: string[];\n}\n\n/**\n * @deprecated Legacy `verifyReply` vocabulary — see this module's header\n * comment. New code reads `AgentProfile.guardrails.params` and the graph\n * `guardrails` node (T17) instead.\n */\nexport interface VerifyReplyInput {\n /** First customer message in the thread (used for blocklist), not the latest. */\n firstCustomerMessage: string;\n candidateAnswer: string;\n hasAttachment: boolean;\n /**\n * True when the ticket has at least one WhatsApp message. Combined with\n * settings.auto_reply_whatsapp_mode, it forces a hold — WhatsApp threads\n * are usually opened by us, so we never auto-answer them.\n */\n isWhatsapp: boolean;\n /**\n * True when the ticket is a Judge.me review notification. Combined with\n * settings.auto_reply_judgeme_escalate_only, it forces a hold — a review\n * notification is not a support request, so we never auto-answer it.\n */\n isJudgeme: boolean;\n /**\n * True when the ticket customer email matches the configured\n * `auto_reply_noreply_senders` list — combined by the caller. It forces a\n * hold: the \"customer\" is an automated no-reply sender (e.g. Bigblue), so we\n * never auto-answer it.\n */\n isAutomatedSender: boolean;\n triageConfidence: 'high' | 'low' | null;\n /**\n * Escalation decision from the triage run (agent 2). `true` blocks the\n * auto-reply outright — a ticket flagged for a human is never auto-answered.\n * null/undefined = escalation disabled or not executed.\n */\n escalated?: boolean | null;\n /**\n * Already-resolved confidence threshold.\n * The CALLER (worker) resolves the per-category override:\n * category.auto_reply_min_confidence ?? settings.auto_reply_min_confidence\n */\n minConfidence: number;\n settings: AutoReplyGuardSettings;\n /**\n * Evaluation-agent result (agent 4), produced by processJob when\n * settings.evaluation_enabled. It is the ONLY source of the send verdict:\n * absent/null (evaluation disabled, or errored) forces a hold.\n */\n evaluation?: JudgedReply | null;\n}\n\n/**\n * @deprecated Legacy `verifyReply` vocabulary — see this module's header\n * comment. New code reads `AgentProfile.guardrails.params` and the graph\n * `guardrails` node (T17) instead.\n */\nexport interface VerifyReplyResult {\n decision: 'send' | 'hold';\n confidence: number;\n reason: string;\n guardrailHits: string[];\n}\n\n/**\n * Verify whether a candidate reply is safe to send automatically.\n *\n * @deprecated Ported verbatim from the legacy fast-response worker (see this\n * module's header comment) — new code should drive auto-send off the graph\n * `guardrails` node (T17), built on `runGuardrails`/`guardrailBucket` and\n * `AgentProfile.guardrails.params`, not off this function's legacy\n * `auto_reply_*` vocabulary.\n *\n * Evaluation order (cheapest first):\n * 1. Triage pre-gate + escalation pre-gate (no LLM call)\n * 2. Deterministic guardrails (no LLM call)\n * 3. Evaluation verdict (agent 4) — mandatory: no verdict, no send\n * 4. Final decision: send iff verdict ∈ {send, send_and_escalate} AND\n * confidence >= minConfidence\n *\n * This function performs NO LLM call of its own — the verdict is always the\n * evaluation agent's.\n */\nexport function verifyReply(input: VerifyReplyInput): VerifyReplyResult {\n const { settings, triageConfidence, minConfidence, candidateAnswer } = input;\n\n // Step 0: WhatsApp pre-gate — WhatsApp threads are usually opened by us, so a\n // customer reply is rarely a real support request. `escalate_only` (the\n // default) always holds (escalate to a human) whatever the other settings\n // say. Fail-safe: a settings doc predating the field counts as\n // `escalate_only` — the gate must never be silently off.\n if ((settings.auto_reply_whatsapp_mode ?? DEFAULT_WHATSAPP_MODE) === 'escalate_only' && input.isWhatsapp) {\n return {\n decision: 'hold',\n confidence: 0,\n reason: 'whatsapp channel — escalate only',\n guardrailHits: ['whatsapp'],\n };\n }\n\n // Step 0bis: Judge.me pre-gate — a review notification is not a support\n // request; never auto-answer, always escalate. Fail-safe: absent counts as\n // enabled.\n if ((settings.auto_reply_judgeme_escalate_only ?? true) && input.isJudgeme) {\n return {\n decision: 'hold',\n confidence: 0,\n reason: 'judgeme review notification — escalate only',\n guardrailHits: ['judgeme'],\n };\n }\n\n // Step 0ter: no-reply sender pre-gate — the ticket \"customer\" is a robot\n // (Bigblue & co); replying to a no-reply address is pointless, always\n // escalate. The caller resolves the configured sender list.\n if (input.isAutomatedSender) {\n return {\n decision: 'hold',\n confidence: 0,\n reason: 'automated no-reply sender — escalate only',\n guardrailHits: ['noreply_sender'],\n };\n }\n\n // Step 1: Triage pre-gate\n if (settings.auto_reply_require_high_triage && triageConfidence !== 'high') {\n return {\n decision: 'hold',\n confidence: 0,\n reason: 'triage confidence not high',\n guardrailHits: ['triage_not_high'],\n };\n }\n\n // Step 1bis: Escalation pre-gate — a ticket the escalation agent flagged for\n // a human must never be auto-answered, even if a fast response exists.\n if (input.escalated === true) {\n return {\n decision: 'hold',\n confidence: 0,\n reason: 'ticket escalated to human',\n guardrailHits: ['escalated'],\n };\n }\n\n // Step 2: Deterministic guardrails\n const guardrailHits = runGuardrails({\n firstCustomerMessage: input.firstCustomerMessage,\n candidateAnswer,\n hasAttachment: input.hasAttachment,\n blocklist: settings.auto_reply_blocklist ?? [],\n });\n\n if (guardrailHits.length > 0) {\n return {\n decision: 'hold',\n confidence: 0,\n reason: `guardrail: ${guardrailHits.join(', ')}`,\n guardrailHits,\n };\n }\n\n // Step 3: Evaluation verdict — the single judge of an auto-send. Missing\n // means evaluation is disabled or it errored: both are a hold, never a send.\n const { evaluation } = input;\n if (!evaluation) {\n return {\n decision: 'hold',\n confidence: 0,\n reason: 'no evaluation verdict — auto-send requires the evaluation agent',\n guardrailHits: ['evaluation_missing'],\n };\n }\n\n // Step 4: Final decision\n const decision = isSendableVerdict(evaluation.verdict) && evaluation.confidence >= minConfidence ? 'send' : 'hold';\n\n return {\n decision,\n confidence: evaluation.confidence,\n reason: evaluation.reason,\n guardrailHits: [],\n };\n}\n","/**\n * Derives the kit's domain `Conversation` from the SINGLE\n * `getTicketWithContext` fetch (`ctx-ports.ts`'s\n * `createGorgiasConversationPort`; B, T21 review), which returns both:\n *\n * - the RAW payload the guardrail detectors need (`isWhatsappTicket`,\n * `isJudgemeTicket`, `isAutomatedSenderTicket`, `isTicketClosed`,\n * `hasCustomerAttachment` — `guardrails/raw-ticket.ts`) and this\n * module's own message-count/timestamp snapshot.\n * - the ALREADY-EXTRACTED chronological messages + customer-info block a\n * node actually drafts against — its HTML-to-text conversion and\n * \"Information Client\" synthetic prefix are Gorgias-specific rendering\n * this package does not re-derive.\n *\n * `getRawTicket` and `buildTicketContext` used to be called as two separate\n * actions reading the exact same Gorgias endpoint (§S1) — a `read()` call\n * paid for it twice, and worse, the two fetches could observe different\n * server states if a message landed between them. `getTicketWithContext`\n * (`@wopilo/gorgias-client`) fetches once and derives both halves from that\n * one payload, so the raw-based facts and the domain conversation are now\n * GUARANTEED — not just assumed — to describe the exact same server\n * response.\n */\nimport {\n accountChannelAddress,\n answerableChannels,\n customerChannelAddress,\n hasCustomerAttachment,\n isTicketClosed,\n isWhatsappChevronNote,\n isWhatsappTicket,\n type RawTicket,\n} from '../guardrails';\nimport type { AwaitingSince, Conversation, ConversationRef, Message } from '../domain';\n\ntype RawMessage = NonNullable<RawTicket['messages']>[number];\n\n/** One turn of `buildTicketContext`'s already-extracted conversation. */\nexport interface RawTicketContextMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n synthetic?: boolean;\n}\n\n/** The shape `ctx.api.integrations.run('gorgias', 'buildTicketContext', …)` returns. */\nexport interface RawTicketContext {\n messages: RawTicketContextMessage[];\n customerContext: string | null;\n customerName?: string | null;\n customerEmail?: string | null;\n}\n\n/**\n * Same predicate `guardrails/raw-ticket.ts` uses internally, un-exported\n * there. Duplicated here BY HAND, same precedent that module's own doc\n * gives for its copy of `@wopilo/gorgias-client`'s `isInternalNoteChannel`:\n * this package may not import that client, so the one-line rule is kept in\n * sync manually rather than reached for through a forbidden import.\n */\nfunction isInternalNoteChannel(message: RawMessage): boolean {\n return message.channel === 'internal-note' || message.source?.type === 'internal-note';\n}\n\n/**\n * Port of `@wopilo/gorgias-client`'s `countableMessages` (`ticket-context.ts`)\n * — the divergence-snapshot rule. This package cannot import that package\n * (dependency-allowlist), so it is kept in sync by hand.\n *\n * \"Has extractable text\" checks PRESENCE across `body_text`/`body_html`/\n * `stripped_text`/`stripped_html` — not conversion. The client's own\n * `extractMessageText` prefers HTML and runs it through `htmlToText`\n * (T3-review-A5: an HTML-only customer reply has a blank `body_text`, so\n * checking that field alone misses a real turn — invisible to\n * `Conversation.messageCount`/`lastMessageAt`, so `act`'s divergence check\n * never sees the customer replied and a stale draft gets auto-sent). This\n * package cannot port `htmlToText` in, so it stays on the SAFE side instead:\n * any non-blank field counts, even a `<br>`-only body that `htmlToText`\n * would reduce to nothing. That can only ever over-count — producing a\n * spurious *hold*, never a spurious send.\n */\nfunction countableMessages(messages: RawMessage[], isWhatsapp: boolean): RawMessage[] {\n return messages.filter((m) => {\n if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);\n const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());\n const hasAttachment = (m.attachments?.length ?? 0) > 0;\n return hasText || hasAttachment;\n });\n}\n\nexport interface ConversationSnapshot {\n count: number;\n lastAt: Date | null;\n}\n\n/** Message count + last-message timestamp — feeds `Conversation.messageCount`/`lastMessageAt` (I8's anti-divergence snapshot). */\nexport function snapshotConversation(raw: RawTicket): ConversationSnapshot {\n const isWhatsapp = isWhatsappTicket(raw);\n const messages = countableMessages(raw.messages ?? [], isWhatsapp);\n let lastAt: Date | null = null;\n for (const m of messages) {\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!lastAt || at > lastAt) lastAt = at;\n }\n return { count: messages.length, lastAt };\n}\n\n/**\n * When an agent (human or our own auto-reply) last spoke. Deliberately\n * applies NO countability/text test of its own — it follows\n * `raw-ticket.ts`'s `hasAgentReplySince` (channel/chevron rule only),\n * generalised from a boolean since-a-date check to the timestamp itself,\n * since `Conversation.lastAgentReplyAt` needs the value, not a threshold.\n * That is the safe direction: an agent message with no extractable text\n * still counts as \"the agent spoke\", so this never under-reports the last\n * agent activity.\n *\n * Exported (28/09/2026) for `guardrails/reconstruct-hold.ts`, which has to\n * answer the same question about a past instant when rebuilding why a reply\n * was held — with THIS rule, not a second reading of it.\n */\nexport function lastAgentReplyAtOf(raw: RawTicket): Date | null {\n const isWhatsapp = isWhatsappTicket(raw);\n return latestAt(raw, (m) => isAgentReply(m, isWhatsapp));\n}\n\nfunction latestAt(raw: RawTicket, counts: (m: RawMessage) => boolean): Date | null {\n let latest: Date | null = null;\n for (const m of raw.messages ?? []) {\n if (!counts(m)) continue;\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!latest || at > latest) latest = at;\n }\n return latest;\n}\n\n/**\n * What counts as \"the agent spoke\" — `lastAgentReplyAtOf`'s rule, extracted\n * so the reply-delay measure (spec-delais-de-reponse-v1 §4) reads the same\n * one: an agent message, internal notes excluded except our WhatsApp chevron\n * note, which IS the reply on that channel.\n */\nfunction isAgentReply(m: RawMessage, isWhatsapp: boolean): boolean {\n if (m.from_agent !== true) return false;\n return !isInternalNoteChannel(m) || isWhatsappChevronNote(m, isWhatsapp);\n}\n\n/** A message a Gorgias rule posted — an acknowledgement or an auto-reply, not a person's or our answer. */\nfunction isRuleMessage(m: RawMessage): boolean {\n return m.via === 'rule';\n}\n\n/**\n * The first customer message written after the last agent reply — where the\n * customer's wait started (D2), not their latest message. Null when the agent\n * has the last word. Only a message the conversation snapshot counts can\n * start the clock: an empty one is not a question anybody waits on.\n *\n * A Gorgias RULE's message is no reply (W0, spec-delais-de-reponse-v1 §4): the\n * helpdesk acknowledges every email within seconds, `from_agent: true`, and\n * read as \"the agent spoke\" it would leave no email turn to measure at all.\n * The guardrails' own reading (`lastAgentReplyAtOf`) is deliberately left as\n * it is.\n */\nexport function awaitingSinceOf(raw: RawTicket): AwaitingSince | null {\n const isWhatsapp = isWhatsappTicket(raw);\n const lastAgentReplyAt = latestAt(raw, (m) => isAgentReply(m, isWhatsapp) && !isRuleMessage(m));\n let first: AwaitingSince | null = null;\n for (const m of countableMessages(raw.messages ?? [], isWhatsapp)) {\n if (m.from_agent === true || isInternalNoteChannel(m) || !m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (lastAgentReplyAt && at <= lastAgentReplyAt) continue;\n if (!first || at < first.at) first = { at, messageId: m.id == null ? null : String(m.id) };\n }\n return first;\n}\n\n/**\n * Assembles the domain `Conversation`. `sourceChannel` honours the T15\n * contract restated in `graph/ports.ts`'s `Conversation` doc: `'whatsapp'`\n * IFF `isWhatsappTicket(raw)`, never a bare `raw.channel` read.\n */\nexport function toConversation(ref: ConversationRef, raw: RawTicket, context: RawTicketContext): Conversation {\n const snapshot = snapshotConversation(raw);\n const messages: Message[] = context.messages\n .filter((m): m is RawTicketContextMessage & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')\n .map((m) => ({ role: m.role, content: m.content }));\n\n const sourceChannel = isWhatsappTicket(raw) ? 'whatsapp' : (raw.channel ?? null);\n return {\n ref,\n subject: raw.subject ?? null,\n messages,\n customer: {\n name: context.customerName ?? null,\n email: context.customerEmail ?? null,\n orderContext: context.customerContext ?? null,\n },\n isClosed: isTicketClosed(raw),\n lastMessageAt: snapshot.lastAt,\n messageCount: snapshot.count,\n lastAgentReplyAt: lastAgentReplyAtOf(raw),\n awaitingSince: awaitingSinceOf(raw),\n answerableChannels: answerableChannels(raw),\n customerChannelAddress: customerChannelAddress(raw, sourceChannel),\n accountChannelAddress: accountChannelAddress(raw, sourceChannel),\n hasCustomerAttachment: hasCustomerAttachment(raw),\n sourceChannel,\n };\n}\n","/**\n * Why a reply was held, rebuilt after the fact.\n *\n * `guardrailHits` was declared on `generated-response` long before anything\n * wrote it, so every hold recorded before 28/09/2026 carries `[]` and its\n * reason exists nowhere — not in the record, not in the run's logs, not in\n * Langfuse. This module rebuilds it for those rows, and only for those rows.\n *\n * It is a DEDUCTION, never a recording, and two things make that so:\n *\n * - the tenant settings it replays are today's, not necessarily the ones\n * the run applied, so the caller must stamp\n * `guardrailHitsReconstructedAt` for the timeline to say as much;\n * - `run_deadline` is invisible from the outside — nothing durable records\n * that a run's budget expired — so a hold caused by it comes back\n * unexplained rather than mislabelled as the next check down the list.\n *\n * What it is NOT is a second implementation of the rules. The content and\n * channel guardrails run through `collectGuardrailHits`, the very function\n * the live `guardrails` node calls; only the two conversation snapshots it\n * works from are rebuilt. `act`'s five send-time checks are restated here —\n * they live inside a node that posts replies, which a backfill may not call\n * — and `reconstruct-hold.spec.ts` pins them against `act.spec.ts`'s own\n * expectations.\n */\nimport { collectGuardrailHits } from '../graph/nodes/guardrails';\nimport { lastAgentReplyAtOf, snapshotConversation } from '../adapters/conversation-mapping';\nimport type { AgentProfile, Classification, Conversation } from '../domain';\nimport { stopOptOut, channelPreGates } from './channel-pre-gates';\nimport { CLOCK_SKEW_MARGIN_MS } from './constants';\nimport type { RawTicket } from './raw-ticket';\n\nexport interface ReconstructHoldInput {\n /** The conversation as the run saw it when it drafted — rebuilt from the record's own `tracedInput` and generation-time snapshot. */\n generatedFrom: Conversation;\n /** The conversation as `act` would have re-read it, rebuilt from the Gorgias ticket truncated at the instant the run ended. */\n atSend: Conversation;\n /** The triage-decision this response was written under. */\n classification: Classification | null;\n /** The text the run drafted — `generated-response.responseText`. */\n draftText: string;\n /** Today's settings, as a profile. The approximation this module's own doc warns about. */\n profile: Pick<AgentProfile, 'guardrails' | 'autoSend'>;\n /** When the run ended, for `act`'s agent-reply window. `null` falls back to generation time. */\n queuedAt: Date | null;\n}\n\n/**\n * The hits the run would have recorded, in the order it would have recorded\n * them. Empty means \"cannot be explained from what survives\" — an honest\n * result the caller must report as unknown, not as \"no guardrail fired\".\n */\nexport function reconstructGuardrailHits(input: ReconstructHoldInput): string[] {\n const { generatedFrom, atSend, classification, draftText, profile, queuedAt } = input;\n\n // `run-ticket.ts`'s order: the STOP opt-out outranks every other exit, then\n // the WhatsApp pre-gates run before drafting, then the `guardrails` node.\n const stopHits = stopOptOut(generatedFrom);\n if (stopHits.length > 0) return stopHits;\n\n const preGateHits = channelPreGates(generatedFrom);\n if (preGateHits.length > 0) return preGateHits;\n\n const nodeHits = collectGuardrailHits(generatedFrom, draftText, classification, profile);\n if (nodeHits.length > 0) return nodeHits;\n\n return collisionHits(generatedFrom, atSend, queuedAt);\n}\n\n/**\n * `graph/nodes/act.ts`'s five send-time checks, in I8's frozen order. Kept in\n * step with that file by `reconstruct-hold.spec.ts`; `run_deadline` is\n * deliberately absent, since nothing outside the dead run can attest to it.\n */\nfunction collisionHits(generatedFrom: Conversation, atSend: Conversation, queuedAt: Date | null): string[] {\n const mode = generatedFrom.sourceChannel === 'whatsapp' ? 'whatsapp_note' : 'email';\n if (mode === 'email' && !atSend.customer.email) return ['customer_email_missing'];\n if (atSend.isClosed) return ['ticket_closed'];\n if (hasAgentRepliedSince(atSend.lastAgentReplyAt, queuedAt)) return ['agent_replied'];\n if (hasDiverged(atSend, generatedFrom)) return ['diverged'];\n return [];\n}\n\n/**\n * `act.ts`'s agent-reply check AS IT STOOD when these rows were written, and\n * deliberately NOT the one `act.ts` runs today.\n *\n * `act`'s rule gained a \"the agent must hold the last word\" clause on\n * 28/09/2026, which is precisely what stops Gorgias' acknowledgement from\n * reading as an answer. Every row this module explains predates that change\n * and was held by the OLD rule, so replaying the new one would report\n * \"indéterminé\" for the very holds the fix was written for.\n *\n * This is the one rule this module may not share with production, and the\n * reason is the reason the module exists: it reconstructs what the code DID,\n * not what the code would do now. `reconstruct-hold.spec.ts` pins the\n * divergence so it cannot be \"tidied up\" into a shared call.\n */\nfunction hasAgentRepliedSince(lastAgentReplyAt: Date | null, queuedAt: Date | null): boolean {\n if (!lastAgentReplyAt) return false;\n if (!queuedAt) return true;\n return lastAgentReplyAt.getTime() > queuedAt.getTime() - CLOCK_SKEW_MARGIN_MS;\n}\n\nfunction hasDiverged(atSend: Conversation, generatedFrom: Conversation): boolean {\n return (\n atSend.messageCount !== generatedFrom.messageCount ||\n (atSend.lastMessageAt?.getTime() ?? null) !== (generatedFrom.lastMessageAt?.getTime() ?? null)\n );\n}\n\n/** The three moving facts `act`'s re-read would have seen, as of one instant. */\nexport interface RawTicketFactsAt {\n messageCount: number;\n lastMessageAt: Date | null;\n lastAgentReplyAt: Date | null;\n}\n\n/**\n * What a Gorgias ticket looked like at `instant` — the only way to ask what\n * `act`'s fresh re-read saw, months later, from a payload that has kept\n * growing since.\n *\n * Messages are dropped by `created_datetime`, then the ticket is handed to\n * the SAME counting and agent-reply rules the live mapping uses\n * (`adapters/conversation-mapping.ts`), so a reconstruction cannot disagree\n * with production about what counts as a message. A message with no\n * timestamp at all is kept: it predates nothing we can prove, and keeping it\n * errs toward finding a hold rather than inventing a clean run.\n */\nexport function rawTicketFactsAt(raw: RawTicket, instant: Date): RawTicketFactsAt {\n const upTo: RawTicket = {\n ...raw,\n messages: (raw.messages ?? []).filter((message) => {\n if (!message.created_datetime) return true;\n return new Date(message.created_datetime).getTime() <= instant.getTime();\n }),\n };\n const { count, lastAt } = snapshotConversation(upTo);\n return { messageCount: count, lastMessageAt: lastAt, lastAgentReplyAt: lastAgentReplyAtOf(upTo) };\n}\n","// Spec: architecture_agent_graphe.md §6.1 (legacy `agent/predicates.ts`,\n// `agent/revise.ts`'s gate); ported per spec-migration-gorgias-backoffice-\n// v1.md §3.3 (`verdict/policy.ts`).\n//\n// DELIBERATE SIMPLIFICATION (§6.1, carried from the legacy source): today's\n// code checks the auto-send confidence TWICE — `evaluation_min_confidence`\n// at verdict time, then `auto_reply_min_confidence` (overridable per\n// category, via `verifyReply`) re-checked AFTER the guardrails. The target\n// keeps only the first check, in `isSendable` below. `CategoryPolicy.\n// minConfidence` is carried on `TicketRunState`/`NodeDeps` (`graph/state.ts`)\n// but INTENTIONALLY UNUSED here — the second gate is gone, not moved\n// elsewhere.\nimport type { AgentProfile, Verdict } from '../domain';\nimport { isSendableVerdict, requiresFollowup } from '../domain';\nimport { SUPPORT_CHANNELS } from '../domain/profile';\nimport { publicationMode } from '../domain/publication';\nimport type { NodeDeps, TicketRunState } from '../graph/state';\n\n/**\n * Evaluation succeeded, the verdict is sendable, confidence clears the\n * profile's bar, and any follow-up it demands is a feature this profile has\n * turned on.\n */\nexport function isSendable(verdict: Verdict | null, profile: AgentProfile): boolean {\n const node = profile.nodes.evaluate;\n if (!node || !verdict || verdict.status !== 'success') return false;\n if (!isSendableVerdict(verdict.verdict)) return false;\n if ((verdict.confidence ?? 0) < node.minConfidence) return false;\n return !requiresFollowup(verdict.verdict) || node.escalationEnabled;\n}\n\n/**\n * Whether the ticket may even be offered to auto-send: the tenant opted in,\n * this category opted in, there is an address to send from, and a verdict\n * was actually produced. Takes `deps` rather than just `profile` (unlike the\n * spec's pseudocode) because category opt-in is resolved by the caller into\n * `NodeDeps.category`, not carried on the profile itself.\n *\n * Whatsapp spec §9.1's own table is explicit that `draft_only` NEVER\n * auto-sends (\"le brouillon est produit (`ready`), **jamais** envoyé\n * automatiquement\") — `draft_only` is excluded here explicitly, on purpose.\n *\n * `escalate_only` is deliberately NOT excluded here, even though it also\n * never sends: it is caught downstream instead, by the `whatsapp` guardrail\n * hit (reached exactly because this predicate stays true), which produces\n * `guardrail_hold` + the escalation tag — the audit trail the spec wants\n * (\"un humain acte l'opt-out\"). Excluding `escalate_only` here too would\n * make that hit unreachable (this predicate gates entry to the `guardrails`\n * node) and silently swap every `escalate_only` WhatsApp ticket's outcome\n * from `guardrail_hold`+tag to `ready`+no tag — losing the tag is a bigger\n * behaviour change than the one this predicate closes.\n *\n * Whatsapp spec §4.4: `autoSend.senderEmail` is the address an email goes\n * out FROM, so the EMAIL path is the only one that needs it — asked of\n * `publicationMode` rather than re-derived from the channel here, so the\n * requirement follows the one decision that names the path.\n *\n * That answer also covers the conversation no path can reach at all\n * (`publicationMode` → `null`), which deliberately does NOT need a sender:\n * failing eligibility on it here would skip the `guardrails` node entirely,\n * and `hasPublicationPath` below exists precisely so that question is asked\n * after they have had their say.\n *\n * Reading the mode replaces an exemption scoped to `whatsappMode ===\n * 'auto_reply'`, which kept a sender-less tenant's `escalate_only` WhatsApp\n * tickets OUT of the guardrails — they ended `ready` with no tag, where the\n * `whatsapp` guardrail would have held them for a human. That hit is the\n * audit trail §5.1 asks for; a missing email address was never a reason to\n * lose it.\n */\nexport function isAutoSendEligible(\n state: TicketRunState,\n deps: Pick<NodeDeps, 'profile' | 'category'>,\n): boolean {\n const isWhatsapp = state.conversation?.sourceChannel === 'whatsapp';\n const whatsappDraftOnly = isWhatsapp && deps.profile.guardrails.params.whatsappMode === 'draft_only';\n const needsSenderEmail = publicationMode(state.conversation) === 'email';\n\n return (\n deps.profile.autoSend.enabled &&\n deps.category.autoReplyEnabled &&\n (!needsSenderEmail || !!deps.profile.autoSend.senderEmail) &&\n !!state.verdict &&\n !whatsappDraftOnly\n );\n}\n\n/**\n * Is there any way to publish a reply on this conversation?\n *\n * NOT \"does the customer have an email address\" — that requirement belongs\n * to the email path alone (`domain/publication.ts`). An Instagram or\n * Facebook contact is addressed by a channel id, and a WhatsApp note needs\n * no recipient at all. Reading the missing email as a universal blocker is\n * what killed tickets 597737746 and 597892224.\n *\n * Deliberately NOT part of `isAutoSendEligible`, even though it is the same\n * kind of question: that predicate gates entry to the `guardrails` node, so\n * failing it there would ALSO skip the blocklist, the attachment rule and\n * the Judge.me/no-reply pre-gates. An Instagram thread saying \"mise en\n * demeure\" would then end `ready` with no escalation tag, where it used to\n * be held for a human — a regression on 45 % of that account's volume, in\n * the name of a fix. `run-ticket.ts` therefore asks this AFTER the\n * guardrails have had their say.\n */\nexport function hasPublicationPath(state: TicketRunState): boolean {\n return publicationMode(state.conversation) !== null;\n}\n\n/**\n * Does auto-send apply to the channel this ticket arrived on\n * (`autoSendChannels`, an allowlist)?\n *\n * An operator's restriction, and only that. It is NOT inert on a fresh\n * install: `DEFAULT_AUTO_SEND_CHANNELS` ships the six channels that were\n * auto-sending before this setting existed, so the six social ones start\n * unchecked and every Instagram/Facebook ticket takes this exit from day\n * one — `ready`, no tag. That is the intended gate (`domain/publication.ts`\n * gives those channels a real send path this deploy has not validated\n * against the live API), not a no-op waiting for someone to untick a box.\n *\n * Checked HERE rather than as a guardrail, like `whatsappDraftOnly` below:\n * a channel auto-send does not cover is not a collision to escalate, it is\n * auto-send being inapplicable. Both land on `ready` with no tag, the draft\n * still served to an agent.\n *\n * `act`'s own `customer_email_missing` check stays where it is: this decides\n * a policy, that one catches a contact whose address vanished between\n * drafting and posting.\n *\n * A channel the catalogue does not name is NOT restricted: the Réglages\n * checkboxes only render `SUPPORT_CHANNELS`, so a channel Gorgias adds\n * tomorrow would lose auto-send with no box to tick it back on. The list can\n * only take away what an operator can see and give back; anything else stays\n * governed by `hasPublicationPath` alone, exactly as it was before this\n * setting existed.\n *\n * An unreadable channel (no conversation, no `sourceChannel`) still fails\n * closed — that is a broken read, not a new channel.\n */\nexport function isAutoSendChannel(state: TicketRunState, deps: Pick<NodeDeps, 'profile'>): boolean {\n const channel = state.conversation?.sourceChannel;\n if (!channel) return false;\n if (!(SUPPORT_CHANNELS as readonly string[]).includes(channel)) return true;\n return deps.profile.autoSend.channels.includes(channel);\n}\n\n/**\n * Whether the draft gets a correction pass (one pass maximum, §6.1).\n *\n * `send_and_escalate` is SENDABLE (I6) and therefore never revised: the\n * reply goes out and a human follows up afterwards, so rewriting it would\n * replace an answer the judge already accepted. An evaluation in `error` is\n * not revised either — fail-safe means needs_human (I5), and there is no\n * judgement to correct against.\n */\nexport function needsRevision(verdict: Verdict | null, profile: AgentProfile, reviseCount: number): boolean {\n if (!profile.nodes.revise) return false;\n if (reviseCount >= 1) return false;\n if (!verdict || verdict.status !== 'success') return false;\n return !isSendableVerdict(verdict.verdict);\n}\n","// Spec: architecture_agent_graphe.md §6.1, §6.4 (fetchContext row); ported\n// per spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// The only node allowed to call `ConversationPort.read` — every other node\n// works off the state it produces. A read failure is a technical failure\n// (`outcome: 'failed'`); a conversation with no customer message is NOT a\n// failure here — a valid, if message-less, `Conversation` is still returned,\n// and the fallback classification for that case is `triage`'s job (§6.4).\nimport type { Node } from '../state';\n\nexport const fetchContext: Node = async (_state, deps) => {\n try {\n const conversation = await deps.ports.conversation.read(deps.ref);\n return { conversation };\n } catch (err) {\n deps.log(`fetchContext: read failed for ${deps.ref.id}: ${(err as Error).message}`);\n return { conversation: null, outcome: 'failed' };\n }\n};\n","// Spec: architecture_agent_graphe.md §6.1, §6.4 (triage row), I1; ported per\n// spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// Strict JSON schema keeps the model inside {tag, confidence, reasoning}. The full enum-of-tags constraint (I1) needs the\n// profile's Category referential, which lives outside the kit and a node may\n// never reach (§1); the schema below still forces the *shape*, not the tag\n// vocabulary. On error, or when there is no customer message to classify,\n// the profile's unknown-tag fallback keeps the ticket on the normal tagging\n// path instead of failing the run (§6.4 — only a technical read error,\n// handled by `fetchContext`, is a run failure).\nimport { firstCustomerMessage, lastCustomerMessage } from '../../guardrails/channel-pre-gates';\nimport { REASONING_MAX_LEN } from '../../domain';\nimport type { Classification } from '../../domain';\nimport type { JsonSchema } from '../ports';\nimport type { CategoryReferentialEntry, Node } from '../state';\n\n/** The `CompletionRequest.label` of the triage call; `functions/ticket-trace.ts` keys its capture on it. */\nexport const TRIAGE_LABEL = 'triage';\n\n// spec-fin-de-conversation-v1 D1: triage only categorises — the end of a conversation is judged by its own step, after triage, on every incoming message.\nconst TRIAGE_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n tag: { type: 'string' },\n confidence: { type: 'string', enum: ['high', 'low'] },\n reasoning: { type: 'string', maxLength: REASONING_MAX_LEN },\n },\n required: ['tag', 'confidence', 'reasoning'],\n additionalProperties: false,\n};\n\n/**\n * Renders the category referential for the `{{categories}}` substitution\n * (§3.7), ported byte-for-byte from legacy `services/triage.ts`'s\n * `renderCategories`/`injectCategories`: `name` kept only when present,\n * `examples` dropped when empty, the whole list serialised as pretty JSON.\n */\nfunction renderCategories(categories: CategoryReferentialEntry[]): string {\n return JSON.stringify(\n categories.map(({ name, tag, desc, examples }) => ({\n ...(name !== undefined ? { name } : {}),\n tag,\n desc,\n ...(examples ? { examples } : {}),\n })),\n null,\n 2,\n );\n}\n\nfunction fallback(unknownTag: string, reason: string): Classification {\n return {\n category: unknownTag,\n confidence: 'low',\n reasoning: reason.slice(0, REASONING_MAX_LEN),\n isFallback: true,\n };\n}\n\nexport const triage: Node = async (state, deps) => {\n const { profile } = deps;\n const conversation = state.conversation;\n if (!conversation) return {}; // fetchContext already failed the run\n\n const message = firstCustomerMessage(conversation);\n if (!message) {\n return { classification: fallback(profile.audit.unknownTag, 'No customer message found in ticket') };\n }\n\n const node = profile.nodes.triage;\n const userParts: string[] = [];\n if (conversation.customer.orderContext) userParts.push(`## Contexte client\\n${conversation.customer.orderContext}`);\n userParts.push(`## Message à classifier\\n${message}`);\n // §5.2's judgement is anchored on the LAST message, not the classification\n // anchor above — added only when it differs, so a single-message thread's\n // payload stays byte-identical (iso-behaviour).\n const last = lastCustomerMessage(conversation);\n if (last && last !== message) userParts.push(`## Dernier message client\\n${last}`);\n\n // `resolve` NEVER REJECTS (PromptPort's contract) — no try/catch needed\n // around it; the try below is for the LLM call/parsing only. `categories`\n // (§3.7) is substituted here so the model always sees the tenant's real\n // taxonomy, never the literal `{{categories}}` placeholder (A1).\n const promptVariables = { categories: renderCategories(deps.categories) };\n const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.triage, promptVariables);\n\n try {\n const result = await deps.ports.llm.complete({\n label: TRIAGE_LABEL,\n // The model stored in the OS wins; the prompt's Langfuse config is ignored.\n model: node.model,\n reasoning: node.reasoning,\n messages: [\n { role: 'system', content: resolvedPrompt.text },\n { role: 'user', content: userParts.join('\\n\\n') },\n ],\n responseSchema: TRIAGE_SCHEMA,\n signal: deps.budget.signal,\n promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false },\n promptVariables,\n });\n deps.budget.charge('triage', result.usage, { usd: 0, pricingMissing: true });\n\n const parsed = JSON.parse(result.text ?? '');\n if (typeof parsed.tag !== 'string' || (parsed.confidence !== 'high' && parsed.confidence !== 'low')) {\n throw new Error(`Invalid triage payload: ${result.text}`);\n }\n return {\n classification: {\n category: parsed.tag,\n confidence: parsed.confidence,\n reasoning: String(parsed.reasoning ?? '').slice(0, REASONING_MAX_LEN),\n isFallback: false,\n },\n };\n } catch (err) {\n return { classification: fallback(profile.audit.unknownTag, `Fallback after error: ${(err as Error).message}`) };\n }\n};\n","// Spec: architecture_agent_graphe.md §6.1, §6.4 (escalate row), I3; ported\n// per spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// Strict boolean schema; FAIL-OPEN (I3): any error — LLM failure, malformed\n// payload — leaves `escalated: false` and the flow continues, exactly like\n// the legacy inline escalation call. A ticket with no customer message, or a\n// profile with no escalate step configured, has nothing to judge and is\n// skipped WITHOUT an LLM call.\nimport { firstCustomerMessage } from '../../guardrails/channel-pre-gates';\nimport { REASONING_MAX_LEN } from '../../domain';\nimport type { JsonSchema } from '../ports';\nimport type { Node } from '../state';\n\n/** The `CompletionRequest.label` of the escalation call; `functions/ticket-trace.ts` keys its capture on it. */\nexport const ESCALATION_LABEL = 'escalation';\n\nconst ESCALATION_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n escalate: { type: 'boolean' },\n confidence: { type: 'string', enum: ['high', 'low'] },\n reasoning: { type: 'string', maxLength: REASONING_MAX_LEN },\n },\n required: ['escalate', 'confidence', 'reasoning'],\n additionalProperties: false,\n};\n\nexport const escalate: Node = async (state, deps) => {\n const { profile } = deps;\n const node = profile.nodes.escalate;\n const conversation = state.conversation;\n if (!node || !conversation) return { escalated: false };\n\n const message = firstCustomerMessage(conversation);\n if (!message) return { escalated: false }; // nothing to judge, no LLM call\n\n // Resolved OUTSIDE the try (C5 as amended, `graph/ports.ts`): a step with\n // no prompt at all must fail the run, and the fail-open catch below would\n // otherwise read it as \"nothing to escalate\" — the exact silent outcome\n // change that contract exists to prevent. Only the LLM call and its\n // parsing may fail open.\n const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.escalate);\n\n try {\n const userParts: string[] = [];\n if (conversation.customer.orderContext) userParts.push(`## Contexte client\\n${conversation.customer.orderContext}`);\n userParts.push(`## Message à classifier\\n${message}`);\n\n const result = await deps.ports.llm.complete({\n label: ESCALATION_LABEL,\n model: node.model,\n reasoning: node.reasoning,\n messages: [\n { role: 'system', content: resolvedPrompt.text },\n { role: 'user', content: userParts.join('\\n\\n') },\n ],\n responseSchema: ESCALATION_SCHEMA,\n signal: deps.budget.signal,\n promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false },\n });\n deps.budget.charge('escalate', result.usage, { usd: 0, pricingMissing: true });\n\n const parsed = JSON.parse(result.text ?? '');\n if (typeof parsed.escalate !== 'boolean') throw new Error(`Invalid escalate payload: ${result.text}`);\n return { escalated: parsed.escalate };\n } catch {\n return { escalated: false }; // fail-open (I3)\n }\n};\n","// Spec: architecture_agent_graphe.md §6.1, §6.4 (authorize row), §7\n// (ProposedAction, reserved for P3); ported per\n// spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// One action kind exists today, `send_reply`; a later phase grows the list.\n// DEFAULT DENY (§6.4): a kind absent from `profile.authorization` decides\n// 'forbidden', never 'auto' — the caller's gate treats anything but an\n// explicit 'auto' the same way.\nimport type { ActionDecision } from '../../domain';\nimport type { Node } from '../state';\n\nexport const authorize: Node = async (state, deps) => {\n const kind = 'send_reply';\n const decision: ActionDecision = deps.profile.authorization[kind] ?? 'forbidden';\n return {\n proposedActions: [\n {\n kind,\n args: { text: state.draft?.text ?? '' },\n idempotencyKey: `${deps.ref.channel}:${deps.ref.id}:${kind}`,\n decision,\n },\n ],\n };\n};\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §3.9; ported unchanged\n// from legacy `agent/tools/readTools.ts`.\n//\n// The four read tools of the P0' catalogue (`AGENT_TOOLS`, `graph/ports.ts`).\n// Each one validates its own arguments and turns a lookup — found, not\n// found, or failing — into a short text observation: the model reads prose,\n// never a raw object or a stack trace. Execution failures are left to throw\n// here; `runToolCall` (`registry.ts`) is the single place that turns a throw\n// into `isError`.\nimport type { JsonSchema, ToolContext } from '../ports';\n\nexport interface ReadTool {\n name: string;\n description: string;\n inputSchema: JsonSchema;\n run(args: Record<string, unknown>, ctx: ToolContext): Promise<string>;\n}\n\nfunction requireString(args: Record<string, unknown>, key: string): string {\n const value = args[key];\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`Missing or invalid argument \"${key}\": expected a non-empty string.`);\n }\n return value;\n}\n\nfunction optionalPositiveNumber(args: Record<string, unknown>, key: string, fallback: number): number {\n const value = args[key];\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new Error(`Invalid argument \"${key}\": expected a positive number.`);\n }\n return value;\n}\n\nconst orderIdSchema: JsonSchema = {\n type: 'object',\n properties: {\n orderId: { type: 'string', description: 'The order id, e.g. \"WPL-42\".' },\n },\n required: ['orderId'],\n additionalProperties: false,\n};\n\nconst getOrder: ReadTool = {\n name: 'get_order',\n description: 'Look up an order by its id and return its current status.',\n inputSchema: orderIdSchema,\n async run(args, ctx) {\n const orderId = requireString(args, 'orderId');\n const order = await ctx.getOrder(orderId);\n if (!order) return `No order found for id \"${orderId}\".`;\n const placed = order.placedAt ? `, placed on ${order.placedAt}` : '';\n return `Order ${order.id}: status \"${order.status}\"${placed}.`;\n },\n};\n\nconst getTracking: ReadTool = {\n name: 'get_tracking',\n description: 'Look up shipment tracking information for an order.',\n inputSchema: orderIdSchema,\n async run(args, ctx) {\n const orderId = requireString(args, 'orderId');\n const tracking = await ctx.getTracking(orderId);\n if (!tracking) return `No tracking information found for order \"${orderId}\".`;\n const url = tracking.url ? ` (${tracking.url})` : '';\n return `Order ${tracking.orderId}: ${tracking.carrier} tracking ${tracking.trackingNumber}, status \"${tracking.status}\"${url}.`;\n },\n};\n\nconst searchKnowledge: ReadTool = {\n name: 'search_knowledge',\n description: 'Search the support knowledge base for information relevant to a query.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'What to search for.' },\n },\n required: ['query'],\n additionalProperties: false,\n },\n async run(args, ctx) {\n const query = requireString(args, 'query');\n const hits = await ctx.searchKnowledge(query);\n if (hits.length === 0) return `No knowledge base entries found for \"${query}\".`;\n return hits.map((hit) => `- ${hit.title}: ${hit.content}`).join('\\n');\n },\n};\n\nconst DEFAULT_SIMILAR_TICKETS_LIMIT = 5;\n\nconst findSimilarTickets: ReadTool = {\n name: 'find_similar_tickets',\n description: 'Find previously handled tickets similar to a query, to see how they were resolved.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'What to search for.' },\n limit: { type: 'number', description: `Maximum number of results (default ${DEFAULT_SIMILAR_TICKETS_LIMIT}).` },\n },\n required: ['query'],\n additionalProperties: false,\n },\n async run(args, ctx) {\n const query = requireString(args, 'query');\n const limit = optionalPositiveNumber(args, 'limit', DEFAULT_SIMILAR_TICKETS_LIMIT);\n const tickets = await ctx.findSimilarTickets(query, limit);\n if (tickets.length === 0) return `No similar tickets found for \"${query}\".`;\n return tickets.map((ticket) => `- [${ticket.category}] ${ticket.excerpt}`).join('\\n');\n },\n};\n\n/** Keyed by the exact names of `AGENT_TOOLS` (`graph/ports.ts`). */\nexport const READ_TOOLS: Record<string, ReadTool> = {\n get_order: getOrder,\n get_tracking: getTracking,\n search_knowledge: searchKnowledge,\n find_similar_tickets: findSimilarTickets,\n};\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §3.9; ported from\n// legacy `agent/tools/registry.ts`.\n//\n// A profile only ever reaches its own read tools. `resolveFor` is the one\n// gate every tool call goes through — refusing here is what keeps\n// `gorgias.rename_conversation` and any other write tool out of the\n// model's reach even if a profile were somehow written to list one (I2).\nimport type { AgentProfile, ToolCallRecord } from '../../domain';\nimport { AGENT_TOOLS, type ToolCallRequest, type ToolContext, type ToolPolicy, type ToolSpec } from '../ports';\nimport { READ_TOOLS } from './read-tools';\n\nexport interface RegisteredTool {\n name: string;\n policy: ToolPolicy;\n}\n\n/** The tools a node call needs to know about — never the full profile. */\ntype ToolProfile = Pick<AgentProfile, 'tools'>;\n\nexport function resolveFor(profile: ToolProfile, name: string): RegisteredTool | null {\n if (!profile.tools.includes(name)) return null; // not listed for this tenant\n const catalogued = AGENT_TOOLS[name];\n if (!catalogued || catalogued.policy !== 'read') return null; // unknown, or a write tool (I2)\n return { name: catalogued.name, policy: catalogued.policy };\n}\n\n/** What the model is shown for one completion: the profile's tools, in the profile's order. */\nexport function buildToolSpecs(profile: ToolProfile): ToolSpec[] {\n const specs: ToolSpec[] = [];\n for (const name of profile.tools) {\n if (!resolveFor(profile, name)) continue; // refused, or the catalogue doesn't know it\n const impl = READ_TOOLS[name];\n if (!impl) continue; // catalogued but not yet implemented — offer the known ones anyway\n specs.push({ name: impl.name, description: impl.description, inputSchema: impl.inputSchema });\n }\n return specs;\n}\n\nexport interface ToolCallOutcome {\n observation: string;\n isError: boolean;\n /** Provenance entry for `Draft.sources` (§3), win or refusal alike. */\n record: ToolCallRecord;\n}\n\nfunction outcome(call: ToolCallRequest, observation: string, isError: boolean): ToolCallOutcome {\n return { observation, isError, record: { name: call.name, arguments: call.arguments, observation } };\n}\n\n/**\n * Runs one tool call. Never throws: a refusal, a bad argument, or a failing\n * lookup all come back as `isError: true` with an observation the model can\n * read and recover from — never a ticket failure (§6.2, §6.3).\n */\nexport async function runToolCall(\n profile: ToolProfile,\n call: ToolCallRequest,\n ctx: ToolContext,\n): Promise<ToolCallOutcome> {\n if (!resolveFor(profile, call.name)) {\n return outcome(call, `Tool \"${call.name}\" is not available for this profile.`, true);\n }\n\n const impl = READ_TOOLS[call.name];\n if (!impl) {\n return outcome(call, `Tool \"${call.name}\" is not implemented.`, true);\n }\n\n try {\n const observation = await impl.run(call.arguments, ctx);\n return outcome(call, observation, false);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return outcome(call, message, true);\n }\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.2, §6.3; ported\n// from legacy `agent/draft.ts`, diagram boucle-outils-agent.\n//\n// The model may ask for read tools; the code runs them and hands the\n// observations back, until it produces text or the budget runs out. The\n// sequence is never the model's to decide — this loop is code, the model\n// only proposes.\nimport type { AgentProfile, Draft, DraftAttribution, ToolCallRecord } from '../domain';\nimport type { ChatMessage, CompletionResult, LlmPort, ToolContext, ToolSpec } from './ports';\nimport type { Budget } from './budget';\nimport { buildToolSpecs, runToolCall } from './tools';\n\n// A misconfigured budget (e.g. maxToolCalls never reached because of a bad\n// wiring) must not turn this into an infinite loop — this is a hard floor\n// under the profile-configured `maxToolCalls`, never the normal exit path.\nconst MAX_LOOP_ROUNDS = 25;\n\nexport interface DraftWithToolsParams {\n profile: AgentProfile;\n llm: LlmPort;\n budget: Budget;\n toolContext: ToolContext;\n messages: ChatMessage[];\n /** Langfuse generation name (I17), forwarded unchanged to every completion. */\n label: string;\n /**\n * Links every completion of the loop to the prompt version that produced\n * its system message (I17). `resolve: false` (D-LF follow-up, link-only\n * mode) — see `CompletionRequest.promptRef`'s doc in `./ports.ts`.\n */\n promptRef?: { name: string; version?: number; resolve?: boolean };\n}\n\nexport async function draftWithTools(params: DraftWithToolsParams): Promise<Draft> {\n const { profile, llm, budget, toolContext, messages, label, promptRef } = params;\n const node = profile.nodes.draft;\n if (!node) throw new Error('draftWithTools requires profile.nodes.draft to be configured.');\n\n const conversation: ChatMessage[] = [...messages];\n const sources: ToolCallRecord[] = [];\n\n for (let round = 0; round < MAX_LOOP_ROUNDS; round++) {\n // Once the budget is spent we still let the model produce text with what\n // we already gathered — we just stop offering it more tools (§6.3).\n const offerTools = !budget.exhausted();\n const tools = offerTools ? toolsOrUndefined(buildToolSpecs(profile)) : [];\n\n const result = await llm.complete({\n label,\n model: node.model,\n reasoning: node.reasoning,\n messages: conversation,\n tools,\n signal: budget.signal,\n promptRef,\n });\n\n // Pricing needs a lookup this node has no access to (it would require a\n // database, forbidden in a node by §1), so the charge is flagged\n // unpriced rather than reported as free (I15's golden-set cost tracking).\n budget.charge('draft', result.usage, { usd: 0, pricingMissing: true });\n\n // The completion that produces the text is also the one that owns the\n // draft's Langfuse attribution (§3.4) — an earlier tool round holds ids\n // for a generation the customer never reads.\n if (result.toolCalls.length === 0) return finish(result.text, sources, messages, attributionOf(result, promptRef));\n\n conversation.push({ role: 'assistant', content: result.text, toolCalls: result.toolCalls });\n for (const call of result.toolCalls) {\n budget.consumeToolCall();\n const { observation, record } = await runToolCall(profile, call, toolContext);\n sources.push(record);\n conversation.push({ role: 'tool', toolCallId: call.id, content: observation });\n }\n }\n\n // The loop-round floor was hit without the model ever producing text.\n return finish(null, sources, messages, null);\n}\n\n/**\n * The loop's single exit. An empty answer is a FAILURE, never a servable\n * draft: persisted as `ready` it would be handed to an agent — or auto-sent —\n * as a blank reply. The throw travels up to the caller, which records the\n * run as `failed`.\n */\nfunction finish(\n text: string | null,\n sources: ToolCallRecord[],\n messages: ChatMessage[],\n attribution: DraftAttribution | null,\n): Draft {\n const trimmed = (text ?? '').trim();\n if (!trimmed) throw new Error('Provider returned empty response');\n return { text: trimmed, sources, messages, revised: false, ...(attribution ? { attribution } : {}) };\n}\n\n/**\n * The four §3.4 ids of one completion: Langfuse's own, plus the prompt\n * version that produced its system message. Reported as `null` rather than\n * omitted when the gateway traces nothing — a partially filled attribution\n * would read as \"this generation exists somewhere\", which is exactly what\n * the quality loop must not assume.\n */\nexport function attributionOf(\n result: CompletionResult,\n promptRef: { name: string; version?: number } | undefined,\n): DraftAttribution {\n return {\n traceId: result.traceId ?? null,\n observationId: result.observationId ?? null,\n promptName: promptRef?.name ?? null,\n promptVersion: promptRef?.version ?? null,\n };\n}\n\nfunction toolsOrUndefined(specs: ToolSpec[]): ToolSpec[] | undefined {\n // `tools: []` and `tools: undefined` are NOT interchangeable on the wire:\n // the canary (§6.2) needs `undefined` so a tools-off profile reproduces\n // today's request byte for byte.\n return specs.length > 0 ? specs : undefined;\n}\n","// Spec: architecture_agent_graphe.md §6.1 (legacy `agent/nodes/shared.ts`);\n// ported per spec-migration-gorgias-backoffice-v1.md §3.3.\n//\n// No `Node` export here on purpose — §1 requires every node file to export\n// exactly one `Node`-typed function. `writerSystemPrompt`/`buildDraftMessages`\n// are DRAFT-node helpers shared by `draft`/`revise`/`evaluate`, each of which\n// calls them directly.\n//\n// `isJudgemeConversation`/`isAutomatedSenderEmail`/`firstCustomerMessage`/\n// `lastCustomerMessage` are NOT re-declared here — T15 already ported them\n// to `guardrails/channel-pre-gates.ts`; import from there instead.\nimport type { Conversation } from '../../domain';\nimport type { ChatMessage } from '../ports';\n\nconst AGENT_NAME_PLACEHOLDER = /\\{\\{\\s*agent_name\\s*\\}\\}/gi;\nconst AGENT_NAME_PLACEHOLDER_TEST = /\\{\\{\\s*agent_name\\s*\\}\\}/i;\n\n/**\n * Ported unchanged from legacy `utils/agentSignature.ts`'s `applySignature`.\n *\n * Exported (T24): `ext-chat` (§5.2, §3.7 — \"l'injection signature\n * `{{agent_name}}` est injectée par `ext-chat`\") needs this SAME function,\n * with the real `agentName` the extension sends — `writerSystemPrompt`\n * below cannot be reused for that call, since it hardcodes an empty name on\n * WhatsApp and `undefined` everywhere else, deliberately never forwarding a\n * real agent name (see its own doc). Reusing `applySignature` itself here\n * keeps this single ported implementation as the one place the rule lives,\n * per the migration's explicit \"do not re-implement it\" instruction.\n *\n * Rules:\n * - Placeholder present + name supplied → replace all occurrences with the trimmed name.\n * - Placeholder present + no name → replace all occurrences with the empty string.\n * - No placeholder + name supplied → append a French signing instruction.\n * - No placeholder + no name → return the prompt unchanged.\n */\nexport function applySignature(systemPrompt: string, agentName?: string): string {\n const trimmedName = (typeof agentName === 'string' ? agentName.trim() : '').slice(0, 200);\n\n if (AGENT_NAME_PLACEHOLDER_TEST.test(systemPrompt)) {\n // Replacer function so a `$`-pattern in the name is never interpreted.\n const replaced = systemPrompt.replace(AGENT_NAME_PLACEHOLDER, () => trimmedName);\n // Collapse lines left blank by a standalone placeholder.\n return replaced.replace(/\\n{3,}/g, '\\n\\n').trim();\n }\n\n if (trimmedName) {\n return `${systemPrompt}\\n\\nSigne toujours la réponse avec ce nom : ${trimmedName}.`;\n }\n\n return systemPrompt;\n}\n\n/**\n * The writer's system prompt exactly as the drafting call sends it.\n *\n * Takes the ALREADY-RESOLVED prompt text, not the profile (post-T17 review\n * A2): the caller resolves `profile.prompts.draft` through `PromptPort`\n * itself — this function only applies the channel-specific signature rule on\n * top, it never reads `AgentProfile.prompts` directly.\n *\n * Never SIGNED on WhatsApp (whatsapp spec §6.3): no caller here passes\n * `applySignature` an `agentName` (no route wires one in on this path), so\n * the empty name forced below changes nothing YET — it documents, in code,\n * that WhatsApp must never receive one even if a future caller starts\n * passing a real name. `applySignature` still runs on every channel for its\n * OTHER job: stripping a stray `{{agent_name}}` placeholder rather than\n * leaking the literal template syntax into the customer's message — §6.3's\n * \"aucune consigne ajoutée\" bans the appended signing INSTRUCTION, not this\n * cleanup, and an empty name never triggers that instruction anyway.\n */\nexport function writerSystemPrompt(resolvedPrompt: string, conversation: Conversation): string {\n return applySignature(resolvedPrompt, conversation.sourceChannel === 'whatsapp' ? '' : undefined);\n}\n\n/**\n * The `ChatMessage[]` a draft/revise completion needs: an optional system\n * prompt (already signed — callers apply `applySignature` themselves, via\n * `writerSystemPrompt`) with the rendered order/customer context, followed by\n * the conversation turns.\n */\nexport function buildDraftMessages(conversation: Conversation, systemPrompt: string): ChatMessage[] {\n const context = conversation.customer.orderContext;\n const system = [systemPrompt, context ? `## Informations client\\n${context}` : null]\n .filter((part): part is string => !!part)\n .join('\\n\\n');\n const turns: ChatMessage[] = conversation.messages.map((m) => ({ role: m.role, content: m.content }));\n return system ? [{ role: 'system', content: system }, ...turns] : turns;\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.1, §6.4 (draft\n// row), I25; ported from legacy `agent/nodes/draft.ts`.\n//\n// Wraps the existing tool loop (`../draft.ts`'s `draftWithTools`, P0'-c) —\n// this node's only job is turning the conversation into the `ChatMessage[]`\n// the loop needs; the loop itself, its budget and its tool wiring are\n// untouched.\nimport { draftWithTools } from '../draft';\nimport type { Node } from '../state';\nimport { buildDraftMessages, writerSystemPrompt } from './shared';\n\n/** Langfuse generation name (I17) — unchanged from today's fast-response worker. */\nconst LABEL = 'fast-response';\n\nexport const draft: Node = async (state, deps) => {\n const { profile } = deps;\n const node = profile.nodes.draft;\n if (!state.conversation || !node) return {};\n\n // `resolve` NEVER REJECTS (`PromptPort`'s contract) — this call cannot\n // itself throw. Reading through the port, not `profile.prompts.draft`\n // directly (post-T17 review A2), is what lets T19's `{{channel_prompt}}`/\n // `{{agent_name}}` resolution reach this node.\n const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.draft);\n\n // No `agentName` here (worker path, unlike an interactive chat route) —\n // mirrors the legacy call site exactly (I25).\n const messages = buildDraftMessages(state.conversation, writerSystemPrompt(resolvedPrompt.text, state.conversation));\n\n const result = await draftWithTools({\n profile,\n llm: deps.ports.llm,\n budget: deps.budget,\n toolContext: deps.toolContext,\n messages,\n label: LABEL,\n promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false },\n });\n return { draft: result };\n};\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.1, §6.4 (evaluate\n// row), I5, I6; ported from legacy `agent/nodes/evaluate.ts`.\n//\n// Ternary verdict, tool-free by design (§6.4). FAIL-SAFE (I5): any error —\n// LLM failure, malformed payload — yields `status: 'error'`, which\n// `isSendable` (`verdict/policy.ts`) never treats as sendable. Called twice\n// on the revision loop (§6.1): once on the first draft, once more after\n// `revise`.\nimport { EVALUATION_VERDICTS, isEvaluationVerdict, REASONING_MAX_LEN } from '../../domain';\nimport type { Conversation, EvaluationVerdict, Verdict } from '../../domain';\nimport type { ChatMessage, JsonSchema } from '../ports';\nimport type { Node } from '../state';\nimport { writerSystemPrompt } from './shared';\n\nconst EVALUATION_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n verdict: { type: 'string', enum: [...EVALUATION_VERDICTS] },\n confidence: { type: 'number', minimum: 0, maximum: 1 },\n reason: { type: 'string', maxLength: REASONING_MAX_LEN },\n },\n required: ['verdict', 'confidence', 'reason'],\n additionalProperties: false,\n};\n\n/** Fail-safe verdict (I5), carrying WHY it failed — the caller persists this reason verbatim. */\nfunction failed(err: unknown): Verdict {\n const message = err instanceof Error ? err.message : String(err);\n return {\n verdict: null,\n confidence: null,\n reason: `evaluation error: ${message}`.slice(0, REASONING_MAX_LEN),\n status: 'error',\n // A call that never returned names no observation worth linking to.\n observationId: null,\n };\n}\n\nexport const evaluate: Node = async (state, deps) => {\n const { profile } = deps;\n const node = profile.nodes.evaluate;\n if (!node || !state.conversation || !state.draft) {\n return { verdict: failed(new Error('evaluate ran without a configured node, conversation or draft')) };\n }\n\n // Both resolved through `PromptPort`, never `AgentProfile.prompts`\n // directly (post-T17 review A2): the judge's own prompt, and the writer's\n // — the judge needs the writer's instructions/product knowledge to ground\n // \"n'invente rien\" against something real.\n //\n // Resolved OUTSIDE the try (C5 as amended, `graph/ports.ts`): the\n // fail-safe catch below turns any throw into a hold, which would bury a\n // step configured with no prompt as an ordinary \"the judge was unsure\".\n const evaluatePrompt = await deps.ports.prompt.resolve(profile.prompts.evaluate);\n const draftPrompt = await deps.ports.prompt.resolve(profile.prompts.draft);\n\n try {\n // The judge's own gateway when the tenant gave evaluation its own\n // provider; the writer's otherwise (`graph/state.ts`, `ports.evaluator`).\n const result = await (deps.ports.evaluator ?? deps.ports.llm).complete({\n label: 'evaluation',\n // The model stored in the OS wins; the prompt's Langfuse config is ignored.\n model: node.model,\n reasoning: node.reasoning,\n messages: buildMessages({\n conversation: state.conversation,\n candidateAnswer: state.draft.text,\n systemPrompt: evaluatePrompt.text,\n writerKnowledge: writerSystemPrompt(draftPrompt.text, state.conversation),\n }),\n responseSchema: EVALUATION_SCHEMA,\n signal: deps.budget.signal,\n promptRef: { name: evaluatePrompt.name, version: evaluatePrompt.version, resolve: false },\n });\n deps.budget.charge('evaluate', result.usage, { usd: 0, pricingMissing: true });\n return { verdict: parseVerdict(result.text, result.observationId ?? null) };\n } catch (err) {\n return { verdict: failed(err) };\n }\n};\n\n/**\n * Read a verdict out of a completion, or throw.\n *\n * The confidence range is re-checked here rather than trusted from\n * `EVALUATION_SCHEMA`: OpenAI's strict structured output enforces the TYPE,\n * not `minimum`/`maximum`, so an out-of-range `confidence: 5` would otherwise\n * clear every threshold it is compared against.\n */\nfunction parseVerdict(text: string | null, observationId: string | null): Verdict {\n const parsed = JSON.parse(text ?? '');\n const confidence: unknown = parsed.confidence;\n if (!isEvaluationVerdict(parsed.verdict)) throw new Error(`Invalid evaluation verdict: ${text}`);\n if (typeof confidence !== 'number' || !Number.isFinite(confidence) || confidence < 0 || confidence > 1) {\n throw new Error(`Evaluation confidence out of range: ${String(confidence)}`);\n }\n return {\n verdict: parsed.verdict as EvaluationVerdict,\n confidence,\n reason: String(parsed.reason ?? '').slice(0, REASONING_MAX_LEN),\n status: 'success',\n observationId,\n };\n}\n\ninterface EvaluationPromptInput {\n conversation: Conversation;\n candidateAnswer: string;\n systemPrompt: string;\n /**\n * The WRITER's system prompt (instructions + product knowledge). Without it\n * the judge grounds \"n'invente rien\" against nothing and reads legitimate\n * product facts as inventions.\n */\n writerKnowledge: string;\n}\n\nfunction buildMessages(input: EvaluationPromptInput): ChatMessage[] {\n const { conversation, candidateAnswer, systemPrompt, writerKnowledge } = input;\n const transcript = conversation.messages\n .map((m) => `[${m.role === 'user' ? 'Client' : 'Agent'}]: ${m.content}`)\n .join('\\n');\n const sections = [\n section('Instructions & connaissances du rédacteur', writerKnowledge),\n section('Infos client / commandes', conversation.customer.orderContext),\n section('Conversation', transcript),\n section('Réponse candidate à évaluer', candidateAnswer),\n ].filter((part): part is string => !!part);\n return [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: sections.join('\\n\\n') },\n ];\n}\n\nfunction section(title: string, body: string | null): string | null {\n const trimmed = body?.trim();\n return trimmed ? `## ${title}\\n${trimmed}` : null;\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.1, §6.4, I6; ported\n// from legacy `agent/revise.ts`.\n//\n// One correction pass between two evaluations. The gate is a predicate, not\n// an LLM call (`needsRevision`, `verdict/policy.ts` — ported in T16): the\n// model never decides whether it gets another turn.\nimport type { AgentProfile, Draft, Verdict } from '../domain';\nimport type { ChatMessage, LlmPort } from './ports';\nimport type { Budget } from './budget';\nimport { attributionOf } from './draft';\n\nexport interface ReviseDraftParams {\n profile: AgentProfile;\n llm: LlmPort;\n budget: Budget;\n draft: Draft;\n verdict: Verdict;\n messages: ChatMessage[];\n /** Langfuse generation name (I17) — its own, so revision cost is separable. */\n label: string;\n /**\n * Links this completion to the WRITER's prompt version (I17) — revision\n * has no prompt of its own, it re-runs the writer's context with the\n * correction turn below. `resolve: false` (D-LF follow-up, link-only\n * mode) — see `CompletionRequest.promptRef`'s doc in `./ports.ts`.\n */\n promptRef?: { name: string; version?: number; resolve?: boolean };\n}\n\n/**\n * Rewrite the draft against the judge's objection.\n *\n * Failure is never fatal (§6.4): a provider error or an empty rewrite keeps\n * the initial draft, which then follows the normal needs_human path. Only a\n * run deadline propagates, because that is not a revision problem (I14).\n */\nexport async function reviseDraft(params: ReviseDraftParams): Promise<Draft> {\n const { profile, llm, budget, draft, verdict, messages, label, promptRef } = params;\n const node = profile.nodes.revise;\n if (!node) return draft;\n\n let result;\n try {\n result = await llm.complete({\n label,\n model: node.model,\n reasoning: node.reasoning,\n messages: [...messages, ...buildRevisionTurn(draft, verdict)],\n tools: [], // tool-free by design (§6.4)\n signal: budget.signal,\n promptRef,\n });\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') throw err;\n return draft;\n }\n\n // Pricing needs a lookup this node has no access to (§1 forbids a database\n // here), so the charge is flagged unpriced rather than reported as free.\n budget.charge('revise', result.usage, { usd: 0, pricingMissing: true });\n\n const revisedText = result.text?.trim();\n if (!revisedText) return draft;\n\n // Sources are carried over untouched: the revision reworks the wording, it\n // does not look anything up again, so the provenance trail still holds.\n // The attribution is NOT: this completion wrote the served text, so it is\n // the one the quality loop must score (§3.4, last call wins). Every early\n // return above keeps the draft's own — a call that errored or came back\n // empty names no generation worth scoring.\n // `messages` carries over for the same reason `sources` does: the timeline's\n // \"Prompt envoyé\"/\"Reçu\" steps describe what the WRITER was given, and a\n // revision reworks that text without ever re-reading the conversation.\n return {\n text: revisedText,\n sources: draft.sources,\n messages: draft.messages,\n revised: true,\n attribution: attributionOf(result, promptRef),\n };\n}\n\n/**\n * The correction turn. The model needs both what it wrote and what the judge\n * objected to — without the reason it has nothing to aim at and tends to\n * paraphrase itself.\n */\nfunction buildRevisionTurn(draft: Draft, verdict: Verdict): ChatMessage[] {\n return [\n { role: 'assistant', content: draft.text },\n {\n role: 'user',\n content: [\n 'Ta réponse a été refusée par le relecteur pour la raison suivante :',\n verdict.reason,\n '',\n 'Réécris la réponse en corrigeant ce point. Garde le même ton, ne réponds',\n 'que par le texte corrigé, sans commentaire ni préambule.',\n ].join('\\n'),\n },\n ];\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.1 (revision loop,\n// P1), §6.4 (revise row), I6; ported from legacy `agent/nodes/revise.ts`.\n//\n// Wraps the existing correction pass (`../revise.ts`'s `reviseDraft`) — this\n// node builds the ORIGINAL conversation context `reviseDraft` needs (it\n// appends its own correction turn on top); the pass itself, and the one-pass\n// gate (`needsRevision`, `verdict/policy.ts`, reused directly by the graph\n// wiring of a later phase) are untouched. `reviseCount` is bumped here,\n// which is what stops the graph from ever looping a second time.\nimport { reviseDraft } from '../revise';\nimport type { Node } from '../state';\nimport { buildDraftMessages, writerSystemPrompt } from './shared';\n\nexport const revise: Node = async (state, deps) => {\n const { profile } = deps;\n const node = profile.nodes.revise;\n if (!node || !state.conversation || !state.draft || !state.verdict) return {};\n\n // Read through `PromptPort`, never `AgentProfile.prompts` directly\n // (post-T17 review A2). The writer's prompt is the ONLY one this step\n // speaks with: revision is the writer re-run against the judge's\n // objection, so the completion below is attributed to that same prompt\n // (I17) and runs on the step's own model setting.\n const draftPrompt = await deps.ports.prompt.resolve(profile.prompts.draft);\n const messages = buildDraftMessages(state.conversation, writerSystemPrompt(draftPrompt.text, state.conversation));\n\n const revised = await reviseDraft({\n profile,\n llm: deps.ports.llm,\n budget: deps.budget,\n draft: state.draft,\n verdict: state.verdict,\n messages,\n label: 'revise',\n promptRef: { name: draftPrompt.name, version: draftPrompt.version, resolve: false },\n });\n return { draft: revised, reviseCount: 1 };\n};\n","// Minimal markdown → HTML converter for the auto-reply email body. Ported\n// unchanged from legacy `utils/markdownToHtml.ts` — self-contained (no\n// imports of its own), so porting it costs the kit no new runtime\n// dependency. Deliberately tiny: the generated answers only use paragraphs,\n// line breaks, bold/italic and links.\n//\n// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.1 (act row).\n// Consumed by `nodes/act.ts` to render `OutboundReply`'s `bodyHtml` in email\n// mode only — the WhatsApp note posts the raw draft text (§4.2/§6.4).\n\nfunction escapeHtml(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n\nexport function markdownToHtml(markdown: string): string {\n let html = escapeHtml(markdown);\n // Links: [text](https://…) — http(s) only, no other protocols.\n html = html.replace(/\\[([^\\]]+)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g, '<a href=\"$2\">$1</a>');\n // Bold then italic (bold first so ** is not eaten as two *).\n html = html.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');\n // Italic only at word boundaries: the opening * must follow start/whitespace\n // and precede a non-space; the closing * must follow a non-space and precede\n // end/whitespace/punctuation — literal asterisks (\"60*60 cm\") stay intact.\n html = html.replace(/(^|\\s)\\*([^\\s*](?:[^*\\n]*[^\\s*])?)\\*(?=$|\\s|[.,;:!?)])/g, '$1<em>$2</em>');\n // Paragraphs on blank lines, <br> inside a paragraph.\n return html\n .split(/\\n{2,}/)\n .map((p) => `<p>${p.trim().replace(/\\n/g, '<br>')}</p>`)\n .join('');\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3, §6.1, §6.4 (act row),\n// §6.5 (send-time controls), §3.9, I8, I9; ported from legacy\n// `agent/nodes/act.ts`.\n//\n// Anti-collision re-read (I8): a fresh read of the conversation right before\n// posting catches what changed since generation — a closed ticket, a new\n// message, or an agent who already answered.\n//\n// The agent check is NOT covered by the divergence count. A reply that landed\n// between the job being queued and generation starting is present in BOTH\n// snapshots, so the counts match and divergence stays blind to it — that is\n// I8's window gap. Hence `lastAgentReplyAt` compared against when the run was\n// queued, which the caller passes in via `deps.queuedAt`.\n//\n// Any hit lands in the SAME `guardrailHits` the `guardrails` node uses —\n// §6.5 groups \"contrôles d'envoi\" as guardrails too.\n//\n// Unicité d'envoi (I9, claim → post → commit): the state machine that makes\n// this safe under concurrency needs persistence a node may never touch (§1).\n// `deps.send` is the discriminated seam (`graph/state.ts`) — `{mode: 'none'}`\n// treats every run as its own uncontested claim, as every node test does\n// today. The claim carries the draft and the verdict so the claiming write\n// persists them atomically: past this point a crash may cost the send, never\n// the generation.\nimport { CLOCK_SKEW_MARGIN_MS, type CollisionGuardrailId } from '../../guardrails/constants';\nimport { markdownToHtml } from '../markdown-to-html';\nimport { publicationMode, type Conversation, type PublicationMode } from '../../domain';\nimport type { OutboundReply } from '../ports';\nimport type { Node } from '../state';\n\n/**\n * True when an agent ANSWERED — meaning both halves below, not just the\n * second one.\n *\n * ONE, the agent has to hold the last word. An agent message older than the\n * thread's last message is not an answer to that message: someone spoke\n * after it, and since a later agent message would itself be\n * `lastAgentReplyAt`, that someone is the customer. Sending our draft, which\n * was written FOR that customer turn, doubles nobody.\n *\n * Added 28/09/2026 for ticket 597671587, where Gorgias' own weekend\n * acknowledgement landed 0,46 s BEFORE the customer message it acknowledged\n * and 32 s before the run — inside the skew margin below, so a perfectly\n * good reply was held and escalated. Gorgias offers nothing to tell that\n * acknowledgement from a human's reply (same `via`, same sender, no\n * `rule_id`), so the ordering is the only signal there is. It is also the\n * signal `channel-pre-gates.ts`'s `not_customer_turn` already reads, from\n * the other side — the two rules stop contradicting each other.\n *\n * TWO, it has to be recent enough to be news. With no queue instant to\n * compare against, any agent reply at all counts — refusing to send is the\n * safe side of an unknown.\n */\nfunction hasAgentAnswered(fresh: Conversation, queuedAt: Date | null): boolean {\n const { lastAgentReplyAt, lastMessageAt } = fresh;\n if (!lastAgentReplyAt) return false;\n if (lastMessageAt && lastAgentReplyAt.getTime() < lastMessageAt.getTime()) return false;\n if (!queuedAt) return true;\n return lastAgentReplyAt.getTime() > queuedAt.getTime() - CLOCK_SKEW_MARGIN_MS;\n}\n\n/**\n * The conversation moved under the run. Both halves matter: the count catches\n * a new message, the timestamp catches an edit or a message that replaced\n * another.\n *\n * L3 cross-reference: this is NOT the same rule\n * `ext-fast-response-check.ts`'s own `checkDivergence` uses — that one is\n * `count >`/\"strictly newer\" (legacy-faithful for serving an\n * already-generated draft), this one is `!==` on both fields (any change,\n * either direction — a re-send must never fire on a run that has drifted in\n * EITHER direction). Both are deliberate, not drift; `handle-approval.ts`\n * reads the same two stored fields a third time, for the same reason this\n * one does (I8's re-read).\n */\nfunction hasDiverged(fresh: Conversation, generatedFrom: Conversation): boolean {\n return (\n fresh.messageCount !== generatedFrom.messageCount ||\n (fresh.lastMessageAt?.getTime() ?? null) !== (generatedFrom.lastMessageAt?.getTime() ?? null)\n );\n}\n\n/**\n * A collision refusal, typed against `COLLISION_GUARDRAILS` so a hit name\n * invented here — or renamed there — is a compile error rather than an\n * unlabelled identifier in the operator's ticket timeline.\n */\nfunction refuse(hit: CollisionGuardrailId): { guardrailHits: string[] } {\n return { guardrailHits: [hit] };\n}\n\nexport const act: Node = async (state, deps) => {\n const generatedFrom = state.conversation;\n const draft = state.draft;\n const action = state.proposedActions[0];\n if (!generatedFrom || !draft || !action) return {};\n\n // Whatsapp spec §4.3 — one datum, one decision: the publication mode is\n // computed once, by `domain/publication.ts`, so the channel is never\n // decided twice.\n //\n // Read off the FRESH conversation, not `generatedFrom`: the mode now\n // depends on the customer's addresses, which can move under the run, and\n // `handle-approval` hands this node a placeholder snapshot that carries a\n // channel and nothing else.\n const fresh = await deps.ports.conversation.read(deps.ref);\n const mode = publicationMode(fresh);\n // No way to publish at all. In practice: an email-mode contact whose\n // address vanished between drafting and posting — `run-ticket.ts` already\n // refuses a conversation that never had a path, before a draft is even\n // written. The hit keeps its historical name; the address requirement it\n // describes belongs to the EMAIL path alone, an Instagram contact being\n // addressed by a channel id and a WhatsApp note by nothing at all.\n if (mode === null) return refuse('customer_email_missing');\n // Order is frozen by I8: a closed ticket wins over an agent reply, which\n // wins over divergence. Applies to both modes.\n if (fresh.isClosed) return refuse('ticket_closed');\n if (hasAgentAnswered(fresh, deps.queuedAt ?? null)) return refuse('agent_replied');\n if (hasDiverged(fresh, generatedFrom)) return refuse('diverged');\n // The re-read above can outlive the run deadline (I14). Posting past it\n // would send a reply the run is no longer accountable for.\n if (deps.budget.signal.aborted) return refuse('run_deadline');\n\n const claimed = deps.send.mode === 'claimed' ? await deps.send.claim({ draft, verdict: state.verdict }) : true;\n if (!claimed) return {}; // another worker already claimed this run\n\n // `OutboundReply` is a discriminated union (spec §4.1): each branch below\n // builds the exact shape its mode requires, so a missing email field would\n // fail to compile rather than post silently as `''`.\n const reply: OutboundReply = buildReply(mode, {\n draftText: draft.text,\n idempotencyKey: action.idempotencyKey,\n fresh,\n senderEmail: deps.profile.autoSend.senderEmail ?? '',\n });\n\n const { messageId } = await deps.ports.reply.post(deps.ref, reply);\n if (deps.send.mode === 'claimed') await deps.send.commit(messageId);\n return {};\n};\n\ninterface ReplyInputs {\n draftText: string;\n idempotencyKey: string;\n fresh: Conversation;\n senderEmail: string;\n}\n\n/**\n * `OutboundReply` is a discriminated union (spec §4.1): each branch builds\n * the exact shape its mode requires, so a missing field would fail to\n * compile rather than post silently as `''`.\n *\n * Every field is read off `fresh` — the SAME snapshot `publicationMode`\n * chose the mode from, which is the only thing that makes the `??` fallbacks\n * below unreachable. Reading the channel ids off `generatedFrom` instead\n * looked equivalent and was not: `handle-approval` hands this node a\n * placeholder snapshot carrying a channel and nothing else, so a `channel`\n * reply built from it would post with empty `toAddress`/`fromAddress` — and\n * the integration's own schema rejects those AFTER the send claim, leaving\n * the row claimed and uncommitted.\n */\nfunction buildReply(mode: PublicationMode, inputs: ReplyInputs): OutboundReply {\n const { draftText, idempotencyKey, fresh, senderEmail } = inputs;\n if (mode === 'whatsapp_note') {\n return {\n mode: 'whatsapp_note',\n // Raw draft text: no markdown-to-HTML rendering (§4.2/§6.4) — the note\n // carries the model's text as-is, the chevron prefix is the adapter's job.\n bodyText: draftText,\n idempotencyKey,\n };\n }\n if (mode === 'channel') {\n return {\n mode: 'channel',\n channel: fresh.sourceChannel ?? '',\n bodyText: draftText,\n bodyHtml: markdownToHtml(draftText),\n // Guaranteed non-null by `publicationMode`, which read THIS snapshot\n // and only returns `'channel'` once both ends are known.\n toAddress: fresh.customerChannelAddress ?? '',\n fromAddress: fresh.accountChannelAddress ?? '',\n receiverName: fresh.customer.name,\n idempotencyKey,\n };\n }\n return legacyEmailReply(draftText, idempotencyKey, fresh, senderEmail);\n}\n\nfunction legacyEmailReply(\n draftText: string,\n idempotencyKey: string,\n fresh: Conversation,\n senderEmail: string,\n): OutboundReply {\n return {\n mode: 'email',\n bodyText: draftText,\n // The draft is markdown; the email channel's HTML body must be rendered,\n // not the raw source.\n bodyHtml: markdownToHtml(draftText),\n subject: fresh.subject,\n fromAddress: senderEmail,\n receiverName: fresh.customer.name,\n // Guaranteed non-null by the `customer_email_missing` gate in `act` —\n // `?? ''` is belt-and-braces for the type, not a real fallback.\n receiverEmail: fresh.customer.email ?? '',\n idempotencyKey,\n };\n}\n","// `runTicket` — the graph's paths and switches (spec §3.3, §6.1, diagram\n// graphe-agent-cible), ported from legacy `agent/graph.ts` per\n// spec-migration-gorgias-backoffice-v1.md §3.3/§3.5.\n//\n// Sequence and switches only (§1): every branch below is code, never an LLM\n// call — the model proposes content, it never decides the sequence.\n//\n// Contract: a run checkpointed with `{until:'triage'}` deliberately does NOT\n// materialise the classification it just produced — see `RunTicketOptions.\n// until` below. The caller owns writing the triage decision and applying\n// tags (§3.5); a caller that drops the returned state loses a paid-for\n// decision. The same gap exists in reverse on a RESUMED run: if `fetchContext`\n// fails after resume, the `failed` exit returns before the injected\n// `resume.classification` is ever merged into state, so it is not\n// materialised either. Both are iso-legacy and harmless today because T22's\n// `triage-tick`/`process-response` persist the decision separately — but\n// they are the same contract, and a future caller that skips that step will\n// silently lose classifications.\nimport type { AgentProfile, Classification, ConversationRef, Verdict } from '../domain';\nimport { requiresFollowup } from '../domain';\nimport { channelPreGates, stopOptOut } from '../guardrails';\nimport {\n hasPublicationPath,\n isAutoSendChannel,\n isAutoSendEligible,\n isSendable,\n needsRevision,\n} from '../verdict/policy';\nimport { act, authorize, draft, escalate, evaluate, fetchContext, guardrails, revise, triage } from './nodes';\nimport type { StatePort } from './ports';\nimport {\n initialState,\n type Node,\n type NodeDeps,\n type NodeName,\n type Outcome,\n type TicketRunState,\n} from './state';\n\nfunction merge(state: TicketRunState, patch: Partial<TicketRunState>): TicketRunState {\n return { ...state, ...patch };\n}\n\n/**\n * Run one node and fold its patch in, telling `deps.trace` what happened when\n * an observer is attached (the admin's graph debugger).\n *\n * With no observer this is the plain call it replaces — production pays\n * nothing. The observer cannot alter the patch or the sequence: a debugged\n * run has to BE the production run, or the page it feeds is fiction. That\n * guarantee is enforced, not just documented — `deps.trace` is handed a\n * `structuredClone` of the patch, so a synchronous observer that mutates\n * what it receives (`s.patch.draft = null`, `s.patch.verdict.verdict =\n * 'hold'`) can never change the object this function actually merges into\n * `state`.\n */\nasync function step(name: NodeName, node: Node, state: TicketRunState, deps: NodeDeps): Promise<TicketRunState> {\n if (!deps.trace) return merge(state, await node(state, deps));\n\n const startedAt = Date.now();\n try {\n const patch = await node(state, deps);\n deps.trace({ node: name, patch: structuredClone(patch), durationMs: Date.now() - startedAt });\n return merge(state, patch);\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n deps.trace({ node: name, patch: {}, durationMs: Date.now() - startedAt, error });\n throw err;\n }\n}\n\n/**\n * Which audit tags an outcome puts on the ticket (§6.1, I20): `ready` = no\n * tag; `needs_human` = needs-review tag; `guardrail_hold` = escalation tag;\n * `sent` = sent tag (+ follow-up tag when `requiresFollowup`);\n * `no_reply_needed` = no tag, like `ready` — kept for rows stored before\n * triage stopped judging the end of a conversation (spec-fin-de-conversation-v1\n * D1); `runTicket` no longer produces it.\n *\n * Split out of `applyOutcomeTags` (21/09/2026) as a PURE list so the ticket\n * timeline can state the tags a run applied without re-deriving them from a\n * hand-copied second table — the same drift `eligibility.ts` documents\n * having been written to avoid. The writer below and the reader in\n * `ui/tickets/ticket-actions.ts` now answer from one source.\n *\n * Order matters and is preserved: `sentTag` before `followupTag`, the order\n * the two `flag` calls were made in.\n */\nexport function outcomeTags(outcome: Outcome, verdict: Verdict | null, audit: AgentProfile['audit']): string[] {\n if (outcome === 'needs_human') return [audit.needsHumanTag];\n if (outcome === 'guardrail_hold') return [audit.escalationTag];\n if (outcome !== 'sent') return [];\n return requiresFollowup(verdict?.verdict ?? null) ? [audit.sentTag, audit.followupTag] : [audit.sentTag];\n}\n\n/**\n * Applies what `outcomeTags` names.\n *\n * Exported (T22 hardening, B1) so `handle-approval` — which reaches `act`\n * DIRECTLY, never through `finish()` below — applies the exact same\n * `sent`/`guardrail_hold` tags `process-response`'s resumed `runTicket` run\n * gets for free. Before this extraction, `handle-approval` had no tag step\n * at all on its own send path: an approved, successfully-sent reply left no\n * `wai/auto-replied` tag on the ticket, silently diverging from §3.6's audit\n * trail. A single shared function is what makes that drift impossible now.\n *\n * Sequential, not `Promise.all`: `StatePort.flag` posts one Gorgias call per\n * tag and the order above is the order they land.\n */\nexport async function applyOutcomeTags(\n outcome: Outcome,\n verdict: Verdict | null,\n deps: { ports: { state: StatePort }; ref: ConversationRef; audit: AgentProfile['audit'] },\n): Promise<void> {\n const { ports, ref, audit } = deps;\n for (const tag of outcomeTags(outcome, verdict, audit)) {\n await ports.state.flag(ref, tag);\n }\n}\n\n/**\n * Writes the run's final state and applies tags by outcome (`applyOutcomeTags`\n * above). The classification itself is materialised whenever one exists,\n * independently of the outcome (I20).\n *\n * Unlike the legacy `finish`, this does NOT write a cost ledger onto the\n * state: `TicketRunState` carries no `costs` field (T17 review) because\n * `deps.budget.ledger()`/`deps.budget.total()` is already the single source\n * of truth for the run's cost — a caller who needs it after the run reads\n * the budget directly instead of through a second, separately-populated copy.\n */\nasync function finish(state: TicketRunState, deps: NodeDeps, outcome: Outcome): Promise<TicketRunState> {\n const final = { ...state, outcome };\n const { audit } = deps.profile;\n\n if (final.classification) await deps.ports.state.record(deps.ref, final.classification, audit);\n await applyOutcomeTags(outcome, final.verdict, { ports: deps.ports, ref: deps.ref, audit });\n return final;\n}\n\n/**\n * Whether triage-time signals alone (no live conversation re-read) mean the\n * sequence would never reach `draft` — `escalated` and the fallback\n * classification are read straight off the triage result, `hasNoDraftNode`\n * off the profile.\n * Exported so `functions/eligibility.ts`'s \"is a `generated-response` worth\n * creating\" check calls the SAME predicates `runTicket` itself branches on,\n * rather than a hand-copied mirror that can silently drift (T22 hardening,\n * E3). The STOP opt-out / WhatsApp pre-gates are deliberately NOT part of\n * this set — both need a fresh conversation read `triage-tick` doesn't pay\n * for at classification time (`eligibility.ts`'s own doc).\n */\nexport function isFallbackClassification(classification: Classification | null): boolean {\n return classification?.isFallback === true;\n}\n\nexport function hasNoDraftNode(profile: Pick<AgentProfile, 'nodes'>): boolean {\n return !profile.nodes.draft;\n}\n\n/**\n * Resume point. §3.5 keeps TWO workers/functions: `triage-tick` classifies a\n * ticket and hands off, `process-response` picks it up later. Persisting\n * `TicketRunState`'s classification/escalated flag and re-entering here with\n * `resume` set is how the second run avoids re-classifying — which would\n * both cost a second LLM call and risk re-escalating a ticket that already\n * passed.\n */\nexport interface ResumeFrom {\n classification: TicketRunState['classification'];\n escalated: boolean;\n}\n\n/**\n * How far `runTicket` is allowed to go this call. The only value today,\n * `'triage'`, names the LAST phase the run may complete — triage AND\n * escalate, escalate being folded into the same phase (§3.3's own\n * sequencing keeps the two together, never a decision point on their own) —\n * so there is no adjacent value (\"before escalate\"?) to misread this as: the\n * run either completes the triage phase in full, or (when this option is\n * absent) keeps going to a terminal outcome.\n */\nexport type RunUntil = 'triage';\n\nexport interface RunTicketOptions {\n resume?: ResumeFrom;\n /**\n * Stop right after triage + escalate, before any exit check or `draft`.\n * `triage-tick` (§3.5) uses this to persist the triage decision without\n * ever paying for a draft `process-response` may not need. The returned\n * state carries no `outcome` and no tag was written — `finish` runs on the\n * LATER, resumed call instead, once the full sequence below decides one.\n *\n * This is a DELIBERATE non-materialisation, not an oversight: a\n * checkpointed run never calls `ports.state.record`, so the classification\n * it just paid for is only held in the returned `TicketRunState`, nowhere\n * else. §3.5 assigns writing it down to the CALLER — `triage-tick` runs\n * `runTicket(deps, {until:'triage'})`, applies the deduplicated tags,\n * writes the `triage-decision` record, then creates the `generated-response`\n * if eligible. A caller that drops this returned state (crash, unhandled\n * rejection, a resumed call that never happens) loses a paid-for LLM\n * decision with nothing left to reconstruct it from.\n */\n until?: RunUntil;\n}\n\nexport async function runTicket(deps: NodeDeps, options: RunTicketOptions = {}): Promise<TicketRunState> {\n const { profile } = deps;\n const { resume, until } = options;\n let s = initialState();\n\n // The conversation is always re-read, even on resume: the reply worker runs\n // minutes after triage and every downstream check wants what is true now.\n s = await step('fetchContext', fetchContext, s, deps);\n if (s.outcome === 'failed') return finish(s, deps, 'failed');\n\n if (resume) {\n s = merge(s, { classification: resume.classification, escalated: resume.escalated });\n } else {\n s = await step('triage', triage, s, deps);\n if (profile.nodes.escalate) s = await step('escalate', escalate, s, deps);\n }\n if (until === 'triage') return s;\n\n if (s.escalated) return finish(s, deps, 'escalated');\n // Whatsapp spec §5.1 — the STOP opt-out outranks EVERY other exit below.\n // A customer who writes \"STOP\" has almost certainly also closed the\n // conversation, and a quiet exit would leave the opt-out with no trace at\n // all. §5.1 asks for the opposite — a hold plus the escalation tag, so a\n // human records the refusal of contact. Consent is the one signal here\n // that must never be silent (and the end-of-conversation step never\n // reaches a STOP, spec-fin-de-conversation-v1 D17).\n const stopHits = s.conversation ? stopOptOut(s.conversation) : [];\n if (stopHits.length) return finish(merge(s, { guardrailHits: stopHits }), deps, 'guardrail_hold');\n // Nothing to draft a reply to (§6.4's fetchContext/triage nuance): tag and stop.\n if (isFallbackClassification(s.classification)) return finish(s, deps, 'triaged_only');\n if (hasNoDraftNode(profile)) return finish(s, deps, 'triaged_only');\n\n // Whatsapp spec §5.3 (lot W2): not-our-turn, checked HERE, before drafting\n // even starts — not only inside the `guardrails` node below, which only\n // runs once auto-send is otherwise eligible (`isAutoSendEligible`). A\n // `draft_only` tenant — where an operator lands the moment they flip the\n // WhatsApp switch, §9.2 — has `autoSend` disabled and would never reach\n // that node at all, so without this early check the rule would never fire\n // for the very configuration this lot ships. Checking here also buys §5's\n // economics: the ticket must not pay for a draft it will never send, the\n // same reason the sibling STOP gate sits above.\n //\n // The pre-existing `whatsapp` (`escalate_only`) hit does NOT move here —\n // see the comment on it in `nodes/guardrails.ts` for why moving it would\n // break iso-behaviour.\n if (s.conversation) {\n const preGateHits = channelPreGates(s.conversation);\n if (preGateHits.length) return finish(merge(s, { guardrailHits: preGateHits }), deps, 'guardrail_hold');\n }\n\n s = await step('draft', draft, s, deps);\n if (profile.nodes.evaluate) {\n s = await step('evaluate', evaluate, s, deps);\n // send_and_escalate is SENDABLE (I6): it never triggers a revision.\n if (needsRevision(s.verdict, profile, s.reviseCount)) {\n s = await step('revise', revise, s, deps);\n s = await step('evaluate', evaluate, s, deps);\n }\n if (!isSendable(s.verdict, profile)) return finish(s, deps, 'needs_human');\n }\n // Nominal service-to-extension path: draft ready, no auto-send requested\n // (or possible) → `ready`, NO tag (I20) — silence is what tells an agent\n // nothing is wrong. A tenant with `evaluate: null` always lands here too:\n // with no verdict, auto-send is impossible by construction.\n if (!isAutoSendEligible(s, deps)) return finish(s, deps, 'ready');\n\n s = await step('guardrails', guardrails, s, deps);\n if (s.guardrailHits.length) return finish(s, deps, 'guardrail_hold');\n\n // The operator has not authorised auto-send on this channel\n // (`autoSendChannels`). Checked after the guardrails, like the path\n // question below, so an unchecked channel keeps its escalations.\n if (!isAutoSendChannel(s, deps)) return finish(s, deps, 'ready');\n // No way to publish a reply here at all (`verdict/policy.ts`'s own doc for\n // why this is not folded into `isAutoSendEligible` above): Gorgias does not\n // declare the channel answerable, or an email-mode contact has no address.\n // `ready` + no tag, like every other \"auto-send does not apply\" exit — the\n // draft is still served to an agent, who is the one such a ticket was\n // always going to need.\n //\n // Checked HERE, after the guardrails, so those keep their say on the very\n // channels this exit covers: a blocklisted term on an Instagram thread\n // must still raise `guardrail_hold` and its escalation tag.\n if (!hasPublicationPath(s)) return finish(merge(s, { ineligibleReason: 'no_publication_path' }), deps, 'ready');\n\n s = await step('authorize', authorize, s, deps);\n // Default deny (§6.4): anything but an explicit 'auto' stops before acting.\n if (s.proposedActions.some((a) => a.decision !== 'auto')) return finish(s, deps, 'awaiting_approval');\n\n s = await step('act', act, s, deps);\n // `act`'s anti-collision checks (I8) land in the SAME `guardrailHits` the\n // pre-flight `guardrails` node uses — this call started empty, so any hit\n // here is act's own.\n return finish(s, deps, s.guardrailHits.length ? 'guardrail_hold' : 'sent');\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.3 (`status/machine.ts`),\n// §3.4 (`generated-response`'s own transition list).\n//\n// New module — no legacy equivalent. The legacy enforced \"one open job per\n// ticket\" and \"no re-sending a sent reply\" with a Mongo partial unique index\n// plus scattered `findOneAndUpdate` guards scattered across the worker and\n// the sweep. Here that becomes one explicit table plus the `openTicketKey`\n// unique index (§3.4) and S5's `ifMatch` at the claim site (T22) — this\n// module is the single source of truth both of those lean on.\n//\n// `assertTransition` is a LOCAL, in-process invariant check: it catches a\n// caller asking for a transition the machine never allows (e.g. code trying\n// to move a `sent` record anywhere) before a single write is attempted. It\n// is deliberately NOT the same failure mode as a lost `ifMatch` race — two\n// workers racing to claim the same `ready` record both ask for a transition\n// this module allows (`ready -> sending`); which one wins is decided by the\n// data API's conditional write, not by this module. T22's claim path should\n// call `assertTransition` first (fail fast on a nonsensical local state) and\n// treat the `ifMatch` conflict as a separate, expected \"someone else claimed\n// it first\" outcome.\n\n/** The `generated-response` record's `status` field (§3.4). */\nexport const GENERATED_RESPONSE_STATUSES = [\n 'pending',\n 'ready',\n 'sending',\n 'sent',\n 'failed',\n 'no_reply_needed',\n 'invalidated',\n 'expired',\n // 24/09/2026 — where \"générer sans envoyer\" rests its draft. It used to\n // finalize as `invalidated`, which the ticket page and the dashboard both\n // read as \"an agent had already answered\": the test artefact was stored,\n // but disguised as a human intervention. Terminal on purpose — nothing may\n // serve, send or revive a test draft — and terminal is also what frees the\n // `openTicketKey` (see `openTicketKeyFor`), so an essay can never hold the\n // real webhook at G9.\n 'test_draft',\n // 24/09/2026 — where a draft goes when a newer customer message arrives\n // before it was sent. The follow-up webhook used to refuse the new message\n // instead (G9 stopped on \"une réponse est déjà ouverte\"), which lost it\n // outright: Gorgias never replays a webhook it acked. The row is closed and\n // the pass drafts again, so the customer's latest message always wins.\n //\n // NOT `invalidated`, for the reason `test_draft` was split off it: the ticket\n // page and the dashboard read `invalidated` as \"a human intervened\", and a\n // draft replaced by a fresher one is nobody's intervention. Terminal, which\n // is also what releases `openTicketKey` (see `openTicketKeyFor`) — without\n // that release the replacement draft could not be created at all.\n 'superseded',\n] as const;\n\nexport type GeneratedResponseStatus = (typeof GENERATED_RESPONSE_STATUSES)[number];\n\n/**\n * `status` lives in `AppRecord` JSONB (§3.4), so it reaches this module as an\n * untrusted string: a record written by another app version, or hand-edited,\n * can carry anything. Parse at that boundary rather than dereferencing the\n * transition table blindly — same reason `domain/evaluation-verdict.ts` ships\n * `isEvaluationVerdict`.\n */\nexport function isGeneratedResponseStatus(value: unknown): value is GeneratedResponseStatus {\n return (\n typeof value === 'string' &&\n (GENERATED_RESPONSE_STATUSES as readonly string[]).includes(value)\n );\n}\n\n/**\n * Exactly the pairs §3.4 lists: `pending->ready|failed|no_reply_needed|sending`;\n * `sending->sent|ready` (the sweep's own reclaim); `ready->sending|invalidated|expired`.\n * Every other status has no outgoing transition at all — it is terminal.\n *\n * Two pairs were added since, each documented where it is declared:\n * `pending->test_draft`/`*->superseded` on the statuses themselves. The third,\n * `pending->invalidated` (16/09/2026), is argued here because it widened the\n * machine rather than extended it. §3.4\n * left `pending` un-invalidatable because it is a TRANSIENT mid-run state —\n * true while the run that opened it is alive, false the moment that process\n * dies (a deploy, an OOM, a killed socket): nothing then ever revisits the\n * row, its `openTicketKey` keeps the ticket locked, and every later tick\n * re-triages the ticket only to 409 on the create and abandon it, until the\n * sweep's TTL pass — `responseTtlMinutes` days later. The operator needs a\n * way out that does not involve waiting for that. Yanking a genuinely\n * in-flight row stays safe without a second guard here: every writer on the\n * live path claims with `ifMatch`, so either the invalidation lands and the\n * run abandons on its own 409, or the run wins and the invalidation is\n * refused — never both.\n */\nconst ALLOWED_TRANSITIONS: Record<GeneratedResponseStatus, readonly GeneratedResponseStatus[]> = {\n // `pending -> test_draft` is the ONLY way in: the test pass finalizes the\n // very `pending` row it opened, and no other status can become a test\n // draft after the fact — an operator invalidating a real `ready` draft is\n // expressing \"discard this\", not \"this was an essay\".\n pending: ['ready', 'failed', 'no_reply_needed', 'sending', 'invalidated', 'test_draft', 'superseded'],\n ready: ['sending', 'invalidated', 'expired', 'superseded'],\n // `sending` reaches neither `invalidated` nor `superseded`, and for the same\n // reason: a worker holds the send lock, so nobody yet knows whether the\n // customer received anything. Closing that row would strand the send — the\n // sweep could no longer reclaim it, and `sentMessageId` would never be\n // written. A follow-up pass that meets one waits for it instead.\n sending: ['sent', 'ready'],\n sent: [],\n failed: [],\n no_reply_needed: [],\n invalidated: [],\n expired: [],\n test_draft: [],\n superseded: [],\n};\n\nexport function canTransition(from: GeneratedResponseStatus, to: GeneratedResponseStatus): boolean {\n // Defensive on `from`: an unknown status must be \"no legal transition\", not\n // a TypeError thrown from inside the send path.\n if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;\n return ALLOWED_TRANSITIONS[from].includes(to);\n}\n\n/**\n * Whether an operator may discard this response to free its ticket for a\n * full re-treatment — derived from the table above rather than restated, so\n * the button that offers the action and the handler that performs it cannot\n * disagree about which rows qualify.\n *\n * `sending` is the one open status excluded, and deliberately: its reply may\n * ALREADY have been posted to the customer, which is `sweep`'s stalled-send\n * reclaim to resolve, not a human's to guess at.\n */\nexport function isInvalidatableStatus(status: GeneratedResponseStatus): boolean {\n return canTransition(status, 'invalidated');\n}\n\n/** A status with no outgoing transition — nothing may ever move it again. */\nexport function isTerminalStatus(status: GeneratedResponseStatus): boolean {\n if (!isGeneratedResponseStatus(status)) return false;\n return ALLOWED_TRANSITIONS[status].length === 0;\n}\n\nexport class InvalidStatusTransitionError extends Error {\n readonly from: GeneratedResponseStatus;\n readonly to: GeneratedResponseStatus;\n\n constructor(from: GeneratedResponseStatus, to: GeneratedResponseStatus) {\n super(`generated-response: illegal status transition \"${from}\" -> \"${to}\"`);\n this.name = 'InvalidStatusTransitionError';\n this.from = from;\n this.to = to;\n }\n}\n\n/** Throws {@link InvalidStatusTransitionError} unless `canTransition(from, to)`. */\nexport function assertTransition(from: GeneratedResponseStatus, to: GeneratedResponseStatus): void {\n if (!canTransition(from, to)) throw new InvalidStatusTransitionError(from, to);\n}\n\n/**\n * §3.4: `openTicketKey` equals the ticket id while the record is still open\n * (`pending`, `ready`, `sending`), and is cleared in a terminal status — the\n * Postgres-unique-index equivalent of the legacy \"one open job per ticket\"\n * guarantee (NULLs are distinct under a unique index, so clearing the key\n * frees the ticket for a fresh `pending` record).\n *\n * Derived from `isTerminalStatus` rather than a second hardcoded status set:\n * \"open\" and \"terminal\" are already the same partition this module tracks\n * for transitions, and duplicating that partition here is exactly the kind\n * of drift this module exists to prevent.\n */\nexport function openTicketKeyFor(status: GeneratedResponseStatus, ticketId: string): string | null {\n return isTerminalStatus(status) ? null : ticketId;\n}\n\n/**\n * The sweep's `sending -> ready` reclaim (§3.5), as a patch rather than a bare\n * status.\n *\n * The \"**jamais de ré-émission**\" promise is carried by `autoSendDecision`,\n * NOT by the status: a record back at `ready` *without* the hold is a\n * perfectly legal claim target for `act`/`handle-approval` via\n * `ifMatch:{status:'ready'}`, so a sweep that sets the status and forgets the\n * flag re-sends the reply — the one outcome §3.5 forbids in bold, and one\n * `assertTransition('sending','ready')` would happily wave through. Deriving\n * the pair here means T22 cannot express the reclaim without the hold.\n */\nexport function reclaimStalledSend(): {\n status: Extract<GeneratedResponseStatus, 'ready'>;\n autoSendDecision: 'hold';\n} {\n return { status: 'ready', autoSendDecision: 'hold' };\n}\n","/**\n * Slot → Langfuse prompt name resolution (spec §3.7).\n *\n * Every kit slot resolves to a Langfuse name via `config.promptNames`\n * (explicit override) or else `<promptPrefix><slot>` — D-LF: no namespacing,\n * no migration, the resolved name is used against the legacy Langfuse\n * project's prompts exactly as they already exist.\n *\n * `experience-client` passes `promptPrefix: ''`, so its slots resolve to the\n * bare legacy names (`triage`, `escalation`, `shared/style-email`, …) with\n * zero Langfuse writes at migration time. A later audience (`pro-sante`)\n * passes `promptPrefix: 'pro-sante/'`, reproducing the legacy's own\n * multi-tenant `<key>/<node>` convention.\n */\n\n/** The seven kit slots §3.7 names. Agent prompts (`agent.promptName`) are NOT a slot — they live on the `agent` record, resolved by its own `PromptRef`, never through this table. */\nexport const PROMPT_SLOTS = [\n 'triage',\n 'escalation',\n 'evaluation',\n 'suggest',\n 'diff-analysis',\n 'shared/style-email',\n 'shared/style-whatsapp',\n] as const;\n\nexport type PromptSlot = (typeof PROMPT_SLOTS)[number];\n\n/**\n * The keys `config.defaults.prompts` actually honours (M7, T25 review) —\n * deliberately NOT `PromptSlot`: `shared/style-email`/`shared/style-whatsapp`\n * are two `PromptSlot`s nothing ever reads a fallback for (they resolve by\n * bare NAME off the settings fields' own defaults, never through a\n * `PromptRef.fallback`), so accepting them here silently drops whatever a\n * caller sets. `revise` is NOT a key either: that step re-runs the writer\n * with a fixed correction turn (`graph/revise.ts`), so it resolves no\n * prompt of its own to fall back for.\n */\nexport type PromptFallbackSlot = Exclude<PromptSlot, 'shared/style-email' | 'shared/style-whatsapp'>;\n\nexport interface PromptNameConfig {\n /**\n * Required, not defaulted (H3, T25 review): §4's checklist for a new\n * audience always passes it explicitly (`promptPrefix: '<slug>/'`), and\n * `experience-client` must say `promptPrefix: ''` out loud rather than\n * omit the field — an omission used to resolve every slot to the BARE\n * legacy name (`triage`, not `pro-sante/triage`), silently pointing a new\n * audience's triage/escalation/evaluation at experience-client's live\n * production prompts, with no error to reveal the mistake (the allowlist\n * is derived from the same default, so nothing 403s either).\n */\n promptPrefix: string;\n promptNames?: Partial<Record<PromptSlot, string>>;\n /**\n * §3.2's `config.defaults.prompts` — the level-3 in-code fallback TEXT\n * (`PromptRef.fallback`, §3.7 point 3) a caller can override per slot,\n * read by `buildPromptsTable` (triage/escalation/evaluation) and\n * by `suggest-prompt`/`run-diff-analysis`'s own meta-prompt constants\n * (`suggest`/`diff-analysis`). Typed as `PromptFallbackSlot`, not\n * `PromptSlot` (M7): the accepted key set must match what is actually\n * honoured in both directions, not just default to every §3.7 slot name.\n */\n defaults?: { prompts?: Partial<Record<PromptFallbackSlot, string>> };\n}\n\n/** Resolve one slot to its Langfuse prompt name for a given `buildSupportPipeline` config. */\nexport function resolvePromptName(slot: PromptSlot, config: PromptNameConfig): string {\n return config.promptNames?.[slot] ?? `${config.promptPrefix}${slot}`;\n}\n","/**\n * Stable per-record keys for the kit's own records, fields and indexes (spec\n * §3.4). Generated once and committed — do NOT regenerate them, per the same\n * convention as `docs/app-template/src/universal-identifiers.ts`: a kit\n * fragment consumed by an app is diffed/reconciled by these ids, not by\n * field name, so changing one here would read to the platform as \"delete\n * field X, add unrelated field Y\".\n *\n * These are NOT the final manifest `universalIdentifier`s written by any\n * consuming app — `buildSupportKitRecords` (records/index.ts) additionally\n * scopes every one of them to the consuming app's slug via\n * `scopeRecordToApp`/`deriveUid` (B1, T25 review), because\n * `AppEntity.universalIdentifier` is unique platform-wide, not per\n * application: two different apps installing this kit must never publish\n * the same value.\n */\nexport const CATEGORY_OBJECT_UID = '8a1c8de3-c288-40a5-9294-a883e1c89784';\nexport const CATEGORY_GROUP_OBJECT_UID = '71ed9161-838a-431b-886c-b99d8a9099a6';\nexport const AGENT_OBJECT_UID = '47c3b216-c5b2-49bb-b1d9-e87db60b7c02';\nexport const TRIAGE_DECISION_OBJECT_UID = 'e6483697-b3ab-424e-b070-a572ad74f899';\nexport const GENERATED_RESPONSE_OBJECT_UID = '367263bd-438d-4cec-8cd7-14f9e0dc780a';\nexport const RESPONSE_COMPARISON_OBJECT_UID = 'a349d47c-fe21-4e09-9475-979f69fbab88';\nexport const EVALUATION_OBJECT_UID = '8a73e22c-d814-47ba-a4ae-f2ca8fff1f35';\nexport const DIFF_ANALYSIS_OBJECT_UID = '7ebb67c3-0f0a-4987-b320-0672a877bb0d';\nexport const PIPELINE_STATE_OBJECT_UID = '812c8498-736c-43bd-8a86-5a979940351e';\nexport const PROMPT_CACHE_OBJECT_UID = 'c01e6c2b-461b-4c3d-8de3-424478457fc5';\nexport const CATEGORY_FIELD_NAME_UID = 'a688aa9e-3cb9-49f6-bc15-07caf0cad481';\nexport const CATEGORY_FIELD_TAG_NAME_UID = '4df1f653-8e24-45cb-acf9-dcb293c3a110';\nexport const CATEGORY_FIELD_ORDER_UID = '25e85490-f365-4d28-98cd-87f93b24f653';\nexport const CATEGORY_FIELD_GROUP_ID_UID = '667697a4-9877-4df7-9b41-86e60b8b0039';\nexport const CATEGORY_FIELD_AGENT_ID_UID = '96e36d98-537c-4db1-ab84-2bb3c188b078';\nexport const CATEGORY_FIELD_EXTRA_TAGS_UID = '8673a239-1a7d-4e4f-b951-b6c5c9d4787e';\nexport const CATEGORY_FIELD_DESCRIPTION_UID = 'fa2aeb51-47b0-4c26-845a-0b9f543f0c89';\nexport const CATEGORY_FIELD_EXAMPLES_UID = '39e52ad6-34b1-4151-a70b-7f996648b9b0';\nexport const CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID = '4fa75e78-b826-4741-9612-b6cf28bde9f9';\nexport const CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID = 'c6822551-821f-4255-b220-be40c9b56052';\n/**\n * spec-gorgias-followup-webhook-v1 §7.1 — the follow-up opt-in, the exact\n * mirror of the `fastResponseEnabled`/`autoReplyEnabled` pair above. Freshly\n * generated, never reused: a consuming app reconciles a kit fragment by these\n * ids, so recycling one would read to the platform as a field RENAME.\n */\nexport const CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID = '6ea5d15b-166e-4c29-8555-844bd7f6193e';\nexport const CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID = '81804963-6ffb-486c-a663-6287353adff5';\nexport const CATEGORY_INDEX_TAG_NAME_UID = '5463dac5-715d-4545-ad75-905477d868eb';\nexport const CATEGORY_INDEX_NAME_UID = '2eda6e49-387a-4e08-94a8-06250652692d';\nexport const CATEGORY_INDEX_ORDER_UID = 'bf4b1f9c-2dc8-4480-8fcb-dba789e8fe62';\nexport const CATEGORY_GROUP_FIELD_NAME_UID = '5feee22b-95dd-4c30-87ea-68a6fd5c4e7a';\nexport const CATEGORY_GROUP_FIELD_ORDER_UID = '975be023-fa11-4168-9a7d-e24b03f7a60e';\nexport const CATEGORY_GROUP_INDEX_NAME_UID = 'e3b2e5cb-9c3a-4824-8b0e-32a9abfed4fd';\nexport const AGENT_FIELD_NAME_UID = 'e9cfec6f-15c6-4d02-8f79-0667f64b9eb5';\nexport const AGENT_FIELD_PROVIDER_UID = 'e522b809-e8a7-4439-a2df-936158d04389';\nexport const AGENT_FIELD_MODEL_ID_UID = 'd95977ba-362c-44d6-a2f0-24156c76cf8a';\nexport const AGENT_FIELD_STATUS_UID = '348725a0-a896-4f8d-8a56-86f4193234a8';\nexport const AGENT_FIELD_DEFAULT_KEY_UID = '0134491a-c969-4c42-894c-36ad4880fed3';\nexport const AGENT_FIELD_PROMPT_NAME_UID = '32e7f234-00bb-44d2-917b-be28f32f7214';\nexport const AGENT_FIELD_PROMPT_LABEL_UID = 'bdee53ff-571a-4df6-91ec-00b513a70fe0';\nexport const AGENT_FIELD_PROMPT_VERSION_UID = 'e7c66f99-e1e0-4fc2-9f9e-3bafe3af8e88';\nexport const AGENT_FIELD_SYSTEM_PROMPT_SNAPSHOT_UID = '710b73c6-929b-48b7-abc0-792849adf1c2';\nexport const AGENT_FIELD_REASONING_EFFORT_UID = 'aa57fc6e-c989-47d3-9fc8-e04184b1e67c';\nexport const AGENT_FIELD_MAX_TOOL_CALLS_UID = '6948a5ca-48ef-45d7-9118-c7ab195343a3';\nexport const AGENT_INDEX_DEFAULT_KEY_UID = '084db2ee-6aae-4b92-af6c-ed9c8dfda075';\nexport const TRIAGE_DECISION_FIELD_TICKET_ID_UID = 'c3df59f1-248f-4396-aa70-7d6ada5edec7';\nexport const TRIAGE_DECISION_FIELD_DECIDED_AT_UID = '8048f69b-2cfe-45e4-9be9-b6d667e92021';\nexport const TRIAGE_DECISION_FIELD_CATEGORY_ID_UID = '1a9f8b77-219b-4b73-935c-620cb228491f';\nexport const TRIAGE_DECISION_FIELD_TAG_UID = 'd8e814b8-d4ac-4cd4-9892-b27e19c66e20';\nexport const TRIAGE_DECISION_FIELD_CONFIDENCE_UID = '9fb1be7b-f697-455f-a7d0-a0e00f8cf634';\nexport const TRIAGE_DECISION_FIELD_REASONING_UID = '75716a98-d430-4c42-ad82-cdf091d8ebf2';\nexport const TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID = '60ffd534-7cda-497e-8b8f-6b6b10de70c1';\nexport const TRIAGE_DECISION_FIELD_ESCALATED_UID = 'dd8384af-b3d1-48af-a883-8e9f0655960c';\nexport const TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID = 'ebdf3a2d-17f7-4da6-a1c4-d0c35febf879';\nexport const TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID = 'd07aa556-b417-479b-a30b-fd29d51ff9e3';\nexport const TRIAGE_DECISION_FIELD_STATUS_UID = '7583d228-4449-40ef-9e7e-44e34897e020';\nexport const TRIAGE_DECISION_FIELD_ERROR_UID = 'b271362b-a1b3-4110-a197-0b7a2ec6b152';\nexport const TRIAGE_DECISION_FIELD_RUN_ID_UID = 'a1e244d6-8f4f-4cd5-8794-14f6e419b64e';\nexport const TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID = '449f1960-be88-4e42-96ee-43cd90f36f4c';\nexport const TRIAGE_DECISION_FIELD_TICKET_URL_UID = '727a775a-ea93-460f-9d08-16b05424c453';\n/** spec-gorgias-followup-webhook-v1 §7.2 — which pass wrote this row (`triage` | `followup`). */\nexport const TRIAGE_DECISION_FIELD_ORIGIN_UID = '8bde8d93-7d06-4cb5-8a88-2d6db562af05';\n/** spec-mcp-service-client-v1 D11 — the Langfuse trace of the triage call. */\nexport const TRIAGE_DECISION_FIELD_LANGFUSE_TRACE_ID_UID = '39fcbbd2-2d18-48db-b096-589f8072f854';\n/** spec-mcp-service-client-v1 D11 — the observation ids of the triage and escalation calls. */\nexport const TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_UID = '15451c73-9f6d-4899-96ca-8fd3f5eb93db';\nexport const TRIAGE_DECISION_INDEX_TICKET_ID_UID = '20433066-e029-4faf-8033-c205cf5de0fb';\nexport const TRIAGE_DECISION_INDEX_DECIDED_AT_UID = '94040f6d-1d55-498f-8db8-abe5aed17c0a';\nexport const TRIAGE_DECISION_INDEX_ESCALATED_UID = '1c0ac4c3-9a48-4858-bbbf-0c689bbb5be5';\nexport const GENERATED_RESPONSE_FIELD_TICKET_ID_UID = '5e4cc51f-a22d-4772-8c81-287baa51fa25';\nexport const GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID = 'a05b435a-e297-476b-9147-42dd7e69f5bd';\nexport const GENERATED_RESPONSE_FIELD_STATUS_UID = '674975e4-d61f-4b4c-9e70-5b4a9133cd0d';\nexport const GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID = 'fdb4a0fb-9d78-4758-b9aa-e420b854d277';\nexport const GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID = '8710988e-9409-4632-83b5-4bb6609cd384';\nexport const GENERATED_RESPONSE_FIELD_AGENT_ID_UID = 'be4d2c06-5108-467a-89fb-24212c82801d';\nexport const GENERATED_RESPONSE_FIELD_CHANNEL_UID = '4fc8cd40-3e59-4da8-a981-81171da4323a';\nexport const GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID = '917926c0-38c6-48b8-835e-922f539777bc';\nexport const GENERATED_RESPONSE_FIELD_SOURCES_UID = '99774717-7a7b-454a-b384-c4f5c8770079';\nexport const GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID = '3b6540dd-2532-4ef3-99a9-9539bf3ac743';\nexport const GENERATED_RESPONSE_FIELD_VERDICT_UID = 'b727b513-77c9-4414-a3c3-282ff1e3712c';\nexport const GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID = '2b010fe3-949f-45f9-9547-a3f5425dc849';\nexport const GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID = 'aa050341-446d-448b-a83f-30bccd328962';\nexport const GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID = 'c598a05b-7354-4445-b114-a4e6e388f965';\nexport const GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID = 'd5c4f8c3-316e-4a53-a9c8-b3bf1e367620';\nexport const GENERATED_RESPONSE_FIELD_SERVED_TO_UID = 'a744d0c8-61ed-4869-ad53-2aab2505ae3f';\nexport const GENERATED_RESPONSE_FIELD_GENERATED_AT_UID = '229ab5da-a68e-49eb-85d4-7fab7941dca0';\nexport const GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID = '6d2fc2f8-16d7-4eed-b307-41972caea350';\nexport const GENERATED_RESPONSE_FIELD_SENT_AT_UID = 'a35c9745-e4bf-4dc2-9e70-1aad4649a112';\nexport const GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID = '65b0ae06-32a7-4938-9464-b31bdb4cdf26';\nexport const GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID = 'c107c692-ec5e-47f6-8fcc-e0817c22ebf9';\nexport const GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID = '789c0773-63ce-4536-b1a0-e182feefd529';\nexport const GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID = 'ffab81da-3764-4aba-969e-1a5030fb0a92';\nexport const GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID = 'aa91867a-41c4-4ebe-ba7a-0baeeb82f9c5';\nexport const GENERATED_RESPONSE_FIELD_ERROR_UID = '40994b59-75f0-4c84-8a8a-a8d3c6cc2b09';\n// T22 additions — see records/generated-response.ts's own doc for why these\n// three exist (act's `generatedFrom` divergence baseline + the sweep's\n// stalled-send staleness check). Freshly generated, never reused.\nexport const GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID = '33a282d3-7a1c-45a3-945e-a39ea459c5f8';\nexport const GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID = '94c4594f-4ad0-4e3b-8a0b-76402b437434';\nexport const GENERATED_RESPONSE_FIELD_SENDING_AT_UID = '2ae9634b-79bb-42d2-a949-8b0f1ac9c763';\n// 21/09/2026 — `outcome` records WHICH exit `runTicket` took, because\n// `status` alone cannot: `ready` covers four different exits (`ready`,\n// `needs_human`, `guardrail_hold`, `awaiting_approval`) and the ticket\n// timeline has to tell them apart to name the tags that were applied.\nexport const GENERATED_RESPONSE_FIELD_OUTCOME_UID = '8834b334-8f91-46f7-9bb9-96b69092d0ae';\n/** spec-gorgias-followup-webhook-v1 §7.2 — the twin of the decision's own marker; §7.3 reads it to pick which auto-reply flag governs the send. */\nexport const GENERATED_RESPONSE_FIELD_ORIGIN_UID = 'e75034d3-ee7f-40e7-b4fe-8be7b4322bdc';\n// 24/09/2026 — the record half of the run⇄draft cross-reference: the follow-up\n// run's result names `responseId`, this field answers back. The decision\n// already carried its `runId`; the response is what the operator actually\n// reads, so it needed the same provenance.\nexport const GENERATED_RESPONSE_FIELD_RUN_ID_UID = 'f3448bca-9c59-418f-9509-ce0e43eb8768';\n// 28/09/2026 — `guardrailHits` was declared long before anything wrote it, so\n// every hold older than that fix carries `[]`. The backfill that rebuilds\n// those reasons from Gorgias stamps this field, because a reason DEDUCED\n// today from today's settings is not the same claim as a reason RECORDED by\n// the run that made the decision, and the timeline must not present the two\n// the same way.\nexport const GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID = 'b4db88de-b712-4713-9fe6-659a5563f4d2';\n// 28/09/2026 — `channel` has never been the channel: it is\n// `sourceChannel === 'whatsapp' ? 'whatsapp' : 'email'`, i.e. the PUBLICATION\n// MODE act picks. That binary is what sent Instagram threads down the email\n// branch. This field carries the channel Gorgias actually reported, so the\n// ticket page can name it and `autoSendChannels` can be audited against it.\nexport const GENERATED_RESPONSE_FIELD_SOURCE_CHANNEL_UID = '0a05be96-0d3e-42f0-9153-4f2ee3cf7859';\n// 28/09/2026 — the one thing the ticket timeline cannot re-derive: whether\n// the contact had an address to send to. Every other \"not sent\" reason is\n// readable from today's settings; this one is a fact about a customer six\n// weeks ago, which nothing on the row otherwise records.\nexport const GENERATED_RESPONSE_FIELD_INELIGIBLE_REASON_UID = '2fd5c90b-e8f4-480c-b040-189e4b1935fc';\nexport const GENERATED_RESPONSE_INDEX_TICKET_ID_UID = 'a4534d26-8f43-4510-9c03-0b28c3d3f8e2';\nexport const GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID = '3d430166-07a2-43c2-911b-89ec25d13f64';\nexport const GENERATED_RESPONSE_INDEX_STATUS_UID = 'f5c4e5d4-0810-424d-8a14-617e9555a7f3';\nexport const GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID = '576b670e-7351-4867-bd5b-45df97bb26f0';\nexport const GENERATED_RESPONSE_INDEX_GENERATED_AT_UID = '4f4ffdb2-c690-407a-bb4f-f82240d6c49f';\nexport const GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID = '311d793a-0c21-45d4-85fa-76d3e48a5cfa';\nexport const RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID = '44ca17c2-6cf2-4008-81e3-d7d5ccf3ab4d';\nexport const RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID = 'a2877acd-1521-49b3-98a3-8a112e6f6adf';\nexport const RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID = 'ab66db96-027e-4f10-8c05-19c9714fa668';\nexport const RESPONSE_COMPARISON_FIELD_TICKET_ID_UID = 'befa0d7f-6c54-403e-bbfe-55dabe305ada';\nexport const RESPONSE_COMPARISON_FIELD_TICKET_URL_UID = '137d66e9-c0b2-40b8-809f-e384b06ded8c';\nexport const RESPONSE_COMPARISON_FIELD_AGENT_ID_UID = '9c968f5f-9f0e-439d-bef1-2189e95c16f6';\nexport const RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID = '2297cb14-6a69-457a-9f73-440b8c54c773';\nexport const RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID = '96461793-0636-4d0d-997f-0bec2870237c';\nexport const RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID = '9142e145-2245-419f-bf46-224dcfe4d946';\nexport const RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID = '6fb501a7-dbbc-41ff-b97f-8afdbdfab3a1';\nexport const RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID = '90695301-55fc-4a85-b998-7433cd1e1c8c';\nexport const RESPONSE_COMPARISON_FIELD_DIFF_UID = '8333eade-5440-4e75-a2b3-d5d55a6af706';\nexport const RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID = 'c5d87db7-7983-4fcc-bf6d-6e61d9ad5b9e';\nexport const RESPONSE_COMPARISON_INDEX_TICKET_ID_UID = 'ccfbe23d-447d-4488-ae4d-3b9c63a917f7';\nexport const EVALUATION_FIELD_AGENT_ID_UID = '4bdde88b-1e83-4df3-986a-f141b4cf0ebe';\nexport const EVALUATION_FIELD_SATISFIED_UID = '9df4c966-954b-4ffa-941d-954102048607';\nexport const EVALUATION_FIELD_MESSAGES_UID = '85aaf232-11de-4916-959b-a4d4833a6d7b';\nexport const EVALUATION_FIELD_TICKET_URL_UID = 'fcf28597-ecce-4f40-9564-0144fecb0273';\nexport const EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID = '5138f710-5cb0-4fa1-ae83-111f640a1aa3';\nexport const EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID = '3d09921f-b1d9-4294-acca-8a60bd005750';\nexport const EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID = 'fad254c1-a76e-49a3-ba47-befbbc3fb8d4';\nexport const DIFF_ANALYSIS_FIELD_AGENT_ID_UID = '7b7fa88e-f54d-493e-a37a-a33c8d67a35e';\nexport const DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID = 'dbcae45f-6b17-44ac-b1fa-cb5fd30bc9b0';\nexport const DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID = 'e301e7cd-f0d7-42f0-b3d9-24a9865faafb';\nexport const DIFF_ANALYSIS_FIELD_POINTS_UID = '8ed96b8f-96bc-44d9-b8f8-1c980e2b4906';\nexport const DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID = '9f4c33b9-5639-491a-8a21-0bb27a9446cd';\nexport const DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID = '1e656a9d-57d1-4a66-b05b-d653aa066cd5';\nexport const PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID = '01a122d4-7b03-48af-8f9c-64c2c1e6ec8e';\nexport const PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID = 'b4ca3c4c-1933-429e-a9d8-1d2842c0b142';\nexport const PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID = '6036fdbf-42c5-4aa2-a813-87ccd5d92ce2';\n/** T22 hardening (A4) — the field/index that makes the singleton a real constraint, not just a convention. */\nexport const PIPELINE_STATE_FIELD_SINGLETON_KEY_UID = 'f4d2c40b-c137-42a2-82c9-981f39cb8c70';\nexport const PIPELINE_STATE_INDEX_SINGLETON_KEY_UID = 'a257c7db-b63b-4535-a0b1-a7d05f5561b6';\nexport const PROMPT_CACHE_FIELD_PROMPT_KEY_UID = 'd5e65781-23c1-4a8d-87d1-992bbf0408fc';\nexport const PROMPT_CACHE_FIELD_CONTENT_UID = '4a2a55e2-468e-4a8d-9a96-eae6e3e629f0';\nexport const PROMPT_CACHE_FIELD_VERSION_UID = '87b77921-6261-4179-a9e6-823e8321ccfd';\nexport const PROMPT_CACHE_FIELD_LABEL_UID = 'ce36ed5b-42e2-45bd-8915-3ef0317e6665';\nexport const PROMPT_CACHE_FIELD_CONFIG_UID = '306cdb0b-433b-44c8-8a5b-6b993d3f0da3';\nexport const PROMPT_CACHE_INDEX_PROMPT_KEY_UID = 'df06ab57-bfc0-4155-a3d6-e22edab8a853';\n/**\n * spec-delais-de-reponse-v1 §3 — `reply-timing`, one row per customer turn.\n * Freshly generated, never reused.\n */\nexport const REPLY_TIMING_OBJECT_UID = '15646c19-965f-4e71-9ada-8dec22cdbb26';\nexport const REPLY_TIMING_FIELD_TICKET_ID_UID = '57faafe3-2846-4d92-b670-295c73b20702';\nexport const REPLY_TIMING_FIELD_TURN_KEY_UID = 'f4365847-09d6-47e2-8c99-95d4138981bd';\nexport const REPLY_TIMING_FIELD_CUSTOMER_MESSAGE_AT_UID = 'a96ce8da-d2b8-4d3f-9728-ea6116fff784';\nexport const REPLY_TIMING_FIELD_REPLIED_AT_UID = 'f9cca111-6da5-4fe1-acc0-d3eebbdb1056';\nexport const REPLY_TIMING_FIELD_RESPONDER_UID = '8b2e951e-dde9-4e2d-a032-073fe0342861';\nexport const REPLY_TIMING_FIELD_RESPONDER_VIA_UID = '125086c7-efea-4d7b-b6a1-49caf77f6866';\nexport const REPLY_TIMING_FIELD_DELAY_SECONDS_UID = 'dcabc93e-2b4b-4219-ac6a-444744227364';\nexport const REPLY_TIMING_FIELD_DELAY_BUCKET_UID = '37d50e89-d9a6-4ac1-b1ce-e4d9861e88d8';\nexport const REPLY_TIMING_FIELD_CATEGORY_ID_UID = '8be48fa6-9faf-4349-ba89-613776fe44d9';\nexport const REPLY_TIMING_FIELD_SOURCE_CHANNEL_UID = 'ff1c1adc-741b-4607-b067-390e25225ec8';\nexport const REPLY_TIMING_FIELD_GENERATED_RESPONSE_ID_UID = '5b73871d-d731-4230-b21f-61565187ab56';\nexport const REPLY_TIMING_FIELD_NEXT_CHECK_AT_UID = '623fc8ad-b810-45b2-b602-9fdf47826716';\nexport const REPLY_TIMING_FIELD_BACKFILLED_UID = 'a773b310-6394-480b-b1c3-6e680e9bd9f6';\nexport const REPLY_TIMING_FIELD_ORIGIN_UID = 'd195f7ca-f469-4725-a92e-58afe8dd0d01';\nexport const REPLY_TIMING_INDEX_TURN_KEY_UID = '4f2bcfc1-8b2b-4771-9866-fdcbb7bce201';\nexport const REPLY_TIMING_INDEX_TICKET_ID_UID = '0d482d11-e45e-4bd2-9d9c-86601e1aed40';\nexport const REPLY_TIMING_INDEX_CUSTOMER_MESSAGE_AT_UID = '78459d0a-dbe8-459f-96f5-8025dc6daf2f';\nexport const REPLY_TIMING_INDEX_RESPONDER_UID = '5fd58fc5-d67c-4936-bdd1-a9daa7d6d4e3';\nexport const REPLY_TIMING_INDEX_NEXT_CHECK_AT_UID = 'cdb66f06-7368-4c30-908e-006a6b3d3a73';\n","/**\n * `agent` (ex-`ModelConfig`) — spec §3.4.\n *\n * `defaultKey` is the equivalent of the legacy partial unique index: it is\n * only ever set to `'default'` when `status === 'default'`, and left absent\n * (`null`) otherwise, so a unique index on it enforces \"at most one default\n * agent\" the same way a Postgres unique index treats NULLs as distinct\n * (already the pattern `generated-response.openTicketKey` uses below).\n * Populating it correctly is a write-handler concern (T22+), not this\n * definition's.\n *\n * `reasoningEffort` reuses `ReasoningEffort` from `../domain/reasoning` — the\n * kit's one vocabulary for this concept — rather than a second hardcoded\n * option list.\n *\n * Deletion detaching `category.agentId` (the legacy Mongoose hook) is a\n * delete-handler rule (T22+), not expressed here.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport type { ReasoningEffort } from '../domain/reasoning';\nimport {\n AGENT_OBJECT_UID,\n AGENT_FIELD_NAME_UID,\n AGENT_FIELD_PROVIDER_UID,\n AGENT_FIELD_MODEL_ID_UID,\n AGENT_FIELD_STATUS_UID,\n AGENT_FIELD_DEFAULT_KEY_UID,\n AGENT_FIELD_PROMPT_NAME_UID,\n AGENT_FIELD_PROMPT_LABEL_UID,\n AGENT_FIELD_PROMPT_VERSION_UID,\n AGENT_FIELD_SYSTEM_PROMPT_SNAPSHOT_UID,\n AGENT_FIELD_REASONING_EFFORT_UID,\n AGENT_FIELD_MAX_TOOL_CALLS_UID,\n AGENT_INDEX_DEFAULT_KEY_UID,\n} from './ids';\n\nexport const AGENT_STATUSES = ['default', 'available', 'archived'] as const;\nexport type AgentStatus = (typeof AGENT_STATUSES)[number];\n\nconst REASONING_EFFORT_OPTIONS: readonly ReasoningEffort[] = ['off', 'low', 'medium', 'high'];\n\n/**\n * The provider an agent (and every graph node built from settings) uses\n * unless one is stated. Named here, next to the field it defaults, so\n * `settings/to-profile.ts` fills `nodes.*.provider` with the same value the\n * record does instead of a second literal.\n */\nexport const DEFAULT_LLM_PROVIDER = 'openai';\n\nexport const agentRecord: ObjectDef = {\n universalIdentifier: AGENT_OBJECT_UID,\n objectKey: 'agent',\n labelSingular: 'Agent',\n labelPlural: 'Agents',\n description: 'A drafting agent: model, prompt binding, and default-agent flag.',\n fields: [\n {\n universalIdentifier: AGENT_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: AGENT_FIELD_PROVIDER_UID,\n name: 'provider',\n type: FieldType.TEXT,\n label: 'Provider',\n description: 'Free text (spec §3.4) — a new provider must not need a kit release.',\n isNullable: false,\n defaultValue: DEFAULT_LLM_PROVIDER,\n },\n {\n universalIdentifier: AGENT_FIELD_MODEL_ID_UID,\n name: 'modelId',\n type: FieldType.TEXT,\n label: 'Model id',\n isNullable: false,\n },\n {\n universalIdentifier: AGENT_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: [...AGENT_STATUSES],\n defaultValue: 'available',\n },\n {\n universalIdentifier: AGENT_FIELD_DEFAULT_KEY_UID,\n name: 'defaultKey',\n type: FieldType.TEXT,\n label: 'Default key',\n description: \"Equals 'default' when status='default', absent otherwise. Unique.\",\n isNullable: true,\n },\n {\n universalIdentifier: AGENT_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n description: 'Free Langfuse prompt name (ETL keeps legacy agent/<old id> names).',\n isNullable: false,\n },\n {\n universalIdentifier: AGENT_FIELD_PROMPT_LABEL_UID,\n name: 'promptLabel',\n type: FieldType.TEXT,\n label: 'Prompt label',\n isNullable: true,\n },\n {\n universalIdentifier: AGENT_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n description: 'Pinning; absent means \"follow the label\".',\n isNullable: true,\n },\n {\n universalIdentifier: AGENT_FIELD_SYSTEM_PROMPT_SNAPSHOT_UID,\n name: 'systemPromptSnapshot',\n type: FieldType.TEXT,\n label: 'System prompt snapshot',\n description: 'Level-3 fallback of the prompt ladder (§3.7).',\n isNullable: true,\n },\n {\n universalIdentifier: AGENT_FIELD_REASONING_EFFORT_UID,\n name: 'reasoningEffort',\n type: FieldType.SELECT,\n label: 'Reasoning effort',\n isNullable: true,\n options: [...REASONING_EFFORT_OPTIONS],\n },\n {\n universalIdentifier: AGENT_FIELD_MAX_TOOL_CALLS_UID,\n name: 'maxToolCalls',\n type: FieldType.NUMBER,\n label: 'Max tool calls',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: AGENT_INDEX_DEFAULT_KEY_UID, fields: ['defaultKey'], isUnique: true }],\n};\n","/**\n * The end-of-conversation settings (spec-fin-de-conversation-v1 §5), read\n * defensively: every field is optional because an app deployed before the\n * feature stores none of them, and that app must keep today's behaviour\n * exactly (D9) — absent reads as `disabled`.\n */\nimport type { NodePromptSettings, SupportKitSettings } from './to-profile';\n\nexport const CONVERSATION_END_ACTIONS = ['disabled', 'tag', 'close'] as const;\nexport type ConversationEndAction = (typeof CONVERSATION_END_ACTIONS)[number];\n\nexport const DEFAULT_CONVERSATION_END_ACTION: ConversationEndAction = 'disabled';\nexport const DEFAULT_CONVERSATION_END_TAG = 'wai/conversation-ended';\n\nexport interface ConversationEndSettings {\n action: ConversationEndAction;\n /** Trimmed. Applied in `tag` mode only, but always read: D11 removes it whatever the mode. */\n tag: string;\n prompt: NodePromptSettings | null;\n}\n\n/** The end action of an app that has one — `null` stands for `disabled`. */\nexport interface ConversationEndConfig {\n action: 'tag' | 'close';\n tag: string;\n}\n\nexport function readConversationEnd(\n settings: SupportKitSettings | Record<string, unknown>,\n): ConversationEndSettings {\n // Read field by field: a stored row may predate the feature or hold anything.\n const raw = settings as Record<string, unknown>;\n const rawAction = raw.conversationEndAction;\n const action = (CONVERSATION_END_ACTIONS as readonly unknown[]).includes(rawAction)\n ? (rawAction as ConversationEndAction)\n : DEFAULT_CONVERSATION_END_ACTION;\n const tag =\n typeof raw.conversationEndTag === 'string'\n ? raw.conversationEndTag.trim()\n : DEFAULT_CONVERSATION_END_TAG;\n return { action, tag, prompt: readPrompt(raw.conversationEndPrompt) };\n}\n\n/** The end action of already-read settings — `null` for `disabled`. */\nexport function endConfigOf({\n action,\n tag,\n}: ConversationEndSettings): ConversationEndConfig | null {\n return action === 'disabled' ? null : { action, tag };\n}\n\nexport function toConversationEnd(\n settings: SupportKitSettings | Record<string, unknown>,\n): ConversationEndConfig | null {\n return endConfigOf(readConversationEnd(settings));\n}\n\n/**\n * What a finished conversation does to the Gorgias ticket (D10): the tag, OR\n * the closure — never both. The webhook applies exactly this and the ticket\n * timeline names exactly this, so the two cannot drift apart.\n */\nexport function conversationEndEffects(end: ConversationEndConfig | null): {\n tags: string[];\n close: boolean;\n} {\n if (!end) return { tags: [], close: false };\n return end.action === 'tag' ? { tags: [end.tag], close: false } : { tags: [], close: true };\n}\n\nfunction readPrompt(raw: unknown): NodePromptSettings | null {\n if (typeof raw !== 'object' || raw === null) return null;\n const { name, label } = raw as Record<string, unknown>;\n if (typeof name !== 'string' || name === '') return null;\n return typeof label === 'string' && label !== '' ? { name, label } : { name };\n}\n","/**\n * Settings fields (spec §3.6) — replaces the legacy `AgentProfile` +\n * `AppSettings`. Assembled into a consuming app's manifest `settings.fields`.\n *\n * `sourceViewId` deliberately has NO `default` — §0 (D-EXT arbitration) and\n * §3.6 both insist: it is the field that separates tickets between apps\n * sharing one Gorgias connection, so a default would silently let two apps\n * observe the same view. `validateSettings` (`./validate`) is what enforces\n * this at read time; this file only declares the field shape.\n *\n * Several `default`s are not spelled out in the spec (the tag/prompt fields\n * carry an explicit legacy default, and so do `batchLimit` (30) and\n * `triageIntervalMinutes` (15), both stated by §3.5/§3.6). Where the spec is\n * silent, this file defaults booleans to `false` (every switch here is an\n * opt-in kill-switch), `whatsappMode` to `DEFAULT_WHATSAPP_MODE` (the most\n * conservative channel behaviour) and `guardrailsActive` to the whole\n * catalogue (default-deny sending, not default-allow). `nodes` carries no\n * default at all — see the field itself. None of these is enforced by\n * `validateSettings`, so a SettingsPage can still override them per-app.\n */\nimport type { SettingsField } from '@apotech-os/app-kit';\nimport {\n CONVERSATION_END_ACTIONS,\n DEFAULT_CONVERSATION_END_ACTION,\n DEFAULT_CONVERSATION_END_TAG,\n} from './conversation-end';\nimport { AGENT_GUARDRAILS } from '../guardrails/constants';\nimport {\n DEFAULT_AUTO_SEND_CHANNELS,\n DEFAULT_CHANNEL_PROMPT_EMAIL,\n DEFAULT_CHANNEL_PROMPT_WHATSAPP,\n DEFAULT_WHATSAPP_MODE,\n WHATSAPP_MODES,\n} from '../domain/profile';\n\n/** Where a stats day starts when the operator has not chosen — also the fallback for a caller that cannot read the settings. */\nexport const DEFAULT_STATS_TIMEZONE = 'Europe/Paris';\n\nexport const SUPPORT_KIT_SETTINGS_FIELDS: SettingsField[] = [\n // Source\n // NO `gorgiasConnectionId`: every Gorgias call in this kit is\n // `ctx.api.integrations.run('gorgias', …)` with no `connectionId`, so the\n // platform resolves the instance's default connection. A settings key here\n // would be written by an operator and read by nobody — see the Source\n // section of `ui/settings/settings-page.tsx`, which STATES the resolved\n // connection instead of pretending to choose it.\n {\n key: 'sourceViewId',\n type: 'string',\n label: 'Gorgias source view',\n // No default — see module doc.\n },\n { key: 'batchLimit', type: 'number', label: 'Batch limit', default: 30 },\n { key: 'triageEnabled', type: 'boolean', label: 'Triage enabled', default: false },\n {\n key: 'triageIntervalMinutes',\n type: 'number',\n label: 'Triage interval (minutes)',\n default: 15,\n },\n { key: 'dryRun', type: 'boolean', label: 'Dry run', default: false },\n\n // Nodes\n // `{triage, escalate, draft, evaluate, revise}`, `null` per key disabling\n // that graph step (§3.6). NO default, same reasoning as `sourceViewId`:\n // the only shape that could be defaulted here (\"every step null\") is a\n // pipeline that triages nothing, and it would install itself silently.\n // `validateSettings` refuses to run until `nodes.triage` is configured.\n { key: 'nodes', type: 'json', label: 'Graph node overrides' },\n\n // Audit tags\n { key: 'unknownTag', type: 'string', label: 'Unknown tag', default: 'wai/unknown' },\n { key: 'handledTag', type: 'string', label: 'Handled tag', default: 'wai/triaged' },\n { key: 'escalationTag', type: 'string', label: 'Escalation tag', default: 'wai/escalated' },\n { key: 'autoRepliedTag', type: 'string', label: 'Auto-replied tag', default: 'wai/auto-replied' },\n { key: 'needsReviewTag', type: 'string', label: 'Review-before-send tag', default: 'wai/escalated' },\n { key: 'followupTag', type: 'string', label: 'Followup tag', default: 'wai/human-required' },\n\n // The app's ticket tag — ONE tag, three readers:\n // - the triage stamps it on every ticket it sees, in the same call as the\n // tags above (`adapters/gorgias-tags.ts`);\n // - the follow-up webhook answers a SUBSEQUENT customer message only on a\n // ticket that carries it (`functions/followup-gates.ts`): two support apps\n // installed on ONE Gorgias account each receive every\n // `ticket-message-created` event, and this tag is what separates them;\n // - the Gorgias extension picks this app's default agent on a ticket that\n // carries it (`functions/ext-models.ts`).\n // Every other audit tag ships the same default in every app — `handledTag`\n // is `wai/triaged` everywhere — so none of them can answer \"whose ticket is\n // this?\". No usable default for the same reason: a mark two apps have in\n // common marks nothing. `validateSettings` refuses to run until it is set.\n { key: 'appScopeTag', type: 'string', label: 'App ticket tag', default: '' },\n\n // End of conversation (spec-fin-de-conversation-v1 §5). Off by default (D9):\n // a new LLM step, with its cost and its false positives, is never switched\n // on for every app without an explicit decision.\n {\n key: 'conversationEndAction',\n type: 'select',\n label: 'End-of-conversation action',\n options: [...CONVERSATION_END_ACTIONS],\n default: DEFAULT_CONVERSATION_END_ACTION,\n },\n {\n key: 'conversationEndTag',\n type: 'string',\n label: 'End-of-conversation tag',\n default: DEFAULT_CONVERSATION_END_TAG,\n },\n // No default, like every step prompt: `validateSettings` requires it once the action is on.\n { key: 'conversationEndPrompt', type: 'json', label: 'End-of-conversation prompt' },\n\n // Sending\n { key: 'autoSendEnabled', type: 'boolean', label: 'Auto-send enabled', default: false },\n { key: 'senderEmail', type: 'string', label: 'Sender email', default: '' },\n {\n key: 'requireHighTriageConfidence',\n type: 'boolean',\n label: 'Require high triage confidence',\n default: false,\n },\n {\n key: 'whatsappMode',\n type: 'select',\n label: 'WhatsApp mode',\n options: [...WHATSAPP_MODES],\n default: DEFAULT_WHATSAPP_MODE,\n },\n // An ALLOWLIST: a channel absent from it never auto-sends. Defaulted to the\n // two that had a publication path before the setting existed, so an app\n // that never touches it keeps behaving exactly as it did.\n { key: 'autoSendChannels', type: 'json', label: 'Auto-send channels', default: [...DEFAULT_AUTO_SEND_CHANNELS] },\n // 14_400 minutes = 10 days, the legacy `fast_response_ttl_minutes` default\n // (`backoffice/src/models/AppSettings.ts`) — copied deliberately, not\n // chosen here. A pre-generated draft is only worth anything while the\n // ticket is still open, and a support ticket routinely sits days before\n // an agent opens it: a shorter TTL expires drafts nobody ever got to see\n // and shows up only as a silently collapsing reuse rate (I1).\n { key: 'responseTtlMinutes', type: 'number', label: 'Response TTL (minutes)', default: 14_400 },\n\n // Guardrails\n // The whole catalogue, not an empty list: guardrails are what hold a reply\n // back, so an install that enables none is an install that sends\n // everything. Derived from `AGENT_GUARDRAILS` so a new rule is active by\n // default rather than silently off (I7).\n { key: 'guardrailsActive', type: 'json', label: 'Active guardrails', default: [...AGENT_GUARDRAILS] },\n { key: 'blocklist', type: 'json', label: 'Blocklist', default: [] },\n { key: 'noreplySenders', type: 'json', label: 'No-reply senders', default: [] },\n\n // Channel prompts\n {\n key: 'channelPromptEmail',\n type: 'string',\n label: 'Email style prompt',\n default: DEFAULT_CHANNEL_PROMPT_EMAIL,\n },\n {\n key: 'channelPromptWhatsapp',\n type: 'string',\n label: 'WhatsApp style prompt',\n default: DEFAULT_CHANNEL_PROMPT_WHATSAPP,\n },\n\n // Misc\n { key: 'renameEnabled', type: 'boolean', label: 'Rename enabled', default: false },\n // §3.6 lists a single `renameTemplate`, but the legacy rename carries TWO\n // semantically different strings: `ticket_rename_from` is a needle matched\n // against the subject with `includes`, and `ticket_rename_to` is the\n // replacement. Encoding both in one field needs a separator nobody specified,\n // which can collide with real subject text. Split instead — a documented\n // one-field deviation from §3.6, recorded for the spec owner.\n { key: 'renameFrom', type: 'string', label: 'Rename — subject pattern to match', default: '' },\n { key: 'renameTo', type: 'string', label: 'Rename — replacement subject', default: '' },\n { key: 'statsTimezone', type: 'string', label: 'Stats timezone (IANA)', default: DEFAULT_STATS_TIMEZONE },\n];\n","/**\n * `validateSettings` — spec §3.6, single point of DRY validation shared by\n * the SettingsPage and every handler.\n *\n * Returns a plain list of issues rather than throwing: a SettingsPage maps\n * `issues` by `key` to show a per-field error, and a handler simply checks\n * `issues.length > 0` to refuse a run — one shape, two callers, no\n * try/catch-driven control flow on either side.\n */\nimport { readConversationEnd } from './conversation-end';\n\n/**\n * Every issue `validateSettings` can raise, by its own `key` — a closed\n * union, not `string` (T27 rework, pass 2 of 2): `ui/shared/\n * settings-issue-labels.ts`'s `SETTINGS_ISSUE_LABELS` is keyed on this same\n * type, so a new issue this function starts raising without a matching\n * French translation is now a COMPILE ERROR in that map, not a silent\n * English leak an operator discovers on a live settings page.\n */\nexport type SettingsIssueKey =\n | 'sourceViewId'\n | 'appScopeTag'\n | 'nodes'\n | 'nodePrompt'\n | 'senderEmail'\n | 'conversationEndTag'\n | 'conversationEndPrompt';\n\nexport interface SettingsValidationIssue {\n /** The offending settings key. */\n key: SettingsIssueKey;\n /** Human-readable reason, safe to show in the SettingsPage. */\n message: string;\n}\n\n/**\n * The two cross-field rules the spec names, the app's own ticket tag, plus\n * the one shape rule no schema can express: `nodes.triage` must be configured. `nodes` has no\n * default (a defaulted \"every step null\" would install a pipeline that\n * triages nothing), and `AgentProfile.nodes.triage` is non-nullable — this\n * check is what makes both safe. Per-field typing (e.g. `batchLimit` being a\n * number) stays the settings API's job at write time, not this function's.\n */\nexport function validateSettings(settings: Record<string, unknown>): SettingsValidationIssue[] {\n const issues: SettingsValidationIssue[] = [];\n\n if (!isNonEmptyString(settings.sourceViewId)) {\n issues.push({\n key: 'sourceViewId',\n message: 'sourceViewId is required — pick the Gorgias view this app owns.',\n });\n }\n\n // Trimmed, like every reader of this tag (`functions/followup-gates.ts`): a\n // stray space is not a tag, and an app with no ticket tag can neither claim\n // its tickets nor be told apart from its neighbour on a shared account.\n if (!isNonEmptyString(settings.appScopeTag) || settings.appScopeTag.trim() === '') {\n issues.push({\n key: 'appScopeTag',\n message: \"appScopeTag is required — set the tag that marks this app's tickets.\",\n });\n }\n\n if (!isConfiguredNode(settings.nodes)) {\n issues.push({\n key: 'nodes',\n message: 'nodes.triage must be configured — a null triage step would triage nothing.',\n });\n }\n\n const stepsWithoutPrompt = stepsMissingPrompt(settings.nodes);\n if (stepsWithoutPrompt.length > 0) {\n issues.push({\n key: 'nodePrompt',\n message: `Every active step needs a Langfuse prompt — missing on: ${stepsWithoutPrompt.join(', ')}.`,\n });\n }\n\n const autoSendEnabled = settings.autoSendEnabled === true;\n const isWhatsappAutoReply = settings.whatsappMode === 'auto_reply';\n if (autoSendEnabled && !isWhatsappAutoReply && !isNonEmptyString(settings.senderEmail)) {\n issues.push({\n key: 'senderEmail',\n message: \"senderEmail is required when autoSendEnabled is on, unless whatsappMode is 'auto_reply'.\",\n });\n }\n\n // spec-fin-de-conversation-v1 §5. The tag is required only by an ACTIVE\n // tag step, but it is removed when the customer writes again in EVERY mode\n // (§4: removal follows the tag, not the mode), so the reserved-tag rule\n // holds whatever the action.\n const end = readConversationEnd(settings);\n if (end.action === 'tag' && end.tag === '') {\n issues.push({\n key: 'conversationEndTag',\n message: 'conversationEndTag is required when the end-of-conversation action is \"tag\".',\n });\n } else if (end.tag !== '' && reservedTags(settings).includes(end.tag)) {\n // D13 — a takeover tag would veto every later message at G6 and make\n // D11's removal impossible; the scope tag would stop identifying the app;\n // removing the handled tag would put the ticket back in the triage view.\n issues.push({\n key: 'conversationEndTag',\n message:\n 'conversationEndTag must differ from escalationTag, needsReviewTag, followupTag, appScopeTag and handledTag.',\n });\n }\n if (end.action !== 'disabled' && end.prompt === null) {\n issues.push({\n key: 'conversationEndPrompt',\n message: 'conversationEndPrompt is required when the end-of-conversation action is on.',\n });\n }\n\n return issues;\n}\n\nfunction reservedTags(settings: Record<string, unknown>): string[] {\n return [\n settings.escalationTag,\n settings.needsReviewTag,\n settings.followupTag,\n settings.appScopeTag,\n settings.handledTag,\n ]\n .filter(isNonEmptyString)\n .map((tag) => tag.trim());\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * The active steps that name no Langfuse prompt, in execution order.\n *\n * `draft` is exempt: it speaks with the resolved agent's voice, so its\n * prompt lives on the `agent` record, not in settings (see\n * `SupportKitDraftNodeSettings`). `revise` is exempt for the same reason —\n * it re-runs the writer against the judge's objection, so the only prompt\n * it speaks with is the writer's own (`graph/nodes/revise.ts`). A disabled\n * step (`null`) is exempt too — a step that never runs has nothing to say.\n *\n * This is the settings-time half of \"no prompt is an error\"; the runtime\n * half is `prompts/resolver.ts`, which fails a run rather than serving a\n * step an empty system message. Both are needed: this one stops a bad\n * install before it runs, that one catches a prompt that stops resolving\n * after the install was already valid.\n */\nconst STEPS_REQUIRING_PROMPT = ['triage', 'escalate', 'evaluate'] as const;\n\nfunction stepsMissingPrompt(nodes: unknown): string[] {\n if (typeof nodes !== 'object' || nodes === null) return [];\n const byStep = nodes as Record<string, unknown>;\n return STEPS_REQUIRING_PROMPT.filter((step) => {\n const node = byStep[step];\n if (typeof node !== 'object' || node === null) return false;\n return !isNonEmptyString(promptNameOf(node as Record<string, unknown>));\n });\n}\n\nfunction promptNameOf(node: Record<string, unknown>): unknown {\n const prompt = node.prompt;\n return typeof prompt === 'object' && prompt !== null ? (prompt as Record<string, unknown>).name : undefined;\n}\n\n/** `nodes` is present AND its mandatory `triage` step is an object, not `null`. */\nfunction isConfiguredNode(nodes: unknown): boolean {\n if (typeof nodes !== 'object' || nodes === null) return false;\n const triage = (nodes as Record<string, unknown>).triage;\n return typeof triage === 'object' && triage !== null;\n}\n","/**\n * `settingsWarnings` — the settings problems that must NOT stop the app.\n *\n * Deliberately separate from `validateSettings`: nine handlers refuse to run\n * as soon as that function reports a single issue, so routing a \"this looks\n * wrong\" remark through it would take a working app off the air. Everything\n * here describes a configuration that runs, and runs in a way its operator\n * probably did not intend.\n *\n * Its only consumer is the SettingsPage, which is why these messages are\n * written in French straight away — unlike `validateSettings`' own, they are\n * never logged, never returned by a handler, and so need no translation layer.\n */\nexport type SettingsWarningKey =\n | 'appScopeTagVetoesFollowups'\n | 'appScopeTagCollision'\n | 'noAutoSendChannels';\n\nexport interface SettingsWarning {\n key: SettingsWarningKey;\n /** Operator-facing French, safe to show as-is. */\n message: string;\n}\n\n/**\n * The three tags G6 (`functions/followup-gates.ts`) reads as \"a human took\n * this thread over\" — keyed by their SETTINGS names, which is what an\n * operator sees on the page.\n */\nconst HUMAN_TAKEOVER_KEYS = ['escalationTag', 'needsReviewTag', 'followupTag'] as const;\n\n/** Every audit tag an ownership tag must not be equal to, in reporting order. */\nconst AUDIT_TAG_KEYS = ['unknownTag', 'handledTag', 'escalationTag', 'autoRepliedTag', 'needsReviewTag', 'followupTag'] as const;\n\nexport function settingsWarnings(settings: Record<string, unknown>): SettingsWarning[] {\n const warnings: SettingsWarning[] = [];\n const appScopeTag = trimmed(settings.appScopeTag);\n const collidesWith = (keys: ReadonlyArray<string>) =>\n appScopeTag ? keys.filter((key) => trimmed(settings[key]) === appScopeTag) : [];\n\n // Every audit tag ships the SAME default in every app — `handledTag` is\n // `wai/triaged` everywhere, `escalationTag` is `wai/escalated` — so an app\n // claiming its tickets with one of them is indistinguishable from its\n // neighbour on the same Gorgias account, which is the one thing the\n // ownership tag exists to prevent.\n //\n // Colliding with a human-takeover tag is reported on its own because the\n // consequence is worse and entirely silent: G6 vetoes a follow-up the moment\n // the ticket carries one of those three, so stamping one on EVERY triaged\n // ticket means the webhook answers nothing, ever.\n if (collidesWith(HUMAN_TAKEOVER_KEYS).length > 0) {\n warnings.push({\n key: 'appScopeTagVetoesFollowups',\n message:\n 'Le tag des tickets de l’application est l’un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi considérera que chaque ticket trié a été repris par un humain et ne répondra plus à aucun message suivant.',\n });\n } else if (collidesWith(AUDIT_TAG_KEYS).length > 0) {\n warnings.push({\n key: 'appScopeTagCollision',\n message:\n 'Le tag des tickets de l’application est l’un des autres tags d’audit, que toutes les apps posent avec la même valeur par défaut : il ne distingue donc pas cette app d’une autre installée sur le même compte Gorgias.',\n });\n }\n\n // Every box unticked. `settingsToProfile` only falls back to the default\n // list on a MISSING value, so a stored `[]` is kept as-is and\n // `isAutoSendChannel` then refuses every channel — auto-send is off for the\n // whole app while its switch still reads \"on\", and the only trace is one\n // sentence on each ticket. An absent list is a fresh install, not this.\n if (settings.autoSendEnabled === true && Array.isArray(settings.autoSendChannels) && settings.autoSendChannels.length === 0) {\n warnings.push({\n key: 'noAutoSendChannels',\n message:\n 'L’envoi automatique est actif mais aucun canal n’est coché : aucune réponse ne peut partir. Cochez au moins un canal, ou coupez l’envoi automatique.',\n });\n }\n\n return warnings;\n}\n\nfunction trimmed(value: unknown): string {\n return typeof value === 'string' ? value.trim() : '';\n}\n","/**\n * `settings` (§3.6) → `AgentProfile` (architecture_agent_graphe.md §5.3).\n *\n * The graph reads a profile, the platform stores flat settings; this is the\n * single, pure translation between the two. Keeping it pure (no `ctx`, no\n * record read, no clock) is what lets every node test build a profile from\n * the same settings an operator actually edits.\n *\n * Three name mismatches are deliberate, and are the reason this mapping is\n * written out by hand instead of being a spread:\n * - `autoRepliedTag` → `audit.sentTag` (same tag, `wai/auto-replied`).\n * - `needsReviewTag` → `audit.needsHumanTag`: the operator-facing name is\n * the review-before-send tag, the graph's is the `needs_human` outcome\n * tag. Same tag, two vocabularies.\n * - `responseTtlMinutes` → `schedule.fastResponseTtlMinutes`, `batchLimit`\n * → `schedule.triageBatchLimit`.\n *\n * Five settings have no profile counterpart on purpose:\n * `dryRun` (read by the HANDLERS — `functions/triage-tick.ts` and\n * `functions/process-response.ts` swap the `reply`/`state` ports for the\n * recorders of `adapters/recording-ports.ts` and force `send: {mode:\n * 'none'}` — not by the graph, which must run identically either way),\n * `statsTimezone` (a §3.8 rendering concern), and the three `conversationEnd*`\n * keys (read by `functions/triage-tick.ts` and the follow-up webhook, which run\n * the end-of-conversation judge and apply the end action themselves — D16; no\n * graph node sees them). `to-profile.spec.ts` pins\n * that list, so a new settings field cannot be forgotten here.\n *\n * `prompts` is a PARAMETER, not derived here: `prompts.draft` is the agent\n * record's own Langfuse binding (§3.4), which a settings blob cannot know.\n * The other slots ARE operator-chosen (`nodes.<step>.prompt`), but the ref\n * they become is assembled by `buildPromptsTable`, alongside `draft` — one\n * place builds the table, this mapper consumes it.\n */\nimport type { ReasoningEffort } from '../domain/reasoning';\nimport {\n DEFAULT_AUTO_SEND_CHANNELS,\n DEFAULT_PROFILE_KEY,\n type AgentProfile,\n type PromptRef,\n type PromptTableKey,\n type WhatsappMode,\n} from '../domain/profile';\nimport { DEFAULT_LLM_PROVIDER } from '../records/agent';\nimport type { AuditTags } from '../graph/ports';\nimport type { ConversationEndAction } from './conversation-end';\n\n/**\n * The Langfuse prompt an operator bound to one graph step, chosen from the\n * catalogue the app's `role.prompts` allowlist exposes (`ui/settings/\n * pipeline-nodes-form.tsx`).\n *\n * Required on every configured step, and NOT defaulted: the prompt is what\n * the step actually says to the model, so a step that names none has no\n * honest behaviour to fall back on. `validateSettings` refuses to run a\n * pipeline missing one, and `prompts/resolver.ts` fails the run rather than\n * serving empty text — the same \"state it or it does not run\" rule\n * `sourceViewId` already follows.\n *\n * `label` floats with Langfuse promotions (`production` unless an operator\n * picks another); no version pin, deliberately — a pinned run stops\n * following the promotions the operator makes in Langfuse.\n */\nexport interface NodePromptSettings {\n name: string;\n /** Defaults to `production`, the label every promotion targets. */\n label?: string;\n}\n\n/** One entry of the `nodes` settings json (§3.6); `null` disables the step. */\nexport interface SupportKitNodeSettings {\n model: string;\n /** The Langfuse prompt this step sends as its system message. */\n prompt: NodePromptSettings;\n /** Falls back to the same provider the `agent` record defaults to. */\n provider?: string;\n reasoning?: ReasoningEffort;\n /** `draft` only. */\n maxToolCalls?: number;\n /** `evaluate` only. */\n minConfidence?: number;\n /** `evaluate` only. */\n escalationEnabled?: boolean;\n}\n\n/**\n * The two steps with no `prompt` of their own. `draft` speaks with the\n * resolved agent's voice, so its Langfuse binding lives on the `agent`\n * record (§3.4, `functions/records.ts`'s `draftPromptRefFor`) and is chosen\n * per agent on the AgentsPage, not per install on the SettingsPage.\n * `revise` re-runs that same writer against the judge's objection\n * (`graph/nodes/revise.ts`), so it too has only the writer's prompt to\n * speak with — a `prompt` key on either would be written by an operator\n * and read by nobody.\n */\nexport type SupportKitDraftNodeSettings = Omit<SupportKitNodeSettings, 'prompt'>;\n\n/**\n * The settings a consuming app stores, typed. The platform hands them over\n * as a `Record<string, unknown>` JSONB blob: a caller narrows it to this\n * type after `validateSettings` returns no issue — in particular\n * `nodes.triage`, which that function is what guarantees.\n */\nexport interface SupportKitSettings {\n sourceViewId: string;\n batchLimit: number;\n triageEnabled: boolean;\n triageIntervalMinutes: number;\n dryRun: boolean;\n nodes: {\n triage: SupportKitNodeSettings;\n escalate?: SupportKitNodeSettings | null;\n draft?: SupportKitDraftNodeSettings | null;\n evaluate?: SupportKitNodeSettings | null;\n revise?: SupportKitDraftNodeSettings | null;\n };\n unknownTag: string;\n handledTag: string;\n escalationTag: string;\n autoRepliedTag: string;\n needsReviewTag: string;\n followupTag: string;\n /** The app's ticket tag: stamped by the triage, required by the follow-up webhook, served to the extension (see `settings/fields.ts`). */\n appScopeTag: string;\n /** spec-fin-de-conversation-v1 §5 — optional: apps deployed before 10.2.0 store none, read as `disabled`. */\n conversationEndAction?: ConversationEndAction;\n conversationEndTag?: string;\n conversationEndPrompt?: NodePromptSettings | null;\n autoSendEnabled: boolean;\n senderEmail: string;\n /** Optional: apps deployed before the field existed have no value stored. */\n autoSendChannels?: string[];\n requireHighTriageConfidence: boolean;\n whatsappMode: WhatsappMode;\n responseTtlMinutes: number;\n guardrailsActive: string[];\n blocklist: string[];\n noreplySenders: string[];\n channelPromptEmail: string;\n channelPromptWhatsapp: string;\n renameEnabled: boolean;\n renameFrom: string;\n renameTo: string;\n statsTimezone: string;\n}\n\n/** No reasoning effort unless a node asks for one — the cheapest setting (§6.3). */\nconst DEFAULT_REASONING: ReasoningEffort = 'off';\n\n/** Legacy `draft` tool budget; overridable per node via `nodes.draft.maxToolCalls`. */\nexport const DEFAULT_MAX_TOOL_CALLS = 5;\n\n/** Legacy auto-reply confidence floor, unchanged since the Mongo profile. */\n/**\n * The settings-key → audit-tag mapping, on its own because two of the six\n * are RENAMES (`autoRepliedTag` → `sentTag`, `needsReviewTag` →\n * `needsHumanTag`) and a second hand-written copy of a rename is a silent\n * break waiting for whoever renames a setting key. The ticket timeline\n * (`ui/tickets/ticket-actions.ts`) needs the same six to name the tags a run\n * applied, and gets them from here rather than re-reading the blob.\n */\nexport function toAuditTags(settings: SupportKitSettings): AuditTags {\n return {\n unknownTag: settings.unknownTag,\n handledTag: settings.handledTag,\n escalationTag: settings.escalationTag,\n sentTag: settings.autoRepliedTag,\n needsHumanTag: settings.needsReviewTag,\n followupTag: settings.followupTag,\n appScopeTag: settings.appScopeTag,\n };\n}\n\nexport const DEFAULT_MIN_CONFIDENCE = 0.8;\n\n/** Evaluation-driven escalation stays opt-in per node (§6.4). */\nexport const DEFAULT_ESCALATION_ENABLED = false;\n\n/**\n * `judgeme` has no settings surface: the legacy held every Judge.me review\n * ticket for a human unconditionally, and this mapper is not the place to\n * loosen a guardrail. Enabling/disabling the rule is done through\n * `guardrailsActive`, which DOES have one.\n */\nconst JUDGEME_ESCALATE_ONLY = true;\n\n/** `triage-tick` runs `concurrency {limit:1}`, `process-response` `{limit:3}` (§3.5). */\nconst TRIAGE_CONCURRENCY = 1;\nconst FAST_RESPONSE_CONCURRENCY = 3;\n\n/**\n * `process-response` is a dbEvent function (§3.5): one record per event, no\n * poll interval and no batch. The legacy's polling fields survive on\n * `AgentProfile.schedule` for the nodes that still read them; they describe\n * a loop that no longer exists, so they are pinned here rather than invented\n * per install.\n */\nconst FAST_RESPONSE_INTERVAL_SECONDS = 0;\nconst FAST_RESPONSE_BATCH_LIMIT = 1;\n\n\nexport function settingsToProfile(\n settings: SupportKitSettings,\n prompts: Record<PromptTableKey, PromptRef>,\n): AgentProfile {\n const evaluate = toEvaluateNode(settings.nodes.evaluate);\n return {\n key: DEFAULT_PROFILE_KEY,\n // One app installs one kit, so its profile is that app's only tenant —\n // the multi-tenant `key` of the legacy is now the app boundary itself.\n isDefault: true,\n enabled: settings.triageEnabled,\n source: { channel: 'gorgias', viewOrTag: settings.sourceViewId },\n schedule: {\n triageIntervalMinutes: settings.triageIntervalMinutes,\n triageBatchLimit: settings.batchLimit,\n triageConcurrency: TRIAGE_CONCURRENCY,\n fastResponseIntervalSeconds: FAST_RESPONSE_INTERVAL_SECONDS,\n fastResponseBatchLimit: FAST_RESPONSE_BATCH_LIMIT,\n fastResponseConcurrency: FAST_RESPONSE_CONCURRENCY,\n fastResponseTtlMinutes: settings.responseTtlMinutes,\n },\n nodes: {\n triage: baseNode(settings.nodes.triage),\n escalate: settings.nodes.escalate ? baseNode(settings.nodes.escalate) : null,\n draft: settings.nodes.draft\n ? {\n ...baseNode(settings.nodes.draft),\n maxToolCalls: settings.nodes.draft.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS,\n }\n : null,\n evaluate,\n revise: settings.nodes.revise ? baseNode(settings.nodes.revise) : null,\n },\n prompts,\n // No settings surface for the §6.2 tool allowlist yet (the registry\n // already refuses every write tool on its own). Default-deny until\n // T22 has a real list to pass; an empty list only costs the `draft`\n // node its optional lookups, it never opens anything.\n tools: [],\n guardrails: {\n active: [...settings.guardrailsActive],\n params: {\n noreplySenders: [...settings.noreplySenders],\n blocklist: [...settings.blocklist],\n whatsappMode: settings.whatsappMode,\n judgemeEscalateOnly: JUDGEME_ESCALATE_ONLY,\n channelPromptEmail: settings.channelPromptEmail,\n channelPromptWhatsapp: settings.channelPromptWhatsapp,\n },\n },\n // `authorize` is DEFAULT DENY on an absent kind, so the one action kind\n // that exists must be stated: auto-send on ⇒ the graph may send, off ⇒\n // a human approves. Nothing here can reach 'forbidden' — that decision\n // belongs to P3's per-role policy, which needs a runtime context this\n // pure mapper does not have.\n authorization: { send_reply: settings.autoSendEnabled ? 'auto' : 'needs_approval' },\n audit: toAuditTags(settings),\n autoSend: {\n enabled: settings.autoSendEnabled,\n senderEmail: settings.senderEmail === '' ? null : settings.senderEmail,\n // The auto-send floor is the evaluation floor: a second, independent\n // threshold would be a silent way to send below the one an operator set.\n minConfidence: evaluate?.minConfidence ?? DEFAULT_MIN_CONFIDENCE,\n requireHighTriage: settings.requireHighTriageConfidence,\n // Defaulted rather than required: `SupportKitSettings` describes what a\n // SettingsPage writes, and an app deployed before this field existed\n // has no value stored for it.\n channels: [...(settings.autoSendChannels ?? DEFAULT_AUTO_SEND_CHANNELS)],\n },\n rename: settings.renameEnabled\n ? { enabled: true, from: settings.renameFrom, to: settings.renameTo }\n : null,\n // Locks and run stamps are per-run state: they live in the\n // `pipeline-state` record (§3.4), never in settings.\n runtime: {\n triageLock: { acquiredAt: null, owner: null },\n fastResponseLock: { acquiredAt: null, owner: null },\n triageLastRun: { startedAt: null, completedAt: null, status: null },\n fastResponseLastRun: { startedAt: null, completedAt: null, status: null },\n lastAutoSendDecisionAt: null,\n },\n };\n}\n\nfunction baseNode(node: SupportKitDraftNodeSettings) {\n return {\n model: node.model,\n provider: node.provider ?? DEFAULT_LLM_PROVIDER,\n reasoning: node.reasoning ?? DEFAULT_REASONING,\n };\n}\n\nfunction toEvaluateNode(node: SupportKitNodeSettings | null | undefined) {\n if (!node) return null;\n return {\n ...baseNode(node),\n minConfidence: node.minConfidence ?? DEFAULT_MIN_CONFIDENCE,\n escalationEnabled: node.escalationEnabled ?? DEFAULT_ESCALATION_ENABLED,\n };\n}\n\n","/**\n * Pure reducers over `ctx.api.aggregate` result rows — `DashboardPage`'s own\n * \"KPIs via `aggregate`\" (§3.8), deliberately NOT a client-side reduction\n * over one bounded fetched page the way `pipeline/stats.ts` is (that page's\n * own header documents why it had to be: it predates this module). Kept\n * framework-free and unit-testable without React, mirroring that file's own\n * split between computation and rendering.\n *\n * THE PAGE'S ONE NUMBER — the autonomy rate: replies the AI settled alone,\n * over those plus the ones a human had to take back.\n *\n * TWO RECORD FAMILIES, and why that cannot double-count. `generated-response`\n * carries every demande that got as far as a draft; `triage-decision` carries\n * the ones that never did because the pipeline handed the ticket over at\n * triage. The two sets are DISJOINT by construction, not by luck:\n * `eligibility.ts` refuses to create a response row for an escalated ticket\n * (`if (escalated) return false`), and `triage-tick`'s `handleTicketFailure`\n * writes an error DECISION only on the branch where no response row exists —\n * the other branch finalises that row to `failed` instead. Verified against\n * production on 24/09/2026: of 59 escalated-or-error decisions, zero carry a\n * `generated-response`.\n *\n * WHICH FIELD SAYS \"a human has this now\" — `outcome`, not\n * `autoSendDecision`. The latter is written in exactly two places\n * (`reclaimStalledSend` and an approval refusal, `handle-approval.ts:86`),\n * never on the guardrail or unsendable-verdict path, so reading it alone\n * filed every held draft as in-flight and dropped it out of the ratio: 76 of\n * the 84 drafts handed to a human between 21/09 and 24/09/2026. `outcome` is\n * persisted since 21/09/2026 and names the exit the run actually took.\n *\n * The partition, row by row (`status/machine.ts` owns the status vocabulary,\n * `graph/state.ts` the outcome one):\n * - `outcome: needs_human` → the verdict was unsendable. A\n * needs-review tag goes on the ticket (`run-ticket.ts`'s `outcomeTags`)\n * and the draft waits for someone. The row STAYS `ready` — `ready` is what\n * `ext-fast-response-check` serves — so status alone cannot tell this from\n * the nominal park below.\n * - `outcome: guardrail_hold` → a guardrail fired, or the reply went out\n * with an escalation: the escalation tag goes on the ticket.\n * - `outcome: escalated` → escalated upstream, no draft written.\n * - `outcome: awaiting_approval`→ an action awaits a human's sign-off (P3).\n * - `outcome: triaged_only` → the tenant has no draft step at all.\n * Outside the ratio: nobody was asked to do anything.\n * - `outcome: ready` → the nominal park. Draft fine, NO tag,\n * auto-send simply not enabled for that category. Still in flight: the\n * silence is what tells an agent nothing is wrong (I20).\n * - a `triage-decision` with `escalated: true`, or `status: 'error'` (whose\n * `escalated` stays at its default while `handleTicketFailure` escalates\n * the ticket for real) → human. A demande nobody could automate is a\n * failure to automate, and has to be visible as one.\n * - `sent` → settled by the AI. `handle-approval`\n * refuses to send a held record, so nothing reaches `sent` against the\n * policy's decision. CAVEAT, and the one number on this page that is not\n * exact: a reply a human APPROVED also commits as `sent`\n * (`handle-approval` → `act` → `claim-commit.ts`) with no field\n * distinguishing it from an unattended send, so it counts here. Closing\n * that gap means writing a `sendPath: 'auto' | 'approved'` at the commit\n * site — a change to the T20-frozen `generated-response` record (§3.4),\n * which belongs to whoever owns `records/generated-response.ts`, not to\n * this reducer.\n * - `autoSendDecision: 'hold'` → a human's problem now, whatever the\n * status still says. Read LAST, and kept only for what nothing else\n * covers: `sweep`'s stalled-send reclaim, whose row carries no held\n * outcome. It is also the one signal available on a row written before\n * `outcome` existed, which is why an absent `outcome` falls through to it\n * rather than being reinterpreted — a day the page has no outcome data\n * for keeps exactly the numbers it showed before.\n * - `invalidated`/`expired` → an agent answered first, or the window\n * closed unused: the ticket was handled without the draft either way.\n * - `superseded` → the customer wrote again before this draft\n * was sent, so a newer one replaced it. Outside the ratio: the replacement\n * is the row that carries the outcome.\n * - `no_reply_needed` → neither side handled anything. Out of the\n * ratio entirely: counting it as AI work inflates the rate, counting it\n * as human work sabotages it.\n * - `failed` → a technical miss, which escalates the\n * ticket on both paths that write it → human, and named on its own by\n * `countFailed` so the outage is still sayable.\n * - `pending`/`ready`/`sending` without a hold → still in flight, no\n * outcome yet.\n *\n * REMAINING GAP 1, stated rather than papered over: a reply a human\n * APPROVED counts as AI work. `claim-commit.ts`'s `commit()` stamps\n * `outcome: 'sent'` deliberately, \"whichever caller got it here (`act`\n * through `process-response`, or `handle-approval`'s direct send)\", so no\n * field on the row distinguishes the two. Closing it needs a `sendPath:\n * 'auto' | 'approved'` written at that commit site — a change to the\n * T20-frozen `generated-response` record (§3.4), which belongs to whoever\n * owns `records/generated-response.ts`, not to this reducer. Production\n * carries zero such rows so far (24/09/2026): the approval path has never\n * been used.\n *\n * `failed` IS in the denominator (24/09/2026), and the fix that made that\n * honest was not here. Both writers now hand the ticket over:\n * `triage-tick.ts`'s `finalizeFailedResponse` always escalated it straight\n * afterwards (\"every per-ticket failure ends the same way for the customer —\n * the ticket is ESCALATED\", owner decision 16/09/2026), and `sweep.ts`'s\n * orphaned-pending reclaim now does the same — it used to flip the row with NO\n * tag, telling nobody, which is precisely what made this bucket impossible to\n * count either way: half hand-off, half silent drop. It is folded into `human`\n * and named separately by `countFailed`, so a drafting outage makes the rate\n * FALL instead of leaving it untouched.\n *\n * DELIBERATELY OUT of the human side: a ticket whose category has no\n * `fastResponseEnabled` opt-in. It never got a draft either, but that is a\n * tenant's configuration choice, not a demande the pipeline failed to\n * automate — and at ~180 of the ~280 messages triaged a day it would drown\n * every other term. The two windows also differ: the triage side is cut on\n * `decidedAt`, the response side on `generatedAt`, the same asymmetry\n * `foldCategoryOutcomes` documents below.\n */\nimport type { AggregateRow } from './aggregate-row';\n\n/** Sums a `count` metric across every row of a `groupBy` result — the group total (e.g. every status bucket added back up). */\nexport function sumCounts(rows: AggregateRow[], countField = 'count'): number {\n return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);\n}\n\n/** The calendar day (or week) an aggregate `bucket` row falls on — the SQL side already applies `statsTimezone` (`AT TIME ZONE`, aggregate-compiler.ts), so this is a plain string slice, not a second timezone conversion. */\nfunction bucketDay(row: AggregateRow): string {\n return String(row['bucket']).slice(0, 10);\n}\n\nexport interface OutcomeTotals {\n /** Replies the AI sent on its own — the numerator. */\n auto: number;\n /** Held, invalidated or expired: a human took the ticket back — the rest of the denominator. */\n human: number;\n /** Still in flight at the end of the window: no outcome to count yet. */\n inProgress: number;\n /** Drafted, then found not to need an answer — outside the ratio. */\n noReplyNeeded: number;\n}\n\nconst EMPTY_TOTALS: OutcomeTotals = {\n auto: 0,\n human: 0,\n inProgress: 0,\n noReplyNeeded: 0,\n};\n\n/**\n * How many generations failed technically — a NAMED REASON inside the human\n * side, not a camp of its own, which is why it is counted here instead of\n * living in `OutcomeTotals`. `dashboardSignals` and the reasons tile both read\n * it; the ratio reads it through `human` like any other hand-off.\n */\nexport function countFailed(rows: AggregateRow[]): number {\n return sumCounts(rows.filter((row) => row['status'] === 'failed'));\n}\n\n/**\n * The exits that put the ticket on a human's desk, each with its own tag\n * (`run-ticket.ts`'s `outcomeTags`). `ready` and `no_reply_needed` are the\n * two that deliberately apply NO tag, and they are not here.\n */\nconst HUMAN_OUTCOMES = new Set(['needs_human', 'guardrail_hold', 'escalated', 'awaiting_approval']);\n\n/**\n * A `triage-decision` that ended on a human without ever reaching a draft —\n * the second half of the denominator, and the reason this reducer reads two\n * record families (see this file's header for why they cannot overlap).\n *\n * `status: 'error'` is in for a reason that is easy to miss:\n * `writeErrorDecision` never sets `escalated`, so the row keeps the field's\n * `false` default, while `handleTicketFailure` escalates the ticket in\n * Gorgias immediately afterwards. The tag is on the ticket; only the record\n * is silent about it.\n *\n * `conversationOver` needs no test here: an escalation decided at triage\n * never reaches the end-of-conversation step (spec-fin-de-conversation-v1\n * D17), so a thread that step ended was not escalated and already carries\n * `escalated: 'false'`.\n *\n * On an aggregate row every value arrives as TEXT: `aggregate`'s `groupBy`\n * emits `data->>'field'` whatever the field's declared type\n * (`aggregate-compiler.ts`), so a BOOLEAN comes back as `'true'`. A record\n * (`list-tickets`' rows) carries the boolean itself: both are read, so the\n * MCP tools and the dashboard share this one predicate (D13).\n */\nexport function isUnautomatedTriage(decision: { escalated?: unknown; status?: unknown }): boolean {\n return (\n decision.escalated === 'true' || decision.escalated === true || decision.status === 'error'\n );\n}\n\n/** The `count` metric of an aggregate row; `0` when absent or not a number. */\nexport function countOf(row: AggregateRow): number {\n return Number(row['count']) || 0;\n}\n\n/**\n * Which bucket one `{status, autoSendDecision, outcome}` group falls in — the\n * partition documented in this file's header. `null` is \"outside the ratio\n * entirely\": a `test_draft` row is an operator's essay, not a customer\n * request anybody answered — counting it as human work would sabotage the\n * rate, and as in-progress would show a run forever in flight.\n *\n * Takes the row rather than three positional arguments: four callers read the\n * same fields, and a third `unknown` in a row of `unknown`s is the kind of\n * signature where an argument silently swaps places.\n */\nfunction outcomeOf(row: AggregateRow): keyof OutcomeTotals | null {\n const status = row['status'];\n const autoSendDecision = row['autoSendDecision'];\n // Both are outside the ratio, for the same arithmetic reason: neither row\n // stands for a customer request anybody answered. A `test_draft` is an\n // operator's essay; a `superseded` draft was replaced because the customer\n // wrote again, and the replacement carries that request's outcome — counting\n // the replaced row too would put one request in the denominator twice.\n if (status === 'test_draft' || status === 'superseded') return null;\n if (status === 'sent') return 'auto';\n if (status === 'no_reply_needed') return 'noReplyNeeded';\n // A technical miss is a HAND-OFF, since 24/09/2026 on both paths that write\n // it: `triage-tick`'s `finalizeFailedResponse` always escalated the ticket\n // straight afterwards, and `sweep`'s orphaned-pending reclaim now does too\n // (it used to flip the row and tell nobody, which is what made this bucket\n // impossible to count either way). A drafting outage must make the rate\n // FALL; `countFailed` keeps it sayable by name.\n if (status === 'failed') return 'human';\n // A terminal status wins over the outcome, and not only for tidiness:\n // `foldHumanReasons` names the reason after the door the row LEFT by, and\n // a draft held then invalidated left through the invalidation. Both land on\n // `human`, so the ratio itself is indifferent to the order.\n if (status === 'invalidated' || status === 'expired') return 'human';\n\n const outcome = row['outcome'];\n if (typeof outcome === 'string' && HUMAN_OUTCOMES.has(outcome)) return 'human';\n if (outcome === 'no_reply_needed') return 'noReplyNeeded';\n if (outcome === 'triaged_only') return null;\n\n return autoSendDecision === 'hold' ? 'human' : 'inProgress';\n}\n\n/**\n * Folds a `groupBy: ['status', 'autoSendDecision', 'outcome']` result — with\n * or without a `bucket`, which only adds rows — into the page's five\n * outcomes, plus the `triage-decision` rows for the demandes that never\n * reached a draft.\n *\n * `triageRows` defaults to empty so a caller that only has response rows\n * (the comparison window before the second aggregate landed, a test) gets the\n * response-only fold rather than a type error.\n */\nexport function foldOutcomes(rows: AggregateRow[], triageRows: AggregateRow[] = []): OutcomeTotals {\n const totals = { ...EMPTY_TOTALS };\n for (const row of rows) {\n const outcome = outcomeOf(row);\n if (outcome !== null) totals[outcome] += countOf(row);\n }\n for (const row of triageRows) {\n if (isUnautomatedTriage(row)) totals.human += countOf(row);\n }\n return totals;\n}\n\n/** Demandes whose outcome is settled — the ratio's denominator. */\nexport function settledCount(totals: OutcomeTotals): number {\n return totals.auto + totals.human;\n}\n\n/**\n * `auto / (auto + human)`, or `NaN` when nothing settled — an empty\n * denominator is not a measured zero (this kit's own \"0/0 must not read as\n * 0 %\" contract, `pipeline/stats.ts`).\n */\nexport function autonomyRate(totals: OutcomeTotals): number {\n const settled = settledCount(totals);\n return settled > 0 ? totals.auto / settled : Number.NaN;\n}\n\nexport interface DailyOutcome {\n day: string;\n auto: number;\n human: number;\n /** `auto / (auto + human)` for that day, or `null` on a day that settled nothing — a gap in the line, not a zero. */\n rate: number | null;\n // ChartKit's `ChartRow` shape (`Record<string, string | number | null | undefined>`) — see pipeline/stats.ts's identical note.\n [key: string]: string | number | null;\n}\n\n/**\n * The same fold, kept per bucket: one row per day (or week) with both sides\n * of the ratio and the ratio itself, so the card can draw the volume and the\n * rate from a single series.\n */\nexport function foldDailyOutcomes(\n rows: AggregateRow[],\n triageRows: AggregateRow[] = [],\n): DailyOutcome[] {\n const byDay = new Map<string, OutcomeTotals>();\n const totalsFor = (day: string): OutcomeTotals => {\n const existing = byDay.get(day);\n if (existing !== undefined) return existing;\n const fresh = { ...EMPTY_TOTALS };\n byDay.set(day, fresh);\n return fresh;\n };\n\n for (const row of rows) {\n const outcome = outcomeOf(row);\n if (outcome === null) continue;\n totalsFor(bucketDay(row))[outcome] += countOf(row);\n }\n // Bucketed on `decidedAt`, not `generatedAt` — a demande handed over at\n // triage has no generation to date it by. The two windows can therefore\n // disagree at their edges by one bucket, which is the same asymmetry\n // `foldCategoryOutcomes` carries and for the same reason.\n for (const row of triageRows) {\n if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);\n }\n\n return [...byDay.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([day, totals]) => ({\n day,\n auto: totals.auto,\n human: totals.human,\n rate: settledCount(totals) > 0 ? autonomyRate(totals) : null,\n }));\n}\n\n/**\n * Days the aggregate returned no row for are real zeros here — nothing was\n * queued that day — unlike the social dashboard's own gaps, which mean \"Meta\n * did not measure\". Filling them keeps the bars on a true calendar axis\n * instead of squeezing a quiet week into the same width as a busy one.\n * Applied to daily buckets only; a weekly bucket's label is the week start,\n * which this function has no business inventing.\n */\nexport function fillMissingDays(\n series: DailyOutcome[],\n fromIso: string,\n toIso: string,\n): DailyOutcome[] {\n const from = Date.parse(fromIso.slice(0, 10));\n const to = Date.parse(toIso.slice(0, 10));\n if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;\n\n const measured = new Map(series.map((point) => [point.day, point]));\n const filled: DailyOutcome[] = [];\n for (let t = from; t <= to; t += 86_400_000) {\n const day = new Date(t).toISOString().slice(0, 10);\n filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });\n }\n return filled;\n}\n\nexport type SignalLevel = 'creuser' | 'info';\n\nexport interface Signal {\n level: SignalLevel;\n text: string;\n}\n\n/** A rate difference in POINTS — the honest unit for two percentages, where a relative delta (\"+22 % vs 28 %\") reads as a third, invented number. */\nexport function ratePoints(rate: number, compareRate: number): number | null {\n return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;\n}\n\n/** Below this many settled demandes a comparison is noise, not a trend. */\nconst SIGNAL_MIN_VOLUME = 20;\n\n/** A rate moving by less than this many points is not worth a line on the page. */\nconst SIGNAL_MIN_POINTS = 3;\n\n/**\n * What the numbers above are worth reading out loud — the social dashboard's\n * own \"Signaux à surveiller\", same two levels (\"À creuser\" / \"Info\") and\n * same rule: say the thing, then say what it is measured against.\n */\nexport function dashboardSignals(\n totals: OutcomeTotals,\n compare: OutcomeTotals | null,\n failed = 0,\n): Signal[] {\n const signals: Signal[] = [];\n const settled = settledCount(totals);\n const rate = autonomyRate(totals);\n\n if (\n compare !== null &&\n settled >= SIGNAL_MIN_VOLUME &&\n settledCount(compare) >= SIGNAL_MIN_VOLUME\n ) {\n const points = ratePoints(rate, autonomyRate(compare));\n if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {\n const move = points < 0 ? 'recule' : 'progresse';\n signals.push({\n level: points < 0 ? 'creuser' : 'info',\n text: `Le taux d’autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport à la période précédente.`,\n });\n }\n }\n\n // Counted inside `human` since 24/09/2026, so it is stated as what it costs\n // rather than as a figure outside the ratio.\n if (failed > 0) {\n signals.push({\n level: 'creuser',\n text: `${failed} génération${failed > 1 ? 's ont' : ' a'} échoué techniquement : ${\n failed > 1 ? 'ces demandes n’ont' : 'cette demande n’a'\n } jamais eu de brouillon et ${failed > 1 ? 'sont retombées' : 'est retombée'} sur un humain.`,\n });\n }\n\n if (totals.inProgress > 0) {\n signals.push({\n level: 'info',\n text: `${totals.inProgress} réponse${totals.inProgress > 1 ? 's sont' : ' est'} encore en cours : ${\n totals.inProgress > 1 ? 'elles ne comptent' : 'elle ne compte'\n } dans aucun des deux camps.`,\n });\n }\n\n if (totals.noReplyNeeded > 0) {\n signals.push({\n level: 'info',\n text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? 's' : ''} ne nécessitai${\n totals.noReplyNeeded > 1 ? 'ent' : 't'\n } aucune réponse : hors du taux d’autonomie.`,\n });\n }\n\n if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {\n signals.push({\n level: 'info',\n text: 'La période précédente compte trop peu de demandes réglées pour que la comparaison veuille dire quelque chose.',\n });\n }\n\n return signals;\n}\n\nexport interface HumanReasons {\n /** The judge or a guardrail kept the draft back — it exists, tagged, waiting for someone. */\n blocked: number;\n /** An agent answered before the draft could be served. */\n invalidated: number;\n /** The serving window closed on an unused draft. */\n expired: number;\n /** Handed over at triage: escalated, or a triage error that escalated the ticket. No draft was ever written. */\n escalatedNoDraft: number;\n /** The generation itself failed, and the ticket was escalated as a result. */\n failed: number;\n}\n\n/**\n * Why the human side of the ratio is the size it is — the same\n * `groupBy: ['status', 'autoSendDecision']` rows the totals come from, split\n * along the three ways `outcomeOf` can land on `human`. No extra round trip.\n *\n * A DRAFT-LESS ESCALATION IS ITS OWN REASON, not a slice of `blocked`: the\n * two say different things to an operator. `blocked` is \"the pipeline wrote\n * an answer and would not send it\", `escalatedNoDraft` is \"the pipeline never\n * tried\". It comes from the triage rows, which is why this takes them — an\n * earlier version of this note claimed the join was impossible per response;\n * it is, but no join is needed, because the two families never overlap.\n *\n * The four reasons add back up to `foldOutcomes(...).human` exactly — a\n * reason is a split, never a second count. Its own test asserts that.\n */\nexport function foldHumanReasons(\n rows: AggregateRow[],\n triageRows: AggregateRow[] = [],\n): HumanReasons {\n const reasons: HumanReasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };\n for (const row of rows) {\n if (outcomeOf(row) !== 'human') continue;\n const count = countOf(row);\n if (row['status'] === 'invalidated') reasons.invalidated += count;\n else if (row['status'] === 'expired') reasons.expired += count;\n else if (row['status'] === 'failed') reasons.failed += count;\n else reasons.blocked += count;\n }\n for (const row of triageRows) {\n if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);\n }\n return reasons;\n}\n\nexport interface CategoryOutcomeBar {\n label: string;\n /** Triage decisions filed under the category — the volume that came IN. */\n total: number;\n auto: number;\n human: number;\n noReply: number;\n /** The rest of `total`: never drafted (escalated before generation, conversation already over), still in flight, or failed. */\n undrafted: number;\n}\n\nexport const CATEGORY_TOP_N = 10;\n\n/**\n * What kind of messages arrive, and who ends up answering each kind — the two\n * questions the volume-only breakdown could not answer on its own.\n *\n * TWO SOURCES, ON PURPOSE. The bar's LENGTH is `triage-decision` (every\n * message triaged, ~3× what the ratio sees); its SEGMENTS are\n * `generated-response` (only the demandes actually queued for a draft). The\n * gap between the two is real and is drawn, not hidden: `undrafted` is\n * whatever the triage counted that no outcome accounts for. Reading the\n * segments alone would silently shrink the page's view of the inbox; reading\n * the total alone was the previous chart, which said nothing about who\n * worked.\n *\n * The two windows are cut on different fields (`decidedAt` vs `generatedAt`),\n * so a message triaged just before the window and drafted just inside it can\n * push a category's segments past its total. `undrafted` floors at zero and\n * the total stretches to fit rather than drawing a bar longer than itself.\n */\nexport function foldCategoryOutcomes(\n triageRows: AggregateRow[],\n responseRows: AggregateRow[],\n categoryNames: Map<string, string>,\n topN = CATEGORY_TOP_N,\n): CategoryOutcomeBar[] {\n const byId = new Map<string, CategoryOutcomeBar>();\n const barFor = (id: unknown): CategoryOutcomeBar | null => {\n const name = typeof id === 'string' ? categoryNames.get(id) : undefined;\n // Same \"unknown is not zero\" rule as the volume-only breakdown: a category\n // the referential no longer resolves is dropped, never drawn unlabelled.\n if (name === undefined) return null;\n const existing = byId.get(id as string);\n if (existing !== undefined) return existing;\n const bar: CategoryOutcomeBar = {\n label: name,\n total: 0,\n auto: 0,\n human: 0,\n noReply: 0,\n undrafted: 0,\n };\n byId.set(id as string, bar);\n return bar;\n };\n\n for (const row of triageRows) {\n const bar = barFor(row['categoryId']);\n if (bar === null) continue;\n const count = countOf(row);\n bar.total += count;\n // The same draft-less escalations the ratio counts. They are part of the\n // bar's LENGTH either way; naming them moves them out of `undrafted`,\n // which lumps them with \"never tried, and nobody asked us to\".\n if (isUnautomatedTriage(row)) bar.human += count;\n }\n for (const row of responseRows) {\n const bar = barFor(row['categoryId']);\n if (bar === null) continue;\n const outcome = outcomeOf(row);\n const count = countOf(row);\n if (outcome === 'auto') bar.auto += count;\n else if (outcome === 'human') bar.human += count;\n else if (outcome === 'noReplyNeeded') bar.noReply += count;\n }\n\n const bars = [...byId.values()]\n .map((bar) => {\n const accounted = bar.auto + bar.human + bar.noReply;\n return {\n ...bar,\n total: Math.max(bar.total, accounted),\n undrafted: Math.max(0, bar.total - accounted),\n };\n })\n .filter((bar) => bar.total > 0)\n .sort((a, b) => b.total - a.total);\n\n if (bars.length <= topN + 1) return bars;\n\n const tail = bars.slice(topN).reduce(\n (sum, bar) => ({\n label: 'Autres',\n total: sum.total + bar.total,\n auto: sum.auto + bar.auto,\n human: sum.human + bar.human,\n noReply: sum.noReply + bar.noReply,\n undrafted: sum.undrafted + bar.undrafted,\n }),\n { label: 'Autres', total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 },\n );\n return [...bars.slice(0, topN), tail];\n}\n","/**\n * Reply delays (spec-delais-de-reponse-v1) — how long a customer waited for\n * the first answer to a turn, and who gave it.\n *\n * Pure: the vocabulary of the `reply-timing` record and the arithmetic over\n * it. This is the ONLY place that knows the bucket thresholds (§3) — the\n * record and the dashboard read them from here, and `ticket-stats` is to\n * read the same (§9).\n */\nimport type { AggregateRow } from './aggregate-row';\nimport type { AwaitingSince } from './conversation';\nimport { countOf } from './dashboard-stats';\n\nexport const RESPONDERS = ['ai', 'human', 'human_ai_assisted', 'other', 'none'] as const;\n\nexport type Responder = (typeof RESPONDERS)[number];\n\nexport const DELAY_BUCKETS = ['lt_5m', '5_15m', '15_60m', '1_4h', '4_24h', 'gt_24h'] as const;\n\nexport type DelayBucket = (typeof DELAY_BUCKETS)[number];\n\n/** Where each bucket starts, in seconds — same order as `DELAY_BUCKETS`, bounds inclusive on the left. */\nconst BUCKET_FLOORS_SECONDS = [0, 5 * 60, 15 * 60, 60 * 60, 4 * 3_600, 24 * 3_600];\n\n/** When the helpdesk is first re-read for an open turn (§5.3): `customerMessageAt` + 15 min. */\nexport const FIRST_CHECK_DELAY_MS = 15 * 60_000;\n\nexport function bucketFor(delaySeconds: number): DelayBucket {\n for (let index = DELAY_BUCKETS.length - 1; index > 0; index -= 1) {\n if (delaySeconds >= BUCKET_FLOORS_SECONDS[index]!) return DELAY_BUCKETS[index]!;\n }\n return DELAY_BUCKETS[0];\n}\n\n/**\n * One row per customer turn: the ticket and the first unanswered customer\n * message. The instant stands in for the id only when Gorgias gave none.\n */\nexport function turnKeyFor(ticketId: string, awaitingSince: AwaitingSince): string {\n return `${ticketId}:${awaitingSince.messageId ?? awaitingSince.at.toISOString()}`;\n}\n\n/**\n * The fields that close a turn. The delay floors at zero: the customer\n * message is timestamped by Gorgias and an AI send by our own clock, and a\n * few seconds of skew must not produce a negative wait.\n */\nexport function closingFields(\n customerMessageAt: Date,\n repliedAt: Date,\n responder: Responder,\n responderVia: string | null = null,\n): {\n repliedAt: Date;\n responder: Responder;\n responderVia: string | null;\n delaySeconds: number;\n delayBucket: DelayBucket;\n nextCheckAt: null;\n} {\n const delaySeconds = Math.max(\n 0,\n Math.round((repliedAt.getTime() - customerMessageAt.getTime()) / 1000),\n );\n return {\n repliedAt,\n responder,\n responderVia,\n delaySeconds,\n delayBucket: bucketFor(delaySeconds),\n nextCheckAt: null,\n };\n}\n\nexport interface ResponderTiming {\n /** Closed turns this responder answered (or, for `none`, left unanswered). */\n count: number;\n /** Exact mean delay, from `sum(delaySeconds)`; null with no timed turn — unmeasured is not zero. */\n avgSeconds: number | null;\n /** The bucket holding the 50th percentile: `aggregate` has no percentile, so the median is a bucket, never a second count. */\n medianBucket: DelayBucket | null;\n buckets: Record<DelayBucket, number>;\n}\n\n/**\n * Folds `aggregate` rows grouped by `REPLY_TIMING_GROUP_BY` with\n * `REPLY_TIMING_METRICS` (`dashboard-queries.ts`) into one entry per\n * responder. Rows with no responder are open turns and count nowhere.\n */\nexport function foldReplyTimings(rows: AggregateRow[]): Record<Responder, ResponderTiming> {\n return Object.fromEntries(\n RESPONDERS.map((responder) => [\n responder,\n timingOf(rows.filter((row) => row['responder'] === responder)),\n ]),\n ) as Record<Responder, ResponderTiming>;\n}\n\nfunction timingOf(rows: AggregateRow[]): ResponderTiming {\n const buckets = emptyBuckets();\n let count = 0;\n let timed = 0;\n let totalSeconds = 0;\n for (const row of rows) {\n const turns = countOf(row);\n count += turns;\n const bucket = row['delayBucket'];\n // A `none` turn has no delay: counted, never timed.\n if (!isDelayBucket(bucket)) continue;\n buckets[bucket] += turns;\n timed += turns;\n totalSeconds += Number(row['totalSeconds']) || 0;\n }\n return {\n count,\n avgSeconds: timed > 0 ? totalSeconds / timed : null,\n medianBucket: medianBucketOf(buckets, timed),\n buckets,\n };\n}\n\nfunction medianBucketOf(buckets: Record<DelayBucket, number>, timed: number): DelayBucket | null {\n let cumulative = 0;\n for (const bucket of DELAY_BUCKETS) {\n cumulative += buckets[bucket];\n if (timed > 0 && cumulative >= timed / 2) return bucket;\n }\n return null;\n}\n\nfunction emptyBuckets(): Record<DelayBucket, number> {\n return Object.fromEntries(DELAY_BUCKETS.map((bucket) => [bucket, 0])) as Record<\n DelayBucket,\n number\n >;\n}\n\nfunction isDelayBucket(value: unknown): value is DelayBucket {\n return (DELAY_BUCKETS as readonly unknown[]).includes(value);\n}\n","/**\n * Typed readers over the kit's own `AppApiRecord.data` blobs, plus the two\n * lookups the spec leaves genuinely unresolved (§3.4/§3.5 name the `agent`\n * and `category` records but never say who picks the drafting agent for a\n * ticket) — shared by `triage-tick` and `process-response` so both compute\n * the SAME agent/category resolution instead of two independently-drifting\n * copies.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport type { Classification } from '../domain';\nimport type { CategoryReferentialEntry, Outcome } from '../graph/state';\nimport { isOutcome } from '../graph/state';\nimport type { PromptRef, PromptTableKey } from '../domain/profile';\nimport type { Verdict } from '../domain/verdict';\nimport { isEvaluationVerdict } from '../domain/evaluation-verdict';\nimport { toDecisionOrigin, type DecisionOrigin } from '../domain/origin';\nimport type { PromptNameConfig } from '../prompts/slots';\nimport { resolvePromptName } from '../prompts/slots';\nimport type { NodePromptSettings, SupportKitSettings } from '../settings/to-profile';\nimport type { SupportKitApi } from '../adapters/api';\nimport type { DiffToken } from './response-comparison-diff';\nimport type { TracedInputMessage } from './traced-input';\n\nexport interface AgentRecord {\n id: string;\n name: string;\n provider: string;\n modelId: string;\n status: 'default' | 'available' | 'archived';\n promptName: string;\n promptLabel: string | null;\n promptVersion: number | null;\n systemPromptSnapshot: string | null;\n}\n\nexport interface CategoryRecord {\n id: string;\n name: string;\n tagName: string;\n agentId: string | null;\n groupId: string | null;\n order: number;\n extraTags: string[];\n /** The short definition triage shows the model; `examples` is sample messages. See `toCategoryReferential`. */\n description: string | null;\n examples: string | null;\n autoReplyEnabled: boolean;\n /** T26 addition — CategoriesPage's own toggle; ext-categories filters on this but never needed it typed. */\n fastResponseEnabled: boolean;\n /** spec-gorgias-followup-webhook-v1 §7.1 — the follow-up opt-in, read by G7 and by §7.3's send policy. */\n followupFastResponseEnabled: boolean;\n followupAutoReplyEnabled: boolean;\n}\n\n/** T24 addition — `ext-categories`' group-then-order-then-name sort key (§5.2). */\nexport interface CategoryGroupRecord {\n id: string;\n name: string;\n order: number;\n}\n\nexport function toAgent(record: AppApiRecord): AgentRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n name: (data.name as string) ?? '',\n provider: (data.provider as string) ?? 'openai',\n modelId: (data.modelId as string) ?? '',\n status: (data.status as AgentRecord['status']) ?? 'available',\n promptName: (data.promptName as string) ?? '',\n promptLabel: (data.promptLabel as string | null) ?? null,\n promptVersion: (data.promptVersion as number | null) ?? null,\n systemPromptSnapshot: (data.systemPromptSnapshot as string | null) ?? null,\n };\n}\n\nexport function toCategory(record: AppApiRecord): CategoryRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n name: (data.name as string) ?? '',\n tagName: (data.tagName as string) ?? '',\n agentId: (data.agentId as string | null) ?? null,\n groupId: (data.groupId as string | null) ?? null,\n order: (data.order as number | undefined) ?? 0,\n extraTags: (data.extraTags as string[] | undefined) ?? [],\n description: (data.description as string | null) ?? null,\n examples: (data.examples as string | null) ?? null,\n autoReplyEnabled: (data.autoReplyEnabled as boolean | undefined) ?? false,\n fastResponseEnabled: (data.fastResponseEnabled as boolean | undefined) ?? false,\n followupFastResponseEnabled: (data.followupFastResponseEnabled as boolean | undefined) ?? false,\n followupAutoReplyEnabled: (data.followupAutoReplyEnabled as boolean | undefined) ?? false,\n };\n}\n\n/** T24 addition — `ext-categories` needs `group.order` for its composite sort (§5.2). */\nexport function toCategoryGroup(record: AppApiRecord): CategoryGroupRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n name: (data.name as string) ?? '',\n order: (data.order as number | undefined) ?? 0,\n };\n}\n\n/** T24 hardening (L7) — `ext-fast-response-check`'s own typed read of `generated-response.data`, replacing ~15 inline casts scattered across that file. */\nexport interface GeneratedResponseRecord {\n id: string;\n ticketId: string;\n status: string;\n expiresAt: string | null;\n generatedMessageCount: number;\n generatedLastMessageAt: string | null;\n generatedAt: string | null;\n responseText: string | null;\n categoryId: string | null;\n agentId: string | null;\n langfuseTraceId: string | null;\n langfuseObservationId: string | null;\n promptName: string | null;\n promptVersion: number | null;\n servedCount: number;\n servedTo: Array<{ user: string; at: string }>;\n /**\n * The messages the drafting call was given — rendered system prompt first,\n * then the customer's turns (`functions/traced-input.ts`). Empty on every\n * row written before that capture existed, and on rows whose run failed\n * before drafting: the ticket timeline falls back to the conversation\n * itself in that case (spec-vue-tickets-unifiee-v1 §4.2).\n */\n tracedInput: TracedInputMessage[];\n /** The tool calls the writer made, `[{name, arguments, observation}]` (§3.4) — the timeline's \"Rédaction\" step lists them. */\n sources: Array<{ name: string; arguments: Record<string, unknown>; observation: string }>;\n /**\n * Typed against `domain/verdict.ts`'s own `Verdict` shape (T26 rework, pass\n * 2) rather than `{verdict?: unknown; reason?: string; confidence?: unknown;\n * status?: unknown}` — PipelinePage now renders `.verdict`/`.confidence`/\n * `.status` directly (the \"Verdict\"/\"Confiance\" columns), so a malformed\n * value on the wire must not reach the page typed as `unknown`.\n */\n verdict: Verdict | null;\n /** The judging call's Langfuse observation — `null` when nothing was traced or on a verdict older than the capture. Not part of `verdict`: see `toEvaluationObservationId`. */\n evaluationObservationId: string | null;\n /** T26 rework (pass 2, A1) — PipelinePage's hold-reason tally groups on this, not `verdict.reason` (a free-text judge justification, never a stable key). */\n guardrailHits: string[];\n /**\n * Non-null on the holds whose reason was rebuilt from Gorgias after the\n * fact, never on one the run recorded itself (28/09/2026). The timeline\n * says so out loud: the deduction used TODAY's settings, which are not\n * necessarily the ones the run applied.\n */\n guardrailHitsReconstructedAt: string | null;\n /**\n * Which exit `runTicket` took (21/09/2026). `null` on rows written before\n * the field existed — `status` alone cannot stand in for it, since `ready`\n * covers `ready`, `needs_human`, `guardrail_hold` and `awaiting_approval`\n * alike.\n */\n outcome: Outcome;\n /** T26 additions — PipelinePage's queue/stats need these; ext-fast-response-check never read them. */\n triageDecisionId: string | null;\n /** Publication MODE — `'whatsapp'` or `'email'`. For where the customer wrote from, read `sourceChannel`. */\n channel: string | null;\n /** The channel Gorgias reported. `null` on rows written before 28/09/2026. */\n sourceChannel: string | null;\n /** Why auto-send did not apply, when the settings cannot say (`'no_publication_path'`). `null` otherwise. */\n ineligibleReason: string | null;\n autoSendDecision: 'auto' | 'hold' | null;\n sentAt: string | null;\n /** T26 rework, pass 2 addition — PipelinePage's detail panel needs the Gorgias message id the reply was posted as (§3.4's own field; legacy `gorgias_message_id`). */\n sentMessageId: string | null;\n error: string | null;\n /** Which pass opened it (§7.2) — `'triage'` on every row older than the field. §7.3 reads it to pick the governing auto-reply flag. */\n origin: DecisionOrigin;\n}\n\n/** T26 addition — EscalationsPage's own typed reader; no prior caller needed the whole `triage-decision` shape. */\nexport interface TriageDecisionRecord {\n id: string;\n ticketId: string;\n /** Frozen at write time — `null` on decisions older than the field. */\n ticketUrl: string | null;\n decidedAt: string | null;\n categoryId: string | null;\n tag: string | null;\n confidence: 'high' | 'low' | null;\n reasoning: string | null;\n conversationOver: boolean;\n escalated: boolean;\n escalationConfidence: 'high' | 'low' | null;\n escalationReasoning: string | null;\n status: 'ok' | 'error' | null;\n error: string | null;\n runId: string | null;\n subjectRenamed: boolean;\n /** Which pass wrote it (§7.2) — `'triage'` on every row older than the field. */\n origin: DecisionOrigin;\n /** The triage call's Langfuse trace (D11). `null` on a decision older than the field, or when nothing was traced. */\n langfuseTraceId: string | null;\n /** Triage then escalation observation ids — NOT positional, the triage one may be absent. Empty when nothing was traced. */\n langfuseObservationIds: string[];\n}\n\nexport function toTriageDecision(record: AppApiRecord): TriageDecisionRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n ticketId: (data.ticketId as string) ?? '',\n ticketUrl: (data.ticketUrl as string | null) ?? null,\n decidedAt: (data.decidedAt as string | null) ?? null,\n categoryId: (data.categoryId as string | null) ?? null,\n tag: (data.tag as string | null) ?? null,\n confidence: (data.confidence as 'high' | 'low' | null) ?? null,\n reasoning: (data.reasoning as string | null) ?? null,\n conversationOver: (data.conversationOver as boolean | undefined) ?? false,\n escalated: (data.escalated as boolean | undefined) ?? false,\n escalationConfidence: (data.escalationConfidence as 'high' | 'low' | null) ?? null,\n escalationReasoning: (data.escalationReasoning as string | null) ?? null,\n status: (data.status as 'ok' | 'error' | null) ?? null,\n error: (data.error as string | null) ?? null,\n runId: (data.runId as string | null) ?? null,\n subjectRenamed: (data.subjectRenamed as boolean | undefined) ?? false,\n origin: toDecisionOrigin(data.origin),\n langfuseTraceId: (data.langfuseTraceId as string | null) ?? null,\n langfuseObservationIds: Array.isArray(data.langfuseObservationIds)\n ? data.langfuseObservationIds.filter((id): id is string => typeof id === 'string' && id !== '')\n : [],\n };\n}\n\n/**\n * `generated-response.data.verdict` reaches the UI as untrusted JSONB (same\n * boundary `status/machine.ts`'s `isGeneratedResponseStatus` guards) — a\n * value written by an older kit version, or hand-edited, can carry anything.\n * A malformed shape degrades to the documented \"evaluation error\" sentinel\n * instead of a `TypeError` deep inside a table cell.\n */\nfunction toVerdict(raw: unknown): Verdict | null {\n if (raw === null || typeof raw !== 'object') return null;\n const data = raw as Record<string, unknown>;\n const verdict = isEvaluationVerdict(data.verdict) ? data.verdict : null;\n const confidence = typeof data.confidence === 'number' ? data.confidence : null;\n const reason = typeof data.reason === 'string' ? data.reason : '';\n const status = data.status === 'success' || data.status === 'error' ? data.status : 'error';\n return { verdict, confidence, reason, status };\n}\n\n/**\n * The judging call's own Langfuse observation, kept off `verdict` on purpose:\n * the UI builds its \"Trace évaluation\" link from `verdict.observationId`, and\n * the evaluation is a trace of its own, so pairing that id with the draft's\n * trace id would break the highlight. Only explain-ticket reads this one.\n */\nfunction toEvaluationObservationId(raw: unknown): string | null {\n if (raw === null || typeof raw !== 'object') return null;\n const observationId = (raw as Record<string, unknown>).observationId;\n return typeof observationId === 'string' && observationId !== '' ? observationId : null;\n}\n\nexport function toGeneratedResponse(record: AppApiRecord): GeneratedResponseRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n ticketId: (data.ticketId as string) ?? '',\n status: (data.status as string) ?? '',\n expiresAt: (data.expiresAt as string | null) ?? null,\n generatedMessageCount: (data.generatedMessageCount as number | undefined) ?? 0,\n generatedLastMessageAt: (data.generatedLastMessageAt as string | null) ?? null,\n generatedAt: (data.generatedAt as string | null) ?? null,\n responseText: (data.responseText as string | null) ?? null,\n categoryId: (data.categoryId as string | null) ?? null,\n agentId: (data.agentId as string | null) ?? null,\n langfuseTraceId: (data.langfuseTraceId as string | null) ?? null,\n langfuseObservationId: (data.langfuseObservationId as string | null) ?? null,\n promptName: (data.promptName as string | null) ?? null,\n promptVersion: (data.promptVersion as number | null) ?? null,\n servedCount: (data.servedCount as number | undefined) ?? 0,\n servedTo: (data.servedTo as Array<{ user: string; at: string }> | undefined) ?? [],\n tracedInput: Array.isArray(data.tracedInput) ? (data.tracedInput as TracedInputMessage[]) : [],\n sources: Array.isArray(data.sources) ? (data.sources as GeneratedResponseRecord['sources']) : [],\n verdict: toVerdict(data.verdict),\n evaluationObservationId: toEvaluationObservationId(data.verdict),\n guardrailHits: (data.guardrailHits as string[] | undefined) ?? [],\n guardrailHitsReconstructedAt: (data.guardrailHitsReconstructedAt as string | null) ?? null,\n outcome: isOutcome(data.outcome) ? data.outcome : null,\n triageDecisionId: (data.triageDecisionId as string | null) ?? null,\n channel: (data.channel as string | null) ?? null,\n sourceChannel: (data.sourceChannel as string | null) ?? null,\n ineligibleReason: (data.ineligibleReason as string | null) ?? null,\n autoSendDecision: (data.autoSendDecision as 'auto' | 'hold' | null | undefined) ?? null,\n sentAt: (data.sentAt as string | null) ?? null,\n sentMessageId: (data.sentMessageId as string | null) ?? null,\n error: (data.error as string | null) ?? null,\n origin: toDecisionOrigin(data.origin),\n };\n}\n\n/** T27 addition — `CorrectionsPage`'s own typed reader; no prior caller needed the whole `response-comparison` shape. */\nexport interface ResponseComparisonRecord {\n id: string;\n generatedText: string | null;\n sentText: string;\n capturedAt: string;\n ticketId: string | null;\n ticketUrl: string;\n agentId: string | null;\n langfuseTraceId: string | null;\n langfuseObservationId: string | null;\n promptName: string | null;\n promptVersion: number | null;\n conversationMessages: Array<{ role: string; content: string }>;\n /** Word-level diff, computed at write time by `ext-response-comparison` (`response-comparison-diff.ts`'s `computeWordDiff`) — `null` on a row captured before that field existed, or when generation/sent text were identical. */\n diff: DiffToken[] | null;\n}\n\nexport function toResponseComparison(record: AppApiRecord): ResponseComparisonRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n generatedText: (data.generatedText as string | null) ?? null,\n sentText: (data.sentText as string) ?? '',\n capturedAt: (data.capturedAt as string) ?? '',\n ticketId: (data.ticketId as string | null) ?? null,\n ticketUrl: (data.ticketUrl as string) ?? '',\n agentId: (data.agentId as string | null) ?? null,\n langfuseTraceId: (data.langfuseTraceId as string | null) ?? null,\n langfuseObservationId: (data.langfuseObservationId as string | null) ?? null,\n promptName: (data.promptName as string | null) ?? null,\n promptVersion: (data.promptVersion as number | null) ?? null,\n conversationMessages: (data.conversationMessages as Array<{ role: string; content: string }> | undefined) ?? [],\n diff: (data.diff as DiffToken[] | null | undefined) ?? null,\n };\n}\n\n/** T27 addition — `CorrectionsPage`'s own typed reader over `run-diff-analysis`'s output record. */\nexport interface DiffAnalysisRecord {\n id: string;\n agentId: string;\n promptName: string;\n promptVersion: number;\n points: string[];\n uniqueKey: string;\n}\n\nexport function toDiffAnalysis(record: AppApiRecord): DiffAnalysisRecord {\n const data = record.data as Record<string, unknown>;\n return {\n id: record.id,\n agentId: (data.agentId as string) ?? '',\n promptName: (data.promptName as string) ?? '',\n promptVersion: (data.promptVersion as number) ?? 0,\n points: (data.points as string[] | undefined) ?? [],\n uniqueKey: (data.uniqueKey as string) ?? '',\n };\n}\n\n/** High limit: the taxonomy is operator-curated, never large. */\nexport const CATEGORY_PAGE_SIZE = 500;\n\n/** Same reasoning: agents are few and operator-created. */\nexport const AGENT_PAGE_SIZE = 500;\n\n/**\n * The category list's order: ungrouped first (`-Infinity`), then group order,\n * category order, name.\n */\nexport function compareByGroupThenCategory(\n a: { groupOrder: number; category: Pick<CategoryRecord, 'order' | 'name'> },\n b: { groupOrder: number; category: Pick<CategoryRecord, 'order' | 'name'> },\n): number {\n if (a.groupOrder !== b.groupOrder) return a.groupOrder < b.groupOrder ? -1 : 1;\n return a.category.order - b.category.order || a.category.name.localeCompare(b.category.name);\n}\n\n/** Every `agent` row. */\nexport async function listAgents(api: Pick<SupportKitApi, 'list'>): Promise<AgentRecord[]> {\n const page = await api.list('agent', { limit: AGENT_PAGE_SIZE });\n return page.items.map(toAgent);\n}\n\n/** Every `category` row, for the triage referential and per-ticket tag matching. */\nexport async function listCategories(api: Pick<SupportKitApi, 'list'>): Promise<CategoryRecord[]> {\n const page = await api.list('category', { limit: CATEGORY_PAGE_SIZE });\n return page.items.map(toCategory);\n}\n\n/** `triage-decision` rows, newest first. */\nexport const NEWEST_DECISION_FIRST = JSON.stringify([{ field: 'decidedAt', direction: 'desc' }]);\n\nconst NEWEST_RESPONSE_FIRST = JSON.stringify([{ field: 'generatedAt', direction: 'desc' }]);\n\n/** A test draft is an operator's essay on the test bench, not an answer the ticket got. */\nconst ANSWERS_ONLY = { status: { neq: 'test_draft' } };\n\n/** The answers a ticket got, newest first, test drafts left out. */\nexport async function listTicketResponses(\n api: Pick<SupportKitApi, 'list'>,\n ticketId: string,\n limit: number,\n): Promise<GeneratedResponseRecord[]> {\n const page = await api.list('generated-response', {\n filter: { ticketId, ...ANSWERS_ONLY },\n sort: NEWEST_RESPONSE_FIRST,\n limit,\n });\n return page.items.map(toGeneratedResponse);\n}\n\n/** The latest answer of each ticket that got one, test drafts left out — one read for all of them. */\nexport async function latestResponsesByTicket(\n api: Pick<SupportKitApi, 'list'>,\n ticketIds: string[],\n): Promise<Map<string, GeneratedResponseRecord>> {\n const newest = await newestPerTicket(api, {\n objectKey: 'generated-response',\n ticketIds,\n filter: ANSWERS_ONLY,\n sort: NEWEST_RESPONSE_FIRST,\n });\n return new Map([...newest].map(([ticketId, record]) => [ticketId, toGeneratedResponse(record)]));\n}\n\n/** Records per read of `newestPerTicket`: room for a few per ticket of a 50-decision batch. */\nconst NEWEST_PER_TICKET_READ_SIZE = 200;\n\ninterface NewestPerTicketQuery {\n objectKey: string;\n ticketIds: string[];\n filter: Record<string, unknown>;\n /** JSON sort spec, newest record first. */\n sort: string;\n}\n\n/**\n * The newest record of each ticket among `ticketIds` that `filter` matches, read\n * with `ticketId in [...]` sorted newest first — so the first record seen for a\n * ticket is its newest. One read covers a batch; it pages on only while some\n * ticket is still unseen and records remain.\n */\nexport async function newestPerTicket(\n api: Pick<SupportKitApi, 'list'>,\n { objectKey, ticketIds, filter, sort }: NewestPerTicketQuery,\n): Promise<Map<string, AppApiRecord>> {\n const wanted = [...new Set(ticketIds)];\n const newest = new Map<string, AppApiRecord>();\n if (wanted.length === 0) return newest;\n\n let cursor: string | null = null;\n do {\n const page = await api.list(objectKey, {\n filter: { ...filter, ticketId: { in: wanted } },\n sort,\n limit: NEWEST_PER_TICKET_READ_SIZE,\n ...(cursor === null ? {} : { cursor }),\n });\n for (const record of page.items) {\n const ticketId = String(record.data['ticketId']);\n if (!newest.has(ticketId)) newest.set(ticketId, record);\n }\n cursor = page.nextCursor;\n } while (cursor !== null && newest.size < wanted.length);\n return newest;\n}\n\n/** Exact, case-sensitive match against `Classification.category` (`category.tagName`'s own contract). */\nexport function findCategoryByTag(categories: CategoryRecord[], tag: string): CategoryRecord | null {\n return categories.find((c) => c.tagName === tag) ?? null;\n}\n\n/**\n * The category sheet triage serialises into `{{categories}}`\n * (`graph/nodes/triage.ts`'s `renderCategories`).\n *\n * `desc` falls back in that order for a reason. Before `category.description`\n * existed, `desc` was filled with `examples` — so a tenant with examples sent\n * THE SAME TEXT TWICE per category, once as `desc` and once as `examples`\n * (measured at ~7 200 referential tokens per triaged ticket instead of ~3 600\n * on a 33-category app). The legacy backoffice had both fields and sent two\n * DIFFERENT texts; the kit lost the field and papered over it by duplicating.\n *\n * Keeping `examples` as the second rung is what makes this safe to ship\n * before any tenant has filled the new field: behaviour is unchanged until\n * `description` is set, and the duplication disappears the moment it is.\n */\nexport function toCategoryReferential(categories: CategoryRecord[]): CategoryReferentialEntry[] {\n return categories.map((c) => ({\n name: c.name,\n tag: c.tagName,\n desc: c.description ?? c.examples ?? c.name,\n ...(c.examples ? { examples: c.examples } : {}),\n }));\n}\n\n/**\n * Who drafts this ticket (nobody else in the kit decides this today):\n * the category's own `agentId` if triage matched one, else the single\n * `status: 'default'` agent, else `null` — a ticket with neither has no\n * agent to draft with, and `draftPromptRefFor` below turns that into an\n * unresolvable prompt name rather than a silent guess.\n */\nexport async function resolveDraftAgent(api: SupportKitApi, categoryAgentId: string | null): Promise<AgentRecord | null> {\n if (categoryAgentId) {\n try {\n return toAgent(await api.get('agent', categoryAgentId));\n } catch {\n // Dangling relation (deleted agent) — fall through to the default agent below.\n }\n }\n const page = await api.list('agent', { filter: { status: 'default' }, limit: 1 });\n const record = page.items[0];\n return record ? toAgent(record) : null;\n}\n\n/**\n * `AgentProfile.prompts.draft` for the resolved agent (§3.4's own binding:\n * name + label + level-3 fallback). `agent: null` (no default agent\n * configured, no category override) has no real prompt to bind — the\n * sentinel name below documents that loudly instead of resolving to some\n * other tenant's prompt by accident; a run built on it fails at prompt\n * resolution or drafts nothing, which is the documented, honest outcome for\n * \"no agent configured\" rather than a silent default.\n *\n * The sentinel is scoped by `config.promptPrefix` (H5, T25 review): it used\n * to be the literal `'support-kit/no-agent-configured'` — the kit's own\n * package name hardcoded into a runtime identifier, the exact pattern T20's\n * review eliminated for `targetRef` (the kit is never itself installed as\n * an app). It is also added to `mergeRole`'s `role.prompts` allowlist\n * (`pipeline.ts`) at the same scoped name, so resolving it degrades\n * cleanly to empty text (`PromptRef.fallback` is absent) instead of a\n * guaranteed, permanent 403 in a live pipeline's logs.\n */\nexport function draftPromptRefFor(agent: AgentRecord | null, config: PromptNameConfig): PromptRef {\n if (!agent) return { name: `${config.promptPrefix}no-agent-configured`, label: 'production' };\n return {\n name: agent.promptName,\n label: agent.promptLabel ?? 'production',\n ...(agent.systemPromptSnapshot ? { fallback: agent.systemPromptSnapshot } : {}),\n };\n}\n\n/**\n * `draftPromptRefFor` deferred until triage has named a category — the\n * binding `triage-tick` performs (`resolveDraftAgent(api, category?.agentId)`)\n * spread over the two functions that replay a graph in one call\n * (`graph-dry-run`, `test-agents`). Both used to resolve the writer BEFORE\n * the run, from the default agent alone, so a ticket triaged into a category\n * with its own agent still drafted with someone else's prompt — and an\n * install with no default agent at all failed in `draft` on the\n * `no-agent-configured` sentinel, whatever triage had found.\n */\nexport function draftRebinder(\n api: SupportKitApi,\n categories: CategoryRecord[],\n config: PromptNameConfig,\n): (classification: Classification | null) => Promise<PromptRef> {\n return async (classification) => {\n const category = classification ? findCategoryByTag(categories, classification.category) : null;\n return draftPromptRefFor(await resolveDraftAgent(api, category?.agentId ?? null), config);\n };\n}\n\n/**\n * The `AgentProfile.prompts` table (§3.7): the three operator-chosen names\n * plus the caller-supplied `draft` ref. `revise` has no entry: it re-runs\n * the writer with a fixed correction turn (`graph/revise.ts`), so the only\n * prompt it speaks with is `draft`'s own.\n *\n * The name of each operator-chosen ref comes from `nodes.<step>.prompt` — the\n * Langfuse prompt an operator picked on the SettingsPage, beside the model\n * for that same step. The slot-resolved name (`<promptPrefix><slot>`) is\n * only the placeholder for a step that is DISABLED: `AgentProfile.prompts`\n * is total over `NodeKey` while `AgentProfile.nodes` is not, so a step\n * nothing runs still needs an entry, and the derived name is the honest\n * \"what this step would have been called\" rather than an invented sentinel.\n * An ACTIVE step with no prompt never reaches here — `validateSettings`\n * refuses the run first.\n *\n * `resolvePromptName` therefore still owns name derivation, shared with\n * `mergeRole`'s `role.prompts` allowlist (T25) so the two cannot drift\n * apart on how a name is computed.\n *\n * `config.defaults.prompts` (§3.7 point 3) becomes each ref's\n * `PromptRef.fallback` — the level-3 text served when Langfuse AND the\n * `prompt-cache` mirror both come up empty (`resolver.ts`'s own ladder).\n * `draft` gets its fallback from the `agent` record's own\n * `systemPromptSnapshot` (`draftPromptRefFor`) instead, which is why it is\n * excluded from `PromptFallbackSlot`.\n */\nexport function buildPromptsTable(\n config: PromptNameConfig,\n draft: PromptRef,\n nodes: SupportKitSettings['nodes'],\n): Record<PromptTableKey, PromptRef> {\n const prompts = config.defaults?.prompts;\n return {\n triage: promptRefFor(nodes.triage, resolvePromptName('triage', config), prompts?.triage),\n escalate: promptRefFor(\n nodes.escalate,\n resolvePromptName('escalation', config),\n prompts?.escalation,\n ),\n evaluate: promptRefFor(\n nodes.evaluate,\n resolvePromptName('evaluation', config),\n prompts?.evaluation,\n ),\n draft,\n };\n}\n\n/** A step's prompt: the name and label its settings node chose, else `derivedName` and `production`. */\nexport function promptRefFor(\n node: { prompt?: NodePromptSettings } | null | undefined,\n derivedName: string,\n fallback?: string,\n): PromptRef {\n return {\n name: node?.prompt?.name ?? derivedName,\n label: node?.prompt?.label ?? 'production',\n ...(fallback ? { fallback } : {}),\n };\n}\n\n/** `id → name` for the referential, as the dashboard reads it (`useRecordList('category', { limit: 500 })`). */\nexport async function readCategoryNames(api: Pick<SupportKitApi, 'list'>): Promise<Map<string, string>> {\n const categories = await listCategories(api);\n return new Map(categories.map((category) => [category.id, category.name]));\n}\n","/**\n * The `aggregate` shapes the dashboard's figures are read from, owned here so\n * the browser page and the server-side MCP tools (`ticket-stats`) ask the\n * data API the SAME questions — the partition in `dashboard-stats.ts` only\n * means something over rows grouped this way (spec D13).\n */\n\nexport const OUTCOME_METRICS = [{ op: 'count' as const, as: 'count' }];\n\nexport const OUTCOME_GROUP_BY = ['status', 'autoSendDecision', 'outcome'];\n\n/** The same partition, kept per category — what feeds the breakdown's segments. */\nexport const CATEGORY_OUTCOME_GROUP_BY = ['categoryId', 'status', 'autoSendDecision', 'outcome'];\n\n/**\n * The other half of the denominator: demandes handed to a human AT TRIAGE,\n * which never produced a `generated-response` row to be counted through\n * (`eligibility.ts` declines to draft for an escalated ticket). Both fields\n * are needed — `isUnautomatedTriage` reads `escalated` for the nominal\n * escalation and `status` for a triage error, which escalates the ticket\n * without ever setting `escalated`.\n */\nexport const TRIAGE_HANDOFF_GROUP_BY = ['escalated', 'status'];\n\n/** The same hand-offs, kept per category — they move out of the bars' `undrafted` segment and into `human`. */\nexport const CATEGORY_TRIAGE_GROUP_BY = ['categoryId', 'escalated', 'status'];\n\n/**\n * spec-delais-de-reponse-v1 §7 — reply delays, per responder and bucket.\n * `sum`, not `avg`: a mean per (responder, bucket) group cannot be recombined\n * into the responder's mean, a sum over the count can — the same exact figure.\n */\nexport const REPLY_TIMING_GROUP_BY = ['responder', 'delayBucket'];\n\nexport const REPLY_TIMING_METRICS = [\n { op: 'count' as const, as: 'count' },\n { op: 'sum' as const, field: 'delaySeconds', as: 'totalSeconds' },\n];\n","/**\n * The handful of settings the ticket timeline needs to EXPLAIN why a reply\n * was not sent (21/09/2026).\n *\n * Deliberately not `settingsToProfile`: that mapper dereferences\n * `settings.nodes.triage.model` unconditionally and throws on the incomplete\n * blob a freshly installed app carries — `sweep.ts`'s own header documents\n * being bitten by exactly that. A ticket panel must degrade to \"no\n * explanation available\", never crash the page it is a sub-view of.\n *\n * What it does NOT re-implement: the two defaults (`DEFAULT_MIN_CONFIDENCE`,\n * `DEFAULT_ESCALATION_ENABLED`) and the audit-tag mapping (`toAuditTags`)\n * are imported from `settings/to-profile.ts`, so the numbers and the two\n * setting-key renames behind `sentTag`/`needsHumanTag` have one home. The\n * rest is a direct read of flat fields, with no logic to drift.\n *\n * This decides nothing. `isSendable`/`isAutoSendEligible` already decided,\n * on the server, and the outcome they produced is stored on the row; this\n * only turns that outcome into a sentence naming the setting behind it.\n */\nimport type { AuditTags } from '../graph/ports';\nimport { DEFAULT_AUTO_SEND_CHANNELS } from '../domain/profile';\nimport { toConversationEnd, type ConversationEndConfig } from './conversation-end';\nimport {\n DEFAULT_ESCALATION_ENABLED,\n DEFAULT_MIN_CONFIDENCE,\n toAuditTags,\n type SupportKitSettings,\n} from './to-profile';\n\nexport interface DeliveryPolicy {\n /** `nodes.evaluate.escalationEnabled` — whether a verdict needing a follow-up may still be sent. */\n followupSendable: boolean;\n /** `nodes.evaluate.minConfidence`, as a 0–1 ratio. */\n minConfidence: number;\n evaluateConfigured: boolean;\n autoSendEnabled: boolean;\n senderEmail: string | null;\n whatsappMode: string | null;\n /** `settings.autoSendChannels` — the allowlist `isAutoSendEligible` checked the ticket's channel against. */\n autoSendChannels: string[];\n /**\n * `settings.dryRun` — a trial run swaps both write ports for recorders\n * (`adapters/recording-ports.ts`), so it tags nothing and posts nothing.\n * The actions panel needs it to avoid crediting a trial with tags it only\n * WOULD have applied.\n */\n dryRun: boolean;\n audit: AuditTags;\n /** The end action as configured today — names the tag or the closure on a conversation judged finished. */\n conversationEnd?: ConversationEndConfig | null;\n}\n\nfunction evaluateNode(settings: SupportKitSettings): Record<string, unknown> | null {\n const node = (settings as { nodes?: { evaluate?: unknown } }).nodes?.evaluate;\n return node && typeof node === 'object' ? (node as Record<string, unknown>) : null;\n}\n\n/** `null` when the blob is unusable — the caller falls back to a generic message. */\nexport function toDeliveryPolicy(raw: unknown): DeliveryPolicy | null {\n if (!raw || typeof raw !== 'object') return null;\n const settings = raw as SupportKitSettings;\n const evaluate = evaluateNode(settings);\n const senderEmail = typeof settings.senderEmail === 'string' ? settings.senderEmail : '';\n return {\n followupSendable:\n typeof evaluate?.escalationEnabled === 'boolean' ? evaluate.escalationEnabled : DEFAULT_ESCALATION_ENABLED,\n minConfidence: typeof evaluate?.minConfidence === 'number' ? evaluate.minConfidence : DEFAULT_MIN_CONFIDENCE,\n evaluateConfigured: evaluate !== null,\n autoSendEnabled: settings.autoSendEnabled === true,\n senderEmail: senderEmail === '' ? null : senderEmail,\n whatsappMode: typeof settings.whatsappMode === 'string' ? settings.whatsappMode : null,\n autoSendChannels: Array.isArray(settings.autoSendChannels)\n ? settings.autoSendChannels\n : [...DEFAULT_AUTO_SEND_CHANNELS],\n dryRun: settings.dryRun === true,\n audit: toAuditTags(settings),\n conversationEnd: toConversationEnd(settings),\n };\n}\n","/**\n * `computeWordDiff` — a word-level diff between the agent's draft and what\n * a human actually sent, computed at WRITE time and stored on\n * `response-comparison.diff` (§3.4: \"diff JSON? — diff mot à mot, calculé\n * à l'écriture\"). §3.4 freezes the FIELD's existence, not its shape — this\n * shape is `ext-response-comparison`'s own choice (referenced, not\n * duplicated, by `run-diff-analysis.ts`'s own module doc).\n *\n * Algorithm: the same word-level LCS diff the legacy admin UI computed\n * on-the-fly for its rewrite-rate stats (`routes/admin.ts`'s\n * `serverWordDiff`) — tokenize on whitespace-PRESERVING `/(\\s+)/` (so a run\n * of spaces is its own token, and joining every token back together\n * reconstructs the original text exactly), then a standard\n * O(len(a)·len(b)) longest-common-subsequence backtrack. The kit computes\n * it once, at write time, rather than the legacy's every-read\n * recomputation, since the record now persists it.\n *\n * `op: 'insert'` marks a token present only in `sentText` (what the human\n * added); `'delete'` marks a token present only in `generatedText` (what\n * the human removed); `'equal'` is unchanged. `sentText` is reconstructed\n * by joining the `equal`+`insert` tokens in order; `generatedText` by\n * joining `equal`+`delete`.\n */\nexport type DiffOp = 'equal' | 'insert' | 'delete';\n\nexport interface DiffToken {\n op: DiffOp;\n text: string;\n}\n\nfunction tokenize(text: string | null | undefined): string[] {\n return (text ?? '').split(/(\\s+)/).filter((token) => token.length > 0);\n}\n\nexport function computeWordDiff(generatedText: string | null | undefined, sentText: string | null | undefined): DiffToken[] {\n const a = tokenize(generatedText);\n const b = tokenize(sentText);\n const m = a.length;\n const n = b.length;\n\n const dp: number[][] = Array.from({ length: m + 1 }, () => new Array<number>(n + 1).fill(0));\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n dp[i]![j] = a[i - 1] === b[j - 1] ? dp[i - 1]![j - 1]! + 1 : Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);\n }\n }\n\n const ops: DiffToken[] = [];\n let i = m;\n let j = n;\n while (i > 0 || j > 0) {\n if (i > 0 && j > 0 && a[i - 1] === b[j - 1]) {\n ops.push({ op: 'equal', text: a[i - 1]! });\n i--;\n j--;\n } else if (j > 0 && (i === 0 || dp[i]![j - 1]! >= dp[i - 1]![j]!)) {\n ops.push({ op: 'insert', text: b[j - 1]! });\n j--;\n } else {\n ops.push({ op: 'delete', text: a[i - 1]! });\n i--;\n }\n }\n\n return ops.reverse();\n}\n","/**\n * What an operator has to type into Gorgias by hand to wire the follow-up\n * webhook (spec-gorgias-followup-webhook-v1 §4).\n *\n * These constants used to be the BODY of `setup-gorgias-webhook`, the button\n * that posted the integration through `upsertHttpIntegration`. That button is\n * gone (operator's call: the integration is installed directly in Gorgias), and\n * with it the action and the `write_widgets` scope it alone required — the kit\n * no longer writes anything on the tenant's helpdesk account.\n *\n * They survive as constants because the recipe did not go away, it changed\n * hands: the settings screen now RENDERS them for the operator to copy. Keeping\n * them here rather than retyping them in the UI is what makes the rendered\n * recipe and the parser agree — `webhook-body.ts` reads exactly the keys of\n * `FOLLOWUP_WEBHOOK_FORM`, and a form field renamed on one side only would\n * produce a webhook that posts fine and resolves nothing.\n */\n\n/**\n * The server variable the operator fills in per app (§4, D7).\n *\n * Still needed, and needed MORE than before: the `wopilo_app_…` key it holds\n * is what the operator now pastes into the integration's `Authorization`\n * header themselves. The route authenticates against it either way.\n */\nexport const GORGIAS_CALLBACK_APP_KEY_VARIABLE = 'GORGIAS_CALLBACK_APP_KEY';\n\n/** The path half of the callback url — the app's own http route (`gorgias-webhook.ts`), leading slash included. */\nexport const FOLLOWUP_WEBHOOK_ROUTE_PATH = '/gorgias/webhook';\n\n/**\n * The `form` template of §4. The values are GORGIAS expressions, interpolated\n * by Gorgias against the ticket; the keys are ours, and `webhook-body.ts` reads\n * exactly these.\n *\n * Only the first three are guaranteed by the macro-variable reference. The\n * other four are plausible-but-undocumented (the template context IS the ticket\n * object — precedent: `ticket.messages[-1].body_html`, undocumented and used in\n * production by the Simio WhatsApp bridge) and are asked for anyway: a variable\n * Gorgias cannot resolve renders as its own literal text, which the parser\n * reads as mute, which costs one fresh Gorgias read and nothing else.\n */\nexport const FOLLOWUP_WEBHOOK_FORM: Record<string, string> = {\n ticket_id: '{{ticket.id}}',\n channel: '{{ticket.channel}}',\n last_message_datetime: '{{ticket.last_message_datetime}}',\n status: '{{ticket.status}}',\n tags: '{{ticket.tags}}',\n last_message_from_agent: '{{ticket.messages[-1].from_agent}}',\n last_message_public: '{{ticket.messages[-1].public}}',\n};\n\n/** The single Gorgias event this integration fires on. */\nexport const FOLLOWUP_WEBHOOK_TRIGGER = 'ticket-message-created';\n\n/**\n * The integration's name. No longer an idempotency key — nothing upserts\n * anymore — but still what separates two apps installed on one shared Gorgias\n * account, hence the slug in it, and still what the settings screen suggests.\n */\nexport function followupIntegrationName(slug: string): string {\n return `Wopilo — Réponses aux messages suivants (${slug})`;\n}\n\n/**\n * The PATH Gorgias must call, app slug included. Deliberately not a full url:\n * the origin is `PUBLIC_BASE_URL`, an API-side instance variable no browser\n * can read, and it is allowed to differ from the origin serving this interface\n * (`WEB_APP_URL`). Building the url from `window.location.origin` would hand a\n * split-origin deployment an address every Gorgias POST 404s on, with nothing\n * anywhere saying why — so the UI shows the path and names the origin instead\n * of guessing it.\n */\nexport function followupWebhookPath(slug: string): string {\n return `/api/s/${slug}${FOLLOWUP_WEBHOOK_ROUTE_PATH}`;\n}\n","/** An argument of an MCP tool call that cannot be used — the message is written to be read by the caller, who can correct the call. */\nexport class ToolInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ToolInputError';\n }\n}\n\n/** An optional flag a client may leave out, send as null, or set — never as the string \"true\". */\nexport function assertOptionalBoolean(name: string, value: unknown): void {\n if (value !== undefined && value !== null && typeof value !== 'boolean') {\n throw new ToolInputError(`\"${name}\" must be a boolean, got ${JSON.stringify(value)}.`);\n }\n}\n","/**\n * The instants an `aggregate` filter needs for a period of calendar days.\n *\n * This kit's records carry ISO instants (`generatedAt`, `decidedAt`), and\n * `jsonb-filter.ts` compares them as TEXT — lexicographic order over ISO-8601\n * UTC, which is chronological order. So the bounds are built as UTC instants\n * and the window is inclusive at both ends.\n *\n * Shared by the dashboard (browser) and by the server-side MCP tools, so it\n * is free of any UI import: resolving a comparison window from a picker\n * preset is the picker's business (`ui/dashboard/period.ts`); here a window\n * is either given or absent.\n */\n\nimport { ToolInputError } from './tool-input-error';\n\n/**\n * Past this many days a daily bucket draws bars one pixel wide and reads as\n * noise — the series switches to weeks, and the chart's own caption says so\n * rather than letting the reader assume days.\n */\nexport const WEEKLY_BUCKET_FROM_DAYS = 46;\n\n/** Calendar days, `YYYY-MM-DD`. `from` absent means unbounded. */\nexport interface DayRange {\n from?: string;\n to: string;\n}\n\nexport interface PeriodRequest {\n range: DayRange;\n /** The window to compare against. Absent when comparing to nothing. */\n compareRange?: DayRange;\n}\n\nexport interface PeriodBounds {\n /** Inclusive lower bound, `YYYY-MM-DDT00:00:00.000Z`. */\n fromIso: string;\n /** Inclusive upper bound, `YYYY-MM-DDT23:59:59.999Z`. */\n toIso: string;\n}\n\nexport interface DashboardPeriod {\n current: PeriodBounds;\n /** `null` when the request carries no comparison window. */\n previous: PeriodBounds | null;\n /** Calendar days covered by `current`, both ends included. */\n days: number;\n interval: 'day' | 'week';\n}\n\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst MS_PER_DAY = 86_400_000;\n\n/** The first instant the kit could ever have written a record — the lower bound when a range has none. */\nconst EPOCH_ISO = '1970-01-01T00:00:00.000Z';\n\nfunction startOfDayIso(day: string | undefined): string {\n return day !== undefined && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;\n}\n\nfunction endOfDayIso(day: string): string {\n return DAY_PATTERN.test(day) ? `${day}T23:59:59.999Z` : new Date().toISOString();\n}\n\nfunction dayCount(bounds: PeriodBounds): number {\n const from = Date.parse(bounds.fromIso);\n const to = Date.parse(bounds.toIso);\n if (Number.isNaN(from) || Number.isNaN(to)) return 0;\n return Math.max(1, Math.round((to - from) / MS_PER_DAY));\n}\n\nfunction boundsOf(range: DayRange): PeriodBounds {\n return { fromIso: startOfDayIso(range.from), toIso: endOfDayIso(range.to) };\n}\n\nexport function periodBoundsOf({ range, compareRange }: PeriodRequest): DashboardPeriod {\n const current = boundsOf(range);\n const days = dayCount(current);\n return {\n current,\n previous: compareRange === undefined ? null : boundsOf(compareRange),\n days,\n interval: days >= WEEKLY_BUCKET_FROM_DAYS ? 'week' : 'day',\n };\n}\n\nfunction dayToMs(day: string): number {\n return Date.parse(`${day}T00:00:00.000Z`);\n}\n\nfunction msToDay(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/** `YYYY-MM-DD` AND a real date: `2026-02-30` matches the pattern and is not a day. */\nfunction isCalendarDay(value: unknown): value is string {\n if (typeof value !== 'string' || !DAY_PATTERN.test(value)) return false;\n const ms = dayToMs(value);\n return !Number.isNaN(ms) && msToDay(ms) === value;\n}\n\nfunction requireCalendarDay(name: string, value: unknown): string {\n if (!isCalendarDay(value)) {\n throw new ToolInputError(\n `\"${name}\" must be a calendar day written YYYY-MM-DD, got ${JSON.stringify(value)}.`,\n );\n }\n return value;\n}\n\n/**\n * A window asked for by a tool caller. `endOfDayIso` answers a malformed day\n * with \"now\" — harmless for a picker that can only produce valid days, wrong\n * for a caller typing them — so days are validated here, at the boundary.\n */\nexport function dayRangeOf(from: unknown, to: unknown, maxDays: number): Required<DayRange> {\n const range = { from: requireCalendarDay('from', from), to: requireCalendarDay('to', to) };\n const length = lengthInDays(range);\n if (length < 1) throw new ToolInputError('\"to\" must not be before \"from\".');\n if (length > maxDays) {\n throw new ToolInputError(`The window is ${length} days long; the maximum is ${maxDays} days.`);\n }\n return range;\n}\n\n/**\n * The window of the same length that ends the day before `range` starts — the\n * `previous_period` mode of ui-sdk's `comparisonRange`, which is React-side\n * and cannot be imported here. `period.spec.ts` pins the two together.\n */\nexport function previousRangeOf(range: Required<DayRange>): Required<DayRange> {\n const from = dayToMs(range.from);\n const length = lengthInDays(range);\n return { from: msToDay(from - length * MS_PER_DAY), to: msToDay(from - MS_PER_DAY) };\n}\n\n/** Calendar days from `range.from` to `range.to`, both included. */\nfunction lengthInDays(range: Required<DayRange>): number {\n return (dayToMs(range.to) - dayToMs(range.from)) / MS_PER_DAY + 1;\n}\n","/**\n * The ticket timeline's MODEL: which of the seven steps the graph actually\n * reached for one ticket, and — when it did not — why\n * (spec-vue-tickets-unifiee-v1 §3).\n *\n * A step that was not reached is the point of the timeline. The four screens\n * it replaces each showed a slice and let the reader infer the rest:\n * Pipeline listed only the tickets that produced a draft, so a ticket stopped\n * at the tag was invisible rather than explained. Here every step is present\n * on every ticket, and an unreached one carries the reason drawn from the\n * records themselves.\n *\n * Shared by the ticket panel (browser) and by the server-side MCP tools, so\n * it decides WHICH reason applies and never how it reads: a reason is a code\n * plus the facts it was drawn from (ratios, ids, raw error text). Turning one\n * into a sentence — titles, French wording, percent rendering, guardrail and\n * channel labels — is the UI's job (`ui/tickets/timeline.ts`).\n */\nimport type {\n CategoryRecord,\n GeneratedResponseRecord,\n ResponseComparisonRecord,\n TriageDecisionRecord,\n} from '../functions/records';\nimport { requiresFollowup } from './evaluation-verdict';\nimport { SUPPORT_CHANNELS } from './profile';\n\nexport type TimelineStepKey =\n | 'received'\n | 'prompt'\n | 'triage'\n | 'draft'\n | 'evaluation'\n | 'delivery'\n | 'correction';\n\n/** Why a drafted reply did not go out. */\nexport type NotSentReason =\n | { code: 'generic_not_sent' }\n | { code: 'held_permanently' }\n | { code: 'guardrail_unrecorded' }\n /** `hits` is never empty; the first one is the decision, the rest merely also fired. */\n | { code: 'guardrail'; hits: string[]; reconstructed: boolean }\n | { code: 'awaiting_approval' }\n | { code: 'trial_mode' }\n | { code: 'no_verdict' }\n | { code: 'evaluation_failed' }\n | { code: 'judge_held' }\n | { code: 'judge_not_authorized' }\n /** Both are 0–1 ratios. */\n | { code: 'below_confidence'; confidence: number; minConfidence: number }\n | { code: 'followup_not_sendable' }\n | { code: 'legacy_followup_probable' }\n | { code: 'evaluation_disabled' }\n | { code: 'auto_send_disabled' }\n | { code: 'category_auto_reply_off'; categoryName: string }\n | { code: 'whatsapp_draft_only' }\n | { code: 'no_publication_path'; channel: string | null }\n | { code: 'channel_not_enabled'; channel: string | null }\n | { code: 'no_sender_address' };\n\n/** Why the graph never opened a `generated-response` for this ticket. */\nexport type NoResponseReason =\n | { code: 'ticket_escalated' }\n | { code: 'conversation_over' }\n | { code: 'triage_error'; error: string | null }\n | { code: 'category_not_drafting' };\n\nexport type TimelineReason =\n | NoResponseReason\n | NotSentReason\n | { code: 'conversation_loading' }\n | { code: 'conversation_unavailable' }\n | { code: 'triage_failed'; error: string | null }\n | { code: 'prompt_not_captured' }\n | { code: 'draft_pending' }\n | { code: 'draft_empty'; error: string | null }\n | { code: 'evaluation_pending' }\n | { code: 'evaluation_missing' }\n | { code: 'reply_queued' }\n /** `detail` is `null` when the only thing to add would be the generic cause. */\n | { code: 'expired'; detail: NotSentReason | null }\n | { code: 'delivery_failed'; error: string | null }\n | { code: 'superseded' }\n | { code: 'test_draft' }\n | { code: 'no_reply_needed' }\n | { code: 'unexpected_status'; status: string }\n | { code: 'no_correction' };\n\n/** A step is reached, or it is not and says why — never both, never neither. */\nexport type TimelineStepState =\n | { key: TimelineStepKey; reached: true }\n | { key: TimelineStepKey; reached: false; reason: TimelineReason };\n\n/** The settings behind the send decision — the subset of the UI's `DeliveryPolicy` the reasons read. */\nexport interface TimelinePolicy {\n /** `nodes.evaluate.escalationEnabled` — whether a verdict needing a follow-up may still be sent. */\n followupSendable: boolean;\n /** `nodes.evaluate.minConfidence`, as a 0–1 ratio. */\n minConfidence: number;\n evaluateConfigured: boolean;\n autoSendEnabled: boolean;\n senderEmail: string | null;\n whatsappMode: string | null;\n /** The allowlist `isAutoSendEligible` checked the ticket's channel against. */\n autoSendChannels: string[];\n}\n\nexport interface TimelineFacts {\n decision: TriageDecisionRecord;\n job: GeneratedResponseRecord | undefined;\n comparisons: readonly ResponseComparisonRecord[];\n /** `null` when no source had anything to show; only the rendered writer prompt matters here. */\n conversation: { systemPrompt: string | null } | null;\n /** True while the live conversation read is still in flight — \"pas encore lu\" is not \"introuvable\". */\n conversationLoading?: boolean;\n /**\n * Absent/`null` degrades the \"not sent\" reasons to their generic cause —\n * never an error, and never a guess.\n */\n policy?: TimelinePolicy | null;\n /** The ticket's own category — `autoReplyEnabled` is half of auto-send eligibility. */\n category?: Pick<CategoryRecord, 'name' | 'autoReplyEnabled'> | null;\n}\n\nconst GENERIC_NOT_SENT: NotSentReason = { code: 'generic_not_sent' };\n\nexport function buildTimelineSteps(facts: TimelineFacts): TimelineStepState[] {\n return [\n step('received', receivedReason(facts)),\n step('prompt', promptReason(facts)),\n step('triage', triageReason(facts)),\n step('draft', draftReason(facts)),\n step('evaluation', evaluationReason(facts)),\n step('delivery', deliveryReason(facts)),\n step('correction', correctionReason(facts)),\n ];\n}\n\n/** `null` reason means reached. */\nfunction step(key: TimelineStepKey, reason: TimelineReason | null): TimelineStepState {\n return reason === null ? { key, reached: true } : { key, reached: false, reason };\n}\n\nfunction receivedReason({\n conversation,\n conversationLoading,\n}: TimelineFacts): TimelineReason | null {\n if (conversation) return null;\n return conversationLoading\n ? { code: 'conversation_loading' }\n : { code: 'conversation_unavailable' };\n}\n\nfunction promptReason({ conversation, job, decision }: TimelineFacts): TimelineReason | null {\n // The absence of a job settles it before the conversation is even consulted:\n // this step describes the prompt sent to the WRITER, and no writer ran.\n if (!job) return noResponseReason(decision);\n if (conversation?.systemPrompt) return null;\n return { code: 'prompt_not_captured' };\n}\n\nfunction triageReason({ decision }: TimelineFacts): TimelineReason | null {\n // A decision row exists by construction (it is the page's own unit), so the\n // only way triage is \"not reached\" is a run that errored before classifying.\n if (decision.status === 'error' && !decision.tag)\n return { code: 'triage_failed', error: decision.error ?? null };\n return null;\n}\n\nfunction draftReason({ job, decision }: TimelineFacts): TimelineReason | null {\n if (!job) return noResponseReason(decision);\n if (job.responseText) return null;\n if (job.status === 'pending') return { code: 'draft_pending' };\n return { code: 'draft_empty', error: job.error ?? null };\n}\n\nfunction evaluationReason({ job, decision }: TimelineFacts): TimelineReason | null {\n if (!job) return noResponseReason(decision);\n if (job.verdict) return null;\n return job.status === 'pending' ? { code: 'evaluation_pending' } : { code: 'evaluation_missing' };\n}\n\nfunction deliveryReason(facts: TimelineFacts): TimelineReason | null {\n const { job, decision } = facts;\n if (!job) return noResponseReason(decision);\n switch (job.status) {\n case 'sent':\n return null;\n case 'pending':\n return { code: 'reply_queued' };\n case 'ready':\n return notSentReason(facts, job);\n case 'expired': {\n const why = notSentReason(facts, job);\n return { code: 'expired', detail: why.code === 'generic_not_sent' ? null : why };\n }\n case 'failed':\n return { code: 'delivery_failed', error: job.error ?? null };\n case 'superseded':\n // The question the timeline exists to answer, for the one status that\n // makes an operator ask it: the draft did not fail and nobody discarded\n // it — the customer moved on and a fresher reply took over.\n return { code: 'superseded' };\n case 'test_draft':\n // The operator's \"générer sans envoyer\" essay — named as such, so it is\n // never read as an agent having answered first.\n return { code: 'test_draft' };\n default:\n // spec-fin-de-conversation-v1 §6 — only the end step writes outcome `no_reply_needed`;\n // process-response also rests `escalated` / `triaged_only` rows on this status.\n if (job.status === 'no_reply_needed' && job.outcome === 'no_reply_needed')\n return { code: 'no_reply_needed' };\n return { code: 'unexpected_status', status: job.status };\n }\n}\n\n/**\n * Why this drafted reply did not go out — the point of the delivery step.\n *\n * The stored `outcome` picks the FAMILY (it is the exit `runTicket` actually\n * took, and `status: 'ready'` covers four of them), the settings explain\n * WHICH condition inside that family fired. Deriving the family here instead\n * would be a second copy of `run-ticket.ts`'s order of early returns; naming\n * the condition is an explanation, not a decision, and the difference is why\n * only the second half is computed.\n *\n * KNOWN LIMIT: the family is a recorded fact, the condition is read off\n * TODAY's settings. Flip a switch and an old ticket's reason changes with it.\n * Recording the condition at run time would fix it and was not done — it\n * means persisting a rendered message, which rots differently and worse.\n * `legacyNotSentReason` states the caveat out loud because there BOTH halves\n * are inferred; here only the second is.\n */\nfunction notSentReason(\n { policy, category }: TimelineFacts,\n job: GeneratedResponseRecord,\n): NotSentReason {\n // The hold outranks the outcome: it is written AFTER the run ended, by\n // three different writers — the sweep's stalled-send reclaim, an approval\n // rejected by a human, and a guardrail `act` hit on an approved send\n // (`handle-approval.ts`, `sweep.ts`). Only the invariant they share can be\n // stated; naming any one of them would be wrong two times out of three, and\n // the record keeps nothing that tells them apart.\n // …unless the hold recorded WHICH guardrail raised it (28/09/2026). One of\n // the three writers — `handle-approval`'s refused send — now persists its\n // hits, so on those rows naming the real reason beats the disjunction.\n if (job.autoSendDecision === 'hold' && job.guardrailHits.length === 0)\n return { code: 'held_permanently' };\n if (job.autoSendDecision === 'hold') return guardrailReason(job);\n switch (job.outcome) {\n case 'needs_human':\n return notSendableReason(job, policy);\n case 'guardrail_hold':\n return guardrailReason(job);\n case 'awaiting_approval':\n return { code: 'awaiting_approval' };\n case 'ready':\n return notEligibleReason(job, policy, category);\n case 'sent':\n return { code: 'trial_mode' };\n case null:\n return legacyNotSentReason(job, policy, category);\n default:\n return GENERIC_NOT_SENT;\n }\n}\n\n/** `isSendable`'s conditions (`verdict/policy.ts`), in the order it checks them. */\nfunction notSendableReason(\n job: GeneratedResponseRecord,\n policy: TimelinePolicy | null | undefined,\n): NotSentReason {\n const verdict = job.verdict;\n if (!verdict) return { code: 'no_verdict' };\n if (verdict.status === 'error') return { code: 'evaluation_failed' };\n if (verdict.verdict === 'hold') return { code: 'judge_held' };\n if (!policy) return { code: 'judge_not_authorized' };\n if ((verdict.confidence ?? 0) < policy.minConfidence) {\n return {\n code: 'below_confidence',\n confidence: verdict.confidence ?? 0,\n minConfidence: policy.minConfidence,\n };\n }\n if (requiresFollowup(verdict.verdict) && !policy.followupSendable)\n return { code: 'followup_not_sendable' };\n return { code: 'judge_not_authorized' };\n}\n\n/**\n * Why a `ready` row was not auto-sent — the exits `run-ticket.ts` takes\n * between the verdict and `act`, in the order it takes them:\n * `isAutoSendEligible`, then `isAutoSendChannel`, then `hasPublicationPath`\n * (`verdict/policy.ts`).\n *\n * Two departures from that order, both because a stored row knows less than\n * the run did:\n *\n * - `ineligibleReason` is read BEFORE the channel allowlist. It is a\n * RECORDED fact, and the run only ever writes it past the allowlist — so\n * a row carrying it proves the channel was authorised, whatever the\n * settings say today.\n * - the sender address is read LAST, though the run asks for it first.\n * Since `publicationMode` decides who needs one, and this row carries no\n * conversation to ask, naming it first would blame a missing address on\n * every Instagram ticket of a WhatsApp-only tenant — which is exactly\n * what the run stopped doing. The more specific reasons get first refusal.\n */\nfunction notEligibleReason(\n job: GeneratedResponseRecord,\n policy: TimelinePolicy | null | undefined,\n category: TimelineFacts['category'],\n): NotSentReason {\n if (!policy) return GENERIC_NOT_SENT;\n if (!policy.evaluateConfigured) return { code: 'evaluation_disabled' };\n if (!policy.autoSendEnabled) return { code: 'auto_send_disabled' };\n if (category && !category.autoReplyEnabled)\n return { code: 'category_auto_reply_off', categoryName: category.name };\n const isWhatsapp = job.channel === 'whatsapp';\n if (isWhatsapp && policy.whatsappMode === 'draft_only') return { code: 'whatsapp_draft_only' };\n // The one reason the run had to record, because nothing readable today can\n // say whether a contact had an address six weeks ago.\n if (job.ineligibleReason === 'no_publication_path') {\n return { code: 'no_publication_path', channel: job.sourceChannel || null };\n }\n // Read off `sourceChannel`, never `channel`: the latter is the publication\n // MODE (`'whatsapp'` or `'email'`), so an Instagram thread reads as \"email\"\n // there and the reason would name the wrong thing. Rows written before\n // that field existed carry null and fall through, as they did.\n //\n // Guarded by the catalogue for the same reason `isAutoSendChannel` is: a\n // channel `SUPPORT_CHANNELS` does not name is not restricted by a list the\n // Réglages cannot show it in, so claiming it was would be a lie about a\n // box that does not exist.\n if (isRestrictedChannel(job.sourceChannel, policy.autoSendChannels)) {\n return { code: 'channel_not_enabled', channel: job.sourceChannel };\n }\n // Only the email path sends FROM an address (`verdict/policy.ts`), and a\n // WhatsApp ticket never takes it.\n if (!policy.senderEmail && !isWhatsapp) return { code: 'no_sender_address' };\n return GENERIC_NOT_SENT;\n}\n\n/** `isAutoSendChannel`'s allowlist, to the letter: unknown channel, or no channel at all, is not a restriction. */\nfunction isRestrictedChannel(sourceChannel: string | null, allowed: string[]): boolean {\n if (!sourceChannel) return false;\n if (!(SUPPORT_CHANNELS as readonly string[]).includes(sourceChannel)) return false;\n return !allowed.includes(sourceChannel);\n}\n\n/**\n * The guardrail(s) that held the reply. Only the FIRST hit is the decision —\n * the evaluation order is frozen (I8 for `act`'s checks, §3.9 for the\n * content rules) — the rest are conditions that merely also happened to be\n * true, and stay in `hits` so nothing is hidden.\n */\nfunction guardrailReason(job: GeneratedResponseRecord): NotSentReason {\n if (job.guardrailHits.length === 0) return { code: 'guardrail_unrecorded' };\n // The backfill's honesty clause: a reason rebuilt from Gorgias after the\n // fact was deduced with TODAY's settings, which are not necessarily the\n // ones the run applied.\n return {\n code: 'guardrail',\n hits: [...job.guardrailHits],\n reconstructed: Boolean(job.guardrailHitsReconstructedAt),\n };\n}\n\n/**\n * Rows written before `outcome` existed (21/09/2026). Their exit was never\n * recorded, so the family has to be guessed from what IS stored — and the\n * guess is checked against TODAY's settings, which may not be the ones the\n * run used.\n */\nfunction legacyNotSentReason(\n job: GeneratedResponseRecord,\n policy: TimelinePolicy | null | undefined,\n category: TimelineFacts['category'],\n): NotSentReason {\n if (job.guardrailHits.length > 0) return guardrailReason(job);\n const verdict = job.verdict;\n if (\n policy &&\n verdict &&\n verdict.status === 'success' &&\n requiresFollowup(verdict.verdict) &&\n !policy.followupSendable\n ) {\n return { code: 'legacy_followup_probable' };\n }\n if (verdict && (verdict.status === 'error' || verdict.verdict === 'hold'))\n return notSendableReason(job, policy);\n return notEligibleReason(job, policy, category);\n}\n\nfunction correctionReason({ comparisons }: TimelineFacts): TimelineReason | null {\n return comparisons.length > 0 ? null : { code: 'no_correction' };\n}\n\n/**\n * Why no `generated-response` row was ever opened for this ticket.\n *\n * `eligibility.ts` holds the real rule, but it needs the profile, the\n * classification and the category record — none of which a ticket view has.\n * What it CAN read off the decision alone is which of the three\n * operator-facing causes applies; the fourth is the residue, and is named as\n * a residue rather than asserted as a fact that cannot be checked.\n */\nexport function noResponseReason(decision: TriageDecisionRecord): NoResponseReason {\n if (decision.escalated) return { code: 'ticket_escalated' };\n if (decision.conversationOver) return { code: 'conversation_over' };\n if (decision.status === 'error') return { code: 'triage_error', error: decision.error ?? null };\n return { code: 'category_not_drafting' };\n}\n"]}
|