@apotech-os/support-kit 6.2.0 → 7.0.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-W2QU5367.js → chunk-CQJJZA4F.js} +46 -16
- package/dist/chunk-CQJJZA4F.js.map +1 -0
- package/dist/index.cjs +66 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -2
- package/dist/index.d.ts +12 -2
- package/dist/index.js +23 -2
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +595 -363
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +224 -27
- package/dist/ui/index.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-W2QU5367.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/domain/classification.ts","../src/domain/profile.ts","../src/domain/evaluation-verdict.ts","../src/graph/state.ts","../src/graph/ports.ts","../src/graph/budget.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/references.ts","../src/prompts/resolver.ts","../src/prompts/slots.ts","../src/records/ids.ts","../src/records/target-ref.ts","../src/records/category.ts","../src/records/category-group.ts","../src/records/agent.ts","../src/records/triage-decision.ts","../src/records/generated-response.ts","../src/records/response-comparison.ts","../src/records/evaluation.ts","../src/records/diff-analysis.ts","../src/records/pipeline-state.ts","../src/records/prompt-cache.ts","../src/records/derive-uid.ts","../src/records/scope-to-app.ts","../src/records/index.ts","../src/settings/fields.ts","../src/settings/validate.ts","../src/settings/to-profile.ts","../src/functions/config.ts","../src/adapters/conversation-mapping.ts","../src/adapters/gorgias-tags.ts","../src/adapters/ctx-ports.ts","../src/adapters/recording-ports.ts","../src/functions/context.ts","../src/functions/eligibility.ts","../src/functions/no-tool-context.ts","../src/functions/pipeline-state.ts","../src/functions/claim-commit.ts","../src/functions/approval-key.ts","../src/functions/traced-input.ts","../src/functions/records.ts","../src/functions/process-response.ts","../src/functions/generated-response-transition.ts","../src/functions/triage-tick.ts","../src/functions/sweep.ts","../src/functions/handle-approval.ts","../src/functions/ids.ts","../src/functions/run-triage-now.ts","../src/functions/invalidate-response.ts","../src/functions/preview-triage.ts","../src/functions/get-ticket-conversation.ts","../src/functions/graph-dry-run-core.ts","../src/functions/graph-dry-run.ts","../src/functions/test-agents.ts","../src/functions/validate-references.ts","../src/functions/suggest-prompt.ts","../src/functions/list-gorgias-views.ts","../src/functions/create-agent.ts","../src/functions/set-default-agent.ts","../src/functions/create-shared-prompt-version.ts","../src/functions/sync-agent-prompt-snapshot.ts","../src/functions/ext-models.ts","../src/functions/ext-categories.ts","../src/functions/ownership-probe.ts","../src/functions/support-extension-envelope.ts","../src/functions/ext-chat.ts","../src/functions/ext-fast-response-check.ts","../src/functions/ext-evaluation.ts","../src/functions/response-comparison-diff.ts","../src/functions/ext-response-comparison.ts","../src/pages/manifest.ts","../src/pipeline.ts"],"names":["firstCustomerMessage","fallback","draft","outcome","finish","AppApiError","text","FieldType","createHash","step","triage","evaluate","isInternalNoteChannel","result","DEFAULT_MAX_TOOL_CALLS","agentRecord","conversation","APPROVAL_DECIDED_EVENT","REF_RE","PIPELINE_STATE_SINGLETON_KEY","AGENT_PAGE_SIZE","record","i","j"],"mappings":";;;;;;AAQO,IAAM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AAA;AAAA,IAC3C,SAAA;AAAA,IACA,QAAA,EAAU,EAAE,MAAA,EAAQ,2BAAA,EAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAShD,SAAS,EAAC;AAAA;AAAA;AAAA;AAAA,IAIV,KAAA,EAAO,WAAW,MAAM,CAAA;AAAA,IACxB,UAAA,EAAY,gBAAgB,MAAM,CAAA;AAAA,IAClC,YAAA,EAAc,kBAAkB,MAAM,CAAA;AAAA,IACtC,YAAA,EAAc,wBAAA;AAAA,IACd,KAAA,EAAO,iBAAA;AAAA,IACP,WAAA,EAAa,WAAA;AAAA,IACb,QAAA;AAAA,IACA,SAAA,EAAW,eAAe,MAAM,CAAA;AAAA,IAChC,iBAAA,EAAmB;AAAA,GACrB;AACF","file":"index.cjs","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","// 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\nexport type Outcome =\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 | null;\n\nexport interface TicketRunState {\n conversation: Conversation | null;\n classification: Classification | null;\n escalated: boolean;\n draft: Draft | null;\n verdict: Verdict | null;\n reviseCount: 0 | 1;\n guardrailHits: string[];\n 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","// Spec: architecture_agent_graphe.md §6.3 (legacy `agent/budget.ts`).\n//\n// Ported unchanged: this bounds ONE run in tool calls and time, and tracks\n// its cost ledger (I15) — it has nothing to do with the worker-level\n// `RUN_DEADLINE_MS`/stale-lock scheduling the migration drops in favour of\n// Inngest retries/concurrency/timeouts (spec §3.3's \"différences assumées\").\n// The caller still supplies whatever `AbortSignal` represents its own\n// deadline; `Budget` only ever reads it.\nimport type { CostLedger, NodeCost, NodeKey, Usage } from '../domain';\n\nconst ZERO_COST: NodeCost = { input: 0, output: 0, reasoning: 0, usd: 0, pricingMissing: false };\n\n/**\n * Run budget: bounds a run in TOOL CALLS and TIME only, never in money —\n * cost is measured (`charge`, I15) and watched separately, not capped here.\n * Every method is a no-throw no-op past the allowance: exhausting the\n * budget must never fail a ticket (§6.3).\n */\nexport interface Budget {\n /** The run's deadline signal, forwarded unchanged to every LLM call. */\n signal: AbortSignal;\n consumeToolCall(): void;\n /** True once `maxToolCalls` is spent OR the run signal aborted. */\n exhausted(): boolean;\n /** Accumulates usage/cost for one node. Reasoning stays out of `output` (§6.3). */\n charge(node: NodeKey, usage: Usage, cost: { usd: number; pricingMissing: boolean }): void;\n /** Per-node breakdown for the ticket's provenance trail. */\n ledger(): CostLedger;\n /** Whole-run total — the per-ticket cost watched downstream. */\n total(): NodeCost;\n}\n\nfunction addCost(existing: NodeCost | undefined, usage: Usage, cost: { usd: number; pricingMissing: boolean }): NodeCost {\n const base = existing ?? ZERO_COST;\n return {\n input: base.input + usage.input,\n output: base.output + usage.output,\n reasoning: base.reasoning + usage.reasoning,\n usd: base.usd + cost.usd,\n // Sticky: one unpriced charge is enough to mark the whole node unpriced,\n // so a later zero-cost charge never makes it read as \"this was free\".\n pricingMissing: base.pricingMissing || cost.pricingMissing,\n };\n}\n\nexport function createBudget({ signal, maxToolCalls }: { signal: AbortSignal; maxToolCalls: number }): Budget {\n let toolCallsUsed = 0;\n const costs: CostLedger = {};\n\n return {\n signal,\n\n consumeToolCall(): void {\n toolCallsUsed += 1;\n },\n\n exhausted(): boolean {\n return toolCallsUsed >= maxToolCalls || signal.aborted;\n },\n\n charge(node, usage, cost): void {\n costs[node] = addCost(costs[node], usage, cost);\n },\n\n ledger(): CostLedger {\n return { ...costs };\n },\n\n total(): NodeCost {\n return Object.values(costs).reduce<NodeCost>(\n (acc, entry) => addCost(acc, entry, { usd: entry.usd, pricingMissing: entry.pricingMissing }),\n ZERO_COST,\n );\n },\n };\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\nfunction 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 * Applies tags BY OUTCOME, exactly as the legacy (§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 * 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 */\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 if (outcome === 'needs_human') await ports.state.flag(ref, audit.needsHumanTag);\n if (outcome === 'guardrail_hold') await ports.state.flag(ref, audit.escalationTag);\n if (outcome === 'sent') {\n await ports.state.flag(ref, audit.sentTag);\n if (requiresFollowup(verdict?.verdict ?? null)) await ports.state.flag(ref, audit.followupTag);\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] 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: ['ready', 'failed', 'no_reply_needed', 'sending', 'invalidated'],\n ready: ['sending', 'invalidated', 'expired'],\n sending: ['sent', 'ready'],\n sent: [],\n failed: [],\n no_reply_needed: [],\n invalidated: [],\n expired: [],\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 * Parsing for Langfuse prompt-composition reference tags\n * (`@@@langfusePrompt:name=<name>|label=<label>@@@` or `|version=<n>@@@`).\n *\n * Ported from legacy `services/promptReferences.ts` (spec §3.7: \"la\n * composition … est résolue par le kit (port de `promptReferences.ts`)\").\n * `parseReferences`/`hasReferences` are pure and dependency-free, exactly as\n * in the legacy module, so `resolver.ts`'s composition pass and the\n * write-through cache guard can both depend on them without pulling in any\n * network/DB concern.\n *\n * `validateReferences` (the admin save-time validator) is NOT ported here:\n * it is an authoring-time concern for the prompt-editing UI (AgentsPage /\n * SharedPromptsPage, §3.8), not part of `PromptPort`'s runtime resolution\n * ladder — out of scope for T19. See the module doc in `resolver.ts` for the\n * runtime composition pass this package does own.\n *\n * `REFERENCE_TAG_SOURCE` (T23 post-review B3): the regex SOURCE, not the\n * stateful `g`-flagged object itself — `functions/validate-references.ts`\n * needs the exact same grammar to tell a well-formed tag from one that only\n * looks like one, and a hand-forked copy silently drifts the moment this\n * one gains a form. Exporting the source string (not `REF_RE`) keeps every\n * importer building its own `RegExp` instance, exactly like `hasReferences`\n * already does below — nobody shares, and therefore nobody can corrupt,\n * `REF_RE.lastIndex`.\n */\n\nconst REF_RE = /@@@langfusePrompt:name=([^|@]+)\\|(?:version=(\\d+)|label=([^@]+))@@@/g;\n\nexport const REFERENCE_TAG_SOURCE = REF_RE.source;\n\nexport interface PromptReference {\n name: string;\n version?: number;\n label?: string;\n raw: string;\n}\n\n/** Parse every well-formed reference tag out of `content`, in order of appearance. */\nexport function parseReferences(content: string): PromptReference[] {\n const refs: PromptReference[] = [];\n for (const [raw, name, version, label] of content.matchAll(REF_RE)) {\n refs.push(version !== undefined ? { name: name as string, version: Number(version), raw } : { name: name as string, label, raw });\n }\n return refs;\n}\n\n/**\n * Cheap synchronous check for \"does this content contain any reference tag\".\n * Used by the write-through cache guard (`resolver.ts`) to decide whether\n * raw content is safe to mirror into the `prompt-cache` record — a fresh\n * `new RegExp` avoids mutating the shared, stateful `REF_RE.lastIndex`.\n */\nexport function hasReferences(content: string): boolean {\n return new RegExp(REF_RE.source).test(content);\n}\n","/**\n * `PromptPort` implementation — §3.7's three-level fallback, ported from\n * legacy `services/promptStore.ts`'s `getActive` ladder:\n *\n * 1. `ctx.api.prompts.get(name, {label:'production', resolve:false})`\n * (T5's platform surface, reached only through the injected\n * `PlatformPromptReader` seam below — this package may not import\n * `@wopilo/*` or reach the network itself). A 60 s in-memory cache sits\n * in front of it, mirroring the legacy SDK's own `cacheTtlSeconds`.\n * Composition tags (`@@@langfusePrompt:name=…@@@`) are resolved by\n * THIS module (`composeReferences` below) — T5's surface reads raw\n * only, unlike legacy's `c.prompt.get` which flattened composition\n * server-side. Composition targets are read through the SAME memory\n * cache as the root prompt (post-review D1) — without that, a template\n * with N reference tags paid for N extra, uncached, sequentially\n * awaited Langfuse round-trips on every single call, TTL or not.\n * 2. The `prompt-cache` record mirror (T20's record, T21's adapter) —\n * reached only through the injected `PromptCachePort` seam. Written\n * through on every successful NON-EMPTY level-1 read, AFTER composition\n * (post-review C): the content mirrored is the fully composed,\n * tag-free text, not the raw pre-composition template. Composing first\n * means a Langfuse outage now degrades to the last-known-good COMPOSED\n * prompt instead of skipping the mirror for every prompt that uses\n * composition (`shared/style-email`/`shared/style-whatsapp` consumers,\n * in particular) — `hasReferences` stays as a cheap, should-never-fire\n * assertion guarding the same invariant it always did: no raw\n * `@@@…@@@` tag may ever reach the `prompt-cache` mirror.\n * 3. `ref.fallback` (the in-code default carried by the `PromptRef` the\n * caller passed in, itself populated from `config.defaults.prompts` at\n * `buildSupportPipeline` assembly time — T20).\n *\n * …and if that last rung is empty too, `MissingPromptError` (C5 as\n * amended, `graph/ports.ts`). \"Empty\" moves DOWN the ladder at every\n * rung, it does not end it: a level that answers with no text (a blank\n * Langfuse version, a mirror entry holding nothing) is that level coming\n * up empty, not the install having no prompt — only the bottom of the\n * ladder raises. This ladder used to terminate at empty\n * text, version 0 — a step reaching the model with no system message\n * at all, reported as a normal run. A step with no prompt is a broken\n * install: it fails the run, loudly, naming the prompt that resolved\n * to nothing. The settings-time half of the same rule is\n * `settings/validate.ts`, which refuses to run a pipeline whose active\n * steps name no prompt at all.\n *\n * Model config (`ResolvedPrompt.config`): populated from the level-1 read's\n * `RawPrompt.config` (T5's `PromptDetail.config`, once threaded through by\n * the platform adapter). Levels 2 and 3 still report `null` today, but for\n * different reasons now that T20 has landed the records: the `prompt-cache`\n * record (§3.4) DOES carry a `config JSON?` column — this module simply\n * neither writes nor reads it yet, so level 2 has a place to recover a\n * config from and does not use it (T21's `PromptCachePort` adapter is where\n * that gets wired). `PromptRef.fallback` carries no config field at all, so\n * level 3 is `null` by construction, not by omission.\n *\n * Cache scope: `createPromptResolver` holds NO module-level state — every\n * call returns a fresh closure over its own `Map`, so two calls (two\n * app instances, or two tests) never share a memory cache. A caller that\n * wants one long-lived resolver per app process constructs it once at\n * startup (T21); a test that wants a clean slate just calls the factory\n * again. The optional `now` hook replaces `Date.now()` for tests that need\n * to force an entry stale without `vi.useFakeTimers`.\n *\n * `onDegraded` (post-review E): the kit has no logging port, and should not\n * grow one just for this — but every point below where this ladder silently\n * empties a segment or falls a level is otherwise indistinguishable from a\n * correct run to an operator. This optional hook fires at each of those\n * points; T21 wires it to the platform logger.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { PromptRef } from '../domain/profile';\nimport { MissingPromptError, type PromptPort, type ResolvedPrompt } from '../graph/ports';\nimport { hasReferences, parseReferences, type PromptReference } from './references';\n\nconst PRODUCTION_LABEL = 'production';\nconst DEFAULT_TTL_MS = 60_000;\n\n/**\n * Langfuse's own prompt-composition resolver caps a reference chain at 5\n * levels; a linear A→B→C… chain here is otherwise bounded only by the\n * number of distinct prompt names, each hop a sequential awaited round-trip\n * inside the LLM path. Matching Langfuse's own cap keeps this module's\n * worst case aligned with the platform it is standing in for.\n *\n * Exported (T23 post-review B1) so `functions/validate-references.ts` can\n * reject, AT SAVE TIME, a chain that would silently degrade past this exact\n * cap at runtime — restating the number there would only let the two drift.\n */\nexport const MAX_COMPOSITION_DEPTH = 5;\n\n/**\n * Back-compat key: the bare name for the default label (legacy `cacheId`),\n * name + NUL + label otherwise. The joint is a NUL byte, not the legacy\n * `::` — prompt names are free-form now (Langfuse is the naming authority),\n * so a name may itself contain `::` and a printable delimiter would let\n * (`a::b`, production) and (`a`, label `b`) collide on one entry.\n */\nfunction cacheKey(name: string, label: string): string {\n return label === PRODUCTION_LABEL ? name : `${name}\\u0000${label}`;\n}\n\n/**\n * Memory-cache key for a platform read. A version-pinned read (a composition\n * target naming `|version=n`) is keyed on the version, since a label can\n * float across versions but a pinned version never does — collapsing it onto\n * `cacheKey`'s label-shaped key would either merge two distinct versions\n * under one entry or never hit at all. JSON-encoded (the shape tag keeps a\n * version key from ever colliding with a label key, whatever the name\n * contains) — this cache is per-process, so unlike `cacheKey` there is no\n * stored back-compat to preserve.\n */\nfunction memoryKey(name: string, opts: { label?: string; version?: number }): string {\n if (opts.version !== undefined) return JSON.stringify(['v', name, opts.version]);\n return JSON.stringify(['l', name, opts.label ?? PRODUCTION_LABEL]);\n}\n\n/**\n * Mustache-style `{{var}}` substitution — mirrors legacy `compileFallback`.\n * Uses the function form of `replaceAll` (post-review D3): a plain string\n * replacement interprets `$&`/`` $` ``/`$'`/`$1` specially, so a value\n * containing a literal `$&` (a quoted ticket excerpt, for instance) would\n * silently splice the matched placeholder back into the compiled prompt.\n */\nfunction substituteVars(text: string, vars: Record<string, string> | undefined): string {\n if (!vars) return text;\n return Object.entries(vars).reduce((out, [key, value]) => out.replaceAll(`{{${key}}}`, () => value), text);\n}\n\n/** One reference tag's target config, as read off T5's `PromptDetail.config`. */\nexport interface RawPromptConfig {\n model?: string;\n temperature?: number;\n}\n\n/** Raw (uncompiled, composition-unresolved) prompt content read at a given name+label/version. */\nexport interface RawPrompt {\n version: number;\n content: string;\n /**\n * Model config carried by the platform prompt, when the endpoint returns\n * one. Optional/absent (not just `null`) so every existing raw literal\n * built before this field existed still type-checks unchanged.\n */\n config?: RawPromptConfig | null;\n}\n\n/**\n * Seam onto T5's `ctx.api.prompts.get(name, {label|version, resolve:false})`.\n * May throw (network error, 404, unconfigured Langfuse, …) — the resolver\n * treats any rejection as a level-1 miss and falls through the ladder. T21\n * supplies the real adapter; `testing/fakes` supplies a test double.\n */\nexport interface PlatformPromptReader {\n get(name: string, ref: { label?: string; version?: number }): Promise<RawPrompt>;\n}\n\n/** One entry of the `prompt-cache` mirror (§3.4) — always RESOLVED content, never a raw reference tag. */\nexport interface PromptCacheEntry {\n content: string;\n version: number;\n}\n\n/**\n * Seam onto the `prompt-cache` record (T20's schema, T21's adapter). Both\n * methods are best-effort from the resolver's point of view — a rejection\n * from either is caught and treated as a miss/no-op, exactly like legacy's\n * Mongo cache: a `prompt-cache` outage must never block the LLM path.\n */\nexport interface PromptCachePort {\n read(key: string): Promise<PromptCacheEntry | null>;\n write(key: string, entry: PromptCacheEntry): Promise<void>;\n}\n\n/**\n * One silent-degradation event (post-review E). `stage` names the point in\n * the ladder that gave up on the \"real\" answer and returned something safe\n * instead; `name` is the prompt/reference name involved; `reason` is a\n * human-readable cause, not a typed error (the kit has no logging/error\n * taxonomy to spend here — that is T21's job once this reaches a real\n * logger).\n */\nexport interface PromptDegradedEvent {\n stage:\n | 'platform-unavailable'\n | 'cache-unavailable'\n | 'composition-target-missing'\n | 'composition-target-forbidden'\n | 'composition-cycle'\n | 'composition-depth-exceeded'\n /**\n * A level answered, and answered with nothing — a Langfuse prompt whose\n * production version is blank (`platform-empty`), or a `prompt-cache`\n * mirror entry holding no text (`cache-empty`). Distinct from the\n * `-unavailable` stages above, which are the level failing to answer at\n * all: both descend, but only these two mean the level was reachable and\n * said nothing. The one an operator needs to see, because nothing else\n * reports that the prompt they just edited is now empty.\n */\n | 'platform-empty'\n | 'cache-empty'\n /**\n * Not a degradation but its terminus: the ladder resolved no text at any\n * level and the run is about to fail on `MissingPromptError`. Emitted\n * here anyway so an operator reading the degradation log sees the whole\n * ladder's story, ending in the reason, rather than the exception alone\n * with no trace of what was tried.\n */\n | 'prompt-missing';\n name: string;\n reason: string;\n}\n\nexport interface PromptResolverDeps {\n platform: PlatformPromptReader;\n cache: PromptCachePort;\n /** Memory-cache TTL override, ms. Defaults to 60 000 (§3.7). */\n ttlMs?: number;\n /** Injectable clock for the memory cache, defaults to `Date.now`. */\n now?: () => number;\n /** Fires at every silent-degradation point in the ladder (post-review E). */\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\ninterface MemoryCacheEntry {\n /** Fully composed content — no remaining reference tag — never the raw fetch. */\n content: string;\n version: number;\n config?: RawPromptConfig | null;\n expiresAt: number;\n}\n\ninterface ComposeContext {\n platform: PlatformPromptReader;\n memory: Map<string, MemoryCacheEntry>;\n ttlMs: number;\n now: () => number;\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\nfunction reasonOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * `parseReferences` returns one entry per OCCURRENCE, not per distinct\n * target (post-review D2) — a template that repeats the same tag twice must\n * still only fetch it once. `ref.raw` identifies the target uniquely enough\n * for this purpose: two occurrences of the same tag share the same raw\n * string, and `replaceAll` below already replaces every occurrence in one\n * pass once the tag is deduped.\n */\nfunction dedupeByRaw(refs: PromptReference[]): PromptReference[] {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n if (seen.has(ref.raw)) return false;\n seen.add(ref.raw);\n return true;\n });\n}\n\nfunction stripReferences(content: string, refs: PromptReference[]): string {\n let out = content;\n for (const ref of dedupeByRaw(refs)) out = out.replaceAll(ref.raw, () => '');\n return out;\n}\n\n/**\n * Fetches `name` at `opts`, composes its references, and caches the\n * COMPOSED result (post-review D1) — shared by both the root prompt read\n * and every composition target, so a reference fetched once by any caller\n * within the TTL window is never fetched again, root or nested.\n */\nasync function readComposed(\n name: string,\n opts: { label?: string; version?: number },\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<MemoryCacheEntry> {\n const key = memoryKey(name, opts);\n const cached = ctx.memory.get(key);\n if (cached && cached.expiresAt > ctx.now()) return cached;\n\n const raw = await ctx.platform.get(name, opts);\n const content = await composeReferences(raw.content, ctx, visited, depth);\n const entry: MemoryCacheEntry = { content, version: raw.version, config: raw.config, expiresAt: ctx.now() + ctx.ttlMs };\n ctx.memory.set(key, entry);\n return entry;\n}\n\n/**\n * Resolves one reference tag to its replacement text: empty on a cycle\n * (visited) or an unresolvable target (fetch/compose throws), the target's\n * own composed content otherwise. Never leaves the literal tag in place —\n * the guarantee this module exists to hold (\"no raw tag reaches the LLM\")\n * applies here, not only through the write-through cache guard.\n */\nasync function resolveOneReference(\n ref: PromptReference,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (visited.has(ref.name)) {\n ctx.onDegraded?.({ stage: 'composition-cycle', name: ref.name, reason: 'cyclic composition reference' });\n return '';\n }\n\n const targetOpts = ref.version !== undefined ? { version: ref.version } : { label: ref.label };\n try {\n const target = await readComposed(ref.name, targetOpts, ctx, new Set([...visited, ref.name]), depth + 1);\n return target.content;\n } catch (err) {\n // M1 (T25 review): a 403 (the target exists but is outside this app's\n // role.prompts allowlist) is a MISCONFIGURATION, not a missing prompt —\n // reported under its own stage so `onDegraded` can name the allowlist\n // instead of reading identically to \"prompt/version/label not found\".\n // Still resolves to '' either way (PromptPort.resolve may never reject,\n // graph/ports.ts's C5) — this only makes the degradation legible.\n const forbidden = err instanceof AppApiError && err.status === 403;\n ctx.onDegraded?.({\n stage: forbidden ? 'composition-target-forbidden' : 'composition-target-missing',\n name: ref.name,\n reason: reasonOf(err),\n });\n return '';\n }\n}\n\n/**\n * Resolves every reference tag in `content`, one round-trip per DISTINCT\n * target (post-review D2), using the function form of `replaceAll`\n * (post-review D3 — see `substituteVars`'s doc comment for why). `depth`\n * bounds the chain at `MAX_COMPOSITION_DEPTH` (post-review D4): past it, the\n * remaining tags are stripped rather than followed one hop further, so a\n * long linear A→B→C… chain degrades instead of costing one sequential\n * round-trip per hop indefinitely.\n */\nasync function composeReferences(\n content: string,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (!hasReferences(content)) return content;\n\n const refs = parseReferences(content);\n if (depth >= MAX_COMPOSITION_DEPTH) {\n for (const ref of dedupeByRaw(refs)) {\n ctx.onDegraded?.({\n stage: 'composition-depth-exceeded',\n name: ref.name,\n reason: `composition chain exceeded ${MAX_COMPOSITION_DEPTH} levels`,\n });\n }\n return stripReferences(content, refs);\n }\n\n let resolved = content;\n for (const ref of dedupeByRaw(refs)) {\n const replacement = await resolveOneReference(ref, ctx, visited, depth);\n resolved = resolved.replaceAll(ref.raw, () => replacement);\n }\n return resolved;\n}\n\n/** Narrows a raw config blob to `ResolvedPrompt.config`'s stricter shape (model required, not just optional). */\nfunction toResolvedConfig(config: RawPromptConfig | null | undefined): ResolvedPrompt['config'] {\n if (!config || typeof config.model !== 'string' || config.model.length === 0) return null;\n return config.temperature !== undefined ? { model: config.model, temperature: config.temperature } : { model: config.model };\n}\n\n/** Builds a `PromptPort` implementing §3.7's three-level fallback ladder. */\nexport function createPromptResolver(deps: PromptResolverDeps): PromptPort {\n const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;\n const now = deps.now ?? Date.now;\n const memory = new Map<string, MemoryCacheEntry>();\n const composeCtx: ComposeContext = { platform: deps.platform, memory, ttlMs, now, onDegraded: deps.onDegraded };\n\n async function resolveFromCacheOrFallback(\n name: string,\n label: string,\n ref: PromptRef,\n vars: Record<string, string> | undefined,\n ): Promise<ResolvedPrompt> {\n const cached = await deps.cache.read(cacheKey(name, label)).catch((err: unknown) => {\n deps.onDegraded?.({ stage: 'cache-unavailable', name, reason: reasonOf(err) });\n return null;\n });\n if (cached) {\n const text = substituteVars(cached.content, vars);\n if (text.trim() !== '') return { name, text, version: cached.version, config: null };\n // A mirror entry that holds no text is this rung coming up empty, not\n // the ladder ending: C5 reserves `MissingPromptError` for every level\n // being empty. Descend to the in-code default below.\n deps.onDegraded?.({ stage: 'cache-empty', name, reason: 'the prompt-cache mirror holds no text' });\n }\n\n // M3 (T25 review): `ref.fallback` (config.defaults.prompts, wired T25)\n // is the one rung of the ladder that used to skip composition entirely\n // — a fallback authored with the house `@@@langfusePrompt:...@@@` idiom\n // (the same syntax every legacy prompt already uses) would reach the\n // LLM as a literal, unresolved tag the moment Langfuse AND the\n // prompt-cache mirror were both unavailable, violating this module's\n // own \"no raw tag reaches the LLM\" guarantee. Composed through the same\n // `composeCtx` (and so the same memory cache) as every other level.\n const rawFallback = ref.fallback ?? '';\n const text = hasReferences(rawFallback)\n ? await composeReferences(rawFallback, composeCtx, new Set([name]), 0)\n : rawFallback;\n return served({ name, text: substituteVars(text, vars), version: 0, config: null }, label);\n }\n\n /**\n * The ladder's terminus, and only its terminus. C5 (`graph/ports.ts`) makes\n * `MissingPromptError` the answer to \"every level came up empty\", not to\n * \"this level came up empty\" — every rung above descends instead of\n * throwing, so the only resolution that reaches this check with no text is\n * one where Langfuse, the `prompt-cache` mirror and the ref's in-code\n * fallback all said nothing. That is the broken install the error names.\n *\n * Whitespace counts as empty — a prompt of three newlines says nothing to a\n * model, and a name that resolves to one is the same broken install as a\n * name that resolves to nothing.\n */\n function served(resolved: ResolvedPrompt, label: string): ResolvedPrompt {\n if (resolved.text.trim() === '') {\n deps.onDegraded?.({ stage: 'prompt-missing', name: resolved.name, reason: 'no prompt content at any level' });\n throw new MissingPromptError(resolved.name, label);\n }\n return resolved;\n }\n\n return {\n async resolve(ref: PromptRef, vars?: Record<string, string>): Promise<ResolvedPrompt> {\n const label = ref.label?.trim() || PRODUCTION_LABEL;\n const persistKey = cacheKey(ref.name, label);\n\n let resolved: MemoryCacheEntry;\n try {\n resolved = await readComposed(ref.name, { label }, composeCtx, new Set([ref.name]), 0);\n } catch (err) {\n deps.onDegraded?.({ stage: 'platform-unavailable', name: ref.name, reason: reasonOf(err) });\n return resolveFromCacheOrFallback(ref.name, label, ref, vars);\n }\n\n // Write-through, AFTER composition (§3.7 invariant, post-review C):\n // only ever mirror composed, tag-free content. `hasReferences` here is\n // a should-never-fire assertion, not a decision point — composition\n // above already strips every matched tag by construction.\n //\n // Gated on the COMPOSED content being non-empty, not on this call's\n // substituted text: a Langfuse version someone has just blanked must\n // never overwrite the mirror's last-known-good entry with that\n // emptiness — that mirror is the very rung the ladder is about to\n // descend to. A template that merely substitutes to nothing for one\n // call's `vars` is still the prompt worth mirroring.\n if (resolved.content.trim() !== '' && !hasReferences(resolved.content)) {\n await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => undefined);\n }\n\n const text = substituteVars(resolved.content, vars);\n if (text.trim() === '') {\n // The platform answered, and answered with nothing. That is this rung\n // being empty, not the install having no prompt at all (C5), so the\n // ladder continues: the mirror still holds the last content that did\n // say something, and the ref still carries its in-code default.\n deps.onDegraded?.({ stage: 'platform-empty', name: ref.name, reason: 'the platform read resolved to no text' });\n return resolveFromCacheOrFallback(ref.name, label, ref, vars);\n }\n\n return { name: ref.name, text, version: resolved.version, config: toResolvedConfig(resolved.config) };\n },\n };\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';\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';\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';\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 * A relation's `targetRef` names the app the target record lives in\n * (`app:<slug>/<objectKey>`, resolved by `app-records.service.ts`), and the\n * kit is never installed under the slug `support-kit`: it is spread into\n * `experience-client`, `pro-sante`, … Every record carrying a relation is\n * therefore built per consuming app, from that app's own slug (§3.2's\n * `config.slug`), never from a literal.\n */\nexport function targetRefFor(slug: string, objectKey: string): string {\n return `app:${slug}/${objectKey}`;\n}\n","/**\n * `category` (ex-`Category`) — spec §3.4.\n *\n * `tagName` is matched exactly, case-sensitively, against Gorgias tags — it is\n * NOT normalised anywhere in this definition, on purpose: the handler that\n * applies tags (T22+) must compare byte-for-byte with what Gorgias sends back.\n *\n * The legacy `auto_reply_min_confidence` field is deliberately not ported —\n * the spec records it as already neutralised upstream in the legacy system.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_OBJECT_UID,\n CATEGORY_FIELD_NAME_UID,\n CATEGORY_FIELD_TAG_NAME_UID,\n CATEGORY_FIELD_ORDER_UID,\n CATEGORY_FIELD_GROUP_ID_UID,\n CATEGORY_FIELD_AGENT_ID_UID,\n CATEGORY_FIELD_EXTRA_TAGS_UID,\n CATEGORY_FIELD_DESCRIPTION_UID,\n CATEGORY_FIELD_EXAMPLES_UID,\n CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n CATEGORY_INDEX_TAG_NAME_UID,\n CATEGORY_INDEX_NAME_UID,\n CATEGORY_INDEX_ORDER_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildCategoryRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: CATEGORY_OBJECT_UID,\n objectKey: 'category',\n labelSingular: 'Category',\n labelPlural: 'Categories',\n description: 'A triage category, matched against a Gorgias tag.',\n fields: [\n {\n universalIdentifier: CATEGORY_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_TAG_NAME_UID,\n name: 'tagName',\n type: FieldType.TEXT,\n label: 'Gorgias tag',\n description: 'Matched exactly, case-sensitively, against Gorgias tags.',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_GROUP_ID_UID,\n name: 'groupId',\n type: FieldType.RELATION,\n label: 'Category group',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category-group'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXTRA_TAGS_UID,\n name: 'extraTags',\n type: FieldType.JSON,\n label: 'Extra tags',\n description: 'string[], at most 10 entries of at most 50 characters each.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: CATEGORY_FIELD_DESCRIPTION_UID,\n name: 'description',\n type: FieldType.TEXT,\n label: 'Description',\n description:\n 'Short definition of what belongs in this category — what triage shows the model to choose between categories. `examples` stays what it says: sample customer messages. Kept separate because the two feed the referential under different keys, and folding one into the other sends the same text twice.',\n // Nullable, and not merely by convention: every category already in a\n // tenant's base predates this field. A required one would fail the\n // read of every existing row.\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXAMPLES_UID,\n name: 'examples',\n type: FieldType.TEXT,\n label: 'Examples',\n description: 'At most 4000 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n name: 'fastResponseEnabled',\n type: FieldType.BOOLEAN,\n label: 'Fast response enabled',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n name: 'autoReplyEnabled',\n type: FieldType.BOOLEAN,\n label: 'Auto-reply enabled',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: CATEGORY_INDEX_TAG_NAME_UID, fields: ['tagName'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_NAME_UID, fields: ['name'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_ORDER_UID, fields: ['order'] },\n ],\n };\n}\n","/** `category-group` — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_GROUP_OBJECT_UID,\n CATEGORY_GROUP_FIELD_NAME_UID,\n CATEGORY_GROUP_FIELD_ORDER_UID,\n CATEGORY_GROUP_INDEX_NAME_UID,\n} from './ids';\n\nexport const categoryGroupRecord: ObjectDef = {\n universalIdentifier: CATEGORY_GROUP_OBJECT_UID,\n objectKey: 'category-group',\n labelSingular: 'Category group',\n labelPlural: 'Category groups',\n fields: [\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n ],\n indexes: [{ universalIdentifier: CATEGORY_GROUP_INDEX_NAME_UID, fields: ['name'], isUnique: true }],\n};\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 * `triage-decision` (ex-`TriageDecision`) — spec §3.4.\n *\n * `decidedAt` is indexed because the 24h/7d stat windows filter and bucket on\n * this DATA field, not on the system `createdAt` — a run replayed or\n * backfilled keeps the decision's own timestamp.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n TRIAGE_DECISION_OBJECT_UID,\n TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n TRIAGE_DECISION_FIELD_TICKET_URL_UID,\n TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n TRIAGE_DECISION_FIELD_TAG_UID,\n TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_REASONING_UID,\n TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n TRIAGE_DECISION_FIELD_ESCALATED_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n TRIAGE_DECISION_FIELD_STATUS_UID,\n TRIAGE_DECISION_FIELD_ERROR_UID,\n TRIAGE_DECISION_FIELD_RUN_ID_UID,\n TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n TRIAGE_DECISION_INDEX_TICKET_ID_UID,\n TRIAGE_DECISION_INDEX_DECIDED_AT_UID,\n TRIAGE_DECISION_INDEX_ESCALATED_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nconst CONFIDENCE_OPTIONS = ['high', 'low'] as const;\n\nexport function buildTriageDecisionRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: TRIAGE_DECISION_OBJECT_UID,\n objectKey: 'triage-decision',\n labelSingular: 'Triage decision',\n labelPlural: 'Triage decisions',\n fields: [\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket url',\n description:\n 'Deep link to the ticket in the helpdesk, resolved once per batch and frozen on the decision. Null on a decision written before this field existed, or when the connection exposes no public url (mock).',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n name: 'decidedAt',\n type: FieldType.DATE_TIME,\n label: 'Decided at',\n description: 'Backs the 24h/7d stat windows — not the system createdAt.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TAG_UID,\n name: 'tag',\n type: FieldType.TEXT,\n label: 'Tag',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n name: 'confidence',\n type: FieldType.SELECT,\n label: 'Confidence',\n isNullable: false,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_REASONING_UID,\n name: 'reasoning',\n type: FieldType.TEXT,\n label: 'Reasoning',\n description: 'At most 280 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n name: 'conversationOver',\n type: FieldType.BOOLEAN,\n label: 'Conversation over',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATED_UID,\n name: 'escalated',\n type: FieldType.BOOLEAN,\n label: 'Escalated',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n name: 'escalationConfidence',\n type: FieldType.SELECT,\n label: 'Escalation confidence',\n isNullable: true,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n name: 'escalationReasoning',\n type: FieldType.TEXT,\n label: 'Escalation reasoning',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: ['ok', 'error'],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_RUN_ID_UID,\n name: 'runId',\n type: FieldType.TEXT,\n label: 'Run id',\n description: 'The application run this decision was made under.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n name: 'subjectRenamed',\n type: FieldType.BOOLEAN,\n label: 'Subject renamed',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: TRIAGE_DECISION_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_DECIDED_AT_UID, fields: ['decidedAt'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_ESCALATED_UID, fields: ['escalated'] },\n ],\n };\n}\n","/**\n * `generated-response` (ex-`FastResponse`) — spec §3.4. Both the send queue\n * and the response cache.\n *\n * `status`'s option list is `GENERATED_RESPONSE_STATUSES` from\n * `../status/machine` — the single source of truth T16 already built for the\n * status vocabulary and its terminal/open partition — rather than a second\n * hardcoded list that could drift from it.\n *\n * `openTicketKey` reconstitutes the legacy \"one open job per ticket\"\n * guarantee as a Postgres unique index (NULLs are distinct): it is\n * `openTicketKeyFor(status, ticketId)` at write time (a T22+ handler\n * concern), so this definition intentionally does NOT restate which statuses\n * count as \"open\" — it only declares the field and its unique index.\n *\n * `autoSendDecision` is the field `reclaimStalledSend()` (T16) writes into\n * alongside `status: 'ready'` on the sweep's stalled-send reclaim.\n *\n * `expiresAt` is non-nullable: it is `generatedAt + responseTtlMinutes`,\n * known at creation time, and the sweep (`ready` expired -> `expired`, T22)\n * plus the extension's TTL check both read it unconditionally — a null there\n * would be a row that never expires.\n *\n * The JSON LIST fields (`sources`, `tracedInput`, `guardrailHits`,\n * `servedTo`) are non-nullable with a `[]` default, so no reader has to\n * distinguish \"null\" from \"empty\" before iterating; the single-object\n * `verdict` stays nullable, where `null` really does mean \"not evaluated\".\n *\n * T22 additions (all nullable — absent until the field's own write path\n * runs):\n * - `generatedMessageCount`/`generatedLastMessageAt` — a snapshot of\n * `Conversation.messageCount`/`lastMessageAt` taken by `process-response`\n * right before `runTicket`'s resumed run. `handle-approval` rebuilds a\n * placeholder `Conversation` for the `act` node's `generatedFrom`\n * argument out of exactly these two fields (plus `channel`) — see\n * `functions/handle-approval.ts` for why `act` never reads anything else\n * off that snapshot. This is a \"close enough\" generation-time reading,\n * not a live one: `act` always re-reads the conversation for real before\n * posting (I8), so a slightly stale baseline here only affects whether\n * THAT re-read counts as diverged, never send safety itself.\n * - `sendingAt` — when the record entered `status: 'sending'` (written by\n * the claim in `functions/claim-commit.ts`). Nothing else on this record\n * timestamps a status transition, and `sweep` needs to know how long a\n * `sending` row has been stuck to reclaim it (§3.5's 30-minute rule).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport { GENERATED_RESPONSE_STATUSES } from '../status/machine';\nimport {\n GENERATED_RESPONSE_OBJECT_UID,\n GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_FIELD_STATUS_UID,\n GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n GENERATED_RESPONSE_FIELD_SOURCES_UID,\n GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n GENERATED_RESPONSE_FIELD_VERDICT_UID,\n GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n GENERATED_RESPONSE_FIELD_ERROR_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n GENERATED_RESPONSE_INDEX_TICKET_ID_UID,\n GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_INDEX_STATUS_UID,\n GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_INDEX_GENERATED_AT_UID,\n GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildGeneratedResponseRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: GENERATED_RESPONSE_OBJECT_UID,\n objectKey: 'generated-response',\n labelSingular: 'Generated response',\n labelPlural: 'Generated responses',\n description: 'A drafted reply, from pending draft through its send outcome.',\n fields: [\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n name: 'openTicketKey',\n type: FieldType.TEXT,\n label: 'Open ticket key',\n description: \"= ticketId while status is open, cleared on a terminal status. Unique — see openTicketKeyFor().\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: [...GENERATED_RESPONSE_STATUSES],\n defaultValue: 'pending',\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n name: 'triageDecisionId',\n type: FieldType.RELATION,\n label: 'Triage decision',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'triage-decision'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n name: 'channel',\n type: FieldType.SELECT,\n label: 'Channel',\n isNullable: false,\n options: ['email', 'whatsapp'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n name: 'responseText',\n type: FieldType.TEXT,\n label: 'Response text',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCES_UID,\n name: 'sources',\n type: FieldType.JSON,\n label: 'Sources',\n description: '[{name, arguments, observation}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n name: 'tracedInput',\n type: FieldType.JSON,\n label: 'Traced input',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_VERDICT_UID,\n name: 'verdict',\n type: FieldType.JSON,\n label: 'Verdict',\n description: '{verdict, confidence, reason, status}',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n name: 'guardrailHits',\n type: FieldType.JSON,\n label: 'Guardrail hits',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n name: 'autoSendDecision',\n type: FieldType.SELECT,\n label: 'Auto-send decision',\n isNullable: true,\n options: ['auto', 'hold'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n name: 'followupRequired',\n type: FieldType.BOOLEAN,\n label: 'Followup required',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n name: 'servedCount',\n type: FieldType.NUMBER,\n label: 'Served count',\n isNullable: false,\n defaultValue: 0,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n name: 'servedTo',\n type: FieldType.JSON,\n label: 'Served to',\n description: '[{user, at}], capped at 500 entries. Updated via S5 ifMatch + retry.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n name: 'generatedAt',\n type: FieldType.DATE_TIME,\n label: 'Generated at',\n description: 'Backs the daily series stat.',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n name: 'expiresAt',\n type: FieldType.DATE_TIME,\n label: 'Expires at',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n name: 'sentAt',\n type: FieldType.DATE_TIME,\n label: 'Sent at',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n name: 'sentMessageId',\n type: FieldType.TEXT,\n label: 'Sent message id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n name: 'generatedMessageCount',\n type: FieldType.NUMBER,\n label: 'Generated message count',\n description: \"Conversation.messageCount snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n name: 'generatedLastMessageAt',\n type: FieldType.DATE_TIME,\n label: 'Generated last message at',\n description: \"Conversation.lastMessageAt snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n name: 'sendingAt',\n type: FieldType.DATE_TIME,\n label: 'Sending at',\n description: \"When status became 'sending' — the sweep's staleness clock (§3.5).\",\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: GENERATED_RESPONSE_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n fields: ['openTicketKey'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_STATUS_UID, fields: ['status'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n fields: ['triageDecisionId'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, fields: ['generatedAt'] },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, fields: ['expiresAt'] },\n ],\n };\n}\n","/** `response-comparison` (ex-`ResponseComparison`) — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n RESPONSE_COMPARISON_OBJECT_UID,\n RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n RESPONSE_COMPARISON_FIELD_DIFF_UID,\n RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_INDEX_TICKET_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildResponseComparisonRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: RESPONSE_COMPARISON_OBJECT_UID,\n objectKey: 'response-comparison',\n labelSingular: 'Response comparison',\n labelPlural: 'Response comparisons',\n description: \"Compares the agent's draft against what the human actually sent.\",\n fields: [\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n name: 'generatedText',\n type: FieldType.TEXT,\n label: 'Generated text',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n name: 'sentText',\n type: FieldType.TEXT,\n label: 'Sent text',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n name: 'capturedAt',\n type: FieldType.DATE_TIME,\n label: 'Captured at',\n description: 'Backs the rewrite-rate trend.',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n name: 'conversationMessages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_DIFF_UID,\n name: 'diff',\n type: FieldType.JSON,\n label: 'Diff',\n description: 'Word-by-word diff, computed at write time.',\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, fields: ['capturedAt'] },\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n ],\n };\n}\n","/** `evaluation` (ex-`Evaluation`) — spec §3.4. No indexes named for this record. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n EVALUATION_OBJECT_UID,\n EVALUATION_FIELD_AGENT_ID_UID,\n EVALUATION_FIELD_SATISFIED_UID,\n EVALUATION_FIELD_MESSAGES_UID,\n EVALUATION_FIELD_TICKET_URL_UID,\n EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildEvaluationRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: EVALUATION_OBJECT_UID,\n objectKey: 'evaluation',\n labelSingular: 'Evaluation',\n labelPlural: 'Evaluations',\n description: 'A human satisfaction verdict on an agent conversation.',\n fields: [\n {\n universalIdentifier: EVALUATION_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: EVALUATION_FIELD_SATISFIED_UID,\n name: 'satisfied',\n type: FieldType.BOOLEAN,\n label: 'Satisfied',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — the conversation the verdict is about.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: EVALUATION_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n name: 'supportUserKeyId',\n type: FieldType.TEXT,\n label: 'Support user key id',\n isNullable: true,\n },\n ],\n };\n}\n","/**\n * `diff-analysis` (ex-`DiffAnalysis`) — spec §3.4.\n *\n * `uniqueKey` is `<agentId>::<promptName>::<promptVersion>`, computed by the\n * write handler (T22+) — this definition only declares the field and its\n * unique index, the equivalent of the legacy composite uniqueness.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n DIFF_ANALYSIS_OBJECT_UID,\n DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n DIFF_ANALYSIS_FIELD_POINTS_UID,\n DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\n/** `<agentId>::<promptName>::<promptVersion>` — spec §3.4. */\nexport function diffAnalysisUniqueKey(\n agentId: string,\n promptName: string,\n promptVersion: number,\n): string {\n return `${agentId}::${promptName}::${promptVersion}`;\n}\n\nexport function buildDiffAnalysisRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: DIFF_ANALYSIS_OBJECT_UID,\n objectKey: 'diff-analysis',\n labelSingular: 'Diff analysis',\n labelPlural: 'Diff analyses',\n description: 'Correction patterns aggregated for one (agent, prompt, version).',\n fields: [\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_POINTS_UID,\n name: 'points',\n type: FieldType.JSON,\n label: 'Points',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n name: 'uniqueKey',\n type: FieldType.TEXT,\n label: 'Unique key',\n description: '<agentId>::<promptName>::<promptVersion>',\n isNullable: false,\n },\n ],\n indexes: [\n { universalIdentifier: DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, fields: ['uniqueKey'], isUnique: true },\n ],\n };\n}\n","/**\n * `pipeline-state` — spec §3.4. Singleton per app; the kit's sole inter-app\n * contact point, read-only (`exposedToApps: ['*']`), purely informational —\n * §4's cross-app view-claim warning is what another app reads `sourceViewId`\n * for, to detect when two support-kit apps have been pointed at the same\n * Gorgias view.\n *\n * `sourceViewId` here mirrors the setting of the same name (§3.6) — it is\n * written by `triage-tick` (T22+), not by this definition.\n *\n * `singletonKey` (T22 hardening, A4 — a schema addition past §3.4's frozen\n * list, recorded as a deviation in the progress doc): `triage-tick` and\n * `sweep` are two independent crons that both fire every five minutes, and\n * on a fresh app both used to find the `list()` empty and both `create()` a\n * \"singleton\" row — nothing enforced only one existing, and `list` carries\n * no ordering guarantee, so `triage-tick` could thereafter read the\n * sweep-created row (no `lastTriageAt`) and silently skip its own cadence\n * gate on EVERY tick. A constant, always-the-same value plus a real unique\n * index turns \"singleton by convention\" into \"singleton by constraint\": the\n * first write goes through `upsert` on this key\n * (`functions/pipeline-state.ts`), so the platform's own `ON CONFLICT` — not\n * a race between two `list()`+`create()` pairs — is what decides there is\n * exactly one row. Subsequent writes go through `update()`, because `upsert`\n * REPLACES the document rather than merging it; see that module's own doc.\n */\nimport { FieldType } from '@apotech-os/app-kit';\nimport type { RecordDef } from './record-def';\nimport {\n PIPELINE_STATE_OBJECT_UID,\n PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n PIPELINE_STATE_INDEX_SINGLETON_KEY_UID,\n} from './ids';\n\nexport const pipelineStateRecord: RecordDef = {\n universalIdentifier: PIPELINE_STATE_OBJECT_UID,\n objectKey: 'pipeline-state',\n labelSingular: 'Pipeline state',\n labelPlural: 'Pipeline state',\n description: 'Singleton run-cadence and view-claim state, readable by every installed app.',\n fields: [\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n name: 'singletonKey',\n type: FieldType.TEXT,\n label: 'Singleton key',\n description: 'Always the same constant value — the unique index below is what makes this record a true singleton, not just a convention.',\n isNullable: false,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n name: 'sourceViewId',\n type: FieldType.TEXT,\n label: 'Source view id',\n description: 'The claimed Gorgias view — supports the cross-app overlap warning (§4).',\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n name: 'lastTriageAt',\n type: FieldType.DATE_TIME,\n label: 'Last triage at',\n description: \"Gates triage-tick's cadence.\",\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n name: 'lastSweepAt',\n type: FieldType.DATE_TIME,\n label: 'Last sweep at',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ['singletonKey'], isUnique: true }],\n exposedToApps: ['*'],\n};\n","/**\n * `prompt-cache` (ex-`PromptCache`) — spec §3.4, level-2 fallback of the\n * prompt ladder (§3.7).\n *\n * `config JSON?` — added beyond the spec's literal field list, on T19's\n * explicit deferral: the legacy cache carried the model config (not just the\n * compiled template), so invariant I16 (\"levels 2/3 keep working through a\n * Langfuse outage\") holds for the *prompt text* but not for the *config* a\n * caller needs alongside it — levels 2 and 3 of the resolver (T19) return\n * `config: null` today. Adding the column here is the minimal step: it makes\n * the record ABLE to carry a config without deciding its shape or wiring it\n * into the resolver. Follow-up (not T20): change `prompts/resolver.ts` to\n * read and write this column, and settle what \"config\" means for a cache row\n * (presumably the same `{model, reasoning}` shape used by `settings.nodes`).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n PROMPT_CACHE_OBJECT_UID,\n PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n PROMPT_CACHE_FIELD_CONTENT_UID,\n PROMPT_CACHE_FIELD_VERSION_UID,\n PROMPT_CACHE_FIELD_LABEL_UID,\n PROMPT_CACHE_FIELD_CONFIG_UID,\n PROMPT_CACHE_INDEX_PROMPT_KEY_UID,\n} from './ids';\n\nexport const promptCacheRecord: ObjectDef = {\n universalIdentifier: PROMPT_CACHE_OBJECT_UID,\n objectKey: 'prompt-cache',\n labelSingular: 'Prompt cache entry',\n labelPlural: 'Prompt cache entries',\n description: 'Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.',\n fields: [\n {\n universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n name: 'promptKey',\n type: FieldType.TEXT,\n label: 'Prompt key',\n description: \"'name' or 'name::label'.\",\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n description: 'Raw, uncompiled template.',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,\n name: 'version',\n type: FieldType.NUMBER,\n label: 'Version',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,\n name: 'label',\n type: FieldType.TEXT,\n label: 'Label',\n isNullable: true,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,\n name: 'config',\n type: FieldType.JSON,\n label: 'Config',\n description: 'Model config snapshot, for I16. Not yet written or read — see module doc.',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ['promptKey'], isUnique: true }],\n};\n","import { createHash } from 'node:crypto';\n\n/**\n * Kit-owned namespace UUID (RFC 4122 §4.3) — fixed and arbitrary, used only\n * as `deriveUid`'s namespace input. Never written to a manifest itself.\n */\nconst SUPPORT_KIT_UID_NAMESPACE = '2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f';\n\nfunction uuidToBytes(uuid: string): Buffer {\n return Buffer.from(uuid.replace(/-/g, ''), 'hex');\n}\n\nfunction bytesToUuid(bytes: Buffer): string {\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * A deterministic UUIDv5 over `seed` (RFC 4122 §4.3: SHA-1 of a namespace +\n * a name, with the version/variant bits fixed up). Same seed always yields\n * the same uid — no randomness, no `Date` — and different seeds yield\n * different uids with cryptographic collision resistance.\n *\n * Used by `scopeRecordToApp` (B1, T25 review) to turn the kit's own stable\n * per-record constants (`ids.ts`) into uids that are additionally scoped to\n * the consuming app's slug, so two different apps installing the same kit\n * never collide on `AppEntity.universalIdentifier` (globally unique on the\n * platform, not per application).\n */\nexport function deriveUid(seed: string): string {\n const hash = createHash('sha1').update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, 'utf8').digest();\n const bytes = hash.subarray(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x50; // version 5\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant RFC4122\n return bytesToUuid(bytes);\n}\n","import { deriveUid } from './derive-uid';\nimport type { RecordDef } from './record-def';\n\n/**\n * Rewrites every `universalIdentifier` in a kit record (object, fields,\n * indexes) from the kit's own stable constant (`ids.ts`) into one\n * deterministically derived from `(slug, that constant)` — B1, T25 review.\n *\n * Why: `ids.ts`'s constants are unique AMONG THEMSELVES, but the platform's\n * `AppEntity.universalIdentifier` is unique GLOBALLY, not per application\n * (`apps/api/prisma/schema.prisma`). Used as-is, the second app to install\n * this kit republishes the same 126 literals the first app already claimed\n * and hits an unhandled Prisma P2002 on publish. Scoping by slug keeps every\n * uid stable across rebuilds (pure function of the slug + the constant, no\n * randomness) while making two different consuming apps' uid sets disjoint.\n */\nexport function scopeRecordToApp(slug: string, record: RecordDef): RecordDef {\n return {\n ...record,\n universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),\n fields: record.fields.map((field) => ({\n ...field,\n universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`),\n })),\n indexes: record.indexes?.map((index) => ({\n ...index,\n universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`),\n })),\n };\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.4 — the kit's own\n// `ObjectDef` fragments, one module per record, assembled here into the\n// array a consuming app's manifest spreads into its own `records: [...]`.\n//\n// Every record that declares a RELATION is a factory over the consuming\n// app's slug (§3.2's `config.slug`), because a relation's `targetRef` is\n// `app:<slug>/<objectKey>` and the kit is installed as `experience-client`,\n// `pro-sante`, … — never as `support-kit`. The four records with no\n// relation stay plain constants: nothing about them varies per app.\nexport { buildCategoryRecord } from './category';\nexport { categoryGroupRecord } from './category-group';\nexport { agentRecord, AGENT_STATUSES, DEFAULT_LLM_PROVIDER, type AgentStatus } from './agent';\nexport { buildTriageDecisionRecord } from './triage-decision';\nexport { buildGeneratedResponseRecord } from './generated-response';\nexport { buildResponseComparisonRecord } from './response-comparison';\nexport { buildEvaluationRecord } from './evaluation';\nexport { buildDiffAnalysisRecord, diffAnalysisUniqueKey } from './diff-analysis';\nexport { pipelineStateRecord } from './pipeline-state';\nexport { promptCacheRecord } from './prompt-cache';\nexport { targetRefFor } from './target-ref';\nexport type { RecordDef } from './record-def';\n\nimport { buildCategoryRecord } from './category';\nimport { categoryGroupRecord } from './category-group';\nimport { agentRecord } from './agent';\nimport { buildTriageDecisionRecord } from './triage-decision';\nimport { buildGeneratedResponseRecord } from './generated-response';\nimport { buildResponseComparisonRecord } from './response-comparison';\nimport { buildEvaluationRecord } from './evaluation';\nimport { buildDiffAnalysisRecord } from './diff-analysis';\nimport { pipelineStateRecord } from './pipeline-state';\nimport { promptCacheRecord } from './prompt-cache';\nimport { scopeRecordToApp } from './scope-to-app';\nimport type { RecordDef } from './record-def';\n\n/**\n * All 10 records of §3.4, in the order the spec lists them, bound to the\n * consuming app's `slug` — the single assembly point `buildSupportPipeline`\n * (T25) spreads into a manifest.\n *\n * Every record/field/index `universalIdentifier` is additionally scoped to\n * `slug` via `scopeRecordToApp` (B1, T25 review): `ids.ts`'s constants are\n * stable per-record keys, not final manifest uids — two different consuming\n * apps installing this kit must never publish the same\n * `AppEntity.universalIdentifier` (unique platform-wide).\n */\nexport function buildSupportKitRecords(slug: string): RecordDef[] {\n return [\n buildCategoryRecord(slug),\n categoryGroupRecord,\n agentRecord,\n buildTriageDecisionRecord(slug),\n buildGeneratedResponseRecord(slug),\n buildResponseComparisonRecord(slug),\n buildEvaluationRecord(slug),\n buildDiffAnalysisRecord(slug),\n pipelineStateRecord,\n promptCacheRecord,\n ].map((record) => scopeRecordToApp(slug, record));\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 // 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 * Two 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) and\n * `statsTimezone` (a §3.8 rendering concern). `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';\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 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. */\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: {\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 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 * `SupportKitFunctionConfig` — what each manifest fragment\n * (`triage-tick`/`sweep`/`handle-approval`/…) needs to build its\n * `FunctionDef` (spec §3.2's `SupportPipelineConfig`, the slice of it these\n * fragments actually read — `buildSupportPipeline`, T25, owns the full\n * shape and passes this down).\n */\nimport type { PromptNameConfig } from '../prompts/slots';\n\n/** Stable keys this module looks up `identifiers` by — documented here so a caller can't guess wrong. */\nexport const FUNCTION_IDENTIFIER_KEYS = [\n // Single-pass (2026-09): 'process-response' left this list — the response\n // phase now runs inside triage-tick's own batch, not as a dbEvent worker.\n // A consuming app may still pass the old identifier; extra entries are\n // ignored, only missing ones throw.\n 'triage-tick',\n 'sweep',\n 'handle-approval',\n // T23 — the seven operator `uiInvoke` functions (§3.5's table).\n 'run-triage-now',\n // B5 — the event-triggered worker `run-triage-now` hands the batch to, so\n // the manual trigger answers inside its `uiInvoke` budget instead of\n // 504-ing halfway through a 30-ticket LLM pass (`run-triage-now.ts`'s doc).\n 'run-triage-batch',\n // Single-pass follow-up — the ticket panel's \"discard this draft\" action,\n // freeing the ticket for a full re-treatment (invalidate-response.ts).\n 'invalidate-response',\n 'preview-triage',\n // spec-vue-tickets-unifiee-v1 §4.2 — the ticket timeline's last-resort\n // conversation read, for the decisions no `generated-response` was ever\n // opened for (a ticket stopped at the tag) and the imported ones.\n 'get-ticket-conversation',\n 'graph-dry-run',\n 'test-agents',\n 'suggest-prompt',\n 'list-gorgias-views',\n // T26 rework — AgentsPage cannot create a valid agent or promote a default\n // one from raw record PATCHes alone (BLOCKER 3, BLOCKER 4); both are\n // write-handler concerns per records/agent.ts's own doc.\n 'create-agent',\n 'set-default-agent',\n // T27 part B — SharedPromptsPage's own write path: validates\n // `@@@langfusePrompt:…@@@` composition (`validateReferences`) before\n // writing a `shared/*` version, a check the raw S3 REST route does not run.\n 'create-shared-prompt-version',\n // §5.2 — `GET /models` serves `system_prompt` from `systemPromptSnapshot`\n // alone, so that snapshot has to be refreshed whenever a new version of an\n // agent's prompt starts being served.\n 'sync-agent-prompt-snapshot',\n // T24 — the six reserved `ext-*` functions (§5.2), the extension gateway's\n // only view of the kit.\n 'ext-models',\n 'ext-categories',\n 'ext-chat',\n 'ext-fast-response-check',\n 'ext-evaluation',\n 'ext-response-comparison',\n] as const;\n\nexport type FunctionIdentifierKey = (typeof FUNCTION_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitFunctionConfig extends PromptNameConfig {\n /** The consuming app's own slug — `app:<slug>/<objectKey>` dbEvent triggers, and the object relations. */\n slug: string;\n /**\n * §3.2's `SupportPipelineConfig.identifiers` — one `universalIdentifier`\n * per manifest function, keyed by the values in `FUNCTION_IDENTIFIER_KEYS`.\n * A manifest fragment with a missing id is broken by construction: looking\n * one up throws immediately rather than inventing a random one that would\n * drift on every rebuild.\n */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry (a broken manifest, not a runtime condition to recover from). */\nexport function identifierFor(config: SupportKitFunctionConfig, key: FunctionIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportKitFunctionConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit function needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * Derives the kit's domain `Conversation` from the SINGLE\n * `getTicketWithContext` fetch (`ctx-ports.ts`'s\n * `createGorgiasConversationPort`; B, T21 review), which returns both:\n *\n * - the RAW payload the guardrail detectors need (`isWhatsappTicket`,\n * `isJudgemeTicket`, `isAutomatedSenderTicket`, `isTicketClosed`,\n * `hasCustomerAttachment` — `guardrails/raw-ticket.ts`) and this\n * module's own message-count/timestamp snapshot.\n * - the ALREADY-EXTRACTED chronological messages + customer-info block a\n * node actually drafts against — its HTML-to-text conversion and\n * \"Information Client\" synthetic prefix are Gorgias-specific rendering\n * this package does not re-derive.\n *\n * `getRawTicket` and `buildTicketContext` used to be called as two separate\n * actions reading the exact same Gorgias endpoint (§S1) — a `read()` call\n * paid for it twice, and worse, the two fetches could observe different\n * server states if a message landed between them. `getTicketWithContext`\n * (`@wopilo/gorgias-client`) fetches once and derives both halves from that\n * one payload, so the raw-based facts and the domain conversation are now\n * GUARANTEED — not just assumed — to describe the exact same server\n * response.\n */\nimport {\n hasCustomerAttachment,\n isTicketClosed,\n isWhatsappChevronNote,\n isWhatsappTicket,\n type RawTicket,\n} from '../guardrails';\nimport type { Conversation, ConversationRef, Message } from '../domain';\n\ntype RawMessage = NonNullable<RawTicket['messages']>[number];\n\n/** One turn of `buildTicketContext`'s already-extracted conversation. */\nexport interface RawTicketContextMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n synthetic?: boolean;\n}\n\n/** The shape `ctx.api.integrations.run('gorgias', 'buildTicketContext', …)` returns. */\nexport interface RawTicketContext {\n messages: RawTicketContextMessage[];\n customerContext: string | null;\n customerName?: string | null;\n customerEmail?: string | null;\n}\n\n/**\n * Same predicate `guardrails/raw-ticket.ts` uses internally, un-exported\n * there. Duplicated here BY HAND, same precedent that module's own doc\n * gives for its copy of `@wopilo/gorgias-client`'s `isInternalNoteChannel`:\n * this package may not import that client, so the one-line rule is kept in\n * sync manually rather than reached for through a forbidden import.\n */\nfunction isInternalNoteChannel(message: RawMessage): boolean {\n return message.channel === 'internal-note' || message.source?.type === 'internal-note';\n}\n\n/**\n * Port of `@wopilo/gorgias-client`'s `countableMessages` (`ticket-context.ts`)\n * — the divergence-snapshot rule. This package cannot import that package\n * (dependency-allowlist), so it is kept in sync by hand.\n *\n * \"Has extractable text\" checks PRESENCE across `body_text`/`body_html`/\n * `stripped_text`/`stripped_html` — not conversion. The client's own\n * `extractMessageText` prefers HTML and runs it through `htmlToText`\n * (T3-review-A5: an HTML-only customer reply has a blank `body_text`, so\n * checking that field alone misses a real turn — invisible to\n * `Conversation.messageCount`/`lastMessageAt`, so `act`'s divergence check\n * never sees the customer replied and a stale draft gets auto-sent). This\n * package cannot port `htmlToText` in, so it stays on the SAFE side instead:\n * any non-blank field counts, even a `<br>`-only body that `htmlToText`\n * would reduce to nothing. That can only ever over-count — producing a\n * spurious *hold*, never a spurious send.\n */\nfunction countableMessages(messages: RawMessage[], isWhatsapp: boolean): RawMessage[] {\n return messages.filter((m) => {\n if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);\n const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());\n const hasAttachment = (m.attachments?.length ?? 0) > 0;\n return hasText || hasAttachment;\n });\n}\n\nexport interface ConversationSnapshot {\n count: number;\n lastAt: Date | null;\n}\n\n/** Message count + last-message timestamp — feeds `Conversation.messageCount`/`lastMessageAt` (I8's anti-divergence snapshot). */\nexport function snapshotConversation(raw: RawTicket): ConversationSnapshot {\n const isWhatsapp = isWhatsappTicket(raw);\n const messages = countableMessages(raw.messages ?? [], isWhatsapp);\n let lastAt: Date | null = null;\n for (const m of messages) {\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!lastAt || at > lastAt) lastAt = at;\n }\n return { count: messages.length, lastAt };\n}\n\n/**\n * When an agent (human or our own auto-reply) last spoke. Deliberately\n * applies NO countability/text test of its own — it follows\n * `raw-ticket.ts`'s `hasAgentReplySince` (channel/chevron rule only),\n * generalised from a boolean since-a-date check to the timestamp itself,\n * since `Conversation.lastAgentReplyAt` needs the value, not a threshold.\n * That is the safe direction: an agent message with no extractable text\n * still counts as \"the agent spoke\", so this never under-reports the last\n * agent activity.\n */\nfunction lastAgentReplyAtOf(raw: RawTicket): Date | null {\n const isWhatsapp = isWhatsappTicket(raw);\n let latest: Date | null = null;\n for (const m of raw.messages ?? []) {\n if (m.from_agent !== true) continue;\n if (isInternalNoteChannel(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!latest || at > latest) latest = at;\n }\n return latest;\n}\n\n/**\n * Assembles the domain `Conversation`. `sourceChannel` honours the T15\n * contract restated in `graph/ports.ts`'s `Conversation` doc: `'whatsapp'`\n * IFF `isWhatsappTicket(raw)`, never a bare `raw.channel` read.\n */\nexport function toConversation(ref: ConversationRef, raw: RawTicket, context: RawTicketContext): Conversation {\n const snapshot = snapshotConversation(raw);\n const messages: Message[] = context.messages\n .filter((m): m is RawTicketContextMessage & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')\n .map((m) => ({ role: m.role, content: m.content }));\n\n return {\n ref,\n subject: raw.subject ?? null,\n messages,\n customer: {\n name: context.customerName ?? null,\n email: context.customerEmail ?? null,\n orderContext: context.customerContext ?? null,\n },\n isClosed: isTicketClosed(raw),\n lastMessageAt: snapshot.lastAt,\n messageCount: snapshot.count,\n lastAgentReplyAt: lastAgentReplyAtOf(raw),\n hasCustomerAttachment: hasCustomerAttachment(raw),\n sourceChannel: isWhatsappTicket(raw) ? 'whatsapp' : (raw.channel ?? null),\n };\n}\n","/**\n * Shared by `ctx-ports.ts`'s real `StatePort.record` and\n * `recording-ports.ts`'s no-op one: the exact tag SET a triage decision\n * materialises, ported from legacy `ClassificationSink.record`\n * (`[category, ...extraTags, handledTag]`, deduplicated). Both need the\n * IDENTICAL computation — the recording port's whole point is to report the\n * tags production WOULD have applied, so a second, drifting copy here would\n * silently defeat that guarantee.\n *\n * The category lookup (`api.list('category', …)`) is a READ, not a write —\n * both the real and the recording `StatePort` perform it for real; only the\n * final `applyTags` call is what the recording port skips.\n */\nimport type { AuditTags } from '../graph/ports';\nimport type { Classification } from '../domain';\nimport type { SupportKitApi } from './api';\n\n/** Trims and deduplicates, in first-seen order, dropping blank entries. */\nexport function dedupeTagNames(tags: ReadonlyArray<string | null | undefined>): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const tag of tags) {\n const trimmed = (tag ?? '').trim();\n if (trimmed && !seen.has(trimmed)) {\n seen.add(trimmed);\n out.push(trimmed);\n }\n }\n return out;\n}\n\n/** The category's own additional tags, resolved by `tagName` — `[]` when no category matches. */\nasync function extraTagsFor(api: SupportKitApi, tagName: string): Promise<string[]> {\n const page = await api.list('category', { filter: { tagName }, limit: 1 });\n const data = page.items[0]?.data as { extraTags?: string[] } | undefined;\n return data?.extraTags ?? [];\n}\n\n/** The deduplicated tag set a triage decision applies: `[category, ...extraTags, handledTag]`. */\nexport async function resolveHandledTags(\n api: SupportKitApi,\n classification: Classification,\n audit: AuditTags,\n): Promise<string[]> {\n const extraTags = await extraTagsFor(api, classification.category);\n return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);\n}\n","/**\n * Real port implementations on `ctx` (spec §3.3 `adapters/ctx-ports.ts`):\n * Conversation/Reply/State via `ctx.api.integrations.run('gorgias', …)`\n * (S1), Llm via `ctx.api.llm.complete` v2 (S2), Prompt via §3.7's resolver\n * (T19), Clock over the real `Date`.\n *\n * `StatePort` deviation, kept from `graph/ports.ts`'s own header comment:\n * §3.3's table names it \"records\", but its actual traffic here is Gorgias\n * tag/rename calls (`applyTags`/`renameTicket`) — S1 integration writes, not\n * an AppRecord write. The one genuine AppRecord read in this file is\n * `StatePort.record`'s category `extraTags` lookup (`gorgias-tags.ts`).\n */\nimport type {\n ChatMessage,\n ClockPort,\n CompletionRequest,\n CompletionResult,\n ConversationPort,\n LlmPort,\n OutboundReply,\n PromptPort,\n ReplyPort,\n StatePort,\n} from '../graph/ports';\nimport type { ConversationRef } from '../domain';\nimport type { PlatformPromptReader, PromptCachePort, PromptDegradedEvent } from '../prompts/resolver';\nimport { createPromptResolver } from '../prompts/resolver';\nimport type { RawTicket } from '../guardrails';\nimport type { SupportKitApi } from './api';\nimport { toConversation, type RawTicketContext } from './conversation-mapping';\nimport { resolveHandledTags } from './gorgias-tags';\n\nfunction asRawTicket(value: unknown): RawTicket {\n return (value ?? {}) as RawTicket;\n}\n\n// --- ConversationPort --------------------------------------------------------\n\nexport function createGorgiasConversationPort(api: SupportKitApi): ConversationPort {\n return {\n async listPending(source, limit) {\n const tickets = (await api.integrations.run('gorgias', 'fetchTicketsFromView', {\n viewId: source.viewOrTag,\n limit,\n })) as Array<{ id: string | number }>;\n return tickets.map((t) => ({ id: String(t.id), channel: 'gorgias' as const }));\n },\n\n async read(ref: ConversationRef) {\n // ONE fetch (B, T21 review): `getTicketWithContext`\n // (@wopilo/gorgias-client) reads `GET /tickets/:id/` once and derives\n // both the raw payload and the extracted context from that single\n // response — see `conversation-mapping.ts`'s module doc. This used to\n // be two separate actions hitting the same endpoint in parallel,\n // which not only doubled the round trips but let the two halves\n // observe different server states if a message landed between them.\n const result = (await api.integrations.run('gorgias', 'getTicketWithContext', {\n ticketId: ref.id,\n })) as { ticket: unknown; context: RawTicketContext } | null;\n return toConversation(ref, asRawTicket(result?.ticket), result?.context ?? { messages: [], customerContext: null });\n },\n };\n}\n\n// --- ReplyPort ---------------------------------------------------------------\n\n/**\n * `OutboundReply.idempotencyKey` is NOT forwarded: neither `replyEmail` nor\n * `postWhatsappNote` accept it (Gorgias has no idempotency-key concept — see\n * `ReplyPort.post`'s own doc, \"NOT by channel idempotence\"). At-most-once is\n * already guaranteed upstream by the claim→post→commit state machine (I9);\n * this field exists for a FUTURE channel that does support one.\n */\nexport function createGorgiasReplyPort(api: SupportKitApi): ReplyPort {\n return {\n async post(ref: ConversationRef, reply: OutboundReply) {\n if (reply.mode === 'email') {\n const result = (await api.integrations.run('gorgias', 'replyEmail', {\n ticketId: ref.id,\n bodyHtml: reply.bodyHtml,\n bodyText: reply.bodyText,\n senderEmail: reply.fromAddress,\n toAddress: reply.receiverEmail,\n ...(reply.subject !== null ? { subject: reply.subject } : {}),\n ...(reply.receiverName !== null ? { receiverName: reply.receiverName } : {}),\n })) as { messageId: string };\n return { messageId: result.messageId };\n }\n const result = (await api.integrations.run('gorgias', 'postWhatsappNote', {\n ticketId: ref.id,\n text: reply.bodyText,\n })) as { messageId: string };\n return { messageId: result.messageId };\n },\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport function createGorgiasStatePort(api: SupportKitApi): StatePort {\n return {\n async record(ref, classification, audit) {\n const names = await resolveHandledTags(api, classification, audit);\n if (names.length === 0) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names });\n },\n async rename(ref, subject) {\n await api.integrations.run('gorgias', 'renameTicket', { ticketId: ref.id, subject });\n },\n async flag(ref, tag) {\n const trimmed = tag.trim();\n if (!trimmed) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names: [trimmed] });\n },\n };\n}\n\n// --- LlmPort ---------------------------------------------------------------\n\n/**\n * `ctx.api.llm.complete` v2 carries no `tool`-role message and no `tools`\n * parameter (S2's surface, `app-api-client.ts`) — §6.2's tool loop has no\n * platform surface to run on YET. This is NOT dead ground: `graph/draft.ts`\n * already calls `buildToolSpecs(profile)` and populates `CompletionRequest\n * .tools` on every round, and already pushes `role: 'tool'` turns once the\n * model asks for one. Nothing in `draft.ts` gates on this adapter's\n * capabilities — what currently keeps `req.tools` empty is\n * `settings/to-profile.ts` hardcoding `tools: []` (\"default-deny until\n * T22\"). The moment that allowlist is populated, `complete()` below would\n * silently drop `req.tools` (this surface has nothing to forward it to) and\n * this port would keep returning `toolCalls: []` regardless of what the\n * model was asked to use — the loop terminates on round one, degraded: no\n * order lookup, no tracking lookup, `Draft.sources` empty, every\n * provenance display blank, the most expensive node hallucinating order\n * facts instead of fetching them. Silently, with no error anywhere.\n *\n * `complete()` below refuses that outcome outright: a request that asks for\n * tools throws, naming the missing surface, so enabling the allowlist\n * degrades loudly (a thrown error) rather than loudly-nothing. See\n * docs/plans/2026-09-02-gorgias-migration-progress.md for the spec gap this\n * leaves for T22 / the spec owner to close (S2 needs a tools/toolCalls\n * surface, or draft's `maxToolCalls` needs to go).\n */\nfunction toPlatformMessage(msg: ChatMessage): { role: 'system' | 'user' | 'assistant'; content: string } {\n // Reachable only once `req.tools` stops being empty (the guard below\n // throws before that point today) — kept exhaustive over `ChatMessage`\n // for type safety, not because production traffic hits these branches.\n if (msg.role === 'tool') return { role: 'user', content: msg.content };\n if (msg.role === 'assistant') return { role: 'assistant', content: msg.content ?? '' };\n return { role: msg.role, content: msg.content };\n}\n\n/** S2's `trace`, as a named type so a handler can build one without reaching into `CompletionRequest`. */\nexport type RunTrace = NonNullable<CompletionRequest['trace']>;\n\n/**\n * `trace` is stamped on every completion this port makes, unless the request\n * carries its own. The legacy grouped one ticket's calls under a single\n * Langfuse session — draft, evaluation and revision read as one conversation\n * instead of a handful of orphan generations — which is what makes a trace\n * navigable when a correction has to be traced back to what produced it\n * (§3.4's quality loop). Omitting it keeps today's untraced behaviour.\n */\nexport function createPlatformLlmPort(api: SupportKitApi, trace?: RunTrace): LlmPort {\n return {\n async complete(req: CompletionRequest): Promise<CompletionResult> {\n // Mirrors `FakeLlm`: an already-aborted signal fails before the\n // platform is reached — `ctx.api.llm.complete` takes no `signal` of\n // its own (I14's deadline is enforced by `budget`/the caller instead).\n if (req.signal?.aborted) {\n throw Object.assign(new Error('Request was aborted.'), { name: 'AbortError' });\n }\n\n // Fail loudly rather than silently ground the model (see the module\n // doc above): `ctx.api.llm.complete` v2 has no tool-calling surface,\n // so honouring `req.tools` here would mean dropping it on the floor.\n if (req.tools?.length) {\n throw new Error(\n 'createPlatformLlmPort: ctx.api.llm.complete v2 has no tool-calling surface (no `tools` parameter, no `role: \\'tool\\'` message) — cannot honour CompletionRequest.tools.',\n );\n }\n\n // A per-request `trace` wins over the port's own: a node that names\n // its own session knows something this port does not.\n const runTrace = req.trace ?? trace;\n const result = await api.llm.complete({\n messages: req.messages.map(toPlatformMessage),\n options: {\n model: req.model,\n reasoningEffort: req.reasoning,\n ...(req.responseSchema !== undefined\n ? { responseSchema: { name: req.label, schema: req.responseSchema as Record<string, unknown> } }\n : {}),\n },\n // `req.promptRef` (including `resolve`, see `CompletionRequest.promptRef`'s\n // own doc) is forwarded WHOLESALE — every caller in this package now\n // sets `resolve: false`, so this pass-through needs no code change of\n // its own to carry the new field; it already carries whatever shape\n // `CompletionRequest.promptRef` has.\n ...(req.promptRef ? { promptRef: req.promptRef } : {}),\n ...(runTrace ? { trace: runTrace } : {}),\n });\n\n return {\n text: result.text ?? null,\n // No tool-calling support on this surface today — see the module\n // doc above.\n toolCalls: [],\n usage: { input: result.usage.inputTokens, output: result.usage.outputTokens, reasoning: 0 },\n ...(result.traceId ? { traceId: result.traceId } : {}),\n ...(result.observationId ? { observationId: result.observationId } : {}),\n };\n },\n };\n}\n\n// --- PromptPort (§3.7 seams) -------------------------------------------------\n\n/** `PlatformPromptReader` over T5's `ctx.api.prompts.get(name, {label|version, resolve:false})` (T19's seam). */\nexport function createPlatformPromptReader(api: SupportKitApi): PlatformPromptReader {\n return {\n async get(name, ref) {\n const detail = await api.prompts.get(name, { ...ref, resolve: false });\n return { version: detail.version, content: detail.content, config: detail.config ?? null };\n },\n };\n}\n\n/** `PromptCachePort` over the `prompt-cache` record (T20's schema, T19's seam). */\nexport function createRecordPromptCachePort(api: SupportKitApi): PromptCachePort {\n return {\n async read(key) {\n const page = await api.list('prompt-cache', { filter: { promptKey: key }, limit: 1 });\n const data = page.items[0]?.data as { content: string; version: number } | undefined;\n return data ? { content: data.content, version: data.version } : null;\n },\n async write(key, entry) {\n await api.upsert(\n 'prompt-cache',\n [{ data: { promptKey: key, content: entry.content, version: entry.version } }],\n { uniqueBy: ['promptKey'] },\n );\n },\n };\n}\n\n/**\n * Assembles the real `PromptPort`: T19's resolver over the two seams above,\n * with `onDegraded` routed to the caller's logger (post-T19-review E) — the\n * kit carries no logging port of its own, so a silent-degradation event\n * (Langfuse down, cache down, a broken composition tag) would otherwise be\n * indistinguishable from a correct run.\n */\nexport function createPlatformPromptPort(api: SupportKitApi, log: (message: string) => void): PromptPort {\n return createPromptResolver({\n platform: createPlatformPromptReader(api),\n cache: createRecordPromptCachePort(api),\n onDegraded: (event: PromptDegradedEvent) => log(`prompt resolution degraded [${event.stage}] ${event.name}: ${event.reason}`),\n });\n}\n\n// --- ClockPort ---------------------------------------------------------------\n\nexport function createRealClock(): ClockPort {\n return { now: () => new Date() };\n}\n","/**\n * Recording ports for the dry-run replay (spec §3.3 `adapters/\n * recording-ports.ts`, §3.5's `graph-dry-run` row), ported from legacy\n * `services/graphDryRun.ts`'s `meta`/`sink`/`reply`/`recordingGateway`.\n *\n * The guarantee (§0's arbitrage, restated in §3.5): dry-run replays the\n * COMPLETE graph — every node, LLM included — but reaches ZERO external\n * action. `ReplyPort.post` and `StatePort.record`/`rename`/`flag` are\n * replaced here by recorders that never call Gorgias; `ConversationPort`,\n * `LlmPort` and `PromptPort` stay the REAL `ctx-ports.ts` adapters — a dry\n * run reads and thinks for real, it just never writes.\n *\n * `state.record`'s READ half (the category's `extraTags`, via\n * `gorgias-tags.ts`) still runs for real, so `wouldHaveTagged` reports the\n * EXACT tag set production would apply — only the final `applyTags` call is\n * skipped, by construction (there is no write call left to make).\n */\nimport type { AuditTags, CompletionRequest, LlmPort, OutboundReply, ReplyPort, StatePort, ToolCallRequest } from '../graph/ports';\nimport type { Classification, Usage } from '../domain';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitApi } from './api';\nimport { resolveHandledTags } from './gorgias-tags';\n\n// --- ReplyPort ---------------------------------------------------------------\n\nexport interface WouldHaveReplied {\n subject: string | null;\n body: string;\n}\n\nexport interface RecordingReplyPort {\n port: ReplyPort;\n /** The reply the run WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied(): WouldHaveReplied | null;\n}\n\nexport function createRecordingReplyPort(): RecordingReplyPort {\n let wouldHaveReplied: WouldHaveReplied | null = null;\n return {\n port: {\n async post(_ref, reply: OutboundReply) {\n wouldHaveReplied = { subject: reply.mode === 'email' ? reply.subject : null, body: reply.bodyText };\n // A message id `act` can commit — nothing left the building.\n return { messageId: 'dry-run' };\n },\n },\n wouldHaveReplied: () => wouldHaveReplied,\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport interface RecordingStatePort {\n port: StatePort;\n /** Tags the run WOULD have applied, in first-seen order. Nothing was applied. */\n wouldHaveTagged(): string[];\n}\n\nexport function createRecordingStatePort(api: SupportKitApi): RecordingStatePort {\n const tagged: string[] = [];\n const push = (tag: string): void => {\n const trimmed = tag.trim();\n if (trimmed && !tagged.includes(trimmed)) tagged.push(trimmed);\n };\n\n return {\n port: {\n async record(_ref, classification: Classification, audit: AuditTags) {\n const names = await resolveHandledTags(api, classification, audit);\n names.forEach(push);\n },\n async rename() {\n // A dry run renames nothing.\n },\n async flag(_ref, tag) {\n push(tag);\n },\n },\n wouldHaveTagged: () => [...tagged],\n };\n}\n\n// --- SendPort recorder (claim -> post -> commit persistence seam, I9) ------\n\ntype ClaimedSend = Extract<NodeDeps['send'], { mode: 'claimed' }>;\n\nexport interface RecordingSendPort {\n send: ClaimedSend;\n /** Every claim/commit call, in order — a dry run must never let these reach real persistence. */\n calls: Array<{ surface: 'send.claim' | 'send.commit'; args: readonly unknown[] }>;\n}\n\n/**\n * Recording `{mode: 'claimed'}` seam (post-T21-review C): when a production\n * dry run wires `deps.send` to `{mode: 'claimed'}` (the `act` node's own\n * gate — see its module doc), THIS package had no recording counterpart, so\n * nothing stopped that dry run's claim/commit calls from writing real rows.\n * `claim` always resolves `true` (a dry run never loses a contest — there is\n * nothing to contest), `commit` no-ops: neither touches persistence.\n */\nexport function createRecordingSendPort(): RecordingSendPort {\n const calls: RecordingSendPort['calls'] = [];\n return {\n calls,\n send: {\n mode: 'claimed',\n async claim(run) {\n calls.push({ surface: 'send.claim', args: [run] });\n return true;\n },\n async commit(messageId) {\n calls.push({ surface: 'send.commit', args: [messageId] });\n },\n },\n };\n}\n\n// --- The pair a production dry run substitutes ------------------------------\n\n/**\n * Swaps the two ports that can reach Gorgias — `reply` and `state` — for\n * their recorders, leaving every READ port (conversation, llm, prompt) and\n * the clock untouched.\n *\n * This is the `settings.dryRun` seam for the PRODUCTION pipeline\n * (`functions/triage-tick.ts`, `functions/process-response.ts`), where the\n * recorded output is deliberately dropped: those handlers report through\n * their records and their run, not through a `wouldHaveTagged()` payload —\n * only the \"never write to Gorgias\" half of the recorders matters there.\n * The `uiInvoke` dry runs that DO read the recordings back\n * (`functions/graph-dry-run-core.ts`) keep wiring the recorders themselves.\n */\nexport function withRecordingWritePorts<T extends { reply: ReplyPort; state: StatePort }>(ports: T, api: SupportKitApi): T {\n return { ...ports, reply: createRecordingReplyPort().port, state: createRecordingStatePort(api).port };\n}\n\n// --- LlmPort recorder (still a REAL call — only its trace is captured) -----\n\n/** One LLM call, as a dry-run page would show it: what was asked, what came back, what it cost. */\nexport interface RecordedCompletion {\n label: string;\n model: string;\n reasoning: string;\n messages: CompletionRequest['messages'];\n toolsOffered: string[];\n text: string | null;\n toolCalls: Array<{ name: string; arguments: Record<string, unknown> }>;\n usage: Usage;\n traceId: string | null;\n durationMs: number;\n error?: string;\n}\n\nexport interface RecordingLlmPort {\n port: LlmPort;\n completions: RecordedCompletion[];\n}\n\nfunction toRecordedToolCalls(calls: ToolCallRequest[]): Array<{ name: string; arguments: Record<string, unknown> }> {\n return calls.map((c) => ({ name: c.name, arguments: c.arguments }));\n}\n\n/** Wraps a REAL `LlmPort` (the LLM still runs — §3.5's \"LLM compris\") and records every completion. */\nexport function createRecordingLlmPort(llm: LlmPort): RecordingLlmPort {\n const completions: RecordedCompletion[] = [];\n return {\n completions,\n port: {\n async complete(req: CompletionRequest) {\n const startedAt = Date.now();\n const entry: RecordedCompletion = {\n label: req.label,\n model: req.model,\n reasoning: req.reasoning,\n messages: req.messages,\n toolsOffered: (req.tools ?? []).map((t) => t.name),\n text: null,\n toolCalls: [],\n usage: { input: 0, output: 0, reasoning: 0 },\n traceId: null,\n durationMs: 0,\n };\n completions.push(entry);\n try {\n const result = await llm.complete(req);\n entry.text = result.text;\n entry.toolCalls = toRecordedToolCalls(result.toolCalls);\n entry.usage = result.usage;\n entry.traceId = result.traceId ?? null;\n return result;\n } catch (err) {\n entry.error = err instanceof Error ? err.message : String(err);\n throw err;\n } finally {\n entry.durationMs = Date.now() - startedAt;\n }\n },\n },\n };\n}\n","/**\n * `SupportKitHandlerContext` — `AppHandlerContext` (`@apotech-os/app-kit`,\n * `handler.ts`) narrowed to `api: SupportKitApi` instead of the concrete\n * `AppApiClient` class.\n *\n * Same reasoning as `SupportKitApi` itself (T21/T22, `adapters/api.ts`): a\n * real `AppHandlerContext` built by the platform carries a real\n * `AppApiClient`, which is a structural superset of `SupportKitApi`, so it\n * is always assignable here — but a unit test can build `ctx.api` as a plain\n * object instead of a live HTTP client.\n *\n * Also the shared home (T22 hardening, E) for the bits every one of the four\n * pipeline handlers otherwise hand-copied: `getOptional` (a 404 read is an\n * ordinary \"not there\" outcome, not a thrown error, for every handler that\n * dereferences a possibly-stale record id), `DEFAULT_MAX_TOOL_CALLS` (the\n * `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset), and\n * `buildTicketPorts` (the six-line `NodeDeps.ports` assembly `triage-tick`/\n * `process-response`/`handle-approval` each wrote out by hand, byte-for-byte\n * identical).\n */\nimport type { AppApiRecord, AppHandlerContext } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport {\n createGorgiasConversationPort,\n createGorgiasReplyPort,\n createGorgiasStatePort,\n createPlatformLlmPort,\n createPlatformPromptPort,\n createRealClock,\n type RunTrace,\n} from '../adapters/ctx-ports';\n\nexport type SupportKitHandlerContext = Omit<AppHandlerContext, 'api'> & { api: SupportKitApi };\n\n/** The `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset (§3.6). */\nexport const DEFAULT_MAX_TOOL_CALLS = 5;\n\n/**\n * Reads `objectKey/id`, returning `null` on a 404 (a dangling relation or an\n * already-deleted record) instead of throwing — the shape every handler here\n * wants when dereferencing an id it did not just create itself. `id: null`\n * short-circuits to `null` without a round trip, for the optional relations\n * (`categoryId`, `agentId`) that may never have been set.\n */\nexport async function getOptional(ctx: SupportKitHandlerContext, objectKey: string, id: string | null): Promise<AppApiRecord | null> {\n if (!id) return null;\n try {\n return await ctx.api.get(objectKey, id);\n } catch (err) {\n if (err instanceof AppApiError && err.status === 404) return null;\n throw err;\n }\n}\n\n/**\n * The `NodeDeps.ports` bundle every handler that runs a ticket through the\n * graph needs — one real Gorgias/platform wiring, reused instead of re-typed\n * per call site.\n *\n * `trace` groups every completion of the run under one Langfuse session\n * (`RunTrace`); a handler that omits it gets today's untraced behaviour.\n */\nexport function buildTicketPorts(ctx: SupportKitHandlerContext, trace?: RunTrace) {\n return {\n conversation: createGorgiasConversationPort(ctx.api),\n reply: createGorgiasReplyPort(ctx.api),\n llm: createPlatformLlmPort(ctx.api, trace),\n prompt: createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message)),\n state: createGorgiasStatePort(ctx.api),\n clock: createRealClock(),\n };\n}\n","/**\n * Whether a `generated-response{status:'pending'}` row is worth creating\n * for a just-triaged ticket (§3.5's \"si éligible, création generated-\n * response{status:'pending'}\").\n *\n * §3.5 does not spell out \"eligible\" — this is `triage-tick`'s own reading,\n * chosen to NEVER DRIFT from what `process-response`'s `runTicket(deps,\n * {resume})` would decide with the SAME classification: it calls the EXACT\n * SAME predicates `run-ticket.ts` branches on right after its own triage\n * phase (`isConversationOver`/`isFallbackClassification`/`hasNoDraftNode`,\n * exported from there — T22 hardening, so this can no longer silently drift\n * the way a hand-copied mirror could), up to (but not including)\n * `channelPreGates`/the WhatsApp not-our-turn check — those need a FRESH\n * conversation read to evaluate, which `triage-tick` does not have (and\n * should not pay for) at classification time. Any ticket this function\n * calls \"eligible\" that later turns out to hit a pre-gate is still\n * perfectly safe: `process-response` runs the real sequence and writes\n * whatever real outcome results, `triage-tick`'s job is only to avoid\n * paying for a draft that could NEVER have produced one — an escalated,\n * closed, or fallback-classified ticket.\n *\n * PER-CATEGORY OPT-IN (B3): the gate above is about what the graph COULD\n * produce; this one is about what the tenant ASKED for. §3.4's `category`\n * record carries `fastResponseEnabled` and `agentId` (with the cross\n * validation `fastResponseEnabled ⇒ agentId`), and the legacy enqueued a\n * fast-response job only for `matched && matched.fast_response_enabled &&\n * matched.agent` (`backoffice/src/services/triage.ts`). Nobody read those\n * fields here, so EVERY triable ticket paid a drafting — and then an\n * evaluation — LLM call, including for categories explicitly left out and\n * for tickets whose classification matched no category at all (drafted with\n * whatever the default agent happened to be). An unmatched or non-opted-in\n * category now stops at triage, as it did before the migration.\n *\n * ESCALATION (B3, connected decision): the legacy made this skip\n * CONDITIONAL on `profile.nodes.escalate.skipsFastResponse` — an escalated\n * ticket was still enqueued when that flag was off. That setting is gone\n * rather than restored: `graph/run-ticket.ts` finishes UNCONDITIONALLY on\n * `s.escalated` (`if (s.escalated) return finish(s, deps, 'escalated')`),\n * so a row created for an escalated ticket could never be fulfilled by\n * `process-response` — it would only ever be a pending row expiring on its\n * TTL. Honouring the flag would require re-opening that graph decision,\n * which §3.3 settled the other way; keeping it mapped-but-unread was the\n * worse of the three options.\n */\nimport type { Classification } from '../domain';\nimport type { AgentProfile } from '../domain/profile';\nimport { hasNoDraftNode, isConversationOver, isFallbackClassification } from '../graph/run-ticket';\nimport type { CategoryRecord } from './records';\n\nexport function isEligibleForGeneratedResponse(\n profile: AgentProfile,\n classification: Classification,\n escalated: boolean,\n category: CategoryRecord | null,\n): boolean {\n if (!category || !category.fastResponseEnabled || !category.agentId) return false;\n if (escalated) return false;\n if (isConversationOver(classification)) return false;\n if (isFallbackClassification(classification)) return false;\n if (hasNoDraftNode(profile)) return false;\n return true;\n}\n","/**\n * A `ToolContext` that refuses every call — used where `NodeDeps` requires\n * one but `AgentProfile.tools` is always `[]` (T22 leaves the §6.2 tool\n * allowlist at default-deny, see `settings/to-profile.ts`'s own doc: nothing\n * in `settingsToProfile` populates it, and `createPlatformLlmPort` throws on\n * a non-empty `CompletionRequest.tools` before ever reaching a provider).\n * With no tool ever exposed to the model, `draft` never calls this — these\n * throws are a loud, defensive backstop against that assumption silently\n * breaking, not a code path anything is expected to take today.\n */\nimport type { ToolContext } from '../graph/ports';\n\nfunction refuse(name: string): never {\n throw new Error(`no-tool-context: \"${name}\" called, but this pipeline configures no tools (profile.tools is always []).`);\n}\n\nexport function createNoToolContext(): ToolContext {\n return {\n getOrder: () => refuse('getOrder'),\n getTracking: () => refuse('getTracking'),\n searchKnowledge: () => refuse('searchKnowledge'),\n findSimilarTickets: () => refuse('findSimilarTickets'),\n };\n}\n","/**\n * The `pipeline-state` singleton (§3.4, `records/pipeline-state.ts`) —\n * shared reader/writer for `triage-tick` and `sweep`, the only two callers\n * (T22 hardening, A4). Both used to hand-roll their own `toDate`/\n * `readPipelineState`, byte-identical between the two files, and each wrote\n * with an independent `list()` + `create()`-or-`update()` pair with no\n * ordering guarantee between them — see `records/pipeline-state.ts`'s own\n * doc for why that raced two crons on a fresh app. Routing both functions\n * through the ONE reader here, and through `upsertPipelineState`'s\n * `singletonKey`-keyed `upsert` on the create path, is what makes \"exactly\n * one row\" the platform's own constraint instead of a hope.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\n\n/** Always the same value — the field the record's unique index is built on. */\nexport const PIPELINE_STATE_SINGLETON_KEY = 'default';\n\nexport function toDate(value: unknown): Date | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value as string);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/** The singleton `pipeline-state` row, or `null` if it has never been written. */\nexport async function readPipelineState(api: SupportKitApi): Promise<AppApiRecord | null> {\n const page = await api.list('pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n return page.items[0] ?? null;\n}\n\n/**\n * Merges `patch` onto the singleton row, creating it on the first call. Both\n * `triage-tick` and `sweep` only ever set a slice of the record's fields\n * (`sourceViewId`+`lastTriageAt`, `lastSweepAt`), so the write MUST merge —\n * whichever cron ran last must not erase the other's stamp.\n *\n * `update()` for the merge, `upsert()` only to create. This used to be a\n * single `upsert` on the assumption that `ON CONFLICT DO UPDATE` merges. It\n * does not: the platform runs `SET data = EXCLUDED.data`, a whole-document\n * REPLACE, and says so — \"to replace a whole document, use `upsert`, which\n * writes `data` as-is\". `update()` is the platform's shallow patch-merge, the\n * same one every other record in this package relies on. So a slice goes\n * through `update()`, and `upsert()` is kept for the one case it is actually\n * needed for: the very first write, where two crons could otherwise race two\n * `create()`s past a \"singleton by convention\".\n *\n * That preserves A4's real guarantee — exactly one row is still the DATABASE's\n * decision, arbitrated by the unique index on `singletonKey`, not a hope. The\n * residual race is narrow and self-healing: only on a fresh app can both crons\n * find no row and both build a full document, one of which loses its stamp and\n * is rewritten five minutes later.\n *\n * The create path sends every field explicitly — nulls included — because it\n * writes a whole document, not a patch. It must not depend on the platform\n * inventing the keys it left out.\n */\nexport async function upsertPipelineState(api: SupportKitApi, patch: Record<string, unknown>): Promise<void> {\n const current = await readPipelineState(api);\n if (current) {\n await api.update('pipeline-state', current.id, patch);\n return;\n }\n\n await api.upsert(\n 'pipeline-state',\n [\n {\n data: {\n singletonKey: PIPELINE_STATE_SINGLETON_KEY,\n sourceViewId: null,\n lastTriageAt: null,\n lastSweepAt: null,\n ...patch,\n },\n },\n ],\n { uniqueBy: ['singletonKey'] },\n );\n}\n","/**\n * `buildSendSeam` — the ONE claim→post→commit persistence seam (I9) shared\n * by `process-response` (claims a `pending` row) and `handle-approval`\n * (claims a `ready` row after an operator approves). §8.4 demands a single\n * send path, not two independently-written ones: this is where that demand\n * actually lives at the persistence layer — both callers hand this function\n * their own `fromStatus` and get back the exact same `NodeDeps.send`\n * shape `act` drives.\n *\n * `assertTransition` runs BEFORE the write attempt (`status/machine.ts`'s own\n * doc): it is a local, in-process sanity check, distinct from the `ifMatch`\n * race below it, which is what actually decides which of two concurrent\n * claimants wins.\n *\n * A 409 from `api.update` is NOT an error here — §3.4/§8.4 read it as \"the\n * other worker already claimed this row\", the ordinary losing side of a\n * race. Any other rejection propagates so Inngest can retry the run.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { Draft, Verdict } from '../domain';\nimport type { ClockPort } from '../graph/ports';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitApi } from '../adapters/api';\n\nexport interface SendSeam {\n claim: (run: { draft: Draft; verdict: Verdict | null }) => Promise<boolean>;\n commit: (messageId: string) => Promise<void>;\n}\n\nexport interface BuildSendSeamParams {\n api: SupportKitApi;\n clock: ClockPort;\n id: string;\n ticketId: string;\n /** The status this claim moves FROM — `'pending'` for `process-response`, `'ready'` for `handle-approval`. */\n fromStatus: Extract<GeneratedResponseStatus, 'pending' | 'ready'>;\n /**\n * Extra fields persisted on the SAME atomic claim write. `process-response`\n * uses this to persist the draft/verdict it just produced (the row had\n * none yet); `handle-approval` needs nothing extra — the row already\n * carries `responseText`/`verdict` from when it was drafted.\n */\n extraClaimData?: (run: { draft: Draft; verdict: Verdict | null }) => Record<string, unknown>;\n}\n\nexport function buildSendSeam(params: BuildSendSeamParams): SendSeam {\n const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;\n\n return {\n async claim(run) {\n assertTransition(fromStatus, 'sending');\n try {\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sending',\n sendingAt: clock.now(),\n openTicketKey: openTicketKeyFor('sending', ticketId),\n ...(extraClaimData ? extraClaimData(run) : {}),\n },\n { ifMatch: { status: fromStatus } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n },\n\n async commit(messageId) {\n assertTransition('sending', 'sent');\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sent',\n sentAt: clock.now(),\n sentMessageId: messageId,\n openTicketKey: openTicketKeyFor('sent', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n },\n };\n}\n","/**\n * The `generated-response:<id>[:suffix]` key shape used by BOTH the\n * `ApprovalRequest.key`/`ApprovalDecidedPayload.key` pair (`process-response`\n * requests, `handle-approval` parses) and the `InboxAlert.key`s\n * `process-response`/`sweep` raise. Shared here so the format can never\n * drift between writers — hand-rolling the same template string twice (or\n * three times) is exactly the kind of duplication that quietly breaks the\n * moment one side changes.\n */\nconst PREFIX = 'generated-response:';\n\n/** The approval key for one `generated-response` row. */\nexport function buildApprovalKey(generatedResponseId: string): string {\n return `${PREFIX}${generatedResponseId}`;\n}\n\n/** The `generated-response` id encoded in `key`, or `null` if `key` isn't one of ours. */\nexport function parseApprovalKey(key: string): string | null {\n if (!key.startsWith(PREFIX)) return null;\n const id = key.slice(PREFIX.length);\n return id.length > 0 ? id : null;\n}\n\n/**\n * The `InboxAlert.key` for one `generated-response` row, optionally\n * suffixed (`sweep`'s `stalled-send` alert vs. `process-response`'s plain\n * `needs_human` one) — same PREFIX as the approval key above, on purpose:\n * both name the same underlying record, in a different platform surface.\n * Added alongside `buildApprovalKey` for the same reason that one exists:\n * `process-response` and `sweep` were each hand-rolling this template\n * string in a slightly different shape, two lines after importing\n * `buildApprovalKey` to avoid doing exactly that for the approval key.\n */\nexport function buildInboxKey(generatedResponseId: string, suffix?: string): string {\n return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;\n}\n","/**\n * The `[{role, content}]` shape `generated-response.tracedInput` declares\n * (§3.4) — built from the messages the drafting call was actually given\n * (`Draft.messages`, spec-vue-tickets-unifiee-v1 §4.1).\n *\n * Two narrowings, both deliberate:\n * - `toolCalls`/`toolCallId` are dropped. The record's own field description\n * says `[{role, content}]`, and the tool round it would describe is\n * already recorded, in a shape built for reading, on `sources`.\n * - Each message's content is capped. A support thread can carry a pasted\n * invoice, a forwarded chain, a base64 signature block; the record exists\n * so an operator can read what the model read, and a truncated message\n * that SAYS it is truncated serves that better than an unbounded column.\n */\nimport type { ChatMessage } from '../graph/ports';\n\n/** Per-message ceiling. Generous enough for a real customer message, short of a pasted archive. */\nexport const TRACED_INPUT_MAX_CHARS = 4000;\n\nconst TRUNCATION_MARK = '… [tronqué]';\n\nexport interface TracedInputMessage {\n role: string;\n content: string;\n}\n\nexport function toTracedInput(messages: readonly ChatMessage[]): TracedInputMessage[] {\n return messages.map((message) => ({ role: message.role, content: cap(message.content ?? '') }));\n}\n\nfunction cap(content: string): string {\n if (content.length <= TRACED_INPUT_MAX_CHARS) return content;\n return `${content.slice(0, TRACED_INPUT_MAX_CHARS)}${TRUNCATION_MARK}`;\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 } from '../graph/state';\nimport type { PromptRef, PromptTableKey } from '../domain/profile';\nimport type { Verdict } from '../domain/verdict';\nimport { isEvaluationVerdict } from '../domain/evaluation-verdict';\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}\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 };\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 /** 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}\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}\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 };\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 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 };\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 * `respondToPendingResponse` — the response phase of the pipeline. Resumes\n * `runTicket` past triage (`resume: {classification, escalated}`,\n * reconstructed from the `triage-decision` row) and persists whatever\n * terminal outcome results.\n *\n * SINGLE-PASS (2026-09): this used to be `process-response`, a standalone\n * dbEvent function triggered on `generated-response{status:'pending'}`\n * created — the batch and the response ran in two decoupled Inngest runs,\n * and a tick exited with tickets still unanswered. It is now called by\n * `triage-tick`'s own batch loop, right after the row is created, so one\n * pass over the view leaves every processed ticket in a terminal state.\n * The `status !== 'pending'` guard below stays: it is what makes a replayed\n * or concurrent call a no-op instead of a second draft.\n *\n * DRY RUN (B1): `settings.dryRun` was read by NO handler — this one drafted\n * and, whenever auto-send was eligible, actually replied to the customer,\n * trial mode or not. It is read here now: the two write ports (`reply`,\n * `state`) are swapped for `adapters/recording-ports.ts`'s recorders and\n * `send` is forced to `{mode: 'none'}`, so the graph runs in FULL (LLM\n * included, §0's arbitrage) and reaches no external action. A trial run that\n * would have sent therefore comes back with `outcome: 'sent'` having sent\n * nothing, and is persisted as `ready` — the draft stays visible for §6's\n * parity control, and `ready` is the one status that says \"a human owns this\n * text now\". `awaiting_approval` raises no approval in a trial: granting one\n * would hand `handle-approval` a real send to perform.\n *\n * The claim→post→commit send seam (`functions/claim-commit.ts`) only covers\n * the ONE outcome where `act` actually runs (`sent`, and the narrow\n * `guardrail_hold` `act` itself can still produce post-claim — see below);\n * every other outcome (`ready`, `needs_human`, `awaiting_approval`,\n * `no_reply_needed`, `failed`, the pre-claim `guardrail_hold`) is written\n * directly here, since `act`/the claim were never reached for them.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef, DraftAttribution } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport { buildSendSeam } from './claim-commit';\nimport { buildApprovalKey, buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { toTracedInput } from './traced-input';\nimport { buildPromptsTable, draftPromptRefFor, resolveDraftAgent, toAgent, toCategory } from './records';\n\n/**\n * Rebuilds the `Classification` `runTicket`'s `resume` needs, field-for-field\n * off the `triage-decision` row `triage-tick` wrote. `isFallback` is always\n * `false`: a `generated-response` is only ever created for a triage that\n * SUCCEEDED (`triage-tick` writes `status:'error'` and stops on a failed\n * classification, never creating one) — see `functions/eligibility.ts`.\n */\nfunction classificationFromDecision(decision: AppApiRecord): Classification {\n const data = decision.data as Record<string, unknown>;\n return {\n category: (data.tag as string) ?? '',\n confidence: (data.confidence as 'high' | 'low') ?? 'low',\n reasoning: (data.reasoning as string) ?? '',\n isFallback: false,\n conversationOver: (data.conversationOver as boolean | undefined) ?? false,\n };\n}\n\n/**\n * §3.4's four Langfuse columns, off the attribution the draft carries (B2).\n * WITHOUT a writer here `ext-fast-response-check` served `null` on every hit,\n * the extension echoed those nulls back, and `ext-response-comparison`'s\n * dataset/score capture — gated on a non-empty trace id — never fired for a\n * single pipeline response: the improvement loop had nothing to score.\n *\n * A run that produced no draft (a failed one) writes explicit `null`s rather\n * than nothing: the ids of a call that never finished would point the loop at\n * a generation nobody read.\n */\nfunction attributionFields(attribution: DraftAttribution | undefined): Record<string, unknown> {\n return {\n langfuseTraceId: attribution?.traceId ?? null,\n langfuseObservationId: attribution?.observationId ?? null,\n promptName: attribution?.promptName ?? null,\n promptVersion: attribution?.promptVersion ?? null,\n };\n}\n\nasync function finalizeNonSent(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n toStatus: GeneratedResponseStatus,\n extra: Record<string, unknown>,\n): Promise<boolean> {\n assertTransition('pending', toStatus);\n try {\n await ctx.api.update(\n 'generated-response',\n id,\n { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },\n { ifMatch: { status: 'pending' } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.info(`respond: generated-response ${id} was already moved off \"pending\" by another worker, abandoning`);\n return false;\n }\n throw err;\n }\n}\n\nexport async function respondToPendingResponse(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n recordId: string,\n): Promise<void> {\n const record = await getOptional(ctx, 'generated-response', recordId);\n if (!record) {\n ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'pending') {\n ctx.logger.info(`respond: generated-response ${recordId} is not pending (status=\"${String(data.status)}\"), skipping — already handled by another worker`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n if (validateSettings(settings as unknown as Record<string, unknown>).length > 0) {\n ctx.logger.info('respond: settings invalid, skipping');\n return;\n }\n\n const ticketId = data.ticketId as string;\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n\n const decision = await getOptional(ctx, 'triage-decision', (data.triageDecisionId as string) ?? null);\n if (!decision) {\n ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { error: 'triage-decision not found' });\n return;\n }\n const classification = classificationFromDecision(decision);\n const escalated = (decision.data as Record<string, unknown>).escalated === true;\n\n const categoryRecord = await getOptional(ctx, 'category', (data.categoryId as string | null) ?? null);\n const category = categoryRecord ? toCategory(categoryRecord) : null;\n const agentRecord = (data.agentId as string | null)\n ? await getOptional(ctx, 'agent', data.agentId as string)\n : null;\n const agent = agentRecord ? toAgent(agentRecord) : await resolveDraftAgent(ctx.api, null);\n\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const dryRun = settings.dryRun === true;\n // Every completion of this ticket under one Langfuse session (§3.4's\n // quality loop reads a conversation, not a pile of orphan generations).\n const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);\n const { clock } = ports;\n\n // Generation-time snapshot for `act`'s divergence baseline WHEN this\n // record is later replayed through `handle-approval` (design decision (a)\n // in T22's brief): a `handle-approval` run has no live conversation read\n // of its own to source these from, and `act` always re-reads for real\n // before posting regardless (I8), so a snapshot taken here — moments\n // before `runTicket`'s own `fetchContext` re-read — is close enough\n // without weakening send safety.\n const conversationSnapshot = await ports.conversation.read(ref);\n\n const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt as string);\n const seam = buildSendSeam({\n api: ctx.api,\n clock,\n id: recordId,\n ticketId,\n fromStatus: 'pending',\n extraClaimData: (run) => ({\n responseText: run.draft.text,\n sources: run.draft.sources,\n tracedInput: toTracedInput(run.draft.messages),\n verdict: run.verdict,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(run.draft.attribution),\n }),\n });\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const result = await runTicket(\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: dryRun ? { mode: 'none' } : { mode: 'claimed', claim: seam.claim, commit: seam.commit },\n queuedAt: generatedAt,\n },\n { resume: { classification, escalated } },\n );\n\n const draftExtra = {\n responseText: result.draft?.text ?? null,\n sources: result.draft?.sources ?? [],\n // The rendered system prompt and the customer's own turns, which nothing\n // else persists (spec-vue-tickets-unifiee-v1 §4.1). Written on BOTH write\n // paths — the send seam's claim above and this finalisation — because a\n // sent reply and a held one are read by the same timeline.\n tracedInput: toTracedInput(result.draft?.messages ?? []),\n verdict: result.verdict ?? null,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(result.draft?.attribution),\n };\n\n switch (result.outcome) {\n case 'sent':\n // Nothing was sent on a dry run — `send: {mode: 'none'}` means no\n // claim/commit ever ran, so this record is still `pending` and would\n // stay there forever if this returned like the live path does.\n if (dryRun) {\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n }\n // Already fully persisted by `seam.claim`/`seam.commit` inside `act`.\n return;\n case 'ready':\n case 'guardrail_hold':\n // `run-ticket.ts`'s own `finish()` doc: both are \"ready + a tag\", the\n // tag alone (already applied by `finish` via `StatePort.flag`)\n // distinguishes them for a human — the record's `status` does not.\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n case 'needs_human': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted) {\n await ctx.api.inbox.raise({\n key: buildInboxKey(recordId),\n severity: 'warning',\n title: `Réponse générée à revoir — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'awaiting_approval': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted && !dryRun) {\n await ctx.api.approvals.request({\n key: buildApprovalKey(recordId),\n title: `Approuver l'envoi automatique — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'escalated':\n case 'triaged_only':\n case 'no_reply_needed':\n await finalizeNonSent(ctx, recordId, ticketId, 'no_reply_needed', draftExtra);\n return;\n case 'failed':\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { ...draftExtra, error: 'runTicket outcome: failed' });\n return;\n default:\n // `outcome` is `null` only mid-run — `runTicket` never returns it on\n // a resumed call (every path through `finish()` sets one).\n ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);\n }\n}\n","/**\n * `transitionGeneratedResponse` (M8 hardening) — the ONE conditional\n * `generated-response` status-write shape shared by every caller that only\n * needs to move a row from one status to another (S5 `ifMatch` + tolerate a\n * lost race as \"someone else already moved it\", not an error): `sweep`'s\n * `ready -> expired` TTL pass and `ext-fast-response-check`'s\n * `ready -> expired|invalidated` flips used to be two independent\n * implementations of the identical transition on the identical record —\n * anything added to one (a stamp, a metric, a different 409 policy) would\n * silently not happen on the other.\n *\n * Deliberately NOT used by `claim-commit.ts`'s `buildSendSeam` or\n * `sweep.ts`'s stalled-sending/stalled-pending passes: those write EXTRA\n * fields the caller computes from the in-flight `run`/reclaim shape\n * (`sendingAt`, `reclaimStalledSend()`'s `autoSendDecision` hold, the\n * `error` message) on the SAME atomic write, which this narrow helper's\n * `extra` param supports but was not the reported duplication — scope kept\n * to the transition the review actually flagged as duplicated.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\n\nexport interface TransitionGeneratedResponseParams {\n id: string;\n ticketId: string;\n from: GeneratedResponseStatus;\n to: GeneratedResponseStatus;\n /** Extra fields persisted on the SAME conditional write, alongside `status`/`openTicketKey`. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Attempts `from -> to` under `ifMatch: {status: from}`. Returns `true` when\n * the write landed, `false` when the row had already moved (a lost race —\n * not an error, exactly the same outcome either way for every caller today).\n */\nexport async function transitionGeneratedResponse(api: SupportKitApi, params: TransitionGeneratedResponseParams): Promise<boolean> {\n const { id, ticketId, from, to, extra } = params;\n assertTransition(from, to);\n try {\n await api.update(\n 'generated-response',\n id,\n { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...(extra ?? {}) },\n { ifMatch: { status: from } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n}\n","/**\n * `triage-tick` (§3.5, reworked 2026-09 into the SINGLE-PASS pipeline job) —\n * cron function. Classifies every pending ticket on the claimed Gorgias view\n * and, per ticket, materialises what `runTicket(deps, {until:'triage'})`\n * deliberately leaves unwritten (see that option's own doc in\n * `graph/run-ticket.ts`): the `triage-decision` row, the deduplicated tag\n * application, and — when eligible — a `generated-response{status:'pending'}`\n * row, which the SAME pass then carries to a terminal state via\n * `respondToPendingResponse` (draft, evaluation, send or hand-off to a\n * human). When this function exits, every ticket of the batch is either\n * answered, explicitly handed to a human (tagged + `ready`/inbox/approval),\n * or recorded as an error — there is no second Inngest job to wait for.\n *\n * ONE BODY, NO INNGEST STEPS, deliberately: every side effect here is either\n * idempotent or guarded by an `ifMatch`/unique-key write, and splitting the\n * batch into `ctx.step.run` checkpoints would re-execute every non-step call\n * (the run open, the view read, the cadence stamp) on each step replay. The\n * cost is a wall-clock bound: the whole batch must fit in one Inngest\n * request (`INNGEST_REQUEST_TIMEOUT_MS`, 15 min by default). An operator\n * whose view outgrows that bound lowers `settings.batchLimit` — leftover\n * tickets are simply picked up by the next tick.\n *\n * WRITE ORDER (T22 hardening, A2): the `triage-decision` row is written\n * BEFORE the Gorgias tags are applied, not after. A duplicate tag apply on a\n * retried/re-run ticket is idempotent (`dedupeTagNames`, `gorgias-tags.ts`);\n * a lost `triage-decision` is not — and if the claimed view filters on the\n * `handledTag` this tag step applies, a ticket tagged with no decision row\n * behind it never comes back into view again, so the classification the LLM\n * call already paid for would be lost OUTRIGHT, not merely re-billed. The\n * decision-first order means the ONLY window left where a crash can still\n * lose a classification is between `runTicket`'s checkpoint returning and\n * THIS row landing — everything after that point (the tag apply, the\n * `generated-response` create) is either idempotent or independently\n * recoverable.\n *\n * CRASH WINDOW that remains (documented, not fully closed — see the\n * module's own final report): `runTicket`'s own doc states it plainly — a\n * checkpointed run never calls `ports.state.record`, so the classification\n * only lives in the RETURNED `TicketRunState` until this function writes it\n * down. If the process dies between the checkpoint returning and the\n * `triage-decision` write above, that LLM call's result is lost with\n * nothing left to reconstruct it from — the ticket is simply re-classified\n * (and re-billed) on the next tick. This is the same trade-off `runTicket`'s\n * doc already names as \"iso-legacy and harmless today\"; nothing in T22\n * changes it.\n *\n * DRY RUN (B1): `settings.dryRun` was a declared, advertised, DEAD setting —\n * no handler read it, so the very first `triageEnabled` activation of the\n * spec's §6 switchover order (\"activate in `dryRun`, control the parity,\n * then `dryRun` off\") tagged and renamed REAL Gorgias tickets. It is read\n * here now, and it substitutes the two write ports (`reply`, `state`) for\n * the recorders of `adapters/recording-ports.ts`: the graph still runs in\n * FULL, LLM included (§0's arbitrage), it simply reaches no external action.\n *\n * What a trial tick still WRITES, deliberately: the `triage-decision` and\n * the `generated-response` rows, exactly as a live tick would. §6 asks the\n * operator to \"control the decisions\" before turning `dryRun` off — with no\n * rows there is nothing to control, and the Pipeline/Escalades pages would\n * show an empty trial. They are identifiable as a trial's through the\n * application run they carry the `runId` of, which is stamped\n * `metadata.dryRun: true` below (the record schemas are frozen by §3.4, so\n * the marker lives on the run, not on a new column). A trial row therefore\n * describes what production WOULD have done — `subjectRenamed: true` on a\n * dry run means \"the subject matched and would have been rewritten\",\n * nothing was sent to Gorgias.\n *\n * PER-TICKET ISOLATION (T22 hardening, A1): one failing ticket no longer\n * aborts the rest of the batch. `retries: 0` on this function (see the\n * manifest fragment below) means a tick that dies partway has no recovery —\n * tickets already processed dropped off the claimed view (their `handledTag`\n * is applied), so the NEXT tick would hit the same poison ticket first and\n * die at the same place, forever, while `lastTriageAt` was never stamped\n * (also re-billing every ticket the dead tick DID manage to finish). Each\n * ticket's own error is caught and handled alone; the loop moves on, and\n * `lastTriageAt` is stamped in a `finally` so the cadence gate always\n * advances once the batch has been attempted, degraded ticket or not.\n *\n * FAILURE = ESCALATION (owner decision, 16/09/2026 — `handleTicketFailure`):\n * a ticket the pipeline could not carry to an answer is TAGGED FOR A HUMAN,\n * the same hand-off `guardrail_hold` and the sweep's stalled-send reclaim\n * already use. This matters more since the response phase moved into this\n * batch: `graph/nodes/draft.ts` has no `try`/`catch` of its own, so a 429\n * from the drafting model reaches this loop for every eligible ticket of the\n * tick, and those tickets used to be left with nothing but a log line. What\n * gets WRITTEN depends on how far the ticket got — a triage that never\n * classified gets the `triage-decision{status:'error'}` row that is its only\n * possible trace, while a failed RESPONSE records the error on its own\n * `generated-response` row rather than contradicting a decision that says,\n * correctly, that the triage succeeded.\n *\n * That tag is the ONLY notification, deliberately (owner decision, same\n * date): the run stays reported SUCCEEDED — a batch that isolated its\n * failures did its job — and no platform alert is raised. The hand-off\n * belongs in Gorgias, where the humans who answer these tickets already\n * work; a second, platform-side alert would report the same thing to people\n * who are not the ones picking the ticket up.\n */\nimport type { AppApiRecord, AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { createRealClock } from '../adapters/ctx-ports';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { openTicketKeyFor } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { isEligibleForGeneratedResponse } from './eligibility';\nimport { createNoToolContext } from './no-tool-context';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\nimport { respondToPendingResponse } from './process-response';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n findCategoryByTag,\n listCategories,\n resolveDraftAgent,\n toCategoryReferential,\n} from './records';\n\n/**\n * The manifest fragment (§3.5's table row): every 5 minutes, no retries (a\n * failed tick is superseded by the next one 5 minutes later — retrying it\n * would just re-run against a possibly-already-advanced view), one run at a\n * time, and a warning alert on failure so an operator notices a stuck\n * pipeline. Cron has no timezone field in this schema (`FunctionTriggerSchema`,\n * `@apotech-os/app-kit` `contracts.ts`) — Europe/Paris from the spec table\n * has nowhere to go here; see this task's final report for that gap.\n */\nexport function buildTriageTickFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'triage-tick'),\n name: 'triage-tick',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createTriageTickHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => triageTickHandler(ctx, config);\n}\n\nexport async function triageTickHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('triage-tick: settings invalid, skipping', { issues });\n return;\n }\n if (!settings.triageEnabled) {\n ctx.logger.info('triage-tick: triageEnabled is off, skipping');\n return;\n }\n if (!settings.sourceViewId) {\n ctx.logger.info('triage-tick: no sourceViewId configured, skipping');\n return;\n }\n\n const clock = createRealClock();\n const now = clock.now();\n\n const pipelineState = await readPipelineState(ctx.api);\n const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);\n if (lastTriageAt) {\n const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 60_000;\n if (now.getTime() < dueAt) {\n ctx.logger.info('triage-tick: not due yet, skipping');\n return;\n }\n }\n\n await runTriageBatch(ctx, config, settings);\n}\n\n/**\n * The ticket deep-link prefix, resolved ONCE per batch and frozen onto every\n * `triage-decision` the batch writes (`${base}/${ticketId}`).\n *\n * Frozen on the row rather than rebuilt by the page: the pages that list\n * these decisions read them through the generic data API and have no way to\n * reach the Gorgias connection's own domain (credentials are stripped from\n * `GET /data/integrations/:provider/connections`). The cost of that choice\n * is stated plainly: a decision written before this field existed, or while\n * the connection was a mock, keeps `ticketUrl: null` forever, and a row\n * keeps the url of the helpdesk domain that was configured the day it was\n * triaged.\n *\n * The base itself comes from the Gorgias CONNECTION (its `baseUrl`\n * credential, or its domain) — `GORGIAS_BASE_URL` only reaches it through\n * the env-backed instance the platform synthesises when no connection is\n * stored. A failure here degrades to `null`: a deep link is decorative, and\n * losing it must never fail a triage batch.\n */\nasync function resolveTicketUrlBase(ctx: SupportKitHandlerContext): Promise<string | null> {\n try {\n // Named connection, unlike every other Gorgias call in this kit: the\n // platform's own default resolution raises `409 AMBIGUOUS_CONNECTION` on\n // several connections with none flagged default (the exact configuration\n // the Settings page already warns about), and a deep link is not worth\n // losing over an ambiguity a single link target settles.\n const connections = await ctx.api.integrations.list('gorgias');\n const connection = connections.find((candidate) => candidate.isDefault) ?? connections[0];\n const result = (await ctx.api.integrations.run(\n 'gorgias',\n 'getTicketUrlBase',\n {},\n connection ? { connectionId: connection.id } : undefined,\n )) as { base?: unknown } | null;\n return typeof result?.base === 'string' && result.base !== '' ? result.base : null;\n } catch (err) {\n ctx.logger.warn('triage-tick: could not resolve the Gorgias ticket url base, decisions will carry no deep link', {\n error: err instanceof Error ? err.message : String(err),\n });\n return null;\n }\n}\n\nfunction ticketUrlFor(base: string | null, ticketId: string): string | null {\n return base ? `${base}/${encodeURIComponent(ticketId)}` : null;\n}\n\n/**\n * The batch itself — every `triage-tick` guard (settings validity,\n * `triageEnabled`, `sourceViewId`, the cadence gate) has already returned by\n * the time this runs. Extracted (T23) so `run-triage-now`\n * (`functions/run-triage-now.ts`, §3.5's \"déclenchement manuel\") can run the\n * EXACT same batch on demand, bypassing only the cadence gate above — not a\n * second, independently-drifting copy of `listPending` → per-ticket triage →\n * `triage-decision` → `generated-response`.\n */\nexport async function runTriageBatch(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n settings: SupportKitSettings,\n): Promise<{ ticketCount: number; failureCount: number }> {\n const dryRun = settings.dryRun === true;\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);\n\n const categories = await listCategories(ctx.api);\n // Draft agent for the WHOLE batch's profile — a placeholder until each\n // ticket's own category is known (see `records.ts`'s doc on\n // `resolveDraftAgent`). The per-ticket agent used on the created\n // `generated-response` row is resolved again below, after triage.\n const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));\n\n const ticketUrlBase = await resolveTicketUrlBase(ctx);\n\n const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);\n\n // §3.5's \"run applicatif\" (T22 hardening, D): one run per tick, threaded\n // onto every `triage-decision` this tick writes (`runId` below) instead of\n // each decision minting its own `crypto.randomUUID()` — an operator can\n // now group a tick's decisions, or find the tick itself, in the platform\n // run history. Started only once we know there is real work to do (the\n // cadence/settings guards above already returned): a skipped tick has\n // nothing to report a run for.\n const run = await ctx.api.runs.start({\n kind: 'triage-tick',\n message: `${dryRun ? 'Dry-run triage tick' : 'Triage tick'} over ${refs.length} ticket(s)`,\n metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun },\n });\n\n let failureCount = 0;\n try {\n for (const ref of refs) {\n try {\n await processOneTicket(ctx, ref, {\n config,\n profile,\n categories,\n ports,\n runId: run.id,\n ticketUrlBase,\n });\n } catch (err) {\n failureCount += 1;\n await handleTicketFailure(ctx, ref, err, {\n profile,\n ports,\n runId: run.id,\n ticketUrlBase,\n });\n }\n }\n await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });\n } catch (err) {\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n } finally {\n // Stamped regardless of per-ticket failures (A1): the cadence gate must\n // advance once the batch has been ATTEMPTED, not only once every ticket\n // in it succeeded — otherwise a single poison ticket would keep\n // `lastTriageAt` frozen and every OTHER ticket in the batch would be\n // re-billed on the next tick too. Also stamped on a `run-triage-now`\n // manual batch, on purpose: it advances the SAME cadence gate\n // `triage-tick` reads, so a manual run just before a scheduled tick is\n // due does not immediately trigger a redundant second pass over the\n // same tickets.\n await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });\n }\n\n return { ticketCount: refs.length, failureCount };\n}\n\n/**\n * A failure of the RESPONSE phase — the ticket WAS classified, its\n * `triage-decision{status:'ok'}` is already written, and the\n * draft/evaluate/send sequence is what threw.\n *\n * Distinguished from a triage failure because the two need opposite\n * bookkeeping: a triage failure has no decision row yet and must write one,\n * while writing a SECOND `status:'error'` decision for a ticket whose triage\n * actually succeeded would describe a classification that never failed — and\n * list that ticket twice on the Tickets page, once \"trié\", once \"en erreur\".\n */\nclass ResponsePhaseError extends Error {\n readonly generatedResponseId: string;\n\n constructor(generatedResponseId: string, cause: unknown) {\n super(cause instanceof Error ? cause.message : String(cause));\n this.name = 'ResponsePhaseError';\n this.generatedResponseId = generatedResponseId;\n }\n}\n\n/**\n * OWNER DECISION (16/09/2026): every per-ticket failure ends the same way for\n * the customer — the ticket is ESCALATED. The pipeline could not answer it,\n * so a human takes over in Gorgias, which is the same hand-off\n * `guardrail_hold` and the sweep's stalled-send reclaim already use. Only the\n * BOOKKEEPING differs, depending on how far the ticket got.\n *\n * Every step here is individually guarded: this runs inside the batch loop's\n * own `catch`, so a throw escaping it would abort the rest of the batch —\n * exactly the per-ticket isolation (A1) the loop exists to provide.\n */\nasync function handleTicketFailure(\n ctx: SupportKitHandlerContext,\n ref: ConversationRef,\n err: unknown,\n deps: TicketFailureDeps,\n): Promise<void> {\n const message = err instanceof Error ? err.message : String(err);\n ctx.logger.error(`triage-tick: ticket ${ref.id} failed, escalating it and continuing with the rest of the batch`, {\n error: message,\n });\n\n if (err instanceof ResponsePhaseError) {\n await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);\n } else {\n await writeErrorDecision(ctx, ref, message, deps);\n }\n\n await escalateTicket(ctx, ref, deps);\n}\n\n/**\n * The response row the failed run left behind, moved to `failed`.\n *\n * This frees `openTicketKey` in the same write (a terminal status clears it),\n * so the NEXT tick can draft for this ticket again — without it the orphan\n * `pending` row holds the ticket's unique key and every later tick 409s on it\n * until the TTL, leaving `sweep` to clean up an hour later.\n *\n * `ifMatch: {status:'pending'}` is what keeps a row the send seam already\n * claimed (`sending`) out of reach: its reply may ALREADY have been posted to\n * the customer, so forcing it to `failed` would erase the one state\n * `sweep`'s stalled-send reclaim knows how to resolve safely. A lost match\n * returns `false` and is left alone, deliberately.\n */\nasync function finalizeFailedResponse(\n ctx: SupportKitHandlerContext,\n ref: ConversationRef,\n generatedResponseId: string,\n message: string,\n): Promise<void> {\n try {\n await transitionGeneratedResponse(ctx.api, {\n id: generatedResponseId,\n ticketId: ref.id,\n from: 'pending',\n to: 'failed',\n extra: { error: message },\n });\n } catch (writeErr) {\n ctx.logger.error(`triage-tick: failed to finalise the response of ticket ${ref.id}`, {\n error: writeErr instanceof Error ? writeErr.message : String(writeErr),\n });\n }\n}\n\n/** The `triage-decision{status:'error'}` row a ticket that never got classified needs — the only row it will ever have. */\nasync function writeErrorDecision(\n ctx: SupportKitHandlerContext,\n ref: ConversationRef,\n message: string,\n deps: TicketFailureDeps,\n): Promise<void> {\n try {\n await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n ticketUrl: ticketUrlFor(deps.ticketUrlBase, ref.id),\n decidedAt: deps.ports.clock.now(),\n status: 'error',\n error: message,\n confidence: 'low',\n runId: deps.runId,\n subjectRenamed: false,\n });\n } catch (writeErr) {\n ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {\n error: writeErr instanceof Error ? writeErr.message : String(writeErr),\n });\n }\n}\n\n/**\n * The hand-off itself: the escalation tag, applied through the same\n * `StatePort.flag` the graph's own `guardrail_hold` outcome uses — so a\n * dry-run batch records the intent instead of touching Gorgias, for free.\n *\n * An unconfigured `escalationTag` is skipped with a warning rather than\n * applied blank: `flag('')` is not a hand-off, and the tenant whose settings\n * are incomplete is exactly the one this path runs for.\n */\nasync function escalateTicket(ctx: SupportKitHandlerContext, ref: ConversationRef, deps: TicketFailureDeps): Promise<void> {\n const tag = deps.profile.audit.escalationTag;\n if (!tag) {\n ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured — no tag applied`);\n return;\n }\n try {\n await deps.ports.state.flag(ref, tag);\n } catch (flagErr) {\n ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} — it is NOT tagged for a human`, {\n error: flagErr instanceof Error ? flagErr.message : String(flagErr),\n });\n }\n}\n\ninterface TickDeps {\n config: SupportKitFunctionConfig;\n profile: ReturnType<typeof settingsToProfile>;\n categories: Awaited<ReturnType<typeof listCategories>>;\n ports: ReturnType<typeof buildTicketPorts>;\n runId: string;\n ticketUrlBase: string | null;\n}\n\n/** What the failure path needs — the batch's own `categories`/`config` have no bearing on how a ticket is escalated. */\ntype TicketFailureDeps = Pick<TickDeps, 'profile' | 'ports' | 'runId' | 'ticketUrlBase'>;\n\nasync function processOneTicket(ctx: SupportKitHandlerContext, ref: ConversationRef, deps: TickDeps): Promise<void> {\n const { config, profile, categories, ports, runId, ticketUrlBase } = deps;\n\n // Optional rename (§3.6's `renameEnabled`/`renameFrom`/`renameTo`) — no\n // node in the graph performs it (see this module's own header doc), so it\n // is done here, once, before triage. `runTicket` re-reads the conversation\n // itself right after (`fetchContext`'s own \"always re-read\" contract) —\n // paying for one extra read here is the same trade-off the whole pipeline\n // already makes at every resume boundary.\n let subjectRenamed = false;\n if (profile.rename) {\n const conversation = await ports.conversation.read(ref);\n const subject = conversation.subject ?? '';\n if (subject.includes(profile.rename.from)) {\n await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));\n subjectRenamed = true;\n }\n }\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: { ...ports },\n toolContext: createNoToolContext(),\n budget,\n // Unknown until triage runs — no node reached in the `until:'triage'`\n // phase reads `deps.category` (`run-ticket.ts`'s early return happens\n // before any node touches it).\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n // Thrown rather than written-and-returned: a ticket nobody could classify\n // is a failed ticket like any other, and the batch's own failure path owns\n // both halves of that — the error decision AND the escalation a silent\n // `return` here used to skip.\n if (!state.classification) throw new Error('triage produced no classification');\n\n const { classification } = state;\n const category = findCategoryByTag(categories, classification.category);\n\n // Decision FIRST, tags SECOND (A2 — see this module's header doc for why\n // the order was inverted).\n const decision = await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),\n decidedAt: ports.clock.now(),\n categoryId: category?.id ?? null,\n tag: classification.category,\n confidence: classification.confidence,\n reasoning: classification.reasoning,\n conversationOver: classification.conversationOver ?? false,\n escalated: state.escalated,\n status: 'ok',\n runId,\n subjectRenamed,\n });\n\n // The dedup+single-`applyTags` call §3.5 asks for already lives in\n // `StatePort.record` (`adapters/gorgias-tags.ts`'s `resolveHandledTags`) —\n // nothing to reimplement here beyond calling the port.\n await ports.state.record(ref, classification, profile.audit);\n\n // The category matched above is passed along, not re-read: §3.4's\n // `fastResponseEnabled`/`agentId` opt-in is half of what \"eligible\" means\n // (B3 — see `eligibility.ts`).\n if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;\n\n const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);\n const conversation = state.conversation;\n const channel = conversation?.sourceChannel === 'whatsapp' ? 'whatsapp' : 'email';\n const generatedAt = ports.clock.now();\n const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 60_000);\n\n let created: AppApiRecord;\n try {\n created = await ctx.api.create('generated-response', {\n ticketId: ref.id,\n openTicketKey: openTicketKeyFor('pending', ref.id),\n status: 'pending',\n triageDecisionId: decision.id,\n categoryId: category?.id ?? null,\n agentId: draftAgent?.id ?? null,\n channel,\n generatedAt,\n expiresAt,\n sources: [],\n tracedInput: [],\n guardrailHits: [],\n servedTo: [],\n servedCount: 0,\n followupRequired: false,\n });\n } catch (err) {\n // §3.5: \"conflit d'unicité openTicketKey ⇒ ignoré, idempotent\" — another\n // tick (or a stray retry) already opened one for this ticket.\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);\n return;\n }\n throw err;\n }\n\n // Single-pass: the response phase runs right here, in the same batch, so\n // the ticket leaves this tick answered (or explicitly handed to a human)\n // instead of waiting for a decoupled dbEvent worker. Its failures are\n // re-thrown carrying the row they left behind — the decision above already\n // records a triage that SUCCEEDED, and the batch's failure path must not\n // contradict it (see `ResponsePhaseError`).\n try {\n await respondToPendingResponse(ctx, config, created.id);\n } catch (err) {\n throw new ResponsePhaseError(created.id, err);\n }\n}\n","/**\n * `sweep` (§3.5) — cron function. Three independent janitor passes over\n * `generated-response`:\n * 1. `ready` rows past `expiresAt` → `expired` (the extension's TTL check\n * mirrored server-side, so a stale draft cannot be served forever).\n * 2. `sending` rows stuck past 30 minutes (a crash between `claim` and\n * `commit`, I9) → reclaimed to `ready` + `autoSendDecision: 'hold'`\n * via `reclaimStalledSend()` (`status/machine.ts`) — NEVER `status`\n * alone, which `reclaimStalledSend`'s own doc calls out as the one\n * write shape that would re-open the record as a legal, un-held claim\n * target and risk RE-SENDING the reply. Every reclaimed ticket is\n * handed to a human: the escalation tag is applied and an Inbox alert\n * raised, since a stuck send is exactly the kind of thing nobody\n * should have to notice on their own.\n * 3. `pending` rows past `expiresAt` → `failed` (T22 hardening, A3 — see\n * that pass's own doc below for why it exists).\n *\n * `sweep` never posts a reply and never calls the claim/commit seam — it\n * only ever touches `generated-response` rows and the Gorgias tag/alert\n * surfaces, which is what makes §8.4's invariant 2 (\"never re-sent\")\n * checkable against it directly.\n *\n * Known limitation: `SupportKitApi.list` carries no cursor, so a sweep pass\n * reads at most one page of `ready`/`sending`/`pending` rows. Acceptable for\n * now — all three sets are normally small and short-lived — but a tenant\n * with a large backlog would need pagination added to the interface first.\n *\n * SETTINGS VALIDATION (T22 hardening, C — a deliberate exemption, not an\n * omission): `sweep` does NOT call `validateSettings` the way the other\n * three handlers do, because it must keep reclaiming stalled sends even on\n * a tenant whose settings are currently incomplete — that reclaim is a\n * safety net, not a feature an operator opted into, and refusing to run it\n * on a misconfigured app would leave a stuck `sending` row (and a customer\n * who may or may not have already been emailed) unattended for longer, not\n * shorter. What IS guarded is the one settings field this file actually\n * reads, `escalationTag`: on an unconfigured tenant it used to be\n * `undefined`, and `StatePort.flag` calling `.trim()` on it threw a\n * `TypeError` mid-loop — with `retries: 0` that killed the rest of the\n * reclaim pass AND skipped `lastSweepAt`. Routing it through\n * `settingsToProfile` instead (as first suggested) would trade this crash\n * for a different one: that mapper dereferences `settings.nodes.triage.model`\n * unconditionally (`baseNode`), which throws just as readily on the exact\n * kind of incomplete settings blob this guard exists for. A direct,\n * narrow-scoped type check on the one field actually read is what stays\n * safe without introducing a new crash surface.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { createGorgiasStatePort, createRealClock } from '../adapters/ctx-ports';\nimport { assertTransition, openTicketKeyFor, reclaimStalledSend } from '../status/machine';\nimport { buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\n\nconst STALE_SENDING_THRESHOLD_MS = 30 * 60_000;\nconst SWEEP_PAGE_SIZE = 500;\n\nexport function buildSweepFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sweep'),\n name: 'sweep',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createSweepHandler(): AppHandler {\n return (ctx) => sweepHandler(ctx);\n}\n\nexport async function sweepHandler(ctx: SupportKitHandlerContext): Promise<void> {\n const clock = createRealClock();\n const now = clock.now();\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const statePort = createGorgiasStatePort(ctx.api);\n // A narrow, defensive read — see this module's header doc (C) for why the\n // full `settingsToProfile` mapping is not used here.\n const escalationTag = typeof settings?.escalationTag === 'string' ? settings.escalationTag : '';\n if (!escalationTag) {\n ctx.logger.warn('sweep: escalationTag is not configured — a stalled-send reclaim will proceed without an escalation tag');\n }\n\n await sweepExpiredReady(ctx, now);\n await sweepStalledSending(ctx, now, escalationTag, statePort);\n await sweepStalledPending(ctx, now);\n\n await upsertPipelineState(ctx.api, { lastSweepAt: now });\n}\n\nasync function sweepExpiredReady(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'ready' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n // M8: the SAME `ready -> expired` conditional transition\n // `ext-fast-response-check`'s own TTL flip uses — see that module's\n // shared helper's own doc for why this used to be two independent\n // copies of the identical write.\n await transitionGeneratedResponse(ctx.api, { id: row.id, ticketId: row.data.ticketId as string, from: 'ready', to: 'expired' });\n }\n}\n\nasync function sweepStalledSending(\n ctx: SupportKitHandlerContext,\n now: Date,\n escalationTag: string,\n statePort: ReturnType<typeof createGorgiasStatePort>,\n): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'sending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const sendingAt = toDate(row.data.sendingAt);\n if (!sendingAt || now.getTime() - sendingAt.getTime() < STALE_SENDING_THRESHOLD_MS) continue;\n\n assertTransition('sending', 'ready');\n const ticketId = row.data.ticketId as string;\n let reclaimed: boolean;\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n {\n // Status AND the hold together, in the SAME write — see the\n // module doc and `reclaimStalledSend`'s own doc for why splitting\n // this into two writes (or dropping the hold) would re-open the\n // record as a sendable `ready` row.\n ...reclaimStalledSend(),\n openTicketKey: openTicketKeyFor('ready', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n reclaimed = true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n reclaimed = false; // already moved by another worker (e.g. a late commit landing)\n } else {\n throw err;\n }\n }\n if (!reclaimed) continue;\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n await statePort.flag(ref, escalationTag);\n await ctx.api.inbox.raise({\n key: buildInboxKey(row.id, 'stalled-send'),\n severity: 'warning',\n title: `Envoi bloqué détecté — ticket ${ticketId}`,\n body: 'La réponse est restée en statut \"sending\" plus de 30 minutes et a été replacée en attente humaine.',\n });\n }\n}\n\n/**\n * A3: a `pending` row is orphaned FOREVER without this pass. Since the\n * single-pass rework, `pending` is a transient state inside one\n * `triage-tick` batch (created, then carried to a terminal status by\n * `respondToPendingResponse` in the same run) — a row still `pending` here\n * means that run died between the create and the response phase, and with\n * `retries: 0` nothing ever revisits it: `sweep`'s other two passes only\n * ever scan `ready`/`sending`, never `pending`. Worse, the stuck row keeps\n * `openTicketKey` set (only a TERMINAL status clears it, `openTicketKeyFor`'s\n * own doc), so the unique index makes any FUTURE `triage-tick` create for\n * the same ticket 409 forever — that ticket could never be drafted again by\n * any later tick.\n *\n * Chosen over a top-level catch inside the response phase itself\n * (finalising straight to `failed`): the row already carries `expiresAt`\n * (set at generation time, independent of status), so this reuses the exact\n * same staleness idiom `sweepExpiredReady` above already established,\n * instead of adding a second, different failure-handling shape to the\n * response phase. It also covers the one case a try/catch inside the\n * handler cannot — a process that dies before any `catch` runs.\n */\nasync function sweepStalledPending(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'pending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n assertTransition('pending', 'failed');\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n { status: 'failed', openTicketKey: openTicketKeyFor('failed', row.data.ticketId as string), error: 'orphaned pending row past its TTL (sweep)' },\n { ifMatch: { status: 'pending' } },\n );\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) continue; // already moved by another worker\n throw err;\n }\n }\n}\n\n","/**\n * `handle-approval` (§3.5) — event function, triggered on\n * `APPROVAL_DECIDED_EVENT` (`app.approval.decided`) for an approval the\n * response phase's (`respondToPendingResponse`) `awaiting_approval` outcome\n * requested.\n *\n * SEND PATH SHARING (§8.4's \"no forked second send implementation\"):\n * - `functions/claim-commit.ts`'s `buildSendSeam` is the SAME\n * claim/commit persistence pair the response phase wires as\n * `NodeDeps.send` — only `fromStatus` differs ('pending' there,\n * 'ready' here).\n * - The actual reply-posting/anti-collision logic is `act`\n * (`graph/nodes/act.ts`) itself, called DIRECTLY here (there is no\n * triage/draft/evaluate to redo — only the send step remains), rather\n * than re-implemented.\n *\n * Rebuilding `act`'s `state.conversation` argument from stored fields is a\n * DELIBERATELY NARROW contract, verified by reading `act.ts` line by line\n * (T22): it reads exactly THREE fields off that argument —\n * `sourceChannel` (the email/whatsapp branch), `messageCount` and\n * `lastMessageAt` (the divergence check against its OWN fresh re-read,\n * `deps.ports.conversation.read`). Every other `Conversation` field\n * (`subject`, `messages`, `customer`, `isClosed`, `lastAgentReplyAt`,\n * `hasCustomerAttachment`) is read off the FRESH re-read `act` performs\n * itself, never off this placeholder — which is why they can be filled with\n * inert defaults below. If `act` ever starts reading more off its\n * `generatedFrom` argument, this placeholder silently stops being enough;\n * there is no compile-time guard for that today.\n */\nimport type { AppApiRecord, AppHandler, ApprovalDecidedPayload, FunctionDef } from '@apotech-os/app-kit';\nimport { APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { act } from '../graph/nodes';\nimport { applyOutcomeTags } from '../graph/run-ticket';\nimport { initialState } from '../graph/state';\nimport type { Conversation, ConversationRef, Draft, ProposedAction, Verdict } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor } from '../status/machine';\nimport { parseApprovalKey } from './approval-key';\nimport { buildSendSeam } from './claim-commit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor } from './records';\n\nexport function buildHandleApprovalFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'handle-approval'),\n name: 'handle-approval',\n trigger: { type: 'event', name: APPROVAL_DECIDED_EVENT },\n retries: 3,\n // No `notify` — §3.5's table gives only the first three functions one.\n };\n}\n\nexport function createHandleApprovalHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => handleApprovalHandler(ctx, config);\n}\n\nexport async function handleApprovalHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const payload = ctx.event as unknown as ApprovalDecidedPayload;\n const id = parseApprovalKey(payload.key);\n if (!id) {\n ctx.logger.debug(`handle-approval: key \"${payload.key}\" is not a generated-response approval, ignoring`);\n return;\n }\n\n const record = await getOptional(ctx, 'generated-response', id);\n if (!record) {\n ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'ready') {\n ctx.logger.info(`handle-approval: generated-response ${id} is not ready (status=\"${String(data.status)}\"), skipping — already handled or reclaimed`);\n return;\n }\n const ticketId = data.ticketId as string;\n\n if (payload.status === 'rejected') {\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n // §8.4 invariant 2's crux: a record the sweep reclaimed to `ready` carries\n // `autoSendDecision: 'hold'` — `status: 'ready'` alone makes it look like\n // an ordinary claimable draft again, but the hold means it may ONLY leave\n // this state through a FRESH approval request, never a silent resend of a\n // decision that already fired once. Nothing else in the pipeline checks\n // `autoSendDecision` before attempting to send (`act` itself has no idea\n // it exists) — this is the one place that gate has to live.\n if (data.autoSendDecision === 'hold') {\n ctx.logger.warn(`handle-approval: generated-response ${id} is on hold (autoSendDecision), refusing to send despite the approval`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('handle-approval: settings invalid, skipping', { issues });\n return;\n }\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config), settings.nodes));\n\n // Empty-draft guard (T22 hardening, B3): `draft.text` below falls back to\n // `''` on a missing `responseText`, and `act` only refuses a MISSING draft\n // object, never an empty one — nothing today can reach this (every\n // `generated-response` reaching `ready` came through `process-response`,\n // which always writes a real `responseText`), but a future caller of\n // `finalizeNonSent`/a hand-edited record could leave one blank, and this\n // is the last line of defence before an empty email goes out. `ready ->\n // invalidated` is a legal transition (`status/machine.ts`) for exactly\n // this kind of \"this record cannot be acted on as-is\" case.\n const responseText = (data.responseText as string | null | undefined) ?? '';\n if (responseText.trim().length === 0) {\n ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);\n assertTransition('ready', 'invalidated');\n try {\n await ctx.api.update('generated-response', id, { status: 'invalidated', openTicketKey: openTicketKeyFor('invalidated', ticketId) }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n const ports = buildTicketPorts(ctx);\n const { clock, state: statePort } = ports;\n\n const conversation: Conversation = {\n ref: { id: ticketId, channel: 'gorgias' },\n subject: null,\n messages: [],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt as string) : null,\n messageCount: (data.generatedMessageCount as number | undefined) ?? 0,\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n sourceChannel: data.channel as string,\n };\n const draft: Draft = {\n text: responseText,\n sources: (data.sources as Draft['sources']) ?? [],\n // Replayed from the record, not re-read: `tracedInput` is what the\n // original drafting call was given (spec-vue-tickets-unifiee-v1 §4.1).\n // Empty on a row written before that capture existed.\n messages: (data.tracedInput as Draft['messages']) ?? [],\n revised: false,\n };\n const proposedActions: ProposedAction[] = [{ kind: 'send_reply', args: {}, idempotencyKey: id, decision: 'auto' }];\n\n // Tracks the seam's OWN claim result (T22 hardening, B2) rather than\n // re-reading the record afterwards: `act` returns `{}` with zero\n // guardrail hits BOTH when the send actually completed AND when\n // `send.claim` returned `false` (another worker already claimed this row\n // — a concurrent decision or a retried delivery of this very event), so a\n // caller that only inspects `patch` cannot tell the two apart. Capturing\n // the seam's own return value is what `buildSendSeam`'s doc already names\n // as the deciding signal — surfaced here instead of silently discarded.\n const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: 'ready' });\n let claimed = true;\n const trackedSeam = {\n claim: async (run: Parameters<typeof seam.claim>[0]) => {\n claimed = await seam.claim(run);\n return claimed;\n },\n commit: seam.commit,\n };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: 1 });\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const verdict = (data.verdict as Verdict | undefined) ?? null;\n\n const patch = await act(\n { ...initialState(), conversation, draft, verdict, proposedActions },\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'claimed', claim: trackedSeam.claim, commit: trackedSeam.commit },\n queuedAt: data.generatedAt ? new Date(data.generatedAt as string) : null,\n },\n );\n\n const guardrailHits = patch.guardrailHits ?? [];\n if (guardrailHits.length === 0) {\n if (!claimed) {\n ctx.logger.warn(\n `handle-approval: generated-response ${id} claim was lost — a concurrent worker already advanced this record, nothing to persist here`,\n );\n return;\n }\n // `act` claimed, posted and committed — apply the SAME outcome tag\n // `process-response`'s resumed `runTicket` would have applied via\n // `finish()` (B1: one shared function, so the two send routes cannot\n // diverge on the audit trail §3.6 defines).\n await applyOutcomeTags('sent', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n return;\n }\n\n // `act`'s own guardrail checks (customer_email_missing/ticket_closed/\n // agent_replied/diverged/run_deadline) all run BEFORE `send.claim`, so a\n // hit here means the claim was NEVER attempted — the record is still\n // `ready`. `ready -> no_reply_needed` is not a legal transition\n // (`status/machine.ts`'s `ALLOWED_TRANSITIONS`), so — unlike\n // `process-response` — there is no legal status change to make here; the\n // record stays `ready`. What DOES change is `autoSendDecision: 'hold'`,\n // so the very next approval decision cannot walk straight back into the\n // same hit, plus the escalation tag `applyOutcomeTags('guardrail_hold', …)`\n // applies for a human to look at why the send never went out.\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n await applyOutcomeTags('guardrail_hold', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n}\n","/**\n * Stable universal identifiers for the T23 `uiInvoke` functions' `input`\n * field defs (§3.5) — same convention as `records/ids.ts`: generated once\n * and committed, never regenerated (a function's `input` is diffed by these\n * ids, not by field name).\n */\n/** Renamed from `dryRun` (T23 post-review D) — same field identity, same uid, honest name: it bypasses the `triageEnabled` kill switch and runs the real batch, the opposite of what \"dry run\" means everywhere else in this kit. */\nexport const RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID = 'dd175229-feee-4306-a429-b25ea5dd89e4';\n\nexport const PREVIEW_TRIAGE_INPUT_TICKET_ID_UID = 'b9d5da91-ce08-4aac-ae52-5ffef730fab0';\n/** spec-vue-tickets-unifiee-v1 §4.2 — the ticket timeline's last-resort conversation read. */\nexport const GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID = '88c62cf9-d3d4-4c1b-a6ae-5ee8cbfd44fd';\n\nexport const GRAPH_DRY_RUN_INPUT_TICKET_ID_UID = '5861e7be-3a28-4852-874c-1c14e82d4b35';\nexport const GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID = 'c47b8b57-6f7a-47d7-a9d1-a18fbf71a0f0';\nexport const GRAPH_DRY_RUN_INPUT_AGENT_ID_UID = '95d38506-bc22-4f91-ad43-797ff7b54f48';\nexport const GRAPH_DRY_RUN_INPUT_OVERRIDES_UID = '306a4f7d-db5d-4144-a6bd-865889e152e2';\n/** The pasted-ticket mode: `{body, subject?, channel?}` replacing `ticketId`, so the graph can be replayed with no Gorgias ticket at all. */\nexport const GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID = '2abcc895-2751-4944-b527-78bc4604eed0';\n\nexport const TEST_AGENTS_INPUT_VIEW_ID_UID = '20227a8f-95d8-4c20-a9cd-eccb0ce39e3e';\nexport const TEST_AGENTS_INPUT_TICKET_IDS_UID = '7d27acff-b558-4783-a3ac-722f676b71a7';\nexport const TEST_AGENTS_INPUT_AGENT_ID_UID = 'ea12d731-708b-4fcc-9ebb-6c4e0d04a60e';\nexport const TEST_AGENTS_INPUT_LIMIT_UID = '95151bdf-2966-41cd-8b6f-c5b0b10c427e';\n\nexport const SUGGEST_PROMPT_INPUT_AGENT_ID_UID = '40509afa-5931-419d-8467-a52cbac5c17e';\nexport const SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID = '0c2e2f58-ffd3-4aee-a1b4-cb81d1762eb6';\n\nexport const RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID = 'bfe1e895-1608-40d8-99e9-230ab9c41473';\nexport const RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID = 'b1936472-a9dc-4b0b-8ef6-ab84733a2bfa';\n\nexport const LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID = '1ac5eb02-32da-4fd4-9462-dac4ff23b208';\n\n/**\n * T26 rework (BLOCKER 3) — `create-agent`'s own `input` field defs. Assigns\n * the new agent's `promptName` server-side (`agent/<recordId>`, §3.4) — see\n * that function's own doc for why a plain `POST records/agent` cannot.\n */\nexport const CREATE_AGENT_INPUT_NAME_UID = '0cb57453-7b02-49ce-875b-7ff079a5810d';\nexport const CREATE_AGENT_INPUT_MODEL_ID_UID = 'f19f1c10-3145-482b-8c1d-6fd3576596ff';\nexport const CREATE_AGENT_INPUT_PROVIDER_UID = '0dd94db4-f31a-4cd2-b030-1b1a4da5b43e';\nexport const CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID = 'd50f3810-b6fe-4c90-b69b-3e36ba502cdb';\n/**\n * Agent-prompt-ref rework — an agent may be created pointing at a Langfuse\n * prompt that ALREADY exists (Gorgias migration: 16 agents whose prompts\n * predate their records), instead of the server-derived `agent/<recordId>`.\n */\nexport const CREATE_AGENT_INPUT_PROMPT_NAME_UID = '102d412a-3299-42a2-ac62-6f7c4155508d';\nexport const CREATE_AGENT_INPUT_PROMPT_LABEL_UID = '04f8eeba-2d0b-4814-8009-a4a3d1530760';\n\n/**\n * T26 rework (BLOCKER 4) — `set-default-agent`'s own `input` field def.\n * Demotes the incumbent default agent and promotes the target in one\n * server-side call — see that function's own doc for why two independent\n * client-side PATCHes cannot maintain the \"at most one default agent\"\n * invariant.\n */\nexport const SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID = '0686c615-63f8-49a1-b3c7-3542bac76cd6';\n\n/**\n * T24 — the six reserved `ext-*` functions' `input` field defs (§5.2's\n * frozen wire payloads). `ext-models`/`ext-categories` have no input (the\n * gateway always sends `{}`), so they need none.\n */\nexport const EXT_CHAT_INPUT_MESSAGES_UID = '874e4408-74c0-4188-b923-a0791da4d096';\nexport const EXT_CHAT_INPUT_MODEL_ID_UID = 'd63f05b1-165d-45e0-9300-cabe5e22fa42';\nexport const EXT_CHAT_INPUT_AGENT_NAME_UID = '928f03e6-2d48-487e-85ee-15999b9cbbbb';\nexport const EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID = '86fcc5df-8545-4d77-b3d7-d741c6b1d5a5';\n\nexport const EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID = '4a597dbf-ba6f-4628-b526-759448e7ed17';\n\nexport const EXT_EVALUATION_INPUT_SATISFIED_UID = 'b1af323a-d1e0-40c7-b975-66a1e3cd4b21';\nexport const EXT_EVALUATION_INPUT_MESSAGES_UID = 'ea5d9df8-c7d5-459c-b25d-2cfe0b45ad45';\nexport const EXT_EVALUATION_INPUT_TICKET_URL_UID = '6648f361-e16b-46b2-a411-3d9cdf35e87a';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID = '0d8d5556-2ffe-4d5e-aaca-55e0eab63066';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID = '8285ab1d-e20d-4088-b9b0-176236339d1c';\nexport const EXT_EVALUATION_INPUT_MODEL_ID_UID = '1646f686-57d9-4204-b901-9d7a8e1a8078';\n\nexport const EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID = 'f2ad97ac-0abf-449a-9cc3-72efff6723c6';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID = '2dfe91f9-7177-4c44-8bcb-f841ff399ce0';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID = '63afd37e-4f0f-411b-aa62-6f480ef6cd3c';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID = '295c10ef-cb7c-4409-876a-1e384cfe6f45';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID = 'c48778a5-a8f5-4ee7-92b7-66de1bb543be';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID = '5113fc86-3865-4110-b65f-c91748816f02';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID = 'e5310144-8004-4c20-9ce4-9c0c820e3577';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID = '4813f09d-88ac-4574-8f38-be5f87a6c9ac';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID = 'e87e65e8-e078-47e3-92b7-104368952a56';\nexport const EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = '0a985d59-fd20-4672-91bb-4824b8dfb026';\n\n/**\n * T27 part B — `create-shared-prompt-version`'s own `input` field defs\n * (§3.8 SharedPromptsPage). Validates `@@@langfusePrompt:…@@@` composition\n * tags through `validateReferences` before writing (see that function's\n * own doc) — the ONE write path this page uses, scoped to `shared/*` names.\n */\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = '1039e196-cf6e-438e-8ec9-7ab422feaf4d';\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = '10ffe3e1-972e-43b4-bb45-343c4664464f';\n\n/**\n * `sync-agent-prompt-snapshot`'s own `input` field def (§5.2) — the\n * background refresh of `agent.systemPromptSnapshot` after a `createVersion`\n * /`promote` on that agent's prompt.\n */\nexport const SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = '2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2';\n\n/** `invalidate-response`'s own `input` field def — the ticket panel's \"discard this draft so the ticket can be re-processed from scratch\". */\nexport const INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = '9748baf5-97be-4a22-940d-46ef2f16a175';\n","/**\n * `run-triage-now` (§3.5) — `uiInvoke`, manual trigger equivalent to the\n * legacy `POST /triage/run`, and `run-triage-batch`, the event-triggered\n * function that actually carries the batch out.\n *\n * WHY TWO FUNCTIONS (B5). `uiInvoke` is a SYNCHRONOUS request: the platform\n * runs the handler in-process under a wall clock capped at 30 s\n * (`app-sync-invocation.service.ts`'s `DEFAULT_INVOKE_TIMEOUT_MS`, clamped\n * by `APP_SYNC_INVOKE_MAX_MS`). `runTriageBatch` processes up to\n * `settings.batchLimit` tickets (30 by default) SEQUENTIALLY, each costing\n * one triage LLM call plus — since the single-pass rework — the full\n * response phase (draft, evaluation, possible send) and several Gorgias\n * round trips — minutes, not seconds. Running it inline meant a guaranteed 504 for the operator while\n * the handler kept going unattended, and a second click starting a SECOND\n * concurrent batch: `triage-decision` rows are `create`d, not upserted, so\n * that duplicated both the rows and the LLM bill (only `generated-response`\n * is deduplicated, by its `openTicketKey` unique index).\n *\n * So the invocation now does only what fits in a request — open the run,\n * emit the event — and answers with the `runId` to follow. The batch itself\n * runs in `run-triage-batch`, a durable event-triggered function with no\n * wall clock. This is the platform's own documented pairing: see\n * `AppRunHandle.reused`'s doc in `@apotech-os/app-kit` — \"what links the\n * `uiInvoke` that triggers a treatment to the asynchronous function that\n * carries it out\".\n *\n * RE-ENTRANCE GUARD. `runs.start` is idempotent on `(kind, key)` while a\n * non-terminal run exists, so the fixed `(MANUAL_TRIAGE_RUN_KIND,\n * MANUAL_TRIAGE_RUN_KEY)` pair IS the guard: a second trigger while a batch\n * is in flight gets `reused: true` back, emits nothing, and reports the run\n * already running. The platform holds that state, not this handler — two\n * concurrent invocations cannot both win it, which a read of\n * `pipeline-state.lastTriageAt` could not have guaranteed (its cadence gate\n * is also stamped by the scheduled `triage-tick`, so it cannot tell \"a\n * manual batch is running right now\" from \"a tick just finished\"). The\n * counterpart is that `run-triage-batch` MUST terminate the run on every\n * path, including failure — see its `try`/`catch` below — otherwise the\n * guard would hold the button closed for good.\n *\n * `input.ignoreTriageDisabled` mirrors the legacy `{dry_run}` body field —\n * renamed here (T23 post-review D): it lets an operator ask for a run while\n * `triageEnabled` is off (the settings-level kill switch stays authoritative\n * for `triage-tick`'s own cron, but a human clicking \"run now\" already\n * knows they are overriding it). The legacy name is not worth preserving —\n * §0 defines \"dry run\" as \"no external action\", three sibling functions\n * (`preview-triage`, `graph-dry-run`, `test-agents`) implement exactly that,\n * and this flag does the OPPOSITE: it bypasses a kill switch and runs the\n * real batch. `ignoreTriageDisabled` does NOT change what the batch\n * writes — this function ALWAYS classifies for real and ALWAYS writes\n * `triage-decision`/`generated-response` rows, exactly like a scheduled\n * tick, whether or not the flag is set. The legacy `/triage/run` never\n * wrote anything different for a \"dry run\" either (`dry_run` only bypassed\n * `triage_enabled`) — a fully side-effect-free \"would triage-tick run\"\n * preview is `preview-triage`'s job (single ticket) and `graph-dry-run`'s\n * (full graph), not this one's (a real batch).\n *\n * `minRole: 'EDITOR'`: triggering a real classification pass — which spends\n * LLM budget and can tag/escalate real tickets — is an editing action, not a\n * read. `VIEWER` (T24's `ext-*` floor) would let a read-only support agent\n * fire a batch run; that is not this function's threat model.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID } from './ids';\nimport { runTriageBatch } from './triage-tick';\n\n/**\n * The app custom event `run-triage-now` emits and `run-triage-batch`\n * subscribes to. Must be declared in the consuming app's `manifest.emits`\n * (`buildSupportPipeline`'s `emits` fragment) — the platform rejects an\n * undeclared name with 403, and refuses to sync a manifest whose event\n * trigger names one it does not emit.\n */\nexport const TRIAGE_RUN_REQUESTED_EVENT = 'triage.run.requested';\n\n/** `(kind, key)` of the applicative run — fixed, because it IS the re-entrance guard (see this module's header doc). */\nexport const MANUAL_TRIAGE_RUN_KIND = 'run-triage-now';\nexport const MANUAL_TRIAGE_RUN_KEY = 'manual';\n\nexport interface RunTriageNowInput {\n /** Bypasses the `triageEnabled` kill switch and runs the real batch anyway — NOT a dry run (see this module's own header doc). */\n ignoreTriageDisabled?: boolean;\n}\n\nexport interface RunTriageNowResult {\n /** The applicative run to follow (`useAppRuns({kind: 'run-triage-now'})`) — the batch's outcome lives there, not in this response. */\n runId: string;\n /** `'already-running'` when the re-entrance guard matched an in-flight batch and nothing new was queued. */\n status: 'queued' | 'already-running';\n}\n\n/** Payload of `TRIAGE_RUN_REQUESTED_EVENT`, as `run-triage-batch` receives it (the unwrapped event data). */\nexport interface TriageRunRequestedPayload {\n runId?: string;\n ignoreTriageDisabled?: boolean;\n}\n\nexport function buildRunTriageNowFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-now'),\n name: 'run-triage-now',\n // The handler is two API calls now, not a batch: a budget well under the\n // platform's 15 s default states that, and turns a hung platform call\n // into a fast error instead of a slow one.\n trigger: { type: 'uiInvoke', minRole: 'EDITOR', timeoutMs: 10_000 },\n input: [\n {\n universalIdentifier: RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID,\n name: 'ignoreTriageDisabled',\n type: FieldType.BOOLEAN,\n label: 'Ignore triageEnabled',\n description: 'Bypass the triageEnabled kill switch and run the real batch anyway. This is NOT a dry run — tickets are classified and tagged for real.',\n isNullable: true,\n },\n ],\n };\n}\n\n/**\n * `retries: 0` and `concurrency: 1`, for `triage-tick`'s own reasons: a\n * retried batch re-classifies (and re-bills) every ticket it already\n * handled and writes a second `triage-decision` for each, and two batches\n * running at once over the same view do the same. The re-entrance guard in\n * `run-triage-now` closes the operator-facing door; `concurrency: 1` closes\n * the platform-facing one.\n */\nexport function buildRunTriageBatchFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-batch'),\n name: 'run-triage-batch',\n trigger: { type: 'event', name: TRIAGE_RUN_REQUESTED_EVENT },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createRunTriageNowHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => runTriageNowHandler(ctx as SupportKitHandlerContext, config, (input as RunTriageNowInput) ?? {});\n}\n\nexport function createRunTriageBatchHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) =>\n runTriageBatchEventHandler(ctx as SupportKitHandlerContext, config, (input as TriageRunRequestedPayload) ?? {});\n}\n\nexport async function runTriageNowHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: RunTriageNowInput,\n): Promise<RunTriageNowResult> {\n const ignoreTriageDisabled = input.ignoreTriageDisabled ?? false;\n // Both guards are re-checked by `run-triage-batch` (an event can also be\n // replayed): they run HERE so the operator gets the refusal in their own\n // request, as a message on screen, instead of a queued run that fails out\n // of sight.\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n assertRunnable(ctx, settings, ignoreTriageDisabled);\n\n const run = await ctx.api.runs.start({\n kind: MANUAL_TRIAGE_RUN_KIND,\n key: MANUAL_TRIAGE_RUN_KEY,\n message: 'Triage manuel demandé',\n metadata: { ignoreTriageDisabled },\n });\n if (run.reused) {\n ctx.logger.info('run-triage-now: a manual batch is already running, not queueing a second one', { runId: run.id });\n return { runId: run.id, status: 'already-running' };\n }\n\n try {\n // `_key` deduplicates the emission itself at the Inngest level, so a\n // retried invocation cannot fan out into two batches for one run.\n await ctx.api.events.send(TRIAGE_RUN_REQUESTED_EVENT, {\n _key: run.id,\n runId: run.id,\n ignoreTriageDisabled,\n });\n } catch (err) {\n // A run left open would keep the guard closed forever — nothing else\n // will ever terminate it, since no batch was queued.\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n\n return { runId: run.id, status: 'queued' };\n}\n\nexport async function runTriageBatchEventHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n payload: TriageRunRequestedPayload,\n): Promise<void> {\n const { runId } = payload;\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n\n try {\n assertRunnable(ctx, settings, payload.ignoreTriageDisabled ?? false);\n const result = await runTriageBatch(ctx, config, settings);\n if (runId) await ctx.api.runs.succeed(runId, result);\n } catch (err) {\n if (runId) await ctx.api.runs.fail(runId, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n}\n\n/** The two refusals shared by the trigger and the batch — invalid settings, and the `triageEnabled` kill switch. */\nfunction assertRunnable(ctx: SupportKitHandlerContext, settings: SupportKitSettings, ignoreTriageDisabled: boolean): void {\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n if (!ignoreTriageDisabled && !settings.triageEnabled) {\n throw new ctx.NonRetriableError('Triage is disabled (triageEnabled is off) — pass ignoreTriageDisabled to override.');\n }\n}\n","/**\n * `invalidate-response` — `uiInvoke`, an operator discards a generated\n * response from the ticket panel so the ticket can be re-processed from\n * scratch, as if the pipeline had never drafted for it.\n *\n * What \"from scratch\" means here, precisely: `invalidated` is a TERMINAL\n * status, so the write below clears `openTicketKey` (`openTicketKeyFor`) —\n * the unique index no longer holds the ticket, and the next pass that sees\n * it (the cron over the view, a manual `run-triage-now`) triages AND drafts\n * it anew instead of 409-ing on the old row. What it deliberately does NOT\n * touch: the `triage-decision` history (an audit trail, not state), and the\n * Gorgias tags already applied — whether the ticket re-enters the source\n * view is the view's own filter's business, not this kit's.\n *\n * WHICH ROWS QUALIFY is the state machine's ruling, not a policy choice of\n * this handler: `isInvalidatableStatus` (`status/machine.ts`) is derived from\n * the transition table, so this handler and the button that offers the action\n * cannot drift apart. Today that means `pending` and `ready`. `sending` is\n * excluded — its reply may ALREADY have been posted, which is `sweep`'s\n * stalled-send reclaim to resolve rather than a human's to guess at — and\n * every terminal status has nothing left to invalidate: the ticket is already\n * free. A row that is already `invalidated` returns success rather than an\n * error (idempotent: the operator's goal is the state, not the transition).\n *\n * `pending` matters most in the case it was originally excluded for. It is a\n * transient mid-run state only while the run that opened it is alive; when\n * that process dies, the row is stranded with the ticket's `openTicketKey`\n * held, and every later tick re-triages the ticket — paying the LLM call and\n * writing another decision row — only to 409 on the create and abandon it,\n * until the sweep's TTL pass days later. This button is the way out.\n *\n * The write is the shared `transitionGeneratedResponse`, with `ifMatch` on\n * the status actually read: a lost race means another worker moved the row\n * between the operator's read and their click — possibly all the way to\n * `sending` — so it surfaces as an explicit refusal to refresh on, never as\n * a silent success. That conditional write is also what makes invalidating a\n * genuinely in-flight `pending` row safe with no second guard: either it\n * lands and the live run abandons on its own 409, or the run wins and this\n * is refused.\n *\n * `minRole: 'EDITOR'`: discarding a draft alters what the pipeline will do\n * next (a full re-triage + re-draft LLM spend); that is an editing action.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { getOptional } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { isGeneratedResponseStatus, isInvalidatableStatus } from '../status/machine';\nimport { INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID } from './ids';\n\nexport interface InvalidateResponseInput {\n generatedResponseId: string;\n}\n\nexport interface InvalidateResponseResult {\n status: 'invalidated';\n}\n\nexport function buildInvalidateResponseFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'invalidate-response'),\n name: 'invalidate-response',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR', timeoutMs: 10_000 },\n input: [\n {\n universalIdentifier: INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID,\n name: 'generatedResponseId',\n type: FieldType.TEXT,\n label: 'Generated response id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createInvalidateResponseHandler(): AppHandler {\n return (ctx, input) =>\n invalidateResponseHandler(ctx as SupportKitHandlerContext, (input as unknown as InvalidateResponseInput) ?? {});\n}\n\nconst REFUSALS: Record<string, string> = {\n sending: \"La réponse est en cours d'envoi — elle ne peut plus être invalidée.\",\n sent: 'La réponse a déjà été envoyée au client — elle ne peut plus être invalidée.',\n};\n\nexport async function invalidateResponseHandler(\n ctx: SupportKitHandlerContext,\n input: InvalidateResponseInput,\n): Promise<InvalidateResponseResult> {\n const id = input?.generatedResponseId?.trim();\n if (!id) throw new ctx.NonRetriableError('generatedResponseId is required');\n\n const record = await getOptional(ctx, 'generated-response', id);\n if (!record) throw new ctx.NonRetriableError(`Réponse générée introuvable (${id}).`);\n\n const data = record.data as Record<string, unknown>;\n const status = String(data.status ?? '');\n if (status === 'invalidated') return { status: 'invalidated' };\n if (!isGeneratedResponseStatus(status) || !isInvalidatableStatus(status)) {\n throw new ctx.NonRetriableError(\n REFUSALS[status] ?? `La réponse est en statut terminal \"${status}\" — le ticket est déjà libre d'être retraité.`,\n );\n }\n\n const moved = await transitionGeneratedResponse(ctx.api, {\n id,\n ticketId: String(data.ticketId ?? ''),\n from: status,\n to: 'invalidated',\n });\n if (!moved) {\n throw new ctx.NonRetriableError(\"La réponse a changé d'état entre-temps — actualisez la page avant de réessayer.\");\n }\n return { status: 'invalidated' };\n}\n","/**\n * `preview-triage` (§3.5) — `uiInvoke`, dry-run classification of ONE\n * ticket, equivalent to the legacy `POST /triage/preview`. Runs\n * `runTicket(deps, {until:'triage'})` — the same checkpoint `triage-tick`\n * uses — but through the recording `state`/`reply` ports (`adapters/\n * recording-ports.ts`, T21) instead of the real Gorgias-writing ones, so\n * nothing is tagged and no `triage-decision`/`generated-response` row is\n * created. `conversation`/`llm`/`prompt` stay the REAL ctx adapters: a\n * preview reads and classifies for real, per §0's dry-run arbitrage\n * (\"aucune action externe (ni réponse, ni tag)\").\n *\n * Narrower than `graph-dry-run`: this stops at the SAME checkpoint\n * `triage-tick` does (triage + escalate only), never drafts. Use\n * `graph-dry-run` to see the full graph, including a draft, for one ticket.\n *\n * `minRole: 'VIEWER'`: a single classification preview spends one LLM call\n * but writes nothing and cannot escalate/send anything for real — the same\n * risk profile as a read.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { createRecordingReplyPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport { resolveHandledTags } from '../adapters/gorgias-tags';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { PREVIEW_TRIAGE_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, listCategories, resolveDraftAgent, toCategoryReferential } from './records';\n\nexport interface PreviewTriageInput {\n ticketId: string;\n}\n\nexport interface PreviewTriageResult {\n ticketId: string;\n classification: Classification | null;\n escalated: boolean;\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n}\n\nexport function buildPreviewTriageFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'preview-triage'),\n name: 'preview-triage',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: PREVIEW_TRIAGE_INPUT_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createPreviewTriageHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => previewTriageHandler(ctx as SupportKitHandlerContext, config, input as unknown as PreviewTriageInput);\n}\n\nexport async function previewTriageHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: PreviewTriageInput,\n): Promise<PreviewTriageResult> {\n const ticketId = input?.ticketId?.trim();\n if (!ticketId) throw new ctx.NonRetriableError('ticketId is required');\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const agent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const realPorts = buildTicketPorts(ctx);\n const recordingState = createRecordingStatePort(ctx.api);\n const recordingReply = createRecordingReplyPort();\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: recordingReply.port,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: recordingState.port,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n // `runTicket(deps, {until:'triage'})` deliberately never calls\n // `ports.state.record` (see its own doc in `graph/run-ticket.ts`) — the\n // recording port above never fires for this checkpoint, so the tag set a\n // REAL `triage-tick` would apply is computed here directly, off the same\n // `resolveHandledTags` both the real and recording `StatePort` share. No\n // write happens either way: this is a plain (already-read-only) lookup.\n const wouldHaveTagged = state.classification\n ? await resolveHandledTags(ctx.api, state.classification, profile.audit)\n : [];\n\n return {\n ticketId,\n classification: state.classification,\n escalated: state.escalated,\n wouldHaveTagged,\n };\n}\n","/**\n * `get-ticket-conversation` (spec-vue-tickets-unifiee-v1 §4.2) — `uiInvoke`,\n * the ticket timeline's LAST-RESORT source for the \"Reçu\" step.\n *\n * The timeline prefers what was persisted at run time\n * (`generated-response.tracedInput`, then\n * `response-comparison.conversationMessages`) because that is what the model\n * actually read. Two populations have neither: the decisions imported from\n * the legacy backoffice, and every ticket the graph stopped at the tag — no\n * `generated-response` row was ever opened for those, so nothing captured\n * their conversation.\n *\n * What this function returns is therefore NOT what the model saw: it is the\n * thread AS IT STANDS NOW, which may have gained an agent reply, or lost\n * nothing at all, since the decision was taken. The page labels it as such\n * rather than letting the two read alike — that honesty is the whole point of\n * keeping this a separate, explicitly-called source instead of silently\n * back-filling `tracedInput`.\n *\n * `minRole: 'VIEWER'`: a pure read. It spends no LLM call, writes no record,\n * applies no tag, and reaches the same conversation the pipeline pages\n * already quote through `responseText` and the verdict's own free text.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID } from './ids';\n\nexport interface GetTicketConversationInput {\n ticketId: string;\n}\n\nexport interface GetTicketConversationResult {\n ticketId: string;\n subject: string | null;\n /** Customer and agent turns, oldest first — the `Message` shape of `domain/conversation.ts`. */\n messages: Array<{ role: 'user' | 'assistant'; content: string }>;\n /** `null` when the thread carries no message at all. */\n lastMessageAt: string | null;\n isClosed: boolean;\n}\n\nexport function buildGetTicketConversationFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'get-ticket-conversation'),\n name: 'get-ticket-conversation',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createGetTicketConversationHandler(): AppHandler {\n return (ctx, input) =>\n getTicketConversationHandler(ctx as SupportKitHandlerContext, (input as unknown as GetTicketConversationInput) ?? { ticketId: '' });\n}\n\nexport async function getTicketConversationHandler(\n ctx: SupportKitHandlerContext,\n input: GetTicketConversationInput,\n): Promise<GetTicketConversationResult> {\n const ticketId = input?.ticketId?.trim();\n if (!ticketId) throw new ctx.NonRetriableError('ticketId is required');\n\n // No `validateSettings` gate, unlike every handler that RUNS the graph:\n // reading a thread needs a Gorgias connection and nothing else. A tenant\n // whose triage settings are half-configured must still be able to open the\n // history of a ticket its previous configuration already decided on.\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const conversation = await buildTicketPorts(ctx).conversation.read(ref);\n\n return {\n ticketId,\n subject: conversation.subject,\n messages: conversation.messages.map((message) => ({ role: message.role, content: message.content })),\n lastMessageAt: conversation.lastMessageAt ? conversation.lastMessageAt.toISOString() : null,\n isClosed: conversation.isClosed,\n };\n}\n","/**\n * `runGraphDryRun` — the graph-dry-run engine itself, split out from\n * `graph-dry-run.ts`'s ctx-wiring/overrides so it can be exercised directly\n * against `graph/run-ticket.fixtures.ts`'s `harness()` (real nodes, fake\n * ports) instead of a fully faked `SupportKitHandlerContext`. §0's dry-run\n * arbitrage: \"graphe complet tant qu'aucune action externe (ni réponse, ni\n * tag, ni écriture de record)\".\n *\n * Takes an already-assembled `NodeDeps` (`base`) — real ports in\n * production (`buildTicketPorts(ctx)`), fake ones in a graph-level test —\n * and overrides exactly the surfaces that could otherwise leak a write:\n * `ports.reply`, `ports.state`, `ports.llm`/`ports.evaluator` (still REAL\n * calls, only their trace is captured) and `send`. `send` is ALWAYS\n * overridden to the recording `{mode:'claimed', ...}` seam, never left as\n * whatever `base.send` was assembled with — a dry run must exercise `act`'s\n * claim→post→commit path for real (so an operator sees the graph actually\n * reach `act`, not silently stop short of it), not skip it because the\n * caller happened to assemble `base` with `{mode:'none'}` (post-T21-review\n * C, `adapters/recording-ports.ts`'s own doc on `createRecordingSendPort`).\n */\nimport { createRecordingLlmPort, createRecordingReplyPort, createRecordingSendPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport type { Classification, PromptRef } from '../domain';\nimport type { RecordedCompletion, WouldHaveReplied } from '../adapters/recording-ports';\nimport type { SupportKitApi } from '../adapters/api';\nimport { NODE_NAMES, type NodeDeps, type NodeName, type NodeStep, type TicketRunState } from '../graph/state';\nimport { runTicket, type ResumeFrom } from '../graph/run-ticket';\n\n/**\n * A dry run may not outlive an admin's patience, nor the `uiInvoke`\n * request's own HTTP timeout (T23 post-review C2) — ported from the legacy\n * `DRY_RUN_DEADLINE_MS`. Both `graph-dry-run.ts` (one ticket) and\n * `test-agents.ts` (up to `MAX_LIMIT` tickets, sequential) build their\n * `AbortSignal` from this constant: without it, neither call site ever\n * aborted, so `test-agents` in particular could run up to 100 full graphs\n * with no bound until the platform itself killed the connection mid-flight\n * — every completion already billed, nothing returned to the operator.\n */\nexport const DRY_RUN_DEADLINE_MS = 3 * 60 * 1000;\n\nexport interface GraphDryRunDeps {\n /** Fully assembled `NodeDeps` — `reply`/`state`/`llm`/`evaluator`/`send` are overridden below regardless of what this carries. */\n base: NodeDeps;\n /** For the recording `StatePort`'s category `extraTags` lookup (a real read — see `recording-ports.ts`). */\n api: SupportKitApi;\n resume?: ResumeFrom;\n /**\n * The writer's prompt for the category triage just named — `runGraphDryRun`\n * calls this between triage and `draft`, and drafts with what it returns.\n *\n * Production never binds the writer before triage either: `triage-tick`\n * resolves the agent from the MATCHED category (`resolveDraftAgent`) and\n * `process-response` builds `prompts.draft` from it on the resumed run.\n * A replay that kept its up-front binding drafts with the default agent's\n * prompt whatever triage found — and on an install with no default agent\n * at all, fails in `draft` on the `no-agent-configured` sentinel while\n * triage had just named a category that HAS an agent.\n *\n * Ignored on a resumed run (`resume`): the classification was forced by\n * the caller, who bound the writer to match it up-front.\n */\n rebindDraft?: (classification: Classification | null) => Promise<PromptRef>;\n}\n\nexport interface GraphDryRunResult {\n ticketId: string;\n outcome: TicketRunState['outcome'];\n /** Nodes the graph called, in order. `evaluate` appears twice on a revision. */\n steps: NodeStep[];\n /** Nodes it did not call. */\n skipped: NodeName[];\n completions: RecordedCompletion[];\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n /** The reply it WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied: WouldHaveReplied | null;\n /**\n * Whether the run actually reached `act`'s claim/commit seam — proof the\n * send path was exercised, not skipped because `send` defaulted to\n * `{mode: 'none'}` (see this module's own header doc).\n */\n sendSeamExercised: boolean;\n draft: TicketRunState['draft'];\n verdict: TicketRunState['verdict'];\n guardrailHits: string[];\n error?: string;\n}\n\n/**\n * The unresumed replay, split at the triage checkpoint exactly where\n * production splits it — `triage-tick`'s `runTicket(deps, {until:'triage'})`\n * then `process-response`'s resumed call — so the writer can be rebound\n * from the classification in between (`GraphDryRunDeps.rebindDraft`). With\n * no rebinder the split would buy nothing, so the run stays a single call.\n *\n * Like production, the resumed half re-reads the conversation: `fetchContext`\n * therefore appears TWICE in the trace, which is what actually happened.\n */\nasync function runFromTriage(deps: NodeDeps, rebindDraft: GraphDryRunDeps['rebindDraft']): Promise<TicketRunState> {\n if (!rebindDraft) return runTicket(deps);\n\n const triaged = await runTicket(deps, { until: 'triage' });\n // `until: 'triage'` returns without an outcome unless `fetchContext` itself\n // failed — that run is already finished, and resuming it would only fail again.\n if (triaged.outcome) return triaged;\n\n const draft = await rebindDraft(triaged.classification);\n const rebound: NodeDeps = { ...deps, profile: { ...deps.profile, prompts: { ...deps.profile.prompts, draft } } };\n return runTicket(rebound, { resume: { classification: triaged.classification, escalated: triaged.escalated } });\n}\n\nexport async function runGraphDryRun({ base, api, resume, rebindDraft }: GraphDryRunDeps): Promise<GraphDryRunResult> {\n const recordingReply = createRecordingReplyPort();\n const recordingState = createRecordingStatePort(api);\n const recordingSend = createRecordingSendPort();\n const recordingLlm = createRecordingLlmPort(base.ports.llm);\n const recordingEvaluator = base.ports.evaluator ? createRecordingLlmPort(base.ports.evaluator) : null;\n\n const steps: NodeStep[] = [];\n const deps: NodeDeps = {\n ...base,\n ports: {\n ...base.ports,\n reply: recordingReply.port,\n state: recordingState.port,\n llm: recordingLlm.port,\n ...(recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}),\n },\n send: recordingSend.send,\n trace: (step) => steps.push(step),\n };\n\n let result: TicketRunState | null = null;\n let error: string | undefined;\n try {\n result = resume ? await runTicket(deps, { resume }) : await runFromTriage(deps, rebindDraft);\n } catch (err) {\n error = err instanceof Error ? err.message : String(err);\n }\n\n const seen = new Set(steps.map((s) => s.node));\n const completions = [...recordingLlm.completions, ...(recordingEvaluator?.completions ?? [])];\n\n return {\n ticketId: base.ref.id,\n outcome: result?.outcome ?? null,\n steps,\n skipped: NODE_NAMES.filter((name) => !seen.has(name)),\n completions,\n wouldHaveTagged: recordingState.wouldHaveTagged(),\n wouldHaveReplied: recordingReply.wouldHaveReplied(),\n sendSeamExercised: recordingSend.calls.length > 0,\n draft: result?.draft ?? null,\n verdict: result?.verdict ?? null,\n guardrailHits: result?.guardrailHits ?? [],\n ...(error ? { error } : {}),\n };\n}\n","/**\n * `graph-dry-run` (§3.5) — `uiInvoke`, replay of the FULL graph for one\n * ticket, equivalent to the legacy `POST /agents/graph-run`. Ports the\n * `GraphDryRunOverrides` switches from\n * `extension-overview/backoffice/src/services/graphDryRun.ts` verbatim\n * (T21 deferred them here — their semantics are non-obvious, see each\n * function's own doc below) and delegates the actual replay to\n * `runGraphDryRun` (`./graph-dry-run-core.ts`), which owns the\n * zero-external-action guarantee.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): unlike `preview-triage`'s single\n * classification, this replays the FULL graph and can conjure trial\n * evaluate/revise nodes — real LLM spend against the app's shared quota,\n * re-invocable at will. `VIEWER` is the read-only support-agent floor;\n * \"writes nothing to Gorgias\" is the wrong axis to gate on when the\n * resource actually being spent is money.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { AgentProfile, Classification, Conversation } from '../domain';\nimport type { ConversationRef } from '../domain';\nimport type { ConversationPort } from '../graph/ports';\nimport type { EvaluateNodeConfig, ReviseNodeConfig } from '../domain/profile';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { ResumeFrom } from '../graph/run-ticket';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID, GRAPH_DRY_RUN_INPUT_OVERRIDES_UID, GRAPH_DRY_RUN_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n draftRebinder,\n listCategories,\n resolveDraftAgent,\n toAgent,\n toCategoryReferential,\n} from './records';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\n\nexport interface GraphDryRunOverrides {\n /** Off skips the judge entirely — the graph then ends at `ready`. On conjures a trial judge when the tenant has none. */\n evaluate?: boolean;\n /** Off makes `needsRevision` always false. On resolves a revision node from the writer's model when the tenant has none. */\n revise?: boolean;\n /** Off empties the guardrail catalogue and forces `whatsappMode: 'auto_reply'`, to reach `act` without a hold. */\n guardrails?: boolean;\n /** On opens auto-send for this run only (still requires a real `senderEmail`). */\n autoSend?: boolean;\n}\n\n/**\n * A ticket typed by hand instead of read from Gorgias. `channel` is not\n * cosmetic: `sourceChannel === 'whatsapp'` is what the `whatsapp_stop` /\n * `not_customer_turn` guardrails and the WhatsApp style prompt key off\n * (`domain/conversation.ts`'s own contract note), so a pasted WhatsApp\n * message must be replayable as one.\n */\nexport interface GraphDryRunInlineTicket {\n /** The customer's message. The only required part — everything else has a defensible default. */\n body: string;\n subject?: string | null;\n channel?: 'email' | 'whatsapp';\n}\n\n/**\n * Every field is `| null` rather than merely optional, because the platform\n * validates this payload against the manifest with `fieldDefsToZod`\n * (`app-input-validation.ts`), where `isNullable: true` permits the VALUE\n * null but NOT an absent key — an omitted optional field is rejected with\n * `422 INVALID_INPUT` before the handler runs. Callers therefore send every\n * declared key, `null` when unset, and this type says so.\n */\nexport interface GraphDryRunInput {\n /** Mutually exclusive with `inlineTicket` — exactly one of the two. */\n ticketId?: string | null;\n /** Replay on a ticket that does not exist in Gorgias (see below). */\n inlineTicket?: GraphDryRunInlineTicket | null;\n /** Forces the writing agent; falls back to the category's, then to the default one. */\n agentId?: string | null;\n /** Forces the category — and with it the classification, so triage does not run. */\n categoryId?: string | null;\n overrides?: GraphDryRunOverrides | null;\n}\n\n/**\n * The revision switch (ported verbatim from `GraphDryRunOverrides.revise`'s\n * legacy doc): `false` removes the node; `true` CONJURES one from the\n * writer's own model when the tenant has none configured, so an operator\n * can try the correction pass on one ticket before turning it on for\n * everybody. `reasoning: 'off'` is required here — an unconfigured trial\n * revise node must never be rejected by a (model, effort) validation rule\n * the tenant never opted into.\n */\nfunction resolveReviseNode(profile: AgentProfile, override: boolean | undefined): ReviseNodeConfig | null {\n if (override === false) return null;\n if (profile.nodes.revise) return profile.nodes.revise;\n if (override !== true) return null;\n const writer = profile.nodes.draft;\n return writer ? { model: writer.model, provider: writer.provider, reasoning: 'off' } : null;\n}\n\n/**\n * The `evaluate` switch, in its FORCING direction (`true`): a tenant with no\n * judge gets a trial one, model left to the prompt (kit's own resolution),\n * threshold pinned to the tenant's own auto-send floor. `false` empties the\n * node outright — `applyOverrides` below is what does that, this helper\n * only ever ADDS a node.\n */\nfunction withTrialJudge(profile: AgentProfile, override: boolean | undefined): AgentProfile {\n if (override !== true || profile.nodes.evaluate) return profile;\n const trial: EvaluateNodeConfig = {\n model: profile.nodes.draft?.model ?? '',\n provider: 'openai',\n reasoning: 'off',\n minConfidence: profile.autoSend.minConfidence,\n escalationEnabled: false,\n };\n return { ...profile, nodes: { ...profile.nodes, evaluate: trial } };\n}\n\n/** Turns the per-run switches into a profile the graph reads normally — never persisted. */\nfunction applyOverrides(profile: AgentProfile, overrides: GraphDryRunOverrides): AgentProfile {\n const withEvaluate = overrides.evaluate === false ? { ...profile, nodes: { ...profile.nodes, evaluate: null } } : withTrialJudge(profile, overrides.evaluate);\n\n return {\n ...withEvaluate,\n nodes: { ...withEvaluate.nodes, revise: resolveReviseNode(withEvaluate, overrides.revise) },\n // `auto_reply`, not `draft_only`: `draft_only` blocks `isAutoSendEligible`\n // outright for a WhatsApp ticket, which would stop the run at `ready`\n // and defeat the whole point of this override — reaching `act` with\n // nothing standing in the way. The category opt-in is bypassed the same\n // way triage-tick's own dry-run-adjacent callers do it (see below,\n // `category: {autoReplyEnabled: true, …}`).\n //\n // `judgemeEscalateOnly: false` (T23 post-review C1): that rule is NOT\n // filtered through `active` (`graph/nodes/guardrails.ts` checks it\n // unconditionally) and `settingsToProfile` hardcodes it to `true` with\n // no settings surface to turn it off — so without this, an operator\n // dry-running a Judge.me ticket with guardrails off still gets held by\n // a guardrail this override exists specifically to bypass.\n guardrails:\n overrides.guardrails === false\n ? { active: [], params: { ...withEvaluate.guardrails.params, whatsappMode: 'auto_reply', judgemeEscalateOnly: false } }\n : withEvaluate.guardrails,\n autoSend: { ...withEvaluate.autoSend, enabled: overrides.autoSend === true && !!withEvaluate.autoSend.senderEmail },\n };\n}\n\n/**\n * The classification a forced category stands for. Confidence is `high` on\n * purpose: the operator asked for THIS category, so the run must not then\n * be held by the `triage_not_high` guardrail for a decision they made\n * themselves. Never claims the conversation is over on the operator's\n * behalf.\n */\nfunction forcedClassification(tagName: string): Classification {\n return { category: tagName, confidence: 'high', reasoning: 'operator: catégorie forcée', isFallback: false, conversationOver: false };\n}\n\n/**\n * The id a pasted ticket runs under. Not a Gorgias id and never mistakable\n * for one: it appears in the result, in the recorded tags and in the\n * would-have-replied payload, and reading it as a real ticket number would\n * send someone looking for a ticket that does not exist.\n */\nexport const INLINE_TICKET_ID = 'ticket-saisi';\n\n/**\n * A `ConversationPort` over a typed-in ticket — the ONE port that still\n * reached Gorgias during a dry run (`reply`/`state`/`send` are already\n * swapped for recorders by `runGraphDryRun`, and the read tools are\n * neutralised by `createNoToolContext`). With this in its place a dry run\n * touches no Gorgias endpoint at all.\n *\n * `read` returns the SAME conversation object on every call, which matters\n * for `act`: it re-reads the conversation right before sending and holds\n * the reply when `messageCount` has moved (the I8 anti-divergence check).\n * A port that rebuilt a fresh object per call would be fine today, but one\n * that recomputed the count from anything time-dependent would hold every\n * pasted run for a collision that never happened.\n *\n * `listPending` returns nothing: a pasted ticket belongs to no view, and\n * this port is only ever assembled for a single-ticket replay.\n */\nfunction createInlineConversationPort(ticket: GraphDryRunInlineTicket, now: Date): ConversationPort {\n const conversation: Conversation = {\n ref: { id: INLINE_TICKET_ID, channel: 'gorgias' },\n subject: ticket.subject?.trim() ? ticket.subject.trim() : null,\n messages: [{ role: 'user', content: ticket.body }],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: now,\n messageCount: 1,\n // No agent ever answered a ticket that was just typed: `null` is the\n // truth, and it is also what keeps `not_customer_turn` from holding the\n // run before a single node has looked at the text.\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER\n // (gorgias) while every channel guardrail and the style prompt read this\n // one (`domain/conversation.ts`).\n sourceChannel: ticket.channel ?? 'email',\n };\n return {\n listPending: async () => [],\n read: async () => conversation,\n };\n}\n\nexport function buildGraphDryRunFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'graph-dry-run'),\n name: 'graph-dry-run',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n // Nullable since the pasted-ticket mode: the handler enforces \"exactly\n // one of ticketId/inlineTicket\", which a per-field flag cannot express.\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_TICKET_ID_UID, name: 'ticketId', type: FieldType.TEXT, label: 'Ticket id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID,\n name: 'inlineTicket',\n type: FieldType.JSON,\n label: 'Inline ticket',\n description: '{body, subject?, channel?} — replays a typed-in ticket instead of reading one from Gorgias.',\n isNullable: true,\n },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, name: 'categoryId', type: FieldType.TEXT, label: 'Category id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_OVERRIDES_UID,\n name: 'overrides',\n type: FieldType.JSON,\n label: 'Overrides',\n description: '{evaluate?, revise?, guardrails?, autoSend?}',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createGraphDryRunHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => graphDryRunHandler(ctx as SupportKitHandlerContext, config, input as unknown as GraphDryRunInput);\n}\n\nexport async function graphDryRunHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: GraphDryRunInput,\n): Promise<GraphDryRunResult> {\n const ticketId = input?.ticketId?.trim();\n const inlineBody = input?.inlineTicket?.body?.trim();\n // Exactly one of the two. Refusing BOTH rather than silently preferring one\n // matters: a caller that sends a ticket id AND a pasted body has a bug, and\n // reading the wrong one would produce a plausible result about the wrong\n // ticket entirely.\n if (ticketId && inlineBody) throw new ctx.NonRetriableError('Provide either ticketId or inlineTicket, not both');\n if (!ticketId && !inlineBody) throw new ctx.NonRetriableError('ticketId or inlineTicket.body is required');\n const inlineTicket = inlineBody ? { ...(input.inlineTicket as GraphDryRunInlineTicket), body: inlineBody } : null;\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const forcedCategory = input.categoryId ? (categories.find((c) => c.id === input.categoryId) ?? null) : null;\n if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category \"${input.categoryId}\" not found`);\n\n const agent = input.agentId\n ? toAgent(await ctx.api.get('agent', input.agentId))\n : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);\n\n const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n const profile = applyOverrides(baseProfile, input.overrides ?? {});\n\n const realPorts = buildTicketPorts(ctx);\n const ref: ConversationRef = { id: inlineTicket ? INLINE_TICKET_ID : (ticketId as string), channel: 'gorgias' };\n const budget = createBudget({ signal: AbortSignal.timeout(DRY_RUN_DEADLINE_MS), maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: inlineTicket ? createInlineConversationPort(inlineTicket, realPorts.clock.now()) : realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n // Bypassed the same way `triage-tick`'s dry-run-adjacent batch is:\n // reaching `act` is what the `autoSend` override is for, and requiring\n // the category to ALSO have opted in would make the override inert on\n // every category that has auto-reply off — which is all of them today.\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n\n const resume: ResumeFrom | undefined = forcedCategory\n ? { classification: forcedClassification(forcedCategory.tagName), escalated: false }\n : undefined;\n\n // Nobody forced the writer or the category: which agent drafts is triage's\n // to decide, once it has run — `draftRebinder`'s own doc. The up-front\n // `agent` above stays the base binding both forced paths keep.\n const rebindDraft = input.agentId || forcedCategory ? undefined : draftRebinder(ctx.api, categories, config);\n\n return runGraphDryRun({ base, api: ctx.api, resume, ...(rebindDraft ? { rebindDraft } : {}) });\n}\n","/**\n * `test-agents` (§3.5) — `uiInvoke`, multi-ticket bench (legacy\n * `POST /agents/test`): runs `graph-dry-run`'s SAME zero-write replay\n * (`runGraphDryRun`, `./graph-dry-run-core.ts`) over either a Gorgias view\n * or an explicit list of ticket ids, so an operator can see what an agent\n * WOULD produce across a batch before turning it loose — nothing tagged,\n * nothing sent, nothing recorded, per §0's dry-run arbitrage.\n *\n * No `GraphDryRunOverrides` here (unlike `graph-dry-run`, which exists\n * precisely to explore an OFF branch on one ticket): a bench is only\n * useful if it reports what the agent does with its REAL configuration,\n * across many tickets — overriding it would just report the same forced\n * branch N times.\n *\n * `category.autoReplyEnabled` is the ONE exception to that, and it is\n * reported as such (T23 post-review C3): the per-ticket category is only\n * known once TRIAGE runs, which happens INSIDE the same full-graph replay\n * this function triggers — there is no category to read a real flag off of\n * before the run starts. `graph-dry-run` can justify forcing it to `true`\n * unconditionally (reaching `act` is that function's whole purpose); a bench\n * with no override cannot make the same claim, so `TestAgentsResult` carries\n * `autoReplyForced: true` alongside every run's outcome — an operator\n * reading \"would have sent\" across a batch sees, in the same response, that\n * every category's own auto-reply setting was bypassed to get there.\n *\n * Sequential on purpose: a batch runs the LLM/Gorgias reads for real\n * (§0/§3.5), and a small, predictable concurrency of 1 is the safer default\n * for a bench an operator triggers by hand — this can grow a concurrency\n * knob later without changing the contract.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): up to `MAX_LIMIT` full graph\n * replays per invocation is real LLM spend against the app's shared quota,\n * not a read — `VIEWER` is the wrong floor for a tool that can burn budget\n * this fast, re-invocable at will.\n *\n * `DRY_RUN_DEADLINE_MS` bounds the WHOLE bench, not each ticket (T23\n * post-review C2, ported from the legacy's single-ticket deadline): past\n * it, the loop stops starting new replays and returns whatever finished —\n * partial results the operator can read, instead of the `uiInvoke` request\n * dying at the platform's own HTTP timeout with nothing returned and every\n * completion so far already billed.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\nimport { TEST_AGENTS_INPUT_AGENT_ID_UID, TEST_AGENTS_INPUT_LIMIT_UID, TEST_AGENTS_INPUT_TICKET_IDS_UID, TEST_AGENTS_INPUT_VIEW_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, draftRebinder, listCategories, resolveDraftAgent, toAgent, toCategoryReferential } from './records';\n\nconst DEFAULT_LIMIT = 20;\nconst MAX_LIMIT = 100;\n\nexport interface TestAgentsInput {\n viewId?: string;\n ticketIds?: string[];\n /** Forces the writing agent; falls back to the default one. */\n agentId?: string;\n limit?: number;\n}\n\nexport interface TestAgentsResult {\n results: GraphDryRunResult[];\n /**\n * `true` when every result above ran with `category.autoReplyEnabled`\n * forced on, regardless of that ticket's own category setting (T23\n * post-review C3) — see this module's own header doc for why a bench\n * cannot know the real per-category flag ahead of triage.\n */\n autoReplyForced: true;\n}\n\nexport function buildTestAgentsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'test-agents'),\n name: 'test-agents',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: TEST_AGENTS_INPUT_VIEW_ID_UID, name: 'viewId', type: FieldType.TEXT, label: 'View id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_TICKET_IDS_UID, name: 'ticketIds', type: FieldType.JSON, label: 'Ticket ids', description: 'string[]', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_LIMIT_UID, name: 'limit', type: FieldType.NUMBER, label: 'Limit', isNullable: true },\n ],\n };\n}\n\nexport function createTestAgentsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => testAgentsHandler(ctx as SupportKitHandlerContext, config, input as unknown as TestAgentsInput);\n}\n\nexport async function testAgentsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: TestAgentsInput,\n): Promise<TestAgentsResult> {\n const explicitIds = (input?.ticketIds ?? []).map((id) => id.trim()).filter(Boolean);\n const viewId = input?.viewId?.trim();\n if (!viewId && explicitIds.length === 0) {\n throw new ctx.NonRetriableError('Either viewId or ticketIds is required');\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);\n const categories = await listCategories(ctx.api);\n const agent = input.agentId ? toAgent(await ctx.api.get('agent', input.agentId)) : await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n // Unless the operator benched ONE agent on purpose, every ticket drafts\n // with the agent its own category names — same rebinding as `graph-dry-run`\n // and as production, or the bench measures the default agent on tickets\n // production would never have given it (`draftRebinder`).\n const rebindDraft = input.agentId ? undefined : draftRebinder(ctx.api, categories, config);\n\n const realPorts = buildTicketPorts(ctx);\n const refs: ConversationRef[] = explicitIds.length\n ? explicitIds.slice(0, limit).map((id) => ({ id, channel: 'gorgias' as const }))\n : await realPorts.conversation.listPending({ viewOrTag: viewId! }, limit);\n\n // One deadline for the WHOLE bench (T23 post-review C2), not one per\n // ticket: past it, the loop below stops starting new replays rather than\n // let the platform's own HTTP timeout kill the request with nothing\n // returned. Every ticket's `Budget` shares this same signal, so an\n // in-flight LLM call is aborted at the same wall-clock moment the loop\n // itself gives up.\n const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);\n\n const results: GraphDryRunResult[] = [];\n for (const ref of refs) {\n if (deadline.aborted) break; // partial results: the bench is out of time, not any one ticket\n const budget = createBudget({ signal: deadline, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n results.push(await runGraphDryRun({ base, api: ctx.api, ...(rebindDraft ? { rebindDraft } : {}) }));\n }\n\n return { results, autoReplyForced: true };\n}\n","/**\n * `validateReferences` — save-time validation for a prompt-composition tag\n * (`@@@langfusePrompt:name=…|label=…@@@` or `|version=…@@@`), ported from\n * legacy `services/promptReferences.ts`. Deferred by T19 (its own module doc\n * on `prompts/references.ts`: \"an admin save-time validator with no runtime-\n * resolution caller in this kit … out of scope for T19\") and picked up here\n * because `suggest-prompt` (§3.5) is the kit's first WRITE path for a\n * prompt's content — nothing gated writes before this.\n *\n * Five error classes, all five kept:\n * 1. Malformed tag (`findMalformedTags`) — a typo'd `label`/`version`\n * keyword, or a missing closing `@@@`.\n * 2. Self-reference — a prompt referencing its own name.\n * 3. Unresolvable target — the referenced prompt/version/label could not\n * be fetched (missing, or Langfuse unreachable; both read the same\n * here, same as legacy).\n * 4. A cycle back to the prompt being saved.\n * 5. A chain longer than the runtime resolver ever actually walks\n * (T23 post-review B1, below).\n *\n * Class 1 is now STRICTLY MORE IMPORTANT than in the legacy: Langfuse used\n * to store a typo'd tag as literal text and its own resolver caught DEEPER\n * cycles on the well-formed ones — but `createPromptResolver`\n * (`prompts/resolver.ts`) now resolves composition itself, reading raw\n * content via `resolve:false` and never asking Langfuse to flatten\n * anything. A typo'd tag saved here reaches the LLM completely verbatim,\n * with NOTHING server-side left to catch it — this validator is the sole\n * arbiter, at save time, of whether that string means anything at all.\n *\n * Class 4 is deepened past legacy's one hop for the identical reason:\n * legacy's own comment justified checking only one level with \"deeper\n * cycles are rejected by Langfuse's own resolver at fetch time\" — that\n * resolver is never consulted anymore (composition is entirely the kit's\n * own `resolveComposition`, `prompts/resolver.ts`), so a 2+-hop cycle saved\n * here would previously have gone uncaught at write time. `resolver.ts`'s\n * OWN runtime composition pass already survives a cycle at read time\n * (`visited`/`MAX_COMPOSITION_DEPTH`, degrading it to empty text) — this\n * validator closes the save-time half of the same gap: catching the\n * mistake when it is made, not silently degrading it forever after.\n *\n * Class 5 (T23 post-review B1) closes a DIFFERENT gap the cycle walk above\n * never covered: a purely LINEAR chain, A→B→C→D→E→F, has no cycle at all,\n * yet `resolver.ts`'s own `MAX_COMPOSITION_DEPTH` (imported below, not\n * restated — the previous revision claimed to mirror it while actually\n * enforcing an unrelated `MAX_CYCLE_DEPTH` that only ever bounded the CYCLE\n * walk's recursion) silently strips whatever sits past that depth at read\n * time. Without this check, such a chain \"saves fine\" and an operator only\n * discovers the loss when the composed prompt quietly stops including its\n * last segment.\n *\n * `MAX_CYCLE_DEPTH` remains its own, separate, larger safety valve: it\n * exists only so an adversarial/cyclic graph the cycle walk is exploring\n * cannot recurse forever, and has nothing to say about how long a valid\n * chain may be — that is `MAX_COMPOSITION_DEPTH`'s job, enforced by class 5.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { MAX_COMPOSITION_DEPTH } from '../prompts/resolver';\nimport { parseReferences, REFERENCE_TAG_SOURCE, type PromptReference } from '../prompts/references';\n\nconst LITERAL_PREFIX = '@@@langfusePrompt:';\nconst MALFORMED_SNIPPET_MAX_LEN = 60;\n/**\n * Bounds the CYCLE WALK's own recursion on adversarial/cyclic content — kept\n * deliberately larger than `MAX_COMPOSITION_DEPTH` (a valid, acyclic chain\n * that merely runs past the runtime cap is class 5's job, reported\n * separately and more usefully than \"cycle walk gave up\").\n */\nconst MAX_CYCLE_DEPTH = 10;\n\n/** Same grammar `parseReferences` matches (`prompts/references.ts`'s exported source) — a single definition, so the two can never drift apart (T23 post-review B3). */\nconst REF_RE = new RegExp(REFERENCE_TAG_SOURCE, 'g');\n\n/** A short, human-readable excerpt of the malformed tag, for the error message. */\nfunction snippetAt(content: string, index: number): string {\n const rest = content.slice(index);\n const closingIdx = rest.indexOf('@@@', LITERAL_PREFIX.length);\n const snippet = closingIdx === -1 ? rest.slice(0, MALFORMED_SNIPPET_MAX_LEN) : rest.slice(0, closingIdx + 3);\n return snippet.length > MALFORMED_SNIPPET_MAX_LEN ? `${snippet.slice(0, MALFORMED_SNIPPET_MAX_LEN)}…` : snippet;\n}\n\n/** Every literal `@@@langfusePrompt:` occurrence NOT part of a well-formed tag `parseReferences` would have matched. */\nfunction findMalformedTags(content: string): string[] {\n if (!content.includes(LITERAL_PREFIX)) return [];\n const validStarts = new Set([...content.matchAll(REF_RE)].map((m) => m.index ?? -1));\n const malformed: string[] = [];\n for (const m of content.matchAll(new RegExp(LITERAL_PREFIX, 'g'))) {\n const index = m.index ?? -1;\n if (!validStarts.has(index)) malformed.push(snippetAt(content, index));\n }\n return malformed;\n}\n\n/** Where a reference points, for an error message (\"version 3\" / label \"production\"). */\nfunction locatorFor(ref: PromptReference): string {\n return ref.version !== undefined ? `version ${ref.version}` : `label \"${ref.label}\"`;\n}\n\ninterface FetchedTarget {\n content: string;\n}\n\n/**\n * A reference target that failed to fetch, distinguishing WHY (M1, T25\n * review): `forbidden` (a 403 — the target exists but is outside this app's\n * `role.prompts` allowlist) is a misconfiguration to fix in the manifest, not\n * a typo'd or genuinely absent prompt name — reporting the two identically\n * sends an operator chasing a \"not found\" prompt that Langfuse would show\n * them exists.\n */\ninterface FetchFailure {\n forbidden: boolean;\n}\n\ntype FetchResult = FetchedTarget | FetchFailure;\n\nfunction isFetchFailure(result: FetchResult): result is FetchFailure {\n return !('content' in result);\n}\n\n/** Stable dedupe key for a reference target — a version-pinned ref and a label-pinned ref never collide, mirroring `resolver.ts`'s own `memoryKey`. */\nfunction targetKey(ref: PromptReference): string {\n return ref.version !== undefined ? `${ref.name}::v${ref.version}` : `${ref.name}::${ref.label}`;\n}\n\n/** `ctx.api.prompts.get(name, {label|version, resolve:false})` — a `FetchFailure` on any error, `forbidden` set only for a 403 (`AppApiError`). */\nasync function fetchTarget(api: SupportKitApi, ref: PromptReference): Promise<FetchResult> {\n try {\n const detail = await api.prompts.get(ref.name, {\n resolve: false,\n ...(ref.version !== undefined ? { version: ref.version } : { label: ref.label }),\n });\n return { content: detail.content };\n } catch (err) {\n return { forbidden: err instanceof AppApiError && err.status === 403 };\n }\n}\n\n/**\n * `fetchTarget`, deduped against `cache` (T23 post-review B2). The legacy\n * gap this closes: the cycle walk used to re-fetch a target the main loop\n * had just fetched, then re-fetch it again on every alternation of an\n * unrelated cycle it stumbled into — this is the one seam both the main\n * loop and the cycle/depth walks below share, so a given (name, version|label)\n * is ever fetched at most once per `validateReferences` call.\n */\nasync function fetchTargetCached(api: SupportKitApi, ref: PromptReference, cache: Map<string, FetchResult>): Promise<FetchResult> {\n const key = targetKey(ref);\n const cached = cache.get(key);\n if (cached) return cached;\n const target = await fetchTarget(api, ref);\n cache.set(key, target);\n return target;\n}\n\n/**\n * Walks the reference chain rooted at `content` looking for a hop back to\n * `origin` (the prompt being validated). `visited` (T23 post-review B2) is\n * THIS walk's own dedupe: once a target has been explored and did not lead\n * back to `origin`, revisiting it can only repeat the same negative answer —\n * skipping it turns \"re-walked alternately to `MAX_CYCLE_DEPTH`\" into \"walked\n * once\". `depth` still bounds the walk independently, for a graph `visited`\n * has not yet caught up with.\n */\nasync function hasPathToOrigin(\n api: SupportKitApi,\n content: string,\n origin: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: Set<string>,\n): Promise<boolean> {\n if (depth > MAX_CYCLE_DEPTH) return false;\n\n for (const ref of parseReferences(content)) {\n if (ref.name === origin) return true;\n\n const key = targetKey(ref);\n if (visited.has(key)) continue;\n visited.add(key);\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a cycle\n\n if (await hasPathToOrigin(api, target.content, origin, depth + 1, cache, visited)) return true;\n }\n return false;\n}\n\n/**\n * Whether `content`'s reference chain runs past `MAX_COMPOSITION_DEPTH` —\n * the exact point `resolver.ts`'s own `composeReferences` stops following a\n * chain and silently strips whatever is left (T23 post-review B1). Mirrors\n * that function's `depth`/cap arithmetic precisely: `content` itself is\n * depth 0 (the prompt being saved, not yet fetched), each reference target\n * is one level deeper, and a target reached at `depth >= MAX_COMPOSITION_DEPTH`\n * is exactly the one the resolver would compose without following further —\n * anything nested inside IT is what gets silently lost at runtime.\n *\n * `visited` mirrors `resolver.ts`'s own cycle guard (keyed by prompt NAME,\n * same as `resolveOneReference`'s `visited.has(ref.name)`): a name already\n * on the path is a cycle, which the runtime resolver degrades to empty text\n * at THAT point regardless of depth, and which class 4 above already\n * reports on its own terms — without this, a short unrelated cycle inside\n * an otherwise-fine chain would recurse forever instead of matching what\n * the resolver actually does with it.\n */\nasync function exceedsCompositionDepth(\n api: SupportKitApi,\n content: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: ReadonlySet<string>,\n): Promise<boolean> {\n const refs = parseReferences(content);\n if (refs.length === 0) return false;\n if (depth >= MAX_COMPOSITION_DEPTH) return true;\n\n for (const ref of refs) {\n if (visited.has(ref.name)) continue; // a cycle — reported separately by class 4, not a depth issue\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a depth issue\n if (await exceedsCompositionDepth(api, target.content, depth + 1, cache, new Set([...visited, ref.name]))) return true;\n }\n return false;\n}\n\n/**\n * Validate every reference tag in `content` (the prompt named `selfName`\n * about to be saved). Returns human-readable error strings; an empty array\n * means the content is valid.\n */\nexport async function validateReferences(api: SupportKitApi, content: string, selfName: string): Promise<string[]> {\n const errors: string[] = [];\n const cache = new Map<string, FetchResult>();\n\n for (const snippet of findMalformedTags(content)) {\n errors.push(`Malformed reference tag near \"${snippet}\": it will be saved as literal text instead of being resolved.`);\n }\n\n for (const ref of parseReferences(content)) {\n if (ref.name === selfName) {\n errors.push(`Reference \"${ref.raw}\" points to this same prompt (\"${selfName}\") — a prompt cannot reference itself.`);\n continue;\n }\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) {\n errors.push(\n target.forbidden\n ? `Reference \"${ref.raw}\" points to prompt \"${ref.name}\", which exists but is outside this app's prompts allowlist (role.prompts) — it cannot be composed here even though it can be read elsewhere.`\n : `Reference \"${ref.raw}\" could not be resolved: prompt \"${ref.name}\" with ${locatorFor(ref)} was not found, or the prompt store could not be reached to verify it.`,\n );\n continue;\n }\n\n if (await hasPathToOrigin(api, target.content, selfName, 1, cache, new Set([targetKey(ref)]))) {\n errors.push(`Reference \"${ref.raw}\" creates a cycle: prompt \"${ref.name}\" (transitively) references this prompt (\"${selfName}\").`);\n }\n }\n\n if (errors.length === 0 && (await exceedsCompositionDepth(api, content, 0, cache, new Set([selfName])))) {\n errors.push(\n `Reference chain exceeds the runtime composition cap (${MAX_COMPOSITION_DEPTH} levels): the segment past that depth would be silently stripped when this prompt is resolved.`,\n );\n }\n\n return errors;\n}\n","/**\n * `suggest-prompt` (§3.5) — `uiInvoke`, LLM prompt suggestion from an\n * agent's `response-comparison` corrections, equivalent to legacy\n * `POST /models/:id/prompt-versions/suggest`. Writes with\n * `ctx.api.prompts.createVersion(...)` (S3), tag `ai_suggested`, gated by\n * `validateReferences` (`./validate-references.ts`, T19's deferred\n * validator) BEFORE the write — the first prompt-content write path in the\n * kit, and the first place a malformed/self-referencing/cyclic reference tag\n * could otherwise reach a live prompt.\n *\n * WHAT THIS CANNOT RECORD (T19): `CreatePromptVersionInput` is\n * `{content, labels?, tags?}` — no `config`, no `commitMessage`. Two losses\n * versus the legacy, both accepted here rather than invented on the\n * platform surface:\n * - No `commitMessage`: legacy wrote\n * `\"AI-suggested based on N comparisons from vX\"` as the version's own\n * changelog entry. That narrative has nowhere to go — the new version\n * carries no explanation of why it exists beyond the `ai_suggested` tag.\n * - No `config`: legacy explicitly inherited the ACTIVE version's model\n * config (\"a suggestion never silently resets a tuned temperature back\n * to the default\"). A version created here carries none — an operator\n * who tuned a model/temperature on the active version loses that\n * tuning the moment they accept a suggestion, silently, until S3 grows\n * a `config` field.\n *\n * `minRole: 'EDITOR'`: this writes a new prompt version (Langfuse), even\n * though it never PROMOTES it to `production` — creating one is still an\n * editing action, not a read.\n */\nimport { AppApiError, FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SUGGEST_PROMPT_INPUT_AGENT_ID_UID, SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID } from './ids';\nimport { resolvePromptName } from '../prompts/slots';\nimport { toAgent } from './records';\nimport { validateReferences } from './validate-references';\n\nconst DEFAULT_MAX_COMPARISONS = 50;\nconst MIN_COMPARISONS_REQUIRED = 3;\n\n/**\n * Level-3 fallback for the `suggest` slot (§3.7 point 3: \"fallback in-code\n * du kit, surchargé par `config.defaults.prompts`\") — used only when the\n * slot has no `production` version yet in the prompt store.\n */\nconst DEFAULT_SUGGEST_META_PROMPT = [\n 'Tu es un expert en rédaction de prompts système pour des assistants IA de support client.',\n \"Analyse les différences entre les réponses de l'IA et celles des agents humains dans les exemples fournis.\",\n 'Identifie les patterns récurrents (ton, structure, longueur, formulations) puis réécris le prompt système actuel pour en corriger les écarts.',\n 'Retourne UNIQUEMENT le texte du prompt système amélioré, sans explication ni mise en forme markdown.',\n \"Toute balise de référence de la forme @@@langfusePrompt:...@@@ présente dans le prompt actuel doit être reproduite telle quelle, sans modification.\",\n].join('\\n');\n\nexport interface SuggestPromptInput {\n agentId: string;\n maxComparisons?: number;\n}\n\nexport interface SuggestPromptResult {\n promptName: string;\n version: number;\n comparisonCount: number;\n}\n\nexport function buildSuggestPromptFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'suggest-prompt'),\n name: 'suggest-prompt',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: SUGGEST_PROMPT_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: false },\n { universalIdentifier: SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID, name: 'maxComparisons', type: FieldType.NUMBER, label: 'Max comparisons', isNullable: true },\n ],\n };\n}\n\nexport function createSuggestPromptHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => suggestPromptHandler(ctx as SupportKitHandlerContext, config, input as unknown as SuggestPromptInput);\n}\n\nfunction comparisonBlock(index: number, generatedText: string | null, sentText: string): string {\n const ai = generatedText?.trim() || '(aucune réponse générée)';\n return `### Exemple ${index + 1}\\nIA a généré :\\n${ai}\\n\\nAgent a réellement envoyé :\\n${sentText.trim()}`;\n}\n\nexport async function suggestPromptHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: SuggestPromptInput,\n): Promise<SuggestPromptResult> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const agent = toAgent(await ctx.api.get('agent', agentId));\n const promptName = agent.promptName;\n if (!promptName) throw new ctx.NonRetriableError(`Agent \"${agentId}\" has no promptName configured`);\n\n // Raw (unresolved) current content — the meta-prompt below must see any\n // `@@@langfusePrompt:...@@@` composition tag verbatim, so it rewrites the\n // template rather than an expansion of it (mirrors legacy's own\n // `getRaw` read, §3.7's \"aplatir\" concern).\n let currentContent: string;\n let promptVersion: number | null;\n try {\n const detail = await ctx.api.prompts.get(promptName, { label: 'production', resolve: false });\n currentContent = detail.content;\n promptVersion = detail.version;\n } catch (err) {\n // H4 (T25 review): a 403 means this agent's own promptName is outside\n // the app's role.prompts allowlist — a manifest/data misconfiguration,\n // not the legitimate \"no production version yet\" case the fallback to\n // systemPromptSnapshot exists for. Swallowing it here would rewrite a\n // STALE snapshot and hand the operator no error explaining why.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n `Agent \"${agentId}\"'s prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts) — suggest-prompt cannot read it. ${err.message}`,\n );\n }\n currentContent = agent.systemPromptSnapshot ?? '';\n promptVersion = agent.promptVersion;\n }\n\n // Scoped to the ACTIVE prompt version, not just the agent (legacy\n // behaviour, ported): a correction captured against v7 has nothing to say\n // about v8 — feeding it back in after the operator already accepted a\n // suggestion re-litigates a fix that was already made and drifts the\n // prompt further every round.\n const limit = Math.min(input?.maxComparisons ?? DEFAULT_MAX_COMPARISONS, DEFAULT_MAX_COMPARISONS);\n const page = await ctx.api.list('response-comparison', { filter: { agentId, promptName, promptVersion }, limit });\n const comparisons = page.items.map((r) => r.data as { generatedText: string | null; sentText: string });\n if (comparisons.length < MIN_COMPARISONS_REQUIRED) {\n throw new ctx.NonRetriableError(\n `Not enough comparison data (${comparisons.length} record(s), minimum ${MIN_COMPARISONS_REQUIRED} required)`,\n );\n }\n\n const metaPromptName = resolvePromptName('suggest', config);\n // §3.7 point 3 — the kit's own built-in text is the LAST resort;\n // `config.defaults.prompts.suggest` (T25) overrides it first.\n const configuredFallback = config.defaults?.prompts?.suggest ?? DEFAULT_SUGGEST_META_PROMPT;\n let metaPromptContent = configuredFallback;\n try {\n metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: 'production' })).content || configuredFallback;\n } catch {\n // Level-3 fallback (§3.7) — the `suggest` slot has no `production`\n // version yet on this tenant.\n }\n\n const userMessage = [\n '--- PROMPT SYSTÈME ACTUEL ---',\n currentContent,\n '--- FIN DU PROMPT SYSTÈME ---',\n '',\n `Voici ${comparisons.length} exemples comparant ce que l'IA a généré avec ce que l'agent a réellement envoyé :`,\n '',\n comparisons.map((c, i) => comparisonBlock(i, c.generatedText, c.sentText)).join('\\n\\n---\\n\\n'),\n ].join('\\n');\n\n const result = await ctx.api.llm.complete({\n messages: [\n { role: 'system', content: metaPromptContent },\n { role: 'user', content: userMessage },\n ],\n options: { model: agent.modelId },\n promptRef: { name: metaPromptName, label: 'production', resolve: false },\n });\n\n const suggestedContent = result.text.trim();\n if (!suggestedContent) throw new ctx.NonRetriableError('The model returned an empty suggestion');\n\n const referenceErrors = await validateReferences(ctx.api, suggestedContent, promptName);\n if (referenceErrors.length > 0) {\n // The rejected content is included, not discarded (T23 post-review B4):\n // without it, an operator can neither see what the model produced nor\n // repair it by hand, and a retry re-spends the completion that already\n // paid for this exact (rejected) text.\n throw new ctx.NonRetriableError(\n [\n `Suggested content has invalid reference tags: ${referenceErrors.join(' ')}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n\n let version: number;\n try {\n ({ version } = await ctx.api.prompts.createVersion(promptName, {\n content: suggestedContent,\n tags: ['ai_suggested'],\n }));\n } catch (err) {\n // H4 (T25 review): left unguarded, a 403 here (promptName outside\n // role.prompts) reached the caller as an opaque platform exception —\n // AFTER the llm.complete call above already paid for suggestedContent.\n // Same courtesy as the reference-validation rejection just above: name\n // the cause and include the content the operator already paid for,\n // rather than discarding it behind a generic failure.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n [\n `Cannot save this suggestion: prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts). ${err.message}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n throw err;\n }\n\n return { promptName, version, comparisonCount: comparisons.length };\n}\n","/**\n * `list-gorgias-views` (§3.5) — `uiInvoke`, view autocomplete (S1\n * `listViews`) for the Settings page's `sourceViewId` field, plus §4's\n * cross-app view-claim warning: \"avertit si la vue configurée est déjà\n * revendiquée par une autre app support (lecture croisée du record\n * `pipeline-state` exposé `exposedToApps:['*']`, en lecture seule — seul\n * point de contact inter-apps, purement informatif)\".\n *\n * DELIBERATE EXCEPTION to \"every handler reads settings through\n * `validateSettings` before use\": this function is the checklist's OWN\n * step 2 tool for CHOOSING `sourceViewId` in the first place (§4's \"créer\n * une nouvelle audience\" checklist) — gating it on `validateSettings`,\n * which itself requires `sourceViewId` to be non-empty, would make the\n * autocomplete unusable on the exact first-run screen it exists for. Every\n * OTHER field `validateSettings` checks (`nodes.triage`, `senderEmail`) is\n * equally irrelevant to listing Gorgias views.\n *\n * ASSUMPTION (stated, not decided silently): the kit has no platform\n * capability to enumerate OTHER installed apps — `SupportKitApi` is scoped\n * to this app's own token, and nothing in §2's S1-S6 socle exposes an \"apps\n * of this kind\" listing. `input.checkAppSlugs` is therefore CALLER-SUPPLIED:\n * the Settings page (out of this task's scope) already has its own,\n * unrelated way to see the instance's installed apps (an admin-facing\n * listing this app's own token cannot and should not reach) and passes the\n * OTHER support-kit apps' slugs in. A slug that turns out not to expose\n * `pipeline-state` to this app (not installed, not a support-kit app, or a\n * true `403`) is reported in `uncheckedAppSlugs` rather than failing the\n * whole call — the warning is \"purement informatif\" (§4), never a gate.\n *\n * P1 (« Connexion Gorgias »): this function ALSO reports the instance's\n * Gorgias connections. The Settings page used to expose a free-text\n * `gorgiasConnectionId` that nothing read — every call in the kit goes\n * through `ctx.api.integrations.run('gorgias', …)` WITHOUT a\n * `connectionId`, so the platform resolves the default connection and the\n * field was decorative. The kit now states which connection answers instead\n * of pretending to choose it, and warns on the one configuration that\n * actually breaks: several connections with no default, which the platform\n * rejects with `409 AMBIGUOUS_CONNECTION`\n * (`app-integrations.controller.ts`). It lives here rather than in a new\n * `uiInvoke` function because the Settings page already calls this one for\n * the very same section, and a new function would cost the consuming app a\n * new `universalIdentifier` (`identifierFor` throws on a missing one) for\n * no added capability.\n *\n * `minRole: 'VIEWER'`: a pure read, informational only.\n *\n * T25 DECISION (spec §3.2, \"T25 or the Settings page must supply\n * `checkAppSlugs`\"): `SupportPipelineConfig` deliberately does NOT grow a\n * field for this. A config field would be a STATIC list, fixed at manifest\n * build/publish time — exactly wrong for \"which other support-kit apps\n * exist\", a fact that changes every time an audience is added or removed\n * without republishing this one. The Settings page (T26) is the only\n * correct owner: it already needs an admin-facing \"installed apps\" listing\n * this function's own scoped token cannot and should not reach (see the\n * ASSUMPTION above), and it is the one place that can pass a FRESH\n * `checkAppSlugs` on every invocation. Nothing changes here.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID } from './ids';\n\nexport interface ListGorgiasViewsInput {\n /** Other installed support-kit apps' slugs to check `sourceViewId` overlap against (§4) — see this module's own doc for why this is caller-supplied. */\n checkAppSlugs?: string[];\n}\n\nexport interface GorgiasViewOption {\n id: string;\n name: string;\n /** Other apps whose `pipeline-state.sourceViewId` already names this view. Empty when clear (or unverifiable). */\n claimedByAppSlugs: string[];\n}\n\nexport interface GorgiasConnection {\n id: string;\n label: string;\n isDefault: boolean;\n}\n\nexport interface ListGorgiasViewsResult {\n views: GorgiasViewOption[];\n /** `checkAppSlugs` entries that could not be read (not installed, not exposing `pipeline-state` to this app, or unreachable) — informational, never a failure. */\n uncheckedAppSlugs: string[];\n /**\n * The instance's Gorgias connections, credentials stripped by the platform\n * (`GET /data/integrations/gorgias/connections`). `null` means the listing\n * itself FAILED — distinct from `[]`, which means the instance genuinely\n * has no Gorgias connection and the pipeline cannot run at all. The\n * Settings page renders the two differently, so collapsing them would turn\n * a real misconfiguration into an unexplained blank.\n */\n connections: GorgiasConnection[] | null;\n}\n\nexport function buildListGorgiasViewsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'list-gorgias-views'),\n name: 'list-gorgias-views',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID,\n name: 'checkAppSlugs',\n type: FieldType.JSON,\n label: 'Check app slugs',\n description: 'string[] — other support-kit app slugs to check for a sourceViewId overlap.',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createListGorgiasViewsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => listGorgiasViewsHandler(ctx as SupportKitHandlerContext, config, (input as ListGorgiasViewsInput) ?? {});\n}\n\nconst PIPELINE_STATE_SINGLETON_KEY = 'default';\n\ntype ClaimedViewRead = { ok: true; claimedViewId: string | null } | { ok: false };\n\n/**\n * The view `appSlug` currently claims, or `null` when it claims none (a\n * SUCCESSFUL read of an empty/unset singleton — a fresh app that has never\n * triaged is \"checked, not claiming anything\", not \"unverifiable\"). `ok:\n * false` is reserved for an actual read FAILURE (not installed, not\n * exposing `pipeline-state` to this app, or unreachable) — the two must\n * stay distinct, or a legitimately-clear app would be reported as\n * unverifiable instead of clear.\n */\nasync function readClaimedView(ctx: SupportKitHandlerContext, appSlug: string): Promise<ClaimedViewRead> {\n try {\n const page = await ctx.api.crossApp.list(appSlug, 'pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n const sourceViewId = page.items[0]?.data.sourceViewId;\n return { ok: true, claimedViewId: typeof sourceViewId === 'string' && sourceViewId.length > 0 ? sourceViewId : null };\n } catch {\n return { ok: false };\n }\n}\n\nexport async function listGorgiasViewsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: ListGorgiasViewsInput,\n): Promise<ListGorgiasViewsResult> {\n const rawViews = (await ctx.api.integrations.run('gorgias', 'listViews', {})) as { views: Array<{ id: string | number; name: string }> };\n const views = rawViews.views.map((v) => ({ id: String(v.id), name: v.name }));\n\n // Reported, never thrown: which connection answers is a property of the\n // instance the operator cannot set from here (P1), so a failure to read it\n // must not take the view autocomplete — this function's actual job — down\n // with it.\n let connections: GorgiasConnection[] | null;\n try {\n connections = await ctx.api.integrations.list('gorgias');\n } catch {\n connections = null;\n }\n\n const candidateSlugs = (input.checkAppSlugs ?? []).filter((slug) => slug && slug !== config.slug);\n\n const claimedByViewId = new Map<string, string[]>();\n const uncheckedAppSlugs: string[] = [];\n for (const slug of candidateSlugs) {\n const read = await readClaimedView(ctx, slug);\n if (!read.ok) {\n uncheckedAppSlugs.push(slug);\n continue;\n }\n if (read.claimedViewId === null) continue; // checked, and it claims nothing\n const claimants = claimedByViewId.get(read.claimedViewId) ?? [];\n claimants.push(slug);\n claimedByViewId.set(read.claimedViewId, claimants);\n }\n\n return {\n views: views.map((v) => ({ id: v.id, name: v.name, claimedByAppSlugs: claimedByViewId.get(v.id) ?? [] })),\n uncheckedAppSlugs,\n connections,\n };\n}\n","/**\n * `create-agent` (§3.4) — `uiInvoke`, creates a new drafting agent with a\n * server-assigned `promptName` of `agent/<recordId>`, unless the caller\n * names an existing Langfuse prompt (`input.promptName`, written verbatim).\n *\n * `agent.promptName` is `isNullable: false` with no default\n * (`records/agent.ts`) — the record's own id does not exist until AFTER the\n * create, so a plain `POST records/agent` from the browser has no legal\n * value to send for it. Before this function existed, AgentsPage's \"Nouvel\n * agent\" form posted with no `promptName` field at all, the write was\n * rejected, `save()` had no `.catch`, and the modal just sat there with no\n * feedback (T26 review, BLOCKER 3).\n *\n * The fix is the two-step create-then-patch the record id makes necessary,\n * done in ONE server-side round trip: the browser only ever sees the final,\n * fully-formed agent — never the placeholder `promptName` the first write is\n * forced to carry for the instant before the id is known.\n *\n * `minRole: 'EDITOR'`: creating an agent is an editing action, matching\n * every other agent-mutating control on AgentsPage.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { DEFAULT_LLM_PROVIDER } from '../records/agent';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n CREATE_AGENT_INPUT_MODEL_ID_UID,\n CREATE_AGENT_INPUT_NAME_UID,\n CREATE_AGENT_INPUT_PROMPT_LABEL_UID,\n CREATE_AGENT_INPUT_PROMPT_NAME_UID,\n CREATE_AGENT_INPUT_PROVIDER_UID,\n CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n} from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\n/**\n * Placeholder `promptName` for the single instant between the create and the\n * patch that overwrites it with `agent/<id>` — this handler is the only\n * thing that ever reads a record carrying it, so its exact spelling has no\n * external contract.\n */\nconst PENDING_PROMPT_NAME = 'agent/pending';\n\nexport interface CreateAgentInput {\n name: string;\n modelId: string;\n provider?: string;\n /**\n * The agent's initial prompt text. On the derived-`agent/<id>` path it is\n * seeded into Langfuse as v1 and promoted to `production` (best-effort —\n * see `seedInitialVersion`); on every path it is also stored on the record\n * as the level-3 fallback, which later version writes keep refreshed.\n */\n systemPromptSnapshot?: string;\n /**\n * Langfuse prompt this agent uses, written VERBATIM (trim only — no case,\n * accent or dash normalisation: `agent/Prompt 7 — Client Satisfait & Avis`\n * must land byte for byte). Absent or empty → the legacy server-derived\n * `agent/<recordId>`.\n */\n promptName?: string;\n /**\n * Langfuse label the agent follows. Absent or empty → stays null, the\n * convention `draftPromptRefFor` reads as \"follow `production`\" — never\n * frozen to the literal string at write time.\n */\n promptLabel?: string;\n}\n\nexport function buildCreateAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-agent'),\n name: 'create-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: CREATE_AGENT_INPUT_NAME_UID, name: 'name', type: FieldType.TEXT, label: 'Name', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_PROVIDER_UID, name: 'provider', type: FieldType.TEXT, label: 'Provider', isNullable: true },\n {\n universalIdentifier: CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n name: 'systemPromptSnapshot',\n type: FieldType.TEXT,\n label: 'System prompt snapshot',\n isNullable: true,\n },\n {\n universalIdentifier: CREATE_AGENT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: CREATE_AGENT_INPUT_PROMPT_LABEL_UID,\n name: 'promptLabel',\n type: FieldType.TEXT,\n label: 'Prompt label',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createCreateAgentHandler(): AppHandler {\n return (ctx, input) =>\n createAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as CreateAgentInput) ?? {});\n}\n\nexport async function createAgentHandler(\n ctx: SupportKitHandlerContext,\n input: CreateAgentInput,\n): Promise<AgentRecord> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n const modelId = input?.modelId?.trim();\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n\n const base = {\n name,\n modelId,\n provider: input.provider?.trim() || DEFAULT_LLM_PROVIDER,\n status: 'available',\n ...(input.systemPromptSnapshot?.trim() ? { systemPromptSnapshot: input.systemPromptSnapshot.trim() } : {}),\n ...(input.promptLabel?.trim() ? { promptLabel: input.promptLabel.trim() } : {}),\n };\n\n // An explicit promptName is written verbatim in ONE create: no placeholder,\n // and no id-derived overwrite — deriving would silently detach the agent\n // from the pre-existing Langfuse prompt the caller just named.\n const promptName = input.promptName?.trim();\n if (promptName) {\n return toAgent(await ctx.api.create('agent', { ...base, promptName }));\n }\n\n const created = await ctx.api.create('agent', { ...base, promptName: PENDING_PROMPT_NAME });\n const derivedName = `agent/${created.id}`;\n const withPromptName = await ctx.api.update('agent', created.id, { promptName: derivedName });\n await seedInitialVersion(ctx, derivedName, input.systemPromptSnapshot?.trim() ?? '');\n return toAgent(withPromptName);\n}\n\n/**\n * Seed the derived prompt with its first version and promote it to\n * `production` — an unpromoted v1 carries no label, so an agent following\n * `production` would resolve to nothing (same reasoning as the shared-prompt\n * creation flow's immediate promote).\n *\n * Best-effort: the agent record already exists and carries the text as its\n * level-3 fallback, so a Langfuse outage must not fail the create — the\n * operator lands on an agent whose \"prompt introuvable\" badge and empty\n * version list say exactly what is missing, and the first version written\n * from the edit panel repairs it.\n */\nasync function seedInitialVersion(\n ctx: SupportKitHandlerContext,\n promptName: string,\n content: string,\n): Promise<void> {\n if (!content) return;\n try {\n const { version } = await ctx.api.prompts.createVersion(promptName, { content });\n await ctx.api.prompts.promote(promptName, version, 'production');\n } catch (err) {\n ctx.logger.warn(\n `create-agent: could not seed \"${promptName}\" with its initial version — the text is kept as the agent's fallback (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n}\n","/**\n * `set-default-agent` (§3.4) — `uiInvoke`, promotes one agent to\n * `status: 'default'` while demoting whatever agent currently holds it.\n *\n * `records/agent.ts` documents the invariant: \"at most one default agent\",\n * enforced by a unique index on `defaultKey`, which is set to `'default'`\n * exactly when `status === 'default'` and left absent otherwise (so Postgres\n * NULLs never collide) — and states that POPULATING `defaultKey` correctly\n * is \"a write-handler concern\", not the record definition's. Before this\n * function existed, nothing populated it at all: AgentsPage's \"Définir par\n * défaut\" button wrote `{status: 'default'}` alone, from the browser, as two\n * independent `PATCH` calls with no shared transaction — `defaultKey` never\n * moved, the unique index never fired, and clicking the button on a second\n * agent produced two rows with `status: 'default'` without demoting the\n * first. `resolveDraftAgent` (`functions/records.ts`) resolves the default\n * agent via `list('agent', {filter:{status:'default'}, limit:1})`, so which\n * of the two an uncategorised ticket drafts with became non-deterministic,\n * and `ext-models` would serve two \"default\" agents to the extension (T26\n * review, BLOCKER 4).\n *\n * This function does both writes from ONE server-side call, DEMOTING the\n * incumbent BEFORE promoting the target — not the other way round, and not\n * in parallel: `defaultKey` carries a unique index, so having the incumbent\n * and the target both hold `'default'` at once, even for one write, would\n * violate it. Demoting first means a failure between the two writes leaves\n * AT MOST ZERO default agents (a safe, if inconvenient, state an operator\n * can fix by retrying) rather than two — this kit has no cross-record\n * transaction to make the pair atomic, so \"the worst reachable state is\n * still a legal one\" is the best guarantee available without one.\n *\n * `minRole: 'EDITOR'`: matches AgentsPage's other agent-mutating controls.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID } from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\nconst DEFAULT_KEY_VALUE = 'default';\n\nexport interface SetDefaultAgentInput {\n agentId: string;\n}\n\nexport function buildSetDefaultAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'set-default-agent'),\n name: 'set-default-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.TEXT,\n label: 'Agent id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSetDefaultAgentHandler(): AppHandler {\n return (ctx, input) =>\n setDefaultAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as SetDefaultAgentInput) ?? {});\n}\n\nexport async function setDefaultAgentHandler(\n ctx: SupportKitHandlerContext,\n input: SetDefaultAgentInput,\n): Promise<AgentRecord> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const target = toAgent(await ctx.api.get('agent', agentId));\n if (target.status === 'default') return target; // already the default — no-op, not an error.\n\n const incumbentPage = await ctx.api.list('agent', { filter: { status: 'default' }, limit: 1 });\n const incumbent = incumbentPage.items[0];\n if (incumbent && incumbent.id !== agentId) {\n await ctx.api.update('agent', incumbent.id, { status: 'available', defaultKey: null });\n }\n\n const promoted = await ctx.api.update('agent', agentId, {\n status: 'default',\n defaultKey: DEFAULT_KEY_VALUE,\n });\n return toAgent(promoted);\n}\n","/**\n * `create-shared-prompt-version` (§3.8 SharedPromptsPage, T27 part B) — the\n * ONE write path SharedPromptsPage uses to save a new `shared/*` prompt\n * version.\n *\n * Why this exists instead of the browser calling S3's own\n * `POST /data/apps/:appSlug/prompts/versions` directly (the way\n * `AgentsPage`'s `usePromptVersions.createVersion` already does for an\n * agent's prompt): that route writes whatever content it is given — it\n * does not run `validateReferences` (`./validate-references.ts`), and per\n * T19/T23's own review, nothing server-side does either. Since the kit\n * resolves `@@@langfusePrompt:…@@@` composition ITSELF (T19's\n * `prompts/resolver.ts`, reading with `resolve:false`), a malformed tag\n * saved through the raw REST route reaches every draft that composes\n * `shared/style-email`/`shared/style-whatsapp` verbatim, with nothing\n * server-side left to catch it — exactly the gap T23's review named for\n * `suggest-prompt`'s write path (§3.5). This is the same guard, for a\n * human operator's edit instead of an LLM suggestion.\n *\n * Scoped to `shared/` names only (refuses anything else): SharedPromptsPage\n * is a `shared/*` library editor, not a general prompt-writing surface.\n * `role.prompts`' `shared/*` glob (`pipeline.ts`'s `buildPromptsAllowlist`)\n * is the actual authorization boundary; this refusal is a narrower,\n * separate promise about what THIS function is for — `AgentsPage` keeps\n * writing an agent's own prompt through S3's raw route, unaffected.\n *\n * `minRole: 'EDITOR'`: a write, like every other prompt-mutating control\n * in the kit (`createVersion`/`promote`/`deleteVersion`, S3).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID, CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID } from './ids';\nimport { validateReferences } from './validate-references';\n\nconst SHARED_PREFIX = 'shared/';\n\nexport interface CreateSharedPromptVersionInput {\n name: string;\n content: string;\n}\n\nexport interface CreateSharedPromptVersionResult {\n version: number;\n}\n\nexport function buildCreateSharedPromptVersionFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-shared-prompt-version'),\n name: 'create-shared-prompt-version',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createCreateSharedPromptVersionHandler(): AppHandler {\n return (ctx, input) =>\n createSharedPromptVersionHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as CreateSharedPromptVersionInput) ?? { name: '', content: '' },\n );\n}\n\nexport async function createSharedPromptVersionHandler(\n ctx: SupportKitHandlerContext,\n input: CreateSharedPromptVersionInput,\n): Promise<CreateSharedPromptVersionResult> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n if (!name.startsWith(SHARED_PREFIX)) {\n throw new ctx.NonRetriableError(\n `\"${name}\" is not a shared/* prompt — create-shared-prompt-version only writes the shared/* library.`,\n );\n }\n const content = input?.content ?? '';\n if (!content.trim()) throw new ctx.NonRetriableError('content is required');\n\n const referenceErrors = await validateReferences(ctx.api, content, name);\n if (referenceErrors.length > 0) {\n throw new ctx.NonRetriableError(`Invalid reference tags: ${referenceErrors.join(' ')}`);\n }\n\n return ctx.api.prompts.createVersion(name, { content });\n}\n","/**\n * `sync-agent-prompt-snapshot` (§5.2) — `uiInvoke`, rewrites one agent's\n * `systemPromptSnapshot` with the prompt content that agent NOW serves.\n *\n * Why the snapshot needs a writer at all: `GET /models` serves\n * `system_prompt` from `agent.systemPromptSnapshot` ONLY (`ext-models.ts`)\n * — §5.2 forbids a synchronous Langfuse read there, because the extension\n * calls that route on every ticket change for every support agent. The spec\n * pays for that with one sentence: the snapshot is \"rafraîchi en tâche de\n * fond à chaque `createVersion`/`promote`\". Nothing did that. The only\n * writers were `create-agent` (from its input, once) and a hand edit in\n * AgentsPage, so promoting a new version moved what the PIPELINE drafts\n * with while the extension kept serving the text of whatever version was\n * current the day the agent was created — and `draftPromptRefFor`'s\n * level-3 fallback (`records.ts`) stayed pinned to that same stale text.\n *\n * Keyed by `promptName`, not by agent id, because the caller\n * (`ui/agents/use-prompt-versions.ts`) is a prompt-versions hook: it knows\n * the prompt it just wrote, never which record owns it. That also gives\n * the `shared/*` case its answer for free — a company-wide prompt belongs\n * to no agent, the lookup finds nothing, and the function is a no-op\n * rather than needing a namespace test of its own.\n *\n * WHAT IS SERVED, not what is newest: an agent pinned via\n * `agent.promptVersion` keeps drafting with that exact version, so its\n * snapshot must be that version's content — refreshing it to the newest\n * one would make `GET /models` advertise a prompt the pipeline does not\n * use. The ref built here is the same one `draftPromptRefFor` resolves.\n *\n * Read with `resolve: false`, like `createPlatformPromptReader`\n * (`adapters/ctx-ports.ts`): the kit flattens `@@@langfusePrompt:…@@@`\n * composition itself, so the snapshot must hold the RAW stored template —\n * the same text the resolver would have cached — not a pre-flattened\n * variant the fallback path would never produce.\n *\n * Never rejects on a resolution failure: by the time this runs, the\n * `createVersion`/`promote` it follows has already committed. Turning a\n * Langfuse outage into a failed promote would report a write that DID\n * happen as a write that did not; a stale snapshot is the lesser, and\n * self-correcting, harm (the next version write retries it).\n *\n * `minRole: 'EDITOR'`: it follows a prompt write, which is already\n * EDITOR-only (S3's own `createVersion`/`promote`).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID } from './ids';\nimport { toAgent } from './records';\n\nexport interface SyncAgentPromptSnapshotInput {\n promptName: string;\n}\n\nexport interface SyncAgentPromptSnapshotResult {\n /** `false` also covers \"nothing to do\": no agent owns the prompt, the snapshot already matched, or the read failed. */\n updated: boolean;\n}\n\nexport function buildSyncAgentPromptSnapshotFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sync-agent-prompt-snapshot'),\n name: 'sync-agent-prompt-snapshot',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSyncAgentPromptSnapshotHandler(): AppHandler {\n return (ctx, input) =>\n syncAgentPromptSnapshotHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as SyncAgentPromptSnapshotInput) ?? { promptName: '' },\n );\n}\n\nexport async function syncAgentPromptSnapshotHandler(\n ctx: SupportKitHandlerContext,\n input: SyncAgentPromptSnapshotInput,\n): Promise<SyncAgentPromptSnapshotResult> {\n const promptName = input?.promptName?.trim();\n if (!promptName) throw new ctx.NonRetriableError('promptName is required');\n\n // EVERY agent carrying the name, not `limit: 1`: two agents may point at\n // the same Langfuse prompt (pin vs follow), and refreshing only whichever\n // one the list returned first left the other serving a stale snapshot in\n // silence.\n const page = await ctx.api.list('agent', { filter: { promptName } });\n let updated = false;\n\n for (const record of page.items) {\n const agent = toAgent(record);\n try {\n const ref =\n agent.promptVersion !== null ? { version: agent.promptVersion } : { label: agent.promptLabel ?? 'production' };\n const detail = await ctx.api.prompts.get(promptName, { ...ref, resolve: false });\n if (detail.content === agent.systemPromptSnapshot) continue;\n\n await ctx.api.update('agent', agent.id, { systemPromptSnapshot: detail.content });\n updated = true;\n } catch (error) {\n ctx.logger.warn(\n `sync-agent-prompt-snapshot: could not refresh \"${promptName}\" for agent ${agent.id} — GET /models keeps serving the previous snapshot (${String(error)})`,\n );\n }\n }\n\n return { updated };\n}\n","/**\n * `ext-models` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports legacy\n * `GET /api/models` (extension-overview backoffice/src/routes/api.ts:27).\n * Reached only through the platform-served extension gateway (S6), always\n * as `phase: 'execute'`, fanned out to every accessible app and unioned —\n * this function MUST return an array: a non-array result is logged and\n * silently dropped from the union by the gateway\n * (`SupportExtensionService.invokeAll`), never surfaced as an error.\n *\n * `system_prompt` is served from `agent.systemPromptSnapshot` ONLY — never\n * a synchronous Langfuse resolution. §5.2 is explicit about why: this\n * endpoint is hit on every ticket change, by every agent, so a per-request\n * Langfuse round trip at that frequency is the exact cost the snapshot\n * exists to avoid. The snapshot itself is kept fresh out-of-band, by\n * whichever write path refreshes it on `createVersion`/`promote` — not this\n * function's job.\n *\n * `system_prompt_token_count` is kept (frozen data model, §5.2 — \"conservé\n * bien qu'ignoré par l'extension\") but is an APPROXIMATION, not tiktoken's\n * real count: the kit cannot depend on `tiktoken`\n * (`dependency-allowlist.ts`, spec §3.1 — it is a native/WASM dependency,\n * unsafe across an arbitrary app's ESM bundler). This ports the legacy\n * tokenizer's OWN documented fallback path verbatim\n * (`utils/tokenizer.ts`'s `catch` branch, `Math.ceil(text.length / 4)`) —\n * here it is the only implementation, not a fallback from a real\n * tokenizer. It is a rough estimate (English text averages roughly 4\n * characters per token; French/accented text and code both deviate\n * further from that ratio) and MUST NOT be treated as exact by any future\n * consumer — today's one consumer (the extension) explicitly ignores it.\n *\n * `archived` agents are excluded — legacy's `status: {$in: ['default',\n * 'available']}` filter. Legacy sorts `{status: 1, name: 1}`; ported here\n * for this function's OWN array. The GATEWAY re-sorts the union by\n * `(order, name)` (§S6, D3) and a model carries no `order` field, so the\n * final wire order across multiple support apps ends up name-alphabetical\n * rather than `(status, name)` — a documented S6/T8 divergence from the\n * legacy, not this function's to fix (see the migration progress journal's\n * T24 entry).\n *\n * SETTINGS VALIDATION: deliberately NOT called here, same reasoning as\n * `list-gorgias-views`'s own documented exception. This function reads no\n * field `validateSettings` checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) — it is a pure read of `agent` records serving a human\n * agent's Gorgias sidebar model picker. Gating it on settings validity\n * would break that picker for a tenant mid-setup, for no correctness\n * reason: nothing here depends on the triage pipeline being configured.\n *\n * `minRole: 'VIEWER'` is load-bearing: `SupportExtensionService\n * .hasAllReservedFunctions` refuses to treat an app as a support app\n * unless all six reserved functions declare exactly `VIEWER`.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent } from './records';\n\nconst TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtModel {\n _id: string;\n name: string;\n provider: string;\n model_id: string;\n system_prompt: string;\n system_prompt_token_count: number;\n status: 'default' | 'available';\n}\n\nexport function buildExtModelsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-models'),\n name: 'ext-models',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtModelsHandler(): AppHandler {\n return (ctx) => extModelsHandler(ctx as SupportKitHandlerContext);\n}\n\nexport async function extModelsHandler(ctx: SupportKitHandlerContext): Promise<ExtModel[]> {\n const page = await ctx.api.list('agent', { limit: AGENT_PAGE_SIZE });\n // L15: the migration's standing rule is \"no silent caps\" — past 500\n // agents the union would silently lose entries with no cursor and no\n // warning.\n if (page.items.length >= AGENT_PAGE_SIZE) {\n ctx.logger.warn(`ext-models: \"agent\" page came back full at ${page.items.length} rows — some may be silently missing from the response.`);\n }\n\n return page.items\n .map(toAgent)\n .filter((agent): agent is typeof agent & { status: 'default' | 'available' } => agent.status !== 'archived')\n .sort((a, b) => (a.status === b.status ? a.name.localeCompare(b.name) : a.status.localeCompare(b.status)))\n .map((agent) => {\n const systemPrompt = agent.systemPromptSnapshot ?? '';\n return {\n _id: agent.id,\n name: agent.name,\n provider: agent.provider,\n model_id: agent.modelId,\n system_prompt: systemPrompt,\n system_prompt_token_count: approximateTokenCount(systemPrompt),\n status: agent.status,\n };\n });\n}\n\nfunction approximateTokenCount(text: string): number {\n return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);\n}\n","/**\n * `ext-categories` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports\n * legacy `GET /api/categories` (extension-overview backoffice/src/routes\n * /api.ts:50). Reached only through the S6 gateway, always `phase:\n * 'execute'`, fanned out to every accessible app and unioned — MUST return\n * an array (a non-array is dropped by the gateway, same rule as\n * `ext-models`).\n *\n * Filter (legacy `Category.find({agent: {$ne: null}}).populate({path:\n * 'agent', match: {status: {$ne: 'archived'}}})` then `.filter(c => c.agent\n * !== null)`): a category counts only when it HAS an `agentId` AND that\n * agent resolves AND is not archived. §5.2's own response shape freezes\n * `agent: {...} | null`, but this filter means the `| null` branch is\n * UNREACHABLE through this handler today — kept in the type for wire\n * fidelity with the frozen contract, never actually emitted.\n *\n * Sort (composite, §5.2's own doc on this route): `group.order` ASC, with\n * ungrouped categories FIRST (`null` sorts as `-Infinity`) → `category\n * .order` ASC → `category.name` `localeCompare`. The category-group record\n * already exists (`records/category-group.ts`); this function is its\n * first reader.\n *\n * WIRE `order` IS NOT `category.order` (M4 hardening): the S6 gateway\n * unions every accessible app's categories and re-sorts by `(order, name)`\n * ONLY — it has no visibility into the group concept at all\n * (`support-extension.service.ts`'s own doc on `sortedUnion`). `order` is\n * per-GROUP, not global, so emitting the raw field would let the gateway's\n * blind re-sort silently destroy the group ordering this function just\n * computed (a single installed app is enough to observe it — no multi-app\n * edge case required). What is emitted instead is this category's own\n * POSITION in the fully sorted sequence above (0, 1, 2, …) — a composite\n * rank that already encodes group→order→name as one monotonic number, so\n * the gateway's re-sort is a genuine no-op on this app's contiguous slice,\n * not just a documented aspiration.\n *\n * SETTINGS VALIDATION: deliberately NOT called, same reasoning as\n * `ext-models` — a pure read of `category`/`agent` records serving a human\n * agent's Gorgias sidebar, gated on none of `validateSettings`'s fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent, toCategory, toCategoryGroup, type AgentRecord, type CategoryRecord } from './records';\n\nconst CATEGORY_PAGE_SIZE = 500;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtCategoryAgent {\n _id: string;\n name: string;\n model_id: string;\n provider: string;\n}\n\nexport interface ExtCategory {\n _id: string;\n name: string;\n tag_name: string;\n order: number;\n agent: ExtCategoryAgent | null;\n}\n\nexport function buildExtCategoriesFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-categories'),\n name: 'ext-categories',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtCategoriesHandler(): AppHandler {\n return (ctx) => extCategoriesHandler(ctx as SupportKitHandlerContext);\n}\n\ninterface SortableEntry {\n category: CategoryRecord;\n agent: AgentRecord;\n groupOrder: number;\n}\n\nexport async function extCategoriesHandler(ctx: SupportKitHandlerContext): Promise<ExtCategory[]> {\n const [categoriesPage, groupsPage, agentsPage] = await Promise.all([\n ctx.api.list('category', { limit: CATEGORY_PAGE_SIZE }),\n ctx.api.list('category-group', { limit: CATEGORY_PAGE_SIZE }),\n // M7: ONE bulk read, not one `ctx.api.get` per category — this endpoint\n // runs on the same \"every ticket change, every agent\" cadence §5.2\n // documents for `/models` (which already does this), inside the\n // gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips\n // risk a slow tenant's whole categories response silently dropping out\n // of the union on budget exhaustion.\n ctx.api.list('agent', { limit: AGENT_PAGE_SIZE }),\n ]);\n warnIfTruncated(ctx, 'category', categoriesPage.items.length, CATEGORY_PAGE_SIZE);\n warnIfTruncated(ctx, 'agent', agentsPage.items.length, AGENT_PAGE_SIZE);\n\n const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));\n const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));\n\n const entries: SortableEntry[] = [];\n for (const category of categoriesPage.items.map(toCategory)) {\n if (!category.agentId) continue;\n const agent = agentById.get(category.agentId);\n if (!agent) continue;\n if (agent.status === 'archived') continue;\n\n const groupOrder = category.groupId ? (groupOrderById.get(category.groupId) ?? -Infinity) : -Infinity;\n entries.push({ category, agent, groupOrder });\n }\n\n entries.sort((a, b) => {\n if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;\n if (a.category.order !== b.category.order) return a.category.order - b.category.order;\n return a.category.name.localeCompare(b.category.name);\n });\n\n return entries.map(({ category, agent }, index) => ({\n _id: category.id,\n name: category.name,\n tag_name: category.tagName,\n // M4: this category's own POSITION in the fully sorted sequence, not\n // `category.order` verbatim — see this module's own doc.\n order: index,\n agent: { _id: agent.id, name: agent.name, model_id: agent.modelId, provider: agent.provider },\n }));\n}\n\n/** L15: the migration's standing rule is \"no silent caps\" — a page that comes back exactly full warrants a log, not a quiet truncation. */\nfunction warnIfTruncated(ctx: SupportKitHandlerContext, objectKey: string, itemCount: number, pageSize: number): void {\n if (itemCount >= pageSize) {\n ctx.logger.warn(`ext-categories: \"${objectKey}\" page came back full at ${itemCount} rows — some may be silently missing from the response.`);\n }\n}\n","/**\n * `ownsAgent` (L6) — the ONE `agent`-ownership probe check shared by\n * `ext-chat`, `ext-evaluation` and `ext-response-comparison`'s `phase:\n * 'probe'` branches (§S6 B1/B2): each restated the same `{claimed: true}`\n * sentinel, the same \"non-null claims / null disclaims / a genuine read\n * failure is never a disclaimer, it propagates as a real error\" contract,\n * and the same union return type. Three uses, so the no-premature-\n * abstraction rule does not shield the duplication.\n *\n * `id` absent/empty never claims — callers decide separately what to try\n * next on a `null` (`ext-chat` falls back to the default agent,\n * `ext-response-comparison` falls back to ticket ownership); this helper\n * only ever answers \"does this app own this one id\".\n */\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface ProbeClaim {\n claimed: true;\n}\n\nexport async function ownsAgent(ctx: SupportKitHandlerContext, id: string | null | undefined): Promise<ProbeClaim | null> {\n if (!id) return null;\n const record = await getOptional(ctx, 'agent', id);\n return record ? { claimed: true } : null;\n}\n","/**\n * `readSupportExtensionEnvelope` — the identity/phase the S6 gateway passes\n * on every reserved `ext-*` invocation\n * (`SupportExtensionService.invoke`'s `event: {supportExtension: {userId,\n * phase}}`, apps/api/src/platform-data/support-extension.service.ts).\n * Shared by every function that needs either half: `ext-chat`/\n * `ext-evaluation`/`ext-response-comparison` for the probe/execute split\n * (§5.1/§S6), `ext-evaluation` (`supportUserKeyId`) and\n * `ext-fast-response-check` (`servedTo`) for the platform user id itself.\n *\n * Defensive default, not a thrown error: an envelope that is missing or\n * malformed — which never happens through the real gateway, nothing else\n * invokes these reserved functions (§3.5 line 291) — resolves to `phase:\n * 'execute'` and `userId: ''` rather than crashing the whole handler on a\n * read. `'execute'` is the safe default direction for the phase: treating\n * an ambiguous call as `'probe'` would silently skip whatever real work the\n * caller actually wanted, while treating it as `'execute'` on a call that\n * WAS meant to be a cheap ownership probe only risks doing that same real\n * work anyway — never doing LESS than asked.\n *\n * `userId: ''` IS a safe default here — this is a pure READ with no side\n * effect. It is NOT safe symmetric treatment for the two call sites that\n * write it into an identity-bearing record (`ext-fast-response-check.ts`'s\n * `servedTo` push, `ext-evaluation.ts`'s `supportUserKeyId`) — §5.1\n * requires those records to carry the platform user id, so both callers\n * guard `!envelope.userId` themselves and fail the WRITE rather than\n * silently producing an anonymous-looking or null-identity row (L11\n * hardening). This function stays a defensive default, not a thrown error,\n * exactly as designed above; the burden of turning \"no identity\" into a\n * hard failure is on the two write sites that actually need one.\n */\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface SupportExtensionEnvelope {\n userId: string;\n phase: 'probe' | 'execute';\n}\n\nexport function readSupportExtensionEnvelope(ctx: SupportKitHandlerContext): SupportExtensionEnvelope {\n const raw = (ctx.event as { supportExtension?: { userId?: unknown; phase?: unknown } } | undefined)?.supportExtension;\n return {\n userId: typeof raw?.userId === 'string' ? raw.userId : '',\n phase: raw?.phase === 'probe' ? 'probe' : 'execute',\n };\n}\n","/**\n * `ext-chat` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-routed\n * (§S6). Ports legacy `POST /api/chat` (extension-overview backoffice/src\n * /routes/api.ts:147).\n *\n * OWNERSHIP PROBE (§S6 B1/B2): the gateway first calls this function with\n * `phase: 'probe'` and an id-only payload `{modelId}` — `modelId` may be\n * `undefined` (the legacy falls back to the single `status: 'default'`\n * model when it is absent). A probe MUST be cheap, local and side-effect-\n * free: no writes, no LLM call, no Gorgias fetch (`readSupportExtension\n * Envelope` picks the phase; the probe branch below only ever reads the\n * `agent` object). Claim rule, decided explicitly:\n * - `modelId` given → claim iff this app owns an `agent` record with\n * that id (any status — the legacy `ModelConfig.findById` applies no\n * status filter for chat, unlike `ext-models`).\n * - `modelId` absent → claim iff this app has a `status: 'default'`\n * agent.\n * AMBIGUITY, stated not hidden: with several installed support apps and no\n * `modelId`, more than one app can legitimately have its own default\n * agent, so more than one can claim the SAME probe. The gateway logs a\n * warning and routes to the first claimant (`SupportExtensionService\n * .invokeOwner`) — this function has no way to break that tie itself, and\n * does not try to. Returning any non-null value claims ownership; `null`\n * disclaims it. THROWING is never a way to say \"not mine\" (a genuine read\n * failure here propagates as a real error, exactly like every other\n * function — the gateway treats a probe throw as a fan-out failure, never\n * a disclaimer).\n *\n * EXECUTE: once ownership resolves, the gateway sends ONE `phase:\n * 'execute'` call with the full body — `{messages, modelId, agentName}` OR\n * `{gorgiasTicketId, modelId, agentName}`. When `gorgiasTicketId` is given\n * the conversation is rebuilt server-side via S1's `buildTicketContext`\n * action (NOT `getTicketWithContext` — only the extracted messages are\n * needed here, not the raw ticket payload `getTicketWithContext` also\n * fetches for the guardrail detectors elsewhere in the kit).\n *\n * PROMPT RESOLUTION reuses the kit's own §3.7 ladder\n * (`createPlatformPromptPort`) and `functions/records.ts`'s\n * `draftPromptRefFor` — the SAME binding `process-response` resolves the\n * `draft` node's prompt from (agent.promptName/promptLabel/\n * systemPromptSnapshot) — rather than writing a second resolver.\n *\n * `{{agent_name}}` SIGNATURE: §3.7 states the substitution is \"injectée\n * par `ext-chat`\" — this function calls the exact ported\n * `applySignature` (`graph/nodes/shared.ts`, exported for this reuse) on\n * the RESOLVED prompt text with the extension's own `agentName`, not the\n * generic `{{var}}` substitution `PromptPort.resolve`'s `vars` parameter\n * offers (which is a plain string replace, not `applySignature`'s full\n * rule set — appending a French signing instruction when there is no\n * placeholder at all). Reusing the ported function here — instead of a\n * second, subtly different implementation — was an explicit instruction in\n * this migration.\n *\n * SETTINGS VALIDATION: deliberately NOT called. Chat resolves its prompt\n * from the `agent` record's own binding, never from `validateSettings`'s\n * three checked fields (`sourceViewId`, `nodes.triage`, `senderEmail`) — a\n * misconfigured triage pipeline must not block an agent from testing a\n * model in the sidebar.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n *\n * POST-T24 REVIEW HARDENING:\n * - `options.model` now reads `resolvedPrompt.config?.model ?? agent\n * .modelId` (I16) — the resolved prompt's own model config wins, matching\n * every ported graph node; this was the one `PromptPort.resolve` consumer\n * that dropped it.\n * - `promptRef` IS forwarded to `ctx.api.llm.complete`, in LINK-ONLY mode\n * (`resolve: false`) — the D-LF follow-up task's resolution (option (b),\n * see the migration progress journal's T24 entry and its \"done\" correction):\n * the platform now decouples trace linkage from resolution, so a caller\n * that already resolved its own prompt (this function did, via\n * `PromptPort` two lines above) can link the completion to it in Langfuse\n * WITHOUT re-triggering the `manifest.prompts[]` declaration gate or the\n * system-message replacement (`app-integrations.controller.ts`'s\n * `llmComplete` JSDoc). This restores the same prompt-identity trace\n * linkage the platform's default mode gives every other caller, without\n * the 403/overwrite defect that forced the `trace.metadata` workaround\n * below during T24. The platform user id still travels on `trace.metadata`\n * (`ctx.api.llm.complete`'s `trace` has no dedicated `userId` field) — the\n * prompt identity no longer needs to, now that `promptRef` carries it. The\n * wire response is UNCHANGED — it still reports `prompt_name`/\n * `prompt_version` off `resolvedPrompt`.\n * The five graph nodes (`triage`/`escalate`/`draft`/`revise`/`evaluate`)\n * plus `suggest-prompt.ts`/`run-diff-analysis.ts` forward `promptRef` the\n * same link-only way now too — all seven sites adopted together.\n * - The gorgias-ticket branch now 400s on zero extracted messages, the same\n * guard the `input.messages` branch already had (M1) — an internal-notes-\n * only or automated-sender ticket must not pay for an LLM call with a\n * system message and no conversation.\n * - A Gorgias 404 (duck-typed off the caught error's `status`, since this\n * package has no dependency on `gorgias-client`'s `ProviderHttpError` to\n * `instanceof`-check) now throws `NonRetriableError` instead of a bare\n * rethrow (L1, PARTIAL). The legacy's other two mappings — \"not\n * configured\" → 503, else → 502 — are NOT reachable from here: every\n * `uiInvoke` throw funnels through `AppSyncInvocationService.toHttpError`\n * (`apps/api/src/platform-data/app-sync-invocation.service.ts`), which\n * recognises exactly two outcomes for an app-thrown error —\n * `AppNonRetriableError` → 422, anything else → 500 — regardless of what\n * `invokeOwner` does or doesn't wrap. 503/502 are outside this function's\n * reach without a platform change to that mapping.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { RawTicketContext } from '../adapters';\nimport { createPlatformPromptPort } from '../adapters/ctx-ports';\n// L9: through the barrel, not `./shared` directly — `graph/nodes/index.ts`'s\n// own doc names `applySignature` as its one curated export existing FOR this\n// reuse; importing straight from the file it lives in made that barrel entry\n// unused and its own justification inaccurate.\nimport { applySignature } from '../graph/nodes';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_CHAT_INPUT_AGENT_NAME_UID,\n EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n EXT_CHAT_INPUT_MESSAGES_UID,\n EXT_CHAT_INPUT_MODEL_ID_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { draftPromptRefFor, toAgent, type AgentRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst DEFAULT_AGENT_FILTER = { status: 'default' } as const;\n\ninterface WireChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ExtChatInput {\n messages?: Array<{ role?: unknown; content?: unknown }> | null;\n modelId?: string | null;\n agentName?: string | null;\n gorgiasTicketId?: string | null;\n}\n\nexport interface ExtChatResult {\n answer: string;\n modelId: string;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n}\n\nexport function buildExtChatFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-chat'),\n name: 'ext-chat',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_CHAT_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — required unless gorgiasTicketId is given.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_MODEL_ID_UID,\n name: 'modelId',\n type: FieldType.TEXT,\n label: 'Model id',\n description: 'Absent falls back to the single status=\"default\" agent.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_AGENT_NAME_UID,\n name: 'agentName',\n type: FieldType.TEXT,\n label: 'Agent name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n name: 'gorgiasTicketId',\n type: FieldType.TEXT,\n label: 'Gorgias ticket id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtChatHandler(): AppHandler {\n return (ctx, input) => extChatHandler(ctx as SupportKitHandlerContext, (input as ExtChatInput) ?? {});\n}\n\nexport async function extChatHandler(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<ExtChatResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeChatOwnership(ctx, input.modelId ?? null);\n return executeChat(ctx, envelope.userId, input);\n}\n\nasync function probeChatOwnership(ctx: SupportKitHandlerContext, modelId: string | null): Promise<ProbeClaim | null> {\n if (modelId) return ownsAgent(ctx, modelId);\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeChat(ctx: SupportKitHandlerContext, userId: string, input: ExtChatInput): Promise<ExtChatResult> {\n const contextMessages = await resolveMessages(ctx, input);\n const agent = await resolveAgent(ctx, input.modelId ?? null);\n\n const promptPort = createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message));\n // H5 (T25 review): draftPromptRefFor's \"no agent configured\" sentinel is\n // scoped by promptPrefix — but createExtChatHandler() takes no\n // SupportKitFunctionConfig at all (unlike every other ext-* handler that\n // needs one, none of the six do), so this call site has no promptPrefix\n // to pass. `{ promptPrefix: '' }` keeps today's behaviour for\n // experience-client unchanged; a pro-sante (or later) audience installed\n // with a non-empty prefix still 403s on this specific path exactly as it\n // already did before this fix. Threading config through the S6 gateway's\n // internal ext-chat invocation is a wider change than this finding's\n // fix — flagged, not silently masked.\n const promptRef = draftPromptRefFor(agent, { promptPrefix: '' });\n const resolvedPrompt = await promptPort.resolve(promptRef);\n const systemContent = applySignature(resolvedPrompt.text, input.agentName ?? undefined);\n const chatMessages: WireChatMessage[] = systemContent\n ? [{ role: 'system', content: systemContent }, ...contextMessages]\n : contextMessages;\n\n const result = await ctx.api.llm.complete({\n messages: chatMessages,\n // H3/I16: the resolved Langfuse prompt's own model config WINS over the\n // agent's fallback modelId — every ported graph node applies this same\n // rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort\n // .resolve` consumer in the repo that dropped it.\n options: { model: resolvedPrompt.config?.model ?? agent.modelId },\n // Link-only (D-LF follow-up, option (b)): this function already resolved\n // its own prompt two lines above via `PromptPort` — `resolve: false`\n // links the completion to it in Langfuse WITHOUT re-triggering the\n // platform's own resolution (no `manifest.prompts[]` gate, no\n // system-message replacement of the `applySignature`-signed message just\n // composed above). `label` is the REAL resolved label — `promptRef\n // .label`, i.e. `agent.promptLabel ?? 'production'`\n // (`functions/records.ts`'s `draftPromptRefFor`) — not a hardcoded\n // 'production', so a staging-labelled agent's traces say so instead of\n // silently attributing to production.\n promptRef: {\n name: resolvedPrompt.name,\n version: resolvedPrompt.version,\n label: promptRef.label,\n resolve: false,\n },\n trace: {\n sessionId: input.gorgiasTicketId ?? undefined,\n metadata: {\n // L2: the agent's own identity — `ctx.api.llm.complete`'s `trace`\n // has no dedicated `userId` field (unlike `graph/ports.ts`'s\n // `CompletionRequest`), only `metadata`. The prompt identity itself\n // no longer needs to travel here — `promptRef` above carries it.\n userId,\n model: agent.modelId,\n ...(input.gorgiasTicketId ? { ticketId: input.gorgiasTicketId } : {}),\n },\n },\n });\n\n const answer = result.text?.trim();\n if (!answer) throw new ctx.NonRetriableError('Provider returned an empty response');\n\n return {\n answer,\n modelId: agent.id,\n langfuse_trace_id: result.traceId ?? null,\n langfuse_observation_id: result.observationId ?? null,\n prompt_name: resolvedPrompt.name,\n prompt_version: resolvedPrompt.version,\n };\n}\n\nasync function resolveMessages(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<WireChatMessage[]> {\n if (input.gorgiasTicketId) {\n // L10: the exported `RawTicketContext` shape (`adapters/index.ts`),\n // not a second inline redeclaration of it. Note the divergence this\n // reader and `toConversation` (`adapters/conversation-mapping.ts`) have\n // on the SAME action's output: this one admits `system` turns\n // (matching the legacy chat route), `toConversation` filters them out —\n // both correct for what each one feeds, neither aware of the other.\n const raw = (await runBuildTicketContext(ctx, input.gorgiasTicketId)) as RawTicketContext;\n // M1: the legacy's shared `messages.length === 0` 400-guard covered\n // BOTH the `input.messages` path and this `gorgiasTicketId` one — this\n // port only guarded the former. A ticket with nothing extractable\n // (internal notes only, an automated-sender thread) must 400 instantly,\n // not pay for an LLM call with a system message and no conversation.\n if (!Array.isArray(raw.messages) || raw.messages.length === 0) {\n throw new ctx.NonRetriableError(`No usable messages extracted for Gorgias ticket ${input.gorgiasTicketId}`);\n }\n return raw.messages.map((m) => toWireChatMessage(m));\n }\n if (Array.isArray(input.messages) && input.messages.length > 0) {\n return input.messages.map((m) => toWireChatMessage(m));\n }\n throw new ctx.NonRetriableError('`messages` must be a non-empty array, or provide `gorgiasTicketId`');\n}\n\n/**\n * L1, PARTIAL — see this module's own doc for what is and is not achievable\n * here. Distinguishes the one genuinely non-retriable Gorgias failure (the\n * ticket does not exist) from everything else (misconfiguration, the\n * provider being down, a timeout) by DUCK-TYPING the error shape\n * `@apotech-os/gorgias-client`'s `ProviderHttpError` carries — `status`/\n * `name` on the caught value — rather than an `instanceof` check: this\n * package has no dependency on `gorgias-client` at all\n * (`dependency-allowlist.ts`; an app cannot import a platform-internal\n * client), so a structural check is the only kind available.\n */\nasync function runBuildTicketContext(ctx: SupportKitHandlerContext, ticketId: string): Promise<unknown> {\n try {\n return await ctx.api.integrations.run('gorgias', 'buildTicketContext', { ticketId });\n } catch (err) {\n if (isGorgiasNotFound(err)) {\n throw new ctx.NonRetriableError(`Gorgias ticket ${ticketId} not found`);\n }\n // Everything else (misconfigured connection, the provider down, a\n // timeout) is NOT retried by throwing `NonRetriableError` — unlike a\n // missing ticket, a transient Gorgias outage may well succeed on the\n // next call. This still surfaces as a generic 500 to the extension: see\n // this module's own doc for why 503/502 are unreachable from here.\n throw err;\n }\n}\n\nfunction isGorgiasNotFound(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false;\n const { status } = err as { status?: unknown };\n return status === 404;\n}\n\nfunction toWireChatMessage(raw: { role?: unknown; content?: unknown }): WireChatMessage {\n const role = raw.role;\n if (role !== 'system' && role !== 'user' && role !== 'assistant') {\n throw new Error(`ext-chat: message role must be \"system\", \"user\" or \"assistant\", got ${JSON.stringify(role)}`);\n }\n return { role, content: typeof raw.content === 'string' ? raw.content : '' };\n}\n\nasync function resolveAgent(ctx: SupportKitHandlerContext, modelId: string | null): Promise<AgentRecord> {\n if (modelId) {\n const record = await getOptional(ctx, 'agent', modelId);\n if (!record) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n return toAgent(record);\n }\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n const record = page.items[0];\n if (!record) throw new ctx.NonRetriableError('No default model configured');\n return toAgent(record);\n}\n","/**\n * `ext-fast-response-check` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * always `phase: 'execute'`, fanned out to every accessible app (§S6: \"au\n * plus un hit attendu — premier hit servi, hits multiples loggés en\n * anomalie\" — that fan-out/first-hit policy is the GATEWAY's, not this\n * function's). Ports legacy `POST /api/fast-response/check`\n * (extension-overview backoffice/src/routes/api.ts:291) — the most\n * defect-prone of the six, ported rule for rule:\n *\n * 1. Look up the `generated-response` row for `ticket_id` with `status:\n * 'ready'`. None → `{available: false}`.\n * 2. TTL: `expiresAt < now` → flip `ready -> expired` (conditional on still\n * being `ready`, S5 `ifMatch`) and return `{available: false}`.\n * 3. Divergence, RECOMPUTED SERVER-SIDE — never from client-supplied\n * values: re-fetch the ticket via S1's `getRawTicket` action and take\n * the snapshot with the kit's own `snapshotConversation`\n * (`adapters/conversation-mapping.ts`, already the symmetric port of the\n * extension's `countableMessages`/divergence rule — reused, not\n * re-derived). Diverged (`currentCount > snappedCount`, or\n * `currentLastAt` present and newer than `snappedLastAt`/absent) → flip\n * `ready -> invalidated` and return `{available: false}`.\n * 4. Gorgias fetch failure, OR a successful-but-unusable payload (no\n * `ticket`, or a `ticket` with no messages — H1 hardening: otherwise\n * `snapshotConversation({})` reads as zero messages, which can only ever\n * look like NO divergence and would serve a stale draft) ⇒ FAIL-CLOSED:\n * `{available: false}`, the row is left `ready`, nothing is written — a\n * transient Gorgias outage must never look like \"the draft was\n * invalidated\".\n * 5. Hit: `servedCount++`, push `{user, at}` onto `servedTo` (capped at 500\n * entries — `servedCount` keeps incrementing past the cap, only the\n * array stops growing) via S5 `ifMatch: {servedCount: <value just read>}`\n * PLUS A RETRY: the read-modify-write of the `servedTo` JSON array is not\n * atomic, so a lost `ifMatch` race (two concurrent `/check` calls on the\n * same ready row) re-reads the row and retries with the fresh count —\n * UNLESS the re-read shows the row is no longer `ready` (another writer\n * genuinely moved it: an expiry/divergence flip, or a send), in which\n * case this is a real miss, exactly the legacy's `race_lost` branch —\n * see `serveHit` below, bounded at `MAX_SERVE_ATTEMPTS`. CASing on\n * `status` here (H2 hardening) would be a no-op guard: this write never\n * changes `status`, so two concurrent hits would both pass an\n * `ifMatch: {status: 'ready'}` unconditionally and one serve record\n * would silently vanish — `servedCount` is the field that actually\n * discriminates concurrent writers.\n *\n * `followup_required` — DECISION (the brief asks for one, explicitly):\n * derived from the record's `verdict.verdict` field via the ported\n * `requiresFollowup` (legacy-faithful: `requiresFollowup(job\n * .evaluation_verdict)`), NOT read off a stored `followupRequired`\n * boolean. Checked before choosing: `records/generated-response.ts`\n * declares `followupRequired` with a `false` default, and grep across this\n * package shows exactly ONE writer — `triage-tick.ts` sets it `false` at\n * CREATION time — and no writer ever updates it once the real verdict is\n * known (`process-response.ts` persists `verdict` on the `ready` row but\n * never touches `followupRequired`). The stored field is therefore\n * effectively dead (always `false`); deriving from `verdict` is both\n * legacy-faithful and the only way to get a correct answer.\n *\n * `last_served_at` — the legacy also stamped this on every hit; the kit's\n * `generated-response` record (§3.4, frozen at T20) has no such field.\n * NOT silently dropped: nothing in this package reads it, and each\n * `servedTo[].at` entry already carries the same information (the most\n * recent entry IS the last-served timestamp) — so the cost is a query that\n * wants \"when was this last served\" needing to read the tail of `servedTo`\n * instead of one scalar field, not a loss of information.\n *\n * SETTINGS VALIDATION: deliberately NOT called. This function reads\n * `expiresAt` off the ROW itself — computed once at generation time from\n * `responseTtlMinutes`, already baked in — never a live settings read; none\n * of `validateSettings`'s three checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) apply to serving an already-generated draft.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { AppApiError, type AppApiRecord, type AppHandler, FieldType, type FunctionDef } from '@apotech-os/app-kit';\nimport { snapshotConversation } from '../adapters/conversation-mapping';\nimport type { RawTicket } from '../guardrails';\nimport { isEvaluationVerdict, requiresFollowup } from '../domain';\nimport { isGeneratedResponseStatus, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID } from './ids';\nimport { toDate } from './pipeline-state';\nimport { toAgent, toCategory, toGeneratedResponse, type GeneratedResponseRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst SERVED_TO_CAP = 500;\nconst MAX_SERVE_ATTEMPTS = 3;\n\nexport interface ExtFastResponseCheckInput {\n ticket_id: string;\n}\n\nexport type ExtFastResponseCheckResult =\n | { available: false }\n | {\n available: true;\n response: string;\n category: { _id: string; name: string } | null;\n agent: { _id: string; name: string; model_id: string } | null;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n generated_at: string;\n followup_required: boolean;\n };\n\nexport function buildExtFastResponseCheckFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-fast-response-check'),\n name: 'ext-fast-response-check',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createExtFastResponseCheckHandler(): AppHandler {\n return (ctx, input) => extFastResponseCheckHandler(ctx as SupportKitHandlerContext, input as unknown as ExtFastResponseCheckInput);\n}\n\nconst NOT_AVAILABLE: ExtFastResponseCheckResult = { available: false };\n\nexport async function extFastResponseCheckHandler(\n ctx: SupportKitHandlerContext,\n input: ExtFastResponseCheckInput,\n): Promise<ExtFastResponseCheckResult> {\n const ticketId = typeof input?.ticket_id === 'string' ? input.ticket_id.trim() : '';\n if (!ticketId) throw new ctx.NonRetriableError('`ticket_id` must be a non-empty string');\n\n const page = await ctx.api.list('generated-response', { filter: { ticketId, status: 'ready' }, limit: 1 });\n const row = page.items[0];\n if (!row) {\n logReason(ctx, ticketId, 'no_ready_job');\n return NOT_AVAILABLE;\n }\n const generatedResponse = toGeneratedResponse(row);\n\n const now = new Date();\n\n const expiresAt = toDate(generatedResponse.expiresAt);\n if (expiresAt && expiresAt.getTime() < now.getTime()) {\n logReason(ctx, ticketId, 'expired');\n await flipStatus(ctx, row.id, ticketId, 'expired');\n return NOT_AVAILABLE;\n }\n\n let rawTicket: RawTicket;\n try {\n const fetched = (await ctx.api.integrations.run('gorgias', 'getRawTicket', { ticketId })) as { ticket?: RawTicket };\n // H1 hardening: a successful-but-unusable payload (no `ticket`, or a\n // `ticket` with no messages) is indistinguishable from a fetch failure\n // for divergence purposes — `snapshotConversation({})` would read as\n // \"0 messages, no last-message date\", which can only ever look like\n // NO divergence and would serve a draft that may already be stale.\n // Fail-closed the same way rule 4 does for a thrown fetch error.\n if (!fetched.ticket || !fetched.ticket.messages || fetched.ticket.messages.length === 0) {\n logReason(ctx, ticketId, 'gorgias_fetch_failed', 'empty or missing ticket.messages');\n return NOT_AVAILABLE;\n }\n rawTicket = fetched.ticket;\n } catch (err) {\n // Fail-closed (rule 4): cannot validate the draft is still fresh, so it\n // is unavailable — but the row itself is left untouched.\n logReason(ctx, ticketId, 'gorgias_fetch_failed', err instanceof Error ? err.message : String(err));\n return NOT_AVAILABLE;\n }\n\n const divergence = checkDivergence(rawTicket, generatedResponse);\n if (divergence.diverged) {\n logReason(ctx, ticketId, `diverged[count(snap=${divergence.snappedCount},now=${divergence.count}),date(snap=${isoOrNull(divergence.snappedLastAt)},now=${isoOrNull(divergence.lastAt)})]`);\n await flipStatus(ctx, row.id, ticketId, 'invalidated');\n return NOT_AVAILABLE;\n }\n\n const envelope = readSupportExtensionEnvelope(ctx);\n // L11: an empty platform user id must fail the WRITE, not silently push\n // `servedTo: [{user: '', at}]` — an anonymous entry indistinguishable\n // from a legitimate serve. `readSupportExtensionEnvelope`'s own doc notes\n // this never happens through the real gateway; this is the last line of\n // defence against a malformed envelope masquerading as a real one.\n if (!envelope.userId) {\n throw new ctx.NonRetriableError('ext-fast-response-check: missing platform user id in the invocation envelope');\n }\n const served = await serveHit(ctx, row, envelope.userId, now);\n if (!served) {\n logReason(ctx, ticketId, 'race_lost');\n return NOT_AVAILABLE;\n }\n const servedResponse = toGeneratedResponse(served);\n logReason(ctx, ticketId, `hit served_count=${servedResponse.servedCount}`);\n if (servedResponse.servedCount > SERVED_TO_CAP) {\n ctx.logger.warn(`ext-fast-response-check: ticket=${ticketId} servedTo capped at ${SERVED_TO_CAP} entries (served_count=${servedResponse.servedCount})`);\n }\n\n return buildAvailableResponse(ctx, servedResponse);\n}\n\nfunction logReason(ctx: SupportKitHandlerContext, ticketId: string, reason: string, detail?: string): void {\n const suffix = detail ? ` detail=${JSON.stringify(detail)}` : '';\n ctx.logger.info(`ext-fast-response-check: ticket=${ticketId} reason=${reason}${suffix}`);\n}\n\nfunction isoOrNull(date: Date | null): string {\n return date ? date.toISOString() : 'null';\n}\n\ninterface DivergenceCheck {\n diverged: boolean;\n count: number;\n lastAt: Date | null;\n snappedCount: number;\n snappedLastAt: Date | null;\n}\n\n/**\n * L3: a SECOND `hasDiverged`, deliberately not unified with `graph/nodes\n * /act.ts`'s own — that one uses `!==` on both count and timestamp (any\n * change, either direction, since a re-send must never fire on a run that\n * has already drifted in EITHER direction); this one is faithful to the\n * legacy's own `POST /api/fast-response/check` rule (`count >`, \"strictly\n * newer\") — a same-or-earlier snapshot is not a divergence for the purpose\n * of serving an already-generated draft. `handle-approval.ts:142-143` reads\n * the same two stored fields by hand a third time, for the same reason\n * `act`'s check does (I8's re-read).\n */\nfunction checkDivergence(rawTicket: RawTicket, generatedResponse: GeneratedResponseRecord): DivergenceCheck {\n const snapshot = snapshotConversation(rawTicket);\n const snappedCount = generatedResponse.generatedMessageCount;\n const snappedLastAt = toDate(generatedResponse.generatedLastMessageAt);\n\n const divergedByCount = snapshot.count > snappedCount;\n const divergedByDate = !!snapshot.lastAt && (!snappedLastAt || snapshot.lastAt.getTime() > snappedLastAt.getTime());\n return { diverged: divergedByCount || divergedByDate, count: snapshot.count, lastAt: snapshot.lastAt, snappedCount, snappedLastAt };\n}\n\n/** `ready -> expired|invalidated`, tolerating a lost race (someone else already moved the row) — the outcome (`{available:false}`) is the same either way. */\nasync function flipStatus(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n status: Extract<GeneratedResponseStatus, 'expired' | 'invalidated'>,\n): Promise<void> {\n await transitionGeneratedResponse(ctx.api, { id, ticketId, from: 'ready', to: status });\n}\n\n/**\n * Rule 5's retry loop (see this module's own doc). Re-reads and retries on\n * a lost `ifMatch` race PROVIDED the row is still `ready` after the\n * re-read; a row that moved off `ready` — INCLUDING one an admin deleted\n * outright (L4: `getOptional`, not `api.get`, so a 404 here reads as the\n * same ordinary miss the legacy's `race_lost` names it, not an app failure\n * `fanOutSettled` would log as an anomaly) — is a genuine miss, returned as\n * `null` without a further retry.\n */\nasync function serveHit(ctx: SupportKitHandlerContext, row: AppApiRecord, userId: string, now: Date): Promise<AppApiRecord | null> {\n let current = row;\n for (let attempt = 0; attempt < MAX_SERVE_ATTEMPTS; attempt++) {\n const currentData = toGeneratedResponse(current);\n const { servedCount, servedTo } = currentData;\n const nextServedTo = servedCount < SERVED_TO_CAP ? [...servedTo, { user: userId, at: now.toISOString() }] : servedTo;\n\n try {\n // H2: CAS on the field this write actually changes (`servedCount`),\n // not `status` — the hit path never moves `status` off `ready`, so an\n // `ifMatch: {status: 'ready'}` guard would let two concurrent hits\n // both pass unconditionally (see this function's own doc, rule 5).\n return await ctx.api.update(\n 'generated-response',\n current.id,\n { servedCount: servedCount + 1, servedTo: nextServedTo },\n { ifMatch: { servedCount } },\n );\n } catch (err) {\n if (!(err instanceof AppApiError) || err.status !== 409) throw err;\n const fresh = await getOptional(ctx, 'generated-response', current.id);\n // L7: the untrusted-JSONB boundary — `isGeneratedResponseStatus`,\n // same guard `isEvaluationVerdict` applies to `verdict` a few lines\n // below, instead of a raw string compare against an unknown value.\n const freshStatus = fresh ? (fresh.data as Record<string, unknown>).status : undefined;\n if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== 'ready') return null;\n current = fresh;\n }\n }\n return null;\n}\n\nasync function buildAvailableResponse(ctx: SupportKitHandlerContext, generatedResponse: GeneratedResponseRecord): Promise<ExtFastResponseCheckResult> {\n const category = await resolveCategoryRef(ctx, generatedResponse.categoryId);\n const agent = await resolveAgentRef(ctx, generatedResponse.agentId);\n // L5: the legacy returned `served.generated_at` verbatim — no fabricated\n // \"now\" fallback. The real record declares `generatedAt` `isNullable:\n // false` (`records/generated-response.ts`), so a row reaching this point\n // without one is corrupted data, not a case to paper over: the extension\n // uses this field to show draft freshness, and silently reporting \"just\n // now\" on a possibly-stale draft is worse than a loud failure.\n const generatedAt = toDate(generatedResponse.generatedAt);\n if (!generatedAt) {\n throw new ctx.NonRetriableError(`generated-response ${generatedResponse.id} is ready but has no generatedAt`);\n }\n const verdictValue = isEvaluationVerdict(generatedResponse.verdict?.verdict) ? generatedResponse.verdict.verdict : null;\n\n return {\n available: true,\n response: generatedResponse.responseText ?? '',\n category,\n agent,\n langfuse_trace_id: generatedResponse.langfuseTraceId,\n langfuse_observation_id: generatedResponse.langfuseObservationId,\n prompt_name: generatedResponse.promptName,\n prompt_version: generatedResponse.promptVersion,\n generated_at: generatedAt.toISOString(),\n followup_required: requiresFollowup(verdictValue),\n };\n}\n\nasync function resolveCategoryRef(ctx: SupportKitHandlerContext, categoryId: string | null): Promise<{ _id: string; name: string } | null> {\n if (!categoryId) return null;\n const record = await getOptional(ctx, 'category', categoryId);\n if (!record) return null;\n const category = toCategory(record);\n return { _id: category.id, name: category.name };\n}\n\nasync function resolveAgentRef(\n ctx: SupportKitHandlerContext,\n agentId: string | null,\n): Promise<{ _id: string; name: string; model_id: string } | null> {\n if (!agentId) return null;\n const record = await getOptional(ctx, 'agent', agentId);\n if (!record) return null;\n const agent = toAgent(record);\n return { _id: agent.id, name: agent.name, model_id: agent.modelId };\n}\n","/**\n * `ext-evaluation` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-\n * routed (§S6). Ports legacy `POST /api/models/:id/evaluation`\n * (extension-overview backoffice/src/routes/api.ts:96). The gateway hands\n * this function `{...body, modelId}` (`SupportExtensionService.evaluation`\n * injects the URL's `:modelId` into the body itself), so `modelId` is\n * always present on `phase: 'execute'`.\n *\n * OWNERSHIP PROBE: `{modelId}`, `modelId` always a real value here (unlike\n * `ext-chat`, there is no \"absent modelId\" branch — the legacy route always\n * has one, from the URL). Claim iff this app owns an `agent` record with\n * that id — a read only, no write/LLM/Gorgias call.\n *\n * EXECUTE: `{satisfied, messages, ticket_url, langfuse_trace_id,\n * langfuse_observation_id, modelId}` → `201` (body ignored by the\n * extension, §5.2). `satisfied` must be a boolean (legacy 400s otherwise).\n * Writes an `evaluation` record with `agentId` = the resolved agent and\n * `supportUserKeyId` = the platform user id read off\n * `ctx.event.supportExtension` (§5.1: \"les records servedTo/évaluations\n * portent l'id utilisateur plateforme\").\n *\n * `ticketUrl` GAP (recorded, not silently routed around; L12 — DECISION\n * made explicitly, not deferred): the extension's request body treats\n * `ticket_url` as optional (legacy: `ticket_url ?? null`), but the T20\n * `evaluation` record (`records/evaluation.ts`) declares `ticketUrl` as\n * `isNullable: false` — no default, no null. Rather than reach back into a\n * frozen T20 record definition (out of this task's scope) or silently\n * attempt an `undefined`/`null` write that would fail the object's own\n * field validation, an absent/non-string `ticket_url` is persisted as an\n * empty string.\n * This is WORSE here than the same gap on `response-comparison.ticketUrl`:\n * `evaluation` has NO `ticketId` field at all (grep `records/evaluation\n * .ts` — `agentId`, `satisfied`, `messages`, `ticketUrl`, the two Langfuse\n * ids, `supportUserKeyId`; nothing else), so `ticketUrl` is this record's\n * ONLY link back to a ticket. `''` is indistinguishable from a genuinely\n * empty URL, and a later backfill has no way to tell \"never sent\" from\n * \"sent empty\". The correct fix is making the field nullable and writing\n * `null` — DECLINED here, deliberately, because it means extending a\n * record definition the spec freezes at T20 (§3.4), which is a call for\n * whoever owns that record, not a T24 function. Flagged for whoever owns\n * `records/evaluation.ts` next, with the concrete cost spelled out above\n * rather than left implicit.\n *\n * LANGFUSE SCORE: when `langfuse_trace_id` is a non-empty string, writes a\n * `user-feedback` BOOLEAN score (S4) with the legacy's deterministic id\n * `user-feedback-<traceId>` (idempotent — toggling 👍/👎 updates the same\n * score instead of creating duplicates). `comment` folds in what the\n * legacy's dataset-store `metadata` carried (`model`, `ticket_url`) — S4's\n * `ctx.api.langfuse.scores.create` has no generic `metadata` field on the\n * platform surface (`CreateLangfuseScoreInput`), only `comment`. The\n * platform user's NAME is not available off `ctx.event` (only the user\n * id), so the comment uses the id instead of the legacy's `req.user.name`.\n * Both deviations are platform-surface limits, not this function's choice.\n * The score write is wrapped and its failure SWALLOWED — legacy is\n * explicit that this block is non-fatal and the 201 is guaranteed.\n *\n * SETTINGS VALIDATION: deliberately NOT called — writing an evaluation and\n * an optional score touches none of `validateSettings`'s three checked\n * fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_EVALUATION_INPUT_MESSAGES_UID,\n EXT_EVALUATION_INPUT_MODEL_ID_UID,\n EXT_EVALUATION_INPUT_SATISFIED_UID,\n EXT_EVALUATION_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { toAgent } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nexport interface ExtEvaluationInput {\n modelId: string;\n satisfied?: unknown;\n messages?: Array<{ role: string; content: string }> | null;\n ticket_url?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n}\n\nexport interface ExtEvaluationResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtEvaluationFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-evaluation'),\n name: 'ext-evaluation',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n { universalIdentifier: EXT_EVALUATION_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: EXT_EVALUATION_INPUT_SATISFIED_UID, name: 'satisfied', type: FieldType.BOOLEAN, label: 'Satisfied', isNullable: false },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtEvaluationHandler(): AppHandler {\n return (ctx, input) => extEvaluationHandler(ctx as SupportKitHandlerContext, input as unknown as ExtEvaluationInput);\n}\n\nexport async function extEvaluationHandler(\n ctx: SupportKitHandlerContext,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return ownsAgent(ctx, input?.modelId ?? null);\n return executeEvaluation(ctx, envelope.userId, input);\n}\n\nasync function executeEvaluation(\n ctx: SupportKitHandlerContext,\n userId: string,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult> {\n if (typeof input.satisfied !== 'boolean') {\n throw new ctx.NonRetriableError('`satisfied` is a required boolean');\n }\n // L11: an empty platform user id must fail the WRITE — §5.1 requires this\n // record to carry it, and silently writing `supportUserKeyId: null`\n // drops that requirement instead of refusing.\n if (!userId) {\n throw new ctx.NonRetriableError('ext-evaluation: missing platform user id in the invocation envelope');\n }\n const modelId = input.modelId;\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n const agentRecord = await getOptional(ctx, 'agent', modelId);\n if (!agentRecord) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n const agent = toAgent(agentRecord);\n\n const satisfied = input.satisfied;\n const messages = Array.isArray(input.messages) ? input.messages : [];\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`,\n // so an absent/non-string value is persisted as an empty string, not null.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const traceId = typeof input.langfuse_trace_id === 'string' && input.langfuse_trace_id.length > 0 ? input.langfuse_trace_id : null;\n const observationId =\n typeof input.langfuse_observation_id === 'string' && input.langfuse_observation_id.length > 0\n ? input.langfuse_observation_id\n : undefined;\n\n const created = await ctx.api.create('evaluation', {\n agentId: agent.id,\n satisfied,\n messages,\n ticketUrl,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n // Non-empty: guarded above (L11).\n supportUserKeyId: userId,\n });\n\n if (traceId) {\n try {\n await ctx.api.langfuse.scores.create({\n id: `user-feedback-${traceId}`,\n traceId,\n observationId,\n name: 'user-feedback',\n value: satisfied,\n dataType: 'BOOLEAN',\n comment: `Thumbs ${satisfied ? 'up' : 'down'} from ${userId || 'agent'} (model: ${agent.name}, ticket_url: ${ticketUrl || 'none'})`,\n });\n } catch (err) {\n // Non-fatal — legacy is explicit that the 201 is guaranteed regardless.\n ctx.logger.warn(`ext-evaluation: user-feedback score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return { ok: true, id: created.id };\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 * `ext-response-comparison` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * ownership-routed (§S6). Ports legacy `POST /api/response-comparisons`\n * (extension-overview backoffice/src/routes/api.ts:404).\n *\n * The gateway already short-circuits `last_message_generated == null` to a\n * `204` BEFORE ever invoking any app, and maps a `null` return from this\n * function to `204` too (`SupportExtensionController.responseComparison`).\n * This handler keeps its OWN guard anyway (per this migration's explicit\n * instruction) — belt and braces, and it is exercised directly by this\n * file's own tests, which do not go through the gateway.\n *\n * OWNERSHIP PROBE (§S6): `model_config_id` non-empty → probe payload\n * `{model_config_id}`, claim iff this app owns that `agent` record.\n * Otherwise → probe payload `{ticket_id, ticket_url}` (§S6: \"sinon fan-out\n * sur la propriété du ticket (`triage-decision`)\") — claim iff this app has\n * a `triage-decision` row for that `ticket_id` (the ticket was triaged by\n * THIS app, i.e. it belongs to this audience). `ticket_url` plays no part\n * in the ownership check (the legacy never used it for anything but\n * display either); it only reaches the WRITE below.\n *\n * EXECUTE: `message_actual_sent` missing → 400-equivalent (legacy 400s);\n * `last_message_generated` null → the guard above. Otherwise writes a\n * `response-comparison` record (`generatedText`/`sentText`/`capturedAt`\n * plus the frozen body's other fields, and `diff` — `response-comparison-\n * diff.ts`'s `computeWordDiff`, \"computed at write time\" per §3.4), then\n * attempts the Langfuse capture.\n *\n * `ticketUrl` GAP (L12 — DECISION made explicitly, not deferred) — the SAME\n * one `ext-evaluation.ts` documents for `evaluation.ticketUrl`: the T20\n * `response-comparison` record declares `ticketUrl` `isNullable: false`,\n * but the extension's own contract treats it as optional. An absent/\n * non-string value is persisted as an empty string, not `null`. Unlike\n * `evaluation`, this record DOES have its own `ticketId` field, so `''`\n * here is not the only link back to a ticket — a strictly smaller gap.\n * Making `ticketUrl` nullable and writing `null` is still the correct fix;\n * DECLINED here for the same reason as `ext-evaluation.ts`: it means\n * extending a T20-frozen record definition (§3.4), a call for whoever owns\n * `records/response-comparison.ts`, not this function.\n *\n * LANGFUSE CAPTURE — gates, decided explicitly: legacy gated on THREE\n * conditions — `CAPTURE_CORRECTIONS_TO_LANGFUSE === 'true'` (an env flag),\n * `message_actual_sent !== last_message_generated` (`textChanged`), and a\n * non-empty trace id. The kit has NO env access (§3.1) and the migration\n * spec §5.2 does not mention this flag at all, so it is DROPPED — the\n * remaining two gates stay: `textChanged` (an unedited reply is not a\n * correction and would poison the `cs-replies-corrections` dataset with\n * noise) and a non-empty trace id (nothing to link the correction back\n * to). Practical effect: this kit ALWAYS captures a genuine edit when a\n * trace id is present, where the legacy required an operator to also\n * enable a deployment flag — a deliberate widening, not an oversight.\n *\n * Dataset item id: the legacy's own deterministic\n * `<traceId>:<observationId>` (or `<traceId>` alone with no observation).\n * SCORE id: the legacy's `createCorrectionScore` had NONE (Langfuse\n * auto-assigns one on every call) — but S4's `ctx.api.langfuse.scores\n * .create` requires an `id` (`CreateLangfuseScoreInput.id`, non-optional).\n * This function reuses the SAME deterministic dataset-item id for the\n * score, which is required by the platform surface — NOT, despite the\n * tempting name, a general idempotency guarantee (H5/L14 correction of an\n * earlier overclaim in this doc):\n * - Langfuse keys a score on `(id, name, toDate(timestamp))`, and\n * `POST /api/public/scores` has no caller-supplied timestamp — a retry\n * that crosses a UTC day boundary from the original call creates a\n * SECOND score under the same id (`AppLangfuseService.createScore`'s\n * own doc, `apps/api/src/platform-data/app-langfuse.service.ts`).\n * - Two DIFFERENT edits on the same trace within the same day reuse this\n * same id and the SECOND CORRECTION score OVERWRITES the first — the\n * legacy minted a distinct score object per edit, so this is a real\n * narrowing, not a wash.\n * Same for the dataset item: a deterministic id genuinely IS a concurrency\n * safety net for the CONCURRENT case (two callers racing on the identical\n * id — Langfuse upserts by id, so the race has a defined winner instead of\n * two rows). What it is NOT is protection for the SEQUENTIAL case: reusing\n * that same deterministic id also means a SECOND, LATER correction on the\n * same generation (an agent edits and\n * sends, then the extension re-posts the same generation on a retry, or a\n * client retries after a lost 201) silently REPLACES `expectedOutput` with\n * the newer edit — last-write-wins, not accumulated history. The legacy\n * guarded exactly this (api.ts:490-497: skip the write when a\n * `ResponseComparison` with this `langfuse_observation_id` already has a\n * `dataset_item_created_at`); this port has no such field to guard on (the\n * T20-frozen `response-comparison` record declares none) and the guard was\n * dropped, not ported. DECIDED, not silently accepted: adding\n * `datasetItemCreatedAt` would mean extending a T20-frozen record\n * definition, out of this task's scope — documenting the real behaviour\n * here (drift toward the latest edit, not a hard guarantee) is the\n * alternative the review offered, and is what this paragraph now does.\n *\n * SCORE VALUE LENGTH — UNVERIFIED, flagged rather than guessed: `value:\n * JSON.stringify(expectedOutput)` embeds the full sent reply. If Langfuse\n * caps score values at some length (a commonly-cited limit for certain\n * value/comment fields is 500 characters, but this could not be confirmed\n * from code in this repo), a real support reply could exceed it. The write\n * is swallowed non-fatally below, so an over-length value would 400 here\n * silently — the feature would look like it works while writing nothing.\n * Treat this as a pre-ship manual probe (write a >500-char correction\n * against a real/staging Langfuse project and confirm the score lands),\n * not a guarantee this doc makes.\n *\n * `traced_input` — read defensively off the raw payload for the dataset\n * item's `input`, falling back to `conversation_messages` when absent\n * (legacy's own fallback rule) — NOT part of §5.2's frozen field table, so\n * it is not declared in this function's `input` FieldDef[] (an\n * undeclared/extra key reaches the handler unstripped; see\n * `app-input-validation.ts`'s zod-strip behaviour), but the extension may\n * still send it and its value should not be silently discarded when it\n * does.\n *\n * Both Langfuse writes (dataset item, score) are wrapped and their failure\n * SWALLOWED — legacy is explicit that this block is non-fatal.\n *\n * SETTINGS VALIDATION: deliberately NOT called — none of `validateSettings`'s\n * three checked fields apply to writing a comparison/capturing a\n * correction.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { computeWordDiff } from './response-comparison-diff';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst CORRECTIONS_DATASET = 'cs-replies-corrections';\n\nexport interface ExtResponseComparisonInput {\n last_message_generated?: string | null;\n message_actual_sent?: string;\n ticket_id?: string | null;\n ticket_url?: string | null;\n model_config_id?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n prompt_name?: string | null;\n prompt_version?: number | null;\n conversation_messages?: unknown[] | null;\n /** Not part of §5.2's frozen field table — see this module's own doc. */\n traced_input?: unknown[] | null;\n}\n\nexport interface ExtResponseComparisonResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtResponseComparisonFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-response-comparison'),\n name: 'ext-response-comparison',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n name: 'last_message_generated',\n type: FieldType.TEXT,\n label: 'Last message generated',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n name: 'message_actual_sent',\n type: FieldType.TEXT,\n label: 'Message actually sent',\n isNullable: false,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n name: 'model_config_id',\n type: FieldType.TEXT,\n label: 'Model config id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n name: 'prompt_name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n name: 'prompt_version',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n name: 'conversation_messages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtResponseComparisonHandler(): AppHandler {\n return (ctx, input) => extResponseComparisonHandler(ctx as SupportKitHandlerContext, (input as ExtResponseComparisonInput) ?? {});\n}\n\nexport async function extResponseComparisonHandler(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeResponseComparisonOwnership(ctx, input);\n return executeResponseComparison(ctx, input);\n}\n\nasync function probeResponseComparisonOwnership(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ProbeClaim | null> {\n const modelConfigId = nonEmptyString(input.model_config_id);\n if (modelConfigId) {\n const claim = await ownsAgent(ctx, modelConfigId);\n if (claim) return claim;\n // M3: a dangling model_config_id (the agent was archived/deleted since\n // the draft that produced this correction) used to disclaim outright —\n // 204, the correction silently lost, with nothing to distinguish \"no\n // owner\" from \"we lost it\". Fall through to ticket ownership instead of\n // returning null immediately: the ticket itself still routes to the app\n // that triaged it, which is the better answer than losing the human\n // correction the whole cs-replies-corrections loop is built on.\n }\n\n const ticketId = nonEmptyString(input.ticket_id);\n if (!ticketId) return null;\n const page = await ctx.api.list('triage-decision', { filter: { ticketId }, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeResponseComparison(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | null> {\n if (!input.message_actual_sent) {\n throw new ctx.NonRetriableError('message_actual_sent is required');\n }\n if (!input.last_message_generated) {\n // M2: falsy, not `== null` — legacy tests `if (!last_message_generated)\n // return 204`, so an empty string must 204 too. `== null` let `''`\n // through and wrote a response-comparison with generatedText: '', a\n // trivially 100%-insert diff, and (with a trace id) a dataset item +\n // CORRECTION score teaching cs-replies-corrections that the model wrote\n // nothing and the human wrote the whole reply — dataset poisoning.\n return null; // -> 204, no write (own guard — see this module's doc)\n }\n\n const generatedText = input.last_message_generated;\n const sentText = input.message_actual_sent;\n const ticketId = nonEmptyString(input.ticket_id);\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const modelConfigId = nonEmptyString(input.model_config_id);\n const traceId = nonEmptyString(input.langfuse_trace_id);\n const observationId = nonEmptyString(input.langfuse_observation_id) ?? undefined;\n const promptName = typeof input.prompt_name === 'string' ? input.prompt_name : null;\n const promptVersion = typeof input.prompt_version === 'number' ? input.prompt_version : null;\n const conversationMessages = Array.isArray(input.conversation_messages) ? input.conversation_messages : [];\n\n const created = await ctx.api.create('response-comparison', {\n generatedText,\n sentText,\n capturedAt: new Date().toISOString(),\n ticketId,\n ticketUrl,\n agentId: modelConfigId,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n promptName,\n promptVersion,\n conversationMessages,\n diff: computeWordDiff(generatedText, sentText),\n });\n\n await captureCorrectionToLangfuse(ctx, {\n generatedText,\n sentText,\n ticketId,\n traceId,\n observationId,\n promptName,\n promptVersion,\n conversationMessages,\n tracedInput: Array.isArray(input.traced_input) ? input.traced_input : null,\n });\n\n return { ok: true, id: created.id };\n}\n\ninterface CorrectionCaptureParams {\n generatedText: string;\n sentText: string;\n ticketId: string | null;\n traceId: string | null;\n observationId: string | undefined;\n promptName: string | null;\n promptVersion: number | null;\n conversationMessages: unknown[];\n tracedInput: unknown[] | null;\n}\n\nasync function captureCorrectionToLangfuse(ctx: SupportKitHandlerContext, params: CorrectionCaptureParams): Promise<void> {\n const textChanged = params.sentText !== params.generatedText;\n if (!textChanged || !params.traceId) return;\n\n const itemId = params.observationId ? `${params.traceId}:${params.observationId}` : params.traceId;\n const expectedOutput = { role: 'assistant', content: params.sentText, refusal: null, annotations: [] as unknown[] };\n const datasetInput = params.tracedInput && params.tracedInput.length > 0 ? params.tracedInput : params.conversationMessages;\n\n try {\n await ctx.api.langfuse.datasets.createItem({\n dataset: CORRECTIONS_DATASET,\n id: itemId,\n input: datasetInput,\n expectedOutput,\n sourceTraceId: params.traceId,\n sourceObservationId: params.observationId,\n metadata: {\n prompt_name: params.promptName,\n prompt_version: params.promptVersion,\n ticket_id: params.ticketId,\n edited: true,\n },\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: dataset item write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n\n try {\n // M5: deliberately trace-level — NO `observationId`. Legacy's own\n // `createCorrectionScore` call passed none either (its doc labels this\n // \"Native trace-level CORRECTION score — renders as the 'Corrected\n // Output' on the trace itself\"); passing one here would move the panel\n // off the trace page. `CreateLangfuseScoreInput` has no generic\n // `metadata` field on the platform surface (only `comment`), so\n // prompt_name/prompt_version — the axis S7's quality loop reads\n // corrections along — fold into `comment` instead, the same way\n // `ext-evaluation.ts` folds its own score metadata.\n await ctx.api.langfuse.scores.create({\n id: itemId,\n traceId: params.traceId,\n name: 'output',\n value: JSON.stringify(expectedOutput),\n dataType: 'CORRECTION',\n comment: `Human correction from ticket ${params.ticketId ?? 'unknown'} (prompt: ${params.promptName ?? 'unknown'}, version: ${params.promptVersion ?? 'unknown'})`,\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: correction score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n","/**\n * Page/settingsPage manifest fragments (spec §3.8) — the T26 counterpart of\n * `functions/config.ts`'s `FUNCTION_IDENTIFIER_KEYS`/`identifierFor`.\n *\n * Page `universalIdentifier`s come from `config.identifiers`, exactly like\n * function uids — NOT from the T25 `deriveUid`/`scopeRecordToApp` mechanism\n * `records/` uses. That mechanism exists because a RECORD's sub-ids (fields,\n * indexes) are numerous and entirely kit-owned, with no natural per-app\n * literal for a consuming app to author; deriving them from `(slug, a kit\n * constant)` is the only way to keep them both stable and disjoint across\n * apps. A page has exactly one id, no sub-ids, and `FUNCTION_IDENTIFIER_KEYS`\n * already established the pattern for exactly this shape: the CONSUMING\n * APP's own config supplies a literal, platform-wide-unique uuid per key —\n * the same discipline `docs/app-template/src/universal-identifiers.ts`\n * documents for every other manifest id an app authors directly.\n *\n * CORRECTION (T26 rework — the prior pass's own justification here was\n * false, and is fixed rather than just removed so the actual mechanism is\n * on record): `AppEntityType.PAGE` rows do land in the same `AppEntity`\n * table as records' OBJECT/FIELD/INDEX rows\n * (`apps/api/src/platform-data/app-entities.ts`), and\n * `AppEntity.universalIdentifier` IS `@unique` platform-wide\n * (`schema.prisma`) — but PAGE, like FUNCTION/VIEW/INDEX/NAV_ITEM, is\n * NAMESPACED before that constraint ever sees it: `buildEntities` computes\n * `deterministicUid('PAGE:<manifest uid>:<page uid>')`\n * (`app-entities.ts:172-175`), not the raw `page.universalIdentifier`\n * literal. Two apps publishing the IDENTICAL local page uid produce two\n * DIFFERENT `deterministicUid` hashes (their own manifest uids differ), so\n * they do not collide — a page id does NOT \"collide across apps exactly\n * like a record id would\". Only OBJECT (`app-entities.ts:84`) and FIELD\n * (`:101`, and `:205` for extension fields) write the raw literal straight\n * through — which is precisely why T25's `scopeRecordToApp` existed for\n * records and is NOT needed here.\n *\n * The mechanism below (config-supplied literal, mirroring\n * `FUNCTION_IDENTIFIER_KEYS`) is still the right choice — consistency with\n * the pattern T22/T23 already established for exactly this shape (one id,\n * no sub-ids, no natural per-app literal to derive from) — it is simply not\n * required by a collision risk that does not exist for this entity type.\n */\n\n/**\n * Stable keys `pageIdentifierFor` looks up `config.identifiers` by — the\n * four phase-2 pages (T26), the settingsPage (§3.8's SettingsPage row),\n * T27 part A's three phase-3 pages (`DashboardPage`, `TicketsPage`,\n * `CorrectionsPage`), part B's `GraphCanvasPage`/`SharedPromptsPage`/\n * `TestPage`, and `QualityPage` — the quality loop, moved here out of the\n * platform's own top-bar section.\n *\n * `reglages-page` is the odd one out: it needs its own id NOT because it is a\n * distinct screen — it mounts the very same `SettingsPage` component — but\n * because a `pages[]` entry and `settingsPage` are two manifest rows, and the\n * schema refuses a shared `universalIdentifier` between them\n * (`app-kit/src/contracts.ts`, `settingsPage.universalIdentifier collides`).\n */\nexport const PAGE_IDENTIFIER_KEYS = [\n 'agents-page',\n 'categories-page',\n 'settings-page',\n 'reglages-page',\n 'dashboard-page',\n 'tickets-page',\n 'graph-canvas-page',\n 'shared-prompts-page',\n 'test-page',\n 'quality-page',\n] as const;\n\nexport type PageIdentifierKey = (typeof PAGE_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitPageConfig {\n /** Same map `functions/config.ts`'s `identifierFor` reads — one entry per `PAGE_IDENTIFIER_KEYS`, alongside the function ones. */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry — mirrors `functions/config.ts`'s `identifierFor` exactly. */\nexport function pageIdentifierFor(config: SupportKitPageConfig, key: PageIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportPipelineConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit page needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * `buildSupportPipeline` (spec §3.2) — the single assembly point that turns\n * a consuming app's own config into every manifest fragment + handler this\n * kit provides. An audience app spreads the result into `defineApp({\n * manifest: {...baseManifest, ...kit-fragments}, handlers: kit.handlers })`.\n *\n * T25 is assembly, not invention: every fragment below is built from pieces\n * T20-T24 already shipped (`records/`, `functions/`, `settings/`,\n * `prompts/slots`) — this module's own job is wiring `config` through to\n * each of them consistently, plus `mergeRole`, the one piece with no prior\n * owner.\n */\nimport type {\n AppHandler,\n AppRole,\n AppSettings,\n FunctionDef,\n NavItem,\n PageDef,\n PromptDef,\n SettingsPage,\n} from '@apotech-os/app-kit';\nimport {\n FUNCTION_IDENTIFIER_KEYS,\n type FunctionIdentifierKey,\n type SupportKitFunctionConfig,\n} from './functions/config';\nimport {\n buildTriageTickFunctionDef,\n createTriageTickHandler,\n buildSweepFunctionDef,\n createSweepHandler,\n buildHandleApprovalFunctionDef,\n createHandleApprovalHandler,\n buildRunTriageNowFunctionDef,\n createRunTriageNowHandler,\n buildRunTriageBatchFunctionDef,\n createRunTriageBatchHandler,\n TRIAGE_RUN_REQUESTED_EVENT,\n buildInvalidateResponseFunctionDef,\n createInvalidateResponseHandler,\n buildGetTicketConversationFunctionDef,\n buildPreviewTriageFunctionDef,\n createGetTicketConversationHandler,\n createPreviewTriageHandler,\n buildGraphDryRunFunctionDef,\n createGraphDryRunHandler,\n buildTestAgentsFunctionDef,\n createTestAgentsHandler,\n buildSuggestPromptFunctionDef,\n createSuggestPromptHandler,\n buildListGorgiasViewsFunctionDef,\n createListGorgiasViewsHandler,\n buildCreateAgentFunctionDef,\n createCreateAgentHandler,\n buildSetDefaultAgentFunctionDef,\n createSetDefaultAgentHandler,\n buildCreateSharedPromptVersionFunctionDef,\n createCreateSharedPromptVersionHandler,\n buildSyncAgentPromptSnapshotFunctionDef,\n createSyncAgentPromptSnapshotHandler,\n buildExtModelsFunctionDef,\n createExtModelsHandler,\n buildExtCategoriesFunctionDef,\n createExtCategoriesHandler,\n buildExtChatFunctionDef,\n createExtChatHandler,\n buildExtFastResponseCheckFunctionDef,\n createExtFastResponseCheckHandler,\n buildExtEvaluationFunctionDef,\n createExtEvaluationHandler,\n buildExtResponseComparisonFunctionDef,\n createExtResponseComparisonHandler,\n} from './functions';\nimport { buildSupportKitRecords, targetRefFor, type RecordDef } from './records';\nimport { SUPPORT_KIT_SETTINGS_FIELDS } from './settings';\nimport type { PromptNameConfig } from './prompts/slots';\nimport { pageIdentifierFor } from './pages/manifest';\n\nexport interface SupportPipelineConfig extends SupportKitFunctionConfig {\n /** Human label shown in the platform's app picker, e.g. 'Expérience client'. */\n displayName: string;\n /**\n * §3.2's own sketch names this field, but has no consumer yet (L1, T25\n * review): `navigation` (this fragment's own `NavItem[]`) is always `[]`\n * today — T26/T27 own the kit's pages/nav (§3.8's phase-2/phase-3), and\n * with it, presumably, grouping those nav items under this section. A\n * caller may set it now for forward compatibility; nothing reads it yet.\n */\n navigationSection?: string;\n /**\n * §3.2's full `config.defaults` shape (`{channel?, prompts?}`), widening\n * `SupportKitFunctionConfig`'s own `defaults` (`{prompts?}` only) with\n * `channel` — `prompts`' shape is NOT restated here (L2, T25 review): it\n * is `PromptNameConfig['defaults']`'s own type, `prompts/slots.ts`'s\n * `PromptFallbackSlot`, referenced rather than copied, so this\n * declaration cannot silently narrow back to the wrong key set if that\n * one changes.\n *\n * `defaults.prompts` is wired to its real consumers: `buildPromptsTable`\n * (triage/escalate/evaluate's `PromptRef.fallback`) and\n * `suggest-prompt`/`run-diff-analysis`'s own meta-prompt fallback.\n *\n * `defaults.channel` (DECISION 3, T25 — see the migration progress\n * journal's T25 entry) is accepted here for fidelity to the spec's own\n * sketch but has NO real consumer today: `settings/fields.ts` declares no\n * field named `channel`, and the nearest candidate, `whatsappMode`\n * (`escalate_only|draft_only|auto_reply`), has an incompatible value\n * domain from `'email'|'whatsapp'|'both'` — a mechanical seed would\n * corrupt it, not configure it. Wiring this for real means either adding\n * a settings field (§3.6 is T20-frozen; out of scope here) or picking an\n * arbitrary channel→whatsappMode mapping, both judgment calls beyond\n * assembly. Flagged for the spec owner, not routed around silently.\n */\n defaults?: PromptNameConfig['defaults'] & {\n channel?: 'email' | 'whatsapp' | 'both';\n };\n}\n\n/** `provider`/`action` pair. 4.0.0 — plus aucun manifest ne le porte ; gardé\n * pour la garde de dérive qui re-dérive les appels `ctx.api.integrations.run`\n * du code source (cf. `SUPPORT_KIT_GORGIAS_ACTIONS`). */\nexport interface ActionRef {\n provider: string;\n action: string;\n}\n\n/** Un bloc de `manifest.integrations[]` — provider + scopes de ressource. */\nexport interface IntegrationRef {\n provider: string;\n scopes: string[];\n}\n\nexport interface SupportPipelineFragments {\n records: RecordDef[];\n functions: FunctionDef[];\n /**\n * The app custom events the kit's own functions emit — spread into\n * `manifest.emits`. NOT optional in practice (B5): `run-triage-batch`\n * declares `trigger: {type:'event', name: TRIAGE_RUN_REQUESTED_EVENT}`,\n * and the platform refuses to sync a manifest whose event trigger names\n * an event the app does not declare\n * (`app-manifest-constraints.ts`'s `validateAppFunctionConstraints`), so\n * a consuming app that spreads `functions` must spread this too.\n */\n emits: string[];\n settings: AppSettings;\n prompts: PromptDef[];\n pages: PageDef[];\n navigation: NavItem[];\n /**\n * §3.8's SettingsPage row — the manifest's `settingsPage`, not a\n * `pages[]` entry (`AppManifestSchema`'s own refinements require it:\n * distinct `entry` from every page, no collision with the bundle the CLI\n * emits for a page `path`, distinct `universalIdentifier`). Not in §3.2's\n * own fragment sketch (T25's `pages`/`navigation` sketch predates T26) —\n * added here because a consuming app has no other way to spread it into\n * its manifest.\n */\n settingsPage: SettingsPage;\n /**\n * 4.0.0 — remplace le fragment `actions`. Les scopes de RESSOURCE dont les\n * adaptateurs du kit ont besoin chez Gorgias, à spread dans\n * `manifest.integrations`.\n */\n integrations: IntegrationRef[];\n /**\n * `'NO_ACCESS'` (H2, T25 review): with no `defaultRole`, the platform\n * grants every platform member `VIEWER` on install\n * (`app-lifecycle.service.ts:1211`) — a `pro-sante` clinician would read\n * `experience-client`'s `generated-response` rows (customer email bodies,\n * drafted replies) by default. Exposed as a named fragment, not baked\n * silently into a spread, so a consuming app can still override it\n * explicitly (`defaultRole: kit.defaultRole` in the common case, or a\n * different value if that app has a real reason to).\n */\n defaultRole: 'NO_ACCESS';\n handlers: Record<string, AppHandler>;\n mergeRole(role: AppRole): AppRole;\n /**\n * 4.0.0 — remplace `mergeActions`. Fond les scopes du kit dans les\n * `integrations[]` de l'app appelante, en dédupliquant par provider et en\n * unionnant les scopes : `integrations: kit.mergeIntegrations(ownIntegrations)`.\n *\n * L'union est la bonne opération, pas le remplacement : une app qui déclare\n * déjà `read_tickets` pour son propre usage ne doit pas le perdre parce que le\n * kit déclare `write_tickets`. Et la déclaration reste une DEMANDE — c'est un\n * admin qui accorde, à l'install.\n */\n mergeIntegrations(integrations: IntegrationRef[]): IntegrationRef[];\n}\n\n/**\n * The ten Gorgias connector actions the kit's adapters/functions actually\n * call — verified by grepping `ctx.api.integrations.run('gorgias', …)`\n * across `src/` (see `pipeline.spec.ts`'s own self-checking test, which\n * re-derives this set from the source tree so it cannot silently drift as\n * new call sites are added).\n */\nexport const SUPPORT_KIT_GORGIAS_ACTIONS = [\n 'applyTags',\n 'buildTicketContext',\n 'fetchTicketsFromView',\n 'getRawTicket',\n 'getTicketUrlBase',\n 'getTicketWithContext',\n 'listViews',\n 'postWhatsappNote',\n 'renameTicket',\n 'replyEmail',\n] as const;\n\n/**\n * §3.2: `mergeRole` adds these capabilities. `'langfuse'` is load-bearing —\n * `adapters/api.ts`'s `ctx.api.langfuse` 403s without it (T24).\n *\n * 4.0.0 — `'llm'` joins the list: the LLM left the action system entirely, so\n * what used to be `role.actions: [{ provider: 'llm', action: 'complete' }]` is\n * now a capability. Forgetting it would 403 every `ctx.api.llm.complete` the\n * kit's own triage functions make.\n */\nexport const SUPPORT_KIT_CAPABILITIES = [\n 'runs',\n 'inbox',\n 'approvals',\n 'prompts',\n 'langfuse',\n 'llm',\n] as const;\n\n/**\n * The kit's whole action surface — `SUPPORT_KIT_GORGIAS_ACTIONS` plus\n * `llm.complete` — as `ActionRef`s. One derivation, reused by\n * `buildSupportPipeline`'s own `actions` fragment, `mergeRole`, and\n * `mergeActions` (M5, T25 review): before this constant existed, the same\n * `[...SUPPORT_KIT_GORGIAS_ACTIONS.map(...), {provider:'llm',action:'complete'}]`\n * expression was written out twice, free to drift apart silently.\n */\nexport const SUPPORT_KIT_ACTIONS: ActionRef[] = [\n ...SUPPORT_KIT_GORGIAS_ACTIONS.map((action) => ({ provider: 'gorgias', action })),\n { provider: 'llm', action: 'complete' },\n];\n\n/**\n * 4.0.0 — les SCOPES Gorgias que les dix actions ci-dessus exigent, réunis.\n *\n * Écrit à la main plutôt que dérivé de `gorgias-client` : le support-kit est\n * publié sur npm et consommé par des dépôts d'app autonomes, à qui on ne va pas\n * imposer une dépendance sur un paquet de connecteur privé pour lire une liste\n * de six chaînes. La garde de dérive reste `pipeline.spec.ts`, qui compare ce\n * jeu à celui des actions effectivement appelées dans `src/`.\n *\n * `read_tags` n'est pas listé : `write_tags` l'implique côté plateforme\n * (`expandScopes`), et le répéter ici ferait croire à deux demandes distinctes\n * dans la modale de consentement.\n */\nexport const SUPPORT_KIT_GORGIAS_SCOPES = [\n 'read_customers',\n 'read_tickets',\n 'read_views',\n 'write_tags',\n 'write_tickets',\n] as const;\n\n/** Le fragment `integrations[]` du kit — un seul provider, Gorgias. */\nexport const SUPPORT_KIT_INTEGRATIONS: IntegrationRef[] = [\n { provider: 'gorgias', scopes: [...SUPPORT_KIT_GORGIAS_SCOPES] },\n];\n\n/**\n * §3.2's `emits` fragment — one entry, the manual-triage hand-off\n * (`functions/run-triage-now.ts`'s own doc explains why that hand-off\n * exists at all).\n */\nexport const SUPPORT_KIT_EMITS: string[] = [TRIAGE_RUN_REQUESTED_EVENT];\n\nconst FUNCTION_ASSEMBLY: ReadonlyArray<{\n key: FunctionIdentifierKey;\n build: (config: SupportKitFunctionConfig) => FunctionDef;\n createHandler: (config: SupportKitFunctionConfig) => AppHandler;\n}> = [\n { key: 'triage-tick', build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },\n { key: 'sweep', build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },\n {\n key: 'handle-approval',\n build: buildHandleApprovalFunctionDef,\n createHandler: createHandleApprovalHandler,\n },\n {\n key: 'run-triage-now',\n build: buildRunTriageNowFunctionDef,\n createHandler: createRunTriageNowHandler,\n },\n {\n key: 'run-triage-batch',\n build: buildRunTriageBatchFunctionDef,\n createHandler: createRunTriageBatchHandler,\n },\n {\n key: 'invalidate-response',\n build: buildInvalidateResponseFunctionDef,\n createHandler: () => createInvalidateResponseHandler(),\n },\n {\n key: 'preview-triage',\n build: buildPreviewTriageFunctionDef,\n createHandler: createPreviewTriageHandler,\n },\n {\n key: 'get-ticket-conversation',\n build: buildGetTicketConversationFunctionDef,\n createHandler: () => createGetTicketConversationHandler(),\n },\n {\n key: 'graph-dry-run',\n build: buildGraphDryRunFunctionDef,\n createHandler: createGraphDryRunHandler,\n },\n { key: 'test-agents', build: buildTestAgentsFunctionDef, createHandler: createTestAgentsHandler },\n {\n key: 'suggest-prompt',\n build: buildSuggestPromptFunctionDef,\n createHandler: createSuggestPromptHandler,\n },\n {\n key: 'list-gorgias-views',\n build: buildListGorgiasViewsFunctionDef,\n createHandler: createListGorgiasViewsHandler,\n },\n {\n key: 'create-agent',\n build: buildCreateAgentFunctionDef,\n createHandler: () => createCreateAgentHandler(),\n },\n {\n key: 'set-default-agent',\n build: buildSetDefaultAgentFunctionDef,\n createHandler: () => createSetDefaultAgentHandler(),\n },\n {\n key: 'create-shared-prompt-version',\n build: buildCreateSharedPromptVersionFunctionDef,\n createHandler: () => createCreateSharedPromptVersionHandler(),\n },\n {\n key: 'sync-agent-prompt-snapshot',\n build: buildSyncAgentPromptSnapshotFunctionDef,\n createHandler: () => createSyncAgentPromptSnapshotHandler(),\n },\n {\n key: 'ext-models',\n build: buildExtModelsFunctionDef,\n createHandler: () => createExtModelsHandler(),\n },\n {\n key: 'ext-categories',\n build: buildExtCategoriesFunctionDef,\n createHandler: () => createExtCategoriesHandler(),\n },\n { key: 'ext-chat', build: buildExtChatFunctionDef, createHandler: () => createExtChatHandler() },\n {\n key: 'ext-fast-response-check',\n build: buildExtFastResponseCheckFunctionDef,\n createHandler: () => createExtFastResponseCheckHandler(),\n },\n {\n key: 'ext-evaluation',\n build: buildExtEvaluationFunctionDef,\n createHandler: () => createExtEvaluationHandler(),\n },\n {\n key: 'ext-response-comparison',\n build: buildExtResponseComparisonFunctionDef,\n createHandler: () => createExtResponseComparisonHandler(),\n },\n];\n\n// FUNCTION_ASSEMBLY must cover exactly FUNCTION_IDENTIFIER_KEYS — asserted\n// in pipeline.spec.ts, not re-asserted here (a compile-time array literal\n// has no length check to attach).\n\n/**\n * §3.7's `role.prompts` allowlist: the WHOLE Langfuse project, deliberately.\n *\n * Two narrowings preceded this one, and both failed the same way. First the\n * five derived slot names (`<prefix>triage`, …) — which stopped making sense\n * the day each graph step's prompt became an operator's choice\n * (`nodes.<step>.prompt`, picked on the SettingsPage from the catalogue THIS\n * allowlist filters): a choice restricted to the names that used to be\n * hardcoded is not a choice. Then `${promptPrefix}*` — bounded for a\n * prefixed audience, but `experience-client` passes `promptPrefix: ''`\n * (D-LF: one shared project, bare legacy names), so its glob was already the\n * whole project, while a `pro-sante/` install could not reach a single\n * prompt outside its own prefix.\n *\n * OWNER DECISION (09/09/2026): no limitation. An operator configuring a\n * pipeline must see every prompt of the project in the picker, whichever\n * audience the app serves. A prefix is a naming convention here, not a\n * tenancy boundary — under D-LF there is no per-app Langfuse namespace to\n * enforce one against, and `agent/*` had been unbounded from the start\n * anyway.\n *\n * WHAT THIS COSTS, stated rather than buried: `role.prompts` gates WRITES\n * too (`app-prompts.controller.ts`'s `requirePromptAllowed` on\n * `createVersion`/`promote`/`deleteVersion`). One audience's app token can\n * therefore read AND version-write another audience's prompts. That was\n * already true of every `agent/<id>` prompt (T25 review H1, accepted); it is\n * now true of all of them. The mitigation NOT taken remains a real per-app\n * Langfuse namespace, which contradicts D-LF and is a migration, not a flag.\n */\nfunction buildPromptsAllowlist(): string[] {\n return ['*'];\n}\n\nfunction dedupe<T>(items: readonly T[], keyOf: (item: T) => string): T[] {\n const seen = new Map<string, T>();\n for (const item of items) seen.set(keyOf(item), item);\n return [...seen.values()];\n}\n\n/**\n * Union par provider : les scopes de l'app et ceux du kit se cumulent, ils ne\n * se remplacent pas. Trié pour que deux appels successifs rendent exactement le\n * même tableau — le manifest est checksummé, un ordre instable le ferait varier\n * sans qu'une ligne ait bougé.\n */\nfunction mergeIntegrationRefs(integrations: readonly IntegrationRef[]): IntegrationRef[] {\n const byProvider = new Map<string, Set<string>>();\n for (const entry of [...integrations, ...SUPPORT_KIT_INTEGRATIONS]) {\n const scopes = byProvider.get(entry.provider) ?? new Set<string>();\n for (const scope of entry.scopes) scopes.add(scope);\n byProvider.set(entry.provider, scopes);\n }\n return [...byProvider.entries()]\n .map(([provider, scopes]) => ({ provider, scopes: [...scopes].sort() }))\n .sort((a, b) => a.provider.localeCompare(b.provider));\n}\n\n/**\n * `category`/`category-group` are the categorisation referential: every call\n * site in `src/` only ever `list`s or `get`s them (verified by grep, M2 in\n * the T25 review) — never `create`/`update`/`upsert`/`delete`. Granting\n * `writes` on them anyway lets the app's own token DELETE them, taking\n * triage offline for the whole audience.\n *\n * `agent` was in this list too until the T26 rework: `create-agent` and\n * `set-default-agent` (BLOCKER 3, BLOCKER 4) now `create`/`update` it from\n * inside a handler, via this same `ctx.api` — AgentsPage cannot assign a new\n * agent's `promptName` or maintain the \"at most one default agent\" invariant\n * from raw, unauthenticated-for-writes record PATCHes alone. `role.writes`\n * has no finer grain than \"create/update/delete\" as one bucket\n * (`SupportKitApi` itself exposes no `delete` method, but a raw app token\n * still could reach the generic records DELETE route with this grant) — this\n * IS a widened blast radius versus the prior read-only grant, accepted\n * because the alternative is an agent CRUD screen that cannot create or\n * promote an agent at all. Flagged for the spec owner, not routed around\n * silently.\n */\nconst KIT_READ_ONLY_OBJECT_KEYS = ['category', 'category-group'];\n\n/**\n * `evaluation`/`diff-analysis` are written (`create`/`upsert`) but never\n * `list`ed or `get`-ed anywhere in `src/` (M2) — the mirror over-grant of\n * `KIT_READ_ONLY_OBJECT_KEYS` above.\n */\nconst KIT_WRITE_ONLY_OBJECT_KEYS = ['evaluation', 'diff-analysis'];\n\nfunction buildMergeRole(config: SupportPipelineConfig): (role: AppRole) => AppRole {\n const kitRecords = buildSupportKitRecords(config.slug);\n const refsExcluding = (excludedObjectKeys: readonly string[]): string[] =>\n kitRecords\n .filter((record) => !excludedObjectKeys.includes(record.objectKey))\n .map((record) => targetRefFor(config.slug, record.objectKey));\n const kitReadRefs = refsExcluding(KIT_WRITE_ONLY_OBJECT_KEYS);\n const kitWriteRefs = refsExcluding(KIT_READ_ONLY_OBJECT_KEYS);\n const kitPrompts = buildPromptsAllowlist();\n\n return (role: AppRole): AppRole => ({\n ...role,\n reads: dedupe([...role.reads, ...kitReadRefs], (ref) => ref),\n writes: dedupe([...role.writes, ...kitWriteRefs], (ref) => ref),\n capabilities: dedupe([...(role.capabilities ?? []), ...SUPPORT_KIT_CAPABILITIES], (c) => c),\n prompts: dedupe([...(role.prompts ?? []), ...kitPrompts], (p) => p),\n });\n}\n\n/**\n * §3.8's phase-2 pages (T26) plus T27 part A's three phase-3 pages\n * (`DashboardPage`, `TicketsPage`, `CorrectionsPage`) plus part B's\n * `GraphCanvasPage`/`SharedPromptsPage`/`TestPage` — §3.8's full page list,\n * now complete. `path` doubles as the CLI's bundle-derivation input\n * (`dist/ui/<path>.js`, `UI_ENTRY_REGEX`) and the component name exported\n * from `src/ui/index.ts` — kept in that 1:1 correspondence by `T26`'s own\n * build-then-verify step, not enforced by a type here (`PageDefSchema`\n * only constrains shape).\n */\nconst KIT_PAGES = [\n { key: 'dashboard-page', path: 'dashboard', title: 'Tableau de bord', icon: 'layout-dashboard' },\n { key: 'tickets-page', path: 'tickets', title: 'Tickets', icon: 'inbox' },\n { key: 'agents-page', path: 'agents', title: 'Agents', icon: 'bot' },\n { key: 'categories-page', path: 'categories', title: 'Catégories', icon: 'tags' },\n { key: 'graph-canvas-page', path: 'graph-canvas', title: 'Graphe', icon: 'workflow' },\n {\n key: 'shared-prompts-page',\n path: 'shared-prompts',\n title: 'Prompts partagés',\n icon: 'library',\n },\n { key: 'test-page', path: 'test', title: 'Banc de test', icon: 'flask-conical' },\n { key: 'quality-page', path: 'quality', title: 'Qualité', icon: 'flask-conical' },\n // The SAME screen as `settingsPage`, declared a second time as an app page.\n // Not a gratuitous duplicate: `getAvailableTargets()`\n // (`apps/api/src/platform-data/spaces.service.ts`) enumerates only\n // views/pages/records, so a `settingsPage` can be mounted in NO Space — by\n // construction (docs/app-platform/app-settings-page-spec.md §2). A `pages[]`\n // entry can. Both surfaces mount the same component, which reads and writes\n // through `useAppSettings()`; that store is keyed by the app slug, so there\n // is ONE `AppSetting` row behind the two, never two copies to reconcile.\n //\n // The path cannot be 'settings': the CLI would derive `dist/ui/settings.js`\n // from it — the entry `settingsPage` already claims — and the manifest would\n // be rejected (app-kit `contracts.ts`, \"collides with the bundle the CLI\n // emits for a pages[] path\").\n { key: 'reglages-page', path: 'reglages', title: 'Réglages', icon: 'settings' },\n] as const;\n\nfunction buildPages(config: SupportPipelineConfig): PageDef[] {\n return KIT_PAGES.map(({ key, path, title, icon }) => ({\n universalIdentifier: pageIdentifierFor(config, key),\n path,\n title,\n icon,\n entry: `dist/ui/${path}.js`,\n }));\n}\n\nfunction buildNavigation(config: SupportPipelineConfig): NavItem[] {\n return KIT_PAGES.map(({ path, title, icon }) => ({\n label: title,\n path,\n icon,\n ...(config.navigationSection !== undefined ? { section: config.navigationSection } : {}),\n }));\n}\n\nfunction buildSettingsPage(config: SupportPipelineConfig): SettingsPage {\n return {\n universalIdentifier: pageIdentifierFor(config, 'settings-page'),\n entry: 'dist/ui/settings.js',\n title: 'Paramètres',\n };\n}\n\nexport function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments {\n const functions = FUNCTION_ASSEMBLY.map(({ build }) => build(config));\n const handlers: Record<string, AppHandler> = {};\n for (const { key, createHandler } of FUNCTION_ASSEMBLY) handlers[key] = createHandler(config);\n\n return {\n records: buildSupportKitRecords(config.slug),\n functions,\n settings: { fields: SUPPORT_KIT_SETTINGS_FIELDS },\n // DECISION 1 (see docs/plans/2026-09-02-gorgias-migration-progress.md's\n // T25 entry): always empty. §3.2's own fragment sketch types this\n // `PromptDef[] // seed Langfuse (§3.7)`, but §3.7 line 322 and D-LF both\n // say manifest.prompts[] is NOT used by the kit — it would seed an\n // `apps/<slug>/…` namespace that contradicts \"same Langfuse project,\n // bare legacy names, zero write at migration time\". A new audience's\n // prompts are seeded at first run via S3 createVersion (a RUNTIME\n // concern), not declared in the manifest.\n prompts: [],\n // T26 fills the four phase-2 pages + the settingsPage (§3.8); T27 part A\n // adds DashboardPage/TicketsPage/CorrectionsPage. Part B's remaining\n // phase-3 pages (GraphCanvasPage, SharedPromptsPage, TestPage) are still ahead.\n pages: buildPages(config),\n navigation: buildNavigation(config),\n settingsPage: buildSettingsPage(config),\n integrations: SUPPORT_KIT_INTEGRATIONS,\n emits: SUPPORT_KIT_EMITS,\n defaultRole: 'NO_ACCESS',\n handlers,\n mergeRole: buildMergeRole(config),\n mergeIntegrations: mergeIntegrationRefs,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/domain/classification.ts","../src/domain/profile.ts","../src/domain/evaluation-verdict.ts","../src/graph/state.ts","../src/graph/ports.ts","../src/graph/budget.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/references.ts","../src/prompts/resolver.ts","../src/prompts/slots.ts","../src/records/ids.ts","../src/records/target-ref.ts","../src/records/category.ts","../src/records/category-group.ts","../src/records/agent.ts","../src/records/triage-decision.ts","../src/records/generated-response.ts","../src/records/response-comparison.ts","../src/records/evaluation.ts","../src/records/diff-analysis.ts","../src/records/pipeline-state.ts","../src/records/prompt-cache.ts","../src/records/derive-uid.ts","../src/records/scope-to-app.ts","../src/records/index.ts","../src/settings/fields.ts","../src/settings/validate.ts","../src/settings/to-profile.ts","../src/functions/config.ts","../src/adapters/conversation-mapping.ts","../src/adapters/gorgias-tags.ts","../src/adapters/ctx-ports.ts","../src/adapters/recording-ports.ts","../src/functions/context.ts","../src/functions/eligibility.ts","../src/functions/no-tool-context.ts","../src/functions/pipeline-state.ts","../src/functions/claim-commit.ts","../src/functions/approval-key.ts","../src/functions/traced-input.ts","../src/functions/records.ts","../src/functions/process-response.ts","../src/functions/generated-response-transition.ts","../src/functions/triage-tick.ts","../src/functions/sweep.ts","../src/functions/handle-approval.ts","../src/functions/ids.ts","../src/functions/run-triage-now.ts","../src/functions/invalidate-response.ts","../src/functions/preview-triage.ts","../src/functions/get-ticket-conversation.ts","../src/functions/graph-dry-run-core.ts","../src/functions/graph-dry-run.ts","../src/functions/test-agents.ts","../src/functions/validate-references.ts","../src/functions/suggest-prompt.ts","../src/functions/list-gorgias-views.ts","../src/functions/create-agent.ts","../src/functions/set-default-agent.ts","../src/functions/create-shared-prompt-version.ts","../src/functions/sync-agent-prompt-snapshot.ts","../src/functions/ext-models.ts","../src/functions/ext-categories.ts","../src/functions/ownership-probe.ts","../src/functions/support-extension-envelope.ts","../src/functions/ext-chat.ts","../src/functions/ext-fast-response-check.ts","../src/functions/ext-evaluation.ts","../src/functions/response-comparison-diff.ts","../src/functions/ext-response-comparison.ts","../src/pages/manifest.ts","../src/pipeline.ts"],"names":["firstCustomerMessage","fallback","draft","outcome","finish","AppApiError","text","FieldType","createHash","step","triage","evaluate","is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;AAAA,IACA,QAAA,EAAU,EAAE,MAAA,EAAQ,2BAAA,EAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAShD,SAAS,EAAC;AAAA;AAAA;AAAA;AAAA,IAIV,KAAA,EAAO,WAAW,MAAM,CAAA;AAAA,IACxB,UAAA,EAAY,gBAAgB,MAAM,CAAA;AAAA,IAClC,YAAA,EAAc,kBAAkB,MAAM,CAAA;AAAA,IACtC,YAAA,EAAc,wBAAA;AAAA,IACd,KAAA,EAAO,iBAAA;AAAA,IACP,WAAA,EAAa,WAAA;AAAA,IACb,QAAA;AAAA,IACA,SAAA,EAAW,eAAe,MAAM,CAAA;AAAA,IAChC,iBAAA,EAAmB;AAAA,GACrB;AACF","file":"index.cjs","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","// 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","// Spec: architecture_agent_graphe.md §6.3 (legacy `agent/budget.ts`).\n//\n// Ported unchanged: this bounds ONE run in tool calls and time, and tracks\n// its cost ledger (I15) — it has nothing to do with the worker-level\n// `RUN_DEADLINE_MS`/stale-lock scheduling the migration drops in favour of\n// Inngest retries/concurrency/timeouts (spec §3.3's \"différences assumées\").\n// The caller still supplies whatever `AbortSignal` represents its own\n// deadline; `Budget` only ever reads it.\nimport type { CostLedger, NodeCost, NodeKey, Usage } from '../domain';\n\nconst ZERO_COST: NodeCost = { input: 0, output: 0, reasoning: 0, usd: 0, pricingMissing: false };\n\n/**\n * Run budget: bounds a run in TOOL CALLS and TIME only, never in money —\n * cost is measured (`charge`, I15) and watched separately, not capped here.\n * Every method is a no-throw no-op past the allowance: exhausting the\n * budget must never fail a ticket (§6.3).\n */\nexport interface Budget {\n /** The run's deadline signal, forwarded unchanged to every LLM call. */\n signal: AbortSignal;\n consumeToolCall(): void;\n /** True once `maxToolCalls` is spent OR the run signal aborted. */\n exhausted(): boolean;\n /** Accumulates usage/cost for one node. Reasoning stays out of `output` (§6.3). */\n charge(node: NodeKey, usage: Usage, cost: { usd: number; pricingMissing: boolean }): void;\n /** Per-node breakdown for the ticket's provenance trail. */\n ledger(): CostLedger;\n /** Whole-run total — the per-ticket cost watched downstream. */\n total(): NodeCost;\n}\n\nfunction addCost(existing: NodeCost | undefined, usage: Usage, cost: { usd: number; pricingMissing: boolean }): NodeCost {\n const base = existing ?? ZERO_COST;\n return {\n input: base.input + usage.input,\n output: base.output + usage.output,\n reasoning: base.reasoning + usage.reasoning,\n usd: base.usd + cost.usd,\n // Sticky: one unpriced charge is enough to mark the whole node unpriced,\n // so a later zero-cost charge never makes it read as \"this was free\".\n pricingMissing: base.pricingMissing || cost.pricingMissing,\n };\n}\n\nexport function createBudget({ signal, maxToolCalls }: { signal: AbortSignal; maxToolCalls: number }): Budget {\n let toolCallsUsed = 0;\n const costs: CostLedger = {};\n\n return {\n signal,\n\n consumeToolCall(): void {\n toolCallsUsed += 1;\n },\n\n exhausted(): boolean {\n return toolCallsUsed >= maxToolCalls || signal.aborted;\n },\n\n charge(node, usage, cost): void {\n costs[node] = addCost(costs[node], usage, cost);\n },\n\n ledger(): CostLedger {\n return { ...costs };\n },\n\n total(): NodeCost {\n return Object.values(costs).reduce<NodeCost>(\n (acc, entry) => addCost(acc, entry, { usd: entry.usd, pricingMissing: entry.pricingMissing }),\n ZERO_COST,\n );\n },\n };\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\nfunction 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] 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: ['ready', 'failed', 'no_reply_needed', 'sending', 'invalidated'],\n ready: ['sending', 'invalidated', 'expired'],\n sending: ['sent', 'ready'],\n sent: [],\n failed: [],\n no_reply_needed: [],\n invalidated: [],\n expired: [],\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 * Parsing for Langfuse prompt-composition reference tags\n * (`@@@langfusePrompt:name=<name>|label=<label>@@@` or `|version=<n>@@@`).\n *\n * Ported from legacy `services/promptReferences.ts` (spec §3.7: \"la\n * composition … est résolue par le kit (port de `promptReferences.ts`)\").\n * `parseReferences`/`hasReferences` are pure and dependency-free, exactly as\n * in the legacy module, so `resolver.ts`'s composition pass and the\n * write-through cache guard can both depend on them without pulling in any\n * network/DB concern.\n *\n * `validateReferences` (the admin save-time validator) is NOT ported here:\n * it is an authoring-time concern for the prompt-editing UI (AgentsPage /\n * SharedPromptsPage, §3.8), not part of `PromptPort`'s runtime resolution\n * ladder — out of scope for T19. See the module doc in `resolver.ts` for the\n * runtime composition pass this package does own.\n *\n * `REFERENCE_TAG_SOURCE` (T23 post-review B3): the regex SOURCE, not the\n * stateful `g`-flagged object itself — `functions/validate-references.ts`\n * needs the exact same grammar to tell a well-formed tag from one that only\n * looks like one, and a hand-forked copy silently drifts the moment this\n * one gains a form. Exporting the source string (not `REF_RE`) keeps every\n * importer building its own `RegExp` instance, exactly like `hasReferences`\n * already does below — nobody shares, and therefore nobody can corrupt,\n * `REF_RE.lastIndex`.\n */\n\nconst REF_RE = /@@@langfusePrompt:name=([^|@]+)\\|(?:version=(\\d+)|label=([^@]+))@@@/g;\n\nexport const REFERENCE_TAG_SOURCE = REF_RE.source;\n\nexport interface PromptReference {\n name: string;\n version?: number;\n label?: string;\n raw: string;\n}\n\n/** Parse every well-formed reference tag out of `content`, in order of appearance. */\nexport function parseReferences(content: string): PromptReference[] {\n const refs: PromptReference[] = [];\n for (const [raw, name, version, label] of content.matchAll(REF_RE)) {\n refs.push(version !== undefined ? { name: name as string, version: Number(version), raw } : { name: name as string, label, raw });\n }\n return refs;\n}\n\n/**\n * Cheap synchronous check for \"does this content contain any reference tag\".\n * Used by the write-through cache guard (`resolver.ts`) to decide whether\n * raw content is safe to mirror into the `prompt-cache` record — a fresh\n * `new RegExp` avoids mutating the shared, stateful `REF_RE.lastIndex`.\n */\nexport function hasReferences(content: string): boolean {\n return new RegExp(REF_RE.source).test(content);\n}\n","/**\n * `PromptPort` implementation — §3.7's three-level fallback, ported from\n * legacy `services/promptStore.ts`'s `getActive` ladder:\n *\n * 1. `ctx.api.prompts.get(name, {label:'production', resolve:false})`\n * (T5's platform surface, reached only through the injected\n * `PlatformPromptReader` seam below — this package may not import\n * `@wopilo/*` or reach the network itself). A 60 s in-memory cache sits\n * in front of it, mirroring the legacy SDK's own `cacheTtlSeconds`.\n * Composition tags (`@@@langfusePrompt:name=…@@@`) are resolved by\n * THIS module (`composeReferences` below) — T5's surface reads raw\n * only, unlike legacy's `c.prompt.get` which flattened composition\n * server-side. Composition targets are read through the SAME memory\n * cache as the root prompt (post-review D1) — without that, a template\n * with N reference tags paid for N extra, uncached, sequentially\n * awaited Langfuse round-trips on every single call, TTL or not.\n * 2. The `prompt-cache` record mirror (T20's record, T21's adapter) —\n * reached only through the injected `PromptCachePort` seam. Written\n * through on every successful NON-EMPTY level-1 read, AFTER composition\n * (post-review C): the content mirrored is the fully composed,\n * tag-free text, not the raw pre-composition template. Composing first\n * means a Langfuse outage now degrades to the last-known-good COMPOSED\n * prompt instead of skipping the mirror for every prompt that uses\n * composition (`shared/style-email`/`shared/style-whatsapp` consumers,\n * in particular) — `hasReferences` stays as a cheap, should-never-fire\n * assertion guarding the same invariant it always did: no raw\n * `@@@…@@@` tag may ever reach the `prompt-cache` mirror.\n * 3. `ref.fallback` (the in-code default carried by the `PromptRef` the\n * caller passed in, itself populated from `config.defaults.prompts` at\n * `buildSupportPipeline` assembly time — T20).\n *\n * …and if that last rung is empty too, `MissingPromptError` (C5 as\n * amended, `graph/ports.ts`). \"Empty\" moves DOWN the ladder at every\n * rung, it does not end it: a level that answers with no text (a blank\n * Langfuse version, a mirror entry holding nothing) is that level coming\n * up empty, not the install having no prompt — only the bottom of the\n * ladder raises. This ladder used to terminate at empty\n * text, version 0 — a step reaching the model with no system message\n * at all, reported as a normal run. A step with no prompt is a broken\n * install: it fails the run, loudly, naming the prompt that resolved\n * to nothing. The settings-time half of the same rule is\n * `settings/validate.ts`, which refuses to run a pipeline whose active\n * steps name no prompt at all.\n *\n * Model config (`ResolvedPrompt.config`): populated from the level-1 read's\n * `RawPrompt.config` (T5's `PromptDetail.config`, once threaded through by\n * the platform adapter). Levels 2 and 3 still report `null` today, but for\n * different reasons now that T20 has landed the records: the `prompt-cache`\n * record (§3.4) DOES carry a `config JSON?` column — this module simply\n * neither writes nor reads it yet, so level 2 has a place to recover a\n * config from and does not use it (T21's `PromptCachePort` adapter is where\n * that gets wired). `PromptRef.fallback` carries no config field at all, so\n * level 3 is `null` by construction, not by omission.\n *\n * Cache scope: `createPromptResolver` holds NO module-level state — every\n * call returns a fresh closure over its own `Map`, so two calls (two\n * app instances, or two tests) never share a memory cache. A caller that\n * wants one long-lived resolver per app process constructs it once at\n * startup (T21); a test that wants a clean slate just calls the factory\n * again. The optional `now` hook replaces `Date.now()` for tests that need\n * to force an entry stale without `vi.useFakeTimers`.\n *\n * `onDegraded` (post-review E): the kit has no logging port, and should not\n * grow one just for this — but every point below where this ladder silently\n * empties a segment or falls a level is otherwise indistinguishable from a\n * correct run to an operator. This optional hook fires at each of those\n * points; T21 wires it to the platform logger.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { PromptRef } from '../domain/profile';\nimport { MissingPromptError, type PromptPort, type ResolvedPrompt } from '../graph/ports';\nimport { hasReferences, parseReferences, type PromptReference } from './references';\n\nconst PRODUCTION_LABEL = 'production';\nconst DEFAULT_TTL_MS = 60_000;\n\n/**\n * Langfuse's own prompt-composition resolver caps a reference chain at 5\n * levels; a linear A→B→C… chain here is otherwise bounded only by the\n * number of distinct prompt names, each hop a sequential awaited round-trip\n * inside the LLM path. Matching Langfuse's own cap keeps this module's\n * worst case aligned with the platform it is standing in for.\n *\n * Exported (T23 post-review B1) so `functions/validate-references.ts` can\n * reject, AT SAVE TIME, a chain that would silently degrade past this exact\n * cap at runtime — restating the number there would only let the two drift.\n */\nexport const MAX_COMPOSITION_DEPTH = 5;\n\n/**\n * Back-compat key: the bare name for the default label (legacy `cacheId`),\n * name + NUL + label otherwise. The joint is a NUL byte, not the legacy\n * `::` — prompt names are free-form now (Langfuse is the naming authority),\n * so a name may itself contain `::` and a printable delimiter would let\n * (`a::b`, production) and (`a`, label `b`) collide on one entry.\n */\nfunction cacheKey(name: string, label: string): string {\n return label === PRODUCTION_LABEL ? name : `${name}\\u0000${label}`;\n}\n\n/**\n * Memory-cache key for a platform read. A version-pinned read (a composition\n * target naming `|version=n`) is keyed on the version, since a label can\n * float across versions but a pinned version never does — collapsing it onto\n * `cacheKey`'s label-shaped key would either merge two distinct versions\n * under one entry or never hit at all. JSON-encoded (the shape tag keeps a\n * version key from ever colliding with a label key, whatever the name\n * contains) — this cache is per-process, so unlike `cacheKey` there is no\n * stored back-compat to preserve.\n */\nfunction memoryKey(name: string, opts: { label?: string; version?: number }): string {\n if (opts.version !== undefined) return JSON.stringify(['v', name, opts.version]);\n return JSON.stringify(['l', name, opts.label ?? PRODUCTION_LABEL]);\n}\n\n/**\n * Mustache-style `{{var}}` substitution — mirrors legacy `compileFallback`.\n * Uses the function form of `replaceAll` (post-review D3): a plain string\n * replacement interprets `$&`/`` $` ``/`$'`/`$1` specially, so a value\n * containing a literal `$&` (a quoted ticket excerpt, for instance) would\n * silently splice the matched placeholder back into the compiled prompt.\n */\nfunction substituteVars(text: string, vars: Record<string, string> | undefined): string {\n if (!vars) return text;\n return Object.entries(vars).reduce((out, [key, value]) => out.replaceAll(`{{${key}}}`, () => value), text);\n}\n\n/** One reference tag's target config, as read off T5's `PromptDetail.config`. */\nexport interface RawPromptConfig {\n model?: string;\n temperature?: number;\n}\n\n/** Raw (uncompiled, composition-unresolved) prompt content read at a given name+label/version. */\nexport interface RawPrompt {\n version: number;\n content: string;\n /**\n * Model config carried by the platform prompt, when the endpoint returns\n * one. Optional/absent (not just `null`) so every existing raw literal\n * built before this field existed still type-checks unchanged.\n */\n config?: RawPromptConfig | null;\n}\n\n/**\n * Seam onto T5's `ctx.api.prompts.get(name, {label|version, resolve:false})`.\n * May throw (network error, 404, unconfigured Langfuse, …) — the resolver\n * treats any rejection as a level-1 miss and falls through the ladder. T21\n * supplies the real adapter; `testing/fakes` supplies a test double.\n */\nexport interface PlatformPromptReader {\n get(name: string, ref: { label?: string; version?: number }): Promise<RawPrompt>;\n}\n\n/** One entry of the `prompt-cache` mirror (§3.4) — always RESOLVED content, never a raw reference tag. */\nexport interface PromptCacheEntry {\n content: string;\n version: number;\n}\n\n/**\n * Seam onto the `prompt-cache` record (T20's schema, T21's adapter). Both\n * methods are best-effort from the resolver's point of view — a rejection\n * from either is caught and treated as a miss/no-op, exactly like legacy's\n * Mongo cache: a `prompt-cache` outage must never block the LLM path.\n */\nexport interface PromptCachePort {\n read(key: string): Promise<PromptCacheEntry | null>;\n write(key: string, entry: PromptCacheEntry): Promise<void>;\n}\n\n/**\n * One silent-degradation event (post-review E). `stage` names the point in\n * the ladder that gave up on the \"real\" answer and returned something safe\n * instead; `name` is the prompt/reference name involved; `reason` is a\n * human-readable cause, not a typed error (the kit has no logging/error\n * taxonomy to spend here — that is T21's job once this reaches a real\n * logger).\n */\nexport interface PromptDegradedEvent {\n stage:\n | 'platform-unavailable'\n | 'cache-unavailable'\n | 'composition-target-missing'\n | 'composition-target-forbidden'\n | 'composition-cycle'\n | 'composition-depth-exceeded'\n /**\n * A level answered, and answered with nothing — a Langfuse prompt whose\n * production version is blank (`platform-empty`), or a `prompt-cache`\n * mirror entry holding no text (`cache-empty`). Distinct from the\n * `-unavailable` stages above, which are the level failing to answer at\n * all: both descend, but only these two mean the level was reachable and\n * said nothing. The one an operator needs to see, because nothing else\n * reports that the prompt they just edited is now empty.\n */\n | 'platform-empty'\n | 'cache-empty'\n /**\n * Not a degradation but its terminus: the ladder resolved no text at any\n * level and the run is about to fail on `MissingPromptError`. Emitted\n * here anyway so an operator reading the degradation log sees the whole\n * ladder's story, ending in the reason, rather than the exception alone\n * with no trace of what was tried.\n */\n | 'prompt-missing';\n name: string;\n reason: string;\n}\n\nexport interface PromptResolverDeps {\n platform: PlatformPromptReader;\n cache: PromptCachePort;\n /** Memory-cache TTL override, ms. Defaults to 60 000 (§3.7). */\n ttlMs?: number;\n /** Injectable clock for the memory cache, defaults to `Date.now`. */\n now?: () => number;\n /** Fires at every silent-degradation point in the ladder (post-review E). */\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\ninterface MemoryCacheEntry {\n /** Fully composed content — no remaining reference tag — never the raw fetch. */\n content: string;\n version: number;\n config?: RawPromptConfig | null;\n expiresAt: number;\n}\n\ninterface ComposeContext {\n platform: PlatformPromptReader;\n memory: Map<string, MemoryCacheEntry>;\n ttlMs: number;\n now: () => number;\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\nfunction reasonOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * `parseReferences` returns one entry per OCCURRENCE, not per distinct\n * target (post-review D2) — a template that repeats the same tag twice must\n * still only fetch it once. `ref.raw` identifies the target uniquely enough\n * for this purpose: two occurrences of the same tag share the same raw\n * string, and `replaceAll` below already replaces every occurrence in one\n * pass once the tag is deduped.\n */\nfunction dedupeByRaw(refs: PromptReference[]): PromptReference[] {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n if (seen.has(ref.raw)) return false;\n seen.add(ref.raw);\n return true;\n });\n}\n\nfunction stripReferences(content: string, refs: PromptReference[]): string {\n let out = content;\n for (const ref of dedupeByRaw(refs)) out = out.replaceAll(ref.raw, () => '');\n return out;\n}\n\n/**\n * Fetches `name` at `opts`, composes its references, and caches the\n * COMPOSED result (post-review D1) — shared by both the root prompt read\n * and every composition target, so a reference fetched once by any caller\n * within the TTL window is never fetched again, root or nested.\n */\nasync function readComposed(\n name: string,\n opts: { label?: string; version?: number },\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<MemoryCacheEntry> {\n const key = memoryKey(name, opts);\n const cached = ctx.memory.get(key);\n if (cached && cached.expiresAt > ctx.now()) return cached;\n\n const raw = await ctx.platform.get(name, opts);\n const content = await composeReferences(raw.content, ctx, visited, depth);\n const entry: MemoryCacheEntry = { content, version: raw.version, config: raw.config, expiresAt: ctx.now() + ctx.ttlMs };\n ctx.memory.set(key, entry);\n return entry;\n}\n\n/**\n * Resolves one reference tag to its replacement text: empty on a cycle\n * (visited) or an unresolvable target (fetch/compose throws), the target's\n * own composed content otherwise. Never leaves the literal tag in place —\n * the guarantee this module exists to hold (\"no raw tag reaches the LLM\")\n * applies here, not only through the write-through cache guard.\n */\nasync function resolveOneReference(\n ref: PromptReference,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (visited.has(ref.name)) {\n ctx.onDegraded?.({ stage: 'composition-cycle', name: ref.name, reason: 'cyclic composition reference' });\n return '';\n }\n\n const targetOpts = ref.version !== undefined ? { version: ref.version } : { label: ref.label };\n try {\n const target = await readComposed(ref.name, targetOpts, ctx, new Set([...visited, ref.name]), depth + 1);\n return target.content;\n } catch (err) {\n // M1 (T25 review): a 403 (the target exists but is outside this app's\n // role.prompts allowlist) is a MISCONFIGURATION, not a missing prompt —\n // reported under its own stage so `onDegraded` can name the allowlist\n // instead of reading identically to \"prompt/version/label not found\".\n // Still resolves to '' either way (PromptPort.resolve may never reject,\n // graph/ports.ts's C5) — this only makes the degradation legible.\n const forbidden = err instanceof AppApiError && err.status === 403;\n ctx.onDegraded?.({\n stage: forbidden ? 'composition-target-forbidden' : 'composition-target-missing',\n name: ref.name,\n reason: reasonOf(err),\n });\n return '';\n }\n}\n\n/**\n * Resolves every reference tag in `content`, one round-trip per DISTINCT\n * target (post-review D2), using the function form of `replaceAll`\n * (post-review D3 — see `substituteVars`'s doc comment for why). `depth`\n * bounds the chain at `MAX_COMPOSITION_DEPTH` (post-review D4): past it, the\n * remaining tags are stripped rather than followed one hop further, so a\n * long linear A→B→C… chain degrades instead of costing one sequential\n * round-trip per hop indefinitely.\n */\nasync function composeReferences(\n content: string,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (!hasReferences(content)) return content;\n\n const refs = parseReferences(content);\n if (depth >= MAX_COMPOSITION_DEPTH) {\n for (const ref of dedupeByRaw(refs)) {\n ctx.onDegraded?.({\n stage: 'composition-depth-exceeded',\n name: ref.name,\n reason: `composition chain exceeded ${MAX_COMPOSITION_DEPTH} levels`,\n });\n }\n return stripReferences(content, refs);\n }\n\n let resolved = content;\n for (const ref of dedupeByRaw(refs)) {\n const replacement = await resolveOneReference(ref, ctx, visited, depth);\n resolved = resolved.replaceAll(ref.raw, () => replacement);\n }\n return resolved;\n}\n\n/** Narrows a raw config blob to `ResolvedPrompt.config`'s stricter shape (model required, not just optional). */\nfunction toResolvedConfig(config: RawPromptConfig | null | undefined): ResolvedPrompt['config'] {\n if (!config || typeof config.model !== 'string' || config.model.length === 0) return null;\n return config.temperature !== undefined ? { model: config.model, temperature: config.temperature } : { model: config.model };\n}\n\n/** Builds a `PromptPort` implementing §3.7's three-level fallback ladder. */\nexport function createPromptResolver(deps: PromptResolverDeps): PromptPort {\n const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;\n const now = deps.now ?? Date.now;\n const memory = new Map<string, MemoryCacheEntry>();\n const composeCtx: ComposeContext = { platform: deps.platform, memory, ttlMs, now, onDegraded: deps.onDegraded };\n\n async function resolveFromCacheOrFallback(\n name: string,\n label: string,\n ref: PromptRef,\n vars: Record<string, string> | undefined,\n ): Promise<ResolvedPrompt> {\n const cached = await deps.cache.read(cacheKey(name, label)).catch((err: unknown) => {\n deps.onDegraded?.({ stage: 'cache-unavailable', name, reason: reasonOf(err) });\n return null;\n });\n if (cached) {\n const text = substituteVars(cached.content, vars);\n if (text.trim() !== '') return { name, text, version: cached.version, config: null };\n // A mirror entry that holds no text is this rung coming up empty, not\n // the ladder ending: C5 reserves `MissingPromptError` for every level\n // being empty. Descend to the in-code default below.\n deps.onDegraded?.({ stage: 'cache-empty', name, reason: 'the prompt-cache mirror holds no text' });\n }\n\n // M3 (T25 review): `ref.fallback` (config.defaults.prompts, wired T25)\n // is the one rung of the ladder that used to skip composition entirely\n // — a fallback authored with the house `@@@langfusePrompt:...@@@` idiom\n // (the same syntax every legacy prompt already uses) would reach the\n // LLM as a literal, unresolved tag the moment Langfuse AND the\n // prompt-cache mirror were both unavailable, violating this module's\n // own \"no raw tag reaches the LLM\" guarantee. Composed through the same\n // `composeCtx` (and so the same memory cache) as every other level.\n const rawFallback = ref.fallback ?? '';\n const text = hasReferences(rawFallback)\n ? await composeReferences(rawFallback, composeCtx, new Set([name]), 0)\n : rawFallback;\n return served({ name, text: substituteVars(text, vars), version: 0, config: null }, label);\n }\n\n /**\n * The ladder's terminus, and only its terminus. C5 (`graph/ports.ts`) makes\n * `MissingPromptError` the answer to \"every level came up empty\", not to\n * \"this level came up empty\" — every rung above descends instead of\n * throwing, so the only resolution that reaches this check with no text is\n * one where Langfuse, the `prompt-cache` mirror and the ref's in-code\n * fallback all said nothing. That is the broken install the error names.\n *\n * Whitespace counts as empty — a prompt of three newlines says nothing to a\n * model, and a name that resolves to one is the same broken install as a\n * name that resolves to nothing.\n */\n function served(resolved: ResolvedPrompt, label: string): ResolvedPrompt {\n if (resolved.text.trim() === '') {\n deps.onDegraded?.({ stage: 'prompt-missing', name: resolved.name, reason: 'no prompt content at any level' });\n throw new MissingPromptError(resolved.name, label);\n }\n return resolved;\n }\n\n return {\n async resolve(ref: PromptRef, vars?: Record<string, string>): Promise<ResolvedPrompt> {\n const label = ref.label?.trim() || PRODUCTION_LABEL;\n const persistKey = cacheKey(ref.name, label);\n\n let resolved: MemoryCacheEntry;\n try {\n resolved = await readComposed(ref.name, { label }, composeCtx, new Set([ref.name]), 0);\n } catch (err) {\n deps.onDegraded?.({ stage: 'platform-unavailable', name: ref.name, reason: reasonOf(err) });\n return resolveFromCacheOrFallback(ref.name, label, ref, vars);\n }\n\n // Write-through, AFTER composition (§3.7 invariant, post-review C):\n // only ever mirror composed, tag-free content. `hasReferences` here is\n // a should-never-fire assertion, not a decision point — composition\n // above already strips every matched tag by construction.\n //\n // Gated on the COMPOSED content being non-empty, not on this call's\n // substituted text: a Langfuse version someone has just blanked must\n // never overwrite the mirror's last-known-good entry with that\n // emptiness — that mirror is the very rung the ladder is about to\n // descend to. A template that merely substitutes to nothing for one\n // call's `vars` is still the prompt worth mirroring.\n if (resolved.content.trim() !== '' && !hasReferences(resolved.content)) {\n await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => undefined);\n }\n\n const text = substituteVars(resolved.content, vars);\n if (text.trim() === '') {\n // The platform answered, and answered with nothing. That is this rung\n // being empty, not the install having no prompt at all (C5), so the\n // ladder continues: the mirror still holds the last content that did\n // say something, and the ref still carries its in-code default.\n deps.onDegraded?.({ stage: 'platform-empty', name: ref.name, reason: 'the platform read resolved to no text' });\n return resolveFromCacheOrFallback(ref.name, label, ref, vars);\n }\n\n return { name: ref.name, text, version: resolved.version, config: toResolvedConfig(resolved.config) };\n },\n };\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';\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';\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';\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 * A relation's `targetRef` names the app the target record lives in\n * (`app:<slug>/<objectKey>`, resolved by `app-records.service.ts`), and the\n * kit is never installed under the slug `support-kit`: it is spread into\n * `experience-client`, `pro-sante`, … Every record carrying a relation is\n * therefore built per consuming app, from that app's own slug (§3.2's\n * `config.slug`), never from a literal.\n */\nexport function targetRefFor(slug: string, objectKey: string): string {\n return `app:${slug}/${objectKey}`;\n}\n","/**\n * `category` (ex-`Category`) — spec §3.4.\n *\n * `tagName` is matched exactly, case-sensitively, against Gorgias tags — it is\n * NOT normalised anywhere in this definition, on purpose: the handler that\n * applies tags (T22+) must compare byte-for-byte with what Gorgias sends back.\n *\n * The legacy `auto_reply_min_confidence` field is deliberately not ported —\n * the spec records it as already neutralised upstream in the legacy system.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_OBJECT_UID,\n CATEGORY_FIELD_NAME_UID,\n CATEGORY_FIELD_TAG_NAME_UID,\n CATEGORY_FIELD_ORDER_UID,\n CATEGORY_FIELD_GROUP_ID_UID,\n CATEGORY_FIELD_AGENT_ID_UID,\n CATEGORY_FIELD_EXTRA_TAGS_UID,\n CATEGORY_FIELD_DESCRIPTION_UID,\n CATEGORY_FIELD_EXAMPLES_UID,\n CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n CATEGORY_INDEX_TAG_NAME_UID,\n CATEGORY_INDEX_NAME_UID,\n CATEGORY_INDEX_ORDER_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildCategoryRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: CATEGORY_OBJECT_UID,\n objectKey: 'category',\n labelSingular: 'Category',\n labelPlural: 'Categories',\n description: 'A triage category, matched against a Gorgias tag.',\n fields: [\n {\n universalIdentifier: CATEGORY_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_TAG_NAME_UID,\n name: 'tagName',\n type: FieldType.TEXT,\n label: 'Gorgias tag',\n description: 'Matched exactly, case-sensitively, against Gorgias tags.',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_GROUP_ID_UID,\n name: 'groupId',\n type: FieldType.RELATION,\n label: 'Category group',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category-group'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXTRA_TAGS_UID,\n name: 'extraTags',\n type: FieldType.JSON,\n label: 'Extra tags',\n description: 'string[], at most 10 entries of at most 50 characters each.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: CATEGORY_FIELD_DESCRIPTION_UID,\n name: 'description',\n type: FieldType.TEXT,\n label: 'Description',\n description:\n 'Short definition of what belongs in this category — what triage shows the model to choose between categories. `examples` stays what it says: sample customer messages. Kept separate because the two feed the referential under different keys, and folding one into the other sends the same text twice.',\n // Nullable, and not merely by convention: every category already in a\n // tenant's base predates this field. A required one would fail the\n // read of every existing row.\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXAMPLES_UID,\n name: 'examples',\n type: FieldType.TEXT,\n label: 'Examples',\n description: 'At most 4000 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n name: 'fastResponseEnabled',\n type: FieldType.BOOLEAN,\n label: 'Fast response enabled',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n name: 'autoReplyEnabled',\n type: FieldType.BOOLEAN,\n label: 'Auto-reply enabled',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: CATEGORY_INDEX_TAG_NAME_UID, fields: ['tagName'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_NAME_UID, fields: ['name'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_ORDER_UID, fields: ['order'] },\n ],\n };\n}\n","/** `category-group` — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_GROUP_OBJECT_UID,\n CATEGORY_GROUP_FIELD_NAME_UID,\n CATEGORY_GROUP_FIELD_ORDER_UID,\n CATEGORY_GROUP_INDEX_NAME_UID,\n} from './ids';\n\nexport const categoryGroupRecord: ObjectDef = {\n universalIdentifier: CATEGORY_GROUP_OBJECT_UID,\n objectKey: 'category-group',\n labelSingular: 'Category group',\n labelPlural: 'Category groups',\n fields: [\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n ],\n indexes: [{ universalIdentifier: CATEGORY_GROUP_INDEX_NAME_UID, fields: ['name'], isUnique: true }],\n};\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 * `triage-decision` (ex-`TriageDecision`) — spec §3.4.\n *\n * `decidedAt` is indexed because the 24h/7d stat windows filter and bucket on\n * this DATA field, not on the system `createdAt` — a run replayed or\n * backfilled keeps the decision's own timestamp.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n TRIAGE_DECISION_OBJECT_UID,\n TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n TRIAGE_DECISION_FIELD_TICKET_URL_UID,\n TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n TRIAGE_DECISION_FIELD_TAG_UID,\n TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_REASONING_UID,\n TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n TRIAGE_DECISION_FIELD_ESCALATED_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n TRIAGE_DECISION_FIELD_STATUS_UID,\n TRIAGE_DECISION_FIELD_ERROR_UID,\n TRIAGE_DECISION_FIELD_RUN_ID_UID,\n TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n TRIAGE_DECISION_INDEX_TICKET_ID_UID,\n TRIAGE_DECISION_INDEX_DECIDED_AT_UID,\n TRIAGE_DECISION_INDEX_ESCALATED_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nconst CONFIDENCE_OPTIONS = ['high', 'low'] as const;\n\nexport function buildTriageDecisionRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: TRIAGE_DECISION_OBJECT_UID,\n objectKey: 'triage-decision',\n labelSingular: 'Triage decision',\n labelPlural: 'Triage decisions',\n fields: [\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket url',\n description:\n 'Deep link to the ticket in the helpdesk, resolved once per batch and frozen on the decision. Null on a decision written before this field existed, or when the connection exposes no public url (mock).',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n name: 'decidedAt',\n type: FieldType.DATE_TIME,\n label: 'Decided at',\n description: 'Backs the 24h/7d stat windows — not the system createdAt.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TAG_UID,\n name: 'tag',\n type: FieldType.TEXT,\n label: 'Tag',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n name: 'confidence',\n type: FieldType.SELECT,\n label: 'Confidence',\n isNullable: false,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_REASONING_UID,\n name: 'reasoning',\n type: FieldType.TEXT,\n label: 'Reasoning',\n description: 'At most 280 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n name: 'conversationOver',\n type: FieldType.BOOLEAN,\n label: 'Conversation over',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATED_UID,\n name: 'escalated',\n type: FieldType.BOOLEAN,\n label: 'Escalated',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n name: 'escalationConfidence',\n type: FieldType.SELECT,\n label: 'Escalation confidence',\n isNullable: true,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n name: 'escalationReasoning',\n type: FieldType.TEXT,\n label: 'Escalation reasoning',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: ['ok', 'error'],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_RUN_ID_UID,\n name: 'runId',\n type: FieldType.TEXT,\n label: 'Run id',\n description: 'The application run this decision was made under.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n name: 'subjectRenamed',\n type: FieldType.BOOLEAN,\n label: 'Subject renamed',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: TRIAGE_DECISION_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_DECIDED_AT_UID, fields: ['decidedAt'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_ESCALATED_UID, fields: ['escalated'] },\n ],\n };\n}\n","/**\n * `generated-response` (ex-`FastResponse`) — spec §3.4. Both the send queue\n * and the response cache.\n *\n * `status`'s option list is `GENERATED_RESPONSE_STATUSES` from\n * `../status/machine` — the single source of truth T16 already built for the\n * status vocabulary and its terminal/open partition — rather than a second\n * hardcoded list that could drift from it.\n *\n * `openTicketKey` reconstitutes the legacy \"one open job per ticket\"\n * guarantee as a Postgres unique index (NULLs are distinct): it is\n * `openTicketKeyFor(status, ticketId)` at write time (a T22+ handler\n * concern), so this definition intentionally does NOT restate which statuses\n * count as \"open\" — it only declares the field and its unique index.\n *\n * `autoSendDecision` is the field `reclaimStalledSend()` (T16) writes into\n * alongside `status: 'ready'` on the sweep's stalled-send reclaim.\n *\n * `expiresAt` is non-nullable: it is `generatedAt + responseTtlMinutes`,\n * known at creation time, and the sweep (`ready` expired -> `expired`, T22)\n * plus the extension's TTL check both read it unconditionally — a null there\n * would be a row that never expires.\n *\n * The JSON LIST fields (`sources`, `tracedInput`, `guardrailHits`,\n * `servedTo`) are non-nullable with a `[]` default, so no reader has to\n * distinguish \"null\" from \"empty\" before iterating; the single-object\n * `verdict` stays nullable, where `null` really does mean \"not evaluated\".\n *\n * T22 additions (all nullable — absent until the field's own write path\n * runs):\n * - `generatedMessageCount`/`generatedLastMessageAt` — a snapshot of\n * `Conversation.messageCount`/`lastMessageAt` taken by `process-response`\n * right before `runTicket`'s resumed run. `handle-approval` rebuilds a\n * placeholder `Conversation` for the `act` node's `generatedFrom`\n * argument out of exactly these two fields (plus `channel`) — see\n * `functions/handle-approval.ts` for why `act` never reads anything else\n * off that snapshot. This is a \"close enough\" generation-time reading,\n * not a live one: `act` always re-reads the conversation for real before\n * posting (I8), so a slightly stale baseline here only affects whether\n * THAT re-read counts as diverged, never send safety itself.\n * - `sendingAt` — when the record entered `status: 'sending'` (written by\n * the claim in `functions/claim-commit.ts`). Nothing else on this record\n * timestamps a status transition, and `sweep` needs to know how long a\n * `sending` row has been stuck to reclaim it (§3.5's 30-minute rule).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport { GENERATED_RESPONSE_STATUSES } from '../status/machine';\nimport { OUTCOMES } from '../graph/state';\nimport {\n GENERATED_RESPONSE_OBJECT_UID,\n GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_FIELD_STATUS_UID,\n GENERATED_RESPONSE_FIELD_OUTCOME_UID,\n GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n GENERATED_RESPONSE_FIELD_SOURCES_UID,\n GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n GENERATED_RESPONSE_FIELD_VERDICT_UID,\n GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n GENERATED_RESPONSE_FIELD_ERROR_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n GENERATED_RESPONSE_INDEX_TICKET_ID_UID,\n GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_INDEX_STATUS_UID,\n GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_INDEX_GENERATED_AT_UID,\n GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildGeneratedResponseRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: GENERATED_RESPONSE_OBJECT_UID,\n objectKey: 'generated-response',\n labelSingular: 'Generated response',\n labelPlural: 'Generated responses',\n description: 'A drafted reply, from pending draft through its send outcome.',\n fields: [\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n name: 'openTicketKey',\n type: FieldType.TEXT,\n label: 'Open ticket key',\n description: \"= ticketId while status is open, cleared on a terminal status. Unique — see openTicketKeyFor().\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: [...GENERATED_RESPONSE_STATUSES],\n defaultValue: 'pending',\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n name: 'triageDecisionId',\n type: FieldType.RELATION,\n label: 'Triage decision',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'triage-decision'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n name: 'channel',\n type: FieldType.SELECT,\n label: 'Channel',\n isNullable: false,\n options: ['email', 'whatsapp'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n name: 'responseText',\n type: FieldType.TEXT,\n label: 'Response text',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCES_UID,\n name: 'sources',\n type: FieldType.JSON,\n label: 'Sources',\n description: '[{name, arguments, observation}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n name: 'tracedInput',\n type: FieldType.JSON,\n label: 'Traced input',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_VERDICT_UID,\n name: 'verdict',\n type: FieldType.JSON,\n label: 'Verdict',\n description: '{verdict, confidence, reason, status}',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n name: 'guardrailHits',\n type: FieldType.JSON,\n label: 'Guardrail hits',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_OUTCOME_UID,\n name: 'outcome',\n type: FieldType.SELECT,\n label: 'Outcome',\n description:\n 'Which exit runTicket took. Nullable: rows written before 21/09/2026 carry none, and inventing one would be a stored lie.',\n isNullable: true,\n options: [...OUTCOMES],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n name: 'autoSendDecision',\n type: FieldType.SELECT,\n label: 'Auto-send decision',\n isNullable: true,\n options: ['auto', 'hold'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n name: 'followupRequired',\n type: FieldType.BOOLEAN,\n label: 'Followup required',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n name: 'servedCount',\n type: FieldType.NUMBER,\n label: 'Served count',\n isNullable: false,\n defaultValue: 0,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n name: 'servedTo',\n type: FieldType.JSON,\n label: 'Served to',\n description: '[{user, at}], capped at 500 entries. Updated via S5 ifMatch + retry.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n name: 'generatedAt',\n type: FieldType.DATE_TIME,\n label: 'Generated at',\n description: 'Backs the daily series stat.',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n name: 'expiresAt',\n type: FieldType.DATE_TIME,\n label: 'Expires at',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n name: 'sentAt',\n type: FieldType.DATE_TIME,\n label: 'Sent at',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n name: 'sentMessageId',\n type: FieldType.TEXT,\n label: 'Sent message id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n name: 'generatedMessageCount',\n type: FieldType.NUMBER,\n label: 'Generated message count',\n description: \"Conversation.messageCount snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n name: 'generatedLastMessageAt',\n type: FieldType.DATE_TIME,\n label: 'Generated last message at',\n description: \"Conversation.lastMessageAt snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n name: 'sendingAt',\n type: FieldType.DATE_TIME,\n label: 'Sending at',\n description: \"When status became 'sending' — the sweep's staleness clock (§3.5).\",\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: GENERATED_RESPONSE_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n fields: ['openTicketKey'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_STATUS_UID, fields: ['status'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n fields: ['triageDecisionId'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, fields: ['generatedAt'] },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, fields: ['expiresAt'] },\n ],\n };\n}\n","/** `response-comparison` (ex-`ResponseComparison`) — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n RESPONSE_COMPARISON_OBJECT_UID,\n RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n RESPONSE_COMPARISON_FIELD_DIFF_UID,\n RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_INDEX_TICKET_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildResponseComparisonRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: RESPONSE_COMPARISON_OBJECT_UID,\n objectKey: 'response-comparison',\n labelSingular: 'Response comparison',\n labelPlural: 'Response comparisons',\n description: \"Compares the agent's draft against what the human actually sent.\",\n fields: [\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n name: 'generatedText',\n type: FieldType.TEXT,\n label: 'Generated text',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n name: 'sentText',\n type: FieldType.TEXT,\n label: 'Sent text',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n name: 'capturedAt',\n type: FieldType.DATE_TIME,\n label: 'Captured at',\n description: 'Backs the rewrite-rate trend.',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n name: 'conversationMessages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_DIFF_UID,\n name: 'diff',\n type: FieldType.JSON,\n label: 'Diff',\n description: 'Word-by-word diff, computed at write time.',\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, fields: ['capturedAt'] },\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n ],\n };\n}\n","/** `evaluation` (ex-`Evaluation`) — spec §3.4. No indexes named for this record. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n EVALUATION_OBJECT_UID,\n EVALUATION_FIELD_AGENT_ID_UID,\n EVALUATION_FIELD_SATISFIED_UID,\n EVALUATION_FIELD_MESSAGES_UID,\n EVALUATION_FIELD_TICKET_URL_UID,\n EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildEvaluationRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: EVALUATION_OBJECT_UID,\n objectKey: 'evaluation',\n labelSingular: 'Evaluation',\n labelPlural: 'Evaluations',\n description: 'A human satisfaction verdict on an agent conversation.',\n fields: [\n {\n universalIdentifier: EVALUATION_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: EVALUATION_FIELD_SATISFIED_UID,\n name: 'satisfied',\n type: FieldType.BOOLEAN,\n label: 'Satisfied',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — the conversation the verdict is about.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: EVALUATION_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n name: 'supportUserKeyId',\n type: FieldType.TEXT,\n label: 'Support user key id',\n isNullable: true,\n },\n ],\n };\n}\n","/**\n * `diff-analysis` (ex-`DiffAnalysis`) — spec §3.4.\n *\n * `uniqueKey` is `<agentId>::<promptName>::<promptVersion>`, computed by the\n * write handler (T22+) — this definition only declares the field and its\n * unique index, the equivalent of the legacy composite uniqueness.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n DIFF_ANALYSIS_OBJECT_UID,\n DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n DIFF_ANALYSIS_FIELD_POINTS_UID,\n DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\n/** `<agentId>::<promptName>::<promptVersion>` — spec §3.4. */\nexport function diffAnalysisUniqueKey(\n agentId: string,\n promptName: string,\n promptVersion: number,\n): string {\n return `${agentId}::${promptName}::${promptVersion}`;\n}\n\nexport function buildDiffAnalysisRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: DIFF_ANALYSIS_OBJECT_UID,\n objectKey: 'diff-analysis',\n labelSingular: 'Diff analysis',\n labelPlural: 'Diff analyses',\n description: 'Correction patterns aggregated for one (agent, prompt, version).',\n fields: [\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_POINTS_UID,\n name: 'points',\n type: FieldType.JSON,\n label: 'Points',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n name: 'uniqueKey',\n type: FieldType.TEXT,\n label: 'Unique key',\n description: '<agentId>::<promptName>::<promptVersion>',\n isNullable: false,\n },\n ],\n indexes: [\n { universalIdentifier: DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, fields: ['uniqueKey'], isUnique: true },\n ],\n };\n}\n","/**\n * `pipeline-state` — spec §3.4. Singleton per app; the kit's sole inter-app\n * contact point, read-only (`exposedToApps: ['*']`), purely informational —\n * §4's cross-app view-claim warning is what another app reads `sourceViewId`\n * for, to detect when two support-kit apps have been pointed at the same\n * Gorgias view.\n *\n * `sourceViewId` here mirrors the setting of the same name (§3.6) — it is\n * written by `triage-tick` (T22+), not by this definition.\n *\n * `singletonKey` (T22 hardening, A4 — a schema addition past §3.4's frozen\n * list, recorded as a deviation in the progress doc): `triage-tick` and\n * `sweep` are two independent crons that both fire every five minutes, and\n * on a fresh app both used to find the `list()` empty and both `create()` a\n * \"singleton\" row — nothing enforced only one existing, and `list` carries\n * no ordering guarantee, so `triage-tick` could thereafter read the\n * sweep-created row (no `lastTriageAt`) and silently skip its own cadence\n * gate on EVERY tick. A constant, always-the-same value plus a real unique\n * index turns \"singleton by convention\" into \"singleton by constraint\": the\n * first write goes through `upsert` on this key\n * (`functions/pipeline-state.ts`), so the platform's own `ON CONFLICT` — not\n * a race between two `list()`+`create()` pairs — is what decides there is\n * exactly one row. Subsequent writes go through `update()`, because `upsert`\n * REPLACES the document rather than merging it; see that module's own doc.\n */\nimport { FieldType } from '@apotech-os/app-kit';\nimport type { RecordDef } from './record-def';\nimport {\n PIPELINE_STATE_OBJECT_UID,\n PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n PIPELINE_STATE_INDEX_SINGLETON_KEY_UID,\n} from './ids';\n\nexport const pipelineStateRecord: RecordDef = {\n universalIdentifier: PIPELINE_STATE_OBJECT_UID,\n objectKey: 'pipeline-state',\n labelSingular: 'Pipeline state',\n labelPlural: 'Pipeline state',\n description: 'Singleton run-cadence and view-claim state, readable by every installed app.',\n fields: [\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n name: 'singletonKey',\n type: FieldType.TEXT,\n label: 'Singleton key',\n description: 'Always the same constant value — the unique index below is what makes this record a true singleton, not just a convention.',\n isNullable: false,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n name: 'sourceViewId',\n type: FieldType.TEXT,\n label: 'Source view id',\n description: 'The claimed Gorgias view — supports the cross-app overlap warning (§4).',\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n name: 'lastTriageAt',\n type: FieldType.DATE_TIME,\n label: 'Last triage at',\n description: \"Gates triage-tick's cadence.\",\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n name: 'lastSweepAt',\n type: FieldType.DATE_TIME,\n label: 'Last sweep at',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ['singletonKey'], isUnique: true }],\n exposedToApps: ['*'],\n};\n","/**\n * `prompt-cache` (ex-`PromptCache`) — spec §3.4, level-2 fallback of the\n * prompt ladder (§3.7).\n *\n * `config JSON?` — added beyond the spec's literal field list, on T19's\n * explicit deferral: the legacy cache carried the model config (not just the\n * compiled template), so invariant I16 (\"levels 2/3 keep working through a\n * Langfuse outage\") holds for the *prompt text* but not for the *config* a\n * caller needs alongside it — levels 2 and 3 of the resolver (T19) return\n * `config: null` today. Adding the column here is the minimal step: it makes\n * the record ABLE to carry a config without deciding its shape or wiring it\n * into the resolver. Follow-up (not T20): change `prompts/resolver.ts` to\n * read and write this column, and settle what \"config\" means for a cache row\n * (presumably the same `{model, reasoning}` shape used by `settings.nodes`).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n PROMPT_CACHE_OBJECT_UID,\n PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n PROMPT_CACHE_FIELD_CONTENT_UID,\n PROMPT_CACHE_FIELD_VERSION_UID,\n PROMPT_CACHE_FIELD_LABEL_UID,\n PROMPT_CACHE_FIELD_CONFIG_UID,\n PROMPT_CACHE_INDEX_PROMPT_KEY_UID,\n} from './ids';\n\nexport const promptCacheRecord: ObjectDef = {\n universalIdentifier: PROMPT_CACHE_OBJECT_UID,\n objectKey: 'prompt-cache',\n labelSingular: 'Prompt cache entry',\n labelPlural: 'Prompt cache entries',\n description: 'Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.',\n fields: [\n {\n universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n name: 'promptKey',\n type: FieldType.TEXT,\n label: 'Prompt key',\n description: \"'name' or 'name::label'.\",\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n description: 'Raw, uncompiled template.',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,\n name: 'version',\n type: FieldType.NUMBER,\n label: 'Version',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,\n name: 'label',\n type: FieldType.TEXT,\n label: 'Label',\n isNullable: true,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,\n name: 'config',\n type: FieldType.JSON,\n label: 'Config',\n description: 'Model config snapshot, for I16. Not yet written or read — see module doc.',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ['promptKey'], isUnique: true }],\n};\n","import { createHash } from 'node:crypto';\n\n/**\n * Kit-owned namespace UUID (RFC 4122 §4.3) — fixed and arbitrary, used only\n * as `deriveUid`'s namespace input. Never written to a manifest itself.\n */\nconst SUPPORT_KIT_UID_NAMESPACE = '2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f';\n\nfunction uuidToBytes(uuid: string): Buffer {\n return Buffer.from(uuid.replace(/-/g, ''), 'hex');\n}\n\nfunction bytesToUuid(bytes: Buffer): string {\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * A deterministic UUIDv5 over `seed` (RFC 4122 §4.3: SHA-1 of a namespace +\n * a name, with the version/variant bits fixed up). Same seed always yields\n * the same uid — no randomness, no `Date` — and different seeds yield\n * different uids with cryptographic collision resistance.\n *\n * Used by `scopeRecordToApp` (B1, T25 review) to turn the kit's own stable\n * per-record constants (`ids.ts`) into uids that are additionally scoped to\n * the consuming app's slug, so two different apps installing the same kit\n * never collide on `AppEntity.universalIdentifier` (globally unique on the\n * platform, not per application).\n */\nexport function deriveUid(seed: string): string {\n const hash = createHash('sha1').update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, 'utf8').digest();\n const bytes = hash.subarray(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x50; // version 5\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant RFC4122\n return bytesToUuid(bytes);\n}\n","import { deriveUid } from './derive-uid';\nimport type { RecordDef } from './record-def';\n\n/**\n * Rewrites every `universalIdentifier` in a kit record (object, fields,\n * indexes) from the kit's own stable constant (`ids.ts`) into one\n * deterministically derived from `(slug, that constant)` — B1, T25 review.\n *\n * Why: `ids.ts`'s constants are unique AMONG THEMSELVES, but the platform's\n * `AppEntity.universalIdentifier` is unique GLOBALLY, not per application\n * (`apps/api/prisma/schema.prisma`). Used as-is, the second app to install\n * this kit republishes the same 126 literals the first app already claimed\n * and hits an unhandled Prisma P2002 on publish. Scoping by slug keeps every\n * uid stable across rebuilds (pure function of the slug + the constant, no\n * randomness) while making two different consuming apps' uid sets disjoint.\n */\nexport function scopeRecordToApp(slug: string, record: RecordDef): RecordDef {\n return {\n ...record,\n universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),\n fields: record.fields.map((field) => ({\n ...field,\n universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`),\n })),\n indexes: record.indexes?.map((index) => ({\n ...index,\n universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`),\n })),\n };\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.4 — the kit's own\n// `ObjectDef` fragments, one module per record, assembled here into the\n// array a consuming app's manifest spreads into its own `records: [...]`.\n//\n// Every record that declares a RELATION is a factory over the consuming\n// app's slug (§3.2's `config.slug`), because a relation's `targetRef` is\n// `app:<slug>/<objectKey>` and the kit is installed as `experience-client`,\n// `pro-sante`, … — never as `support-kit`. The four records with no\n// relation stay plain constants: nothing about them varies per app.\nexport { buildCategoryRecord } from './category';\nexport { categoryGroupRecord } from './category-group';\nexport { agentRecord, AGENT_STATUSES, DEFAULT_LLM_PROVIDER, type AgentStatus } from './agent';\nexport { buildTriageDecisionRecord } from './triage-decision';\nexport { buildGeneratedResponseRecord } from './generated-response';\nexport { buildResponseComparisonRecord } from './response-comparison';\nexport { buildEvaluationRecord } from './evaluation';\nexport { buildDiffAnalysisRecord, diffAnalysisUniqueKey } from './diff-analysis';\nexport { pipelineStateRecord } from './pipeline-state';\nexport { promptCacheRecord } from './prompt-cache';\nexport { targetRefFor } from './target-ref';\nexport type { RecordDef } from './record-def';\n\nimport { buildCategoryRecord } from './category';\nimport { categoryGroupRecord } from './category-group';\nimport { agentRecord } from './agent';\nimport { buildTriageDecisionRecord } from './triage-decision';\nimport { buildGeneratedResponseRecord } from './generated-response';\nimport { buildResponseComparisonRecord } from './response-comparison';\nimport { buildEvaluationRecord } from './evaluation';\nimport { buildDiffAnalysisRecord } from './diff-analysis';\nimport { pipelineStateRecord } from './pipeline-state';\nimport { promptCacheRecord } from './prompt-cache';\nimport { scopeRecordToApp } from './scope-to-app';\nimport type { RecordDef } from './record-def';\n\n/**\n * All 10 records of §3.4, in the order the spec lists them, bound to the\n * consuming app's `slug` — the single assembly point `buildSupportPipeline`\n * (T25) spreads into a manifest.\n *\n * Every record/field/index `universalIdentifier` is additionally scoped to\n * `slug` via `scopeRecordToApp` (B1, T25 review): `ids.ts`'s constants are\n * stable per-record keys, not final manifest uids — two different consuming\n * apps installing this kit must never publish the same\n * `AppEntity.universalIdentifier` (unique platform-wide).\n */\nexport function buildSupportKitRecords(slug: string): RecordDef[] {\n return [\n buildCategoryRecord(slug),\n categoryGroupRecord,\n agentRecord,\n buildTriageDecisionRecord(slug),\n buildGeneratedResponseRecord(slug),\n buildResponseComparisonRecord(slug),\n buildEvaluationRecord(slug),\n buildDiffAnalysisRecord(slug),\n pipelineStateRecord,\n promptCacheRecord,\n ].map((record) => scopeRecordToApp(slug, record));\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 // 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 * Two 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) and\n * `statsTimezone` (a §3.8 rendering concern). `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 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 * `SupportKitFunctionConfig` — what each manifest fragment\n * (`triage-tick`/`sweep`/`handle-approval`/…) needs to build its\n * `FunctionDef` (spec §3.2's `SupportPipelineConfig`, the slice of it these\n * fragments actually read — `buildSupportPipeline`, T25, owns the full\n * shape and passes this down).\n */\nimport type { PromptNameConfig } from '../prompts/slots';\n\n/** Stable keys this module looks up `identifiers` by — documented here so a caller can't guess wrong. */\nexport const FUNCTION_IDENTIFIER_KEYS = [\n // Single-pass (2026-09): 'process-response' left this list — the response\n // phase now runs inside triage-tick's own batch, not as a dbEvent worker.\n // A consuming app may still pass the old identifier; extra entries are\n // ignored, only missing ones throw.\n 'triage-tick',\n 'sweep',\n 'handle-approval',\n // T23 — the seven operator `uiInvoke` functions (§3.5's table).\n 'run-triage-now',\n // B5 — the event-triggered worker `run-triage-now` hands the batch to, so\n // the manual trigger answers inside its `uiInvoke` budget instead of\n // 504-ing halfway through a 30-ticket LLM pass (`run-triage-now.ts`'s doc).\n 'run-triage-batch',\n // Single-pass follow-up — the ticket panel's \"discard this draft\" action,\n // freeing the ticket for a full re-treatment (invalidate-response.ts).\n 'invalidate-response',\n 'preview-triage',\n // spec-vue-tickets-unifiee-v1 §4.2 — the ticket timeline's last-resort\n // conversation read, for the decisions no `generated-response` was ever\n // opened for (a ticket stopped at the tag) and the imported ones.\n 'get-ticket-conversation',\n 'graph-dry-run',\n 'test-agents',\n 'suggest-prompt',\n 'list-gorgias-views',\n // T26 rework — AgentsPage cannot create a valid agent or promote a default\n // one from raw record PATCHes alone (BLOCKER 3, BLOCKER 4); both are\n // write-handler concerns per records/agent.ts's own doc.\n 'create-agent',\n 'set-default-agent',\n // T27 part B — SharedPromptsPage's own write path: validates\n // `@@@langfusePrompt:…@@@` composition (`validateReferences`) before\n // writing a `shared/*` version, a check the raw S3 REST route does not run.\n 'create-shared-prompt-version',\n // §5.2 — `GET /models` serves `system_prompt` from `systemPromptSnapshot`\n // alone, so that snapshot has to be refreshed whenever a new version of an\n // agent's prompt starts being served.\n 'sync-agent-prompt-snapshot',\n // T24 — the six reserved `ext-*` functions (§5.2), the extension gateway's\n // only view of the kit.\n 'ext-models',\n 'ext-categories',\n 'ext-chat',\n 'ext-fast-response-check',\n 'ext-evaluation',\n 'ext-response-comparison',\n] as const;\n\nexport type FunctionIdentifierKey = (typeof FUNCTION_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitFunctionConfig extends PromptNameConfig {\n /** The consuming app's own slug — `app:<slug>/<objectKey>` dbEvent triggers, and the object relations. */\n slug: string;\n /**\n * §3.2's `SupportPipelineConfig.identifiers` — one `universalIdentifier`\n * per manifest function, keyed by the values in `FUNCTION_IDENTIFIER_KEYS`.\n * A manifest fragment with a missing id is broken by construction: looking\n * one up throws immediately rather than inventing a random one that would\n * drift on every rebuild.\n */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry (a broken manifest, not a runtime condition to recover from). */\nexport function identifierFor(config: SupportKitFunctionConfig, key: FunctionIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportKitFunctionConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit function needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * Derives the kit's domain `Conversation` from the SINGLE\n * `getTicketWithContext` fetch (`ctx-ports.ts`'s\n * `createGorgiasConversationPort`; B, T21 review), which returns both:\n *\n * - the RAW payload the guardrail detectors need (`isWhatsappTicket`,\n * `isJudgemeTicket`, `isAutomatedSenderTicket`, `isTicketClosed`,\n * `hasCustomerAttachment` — `guardrails/raw-ticket.ts`) and this\n * module's own message-count/timestamp snapshot.\n * - the ALREADY-EXTRACTED chronological messages + customer-info block a\n * node actually drafts against — its HTML-to-text conversion and\n * \"Information Client\" synthetic prefix are Gorgias-specific rendering\n * this package does not re-derive.\n *\n * `getRawTicket` and `buildTicketContext` used to be called as two separate\n * actions reading the exact same Gorgias endpoint (§S1) — a `read()` call\n * paid for it twice, and worse, the two fetches could observe different\n * server states if a message landed between them. `getTicketWithContext`\n * (`@wopilo/gorgias-client`) fetches once and derives both halves from that\n * one payload, so the raw-based facts and the domain conversation are now\n * GUARANTEED — not just assumed — to describe the exact same server\n * response.\n */\nimport {\n hasCustomerAttachment,\n isTicketClosed,\n isWhatsappChevronNote,\n isWhatsappTicket,\n type RawTicket,\n} from '../guardrails';\nimport type { Conversation, ConversationRef, Message } from '../domain';\n\ntype RawMessage = NonNullable<RawTicket['messages']>[number];\n\n/** One turn of `buildTicketContext`'s already-extracted conversation. */\nexport interface RawTicketContextMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n synthetic?: boolean;\n}\n\n/** The shape `ctx.api.integrations.run('gorgias', 'buildTicketContext', …)` returns. */\nexport interface RawTicketContext {\n messages: RawTicketContextMessage[];\n customerContext: string | null;\n customerName?: string | null;\n customerEmail?: string | null;\n}\n\n/**\n * Same predicate `guardrails/raw-ticket.ts` uses internally, un-exported\n * there. Duplicated here BY HAND, same precedent that module's own doc\n * gives for its copy of `@wopilo/gorgias-client`'s `isInternalNoteChannel`:\n * this package may not import that client, so the one-line rule is kept in\n * sync manually rather than reached for through a forbidden import.\n */\nfunction isInternalNoteChannel(message: RawMessage): boolean {\n return message.channel === 'internal-note' || message.source?.type === 'internal-note';\n}\n\n/**\n * Port of `@wopilo/gorgias-client`'s `countableMessages` (`ticket-context.ts`)\n * — the divergence-snapshot rule. This package cannot import that package\n * (dependency-allowlist), so it is kept in sync by hand.\n *\n * \"Has extractable text\" checks PRESENCE across `body_text`/`body_html`/\n * `stripped_text`/`stripped_html` — not conversion. The client's own\n * `extractMessageText` prefers HTML and runs it through `htmlToText`\n * (T3-review-A5: an HTML-only customer reply has a blank `body_text`, so\n * checking that field alone misses a real turn — invisible to\n * `Conversation.messageCount`/`lastMessageAt`, so `act`'s divergence check\n * never sees the customer replied and a stale draft gets auto-sent). This\n * package cannot port `htmlToText` in, so it stays on the SAFE side instead:\n * any non-blank field counts, even a `<br>`-only body that `htmlToText`\n * would reduce to nothing. That can only ever over-count — producing a\n * spurious *hold*, never a spurious send.\n */\nfunction countableMessages(messages: RawMessage[], isWhatsapp: boolean): RawMessage[] {\n return messages.filter((m) => {\n if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);\n const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());\n const hasAttachment = (m.attachments?.length ?? 0) > 0;\n return hasText || hasAttachment;\n });\n}\n\nexport interface ConversationSnapshot {\n count: number;\n lastAt: Date | null;\n}\n\n/** Message count + last-message timestamp — feeds `Conversation.messageCount`/`lastMessageAt` (I8's anti-divergence snapshot). */\nexport function snapshotConversation(raw: RawTicket): ConversationSnapshot {\n const isWhatsapp = isWhatsappTicket(raw);\n const messages = countableMessages(raw.messages ?? [], isWhatsapp);\n let lastAt: Date | null = null;\n for (const m of messages) {\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!lastAt || at > lastAt) lastAt = at;\n }\n return { count: messages.length, lastAt };\n}\n\n/**\n * When an agent (human or our own auto-reply) last spoke. Deliberately\n * applies NO countability/text test of its own — it follows\n * `raw-ticket.ts`'s `hasAgentReplySince` (channel/chevron rule only),\n * generalised from a boolean since-a-date check to the timestamp itself,\n * since `Conversation.lastAgentReplyAt` needs the value, not a threshold.\n * That is the safe direction: an agent message with no extractable text\n * still counts as \"the agent spoke\", so this never under-reports the last\n * agent activity.\n */\nfunction lastAgentReplyAtOf(raw: RawTicket): Date | null {\n const isWhatsapp = isWhatsappTicket(raw);\n let latest: Date | null = null;\n for (const m of raw.messages ?? []) {\n if (m.from_agent !== true) continue;\n if (isInternalNoteChannel(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!latest || at > latest) latest = at;\n }\n return latest;\n}\n\n/**\n * Assembles the domain `Conversation`. `sourceChannel` honours the T15\n * contract restated in `graph/ports.ts`'s `Conversation` doc: `'whatsapp'`\n * IFF `isWhatsappTicket(raw)`, never a bare `raw.channel` read.\n */\nexport function toConversation(ref: ConversationRef, raw: RawTicket, context: RawTicketContext): Conversation {\n const snapshot = snapshotConversation(raw);\n const messages: Message[] = context.messages\n .filter((m): m is RawTicketContextMessage & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')\n .map((m) => ({ role: m.role, content: m.content }));\n\n return {\n ref,\n subject: raw.subject ?? null,\n messages,\n customer: {\n name: context.customerName ?? null,\n email: context.customerEmail ?? null,\n orderContext: context.customerContext ?? null,\n },\n isClosed: isTicketClosed(raw),\n lastMessageAt: snapshot.lastAt,\n messageCount: snapshot.count,\n lastAgentReplyAt: lastAgentReplyAtOf(raw),\n hasCustomerAttachment: hasCustomerAttachment(raw),\n sourceChannel: isWhatsappTicket(raw) ? 'whatsapp' : (raw.channel ?? null),\n };\n}\n","/**\n * Shared by `ctx-ports.ts`'s real `StatePort.record` and\n * `recording-ports.ts`'s no-op one: the exact tag SET a triage decision\n * materialises, ported from legacy `ClassificationSink.record`\n * (`[category, ...extraTags, handledTag]`, deduplicated). Both need the\n * IDENTICAL computation — the recording port's whole point is to report the\n * tags production WOULD have applied, so a second, drifting copy here would\n * silently defeat that guarantee.\n *\n * The category lookup (`api.list('category', …)`) is a READ, not a write —\n * both the real and the recording `StatePort` perform it for real; only the\n * final `applyTags` call is what the recording port skips.\n */\nimport type { AuditTags } from '../graph/ports';\nimport type { Classification } from '../domain';\nimport type { SupportKitApi } from './api';\n\n/** Trims and deduplicates, in first-seen order, dropping blank entries. */\nexport function dedupeTagNames(tags: ReadonlyArray<string | null | undefined>): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const tag of tags) {\n const trimmed = (tag ?? '').trim();\n if (trimmed && !seen.has(trimmed)) {\n seen.add(trimmed);\n out.push(trimmed);\n }\n }\n return out;\n}\n\n/** The category's own additional tags, resolved by `tagName` — `[]` when no category matches. */\nasync function extraTagsFor(api: SupportKitApi, tagName: string): Promise<string[]> {\n const page = await api.list('category', { filter: { tagName }, limit: 1 });\n const data = page.items[0]?.data as { extraTags?: string[] } | undefined;\n return data?.extraTags ?? [];\n}\n\n/** The deduplicated tag set a triage decision applies: `[category, ...extraTags, handledTag]`. */\nexport async function resolveHandledTags(\n api: SupportKitApi,\n classification: Classification,\n audit: AuditTags,\n): Promise<string[]> {\n const extraTags = await extraTagsFor(api, classification.category);\n return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);\n}\n","/**\n * Real port implementations on `ctx` (spec §3.3 `adapters/ctx-ports.ts`):\n * Conversation/Reply/State via `ctx.api.integrations.run('gorgias', …)`\n * (S1), Llm via `ctx.api.llm.complete` v2 (S2), Prompt via §3.7's resolver\n * (T19), Clock over the real `Date`.\n *\n * `StatePort` deviation, kept from `graph/ports.ts`'s own header comment:\n * §3.3's table names it \"records\", but its actual traffic here is Gorgias\n * tag/rename calls (`applyTags`/`renameTicket`) — S1 integration writes, not\n * an AppRecord write. The one genuine AppRecord read in this file is\n * `StatePort.record`'s category `extraTags` lookup (`gorgias-tags.ts`).\n */\nimport type {\n ChatMessage,\n ClockPort,\n CompletionRequest,\n CompletionResult,\n ConversationPort,\n LlmPort,\n OutboundReply,\n PromptPort,\n ReplyPort,\n StatePort,\n} from '../graph/ports';\nimport type { ConversationRef } from '../domain';\nimport type { PlatformPromptReader, PromptCachePort, PromptDegradedEvent } from '../prompts/resolver';\nimport { createPromptResolver } from '../prompts/resolver';\nimport type { RawTicket } from '../guardrails';\nimport type { SupportKitApi } from './api';\nimport { toConversation, type RawTicketContext } from './conversation-mapping';\nimport { resolveHandledTags } from './gorgias-tags';\n\nfunction asRawTicket(value: unknown): RawTicket {\n return (value ?? {}) as RawTicket;\n}\n\n// --- ConversationPort --------------------------------------------------------\n\nexport function createGorgiasConversationPort(api: SupportKitApi): ConversationPort {\n return {\n async listPending(source, limit) {\n const tickets = (await api.integrations.run('gorgias', 'fetchTicketsFromView', {\n viewId: source.viewOrTag,\n limit,\n })) as Array<{ id: string | number }>;\n return tickets.map((t) => ({ id: String(t.id), channel: 'gorgias' as const }));\n },\n\n async read(ref: ConversationRef) {\n // ONE fetch (B, T21 review): `getTicketWithContext`\n // (@wopilo/gorgias-client) reads `GET /tickets/:id/` once and derives\n // both the raw payload and the extracted context from that single\n // response — see `conversation-mapping.ts`'s module doc. This used to\n // be two separate actions hitting the same endpoint in parallel,\n // which not only doubled the round trips but let the two halves\n // observe different server states if a message landed between them.\n const result = (await api.integrations.run('gorgias', 'getTicketWithContext', {\n ticketId: ref.id,\n })) as { ticket: unknown; context: RawTicketContext } | null;\n return toConversation(ref, asRawTicket(result?.ticket), result?.context ?? { messages: [], customerContext: null });\n },\n };\n}\n\n// --- ReplyPort ---------------------------------------------------------------\n\n/**\n * `OutboundReply.idempotencyKey` is NOT forwarded: neither `replyEmail` nor\n * `postWhatsappNote` accept it (Gorgias has no idempotency-key concept — see\n * `ReplyPort.post`'s own doc, \"NOT by channel idempotence\"). At-most-once is\n * already guaranteed upstream by the claim→post→commit state machine (I9);\n * this field exists for a FUTURE channel that does support one.\n */\nexport function createGorgiasReplyPort(api: SupportKitApi): ReplyPort {\n return {\n async post(ref: ConversationRef, reply: OutboundReply) {\n if (reply.mode === 'email') {\n const result = (await api.integrations.run('gorgias', 'replyEmail', {\n ticketId: ref.id,\n bodyHtml: reply.bodyHtml,\n bodyText: reply.bodyText,\n senderEmail: reply.fromAddress,\n toAddress: reply.receiverEmail,\n ...(reply.subject !== null ? { subject: reply.subject } : {}),\n ...(reply.receiverName !== null ? { receiverName: reply.receiverName } : {}),\n })) as { messageId: string };\n return { messageId: result.messageId };\n }\n const result = (await api.integrations.run('gorgias', 'postWhatsappNote', {\n ticketId: ref.id,\n text: reply.bodyText,\n })) as { messageId: string };\n return { messageId: result.messageId };\n },\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport function createGorgiasStatePort(api: SupportKitApi): StatePort {\n return {\n async record(ref, classification, audit) {\n const names = await resolveHandledTags(api, classification, audit);\n if (names.length === 0) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names });\n },\n async rename(ref, subject) {\n await api.integrations.run('gorgias', 'renameTicket', { ticketId: ref.id, subject });\n },\n async flag(ref, tag) {\n const trimmed = tag.trim();\n if (!trimmed) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names: [trimmed] });\n },\n };\n}\n\n// --- LlmPort ---------------------------------------------------------------\n\n/**\n * `ctx.api.llm.complete` v2 carries no `tool`-role message and no `tools`\n * parameter (S2's surface, `app-api-client.ts`) — §6.2's tool loop has no\n * platform surface to run on YET. This is NOT dead ground: `graph/draft.ts`\n * already calls `buildToolSpecs(profile)` and populates `CompletionRequest\n * .tools` on every round, and already pushes `role: 'tool'` turns once the\n * model asks for one. Nothing in `draft.ts` gates on this adapter's\n * capabilities — what currently keeps `req.tools` empty is\n * `settings/to-profile.ts` hardcoding `tools: []` (\"default-deny until\n * T22\"). The moment that allowlist is populated, `complete()` below would\n * silently drop `req.tools` (this surface has nothing to forward it to) and\n * this port would keep returning `toolCalls: []` regardless of what the\n * model was asked to use — the loop terminates on round one, degraded: no\n * order lookup, no tracking lookup, `Draft.sources` empty, every\n * provenance display blank, the most expensive node hallucinating order\n * facts instead of fetching them. Silently, with no error anywhere.\n *\n * `complete()` below refuses that outcome outright: a request that asks for\n * tools throws, naming the missing surface, so enabling the allowlist\n * degrades loudly (a thrown error) rather than loudly-nothing. See\n * docs/plans/2026-09-02-gorgias-migration-progress.md for the spec gap this\n * leaves for T22 / the spec owner to close (S2 needs a tools/toolCalls\n * surface, or draft's `maxToolCalls` needs to go).\n */\nfunction toPlatformMessage(msg: ChatMessage): { role: 'system' | 'user' | 'assistant'; content: string } {\n // Reachable only once `req.tools` stops being empty (the guard below\n // throws before that point today) — kept exhaustive over `ChatMessage`\n // for type safety, not because production traffic hits these branches.\n if (msg.role === 'tool') return { role: 'user', content: msg.content };\n if (msg.role === 'assistant') return { role: 'assistant', content: msg.content ?? '' };\n return { role: msg.role, content: msg.content };\n}\n\n/** S2's `trace`, as a named type so a handler can build one without reaching into `CompletionRequest`. */\nexport type RunTrace = NonNullable<CompletionRequest['trace']>;\n\n/**\n * `trace` is stamped on every completion this port makes, unless the request\n * carries its own. The legacy grouped one ticket's calls under a single\n * Langfuse session — draft, evaluation and revision read as one conversation\n * instead of a handful of orphan generations — which is what makes a trace\n * navigable when a correction has to be traced back to what produced it\n * (§3.4's quality loop). Omitting it keeps today's untraced behaviour.\n */\nexport function createPlatformLlmPort(api: SupportKitApi, trace?: RunTrace): LlmPort {\n return {\n async complete(req: CompletionRequest): Promise<CompletionResult> {\n // Mirrors `FakeLlm`: an already-aborted signal fails before the\n // platform is reached — `ctx.api.llm.complete` takes no `signal` of\n // its own (I14's deadline is enforced by `budget`/the caller instead).\n if (req.signal?.aborted) {\n throw Object.assign(new Error('Request was aborted.'), { name: 'AbortError' });\n }\n\n // Fail loudly rather than silently ground the model (see the module\n // doc above): `ctx.api.llm.complete` v2 has no tool-calling surface,\n // so honouring `req.tools` here would mean dropping it on the floor.\n if (req.tools?.length) {\n throw new Error(\n 'createPlatformLlmPort: ctx.api.llm.complete v2 has no tool-calling surface (no `tools` parameter, no `role: \\'tool\\'` message) — cannot honour CompletionRequest.tools.',\n );\n }\n\n // A per-request `trace` wins over the port's own: a node that names\n // its own session knows something this port does not.\n const runTrace = req.trace ?? trace;\n const result = await api.llm.complete({\n messages: req.messages.map(toPlatformMessage),\n options: {\n model: req.model,\n reasoningEffort: req.reasoning,\n ...(req.responseSchema !== undefined\n ? { responseSchema: { name: req.label, schema: req.responseSchema as Record<string, unknown> } }\n : {}),\n },\n // `req.promptRef` (including `resolve`, see `CompletionRequest.promptRef`'s\n // own doc) is forwarded WHOLESALE — every caller in this package now\n // sets `resolve: false`, so this pass-through needs no code change of\n // its own to carry the new field; it already carries whatever shape\n // `CompletionRequest.promptRef` has.\n ...(req.promptRef ? { promptRef: req.promptRef } : {}),\n ...(runTrace ? { trace: runTrace } : {}),\n });\n\n return {\n text: result.text ?? null,\n // No tool-calling support on this surface today — see the module\n // doc above.\n toolCalls: [],\n usage: { input: result.usage.inputTokens, output: result.usage.outputTokens, reasoning: 0 },\n ...(result.traceId ? { traceId: result.traceId } : {}),\n ...(result.observationId ? { observationId: result.observationId } : {}),\n };\n },\n };\n}\n\n// --- PromptPort (§3.7 seams) -------------------------------------------------\n\n/** `PlatformPromptReader` over T5's `ctx.api.prompts.get(name, {label|version, resolve:false})` (T19's seam). */\nexport function createPlatformPromptReader(api: SupportKitApi): PlatformPromptReader {\n return {\n async get(name, ref) {\n const detail = await api.prompts.get(name, { ...ref, resolve: false });\n return { version: detail.version, content: detail.content, config: detail.config ?? null };\n },\n };\n}\n\n/** `PromptCachePort` over the `prompt-cache` record (T20's schema, T19's seam). */\nexport function createRecordPromptCachePort(api: SupportKitApi): PromptCachePort {\n return {\n async read(key) {\n const page = await api.list('prompt-cache', { filter: { promptKey: key }, limit: 1 });\n const data = page.items[0]?.data as { content: string; version: number } | undefined;\n return data ? { content: data.content, version: data.version } : null;\n },\n async write(key, entry) {\n await api.upsert(\n 'prompt-cache',\n [{ data: { promptKey: key, content: entry.content, version: entry.version } }],\n { uniqueBy: ['promptKey'] },\n );\n },\n };\n}\n\n/**\n * Assembles the real `PromptPort`: T19's resolver over the two seams above,\n * with `onDegraded` routed to the caller's logger (post-T19-review E) — the\n * kit carries no logging port of its own, so a silent-degradation event\n * (Langfuse down, cache down, a broken composition tag) would otherwise be\n * indistinguishable from a correct run.\n */\nexport function createPlatformPromptPort(api: SupportKitApi, log: (message: string) => void): PromptPort {\n return createPromptResolver({\n platform: createPlatformPromptReader(api),\n cache: createRecordPromptCachePort(api),\n onDegraded: (event: PromptDegradedEvent) => log(`prompt resolution degraded [${event.stage}] ${event.name}: ${event.reason}`),\n });\n}\n\n// --- ClockPort ---------------------------------------------------------------\n\nexport function createRealClock(): ClockPort {\n return { now: () => new Date() };\n}\n","/**\n * Recording ports for the dry-run replay (spec §3.3 `adapters/\n * recording-ports.ts`, §3.5's `graph-dry-run` row), ported from legacy\n * `services/graphDryRun.ts`'s `meta`/`sink`/`reply`/`recordingGateway`.\n *\n * The guarantee (§0's arbitrage, restated in §3.5): dry-run replays the\n * COMPLETE graph — every node, LLM included — but reaches ZERO external\n * action. `ReplyPort.post` and `StatePort.record`/`rename`/`flag` are\n * replaced here by recorders that never call Gorgias; `ConversationPort`,\n * `LlmPort` and `PromptPort` stay the REAL `ctx-ports.ts` adapters — a dry\n * run reads and thinks for real, it just never writes.\n *\n * `state.record`'s READ half (the category's `extraTags`, via\n * `gorgias-tags.ts`) still runs for real, so `wouldHaveTagged` reports the\n * EXACT tag set production would apply — only the final `applyTags` call is\n * skipped, by construction (there is no write call left to make).\n */\nimport type { AuditTags, CompletionRequest, LlmPort, OutboundReply, ReplyPort, StatePort, ToolCallRequest } from '../graph/ports';\nimport type { Classification, Usage } from '../domain';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitApi } from './api';\nimport { resolveHandledTags } from './gorgias-tags';\n\n// --- ReplyPort ---------------------------------------------------------------\n\nexport interface WouldHaveReplied {\n subject: string | null;\n body: string;\n}\n\nexport interface RecordingReplyPort {\n port: ReplyPort;\n /** The reply the run WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied(): WouldHaveReplied | null;\n}\n\nexport function createRecordingReplyPort(): RecordingReplyPort {\n let wouldHaveReplied: WouldHaveReplied | null = null;\n return {\n port: {\n async post(_ref, reply: OutboundReply) {\n wouldHaveReplied = { subject: reply.mode === 'email' ? reply.subject : null, body: reply.bodyText };\n // A message id `act` can commit — nothing left the building.\n return { messageId: 'dry-run' };\n },\n },\n wouldHaveReplied: () => wouldHaveReplied,\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport interface RecordingStatePort {\n port: StatePort;\n /** Tags the run WOULD have applied, in first-seen order. Nothing was applied. */\n wouldHaveTagged(): string[];\n}\n\nexport function createRecordingStatePort(api: SupportKitApi): RecordingStatePort {\n const tagged: string[] = [];\n const push = (tag: string): void => {\n const trimmed = tag.trim();\n if (trimmed && !tagged.includes(trimmed)) tagged.push(trimmed);\n };\n\n return {\n port: {\n async record(_ref, classification: Classification, audit: AuditTags) {\n const names = await resolveHandledTags(api, classification, audit);\n names.forEach(push);\n },\n async rename() {\n // A dry run renames nothing.\n },\n async flag(_ref, tag) {\n push(tag);\n },\n },\n wouldHaveTagged: () => [...tagged],\n };\n}\n\n// --- SendPort recorder (claim -> post -> commit persistence seam, I9) ------\n\ntype ClaimedSend = Extract<NodeDeps['send'], { mode: 'claimed' }>;\n\nexport interface RecordingSendPort {\n send: ClaimedSend;\n /** Every claim/commit call, in order — a dry run must never let these reach real persistence. */\n calls: Array<{ surface: 'send.claim' | 'send.commit'; args: readonly unknown[] }>;\n}\n\n/**\n * Recording `{mode: 'claimed'}` seam (post-T21-review C): when a production\n * dry run wires `deps.send` to `{mode: 'claimed'}` (the `act` node's own\n * gate — see its module doc), THIS package had no recording counterpart, so\n * nothing stopped that dry run's claim/commit calls from writing real rows.\n * `claim` always resolves `true` (a dry run never loses a contest — there is\n * nothing to contest), `commit` no-ops: neither touches persistence.\n */\nexport function createRecordingSendPort(): RecordingSendPort {\n const calls: RecordingSendPort['calls'] = [];\n return {\n calls,\n send: {\n mode: 'claimed',\n async claim(run) {\n calls.push({ surface: 'send.claim', args: [run] });\n return true;\n },\n async commit(messageId) {\n calls.push({ surface: 'send.commit', args: [messageId] });\n },\n },\n };\n}\n\n// --- The pair a production dry run substitutes ------------------------------\n\n/**\n * Swaps the two ports that can reach Gorgias — `reply` and `state` — for\n * their recorders, leaving every READ port (conversation, llm, prompt) and\n * the clock untouched.\n *\n * This is the `settings.dryRun` seam for the PRODUCTION pipeline\n * (`functions/triage-tick.ts`, `functions/process-response.ts`), where the\n * recorded output is deliberately dropped: those handlers report through\n * their records and their run, not through a `wouldHaveTagged()` payload —\n * only the \"never write to Gorgias\" half of the recorders matters there.\n * The `uiInvoke` dry runs that DO read the recordings back\n * (`functions/graph-dry-run-core.ts`) keep wiring the recorders themselves.\n */\nexport function withRecordingWritePorts<T extends { reply: ReplyPort; state: StatePort }>(ports: T, api: SupportKitApi): T {\n return { ...ports, reply: createRecordingReplyPort().port, state: createRecordingStatePort(api).port };\n}\n\n// --- LlmPort recorder (still a REAL call — only its trace is captured) -----\n\n/** One LLM call, as a dry-run page would show it: what was asked, what came back, what it cost. */\nexport interface RecordedCompletion {\n label: string;\n model: string;\n reasoning: string;\n messages: CompletionRequest['messages'];\n toolsOffered: string[];\n text: string | null;\n toolCalls: Array<{ name: string; arguments: Record<string, unknown> }>;\n usage: Usage;\n traceId: string | null;\n durationMs: number;\n error?: string;\n}\n\nexport interface RecordingLlmPort {\n port: LlmPort;\n completions: RecordedCompletion[];\n}\n\nfunction toRecordedToolCalls(calls: ToolCallRequest[]): Array<{ name: string; arguments: Record<string, unknown> }> {\n return calls.map((c) => ({ name: c.name, arguments: c.arguments }));\n}\n\n/** Wraps a REAL `LlmPort` (the LLM still runs — §3.5's \"LLM compris\") and records every completion. */\nexport function createRecordingLlmPort(llm: LlmPort): RecordingLlmPort {\n const completions: RecordedCompletion[] = [];\n return {\n completions,\n port: {\n async complete(req: CompletionRequest) {\n const startedAt = Date.now();\n const entry: RecordedCompletion = {\n label: req.label,\n model: req.model,\n reasoning: req.reasoning,\n messages: req.messages,\n toolsOffered: (req.tools ?? []).map((t) => t.name),\n text: null,\n toolCalls: [],\n usage: { input: 0, output: 0, reasoning: 0 },\n traceId: null,\n durationMs: 0,\n };\n completions.push(entry);\n try {\n const result = await llm.complete(req);\n entry.text = result.text;\n entry.toolCalls = toRecordedToolCalls(result.toolCalls);\n entry.usage = result.usage;\n entry.traceId = result.traceId ?? null;\n return result;\n } catch (err) {\n entry.error = err instanceof Error ? err.message : String(err);\n throw err;\n } finally {\n entry.durationMs = Date.now() - startedAt;\n }\n },\n },\n };\n}\n","/**\n * `SupportKitHandlerContext` — `AppHandlerContext` (`@apotech-os/app-kit`,\n * `handler.ts`) narrowed to `api: SupportKitApi` instead of the concrete\n * `AppApiClient` class.\n *\n * Same reasoning as `SupportKitApi` itself (T21/T22, `adapters/api.ts`): a\n * real `AppHandlerContext` built by the platform carries a real\n * `AppApiClient`, which is a structural superset of `SupportKitApi`, so it\n * is always assignable here — but a unit test can build `ctx.api` as a plain\n * object instead of a live HTTP client.\n *\n * Also the shared home (T22 hardening, E) for the bits every one of the four\n * pipeline handlers otherwise hand-copied: `getOptional` (a 404 read is an\n * ordinary \"not there\" outcome, not a thrown error, for every handler that\n * dereferences a possibly-stale record id), `DEFAULT_MAX_TOOL_CALLS` (the\n * `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset), and\n * `buildTicketPorts` (the six-line `NodeDeps.ports` assembly `triage-tick`/\n * `process-response`/`handle-approval` each wrote out by hand, byte-for-byte\n * identical).\n */\nimport type { AppApiRecord, AppHandlerContext } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport {\n createGorgiasConversationPort,\n createGorgiasReplyPort,\n createGorgiasStatePort,\n createPlatformLlmPort,\n createPlatformPromptPort,\n createRealClock,\n type RunTrace,\n} from '../adapters/ctx-ports';\n\nexport type SupportKitHandlerContext = Omit<AppHandlerContext, 'api'> & { api: SupportKitApi };\n\n/** The `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset (§3.6). */\nexport const DEFAULT_MAX_TOOL_CALLS = 5;\n\n/**\n * Reads `objectKey/id`, returning `null` on a 404 (a dangling relation or an\n * already-deleted record) instead of throwing — the shape every handler here\n * wants when dereferencing an id it did not just create itself. `id: null`\n * short-circuits to `null` without a round trip, for the optional relations\n * (`categoryId`, `agentId`) that may never have been set.\n */\nexport async function getOptional(ctx: SupportKitHandlerContext, objectKey: string, id: string | null): Promise<AppApiRecord | null> {\n if (!id) return null;\n try {\n return await ctx.api.get(objectKey, id);\n } catch (err) {\n if (err instanceof AppApiError && err.status === 404) return null;\n throw err;\n }\n}\n\n/**\n * The `NodeDeps.ports` bundle every handler that runs a ticket through the\n * graph needs — one real Gorgias/platform wiring, reused instead of re-typed\n * per call site.\n *\n * `trace` groups every completion of the run under one Langfuse session\n * (`RunTrace`); a handler that omits it gets today's untraced behaviour.\n */\nexport function buildTicketPorts(ctx: SupportKitHandlerContext, trace?: RunTrace) {\n return {\n conversation: createGorgiasConversationPort(ctx.api),\n reply: createGorgiasReplyPort(ctx.api),\n llm: createPlatformLlmPort(ctx.api, trace),\n prompt: createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message)),\n state: createGorgiasStatePort(ctx.api),\n clock: createRealClock(),\n };\n}\n","/**\n * Whether a `generated-response{status:'pending'}` row is worth creating\n * for a just-triaged ticket (§3.5's \"si éligible, création generated-\n * response{status:'pending'}\").\n *\n * §3.5 does not spell out \"eligible\" — this is `triage-tick`'s own reading,\n * chosen to NEVER DRIFT from what `process-response`'s `runTicket(deps,\n * {resume})` would decide with the SAME classification: it calls the EXACT\n * SAME predicates `run-ticket.ts` branches on right after its own triage\n * phase (`isConversationOver`/`isFallbackClassification`/`hasNoDraftNode`,\n * exported from there — T22 hardening, so this can no longer silently drift\n * the way a hand-copied mirror could), up to (but not including)\n * `channelPreGates`/the WhatsApp not-our-turn check — those need a FRESH\n * conversation read to evaluate, which `triage-tick` does not have (and\n * should not pay for) at classification time. Any ticket this function\n * calls \"eligible\" that later turns out to hit a pre-gate is still\n * perfectly safe: `process-response` runs the real sequence and writes\n * whatever real outcome results, `triage-tick`'s job is only to avoid\n * paying for a draft that could NEVER have produced one — an escalated,\n * closed, or fallback-classified ticket.\n *\n * PER-CATEGORY OPT-IN (B3): the gate above is about what the graph COULD\n * produce; this one is about what the tenant ASKED for. §3.4's `category`\n * record carries `fastResponseEnabled` and `agentId` (with the cross\n * validation `fastResponseEnabled ⇒ agentId`), and the legacy enqueued a\n * fast-response job only for `matched && matched.fast_response_enabled &&\n * matched.agent` (`backoffice/src/services/triage.ts`). Nobody read those\n * fields here, so EVERY triable ticket paid a drafting — and then an\n * evaluation — LLM call, including for categories explicitly left out and\n * for tickets whose classification matched no category at all (drafted with\n * whatever the default agent happened to be). An unmatched or non-opted-in\n * category now stops at triage, as it did before the migration.\n *\n * ESCALATION (B3, connected decision): the legacy made this skip\n * CONDITIONAL on `profile.nodes.escalate.skipsFastResponse` — an escalated\n * ticket was still enqueued when that flag was off. That setting is gone\n * rather than restored: `graph/run-ticket.ts` finishes UNCONDITIONALLY on\n * `s.escalated` (`if (s.escalated) return finish(s, deps, 'escalated')`),\n * so a row created for an escalated ticket could never be fulfilled by\n * `process-response` — it would only ever be a pending row expiring on its\n * TTL. Honouring the flag would require re-opening that graph decision,\n * which §3.3 settled the other way; keeping it mapped-but-unread was the\n * worse of the three options.\n */\nimport type { Classification } from '../domain';\nimport type { AgentProfile } from '../domain/profile';\nimport { hasNoDraftNode, isConversationOver, isFallbackClassification } from '../graph/run-ticket';\nimport type { CategoryRecord } from './records';\n\nexport function isEligibleForGeneratedResponse(\n profile: AgentProfile,\n classification: Classification,\n escalated: boolean,\n category: CategoryRecord | null,\n): boolean {\n if (!category || !category.fastResponseEnabled || !category.agentId) return false;\n if (escalated) return false;\n if (isConversationOver(classification)) return false;\n if (isFallbackClassification(classification)) return false;\n if (hasNoDraftNode(profile)) return false;\n return true;\n}\n","/**\n * A `ToolContext` that refuses every call — used where `NodeDeps` requires\n * one but `AgentProfile.tools` is always `[]` (T22 leaves the §6.2 tool\n * allowlist at default-deny, see `settings/to-profile.ts`'s own doc: nothing\n * in `settingsToProfile` populates it, and `createPlatformLlmPort` throws on\n * a non-empty `CompletionRequest.tools` before ever reaching a provider).\n * With no tool ever exposed to the model, `draft` never calls this — these\n * throws are a loud, defensive backstop against that assumption silently\n * breaking, not a code path anything is expected to take today.\n */\nimport type { ToolContext } from '../graph/ports';\n\nfunction refuse(name: string): never {\n throw new Error(`no-tool-context: \"${name}\" called, but this pipeline configures no tools (profile.tools is always []).`);\n}\n\nexport function createNoToolContext(): ToolContext {\n return {\n getOrder: () => refuse('getOrder'),\n getTracking: () => refuse('getTracking'),\n searchKnowledge: () => refuse('searchKnowledge'),\n findSimilarTickets: () => refuse('findSimilarTickets'),\n };\n}\n","/**\n * The `pipeline-state` singleton (§3.4, `records/pipeline-state.ts`) —\n * shared reader/writer for `triage-tick` and `sweep`, the only two callers\n * (T22 hardening, A4). Both used to hand-roll their own `toDate`/\n * `readPipelineState`, byte-identical between the two files, and each wrote\n * with an independent `list()` + `create()`-or-`update()` pair with no\n * ordering guarantee between them — see `records/pipeline-state.ts`'s own\n * doc for why that raced two crons on a fresh app. Routing both functions\n * through the ONE reader here, and through `upsertPipelineState`'s\n * `singletonKey`-keyed `upsert` on the create path, is what makes \"exactly\n * one row\" the platform's own constraint instead of a hope.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\n\n/** Always the same value — the field the record's unique index is built on. */\nexport const PIPELINE_STATE_SINGLETON_KEY = 'default';\n\nexport function toDate(value: unknown): Date | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value as string);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/** The singleton `pipeline-state` row, or `null` if it has never been written. */\nexport async function readPipelineState(api: SupportKitApi): Promise<AppApiRecord | null> {\n const page = await api.list('pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n return page.items[0] ?? null;\n}\n\n/**\n * Merges `patch` onto the singleton row, creating it on the first call. Both\n * `triage-tick` and `sweep` only ever set a slice of the record's fields\n * (`sourceViewId`+`lastTriageAt`, `lastSweepAt`), so the write MUST merge —\n * whichever cron ran last must not erase the other's stamp.\n *\n * `update()` for the merge, `upsert()` only to create. This used to be a\n * single `upsert` on the assumption that `ON CONFLICT DO UPDATE` merges. It\n * does not: the platform runs `SET data = EXCLUDED.data`, a whole-document\n * REPLACE, and says so — \"to replace a whole document, use `upsert`, which\n * writes `data` as-is\". `update()` is the platform's shallow patch-merge, the\n * same one every other record in this package relies on. So a slice goes\n * through `update()`, and `upsert()` is kept for the one case it is actually\n * needed for: the very first write, where two crons could otherwise race two\n * `create()`s past a \"singleton by convention\".\n *\n * That preserves A4's real guarantee — exactly one row is still the DATABASE's\n * decision, arbitrated by the unique index on `singletonKey`, not a hope. The\n * residual race is narrow and self-healing: only on a fresh app can both crons\n * find no row and both build a full document, one of which loses its stamp and\n * is rewritten five minutes later.\n *\n * The create path sends every field explicitly — nulls included — because it\n * writes a whole document, not a patch. It must not depend on the platform\n * inventing the keys it left out.\n */\nexport async function upsertPipelineState(api: SupportKitApi, patch: Record<string, unknown>): Promise<void> {\n const current = await readPipelineState(api);\n if (current) {\n await api.update('pipeline-state', current.id, patch);\n return;\n }\n\n await api.upsert(\n 'pipeline-state',\n [\n {\n data: {\n singletonKey: PIPELINE_STATE_SINGLETON_KEY,\n sourceViewId: null,\n lastTriageAt: null,\n lastSweepAt: null,\n ...patch,\n },\n },\n ],\n { uniqueBy: ['singletonKey'] },\n );\n}\n","/**\n * `buildSendSeam` — the ONE claim→post→commit persistence seam (I9) shared\n * by `process-response` (claims a `pending` row) and `handle-approval`\n * (claims a `ready` row after an operator approves). §8.4 demands a single\n * send path, not two independently-written ones: this is where that demand\n * actually lives at the persistence layer — both callers hand this function\n * their own `fromStatus` and get back the exact same `NodeDeps.send`\n * shape `act` drives.\n *\n * `assertTransition` runs BEFORE the write attempt (`status/machine.ts`'s own\n * doc): it is a local, in-process sanity check, distinct from the `ifMatch`\n * race below it, which is what actually decides which of two concurrent\n * claimants wins.\n *\n * A 409 from `api.update` is NOT an error here — §3.4/§8.4 read it as \"the\n * other worker already claimed this row\", the ordinary losing side of a\n * race. Any other rejection propagates so Inngest can retry the run.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { Draft, Verdict } from '../domain';\nimport type { ClockPort } from '../graph/ports';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitApi } from '../adapters/api';\n\nexport interface SendSeam {\n claim: (run: { draft: Draft; verdict: Verdict | null }) => Promise<boolean>;\n commit: (messageId: string) => Promise<void>;\n}\n\nexport interface BuildSendSeamParams {\n api: SupportKitApi;\n clock: ClockPort;\n id: string;\n ticketId: string;\n /** The status this claim moves FROM — `'pending'` for `process-response`, `'ready'` for `handle-approval`. */\n fromStatus: Extract<GeneratedResponseStatus, 'pending' | 'ready'>;\n /**\n * Extra fields persisted on the SAME atomic claim write. `process-response`\n * uses this to persist the draft/verdict it just produced (the row had\n * none yet); `handle-approval` needs nothing extra — the row already\n * carries `responseText`/`verdict` from when it was drafted.\n */\n extraClaimData?: (run: { draft: Draft; verdict: Verdict | null }) => Record<string, unknown>;\n}\n\nexport function buildSendSeam(params: BuildSendSeamParams): SendSeam {\n const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;\n\n return {\n async claim(run) {\n assertTransition(fromStatus, 'sending');\n try {\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sending',\n sendingAt: clock.now(),\n openTicketKey: openTicketKeyFor('sending', ticketId),\n ...(extraClaimData ? extraClaimData(run) : {}),\n },\n { ifMatch: { status: fromStatus } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n },\n\n async commit(messageId) {\n assertTransition('sending', 'sent');\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sent',\n // The ONE place a reply becomes sent, whichever caller got it here\n // (`act` through `process-response`, or `handle-approval`'s direct\n // send) — so stamping the outcome here covers both without either\n // needing to remember to.\n outcome: 'sent',\n sentAt: clock.now(),\n sentMessageId: messageId,\n openTicketKey: openTicketKeyFor('sent', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n },\n };\n}\n","/**\n * The `generated-response:<id>[:suffix]` key shape used by BOTH the\n * `ApprovalRequest.key`/`ApprovalDecidedPayload.key` pair (`process-response`\n * requests, `handle-approval` parses) and the `InboxAlert.key`s\n * `process-response`/`sweep` raise. Shared here so the format can never\n * drift between writers — hand-rolling the same template string twice (or\n * three times) is exactly the kind of duplication that quietly breaks the\n * moment one side changes.\n */\nconst PREFIX = 'generated-response:';\n\n/** The approval key for one `generated-response` row. */\nexport function buildApprovalKey(generatedResponseId: string): string {\n return `${PREFIX}${generatedResponseId}`;\n}\n\n/** The `generated-response` id encoded in `key`, or `null` if `key` isn't one of ours. */\nexport function parseApprovalKey(key: string): string | null {\n if (!key.startsWith(PREFIX)) return null;\n const id = key.slice(PREFIX.length);\n return id.length > 0 ? id : null;\n}\n\n/**\n * The `InboxAlert.key` for one `generated-response` row, optionally\n * suffixed (`sweep`'s `stalled-send` alert vs. `process-response`'s plain\n * `needs_human` one) — same PREFIX as the approval key above, on purpose:\n * both name the same underlying record, in a different platform surface.\n * Added alongside `buildApprovalKey` for the same reason that one exists:\n * `process-response` and `sweep` were each hand-rolling this template\n * string in a slightly different shape, two lines after importing\n * `buildApprovalKey` to avoid doing exactly that for the approval key.\n */\nexport function buildInboxKey(generatedResponseId: string, suffix?: string): string {\n return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;\n}\n","/**\n * The `[{role, content}]` shape `generated-response.tracedInput` declares\n * (§3.4) — built from the messages the drafting call was actually given\n * (`Draft.messages`, spec-vue-tickets-unifiee-v1 §4.1).\n *\n * Two narrowings, both deliberate:\n * - `toolCalls`/`toolCallId` are dropped. The record's own field description\n * says `[{role, content}]`, and the tool round it would describe is\n * already recorded, in a shape built for reading, on `sources`.\n * - Each message's content is capped. A support thread can carry a pasted\n * invoice, a forwarded chain, a base64 signature block; the record exists\n * so an operator can read what the model read, and a truncated message\n * that SAYS it is truncated serves that better than an unbounded column.\n */\nimport type { ChatMessage } from '../graph/ports';\n\n/** Per-message ceiling. Generous enough for a real customer message, short of a pasted archive. */\nexport const TRACED_INPUT_MAX_CHARS = 4000;\n\nconst TRUNCATION_MARK = '… [tronqué]';\n\nexport interface TracedInputMessage {\n role: string;\n content: string;\n}\n\nexport function toTracedInput(messages: readonly ChatMessage[]): TracedInputMessage[] {\n return messages.map((message) => ({ role: message.role, content: cap(message.content ?? '') }));\n}\n\nfunction cap(content: string): string {\n if (content.length <= TRACED_INPUT_MAX_CHARS) return content;\n return `${content.slice(0, TRACED_INPUT_MAX_CHARS)}${TRUNCATION_MARK}`;\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 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}\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 };\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}\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}\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 };\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 };\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 * `respondToPendingResponse` — the response phase of the pipeline. Resumes\n * `runTicket` past triage (`resume: {classification, escalated}`,\n * reconstructed from the `triage-decision` row) and persists whatever\n * terminal outcome results.\n *\n * SINGLE-PASS (2026-09): this used to be `process-response`, a standalone\n * dbEvent function triggered on `generated-response{status:'pending'}`\n * created — the batch and the response ran in two decoupled Inngest runs,\n * and a tick exited with tickets still unanswered. It is now called by\n * `triage-tick`'s own batch loop, right after the row is created, so one\n * pass over the view leaves every processed ticket in a terminal state.\n * The `status !== 'pending'` guard below stays: it is what makes a replayed\n * or concurrent call a no-op instead of a second draft.\n *\n * DRY RUN (B1): `settings.dryRun` was read by NO handler — this one drafted\n * and, whenever auto-send was eligible, actually replied to the customer,\n * trial mode or not. It is read here now: the two write ports (`reply`,\n * `state`) are swapped for `adapters/recording-ports.ts`'s recorders and\n * `send` is forced to `{mode: 'none'}`, so the graph runs in FULL (LLM\n * included, §0's arbitrage) and reaches no external action. A trial run that\n * would have sent therefore comes back with `outcome: 'sent'` having sent\n * nothing, and is persisted as `ready` — the draft stays visible for §6's\n * parity control, and `ready` is the one status that says \"a human owns this\n * text now\". `awaiting_approval` raises no approval in a trial: granting one\n * would hand `handle-approval` a real send to perform.\n *\n * The claim→post→commit send seam (`functions/claim-commit.ts`) only covers\n * the ONE outcome where `act` actually runs (`sent`, and the narrow\n * `guardrail_hold` `act` itself can still produce post-claim — see below);\n * every other outcome (`ready`, `needs_human`, `awaiting_approval`,\n * `no_reply_needed`, `failed`, the pre-claim `guardrail_hold`) is written\n * directly here, since `act`/the claim were never reached for them.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef, DraftAttribution } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport { buildSendSeam } from './claim-commit';\nimport { buildApprovalKey, buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { toTracedInput } from './traced-input';\nimport { buildPromptsTable, draftPromptRefFor, resolveDraftAgent, toAgent, toCategory } from './records';\n\n/**\n * Rebuilds the `Classification` `runTicket`'s `resume` needs, field-for-field\n * off the `triage-decision` row `triage-tick` wrote. `isFallback` is always\n * `false`: a `generated-response` is only ever created for a triage that\n * SUCCEEDED (`triage-tick` writes `status:'error'` and stops on a failed\n * classification, never creating one) — see `functions/eligibility.ts`.\n */\nfunction classificationFromDecision(decision: AppApiRecord): Classification {\n const data = decision.data as Record<string, unknown>;\n return {\n category: (data.tag as string) ?? '',\n confidence: (data.confidence as 'high' | 'low') ?? 'low',\n reasoning: (data.reasoning as string) ?? '',\n isFallback: false,\n conversationOver: (data.conversationOver as boolean | undefined) ?? false,\n };\n}\n\n/**\n * §3.4's four Langfuse columns, off the attribution the draft carries (B2).\n * WITHOUT a writer here `ext-fast-response-check` served `null` on every hit,\n * the extension echoed those nulls back, and `ext-response-comparison`'s\n * dataset/score capture — gated on a non-empty trace id — never fired for a\n * single pipeline response: the improvement loop had nothing to score.\n *\n * A run that produced no draft (a failed one) writes explicit `null`s rather\n * than nothing: the ids of a call that never finished would point the loop at\n * a generation nobody read.\n */\nfunction attributionFields(attribution: DraftAttribution | undefined): Record<string, unknown> {\n return {\n langfuseTraceId: attribution?.traceId ?? null,\n langfuseObservationId: attribution?.observationId ?? null,\n promptName: attribution?.promptName ?? null,\n promptVersion: attribution?.promptVersion ?? null,\n };\n}\n\nasync function finalizeNonSent(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n toStatus: GeneratedResponseStatus,\n extra: Record<string, unknown>,\n): Promise<boolean> {\n assertTransition('pending', toStatus);\n try {\n await ctx.api.update(\n 'generated-response',\n id,\n { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },\n { ifMatch: { status: 'pending' } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.info(`respond: generated-response ${id} was already moved off \"pending\" by another worker, abandoning`);\n return false;\n }\n throw err;\n }\n}\n\nexport async function respondToPendingResponse(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n recordId: string,\n): Promise<void> {\n const record = await getOptional(ctx, 'generated-response', recordId);\n if (!record) {\n ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'pending') {\n ctx.logger.info(`respond: generated-response ${recordId} is not pending (status=\"${String(data.status)}\"), skipping — already handled by another worker`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n if (validateSettings(settings as unknown as Record<string, unknown>).length > 0) {\n ctx.logger.info('respond: settings invalid, skipping');\n return;\n }\n\n const ticketId = data.ticketId as string;\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n\n const decision = await getOptional(ctx, 'triage-decision', (data.triageDecisionId as string) ?? null);\n if (!decision) {\n ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { error: 'triage-decision not found' });\n return;\n }\n const classification = classificationFromDecision(decision);\n const escalated = (decision.data as Record<string, unknown>).escalated === true;\n\n const categoryRecord = await getOptional(ctx, 'category', (data.categoryId as string | null) ?? null);\n const category = categoryRecord ? toCategory(categoryRecord) : null;\n const agentRecord = (data.agentId as string | null)\n ? await getOptional(ctx, 'agent', data.agentId as string)\n : null;\n const agent = agentRecord ? toAgent(agentRecord) : await resolveDraftAgent(ctx.api, null);\n\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const dryRun = settings.dryRun === true;\n // Every completion of this ticket under one Langfuse session (§3.4's\n // quality loop reads a conversation, not a pile of orphan generations).\n const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);\n const { clock } = ports;\n\n // Generation-time snapshot for `act`'s divergence baseline WHEN this\n // record is later replayed through `handle-approval` (design decision (a)\n // in T22's brief): a `handle-approval` run has no live conversation read\n // of its own to source these from, and `act` always re-reads for real\n // before posting regardless (I8), so a snapshot taken here — moments\n // before `runTicket`'s own `fetchContext` re-read — is close enough\n // without weakening send safety.\n const conversationSnapshot = await ports.conversation.read(ref);\n\n const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt as string);\n const seam = buildSendSeam({\n api: ctx.api,\n clock,\n id: recordId,\n ticketId,\n fromStatus: 'pending',\n extraClaimData: (run) => ({\n responseText: run.draft.text,\n sources: run.draft.sources,\n tracedInput: toTracedInput(run.draft.messages),\n verdict: run.verdict,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(run.draft.attribution),\n }),\n });\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const result = await runTicket(\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: dryRun ? { mode: 'none' } : { mode: 'claimed', claim: seam.claim, commit: seam.commit },\n queuedAt: generatedAt,\n },\n { resume: { classification, escalated } },\n );\n\n const draftExtra = {\n // Stamped once for every branch of the switch below rather than per\n // case: `status` cannot carry it (four of these outcomes all persist as\n // `ready`), and a per-case literal is a list that drifts the first time\n // a case is added. A dry run records the outcome the graph REACHED —\n // `outcome: 'sent'` on a `ready` row is exactly what \"would have been\n // sent, wasn't\" looks like, and the timeline reads it that way.\n outcome: result.outcome,\n responseText: result.draft?.text ?? null,\n sources: result.draft?.sources ?? [],\n // The rendered system prompt and the customer's own turns, which nothing\n // else persists (spec-vue-tickets-unifiee-v1 §4.1). Written on BOTH write\n // paths — the send seam's claim above and this finalisation — because a\n // sent reply and a held one are read by the same timeline.\n tracedInput: toTracedInput(result.draft?.messages ?? []),\n verdict: result.verdict ?? null,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(result.draft?.attribution),\n };\n\n switch (result.outcome) {\n case 'sent':\n // Nothing was sent on a dry run — `send: {mode: 'none'}` means no\n // claim/commit ever ran, so this record is still `pending` and would\n // stay there forever if this returned like the live path does.\n if (dryRun) {\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n }\n // Already fully persisted by `seam.claim`/`seam.commit` inside `act`.\n return;\n case 'ready':\n case 'guardrail_hold':\n // `run-ticket.ts`'s own `finish()` doc: both are \"ready + a tag\", the\n // tag alone (already applied by `finish` via `StatePort.flag`)\n // distinguishes them for a human — the record's `status` does not.\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n case 'needs_human': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted) {\n await ctx.api.inbox.raise({\n key: buildInboxKey(recordId),\n severity: 'warning',\n title: `Réponse générée à revoir — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'awaiting_approval': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted && !dryRun) {\n await ctx.api.approvals.request({\n key: buildApprovalKey(recordId),\n title: `Approuver l'envoi automatique — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'escalated':\n case 'triaged_only':\n case 'no_reply_needed':\n await finalizeNonSent(ctx, recordId, ticketId, 'no_reply_needed', draftExtra);\n return;\n case 'failed':\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { ...draftExtra, error: 'runTicket outcome: failed' });\n return;\n default:\n // `outcome` is `null` only mid-run — `runTicket` never returns it on\n // a resumed call (every path through `finish()` sets one).\n ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);\n }\n}\n","/**\n * `transitionGeneratedResponse` (M8 hardening) — the ONE conditional\n * `generated-response` status-write shape shared by every caller that only\n * needs to move a row from one status to another (S5 `ifMatch` + tolerate a\n * lost race as \"someone else already moved it\", not an error): `sweep`'s\n * `ready -> expired` TTL pass and `ext-fast-response-check`'s\n * `ready -> expired|invalidated` flips used to be two independent\n * implementations of the identical transition on the identical record —\n * anything added to one (a stamp, a metric, a different 409 policy) would\n * silently not happen on the other.\n *\n * Deliberately NOT used by `claim-commit.ts`'s `buildSendSeam` or\n * `sweep.ts`'s stalled-sending/stalled-pending passes: those write EXTRA\n * fields the caller computes from the in-flight `run`/reclaim shape\n * (`sendingAt`, `reclaimStalledSend()`'s `autoSendDecision` hold, the\n * `error` message) on the SAME atomic write, which this narrow helper's\n * `extra` param supports but was not the reported duplication — scope kept\n * to the transition the review actually flagged as duplicated.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\n\nexport interface TransitionGeneratedResponseParams {\n id: string;\n ticketId: string;\n from: GeneratedResponseStatus;\n to: GeneratedResponseStatus;\n /** Extra fields persisted on the SAME conditional write, alongside `status`/`openTicketKey`. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Attempts `from -> to` under `ifMatch: {status: from}`. Returns `true` when\n * the write landed, `false` when the row had already moved (a lost race —\n * not an error, exactly the same outcome either way for every caller today).\n */\nexport async function transitionGeneratedResponse(api: SupportKitApi, params: TransitionGeneratedResponseParams): Promise<boolean> {\n const { id, ticketId, from, to, extra } = params;\n assertTransition(from, to);\n try {\n await api.update(\n 'generated-response',\n id,\n { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...(extra ?? {}) },\n { ifMatch: { status: from } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n}\n","/**\n * `triage-tick` (§3.5, reworked 2026-09 into the SINGLE-PASS pipeline job) —\n * cron function. Classifies every pending ticket on the claimed Gorgias view\n * and, per ticket, materialises what `runTicket(deps, {until:'triage'})`\n * deliberately leaves unwritten (see that option's own doc in\n * `graph/run-ticket.ts`): the `triage-decision` row, the deduplicated tag\n * application, and — when eligible — a `generated-response{status:'pending'}`\n * row, which the SAME pass then carries to a terminal state via\n * `respondToPendingResponse` (draft, evaluation, send or hand-off to a\n * human). When this function exits, every ticket of the batch is either\n * answered, explicitly handed to a human (tagged + `ready`/inbox/approval),\n * or recorded as an error — there is no second Inngest job to wait for.\n *\n * ONE BODY, NO INNGEST STEPS, deliberately: every side effect here is either\n * idempotent or guarded by an `ifMatch`/unique-key write, and splitting the\n * batch into `ctx.step.run` checkpoints would re-execute every non-step call\n * (the run open, the view read, the cadence stamp) on each step replay. The\n * cost is a wall-clock bound: the whole batch must fit in one Inngest\n * request (`INNGEST_REQUEST_TIMEOUT_MS`, 15 min by default). An operator\n * whose view outgrows that bound lowers `settings.batchLimit` — leftover\n * tickets are simply picked up by the next tick.\n *\n * WRITE ORDER (T22 hardening, A2): the `triage-decision` row is written\n * BEFORE the Gorgias tags are applied, not after. A duplicate tag apply on a\n * retried/re-run ticket is idempotent (`dedupeTagNames`, `gorgias-tags.ts`);\n * a lost `triage-decision` is not — and if the claimed view filters on the\n * `handledTag` this tag step applies, a ticket tagged with no decision row\n * behind it never comes back into view again, so the classification the LLM\n * call already paid for would be lost OUTRIGHT, not merely re-billed. The\n * decision-first order means the ONLY window left where a crash can still\n * lose a classification is between `runTicket`'s checkpoint returning and\n * THIS row landing — everything after that point (the tag apply, the\n * `generated-response` create) is either idempotent or independently\n * recoverable.\n *\n * CRASH WINDOW that remains (documented, not fully closed — see the\n * module's own final report): `runTicket`'s own doc states it plainly — a\n * checkpointed run never calls `ports.state.record`, so the classification\n * only lives in the RETURNED `TicketRunState` until this function writes it\n * down. If the process dies between the checkpoint returning and the\n * `triage-decision` write above, that LLM call's result is lost with\n * nothing left to reconstruct it from — the ticket is simply re-classified\n * (and re-billed) on the next tick. This is the same trade-off `runTicket`'s\n * doc already names as \"iso-legacy and harmless today\"; nothing in T22\n * changes it.\n *\n * DRY RUN (B1): `settings.dryRun` was a declared, advertised, DEAD setting —\n * no handler read it, so the very first `triageEnabled` activation of the\n * spec's §6 switchover order (\"activate in `dryRun`, control the parity,\n * then `dryRun` off\") tagged and renamed REAL Gorgias tickets. It is read\n * here now, and it substitutes the two write ports (`reply`, `state`) for\n * the recorders of `adapters/recording-ports.ts`: the graph still runs in\n * FULL, LLM included (§0's arbitrage), it simply reaches no external action.\n *\n * What a trial tick still WRITES, deliberately: the `triage-decision` and\n * the `generated-response` rows, exactly as a live tick would. §6 asks the\n * operator to \"control the decisions\" before turning `dryRun` off — with no\n * rows there is nothing to control, and the Pipeline/Escalades pages would\n * show an empty trial. They are identifiable as a trial's through the\n * application run they carry the `runId` of, which is stamped\n * `metadata.dryRun: true` below (the record schemas are frozen by §3.4, so\n * the marker lives on the run, not on a new column). A trial row therefore\n * describes what production WOULD have done — `subjectRenamed: true` on a\n * dry run means \"the subject matched and would have been rewritten\",\n * nothing was sent to Gorgias.\n *\n * PER-TICKET ISOLATION (T22 hardening, A1): one failing ticket no longer\n * aborts the rest of the batch. `retries: 0` on this function (see the\n * manifest fragment below) means a tick that dies partway has no recovery —\n * tickets already processed dropped off the claimed view (their `handledTag`\n * is applied), so the NEXT tick would hit the same poison ticket first and\n * die at the same place, forever, while `lastTriageAt` was never stamped\n * (also re-billing every ticket the dead tick DID manage to finish). Each\n * ticket's own error is caught and handled alone; the loop moves on, and\n * `lastTriageAt` is stamped in a `finally` so the cadence gate always\n * advances once the batch has been attempted, degraded ticket or not.\n *\n * FAILURE = ESCALATION (owner decision, 16/09/2026 — `handleTicketFailure`):\n * a ticket the pipeline could not carry to an answer is TAGGED FOR A HUMAN,\n * the same hand-off `guardrail_hold` and the sweep's stalled-send reclaim\n * already use. This matters more since the response phase moved into this\n * batch: `graph/nodes/draft.ts` has no `try`/`catch` of its own, so a 429\n * from the drafting model reaches this loop for every eligible ticket of the\n * tick, and those tickets used to be left with nothing but a log line. What\n * gets WRITTEN depends on how far the ticket got — a triage that never\n * classified gets the `triage-decision{status:'error'}` row that is its only\n * possible trace, while a failed RESPONSE records the error on its own\n * `generated-response` row rather than contradicting a decision that says,\n * correctly, that the triage succeeded.\n *\n * That tag is the ONLY notification, deliberately (owner decision, same\n * date): the run stays reported SUCCEEDED — a batch that isolated its\n * failures did its job — and no platform alert is raised. The hand-off\n * belongs in Gorgias, where the humans who answer these tickets already\n * work; a second, platform-side alert would report the same thing to people\n * who are not the ones picking the ticket up.\n */\nimport type { AppApiRecord, AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { createRealClock } from '../adapters/ctx-ports';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { openTicketKeyFor } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { isEligibleForGeneratedResponse } from './eligibility';\nimport { createNoToolContext } from './no-tool-context';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\nimport { respondToPendingResponse } from './process-response';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n findCategoryByTag,\n listCategories,\n resolveDraftAgent,\n toCategoryReferential,\n} from './records';\n\n/**\n * The manifest fragment (§3.5's table row): every 5 minutes, no retries (a\n * failed tick is superseded by the next one 5 minutes later — retrying it\n * would just re-run against a possibly-already-advanced view), one run at a\n * time, and a warning alert on failure so an operator notices a stuck\n * pipeline. Cron has no timezone field in this schema (`FunctionTriggerSchema`,\n * `@apotech-os/app-kit` `contracts.ts`) — Europe/Paris from the spec table\n * has nowhere to go here; see this task's final report for that gap.\n */\nexport function buildTriageTickFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'triage-tick'),\n name: 'triage-tick',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createTriageTickHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => triageTickHandler(ctx, config);\n}\n\nexport async function triageTickHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('triage-tick: settings invalid, skipping', { issues });\n return;\n }\n if (!settings.triageEnabled) {\n ctx.logger.info('triage-tick: triageEnabled is off, skipping');\n return;\n }\n if (!settings.sourceViewId) {\n ctx.logger.info('triage-tick: no sourceViewId configured, skipping');\n return;\n }\n\n const clock = createRealClock();\n const now = clock.now();\n\n const pipelineState = await readPipelineState(ctx.api);\n const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);\n if (lastTriageAt) {\n const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 60_000;\n if (now.getTime() < dueAt) {\n ctx.logger.info('triage-tick: not due yet, skipping');\n return;\n }\n }\n\n await runTriageBatch(ctx, config, settings);\n}\n\n/**\n * The ticket deep-link prefix, resolved ONCE per batch and frozen onto every\n * `triage-decision` the batch writes (`${base}/${ticketId}`).\n *\n * Frozen on the row rather than rebuilt by the page: the pages that list\n * these decisions read them through the generic data API and have no way to\n * reach the Gorgias connection's own domain (credentials are stripped from\n * `GET /data/integrations/:provider/connections`). The cost of that choice\n * is stated plainly: a decision written before this field existed, or while\n * the connection was a mock, keeps `ticketUrl: null` forever, and a row\n * keeps the url of the helpdesk domain that was configured the day it was\n * triaged.\n *\n * The base itself comes from the Gorgias CONNECTION (its `baseUrl`\n * credential, or its domain) — `GORGIAS_BASE_URL` only reaches it through\n * the env-backed instance the platform synthesises when no connection is\n * stored. A failure here degrades to `null`: a deep link is decorative, and\n * losing it must never fail a triage batch.\n */\nasync function resolveTicketUrlBase(ctx: SupportKitHandlerContext): Promise<string | null> {\n try {\n // Named connection, unlike every other Gorgias call in this kit: the\n // platform's own default resolution raises `409 AMBIGUOUS_CONNECTION` on\n // several connections with none flagged default (the exact configuration\n // the Settings page already warns about), and a deep link is not worth\n // losing over an ambiguity a single link target settles.\n const connections = await ctx.api.integrations.list('gorgias');\n const connection = connections.find((candidate) => candidate.isDefault) ?? connections[0];\n const result = (await ctx.api.integrations.run(\n 'gorgias',\n 'getTicketUrlBase',\n {},\n connection ? { connectionId: connection.id } : undefined,\n )) as { base?: unknown } | null;\n return typeof result?.base === 'string' && result.base !== '' ? result.base : null;\n } catch (err) {\n ctx.logger.warn('triage-tick: could not resolve the Gorgias ticket url base, decisions will carry no deep link', {\n error: err instanceof Error ? err.message : String(err),\n });\n return null;\n }\n}\n\nfunction ticketUrlFor(base: string | null, ticketId: string): string | null {\n return base ? `${base}/${encodeURIComponent(ticketId)}` : null;\n}\n\n/**\n * The batch itself — every `triage-tick` guard (settings validity,\n * `triageEnabled`, `sourceViewId`, the cadence gate) has already returned by\n * the time this runs. Extracted (T23) so `run-triage-now`\n * (`functions/run-triage-now.ts`, §3.5's \"déclenchement manuel\") can run the\n * EXACT same batch on demand, bypassing only the cadence gate above — not a\n * second, independently-drifting copy of `listPending` → per-ticket triage →\n * `triage-decision` → `generated-response`.\n */\nexport async function runTriageBatch(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n settings: SupportKitSettings,\n): Promise<{ ticketCount: number; failureCount: number }> {\n const dryRun = settings.dryRun === true;\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);\n\n const categories = await listCategories(ctx.api);\n // Draft agent for the WHOLE batch's profile — a placeholder until each\n // ticket's own category is known (see `records.ts`'s doc on\n // `resolveDraftAgent`). The per-ticket agent used on the created\n // `generated-response` row is resolved again below, after triage.\n const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));\n\n const ticketUrlBase = await resolveTicketUrlBase(ctx);\n\n const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);\n\n // §3.5's \"run applicatif\" (T22 hardening, D): one run per tick, threaded\n // onto every `triage-decision` this tick writes (`runId` below) instead of\n // each decision minting its own `crypto.randomUUID()` — an operator can\n // now group a tick's decisions, or find the tick itself, in the platform\n // run history. Started only once we know there is real work to do (the\n // cadence/settings guards above already returned): a skipped tick has\n // nothing to report a run for.\n const run = await ctx.api.runs.start({\n kind: 'triage-tick',\n message: `${dryRun ? 'Dry-run triage tick' : 'Triage tick'} over ${refs.length} ticket(s)`,\n metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun },\n });\n\n let failureCount = 0;\n try {\n for (const ref of refs) {\n try {\n await processOneTicket(ctx, ref, {\n config,\n profile,\n categories,\n ports,\n runId: run.id,\n ticketUrlBase,\n });\n } catch (err) {\n failureCount += 1;\n await handleTicketFailure(ctx, ref, err, {\n profile,\n ports,\n runId: run.id,\n ticketUrlBase,\n });\n }\n }\n await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });\n } catch (err) {\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n } finally {\n // Stamped regardless of per-ticket failures (A1): the cadence gate must\n // advance once the batch has been ATTEMPTED, not only once every ticket\n // in it succeeded — otherwise a single poison ticket would keep\n // `lastTriageAt` frozen and every OTHER ticket in the batch would be\n // re-billed on the next tick too. Also stamped on a `run-triage-now`\n // manual batch, on purpose: it advances the SAME cadence gate\n // `triage-tick` reads, so a manual run just before a scheduled tick is\n // due does not immediately trigger a redundant second pass over the\n // same tickets.\n await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });\n }\n\n return { ticketCount: refs.length, failureCount };\n}\n\n/**\n * A failure of the RESPONSE phase — the ticket WAS classified, its\n * `triage-decision{status:'ok'}` is already written, and the\n * draft/evaluate/send sequence is what threw.\n *\n * Distinguished from a triage failure because the two need opposite\n * bookkeeping: a triage failure has no decision row yet and must write one,\n * while writing a SECOND `status:'error'` decision for a ticket whose triage\n * actually succeeded would describe a classification that never failed — and\n * list that ticket twice on the Tickets page, once \"trié\", once \"en erreur\".\n */\nclass ResponsePhaseError extends Error {\n readonly generatedResponseId: string;\n\n constructor(generatedResponseId: string, cause: unknown) {\n super(cause instanceof Error ? cause.message : String(cause));\n this.name = 'ResponsePhaseError';\n this.generatedResponseId = generatedResponseId;\n }\n}\n\n/**\n * OWNER DECISION (16/09/2026): every per-ticket failure ends the same way for\n * the customer — the ticket is ESCALATED. The pipeline could not answer it,\n * so a human takes over in Gorgias, which is the same hand-off\n * `guardrail_hold` and the sweep's stalled-send reclaim already use. Only the\n * BOOKKEEPING differs, depending on how far the ticket got.\n *\n * Every step here is individually guarded: this runs inside the batch loop's\n * own `catch`, so a throw escaping it would abort the rest of the batch —\n * exactly the per-ticket isolation (A1) the loop exists to provide.\n */\nasync function handleTicketFailure(\n ctx: SupportKitHandlerContext,\n ref: ConversationRef,\n err: unknown,\n deps: TicketFailureDeps,\n): Promise<void> {\n const message = err instanceof Error ? err.message : String(err);\n ctx.logger.error(`triage-tick: ticket ${ref.id} failed, escalating it and continuing with the rest of the batch`, {\n error: message,\n });\n\n if (err instanceof ResponsePhaseError) {\n await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);\n } else {\n await writeErrorDecision(ctx, ref, message, deps);\n }\n\n await escalateTicket(ctx, ref, deps);\n}\n\n/**\n * The response row the failed run left behind, moved to `failed`.\n *\n * This frees `openTicketKey` in the same write (a terminal status clears it),\n * so the NEXT tick can draft for this ticket again — without it the orphan\n * `pending` row holds the ticket's unique key and every later tick 409s on it\n * until the TTL, leaving `sweep` to clean up an hour later.\n *\n * `ifMatch: {status:'pending'}` is what keeps a row the send seam already\n * claimed (`sending`) out of reach: its reply may ALREADY have been posted to\n * the customer, so forcing it to `failed` would erase the one state\n * `sweep`'s stalled-send reclaim knows how to resolve safely. A lost match\n * returns `false` and is left alone, deliberately.\n */\nasync function finalizeFailedResponse(\n ctx: SupportKitHandlerContext,\n ref: ConversationRef,\n generatedResponseId: string,\n message: string,\n): Promise<void> {\n try {\n await transitionGeneratedResponse(ctx.api, {\n id: generatedResponseId,\n ticketId: ref.id,\n from: 'pending',\n to: 'failed',\n extra: { error: message },\n });\n } catch (writeErr) {\n ctx.logger.error(`triage-tick: failed to finalise the response of ticket ${ref.id}`, {\n error: writeErr instanceof Error ? writeErr.message : String(writeErr),\n });\n }\n}\n\n/** The `triage-decision{status:'error'}` row a ticket that never got classified needs — the only row it will ever have. */\nasync function writeErrorDecision(\n ctx: SupportKitHandlerContext,\n ref: ConversationRef,\n message: string,\n deps: TicketFailureDeps,\n): Promise<void> {\n try {\n await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n ticketUrl: ticketUrlFor(deps.ticketUrlBase, ref.id),\n decidedAt: deps.ports.clock.now(),\n status: 'error',\n error: message,\n confidence: 'low',\n runId: deps.runId,\n subjectRenamed: false,\n });\n } catch (writeErr) {\n ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {\n error: writeErr instanceof Error ? writeErr.message : String(writeErr),\n });\n }\n}\n\n/**\n * The hand-off itself: the escalation tag, applied through the same\n * `StatePort.flag` the graph's own `guardrail_hold` outcome uses — so a\n * dry-run batch records the intent instead of touching Gorgias, for free.\n *\n * An unconfigured `escalationTag` is skipped with a warning rather than\n * applied blank: `flag('')` is not a hand-off, and the tenant whose settings\n * are incomplete is exactly the one this path runs for.\n */\nasync function escalateTicket(ctx: SupportKitHandlerContext, ref: ConversationRef, deps: TicketFailureDeps): Promise<void> {\n const tag = deps.profile.audit.escalationTag;\n if (!tag) {\n ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured — no tag applied`);\n return;\n }\n try {\n await deps.ports.state.flag(ref, tag);\n } catch (flagErr) {\n ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} — it is NOT tagged for a human`, {\n error: flagErr instanceof Error ? flagErr.message : String(flagErr),\n });\n }\n}\n\ninterface TickDeps {\n config: SupportKitFunctionConfig;\n profile: ReturnType<typeof settingsToProfile>;\n categories: Awaited<ReturnType<typeof listCategories>>;\n ports: ReturnType<typeof buildTicketPorts>;\n runId: string;\n ticketUrlBase: string | null;\n}\n\n/** What the failure path needs — the batch's own `categories`/`config` have no bearing on how a ticket is escalated. */\ntype TicketFailureDeps = Pick<TickDeps, 'profile' | 'ports' | 'runId' | 'ticketUrlBase'>;\n\nasync function processOneTicket(ctx: SupportKitHandlerContext, ref: ConversationRef, deps: TickDeps): Promise<void> {\n const { config, profile, categories, ports, runId, ticketUrlBase } = deps;\n\n // Optional rename (§3.6's `renameEnabled`/`renameFrom`/`renameTo`) — no\n // node in the graph performs it (see this module's own header doc), so it\n // is done here, once, before triage. `runTicket` re-reads the conversation\n // itself right after (`fetchContext`'s own \"always re-read\" contract) —\n // paying for one extra read here is the same trade-off the whole pipeline\n // already makes at every resume boundary.\n let subjectRenamed = false;\n if (profile.rename) {\n const conversation = await ports.conversation.read(ref);\n const subject = conversation.subject ?? '';\n if (subject.includes(profile.rename.from)) {\n await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));\n subjectRenamed = true;\n }\n }\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: { ...ports },\n toolContext: createNoToolContext(),\n budget,\n // Unknown until triage runs — no node reached in the `until:'triage'`\n // phase reads `deps.category` (`run-ticket.ts`'s early return happens\n // before any node touches it).\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n // Thrown rather than written-and-returned: a ticket nobody could classify\n // is a failed ticket like any other, and the batch's own failure path owns\n // both halves of that — the error decision AND the escalation a silent\n // `return` here used to skip.\n if (!state.classification) throw new Error('triage produced no classification');\n\n const { classification } = state;\n const category = findCategoryByTag(categories, classification.category);\n\n // Decision FIRST, tags SECOND (A2 — see this module's header doc for why\n // the order was inverted).\n const decision = await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),\n decidedAt: ports.clock.now(),\n categoryId: category?.id ?? null,\n tag: classification.category,\n confidence: classification.confidence,\n reasoning: classification.reasoning,\n conversationOver: classification.conversationOver ?? false,\n escalated: state.escalated,\n status: 'ok',\n runId,\n subjectRenamed,\n });\n\n // The dedup+single-`applyTags` call §3.5 asks for already lives in\n // `StatePort.record` (`adapters/gorgias-tags.ts`'s `resolveHandledTags`) —\n // nothing to reimplement here beyond calling the port.\n await ports.state.record(ref, classification, profile.audit);\n\n // The category matched above is passed along, not re-read: §3.4's\n // `fastResponseEnabled`/`agentId` opt-in is half of what \"eligible\" means\n // (B3 — see `eligibility.ts`).\n if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;\n\n const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);\n const conversation = state.conversation;\n const channel = conversation?.sourceChannel === 'whatsapp' ? 'whatsapp' : 'email';\n const generatedAt = ports.clock.now();\n const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 60_000);\n\n let created: AppApiRecord;\n try {\n created = await ctx.api.create('generated-response', {\n ticketId: ref.id,\n openTicketKey: openTicketKeyFor('pending', ref.id),\n status: 'pending',\n triageDecisionId: decision.id,\n categoryId: category?.id ?? null,\n agentId: draftAgent?.id ?? null,\n channel,\n generatedAt,\n expiresAt,\n sources: [],\n tracedInput: [],\n guardrailHits: [],\n servedTo: [],\n servedCount: 0,\n followupRequired: false,\n });\n } catch (err) {\n // §3.5: \"conflit d'unicité openTicketKey ⇒ ignoré, idempotent\" — another\n // tick (or a stray retry) already opened one for this ticket.\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);\n return;\n }\n throw err;\n }\n\n // Single-pass: the response phase runs right here, in the same batch, so\n // the ticket leaves this tick answered (or explicitly handed to a human)\n // instead of waiting for a decoupled dbEvent worker. Its failures are\n // re-thrown carrying the row they left behind — the decision above already\n // records a triage that SUCCEEDED, and the batch's failure path must not\n // contradict it (see `ResponsePhaseError`).\n try {\n await respondToPendingResponse(ctx, config, created.id);\n } catch (err) {\n throw new ResponsePhaseError(created.id, err);\n }\n}\n","/**\n * `sweep` (§3.5) — cron function. Three independent janitor passes over\n * `generated-response`:\n * 1. `ready` rows past `expiresAt` → `expired` (the extension's TTL check\n * mirrored server-side, so a stale draft cannot be served forever).\n * 2. `sending` rows stuck past 30 minutes (a crash between `claim` and\n * `commit`, I9) → reclaimed to `ready` + `autoSendDecision: 'hold'`\n * via `reclaimStalledSend()` (`status/machine.ts`) — NEVER `status`\n * alone, which `reclaimStalledSend`'s own doc calls out as the one\n * write shape that would re-open the record as a legal, un-held claim\n * target and risk RE-SENDING the reply. Every reclaimed ticket is\n * handed to a human: the escalation tag is applied and an Inbox alert\n * raised, since a stuck send is exactly the kind of thing nobody\n * should have to notice on their own.\n * 3. `pending` rows past `expiresAt` → `failed` (T22 hardening, A3 — see\n * that pass's own doc below for why it exists).\n *\n * `sweep` never posts a reply and never calls the claim/commit seam — it\n * only ever touches `generated-response` rows and the Gorgias tag/alert\n * surfaces, which is what makes §8.4's invariant 2 (\"never re-sent\")\n * checkable against it directly.\n *\n * Known limitation: `SupportKitApi.list` carries no cursor, so a sweep pass\n * reads at most one page of `ready`/`sending`/`pending` rows. Acceptable for\n * now — all three sets are normally small and short-lived — but a tenant\n * with a large backlog would need pagination added to the interface first.\n *\n * SETTINGS VALIDATION (T22 hardening, C — a deliberate exemption, not an\n * omission): `sweep` does NOT call `validateSettings` the way the other\n * three handlers do, because it must keep reclaiming stalled sends even on\n * a tenant whose settings are currently incomplete — that reclaim is a\n * safety net, not a feature an operator opted into, and refusing to run it\n * on a misconfigured app would leave a stuck `sending` row (and a customer\n * who may or may not have already been emailed) unattended for longer, not\n * shorter. What IS guarded is the one settings field this file actually\n * reads, `escalationTag`: on an unconfigured tenant it used to be\n * `undefined`, and `StatePort.flag` calling `.trim()` on it threw a\n * `TypeError` mid-loop — with `retries: 0` that killed the rest of the\n * reclaim pass AND skipped `lastSweepAt`. Routing it through\n * `settingsToProfile` instead (as first suggested) would trade this crash\n * for a different one: that mapper dereferences `settings.nodes.triage.model`\n * unconditionally (`baseNode`), which throws just as readily on the exact\n * kind of incomplete settings blob this guard exists for. A direct,\n * narrow-scoped type check on the one field actually read is what stays\n * safe without introducing a new crash surface.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { createGorgiasStatePort, createRealClock } from '../adapters/ctx-ports';\nimport { assertTransition, openTicketKeyFor, reclaimStalledSend } from '../status/machine';\nimport { buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\n\nconst STALE_SENDING_THRESHOLD_MS = 30 * 60_000;\nconst SWEEP_PAGE_SIZE = 500;\n\nexport function buildSweepFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sweep'),\n name: 'sweep',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createSweepHandler(): AppHandler {\n return (ctx) => sweepHandler(ctx);\n}\n\nexport async function sweepHandler(ctx: SupportKitHandlerContext): Promise<void> {\n const clock = createRealClock();\n const now = clock.now();\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const statePort = createGorgiasStatePort(ctx.api);\n // A narrow, defensive read — see this module's header doc (C) for why the\n // full `settingsToProfile` mapping is not used here.\n const escalationTag = typeof settings?.escalationTag === 'string' ? settings.escalationTag : '';\n if (!escalationTag) {\n ctx.logger.warn('sweep: escalationTag is not configured — a stalled-send reclaim will proceed without an escalation tag');\n }\n\n await sweepExpiredReady(ctx, now);\n await sweepStalledSending(ctx, now, escalationTag, statePort);\n await sweepStalledPending(ctx, now);\n\n await upsertPipelineState(ctx.api, { lastSweepAt: now });\n}\n\nasync function sweepExpiredReady(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'ready' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n // M8: the SAME `ready -> expired` conditional transition\n // `ext-fast-response-check`'s own TTL flip uses — see that module's\n // shared helper's own doc for why this used to be two independent\n // copies of the identical write.\n await transitionGeneratedResponse(ctx.api, { id: row.id, ticketId: row.data.ticketId as string, from: 'ready', to: 'expired' });\n }\n}\n\nasync function sweepStalledSending(\n ctx: SupportKitHandlerContext,\n now: Date,\n escalationTag: string,\n statePort: ReturnType<typeof createGorgiasStatePort>,\n): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'sending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const sendingAt = toDate(row.data.sendingAt);\n if (!sendingAt || now.getTime() - sendingAt.getTime() < STALE_SENDING_THRESHOLD_MS) continue;\n\n assertTransition('sending', 'ready');\n const ticketId = row.data.ticketId as string;\n let reclaimed: boolean;\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n {\n // Status AND the hold together, in the SAME write — see the\n // module doc and `reclaimStalledSend`'s own doc for why splitting\n // this into two writes (or dropping the hold) would re-open the\n // record as a sendable `ready` row.\n ...reclaimStalledSend(),\n openTicketKey: openTicketKeyFor('ready', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n reclaimed = true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n reclaimed = false; // already moved by another worker (e.g. a late commit landing)\n } else {\n throw err;\n }\n }\n if (!reclaimed) continue;\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n await statePort.flag(ref, escalationTag);\n await ctx.api.inbox.raise({\n key: buildInboxKey(row.id, 'stalled-send'),\n severity: 'warning',\n title: `Envoi bloqué détecté — ticket ${ticketId}`,\n body: 'La réponse est restée en statut \"sending\" plus de 30 minutes et a été replacée en attente humaine.',\n });\n }\n}\n\n/**\n * A3: a `pending` row is orphaned FOREVER without this pass. Since the\n * single-pass rework, `pending` is a transient state inside one\n * `triage-tick` batch (created, then carried to a terminal status by\n * `respondToPendingResponse` in the same run) — a row still `pending` here\n * means that run died between the create and the response phase, and with\n * `retries: 0` nothing ever revisits it: `sweep`'s other two passes only\n * ever scan `ready`/`sending`, never `pending`. Worse, the stuck row keeps\n * `openTicketKey` set (only a TERMINAL status clears it, `openTicketKeyFor`'s\n * own doc), so the unique index makes any FUTURE `triage-tick` create for\n * the same ticket 409 forever — that ticket could never be drafted again by\n * any later tick.\n *\n * Chosen over a top-level catch inside the response phase itself\n * (finalising straight to `failed`): the row already carries `expiresAt`\n * (set at generation time, independent of status), so this reuses the exact\n * same staleness idiom `sweepExpiredReady` above already established,\n * instead of adding a second, different failure-handling shape to the\n * response phase. It also covers the one case a try/catch inside the\n * handler cannot — a process that dies before any `catch` runs.\n */\nasync function sweepStalledPending(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'pending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n assertTransition('pending', 'failed');\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n { status: 'failed', openTicketKey: openTicketKeyFor('failed', row.data.ticketId as string), error: 'orphaned pending row past its TTL (sweep)' },\n { ifMatch: { status: 'pending' } },\n );\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) continue; // already moved by another worker\n throw err;\n }\n }\n}\n\n","/**\n * `handle-approval` (§3.5) — event function, triggered on\n * `APPROVAL_DECIDED_EVENT` (`app.approval.decided`) for an approval the\n * response phase's (`respondToPendingResponse`) `awaiting_approval` outcome\n * requested.\n *\n * SEND PATH SHARING (§8.4's \"no forked second send implementation\"):\n * - `functions/claim-commit.ts`'s `buildSendSeam` is the SAME\n * claim/commit persistence pair the response phase wires as\n * `NodeDeps.send` — only `fromStatus` differs ('pending' there,\n * 'ready' here).\n * - The actual reply-posting/anti-collision logic is `act`\n * (`graph/nodes/act.ts`) itself, called DIRECTLY here (there is no\n * triage/draft/evaluate to redo — only the send step remains), rather\n * than re-implemented.\n *\n * Rebuilding `act`'s `state.conversation` argument from stored fields is a\n * DELIBERATELY NARROW contract, verified by reading `act.ts` line by line\n * (T22): it reads exactly THREE fields off that argument —\n * `sourceChannel` (the email/whatsapp branch), `messageCount` and\n * `lastMessageAt` (the divergence check against its OWN fresh re-read,\n * `deps.ports.conversation.read`). Every other `Conversation` field\n * (`subject`, `messages`, `customer`, `isClosed`, `lastAgentReplyAt`,\n * `hasCustomerAttachment`) is read off the FRESH re-read `act` performs\n * itself, never off this placeholder — which is why they can be filled with\n * inert defaults below. If `act` ever starts reading more off its\n * `generatedFrom` argument, this placeholder silently stops being enough;\n * there is no compile-time guard for that today.\n */\nimport type { AppApiRecord, AppHandler, ApprovalDecidedPayload, FunctionDef } from '@apotech-os/app-kit';\nimport { APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { act } from '../graph/nodes';\nimport { applyOutcomeTags } from '../graph/run-ticket';\nimport { initialState } from '../graph/state';\nimport type { Conversation, ConversationRef, Draft, ProposedAction, Verdict } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor } from '../status/machine';\nimport { parseApprovalKey } from './approval-key';\nimport { buildSendSeam } from './claim-commit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor } from './records';\n\nexport function buildHandleApprovalFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'handle-approval'),\n name: 'handle-approval',\n trigger: { type: 'event', name: APPROVAL_DECIDED_EVENT },\n retries: 3,\n // No `notify` — §3.5's table gives only the first three functions one.\n };\n}\n\nexport function createHandleApprovalHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => handleApprovalHandler(ctx, config);\n}\n\nexport async function handleApprovalHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const payload = ctx.event as unknown as ApprovalDecidedPayload;\n const id = parseApprovalKey(payload.key);\n if (!id) {\n ctx.logger.debug(`handle-approval: key \"${payload.key}\" is not a generated-response approval, ignoring`);\n return;\n }\n\n const record = await getOptional(ctx, 'generated-response', id);\n if (!record) {\n ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'ready') {\n ctx.logger.info(`handle-approval: generated-response ${id} is not ready (status=\"${String(data.status)}\"), skipping — already handled or reclaimed`);\n return;\n }\n const ticketId = data.ticketId as string;\n\n if (payload.status === 'rejected') {\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n // §8.4 invariant 2's crux: a record the sweep reclaimed to `ready` carries\n // `autoSendDecision: 'hold'` — `status: 'ready'` alone makes it look like\n // an ordinary claimable draft again, but the hold means it may ONLY leave\n // this state through a FRESH approval request, never a silent resend of a\n // decision that already fired once. Nothing else in the pipeline checks\n // `autoSendDecision` before attempting to send (`act` itself has no idea\n // it exists) — this is the one place that gate has to live.\n if (data.autoSendDecision === 'hold') {\n ctx.logger.warn(`handle-approval: generated-response ${id} is on hold (autoSendDecision), refusing to send despite the approval`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('handle-approval: settings invalid, skipping', { issues });\n return;\n }\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config), settings.nodes));\n\n // Empty-draft guard (T22 hardening, B3): `draft.text` below falls back to\n // `''` on a missing `responseText`, and `act` only refuses a MISSING draft\n // object, never an empty one — nothing today can reach this (every\n // `generated-response` reaching `ready` came through `process-response`,\n // which always writes a real `responseText`), but a future caller of\n // `finalizeNonSent`/a hand-edited record could leave one blank, and this\n // is the last line of defence before an empty email goes out. `ready ->\n // invalidated` is a legal transition (`status/machine.ts`) for exactly\n // this kind of \"this record cannot be acted on as-is\" case.\n const responseText = (data.responseText as string | null | undefined) ?? '';\n if (responseText.trim().length === 0) {\n ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);\n assertTransition('ready', 'invalidated');\n try {\n await ctx.api.update('generated-response', id, { status: 'invalidated', openTicketKey: openTicketKeyFor('invalidated', ticketId) }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n const ports = buildTicketPorts(ctx);\n const { clock, state: statePort } = ports;\n\n const conversation: Conversation = {\n ref: { id: ticketId, channel: 'gorgias' },\n subject: null,\n messages: [],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt as string) : null,\n messageCount: (data.generatedMessageCount as number | undefined) ?? 0,\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n sourceChannel: data.channel as string,\n };\n const draft: Draft = {\n text: responseText,\n sources: (data.sources as Draft['sources']) ?? [],\n // Replayed from the record, not re-read: `tracedInput` is what the\n // original drafting call was given (spec-vue-tickets-unifiee-v1 §4.1).\n // Empty on a row written before that capture existed.\n messages: (data.tracedInput as Draft['messages']) ?? [],\n revised: false,\n };\n const proposedActions: ProposedAction[] = [{ kind: 'send_reply', args: {}, idempotencyKey: id, decision: 'auto' }];\n\n // Tracks the seam's OWN claim result (T22 hardening, B2) rather than\n // re-reading the record afterwards: `act` returns `{}` with zero\n // guardrail hits BOTH when the send actually completed AND when\n // `send.claim` returned `false` (another worker already claimed this row\n // — a concurrent decision or a retried delivery of this very event), so a\n // caller that only inspects `patch` cannot tell the two apart. Capturing\n // the seam's own return value is what `buildSendSeam`'s doc already names\n // as the deciding signal — surfaced here instead of silently discarded.\n const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: 'ready' });\n let claimed = true;\n const trackedSeam = {\n claim: async (run: Parameters<typeof seam.claim>[0]) => {\n claimed = await seam.claim(run);\n return claimed;\n },\n commit: seam.commit,\n };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: 1 });\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const verdict = (data.verdict as Verdict | undefined) ?? null;\n\n const patch = await act(\n { ...initialState(), conversation, draft, verdict, proposedActions },\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'claimed', claim: trackedSeam.claim, commit: trackedSeam.commit },\n queuedAt: data.generatedAt ? new Date(data.generatedAt as string) : null,\n },\n );\n\n const guardrailHits = patch.guardrailHits ?? [];\n if (guardrailHits.length === 0) {\n if (!claimed) {\n ctx.logger.warn(\n `handle-approval: generated-response ${id} claim was lost — a concurrent worker already advanced this record, nothing to persist here`,\n );\n return;\n }\n // `act` claimed, posted and committed — apply the SAME outcome tag\n // `process-response`'s resumed `runTicket` would have applied via\n // `finish()` (B1: one shared function, so the two send routes cannot\n // diverge on the audit trail §3.6 defines).\n await applyOutcomeTags('sent', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n return;\n }\n\n // `act`'s own guardrail checks (customer_email_missing/ticket_closed/\n // agent_replied/diverged/run_deadline) all run BEFORE `send.claim`, so a\n // hit here means the claim was NEVER attempted — the record is still\n // `ready`. `ready -> no_reply_needed` is not a legal transition\n // (`status/machine.ts`'s `ALLOWED_TRANSITIONS`), so — unlike\n // `process-response` — there is no legal status change to make here; the\n // record stays `ready`. What DOES change is `autoSendDecision: 'hold'`,\n // so the very next approval decision cannot walk straight back into the\n // same hit, plus the escalation tag `applyOutcomeTags('guardrail_hold', …)`\n // applies for a human to look at why the send never went out.\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n await applyOutcomeTags('guardrail_hold', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n}\n","/**\n * Stable universal identifiers for the T23 `uiInvoke` functions' `input`\n * field defs (§3.5) — same convention as `records/ids.ts`: generated once\n * and committed, never regenerated (a function's `input` is diffed by these\n * ids, not by field name).\n */\n/** Renamed from `dryRun` (T23 post-review D) — same field identity, same uid, honest name: it bypasses the `triageEnabled` kill switch and runs the real batch, the opposite of what \"dry run\" means everywhere else in this kit. */\nexport const RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID = 'dd175229-feee-4306-a429-b25ea5dd89e4';\n\nexport const PREVIEW_TRIAGE_INPUT_TICKET_ID_UID = 'b9d5da91-ce08-4aac-ae52-5ffef730fab0';\n/** spec-vue-tickets-unifiee-v1 §4.2 — the ticket timeline's last-resort conversation read. */\nexport const GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID = '88c62cf9-d3d4-4c1b-a6ae-5ee8cbfd44fd';\n\nexport const GRAPH_DRY_RUN_INPUT_TICKET_ID_UID = '5861e7be-3a28-4852-874c-1c14e82d4b35';\nexport const GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID = 'c47b8b57-6f7a-47d7-a9d1-a18fbf71a0f0';\nexport const GRAPH_DRY_RUN_INPUT_AGENT_ID_UID = '95d38506-bc22-4f91-ad43-797ff7b54f48';\nexport const GRAPH_DRY_RUN_INPUT_OVERRIDES_UID = '306a4f7d-db5d-4144-a6bd-865889e152e2';\n/** The pasted-ticket mode: `{body, subject?, channel?}` replacing `ticketId`, so the graph can be replayed with no Gorgias ticket at all. */\nexport const GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID = '2abcc895-2751-4944-b527-78bc4604eed0';\n\nexport const TEST_AGENTS_INPUT_VIEW_ID_UID = '20227a8f-95d8-4c20-a9cd-eccb0ce39e3e';\nexport const TEST_AGENTS_INPUT_TICKET_IDS_UID = '7d27acff-b558-4783-a3ac-722f676b71a7';\nexport const TEST_AGENTS_INPUT_AGENT_ID_UID = 'ea12d731-708b-4fcc-9ebb-6c4e0d04a60e';\nexport const TEST_AGENTS_INPUT_LIMIT_UID = '95151bdf-2966-41cd-8b6f-c5b0b10c427e';\n\nexport const SUGGEST_PROMPT_INPUT_AGENT_ID_UID = '40509afa-5931-419d-8467-a52cbac5c17e';\nexport const SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID = '0c2e2f58-ffd3-4aee-a1b4-cb81d1762eb6';\n\nexport const RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID = 'bfe1e895-1608-40d8-99e9-230ab9c41473';\nexport const RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID = 'b1936472-a9dc-4b0b-8ef6-ab84733a2bfa';\n\nexport const LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID = '1ac5eb02-32da-4fd4-9462-dac4ff23b208';\n\n/**\n * T26 rework (BLOCKER 3) — `create-agent`'s own `input` field defs. Assigns\n * the new agent's `promptName` server-side (`agent/<recordId>`, §3.4) — see\n * that function's own doc for why a plain `POST records/agent` cannot.\n */\nexport const CREATE_AGENT_INPUT_NAME_UID = '0cb57453-7b02-49ce-875b-7ff079a5810d';\nexport const CREATE_AGENT_INPUT_MODEL_ID_UID = 'f19f1c10-3145-482b-8c1d-6fd3576596ff';\nexport const CREATE_AGENT_INPUT_PROVIDER_UID = '0dd94db4-f31a-4cd2-b030-1b1a4da5b43e';\nexport const CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID = 'd50f3810-b6fe-4c90-b69b-3e36ba502cdb';\n/**\n * Agent-prompt-ref rework — an agent may be created pointing at a Langfuse\n * prompt that ALREADY exists (Gorgias migration: 16 agents whose prompts\n * predate their records), instead of the server-derived `agent/<recordId>`.\n */\nexport const CREATE_AGENT_INPUT_PROMPT_NAME_UID = '102d412a-3299-42a2-ac62-6f7c4155508d';\nexport const CREATE_AGENT_INPUT_PROMPT_LABEL_UID = '04f8eeba-2d0b-4814-8009-a4a3d1530760';\n\n/**\n * T26 rework (BLOCKER 4) — `set-default-agent`'s own `input` field def.\n * Demotes the incumbent default agent and promotes the target in one\n * server-side call — see that function's own doc for why two independent\n * client-side PATCHes cannot maintain the \"at most one default agent\"\n * invariant.\n */\nexport const SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID = '0686c615-63f8-49a1-b3c7-3542bac76cd6';\n\n/**\n * T24 — the six reserved `ext-*` functions' `input` field defs (§5.2's\n * frozen wire payloads). `ext-models`/`ext-categories` have no input (the\n * gateway always sends `{}`), so they need none.\n */\nexport const EXT_CHAT_INPUT_MESSAGES_UID = '874e4408-74c0-4188-b923-a0791da4d096';\nexport const EXT_CHAT_INPUT_MODEL_ID_UID = 'd63f05b1-165d-45e0-9300-cabe5e22fa42';\nexport const EXT_CHAT_INPUT_AGENT_NAME_UID = '928f03e6-2d48-487e-85ee-15999b9cbbbb';\nexport const EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID = '86fcc5df-8545-4d77-b3d7-d741c6b1d5a5';\n\nexport const EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID = '4a597dbf-ba6f-4628-b526-759448e7ed17';\n\nexport const EXT_EVALUATION_INPUT_SATISFIED_UID = 'b1af323a-d1e0-40c7-b975-66a1e3cd4b21';\nexport const EXT_EVALUATION_INPUT_MESSAGES_UID = 'ea5d9df8-c7d5-459c-b25d-2cfe0b45ad45';\nexport const EXT_EVALUATION_INPUT_TICKET_URL_UID = '6648f361-e16b-46b2-a411-3d9cdf35e87a';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID = '0d8d5556-2ffe-4d5e-aaca-55e0eab63066';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID = '8285ab1d-e20d-4088-b9b0-176236339d1c';\nexport const EXT_EVALUATION_INPUT_MODEL_ID_UID = '1646f686-57d9-4204-b901-9d7a8e1a8078';\n\nexport const EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID = 'f2ad97ac-0abf-449a-9cc3-72efff6723c6';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID = '2dfe91f9-7177-4c44-8bcb-f841ff399ce0';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID = '63afd37e-4f0f-411b-aa62-6f480ef6cd3c';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID = '295c10ef-cb7c-4409-876a-1e384cfe6f45';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID = 'c48778a5-a8f5-4ee7-92b7-66de1bb543be';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID = '5113fc86-3865-4110-b65f-c91748816f02';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID = 'e5310144-8004-4c20-9ce4-9c0c820e3577';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID = '4813f09d-88ac-4574-8f38-be5f87a6c9ac';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID = 'e87e65e8-e078-47e3-92b7-104368952a56';\nexport const EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = '0a985d59-fd20-4672-91bb-4824b8dfb026';\n\n/**\n * T27 part B — `create-shared-prompt-version`'s own `input` field defs\n * (§3.8 SharedPromptsPage). Validates `@@@langfusePrompt:…@@@` composition\n * tags through `validateReferences` before writing (see that function's\n * own doc) — the ONE write path this page uses, scoped to `shared/*` names.\n */\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = '1039e196-cf6e-438e-8ec9-7ab422feaf4d';\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = '10ffe3e1-972e-43b4-bb45-343c4664464f';\n\n/**\n * `sync-agent-prompt-snapshot`'s own `input` field def (§5.2) — the\n * background refresh of `agent.systemPromptSnapshot` after a `createVersion`\n * /`promote` on that agent's prompt.\n */\nexport const SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = '2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2';\n\n/** `invalidate-response`'s own `input` field def — the ticket panel's \"discard this draft so the ticket can be re-processed from scratch\". */\nexport const INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = '9748baf5-97be-4a22-940d-46ef2f16a175';\n","/**\n * `run-triage-now` (§3.5) — `uiInvoke`, manual trigger equivalent to the\n * legacy `POST /triage/run`, and `run-triage-batch`, the event-triggered\n * function that actually carries the batch out.\n *\n * WHY TWO FUNCTIONS (B5). `uiInvoke` is a SYNCHRONOUS request: the platform\n * runs the handler in-process under a wall clock capped at 30 s\n * (`app-sync-invocation.service.ts`'s `DEFAULT_INVOKE_TIMEOUT_MS`, clamped\n * by `APP_SYNC_INVOKE_MAX_MS`). `runTriageBatch` processes up to\n * `settings.batchLimit` tickets (30 by default) SEQUENTIALLY, each costing\n * one triage LLM call plus — since the single-pass rework — the full\n * response phase (draft, evaluation, possible send) and several Gorgias\n * round trips — minutes, not seconds. Running it inline meant a guaranteed 504 for the operator while\n * the handler kept going unattended, and a second click starting a SECOND\n * concurrent batch: `triage-decision` rows are `create`d, not upserted, so\n * that duplicated both the rows and the LLM bill (only `generated-response`\n * is deduplicated, by its `openTicketKey` unique index).\n *\n * So the invocation now does only what fits in a request — open the run,\n * emit the event — and answers with the `runId` to follow. The batch itself\n * runs in `run-triage-batch`, a durable event-triggered function with no\n * wall clock. This is the platform's own documented pairing: see\n * `AppRunHandle.reused`'s doc in `@apotech-os/app-kit` — \"what links the\n * `uiInvoke` that triggers a treatment to the asynchronous function that\n * carries it out\".\n *\n * RE-ENTRANCE GUARD. `runs.start` is idempotent on `(kind, key)` while a\n * non-terminal run exists, so the fixed `(MANUAL_TRIAGE_RUN_KIND,\n * MANUAL_TRIAGE_RUN_KEY)` pair IS the guard: a second trigger while a batch\n * is in flight gets `reused: true` back, emits nothing, and reports the run\n * already running. The platform holds that state, not this handler — two\n * concurrent invocations cannot both win it, which a read of\n * `pipeline-state.lastTriageAt` could not have guaranteed (its cadence gate\n * is also stamped by the scheduled `triage-tick`, so it cannot tell \"a\n * manual batch is running right now\" from \"a tick just finished\"). The\n * counterpart is that `run-triage-batch` MUST terminate the run on every\n * path, including failure — see its `try`/`catch` below — otherwise the\n * guard would hold the button closed for good.\n *\n * `input.ignoreTriageDisabled` mirrors the legacy `{dry_run}` body field —\n * renamed here (T23 post-review D): it lets an operator ask for a run while\n * `triageEnabled` is off (the settings-level kill switch stays authoritative\n * for `triage-tick`'s own cron, but a human clicking \"run now\" already\n * knows they are overriding it). The legacy name is not worth preserving —\n * §0 defines \"dry run\" as \"no external action\", three sibling functions\n * (`preview-triage`, `graph-dry-run`, `test-agents`) implement exactly that,\n * and this flag does the OPPOSITE: it bypasses a kill switch and runs the\n * real batch. `ignoreTriageDisabled` does NOT change what the batch\n * writes — this function ALWAYS classifies for real and ALWAYS writes\n * `triage-decision`/`generated-response` rows, exactly like a scheduled\n * tick, whether or not the flag is set. The legacy `/triage/run` never\n * wrote anything different for a \"dry run\" either (`dry_run` only bypassed\n * `triage_enabled`) — a fully side-effect-free \"would triage-tick run\"\n * preview is `preview-triage`'s job (single ticket) and `graph-dry-run`'s\n * (full graph), not this one's (a real batch).\n *\n * `minRole: 'EDITOR'`: triggering a real classification pass — which spends\n * LLM budget and can tag/escalate real tickets — is an editing action, not a\n * read. `VIEWER` (T24's `ext-*` floor) would let a read-only support agent\n * fire a batch run; that is not this function's threat model.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID } from './ids';\nimport { runTriageBatch } from './triage-tick';\n\n/**\n * The app custom event `run-triage-now` emits and `run-triage-batch`\n * subscribes to. Must be declared in the consuming app's `manifest.emits`\n * (`buildSupportPipeline`'s `emits` fragment) — the platform rejects an\n * undeclared name with 403, and refuses to sync a manifest whose event\n * trigger names one it does not emit.\n */\nexport const TRIAGE_RUN_REQUESTED_EVENT = 'triage.run.requested';\n\n/** `(kind, key)` of the applicative run — fixed, because it IS the re-entrance guard (see this module's header doc). */\nexport const MANUAL_TRIAGE_RUN_KIND = 'run-triage-now';\nexport const MANUAL_TRIAGE_RUN_KEY = 'manual';\n\nexport interface RunTriageNowInput {\n /** Bypasses the `triageEnabled` kill switch and runs the real batch anyway — NOT a dry run (see this module's own header doc). */\n ignoreTriageDisabled?: boolean;\n}\n\nexport interface RunTriageNowResult {\n /** The applicative run to follow (`useAppRuns({kind: 'run-triage-now'})`) — the batch's outcome lives there, not in this response. */\n runId: string;\n /** `'already-running'` when the re-entrance guard matched an in-flight batch and nothing new was queued. */\n status: 'queued' | 'already-running';\n}\n\n/** Payload of `TRIAGE_RUN_REQUESTED_EVENT`, as `run-triage-batch` receives it (the unwrapped event data). */\nexport interface TriageRunRequestedPayload {\n runId?: string;\n ignoreTriageDisabled?: boolean;\n}\n\nexport function buildRunTriageNowFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-now'),\n name: 'run-triage-now',\n // The handler is two API calls now, not a batch: a budget well under the\n // platform's 15 s default states that, and turns a hung platform call\n // into a fast error instead of a slow one.\n trigger: { type: 'uiInvoke', minRole: 'EDITOR', timeoutMs: 10_000 },\n input: [\n {\n universalIdentifier: RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID,\n name: 'ignoreTriageDisabled',\n type: FieldType.BOOLEAN,\n label: 'Ignore triageEnabled',\n description: 'Bypass the triageEnabled kill switch and run the real batch anyway. This is NOT a dry run — tickets are classified and tagged for real.',\n isNullable: true,\n },\n ],\n };\n}\n\n/**\n * `retries: 0` and `concurrency: 1`, for `triage-tick`'s own reasons: a\n * retried batch re-classifies (and re-bills) every ticket it already\n * handled and writes a second `triage-decision` for each, and two batches\n * running at once over the same view do the same. The re-entrance guard in\n * `run-triage-now` closes the operator-facing door; `concurrency: 1` closes\n * the platform-facing one.\n */\nexport function buildRunTriageBatchFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-batch'),\n name: 'run-triage-batch',\n trigger: { type: 'event', name: TRIAGE_RUN_REQUESTED_EVENT },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createRunTriageNowHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => runTriageNowHandler(ctx as SupportKitHandlerContext, config, (input as RunTriageNowInput) ?? {});\n}\n\nexport function createRunTriageBatchHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) =>\n runTriageBatchEventHandler(ctx as SupportKitHandlerContext, config, (input as TriageRunRequestedPayload) ?? {});\n}\n\nexport async function runTriageNowHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: RunTriageNowInput,\n): Promise<RunTriageNowResult> {\n const ignoreTriageDisabled = input.ignoreTriageDisabled ?? false;\n // Both guards are re-checked by `run-triage-batch` (an event can also be\n // replayed): they run HERE so the operator gets the refusal in their own\n // request, as a message on screen, instead of a queued run that fails out\n // of sight.\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n assertRunnable(ctx, settings, ignoreTriageDisabled);\n\n const run = await ctx.api.runs.start({\n kind: MANUAL_TRIAGE_RUN_KIND,\n key: MANUAL_TRIAGE_RUN_KEY,\n message: 'Triage manuel demandé',\n metadata: { ignoreTriageDisabled },\n });\n if (run.reused) {\n ctx.logger.info('run-triage-now: a manual batch is already running, not queueing a second one', { runId: run.id });\n return { runId: run.id, status: 'already-running' };\n }\n\n try {\n // `_key` deduplicates the emission itself at the Inngest level, so a\n // retried invocation cannot fan out into two batches for one run.\n await ctx.api.events.send(TRIAGE_RUN_REQUESTED_EVENT, {\n _key: run.id,\n runId: run.id,\n ignoreTriageDisabled,\n });\n } catch (err) {\n // A run left open would keep the guard closed forever — nothing else\n // will ever terminate it, since no batch was queued.\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n\n return { runId: run.id, status: 'queued' };\n}\n\nexport async function runTriageBatchEventHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n payload: TriageRunRequestedPayload,\n): Promise<void> {\n const { runId } = payload;\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n\n try {\n assertRunnable(ctx, settings, payload.ignoreTriageDisabled ?? false);\n const result = await runTriageBatch(ctx, config, settings);\n if (runId) await ctx.api.runs.succeed(runId, result);\n } catch (err) {\n if (runId) await ctx.api.runs.fail(runId, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n}\n\n/** The two refusals shared by the trigger and the batch — invalid settings, and the `triageEnabled` kill switch. */\nfunction assertRunnable(ctx: SupportKitHandlerContext, settings: SupportKitSettings, ignoreTriageDisabled: boolean): void {\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n if (!ignoreTriageDisabled && !settings.triageEnabled) {\n throw new ctx.NonRetriableError('Triage is disabled (triageEnabled is off) — pass ignoreTriageDisabled to override.');\n }\n}\n","/**\n * `invalidate-response` — `uiInvoke`, an operator discards a generated\n * response from the ticket panel so the ticket can be re-processed from\n * scratch, as if the pipeline had never drafted for it.\n *\n * What \"from scratch\" means here, precisely: `invalidated` is a TERMINAL\n * status, so the write below clears `openTicketKey` (`openTicketKeyFor`) —\n * the unique index no longer holds the ticket, and the next pass that sees\n * it (the cron over the view, a manual `run-triage-now`) triages AND drafts\n * it anew instead of 409-ing on the old row. What it deliberately does NOT\n * touch: the `triage-decision` history (an audit trail, not state), and the\n * Gorgias tags already applied — whether the ticket re-enters the source\n * view is the view's own filter's business, not this kit's.\n *\n * WHICH ROWS QUALIFY is the state machine's ruling, not a policy choice of\n * this handler: `isInvalidatableStatus` (`status/machine.ts`) is derived from\n * the transition table, so this handler and the button that offers the action\n * cannot drift apart. Today that means `pending` and `ready`. `sending` is\n * excluded — its reply may ALREADY have been posted, which is `sweep`'s\n * stalled-send reclaim to resolve rather than a human's to guess at — and\n * every terminal status has nothing left to invalidate: the ticket is already\n * free. A row that is already `invalidated` returns success rather than an\n * error (idempotent: the operator's goal is the state, not the transition).\n *\n * `pending` matters most in the case it was originally excluded for. It is a\n * transient mid-run state only while the run that opened it is alive; when\n * that process dies, the row is stranded with the ticket's `openTicketKey`\n * held, and every later tick re-triages the ticket — paying the LLM call and\n * writing another decision row — only to 409 on the create and abandon it,\n * until the sweep's TTL pass days later. This button is the way out.\n *\n * The write is the shared `transitionGeneratedResponse`, with `ifMatch` on\n * the status actually read: a lost race means another worker moved the row\n * between the operator's read and their click — possibly all the way to\n * `sending` — so it surfaces as an explicit refusal to refresh on, never as\n * a silent success. That conditional write is also what makes invalidating a\n * genuinely in-flight `pending` row safe with no second guard: either it\n * lands and the live run abandons on its own 409, or the run wins and this\n * is refused.\n *\n * `minRole: 'EDITOR'`: discarding a draft alters what the pipeline will do\n * next (a full re-triage + re-draft LLM spend); that is an editing action.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { getOptional } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { isGeneratedResponseStatus, isInvalidatableStatus } from '../status/machine';\nimport { INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID } from './ids';\n\nexport interface InvalidateResponseInput {\n generatedResponseId: string;\n}\n\nexport interface InvalidateResponseResult {\n status: 'invalidated';\n}\n\nexport function buildInvalidateResponseFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'invalidate-response'),\n name: 'invalidate-response',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR', timeoutMs: 10_000 },\n input: [\n {\n universalIdentifier: INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID,\n name: 'generatedResponseId',\n type: FieldType.TEXT,\n label: 'Generated response id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createInvalidateResponseHandler(): AppHandler {\n return (ctx, input) =>\n invalidateResponseHandler(ctx as SupportKitHandlerContext, (input as unknown as InvalidateResponseInput) ?? {});\n}\n\nconst REFUSALS: Record<string, string> = {\n sending: \"La réponse est en cours d'envoi — elle ne peut plus être invalidée.\",\n sent: 'La réponse a déjà été envoyée au client — elle ne peut plus être invalidée.',\n};\n\nexport async function invalidateResponseHandler(\n ctx: SupportKitHandlerContext,\n input: InvalidateResponseInput,\n): Promise<InvalidateResponseResult> {\n const id = input?.generatedResponseId?.trim();\n if (!id) throw new ctx.NonRetriableError('generatedResponseId is required');\n\n const record = await getOptional(ctx, 'generated-response', id);\n if (!record) throw new ctx.NonRetriableError(`Réponse générée introuvable (${id}).`);\n\n const data = record.data as Record<string, unknown>;\n const status = String(data.status ?? '');\n if (status === 'invalidated') return { status: 'invalidated' };\n if (!isGeneratedResponseStatus(status) || !isInvalidatableStatus(status)) {\n throw new ctx.NonRetriableError(\n REFUSALS[status] ?? `La réponse est en statut terminal \"${status}\" — le ticket est déjà libre d'être retraité.`,\n );\n }\n\n const moved = await transitionGeneratedResponse(ctx.api, {\n id,\n ticketId: String(data.ticketId ?? ''),\n from: status,\n to: 'invalidated',\n });\n if (!moved) {\n throw new ctx.NonRetriableError(\"La réponse a changé d'état entre-temps — actualisez la page avant de réessayer.\");\n }\n return { status: 'invalidated' };\n}\n","/**\n * `preview-triage` (§3.5) — `uiInvoke`, dry-run classification of ONE\n * ticket, equivalent to the legacy `POST /triage/preview`. Runs\n * `runTicket(deps, {until:'triage'})` — the same checkpoint `triage-tick`\n * uses — but through the recording `state`/`reply` ports (`adapters/\n * recording-ports.ts`, T21) instead of the real Gorgias-writing ones, so\n * nothing is tagged and no `triage-decision`/`generated-response` row is\n * created. `conversation`/`llm`/`prompt` stay the REAL ctx adapters: a\n * preview reads and classifies for real, per §0's dry-run arbitrage\n * (\"aucune action externe (ni réponse, ni tag)\").\n *\n * Narrower than `graph-dry-run`: this stops at the SAME checkpoint\n * `triage-tick` does (triage + escalate only), never drafts. Use\n * `graph-dry-run` to see the full graph, including a draft, for one ticket.\n *\n * `minRole: 'VIEWER'`: a single classification preview spends one LLM call\n * but writes nothing and cannot escalate/send anything for real — the same\n * risk profile as a read.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { createRecordingReplyPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport { resolveHandledTags } from '../adapters/gorgias-tags';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { PREVIEW_TRIAGE_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, listCategories, resolveDraftAgent, toCategoryReferential } from './records';\n\nexport interface PreviewTriageInput {\n ticketId: string;\n}\n\nexport interface PreviewTriageResult {\n ticketId: string;\n classification: Classification | null;\n escalated: boolean;\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n}\n\nexport function buildPreviewTriageFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'preview-triage'),\n name: 'preview-triage',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: PREVIEW_TRIAGE_INPUT_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createPreviewTriageHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => previewTriageHandler(ctx as SupportKitHandlerContext, config, input as unknown as PreviewTriageInput);\n}\n\nexport async function previewTriageHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: PreviewTriageInput,\n): Promise<PreviewTriageResult> {\n const ticketId = input?.ticketId?.trim();\n if (!ticketId) throw new ctx.NonRetriableError('ticketId is required');\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const agent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const realPorts = buildTicketPorts(ctx);\n const recordingState = createRecordingStatePort(ctx.api);\n const recordingReply = createRecordingReplyPort();\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: recordingReply.port,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: recordingState.port,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n // `runTicket(deps, {until:'triage'})` deliberately never calls\n // `ports.state.record` (see its own doc in `graph/run-ticket.ts`) — the\n // recording port above never fires for this checkpoint, so the tag set a\n // REAL `triage-tick` would apply is computed here directly, off the same\n // `resolveHandledTags` both the real and recording `StatePort` share. No\n // write happens either way: this is a plain (already-read-only) lookup.\n const wouldHaveTagged = state.classification\n ? await resolveHandledTags(ctx.api, state.classification, profile.audit)\n : [];\n\n return {\n ticketId,\n classification: state.classification,\n escalated: state.escalated,\n wouldHaveTagged,\n };\n}\n","/**\n * `get-ticket-conversation` (spec-vue-tickets-unifiee-v1 §4.2) — `uiInvoke`,\n * the ticket timeline's LAST-RESORT source for the \"Reçu\" step.\n *\n * The timeline prefers what was persisted at run time\n * (`generated-response.tracedInput`, then\n * `response-comparison.conversationMessages`) because that is what the model\n * actually read. Two populations have neither: the decisions imported from\n * the legacy backoffice, and every ticket the graph stopped at the tag — no\n * `generated-response` row was ever opened for those, so nothing captured\n * their conversation.\n *\n * What this function returns is therefore NOT what the model saw: it is the\n * thread AS IT STANDS NOW, which may have gained an agent reply, or lost\n * nothing at all, since the decision was taken. The page labels it as such\n * rather than letting the two read alike — that honesty is the whole point of\n * keeping this a separate, explicitly-called source instead of silently\n * back-filling `tracedInput`.\n *\n * `minRole: 'VIEWER'`: a pure read. It spends no LLM call, writes no record,\n * applies no tag, and reaches the same conversation the pipeline pages\n * already quote through `responseText` and the verdict's own free text.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID } from './ids';\n\nexport interface GetTicketConversationInput {\n ticketId: string;\n}\n\nexport interface GetTicketConversationResult {\n ticketId: string;\n subject: string | null;\n /** Customer and agent turns, oldest first — the `Message` shape of `domain/conversation.ts`. */\n messages: Array<{ role: 'user' | 'assistant'; content: string }>;\n /** `null` when the thread carries no message at all. */\n lastMessageAt: string | null;\n isClosed: boolean;\n}\n\nexport function buildGetTicketConversationFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'get-ticket-conversation'),\n name: 'get-ticket-conversation',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createGetTicketConversationHandler(): AppHandler {\n return (ctx, input) =>\n getTicketConversationHandler(ctx as SupportKitHandlerContext, (input as unknown as GetTicketConversationInput) ?? { ticketId: '' });\n}\n\nexport async function getTicketConversationHandler(\n ctx: SupportKitHandlerContext,\n input: GetTicketConversationInput,\n): Promise<GetTicketConversationResult> {\n const ticketId = input?.ticketId?.trim();\n if (!ticketId) throw new ctx.NonRetriableError('ticketId is required');\n\n // No `validateSettings` gate, unlike every handler that RUNS the graph:\n // reading a thread needs a Gorgias connection and nothing else. A tenant\n // whose triage settings are half-configured must still be able to open the\n // history of a ticket its previous configuration already decided on.\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const conversation = await buildTicketPorts(ctx).conversation.read(ref);\n\n return {\n ticketId,\n subject: conversation.subject,\n messages: conversation.messages.map((message) => ({ role: message.role, content: message.content })),\n lastMessageAt: conversation.lastMessageAt ? conversation.lastMessageAt.toISOString() : null,\n isClosed: conversation.isClosed,\n };\n}\n","/**\n * `runGraphDryRun` — the graph-dry-run engine itself, split out from\n * `graph-dry-run.ts`'s ctx-wiring/overrides so it can be exercised directly\n * against `graph/run-ticket.fixtures.ts`'s `harness()` (real nodes, fake\n * ports) instead of a fully faked `SupportKitHandlerContext`. §0's dry-run\n * arbitrage: \"graphe complet tant qu'aucune action externe (ni réponse, ni\n * tag, ni écriture de record)\".\n *\n * Takes an already-assembled `NodeDeps` (`base`) — real ports in\n * production (`buildTicketPorts(ctx)`), fake ones in a graph-level test —\n * and overrides exactly the surfaces that could otherwise leak a write:\n * `ports.reply`, `ports.state`, `ports.llm`/`ports.evaluator` (still REAL\n * calls, only their trace is captured) and `send`. `send` is ALWAYS\n * overridden to the recording `{mode:'claimed', ...}` seam, never left as\n * whatever `base.send` was assembled with — a dry run must exercise `act`'s\n * claim→post→commit path for real (so an operator sees the graph actually\n * reach `act`, not silently stop short of it), not skip it because the\n * caller happened to assemble `base` with `{mode:'none'}` (post-T21-review\n * C, `adapters/recording-ports.ts`'s own doc on `createRecordingSendPort`).\n */\nimport { createRecordingLlmPort, createRecordingReplyPort, createRecordingSendPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport type { Classification, PromptRef } from '../domain';\nimport type { RecordedCompletion, WouldHaveReplied } from '../adapters/recording-ports';\nimport type { SupportKitApi } from '../adapters/api';\nimport { NODE_NAMES, type NodeDeps, type NodeName, type NodeStep, type TicketRunState } from '../graph/state';\nimport { runTicket, type ResumeFrom } from '../graph/run-ticket';\n\n/**\n * A dry run may not outlive an admin's patience, nor the `uiInvoke`\n * request's own HTTP timeout (T23 post-review C2) — ported from the legacy\n * `DRY_RUN_DEADLINE_MS`. Both `graph-dry-run.ts` (one ticket) and\n * `test-agents.ts` (up to `MAX_LIMIT` tickets, sequential) build their\n * `AbortSignal` from this constant: without it, neither call site ever\n * aborted, so `test-agents` in particular could run up to 100 full graphs\n * with no bound until the platform itself killed the connection mid-flight\n * — every completion already billed, nothing returned to the operator.\n */\nexport const DRY_RUN_DEADLINE_MS = 3 * 60 * 1000;\n\nexport interface GraphDryRunDeps {\n /** Fully assembled `NodeDeps` — `reply`/`state`/`llm`/`evaluator`/`send` are overridden below regardless of what this carries. */\n base: NodeDeps;\n /** For the recording `StatePort`'s category `extraTags` lookup (a real read — see `recording-ports.ts`). */\n api: SupportKitApi;\n resume?: ResumeFrom;\n /**\n * The writer's prompt for the category triage just named — `runGraphDryRun`\n * calls this between triage and `draft`, and drafts with what it returns.\n *\n * Production never binds the writer before triage either: `triage-tick`\n * resolves the agent from the MATCHED category (`resolveDraftAgent`) and\n * `process-response` builds `prompts.draft` from it on the resumed run.\n * A replay that kept its up-front binding drafts with the default agent's\n * prompt whatever triage found — and on an install with no default agent\n * at all, fails in `draft` on the `no-agent-configured` sentinel while\n * triage had just named a category that HAS an agent.\n *\n * Ignored on a resumed run (`resume`): the classification was forced by\n * the caller, who bound the writer to match it up-front.\n */\n rebindDraft?: (classification: Classification | null) => Promise<PromptRef>;\n}\n\nexport interface GraphDryRunResult {\n ticketId: string;\n outcome: TicketRunState['outcome'];\n /** Nodes the graph called, in order. `evaluate` appears twice on a revision. */\n steps: NodeStep[];\n /** Nodes it did not call. */\n skipped: NodeName[];\n completions: RecordedCompletion[];\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n /** The reply it WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied: WouldHaveReplied | null;\n /**\n * Whether the run actually reached `act`'s claim/commit seam — proof the\n * send path was exercised, not skipped because `send` defaulted to\n * `{mode: 'none'}` (see this module's own header doc).\n */\n sendSeamExercised: boolean;\n draft: TicketRunState['draft'];\n verdict: TicketRunState['verdict'];\n guardrailHits: string[];\n error?: string;\n}\n\n/**\n * The unresumed replay, split at the triage checkpoint exactly where\n * production splits it — `triage-tick`'s `runTicket(deps, {until:'triage'})`\n * then `process-response`'s resumed call — so the writer can be rebound\n * from the classification in between (`GraphDryRunDeps.rebindDraft`). With\n * no rebinder the split would buy nothing, so the run stays a single call.\n *\n * Like production, the resumed half re-reads the conversation: `fetchContext`\n * therefore appears TWICE in the trace, which is what actually happened.\n */\nasync function runFromTriage(deps: NodeDeps, rebindDraft: GraphDryRunDeps['rebindDraft']): Promise<TicketRunState> {\n if (!rebindDraft) return runTicket(deps);\n\n const triaged = await runTicket(deps, { until: 'triage' });\n // `until: 'triage'` returns without an outcome unless `fetchContext` itself\n // failed — that run is already finished, and resuming it would only fail again.\n if (triaged.outcome) return triaged;\n\n const draft = await rebindDraft(triaged.classification);\n const rebound: NodeDeps = { ...deps, profile: { ...deps.profile, prompts: { ...deps.profile.prompts, draft } } };\n return runTicket(rebound, { resume: { classification: triaged.classification, escalated: triaged.escalated } });\n}\n\nexport async function runGraphDryRun({ base, api, resume, rebindDraft }: GraphDryRunDeps): Promise<GraphDryRunResult> {\n const recordingReply = createRecordingReplyPort();\n const recordingState = createRecordingStatePort(api);\n const recordingSend = createRecordingSendPort();\n const recordingLlm = createRecordingLlmPort(base.ports.llm);\n const recordingEvaluator = base.ports.evaluator ? createRecordingLlmPort(base.ports.evaluator) : null;\n\n const steps: NodeStep[] = [];\n const deps: NodeDeps = {\n ...base,\n ports: {\n ...base.ports,\n reply: recordingReply.port,\n state: recordingState.port,\n llm: recordingLlm.port,\n ...(recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}),\n },\n send: recordingSend.send,\n trace: (step) => steps.push(step),\n };\n\n let result: TicketRunState | null = null;\n let error: string | undefined;\n try {\n result = resume ? await runTicket(deps, { resume }) : await runFromTriage(deps, rebindDraft);\n } catch (err) {\n error = err instanceof Error ? err.message : String(err);\n }\n\n const seen = new Set(steps.map((s) => s.node));\n const completions = [...recordingLlm.completions, ...(recordingEvaluator?.completions ?? [])];\n\n return {\n ticketId: base.ref.id,\n outcome: result?.outcome ?? null,\n steps,\n skipped: NODE_NAMES.filter((name) => !seen.has(name)),\n completions,\n wouldHaveTagged: recordingState.wouldHaveTagged(),\n wouldHaveReplied: recordingReply.wouldHaveReplied(),\n sendSeamExercised: recordingSend.calls.length > 0,\n draft: result?.draft ?? null,\n verdict: result?.verdict ?? null,\n guardrailHits: result?.guardrailHits ?? [],\n ...(error ? { error } : {}),\n };\n}\n","/**\n * `graph-dry-run` (§3.5) — `uiInvoke`, replay of the FULL graph for one\n * ticket, equivalent to the legacy `POST /agents/graph-run`. Ports the\n * `GraphDryRunOverrides` switches from\n * `extension-overview/backoffice/src/services/graphDryRun.ts` verbatim\n * (T21 deferred them here — their semantics are non-obvious, see each\n * function's own doc below) and delegates the actual replay to\n * `runGraphDryRun` (`./graph-dry-run-core.ts`), which owns the\n * zero-external-action guarantee.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): unlike `preview-triage`'s single\n * classification, this replays the FULL graph and can conjure trial\n * evaluate/revise nodes — real LLM spend against the app's shared quota,\n * re-invocable at will. `VIEWER` is the read-only support-agent floor;\n * \"writes nothing to Gorgias\" is the wrong axis to gate on when the\n * resource actually being spent is money.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { AgentProfile, Classification, Conversation } from '../domain';\nimport type { ConversationRef } from '../domain';\nimport type { ConversationPort } from '../graph/ports';\nimport type { EvaluateNodeConfig, ReviseNodeConfig } from '../domain/profile';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { ResumeFrom } from '../graph/run-ticket';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID, GRAPH_DRY_RUN_INPUT_OVERRIDES_UID, GRAPH_DRY_RUN_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n draftRebinder,\n listCategories,\n resolveDraftAgent,\n toAgent,\n toCategoryReferential,\n} from './records';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\n\nexport interface GraphDryRunOverrides {\n /** Off skips the judge entirely — the graph then ends at `ready`. On conjures a trial judge when the tenant has none. */\n evaluate?: boolean;\n /** Off makes `needsRevision` always false. On resolves a revision node from the writer's model when the tenant has none. */\n revise?: boolean;\n /** Off empties the guardrail catalogue and forces `whatsappMode: 'auto_reply'`, to reach `act` without a hold. */\n guardrails?: boolean;\n /** On opens auto-send for this run only (still requires a real `senderEmail`). */\n autoSend?: boolean;\n}\n\n/**\n * A ticket typed by hand instead of read from Gorgias. `channel` is not\n * cosmetic: `sourceChannel === 'whatsapp'` is what the `whatsapp_stop` /\n * `not_customer_turn` guardrails and the WhatsApp style prompt key off\n * (`domain/conversation.ts`'s own contract note), so a pasted WhatsApp\n * message must be replayable as one.\n */\nexport interface GraphDryRunInlineTicket {\n /** The customer's message. The only required part — everything else has a defensible default. */\n body: string;\n subject?: string | null;\n channel?: 'email' | 'whatsapp';\n}\n\n/**\n * Every field is `| null` rather than merely optional, because the platform\n * validates this payload against the manifest with `fieldDefsToZod`\n * (`app-input-validation.ts`), where `isNullable: true` permits the VALUE\n * null but NOT an absent key — an omitted optional field is rejected with\n * `422 INVALID_INPUT` before the handler runs. Callers therefore send every\n * declared key, `null` when unset, and this type says so.\n */\nexport interface GraphDryRunInput {\n /** Mutually exclusive with `inlineTicket` — exactly one of the two. */\n ticketId?: string | null;\n /** Replay on a ticket that does not exist in Gorgias (see below). */\n inlineTicket?: GraphDryRunInlineTicket | null;\n /** Forces the writing agent; falls back to the category's, then to the default one. */\n agentId?: string | null;\n /** Forces the category — and with it the classification, so triage does not run. */\n categoryId?: string | null;\n overrides?: GraphDryRunOverrides | null;\n}\n\n/**\n * The revision switch (ported verbatim from `GraphDryRunOverrides.revise`'s\n * legacy doc): `false` removes the node; `true` CONJURES one from the\n * writer's own model when the tenant has none configured, so an operator\n * can try the correction pass on one ticket before turning it on for\n * everybody. `reasoning: 'off'` is required here — an unconfigured trial\n * revise node must never be rejected by a (model, effort) validation rule\n * the tenant never opted into.\n */\nfunction resolveReviseNode(profile: AgentProfile, override: boolean | undefined): ReviseNodeConfig | null {\n if (override === false) return null;\n if (profile.nodes.revise) return profile.nodes.revise;\n if (override !== true) return null;\n const writer = profile.nodes.draft;\n return writer ? { model: writer.model, provider: writer.provider, reasoning: 'off' } : null;\n}\n\n/**\n * The `evaluate` switch, in its FORCING direction (`true`): a tenant with no\n * judge gets a trial one, model left to the prompt (kit's own resolution),\n * threshold pinned to the tenant's own auto-send floor. `false` empties the\n * node outright — `applyOverrides` below is what does that, this helper\n * only ever ADDS a node.\n */\nfunction withTrialJudge(profile: AgentProfile, override: boolean | undefined): AgentProfile {\n if (override !== true || profile.nodes.evaluate) return profile;\n const trial: EvaluateNodeConfig = {\n model: profile.nodes.draft?.model ?? '',\n provider: 'openai',\n reasoning: 'off',\n minConfidence: profile.autoSend.minConfidence,\n escalationEnabled: false,\n };\n return { ...profile, nodes: { ...profile.nodes, evaluate: trial } };\n}\n\n/** Turns the per-run switches into a profile the graph reads normally — never persisted. */\nfunction applyOverrides(profile: AgentProfile, overrides: GraphDryRunOverrides): AgentProfile {\n const withEvaluate = overrides.evaluate === false ? { ...profile, nodes: { ...profile.nodes, evaluate: null } } : withTrialJudge(profile, overrides.evaluate);\n\n return {\n ...withEvaluate,\n nodes: { ...withEvaluate.nodes, revise: resolveReviseNode(withEvaluate, overrides.revise) },\n // `auto_reply`, not `draft_only`: `draft_only` blocks `isAutoSendEligible`\n // outright for a WhatsApp ticket, which would stop the run at `ready`\n // and defeat the whole point of this override — reaching `act` with\n // nothing standing in the way. The category opt-in is bypassed the same\n // way triage-tick's own dry-run-adjacent callers do it (see below,\n // `category: {autoReplyEnabled: true, …}`).\n //\n // `judgemeEscalateOnly: false` (T23 post-review C1): that rule is NOT\n // filtered through `active` (`graph/nodes/guardrails.ts` checks it\n // unconditionally) and `settingsToProfile` hardcodes it to `true` with\n // no settings surface to turn it off — so without this, an operator\n // dry-running a Judge.me ticket with guardrails off still gets held by\n // a guardrail this override exists specifically to bypass.\n guardrails:\n overrides.guardrails === false\n ? { active: [], params: { ...withEvaluate.guardrails.params, whatsappMode: 'auto_reply', judgemeEscalateOnly: false } }\n : withEvaluate.guardrails,\n autoSend: { ...withEvaluate.autoSend, enabled: overrides.autoSend === true && !!withEvaluate.autoSend.senderEmail },\n };\n}\n\n/**\n * The classification a forced category stands for. Confidence is `high` on\n * purpose: the operator asked for THIS category, so the run must not then\n * be held by the `triage_not_high` guardrail for a decision they made\n * themselves. Never claims the conversation is over on the operator's\n * behalf.\n */\nfunction forcedClassification(tagName: string): Classification {\n return { category: tagName, confidence: 'high', reasoning: 'operator: catégorie forcée', isFallback: false, conversationOver: false };\n}\n\n/**\n * The id a pasted ticket runs under. Not a Gorgias id and never mistakable\n * for one: it appears in the result, in the recorded tags and in the\n * would-have-replied payload, and reading it as a real ticket number would\n * send someone looking for a ticket that does not exist.\n */\nexport const INLINE_TICKET_ID = 'ticket-saisi';\n\n/**\n * A `ConversationPort` over a typed-in ticket — the ONE port that still\n * reached Gorgias during a dry run (`reply`/`state`/`send` are already\n * swapped for recorders by `runGraphDryRun`, and the read tools are\n * neutralised by `createNoToolContext`). With this in its place a dry run\n * touches no Gorgias endpoint at all.\n *\n * `read` returns the SAME conversation object on every call, which matters\n * for `act`: it re-reads the conversation right before sending and holds\n * the reply when `messageCount` has moved (the I8 anti-divergence check).\n * A port that rebuilt a fresh object per call would be fine today, but one\n * that recomputed the count from anything time-dependent would hold every\n * pasted run for a collision that never happened.\n *\n * `listPending` returns nothing: a pasted ticket belongs to no view, and\n * this port is only ever assembled for a single-ticket replay.\n */\nfunction createInlineConversationPort(ticket: GraphDryRunInlineTicket, now: Date): ConversationPort {\n const conversation: Conversation = {\n ref: { id: INLINE_TICKET_ID, channel: 'gorgias' },\n subject: ticket.subject?.trim() ? ticket.subject.trim() : null,\n messages: [{ role: 'user', content: ticket.body }],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: now,\n messageCount: 1,\n // No agent ever answered a ticket that was just typed: `null` is the\n // truth, and it is also what keeps `not_customer_turn` from holding the\n // run before a single node has looked at the text.\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER\n // (gorgias) while every channel guardrail and the style prompt read this\n // one (`domain/conversation.ts`).\n sourceChannel: ticket.channel ?? 'email',\n };\n return {\n listPending: async () => [],\n read: async () => conversation,\n };\n}\n\nexport function buildGraphDryRunFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'graph-dry-run'),\n name: 'graph-dry-run',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n // Nullable since the pasted-ticket mode: the handler enforces \"exactly\n // one of ticketId/inlineTicket\", which a per-field flag cannot express.\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_TICKET_ID_UID, name: 'ticketId', type: FieldType.TEXT, label: 'Ticket id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID,\n name: 'inlineTicket',\n type: FieldType.JSON,\n label: 'Inline ticket',\n description: '{body, subject?, channel?} — replays a typed-in ticket instead of reading one from Gorgias.',\n isNullable: true,\n },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, name: 'categoryId', type: FieldType.TEXT, label: 'Category id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_OVERRIDES_UID,\n name: 'overrides',\n type: FieldType.JSON,\n label: 'Overrides',\n description: '{evaluate?, revise?, guardrails?, autoSend?}',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createGraphDryRunHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => graphDryRunHandler(ctx as SupportKitHandlerContext, config, input as unknown as GraphDryRunInput);\n}\n\nexport async function graphDryRunHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: GraphDryRunInput,\n): Promise<GraphDryRunResult> {\n const ticketId = input?.ticketId?.trim();\n const inlineBody = input?.inlineTicket?.body?.trim();\n // Exactly one of the two. Refusing BOTH rather than silently preferring one\n // matters: a caller that sends a ticket id AND a pasted body has a bug, and\n // reading the wrong one would produce a plausible result about the wrong\n // ticket entirely.\n if (ticketId && inlineBody) throw new ctx.NonRetriableError('Provide either ticketId or inlineTicket, not both');\n if (!ticketId && !inlineBody) throw new ctx.NonRetriableError('ticketId or inlineTicket.body is required');\n const inlineTicket = inlineBody ? { ...(input.inlineTicket as GraphDryRunInlineTicket), body: inlineBody } : null;\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const forcedCategory = input.categoryId ? (categories.find((c) => c.id === input.categoryId) ?? null) : null;\n if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category \"${input.categoryId}\" not found`);\n\n const agent = input.agentId\n ? toAgent(await ctx.api.get('agent', input.agentId))\n : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);\n\n const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n const profile = applyOverrides(baseProfile, input.overrides ?? {});\n\n const realPorts = buildTicketPorts(ctx);\n const ref: ConversationRef = { id: inlineTicket ? INLINE_TICKET_ID : (ticketId as string), channel: 'gorgias' };\n const budget = createBudget({ signal: AbortSignal.timeout(DRY_RUN_DEADLINE_MS), maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: inlineTicket ? createInlineConversationPort(inlineTicket, realPorts.clock.now()) : realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n // Bypassed the same way `triage-tick`'s dry-run-adjacent batch is:\n // reaching `act` is what the `autoSend` override is for, and requiring\n // the category to ALSO have opted in would make the override inert on\n // every category that has auto-reply off — which is all of them today.\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n\n const resume: ResumeFrom | undefined = forcedCategory\n ? { classification: forcedClassification(forcedCategory.tagName), escalated: false }\n : undefined;\n\n // Nobody forced the writer or the category: which agent drafts is triage's\n // to decide, once it has run — `draftRebinder`'s own doc. The up-front\n // `agent` above stays the base binding both forced paths keep.\n const rebindDraft = input.agentId || forcedCategory ? undefined : draftRebinder(ctx.api, categories, config);\n\n return runGraphDryRun({ base, api: ctx.api, resume, ...(rebindDraft ? { rebindDraft } : {}) });\n}\n","/**\n * `test-agents` (§3.5) — `uiInvoke`, multi-ticket bench (legacy\n * `POST /agents/test`): runs `graph-dry-run`'s SAME zero-write replay\n * (`runGraphDryRun`, `./graph-dry-run-core.ts`) over either a Gorgias view\n * or an explicit list of ticket ids, so an operator can see what an agent\n * WOULD produce across a batch before turning it loose — nothing tagged,\n * nothing sent, nothing recorded, per §0's dry-run arbitrage.\n *\n * No `GraphDryRunOverrides` here (unlike `graph-dry-run`, which exists\n * precisely to explore an OFF branch on one ticket): a bench is only\n * useful if it reports what the agent does with its REAL configuration,\n * across many tickets — overriding it would just report the same forced\n * branch N times.\n *\n * `category.autoReplyEnabled` is the ONE exception to that, and it is\n * reported as such (T23 post-review C3): the per-ticket category is only\n * known once TRIAGE runs, which happens INSIDE the same full-graph replay\n * this function triggers — there is no category to read a real flag off of\n * before the run starts. `graph-dry-run` can justify forcing it to `true`\n * unconditionally (reaching `act` is that function's whole purpose); a bench\n * with no override cannot make the same claim, so `TestAgentsResult` carries\n * `autoReplyForced: true` alongside every run's outcome — an operator\n * reading \"would have sent\" across a batch sees, in the same response, that\n * every category's own auto-reply setting was bypassed to get there.\n *\n * Sequential on purpose: a batch runs the LLM/Gorgias reads for real\n * (§0/§3.5), and a small, predictable concurrency of 1 is the safer default\n * for a bench an operator triggers by hand — this can grow a concurrency\n * knob later without changing the contract.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): up to `MAX_LIMIT` full graph\n * replays per invocation is real LLM spend against the app's shared quota,\n * not a read — `VIEWER` is the wrong floor for a tool that can burn budget\n * this fast, re-invocable at will.\n *\n * `DRY_RUN_DEADLINE_MS` bounds the WHOLE bench, not each ticket (T23\n * post-review C2, ported from the legacy's single-ticket deadline): past\n * it, the loop stops starting new replays and returns whatever finished —\n * partial results the operator can read, instead of the `uiInvoke` request\n * dying at the platform's own HTTP timeout with nothing returned and every\n * completion so far already billed.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\nimport { TEST_AGENTS_INPUT_AGENT_ID_UID, TEST_AGENTS_INPUT_LIMIT_UID, TEST_AGENTS_INPUT_TICKET_IDS_UID, TEST_AGENTS_INPUT_VIEW_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, draftRebinder, listCategories, resolveDraftAgent, toAgent, toCategoryReferential } from './records';\n\nconst DEFAULT_LIMIT = 20;\nconst MAX_LIMIT = 100;\n\nexport interface TestAgentsInput {\n viewId?: string;\n ticketIds?: string[];\n /** Forces the writing agent; falls back to the default one. */\n agentId?: string;\n limit?: number;\n}\n\nexport interface TestAgentsResult {\n results: GraphDryRunResult[];\n /**\n * `true` when every result above ran with `category.autoReplyEnabled`\n * forced on, regardless of that ticket's own category setting (T23\n * post-review C3) — see this module's own header doc for why a bench\n * cannot know the real per-category flag ahead of triage.\n */\n autoReplyForced: true;\n}\n\nexport function buildTestAgentsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'test-agents'),\n name: 'test-agents',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: TEST_AGENTS_INPUT_VIEW_ID_UID, name: 'viewId', type: FieldType.TEXT, label: 'View id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_TICKET_IDS_UID, name: 'ticketIds', type: FieldType.JSON, label: 'Ticket ids', description: 'string[]', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_LIMIT_UID, name: 'limit', type: FieldType.NUMBER, label: 'Limit', isNullable: true },\n ],\n };\n}\n\nexport function createTestAgentsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => testAgentsHandler(ctx as SupportKitHandlerContext, config, input as unknown as TestAgentsInput);\n}\n\nexport async function testAgentsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: TestAgentsInput,\n): Promise<TestAgentsResult> {\n const explicitIds = (input?.ticketIds ?? []).map((id) => id.trim()).filter(Boolean);\n const viewId = input?.viewId?.trim();\n if (!viewId && explicitIds.length === 0) {\n throw new ctx.NonRetriableError('Either viewId or ticketIds is required');\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);\n const categories = await listCategories(ctx.api);\n const agent = input.agentId ? toAgent(await ctx.api.get('agent', input.agentId)) : await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n // Unless the operator benched ONE agent on purpose, every ticket drafts\n // with the agent its own category names — same rebinding as `graph-dry-run`\n // and as production, or the bench measures the default agent on tickets\n // production would never have given it (`draftRebinder`).\n const rebindDraft = input.agentId ? undefined : draftRebinder(ctx.api, categories, config);\n\n const realPorts = buildTicketPorts(ctx);\n const refs: ConversationRef[] = explicitIds.length\n ? explicitIds.slice(0, limit).map((id) => ({ id, channel: 'gorgias' as const }))\n : await realPorts.conversation.listPending({ viewOrTag: viewId! }, limit);\n\n // One deadline for the WHOLE bench (T23 post-review C2), not one per\n // ticket: past it, the loop below stops starting new replays rather than\n // let the platform's own HTTP timeout kill the request with nothing\n // returned. Every ticket's `Budget` shares this same signal, so an\n // in-flight LLM call is aborted at the same wall-clock moment the loop\n // itself gives up.\n const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);\n\n const results: GraphDryRunResult[] = [];\n for (const ref of refs) {\n if (deadline.aborted) break; // partial results: the bench is out of time, not any one ticket\n const budget = createBudget({ signal: deadline, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n results.push(await runGraphDryRun({ base, api: ctx.api, ...(rebindDraft ? { rebindDraft } : {}) }));\n }\n\n return { results, autoReplyForced: true };\n}\n","/**\n * `validateReferences` — save-time validation for a prompt-composition tag\n * (`@@@langfusePrompt:name=…|label=…@@@` or `|version=…@@@`), ported from\n * legacy `services/promptReferences.ts`. Deferred by T19 (its own module doc\n * on `prompts/references.ts`: \"an admin save-time validator with no runtime-\n * resolution caller in this kit … out of scope for T19\") and picked up here\n * because `suggest-prompt` (§3.5) is the kit's first WRITE path for a\n * prompt's content — nothing gated writes before this.\n *\n * Five error classes, all five kept:\n * 1. Malformed tag (`findMalformedTags`) — a typo'd `label`/`version`\n * keyword, or a missing closing `@@@`.\n * 2. Self-reference — a prompt referencing its own name.\n * 3. Unresolvable target — the referenced prompt/version/label could not\n * be fetched (missing, or Langfuse unreachable; both read the same\n * here, same as legacy).\n * 4. A cycle back to the prompt being saved.\n * 5. A chain longer than the runtime resolver ever actually walks\n * (T23 post-review B1, below).\n *\n * Class 1 is now STRICTLY MORE IMPORTANT than in the legacy: Langfuse used\n * to store a typo'd tag as literal text and its own resolver caught DEEPER\n * cycles on the well-formed ones — but `createPromptResolver`\n * (`prompts/resolver.ts`) now resolves composition itself, reading raw\n * content via `resolve:false` and never asking Langfuse to flatten\n * anything. A typo'd tag saved here reaches the LLM completely verbatim,\n * with NOTHING server-side left to catch it — this validator is the sole\n * arbiter, at save time, of whether that string means anything at all.\n *\n * Class 4 is deepened past legacy's one hop for the identical reason:\n * legacy's own comment justified checking only one level with \"deeper\n * cycles are rejected by Langfuse's own resolver at fetch time\" — that\n * resolver is never consulted anymore (composition is entirely the kit's\n * own `resolveComposition`, `prompts/resolver.ts`), so a 2+-hop cycle saved\n * here would previously have gone uncaught at write time. `resolver.ts`'s\n * OWN runtime composition pass already survives a cycle at read time\n * (`visited`/`MAX_COMPOSITION_DEPTH`, degrading it to empty text) — this\n * validator closes the save-time half of the same gap: catching the\n * mistake when it is made, not silently degrading it forever after.\n *\n * Class 5 (T23 post-review B1) closes a DIFFERENT gap the cycle walk above\n * never covered: a purely LINEAR chain, A→B→C→D→E→F, has no cycle at all,\n * yet `resolver.ts`'s own `MAX_COMPOSITION_DEPTH` (imported below, not\n * restated — the previous revision claimed to mirror it while actually\n * enforcing an unrelated `MAX_CYCLE_DEPTH` that only ever bounded the CYCLE\n * walk's recursion) silently strips whatever sits past that depth at read\n * time. Without this check, such a chain \"saves fine\" and an operator only\n * discovers the loss when the composed prompt quietly stops including its\n * last segment.\n *\n * `MAX_CYCLE_DEPTH` remains its own, separate, larger safety valve: it\n * exists only so an adversarial/cyclic graph the cycle walk is exploring\n * cannot recurse forever, and has nothing to say about how long a valid\n * chain may be — that is `MAX_COMPOSITION_DEPTH`'s job, enforced by class 5.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { MAX_COMPOSITION_DEPTH } from '../prompts/resolver';\nimport { parseReferences, REFERENCE_TAG_SOURCE, type PromptReference } from '../prompts/references';\n\nconst LITERAL_PREFIX = '@@@langfusePrompt:';\nconst MALFORMED_SNIPPET_MAX_LEN = 60;\n/**\n * Bounds the CYCLE WALK's own recursion on adversarial/cyclic content — kept\n * deliberately larger than `MAX_COMPOSITION_DEPTH` (a valid, acyclic chain\n * that merely runs past the runtime cap is class 5's job, reported\n * separately and more usefully than \"cycle walk gave up\").\n */\nconst MAX_CYCLE_DEPTH = 10;\n\n/** Same grammar `parseReferences` matches (`prompts/references.ts`'s exported source) — a single definition, so the two can never drift apart (T23 post-review B3). */\nconst REF_RE = new RegExp(REFERENCE_TAG_SOURCE, 'g');\n\n/** A short, human-readable excerpt of the malformed tag, for the error message. */\nfunction snippetAt(content: string, index: number): string {\n const rest = content.slice(index);\n const closingIdx = rest.indexOf('@@@', LITERAL_PREFIX.length);\n const snippet = closingIdx === -1 ? rest.slice(0, MALFORMED_SNIPPET_MAX_LEN) : rest.slice(0, closingIdx + 3);\n return snippet.length > MALFORMED_SNIPPET_MAX_LEN ? `${snippet.slice(0, MALFORMED_SNIPPET_MAX_LEN)}…` : snippet;\n}\n\n/** Every literal `@@@langfusePrompt:` occurrence NOT part of a well-formed tag `parseReferences` would have matched. */\nfunction findMalformedTags(content: string): string[] {\n if (!content.includes(LITERAL_PREFIX)) return [];\n const validStarts = new Set([...content.matchAll(REF_RE)].map((m) => m.index ?? -1));\n const malformed: string[] = [];\n for (const m of content.matchAll(new RegExp(LITERAL_PREFIX, 'g'))) {\n const index = m.index ?? -1;\n if (!validStarts.has(index)) malformed.push(snippetAt(content, index));\n }\n return malformed;\n}\n\n/** Where a reference points, for an error message (\"version 3\" / label \"production\"). */\nfunction locatorFor(ref: PromptReference): string {\n return ref.version !== undefined ? `version ${ref.version}` : `label \"${ref.label}\"`;\n}\n\ninterface FetchedTarget {\n content: string;\n}\n\n/**\n * A reference target that failed to fetch, distinguishing WHY (M1, T25\n * review): `forbidden` (a 403 — the target exists but is outside this app's\n * `role.prompts` allowlist) is a misconfiguration to fix in the manifest, not\n * a typo'd or genuinely absent prompt name — reporting the two identically\n * sends an operator chasing a \"not found\" prompt that Langfuse would show\n * them exists.\n */\ninterface FetchFailure {\n forbidden: boolean;\n}\n\ntype FetchResult = FetchedTarget | FetchFailure;\n\nfunction isFetchFailure(result: FetchResult): result is FetchFailure {\n return !('content' in result);\n}\n\n/** Stable dedupe key for a reference target — a version-pinned ref and a label-pinned ref never collide, mirroring `resolver.ts`'s own `memoryKey`. */\nfunction targetKey(ref: PromptReference): string {\n return ref.version !== undefined ? `${ref.name}::v${ref.version}` : `${ref.name}::${ref.label}`;\n}\n\n/** `ctx.api.prompts.get(name, {label|version, resolve:false})` — a `FetchFailure` on any error, `forbidden` set only for a 403 (`AppApiError`). */\nasync function fetchTarget(api: SupportKitApi, ref: PromptReference): Promise<FetchResult> {\n try {\n const detail = await api.prompts.get(ref.name, {\n resolve: false,\n ...(ref.version !== undefined ? { version: ref.version } : { label: ref.label }),\n });\n return { content: detail.content };\n } catch (err) {\n return { forbidden: err instanceof AppApiError && err.status === 403 };\n }\n}\n\n/**\n * `fetchTarget`, deduped against `cache` (T23 post-review B2). The legacy\n * gap this closes: the cycle walk used to re-fetch a target the main loop\n * had just fetched, then re-fetch it again on every alternation of an\n * unrelated cycle it stumbled into — this is the one seam both the main\n * loop and the cycle/depth walks below share, so a given (name, version|label)\n * is ever fetched at most once per `validateReferences` call.\n */\nasync function fetchTargetCached(api: SupportKitApi, ref: PromptReference, cache: Map<string, FetchResult>): Promise<FetchResult> {\n const key = targetKey(ref);\n const cached = cache.get(key);\n if (cached) return cached;\n const target = await fetchTarget(api, ref);\n cache.set(key, target);\n return target;\n}\n\n/**\n * Walks the reference chain rooted at `content` looking for a hop back to\n * `origin` (the prompt being validated). `visited` (T23 post-review B2) is\n * THIS walk's own dedupe: once a target has been explored and did not lead\n * back to `origin`, revisiting it can only repeat the same negative answer —\n * skipping it turns \"re-walked alternately to `MAX_CYCLE_DEPTH`\" into \"walked\n * once\". `depth` still bounds the walk independently, for a graph `visited`\n * has not yet caught up with.\n */\nasync function hasPathToOrigin(\n api: SupportKitApi,\n content: string,\n origin: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: Set<string>,\n): Promise<boolean> {\n if (depth > MAX_CYCLE_DEPTH) return false;\n\n for (const ref of parseReferences(content)) {\n if (ref.name === origin) return true;\n\n const key = targetKey(ref);\n if (visited.has(key)) continue;\n visited.add(key);\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a cycle\n\n if (await hasPathToOrigin(api, target.content, origin, depth + 1, cache, visited)) return true;\n }\n return false;\n}\n\n/**\n * Whether `content`'s reference chain runs past `MAX_COMPOSITION_DEPTH` —\n * the exact point `resolver.ts`'s own `composeReferences` stops following a\n * chain and silently strips whatever is left (T23 post-review B1). Mirrors\n * that function's `depth`/cap arithmetic precisely: `content` itself is\n * depth 0 (the prompt being saved, not yet fetched), each reference target\n * is one level deeper, and a target reached at `depth >= MAX_COMPOSITION_DEPTH`\n * is exactly the one the resolver would compose without following further —\n * anything nested inside IT is what gets silently lost at runtime.\n *\n * `visited` mirrors `resolver.ts`'s own cycle guard (keyed by prompt NAME,\n * same as `resolveOneReference`'s `visited.has(ref.name)`): a name already\n * on the path is a cycle, which the runtime resolver degrades to empty text\n * at THAT point regardless of depth, and which class 4 above already\n * reports on its own terms — without this, a short unrelated cycle inside\n * an otherwise-fine chain would recurse forever instead of matching what\n * the resolver actually does with it.\n */\nasync function exceedsCompositionDepth(\n api: SupportKitApi,\n content: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: ReadonlySet<string>,\n): Promise<boolean> {\n const refs = parseReferences(content);\n if (refs.length === 0) return false;\n if (depth >= MAX_COMPOSITION_DEPTH) return true;\n\n for (const ref of refs) {\n if (visited.has(ref.name)) continue; // a cycle — reported separately by class 4, not a depth issue\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a depth issue\n if (await exceedsCompositionDepth(api, target.content, depth + 1, cache, new Set([...visited, ref.name]))) return true;\n }\n return false;\n}\n\n/**\n * Validate every reference tag in `content` (the prompt named `selfName`\n * about to be saved). Returns human-readable error strings; an empty array\n * means the content is valid.\n */\nexport async function validateReferences(api: SupportKitApi, content: string, selfName: string): Promise<string[]> {\n const errors: string[] = [];\n const cache = new Map<string, FetchResult>();\n\n for (const snippet of findMalformedTags(content)) {\n errors.push(`Malformed reference tag near \"${snippet}\": it will be saved as literal text instead of being resolved.`);\n }\n\n for (const ref of parseReferences(content)) {\n if (ref.name === selfName) {\n errors.push(`Reference \"${ref.raw}\" points to this same prompt (\"${selfName}\") — a prompt cannot reference itself.`);\n continue;\n }\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) {\n errors.push(\n target.forbidden\n ? `Reference \"${ref.raw}\" points to prompt \"${ref.name}\", which exists but is outside this app's prompts allowlist (role.prompts) — it cannot be composed here even though it can be read elsewhere.`\n : `Reference \"${ref.raw}\" could not be resolved: prompt \"${ref.name}\" with ${locatorFor(ref)} was not found, or the prompt store could not be reached to verify it.`,\n );\n continue;\n }\n\n if (await hasPathToOrigin(api, target.content, selfName, 1, cache, new Set([targetKey(ref)]))) {\n errors.push(`Reference \"${ref.raw}\" creates a cycle: prompt \"${ref.name}\" (transitively) references this prompt (\"${selfName}\").`);\n }\n }\n\n if (errors.length === 0 && (await exceedsCompositionDepth(api, content, 0, cache, new Set([selfName])))) {\n errors.push(\n `Reference chain exceeds the runtime composition cap (${MAX_COMPOSITION_DEPTH} levels): the segment past that depth would be silently stripped when this prompt is resolved.`,\n );\n }\n\n return errors;\n}\n","/**\n * `suggest-prompt` (§3.5) — `uiInvoke`, LLM prompt suggestion from an\n * agent's `response-comparison` corrections, equivalent to legacy\n * `POST /models/:id/prompt-versions/suggest`. Writes with\n * `ctx.api.prompts.createVersion(...)` (S3), tag `ai_suggested`, gated by\n * `validateReferences` (`./validate-references.ts`, T19's deferred\n * validator) BEFORE the write — the first prompt-content write path in the\n * kit, and the first place a malformed/self-referencing/cyclic reference tag\n * could otherwise reach a live prompt.\n *\n * WHAT THIS CANNOT RECORD (T19): `CreatePromptVersionInput` is\n * `{content, labels?, tags?}` — no `config`, no `commitMessage`. Two losses\n * versus the legacy, both accepted here rather than invented on the\n * platform surface:\n * - No `commitMessage`: legacy wrote\n * `\"AI-suggested based on N comparisons from vX\"` as the version's own\n * changelog entry. That narrative has nowhere to go — the new version\n * carries no explanation of why it exists beyond the `ai_suggested` tag.\n * - No `config`: legacy explicitly inherited the ACTIVE version's model\n * config (\"a suggestion never silently resets a tuned temperature back\n * to the default\"). A version created here carries none — an operator\n * who tuned a model/temperature on the active version loses that\n * tuning the moment they accept a suggestion, silently, until S3 grows\n * a `config` field.\n *\n * `minRole: 'EDITOR'`: this writes a new prompt version (Langfuse), even\n * though it never PROMOTES it to `production` — creating one is still an\n * editing action, not a read.\n */\nimport { AppApiError, FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SUGGEST_PROMPT_INPUT_AGENT_ID_UID, SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID } from './ids';\nimport { resolvePromptName } from '../prompts/slots';\nimport { toAgent } from './records';\nimport { validateReferences } from './validate-references';\n\nconst DEFAULT_MAX_COMPARISONS = 50;\nconst MIN_COMPARISONS_REQUIRED = 3;\n\n/**\n * Level-3 fallback for the `suggest` slot (§3.7 point 3: \"fallback in-code\n * du kit, surchargé par `config.defaults.prompts`\") — used only when the\n * slot has no `production` version yet in the prompt store.\n */\nconst DEFAULT_SUGGEST_META_PROMPT = [\n 'Tu es un expert en rédaction de prompts système pour des assistants IA de support client.',\n \"Analyse les différences entre les réponses de l'IA et celles des agents humains dans les exemples fournis.\",\n 'Identifie les patterns récurrents (ton, structure, longueur, formulations) puis réécris le prompt système actuel pour en corriger les écarts.',\n 'Retourne UNIQUEMENT le texte du prompt système amélioré, sans explication ni mise en forme markdown.',\n \"Toute balise de référence de la forme @@@langfusePrompt:...@@@ présente dans le prompt actuel doit être reproduite telle quelle, sans modification.\",\n].join('\\n');\n\nexport interface SuggestPromptInput {\n agentId: string;\n maxComparisons?: number;\n}\n\nexport interface SuggestPromptResult {\n promptName: string;\n version: number;\n comparisonCount: number;\n}\n\nexport function buildSuggestPromptFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'suggest-prompt'),\n name: 'suggest-prompt',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: SUGGEST_PROMPT_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: false },\n { universalIdentifier: SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID, name: 'maxComparisons', type: FieldType.NUMBER, label: 'Max comparisons', isNullable: true },\n ],\n };\n}\n\nexport function createSuggestPromptHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => suggestPromptHandler(ctx as SupportKitHandlerContext, config, input as unknown as SuggestPromptInput);\n}\n\nfunction comparisonBlock(index: number, generatedText: string | null, sentText: string): string {\n const ai = generatedText?.trim() || '(aucune réponse générée)';\n return `### Exemple ${index + 1}\\nIA a généré :\\n${ai}\\n\\nAgent a réellement envoyé :\\n${sentText.trim()}`;\n}\n\nexport async function suggestPromptHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: SuggestPromptInput,\n): Promise<SuggestPromptResult> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const agent = toAgent(await ctx.api.get('agent', agentId));\n const promptName = agent.promptName;\n if (!promptName) throw new ctx.NonRetriableError(`Agent \"${agentId}\" has no promptName configured`);\n\n // Raw (unresolved) current content — the meta-prompt below must see any\n // `@@@langfusePrompt:...@@@` composition tag verbatim, so it rewrites the\n // template rather than an expansion of it (mirrors legacy's own\n // `getRaw` read, §3.7's \"aplatir\" concern).\n let currentContent: string;\n let promptVersion: number | null;\n try {\n const detail = await ctx.api.prompts.get(promptName, { label: 'production', resolve: false });\n currentContent = detail.content;\n promptVersion = detail.version;\n } catch (err) {\n // H4 (T25 review): a 403 means this agent's own promptName is outside\n // the app's role.prompts allowlist — a manifest/data misconfiguration,\n // not the legitimate \"no production version yet\" case the fallback to\n // systemPromptSnapshot exists for. Swallowing it here would rewrite a\n // STALE snapshot and hand the operator no error explaining why.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n `Agent \"${agentId}\"'s prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts) — suggest-prompt cannot read it. ${err.message}`,\n );\n }\n currentContent = agent.systemPromptSnapshot ?? '';\n promptVersion = agent.promptVersion;\n }\n\n // Scoped to the ACTIVE prompt version, not just the agent (legacy\n // behaviour, ported): a correction captured against v7 has nothing to say\n // about v8 — feeding it back in after the operator already accepted a\n // suggestion re-litigates a fix that was already made and drifts the\n // prompt further every round.\n const limit = Math.min(input?.maxComparisons ?? DEFAULT_MAX_COMPARISONS, DEFAULT_MAX_COMPARISONS);\n const page = await ctx.api.list('response-comparison', { filter: { agentId, promptName, promptVersion }, limit });\n const comparisons = page.items.map((r) => r.data as { generatedText: string | null; sentText: string });\n if (comparisons.length < MIN_COMPARISONS_REQUIRED) {\n throw new ctx.NonRetriableError(\n `Not enough comparison data (${comparisons.length} record(s), minimum ${MIN_COMPARISONS_REQUIRED} required)`,\n );\n }\n\n const metaPromptName = resolvePromptName('suggest', config);\n // §3.7 point 3 — the kit's own built-in text is the LAST resort;\n // `config.defaults.prompts.suggest` (T25) overrides it first.\n const configuredFallback = config.defaults?.prompts?.suggest ?? DEFAULT_SUGGEST_META_PROMPT;\n let metaPromptContent = configuredFallback;\n try {\n metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: 'production' })).content || configuredFallback;\n } catch {\n // Level-3 fallback (§3.7) — the `suggest` slot has no `production`\n // version yet on this tenant.\n }\n\n const userMessage = [\n '--- PROMPT SYSTÈME ACTUEL ---',\n currentContent,\n '--- FIN DU PROMPT SYSTÈME ---',\n '',\n `Voici ${comparisons.length} exemples comparant ce que l'IA a généré avec ce que l'agent a réellement envoyé :`,\n '',\n comparisons.map((c, i) => comparisonBlock(i, c.generatedText, c.sentText)).join('\\n\\n---\\n\\n'),\n ].join('\\n');\n\n const result = await ctx.api.llm.complete({\n messages: [\n { role: 'system', content: metaPromptContent },\n { role: 'user', content: userMessage },\n ],\n options: { model: agent.modelId },\n promptRef: { name: metaPromptName, label: 'production', resolve: false },\n });\n\n const suggestedContent = result.text.trim();\n if (!suggestedContent) throw new ctx.NonRetriableError('The model returned an empty suggestion');\n\n const referenceErrors = await validateReferences(ctx.api, suggestedContent, promptName);\n if (referenceErrors.length > 0) {\n // The rejected content is included, not discarded (T23 post-review B4):\n // without it, an operator can neither see what the model produced nor\n // repair it by hand, and a retry re-spends the completion that already\n // paid for this exact (rejected) text.\n throw new ctx.NonRetriableError(\n [\n `Suggested content has invalid reference tags: ${referenceErrors.join(' ')}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n\n let version: number;\n try {\n ({ version } = await ctx.api.prompts.createVersion(promptName, {\n content: suggestedContent,\n tags: ['ai_suggested'],\n }));\n } catch (err) {\n // H4 (T25 review): left unguarded, a 403 here (promptName outside\n // role.prompts) reached the caller as an opaque platform exception —\n // AFTER the llm.complete call above already paid for suggestedContent.\n // Same courtesy as the reference-validation rejection just above: name\n // the cause and include the content the operator already paid for,\n // rather than discarding it behind a generic failure.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n [\n `Cannot save this suggestion: prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts). ${err.message}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n throw err;\n }\n\n return { promptName, version, comparisonCount: comparisons.length };\n}\n","/**\n * `list-gorgias-views` (§3.5) — `uiInvoke`, view autocomplete (S1\n * `listViews`) for the Settings page's `sourceViewId` field, plus §4's\n * cross-app view-claim warning: \"avertit si la vue configurée est déjà\n * revendiquée par une autre app support (lecture croisée du record\n * `pipeline-state` exposé `exposedToApps:['*']`, en lecture seule — seul\n * point de contact inter-apps, purement informatif)\".\n *\n * DELIBERATE EXCEPTION to \"every handler reads settings through\n * `validateSettings` before use\": this function is the checklist's OWN\n * step 2 tool for CHOOSING `sourceViewId` in the first place (§4's \"créer\n * une nouvelle audience\" checklist) — gating it on `validateSettings`,\n * which itself requires `sourceViewId` to be non-empty, would make the\n * autocomplete unusable on the exact first-run screen it exists for. Every\n * OTHER field `validateSettings` checks (`nodes.triage`, `senderEmail`) is\n * equally irrelevant to listing Gorgias views.\n *\n * ASSUMPTION (stated, not decided silently): the kit has no platform\n * capability to enumerate OTHER installed apps — `SupportKitApi` is scoped\n * to this app's own token, and nothing in §2's S1-S6 socle exposes an \"apps\n * of this kind\" listing. `input.checkAppSlugs` is therefore CALLER-SUPPLIED:\n * the Settings page (out of this task's scope) already has its own,\n * unrelated way to see the instance's installed apps (an admin-facing\n * listing this app's own token cannot and should not reach) and passes the\n * OTHER support-kit apps' slugs in. A slug that turns out not to expose\n * `pipeline-state` to this app (not installed, not a support-kit app, or a\n * true `403`) is reported in `uncheckedAppSlugs` rather than failing the\n * whole call — the warning is \"purement informatif\" (§4), never a gate.\n *\n * P1 (« Connexion Gorgias »): this function ALSO reports the instance's\n * Gorgias connections. The Settings page used to expose a free-text\n * `gorgiasConnectionId` that nothing read — every call in the kit goes\n * through `ctx.api.integrations.run('gorgias', …)` WITHOUT a\n * `connectionId`, so the platform resolves the default connection and the\n * field was decorative. The kit now states which connection answers instead\n * of pretending to choose it, and warns on the one configuration that\n * actually breaks: several connections with no default, which the platform\n * rejects with `409 AMBIGUOUS_CONNECTION`\n * (`app-integrations.controller.ts`). It lives here rather than in a new\n * `uiInvoke` function because the Settings page already calls this one for\n * the very same section, and a new function would cost the consuming app a\n * new `universalIdentifier` (`identifierFor` throws on a missing one) for\n * no added capability.\n *\n * `minRole: 'VIEWER'`: a pure read, informational only.\n *\n * T25 DECISION (spec §3.2, \"T25 or the Settings page must supply\n * `checkAppSlugs`\"): `SupportPipelineConfig` deliberately does NOT grow a\n * field for this. A config field would be a STATIC list, fixed at manifest\n * build/publish time — exactly wrong for \"which other support-kit apps\n * exist\", a fact that changes every time an audience is added or removed\n * without republishing this one. The Settings page (T26) is the only\n * correct owner: it already needs an admin-facing \"installed apps\" listing\n * this function's own scoped token cannot and should not reach (see the\n * ASSUMPTION above), and it is the one place that can pass a FRESH\n * `checkAppSlugs` on every invocation. Nothing changes here.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID } from './ids';\n\nexport interface ListGorgiasViewsInput {\n /** Other installed support-kit apps' slugs to check `sourceViewId` overlap against (§4) — see this module's own doc for why this is caller-supplied. */\n checkAppSlugs?: string[];\n}\n\nexport interface GorgiasViewOption {\n id: string;\n name: string;\n /** Other apps whose `pipeline-state.sourceViewId` already names this view. Empty when clear (or unverifiable). */\n claimedByAppSlugs: string[];\n}\n\nexport interface GorgiasConnection {\n id: string;\n label: string;\n isDefault: boolean;\n}\n\nexport interface ListGorgiasViewsResult {\n views: GorgiasViewOption[];\n /** `checkAppSlugs` entries that could not be read (not installed, not exposing `pipeline-state` to this app, or unreachable) — informational, never a failure. */\n uncheckedAppSlugs: string[];\n /**\n * The instance's Gorgias connections, credentials stripped by the platform\n * (`GET /data/integrations/gorgias/connections`). `null` means the listing\n * itself FAILED — distinct from `[]`, which means the instance genuinely\n * has no Gorgias connection and the pipeline cannot run at all. The\n * Settings page renders the two differently, so collapsing them would turn\n * a real misconfiguration into an unexplained blank.\n */\n connections: GorgiasConnection[] | null;\n}\n\nexport function buildListGorgiasViewsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'list-gorgias-views'),\n name: 'list-gorgias-views',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID,\n name: 'checkAppSlugs',\n type: FieldType.JSON,\n label: 'Check app slugs',\n description: 'string[] — other support-kit app slugs to check for a sourceViewId overlap.',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createListGorgiasViewsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => listGorgiasViewsHandler(ctx as SupportKitHandlerContext, config, (input as ListGorgiasViewsInput) ?? {});\n}\n\nconst PIPELINE_STATE_SINGLETON_KEY = 'default';\n\ntype ClaimedViewRead = { ok: true; claimedViewId: string | null } | { ok: false };\n\n/**\n * The view `appSlug` currently claims, or `null` when it claims none (a\n * SUCCESSFUL read of an empty/unset singleton — a fresh app that has never\n * triaged is \"checked, not claiming anything\", not \"unverifiable\"). `ok:\n * false` is reserved for an actual read FAILURE (not installed, not\n * exposing `pipeline-state` to this app, or unreachable) — the two must\n * stay distinct, or a legitimately-clear app would be reported as\n * unverifiable instead of clear.\n */\nasync function readClaimedView(ctx: SupportKitHandlerContext, appSlug: string): Promise<ClaimedViewRead> {\n try {\n const page = await ctx.api.crossApp.list(appSlug, 'pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n const sourceViewId = page.items[0]?.data.sourceViewId;\n return { ok: true, claimedViewId: typeof sourceViewId === 'string' && sourceViewId.length > 0 ? sourceViewId : null };\n } catch {\n return { ok: false };\n }\n}\n\nexport async function listGorgiasViewsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: ListGorgiasViewsInput,\n): Promise<ListGorgiasViewsResult> {\n const rawViews = (await ctx.api.integrations.run('gorgias', 'listViews', {})) as { views: Array<{ id: string | number; name: string }> };\n const views = rawViews.views.map((v) => ({ id: String(v.id), name: v.name }));\n\n // Reported, never thrown: which connection answers is a property of the\n // instance the operator cannot set from here (P1), so a failure to read it\n // must not take the view autocomplete — this function's actual job — down\n // with it.\n let connections: GorgiasConnection[] | null;\n try {\n connections = await ctx.api.integrations.list('gorgias');\n } catch {\n connections = null;\n }\n\n const candidateSlugs = (input.checkAppSlugs ?? []).filter((slug) => slug && slug !== config.slug);\n\n const claimedByViewId = new Map<string, string[]>();\n const uncheckedAppSlugs: string[] = [];\n for (const slug of candidateSlugs) {\n const read = await readClaimedView(ctx, slug);\n if (!read.ok) {\n uncheckedAppSlugs.push(slug);\n continue;\n }\n if (read.claimedViewId === null) continue; // checked, and it claims nothing\n const claimants = claimedByViewId.get(read.claimedViewId) ?? [];\n claimants.push(slug);\n claimedByViewId.set(read.claimedViewId, claimants);\n }\n\n return {\n views: views.map((v) => ({ id: v.id, name: v.name, claimedByAppSlugs: claimedByViewId.get(v.id) ?? [] })),\n uncheckedAppSlugs,\n connections,\n };\n}\n","/**\n * `create-agent` (§3.4) — `uiInvoke`, creates a new drafting agent with a\n * server-assigned `promptName` of `agent/<recordId>`, unless the caller\n * names an existing Langfuse prompt (`input.promptName`, written verbatim).\n *\n * `agent.promptName` is `isNullable: false` with no default\n * (`records/agent.ts`) — the record's own id does not exist until AFTER the\n * create, so a plain `POST records/agent` from the browser has no legal\n * value to send for it. Before this function existed, AgentsPage's \"Nouvel\n * agent\" form posted with no `promptName` field at all, the write was\n * rejected, `save()` had no `.catch`, and the modal just sat there with no\n * feedback (T26 review, BLOCKER 3).\n *\n * The fix is the two-step create-then-patch the record id makes necessary,\n * done in ONE server-side round trip: the browser only ever sees the final,\n * fully-formed agent — never the placeholder `promptName` the first write is\n * forced to carry for the instant before the id is known.\n *\n * `minRole: 'EDITOR'`: creating an agent is an editing action, matching\n * every other agent-mutating control on AgentsPage.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { DEFAULT_LLM_PROVIDER } from '../records/agent';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n CREATE_AGENT_INPUT_MODEL_ID_UID,\n CREATE_AGENT_INPUT_NAME_UID,\n CREATE_AGENT_INPUT_PROMPT_LABEL_UID,\n CREATE_AGENT_INPUT_PROMPT_NAME_UID,\n CREATE_AGENT_INPUT_PROVIDER_UID,\n CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n} from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\n/**\n * Placeholder `promptName` for the single instant between the create and the\n * patch that overwrites it with `agent/<id>` — this handler is the only\n * thing that ever reads a record carrying it, so its exact spelling has no\n * external contract.\n */\nconst PENDING_PROMPT_NAME = 'agent/pending';\n\nexport interface CreateAgentInput {\n name: string;\n modelId: string;\n provider?: string;\n /**\n * The agent's initial prompt text. On the derived-`agent/<id>` path it is\n * seeded into Langfuse as v1 and promoted to `production` (best-effort —\n * see `seedInitialVersion`); on every path it is also stored on the record\n * as the level-3 fallback, which later version writes keep refreshed.\n */\n systemPromptSnapshot?: string;\n /**\n * Langfuse prompt this agent uses, written VERBATIM (trim only — no case,\n * accent or dash normalisation: `agent/Prompt 7 — Client Satisfait & Avis`\n * must land byte for byte). Absent or empty → the legacy server-derived\n * `agent/<recordId>`.\n */\n promptName?: string;\n /**\n * Langfuse label the agent follows. Absent or empty → stays null, the\n * convention `draftPromptRefFor` reads as \"follow `production`\" — never\n * frozen to the literal string at write time.\n */\n promptLabel?: string;\n}\n\nexport function buildCreateAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-agent'),\n name: 'create-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: CREATE_AGENT_INPUT_NAME_UID, name: 'name', type: FieldType.TEXT, label: 'Name', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_PROVIDER_UID, name: 'provider', type: FieldType.TEXT, label: 'Provider', isNullable: true },\n {\n universalIdentifier: CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n name: 'systemPromptSnapshot',\n type: FieldType.TEXT,\n label: 'System prompt snapshot',\n isNullable: true,\n },\n {\n universalIdentifier: CREATE_AGENT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: CREATE_AGENT_INPUT_PROMPT_LABEL_UID,\n name: 'promptLabel',\n type: FieldType.TEXT,\n label: 'Prompt label',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createCreateAgentHandler(): AppHandler {\n return (ctx, input) =>\n createAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as CreateAgentInput) ?? {});\n}\n\nexport async function createAgentHandler(\n ctx: SupportKitHandlerContext,\n input: CreateAgentInput,\n): Promise<AgentRecord> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n const modelId = input?.modelId?.trim();\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n\n const base = {\n name,\n modelId,\n provider: input.provider?.trim() || DEFAULT_LLM_PROVIDER,\n status: 'available',\n ...(input.systemPromptSnapshot?.trim() ? { systemPromptSnapshot: input.systemPromptSnapshot.trim() } : {}),\n ...(input.promptLabel?.trim() ? { promptLabel: input.promptLabel.trim() } : {}),\n };\n\n // An explicit promptName is written verbatim in ONE create: no placeholder,\n // and no id-derived overwrite — deriving would silently detach the agent\n // from the pre-existing Langfuse prompt the caller just named.\n const promptName = input.promptName?.trim();\n if (promptName) {\n return toAgent(await ctx.api.create('agent', { ...base, promptName }));\n }\n\n const created = await ctx.api.create('agent', { ...base, promptName: PENDING_PROMPT_NAME });\n const derivedName = `agent/${created.id}`;\n const withPromptName = await ctx.api.update('agent', created.id, { promptName: derivedName });\n await seedInitialVersion(ctx, derivedName, input.systemPromptSnapshot?.trim() ?? '');\n return toAgent(withPromptName);\n}\n\n/**\n * Seed the derived prompt with its first version and promote it to\n * `production` — an unpromoted v1 carries no label, so an agent following\n * `production` would resolve to nothing (same reasoning as the shared-prompt\n * creation flow's immediate promote).\n *\n * Best-effort: the agent record already exists and carries the text as its\n * level-3 fallback, so a Langfuse outage must not fail the create — the\n * operator lands on an agent whose \"prompt introuvable\" badge and empty\n * version list say exactly what is missing, and the first version written\n * from the edit panel repairs it.\n */\nasync function seedInitialVersion(\n ctx: SupportKitHandlerContext,\n promptName: string,\n content: string,\n): Promise<void> {\n if (!content) return;\n try {\n const { version } = await ctx.api.prompts.createVersion(promptName, { content });\n await ctx.api.prompts.promote(promptName, version, 'production');\n } catch (err) {\n ctx.logger.warn(\n `create-agent: could not seed \"${promptName}\" with its initial version — the text is kept as the agent's fallback (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n}\n","/**\n * `set-default-agent` (§3.4) — `uiInvoke`, promotes one agent to\n * `status: 'default'` while demoting whatever agent currently holds it.\n *\n * `records/agent.ts` documents the invariant: \"at most one default agent\",\n * enforced by a unique index on `defaultKey`, which is set to `'default'`\n * exactly when `status === 'default'` and left absent otherwise (so Postgres\n * NULLs never collide) — and states that POPULATING `defaultKey` correctly\n * is \"a write-handler concern\", not the record definition's. Before this\n * function existed, nothing populated it at all: AgentsPage's \"Définir par\n * défaut\" button wrote `{status: 'default'}` alone, from the browser, as two\n * independent `PATCH` calls with no shared transaction — `defaultKey` never\n * moved, the unique index never fired, and clicking the button on a second\n * agent produced two rows with `status: 'default'` without demoting the\n * first. `resolveDraftAgent` (`functions/records.ts`) resolves the default\n * agent via `list('agent', {filter:{status:'default'}, limit:1})`, so which\n * of the two an uncategorised ticket drafts with became non-deterministic,\n * and `ext-models` would serve two \"default\" agents to the extension (T26\n * review, BLOCKER 4).\n *\n * This function does both writes from ONE server-side call, DEMOTING the\n * incumbent BEFORE promoting the target — not the other way round, and not\n * in parallel: `defaultKey` carries a unique index, so having the incumbent\n * and the target both hold `'default'` at once, even for one write, would\n * violate it. Demoting first means a failure between the two writes leaves\n * AT MOST ZERO default agents (a safe, if inconvenient, state an operator\n * can fix by retrying) rather than two — this kit has no cross-record\n * transaction to make the pair atomic, so \"the worst reachable state is\n * still a legal one\" is the best guarantee available without one.\n *\n * `minRole: 'EDITOR'`: matches AgentsPage's other agent-mutating controls.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID } from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\nconst DEFAULT_KEY_VALUE = 'default';\n\nexport interface SetDefaultAgentInput {\n agentId: string;\n}\n\nexport function buildSetDefaultAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'set-default-agent'),\n name: 'set-default-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.TEXT,\n label: 'Agent id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSetDefaultAgentHandler(): AppHandler {\n return (ctx, input) =>\n setDefaultAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as SetDefaultAgentInput) ?? {});\n}\n\nexport async function setDefaultAgentHandler(\n ctx: SupportKitHandlerContext,\n input: SetDefaultAgentInput,\n): Promise<AgentRecord> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const target = toAgent(await ctx.api.get('agent', agentId));\n if (target.status === 'default') return target; // already the default — no-op, not an error.\n\n const incumbentPage = await ctx.api.list('agent', { filter: { status: 'default' }, limit: 1 });\n const incumbent = incumbentPage.items[0];\n if (incumbent && incumbent.id !== agentId) {\n await ctx.api.update('agent', incumbent.id, { status: 'available', defaultKey: null });\n }\n\n const promoted = await ctx.api.update('agent', agentId, {\n status: 'default',\n defaultKey: DEFAULT_KEY_VALUE,\n });\n return toAgent(promoted);\n}\n","/**\n * `create-shared-prompt-version` (§3.8 SharedPromptsPage, T27 part B) — the\n * ONE write path SharedPromptsPage uses to save a new `shared/*` prompt\n * version.\n *\n * Why this exists instead of the browser calling S3's own\n * `POST /data/apps/:appSlug/prompts/versions` directly (the way\n * `AgentsPage`'s `usePromptVersions.createVersion` already does for an\n * agent's prompt): that route writes whatever content it is given — it\n * does not run `validateReferences` (`./validate-references.ts`), and per\n * T19/T23's own review, nothing server-side does either. Since the kit\n * resolves `@@@langfusePrompt:…@@@` composition ITSELF (T19's\n * `prompts/resolver.ts`, reading with `resolve:false`), a malformed tag\n * saved through the raw REST route reaches every draft that composes\n * `shared/style-email`/`shared/style-whatsapp` verbatim, with nothing\n * server-side left to catch it — exactly the gap T23's review named for\n * `suggest-prompt`'s write path (§3.5). This is the same guard, for a\n * human operator's edit instead of an LLM suggestion.\n *\n * Scoped to `shared/` names only (refuses anything else): SharedPromptsPage\n * is a `shared/*` library editor, not a general prompt-writing surface.\n * `role.prompts`' `shared/*` glob (`pipeline.ts`'s `buildPromptsAllowlist`)\n * is the actual authorization boundary; this refusal is a narrower,\n * separate promise about what THIS function is for — `AgentsPage` keeps\n * writing an agent's own prompt through S3's raw route, unaffected.\n *\n * `minRole: 'EDITOR'`: a write, like every other prompt-mutating control\n * in the kit (`createVersion`/`promote`/`deleteVersion`, S3).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID, CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID } from './ids';\nimport { validateReferences } from './validate-references';\n\nconst SHARED_PREFIX = 'shared/';\n\nexport interface CreateSharedPromptVersionInput {\n name: string;\n content: string;\n}\n\nexport interface CreateSharedPromptVersionResult {\n version: number;\n}\n\nexport function buildCreateSharedPromptVersionFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-shared-prompt-version'),\n name: 'create-shared-prompt-version',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createCreateSharedPromptVersionHandler(): AppHandler {\n return (ctx, input) =>\n createSharedPromptVersionHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as CreateSharedPromptVersionInput) ?? { name: '', content: '' },\n );\n}\n\nexport async function createSharedPromptVersionHandler(\n ctx: SupportKitHandlerContext,\n input: CreateSharedPromptVersionInput,\n): Promise<CreateSharedPromptVersionResult> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n if (!name.startsWith(SHARED_PREFIX)) {\n throw new ctx.NonRetriableError(\n `\"${name}\" is not a shared/* prompt — create-shared-prompt-version only writes the shared/* library.`,\n );\n }\n const content = input?.content ?? '';\n if (!content.trim()) throw new ctx.NonRetriableError('content is required');\n\n const referenceErrors = await validateReferences(ctx.api, content, name);\n if (referenceErrors.length > 0) {\n throw new ctx.NonRetriableError(`Invalid reference tags: ${referenceErrors.join(' ')}`);\n }\n\n return ctx.api.prompts.createVersion(name, { content });\n}\n","/**\n * `sync-agent-prompt-snapshot` (§5.2) — `uiInvoke`, rewrites one agent's\n * `systemPromptSnapshot` with the prompt content that agent NOW serves.\n *\n * Why the snapshot needs a writer at all: `GET /models` serves\n * `system_prompt` from `agent.systemPromptSnapshot` ONLY (`ext-models.ts`)\n * — §5.2 forbids a synchronous Langfuse read there, because the extension\n * calls that route on every ticket change for every support agent. The spec\n * pays for that with one sentence: the snapshot is \"rafraîchi en tâche de\n * fond à chaque `createVersion`/`promote`\". Nothing did that. The only\n * writers were `create-agent` (from its input, once) and a hand edit in\n * AgentsPage, so promoting a new version moved what the PIPELINE drafts\n * with while the extension kept serving the text of whatever version was\n * current the day the agent was created — and `draftPromptRefFor`'s\n * level-3 fallback (`records.ts`) stayed pinned to that same stale text.\n *\n * Keyed by `promptName`, not by agent id, because the caller\n * (`ui/agents/use-prompt-versions.ts`) is a prompt-versions hook: it knows\n * the prompt it just wrote, never which record owns it. That also gives\n * the `shared/*` case its answer for free — a company-wide prompt belongs\n * to no agent, the lookup finds nothing, and the function is a no-op\n * rather than needing a namespace test of its own.\n *\n * WHAT IS SERVED, not what is newest: an agent pinned via\n * `agent.promptVersion` keeps drafting with that exact version, so its\n * snapshot must be that version's content — refreshing it to the newest\n * one would make `GET /models` advertise a prompt the pipeline does not\n * use. The ref built here is the same one `draftPromptRefFor` resolves.\n *\n * Read with `resolve: false`, like `createPlatformPromptReader`\n * (`adapters/ctx-ports.ts`): the kit flattens `@@@langfusePrompt:…@@@`\n * composition itself, so the snapshot must hold the RAW stored template —\n * the same text the resolver would have cached — not a pre-flattened\n * variant the fallback path would never produce.\n *\n * Never rejects on a resolution failure: by the time this runs, the\n * `createVersion`/`promote` it follows has already committed. Turning a\n * Langfuse outage into a failed promote would report a write that DID\n * happen as a write that did not; a stale snapshot is the lesser, and\n * self-correcting, harm (the next version write retries it).\n *\n * `minRole: 'EDITOR'`: it follows a prompt write, which is already\n * EDITOR-only (S3's own `createVersion`/`promote`).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID } from './ids';\nimport { toAgent } from './records';\n\nexport interface SyncAgentPromptSnapshotInput {\n promptName: string;\n}\n\nexport interface SyncAgentPromptSnapshotResult {\n /** `false` also covers \"nothing to do\": no agent owns the prompt, the snapshot already matched, or the read failed. */\n updated: boolean;\n}\n\nexport function buildSyncAgentPromptSnapshotFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sync-agent-prompt-snapshot'),\n name: 'sync-agent-prompt-snapshot',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSyncAgentPromptSnapshotHandler(): AppHandler {\n return (ctx, input) =>\n syncAgentPromptSnapshotHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as SyncAgentPromptSnapshotInput) ?? { promptName: '' },\n );\n}\n\nexport async function syncAgentPromptSnapshotHandler(\n ctx: SupportKitHandlerContext,\n input: SyncAgentPromptSnapshotInput,\n): Promise<SyncAgentPromptSnapshotResult> {\n const promptName = input?.promptName?.trim();\n if (!promptName) throw new ctx.NonRetriableError('promptName is required');\n\n // EVERY agent carrying the name, not `limit: 1`: two agents may point at\n // the same Langfuse prompt (pin vs follow), and refreshing only whichever\n // one the list returned first left the other serving a stale snapshot in\n // silence.\n const page = await ctx.api.list('agent', { filter: { promptName } });\n let updated = false;\n\n for (const record of page.items) {\n const agent = toAgent(record);\n try {\n const ref =\n agent.promptVersion !== null ? { version: agent.promptVersion } : { label: agent.promptLabel ?? 'production' };\n const detail = await ctx.api.prompts.get(promptName, { ...ref, resolve: false });\n if (detail.content === agent.systemPromptSnapshot) continue;\n\n await ctx.api.update('agent', agent.id, { systemPromptSnapshot: detail.content });\n updated = true;\n } catch (error) {\n ctx.logger.warn(\n `sync-agent-prompt-snapshot: could not refresh \"${promptName}\" for agent ${agent.id} — GET /models keeps serving the previous snapshot (${String(error)})`,\n );\n }\n }\n\n return { updated };\n}\n","/**\n * `ext-models` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports legacy\n * `GET /api/models` (extension-overview backoffice/src/routes/api.ts:27).\n * Reached only through the platform-served extension gateway (S6), always\n * as `phase: 'execute'`, fanned out to every accessible app and unioned —\n * this function MUST return an array: a non-array result is logged and\n * silently dropped from the union by the gateway\n * (`SupportExtensionService.invokeAll`), never surfaced as an error.\n *\n * `system_prompt` is served from `agent.systemPromptSnapshot` ONLY — never\n * a synchronous Langfuse resolution. §5.2 is explicit about why: this\n * endpoint is hit on every ticket change, by every agent, so a per-request\n * Langfuse round trip at that frequency is the exact cost the snapshot\n * exists to avoid. The snapshot itself is kept fresh out-of-band, by\n * whichever write path refreshes it on `createVersion`/`promote` — not this\n * function's job.\n *\n * `system_prompt_token_count` is kept (frozen data model, §5.2 — \"conservé\n * bien qu'ignoré par l'extension\") but is an APPROXIMATION, not tiktoken's\n * real count: the kit cannot depend on `tiktoken`\n * (`dependency-allowlist.ts`, spec §3.1 — it is a native/WASM dependency,\n * unsafe across an arbitrary app's ESM bundler). This ports the legacy\n * tokenizer's OWN documented fallback path verbatim\n * (`utils/tokenizer.ts`'s `catch` branch, `Math.ceil(text.length / 4)`) —\n * here it is the only implementation, not a fallback from a real\n * tokenizer. It is a rough estimate (English text averages roughly 4\n * characters per token; French/accented text and code both deviate\n * further from that ratio) and MUST NOT be treated as exact by any future\n * consumer — today's one consumer (the extension) explicitly ignores it.\n *\n * `archived` agents are excluded — legacy's `status: {$in: ['default',\n * 'available']}` filter. Legacy sorts `{status: 1, name: 1}`; ported here\n * for this function's OWN array. The GATEWAY re-sorts the union by\n * `(order, name)` (§S6, D3) and a model carries no `order` field, so the\n * final wire order across multiple support apps ends up name-alphabetical\n * rather than `(status, name)` — a documented S6/T8 divergence from the\n * legacy, not this function's to fix (see the migration progress journal's\n * T24 entry).\n *\n * SETTINGS VALIDATION: deliberately NOT called here, same reasoning as\n * `list-gorgias-views`'s own documented exception. This function reads no\n * field `validateSettings` checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) — it is a pure read of `agent` records serving a human\n * agent's Gorgias sidebar model picker. Gating it on settings validity\n * would break that picker for a tenant mid-setup, for no correctness\n * reason: nothing here depends on the triage pipeline being configured.\n *\n * `minRole: 'VIEWER'` is load-bearing: `SupportExtensionService\n * .hasAllReservedFunctions` refuses to treat an app as a support app\n * unless all six reserved functions declare exactly `VIEWER`.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent } from './records';\n\nconst TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtModel {\n _id: string;\n name: string;\n provider: string;\n model_id: string;\n system_prompt: string;\n system_prompt_token_count: number;\n status: 'default' | 'available';\n}\n\nexport function buildExtModelsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-models'),\n name: 'ext-models',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtModelsHandler(): AppHandler {\n return (ctx) => extModelsHandler(ctx as SupportKitHandlerContext);\n}\n\nexport async function extModelsHandler(ctx: SupportKitHandlerContext): Promise<ExtModel[]> {\n const page = await ctx.api.list('agent', { limit: AGENT_PAGE_SIZE });\n // L15: the migration's standing rule is \"no silent caps\" — past 500\n // agents the union would silently lose entries with no cursor and no\n // warning.\n if (page.items.length >= AGENT_PAGE_SIZE) {\n ctx.logger.warn(`ext-models: \"agent\" page came back full at ${page.items.length} rows — some may be silently missing from the response.`);\n }\n\n return page.items\n .map(toAgent)\n .filter((agent): agent is typeof agent & { status: 'default' | 'available' } => agent.status !== 'archived')\n .sort((a, b) => (a.status === b.status ? a.name.localeCompare(b.name) : a.status.localeCompare(b.status)))\n .map((agent) => {\n const systemPrompt = agent.systemPromptSnapshot ?? '';\n return {\n _id: agent.id,\n name: agent.name,\n provider: agent.provider,\n model_id: agent.modelId,\n system_prompt: systemPrompt,\n system_prompt_token_count: approximateTokenCount(systemPrompt),\n status: agent.status,\n };\n });\n}\n\nfunction approximateTokenCount(text: string): number {\n return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);\n}\n","/**\n * `ext-categories` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports\n * legacy `GET /api/categories` (extension-overview backoffice/src/routes\n * /api.ts:50). Reached only through the S6 gateway, always `phase:\n * 'execute'`, fanned out to every accessible app and unioned — MUST return\n * an array (a non-array is dropped by the gateway, same rule as\n * `ext-models`).\n *\n * Filter (legacy `Category.find({agent: {$ne: null}}).populate({path:\n * 'agent', match: {status: {$ne: 'archived'}}})` then `.filter(c => c.agent\n * !== null)`): a category counts only when it HAS an `agentId` AND that\n * agent resolves AND is not archived. §5.2's own response shape freezes\n * `agent: {...} | null`, but this filter means the `| null` branch is\n * UNREACHABLE through this handler today — kept in the type for wire\n * fidelity with the frozen contract, never actually emitted.\n *\n * Sort (composite, §5.2's own doc on this route): `group.order` ASC, with\n * ungrouped categories FIRST (`null` sorts as `-Infinity`) → `category\n * .order` ASC → `category.name` `localeCompare`. The category-group record\n * already exists (`records/category-group.ts`); this function is its\n * first reader.\n *\n * WIRE `order` IS NOT `category.order` (M4 hardening): the S6 gateway\n * unions every accessible app's categories and re-sorts by `(order, name)`\n * ONLY — it has no visibility into the group concept at all\n * (`support-extension.service.ts`'s own doc on `sortedUnion`). `order` is\n * per-GROUP, not global, so emitting the raw field would let the gateway's\n * blind re-sort silently destroy the group ordering this function just\n * computed (a single installed app is enough to observe it — no multi-app\n * edge case required). What is emitted instead is this category's own\n * POSITION in the fully sorted sequence above (0, 1, 2, …) — a composite\n * rank that already encodes group→order→name as one monotonic number, so\n * the gateway's re-sort is a genuine no-op on this app's contiguous slice,\n * not just a documented aspiration.\n *\n * SETTINGS VALIDATION: deliberately NOT called, same reasoning as\n * `ext-models` — a pure read of `category`/`agent` records serving a human\n * agent's Gorgias sidebar, gated on none of `validateSettings`'s fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent, toCategory, toCategoryGroup, type AgentRecord, type CategoryRecord } from './records';\n\nconst CATEGORY_PAGE_SIZE = 500;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtCategoryAgent {\n _id: string;\n name: string;\n model_id: string;\n provider: string;\n}\n\nexport interface ExtCategory {\n _id: string;\n name: string;\n tag_name: string;\n order: number;\n agent: ExtCategoryAgent | null;\n}\n\nexport function buildExtCategoriesFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-categories'),\n name: 'ext-categories',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtCategoriesHandler(): AppHandler {\n return (ctx) => extCategoriesHandler(ctx as SupportKitHandlerContext);\n}\n\ninterface SortableEntry {\n category: CategoryRecord;\n agent: AgentRecord;\n groupOrder: number;\n}\n\nexport async function extCategoriesHandler(ctx: SupportKitHandlerContext): Promise<ExtCategory[]> {\n const [categoriesPage, groupsPage, agentsPage] = await Promise.all([\n ctx.api.list('category', { limit: CATEGORY_PAGE_SIZE }),\n ctx.api.list('category-group', { limit: CATEGORY_PAGE_SIZE }),\n // M7: ONE bulk read, not one `ctx.api.get` per category — this endpoint\n // runs on the same \"every ticket change, every agent\" cadence §5.2\n // documents for `/models` (which already does this), inside the\n // gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips\n // risk a slow tenant's whole categories response silently dropping out\n // of the union on budget exhaustion.\n ctx.api.list('agent', { limit: AGENT_PAGE_SIZE }),\n ]);\n warnIfTruncated(ctx, 'category', categoriesPage.items.length, CATEGORY_PAGE_SIZE);\n warnIfTruncated(ctx, 'agent', agentsPage.items.length, AGENT_PAGE_SIZE);\n\n const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));\n const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));\n\n const entries: SortableEntry[] = [];\n for (const category of categoriesPage.items.map(toCategory)) {\n if (!category.agentId) continue;\n const agent = agentById.get(category.agentId);\n if (!agent) continue;\n if (agent.status === 'archived') continue;\n\n const groupOrder = category.groupId ? (groupOrderById.get(category.groupId) ?? -Infinity) : -Infinity;\n entries.push({ category, agent, groupOrder });\n }\n\n entries.sort((a, b) => {\n if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;\n if (a.category.order !== b.category.order) return a.category.order - b.category.order;\n return a.category.name.localeCompare(b.category.name);\n });\n\n return entries.map(({ category, agent }, index) => ({\n _id: category.id,\n name: category.name,\n tag_name: category.tagName,\n // M4: this category's own POSITION in the fully sorted sequence, not\n // `category.order` verbatim — see this module's own doc.\n order: index,\n agent: { _id: agent.id, name: agent.name, model_id: agent.modelId, provider: agent.provider },\n }));\n}\n\n/** L15: the migration's standing rule is \"no silent caps\" — a page that comes back exactly full warrants a log, not a quiet truncation. */\nfunction warnIfTruncated(ctx: SupportKitHandlerContext, objectKey: string, itemCount: number, pageSize: number): void {\n if (itemCount >= pageSize) {\n ctx.logger.warn(`ext-categories: \"${objectKey}\" page came back full at ${itemCount} rows — some may be silently missing from the response.`);\n }\n}\n","/**\n * `ownsAgent` (L6) — the ONE `agent`-ownership probe check shared by\n * `ext-chat`, `ext-evaluation` and `ext-response-comparison`'s `phase:\n * 'probe'` branches (§S6 B1/B2): each restated the same `{claimed: true}`\n * sentinel, the same \"non-null claims / null disclaims / a genuine read\n * failure is never a disclaimer, it propagates as a real error\" contract,\n * and the same union return type. Three uses, so the no-premature-\n * abstraction rule does not shield the duplication.\n *\n * `id` absent/empty never claims — callers decide separately what to try\n * next on a `null` (`ext-chat` falls back to the default agent,\n * `ext-response-comparison` falls back to ticket ownership); this helper\n * only ever answers \"does this app own this one id\".\n */\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface ProbeClaim {\n claimed: true;\n}\n\nexport async function ownsAgent(ctx: SupportKitHandlerContext, id: string | null | undefined): Promise<ProbeClaim | null> {\n if (!id) return null;\n const record = await getOptional(ctx, 'agent', id);\n return record ? { claimed: true } : null;\n}\n","/**\n * `readSupportExtensionEnvelope` — the identity/phase the S6 gateway passes\n * on every reserved `ext-*` invocation\n * (`SupportExtensionService.invoke`'s `event: {supportExtension: {userId,\n * phase}}`, apps/api/src/platform-data/support-extension.service.ts).\n * Shared by every function that needs either half: `ext-chat`/\n * `ext-evaluation`/`ext-response-comparison` for the probe/execute split\n * (§5.1/§S6), `ext-evaluation` (`supportUserKeyId`) and\n * `ext-fast-response-check` (`servedTo`) for the platform user id itself.\n *\n * Defensive default, not a thrown error: an envelope that is missing or\n * malformed — which never happens through the real gateway, nothing else\n * invokes these reserved functions (§3.5 line 291) — resolves to `phase:\n * 'execute'` and `userId: ''` rather than crashing the whole handler on a\n * read. `'execute'` is the safe default direction for the phase: treating\n * an ambiguous call as `'probe'` would silently skip whatever real work the\n * caller actually wanted, while treating it as `'execute'` on a call that\n * WAS meant to be a cheap ownership probe only risks doing that same real\n * work anyway — never doing LESS than asked.\n *\n * `userId: ''` IS a safe default here — this is a pure READ with no side\n * effect. It is NOT safe symmetric treatment for the two call sites that\n * write it into an identity-bearing record (`ext-fast-response-check.ts`'s\n * `servedTo` push, `ext-evaluation.ts`'s `supportUserKeyId`) — §5.1\n * requires those records to carry the platform user id, so both callers\n * guard `!envelope.userId` themselves and fail the WRITE rather than\n * silently producing an anonymous-looking or null-identity row (L11\n * hardening). This function stays a defensive default, not a thrown error,\n * exactly as designed above; the burden of turning \"no identity\" into a\n * hard failure is on the two write sites that actually need one.\n */\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface SupportExtensionEnvelope {\n userId: string;\n phase: 'probe' | 'execute';\n}\n\nexport function readSupportExtensionEnvelope(ctx: SupportKitHandlerContext): SupportExtensionEnvelope {\n const raw = (ctx.event as { supportExtension?: { userId?: unknown; phase?: unknown } } | undefined)?.supportExtension;\n return {\n userId: typeof raw?.userId === 'string' ? raw.userId : '',\n phase: raw?.phase === 'probe' ? 'probe' : 'execute',\n };\n}\n","/**\n * `ext-chat` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-routed\n * (§S6). Ports legacy `POST /api/chat` (extension-overview backoffice/src\n * /routes/api.ts:147).\n *\n * OWNERSHIP PROBE (§S6 B1/B2): the gateway first calls this function with\n * `phase: 'probe'` and an id-only payload `{modelId}` — `modelId` may be\n * `undefined` (the legacy falls back to the single `status: 'default'`\n * model when it is absent). A probe MUST be cheap, local and side-effect-\n * free: no writes, no LLM call, no Gorgias fetch (`readSupportExtension\n * Envelope` picks the phase; the probe branch below only ever reads the\n * `agent` object). Claim rule, decided explicitly:\n * - `modelId` given → claim iff this app owns an `agent` record with\n * that id (any status — the legacy `ModelConfig.findById` applies no\n * status filter for chat, unlike `ext-models`).\n * - `modelId` absent → claim iff this app has a `status: 'default'`\n * agent.\n * AMBIGUITY, stated not hidden: with several installed support apps and no\n * `modelId`, more than one app can legitimately have its own default\n * agent, so more than one can claim the SAME probe. The gateway logs a\n * warning and routes to the first claimant (`SupportExtensionService\n * .invokeOwner`) — this function has no way to break that tie itself, and\n * does not try to. Returning any non-null value claims ownership; `null`\n * disclaims it. THROWING is never a way to say \"not mine\" (a genuine read\n * failure here propagates as a real error, exactly like every other\n * function — the gateway treats a probe throw as a fan-out failure, never\n * a disclaimer).\n *\n * EXECUTE: once ownership resolves, the gateway sends ONE `phase:\n * 'execute'` call with the full body — `{messages, modelId, agentName}` OR\n * `{gorgiasTicketId, modelId, agentName}`. When `gorgiasTicketId` is given\n * the conversation is rebuilt server-side via S1's `buildTicketContext`\n * action (NOT `getTicketWithContext` — only the extracted messages are\n * needed here, not the raw ticket payload `getTicketWithContext` also\n * fetches for the guardrail detectors elsewhere in the kit).\n *\n * PROMPT RESOLUTION reuses the kit's own §3.7 ladder\n * (`createPlatformPromptPort`) and `functions/records.ts`'s\n * `draftPromptRefFor` — the SAME binding `process-response` resolves the\n * `draft` node's prompt from (agent.promptName/promptLabel/\n * systemPromptSnapshot) — rather than writing a second resolver.\n *\n * `{{agent_name}}` SIGNATURE: §3.7 states the substitution is \"injectée\n * par `ext-chat`\" — this function calls the exact ported\n * `applySignature` (`graph/nodes/shared.ts`, exported for this reuse) on\n * the RESOLVED prompt text with the extension's own `agentName`, not the\n * generic `{{var}}` substitution `PromptPort.resolve`'s `vars` parameter\n * offers (which is a plain string replace, not `applySignature`'s full\n * rule set — appending a French signing instruction when there is no\n * placeholder at all). Reusing the ported function here — instead of a\n * second, subtly different implementation — was an explicit instruction in\n * this migration.\n *\n * SETTINGS VALIDATION: deliberately NOT called. Chat resolves its prompt\n * from the `agent` record's own binding, never from `validateSettings`'s\n * three checked fields (`sourceViewId`, `nodes.triage`, `senderEmail`) — a\n * misconfigured triage pipeline must not block an agent from testing a\n * model in the sidebar.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n *\n * POST-T24 REVIEW HARDENING:\n * - `options.model` now reads `resolvedPrompt.config?.model ?? agent\n * .modelId` (I16) — the resolved prompt's own model config wins, matching\n * every ported graph node; this was the one `PromptPort.resolve` consumer\n * that dropped it.\n * - `promptRef` IS forwarded to `ctx.api.llm.complete`, in LINK-ONLY mode\n * (`resolve: false`) — the D-LF follow-up task's resolution (option (b),\n * see the migration progress journal's T24 entry and its \"done\" correction):\n * the platform now decouples trace linkage from resolution, so a caller\n * that already resolved its own prompt (this function did, via\n * `PromptPort` two lines above) can link the completion to it in Langfuse\n * WITHOUT re-triggering the `manifest.prompts[]` declaration gate or the\n * system-message replacement (`app-integrations.controller.ts`'s\n * `llmComplete` JSDoc). This restores the same prompt-identity trace\n * linkage the platform's default mode gives every other caller, without\n * the 403/overwrite defect that forced the `trace.metadata` workaround\n * below during T24. The platform user id still travels on `trace.metadata`\n * (`ctx.api.llm.complete`'s `trace` has no dedicated `userId` field) — the\n * prompt identity no longer needs to, now that `promptRef` carries it. The\n * wire response is UNCHANGED — it still reports `prompt_name`/\n * `prompt_version` off `resolvedPrompt`.\n * The five graph nodes (`triage`/`escalate`/`draft`/`revise`/`evaluate`)\n * plus `suggest-prompt.ts`/`run-diff-analysis.ts` forward `promptRef` the\n * same link-only way now too — all seven sites adopted together.\n * - The gorgias-ticket branch now 400s on zero extracted messages, the same\n * guard the `input.messages` branch already had (M1) — an internal-notes-\n * only or automated-sender ticket must not pay for an LLM call with a\n * system message and no conversation.\n * - A Gorgias 404 (duck-typed off the caught error's `status`, since this\n * package has no dependency on `gorgias-client`'s `ProviderHttpError` to\n * `instanceof`-check) now throws `NonRetriableError` instead of a bare\n * rethrow (L1, PARTIAL). The legacy's other two mappings — \"not\n * configured\" → 503, else → 502 — are NOT reachable from here: every\n * `uiInvoke` throw funnels through `AppSyncInvocationService.toHttpError`\n * (`apps/api/src/platform-data/app-sync-invocation.service.ts`), which\n * recognises exactly two outcomes for an app-thrown error —\n * `AppNonRetriableError` → 422, anything else → 500 — regardless of what\n * `invokeOwner` does or doesn't wrap. 503/502 are outside this function's\n * reach without a platform change to that mapping.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { RawTicketContext } from '../adapters';\nimport { createPlatformPromptPort } from '../adapters/ctx-ports';\n// L9: through the barrel, not `./shared` directly — `graph/nodes/index.ts`'s\n// own doc names `applySignature` as its one curated export existing FOR this\n// reuse; importing straight from the file it lives in made that barrel entry\n// unused and its own justification inaccurate.\nimport { applySignature } from '../graph/nodes';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_CHAT_INPUT_AGENT_NAME_UID,\n EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n EXT_CHAT_INPUT_MESSAGES_UID,\n EXT_CHAT_INPUT_MODEL_ID_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { draftPromptRefFor, toAgent, type AgentRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst DEFAULT_AGENT_FILTER = { status: 'default' } as const;\n\ninterface WireChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ExtChatInput {\n messages?: Array<{ role?: unknown; content?: unknown }> | null;\n modelId?: string | null;\n agentName?: string | null;\n gorgiasTicketId?: string | null;\n}\n\nexport interface ExtChatResult {\n answer: string;\n modelId: string;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n}\n\nexport function buildExtChatFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-chat'),\n name: 'ext-chat',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_CHAT_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — required unless gorgiasTicketId is given.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_MODEL_ID_UID,\n name: 'modelId',\n type: FieldType.TEXT,\n label: 'Model id',\n description: 'Absent falls back to the single status=\"default\" agent.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_AGENT_NAME_UID,\n name: 'agentName',\n type: FieldType.TEXT,\n label: 'Agent name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n name: 'gorgiasTicketId',\n type: FieldType.TEXT,\n label: 'Gorgias ticket id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtChatHandler(): AppHandler {\n return (ctx, input) => extChatHandler(ctx as SupportKitHandlerContext, (input as ExtChatInput) ?? {});\n}\n\nexport async function extChatHandler(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<ExtChatResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeChatOwnership(ctx, input.modelId ?? null);\n return executeChat(ctx, envelope.userId, input);\n}\n\nasync function probeChatOwnership(ctx: SupportKitHandlerContext, modelId: string | null): Promise<ProbeClaim | null> {\n if (modelId) return ownsAgent(ctx, modelId);\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeChat(ctx: SupportKitHandlerContext, userId: string, input: ExtChatInput): Promise<ExtChatResult> {\n const contextMessages = await resolveMessages(ctx, input);\n const agent = await resolveAgent(ctx, input.modelId ?? null);\n\n const promptPort = createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message));\n // H5 (T25 review): draftPromptRefFor's \"no agent configured\" sentinel is\n // scoped by promptPrefix — but createExtChatHandler() takes no\n // SupportKitFunctionConfig at all (unlike every other ext-* handler that\n // needs one, none of the six do), so this call site has no promptPrefix\n // to pass. `{ promptPrefix: '' }` keeps today's behaviour for\n // experience-client unchanged; a pro-sante (or later) audience installed\n // with a non-empty prefix still 403s on this specific path exactly as it\n // already did before this fix. Threading config through the S6 gateway's\n // internal ext-chat invocation is a wider change than this finding's\n // fix — flagged, not silently masked.\n const promptRef = draftPromptRefFor(agent, { promptPrefix: '' });\n const resolvedPrompt = await promptPort.resolve(promptRef);\n const systemContent = applySignature(resolvedPrompt.text, input.agentName ?? undefined);\n const chatMessages: WireChatMessage[] = systemContent\n ? [{ role: 'system', content: systemContent }, ...contextMessages]\n : contextMessages;\n\n const result = await ctx.api.llm.complete({\n messages: chatMessages,\n // H3/I16: the resolved Langfuse prompt's own model config WINS over the\n // agent's fallback modelId — every ported graph node applies this same\n // rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort\n // .resolve` consumer in the repo that dropped it.\n options: { model: resolvedPrompt.config?.model ?? agent.modelId },\n // Link-only (D-LF follow-up, option (b)): this function already resolved\n // its own prompt two lines above via `PromptPort` — `resolve: false`\n // links the completion to it in Langfuse WITHOUT re-triggering the\n // platform's own resolution (no `manifest.prompts[]` gate, no\n // system-message replacement of the `applySignature`-signed message just\n // composed above). `label` is the REAL resolved label — `promptRef\n // .label`, i.e. `agent.promptLabel ?? 'production'`\n // (`functions/records.ts`'s `draftPromptRefFor`) — not a hardcoded\n // 'production', so a staging-labelled agent's traces say so instead of\n // silently attributing to production.\n promptRef: {\n name: resolvedPrompt.name,\n version: resolvedPrompt.version,\n label: promptRef.label,\n resolve: false,\n },\n trace: {\n sessionId: input.gorgiasTicketId ?? undefined,\n metadata: {\n // L2: the agent's own identity — `ctx.api.llm.complete`'s `trace`\n // has no dedicated `userId` field (unlike `graph/ports.ts`'s\n // `CompletionRequest`), only `metadata`. The prompt identity itself\n // no longer needs to travel here — `promptRef` above carries it.\n userId,\n model: agent.modelId,\n ...(input.gorgiasTicketId ? { ticketId: input.gorgiasTicketId } : {}),\n },\n },\n });\n\n const answer = result.text?.trim();\n if (!answer) throw new ctx.NonRetriableError('Provider returned an empty response');\n\n return {\n answer,\n modelId: agent.id,\n langfuse_trace_id: result.traceId ?? null,\n langfuse_observation_id: result.observationId ?? null,\n prompt_name: resolvedPrompt.name,\n prompt_version: resolvedPrompt.version,\n };\n}\n\nasync function resolveMessages(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<WireChatMessage[]> {\n if (input.gorgiasTicketId) {\n // L10: the exported `RawTicketContext` shape (`adapters/index.ts`),\n // not a second inline redeclaration of it. Note the divergence this\n // reader and `toConversation` (`adapters/conversation-mapping.ts`) have\n // on the SAME action's output: this one admits `system` turns\n // (matching the legacy chat route), `toConversation` filters them out —\n // both correct for what each one feeds, neither aware of the other.\n const raw = (await runBuildTicketContext(ctx, input.gorgiasTicketId)) as RawTicketContext;\n // M1: the legacy's shared `messages.length === 0` 400-guard covered\n // BOTH the `input.messages` path and this `gorgiasTicketId` one — this\n // port only guarded the former. A ticket with nothing extractable\n // (internal notes only, an automated-sender thread) must 400 instantly,\n // not pay for an LLM call with a system message and no conversation.\n if (!Array.isArray(raw.messages) || raw.messages.length === 0) {\n throw new ctx.NonRetriableError(`No usable messages extracted for Gorgias ticket ${input.gorgiasTicketId}`);\n }\n return raw.messages.map((m) => toWireChatMessage(m));\n }\n if (Array.isArray(input.messages) && input.messages.length > 0) {\n return input.messages.map((m) => toWireChatMessage(m));\n }\n throw new ctx.NonRetriableError('`messages` must be a non-empty array, or provide `gorgiasTicketId`');\n}\n\n/**\n * L1, PARTIAL — see this module's own doc for what is and is not achievable\n * here. Distinguishes the one genuinely non-retriable Gorgias failure (the\n * ticket does not exist) from everything else (misconfiguration, the\n * provider being down, a timeout) by DUCK-TYPING the error shape\n * `@apotech-os/gorgias-client`'s `ProviderHttpError` carries — `status`/\n * `name` on the caught value — rather than an `instanceof` check: this\n * package has no dependency on `gorgias-client` at all\n * (`dependency-allowlist.ts`; an app cannot import a platform-internal\n * client), so a structural check is the only kind available.\n */\nasync function runBuildTicketContext(ctx: SupportKitHandlerContext, ticketId: string): Promise<unknown> {\n try {\n return await ctx.api.integrations.run('gorgias', 'buildTicketContext', { ticketId });\n } catch (err) {\n if (isGorgiasNotFound(err)) {\n throw new ctx.NonRetriableError(`Gorgias ticket ${ticketId} not found`);\n }\n // Everything else (misconfigured connection, the provider down, a\n // timeout) is NOT retried by throwing `NonRetriableError` — unlike a\n // missing ticket, a transient Gorgias outage may well succeed on the\n // next call. This still surfaces as a generic 500 to the extension: see\n // this module's own doc for why 503/502 are unreachable from here.\n throw err;\n }\n}\n\nfunction isGorgiasNotFound(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false;\n const { status } = err as { status?: unknown };\n return status === 404;\n}\n\nfunction toWireChatMessage(raw: { role?: unknown; content?: unknown }): WireChatMessage {\n const role = raw.role;\n if (role !== 'system' && role !== 'user' && role !== 'assistant') {\n throw new Error(`ext-chat: message role must be \"system\", \"user\" or \"assistant\", got ${JSON.stringify(role)}`);\n }\n return { role, content: typeof raw.content === 'string' ? raw.content : '' };\n}\n\nasync function resolveAgent(ctx: SupportKitHandlerContext, modelId: string | null): Promise<AgentRecord> {\n if (modelId) {\n const record = await getOptional(ctx, 'agent', modelId);\n if (!record) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n return toAgent(record);\n }\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n const record = page.items[0];\n if (!record) throw new ctx.NonRetriableError('No default model configured');\n return toAgent(record);\n}\n","/**\n * `ext-fast-response-check` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * always `phase: 'execute'`, fanned out to every accessible app (§S6: \"au\n * plus un hit attendu — premier hit servi, hits multiples loggés en\n * anomalie\" — that fan-out/first-hit policy is the GATEWAY's, not this\n * function's). Ports legacy `POST /api/fast-response/check`\n * (extension-overview backoffice/src/routes/api.ts:291) — the most\n * defect-prone of the six, ported rule for rule:\n *\n * 1. Look up the `generated-response` row for `ticket_id` with `status:\n * 'ready'`. None → `{available: false}`.\n * 2. TTL: `expiresAt < now` → flip `ready -> expired` (conditional on still\n * being `ready`, S5 `ifMatch`) and return `{available: false}`.\n * 3. Divergence, RECOMPUTED SERVER-SIDE — never from client-supplied\n * values: re-fetch the ticket via S1's `getRawTicket` action and take\n * the snapshot with the kit's own `snapshotConversation`\n * (`adapters/conversation-mapping.ts`, already the symmetric port of the\n * extension's `countableMessages`/divergence rule — reused, not\n * re-derived). Diverged (`currentCount > snappedCount`, or\n * `currentLastAt` present and newer than `snappedLastAt`/absent) → flip\n * `ready -> invalidated` and return `{available: false}`.\n * 4. Gorgias fetch failure, OR a successful-but-unusable payload (no\n * `ticket`, or a `ticket` with no messages — H1 hardening: otherwise\n * `snapshotConversation({})` reads as zero messages, which can only ever\n * look like NO divergence and would serve a stale draft) ⇒ FAIL-CLOSED:\n * `{available: false}`, the row is left `ready`, nothing is written — a\n * transient Gorgias outage must never look like \"the draft was\n * invalidated\".\n * 5. Hit: `servedCount++`, push `{user, at}` onto `servedTo` (capped at 500\n * entries — `servedCount` keeps incrementing past the cap, only the\n * array stops growing) via S5 `ifMatch: {servedCount: <value just read>}`\n * PLUS A RETRY: the read-modify-write of the `servedTo` JSON array is not\n * atomic, so a lost `ifMatch` race (two concurrent `/check` calls on the\n * same ready row) re-reads the row and retries with the fresh count —\n * UNLESS the re-read shows the row is no longer `ready` (another writer\n * genuinely moved it: an expiry/divergence flip, or a send), in which\n * case this is a real miss, exactly the legacy's `race_lost` branch —\n * see `serveHit` below, bounded at `MAX_SERVE_ATTEMPTS`. CASing on\n * `status` here (H2 hardening) would be a no-op guard: this write never\n * changes `status`, so two concurrent hits would both pass an\n * `ifMatch: {status: 'ready'}` unconditionally and one serve record\n * would silently vanish — `servedCount` is the field that actually\n * discriminates concurrent writers.\n *\n * `followup_required` — DECISION (the brief asks for one, explicitly):\n * derived from the record's `verdict.verdict` field via the ported\n * `requiresFollowup` (legacy-faithful: `requiresFollowup(job\n * .evaluation_verdict)`), NOT read off a stored `followupRequired`\n * boolean. Checked before choosing: `records/generated-response.ts`\n * declares `followupRequired` with a `false` default, and grep across this\n * package shows exactly ONE writer — `triage-tick.ts` sets it `false` at\n * CREATION time — and no writer ever updates it once the real verdict is\n * known (`process-response.ts` persists `verdict` on the `ready` row but\n * never touches `followupRequired`). The stored field is therefore\n * effectively dead (always `false`); deriving from `verdict` is both\n * legacy-faithful and the only way to get a correct answer.\n *\n * `last_served_at` — the legacy also stamped this on every hit; the kit's\n * `generated-response` record (§3.4, frozen at T20) has no such field.\n * NOT silently dropped: nothing in this package reads it, and each\n * `servedTo[].at` entry already carries the same information (the most\n * recent entry IS the last-served timestamp) — so the cost is a query that\n * wants \"when was this last served\" needing to read the tail of `servedTo`\n * instead of one scalar field, not a loss of information.\n *\n * SETTINGS VALIDATION: deliberately NOT called. This function reads\n * `expiresAt` off the ROW itself — computed once at generation time from\n * `responseTtlMinutes`, already baked in — never a live settings read; none\n * of `validateSettings`'s three checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) apply to serving an already-generated draft.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { AppApiError, type AppApiRecord, type AppHandler, FieldType, type FunctionDef } from '@apotech-os/app-kit';\nimport { snapshotConversation } from '../adapters/conversation-mapping';\nimport type { RawTicket } from '../guardrails';\nimport { isEvaluationVerdict, requiresFollowup } from '../domain';\nimport { isGeneratedResponseStatus, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID } from './ids';\nimport { toDate } from './pipeline-state';\nimport { toAgent, toCategory, toGeneratedResponse, type GeneratedResponseRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst SERVED_TO_CAP = 500;\nconst MAX_SERVE_ATTEMPTS = 3;\n\nexport interface ExtFastResponseCheckInput {\n ticket_id: string;\n}\n\nexport type ExtFastResponseCheckResult =\n | { available: false }\n | {\n available: true;\n response: string;\n category: { _id: string; name: string } | null;\n agent: { _id: string; name: string; model_id: string } | null;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n generated_at: string;\n followup_required: boolean;\n };\n\nexport function buildExtFastResponseCheckFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-fast-response-check'),\n name: 'ext-fast-response-check',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createExtFastResponseCheckHandler(): AppHandler {\n return (ctx, input) => extFastResponseCheckHandler(ctx as SupportKitHandlerContext, input as unknown as ExtFastResponseCheckInput);\n}\n\nconst NOT_AVAILABLE: ExtFastResponseCheckResult = { available: false };\n\nexport async function extFastResponseCheckHandler(\n ctx: SupportKitHandlerContext,\n input: ExtFastResponseCheckInput,\n): Promise<ExtFastResponseCheckResult> {\n const ticketId = typeof input?.ticket_id === 'string' ? input.ticket_id.trim() : '';\n if (!ticketId) throw new ctx.NonRetriableError('`ticket_id` must be a non-empty string');\n\n const page = await ctx.api.list('generated-response', { filter: { ticketId, status: 'ready' }, limit: 1 });\n const row = page.items[0];\n if (!row) {\n logReason(ctx, ticketId, 'no_ready_job');\n return NOT_AVAILABLE;\n }\n const generatedResponse = toGeneratedResponse(row);\n\n const now = new Date();\n\n const expiresAt = toDate(generatedResponse.expiresAt);\n if (expiresAt && expiresAt.getTime() < now.getTime()) {\n logReason(ctx, ticketId, 'expired');\n await flipStatus(ctx, row.id, ticketId, 'expired');\n return NOT_AVAILABLE;\n }\n\n let rawTicket: RawTicket;\n try {\n const fetched = (await ctx.api.integrations.run('gorgias', 'getRawTicket', { ticketId })) as { ticket?: RawTicket };\n // H1 hardening: a successful-but-unusable payload (no `ticket`, or a\n // `ticket` with no messages) is indistinguishable from a fetch failure\n // for divergence purposes — `snapshotConversation({})` would read as\n // \"0 messages, no last-message date\", which can only ever look like\n // NO divergence and would serve a draft that may already be stale.\n // Fail-closed the same way rule 4 does for a thrown fetch error.\n if (!fetched.ticket || !fetched.ticket.messages || fetched.ticket.messages.length === 0) {\n logReason(ctx, ticketId, 'gorgias_fetch_failed', 'empty or missing ticket.messages');\n return NOT_AVAILABLE;\n }\n rawTicket = fetched.ticket;\n } catch (err) {\n // Fail-closed (rule 4): cannot validate the draft is still fresh, so it\n // is unavailable — but the row itself is left untouched.\n logReason(ctx, ticketId, 'gorgias_fetch_failed', err instanceof Error ? err.message : String(err));\n return NOT_AVAILABLE;\n }\n\n const divergence = checkDivergence(rawTicket, generatedResponse);\n if (divergence.diverged) {\n logReason(ctx, ticketId, `diverged[count(snap=${divergence.snappedCount},now=${divergence.count}),date(snap=${isoOrNull(divergence.snappedLastAt)},now=${isoOrNull(divergence.lastAt)})]`);\n await flipStatus(ctx, row.id, ticketId, 'invalidated');\n return NOT_AVAILABLE;\n }\n\n const envelope = readSupportExtensionEnvelope(ctx);\n // L11: an empty platform user id must fail the WRITE, not silently push\n // `servedTo: [{user: '', at}]` — an anonymous entry indistinguishable\n // from a legitimate serve. `readSupportExtensionEnvelope`'s own doc notes\n // this never happens through the real gateway; this is the last line of\n // defence against a malformed envelope masquerading as a real one.\n if (!envelope.userId) {\n throw new ctx.NonRetriableError('ext-fast-response-check: missing platform user id in the invocation envelope');\n }\n const served = await serveHit(ctx, row, envelope.userId, now);\n if (!served) {\n logReason(ctx, ticketId, 'race_lost');\n return NOT_AVAILABLE;\n }\n const servedResponse = toGeneratedResponse(served);\n logReason(ctx, ticketId, `hit served_count=${servedResponse.servedCount}`);\n if (servedResponse.servedCount > SERVED_TO_CAP) {\n ctx.logger.warn(`ext-fast-response-check: ticket=${ticketId} servedTo capped at ${SERVED_TO_CAP} entries (served_count=${servedResponse.servedCount})`);\n }\n\n return buildAvailableResponse(ctx, servedResponse);\n}\n\nfunction logReason(ctx: SupportKitHandlerContext, ticketId: string, reason: string, detail?: string): void {\n const suffix = detail ? ` detail=${JSON.stringify(detail)}` : '';\n ctx.logger.info(`ext-fast-response-check: ticket=${ticketId} reason=${reason}${suffix}`);\n}\n\nfunction isoOrNull(date: Date | null): string {\n return date ? date.toISOString() : 'null';\n}\n\ninterface DivergenceCheck {\n diverged: boolean;\n count: number;\n lastAt: Date | null;\n snappedCount: number;\n snappedLastAt: Date | null;\n}\n\n/**\n * L3: a SECOND `hasDiverged`, deliberately not unified with `graph/nodes\n * /act.ts`'s own — that one uses `!==` on both count and timestamp (any\n * change, either direction, since a re-send must never fire on a run that\n * has already drifted in EITHER direction); this one is faithful to the\n * legacy's own `POST /api/fast-response/check` rule (`count >`, \"strictly\n * newer\") — a same-or-earlier snapshot is not a divergence for the purpose\n * of serving an already-generated draft. `handle-approval.ts:142-143` reads\n * the same two stored fields by hand a third time, for the same reason\n * `act`'s check does (I8's re-read).\n */\nfunction checkDivergence(rawTicket: RawTicket, generatedResponse: GeneratedResponseRecord): DivergenceCheck {\n const snapshot = snapshotConversation(rawTicket);\n const snappedCount = generatedResponse.generatedMessageCount;\n const snappedLastAt = toDate(generatedResponse.generatedLastMessageAt);\n\n const divergedByCount = snapshot.count > snappedCount;\n const divergedByDate = !!snapshot.lastAt && (!snappedLastAt || snapshot.lastAt.getTime() > snappedLastAt.getTime());\n return { diverged: divergedByCount || divergedByDate, count: snapshot.count, lastAt: snapshot.lastAt, snappedCount, snappedLastAt };\n}\n\n/** `ready -> expired|invalidated`, tolerating a lost race (someone else already moved the row) — the outcome (`{available:false}`) is the same either way. */\nasync function flipStatus(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n status: Extract<GeneratedResponseStatus, 'expired' | 'invalidated'>,\n): Promise<void> {\n await transitionGeneratedResponse(ctx.api, { id, ticketId, from: 'ready', to: status });\n}\n\n/**\n * Rule 5's retry loop (see this module's own doc). Re-reads and retries on\n * a lost `ifMatch` race PROVIDED the row is still `ready` after the\n * re-read; a row that moved off `ready` — INCLUDING one an admin deleted\n * outright (L4: `getOptional`, not `api.get`, so a 404 here reads as the\n * same ordinary miss the legacy's `race_lost` names it, not an app failure\n * `fanOutSettled` would log as an anomaly) — is a genuine miss, returned as\n * `null` without a further retry.\n */\nasync function serveHit(ctx: SupportKitHandlerContext, row: AppApiRecord, userId: string, now: Date): Promise<AppApiRecord | null> {\n let current = row;\n for (let attempt = 0; attempt < MAX_SERVE_ATTEMPTS; attempt++) {\n const currentData = toGeneratedResponse(current);\n const { servedCount, servedTo } = currentData;\n const nextServedTo = servedCount < SERVED_TO_CAP ? [...servedTo, { user: userId, at: now.toISOString() }] : servedTo;\n\n try {\n // H2: CAS on the field this write actually changes (`servedCount`),\n // not `status` — the hit path never moves `status` off `ready`, so an\n // `ifMatch: {status: 'ready'}` guard would let two concurrent hits\n // both pass unconditionally (see this function's own doc, rule 5).\n return await ctx.api.update(\n 'generated-response',\n current.id,\n { servedCount: servedCount + 1, servedTo: nextServedTo },\n { ifMatch: { servedCount } },\n );\n } catch (err) {\n if (!(err instanceof AppApiError) || err.status !== 409) throw err;\n const fresh = await getOptional(ctx, 'generated-response', current.id);\n // L7: the untrusted-JSONB boundary — `isGeneratedResponseStatus`,\n // same guard `isEvaluationVerdict` applies to `verdict` a few lines\n // below, instead of a raw string compare against an unknown value.\n const freshStatus = fresh ? (fresh.data as Record<string, unknown>).status : undefined;\n if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== 'ready') return null;\n current = fresh;\n }\n }\n return null;\n}\n\nasync function buildAvailableResponse(ctx: SupportKitHandlerContext, generatedResponse: GeneratedResponseRecord): Promise<ExtFastResponseCheckResult> {\n const category = await resolveCategoryRef(ctx, generatedResponse.categoryId);\n const agent = await resolveAgentRef(ctx, generatedResponse.agentId);\n // L5: the legacy returned `served.generated_at` verbatim — no fabricated\n // \"now\" fallback. The real record declares `generatedAt` `isNullable:\n // false` (`records/generated-response.ts`), so a row reaching this point\n // without one is corrupted data, not a case to paper over: the extension\n // uses this field to show draft freshness, and silently reporting \"just\n // now\" on a possibly-stale draft is worse than a loud failure.\n const generatedAt = toDate(generatedResponse.generatedAt);\n if (!generatedAt) {\n throw new ctx.NonRetriableError(`generated-response ${generatedResponse.id} is ready but has no generatedAt`);\n }\n const verdictValue = isEvaluationVerdict(generatedResponse.verdict?.verdict) ? generatedResponse.verdict.verdict : null;\n\n return {\n available: true,\n response: generatedResponse.responseText ?? '',\n category,\n agent,\n langfuse_trace_id: generatedResponse.langfuseTraceId,\n langfuse_observation_id: generatedResponse.langfuseObservationId,\n prompt_name: generatedResponse.promptName,\n prompt_version: generatedResponse.promptVersion,\n generated_at: generatedAt.toISOString(),\n followup_required: requiresFollowup(verdictValue),\n };\n}\n\nasync function resolveCategoryRef(ctx: SupportKitHandlerContext, categoryId: string | null): Promise<{ _id: string; name: string } | null> {\n if (!categoryId) return null;\n const record = await getOptional(ctx, 'category', categoryId);\n if (!record) return null;\n const category = toCategory(record);\n return { _id: category.id, name: category.name };\n}\n\nasync function resolveAgentRef(\n ctx: SupportKitHandlerContext,\n agentId: string | null,\n): Promise<{ _id: string; name: string; model_id: string } | null> {\n if (!agentId) return null;\n const record = await getOptional(ctx, 'agent', agentId);\n if (!record) return null;\n const agent = toAgent(record);\n return { _id: agent.id, name: agent.name, model_id: agent.modelId };\n}\n","/**\n * `ext-evaluation` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-\n * routed (§S6). Ports legacy `POST /api/models/:id/evaluation`\n * (extension-overview backoffice/src/routes/api.ts:96). The gateway hands\n * this function `{...body, modelId}` (`SupportExtensionService.evaluation`\n * injects the URL's `:modelId` into the body itself), so `modelId` is\n * always present on `phase: 'execute'`.\n *\n * OWNERSHIP PROBE: `{modelId}`, `modelId` always a real value here (unlike\n * `ext-chat`, there is no \"absent modelId\" branch — the legacy route always\n * has one, from the URL). Claim iff this app owns an `agent` record with\n * that id — a read only, no write/LLM/Gorgias call.\n *\n * EXECUTE: `{satisfied, messages, ticket_url, langfuse_trace_id,\n * langfuse_observation_id, modelId}` → `201` (body ignored by the\n * extension, §5.2). `satisfied` must be a boolean (legacy 400s otherwise).\n * Writes an `evaluation` record with `agentId` = the resolved agent and\n * `supportUserKeyId` = the platform user id read off\n * `ctx.event.supportExtension` (§5.1: \"les records servedTo/évaluations\n * portent l'id utilisateur plateforme\").\n *\n * `ticketUrl` GAP (recorded, not silently routed around; L12 — DECISION\n * made explicitly, not deferred): the extension's request body treats\n * `ticket_url` as optional (legacy: `ticket_url ?? null`), but the T20\n * `evaluation` record (`records/evaluation.ts`) declares `ticketUrl` as\n * `isNullable: false` — no default, no null. Rather than reach back into a\n * frozen T20 record definition (out of this task's scope) or silently\n * attempt an `undefined`/`null` write that would fail the object's own\n * field validation, an absent/non-string `ticket_url` is persisted as an\n * empty string.\n * This is WORSE here than the same gap on `response-comparison.ticketUrl`:\n * `evaluation` has NO `ticketId` field at all (grep `records/evaluation\n * .ts` — `agentId`, `satisfied`, `messages`, `ticketUrl`, the two Langfuse\n * ids, `supportUserKeyId`; nothing else), so `ticketUrl` is this record's\n * ONLY link back to a ticket. `''` is indistinguishable from a genuinely\n * empty URL, and a later backfill has no way to tell \"never sent\" from\n * \"sent empty\". The correct fix is making the field nullable and writing\n * `null` — DECLINED here, deliberately, because it means extending a\n * record definition the spec freezes at T20 (§3.4), which is a call for\n * whoever owns that record, not a T24 function. Flagged for whoever owns\n * `records/evaluation.ts` next, with the concrete cost spelled out above\n * rather than left implicit.\n *\n * LANGFUSE SCORE: when `langfuse_trace_id` is a non-empty string, writes a\n * `user-feedback` BOOLEAN score (S4) with the legacy's deterministic id\n * `user-feedback-<traceId>` (idempotent — toggling 👍/👎 updates the same\n * score instead of creating duplicates). `comment` folds in what the\n * legacy's dataset-store `metadata` carried (`model`, `ticket_url`) — S4's\n * `ctx.api.langfuse.scores.create` has no generic `metadata` field on the\n * platform surface (`CreateLangfuseScoreInput`), only `comment`. The\n * platform user's NAME is not available off `ctx.event` (only the user\n * id), so the comment uses the id instead of the legacy's `req.user.name`.\n * Both deviations are platform-surface limits, not this function's choice.\n * The score write is wrapped and its failure SWALLOWED — legacy is\n * explicit that this block is non-fatal and the 201 is guaranteed.\n *\n * SETTINGS VALIDATION: deliberately NOT called — writing an evaluation and\n * an optional score touches none of `validateSettings`'s three checked\n * fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_EVALUATION_INPUT_MESSAGES_UID,\n EXT_EVALUATION_INPUT_MODEL_ID_UID,\n EXT_EVALUATION_INPUT_SATISFIED_UID,\n EXT_EVALUATION_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { toAgent } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nexport interface ExtEvaluationInput {\n modelId: string;\n satisfied?: unknown;\n messages?: Array<{ role: string; content: string }> | null;\n ticket_url?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n}\n\nexport interface ExtEvaluationResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtEvaluationFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-evaluation'),\n name: 'ext-evaluation',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n { universalIdentifier: EXT_EVALUATION_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: EXT_EVALUATION_INPUT_SATISFIED_UID, name: 'satisfied', type: FieldType.BOOLEAN, label: 'Satisfied', isNullable: false },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtEvaluationHandler(): AppHandler {\n return (ctx, input) => extEvaluationHandler(ctx as SupportKitHandlerContext, input as unknown as ExtEvaluationInput);\n}\n\nexport async function extEvaluationHandler(\n ctx: SupportKitHandlerContext,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return ownsAgent(ctx, input?.modelId ?? null);\n return executeEvaluation(ctx, envelope.userId, input);\n}\n\nasync function executeEvaluation(\n ctx: SupportKitHandlerContext,\n userId: string,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult> {\n if (typeof input.satisfied !== 'boolean') {\n throw new ctx.NonRetriableError('`satisfied` is a required boolean');\n }\n // L11: an empty platform user id must fail the WRITE — §5.1 requires this\n // record to carry it, and silently writing `supportUserKeyId: null`\n // drops that requirement instead of refusing.\n if (!userId) {\n throw new ctx.NonRetriableError('ext-evaluation: missing platform user id in the invocation envelope');\n }\n const modelId = input.modelId;\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n const agentRecord = await getOptional(ctx, 'agent', modelId);\n if (!agentRecord) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n const agent = toAgent(agentRecord);\n\n const satisfied = input.satisfied;\n const messages = Array.isArray(input.messages) ? input.messages : [];\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`,\n // so an absent/non-string value is persisted as an empty string, not null.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const traceId = typeof input.langfuse_trace_id === 'string' && input.langfuse_trace_id.length > 0 ? input.langfuse_trace_id : null;\n const observationId =\n typeof input.langfuse_observation_id === 'string' && input.langfuse_observation_id.length > 0\n ? input.langfuse_observation_id\n : undefined;\n\n const created = await ctx.api.create('evaluation', {\n agentId: agent.id,\n satisfied,\n messages,\n ticketUrl,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n // Non-empty: guarded above (L11).\n supportUserKeyId: userId,\n });\n\n if (traceId) {\n try {\n await ctx.api.langfuse.scores.create({\n id: `user-feedback-${traceId}`,\n traceId,\n observationId,\n name: 'user-feedback',\n value: satisfied,\n dataType: 'BOOLEAN',\n comment: `Thumbs ${satisfied ? 'up' : 'down'} from ${userId || 'agent'} (model: ${agent.name}, ticket_url: ${ticketUrl || 'none'})`,\n });\n } catch (err) {\n // Non-fatal — legacy is explicit that the 201 is guaranteed regardless.\n ctx.logger.warn(`ext-evaluation: user-feedback score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return { ok: true, id: created.id };\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 * `ext-response-comparison` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * ownership-routed (§S6). Ports legacy `POST /api/response-comparisons`\n * (extension-overview backoffice/src/routes/api.ts:404).\n *\n * The gateway already short-circuits `last_message_generated == null` to a\n * `204` BEFORE ever invoking any app, and maps a `null` return from this\n * function to `204` too (`SupportExtensionController.responseComparison`).\n * This handler keeps its OWN guard anyway (per this migration's explicit\n * instruction) — belt and braces, and it is exercised directly by this\n * file's own tests, which do not go through the gateway.\n *\n * OWNERSHIP PROBE (§S6): `model_config_id` non-empty → probe payload\n * `{model_config_id}`, claim iff this app owns that `agent` record.\n * Otherwise → probe payload `{ticket_id, ticket_url}` (§S6: \"sinon fan-out\n * sur la propriété du ticket (`triage-decision`)\") — claim iff this app has\n * a `triage-decision` row for that `ticket_id` (the ticket was triaged by\n * THIS app, i.e. it belongs to this audience). `ticket_url` plays no part\n * in the ownership check (the legacy never used it for anything but\n * display either); it only reaches the WRITE below.\n *\n * EXECUTE: `message_actual_sent` missing → 400-equivalent (legacy 400s);\n * `last_message_generated` null → the guard above. Otherwise writes a\n * `response-comparison` record (`generatedText`/`sentText`/`capturedAt`\n * plus the frozen body's other fields, and `diff` — `response-comparison-\n * diff.ts`'s `computeWordDiff`, \"computed at write time\" per §3.4), then\n * attempts the Langfuse capture.\n *\n * `ticketUrl` GAP (L12 — DECISION made explicitly, not deferred) — the SAME\n * one `ext-evaluation.ts` documents for `evaluation.ticketUrl`: the T20\n * `response-comparison` record declares `ticketUrl` `isNullable: false`,\n * but the extension's own contract treats it as optional. An absent/\n * non-string value is persisted as an empty string, not `null`. Unlike\n * `evaluation`, this record DOES have its own `ticketId` field, so `''`\n * here is not the only link back to a ticket — a strictly smaller gap.\n * Making `ticketUrl` nullable and writing `null` is still the correct fix;\n * DECLINED here for the same reason as `ext-evaluation.ts`: it means\n * extending a T20-frozen record definition (§3.4), a call for whoever owns\n * `records/response-comparison.ts`, not this function.\n *\n * LANGFUSE CAPTURE — gates, decided explicitly: legacy gated on THREE\n * conditions — `CAPTURE_CORRECTIONS_TO_LANGFUSE === 'true'` (an env flag),\n * `message_actual_sent !== last_message_generated` (`textChanged`), and a\n * non-empty trace id. The kit has NO env access (§3.1) and the migration\n * spec §5.2 does not mention this flag at all, so it is DROPPED — the\n * remaining two gates stay: `textChanged` (an unedited reply is not a\n * correction and would poison the `cs-replies-corrections` dataset with\n * noise) and a non-empty trace id (nothing to link the correction back\n * to). Practical effect: this kit ALWAYS captures a genuine edit when a\n * trace id is present, where the legacy required an operator to also\n * enable a deployment flag — a deliberate widening, not an oversight.\n *\n * Dataset item id: the legacy's own deterministic\n * `<traceId>:<observationId>` (or `<traceId>` alone with no observation).\n * SCORE id: the legacy's `createCorrectionScore` had NONE (Langfuse\n * auto-assigns one on every call) — but S4's `ctx.api.langfuse.scores\n * .create` requires an `id` (`CreateLangfuseScoreInput.id`, non-optional).\n * This function reuses the SAME deterministic dataset-item id for the\n * score, which is required by the platform surface — NOT, despite the\n * tempting name, a general idempotency guarantee (H5/L14 correction of an\n * earlier overclaim in this doc):\n * - Langfuse keys a score on `(id, name, toDate(timestamp))`, and\n * `POST /api/public/scores` has no caller-supplied timestamp — a retry\n * that crosses a UTC day boundary from the original call creates a\n * SECOND score under the same id (`AppLangfuseService.createScore`'s\n * own doc, `apps/api/src/platform-data/app-langfuse.service.ts`).\n * - Two DIFFERENT edits on the same trace within the same day reuse this\n * same id and the SECOND CORRECTION score OVERWRITES the first — the\n * legacy minted a distinct score object per edit, so this is a real\n * narrowing, not a wash.\n * Same for the dataset item: a deterministic id genuinely IS a concurrency\n * safety net for the CONCURRENT case (two callers racing on the identical\n * id — Langfuse upserts by id, so the race has a defined winner instead of\n * two rows). What it is NOT is protection for the SEQUENTIAL case: reusing\n * that same deterministic id also means a SECOND, LATER correction on the\n * same generation (an agent edits and\n * sends, then the extension re-posts the same generation on a retry, or a\n * client retries after a lost 201) silently REPLACES `expectedOutput` with\n * the newer edit — last-write-wins, not accumulated history. The legacy\n * guarded exactly this (api.ts:490-497: skip the write when a\n * `ResponseComparison` with this `langfuse_observation_id` already has a\n * `dataset_item_created_at`); this port has no such field to guard on (the\n * T20-frozen `response-comparison` record declares none) and the guard was\n * dropped, not ported. DECIDED, not silently accepted: adding\n * `datasetItemCreatedAt` would mean extending a T20-frozen record\n * definition, out of this task's scope — documenting the real behaviour\n * here (drift toward the latest edit, not a hard guarantee) is the\n * alternative the review offered, and is what this paragraph now does.\n *\n * SCORE VALUE LENGTH — UNVERIFIED, flagged rather than guessed: `value:\n * JSON.stringify(expectedOutput)` embeds the full sent reply. If Langfuse\n * caps score values at some length (a commonly-cited limit for certain\n * value/comment fields is 500 characters, but this could not be confirmed\n * from code in this repo), a real support reply could exceed it. The write\n * is swallowed non-fatally below, so an over-length value would 400 here\n * silently — the feature would look like it works while writing nothing.\n * Treat this as a pre-ship manual probe (write a >500-char correction\n * against a real/staging Langfuse project and confirm the score lands),\n * not a guarantee this doc makes.\n *\n * `traced_input` — read defensively off the raw payload for the dataset\n * item's `input`, falling back to `conversation_messages` when absent\n * (legacy's own fallback rule) — NOT part of §5.2's frozen field table, so\n * it is not declared in this function's `input` FieldDef[] (an\n * undeclared/extra key reaches the handler unstripped; see\n * `app-input-validation.ts`'s zod-strip behaviour), but the extension may\n * still send it and its value should not be silently discarded when it\n * does.\n *\n * Both Langfuse writes (dataset item, score) are wrapped and their failure\n * SWALLOWED — legacy is explicit that this block is non-fatal.\n *\n * SETTINGS VALIDATION: deliberately NOT called — none of `validateSettings`'s\n * three checked fields apply to writing a comparison/capturing a\n * correction.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { computeWordDiff } from './response-comparison-diff';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst CORRECTIONS_DATASET = 'cs-replies-corrections';\n\nexport interface ExtResponseComparisonInput {\n last_message_generated?: string | null;\n message_actual_sent?: string;\n ticket_id?: string | null;\n ticket_url?: string | null;\n model_config_id?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n prompt_name?: string | null;\n prompt_version?: number | null;\n conversation_messages?: unknown[] | null;\n /** Not part of §5.2's frozen field table — see this module's own doc. */\n traced_input?: unknown[] | null;\n}\n\nexport interface ExtResponseComparisonResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtResponseComparisonFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-response-comparison'),\n name: 'ext-response-comparison',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n name: 'last_message_generated',\n type: FieldType.TEXT,\n label: 'Last message generated',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n name: 'message_actual_sent',\n type: FieldType.TEXT,\n label: 'Message actually sent',\n isNullable: false,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n name: 'model_config_id',\n type: FieldType.TEXT,\n label: 'Model config id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n name: 'prompt_name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n name: 'prompt_version',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n name: 'conversation_messages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtResponseComparisonHandler(): AppHandler {\n return (ctx, input) => extResponseComparisonHandler(ctx as SupportKitHandlerContext, (input as ExtResponseComparisonInput) ?? {});\n}\n\nexport async function extResponseComparisonHandler(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeResponseComparisonOwnership(ctx, input);\n return executeResponseComparison(ctx, input);\n}\n\nasync function probeResponseComparisonOwnership(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ProbeClaim | null> {\n const modelConfigId = nonEmptyString(input.model_config_id);\n if (modelConfigId) {\n const claim = await ownsAgent(ctx, modelConfigId);\n if (claim) return claim;\n // M3: a dangling model_config_id (the agent was archived/deleted since\n // the draft that produced this correction) used to disclaim outright —\n // 204, the correction silently lost, with nothing to distinguish \"no\n // owner\" from \"we lost it\". Fall through to ticket ownership instead of\n // returning null immediately: the ticket itself still routes to the app\n // that triaged it, which is the better answer than losing the human\n // correction the whole cs-replies-corrections loop is built on.\n }\n\n const ticketId = nonEmptyString(input.ticket_id);\n if (!ticketId) return null;\n const page = await ctx.api.list('triage-decision', { filter: { ticketId }, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeResponseComparison(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | null> {\n if (!input.message_actual_sent) {\n throw new ctx.NonRetriableError('message_actual_sent is required');\n }\n if (!input.last_message_generated) {\n // M2: falsy, not `== null` — legacy tests `if (!last_message_generated)\n // return 204`, so an empty string must 204 too. `== null` let `''`\n // through and wrote a response-comparison with generatedText: '', a\n // trivially 100%-insert diff, and (with a trace id) a dataset item +\n // CORRECTION score teaching cs-replies-corrections that the model wrote\n // nothing and the human wrote the whole reply — dataset poisoning.\n return null; // -> 204, no write (own guard — see this module's doc)\n }\n\n const generatedText = input.last_message_generated;\n const sentText = input.message_actual_sent;\n const ticketId = nonEmptyString(input.ticket_id);\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const modelConfigId = nonEmptyString(input.model_config_id);\n const traceId = nonEmptyString(input.langfuse_trace_id);\n const observationId = nonEmptyString(input.langfuse_observation_id) ?? undefined;\n const promptName = typeof input.prompt_name === 'string' ? input.prompt_name : null;\n const promptVersion = typeof input.prompt_version === 'number' ? input.prompt_version : null;\n const conversationMessages = Array.isArray(input.conversation_messages) ? input.conversation_messages : [];\n\n const created = await ctx.api.create('response-comparison', {\n generatedText,\n sentText,\n capturedAt: new Date().toISOString(),\n ticketId,\n ticketUrl,\n agentId: modelConfigId,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n promptName,\n promptVersion,\n conversationMessages,\n diff: computeWordDiff(generatedText, sentText),\n });\n\n await captureCorrectionToLangfuse(ctx, {\n generatedText,\n sentText,\n ticketId,\n traceId,\n observationId,\n promptName,\n promptVersion,\n conversationMessages,\n tracedInput: Array.isArray(input.traced_input) ? input.traced_input : null,\n });\n\n return { ok: true, id: created.id };\n}\n\ninterface CorrectionCaptureParams {\n generatedText: string;\n sentText: string;\n ticketId: string | null;\n traceId: string | null;\n observationId: string | undefined;\n promptName: string | null;\n promptVersion: number | null;\n conversationMessages: unknown[];\n tracedInput: unknown[] | null;\n}\n\nasync function captureCorrectionToLangfuse(ctx: SupportKitHandlerContext, params: CorrectionCaptureParams): Promise<void> {\n const textChanged = params.sentText !== params.generatedText;\n if (!textChanged || !params.traceId) return;\n\n const itemId = params.observationId ? `${params.traceId}:${params.observationId}` : params.traceId;\n const expectedOutput = { role: 'assistant', content: params.sentText, refusal: null, annotations: [] as unknown[] };\n const datasetInput = params.tracedInput && params.tracedInput.length > 0 ? params.tracedInput : params.conversationMessages;\n\n try {\n await ctx.api.langfuse.datasets.createItem({\n dataset: CORRECTIONS_DATASET,\n id: itemId,\n input: datasetInput,\n expectedOutput,\n sourceTraceId: params.traceId,\n sourceObservationId: params.observationId,\n metadata: {\n prompt_name: params.promptName,\n prompt_version: params.promptVersion,\n ticket_id: params.ticketId,\n edited: true,\n },\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: dataset item write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n\n try {\n // M5: deliberately trace-level — NO `observationId`. Legacy's own\n // `createCorrectionScore` call passed none either (its doc labels this\n // \"Native trace-level CORRECTION score — renders as the 'Corrected\n // Output' on the trace itself\"); passing one here would move the panel\n // off the trace page. `CreateLangfuseScoreInput` has no generic\n // `metadata` field on the platform surface (only `comment`), so\n // prompt_name/prompt_version — the axis S7's quality loop reads\n // corrections along — fold into `comment` instead, the same way\n // `ext-evaluation.ts` folds its own score metadata.\n await ctx.api.langfuse.scores.create({\n id: itemId,\n traceId: params.traceId,\n name: 'output',\n value: JSON.stringify(expectedOutput),\n dataType: 'CORRECTION',\n comment: `Human correction from ticket ${params.ticketId ?? 'unknown'} (prompt: ${params.promptName ?? 'unknown'}, version: ${params.promptVersion ?? 'unknown'})`,\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: correction score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n","/**\n * Page/settingsPage manifest fragments (spec §3.8) — the T26 counterpart of\n * `functions/config.ts`'s `FUNCTION_IDENTIFIER_KEYS`/`identifierFor`.\n *\n * Page `universalIdentifier`s come from `config.identifiers`, exactly like\n * function uids — NOT from the T25 `deriveUid`/`scopeRecordToApp` mechanism\n * `records/` uses. That mechanism exists because a RECORD's sub-ids (fields,\n * indexes) are numerous and entirely kit-owned, with no natural per-app\n * literal for a consuming app to author; deriving them from `(slug, a kit\n * constant)` is the only way to keep them both stable and disjoint across\n * apps. A page has exactly one id, no sub-ids, and `FUNCTION_IDENTIFIER_KEYS`\n * already established the pattern for exactly this shape: the CONSUMING\n * APP's own config supplies a literal, platform-wide-unique uuid per key —\n * the same discipline `docs/app-template/src/universal-identifiers.ts`\n * documents for every other manifest id an app authors directly.\n *\n * CORRECTION (T26 rework — the prior pass's own justification here was\n * false, and is fixed rather than just removed so the actual mechanism is\n * on record): `AppEntityType.PAGE` rows do land in the same `AppEntity`\n * table as records' OBJECT/FIELD/INDEX rows\n * (`apps/api/src/platform-data/app-entities.ts`), and\n * `AppEntity.universalIdentifier` IS `@unique` platform-wide\n * (`schema.prisma`) — but PAGE, like FUNCTION/VIEW/INDEX/NAV_ITEM, is\n * NAMESPACED before that constraint ever sees it: `buildEntities` computes\n * `deterministicUid('PAGE:<manifest uid>:<page uid>')`\n * (`app-entities.ts:172-175`), not the raw `page.universalIdentifier`\n * literal. Two apps publishing the IDENTICAL local page uid produce two\n * DIFFERENT `deterministicUid` hashes (their own manifest uids differ), so\n * they do not collide — a page id does NOT \"collide across apps exactly\n * like a record id would\". Only OBJECT (`app-entities.ts:84`) and FIELD\n * (`:101`, and `:205` for extension fields) write the raw literal straight\n * through — which is precisely why T25's `scopeRecordToApp` existed for\n * records and is NOT needed here.\n *\n * The mechanism below (config-supplied literal, mirroring\n * `FUNCTION_IDENTIFIER_KEYS`) is still the right choice — consistency with\n * the pattern T22/T23 already established for exactly this shape (one id,\n * no sub-ids, no natural per-app literal to derive from) — it is simply not\n * required by a collision risk that does not exist for this entity type.\n */\n\n/**\n * Stable keys `pageIdentifierFor` looks up `config.identifiers` by — the\n * four phase-2 pages (T26), the settingsPage (§3.8's SettingsPage row),\n * T27 part A's three phase-3 pages (`DashboardPage`, `TicketsPage`,\n * `CorrectionsPage`), part B's `GraphCanvasPage`/`SharedPromptsPage`/\n * `TestPage`, and `QualityPage` — the quality loop, moved here out of the\n * platform's own top-bar section.\n *\n * `reglages-page` is the odd one out: it needs its own id NOT because it is a\n * distinct screen — it mounts the very same `SettingsPage` component — but\n * because a `pages[]` entry and `settingsPage` are two manifest rows, and the\n * schema refuses a shared `universalIdentifier` between them\n * (`app-kit/src/contracts.ts`, `settingsPage.universalIdentifier collides`).\n */\nexport const PAGE_IDENTIFIER_KEYS = [\n 'agents-page',\n 'categories-page',\n 'settings-page',\n 'reglages-page',\n 'dashboard-page',\n 'tickets-page',\n 'graph-canvas-page',\n 'shared-prompts-page',\n 'test-page',\n 'quality-page',\n] as const;\n\nexport type PageIdentifierKey = (typeof PAGE_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitPageConfig {\n /** Same map `functions/config.ts`'s `identifierFor` reads — one entry per `PAGE_IDENTIFIER_KEYS`, alongside the function ones. */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry — mirrors `functions/config.ts`'s `identifierFor` exactly. */\nexport function pageIdentifierFor(config: SupportKitPageConfig, key: PageIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportPipelineConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit page needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * `buildSupportPipeline` (spec §3.2) — the single assembly point that turns\n * a consuming app's own config into every manifest fragment + handler this\n * kit provides. An audience app spreads the result into `defineApp({\n * manifest: {...baseManifest, ...kit-fragments}, handlers: kit.handlers })`.\n *\n * T25 is assembly, not invention: every fragment below is built from pieces\n * T20-T24 already shipped (`records/`, `functions/`, `settings/`,\n * `prompts/slots`) — this module's own job is wiring `config` through to\n * each of them consistently, plus `mergeRole`, the one piece with no prior\n * owner.\n */\nimport type {\n AppHandler,\n AppRole,\n AppSettings,\n FunctionDef,\n NavItem,\n PageDef,\n PromptDef,\n SettingsPage,\n} from '@apotech-os/app-kit';\nimport {\n FUNCTION_IDENTIFIER_KEYS,\n type FunctionIdentifierKey,\n type SupportKitFunctionConfig,\n} from './functions/config';\nimport {\n buildTriageTickFunctionDef,\n createTriageTickHandler,\n buildSweepFunctionDef,\n createSweepHandler,\n buildHandleApprovalFunctionDef,\n createHandleApprovalHandler,\n buildRunTriageNowFunctionDef,\n createRunTriageNowHandler,\n buildRunTriageBatchFunctionDef,\n createRunTriageBatchHandler,\n TRIAGE_RUN_REQUESTED_EVENT,\n buildInvalidateResponseFunctionDef,\n createInvalidateResponseHandler,\n buildGetTicketConversationFunctionDef,\n buildPreviewTriageFunctionDef,\n createGetTicketConversationHandler,\n createPreviewTriageHandler,\n buildGraphDryRunFunctionDef,\n createGraphDryRunHandler,\n buildTestAgentsFunctionDef,\n createTestAgentsHandler,\n buildSuggestPromptFunctionDef,\n createSuggestPromptHandler,\n buildListGorgiasViewsFunctionDef,\n createListGorgiasViewsHandler,\n buildCreateAgentFunctionDef,\n createCreateAgentHandler,\n buildSetDefaultAgentFunctionDef,\n createSetDefaultAgentHandler,\n buildCreateSharedPromptVersionFunctionDef,\n createCreateSharedPromptVersionHandler,\n buildSyncAgentPromptSnapshotFunctionDef,\n createSyncAgentPromptSnapshotHandler,\n buildExtModelsFunctionDef,\n createExtModelsHandler,\n buildExtCategoriesFunctionDef,\n createExtCategoriesHandler,\n buildExtChatFunctionDef,\n createExtChatHandler,\n buildExtFastResponseCheckFunctionDef,\n createExtFastResponseCheckHandler,\n buildExtEvaluationFunctionDef,\n createExtEvaluationHandler,\n buildExtResponseComparisonFunctionDef,\n createExtResponseComparisonHandler,\n} from './functions';\nimport { buildSupportKitRecords, targetRefFor, type RecordDef } from './records';\nimport { SUPPORT_KIT_SETTINGS_FIELDS } from './settings';\nimport type { PromptNameConfig } from './prompts/slots';\nimport { pageIdentifierFor } from './pages/manifest';\n\nexport interface SupportPipelineConfig extends SupportKitFunctionConfig {\n /** Human label shown in the platform's app picker, e.g. 'Expérience client'. */\n displayName: string;\n /**\n * §3.2's own sketch names this field, but has no consumer yet (L1, T25\n * review): `navigation` (this fragment's own `NavItem[]`) is always `[]`\n * today — T26/T27 own the kit's pages/nav (§3.8's phase-2/phase-3), and\n * with it, presumably, grouping those nav items under this section. A\n * caller may set it now for forward compatibility; nothing reads it yet.\n */\n navigationSection?: string;\n /**\n * §3.2's full `config.defaults` shape (`{channel?, prompts?}`), widening\n * `SupportKitFunctionConfig`'s own `defaults` (`{prompts?}` only) with\n * `channel` — `prompts`' shape is NOT restated here (L2, T25 review): it\n * is `PromptNameConfig['defaults']`'s own type, `prompts/slots.ts`'s\n * `PromptFallbackSlot`, referenced rather than copied, so this\n * declaration cannot silently narrow back to the wrong key set if that\n * one changes.\n *\n * `defaults.prompts` is wired to its real consumers: `buildPromptsTable`\n * (triage/escalate/evaluate's `PromptRef.fallback`) and\n * `suggest-prompt`/`run-diff-analysis`'s own meta-prompt fallback.\n *\n * `defaults.channel` (DECISION 3, T25 — see the migration progress\n * journal's T25 entry) is accepted here for fidelity to the spec's own\n * sketch but has NO real consumer today: `settings/fields.ts` declares no\n * field named `channel`, and the nearest candidate, `whatsappMode`\n * (`escalate_only|draft_only|auto_reply`), has an incompatible value\n * domain from `'email'|'whatsapp'|'both'` — a mechanical seed would\n * corrupt it, not configure it. Wiring this for real means either adding\n * a settings field (§3.6 is T20-frozen; out of scope here) or picking an\n * arbitrary channel→whatsappMode mapping, both judgment calls beyond\n * assembly. Flagged for the spec owner, not routed around silently.\n */\n defaults?: PromptNameConfig['defaults'] & {\n channel?: 'email' | 'whatsapp' | 'both';\n };\n}\n\n/** `provider`/`action` pair. 4.0.0 — plus aucun manifest ne le porte ; gardé\n * pour la garde de dérive qui re-dérive les appels `ctx.api.integrations.run`\n * du code source (cf. `SUPPORT_KIT_GORGIAS_ACTIONS`). */\nexport interface ActionRef {\n provider: string;\n action: string;\n}\n\n/** Un bloc de `manifest.integrations[]` — provider + scopes de ressource. */\nexport interface IntegrationRef {\n provider: string;\n scopes: string[];\n}\n\nexport interface SupportPipelineFragments {\n records: RecordDef[];\n functions: FunctionDef[];\n /**\n * The app custom events the kit's own functions emit — spread into\n * `manifest.emits`. NOT optional in practice (B5): `run-triage-batch`\n * declares `trigger: {type:'event', name: TRIAGE_RUN_REQUESTED_EVENT}`,\n * and the platform refuses to sync a manifest whose event trigger names\n * an event the app does not declare\n * (`app-manifest-constraints.ts`'s `validateAppFunctionConstraints`), so\n * a consuming app that spreads `functions` must spread this too.\n */\n emits: string[];\n settings: AppSettings;\n prompts: PromptDef[];\n pages: PageDef[];\n navigation: NavItem[];\n /**\n * §3.8's SettingsPage row — the manifest's `settingsPage`, not a\n * `pages[]` entry (`AppManifestSchema`'s own refinements require it:\n * distinct `entry` from every page, no collision with the bundle the CLI\n * emits for a page `path`, distinct `universalIdentifier`). Not in §3.2's\n * own fragment sketch (T25's `pages`/`navigation` sketch predates T26) —\n * added here because a consuming app has no other way to spread it into\n * its manifest.\n */\n settingsPage: SettingsPage;\n /**\n * 4.0.0 — remplace le fragment `actions`. Les scopes de RESSOURCE dont les\n * adaptateurs du kit ont besoin chez Gorgias, à spread dans\n * `manifest.integrations`.\n */\n integrations: IntegrationRef[];\n /**\n * `'NO_ACCESS'` (H2, T25 review): with no `defaultRole`, the platform\n * grants every platform member `VIEWER` on install\n * (`app-lifecycle.service.ts:1211`) — a `pro-sante` clinician would read\n * `experience-client`'s `generated-response` rows (customer email bodies,\n * drafted replies) by default. Exposed as a named fragment, not baked\n * silently into a spread, so a consuming app can still override it\n * explicitly (`defaultRole: kit.defaultRole` in the common case, or a\n * different value if that app has a real reason to).\n */\n defaultRole: 'NO_ACCESS';\n handlers: Record<string, AppHandler>;\n mergeRole(role: AppRole): AppRole;\n /**\n * 4.0.0 — remplace `mergeActions`. Fond les scopes du kit dans les\n * `integrations[]` de l'app appelante, en dédupliquant par provider et en\n * unionnant les scopes : `integrations: kit.mergeIntegrations(ownIntegrations)`.\n *\n * L'union est la bonne opération, pas le remplacement : une app qui déclare\n * déjà `read_tickets` pour son propre usage ne doit pas le perdre parce que le\n * kit déclare `write_tickets`. Et la déclaration reste une DEMANDE — c'est un\n * admin qui accorde, à l'install.\n */\n mergeIntegrations(integrations: IntegrationRef[]): IntegrationRef[];\n}\n\n/**\n * The ten Gorgias connector actions the kit's adapters/functions actually\n * call — verified by grepping `ctx.api.integrations.run('gorgias', …)`\n * across `src/` (see `pipeline.spec.ts`'s own self-checking test, which\n * re-derives this set from the source tree so it cannot silently drift as\n * new call sites are added).\n */\nexport const SUPPORT_KIT_GORGIAS_ACTIONS = [\n 'applyTags',\n 'buildTicketContext',\n 'fetchTicketsFromView',\n 'getRawTicket',\n 'getTicketUrlBase',\n 'getTicketWithContext',\n 'listViews',\n 'postWhatsappNote',\n 'renameTicket',\n 'replyEmail',\n] as const;\n\n/**\n * §3.2: `mergeRole` adds these capabilities. `'langfuse'` is load-bearing —\n * `adapters/api.ts`'s `ctx.api.langfuse` 403s without it (T24).\n *\n * 4.0.0 — `'llm'` joins the list: the LLM left the action system entirely, so\n * what used to be `role.actions: [{ provider: 'llm', action: 'complete' }]` is\n * now a capability. Forgetting it would 403 every `ctx.api.llm.complete` the\n * kit's own triage functions make.\n */\nexport const SUPPORT_KIT_CAPABILITIES = [\n 'runs',\n 'inbox',\n 'approvals',\n 'prompts',\n 'langfuse',\n 'llm',\n] as const;\n\n/**\n * The kit's whole action surface — `SUPPORT_KIT_GORGIAS_ACTIONS` plus\n * `llm.complete` — as `ActionRef`s. One derivation, reused by\n * `buildSupportPipeline`'s own `actions` fragment, `mergeRole`, and\n * `mergeActions` (M5, T25 review): before this constant existed, the same\n * `[...SUPPORT_KIT_GORGIAS_ACTIONS.map(...), {provider:'llm',action:'complete'}]`\n * expression was written out twice, free to drift apart silently.\n */\nexport const SUPPORT_KIT_ACTIONS: ActionRef[] = [\n ...SUPPORT_KIT_GORGIAS_ACTIONS.map((action) => ({ provider: 'gorgias', action })),\n { provider: 'llm', action: 'complete' },\n];\n\n/**\n * 4.0.0 — les SCOPES Gorgias que les dix actions ci-dessus exigent, réunis.\n *\n * Écrit à la main plutôt que dérivé de `gorgias-client` : le support-kit est\n * publié sur npm et consommé par des dépôts d'app autonomes, à qui on ne va pas\n * imposer une dépendance sur un paquet de connecteur privé pour lire une liste\n * de six chaînes. La garde de dérive reste `pipeline.spec.ts`, qui compare ce\n * jeu à celui des actions effectivement appelées dans `src/`.\n *\n * `read_tags` n'est pas listé : `write_tags` l'implique côté plateforme\n * (`expandScopes`), et le répéter ici ferait croire à deux demandes distinctes\n * dans la modale de consentement.\n */\nexport const SUPPORT_KIT_GORGIAS_SCOPES = [\n 'read_customers',\n 'read_tickets',\n 'read_views',\n 'write_tags',\n 'write_tickets',\n] as const;\n\n/** Le fragment `integrations[]` du kit — un seul provider, Gorgias. */\nexport const SUPPORT_KIT_INTEGRATIONS: IntegrationRef[] = [\n { provider: 'gorgias', scopes: [...SUPPORT_KIT_GORGIAS_SCOPES] },\n];\n\n/**\n * §3.2's `emits` fragment — one entry, the manual-triage hand-off\n * (`functions/run-triage-now.ts`'s own doc explains why that hand-off\n * exists at all).\n */\nexport const SUPPORT_KIT_EMITS: string[] = [TRIAGE_RUN_REQUESTED_EVENT];\n\nconst FUNCTION_ASSEMBLY: ReadonlyArray<{\n key: FunctionIdentifierKey;\n build: (config: SupportKitFunctionConfig) => FunctionDef;\n createHandler: (config: SupportKitFunctionConfig) => AppHandler;\n}> = [\n { key: 'triage-tick', build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },\n { key: 'sweep', build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },\n {\n key: 'handle-approval',\n build: buildHandleApprovalFunctionDef,\n createHandler: createHandleApprovalHandler,\n },\n {\n key: 'run-triage-now',\n build: buildRunTriageNowFunctionDef,\n createHandler: createRunTriageNowHandler,\n },\n {\n key: 'run-triage-batch',\n build: buildRunTriageBatchFunctionDef,\n createHandler: createRunTriageBatchHandler,\n },\n {\n key: 'invalidate-response',\n build: buildInvalidateResponseFunctionDef,\n createHandler: () => createInvalidateResponseHandler(),\n },\n {\n key: 'preview-triage',\n build: buildPreviewTriageFunctionDef,\n createHandler: createPreviewTriageHandler,\n },\n {\n key: 'get-ticket-conversation',\n build: buildGetTicketConversationFunctionDef,\n createHandler: () => createGetTicketConversationHandler(),\n },\n {\n key: 'graph-dry-run',\n build: buildGraphDryRunFunctionDef,\n createHandler: createGraphDryRunHandler,\n },\n { key: 'test-agents', build: buildTestAgentsFunctionDef, createHandler: createTestAgentsHandler },\n {\n key: 'suggest-prompt',\n build: buildSuggestPromptFunctionDef,\n createHandler: createSuggestPromptHandler,\n },\n {\n key: 'list-gorgias-views',\n build: buildListGorgiasViewsFunctionDef,\n createHandler: createListGorgiasViewsHandler,\n },\n {\n key: 'create-agent',\n build: buildCreateAgentFunctionDef,\n createHandler: () => createCreateAgentHandler(),\n },\n {\n key: 'set-default-agent',\n build: buildSetDefaultAgentFunctionDef,\n createHandler: () => createSetDefaultAgentHandler(),\n },\n {\n key: 'create-shared-prompt-version',\n build: buildCreateSharedPromptVersionFunctionDef,\n createHandler: () => createCreateSharedPromptVersionHandler(),\n },\n {\n key: 'sync-agent-prompt-snapshot',\n build: buildSyncAgentPromptSnapshotFunctionDef,\n createHandler: () => createSyncAgentPromptSnapshotHandler(),\n },\n {\n key: 'ext-models',\n build: buildExtModelsFunctionDef,\n createHandler: () => createExtModelsHandler(),\n },\n {\n key: 'ext-categories',\n build: buildExtCategoriesFunctionDef,\n createHandler: () => createExtCategoriesHandler(),\n },\n { key: 'ext-chat', build: buildExtChatFunctionDef, createHandler: () => createExtChatHandler() },\n {\n key: 'ext-fast-response-check',\n build: buildExtFastResponseCheckFunctionDef,\n createHandler: () => createExtFastResponseCheckHandler(),\n },\n {\n key: 'ext-evaluation',\n build: buildExtEvaluationFunctionDef,\n createHandler: () => createExtEvaluationHandler(),\n },\n {\n key: 'ext-response-comparison',\n build: buildExtResponseComparisonFunctionDef,\n createHandler: () => createExtResponseComparisonHandler(),\n },\n];\n\n// FUNCTION_ASSEMBLY must cover exactly FUNCTION_IDENTIFIER_KEYS — asserted\n// in pipeline.spec.ts, not re-asserted here (a compile-time array literal\n// has no length check to attach).\n\n/**\n * §3.7's `role.prompts` allowlist: the WHOLE Langfuse project, deliberately.\n *\n * Two narrowings preceded this one, and both failed the same way. First the\n * five derived slot names (`<prefix>triage`, …) — which stopped making sense\n * the day each graph step's prompt became an operator's choice\n * (`nodes.<step>.prompt`, picked on the SettingsPage from the catalogue THIS\n * allowlist filters): a choice restricted to the names that used to be\n * hardcoded is not a choice. Then `${promptPrefix}*` — bounded for a\n * prefixed audience, but `experience-client` passes `promptPrefix: ''`\n * (D-LF: one shared project, bare legacy names), so its glob was already the\n * whole project, while a `pro-sante/` install could not reach a single\n * prompt outside its own prefix.\n *\n * OWNER DECISION (09/09/2026): no limitation. An operator configuring a\n * pipeline must see every prompt of the project in the picker, whichever\n * audience the app serves. A prefix is a naming convention here, not a\n * tenancy boundary — under D-LF there is no per-app Langfuse namespace to\n * enforce one against, and `agent/*` had been unbounded from the start\n * anyway.\n *\n * WHAT THIS COSTS, stated rather than buried: `role.prompts` gates WRITES\n * too (`app-prompts.controller.ts`'s `requirePromptAllowed` on\n * `createVersion`/`promote`/`deleteVersion`). One audience's app token can\n * therefore read AND version-write another audience's prompts. That was\n * already true of every `agent/<id>` prompt (T25 review H1, accepted); it is\n * now true of all of them. The mitigation NOT taken remains a real per-app\n * Langfuse namespace, which contradicts D-LF and is a migration, not a flag.\n */\nfunction buildPromptsAllowlist(): string[] {\n return ['*'];\n}\n\nfunction dedupe<T>(items: readonly T[], keyOf: (item: T) => string): T[] {\n const seen = new Map<string, T>();\n for (const item of items) seen.set(keyOf(item), item);\n return [...seen.values()];\n}\n\n/**\n * Union par provider : les scopes de l'app et ceux du kit se cumulent, ils ne\n * se remplacent pas. Trié pour que deux appels successifs rendent exactement le\n * même tableau — le manifest est checksummé, un ordre instable le ferait varier\n * sans qu'une ligne ait bougé.\n */\nfunction mergeIntegrationRefs(integrations: readonly IntegrationRef[]): IntegrationRef[] {\n const byProvider = new Map<string, Set<string>>();\n for (const entry of [...integrations, ...SUPPORT_KIT_INTEGRATIONS]) {\n const scopes = byProvider.get(entry.provider) ?? new Set<string>();\n for (const scope of entry.scopes) scopes.add(scope);\n byProvider.set(entry.provider, scopes);\n }\n return [...byProvider.entries()]\n .map(([provider, scopes]) => ({ provider, scopes: [...scopes].sort() }))\n .sort((a, b) => a.provider.localeCompare(b.provider));\n}\n\n/**\n * `category`/`category-group` are the categorisation referential: every call\n * site in `src/` only ever `list`s or `get`s them (verified by grep, M2 in\n * the T25 review) — never `create`/`update`/`upsert`/`delete`. Granting\n * `writes` on them anyway lets the app's own token DELETE them, taking\n * triage offline for the whole audience.\n *\n * `agent` was in this list too until the T26 rework: `create-agent` and\n * `set-default-agent` (BLOCKER 3, BLOCKER 4) now `create`/`update` it from\n * inside a handler, via this same `ctx.api` — AgentsPage cannot assign a new\n * agent's `promptName` or maintain the \"at most one default agent\" invariant\n * from raw, unauthenticated-for-writes record PATCHes alone. `role.writes`\n * has no finer grain than \"create/update/delete\" as one bucket\n * (`SupportKitApi` itself exposes no `delete` method, but a raw app token\n * still could reach the generic records DELETE route with this grant) — this\n * IS a widened blast radius versus the prior read-only grant, accepted\n * because the alternative is an agent CRUD screen that cannot create or\n * promote an agent at all. Flagged for the spec owner, not routed around\n * silently.\n */\nconst KIT_READ_ONLY_OBJECT_KEYS = ['category', 'category-group'];\n\n/**\n * `evaluation`/`diff-analysis` are written (`create`/`upsert`) but never\n * `list`ed or `get`-ed anywhere in `src/` (M2) — the mirror over-grant of\n * `KIT_READ_ONLY_OBJECT_KEYS` above.\n */\nconst KIT_WRITE_ONLY_OBJECT_KEYS = ['evaluation', 'diff-analysis'];\n\nfunction buildMergeRole(config: SupportPipelineConfig): (role: AppRole) => AppRole {\n const kitRecords = buildSupportKitRecords(config.slug);\n const refsExcluding = (excludedObjectKeys: readonly string[]): string[] =>\n kitRecords\n .filter((record) => !excludedObjectKeys.includes(record.objectKey))\n .map((record) => targetRefFor(config.slug, record.objectKey));\n const kitReadRefs = refsExcluding(KIT_WRITE_ONLY_OBJECT_KEYS);\n const kitWriteRefs = refsExcluding(KIT_READ_ONLY_OBJECT_KEYS);\n const kitPrompts = buildPromptsAllowlist();\n\n return (role: AppRole): AppRole => ({\n ...role,\n reads: dedupe([...role.reads, ...kitReadRefs], (ref) => ref),\n writes: dedupe([...role.writes, ...kitWriteRefs], (ref) => ref),\n capabilities: dedupe([...(role.capabilities ?? []), ...SUPPORT_KIT_CAPABILITIES], (c) => c),\n prompts: dedupe([...(role.prompts ?? []), ...kitPrompts], (p) => p),\n });\n}\n\n/**\n * §3.8's phase-2 pages (T26) plus T27 part A's three phase-3 pages\n * (`DashboardPage`, `TicketsPage`, `CorrectionsPage`) plus part B's\n * `GraphCanvasPage`/`SharedPromptsPage`/`TestPage` — §3.8's full page list,\n * now complete. `path` doubles as the CLI's bundle-derivation input\n * (`dist/ui/<path>.js`, `UI_ENTRY_REGEX`) and the component name exported\n * from `src/ui/index.ts` — kept in that 1:1 correspondence by `T26`'s own\n * build-then-verify step, not enforced by a type here (`PageDefSchema`\n * only constrains shape).\n */\nconst KIT_PAGES = [\n { key: 'dashboard-page', path: 'dashboard', title: 'Tableau de bord', icon: 'layout-dashboard' },\n { key: 'tickets-page', path: 'tickets', title: 'Tickets', icon: 'inbox' },\n { key: 'agents-page', path: 'agents', title: 'Agents', icon: 'bot' },\n { key: 'categories-page', path: 'categories', title: 'Catégories', icon: 'tags' },\n { key: 'graph-canvas-page', path: 'graph-canvas', title: 'Graphe', icon: 'workflow' },\n {\n key: 'shared-prompts-page',\n path: 'shared-prompts',\n title: 'Prompts partagés',\n icon: 'library',\n },\n { key: 'test-page', path: 'test', title: 'Banc de test', icon: 'flask-conical' },\n { key: 'quality-page', path: 'quality', title: 'Qualité', icon: 'flask-conical' },\n // The SAME screen as `settingsPage`, declared a second time as an app page.\n // Not a gratuitous duplicate: `getAvailableTargets()`\n // (`apps/api/src/platform-data/spaces.service.ts`) enumerates only\n // views/pages/records, so a `settingsPage` can be mounted in NO Space — by\n // construction (docs/app-platform/app-settings-page-spec.md §2). A `pages[]`\n // entry can. Both surfaces mount the same component, which reads and writes\n // through `useAppSettings()`; that store is keyed by the app slug, so there\n // is ONE `AppSetting` row behind the two, never two copies to reconcile.\n //\n // The path cannot be 'settings': the CLI would derive `dist/ui/settings.js`\n // from it — the entry `settingsPage` already claims — and the manifest would\n // be rejected (app-kit `contracts.ts`, \"collides with the bundle the CLI\n // emits for a pages[] path\").\n { key: 'reglages-page', path: 'reglages', title: 'Réglages', icon: 'settings' },\n] as const;\n\nfunction buildPages(config: SupportPipelineConfig): PageDef[] {\n return KIT_PAGES.map(({ key, path, title, icon }) => ({\n universalIdentifier: pageIdentifierFor(config, key),\n path,\n title,\n icon,\n entry: `dist/ui/${path}.js`,\n }));\n}\n\nfunction buildNavigation(config: SupportPipelineConfig): NavItem[] {\n return KIT_PAGES.map(({ path, title, icon }) => ({\n label: title,\n path,\n icon,\n ...(config.navigationSection !== undefined ? { section: config.navigationSection } : {}),\n }));\n}\n\nfunction buildSettingsPage(config: SupportPipelineConfig): SettingsPage {\n return {\n universalIdentifier: pageIdentifierFor(config, 'settings-page'),\n entry: 'dist/ui/settings.js',\n title: 'Paramètres',\n };\n}\n\nexport function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments {\n const functions = FUNCTION_ASSEMBLY.map(({ build }) => build(config));\n const handlers: Record<string, AppHandler> = {};\n for (const { key, createHandler } of FUNCTION_ASSEMBLY) handlers[key] = createHandler(config);\n\n return {\n records: buildSupportKitRecords(config.slug),\n functions,\n settings: { fields: SUPPORT_KIT_SETTINGS_FIELDS },\n // DECISION 1 (see docs/plans/2026-09-02-gorgias-migration-progress.md's\n // T25 entry): always empty. §3.2's own fragment sketch types this\n // `PromptDef[] // seed Langfuse (§3.7)`, but §3.7 line 322 and D-LF both\n // say manifest.prompts[] is NOT used by the kit — it would seed an\n // `apps/<slug>/…` namespace that contradicts \"same Langfuse project,\n // bare legacy names, zero write at migration time\". A new audience's\n // prompts are seeded at first run via S3 createVersion (a RUNTIME\n // concern), not declared in the manifest.\n prompts: [],\n // T26 fills the four phase-2 pages + the settingsPage (§3.8); T27 part A\n // adds DashboardPage/TicketsPage/CorrectionsPage. Part B's remaining\n // phase-3 pages (GraphCanvasPage, SharedPromptsPage, TestPage) are still ahead.\n pages: buildPages(config),\n navigation: buildNavigation(config),\n settingsPage: buildSettingsPage(config),\n integrations: SUPPORT_KIT_INTEGRATIONS,\n emits: SUPPORT_KIT_EMITS,\n defaultRole: 'NO_ACCESS',\n handlers,\n mergeRole: buildMergeRole(config),\n mergeIntegrations: mergeIntegrationRefs,\n };\n}\n"]}
|