From e8aa2affcf222d7ca4c98f3d4cc743c8b771a8eb Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Thu, 12 Nov 2026 05:39:09 -0500 Subject: [PATCH 01/34] Compose staff-reviewed release follow-up with published Support 0.2.8 --- docs/KNOWLEDGE_COMPOSITION.md | 5 +- docs/SUPPORT_COMPOSITION.md | 10 +- docs/SUPPORT_ENGINEERING.md | 6 +- docs/SUPPORT_RELEASE_FOLLOWUP.md | 100 +++ package.json | 10 +- pnpm-lock.yaml | 58 +- public/staff-support-followup.js | 455 +++++++++++++ public/staff-support-ticket.js | 54 +- src/pages/staff/support/ticket.astro | 13 +- src/support-release-followup-ui.test.ts | 264 ++++++++ worker/src/index.ts | 25 +- worker/src/support-access.test.ts | 3 + worker/src/support-access.ts | 6 +- worker/src/support-api.ts | 5 + worker/src/support-desk.ts | 3 + worker/src/support-human-auth.ts | 8 + .../support-release-followup-composition.ts | 35 + .../src/support-release-followup-fixtures.ts | 501 ++++++++++++++ .../support-release-followup-guards.test.ts | 195 ++++++ .../src/support-release-followup-handlers.ts | 388 +++++++++++ worker/src/support-release-followup-ports.ts | 108 +++ worker/src/support-release-followup-usage.ts | 48 ++ .../src/support-release-followup.d1.test.ts | 524 +++++++++++++++ worker/src/support-release-followup.test.ts | 630 ++++++++++++++++++ worker/src/support-release-followup.ts | 311 +++++++++ 25 files changed, 3709 insertions(+), 56 deletions(-) create mode 100644 docs/SUPPORT_RELEASE_FOLLOWUP.md create mode 100644 public/staff-support-followup.js create mode 100644 src/support-release-followup-ui.test.ts create mode 100644 worker/src/support-release-followup-composition.ts create mode 100644 worker/src/support-release-followup-fixtures.ts create mode 100644 worker/src/support-release-followup-guards.test.ts create mode 100644 worker/src/support-release-followup-handlers.ts create mode 100644 worker/src/support-release-followup-ports.ts create mode 100644 worker/src/support-release-followup-usage.ts create mode 100644 worker/src/support-release-followup.d1.test.ts create mode 100644 worker/src/support-release-followup.test.ts create mode 100644 worker/src/support-release-followup.ts diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index a05a078..247d971 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -223,8 +223,9 @@ The [host policy](../worker/src/support-access.ts) keeps authority explicit: 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 + `pegma.dev-policy-7` retains them and adds 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 diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index 7b2800f..536b4f2 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -83,7 +83,7 @@ unified host policy's `defaults` (no paid entitlement): - `support.ticket.reply.own` - `support.ticket.request_person.own` -Policy version: `pegma.dev-policy-6` — one `PolicyDocumentV1` for the whole +Policy version: `pegma.dev-policy-7` — one `PolicyDocumentV1` for the whole host, schema-validated in tests (see `docs/ROLE_ADOPTION_PLAN.md`). ### Staff (stored `Support` role) @@ -315,8 +315,8 @@ 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`. Current policy `pegma.dev-policy-7` retains those grants and adds +human engineering and release-follow-up permissions; 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 @@ -446,7 +446,9 @@ 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. Current policy version 7 retains them and adds the separate +[release-follow-up controls](SUPPORT_RELEASE_FOLLOWUP.md). 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..cf79d62 100644 --- a/docs/SUPPORT_ENGINEERING.md +++ b/docs/SUPPORT_ENGINEERING.md @@ -15,10 +15,14 @@ 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: +`pegma.dev-policy-7`, retains these five human engineering permissions: | Published `supportPermissions` member | Current human surface | | --- | --- | diff --git a/docs/SUPPORT_RELEASE_FOLLOWUP.md b/docs/SUPPORT_RELEASE_FOLLOWUP.md new file mode 100644 index 0000000..a114f90 --- /dev/null +++ b/docs/SUPPORT_RELEASE_FOLLOWUP.md @@ -0,0 +1,100 @@ +# Staff release-follow-up controls + +This source slice connects optional Support SDK follow-up methods to the +registered Worker and staff ticket panel. The default Worker supplies no trusted +follow-up composition. Its routes return 404 before opening the database. It +adds no scheduled trigger, automatic notification, remote issue mutation or KB +publication. + +This isolated source selects all five qualified public Support 0.2.8 packages +and all four public KB 0.1.6 packages. The follow-up mutations pass the original +browser's fresh authority and synchronous closing assertion through the released +late-guard options. The [0.2.8 publication receipt](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.8) +binds the registry packages and their signature, provenance and clean-consumer +qualification. + +The trusted composition remains absent from the default Worker. Current public +graph Node and physical invocation results are recorded separately from earlier +private development runs. Reconciliation onto the current host branch, complete +normal gates and the unchanged 50-query/100-parameter Native profile remain +pending. Live deployment, provider, CPU and Workers Free acceptance remain open. + +## 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. + +Policy version 7 gives the stored Support role engineeringFollowupRead, +engineeringFollowupReview and engineeringFollowupEvidenceSubmit, alongside its +existing queue and reply authority. Admin or Knowledge alone receives no +follow-up authority. Processing uses a separate current service principal. +Work hints contain no saved browser credentials or AccessContext. + +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. Each mutation reaches the SDK's late +current-authority guard and synchronous closing fence. 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. Mutation responses contain result, commandId, +operation and the current csrfToken. 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. + +## Evidence and remaining integration + +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. + +Reopened issues, rollback heads, withdrawn sources and stale proof hold new +updates. 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 test is +worker/src/support-release-followup.d1.test.ts under vitest.d1.config.ts. +It meters the entire cold Worker.fetch invocation, including authentication, +quotas, SDK work and closing checks, with unchanged 50-query/100-parameter guards. diff --git a/package.json b/package.json index d7c367e..462c8cf 100644 --- a/package.json +++ b/package.json @@ -46,11 +46,11 @@ "@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.8", + "@pegma/support-desk-application": "0.2.8", + "@pegma/support-desk-contracts": "0.2.8", + "@pegma/support-desk-core": "0.2.8", + "@pegma/support-desk-templates": "0.2.8", "@pegma/webhooks": "0.1.1", "agents": "^0.20.1", "gpt-tokenizer": "4.1.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 43040aa..8c86855 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,20 +81,20 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.8 + version: 0.2.8 '@pegma/support-desk-application': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.8 + version: 0.2.8 '@pegma/support-desk-contracts': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.8 + version: 0.2.8 '@pegma/support-desk-core': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.8 + version: 0.2.8 '@pegma/support-desk-templates': - specifier: 0.2.7 - version: 0.2.7 + specifier: 0.2.8 + version: 0.2.8 '@pegma/webhooks': specifier: 0.1.1 version: 0.1.1 @@ -1242,24 +1242,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.8': + resolution: {integrity: sha512-+J/rMRzzSx6IWrZTZPi4Zvc9nAxA2RCd1hQkhne2xq0KfiNjH4qcLt2HD9J+wZaRAPOO9HBq2w7qrIN0E9QBNg==} engines: {node: '>=22'} - '@pegma/support-desk-application@0.2.7': - resolution: {integrity: sha512-t0asEJYY7Xmndz1GTp/7j5RUVzXYIs0a8uZ+hRUq5fwgPmqfMoPVJ9xSA7xPhbhDtZUq3B2tRD4tG91Fn6XA0g==} + '@pegma/support-desk-application@0.2.8': + resolution: {integrity: sha512-E9TStaMlvFcug5Eyp4LUiyO+DjG3FF+2ItSe5hk7aJk96yQ6SlAo7784+7J/GPok4d5aTTD0xL2YImxBEufzKw==} engines: {node: '>=22'} - '@pegma/support-desk-contracts@0.2.7': - resolution: {integrity: sha512-/9Zz473fyItEjJWLEzyXBzIR2poCqhvsqwdxU1yQOchy2++E9fdj/ErklGmea4VouUdnouhx2mRpIJJ0+gn+0A==} + '@pegma/support-desk-contracts@0.2.8': + resolution: {integrity: sha512-WxXGlEWr0GxE32O3DNkXIgF9SODMOmt8+PlA4j3isddQHnMEFihwA+w9OW6nR20vcyolv9fothxwg02CKdorjg==} engines: {node: '>=22'} - '@pegma/support-desk-core@0.2.7': - resolution: {integrity: sha512-3+8e2ZS1J2om0ePn2ioQ1wpqdY5f9NA6svEPl4RPVpmCdXwwiJxLbocLHtjcGJNbW37MnyOZKY97X5jdrMXSAw==} + '@pegma/support-desk-core@0.2.8': + resolution: {integrity: sha512-vYApKfk+JvEHjs3z8zvJyvG70+81sleb5Az4Cs07AOa+3C6FFJqrxt4qBAsE9oIQQOKQyC951P6up0zKg/VhOg==} engines: {node: '>=22'} - '@pegma/support-desk-templates@0.2.7': - resolution: {integrity: sha512-4mDF2e4ZzYjSlIQYu4FWpjr1cUUU2N7jJUfGTTMnYG6Gf5UN45j7q7ueOFJjlcgC7D0+TqKludaKDYZf0nqTjg==} + '@pegma/support-desk-templates@0.2.8': + resolution: {integrity: sha512-gmvmY5kThZIDnWiO2zs0GjIn+8RU7R6RBk9Hk3dNjEh6hpRGGIgNQUJGqJkeOxHDlEnJT4XfUhhoKfa9c6hrjA==} engines: {node: '>=22'} '@pegma/webhooks@0.1.1': @@ -4266,33 +4266,33 @@ snapshots: '@pegma/storage-core@0.4.0': {} - '@pegma/support-desk-ai@0.2.7': + '@pegma/support-desk-ai@0.2.8': dependencies: '@pegma/authorization-core': 0.4.0 '@pegma/knowledge-base-application': 0.1.6 '@pegma/knowledge-base-contracts': 0.1.6 '@pegma/spine': 0.1.2 - '@pegma/support-desk-application': 0.2.7 + '@pegma/support-desk-application': 0.2.8 - '@pegma/support-desk-application@0.2.7': + '@pegma/support-desk-application@0.2.8': 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.8 + '@pegma/support-desk-core': 0.2.8 - '@pegma/support-desk-contracts@0.2.7': + '@pegma/support-desk-contracts@0.2.8': dependencies: '@pegma/spine': 0.1.2 - '@pegma/support-desk-core@0.2.7': + '@pegma/support-desk-core@0.2.8': dependencies: - '@pegma/support-desk-contracts': 0.2.7 + '@pegma/support-desk-contracts': 0.2.8 - '@pegma/support-desk-templates@0.2.7': {} + '@pegma/support-desk-templates@0.2.8': {} '@pegma/webhooks@0.1.1': dependencies: diff --git a/public/staff-support-followup.js b/public/staff-support-followup.js new file mode 100644 index 0000000..52a12a5 --- /dev/null +++ b/public/staff-support-followup.js @@ -0,0 +1,455 @@ +(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 epoch = 0; + let busy = false; + let retryAt = 0; + let timer = null; + let cursor = null; + const now = options.now ?? Date.now; + const commandId = options.commandId ?? (() => global.crypto.randomUUID()); + const create = (tag, text) => { + const node = document.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 reason = create('input'); + reason.dataset.followupField = 'reason'; + reason.setAttribute('aria-label', 'Staff hold or rejection reason'); + const content = create('textarea'); + 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('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('exact-retry', 'Retry the exact previous 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, + 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 || + (action === 'exact-retry' ? !owns : owner !== 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, + ]) + 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 clearPrivate() { + work = null; + privateView.textContent = ''; + content.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 ack(value, packet) { + 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 === '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 && + (action !== 'exact-retry' || + owner.actorSubject !== selected.actorSubject || + owner.ticketId !== selected.ticketId) + ) + return; + busy = true; + options.onBusyChange?.(true); + render(); + try { + const session = await authority(token, selected); + 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; + 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 === '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, + }); + notify(); + } + const packet = owner; + const value = await request(path(selected, packet.operation), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Pegma-CSRF': session.csrfToken, + }, + body: packet.body, + }); + ensure(token, selected); + const closing = await readSession(); + ensure(token, selected); + if ( + !sameSession(session, closing) || + value?.csrfToken !== closing.csrfToken || + !ack(value, packet) + ) + throw new Error('unconfirmed_exact_command'); + owner = null; + notify(); + clearPrivate(); + status.textContent = + 'The exact command was acknowledged. Reloading current ticket state.'; + await options.onSettled?.(); + } catch (error) { + if (epoch !== token) return; + if (error.local === true && owner === null) { + status.textContent = error.message; + return; + } + clearPrivate(); + if (error.status === 429) + retryAt = Math.max(retryAt, error.retryAt ?? now() + 30_000); + status.textContent = + owner === null + ? 'Follow-up is unavailable. Check current access and retry the read.' + : '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.' + : '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-ticket.js b/public/staff-support-ticket.js index 608a034..1e33458 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 = !followup?.hasPending(); 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 = !followup?.hasPending(); 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'; @@ -871,8 +878,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 +904,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 +917,8 @@ async function engineeringRequest(run) { } async function syncExtensions(view) { const generation = readGeneration; + if (followup !== null && viewer !== null && isCurrent(generation)) + followup.showTicket({ ticketId: view.ticket.id, actorSubject: viewer.subject }); await syncLearning(view); if (!isCurrent(generation) || currentView !== view || engineering === null) return; if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || learningOccupied() || view.engineeringEnabled !== true) { @@ -952,7 +962,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 +989,40 @@ 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 === null || !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 !== null && onThisTicket(), + request: (path, init) => followupRequest(() => api(path, init)), + readSession: () => followupRequest(() => readViewer(readGeneration)), + readCurrentTicket: (id) => followupRequest(async () => { + if (id !== ticketId) throw Object.assign(new Error('wrong_ticket'), { stale: true }); + const value = await api('/api/support/admin/tickets/' + encodeURIComponent(id)); validateView(value); 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/src/pages/staff/support/ticket.astro b/src/pages/staff/support/ticket.astro index f1d2774..553e5fc 100644 --- a/src/pages/staff/support/ticket.astro +++ b/src/pages/staff/support/ticket.astro @@ -137,6 +137,9 @@ import Base from '../../../layouts/Base.astro'; + + +