diff --git a/README.md b/README.md index 5541cba..5246545 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,13 @@ retiregolden.org, runs the stack on Azure). Datadog. Workers Logs persistence is enabled via Wrangler `observability` (the Cloudflare log store). Datadog ships when `DATADOG_API_KEY` is set as a Worker secret. -- The **portability exhibit**: the account API composes exact - `@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.2.1`, +- The **portability exhibit**: the account API composes + `@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions`, `@pegma/identity@0.1.2`, and `@pegma/authorization-identity@0.4.0` - through `worker/src/identity-runtime.ts`. + through `worker/src/identity-runtime.ts`. Current dependency selections are + recorded in [`package.json`](package.json) and [`pnpm-lock.yaml`](pnpm-lock.yaml); + the [Support composition snapshot](docs/SUPPORT_COMPOSITION.md#packages) + distinguishes the current public graph from historical qualification receipts. - **Environment runbooks** for a synthetic Bench Ticket demo (email-code identity, sessions, mail catcher, support desk, health): [https://pegma.dev/runbooks](https://pegma.dev/runbooks). diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index a05a078..d0e3aca 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -8,7 +8,8 @@ the existing deployment workflow, which deploys the Worker before the Pages site. Confirm that run and the metadata readback below before client tests. Native-client acceptance and broader rollout remain pending. The host uses exact published `@pegma/agent-access@0.1.1` and all four -`@pegma/knowledge-base-*` packages at `0.1.6`, over its existing Identity, +`@pegma/knowledge-base-*` packages in the +[current public graph](SUPPORT_COMPOSITION.md#packages), over its existing Identity, Sessions, stored roles and D1 Store. The public catalog at `/api/mcp` remains separate from protected article authoring. @@ -20,21 +21,21 @@ at signed source [`72358940203e1d398087f2fbe49d33ee95b6fb71`](https://github.com/pegma-dev/rate-limit/commit/72358940203e1d398087f2fbe49d33ee95b6fb71) 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.7`, including the optional AI coordinator. The separate -synthetic stage remains default-disabled. The -[verified Support Desk `0.2.7` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.7) -pins its optional AI dependency on KB application/contracts `0.1.6`. +`@pegma/rate-limit@0.2.0` dependency. The current host uses the +[public Support/KB/Sessions graph](SUPPORT_COMPOSITION.md#packages), including the +optional AI coordinator's exact direct KB application/contracts dependencies. +The manifest and lockfile are authoritative for current selections. The separate +synthetic stage remains default-disabled. 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.6` packages are installed in the manifest and lockfile. -The release adds bounded native-client MCP request-metadata compatibility and -retains the shared report factory and governed authoring-context/report-query -APIs. Its producer verification covers +The current four direct KB selections are recorded in the linked graph above. +The earlier KB `0.1.6` producer checkpoint added bounded native-client MCP +request-metadata compatibility and retained the shared report factory and +governed authoring-context/report-query APIs. Its producer verification covers original registry bytes, signatures/source provenance and public-consumer checks at signed source [`b2946e149078e0ef460f970c2271c196ea9fc759`](https://github.com/pegma-dev/knowledge-base/commit/b2946e149078e0ef460f970c2271c196ea9fc759). @@ -60,7 +61,7 @@ model. It adds no public ingress or sixth cron to the existing human/KB 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.6`, +The current manifest and lockfile pin the released KB graph linked above, `@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 @@ -222,9 +223,11 @@ 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 adds explicit human takeover plus explicit learning read, evidence submission, review and - withdrawal introduced by policy `pegma.dev-policy-5`. Current policy - `pegma.dev-policy-6` retains them and adds human engineering read, evidence - submission, review, withdrawal and repository-policy read. Learning processing + withdrawal introduced by policy `pegma.dev-policy-5`. The + [current policy](SUPPORT_COMPOSITION.md#authorization) retains them alongside + human engineering read, evidence + submission, review, withdrawal and repository-policy read, plus named human + release-follow-up read, review and evidence submission. 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 @@ -237,6 +240,9 @@ The [host policy](../worker/src/support-access.ts) keeps authority explicit: Authenticated accounts receive the named article-read permission; collection audience policy and the released KB's current publication checks still decide which guides they can read. Role names do not bypass those checks. +Their separate customer Support defaults include owned success confirmation, +as defined by the [host policy](../worker/src/support-access.ts); this does not +grant KB test-report confirmation or publication authority. Portal article, search and collection results are withheld if the session or principal changes, or any captured permission is lost during the read. Added grants do not invalidate an otherwise authorized result. diff --git a/docs/SUPPORT_ASSISTANT_STAGE.md b/docs/SUPPORT_ASSISTANT_STAGE.md index 41ae20d..1438652 100644 --- a/docs/SUPPORT_ASSISTANT_STAGE.md +++ b/docs/SUPPORT_ASSISTANT_STAGE.md @@ -51,8 +51,9 @@ 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.7` with direct Knowledge Base -`0.1.6`; [package.json](../package.json) is authoritative. +The current package selection is Support Desk `0.2.10` with direct Knowledge Base +`0.1.8`; [package.json](../package.json) and the +[lockfile](../pnpm-lock.yaml) are authoritative. From the repository root: @@ -90,7 +91,7 @@ reconciliation, with the persisted ledger stable across later duplicates. These historical results apply to that fictional fixture. The earlier public `0.2.5` graph passed the normal 1,125-test local/CI [adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint). -That checkpoint does not qualify the current `0.2.7` graph. Current host +That checkpoint does not qualify the current `0.2.10` graph. Current host validation remains pending. Deployed broker timing, retry delivery, CPU use and wider workloads retain their qualification gates. diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index 7b2800f..1a9e156 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -16,13 +16,16 @@ provider and customer activation retain their acceptance gates. See the ## Packages -Exact published versions: - -- `@pegma/support-desk-application@0.2.7` -- `@pegma/support-desk-contracts@0.2.7` -- `@pegma/support-desk-core@0.2.7` -- `@pegma/support-desk-templates@0.2.7` -- `@pegma/support-desk-ai@0.2.7` (optional coordinator) +Public selection as of 2026-11-13: Support Desk `0.2.10`, Knowledge Base `0.1.8` +and Sessions `0.3.0`. [`package.json`](../package.json) and +[`pnpm-lock.yaml`](../pnpm-lock.yaml) are the source of truth for current direct +selections and the installed graph. + +- `@pegma/support-desk-application@0.2.10` +- `@pegma/support-desk-contracts@0.2.10` +- `@pegma/support-desk-core@0.2.10` +- `@pegma/support-desk-templates@0.2.10` +- `@pegma/support-desk-ai@0.2.10` (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) @@ -30,14 +33,18 @@ Exact published versions: All five Support Desk packages have completed producer publication and registry qualification. The optional AI package selects exact KB application -and contracts `0.1.6`; the host selects all four KB packages at that version. +and contracts `0.1.8`; 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.7` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.7), -[verified KB `0.1.6` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6). +acceptance. [Public Support Desk release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.10), +[public KB release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.8). +The earlier [Support `0.2.7`](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.7) +and [KB `0.1.6`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6) +producer checkpoints remain historical; they do not qualify the current host. Peers already present on the host: `@pegma/storage-core@0.4.0`, -`@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.2.1`, -`@pegma/rate-limit@0.2.0`, `@pegma/identity@0.1.2`, `@pegma/spine@0.1.1`. +`@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.3.0`, +`@pegma/rate-limit@0.2.0`, `@pegma/identity@0.1.2` and `@pegma/spine` +(declared range and resolution are recorded in the manifest and lockfile). 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. @@ -48,10 +55,10 @@ uses signed source [Strict release verification](https://github.com/pegma-dev/support-desk/actions/runs/42907283767/job/130161276758) qualifies those historical producer packages. The earlier public `0.2.5` graph passed the [normal local and CI validation checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint). -That checkpoint does not qualify the current `0.2.7` host graph. Current host -validation, review and deployment acceptance remain pending. The current -[Sessions `0.2.1` selection](https://github.com/pegma-dev/sessions/releases/tag/v0.2.1) -includes the verified producer fix for the earlier `0.2.0` default-clock +That checkpoint does not qualify the current public graph above. Current host +validation, review and deployment acceptance remain pending. The earlier +[Sessions `0.2.1` checkpoint](https://github.com/pegma-dev/sessions/releases/tag/v0.2.1) +included the verified producer fix for the earlier `0.2.0` default-clock concurrency defect under a consistent advancing clock. ## Storage namespace @@ -82,9 +89,13 @@ unified host policy's `defaults` (no paid entitlement): - `support.ticket.read.own` - `support.ticket.reply.own` - `support.ticket.request_person.own` +- `support.ticket.confirm_success.own` -Policy version: `pegma.dev-policy-6` — one `PolicyDocumentV1` for the whole -host, schema-validated in tests (see `docs/ROLE_ADOPTION_PLAN.md`). +The current [stored-role policy](../worker/src/support-access.ts) is +`pegma.dev-policy-8` — one `PolicyDocumentV1` for the whole host, +schema-validated in tests (see `docs/ROLE_ADOPTION_PLAN.md`). Version 8 adds +authenticated owner success confirmation; version 7 introduced the three human +release-follow-up rights. These are authority revisions; the schema remains v1. ### Staff (stored `Support` role) @@ -113,6 +124,9 @@ The `Support` role maps to: - `support.engineering.review` - `support.engineering.withdraw` - `support.engineering.policy.read` +- `support.engineering.followup.read` +- `support.engineering.followup.review` +- `support.engineering.followup.evidence.submit` `Admin` and `Knowledge` alone do not grant Support queue authority. Taking over changes handling authority; the existing assignment action remains separate. @@ -162,6 +176,7 @@ Worker routes (same-origin session + CSRF `X-Pegma-CSRF` for mutations): | `GET` | `/api/support/tickets/:id` | Read own; missing/non-owned → same 404 | | `POST` | `/api/support/tickets/:id/replies` | Reply (rate-limited) | | `POST` | `/api/support/tickets/:id/request-person` | Owned human request; body `{ commandId }` | +| `POST` | `/api/support/tickets/:id/confirm-success` | Owned success confirmation; body `{ commandId, lastSeenVisibleMessageId }` | ### Staff (`/api/support/admin/…`) @@ -191,7 +206,7 @@ Worker routes (same-origin session + CSRF `X-Pegma-CSRF` for mutations): ### Human controls -The three human-control routes require the original same-origin browser +The human-control routes require the original same-origin browser session; bearer `Authorization` is rejected. Mutations use the current `csrfToken` from the account/ticket response in `X-Pegma-CSRF`. The server rechecks current Identity, stored Support authority where required, original @@ -287,16 +302,16 @@ invocation. ## Optional resolution learning -The current source selects all five published Support Desk `0.2.7` packages -with the four direct KB `0.1.6` packages. AI `0.2.7` also declares exact KB -`0.1.6` dependencies. The public forwarding port preserves KB error instances; +The current source uses the [public package graph above](#packages), including +the optional AI coordinator's exact direct KB 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.7` APIs. The earlier +use the published Support Desk APIs in that graph. The earlier `0.2.5` host validation checkpoint remains historical. Current host validation, review and deployment acceptance remain pending. Runtime availability and feature activation retain their existing trusted composition and readiness @@ -315,8 +330,10 @@ approval nor delivery publishes a guide: ordinary KB evidence, review and publication gates still apply. Policy `pegma.dev-policy-5` introduced four explicit learning permissions to -`Support`. Current policy `pegma.dev-policy-6` retains those grants and adds -human engineering permissions; learning processing and KB staff access remain +`Support`. The [current host policy](../worker/src/support-access.ts) retains +those grants alongside human engineering and release-follow-up permissions; +authenticated owner success confirmation is a separate customer default. +Learning processing and KB staff access remain separate. Private proposal reads and new review commits also require separately current KB `draftRead` and `provenanceRead`, normally through `Knowledge` or `Admin`. Browser submissions @@ -369,7 +386,7 @@ request/maintenance batching and activation limits remain documented in ## Staged assistant retrieval is separate AI `0.2.2` introduced explicit `stagedRetrieval:true`, retained by the current -`0.2.7` selection; omission remains monolithic. The preparation attempt retrieves authorized sources and records a +public graph above; 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 @@ -446,7 +463,10 @@ Built in the open by RetireGolden, LLC. ## Optional engineering human composition -The [engineering assembly](SUPPORT_ENGINEERING.md) uses policy version 6. +The [engineering assembly](SUPPORT_ENGINEERING.md) introduced its grants in policy +version 6. Version 7 added the separate +[release-follow-up controls](SUPPORT_RELEASE_FOLLOWUP.md). Current policy +version 8 retains both sets of grants and adds owner success confirmation. Support receives the five named human engineering permissions. Admin adds repository-policy read and manage permissions. Policy operations require current Admin and Support queue authority together. diff --git a/docs/SUPPORT_ENGINEERING.md b/docs/SUPPORT_ENGINEERING.md index f9d751d..eea7b69 100644 --- a/docs/SUPPORT_ENGINEERING.md +++ b/docs/SUPPORT_ENGINEERING.md @@ -4,7 +4,8 @@ Developer and operator documentation for the optional engineering assembly. The Worker and staff ticket controller accept the human engineering composition through explicit trusted configuration. The default Worker supplies no such configuration, so engineering intake and review remain OFF. This assembly uses -the five published Support Desk packages at exact version `0.2.7`. +the [current public package graph](SUPPORT_COMPOSITION.md#packages), with exact +selections recorded in the manifest and lockfile. The [runtime](../worker/src/support-engineering.ts), [HTTP adapter](../worker/src/support-engineering-handlers.ts), @@ -15,10 +16,16 @@ The [human composition](../worker/src/support-engineering-composition.ts) provides the request-local assembly. The existing learning queue and its physical phase boundaries continue through the same Worker entry point. +The separate [release-follow-up controls](SUPPORT_RELEASE_FOLLOWUP.md) connect +trusted deployment evidence and explicit staff web updates. Their current +producer and host validation holds are documented in that guide. + ## Authority and defaults -The [stored-role policy](../worker/src/support-access.ts), -`pegma.dev-policy-6`, gives Support these five additional human permissions: +The [stored-role policy](../worker/src/support-access.ts) retains these five +human engineering permissions. See the [current policy and full permission +sets](SUPPORT_COMPOSITION.md#authorization) for its authority revision, customer +defaults and separate human release-follow-up grants: | Published `supportPermissions` member | Current human surface | | --- | --- | @@ -222,6 +229,75 @@ Its retained-owner controls preserve the original account and ticket coordinates Global repository-policy recovery uses current account authority independently of ticket selection. +## GitHub creation receipts and current repository authority + +The [repository adapter](../worker/src/support-engineering-repository.ts) keeps +issue creation separately OFF by default. Its explicit trusted configuration +supplies immutable repository/App/installation coordinates and current issuer +authority. Numeric token scope proves only the selected repository ID, exact +permission scope and expiry; token response entries may contain only that ID. +Full names, ownership, visibility and repository state come from an authoritative +scoped-token repository GET after every asynchronous authentication boundary, +for every issue read and write. That snapshot must still match the approved +identity/state/version. Only synchronous current/enablement guards separate it +from the issue request. + +GitHub offers no atomic visibility precondition for issue creation. A repository +administrator can publish a private repository or its existing content at any +time. The final GET rejects visibility changes during token minting or awaited +authentication; it does not make visibility atomic with the POST. Trusted +activation must retain that external administrator disclosure boundary. + +New issue creation also requires a durable +[creation receipt port](../worker/src/support-engineering-acceptance.ts). +The production composition's existing `attachRuntime` binds it to the actual +Support Store and clock, independently of model/checker readiness. Before that +binding, a new issue write is unavailable. Missing or incomplete production +configuration retains the original OFF behavior and performs no receipt Store +I/O. This adds no default customer, service, role or publication authority. + +An acknowledged one-shot durable intent precedes a new POST. Existing, uncertain +or accepted intents never authorize another physical POST. The captured provider +response must match the approved title, body and normalized label set before the +exact issue acknowledgement is durably recorded. The stored receipt contains +opaque request/source/App/installation/repository bindings, immutable issue +coordinates and the historical accepted payload hash; it stores no issue text, +labels or credentials. + +Create reconciliation and its independent verifier require that matching known +receipt and a current direct observation of its exact issue coordinates/App +origin and repository authority. Mutable markers, copied same-App content, +search absence or indexing delay cannot create acceptance. If the provider HTTP +ACK never arrived, the operation remains unknown for human review with no second +POST. If the exact response was recorded and only the later SDK ACK was lost, +recovery can confirm it with model and creation OFF, including after source +withdrawal. Later legitimate remote title/body/label edits do not erase that +historical receipt. Existing-issue links instead use their approved immutable +coordinates and current reads without creating a receipt or modifying the issue. + +Remote issue text is bounded by the 64 KiB response limit; duplicate display +context is projected to the SDK's title200/body12000 bounds. Projection grants +no issue identity or acceptance authority. Search and create inputs are captured +before awaits. The stream reader skips empty chunks, rejects more than 64 +consecutive empty chunks and enforces a finite 65,600-chunk read budget alongside +the existing byte, abort and nonrenewing operation deadline bounds. + +Per operation, metadata uses two GETs. Duplicate search uses five HTTP requests: +two metadata GETs, one exact-ID scoped-token POST, the final scoped repository GET +and one search GET. Creation uses the same five-request shape with one issue POST +in place of search. Known-receipt create/link reconciliation and its independent +verifier each use five: two metadata GETs, one scoped-token POST, the final scoped +repository GET and one direct issue GET. Read tokens have Metadata read and Issues +read only. Tokens stay private to the operation; no App JWT is minted and no HTTP +request is automatically retried. + +The [actual SDK/MemoryStore cases](../worker/src/support-engineering-github.test.ts) +separate missing provider ACKs from ACK loss after durable recording, retained +source withdrawal, mutable/copyable markers, indexing delay and ID-only grants. +Earlier marker-only Native measurements do not qualify this new receipt path; +fresh registered-route Native qualification must use the actual Store-backed +creation capability and both uncertainty cases. + ## Qualification and configuration The earlier standalone source checkpoint passed its 1,142-test suite with @@ -229,9 +305,10 @@ The earlier standalone source checkpoint passed its 1,142-test suite with engineering HTTP scenarios passed the 50-binding-call and 100-parameter test ceilings. Those results describe the earlier standalone assembly. -The current source selects the verified -[Sessions `0.2.1` release](https://github.com/pegma-dev/sessions/releases/tag/v0.2.1). -Its default read and expiry-sweep observations follow their awaited storage +The current Sessions selection is recorded in the +[public package graph](SUPPORT_COMPOSITION.md#packages) and manifest. The earlier +[Sessions `0.2.1` producer checkpoint](https://github.com/pegma-dev/sessions/releases/tag/v0.2.1) +established that default read and expiry-sweep observations follow their awaited storage snapshots under a consistent advancing clock. Explicit caller instants retain their semantics, and future idle anchors from rollback or skew still fail closed. diff --git a/docs/SUPPORT_LEARNING.md b/docs/SUPPORT_LEARNING.md index 3ba6450..ade6030 100644 --- a/docs/SUPPORT_LEARNING.md +++ b/docs/SUPPORT_LEARNING.md @@ -7,18 +7,20 @@ 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 +The factories, authenticated routes and staff panel exist in source. The +[Worker entry point](../worker/src/index.ts) supports an optional learning +composition. Intake, model processing and staged review remain default off in the +[checked-in configuration](../worker/wrangler.jsonc). +Activation requires the corresponding flags, trusted configuration and authority +ports. 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.7** and its -four direct Knowledge Base packages at **0.1.6**. The qualified -[Support 0.2.7 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.7) -also uses exact KB **0.1.6** public contracts. The +The host selects all five published Support Desk packages at **0.2.10** and its +four direct Knowledge Base packages at **0.1.8**. The qualified +[Support 0.2.10 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.10) +also uses exact KB **0.1.8** 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 @@ -29,10 +31,11 @@ Historically, Support **0.2.1** used nested KB **0.1.2** while this host selecte 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.7 graph. +ordinary fixture passes nor that failure qualifies the current 0.2.10 graph. -The current [host policy](../worker/src/support-access.ts) grants four human -learning permissions through the actual stored, audited **Support** role: +The current [host policy](../worker/src/support-access.ts), `pegma.dev-policy-8`, +grants four human learning permissions through the actual stored, audited +**Support** role: | Permission | Human operation | | --- | --- | @@ -301,8 +304,9 @@ 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 +default `createWorker()` has no staged-review composition. Intake and processing +have separate flags and configuration; the review flag alone supplies neither +their runtime nor trusted processing ports. See the [composition controls](SUPPORT_COMPOSITION.md#optional-resolution-learning). For executed lower-layer composition, see @@ -325,7 +329,7 @@ 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 earlier public `0.2.5` [adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint) -passed 1,125 tests locally and in CI. It does not qualify the current `0.2.7` +passed 1,125 tests locally and in CI. It does not qualify the current `0.2.10` graph. Current host validation, review and deployment acceptance remain pending. Relevant executable sources are the diff --git a/docs/SUPPORT_RELEASE_FOLLOWUP.md b/docs/SUPPORT_RELEASE_FOLLOWUP.md new file mode 100644 index 0000000..9eb912f --- /dev/null +++ b/docs/SUPPORT_RELEASE_FOLLOWUP.md @@ -0,0 +1,284 @@ +# Staff release-follow-up controls + +The default Worker can compose staff-verified deployed-fix evidence and the +bounded SD05 driver. `PEGMA_SUPPORT_RELEASE_FOLLOWUP_ENABLED` controls the +nonpaid staff/source surface; `PEGMA_SUPPORT_RELEASE_FOLLOWUP_PROCESSING_ENABLED` +separately controls background preparation. Both default to `false`. An explicit +`createWorker({ releaseFollowup })` selection retains its existing behavior, +including an explicitly absent selection. OFF routes return 404 before Store +initialization. No new cron, queue, remote issue write or automatic send/publish +is installed. + +This source selects the [current published package graph](SUPPORT_COMPOSITION.md#packages); +the manifest and lockfile record its exact versions. Producer publication is +separate from host deployment acceptance. Development functional evidence and +the unchanged Native 50-query/100-parameter acceptance +are recorded separately; a functional Memory result does not establish that +physical budget, provider quality, CPU use or Workers Free acceptance. + +## Composition and current authority + +The registered createWorker source composition accepts releaseFollowup. +The [trusted port contract](../worker/src/support-release-followup-ports.ts) +requires current release evidence, complete bundle checks, retest-receipt +verification and explicit KB target resolution. The same evidence verifier +reaches the application and coordinator. Optional generation requires separate +evaluated support_release_followup configuration, current service authority, +model, token counter and bounded durable usage policy. Missing generation is +held without a provider call. Checks on retained content remain independent of +paid generation availability. + +The [current host policy](SUPPORT_COMPOSITION.md#authorization) retains the +Support-role grants introduced in version 7: engineeringFollowupRead, +engineeringFollowupReview and engineeringFollowupEvidenceSubmit, alongside its +existing queue and reply authority. Admin or Knowledge alone receives no +follow-up authority. Processing uses an intrinsic service identity with exactly follow-up Process, +Read and queueRead. It has no human account, stored Role grant or review/send +authority. The existing scoped governance reader is reused without new grants. +Work hints contain no saved browser credentials or AccessContext. + +The staff ticket detail supplies the optional `releaseFollowupEnabled` hint. +The page shows the panel only when this hint is `true`; omitted or false means +OFF. This is a display hint, not authority for a follow-up route. Suspending the +panel retains any unknown command for recovery by its original account after a +current enabled ticket read. + +HTTP controls reuse Identity, Sessions, audited roles and the existing +engineering read/control quotas. They require the original current cookie +session and actor. Mutations require dynamic X-Pegma-CSRF, same-origin headers +and a total ten-second JSON-read deadline. SDK mutations receive the late +current-authority guard and synchronous closing fence; host mapping/receipt +writes close the same browser authority around their own conditional commits. A closing guard can +withhold an acknowledgement after a commit. + +## HTTP and exact retry + +Paths start at /api/support/admin/tickets/{ticketId}/follow-up/. +Each operation requires current queue authority and its named follow-up grant. +New posting additionally requires replyAny. + +| Method and suffix | Exact input | +| ----------------- | -------------------------------------------------------------------------------------------- | +| GET scan | Optional opaque cursor; one SDK page of 16 physical rows, with hints filtered to this ticket | +| GET work | Query workId | +| POST observe | commandId, repositoryId, issueId, inputReference | +| POST reassess | commandId, workId, expectedWorkGeneration, optional complete content | +| POST post | commandId, workId, expectedWorkGeneration, expectedTicketRevision, bundleHash, messageId | +| POST reject | commandId, workId, expectedWorkGeneration, bundleHash, reason | +| POST retry | commandId, workId, expectedWorkGeneration | +| POST abandon | commandId, workId, expectedWorkGeneration, reason | + +Client command IDs are stable UUIDs. The server derives correlation from actor, +operation, ticket and command. Work-command mutations (`observe`, `reassess`, +`post`, `reject`, `retry`, `abandon` and `retest`) return +`{ result, commandId, operation, csrfToken }`. Mapping mutations +(`verify-mapping`, `withdraw-mapping`) and `retest-receipt` instead return +`{ result, csrfToken }`; their command identity is inside `result`, with no +top-level `commandId` or `operation`. Retest preparation can return HTTP 202 +while the report phase is pending, then HTTP 200 when its receipt is ready. +The [HTTP adapter](../worker/src/support-release-followup-handlers.ts) owns these +envelopes; SDK result DTOs remain nested under `result`. +The SDK owns exact fingerprints, accepted receipts, generations, semantic +identities and conditional commits. Private +views expose selected metadata and candidate/checked content, while claim +identities, provider metadata and private check receipts stay server-side. + +The panel displays complete retained content before explicit posting. Its +buttons are independent of new-draft form validation. Sent commands remain in +memory with their original actor, operation and byte-identical body. Unknown +responses block other writes. Restore the original account and current ticket +view, then use **Retry the exact previous command**. Another actor cannot view +or replay the retained packet. Keep the original tab open until confirmation. + +## Current release and deployment evidence + +The normal signed GitHub release webhook and existing reconciliation feed +maintain a small release epoch journal even while the SD05 Source flag is OFF. +Projection writers read the epoch observation and conditionally transact it +with the projection. Unchanged refreshes keep their epoch; withdrawal, +replacement and republication advance it. Identical display facts after +republication cannot revive an old mapping. This journal I/O remains required +while OFF; disabling follow-up routes and processing does not remove its fence. + +The mapping picker reads at most 16 actual accepted SDK issue associations and +their genuine Source product. Staff explicitly verifies the issue state, +deployed version/build, deployment identity/epoch, scope and public facts under +the current cookie, Role and ticket/mapping generations. The server records the +mapping, exact command receipt and Audit atomically. The reference is meaningful +only with that durable record, current repository policy and the SDK's accepted +association/product checks. It is not a signed-marker claim. Withdrawal and +rollback retain historical receipts and hold new work. + +An explicit staff verification is valid for one hour. Mapping reads expose its +`verificationValidUntil` deadline and report `current: false` after expiry. +Operation attestations last at most five minutes and never extend beyond that +original deadline. Reading or replaying an accepted verification command does +not renew it; staff must submit a new verification command against the current +mapping generation. The default verifier does not poll GitHub or deployment +systems for reopen or rollback changes. Staff must record those changes or +withdraw the mapping within this bounded verification window. Current release +epoch, repository policy and Source withdrawal checks still apply immediately. + +New mapping routes share the existing namespace and quotas: + +| Method and suffix | Exact input | +| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| GET mapping | No query: bounded accepted choices. Or exactly repositoryId and issueId for one current mapping/release view | +| POST verify-mapping | commandId, expectedPrincipalId, expectedTicketRevision, expectedMappingGeneration, repositoryId, issueId, releaseRef, issueState, deploymentState, fixedProduct, deploymentId, deploymentEpoch, scopeRef, verificationReference, publicFacts | +| POST withdraw-mapping | commandId, expectedPrincipalId, expectedTicketRevision, expectedMappingGeneration, repositoryId, issueId, reason | + +`fixedProduct` is exactly productId/version/buildId. Public facts have 1-4 unique +references (200 characters each), with text bounded to 1,000 characters. +Mapping ACKs contain only actorId, ticketId, commandId, mappingGeneration and +inputReference, plus the normal CSRF envelope. Observing that reference remains +a separate SDK command. + +## Retest report association + +Default retest association requires `PEGMA_KNOWLEDGE_ENABLED=true` and a valid +`SUPPORT_LEARNING_SOURCE_CONFIGURATION_JSON` with its optional `testEvidence` +block configured. That block contains a positive safe integer +`retentionMilliseconds`; the report article's collection must also appear in +the configuration's `collectionIds`. The existing intrinsic governance reader +uses this scope to read the current validation policy. Follow-up Source and +Knowledge must remain enabled and the selected configuration must remain +current. This governance read does not require learning intake or paid/model +processing to be ON, and it grants no human review or publication permission. +Missing or unavailable scoped governance returns HTTP 503 +`followup_retest_unavailable`; HTTP 409 `followup_retest_changed` identifies an +actual report or Work conflict. + +A local agent submits the existing KB test report; an authorized staff member +must confirm it through the existing KB controls. Follow-up association neither +confirms a report nor accepts KB evidence. It reads and confirms the actual +current report, draft, requirements, evidence revocations and reviewer authority, +and binds its product/build and request to the exact Work/release/target bundle. +Passed and failed reports retain their actual result. + +`POST retest-receipt` accepts exactly commandId, expectedPrincipalId, workId, +expectedWorkGeneration, expectedTicketRevision, retestRequestId and report. The +report object is exactly articleId, ledgerEpoch, reportId, +expectedReportGeneration, reviewBindingHash and receipt, obtained from the +existing `reportRead` KB command. + +PG preparation first returns HTTP 202 with actorId, ticketId, commandId, workId, +retestRequestId and `pending: "report"`. This acknowledges a body-free durable +Work intent, not a test result or pass. Retry the same original packet in a +separate invocation. The HTTP 200 result adds the purpose-bound opaque receipt +and validUntil instead of pending. Unknown ACKs retain the same actor, command +and packet; they never cause another association under a new identity. + +A staged preparation intent expires after five minutes. An expired intent or +an exact command retained only as a tombstone returns HTTP 410 +`followup_retest_expired`. Receipt and intent payloads become eligible for +redaction after 24 hours; associated Audit rows become eligible for deletion at +that age. The existing bounded nonpaid maintenance sweep performs this work +when it reaches each row, rather than purging at an exact time. Redaction keeps +the ticket/key and command/input hashes as exact-command tombstones. Legacy +rows are also swept. + +Each ticket admits at most 64 new preparation commands over its lifetime. +Cleanup does not recycle admissions. This counter does not retroactively count +legacy history, so older records can exist in addition to those admissions. +A new command at the limit returns HTTP 429 `followup_retest_capacity`; an +already admitted command can still complete its requested second phase before +its intent expires. + +`POST retest` takes commandId, workId, retestRequestId and receiptReference. +The real SDK owns current Source/association/release/Work checks and the late +browser/session guard. The verifier reobserves the KB report under its original +staff authority. Its operation-local observation remains provisional until the +actual KB confirmation closes alongside the SDK's current Source versions. +The original browser guard then runs before the final synchronous assertion +and conditional commit. Handles are never serialized or reused across requests. +Exact accepted SDK receipts recover before mutable proof reads. +A delivered Work uses its handoff requests, original delivered bundle hash and +delivered ticket revision. A later failed retest records failure and holds +further work without retracting or sending another notice. + +## Background preparation and operator selection + +The optional `releaseFollowup` member of the existing closed paid profile holds +its separate generator route, explicit evaluation, tokenizer evidence, finite +usage policy and one explicit KB target (or none). Its independent route also +needs the SD05-specific qualification. Existing engineering approval is not +relabelled as follow-up approval. The dedicated versioned operator HMAC key +provider remains separate from the provider API key. The fixed Azure Sweden +endpoint allowlist accepts an explicitly approved `max_completion_tokens` route +and retains `max_tokens` for existing qualified profiles. The exact provided +parameter remains part of the approval hash; the host does not rewrite it or +retry a request with a different alias. + +The shared optional OpenRouter adapters bind the actual final Support App, +Knowledge App, Store and Clock. Purpose-specific checker handles use the same +global independent-check pool as learning and engineering. Staff reassessment +binds the original current staff resolver; it does not give Review to a service. +Missing model, funding, key, evaluation or route approval holds paid preparation +while ordinary Support and nonpaid Source actions remain available. + +Default background processing opts into the SDK's staged invocation mode. +Planning records an explicit durable `not_called` state. A later one-shot begin +marks a possible provider attempt before transport, records the bounded result +and accounting, and releases it for a later completion stage. Unknown attempts +remain held and cannot authorize another call. Independent checks likewise +separate preparation, one provider attempt and a later fresh receipt phase; +a recorded verdict is not an approval receipt. Staff reassessment remains the +existing inline, original-staff-authorized flow. An injected legacy composition +without staged mode retains its prior behavior. + +The host prewrites a bounded body-free Work or check-operation continuation +before every possible paid phase, including a lost planning ACK. It does not +infer a new paid chance from `model_prepared` or an unmarked pending result. +Exhausted advisory hints settle in a separate no-SDK tick; a confirmed +`not_claimed` result can drain its hint in that nonprovider invocation. Current +SDK claims, receipts and live authority remain the sole work authority. + +Deferred request cleanup uses the existing inactive-sweep lane and accepted +Source-withdraw hook. Its Store/Clock-only SDK helper requires no paid profile, +provider key, receipt key or model funding. It erases private request payloads +while retaining body-free one-shot intent tombstones. + +The existing cleanup cron seeds SD05 on UTC minutes 0, 15, 30 and 45. Existing +engineering/learning cadence is unchanged. One queue invocation performs one +body-free scan or one SDK stage, using a separate durable SD05 cursor. Finite +continuations reuse the original bounded queue delivery; no producer send or +cursor write follows a paid/unknown model outcome. Retained SDK state is +rediscovered after a crash or unknown ACK. Background work prepares drafts, +private KB proposals and retest requests; current staff approval still sends a +web notice, and KB review/publication remains separate. + +With the current `0-58 * * * *` cleanup schedule, two idle minute domains cost +8,496 queue operations/day and SD05 adds 288, totaling 8,784 before retries or +other queue traffic. Treating the first two as full minute domains gives a +conservative 8,928. A disabled SD05 worker adds zero queue operations; retention +cleanup uses the existing maintenance invocation. These are scheduling +arithmetic, not a universal Free-tier traffic guarantee. + +## Evidence and validation + +A real ordinary accepted engineering association must already exist through +approved SDK export/reconciliation. Entering an issue ID cannot create that +authority. The verifier must confirm the issue head, affected product/build/ +scope and deployed fix mapping. A release tag, closed issue or green CI job alone +is insufficient. The existing signed [release feed](GITHUB_RELEASE_WEBHOOK_PLAN.md) +supplies hints and public facts, not deployment applicability. + +Recorded reopened issues and rollback heads, withdrawn sources and expired +verification hold new updates. External issue or deployment changes require the +explicit mapping update described above. Accepted receipts recover before +mutable proof reads. Reassessment can +edit a retained candidate or bundle; it cannot create a first draft for +draftless work. Unknown paid outcomes stay reserved by the purpose-isolated +[durable usage adapter](../worker/src/support-release-followup-usage.ts). +Posting adds one existing web reply. KB proposals and retests remain private +handoffs for separately authorized workflows. + +Real-SDK fixtures cover accepted association, complete bundle approval, +role/session loss during proof, rollback/reopen and lost-ACK recovery. Run the +normal check, test:node and build scripts. The focused physical tests are worker/src/support-release-followup.d1.test.ts +and worker/src/support-release-followup-host.d1.test.ts under vitest.d1.config.ts. +They meter cold Worker.fetch and registered queue invocations, including +authentication, quotas, SDK work and closing checks, with unchanged +50-query/100-parameter guards. The host suite also measures the default shared +generator/checker composition and the real paired report preparation and +consumption separately. diff --git a/evals/assembly-eval.test.ts b/evals/assembly-eval.test.ts index 7987b80..80640eb 100644 --- a/evals/assembly-eval.test.ts +++ b/evals/assembly-eval.test.ts @@ -39,12 +39,12 @@ const EVAL_NPM: Record = { '@pegma/authorization-tokens': '0.4.0', '@pegma/authorization-identity': '0.4.0', '@pegma/audit': '0.2.0', - '@pegma/support-desk-contracts': '0.2.7', - '@pegma/support-desk-core': '0.2.7', - '@pegma/support-desk-application': '0.2.7', + '@pegma/support-desk-contracts': '0.2.10', + '@pegma/support-desk-core': '0.2.10', + '@pegma/support-desk-application': '0.2.10', '@pegma/support-desk-templates': '0.1.1', '@pegma/webhooks': '0.1.1', - '@pegma/sessions': '0.2.1', + '@pegma/sessions': '0.3.0', '@pegma/mail': '0.1.1', '@pegma/billing-core': '0.1.1', '@pegma/billing-stripe': '0.1.1', diff --git a/package.json b/package.json index d7c367e..d6c6697 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "worker:types": "wrangler types worker/worker-configuration.d.ts -c worker/wrangler.jsonc && node scripts/normalize-worker-types.mjs" }, "dependencies": { - "@modelcontextprotocol/server": "^2.0.0", + "@modelcontextprotocol/server": "2.3.0", "@pegma/agent-access": "0.1.1", "@pegma/audit": "0.2.0", "@pegma/authorization-admin": "0.4.0", @@ -32,29 +32,29 @@ "@pegma/authorization-storage": "0.4.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", - "@pegma/knowledge-base-application": "0.1.6", - "@pegma/knowledge-base-contracts": "0.1.6", - "@pegma/knowledge-base-core": "0.1.6", - "@pegma/knowledge-base-mcp": "0.1.6", + "@pegma/knowledge-base-application": "0.1.8", + "@pegma/knowledge-base-contracts": "0.1.8", + "@pegma/knowledge-base-core": "0.1.8", + "@pegma/knowledge-base-mcp": "0.1.8", "@pegma/logger-cloudflare": "^0.1.1", "@pegma/logger-datadog": "^0.1.1", "@pegma/logger-tee": "^0.1.1", "@pegma/mail": "0.1.1", "@pegma/rate-limit": "0.2.0", "@pegma/rate-limit-paged": "npm:@pegma/rate-limit@0.3.3", - "@pegma/sessions": "0.2.1", + "@pegma/sessions": "0.3.0", "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.7", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-ai": "0.2.7", - "@pegma/support-desk-application": "0.2.7", - "@pegma/support-desk-contracts": "0.2.7", - "@pegma/support-desk-core": "0.2.7", - "@pegma/support-desk-templates": "0.2.7", + "@pegma/support-desk-ai": "0.2.10", + "@pegma/support-desk-application": "0.2.10", + "@pegma/support-desk-contracts": "0.2.10", + "@pegma/support-desk-core": "0.2.10", + "@pegma/support-desk-templates": "0.2.10", "@pegma/webhooks": "0.1.1", "agents": "^0.20.1", "gpt-tokenizer": "4.1.2", - "zod": "^4.4.3" + "zod": "4.6.7" }, "devDependencies": { "@astrojs/check": "0.9.10", @@ -70,6 +70,14 @@ "onlyBuiltDependencies": [ "esbuild", "workerd" - ] + ], + "overrides": { + "agents>@modelcontextprotocol/sdk": "1.32.2", + "agents>@modelcontextprotocol/client": "2.3.0", + "agents>@modelcontextprotocol/server": "2.3.0", + "express@5.2.1>body-parser": "2.4.0", + "express@5.2.1>proxy-addr": "2.0.8", + "ajv@8.20.0>fast-uri": "3.1.9" + } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 43040aa..b854574 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,13 +4,21 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + agents>@modelcontextprotocol/sdk: 1.32.2 + agents>@modelcontextprotocol/client: 2.3.0 + agents>@modelcontextprotocol/server: 2.3.0 + express@5.2.1>body-parser: 2.4.0 + express@5.2.1>proxy-addr: 2.0.8 + ajv@8.20.0>fast-uri: 3.1.9 + importers: .: dependencies: '@modelcontextprotocol/server': - specifier: ^2.0.0 - version: 2.0.0 + specifier: 2.3.0 + version: 2.3.0 '@pegma/agent-access': specifier: 0.1.1 version: 0.1.1 @@ -39,17 +47,17 @@ importers: specifier: 0.1.2 version: 0.1.2 '@pegma/knowledge-base-application': - specifier: 0.1.6 - version: 0.1.6 + specifier: 0.1.8 + version: 0.1.8 '@pegma/knowledge-base-contracts': - specifier: 0.1.6 - version: 0.1.6 + specifier: 0.1.8 + version: 0.1.8 '@pegma/knowledge-base-core': - specifier: 0.1.6 - version: 0.1.6 + specifier: 0.1.8 + version: 0.1.8 '@pegma/knowledge-base-mcp': - specifier: 0.1.6 - version: 0.1.6 + specifier: 0.1.8 + version: 0.1.8 '@pegma/logger-cloudflare': specifier: ^0.1.1 version: 0.1.1 @@ -69,8 +77,8 @@ importers: specifier: npm:@pegma/rate-limit@0.3.3 version: '@pegma/rate-limit@0.3.3' '@pegma/sessions': - specifier: 0.2.1 - version: 0.2.1 + specifier: 0.3.0 + version: 0.3.0 '@pegma/spine': specifier: ^0.1.1 version: 0.1.1 @@ -81,32 +89,32 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.10 + version: 0.2.10 '@pegma/support-desk-application': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.10 + version: 0.2.10 '@pegma/support-desk-contracts': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.10 + version: 0.2.10 '@pegma/support-desk-core': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.10 + version: 0.2.10 '@pegma/support-desk-templates': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.10 + version: 0.2.10 '@pegma/webhooks': specifier: 0.1.1 version: 0.1.1 agents: specifier: ^0.20.1 - version: 0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3) + version: 0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.3.0)(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7))(@modelcontextprotocol/server@2.3.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.6.7) gpt-tokenizer: specifier: 4.1.2 version: 4.1.2 zod: - specifier: ^4.4.3 - version: 4.4.3 + specifier: 4.6.7 + version: 4.6.7 devDependencies: '@astrojs/check': specifier: 0.9.10 @@ -1057,24 +1065,14 @@ packages: '@levischuck/tiny-cbor@0.2.11': resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==} - '@modelcontextprotocol/client@2.0.0': - resolution: {integrity: sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==} + '@modelcontextprotocol/client@2.3.0': + resolution: {integrity: sha512-pbHtGj6EeFCHngFE8gtNPaKrsj8Mb1IMw45BLcaPML/m2WTxI7pyYmeNQvaux88Lw8BSO5r7nyRbUyIkICmGrg==} engines: {node: '>=20'} - '@modelcontextprotocol/core@2.0.0': - resolution: {integrity: sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==} + '@modelcontextprotocol/core@2.3.0': + resolution: {integrity: sha512-09BHFaNVBe5pB2AhzCfLj0cqmsKLERvZQ4FblzP90UMGLaXVqdZPByFjURwsUYCmxonUW2yAwgTTvle+8O2/8w==} engines: {node: '>=20'} - '@modelcontextprotocol/sdk@1.30.0': - resolution: {integrity: sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==} - engines: {node: '>=18'} - peerDependencies: - '@cfworker/json-schema': ^4.1.1 - zod: ^3.25 || ^4.0 - peerDependenciesMeta: - '@cfworker/json-schema': - optional: true - '@modelcontextprotocol/sdk@1.32.2': resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} engines: {node: '>=18'} @@ -1085,8 +1083,8 @@ packages: '@cfworker/json-schema': optional: true - '@modelcontextprotocol/server@2.0.0': - resolution: {integrity: sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==} + '@modelcontextprotocol/server@2.3.0': + resolution: {integrity: sha512-+6b0LdsQLmHsvS7J6sQJ4weTpzUn61fU1JKS+321/+IyDYoHW5CR2Tgqcs6GgAAQvlesCo6yX3xttgmx+XGtJw==} engines: {node: '>=20'} '@napi-rs/wasm-runtime@1.2.0': @@ -1182,20 +1180,20 @@ packages: resolution: {integrity: sha512-r8AsVTnwCSBU2LZZjieW5FgIJ2TUWi5DlU9kp+4tuaWDFfl85EezkD6F5omAFjTnaFqCRN1T2d/KsHoESarB2A==} engines: {node: '>=22'} - '@pegma/knowledge-base-application@0.1.6': - resolution: {integrity: sha512-i7rD3uWz4XSuii7Kx3Y2l1tn3TK6WHfjBpJxkmdxYLVes2cBYaaQ3KgCjSbU5m0W01w0SmDPDOLsvFWdHGFDow==} + '@pegma/knowledge-base-application@0.1.8': + resolution: {integrity: sha512-G9TF3mBKhlAaI+QcZb56prTvXYi0eHzw9djGAqrFoRfyq+u5FUDwME+pdKvk1rUN19etMafqB6EQsMIUipCC8Q==} engines: {node: '>=22'} - '@pegma/knowledge-base-contracts@0.1.6': - resolution: {integrity: sha512-/jntfNSu0OGrDpaEg+Mhi1kv9ek8thbEBObT9WYmeo6laPr4jEmYqiLi+zBT52SinMmnGEUGU3f0dzeM9i2CQQ==} + '@pegma/knowledge-base-contracts@0.1.8': + resolution: {integrity: sha512-6Q6kPEjrDzYuPiwtTMhbOg7m6Qo6XvM34E+psvzRHO1eN8tE+u4iMAok7uff3Zcsi1O2smqmjcE6IukscPbVrQ==} engines: {node: '>=22'} - '@pegma/knowledge-base-core@0.1.6': - resolution: {integrity: sha512-VKK5r8vNed9b2BZJQTAf68faW6mjjR/SLCooOtLvQsw5xhYjvNwfkri2cqPLVSZ44xMQXNRlx1nD1DfddNkoKw==} + '@pegma/knowledge-base-core@0.1.8': + resolution: {integrity: sha512-pqHYS1fasulNScra2wcGO3Aayt5egvImXJuxWejTKShYR8KRqxscvGQXcr51PONoSfxs+zer8YqoTixc6gQfYA==} engines: {node: '>=22'} - '@pegma/knowledge-base-mcp@0.1.6': - resolution: {integrity: sha512-e1LIDIElZPa+JyyuYrw0VmqTzK4OULmxQBI1eZWIupu6PonDvIRQLbMSlI8KPFEGRuoMnEP3IbXoQCzmtf//aA==} + '@pegma/knowledge-base-mcp@0.1.8': + resolution: {integrity: sha512-f1r/6xTmC705QMwkgTirAJGuQNWhCxBObr7E3AAhA9RKONhwbewDJTG1kSaLYhn6jXT+dQszeJyuTskaWQPB3A==} engines: {node: '>=22'} '@pegma/logger-cloudflare@0.1.1': @@ -1222,8 +1220,8 @@ packages: resolution: {integrity: sha512-Bu2t3WjD4VsQj5lWnz+XZ0KQ/F2rbs1CkDmH6aSl9kCg1cYNZHviL9o5XJhbsA7siFo9G+FOJXK2REnnzWtk9Q==} engines: {node: '>=22'} - '@pegma/sessions@0.2.1': - resolution: {integrity: sha512-GOpwpL0S7/wXpUFuuR0aza+2enGDuUdFrgvOKAbUljDABSj1g/+QOzwQPbe9QYsGI7AImlk4El8cc5qzguNP9Q==} + '@pegma/sessions@0.3.0': + resolution: {integrity: sha512-Lk/dWfdY5pNTp7xGmU2vySpfoNdYQ/RFar4KnxlKYL9Xvn1/vEvgGrkJ6J6g22CnSrrii3DawwKV+JEDrDbUFg==} engines: {node: '>=22'} '@pegma/spine@0.1.1': @@ -1242,24 +1240,24 @@ packages: resolution: {integrity: sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==} engines: {node: '>=22'} - '@pegma/support-desk-ai@0.2.7': - resolution: {integrity: sha512-Ra6k3a0JEERXeIfDbRlUMOa9F4/o4W0l54yjMDBcoM16tjUUmGrifc8oxWrSNir0p7a8TLyevVkfNxs+T6szUA==} + '@pegma/support-desk-ai@0.2.10': + resolution: {integrity: sha512-PvQ/1DB54ev1sNV/jIuwRltdGCTKQ0GYNMSAtTzaWa1ErkZyLijgG3t8DPO+Z+O7aH5T5JL/3ECSHP38RMfshw==} engines: {node: '>=22'} - '@pegma/support-desk-application@0.2.7': - resolution: {integrity: sha512-t0asEJYY7Xmndz1GTp/7j5RUVzXYIs0a8uZ+hRUq5fwgPmqfMoPVJ9xSA7xPhbhDtZUq3B2tRD4tG91Fn6XA0g==} + '@pegma/support-desk-application@0.2.10': + resolution: {integrity: sha512-LVeGvoW0kHmkSYuxpVkbrgAsowNRaVAXlQ31SjcqCgD3iVgcICajXMv2kbqx1BRwODdFEZgJByFUBXcipXZ5Ig==} engines: {node: '>=22'} - '@pegma/support-desk-contracts@0.2.7': - resolution: {integrity: sha512-/9Zz473fyItEjJWLEzyXBzIR2poCqhvsqwdxU1yQOchy2++E9fdj/ErklGmea4VouUdnouhx2mRpIJJ0+gn+0A==} + '@pegma/support-desk-contracts@0.2.10': + resolution: {integrity: sha512-ZjpoS8Xqs1BtY/cH/hhvtE2JecKZ9AGEPWKeX0HG/tqvjjQ3h6ZiWxQQqvBizxyRxdZ+17U3XEs3Yg+EvGB5bA==} engines: {node: '>=22'} - '@pegma/support-desk-core@0.2.7': - resolution: {integrity: sha512-3+8e2ZS1J2om0ePn2ioQ1wpqdY5f9NA6svEPl4RPVpmCdXwwiJxLbocLHtjcGJNbW37MnyOZKY97X5jdrMXSAw==} + '@pegma/support-desk-core@0.2.10': + resolution: {integrity: sha512-/YuOj/QEOtSzDbCO1nQhjyJv1g97z4s39BsznR9cFgeIyCAoF9ReXTPzZDCNLm/XApTrlNL47X1H93XoTJgb9w==} engines: {node: '>=22'} - '@pegma/support-desk-templates@0.2.7': - resolution: {integrity: sha512-4mDF2e4ZzYjSlIQYu4FWpjr1cUUU2N7jJUfGTTMnYG6Gf5UN45j7q7ueOFJjlcgC7D0+TqKludaKDYZf0nqTjg==} + '@pegma/support-desk-templates@0.2.10': + resolution: {integrity: sha512-Dtp7ilfsYuklSOIHRauBEtowUfbcwekoYzj3MoldBLzyQT20oTvyI8lekaY3S36k1sfBmyj+gAKrFN/Ed95Olg==} engines: {node: '>=22'} '@pegma/webhooks@0.1.1': @@ -1548,9 +1546,9 @@ packages: peerDependencies: '@ai-sdk/react': ^3.0.0 || ^4.0.0 '@cloudflare/codemode': '>=0.5.0' - '@modelcontextprotocol/client': 2.0.0 - '@modelcontextprotocol/sdk': 1.30.0 - '@modelcontextprotocol/server': 2.0.0 + '@modelcontextprotocol/client': 2.3.0 + '@modelcontextprotocol/sdk': 1.32.2 + '@modelcontextprotocol/server': 2.3.0 '@tanstack/ai': '>=0.10.2 <1.0.0' '@x402/core': ^2.0.0 '@x402/evm': ^2.0.0 @@ -1660,8 +1658,8 @@ packages: blake3-wasm@2.1.5: resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} - body-parser@2.3.0: - resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} + body-parser@2.4.0: + resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} engines: {node: '>=18'} boolbase@1.0.0: @@ -1746,6 +1744,10 @@ packages: resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==} engines: {node: '>=18'} + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} @@ -1971,8 +1973,8 @@ packages: fast-string-width@3.0.2: resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} - fast-uri@3.1.4: - resolution: {integrity: sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==} + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} fast-wrap-ansi@0.2.2: resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} @@ -2491,8 +2493,8 @@ packages: property-information@7.2.0: resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==} - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} punycode@2.3.1: @@ -2510,6 +2512,10 @@ packages: resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==} engines: {node: '>=0.6'} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} + engines: {node: '>=0.6'} + radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} @@ -3193,9 +3199,6 @@ packages: zod@3.25.76: resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - zod@4.4.3: - resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} - zod@4.6.7: resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} @@ -3957,9 +3960,9 @@ snapshots: '@levischuck/tiny-cbor@0.2.11': {} - '@modelcontextprotocol/client@2.0.0': + '@modelcontextprotocol/client@2.3.0': dependencies: - '@modelcontextprotocol/core': 2.0.0 + '@modelcontextprotocol/core': 2.3.0 cross-spawn: 7.0.6 eventsource: 3.0.7 eventsource-parser: 3.1.0 @@ -3967,34 +3970,10 @@ snapshots: pkce-challenge: 5.0.1 zod: 4.6.7 - '@modelcontextprotocol/core@2.0.0': + '@modelcontextprotocol/core@2.3.0': dependencies: zod: 4.6.7 - '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3)': - dependencies: - '@hono/node-server': 2.0.12(hono@4.12.32) - ajv: 8.20.0 - ajv-formats: 3.0.1(ajv@8.20.0) - content-type: 1.0.5 - cors: 2.8.6 - cross-spawn: 7.0.6 - eventsource: 3.0.7 - eventsource-parser: 3.1.0 - express: 5.2.1 - express-rate-limit: 8.6.1(express@5.2.1) - hono: 4.12.32 - jose: 6.2.4 - json-schema-typed: 8.0.2 - pkce-challenge: 5.0.1 - raw-body: 3.0.2 - zod: 4.4.3 - zod-to-json-schema: 3.25.2(zod@4.4.3) - optionalDependencies: - '@cfworker/json-schema': 4.1.6 - transitivePeerDependencies: - - supports-color - '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)': dependencies: '@hono/node-server': 2.0.12(hono@4.12.32) @@ -4019,10 +3998,10 @@ snapshots: transitivePeerDependencies: - supports-color - '@modelcontextprotocol/server@2.0.0': + '@modelcontextprotocol/server@2.3.0': dependencies: - '@modelcontextprotocol/core': 2.0.0 - zod: 4.4.3 + '@modelcontextprotocol/core': 2.3.0 + zod: 4.6.7 '@napi-rs/wasm-runtime@1.2.0(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: @@ -4195,31 +4174,31 @@ snapshots: unicode-case-folding: 1.1.1 unorm: 1.6.0 - '@pegma/knowledge-base-application@0.1.6': + '@pegma/knowledge-base-application@0.1.8': dependencies: '@pegma/audit': 0.2.0 '@pegma/authorization-core': 0.4.0 - '@pegma/knowledge-base-contracts': 0.1.6 - '@pegma/knowledge-base-core': 0.1.6 + '@pegma/knowledge-base-contracts': 0.1.8 + '@pegma/knowledge-base-core': 0.1.8 '@pegma/spine': 0.1.2 '@pegma/storage-core': 0.4.0 - '@pegma/knowledge-base-contracts@0.1.6': + '@pegma/knowledge-base-contracts@0.1.8': dependencies: '@pegma/spine': 0.1.2 - '@pegma/knowledge-base-core@0.1.6': + '@pegma/knowledge-base-core@0.1.8': dependencies: - '@pegma/knowledge-base-contracts': 0.1.6 + '@pegma/knowledge-base-contracts': 0.1.8 - '@pegma/knowledge-base-mcp@0.1.6': + '@pegma/knowledge-base-mcp@0.1.8': dependencies: '@cfworker/json-schema': 4.1.6 '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7) '@pegma/authorization-core': 0.4.0 - '@pegma/knowledge-base-application': 0.1.6 - '@pegma/knowledge-base-contracts': 0.1.6 - '@pegma/knowledge-base-core': 0.1.6 + '@pegma/knowledge-base-application': 0.1.8 + '@pegma/knowledge-base-contracts': 0.1.8 + '@pegma/knowledge-base-core': 0.1.8 zod: 4.6.7 transitivePeerDependencies: - supports-color @@ -4251,7 +4230,7 @@ snapshots: '@pegma/spine': 0.1.1 '@pegma/storage-core': 0.4.0 - '@pegma/sessions@0.2.1': + '@pegma/sessions@0.3.0': dependencies: '@pegma/spine': 0.1.1 '@pegma/storage-core': 0.4.0 @@ -4266,33 +4245,35 @@ snapshots: '@pegma/storage-core@0.4.0': {} - '@pegma/support-desk-ai@0.2.7': + '@pegma/support-desk-ai@0.2.10': dependencies: '@pegma/authorization-core': 0.4.0 - '@pegma/knowledge-base-application': 0.1.6 - '@pegma/knowledge-base-contracts': 0.1.6 + '@pegma/knowledge-base-application': 0.1.8 + '@pegma/knowledge-base-contracts': 0.1.8 '@pegma/spine': 0.1.2 - '@pegma/support-desk-application': 0.2.7 + '@pegma/storage-core': 0.4.0 + '@pegma/support-desk-application': 0.2.10 + zod: 4.6.7 - '@pegma/support-desk-application@0.2.7': + '@pegma/support-desk-application@0.2.10': 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.7 - '@pegma/support-desk-core': 0.2.7 + '@pegma/support-desk-contracts': 0.2.10 + '@pegma/support-desk-core': 0.2.10 - '@pegma/support-desk-contracts@0.2.7': + '@pegma/support-desk-contracts@0.2.10': dependencies: '@pegma/spine': 0.1.2 - '@pegma/support-desk-core@0.2.7': + '@pegma/support-desk-core@0.2.10': dependencies: - '@pegma/support-desk-contracts': 0.2.7 + '@pegma/support-desk-contracts': 0.2.10 - '@pegma/support-desk-templates@0.2.7': {} + '@pegma/support-desk-templates@0.2.10': {} '@pegma/webhooks@0.1.1': dependencies: @@ -4572,13 +4553,13 @@ snapshots: mime-types: 3.0.2 negotiator: 1.0.0 - agents@0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3): + agents@0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.3.0)(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7))(@modelcontextprotocol/server@2.3.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.6.7): dependencies: '@babel/plugin-proposal-decorators': 8.0.2(@babel/core@8.0.1) '@cfworker/json-schema': 4.1.1 - '@modelcontextprotocol/client': 2.0.0 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3) - '@modelcontextprotocol/server': 2.0.0 + '@modelcontextprotocol/client': 2.3.0 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7) + '@modelcontextprotocol/server': 2.3.0 '@rolldown/plugin-babel': 0.2.3(@babel/core@8.0.1)(@babel/runtime@7.29.7)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) cron-schedule: 6.0.0 esbuild: 0.28.1 @@ -4589,7 +4570,7 @@ snapshots: react: 19.2.8 yaml: 2.9.0 yargs: 18.1.0 - zod: 4.4.3 + zod: 4.6.7 optionalDependencies: vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) transitivePeerDependencies: @@ -4614,7 +4595,7 @@ snapshots: ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.4 + fast-uri: 3.1.9 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -4697,7 +4678,7 @@ snapshots: vitefu: 1.1.3(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) xxhash-wasm: 1.1.0 yargs-parser: 22.0.0 - zod: 4.4.3 + zod: 4.6.7 optionalDependencies: sharp: 0.35.3(@types/node@26.1.1) transitivePeerDependencies: @@ -4743,15 +4724,15 @@ snapshots: blake3-wasm@2.1.5: {} - body-parser@2.3.0: + body-parser@2.4.0: dependencies: bytes: 3.1.2 - content-type: 2.0.0 + content-type: 2.1.0 debug: 4.4.3 http-errors: 2.0.1 iconv-lite: 0.7.3 on-finished: 2.4.1 - qs: 6.15.3 + qs: 6.17.1 raw-body: 3.0.2 type-is: 2.1.0 transitivePeerDependencies: @@ -4821,6 +4802,8 @@ snapshots: content-type@2.0.0: {} + content-type@2.1.0: {} + convert-source-map@2.0.0: {} cookie-es@1.2.3: {} @@ -5019,7 +5002,7 @@ snapshots: express@5.2.1: dependencies: accepts: 2.0.0 - body-parser: 2.3.0 + body-parser: 2.4.0 content-disposition: 1.1.0 content-type: 1.0.5 cookie: 0.7.2 @@ -5037,7 +5020,7 @@ snapshots: on-finished: 2.4.1 once: 1.4.0 parseurl: 1.3.3 - proxy-addr: 2.0.7 + proxy-addr: 2.0.8 qs: 6.15.3 range-parser: 1.3.0 router: 2.2.0 @@ -5059,7 +5042,7 @@ snapshots: dependencies: fast-string-truncated-width: 3.0.3 - fast-uri@3.1.4: {} + fast-uri@3.1.9: {} fast-wrap-ansi@0.2.2: dependencies: @@ -5534,7 +5517,7 @@ snapshots: property-information@7.2.0: {} - proxy-addr@2.0.7: + proxy-addr@2.0.8: dependencies: forwarded: 0.2.0 ipaddr.js: 1.9.1 @@ -5552,6 +5535,11 @@ snapshots: es-define-property: 1.0.1 side-channel: 1.1.1 + qs@6.17.1: + dependencies: + es-define-property: 1.0.1 + side-channel: 1.1.1 + radix3@1.1.2: {} range-parser@1.3.0: {} @@ -6254,18 +6242,12 @@ snapshots: cookie: 1.1.1 youch-core: 0.3.3 - zod-to-json-schema@3.25.2(zod@4.4.3): - dependencies: - zod: 4.4.3 - zod-to-json-schema@3.25.2(zod@4.6.7): dependencies: zod: 4.6.7 zod@3.25.76: {} - zod@4.4.3: {} - zod@4.6.7: {} zwitch@2.0.4: {} diff --git a/public/feedback-ticket.js b/public/feedback-ticket.js index 7dc99e4..522c773 100644 --- a/public/feedback-ticket.js +++ b/public/feedback-ticket.js @@ -2,7 +2,9 @@ const select = (selector) => document.querySelector(selector); const statusNode = select('#ticket-status'); const signedOut = select('#ticket-signed-out'); const signInLinks = [...signedOut.querySelectorAll('a')].map((node) => ({ - node, target: node.target ?? '', rel: node.rel ?? '', + node, + target: node.target ?? '', + rel: node.rel ?? '', })); const detail = select('#ticket-detail'); const heading = select('#ticket-heading'); @@ -12,6 +14,7 @@ const replyForm = select('#reply-form'); const humanControls = select('#ticket-human-controls'); const humanStatus = select('#ticket-human-status'); const personButton = select('#request-person'); +const successButton = select('#confirm-success'); const ticketId = new URL(window.location.href).searchParams.get('id') ?? ''; let csrfToken = ''; let viewer = null; @@ -20,6 +23,9 @@ let currentView = null; let readGeneration = 0; let busy = null; let personPacket = null; +let successPacket = null; +let successAcknowledged = false; +const successOwners = new Map(); let replyPacket = null; let replyAcknowledged = false; let packetOutcome = 'unconfirmed'; @@ -74,6 +80,7 @@ function clearTicket() { humanControls.hidden = true; humanStatus.textContent = ''; personButton.disabled = true; + successButton.disabled = true; for (const button of replyForm.querySelectorAll('button')) button.disabled = true; // Unsent reply text stays in the form when the private view is cleared. @@ -86,6 +93,7 @@ function invalidate() { viewer = null; csrfToken = ''; if (!onThisTicket()) personPacket = null; + if (!onThisTicket()) successPacket = null; if (retryTimer !== null) clearTimeout(retryTimer); retryTimer = null; clearTicket(); @@ -123,8 +131,12 @@ function armRetryTimer() { function updateHumanControl() { replyForm.noValidate = replyPacket !== null; for (const link of signInLinks) { - link.node.target = replyPacket === null ? link.target : '_blank'; - link.node.rel = replyPacket === null ? link.rel : 'noopener noreferrer'; + link.node.target = + replyPacket === null && successPacket === null ? link.target : '_blank'; + link.node.rel = + replyPacket === null && successPacket === null + ? link.rel + : 'noopener noreferrer'; } const ticket = currentView?.ticket; const terminal = ticket?.status === 'resolved' || ticket?.status === 'closed'; @@ -133,29 +145,32 @@ function updateHumanControl() { humanControls.hidden = viewer === null || authorityReloadRequired || - (ticket === undefined && personPacket === null); + (ticket === undefined && personPacket === null && successPacket === null); humanStatus.textContent = humanControls.hidden ? '' - : personPacket !== null - ? packetOutcome === 'rate_limited' - ? seconds > 0 - ? `The server rate limited this request. Wait at least ${seconds} seconds before retrying the same request.` - : 'Retry the same human-support request when ready.' - : 'The previous human-support request has no confirmed acknowledgement. Retry that same request.' - : terminal - ? `This ticket is ${ticket.status}. Request human support to reopen it.` - : state === 'assistant' - ? 'You can ask for human support at any time.' - : state === 'human-active' - ? 'Human support is active on this ticket.' - : state === 'human-pending' - ? 'This ticket is waiting for human support.' - : 'Human support handles this ticket.'; + : successPacket !== null + ? 'The confirmation has no settled acknowledgement. Retry the same confirmation.' + : personPacket !== null + ? packetOutcome === 'rate_limited' + ? seconds > 0 + ? `The server rate limited this request. Wait at least ${seconds} seconds before retrying the same request.` + : 'Retry the same human-support request when ready.' + : 'The previous human-support request has no confirmed acknowledgement. Retry that same request.' + : terminal + ? `This ticket is ${ticket.status}. Request human support to reopen it.` + : state === 'assistant' + ? 'You can ask for human support at any time.' + : state === 'human-active' + ? 'Human support is active on this ticket.' + : state === 'human-pending' + ? 'This ticket is waiting for human support.' + : 'Human support handles this ticket.'; personButton.hidden = personPacket === null && !terminal && state !== 'assistant'; personButton.disabled = busy !== null || replyPacket !== null || + successPacket !== null || viewer === null || authorityReloadRequired || suspended || @@ -167,6 +182,23 @@ function updateHumanControl() { : personPacket === null ? 'Request human support' : 'Retry human-support request'; + const confirmable = ticket?.status === 'resolved'; + successButton.hidden = successPacket === null && !confirmable; + successButton.disabled = + busy !== null || + viewer === null || + authorityReloadRequired || + suspended || + seconds > 0 || + personPacket !== null || + replyPacket !== null || + successAcknowledged || + (successPacket === null && + (!confirmable || !currentView?.messages.at(-1)?.id)); + successButton.textContent = + successPacket === null + ? 'Confirm this solved my issue' + : 'Retry the same confirmation'; for (const button of replyForm.querySelectorAll('button')) { button.textContent = replyPacket === null ? 'Send reply' : 'Retry previous reply'; @@ -174,6 +206,7 @@ function updateHumanControl() { busy !== null || currentView === null || personPacket !== null || + successPacket !== null || authorityReloadRequired || replyAcknowledged || suspended || @@ -257,6 +290,9 @@ async function readViewer(generation, expected = viewer) { subject: result.account.subject, csrfToken: result.csrfToken, }); + restoreSuccess(next); + if (successPacket !== null && next.subject !== successPacket.subject) + throw Object.assign(new Error('session_changed'), { status: 401 }); // An unresolved command belongs to its original principal, not old credentials. if (personPacket !== null && next.subject !== personPacket.subject) { personPacket = null; @@ -275,6 +311,99 @@ async function readViewer(generation, expected = viewer) { csrfToken = next.csrfToken; return next; } +function successKey(subject) { + return ( + 'pegma.support.success.v1:' + + encodeURIComponent(subject) + + ':' + + encodeURIComponent(ticketId) + ); +} +function restoreSuccess(next) { + if (successPacket !== null && successPacket.subject !== next.subject) { + successOwners.set(successPacket.subject, { + packet: successPacket, + acknowledged: successAcknowledged, + }); + successPacket = null; + successAcknowledged = false; + } + if (successPacket !== null) return; + const retained = successOwners.get(next.subject); + if (retained) { + successPacket = retained.packet; + successAcknowledged = retained.acknowledged; + return; + } + let saved; + try { + saved = window.sessionStorage?.getItem(successKey(next.subject)); + } catch { + return; + } + if (!saved) return; + try { + const packet = JSON.parse(saved); + if ( + !packet || + typeof packet !== 'object' || + Array.isArray(packet) || + typeof packet.body !== 'string' + ) + return; + const body = JSON.parse(packet.body); + if ( + !body || + typeof body !== 'object' || + Array.isArray(body) || + typeof body.commandId !== 'string' || + packet.subject !== next.subject || + packet.ticketId !== ticketId || + Object.keys(packet).sort().join(',') !== 'body,subject,ticketId' || + Object.keys(body).sort().join(',') !== + 'commandId,lastSeenVisibleMessageId' || + !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(body.commandId) || + typeof body.lastSeenVisibleMessageId !== 'string' || + body.lastSeenVisibleMessageId.length < 1 || + body.lastSeenVisibleMessageId.length > 200 || + /[\u0000-\u001F\u007F-\u009F]/u.test(body.lastSeenVisibleMessageId) + ) + return; + successPacket = Object.freeze(packet); + successOwners.set(next.subject, { + packet: successPacket, + acknowledged: false, + }); + } catch { + // Invalid saved data is not a replayable command or authority for this viewer. + } +} +function retainSuccess(packet) { + successOwners.set(packet.subject, { + packet, + acknowledged: successAcknowledged, + }); + try { + window.sessionStorage?.setItem( + successKey(packet.subject), + JSON.stringify(packet), + ); + } catch { + /* The same immutable packet remains in this tab if storage is unavailable. */ + } +} +function clearSuccess() { + if (successPacket !== null) { + successOwners.delete(successPacket.subject); + try { + window.sessionStorage?.removeItem(successKey(successPacket.subject)); + } catch { + /* Replaying a retained exact SDK receipt is safe. */ + } + } + successPacket = null; + successAcknowledged = false; +} function validateView(view) { if ( view?.ticket?.id !== ticketId || @@ -327,8 +456,9 @@ function failure(error, action, generation) { personPacket = null; } if ( - error.status === 401 || error.status === 403 || - (error.status === 404 && replyPacket !== null) + error.status === 401 || + error.status === 403 || + (error.status === 404 && (replyPacket !== null || successPacket !== null)) ) { // A denied ACK may follow a real commit. Retain exact JSON for its owner, // including a not-found read under raced cookies. Neither 404 nor GET can @@ -388,6 +518,7 @@ async function loadTicket() { replyPacket = null; replyAcknowledged = false; } + if (successPacket !== null && successAcknowledged) clearSuccess(); renderTicket(view); showStatus('Ticket loaded.'); return { generation, loaded: true }; @@ -406,6 +537,7 @@ personButton.addEventListener('click', async () => { !onThisTicket() || authorityReloadRequired || replyPacket !== null || + successPacket !== null || viewer === null ) return; @@ -461,6 +593,78 @@ personButton.addEventListener('click', async () => { finishOperation(operation); } }); +successButton.addEventListener('click', async () => { + if ( + busy !== null || + retrySeconds() > 0 || + suspended || + !onThisTicket() || + authorityReloadRequired || + viewer === null || + personPacket !== null || + replyPacket !== null || + successAcknowledged + ) + return; + if (successPacket === null) { + if (currentView?.ticket.status !== 'resolved') return; + const lastSeenVisibleMessageId = currentView.messages.at(-1)?.id; + if ( + typeof lastSeenVisibleMessageId !== 'string' || + lastSeenVisibleMessageId.length < 1 || + lastSeenVisibleMessageId.length > 200 + ) + return; + successPacket = Object.freeze({ + subject: viewer.subject, + ticketId, + body: JSON.stringify({ + commandId: crypto.randomUUID(), + lastSeenVisibleMessageId, + }), + }); + retainSuccess(successPacket); + } + const packet = successPacket; + const expectedViewer = viewer; + const operation = beginOperation(); + const generation = operation.generation; + updateHumanControl(); + try { + await readViewer(generation, expectedViewer); + const result = await api( + '/api/support/tickets/' + + encodeURIComponent(ticketId) + + '/confirm-success', + { method: 'POST', body: packet.body }, + ); + guard(generation); + validateView(result); + await readViewer(generation, expectedViewer); + successAcknowledged = true; + const refreshed = await loadTicket(); + if (isCurrent(refreshed.generation)) + showStatus( + refreshed.loaded + ? 'Resolution confirmed. Thank you.' + : 'Confirmation accepted. Reload to refresh the current ticket.', + !refreshed.loaded, + ); + } catch (error) { + if (!isCurrent(generation) || error.stale) return; + if (error.status === 409) { + clearSuccess(); + const refreshed = await loadTicket(); + if (refreshed.loaded && isCurrent(refreshed.generation)) + showStatus( + 'The visible conversation changed. Review it before making a new confirmation.', + true, + ); + } else failure(error, 'Resolution confirmation', generation); + } finally { + finishOperation(operation); + } +}); replyForm.addEventListener('submit', async (event) => { event.preventDefault(); if ( @@ -469,6 +673,7 @@ replyForm.addEventListener('submit', async (event) => { suspended || authorityReloadRequired || personPacket !== null || + successPacket !== null || replyAcknowledged || viewer === null || currentView === null || @@ -478,10 +683,15 @@ replyForm.addEventListener('submit', async (event) => { if (replyPacket === null) { const body = new FormData(replyForm).get('body'); if ( - typeof body !== 'string' || body.trim() === '' || body.length > 20_000 || + typeof body !== 'string' || + body.trim() === '' || + body.length > 20_000 || /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/u.test(body) ) { - showStatus('Check the reply. Remove unsupported control characters and stay within the field limit.', true); + showStatus( + 'Check the reply. Remove unsupported control characters and stay within the field limit.', + true, + ); return; } const expectedAccountId = viewer.subject; @@ -492,7 +702,10 @@ replyForm.addEventListener('submit', async (event) => { /^[A-Za-z0-9._~-]{1,128}$/u.test(id), ) ) { - showStatus('Could not prepare a retry-safe reply for this account.', true); + showStatus( + 'Could not prepare a retry-safe reply for this account.', + true, + ); return; } replyPacket = Object.freeze({ diff --git a/public/staff-knowledge.js b/public/staff-knowledge.js index 5bb2cc0..8b84d6b 100644 --- a/public/staff-knowledge.js +++ b/public/staff-knowledge.js @@ -177,6 +177,7 @@ async function loadCollection(collectionId) { collection = null; governanceGeneration = null; policyPreview = null; + ++policyEditorVersion; select('#kb-collection-detail').textContent = ''; select('#kb-governance-detail').textContent = ''; select('#kb-portal-form').hidden = true; @@ -185,6 +186,12 @@ async function loadCollection(collectionId) { collection = await call('getCollection', { collectionId }); text('#kb-collection-detail', collection); select('#kb-portal-form').hidden = permissions.collectionManage !== true; + const bot = collection.collection.policy.bot; + select('#kb-bot-enabled').checked = bot.enabled; + select('#kb-bot-permission').value = + bot.enabled && bot.audience.kind === 'permission' + ? bot.audience.permission + : 'knowledge.article.read'; const portal = collection.collection.policy.portal; select('#kb-portal-enabled').checked = portal.enabled; select('#kb-portal-permission').value = @@ -213,6 +220,7 @@ select('#kb-collection-form').addEventListener('submit', (event) => { }); let policyPreview = null; +let policyEditorVersion = 0; select('#kb-portal-form').addEventListener('submit', (event) => { event.preventDefault(); run(async () => { @@ -226,10 +234,25 @@ select('#kb-portal-form').addEventListener('submit', (event) => { }, } : { enabled: false }; - policyPreview = await call('previewCollectionPolicy', { + const bot = select('#kb-bot-enabled').checked + ? { + enabled: true, + audience: { + kind: 'permission', + permission: required('#kb-bot-permission'), + }, + } + : { enabled: false }; + const editorVersion = policyEditorVersion; + const preview = await call('previewCollectionPolicy', { collectionId, - uses: { portal, bot: collection.collection.policy.bot }, + uses: { portal, bot }, }); + if (editorVersion !== policyEditorVersion) { + status('Audience settings changed. Preview them again before applying.'); + return; + } + policyPreview = preview; text('#kb-policy-preview', policyPreview); select('#kb-policy-preview').hidden = false; select('#kb-policy-apply').hidden = permissions.collectionManage !== true; @@ -237,6 +260,20 @@ select('#kb-portal-form').addEventListener('submit', (event) => { }); }); +for (const field of [ + '#kb-portal-enabled', + '#kb-portal-permission', + '#kb-bot-enabled', + '#kb-bot-permission', +]) { + for (const event of ['input', 'change']) + select(field).addEventListener(event, () => { + ++policyEditorVersion; + policyPreview = null; + select('#kb-policy-preview').hidden = true; + select('#kb-policy-apply').hidden = true; + }); +} select('#kb-policy-apply').addEventListener('click', () => run(async () => { if ( diff --git a/public/staff-support-followup.js b/public/staff-support-followup.js new file mode 100644 index 0000000..a5e2321 --- /dev/null +++ b/public/staff-support-followup.js @@ -0,0 +1,1231 @@ +(function (global) { + 'use strict'; + const sameSession = (a, b) => + a?.subject === b?.subject && a?.csrfToken === b?.csrfToken; + function createPanel(options) { + const { root, request, readSession, readCurrentTicket } = options; + let context = null; + let work = null; + let owner = null; + let ownerState = null; + let epoch = 0; + let busy = false; + let retryAt = 0; + let timer = null; + let cursor = null; + let associations = []; + let mappingView = null; + let shownReport = null; + let reportVersion = 0; + const now = options.now ?? Date.now; + const commandId = options.commandId ?? (() => global.crypto.randomUUID()); + const doc = root.ownerDocument ?? document; + const create = (tag, text) => { + const node = doc.createElement(tag); + if (text !== undefined) node.textContent = text; + return node; + }; + const heading = create('h2', 'Release follow-up'); + const status = create( + 'p', + 'Check the optional release-follow-up controls.', + ); + status.setAttribute('role', 'status'); + const workId = create('input'); + workId.dataset.followupField = 'workId'; + workId.setAttribute('aria-label', 'Follow-up work ID'); + const reference = create('input'); + reference.dataset.followupField = 'inputReference'; + reference.setAttribute('aria-label', 'Trusted release input reference'); + const repository = create('input'); + repository.dataset.followupField = 'repositoryId'; + repository.setAttribute('aria-label', 'Accepted repository ID'); + const issue = create('input'); + issue.dataset.followupField = 'issueId'; + issue.setAttribute('aria-label', 'Accepted issue ID'); + const association = create('select'); + association.dataset.followupField = 'association'; + const mappingFields = {}; + for (const name of [ + 'releaseRef', + 'productId', + 'version', + 'buildId', + 'deploymentId', + 'deploymentEpoch', + 'scopeRef', + 'verificationReference', + ]) { + const field = create('input'); + field.maxLength = 200; + field.dataset.followupField = name; + mappingFields[name] = field; + } + mappingFields.releaseRef.readOnly = true; + mappingFields.productId.readOnly = true; + for (const [name, values] of [ + ['issueState', ['open', 'closed']], + ['deploymentState', ['unknown', 'deployed', 'rolled_back']], + ]) { + const field = create('select'); + field.dataset.followupField = name; + for (const value of values) { + const option = create('option', value); + option.value = value; + field.append(option); + } + mappingFields[name] = field; + } + const facts = create('textarea'); + facts.maxLength = 10000; + facts.dataset.followupField = 'publicFacts'; + const verified = create('input'); + verified.type = 'checkbox'; + verified.dataset.followupField = 'mappingVerified'; + const mappingControls = create('fieldset'); + mappingControls.className = 'account-form'; + mappingControls.append( + create('legend', 'Staff-verified deployed fix'), + labelled('Accepted engineering association', association), + ...Object.entries(mappingFields).map(([name, field]) => + labelled( + { + releaseRef: 'Current release reference', + productId: 'Product', + version: 'Fixed version', + buildId: 'Fixed build', + deploymentId: 'Deployment ID', + deploymentEpoch: 'Deployment version', + scopeRef: 'Deployment scope', + verificationReference: 'Verification reference', + issueState: 'Issue state', + deploymentState: 'Deployment state', + }[name], + field, + ), + ), + labelled( + 'Public facts JSON: one to four unique {reference,text} entries', + facts, + ), + labelled( + 'I verified these issue, deployment and product facts.', + verified, + ), + ); + association.addEventListener('change', () => { + mappingView = null; + reference.value = ''; + verified.checked = false; + const selected = + association.value === '' + ? undefined + : associations[Number(association.value)]; + repository.value = selected?.repositoryId ?? ''; + issue.value = selected?.issueId ?? ''; + mappingFields.productId.value = selected?.product?.productId ?? ''; + render(); + }); + const reason = create('input'); + reason.dataset.followupField = 'reason'; + reason.setAttribute('aria-label', 'Staff hold or rejection reason'); + const content = create('textarea'); + const retestRequest = create('select'); + retestRequest.dataset.followupField = 'retestRequestId'; + const reportFields = {}; + for (const name of ['articleId', 'ledgerEpoch', 'reportId']) { + const field = create('input'); + field.maxLength = 200; + field.dataset.followupField = name; + reportFields[name] = field; + for (const event of ['input', 'change']) + field.addEventListener(event, () => { + ++reportVersion; + shownReport = null; + reportView.textContent = ''; + render(); + }); + } + const reportView = create('pre'); + reportView.className = 'support-message-body'; + retestRequest.addEventListener('change', () => { + ++reportVersion; + shownReport = null; + reportView.textContent = ''; + render(); + }); + const retestControls = create('fieldset'); + retestControls.className = 'account-form'; + retestControls.append( + create('legend', 'Record a verified retest result'), + labelled('Exact retest request', retestRequest), + labelled('Knowledge article ID', reportFields.articleId), + labelled('Report ledger epoch', reportFields.ledgerEpoch), + labelled('Knowledge report ID', reportFields.reportId), + reportView, + ); + content.dataset.followupField = 'content'; + content.setAttribute( + 'aria-label', + 'Complete retained follow-up candidate JSON', + ); + const privateView = create('pre'); + content.rows = 8; + function labelled(text, field) { + const label = create('label', text); + label.append(field); + return label; + } + const controls = new Map(); + for (const field of [workId, reference, repository, issue, reason]) + field.maxLength = 200; + content.maxLength = 16_000; + const actions = create('div'); + function add(action, text) { + const button = create('button', text); + button.type = 'button'; + button.dataset.followupAction = action; + button.addEventListener('click', () => { + void perform(action); + }); + controls.set(action, button); + actions.append(button); + } + add('mapping-list', 'Load accepted issue choices'); + add('mapping', 'Read selected fix mapping'); + add('verify-mapping', 'Record this staff verification'); + add('withdraw-mapping', 'Withdraw this verified mapping'); + add('scan', 'Find follow-up work'); + add('work', 'Read private follow-up'); + add('observe', 'Verify trusted release input'); + add('reassess', 'Check retained draft and edits'); + add('post', 'Approve and post this exact web update'); + add('reject', 'Reject checked bundle'); + add('retry', 'Retry draftless work'); + add('abandon', 'Hold this work'); + add('report-read', 'Read current Knowledge report'); + add('retest-receipt', 'Associate this report with the retest'); + add('retest-result', 'Record the prepared retest result'); + add('exact-retry', 'Retry the exact previous command'); + add('discard', 'Discard an unsent or rejected command'); + root.replaceChildren( + heading, + status, + labelled('Follow-up work ID', workId), + labelled('Trusted release input reference', reference), + labelled('Accepted repository ID', repository), + labelled('Accepted issue ID', issue), + labelled('Staff hold or rejection reason', reason), + labelled('Complete retained candidate JSON', content), + privateView, + mappingControls, + retestControls, + actions, + ); + function notify() { + options.onPendingChange?.( + owner === null + ? null + : Object.freeze({ + actorSubject: owner.actorSubject, + ticketId: owner.ticketId, + }), + ); + } + function render() { + const ready = context !== null && options.canRequest?.() !== false; + const owns = + owner !== null && + context?.actorSubject === owner.actorSubject && + context?.ticketId === owner.ticketId; + for (const [action, button] of controls) { + button.disabled = + !ready || + busy || + now() < retryAt || + (['exact-retry', 'retest-result', 'discard'].includes(action) + ? !owns || + (action === 'discard' && !canDiscard()) || + (action === 'retest-result' && owner.operation !== 'retest') + : owner !== null) || + (action === 'report-read' && work === null) || + (action === 'retest-receipt' && + (work === null || + shownReport?.qualified !== true || + retestRequest.value === '')) || + (['verify-mapping', 'withdraw-mapping'].includes(action) && + mappingView === null) || + (['reassess', 'post', 'reject', 'retry', 'abandon'].includes( + action, + ) && + work === null) || + (['post', 'reject'].includes(action) && work?.prepared === undefined); + } + for (const field of [ + workId, + reference, + repository, + issue, + reason, + content, + association, + facts, + verified, + ...Object.values(mappingFields), + retestRequest, + ...Object.values(reportFields), + ]) + field.disabled = !ready || busy || owner !== null; + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + if (ready && retryAt > now()) + timer = setTimeout( + () => { + timer = null; + render(); + }, + Math.min(60_000, retryAt - now()), + ); + } + function canDiscard() { + return ( + owner !== null && + ownerState !== null && + !ownerState.uncertain && + (!ownerState.sent || ownerState.rejected) + ); + } + function terminalPreparationRefusal(error) { + return owner?.operation === 'retest-receipt' && + ((error.status === 410 && error.code === 'followup_retest_expired') || + (error.status === 429 && error.code === 'followup_retest_capacity')); + } + async function ownedRequest(send, qualify) { + const state = ownerState; + const previouslyUncertain = state.uncertain; + state.sent = true; + state.uncertain = true; + state.rejected = false; + let response; + try { + response = await send(); + } catch (error) { + // A closed refusal cannot erase a prior unknown acknowledgement. + if (([400, 409, 413].includes(error.status) || terminalPreparationRefusal(error)) && !previouslyUncertain) { + state.uncertain = false; + state.rejected = true; + } + throw error; + } + const result = await qualify(response); + state.uncertain = previouslyUncertain; + return result; + } + function clearPrivate() { + work = null; + ++reportVersion; + shownReport = null; + reportView.textContent = ''; + retestRequest.replaceChildren(); + retestRequest.value = ''; + for (const field of Object.values(reportFields)) field.value = ''; + privateView.textContent = ''; + content.value = ''; + associations = []; + mappingView = null; + association.replaceChildren(); + facts.value = ''; + verified.checked = false; + for (const field of Object.values(mappingFields)) field.value = ''; + for (const field of [workId, reference, repository, issue, reason]) + field.value = ''; + } + function suspend() { + ++epoch; + context = null; + clearPrivate(); + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + status.textContent = + owner === null + ? 'Reload current staff access.' + : 'Keep this tab open. The original command may have completed. Restore its original account and reload the ticket.'; + render(); + } + function ensure(token, selected) { + if ( + epoch !== token || + context !== selected || + options.canRequest?.() === false + ) + throw Object.assign(new Error('stale_followup_view'), { stale: true }); + } + async function authority(token, selected) { + ensure(token, selected); + const session = await readSession(); + ensure(token, selected); + if ( + session?.subject !== selected.actorSubject || + typeof session.csrfToken !== 'string' || + session.csrfToken === '' + ) + throw Object.assign(new Error('original_actor_required'), { + status: 401, + }); + const current = await readCurrentTicket(selected.ticketId); + ensure(token, selected); + if ( + current?.ticket?.id !== selected.ticketId || + current.csrfToken !== session.csrfToken + ) + throw new Error('invalid_current_ticket'); + const closing = await readSession(); + ensure(token, selected); + if (!sameSession(session, closing)) + throw Object.assign(new Error('session_changed'), { status: 401 }); + return session; + } + function path(selected, operation) { + return ( + '/api/support/admin/tickets/' + + encodeURIComponent(selected.ticketId) + + '/follow-up/' + + operation + ); + } + function required(value, label) { + const text = typeof value === 'string' ? value.trim() : ''; + if ( + text.length < 1 || + text.length > 200 || + /[\u0000-\u001F\u007F]/u.test(text) + ) + throw Object.assign(new Error('Enter ' + label + ' before sending.'), { + local: true, + }); + return text; + } + function currentRetestRequests() { + const values = + work?.prepared?.bundle?.retestRequests ?? work?.handoff?.retestRequests; + return Array.isArray(values) && + values.length <= 4 && + values.every( + (value) => + value && + typeof value.requestId === 'string' && + value.requestId.length > 0 && + value.requestId.length <= 200, + ) + ? values + : []; + } + function showRetestRequests() { + ++reportVersion; + shownReport = null; + reportView.textContent = ''; + retestRequest.replaceChildren(); + const placeholder = create('option', 'Choose the exact retest request'); + placeholder.value = ''; + retestRequest.append(placeholder); + for (const item of currentRetestRequests()) { + const option = create( + 'option', + item.requestId + ' · ' + item.expectedBehavior, + ); + option.value = item.requestId; + retestRequest.append(option); + } + retestRequest.value = ''; + } + function reportCoordinates() { + const articleId = reportFields.articleId.value; + const reportId = reportFields.reportId.value; + if ( + ![articleId, reportId].every( + (v) => + typeof v === 'string' && + v.trim().length > 0 && + v.length <= 200 && + !/[\u0000-\u001f\u007f]/u.test(v), + ) || + !/^[1-9][0-9]*$/u.test(reportFields.ledgerEpoch.value) + ) + throw Object.assign( + new Error( + 'Complete the article, positive ledger epoch and report ID before reading.', + ), + { local: true }, + ); + const ledgerEpoch = Number(reportFields.ledgerEpoch.value); + if (!Number.isSafeInteger(ledgerEpoch)) + throw Object.assign(new Error('Enter a valid report ledger epoch.'), { + local: true, + }); + return { articleId, ledgerEpoch, reportId }; + } + function readReportView(value, coordinates) { + if ( + !value || + value.articleId !== coordinates.articleId || + value.ledgerEpoch !== coordinates.ledgerEpoch || + value.reportId !== coordinates.reportId || + !Number.isSafeInteger(value.reportGeneration) || + value.reportGeneration < 1 || + value.expectedReportGeneration !== value.reportGeneration || + !/^[a-f0-9]{64}$/u.test(value.reviewBindingHash) || + typeof value.receipt !== 'string' || + value.receipt.length < 1 || + value.receipt.length > 200 || + !['pending', 'confirmed', 'rejected'].includes(value.status) || + !['passed', 'failed', 'inconclusive'].includes( + value.evidence?.result, + ) || + typeof value.report?.summary !== 'string' || + typeof value.report?.details !== 'string' + ) + throw new Error('invalid_current_report'); + return Object.freeze({ + ...coordinates, + expectedReportGeneration: value.reportGeneration, + reviewBindingHash: value.reviewBindingHash, + receipt: value.receipt, + qualified: + value.status === 'confirmed' && + ['passed', 'failed'].includes(value.evidence.result) && + value.confirmation !== null && + typeof value.confirmation === 'object', + display: JSON.stringify( + { + articleId: value.articleId, + ledgerEpoch: value.ledgerEpoch, + reportId: value.reportId, + reportGeneration: value.reportGeneration, + status: value.status, + result: value.evidence.result, + summary: value.report.summary, + details: value.report.details, + }, + null, + 2, + ), + }); + } + function preparationResult(httpStatus, value, packet) { + const pending = httpStatus === 202; + const keys = [ + 'actorId', + 'ticketId', + 'commandId', + 'workId', + 'retestRequestId', + ...(pending ? ['pending'] : ['receipt', 'validUntil']), + ]; + if ( + ![200, 202].includes(httpStatus) || + !value || + Object.keys(value).sort().join(',') !== keys.sort().join(',') || + value.actorId !== packet.actorSubject || + value.ticketId !== packet.ticketId || + value.commandId !== packet.commandId || + value.workId !== packet.workId || + value.retestRequestId !== packet.retestRequestId + ) + throw new Error('unconfirmed_retest_preparation'); + if (pending) { + if (value.pending !== 'report') + throw new Error('invalid_pending_phase'); + return { pending: true }; + } + if ( + typeof value.receipt !== 'string' || + !value.receipt.trim() || + value.receipt.length > 200 || + typeof value.validUntil !== 'string' || + !Number.isFinite(Date.parse(value.validUntil)) || + new Date(value.validUntil).toISOString() !== value.validUntil + ) + throw new Error('invalid_retest_receipt'); + return { pending: false, receipt: value.receipt }; + } + function ack(value, packet) { + if (['verify-mapping', 'withdraw-mapping'].includes(packet.operation)) + return ( + value?.result?.actorId === packet.actorSubject && + value.result.ticketId === packet.ticketId && + value.result.commandId === packet.commandId && + Number.isSafeInteger(value.result.mappingGeneration) && + value.result.mappingGeneration >= 1 && + typeof value.result.inputReference === 'string' && + value.result.inputReference.length > 0 + ); + + if ( + value?.commandId !== packet.commandId || + value.operation !== packet.operation || + value.result?.ticketId !== packet.ticketId + ) + return false; + if (packet.operation === 'observe') + return ( + Number.isSafeInteger(value.result.headGeneration) && + ['queued', 'unchanged', 'held', 'stale'].includes( + value.result.outcome, + ) + ); + if (value.result.workId !== packet.workId) return false; + if (packet.operation === 'retest') + return ( + Object.keys(value.result).sort().join(',') === + 'outcome,result,ticketId,workId' && + ['recorded', 'unchanged', 'held'].includes(value.result.outcome) && + ['passed', 'failed'].includes(value.result.result) + ); + if (packet.operation === 'post') + return ( + value.result.messageId === packet.messageId && + value.result.bundleHash === packet.bundleHash && + Number.isSafeInteger(value.result.ticketRevision) && + value.result.ticketRevision >= 1 + ); + return ( + Number.isSafeInteger(value.result.workGeneration) && + value.result.workGeneration >= 1 && + typeof value.result.status === 'string' + ); + } + async function perform(action) { + if ( + !controls.has(action) || + context === null || + busy || + options.canRequest?.() === false || + now() < retryAt + ) + return; + const selected = context; + const token = epoch; + if ( + owner !== null && + (!['exact-retry', 'retest-result', 'discard'].includes(action) || + owner.actorSubject !== selected.actorSubject || + owner.ticketId !== selected.ticketId) + ) + return; + busy = true; + options.onBusyChange?.(true); + render(); + try { + let session = await authority(token, selected); + if (action === 'discard') { + if (!canDiscard()) return; + owner = null; + ownerState = null; + notify(); + clearPrivate(); + status.textContent = + 'The unsent or rejected command was discarded locally. Reload current follow-up state before preparing another command.'; + return; + } + if (action === 'report-read') { + if ( + !currentRetestRequests().some( + (item) => item.requestId === retestRequest.value, + ) + ) + throw Object.assign( + new Error('Read work and choose its exact retest request first.'), + { local: true }, + ); + const coordinates = reportCoordinates(); + const observed = reportVersion; + const chosen = retestRequest.value; + shownReport = null; + reportView.textContent = ''; + const value = await request('/api/staff/knowledge/command', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Pegma-CSRF': session.csrfToken, + }, + body: JSON.stringify({ + operation: 'reportRead', + input: coordinates, + }), + }); + ensure(token, selected); + const closing = await readSession(); + ensure(token, selected); + if (!sameSession(session, closing)) + throw Object.assign(new Error('session_changed'), { status: 401 }); + if ( + observed !== reportVersion || + chosen !== retestRequest.value || + JSON.stringify(reportCoordinates()) !== JSON.stringify(coordinates) + ) { + status.textContent = + 'The report selection changed. Read the selected report again.'; + return; + } + shownReport = readReportView(value, coordinates); + reportView.textContent = shownReport.display; + status.textContent = shownReport.qualified + ? 'Confirmed report shown. Associate this exact report version with the selected retest.' + : 'This report is pending, rejected or inconclusive. Use the existing Knowledge confirmation workflow before association.'; + return; + } + if (action === 'mapping-list' || action === 'mapping') { + const suffix = + action === 'mapping-list' + ? '' + : '?' + + new URLSearchParams({ + repositoryId: required( + repository.value, + 'an accepted repository', + ), + issueId: required(issue.value, 'an accepted issue'), + }); + const value = await request(path(selected, 'mapping') + suffix); + ensure(token, selected); + const closing = await readSession(); + ensure(token, selected); + const view = value?.result; + if ( + !sameSession(session, closing) || + value.csrfToken !== closing.csrfToken || + view?.actorId !== selected.actorSubject || + view.ticketId !== selected.ticketId || + !Number.isSafeInteger(view.ticketRevision) || + view.ticketRevision < 1 + ) + throw new Error('invalid_mapping_response'); + if (action === 'mapping-list') { + if ( + !Array.isArray(view.choices) || + view.choices.length > 16 || + typeof view.hasMore !== 'boolean' || + view.choices.some( + (entry) => + typeof entry.repositoryId !== 'string' || + typeof entry.issueId !== 'string' || + !Number.isSafeInteger(entry.issueNumber) || + typeof entry.repositoryName !== 'string', + ) + ) + throw new Error('invalid_mapping_choices'); + associations = view.choices; + mappingView = null; + reference.value = ''; + verified.checked = false; + association.replaceChildren(); + const placeholder = create('option', 'Choose an accepted issue'); + placeholder.value = ''; + association.append(placeholder); + associations.forEach((entry, index) => { + const option = create( + 'option', + entry.repositoryName + ' #' + entry.issueNumber, + ); + option.value = String(index); + association.append(option); + }); + association.value = ''; + repository.value = ''; + issue.value = ''; + status.textContent = view.hasMore + ? 'The bounded issue list has more associations. Select one of the visible accepted issues.' + : 'Choose an accepted issue, then read its current mapping.'; + } else { + if ( + view.repositoryId !== repository.value || + view.issueId !== issue.value || + !Number.isSafeInteger(view.mappingGeneration) || + view.mappingGeneration < 0 || + !(view.mapping === null || typeof view.mapping === 'object') || + !(view.release === null || typeof view.release === 'object') + ) + throw new Error('invalid_mapping_view'); + mappingView = view; + verified.checked = false; + const mapping = view.mapping; + reference.value = + mapping?.current === true && mapping.withdrawn !== true + ? mapping.inputReference + : ''; + for (const name of [ + 'deploymentId', + 'deploymentEpoch', + 'scopeRef', + 'verificationReference', + ]) + mappingFields[name].value = mapping?.[name] ?? ''; + mappingFields.releaseRef.value = view.release?.releaseRef ?? ''; + mappingFields.productId.value = + associations.find( + (entry) => + entry.repositoryId === view.repositoryId && + entry.issueId === view.issueId, + )?.product?.productId ?? + mapping?.fixedProduct?.productId ?? + ''; + mappingFields.version.value = mapping?.fixedProduct?.version ?? ''; + mappingFields.buildId.value = mapping?.fixedProduct?.buildId ?? ''; + mappingFields.issueState.value = mapping?.issueState ?? 'open'; + mappingFields.deploymentState.value = + mapping?.deploymentState ?? 'unknown'; + facts.value = JSON.stringify(mapping?.publicFacts ?? [], null, 2); + privateView.textContent = JSON.stringify(view, null, 2); + status.textContent = + 'Inspect the authenticated release and verify the entered facts. Issue closure alone is not deployment proof.'; + } + return; + } + if (action === 'scan' || action === 'work') { + const suffix = + action === 'scan' + ? cursor === null + ? '' + : '?cursor=' + encodeURIComponent(cursor) + : '?workId=' + encodeURIComponent(workId.value.trim()); + const value = await request(path(selected, action) + suffix); + ensure(token, selected); + const closing = await readSession(); + ensure(token, selected); + if ( + !sameSession(session, closing) || + value?.csrfToken !== closing.csrfToken || + value.result?.ticketId !== selected.ticketId + ) + throw new Error('invalid_followup_response'); + if (action === 'scan') { + const keys = [ + ...(value.result.reviewCandidates ?? []), + ...(value.result.candidates ?? []), + ]; + if ( + !Array.isArray(value.result.reviewCandidates) || + !Array.isArray(value.result.candidates) || + keys.some( + (key) => + key.ticketId !== selected.ticketId || + typeof key.workId !== 'string', + ) || + !( + value.result.nextCursor === null || + typeof value.result.nextCursor === 'string' + ) + ) + throw new Error('invalid_followup_page'); + cursor = value.result.nextCursor; + privateView.textContent = keys.map((key) => key.workId).join('\n'); + if (keys[0]) workId.value = keys[0].workId; + status.textContent = + cursor === null + ? 'Bounded follow-up scan complete.' + : 'More records remain. Find follow-up work again to continue.'; + } else { + if ( + value.result.workId !== workId.value.trim() || + !Number.isSafeInteger(value.result.workGeneration) || + value.result.workGeneration < 1 + ) + throw new Error('invalid_followup_work'); + work = value.result; + showRetestRequests(); + privateView.textContent = JSON.stringify(work, null, 2); + content.value = + work.candidate === undefined + ? '' + : JSON.stringify(work.candidate, null, 2); + status.textContent = + 'Private follow-up loaded. Review the complete bundle before posting.'; + } + return; + } + if (owner === null) { + const id = commandId(); + let body; + if (action === 'retest-receipt') { + const expectedTicketRevision = + work?.delivered?.ticketRevision ?? work?.acceptedTicketRevision; + const coordinates = reportCoordinates(); + if ( + work === null || + work.workId !== workId.value.trim() || + shownReport?.qualified !== true || + ['articleId', 'ledgerEpoch', 'reportId'].some( + (key) => coordinates[key] !== shownReport[key], + ) || + !currentRetestRequests().some( + (item) => item.requestId === retestRequest.value, + ) || + !Number.isSafeInteger(expectedTicketRevision) || + expectedTicketRevision < 1 + ) + throw Object.assign( + new Error( + 'Read current work, choose its retest and read a confirmed report first.', + ), + { local: true }, + ); + body = { + commandId: id, + expectedPrincipalId: selected.actorSubject, + workId: work.workId, + expectedWorkGeneration: work.workGeneration, + expectedTicketRevision: expectedTicketRevision, + retestRequestId: retestRequest.value, + report: { + ...coordinates, + expectedReportGeneration: shownReport.expectedReportGeneration, + reviewBindingHash: shownReport.reviewBindingHash, + receipt: shownReport.receipt, + }, + }; + } else if ( + action === 'verify-mapping' || + action === 'withdraw-mapping' + ) { + if ( + mappingView === null || + mappingView.repositoryId !== repository.value || + mappingView.issueId !== issue.value + ) + throw Object.assign( + new Error('Read the current selected mapping first.'), + { local: true }, + ); + body = { + commandId: id, + expectedPrincipalId: selected.actorSubject, + expectedTicketRevision: mappingView.ticketRevision, + expectedMappingGeneration: mappingView.mappingGeneration, + repositoryId: mappingView.repositoryId, + issueId: mappingView.issueId, + }; + if (action === 'withdraw-mapping') + body.reason = required(reason.value, 'a withdrawal reason'); + else { + if (!verified.checked) + throw Object.assign( + new Error( + 'Confirm the facts you actually verified before recording them.', + ), + { local: true }, + ); + let publicFacts; + try { + publicFacts = JSON.parse(facts.value); + } catch { + throw Object.assign( + new Error('Enter valid public facts JSON.'), + { local: true }, + ); + } + if ( + !Array.isArray(publicFacts) || + publicFacts.length < 1 || + publicFacts.length > 4 || + publicFacts.some( + (fact) => + !fact || + Object.keys(fact).sort().join(',') !== 'reference,text' || + typeof fact.reference !== 'string' || + !fact.reference.trim() || + fact.reference.length > 200 || + typeof fact.text !== 'string' || + !fact.text.trim() || + fact.text.length > 1000 || + /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test( + fact.text, + ), + ) + ) + throw Object.assign( + new Error( + 'Use one to four public facts with unique references and text of at most 1000 characters.', + ), + { local: true }, + ); + if ( + new Set(publicFacts.map((fact) => fact.reference)).size !== + publicFacts.length + ) + throw Object.assign( + new Error('Each public fact needs a unique reference.'), + { local: true }, + ); + Object.assign(body, { + releaseRef: required( + mappingFields.releaseRef.value, + 'the current release reference', + ), + issueState: required( + mappingFields.issueState.value, + 'the issue state', + ), + deploymentState: required( + mappingFields.deploymentState.value, + 'the deployment state', + ), + fixedProduct: { + productId: required( + mappingFields.productId.value, + 'the product ID', + ), + version: required( + mappingFields.version.value, + 'the fixed version', + ), + buildId: required( + mappingFields.buildId.value, + 'the fixed build ID', + ), + }, + deploymentId: required( + mappingFields.deploymentId.value, + 'the deployment ID', + ), + deploymentEpoch: required( + mappingFields.deploymentEpoch.value, + 'the deployment epoch', + ), + scopeRef: required( + mappingFields.scopeRef.value, + 'the deployment scope', + ), + verificationReference: required( + mappingFields.verificationReference.value, + 'the verification reference', + ), + publicFacts, + }); + } + } else if (action === 'observe') + body = { + commandId: id, + repositoryId: required( + repository.value, + 'the accepted repository ID', + ), + issueId: required(issue.value, 'the accepted issue ID'), + inputReference: required( + reference.value, + 'the trusted input reference', + ), + }; + else { + if (work === null || work.workId !== workId.value.trim()) + throw new Error('read_current_work_first'); + body = { + commandId: id, + workId: work.workId, + expectedWorkGeneration: work.workGeneration, + }; + if (action === 'post') + Object.assign(body, { + expectedTicketRevision: work.acceptedTicketRevision, + bundleHash: work.prepared?.bundleHash, + messageId: commandId(), + }); + else if (action === 'reject') + Object.assign(body, { + bundleHash: work.prepared?.bundleHash, + reason: required(reason.value, 'a rejection reason'), + }); + else if (action === 'abandon') + body.reason = required(reason.value, 'a hold reason'); + else if (action === 'reassess' && content.value.trim() !== '') + body.content = JSON.parse(content.value); + } + owner = Object.freeze({ + actorSubject: selected.actorSubject, + ticketId: selected.ticketId, + operation: action, + body: JSON.stringify(body), + ...body, + }); + ownerState = { sent: false, uncertain: false, rejected: false }; + notify(); + } + const packet = owner; + if (packet.operation === 'retest-receipt') { + const sendPreparation = async () => { + const init = { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Pegma-CSRF': session.csrfToken, + }, + body: packet.body, + }; + return ownedRequest( + async () => + options.requestWithStatus + ? options.requestWithStatus( + path(selected, packet.operation), + init, + ) + : { + status: 200, + body: await request( + path(selected, packet.operation), + init, + ), + }, + async (response) => { + ensure(token, selected); + const closing = await readSession(); + ensure(token, selected); + if ( + !sameSession(session, closing) || + response.body?.csrfToken !== closing.csrfToken + ) + throw new Error('unconfirmed_preparation_session'); + return preparationResult( + response.status, + response.body?.result, + packet, + ); + }, + ); + }; + let result = await sendPreparation(); + if (result.pending) { + session = await authority(token, selected); + result = await sendPreparation(); + } + if (result.pending) { + status.textContent = + 'Report association is pending. No retest result has been recorded. Retry the exact preparation.'; + return; + } + const id = commandId(); + const body = { + commandId: id, + workId: packet.workId, + retestRequestId: packet.retestRequestId, + receiptReference: result.receipt, + }; + owner = Object.freeze({ + actorSubject: packet.actorSubject, + ticketId: packet.ticketId, + operation: 'retest', + preparation: packet, + body: JSON.stringify(body), + ...body, + }); + ownerState = { sent: false, uncertain: false, rejected: false }; + notify(); + clearPrivate(); + status.textContent = + 'Report associated. No retest result has been recorded. Choose Record the prepared retest result.'; + return; + } + const value = await ownedRequest( + () => + request(path(selected, packet.operation), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Pegma-CSRF': session.csrfToken, + }, + body: packet.body, + }), + async (response) => { + ensure(token, selected); + const closing = await readSession(); + ensure(token, selected); + if ( + !sameSession(session, closing) || + response?.csrfToken !== closing.csrfToken || + !ack(response, packet) + ) + throw new Error('unconfirmed_exact_command'); + return response; + }, + ); + owner = null; + ownerState = null; + notify(); + clearPrivate(); + status.textContent = + packet.operation === 'retest' + ? value.result.outcome === 'held' + ? 'Retest result held. No new result was recorded.' + : 'Retest ' + value.result.result + ' result acknowledged.' + : 'The exact command was acknowledged. Reloading current ticket state.'; + await options.onSettled?.(); + if ( + packet.operation === 'retest' && + context?.ticketId === packet.ticketId && + context?.actorSubject === packet.actorSubject + ) + status.textContent = + value.result.outcome === 'held' + ? 'Retest result held. No new result was recorded.' + : 'Retest ' + value.result.result + ' result acknowledged.'; + } catch (error) { + if (epoch !== token) return; + if (error.local === true && owner === null) { + status.textContent = error.message; + return; + } + clearPrivate(); + if (error.status === 429 && !(terminalPreparationRefusal(error) && canDiscard())) + retryAt = Math.max(retryAt, error.retryAt ?? now() + 30_000); + status.textContent = + owner === null + ? 'Follow-up is unavailable. Check current access and retry the read.' + : canDiscard() + ? 'The command was rejected. Discard it locally, then reload current follow-up state.' + : 'The original command may have completed. Restore current access, then retry its exact packet.'; + if ([401, 403].includes(error.status)) { + suspend(); + options.onAccessLost?.({ status: error.status }); + } + } finally { + busy = false; + options.onBusyChange?.(false); + render(); + } + } + render(); + return Object.freeze({ + showTicket(value) { + ++epoch; + clearPrivate(); + cursor = null; + context = Object.freeze({ + ticketId: value.ticketId, + actorSubject: value.actorSubject, + }); + if ( + owner !== null && + (owner.ticketId !== context.ticketId || + owner.actorSubject !== context.actorSubject) + ) + status.textContent = + 'Return to the original account and ticket to recover its pending command.'; + else + status.textContent = + owner === null + ? 'Check the optional release-follow-up controls.' + : canDiscard() + ? 'The original command is unsent or rejected. Discard it locally to reload current follow-up state.' + : 'Current ticket loaded. Retry the exact previous command.'; + root.hidden = false; + render(); + }, + suspend, + hasPending: () => owner !== null, + perform, + }); + } + global.PegmaSupportFollowup = Object.freeze({ createPanel }); +})(globalThis); diff --git a/public/staff-support-learning.js b/public/staff-support-learning.js index e2264a0..927dfcf 100644 --- a/public/staff-support-learning.js +++ b/public/staff-support-learning.js @@ -33,6 +33,7 @@ let source = null; let work = null; let shownBinding = null; + let shownReport = null; let pending = null; let pendingAction = 'submit'; let pollTimer = null; @@ -55,8 +56,16 @@ 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 evidenceKind = choice('evidence-kind', 'Evidence', ['staff_verified_fix', 'successful_test']); const verification = field('verification', 'Staff verification reference'); - const evidenceButton = button('evidence', 'Record staff-verified fix', () => mutate('evidence')); + const reportArticle = field('report-article', 'Knowledge article ID'); + const reportLedger = field('report-ledger', 'Report ledger epoch'); + const reportId = field('report-id', 'Knowledge report ID'); + const reportReadButton = button('report-read', 'Read current Knowledge report', () => readReport()); + const reportText = element('pre'); + const reportAssociateButton = button('report-associate', 'Associate shown report with this solution', () => mutate('test-receipt')); + const testNotice = element('p', 'Read a confirmed passed report, explicitly associate it with this ticket and solution, then record resolution evidence. Report confirmation remains in the existing Knowledge workflow.'); + const evidenceButton = button('evidence', 'Record resolution evidence', () => 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')); @@ -68,12 +77,22 @@ 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, + proposalText, enrollButton, solution.label, evidenceKind.label, verification.label, + reportArticle.label, reportLedger.label, reportId.label, reportReadButton, + reportText, reportAssociateButton, testNotice, 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); + for (const input of [reportArticle.input, reportLedger.input, reportId.input]) { + input.addEventListener('input', () => { + shownReport = null; + reportText.textContent = ''; + controls(); + }); + } + evidenceKind.input.addEventListener('change', controls); hidePrivate(); controls(); @@ -123,6 +142,11 @@ proposalText.textContent = ''; solution.input.value = ''; verification.input.value = ''; + reportArticle.input.value = ''; + reportLedger.input.value = ''; + reportId.input.value = ''; + reportText.textContent = ''; + shownReport = null; reviewReason.input.value = ''; source = null; work = null; @@ -149,6 +173,24 @@ function canRecordEvidence() { return source !== null && source.state !== 'withdrawn' && context?.resolved === true; } + function testReceiptEnabled() { + try { + return options.testReceiptEnabled?.() === true; + } catch { + return false; + } + } + function ownsPending() { + return ( + pending !== null && + context !== null && + pending.subject === context.actorSubject && + pending.ticketId === context.ticketId + ); + } + function preparedEvidence() { + return ownsPending() && pending.intake === 'evidence' && pendingAction === 'prepared'; + } function canReadWork() { return source !== null && source.state === 'eligible' && source.sourceGeneration > 0; } @@ -157,7 +199,11 @@ const blocked = busy || !ready || context === null; for (const node of [enrollButton, evidenceButton, approveButton, rejectButton, withdrawButton, invalidateButton]) node.disabled = blocked || pending !== null; - evidenceButton.disabled ||= !canRecordEvidence(); + evidenceButton.disabled ||= !canRecordEvidence() || evidenceKind.input.value === 'successful_test'; + if (preparedEvidence()) evidenceButton.disabled = blocked; + reportReadButton.disabled = blocked || pending !== null || !testReceiptEnabled(); + reportAssociateButton.disabled = blocked || pending !== null || !canRecordEvidence() || + !testReceiptEnabled() || shownReport?.qualified !== true; approveButton.disabled ||= shownBinding === null || !canReadWork(); rejectButton.disabled ||= shownBinding === null || !canReadWork(); readWorkButton.disabled = blocked || !canReadWork(); @@ -170,12 +216,16 @@ 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'; + if (preparedEvidence()) retryButton.textContent = 'Record evidence from the associated report'; + else if (pending?.preparation === true) retryButton.textContent = 'Retry the exact report association'; + else 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, + for (const node of [solution.input, evidenceKind.input, verification.input, reviewReason.input, withdrawReason.input, invalidateReason.input]) node.disabled = blocked || pending !== null; + for (const node of [reportArticle.input, reportLedger.input, reportId.input]) + node.disabled = blocked || pending !== null || !testReceiptEnabled(); } function cancelReads() { for (const controller of controllers) controller.abort(); @@ -201,7 +251,7 @@ throw Object.assign(new Error('session_changed'), { status: 401 }); return next; } - async function call(path, init, generation, actor) { + async function callRaw(path, init, generation, actor) { current(generation); const controller = new AbortController(); controllers.add(controller); @@ -212,11 +262,15 @@ signal: controller.signal, }); current(generation); - if (!object(result) || !Object.prototype.hasOwnProperty.call(result, 'result') || - result.csrfToken !== actor.csrfToken) throw invalid(); - return result.result; + return result; } finally { controllers.delete(controller); } } + async function call(path, init, generation, actor) { + const result = await callRaw(path, init, generation, actor); + if (!object(result) || !Object.prototype.hasOwnProperty.call(result, 'result') || + result.csrfToken !== actor.csrfToken) throw invalid(); + return result.result; + } function base() { return `/api/support/admin/tickets/${encodeURIComponent(context.ticketId)}/learning`; } @@ -351,15 +405,140 @@ notice(kind === 'work' ? 'Current learning work read.' : 'Checked private KB proposal shown. Choose approve or reject explicitly.'); }); } + function reportCoordinates() { + const articleId = scalar(reportArticle.input.value); + const reportIdValue = scalar(reportId.input.value); + const ledger = reportLedger.input.value; + if (!/^[1-9][0-9]*$/u.test(ledger)) throw new Error('invalid_input'); + return Object.freeze({ + articleId, + ledgerEpoch: positive(Number(ledger)), + reportId: reportIdValue, + }); + } + function checkedReport(value, selected) { + if ( + !object(value) || + value.articleId !== selected.articleId || + value.reportId !== selected.reportId || + value.ledgerEpoch !== selected.ledgerEpoch || + !['pending', 'confirmed', 'rejected'].includes(value.status) || + !object(value.report) || + typeof value.report.summary !== 'string' || + typeof value.report.details !== 'string' || + !object(value.evidence) || + !['passed', 'failed', 'inconclusive'].includes(value.evidence.result) + ) + throw invalid(); + positive(value.reportGeneration); + if ( + value.expectedReportGeneration !== value.reportGeneration || + typeof value.reviewBindingHash !== 'string' || + !/^[0-9a-f]{64}$/u.test(value.reviewBindingHash) + ) + throw invalid(); + const receipt = scalar(value.receipt); + const qualified = + value.status === 'confirmed' && + value.evidence.result === 'passed' && + object(value.confirmation); + return Object.freeze({ + ...selected, + expectedReportGeneration: value.expectedReportGeneration, + reviewBindingHash: value.reviewBindingHash, + receipt, + qualified, + display: JSON.stringify( + { + articleId: value.articleId, + ledgerEpoch: value.ledgerEpoch, + reportId: value.reportId, + reportGeneration: value.reportGeneration, + status: value.status, + result: value.evidence.result, + summary: value.report.summary, + details: value.report.details, + }, + null, + 2, + ), + }); + } + async function readReport() { + if (!ready || pending !== null || !testReceiptEnabled()) return; + let selected; + try { + selected = reportCoordinates(); + } catch { + notice('Complete the article, positive ledger epoch and report ID before reading.', true); + return; + } + const expected = session; + shownReport = null; + reportText.textContent = ''; + return operation(async (generation) => { + const actor = await viewer(generation, expected); + const value = await callRaw( + '/api/staff/knowledge/command', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ operation: 'reportRead', input: selected }), + }, + generation, + actor, + ); + const checked = checkedReport(value, selected); + await viewer(generation, actor); + current(generation); + if (!testReceiptEnabled()) { + notice('Test-report association is unavailable.', true); + return; + } + session = actor; + shownReport = checked; + reportText.textContent = checked.display; + notice( + checked.qualified + ? 'Confirmed passed report shown. Explicitly associate it with this ticket revision, resolution cycle and public solution.' + : 'This report cannot be associated. Use the existing Knowledge confirmation workflow for a confirmed passed report.', + ); + }); + } 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 }; + if (action === 'test-receipt') { + if (!canRecordEvidence() || !testReceiptEnabled() || shownReport?.qualified !== true) + throw new Error('not_ready'); + const selected = reportCoordinates(); + if (selected.articleId !== shownReport.articleId || + selected.ledgerEpoch !== shownReport.ledgerEpoch || + selected.reportId !== shownReport.reportId) + throw new Error('report_changed'); + value = { + expectedPrincipalId: context.actorSubject, + expectedRevision: context.revision, + resolutionCycle: source.resolutionCycle, + solutionMessageId: scalar(solution.input.value), + report: { + articleId: shownReport.articleId, + ledgerEpoch: shownReport.ledgerEpoch, + reportId: shownReport.reportId, + expectedReportGeneration: shownReport.expectedReportGeneration, + reviewBindingHash: shownReport.reviewBindingHash, + receipt: shownReport.receipt, + }, + }; + } else 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) }; + const common = { expectedRevision: context.revision, resolutionCycle: source.resolutionCycle, + solutionMessageId: scalar(solution.input.value) }; + if (evidenceKind.input.value === 'staff_verified_fix') + value = { ...common, verificationReference: scalar(verification.input.value) }; + else throw new Error('invalid_input'); } else if (action === 'approve' || action === 'reject') { if (shownBinding === null || !canReadWork()) throw new Error('not_ready'); try { path = options.stagedReviewsEnabled?.() === true ? 'review-queue' : 'review'; } @@ -376,11 +555,50 @@ const body = JSON.stringify({ commandId: id, ...value }); return Object.freeze({ subject: context.actorSubject, ticketId: context.ticketId, path: `${base()}/${path}`, body, commandId: id, + preparation: action === 'test-receipt', + preparationEvidence: action === 'test-receipt' ? Object.freeze({ expectedRevision: value.expectedRevision, + resolutionCycle: value.resolutionCycle, solutionMessageId: value.solutionMessageId }) : undefined, 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 checkedPreparation(candidate, result) { + const keys = ['actorId', 'ticketId', 'commandId', 'receipt', 'validUntil']; + if ( + !object(result) || + Object.keys(result).length !== keys.length || + !keys.every((key) => Object.prototype.hasOwnProperty.call(result, key)) || + result.actorId !== candidate.subject || + result.ticketId !== candidate.ticketId || + result.commandId !== candidate.commandId + ) + throw invalid(); + const receipt = scalar(result.receipt); + const stamp = scalar(result.validUntil, 40); + const parsed = Date.parse(stamp); + if (!Number.isFinite(parsed) || new Date(parsed).toISOString() !== stamp) throw invalid(); + return receipt; + } + function preparedPacket(candidate, receipt) { + const id = scalar(commandId()); + return Object.freeze({ + subject: candidate.subject, + ticketId: candidate.ticketId, + path: candidate.path.replace(/\/test-receipt$/u, '/evidence'), + body: JSON.stringify({ + commandId: id, + ...candidate.preparationEvidence, + kind: 'successful_test', + receipt, + }), + commandId: id, + review: false, + queued: false, + intake: 'evidence', + expectedRevision: candidate.preparationEvidence.expectedRevision, + }); + } function pendingChanged() { try { options.onPendingChange?.(pending !== null); } catch { /* The packet remains owned here. */ } } @@ -406,8 +624,23 @@ const path = candidate.review && action !== 'submit' ? candidate.path + (action === 'receipt' ? (candidate.queued ? '-status' : '-receipt') : '-cancel') : candidate.intake && action === 'recover' ? candidate.path + '-recovery' : candidate.path; + if (pendingAction === 'prepared') pendingAction = 'submit'; let result = await call(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: candidate.body }, generation, actor); + if (candidate.preparation === true) { + const receipt = checkedPreparation(candidate, result); + await viewer(generation, actor); + current(generation); + if (pending !== candidate) throw invalid(); + pending = preparedPacket(candidate, receipt); + pendingAction = 'prepared'; + session = actor; + ready = true; + privatePanel.hidden = false; + pendingChanged(); + notice('Report associated. Resolution evidence has not been recorded. Choose Record resolution evidence explicitly.'); + return; + } let cancelled = false; let superseded = false; if (candidate.intake && action === 'recover') { @@ -480,6 +713,8 @@ : 'Action acknowledged. Read the source again before another action.'); } async function mutate(action) { + if (action === 'evidence' && preparedEvidence() && !busy && ready) + return operation((generation) => send(pending, generation)); if (pending !== null || busy || !ready) return; let candidate; try { candidate = packet(action); } @@ -488,7 +723,7 @@ } async function retry() { if (pending === null || (pending.review !== true && !ready) || busy) return; - return operation((generation) => send(pending, generation, pending.intake ? 'recover' : 'submit')); + return operation((generation) => send(pending, generation, pending.intake && pendingAction !== 'prepared' ? 'recover' : 'submit')); } async function recoverReview(action) { if (pending?.review !== true || context === null || busy) return; diff --git a/public/staff-support-review-inbox.js b/public/staff-support-review-inbox.js new file mode 100644 index 0000000..a89dc19 --- /dev/null +++ b/public/staff-support-review-inbox.js @@ -0,0 +1,178 @@ +(function (global) { + 'use strict'; + const INBOX = '/api/support/admin/engineering/review-inbox'; + const scalar = (v, max = 200) => + typeof v === 'string' && + v.length > 0 && + v.length <= max && + v.trim().length > 0 && + !/[\u0000-\u001f\u007f-\u009f]/u.test(v); + function reviewPage(value) { + if ( + !value || + !Array.isArray(value.reviewSources) || + !Array.isArray(value.reviewCandidates) || + value.reviewSources.length + value.reviewCandidates.length > 10 || + !value.reviewSources.every((id) => scalar(id)) || + !value.reviewCandidates.every( + (item) => + item && + scalar(item.ticketId) && + Number.isSafeInteger(item.sourceGeneration) && + item.sourceGeneration > 0, + ) || + !Number.isSafeInteger(value.physicalRows) || + value.physicalRows < 0 || + value.pages !== 1 || + (value.nextCursor !== null && !scalar(value.nextCursor, 20000)) + ) + return null; + return value; + } + function createReviewInbox(options) { + const { host, request, session, capture, openTicket, denied } = options; + const doc = host.ownerDocument ?? document; + const create = (tag, text, key) => { + const node = doc.createElement(tag); + if (text !== undefined) node.textContent = text; + if (key) node.setAttribute('data-engineering-inbox', key); + return node; + }; + const heading = create('h3', 'Engineering review inbox'); + const status = create( + 'p', + 'Load one bounded page of sources and proposals needing staff review.', + 'status', + ); + status.setAttribute('role', 'status'); + const list = create('ul', undefined, 'list'); + const load = create('button', 'Load review inbox', 'load'); + const next = create('button', 'Next review page', 'next'); + for (const button of [load, next]) { + button.type = 'button'; + button.className = 'account-button'; + } + next.disabled = true; + host.replaceChildren(heading, status, list, load, next); + let epoch = 0; + let cursor; + let busy = false; + let retryAt = 0; + function clear() { + ++epoch; + cursor = undefined; + busy = false; + list.replaceChildren(); + next.disabled = true; + load.disabled = false; + status.textContent = + 'Load one bounded page of sources and proposals needing staff review.'; + } + async function scan(after) { + if (busy) return; + if (Date.now() < retryAt) { + status.textContent = 'Please wait before requesting another page.'; + return; + } + const observed = ++epoch; + const currentView = capture(); + const current = () => observed === epoch && currentView(); + if (!current()) return; + busy = true; + load.disabled = true; + next.disabled = true; + list.replaceChildren(); + cursor = undefined; + status.textContent = 'Loading review inbox...'; + try { + const before = await session(); + if (!current()) return; + if (!before?.accountId) + throw new Error('Current staff account is unavailable.'); + const query = new URLSearchParams({ limit: '10' }); + if (after !== undefined) query.set('cursor', after); + const response = await request(INBOX + '?' + query); + if (!current()) return; + if (response.status === 401 || response.status === 403) { + clear(); + denied(response.status); + return; + } + if (response.status === 429) { + const hint = + response.headers?.get?.('Retry-After') ?? + response.headers?.['retry-after']; + const seconds = + typeof hint === 'string' && /^\d+$/u.test(hint) ? Number(hint) : 30; + retryAt = Date.now() + Math.max(1, Math.min(seconds, 3600)) * 1000; + throw new Error('Please wait before requesting another page.'); + } + const page = + response.status === 200 ? reviewPage(response.body?.result) : null; + if (!page) throw new Error('Review inbox is unavailable.'); + const latest = await session(); + if (!current()) return; + if (latest?.accountId !== before.accountId) { + clear(); + denied(403); + return; + } + for (const item of [ + ...page.reviewSources.map((ticketId) => ({ + ticketId, + label: 'Source needs review', + })), + ...page.reviewCandidates.map((candidate) => ({ + ...candidate, + label: 'Proposal generation ' + candidate.sourceGeneration, + })), + ]) { + const row = create('li'); + const button = create( + 'button', + item.ticketId + ' · ' + item.label, + 'ticket', + ); + button.type = 'button'; + button.className = 'account-button account-button-quiet'; + button.addEventListener('click', () => { + if (current()) { + clear(); + openTicket(item.ticketId); + } + }); + row.append(button); + list.append(row); + } + cursor = page.nextCursor ?? undefined; + status.textContent = + page.reviewSources.length + page.reviewCandidates.length === 0 + ? 'No staff reviews on this page.' + : 'Open a ticket to inspect its current source and exact proposal.'; + } catch (error) { + if (current() && (error?.status === 401 || error?.status === 403)) { + clear(); + denied(error.status); + } else if (current()) + status.textContent = + error instanceof Error + ? error.message + : 'Review inbox is unavailable.'; + } finally { + if (current()) { + busy = false; + load.disabled = false; + next.disabled = cursor === undefined; + } + } + } + load.addEventListener('click', () => { + void scan(); + }); + next.addEventListener('click', () => { + if (cursor !== undefined) void scan(cursor); + }); + return { clear }; + } + global.PegmaSupportReviewInbox = { createReviewInbox }; +})(globalThis); diff --git a/public/staff-support-ticket.js b/public/staff-support-ticket.js index 608a034..eb5303b 100644 --- a/public/staff-support-ticket.js +++ b/public/staff-support-ticket.js @@ -21,6 +21,9 @@ const handoffStatus = select('#staff-handoff-status'); const handoffList = select('#staff-handoff-list'); const learningRoot = select('#staff-learning-panel'); const engineeringRoot = select('#staff-engineering-panel'); +const followupRoot = select('#staff-followup-panel'); +let followup = null; +let followupBusy = false; const engineeringRecovery = select('#staff-engineering-recovery'); const engineeringOwnerList = select('#staff-engineering-recovery-owners'); const engineeringRecoveryStatus = select('#staff-engineering-recovery-status'); @@ -77,6 +80,8 @@ function cancelRequests() { function beginOperation() { // Retain unknown intent, but retire every old panel context before an // ordinary mutation or current-ticket reload can await anything. + followup?.suspend(); + if (followupRoot !== null) followupRoot.hidden = true; learning?.suspend(); if (learningRoot !== null) learningRoot.hidden = true; engineeringPolicyRecovery = null; @@ -102,6 +107,8 @@ function clearHandoff() { handoffPanel.hidden = true; } function hideAll() { + followup?.suspend(); + if (followupRoot !== null) followupRoot.hidden = true; learning?.suspend(); if (learningRoot !== null) learningRoot.hidden = true; engineeringPolicyRecovery = null; @@ -156,8 +163,8 @@ function selectedComposeMode() { function updateControls() { composeForm.noValidate = ordinaryPacket !== null && ordinaryPacket.kind !== 'patch'; for (const link of signInLinks) { - link.node.target = ordinaryPacket === null && !learningPending() && !engineeringPending() ? link.target : '_blank'; - link.node.rel = ordinaryPacket === null && !learningPending() && !engineeringPending() ? link.rel : 'noopener noreferrer'; + link.node.target = ordinaryPacket === null && !learningPending() && !engineeringPending() && !followup?.hasPending() ? link.target : '_blank'; + link.node.rel = ordinaryPacket === null && !learningPending() && !engineeringPending() && !followup?.hasPending() ? link.rel : 'noopener noreferrer'; } const ticket = currentView?.ticket; const terminal = ticket?.status === 'resolved' || ticket?.status === 'closed'; @@ -245,7 +252,7 @@ function retryDeadline(value) { // A missing or malformed server hint never triggers a tight retry loop. return Date.now() + 30_000; } -async function api(path, init = {}) { +async function api(path, init = {}, includeStatus = false) { const headers = new Headers(init.headers); if (init.body !== undefined) headers.set('Content-Type', 'application/json'); if (csrfToken !== '') headers.set('X-Pegma-CSRF', csrfToken); @@ -279,14 +286,25 @@ async function api(path, init = {}) { cache: 'no-store', referrerPolicy: 'no-referrer', }); - if (!response.ok) + if (!response.ok) { + let code; + if (response.status === 410 || response.status === 429) { + try { + const failure = await response.json(); + if (typeof failure?.error === 'string' && failure.error.length <= 200) + code = failure.error; + } catch { /* Missing/malformed error data retains unknown-outcome handling. */ } + } throw Object.assign(new Error('request_failed'), { status: response.status, + ...(code === undefined ? {} : { code }), ...(response.status === 429 ? { retryAt: retryDeadline(response.headers.get('Retry-After')) } : {}), }); - return await response.json(); + } + const body = await response.json(); + return includeStatus ? { status: response.status, body } : body; })(), aborted, ]); @@ -337,9 +355,11 @@ function validateView(view) { ) throw Object.assign(new Error('invalid_response'), { status: 502 }); if ((view.engineeringEnabled !== undefined && typeof view.engineeringEnabled !== 'boolean') || + (view.releaseFollowupEnabled !== undefined && typeof view.releaseFollowupEnabled !== 'boolean') || (view.engineeringReviewEnabled !== undefined && typeof view.engineeringReviewEnabled !== 'boolean') || (view.learningReviewRecoveryEnabled !== undefined && typeof view.learningReviewRecoveryEnabled !== 'boolean') || (view.learningEnabled !== undefined && typeof view.learningEnabled !== 'boolean') || + (view.learningTestReceiptEnabled !== undefined && typeof view.learningTestReceiptEnabled !== 'boolean') || (view.learningStagedReviewEnabled !== undefined && typeof view.learningStagedReviewEnabled !== 'boolean')) throw Object.assign(new Error('invalid_response'), { status: 502 }); effectiveHandling(view.ticket); @@ -841,6 +861,7 @@ if (learningRoot !== null && typeof globalThis.PegmaSupportLearning?.createPanel learning = globalThis.PegmaSupportLearning.createPanel({ root: learningRoot, stagedReviewsEnabled: () => currentView?.learningStagedReviewEnabled === true, + testReceiptEnabled: () => currentView?.learningTestReceiptEnabled === true, request: (path, init) => learningRequest(() => api(path, init), learning.hasPendingReview?.() === true && /\/review(?:-receipt|-cancel|-queue(?:-status|-cancel)?)?$/u.test(path)), readSession: () => learningRequest(async () => { @@ -871,8 +892,9 @@ if (learningRoot !== null && typeof globalThis.PegmaSupportLearning?.createPanel function engineeringPending() { return engineeringOwnershipInvalid || engineeringOwners.length > 0; } +function followupOccupied() { return followupBusy || followup?.hasPending() === true; } function engineeringOccupied() { - return engineeringPending() || engineeringBusy || engineeringRequests > 0; + return followupOccupied() || engineeringPending() || engineeringBusy || engineeringRequests > 0; } function extensionOccupied() { return learningOccupied() || engineeringOccupied(); } function renderEngineeringRecovery() { @@ -896,7 +918,7 @@ function renderEngineeringRecovery() { function requireEngineeringAdmission() { const policyMode = engineeringPolicyRecovery !== null; if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || ordinaryAcknowledged || - learningOccupied() || suspended || authorityReloadRequired || viewer === null || + learningOccupied() || followupOccupied() || suspended || authorityReloadRequired || viewer === null || (!policyMode && (currentView?.engineeringEnabled !== true || !onThisTicket())) || (policyMode && viewer.subject !== engineeringPolicyRecovery.actorSubject)) throw Object.assign(new Error('engineering_suspended'), { stale: true }); @@ -909,6 +931,16 @@ async function engineeringRequest(run) { } async function syncExtensions(view) { const generation = readGeneration; + if (followup !== null) { + if (viewer !== null && isCurrent(generation) && currentView === view && view.releaseFollowupEnabled === true) + followup.showTicket({ ticketId: view.ticket.id, actorSubject: viewer.subject }); + else { + // Keep any unknown packet in its owner closure while deployment admission + // is absent. A later current enabled view can recover that same packet. + followup.suspend(); + if (followupRoot !== null) followupRoot.hidden = true; + } + } await syncLearning(view); if (!isCurrent(generation) || currentView !== view || engineering === null) return; if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || learningOccupied() || view.engineeringEnabled !== true) { @@ -952,7 +984,7 @@ if (engineeringRoot !== null && typeof globalThis.PegmaSupportEngineering?.creat isEnabled: () => engineeringPolicyRecovery !== null || currentView?.engineeringEnabled === true, isReviewEnabled: () => currentView?.engineeringReviewEnabled === true, canRequest: () => busy === null && ordinaryPacket === null && takeoverPacket === null && - !ordinaryAcknowledged && !learningOccupied() && !suspended && !authorityReloadRequired, + !ordinaryAcknowledged && !learningOccupied() && !followupOccupied() && !suspended && !authorityReloadRequired, request: (path, init) => engineeringRequest(() => api(path, init)), readSession: () => engineeringRequest(() => readViewer(readGeneration)), readCurrentTicket: (id) => engineeringRequest(async () => { @@ -979,8 +1011,51 @@ if (engineeringRoot !== null && typeof globalThis.PegmaSupportEngineering?.creat }); select('#staff-engineering-check-access')?.addEventListener('click', () => { void readEngineeringRecoveryAccount(); }); } +if (followupRoot !== null && typeof globalThis.PegmaSupportFollowup?.createPanel === 'function') { + function followupAdmission() { + if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || ordinaryAcknowledged || + learningOccupied() || engineeringPending() || engineeringBusy || engineeringRequests > 0 || + suspended || authorityReloadRequired || viewer === null || currentView?.releaseFollowupEnabled !== true || !onThisTicket()) + throw Object.assign(new Error('followup_suspended'), { stale: true }); + } + async function followupRequest(run) { + followupAdmission(); const generation = readGeneration; + const value = await run(); guard(generation); followupAdmission(); return value; + } + followup = globalThis.PegmaSupportFollowup.createPanel({ root: followupRoot, + canRequest: () => busy === null && ordinaryPacket === null && takeoverPacket === null && !ordinaryAcknowledged && + !learningOccupied() && !engineeringPending() && !engineeringBusy && engineeringRequests === 0 && + !suspended && !authorityReloadRequired && viewer !== null && currentView?.releaseFollowupEnabled === true && onThisTicket(), + request: (path, init) => followupRequest(() => api(path, init)), + requestWithStatus: (path, init) => + followupRequest(() => api(path, init, true)), + readSession: () => followupRequest(() => readViewer(readGeneration)), + readCurrentTicket: (id) => followupRequest(async () => { + if (id !== ticketId) throw Object.assign(new Error('wrong_ticket'), { stale: true }); + const generation = readGeneration; + const value = await api('/api/support/admin/tickets/' + encodeURIComponent(id)); guard(generation); validateView(value); + if (value.releaseFollowupEnabled !== true) { + // Retire cached admission without replacing the ticket facts the staff + // member has actually seen. Unknown command ownership remains intact. + currentView = { ...currentView, releaseFollowupEnabled: false }; + followup.suspend(); followupRoot.hidden = true; updateControls(); + throw Object.assign(new Error('followup_suspended'), { stale: true }); + } + return value; + }), + onPendingChange: () => updateControls(), + onBusyChange: (value) => { followupBusy = value === true; updateControls(); }, + onSettled: () => loadTicket(), + onAccessLost: ({ status }) => { + ++readGeneration; cancelRequests(); busy = null; viewer = null; csrfToken = ''; authorityReloadRequired = true; + hideAll(); signedOut.hidden = status !== 401; forbidden.hidden = status !== 403; + showStatus('Restore the original account in another tab, then reload this ticket to retry its exact follow-up command.', true); + updateControls(); + }, + }); +} window.addEventListener('beforeunload', (event) => { - if (!learningPending() && !engineeringPending() && ordinaryPacket === null && takeoverPacket === null) return; + if (!followup?.hasPending() && !learningPending() && !engineeringPending() && ordinaryPacket === null && takeoverPacket === null) return; event.preventDefault(); event.returnValue = ''; }); diff --git a/public/staff-support.js b/public/staff-support.js index f327915..3626e2b 100644 --- a/public/staff-support.js +++ b/public/staff-support.js @@ -7,6 +7,8 @@ const queueList = document.querySelector('#queue-list'); const filterForm = document.querySelector('#queue-filters'); let csrfToken = ''; +let viewerSubject = ''; +let reviewInbox = null; let queueGeneration = 0; let suspended = false; const requests = new Set(); @@ -19,6 +21,8 @@ function showStatus(message, isError = false) { function hideAll() { ++queueGeneration; + reviewInbox?.clear(); + viewerSubject = ''; signedOut.hidden = true; forbidden.hidden = true; panel.hidden = true; @@ -128,6 +132,9 @@ function renderQueue(items) { function filterQuery() { const form = new FormData(filterForm); const params = new URLSearchParams(); + const handling = form.get('handling'); + if (handling === 'assistant' || handling === 'all') + params.set('handling', handling); const status = form.get('status'); const sort = form.get('sort'); if (typeof status === 'string' && status !== '') { @@ -145,6 +152,8 @@ function filterQuery() { async function refreshQueue() { if (suspended) return false; const generation = ++queueGeneration; + reviewInbox?.clear(); + const handling = new FormData(filterForm).get('handling'); for (const controller of requests) controller.abort(); requests.clear(); let result; @@ -158,6 +167,14 @@ async function refreshQueue() { if (typeof result.csrfToken === 'string') { csrfToken = result.csrfToken; } + const heading = document.querySelector('#queue-heading'); + if (heading) + heading.textContent = + handling === 'assistant' + ? 'Assistant supervision' + : handling === 'all' + ? 'All support work' + : 'Human queue'; renderQueue(result.items); return true; } @@ -170,6 +187,7 @@ async function start() { const account = await api('/api/identity/account'); if (generation !== queueGeneration || suspended) return; csrfToken = account.csrfToken; + viewerSubject = account.account.subject; emailNode.textContent = account.account.email; } catch (error) { if (generation !== queueGeneration || suspended) return; @@ -228,6 +246,60 @@ filterForm.addEventListener('submit', async (event) => { } }); +const inboxRoot = document.querySelector('#engineering-review-inbox'); +if ( + inboxRoot && + typeof globalThis.PegmaSupportReviewInbox?.createReviewInbox === 'function' +) { + reviewInbox = globalThis.PegmaSupportReviewInbox.createReviewInbox({ + host: inboxRoot, + request: async (path) => { + try { + return { status: 200, body: await api(path) }; + } catch (error) { + if (error.status === 429) + return { + status: 429, + headers: { + 'retry-after': String( + Math.max(1, Math.ceil((error.retryAt - Date.now()) / 1000)), + ), + }, + }; + if (error.status) return { status: error.status }; + throw error; + } + }, + session: async () => { + const subject = viewerSubject; + if (!subject || suspended) return null; + const latest = await api('/api/identity/session'); + return latest.account?.subject === subject + ? { accountId: subject } + : null; + }, + capture: () => { + const generation = queueGeneration; + return () => + generation === queueGeneration && !suspended && !panel.hidden; + }, + openTicket: (id) => { + window.location.href = + '/staff/support/ticket/?id=' + encodeURIComponent(id); + }, + denied: (status) => { + hideAll(); + signedOut.hidden = status !== 401; + forbidden.hidden = status !== 403; + showStatus( + status === 401 + ? 'Sign in to use the staff queue.' + : 'You do not have staff access.', + status !== 401, + ); + }, + }); +} function invalidate() { suspended = true; for (const controller of requests) controller.abort(); diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index bff5279..382c786 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -16,7 +16,7 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 'A small Cloudflare Worker host for a fictional community library (Northshelf Branch) offers first-party accounts: passkey sign-in, email one-time codes for enrollment and recovery, server-side sessions, and durable rate limits on expensive auth paths. No passwords.', packages: [ '@pegma/identity@0.1.2', - '@pegma/sessions@0.2.1', + '@pegma/sessions@0.3.0', '@pegma/mail@0.1.1', '@pegma/rate-limit@0.2.0', '@pegma/authorization-identity@0.4.0', @@ -243,13 +243,13 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 'A fictional makerspace helpdesk (Bench Ticket) runs a small support-desk site with first-party email-code login (not Auth0, Entra, or passkeys-required), server-side sessions, mail to a catcher, and ticket create/list/reply. Environment runbooks one-shot it on Docker, Cloudflare D1, Azure Tables, and AWS DynamoDB once @pegma/storage-dynamodb is published.', packages: [ '@pegma/identity@0.1.2', - '@pegma/sessions@0.2.1', + '@pegma/sessions@0.3.0', '@pegma/mail@0.1.1', '@pegma/rate-limit@0.2.0', '@pegma/health@0.2.0', - '@pegma/support-desk-application@0.2.7', - '@pegma/support-desk-contracts@0.2.7', - '@pegma/support-desk-core@0.2.7', + '@pegma/support-desk-application@0.2.10', + '@pegma/support-desk-contracts@0.2.10', + '@pegma/support-desk-core@0.2.10', '@pegma/authorization-core@0.4.0', '@pegma/storage-core@0.4.0', '@pegma/spine@0.1.1', diff --git a/src/pages/feedback/ticket.astro b/src/pages/feedback/ticket.astro index 3dfcf6f..f8e9474 100644 --- a/src/pages/feedback/ticket.astro +++ b/src/pages/feedback/ticket.astro @@ -33,6 +33,7 @@ import Base from '../../layouts/Base.astro';

Human support

+