diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index b685764..2c64108 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -17,11 +17,16 @@ at signed source passed independent exact-byte, signature/provenance and registry-consumer verification. Existing Identity and Support Desk keep their `@pegma/rate-limit@0.2.0` dependency. The current host selects all five Support -Desk packages at `0.2.3`, including the optional AI coordinator used only by the -separate default-disabled synthetic stage. The -[verified Support Desk `0.2.3` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.3) +Desk packages at `0.2.5`, including the optional AI coordinator. The separate +synthetic stage remains default-disabled. The +[verified Support Desk `0.2.5` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5) pins its optional AI dependency on KB application/contracts `0.1.5`. +The learning port forwards actual KB errors without the obsolete `0.1.2` +constructor alias or class-translation shim. The earlier `0.2.1` / nested `0.1.2` +assembly and its failed isolated production-layout diagnostic remain historical; +they neither establish nor replace current-graph qualification. + All four exact KB `0.1.5` packages are installed in the manifest and lockfile. The answering read-batching release retains the shared report factory and governed authoring-context/report-query APIs. Its producer verification covers @@ -51,10 +56,13 @@ handlers. Actual stage broker and CPU proof remain pending, together with the existing production, customer and provider acceptance gates. The current manifest and lockfile pin released KB `0.1.5`, -`@pegma/storage-cloudflare-d1@0.4.6` and genuine `@pegma/storage-core@0.4.0`. +`@pegma/storage-cloudflare-d1@0.4.7` and genuine `@pegma/storage-core@0.4.0`. The D1 adapter itself retains that exact Core `0.4.0` dependency; no source alias, local archive, override or forced Core deduplication supplies the canonical -graph. The frozen registry installation is complete. +graph. The frozen registry installation is complete. The current adapter is +identified by the [D1 `0.4.7` release](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.7). + +The following D1 `0.4.6` receipt and PG-01 figures describe the earlier checkpoint. The [qualified D1 `0.4.6` release](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.6) uses signed source @@ -74,8 +82,20 @@ Wrangler's explicit dry run packages the Worker without uploading it. These checks use the published registry graph, without source aliases. Earlier source-alias runs remain historical diagnostics. -PG-01's full review, CI and automatic deployment passed. The subsequent -human-control changes require their own current-head review and CI. +PG-01's full review, CI and automatic deployment passed at that earlier checkpoint. + +### Public 0.2.5 adoption checkpoint + +On 2026-11-11, the normal public Support `0.2.5` / D1 `0.4.7` graph passed local +Node `22.18.0` checks, all 1,125 tests, the static build and the main-Worker +packaging dry run. The normal suites comprised 1,002 Node tests across 62 files, +121 Native D1 tests across 12 files and two Bench Ticket Worker/D1/R2 tests, +with zero skips. +[CI run 43034119881](https://github.com/pegma-dev/pegma.dev/actions/runs/43034119881) +for [commit `3a4e5c6a`](https://github.com/pegma-dev/pegma.dev/commit/3a4e5c6a3924acad5764db7173046380f360166f) +also passed the configured frozen install, check, full 1,125 tests and build. +These results describe that source checkpoint. Review and deployment acceptance +remain pending for the changed host. Actual-client acceptances remain at zero and no pilot has run. Keep activation disabled through the remaining deployed-host, staging/privacy and actual-client acceptance gates. @@ -119,9 +139,11 @@ acceptances, provider/staging controls, production readiness, or pilot results. The [host policy](../worker/src/support-access.ts) keeps authority explicit: - `Support` retains its original six Support Desk permissions (queue read, - staff reply, notes, assignment, management and Audit read) and the explicit - human takeover introduced in Support Desk `0.2.0`. Existing - assignments are not migrated or silently granted KB powers. + staff reply, notes, assignment, management and Audit read) and adds explicit + human takeover plus explicit learning read, evidence submission, review and + withdrawal under policy `pegma.dev-policy-5`. + Learning processing is not granted. Existing assignments are not migrated + or silently granted KB powers. - `Knowledge` is a separately assigned role for collection reads, draft and evidence work, human report review, publication and withdrawal. Admin-only collection/governance mutation controls remain separate. @@ -241,10 +263,21 @@ that epoch's replay horizon; only the head's latest exact reset operation has its bounded retry acknowledgement. Preserve required operational evidence before choosing a reset rather than treating receipts as permanent history. -There is no report-backed private-source bridge in this integration. Browser -and agent draft inputs cannot attach arbitrary `sourceReferences`; PG01 -provenance remains empty/read-only. A later Support-source integration must -compose the real authorization/withdrawal verifier separately. +Browser and agent draft inputs cannot attach arbitrary `sourceReferences`; +PG-01 authoring provenance remains read-only through those routes. The optional +[Support learning composition](SUPPORT_COMPOSITION.md#optional-resolution-learning) +now supplies a real SDK source bridge for trusted host assembly. That bridge +checks current source authority, eligibility and the exact staff-reviewed +article/provenance target; it is separate from test-report receipt verification. +A report receipt alone never establishes private-source approval. Support review +uses a complete immutable intent for submit, receipt and explicit cancellation. +Its new-mutation guard checks fresh learning review/queue plus KB draftRead and +provenanceRead before and after the SDK proof, with an additional original-browser +fence in HTTP. Exact accepted-receipt recovery and cancellation retain current +review/queue authority without requiring obsolete KB rights; neither operation +publishes an article or supplies new source approval. The root +request composition supplies no private-source verifier and keeps Knowledge +disabled; source-enabled production wiring is not implied by the factory seam. Once the actual KB accepts evidence and publishes revision 1, a later draft or elapsed report/check TTL alone does not withdraw that approved publication. @@ -288,8 +321,11 @@ two isolated rate invocations followed by one ready-hint invocation: task. This reduces the previous 29 ready opportunities to 19; ready hints remain a latency aid, with atomic SDK jobs and physical recovery preserved. -The original four other expressions and all 15 rotating cleanup lanes remain -in place. Minutes 58 and 59 have no `RATE_LIMIT_CRON` invocation. Before +The original four other expressions remain in place. The cleanup rotation +retains its original 15 lanes and adds one separately gated learning-review +discovery lane, for 16 exclusive lanes. That lane emits queue hints only; a +review phase runs in a later Queue invocation. The default root supplies no +trusted learning bundle and keeps the review flag off. Minutes 58 and 59 have no `RATE_LIMIT_CRON` invocation. Before merging, inventory every Worker's current cron triggers in the deployment account: pushes to `main` deploy these schedules even while Knowledge is disabled. Deployment replaces this Worker's existing expressions with these @@ -359,7 +395,7 @@ completions cannot overwrite a newer generation. Already committed projection writes are not rolled back after acknowledgement uncertainty. The existing Knowledge turn in the -[15-lane cleanup schedule](../worker/src/maintenance-schedule.ts) independently +[16-lane cleanup schedule](../worker/src/maintenance-schedule.ts) independently calls `repairRetrievalPage` with `limit:1` and `maxBatches:1`. Complete physical cycles and the SDK's existing atomic article-change jobs remain the recovery path for a lost hint, collection/policy changes and unfinished work. The ready @@ -378,13 +414,22 @@ checks the current `PEGMA_KNOWLEDGE_ENABLED=true` flag before Store access and after awaits; disabled ticks do no projection work. Limiter cleanup remains independent of that flag and projection failures. -This phase has no private-source eligibility verifier. Retained nonempty -`privateSources` references remain blocked/unavailable. A future source-enabled -composition must provide its real authorization/withdrawal ports in both -request and repair paths; there is no allow-all fallback. HTTP handlers do not -scan the corpus or expose maintenance DTOs. Coarse diagnostics contain counts -and fixed stages, not article IDs, cursors, queries, private bodies or exception -text. +The three host factories accept an optional real `privateSources` verifier. +Source-enabled assembly must pass the same current authorization/withdrawal +bridge to `createKnowledgeRuntime`, `createKnowledgeRetrievalReady` and +`createKnowledgeRetrievalMaintenance`; request-only wiring cannot qualify +projection work. Omission blocks retained nonempty source references; there is +no allow-all fallback. The root request and scheduled compositions do not yet +supply that bridge and keep Knowledge disabled. The real-Memory +[composition test](../worker/src/support-learning-composition.test.ts) exercises +accepted Support sources and current reopen/withdraw/missing-ticket refusals +through the actual factories, without bypassing KB evidence/publication gates. +Those tests do not qualify an activated source-enabled D1 path: source checks add +reads and require new whole-invocation query/parameter, CPU, quota and privacy +measurements. `readBatchSize:512` coalesces prepared reads; it does not cap SDK +work or prove the Free budget. HTTP handlers do not scan the corpus or expose +maintenance DTOs. Coarse diagnostics contain counts and fixed stages, not +article IDs, cursors, queries, private bodies or exception text. Projection-dependent portal discovery/search stays empty or unavailable until current repair qualifies it. Known-ID publication reads retain their existing diff --git a/docs/SUPPORT_ASSISTANT_STAGE.md b/docs/SUPPORT_ASSISTANT_STAGE.md index 01718a2..cc349d7 100644 --- a/docs/SUPPORT_ASSISTANT_STAGE.md +++ b/docs/SUPPORT_ASSISTANT_STAGE.md @@ -51,7 +51,7 @@ checked during cloud qualification. See ## Run the local checks Use the repository's supported Node version and frozen dependency install. -The current package selection is Support Desk `0.2.3` with direct Knowledge Base +The current package selection is Support Desk `0.2.5` with direct Knowledge Base `0.1.5`; [package.json](../package.json) is authoritative. From the repository root: @@ -81,13 +81,17 @@ which blocks physical call 51 and parameter 101 before execution or binding. Batches retain their actual statement count; the physical-call metric counts a native batch invocation once. -The 35 entry and recovery cases passed against the selected `0.2.3` packages +At the earlier checkpoint, 35 entry and recovery cases passed against the +then-selected `0.2.3` packages on Node 22.18.0. Recovery profiles recorded 31 physical D1 calls for preparation and 50 for answering, with zero blocked calls. Preparation made zero model or reservation calls. Answering used one model call, one reservation and one reconciliation, with the persisted ledger stable across later duplicates. -These results apply to the fictional fixture. Deployed broker timing, retry -delivery, CPU use and wider workloads retain their qualification gates. +These historical results apply to that fictional fixture. The current public +`0.2.5` graph passed the normal 1,125-test local/CI +[adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint). +Deployed broker timing, retry delivery, CPU use and wider workloads retain +their qualification gates. ## Generate a fictional seed locally diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index bc8c833..704cdf5 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -17,11 +17,11 @@ provider and customer activation retain their acceptance gates. See the Exact published versions: -- `@pegma/support-desk-application@0.2.3` -- `@pegma/support-desk-contracts@0.2.3` -- `@pegma/support-desk-core@0.2.3` -- `@pegma/support-desk-templates@0.2.3` -- `@pegma/support-desk-ai@0.2.3` (isolated scripted stage only) +- `@pegma/support-desk-application@0.2.5` +- `@pegma/support-desk-contracts@0.2.5` +- `@pegma/support-desk-core@0.2.5` +- `@pegma/support-desk-templates@0.2.5` +- `@pegma/support-desk-ai@0.2.5` (optional coordinator) - `@pegma/authorization-admin@0.4.0` (role administration service) - `@pegma/authorization-core@0.4.0` (AccessContext resolution) - `@pegma/authorization-policy@0.4.0` (PolicyDocumentV1 schema validation) @@ -31,16 +31,24 @@ All five Support Desk packages have completed producer publication and registry qualification. The optional AI package selects exact KB application and contracts `0.1.5`; the host selects all four KB packages at that version. Producer qualification and installation do not complete host or provider -acceptance. [Verified Support Desk `0.2.3` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.3), +acceptance. [Verified Support Desk `0.2.5` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5), [verified KB `0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5). Peers already present on the host: `@pegma/storage-core@0.4.0`, -`@pegma/storage-cloudflare-d1@0.4.6`, `@pegma/sessions@0.2.0`, +`@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.2.0`, `@pegma/rate-limit@0.2.0`, `@pegma/identity@0.1.2`, `@pegma/spine@0.1.1`. These are direct host selections; the lockfile retains each released package's own dependencies, including Support Desk's Spine `0.1.2`. No override or forced deduplication replaces that graph. +The earlier [qualified Support 0.2.2 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.2) +uses signed source +[`99cf4e67da1d2357d99fd80389a96318a6e2cc93`](https://github.com/pegma-dev/support-desk/commit/99cf4e67da1d2357d99fd80389a96318a6e2cc93). +[Strict release verification](https://github.com/pegma-dev/support-desk/actions/runs/42907283767/job/130161276758) +qualifies those historical producer packages. The current public `0.2.5` graph +has passed the [normal local and CI validation checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint). +Review and deployment acceptance remain pending for the changed host. + ## Storage namespace Support Desk uses the existing `IDENTITY_DB` D1 binding. Isolation is by @@ -70,7 +78,7 @@ unified host policy's `defaults` (no paid entitlement): - `support.ticket.reply.own` - `support.ticket.request_person.own` -Policy version: `pegma.dev-policy-4` — one `PolicyDocumentV1` for the whole +Policy version: `pegma.dev-policy-5` — one `PolicyDocumentV1` for the whole host, schema-validated in tests (see `docs/ROLE_ADOPTION_PLAN.md`). ### Staff (stored `Support` role) @@ -91,6 +99,10 @@ The `Support` role maps to: - `support.ticket.manage` - `support.audit.read` - `support.ticket.take_over` +- `support.learning.read` +- `support.learning.evidence.submit` +- `support.learning.review` +- `support.learning.withdraw` `Admin` and `Knowledge` alone do not grant Support permissions. Taking over changes handling authority; the existing assignment action remains separate. @@ -261,12 +273,109 @@ invocation. | `/staff/support/ticket/?id=…` | Staff ticket detail, compose, lifecycle | | `/staff/roles` | Role administration (Admin role holders) | +## Optional resolution learning + +The current source selects all five published Support Desk `0.2.5` packages +with the four direct KB `0.1.5` packages. AI `0.2.5` also declares exact KB +`0.1.5` dependencies. The public forwarding port preserves KB error instances; +no KB `0.1.2` alias, translation shim, second Store, override or private SDK +import supplies this assembly. The earlier Support `0.2.1` / nested KB `0.1.2` +compatibility assembly and its failed isolated production-layout diagnostic are +historical, not current graph or host-acceptance evidence. + +The staged learning review admission and Queue worker retained in this branch +use the published, strictly verified Support Desk `0.2.5` APIs. The combined +public graph passed normal local and CI validation; review and deployment +acceptance remain pending. Runtime availability and feature activation retain +their existing trusted composition and readiness controls. + +[Learning intake and processing](../worker/src/support-learning.ts) are separate, +default-disabled SDK boundaries. A real source verifier, current service/staff +authority, product context, independently verified checks, target mapping, +configuration/data controls, local counter, usage accounting and model port are +required where the corresponding SDK operation needs them. Missing, expired +or throwing readiness holds work; no model, route, source approval or check +receipt is synthesized. Enrollment alone produces an unverified generation-zero +source. Staff-verified resolution evidence establishes eligibility; generation +and staff approval of the exact checked KB target remain separate. Neither +approval nor delivery publishes a guide: ordinary KB evidence, review and +publication gates still apply. + +Policy `pegma.dev-policy-5` adds four explicit learning permissions to `Support`; +it grants neither learning processing nor KB staff access. Private proposal +reads and new review commits also require separately current KB `draftRead` and +`provenanceRead`, normally through `Knowledge` or `Admin`. Browser submissions +and trusted direct SDK reviews enforce fresh KB and learning review/queue +permissions before and after the actual SDK proof. HTTP requires the complete +intent and adds its original-browser fence. +Accepted receipt recovery and explicit cancellation retain current review/queue +and browser authority without requiring obsolete KB proof. Customer ticket +responses, agent scopes and the public KB DTOs gain no source, private evidence or learning-work fields. + +The [optional HTTP adapter](../worker/src/support-learning-handlers.ts) uses the +existing cookie/session, Origin, CSRF and durable admission ports. It preserves +the original credential and permission ceiling around awaited work, rechecks +current stored roles, bounds staff operations and withholds stale replies, +including after a committed mutation. Client command bytes are retained; +ambiguous acknowledgements require the exact original actor/operation/ticket +packet. The proposal route now returns a complete immutable SDK review intent; +submit, receipt lookup and cancellation use the same full packet and identity. +A lost cancellation ACK keeps retries on cancellation, rather than resending +approval. Arbitrary GET success or a null receipt cannot settle an unknown +mutation. Private source and proposal content is rendered as text and cleared on +denial or owner change; retained recovery controls remain available only under +their current server capability and real review/queue authority. See +[the exact HTTP and recovery contract](SUPPORT_LEARNING.md). + +The default [root Support composition](../worker/src/index.ts) supplies no +trusted learning bundle. The optional server composition requires that bundle, +its explicit readiness callback, the review queue binding and +`PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED` set exactly to `"true"`; the checked-in +flag remains `"false"`. Without that composition, learning routes remain 404 and +no review phase runs. The exclusive learning cleanup lane discovers durable SDK +work and emits opaque queue hints; a separate Queue delivery advances at most +one SDK phase. Hints and delivery retries grant no review authority. Actual +product/check/target/configuration/usage ports and trusted admission remain +activation work; no model, provider or client is activated by this source. + +Source eligibility must also reach every KB application that reads or repairs a +learned publication: pass the same live bridge as `privateSources` to +`createKnowledgeRuntime`, `createKnowledgeRetrievalReady` and +`createKnowledgeRetrievalMaintenance`. Their default omission refuses nonempty +private-source provenance. Reopening, withdrawal or a missing source invalidates +read eligibility immediately; indexing cannot restore it. The real-Memory +[composition regression](../worker/src/support-learning-composition.test.ts) +uses SDK-created sources, actual staff decisions, report-backed evidence and +publication through these host factories. It is not deployed-provider, privacy, +Native D1 query-budget, Free CPU, daily-quota or pilot qualification. Knowledge +request/maintenance batching and activation limits remain documented in +[Knowledge composition](KNOWLEDGE_COMPOSITION.md). + +## Staged assistant retrieval is separate + +AI `0.2.2` introduced explicit `stagedRetrieval:true`, retained by the current +`0.2.5` selection; omission remains monolithic. The preparation attempt retrieves authorized sources and records a +bounded no-call request without reserving paid usage. Only its durably +acknowledged finish returns `prepared`. The host must return and schedule a +genuinely later physical invocation at or after `nextAttemptAt`, never loop or +use `waitUntil` to perform generation in the same invocation. Paid generation +uses attempt two, so application and assistant budget limits must both permit +at least two attempts. Unknown preparation/finish remains `pending` and does not +authorize a provider call. `AssistantProcessResult` includes `prepared` even for +an opted-out runtime, so exhaustive consumers must handle it. Fresh source, +customer, full configuration and usage-scope checks remain required across +phases. Configuration timestamps and opaque `usageScopeRef` must remain exact; +reattestation or scope reissuance invalidates preparation rather than being +normalized away. This learning composition does not register an answering worker, and producer publication proves no host Free/CPU, +provider or activation result. + ## Maintenance and health The separate cleanup cron (`0-58 * * * *`) runs one rotating task per invocation, including Support Desk queue repair, inactive projection sweep, -and each Support/Admin rate-limit policy. Each task runs once per fifteen -eligible ticks (minute 59 is omitted), with independent queue cursors and no +each Support/Admin rate-limit policy and the separately gated learning-review +discovery lane. Each task runs once per sixteen eligible ticks (minute 59 is +omitted), with independent queue cursors and no writes for unchanged bookmarks. Identity Mail send and reconciliation have separate invocations (`* * * * *` and `1-59 * * * *`); KB ready hints and their isolated rate cleanup diff --git a/docs/SUPPORT_LEARNING.md b/docs/SUPPORT_LEARNING.md new file mode 100644 index 0000000..29ba8dc --- /dev/null +++ b/docs/SUPPORT_LEARNING.md @@ -0,0 +1,353 @@ +# Support resolution learning + +Maintained by RetireGolden, LLC. + +This optional assembly turns a verified support resolution into a private KB +proposal for human review. Approval records the exact checked proposal; KB +publication remains a separate human workflow. The learning panel does not +publish articles, call a model, or notify customers. + +The factories, authenticated routes and staff panel exist in source. The current +[Worker entry point](../worker/src/index.ts) does **not** compose the learning +handler, processing worker or required trusted processing ports. Learning remains +default off. Passing factory and synthetic integration tests is not deployment or +activation evidence. + +## Packages and authority + +The host selects all five published Support Desk packages at **0.2.5** and its +four direct Knowledge Base packages at **0.1.5**. The qualified +[Support 0.2.5 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5) +also uses exact KB **0.1.5** public contracts. The +[public forwarding port](../worker/src/support-learning-ports.ts) preserves the +actual KB error instances; the obsolete KB 0.1.2 constructor alias and translation +shim are removed. See [package pins](../package.json) and the +[lockfile](../pnpm-lock.yaml). Package publication and installation do not qualify +this host's changed review flow or activate learning. + +Historically, Support **0.2.1** used nested KB **0.1.2** while this host selected +direct KB **0.1.5**. The exact `@pegma/knowledge-base-ai-compat` registry alias and +recognized-error translation belonged to that earlier assembly. Its failed +isolated production-layout diagnostic remains historical evidence; neither its +ordinary fixture passes nor that failure qualifies the current 0.2.5 graph. + +The current [host policy](../worker/src/support-access.ts) grants four human +learning permissions through the actual stored, audited **Support** role: + +| Permission | Human operation | +| --- | --- | +| `support.learning.read` | Read source state and work metadata | +| `support.learning.evidence.submit` | Enroll, submit a staff-verified fix, enter the invalidation route | +| `support.learning.review` | Approve or reject an exactly checked proposal | +| `support.learning.withdraw` | Withdraw a source for privacy, access or deletion | + +The routes also require current Support queue-read authority. Invalidation keeps +the SDK's learning-withdraw check as well as the HTTP evidence-submit entry +check; the entry permission never replaces application/resource guards. Human Support does +not gain `support.learning.process`, service identities or KB permissions. +Proposal reads and new review mutations additionally require current KB +`draftRead` **and** `provenanceRead`, normally through the separately assigned +**Knowledge** role. The runtime rechecks those permissions, learning review and +queue authority before and after the SDK's actual commit-proof callback, for +browser submissions and trusted direct SDK reviews. HTTP requires a complete +review intent and fences the original browser session and headers at commit. Exact accepted-receipt recovery and explicit +cancellation require current learning review/queue and browser authority without +reconstructing obsolete KB proof or requiring a retained Knowledge grant. +Knowledge or Admin alone does not grant Support access. Learning approval does +not grant KB review or publication authority. + +Agent delegation remains exactly the existing three scopes: KB draft-read, +draft-write and evidence-submit. There is no added learning, provenance, +human-report-confirmation, review, publication or role-administration scope. +Browser role fields never establish authority. + +## Source generation zero is real state + +Enrollment creates `unverified`, `sourceGeneration: 0`, `resolutionCycle: 1`. +It does not establish verified evidence or create generation work. Source +counters are nonnegative; work and review keys require positive generations. +A valid generation-zero source read or mutation ACK must not be treated as an +unknown failed write. + +The first staff-verified fix uses the current ticket revision and resolution +cycle, a current customer-visible solution message, and a bounded verification +reference. The SDK requires a resolved or closed ticket with `resolvedAt` and +current human permission. The server supplies the authenticated actor and trusted +product/build facts. Current eligible evidence advances the initial source to +`eligible`, generation **1**, and creates bounded work. Missing or expired trusted +product context can instead produce **held generation 0** with no work or model +call; that is also a valid acknowledged result. + +The panel enables initial evidence from current resolved-ticket metadata; it does +not require generation 1 before the evidence that creates it. Work, proposal and +review controls require a current **eligible, positive-generation** source, and +review additionally requires the separately checked target. A zero counter alone +never qualifies a source for processing. Reopened, invalidated or withdrawn +sources cannot borrow authority from an earlier review. + +Processing uses only the permitted customer-visible solution/transcript rows; +internal notes never enter model input or customer KB output. A generated +candidate is bounded untrusted data, not publication proof. Trusted checks, +current target selection and human KB governance remain separate gates. +The actual transitions, including `unverified0 -> eligible1` and a missing-product +`held0`, run through real auth, routes and SDKs in +[the browser integration tests](../src/support-learning-integration.test.ts). +The [panel tests](../src/support-learning.test.ts) also cover invalid counters, +terminal-ticket prerequisites and exact unknown-packet recovery. + +## Authenticated HTTP contract + +[The handler](../worker/src/support-learning-handlers.ts) owns only this prefix: + +`/api/support/admin/tickets/:ticketId/learning` + +It accepts the existing authenticated browser session, same-origin mutation +headers and current CSRF token. Current Identity, stored roles, session and +request-header bindings are fenced across awaited reads, body parsing, operations +and final responses. A postcommit denial can withhold an ACK while a durable SDK +effect remains; it does not roll the effect back. + +All mutation bodies are closed objects. Ordinary packets cannot independently +supply actor, role, target, provenance, product, policy, timestamp, +receipt-authority or correlation fields. Review packets echo the complete +server-prepared immutable intent, including its actor/target/policy coordinates; +that echo grants no authority and remains subject to SDK validation. The server +preserves `commandId` exactly, including case, and derives its own stable +correlation identity from actor, operation, ticket and that exact ID for submit, +receipt and cancellation alike. Scalar IDs and reasons are bounded to 200 +characters. A hash-only body fails review packet validation. Ticket revisions, +resolution cycles and requested work/review generations are positive safe +integers. Query generations use canonical positive decimal text, with no +duplicate or extra query keys. The existing JSON reader limits the body to +64 KiB with a 10-second +body deadline. + +| Method and suffix | Accepted fields or query | Result boundary | +| --- | --- | --- | +| `GET` base | No query | Source generation, resolution cycle, state, reconciliation flag and optional hold reason | +| `GET /work` | Exactly `sourceGeneration=N`, positive | Work generation, status, stage, proposal-presence flag and optional hold reason | +| `GET /proposal` | Exactly `sourceGeneration=N`, positive | Actual checked private KB draft and complete immutable review intent, including source/work/target and full trusted policy binding | +| `POST /enroll` | `commandId`, `expectedRevision` | Actual SDK source result; initial generation may be zero | +| `POST /enroll-recovery` | The byte-identical retained enrollment body | `200` accepted/pending/superseded retry-and-reconcile result | +| `POST /evidence` | `commandId`, `expectedRevision`, `resolutionCycle`, `solutionMessageId`, `verificationReference` | Server fixes the evidence kind to `staff_verified_fix` | +| `POST /evidence-recovery` | The byte-identical retained evidence body | `200` accepted/pending/superseded retry-and-reconcile result | +| `POST /review` | `commandId`, `intent`, `decision`; optional `reason` | `approve` or `reject`; accepted result is `{outcome:'accepted',result}` | +| `POST /review-receipt` | The identical retained review packet | Actual accepted/cancelled receipt union, or `null`; no stale source/KB reconstruction | +| `POST /review-cancel` | The identical retained review packet | Atomically fence that exact unaccepted review, or recover its existing accepted receipt | +| `POST /invalidate` | `commandId`, `reason` | Evidence/product/check-policy invalidation | +| `POST /withdraw` | `commandId`, `reason` | Privacy/access/deletion withdrawal | + +Invalidation reasons are exactly `evidence_revoked`, `product_binding_revoked` and +`check_policy_revoked`. Withdrawal reasons are exactly `privacy_withdrawal`, +`source_access_revoked` and `source_deleted`. + +Ordinary source/work DTOs contain no KB body, generated candidate, draft payload, +private proof or exact delivery request. The separate proposal route requires KB +authority and prepares the actual draft plus the SDK's full immutable intent. +The entire policy binding, including verification and expiry timestamps, remains +part of that exact command. A new review checks current source, target and +policy plus the fresh human commit guards. Accepted receipt recovery precedes +obsolete proof reads. A changed proposal needs a new explicit review after the +old command is acknowledged or explicitly cancelled; it cannot rebind an earlier +command ID. Cancellation does not undo an already accepted review. A `null` +receipt or any error is not a terminal acknowledgement. An external commit-guard +refusal may conservatively surface as `503` acknowledgement uncertainty; retain +the packet instead of inferring a new command is safe. + +Success is `{result, csrfToken}`. Errors use closed safe codes and the existing +no-store JSON response convention; durable rate limiting supplies `Retry-After` +when applicable. Raw dependency errors, model output and private proof are not +returned as error messages. + +### Retained intake retry and reconciliation + +The existing manual Retry control sends retained enrollment/evidence packets to +`enroll-recovery` or `evidence-recovery` with byte-identical original bodies. +These operations can apply the original valid command; they are retry and +reconciliation endpoints rather than read-only receipt/status queries. They +retain the original EvidenceSubmit/queue permissions, authenticated browser, +CSRF, limiter and closing authority fences. There is no automatic mutation +polling or new command ID. + +Each `200` response uses `{result, csrfToken}`. Its result always binds +`ticketId`, the exact `commandId` and `operation:'enroll'|'evidence'`, plus one +closed variant: + +| Outcome | Additional fields and meaning | +| --- | --- | +| `accepted` | `result` contains the actual SDK source result for that exact command | +| `pending` | The original command remains unresolved | +| `superseded`, newer revision | `expectedRevision` and strictly newer `observedRevision` prove that the old-revision command cannot apply in the future. This variant has no `fence` field | +| `superseded`, same-revision evidence | Equal `expectedRevision` and `observedRevision`, with required `fence` set to `solution_unavailable`, `resolution_unavailable` or `resolution_cycle_changed`, prove that the original evidence command cannot apply in the future | + +A superseded result leaves the earlier historical outcome unknown. The panel +requires its closing same-actor/session/epoch checks before releasing that +retained owner and directs the operator to read current state before another +action. Generic `409`/`503` responses, mutable-read failures and other errors +retain ownership. The server attempts exact SDK recovery before observing the +current ticket and retries that exact command again after the proof before +reporting superseded. For same-revision evidence, it verifies the current +resolution status and customer-visible solution message, or separately reads +the current source cycle with the existing learning-read permission. Repairs +to these prerequisites advance the ticket revision. Enrollment has no +same-revision content-fence result. + +A pending result keeps the original packet. If the ticket needs an ordinary +reply or status change, an authorized operator can use another staff tab and +then retry the exact original packet here after the revision advances. Reads, +generic conflicts and an unrecognized same-revision fence do not release the +retained owner. + +### Opt-in staged review HTTP + +The staged protocol uses the same authenticated prefix and complete retained +`{commandId, intent, decision, reason?}` packet as inline review. It requires the +configured staged capability. The staff-ticket response's optional +`learningStagedReviewEnabled` hint selects this protocol in the panel; current +server authority and SDK guards still decide every operation. + +| Method and suffix | Accepted body | Status and result | +| --- | --- | --- | +| `POST /review-queue` | The complete original review packet | `202` when the durable intent is pending; `200` for an existing accepted/cancelled result | +| `POST /review-queue-status` | The identical retained review packet | `200` with pending status, an accepted/cancelled result, or `null` | +| `POST /review-queue-cancel` | The identical retained review packet | `200` with the exact cancellation or an already accepted result | + +Each success retains the `{result, csrfToken}` envelope. A pending result has +`outcome:'pending'`, `ticketId`, `commandId`, `phase:'proof'|'commit'`, boolean +`claimed` and `held`, and canonical ISO `expiresAt`. It records an admitted human +intent, not a completed review or KB publication. Claims and proof phases remain +SDK-owned. Expiry, a hold, a `null` observation or an error does not settle the +original command. Accepted receipt recovery and cancellation use current +browser/review/queue authority without reconstructing obsolete KB proofs; new +admission and proof still require their current KB authority. + +After a valid non-held pending acknowledgement, the panel schedules only +review-status requests: at most ten automatic polls, thirty seconds apart. +A hold, terminal result, changed owner/ticket context or suspension stops polling. +The limit leaves the exact packet available for explicit status/retry/cancel +recovery. Polling never submits another approval or changes its command bytes, +and an unknown cancellation keeps cancellation as the retained operation. + +See the actual +[HTTP tests](../worker/src/support-learning-handlers.test.ts) and +[router tests](../worker/src/support-learning-routing.test.ts). + +## One panel, current capability, exact retry + +The [staff ticket page](../src/pages/staff/support/ticket.astro) loads one +[persistent panel instance](../public/staff-support-learning.js), wired by the +[existing controller](../public/staff-support-ticket.js) to its current session, +CSRF and request primitives. Private content uses inert text rendering. + +Only a fully refreshed current staff detail response with +`learningEnabled === true` can show the panel. This boolean is a display hint, +not a credential. [The router](../worker/src/support-api.ts) emits it only when the +optional server callback is configured, after current stored Support, +Identity/session and ticket reads. Absent capability is false; the browser does +not infer it from a 404. The separate `learningReviewRecoveryEnabled` hint can +keep only a retained review's receipt/cancel controls available when ordinary +learning reads are unavailable. It grants no authority; the server still checks +the original browser and current review/queue permissions. Recovery controls +remain outside the hidden private-draft panel. The old detail JSON shape stays +unchanged when the callback is omitted. The learning namespace is dispatched +before legacy generic mutations, and stays 404 without both a configured handler and a current strict +true readiness callback. + +A sent action retains its original actor, ticket, route and **exact JSON bytes** +in the panel's page-lifetime closure. A timeout, denial, malformed ACK or raced +session change leaves it unresolved. No GET, new proposal or apparent state +change acknowledges it. Recovery uses the original account and ticket with +current CSRF and the identical retained packet. Explicit receipt lookup or exact submission retry can recover +acceptance without reopening obsolete source/KB facts. Explicit cancellation +becomes sticky: after an unknown cancellation ACK, Retry keeps cancelling the +same command instead of resending approval. A null receipt, ordinary GET or new +proposal never clears it. A valid accepted/cancelled ACK must also pass the +closing same-session check before the packet can clear; no replacement command +ID is invented. + +Ticket refresh, sign-out, address changes and account A-to-B-to-A transitions +clear private DOM immediately while preserving that unresolved packet for its +owner. Pending state blocks competing writes and automatic navigation; sign-in +opens separately and the page has an unload guard. This is in-memory intent +preservation for the current page, not a new browser persistence service. A full +page unload discards that closure, so the controller does not automatically +navigate away to recover from a 401. + +## Compose trusted factories before activation + +The source seams are optional and preserve previous defaults: + +| Factory or seam | Host responsibility | +| --- | --- | +| [Support runtime](../worker/src/support-desk.ts) `resolutionLearning` option | Supply reviewed SDK intake options; ordinary runtime construction keeps intake off | +| [Application option helper and source bridge](../worker/src/support-learning.ts) | Intake `enabled` is explicit; construct the source verifier from current real Support facts before KB | +| [Learning processing ports](../worker/src/support-learning-ports.ts) | Supply actual service, KB and retirement authority, verified configuration, checks, model, usage, target selection and local token counter | +| [Learning runtime](../worker/src/support-learning.ts) | Supply actual applications, source verifier, clock and a current staff resolver; `processingEnabled` defaults false and missing ports hold work before claiming or paying | +| [Knowledge runtime](../worker/src/knowledge-runtime.ts) `privateSources` option | Pass the same current source verifier into the direct KB application and its ready path | +| [Projection application and maintenance](../worker/src/knowledge-retrieval-maintenance.ts), [ready factory](../worker/src/knowledge-retrieval-ready.ts) `privateSources` options | Preserve that verifier when constructing projection/repair applications, so derived hints cannot bypass current source authority | +| [HTTP handler](../worker/src/support-learning-handlers.ts) and [Support router](../worker/src/support-api.ts) | Supply real auth, lazy learning runtime, existing durable limiter and current surface/readiness callbacks. The runtime supplies trusted KB, checks and clock ports. | + +Intake, model processing and HTTP availability are separate controls. Model +processing defaults off; an incomplete processing assembly returns a held result. +Do not gate privacy withdrawal, invalidation or source reconciliation on the model +switch. With their real authority ports present, cleanup can continue while +models are off. Current source verification can refuse an already published guide +immediately after reopening or withdrawal; physical reconciliation does not +restore publication authority. These paths are exercised in +[the learning assembly tests](../worker/src/support-learning.test.ts). + +No provider route, account/project configuration, service grant, scheduler or +worker is constructed from an HTTP packet. Staged review requires +`PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED` exactly `"true"`, a +`SUPPORT_LEARNING_REVIEWS` binding and a trusted `learningReviews` composition +whose readiness callback returns true. The checked-in flag is `"false"`, and the +production default `createWorker()` supplies no such learning bundle. The flag +alone supplies neither that runtime nor its trusted processing ports. See the +[composition controls](SUPPORT_COMPOSITION.md#optional-resolution-learning). + +For executed lower-layer composition, see +[Bench Ticket](../recipes/bench-ticket/README.md), its +[composition](../recipes/bench-ticket/composition.ts) and +[composition tests](../recipes/bench-ticket/composition.test.ts). That recipe is a +support-queue foundation, not a learning activation recipe. The learning assembly +itself is explicit in the public +[SDK fixture](../worker/src/support-learning-fixtures.ts) and authenticated +integration tests; all business data and external model/check ports there are +synthetic. + +## Validation status and remaining gates + +At the earlier Support **0.2.1** / direct KB **0.1.5** learning checkpoint, +**24 Memory cases and three genuine local Native D1 cases** passed; the HTTP +surface passed **39 cases**. That earlier focused browser/backend run passed +**93 cases**: 24 assembly, 45 panel, nine actual browser integration and 15 router +cases, with zero errors in its Astro, Worker and recipe check. These historical +counts overlap the assembly baseline. They predate the earlier 0.2.2 adoption and +full-intent/commit-guard changes and do not qualify the current host source. +The normal public `0.2.5` [adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint) +passed 1,125 tests locally and in CI. Current review and deployment acceptance +remain pending. + +Relevant executable sources are the +[Memory assembly](../worker/src/support-learning.test.ts), +[Native D1 assembly](../worker/src/support-learning.d1.test.ts), +[HTTP](../worker/src/support-learning-handlers.test.ts), +[panel](../src/support-learning.test.ts), +[browser integration](../src/support-learning-integration.test.ts) and +[router](../worker/src/support-learning-routing.test.ts) tests. + +The normal Native suite and its bounded HTTP/Queue profiles passed at that +checkpoint. Those fixture-profile results leave CPU/day limits, deployment, +actual client/provider privacy evidence, complete customer/staff/admin workflow +acceptance and pilot gates open. A separate +native answering run with released Support 0.2.1, KB 0.1.5 and the D1 adapter +failed the Workers Free 50-call whole-invocation limit. Published Support +**0.2.2** introduced opt-in staged assistant retrieval, separately from learning: +preparation consumes attempt one without paid usage or a model call, and paid +generation consumes attempt two in a genuinely later physical invocation. Both +attempt limits must allow at least two. Only a durable acknowledged no-call finish +returns `prepared`; an uncertain finish remains `pending`. Default behavior stays +monolithic, and an opted-in host must return rather than resume through the same +invocation or `waitUntil`. These producer semantics are not a passed whole-host +Free, CPU or daily-quota result. Neither grouped reads nor historical focused +source results close activation. diff --git a/package.json b/package.json index ae5c98e..9b823fd 100644 --- a/package.json +++ b/package.json @@ -43,13 +43,13 @@ "@pegma/rate-limit-paged": "npm:@pegma/rate-limit@0.3.3", "@pegma/sessions": "0.2.0", "@pegma/spine": "^0.1.1", - "@pegma/storage-cloudflare-d1": "0.4.6", + "@pegma/storage-cloudflare-d1": "0.4.7", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-ai": "0.2.3", - "@pegma/support-desk-application": "0.2.3", - "@pegma/support-desk-contracts": "0.2.3", - "@pegma/support-desk-core": "0.2.3", - "@pegma/support-desk-templates": "0.2.3", + "@pegma/support-desk-ai": "0.2.5", + "@pegma/support-desk-application": "0.2.5", + "@pegma/support-desk-contracts": "0.2.5", + "@pegma/support-desk-core": "0.2.5", + "@pegma/support-desk-templates": "0.2.5", "@pegma/webhooks": "0.1.1", "agents": "^0.20.1", "zod": "^4.4.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b6af3b4..bae2a7b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -75,26 +75,26 @@ importers: specifier: ^0.1.1 version: 0.1.1 '@pegma/storage-cloudflare-d1': - specifier: 0.4.6 - version: 0.4.6 + specifier: 0.4.7 + version: 0.4.7 '@pegma/storage-core': specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.3 - version: 0.2.3 + specifier: 0.2.5 + version: 0.2.5 '@pegma/support-desk-application': - specifier: 0.2.3 - version: 0.2.3 + specifier: 0.2.5 + version: 0.2.5 '@pegma/support-desk-contracts': - specifier: 0.2.3 - version: 0.2.3 + specifier: 0.2.5 + version: 0.2.5 '@pegma/support-desk-core': - specifier: 0.2.3 - version: 0.2.3 + specifier: 0.2.5 + version: 0.2.5 '@pegma/support-desk-templates': - specifier: 0.2.3 - version: 0.2.3 + specifier: 0.2.5 + version: 0.2.5 '@pegma/webhooks': specifier: 0.1.1 version: 0.1.1 @@ -1201,32 +1201,32 @@ packages: resolution: {integrity: sha512-jueFYJ3oJUacKdiERkEZ7R34xDMiEWXqn4MSA5bpTXzsXhWSap4EJUzKXtXnXuLPPjwJWLn5uoQe98kWQ6NS8A==} engines: {node: '>=22'} - '@pegma/storage-cloudflare-d1@0.4.6': - resolution: {integrity: sha512-DjBRoRq5C6sWgL2KWdWOcW0F3N7HHuRu1i7Gr8SM4Aeh4FpEh1hQwIdMvkXpPHCd48CMqLJz8M5HYYR+/sRUgw==} + '@pegma/storage-cloudflare-d1@0.4.7': + resolution: {integrity: sha512-Y31+USsM+MHIBN93xgGxjgr5cxBFc1qUEx2bXTeDoYK36nl5YvKfWQlidKeBvtMtMClx47g0QTbklE5A0WUB8g==} engines: {node: '>=22'} '@pegma/storage-core@0.4.0': resolution: {integrity: sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==} engines: {node: '>=22'} - '@pegma/support-desk-ai@0.2.3': - resolution: {integrity: sha512-6xkWXPuOAyPboqvnpybP4bMLMmxpOMw5WQAr9NypL18iEKr5E3J/AJbDPaVWSNr03ossPHLSD+JrIJCbkuQRFg==} + '@pegma/support-desk-ai@0.2.5': + resolution: {integrity: sha512-N2IFpoiD1g8tAgZjmBb3OcNxZiAZNDwNMVxxUy/1SkVZOT0r+THDw/R21MWw1raF6LsZdurnAZ8AyZFLX+RaCw==} engines: {node: '>=22'} - '@pegma/support-desk-application@0.2.3': - resolution: {integrity: sha512-Ul64+A+5ccIcdFiAnzVdjnm7L3hXSPbz7U/g5ZREkEPMDs3uX/c9/pMpBy7yZIAJvrYLIizbctEv5NpoAuARsg==} + '@pegma/support-desk-application@0.2.5': + resolution: {integrity: sha512-RwDvWkelRKYTyKxx/8xp8FFTtV2nKjLlsHFD3y6a2hU0ZOeeigbWpmyflY0eB/qwlIEFaCn1MPSfCykNgP4ZOg==} engines: {node: '>=22'} - '@pegma/support-desk-contracts@0.2.3': - resolution: {integrity: sha512-Xa4jHOpe30s+tAlJB1ZGfY/kIEZ0eCKg5bbo3oVqsPqRVtTtUU/dXP25KldrNOG3RFUDQo3ASjbjXzLsgDsvhA==} + '@pegma/support-desk-contracts@0.2.5': + resolution: {integrity: sha512-XKzPVnhOpd0PUmzcNjeYE1bh5+RFWM9O+rHwqCDaVR9a+jUvh7u2ENoGSSxg6GG1FYRwqhoWCpTMCY3wEAZwZw==} engines: {node: '>=22'} - '@pegma/support-desk-core@0.2.3': - resolution: {integrity: sha512-BgF2/WnDXW5dbqShOHRhwQ0i/cWHuNlUkWVxfW8abZ5/qN2wW9MqAO3dci3hjK6DT5i4SpzKgnT7Zzx0a9f5IA==} + '@pegma/support-desk-core@0.2.5': + resolution: {integrity: sha512-9hXyfL15CqJfSPSmgeJZ8xbGD8ZuBCQsceci5RlesP3wEjhdqVZHYC9fEDj6PuL1locvoanmTBXsIVkU52LWQw==} engines: {node: '>=22'} - '@pegma/support-desk-templates@0.2.3': - resolution: {integrity: sha512-VMXt8BsVI8p74b9EfJzW9Y1EaUXMhKnY/RWW/k46EEH0qKIYz6f6WIq6iRaVL8z+fh2AbTaA6WsGjMWF56nDLw==} + '@pegma/support-desk-templates@0.2.5': + resolution: {integrity: sha512-W9DXJJ465b3BCnn9AgViRXqSd0fIHTRD/w6TU+1cmHj7C61zcg7vg5Qk7CEZ4raPwrWsp1JvNQxtAHRMNSeOjw==} engines: {node: '>=22'} '@pegma/webhooks@0.1.1': @@ -4180,39 +4180,39 @@ snapshots: '@pegma/spine@0.1.2': {} - '@pegma/storage-cloudflare-d1@0.4.6': + '@pegma/storage-cloudflare-d1@0.4.7': dependencies: '@pegma/storage-core': 0.4.0 '@pegma/storage-core@0.4.0': {} - '@pegma/support-desk-ai@0.2.3': + '@pegma/support-desk-ai@0.2.5': dependencies: '@pegma/authorization-core': 0.4.0 '@pegma/knowledge-base-application': 0.1.5 '@pegma/knowledge-base-contracts': 0.1.5 '@pegma/spine': 0.1.2 - '@pegma/support-desk-application': 0.2.3 + '@pegma/support-desk-application': 0.2.5 - '@pegma/support-desk-application@0.2.3': + '@pegma/support-desk-application@0.2.5': dependencies: '@pegma/audit': 0.2.0 '@pegma/authorization-core': 0.4.0 '@pegma/mail': 0.1.1 '@pegma/spine': 0.1.2 '@pegma/storage-core': 0.4.0 - '@pegma/support-desk-contracts': 0.2.3 - '@pegma/support-desk-core': 0.2.3 + '@pegma/support-desk-contracts': 0.2.5 + '@pegma/support-desk-core': 0.2.5 - '@pegma/support-desk-contracts@0.2.3': + '@pegma/support-desk-contracts@0.2.5': dependencies: '@pegma/spine': 0.1.2 - '@pegma/support-desk-core@0.2.3': + '@pegma/support-desk-core@0.2.5': dependencies: - '@pegma/support-desk-contracts': 0.2.3 + '@pegma/support-desk-contracts': 0.2.5 - '@pegma/support-desk-templates@0.2.3': {} + '@pegma/support-desk-templates@0.2.5': {} '@pegma/webhooks@0.1.1': dependencies: diff --git a/public/staff-support-learning.js b/public/staff-support-learning.js new file mode 100644 index 0000000..e2264a0 --- /dev/null +++ b/public/staff-support-learning.js @@ -0,0 +1,528 @@ +/* Optional staff learning panel. The host supplies its existing authenticated + * request/session readers and calls suspend before hiding/changing staff views. + * This module registers no route, reads no roles and creates no persistent store. */ +(function () { + const invalid = () => Object.assign(new Error('invalid_response'), { status: 502 }); + const scalar = (value, maximum = 200) => { + if (typeof value !== 'string' || value.length < 1 || value.length > maximum || /[\u0000-\u001f\u007f-\u009f]/u.test(value)) + throw new Error('invalid_input'); + return value; + }; + const positive = (value) => { + if (!Number.isSafeInteger(value) || value < 1) throw invalid(); + return value; + }; + // SourceResult starts at zero; an unsuccessful first proof can remain held0. + // Positive work/review keys are a separate published SDK contract. + const sourceCounter = (value) => { + if (!Number.isSafeInteger(value) || value < 0) throw invalid(); + return value; + }; + const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); + const withdrawalReasons = ['privacy_withdrawal', 'source_access_revoked', 'source_deleted']; + const invalidationReasons = ['evidence_revoked', 'product_binding_revoked', 'check_policy_revoked']; + + function createPanel(options) { + const { root, request, readSession } = options; + const document = options.document ?? globalThis.document; + if (!root || typeof request !== 'function' || typeof readSession !== 'function') + throw new TypeError('Learning panel requires the existing host request/session readers.'); + let epoch = 0; + let context = null; + let session = null; + let source = null; + let work = null; + let shownBinding = null; + let pending = null; + let pendingAction = 'submit'; + let pollTimer = null; + let polls = 0; + let busy = false; + let ready = false; + let retryAt = 0; + const controllers = new Set(); + const now = options.now ?? (() => Date.now()); + const commandId = options.commandId ?? (() => crypto.randomUUID()); + const status = element('p', 'Learning tools are not loaded.'); + status.role = 'status'; + status.ariaLive = 'polite'; + const refreshButton = button('refresh', 'Read learning source', () => refresh()); + const privatePanel = element('section'); + const sourceText = element('p'); + const workText = element('p'); + const proposalText = element('pre'); + const readWorkButton = button('work', 'Read learning work', () => read('work')); + const proposalButton = button('proposal', 'Read private KB proposal', () => read('proposal')); + const enrollButton = button('enroll', 'Enroll this resolved ticket', () => mutate('enroll')); + const solution = field('solution', 'Public solution message ID'); + const verification = field('verification', 'Staff verification reference'); + const evidenceButton = button('evidence', 'Record staff-verified fix', () => mutate('evidence')); + const reviewReason = field('review-reason', 'Review reason (optional)'); + const approveButton = button('approve', 'Approve shown proposal', () => mutate('approve')); + const rejectButton = button('reject', 'Reject shown proposal', () => mutate('reject')); + const withdrawReason = choice('withdraw-reason', 'Withdrawal reason', withdrawalReasons); + const withdrawButton = button('withdraw', 'Withdraw learning source', () => mutate('withdraw')); + const invalidateReason = choice('invalidate-reason', 'Invalidation reason', invalidationReasons); + const invalidateButton = button('invalidate', 'Invalidate learning evidence', () => mutate('invalidate')); + const retryButton = button('retry', 'Retry the previous exact action', () => retry()); + const receiptButton = button('check-review', 'Check the unresolved review', () => recoverReview('receipt')); + const cancelButton = button('cancel-review', 'Cancel the unresolved review', () => recoverReview('cancel')); + privatePanel.append(sourceText, workText, readWorkButton, proposalButton, + proposalText, enrollButton, solution.label, verification.label, evidenceButton, + reviewReason.label, approveButton, rejectButton, withdrawReason.label, + withdrawButton, invalidateReason.label, invalidateButton); + root.replaceChildren(element('h2', 'Resolution learning'), + element('p', 'Staff review only. Approved proposals remain KB drafts for a separate publication review.'), + status, refreshButton, privatePanel, retryButton, receiptButton, cancelButton); + hidePrivate(); + controls(); + + function element(tag, text) { + const node = document.createElement(tag); + if (text !== undefined) node.textContent = text; + return node; + } + function button(action, label, run) { + const node = element('button', label); + node.type = 'button'; + node.dataset.learningAction = action; + node.addEventListener('click', () => { void run(); }); + return node; + } + function field(name, labelText) { + const label = element('label', labelText + ' '); + const input = element('input'); + input.type = 'text'; + input.maxLength = 200; + input.autocomplete = 'off'; + input.dataset.learningField = name; + label.append(input); + return { label, input }; + } + function choice(name, labelText, values) { + const label = element('label', labelText + ' '); + const input = element('select'); + input.dataset.learningField = name; + for (const value of values) { + const option = element('option', value.replaceAll('_', ' ')); + option.value = value; + input.append(option); + } + input.value = values[0]; + label.append(input); + return { label, input }; + } + function notice(message, error = false) { + status.textContent = message; + status.dataset.tone = error ? 'error' : 'neutral'; + } + function hidePrivate() { + privatePanel.hidden = true; + sourceText.textContent = ''; + workText.textContent = ''; + proposalText.textContent = ''; + solution.input.value = ''; + verification.input.value = ''; + reviewReason.input.value = ''; + source = null; + work = null; + shownBinding = null; + ready = false; + } + function stopPolling() { + if (pollTimer !== null) globalThis.clearTimeout?.(pollTimer); + pollTimer = null; + } + function pollReview(generation, candidate, held) { + stopPolling(); + // Poll only a durably admitted intent, never an ambiguous failed write. + // Ten read-only polls bound automatic traffic; explicit recovery remains. + if (held || polls >= 10 || candidate.queued !== true || pending !== candidate || + generation !== epoch || context === null || typeof globalThis.setTimeout !== 'function') return; + pollTimer = globalThis.setTimeout(() => { + pollTimer = null; + if (pending !== candidate || generation !== epoch || context === null || busy) return; + ++polls; + void recoverReview('receipt'); + }, 30_000); + } + function canRecordEvidence() { + return source !== null && source.state !== 'withdrawn' && context?.resolved === true; + } + function canReadWork() { + return source !== null && source.state === 'eligible' && source.sourceGeneration > 0; + } + function controls() { + refreshButton.disabled = busy || context === null; + const blocked = busy || !ready || context === null; + for (const node of [enrollButton, evidenceButton, approveButton, rejectButton, + withdrawButton, invalidateButton]) node.disabled = blocked || pending !== null; + evidenceButton.disabled ||= !canRecordEvidence(); + approveButton.disabled ||= shownBinding === null || !canReadWork(); + rejectButton.disabled ||= shownBinding === null || !canReadWork(); + readWorkButton.disabled = blocked || !canReadWork(); + proposalButton.disabled = blocked || !canReadWork() || work?.hasProposal !== true; + retryButton.hidden = pending === null; + retryButton.disabled = busy || context === null || (pending?.review !== true && !ready) || pending === null || + pending.subject !== context?.actorSubject || pending.ticketId !== context?.ticketId; + for (const node of [receiptButton, cancelButton]) { + node.hidden = pending?.review !== true; + node.disabled = busy || context === null || pending?.review !== true || + pending.subject !== context?.actorSubject || pending.ticketId !== context?.ticketId; + } + if (pending?.review === true && pendingAction === 'cancel') retryButton.textContent = 'Retry the exact cancellation'; + else if (pending?.queued === true) retryButton.textContent = 'Retry the exact queued review intent'; + else if (pending?.intake) retryButton.textContent = 'Retry and reconcile the previous intake action'; + else retryButton.textContent = 'Retry the previous exact action'; + for (const node of [solution.input, verification.input, reviewReason.input, + withdrawReason.input, invalidateReason.input]) node.disabled = blocked || pending !== null; + } + function cancelReads() { + for (const controller of controllers) controller.abort(); + controllers.clear(); + } + function current(generation) { + if (generation !== epoch || context === null) + throw Object.assign(new Error('stale_view'), { stale: true }); + } + function sameSession(left, right) { + return left.subject === right.subject && left.csrfToken === right.csrfToken; + } + async function viewer(generation, expected) { + const raw = await readSession(); + current(generation); + const next = Object.freeze({ + subject: scalar(raw?.subject ?? raw?.account?.subject), + csrfToken: scalar(raw?.csrfToken, 2_000), + }); + if (next.subject !== context.actorSubject || + (expected && !sameSession(next, expected)) || + (pending && (pending.subject !== next.subject || pending.ticketId !== context.ticketId))) + throw Object.assign(new Error('session_changed'), { status: 401 }); + return next; + } + async function call(path, init, generation, actor) { + current(generation); + const controller = new AbortController(); + controllers.add(controller); + try { + const result = await request(path, { + ...init, + headers: { ...(init?.headers ?? {}), 'X-Pegma-CSRF': actor.csrfToken }, + signal: controller.signal, + }); + current(generation); + if (!object(result) || !Object.prototype.hasOwnProperty.call(result, 'result') || + result.csrfToken !== actor.csrfToken) throw invalid(); + return result.result; + } finally { controllers.delete(controller); } + } + function base() { + return `/api/support/admin/tickets/${encodeURIComponent(context.ticketId)}/learning`; + } + function failure(error, generation) { + if (generation !== epoch || error?.stale) return; + stopPolling(); + hidePrivate(); + session = null; + if (error?.status === 429) retryAt = Math.max(retryAt, + Number.isSafeInteger(error.retryAt) ? error.retryAt : now() + 30_000); + notice(error?.status === 401 + ? 'Current account could not be confirmed. Sign in to the original account in another tab and reload this ticket.' + : error?.status === 403 + ? 'Current access could not be confirmed. Reload to check access again.' + : pending + ? 'The action may have completed. Reload, then explicitly retry the previous exact action.' + : 'Learning data could not be confirmed. Reload before another action.', true); + if ([401, 403].includes(error?.status)) { + try { options.onAccessLost?.({ status: error.status, hasPending: pending !== null }); } catch { /* Host reporting cannot settle a command. */ } + } + } + async function operation(run) { + if (busy || context === null) return; + busy = true; + const generation = epoch; + controls(); + try { await run(generation); } + catch (error) { failure(error, generation); } + finally { if (generation === epoch) { busy = false; controls(); } } + } + function checkedIntent(value) { + const exact = (input, keys) => object(input) && Object.keys(input).length === keys.length && + keys.every((key) => Object.prototype.hasOwnProperty.call(input, key)); + if (!exact(value, ['reviewerId', 'ticketId', 'sourceGeneration', 'expectedWorkGeneration', 'target', 'policy']) || + value.reviewerId !== context.actorSubject || value.ticketId !== context.ticketId || + !exact(value.target, ['articleId', 'collectionId', 'articleRevision', 'contentHash', + 'sourceSnapshotGeneration', 'sourceSnapshotHash', 'orderedReferencesHash']) || + !exact(value.policy, ['version', 'binding', 'verifiedAt', 'validUntil'])) throw invalid(); + positive(value.sourceGeneration); positive(value.expectedWorkGeneration); + positive(value.target.articleRevision); sourceCounter(value.target.sourceSnapshotGeneration); + for (const key of ['articleId', 'collectionId']) scalar(value.target[key]); + for (const key of ['contentHash', 'sourceSnapshotHash', 'orderedReferencesHash']) + if (typeof value.target[key] !== 'string' || !/^[0-9a-f]{64}$/u.test(value.target[key])) throw invalid(); + scalar(value.policy.version); scalar(value.policy.binding); + for (const key of ['verifiedAt', 'validUntil']) { + const stamp = scalar(value.policy[key], 40); const parsed = Date.parse(stamp); + if (!Number.isFinite(parsed) || new Date(parsed).toISOString() !== stamp) throw invalid(); + } + return Object.freeze({ reviewerId: value.reviewerId, ticketId: value.ticketId, + sourceGeneration: value.sourceGeneration, expectedWorkGeneration: value.expectedWorkGeneration, + target: Object.freeze({ ...value.target }), policy: Object.freeze({ ...value.policy }) }); + } + function validateSource(value) { + if (!object(value) || value.ticketId !== context.ticketId || + !['unverified', 'eligible', 'held', 'withdrawn'].includes(value.state) || + typeof value.reconciliationPending !== 'boolean') throw invalid(); + sourceCounter(value.sourceGeneration); + positive(value.resolutionCycle); + if (value.heldReason !== undefined) scalar(value.heldReason); + return Object.freeze({ sourceGeneration: value.sourceGeneration, + resolutionCycle: value.resolutionCycle, state: value.state, + reconciliationPending: value.reconciliationPending, + heldReason: value.heldReason }); + } + async function refresh() { + return operation(async (generation) => { + hidePrivate(); + notice('Reading current learning source…'); + const actor = await viewer(generation); + let result = null; + try { result = await call(base(), { method: 'GET' }, generation, actor); } + catch (error) { + // A 404 does not settle an earlier write or establish a role. Explicit + // enrollment still receives all current server checks. + if (error?.status !== 404) throw error; + } + const next = result === null ? null : validateSource(result); + await viewer(generation, actor); + current(generation); + session = actor; + source = next; + ready = true; + sourceText.textContent = next === null ? 'No learning source was returned.' + : `Source ${next.sourceGeneration} · resolution cycle ${next.resolutionCycle} · ${next.state}${next.heldReason ? ' · ' + next.heldReason : ''}${next.reconciliationPending ? ' · reconciliation pending' : ''}`; + privatePanel.hidden = false; + notice(pending ? 'An earlier action is unresolved. Reads do not acknowledge it; retry the same action explicitly.' : 'Current source read. Each action is checked again by the server.'); + }); + } + async function read(kind) { + if (!ready || !canReadWork() || (kind === 'proposal' && work?.hasProposal !== true)) return; + const selected = source.sourceGeneration; + const previous = { source, work, sourceText: sourceText.textContent, workText: workText.textContent, session }; + return operation(async (generation) => { + hidePrivate(); + const actor = await viewer(generation, previous.session); + const result = await call(`${base()}/${kind}?sourceGeneration=${selected}`, { method: 'GET' }, generation, actor); + if (!object(result) || result.ticketId !== context.ticketId || + (kind === 'work' && result.sourceGeneration !== selected)) throw invalid(); + let next; + if (kind === 'work') { + positive(result.workGeneration); + scalar(result.status); scalar(result.stage); + if (typeof result.hasProposal !== 'boolean') throw invalid(); + next = Object.freeze({ workGeneration: result.workGeneration, + status: result.status, stage: result.stage, hasProposal: result.hasProposal }); + } else { + const intent = checkedIntent(result.intent); + if (intent.sourceGeneration !== selected || + !object(result.draft?.revision) || typeof result.draft.revision.title !== 'string' || + !object(result.draft.revision.content) || typeof result.draft.revision.content.text !== 'string' || + result.draft.revision.articleId !== intent.target.articleId) throw invalid(); + next = Object.freeze({ intent }); + } + await viewer(generation, actor); + current(generation); + source = previous.source; + work = previous.work; + sourceText.textContent = previous.sourceText; + workText.textContent = previous.workText; + session = actor; + ready = true; + privatePanel.hidden = false; + if (kind === 'work') { + work = next; + workText.textContent = `Work ${next.workGeneration} · ${next.status} · ${next.stage}${next.hasProposal ? ' · private proposal available' : ''}`; + } else { + // The actual checked revision is inert text. Echo its immutable intent + // as a binding; the server/SDK recheck authority and new-write proof. + proposalText.textContent = JSON.stringify(result.draft.revision, null, 2); + shownBinding = next; + } + notice(kind === 'work' ? 'Current learning work read.' : 'Checked private KB proposal shown. Choose approve or reject explicitly.'); + }); + } + function packet(action) { + if (!ready || session === null || context === null) throw new Error('not_ready'); + let path = action; + let value; + if (action === 'enroll') value = { expectedRevision: context.revision }; + else if (action === 'evidence') { + if (!canRecordEvidence()) throw new Error('not_ready'); + value = { expectedRevision: context.revision, resolutionCycle: source.resolutionCycle, + solutionMessageId: scalar(solution.input.value), verificationReference: scalar(verification.input.value) }; + } else if (action === 'approve' || action === 'reject') { + if (shownBinding === null || !canReadWork()) throw new Error('not_ready'); + try { path = options.stagedReviewsEnabled?.() === true ? 'review-queue' : 'review'; } + catch { path = 'review'; } + value = { intent: shownBinding.intent, decision: action, + ...(reviewReason.input.value === '' ? {} : { reason: scalar(reviewReason.input.value) }) }; + } else if (action === 'withdraw' || action === 'invalidate') { + const reason = action === 'withdraw' ? withdrawReason.input.value : invalidateReason.input.value; + if (!(action === 'withdraw' ? withdrawalReasons : invalidationReasons).includes(reason)) throw new Error('invalid_input'); + value = { reason }; + } else throw new Error('invalid_input'); + // Never normalize a command identifier or reconstruct a sent JSON packet. + const id = scalar(commandId()); + const body = JSON.stringify({ commandId: id, ...value }); + return Object.freeze({ subject: context.actorSubject, ticketId: context.ticketId, + path: `${base()}/${path}`, body, commandId: id, + review: path === 'review' || path === 'review-queue', queued: path === 'review-queue', + intake: action === 'enroll' || action === 'evidence' ? action : null, + expectedRevision: action === 'enroll' || action === 'evidence' ? value.expectedRevision : undefined, + reviewGeneration: path === 'review' || path === 'review-queue' ? shownBinding.intent.sourceGeneration : undefined }); + } + function pendingChanged() { + try { options.onPendingChange?.(pending !== null); } catch { /* The packet remains owned here. */ } + } + async function send(candidate, generation, action = 'submit') { + if (now() < retryAt) { + notice('The server requested a retry delay. Wait before retrying the same action.', true); + return; + } + const expected = session; + stopPolling(); + hidePrivate(); + controls(); + const actor = await viewer(generation, expected); + if (candidate.subject !== actor.subject || candidate.ticketId !== context.ticketId) + throw Object.assign(new Error('session_changed'), { status: 401 }); + current(generation); + if (pending === null) { pending = candidate; pendingAction = 'submit'; pendingChanged(); } + else if (pending !== candidate) throw new Error('pending_action'); + hidePrivate(); + controls(); + if (candidate.review && action === 'cancel') pendingAction = 'cancel'; + if (candidate.review && action === 'submit' && pendingAction === 'cancel') action = 'cancel'; + const path = candidate.review && action !== 'submit' + ? candidate.path + (action === 'receipt' ? (candidate.queued ? '-status' : '-receipt') : '-cancel') + : candidate.intake && action === 'recover' ? candidate.path + '-recovery' : candidate.path; + let result = await call(path, { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: candidate.body }, generation, actor); + let cancelled = false; + let superseded = false; + if (candidate.intake && action === 'recover') { + if (!object(result) || result.ticketId !== candidate.ticketId || result.commandId !== candidate.commandId || + result.operation !== candidate.intake) throw invalid(); + const scoped = ['outcome', 'ticketId', 'commandId', 'operation']; + const keys = result.outcome === 'accepted' ? [...scoped, 'result'] + : result.outcome === 'superseded' ? [...scoped, 'expectedRevision', 'observedRevision', ...(Object.hasOwn(result, 'fence') ? ['fence'] : [])] : scoped; + if (Object.keys(result).sort().join(',') !== keys.sort().join(',')) throw invalid(); + if (result.outcome === 'pending') { + await viewer(generation, actor); current(generation); + notice('Keep this unresolved action and retry its exact packet. If the ticket needs a reply or status change, use another staff tab, then retry here after the revision advances.', true); + return; + } + if (result.outcome === 'superseded') { + if (result.expectedRevision !== candidate.expectedRevision || !Number.isSafeInteger(result.observedRevision)) throw invalid(); + if (Object.hasOwn(result, 'fence')) { + if (candidate.intake !== 'evidence' || result.observedRevision !== candidate.expectedRevision || + !['resolution_unavailable', 'solution_unavailable', 'resolution_cycle_changed'].includes(result.fence)) throw invalid(); + } else if (result.observedRevision <= candidate.expectedRevision) throw invalid(); + superseded = true; + } else if (result.outcome === 'accepted') result = result.result; + else throw invalid(); + } + if (candidate.review) { + if (candidate.queued && object(result) && result.outcome === 'pending') { + if (result.ticketId !== candidate.ticketId || result.commandId !== candidate.commandId || + !['proof', 'commit'].includes(result.phase) || typeof result.claimed !== 'boolean' || + typeof result.held !== 'boolean' || typeof result.expiresAt !== 'string' || + !Number.isFinite(Date.parse(result.expiresAt)) || new Date(result.expiresAt).toISOString() !== result.expiresAt) + throw invalid(); + await viewer(generation, actor); + session = actor; + notice(result.held + ? 'The recorded review intent is held. Keep the original action to check or cancel it.' + : 'The review intent is recorded and pending. This is not a completed review or KB publication.'); + pollReview(generation, candidate, result.held); + return; + } + if (action === 'receipt' && result === null) { + await viewer(generation, actor); current(generation); + notice('No exact receipt was observed. The review may still complete; keep its original packet.', true); + return; + } + if (!object(result)) throw invalid(); + if (result.outcome === 'cancelled') { + if (result.ticketId !== candidate.ticketId || result.commandId !== candidate.commandId) throw invalid(); + cancelled = true; + } else if (result.outcome === 'accepted') { + const accepted = result.result; + if (!object(accepted) || accepted.ticketId !== candidate.ticketId || + accepted.sourceGeneration !== candidate.reviewGeneration || + !['unverified', 'eligible', 'held', 'withdrawn'].includes(accepted.state)) throw invalid(); + positive(accepted.sourceGeneration); positive(accepted.resolutionCycle); + } else throw invalid(); + } else if (!superseded) { + if (!object(result) || result.ticketId !== candidate.ticketId || + !['unverified', 'eligible', 'held', 'withdrawn'].includes(result.state)) throw invalid(); + sourceCounter(result.sourceGeneration); positive(result.resolutionCycle); + } + await viewer(generation, actor); + current(generation); + if (pending !== candidate) throw invalid(); + pending = null; pendingAction = 'submit'; + polls = 0; + stopPolling(); + pendingChanged(); + notice(superseded ? 'The original action is fenced from future application. Its earlier outcome remains unknown. Read current state before another action.' + : cancelled ? 'Review cancellation acknowledged. Read current state before another action.' + : 'Action acknowledged. Read the source again before another action.'); + } + async function mutate(action) { + if (pending !== null || busy || !ready) return; + let candidate; + try { candidate = packet(action); } + catch { notice('Complete the required bounded fields before submitting.', true); return; } + return operation((generation) => send(candidate, generation)); + } + async function retry() { + if (pending === null || (pending.review !== true && !ready) || busy) return; + return operation((generation) => send(pending, generation, pending.intake ? 'recover' : 'submit')); + } + async function recoverReview(action) { + if (pending?.review !== true || context === null || busy) return; + return operation((generation) => send(pending, generation, action)); + } + function suspend() { + ++epoch; + stopPolling(); + cancelReads(); + context = null; + session = null; + busy = false; + hidePrivate(); + notice(pending ? 'An earlier action is awaiting confirmation under its original account and ticket.' : 'Learning view cleared.'); + controls(); + } + async function showTicket(value, mode = {}) { + suspend(); + try { + const ticketId = scalar(value?.ticketId); + if (!/^[A-Za-z0-9._~-]{1,200}$/u.test(ticketId)) throw new Error('invalid_input'); + context = Object.freeze({ ticketId, revision: positive(value.revision), + actorSubject: scalar(value.actorSubject), + resolved: ['resolved', 'closed'].includes(value.status) && + typeof value.resolvedAt === 'string' && Number.isFinite(Date.parse(value.resolvedAt)) }); + } catch { notice('A current staff ticket is required.', true); controls(); return; } + if (mode.recoveryOnly === true && pending?.review === true) { + notice('The original review is retained. Check its exact receipt or explicitly cancel it.'); + controls(); return; + } + return refresh(); + } + return Object.freeze({ showTicket, refresh, suspend, + hasPending: () => pending !== null, hasPendingReview: () => pending?.review === true }); + } + globalThis.PegmaSupportLearning = Object.freeze({ createPanel }); +})(); diff --git a/public/staff-support-ticket.js b/public/staff-support-ticket.js index 3bec334..8c230bb 100644 --- a/public/staff-support-ticket.js +++ b/public/staff-support-ticket.js @@ -19,7 +19,10 @@ const handlingNode = select('#staff-ticket-handling'); const handoffPanel = select('#staff-handoff'); const handoffStatus = select('#staff-handoff-status'); const handoffList = select('#staff-handoff-list'); +const learningRoot = select('#staff-learning-panel'); const ticketId = new URL(window.location.href).searchParams.get('id') ?? ''; +let learning = null; +let learningRequests = 0; let csrfToken = ''; let viewer = null; let authorityReloadRequired = false; @@ -60,6 +63,10 @@ function cancelRequests() { requests.clear(); } function beginOperation() { + // Retain unknown intent, but retire every old panel context before an + // ordinary mutation or current-ticket reload can await anything. + learning?.suspend(); + if (learningRoot !== null) learningRoot.hidden = true; suspended = false; const operation = { generation: ++readGeneration }; cancelRequests(); @@ -79,6 +86,8 @@ function clearHandoff() { handoffPanel.hidden = true; } function hideAll() { + learning?.suspend(); + if (learningRoot !== null) learningRoot.hidden = true; currentView = null; signedOut.hidden = true; forbidden.hidden = true; @@ -127,14 +136,15 @@ function selectedComposeMode() { function updateControls() { composeForm.noValidate = ordinaryPacket !== null && ordinaryPacket.kind !== 'patch'; for (const link of signInLinks) { - link.node.target = ordinaryPacket === null ? link.target : '_blank'; - link.node.rel = ordinaryPacket === null ? link.rel : 'noopener noreferrer'; + link.node.target = ordinaryPacket === null && !learningPending() ? link.target : '_blank'; + link.node.rel = ordinaryPacket === null && !learningPending() ? link.rel : 'noopener noreferrer'; } const ticket = currentView?.ticket; const terminal = ticket?.status === 'resolved' || ticket?.status === 'closed'; const state = ticket === undefined ? '' : effectiveHandling(ticket).state; const seconds = retrySeconds(); const blocked = + learningOccupied() || busy !== null || viewer === null || authorityReloadRequired || @@ -306,6 +316,10 @@ function validateView(view) { view.csrfToken !== viewer?.csrfToken ) throw Object.assign(new Error('invalid_response'), { status: 502 }); + if ((view.learningReviewRecoveryEnabled !== undefined && typeof view.learningReviewRecoveryEnabled !== 'boolean') || + (view.learningEnabled !== undefined && typeof view.learningEnabled !== 'boolean') || + (view.learningStagedReviewEnabled !== undefined && typeof view.learningStagedReviewEnabled !== 'boolean')) + throw Object.assign(new Error('invalid_response'), { status: 502 }); effectiveHandling(view.ticket); return view; } @@ -401,7 +415,7 @@ function failure(error, action, generation) { } else showStatus( error.status === 401 - ? ordinaryPacket !== null + ? ordinaryPacket !== null || learningPending() ? 'Sign in to the original account in another tab, then return here and reload this ticket. The action already sent may have completed.' : 'Sign in, then reload this ticket. Any request already sent may have completed.' : error.status === 403 @@ -520,6 +534,8 @@ async function loadTicket() { showStatus('Ticket loaded.'); // Private handoff availability does not lock a fully refreshed ticket view. finishOperation(operation); + // Admission opens only after the ACK (if any) and this complete current GET. + syncLearning(view); await loadHandoff(); return { generation, @@ -593,6 +609,7 @@ async function sendOrdinaryPacket(packet, label) { } async function patchTicket(action, extra = {}) { if ( + learningOccupied() || busy !== null || retrySeconds() > 0 || suspended || @@ -624,6 +641,7 @@ async function patchTicket(action, extra = {}) { } takeoverButton.addEventListener('click', async () => { if ( + learningOccupied() || busy !== null || retrySeconds() > 0 || suspended || @@ -706,6 +724,7 @@ composeForm.addEventListener('submit', async (event) => { const mode = selectedComposeMode(); const body = composeBody.value.trim(); if ( + learningOccupied() || busy !== null || retrySeconds() > 0 || suspended || @@ -747,12 +766,91 @@ composeForm.addEventListener('submit', async (event) => { ); }); select('#staff-ticket-reload').addEventListener('click', () => { - if (!onThisTicket()) window.location.reload(); + if (!onThisTicket() && learningPending()) { + invalidate(); + showStatus('Return to the original ticket address before reloading. An earlier learning action may have completed.', true); + } else if (!onThisTicket()) window.location.reload(); else void loadTicket(); }); select('#staff-handoff-reload').addEventListener('click', () => { void loadHandoff(); }); +function learningPending() { + return learning?.hasPending() === true; +} +function learningOccupied() { + return learningRequests > 0 || learningPending(); +} +function requireLearningAdmission(reviewRecovery = false) { + if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || + ordinaryAcknowledged || suspended || authorityReloadRequired || + viewer === null || currentView === null || + (currentView.learningEnabled !== true && !(reviewRecovery && learning?.hasPendingReview?.() === true && + currentView.learningReviewRecoveryEnabled === true)) || !onThisTicket()) + throw Object.assign(new Error('learning_suspended'), { stale: true }); +} +async function learningRequest(run, reviewRecovery = false) { + requireLearningAdmission(reviewRecovery); + const generation = readGeneration; + ++learningRequests; + updateControls(); + try { + const result = await run(); + guard(generation); + requireLearningAdmission(reviewRecovery); + return result; + } finally { --learningRequests; updateControls(); } +} +function syncLearning(view) { + if (learning === null || learningRoot === null) return; + if (busy !== null || (view.learningEnabled !== true && !(learning.hasPendingReview?.() === true && + view.learningReviewRecoveryEnabled === true)) || ordinaryPacket !== null || takeoverPacket !== null) { + learning.suspend(); + learningRoot.hidden = true; + return; + } + learningRoot.hidden = false; + void learning.showTicket({ ticketId: view.ticket.id, revision: view.ticket.revision, + actorSubject: viewer.subject, status: view.ticket.status, resolvedAt: view.ticket.resolvedAt }, + { recoveryOnly: view.learningEnabled !== true }); +} +if (learningRoot !== null && typeof globalThis.PegmaSupportLearning?.createPanel === 'function') { + // One closure owns all unresolved packets for the lifetime of this staff page. + learning = globalThis.PegmaSupportLearning.createPanel({ + root: learningRoot, + stagedReviewsEnabled: () => currentView?.learningStagedReviewEnabled === true, + request: (path, init) => learningRequest(() => api(path, init), + learning.hasPendingReview?.() === true && /\/review(?:-receipt|-cancel|-queue(?:-status|-cancel)?)?$/u.test(path)), + readSession: () => learningRequest(async () => { + const generation = readGeneration; + const current = await readViewer(generation); + guard(generation); + return current; + }, learning.hasPendingReview?.() === true), + onPendingChange: () => updateControls(), + onAccessLost: ({ status }) => { + // Fence concurrent handoff/detail reads as well as the learning closure. + ++readGeneration; + cancelRequests(); + busy = null; + viewer = null; + csrfToken = ''; + authorityReloadRequired = true; + hideAll(); + signedOut.hidden = status !== 401; + forbidden.hidden = status !== 403; + showStatus(status === 401 && learningPending() + ? 'Sign in to the original account in another tab, then reload this ticket. The learning action may have completed.' + : 'Current access could not be confirmed. Reload this ticket to check access again.', true); + updateControls(); + }, + }); +} +window.addEventListener('beforeunload', (event) => { + if (!learningPending()) return; + event.preventDefault(); + event.returnValue = ''; +}); window.addEventListener('pagehide', invalidate); window.addEventListener('popstate', invalidate); window.addEventListener('pageshow', () => { diff --git a/src/pages/staff/support/ticket.astro b/src/pages/staff/support/ticket.astro index 6fc6427..c68044a 100644 --- a/src/pages/staff/support/ticket.astro +++ b/src/pages/staff/support/ticket.astro @@ -135,5 +135,8 @@ import Base from '../../../layouts/Base.astro'; + + + diff --git a/src/support-learning-integration.test.ts b/src/support-learning-integration.test.ts new file mode 100644 index 0000000..fdc8d06 --- /dev/null +++ b/src/support-learning-integration.test.ts @@ -0,0 +1,705 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createMemoryStore } from '@pegma/storage-core'; +import { createSupportDeskApplication } from '@pegma/support-desk-application'; +import { describe, expect, it } from 'vitest'; +import { createAgentPrincipalResolver } from '../worker/src/agent-authority'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from '../worker/src/identity-api'; +import { createIdentityRuntime } from '../worker/src/identity-runtime'; +import { ADMIN_ROLE, APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE } from '../worker/src/support-access'; +import { createSupportApi } from '../worker/src/support-api'; +import { createSupportRuntime } from '../worker/src/support-desk'; +import { createSupportLearningRuntime } from '../worker/src/support-learning'; +import { createSupportLearningFixture, learningTicketId } from '../worker/src/support-learning-fixtures'; +import { createSupportLearningHandlers } from '../worker/src/support-learning-handlers'; + +type Actor = 'staff' | 'support' | 'customer' | 'admin' | 'knowledge'; +const base = '/api/support/admin/tickets/' + learningTicketId; +function isLearningPath(path: string) { + const pathname = new URL(path, IDENTITY_ISSUER).pathname; + return pathname === base + '/learning' || pathname.startsWith(base + '/learning/'); +} +async function backend() { + const store = createMemoryStore(); + const learning = await createSupportLearningFixture(store); + const logger = { log() {} }; + const identityRuntime = createIdentityRuntime({ store, emailCodeSecretBase64: btoa('r'.repeat(32)), + emailFrom: 'Pegma ', emailEnabled: false }, logger); + const { identity, sessions } = identityRuntime; + const host = createSupportRuntime({ store, identity, sessions, logger, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }); + const principals = { staff: learning.actors.staff.principalId, support: 'synthetic-routing-support', + customer: learning.actors.customer.principalId, admin: 'synthetic-routing-admin', knowledge: 'synthetic-routing-knowledge' }; + const cookies = new Map(); + const csrf = new Map(); + const ids = new Map(); + for (const [index, actor] of (Object.keys(principals) as Actor[]).entries()) { + const principalId = principals[actor]; + await identity.provisionVerifiedUser({ principalId, email: actor + '@example.test' }); + const sessionId = String(index + 1).repeat(43); + const token = String.fromCharCode(97 + index).repeat(43); + await sessions.create(sessionId, { principalId, data: JSON.stringify({ version: 1, + issuer: IDENTITY_ISSUER, subject: principalId, csrfToken: token }) }); + cookies.set(actor, SESSION_COOKIE + '=' + sessionId); csrf.set(actor, token); ids.set(actor, sessionId); + const roles = actor === 'staff' ? [SUPPORT_ROLE, KNOWLEDGE_ROLE] : actor === 'support' ? [SUPPORT_ROLE] + : actor === 'admin' ? [ADMIN_ROLE] : actor === 'knowledge' ? [KNOWLEDGE_ROLE] : []; + for (const role of roles) await host.roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'routing-' + actor + '-' + role, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-routing' }, grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'routing-grant-' + actor + '-' + role }); + } + const authority = { identity, sessions, logger, roleStore: host.roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }; + const resolve = createAgentPrincipalResolver(authority); + const runtime = createSupportLearningRuntime({ application: learning.application, knowledge: learning.knowledge, + sources: learning.sources, clock: learning.clock, ports: learning.ports, + staffAccess: { resolve }, processingEnabled: () => learning.state.enabled }); + const state = { enabled: true, flagResult: true as unknown, flagThrows: false, + afterDetail: undefined as (() => Promise) | undefined, + afterHandler: undefined as (() => Promise) | undefined }; + const actualHandler = createSupportLearningHandlers({ ...authority, + enabled: () => state.enabled, runtime: () => runtime, limiter: host.replyLimiter }); + const learningHandler = async (request: Request) => { + const response = await actualHandler(request); await state.afterHandler?.(); return response; + }; + const options = { ...authority, createLimiter: host.createLimiter, replyLimiter: host.replyLimiter, + application: { ...learning.application, async readStaffTicket(...args: Parameters) { + const value = await learning.application.readStaffTicket(...args); await state.afterDetail?.(); return value; + } } }; + const configured = { learningHandler, learningEnabled: () => { + if (state.flagThrows) throw new Error('Synthetic flag unavailable'); + return state.flagResult === true; + } }; + const api = createSupportApi({ ...options, ...configured }); + function request(path = base, actor: Actor = 'staff', body?: unknown, extra: Record = {}) { + return new Request(IDENTITY_ISSUER + path, { method: body === undefined ? 'GET' : 'POST', + headers: { Cookie: cookies.get(actor)!, ...extra, ...(body === undefined ? {} : { + Origin: IDENTITY_ISSUER, 'Sec-Fetch-Site': 'same-origin', 'X-Pegma-CSRF': csrf.get(actor)!, 'Content-Type': 'application/json' }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + } + async function revoke(actor: Actor, role: string) { + const id = 'routing-' + actor + '-' + role; + const row = await host.roleStore.getRoleAssignment(id); + if (row === null) throw new Error('Missing actual audited assignment'); + await host.roleStore.revokeRoleAssignmentWithAudit({ assignmentId: id, expectedConcurrencyToken: row.concurrencyToken, + revokedBy: { kind: 'system', systemId: 'synthetic-routing' }, revokedAtEpochMs: Date.now(), auditEventId: 'routing-revoke-' + actor + '-' + role }); + } + return { learning, identityRuntime, identity, sessions, host, options, configured, api, request, state, revoke, + cookies, csrf, ids, principals, actualHandler }; +} + +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createContext, runInContext } from 'node:vm'; +import { afterEach } from 'vitest'; +import { BrowserNode, browserGate } from './test-support-browser'; + +// Reuse the current Support test's inert DOM model with the real staff template. +// Both actual public scripts and actual HTTP/auth/SDK routes run in these cases; +// this is still a synthetic browser, not deployed layout or D1/Free admission proof. +function documentFromStaffTemplate() { + const template = readFileSync(new URL('./pages/staff/support/ticket.astro', import.meta.url), 'utf8'); + const root = new BrowserNode('document'); const stack = [root]; + const voidTags = new Set(['input', 'img', 'link', 'meta', 'br', 'hr']); + for (const match of template.matchAll(/<(\/?)([a-z][a-z0-9-]*)([^>]*?)>/giu)) { + const tag = match[2]?.toLowerCase() ?? ''; + if (match[1]) { const last = stack.findLastIndex((node) => node.tagName === tag); if (last > 0) stack.splice(last); continue; } + const node = new BrowserNode(tag); const attributes = match[3] ?? ''; + for (const attr of attributes.matchAll(/([\w:-]+)(?:="([^"]*)")?/gu)) if (attr[1]) node.attributes.set(attr[1], attr[2] ?? ''); + node.hidden = node.attributes.has('hidden'); node.disabled = node.attributes.has('disabled'); + node.checked = node.attributes.has('checked'); node.value = node.attributes.get('value') ?? ''; + stack.at(-1)?.append(node); + if (!voidTags.has(tag) && !attributes.endsWith('/')) stack.push(node); + } + for (const node of root.all().filter((value) => value.tagName === 'select')) + node.value = node.all().find((value) => value.tagName === 'option')?.value ?? ''; + return Object.assign(root, { createElement: (tag: string) => new BrowserNode(tag) }); +} +const disposers = new Set<() => void>(); +afterEach(() => { for (const dispose of [...disposers]) dispose(); }); +async function eventually(check: () => boolean, snapshot?: () => Promise) { + for (let index = 0; index < 250; index++) { + if (check()) return; + // Real SDK hashing and actual storage callbacks can yield past microtasks. + await new Promise((resolve) => setTimeout(resolve, 2)); + } + let details: unknown; + if (snapshot) { + try { details = await snapshot(); } catch { details = { diagnosticUnavailable: true }; } + } + throw new Error('Actual staff learning integration did not settle.' + + (details === undefined ? '' : ' Body-free snapshot: ' + JSON.stringify(details))); +} +async function browser(f: Awaited>, legacy = false) { + const document = documentFromStaffTemplate(); + const calls: { path: string; method: string; body?: string; csrf: string | null; + status?: number; serverStatus?: number; transportError?: boolean }[] = []; + const state = { actor: 'staff' as Actor, lostAck: false, loseOrdinaryAck: false, postCommitLogout: false, + loseReviewAck: false, loseCancelAck: false, postReviewLogout: false, + pauseLearning: undefined as ReturnType> | undefined, + pauseOrdinaryAck: undefined as ReturnType> | undefined, + pauseCurrentDetail: undefined as ReturnType> | undefined, + loseMutationAck: false }; + let reloads = 0; + let activeRequests = 0; + const window = Object.assign(new EventTarget(), { location: { + href: IDENTITY_ISSUER + '/staff/support/ticket/?id=' + learningTicketId, + reload: () => { ++reloads; }, + } }); + const api = legacy ? createSupportApi(f.options) : f.api; + const timers = new Set>(); + class FormDataAdapter { + constructor(readonly form: BrowserNode) {} + get(name: string) { return this.form.all().find((node) => node.attributes.get('name') === name)?.value ?? null; } + } + const vm = createContext({ document, window, URL, URLSearchParams, Headers, Date, AbortController, + FormData: FormDataAdapter, crypto: { randomUUID: () => randomUUID().toUpperCase() }, + setTimeout: (run: () => void, duration: number) => { + const timer = setTimeout(() => { timers.delete(timer); run(); }, duration); timers.add(timer); return timer; + }, + clearTimeout: (timer: ReturnType) => { timers.delete(timer); clearTimeout(timer); }, + fetch: async (path: string, init: RequestInit = {}) => { + ++activeRequests; + let observed: (typeof calls)[number] | undefined; + try { + const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get(state.actor)!); + if (init.method === 'POST' || init.method === 'PATCH') { headers.set('Origin', IDENTITY_ISSUER); headers.set('Sec-Fetch-Site', 'same-origin'); } + observed = { path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}), csrf: headers.get('X-Pegma-CSRF') }; + calls.push(observed); + if (isLearningPath(path) && state.pauseLearning) await state.pauseLearning.promise; + const incoming = new Request(IDENTITY_ISSUER + path, { ...init, headers }); + const response = path.startsWith('/api/identity/') ? await f.identityRuntime.api(incoming) : await api(incoming); + observed.serverStatus = response.status; + const pathname = new URL(path, IDENTITY_ISSUER).pathname; + const ordinaryMutation = (init.method === 'PATCH' && pathname === base) || + (init.method === 'POST' && (pathname === base + '/messages' || pathname === base + '/take-over')); + // Defer delivery only after genuine route/SDK execution. No auth or + // persistence result is synthesized by these ordering barriers. + if (ordinaryMutation && state.pauseOrdinaryAck) await state.pauseOrdinaryAck.promise; + // The real controller omits method for GET, as fetch permits. Hold the + // normalized request method already recorded above, including default GET. + if (observed.method === 'GET' && pathname === base && state.pauseCurrentDetail) + await state.pauseCurrentDetail.promise; + if (ordinaryMutation && response.ok && state.loseMutationAck) { + state.loseMutationAck = false; + observed.status = 503; + return new Response(JSON.stringify({ error: 'synthetic_lost_ack' }), { status: 503 }); + } + if (path.endsWith('/learning/enroll') && init.method === 'POST' && response.ok) { + if (state.postCommitLogout) { + state.postCommitLogout = false; + await f.sessions.destroy(f.ids.get(state.actor)!); + // The client must also fence an ACK against the closing real session. + } + if (state.lostAck) { state.lostAck = false; observed.status = 503; return new Response(JSON.stringify({ error: 'synthetic_lost_ack' }), { status: 503 }); } + } + if (init.method === 'POST' && path.endsWith('/learning/review') && response.ok && state.postReviewLogout) { + state.postReviewLogout = false; + await f.sessions.destroy(f.ids.get(state.actor)!); + } + if (init.method === 'POST' && response.ok && + ((path.endsWith('/learning/review') && state.loseReviewAck) || + (path.endsWith('/learning/review-cancel') && state.loseCancelAck))) { + state.loseReviewAck = false; state.loseCancelAck = false; observed.status = 503; + return new Response(JSON.stringify({ error: 'synthetic_lost_review_ack' }), { status: 503 }); + } + if (path.endsWith('/messages') && init.method === 'POST' && response.ok && state.loseOrdinaryAck) { + state.loseOrdinaryAck = false; + observed.status = 503; + return new Response(JSON.stringify({ error: 'synthetic_lost_ack' }), { status: 503 }); + } + observed.status = response.status; + return response; + } catch (error) { + if (observed) observed.transportError = true; + throw error; + } finally { --activeRequests; } + }, + }); + runInContext(readFileSync(new URL('../public/staff-support-learning.js', import.meta.url), 'utf8'), vm); + runInContext(readFileSync(new URL('../public/staff-support-ticket.js', import.meta.url), 'utf8'), vm); + const node = (id: string) => { const value = document.querySelector('#' + id); if (!value) throw new Error('Missing actual staff node ' + id); return value; }; + const control = (key: string) => { const value = node('staff-learning-panel').all().find((value) => value.dataset.learningAction === key); if (!value) throw new Error('Missing learning action ' + key); return value; }; + const action = (key: string) => { control(key).fire('click'); }; + const field = (key: string) => { const value = node('staff-learning-panel').all().find((value) => value.dataset.learningField === key); if (!value) throw new Error('Missing learning field ' + key); return value; }; + const pending = () => runInContext('learningPending()', vm) as boolean; + const writes = () => calls.filter((call) => call.method !== 'GET'); + const ordinaryPending = () => runInContext('ordinaryPacket !== null || takeoverPacket !== null', vm) as boolean; + const admittedLearning = runInContext('learningRequest', vm) as (run: () => Promise) => Promise; + const actualApi = runInContext('api', vm) as (path: string, init: RequestInit) => Promise; + const probeLearningAdmission = (expectedRevision: number) => admittedLearning(() => actualApi(base + '/learning/enroll', { + method: 'POST', body: JSON.stringify({ commandId: 'QUEUED-ENROLL-MUST-STAY-BLOCKED', expectedRevision }), + })); + async function diagnose() { + // Failure-only metadata: no DOM inputs, request bodies, credentials, hashes, + // article text, candidate content, provenance or arbitrary SDK payloads. + const sdkRead = (async () => { + try { + const source = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + const sourceFlags = { exists: true, generation: source.sourceGeneration, + cycle: source.resolutionCycle, state: source.state, + held: source.heldReason !== undefined, reconciliationPending: source.reconciliationPending }; + try { + const work = await f.learning.runtime.readWork(f.learning.actors.staff, + { ticketId: learningTicketId, sourceGeneration: source.sourceGeneration }); + return { source: sourceFlags, work: { exists: true, generation: work.workGeneration, + status: work.status, stage: work.stage, hasTarget: work.target !== undefined } }; + } catch { return { source: sourceFlags, work: { exists: false, unavailable: true } }; } + } catch { return { source: { exists: false, unavailable: true }, work: { unavailable: true } }; } + })(); + let timer: ReturnType | undefined; + const diagnosticDeadline = new Promise<{ unavailable: true }>((resolve) => { + timer = setTimeout(() => resolve({ unavailable: true }), 100); + }); + let sdk: unknown; + try { sdk = await Promise.race([sdkRead, diagnosticDeadline]); } + finally { if (timer !== undefined) clearTimeout(timer); } + const panel = node('staff-learning-panel'); + const panelStatus = panel.all().find((value) => 'role' in value && value.role === 'status'); + return { + actor: state.actor, pending: pending(), activeRequests, reloads, + panelHidden: panel.hidden, detailHidden: node('staff-ticket-detail').hidden, + signedOutHidden: node('staff-ticket-signed-out').hidden, + forbiddenHidden: node('staff-ticket-forbidden').hidden, + panelStatus: panelStatus?.textContent.slice(0, 240) ?? null, + staffStatus: node('staff-ticket-status').textContent.slice(0, 240), + controller: { + authorityReloadRequired: runInContext('authorityReloadRequired', vm) as boolean, + suspended: runInContext('suspended', vm) as boolean, + generation: runInContext('readGeneration', vm) as number, + busy: runInContext('busy !== null', vm) as boolean, + learningRequests: runInContext('learningRequests', vm) as number, + viewerMatchesActor: runInContext('viewer?.subject', vm) === f.principals[state.actor], + csrfMatchesActor: runInContext('csrfToken', vm) === f.csrf.get(state.actor), + }, + buttons: Object.fromEntries(['refresh', 'enroll', 'evidence', 'work', 'proposal', + 'approve', 'reject', 'withdraw', 'invalidate', 'retry'].map((key) => { + const value = panel.all().find((value) => value.dataset.learningAction === key); + return [key, value ? { hidden: value.hidden, disabled: value.disabled } : { missing: true }]; + })), + requestCount: calls.length, + requests: calls.slice(-32).map((call) => ({ method: call.method, + path: call.path.slice(0, 300), status: call.status ?? null, + serverStatus: call.serverStatus ?? null, transportError: call.transportError === true })), + sdk, + }; + } + const wait = (check: () => boolean) => eventually(check, diagnose); + const dispose = () => { + state.pauseLearning?.resolve(); state.pauseOrdinaryAck?.resolve(); state.pauseCurrentDetail?.resolve(); + window.dispatchEvent(new Event('pagehide')); + for (const timer of timers) clearTimeout(timer); timers.clear(); disposers.delete(dispose); + }; + disposers.add(dispose); + await wait(() => node('staff-ticket-detail').hidden === false || node('staff-ticket-signed-out').hidden === false || node('staff-ticket-forbidden').hidden === false); + return { node, action, control, field, pending, ordinaryPending, probeLearningAdmission, state, calls, writes, window, document, dispose, wait, get reloads() { return reloads; }, + async idle() { await wait(() => activeRequests === 0); }, + async ready(phase: 'fresh' | 'unresolved' = 'fresh') { + const unresolved = phase === 'unresolved'; + const expected = unresolved + ? 'An earlier action is unresolved. Reads do not acknowledge it; retry the same action explicitly.' + : 'Current source read. Each action is checked again by the server.'; + await wait(() => !node('staff-learning-panel').hidden && pending() === unresolved && + node('staff-learning-panel').all().some((value) => value.textContent === expected) && + (unresolved ? !control('retry').hidden && !control('retry').disabled && control('enroll').disabled + : control('retry').hidden && !control('enroll').disabled)); + }, + async reload() { node('staff-ticket-reload').fire('click'); await wait(() => node('staff-ticket-detail').hidden === false); }, + }; +} + +describe('registered public staff ticket and learning panel with real auth/SDK routes', () => { + + it.each(['enroll', 'evidence'] as const)('reconciles a genuinely stale %s packet and restores fresh actions without rebinding its original bytes', async (operation) => { + const f = await backend(); const ticket = await f.learning.terminal(); + const page = await browser(f); await page.ready(); + if (operation === 'evidence') { + page.action('enroll'); await page.wait(() => !page.pending() && page.writes().length === 1); + await page.reload(); await page.ready(); + page.field('solution').value = 'learning-solution'; page.field('verification').value = 'SYNTHETIC_STAFF_VERIFICATION'; + } + const legacy = createSupportDeskApplication({ store: f.learning.store, clock: f.learning.clock }); + await legacy.addNote(f.learning.actors.staff, { ...f.learning.command('competing-intake-revision'), ticketId: learningTicketId, + messageId: 'competing-intake-note', body: 'An independent fictional staff edit advances the ticket revision.' }); + page.action(operation); + await page.wait(() => page.writes().some((call) => call.path.endsWith('/learning/' + operation) && call.status === 409)); + await page.idle(); expect(page.pending()).toBe(true); expect(page.node('action-reopen').disabled).toBe(true); + const original = page.writes().find((call) => call.path.endsWith('/learning/' + operation))!; + const before = await f.learning.rows(); + await page.reload(); await page.ready('unresolved'); page.action('retry'); + await page.wait(() => !page.pending()); await page.idle(); + const recovery = page.writes().find((call) => call.path.endsWith('/learning/' + operation + '-recovery'))!; + expect(recovery.body).toBe(original.body); expect(recovery.serverStatus).toBe(200); + expect(page.node('staff-learning-panel').textContent).toContain('fenced from future application'); + expect(page.node('staff-learning-panel').textContent).toContain('earlier outcome remains unknown'); + expect(page.node('action-reopen').disabled).toBe(false); expect(await f.learning.rows()).toEqual(before); + await page.reload(); await page.ready(); + if (operation === 'evidence') { + page.field('solution').value = 'learning-solution'; page.field('verification').value = 'SYNTHETIC_STAFF_VERIFICATION'; + } + page.action(operation); + await page.wait(() => !page.pending() && page.writes().some((call) => call.path.endsWith('/learning/' + operation) && call.status === 200)); + const fresh = page.writes().filter((call) => call.path.endsWith('/learning/' + operation)).at(-1)!; + expect(JSON.parse(fresh.body ?? '{}').expectedRevision).toBe(ticket.revision + 1); + expect(JSON.parse(fresh.body ?? '{}').commandId).not.toBe(JSON.parse(original.body ?? '{}').commandId); + expect(f.learning.state.modelCalls).toBe(0); + }); + + + it.each(['missing', 'internal'] as const)('reassesses a same-revision %s solution and restores the actual page without losing the original packet', async (kind) => { + const f = await backend(); const ticket = await f.learning.terminal(); + const page = await browser(f); await page.ready(); + page.action('enroll'); await page.wait(() => !page.pending() && page.writes().length === 1); + await page.reload(); await page.ready(); + page.field('solution').value = kind === 'missing' ? 'missing-visible-solution' : 'learning-note'; + page.field('verification').value = 'SYNTHETIC_STAFF_VERIFICATION'; page.action('evidence'); + await page.wait(() => page.writes().some((call) => call.path.endsWith('/learning/evidence') && call.status === 409)); + await page.idle(); expect(page.pending()).toBe(true); expect(page.node('action-reopen').disabled).toBe(true); + const original = page.writes().find((call) => call.path.endsWith('/learning/evidence'))!; + const before = await f.learning.rows(); + await page.reload(); await page.ready('unresolved'); page.action('retry'); + await page.wait(() => !page.pending()); await page.idle(); + const recovery = page.writes().find((call) => call.path.endsWith('/learning/evidence-recovery'))!; + expect(recovery.body).toBe(original.body); expect(recovery.serverStatus).toBe(200); + expect(page.node('staff-learning-panel').textContent).toContain('fenced from future application'); + expect(page.node('staff-learning-panel').textContent).toContain('earlier outcome remains unknown'); + expect(page.node('action-reopen').disabled).toBe(false); expect(await f.learning.rows()).toEqual(before); + await page.reload(); await page.ready(); page.field('solution').value = 'learning-solution'; + page.field('verification').value = 'SYNTHETIC_STAFF_VERIFICATION'; page.action('evidence'); + await page.wait(() => !page.pending() && page.writes().some((call) => call.path.endsWith('/learning/evidence') && call.status === 200)); + const fresh = page.writes().filter((call) => call.path.endsWith('/learning/evidence')).at(-1)!; + expect(JSON.parse(fresh.body ?? '{}').expectedRevision).toBe(ticket.revision); + expect(JSON.parse(fresh.body ?? '{}').commandId).not.toBe(JSON.parse(original.body ?? '{}').commandId); + expect((await f.learning.rows()).filter((row) => row.kind === 'resolution_learning_work')).toHaveLength(1); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('retains a genuinely accepted review when its original session is destroyed before the client closing fence', async () => { + const f = await backend(); await f.learning.enrollAndVerify(); await f.learning.delivered(); + const page = await browser(f); await page.ready(); + page.action('work'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Current learning work read.')); + page.action('proposal'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Checked private KB proposal shown.')); + page.state.postReviewLogout = true; page.action('approve'); + await page.wait(() => page.node('staff-ticket-signed-out').hidden === false); await page.idle(); + expect(page.pending()).toBe(true); + expect(page.node('staff-learning-panel').hidden).toBe(true); + expect(page.node('staff-learning-panel').textContent).not.toContain('Download and verify'); + expect(page.writes().find((call) => call.path.endsWith('/learning/review'))?.serverStatus).toBe(200); + expect((await f.learning.rows()).filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(1); + }); + it('recovers a lost real review ACK through the actual controller after reopen and actual Knowledge revocation', async () => { + const f = await backend(); await f.learning.enrollAndVerify(); await f.learning.delivered(); + const page = await browser(f); await page.ready(); + page.action('work'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Current learning work read.')); + page.action('proposal'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Checked private KB proposal shown.')); + page.state.loseReviewAck = true; page.action('approve'); + await page.wait(() => page.writes().some((call) => call.path.endsWith('/learning/review') && call.status === 503)); await page.idle(); + const original = page.writes().find((call) => call.path.endsWith('/learning/review'))!; + await f.learning.application.reopenTicket(f.learning.actors.staff, + { ...f.learning.command('controller-after-review-reopen'), ticketId: learningTicketId }); + await f.revoke('staff', KNOWLEDGE_ROLE); + const before = await f.learning.rows(); const start = page.calls.length; + page.action('check-review'); await page.wait(() => !page.pending()); await page.idle(); + const recovery = page.writes().find((call) => call.path.endsWith('/learning/review-receipt'))!; + expect(recovery.body).toBe(original.body); expect(recovery.serverStatus).toBe(200); + expect(page.calls.slice(start).some((call) => /\/learning(?:\/(?:work|proposal))?(?:\?|$)/u.test(call.path))).toBe(false); + expect(await f.learning.rows()).toEqual(before); + }); + + it('keeps the actual controller pending after lost cancellation ACK and retries cancellation only', async () => { + const f = await backend(); await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const page = await browser(f); await page.ready(); + page.action('work'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Current learning work read.')); + page.action('proposal'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Checked private KB proposal shown.')); + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId }); + await f.learning.knowledge.updateDraft(f.learning.actors.staff, + { ...f.learning.command('controller-stale-target', draft.generation), articleId: delivered.articleId, + collectionId: draft.revision.collectionId, draft: { kind: draft.revision.kind, title: 'Independently updated', + summary: draft.revision.summary, content: draft.revision.content, tags: draft.revision.tags, + applicability: draft.revision.applicability } }); + page.action('approve'); + await page.wait(() => page.writes().some((call) => call.path.endsWith('/learning/review') && call.status === 503)); await page.idle(); + const original = page.writes()[0]!; + page.state.loseCancelAck = true; page.action('cancel-review'); + await page.wait(() => page.writes().some((call) => call.path.endsWith('/learning/review-cancel') && call.status === 503)); await page.idle(); + expect(page.pending()).toBe(true); const before = await f.learning.rows(); + page.action('retry'); await page.wait(() => !page.pending()); await page.idle(); + const reviews = page.writes().filter((call) => /\/learning\/review(?:-cancel)?$/u.test(call.path)); + expect(reviews.map((call) => call.path.split('/').at(-1))).toEqual(['review', 'review-cancel', 'review-cancel']); + expect(reviews.every((call) => call.body === original.body)).toBe(true); + expect(await f.learning.rows()).toEqual(before); + expect(before.filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(0); + }); + + it('mounts one persistent panel only from the current detail capability and leaves the legacy absence OFF', async () => { + const f = await backend(); await f.learning.terminal(); + const old = await browser(f, true); + expect(old.node('staff-learning-panel').hidden).toBe(true); + expect(old.calls.some((call) => isLearningPath(call.path))).toBe(false); + const current = await browser(f); await current.ready(); + expect(current.node('staff-learning-panel').hidden).toBe(false); + const heading = current.node('staff-learning-panel').children[0]; + await current.reload(); await current.ready(); + expect(current.node('staff-learning-panel').children[0]).toBe(heading); + expect(current.calls.some((call) => /roles|permissions/u.test(call.path))).toBe(false); + }); + + it('enrolls actual unverified0, accepts first staff evidence and opens only actual eligible1 work', async () => { + const f = await backend(); const ticket = await f.learning.terminal(); + const page = await browser(f); await page.ready(); + page.action('enroll'); + await page.wait(() => !page.pending() && page.writes().length === 1 && + page.node('staff-learning-panel').textContent.includes('Action acknowledged.')); + const initial = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(initial).toMatchObject({ state: 'unverified', sourceGeneration: 0, resolutionCycle: 1 }); + await page.reload(); await page.ready(); + expect(page.control('evidence').disabled).toBe(false); + expect(page.control('work').disabled).toBe(true); + expect(page.control('proposal').disabled).toBe(true); + page.action('work'); page.action('proposal'); + expect(page.calls.some((call) => /\/learning\/(work|proposal)\?/u.test(call.path))).toBe(false); + page.field('solution').value = 'learning-solution'; + page.field('verification').value = 'SYNTHETIC_STAFF_VERIFICATION'; + page.action('evidence'); + await page.wait(() => !page.pending() && page.writes().length === 2 && + page.node('staff-learning-panel').textContent.includes('Action acknowledged.')); + const packet = JSON.parse(page.writes()[1]?.body ?? '{}'); + expect(packet).toMatchObject({ expectedRevision: ticket.revision, resolutionCycle: 1, + solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' }); + expect(packet).not.toHaveProperty('sourceGeneration'); + const eligible = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(eligible).toMatchObject({ state: 'eligible', sourceGeneration: 1, resolutionCycle: 1 }); + expect(f.learning.state.modelCalls).toBe(0); + await page.reload(); await page.ready(); + expect(page.control('work').disabled).toBe(false); + expect(page.control('proposal').disabled).toBe(true); + page.action('work'); + await page.wait(() => page.node('staff-learning-panel').textContent.includes('Current learning work read.')); + expect(page.calls.some((call) => call.path === base + '/learning/work?sourceGeneration=1')).toBe(true); + expect(page.calls.some((call) => /sourceGeneration=0(?:&|$)/u.test(call.path))).toBe(false); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('acknowledges actual held0 evidence without inventing eligibility or work', async () => { + const f = await backend(); await f.learning.terminal(); + const page = await browser(f); await page.ready(); + page.action('enroll'); await page.wait(() => !page.pending() && page.writes().length === 1 && + page.node('staff-learning-panel').textContent.includes('Action acknowledged.')); + await page.reload(); await page.ready(); + f.learning.state.product = 'missing'; + page.field('solution').value = 'learning-solution'; + page.field('verification').value = 'SYNTHETIC_STAFF_VERIFICATION'; + page.action('evidence'); await page.wait(() => !page.pending() && page.writes().length === 2 && + page.node('staff-learning-panel').textContent.includes('Action acknowledged.')); + const held = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(held).toMatchObject({ state: 'held', sourceGeneration: 0, resolutionCycle: 1, + heldReason: 'product_context_unavailable' }); + await page.reload(); await page.ready(); + expect(page.control('evidence').disabled).toBe(false); + expect(page.control('work').disabled).toBe(true); + expect(page.control('proposal').disabled).toBe(true); + expect(page.calls.some((call) => /\/learning\/(work|proposal)\?/u.test(call.path))).toBe(false); + expect(f.learning.state.modelCalls).toBe(0); + }); + it('uses real current session/CSRF to enroll and records one SDK effect after lost ACK and exact uppercase retry', async () => { + const f = await backend(); await f.learning.terminal(); + const page = await browser(f); await page.ready(); + page.state.lostAck = true; page.action('enroll'); + await page.wait(() => page.pending() && page.node('staff-learning-panel').textContent.includes('may have completed')); + const first = page.writes().find((call) => call.path.endsWith('/learning/enroll'))!; + const command = JSON.parse(first.body ?? '{}').commandId as string; + expect(command).toBe(command.toUpperCase()); + expect(first.csrf).toBe(f.csrf.get('staff')); + const source = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(source.state).toBe('unverified'); + const rows = JSON.stringify(await f.learning.rows()); + const unload = new Event('beforeunload', { cancelable: true }); page.window.dispatchEvent(unload); + expect(unload.defaultPrevented).toBe(true); + await page.reload(); await page.ready('unresolved'); + expect(page.pending()).toBe(true); + expect(page.node('compose-submit').disabled).toBe(true); + expect(page.node('action-take-over').disabled).toBe(true); + page.action('retry'); await page.wait(() => !page.pending()); + const retries = page.writes().filter((call) => /\/learning\/enroll(?:-recovery)?$/u.test(call.path)); + expect(retries).toHaveLength(2); expect(retries[1]?.body).toBe(first.body); + expect(JSON.stringify(await f.learning.rows())).toBe(rows); + expect(page.reloads).toBe(0); + }); + + it('retains an unknown packet through actual logout and account A to B to A without automatic unload', async () => { + const f = await backend(); await f.learning.terminal(); + const page = await browser(f); await page.ready(); + page.state.postCommitLogout = true; page.action('enroll'); + await page.wait(() => page.node('staff-ticket-signed-out').hidden === false); + expect(page.pending()).toBe(true); expect(page.reloads).toBe(0); + const signIn = page.node('staff-ticket-signed-out').querySelector('a') as BrowserNode & { target?: string }; + expect(signIn.target).toBe('_blank'); + const first = page.writes()[0]!; + page.state.actor = 'support'; page.node('staff-ticket-reload').fire('click'); + await page.wait(() => page.node('staff-ticket-signed-out').hidden === false && page.calls.some((call) => call.path === base)); + expect(page.pending()).toBe(true); + expect(page.writes()).toHaveLength(1); + expect(page.node('staff-learning-panel').hidden).toBe(true); + const newId = 'Z'.repeat(43); const newCsrf = 'z'.repeat(43); + await f.sessions.create(newId, { principalId: f.principals.staff, data: JSON.stringify({ version: 1, + issuer: IDENTITY_ISSUER, subject: f.principals.staff, csrfToken: newCsrf }) }); + f.cookies.set('staff', SESSION_COOKIE + '=' + newId); f.csrf.set('staff', newCsrf); + page.state.actor = 'staff'; page.node('staff-ticket-reload').fire('click'); await page.ready('unresolved'); + page.action('retry'); await page.wait(() => !page.pending()); + expect(page.writes()[1]?.body).toBe(first.body); expect(page.writes()[1]?.csrf).toBe(newCsrf); + expect(page.reloads).toBe(0); + }); + + it('reviews the actual separately checked draft using only its shown binding and never publishes it', async () => { + const f = await backend(); await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const page = await browser(f); await page.ready(); + page.action('work'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Current learning work read.')); + expect(page.calls.some((call) => call.path.includes('/proposal?'))).toBe(false); + page.action('proposal'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Checked private KB proposal shown.')); + page.action('approve'); await page.wait(() => !page.pending() && page.writes().length === 1); + const packet = JSON.parse(page.writes()[0]?.body ?? '{}'); + expect(Object.keys(packet).sort()).toEqual(['commandId', 'decision', 'intent']); + expect(packet.intent.reviewerId).toBe(f.principals.staff); + expect(packet.intent.target.contentHash).toMatch(/^[0-9a-f]{64}$/u); + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId }); + expect(draft.state).toBe('draft'); + }); + + it('keeps source/work available to stored Support while an actual separate Knowledge denial hides all private DOM', async () => { + const f = await backend(); await f.learning.enrollAndVerify(); await f.learning.delivered(); + const page = await browser(f); await page.ready(); + page.state.actor = 'support'; page.node('staff-ticket-reload').fire('click'); await page.ready(); + page.action('work'); await page.wait(() => page.node('staff-learning-panel').textContent.includes('Current learning work read.')); + page.action('proposal'); await page.wait(() => page.node('staff-ticket-forbidden').hidden === false); + expect(page.node('staff-learning-panel').hidden).toBe(true); + expect(page.node('staff-learning-panel').textContent).not.toContain('Download and verify'); + expect(page.writes()).toEqual([]); + }); + + it('preserves the existing unknown ordinary staff reply packet with the optional panel enabled', async () => { + const f = await backend(); await f.learning.terminal(); + const page = await browser(f); await page.ready(); await page.idle(); + for (const input of page.node('staff-compose-form').all()) + if (input.attributes.get('name') === 'composeMode') input.checked = input.value === 'public'; + page.node('compose-body').value = 'A fictional public staff follow-up.'; + page.node('staff-compose-form').fire('change'); + page.state.loseOrdinaryAck = true; page.node('staff-compose-form').fire('submit'); + await page.wait(() => page.node('staff-ticket-detail').hidden && page.writes().length === 1); + const first = page.writes()[0]!; + expect(first.path).toBe(base + '/messages'); + await page.reload(); await page.idle(); + expect(page.node('staff-learning-panel').hidden).toBe(true); + expect(page.node('compose-submit').disabled).toBe(false); + const rows = JSON.stringify(await f.learning.rows()); + page.node('staff-compose-form').fire('submit'); + await page.wait(() => page.node('staff-ticket-status').textContent.includes('Public reply sent.')); + const repeated = page.writes().filter((call) => call.path.endsWith('/messages')); + expect(repeated).toHaveLength(2); expect(repeated[1]?.body).toBe(first.body); + expect(JSON.stringify(await f.learning.rows())).toBe(rows); + }); + it.each(['patch', 'reply', 'take-over'] as const)( + 'suspends learning during an actual %s and admits it only after the ACK and complete current GET', async (kind) => { + const f = await backend(); await f.learning.terminal(); + if (kind === 'take-over') await f.learning.application.reopenTicket(f.learning.actors.staff, + { ...f.learning.command('open-deferred-takeover'), ticketId: learningTicketId }); + const before = await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId); + const page = await browser(f); await page.ready(); await page.idle(); + const staleEnroll = page.control('enroll'); + const ack = browserGate(); page.state.pauseOrdinaryAck = ack; + if (kind === 'patch') page.node('action-assign').fire('click'); + else if (kind === 'take-over') page.node('action-take-over').fire('click'); + else { + for (const input of page.node('staff-compose-form').all()) + if (input.attributes.get('name') === 'composeMode') input.checked = input.value === 'public'; + page.node('compose-body').value = 'A fictional deferred ordinary reply.'; + page.node('staff-compose-form').fire('change'); page.node('staff-compose-form').fire('submit'); + } + await page.wait(() => page.writes().length === 1 && page.writes()[0]?.serverStatus === (kind === 'reply' ? 201 : 200)); + expect(page.node('staff-learning-panel').hidden).toBe(true); + expect(staleEnroll.disabled).toBe(true); + staleEnroll.fire('click'); + await expect(page.probeLearningAdmission(before.ticket.revision)).rejects.toMatchObject({ stale: true }); + expect(page.writes().filter((call) => isLearningPath(call.path))).toEqual([]); + expect(page.pending()).toBe(false); + const current = browserGate(); page.state.pauseCurrentDetail = current; + page.state.pauseOrdinaryAck = undefined; ack.resolve(); + await page.wait(() => page.calls.some((call) => call.path === base && call.method === 'GET' && + call.serverStatus === 200 && call.status === undefined)); + expect(page.node('staff-learning-panel').hidden).toBe(true); + staleEnroll.fire('click'); + await expect(page.probeLearningAdmission(before.ticket.revision)).rejects.toMatchObject({ stale: true }); + expect(page.writes().filter((call) => isLearningPath(call.path))).toEqual([]); + page.state.pauseCurrentDetail = undefined; current.resolve(); + await page.ready(); await page.idle(); + expect(page.ordinaryPending()).toBe(false); + const after = await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId); + expect(after.ticket.revision).toBeGreaterThan(before.ticket.revision); + page.action('enroll'); + await page.wait(() => !page.pending() && page.writes().filter((call) => isLearningPath(call.path)).length === 1 && + page.node('staff-learning-panel').textContent.includes('Action acknowledged.')); + const enrollment = page.writes().find((call) => isLearningPath(call.path))!; + expect(enrollment.path).toBe(base + '/learning/enroll'); + expect(JSON.parse(enrollment.body ?? '{}').expectedRevision).toBe(after.ticket.revision); + expect(f.learning.state.modelCalls).toBe(0); + }, + ); + + it.each(['patch', 'reply', 'take-over'] as const)( + 'keeps learning blocked through an unknown actual %s ACK and a current GET until exact ordinary recovery', async (kind) => { + const f = await backend(); await f.learning.terminal(); + if (kind === 'take-over') await f.learning.application.reopenTicket(f.learning.actors.staff, + { ...f.learning.command('open-unknown-takeover'), ticketId: learningTicketId }); + const before = await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId); + const page = await browser(f); await page.ready(); await page.idle(); + page.state.loseMutationAck = true; + if (kind === 'patch') page.node('action-assign').fire('click'); + else if (kind === 'take-over') page.node('action-take-over').fire('click'); + else { + for (const input of page.node('staff-compose-form').all()) + if (input.attributes.get('name') === 'composeMode') input.checked = input.value === 'public'; + page.node('compose-body').value = 'A fictional unknown ordinary reply.'; + page.node('staff-compose-form').fire('change'); page.node('staff-compose-form').fire('submit'); + } + await page.wait(() => page.node('staff-ticket-detail').hidden && page.ordinaryPending() && page.writes().length === 1); + const original = page.writes()[0]!; + expect(original.serverStatus).toBe(kind === 'reply' ? 201 : 200); + expect(original.status).toBe(503); + await page.reload(); await page.idle(); + expect(page.ordinaryPending()).toBe(true); + expect(page.node('staff-learning-panel').hidden).toBe(true); + expect(page.control('enroll').disabled).toBe(true); + page.action('enroll'); + await expect(page.probeLearningAdmission(before.ticket.revision)).rejects.toMatchObject({ stale: true }); + expect(page.writes()).toHaveLength(1); + expect(page.pending()).toBe(false); + const rows = JSON.stringify(await f.learning.rows()); + if (kind === 'patch') page.node('action-assign').fire('click'); + else if (kind === 'take-over') page.node('action-take-over').fire('click'); + else page.node('staff-compose-form').fire('submit'); + await page.ready(); await page.idle(); + expect(page.ordinaryPending()).toBe(false); + const repeated = page.writes().filter((call) => !isLearningPath(call.path)); + expect(repeated).toHaveLength(2); + expect(repeated[1]?.path).toBe(original.path); + expect(repeated[1]?.method).toBe(original.method); + expect(repeated[1]?.body).toBe(original.body); + expect(JSON.stringify(await f.learning.rows())).toBe(rows); + expect(page.writes().filter((call) => isLearningPath(call.path))).toEqual([]); + expect(f.learning.state.modelCalls).toBe(0); + }, + ); + it('does not let ordinary controls race an awaited learning request and clears the panel on page suspension', async () => { + const f = await backend(); await f.learning.terminal(); + const page = await browser(f); await page.ready(); + page.state.pauseLearning = browserGate(); + page.action('enroll'); + await page.wait(() => page.writes().length === 1); + expect(page.node('action-assign').disabled).toBe(true); + page.node('action-assign').fire('click'); + expect(page.writes()).toHaveLength(1); + page.window.dispatchEvent(new Event('pagehide')); + expect(page.node('staff-learning-panel').hidden).toBe(true); + expect(page.node('staff-learning-panel').textContent).not.toContain('Source '); + page.state.pauseLearning.resolve(); + await page.idle(); + }); +}); diff --git a/src/support-learning-staged-review.test.ts b/src/support-learning-staged-review.test.ts new file mode 100644 index 0000000..8aa2c59 --- /dev/null +++ b/src/support-learning-staged-review.test.ts @@ -0,0 +1,131 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it } from 'vitest'; +import { BrowserNode } from './test-support-browser'; + +interface Panel { + showTicket(ticket: { ticketId: string; revision: number; actorSubject: string; status: string; resolvedAt: string }): Promise; + suspend(): void; + hasPending(): boolean; +} +interface Call { readonly path: string; readonly body?: string } +const actor = 'fictional-reviewer-A'; +const ticket = { ticketId: 'fictional-ticket', revision: 3, actorSubject: actor, + status: 'resolved', resolvedAt: '2026-11-11T12:00:00.000Z' }; +async function drain() { for (let index = 0; index < 160; index++) await Promise.resolve(); } + +function fixture() { + const root = new BrowserNode('section'); + const calls: Call[] = []; + const timers = new Map void>(); + const state = { enabled: true, subject: actor, csrf: 'fictional-A-csrf', terminal: false, + held: false, failCancel: false, deny: false, nextTimer: 0 }; + const hash = 'a'.repeat(64); + const intent = { reviewerId: actor, ticketId: ticket.ticketId, sourceGeneration: 1, expectedWorkGeneration: 2, + target: { articleId: 'fictional-guide', collectionId: 'fictional-guides', articleRevision: 1, + contentHash: hash, sourceSnapshotGeneration: 1, sourceSnapshotHash: hash, orderedReferencesHash: hash }, + policy: { version: 'fictional-checks', binding: 'fictional-check-binding', + verifiedAt: '2026-11-11T12:00:00.000Z', validUntil: '2026-11-11T13:00:00.000Z' } }; + const pending = () => ({ outcome: 'pending', ticketId: ticket.ticketId, commandId: 'EXACT-UPPERCASE', + phase: 'proof', claimed: false, held: state.held, expiresAt: '2026-11-11T13:00:00.000Z' }); + const accepted = { outcome: 'accepted', result: { ticketId: ticket.ticketId, sourceGeneration: 1, + resolutionCycle: 1, state: 'eligible' } }; + const vm = { document: { createElement: (tag: string) => new BrowserNode(tag) }, AbortController, + setTimeout(run: () => void, delay: number) { + expect(delay).toBe(30_000); const id = ++state.nextTimer; timers.set(id, run); return id; + }, clearTimeout(id: number) { timers.delete(id); } }; + runInNewContext(readFileSync(new URL('../public/staff-support-learning.js', import.meta.url), 'utf8'), vm); + const factory = (vm as typeof vm & { PegmaSupportLearning: { createPanel(options: unknown): Panel } }).PegmaSupportLearning; + const panel = factory.createPanel({ root, stagedReviewsEnabled: () => state.enabled, + commandId: () => 'EXACT-UPPERCASE', readSession: async () => ({ subject: state.subject, csrfToken: state.csrf }), + request: async (path: string, init: RequestInit) => { + calls.push({ path, body: typeof init.body === 'string' ? init.body : undefined }); + if (state.deny) throw Object.assign(new Error('fictional denied'), { status: 403 }); + let result: unknown; + if (path.endsWith('/review-queue-cancel')) { + if (state.failCancel) throw Object.assign(new Error('fictional lost cancellation ACK'), { status: 503 }); + result = { outcome: 'cancelled', ticketId: ticket.ticketId, commandId: 'EXACT-UPPERCASE' }; + } else if (/\/review-queue(?:-status)?$/u.test(path)) result = state.terminal ? accepted : pending(); + else if (path.endsWith('/review')) result = accepted; + else if (path.includes('/proposal?')) result = { ticketId: ticket.ticketId, intent, + draft: { revision: { articleId: 'fictional-guide', title: 'PRIVATE_REVIEW_TITLE', content: { text: 'PRIVATE_REVIEW_BODY' } } } }; + else if (path.includes('/work?')) result = { ticketId: ticket.ticketId, sourceGeneration: 1, + workGeneration: 2, status: 'awaiting_review', stage: 'kb_delivery', hasProposal: true }; + else result = { ticketId: ticket.ticketId, sourceGeneration: 1, resolutionCycle: 1, state: 'eligible', reconciliationPending: false }; + return { result, csrfToken: state.csrf }; + } }); + function control(action: string) { + const value = root.all().find((node) => node.dataset.learningAction === action); + if (value === undefined) throw new Error('Missing actual panel control'); + return value; + } + async function click(action: string) { control(action).fire('click'); await drain(); } + async function proposal() { + await panel.showTicket(ticket); + expect(control('work').disabled, 'The actual source DTO must make work readable').toBe(false); + await click('work'); + expect(control('proposal').disabled, 'The actual work DTO must make the proposal readable').toBe(false); + await click('proposal'); + expect(control('approve').disabled, 'The checked proposal must be ready before a review intent is minted').toBe(false); + } + async function tick() { + const entry = timers.entries().next().value; + if (entry === undefined) throw new Error('Expected a bounded read-only poll'); + timers.delete(entry[0]); entry[1](); await drain(); + } + return { panel, root, calls, timers, state, click, proposal, tick, control }; +} + +describe('staged learning review in the actual public panel', () => { + it('retains a durable pending packet and polls only its exact status until terminal receipt', async () => { + const f = fixture(); await f.proposal(); await f.click('approve'); + const original = f.calls.find((call) => call.path.endsWith('/review-queue'))!; + expect(f.panel.hasPending()).toBe(true); + expect(f.root.textContent).toContain('not a completed review'); + expect(f.root.textContent).not.toContain('PRIVATE_REVIEW_BODY'); + await f.tick(); expect(f.calls.at(-1)).toEqual({ path: original.path + '-status', body: original.body }); + expect(f.panel.hasPending()).toBe(true); + f.state.terminal = true; await f.tick(); + expect(f.panel.hasPending()).toBe(false); expect(f.timers.size).toBe(0); + expect(f.calls.filter((call) => call.path === original.path)).toHaveLength(1); + }); + + it('keeps cancellation sticky after lost ACK and never resends approval', async () => { + const f = fixture(); await f.proposal(); await f.click('approve'); + const original = f.calls.at(-1)!; f.state.failCancel = true; + await f.click('cancel-review'); expect(f.panel.hasPending()).toBe(true); + expect(f.timers.size).toBe(0); + f.state.failCancel = false; await f.panel.showTicket(ticket); await f.click('retry'); + expect(f.calls.at(-1)).toEqual({ path: original.path + '-cancel', body: original.body }); + expect(f.panel.hasPending()).toBe(false); + expect(f.calls.filter((call) => call.path === original.path)).toHaveLength(1); + }); + + it('clears private state and polling on current denial while retaining exact original ownership', async () => { + const f = fixture(); await f.proposal(); await f.click('approve'); const original = f.calls.at(-1)!; + f.state.deny = true; await f.tick(); + expect(f.panel.hasPending()).toBe(true); expect(f.timers.size).toBe(0); + expect(f.root.textContent).not.toContain('PRIVATE_REVIEW_TITLE'); + const count = f.calls.length; f.state.subject = 'fictional-reviewer-B'; f.state.deny = false; + await f.panel.showTicket({ ...ticket, actorSubject: 'fictional-reviewer-B' }); await f.click('retry'); + expect(f.calls).toHaveLength(count); + f.state.subject = actor; await f.panel.showTicket(ticket); await f.click('check-review'); + expect(f.calls.at(-1)).toEqual({ path: original.path + '-status', body: original.body }); + }); + + it('bounds automatic polling and stops immediately when suspended or held', async () => { + const f = fixture(); await f.proposal(); await f.click('approve'); + for (let index = 0; index < 10; index++) await f.tick(); + expect(f.timers.size).toBe(0); expect(f.panel.hasPending()).toBe(true); + f.panel.suspend(); expect(f.timers.size).toBe(0); + const held = fixture(); held.state.held = true; await held.proposal(); await held.click('approve'); + expect(held.timers.size).toBe(0); expect(held.panel.hasPending()).toBe(true); + expect(held.root.textContent).toContain('held'); + }); + + it('uses the original inline path when the trusted capability is false', async () => { + const f = fixture(); f.state.enabled = false; await f.proposal(); await f.click('approve'); + expect(f.calls.at(-1)?.path).toMatch(/\/review$/u); expect(f.panel.hasPending()).toBe(false); + expect(f.timers.size).toBe(0); + }); +}); diff --git a/src/support-learning.test.ts b/src/support-learning.test.ts new file mode 100644 index 0000000..4a8f14a --- /dev/null +++ b/src/support-learning.test.ts @@ -0,0 +1,540 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it, vi } from 'vitest'; +import { BrowserNode, browserGate } from './test-support-browser'; + +// The same inert DOM guard used by existing public Support tests executes the +// actual module and event handlers. HTTP packets here are synthetic adapters; +// backend persistence/authorization and real-browser layout are separate proof. +interface Call { path: string; method: string; body?: string; headers: Headers; signal?: AbortSignal | null } +interface Ticket { ticketId: string; revision: number; actorSubject: string; status?: string; resolvedAt?: string } +interface Panel { + showTicket(ticket: Ticket, mode?: { recoveryOnly?: boolean }): Promise; + refresh(): Promise; + suspend(): void; + hasPending(): boolean; + hasPendingReview(): boolean; +} +const ticket = { ticketId: 'ticket-example', revision: 7, actorSubject: 'synthetic-staff-A', + status: 'resolved', resolvedAt: '2026-11-09T12:00:00.000Z' }; +const hash = 'a'.repeat(64); +function intentFor() { + return { reviewerId: ticket.actorSubject, ticketId: ticket.ticketId, sourceGeneration: 4, expectedWorkGeneration: 8, + target: { articleId: 'fictional-guide', collectionId: 'fictional-collection', articleRevision: 1, + contentHash: hash, sourceSnapshotGeneration: 1, sourceSnapshotHash: hash, orderedReferencesHash: hash }, + policy: { version: 'fixture-checks', binding: 'fixture-check-binding', + verifiedAt: '2026-11-10T12:00:00.000Z', validUntil: '2026-11-10T13:00:00.000Z' } }; +} +function failure(status: number, extra = {}) { + return Object.assign(new Error('request_failed'), { status, ...extra }); +} +async function drain() { for (let index = 0; index < 80; index++) await Promise.resolve(); } +async function until(check: () => boolean) { + for (let index = 0; index < 500; index++) { if (check()) return; await Promise.resolve(); } + throw new Error('Expected public learning event handler to settle.'); +} +function fixture() { + const root = new BrowserNode('section'); + const calls: Call[] = []; + const lost: { status: number; hasPending: boolean }[] = []; + const ownership: boolean[] = []; + const state = { + identity: { subject: ticket.actorSubject, csrfToken: 'synthetic-current-A' }, + time: 1_000, + reviewHash: hash, + workGeneration: 8, + sourceState: 'eligible', + sourceGeneration: 4, + nextId: 0, + handler: undefined as ((call: Call) => Promise) | undefined, + }; + const envelope = (result: unknown) => ({ result, csrfToken: state.identity.csrfToken }); + const intent = (id: string) => ({ reviewerId: state.identity.subject, ticketId: id, + sourceGeneration: state.sourceGeneration, expectedWorkGeneration: state.workGeneration, + target: { articleId: 'fictional-guide', collectionId: 'fictional-collection', articleRevision: 1, + contentHash: state.reviewHash, sourceSnapshotGeneration: 1, sourceSnapshotHash: hash, orderedReferencesHash: hash }, + policy: { version: 'fixture-checks', binding: 'fixture-check-binding', + verifiedAt: '2026-11-10T12:00:00.000Z', validUntil: '2026-11-10T13:00:00.000Z' } }); + function response(call: Call) { + const id = decodeURIComponent(/\/tickets\/([^/]+)\/learning/u.exec(call.path)?.[1] ?? ''); + if (call.method === 'POST') { + const packet = JSON.parse(call.body ?? '{}'); + if (call.path.endsWith('/review-cancel')) return envelope({ outcome: 'cancelled', ticketId: id, commandId: packet.commandId }); + const accepted = { ticketId: id, sourceGeneration: packet.intent?.sourceGeneration ?? state.sourceGeneration, resolutionCycle: 2, state: state.sourceState }; + const intake = /\/(enroll|evidence)-recovery$/u.exec(call.path)?.[1]; + if (intake) return envelope({ ticketId: id, commandId: packet.commandId, operation: intake, outcome: 'accepted', result: accepted }); + return envelope(packet.intent ? { outcome: 'accepted', result: accepted } : accepted); + } + if (call.path.includes('/proposal?')) return envelope({ + ticketId: id, intent: intent(id), + draft: { generation: 3, revision: { + articleId: 'fictional-guide', collectionId: 'fictional-collection', + title: '', summary: 'Checked private draft.', + content: { format: 'plain_text', text: '' }, + tags: ['fictional'], applicability: { productId: 'fictional', productVersion: '1' }, + } }, + }); + if (call.path.includes('/work?')) return envelope({ ticketId: id, + sourceGeneration: state.sourceGeneration, workGeneration: state.workGeneration, + status: 'awaiting_review', stage: 'kb_delivery', hasProposal: true }); + return envelope({ ticketId: id, sourceGeneration: state.sourceGeneration, + resolutionCycle: 2, state: state.sourceState, reconciliationPending: false }); + } + const request = vi.fn(async (path: string, init: RequestInit) => { + const call: Call = { path, method: init.method ?? 'GET', body: typeof init.body === 'string' ? init.body : undefined, + headers: new Headers(init.headers), signal: init.signal }; + calls.push(call); + return state.handler ? state.handler(call) : response(call); + }); + const readSession = vi.fn(async () => ({ ...state.identity })); + const commandId = vi.fn(() => `EXACT-UpperCase-ID-${++state.nextId}`); + const vm: Record = { document: { createElement: (tag: string) => new BrowserNode(tag) }, AbortController }; + runInNewContext(readFileSync(new URL('../public/staff-support-learning.js', import.meta.url), 'utf8'), vm, + { filename: 'staff-support-learning.js' }); + const factory = vm.PegmaSupportLearning as { createPanel(options: unknown): Panel }; + const panel = factory.createPanel({ root, request, readSession, commandId, + now: () => state.time, onPendingChange: (value: boolean) => ownership.push(value), + onAccessLost: (value: { status: number; hasPending: boolean }) => lost.push(value) }); + function node(key: string, field = false) { + const found = root.all().find((value) => value.dataset[field ? 'learningField' : 'learningAction'] === key); + if (!found) throw new Error('Missing actual learning control: ' + key); + return found; + } + return { root, calls, state, response, envelope, request, readSession, commandId, panel, lost, ownership, node, + writes: () => calls.filter((call) => call.method === 'POST'), + async action(key: string) { node(key).fire('click'); await drain(); }, + async proposal() { await panel.showTicket(ticket); await this.action('work'); await this.action('proposal'); }, + }; +} + +describe('optional public staff learning panel', () => { + it.each(['ticket', 'command', 'operation', 'expected', 'observed', 'extra'] as const)('retains an intake owner after a malformed %s terminal recovery', async (kind) => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.handler = async (call) => call.method === 'POST' ? Promise.reject(failure(409)) : f.response(call); + await f.action('enroll'); const original = f.writes()[0]!; await f.panel.refresh(); + const packet = JSON.parse(original.body ?? '{}'); + const recovered = { outcome: 'superseded', ticketId: ticket.ticketId, commandId: packet.commandId, + operation: 'enroll', expectedRevision: packet.expectedRevision, observedRevision: packet.expectedRevision + 1 }; + if (kind === 'ticket') recovered.ticketId = 'another-ticket'; + else if (kind === 'command') recovered.commandId = packet.commandId.toLowerCase(); + else if (kind === 'operation') recovered.operation = 'evidence'; + else if (kind === 'expected') recovered.expectedRevision += 1; + else if (kind === 'observed') recovered.observedRevision = packet.expectedRevision; + else Object.assign(recovered, { proof: 'client-forged' }); + f.state.handler = async (call) => call.method === 'POST' ? f.envelope(recovered) : f.response(call); + await f.action('retry'); + expect(f.panel.hasPending()).toBe(true); expect(f.ownership).toEqual([true]); + expect(f.writes()[1]?.body).toBe(original.body); expect(f.commandId).toHaveBeenCalledOnce(); + }); + + it('retains a terminal recovery when the closing original session changes', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.handler = async (call) => call.method === 'POST' ? Promise.reject(failure(409)) : f.response(call); + await f.action('enroll'); const original = f.writes()[0]!; await f.panel.refresh(); const packet = JSON.parse(original.body ?? '{}'); + f.state.handler = async (call) => { + if (call.method !== 'POST') return f.response(call); + const value = f.envelope({ outcome: 'superseded', ticketId: ticket.ticketId, commandId: packet.commandId, + operation: 'enroll', expectedRevision: packet.expectedRevision, observedRevision: packet.expectedRevision + 1 }); + f.state.identity = { ...f.state.identity, csrfToken: 'a-replaced-current-session' }; return value; + }; + await f.action('retry'); expect(f.panel.hasPending()).toBe(true); expect(f.ownership).toEqual([true]); + expect(f.lost.at(-1)).toEqual({ status: 401, hasPending: true }); expect(f.writes()[1]?.body).toBe(original.body); + }); + + it.each(['fence', 'operation', 'revision', 'session'] as const)('keeps the original owner after an invalid %s same-revision fence', async (kind) => { + const f = fixture(); await f.panel.showTicket(ticket); + f.node('solution', true).value = 'missing-visible-solution'; f.node('verification', true).value = 'SYNTHETIC_VERIFICATION'; + f.state.handler = async (call) => call.method === 'POST' ? Promise.reject(failure(409)) : f.response(call); + await f.action(kind === 'operation' ? 'enroll' : 'evidence'); const original = f.writes()[0]!; + await f.panel.refresh(); const packet = JSON.parse(original.body ?? '{}'); + f.state.handler = async (call) => { + if (call.method !== 'POST') return f.response(call); + const value = f.envelope({ outcome: 'superseded', ticketId: ticket.ticketId, commandId: packet.commandId, + operation: kind === 'operation' ? 'enroll' : 'evidence', expectedRevision: packet.expectedRevision, + observedRevision: packet.expectedRevision + (kind === 'revision' ? 1 : 0), + fence: kind === 'fence' ? 'unverified_guess' : 'solution_unavailable' }); + if (kind === 'session') f.state.identity = { ...f.state.identity, csrfToken: 'a-different-current-session' }; + return value; + }; + await f.action('retry'); expect(f.panel.hasPending()).toBe(true); expect(f.ownership).toEqual([true]); + expect(f.writes()[1]?.body).toBe(original.body); expect(f.commandId).toHaveBeenCalledOnce(); + if (kind === 'session') expect(f.lost.at(-1)).toEqual({ status: 401, hasPending: true }); + }); + + it('keeps pending recovery owned and performs no automatic mutating retry', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.handler = async (call) => call.method === 'POST' ? Promise.reject(failure(409)) : f.response(call); + await f.action('enroll'); const original = f.writes()[0]!; await f.panel.refresh(); const packet = JSON.parse(original.body ?? '{}'); + f.state.handler = async (call) => call.method === 'POST' ? f.envelope({ outcome: 'pending', ticketId: ticket.ticketId, + commandId: packet.commandId, operation: 'enroll' }) : f.response(call); + await f.action('retry'); await drain(); expect(f.panel.hasPending()).toBe(true); + expect(f.writes()).toHaveLength(2); expect(f.writes()[1]?.body).toBe(original.body); expect(f.commandId).toHaveBeenCalledOnce(); + }); + + it('retains a null receipt and makes cancellation retry sticky after its ACK is lost', async () => { + const f = fixture(); await f.proposal(); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(503); return f.response(call); }; + await f.action('approve'); const original = f.writes()[0]!; + await f.panel.showTicket(ticket, { recoveryOnly: true }); + f.state.handler = async (call) => call.path.endsWith('/review-receipt') ? f.envelope(null) + : call.path.endsWith('/review-cancel') ? Promise.reject(failure(503)) : f.response(call); + await f.action('check-review'); expect(f.panel.hasPending()).toBe(true); + await f.action('cancel-review'); expect(f.panel.hasPending()).toBe(true); + f.state.handler = undefined; + await f.action('retry'); + expect(f.writes().map((call) => call.path.split('/').at(-1))).toEqual(['review', 'review-receipt', 'review-cancel', 'review-cancel']); + expect(f.writes().every((call) => call.body === original.body)).toBe(true); + expect(f.panel.hasPending()).toBe(false); expect(f.commandId).toHaveBeenCalledOnce(); + }); + + it('registers no request until a current staff view is supplied and separates every private read', async () => { + const f = fixture(); + expect(f.calls).toEqual([]); + await f.panel.showTicket(ticket); + expect(f.calls.map((call) => call.path)).toEqual(['/api/support/admin/tickets/ticket-example/learning']); + expect(f.readSession).toHaveBeenCalledTimes(2); + expect(f.node('proposal').disabled).toBe(true); + await f.action('work'); + expect(f.calls.at(-1)?.path).toBe('/api/support/admin/tickets/ticket-example/learning/work?sourceGeneration=4'); + expect(f.node('proposal').disabled).toBe(false); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + await f.action('proposal'); + expect(f.calls.at(-1)?.path).toBe('/api/support/admin/tickets/ticket-example/learning/proposal?sourceGeneration=4'); + expect(f.root.textContent).toContain(''); + expect(f.root.all().some((node) => node.tagName === 'script' || node.tagName === 'img')).toBe(false); + expect(f.writes()).toEqual([]); + }); + + it.each(['unverified', 'held'] as const)('accepts SDK %s source generation0 for initial evidence without allowing work or review', async (state) => { + const f = fixture(); f.state.sourceGeneration = 0; f.state.sourceState = state; + await f.panel.showTicket(ticket); + expect(f.root.textContent).toContain('Source 0'); + expect(f.node('evidence').disabled).toBe(false); + for (const action of ['work', 'proposal', 'approve', 'reject']) { + expect(f.node(action).disabled).toBe(true); + await f.action(action); + } + expect(f.calls.some((call) => /\/(work|proposal)\?/u.test(call.path))).toBe(false); + f.node('solution', true).value = 'public-solution-message'; + f.node('verification', true).value = 'staff-verification-reference'; + await f.action('evidence'); + expect(f.writes()).toHaveLength(1); + expect(f.panel.hasPending()).toBe(false); + expect(JSON.parse(f.writes()[0]?.body ?? '{}')).toEqual({ commandId: 'EXACT-UpperCase-ID-1', + expectedRevision: ticket.revision, resolutionCycle: 2, + solutionMessageId: 'public-solution-message', verificationReference: 'staff-verification-reference' }); + }); + + it('keeps an unknown generation0 enrollment pending through GET until its exact manual retry ACK', async () => { + const f = fixture(); f.state.sourceGeneration = 0; f.state.sourceState = 'unverified'; + await f.panel.showTicket(ticket); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(503); return f.response(call); }; + await f.action('enroll'); const first = f.writes()[0]!; + expect(f.panel.hasPending()).toBe(true); + await f.panel.refresh(); + expect(f.panel.hasPending()).toBe(true); + expect(f.node('retry').disabled).toBe(false); + expect(f.node('evidence').disabled).toBe(true); + expect(f.writes()).toHaveLength(1); + f.state.handler = undefined; await f.action('retry'); + expect(f.writes()[1]?.body).toBe(first.body); + expect(f.panel.hasPending()).toBe(false); + expect(f.commandId).toHaveBeenCalledOnce(); + }); + + it.each(['open', 'missing-resolved-at', 'invalid-resolved-at', 'withdrawn'] as const)( + 'does not enable first evidence from %s metadata', async (variant) => { + const f = fixture(); f.state.sourceGeneration = 0; f.state.sourceState = variant === 'withdrawn' ? 'withdrawn' : 'unverified'; + const bound: Ticket = variant === 'missing-resolved-at' + ? { ticketId: ticket.ticketId, revision: ticket.revision, actorSubject: ticket.actorSubject, status: 'resolved' } + : { ...ticket, ...(variant === 'open' ? { status: 'open' } + : variant === 'invalid-resolved-at' ? { resolvedAt: 'not-a-timestamp' } : {}) }; + await f.panel.showTicket(bound); + expect(f.node('evidence').disabled).toBe(true); + await f.action('evidence'); expect(f.writes()).toEqual([]); + expect(f.panel.hasPending()).toBe(false); + }, + ); + + it.each([-1, 0.5, Number.MAX_SAFE_INTEGER + 1])('still rejects invalid source counter %s', async (generation) => { + const f = fixture(); f.state.sourceGeneration = generation; f.state.sourceState = 'unverified'; + await f.panel.showTicket(ticket); + expect(f.node('enroll').disabled).toBe(true); + expect(f.node('evidence').disabled).toBe(true); + expect(f.node('work').disabled).toBe(true); + expect(f.writes()).toEqual([]); + }); + it.each(['enroll', 'evidence', 'approve', 'reject', 'withdraw', 'invalidate'] as const)( + 'sends the closed %s packet with an exact echoed intent and no added authority', async (action) => { + const f = fixture(); + await f.proposal(); + f.node('solution', true).value = 'public-solution-message'; + f.node('verification', true).value = 'staff-verification-reference'; + f.node('review-reason', true).value = 'Reviewed the shown proposal.'; + await f.action(action); + const post = f.writes()[0]!; + expect(post.path).toBe(`/api/support/admin/tickets/ticket-example/learning/${action === 'approve' || action === 'reject' ? 'review' : action}`); + const packet = JSON.parse(post.body ?? '{}'); + expect(packet.commandId).toBe('EXACT-UpperCase-ID-1'); + if (action === 'enroll') expect(packet).toEqual({ commandId: packet.commandId, expectedRevision: 7 }); + if (action === 'evidence') expect(packet).toEqual({ commandId: packet.commandId, + expectedRevision: 7, resolutionCycle: 2, solutionMessageId: 'public-solution-message', + verificationReference: 'staff-verification-reference' }); + if (action === 'approve' || action === 'reject') expect(packet).toEqual({ + commandId: packet.commandId, intent: intentFor(), decision: action, reason: 'Reviewed the shown proposal.' }); + if (action === 'withdraw') expect(packet).toEqual({ commandId: packet.commandId, reason: 'privacy_withdrawal' }); + if (action === 'invalidate') expect(packet).toEqual({ commandId: packet.commandId, reason: 'evidence_revoked' }); + for (const forbidden of ['target', 'provenance', 'actor', 'policyVersion', 'product', 'evidence', 'correlationId']) + expect(packet).not.toHaveProperty(forbidden); + expect(post.headers.get('X-Pegma-CSRF')).toBe('synthetic-current-A'); + expect(post.headers.get('Content-Type')).toBe('application/json'); + expect(f.panel.hasPending()).toBe(false); + expect(f.ownership).toEqual([true, false]); + expect(f.node('enroll').disabled).toBe(true); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + expect(f.writes()).toHaveLength(1); + }, + ); + + it.each([400, 401, 403, 404, 409, 429, 500, 503])( + 'retains an unknown mutation through HTTP%s and GET never acknowledges it', async (status) => { + const f = fixture(); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(status); return f.response(call); }; + await f.panel.showTicket(ticket); + await f.action('enroll'); + const first = f.writes()[0]!; + expect(f.panel.hasPending()).toBe(true); + expect(f.root.textContent).not.toContain('Source 4'); + await f.panel.refresh(); + expect(f.panel.hasPending()).toBe(true); + expect(f.node('enroll').disabled).toBe(true); + expect(f.writes()).toHaveLength(1); + if (status === 401 || status === 403) expect(f.lost).toEqual([{ status, hasPending: true }]); + f.state.time = 100_000; + f.state.handler = undefined; + await f.action('retry'); + expect(f.writes()[1]?.body).toBe(first.body); + expect(f.writes()[1]?.path).toBe(first.path + '-recovery'); + expect(f.commandId).toHaveBeenCalledOnce(); + expect(f.panel.hasPending()).toBe(false); + }, + ); + + it('keeps the exact A-owned packet through account A to B to A and uses only fresh A credentials', async () => { + const f = fixture(); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(503); return f.response(call); }; + await f.proposal(); + await f.action('approve'); + const original = f.writes()[0]!; + f.state.identity = { subject: 'synthetic-staff-B', csrfToken: 'synthetic-current-B' }; + await f.panel.showTicket({ ...ticket, actorSubject: 'synthetic-staff-B' }); + await f.action('retry'); + expect(f.writes()).toHaveLength(1); + expect(f.panel.hasPending()).toBe(true); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + expect(f.root.textContent).not.toContain('Source 4'); + f.state.identity = { subject: ticket.actorSubject, csrfToken: 'synthetic-fresh-A' }; + await f.panel.showTicket(ticket); + f.state.handler = undefined; + await f.action('retry'); + expect(f.writes()[1]?.body).toBe(original.body); + expect(f.writes()[1]?.headers.get('X-Pegma-CSRF')).toBe('synthetic-fresh-A'); + expect(f.commandId).toHaveBeenCalledOnce(); + }); + + it('retains ticket A ownership through ticket A to B to A without sending under B', async () => { + const f = fixture(); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(503); return f.response(call); }; + await f.panel.showTicket(ticket); await f.action('enroll'); + const original = f.writes()[0]!; + await f.panel.showTicket({ ...ticket, ticketId: 'another-ticket' }); + await f.action('retry'); + expect(f.writes()).toHaveLength(1); + expect(f.calls.some((call) => call.path.includes('/another-ticket/'))).toBe(false); + await f.panel.showTicket(ticket); + f.state.handler = undefined; + await f.action('retry'); + expect(f.writes()[1]?.body).toBe(original.body); + expect(f.writes()[1]?.path).toBe(original.path + '-recovery'); + }); + + it('immediately clears private DOM and fields on sign-out while retaining an unknown command', async () => { + const f = fixture(); + await f.proposal(); + f.node('verification', true).value = 'PRIVATE_UNSENT_REFERENCE'; + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(503); return f.response(call); }; + await f.action('approve'); + f.panel.suspend(); + expect(f.panel.hasPending()).toBe(true); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + expect(f.node('verification', true).value).toBe(''); + expect(f.node('retry').disabled).toBe(true); + expect(f.node('refresh').disabled).toBe(true); + }); + + it('does not consume a command ID or hold a phantom packet for locally invalid evidence', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + f.node('solution', true).value = 'solution'; + f.node('verification', true).value = 'bad\u009breference'; + await f.action('evidence'); + expect(f.writes()).toEqual([]); + expect(f.panel.hasPending()).toBe(false); + expect(f.commandId).not.toHaveBeenCalled(); + f.node('verification', true).value = 'valid-reference'; + await f.action('evidence'); + expect(f.writes()).toHaveLength(1); + }); + + it('does not send if the current actor or session changes before submission', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.identity = { subject: ticket.actorSubject, csrfToken: 'rotated-session' }; + await f.action('enroll'); + expect(f.writes()).toEqual([]); + expect(f.panel.hasPending()).toBe(false); + expect(f.lost).toEqual([{ status: 401, hasPending: false }]); + expect(f.root.textContent).not.toContain('Source 4'); + }); + + it('keeps an ACK unknown when the closing session changes, then retries the exact packet', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.handler = async (call) => { + if (call.method !== 'POST') return f.response(call); + const ack = f.response(call); + f.state.identity = { subject: 'synthetic-staff-B', csrfToken: 'new-cookie' }; + return ack; + }; + await f.action('enroll'); + const first = f.writes()[0]!; + expect(f.panel.hasPending()).toBe(true); + f.state.identity = { subject: ticket.actorSubject, csrfToken: 'fresh-owner-session' }; + f.state.handler = undefined; + await f.panel.showTicket(ticket); + expect(f.panel.hasPending()).toBe(true); + await f.action('retry'); + expect(f.writes()[1]?.body).toBe(first.body); + expect(f.panel.hasPending()).toBe(false); + }); + + it.each(['csrf', 'missing-result', 'invalid-result'])( + 'does not settle a mutation from a malformed %s acknowledgment', async (kind) => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.handler = async () => kind === 'csrf' ? { result: {}, csrfToken: 'wrong' } + : kind === 'missing-result' ? { csrfToken: f.state.identity.csrfToken } + : f.envelope(null); + await f.action('enroll'); + expect(f.panel.hasPending()).toBe(true); + expect(f.ownership).toEqual([true]); + expect(f.root.textContent).not.toContain('Source 4'); + }, + ); + + it('never rebinds an unknown review to a later GET proposal or invents a new command ID', async () => { + const f = fixture(); await f.proposal(); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(409); return f.response(call); }; + await f.action('reject'); + const first = f.writes()[0]!; + f.state.reviewHash = 'b'.repeat(64); f.state.workGeneration = 9; + await f.panel.refresh(); await f.action('work'); await f.action('proposal'); + expect(f.panel.hasPending()).toBe(true); + expect(f.node('approve').disabled).toBe(true); + await f.action('retry'); + expect(f.writes()[1]?.body).toBe(first.body); + expect(JSON.parse(f.writes()[1]?.body ?? '{}').intent.target.contentHash).toBe(hash); + expect(JSON.parse(f.writes()[1]?.body ?? '{}').intent.expectedWorkGeneration).toBe(8); + expect(f.commandId).toHaveBeenCalledOnce(); + }); + + it('does not infer KB access after a proposal denial or continue to a review', async () => { + const f = fixture(); await f.panel.showTicket(ticket); await f.action('work'); + f.state.handler = async (call) => { if (call.path.includes('/proposal?')) throw failure(403); return f.response(call); }; + await f.action('proposal'); await f.action('approve'); + expect(f.writes()).toEqual([]); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + expect(f.root.textContent).not.toContain('Source 4'); + expect(f.lost).toEqual([{ status: 403, hasPending: false }]); + expect(f.calls.some((call) => /roles|policy|permissions/u.test(call.path))).toBe(false); + }); + + it('allows explicit enrollment after a source 404 without treating that read as an ACK', async () => { + const f = fixture(); + f.state.handler = async (call) => { if (call.method === 'GET') throw failure(404); return f.response(call); }; + await f.panel.showTicket(ticket); + expect(f.node('enroll').disabled).toBe(false); + expect(f.node('evidence').disabled).toBe(true); + await f.action('enroll'); + expect(f.writes()).toHaveLength(1); + expect(f.panel.hasPending()).toBe(false); + }); + + it('discards a delayed private proposal after suspension even when the request ignores abort', async () => { + const f = fixture(); await f.panel.showTicket(ticket); await f.action('work'); + const gate = browserGate(); + f.state.handler = async (call) => call.path.includes('/proposal?') ? gate.promise : f.response(call); + f.node('proposal').fire('click'); + await until(() => f.calls.some((call) => call.path.includes('/proposal?'))); + const call = f.calls.at(-1)!; + f.panel.suspend(); + expect(call.signal?.aborted).toBe(true); + gate.resolve(f.response(call)); await drain(); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + expect(f.node('approve').disabled).toBe(true); + }); + + it('discards a delayed mutation ACK after sign-out and retains the packet for its owner', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + const gate = browserGate(); + f.state.handler = async (call) => call.method === 'POST' ? gate.promise : f.response(call); + f.node('enroll').fire('click'); await until(() => f.writes().length === 1); + const original = f.writes()[0]!; + f.panel.suspend(); + gate.resolve(f.response(original)); await drain(); + expect(f.panel.hasPending()).toBe(true); + expect(f.ownership).toEqual([true]); + f.state.handler = undefined; + await f.panel.showTicket(ticket); await f.action('retry'); + expect(f.writes()[1]?.body).toBe(original.body); + expect(f.panel.hasPending()).toBe(false); + }); + + it('does not overlap writes or automatically retry while a mutation is pending', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + const gate = browserGate(); + f.state.handler = async (call) => call.method === 'POST' ? gate.promise : f.response(call); + f.node('enroll').fire('click'); f.node('withdraw').fire('click'); + await until(() => f.writes().length === 1); + await drain(); expect(f.writes()).toHaveLength(1); + gate.reject(new Error('Synthetic request deadline')); await drain(); + expect(f.panel.hasPending()).toBe(true); + expect(f.writes()).toHaveLength(1); + }); + + it('respects the injected existing Retry-After deadline without an automatic retry', async () => { + const f = fixture(); await f.panel.showTicket(ticket); + f.state.handler = async (call) => { if (call.method === 'POST') throw failure(429, { retryAt: 9_000 }); return f.response(call); }; + await f.action('enroll'); await f.panel.refresh(); await f.action('retry'); + expect(f.writes()).toHaveLength(1); + f.state.time = 9_000; f.state.handler = undefined; + await f.action('retry'); expect(f.writes()).toHaveLength(2); + expect(f.writes()[1]?.body).toBe(f.writes()[0]?.body); + }); + + it.each(['ticket', 'generation', 'hash', 'draft'])( + 'never enables review for a malformed proposal %s', async (kind) => { + const f = fixture(); await f.panel.showTicket(ticket); await f.action('work'); + f.state.handler = async (call) => { + const response = f.response(call) as { result: Record; csrfToken: string }; + if (call.path.includes('/proposal?')) { + if (kind === 'ticket') response.result.ticketId = 'another-ticket'; + if (kind === 'generation') (response.result.intent as Record).sourceGeneration = 99; + if (kind === 'hash') ((response.result.intent as Record).target as Record).contentHash = 'forged'; + if (kind === 'draft') response.result.draft = { revision: { title: 'Incomplete' } }; + } + return response; + }; + await f.action('proposal'); await f.action('approve'); + expect(f.writes()).toEqual([]); + expect(f.node('approve').disabled).toBe(true); + expect(f.root.textContent).not.toContain('PRIVATE_CHECKED_PROPOSAL'); + }, + ); +}); diff --git a/worker/README.md b/worker/README.md index b4d1b95..cc9e8d7 100644 --- a/worker/README.md +++ b/worker/README.md @@ -41,11 +41,21 @@ no Worker authority). Do not substitute a broad personal OAuth token into GitHub. `pnpm run worker:deploy` from an authenticated operator session remains the break-glass path. +Wrangler 4.114 applies configured queue producers and consumers during deployment. +The learning flag controls runtime handling. Queue lookup and consumer +creation/update accept the existing Workers Scripts write grant. Cloudflare's +permission reference describes the Scripts Edit permission as write access. +The queue and dead-letter queue are provisioned in the deployment account. +[List queues](https://developers.cloudflare.com/api/resources/queues/methods/list/), +[create consumer](https://developers.cloudflare.com/api/resources/queues/subresources/consumers/methods/create/), +[update consumer](https://developers.cloudflare.com/api/resources/queues/subresources/consumers/methods/update/), +[permission reference](https://developers.cloudflare.com/fundamentals/api/reference/permissions/). + ## Identity composition The account boundary is fixed to issuer `https://pegma.dev` and WebAuthn RP ID `pegma.dev`. Cloudflare D1 is consumed only through -`@pegma/storage-cloudflare-d1`; `@pegma/sessions@0.1.0` stores SHA-256-hashed +`@pegma/storage-cloudflare-d1`; `@pegma/sessions@0.2.0` stores SHA-256-hashed opaque session identifiers. The browser receives a cryptographically random `__Host-pegma_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, and `Path=/`. @@ -62,9 +72,9 @@ stored principal against Identity and the Authorization claims adapter, and returns only the issuer and subject. Missing, expired, revoked, malformed, or account-invalid sessions receive `401`; every response is `no-store`. -The production composition pins `@pegma/identity@0.1.0` and -`@pegma/authorization-identity@0.1.2`. Account creation and fallback sign-in -commit the email-code operation and its `@pegma/mail@0.1.0` job atomically in +The production composition pins `@pegma/identity@0.1.2` and +`@pegma/authorization-identity@0.4.0`. Account creation and fallback sign-in +commit the email-code operation and its `@pegma/mail@0.1.1` job atomically in Identity's D1 collection. Start routes never receive or return the generated code; verify routes accept the user-supplied eight digits, and only the scheduled renderer recovers the stored protected material for delivery. @@ -164,9 +174,10 @@ Idle runs do not import an unused HMAC key; secret validation remains eager. A s `0-58 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup, email-operation repair, Mail retention, expired Sessions, each of the four Identity rate-limit policies, Support queue repair/inactive sweep, and each of -the four Support/Admin rate-limit policies. The 14 lanes rotate using the -scheduled UTC time, including across hour boundaries, so each runs every -14–15 minutes. This gives cleanup its own invocation CPU budget instead of +the four Support/Admin rate-limit policies, Knowledge maintenance and the +separately gated learning-review discovery lane. The 16 lanes rotate through +eligible scheduled UTC ticks, including across hour boundaries, so each runs +every 16 ticks (a nominal 16-17 minutes because minute 59 is omitted). This gives cleanup its own invocation CPU budget instead of combining every task under the Workers Free 10 ms limit. Authentication and rate-limit checks still enforce expiry on access; cleanup only reclaims or repairs stored data. Paged Identity and Support cleanup also consumes at most @@ -194,7 +205,7 @@ public acknowledgement endpoint. ## Support Desk composition -Authenticated product feedback composes exact `0.2.3` versions of +Authenticated product feedback composes exact `0.2.5` versions of `@pegma/support-desk-contracts`, `@pegma/support-desk-core`, `@pegma/support-desk-application`, and `@pegma/support-desk-templates` over the same `IDENTITY_DB` D1 binding. Support Desk collections @@ -205,8 +216,11 @@ via AccessContext defaults (not a paid entitlement). Categories: `feedback`, `bug`, `feature_request`, `documentation`, `question`. Subject marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/ticket/?id=…`. -The optional `@pegma/support-desk-ai@0.2.3` package is installed for the -[isolated scripted answering stage](../docs/SUPPORT_ASSISTANT_STAGE.md). +The optional `@pegma/support-desk-ai@0.2.5` package is installed for the +[isolated scripted answering stage](../docs/SUPPORT_ASSISTANT_STAGE.md). The +normal public `0.2.5` graph passed the 1,125-test local/CI +[adoption checkpoint](../docs/KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint); +review and deployment acceptance remain pending for the changed source. Create and reply use durable rate limits `pegma.support.ticket.create` and `pegma.support.ticket.reply`. Rotating cleanup runs queue repair and @@ -302,7 +316,7 @@ Existing records decode missing per-repository progress as empty. No D1 schema migration is required, and reconciliation never fabricates webhook receipts. After deploying maintenance changes, check CPU distributions and resource-limit -outcomes for all four triggers, including populated mail pages and release +outcomes for all five configured cron triggers, including populated mail pages and release 200/304 responses. Local D1 tests prove bounded page progress and delivery idempotency, not Cloudflare's production CPU accounting. These changes target the Workers Free 10 ms allowance; they cannot guarantee an absolute CPU ceiling. @@ -310,8 +324,8 @@ the Workers Free 10 ms allowance; they cannot guarantee an absolute CPU ceiling. One-record pages trade throughput for headroom: mail scans at most 60 send and 59 reconciliation operation records per hour, including retained terminal records. A full scan must remain comfortably shorter than the email-code lifetime; inspect scan -backlogs as usage grows. Cleanup pages advance once per lane every 14-15 -minutes. The published Sessions and rate-limit packages still expose +backlogs as usage grows. Cleanup pages advance once per lane every 16 eligible +ticks (a nominal 16-17 minutes). The published Sessions and rate-limit packages still expose whole-partition sweeps, so their work grows with partition size. Sustained backlogs need indexed discovery and paginated component APIs, or a larger CPU allowance. Reducing frequency alone does not raise the per-invocation limit. diff --git a/worker/src/index.ts b/worker/src/index.ts index eb4a62a..b00014c 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -56,13 +56,34 @@ import { import { createPegmaMcpHandler } from './mcp-server'; import type { CatalogFetchEnv } from './mcp-catalog-fetch'; import { handleKnowledgeRequest, isKnowledgeRequest } from './knowledge-host'; +import type { createSupportLearningReviewQueue, SupportLearningReviewQueueMessage } from './support-learning-review-queue'; -type AppEnv = Env & +type AppEnv = Omit & LoggerEnv & IdentityRuntimeEnv & GitHubReleaseWebhookEnv & SupportRuntimeEnv & - CatalogFetchEnv; + CatalogFetchEnv & { + readonly PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED?: string; + readonly SUPPORT_LEARNING_REVIEWS?: Queue; + }; + +/** Trusted source composition only; no product/check/source ports are invented here. */ +export interface SupportLearningReviewWorkerComposition { + readonly enabled: () => boolean; + create(environment: AppEnv, logger: ReturnType): { + /** The actual configured Support API, including its fresh staff-detail hints. */ + readonly api: (request: Request) => Promise; + readonly queue: ReturnType; + }; +} + +function learningReviewsEnabled(environment: { readonly PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED?: string; + readonly SUPPORT_LEARNING_REVIEWS?: unknown }, composition?: SupportLearningReviewWorkerComposition): boolean { + try { return environment.PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED === 'true' && + environment.SUPPORT_LEARNING_REVIEWS !== undefined && composition?.enabled() === true; } + catch { return false; } +} function knowledgeRetrievalEnabled(environment: { readonly PEGMA_KNOWLEDGE_ENABLED?: string; @@ -125,7 +146,8 @@ function createSupportHandler( * Cloudflare Workers Logs (via @pegma/logger-cloudflare + observability) * teed with Datadog when DATADOG_API_KEY is set. */ -export default { +export function createWorker(options: { readonly learningReviews?: SupportLearningReviewWorkerComposition } = {}) { +return { async fetch( request: Request, env: AppEnv, @@ -197,7 +219,7 @@ export default { probe: 'disabled' | 'ok' | 'fail'; } = { storage: 'cloudflare-d1', - packages: '@pegma/support-desk-application@0.2.3', + packages: '@pegma/support-desk-application@0.2.5', probe: 'disabled', }; if (supportHealthProbeEnabled(env)) { @@ -379,6 +401,9 @@ export default { if (path.startsWith('/api/support/')) { try { + const reviews = options.learningReviews; + if (reviews !== undefined && learningReviewsEnabled(env, reviews)) + return await reviews.create(env, logger).api(request); return await createSupportHandler(env, logger).api(request); } catch (error) { logger.log('error', 'support.runtime_unavailable', { @@ -528,6 +553,16 @@ export default { })(), ); + if (cleanup?.kind === 'learning_reviews') { + const reviews = options.learningReviews; + if (reviews !== undefined && learningReviewsEnabled(env, reviews)) + ctx.waitUntil((async () => { + try { await reviews.create(env, logger).queue.runPage(); } + catch { /* Durable SDK rows remain available on the next physical scan. */ } + })()); + return; + } + if (cleanup?.kind === 'support') ctx.waitUntil( (async () => { @@ -550,4 +585,23 @@ export default { })(), ); }, + async queue(batch: MessageBatch, env: AppEnv, ctx: ExecutionContext): Promise { + // The consumer configuration is max_batch_size:1. Refuse accidental other + // queues and leave durable SDK requests available for rediscovery. + const reviews = options.learningReviews; + if (batch.queue !== 'pegma-dev-support-learning-reviews' || reviews === undefined || + !learningReviewsEnabled(env, reviews)) { + for (const message of batch.messages) message.retry({ delaySeconds: 30 }); + return; + } + const logger = createAppLogger(env, (promise) => ctx.waitUntil(promise)); + try { await reviews.create(env, logger).queue.consume(batch); } + catch { + for (const message of batch.messages) message.retry({ delaySeconds: 30 }); + } + }, } satisfies ExportedHandler; +} + +// A binding/flag alone cannot supply missing trusted runtime configuration. +export default createWorker(); diff --git a/worker/src/knowledge-retrieval-maintenance.ts b/worker/src/knowledge-retrieval-maintenance.ts index 46154ca..132a9e7 100644 --- a/worker/src/knowledge-retrieval-maintenance.ts +++ b/worker/src/knowledge-retrieval-maintenance.ts @@ -2,6 +2,7 @@ import { resolveAccess } from '@pegma/authorization-core'; import { createKnowledgeBaseApplication, type RepairRetrievalPageResult, + type PrivateSourcesVerifier, } from '@pegma/knowledge-base-application'; import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; import type { Clock, Logger } from '@pegma/spine'; @@ -16,6 +17,7 @@ export interface KnowledgeRetrievalMaintenanceOptions { readonly clock: Clock; readonly logger: Logger; readonly isEnabled: () => boolean; + readonly privateSources?: PrivateSourcesVerifier; } interface BookmarkRecord { @@ -111,12 +113,16 @@ function validPage(result: RepairRetrievalPageResult): boolean { /** Server-owned projection authority; never a human or delegated principal. */ export const knowledgeIndexAccess = access; -/** Phase01 is source-free: private source snapshots fail closed in the SDK. */ +/** An absent source verifier keeps private-source snapshots fail-closed. */ export function createKnowledgeProjectionApplication( store: Store, clock: Clock, + privateSources?: PrivateSourcesVerifier, ) { - return createKnowledgeBaseApplication({ store, clock }); + return createKnowledgeBaseApplication({ + store, clock, + ...(privateSources === undefined ? {} : { privateSources }), + }); } export function knowledgeRetrievalCurrent( @@ -206,6 +212,7 @@ export function createKnowledgeRetrievalMaintenance( const application = createKnowledgeProjectionApplication( options.store, options.clock, + options.privateSources, ); stage = 'repair'; const result = await application.repairRetrievalPage(access, { diff --git a/worker/src/knowledge-retrieval-ready.ts b/worker/src/knowledge-retrieval-ready.ts index 0a69f5e..f08313b 100644 --- a/worker/src/knowledge-retrieval-ready.ts +++ b/worker/src/knowledge-retrieval-ready.ts @@ -1,4 +1,4 @@ -import type { ArticleIndexStatusDto } from '@pegma/knowledge-base-application'; +import type { ArticleIndexStatusDto, PrivateSourcesVerifier } from '@pegma/knowledge-base-application'; import type { Clock, Logger } from '@pegma/spine'; import { defineCollection, type Store } from '@pegma/storage-core'; import { @@ -14,6 +14,7 @@ export interface KnowledgeRetrievalReadyOptions { readonly clock: Clock; readonly logger: Logger; readonly isEnabled: () => boolean; + readonly privateSources?: PrivateSourcesVerifier; } interface ReadyHint { readonly id: string; @@ -160,6 +161,7 @@ export function createKnowledgeRetrievalReady( const result = await createKnowledgeProjectionApplication( options.store, options.clock, + options.privateSources, ).repairArticleIndex(knowledgeIndexAccess, { articleId: row.value.articleId, maxBatches: 1, diff --git a/worker/src/knowledge-runtime.ts b/worker/src/knowledge-runtime.ts index 38c0bcd..9a555b4 100644 --- a/worker/src/knowledge-runtime.ts +++ b/worker/src/knowledge-runtime.ts @@ -5,6 +5,7 @@ import { createKnowledgeBaseApplication, KnowledgeBaseAuthorizationError, type KnowledgeBaseApplication, + type PrivateSourcesVerifier, } from '@pegma/knowledge-base-application'; import { knowledgePermissions, @@ -51,6 +52,7 @@ export interface KnowledgeRuntimeOptions readonly agentAccess: AgentAccessRuntime | null; readonly browserLimitCount?: number; readonly isEnabled?: () => boolean; + readonly privateSources?: PrivateSourcesVerifier; } export interface KnowledgeRuntime { readonly application: KnowledgeBaseApplication; @@ -101,6 +103,7 @@ export function createKnowledgeRuntime( store: options.store, clock: options.clock, evidenceVerifier: evidence.verifier, + ...(options.privateSources === undefined ? {} : { privateSources: options.privateSources }), }); const browserLimit = createDurableLimiter( defineRateLimitPolicy({ @@ -123,6 +126,7 @@ export function createKnowledgeRuntime( clock: options.clock, logger: options.logger, isEnabled: options.isEnabled ?? (() => true), + ...(options.privateSources === undefined ? {} : { privateSources: options.privateSources }), }).enqueue, async limitBrowser(request) { const key = await knowledgeDigest( diff --git a/worker/src/maintenance-cursors.d1.test.ts b/worker/src/maintenance-cursors.d1.test.ts index 2185d4f..04a238a 100644 --- a/worker/src/maintenance-cursors.d1.test.ts +++ b/worker/src/maintenance-cursors.d1.test.ts @@ -374,7 +374,7 @@ describe('maintenance cursor writes over D1', () => { expect( createProductionSupportMaintenanceRuntime(env).limiters, ).toHaveLength(supportLimiters.length); - const lanes = Array.from({ length: 15 }, (_, index) => + const lanes = Array.from({ length: 16 }, (_, index) => cleanupLaneAt(Date.parse('2026-10-15T12:01:00Z') + index * 60_000), ); for (const [kind, limiters] of [ @@ -382,7 +382,7 @@ describe('maintenance cursor writes over D1', () => { ['support', supportLimiters], ] as const) { const indices = lanes - .filter((lane) => lane.kind !== 'knowledge') + .filter((lane) => lane.kind === 'identity' || lane.kind === 'support') .filter((lane) => lane.kind === kind && lane.task === 'rate_limits') .map((lane) => lane.limiterIndex) .sort(); diff --git a/worker/src/maintenance-schedule.test.ts b/worker/src/maintenance-schedule.test.ts index fbd39a4..4fa7e3f 100644 --- a/worker/src/maintenance-schedule.test.ts +++ b/worker/src/maintenance-schedule.test.ts @@ -131,7 +131,7 @@ describe('maintenance dispatch', () => { ]) { expect(cleanupLaneAt(time)).toEqual( expect.objectContaining({ - kind: expect.stringMatching(/^(identity|support|knowledge)$/), + kind: expect.stringMatching(/^(identity|support|knowledge|learning_reviews)$/), }), ); } @@ -174,8 +174,8 @@ describe('maintenance dispatch', () => { observed.push(JSON.stringify(cleanupLaneAt(time))); } } - const cycle = observed.slice(0, 15); - expect(new Set(cycle).size).toBe(15); + const cycle = observed.slice(0, 16); + expect(new Set(cycle).size).toBe(16); for (let index = 0; index < observed.length; index++) { expect(observed[index]).toBe(cycle[index % cycle.length]); } @@ -207,10 +207,10 @@ describe('maintenance dispatch', () => { expect(runReleaseReconciliation).not.toHaveBeenCalled(); }); - it('preserves all 15 cleanup lanes across a UTC day boundary without sharing the global rate job', async () => { + it('preserves all 16 cleanup lanes across a UTC day boundary without sharing the global rate job', async () => { const lanes = []; const start = Date.parse('2026-10-15T23:53:00Z'); - for (let minute = 0; minute < 16; minute++) { + for (let minute = 0; minute < 17; minute++) { const time = start + minute * 60_000; if (new Date(time).getUTCMinutes() === 59) continue; const lane = cleanupLaneAt(time); @@ -222,7 +222,7 @@ describe('maintenance dispatch', () => { identity: runIdentityMaintenance, support: runSupportMaintenance, }; - if (lane.kind !== 'knowledge') { + if (lane.kind === 'identity' || lane.kind === 'support') { expect(maintenance[lane.kind]).toHaveBeenCalledExactlyOnceWith( expect.anything(), expect.anything(), @@ -239,7 +239,7 @@ describe('maintenance dispatch', () => { } expect(runReleaseReconciliation).not.toHaveBeenCalled(); } - expect(new Set(lanes).size).toBe(15); + expect(new Set(lanes).size).toBe(16); expect( lanes.filter( (lane) => @@ -259,6 +259,21 @@ describe('maintenance dispatch', () => { } }); + it('leaves the learning dispatch lane port-free when trusted review composition is absent', async () => { + const start = Date.parse('2026-10-15T00:00:00Z'); + const offset = Array.from({ length: 16 }, (_, minute) => minute).find( + (minute) => cleanupLaneAt(start + minute * 60_000).kind === 'learning_reviews', + ); + if (offset === undefined) throw new Error('Expected the exclusive review dispatch lane'); + expect(await scheduled(CLEANUP_CRON, start + offset * 60_000)).toBe(0); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createCloudflareD1Store).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalReady).not.toHaveBeenCalled(); + }); + it('isolates 39 rate pages and 19 ready pages per hour across a UTC day boundary', async () => { const range = /^(\d+)-(\d+) \* \* \* \*$/.exec(RATE_LIMIT_CRON); expect(range).not.toBeNull(); @@ -308,7 +323,7 @@ describe('maintenance dispatch', () => { it('isolates a failed rate invocation from later identity and support cleanup invocations', async () => { const start = Date.parse('2026-10-15T00:00:00Z'); for (const kind of ['identity', 'support'] as const) { - const offset = Array.from({ length: 15 }, (_, minute) => minute).find( + const offset = Array.from({ length: 16 }, (_, minute) => minute).find( (minute) => cleanupLaneAt(start + minute * 60_000).kind === kind, ); if (offset === undefined) diff --git a/worker/src/maintenance-schedule.ts b/worker/src/maintenance-schedule.ts index 12e78f6..9793ef7 100644 --- a/worker/src/maintenance-schedule.ts +++ b/worker/src/maintenance-schedule.ts @@ -5,7 +5,7 @@ import type { SupportMaintenanceTask } from './support-maintenance'; export const MAIL_CRON = '* * * * *'; // Skip minute zero so every trigger has a distinct schedule. export const MAIL_RECONCILE_CRON = '1-59 * * * *'; -// Cleanup skips minute 59 and rotates through 15 small lanes. +// Cleanup skips minute 59 and rotates through 16 exclusive small lanes. export const CLEANUP_CRON = '0-58 * * * *'; // Two ticks clean rate windows, then one advances a ready KB hint. export const RATE_LIMIT_CRON = '0-57 * * * *'; @@ -24,7 +24,8 @@ export type CleanupLane = | { readonly kind: 'knowledge'; readonly task: KnowledgeMaintenanceTask; - }; + } + | { readonly kind: 'learning_reviews' }; const CLEANUP_LANES: readonly CleanupLane[] = [ { kind: 'identity', task: 'challenges' }, @@ -44,6 +45,7 @@ const CLEANUP_LANES: readonly CleanupLane[] = [ limiterIndex, })), { kind: 'knowledge', task: 'rate_limits' }, + { kind: 'learning_reviews' }, ]; /** Deterministic across cold starts, delayed delivery, and UTC hour boundaries. */ diff --git a/worker/src/support-access.test.ts b/worker/src/support-access.test.ts index f2ebd3c..ebb83d5 100644 --- a/worker/src/support-access.test.ts +++ b/worker/src/support-access.test.ts @@ -3,9 +3,11 @@ import { createRoleStore } from '@pegma/authorization-storage'; import type { PrincipalId } from '@pegma/spine'; import { createMemoryStore } from '@pegma/storage-core'; import { supportPermissions } from '@pegma/support-desk-application'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; import { describe, expect, it } from 'vitest'; import { ADMIN_ROLE, + AGENT_KNOWLEDGE_PERMISSIONS, APPLICATION_SCOPE, AUTHORIZATION_APPLICATION_ID, customerAccessContext, @@ -31,6 +33,10 @@ const staffPermissions = [ supportPermissions.manage, supportPermissions.auditRead, supportPermissions.takeOver, + supportPermissions.learningRead, + supportPermissions.learningEvidenceSubmit, + supportPermissions.learningReview, + supportPermissions.learningWithdraw, ]; function roleStore() { @@ -92,6 +98,10 @@ describe('Support human-control grants', () => { ); expect(access.permissions).not.toContain(supportPermissions.queueRead); expect(access.permissions).not.toContain(supportPermissions.takeOver); + for (const permission of [supportPermissions.learningRead, supportPermissions.learningEvidenceSubmit, + supportPermissions.learningReview, supportPermissions.learningWithdraw, supportPermissions.learningProcess]) { + expect(access.permissions).not.toContain(permission); + } expect(await staffAccessContextFromRoles(operator, store)).toBeNull(); await grantRole(store, SUPPORT_ROLE); @@ -102,6 +112,7 @@ describe('Support human-control grants', () => { .filter((permission) => permission.startsWith('support.')) .sort(), ).toEqual([...customerPermissions, ...staffPermissions].sort()); + expect(staff?.permissions).not.toContain(supportPermissions.learningProcess); const current = await store.getRoleAssignment( `synthetic-${SUPPORT_ROLE}`, @@ -126,4 +137,23 @@ describe('Support human-control grants', () => { ); }, ); + + it('keeps human learning separate from KB powers and the exact three delegated client scopes', async () => { + const store = roleStore(); + await grantRole(store, SUPPORT_ROLE); + const staff = await staffAccessContextFromRoles(operator, store); + expect(staff).not.toBeNull(); + for (const permission of [knowledgePermissions.draftRead, knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, knowledgePermissions.provenanceRead, knowledgePermissions.review, + knowledgePermissions.publish, supportPermissions.learningProcess]) { + expect(staff?.permissions).not.toContain(permission); + } + expect([...AGENT_KNOWLEDGE_PERMISSIONS]).toEqual([ + knowledgePermissions.draftRead, knowledgePermissions.draftWrite, knowledgePermissions.evidenceSubmit, + ]); + for (const permission of [supportPermissions.learningRead, supportPermissions.learningEvidenceSubmit, + supportPermissions.learningReview, supportPermissions.learningWithdraw, supportPermissions.learningProcess]) { + expect(AGENT_KNOWLEDGE_PERMISSIONS).not.toContain(permission); + } + }); }); diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts index 16d99ca..33e7091 100644 --- a/worker/src/support-access.ts +++ b/worker/src/support-access.ts @@ -27,6 +27,10 @@ export const SUPPORT_STAFF_PERMISSIONS = Object.freeze([ supportPermissions.manage, supportPermissions.auditRead, supportPermissions.takeOver, + supportPermissions.learningRead, + supportPermissions.learningEvidenceSubmit, + supportPermissions.learningReview, + supportPermissions.learningWithdraw, ] as const); /** The support-operator role name (docs/ROLE_ADOPTION_PLAN.md). */ @@ -103,10 +107,11 @@ export const APPLICATION_SCOPE = Object.freeze({ * with the Phase 5 surface. Version 3 adds Knowledge Base permissions and * administrator-only agent linking without replacing any stored assignment. * Version 4 adds owned human requests and explicit Support takeover. + * Version 5 adds human learning review; processing and KB grants stay separate. */ export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({ schemaVersion: 1, - version: 'pegma.dev-policy-4', + version: 'pegma.dev-policy-5', defaults: [...SUPPORT_CUSTOMER_PERMISSIONS, knowledgePermissions.articleRead], roles: Object.freeze({ [SUPPORT_ROLE]: [...SUPPORT_STAFF_PERMISSIONS], diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index 3e38c45..ee56431 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -65,6 +65,10 @@ import { supportHumanBrowser, type SupportHumanCoordinates, } from './support-human-auth'; +import { + createSupportLearningBrowserHandlers, + type SupportLearningRuntimeOptions, +} from './support-learning'; import { SUPPORT_BROWSER_COMMAND_HEADER, supportBrowserCommand, @@ -80,6 +84,11 @@ const PERSON_PATH = const HUMAN_STAFF_PATH = /^\/api\/support\/admin\/tickets\/([A-Za-z0-9._~-]{1,200})\/(take-over|handoff)$/u; +// Own this namespace before legacy browser-command routing, including unknown +// learning subpaths. Disabled composition is indistinguishable from absence. +const LEARNING_NAMESPACE = + /^\/api\/support\/admin\/tickets\/[A-Za-z0-9._~-]{1,200}\/learning(?:\/|$)/u; + const TICKET_STATUSES = new Set([ 'open', 'waiting_on_support', @@ -122,6 +131,14 @@ interface SupportApiOptions { readonly roleStore?: SupportRoleReader & BootstrapRoleStore; /** One-time Support bootstrap principals (Phase 3). */ readonly bootstrapPrincipals?: ReadonlySet; + /** Trusted optional composition: construct createSupportLearningHandlers in the host. */ + readonly learningHandler?: (request: Request) => Promise; + /** Trusted runtime ports; the API owns actual browser/staff resolution. */ + readonly learningRuntime?: Omit; + /** Current server flag. Only strict true plus a handler enables this surface. */ + readonly learningEnabled?: () => boolean; + /** Additive trusted staged-review capability; it never enables learning itself. */ + readonly learningStagedReviewsEnabled?: () => boolean; } async function requireAuthentication( @@ -736,10 +753,42 @@ async function stableBrowserMutation( export function createSupportApi( options: SupportApiOptions, ): (request: Request) => Promise { + if (options.learningHandler !== undefined && options.learningRuntime !== undefined) + throw new TypeError('Choose one trusted Support learning composition'); + const learningHandler = options.learningHandler ?? ( + options.learningRuntime !== undefined && options.roleStore !== undefined + ? createSupportLearningBrowserHandlers({ + identity: options.identity, sessions: options.sessions, + identityLinkFromClaims: options.identityLinkFromClaims, + logger: options.logger, roleStore: options.roleStore, + ...(options.learningEnabled === undefined ? {} : { enabled: options.learningEnabled }), + limiter: options.replyLimiter, + learning: options.learningRuntime, + }) + : undefined + ); + const learningReady = (): boolean => { + if (typeof learningHandler !== 'function' || typeof options.learningEnabled !== 'function') return false; + try { return options.learningEnabled() === true; } catch { return false; } + }; + const stagedReviewsReady = (): boolean => { + if (!learningReady() || options.learningRuntime?.stagedReviews === undefined) return false; + try { return options.learningStagedReviewsEnabled?.() === true && + options.learningRuntime.stagedReviews.enabled() === true; } catch { return false; } + }; return async (request) => { const url = new URL(request.url); const path = url.pathname; try { + if (LEARNING_NAMESPACE.test(path)) { + if (!learningReady()) throw new ApiError(404, 'not_found'); + let response: Response | null; + try { response = await learningHandler!(request); } + catch { throw new ApiError(503, 'support_learning_unavailable'); } + // A flag change may withhold an ACK; the browser retains its exact packet. + if (!learningReady() || response === null) throw new ApiError(404, 'not_found'); + return response; + } if (supportBrowserCommandMode(request)) return await stableBrowserMutation(request, options); const person = PERSON_PATH.exec(path); @@ -901,6 +950,40 @@ export function createSupportApi( request.method === 'GET' ) { const ticketId = adminMatch[1]!; + if (typeof options.learningEnabled === 'function') { + // This optional hint comes from current real stored Support authority, + // active Identity and the same live session, never browser role fields. + const browser = supportHumanBrowser(request, { + sessions: options.sessions, + authenticate: (incoming) => requireAuthentication(incoming, options), + access: (authenticated) => humanAccess(authenticated, options, true), + permission: supportPermissions.queueRead, + mutation: false, + }); + try { + const initial = await browser.current(); + const view = await options.application.readStaffTicket(initial.access, ticketId); + const final = await browser.current(); + return json({ + ...staffTicketView(view), + csrfToken: final.authenticated.csrfToken, + learningEnabled: learningReady() && hasPermission(final.access, supportPermissions.learningRead), + learningReviewRecoveryEnabled: learningReady() && + hasPermission(final.access, supportPermissions.learningReview) && + hasPermission(final.access, supportPermissions.queueRead), + ...(options.learningStagedReviewsEnabled === undefined ? {} : { + learningStagedReviewEnabled: stagedReviewsReady() && + hasPermission(final.access, supportPermissions.learningReview) && + hasPermission(final.access, supportPermissions.queueRead), + }), + }); + } catch (error) { + // A raced loss of current access wins over an earlier failed read. + await browser.current(); + throw error; + } + } + // Preserve the legacy detail contract when no capability callback exists. const authenticated = await requireAuthentication(request, options); const access = await requireStaffAccess(authenticated, options); const view = await options.application.readStaffTicket( diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index 1257a49..4da02fd 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -22,6 +22,7 @@ import { SupportDeskQueueCapacityError, ticketNumbers, type SupportDeskApplication, + type ResolutionLearningOptions, } from '@pegma/support-desk-application'; import { defineTemplate } from '@pegma/support-desk-templates'; import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; @@ -180,6 +181,7 @@ export interface SupportCompositionOptions { readonly clock?: Clock; readonly createLimiter?: DurableRateLimiter; readonly replyLimiter?: DurableRateLimiter; + readonly resolutionLearning?: ResolutionLearningOptions; } export interface SupportRuntime { @@ -324,6 +326,7 @@ export function createSupportRuntime( assistantHandlingEnabled: false, allowedCategories: PEGMA_SUPPORT_CATEGORIES, queueTerminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, + ...(options.resolutionLearning === undefined ? {} : { resolutionLearning: options.resolutionLearning }), }); // Audited role store on the SAME Store, partitioned by this host's diff --git a/worker/src/support-learning-composition.test.ts b/worker/src/support-learning-composition.test.ts new file mode 100644 index 0000000..89602bd --- /dev/null +++ b/worker/src/support-learning-composition.test.ts @@ -0,0 +1,184 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { createMemoryStore } from '@pegma/storage-core'; +import { supportRecords } from '@pegma/support-desk-application'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import { describe, expect, it } from 'vitest'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; +import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance'; +import { + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, + KNOWLEDGE_ROLE, + SUPPORT_ROLE, + customerAccessContext, +} from './support-access'; +import { + createSupportLearningFixture, + learningCanary, + learningTicketId, +} from './support-learning-fixtures'; + +/** All domain state is admitted through the existing public SDK fixture. */ +async function fixture() { + const store = createMemoryStore(); + const learning = await createSupportLearningFixture(store); + // Use the host's actual customer audience before creating the learned draft. + const preview = await learning.knowledge.previewCollectionPolicy(learning.actors.admin, { + collectionId: 'learning-guides', + uses: { + portal: { enabled: true, audience: { kind: 'permission', permission: knowledgePermissions.articleRead } }, + bot: { enabled: false }, + }, + }); + await learning.knowledge.updateCollectionPolicy(learning.actors.admin, { + ...learning.command('host-audience', preview.generation), collectionId: 'learning-guides', preview: preview.preview, + }); + await learning.enrollAndVerify(); + const delivered = await learning.delivered(); + await learning.review(delivered.articleId); + await learning.evidenceAndPublish(delivered.articleId); + + const logger = { log() {} }; + const identityRuntime = createIdentityRuntime({ store, + emailCodeSecretBase64: btoa('c'.repeat(32)), emailFrom: 'Pegma ', emailEnabled: false, + }, logger); + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const cookies = new Map(); + const principals = [learning.actors.staff.principalId, learning.actors.customer.principalId, 'synthetic-learning-unrelated']; + for (const [index, principalId] of principals.entries()) { + await identityRuntime.identity.provisionVerifiedUser({ principalId, email: `composition-${index}@example.test` }); + const sessionId = String(index + 1).repeat(43); + await identityRuntime.sessions.create(sessionId, { principalId, data: JSON.stringify({ version: 1, + csrfToken: 'c'.repeat(43), issuer: IDENTITY_ISSUER, subject: principalId }) }); + cookies.set(principalId, SESSION_COOKIE + '=' + sessionId); + } + for (const role of [SUPPORT_ROLE, KNOWLEDGE_ROLE]) { + const granted = await roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'learning-composition-' + role, principalId: learning.actors.staff.principalId, + role, scope: APPLICATION_SCOPE, grantedBy: { kind: 'system', systemId: 'synthetic-learning-composition' }, + grantedAtEpochMs: Date.parse(learning.clock.now()), status: 'active', + }, auditEventId: 'learning-composition-grant-' + role }); + expect(granted.status).toBe('granted'); + } + const options = { store, clock: learning.clock, logger, sessions: identityRuntime.sessions, + identity: identityRuntime.identity, roleStore, identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + agentAccess: null, isEnabled: () => true }; + const runtime = createKnowledgeRuntime({ ...options, privateSources: learning.sources }); + const absent = createKnowledgeRuntime(options); + const projection = { store, clock: learning.clock, logger, isEnabled: () => true, privateSources: learning.sources }; + const ready = createKnowledgeRetrievalReady(projection); + const physical = createKnowledgeRetrievalMaintenance(projection); + const articleId = delivered.articleId; + const input = { collectionId: 'learning-guides', query: 'workspace export', applicability: learning.product }; + const search = () => runtime.application.searchPublishedArticles(learning.actors.customer, input); + async function request(operation: string, principalId = learning.actors.customer.principalId, staff = false) { + const response = await runtime.handle(new Request(IDENTITY_ISSUER + + (staff ? '/api/staff/knowledge/command' : '/api/knowledge/portal'), { + method: 'POST', headers: { Cookie: cookies.get(principalId) ?? '', Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', 'Content-Type': 'application/json', 'X-Pegma-CSRF': 'c'.repeat(43) }, + body: JSON.stringify({ operation, input: { articleId } }), + })); + if (response === null) throw new Error('Expected the real Knowledge HTTP route'); + return response; + } + return { learning, runtime, absent, ready, physical, articleId, search, request, principals }; +} + +type CompositionFixture = Awaited>; +type Worker = 'ready' | 'physical'; + +async function converge(f: CompositionFixture, worker: Worker, indexed: boolean) { + if (worker === 'ready') await f.ready.enqueue(f.articleId); + // Full physical cycles include immutable rows; one row/step is still used per call. + for (let tick = 0; tick < 512; tick++) { + if (worker === 'ready') await f.ready.runPage(); + else await f.physical.runPage(); + const status = await f.runtime.application.getArticleIndexStatus(f.learning.actors.admin, { articleId: f.articleId }); + if (status.status === 'ready' && status.indexed === indexed) return; + } + throw new Error(`The actual ${worker} worker did not converge to indexed=${indexed}`); +} + +function expectPublic(value: unknown) { + const encoded = JSON.stringify(value); + for (const privateValue of [learningCanary, learningTicketId, 'pegma.support-desk', + 'SYNTHETIC_PRIVATE_VERIFICATION', 'synthetic-independent-learning-check']) { + expect(encoded).not.toContain(privateValue); + } +} + +describe('support learning verifier host composition', () => { + it('uses the actual request verifier and keeps private provenance unavailable to another actor', async () => { + const f = await fixture(); + const input = { articleId: f.articleId }; + await expect(f.absent.application.getPublishedArticle(f.learning.actors.customer, input)).rejects.toThrow(); + const accepted = await f.request('getPublishedArticle'); + expect(accepted.status).toBe(200); + expect(await accepted.json()).toMatchObject({ articleId: f.articleId, title: 'Export your workspace' }); + const own = await f.request('getProvenance', f.learning.actors.staff.principalId, true); + expect(own.status).toBe(200); + const provenance: unknown = await own.json(); + expect(JSON.stringify(provenance)).toContain('pegma.support-desk'); + expect(JSON.stringify(provenance)).toContain(learningTicketId); + for (const principalId of [f.learning.actors.customer.principalId, 'synthetic-learning-unrelated']) { + const denied = await f.request('getProvenance', principalId, true); + expect(denied.status).toBe(403); + expect(await denied.json()).toEqual({ error: 'forbidden' }); + await expect(f.learning.application.readStaffTicket( + customerAccessContext(principalId), learningTicketId, + )).rejects.toThrow(); + const publicView = await f.request('getPublishedArticle', principalId); + expect(publicView.status).toBe(200); + expectPublic(await publicView.json()); + } + }); + + for (const worker of ['ready', 'physical'] as const) { + for (const change of ['reopen', 'withdraw', 'missing-ticket'] as const) { + it(`${worker} propagates current source eligibility through indexing and ${change}`, async () => { + const f = await fixture(); + expect(await f.search()).toEqual({ outcome: 'no_result', articles: [] }); + await converge(f, worker, true); + const visible = await f.search(); + expect(visible.outcome).toBe('results'); + expect(visible.articles.map((article) => article.articleId)).toEqual([f.articleId]); + expectPublic(visible); + expect((await f.request('getPublishedArticle')).status).toBe(200); + + if (change === 'reopen') { + await f.learning.application.reopenTicket(f.learning.actors.staff, { + ...f.learning.command('composition-reopen'), ticketId: learningTicketId, + }); + expect((await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId)).state).toBe('held'); + } else if (change === 'withdraw') { + const withdrawn = await f.learning.runtime.withdraw(f.learning.actors.staff, { + ticketId: learningTicketId, clientCommandId: 'composition-withdraw', reason: 'privacy_withdrawal', + }); + expect(withdrawn.state).toBe('withdrawn'); + } else { + // Missing-source storage case: remove only the real SDK-created ticket. + // This is not a claim that a host-wide data-erasure procedure ran. + const records = f.learning.store.collection(supportRecords); + const ticket = (await records.list(learningTicketId)).find((row) => row.kind === 'ticket'); + if (ticket === undefined) throw new Error('Actual source ticket absent before deletion'); + expect(await records.delete(supportRecords.key(ticket))).toBe(true); + await expect(f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId)).rejects.toThrow(); + } + + // A stale posting cannot override the current source even before repair. + expect((await f.request('getPublishedArticle')).status).toBe(404); + expect(await f.search()).toEqual({ outcome: 'no_result', articles: [] }); + await converge(f, worker, false); + expect(await f.search()).toEqual({ outcome: 'no_result', articles: [] }); + const denied = await f.request('getProvenance', 'synthetic-learning-unrelated', true); + expect(denied.status).toBe(403); + expectPublic(await denied.json()); + expect(f.learning.state.modelCalls).toBe(1); + }); + } + } +}); diff --git a/worker/src/support-learning-fixtures.ts b/worker/src/support-learning-fixtures.ts new file mode 100644 index 0000000..23e4cfe --- /dev/null +++ b/worker/src/support-learning-fixtures.ts @@ -0,0 +1,364 @@ +import { hasPermission, resolveAccess, type AccessContext } from '@pegma/authorization-core'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { + createKnowledgeBaseApplication, + createKnowledgeEvidenceReports, + type KnowledgeBaseApplication, +} from '@pegma/knowledge-base-application'; +import { articleKinds, knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import type { EvidenceSubmission } from '@pegma/knowledge-base-core'; +import type { Store } from '@pegma/storage-core'; +import { + learningTargetBinding, + type LearningChecksPort, + type LearningModelInput, + type LearningModelPort, + type VerifiedLearningConfiguration, +} from '@pegma/support-desk-ai'; +import { + createSupportDeskApplication, + supportPermissions, + supportRecords, + type ResolutionLearningChecksBinding, +} from '@pegma/support-desk-application'; +import { isDeepStrictEqual } from 'node:util'; +import { KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION } from './support-access'; +import { + createSupportLearningRuntime, + createSupportLearningSourceBridge, + supportLearningApplicationOptions, + type LearningVerifiedFixPacket, +} from './support-learning'; +import type { DirectLearningKnowledge, SupportLearningProcessingPorts } from './support-learning-ports'; + +export const learningCanary = 'SYNTHETIC_PRIVATE_LEARNING_NOTE'; +export const learningTicketId = 'learning-ticket'; +const collectionId = 'learning-guides'; +const audience = 'fixture.learning.audience'; +const scope = { kind: 'application' } as const; +const principalIds = { + admin: 'fixture-learning-admin', + staff: 'fixture-learning-staff', + runner: 'fixture-learning-runner', + supportService: 'fixture-learning-support-service', + knowledgeService: 'fixture-learning-draft-service', + retirementService: 'fixture-learning-retirement-service', + customer: 'fixture-learning-customer', +} as const; +type Actor = keyof typeof principalIds; + +/** Actual audited role assignments are read again for every authority resolve. */ +export async function createSupportLearningFixture( + store: Store, + options: { readonly intake?: boolean; readonly processing?: boolean; readonly stagedReviews?: boolean; + readonly readScheduling?: 'sdk'; readonly beforeSourceRead?: (ticketId: string) => void | Promise } = {}, +) { + let milliseconds = Date.parse('2026-11-10T12:00:00.000Z'); + const clock = { now: () => new Date(milliseconds).toISOString() }; + let ordinal = 0; + const command = (label: string, expectedGeneration = 0) => ({ + commandId: `fixture-learning-${label}-${++ordinal}`, + correlationId: 'fixture-learning', + expectedGeneration, + }); + const sourceRead = [supportPermissions.learningRead, supportPermissions.queueRead]; + const rolePermissions: Record = { + admin: [...Object.values(knowledgePermissions), ...Object.values(supportPermissions), audience, KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION], + staff: [...sourceRead, supportPermissions.learningEvidenceSubmit, supportPermissions.learningReview, + supportPermissions.learningWithdraw, supportPermissions.replyAny, supportPermissions.note, + supportPermissions.manage, knowledgePermissions.collectionRead, knowledgePermissions.articleRead, + knowledgePermissions.draftRead, knowledgePermissions.draftWrite, knowledgePermissions.provenanceRead, + knowledgePermissions.evidenceRead, knowledgePermissions.evidenceSubmit, knowledgePermissions.review, + knowledgePermissions.reviewSubmit, knowledgePermissions.publish, KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION], + runner: [...sourceRead, knowledgePermissions.collectionRead, knowledgePermissions.draftRead, + knowledgePermissions.provenanceRead, knowledgePermissions.evidenceSubmit, knowledgePermissions.reviewSubmit], + supportService: [...sourceRead, supportPermissions.learningProcess], + knowledgeService: [...sourceRead, knowledgePermissions.collectionRead, knowledgePermissions.articleRead, + knowledgePermissions.draftRead, knowledgePermissions.draftWrite, knowledgePermissions.provenanceRead, + knowledgePermissions.provenanceWrite, audience], + retirementService: [...sourceRead, supportPermissions.learningProcess, + knowledgePermissions.collectionRead, knowledgePermissions.draftRead, + knowledgePermissions.provenanceRead, knowledgePermissions.retire], + customer: [supportPermissions.create, supportPermissions.readOwn, supportPermissions.replyOwn, + knowledgePermissions.articleRead, audience], + }; + const policy = { version: 'synthetic-learning-fixture-v1', roles: rolePermissions }; + const roles = createRoleStore(store, 'pegma-learning-fixture'); + for (const actor of Object.keys(principalIds) as Actor[]) { + const result = await roles.grantRoleAssignmentWithAudit({ + assignment: { + id: `fixture-learning-role-${actor}`, principalId: principalIds[actor], role: actor, + scope, grantedBy: { kind: 'system', systemId: 'synthetic-learning-fixture' }, + grantedAtEpochMs: milliseconds, status: 'active', + }, + auditEventId: `fixture-learning-role-grant-${actor}`, + }); + if (result.status !== 'granted') throw new Error('Synthetic role grant failed'); + } + async function resolve(principalId: string): Promise { + const assignments = await roles.listActiveRoleAssignments(principalId, scope); + return resolveAccess({ principalId, roles: assignments.map((entry) => entry.role) }, policy); + } + const actors = { + admin: await resolve(principalIds.admin), staff: await resolve(principalIds.staff), + runner: await resolve(principalIds.runner), customer: await resolve(principalIds.customer), + }; + const state = { + enabled: options.processing ?? true, + product: 'ready' as 'ready' | 'missing' | 'expired', + check: 'checked' as 'checked' | 'held', + checkReadable: true, + explicitDraftIds: [] as string[], + modelCalls: 0, + modelInputs: [] as LearningModelInput[], + beforeModelReturn: undefined as (() => Promise) | undefined, + beforeStaffResolve: undefined as (() => Promise) | undefined, + }; + const product = { productId: 'synthetic-workspace', productVersion: '1.0.0', buildId: 'synthetic-build-1' }; + const candidate = { + problem: 'Export a workspace.', + applicability: { productId: product.productId, version: product.productVersion, buildId: product.buildId }, + steps: ['Open Workspace.', 'Choose Export.'], + solution: 'Download and verify the workspace export.', + validationRequirements: ['Verify the exported file opens.'], + }; + const policyStamp = { + version: 'synthetic-learning-check-policy-v1', binding: 'synthetic-independent-learning-checks', + verifiedAt: clock.now(), validUntil: new Date(milliseconds + 3_600_000).toISOString(), + }; + const checkReceipts = new Map(); + const checks: LearningChecksPort = { + async resolvePolicy(expected) { + return expected !== undefined && expected !== policyStamp.version + ? { outcome: 'unavailable' } : { outcome: 'ready', policy: structuredClone(policyStamp) }; + }, + async check(input) { + if (state.check !== 'checked') return { outcome: 'held' }; + const receipt = `synthetic-independent-learning-check-${++ordinal}`; + checkReceipts.set(receipt, structuredClone(input.binding)); + return { outcome: 'checked', receipt }; + }, + async verify(receipt, binding) { + if (!state.checkReadable || !isDeepStrictEqual(checkReceipts.get(receipt), binding)) return null; + return { + binding: structuredClone(binding), privacy: 'passed', factual: 'passed', applicability: 'passed', duplication: 'passed', + verifierReceiptId: receipt, verifierVersion: 'synthetic-independent-checker-v1', + verifiedAt: clock.now(), validUntil: policyStamp.validUntil, + }; + }, + }; + const application = createSupportDeskApplication({ + store, clock, + resolutionLearning: supportLearningApplicationOptions({ + enabled: options.intake ?? true, + ...(options.stagedReviews === true ? { stagedReviews: true } : {}), + checks, + productContext: { + async resolve(context) { + if (state.product === 'missing') return null; + return { + productId: product.productId, version: product.productVersion, buildId: product.buildId, + binding: 'synthetic-workspace-build-1', contextVersion: 'synthetic-product-context-v1', + receiptId: `synthetic-product-${context.ticketId}-${context.resolutionCycle}`, + verifiedAt: context.acceptedAt, + validUntil: new Date(Date.parse(context.acceptedAt) + (state.product === 'expired' ? -1 : 60_000)).toISOString(), + }; + }, + }, + }), + }); + const serviceAccess: SupportLearningProcessingPorts['serviceAccess'] = { + async resolve() { + return { outcome: 'ready', authority: { + access: await resolve(principalIds.supportService), authorityVersion: 'synthetic-support-authority-v1', + usageScopeRef: 'synthetic-learning-only-usage', + } }; + }, + }; + const sourceApplication = options.beforeSourceRead === undefined ? application : { + ...application, + async readResolutionLearningSource(...args: Parameters) { + await options.beforeSourceRead?.(args[1]); + return application.readResolutionLearningSource(...args); + }, + }; + const sources = createSupportLearningSourceBridge({ application: sourceApplication, serviceAccess, reviewPolicy: checks, clock, + ...(options.readScheduling === undefined ? {} : { readScheduling: options.readScheduling }) }); + let knowledge: KnowledgeBaseApplication; + const reports = createKnowledgeEvidenceReports({ + store, clock, collectionName: 'synthetic-support-learning-reports.v1', + confirmationPermission: KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + resolvePrincipal: resolve, + async readContext(access, articleId) { + const result = await knowledge.getAuthoringContext(access, { + articleId, includeEvidence: hasPermission(access, knowledgePermissions.evidenceRead), + }); + return result.context; + }, + }); + knowledge = createKnowledgeBaseApplication({ store, clock, privateSources: sources, evidenceVerifier: reports.verifier }); + const configuration: VerifiedLearningConfiguration = { + purpose: 'support_learning', version: 'synthetic-learning-config-v1', promptVersion: 'synthetic-learning-prompt-v1', + modelVersion: 'synthetic-learning-model-v1', provider: 'synthetic-learning-provider', model: 'synthetic-learning-model', + pricingRef: 'synthetic-learning-pricing', trustedInstructions: 'Generalize the visible verified solution.', framingTokens: 20, + budgets: { maxMessages: 20, maxInputBytes: 32_768, maxInputTokens: 32_768, maxContextTokens: 65_536, + maxOutputBytes: 16_000, maxOutputTokens: 8_192, maxCandidateBytes: 16_000, maxDurationMilliseconds: 5_000, + maxCostMicros: 10_000, currency: 'USD', maxAttempts: 2 }, + dataControls: { status: 'verified', purpose: 'support_learning', configurationBinding: 'synthetic-learning-config-v1', + accountRef: 'synthetic-account', projectRef: 'synthetic-project', endpointRef: 'synthetic-endpoint', + modelRef: 'synthetic-model', featuresRef: 'synthetic-features', exceptionsRef: 'synthetic-exceptions', intermediaryRefs: [], + verifiedAt: clock.now(), validUntil: new Date(milliseconds + 3_600_000).toISOString() }, + }; + let generate: LearningModelPort['generate'] = async (input) => { + state.modelCalls += 1; state.modelInputs.push(structuredClone(input)); + await state.beforeModelReturn?.(); + return { outputJson: JSON.stringify(candidate), provider: configuration.provider, model: configuration.model, + requestId: 'synthetic-learning-request', usage: { inputTokens: 100, outputTokens: 50, costMicros: 10, currency: 'USD' } }; + }; + const ports: SupportLearningProcessingPorts = { + serviceAccess, + knowledgeAccess: { async resolve() { return { outcome: 'ready', authority: { + access: await resolve(principalIds.knowledgeService), authorityVersion: 'synthetic-draft-authority-v1' } }; } }, + retirementAccess: { async resolve() { return { outcome: 'ready', authority: { + access: await resolve(principalIds.retirementService), authorityVersion: 'synthetic-retirement-authority-v1' } }; } }, + configuration: { async resolve() { return { outcome: 'ready', configuration: structuredClone(configuration) }; } }, + checks, + model: { generate: (...args) => generate(...args) }, + usage: { async reserve(context) { return { outcome: 'reserved', usageReservationId: context.usageReservationId }; }, + async reconcile() { return 'reconciled'; } }, + tokenCounter: { count: (text) => new TextEncoder().encode(text).byteLength }, + targets: { + async resolveScope() { + return { outcome: 'ready', scope: { version: 'synthetic-learning-target-v1', collectionId, + kind: 'explanation', searchQuery: 'workspace export', explicitDraftIds: [...state.explicitDraftIds] } }; + }, + async select(input) { + return { outcome: 'selected', operation: 'create', articleId: input.newArticleId, + draft: { kind: 'explanation', title: 'Export your workspace', summary: 'Download and verify an export.', + content: { format: 'plain_text', text: [input.candidate.problem, ...input.candidate.steps, + input.candidate.solution, ...input.candidate.validationRequirements].join('\n\n') }, + tags: ['export'], applicability: product } }; + }, + }, + }; + let directKnowledge: DirectLearningKnowledge = knowledge; + const runtimeFor = () => createSupportLearningRuntime({ + application, knowledge: directKnowledge, sources, clock, ports, + processingEnabled: () => state.enabled, + ...(options.readScheduling === undefined ? {} : { readScheduling: options.readScheduling }), + staffAccess: { async resolve(id) { await state.beforeStaffResolve?.(); return resolve(id); } }, + }); + let runtime = runtimeFor(); + await knowledge.createCollection(actors.admin, { ...command('collection'), collectionId, name: 'Synthetic learned guides' }); + const validation = { id: 'synthetic-learning-validation', version: 1, + requirements: [...articleKinds.map((kind) => ({ id: `${kind}-content`, kind, testKind: 'content' as const, + maxAgeMilliseconds: 3_600_000, trustedRunnerIds: [principalIds.runner] })), + { id: 'walkthrough-workflow', kind: 'walkthrough' as const, testKind: 'workflow' as const, + maxAgeMilliseconds: 3_600_000, trustedRunnerIds: [principalIds.runner] }] }; + await knowledge.putValidationPolicy(actors.admin, { ...command('policy'), policy: validation }); + const collection = await knowledge.getCollection(actors.admin, { collectionId }); + await knowledge.putGovernanceConfiguration(actors.admin, { ...command('governance', collection.generation), collectionId, + configuration: { validationPolicy: { id: validation.id, version: 1 }, expectedStagingBuildId: product.buildId, + trustedAttesterIds: [principalIds.staff] } }); + const preview = await knowledge.previewCollectionPolicy(actors.admin, { collectionId, + uses: { portal: { enabled: true, audience: { kind: 'permission', permission: audience } }, + bot: { enabled: true, audience: { kind: 'permission', permission: audience } } } }); + await knowledge.updateCollectionPolicy(actors.admin, { ...command('audience', preview.generation), collectionId, preview: preview.preview }); + + async function terminal() { + // Existing unenrolled ticket: explicit enrollment must not rewrite history. + const oldApplication = createSupportDeskApplication({ store, clock }); + await oldApplication.createCustomerTicket(actors.customer, { ...command('ticket'), ticketId: learningTicketId, + messageId: 'learning-question', subject: 'Synthetic workspace export', body: 'How do I export a workspace?' }); + await oldApplication.replyAsStaff(actors.staff, { ...command('solution'), ticketId: learningTicketId, + messageId: 'learning-solution', body: 'Open Workspace and choose Export.' }); + await oldApplication.addNote(actors.staff, { ...command('note'), ticketId: learningTicketId, + messageId: 'learning-note', body: learningCanary }); + await oldApplication.resolveTicket(actors.staff, { ...command('resolve'), ticketId: learningTicketId }); + return (await oldApplication.readStaffTicket(actors.staff, learningTicketId)).ticket; + } + async function enrollAndVerify(): Promise { + const ticket = await terminal(); + await runtime.enroll(actors.staff, { clientCommandId: 'ENROLL-EXACT-1', ticketId: learningTicketId, expectedRevision: ticket.revision }); + const source = await runtime.readSource(actors.staff, learningTicketId); + const packet: LearningVerifiedFixPacket = { clientCommandId: 'VERIFY-EXACT-1', ticketId: learningTicketId, + expectedRevision: ticket.revision, resolutionCycle: source.resolutionCycle, + evidence: { kind: 'staff_verified_fix', solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_PRIVATE_VERIFICATION' } }; + await runtime.submitVerifiedFix(actors.staff, packet); + return packet; + } + async function process() { + const source = await runtime.readSource(actors.staff, learningTicketId); + return runtime.processWork({ ticketId: learningTicketId, sourceGeneration: source.sourceGeneration, + workerId: 'synthetic-learning-worker', leaseMilliseconds: 30_000 }); + } + async function delivered() { + const generated = await process(); + if (generated.outcome !== 'candidate') throw new Error(`Learning candidate unavailable: ${generated.outcome}`); + const result = await process(); + if (result.outcome !== 'delivered') throw new Error(`Learning draft unavailable: ${result.outcome}`); + const source = await runtime.readSource(actors.staff, learningTicketId); + const work = await runtime.readWork(actors.staff, { ticketId: learningTicketId, sourceGeneration: source.sourceGeneration }); + if (work.target === undefined) throw new Error('Actual delivered target missing'); + return { source, work, articleId: work.target.articleId }; + } + async function review(articleId: string) { + const source = await runtime.readSource(actors.staff, learningTicketId); + const work = await runtime.readWork(actors.staff, { ticketId: learningTicketId, sourceGeneration: source.sourceGeneration }); + const draft = await knowledge.getDraft(actors.staff, { articleId }); + const provenance = await knowledge.getProvenance(actors.staff, { articleId }); + const packet = { clientCommandId: 'REVIEW-EXACT-1', ticketId: learningTicketId, + sourceGeneration: source.sourceGeneration, expectedWorkGeneration: work.workGeneration, + target: await learningTargetBinding(draft.revision, provenance.snapshot), decision: 'approve' as const, + policyVersion: policyStamp.version }; + await runtime.reviewProposal(actors.staff, packet); + return packet; + } + async function evidenceAndPublish(articleId: string) { + const draft = await knowledge.getDraft(actors.runner, { articleId }); + const requirements = await knowledge.getValidationRequirements(actors.runner, { + collectionId, kind: draft.revision.kind, + }); + for (const check of requirements.checks) { + const current = await knowledge.getDraft(actors.runner, { articleId }); + const evidence: EvidenceSubmission = { id: `synthetic-learning-evidence-${++ordinal}`, articleId, + articleRevision: current.revision.number, contentHash: current.revision.contentHash, + validationPolicy: current.revision.validationPolicy, checkId: check.id, testKind: check.testKind, + applicability: current.revision.applicability, stagingBuildId: requirements.expectedStagingBuildId, + steps: ['Open the synthetic workspace.', 'Export and verify the file.'], result: 'passed', executedAt: clock.now(), + runnerId: principalIds.runner, artifacts: [{ id: 'synthetic-export-artifact', hash: 'a'.repeat(64) }] }; + const ledger = await reports.ledger(actors.runner, { articleId }); + const reported = await reports.report(actors.runner, { commandId: `synthetic-report-${ordinal}`, articleId, + ledgerEpoch: ledger.ledgerEpoch, evidence, report: { summary: 'Synthetic export passed', details: 'The exported synthetic fixture opened.' } }); + const key = { articleId, ledgerEpoch: reported.ledgerEpoch, reportId: reported.reportId }; + const viewed = await reports.read(actors.staff, key); + const confirmed = await reports.decide(actors.staff, { ...key, commandId: `synthetic-confirm-${ordinal}`, + expectedReportGeneration: viewed.expectedReportGeneration, reviewBindingHash: viewed.reviewBindingHash }, 'confirmed'); + await knowledge.submitEvidence(actors.runner, { ...command('submit-evidence', current.generation), articleId, + evidence, receipt: confirmed.receipt }); + } + const current = await knowledge.getDraft(actors.runner, { articleId }); + await knowledge.submitForReview(actors.runner, { ...command('submit-review', current.generation), articleId }); + const reviewed = await knowledge.getReview(actors.staff, { articleId }); + await knowledge.publishArticle(actors.staff, { ...command('publish', reviewed.generation), articleId, review: reviewed.review }); + return knowledge.getPublishedArticle(actors.customer, { articleId }); + } + return { + store, clock, application, knowledge, reports, sources, actors, state, ports, product, candidate, command, + get runtime() { return runtime; }, + resolve, terminal, enrollAndVerify, process, delivered, review, evidenceAndPublish, + rows: () => store.collection(supportRecords).list(learningTicketId), + advance: (amount: number) => { milliseconds += amount; }, + setKnowledge(port: DirectLearningKnowledge) { directKnowledge = port; runtime = runtimeFor(); }, + setModel(value: LearningModelPort['generate']) { generate = value; }, + async revokeStaff() { + const role = await roles.getRoleAssignment('fixture-learning-role-staff'); + if (role === null) throw new Error('Synthetic staff role absent'); + return roles.revokeRoleAssignmentWithAudit({ assignmentId: 'fixture-learning-role-staff', + expectedConcurrencyToken: role.concurrencyToken, revokedBy: { kind: 'system', systemId: 'synthetic-learning-fixture' }, + revokedAtEpochMs: milliseconds, auditEventId: 'synthetic-learning-staff-revoke' }); + }, + }; +} + +export type SupportLearningFixture = Awaited>; diff --git a/worker/src/support-learning-handlers.test.ts b/worker/src/support-learning-handlers.test.ts new file mode 100644 index 0000000..c9b467b --- /dev/null +++ b/worker/src/support-learning-handlers.test.ts @@ -0,0 +1,698 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createMemoryStore, type CollectionDefinition, type CollectionStore, type Store } from '@pegma/storage-core'; +import { learningTargetBinding, type LearningReviewIntent } from '@pegma/support-desk-ai'; +import { createSupportDeskApplication, supportPermissions, supportRecords } from '@pegma/support-desk-application'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import { describe, expect, it, vi } from 'vitest'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { + ADMIN_ROLE, APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE, +} from './support-access'; +import { createSupportRuntime } from './support-desk'; +import { controlledHumanBody, humanLatch } from './support-human-control-fixtures'; +import { createSupportLearningRuntime } from './support-learning'; +import { + createSupportLearningFixture, learningCanary, learningTicketId, +} from './support-learning-fixtures'; +import { createSupportLearningHandlers } from './support-learning-handlers'; + +const route = '/api/support/admin/tickets/' + learningTicketId + '/learning'; +const uppercaseCommand = 'ABCDEFAB-1234-4ABC-8DEF-ABCDEF123456'; +type Actor = 'staff' | 'support' | 'knowledge' | 'admin' | 'customer'; + +async function object(response: Response) { + const value: unknown = await response.json(); + if (!isPlainObject(value)) throw new Error('Expected a JSON object'); + return value; +} +function result(value: Record) { + if (!isPlainObject(value.result)) throw new Error('Expected the actual SDK response'); + return value.result; +} +function number(value: unknown) { + if (typeof value !== 'number') throw new Error('Expected a number'); + return value; +} +function text(value: unknown) { + if (typeof value !== 'string') throw new Error('Expected a string'); + return value; +} + +/** Actual Identity, session, audited host roles, limiter and both SDK factories. */ +async function fixture() { + const backing = createMemoryStore(); + const hooks: { commit?: () => Promise; draft?: () => Promise; reviewProof?: () => Promise } = {}; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const actual = backing.collection(definition); + if (definition.name !== supportRecords.name) return actual; + return { ...actual, async transact(partition, actions) { + const value = await actual.transact(partition, actions); + if (value.committed && partition === learningTicketId) await hooks.commit?.(); + return value; + } }; + }, + }; + const learning = await createSupportLearningFixture(store); + const logger = { log() {} }; + const identityRuntime = createIdentityRuntime({ store, + emailCodeSecretBase64: btoa('l'.repeat(32)), emailFrom: 'Pegma ', emailEnabled: false }, logger); + const { identity, sessions } = identityRuntime; + const host = createSupportRuntime({ store, identity, sessions, logger, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }); + const principals = { + staff: learning.actors.staff.principalId, + support: 'synthetic-learning-support-only', knowledge: 'synthetic-learning-knowledge-only', + admin: 'synthetic-learning-admin-only', customer: learning.actors.customer.principalId, + }; + const cookies = new Map(); + const csrf = new Map(); + const sessionIds = new Map(); + for (const [index, actor] of (Object.keys(principals) as Actor[]).entries()) { + const principalId = principals[actor]; + await identity.provisionVerifiedUser({ principalId, email: actor + '@example.test' }); + const sessionId = String(index + 1).repeat(43); + const token = String.fromCharCode(97 + index).repeat(43); + await sessions.create(sessionId, { principalId, data: JSON.stringify({ version: 1, + csrfToken: token, issuer: IDENTITY_ISSUER, subject: principalId }) }); + sessionIds.set(actor, sessionId); cookies.set(actor, SESSION_COOKIE + '=' + sessionId); csrf.set(actor, token); + const roles = actor === 'staff' ? [SUPPORT_ROLE, KNOWLEDGE_ROLE] : actor === 'support' ? [SUPPORT_ROLE] + : actor === 'knowledge' ? [KNOWLEDGE_ROLE] : actor === 'admin' ? [ADMIN_ROLE] : []; + for (const role of roles) await host.roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'learning-http-' + actor + '-' + role, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-learning-http' }, grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'learning-http-grant-' + actor + '-' + role }); + } + const authority = { identity, sessions, logger, roleStore: host.roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }; + const resolve = createAgentPrincipalResolver(authority); + let reviewDepth = 0; + const observedKnowledge = { ...learning.knowledge, async getDraft(...args: Parameters) { + const draft = await learning.knowledge.getDraft(...args); await hooks.draft?.(); + if (reviewDepth > 0) await hooks.reviewProof?.(); + return draft; + } }; + const observedApplication = { ...learning.application, + async reviewResolutionLearningProposal(...args: Parameters) { + reviewDepth += 1; + try { return await learning.application.reviewResolutionLearningProposal(...args); } + finally { reviewDepth -= 1; } + }, + }; + const runtime = createSupportLearningRuntime({ application: observedApplication, knowledge: observedKnowledge, + sources: learning.sources, clock: learning.clock, ports: learning.ports, + staffAccess: { resolve: (principalId) => resolve(principalId) }, processingEnabled: () => learning.state.enabled }); + const state = { enabled: true, runtimeCalls: 0, runtime, captured: [] as string[] }; + const options = { + ...authority, + enabled: () => state.enabled, + runtime: () => { state.runtimeCalls += 1; return state.runtime; }, + limiter: host.replyLimiter, + }; + const handle = createSupportLearningHandlers(options); + function request(operation = '', body?: unknown, actor: Actor = 'staff', query = '') { + const headers: Record = { Cookie: cookies.get(actor)! }; + if (body !== undefined) Object.assign(headers, { Origin: IDENTITY_ISSUER, + 'X-Pegma-CSRF': csrf.get(actor)!, 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' }); + return new Request(IDENTITY_ISSUER + route + (operation === '' ? '' : '/' + operation) + query, + { method: body === undefined ? 'GET' : 'POST', headers, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + } + async function send(input: Request) { + const response = await handle(input); + if (response === null) throw new Error('Expected an owned learning route'); + return response; + } + async function revoke(actor: Actor, role: string) { + const assignmentId = 'learning-http-' + actor + '-' + role; + const row = await host.roleStore.getRoleAssignment(assignmentId); + if (row === null) throw new Error('Missing real role assignment'); + return host.roleStore.revokeRoleAssignmentWithAudit({ assignmentId, expectedConcurrencyToken: row.concurrencyToken, + revokedBy: { kind: 'system', systemId: 'synthetic-learning-http' }, revokedAtEpochMs: Date.now(), + auditEventId: 'learning-http-revoke-' + actor + '-' + role }); + } + async function verified() { + const ticket = await learning.terminal(); + const enrolled = await send(request('enroll', { commandId: uppercaseCommand, expectedRevision: ticket.revision })); + expect(enrolled.status).toBe(200); + const source = result(await object(enrolled)); + const verifiedPacket = { commandId: 'VERIFIED-FIX-EXACT', expectedRevision: ticket.revision, + resolutionCycle: number(source.resolutionCycle), solutionMessageId: 'learning-solution', + verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' }; + const accepted = await send(request('evidence', verifiedPacket)); + expect(accepted.status).toBe(200); + return { ticket, source: result(await object(accepted)), verifiedPacket }; + } + async function proposal() { + await verified(); + const delivered = await learning.delivered(); + const response = await send(request('proposal', undefined, 'staff', '?sourceGeneration=' + delivered.source.sourceGeneration)); + expect(response.status).toBe(200); + const view = result(await object(response)); + return { delivered, view, packet: { commandId: 'REVIEW-EXACT', + intent: view.intent as LearningReviewIntent, decision: 'approve' as const } }; + } + return { learning, host, identity, sessions, principals, cookies, csrf, hooks, state, options, resolve, handle, + request, send, revoke, verified, proposal, + destroy: (actor: Actor) => sessions.destroy(sessionIds.get(actor)!), + }; +} + +/** A well-formed retired HTTP packet, computed from actual SDK coordinates. */ +async function hashOnlyReviewPacket(f: Awaited>) { + const prepared = await f.proposal(); const intent = prepared.packet.intent; + const work = await f.learning.runtime.readWork(f.learning.actors.staff, + { ticketId: learningTicketId, sourceGeneration: intent.sourceGeneration }); + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: intent.target.articleId }); + const provenance = await f.learning.knowledge.getProvenance(f.learning.actors.staff, { articleId: intent.target.articleId }); + // The old HTTP tuple hashes the public binding's insertion order. The new + // immutable intent is a canonical SDK snapshot with different object order. + const target = await learningTargetBinding(draft.revision, provenance.snapshot); + expect(target).toEqual(intent.target); + const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([ + 'pegma.support-learning.review.v1', f.principals.staff, learningTicketId, + intent.sourceGeneration, intent.expectedWorkGeneration, work.sourceBindingHash, target, + [intent.policy.version, intent.policy.binding, intent.policy.verifiedAt, intent.policy.validUntil], + ]))); + const reviewBindingHash = [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); + return { commandId: 'LEGACY-ABCDEFAB-1234-4ABC-8DEF-ABCDEF123456', + sourceGeneration: intent.sourceGeneration, expectedWorkGeneration: intent.expectedWorkGeneration, + reviewBindingHash, decision: 'approve' as const }; +} + +describe('unregistered staff learning HTTP with current public host authority', () => { + it.each(['enroll', 'evidence'] as const)('returns an authenticated future-effect fence for the exact stale %s command', async (operation) => { + const f = await fixture(); const ticket = await f.learning.terminal(); + if (operation === 'evidence') expect((await f.send(f.request('enroll', { commandId: 'SETUP-ENROLL', expectedRevision: ticket.revision }))).status).toBe(200); + const packet = { commandId: 'EXACT-STALE-' + operation.toUpperCase(), expectedRevision: ticket.revision, + ...(operation === 'evidence' ? { resolutionCycle: 1, solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' } : {}) }; + const legacy = createSupportDeskApplication({ store: f.learning.store, clock: f.learning.clock }); + await legacy.addNote(f.learning.actors.staff, { ...f.learning.command('http-intake-revision'), ticketId: learningTicketId, + messageId: 'http-intake-revision-note', body: 'An independent fictional staff edit.' }); + expect((await f.send(f.request(operation, packet))).status).toBe(409); const before = await f.learning.rows(); + const recovered = await f.send(f.request(operation + '-recovery', packet)); expect(recovered.status).toBe(200); + expect(result(await object(recovered))).toEqual({ outcome: 'superseded', ticketId: learningTicketId, commandId: packet.commandId, + operation, expectedRevision: ticket.revision, observedRevision: ticket.revision + 1 }); + expect(await f.learning.rows()).toEqual(before); + const forged = { ...packet, actorId: f.principals.staff }; + expect((await f.send(f.request(operation + '-recovery', forged))).status).toBe(400); + expect((await f.send(f.request(operation + '-recovery', packet, 'admin'))).status).toBe(403); + const csrf = f.request(operation + '-recovery', packet); csrf.headers.delete('X-Pegma-CSRF'); + expect((await f.send(csrf)).status).toBe(403); expect(await f.learning.rows()).toEqual(before); + }); + + it('manual enrollment recovery can apply the still-valid exact original command once', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const packet = { commandId: 'EXACT-VALID-RECOVERY', expectedRevision: ticket.revision }; + const accepted = await f.send(f.request('enroll-recovery', packet)); expect(accepted.status).toBe(200); + const body = result(await object(accepted)); expect(body).toMatchObject({ operation: 'enroll', commandId: packet.commandId, outcome: 'accepted' }); + const rows = await f.learning.rows(); + const repeated = await f.send(f.request('enroll-recovery', packet)); expect(await object(repeated)).toMatchObject({ result: body }); + expect(await f.learning.rows()).toEqual(rows); expect(rows.filter((row) => row.kind === 'resolution_learning_source')).toHaveLength(1); + }); + + it.each(['missing', 'internal', 'unresolved', 'cycle'] as const)('fences a same-revision %s evidence prerequisite with the complete public ticket view', async (kind) => { + const f = await fixture(); let ticket = await f.learning.terminal(); + expect((await f.send(f.request('enroll', { commandId: 'SETUP-CONTENT-FENCE', expectedRevision: ticket.revision }))).status).toBe(200); + if (kind === 'unresolved') { + await f.learning.application.reopenTicket(f.learning.actors.staff, { ...f.learning.command('same-revision-reopen'), ticketId: learningTicketId }); + ticket = (await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId)).ticket; + } + const view = await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId); + expect(view.ticket.revision).toBe(ticket.revision); + expect(view.messages.some((message) => message.id === 'learning-solution' && message.visibility === 'customer')).toBe(true); + expect(view.messages.some((message) => message.id === 'learning-note' && message.visibility === 'internal')).toBe(true); + const solutionRow = (await f.learning.rows()).find((row) => row.kind === 'message' && row.message.id === 'learning-solution'); + if (solutionRow?.kind !== 'message') throw new Error('Expected the genuine SDK solution row'); + expect(solutionRow.ordinal).toBeLessThanOrEqual(ticket.revision); + const packet = { commandId: 'EXACT-CONTENT-FENCE-' + kind.toUpperCase(), expectedRevision: ticket.revision, + resolutionCycle: kind === 'cycle' ? 2 : 1, + solutionMessageId: kind === 'missing' ? 'missing-visible-message' : kind === 'internal' ? 'learning-note' : 'learning-solution', + verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' }; + const before = await f.learning.rows(); + expect((await f.send(f.request('evidence', packet))).status).toBe(409); + const response = await f.send(f.request('evidence-recovery', packet)); + expect(response.status).toBe(200); expect(result(await object(response))).toEqual({ outcome: 'superseded', operation: 'evidence', + ticketId: learningTicketId, commandId: packet.commandId, expectedRevision: ticket.revision, observedRevision: ticket.revision, + fence: kind === 'unresolved' ? 'resolution_unavailable' : kind === 'cycle' ? 'resolution_cycle_changed' : 'solution_unavailable' }); + expect(await f.learning.rows()).toEqual(before); expect(f.learning.state.modelCalls).toBe(0); + }); + + it.each(['logout', 'role', 'outage'] as const)('keeps terminal recovery unavailable after %s at its real ticket observation', async (change) => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const legacy = createSupportDeskApplication({ store: f.learning.store, clock: f.learning.clock }); + await legacy.addNote(f.learning.actors.staff, { ...f.learning.command('http-recovery-role-revision'), ticketId: learningTicketId, + messageId: 'http-recovery-role-note', body: 'A competing fictional note.' }); + f.state.runtime = createSupportLearningRuntime({ application: { ...f.learning.application, + async readStaffTicket(...args) { + const view = await f.learning.application.readStaffTicket(...args); + if (change === 'logout') await f.destroy('staff'); + else if (change === 'role') await f.revoke('staff', SUPPORT_ROLE); + else throw new Error('Fictional private ticket outage'); + return view; + }, + }, knowledge: f.learning.knowledge, sources: f.learning.sources, clock: f.learning.clock, ports: f.learning.ports, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const before = await f.learning.rows(); const response = await f.send(f.request('enroll-recovery', { + commandId: 'EXACT-RECOVERY-GUARD', expectedRevision: ticket.revision })); + expect(response.status).toBe(change === 'logout' ? 401 : change === 'role' ? 403 : 503); + expect(await object(response)).not.toHaveProperty('result'); expect(await f.learning.rows()).toEqual(before); + }); + + it.each(['session', 'knowledge', 'support'] as const)( + 'prevents a full-intent review commit when %s is revoked inside the actual SDK proof', + async (change) => { + const f = await fixture(); + const { packet } = await f.proposal(); + const before = await f.learning.rows(); + const hold = humanLatch(); + let proofReached = false; + let commits = 0; + f.hooks.commit = async () => { commits += 1; }; + f.hooks.reviewProof = async () => { + delete f.hooks.reviewProof; + proofReached = true; + await hold.ready; + }; + const pending = f.send(f.request('review', packet)); + try { + await vi.waitFor(() => expect(proofReached).toBe(true), { timeout: 3_000 }); + if (change === 'session') await f.destroy('staff'); + else await f.revoke('staff', change === 'knowledge' ? KNOWLEDGE_ROLE : SUPPORT_ROLE); + } finally { + hold.release(); + } + const response = await pending; + // The SDK reports a Knowledge-only host guard rejection as unknown. + // Closing browser authority reports session and Support loss directly. + const expectedStatus = { session: 401, knowledge: 503, support: 403 }[change]; + expect(response.status).toBe(expectedStatus); + expect(commits).toBe(0); + expect(await f.learning.rows()).toEqual(before); + expect(before.filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(0); + expect(await object(response)).not.toHaveProperty('result'); + }, + ); + + it('rejects a valid hash-only review packet before invoking the runtime', async () => { + const f = await fixture(); + const packet = await hashOnlyReviewPacket(f); + const before = await f.learning.rows(); + const calls = f.state.runtimeCalls; + const response = await f.send(f.request('review', packet)); + expect(response.status).toBe(400); + expect(await object(response)).toEqual({ error: 'invalid_request' }); + expect(f.state.runtimeCalls).toBe(calls); + expect(await f.learning.rows()).toEqual(before); + }); + + it('requires current Knowledge authority inside a direct legacy runtime mutation even without a browser callback', async () => { + const f = await fixture(); const { packet } = await f.proposal(); const intent = packet.intent; + const access = await f.resolve(f.principals.staff); if (access === null) throw new Error('Expected current staff authority'); + const before = await f.learning.rows(); const hold = humanLatch(); let proofReached = false; let commits = 0; + f.hooks.commit = async () => { commits += 1; }; + f.hooks.reviewProof = async () => { delete f.hooks.reviewProof; proofReached = true; await hold.ready; }; + const pending = f.state.runtime.reviewProposal(access, { ticketId: learningTicketId, + clientCommandId: 'DIRECT-LEGACY-REVIEW-EXACT', sourceGeneration: intent.sourceGeneration, + expectedWorkGeneration: intent.expectedWorkGeneration, target: intent.target, + policyVersion: intent.policy.version, decision: 'approve' }).then(() => 'accepted' as const, () => 'rejected' as const); + try { + await vi.waitFor(() => expect(proofReached).toBe(true), { timeout: 3_000 }); + await f.revoke('staff', KNOWLEDGE_ROLE); + } finally { hold.release(); } + expect(await pending).toBe('rejected'); expect(commits).toBe(0); + expect(await f.learning.rows()).toEqual(before); + }); + + it('recovers the accepted full review through HTTP with the original body after reopening and Knowledge loss', async () => { + const f = await fixture(); + const { packet } = await f.proposal(); + const retained = { ...packet, commandId: uppercaseCommand + '-REVIEW', reason: 'Retain this exact review decision.' }; + const first = f.request('review', retained); + const body = await first.clone().text(); + const original = f.state.runtime; + const observed: { accepted?: Awaited> } = {}; + f.state.runtime = { ...original, async submitReviewIntent(access, input, guard) { + const accepted = await original.submitReviewIntent(access, input, guard); + if (observed.accepted === undefined) { + observed.accepted = accepted; + throw new Error('Synthetic lost committed review ACK'); + } + return accepted; + } }; + expect((await f.send(first)).status).toBe(503); + const accepted = observed.accepted; + if (accepted === undefined) throw new Error('Expected an actual committed review'); + const acceptedRows = await f.learning.rows(); + expect(acceptedRows.filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(1); + + await f.learning.application.reopenTicket(f.learning.actors.staff, + { ...f.learning.command('exact-body-receipt-reopen'), ticketId: learningTicketId }); + const currentSource = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(currentSource).toMatchObject({ + state: 'held', heldReason: 'reopened', sourceGeneration: retained.intent.sourceGeneration + 1, + }); + await f.revoke('staff', KNOWLEDGE_ROLE); + const current = await f.resolve(f.principals.staff); + expect(current?.permissions).toEqual(expect.arrayContaining([supportPermissions.learningReview, supportPermissions.queueRead])); + expect(current?.permissions).not.toContain(knowledgePermissions.draftRead); + expect(current?.permissions).not.toContain(knowledgePermissions.provenanceRead); + f.hooks.draft = async () => { throw new Error('Receipt recovery must not read the obsolete draft'); }; + f.state.runtime = { ...f.state.runtime, + async readSource() { throw new Error('Receipt recovery must not rebuild the source'); }, + async readWork() { throw new Error('Receipt recovery must not rebuild the work'); }, + }; + const before = await f.learning.rows(); + for (const operation of ['review-receipt', 'review', 'review-cancel'] as const) { + const response = await f.send(new Request(f.request(operation, retained), { body })); + expect(response.status).toBe(200); + expect(result(await object(response))).toEqual({ outcome: 'accepted', result: accepted }); + expect(await f.learning.rows()).toEqual(before); + } + expect(f.learning.state.modelCalls).toBe(1); + }); + + it.each(['reopen', 'withdraw', 'draft-edit'] as const)('recovers the exact committed review after %s and actual KB role revocation without stale proposal reads', async (change) => { + const f = await fixture(); const { packet, delivered } = await f.proposal(); + const original = f.state.runtime; let lose = true; + f.state.runtime = { ...original, async submitReviewIntent(access, input, guard) { + const accepted = await original.submitReviewIntent(access, input, guard); + if (lose) { lose = false; throw new Error('Synthetic lost committed review ACK'); } + return accepted; + } }; + expect((await f.send(f.request('review', packet))).status).toBe(503); + if (change === 'reopen') await f.learning.application.reopenTicket(f.learning.actors.staff, + { ...f.learning.command('receipt-after-reopen'), ticketId: learningTicketId }); + else if (change === 'withdraw') await f.learning.runtime.withdraw(f.learning.actors.staff, + { ticketId: learningTicketId, clientCommandId: 'receipt-after-withdraw', reason: 'privacy_withdrawal' }); + else { + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId }); + await f.learning.knowledge.updateDraft(f.learning.actors.staff, + { ...f.learning.command('receipt-after-edit', draft.generation), articleId: delivered.articleId, + collectionId: draft.revision.collectionId, draft: { kind: draft.revision.kind, title: 'New current draft', + summary: draft.revision.summary, content: draft.revision.content, tags: draft.revision.tags, + applicability: draft.revision.applicability } }); + } + await f.revoke('staff', KNOWLEDGE_ROLE); f.learning.state.enabled = false; + f.hooks.draft = async () => { throw new Error('Receipt must not read obsolete KB target'); }; + f.state.runtime = { ...f.state.runtime, async readSource() { throw new Error('No source preflight'); }, + async readWork() { throw new Error('No work preflight'); } }; + const before = await f.learning.rows(); + const receipt = await f.send(f.request('review-receipt', packet)); + expect(receipt.status).toBe(200); expect(result(await object(receipt)).outcome).toBe('accepted'); + expect((await f.send(f.request('review', packet))).status).toBe(200); + expect((await f.send(f.request('review-cancel', packet))).status).toBe(200); + expect(await f.learning.rows()).toEqual(before); expect(f.learning.state.modelCalls).toBe(1); + expect((await f.learning.knowledge.getDraft(f.learning.actors.admin, { articleId: delivered.articleId })).state).toBe('draft'); + }); + + it('recovers a lost real cancellation ACK with the same complete packet and no new review rows', async () => { + const f = await fixture(); const { packet } = await f.proposal(); const original = f.state.runtime; let lose = true; + f.state.runtime = { ...original, async cancelReview(access, input, guard) { + const cancelled = await original.cancelReview(access, input, guard); + if (lose) { lose = false; throw new Error('Synthetic lost committed cancellation ACK'); } + return cancelled; + } }; + expect((await f.send(f.request('review-cancel', packet))).status).toBe(503); + const before = await f.learning.rows(); + expect(before.filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(0); + const receipt = await f.send(f.request('review-receipt', packet)); + expect(receipt.status).toBe(200); + expect(result(await object(receipt))).toEqual({ outcome: 'cancelled', ticketId: learningTicketId, commandId: packet.commandId }); + expect((await f.send(f.request('review-cancel', packet))).status).toBe(200); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect(await f.learning.rows()).toEqual(before); + }); + + it('binds complete policy timestamps on exact HTTP receipt and cancellation recovery', async () => { + const f = await fixture(); const { packet } = await f.proposal(); + expect((await f.send(f.request('review', packet))).status).toBe(200); + const before = await f.learning.rows(); + const changed = { ...packet, intent: { ...packet.intent, policy: { ...packet.intent.policy, + verifiedAt: new Date(Date.parse(packet.intent.policy.verifiedAt) - 1).toISOString() } } }; + expect((await f.send(f.request('review-receipt', changed))).status).toBe(409); + expect((await f.send(f.request('review-cancel', changed))).status).toBe(409); + expect(await f.learning.rows()).toEqual(before); + }); + + it.each(['submit', 'cancel'] as const)('fences the actual %s commit against revocation of the original session', async (action) => { + const f = await fixture(); const { packet } = await f.proposal(); const before = await f.learning.rows(); + if (action === 'submit') f.hooks.draft = async () => { delete f.hooks.draft; await f.destroy('staff'); }; + else { + const original = f.state.runtime; + f.state.runtime = { ...original, async cancelReview(access, input, guard) { + await f.destroy('staff'); return original.cancelReview(access, input, guard); + } }; + } + const response = await f.send(f.request(action === 'submit' ? 'review' : 'review-cancel', packet)); + expect(response.status).toBe(401); expect(await f.learning.rows()).toEqual(before); + expect(JSON.stringify(await object(response))).not.toContain(learningCanary); + }); + + it('defaults OFF before lazy runtime construction and leaves unrelated routes unclaimed', async () => { + const f = await fixture(); + const { enabled, ...options } = f.options; + void enabled; + const handle = createSupportLearningHandlers(options); + const response = await handle(f.request()); + expect(response?.status).toBe(503); + expect(f.state.runtimeCalls).toBe(0); + expect(await handle(new Request(IDENTITY_ISSUER + '/api/support/tickets'))).toBeNull(); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('uses real separate Support/Knowledge grants without granting human process or administrator Support powers', async () => { + const f = await fixture(); + const staff = await f.resolve(f.principals.staff); + const support = await f.resolve(f.principals.support); + const knowledge = await f.resolve(f.principals.knowledge); + const admin = await f.resolve(f.principals.admin); + expect(staff?.permissions).toContain(supportPermissions.learningRead); + expect(staff?.permissions).toContain(knowledgePermissions.draftRead); + expect(support?.permissions).not.toContain(knowledgePermissions.draftRead); + expect(knowledge?.permissions).not.toContain(supportPermissions.learningReview); + expect(admin?.permissions).not.toContain(supportPermissions.learningRead); + expect(staff?.permissions).not.toContain(supportPermissions.learningProcess); + }); + + it('enrolls and records an actual staff-verified fix, preserving uppercase command bytes and exact replay', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const original = f.state.runtime; + f.state.runtime = { ...original, async enroll(access, packet) { + f.state.captured.push(packet.clientCommandId); return original.enroll(access, packet); + } }; + const packet = { commandId: uppercaseCommand, expectedRevision: ticket.revision }; + const first = await object(await f.send(f.request('enroll', packet))); + const rows = await f.learning.rows(); + expect(await object(await f.send(f.request('enroll', packet)))).toEqual(first); + expect(await f.learning.rows()).toEqual(rows); + expect(f.state.captured).toEqual([uppercaseCommand, uppercaseCommand]); + const source = result(first); + const response = await f.send(f.request('evidence', { commandId: 'FIX-EXACT', expectedRevision: ticket.revision, + resolutionCycle: source.resolutionCycle, solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_VERIFIED_FIX' })); + expect(result(await object(response))).toMatchObject({ state: 'eligible', ticketId: learningTicketId }); + const actual = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(actual.evidence).toMatchObject({ kind: 'staff_verified_fix', actorId: f.principals.staff }); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('returns the actual checked private draft, reviews its exact server target and replays a lost ACK without duplicate rows', async () => { + const f = await fixture(); const { packet, delivered, view } = await f.proposal(); + expect(view.draft).toEqual(await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId })); + expect(JSON.stringify(view)).not.toContain(learningCanary); + const original = f.state.runtime; let lose = true; + f.state.runtime = { ...original, async submitReviewIntent(access, input, guard) { + const value = await original.submitReviewIntent(access, input, guard); + if (lose) { lose = false; throw new Error('Synthetic post-commit response loss'); } + return value; + } }; + expect((await f.send(f.request('review', packet))).status).toBe(503); + const rows = await f.learning.rows(); + expect(rows.some((row) => row.kind === 'resolution_learning_review')).toBe(true); + expect((await f.send(f.request('review', packet))).status).toBe(200); + expect(await f.learning.rows()).toEqual(rows); + expect(f.learning.state.modelCalls).toBe(1); + }); + + it('keeps ordinary source/work projections body-free and requires separate KB authority for proposal and review', async () => { + const f = await fixture(); const { packet, delivered } = await f.proposal(); + for (const operation of ['', 'work']) { + const response = await f.send(f.request(operation, undefined, 'support', operation === '' ? '' : '?sourceGeneration=' + delivered.source.sourceGeneration)); + expect(response.status).toBe(200); + const projected = result(await object(response)); + expect(projected).not.toHaveProperty('candidate'); expect(projected).not.toHaveProperty('exactRequest'); + expect(JSON.stringify(projected)).not.toContain('draftPayload'); + expect(JSON.stringify(projected)).not.toContain(learningCanary); + } + const before = await f.learning.rows(); + expect((await f.send(f.request('proposal', undefined, 'support', '?sourceGeneration=' + delivered.source.sourceGeneration))).status).toBe(403); + expect((await f.send(f.request('review', packet, 'support'))).status).toBe(403); + expect(await f.learning.rows()).toEqual(before); + }); + + it.each(['customer', 'knowledge', 'admin'] as const)('denies %s without current Support authority before any private factory call', async (actor) => { + const f = await fixture(); + expect((await f.send(f.request('', undefined, actor))).status).toBe(403); + expect(f.state.runtimeCalls).toBe(0); + }); + + it.each(['Origin', 'Authorization', 'X-Pegma-CSRF', 'Cookie'] as const)('rejects invalid browser %s before enrollment', async (header) => { + const f = await fixture(); const ticket = await f.learning.terminal(); const rows = await f.learning.rows(); + const request = f.request('enroll', { commandId: 'INVALID-BROWSER', expectedRevision: ticket.revision }); + request.headers.set(header, header === 'Origin' ? 'https://foreign.example' : header === 'Authorization' ? 'Bearer synthetic' : 'invalid'); + const response = await f.send(request); + expect([401, 403]).toContain(response.status); + expect(await f.learning.rows()).toEqual(rows); + }); + + it.each([ + { actorId: 'forged' }, { productId: 'forged' }, { buildId: 'forged' }, { verifiedAt: '2026-11-10T12:00:00Z' }, + { provenance: [] }, { correlationId: 'forged' }, + ])('refuses extra authority/proof fields without a write: %j', async (extra) => { + const f = await fixture(); const ticket = await f.learning.terminal(); const rows = await f.learning.rows(); + const response = await f.send(f.request('enroll', { commandId: 'CLOSED-PACKET', expectedRevision: ticket.revision, ...extra })); + expect(response.status).toBe(400); expect(await f.learning.rows()).toEqual(rows); + }); + + it.each(['?sourceGeneration=0', '?sourceGeneration=1&sourceGeneration=1', '?sourceGeneration=9007199254740992', '?sourceGeneration=1&actor=forged'])('bounds the server-validated work key %s', async (query) => { + const f = await fixture(); const rows = await f.learning.rows(); + expect((await f.send(f.request('work', undefined, 'staff', query))).status).toBe(400); + expect(f.state.runtimeCalls).toBe(0); expect(await f.learning.rows()).toEqual(rows); + }); + + it('refuses changed exact command fields instead of silently rebinding a retained command', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const packet = { commandId: uppercaseCommand, expectedRevision: ticket.revision }; + expect((await f.send(f.request('enroll', packet))).status).toBe(200); + const rows = await f.learning.rows(); + expect((await f.send(f.request('enroll', { ...packet, expectedRevision: ticket.revision + 1 }))).status).toBe(409); + expect(await f.learning.rows()).toEqual(rows); + }); + + it('rejects the shown review binding after a real KB draft edit', async () => { + const f = await fixture(); const { packet, delivered } = await f.proposal(); + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId }); + await f.learning.knowledge.updateDraft(f.learning.actors.staff, { ...f.learning.command('http-draft-edit', draft.generation), + articleId: delivered.articleId, collectionId: draft.revision.collectionId, + draft: { kind: draft.revision.kind, title: 'A separately edited guide', summary: draft.revision.summary, + content: draft.revision.content, tags: draft.revision.tags, applicability: draft.revision.applicability } }); + const rows = await f.learning.rows(); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect(await f.learning.rows()).toEqual(rows); + }); + + it('refuses extra review provenance and a changed complete intent', async () => { + const f = await fixture(); const { packet } = await f.proposal(); const rows = await f.learning.rows(); + expect((await f.send(f.request('review', { ...packet, target: { articleId: 'forged' } }))).status).toBe(400); + expect((await f.send(f.request('review', { ...packet, intent: { ...packet.intent, target: { ...packet.intent.target, contentHash: '0'.repeat(64) } } }))).status).toBe(503); + expect(await f.learning.rows()).toEqual(rows); + }); + + it('holds the private review surface when the independent trusted check policy is unavailable', async () => { + const f = await fixture(); const { packet, delivered } = await f.proposal(); const rows = await f.learning.rows(); + f.state.runtime = createSupportLearningRuntime({ application: f.learning.application, knowledge: f.learning.knowledge, + sources: f.learning.sources, clock: f.learning.clock, staffAccess: { resolve: f.resolve }, + ports: { ...f.learning.ports, checks: { ...f.learning.ports.checks, + async resolvePolicy() { return { outcome: 'unavailable' }; } } } }); + const handle = createSupportLearningHandlers(f.options); + const read = await handle(f.request('proposal', undefined, 'staff', '?sourceGeneration=' + delivered.source.sourceGeneration)); + expect(read?.status).toBe(503); + if (read === null) throw new Error('Expected an owned route'); + expect(await object(read)).toEqual({ error: 'support_learning_unavailable' }); + expect((await handle(f.request('review', packet)))?.status).toBe(503); + expect(await f.learning.rows()).toEqual(rows); + }); + + it('retains the actual product-trust hold instead of creating learning work from browser evidence', async () => { + const f = await fixture(); f.learning.state.product = 'missing'; + const { source } = await f.verified(); + expect(source.state).toBe('held'); + expect((await f.learning.rows()).filter((row) => row.kind === 'resolution_learning_work')).toEqual([]); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('enforces packet scalar and existing body-byte bounds before creating a source', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); const rows = await f.learning.rows(); + expect((await f.send(f.request('enroll', { commandId: 'x'.repeat(201), expectedRevision: ticket.revision }))).status).toBe(400); + const oversized = f.request('enroll', { commandId: 'x'.repeat(65_536), expectedRevision: ticket.revision }); + expect((await f.send(oversized)).status).toBe(413); + expect(await f.learning.rows()).toEqual(rows); expect(f.state.runtimeCalls).toBe(0); + }); + + it.each(['logout', 'role', 'header'] as const)('rechecks %s after the bounded request body before any enrollment', async (change) => { + const f = await fixture(); const ticket = await f.learning.terminal(); const rows = await f.learning.rows(); + const body = await controlledHumanBody(f.request('enroll', { commandId: 'BODY-RACE', expectedRevision: ticket.revision })); + const pending = f.send(body.request); + try { + await body.waitFor(pending); + if (change === 'logout') await f.destroy('staff'); + else if (change === 'role') await f.revoke('staff', SUPPORT_ROLE); + else body.request.headers.set('Cookie', f.cookies.get('support')!); + } finally { body.complete(); } + const response = await pending; + expect([401, 403]).toContain(response.status); expect(await f.learning.rows()).toEqual(rows); + }); + + it('withholds a committed SDK enrollment ACK after real role revocation without pretending to roll it back', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + f.hooks.commit = async () => { delete f.hooks.commit; await f.revoke('staff', SUPPORT_ROLE); }; + expect((await f.send(f.request('enroll', { commandId: 'COMMITTED-DENIED', expectedRevision: ticket.revision }))).status).toBe(403); + const source = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(source.ticketId).toBe(learningTicketId); + expect((await f.learning.rows()).some((row) => row.kind === 'resolution_learning_source')).toBe(true); + }); + + it('rechecks current Knowledge authority after an actual private KB read before disclosing the draft', async () => { + const f = await fixture(); await f.verified(); const delivered = await f.learning.delivered(); + f.hooks.draft = async () => { delete f.hooks.draft; await f.revoke('staff', KNOWLEDGE_ROLE); }; + const response = await f.send(f.request('proposal', undefined, 'staff', '?sourceGeneration=' + delivered.source.sourceGeneration)); + expect(response.status).toBe(403); expect(await object(response)).toEqual({ error: 'forbidden' }); + }); + + it.each([false, true])('applies the final original-session fence to read results/failures (throws=%s)', async (fail) => { + const f = await fixture(); await f.verified(); const original = f.state.runtime; + f.state.runtime = { ...original, async readSource(access, ticketId) { + const source = await original.readSource(access, ticketId); + await f.destroy('staff'); + if (fail) throw new Error('SYNTHETIC_PRIVATE_DEPENDENCY_FAILURE'); + return source; + } }; + const response = await f.send(f.request()); + expect(response.status).toBe(401); + expect(JSON.stringify(await object(response))).not.toContain('SYNTHETIC_PRIVATE'); + }); + + it.each(['invalidate', 'withdraw'] as const)('keeps authorized %s available while model generation is OFF', async (operation) => { + const f = await fixture(); await f.verified(); f.learning.state.enabled = false; + const response = await f.send(f.request(operation, { commandId: operation.toUpperCase() + '-EXACT', + reason: operation === 'withdraw' ? 'privacy_withdrawal' : 'evidence_revoked' })); + expect(response.status).toBe(200); + expect(result(await object(response)).state).toBe(operation === 'withdraw' ? 'withdrawn' : 'held'); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('shares an actual durable limiter and returns Retry-After without a private source result', async () => { + const f = await fixture(); + for (let index = 0; index < 30; index += 1) await f.host.replyLimiter.allow(f.principals.staff); + const response = await f.send(f.request()); + expect(response.status).toBe(429); expect(Number(response.headers.get('Retry-After'))).toBeGreaterThan(0); + expect(await object(response)).toEqual({ error: 'rate_limited' }); expect(f.state.runtimeCalls).toBe(0); + }); + + it('uses a finite body deadline and never enrolls from an unfinished body', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); const rows = await f.learning.rows(); + const body = await controlledHumanBody(f.request('enroll', { commandId: 'UNFINISHED', expectedRevision: ticket.revision })); + vi.useFakeTimers(); + const pending = f.send(body.request); + try { + await body.waitFor(pending); + await vi.advanceTimersByTimeAsync(10_001); + expect((await pending).status).toBe(408); + expect(body.cancellations).toBeGreaterThan(0); + expect(await f.learning.rows()).toEqual(rows); + } finally { body.complete(); vi.useRealTimers(); } + }); +}); diff --git a/worker/src/support-learning-handlers.ts b/worker/src/support-learning-handlers.ts new file mode 100644 index 0000000..e07f0b7 --- /dev/null +++ b/worker/src/support-learning-handlers.ts @@ -0,0 +1,295 @@ +import { hasPermission, type AccessContext } from '@pegma/authorization-core'; +import { + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, + RepositoryConflictError, +} from '@pegma/knowledge-base-application'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import type { DurableRateLimiter } from '@pegma/rate-limit'; +import type { LearningReviewIntent } from '@pegma/support-desk-ai'; +import { supportPermissions } from '@pegma/support-desk-application'; +import { + createAgentPrincipalResolver, + type AgentBrowserOptions, +} from './agent-authority'; +import { + ApiError, authenticate, boundedString, enforceRateLimit, exactObject, + json, optionalKeysObject, readJson, +} from './api-auth'; +import { mapSupportError } from './support-desk'; +import { supportHumanBrowser } from './support-human-auth'; +import type { LearningReviewIntentPacket, SupportLearningRuntime } from './support-learning'; + +/** Trusted composition only. This module registers no route or worker. */ +export interface SupportLearningHandlerOptions extends AgentBrowserOptions { + /** Independent of generation: an enabled surface can still withdraw sources. */ + readonly enabled?: () => boolean; + readonly stagedReviewsEnabled?: () => boolean; + readonly runtime: () => SupportLearningRuntime; + /** An existing host durable limiter, not a second admission ledger. */ + readonly limiter: DurableRateLimiter; +} + +type Operation = 'source' | 'work' | 'proposal' | 'enroll' | 'enroll-recovery' | 'evidence' | 'evidence-recovery' | 'review' | 'review-receipt' | 'review-cancel' | 'review-queue' | 'review-queue-status' | 'review-queue-cancel' | 'withdraw' | 'invalidate'; +const path = /^\/api\/support\/admin\/tickets\/([A-Za-z0-9._~-]{1,200})\/learning(?:\/(work|proposal|enroll|enroll-recovery|evidence|evidence-recovery|review|review-receipt|review-cancel|review-queue|review-queue-status|review-queue-cancel|withdraw|invalidate))?$/u; + +function integer(value: unknown, minimum = 1): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum) + throw new ApiError(400, 'invalid_request'); + return value; +} + +function sourceGeneration(url: URL): number { + if (url.searchParams.size !== 1 || url.searchParams.getAll('sourceGeneration').length !== 1) + throw new ApiError(400, 'invalid_request'); + const value = url.searchParams.get('sourceGeneration'); + if (value === null || !/^[1-9][0-9]*$/u.test(value)) + throw new ApiError(400, 'invalid_request'); + return integer(Number(value)); +} + +function operationPermission(operation: Operation): string { + if (operation.startsWith('review')) return supportPermissions.learningReview; + if (operation === 'withdraw') return supportPermissions.learningWithdraw; + if (operation === 'enroll' || operation === 'enroll-recovery' || operation === 'evidence' || operation === 'evidence-recovery' || operation === 'invalidate') + return supportPermissions.learningEvidenceSubmit; + return supportPermissions.learningRead; +} + +function reviewIntent(raw: unknown, ticketId: string): LearningReviewIntent { + const value = exactObject(raw, ['reviewerId', 'ticketId', 'sourceGeneration', 'expectedWorkGeneration', 'target', 'policy']); + const target = exactObject(value.target, ['articleId', 'collectionId', 'articleRevision', 'contentHash', + 'sourceSnapshotGeneration', 'sourceSnapshotHash', 'orderedReferencesHash']); + const policy = exactObject(value.policy, ['version', 'binding', 'verifiedAt', 'validUntil']); + const scalar = (input: unknown) => boundedString(input, 1, 200); + const hash = (input: unknown) => { + const result = boundedString(input, 64, 64); + if (!/^[0-9a-f]{64}$/u.test(result)) throw new ApiError(400, 'invalid_request'); + return result; + }; + const stamp = (input: unknown) => { + const result = boundedString(input, 1, 40); const parsed = Date.parse(result); + if (!Number.isFinite(parsed) || new Date(parsed).toISOString() !== result) + throw new ApiError(400, 'invalid_request'); + return result; // Historical receipt/cancel must accept an expired snapshot. + }; + if (value.ticketId !== ticketId) throw new ApiError(400, 'invalid_request'); + return { reviewerId: scalar(value.reviewerId), ticketId, + sourceGeneration: integer(value.sourceGeneration), expectedWorkGeneration: integer(value.expectedWorkGeneration), + target: { articleId: scalar(target.articleId), collectionId: scalar(target.collectionId), + articleRevision: integer(target.articleRevision), contentHash: hash(target.contentHash), + sourceSnapshotGeneration: integer(target.sourceSnapshotGeneration, 0), + sourceSnapshotHash: hash(target.sourceSnapshotHash), orderedReferencesHash: hash(target.orderedReferencesHash) }, + policy: { version: scalar(policy.version), binding: scalar(policy.binding), + verifiedAt: stamp(policy.verifiedAt), validUntil: stamp(policy.validUntil) } }; +} + +function mapped(error: unknown) { + if (error instanceof ApiError) return error; + if (error instanceof KnowledgeBaseAuthorizationError) + return new ApiError(403, 'forbidden'); + if (error instanceof KnowledgeBaseNotFoundError) + return new ApiError(404, 'not_found'); + if (error instanceof RepositoryConflictError) + return new ApiError(409, 'conflict'); + const result = mapSupportError(error); + // Unknown dependency failures are opaque; no raw model, source or SDK errors. + return new ApiError(result.status >= 500 ? 503 : result.status, + result.status >= 500 ? 'support_learning_unavailable' : result.code, + result.retryAfterSeconds); +} + +function failureResponse(error: unknown): Response { + const value = mapped(error); + return json({ error: value.code }, { status: value.status, + headers: value.retryAfterSeconds === undefined ? {} : { 'Retry-After': String(value.retryAfterSeconds) } }); +} + +/** + * Optional staff HTTP seam. Check current authority for the original browser + * before each SDK operation and before returning its result or failure. + * A committed SDK mutation can outlive its ACK. Recover the original packet. + */ +export function createSupportLearningHandlers(options: SupportLearningHandlerOptions) { + const resolve = createAgentPrincipalResolver(options); + function enabled() { + try { return options.enabled?.() === true; } catch { return false; } + } + function stagedEnabled() { + try { return options.stagedReviewsEnabled?.() === true; } catch { return false; } + } + return async function handle(request: Request): Promise { + const url = new URL(request.url); + const match = path.exec(url.pathname); + if (match === null) return null; + if (!enabled()) return json({ error: 'support_learning_disabled' }, { status: 503 }); + const ticketId = match[1]; + if (ticketId === undefined) return json({ error: 'invalid_request' }, { status: 400 }); + const name = match[2] ?? 'source'; + const operation: Operation = name === 'work' || name === 'proposal' || name === 'enroll' || name === 'enroll-recovery' || + name === 'evidence' || name === 'evidence-recovery' || name === 'review' || name === 'review-receipt' || name === 'review-cancel' || name === 'review-queue' || name === 'review-queue-status' || name === 'review-queue-cancel' || name === 'withdraw' || name === 'invalidate' + ? name : 'source'; + const mutation = operation !== 'source' && operation !== 'work' && operation !== 'proposal'; + const permission = operationPermission(operation); + const queued = operation.startsWith('review-queue'); + if (queued && !stagedEnabled()) return json({ error: 'support_learning_disabled' }, { status: 503 }); + const requiresKnowledge = operation === 'proposal'; + const browser = supportHumanBrowser(request, { + sessions: options.sessions, + async authenticate(incoming) { + const value = await authenticate(incoming, options); + if (value === null) throw new ApiError(401, 'authentication_required'); + return value; + }, + async access(authenticated) { + const value = await resolve(authenticated.link.subject); + if (value === null) throw new ApiError(401, 'authentication_required'); + return value; + }, + permission, + mutation, + }); + let ceiling: AccessContext | undefined; + async function current() { + if (!enabled()) throw new ApiError(503, 'support_learning_disabled'); + if (queued && !stagedEnabled()) throw new ApiError(503, 'support_learning_disabled'); + const fresh = await browser.current(); + if (!enabled()) throw new ApiError(503, 'support_learning_disabled'); + if (queued && !stagedEnabled()) throw new ApiError(503, 'support_learning_disabled'); + ceiling ??= structuredClone(fresh.access); + const access: AccessContext = { + principalId: ceiling.principalId, + policyVersion: fresh.access.policyVersion, + roles: fresh.access.roles.filter((role) => ceiling?.roles.includes(role)), + entitlements: fresh.access.entitlements.filter((entry) => ceiling?.entitlements.includes(entry)), + permissions: fresh.access.permissions.filter((entry) => ceiling?.permissions.includes(entry)), + }; + for (const required of [permission, supportPermissions.queueRead, + ...(operation === 'proposal' ? [supportPermissions.learningReview] : []), + ...(requiresKnowledge ? [knowledgePermissions.draftRead, knowledgePermissions.provenanceRead] : [])]) { + if (!hasPermission(access, required)) throw new ApiError(403, 'forbidden'); + } + return { access, csrfToken: fresh.authenticated.csrfToken }; + } + async function withCurrentAccess(run: (access: AccessContext) => Promise): Promise { + return run((await current()).access); + } + try { + if (request.method !== (mutation ? 'POST' : 'GET')) throw new ApiError(405, 'method_not_allowed'); + if (url.hash !== '' || ((operation !== 'work' && operation !== 'proposal') && url.search !== '')) + throw new ApiError(400, 'invalid_request'); + const principalId = (await current()).access.principalId; + await enforceRateLimit(options.limiter, principalId); + let result: unknown; + let responseStatus = 200; + if (operation === 'source') { + const source = await withCurrentAccess((access) => options.runtime().readSource(access, ticketId)); + result = { ticketId, sourceGeneration: source.sourceGeneration, resolutionCycle: source.resolutionCycle, + state: source.state, reconciliationPending: source.reconciliationPending, + ...(source.heldReason === undefined ? {} : { heldReason: source.heldReason }) }; + } else if (operation === 'work') { + const generation = sourceGeneration(url); + const work = await withCurrentAccess((access) => options.runtime().readWork(access, { ticketId, sourceGeneration: generation })); + // Candidate/draft payloads and proof references require the KB-gated proposal route. + result = { ticketId, sourceGeneration: work.sourceGeneration, workGeneration: work.workGeneration, + status: work.status, stage: work.stage, hasProposal: work.target !== undefined, + ...(work.heldReason === undefined ? {} : { heldReason: work.heldReason }) }; + } else if (operation === 'proposal') { + const value = await withCurrentAccess((access) => options.runtime().prepareReviewIntent(access, { + ticketId, sourceGeneration: sourceGeneration(url), + })); + result = { ticketId, intent: value.intent, draft: value.draft }; + } else { + // Recheck after the limiter and before reading the bounded body. + // The SDK operation resolves current authority again after the read. + const body = await withCurrentAccess(() => readJson(request, { timeoutMs: 10_000 })); + if (operation === 'enroll' || operation === 'enroll-recovery') { + const packet = exactObject(body, ['commandId', 'expectedRevision']); + const clientCommandId = boundedString(packet.commandId, 1, 200); + const expectedRevision = integer(packet.expectedRevision); + result = await withCurrentAccess(async (access) => options.runtime()[operation === 'enroll' ? 'enroll' : 'recoverEnrollment'](access, { + ticketId, clientCommandId, expectedRevision, + })); + } else if (operation === 'evidence' || operation === 'evidence-recovery') { + const packet = exactObject(body, ['commandId', 'expectedRevision', 'resolutionCycle', 'solutionMessageId', 'verificationReference']); + const clientCommandId = boundedString(packet.commandId, 1, 200); + const expectedRevision = integer(packet.expectedRevision); + const resolutionCycle = integer(packet.resolutionCycle); + const solutionMessageId = boundedString(packet.solutionMessageId, 1, 200); + const verificationReference = boundedString(packet.verificationReference, 1, 200); + result = await withCurrentAccess(async (access) => options.runtime()[operation === 'evidence' ? 'submitVerifiedFix' : 'recoverVerifiedFix'](access, { + ticketId, clientCommandId, expectedRevision, resolutionCycle, + evidence: { kind: 'staff_verified_fix', solutionMessageId, verificationReference }, + })); + } else if (operation.startsWith('review')) { + const packet = optionalKeysObject(body, ['commandId', 'intent', 'decision'], ['reason']); + const clientCommandId = boundedString(packet.commandId, 1, 200); + const intent = reviewIntent(packet.intent, ticketId); + if (packet.decision !== 'approve' && packet.decision !== 'reject') throw new ApiError(400, 'invalid_request'); + const reason = packet.reason === undefined ? undefined : boundedString(packet.reason, 1, 200); + const command: LearningReviewIntentPacket = { clientCommandId, intent, decision: packet.decision, + ...(reason === undefined ? {} : { reason }) }; + if (intent.reviewerId !== principalId) throw new ApiError(403, 'forbidden'); + const verifyHumanBeforeCommit = async () => { + const fresh = await current(); + // Admission's receipt lookup precedes old KB prerequisites. A NEW + // durable intent still requires current KB grants at its guard. + if (operation === 'review-queue') + for (const required of [knowledgePermissions.draftRead, knowledgePermissions.provenanceRead]) + if (!hasPermission(fresh.access, required)) throw new ApiError(403, 'forbidden'); + }; + if (operation === 'review-queue') { + const status = await withCurrentAccess((access) => options.runtime().admitReviewIntent(access, command, verifyHumanBeforeCommit)); + result = status; + responseStatus = status.outcome === 'pending' ? 202 : 200; + } else if (operation === 'review-queue-status') + result = await withCurrentAccess((access) => options.runtime().readStagedReviewStatus(access, command)); + else if (operation === 'review-queue-cancel') + result = await withCurrentAccess((access) => options.runtime().cancelStagedReview(access, command, verifyHumanBeforeCommit)); + else if (operation === 'review-receipt') + result = await withCurrentAccess((access) => options.runtime().readReviewReceipt(access, command)); + else if (operation === 'review-cancel') + result = await withCurrentAccess((access) => options.runtime().cancelReview(access, command, verifyHumanBeforeCommit)); + else result = { outcome: 'accepted', result: await withCurrentAccess((access) => + options.runtime().submitReviewIntent(access, command, verifyHumanBeforeCommit)) }; + } else if (operation === 'invalidate') { + const packet = exactObject(body, ['commandId', 'reason']); + if (packet.reason !== 'evidence_revoked' && packet.reason !== 'product_binding_revoked' && packet.reason !== 'check_policy_revoked') + throw new ApiError(400, 'invalid_request'); + const reason = packet.reason; + const clientCommandId = boundedString(packet.commandId, 1, 200); + result = await withCurrentAccess((access) => options.runtime().invalidate(access, { + ticketId, clientCommandId, reason, + })); + } else { + const packet = exactObject(body, ['commandId', 'reason']); + if (packet.reason !== 'privacy_withdrawal' && packet.reason !== 'source_access_revoked' && packet.reason !== 'source_deleted') + throw new ApiError(400, 'invalid_request'); + const reason = packet.reason; + const clientCommandId = boundedString(packet.commandId, 1, 200); + result = await withCurrentAccess((access) => options.runtime().withdraw(access, { + ticketId, clientCommandId, reason, + })); + } + } + // This closing check fences the complete protected runtime operation + // and its synchronous response projection. + let final: Awaited>; + try { + final = await current(); + } catch (authorityError) { + // The closing fence supplies the fresh denial. Keep synchronous kill + // priority here and return its failure directly from this boundary. + if (!enabled() || (queued && !stagedEnabled())) + return failureResponse(new ApiError(503, 'support_learning_disabled')); + return failureResponse(authorityError); + } + return json({ result, csrfToken: final.csrfToken }, { status: responseStatus }); + } catch (error) { + let failure = error; + // Denial/outage after an awaited failure wins over a stale earlier error. + try { await current(); } catch (authorityError) { failure = authorityError; } + return failureResponse(failure); + } + }; +} diff --git a/worker/src/support-learning-http.d1.test.ts b/worker/src/support-learning-http.d1.test.ts new file mode 100644 index 0000000..d1657be --- /dev/null +++ b/worker/src/support-learning-http.d1.test.ts @@ -0,0 +1,921 @@ +/// + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { env } from 'cloudflare:workers'; +import { createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { createSupportDeskApplication, supportRecords } from '@pegma/support-desk-application'; +import type { CollectionDefinition, CollectionStore, Store } from '@pegma/storage-core'; +import { learningTargetBinding } from '@pegma/support-desk-ai'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE } from './support-access'; +import { createSupportApi } from './support-api'; +import { createSupportRuntime } from './support-desk'; +import { createWorker } from './index'; +import { createSupportLearningRuntime, type SupportLearningRuntimeOptions } from './support-learning'; +import { createSupportLearningReviewQueue, type SupportLearningReviewQueueMessage } from './support-learning-review-queue'; +import type { SupportLearningProcessingPorts } from './support-learning-ports'; +import { controlledHumanBody } from './support-human-control-fixtures'; +import { + createSupportLearningFixture, learningCanary, learningTicketId, +} from './support-learning-fixtures'; + +const base = '/api/support/admin/tickets/' + learningTicketId + '/learning'; +const sessionId = 's'.repeat(43); +const csrf = 'c'.repeat(43); + +type BindingMethod = 'first' | 'all' | 'run' | 'raw' | 'batch'; +type Phase = 'route' | 'session' | 'identity' | 'roles' | 'limiter' | + 'runtime-staff' | 'prepare-intent' | 'submit-intent' | 'read-receipt' | 'cancel-review'; + +interface BindingTrace { + readonly call: number; + readonly method: BindingMethod; + readonly phase: readonly Phase[]; + readonly categories: readonly string[]; + readonly statements: number; + readonly maximumParameters: number; + readonly blocked: boolean; +} + +interface InvocationBudget { + readonly operation: string; + calls: number; + executed: number; + statements: number; + batches: number; + maximumParameters: number; + blocked: number; + readonly trace: BindingTrace[]; + firstBlocked?: BindingTrace; + status?: number; +} + +const profiles: InvocationBudget[] = []; + +beforeAll(async () => { + expect(String(env.IDENTITY_EMAIL_ENABLED)).toBe('false'); + // Test schema setup is outside measured HTTP invocations. + const store = createCloudflareD1Store({ database: env.IDENTITY_DB }); + await store.collection(supportRecords).get({ + partition: 'learning-http-schema-probe', id: 'absent', + }); +}); + +beforeEach(async () => { + profiles.length = 0; + // The Native test pool gives this file its own D1 binding. + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +afterEach(({ task }) => { + Object.assign(task.meta, { supportLearningHttpD1Budget: structuredClone(profiles) }); + console.info('support-learning-http-d1-budgets', JSON.stringify(profiles.map(({ trace, firstBlocked, ...budget }) => budget))); + for (const profile of profiles) { + const { trace, firstBlocked, ...budget } = profile; + console.info('support-learning-http-d1-trace', JSON.stringify({ operation: profile.operation, firstBlocked, trace })); + const detail = JSON.stringify(budget); + expect(profile.calls, detail).toBeGreaterThan(0); + expect(profile.calls, detail).toBeLessThanOrEqual(50); + expect(profile.executed, detail).toBe(profile.calls); + expect(profile.maximumParameters, detail).toBeLessThanOrEqual(100); + expect(profile.blocked, detail).toBe(0); + } +}); + +// Emit fixed categories only. Stack strings, SQL and bound values stay out of the report. +function stackCategories(): readonly string[] { + const stack = (new Error().stack ?? '').replaceAll('\\', '/'); + const markers = [ + ['sessions', '/@pegma/sessions/'], + ['identity', '/@pegma/identity/'], + ['authorization', '/@pegma/authorization-core/'], + ['rate-limit', '/@pegma/rate-limit/'], + ['support-application', '/@pegma/support-desk-application/'], + ['support-ai', '/@pegma/support-desk-ai/'], + ['knowledge-application', '/@pegma/knowledge-base-application/'], + ['browser-authority', 'support-human-auth.ts'], + ['host-learning-runtime', 'support-learning.ts'], + ['host-learning-handler', 'support-learning-handlers.ts'], + ] as const; + return markers.filter(([, marker]) => stack.includes(marker)).map(([label]) => label); +} + +/** Count calls at the genuine binding, including sessions, roles and limiter. + * Charge a batch once and enforce the parameter ceiling on every statement. */ +function meter(backing: D1Database) { + const scope = new AsyncLocalStorage<{ profile: InvocationBudget; phase: readonly Phase[] }>(); + const originals = new WeakMap(); + const parameters = new WeakMap(); + + function charge(method: BindingMethod, statements: readonly D1PreparedStatement[]) { + const current = scope.getStore(); + if (current === undefined) return; + const { profile, phase } = current; + profile.calls += 1; + profile.statements += statements.length; + let maximumParameters = 0; + for (const statement of statements) { + maximumParameters = Math.max(maximumParameters, parameters.get(statement) ?? 0); + } + profile.maximumParameters = Math.max(profile.maximumParameters, maximumParameters); + const blocked = profile.calls > 50 || profile.maximumParameters > 100; + const trace = { call: profile.calls, method, phase, categories: stackCategories(), + statements: statements.length, maximumParameters, blocked }; + profile.trace.push(trace); + if (blocked) { + profile.blocked += 1; + profile.firstBlocked ??= trace; + throw new Error('Workers Free learning HTTP D1 budget exceeded'); + } + profile.executed += 1; + } + + function observed(original: D1PreparedStatement, count = 0): D1PreparedStatement { + const statement: D1PreparedStatement = { + bind(...values: unknown[]) { + return observed(original.bind(...values), values.length); + }, + first>(column?: string): Promise { + charge('first', [statement]); + return column === undefined ? original.first() : original.first(column); + }, + all>() { + charge('all', [statement]); + return original.all(); + }, + run>() { + charge('run', [statement]); + return original.run(); + }, + raw: original.raw, + }; + statement.raw = new Proxy(original.raw, { apply(target, _receiver, args) { + charge('raw', [statement]); + return Reflect.apply(target, original, args); + } }); + originals.set(statement, original); + parameters.set(statement, count); + return statement; + } + + const database: D1Database = { + prepare(query) { return observed(backing.prepare(query)); }, + async batch(statements: D1PreparedStatement[]) { + charge('batch', statements); + const profile = scope.getStore()?.profile; + if (profile !== undefined) profile.batches += 1; + const native = statements.map((statement) => { + const original = originals.get(statement); + if (original === undefined) throw new Error('Expected a metered D1 statement'); + return original; + }); + return backing.batch(native); + }, + exec() { throw new Error('Runtime schema work is outside this test'); }, + dump() { throw new Error('Runtime D1 dump is outside this test'); }, + withSession() { throw new Error('Expected the direct D1 binding'); }, + }; + return { + database, + // Deliberate peer mutations are independent fixture actors, not calls made + // by the measured HTTP request. Their effects remain genuine native writes. + outside(action: () => Value): Value { + return scope.exit(action); + }, + phase(name: Phase, action: () => Value): Value { + const current = scope.getStore(); + return current === undefined ? action() : scope.run({ ...current, phase: [...current.phase, name] }, action); + }, + run(operation: string, action: () => Promise) { + const profile: InvocationBudget = { + operation, calls: 0, executed: 0, statements: 0, batches: 0, + maximumParameters: 0, blocked: 0, trace: [], + }; + profiles.push(profile); + return scope.run({ profile, phase: ['route'] }, async () => { + const result = await action(); + if (result instanceof Response) { + profile.status = result.status; + await result.clone().arrayBuffer(); + } + return result; + }); + }, + }; +} + +async function fixture() { + const binding = meter(env.IDENTITY_DB); + const backing = createCloudflareD1Store({ + database: binding.database, createSchemaIfMissing: false, readBatchSize: 512, + }); + const hooks: { + afterLimiter?: () => Promise; + afterDraft?: () => Promise; + beforeCommit?: () => Promise; + afterCommit?: () => Promise; + targetArticleId?: string; + armed: boolean; + policyCalls: number; + draftCalls: number; + reviewDepth: number; + committed: number; + conflicts: number; + } = { armed: false, policyCalls: 0, draftCalls: 0, reviewDepth: 0, committed: 0, conflicts: 0 }; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const actual = backing.collection(definition); + if (definition.name !== supportRecords.name) return actual; + return { ...actual, async transact(partition, actions) { + const acceptedReview = actions.some((action) => action.action !== 'delete' && + isPlainObject(action.value) && action.value.kind === 'resolution_learning_review'); + if (hooks.armed && partition === learningTicketId && acceptedReview) await hooks.beforeCommit?.(); + const result = await actual.transact(partition, actions); + if (hooks.armed && partition === learningTicketId && acceptedReview) { + if (result.committed) { + hooks.committed += 1; + await hooks.afterCommit?.(); + } else hooks.conflicts += 1; + } + return result; + } }; + }, + }; + const learning = await createSupportLearningFixture(store, { stagedReviews: true, readScheduling: 'sdk' }); + const logger = { log() {} }; + const { identity, sessions } = createIdentityRuntime({ + store, emailCodeSecretBase64: btoa('r'.repeat(32)), + emailFrom: 'Pegma ', emailEnabled: false, + }, logger); + const identityLinkFromClaims = identityLinkKeyFromVerifiedIdentityClaims; + const host = createSupportRuntime({ store, identity, sessions, logger, identityLinkFromClaims }); + const principalId = learning.actors.staff.principalId; + await identity.provisionVerifiedUser({ principalId, email: 'learning-http@example.test' }); + await sessions.create(sessionId, { + principalId, + data: JSON.stringify({ version: 1, issuer: IDENTITY_ISSUER, subject: principalId, csrfToken: csrf }), + }); + for (const role of [SUPPORT_ROLE, KNOWLEDGE_ROLE]) { + const grant = await host.roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'native-learning-http-' + role, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-learning-http' }, + grantedAtEpochMs: Date.now(), status: 'active', + }, + auditEventId: 'native-learning-http-grant-' + role, + }); + expect(grant.status).toBe('granted'); + } + + const authority = { + identity: { ...identity, claimsFor: (id: string) => binding.phase('identity', () => identity.claimsFor(id)) }, + sessions: { ...sessions, get: (id: string) => binding.phase('session', () => sessions.get(id)) }, + identityLinkFromClaims, + logger, + roleStore: { ...host.roleStore, listActiveRoleAssignments: (...args: Parameters) => + binding.phase('roles', () => host.roleStore.listActiveRoleAssignments(...args)) }, + }; + const resolve = createAgentPrincipalResolver(authority); + const ports: SupportLearningProcessingPorts = { + ...learning.ports, + checks: { ...learning.ports.checks, async resolvePolicy(...args) { + hooks.policyCalls += 1; + return learning.ports.checks.resolvePolicy(...args); + } }, + targets: { + async resolveScope(...args) { + const result = await learning.ports.targets.resolveScope(...args); + return result.outcome === 'ready' && hooks.targetArticleId !== undefined + ? { ...result, scope: { ...result.scope, explicitDraftIds: [hooks.targetArticleId] } } + : result; + }, + async select(input, context) { + const result = await learning.ports.targets.select(input, context); + if (hooks.targetArticleId === undefined || result.outcome !== 'selected') return result; + const existing = input.explicitDrafts.find((draft) => draft.articleId === hooks.targetArticleId); + if (existing === undefined) return { outcome: 'held' }; + // Script only the trusted external target policy. The real coordinator + // reads, merges provenance, checks and delivers this actual KB update. + return { ...result, operation: 'update', articleId: existing.articleId, + draft: { ...result.draft, content: { format: 'plain_text', + text: existing.revision.content.text + '\n\n' + result.draft.content.text } } }; + }, + }, + }; + const staged = (() => { + const capability = learning.application.stagedResolutionLearningReviews; + if (capability === undefined) throw new Error('Expected the real opted-in SDK staged review capability'); + return capability; + })(); + const application = { ...learning.application, + stagedResolutionLearningReviews: { ...staged, + async complete(...args: Parameters) { + hooks.reviewDepth += 1; + try { return await staged.complete(...args); } + finally { hooks.reviewDepth -= 1; } + }, + }, + async reviewResolutionLearningProposal(...args: Parameters) { + hooks.reviewDepth += 1; + try { return await learning.application.reviewResolutionLearningProposal(...args); } + finally { hooks.reviewDepth -= 1; } + }, + }; + const knowledge = { ...learning.knowledge, + async getDraft(...args: Parameters) { + const result = await learning.knowledge.getDraft(...args); + hooks.draftCalls += 1; + await hooks.afterDraft?.(); + return result; + }, + }; + const messages: SupportLearningReviewQueueMessage[] = []; + const sender = { async send(message: SupportLearningReviewQueueMessage) { messages.push(structuredClone(message)); } }; + let queue: ReturnType; + const learningRuntime: Omit = { + application, knowledge, sources: learning.sources, clock: learning.clock, ports, + processingEnabled: () => learning.state.enabled, + readScheduling: 'sdk', + stagedReviews: { enabled: () => true, enqueue: (key) => queue.enqueue(key) }, + }; + // SDK-only diagnostics retain the standalone factory's genuine current + // resolver. HTTP uses the normal router's private Request-only composition. + const runtime = createSupportLearningRuntime({ ...learningRuntime, + staffAccess: { resolve: (id) => binding.phase('runtime-staff', () => resolve(id)) }, + }); + queue = createSupportLearningReviewQueue({ enabled: () => true, store: () => store, + clock: learning.clock, logger, sender, runtime: () => runtime.stagedReviewDispatch() }); + const observedRuntime = { + ...runtime, + prepareReviewIntent: (...args: Parameters) => + binding.phase('prepare-intent', () => runtime.prepareReviewIntent(...args)), + submitReviewIntent: (...args: Parameters) => + binding.phase('submit-intent', () => runtime.submitReviewIntent(...args)), + readReviewReceipt: (...args: Parameters) => + binding.phase('read-receipt', () => runtime.readReviewReceipt(...args)), + cancelReview: (...args: Parameters) => + binding.phase('cancel-review', () => runtime.cancelReview(...args)), + }; + const enabled = () => true; + const limiter = { ...host.replyLimiter, async allow(...args: Parameters) { + const result = await binding.phase('limiter', () => host.replyLimiter.allow(...args)); + await hooks.afterLimiter?.(); + return result; + } }; + const api = createSupportApi({ + ...authority, application: learning.application, + createLimiter: host.createLimiter, replyLimiter: limiter, + learningRuntime, learningEnabled: enabled, learningStagedReviewsEnabled: enabled, + }); + const worker = () => createWorker({ learningReviews: { enabled, create: () => ({ api, queue }) } }); + const broker: Queue = { + async metrics() { return { backlogCount: messages.length, backlogBytes: 0 }; }, + async send(message) { + await sender.send(message); + return { metadata: { metrics: { backlogCount: messages.length, backlogBytes: 0 } } }; + }, + async sendBatch() { throw new Error('Expected one opaque review hint'); }, + }; + const environment: Parameters['queue']>[1] = { + ...env, IDENTITY_DB: binding.database, IDENTITY_EMAIL_CODE_SECRET_BASE64: btoa('r'.repeat(32)), + PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: 'true', SUPPORT_LEARNING_REVIEWS: broker, + }; + + let peerOrdinal = 0; + async function revokeRole(role: typeof SUPPORT_ROLE | typeof KNOWLEDGE_ROLE) { + return binding.outside(async () => { + const id = 'native-learning-http-' + role; + const row = await host.roleStore.getRoleAssignment(id); + if (row === null) throw new Error('Expected the stored human assignment'); + await host.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: id, expectedConcurrencyToken: row.concurrencyToken, + revokedBy: { kind: 'system', systemId: 'synthetic-learning-http' }, + revokedAtEpochMs: Date.now(), auditEventId: 'native-learning-http-revoke-' + ++peerOrdinal, + }); + expect((await resolve(principalId))?.roles).not.toContain(role); + }); + } + async function grantRole(role: typeof SUPPORT_ROLE | typeof KNOWLEDGE_ROLE) { + return binding.outside(async () => { + const id = 'native-learning-http-restored-' + ++peerOrdinal; + const result = await host.roleStore.grantRoleAssignmentWithAudit({ + assignment: { id, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-learning-http' }, + grantedAtEpochMs: Date.now(), status: 'active' }, + auditEventId: id + '-audit', + }); + expect(result.status).toBe('granted'); + }); + } + const revokeKnowledge = () => revokeRole(KNOWLEDGE_ROLE); + const destroySession = () => binding.outside(() => sessions.destroy(sessionId)); + function request(suffix: string, retainedBody?: string) { + return new Request(IDENTITY_ISSUER + base + suffix, { + method: retainedBody === undefined ? 'GET' : 'POST', + headers: { + Cookie: SESSION_COOKIE + '=' + sessionId, + ...(retainedBody === undefined ? {} : { + Origin: IDENTITY_ISSUER, 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': csrf, 'Content-Type': 'application/json', + }), + }, + ...(retainedBody === undefined ? {} : { body: retainedBody }), + }); + } + const send = (operation: string, value: Request) => binding.run(operation, async () => { + const context = createExecutionContext(); + try { return await worker().fetch(value, environment, context); } + finally { await waitOnExecutionContext(context); } + }); + const invoke = (operation: string, suffix: string, retainedBody?: string) => + send(operation, request(suffix, retainedBody)); + const deliver = (operation: string) => binding.run(operation, async () => { + const message = messages.at(-1); + if (message === undefined) throw new Error('Expected a genuine admitted review hint'); + const result = { acknowledgements: 0, delays: [] as number[] }; + const batch: MessageBatch = { + queue: 'pegma-dev-support-learning-reviews', + metadata: { metrics: { backlogCount: 1, backlogBytes: 0 } }, + messages: [{ id: 'native-review-delivery', body: message, timestamp: new Date(learning.clock.now()), attempts: 1, + ack() { result.acknowledgements += 1; }, + retry(options) { + if (options?.delaySeconds === undefined) throw new Error('Expected bounded same-message retry'); + result.delays.push(options.delaySeconds); + } }], + ackAll() { throw new Error('Expected individual acknowledgement'); }, + retryAll() { throw new Error('Expected individual retry'); }, + }; + const context = createExecutionContext(); + try { await worker().queue(batch, environment, context); } + finally { await waitOnExecutionContext(context); } + return result; + }); + + async function prepareSdk(sourceGeneration: number) { + // Set up the actual host AccessContext outside this SDK-only scope. The + // runtime still performs its own current staff checks inside the meter. + const access = await resolve(principalId); + if (access === null) throw new Error('Expected a real current staff actor'); + return binding.run('proposal.sdk-only', () => observedRuntime.prepareReviewIntent(access, { + ticketId: learningTicketId, sourceGeneration, + })); + } + + async function rewriteTicketVersion() { + return binding.outside(async () => { + const rows = backing.collection(supportRecords); + const ticket = await rows.getVersioned({ partition: learningTicketId, id: 'ticket' }); + if (ticket === null || ticket.value.kind !== 'ticket') throw new Error('Expected the actual ticket'); + // Same decoded SDK value, fresh opaque native version: a real competing + // writer forces the target transaction's original version condition to fail. + expect(await rows.putIfUnchanged(ticket.value, ticket.version)).toBe(true); + }); + } + return { learning, principalId, invoke, request, send, deliver, revokeKnowledge, revokeRole, + grantRole, destroySession, prepareSdk, runtime, hooks, rewriteTicketVersion }; + +} + +async function envelope(response: Response) { + const body: unknown = await response.json(); + if (!isPlainObject(body)) throw new Error('Expected a Support route JSON envelope'); + return body; +} + +type NativeFixture = Awaited>; +type Delivered = Awaited>; + +async function inspect(f: NativeFixture, delivered: Delivered, commandId: string) { + const response = await f.invoke('proposal.prepare', + '/proposal?sourceGeneration=' + delivered.source.sourceGeneration); + expect(response.status).toBe(200); + const body = await envelope(response); + if (!isPlainObject(body.result) || !isPlainObject(body.result.intent)) + throw new Error('Expected the actual prepared SDK intent'); + expect(body.csrfToken).toBe(csrf); + return { intent: body.result.intent, + packet: JSON.stringify({ commandId, intent: body.result.intent, + decision: 'approve', reason: 'A synthetic exact Native review.' }) }; +} + +async function changeDraft(f: NativeFixture, delivered: Delivered) { + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId }); + await f.learning.knowledge.updateDraft(f.learning.actors.staff, { + ...f.learning.command('native-http-current-edit', draft.generation), + articleId: delivered.articleId, collectionId: draft.revision.collectionId, + draft: { kind: draft.revision.kind, title: 'A separately edited synthetic guide', + summary: draft.revision.summary, content: draft.revision.content, + tags: draft.revision.tags, applicability: draft.revision.applicability }, + }); +} + +/** Construct every contributor through actual public Support and KB workflows. */ +async function multipleContributors(f: NativeFixture, published: boolean): Promise { + const ticketId = 'native-secondary-learning-ticket'; + const messageId = 'native-secondary-learning-solution'; + const old = createSupportDeskApplication({ store: f.learning.store, clock: f.learning.clock }); + await old.createCustomerTicket(f.learning.actors.customer, { + ...f.learning.command('secondary-ticket'), ticketId, messageId: 'native-secondary-question', + subject: 'A second synthetic export problem', body: 'How can a second workspace be exported?', + }); + await old.replyAsStaff(f.learning.actors.staff, { + ...f.learning.command('secondary-solution'), ticketId, messageId, + body: 'Open Workspace and choose Export for the second workspace.', + }); + await old.resolveTicket(f.learning.actors.staff, { ...f.learning.command('secondary-resolve'), ticketId }); + const ticket = (await old.readStaffTicket(f.learning.actors.staff, ticketId)).ticket; + await f.learning.runtime.enroll(f.learning.actors.staff, { + ticketId, clientCommandId: 'SECONDARY-ENROLL:UPPER', expectedRevision: ticket.revision, + }); + const enrolled = await f.learning.runtime.readSource(f.learning.actors.staff, ticketId); + await f.learning.runtime.submitVerifiedFix(f.learning.actors.staff, { + ticketId, clientCommandId: 'SECONDARY-VERIFY:UPPER', expectedRevision: ticket.revision, + resolutionCycle: enrolled.resolutionCycle, + evidence: { kind: 'staff_verified_fix', solutionMessageId: messageId, + verificationReference: 'SYNTHETIC_SECONDARY_VERIFICATION' }, + }); + // Accepted evidence advances generation0 enrollment and creates work for the + // new current generation. Never reuse the pre-evidence work key. + const source = await f.learning.runtime.readSource(f.learning.actors.staff, ticketId); + expect(source.state).toBe('eligible'); + expect(source.sourceGeneration).toBeGreaterThan(enrolled.sourceGeneration); + const process = () => f.learning.runtime.processWork({ + ticketId, sourceGeneration: source.sourceGeneration, + workerId: 'native-secondary-worker', leaseMilliseconds: 30_000, + }); + expect(await process()).toMatchObject({ outcome: 'candidate' }); + expect(await process()).toMatchObject({ outcome: 'delivered' }); + const secondary = await f.learning.runtime.readWork(f.learning.actors.staff, { + ticketId, sourceGeneration: source.sourceGeneration, + }); + if (secondary.target === undefined || secondary.checkPolicyVersion === undefined) + throw new Error('Expected the genuine second delivered target'); + const articleId = secondary.target.articleId; + if (published) { + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId }); + const provenance = await f.learning.knowledge.getProvenance(f.learning.actors.staff, { articleId }); + await f.learning.runtime.reviewProposal(f.learning.actors.staff, { + ticketId, clientCommandId: 'SECONDARY-REVIEW:UPPER', sourceGeneration: source.sourceGeneration, + expectedWorkGeneration: secondary.workGeneration, + target: await learningTargetBinding(draft.revision, provenance.snapshot), + policyVersion: secondary.checkPolicyVersion, decision: 'approve', + }); + await f.learning.evidenceAndPublish(articleId); + } + // The trusted test target policy selects a real explicitly permitted draft. + // The actual coordinator merges both source references and keeps published + // provenance. No test constructs a reference, provenance hash or accepted row. + f.hooks.targetArticleId = articleId; + await f.learning.enrollAndVerify(); + const primary = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + const primaryProcess = () => f.runtime.processWork({ + ticketId: learningTicketId, sourceGeneration: primary.sourceGeneration, + workerId: 'native-primary-multi-worker', leaseMilliseconds: 30_000, + }); + expect((await primaryProcess()).outcome).toBe('candidate'); + expect((await primaryProcess()).outcome).toBe('delivered'); + const work = await f.runtime.readWork(f.learning.actors.staff, { + ticketId: learningTicketId, sourceGeneration: primary.sourceGeneration, + }); + expect(work.target?.articleId).toBe(articleId); + const provenance = await f.learning.knowledge.getProvenance(f.learning.actors.staff, { articleId }); + expect(provenance.snapshot.references.map((value) => value.resourceId).sort()) + .toEqual([learningTicketId, ticketId].sort()); + if (published) + expect(provenance.publishedSnapshot?.references.map((value) => value.resourceId)).toEqual([ticketId]); + else expect(provenance.publishedSnapshot).toBeUndefined(); + const completedSource = await f.runtime.readSource(f.learning.actors.staff, learningTicketId); + return { source: completedSource, work, articleId }; +} + +describe('enabled learning HTTP namespace on real Native D1', () => { + it('measures complete SDK preparation on real Native D1', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); + const delivered = await f.learning.delivered(); + const rows = await f.learning.rows(); + const draft = await f.learning.knowledge.getDraft(f.learning.actors.admin, { articleId: delivered.articleId }); + + const prepared = await f.prepareSdk(delivered.source.sourceGeneration); + expect(prepared.intent).toMatchObject({ + reviewerId: f.principalId, ticketId: learningTicketId, + sourceGeneration: delivered.source.sourceGeneration, + expectedWorkGeneration: delivered.work.workGeneration, + }); + expect(prepared.intent.target).toEqual(delivered.work.target); + expect(prepared.draft).toEqual(draft); + expect(await f.learning.rows()).toEqual(rows); + expect(f.learning.state.modelCalls).toBe(1); + expect(profiles).toHaveLength(1); + }); + + it('commits the inspected intent and recovers its discarded ACK after reopening and stored Knowledge revocation', async () => { + // Seed the actual terminal ticket, evidence and delivered draft outside the + // HTTP meter. The model and independent-check inputs use existing fictional ports. + const f = await fixture(); + await f.learning.enrollAndVerify(); + const delivered = await f.learning.delivered(); + const beforeReview = await f.learning.rows(); + expect(beforeReview.some((row) => row.kind === 'resolution_learning_review')).toBe(false); + + const proposalResponse = await f.invoke('proposal.prepare', + '/proposal?sourceGeneration=' + delivered.source.sourceGeneration); + expect(proposalResponse.status).toBe(200); + const proposal = await envelope(proposalResponse); + if (!isPlainObject(proposal.result) || !isPlainObject(proposal.result.intent)) + throw new Error('Expected the actual server-prepared learning intent'); + const intent = proposal.result.intent; + expect(proposal.csrfToken).toBe(csrf); + expect(intent).toMatchObject({ + reviewerId: f.principalId, ticketId: learningTicketId, + sourceGeneration: delivered.source.sourceGeneration, + expectedWorkGeneration: delivered.work.workGeneration, target: delivered.work.target, + }); + expect(JSON.stringify(proposal)).not.toContain(learningCanary); + expect(await f.learning.rows()).toEqual(beforeReview); + + const decision = 'approve'; + const reason = 'Retain this exact Native review.'; + const originalBody = JSON.stringify({ commandId: 'NATIVE-REVIEW:UPPER', intent, decision, reason }); + const lost = await f.invoke('review.admission-discarded-ack', '/review-queue', originalBody); + // 202 acknowledges durable intent, not review completion. Discard that + // browser ACK, then let the two genuine worker invocations make progress. + expect(lost.status).toBe(202); + await lost.body?.cancel(); + expect((await f.learning.rows()).filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(0); + expect(await f.deliver('review.proof')).toEqual({ acknowledgements: 0, delays: [30] }); + expect(await f.deliver('review.commit-discarded-ack')).toEqual({ acknowledgements: 1, delays: [] }); + const committed = await f.learning.rows(); + expect(committed.filter((row) => row.kind === 'resolution_learning_review')).toMatchObject([{ + ticketId: learningTicketId, reviewerId: f.principalId, decision, reason, + sourceGeneration: intent.sourceGeneration, target: intent.target, + }]); + const oldIds = new Set(beforeReview.map((row) => row.id)); + const receipt = committed.find((row) => row.kind === 'resolution_learning_receipt' && !oldIds.has(row.id)); + if (receipt?.kind !== 'resolution_learning_receipt') + throw new Error('Expected the original durable SDK review receipt'); + const expected = { outcome: 'accepted', result: receipt.result }; + + // Separate lifecycle changes and verification reads are test setup, rather + // than D1 calls performed by the physical review and recovery requests. + await f.learning.application.reopenTicket(f.learning.actors.staff, { + ...f.learning.command('native-http-reopen'), ticketId: learningTicketId, + }); + const reopened = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(reopened).toMatchObject({ state: 'held', heldReason: 'reopened', + sourceGeneration: delivered.source.sourceGeneration + 1 }); + await f.revokeKnowledge(); + f.learning.state.enabled = false; + f.learning.state.checkReadable = false; + const afterReopen = await f.learning.rows(); + const draftBefore = await f.learning.knowledge.getDraft(f.learning.actors.admin, { articleId: delivered.articleId }); + + const recovered = await f.invoke('review.receipt-after-reopen-and-role-loss', '/review-queue-status', originalBody); + expect(recovered.status).toBe(200); + expect(await envelope(recovered)).toEqual({ result: expected, csrfToken: csrf }); + expect(await f.learning.rows()).toEqual(afterReopen); + + // Cancelling an already accepted original command returns its accepted + // receipt. The current human route still runs every browser check. + const cancel = await f.invoke('review.cancel-after-accepted', '/review-queue-cancel', originalBody); + expect(cancel.status).toBe(200); + expect(await envelope(cancel)).toEqual({ result: expected, csrfToken: csrf }); + expect(await f.learning.rows()).toEqual(afterReopen); + expect(await f.learning.knowledge.getDraft(f.learning.actors.admin, { articleId: delivered.articleId })).toEqual(draftBefore); + expect(f.learning.state.modelCalls).toBe(1); + expect(profiles).toHaveLength(6); + }); + + for (const change of ['support', 'session'] as const) { + it('denies ' + change + ' revocation after the real limiter before protected SDK reads', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); + const before = await f.learning.rows(); + let entered = false; + f.hooks.afterLimiter = async () => { + delete f.hooks.afterLimiter; entered = true; + if (change === 'support') await f.revokeRole(SUPPORT_ROLE); + else await f.destroySession(); + }; + const response = await f.invoke('authority.after-limiter', ''); + expect(entered).toBe(true); + expect(response.status).toBe(change === 'support' ? 403 : 401); + expect(await envelope(response)).not.toHaveProperty('result'); + expect(await f.learning.rows()).toEqual(before); + expect(f.learning.state.modelCalls).toBe(0); + }); + } + + it('denies current Support loss while the genuine bounded request body is delayed', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); + const before = await f.learning.rows(); + const body = await controlledHumanBody(f.request('/withdraw', + JSON.stringify({ commandId: 'DELAYED-WITHDRAW:UPPER', reason: 'privacy_withdrawal' }))); + const pending = f.send('authority.delayed-body', body.request); + try { + await body.waitFor(pending); + await f.revokeRole(SUPPORT_ROLE); + } finally { body.complete(); } + const response = await pending; + expect(response.status).toBe(403); + expect(await envelope(response)).not.toHaveProperty('result'); + expect(await f.learning.rows()).toEqual(before); + expect(f.learning.state.modelCalls).toBe(0); + }); + + it('withholds a prepared private result after Knowledge is revoked in the late actual KB draft read', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const before = await f.learning.rows(); + f.hooks.policyCalls = 0; f.hooks.draftCalls = 0; + let entered = false; + f.hooks.afterDraft = async () => { + // The current producer's final draft read follows its closing policy + // observation. This assertion must not silently fall back to an early read. + if (f.hooks.policyCalls < 2) return; + delete f.hooks.afterDraft; entered = true; + await f.revokeKnowledge(); + }; + const response = await f.invoke('authority.late-draft-read', + '/proposal?sourceGeneration=' + delivered.source.sourceGeneration); + expect(entered).toBe(true); + expect(response.status).toBe(403); + expect(await envelope(response)).not.toHaveProperty('result'); + expect(await f.learning.rows()).toEqual(before); + expect(f.learning.state.modelCalls).toBe(1); + }); + + it('denies a changed original Cookie after an actual KB read', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const before = await f.learning.rows(); + const request = f.request('/proposal?sourceGeneration=' + delivered.source.sourceGeneration); + let entered = false; + f.hooks.afterDraft = async () => { + delete f.hooks.afterDraft; entered = true; + request.headers.set('Cookie', SESSION_COOKIE + '=' + 'x'.repeat(43)); + }; + const response = await f.send('authority.changed-header', request); + expect(entered).toBe(true); + expect(response.status).toBe(403); + expect(await envelope(response)).not.toHaveProperty('result'); + expect(await f.learning.rows()).toEqual(before); + }); + + it('keeps the original permission ceiling when Knowledge is granted after admission', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const shown = await inspect(f, delivered, 'LATER-KNOWLEDGE-GRANT:UPPER'); + await f.revokeKnowledge(); + const before = await f.learning.rows(); + let entered = false; + f.hooks.afterLimiter = async () => { + delete f.hooks.afterLimiter; entered = true; await f.grantRole(KNOWLEDGE_ROLE); + }; + const response = await f.invoke('authority.new-permission-ceiling', '/review-queue', shown.packet); + expect(entered).toBe(true); + expect(response.status).toBe(403); + expect(await envelope(response)).not.toHaveProperty('result'); + expect(await f.learning.rows()).toEqual(before); + }); + + it('refuses a queued review after real Knowledge loss during its actual P2 proof', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const shown = await inspect(f, delivered, 'PROOF-KNOWLEDGE-LOSS:UPPER'); + expect((await f.invoke('review.proof-race-admission', '/review-queue', shown.packet)).status).toBe(202); + expect(await f.deliver('review.proof-before-role-race')).toEqual({ acknowledgements: 0, delays: [30] }); + const before = await f.learning.rows(); + let entered = false; + f.hooks.afterDraft = async () => { + if (f.hooks.reviewDepth === 0) return; + delete f.hooks.afterDraft; entered = true; await f.revokeKnowledge(); + }; + f.hooks.armed = true; + const delivery = await f.deliver('authority.review-proof'); + expect(entered).toBe(true); + expect(delivery).toEqual({ acknowledgements: 0, delays: [30] }); + expect(f.hooks.committed).toBe(0); + const after = await f.learning.rows(); + expect(after.filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(0); + // A failed phase may retain its genuine claim, but no source, work, Audit + // or receipt can be accepted by that failed proof. + expect(after.filter((row) => row.kind !== 'resolution_learning_review_attempt')) + .toEqual(before.filter((row) => row.kind !== 'resolution_learning_review_attempt')); + const denied = await f.invoke('authority.private-read-after-proof-revocation', + '/proposal?sourceGeneration=' + delivered.source.sourceGeneration); + expect(denied.status).toBe(403); + expect(await envelope(denied)).not.toHaveProperty('result'); + }); + + it('withholds a browser receipt after actual queued commit role revocation and recovers the original receipt', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const shown = await inspect(f, delivered, 'POST-COMMIT-ROLE-LOSS:UPPER'); + expect((await f.invoke('review.postcommit-race-admission', '/review-queue', shown.packet)).status).toBe(202); + expect(await f.deliver('review.proof-before-committed-role-race')).toEqual({ acknowledgements: 0, delays: [30] }); + f.hooks.armed = true; + let entered = false; + f.hooks.afterCommit = async () => { + delete f.hooks.afterCommit; entered = true; await f.revokeRole(SUPPORT_ROLE); + }; + expect(await f.deliver('review.commit-before-role-loss')).toEqual({ acknowledgements: 1, delays: [] }); + expect(entered).toBe(true); + // The worker's transport acknowledgement is not a browser authority + // decision. The fresh original browser still cannot receive private data. + const response = await f.invoke('authority.after-committed-review', '/review-queue-status', shown.packet); + expect(response.status).toBe(403); + expect(await envelope(response)).not.toHaveProperty('result'); + const committed = await f.learning.rows(); + expect(committed.filter((value) => value.kind === 'resolution_learning_review')).toHaveLength(1); + expect(f.hooks.committed).toBe(1); + await f.grantRole(SUPPORT_ROLE); + const recovered = await f.invoke('review.receipt-after-postcommit-revocation', '/review-queue-status', shown.packet); + expect(recovered.status).toBe(200); + const body = await envelope(recovered); + expect(body.result).toMatchObject({ outcome: 'accepted' }); + expect(await f.learning.rows()).toEqual(committed); + expect(f.learning.state.modelCalls).toBe(1); + }); + + it('retains a stale unaccepted exact intent and cancels it without obsolete Knowledge authority', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const shown = await inspect(f, delivered, 'STALE-UNACCEPTED:UPPER'); + await changeDraft(f, delivered); + const before = await f.learning.rows(); + const refused = await f.invoke('review.stale-target', '/review', shown.packet); + expect(refused.status).toBe(503); + expect(await f.learning.rows()).toEqual(before); + const missing = await f.invoke('review.stale-missing-receipt', '/review-receipt', shown.packet); + expect(missing.status).toBe(200); + expect(await envelope(missing)).toEqual({ result: null, csrfToken: csrf }); + expect(await f.learning.rows()).toEqual(before); + await f.revokeKnowledge(); + const cancelled = await f.invoke('review.cancel-new-exact', '/review-cancel', shown.packet); + expect(cancelled.status).toBe(200); + expect((await envelope(cancelled)).result).toMatchObject({ outcome: 'cancelled', ticketId: learningTicketId }); + const rows = await f.learning.rows(); + expect(rows.filter((value) => value.kind === 'resolution_learning_review')).toHaveLength(0); + const receipt = await f.invoke('review.receipt-cancelled-exact', '/review-receipt', shown.packet); + expect(receipt.status).toBe(200); + expect((await envelope(receipt)).result).toMatchObject({ outcome: 'cancelled', ticketId: learningTicketId }); + expect(await f.learning.rows()).toEqual(rows); + }); + + it('rebuilds a genuine public SDK transaction in a later invocation after a native opaque-version conflict', async () => { + const f = await fixture(); + await f.learning.enrollAndVerify(); const delivered = await f.learning.delivered(); + const shown = await inspect(f, delivered, 'REAL-CONFLICT-RETRY:UPPER'); + expect((await f.invoke('review.conflict-admission', '/review-queue', shown.packet)).status).toBe(202); + expect(await f.deliver('review.proof-before-version-conflict')).toEqual({ acknowledgements: 0, delays: [30] }); + f.hooks.armed = true; + let entered = false; + f.hooks.beforeCommit = async () => { + delete f.hooks.beforeCommit; entered = true; await f.rewriteTicketVersion(); + }; + expect(await f.deliver('review.real-version-conflict')).toEqual({ acknowledgements: 0, delays: [30] }); + expect(entered).toBe(true); + expect(f.hooks.conflicts).toBeGreaterThanOrEqual(1); + expect(f.hooks.committed).toBe(0); + expect((await f.learning.rows()).filter((value) => value.kind === 'resolution_learning_review')).toHaveLength(0); + // The configured lease is25s. Keep the exact command, let that old claim + // expire, and run a new physical P2 invocation with fresh proof and CAS. + f.learning.advance(25_001); + expect(await f.deliver('review.real-version-conflict-retry')).toEqual({ acknowledgements: 1, delays: [] }); + const response = await f.invoke('review.real-version-conflict-receipt', '/review-queue-status', shown.packet); + expect(response.status).toBe(200); + expect((await envelope(response)).result).toMatchObject({ outcome: 'accepted' }); + expect(f.hooks.conflicts).toBeGreaterThanOrEqual(1); + expect(f.hooks.committed).toBe(1); + expect((await f.learning.rows()).filter((value) => value.kind === 'resolution_learning_review')).toHaveLength(1); + expect(f.learning.state.modelCalls).toBe(1); + }); + + for (const published of [false, true]) { + it('measures real multiple contributors with ' + (published ? 'current and published provenance' : 'current provenance only'), async () => { + const f = await fixture(); + const delivered = await multipleContributors(f, published); + const before = await f.learning.rows(); + const shown = await inspect(f, delivered, 'MULTI-CONTRIBUTOR:' + (published ? 'PUBLISHED' : 'CURRENT')); + expect(await f.learning.rows()).toEqual(before); + expect(shown.intent.target).toEqual(delivered.work.target); + expect((await f.invoke('review.multi-contributor-admission', '/review-queue', shown.packet)).status).toBe(202); + expect(await f.deliver('review.multi-contributor-proof')).toEqual({ acknowledgements: 0, delays: [30] }); + expect(await f.deliver('review.multi-contributor-commit')).toEqual({ acknowledgements: 1, delays: [] }); + const response = await f.invoke('review.multi-contributor', '/review-queue-status', shown.packet); + expect(response.status).toBe(200); + expect((await envelope(response)).result).toMatchObject({ outcome: 'accepted' }); + expect((await f.learning.rows()).filter((value) => value.kind === 'resolution_learning_review')).toHaveLength(1); + expect(f.learning.state.modelCalls).toBe(2); + }); + } +}); diff --git a/worker/src/support-learning-intake-recovery.d1.test.ts b/worker/src/support-learning-intake-recovery.d1.test.ts new file mode 100644 index 0000000..d5ffa48 --- /dev/null +++ b/worker/src/support-learning-intake-recovery.d1.test.ts @@ -0,0 +1,204 @@ +/// +import { AsyncLocalStorage } from 'node:async_hooks'; +import { env } from 'cloudflare:workers'; +import { createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { createSupportDeskApplication, supportRecords } from '@pegma/support-desk-application'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createStagedReviewFixture, responseObject, resultObject } from './support-learning-staged-review-fixture'; +import { learningTicketId } from './support-learning-fixtures'; +import type { SupportLearningReviewQueueMessage } from './support-learning-review-queue'; + +interface Budget { + readonly operation: string; + calls: number; + executed: number; + statements: number; + batches: number; + maximumParameters: number; + blocked: number; + status?: number; +} +const profiles: Budget[][] = []; + +beforeAll(async () => { + expect(String(env.IDENTITY_EMAIL_ENABLED)).toBe('false'); + // Test schema only, through the genuine adapter, outside measured requests. + const store = createCloudflareD1Store({ database: env.IDENTITY_DB }); + await store.collection(supportRecords).get({ partition: 'learning-intake-recovery-schema', id: 'absent' }); +}); +beforeEach(async () => { + profiles.length = 0; + // Per-file isolated D1 pool reset, matching existing Native suites. + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); +afterEach(({ task }) => { + Object.assign(task.meta, { supportLearningIntakeRecoveryD1Budget: structuredClone(profiles.flat()) }); + console.info('support-learning-intake-recovery-d1-budgets', JSON.stringify(profiles.flat())); +}); + +/** Observe actual binding calls, never SQL, results, codecs or Store decisions. + * A D1 batch counts one call; each statement keeps its real bound-parameter + * count. A refused 51st attempt is recorded but never delegated to D1. */ +function meter(backing: D1Database) { + const scope = new AsyncLocalStorage(); + const budgets: Budget[] = []; profiles.push(budgets); + const originals = new WeakMap(); + const parameters = new WeakMap(); + function charge(statements: readonly D1PreparedStatement[]) { + const budget = scope.getStore(); if (budget === undefined) return; + budget.calls += 1; budget.statements += statements.length; + budget.maximumParameters = Math.max(budget.maximumParameters, + ...statements.map((statement) => parameters.get(statement) ?? 0)); + if (budget.calls > 50 || budget.maximumParameters > 100) { + budget.blocked += 1; + throw new Error('Synthetic Workers Free intake recovery guard refused execution.'); + } + budget.executed += 1; + } + function observed(original: D1PreparedStatement, count = 0): D1PreparedStatement { + const statement: D1PreparedStatement = { + bind(...values: unknown[]) { return observed(original.bind(...values), values.length); }, + first>(column?: string): Promise { + charge([statement]); return column === undefined ? original.first() : original.first(column); + }, + all>() { charge([statement]); return original.all(); }, + run>() { charge([statement]); return original.run(); }, + raw: original.raw, + }; + statement.raw = new Proxy(original.raw, { apply(target, _receiver, args) { + charge([statement]); return Reflect.apply(target, original, args); + } }); + originals.set(statement, original); parameters.set(statement, count); return statement; + } + const database: D1Database = { + prepare(query) { return observed(backing.prepare(query)); }, + async batch(statements: D1PreparedStatement[]) { + charge(statements); const budget = scope.getStore(); if (budget !== undefined) budget.batches += 1; + const native = statements.map((statement) => { + const actual = originals.get(statement); + if (actual === undefined) throw new Error('Expected an observed genuine D1 statement.'); + return actual; + }); + return backing.batch(native); + }, + exec() { throw new Error('Runtime schema work is excluded from engineering request profiles.'); }, + dump() { throw new Error('Runtime D1 dump is excluded from engineering request profiles.'); }, + withSession() { throw new Error('The public adapter uses the direct D1 binding.'); }, + }; + return { + database, + budgets, + run(operation: string, action: () => Promise) { + const budget: Budget = { operation, calls: 0, executed: 0, statements: 0, + batches: 0, maximumParameters: 0, blocked: 0 }; + budgets.push(budget); + return scope.run(budget, async () => { + const response = await action(); + await response.clone().arrayBuffer(); + budget.status = response.status; + return response; + }); + }, + assertBounds() { + for (const budget of budgets) { + const detail = JSON.stringify(budget); + expect(budget.calls, detail).toBeLessThanOrEqual(50); + expect(budget.executed, detail).toBe(budget.calls); + expect(budget.maximumParameters, detail).toBeLessThanOrEqual(100); + expect(budget.blocked, detail).toBe(0); + } + }, + }; +} + +async function fixture() { + const observed = meter(env.IDENTITY_DB); + const store = createCloudflareD1Store({ database: observed.database, createSchemaIfMissing: false, readBatchSize: 512 }); + const f = await createStagedReviewFixture(store, { + context() { const value = createExecutionContext(); return { value, finish: () => waitOnExecutionContext(value) }; }, + environment(sender) { + const broker: Queue = { + async metrics() { return { backlogCount: 0, backlogBytes: 0 }; }, + async send(message) { await sender.send(message); return { metadata: { metrics: { backlogCount: 1, backlogBytes: 0 } } }; }, + async sendBatch() { throw new Error('Expected an individual opaque SDK hint'); }, + }; + return { ...env, IDENTITY_DB: observed.database, IDENTITY_EMAIL_CODE_SECRET_BASE64: btoa('q'.repeat(32)), + PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: 'true', SUPPORT_LEARNING_REVIEWS: broker }; + }, + }, { clockedAuthentication: true }); + return { ...f, observed }; +} + +describe('registered intake retry and reconciliation on clocked real Native D1', () => { + it('recovers the genuine discarded enrollment ACK before a changed revision under the full request meter', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const commandId = 'EXACT-UPPERCASE-ACK-RECOVERY'; const packet = JSON.stringify({ commandId, expectedRevision: ticket.revision }); + // The actual server commits, and this fixture deliberately discards that + // response. No accepted source or receipt value is constructed by the test. + expect((await f.invoke('/enroll', packet)).status).toBe(200); + const legacy = createSupportDeskApplication({ store: f.learning.store, clock: f.learning.clock }); + await legacy.addNote(f.learning.actors.staff, { ...f.learning.command('native-after-discarded-ack'), ticketId: learningTicketId, + messageId: 'native-after-ack-note', body: 'A real fictional edit after the earlier enrollment.' }); + const before = await f.learning.rows(); f.learning.state.product = 'missing'; + const recovered = await f.observed.run('enroll.recovery.accepted', () => f.invoke('/enroll-recovery', packet)); + expect(recovered.status).toBe(200); const result = resultObject(await responseObject(recovered)); + expect(result).toMatchObject({ outcome: 'accepted', operation: 'enroll', commandId, ticketId: learningTicketId }); + expect(result.result).toMatchObject({ ticketId: learningTicketId, state: 'unverified', sourceGeneration: 0 }); + expect(await f.learning.rows()).toEqual(before); expect(f.learning.state.modelCalls).toBe(0); f.observed.assertBounds(); + }); + + it.each(['missing', 'internal', 'unresolved', 'cycle'] as const)('fences a same-revision %s evidence prerequisite within the full clocked-session request budget', async (kind) => { + const f = await fixture(); let ticket = await f.learning.terminal(); + expect((await f.invoke('/enroll', JSON.stringify({ commandId: 'SETUP-CONTENT-NATIVE', expectedRevision: ticket.revision }))).status).toBe(200); + if (kind === 'unresolved') { + await f.learning.application.reopenTicket(f.learning.actors.staff, { ...f.learning.command('native-content-reopen'), ticketId: learningTicketId }); + ticket = (await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId)).ticket; + } + const view = await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId); + expect(view.ticket.revision).toBe(ticket.revision); + expect(view.messages.some((message) => message.id === 'learning-solution' && message.visibility === 'customer')).toBe(true); + expect(view.messages.some((message) => message.id === 'learning-note' && message.visibility === 'internal')).toBe(true); + const solutionRow = (await f.learning.rows()).find((row) => row.kind === 'message' && row.message.id === 'learning-solution'); + if (solutionRow?.kind !== 'message') throw new Error('Expected the genuine SDK solution row'); + expect(solutionRow.ordinal).toBeLessThanOrEqual(ticket.revision); + const commandId = 'EXACT-UPPERCASE-CONTENT-' + kind.toUpperCase(); + const packet = JSON.stringify({ commandId, expectedRevision: ticket.revision, resolutionCycle: kind === 'cycle' ? 2 : 1, + solutionMessageId: kind === 'missing' ? 'missing-visible-solution' : kind === 'internal' ? 'learning-note' : 'learning-solution', + verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' }); + const before = await f.learning.rows(); + expect((await f.invoke('/evidence', packet)).status).toBe(409); + const recovered = await f.observed.run('evidence.recovery.content.' + kind, () => f.invoke('/evidence-recovery', packet)); + expect(recovered.status).toBe(200); + expect(resultObject(await responseObject(recovered))).toEqual({ outcome: 'superseded', ticketId: learningTicketId, + commandId, operation: 'evidence', expectedRevision: ticket.revision, observedRevision: ticket.revision, + fence: kind === 'unresolved' ? 'resolution_unavailable' : kind === 'cycle' ? 'resolution_cycle_changed' : 'solution_unavailable' }); + expect(await f.learning.rows()).toEqual(before); expect(f.learning.state.modelCalls).toBe(0); f.observed.assertBounds(); + }); + + it.each(['enroll', 'evidence'] as const)('fences the exact stale %s revision within50calls/100parameters', async (operation) => { + const f = await fixture(); const ticket = await f.learning.terminal(); + if (operation === 'evidence') { + const accepted = await f.invoke('/enroll', JSON.stringify({ commandId: 'SETUP-ENROLL-EXACT', expectedRevision: ticket.revision })); + expect(accepted.status).toBe(200); + } + const commandId = 'EXACT-UPPERCASE-' + operation.toUpperCase(); + const packet = JSON.stringify({ commandId, expectedRevision: ticket.revision, + ...(operation === 'evidence' ? { resolutionCycle: 1, solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' } : {}) }); + const legacy = createSupportDeskApplication({ store: f.learning.store, clock: f.learning.clock }); + await legacy.addNote(f.learning.actors.staff, { ...f.learning.command('native-intake-revision'), ticketId: learningTicketId, + messageId: 'native-intake-competing-note', body: 'An independent fictional staff note advances the real revision.' }); + const original = await f.invoke('/' + operation, packet); expect(original.status).toBe(409); + const before = await f.learning.rows(); + const recovered = await f.observed.run(operation + '.recovery.stale', () => f.invoke('/' + operation + '-recovery', packet)); + expect(recovered.status).toBe(200); + expect(resultObject(await responseObject(recovered))).toMatchObject({ outcome: 'superseded', operation, + ticketId: learningTicketId, commandId, expectedRevision: ticket.revision, observedRevision: ticket.revision + 1 }); + expect(await f.learning.rows()).toEqual(before); expect(f.learning.state.modelCalls).toBe(0); + const observations = f.sessionObservations.filter((value) => value.previousLastSeenAt !== null); + expect(observations.length).toBeGreaterThan(2); + expect(observations.every((value) => value.previousLastSeenAt !== null && Date.parse(value.at) > Date.parse(value.previousLastSeenAt))).toBe(true); + f.observed.assertBounds(); + }); +}); diff --git a/worker/src/support-learning-ports.ts b/worker/src/support-learning-ports.ts new file mode 100644 index 0000000..28a423a --- /dev/null +++ b/worker/src/support-learning-ports.ts @@ -0,0 +1,120 @@ +import type { AccessContext } from '@pegma/authorization-core'; +import type { KnowledgeBaseApplication } from '@pegma/knowledge-base-application'; +import type { + LearningKnowledgeApplication, + SupportDeskLearningOptions, +} from '@pegma/support-desk-ai'; + +/** A host resolver must read current facts and honor cancellation. */ +export interface SupportLearningStaffAccess { + resolve( + principalId: string, + signal: AbortSignal, + ): Promise; +} + +/** Durable review admission is explicitly opt-in and independent of model generation. */ +export interface SupportLearningStagedReviewOptions { + readonly enabled: () => boolean; + /** Best-effort acceleration after durable SDK admission; never review authority. */ + readonly enqueue: (key: { readonly ticketId: string; readonly commandId: string }) => Promise; +} + +/** These are trusted server ports, never a browser or model response envelope. */ +export type SupportLearningProcessingPorts = Pick< + SupportDeskLearningOptions, + | 'serviceAccess' + | 'knowledgeAccess' + | 'retirementAccess' + | 'configuration' + | 'checks' + | 'model' + | 'usage' + | 'targets' + | 'tokenCounter' +>; + +export type DirectLearningKnowledge = Pick< + KnowledgeBaseApplication, + keyof LearningKnowledgeApplication +>; + +/** + * Support 0.2.5 uses the same exact KB 0.1.5 public contracts as this host. + * Forward the narrow capability surface and preserve actual error identity. + */ +export function createSupportLearningKnowledgePort( + application: DirectLearningKnowledge, +): LearningKnowledgeApplication { + async function call(operation: () => Promise): Promise { + return operation(); + } + return Object.freeze({ + searchPublishedArticles: (access, input) => + call(() => application.searchPublishedArticles(access, input)), + getPublishedArticle: (access, input) => + call(() => application.getPublishedArticle(access, input)), + getDraft: (access, input) => call(() => application.getDraft(access, input)), + getProvenance: (access, input) => + call(() => application.getProvenance(access, input)), + getValidationRequirements: (access, input) => + call(() => application.getValidationRequirements(access, input)), + createDraft: (access, input) => + call(() => application.createDraft(access, input)), + updateDraft: (access, input) => + call(() => application.updateDraft(access, input)), + retireArticle: (access, input) => + call(() => application.retireArticle(access, input)), + }); +} + +export type SupportLearningStaffOperation = + | 'enroll' + | 'verified_fix' + | 'review' + | 'invalidate' + | 'withdraw'; + +function identifier(value: string): string { + if ( + typeof value !== 'string' || + value.length === 0 || + value.length > 200 || + /[\u0000-\u001f\u007f]/u.test(value) + ) + throw new TypeError('Invalid learning command identity'); + return value; +} + +/** + * Retain the exact client identifier. Only the server correlation identity is + * derived. Its domain includes the authenticated actor, operation and ticket; + * a new HTTP attempt cannot accidentally change the SDK command fingerprint. + * This digest is an operation identity, never authentication or a credential. + */ +export async function supportLearningCommandIdentity(input: { + readonly principalId: string; + readonly ticketId: string; + readonly operation: SupportLearningStaffOperation; + readonly clientCommandId: string; +}): Promise<{ + readonly commandId: string; + readonly correlationId: string; +}> { + const actor = identifier(input.principalId); + const ticket = identifier(input.ticketId); + const commandId = identifier(input.clientCommandId); + const operation = input.operation; + if ( + !['enroll', 'verified_fix', 'review', 'invalidate', 'withdraw'].includes( + operation, + ) + ) + throw new TypeError('Invalid learning operation'); + const bytes = new TextEncoder().encode( + JSON.stringify(['pegma.support-learning.command.v1', actor, ticket, operation, commandId]), + ); + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); + const hash = Array.from(digest, (part) => part.toString(16).padStart(2, '0')).join(''); + return Object.freeze({ commandId, correlationId: `learning:${hash}` }); +} diff --git a/worker/src/support-learning-review-queue.d1.test.ts b/worker/src/support-learning-review-queue.d1.test.ts new file mode 100644 index 0000000..91fa842 --- /dev/null +++ b/worker/src/support-learning-review-queue.d1.test.ts @@ -0,0 +1,379 @@ +/// + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { env } from 'cloudflare:workers'; +import { createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { auditRecordId } from '@pegma/audit'; +import { supportAudit, supportRecords } from '@pegma/support-desk-application'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { isPlainObject } from './api-auth'; +import { KNOWLEDGE_ROLE } from './support-access'; +import { createStagedReviewFixture, responseObject, resultObject, type StagedReviewFixtureOptions } from './support-learning-staged-review-fixture'; +import type { SupportLearningReviewQueueMessage } from './support-learning-review-queue'; + +interface Profile { + readonly operation: string; + calls: number; + executed: number; + batches: number; + statements: number; + maximumParameters: number; + blocked: number; +} +const profiles: Profile[] = []; +// Only an explicitly registered negative transport/port diagnostic may expect +// attempted calls beyond50. Executed calls must still stop at50 exactly. +const expectedRefusals = new Set(); + +beforeAll(async () => { + await createCloudflareD1Store({ database: env.IDENTITY_DB }).collection(supportRecords) + .get({ partition: 'staged-review-schema-probe', id: 'absent' }); +}); +beforeEach(async () => { + profiles.length = 0; + expectedRefusals.clear(); + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); +afterEach(({ task }) => { + Object.assign(task.meta, { supportLearningStagedReviewD1Budget: structuredClone(profiles) }); + for (const profile of profiles) { + const detail = JSON.stringify(profile); + expect(profile.calls, detail).toBeGreaterThan(0); + expect(profile.executed, detail).toBeLessThanOrEqual(50); + if (expectedRefusals.has(profile.operation)) { + expect(profile.calls, detail).toBeGreaterThan(50); + expect(profile.executed, detail).toBe(50); + expect(profile.blocked, detail).toBeGreaterThanOrEqual(1); + expect(profile.blocked, detail).toBe(profile.calls - profile.executed); + } else { + expect(profile.calls, detail).toBeLessThanOrEqual(50); + expect(profile.executed, detail).toBe(profile.calls); + expect(profile.blocked, detail).toBe(0); + } + expect(profile.maximumParameters, detail).toBeLessThanOrEqual(100); + } +}); + +/** Genuine D1 execution boundary: each batch is charged once, every statement + * retains its own parameter ceiling, and attempted query51 throws immediately. */ +function meter(database: D1Database) { + const scope = new AsyncLocalStorage(); + const originals = new WeakMap(); + const parameters = new WeakMap(); + function charge(statements: readonly D1PreparedStatement[], batch = false) { + const current = scope.getStore(); if (current === undefined) return; + current.calls += 1; current.statements += statements.length; + if (batch) current.batches += 1; + for (const statement of statements) current.maximumParameters = Math.max(current.maximumParameters, parameters.get(statement) ?? 0); + if (current.calls > 50 || current.maximumParameters > 100) { + current.blocked += 1; throw new Error('Workers Free staged learning review D1 budget exceeded'); + } + current.executed += 1; + } + function observe(original: D1PreparedStatement, count = 0): D1PreparedStatement { + const statement: D1PreparedStatement = { + bind(...values: unknown[]) { return observe(original.bind(...values), values.length); }, + first>(column?: string): Promise { + charge([statement]); return column === undefined ? original.first() : original.first(column); + }, + all>() { charge([statement]); return original.all(); }, + run>() { charge([statement]); return original.run(); }, + raw: original.raw, + }; + statement.raw = new Proxy(original.raw, { apply(target, _receiver, args) { + charge([statement]); return Reflect.apply(target, original, args); + } }); + originals.set(statement, original); parameters.set(statement, count); return statement; + } + const binding: D1Database = { + prepare(query) { return observe(database.prepare(query)); }, + batch(statements: D1PreparedStatement[]) { + charge(statements, true); + return database.batch(statements.map((statement) => { + const original = originals.get(statement); + if (original === undefined) throw new Error('Expected an observed statement'); return original; + })); + }, + exec() { throw new Error('Runtime schema initialization is unavailable'); }, + dump() { throw new Error('Runtime dump is unavailable'); }, + withSession() { throw new Error('Expected the actual direct binding'); }, + }; + return { binding, run(operation: string, action: () => Promise): Promise { + const profile: Profile = { operation, calls: 0, executed: 0, batches: 0, statements: 0, maximumParameters: 0, blocked: 0 }; + profiles.push(profile); return scope.run(profile, action); + } }; +} +async function fixture(options: StagedReviewFixtureOptions = {}) { + const observed = meter(env.IDENTITY_DB); + const store = createCloudflareD1Store({ database: observed.binding, createSchemaIfMissing: false, readBatchSize: 512 }); + const f = await createStagedReviewFixture(store, { + context() { + const value = createExecutionContext(); + return { value, finish: () => waitOnExecutionContext(value) }; + }, + environment(sender) { + // Only broker delivery is scripted. The database remains the actual + // observed Workers-pool binding; no fake DB or authentication is supplied. + const broker: Queue = { + async metrics() { return { backlogCount: 0, backlogBytes: 0 }; }, + async send(message) { + await sender.send(message); + return { metadata: { metrics: { backlogCount: 1, backlogBytes: 0 } } }; + }, + async sendBatch() { throw new Error('The review producer must send one hint'); }, + }; + return { ...env, IDENTITY_DB: observed.binding, + IDENTITY_EMAIL_CODE_SECRET_BASE64: btoa('q'.repeat(32)), + PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: 'true', SUPPORT_LEARNING_REVIEWS: broker }; + }, + }, options); + return { f, run: observed.run }; +} + +/** Assertion-only session readback is outside the measured invocation. Every + * protected HTTP fence itself uses the real advancing Identity/Sessions clock. */ +async function afterSessionIdle( + f: Awaited>['f'], run: ReturnType['run'], + operation: string, action: () => Promise, +): Promise { + // Published Sessions has no coarser touch interval: now>lastSeenAt writes. + // Two seconds crosses that boundary without expiring/renewing source proofs. + f.learning.advance(2_000); + const first = f.sessionObservations.length; + const result = await run(operation, action).finally(() => { + const reads = f.sessionObservations.slice(first); + const profile = profiles.at(-1); + if (profile?.operation !== operation) throw new Error('Expected the measured invocation profile'); + Object.assign(profile, { sessionReadObservations: reads.length, idleAdvanceMilliseconds: 2_000, + strictlyAdvancingSessionReads: reads.filter((read) => read.previousLastSeenAt !== null && + Date.parse(read.at) > Date.parse(read.previousLastSeenAt)).length }); + }); + const reads = f.sessionObservations.slice(first); + expect(reads.length, operation + ' must observe actual session fences').toBeGreaterThan(1); + for (const [index, read] of reads.entries()) { + expect(read.previousLastSeenAt, operation).not.toBeNull(); + if (read.previousLastSeenAt === null) throw new Error('Expected the actual live session'); + expect(Date.parse(read.at), operation).toBeGreaterThan(Date.parse(read.previousLastSeenAt)); + if (index > 0) expect(read.previousLastSeenAt, operation + ' persisted previous fence touch').toBe(reads[index - 1]?.at); + } + const last = reads.at(-1); + if (last === undefined) throw new Error('Expected the final observed session fence'); + // Same-time public get cannot advance this anchor. It proves that the final + // request fence's best-effort touch actually persisted through Native D1. + expect((await f.readSessionAt(last.at))?.lastSeenAt, operation + ' persisted final touch').toBe(last.at); + const profile = profiles.at(-1); + if (profile?.operation !== operation) throw new Error('Expected the measured invocation profile'); + Object.assign(profile, { sessionTouches: reads.length, verifiedPersistedTouch: true, idleAdvanceMilliseconds: 2_000 }); + return result; +} + +/** Verify public Audit mapping and actual Native D1 encoding after completion. + * No codec or alternate writer is manufactured. These assertion-only reads + * are outside the measured request and cannot affect its recorded budget. */ +async function assertPersistedStageAuditEncoding(f: Awaited>['f']) { + const records = f.learning.store.collection(supportRecords); + const rows = await records.list('learning-ticket'); + const admission = rows.find((row) => row.kind === 'audit' && + row.event.action === 'support.learning.review_requested'); + if (admission?.kind !== 'audit') throw new Error('Expected the actual staged admission Audit row'); + const commandId = admission.event.details?.commandId; + if (typeof commandId !== 'string') throw new Error('Expected the retained original SDK command identity'); + const eventId = String.fromCharCode(0) + 'support.learning.review.requested:' + commandId; + const key = auditRecordId(eventId); + expect(admission.event.id).toBe(eventId); + expect(admission.id).toBe(key); + expect(key.startsWith('audit|%00support.learning.review.requested:')).toBe(true); + expect(key).not.toContain(String.fromCharCode(0)); + expect(await records.get({ partition: 'learning-ticket', id: key })).toEqual(admission); + const literalPercentKey = auditRecordId('%00support.learning.review.requested:' + commandId); + expect(literalPercentKey.startsWith('audit|%2500support.learning.review.requested:')).toBe(true); + expect(literalPercentKey).not.toBe(key); + const history = await supportAudit.history(records, 'learning-ticket'); + expect(history.some((event) => event.id === eventId)).toBe(true); + const reviewed = rows.find((row) => row.kind === 'audit' && + row.event.action === 'support.learning.reviewed' && row.event.details?.commandId === commandId); + if (reviewed?.kind !== 'audit') throw new Error('Expected the actual final review Audit row'); + expect(reviewed.id).toBe(auditRecordId(commandId)); + expect(reviewed.id).not.toBe(key); + expect(await records.get({ partition: 'learning-ticket', id: reviewed.id })).toEqual(reviewed); + + const physical = await env.IDENTITY_DB.prepare( + 'SELECT row_key, record_json FROM RECORDS WHERE partition_key = ? AND row_key = ? AND deleted = 0', + ).bind(supportRecords.name + ':learning-ticket', key).first<{ row_key: string; record_json: string }>(); + if (physical === null) throw new Error('Expected the actual physical D1 admission Audit row'); + expect(physical.row_key).toBe(key); + expect(physical.row_key).not.toContain(String.fromCharCode(0)); + expect(physical.record_json).not.toContain(String.fromCharCode(0)); + const encoded: unknown = JSON.parse(physical.record_json); + if (!isPlainObject(encoded) || typeof encoded.payload !== 'string') + throw new Error('Expected the actual Support JSON codec payload'); + expect(encoded.id).toBe(key); + expect(encoded.payload).not.toContain(String.fromCharCode(0)); + expect(encoded.payload).toContain('\\u0000support.learning.review.requested:'); + const decodedPayload: unknown = JSON.parse(encoded.payload); + if (!isPlainObject(decodedPayload) || !isPlainObject(decodedPayload.event)) + throw new Error('Expected the actual decoded Audit event'); + expect(decodedPayload.event.id).toBe(eventId); +} + +describe('whole staged review Worker invocations on real Native D1', () => { + it('counts proposal, durable admission, separate P1/P2, duplicate and historical recovery under hard50', async () => { + const { f, run } = await fixture(); const delivered = await f.checked(); + const packet = await run('http.proposal', () => f.prepare(delivered.source.sourceGeneration)); + const admitted = await run('http.admit', () => f.invoke('/review-queue', packet.body)); + expect(admitted.status).toBe(202); + expect(resultObject(await responseObject(admitted)).outcome).toBe('pending'); + const models = f.learning.state.modelCalls; const message = f.messages[0]!; + expect(await run('queue.proof', () => f.deliver(message))).toEqual({ acknowledgements: 0, delays: [30] }); + expect(resultObject(await responseObject(await run('http.pending', () => f.invoke('/review-queue-status', packet.body))))) + .toMatchObject({ outcome: 'pending', phase: 'commit' }); + expect(await run('queue.commit', () => f.deliver(message))).toEqual({ acknowledgements: 1, delays: [] }); + const budgetBeforeAuditReadback = structuredClone(profiles); + await assertPersistedStageAuditEncoding(f); + expect(profiles).toEqual(budgetBeforeAuditReadback); + expect(await run('queue.duplicate', () => f.deliver(message))).toEqual({ acknowledgements: 1, delays: [] }); + await f.revoke(KNOWLEDGE_ROLE); f.learning.advance(3_600_001); + const receipt = await run('http.receipt-after-kb-revoke-and-expiry', () => f.invoke('/review-queue-status', packet.body)); + expect(receipt.status).toBe(200); expect(resultObject(await responseObject(receipt)).outcome).toBe('accepted'); + const replay = await run('http.admission-replay-after-kb-revoke-and-expiry', () => f.invoke('/review-queue', packet.body)); + expect(replay.status).toBe(200); expect(resultObject(await responseObject(replay)).outcome).toBe('accepted'); + expect(f.learning.state.modelCalls).toBe(models); + }); + + it('measures fresh cancellation separately and never permits its delayed P2 to accept', async () => { + const { f, run } = await fixture(); const delivered = await f.checked(); + const packet = await f.prepare(delivered.source.sourceGeneration); + expect((await run('http.admit', () => f.invoke('/review-queue', packet.body))).status).toBe(202); + const message = f.messages[0]!; await run('queue.proof', () => f.deliver(message)); + await f.revoke(KNOWLEDGE_ROLE); + const response = await run('http.cancel', () => f.invoke('/review-queue-cancel', packet.body)); + expect(response.status).toBe(200); expect(resultObject(await responseObject(response)).outcome).toBe('cancelled'); + expect(await run('queue.cancelled-duplicate', () => f.deliver(message))).toEqual({ acknowledgements: 1, delays: [] }); + expect((await f.learning.application.readResolutionLearningSource(f.learning.actors.staff, 'learning-ticket')).reviewBindingCount).toBe(0); + }); + + it('rediscovers a lost post-admission send with separate bounded scheduled pages', async () => { + const { f, run } = await fixture(); const delivered = await f.checked(); + const packet = await f.prepare(delivered.source.sourceGeneration); f.state.sendFailure = true; + expect((await run('http.admit-lost-send', () => f.invoke('/review-queue', packet.body))).status).toBe(202); + expect(f.messages).toHaveLength(0); f.state.sendFailure = false; + for (let page = 0; page < 256 && f.messages.length === 0; page++) await run('scheduled.scan.' + page, () => f.scan()); + expect(f.messages).toHaveLength(1); + expect(resultObject(await responseObject(await run('http.pending-after-scan', () => f.invoke('/review-queue-status', packet.body))))) + .toMatchObject({ outcome: 'pending', phase: 'proof' }); + }); + + it.each([false, true])('preserves both current contributors and distinct published history=%s under each physical cap', async (published) => { + const { f, run } = await fixture(); const delivered = await f.multipleContributors(published); + expect(delivered.provenance.snapshot.references.map((value) => value.resourceId).sort()) + .toEqual(['learning-ticket', delivered.secondaryTicketId].sort()); + if (published) expect(delivered.provenance.publishedSnapshot?.references.map((value) => value.resourceId)) + .toEqual([delivered.secondaryTicketId]); + else expect(delivered.provenance.publishedSnapshot).toBeUndefined(); + const packet = await run('http.two-contributors.proposal', () => f.prepare(delivered.source.sourceGeneration)); + expect((await run('http.two-contributors.admit', () => f.invoke('/review-queue', packet.body))).status).toBe(202); + const message = f.messages[0]!; + expect(await run('queue.two-contributors.proof', () => f.deliver(message))).toEqual({ acknowledgements: 0, delays: [30] }); + expect(await run('queue.two-contributors.commit', () => f.deliver(message))).toEqual({ acknowledgements: 1, delays: [] }); + expect(resultObject(await responseObject(await run('http.two-contributors.receipt', () => f.invoke('/review-queue-status', packet.body)))).outcome) + .toBe('accepted'); + }); + + it('meters actual Identity/Sessions clock touches before prepare, admission, status and cancellation', async () => { + const { f, run } = await fixture({ clockedAuthentication: true }); + expect(Date.parse(f.identityCreatedAt)).toBeGreaterThan(Date.parse(f.authenticationClockStartedAt)); + const delivered = await f.checked(); + const packet = await afterSessionIdle(f, run, 'http.idle.proposal', () => f.prepare(delivered.source.sourceGeneration)); + expect((await afterSessionIdle(f, run, 'http.idle.admit', () => f.invoke('/review-queue', packet.body))).status).toBe(202); + const message = f.messages[0]!; + expect(await run('queue.idle.proof', () => f.deliver(message))).toEqual({ acknowledgements: 0, delays: [30] }); + const pending = await afterSessionIdle(f, run, 'http.idle.pending', () => f.invoke('/review-queue-status', packet.body)); + expect(pending.status).toBe(200); expect(resultObject(await responseObject(pending)).outcome).toBe('pending'); + const cancelled = await afterSessionIdle(f, run, 'http.idle.cancel', () => f.invoke('/review-queue-cancel', packet.body)); + expect(cancelled.status).toBe(200); expect(resultObject(await responseObject(cancelled)).outcome).toBe('cancelled'); + expect(await run('queue.idle.cancelled', () => f.deliver(message))).toEqual({ acknowledgements: 1, delays: [] }); + }); + + it('meters session touches with two current contributors and distinct complete published provenance', async () => { + const { f, run } = await fixture({ clockedAuthentication: true }); + const delivered = await f.multipleContributors(true); + expect(delivered.provenance.snapshot.references.map((entry) => entry.resourceId).sort()) + .toEqual(['learning-ticket', delivered.secondaryTicketId].sort()); + expect(delivered.provenance.publishedSnapshot?.references.map((entry) => entry.resourceId)).toEqual([delivered.secondaryTicketId]); + const packet = await afterSessionIdle(f, run, 'http.idle.multi.proposal', () => f.prepare(delivered.source.sourceGeneration)); + expect((await afterSessionIdle(f, run, 'http.idle.multi.admit', () => f.invoke('/review-queue', packet.body))).status).toBe(202); + const message = f.messages[0]!; + expect(await run('queue.idle.multi.proof', () => f.deliver(message))).toEqual({ acknowledgements: 0, delays: [30] }); + const pending = await afterSessionIdle(f, run, 'http.idle.multi.pending', () => f.invoke('/review-queue-status', packet.body)); + expect(pending.status).toBe(200); expect(resultObject(await responseObject(pending)).outcome).toBe('pending'); + expect(await run('queue.idle.multi.commit', () => f.deliver(message))).toEqual({ acknowledgements: 1, delays: [] }); + const accepted = await afterSessionIdle(f, run, 'http.idle.multi.receipt', () => f.invoke('/review-queue-status', packet.body)); + expect(accepted.status).toBe(200); expect(resultObject(await responseObject(accepted)).outcome).toBe('accepted'); + }); + + it('refuses an out-of-qualified-profile custom source wrapper at hard50 without review or KB effects', async () => { + const observed = new Set(); let delayedReads = 0; + const { f, run } = await fixture({ + async beforeSourceRead(ticketId) { + observed.add(ticketId); + if (ticketId === 'staged-secondary-ticket') { + delayedReads += 1; + await new Promise((resolve) => setTimeout(resolve, 5)); + } + }, + }); + const delivered = await f.multipleContributors(true); observed.clear(); delayedReads = 0; + const models = f.learning.state.modelCalls; + expect(delivered.provenance.snapshot.references.map((entry) => entry.resourceId).sort()) + .toEqual(['learning-ticket', delivered.secondaryTicketId].sort()); + expect(delivered.provenance.publishedSnapshot?.references.map((entry) => entry.resourceId)).toEqual([delivered.secondaryTicketId]); + const rowsBefore = await f.learning.rows(); + const draftBefore = await f.learning.knowledge.getDraft(f.learning.actors.admin, { articleId: delivered.articleId }); + const provenanceBefore = await f.learning.knowledge.getProvenance(f.learning.actors.admin, { articleId: delivered.articleId }); + const publishedBefore = await f.learning.knowledge.getPublishedArticle(f.learning.actors.customer, { articleId: delivered.articleId }); + observed.clear(); delayedReads = 0; + const operation = 'http.unqualified-custom-source.proposal'; + expectedRefusals.add(operation); + let invocationSourceReads: { readonly delayed: number; readonly distinct: number } | undefined; + try { + // This additional asynchronous wrapper is absent from the known real + // SDK graph under test. It is a fail-closed diagnostic, not a successful + // arbitrary-port budget claim. Do not admit or deliver a review afterward. + const response = await run(operation, () => f.invoke('/proposal?sourceGeneration=' + delivered.source.sourceGeneration)); + invocationSourceReads = { delayed: delayedReads, distinct: observed.size }; + expect(response.status).toBe(503); + expect(await responseObject(response)).toEqual({ error: 'support_learning_unavailable' }); + expect(profiles).toHaveLength(1); + const refused = profiles[0]; + if (refused === undefined) throw new Error('Expected the actual refused invocation'); + expect(refused.operation).toBe(operation); + expect(refused.executed).toBe(50); + expect(refused.calls).toBeGreaterThan(50); + expect(refused.blocked).toBeGreaterThanOrEqual(1); + expect(refused.blocked).toBe(refused.calls - refused.executed); + expect([...observed].sort()).toEqual(['learning-ticket', delivered.secondaryTicketId].sort()); + expect(delayedReads).toBeGreaterThan(0); + expect(f.messages).toHaveLength(0); + // Complete public Support rows cover review bindings, receipts, Audit + // and durable attempts, rather than guessing private record encoders. + expect(await f.learning.rows()).toEqual(rowsBefore); + expect(await f.learning.knowledge.getDraft(f.learning.actors.admin, { articleId: delivered.articleId })).toEqual(draftBefore); + expect(await f.learning.knowledge.getProvenance(f.learning.actors.admin, { articleId: delivered.articleId })).toEqual(provenanceBefore); + expect(await f.learning.knowledge.getPublishedArticle(f.learning.actors.customer, { articleId: delivered.articleId })).toEqual(publishedBefore); + expect(f.learning.state.modelCalls).toBe(models); + const profile = profiles[0]; + if (profile === undefined) throw new Error('Expected the actual refused invocation'); + Object.assign(profile, { noDomainEffectsVerified: true }); + } finally { + // Preserve causal diagnostics even when the strict binding guard refuses + // a phase; a red profile is never turned into successful completion. + for (const profile of profiles) Object.assign(profile, { + profileClassification: 'out_of_qualified_profile_custom_source_wrapper', + sourceReadDelayMilliseconds: 5, delayedSourceReads: invocationSourceReads?.delayed ?? delayedReads, + distinctObservedSources: invocationSourceReads?.distinct ?? observed.size, + }); + } + }); +}); diff --git a/worker/src/support-learning-review-queue.test.ts b/worker/src/support-learning-review-queue.test.ts new file mode 100644 index 0000000..7dc9dee --- /dev/null +++ b/worker/src/support-learning-review-queue.test.ts @@ -0,0 +1,207 @@ +import { createMemoryStore, type Store } from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { createSupportLearningReviewQueue, type SupportLearningReviewQueueMessage } from './support-learning-review-queue'; +import { createStagedReviewFixture } from './support-learning-staged-review-fixture'; + +// These isolate transport/cursor mechanics with actual public Store persistence. +// Real SDK review/authority and Native binding budgets are tested separately. +function fixture() { + const backing = createMemoryStore(); + const state = { enabled: true, process: 'pending' as 'pending' | 'settled', + physicalRows: 1, cursor: 'page-two' as string | null, held: false, + scanFailure: false, sendFailure: false, processFailure: false, + afterProcess: undefined as (() => Promise) | undefined, + afterScan: undefined as (() => Promise) | undefined, + storeGets: 0 }; + const key = { ticketId: 'fictional-ticket', commandId: 'EXACT-UPPERCASE-command' }; + const scans: ({ limit: 1; cursor?: string })[] = []; + const deliveries: SupportLearningReviewQueueMessage[] = []; + const process = vi.fn(async () => { + if (state.processFailure) throw new Error('Synthetic private dependency failure'); + await state.afterProcess?.(); + return state.process; + }); + const scanPending = vi.fn(async (bounds: { limit: 1; cursor?: string }) => { + scans.push(bounds); + if (state.scanFailure) throw new Error('Synthetic scan failure'); + await state.afterScan?.(); + return { candidates: state.physicalRows === 0 ? [] : [{ ...key, held: state.held }], + physicalRows: state.physicalRows, pages: 1 as const, nextCursor: state.cursor }; + }); + const send = vi.fn(async (message: SupportLearningReviewQueueMessage) => { + if (state.sendFailure) throw new Error('Synthetic send failure'); + deliveries.push(message); + }); + const create = (store: Store = backing) => createSupportLearningReviewQueue({ + enabled: () => state.enabled, + store: () => { state.storeGets += 1; return store; }, + clock: { now: () => '2026-11-11T12:00:00.000Z' }, + logger: { log() { throw new Error('Synthetic logger failure'); } }, + runtime: () => ({ scanPending, process }), sender: { send }, newId: () => 'fictional-worker', + }); + const queue = create(); + return { backing, state, key, scans, deliveries, process, scanPending, send, queue, create }; +} + +function delivery(body: unknown) { + const ack = vi.fn(); const retry = vi.fn(); + const message = { id: 'synthetic-delivery', timestamp: new Date('2026-11-11T12:00:00.000Z'), + body, attempts: 1, ack, retry }; + const batch: MessageBatch = { queue: 'pegma-dev-support-learning-reviews', + messages: [message], metadata: { metrics: { backlogCount: 1, backlogBytes: 0 } }, ackAll: vi.fn(), retryAll: vi.fn() }; + return { batch, ack, retry }; +} + +describe('durable learning review queue transport', () => { + it('defaults off before persistence, runtime construction or send', async () => { + const store = vi.fn(() => { throw new Error('Unexpected Store'); }); + const runtime = vi.fn(() => { throw new Error('Unexpected runtime'); }); + const send = vi.fn(); + const queue = createSupportLearningReviewQueue({ store, runtime, sender: { send }, + clock: { now: () => { throw new Error('Unexpected clock'); } }, logger: { log() {} } }); + const item = delivery({ version: 1, key: 'a'.repeat(64) }); + await queue.enqueue({ ticketId: 'fictional', commandId: 'same' }); await queue.runPage(); await queue.consume(item.batch); + expect(store).not.toHaveBeenCalled(); expect(runtime).not.toHaveBeenCalled(); expect(send).not.toHaveBeenCalled(); + expect(item.ack).not.toHaveBeenCalled(); expect(item.retry).toHaveBeenCalledWith({ delaySeconds: 30 }); + }); + + it('uses opaque messages, one phase per delivery, and the same key through P1/P2', async () => { + const f = fixture(); await f.queue.enqueue(f.key); + const body = f.deliveries[0]!; + expect(body).toEqual({ version: 1, key: expect.stringMatching(/^[a-f0-9]{64}$/u) }); + expect(JSON.stringify(body)).not.toContain(f.key.ticketId); + const proof = delivery(body); await f.queue.consume(proof.batch); + expect(f.process).toHaveBeenCalledTimes(1); expect(proof.ack).not.toHaveBeenCalled(); + expect(proof.retry).toHaveBeenCalledWith({ delaySeconds: 30 }); + f.state.process = 'settled'; + const commit = delivery(body); await f.create().consume(commit.batch); + expect(f.process).toHaveBeenCalledTimes(2); expect(commit.ack).toHaveBeenCalledOnce(); + const duplicate = delivery(body); await f.create().consume(duplicate.batch); + expect(duplicate.ack).toHaveBeenCalledOnce(); expect(f.process).toHaveBeenCalledTimes(2); + }); + + it('does not change durable acknowledgement when send and logger both throw; scan repairs the lost send', async () => { + const f = fixture(); f.state.sendFailure = true; + await expect(f.queue.enqueue(f.key)).resolves.toBeUndefined(); + f.state.sendFailure = false; await f.create().runPage(); + expect(f.deliveries).toHaveLength(1); + await f.queue.consume(delivery(f.deliveries[0]).batch); + expect(f.process).toHaveBeenCalledOnce(); + }); + + it('retries a failed phase without losing the pointer or launching another phase', async () => { + const f = fixture(); await f.queue.enqueue(f.key); f.state.processFailure = true; + const failed = delivery(f.deliveries[0]); await f.queue.consume(failed.batch); + expect(failed.retry).toHaveBeenCalledOnce(); expect(failed.ack).not.toHaveBeenCalled(); + f.state.processFailure = false; await f.create().consume(delivery(f.deliveries[0]).batch); + expect(f.process).toHaveBeenCalledTimes(2); + }); + + it('keeps a newer hint when an older worker finishes', async () => { + const f = fixture(); await f.queue.enqueue(f.key); f.state.process = 'settled'; + f.state.afterProcess = async () => { f.state.afterProcess = undefined; await f.queue.enqueue(f.key); }; + await f.queue.consume(delivery(f.deliveries[0]).batch); + await f.queue.consume(delivery(f.deliveries[0]).batch); + expect(f.process).toHaveBeenCalledTimes(2); + }); + + it('recovers a newer terminal hint whose send and old delivery retry were both lost', async () => { + const f = fixture(); await f.queue.enqueue(f.key); f.state.process = 'settled'; + f.state.afterProcess = async () => { + f.state.afterProcess = undefined; f.state.sendFailure = true; + await f.queue.enqueue(f.key); + }; + const old = delivery(f.deliveries[0]); await f.queue.consume(old.batch); + expect(old.ack).not.toHaveBeenCalled(); expect(old.retry).toHaveBeenCalledOnce(); + // The SDK no longer enumerates a terminal command. Only the independent + // host-hint cycle can rediscover this orphaned acceleration row. + f.deliveries.length = 0; f.state.physicalRows = 0; f.state.sendFailure = false; + await f.create().runPage(); expect(f.deliveries).toHaveLength(0); + await f.create().runPage(); expect(f.deliveries).toHaveLength(1); + const recovered = delivery(f.deliveries[0]); await f.create().consume(recovered.batch); + expect(recovered.ack).toHaveBeenCalledOnce(); + }); + + it('does not checkpoint a failed scan/send and resumes its exact cursor after reconstruction', async () => { + const f = fixture(); await f.queue.runPage(); + await f.create().runPage(); // the independent hint lane + f.state.sendFailure = true; await f.create().runPage(); + f.state.sendFailure = false; await f.create().runPage(); + expect(f.scans).toEqual([{ limit: 1 }, { limit: 1, cursor: 'page-two' }, { limit: 1, cursor: 'page-two' }]); + expect(f.process).not.toHaveBeenCalled(); + }); + + it('completes full cursor cycles and rotates past held work without pretending it settled', async () => { + const f = fixture(); f.state.held = true; f.state.cursor = null; + for (let index = 0; index < 4; index++) await f.create().runPage(); + expect(f.scans).toEqual([{ limit: 1 }, { limit: 1 }]); + expect(f.send).not.toHaveBeenCalled(); expect(f.process).not.toHaveBeenCalled(); + }); + + it('fences a stale null→cursor→null checkpoint worker with monotone generation', async () => { + const f = fixture(); let release = () => {}; let entered = () => {}; + const paused = new Promise((resolve) => { release = resolve; }); + const ready = new Promise((resolve) => { entered = resolve; }); + f.state.afterScan = async () => { f.state.afterScan = undefined; entered(); await paused; }; + const old = f.queue.runPage(); await ready; + f.state.cursor = 'peer'; await f.create().runPage(); + await f.create().runPage(); // hint cursor moves independently + f.state.cursor = null; await f.create().runPage(); + await f.create().runPage(); + f.state.cursor = 'stale'; + release(); await old; + f.state.cursor = null; + await f.create().runPage(); + expect(f.scans.at(-1)).toEqual({ limit: 1 }); + }); + + it('rejects oversized pages and malformed messages before processing', async () => { + const f = fixture(); f.state.physicalRows = 2; + await f.queue.runPage(); expect(f.send).not.toHaveBeenCalled(); + for (const body of [null, { version: 1, key: 'bad' }, { version: 1, key: 'a'.repeat(64), actor: 'untrusted' }]) { + const item = delivery(body); await f.queue.consume(item.batch); expect(item.ack).toHaveBeenCalledOnce(); + } + expect(f.process).not.toHaveBeenCalled(); + }); + + it('refuses batch amplification before persistence or runtime work', async () => { + const f = fixture(); const one = delivery({ version: 1, key: 'a'.repeat(64) }); + await f.queue.consume({ ...one.batch, messages: [...one.batch.messages, ...one.batch.messages] }); + expect(one.retry).toHaveBeenCalledTimes(2); expect(f.state.storeGets).toBe(0); expect(f.process).not.toHaveBeenCalled(); + }); + + it('observes the live switch again after a phase and preserves uncertain work', async () => { + const f = fixture(); await f.queue.enqueue(f.key); f.state.process = 'settled'; + f.state.afterProcess = async () => { f.state.enabled = false; }; + const item = delivery(f.deliveries[0]); await f.queue.consume(item.batch); + expect(item.ack).not.toHaveBeenCalled(); expect(item.retry).toHaveBeenCalledOnce(); + f.state.enabled = true; f.state.afterProcess = undefined; + await f.create().consume(delivery(f.deliveries[0]).batch); expect(f.process).toHaveBeenCalledTimes(2); + }); +}); + + +describe('staged review authentication calendar', () => { + it('anchors actual clocked Identity/Sessions to the current epoch while preserving learning elapsed time', async () => { + const startedAt = Date.now(); + const f = await createStagedReviewFixture(createMemoryStore(), undefined, { clockedAuthentication: true }); + expect(Date.parse(f.authenticationClockStartedAt)).toBeGreaterThanOrEqual(startedAt); + expect(Date.parse(f.authenticationClockStartedAt)).toBeLessThanOrEqual(Date.now()); + expect(Date.parse(f.identityCreatedAt)).toBeGreaterThan(Date.parse(f.authenticationClockStartedAt)); + const logicalStartedAt = Date.parse(f.learning.clock.now()); + const delivered = await f.checked(); + const packet = await f.prepare(delivered.source.sourceGeneration); + const first = f.sessionObservations.at(-1); + if (first === undefined) throw new Error('Expected real browser session fences.'); + f.learning.advance(2_000); + expect((await f.invoke('/review-queue', packet.body)).status).toBe(202); + const last = f.sessionObservations.at(-1); + if (last === undefined) throw new Error('Expected the real closing session fence.'); + expect(Date.parse(last.at) - Date.parse(first.at)).toBeGreaterThanOrEqual(2_000); + expect(Date.parse(f.learning.clock.now()) - logicalStartedAt).toBeGreaterThanOrEqual(2_000); + const session = await f.readSessionAt(last.at); + expect(session?.lastSeenAt).toBe(last.at); + if (session === null) throw new Error('Expected the actual live session.'); + expect(Date.parse(session.expiresAt)).toBeGreaterThan(Date.now()); + }); +}); diff --git a/worker/src/support-learning-review-queue.ts b/worker/src/support-learning-review-queue.ts new file mode 100644 index 0000000..9e54761 --- /dev/null +++ b/worker/src/support-learning-review-queue.ts @@ -0,0 +1,251 @@ +import type { Clock, Logger } from '@pegma/spine'; +import { defineCollection, type Store } from '@pegma/storage-core'; + +interface ReviewKey { + readonly ticketId: string; + readonly commandId: string; +} + +/** Transport-facing projection of the SDK worker. It grants no review authority. */ +export interface SupportLearningReviewDispatch { + scanPending(input: { readonly limit: 1; readonly cursor?: string }): Promise<{ + readonly candidates: readonly (ReviewKey & { readonly held: boolean })[]; + readonly physicalRows: number; + readonly pages: 1; + readonly nextCursor: string | null; + }>; + /** One freshly claimed SDK phase; never run a second phase in this invocation. */ + process(input: ReviewKey & { + readonly workerId: string; + readonly leaseMilliseconds: number; + }): Promise<'pending' | 'settled'>; +} + +export interface SupportLearningReviewQueueMessage { + readonly version: 1; + readonly key: string; +} + +export interface SupportLearningReviewQueueOptions { + readonly enabled?: () => boolean; + readonly store: () => Store; + readonly clock: Clock; + readonly logger: Logger; + readonly runtime: () => SupportLearningReviewDispatch; + readonly sender: { + send(message: SupportLearningReviewQueueMessage): Promise; + }; + readonly newId?: () => string; +} + +interface Hint extends ReviewKey { + readonly id: string; + readonly version: 1; +} +interface Checkpoint { + readonly id: 'cursor'; + readonly sdkCursor: string; + readonly hintCursor: string; + readonly next: 'sdk' | 'hints'; + readonly generation: number; +} +const PARTITION = 'reviews'; +const MAX_CURSOR = 16_384; +const RETRY_SECONDS = 30; + +function scalar(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= 200 && + !/[\u0000-\u001f\u007f-\u009f]/u.test(value); +} +function cursor(value: unknown): value is string | null { + return value === null || (typeof value === 'string' && value.length > 0 && value.length <= MAX_CURSOR); +} +function canonicalTime(clock: Clock): void { + const value = clock.now(); + if (typeof value !== 'string' || !Number.isFinite(Date.parse(value)) || + new Date(value).toISOString() !== value) throw new TypeError('Invalid review dispatcher clock'); +} +function checkedHint(value: Hint): Hint { + if (Object.keys(value).length !== 4 || !/^[a-f0-9]{64}$/u.test(value.id) || + value.version !== 1 || !scalar(value.ticketId) || !scalar(value.commandId)) + throw new TypeError('Invalid review dispatch hint'); + return value; +} +const hints = defineCollection({ + name: 'pegma-dev.support-learning-review-hints.v1', + key: (value) => ({ partition: PARTITION, id: value.id }), + codec: { + encode: (value) => ({ ...checkedHint(value) }), + decode(value) { + if (Object.keys(value).length !== 4 || typeof value.id !== 'string' || + typeof value.ticketId !== 'string' || typeof value.commandId !== 'string' || value.version !== 1) + throw new TypeError('Invalid review dispatch hint'); + return checkedHint({ id: value.id, ticketId: value.ticketId, commandId: value.commandId, version: 1 }); + }, + }, +}); +function checkedCheckpoint(value: Checkpoint): Checkpoint { + const physicalCursor = (value: string) => value === 'end' || (value.startsWith('next:') && cursor(value.slice(5))); + if (Object.keys(value).length !== 5 || value.id !== 'cursor' || + !Number.isSafeInteger(value.generation) || value.generation < 1 || + !['sdk', 'hints'].includes(value.next) || !physicalCursor(value.sdkCursor) || !physicalCursor(value.hintCursor)) + throw new TypeError('Invalid review dispatch checkpoint'); + return value; +} +const checkpoints = defineCollection({ + name: 'pegma-dev.support-learning-review-dispatch.v1', + key: () => ({ partition: PARTITION, id: 'cursor' }), + codec: { + encode: (value) => ({ ...checkedCheckpoint(value) }), + decode(value) { + if (Object.keys(value).length !== 5 || value.id !== 'cursor' || + typeof value.sdkCursor !== 'string' || typeof value.hintCursor !== 'string' || + (value.next !== 'sdk' && value.next !== 'hints') || typeof value.generation !== 'number') + throw new TypeError('Invalid review dispatch checkpoint'); + return checkedCheckpoint({ id: 'cursor', sdkCursor: value.sdkCursor, hintCursor: value.hintCursor, + next: value.next, generation: value.generation }); + }, + }, +}); + +async function opaqueKey(input: ReviewKey): Promise { + if (!scalar(input.ticketId) || !scalar(input.commandId)) throw new TypeError('Invalid review dispatch key'); + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode( + JSON.stringify(['pegma.support-learning.review-hint.v1', input.ticketId, input.commandId]), + )); + return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, '0')).join(''); +} +function message(value: unknown): value is SupportLearningReviewQueueMessage { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return false; + return Object.keys(value).length === 2 && 'version' in value && value.version === 1 && + 'key' in value && typeof value.key === 'string' && /^[a-f0-9]{64}$/u.test(value.key); +} + +/** Lossy acceleration only. SDK pending rows, claims and receipts are authoritative. */ +export function createSupportLearningReviewQueue(options: SupportLearningReviewQueueOptions) { + function enabled(): boolean { + try { return options.enabled?.() === true; } catch { return false; } + } + function current(): void { + if (!enabled()) throw new Error('Review dispatcher disabled'); + canonicalTime(options.clock); + } + function diagnostic(stage: string): void { + try { options.logger.log('warn', 'support.learning_review_dispatch.unavailable', { stage }); } + catch { /* Diagnostics cannot alter a durable review or its acknowledgement. */ } + } + async function send(input: ReviewKey): Promise { + current(); + const id = await opaqueKey(input); + current(); + await options.store().collection(hints).put({ ...input, id, version: 1 }); + current(); + await options.sender.send({ version: 1, key: id }); + current(); + } + return Object.freeze({ + /** Run only AFTER the SDK has durably admitted the exact review command. */ + async enqueue(input: ReviewKey): Promise { + if (!enabled()) return; + try { await send(input); } catch { diagnostic('enqueue'); } + }, + /** Alternate one SDK page and one hint page; never perform a review phase here. */ + async runPage(): Promise { + if (!enabled()) return; + try { + current(); + const collection = options.store().collection(checkpoints); + const key = { partition: PARTITION, id: 'cursor' }; + const prior = await collection.get(key); + current(); + const generation = prior?.generation ?? 0; + if (generation === Number.MAX_SAFE_INTEGER) throw new RangeError('Review dispatch generation exhausted'); + const lane = prior?.next ?? 'sdk'; + const sdkCursor = prior?.sdkCursor ?? 'end'; + const hintCursor = prior?.hintCursor ?? 'end'; + const before = lane === 'sdk' ? sdkCursor : hintCursor; + let nextCursor: string | null; + if (lane === 'sdk') { + const page = await options.runtime().scanPending({ limit: 1, + ...(before === 'end' ? {} : { cursor: before.slice(5) }) }); + current(); + if (!Number.isSafeInteger(page.physicalRows) || page.physicalRows < 0 || page.physicalRows > 1 || + page.pages !== 1 || !Array.isArray(page.candidates) || page.candidates.length > page.physicalRows || + !cursor(page.nextCursor)) throw new TypeError('Invalid review dispatch page'); + for (const candidate of page.candidates) { + if (!scalar(candidate.ticketId) || !scalar(candidate.commandId) || typeof candidate.held !== 'boolean') + throw new TypeError('Invalid review dispatch candidate'); + if (!candidate.held) await send({ ticketId: candidate.ticketId, commandId: candidate.commandId }); + } + nextCursor = page.nextCursor; + } else { + // Existing hints can outlive a terminal SDK request when a newer put + // loses its send. Re-delivery confirms current SDK absence/receipt; + // neither cursor nor transport age is itself a completion proof. + const page = await options.store().collection(hints).scan({ limit: 1, + ...(before === 'end' ? {} : { cursor: before.slice(5) }) }); + current(); + if (!Array.isArray(page.records) || page.records.length > 1 || !cursor(page.nextCursor)) + throw new TypeError('Invalid review hint page'); + for (const row of page.records) { + if (row.key.partition !== PARTITION || row.key.id !== row.value.id || + await opaqueKey(row.value) !== row.value.id) throw new TypeError('Invalid review hint binding'); + current(); + await options.sender.send({ version: 1, key: row.value.id }); + current(); + } + nextCursor = page.nextCursor; + } + current(); + const next = nextCursor === null ? 'end' : 'next:' + nextCursor; + await collection.update(key, (actual) => { + if (!enabled() || (actual?.generation ?? 0) !== generation || (actual?.sdkCursor ?? 'end') !== sdkCursor || + (actual?.hintCursor ?? 'end') !== hintCursor || (actual?.next ?? 'sdk') !== lane) + return { action: 'keep' }; + return { action: 'write', value: { id: 'cursor', sdkCursor: lane === 'sdk' ? next : sdkCursor, + hintCursor: lane === 'hints' ? next : hintCursor, next: lane === 'sdk' ? 'hints' : 'sdk', generation: generation + 1 } }; + }, { maxAttempts: 1 }); + } catch { diagnostic('scan'); } + }, + /** One Queue delivery is one physical invocation and at most one SDK phase. */ + async consume(batch: MessageBatch): Promise { + if (batch.messages.length !== 1) { + for (const item of batch.messages) item.retry({ delaySeconds: RETRY_SECONDS }); + return; + } + const item = batch.messages[0]; + if (item === undefined) return; + if (!enabled()) { item.retry({ delaySeconds: RETRY_SECONDS }); return; } + // Refuse malformed transport data without touching persistence or the SDK. + if (!message(item.body)) { item.ack(); return; } + try { + current(); + const collection = options.store().collection(hints); + const key = { partition: PARTITION, id: item.body.key }; + const hint = await collection.getVersioned(key); + current(); + if (hint === null) { item.ack(); return; } + if (hint.value.id !== item.body.key || await opaqueKey(hint.value) !== item.body.key) + throw new TypeError('Invalid review hint binding'); + current(); + const workerId = options.newId?.() ?? crypto.randomUUID(); + if (!scalar(workerId)) throw new TypeError('Invalid review worker identity'); + const outcome = await options.runtime().process({ ticketId: hint.value.ticketId, + commandId: hint.value.commandId, workerId, leaseMilliseconds: 25_000 }); + current(); + if (outcome === 'settled') { + const removed = await collection.deleteIfUnchanged(key, hint.version); + current(); + if (removed) item.ack(); + else item.retry({ delaySeconds: RETRY_SECONDS }); + } else { + if (outcome !== 'pending') throw new TypeError('Invalid review worker outcome'); + item.retry({ delaySeconds: RETRY_SECONDS }); + } + } catch { + diagnostic('process'); + item.retry({ delaySeconds: RETRY_SECONDS }); + } + }, + }); +} diff --git a/worker/src/support-learning-routing.test.ts b/worker/src/support-learning-routing.test.ts new file mode 100644 index 0000000..58ee386 --- /dev/null +++ b/worker/src/support-learning-routing.test.ts @@ -0,0 +1,227 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { ADMIN_ROLE, APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE } from './support-access'; +import { createSupportApi } from './support-api'; +import { createSupportRuntime } from './support-desk'; +import { createSupportLearningRuntime } from './support-learning'; +import { createSupportLearningFixture, learningTicketId } from './support-learning-fixtures'; +import { createSupportLearningHandlers } from './support-learning-handlers'; + +type Actor = 'staff' | 'support' | 'customer' | 'admin' | 'knowledge'; +const base = '/api/support/admin/tickets/' + learningTicketId; +async function json(response: Response) { + const value: unknown = await response.json(); + if (!isPlainObject(value)) throw new Error('Expected actual route JSON'); + return value; +} +async function fixture() { + const store = createMemoryStore(); + const learning = await createSupportLearningFixture(store); + const logger = { log() {} }; + const identityRuntime = createIdentityRuntime({ store, emailCodeSecretBase64: btoa('r'.repeat(32)), + emailFrom: 'Pegma ', emailEnabled: false }, logger); + const { identity, sessions } = identityRuntime; + const host = createSupportRuntime({ store, identity, sessions, logger, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }); + const principals = { staff: learning.actors.staff.principalId, support: 'synthetic-routing-support', + customer: learning.actors.customer.principalId, admin: 'synthetic-routing-admin', knowledge: 'synthetic-routing-knowledge' }; + const cookies = new Map(); + const csrf = new Map(); + const ids = new Map(); + for (const [index, actor] of (Object.keys(principals) as Actor[]).entries()) { + const principalId = principals[actor]; + await identity.provisionVerifiedUser({ principalId, email: actor + '@example.test' }); + const sessionId = String(index + 1).repeat(43); + const token = String.fromCharCode(97 + index).repeat(43); + await sessions.create(sessionId, { principalId, data: JSON.stringify({ version: 1, + issuer: IDENTITY_ISSUER, subject: principalId, csrfToken: token }) }); + cookies.set(actor, SESSION_COOKIE + '=' + sessionId); csrf.set(actor, token); ids.set(actor, sessionId); + const roles = actor === 'staff' ? [SUPPORT_ROLE, KNOWLEDGE_ROLE] : actor === 'support' ? [SUPPORT_ROLE] + : actor === 'admin' ? [ADMIN_ROLE] : actor === 'knowledge' ? [KNOWLEDGE_ROLE] : []; + for (const role of roles) await host.roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'routing-' + actor + '-' + role, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-routing' }, grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'routing-grant-' + actor + '-' + role }); + } + const authority = { identity, sessions, logger, roleStore: host.roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }; + const resolve = createAgentPrincipalResolver(authority); + const runtime = createSupportLearningRuntime({ application: learning.application, knowledge: learning.knowledge, + sources: learning.sources, clock: learning.clock, ports: learning.ports, + staffAccess: { resolve }, processingEnabled: () => learning.state.enabled }); + const state = { enabled: true, flagResult: true as unknown, flagThrows: false, + afterDetail: undefined as (() => Promise) | undefined, + afterHandler: undefined as (() => Promise) | undefined }; + const actualHandler = createSupportLearningHandlers({ ...authority, + enabled: () => state.enabled, runtime: () => runtime, limiter: host.replyLimiter }); + const learningHandler = async (request: Request) => { + const response = await actualHandler(request); await state.afterHandler?.(); return response; + }; + const options = { ...authority, createLimiter: host.createLimiter, replyLimiter: host.replyLimiter, + application: { ...learning.application, async readStaffTicket(...args: Parameters) { + const value = await learning.application.readStaffTicket(...args); await state.afterDetail?.(); return value; + } } }; + const configured = { learningHandler, learningEnabled: () => { + if (state.flagThrows) throw new Error('Synthetic flag unavailable'); + return state.flagResult === true; + } }; + const api = createSupportApi({ ...options, ...configured }); + function request(path = base, actor: Actor = 'staff', body?: unknown, extra: Record = {}) { + return new Request(IDENTITY_ISSUER + path, { method: body === undefined ? 'GET' : 'POST', + headers: { Cookie: cookies.get(actor)!, ...extra, ...(body === undefined ? {} : { + Origin: IDENTITY_ISSUER, 'Sec-Fetch-Site': 'same-origin', 'X-Pegma-CSRF': csrf.get(actor)!, 'Content-Type': 'application/json' }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + } + async function revoke(actor: Actor, role: string) { + const id = 'routing-' + actor + '-' + role; + const row = await host.roleStore.getRoleAssignment(id); + if (row === null) throw new Error('Missing actual audited assignment'); + await host.roleStore.revokeRoleAssignmentWithAudit({ assignmentId: id, expectedConcurrencyToken: row.concurrencyToken, + revokedBy: { kind: 'system', systemId: 'synthetic-routing' }, revokedAtEpochMs: Date.now(), auditEventId: 'routing-revoke-' + actor + '-' + role }); + } + return { learning, identityRuntime, identity, sessions, host, options, configured, api, request, state, revoke, + cookies, csrf, ids, principals, actualHandler }; +} + +describe('optional public learning namespace through actual Support router/auth/SDK', () => { + it('keeps the old staff and customer detail JSON unchanged when the callback is omitted', async () => { + const f = await fixture(); await f.learning.terminal(); + const legacy = createSupportApi(f.options); + const before = await json(await legacy(f.request())); + expect(before).not.toHaveProperty('learningEnabled'); + expect(Object.keys(before).sort()).toEqual(['csrfToken', 'messages', 'ticket']); + const customerPath = '/api/support/tickets/' + learningTicketId; + const customer = await json(await legacy(f.request(customerPath, 'customer'))); + const configuredCustomer = await json(await f.api(f.request(customerPath, 'customer'))); + expect(configuredCustomer).toEqual(customer); + expect(configuredCustomer).not.toHaveProperty('learningEnabled'); + }); + + it('preserves actual legacy customer reply receipts through the optional router', async () => { + const f = await fixture(); await f.learning.terminal(); + const legacy = createSupportApi(f.options); + const principal = f.principals.customer; + const packet = { command: { version: 1, expectedAccountId: principal, + commandId: principal + '~ABCDEFAB-1234-4ABC-8DEF-ABCDEF123456', + messageId: principal + '~ABCDEFAB-1234-4ABC-8DEF-ABCDEF123457' }, body: 'A fictional follow-up question.' }; + const path = '/api/support/tickets/' + learningTicketId + '/replies'; + const first = await legacy(f.request(path, 'customer', packet, { 'X-Pegma-Support-Command': '1' })); + expect(first.status).toBe(201); + const rows = JSON.stringify(await f.learning.rows()); + const repeated = await f.api(f.request(path, 'customer', packet, { 'X-Pegma-Support-Command': '1' })); + expect(repeated.status).toBe(201); + const current = await json(repeated); + expect(current).toEqual(await json(first)); + expect(current).not.toHaveProperty('learningEnabled'); + expect(JSON.stringify(await f.learning.rows())).toBe(rows); + }); + it('issues a current boolean from actual stored Support and session authority without role claims', async () => { + const f = await fixture(); await f.learning.terminal(); + const current = await json(await f.api(f.request())); + expect(current.learningEnabled).toBe(true); + expect(current.csrfToken).toBe(f.csrf.get('staff')); + expect(current).not.toHaveProperty('roles'); + const supportOnly = await json(await f.api(f.request(base, 'support'))); + expect(supportOnly.learningEnabled).toBe(true); + for (const actor of ['admin', 'knowledge', 'customer'] as const) + expect((await f.api(f.request(base, actor))).status).toBe(403); + }); + + it.each(['absent', 'flag-only', 'handler-only', 'false', 'throws', 'non-true'] as const)( + 'keeps the %s composition OFF404, including the legacy browser-command header', async (mode) => { + const f = await fixture(); await f.learning.terminal(); + f.state.flagResult = mode === 'false' ? false : mode === 'non-true' ? 'true' : true; + f.state.flagThrows = mode === 'throws'; + const composition = mode === 'absent' ? {} : mode === 'flag-only' ? { learningEnabled: f.configured.learningEnabled } + : mode === 'handler-only' ? { learningHandler: f.configured.learningHandler } : f.configured; + const api = createSupportApi({ ...f.options, ...composition }); + for (const suffix of ['', '/enroll', '/unknown']) { + const response = await api(f.request(base + '/learning' + suffix, 'staff', suffix === '' ? undefined + : { commandId: 'EXACT-UPPERCASE', expectedRevision: 1 }, { 'X-Pegma-Support-Command': '1' })); + expect(response.status).toBe(404); + expect(await json(response)).toEqual({ error: 'not_found' }); + } + const detail = await json(await api(f.request())); + if (mode === 'absent' || mode === 'handler-only') expect(detail).not.toHaveProperty('learningEnabled'); + else expect(detail.learningEnabled).toBe(false); + }, + ); + + it('dispatches genuine enrollment/evidence/proposal/review and exact replay before generic browser routing', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const enroll = { commandId: 'ENROLL-EXACT-UPPERCASE', expectedRevision: ticket.revision }; + const enrolled = await f.api(f.request(base + '/learning/enroll', 'staff', enroll, { 'X-Pegma-Support-Command': '1' })); + expect(enrolled.status).toBe(200); + const source = (await json(enrolled)).result; + if (!isPlainObject(source)) throw new Error('Expected actual source result'); + const evidence = { commandId: 'EVIDENCE-EXACT-UPPERCASE', expectedRevision: ticket.revision, + resolutionCycle: source.resolutionCycle, solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' }; + expect((await f.api(f.request(base + '/learning/evidence', 'staff', evidence))).status).toBe(200); + const delivered = await f.learning.delivered(); + const shown = await json(await f.api(f.request(base + '/learning/proposal?sourceGeneration=' + delivered.source.sourceGeneration))); + if (!isPlainObject(shown.result)) throw new Error('Expected actual checked proposal'); + if (!isPlainObject(shown.result.intent)) throw new Error('Expected the actual complete SDK review intent'); + const packet = { commandId: 'REVIEW-EXACT-UPPERCASE', intent: shown.result.intent, decision: 'approve' }; + const first = await f.api(f.request(base + '/learning/review', 'staff', packet)); + expect(first.status).toBe(200); + const rows = JSON.stringify(await f.learning.rows()); + const replay = await f.api(f.request(base + '/learning/review', 'staff', packet)); + expect(replay.status).toBe(200); + expect(await json(replay)).toEqual(await json(first)); + expect(JSON.stringify(await f.learning.rows())).toBe(rows); + const draft = await f.learning.knowledge.getDraft(f.learning.actors.staff, { articleId: delivered.articleId }); + expect(draft.state).not.toBe('published'); + }); + + it('keeps source/work separate from actual Knowledge permission and never derives access from a query', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + expect((await f.api(f.request(base + '/learning/enroll', 'staff', { commandId: 'ENROLL', expectedRevision: ticket.revision }))).status).toBe(200); + const source = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect((await f.api(f.request(base + '/learning', 'support'))).status).toBe(200); + expect((await f.api(f.request(base + '/learning/proposal?sourceGeneration=' + source.sourceGeneration, 'support'))).status).toBe(403); + const forgedQuery = await f.api(f.request(base + '/learning?role=Support', 'admin')); + // The closing real current-authority fence wins over the malformed query. + expect(forgedQuery.status).toBe(403); + expect(await json(forgedQuery)).toEqual({ error: 'forbidden' }); + expect((await f.api(f.request(base + '/learning', 'admin'))).status).toBe(403); + }); + + it.each(['session', 'role'] as const)('withholds the capability and private detail after actual %s loss during the read', async (kind) => { + const f = await fixture(); await f.learning.terminal(); + f.state.afterDetail = async () => { + f.state.afterDetail = undefined; + if (kind === 'session') await f.sessions.destroy(f.ids.get('staff')!); + else await f.revoke('staff', SUPPORT_ROLE); + }; + const response = await f.api(f.request()); + expect(response.status).toBe(kind === 'session' ? 401 : 403); + const denied = await json(response); + expect(denied).not.toHaveProperty('ticket'); + expect(denied).not.toHaveProperty('learningEnabled'); + }); + + it('rechecks the current route flag after an actual committed mutation without inventing rollback', async () => { + const f = await fixture(); const ticket = await f.learning.terminal(); + const packet = { commandId: 'COMMIT-EXACT-UPPERCASE', expectedRevision: ticket.revision }; + f.state.afterHandler = async () => { f.state.flagResult = false; }; + expect((await f.api(f.request(base + '/learning/enroll', 'staff', packet))).status).toBe(404); + const actual = await f.learning.runtime.readSource(f.learning.actors.staff, learningTicketId); + expect(actual.state).toBe('unverified'); + f.state.afterHandler = undefined; f.state.flagResult = true; + const rows = JSON.stringify(await f.learning.rows()); + expect((await f.api(f.request(base + '/learning/enroll', 'staff', packet))).status).toBe(200); + expect(JSON.stringify(await f.learning.rows())).toBe(rows); + }); + + it('never falls unknown learning subpaths through to a legacy mutation', async () => { + const f = await fixture(); await f.learning.terminal(); + const before = JSON.stringify(await f.learning.rows()); + expect((await f.api(f.request(base + '/learning/not-an-operation', 'staff', { action: 'close' }, { 'X-Pegma-Support-Command': '1' }))).status).toBe(404); + expect(JSON.stringify(await f.learning.rows())).toBe(before); + }); +}); diff --git a/worker/src/support-learning-staged-review-fixture.ts b/worker/src/support-learning-staged-review-fixture.ts new file mode 100644 index 0000000..f96b29a --- /dev/null +++ b/worker/src/support-learning-staged-review-fixture.ts @@ -0,0 +1,271 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createIdentity, createHmacEmailCodeProtector } from '@pegma/identity'; +import { createSessionStore } from '@pegma/sessions'; +import type { Clock } from '@pegma/spine'; +import type { Store } from '@pegma/storage-core'; +import { createSupportDeskApplication } from '@pegma/support-desk-application'; +import { learningTargetBinding } from '@pegma/support-desk-ai'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { createWorker } from './index'; +import { CLEANUP_CRON, cleanupLaneAt } from './maintenance-schedule'; +import { APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE } from './support-access'; +import { createSupportApi } from './support-api'; +import { createSupportRuntime } from './support-desk'; +import { createSupportLearningRuntime, type SupportLearningRuntimeOptions } from './support-learning'; +import { createSupportLearningFixture, learningTicketId } from './support-learning-fixtures'; +import { createSupportLearningReviewQueue, type SupportLearningReviewQueueMessage } from './support-learning-review-queue'; + +const sessionId = 's'.repeat(43); +const csrf = 'c'.repeat(43); +const base = '/api/support/admin/tickets/' + learningTicketId + '/learning'; + +type WorkerEnvironment = Parameters['queue']>[1]; +export interface StagedReviewWorkerHarness { + /** Native supplies its actual environment, including the metered D1 binding. */ + environment(sender: { send(message: SupportLearningReviewQueueMessage): Promise }): WorkerEnvironment; + /** Native supplies the public Workers-pool context and continuation waiter. */ + context(): { readonly value: ExecutionContext; finish(): Promise }; +} +export interface StagedReviewFixtureOptions { + /** Real Identity/Sessions clock: current calendar plus learning elapsed time. */ + readonly clockedAuthentication?: boolean; + /** Delay only; every source observation still comes from the actual SDK. */ + readonly beforeSourceRead?: (ticketId: string) => void | Promise; +} + +export async function responseObject(response: Response) { + const value: unknown = await response.json(); + if (!isPlainObject(value)) throw new Error('Expected the actual HTTP response'); + return value; +} +export function resultObject(value: Record) { + if (!isPlainObject(value.result)) throw new Error('Expected the actual SDK result'); + return value.result; +} + +/** Shared real SDK/Identity/Sessions/RoleStore fixture. Only broker and the + * existing fictional product/check/model connectors are scripted. */ +export async function createStagedReviewFixture(store: Store, workerHarness?: StagedReviewWorkerHarness, + fixtureOptions: StagedReviewFixtureOptions = {}) { + const learning = await createSupportLearningFixture(store, { stagedReviews: true, readScheduling: 'sdk', + ...(fixtureOptions.beforeSourceRead === undefined ? {} : { beforeSourceRead: fixtureOptions.beforeSourceRead }) }); + const state = { enabled: true, stagedEnabled: true, sendFailure: false, throwingLogger: false, + targetArticleId: undefined as string | undefined, + afterDraft: undefined as (() => Promise) | undefined }; + const logger = { log() { if (state.throwingLogger) throw new Error('Synthetic logger failure'); } }; + const identityLinkFromClaims = identityLinkKeyFromVerifiedIdentityClaims; + const authenticationLearningStartedAt = Date.parse(learning.clock.now()); + const authenticationWallStartedAt = Date.now(); + const authenticationClockStartedAt = fixtureOptions.clockedAuthentication === true + ? new Date(authenticationWallStartedAt).toISOString() : learning.clock.now(); + const authClock: Clock | undefined = fixtureOptions.clockedAuthentication === true ? { + now() { + // Preserve every real touch and logical SDK advance, but anchor absolute + // session expiry to the same current calendar as the browser fence. + learning.advance(1); + return new Date(authenticationWallStartedAt + Date.parse(learning.clock.now()) - + authenticationLearningStartedAt).toISOString(); + }, + } : undefined; + const sessionObservations: { readonly at: string; readonly previousLastSeenAt: string | null }[] = []; + function authority() { + const base = createIdentityRuntime({ store, + emailCodeSecretBase64: btoa('q'.repeat(32)), emailFrom: 'Pegma ', emailEnabled: false }, logger); + let identity = base.identity; + let sessions = base.sessions; + if (authClock !== undefined) { + const [registrationLimiter, authenticationLimiter, emailCodeRequestLimiter, emailCodeVerificationLimiter] = base.limiters; + if (registrationLimiter === undefined || authenticationLimiter === undefined || + emailCodeRequestLimiter === undefined || emailCodeVerificationLimiter === undefined) + throw new Error('Expected the actual host Identity limiter graph'); + identity = createIdentity({ store, issuer: IDENTITY_ISSUER, rpName: 'Pegma', rpID: 'pegma.dev', + origins: [IDENTITY_ISSUER], registrationLimiter, authenticationLimiter, + emailCodeRequestLimiter, emailCodeVerificationLimiter, + emailCodeProtector: createHmacEmailCodeProtector(new Uint8Array(32).fill(113)), clock: authClock }); + const actualSessions = createSessionStore(store, { logger, clock: authClock }); + sessions = { ...actualSessions, async get(id, at = authClock.now()) { + const result = await actualSessions.get(id, at); + sessionObservations.push({ at, previousLastSeenAt: result?.lastSeenAt ?? null }); + return result; + } }; + } + const host = createSupportRuntime({ store, identity, sessions, logger, identityLinkFromClaims }); + return { identity, sessions, host, options: { identity, sessions, logger, identityLinkFromClaims, roleStore: host.roleStore } }; + } + const seed = authority(); + const principalId = learning.actors.staff.principalId; + const seededIdentity = await seed.identity.provisionVerifiedUser({ principalId, email: 'reviewer@example.test' }); + await seed.sessions.create(sessionId, { principalId, data: JSON.stringify({ version: 1, + issuer: IDENTITY_ISSUER, subject: principalId, csrfToken: csrf }) }); + for (const role of [SUPPORT_ROLE, KNOWLEDGE_ROLE]) { + const granted = await seed.host.roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'staged-review-' + role, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'fictional-staged-review' }, grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'staged-review-grant-' + role }); + if (granted.status !== 'granted') throw new Error('Real fixture role grant failed'); + } + const messages: SupportLearningReviewQueueMessage[] = []; + const sender = { async send(message: SupportLearningReviewQueueMessage) { + if (state.sendFailure) throw new Error('Synthetic broker failure'); + messages.push(structuredClone(message)); + } }; + const enabled = () => state.enabled; + const stagedEnabled = () => state.enabled && state.stagedEnabled; + function graph() { + const current = authority(); + const resolve = createAgentPrincipalResolver(current.options); + let queue: ReturnType; + const learningOptions: Omit = { + application: learning.application, + knowledge: { ...learning.knowledge, async getDraft(...args: Parameters) { + const value = await learning.knowledge.getDraft(...args); await state.afterDraft?.(); return value; + } }, + sources: learning.sources, clock: learning.clock, + ports: { ...learning.ports, targets: { + async resolveScope(...args) { + const value = await learning.ports.targets.resolveScope(...args); + return value.outcome === 'ready' && state.targetArticleId !== undefined + ? { ...value, scope: { ...value.scope, explicitDraftIds: [state.targetArticleId] } } : value; + }, + async select(input, context) { + const value = await learning.ports.targets.select(input, context); + if (value.outcome !== 'selected' || state.targetArticleId === undefined) return value; + const prior = input.explicitDrafts.find((draft) => draft.articleId === state.targetArticleId); + if (prior === undefined) return { outcome: 'held' }; + return { ...value, operation: 'update', articleId: prior.articleId, + draft: { ...value.draft, content: { format: 'plain_text', text: prior.revision.content.text + '\n\n' + value.draft.content.text } } }; + }, + } }, + processingEnabled: () => learning.state.enabled, + readScheduling: 'sdk', + stagedReviews: { enabled: stagedEnabled, enqueue: (key) => queue.enqueue(key) }, + }; + const runtime = createSupportLearningRuntime({ ...learningOptions, staffAccess: { resolve } }); + queue = createSupportLearningReviewQueue({ enabled: stagedEnabled, store: () => store, clock: learning.clock, logger, + sender, runtime: () => runtime.stagedReviewDispatch() }); + const api = createSupportApi({ ...current.options, application: learning.application, + createLimiter: current.host.createLimiter, replyLimiter: current.host.replyLimiter, + learningRuntime: learningOptions, learningEnabled: enabled, learningStagedReviewsEnabled: stagedEnabled }); + return { api, queue, runtime }; + } + function request(suffix: string, body?: string) { + return new Request(IDENTITY_ISSUER + base + suffix, { method: body === undefined ? 'GET' : 'POST', + headers: { Cookie: SESSION_COOKIE + '=' + sessionId, + ...(body === undefined ? {} : { Origin: IDENTITY_ISSUER, 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': csrf, 'Content-Type': 'application/json' }) }, + ...(body === undefined ? {} : { body }) }); + } + const worker = () => createWorker({ learningReviews: { enabled: stagedEnabled, create: () => graph() } }); + async function invoke(suffix: string, body?: string) { + // Memory owns actual HTTP/SDK adapters without inventing a D1 binding. + // Native exercises the root Worker with its actual environment/context. + if (workerHarness === undefined) { + const response = await graph().api(request(suffix, body)); + await response.clone().arrayBuffer(); return response; + } + const ctx = workerHarness.context(); + try { + const response = await worker().fetch(request(suffix, body), workerHarness.environment(sender), ctx.value); + await response.clone().arrayBuffer(); return response; + } finally { await ctx.finish(); } + } + async function deliver(message: SupportLearningReviewQueueMessage) { + const observed = { acknowledgements: 0, delays: [] as number[] }; + const batch: MessageBatch = { queue: 'pegma-dev-support-learning-reviews', + metadata: { metrics: { backlogCount: 1, backlogBytes: 0 } }, + messages: [{ id: 'fictional-delivery', attempts: 1, timestamp: new Date(learning.clock.now()), body: message, + ack() { observed.acknowledgements += 1; }, retry(options) { + if (options?.delaySeconds === undefined) throw new Error('Expected bounded same-message retry'); + observed.delays.push(options.delaySeconds); + } }], ackAll() { throw new Error('Expected individual acknowledgement'); }, + retryAll() { throw new Error('Expected individual bounded retry'); } }; + if (workerHarness === undefined) await graph().queue.consume(batch); + else { + const ctx = workerHarness.context(); + try { await worker().queue(batch, workerHarness.environment(sender), ctx.value); } + finally { await ctx.finish(); } + } + return observed; + } + async function scan() { + let time = Date.parse('2026-11-11T00:00:00.000Z'); + for (let minute = 0; minute < 32; minute++) { + const candidate = time + minute * 60_000; + if (new Date(candidate).getUTCMinutes() !== 59 && cleanupLaneAt(candidate).kind === 'learning_reviews') { + time = candidate; break; + } + } + if (cleanupLaneAt(time).kind !== 'learning_reviews') throw new Error('Expected exclusive review dispatch lane'); + if (workerHarness === undefined) { await graph().queue.runPage(); return; } + const ctx = workerHarness.context(); + worker().scheduled({ cron: CLEANUP_CRON, scheduledTime: time, noRetry() {} }, workerHarness.environment(sender), ctx.value); + await ctx.finish(); + } + async function checked() { + await learning.enrollAndVerify(); + return learning.delivered(); + } + async function multipleContributors(published: boolean) { + const ticketId = 'staged-secondary-ticket'; const solutionId = 'staged-secondary-solution'; + const old = createSupportDeskApplication({ store, clock: learning.clock }); + await old.createCustomerTicket(learning.actors.customer, { ...learning.command('secondary-create'), ticketId, + messageId: 'staged-secondary-question', subject: 'A second fictional export', body: 'How do I export another workspace?' }); + await old.replyAsStaff(learning.actors.staff, { ...learning.command('secondary-reply'), ticketId, + messageId: solutionId, body: 'Choose Export and verify the downloaded workspace.' }); + await old.resolveTicket(learning.actors.staff, { ...learning.command('secondary-resolve'), ticketId }); + const ticket = (await old.readStaffTicket(learning.actors.staff, ticketId)).ticket; + await learning.runtime.enroll(learning.actors.staff, { ticketId, clientCommandId: 'SECONDARY-ENROLL', expectedRevision: ticket.revision }); + const enrolled = await learning.runtime.readSource(learning.actors.staff, ticketId); + await learning.runtime.submitVerifiedFix(learning.actors.staff, { ticketId, clientCommandId: 'SECONDARY-EVIDENCE', + expectedRevision: ticket.revision, resolutionCycle: enrolled.resolutionCycle, + evidence: { kind: 'staff_verified_fix', solutionMessageId: solutionId, verificationReference: 'FICTIONAL-SECONDARY-VERIFICATION' } }); + const source = await learning.runtime.readSource(learning.actors.staff, ticketId); + const process = () => learning.runtime.processWork({ ticketId, sourceGeneration: source.sourceGeneration, + workerId: 'fictional-secondary-worker', leaseMilliseconds: 30_000 }); + if ((await process()).outcome !== 'candidate' || (await process()).outcome !== 'delivered') + throw new Error('Expected actual secondary KB delivery'); + const secondary = await learning.runtime.readWork(learning.actors.staff, { ticketId, sourceGeneration: source.sourceGeneration }); + if (secondary.target === undefined || secondary.checkPolicyVersion === undefined) throw new Error('Expected actual secondary target'); + const articleId = secondary.target.articleId; + if (published) { + const draft = await learning.knowledge.getDraft(learning.actors.staff, { articleId }); + const provenance = await learning.knowledge.getProvenance(learning.actors.staff, { articleId }); + await learning.runtime.reviewProposal(learning.actors.staff, { ticketId, clientCommandId: 'SECONDARY-REVIEW', + sourceGeneration: source.sourceGeneration, expectedWorkGeneration: secondary.workGeneration, + target: await learningTargetBinding(draft.revision, provenance.snapshot), + policyVersion: secondary.checkPolicyVersion, decision: 'approve' }); + await learning.evidenceAndPublish(articleId); + } + state.targetArticleId = articleId; + await learning.enrollAndVerify(); + const primary = await learning.runtime.readSource(learning.actors.staff, learningTicketId); + const primaryProcess = () => graph().runtime.processWork({ ticketId: learningTicketId, + sourceGeneration: primary.sourceGeneration, workerId: 'fictional-primary-worker', leaseMilliseconds: 30_000 }); + if ((await primaryProcess()).outcome !== 'candidate' || (await primaryProcess()).outcome !== 'delivered') + throw new Error('Expected actual merged primary KB delivery'); + const provenance = await learning.knowledge.getProvenance(learning.actors.staff, { articleId }); + return { source: await learning.runtime.readSource(learning.actors.staff, learningTicketId), articleId, provenance, secondaryTicketId: ticketId }; + } + async function prepare(sourceGeneration: number) { + const response = await invoke('/proposal?sourceGeneration=' + sourceGeneration); + if (response.status !== 200) throw new Error('Actual HTTP proposal unavailable: ' + response.status); + const value = resultObject(await responseObject(response)); + if (!isPlainObject(value.intent)) throw new Error('Expected the actual prepared SDK intent'); + return { body: JSON.stringify({ commandId: 'EXACT-UPPERCASE-STAGED-REVIEW', intent: value.intent, decision: 'approve' }) }; + } + async function revoke(role: typeof SUPPORT_ROLE | typeof KNOWLEDGE_ROLE) { + const id = 'staged-review-' + role; + const row = await seed.host.roleStore.getRoleAssignment(id); + if (row === null) throw new Error('Expected actual role assignment'); + await seed.host.roleStore.revokeRoleAssignmentWithAudit({ assignmentId: id, + expectedConcurrencyToken: row.concurrencyToken, revokedBy: { kind: 'system', systemId: 'fictional-staged-review' }, + revokedAtEpochMs: Date.now(), auditEventId: id + '-revoke' }); + } + return { learning, state, principalId, messages, graph, request, invoke, deliver, scan, checked, multipleContributors, prepare, revoke, + sessionObservations, authenticationClockStartedAt, identityCreatedAt: seededIdentity.createdAt, + readSessionAt: (at: string) => seed.sessions.get(sessionId, at), + destroySession: () => seed.sessions.destroy(sessionId) }; +} diff --git a/worker/src/support-learning-staged-review.test.ts b/worker/src/support-learning-staged-review.test.ts new file mode 100644 index 0000000..59f4c4b --- /dev/null +++ b/worker/src/support-learning-staged-review.test.ts @@ -0,0 +1,120 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { KNOWLEDGE_ROLE, SUPPORT_ROLE } from './support-access'; +import { createStagedReviewFixture, responseObject, resultObject } from './support-learning-staged-review-fixture'; + +async function prepared() { + const f = await createStagedReviewFixture(createMemoryStore()); + const delivered = await f.checked(); + const packet = await f.prepare(delivered.source.sourceGeneration); + return { f, delivered, packet }; +} + +describe('staged staff learning review through actual HTTP and SDK adapters', () => { + it('admits durably, runs one phase in each reconstructed delivery, then recovers the exact receipt', async () => { + const { f, delivered, packet } = await prepared(); + const before = await f.learning.application.readResolutionLearningSource(f.learning.actors.staff, 'learning-ticket'); + const models = f.learning.state.modelCalls; + const admitted = await f.invoke('/review-queue', packet.body); + expect(admitted.status).toBe(202); + expect(resultObject(await responseObject(admitted))).toMatchObject({ outcome: 'pending', phase: 'proof', claimed: false }); + expect((await f.learning.application.readResolutionLearningSource(f.learning.actors.staff, 'learning-ticket')).reviewBindingCount) + .toBe(before.reviewBindingCount); + const hint = f.messages[0]!; + const proof = await f.deliver(hint); + expect(proof).toEqual({ acknowledgements: 0, delays: [30] }); + const pending = resultObject(await responseObject(await f.invoke('/review-queue-status', packet.body))); + expect(pending).toMatchObject({ outcome: 'pending', phase: 'commit', claimed: false }); + const commit = await f.deliver(hint); + expect(commit).toEqual({ acknowledgements: 1, delays: [] }); + const receipt = resultObject(await responseObject(await f.invoke('/review-queue-status', packet.body))); + expect(receipt).toMatchObject({ outcome: 'accepted', result: { ticketId: 'learning-ticket', sourceGeneration: delivered.source.sourceGeneration } }); + expect(await f.deliver(hint)).toEqual({ acknowledgements: 1, delays: [] }); + expect(f.learning.state.modelCalls).toBe(models); + expect((await f.learning.application.readResolutionLearningSource(f.learning.actors.staff, 'learning-ticket')).reviewBindingCount) + .toBe(before.reviewBindingCount + 1); + await f.revoke(KNOWLEDGE_ROLE); + const replay = await f.invoke('/review-queue', packet.body); + expect(replay.status).toBe(200); + expect(resultObject(await responseObject(replay)).outcome).toBe('accepted'); + await expect(f.learning.knowledge.getPublishedArticle(f.learning.actors.customer, { articleId: delivered.articleId })).rejects.toThrow(); + }); + + it('recovers a lost send by bounded scheduled pages; no scan invocation performs either review proof', async () => { + const { f, packet } = await prepared(); + f.state.sendFailure = true; + expect((await f.invoke('/review-queue', packet.body)).status).toBe(202); + expect(f.messages).toHaveLength(0); + f.state.sendFailure = false; + for (let page = 0; page < 256 && f.messages.length === 0; page++) await f.scan(); + expect(f.messages).toHaveLength(1); + expect(resultObject(await responseObject(await f.invoke('/review-queue-status', packet.body)))).toMatchObject({ outcome: 'pending', phase: 'proof' }); + await f.deliver(f.messages[0]!); + // Simulate exhausted/lost broker retries after P1, then cold physical scan + // recovery. SDK commit phase remains durable; it never regenerates P1. + f.messages.length = 0; + for (let page = 0; page < 256 && f.messages.length === 0; page++) await f.scan(); + expect(f.messages).toHaveLength(1); + expect(resultObject(await responseObject(await f.invoke('/review-queue-status', packet.body)))).toMatchObject({ outcome: 'pending', phase: 'commit' }); + expect(await f.deliver(f.messages[0]!)).toEqual({ acknowledgements: 1, delays: [] }); + expect(resultObject(await responseObject(await f.invoke('/review-queue-status', packet.body))).outcome).toBe('accepted'); + }); + + it('cancels the exact admitted packet after P1 without old KB permission or proof', async () => { + const { f, packet } = await prepared(); + expect((await f.invoke('/review-queue', packet.body)).status).toBe(202); + const hint = f.messages[0]!; await f.deliver(hint); await f.revoke(KNOWLEDGE_ROLE); + const cancelled = await f.invoke('/review-queue-cancel', packet.body); + expect(cancelled.status).toBe(200); + expect(resultObject(await responseObject(cancelled))).toMatchObject({ outcome: 'cancelled', commandId: 'EXACT-UPPERCASE-STAGED-REVIEW' }); + expect(await f.deliver(hint)).toEqual({ acknowledgements: 1, delays: [] }); + expect(resultObject(await responseObject(await f.invoke('/review-queue-status', packet.body))).outcome).toBe('cancelled'); + }); + + it('denies a fresh original actor role revocation in the worker and withholds private status', async () => { + const { f, packet } = await prepared(); + expect((await f.invoke('/review-queue', packet.body)).status).toBe(202); + await f.revoke(SUPPORT_ROLE); + expect(await f.deliver(f.messages[0]!)).toEqual({ acknowledgements: 0, delays: [30] }); + const denied = await f.invoke('/review-queue-status', packet.body); + expect(denied.status).toBe(403); + expect(await responseObject(denied)).toEqual({ error: 'forbidden' }); + expect((await f.learning.application.readResolutionLearningSource(f.learning.actors.staff, 'learning-ticket')).reviewBindingCount).toBe(0); + }); + + it('requires fresh KB permission for new admission but not an absent-receipt status read', async () => { + const { f, packet } = await prepared(); await f.revoke(KNOWLEDGE_ROLE); + expect((await f.invoke('/review-queue', packet.body)).status).toBe(403); + expect(f.messages).toHaveLength(0); + const status = await f.invoke('/review-queue-status', packet.body); + expect(status.status).toBe(200); expect((await responseObject(status)).result).toBeNull(); + }); + + it('treats logout after durable admission as lost browser access, not command cancellation', async () => { + const { f, packet } = await prepared(); + expect((await f.invoke('/review-queue', packet.body)).status).toBe(202); + await f.destroySession(); + expect((await f.invoke('/review-queue-status', packet.body)).status).toBe(401); + const hint = f.messages[0]!; + expect((await f.deliver(hint)).acknowledgements).toBe(0); + expect((await f.deliver(hint)).acknowledgements).toBe(1); + expect((await f.learning.application.readResolutionLearningSource(f.learning.actors.staff, 'learning-ticket')).reviewBindingCount).toBe(1); + }); + + it('keeps disabled learning routes unavailable without queue delivery', async () => { + const { f, packet } = await prepared(); f.state.enabled = false; + for (const operation of ['/review-queue', '/review-queue-status', '/review-queue-cancel']) { + expect((await f.graph().api(f.request(operation, packet.body))).status).toBe(404); + } + expect(f.messages).toHaveLength(0); + }); + + it('preserves real inline review when the separate staged switch is false', async () => { + const { f, packet } = await prepared(); f.state.stagedEnabled = false; + expect((await f.graph().api(f.request('/review-queue', packet.body))).status).toBe(503); + const response = await f.graph().api(f.request('/review', packet.body)); + expect(response.status).toBe(200); + expect(resultObject(await responseObject(response)).outcome).toBe('accepted'); + expect(f.messages).toHaveLength(0); + }); +}); diff --git a/worker/src/support-learning.d1.test.ts b/worker/src/support-learning.d1.test.ts new file mode 100644 index 0000000..3388893 --- /dev/null +++ b/worker/src/support-learning.d1.test.ts @@ -0,0 +1,65 @@ +import { env } from 'cloudflare:workers'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { supportRecords } from '@pegma/support-desk-application'; +import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createSupportLearningFixture, learningCanary, learningTicketId } from './support-learning-fixtures'; + +beforeAll(async () => { + // Test-only public adapter initialization. Production schema/migration flags + // and the actual Worker entrypoint are not changed or invoked by this suite. + const store = createCloudflareD1Store({ database: env.IDENTITY_DB }); + await store.collection(supportRecords).get({ partition: 'learning-schema-probe', id: 'probe' }); +}); + +beforeEach(async () => { + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +function fixture(options?: Parameters[1]) { + return createSupportLearningFixture(createCloudflareD1Store({ + database: env.IDENTITY_DB, createSchemaIfMissing: false, readBatchSize: 512, + }), options); +} + +describe('learning assembly on the actual D1 binding', () => { + it('delivers and exactly reviews a private draft, uses confirmed real KB reports, then rejects reopened source authority', async () => { + const f = await fixture(); + const packet = await f.enrollAndVerify(); + const accepted = await f.rows(); + await f.runtime.submitVerifiedFix(f.actors.staff, structuredClone(packet)); + expect(await f.rows()).toEqual(accepted); + const delivered = await f.delivered(); + const provenance = await f.knowledge.getProvenance(f.actors.staff, { articleId: delivered.articleId }); + expect(provenance.snapshot.references).toHaveLength(1); + const review = await f.review(delivered.articleId); + expect(review.target.articleId).toBe(delivered.articleId); + const published = await f.evidenceAndPublish(delivered.articleId); + expect(published.title).toBe('Export your workspace'); + expect(JSON.stringify(published)).not.toContain(learningTicketId); + expect(JSON.stringify(published)).not.toContain(learningCanary); + expect(JSON.stringify(f.state.modelInputs)).not.toContain(learningCanary); + expect(f.state.modelCalls).toBe(1); + await f.application.reopenTicket(f.actors.staff, { ...f.command('reopen-native'), ticketId: learningTicketId }); + const source = await f.runtime.readSource(f.actors.staff, learningTicketId); + expect(source.sourceGeneration).toBeGreaterThan(delivered.source.sourceGeneration); + expect(source.state).toBe('held'); + await expect(f.knowledge.getPublishedArticle(f.actors.customer, { articleId: delivered.articleId })).rejects.toThrow(); + }); + + it('holds expired trusted product evidence with no generation work or paid call', async () => { + const f = await fixture(); f.state.product = 'expired'; + await f.enrollAndVerify(); + expect((await f.runtime.readSource(f.actors.staff, learningTicketId)).state).toBe('held'); + expect((await f.rows()).filter((row) => row.kind === 'resolution_learning_work')).toEqual([]); + expect(f.state.modelCalls).toBe(0); + }); + + it('observes actual stored staff revocation without returning the private source', async () => { + const f = await fixture(); await f.enrollAndVerify(); + await f.revokeStaff(); + const before = await f.rows(); + await expect(f.runtime.readSource(f.actors.staff, learningTicketId)).rejects.toThrow(); + expect(await f.rows()).toEqual(before); + }); +}); diff --git a/worker/src/support-learning.test.ts b/worker/src/support-learning.test.ts new file mode 100644 index 0000000..1c7b23f --- /dev/null +++ b/worker/src/support-learning.test.ts @@ -0,0 +1,652 @@ +import { createMemoryStore, type Store, type CollectionDefinition, type CollectionStore } from '@pegma/storage-core'; +import { + KnowledgeBaseNotFoundError, + KnowledgeBaseAuthorizationError, + RepositoryConflictError, +} from '@pegma/knowledge-base-application'; +import { createSupportDeskApplication, SupportDeskAuthorizationError, supportPermissions, supportRecords } from '@pegma/support-desk-application'; +import { learningTargetBinding } from '@pegma/support-desk-ai'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import { describe, expect, it, vi } from 'vitest'; +import { + createSupportLearningRuntime, + SupportLearningUnavailableError, + supportLearningApplicationOptions, +} from './support-learning'; +import { + createSupportLearningKnowledgePort, + supportLearningCommandIdentity, +} from './support-learning-ports'; +import { + createSupportLearningFixture, + learningCanary, + learningTicketId, +} from './support-learning-fixtures'; + +function fixture(options?: Parameters[1]) { + return createSupportLearningFixture(createMemoryStore(), options); +} + +function barrier() { + let release = () => {}; + const reached = new Promise((resolve) => { release = resolve; }); + return { reached, release }; +} + +describe('published learning assembly', () => { + it('recovers an accepted intake ACK before requiring the optional public ticket reader', async () => { + const f = await fixture(); const ticket = await f.terminal(); + const packet = { ticketId: learningTicketId, clientCommandId: 'LEGACY-STRUCTURAL-ACK-EXACT', expectedRevision: ticket.revision }; + const accepted = await f.runtime.enroll(f.actors.staff, packet); + const { readStaffTicket, ...application } = f.application; void readStaffTicket; + const runtime = createSupportLearningRuntime({ application, knowledge: f.knowledge, sources: f.sources, clock: f.clock, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const before = await f.rows(); + expect(await runtime.recoverEnrollment(f.actors.staff, packet)).toEqual({ ticketId: learningTicketId, + commandId: packet.clientCommandId, operation: 'enroll', outcome: 'accepted', result: accepted }); + expect(await f.rows()).toEqual(before); + }); + + it('fails closed on a conflict when a legacy structural port omits the public revision observation', async () => { + const f = await fixture(); const ticket = await f.terminal(); + const legacy = createSupportDeskApplication({ store: f.store, clock: f.clock }); + await legacy.addNote(f.actors.staff, { ...f.command('legacy-reader-revision'), ticketId: learningTicketId, + messageId: 'legacy-reader-note', body: 'A real competing fictional revision.' }); + const { readStaffTicket, ...application } = f.application; void readStaffTicket; + const runtime = createSupportLearningRuntime({ application, knowledge: f.knowledge, sources: f.sources, clock: f.clock, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const before = await f.rows(); + await expect(runtime.recoverEnrollment(f.actors.staff, { ticketId: learningTicketId, + clientCommandId: 'LEGACY-STRUCTURAL-UNKNOWN', expectedRevision: ticket.revision })).rejects.toBeInstanceOf(SupportLearningUnavailableError); + expect(await f.rows()).toEqual(before); + }); + + it('recovers an actual concurrent evidence commit after an initial missing receipt and newer-revision conflict', async () => { + const backing = createMemoryStore(); const entered = barrier(); const release = barrier(); + let armed = false; const receipts: boolean[] = []; + const store: Store = { collection(definition: CollectionDefinition): CollectionStore { + const actual = backing.collection(definition); + if (definition.name !== supportRecords.name) return actual; + return { ...actual, async get(key) { + const value = await actual.get(key); + if (key.id === 'learning-command:REAL-EVIDENCE-RACE-EXACT') { + receipts.push(value !== null); + if (armed && value === null) { armed = false; entered.release(); await release.reached; } + } + return value; + } }; + } }; + const f = await createSupportLearningFixture(store); const ticket = await f.terminal(); + await f.runtime.enroll(f.actors.staff, { ticketId: learningTicketId, clientCommandId: 'RACE-SETUP', expectedRevision: ticket.revision }); + const packet = { ticketId: learningTicketId, clientCommandId: 'REAL-EVIDENCE-RACE-EXACT', expectedRevision: ticket.revision, + resolutionCycle: 1, evidence: { kind: 'staff_verified_fix' as const, solutionMessageId: 'learning-solution', verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' } }; + armed = true; const recovery = f.runtime.recoverVerifiedFix(f.actors.staff, packet); + let accepted: Awaited> | undefined; + let rows: Awaited> | undefined; + try { + await Promise.race([entered.reached, recovery.then(() => { throw new Error('Expected the real receipt-read barrier'); })]); + accepted = await f.runtime.submitVerifiedFix(f.actors.staff, packet); + const legacy = createSupportDeskApplication({ store, clock: f.clock }); + await legacy.addNote(f.actors.staff, { ...f.command('race-after-real-evidence'), ticketId: learningTicketId, + messageId: 'race-after-evidence-note', body: 'An independent fictional edit after the accepted evidence.' }); + rows = await f.rows(); + } finally { release.release(); } + const result = await recovery; + expect(result.outcome).toBe('accepted'); + if (result.outcome !== 'accepted') throw new Error('The second exact SDK retry must recover the genuine accepted ACK'); + expect(result.result).toEqual(accepted); expect(await f.rows()).toEqual(rows); + expect(receipts).toEqual([false, false, true]); + }); + + it('keeps disabled enrollment pending until the same command can be accepted after the intake configuration changes', async () => { + const f = await fixture({ intake: false }); const ticket = await f.terminal(); + const packet = { ticketId: learningTicketId, clientCommandId: 'DISABLED-ENROLL-EXACT', expectedRevision: ticket.revision }; + const before = await f.rows(); + expect(await f.runtime.recoverEnrollment(f.actors.staff, packet)).toEqual({ outcome: 'pending', operation: 'enroll', + ticketId: learningTicketId, commandId: packet.clientCommandId }); + expect(await f.rows()).toEqual(before); + const application = createSupportDeskApplication({ store: f.store, clock: f.clock, resolutionLearning: { enabled: true } }); + const runtime = createSupportLearningRuntime({ application, knowledge: f.knowledge, sources: f.sources, clock: f.clock, + staffAccess: { resolve: (id) => f.resolve(id) } }); + expect(await runtime.recoverEnrollment(f.actors.staff, packet)).toMatchObject({ outcome: 'accepted', + commandId: packet.clientCommandId, result: { ticketId: learningTicketId, state: 'unverified' } }); + const rows = await f.rows(); + expect(await runtime.recoverEnrollment(f.actors.staff, packet)).toMatchObject({ outcome: 'accepted' }); + expect(await f.rows()).toEqual(rows); + }); + + it('performs a second actual SDK exact retry after a complete same-revision solution fence', async () => { + const f = await fixture(); const ticket = await f.terminal(); + await f.runtime.enroll(f.actors.staff, { ticketId: learningTicketId, clientCommandId: 'CONTENT-RETRY-SETUP', expectedRevision: ticket.revision }); + let attempts = 0; + const application = { ...f.application, async submitResolutionEvidence(...args: Parameters) { + attempts += 1; return f.application.submitResolutionEvidence(...args); + } }; + const runtime = createSupportLearningRuntime({ application, knowledge: f.knowledge, sources: f.sources, clock: f.clock, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const before = await f.rows(); + expect(await runtime.recoverVerifiedFix(f.actors.staff, { ticketId: learningTicketId, clientCommandId: 'CONTENT-RETRY-EXACT', + expectedRevision: ticket.revision, resolutionCycle: 1, evidence: { kind: 'staff_verified_fix', + solutionMessageId: 'learning-note', verificationReference: 'SYNTHETIC_STAFF_VERIFICATION' } })).toEqual({ outcome: 'superseded', + operation: 'evidence', ticketId: learningTicketId, commandId: 'CONTENT-RETRY-EXACT', expectedRevision: ticket.revision, + observedRevision: ticket.revision, fence: 'solution_unavailable' }); + expect(attempts).toBe(2); expect(await f.rows()).toEqual(before); expect(f.state.modelCalls).toBe(0); + }); + + it('preserves exact client bytes and derives a stable actor/operation/ticket correlation', async () => { + const input = { principalId: 'staff-one', ticketId: 'ticket-one', operation: 'enroll' as const, + clientCommandId: 'A1B2C3D4-1234-4ABC-8DEF-ABCDEF123456' }; + const identity = await supportLearningCommandIdentity(input); + expect(await supportLearningCommandIdentity({ ...input })).toEqual(identity); + expect(identity.commandId).toBe(input.clientCommandId); + for (const changed of [{ ...input, principalId: 'staff-two' }, { ...input, ticketId: 'ticket-two' }, + { ...input, operation: 'verified_fix' as const }, { ...input, clientCommandId: input.clientCommandId.toLowerCase() }]) { + expect((await supportLearningCommandIdentity(changed)).correlationId).not.toBe(identity.correlationId); + } + }); + + it('defaults intake OFF and refuses explicit enrollment without writing a source', async () => { + expect(supportLearningApplicationOptions().enabled).toBe(false); + const f = await fixture({ intake: false }); + const ticket = await f.terminal(); + const before = await f.rows(); + await expect(f.runtime.enroll(f.actors.staff, { ticketId: learningTicketId, + clientCommandId: 'enroll-disabled', expectedRevision: ticket.revision })).rejects.toThrow(); + expect(await f.rows()).toEqual(before); + }); + + it('keeps generation OFF separately from accepted evidence and private reads', async () => { + const f = await fixture({ processing: false }); + await f.enrollAndVerify(); + expect((await f.runtime.readSource(f.actors.staff, learningTicketId)).state).toBe('eligible'); + const before = await f.rows(); + expect(await f.process()).toEqual({ outcome: 'held', reason: 'learning_disabled' }); + expect(await f.runtime.scanCandidates({ limit: 8 })).toEqual({ outcome: 'held', reason: 'learning_disabled' }); + expect(f.state.modelCalls).toBe(0); + expect(await f.rows()).toEqual(before); + }); + + it('holds an incompletely configured generation path before claiming or paying', async () => { + const f = await fixture(); + await f.enrollAndVerify(); + const runtime = createSupportLearningRuntime({ application: f.application, knowledge: f.knowledge, + sources: f.sources, clock: f.clock, processingEnabled: () => true, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const source = await runtime.readSource(f.actors.staff, learningTicketId); + const before = await f.rows(); + expect(await runtime.processWork({ ticketId: learningTicketId, sourceGeneration: source.sourceGeneration, + workerId: 'synthetic-worker', leaseMilliseconds: 30_000 })).toEqual({ outcome: 'held', reason: 'learning_unavailable' }); + expect(await f.rows()).toEqual(before); + expect(f.state.modelCalls).toBe(0); + }); + + it('distinguishes a readiness callback outage from deliberately disabled processing without exposing its cause', async () => { + const f = await fixture(); await f.enrollAndVerify(); + const runtime = createSupportLearningRuntime({ application: f.application, knowledge: f.knowledge, + sources: f.sources, clock: f.clock, ports: f.ports, + processingEnabled() { throw new Error(learningCanary); }, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const source = await runtime.readSource(f.actors.staff, learningTicketId); + const before = await f.rows(); + const result = await runtime.processWork({ ticketId: learningTicketId, + sourceGeneration: source.sourceGeneration, workerId: 'synthetic-worker', leaseMilliseconds: 30_000 }); + expect(result).toEqual({ outcome: 'held', reason: 'learning_readiness_unavailable' }); + expect(await runtime.scanCandidates({ limit: 8 })).toEqual(result); + expect(JSON.stringify(result)).not.toContain(learningCanary); + expect(await f.rows()).toEqual(before); + expect(f.state.modelCalls).toBe(0); + }); + + it('reports an opaque staff authority outage separately from a deadline', async () => { + const f = await fixture(); await f.enrollAndVerify(); + const runtime = createSupportLearningRuntime({ application: f.application, knowledge: f.knowledge, + sources: f.sources, clock: f.clock, + staffAccess: { async resolve() { throw new Error(learningCanary); } } }); + const failure: unknown = await runtime.readSource(f.actors.staff, learningTicketId).catch((error: unknown) => error); + expect(failure).toBeInstanceOf(SupportLearningUnavailableError); + expect(failure).toMatchObject({ code: 'support_learning_unavailable', reason: 'staff_authority_unavailable', + message: 'Support learning is unavailable' }); + expect(failure).not.toHaveProperty('cause'); + expect(JSON.stringify(failure)).not.toContain(learningCanary); + }); + + it.each([0, -1, 25_001, 1.5, Number.NaN, Number.POSITIVE_INFINITY])( + 'rejects invalid server staff boundary %s', async (staffOperationMilliseconds) => { + const f = await fixture(); + expect(() => createSupportLearningRuntime({ application: f.application, knowledge: f.knowledge, + sources: f.sources, clock: f.clock, staffOperationMilliseconds, + staffAccess: { resolve: (id) => f.resolve(id) } })).toThrow('Invalid staff operation boundary'); + }, + ); + + it('bounds a deferred actual application read and aborts the same authority signal', async () => { + const f = await fixture(); await f.enrollAndVerify(); + const entered = barrier(); const wait = barrier(); const returned = barrier(); + let signal: AbortSignal | undefined; let reads = 0; + const runtime = createSupportLearningRuntime({ + application: { ...f.application, async readResolutionLearningSource(...args) { + reads += 1; const result = await f.application.readResolutionLearningSource(...args); + entered.release(); await wait.reached; returned.release(); return result; + } }, + knowledge: f.knowledge, sources: f.sources, clock: f.clock, staffOperationMilliseconds: 1000, + staffAccess: { async resolve(id, currentSignal) { signal = currentSignal; return f.resolve(id); } }, + }); + const before = await f.rows(); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + try { + let settled = false; + const result = runtime.readSource(f.actors.staff, learningTicketId) + .catch((error: unknown) => error).finally(() => { settled = true; }); + await entered.reached; + await vi.advanceTimersByTimeAsync(999); expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(await result).toMatchObject({ code: 'support_learning_unavailable', reason: 'staff_deadline' }); + expect(signal?.aborted).toBe(true); expect(reads).toBe(1); + wait.release(); await returned.reached; + expect(await f.rows()).toEqual(before); + } finally { wait.release(); vi.useRealTimers(); } + }); + + it.each(['initial', 'final'] as const)('classifies an %s authority deadline without treating it as revocation or an outage', async (phase) => { + const f = await fixture(); await f.enrollAndVerify(); + const entered = barrier(); const wait = barrier(); + let authorityCalls = 0; let signal: AbortSignal | undefined; + const runtime = createSupportLearningRuntime({ application: f.application, knowledge: f.knowledge, + sources: f.sources, clock: f.clock, staffOperationMilliseconds: 1000, + staffAccess: { async resolve(id, currentSignal) { + const access = await f.resolve(id); authorityCalls += 1; signal = currentSignal; + if (authorityCalls === (phase === 'initial' ? 1 : 2)) { + entered.release(); await wait.reached; + } + return access; + } }, + }); + const before = await f.rows(); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + try { + const result = runtime.readSource(f.actors.staff, learningTicketId).catch((error: unknown) => error); + await entered.reached; await vi.advanceTimersByTimeAsync(1000); + expect(await result).toMatchObject({ reason: 'staff_deadline' }); + expect(signal?.aborted).toBe(true); + expect(await f.rows()).toEqual(before); + } finally { wait.release(); vi.useRealTimers(); } + }); + + it('uses one staff deadline and preserves a late actual enrollment for exact historical receipt replay', async () => { + const f = await fixture(); const ticket = await f.terminal(); + const authorityEntered = barrier(); const authorityWait = barrier(); + const entered = barrier(); const wait = barrier(); const committed = barrier(); + let calls = 0; let authorityCalls = 0; + const runtime = createSupportLearningRuntime({ + application: { ...f.application, async enrollResolutionLearning(...args) { + calls += 1; entered.release(); await wait.reached; + const result = await f.application.enrollResolutionLearning(...args); + committed.release(); return result; + } }, + knowledge: f.knowledge, sources: f.sources, clock: f.clock, staffOperationMilliseconds: 1000, + staffAccess: { async resolve(id) { + const access = await f.resolve(id); + if (++authorityCalls === 1) { authorityEntered.release(); await authorityWait.reached; } + return access; + } }, + }); + const packet = Object.freeze({ ticketId: learningTicketId, clientCommandId: 'deadline-enroll-exact', + expectedRevision: ticket.revision }); + const before = await f.rows(); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + try { + let settled = false; + const result = runtime.enroll(f.actors.staff, packet) + .catch((error: unknown) => error).finally(() => { settled = true; }); + await authorityEntered.reached; + await vi.advanceTimersByTimeAsync(600); authorityWait.release(); await entered.reached; + await vi.advanceTimersByTimeAsync(399); expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(await result).toMatchObject({ reason: 'staff_deadline' }); + expect(calls).toBe(1); expect(authorityCalls).toBe(1); + expect(await f.rows()).toEqual(before); + wait.release(); await committed.reached; + const accepted = await f.application.readResolutionLearningSource(f.actors.staff, learningTicketId); + expect(accepted.sourceGeneration).toBe(0); + const acceptedRows = await f.rows(); + expect(acceptedRows.filter((row) => row.kind === 'resolution_learning_receipt')).toHaveLength(1); + await f.application.reopenTicket(f.actors.staff, { ...f.command('after-timeout-reopen'), ticketId: learningTicketId }); + const current = await f.application.readResolutionLearningSource(f.actors.staff, learningTicketId); + expect(current.sourceGeneration).toBeGreaterThan(accepted.sourceGeneration); + const history = await f.rows(); + expect((await runtime.enroll(f.actors.staff, structuredClone(packet))).sourceGeneration).toBe(0); + expect(calls).toBe(2); expect(await f.rows()).toEqual(history); + expect(await f.application.readResolutionLearningSource(f.actors.staff, learningTicketId)).toEqual(current); + } finally { authorityWait.release(); wait.release(); vi.useRealTimers(); } + }); + + it.each(['missing', 'expired'] as const)('holds %s trusted product evidence instead of creating generation work', async (mode) => { + const f = await fixture(); f.state.product = mode; + await f.enrollAndVerify(); + expect((await f.runtime.readSource(f.actors.staff, learningTicketId)).state).toBe('held'); + expect((await f.rows()).filter((row) => row.kind === 'resolution_learning_work')).toEqual([]); + expect(f.state.modelCalls).toBe(0); + }); + + it('refuses a derived candidate that changes the trusted product/build binding', async () => { + const f = await fixture(); await f.enrollAndVerify(); + f.setModel(async (_input, _context, configuration) => ({ + outputJson: JSON.stringify({ ...f.candidate, + applicability: { ...f.candidate.applicability, buildId: 'different-build' } }), + provider: configuration.provider, model: configuration.model, requestId: 'synthetic-wrong-build', + usage: { inputTokens: 100, outputTokens: 50, costMicros: 10, currency: 'USD' }, + })); + expect((await f.process()).outcome).not.toBe('candidate'); + const source = await f.runtime.readSource(f.actors.staff, learningTicketId); + const work = await f.runtime.readWork(f.actors.staff, { ticketId: learningTicketId, sourceGeneration: source.sourceGeneration }); + expect(work.candidate).toBeUndefined(); + expect(work.target).toBeUndefined(); + }); + + it('delivers one private checked draft, reviews its exact target and accepts only human-confirmed KB evidence', async () => { + const f = await fixture(); + await f.enrollAndVerify(); + const result = await f.delivered(); + const draft = await f.knowledge.getDraft(f.actors.staff, { articleId: result.articleId }); + const provenance = await f.knowledge.getProvenance(f.actors.staff, { articleId: result.articleId }); + expect(draft.state).toBe('draft'); + for (const advisory of f.candidate.validationRequirements) + expect(draft.revision.content.text).toContain(advisory); + const requirements = await f.knowledge.getValidationRequirements(f.actors.runner, { + collectionId: draft.revision.collectionId, kind: draft.revision.kind, + }); + expect(requirements.checks.map((check) => check.id)).toContain('explanation-content'); + expect(provenance.snapshot.references).toHaveLength(1); + expect(JSON.stringify(provenance.snapshot)).toContain('pegma.support-desk'); + expect(JSON.stringify(f.state.modelInputs)).not.toContain(learningCanary); + expect(JSON.stringify(f.state.modelInputs)).not.toContain('SYNTHETIC_PRIVATE_VERIFICATION'); + expect(JSON.stringify(f.state.modelInputs)).not.toContain('synthetic-independent-learning-check'); + await f.review(result.articleId); + const published = await f.evidenceAndPublish(result.articleId); + expect(published.title).toBe('Export your workspace'); + expect(JSON.stringify(published)).not.toContain(learningTicketId); + expect(JSON.stringify(published)).not.toContain('pegma.support-desk'); + expect(JSON.stringify(published)).not.toContain(learningCanary); + expect(f.state.modelCalls).toBe(1); + expect((await f.rows()).filter((row) => row.kind === 'resolution_learning_work')).toHaveLength(1); + }); + + it('replays the same staff evidence packet without another work or receipt', async () => { + const f = await fixture(); const packet = await f.enrollAndVerify(); + const before = await f.rows(); + const result = await f.runtime.submitVerifiedFix(f.actors.staff, structuredClone(packet)); + expect(result.state).toBe('eligible'); + expect(await f.rows()).toEqual(before); + }); + + it('lets only one overlapping physical worker enter the paid model stage', async () => { + const f = await fixture(); await f.enrollAndVerify(); + let entered = () => {}; let release = () => {}; + const reached = new Promise((resolve) => { entered = resolve; }); + const waiting = new Promise((resolve) => { release = resolve; }); + f.state.beforeModelReturn = async () => { entered(); await waiting; }; + const first = f.process(); + let timer: ReturnType | undefined; + try { + await Promise.race([ + reached, + first.then(() => { throw new Error('The first worker did not reach its model barrier'); }), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('Learning model barrier not reached')), 3000); + }), + ]); + expect(await f.process()).toEqual({ outcome: 'not_claimed' }); + expect(f.state.modelCalls).toBe(1); + } finally { + release(); if (timer !== undefined) clearTimeout(timer); + } + expect((await first).outcome).toBe('candidate'); + expect((await f.process()).outcome).toBe('delivered'); + expect(f.state.modelCalls).toBe(1); + expect((await f.rows()).filter((row) => row.kind === 'resolution_learning_work')).toHaveLength(1); + }); + + it('recovers a host ACK lost after actual SDK acceptance with the original immutable packet', async () => { + const f = await fixture(); const original = await f.enrollAndVerify(); + let lost = true; + const runtime = createSupportLearningRuntime({ + application: { ...f.application, async submitResolutionEvidence(...args) { + const result = await f.application.submitResolutionEvidence(...args); + if (lost) { lost = false; throw new Error('Synthetic withheld host acknowledgement'); } + return result; + } }, + knowledge: f.knowledge, sources: f.sources, clock: f.clock, ports: f.ports, + staffAccess: { resolve: (id) => f.resolve(id) }, + }); + const packet = { ...original, clientCommandId: 'lost-host-ack-exact' }; + const before = await f.rows(); + await expect(runtime.submitVerifiedFix(f.actors.staff, packet)).rejects.toThrow('Synthetic withheld host acknowledgement'); + const committed = await f.rows(); expect(committed.length).toBeGreaterThan(before.length); + expect((await runtime.submitVerifiedFix(f.actors.staff, structuredClone(packet))).state).toBe('eligible'); + expect(await f.rows()).toEqual(committed); + }); + + it('does not promote a restricted caller through a broader current staff resolver', async () => { + const f = await fixture(); const ticket = await f.terminal(); + const restricted = { ...f.actors.staff, + permissions: f.actors.staff.permissions.filter((name) => name !== supportPermissions.learningEvidenceSubmit) }; + const before = await f.rows(); + await expect(f.runtime.enroll(restricted, { ticketId: learningTicketId, clientCommandId: 'restricted', + expectedRevision: ticket.revision })).rejects.toBeInstanceOf(SupportDeskAuthorizationError); + expect(await f.rows()).toEqual(before); + }); + + it('observes a real audited role revocation on the next call', async () => { + const f = await fixture(); await f.enrollAndVerify(); + await f.revokeStaff(); + const before = await f.rows(); + await expect(f.runtime.readSource(f.actors.staff, learningTicketId)).rejects.toBeInstanceOf(SupportDeskAuthorizationError); + expect(await f.rows()).toEqual(before); + }); + + it('rejects a caller principal changed while current authority is being read', async () => { + const f = await fixture(); const ticket = await f.terminal(); + const caller = { ...f.actors.staff }; + f.state.beforeStaffResolve = async () => { caller.principalId = 'another-principal'; }; + const before = await f.rows(); + await expect(f.runtime.enroll(caller, { ticketId: learningTicketId, clientCommandId: 'actor-changed', + expectedRevision: ticket.revision })).rejects.toBeInstanceOf(SupportDeskAuthorizationError); + expect(await f.rows()).toEqual(before); + }); + + it('withholds a committed enrollment ACK when the actual staff role is revoked before return', async () => { + const f = await fixture(); const ticket = await f.terminal(); + let reads = 0; + f.state.beforeStaffResolve = async () => { if (++reads === 2) await f.revokeStaff(); }; + const packet = { ticketId: learningTicketId, clientCommandId: 'commit-then-revoke', expectedRevision: ticket.revision }; + await expect(f.runtime.enroll(f.actors.staff, packet)).rejects.toBeInstanceOf(SupportDeskAuthorizationError); + const accepted = await f.application.readResolutionLearningSource(f.actors.admin, learningTicketId); + expect(accepted.sourceGeneration).toBe(0); + const committed = await f.rows(); + await expect(f.runtime.enroll(f.actors.staff, packet)).rejects.toBeInstanceOf(SupportDeskAuthorizationError); + expect(await f.rows()).toEqual(committed); + }); + + it.each(['held', 'revoked'] as const)('refuses independent checks that are %s without transferring a draft', async (mode) => { + const f = await fixture(); await f.enrollAndVerify(); + expect((await f.process()).outcome).toBe('candidate'); + if (mode === 'held') f.state.check = 'held'; else f.state.checkReadable = false; + const result = await f.process(); expect(result.outcome).toBe('held'); + const source = await f.runtime.readSource(f.actors.staff, learningTicketId); + const work = await f.runtime.readWork(f.actors.staff, { ticketId: learningTicketId, sourceGeneration: source.sourceGeneration }); + expect(work.target).toBeUndefined(); + expect(f.state.modelCalls).toBe(1); + }); + + it('rejects a changed exact review binding without adding a review', async () => { + const f = await fixture(); await f.enrollAndVerify(); const { articleId } = await f.delivered(); + const packet = await f.review(articleId); const before = await f.rows(); + await expect(f.runtime.reviewProposal(f.actors.staff, { ...packet, + target: { ...packet.target, contentHash: '0'.repeat(64) } })).rejects.toThrow(); + expect(await f.rows()).toEqual(before); + }); + + it('makes missing independent checks explicitly unavailable for a real review while leaving private reads enabled', async () => { + const f = await fixture(); await f.enrollAndVerify(); + const { source, work, articleId } = await f.delivered(); + const draft = await f.knowledge.getDraft(f.actors.staff, { articleId }); + const provenance = await f.knowledge.getProvenance(f.actors.staff, { articleId }); + const policy = await f.ports.checks.resolvePolicy(undefined, new AbortController().signal); + if (policy.outcome !== 'ready') throw new Error('Synthetic checks unavailable'); + const packet = { ticketId: learningTicketId, clientCommandId: 'missing-checks-exact-review', + sourceGeneration: source.sourceGeneration, expectedWorkGeneration: work.workGeneration, + target: await learningTargetBinding(draft.revision, provenance.snapshot), + decision: 'approve' as const, policyVersion: policy.policy.version }; + const { checks, ...ports } = f.ports; expect(checks).toBeDefined(); + const runtime = createSupportLearningRuntime({ application: f.application, knowledge: f.knowledge, + sources: f.sources, clock: f.clock, ports, processingEnabled: () => false, + staffAccess: { resolve: (id) => f.resolve(id) } }); + const before = await f.rows(); + expect(await runtime.readSource(f.actors.staff, learningTicketId)).toEqual(source); + await expect(runtime.reviewProposal(f.actors.staff, packet)).rejects.toMatchObject({ + code: 'support_learning_unavailable', reason: 'review_checks_unavailable', + }); + expect(await f.rows()).toEqual(before); + // The same exact live target succeeds through the actual independent checks. + expect((await f.runtime.reviewProposal(f.actors.staff, packet)).sourceGeneration).toBe(source.sourceGeneration); + expect((await f.rows()).filter((row) => row.kind === 'resolution_learning_review')).toHaveLength(1); + }); + + it('propagates the staff deadline to SDK review guards and never approves after a delayed actual target read', async () => { + const f = await fixture(); await f.enrollAndVerify(); + const { source, work, articleId } = await f.delivered(); + const draft = await f.knowledge.getDraft(f.actors.staff, { articleId }); + const provenance = await f.knowledge.getProvenance(f.actors.staff, { articleId }); + const policy = await f.ports.checks.resolvePolicy(undefined, new AbortController().signal); + if (policy.outcome !== 'ready') throw new Error('Synthetic checks unavailable'); + const packet = { ticketId: learningTicketId, clientCommandId: 'deadline-review-exact', + sourceGeneration: source.sourceGeneration, expectedWorkGeneration: work.workGeneration, + target: await learningTargetBinding(draft.revision, provenance.snapshot), + decision: 'approve' as const, policyVersion: policy.policy.version }; + const entered = barrier(); const wait = barrier(); const returned = barrier(); + let reviewCalls = 0; let policySignal: AbortSignal | undefined; + const runtime = createSupportLearningRuntime({ + application: { ...f.application, async reviewResolutionLearningProposal(...args) { + reviewCalls += 1; return f.application.reviewResolutionLearningProposal(...args); + } }, + knowledge: { ...f.knowledge, async getDraft(...args) { + const result = await f.knowledge.getDraft(...args); + entered.release(); await wait.reached; returned.release(); return result; + } }, + sources: f.sources, clock: f.clock, staffOperationMilliseconds: 1000, + ports: { ...f.ports, checks: { ...f.ports.checks, async resolvePolicy(...args) { + policySignal = args[1]; return f.ports.checks.resolvePolicy(...args); + } } }, + staffAccess: { resolve: (id) => f.resolve(id) }, + }); + const before = await f.rows(); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + try { + const result = runtime.reviewProposal(f.actors.staff, packet).catch((error: unknown) => error); + await entered.reached; await vi.advanceTimersByTimeAsync(1000); + expect(await result).toMatchObject({ reason: 'staff_deadline' }); + expect(policySignal?.aborted).toBe(true); + wait.release(); await returned.reached; await vi.advanceTimersByTimeAsync(0); + expect(reviewCalls).toBe(0); expect(await f.rows()).toEqual(before); + expect(f.state.modelCalls).toBe(1); + } finally { wait.release(); vi.useRealTimers(); } + }); + + it('reopening the source denies an already published guide without trusting its old review', async () => { + const f = await fixture(); await f.enrollAndVerify(); const result = await f.delivered(); + await f.review(result.articleId); await f.evidenceAndPublish(result.articleId); + await f.application.reopenTicket(f.actors.staff, { ...f.command('reopen'), ticketId: learningTicketId }); + const current = await f.runtime.readSource(f.actors.staff, learningTicketId); + expect(current.sourceGeneration).toBeGreaterThan(result.source.sourceGeneration); + expect(current.state).toBe('held'); + await expect(f.knowledge.getPublishedArticle(f.actors.customer, { articleId: result.articleId })).rejects.toThrow(); + expect(f.state.modelCalls).toBe(1); + }); + + it('honors a generation kill switch during the actual model await', async () => { + const f = await fixture(); await f.enrollAndVerify(); + f.state.beforeModelReturn = async () => { f.state.enabled = false; }; + expect((await f.process()).outcome).not.toBe('candidate'); + const source = await f.runtime.readSource(f.actors.staff, learningTicketId); + const work = await f.runtime.readWork(f.actors.staff, { ticketId: learningTicketId, sourceGeneration: source.sourceGeneration }); + expect(work.candidate).toBeUndefined(); + expect(f.state.modelCalls).toBe(1); + expect(await f.process()).toEqual({ outcome: 'held', reason: 'learning_disabled' }); + expect(f.state.modelCalls).toBe(1); + }); + + it('keeps privacy withdrawal and actual source reconciliation available with generation OFF', async () => { + const f = await fixture(); await f.enrollAndVerify(); const { articleId } = await f.delivered(); + await f.review(articleId); await f.evidenceAndPublish(articleId); + expect(f.actors.staff.permissions).not.toContain(supportPermissions.learningProcess); + const retirement = await f.ports.retirementAccess.resolve(new AbortController().signal); + expect(retirement.outcome).toBe('ready'); + if (retirement.outcome !== 'ready') throw new Error('Synthetic retirement authority unavailable'); + expect(retirement.authority.access.permissions).toContain(supportPermissions.learningProcess); + expect(retirement.authority.access.permissions).not.toContain(knowledgePermissions.publish); + f.state.enabled = false; + const result = await f.runtime.withdraw(f.actors.staff, { ticketId: learningTicketId, + clientCommandId: 'privacy-withdraw-exact', reason: 'privacy_withdrawal' }); + expect(result.state).toBe('withdrawn'); + expect((await f.runtime.reconcileSource(learningTicketId)).outcome).toBe('reconciled'); + await expect(f.knowledge.getPublishedArticle(f.actors.customer, { articleId })).rejects.toThrow(); + expect(f.state.modelCalls).toBe(1); + }); + + it('preserves actual aligned KB015 missing-draft identity and public coordinator target_unavailable', async () => { + const f = await fixture(); + const port = createSupportLearningKnowledgePort(f.knowledge); + await expect(f.knowledge.getDraft(f.actors.admin, { articleId: 'missing-guide' })).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + await expect(port.getDraft(f.actors.admin, { articleId: 'missing-guide' })).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + await f.enrollAndVerify(); expect((await f.process()).outcome).toBe('candidate'); + f.state.explicitDraftIds = ['missing-guide']; + expect(await f.process()).toMatchObject({ outcome: 'held', reason: 'target_unavailable' }); + }); + + it('preserves an unrecognized genuine KB authorization error without translating its identity', async () => { + const f = await fixture(); + let observed: unknown; + const port = createSupportLearningKnowledgePort({ ...f.knowledge, async getDraft(...args) { + try { return await f.knowledge.getDraft(...args); } + catch (error) { observed = error; throw error; } + } }); + const failure = await port.getDraft(f.actors.customer, { articleId: 'private-guide' }).catch((error: unknown) => error); + expect(failure).toBeInstanceOf(KnowledgeBaseAuthorizationError); + expect(failure).toBe(observed); + }); + + it('retries actual reconciliation when a genuine SDK conflict is forwarded at the public read boundary', async () => { + const f = await fixture(); await f.enrollAndVerify(); const { articleId } = await f.delivered(); + await f.review(articleId); await f.evidenceAndPublish(articleId); + const draft = await f.knowledge.getDraft(f.actors.admin, { articleId }); + let actualConflict: RepositoryConflictError | undefined; + try { + await f.knowledge.updateDraft(f.actors.admin, { ...f.command('stale-edit', draft.generation - 1), articleId, collectionId: draft.revision.collectionId, + draft: { kind: draft.revision.kind, title: draft.revision.title, summary: draft.revision.summary, + content: draft.revision.content, tags: draft.revision.tags, applicability: draft.revision.applicability } }); + } catch (error) { + if (!(error instanceof RepositoryConflictError)) throw error; + actualConflict = error; + } + expect(actualConflict).toBeInstanceOf(RepositoryConflictError); + const conflict = actualConflict; + if (conflict === undefined) throw new Error('Actual stale SDK mutation did not conflict'); + let injected = false; let reads = 0; + // The error is genuine SDK output from the stale public mutation above. + // Forward it once after a real read; this is not a fabricated Store race. + f.setKnowledge({ ...f.knowledge, async getDraft(...args) { + reads += 1; + const result = await f.knowledge.getDraft(...args); + if (!injected) { injected = true; throw conflict; } + return result; + } }); + await expect(createSupportLearningKnowledgePort({ ...f.knowledge, async getDraft(...args) { + await f.knowledge.getDraft(...args); throw conflict; + } }).getDraft(f.actors.admin, { articleId })).rejects.toBeInstanceOf(RepositoryConflictError); + await f.runtime.withdraw(f.actors.staff, { ticketId: learningTicketId, + clientCommandId: 'withdraw-before-conflict', reason: 'privacy_withdrawal' }); + expect((await f.runtime.reconcileSource(learningTicketId)).outcome).toBe('reconciled'); + expect(injected).toBe(true); expect(reads).toBeGreaterThan(1); + expect(f.state.modelCalls).toBe(1); + }); +}); diff --git a/worker/src/support-learning.ts b/worker/src/support-learning.ts new file mode 100644 index 0000000..092363c --- /dev/null +++ b/worker/src/support-learning.ts @@ -0,0 +1,623 @@ +import { hasPermission, type AccessContext } from '@pegma/authorization-core'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { + createSupportLearningHandlers, + type SupportLearningHandlerOptions, +} from './support-learning-handlers'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import { + createSupportDeskLearning, + createSupportDeskStagedLearningReviews, + createSupportDeskLearningSourceVerifier, + type LearningProcessResult, + type LearningScanBounds, + type LearningReviewCommand, + type ProcessLearningWorkCommand, + type SupportDeskLearningOptions, + type SupportDeskLearningSourceVerifierOptions, +} from '@pegma/support-desk-ai'; +import { + SupportDeskAuthorizationError, + SupportDeskConflictError, + type SupportDeskApplication, + type StaffTicketView, + type ResolutionLearningSourceResult, + supportPermissions, + type EnrollResolutionLearningCommand, + type InvalidateResolutionEvidenceCommand, + type ResolutionLearningApplication, + type ResolutionLearningKey, + type ResolutionLearningOptions, + type ReviewResolutionLearningProposalCommand, + type SubmitResolutionEvidenceCommand, + type WithdrawResolutionLearningSourceCommand, +} from '@pegma/support-desk-application'; +import type { Clock } from '@pegma/spine'; +import { + createSupportLearningKnowledgePort, + supportLearningCommandIdentity, + type DirectLearningKnowledge, + type SupportLearningProcessingPorts, + type SupportLearningStaffAccess, + type SupportLearningStaffOperation, + type SupportLearningStagedReviewOptions, +} from './support-learning-ports'; +import type { SupportLearningReviewDispatch } from './support-learning-review-queue'; + +type Packet = Omit & { + readonly clientCommandId: string; +}; +export type LearningEnrollmentPacket = Packet; +export type LearningVerifiedFixPacket = Packet< + Omit & { + readonly evidence: Extract< + SubmitResolutionEvidenceCommand['evidence'], + { readonly kind: 'staff_verified_fix' } + >; + } +>; +export type LearningReviewPacket = Packet; +export type LearningReviewIntentPacket = Packet; +export type LearningReviewHumanGuard = () => void | Promise; +export type LearningInvalidationPacket = Packet; +export type LearningWithdrawalPacket = Packet; + +type LearningIntakeContentFence = 'resolution_unavailable' | 'solution_unavailable' | 'resolution_cycle_changed'; + +export type LearningIntakeRecoveryResult = { + readonly ticketId: string; + readonly commandId: string; + readonly operation: 'enroll' | 'evidence'; +} & ( + | { readonly outcome: 'accepted'; readonly result: ResolutionLearningSourceResult } + | { readonly outcome: 'pending' } + | { readonly outcome: 'superseded'; readonly expectedRevision: number; readonly observedRevision: number; readonly fence?: LearningIntakeContentFence } +); + +/** Intake is a separate SDK switch from model processing. Neither defaults ON. */ +export function supportLearningApplicationOptions( + options: ResolutionLearningOptions = {}, +): ResolutionLearningOptions { + return Object.freeze({ ...options, enabled: options.enabled === true }); +} + +/** + * Construct before KB; pass this SAME verifier to KB and the learning runtime. + * For a known real SDK graph, explicitly select readScheduling:'sdk' HERE and + * on SupportLearningRuntimeOptions. The two producer read boundaries opt in + * independently; no customer field or structural-port detection selects it. + * Omitted options preserve the serial custom-port path. + */ +export function createSupportLearningSourceBridge( + options: SupportDeskLearningSourceVerifierOptions, +) { + return createSupportDeskLearningSourceVerifier(options); +} + +export interface SupportLearningRuntimeOptions { + readonly application: ResolutionLearningApplication & Partial>; + readonly knowledge: DirectLearningKnowledge; + readonly sources: SupportDeskLearningOptions['sources']; + readonly clock: Clock; + readonly staffAccess: SupportLearningStaffAccess; + /** Server-only staff boundary, including authority, SDK work and final ACK. */ + readonly staffOperationMilliseconds?: number; + readonly processingEnabled?: () => boolean; + readonly ports?: Partial; + readonly stagedReviews?: SupportLearningStagedReviewOptions; + /** Explicit only for the known real SDK read graph; custom ports remain serial. */ + readonly readScheduling?: SupportDeskLearningOptions['readScheduling']; +} + +export type SupportLearningUnavailableReason = + | 'unavailable' + | 'staff_deadline' + | 'staff_authority_unavailable' + | 'processing_readiness_unavailable' + | 'review_checks_unavailable'; + +export class SupportLearningUnavailableError extends Error { + readonly code = 'support_learning_unavailable'; + constructor(readonly reason: SupportLearningUnavailableReason = 'unavailable') { + super('Support learning is unavailable'); + this.name = 'SupportLearningUnavailableError'; + } +} + +/** + * No HTTP, issuer, scheduler, Store or publication authority is created here. + * The later browser adapter must also fence its original cookie/session/headers. + */ +export function createSupportLearningRuntime(options: SupportLearningRuntimeOptions) { + return createLearningRuntime(options); +} + +// Only this module can select the browser lane. Its AccessContext-taking +// implementation is never returned from a browser composition factory. +const browserLane = Symbol('support-learning-browser-lane'); + +function createLearningRuntime( + options: SupportLearningRuntimeOptions, + lane?: typeof browserLane, +) { + const ports = options.ports ?? {}; + const staffOperationMilliseconds = options.staffOperationMilliseconds ?? 25_000; + if (!Number.isSafeInteger(staffOperationMilliseconds) || + staffOperationMilliseconds < 1 || staffOperationMilliseconds > 25_000) + throw new TypeError('Invalid staff operation boundary'); + const processingEnabled = (): boolean => { + try { return options.processingEnabled?.() === true; } + catch { throw new SupportLearningUnavailableError('processing_readiness_unavailable'); } + }; + const unavailable = async (): Promise => { + throw new SupportLearningUnavailableError(); + }; + const unavailableChecks: SupportLearningProcessingPorts['checks'] = { + resolvePolicy: async () => ({ outcome: 'unavailable' }), + check: async () => ({ outcome: 'held' }), + verify: async () => null, + }; + const coordinatorOptions: SupportDeskLearningOptions = { + application: options.application, + knowledge: createSupportLearningKnowledgePort(options.knowledge), + sources: options.sources, + clock: options.clock, + serviceAccess: ports.serviceAccess ?? { resolve: async () => ({ outcome: 'inactive' }) }, + knowledgeAccess: ports.knowledgeAccess ?? { resolve: async () => ({ outcome: 'inactive' }) }, + retirementAccess: ports.retirementAccess ?? { resolve: async () => ({ outcome: 'inactive' }) }, + configuration: { + async resolve(expected, signal) { + if (!processingEnabled() || ports.configuration === undefined) + return { outcome: 'disabled' }; + const result = await ports.configuration.resolve(expected, signal); + return processingEnabled() ? result : { outcome: 'disabled' }; + }, + }, + checks: ports.checks ?? unavailableChecks, + model: ports.model ?? { generate: unavailable }, + usage: ports.usage ?? { + reserve: async () => ({ outcome: 'denied' }), + reconcile: async () => 'pending', + }, + targets: ports.targets ?? { + resolveScope: async () => ({ outcome: 'held' }), + select: async () => ({ outcome: 'held' }), + }, + tokenCounter: ports.tokenCounter ?? { count: () => { throw new SupportLearningUnavailableError(); } }, + storageCommandAttempts: 2, + ...(options.readScheduling === undefined ? {} : { readScheduling: options.readScheduling }), + }; + const coordinator = createSupportDeskLearning(coordinatorOptions); + function stagedEnabled(): boolean { + try { return options.stagedReviews?.enabled() === true; } catch { return false; } + } + function stagedCoordinator() { + if (!stagedEnabled()) throw new SupportLearningUnavailableError(); + return createSupportDeskStagedLearningReviews({ + ...coordinatorOptions, + maxOperationMilliseconds: staffOperationMilliseconds, + async resolveActor({ principalId, signal }) { + if (!stagedEnabled() || signal.aborted) throw new SupportLearningUnavailableError(); + const access = await options.staffAccess.resolve(principalId, signal); + if (!stagedEnabled() || signal.aborted) throw new SupportLearningUnavailableError(); + return access; + }, + }); + } + // The process coordinator checks the host switch at each SDK service fence. + // The review/reconciliation coordinator retains independent read authority. + const processingCoordinator = createSupportDeskLearning({ + ...coordinatorOptions, + serviceAccess: { + async resolve(signal) { + if (!processingEnabled() || ports.serviceAccess === undefined) + return { outcome: 'inactive' }; + const result = await ports.serviceAccess.resolve(signal); + return processingEnabled() ? result : { outcome: 'inactive' }; + }, + }, + }); + + async function staff( + original: AccessContext, + permission: string, + operation: (access: AccessContext, boundary: { + readonly signal: AbortSignal; + ensure(): void; + current(): Promise; + }) => Promise, + ): Promise { + const bound = structuredClone(original); + // Ordinary intake/evidence/withdrawal retain their standalone resolver + // path. Only reads and the exact review protocol share browser fences. + const browserOperation = lane === browserLane && + (permission === supportPermissions.learningRead || permission === supportPermissions.learningReview); + const started = performance.now(); + const controller = new AbortController(); + const ensure = (): void => { + if (controller.signal.aborted || performance.now() - started >= staffOperationMilliseconds) + throw new SupportLearningUnavailableError('staff_deadline'); + }; + let rejectDeadline: (error: Error) => void = () => {}; + const deadline = new Promise((_resolve, reject) => { rejectDeadline = reject; }); + const timer = setTimeout(() => { + rejectDeadline(new SupportLearningUnavailableError('staff_deadline')); + controller.abort(); + }, staffOperationMilliseconds); + const within = async (action: () => Promise): Promise => { + const value = await Promise.race([ + Promise.resolve().then(() => { ensure(); return action(); }), + deadline, + ]); + ensure(); + return value; + }; + const current = async (): Promise => { + ensure(); + if (original.principalId !== bound.principalId) + throw new SupportDeskAuthorizationError(permission); + let resolved: AccessContext | null; + try { + resolved = await within(() => options.staffAccess.resolve(bound.principalId, controller.signal)); + } catch { + ensure(); + throw new SupportLearningUnavailableError('staff_authority_unavailable'); + } + if ( + resolved === null || resolved.principalId !== bound.principalId || + original.principalId !== bound.principalId + ) + throw new SupportDeskAuthorizationError(permission); + const access: AccessContext = { + principalId: bound.principalId, + policyVersion: resolved.policyVersion, + roles: resolved.roles.filter((role) => bound.roles.includes(role)), + entitlements: resolved.entitlements.filter((entry) => bound.entitlements.includes(entry)), + permissions: resolved.permissions.filter((entry) => bound.permissions.includes(entry)), + }; + if (!hasPermission(access, permission)) + throw new SupportDeskAuthorizationError(permission); + if (!hasPermission(access, supportPermissions.queueRead)) + throw new SupportDeskAuthorizationError(supportPermissions.queueRead); + return access; + }; + try { + let access: AccessContext; + if (browserOperation) { + // The private HTTP handler has just resolved the original browser's + // current roles, Identity and session. Do not immediately repeat only + // its roles/Identity subset. No caller can supply this internal lane. + ensure(); + if (original.principalId !== bound.principalId || !hasPermission(bound, permission)) + throw new SupportDeskAuthorizationError(permission); + if (!hasPermission(bound, supportPermissions.queueRead)) + throw new SupportDeskAuthorizationError(supportPermissions.queueRead); + access = bound; + } else { + access = await current(); + } + const result = await within(() => operation(access, { signal: controller.signal, ensure, current })); + // Revocation can withhold an ACK after a committed SDK mutation. The + // same deadline also bounds direct SDK calls that cannot be cancelled. + // A late commit remains unknown until the original immutable packet is + // replayed; timeout neither rolls it back nor launches another mutation. + // The Request-only browser lane performs its complete fresh browser + // closing check and synchronous response projection in the handler. + // Proof-time current() above still resolves independently in both lanes. + if (!browserOperation) await current(); + return result; + } finally { + clearTimeout(timer); + controller.abort(); + } + } + + async function command( + access: AccessContext, + permission: string, + operation: SupportLearningStaffOperation, + input: Command, + invoke: (current: AccessContext, packet: Omit & { commandId: string; correlationId: string }, signal: AbortSignal, boundary: { + readonly signal: AbortSignal; + ensure(): void; + current(): Promise; + }) => Promise, + ) { + const packet = structuredClone(input); + const actor = access.principalId; + return staff(access, permission, async (current, boundary) => { + const { clientCommandId, ...fields } = packet; + const identity = await supportLearningCommandIdentity({ + principalId: actor, ticketId: packet.ticketId, operation, clientCommandId, + }); + boundary.ensure(); + return invoke(current, { ...fields, ...identity }, boundary.signal, boundary); + }); + } + + function recoverIntake( + access: AccessContext, operation: 'enroll' | 'evidence', input: Command, + invoke: (current: AccessContext, packet: Omit & { commandId: string; correlationId: string }) => Promise, + contentFence?: (view: StaffTicketView, packet: Omit, + current: () => Promise) => Promise, + ): Promise { + return command(access, supportPermissions.learningEvidenceSubmit, operation === 'enroll' ? 'enroll' : 'verified_fix', input, + async (current, packet, _signal, boundary): Promise => { + const scope = { ticketId: packet.ticketId, commandId: packet.commandId, operation }; + // An exact accepted ACK wins before any mutable ticket observation. + try { return { ...scope, outcome: 'accepted', result: await invoke(current, packet) }; } + catch (error) { boundary.ensure(); if (!(error instanceof SupportDeskConflictError)) throw error; } + const read = options.application.readStaffTicket; + if (read === undefined) throw new SupportLearningUnavailableError(); + const view = await read.call(options.application, await boundary.current(), packet.ticketId); + boundary.ensure(); + const revision = view.ticket.revision; + if (view.ticket.id !== packet.ticketId || !Number.isSafeInteger(revision) || revision < 1) + throw new SupportLearningUnavailableError(); + if (revision < packet.expectedRevision) return { ...scope, outcome: 'pending' }; + const fence = revision === packet.expectedRevision + ? await contentFence?.(view, packet, boundary.current) : undefined; + boundary.ensure(); + if (revision === packet.expectedRevision && fence === undefined) return { ...scope, outcome: 'pending' }; + // A newer revision or an immutable prerequisite at this exact revision + // excludes future application. Public message/status/cycle repairs + // advance the ticket revision. Retry the exact command AFTER the proof + // so a raced accepted receipt wins before ownership is released. + try { return { ...scope, outcome: 'accepted', result: await invoke(await boundary.current(), packet) }; } + catch (error) { boundary.ensure(); if (!(error instanceof SupportDeskConflictError)) throw error; } + // This proves that the old revision cannot act in the future. Earlier + // acceptance may remain historically unknown for retained legacy data. + return { ...scope, outcome: 'superseded', expectedRevision: packet.expectedRevision, observedRevision: revision, + ...(fence === undefined ? {} : { fence }) }; + }); + } + + function processingReady(): 'disabled' | 'readiness_unavailable' | 'unavailable' | 'ready' { + try { if (!processingEnabled()) return 'disabled'; } + catch { return 'readiness_unavailable'; } + return [ports.serviceAccess, ports.knowledgeAccess, ports.retirementAccess, + ports.configuration, ports.checks, ports.model, ports.usage, ports.targets, + ports.tokenCounter].some((port) => port === undefined) ? 'unavailable' : 'ready'; + } + + async function reviewCommand( + access: AccessContext, + input: LearningReviewIntentPacket, + invoke: (current: AccessContext, packet: LearningReviewCommand, boundary: { + readonly signal: AbortSignal; + ensure(): void; + current(): Promise; + }) => Promise, + ): Promise { + const bound = structuredClone(input); + return staff(access, supportPermissions.learningReview, async (current, boundary) => { + if (bound.intent.reviewerId !== current.principalId) + throw new SupportDeskAuthorizationError(supportPermissions.learningReview); + const { clientCommandId, ...fields } = bound; + const identity = await supportLearningCommandIdentity({ principalId: current.principalId, + ticketId: bound.intent.ticketId, operation: 'review', clientCommandId }); + boundary.ensure(); + return invoke(current, { ...fields, ...identity }, boundary); + }); + } + + function guardedReviewCoordinator(boundary: { + readonly signal: AbortSignal; + ensure(): void; + current(): Promise; + }, verifyHumanBeforeCommit?: LearningReviewHumanGuard) { + const verifyCurrentReviewer = async () => { + const access = await boundary.current(); + for (const permission of [knowledgePermissions.draftRead, knowledgePermissions.provenanceRead]) + if (!hasPermission(access, permission)) throw new SupportDeskAuthorizationError(permission); + await verifyHumanBeforeCommit?.(); boundary.ensure(); + }; + return createSupportDeskLearning({ ...coordinatorOptions, + application: { ...options.application, async reviewResolutionLearningProposal(actor, packet, guard) { + return options.application.reviewResolutionLearningProposal(actor, packet, async () => { + await verifyCurrentReviewer(); + await guard(); + await verifyCurrentReviewer(); + }); + } }, + }); + } + + return Object.freeze({ + enroll: (access: AccessContext, input: LearningEnrollmentPacket) => + command(access, supportPermissions.learningEvidenceSubmit, 'enroll', input, + (current, packet) => options.application.enrollResolutionLearning(current, packet)), + submitVerifiedFix: (access: AccessContext, input: LearningVerifiedFixPacket) => + command(access, supportPermissions.learningEvidenceSubmit, 'verified_fix', input, + (current, packet) => options.application.submitResolutionEvidence(current, packet)), + recoverEnrollment: (access: AccessContext, input: LearningEnrollmentPacket) => + recoverIntake(access, 'enroll', input, (current, packet) => options.application.enrollResolutionLearning(current, packet)), + recoverVerifiedFix: (access: AccessContext, input: LearningVerifiedFixPacket) => + recoverIntake(access, 'evidence', input, (current, packet) => options.application.submitResolutionEvidence(current, packet), + async (view, packet, current) => { + if (!['resolved', 'closed'].includes(view.ticket.status) || view.ticket.resolvedAt === undefined) + return 'resolution_unavailable'; + if (!view.messages.some((message) => message.id === packet.evidence.solutionMessageId && message.visibility === 'customer')) + return 'solution_unavailable'; + // Resolution cycles only advance with public ticket mutations. + // The separate public read requires its own existing permission. + const access = await current(); + if (!hasPermission(access, supportPermissions.learningRead)) return undefined; + const source = await options.application.readResolutionLearningSource(access, packet.ticketId); + if (source.ticketId !== packet.ticketId || !Number.isSafeInteger(source.resolutionCycle) || source.resolutionCycle < 1) + throw new SupportLearningUnavailableError(); + return source.resolutionCycle !== packet.resolutionCycle ? 'resolution_cycle_changed' : undefined; + }), + reviewProposal(access: AccessContext, input: LearningReviewPacket, + verifyHumanBeforeCommit?: LearningReviewHumanGuard) { + if (verifyHumanBeforeCommit !== undefined && typeof verifyHumanBeforeCommit !== 'function') + throw new TypeError('Review submission requires a callable current-human guard'); + return command(access, supportPermissions.learningReview, 'review', input, + (current, packet, _signal, boundary) => { + if (ports.checks === undefined) + throw new SupportLearningUnavailableError('review_checks_unavailable'); + // SDK guards share this staff boundary instead of starting another + // independent host timer around the same review operation. + return guardedReviewCoordinator(boundary, verifyHumanBeforeCommit) + .reviewProposal(current, packet, { signal: boundary.signal }); + }); + }, + prepareReviewIntent(access: AccessContext, key: ResolutionLearningKey) { + const bound = structuredClone(key); + return staff(access, supportPermissions.learningReview, (current, boundary) => + coordinator.prepareReviewIntent(current, bound, { signal: boundary.signal })); + }, + submitReviewIntent(access: AccessContext, input: LearningReviewIntentPacket, + verifyHumanBeforeCommit: LearningReviewHumanGuard) { + if (typeof verifyHumanBeforeCommit !== 'function') + throw new TypeError('Review submission requires a current-human guard'); + return reviewCommand(access, input, (current, packet, boundary) => { + const guarded = guardedReviewCoordinator(boundary, verifyHumanBeforeCommit); + return guarded.submitReviewIntent(current, packet, { signal: boundary.signal }); + }); + }, + /** No model call or review acceptance occurs in this HTTP admission. */ + admitReviewIntent(access: AccessContext, input: LearningReviewIntentPacket, + verifyHumanBeforeCommit: LearningReviewHumanGuard) { + if (typeof verifyHumanBeforeCommit !== 'function') + throw new TypeError('Review admission requires a current-human guard'); + return reviewCommand(access, input, async (current, packet, boundary) => { + const result = await stagedCoordinator().admitReviewIntent(current, packet, { + signal: boundary.signal, + async verifyBeforeCommit() { + boundary.ensure(); + if (!stagedEnabled()) throw new SupportLearningUnavailableError(); + await verifyHumanBeforeCommit(); + boundary.ensure(); + if (!stagedEnabled()) throw new SupportLearningUnavailableError(); + return (): true => { + boundary.ensure(); + if (!stagedEnabled()) throw new SupportLearningUnavailableError(); + return true; + }; + }, + }); + // Admission has already committed. A lost acceleration hint never + // changes the honest durable result; the SDK scan recovers it. + if (result.outcome === 'pending') { + try { await options.stagedReviews?.enqueue({ ticketId: packet.intent.ticketId, commandId: packet.commandId }); } + catch { /* The SDK pending row remains the authoritative outbox. */ } + } + return result; + }); + }, + readStagedReviewStatus: (access: AccessContext, input: LearningReviewIntentPacket) => + reviewCommand(access, input, (current, packet, boundary) => + stagedCoordinator().readReviewStatus(current, packet, { signal: boundary.signal })), + cancelStagedReview(access: AccessContext, input: LearningReviewIntentPacket, + verifyHumanBeforeCommit: LearningReviewHumanGuard) { + if (typeof verifyHumanBeforeCommit !== 'function') + throw new TypeError('Review cancellation requires a current-human guard'); + return reviewCommand(access, input, (current, packet, boundary) => + stagedCoordinator().cancelReview(current, packet, { signal: boundary.signal, + async verifyBeforeCommit() { + boundary.ensure(); + if (!stagedEnabled()) throw new SupportLearningUnavailableError(); + await verifyHumanBeforeCommit(); + boundary.ensure(); + return (): true => { + boundary.ensure(); + if (!stagedEnabled()) throw new SupportLearningUnavailableError(); + return true; + }; + }, + })); + }, + stagedReviewDispatch(): SupportLearningReviewDispatch { + return Object.freeze({ + scanPending: (bounds) => stagedCoordinator().scanPending(bounds), + async process(input) { + const result = await stagedCoordinator().processReview(input); + // Only authoritative no-pending or a canonical completed receipt + // retires the transport hint. Every other result remains discoverable. + return result.outcome === 'not_pending' || result.outcome === 'completed' ? 'settled' : 'pending'; + }, + }); + }, + readReviewReceipt: (access: AccessContext, input: LearningReviewIntentPacket) => + reviewCommand(access, input, (current, packet, boundary) => + coordinator.readReviewReceipt(current, packet, { signal: boundary.signal })), + cancelReview(access: AccessContext, input: LearningReviewIntentPacket, + verifyHumanBeforeCommit: LearningReviewHumanGuard) { + if (typeof verifyHumanBeforeCommit !== 'function') + throw new TypeError('Review cancellation requires a current-human guard'); + return reviewCommand(access, input, (current, packet, boundary) => + coordinator.cancelReview(current, packet, { signal: boundary.signal, + async verifyBeforeCommit() { + await boundary.current(); await verifyHumanBeforeCommit(); boundary.ensure(); + }, + })); + }, + invalidate: (access: AccessContext, input: LearningInvalidationPacket) => + command(access, supportPermissions.learningEvidenceSubmit, 'invalidate', input, + (current, packet) => options.application.invalidateResolutionEvidence(current, packet)), + withdraw: (access: AccessContext, input: LearningWithdrawalPacket) => + command(access, supportPermissions.learningWithdraw, 'withdraw', input, + (current, packet) => options.application.withdrawResolutionLearningSource(current, packet)), + readSource: (access: AccessContext, ticketId: string) => + staff(access, supportPermissions.learningRead, (current) => + options.application.readResolutionLearningSource(current, ticketId)), + readWork(access: AccessContext, key: ResolutionLearningKey) { + const bound = structuredClone(key); + return staff(access, supportPermissions.learningRead, (current) => + options.application.readResolutionLearningWork(current, bound)); + }, + async scanCandidates(bounds: LearningScanBounds) { + const state = processingReady(); + if (state !== 'ready') return { outcome: 'held' as const, reason: `learning_${state}` }; + return processingCoordinator.scanCandidates(structuredClone(bounds)); + }, + async processWork(input: ProcessLearningWorkCommand): Promise { + const state = processingReady(); + if (state !== 'ready') return { outcome: 'held', reason: `learning_${state}` }; + return processingCoordinator.processWork(structuredClone(input)); + }, + // Privacy and source reconciliation stay available independently of the + // generation switch and provider configuration. The SDK checks authority. + reconcileSource: (ticketId: string) => coordinator.reconcileSource(ticketId), + }); +} + +export type SupportLearningRuntime = ReturnType; + +/** + * Trusted host composition, returning only a Request handler. Original browser + * coordinates and permission ceilings are created inside the existing handler; + * no optimized access-taking method or authority observation escapes here. + */ +export function createSupportLearningBrowserHandlers( + options: Omit & { + readonly learning: Omit; + }, +): (request: Request) => Promise { + const { learning, ...browser } = options; + const resolve = createAgentPrincipalResolver(browser); + let runtime: SupportLearningRuntime | undefined; + return createSupportLearningHandlers({ + ...browser, + stagedReviewsEnabled: () => { + try { return learning.stagedReviews?.enabled() === true; } catch { return false; } + }, + runtime() { + // SDK composition is lazy; disabled and unauthenticated requests do not + // construct it. This closure retains no browser or permission snapshot. + runtime ??= createLearningRuntime({ + ...learning, + staffAccess: { + async resolve(principalId, signal) { + if (signal.aborted) throw new SupportLearningUnavailableError('staff_deadline'); + const access = await resolve(principalId); + if (signal.aborted) throw new SupportLearningUnavailableError('staff_deadline'); + return access; + }, + }, + }, browserLane); + return runtime; + }, + }); +} diff --git a/worker/worker-configuration.d.ts b/worker/worker-configuration.d.ts index ea0052f..b3c6575 100644 --- a/worker/worker-configuration.d.ts +++ b/worker/worker-configuration.d.ts @@ -1,9 +1,11 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: a18220f8dbb36158ee2acfd36ef59c5b) +// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 70e83c2cdd509101b5441bbc4d72b275) // Runtime types generated with workerd@1.20260722.1 2026-07-28 nodejs_compat interface __BaseEnv_Env { IDENTITY_DB: D1Database; + SUPPORT_LEARNING_REVIEWS: Queue; PEGMA_KNOWLEDGE_ENABLED: "false"; + PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: "false"; PEGMA_AGENT_CLIENTS_JSON: "[]"; PEGMA_KNOWLEDGE_BROWSER_LIMIT: "120"; PEGMA_AGENT_RESOURCE_LIMIT: "300"; @@ -23,7 +25,7 @@ type StringifyValues> = { [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} + interface ProcessEnv extends StringifyValues> {} } // Begin runtime types diff --git a/worker/wrangler.jsonc b/worker/wrangler.jsonc index 2cb3b3c..3ce3943 100644 --- a/worker/wrangler.jsonc +++ b/worker/wrangler.jsonc @@ -22,6 +22,7 @@ ], "vars": { "PEGMA_KNOWLEDGE_ENABLED": "false", + "PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED": "false", "PEGMA_AGENT_CLIENTS_JSON": "[]", "PEGMA_KNOWLEDGE_BROWSER_LIMIT": "120", "PEGMA_AGENT_RESOURCE_LIMIT": "300", @@ -48,6 +49,16 @@ "migrations_dir": "migrations", }, ], + // Resource existence is verified before deploying this opt-in configuration. + "queues": { + "producers": [ + { "binding": "SUPPORT_LEARNING_REVIEWS", "queue": "pegma-dev-support-learning-reviews" }, + ], + "consumers": [ + { "queue": "pegma-dev-support-learning-reviews", "max_batch_size": 1, + "max_retries": 3, "dead_letter_queue": "pegma-dev-support-learning-reviews-dlq" }, + ], + }, "observability": { "enabled": true, "head_sampling_rate": 1,