From 275c0624dc3115a22aa2228b9d99638512c7de3f Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 01:18:36 -0500 Subject: [PATCH 1/4] Guard final customer confirmation and resolution evidence commits --- AGENTS.md | 49 +- README.md | 53 +- docs/KNOWLEDGE_AI_PLAN.md | 42 +- docs/PROJECT_PLAN.md | 36 +- docs/RELEASE_NOTES.md | 56 +- docs/RELEASING.md | 100 +++- docs/RESOLUTION_LEARNING.md | 63 ++- docs/UPGRADING.md | 105 +++- package.json | 6 +- packages/ai/package.json | 4 +- packages/application/README.md | 41 +- packages/application/package.json | 6 +- packages/application/src/index.ts | 83 ++- .../src/resolution-learning-types.ts | 13 + .../application/src/resolution-learning.ts | 56 +- packages/contracts/package.json | 2 +- packages/core/package.json | 4 +- packages/templates/package.json | 2 +- pnpm-lock.yaml | 14 +- tests/customer-success-mutation-guard.test.ts | 474 ++++++++++++++++ ...resolution-evidence-mutation-guard.test.ts | 535 ++++++++++++++++++ 21 files changed, 1563 insertions(+), 181 deletions(-) create mode 100644 tests/customer-success-mutation-guard.test.ts create mode 100644 tests/resolution-evidence-mutation-guard.test.ts diff --git a/AGENTS.md b/AGENTS.md index fed46c7..060c1bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -146,8 +146,17 @@ first publish and later OIDC releases. ## Where things stand +Source preparation, 2026-11-13, synchronizes all five packages and internal +Support pins at `0.2.10`; the root remains private at `0.0.0`. It adds optional +third-argument `signal`/`verifyBeforeCommit` options to customer success and +resolution evidence, retaining two-argument compatibility and receipt-first +recovery under current authority. Exact KB `0.1.8`, `zod@4.6.7` and other +external selections are unchanged. The combined source still needs the normal +release gates and a publication receipt. See [patch notes](docs/RELEASE_NOTES.md#0210-final-success-evidence-guards) +and [release status](docs/RELEASING.md#source-version-0210). + Task 15's bounded deployment-owned canned-response catalog is implemented in -the unpublished source candidate. Staff preview literal values and explicitly +the released SDK source. Staff preview literal values and explicitly submit an existing reply/note command; exact version/body/target validation and transactional Audit provenance retain current authorization, revision, replay and internal-note boundaries. It adds no collection or package version. See @@ -179,19 +188,19 @@ collision hints. Customer DTOs and automatic customer mail omit these fields. Calendars and presence stay host-owned. Task 12 remains pending on both hosts' durable-store production evidence. Source work does not publish a package. -The five local manifests and exact internal Support pins target unpublished -`0.2.9`. It adds optional per-attempt model-planning/completion, proposal and +All five synchronized packages are published and strictly verified at `0.2.9`. +It adds optional per-attempt model-planning/completion, proposal and dispatch observations while retaining fresh proof, authority, opaque-version confirmation and exact ACK recovery. Legacy structural ports keep their full -fallback. See the [candidate notes](docs/RELEASE_NOTES.md#029-engineering-worker-observations) +fallback. See the [release notes](docs/RELEASE_NOTES.md#029-engineering-worker-observations) and [worker contract](docs/ENGINEERING_EXPORT.md#candidate-029-worker-observations). -The candidate now pins exact verified public KB application/contracts `0.1.8`. -Its changed dependency graph requires fresh SDK qualification; published -`0.2.8` retains its exact KB `0.1.6` pins. The -root stays private at `0.0.0`; source or candidate packs do not qualify registry -publication or a host's complete query/CPU budget. +The optional AI package pins exact public KB application/contracts `0.1.8`. +Its changed dependency graph passed strict registry, native cryptographic/source +and clean-public-consumer qualification. Historical `0.2.8` retains its exact KB +`0.1.6` pins. The root stays private at `0.0.0`; host integration and complete +query/CPU acceptance retain their own gates. -The unpublished `0.2.9` candidate also adds opt-in +Published `0.2.9` also adds opt-in [`deliveryMode: 'staged'`](docs/RESOLUTION_LEARNING.md#opt-in-staged-draft-delivery-029-candidate) with durable prepare/write checkpoints that release the claim and a later physical completion phase. @@ -200,14 +209,16 @@ yields after one retirement attempt for later fresh readback. Closing policy/receipt checks apply to inline delivery too. The optional [`./openrouter` entry](packages/ai/README.md#optional-openrouter-adapter-source-candidate) keeps the AI root provider-neutral and requires explicit host binding with -separate host stores, keys and current privacy/configuration evidence. Native -Workers Free 50/100 qualification remains pending. +separate host stores, keys and current privacy/configuration evidence. The +Sessions `0.3.0` prerequisite is public. Final site integration, complete host +Workers Free 50/100 invocation/CPU acceptance, provider/privacy and requested-client +acceptance, and supervised pilots remain pending. -All five packages have verified published `0.2.8` versions. The synchronized +All five packages have verified published `0.2.9` versions. The synchronized `0.2.1` and `0.2.0` artifacts remain immutable history. The original four names also retain their published `0.1.0`/`0.1.1` artifacts; the AI name's `0.1.1` is a separate registration-only bootstrap. Follow the -[publication receipt](docs/RELEASING.md#verified-028-publication-2026-11-12) +[publication receipt](docs/RELEASING.md#verified-029-publication-2026-11-13) and release operations. Customer services return safe DTOs; staff services return the authoritative ticket for authorized staff only, and the staff queue scans a confirmed projection that is never authorization evidence. @@ -257,13 +268,13 @@ messages with exact completion fences, and adds deterministic owned request-person, staff takeover, private success evidence, human queue selection, and bounded atomic handoff work. It adds no model, KB dependency, or package; its behavior first shipped in synchronized `0.2.0` and remains in -current `0.2.8`. Do not overwrite registry `0.1.1` or install a source substitute. Host adoption retains its own +published `0.2.9`. Do not overwrite registry `0.1.1` or install a source substitute. Host adoption retains its own activation gates after verified SDK publication. Standalone KB-01 through KB-04, AUTH-01 Agent Access, partial KB-05 source preparation ([KB #4](https://github.com/pegma-dev/knowledge-base/pull/4)), and both producers' final release preparation are merged. The -[standalone authoring recipe](docs/HOST_COMPOSITION.md#kb-authoring-producers) -selects all four strictly verified KB `0.1.6` packages and verified Agent +[historical standalone authoring recipe](docs/HOST_COMPOSITION.md#kb-authoring-producers) +selected all four strictly verified KB `0.1.6` packages and verified Agent Access `0.1.1`. The trusted releases close the producer publication gates. Their manual `0.1.0` bootstrap receipts remain historical and have no OIDC provenance. SD-02 @@ -281,8 +292,8 @@ signed `v0.2.0` at `efc9d733b3d305d24cf4197444e1d76c99bdb777`; see `docs/RELEASING.md` for the dated receipt. Its public composition example lives in `examples/ai`; the migration and operations handbooks are `docs/UPGRADING.md` and `docs/AI_OPERATIONS.md`. The base application has no KB or provider dependency; actual KB -`0.1.6` application/contracts dependencies belong only to the current -optional AI `0.2.8` package. Older `0.2.0` and +`0.1.8` application/contracts dependencies belong only to the current +published optional AI `0.2.9` package and prepared `0.2.10` metadata. Historical `0.2.8` retains `0.1.6`; older `0.2.0` and `0.2.1` AI manifests retain their original `0.1.2` pins. See [assistant coordination](docs/ASSISTANT_COORDINATION.md) and its [layout checkpoint](docs/COLLECTIONS.md#sd-02-assistant-turn-layout-checkpoint). PG-01/RG-01 consume exact verified published producers and still require actual diff --git a/README.md b/README.md index 7df6b3c..5e5dac6 100644 --- a/README.md +++ b/README.md @@ -6,28 +6,36 @@ A composable, open-source support queue for web and email. > [!IMPORTANT] -> Support Desk is in early `0.x` development. All five synchronized `0.2.8` +> Support Desk is in early `0.x` development. All five synchronized `0.2.9` > packages are published and strictly verified. Hosts consume exact published > versions and retain their own adoption and activation gates. -The local synchronized source version is **`0.2.9`** and remains unpublished. +Source preparation, 2026-11-13, selects synchronized **`0.2.10`** with optional +final host guards/cancellation on customer success and resolution evidence. +Existing two-argument calls remain valid. Exact accepted receipts recover +under current permissions before obsolete proofs, the optional final guard or +abort checks. See the [patch notes](docs/RELEASE_NOTES.md#0210-final-success-evidence-guards) +and [release status](docs/RELEASING.md#source-version-0210); preparation is not +publication or host acceptance. + +The dated verified synchronized publication is **`0.2.9`**. It adds optional per-attempt engineering model-planning/completion, proposal and dispatch observations through existing mutation kernels. Current proof, authority, opaque-version confirmation and exact receipt recovery remain; older structural ports retain their full fallback. See the -[candidate notes](docs/RELEASE_NOTES.md#029-engineering-worker-observations) and +[release notes](docs/RELEASE_NOTES.md#029-engineering-worker-observations) and [worker contract](docs/ENGINEERING_EXPORT.md#candidate-029-worker-observations). Use verified published artifacts for host adoption; source metadata is not a publication or host-qualification receipt. -The current [verified `0.2.8` release](docs/RELEASING.md#verified-028-publication-2026-11-12) -adds optional late host guards/cancellation and authorized reassessment/post -observations for release follow-up. It retains `0.2.7` engineering read batching -and actual provider-usage accounting, earlier guarded controls, attachments, -staged human learning reviews and recovery APIs. Its optional AI package pins -exact KB application/contracts `0.1.6`. The unpublished `0.2.9` candidate now -targets exact verified public KB `0.1.8` and requires fresh dependency graph -qualification. Earlier artifacts and dated receipts remain immutable. +The [verified `0.2.9` release](docs/RELEASING.md#verified-029-publication-2026-11-13) +also adds opt-in durable release-follow-up check phases and bundle observations, +corrects approval renewal and deferred receipt expiry, and screens the complete +independent-check payload for private ticket text. Its optional AI package pins +exact public KB application/contracts `0.1.8`; the changed dependency graph passed +strict registry, provenance and clean-consumer verification. It retains `0.2.8` +follow-up guards, `0.2.7` engineering read batching and earlier workflows. +Earlier artifacts and dated receipts remain immutable. Staged retrieval remains OFF by default. Preparation consumes one existing attempt; both application and verified-configuration caps must allow at least @@ -38,9 +46,11 @@ one. Full configuration and authority snapshots must remain identical across phases; live guards still run. Publication establishes no universal query or CPU budget and does not qualify a host, provider or client. -All five synchronized `0.2.8` packages are published and strictly verified. See +All five synchronized `0.2.9` packages are published and strictly verified. See the [release notes](docs/RELEASE_NOTES.md). Host composition, deployment, -provider/privacy and client acceptance remain separate gates. +provider/privacy and client acceptance remain separate gates. The Sessions +`0.3.0` prerequisite is public; final site integration, complete host Workers +Free invocation/CPU acceptance and supervised pilots remain pending. Implemented in source today: the customer-facing and staff application services, the repairable staff queue projection, declared collections, @@ -52,7 +62,7 @@ tags, host-computed response targets and milestones, and revision collision hint (Buildout Task 13), with all new metadata limited to staff views. Durable host deployments, customer UI, staff UI, inbound provider adapters, and production hardening remain later buildout tasks. Task 12 stays pending on host durable-store -evidence; the current verified package release is `0.2.8`. +evidence; the dated verified package receipt records `0.2.9`. Buildout Task 14 [attachment APIs](docs/ATTACHMENTS.md) are also implemented in published `0.2.5`: a host blob port, transactional message metadata, @@ -86,8 +96,8 @@ human controls and atomic handoff work, private customer success evidence, and human queue separation. That source slice includes no model or KB integration and shipped in `0.2.0`. Standalone KB-01 through KB-04, AUTH-01 Agent Access, partial KB-05 source preparation ([KB #4](https://github.com/pegma-dev/knowledge-base/pull/4)), -and both producers' final release preparation are merged. The standalone -authoring recipe selects all four strictly verified KB `0.1.6` packages and +and both producers' final release preparation are merged. The historical +standalone authoring recipe selected all four strictly verified KB `0.1.6` packages and verified `@pegma/agent-access@0.1.1`. The producer releases close SD-02's KB-05 publication prerequisite. SD-02's optional `@pegma/support-desk-ai` coordinator and bounded ticket-partition turn jobs @@ -100,11 +110,12 @@ See the [producer evidence and bootstrap handoff](docs/HOST_COMPOSITION.md#kb-au The [assistant coordination guide](docs/ASSISTANT_COORDINATION.md) and [layout checkpoint](docs/COLLECTIONS.md#sd-02-assistant-turn-layout-checkpoint) describe the SDK contracts. The base application works without AI; only -the optional coordinator depends on KB. Its current released `0.2.8` manifest -pins exact KB application/contracts `0.1.6`; the older `0.2.1` manifest retains +the optional coordinator depends on KB. Its current released `0.2.9` manifest +pins exact KB application/contracts `0.1.8`; historical `0.2.8` retains `0.1.6`, +and the older `0.2.1` manifest retains its original `0.1.2` dependencies. The standalone-authoring recipe and Agent Access selection in the producer handoff remain separate compositions. The -[verified 0.2.8 publication receipt](docs/RELEASING.md#verified-028-publication-2026-11-12) +[verified 0.2.9 publication receipt](docs/RELEASING.md#verified-029-publication-2026-11-13) records the exact release; host adoption retains its own acceptance gates. Use the [implementation ledger](docs/KNOWLEDGE_AI_PLAN.md#status-and-reading-order) for source/release evidence and the remaining activation gates. @@ -194,9 +205,9 @@ The organization profile is at | `@pegma/support-desk-ai` | Optional answers, resolution learning, engineering export and follow-up | All five packages are published under the `@pegma` scope at verified -[`0.2.8`](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.8). The optional AI package's +[`0.2.9`](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.9). The optional AI package's registration-only `bootstrap` remains `0.1.1`; earlier registry versions are -immutable history. The [publication receipt](docs/RELEASING.md#verified-028-publication-2026-11-12) +immutable history. The [publication receipt](docs/RELEASING.md#verified-029-publication-2026-11-13) records the original artifacts and strict verification. There is deliberately no storage package and no access package. Inbound mail processing is implemented (Buildout Task 11); host adapters, production hardening, and the diff --git a/docs/KNOWLEDGE_AI_PLAN.md b/docs/KNOWLEDGE_AI_PLAN.md index 81dc88a..3407f7b 100644 --- a/docs/KNOWLEDGE_AI_PLAN.md +++ b/docs/KNOWLEDGE_AI_PLAN.md @@ -5,11 +5,20 @@ Approved product decisions: 2026-11-06; scoped-agent-access decision added 2026-11-07. The ten entries in the ledger below are merged source, including AUTH-01, KB-04's transport source exit, and both producers' release preparation. +Source preparation on 2026-11-13 now selects synchronized Support Desk +`0.2.10`, adding optional final host guards/cancellation to customer success +and resolution evidence while retaining exact KB `0.1.8` and other external +pins. The [patch notes](RELEASE_NOTES.md#0210-final-success-evidence-guards) and +[release operations](RELEASING.md#source-version-0210) distinguish prepared +source from verified publication; host activation gates remain open. All five synchronized Support Desk packages are published and strictly -verified at `0.2.8`. Optional AI pins Knowledge Base application and contracts -to exact `0.1.6`. This host composition selects all four verified Knowledge -Base `0.1.6` packages and Agent Access `0.1.1`. The dated ledger below records -earlier checkpoints. [Support Desk publication receipt](RELEASING.md#verified-028-publication-2026-11-12) · [Knowledge Base release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6) +verified at `0.2.9`. Optional AI pins Knowledge Base application and contracts +to exact public `0.1.8`; fresh dependency, native cryptographic/source and clean +public-consumer verification passed. The public producer tuple is SDK `0.2.9` / +KB `0.1.8`; Agent Access `0.1.1` remains a separate authoring composition. +Sessions `0.3.0` is also public. Final site integration and host activation gates +remain open. The dated ledger below records earlier checkpoints. +[Support Desk publication receipt](RELEASING.md#verified-029-publication-2026-11-13) · [Knowledge Base release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.8) Published `0.2.3` includes the final engineering approval/rejection guards and proof-expiry fence. Published `0.2.4` adds admitted customer intake, final draft @@ -129,14 +138,15 @@ read-batching SDK patch establishes no universal Workers Free query or CPU bound and no host KB/AI activation, live-provider/privacy acceptance, actual requested-client acceptance (zero recorded here), evaluations or pilots. -**Current version facts and next gates.** The verified Support Desk `0.2.8` -AI manifest pins Knowledge Base application and contracts to exact `0.1.6`. -The unpublished `0.2.9` AI manifest and repository development pins select exact -verified public KB application/contracts `0.1.8`. -Fresh SDK dependency qualification remains required; earlier candidate artifacts -and results do not substitute for that changed public dependency graph. +**Dated publication facts and next gates.** The verified Support Desk `0.2.9` +AI manifest and repository development pins select exact public Knowledge Base +application/contracts `0.1.8`. Release run +[43366221098, attempt 1](https://github.com/pegma-dev/support-desk/actions/runs/43366221098/attempts/1) +passed all seven jobs and 94 steps; all five packages passed strict original-byte, +dependency, native signature/Sigstore/source and clean-public-consumer checks. +Historical `0.2.8` retains its exact KB `0.1.6` pins. The earlier `0.2.1` AI manifest retains its exact `0.1.2` dependencies. The base -application remains independent of KB and providers. [Current publication receipt](RELEASING.md#verified-028-publication-2026-11-12) · [Historical AI manifest](https://github.com/pegma-dev/support-desk/blob/v0.2.1/packages/ai/package.json) +application remains independent of KB and providers. [Current publication receipt](RELEASING.md#verified-029-publication-2026-11-13) · [Historical AI manifest](https://github.com/pegma-dev/support-desk/blob/v0.2.1/packages/ai/package.json) Qualified Storage Core adapter releases include [Cloudflare D1 `0.4.6`](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.6) @@ -155,8 +165,9 @@ authority/data controls, and replay contract. Public-entry memory/Azurite tests with the actual KB and a fake provider, Node 22/24 gates, and code/security review support this SDK release; they do not establish host activation. The earlier standalone authoring recipe selected all four exact KB `0.1.4` -packages and Agent Access `0.1.1`. This host composition pins KB `0.1.6` and -Agent Access `0.1.1`. Each host qualifies its actual installed graph and records +packages and Agent Access `0.1.1`. The historical host composition pinned KB +`0.1.6` and Agent Access `0.1.1`; each host qualifies its actual installed graph +when adopting the public SDK `0.2.9` / KB `0.1.8` tuple and records its own adoption evidence. [Producer handoff](HOST_COMPOSITION.md#kb-authoring-producers) PG-01 source integration is tracked in [PR #59](https://github.com/pegma-dev/pegma.dev/pull/59). Neither host's source @@ -166,8 +177,9 @@ every requested client/mode acceptance. Those remain open activation gates tracked by P-00 and PG-01/RG-01; publication and source/SDK results do not close them. Task 12, provider/ZDR/intermediary verification, issue-to-deployed-build mapping, operations, dual-host acceptance, and supervised -pilots remain open. Verified SDK publication does not close -those gates. +pilots remain open. The published Sessions `0.3.0` prerequisite and selected +Native cases do not close final site integration, each host's complete Workers +Free 50/100 invocation/CPU acceptance, or those client/provider/pilot gates. Read the decision record and boundaries below, then give an implementation agent exactly one task card. `PROJECT_PLAN.md` remains the roadmap and diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 4ac2490..22cfbd7 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -11,12 +11,19 @@ preparation are also merged. The ten entries in the [historical source ledger](KNOWLEDGE_AI_PLAN.md#status-and-reading-order) record the exact PRs/commits, verified gates, and remaining dependency order. -Support Desk's current synchronized `0.2.8` release is published and strictly verified; -see the [publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +Source preparation, 2026-11-13, selects synchronized `0.2.10` and additive final +host guards/cancellation for customer success and resolution evidence. Current +receipt recovery, permissions and external dependency pins are retained. See +the [patch notes](RELEASE_NOTES.md#0210-final-success-evidence-guards) and +[release status](RELEASING.md#source-version-0210); combined-source review, +validation and publication remain separate from this preparation. + +The synchronized `0.2.9` publication is strictly verified; +see the [publication receipt](RELEASING.md#verified-029-publication-2026-11-13). It pins Audit `0.2.0`, Authorization Core `0.4.0`, Mail `0.1.1`, Spine `0.1.2`, and Storage Core `0.4.0`. The older base registry `0.1.1` artifacts remain immutable. Host adoption retains its own acceptance gates. All four KB packages -have strictly verified trusted [`0.1.6` releases](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6). +have strictly verified trusted [`0.1.8` releases](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.8). Agent Access remains verified at `0.1.1`. The [producer verification receipts](HOST_COMPOSITION.md#kb-authoring-producers) record exact release commits and strict registry/clean-consumer jobs. Earlier @@ -24,7 +31,7 @@ manual `0.1.0` bootstrap receipts have no OIDC provenance and remain historical; the later trusted releases close the KB-05/Agent Access publication gates. SD-02's optional coordinator first shipped as `@pegma/support-desk-ai@0.2.0`. -The current `@pegma/support-desk-ai@0.2.8` pins exact KB `0.1.6` runtime +The published `@pegma/support-desk-ai@0.2.9` and prepared `0.2.10` metadata pin exact KB `0.1.8` runtime dependencies and bounded turn jobs in the existing ticket partition. The base application remains independent of KB/providers. Read the [coordination guide](ASSISTANT_COORDINATION.md) and @@ -35,7 +42,7 @@ gates are recorded in the publication receipt above. Qualified storage adapter releases include `@pegma/storage-cloudflare-d1@0.4.6` and `@pegma/storage-dynamodb@0.4.5`; the [storage receipts](HOST_COMPOSITION.md#qualified-storage-adapters) bind their signed source, verification jobs, and unchanged Core/Azure `0.4.0` -archives. The standalone authoring recipe selects all four KB `0.1.6` +archives. The historical standalone authoring recipe selected all four KB `0.1.6` packages and Agent Access `0.1.1`. Published AI `0.2.1` retains its original KB `0.1.2` dependencies. Each host qualifies its installed graph separately. PG-01 source integration is tracked in @@ -53,7 +60,9 @@ composition, deployment, provider/privacy and client acceptance gates. Task 12 remains pending on both hosts' durable-store production evidence. Provider/ZDR/intermediary verification, deployment applicability mapping, retention/recovery operations, dual-host acceptance, and pilots also remain -open. Source tests do not satisfy these gates. Business-hours calendars, +open. Sessions `0.3.0` is public; final site integration and complete host +Workers Free 50/100 invocation/CPU acceptance remain pending. Source tests do +not satisfy these gates. Business-hours calendars, presence, provider adapters, and operation remain host responsibilities. **Initial reference applications:** retiregolden.org for paid customer support @@ -437,8 +446,8 @@ Current package work and remaining candidates: - [x] web attachment metadata and host blob port (Task 14, PR #32, `84dfcb2`); - [x] clean-only authorized downloads and digest-bound scan states (Task 14); - inbound attachment extraction remains deferred; host MIME adapters drop it; -- [x] bounded staff canned responses and one-message macros (Task 15 source - candidate; unpublished, deployment-owned catalog and explicit staff send); +- [x] bounded staff canned responses and one-message macros (Task 15, + included in published `0.2.9`; deployment-owned catalog and explicit staff send); - [x] staff-managed tags from a bounded host allowlist (Task 13); - category changes beyond the launch allowlists; - [x] revision-based collision hints for staff (Task 13); @@ -462,10 +471,11 @@ producers' release preparation were merged. The four KB packages had strictly verified trusted `0.1.4` releases and Agent Access had verified `0.1.1`, closing SD-02's publication prerequisite at that checkpoint. -The current standalone authoring recipe selects all four strictly verified KB +The historical standalone authoring recipe selected all four strictly verified KB `0.1.6` packages and Agent Access `0.1.1` from the [producer handoff](HOST_COMPOSITION.md#kb-authoring-producers). Released -Support Desk AI `0.2.8` pins exact KB application/contracts `0.1.6`. Older +Support Desk AI `0.2.9` pins exact KB application/contracts `0.1.8`. Historical +`0.2.8` retains its `0.1.6` pins. Older `0.2.1`/KB `0.1.2` manifests remain immutable. Host adoption requires its own reviewed exact registry set. Actual two-host existing-login/current-Admin consent and Codex, Claude Code, @@ -497,7 +507,7 @@ human handoff, reviewed learning, and safe engineering follow-up. **Source status:** SD-01 through SD-05 are merged, covering handling/handoff, optional answer coordination, resolution learning, engineering export, and release follow-up. They first shipped in verified synchronized `0.2.0` and -remain in current `0.2.8`, whose publication receipt is linked above. This phase's +remain in current `0.2.9`, whose publication receipt is linked above. This phase's host/production acceptance remains open. See [assistant coordination](ASSISTANT_COORDINATION.md). @@ -673,8 +683,8 @@ After the launch definition, the post-MVP queue in [`BUILDOUT.md`](BUILDOUT.md#post-mvp-queue) sequences the remaining full-featured support-desk work. Task 13 lifecycle extras (PR #29) and Task 14 attachments (PR #32) are merged and shipped. Task 15's staff-only audited canned -responses and one-message macros are implemented in the current source -candidate without publication. Remaining package work starts with customer +responses and one-message macros are included in published `0.2.9`. +Remaining package work starts with customer self-service contract polish, rate-limit and abuse composition notes, and the approved standalone KB and evaluated customer-visible AI support work in [`KNOWLEDGE_AI_PLAN.md`](KNOWLEDGE_AI_PLAN.md), which supersedes the earlier diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 81e19cf..e8778d0 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,12 +1,43 @@ # Release notes + + +## 0.2.10 — final customer-success and resolution-evidence guards + +Release preparation, 2026-11-13: all five package versions and exact internal +Support pins select `0.2.10`. The root remains private at `0.0.0`; exact public +KB application/contracts `0.1.8`, `zod@4.6.7` and other external dependencies +remain unchanged. This preparation is not a publication receipt. Use the +[release operations](RELEASING.md#source-version-0210) and dated verified +receipts for publication status. + +`confirmCustomerSuccess` and `submitResolutionEvidence` accept an additive +optional third argument, respectively `ConfirmCustomerSuccessOptions` and +`SubmitResolutionEvidenceOptions`, with `signal` and `verifyBeforeCommit`. +Their existing two-argument calls and return types remain valid. The trusted +host callback runs after asynchronous product/test/KB proof and mutation +planning, freshly for each actual conditional-write attempt. Its optional +synchronous literal-true assertion and the original signal, actor/grant, +required permissions and customer ownership checks close the final commit +boundary. No asynchronous SDK work follows the final awaited host callback. + +Exact accepted commands still recover their original receipt under current +permissions, and customer ownership where required, before obsolete proofs, +the optional final guard or an aborted signal. Cancellation prevents a new +mutation; it cannot undo an accepted transaction. No permission, record +migration, host access port, paid attempt or automatic retry is added. +See [the public options contract](RESOLUTION_LEARNING.md#final-human-success-and-evidence-guards-0210) +and [upgrade guidance](UPGRADING.md#0210-final-success-and-evidence-guards). +Host integration, deployment, provider/privacy, requested-client and pilot +acceptance retain their separate gates. + -## 0.2.9 candidate — per-attempt engineering worker observations +## 0.2.9 — per-attempt engineering worker observations, 2026-11-13 -All five local package versions and exact internal Support pins target -unpublished `0.2.9`. Exact KB application/contracts now pin verified public -`0.1.8`, requiring fresh SDK graph qualification. Published `0.2.8` retains KB `0.1.6`; Authorization Core `0.4.0` +All five synchronized packages and exact internal Support pins are published +and strictly verified at `0.2.9`. Exact KB application/contracts pin public +`0.1.8`; fresh SDK graph qualification passed. Historical `0.2.8` retains KB `0.1.6`; Authorization Core `0.4.0` remains unchanged. The AI manifest adds exact direct `zod@4.6.7` and `@pegma/storage-core@0.4.0` dependencies. The root stays private at `0.0.0`. @@ -29,8 +60,11 @@ activation. See the [worker observation contract](ENGINEERING_EXPORT.md#candidate-029-worker-observations) and [upgrade guidance](UPGRADING.md#unpublished-029-engineering-worker-observations). -These source changes do not establish a complete host query/CPU budget, -provider qualification or registry publication. +The [dated publication receipt](RELEASING.md#verified-029-publication-2026-11-13) +binds the signed source, complete release workflow, strict public verification +and permanent assets. The Sessions `0.3.0` prerequisite is also public. Final +site integration, complete host query/CPU acceptance, provider/privacy and +requested-client qualification, and pilots remain pending. ### Staff canned responses (Task 15 source addition) @@ -68,7 +102,7 @@ Inline reconciliation retains its bounded retry behavior. ### Optional OpenRouter entry -The candidate adds `@pegma/support-desk-ai/openrouter` while keeping the AI root +The release adds `@pegma/support-desk-ai/openrouter` while keeping the AI root provider-neutral. Both independent-check constructors require an explicit second logical host string and current host callbacks. Pegma's existing `ic2` encoding and `pegma.dev.support-independent-checks.v2` MAC domain are preserved. @@ -109,11 +143,11 @@ precedes observation, and omitted observation retains legacy verification. See the [physical invocation contract](ENGINEERING_FOLLOWUP.md#candidate-029-followup-invocations). KB `0.1.8` supplies the optional authoring `publishedSearchObservations` -capability for bounded background new-create comparison. The candidate retains +capability for bounded background new-create comparison. The release retains complete/partial/unavailable handling, current resource/authority confirmation and exact historical ACK recovery. See the [comparison contract](RESOLUTION_LEARNING.md#candidate-scoped-comparison-evidence) and [SD05 adapter contract](../packages/ai/README.md#release-follow-up-provider-ports). -Combined SDK and host qualification remain pending. +SDK publication is qualified; complete host qualification remains pending. @@ -121,8 +155,8 @@ Combined SDK and host qualification remain pending. All five synchronized `0.2.8` packages are published and strictly verified. Its published AI package retains exact KB application/contracts `0.1.6`. -The unpublished `0.2.9` candidate retains these controls and pins verified public -KB `0.1.8`, requiring fresh SDK graph qualification. See the +The later verified `0.2.9` release retains these controls and pins public +KB `0.1.8`. See the [publication receipt](RELEASING.md#verified-028-publication-2026-11-12). Optional `EngineeringMutationOptions` add caller cancellation and a trusted late `verifyBeforeCommit` guard to non-post follow-up mutations. Observation, diff --git a/docs/RELEASING.md b/docs/RELEASING.md index e1f0ad7..82d1a6c 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,10 +1,79 @@ # Release operations + + +## 0.2.10 release preparation: 2026-11-13 + +The synchronized source manifests and internal Support pins select `0.2.10`; +the repository root stays private at `0.0.0`. This patch adds optional final +host guards/cancellation to customer success confirmation and resolution +evidence submission. Exact KB application/contracts `0.1.8`, `zod@4.6.7` and +other external dependency selections are unchanged. See the +[release notes](RELEASE_NOTES.md#0210-final-success-evidence-guards). + +Source preparation does not establish publication. The combined source must +pass the normal Node 22/24 format, types, complete runtime tests, examples, +release-pack and clean-consumer gates, configured review and CI before the +protected signed-tag/OIDC release flow below. Its completed workflow, registry +verification and permanent original assets must supply a new dated receipt. +Consult [published releases](https://github.com/pegma-dev/support-desk/releases) +for authoritative release status. The verified `0.2.9` receipt and all earlier +artifacts remain preserved below; SDK publication does not close host +deployment, complete invocation/CPU, provider/privacy, requested-client or pilot +acceptance. + + + +## Verified 0.2.9 publication: 2026-11-13 + +At this publication checkpoint, the verified synchronized release was **0.2.9** for all five public +packages. The [protected signed `v0.2.9` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.9) +binds source [`4d080cb11fa36a35ece2f21c51ee14812339eaf6`](https://github.com/pegma-dev/support-desk/commit/4d080cb11fa36a35ece2f21c51ee14812339eaf6) +and tag object `ba6b4dfcbd304a1b016e2b39a6df986126573420`. +[Run 43366221098, attempt 1](https://github.com/pegma-dev/support-desk/actions/runs/43366221098/attempts/1) +completed all seven jobs and 94 steps successfully. Each Node22/24 release lane +passed 4,061 tests across 93 files with zero skips. All five packages were +published in attempt one; none was skipped and no recovery, repack or retag was +required. + +The hosted verifier and an independent exact-source invocation passed original +registry bytes and dependencies, native npm `11.18.0` signatures, +Sigstore/TUF/source provenance and clean scripts-disabled public installation +and entry-point imports. All five npm `latest` tags resolved to `0.2.9` at verification; AI's +registration-only `bootstrap: 0.1.1` remains separate. Optional AI pins exact +public KB application/contracts `0.1.8`. + +Original prepared artifact `14011470401` is retained byte-for-byte. Its ZIP +SHA-256 is `14507d4610790b2b3222d88074648a37eb896c8127d03ec2810786396dacead7`; +the independently recorded manifest SHA-256 is +`fd08a7f6d50853bc6432cd79a57ed433337e3afff6d85bccb0d3f9786a8013d3`. + +The six permanent public assets passed authenticated API/digest checks and +authenticated and anonymous exact-byte downloads before promotion to GitHub +Latest at 05:06:16 UTC: + +| Public asset | Asset ID | Bytes | SHA-256 | +| --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ------ | ------------------------------------------------------------------ | +| [package-manifest.json](https://github.com/pegma-dev/support-desk/releases/download/v0.2.9/package-manifest.json) | `742349609` | 34592 | `fd08a7f6d50853bc6432cd79a57ed433337e3afff6d85bccb0d3f9786a8013d3` | +| [prepared-artifact.json](https://github.com/pegma-dev/support-desk/releases/download/v0.2.9/prepared-artifact.json) | `742349649` | 4314 | `5f0b947d21eb6333564e8603952a52ad8a62048ba0e2c8fa43fa060b2537cb59` | +| [qualified-release-notes.md](https://github.com/pegma-dev/support-desk/releases/download/v0.2.9/qualified-release-notes.md) | `742349681` | 1899 | `627268f824fc671fdc992ef47e471c1687df3f46a73c546bb47b089a2e33417c` | +| [registry-verification.json](https://github.com/pegma-dev/support-desk/releases/download/v0.2.9/registry-verification.json) | `742349725` | 17890 | `1ea0c8897c58f1d3223c998650dd6ba4507be2cf97b365ad9117a995e6d75630` | +| [support-desk-release-43366221098-1.zip](https://github.com/pegma-dev/support-desk/releases/download/v0.2.9/support-desk-release-43366221098-1.zip) | `742349762` | 692915 | `14507d4610790b2b3222d88074648a37eb896c8127d03ec2810786396dacead7` | +| [verification-job.json](https://github.com/pegma-dev/support-desk/releases/download/v0.2.9/verification-job.json) | `742349812` | 2925 | `2f913b97c657e1523e31c91263ec5b79a53e6378d6bc371e7827490e2ae60969` | + +The release adds opt-in durable release-follow-up check phases and bundle +observations, corrects approval renewal and deferred receipt expiry, and screens +the complete independent-check payload for private ticket text. The Sessions +`0.3.0` prerequisite is also public. SDK publication leaves final site +integration, host deployment, complete Workers Free 50/100 invocation/CPU +acceptance, provider/privacy and requested-client acceptance, and supervised +pilots pending. Earlier receipts and original archives remain unchanged. + ## Verified 0.2.8 publication: 2026-11-12 -The current verified synchronized release is **0.2.8** for all five public +The verified synchronized release on this date was **0.2.8** for all five public packages. The [signed `v0.2.8` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.8) binds source [`e87381d547506ff5ebe8f5d92703a467647c2dce`](https://github.com/pegma-dev/support-desk/commit/e87381d547506ff5ebe8f5d92703a467647c2dce) and tag object `995634e2347f9fe037e643051d8170d3021d44e9`. @@ -13,7 +82,7 @@ completed all seven jobs and 94 steps, including 3,355 tests across 72 files with zero skips on each Node22/24 lane. It published all five packages and skipped none. Independent native npm `11.18.0` signature and Sigstore/source verification passed before clean public entry-point imports. All five npm -`latest` tags resolve to `0.2.8`; AI's registration-only `bootstrap: 0.1.1` +`latest` tags resolved to `0.2.8` at verification; AI's registration-only `bootstrap: 0.1.1` remains separate. Original prepared artifact `13920290093` is retained byte-for-byte. Its ZIP @@ -36,8 +105,8 @@ controls and callback-scoped reassessment/post observations, retaining current proof, authority and exact ACK recovery. Exact KB application/contracts `0.1.6` remain unchanged. This qualifies SDK publication; host deployment, privacy, provider, client and complete invocation/CPU acceptance remain separate. -Earlier releases, receipts and original archives remain unchanged. The local -`0.2.9` engineering-worker candidate below is not published. +Earlier releases, receipts and original archives remain unchanged. The +prepublication `0.2.9` source checkpoint below is retained as history. ## Historical 0.2.7 publication: 2026-11-11 @@ -71,16 +140,19 @@ SDK publication does not establish host deployment, privacy, client or pilot acceptance. Earlier `0.2.6` and older releases retain their immutable artifacts and original dependency pins. -## Source version 0.2.9 + + +## Historical source preparation for 0.2.9 -All five local manifests and exact internal Support pins target unpublished +Before the verified publication recorded above, all five local manifests and +exact internal Support pins targeted then-unpublished `0.2.9`. Optional per-attempt engineering model planning/completion, proposal and dispatch observations share the existing guarded mutation kernels. Fresh proof, authority, Source/Work opaque-version confirmation, exact ACK recovery and legacy structural-port fallbacks remain. See the [candidate notes](RELEASE_NOTES.md#029-engineering-worker-observations) and [worker contract](ENGINEERING_EXPORT.md#candidate-029-worker-observations). -The candidate pins exact verified public KB application/contracts `0.1.8`. +The candidate pinned exact verified public KB application/contracts `0.1.8`. All four KB packages passed strict native registry/source/provenance and public consumer verification at 22:49:06 UTC on 2026-11-12 from signed source `04d07b66cac18b7f6e0ca1530714878f3d66084d`. The completed @@ -90,7 +162,8 @@ retains original preparation artifact `13989866818` and manifest SHA-256 The [KB `0.1.8` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.8) retains the [strict public receipt](https://github.com/pegma-dev/knowledge-base/releases/download/v0.1.8/registry-verification.json), SHA-256 `22888dada71e6723d3852d2509adbd5392ec598ad11d7ccece3373451473cb6c`. -The changed SDK composition remains unpublished pending fresh qualification. +At this checkpoint, the changed SDK composition remained unpublished pending +fresh qualification; the dated `0.2.9` receipt above closes that publication gate. ### Historical KB 0.1.7 qualification @@ -114,9 +187,10 @@ on the same date. Release `443299806` retains original preparation artifact The API digests match these identities. An anonymous receipt download also matched the retained receipt bytes and digest. -The changed SDK dependency graph requires fresh qualification. Published Support Desk `0.2.8` and its exact KB -`0.1.6` pins remain unchanged. Keep hosts on verified published artifacts -until this candidate is merged, published and qualified. +At this checkpoint, the changed SDK dependency graph required fresh +qualification. Published Support Desk `0.2.8` and its exact KB `0.1.6` pins +remained unchanged. Hosts stayed on verified published artifacts while this +candidate awaited merge, publication and qualification. No candidate pack, copied source, local archive or override substitutes for a production dependency. The root remains private at `0.0.0`. @@ -656,8 +730,8 @@ SD-06, and a clean memory consumer does not certify a host's durable migration. After the reviewed release PR is merged and every current-head gate is green, the authorized maintainer creates the protected signed annotated stable tag at the exact `origin/main` commit, pushes it, and creates its verified GitHub -release. The current verified release identity is `v0.2.8`; the earlier -`v0.2.7`, `v0.2.6`, +release. The current verified release identity is `v0.2.9`; the earlier +`v0.2.8`, `v0.2.7`, `v0.2.6`, `v0.2.5`, `v0.2.4`, `v0.2.3`, `v0.2.2`, `v0.2.1` and SD-06 `v0.2.0` identities remain historical. Do not create a GitHub release for `v0.1.1-ai-bootstrap`. diff --git a/docs/RESOLUTION_LEARNING.md b/docs/RESOLUTION_LEARNING.md index 9cd59c5..3b6f53c 100644 --- a/docs/RESOLUTION_LEARNING.md +++ b/docs/RESOLUTION_LEARNING.md @@ -3,16 +3,19 @@ SD-03's source merged in [PR #39](https://github.com/pegma-dev/support-desk/pull/39) and first shipped in the verified synchronized [`0.2.0` release](RELEASING.md#verified-sd-06-publication-2026-11-08). -The current synchronized release is `0.2.8`; see its -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +The dated `0.2.9` +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13) records +the verified public graph. Source metadata now prepares synchronized `0.2.10`; +see [release status](RELEASING.md#source-version-0210) before host adoption. The ticket application implements enrollment, structured resolution evidence, durable work, exact staff review, invalidation, withdrawal, and reconciliation records. The optional AI package adds bounded model processing, KB draft delivery, exact staff review, and source retirement/reconciliation through `createSupportDeskLearning`, with read-only callbacks from -`createSupportDeskLearningSourceVerifier`. The current AI `0.2.8` release +`createSupportDeskLearningSourceVerifier`. The published AI `0.2.9` release consumes the application and contracts packages from the verified -[KB `0.1.6` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6). +[KB `0.1.8` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.8). +The historical AI `0.2.8` graph retains exact KB `0.1.6`. The initial SD-03 release consumed [KB `0.1.2`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.2). SDK validation and publication do not establish host activation. No host has @@ -25,10 +28,58 @@ durable layout and producer prerequisites in the [SD-03 collection checkpoint](COLLECTIONS.md#sd-03-resolution-learning-layout-and-api-checkpoint). The base application has no KB or model-provider dependency. -Unpublished `0.2.9` adds [opt-in staged draft delivery](#opt-in-staged-draft-delivery-029-candidate). +Published `0.2.9` adds [opt-in staged draft delivery](#opt-in-staged-draft-delivery-029-candidate). Its complete Native host qualification under 50 D1 calls and 100 SQL parameters remains pending. + + +## Final human success and evidence guards (0.2.10) + +`confirmCustomerSuccess` and `submitResolutionEvidence` add optional third +arguments named `ConfirmCustomerSuccessOptions` and +`SubmitResolutionEvidenceOptions`. Their public declarations are: + +```ts +interface ConfirmCustomerSuccessOptions { + readonly signal?: AbortSignal; + readonly verifyBeforeCommit?: () => + void | (() => true) | Promise true)>; +} + +interface SubmitResolutionEvidenceOptions { + readonly signal?: AbortSignal; + readonly verifyBeforeCommit?: () => + void | (() => true) | Promise true)>; +} +``` + +Both are exported by the application package. Existing two-argument calls +remain valid, with unchanged `CustomerTicketView` and +`ResolutionLearningSourceResult` return types. This is a contract declaration, +not a complete host composition example. + +The host callback is a trusted, read-only check of the original live browser +session and current purpose-specific authority, including entitlement where +the host requires it. It runs after all asynchronous product/test/KB proof, +reads and mutation planning, freshly for each actual CAS attempt. It may +return a synchronous assertion that must return the literal `true` at the +conditional transaction boundary. No asynchronous SDK work follows the final +awaited callback. The SDK closes with that assertion, the original signal, +captured actor/full serialized grant and required permissions; customer +confirmation also checks ticket ownership. A callback is not an access grant +and must not mutate the supplied context or perform side effects. + +An aborted signal prevents new writes, including abort during product, test or +guard waits. It cannot roll back an already committed transaction. Exact +accepted-command recovery still requires current original permissions and, +for customer confirmation, ticket ownership; it precedes obsolete product/test +proof, the optional final guard and abort checks. Keep the original actor, +command identity and packet after an unknown acknowledgement. A lost ACK is +not permission to create another command or paid attempt. These options add +no role, storage/access port, record migration or model call. Publication and +host qualification remain governed by the dated release and host receipts. + ## Enrollment and working facts Learning is a separate opt-in from assistant answering. @@ -289,7 +340,7 @@ the start of the invocation, including time spent awaiting verification ports. ### Candidate scoped comparison evidence -The unpublished `0.2.9` OpenRouter controller requires genuine comparison +The published `0.2.9` OpenRouter controller requires genuine comparison evidence before signing a new-create check. Selection carries the actual bounded published matches, explicit draft versions and configured scope into the exact request. These are hints, not a completeness assertion. A caller's diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index e0a6406..63fc3de 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -1,8 +1,10 @@ -# Upgrading to the synchronized 0.2.8 release +# Upgrading synchronized Support Desk packages -`0.2.8` is the current verified published synchronized release. Hosts retain -their own deployment and acceptance gates. See the -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +Source preparation, 2026-11-13, selects synchronized `0.2.10`. Verify publication +through [release operations](RELEASING.md#source-version-0210) before adopting +its packages. The verified `0.2.9` +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13) remains +the dated prior checkpoint; host deployment and acceptance gates are separate. The original SD-06 `0.2.0` release has its separate [historical receipt](RELEASING.md#verified-sd-06-publication-2026-11-08). The original four Support Desk packages were published at `0.1.1`. Before @@ -18,20 +20,55 @@ registry application dependency lacks the new source exports. The five local bootstrap tarballs prove an isolated source assembly, not a usable registry dependency tree. -## Unpublished 0.2.9 KB 0.1.8 alignment - -The candidate AI manifest and repository development pins now select exact -verified public KB application/contracts `0.1.8`. Use normal registry resolution -and a frozen install, then qualify the changed candidate graph on Node 22/24. -Existing `0.2.9`/KB `0.1.6` results do not qualify this dependency alignment. - -The current verified Support Desk `0.2.8` tuple retains exact KB `0.1.6`. -All five candidate versions and internal Support pins remain `0.2.9`; the root -remains private at `0.0.0`. This alignment changes no Support Desk runtime + + +## 0.2.10 final success and evidence guards + +Synchronize all five public package versions and exact internal Support pins. +The optional AI package and repository development pins retain exact public KB +application/contracts `0.1.8`; `zod@4.6.7` and other external selections are +unchanged. The root remains private at `0.0.0`. + +Forward the optional third argument on `confirmCustomerSuccess` and +`submitResolutionEvidence` through host adapters. Its exported type is +`ConfirmCustomerSuccessOptions` or `SubmitResolutionEvidenceOptions`, with +`signal?: AbortSignal` and a read-only `verifyBeforeCommit` callback that may +return a synchronous literal-true assertion. See the +[exact declarations and commit/recovery contract](RESOLUTION_LEARNING.md#final-human-success-and-evidence-guards-0210). +Return types and existing two-argument calls remain unchanged. + +Supply the original browser/entitlement guard for new host mutations, after +body admission. The SDK awaits it after asynchronous proof/planning, freshly +on every actual CAS attempt, then makes its final synchronous checks without +another SDK await. An abort prevents new acceptance and does not undo a +commit. Do not place receipt lookup behind an obsolete product/test proof or +an already aborted signal: exact accepted receipts recover first under current +original permissions and customer ownership where required. Preserve the +original command after an unknown ACK. No record migration, permission, +storage/access port, paid retry or automatic activation is introduced. +Qualify the combined source and each host independently; metadata and type +checks alone do not establish the runtime guard or deployed-session behavior. + + + +## Published 0.2.9 KB 0.1.8 alignment + +The published `0.2.9` AI manifest and repository development pins select exact +verified public KB application/contracts `0.1.8`. Its +[dated release receipt](RELEASING.md#verified-029-publication-2026-11-13) records +strict qualification of that graph. Use normal registry resolution and frozen +installs. Earlier `0.2.9`/KB `0.1.6` source-checkpoint results did not qualify +this dependency alignment. + +The historical verified Support Desk `0.2.8` tuple retains exact KB `0.1.6`. +All five published `0.2.9` versions and internal Support pins advanced together; +the root stayed private at `0.0.0`. This alignment changed no Support Desk runtime source, API surface, record layout or host activation decision. Earlier release artifacts and receipts keep their original identities. -## Unpublished Task 15 canned responses + + +## Task 15 canned responses Omitting `cannedResponses` preserves manual staff replies/notes and their original fingerprints. Hosts may supply a bounded deployment catalog and explicitly pass @@ -45,13 +82,15 @@ The existing reply/note Audit details gain only template ID/version on selected uses. Keep catalog versions immutable across deployments. Withdrawn definitions refuse new uses; exact accepted commands replay under current permissions even after withdrawal. Do not remove or change their selection when retrying an -uncertain commit. This is source-only work with unchanged package versions; -verified publication and host acceptance remain required for production use. +uncertain commit. Use verified published artifacts and keep host acceptance +separate from source readiness for production use. See [bounds and send semantics](HOST_COMPOSITION.md#staff-canned-responses-task-15-source-candidate). -## Unpublished 0.2.9 engineering worker observations + + +## Published 0.2.9 engineering worker observations -All five candidate versions and internal Support pins advance together. The +All five published `0.2.9` versions and internal Support pins advanced together. The optional application methods are `prepareEngineeringModelPlanned`, `prepareEngineeringModelObserved`, `completeEngineeringModelObserved`, `prepareEngineeringProposalObserved` and `beginEngineeringDispatchObserved`. @@ -79,7 +118,9 @@ after returning; forwarding an observation does not certify an adapter's later awaits or confer permissions. Completion ACK recovery preserves a current held or superseded result instead of reporting a candidate. -## Unpublished 0.2.9 staged learning delivery + + +## Published 0.2.9 staged learning delivery Omitting `deliveryMode` preserves inline delivery. To select `deliveryMode: 'staged'`, forward the exact SDK-owned @@ -99,8 +140,8 @@ composition uses deferred checks and receipt-only verification in these phases. Both inline and staged completion perform final policy/receipt/configuration checks after late KB reads. Current Source, role, target and opaque-version fences still apply. See [the staged contract](RESOLUTION_LEARNING.md#opt-in-staged-draft-delivery-029-candidate). -The candidate is unpublished and complete Native Workers Free 50/100 -qualification remains pending. +SDK publication does not establish complete Native Workers Free 50/100 host +qualification, which remains pending. The same staged option bounds `reconcileSource` to one unconfirmed destination per invocation. A retirement attempt yields to later physical readback and @@ -108,7 +149,9 @@ verified reconciliation, including after an unknown ACK. Keep scheduling the existing reconciliation result under fresh retirement authority while durable destinations remain pending. Inline reconciliation retains its bounded retries. -## Unpublished 0.2.9 follow-up version reads + + +## Published 0.2.9 follow-up version reads Closing follow-up version checks start up to five independent Store reads together and wait for the whole wave to settle. Results retain their original @@ -120,7 +163,9 @@ the started wave. Current permission, proof, version and commit guards remain. Include every started read in host invocation budgets and measure latency on the actual adapter. -## Unpublished 0.2.9 optional OpenRouter entry + + +## Published 0.2.9 optional OpenRouter entry Import provider adapters explicitly from `@pegma/support-desk-ai/openrouter`. The AI root remains provider-neutral. Its manifest declares exact direct @@ -166,10 +211,10 @@ Structural ports may omit it to retain the full legacy path. Do not replace receipt recovery or fresh proof with retained observation data. See the [follow-up contract](ENGINEERING_FOLLOWUP.md#candidate-028-followup-host-guards). -Use the verified `0.2.8`/KB `0.1.6` tuple; `0.2.9` remains an unpublished -candidate pinning exact verified public KB `0.1.8` and requiring fresh SDK -dependency qualification. All five candidate versions/internal -pins advance together. No record migration is added. +The dated verified `0.2.9`/KB `0.1.8` tuple supersedes the historical +`0.2.8`/KB `0.1.6` checkpoint for producer adoption. Source preparation for +`0.2.10` retains the same external graph; it requires its own combined-source +release gates and publication receipt. No record migration is added. @@ -415,8 +460,8 @@ boundaries before exposing the review surface. ## Rehearse the actual 0.1.1-to-0.2.0 upgrade The SD-06 rehearsal below is retained as historical migration evidence. For -current `0.2.8` adoption, repeat the rehearsal against the exact selected `0.2.8` -artifacts and record a new receipt; a `0.2.0` result does not qualify changed +any later adoption, repeat the rehearsal against the exact selected verified +published artifacts and record a new receipt; a `0.2.0` result does not qualify changed artifacts or a host's durable-store migration. The required migration proof starts with records produced by the actual diff --git a/package.json b/package.json index 3e98862..f04146c 100644 --- a/package.json +++ b/package.json @@ -38,9 +38,9 @@ "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-ai": "0.2.9", - "@pegma/support-desk-application": "0.2.9", - "@pegma/support-desk-templates": "0.2.9", + "@pegma/support-desk-ai": "0.2.10", + "@pegma/support-desk-application": "0.2.10", + "@pegma/support-desk-templates": "0.2.10", "@types/node": "^26.6.6", "azurite": "^3.37.0", "prettier": "^3.9.10", diff --git a/packages/ai/package.json b/packages/ai/package.json index ac58d7e..9e3c59f 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-ai", - "version": "0.2.9", + "version": "0.2.10", "description": "Optional bounded, provider-neutral Support Desk answer coordinator.", "license": "MIT", "type": "module", @@ -42,7 +42,7 @@ "@pegma/knowledge-base-application": "0.1.8", "@pegma/knowledge-base-contracts": "0.1.8", "@pegma/spine": "0.1.2", - "@pegma/support-desk-application": "0.2.9", + "@pegma/support-desk-application": "0.2.10", "@pegma/storage-core": "0.4.0", "zod": "4.6.7" } diff --git a/packages/application/README.md b/packages/application/README.md index 2af7ff7..7b65ea8 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -1,13 +1,27 @@ # @pegma/support-desk-application -The local synchronized source version is unpublished `0.2.9`. It adds optional -per-attempt engineering model-planning/completion, proposal and dispatch -observations through the existing guarded kernels. Current authority, fresh -proof and opaque-version checks remain; older structural ports keep their -standalone fallback. See the [candidate notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) +Source preparation, 2026-11-13, selects synchronized `0.2.10`. Verify publication +through the [release operations](../../docs/RELEASING.md#source-version-0210) +before host adoption. The patch adds optional final browser/authority guards +and cancellation to customer success confirmation and resolution evidence. +`ConfirmCustomerSuccessOptions` and `SubmitResolutionEvidenceOptions` are +optional third arguments with `signal` and `verifyBeforeCommit`; existing +two-argument calls and return types stay valid. The host callback follows all +asynchronous proof/planning, freshly per CAS attempt, with its optional +synchronous assertion at the transaction boundary. Exact accepted receipts +recover first under current permissions and customer ownership where required, +before obsolete proof, guard or abort checks. See the +[exact options and recovery contract](../../docs/RESOLUTION_LEARNING.md#final-human-success-and-evidence-guards-0210) +and [release notes](../../docs/RELEASE_NOTES.md#0210-final-success-evidence-guards). + +The verified `0.2.9` publication added optional per-attempt engineering +model-planning/completion, proposal and dispatch observations through existing +guarded kernels. Current authority, fresh proof and opaque-version checks +remain; older structural ports keep their standalone fallback. See the +[dated notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) and [worker contract](../../docs/ENGINEERING_EXPORT.md#candidate-029-worker-observations). -The candidate exposes the optional SDK-owned +The application exposes the optional SDK-owned `stagedResolutionLearningDelivery` capability with its exact own `prepare`, `write` and `complete` methods. It retains one immutable KB request, historical acknowledgement, current target checks and atomic claim release at delivery @@ -15,10 +29,9 @@ checkpoints. Fresh authority, Source/Work/Ticket versions, claim and deadline fences remain required. The AI option `deliveryMode: 'staged'` requires the original capability and methods before claiming work. Existing inline delivery remains available to structural ports. See [staged draft delivery](../../docs/RESOLUTION_LEARNING.md#opt-in-staged-draft-delivery-029-candidate). -The source candidate is unpublished and current Native Workers Free 50/100 -qualification remains pending. +Complete Native Workers Free 50/100 host qualification remains pending. -The candidate also accepts optional `EngineeringMutationOptions` on +The application also accepts optional `EngineeringMutationOptions` on `submitEngineeringFollowupRetestResult` after its existing command. New writes retain current retest evidence, signal and final host guards. Exact accepted receipts recover under current authorization before new mutable proof. @@ -27,7 +40,7 @@ See the [retest controls](../../docs/ENGINEERING_FOLLOWUP.md#candidate-029-retes Authorized customer ticket services and provider-neutral durable outbox records for Support Desk. The host supplies an `@pegma/storage-core` `Store` and a trusted Authorization Core access context. -The unpublished Task 15 source addition accepts optional `cannedResponses` +The Task 15 source addition accepts optional `cannedResponses` configuration and exposes `listCannedResponses` and pure `renderCannedResponse`. Existing explicit staff reply/note commands accept `cannedResponse` selections with exact preview validation and transactional content-free Audit provenance. @@ -35,11 +48,11 @@ See [bounds, permissions and replay](../../docs/HOST_COMPOSITION.md#staff-canned The host server supplies `correlationId` on commands; the application validates and propagates it and never generates it. -The current verified published synchronized release is `0.2.8` and includes +The verified `0.2.9` publication includes changes beyond the immutable `0.1.0`/`0.1.1` artifacts. SD-01 first shipped handling/handoff foundations in `0.2.0` without model generation or a KB -dependency. See the current -[publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). +dependency. See its dated +[publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). Host adoption retains its own activation gates; source checkouts and overwritten registry versions are not release substitutes. @@ -47,7 +60,7 @@ The published synchronized `0.2.1` patch groups independent Store reads for assistant answering while retaining current authority, ticket and turn fences. This package gains no KB or provider dependency. The historical [0.2.1 receipt](../../docs/RELEASING.md#verified-021-publication-2026-11-10) -records that patch's exact artifacts; current `0.2.8` retains those guards. Grouped reads do not establish a universal host query or CPU +records that patch's exact artifacts; later releases retain those guards. Grouped reads do not establish a universal host query or CPU budget. Published `0.2.3` includes the final engineering review guards described in diff --git a/packages/application/package.json b/packages/application/package.json index 7a8cc9f..1cda078 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-application", - "version": "0.2.9", + "version": "0.2.10", "description": "Authorized application services, declared collections, and durable outbox records for Support Desk.", "license": "MIT", "type": "module", @@ -39,7 +39,7 @@ "@pegma/mail": "0.1.1", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-contracts": "0.2.9", - "@pegma/support-desk-core": "0.2.9" + "@pegma/support-desk-contracts": "0.2.10", + "@pegma/support-desk-core": "0.2.10" } } diff --git a/packages/application/src/index.ts b/packages/application/src/index.ts index e199eb3..dcae1eb 100644 --- a/packages/application/src/index.ts +++ b/packages/application/src/index.ts @@ -23,7 +23,12 @@ import { type ResolutionLearningReviewAttemptRecord, } from "./resolution-learning-staged-records.js"; import { auditRecordId, defineAudit, type AuditEvent } from "@pegma/audit"; -import { hasPermission, type AccessContext } from "@pegma/authorization-core"; +import { + hasPermission, + serializeAccessContext, + type AccessContext, +} from "@pegma/authorization-core"; +import { engineeringMutationBoundary } from "./engineering-mutation-guard.js"; import { defineMail, maxMailAttempts, type MailJob } from "@pegma/mail"; import type { Clock, IsoTimestamp, Logger, PrincipalId } from "@pegma/spine"; import { noopLogger } from "@pegma/spine"; @@ -1647,6 +1652,19 @@ export interface ConfirmCustomerSuccessCommand extends RequestPersonCommand { readonly lastSeenVisibleMessageId: MessageId; } +/** Optional live host authority fence for a new customer-success mutation. */ +export interface ConfirmCustomerSuccessOptions { + /** Cancellation prevents a new write; exact accepted receipts remain recoverable. */ + readonly signal?: AbortSignal; + /** + * Read-only current browser/entitlement check after all SDK proof reads, once + * per CAS attempt. A returned synchronous assertion runs at the transaction + * handoff; it must not perform async work. Exact accepted replay skips this. + */ + readonly verifyBeforeCommit?: () => + void | (() => true) | Promise true)>; +} + export interface AttachmentStateCommand { readonly ticketId: string; readonly messageId: string; @@ -1868,6 +1886,7 @@ export interface SupportDeskApplication confirmCustomerSuccess( access: AccessContext, command: ConfirmCustomerSuccessCommand, + options?: ConfirmCustomerSuccessOptions, ): Promise; readCustomerSuccessConfirmations( access: AccessContext, @@ -6220,7 +6239,13 @@ export function createSupportDeskApplication(options: { command: HandlingMutation, operation: HandlingOperation, assistantTurnCommit?: AssistantTurnCommit, + customerSuccess?: { + readonly actorId: PrincipalId; + readonly authorize: () => void; + readonly mutation: ReturnType; + }, ): Promise { + customerSuccess?.authorize(); requireIdentifier(access.principalId, "principalId"); const customer = operation === "request_person" || @@ -6241,6 +6266,7 @@ export function createSupportDeskApplication(options: { const parallel = completion?.kind === "complete" || completion?.kind === "finish"; for (let attempt = 0; attempt < maxConflictAttempts; attempt += 1) { + customerSuccess?.authorize(); const ticketRead = records.getVersioned(ticketKey(command.ticketId)); const duplicateRead = parallel ? prepareRead(() => @@ -6248,6 +6274,7 @@ export function createSupportDeskApplication(options: { ) : undefined; const versioned = await ticketRead; + customerSuccess?.authorize(); if ( versioned?.value.kind !== "ticket" || (customer && !owns(versioned.value.ticket, access.principalId)) @@ -6258,6 +6285,7 @@ export function createSupportDeskApplication(options: { duplicateRead === undefined ? await records.get(commandKey(command.ticketId, command.commandId)) : readValue(await duplicateRead); + customerSuccess?.authorize(); if ( duplicateMatches(duplicate, operation, command.messageId, fingerprint) ) { @@ -6272,6 +6300,7 @@ export function createSupportDeskApplication(options: { throw new SupportDeskConflictError( "Command ID reused with different input", ); + customerSuccess?.mutation?.ensure(); if ( parallel && (ticket.channel !== "web" || @@ -6308,6 +6337,7 @@ export function createSupportDeskApplication(options: { if (operation === "assistant_reply" && !assistantHandlingEnabled) throw new SupportDeskConflictError("Assistant handling is disabled"); const rows = await records.list(command.ticketId); + customerSuccess?.authorize(); enforcePartitionRecordLimit( partitionSizeWithAttachmentReserve(rows), limits.maxRecordsPerTicket, @@ -6595,12 +6625,28 @@ export function createSupportDeskApplication(options: { actions.push(assistantCommit.action); await assistantCommit.verifyBeforeCommit(); } + if (customerSuccess !== undefined) { + // All SDK reads/planning precede the last awaited host authority check. + // A conflict discards this assertion and obtains a fresh one next time. + customerSuccess.authorize(); + const assertCurrent = + customerSuccess.mutation === undefined + ? undefined + : await customerSuccess.mutation.verify(); + customerSuccess.authorize(); + if (!owns(ticket, customerSuccess.actorId)) + throw new SupportDeskNotFoundError(); + assertCurrent?.(); + customerSuccess.authorize(); + customerSuccess.mutation?.ensure(); + } if ((await records.transact(ticket.id, actions)).committed) { await safeProjectQueue(ticket.id); return updated; } } const current = await records.get(ticketKey(command.ticketId)); + customerSuccess?.authorize(); if ( current?.kind !== "ticket" || (customer && !owns(current.ticket, access.principalId)) @@ -6609,6 +6655,7 @@ export function createSupportDeskApplication(options: { const receipt = await records.get( commandKey(command.ticketId, command.commandId), ); + customerSuccess?.authorize(); if ( duplicateMatches(receipt, operation, command.messageId, fingerprint) && receipt?.kind === "command" && @@ -6930,8 +6977,23 @@ export function createSupportDeskApplication(options: { await mutateHandling(access, command, "take_over"); return staffCommandResult(command.ticketId, command.commandId); }, - async confirmCustomerSuccess(access, input) { + async confirmCustomerSuccess(access, input, options) { requirePermission(access, supportPermissions.confirmSuccess); + requireIdentifier(access.principalId, "principalId"); + const actorId = access.principalId; + // A comparison fence for this trusted context, never a live session cache. + const grant = serializeAccessContext(access); + const authorize = (): void => { + requirePermission(access, supportPermissions.confirmSuccess); + if ( + access.principalId !== actorId || + serializeAccessContext(access) !== grant + ) + throw new SupportDeskAuthorizationError( + supportPermissions.confirmSuccess, + ); + }; + const mutation = engineeringMutationBoundary(options); const raw = handlingInput(input, ["lastSeenVisibleMessageId"]); requireIdentifier( boundaryString( @@ -6941,8 +7003,21 @@ export function createSupportDeskApplication(options: { "lastSeenVisibleMessageId", ); const command = raw as unknown as ConfirmCustomerSuccessCommand; - await mutateHandling(access, command, "confirm_customer_success"); - return customerViewAfterChange(access.principalId, command.ticketId); + await mutateHandling( + access, + command, + "confirm_customer_success", + undefined, + { + actorId, + authorize, + mutation, + }, + ); + authorize(); + const view = await customerViewAfterChange(actorId, command.ticketId); + authorize(); + return view; }, async readCustomerSuccessConfirmations(access, ticketId) { requireStaffMutationAccess(access, supportPermissions.auditRead); diff --git a/packages/application/src/resolution-learning-types.ts b/packages/application/src/resolution-learning-types.ts index 4ffdc00..83ec8b1 100644 --- a/packages/application/src/resolution-learning-types.ts +++ b/packages/application/src/resolution-learning-types.ts @@ -408,6 +408,18 @@ export type ResolutionLearningReviewReceipt = }; /** Read-only current authority/configuration/KB target confirmation. */ export type ResolutionLearningCommitGuard = () => void | Promise; +/** Optional live host authority fence for a new resolution-evidence mutation. */ +export interface SubmitResolutionEvidenceOptions { + /** Cancellation prevents a new write; exact accepted receipts remain recoverable. */ + readonly signal?: AbortSignal; + /** + * Read-only current browser/entitlement check after all SDK proof reads, once + * per CAS attempt. A returned synchronous assertion runs at the transaction + * handoff; it must not perform async work. Exact accepted replay skips this. + */ + readonly verifyBeforeCommit?: () => + void | (() => true) | Promise true)>; +} export interface ResolutionLearningReconciliationView { readonly ticketId: TicketId; readonly sourceGeneration: number; @@ -447,6 +459,7 @@ export interface ResolutionLearningApplication { submitResolutionEvidence( access: AccessContext, command: SubmitResolutionEvidenceCommand, + options?: SubmitResolutionEvidenceOptions, ): Promise; readResolutionLearningSource( access: AccessContext, diff --git a/packages/application/src/resolution-learning.ts b/packages/application/src/resolution-learning.ts index 5362cc6..4435de8 100644 --- a/packages/application/src/resolution-learning.ts +++ b/packages/application/src/resolution-learning.ts @@ -1,6 +1,11 @@ import type { supportTicketAuditActions } from "./index.js"; import { createResolutionLearningStagedReviewServices } from "./resolution-learning-staged.js"; -import { hasPermission, type AccessContext } from "@pegma/authorization-core"; +import { + hasPermission, + serializeAccessContext, + type AccessContext, +} from "@pegma/authorization-core"; +import { engineeringMutationBoundary } from "./engineering-mutation-guard.js"; import type { Clock } from "@pegma/spine"; import { MAX_SCAN_PAGE_SIZE, @@ -889,8 +894,22 @@ export function createResolutionLearningServices(deps: Dependencies): { } throw new SupportDeskConflictError(); }, - async submitResolutionEvidence(access, input) { + async submitResolutionEvidence(access, input, mutationOptions) { permission(access, supportPermissions.learningEvidenceSubmit, true); + const actorId = access.principalId; + // A comparison fence for this trusted context, never a live session cache. + const grant = serializeAccessContext(access); + const authorize = (): void => { + permission(access, supportPermissions.learningEvidenceSubmit, true); + if ( + access.principalId !== actorId || + serializeAccessContext(access) !== grant + ) + throw new SupportDeskAuthorizationError( + supportPermissions.learningEvidenceSubmit, + ); + }; + const mutation = engineeringMutationBoundary(mutationOptions); const command = snapshot( fields(input, "evidence command", [ "ticketId", @@ -921,19 +940,19 @@ export function createResolutionLearningServices(deps: Dependencies): { : raw.receipt, "verification reference", ); - const hash = await commandFingerprint( - command, - access.principalId, - "evidence", - ); + const hash = await commandFingerprint(command, actorId, "evidence"); for (let attempt = 0; attempt < deps.maxConflictAttempts; attempt += 1) { + authorize(); const previous = await replay(command, hash); + authorize(); if (previous !== null) return previous; + mutation?.ensure(); const { ticket: versioned, source, rows, } = await load(command.ticketId); + authorize(); const ticket = versioned.value.ticket; if ( ticket.revision !== command.expectedRevision || @@ -954,15 +973,10 @@ export function createResolutionLearningServices(deps: Dependencies): { "Visible solution message missing", ); const now = clock.now(); - const trusted = await context( - ticket, - source.value, - access.principalId, - now, - ); + const trusted = await context(ticket, source.value, actorId, now); let evidence: ResolutionEvidence | null = null; if (command.evidence.kind === "staff_verified_fix") - evidence = { ...command.evidence, actorId: access.principalId }; + evidence = { ...command.evidence, actorId }; else if ( trusted.product !== null && options.testReceipts !== undefined @@ -981,7 +995,7 @@ export function createResolutionLearningServices(deps: Dependencies): { if (test !== null) { const proposed: ResolutionEvidence = { kind: "successful_test", - actorId: access.principalId, + actorId, solutionMessageId: command.evidence.solutionMessageId, test, }; @@ -1038,16 +1052,26 @@ export function createResolutionLearningServices(deps: Dependencies): { deps.audit( command, ticket, - access.principalId, + actorId, now, "support.learning.evidence_recorded", ), receipt(command, hash, result(plan.source)), ]; + // All SDK reads/planning precede the last awaited host authority check. + // A conflict discards this assertion and obtains a fresh one next time. + authorize(); + const assertCurrent = + mutation === undefined ? undefined : await mutation.verify(); + authorize(); + assertCurrent?.(); + authorize(); + mutation?.ensure(); if ((await records.transact(command.ticketId, actions)).committed) return result(plan.source); } const previous = await replay(command, hash); + authorize(); if (previous !== null) return previous; throw new SupportDeskConflictError(); }, diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 6bbae26..b69d82b 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-contracts", - "version": "0.2.9", + "version": "0.2.10", "description": "Provider-neutral ticket and message contracts for Support Desk.", "license": "MIT", "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index 2f0ba82..1bd71ab 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-core", - "version": "0.2.9", + "version": "0.2.10", "description": "Pure ticket creation and workflow transitions for Support Desk.", "license": "MIT", "type": "module", @@ -29,7 +29,7 @@ "directory": "packages/core" }, "dependencies": { - "@pegma/support-desk-contracts": "0.2.9" + "@pegma/support-desk-contracts": "0.2.10" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/templates/package.json b/packages/templates/package.json index 96fb793..5e7d6a7 100644 --- a/packages/templates/package.json +++ b/packages/templates/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-templates", - "version": "0.2.9", + "version": "0.2.10", "description": "Safe, versioned notification templates for Support Desk.", "license": "MIT", "type": "module", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e5b552..020716b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,13 +39,13 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.9 + specifier: 0.2.10 version: link:packages/ai '@pegma/support-desk-application': - specifier: 0.2.9 + specifier: 0.2.10 version: link:packages/application '@pegma/support-desk-templates': - specifier: 0.2.9 + specifier: 0.2.10 version: link:packages/templates '@types/node': specifier: ^26.6.6 @@ -81,7 +81,7 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-application': - specifier: 0.2.9 + specifier: 0.2.10 version: link:../application zod: specifier: 4.6.7 @@ -105,10 +105,10 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-contracts': - specifier: 0.2.9 + specifier: 0.2.10 version: link:../contracts '@pegma/support-desk-core': - specifier: 0.2.9 + specifier: 0.2.10 version: link:../core packages/contracts: @@ -120,7 +120,7 @@ importers: packages/core: dependencies: '@pegma/support-desk-contracts': - specifier: 0.2.9 + specifier: 0.2.10 version: link:../contracts packages/templates: {} diff --git a/tests/customer-success-mutation-guard.test.ts b/tests/customer-success-mutation-guard.test.ts new file mode 100644 index 0000000..ab566f6 --- /dev/null +++ b/tests/customer-success-mutation-guard.test.ts @@ -0,0 +1,474 @@ +import type { CollectionDefinition, Store } from "@pegma/storage-core"; +import { + supportPermissions, + supportRecords, + type ConfirmCustomerSuccessOptions, + type SupportRecord, +} from "@pegma/support-desk-application"; +import { describe, expect, it, vi } from "vitest"; +import { + handlingBarrier, + handlingCustomer as customer, + handlingStaff as staff, +} from "../test/handling-fixtures.js"; +import { + resolutionLearningFixture, + learningStores, +} from "../test/resolution-learning-fixtures.js"; + +type Fixture = ReturnType; + +async function packet(f: Fixture) { + const terminal = await f.terminal(); + return { + ...f.command("guarded-success"), + lastSeenVisibleMessageId: terminal.solutionMessageId, + }; +} + +function caught(promise: Promise) { + return promise.then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); +} + +async function reached( + gate: ReturnType, + pending: Promise, +) { + await Promise.race([ + gate.reached, + pending.then(() => { + throw new Error("Success mutation did not reach its expected barrier"); + }), + ]); +} + +function successTransaction(trace: { + actions: readonly { action: string; value?: unknown }[]; +}) { + return trace.actions.some( + (action) => + action.action !== "delete" && + (action.value as SupportRecord)?.kind === "customer_success", + ); +} + +for (const [backend, createStore] of learningStores) { + describe(`customer success current mutation guard (${backend})`, () => { + it.each(["revoked session", "expired entitlement"] as const)( + "refuses %s observed after the real product await without committing confirmation, Source or Work", + async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + productContext: { + async resolve(context) { + await gate.wait(); + return f.trust.productFor(context); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + let current = true; + const guard = vi.fn(async () => { + if (!current) + throw new Error("Current browser authority unavailable"); + return (): true => true; + }); + const pending = caught( + f.app.confirmCustomerSuccess(customer, input, { + verifyBeforeCommit: guard, + }), + ); + await reached(gate, pending); + expect(guard).not.toHaveBeenCalled(); + current = false; + gate.release(); + const result = await pending; + expect(await f.rows()).toEqual(before); + expect(result).toHaveProperty("error"); + expect(guard).toHaveBeenCalledOnce(); + }, + ); + + it("rechecks an original permission changed during product verification even for legacy calls", async () => { + const access = { ...customer, permissions: [...customer.permissions] }; + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + productContext: { + async resolve(context) { + access.permissions = []; + return f.trust.productFor(context); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + const result = await caught(f.app.confirmCustomerSuccess(access, input)); + expect(await f.rows()).toEqual(before); + expect(result).toMatchObject({ + error: { permission: supportPermissions.confirmSuccess }, + }); + }); + + it("makes the host refresh the last awaited precommit work, with its synchronous proof directly at the handoff", async () => { + const backing = createStore(); + let armed = false; + const events: string[] = []; + const observed: Store = { + collection(definition: CollectionDefinition) { + const actual = backing.collection(definition); + return new Proxy(actual, { + get(object, property) { + const value: unknown = Reflect.get(object, property, object); + if (typeof value !== "function") return value; + return (...args: unknown[]) => { + if (armed && definition.name === supportRecords.name) + events.push(String(property)); + return Reflect.apply(value, object, args); + }; + }, + }); + }, + }; + const f = resolutionLearningFixture(observed); + const input = await packet(f); + armed = true; + const result = await f.app.confirmCustomerSuccess(customer, input, { + async verifyBeforeCommit() { + events.push("host-refresh"); + await Promise.resolve(); + events.push("host-ready"); + return (): true => { + events.push("sync-proof"); + return true; + }; + }, + }); + expect(result.ticket.status).toBe("resolved"); + const ready = events.indexOf("host-ready"); + const transaction = events.indexOf("transact", ready); + expect(ready).toBeGreaterThan(-1); + expect(events.slice(ready + 1, transaction)).toEqual(["sync-proof"]); + expect(transaction).toBe(ready + 2); + expect(f.trust.productCalls).toHaveLength(1); + }); + + it.each(["principal", "permission", "policy", "roles"] as const)( + "rechecks the original %s context after the awaited host callback", + async (change) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const access = { + ...customer, + roles: [...customer.roles], + permissions: [...customer.permissions], + }; + const assertion = vi.fn((): true => true); + await expect( + f.app.confirmCustomerSuccess(access, input, { + async verifyBeforeCommit() { + await Promise.resolve(); + if (change === "principal") + access.principalId = "different-customer"; + else if (change === "permission") access.permissions = []; + else if (change === "policy") + access.policyVersion = "different-current-policy"; + else access.roles = [...access.roles, "changed-role"]; + return assertion; + }, + }), + ).rejects.toMatchObject({ + permission: supportPermissions.confirmSuccess, + }); + expect(assertion).not.toHaveBeenCalled(); + expect(await f.rows()).toEqual(before); + }, + ); + + it("rejects a deadline crossing inside the synchronous handoff assertion", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const deadline = Date.parse(f.clock.now()) + 1; + const assertion = vi.fn((): true => { + if (Date.parse(f.clock.now()) >= deadline) + throw new Error("Browser deadline expired"); + return true; + }); + await expect( + f.app.confirmCustomerSuccess(customer, input, { + async verifyBeforeCommit() { + f.advance(1); + return assertion; + }, + }), + ).rejects.toThrow("deadline expired"); + expect(assertion).toHaveBeenCalledOnce(); + expect(await f.rows()).toEqual(before); + }); + + it.each(["not true", "async"] as const)( + "refuses a malformed %s handoff assertion without writing", + async (kind) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const bad = kind === "async" ? async () => true : () => false; + const verifyBeforeCommit = (() => + bad) as unknown as ConfirmCustomerSuccessOptions["verifyBeforeCommit"]; + await expect( + f.app.confirmCustomerSuccess(customer, input, { + verifyBeforeCommit: verifyBeforeCommit!, + }), + ).rejects.toThrow("proof is not current"); + expect(await f.rows()).toEqual(before); + }, + ); + + it.each(["before proof", "during product", "during guard"] as const)( + "honors cancellation %s without changing rows", + async (when) => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + productContext: { + async resolve(context) { + if (when === "during product") await gate.wait(); + return f.trust.productFor(context); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + const abort = new AbortController(); + const guard = vi.fn(async () => { + if (when === "during guard") await gate.wait(); + }); + if (when === "before proof") abort.abort(); + const pending = caught( + f.app.confirmCustomerSuccess(customer, input, { + signal: abort.signal, + verifyBeforeCommit: guard, + }), + ); + if (when !== "before proof") { + await reached(gate, pending); + abort.abort(); + if (when === "during product") gate.release(); + } + try { + expect(await pending).toMatchObject({ + error: { name: "AbortError" }, + }); + expect(await f.rows()).toEqual(before); + } finally { + gate.release(); + } + if (when !== "during guard") expect(guard).not.toHaveBeenCalled(); + }, + ); + + it.each(["accept", "deny"] as const)( + "obtains a new host fence after a genuine CAS conflict and then %s", + async (next) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + let current = true; + let conflicted = false; + let afterNote: Awaited> | undefined; + const assertions: ReturnType[] = []; + const guard = vi.fn(async () => { + if (!current) throw new Error("Authority lost before retry"); + const proof = vi.fn((): true => true); + assertions.push(proof); + return proof; + }); + f.observed.intercept(async (trace, commit) => { + if (!conflicted && successTransaction(trace)) { + conflicted = true; + await f.app.addNote(staff, { + ...f.command("concurrent-note"), + messageId: "concurrent-note", + body: "Private note forces a genuine Ticket version conflict.", + }); + afterNote = await f.rows(); + if (next === "deny") current = false; + } + return commit(); + }); + const result = await caught( + f.app.confirmCustomerSuccess(customer, input, { + verifyBeforeCommit: guard, + }), + ); + f.observed.intercept(undefined); + expect(conflicted).toBe(true); + expect(guard).toHaveBeenCalledTimes(2); + expect(assertions).toHaveLength(next === "accept" ? 2 : 1); + for (const assertion of assertions) + expect(assertion).toHaveBeenCalledOnce(); + if (next === "deny") { + expect(result).toHaveProperty("error"); + expect(await f.rows()).toEqual(afterNote); + } else { + expect(result).toHaveProperty("value"); + const rows = await f.rows(); + expect( + rows.filter((row) => row.kind === "customer_success"), + ).toHaveLength(1); + expect( + rows.filter((row) => row.kind === "resolution_learning_work"), + ).toHaveLength(1); + } + }, + ); + + it("keeps callback-time ownership changes fenced by the original Ticket CAS", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + let transferred = false; + const guard = vi.fn(async () => { + if (!transferred) { + const records = f.backing.collection(supportRecords); + const row = await records.getVersioned({ + partition: input.ticketId, + id: "ticket", + }); + if (row?.value.kind !== "ticket") + throw new Error("Real Ticket missing"); + transferred = await records.putIfUnchanged( + { + ...row.value, + ticket: { + ...row.value.ticket, + requester: { + ...row.value.ticket.requester, + principalId: "other-customer", + }, + }, + }, + row.version, + ); + } + }); + await expect( + f.app.confirmCustomerSuccess(customer, input, { + verifyBeforeCommit: guard, + }), + ).rejects.toThrow(); + expect(transferred).toBe(true); + expect(guard).toHaveBeenCalledOnce(); + const rows = await f.rows(); + expect( + rows.filter( + (row) => + row.kind === "customer_success" || + row.kind === "resolution_learning_work", + ), + ).toEqual([]); + }); + + it("recovers an accepted lost ACK before unavailable product proof, obsolete guard and cancellation", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + let lost = false; + f.observed.intercept(async (trace, commit) => { + const result = await commit(); + if (result.committed && successTransaction(trace) && !lost) { + lost = true; + throw new Error("Lost accepted success ACK"); + } + return result; + }); + await expect( + f.app.confirmCustomerSuccess(customer, input, { + verifyBeforeCommit: async () => () => true, + }), + ).rejects.toThrow("Lost accepted"); + f.observed.intercept(undefined); + const acceptedRows = await f.rows(); + const guard = vi.fn(async () => { + throw new Error("Obsolete host mutation proof must not run"); + }); + const controller = new AbortController(); + controller.abort(); + const unavailable = f.freshApplication({ + resolutionLearning: { enabled: false, productContext: undefined }, + }); + const result = await unavailable.confirmCustomerSuccess(customer, input, { + signal: controller.signal, + verifyBeforeCommit: guard, + }); + expect(result.ticket.status).toBe("resolved"); + expect(guard).not.toHaveBeenCalled(); + expect(await f.rows()).toEqual(acceptedRows); + for (const access of [ + { ...customer, principalId: "another-customer" }, + { ...customer, permissions: [] }, + ]) { + await expect( + unavailable.confirmCustomerSuccess(access, input, { + verifyBeforeCommit: guard, + }), + ).rejects.toThrow(); + } + expect(await f.rows()).toEqual(acceptedRows); + }); + + it("captures the initial guard before product awaits so mutable options cannot replace it", async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + productContext: { + async resolve(context) { + await gate.wait(); + return f.trust.productFor(context); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + const deny = vi.fn(async () => { + throw new Error("Captured original guard denies"); + }); + const allow = vi.fn(async () => {}); + const options: { verifyBeforeCommit: () => Promise } = { + verifyBeforeCommit: deny, + }; + const pending = caught( + f.app.confirmCustomerSuccess(customer, input, options), + ); + await reached(gate, pending); + options.verifyBeforeCommit = allow; + gate.release(); + expect(await pending).toHaveProperty("error"); + expect(deny).toHaveBeenCalledOnce(); + expect(allow).not.toHaveBeenCalled(); + expect(await f.rows()).toEqual(before); + }); + + it("retains two-argument legacy success confirmation", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + expect( + (await f.app.confirmCustomerSuccess(customer, input)).ticket.status, + ).toBe("resolved"); + expect( + (await f.rows()).filter((row) => row.kind === "customer_success"), + ).toHaveLength(1); + }); + }); +} diff --git a/tests/resolution-evidence-mutation-guard.test.ts b/tests/resolution-evidence-mutation-guard.test.ts new file mode 100644 index 0000000..f26116d --- /dev/null +++ b/tests/resolution-evidence-mutation-guard.test.ts @@ -0,0 +1,535 @@ +import type { CollectionDefinition, Store } from "@pegma/storage-core"; +import { + supportPermissions, + supportRecords, + type SubmitResolutionEvidenceCommand, + type SubmitResolutionEvidenceOptions, + type SupportRecord, +} from "@pegma/support-desk-application"; +import { describe, expect, it, vi } from "vitest"; +import { handlingBarrier } from "../test/handling-fixtures.js"; +import { + learningStaff as staff, + learningStores, + resolutionLearningFixture, +} from "../test/resolution-learning-fixtures.js"; + +type Fixture = ReturnType; + +async function packet( + f: Fixture, + kind: "successful_test" | "staff_verified_fix" = "successful_test", +): Promise { + const terminal = await f.terminal(); + const trust = { + ticketId: terminal.ticket.id, + ticketRevision: terminal.ticket.revision, + resolutionCycle: terminal.source.resolutionCycle, + resolvedAt: terminal.ticket.resolvedAt!, + actorId: staff.principalId, + acceptedAt: f.clock.now(), + }; + f.trust.issueTest("verified-run", { + ...trust, + product: f.trust.productFor(trust), + }); + return { + ...f.command("guarded-evidence"), + expectedRevision: terminal.ticket.revision, + resolutionCycle: terminal.source.resolutionCycle, + evidence: + kind === "successful_test" + ? { + kind, + solutionMessageId: terminal.solutionMessageId, + receipt: "verified-run", + } + : { + kind, + solutionMessageId: terminal.solutionMessageId, + verificationReference: "verified-fix", + }, + }; +} + +function caught(promise: Promise) { + return promise.then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); +} + +async function reached( + gate: ReturnType, + pending: Promise, +) { + await Promise.race([ + gate.reached, + pending.then(() => { + throw new Error("Evidence mutation did not reach its expected barrier"); + }), + ]); +} + +function evidenceTransaction(trace: { + actions: readonly { action: string; value?: unknown }[]; +}) { + return trace.actions.some( + (action) => + action.action !== "delete" && + (action.value as SupportRecord)?.kind === "resolution_learning_receipt", + ); +} + +for (const [backend, createStore] of learningStores) { + describe(`resolution evidence current mutation guard (${backend})`, () => { + it.each(["revoked session", "expired entitlement"] as const)( + "refuses %s after the real test-receipt await without changing Source, Work, Audit or receipt", + async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + testReceipts: { + async verify(...args) { + await gate.wait(); + return f.learningOptions.testReceipts!.verify(...args); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + let current = true; + const guard = vi.fn(async () => { + if (!current) throw new Error("Current browser authority lost"); + return (): true => true; + }); + const pending = caught( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: guard, + }), + ); + await reached(gate, pending); + expect(guard).not.toHaveBeenCalled(); + current = false; + gate.release(); + const result = await pending; + expect(await f.rows()).toEqual(before); + expect(result).toHaveProperty("error"); + expect(guard).toHaveBeenCalledOnce(); + expect(f.trust.testCalls).toHaveLength(1); + }, + ); + + it("fences staff verification after the real product await too", async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + productContext: { + async resolve(context) { + await gate.wait(); + return f.trust.productFor(context); + }, + }, + }, + }); + const input = await packet(f, "staff_verified_fix"); + const before = await f.rows(); + const guard = vi.fn(async () => { + throw new Error("Staff session revoked during product verification"); + }); + const pending = caught( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: guard, + }), + ); + await reached(gate, pending); + gate.release(); + const result = await pending; + expect(await f.rows()).toEqual(before); + expect(result).toHaveProperty("error"); + expect(guard).toHaveBeenCalledOnce(); + }); + + it("rechecks original permission changed during receipt verification for legacy calls", async () => { + const access = { ...staff, permissions: [...staff.permissions] }; + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + testReceipts: { + async verify(...args) { + access.permissions = []; + return f.learningOptions.testReceipts!.verify(...args); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + const result = await caught( + f.app.submitResolutionEvidence(access, input), + ); + expect(await f.rows()).toEqual(before); + expect(result).toMatchObject({ + error: { permission: supportPermissions.learningEvidenceSubmit }, + }); + }); + + it("also fences the held-source mutation when the test receipt cannot qualify", async () => { + const f = resolutionLearningFixture(createStore(), { + resolutionLearning: { testReceipts: undefined }, + }); + const input = await packet(f); + const before = await f.rows(); + const guard = vi.fn(async () => { + throw new Error("Current browser authority lost"); + }); + await expect( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: guard, + }), + ).rejects.toThrow("authority lost"); + expect(guard).toHaveBeenCalledOnce(); + expect(await f.rows()).toEqual(before); + }); + + it("makes host refresh the last awaited precommit work with its synchronous proof at the handoff", async () => { + const backing = createStore(); + let armed = false; + const events: string[] = []; + const observed: Store = { + collection(definition: CollectionDefinition) { + const actual = backing.collection(definition); + return new Proxy(actual, { + get(object, property) { + const value: unknown = Reflect.get(object, property, object); + if (typeof value !== "function") return value; + return (...args: unknown[]) => { + if (armed) events.push(String(property)); + return Reflect.apply(value, object, args); + }; + }, + }); + }, + }; + const f = resolutionLearningFixture(observed); + const input = await packet(f); + armed = true; + expect( + ( + await f.app.submitResolutionEvidence(staff, input, { + async verifyBeforeCommit() { + events.push("host-refresh"); + await Promise.resolve(); + events.push("host-ready"); + return (): true => { + events.push("sync-proof"); + return true; + }; + }, + }) + ).state, + ).toBe("eligible"); + const ready = events.indexOf("host-ready"); + const transaction = events.indexOf("transact", ready); + expect(ready).toBeGreaterThan(-1); + expect(events.slice(ready + 1, transaction)).toEqual(["sync-proof"]); + expect(transaction).toBe(ready + 2); + expect(f.trust.testCalls).toHaveLength(1); + }); + + it.each(["principal", "permission", "queue", "policy", "roles"] as const)( + "rechecks original %s context after the awaited host callback", + async (change) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const access = { + ...staff, + roles: [...staff.roles], + permissions: [...staff.permissions], + }; + const assertion = vi.fn((): true => true); + await expect( + f.app.submitResolutionEvidence(access, input, { + async verifyBeforeCommit() { + await Promise.resolve(); + if (change === "principal") access.principalId = "other-staff"; + else if (change === "permission") access.permissions = []; + else if (change === "queue") + access.permissions = access.permissions.filter( + (name) => name !== supportPermissions.queueRead, + ); + else if (change === "policy") access.policyVersion = "changed"; + else access.roles = [...access.roles, "changed"]; + return assertion; + }, + }), + ).rejects.toMatchObject({ + permission: + change === "queue" + ? supportPermissions.queueRead + : supportPermissions.learningEvidenceSubmit, + }); + expect(assertion).not.toHaveBeenCalled(); + expect(await f.rows()).toEqual(before); + }, + ); + + it("rejects deadline expiry inside the synchronous transaction assertion", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const deadline = Date.parse(f.clock.now()) + 1; + const assertion = vi.fn((): true => { + if (Date.parse(f.clock.now()) >= deadline) + throw new Error("Browser deadline expired"); + return true; + }); + await expect( + f.app.submitResolutionEvidence(staff, input, { + async verifyBeforeCommit() { + f.advance(1); + return assertion; + }, + }), + ).rejects.toThrow("deadline expired"); + expect(assertion).toHaveBeenCalledOnce(); + expect(await f.rows()).toEqual(before); + }); + + it.each(["not true", "async"] as const)( + "refuses malformed %s synchronous proof without writing", + async (kind) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const bad = kind === "async" ? async () => true : () => false; + const verifyBeforeCommit = (() => + bad) as unknown as SubmitResolutionEvidenceOptions["verifyBeforeCommit"]; + await expect( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: verifyBeforeCommit!, + }), + ).rejects.toThrow("proof is not current"); + expect(await f.rows()).toEqual(before); + }, + ); + + it.each(["before proof", "during receipt", "during guard"] as const)( + "honors cancellation %s without changing rows", + async (when) => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + testReceipts: { + async verify(...args) { + if (when === "during receipt") await gate.wait(); + return f.learningOptions.testReceipts!.verify(...args); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + const abort = new AbortController(); + const guard = vi.fn(async () => { + if (when === "during guard") await gate.wait(); + }); + if (when === "before proof") abort.abort(); + const pending = caught( + f.app.submitResolutionEvidence(staff, input, { + signal: abort.signal, + verifyBeforeCommit: guard, + }), + ); + if (when !== "before proof") { + await reached(gate, pending); + abort.abort(); + if (when === "during receipt") gate.release(); + } + try { + expect(await pending).toMatchObject({ + error: { name: "AbortError" }, + }); + expect(await f.rows()).toEqual(before); + } finally { + gate.release(); + } + if (when !== "during guard") expect(guard).not.toHaveBeenCalled(); + }, + ); + + it.each(["accept", "deny"] as const)( + "obtains a fresh host fence after a real Source CAS conflict then %s", + async (next) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + let conflicted = false; + let current = true; + const assertions: ReturnType[] = []; + const guard = vi.fn(async () => { + if (!current) throw new Error("Authority lost before retry"); + const assertion = vi.fn((): true => true); + assertions.push(assertion); + return assertion; + }); + f.observed.intercept(async (trace, commit) => { + if (!conflicted && evidenceTransaction(trace)) { + const records = f.backing.collection(supportRecords); + const source = await records.getVersioned({ + partition: input.ticketId, + id: "learning-source", + }); + if (source?.value.kind !== "resolution_learning_source") + throw new Error("Real Source missing"); + // Rewrite the same public Store record to change its real opaque + // version without changing the explicit resolution/revision fence. + conflicted = await records.putIfUnchanged( + source.value, + source.version, + ); + if (next === "deny") current = false; + } + return commit(); + }); + const result = await caught( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: guard, + }), + ); + f.observed.intercept(undefined); + expect(conflicted).toBe(true); + expect(guard).toHaveBeenCalledTimes(2); + expect(f.trust.testCalls).toHaveLength(2); + expect(assertions).toHaveLength(next === "accept" ? 2 : 1); + for (const assertion of assertions) + expect(assertion).toHaveBeenCalledOnce(); + if (next === "deny") { + expect(result).toHaveProperty("error"); + expect(await f.rows()).toEqual(before); + } else { + expect(result).toMatchObject({ value: { state: "eligible" } }); + const rows = await f.rows(); + for (const kind of [ + "resolution_learning_work", + "resolution_learning_receipt", + ]) + expect(rows.filter((row) => row.kind === kind)).toHaveLength(1); + } + }, + ); + + it("recovers an accepted lost ACK before unavailable proof, obsolete guard and cancellation", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + let lost = false; + f.observed.intercept(async (trace, commit) => { + const result = await commit(); + if (!lost && result.committed && evidenceTransaction(trace)) { + lost = true; + throw new Error("Lost accepted evidence ACK"); + } + return result; + }); + await expect( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: async () => () => true, + }), + ).rejects.toThrow("Lost accepted"); + f.observed.intercept(undefined); + const accepted = await f.rows(); + const guard = vi.fn(async () => { + throw new Error("Obsolete guard must not run"); + }); + const abort = new AbortController(); + abort.abort(); + const unavailable = f.freshApplication({ + resolutionLearning: { + enabled: false, + productContext: undefined, + testReceipts: undefined, + }, + }); + expect( + await unavailable.submitResolutionEvidence(staff, input, { + signal: abort.signal, + verifyBeforeCommit: guard, + }), + ).toMatchObject({ state: "eligible" }); + expect(guard).not.toHaveBeenCalled(); + expect(f.trust.testCalls).toHaveLength(1); + expect(await f.rows()).toEqual(accepted); + for (const access of [ + { ...staff, principalId: "other-staff" }, + { ...staff, permissions: [] }, + { + ...staff, + permissions: staff.permissions.filter( + (name) => name !== supportPermissions.queueRead, + ), + }, + ]) + await expect( + unavailable.submitResolutionEvidence(access, input, { + verifyBeforeCommit: guard, + }), + ).rejects.toThrow(); + expect(await f.rows()).toEqual(accepted); + }); + + it("captures the initial guard before receipt awaits so mutable options cannot replace it", async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + testReceipts: { + async verify(...args) { + await gate.wait(); + return f.learningOptions.testReceipts!.verify(...args); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + const deny = vi.fn(async () => { + throw new Error("Captured original guard denies"); + }); + const allow = vi.fn(async () => {}); + const options: { verifyBeforeCommit: () => Promise } = { + verifyBeforeCommit: deny, + }; + const pending = caught( + f.app.submitResolutionEvidence(staff, input, options), + ); + await reached(gate, pending); + options.verifyBeforeCommit = allow; + gate.release(); + expect(await pending).toHaveProperty("error"); + expect(deny).toHaveBeenCalledOnce(); + expect(allow).not.toHaveBeenCalled(); + expect(await f.rows()).toEqual(before); + }); + + it.each(["successful_test", "staff_verified_fix"] as const)( + "retains legacy two-argument %s submission", + async (kind) => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f, kind); + expect((await f.app.submitResolutionEvidence(staff, input)).state).toBe( + "eligible", + ); + expect( + (await f.rows()).filter( + (row) => row.kind === "resolution_learning_work", + ), + ).toHaveLength(1); + }, + ); + }); +} From 3872459c33e7dc1a37e0d8c82d295cf55212168c Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 01:27:43 -0500 Subject: [PATCH 2/4] Align current release fixture expectations with version 0.2.10 --- tests/release-packages.test.ts | 22 +++++++++++----------- tests/release-verification.test.ts | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 299eab3..bce5d3d 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -90,7 +90,7 @@ describe("release package metadata", () => { ]); }); - it("ships the synchronized 0.2.9 package set with exact internal pins", () => { + it("ships the synchronized 0.2.10 package set with exact internal pins", () => { const manifests = RELEASE_PACKAGES.map(({ directory }) => JSON.parse( readFileSync( @@ -105,24 +105,24 @@ describe("release package metadata", () => { }>; expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ - { name: "@pegma/support-desk-contracts", version: "0.2.9" }, - { name: "@pegma/support-desk-core", version: "0.2.9" }, - { name: "@pegma/support-desk-templates", version: "0.2.9" }, - { name: "@pegma/support-desk-application", version: "0.2.9" }, - { name: "@pegma/support-desk-ai", version: "0.2.9" }, + { name: "@pegma/support-desk-contracts", version: "0.2.10" }, + { name: "@pegma/support-desk-core", version: "0.2.10" }, + { name: "@pegma/support-desk-templates", version: "0.2.10" }, + { name: "@pegma/support-desk-application", version: "0.2.10" }, + { name: "@pegma/support-desk-ai", version: "0.2.10" }, ]); expect(manifests[1]?.dependencies?.["@pegma/support-desk-contracts"]).toBe( - "0.2.9", + "0.2.10", ); expect(manifests[3]?.dependencies?.["@pegma/support-desk-contracts"]).toBe( - "0.2.9", + "0.2.10", ); expect(manifests[3]?.dependencies?.["@pegma/support-desk-core"]).toBe( - "0.2.9", + "0.2.10", ); expect( manifests[4]?.dependencies?.["@pegma/support-desk-application"], - ).toBe("0.2.9"); + ).toBe("0.2.10"); expect( manifests[4]?.dependencies?.["@pegma/support-desk-contracts"], ).toBeUndefined(); @@ -245,7 +245,7 @@ packages: "@pegma/support-desk-contracts" ], ).toEqual({ - specifier: "0.2.9", + specifier: "0.2.10", version: "link:../contracts", }); expect( diff --git a/tests/release-verification.test.ts b/tests/release-verification.test.ts index 9ff5b0d..38526e0 100644 --- a/tests/release-verification.test.ts +++ b/tests/release-verification.test.ts @@ -1230,7 +1230,7 @@ describe("source-bound original release artifact", () => { }); it("reads real gzip/tar artifacts and accepts the independently pinned exact five-package candidate", async () => { - expect(releaseVerificationVersion).toBe("0.2.9"); + expect(releaseVerificationVersion).toBe("0.2.10"); const f = fixture(); expect( f.manifest.packages.map(({ name, version }) => ({ name, version })), From f7bae28648cb760c6ee69430cdf3cf92b7b612da Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 02:01:12 -0500 Subject: [PATCH 3/4] Close learning proof freshness at the guarded write boundary --- docs/AI_OPERATIONS.md | 23 +- docs/ARCHITECTURE.md | 12 +- docs/ASSISTANT_COORDINATION.md | 10 +- docs/BUILDOUT.md | 13 +- docs/COLLECTIONS.md | 25 +- docs/ENGINEERING_EXPORT.md | 24 +- docs/ENGINEERING_FOLLOWUP.md | 27 +- docs/HOST_COMPOSITION.md | 55 ++-- docs/RELEASE_NOTES.md | 4 +- docs/RESOLUTION_LEARNING.md | 13 +- docs/UPGRADING.md | 11 +- examples/ai/README.md | 19 +- packages/ai/README.md | 44 ++-- .../src/engineering-mutation-guard.ts | 22 +- packages/application/src/index.ts | 16 +- .../application/src/resolution-learning.ts | 99 +++++++- packages/contracts/README.md | 17 +- packages/core/README.md | 17 +- packages/templates/README.md | 13 +- tests/customer-success-mutation-guard.test.ts | 166 ++++++++++--- ...resolution-evidence-mutation-guard.test.ts | 234 +++++++++++++++--- 21 files changed, 633 insertions(+), 231 deletions(-) diff --git a/docs/AI_OPERATIONS.md b/docs/AI_OPERATIONS.md index 052640f..a475dbb 100644 --- a/docs/AI_OPERATIONS.md +++ b/docs/AI_OPERATIONS.md @@ -1,8 +1,8 @@ # Optional AI operations This runbook describes the merged SD-01 through SD-05 contracts assembled by -the current verified published synchronized `0.2.8` release; see its -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +the current verified published synchronized `0.2.9` release; see its +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13). SDK publication does not establish production deployment, verified host data controls, or pilot acceptance. Use exact published artifacts and complete each host's own [upgrade rehearsal](UPGRADING.md). @@ -16,10 +16,13 @@ usable with all optional AI capabilities disabled. Published `0.2.6` introduced final host guards and cancellation on seven engineering controls. Published `0.2.7` adds compatible approval observations and authorized engineering reads, retaining fresh proof and host authority. -The current `0.2.8` tuple pins exact public KB application/contracts `0.1.6`. -The unpublished `0.2.9` candidate now pins exact verified public KB `0.1.8`; -its changed dependency graph requires fresh SDK qualification. -The published `0.2.8` graph and earlier artifacts remain unchanged. +The current `0.2.9` tuple pins exact public KB application/contracts `0.1.8` +and passed strict registry and clean-consumer qualification. Local source +prepares unpublished `0.2.10` with the same external KB pins; its guards need +their own combined-source qualification and publication before adoption. +See the [source handoff](RELEASING.md#source-version-0210). The historical +[`0.2.8` receipt](RELEASING.md#verified-028-publication-2026-11-12) and its KB +`0.1.6` graph remain unchanged. The `0.2.8` source additions retained in `0.2.9` add optional late host guards/cancellation to non-post follow-up controls and forwards staff reassessment guards. Reassessment may @@ -29,10 +32,10 @@ ports keep the full legacy path. Use the existing current-browser/permission/deadline fence; a guard is read-only and does not replace SDK proof. Web posting retains its authorization/delivery guarantees and can use a per-attempt application-owned read observation with fresh opaque -confirmations; the compatibility fallback remains. Keep hosts on -the verified `0.2.8` tuple until the next release is published and qualified. +confirmations; the compatibility fallback remains. Use the verified `0.2.9` +tuple and qualify the host's actual composition separately. See the [published 0.2.8 contract](ENGINEERING_FOLLOWUP.md#candidate-028-followup-host-guards) -and [current source handoff](RELEASING.md#source-version-029). +and [current source handoff](RELEASING.md#source-version-0210). ## Controls and human fallback @@ -95,7 +98,7 @@ retest Audit/receipt rows use ordinary capacity. Use explicit staff retry for eligible draftless held/expired work, reassessment for retained drafts, or local abandonment to release reservations. None clears parent privacy withdrawal. -The unpublished `0.2.9` follow-up `invocationMode: 'staged'` separates durable +Published `0.2.9` follow-up `invocationMode: 'staged'` separates durable not-called planning, one conditional generator attempt and fresh completion. Use deferred Work checks for their separate prepare, provider and receipt invocations. A received verdict carries no check receipt. Original attempt diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 393a02a..3d3ccc4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -368,17 +368,17 @@ previous limits. All admission remains under the hard partition cap. See [declared collections](COLLECTIONS.md#sd-01-handling-and-handoff-layout-checkpoint) for row, serialized-byte, and capacity bounds before changing durable work. -Changes need their own tests/review. The current synchronized `0.2.8` release is +Changes need their own tests/review. The current synchronized `0.2.9` release is published and strictly verified; its -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12) +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13) records the exact artifacts. Older base registry `0.1.1` artifacts remain immutable history. AUTH-01, KB-04 transport source/SDK proof, partial KB-05 source preparation ([KB #4](https://github.com/pegma-dev/knowledge-base/pull/4)), and both producers' final release preparation are merged. The [standalone authoring recipe](HOST_COMPOSITION.md#kb-authoring-producers) -selects all four strictly verified KB `0.1.6` packages and verified Agent +selects all four strictly verified KB `0.1.8` packages and verified Agent Access `0.1.1`, closing SD-02's producer publication prerequisite. The current -AI release pins the KB application and contracts packages at `0.1.6`. +AI release pins the KB application and contracts packages at `0.1.8`. PG-01/RG-01 retain actual two-host existing-login/Admin consent and requested-client proof before activation or pilots. Synthetic proof uses no actual customer data and cannot close those host gates. Host privacy, operations, full-workflow, @@ -387,8 +387,8 @@ activation, and pilot gates remain pending. Follow the ### SD-02 optional coordination -The optional `@pegma/support-desk-ai@0.2.8` package composes exact published KB -`0.1.6` APIs with five fixed turn operations on the base application. The +The optional `@pegma/support-desk-ai@0.2.9` package composes exact published KB +`0.1.8` APIs with five fixed turn operations on the base application. The application has no KB/provider dependency. Causal signed-in web ingress writes bounded `assistant_turn` work in the existing ticket partition with its message, Ticket, Audit, receipt, and quota changes. Lease, preparation, and diff --git a/docs/ASSISTANT_COORDINATION.md b/docs/ASSISTANT_COORDINATION.md index 54ff443..4183793 100644 --- a/docs/ASSISTANT_COORDINATION.md +++ b/docs/ASSISTANT_COORDINATION.md @@ -11,11 +11,13 @@ deployment, live-provider, or pilot result. Follow and the actual public types in `packages/application/src/assistant-turn-types.ts` and `packages/ai/src/ports.ts` when changing this boundary. -The published `0.2.8` optional `@pegma/support-desk-ai` package owns coordination -and exact KB application/contracts `0.1.6` dependencies. The base application +The published `0.2.9` optional `@pegma/support-desk-ai` package owns coordination +and exact KB application/contracts `0.1.8` dependencies. The base application remains usable without AI and contains no KB or model-provider dependency. The -current synchronized `0.2.8` release is published and strictly verified; see the -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +current synchronized `0.2.9` release is published and strictly verified; see the +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13). +Local source prepares unpublished `0.2.10` with unchanged external KB pins; +see the [source handoff](RELEASING.md#source-version-0210). Host activation retains its own acceptance gates. Existing registry versions remain immutable. diff --git a/docs/BUILDOUT.md b/docs/BUILDOUT.md index 601db98..537f6d1 100644 --- a/docs/BUILDOUT.md +++ b/docs/BUILDOUT.md @@ -650,9 +650,9 @@ P-00, KB-01 through KB-04, AUTH-01, SD-01, partial KB-05 source preparation ([KB #4](https://github.com/pegma-dev/knowledge-base/pull/4)), and both producers' final release preparation are already merged. The [standalone authoring recipe](HOST_COMPOSITION.md#kb-authoring-producers) -selects the four strictly verified KB `0.1.6` packages and verified Agent -Access `0.1.1`. Support Desk's current synchronized `0.2.8` release is published and strictly -verified; see the [publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +selects the four strictly verified KB `0.1.8` packages and verified Agent +Access `0.1.1`. Support Desk's current synchronized `0.2.9` release is published and strictly +verified; see the [publication receipt](RELEASING.md#verified-029-publication-2026-11-13). Follow its [coordination checkpoint](ASSISTANT_COORDINATION.md). PG-01/RG-01 consume both exact verified published producers and retain actual two-host existing-login/Admin consent and requested-client acceptance before activation @@ -724,7 +724,9 @@ The initial buildout is complete only when: The additive attachment slice is published in `0.2.5`. Host adoption retains its storage, scanner, retention and deployment acceptance gates. See [ATTACHMENTS.md](./ATTACHMENTS.md) for the host blob port, bounds, transactional metadata, scan callback, download gates, deletion and worker contracts. Inbound attachments remain explicitly dropped. Task 12 still awaits host production evidence. -## Task 15 — staff canned responses and one-message macros: source candidate + + +## Task 15 — staff canned responses and one-message macros: published 0.2.9 The host supplies at most 64 immutable, versioned plain-text response definitions. Staff list only definitions permitted for their reply/note target, preview literal @@ -739,7 +741,8 @@ Memory and Azurite public-entry tests cover authorization, validation, replay, concurrency, atomic failure recovery and the internal-note boundary. The runnable composition demonstrates separate preview and staff send. See [host composition](HOST_COMPOSITION.md#staff-canned-responses-task-15-source-candidate). -This source addition changes no package versions or collection layouts. +This API is included in published `0.2.9` and adds no package or collection layout. +Host adoption retains its own acceptance gates. Open questions for later tasks: durable administrator authoring/activation and multi-action macros need a reviewed version-retention/approval model. This slice diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index c13999a..41f8aba 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -27,8 +27,8 @@ memory tests, and real-adapter tests. This checkpoint originated before SD-05 implementation. SD-05 later merged in [PR #41](https://github.com/pegma-dev/support-desk/pull/41) and first shipped in the verified synchronized [`0.2.0` release](RELEASING.md#verified-sd-06-publication-2026-11-08). -The current synchronized release is `0.2.8`; see its -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +The current verified synchronized release is `0.2.9`; see its +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13). Host acceptance remains open. The owning scope is [the approved release follow-up task](KNOWLEDGE_AI_PLAN.md#release-follow-up). @@ -162,7 +162,7 @@ no new KB write, source verifier or fabricated resolution proof is introduced. This checkpoint originated before SD-04 production changes. SD-04 later merged in [PR #40](https://github.com/pegma-dev/support-desk/pull/40) and first shipped in -verified synchronized `0.2.0`. Those contracts remain in current `0.2.8`, whose +verified synchronized `0.2.0`. Those contracts remain in current public `0.2.9`, whose publication receipt is linked above. Host acceptance remains separate. SD-03 merged in [PR #39](https://github.com/pegma-dev/support-desk/pull/39) before this work began. @@ -399,16 +399,17 @@ still grants no web principal or account access. SD-01 supplies handling and deterministic controls only. AUTH-01, KB-04 transport source/SDK proof, partial KB-05 source preparation ([KB #4](https://github.com/pegma-dev/knowledge-base/pull/4)), and both producers' final release preparation are merged. All four KB -packages have strictly verified trusted `0.1.6` releases. Verified Agent +packages have strictly verified trusted `0.1.8` releases. Verified Agent Access `0.1.1` completes the producer publication prerequisite. Support Desk's -current synchronized `0.2.8` +current synchronized `0.2.9` release is published and strictly verified; see the -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13). The implementation checkpoint below is historical. The [standalone authoring recipe](HOST_COMPOSITION.md#kb-authoring-producers) -selects all four KB `0.1.6` packages with Agent Access `0.1.1`. The current -released AI `0.2.8` -pins KB application/contracts `0.1.6`; earlier `0.2.1` manifests retain their +selects all four KB `0.1.8` packages with Agent Access `0.1.1`. The current +released AI `0.2.9` +pins KB application/contracts `0.1.8`; historical AI `0.2.8` retains KB `0.1.6`, +and earlier `0.2.1` manifests retain their exact KB `0.1.2` dependencies. The checkpoints below remain historical. PG-01/RG-01 retain actual two-host existing-login/Admin consent and requested-client proof before activation or @@ -516,10 +517,10 @@ work became consumable after its exact public artifacts, signatures, provenance, and clean consumer were verified in [release run 42436081951](https://github.com/pegma-dev/knowledge-base/actions/runs/42436081951). At this historical checkpoint the optional delivery adapter pinned the verified -public `0.1.2` producers. Current AI `0.2.8` explicitly pins KB application/ -contracts `0.1.6`; this does not rewrite the checkpoint's dependency evidence. +public `0.1.2` producers. Current public AI `0.2.9` explicitly pins KB application/ +contracts `0.1.8`; this does not rewrite the checkpoint's dependency evidence. SD-03 later merged in [PR #39](https://github.com/pegma-dev/support-desk/pull/39) -and first shipped in the verified `0.2.0` release. The current `0.2.8` release +and first shipped in the verified `0.2.0` release. The current public `0.2.9` release retains those contracts; host activation remains separate. #### Enrollment, source authority, and evidence diff --git a/docs/ENGINEERING_EXPORT.md b/docs/ENGINEERING_EXPORT.md index ca769c4..f180be3 100644 --- a/docs/ENGINEERING_EXPORT.md +++ b/docs/ENGINEERING_EXPORT.md @@ -3,10 +3,12 @@ SD-04's source merged in [PR #40](https://github.com/pegma-dev/support-desk/pull/40) and first shipped in the verified synchronized [`0.2.0` release](RELEASING.md#verified-sd-06-publication-2026-11-08). -The current synchronized release is `0.2.8`; see its -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). -This handbook describes released contracts, explicitly marked source-candidate -changes, and host responsibilities, not host activation. There is no runnable host recipe here. Scope comes from the +The current verified synchronized release is `0.2.9`; see its +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13). +Local source prepares unpublished `0.2.10`; see the +[source handoff](RELEASING.md#source-version-0210). This handbook describes +released engineering contracts and host responsibilities, not host activation. +There is no runnable host recipe here. Scope comes from the [approved plan](KNOWLEDGE_AI_PLAN.md#bug-evaluation-routing-and-github-export) and the [collection checkpoint](COLLECTIONS.md#sd-04-engineering-layout-checkpoint). @@ -27,9 +29,9 @@ the optional context, or uses its original sequential Source-validation/Work read fallback when the structural application port omits it. No observation crosses an external proof boundary, and accepted receipts still precede new proof reads. This adds no permission, cache, Store primitive or atomic-snapshot -guarantee. The released AI package pins exact verified public KB -application/contracts `0.1.6`; see the -[current source dependency contract](RELEASING.md#source-version-029). +guarantee. The published `0.2.7` AI package retains exact KB +application/contracts `0.1.6`; current public `0.2.9` pins exact verified `0.1.8`. +See the [publication receipt](RELEASING.md#verified-029-publication-2026-11-13). Hosts must measure the complete invocation, including their own authentication, proofs, limiter and closing checks; grouped reads do not establish a universal Workers query or CPU budget. @@ -57,9 +59,9 @@ authorization and does not establish current policy or remote authority. -## Candidate 0.2.9 worker observations +## Published 0.2.9 worker observations -The unpublished source candidate adds optional application methods without +Published `0.2.9` adds optional application methods without changing existing required methods or the AI coordinator's four entry points: | Application method | Callback contract | @@ -101,8 +103,8 @@ plan or a deployed host. ## 0.2.6: guarded engineering controls -These controls are published and strictly verified in `0.2.6` and retained by -the local unpublished `0.2.9` source candidate. +These controls are published and strictly verified in `0.2.6`, retained by +published `0.2.9` and the local unpublished `0.2.10` source candidate. The optional third `EngineeringMutationOptions` argument applies to `enrollEngineeringSource`, `submitEngineeringEvidence`, `selectEngineeringRepository`, `withdrawEngineeringSource`, diff --git a/docs/ENGINEERING_FOLLOWUP.md b/docs/ENGINEERING_FOLLOWUP.md index 214ac38..f6d8a45 100644 --- a/docs/ENGINEERING_FOLLOWUP.md +++ b/docs/ENGINEERING_FOLLOWUP.md @@ -3,8 +3,10 @@ SD-05's source merged in [PR #41](https://github.com/pegma-dev/support-desk/pull/41) and first shipped in the verified synchronized [`0.2.0` release](RELEASING.md#verified-sd-06-publication-2026-11-08). -The current synchronized release is `0.2.8`; see its -[publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +The current verified synchronized release is `0.2.9`; see its +[publication receipt](RELEASING.md#verified-029-publication-2026-11-13). +Local source prepares unpublished `0.2.10`; see the +[source handoff](RELEASING.md#source-version-0210). This handbook describes its contracts and host responsibilities, not deployment or host acceptance. SD-04 merged in [PR #40](https://github.com/pegma-dev/support-desk/pull/40). Scope comes from the @@ -112,9 +114,11 @@ existing proof, host guard and delivery guarantees, with the optional read observation below. No role, permission, record layout, model call or automatic customer notification is added. -### Candidate 0.2.9 retest and provider controls + -The unpublished candidate adds optional `EngineeringMutationOptions` as the +### Published 0.2.9 retest and provider controls + +Published `0.2.9` adds optional `EngineeringMutationOptions` as the third argument to `submitEngineeringFollowupRetestResult`. A new retest write checks its original signal and late host guard after awaited evidence and at transaction handoff. Current-authorized exact accepted receipts recover before @@ -128,8 +132,9 @@ provider and host activation remain pending. Retest requests remain advisory until the owning trusted evidence workflow verifies their actual execution. + -### Candidate 0.2.9 physical invocation phases +### Published 0.2.9 physical invocation phases Set `invocationMode: 'staged'` on the AI coordinator to separate durable model planning, one provider attempt and candidate completion. The actual application @@ -219,7 +224,9 @@ enter stored records. These source contracts do not qualify a host's physical D1 or CPU budget. Actual Workers Free 50-call and 100-parameter qualification remains separate. -### Candidate bundle observation + + +### Published bundle observation Actual Application claims advertise `bundleObservation: true` without storing an observation or changing the Work record. Staged workers may use that claim's @@ -242,7 +249,9 @@ argument, and ordinary inline composition, retain full fresh proof/current-read fallbacks. A planning proof never authorizes commitment, posting or a provider call. This operation-local read reduction does not establish a host budget pass. -### Candidate post observation + + +### Published post observation For each new application post attempt, the proof guard may receive an optional `EngineeringFollowupPostObservation`. `readWork(access)` lazily enforces the @@ -260,7 +269,9 @@ forward its optional argument and returned assertion unchanged. Hosts must measure their complete invocation; this read optimization establishes no universal Workers call or CPU qualification. -### Candidate reassessment observation + + +### Published reassessment observation `reassessEngineeringFollowupBundle` lets the Application own an entire staff reassessment attempt. Its immutable `ReassessEngineeringFollowupBundleCommand` diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index 55be767..e590b67 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -12,7 +12,7 @@ See also the runnable example at ## Published 0.2.6 guarded engineering controls -The current verified registry tuple is `0.2.8`. The local synchronized `0.2.9` +The current verified registry tuple is `0.2.9`. The local synchronized `0.2.10` source candidate remains unpublished and retains these guarded controls. Candidate metadata or a local pack does not qualify host adoption. Published `0.2.6` adds an optional third @@ -32,12 +32,15 @@ to approval guards, with lazy authorized reads and a legacy standalone-read fallback. It does not extend that observation to all seven controls. See the [approval contract](ENGINEERING_EXPORT.md#candidate-027-approval-observation). Its optional AI package pins exact verified public KB application/contracts -`0.1.6`. The unpublished `0.2.9` candidate instead pins exact verified public KB -application/contracts `0.1.8` and requires fresh graph qualification. The `0.2.8` source additions retained in `0.2.9` add late host controls to the separate non-post follow-up methods and +`0.1.6`. Published `0.2.9` instead pins exact verified public KB +application/contracts `0.1.8`; that graph passed strict registry and clean-consumer +qualification. Source preparation for `0.2.10` retains those external pins and +requires its own release qualification. The `0.2.8` controls retained in `0.2.9` +add late host controls to the separate non-post follow-up methods and optional callback-scoped reassessment/post read observations; see the [published 0.2.8 follow-up contract](ENGINEERING_FOLLOWUP.md#candidate-028-followup-host-guards). Qualify the complete published consumer graph for the host; the candidate -remains unpublished. See the [source handoff](RELEASING.md#source-version-029). +remains unpublished. See the [source handoff](RELEASING.md#source-version-0210). Options use a plain object with the two named, enumerable own data fields. Unknown keys, accessors and inherited options fail validation. The optional @@ -77,9 +80,11 @@ request budget and qualifies its deployment separately. ## Public packages -This guide describes the verified published synchronized `0.2.8` release. -Use exact `0.2.8` for the five Support Desk packages, including optional AI; see -the [publication receipt](RELEASING.md#verified-028-publication-2026-11-12). +This guide describes the verified published synchronized `0.2.9` release. +Use exact `0.2.9` for the five Support Desk packages, including optional AI; see +the [publication receipt](RELEASING.md#verified-029-publication-2026-11-13). +The historical [`0.2.8` receipt](RELEASING.md#verified-028-publication-2026-11-12) +retains its original dependency graph and artifacts. It retains the attachments and opt-in staged human learning reviews published in `0.2.5`. Host composition and activation retain their own acceptance gates. SD-01 through SD-05 first shipped in the @@ -145,13 +150,13 @@ recorded synthetic KB protocol proof used four packed KB packages with registry `@pegma/agent-access@0.1.1`. The KB-05 publication prerequisite for SD-02 is closed. The optional AI package -in the verified `0.2.8` tuple uses exact KB application/contracts `0.1.6` -dependencies. The unpublished `0.2.9` candidate pins verified public `0.1.8` -and requires its own fresh graph qualification. The base application has no KB +in the verified `0.2.9` tuple uses exact KB application/contracts `0.1.8` +dependencies. The unpublished `0.2.10` candidate retains those external pins +and requires its own release qualification. The base application has no KB or provider dependency. SD-02 source passed validation/review and merged in [PR #38](https://github.com/pegma-dev/support-desk/pull/38); that behavior first shipped in verified synchronized `0.2.0` and remains in -current `0.2.8`, whose publication receipt is linked above. Host acceptance remains required. Do not substitute branches, copied source, +current public `0.2.9`, whose publication receipt is linked above. Host acceptance remains required. Do not substitute branches, copied source, local paths, or unpublished tarballs for production dependencies. SD-03's atomic-provenance prerequisite is the verified trusted @@ -172,9 +177,11 @@ added shared test reports and staff confirmation. Its signed source is passed on release run 42533473529, attempt 5. That release remains historical evidence. -#### Standalone authoring with published Support Desk 0.2.8 + -For standalone authoring alongside published Support Desk `0.2.8`, compose these +#### Historical standalone authoring with Support Desk 0.2.8 + +The historical standalone authoring recipe alongside Support Desk `0.2.8` used these exact packages. The optional AI package directly requires KB application/contracts; MCP and Agent Access belong to the standalone authoring host. @@ -189,7 +196,9 @@ against signed source `b2946e149078e0ef460f970c2271c196ea9fc759`. Each host qualifies its installed dependency graph, permissions and actual client flows. [Knowledge Base release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6) · [Registry verification receipt](https://github.com/pegma-dev/knowledge-base/releases/download/v0.1.6/registry-verification.json) -The unpublished Support Desk `0.2.9` candidate instead selects exact verified +#### Standalone authoring with published Support Desk 0.2.9 + +Published Support Desk `0.2.9` selects exact verified public KB application/contracts `0.1.8`; standalone authoring aligns contracts, core, application and MCP at `0.1.8`, with Agent Access unchanged at `0.1.1`. All four KB packages passed strict public verification from signed source @@ -218,8 +227,8 @@ own dependency pins. The AI package's immutable pins `@pegma/knowledge-base-application@0.1.2` and `@pegma/knowledge-base-contracts@0.1.2`. Adding a newer standalone SDK does not replace those dependencies or establish mixed-version host acceptance. The -current verified AI `0.2.8` manifest explicitly pins KB application/contracts -`0.1.6`; hosts must adopt and qualify that coherent graph separately. +current verified AI `0.2.9` manifest explicitly pins KB application/contracts +`0.1.8`; hosts must adopt and qualify that coherent graph separately. #### Qualified storage adapters @@ -387,10 +396,12 @@ Tags, due timestamps, and milestones never enter customer DTOs or automatic customer mail projections. Hosts must keep these fields out of customer notification variables and template bodies as well. -## Staff canned responses (Task 15 source candidate) + + +## Staff canned responses (Task 15, published 0.2.9) -This API is an unpublished source addition to the existing candidate, with no -version change. Adopt only after a verified public release and host acceptance. +This API is included in verified public `0.2.9`. Host adoption still requires +the host's own acceptance; no additional package or collection is introduced. The host supplies `cannedResponses` when constructing the application: ```ts @@ -579,12 +590,12 @@ refused; missing or inactive hints can still leave a temporary repair gap. SD-01 includes no AI provider, knowledge retrieval, learning, or publication. Keep model activation disabled until the host gates pass. This composition -uses the verified KB `0.1.6` set and Agent Access `0.1.1` listed above. +uses the verified KB `0.1.8` set and Agent Access `0.1.1` listed above. SD-02's producer publication prerequisite is complete. Its optional coordinator source is merged after validation/review, as are SD-03 through SD-05. They first shipped -in verified synchronized `0.2.0` and remain in current `0.2.8`, whose publication +in verified synchronized `0.2.0` and remain in current public `0.2.9`, whose publication receipt is linked above. The current AI consumer pins exact KB application/ -contracts `0.1.6`; the earlier `0.2.1`/KB `0.1.2` manifests remain immutable. Actual two-host +contracts `0.1.8`; the earlier `0.2.1`/KB `0.1.2` manifests remain immutable. Actual two-host login/client, privacy, operations, Task 12, full-workflow, and pilot evidence remain separate gates. diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index e8778d0..59ece50 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -66,7 +66,9 @@ and permanent assets. The Sessions `0.3.0` prerequisite is also public. Final site integration, complete host query/CPU acceptance, provider/privacy and requested-client qualification, and pilots remain pending. -### Staff canned responses (Task 15 source addition) + + +### Staff canned responses (Task 15, published 0.2.9) The optional deployment-owned `cannedResponses` catalog supplies bounded, immutable plain-text versions for staff preview and explicit reply/note commands. diff --git a/docs/RESOLUTION_LEARNING.md b/docs/RESOLUTION_LEARNING.md index 3b6f53c..d727053 100644 --- a/docs/RESOLUTION_LEARNING.md +++ b/docs/RESOLUTION_LEARNING.md @@ -338,7 +338,9 @@ model validation requirements do not replace KB's actual guide requirements. Check-receipt and source-publication policy expiry also count elapsed time from the start of the invocation, including time spent awaiting verification ports. -### Candidate scoped comparison evidence + + +### Published 0.2.9 scoped comparison evidence The published `0.2.9` OpenRouter controller requires genuine comparison evidence before signing a new-create check. Selection carries the actual @@ -401,7 +403,7 @@ Support Work row; the optional recovery input is not caller authority and the App's ordinary two-argument verifier cannot grant this exception. If KB accepted but Support never retained its ACK, KB `0.1.8` has no read-only draft-write receipt lookup: the attempt stays unknown/held without a speculative create replay. -This candidate adds no Native query/CPU or host activation qualification. +SDK publication adds no Native query/CPU or host activation qualification. Successful independent checks permit private draft transfer without routine human pre-transfer approval. Staff approval applies to the **actual KB draft** @@ -434,8 +436,9 @@ authority. The exact-target and recovery contracts are exercised in [released-KB integration suite](../tests/resolution-learning-kb.test.ts). + -## Opt-in staged draft delivery (0.2.9 candidate) +## Opt-in staged draft delivery (published 0.2.9) Set `deliveryMode: 'staged'` on `createSupportDeskLearning` to separate delivery work across physical invocations. Forward the exact SDK-owned @@ -476,8 +479,8 @@ configuration checks run again. The application retains opaque Ticket/Source/Work confirmation, claim/lease and deadline fences at its conditional write boundary. Callback observations expire with their owning application call. The [staged delivery suite](../tests/resolution-learning-delivery-stages.test.ts) -exercises these phases and inline closing checks. Publication and complete -Native Workers Free 50/100 qualification remain pending for this candidate. +exercises these phases and inline closing checks. SDK publication is verified; +complete host Native Workers Free 50/100 qualification remains pending. In staged mode, `reconcileSource` processes one unconfirmed durable destination per invocation and skips confirmed entries. After one exact KB retirement diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index 63fc3de..59298d9 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -35,7 +35,16 @@ Forward the optional third argument on `confirmCustomerSuccess` and `signal?: AbortSignal` and a read-only `verifyBeforeCommit` callback that may return a synchronous literal-true assertion. See the [exact declarations and commit/recovery contract](RESOLUTION_LEARNING.md#final-human-success-and-evidence-guards-0210). -Return types and existing two-argument calls remain unchanged. +Existing two-argument signatures and return types remain supported. + +Current-authority checks also govern acknowledgements. `confirmCustomerSuccess` rechecks current +authority before and after its post-commit customer-view read, including for +two-argument callers. If access changes during that read, the SDK can refuse +the view and surface an error after the confirmation transaction was accepted. +That error does not roll back the accepted transaction or prove the command +failed. Retain the exact original command and retry receipt recovery only with +restored/current access and the required customer ownership; do not issue a +replacement command to explain the missing acknowledgement. Supply the original browser/entitlement guard for new host mutations, after body admission. The SDK awaits it after asynchronous proof/planning, freshly diff --git a/examples/ai/README.md b/examples/ai/README.md index 750af70..fdbdba2 100644 --- a/examples/ai/README.md +++ b/examples/ai/README.md @@ -5,11 +5,12 @@ dependencies. The root command builds the SDK and these TypeScript files, then runs `run.ts` from its compiled output. Node 22 and 24 are supported. The example uses public package entry points, an actual Storage Core Store, -and all four optional Support Desk coordinators from the unpublished `0.2.9` +and all four optional Support Desk coordinators from the unpublished `0.2.10` source candidate. It pins exact verified public KB application/contracts -`0.1.8`. Fresh Node 22/24 qualification must exercise that installed graph; -earlier `0.2.9`/KB `0.1.6` example results do not qualify this changed graph. -It is not a published Support `0.2.9` consumer qualification. It uses no provider +`0.1.8`, the same external KB selection as verified public Support `0.2.9`. +Node 22/24 source qualification must exercise the current candidate; historical +example results do not qualify it. Running this source example is separate from +the published `0.2.9` clean-consumer qualification. It uses no provider SDK, network client, mail provider, host framework, or production credentials. Its scripted `github.createIssue` throws; the engineering flow only links an existing fictional issue privately. @@ -51,10 +52,12 @@ must supply their own current authorities, verified provider route and evaluations, release attesters, usage ledger, and operational controls. Separate instances keep their own Store, configuration, cursors, and secrets. -The current synchronized Support Desk `0.2.8` release is published and strictly verified; -see the [publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). -Its published AI package pins KB `0.1.6`; the `0.2.9`/public KB `0.1.8` graph -above remains development-only until the SDK candidate is qualified and released. Production adoption retains +The current synchronized Support Desk `0.2.9` release is published and strictly verified; +see the [publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). +Its published AI package pins KB `0.1.8`. The historical +[`0.2.8` receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12) +retains its KB `0.1.6` graph. The local `0.2.10` source candidate remains +unpublished until separately qualified and released. Production adoption retains its own host acceptance gates. See [the existing human-support example](../composition/README.md), [host composition](../../docs/HOST_COMPOSITION.md), and the individual diff --git a/packages/ai/README.md b/packages/ai/README.md index d7ac1d2..46b1a90 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1,18 +1,26 @@ # @pegma/support-desk-ai -The local synchronized source candidate is unpublished `0.2.9`. Engineering -coordination selects optional application-owned model-planning/completion, +The local synchronized source candidate is unpublished `0.2.10`. Its internal +Support application pin is exact `0.2.10`; external KB application/contracts +retain exact verified public `0.1.8`. See the +[source handoff](../../docs/RELEASING.md#source-version-0210) and +[guard upgrade guidance](../../docs/UPGRADING.md#0210-final-success-and-evidence-guards). +Candidate source requires its own release qualification and publication before +production adoption. + +Published `0.2.9` engineering coordination selects optional application-owned model-planning/completion, proposal and dispatch observations while preserving fresh proof, authority, exact ACK recovery and the full fallback for older structural ports. Engineering -coordinator methods are unchanged. See the [candidate notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) +coordinator methods are unchanged. See the [release notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) and [worker contract](../../docs/ENGINEERING_EXPORT.md#candidate-029-worker-observations). -Its internal Support application pin is exact `0.2.9`; external KB application/ -contracts now pin exact verified public `0.1.8`; see its +The published `0.2.9` AI package pins its internal Support application at `0.2.9` +and exact public KB application/contracts `0.1.8`; see KB's [strict registry verification](https://github.com/pegma-dev/knowledge-base/releases/download/v0.1.8/registry-verification.json). -The changed SDK candidate graph requires fresh qualification. Published Support Desk `0.2.8` retains KB `0.1.6`. Candidate source does not -qualify registry publication, a host's query/CPU budget or activation. +That published graph passed strict registry and clean-consumer qualification. +Historical Support Desk `0.2.8` retains KB `0.1.6`. SDK qualification does not +establish a host's query/CPU budget or activation. -The candidate also accepts `deliveryMode: 'staged'` in +Published `0.2.9` also accepts `deliveryMode: 'staged'` in `createSupportDeskLearning`. Candidate generation, request preparation, KB write and completion run in separate physical invocations. Delivery checkpoints retain the existing `pending`/`delivery` result with optional @@ -28,7 +36,7 @@ Staged `reconcileSource` also advances one unconfirmed durable destination per invocation. An exact retirement attempt yields to a later physical readback under fresh retirement authority. Its existing result union is unchanged. -The unpublished candidate also adds `invocationMode: 'staged'` to release +Published `0.2.9` also adds `invocationMode: 'staged'` to release follow-up coordination. Durable model planning, one provider attempt and fresh completion use separate physical invocations. Work checks can separately opt into deferred preparation, paid precompute and fresh receipt completion. See @@ -36,10 +44,12 @@ the [follow-up invocation contract](../../docs/ENGINEERING_FOLLOWUP.md#candidate Optional, provider-neutral Support Desk answer, learning, engineering, and release follow-up coordination. -The current verified published synchronized release is `0.2.8`; -see the [publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). -Its exact internal Support application pin is `0.2.8`; external KB application -and contracts pins are exact `0.1.6`. Host activation and whole-invocation/CPU +The current verified published synchronized release is `0.2.9`; +see the [publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). +Its exact internal Support application pin is `0.2.9`; external KB application +and contracts pins are exact `0.1.8`. The earlier +[`0.2.8` receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12) +retains its original KB `0.1.6` graph. Host activation and whole-invocation/CPU acceptance retain separate gates. The published `0.2.1`/KB `0.1.2` artifacts and their original receipts remain immutable. @@ -340,9 +350,11 @@ evaluations, complete-workflow acceptance, and supervised pilots remain their separate activation gates. Provider SDKs, credentials, model selection, HTTP, customer UI, schedulers, and operational content logging remain host work. -## Optional OpenRouter adapter source candidate + -The unpublished source candidate exposes provider adapters through +## Optional OpenRouter adapter (published 0.2.9) + +Published `0.2.9` exposes provider adapters through `@pegma/support-desk-ai/openrouter`. The AI root entry remains provider-neutral. The optional entry contains the bounded transport, purpose-isolated durable usage ledger and engineering/learning independent-check adapters ported from @@ -389,7 +401,7 @@ plans. ### Release follow-up provider ports -The unpublished candidate adds `createSupportReleaseFollowupModel(options, +Published `0.2.9` adds `createSupportReleaseFollowupModel(options, logicalHost)` and `createSupportReleaseFollowupUsage({store, clock, policy})`. The model factory returns the SD05 configuration, evaluations, generator and qualified token counter. Its closed route binds `support_release_followup`, diff --git a/packages/application/src/engineering-mutation-guard.ts b/packages/application/src/engineering-mutation-guard.ts index 0529682..63a40b6 100644 --- a/packages/application/src/engineering-mutation-guard.ts +++ b/packages/application/src/engineering-mutation-guard.ts @@ -7,16 +7,11 @@ export function engineeringMutationBoundary( options?: EngineeringMutationOptions, ) { if (options === undefined) return undefined; - fields( - options, - "Engineering mutation options", - [], - ["signal", "verifyBeforeCommit"], - ); + fields(options, "Mutation options", [], ["signal", "verifyBeforeCommit"]); const signal = options.signal; const guard = options.verifyBeforeCommit; if (guard !== undefined && typeof guard !== "function") - throw new TypeError("Engineering mutation guard must be callable"); + throw new TypeError("Mutation guard must be callable"); if ( signal !== undefined && (signal === null || @@ -25,9 +20,8 @@ export function engineeringMutationBoundary( typeof signal.addEventListener !== "function" || typeof signal.removeEventListener !== "function") ) - throw new TypeError("Engineering mutation requires an AbortSignal"); - const aborted = () => - new DOMException("Engineering mutation aborted", "AbortError"); + throw new TypeError("Mutation requires an AbortSignal"); + const aborted = () => new DOMException("Mutation aborted", "AbortError"); const ensure = (): void => { if (signal?.aborted) throw aborted(); }; @@ -63,16 +57,12 @@ export function engineeringMutationBoundary( ensure(); if (proof !== undefined) { if (typeof proof !== "function") - throw new SupportDeskConflictError( - "Engineering mutation proof is not current", - ); + throw new SupportDeskConflictError("Mutation proof is not current"); const current: unknown = proof(); if (current !== true) { // Observe a malformed async return while refusing it synchronously. void Promise.resolve(current).catch(() => {}); - throw new SupportDeskConflictError( - "Engineering mutation proof is not current", - ); + throw new SupportDeskConflictError("Mutation proof is not current"); } } ensure(); diff --git a/packages/application/src/index.ts b/packages/application/src/index.ts index dcae1eb..cdfbce4 100644 --- a/packages/application/src/index.ts +++ b/packages/application/src/index.ts @@ -6455,7 +6455,7 @@ export function createSupportDeskApplication(options: { rows, partitionSizeWithAttachmentReserve(rows), ) - : { actions: [], additionalRows: 0 }; + : { actions: [], additionalRows: 0, atCommit: undefined }; const newRows = (operation === "take_over" ? 2 : 3) + learningMutation.additionalRows + @@ -6637,9 +6637,19 @@ export function createSupportDeskApplication(options: { if (!owns(ticket, customerSuccess.actorId)) throw new SupportDeskNotFoundError(); assertCurrent?.(); - customerSuccess.authorize(); - customerSuccess.mutation?.ensure(); } + const currentLearningActions = learningConfirmation.atCommit?.(); + if ( + currentLearningActions !== undefined && + currentLearningActions !== learningConfirmation.actions + ) + actions.splice( + learningMutation.actions.length, + learningConfirmation.actions.length, + ...currentLearningActions, + ); + customerSuccess?.authorize(); + customerSuccess?.mutation?.ensure(); if ((await records.transact(ticket.id, actions)).committed) { await safeProjectQueue(ticket.id); return updated; diff --git a/packages/application/src/resolution-learning.ts b/packages/application/src/resolution-learning.ts index 4435de8..a519af9 100644 --- a/packages/application/src/resolution-learning.ts +++ b/packages/application/src/resolution-learning.ts @@ -255,6 +255,59 @@ function heldSource( ...(pending === undefined ? {} : { pendingProofReference: pending }), }; } +interface EvidencePlan { + readonly actions: readonly Action[]; + readonly source: ResolutionLearningSourceRecord; + readonly additionalRows: number; +} + +/** Prepare both held alternatives before the host's final await. Selection is + * synchronous at the transaction boundary and never renews captured trust. */ +function evidenceCommitPlans( + clock: Clock, + stored: SourceVersion, + plan: EvidencePlan, + evidence: ResolutionEvidence | null, + product: ResolutionProductContext | null, + now: string, + pending: string, +) { + const hold = (reason: string): EvidencePlan => { + const source = heldSource(stored.value, now, reason, pending); + return { + source, + actions: [sourceAction(stored, source)], + additionalRows: 0, + }; + }; + const plans = [ + plan, + hold("product_context_unverified"), + hold("test_receipt_unverified"), + ] as const; + return { + plans, + select(): 0 | 1 | 2 { + if (plan.source.state !== "eligible") return 0; + const at = timestamp(clock.now(), "clock.now()"); + if ( + product === null || + timestamp(product.verifiedAt, "product.verifiedAt") > at || + timestamp(product.validUntil, "product.validUntil") < at + ) + return 1; + if ( + evidence?.kind === "successful_test" && + (timestamp(evidence.test.verifiedAt, "test.verifiedAt") > at || + timestamp(evidence.test.executedAt, "test.executedAt") > at || + timestamp(evidence.test.validUntil, "test.validUntil") < at) + ) + return 2; + return 0; + }, + }; +} + async function evidencePlan( deps: Dependencies, stored: SourceVersion, @@ -265,11 +318,7 @@ async function evidencePlan( pending: string, capacity: boolean, rows: readonly SupportRecord[], -): Promise<{ - readonly actions: readonly Action[]; - readonly source: ResolutionLearningSourceRecord; - readonly additionalRows: number; -}> { +): Promise { const source = stored.value; const hold = (reason: string) => { const next = heldSource(source, now, reason, pending); @@ -434,6 +483,7 @@ export function createResolutionLearningServices(deps: Dependencies): { ): Promise<{ readonly actions: readonly Action[]; readonly additionalRows: number; + readonly atCommit?: () => readonly Action[]; }>; } { const { records, options, clock } = deps; @@ -1040,7 +1090,16 @@ export function createResolutionLearningServices(deps: Dependencies): { room(ticket, rows, 3), rows, ); - const actions: Action[] = [ + const commitProof = evidenceCommitPlans( + clock, + source, + plan, + evidence, + trusted.product, + now, + command.commandId, + ); + const prepareActions = (plan: EvidencePlan): Action[] => [ { action: "putIfUnchanged", version: versioned.version, @@ -1058,6 +1117,11 @@ export function createResolutionLearningServices(deps: Dependencies): { ), receipt(command, hash, result(plan.source)), ]; + const alternatives = [ + prepareActions(commitProof.plans[0]), + prepareActions(commitProof.plans[1]), + prepareActions(commitProof.plans[2]), + ] as const; // All SDK reads/planning precede the last awaited host authority check. // A conflict discards this assertion and obtains a fresh one next time. authorize(); @@ -1065,10 +1129,14 @@ export function createResolutionLearningServices(deps: Dependencies): { mutation === undefined ? undefined : await mutation.verify(); authorize(); assertCurrent?.(); + const selected = commitProof.select(); authorize(); mutation?.ensure(); - if ((await records.transact(command.ticketId, actions)).committed) - return result(plan.source); + if ( + (await records.transact(command.ticketId, alternatives[selected])) + .committed + ) + return result(commitProof.plans[selected].source); } const previous = await replay(command, hash); authorize(); @@ -1343,7 +1411,20 @@ export function createResolutionLearningServices(deps: Dependencies): { capacityRows + 4 <= deps.limits.maxRecordsPerTicket - humanTail, rows, ); - return { actions: plan.actions, additionalRows: plan.additionalRows }; + const commitProof = evidenceCommitPlans( + clock, + source, + plan, + { kind: "customer_confirmation", actorId, lastVisibleMessageId }, + trusted.product, + ticket.updatedAt, + `success:${commandId}`, + ); + return { + actions: plan.actions, + additionalRows: plan.additionalRows, + atCommit: () => commitProof.plans[commitProof.select()].actions, + }; }, }; } diff --git a/packages/contracts/README.md b/packages/contracts/README.md index b858c5b..eebb454 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -1,19 +1,20 @@ # @pegma/support-desk-contracts -The local synchronized source version is `0.2.9`. See the -[release notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) +The local synchronized source version is unpublished `0.2.10`. See the +[source handoff](../../docs/RELEASING.md#source-version-0210), +[release notes](../../docs/RELEASE_NOTES.md#0210-final-success-evidence-guards) and [engineering read phases](../../docs/ENGINEERING_EXPORT.md#entry-points-and-authority). This package adds no new runtime API. -The current verified synchronized registry release is `0.2.8`; see the -[publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). -The synchronized `0.2.8` release includes the +The current verified synchronized registry release is `0.2.9`; see the +[publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). +The synchronized `0.2.9` release includes the [application/AI additions](../../docs/RELEASE_NOTES.md). Host adoption retains its own composition and activation gates. Provider-neutral ticket, requester, message, and event contracts shared by Support Desk packages and host applications. -The Task 15 source addition defines `CannedResponseDefinition` and +Task 15, published in `0.2.9`, defines `CannedResponseDefinition` and `CannedResponseSelection` for deployment-owned staff reply/note templates. These are configuration/command contracts, not new stored ticket fields or customer DTOs. See the [composition contract](../../docs/HOST_COMPOSITION.md#staff-canned-responses-task-15-source-candidate). @@ -59,6 +60,6 @@ checks permissions/ownership and current visible-message proof, commits Audit/receipts/work, and keeps private handling generations and evidence out of customer DTOs. Core performs pure transitions and validates its handling inputs. These changes first shipped in verified synchronized `0.2.0` and remain -in current `0.2.8`, with no model or KB dependency. See the current -[publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12); +in current public `0.2.9`, with no model or KB dependency. See the current +[publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13); host activation retains its own acceptance gates. diff --git a/packages/core/README.md b/packages/core/README.md index c14a3b9..1cffd4c 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -1,18 +1,19 @@ # @pegma/support-desk-core -The local synchronized source version is `0.2.9`. See the -[release notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) +The local synchronized source version is unpublished `0.2.10`. See the +[source handoff](../../docs/RELEASING.md#source-version-0210), +[release notes](../../docs/RELEASE_NOTES.md#0210-final-success-evidence-guards) and [engineering read phases](../../docs/ENGINEERING_EXPORT.md#entry-points-and-authority). -Task 15's unpublished source addition exposes pure `defineCannedResponse`, +Task 15, published in `0.2.9`, exposes pure `defineCannedResponse`, `defineCannedResponseCatalog`, `snapshotCannedResponseSelection` and `renderCannedResponse` helpers. They validate bounded plain-text definitions and literal value substitution; application services enforce staff permissions, catalog selection and atomic Audit. See [host composition](../../docs/HOST_COMPOSITION.md#staff-canned-responses-task-15-source-candidate). -The current verified synchronized registry release is `0.2.8`; see the -[publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). -The synchronized `0.2.8` release includes the +The current verified synchronized registry release is `0.2.9`; see the +[publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). +The synchronized `0.2.9` release includes the [application/AI additions](../../docs/RELEASE_NOTES.md). Host adoption retains its own composition and activation gates. @@ -68,7 +69,7 @@ application's explicit assistant creation sets that reserve marker. closed work first; ownership and visible-message evidence are application checks. Pure functions grant no permission, perform no model/KB work, and commit no Audit, receipt, or handoff row. These SD-01 changes first shipped in -verified synchronized `0.2.0` and remain in current `0.2.8`; see its -[publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). +verified synchronized `0.2.0` and remain in current public `0.2.9`; see its +[publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). Existing registry `0.1.1` artifacts remain immutable; host activation retains its own acceptance gates. diff --git a/packages/templates/README.md b/packages/templates/README.md index e98a0ba..ef11b98 100644 --- a/packages/templates/README.md +++ b/packages/templates/README.md @@ -1,12 +1,13 @@ # @pegma/support-desk-templates -The local synchronized source version is `0.2.9`. See the -[release notes](../../docs/RELEASE_NOTES.md#029-engineering-worker-observations) +The local synchronized source version is unpublished `0.2.10`. See the +[source handoff](../../docs/RELEASING.md#source-version-0210), +[release notes](../../docs/RELEASE_NOTES.md#0210-final-success-evidence-guards) and [engineering read phases](../../docs/ENGINEERING_EXPORT.md#entry-points-and-authority). This package adds no new runtime API. -The current verified synchronized registry release is `0.2.8`; see the -[publication receipt](../../docs/RELEASING.md#verified-028-publication-2026-11-12). -The synchronized `0.2.8` release includes the +The current verified synchronized registry release is `0.2.9`; see the +[publication receipt](../../docs/RELEASING.md#verified-029-publication-2026-11-13). +The synchronized `0.2.9` release includes the [application/AI additions](../../docs/RELEASE_NOTES.md). Host adoption retains its own composition and activation gates. @@ -30,7 +31,7 @@ Task 13 staff tags, response targets, and milestones are not customer template variables. Keep host-supplied customer notification maps free of this metadata; the generic renderer receives only the explicitly supplied variable allowlist. -Task 15's source-candidate staff canned responses are separate plain-text +Task 15's staff canned responses, published in `0.2.9`, are separate plain-text reply/note definitions, validated and expanded by core and application. See [host composition](../../docs/HOST_COMPOSITION.md#staff-canned-responses-task-15-source-candidate). Keep their catalog, internal-note text and template provenance out of customer diff --git a/tests/customer-success-mutation-guard.test.ts b/tests/customer-success-mutation-guard.test.ts index ab566f6..d6258c1 100644 --- a/tests/customer-success-mutation-guard.test.ts +++ b/tests/customer-success-mutation-guard.test.ts @@ -57,45 +57,142 @@ function successTransaction(trace: { for (const [backend, createStore] of learningStores) { describe(`customer success current mutation guard (${backend})`, () => { - it.each(["revoked session", "expired entitlement"] as const)( - "refuses %s observed after the real product await without committing confirmation, Source or Work", - async () => { - const gate = handlingBarrier(); - let f!: Fixture; - f = resolutionLearningFixture(createStore(), { - resolutionLearning: { - productContext: { - async resolve(context) { - await gate.wait(); - return f.trust.productFor(context); - }, - }, - }, - }); + it.each([ + ["guard", 60_000, true], + ["guard", 60_001, false], + ["assertion", 60_001, false], + ] as const)( + "proof freshness preserves human confirmation after %s advances %ims, with eligible learning=%s", + async (when, elapsed, eligible) => { + const f = resolutionLearningFixture(createStore()); const input = await packet(f); - const before = await f.rows(); - let current = true; - const guard = vi.fn(async () => { - if (!current) - throw new Error("Current browser authority unavailable"); - return (): true => true; + const result = await f.app.confirmCustomerSuccess(customer, input, { + async verifyBeforeCommit() { + if (when === "guard") f.advance(elapsed); + return (): true => { + if (when === "assertion") f.advance(elapsed); + return true; + }; + }, }); - const pending = caught( - f.app.confirmCustomerSuccess(customer, input, { - verifyBeforeCommit: guard, - }), - ); - await reached(gate, pending); - expect(guard).not.toHaveBeenCalled(); - current = false; - gate.release(); - const result = await pending; - expect(await f.rows()).toEqual(before); - expect(result).toHaveProperty("error"); - expect(guard).toHaveBeenCalledOnce(); + expect(result.ticket.status).toBe("resolved"); + const source = await f.source(); + expect(source.state).toBe(eligible ? "eligible" : "held"); + if (!eligible) + expect(source.heldReason).toBe("product_context_unverified"); + const rows = await f.rows(); + expect( + rows.filter((row) => row.kind === "customer_success"), + ).toHaveLength(1); + expect( + rows.filter((row) => row.kind === "resolution_learning_work"), + ).toHaveLength(eligible ? 1 : 0); }, ); + it("proof freshness selects a new product plan after a genuine Ticket CAS conflict", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + let guards = 0; + let conflicted = false; + f.observed.intercept(async (trace, commit) => { + if (!conflicted && successTransaction(trace)) { + const source = trace.actions.find( + (action) => + action.action !== "delete" && + (action.value as SupportRecord)?.kind === + "resolution_learning_source", + ); + expect( + source && source.action !== "delete" && source.value, + ).toMatchObject({ state: "held" }); + expect( + trace.actions.some( + (action) => + action.action !== "delete" && + (action.value as SupportRecord)?.kind === + "resolution_learning_work", + ), + ).toBe(false); + conflicted = true; + await f.app.addNote(staff, { + ...f.command("freshness-conflict"), + messageId: "freshness-note", + body: "A real concurrent note changes the Ticket version.", + }); + } + return commit(); + }); + await f.app.confirmCustomerSuccess(customer, input, { + async verifyBeforeCommit() { + if (++guards === 1) f.advance(60_001); + return (): true => true; + }, + }); + f.observed.intercept(undefined); + expect(conflicted).toBe(true); + expect(guards).toBe(2); + expect(f.trust.productCalls).toHaveLength(2); + expect((await f.source()).state).toBe("eligible"); + expect( + (await f.rows()).filter( + (row) => row.kind === "resolution_learning_work", + ), + ).toHaveLength(1); + }); + + it("observes cancellation triggered by the final literal-true assertion before any transaction", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const controller = new AbortController(); + await expect( + f.app.confirmCustomerSuccess(customer, input, { + signal: controller.signal, + verifyBeforeCommit: async () => (): true => { + controller.abort(); + return true; + }, + }), + ).rejects.toMatchObject({ name: "AbortError" }); + expect(await f.rows()).toEqual(before); + }); + + it("refuses current host authority denied after the real product await without committing confirmation, Source or Work", async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + productContext: { + async resolve(context) { + await gate.wait(); + return f.trust.productFor(context); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + let current = true; + const guard = vi.fn(async () => { + if (!current) throw new Error("Current browser authority unavailable"); + return (): true => true; + }); + const pending = caught( + f.app.confirmCustomerSuccess(customer, input, { + verifyBeforeCommit: guard, + }), + ); + await reached(gate, pending); + expect(guard).not.toHaveBeenCalled(); + current = false; + gate.release(); + const result = await pending; + expect(await f.rows()).toEqual(before); + expect(result).toHaveProperty("error"); + expect(guard).toHaveBeenCalledOnce(); + }); + it("rechecks an original permission changed during product verification even for legacy calls", async () => { const access = { ...customer, permissions: [...customer.permissions] }; let f!: Fixture; @@ -398,6 +495,7 @@ for (const [backend, createStore] of learningStores) { ).rejects.toThrow("Lost accepted"); f.observed.intercept(undefined); const acceptedRows = await f.rows(); + f.advance(60_001); const guard = vi.fn(async () => { throw new Error("Obsolete host mutation proof must not run"); }); diff --git a/tests/resolution-evidence-mutation-guard.test.ts b/tests/resolution-evidence-mutation-guard.test.ts index f26116d..b432e27 100644 --- a/tests/resolution-evidence-mutation-guard.test.ts +++ b/tests/resolution-evidence-mutation-guard.test.ts @@ -19,6 +19,7 @@ type Fixture = ReturnType; async function packet( f: Fixture, kind: "successful_test" | "staff_verified_fix" = "successful_test", + testLifetimeMilliseconds = 60_000, ): Promise { const terminal = await f.terminal(); const trust = { @@ -29,10 +30,18 @@ async function packet( actorId: staff.principalId, acceptedAt: f.clock.now(), }; - f.trust.issueTest("verified-run", { - ...trust, - product: f.trust.productFor(trust), - }); + f.trust.issueTest( + "verified-run", + { + ...trust, + product: f.trust.productFor(trust), + }, + { + validUntil: new Date( + Date.parse(f.clock.now()) + testLifetimeMilliseconds, + ).toISOString(), + }, + ); return { ...f.command("guarded-evidence"), expectedRevision: terminal.ticket.revision, @@ -83,45 +92,193 @@ function evidenceTransaction(trace: { for (const [backend, createStore] of learningStores) { describe(`resolution evidence current mutation guard (${backend})`, () => { - it.each(["revoked session", "expired entitlement"] as const)( - "refuses %s after the real test-receipt await without changing Source, Work, Audit or receipt", - async () => { - const gate = handlingBarrier(); - let f!: Fixture; - f = resolutionLearningFixture(createStore(), { - resolutionLearning: { - testReceipts: { - async verify(...args) { - await gate.wait(); - return f.learningOptions.testReceipts!.verify(...args); - }, - }, - }, - }); - const input = await packet(f); - const before = await f.rows(); - let current = true; - const guard = vi.fn(async () => { - if (!current) throw new Error("Current browser authority lost"); - return (): true => true; + it.each([ + ["product", "guard", 60_001, false], + ["product", "assertion", 60_001, false], + ["test", "guard", 60_001, false], + ["test", "assertion", 60_001, false], + ["both", "guard", 60_000, true], + ["both", "assertion", 60_000, true], + ] as const)( + "proof freshness selects %s after %s advances %ims, with eligible learning=%s", + async (proof, when, elapsed, eligible) => { + const f = resolutionLearningFixture(createStore()); + f.trust.setProduct({ + validUntil: new Date( + Date.parse(f.clock.now()) + (proof === "test" ? 120_000 : 60_000), + ).toISOString(), }); - const pending = caught( - f.app.submitResolutionEvidence(staff, input, { - verifyBeforeCommit: guard, - }), + const input = await packet( + f, + "successful_test", + proof === "product" ? 120_000 : 60_000, ); - await reached(gate, pending); - expect(guard).not.toHaveBeenCalled(); - current = false; - gate.release(); - const result = await pending; - expect(await f.rows()).toEqual(before); - expect(result).toHaveProperty("error"); - expect(guard).toHaveBeenCalledOnce(); - expect(f.trust.testCalls).toHaveLength(1); + const result = await f.app.submitResolutionEvidence(staff, input, { + async verifyBeforeCommit() { + if (when === "guard") f.advance(elapsed); + return (): true => { + if (when === "assertion") f.advance(elapsed); + return true; + }; + }, + }); + expect(result.state).toBe(eligible ? "eligible" : "held"); + if (!eligible) + expect((await f.source()).heldReason).toBe( + proof === "product" + ? "product_context_unverified" + : "test_receipt_unverified", + ); + expect( + (await f.rows()).filter( + (row) => row.kind === "resolution_learning_work", + ), + ).toHaveLength(eligible ? 1 : 0); }, ); + it("proof freshness holds a staff-verified fix when its product expires during the guard", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f, "staff_verified_fix"); + expect( + await f.app.submitResolutionEvidence(staff, input, { + async verifyBeforeCommit() { + f.advance(60_001); + return (): true => true; + }, + }), + ).toMatchObject({ state: "held" }); + expect((await f.source()).heldReason).toBe("product_context_unverified"); + expect( + (await f.rows()).filter( + (row) => row.kind === "resolution_learning_work", + ), + ).toHaveLength(0); + }); + + it("proof freshness rebuilds product and test plans after a genuine Source CAS conflict", async () => { + let f!: Fixture; + let verifications = 0; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + testReceipts: { + async verify(receipt, context, signal) { + if (++verifications > 1) f.trust.issueTest(receipt, context); + return f.learningOptions.testReceipts!.verify( + receipt, + context, + signal, + ); + }, + }, + }, + }); + const input = await packet(f); + let guards = 0, + conflicted = false; + f.observed.intercept(async (trace, commit) => { + if (!conflicted && evidenceTransaction(trace)) { + const source = trace.actions.find( + (action) => + action.action !== "delete" && + (action.value as SupportRecord)?.kind === + "resolution_learning_source", + ); + expect( + source && source.action !== "delete" && source.value, + ).toMatchObject({ state: "held" }); + expect( + trace.actions.some( + (action) => + action.action !== "delete" && + (action.value as SupportRecord)?.kind === + "resolution_learning_work", + ), + ).toBe(false); + const records = f.backing.collection(supportRecords); + const row = await records.getVersioned({ + partition: input.ticketId, + id: "learning-source", + }); + if (row?.value.kind !== "resolution_learning_source") + throw new Error("Real Source missing"); + conflicted = await records.putIfUnchanged(row.value, row.version); + } + return commit(); + }); + expect( + await f.app.submitResolutionEvidence(staff, input, { + async verifyBeforeCommit() { + if (++guards === 1) f.advance(60_001); + return (): true => true; + }, + }), + ).toMatchObject({ state: "eligible" }); + f.observed.intercept(undefined); + expect(conflicted).toBe(true); + expect(guards).toBe(2); + expect(f.trust.productCalls).toHaveLength(2); + expect(verifications).toBe(2); + expect( + (await f.rows()).filter( + (row) => row.kind === "resolution_learning_work", + ), + ).toHaveLength(1); + }); + + it("observes cancellation triggered by the final literal-true assertion before any transaction", async () => { + const f = resolutionLearningFixture(createStore()); + const input = await packet(f); + const before = await f.rows(); + const controller = new AbortController(); + await expect( + f.app.submitResolutionEvidence(staff, input, { + signal: controller.signal, + verifyBeforeCommit: async () => (): true => { + controller.abort(); + return true; + }, + }), + ).rejects.toMatchObject({ name: "AbortError" }); + expect(await f.rows()).toEqual(before); + }); + + it("refuses current host authority denied after the real test-receipt await without changing Source, Work, Audit or receipt", async () => { + const gate = handlingBarrier(); + let f!: Fixture; + f = resolutionLearningFixture(createStore(), { + resolutionLearning: { + testReceipts: { + async verify(...args) { + await gate.wait(); + return f.learningOptions.testReceipts!.verify(...args); + }, + }, + }, + }); + const input = await packet(f); + const before = await f.rows(); + let current = true; + const guard = vi.fn(async () => { + if (!current) throw new Error("Current browser authority lost"); + return (): true => true; + }); + const pending = caught( + f.app.submitResolutionEvidence(staff, input, { + verifyBeforeCommit: guard, + }), + ); + await reached(gate, pending); + expect(guard).not.toHaveBeenCalled(); + current = false; + gate.release(); + const result = await pending; + expect(await f.rows()).toEqual(before); + expect(result).toHaveProperty("error"); + expect(guard).toHaveBeenCalledOnce(); + expect(f.trust.testCalls).toHaveLength(1); + }); + it("fences staff verification after the real product await too", async () => { const gate = handlingBarrier(); let f!: Fixture; @@ -443,6 +600,7 @@ for (const [backend, createStore] of learningStores) { ).rejects.toThrow("Lost accepted"); f.observed.intercept(undefined); const accepted = await f.rows(); + f.advance(60_001); const guard = vi.fn(async () => { throw new Error("Obsolete guard must not run"); }); From 6d7702f6a995e49430d3552ece61a4f7a85ec6e4 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 02:25:06 -0500 Subject: [PATCH 4/4] Clarify published spec and public authorization export compatibility --- docs/MVP_SPEC.md | 8 +++++--- docs/UPGRADING.md | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/MVP_SPEC.md b/docs/MVP_SPEC.md index b8dc36b..b88f8c5 100644 --- a/docs/MVP_SPEC.md +++ b/docs/MVP_SPEC.md @@ -258,7 +258,9 @@ Staff can: The UI should make customer-visible replies visually distinct from internal notes and require an explicit choice before sending. -## Staff canned responses (Task 15 source candidate) + + +## Staff canned responses (Task 15, published 0.2.9) Hosts may configure a bounded catalog of immutable plain-text response versions. Authorized staff preview substitutions and explicitly submit a reply or internal @@ -270,8 +272,8 @@ retries recover the original result under current permissions. Each accepted use records template ID/version through the existing reply/note Audit action in the same transaction. Internal notes and provenance stay out of -customer DTOs and automatic mail. This unpublished source slice adds no package -version or durable layout change. See the +customer DTOs and automatic mail. This feature is included in verified public +`0.2.9` and adds no new package or durable layout. See the [composition contract](HOST_COMPOSITION.md#staff-canned-responses-task-15-source-candidate). ## Lifecycle extras (Buildout Task 13) diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index 59298d9..c221b98 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -29,6 +29,22 @@ The optional AI package and repository development pins retain exact public KB application/contracts `0.1.8`; `zod@4.6.7` and other external selections are unchanged. The root remains private at `0.0.0`. +The unchanged `@pegma/authorization-core@0.4.0` dependency already exports +`serializeAccessContext`. Its [original public tarball](https://registry.npmjs.org/@pegma/authorization-core/-/authorization-core-0.4.0.tgz) +contains the named JavaScript export at `dist/index.js:121` and its declaration +at `dist/index.d.ts:22`. The original archive SHA-256 is +`1e449abf4815b99984f1991cb03be3a337edd1b092e523723b3eff8ed07625aa`; +its [lockfile](../pnpm-lock.yaml) integrity is +`sha512-GkagQwyDfKokB2Nm9EAo6cvKB8c90VN6Or6IdaWeMwCeuseOxDZ8ccxKqccW9YorByE6rHhr2nbxjsNWorZTHQ==`. +Installed public JavaScript/declaration bytes matched that archive, and direct +named ESM imports resolved to a function on Node 22.18.0 and 24.18.0. +The [candidate CI run](https://github.com/pegma-dev/support-desk/actions/runs/43383002448) +at [`f7bae286`](https://github.com/pegma-dev/support-desk/commit/f7bae28648cb760c6ee69430cdf3cf92b7b612da) +passed 4,171 tests in each Node 22/24 lane and the normal packed-consumer checks +([Node 22 artifact](https://github.com/pegma-dev/support-desk/actions/runs/43383002448/artifacts/14016684868), +[Node 24 artifact](https://github.com/pegma-dev/support-desk/actions/runs/43383002448/artifacts/14017652633)). +These calls use an existing public export; the dependency pin stays `0.4.0`. + Forward the optional third argument on `confirmCustomerSuccess` and `submitResolutionEvidence` through host adapters. Its exported type is `ConfirmCustomerSuccessOptions` or `SubmitResolutionEvidenceOptions`, with