@happyvertical/smrt-support 0.39.4 → 0.39.7

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.
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-07-12T01:27:41.578Z",
3
+ "generatedAt": "2026-07-12T16:59:09.211Z",
4
4
  "packageName": "@happyvertical/smrt-support",
5
- "packageVersion": "0.39.4",
5
+ "packageVersion": "0.39.7",
6
6
  "sourceManifestPath": "dist/manifest.json",
7
7
  "agentDocPath": "AGENTS.md",
8
8
  "sourceHashes": {
9
- "manifest": "25a4cce79d3d95f05e0616f3de846de906171dae8acda41ce0f381e68a5660b0",
10
- "packageJson": "98e7acfb01ecd4241801481ee5ebc5d7766788b4ab88b7003a61207e6c78b483",
11
- "agents": "7fa08df9e553d6f53e4c650e8fdcdffabfb8fb12ca7ce91a368955c85de24148"
9
+ "manifest": "5a7a7ac49f8b2c356a9eb2d36b54caf17fcd4ac0478bf3b3aa12b7cfbccb7de6",
10
+ "packageJson": "bf95dbe8b2e23122a79c8f7d6ba7d8b648bba36808504bb6ba14719a69eb69a6",
11
+ "agents": "3e834b4860801f2647b32bb1bc2169373a9715a946338895426461ff16b646d3"
12
12
  },
13
13
  "exports": [
14
14
  ".",
@@ -22,6 +22,7 @@
22
22
  "@happyvertical/smrt-core": "workspace:*",
23
23
  "@happyvertical/smrt-jobs": "workspace:*",
24
24
  "@happyvertical/smrt-messages": "workspace:*",
25
+ "@happyvertical/smrt-projects": "workspace:*",
25
26
  "@happyvertical/smrt-tenancy": "workspace:*",
26
27
  "@happyvertical/smrt-ui": "workspace:*",
27
28
  "@happyvertical/smrt-users": "workspace:*",
@@ -41,6 +42,7 @@
41
42
  "@happyvertical/smrt-core",
42
43
  "@happyvertical/smrt-jobs",
43
44
  "@happyvertical/smrt-messages",
45
+ "@happyvertical/smrt-projects",
44
46
  "@happyvertical/smrt-tenancy",
45
47
  "@happyvertical/smrt-ui",
46
48
  "@happyvertical/smrt-users",
@@ -59,7 +61,7 @@
59
61
  "collection": "servicetimeentries",
60
62
  "tableName": "service_time_entries",
61
63
  "packageName": "@happyvertical/smrt-support",
62
- "extends": "SmrtObject",
64
+ "extends": "ServiceTimeEntry",
63
65
  "fields": [
64
66
  {
65
67
  "name": "tenantId",
@@ -270,15 +272,7 @@
270
272
  "columnType": "UUID"
271
273
  }
272
274
  ],
273
- "methods": [
274
- "durationHours",
275
- "getEvidence",
276
- "getMetadata",
277
- "initialize",
278
- "save",
279
- "setEvidence",
280
- "setMetadata"
281
- ],
275
+ "methods": [],
282
276
  "surfaces": [
283
277
  {
284
278
  "kind": "api",
@@ -4238,5 +4232,5 @@
4238
4232
  "polymorphicAssociations": 0,
4239
4233
  "uuidColumns": 92
4240
4234
  },
4241
- "agentDoc": "# @happyvertical/smrt-support\n\nAI-first Support Cases for the SMRT framework (epic #1934). Every inbound\nsupport interaction — chat message or email — creates or joins one canonical,\ntenant-scoped **Support Case**; channels stay transports, never separate\nsystems of record. The package owns the case lifecycle, channel intake, the\nAutomated Support Response workflow with lossless **Human Handoff**,\nProject-qualified routing, **Service Target** clocks with timed escalation,\nand auditable **Service Time Entries** whose client charges and provider\ncompensation stay separate.\n\n**Boundary (FR-29a):** Support owns tickets, interactions, routing, and\nservice targets. Delivery Operations owns repository work — a **Delivery\nHandoff** links a case to a Development Work Item (e.g.\n`@happyvertical/smrt-projects:Issue`) via a `SupportWorkLink` without ever\ndriving its execution; the delivery side reports status echoes back.\n\n## Models\n\nCase-side models are **internal**: generated API/CLI/MCP surfaces are\nread-only (`list`/`get`) and every write goes through the service facades\n(the `smrt-chat` `ChatService` idiom). Operational configuration models\n(bindings, policies, specialists, qualifications, availability) expose full\ngenerated CRUD; **commercial terms** (`SupportPlan`,\n`SupportCompensationPlan`) are read-only too — their writes flow through the\n`support.manage-plans`-gated `SupportPlanAdminService`.\n\n### Case core (#1926)\n\n- **SupportCase** (`support_cases`) — canonical ticket: `caseNumber`,\n `subject`, `status` (`new → triaged → assigned → in_progress →\n waiting_on_client|escalated → resolved → closed`, guarded at save time via\n the WeakMap + authoritative-DB-read idiom from S5 #1390), `priority`,\n `severity` (plan-defined key), `category`, `sensitive`, `channelKind`,\n `clientProfileId`/`openedByProfileId` (crossPackageRef → Profile),\n `projectId` (app-defined string — deliberately not an FK), `bindingId`,\n `threadKey` (create-or-join dedup key), `planId` + `planSnapshot` (terms\n frozen at apply time), assignment fields, response stamps\n (`acknowledgedAt`, `firstRespondedAt`), `humanRequestedAt`, resolution\n fields, `reopenCount`/`lastReopenedAt`, `aiEnabled`.\n- **SupportInteraction** (`support_interactions`,\n `conflictColumns: ['source_key']`) — channel-neutral transport record:\n `direction` (`inbound`/`outbound`/`internal`), `channelKind`, `actorKind`\n (`client`/`specialist`/`agent`/`system`), denormalized `body`, and the\n qualified `sourceType`/`sourceId` + globally unique `sourceKey`\n (`chat:<messageId>`, `email:<emailId>`, `manual:<uuid>`) that makes\n re-ingestion idempotent.\n- **SupportCaseEvent** (`support_case_events`) — append-only audit trail\n (transitions, assignments, AI runs, handoffs, escalations, target state,\n work links, reopens). Together with interactions this is the complete\n context a Human Handoff transfers.\n- **SupportChannelBinding** (`support_channel_bindings`,\n `conflictColumns: ['target_type','target_id']`) — marks a container as a\n support intake channel: `bindingKind` (`chat_room`/`email_account`),\n qualified `targetType` + `targetId`, default client/project/plan,\n `selfAddresses` (email direction heuristic). Unbound containers are never\n touched.\n- **SupportWorkLink** (`support_work_links`) — Support/Development Work Item\n links with a read-only `status` echo.\n\n### AI workflow (#1928)\n\n- **SupportPolicy** (`support_policies`) — what the AI may do without a\n human: `autoAcknowledge`/`autoClassify`/`autoAnswer` (on by default),\n `autoTroubleshoot`/`autoResolve` (off by default),\n `autoResolveMaxSeverity`, `confidenceThreshold`, `maxAutoAttempts`,\n `sensitiveCategories`, `allowedTools`, `autoSendEmailReplies` (off —\n email replies are drafted, not sent). Resolution is most-specific-wins on\n `(planId, projectId)`; no row → `DEFAULT_SUPPORT_POLICY` (conservative).\n- **SupportAiRun** (`support_ai_runs`) — append-only audit of each phase\n (`acknowledge`/`classify`/`answer`/`troubleshoot`/`resolve`) with\n `confidence`, classification output, knowledge refs, tool calls, outcome\n (`completed`/`skipped`/`failed`/`handed_off`), and `correlationId`.\n\n### Routing, targets, escalation (#1929)\n\n- **SupportSpecialist** (`support_specialists`) — specialist role record on a\n Profile (the commerce `Customer` role-record idiom): `languages`,\n `timezone`, `maxConcurrentCases`, `onCallPriority`, status.\n- **SupportQualification** (`support_qualifications`) — effective-dated\n Project Support Qualification (`trainee`/`qualified`/`expert`).\n- **SupportAvailability** (`support_availability_windows`) — weekly windows\n plus `on_call`/`time_off` spans.\n- **SupportPlan** (`support_plans`, `conflictColumns:\n ['tenant_id','plan_key']`) — the Managed Support Plan: coverage calendar +\n holidays + timezone, channels, severity definitions, per-severity\n acknowledgement/response/update/resolution target minutes, `pauseStatuses`\n (clocks pause only when the plan says so), escalation policy steps,\n availability fee, `includedMinutes`, `overageHourlyRate`,\n `onCallHourlyRate`, time-approval policy, optional\n `subscriptionPlanKey` binding (string, not a dependency).\n `snapshotTerms()` feeds `SupportCase.planSnapshot`.\n- **SupportServiceTarget** (`support_service_targets`,\n `conflictColumns: ['case_id','target_type','cycle']`) — one clock per\n target type (update clocks recur via `cycle`), with pause accounting and\n `escalationJobId` (the one-shot `_smrt_jobs` row scheduled at `dueAt`,\n cancelled on satisfy).\n- **SupportEscalation** (`support_escalations`) — the audit record of one\n escalation firing.\n- **SupportCompensationPlan** (`support_compensation_plans`) —\n effective-dated Support Specialist earning terms; specialist-specific plan\n wins over the tenant default at the work instant. Deliberately separate\n from `SupportPlan` (client pricing) so margin stays measurable.\n\n### Service time (#1930)\n\n- **ServiceTimeEntry** (`service_time_entries`) — auditable Professional\n Service duration: work-context-generic (`caseId` and/or polymorphic\n `workRefType`/`workRefId`), delivering Participant (`participantKind`\n `human`/`agent` + `participantProfileId`/`agentRef`), `source`\n (`timer`/`manual`/`import`/`agent` — one shared validation/audit\n contract), evidence JSON, and lifecycle `draft → submitted →\n approved|rejected`, `approved → corrected` only. **Approved entries are\n immutable**: the work-defining fields are frozen at save time (the\n `LicenseSale` WeakMap-freeze idiom, backed by an authoritative DB-row\n comparison); disputes create explicit corrections via `correctionOfId`.\n- **SupportCharge** / **SupportCompensation** (`support_charges` /\n `support_compensations`, one per time entry) — derived commercial\n snapshots: client amount from the Managed Support Plan (included-time\n consumption then metered overage) vs provider amount from the Support\n Compensation Plan, each with a frozen `rateSnapshot`. Margin = charge −\n compensation, computed by readers; settlement/invoicing composes at the\n app/accounting boundary (#1925) and is out of scope here.\n\n## Services\n\n- **SupportCaseService** — the closed write facade: `openCase`,\n `recordInteraction` (idempotent on `sourceKey`; stamps\n `acknowledgedAt`/`firstRespondedAt`; inbound un-parks\n `waiting_on_client`), `transition`, `assign`, `resolve`, `close`,\n `reopen` (preserves prior resolution in the reopen event), `requestHuman`,\n `linkWork`/`recordWorkStatus` (Delivery Handoff), `recordEvent`,\n `getTimeline` (merged interactions + events).\n- **SupportIntakeService** — create-or-join intake for both channels:\n `ingestChatMessage` (bound `ChatRoom`; `chat:<roomId>[:<threadId>]` thread\n keys; only `role: 'user'` messages), `ingestEmail` (bound `EmailAccount`;\n RFC-thread joins via `inReplyTo`; `selfAddresses` skip; unresolved senders\n park the case with `metadata.unresolvedClient`), plus\n `registerSupportIntake()` — an opt-in `GlobalInterceptors.afterSave`\n observer keyed on the `ChatMessage`/`Email` class names that never throws\n into the source package's save path. Join semantics: open case → join;\n resolved → reopen; closed → new case.\n- **SupportAiWorkflow** — the Automated Support Response (FR-28a):\n `processIntake`/`processCase` run acknowledge → classify → answer →\n resolve under the resolved `SupportPolicy` (conservative defaults), each\n phase writing a `SupportAiRun` + `ai_run` case event. AI calls go through\n the injected `SupportAiBoundary` (default uses `supportCase.do()` with\n defensive JSON parsing that fails toward the human); knowledge comes from\n the pluggable `SupportKnowledgeProvider` (default no-op). Classification\n never overwrites human triage; email answers are drafted\n (`metadata.draft`) unless the policy allows sending. Handoff triggers —\n `client_request`, `low_confidence`, `high_severity`, `sensitive`,\n `failed_resolution`, `policy` (attempt budget) — are always active.\n- **HumanHandoffService** — the lossless Human Handoff (FR-28b):\n `handoff` assembles the full context package (case state + compact\n timeline + AI runs) into the `handoff` event, stamps\n `metadata.activeHandoff` for the no-repeat guarantee (repeat triggers are\n deduped events), routes through the injected `assignSpecialist` seam\n (#1929's routing service plugs in; default queues `new` cases to\n `triaged`), and `releaseHandoff` clears the flag.\n- **ServiceTargetEngine** — Service Target clocks (FR-30/31):\n `startTargetsForCase` derives per-severity clocks from the case's\n `planSnapshot` (live plan fallback) with due times computed in covered\n time (`coverage-calendar.ts`: timezone-aware weekly windows + holidays;\n empty coverage = 24×7) and schedules one-shot `_smrt_jobs` escalation jobs\n at `dueAt`; `onInteractionRecorded` satisfies acknowledgement/response and\n recurs `update` cycles; `onCaseTransition` pauses/resumes clocks only when\n the plan's `pauseStatuses` say so (recomputing remaining covered minutes)\n and settles targets on resolve. Breach → `SupportServiceTarget.\n checkAndEscalate` (background-eligible, at-least-once-safe) marks the\n breach and escalates through the plan's policy steps (notify/reassign,\n delayed follow-up levels), transitioning the case to `escalated`.\n- **SupportPlanAdminService** — the permission-gated write surface for\n commercial terms: create/update/archive for Managed Support Plans and\n Support Compensation Plans, every act behind `support.manage-plans` with\n cross-tenant writes refused (generated CRUD on both models is read-only).\n- **SupportRoutingService** — explainable ranked routing (FR-30):\n `rankSpecialists` hard-filters on active status, effective Project\n Support Qualification, workload cap, and availability windows (specialist\n timezone), then scores preferred-specialist, qualification level, on-call,\n workload headroom, and language (weights in `ROUTING_WEIGHTS`; every\n factor recorded so ineligible specialists show why); `autoAssign` writes\n the assignment with its rationale; `reassign` is gated by\n `support.reassign-case` and refuses cross-tenant principals.\n- **ServiceTimeEntryService** — the ONE recording contract for all four\n entry sources (FR-40): `record` validates duration (explicit or derived\n from the period; `timer` needs both bounds), participant coherence\n (`human` → `participantProfileId`, `agent` → `agentRef`), and the work\n context (case and/or work ref; case entries copy the tenant and append a\n `time_recorded` event); `submit` stamps the submitter.\n- **TimeEntryApprovalService** — the approval gate and only writer of the\n commercial snapshots (FR-36): `approve` resolves the governing terms (case\n `planSnapshot` first, live plan fallback, zero-rate default), gates by\n policy path (`automatic`/`threshold`/`operator`/`client`; operator paths\n behind `support.approve-time-entry`; cross-tenant principals refused), then\n derives the `SupportCharge` (included time first, then overage/on-call) and\n `SupportCompensation` (effective-dated plan) rows; `reject` and `correct`\n (supersede + linked fresh draft via `correctionOfId`) round out the\n lifecycle. Case events carry the charge amount only — compensation never\n leaks case-side.\n\n## Permissions\n\nContributed to the runtime catalog on import (the\n`personas.activate-directive` pattern): `support.reassign-case`,\n`support.approve-time-entry`, `support.manage-plans`. Privileged service\noperations take a `SupportPrincipal` (`can(slug)`), built from explicit slugs\nor a `PermissionResolver`.\n\n## Svelte UI\n\n`@happyvertical/smrt-support/svelte` ships presentational Svelte 5 surfaces:\n`CaseQueue` (priority/status/assignment/channel at a glance, `onselect`),\n`CaseDetail` (header, meta, linked work, merged timeline), `TargetList`\n(Service Target clocks with due/paused/satisfied/breached badges),\n`RoutingRationale` (ranked specialists with eligibility + factor chips and\nan optional reassign action), and `TimeEntryApprovalQueue`\n(date/hours/description/worker/status/amount with\napprove/reject-with-reason actions on submitted rows). Hosts adapt models\nwith `toSupportCaseView` / `toCaseTimelineItemView` / `toServiceTargetView`\n/ `toSupportTimeEntryView` — the time-entry view's first eight fields\ndeliberately match `smrt-projects`' presentation `TimeEntry` contract.\nComponents use `smrt-ui` primitives (`smrtRawPrimitives: \"strict\"`).\n\n## Dependencies\n\nLeaf package (nothing depends back on it): `smrt-core`, `smrt-tenancy`,\n`smrt-chat`, `smrt-messages`, `smrt-jobs`, `smrt-users`, `smrt-ui`,\n`@happyvertical/logger`, `@happyvertical/sql`. Profile / smrt-projects /\nsubscriptions references are `@crossPackageRef` string ids or plain string\nkeys only — no package edge. No inter-`smrt-*` `peerDependencies`.\n\n## Validation\n\n```sh\npnpm --filter @happyvertical/smrt-support test\npnpm --filter @happyvertical/smrt-support typecheck\npnpm --filter @happyvertical/smrt-support build\n```\n\n## Gotchas\n\n- **Writes go through the facades** — the case-side generated routes are\n read-only on purpose; `create`/`update` on them is not a bug to \"fix\".\n- **`projectId` is an app-defined string** — the consuming app owns the\n Project concept; don't turn it into an FK or a crossPackageRef to\n `smrt-projects:Project` (that class is a provider board, not a client\n initiative).\n- **`SupportCase.threadKey` + `SupportInteraction.sourceKey` carry intake\n correctness** — `sourceKey` is globally unique (`conflictColumns`), so\n replayed transport rows are no-ops; new manual interactions must use a\n fresh `manual:<uuid>` key.\n- **High-volume models avoid the inherited `name` field** (`subject`,\n `displayName`, …) so the default `(slug, context, _meta_type)` unique index\n falls back to id-derived slugs; named config models carry\n `conflictColumns` instead (which replaces that index).\n- **Approved time entries never change** — corrections are new rows linked\n by `correctionOfId`; the original flips to `corrected` with its snapshot\n intact.\n- **Plan edits never rewrite history** — cases keep `planSnapshot`, charges\n and compensation keep `rateSnapshot`.\n- **Create-or-join and included-time consumption serialize in-process** —\n `SupportIntakeService` (per conversation key) and\n `TimeEntryApprovalService` (per case) use a `KeyedMutex`, which covers the\n single-app-process deployment these paths run in. Multi-replica\n deployments must serialize at the app layer (route a conversation's\n intake / a case's approvals through one worker, or add an app-level\n claim) — the framework exposes no cross-adapter transaction primitive at\n this seam. Escalation is additionally idempotent per `(target, level)`,\n so at-least-once job redelivery never stacks duplicate escalations.\n"
4235
+ "agentDoc": "# @happyvertical/smrt-support\n\nAI-first Support Cases for the SMRT framework (epic #1934). Every inbound\nsupport interaction — chat message or email — creates or joins one canonical,\ntenant-scoped **Support Case**; channels stay transports, never separate\nsystems of record. The package owns the case lifecycle, channel intake, the\nAutomated Support Response workflow with lossless **Human Handoff**,\nProject-qualified routing, **Service Target** clocks with timed escalation,\nand auditable **Service Time Entries** whose client charges and provider\ncompensation stay separate. Since #1955 the canonical `ServiceTimeEntry` class\nis owned by `smrt-projects`; this package exposes a compatibility subtype that\nrestates the shared fields for isolated manifest scanning. Both imports use the\nunchanged `service_time_entries` table, so no data is duplicated.\n\n**Boundary (FR-29a):** Support owns tickets, interactions, routing, and\nservice targets. Delivery Operations owns repository work — a **Delivery\nHandoff** links a case to a Development Work Item (e.g.\n`@happyvertical/smrt-projects:Issue`) via a `SupportWorkLink` without ever\ndriving its execution; the delivery side reports status echoes back.\n\n## Models\n\nCase-side models are **internal**: generated API/CLI/MCP surfaces are\nread-only (`list`/`get`) and every write goes through the service facades\n(the `smrt-chat` `ChatService` idiom). Operational configuration models\n(bindings, policies, specialists, qualifications, availability) expose full\ngenerated CRUD; **commercial terms** (`SupportPlan`,\n`SupportCompensationPlan`) are read-only too — their writes flow through the\n`support.manage-plans`-gated `SupportPlanAdminService`.\n\n### Case core (#1926)\n\n- **SupportCase** (`support_cases`) — canonical ticket: `caseNumber`,\n `subject`, `status` (`new → triaged → assigned → in_progress →\n waiting_on_client|escalated → resolved → closed`, guarded at save time via\n the WeakMap + authoritative-DB-read idiom from S5 #1390), `priority`,\n `severity` (plan-defined key), `category`, `sensitive`, `channelKind`,\n `clientProfileId`/`openedByProfileId` (crossPackageRef → Profile),\n `projectId` (app-defined string — deliberately not an FK), `bindingId`,\n `threadKey` (create-or-join dedup key), `planId` + `planSnapshot` (terms\n frozen at apply time), assignment fields, response stamps\n (`acknowledgedAt`, `firstRespondedAt`), `humanRequestedAt`, resolution\n fields, `reopenCount`/`lastReopenedAt`, `aiEnabled`.\n- **SupportInteraction** (`support_interactions`,\n `conflictColumns: ['source_key']`) — channel-neutral transport record:\n `direction` (`inbound`/`outbound`/`internal`), `channelKind`, `actorKind`\n (`client`/`specialist`/`agent`/`system`), denormalized `body`, and the\n qualified `sourceType`/`sourceId` + globally unique `sourceKey`\n (`chat:<messageId>`, `email:<emailId>`, `manual:<uuid>`) that makes\n re-ingestion idempotent.\n- **SupportCaseEvent** (`support_case_events`) — append-only audit trail\n (transitions, assignments, AI runs, handoffs, escalations, target state,\n work links, reopens). Together with interactions this is the complete\n context a Human Handoff transfers.\n- **SupportChannelBinding** (`support_channel_bindings`,\n `conflictColumns: ['target_type','target_id']`) — marks a container as a\n support intake channel: `bindingKind` (`chat_room`/`email_account`),\n qualified `targetType` + `targetId`, default client/project/plan,\n `selfAddresses` (email direction heuristic). Unbound containers are never\n touched.\n- **SupportWorkLink** (`support_work_links`) — Support/Development Work Item\n links with a read-only `status` echo.\n\n### AI workflow (#1928)\n\n- **SupportPolicy** (`support_policies`) — what the AI may do without a\n human: `autoAcknowledge`/`autoClassify`/`autoAnswer` (on by default),\n `autoTroubleshoot`/`autoResolve` (off by default),\n `autoResolveMaxSeverity`, `confidenceThreshold`, `maxAutoAttempts`,\n `sensitiveCategories`, `allowedTools`, `autoSendEmailReplies` (off —\n email replies are drafted, not sent). Resolution is most-specific-wins on\n `(planId, projectId)`; no row → `DEFAULT_SUPPORT_POLICY` (conservative).\n- **SupportAiRun** (`support_ai_runs`) — append-only audit of each phase\n (`acknowledge`/`classify`/`answer`/`troubleshoot`/`resolve`) with\n `confidence`, classification output, knowledge refs, tool calls, outcome\n (`completed`/`skipped`/`failed`/`handed_off`), and `correlationId`.\n\n### Routing, targets, escalation (#1929)\n\n- **SupportSpecialist** (`support_specialists`) — specialist role record on a\n Profile (the commerce `Customer` role-record idiom): `languages`,\n `timezone`, `maxConcurrentCases`, `onCallPriority`, status.\n- **SupportQualification** (`support_qualifications`) — effective-dated\n Project Support Qualification (`trainee`/`qualified`/`expert`).\n- **SupportAvailability** (`support_availability_windows`) — weekly windows\n plus `on_call`/`time_off` spans.\n- **SupportPlan** (`support_plans`, `conflictColumns:\n ['tenant_id','plan_key']`) — the Managed Support Plan: coverage calendar +\n holidays + timezone, channels, severity definitions, per-severity\n acknowledgement/response/update/resolution target minutes, `pauseStatuses`\n (clocks pause only when the plan says so), escalation policy steps,\n availability fee, `includedMinutes`, `overageHourlyRate`,\n `onCallHourlyRate`, time-approval policy, optional\n `subscriptionPlanKey` binding (string, not a dependency).\n `snapshotTerms()` feeds `SupportCase.planSnapshot`.\n- **SupportServiceTarget** (`support_service_targets`,\n `conflictColumns: ['case_id','target_type','cycle']`) — one clock per\n target type (update clocks recur via `cycle`), with pause accounting and\n `escalationJobId` (the one-shot `_smrt_jobs` row scheduled at `dueAt`,\n cancelled on satisfy).\n- **SupportEscalation** (`support_escalations`) — the audit record of one\n escalation firing.\n- **SupportCompensationPlan** (`support_compensation_plans`) —\n effective-dated Support Specialist earning terms; specialist-specific plan\n wins over the tenant default at the work instant. Deliberately separate\n from `SupportPlan` (client pricing) so margin stays measurable.\n\n### Service time (#1930)\n\n- **ServiceTimeEntry** (`service_time_entries`) — auditable Professional\n Service duration: work-context-generic (`caseId` and/or polymorphic\n `workRefType`/`workRefId`), delivering Participant (`participantKind`\n `human`/`agent` + `participantProfileId`/`agentRef`), `source`\n (`timer`/`manual`/`import`/`agent` — one shared validation/audit\n contract), evidence JSON, and lifecycle `draft → submitted →\n approved|rejected`, `approved → corrected` only. **Approved entries are\n immutable**: the work-defining fields are frozen at save time (the\n `LicenseSale` WeakMap-freeze idiom, backed by an authoritative DB-row\n comparison); disputes create explicit corrections via `correctionOfId`.\n- **SupportCharge** / **SupportCompensation** (`support_charges` /\n `support_compensations`, one per time entry) — derived commercial\n snapshots: client amount from the Managed Support Plan (included-time\n consumption then metered overage) vs provider amount from the Support\n Compensation Plan, each with a frozen `rateSnapshot`. Margin = charge −\n compensation, computed by readers; settlement/invoicing composes at the\n app/accounting boundary (#1925) and is out of scope here.\n\n## Services\n\n- **SupportCaseService** — the closed write facade: `openCase`,\n `recordInteraction` (idempotent on `sourceKey`; stamps\n `acknowledgedAt`/`firstRespondedAt`; inbound un-parks\n `waiting_on_client`), `transition`, `assign`, `resolve`, `close`,\n `reopen` (preserves prior resolution in the reopen event), `requestHuman`,\n `linkWork`/`recordWorkStatus` (Delivery Handoff), `recordEvent`,\n `getTimeline` (merged interactions + events).\n- **SupportIntakeService** — create-or-join intake for both channels:\n `ingestChatMessage` (bound `ChatRoom`; `chat:<roomId>[:<threadId>]` thread\n keys; only `role: 'user'` messages), `ingestEmail` (bound `EmailAccount`;\n RFC-thread joins via `inReplyTo`; `selfAddresses` skip; unresolved senders\n park the case with `metadata.unresolvedClient`), plus\n `registerSupportIntake()` — an opt-in `GlobalInterceptors.afterSave`\n observer keyed on the `ChatMessage`/`Email` class names that never throws\n into the source package's save path. Join semantics: open case → join;\n resolved → reopen; closed → new case.\n- **SupportAiWorkflow** — the Automated Support Response (FR-28a):\n `processIntake`/`processCase` run acknowledge → classify → answer →\n resolve under the resolved `SupportPolicy` (conservative defaults), each\n phase writing a `SupportAiRun` + `ai_run` case event. AI calls go through\n the injected `SupportAiBoundary` (default uses `supportCase.do()` with\n defensive JSON parsing that fails toward the human); knowledge comes from\n the pluggable `SupportKnowledgeProvider` (default no-op). Classification\n never overwrites human triage; email answers are drafted\n (`metadata.draft`) unless the policy allows sending. Handoff triggers —\n `client_request`, `low_confidence`, `high_severity`, `sensitive`,\n `failed_resolution`, `policy` (attempt budget) — are always active.\n- **HumanHandoffService** — the lossless Human Handoff (FR-28b):\n `handoff` assembles the full context package (case state + compact\n timeline + AI runs) into the `handoff` event, stamps\n `metadata.activeHandoff` for the no-repeat guarantee (repeat triggers are\n deduped events), routes through the injected `assignSpecialist` seam\n (#1929's routing service plugs in; default queues `new` cases to\n `triaged`), and `releaseHandoff` clears the flag.\n- **ServiceTargetEngine** — Service Target clocks (FR-30/31):\n `startTargetsForCase` derives per-severity clocks from the case's\n `planSnapshot` (live plan fallback) with due times computed in covered\n time (`coverage-calendar.ts`: timezone-aware weekly windows + holidays;\n empty coverage = 24×7) and schedules one-shot `_smrt_jobs` escalation jobs\n at `dueAt`; `onInteractionRecorded` satisfies acknowledgement/response and\n recurs `update` cycles; `onCaseTransition` pauses/resumes clocks only when\n the plan's `pauseStatuses` say so (recomputing remaining covered minutes)\n and settles targets on resolve. Breach → `SupportServiceTarget.\n checkAndEscalate` (background-eligible, at-least-once-safe) marks the\n breach and escalates through the plan's policy steps (notify/reassign,\n delayed follow-up levels), transitioning the case to `escalated`.\n- **SupportPlanAdminService** — the permission-gated write surface for\n commercial terms: create/update/archive for Managed Support Plans and\n Support Compensation Plans, every act behind `support.manage-plans` with\n cross-tenant writes refused (generated CRUD on both models is read-only).\n- **SupportRoutingService** — explainable ranked routing (FR-30):\n `rankSpecialists` hard-filters on active status, effective Project\n Support Qualification, workload cap, and availability windows (specialist\n timezone), then scores preferred-specialist, qualification level, on-call,\n workload headroom, and language (weights in `ROUTING_WEIGHTS`; every\n factor recorded so ineligible specialists show why); `autoAssign` writes\n the assignment with its rationale; `reassign` is gated by\n `support.reassign-case` and refuses cross-tenant principals.\n- **ServiceTimeEntryService** — the ONE recording contract for all four\n entry sources (FR-40): `record` validates duration (explicit or derived\n from the period; `timer` needs both bounds), participant coherence\n (`human` → `participantProfileId`, `agent` → `agentRef`), and the work\n context (case and/or work ref; case entries copy the tenant and append a\n `time_recorded` event); `submit` stamps the submitter.\n- **TimeEntryApprovalService** — the approval gate and only writer of the\n commercial snapshots (FR-36): `approve` resolves the governing terms (case\n `planSnapshot` first, live plan fallback, zero-rate default), gates by\n policy path (`automatic`/`threshold`/`operator`/`client`; operator paths\n behind `support.approve-time-entry`; cross-tenant principals refused), then\n derives the `SupportCharge` (included time first, then overage/on-call) and\n `SupportCompensation` (effective-dated plan) rows; `reject` and `correct`\n (supersede + linked fresh draft via `correctionOfId`) round out the\n lifecycle. Case events carry the charge amount only — compensation never\n leaks case-side.\n\n## Permissions\n\nContributed to the runtime catalog on import (the\n`personas.activate-directive` pattern): `support.reassign-case`,\n`support.approve-time-entry`, `support.manage-plans`. Privileged service\noperations take a `SupportPrincipal` (`can(slug)`), built from explicit slugs\nor a `PermissionResolver`.\n\n## Svelte UI\n\n`@happyvertical/smrt-support/svelte` ships presentational Svelte 5 surfaces:\n`CaseQueue` (priority/status/assignment/channel at a glance, `onselect`),\n`CaseDetail` (header, meta, linked work, merged timeline), `TargetList`\n(Service Target clocks with due/paused/satisfied/breached badges),\n`RoutingRationale` (ranked specialists with eligibility + factor chips and\nan optional reassign action), and `TimeEntryApprovalQueue`\n(date/hours/description/worker/status/amount with\napprove/reject-with-reason actions on submitted rows). Hosts adapt models\nwith `toSupportCaseView` / `toCaseTimelineItemView` / `toServiceTargetView`\n/ `toSupportTimeEntryView` — the time-entry view's first eight fields\ndeliberately match `smrt-projects`' presentation `TimeEntry` contract.\nComponents use `smrt-ui` primitives (`smrtRawPrimitives: \"strict\"`).\n\n## Dependencies\n\nPackage dependencies: `smrt-core`, `smrt-tenancy`, `smrt-projects`,\n`smrt-chat`, `smrt-messages`, `smrt-jobs`, `smrt-users`, `smrt-ui`,\n`@happyvertical/logger`, `@happyvertical/sql`. Profile and subscriptions\nreferences are `@crossPackageRef` string ids or plain string\nkeys. `smrt-projects` is the intentional shared delivery/evidence edge added\nby #1955. No inter-`smrt-*` `peerDependencies`.\n\n## Validation\n\n```sh\npnpm --filter @happyvertical/smrt-support test\npnpm --filter @happyvertical/smrt-support typecheck\npnpm --filter @happyvertical/smrt-support build\n```\n\n## Gotchas\n\n- **Writes go through the facades** — the case-side generated routes are\n read-only on purpose; `create`/`update` on them is not a bug to \"fix\".\n- **`projectId` is an app-defined string** — the consuming app owns the\n Project concept; don't turn it into an FK or a crossPackageRef to\n `smrt-projects:Project` (that class is a provider board, not a client\n initiative).\n- **`SupportCase.threadKey` + `SupportInteraction.sourceKey` carry intake\n correctness** — `sourceKey` is globally unique (`conflictColumns`), so\n replayed transport rows are no-ops; new manual interactions must use a\n fresh `manual:<uuid>` key.\n- **High-volume models avoid the inherited `name` field** (`subject`,\n `displayName`, …) so the default `(slug, context, _meta_type)` unique index\n falls back to id-derived slugs; named config models carry\n `conflictColumns` instead (which replaces that index).\n- **Approved time entries never change** — corrections are new rows linked\n by `correctionOfId`; the original flips to `corrected` with its snapshot\n intact.\n- **Plan edits never rewrite history** — cases keep `planSnapshot`, charges\n and compensation keep `rateSnapshot`.\n- **Create-or-join and included-time consumption serialize in-process** —\n `SupportIntakeService` (per conversation key) and\n `TimeEntryApprovalService` (per case) use a `KeyedMutex`, which covers the\n single-app-process deployment these paths run in. Multi-replica\n deployments must serialize at the app layer (route a conversation's\n intake / a case's approvals through one worker, or add an app-level\n claim) — the framework exposes no cross-adapter transaction primitive at\n this seam. Escalation is additionally idempotent per `(target, level)`,\n so at-least-once job redelivery never stacks duplicate escalations.\n"
4242
4236
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-support",
3
- "version": "0.39.4",
3
+ "version": "0.39.7",
4
4
  "description": "AI-first Support Cases: channel-neutral intake, lifecycle, routing, service targets, and service time for the SMRT framework",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,13 +27,14 @@
27
27
  "dependencies": {
28
28
  "@happyvertical/logger": "^0.78.0",
29
29
  "@happyvertical/sql": "^0.78.0",
30
- "@happyvertical/smrt-chat": "0.39.4",
31
- "@happyvertical/smrt-core": "0.39.4",
32
- "@happyvertical/smrt-jobs": "0.39.4",
33
- "@happyvertical/smrt-tenancy": "0.39.4",
34
- "@happyvertical/smrt-messages": "0.39.4",
35
- "@happyvertical/smrt-ui": "0.39.4",
36
- "@happyvertical/smrt-users": "0.39.4"
30
+ "@happyvertical/smrt-chat": "0.39.7",
31
+ "@happyvertical/smrt-core": "0.39.7",
32
+ "@happyvertical/smrt-jobs": "0.39.7",
33
+ "@happyvertical/smrt-messages": "0.39.7",
34
+ "@happyvertical/smrt-projects": "0.39.7",
35
+ "@happyvertical/smrt-tenancy": "0.39.7",
36
+ "@happyvertical/smrt-ui": "0.39.7",
37
+ "@happyvertical/smrt-users": "0.39.7"
37
38
  },
38
39
  "peerDependencies": {
39
40
  "svelte": "^5.56.4"
@@ -52,7 +53,7 @@
52
53
  "typescript": "^5.9.3",
53
54
  "vite": "^8.1.3",
54
55
  "vitest": "^4.1.9",
55
- "@happyvertical/smrt-vitest": "0.39.4"
56
+ "@happyvertical/smrt-vitest": "0.39.7"
56
57
  },
57
58
  "keywords": [
58
59
  "smrt",