@apotech-os/support-kit 8.0.0 → 8.1.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/dist/{chunk-2UHFKGMI.js → chunk-LXHPPWPM.js} +20 -6
- package/dist/chunk-LXHPPWPM.js.map +1 -0
- package/dist/index.cjs +86 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +71 -32
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +144 -46
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +131 -46
- package/dist/ui/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2UHFKGMI.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/domain/classification.ts","../src/domain/profile.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/guardrails/verify-reply.ts","../src/verdict/policy.ts","../src/graph/nodes/fetch-context.ts","../src/graph/nodes/triage.ts","../src/graph/nodes/escalate.ts","../src/graph/nodes/guardrails.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/fields.ts","../src/settings/validate.ts","../src/settings/to-profile.ts","../src/functions/records.ts","../src/functions/response-comparison-diff.ts","../src/functions/followup-webhook-install.ts"],"names":["firstCustomerMessage","fallback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AAA,CAAA,EAAA;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,IAAI,OAAA,EAAQ;AACrB;;;ACrCO,IAAM,2BAAA,GAA8B,kBAAA;AAcpC,IAAM,qBAAA,GAAgD;AAAA,EAC3D,SAAA,EAAW,eAAA;AAAA,EACX,OAAA,EAAS,oBAAA;AAAA,EACT,qBAAA,EAAuB,kCAAA;AAAA,EACvB,MAAA,EAAQ,mBAAA;AAAA,EACR,IAAA,EAAM,iBAAA;AAAA,EACN,uBAAA,EAAyB,oCAAA;AAAA,EACzB,mBAAA,EAAqB;AACvB;AAGO,IAAM,wBAAA,GAA2B;AAOjC,SAAS,wBAAwB,IAAA,EAAsB;AAC5D,EAAA,OAAO,oDAA4C,IAAI,CAAA,CAAA,CAAA;AACzD;AAWO,SAAS,oBAAoB,IAAA,EAAsB;AACxD,EAAA,OAAO,CAAA,OAAA,EAAU,IAAI,CAAA,EAAG,2BAA2B,CAAA,CAAA;AACrD","file":"chunk-LXHPPWPM.js","sourcesContent":["// Spec: architecture_agent_graphe.md §3, I1\n\n/**\n * Safety bound on every model-written justification 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 * True when triage judged the LAST customer message closes the thread\n * (« merci », « ok parfait »…) — the graph then exits `no_reply_needed`\n * before `draft` ever runs (whatsapp spec §5.2). Optional: some existing\n * fixtures and older wire-decoded values omit it — absent means `false`.\n */\n conversationOver?: 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 * 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 FALLBACKS ONLY: when the resolved Langfuse\n * prompt carries a model config, it wins (I16).\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 };\n autoSend: {\n enabled: boolean;\n senderEmail: string | null;\n minConfidence: number;\n requireHighTriage: boolean;\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","// 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', // triage read the thread as already closed → NO tag, like 'ready' (whatsapp spec §5.2)\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\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 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 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\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 /** 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. WINS over `AgentProfile.nodes.<node>`'s own `model`/`provider`\n * (I16 — see `domain/profile.ts`'s `AgentProfile.nodes` doc: those fields\n * are fallbacks only). `null`/absent means \"no override\", the profile's\n * own settings apply unchanged.\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\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","// 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 the `no_reply_needed` exit, which\n * applies no tag and would leave the opt-out no trace (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 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 /** See `isInternalNoteChannel` below (B2). */\n source?: { type?: string } | null;\n}\n\nexport interface RawTicket {\n channel?: string | null;\n subject?: string | null;\n status?: string | null;\n customer?: { email?: string | null } | null;\n messages?: RawTicketMessage[];\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","// 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","// 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 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 required in EMAIL mode only\n * — a WhatsApp note has no \"from\" email address to send with. The sender\n * exemption below is scoped to `whatsappMode === 'auto_reply'` specifically\n * — the ONE mode where a WhatsApp note is actually the reply that would go\n * out — NOT to every WhatsApp ticket, to keep `escalate_only` iso-behaviour\n * to the byte.\n */\nexport function isAutoSendEligible(\n state: TicketRunState,\n deps: Pick<NodeDeps, 'profile' | 'category'>,\n): boolean {\n const isWhatsapp = state.conversation?.sourceChannel === 'whatsapp';\n const whatsappMode = deps.profile.guardrails.params.whatsappMode;\n const whatsappDraftOnly = isWhatsapp && whatsappMode === 'draft_only';\n const hasSenderForMode = (isWhatsapp && whatsappMode === 'auto_reply') || !!deps.profile.autoSend.senderEmail;\n\n return (\n deps.profile.autoSend.enabled &&\n deps.category.autoReplyEnabled &&\n hasSenderForMode &&\n !!state.verdict &&\n !whatsappDraftOnly\n );\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,\n// conversationOver}. 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// `conversationOver` (whatsapp spec §5.2): does the LAST customer message\n// close the thread (« merci », « ok parfait »…)?\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 conversationOver: { type: 'boolean' },\n },\n required: ['tag', 'confidence', 'reasoning', 'conversationOver'],\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 conversationOver: false, // fail-safe (§5.2): never close on an error\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 resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.triage, {\n categories: renderCategories(deps.categories),\n });\n\n try {\n const result = await deps.ports.llm.complete({\n label: 'triage',\n // The resolved Langfuse prompt's own model config WINS over the\n // profile's fallback (I16) — see `PromptPort.resolve`'s doc.\n model: resolvedPrompt.config?.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 });\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 conversationOver: parsed.conversationOver === true,\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\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',\n model: resolvedPrompt.config?.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.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 { Node } from '../state';\n\nexport const guardrails: Node = async (state, deps) => {\n const { profile } = deps;\n const conversation = state.conversation;\n if (!conversation || !state.draft) return { guardrailHits: [] };\n\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 && state.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: state.draft.text,\n hasAttachment: conversation.hasCustomerAttachment,\n blocklist: params.blocklist,\n }).filter((hit) => active.includes(guardrailBucket(hit)));\n\n return { guardrailHits: [...hits, ...contentHits] };\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 * The resolved Langfuse prompt's own model config, when it declares one\n * (I16) — WINS over `profile.nodes.draft.model` on every completion of the\n * loop. Absent means \"use the profile's own model\", today's behaviour.\n */\n model?: 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, model, 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: 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 and its own model config 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 // The resolved Langfuse prompt's own model config WINS over the\n // profile's fallback (I16) — see `PromptPort.resolve`'s doc.\n model: resolvedPrompt.config?.model ?? node.model,\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 resolved Langfuse prompt's own model config WINS over the\n // profile's fallback (I16) — see `PromptPort.resolve`'s doc.\n model: evaluatePrompt.config?.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 } from '../../guardrails/constants';\nimport { markdownToHtml } from '../markdown-to-html';\nimport type { Conversation } from '../../domain';\nimport type { OutboundReply } from '../ports';\nimport type { Node } from '../state';\n\n/**\n * True when an agent answered after the run was queued. With no queue instant\n * to compare against, any agent reply at all counts — refusing to send is the\n * safe side of an unknown.\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\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\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 same `sourceChannel`\n // the `guardrails` node reads off `state.conversation` picks the\n // publication mode here, so the channel is never decided twice.\n //\n // Deliberately read off `generatedFrom` (the GENERATED-FROM snapshot), not\n // `fresh` below like every other check in this node — `sourceChannel`\n // cannot change mid-run, so there is nothing for the fresh re-read to\n // catch here, unlike the divergence/agent-reply/closed checks that exist\n // precisely because their fields CAN move under the run.\n const mode = generatedFrom.sourceChannel === 'whatsapp' ? 'whatsapp_note' : 'email';\n\n const fresh = await deps.ports.conversation.read(deps.ref);\n // A WhatsApp contact is often addressless — this pre-check is email-only\n // (spec §4.3).\n if (mode === 'email' && !fresh.customer.email) return { guardrailHits: ['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 { guardrailHits: ['ticket_closed'] };\n if (hasAgentRepliedSince(fresh.lastAgentReplyAt, deps.queuedAt ?? null)) {\n return { guardrailHits: ['agent_replied'] };\n }\n if (hasDiverged(fresh, generatedFrom)) return { guardrailHits: ['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 { guardrailHits: ['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 =\n mode === 'email'\n ? {\n mode: 'email',\n bodyText: draft.text,\n // The draft is markdown; the email channel's HTML body must be\n // rendered, not the raw source.\n bodyHtml: markdownToHtml(draft.text),\n subject: fresh.subject,\n fromAddress: deps.profile.autoSend.senderEmail ?? '',\n receiverName: fresh.customer.name,\n // Guaranteed non-null by the `customer_email_missing` gate above,\n // in email mode — `?? ''` is belt-and-braces for the type, not a\n // real fallback.\n receiverEmail: fresh.customer.email ?? '',\n idempotencyKey: action.idempotencyKey,\n }\n : {\n mode: 'whatsapp_note',\n // Raw draft text: no markdown-to-HTML rendering (§4.2/§6.4) — the\n // note carries the model's text as-is, the chevron prefix is the\n // adapter's job.\n bodyText: draft.text,\n idempotencyKey: action.idempotencyKey,\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","// `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 { isAutoSendEligible, isSendable, needsRevision } 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` — the silence says there is\n * nothing to do (whatsapp spec §5.2, I20).\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`/`conversationOver` are\n * read straight off the classification, `hasNoDraftNode` 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 isConversationOver(classification: Classification | null): boolean {\n return classification?.conversationOver === true;\n}\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 // `no_reply_needed` included. A customer who writes \"STOP\" has almost\n // certainly also closed the conversation, so triage will happily report\n // `conversationOver: true` on the very same ticket; if that exit won, the\n // run would end with NO tag (I20) and the opt-out would leave 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.\n const stopHits = s.conversation ? stopOptOut(s.conversation) : [];\n if (stopHits.length) return finish(merge(s, { guardrailHits: stopHits }), deps, 'guardrail_hold');\n // Whatsapp spec §5.2: placed before the `triaged_only` checks below so a\n // tenant with no draft node still reports the real reason (conversation\n // over), not the generic \"no draft step\" one.\n if (isConversationOver(s.classification)) return finish(s, deps, 'no_reply_needed');\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 §5.2 moved the sibling \"merci\" rule up into `triage`.\n //\n // Unlike the STOP gate above, this one sits AFTER `no_reply_needed`: a\n // finished thread where we happen to have spoken last is described better\n // by \"aucune réponse nécessaire\" than by a hold plus an escalation tag\n // asking a human to look at nothing. §5.3 is the belt, not the braces.\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 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] 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 * `pending->invalidated` is the one addition to that list (16/09/2026). §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'],\n ready: ['sending', 'invalidated', 'expired'],\n sending: ['sent', 'ready'],\n sent: [],\n failed: [],\n no_reply_needed: [],\n invalidated: [],\n expired: [],\n test_draft: [],\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';\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';\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 * `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 * 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 { AGENT_GUARDRAILS } from '../guardrails/constants';\nimport {\n DEFAULT_CHANNEL_PROMPT_EMAIL,\n DEFAULT_CHANNEL_PROMPT_WHATSAPP,\n DEFAULT_WHATSAPP_MODE,\n WHATSAPP_MODES,\n} from '../domain/profile';\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 // Follow-up webhook (spec-gorgias-followup-webhook-v1 D2)\n // The tag a ticket must ALREADY carry for this app to answer a SUBSEQUENT\n // customer message on it. Deliberately empty by default, twice over:\n // - two support apps installed on ONE Gorgias account each receive every\n // `ticket-message-created` event, so a shared default would make a\n // freshly-installed app answer the other audience's tickets. Two apps of\n // the same account MUST configure distinct values;\n // - empty therefore means \"process no follow-up message at all\", which is\n // both the fail-closed default and the feature's kill switch.\n // Not named `followupTag`: that key is taken (`wai/human-required`).\n { key: 'webhookScopeTag', type: 'string', label: 'Webhook scope tag', default: '' },\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 // 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: 'Europe/Paris' },\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 */\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 = 'sourceViewId' | 'nodes' | 'nodePrompt' | 'senderEmail';\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, plus the one shape rule no\n * 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 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 return issues;\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 * `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 * Three 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 `webhookScopeTag`\n * (spec-gorgias-followup-webhook-v1 D2 — which tickets of a shared Gorgias\n * account this app may answer a follow-up on is a routing decision, read by\n * the webhook's own gates, never by a node). `to-profile.spec.ts` pins that\n * 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_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';\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 /** D2 — the tag scoping which tickets the follow-up webhook may answer. Empty = inert (see `settings/fields.ts`). */\n webhookScopeTag: string;\n autoSendEnabled: boolean;\n senderEmail: 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 };\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 },\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 * 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 /** 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 * 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 channel: 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}\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 };\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\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 guardrailHits: (data.guardrailHits as string[] | undefined) ?? [],\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 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/** Every `category` row, for the triage referential and per-ticket tag matching. High limit: the taxonomy is operator-curated, never large. */\nexport async function listCategories(api: SupportKitApi): Promise<CategoryRecord[]> {\n const page = await api.list('category', { limit: 500 });\n return page.items.map(toCategory);\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 DEFAULT_LABEL = 'production';\n const refFor = (\n node: { prompt?: NodePromptSettings } | null | undefined,\n derivedName: string,\n fallback: string | undefined,\n ): PromptRef => ({\n name: node?.prompt?.name ?? derivedName,\n label: node?.prompt?.label ?? DEFAULT_LABEL,\n ...(fallback ? { fallback } : {}),\n });\n const prompts = config.defaults?.prompts;\n return {\n triage: refFor(nodes.triage, resolvePromptName('triage', config), prompts?.triage),\n escalate: refFor(nodes.escalate, resolvePromptName('escalation', config), prompts?.escalation),\n evaluate: refFor(nodes.evaluate, resolvePromptName('evaluation', config), prompts?.evaluation),\n draft,\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"]}
|