From 53f2f1f961f48e4cf34bf1d68bac1bf10549d5f4 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 10:51:51 -0500 Subject: [PATCH 1/7] Add optional human engineering intake and review controls --- docs/SUPPORT_COMPOSITION.md | 26 +- docs/SUPPORT_ENGINEERING.md | 212 ++++++ public/staff-support-engineering.js | 511 ++++++++++++++ public/staff-support-ticket.js | 163 ++++- src/pages/staff/support/ticket.astro | 9 + src/support-engineering-controller.test.ts | 172 +++++ src/support-engineering-integration.test.ts | 235 +++++++ ...upport-engineering-policy-recovery.test.ts | 87 +++ src/support-engineering-review.test.ts | 172 +++++ src/support-engineering-ui.test.ts | 136 ++++ worker/src/api-auth.ts | 10 +- worker/src/api-json-limits.test.ts | 61 ++ worker/src/index.ts | 42 +- worker/src/support-access.test.ts | 13 +- worker/src/support-access.ts | 10 +- worker/src/support-api.ts | 23 +- worker/src/support-desk.ts | 3 + .../support-engineering-composition.test.ts | 87 +++ worker/src/support-engineering-composition.ts | 46 ++ worker/src/support-engineering-fixtures.ts | 342 ++++++++++ .../src/support-engineering-handlers.test.ts | 623 ++++++++++++++++++ worker/src/support-engineering-handlers.ts | 402 +++++++++++ .../src/support-engineering-http-fixtures.ts | 167 +++++ .../src/support-engineering-http.d1.test.ts | 319 +++++++++ worker/src/support-engineering-ports.ts | 42 ++ worker/src/support-engineering-review.test.ts | 226 +++++++ worker/src/support-engineering-review.ts | 71 ++ worker/src/support-engineering-router.test.ts | 168 +++++ worker/src/support-engineering-router.ts | 52 ++ worker/src/support-engineering.d1.test.ts | 89 +++ worker/src/support-engineering.test.ts | 524 +++++++++++++++ worker/src/support-engineering.ts | 267 ++++++++ worker/src/support-learning-http.d1.test.ts | 66 +- 33 files changed, 5343 insertions(+), 33 deletions(-) create mode 100644 docs/SUPPORT_ENGINEERING.md create mode 100644 public/staff-support-engineering.js create mode 100644 src/support-engineering-controller.test.ts create mode 100644 src/support-engineering-integration.test.ts create mode 100644 src/support-engineering-policy-recovery.test.ts create mode 100644 src/support-engineering-review.test.ts create mode 100644 src/support-engineering-ui.test.ts create mode 100644 worker/src/api-json-limits.test.ts create mode 100644 worker/src/support-engineering-composition.test.ts create mode 100644 worker/src/support-engineering-composition.ts create mode 100644 worker/src/support-engineering-fixtures.ts create mode 100644 worker/src/support-engineering-handlers.test.ts create mode 100644 worker/src/support-engineering-handlers.ts create mode 100644 worker/src/support-engineering-http-fixtures.ts create mode 100644 worker/src/support-engineering-http.d1.test.ts create mode 100644 worker/src/support-engineering-ports.ts create mode 100644 worker/src/support-engineering-review.test.ts create mode 100644 worker/src/support-engineering-review.ts create mode 100644 worker/src/support-engineering-router.test.ts create mode 100644 worker/src/support-engineering-router.ts create mode 100644 worker/src/support-engineering.d1.test.ts create mode 100644 worker/src/support-engineering.test.ts create mode 100644 worker/src/support-engineering.ts diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index 704cdf5..d51bd88 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -78,7 +78,7 @@ unified host policy's `defaults` (no paid entitlement): - `support.ticket.reply.own` - `support.ticket.request_person.own` -Policy version: `pegma.dev-policy-5` — one `PolicyDocumentV1` for the whole +Policy version: `pegma.dev-policy-6` — one `PolicyDocumentV1` for the whole host, schema-validated in tests (see `docs/ROLE_ADOPTION_PLAN.md`). ### Staff (stored `Support` role) @@ -404,3 +404,27 @@ store probe runs only when `SUPPORT_HEALTH_PROBE` is exactly `"true"`. documented further before accepting production-sensitive data at scale. Built in the open by RetireGolden, LLC. + + +## Optional engineering human composition + +The [engineering assembly](SUPPORT_ENGINEERING.md) uses policy version 6. +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. + +The Worker accepts a trusted optional engineering composition. Its current +enabled callback and dependency bundle gate the router and staff-detail hints. +Human review has an additional strict current flag. The default Worker passes +no engineering configuration, leaving intake, review and processing OFF. + +A configured staged-learning factory receives the same optional composition +as its third `create` argument. It composes `composeSupportEngineeringHuman` +into its existing `createSupportApi` call so current staff-detail hints and +its learning queue use their actual shared runtime. Engineering namespaces +also pass through the request-local root assembly before legacy routes. + +Both engineering review entry points pass fresh host authority through the +public coordinator's `verifyBeforeCommit` option. The SDK returns its final +synchronous proof assertion to the Application commit boundary. Exact retained +review commands recover accepted receipts before mutable proof reads. diff --git a/docs/SUPPORT_ENGINEERING.md b/docs/SUPPORT_ENGINEERING.md new file mode 100644 index 0000000..925885a --- /dev/null +++ b/docs/SUPPORT_ENGINEERING.md @@ -0,0 +1,212 @@ +# Support engineering intake and repository policy + +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. + +The [runtime](../worker/src/support-engineering.ts), +[HTTP adapter](../worker/src/support-engineering-handlers.ts), +[router](../worker/src/support-engineering-router.ts) and +[panel](../public/staff-support-engineering.js) reuse the host's existing +Support application, Identity, sessions, stored roles and durable limiter. +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. + +## Authority and defaults + +The [stored-role policy](../worker/src/support-access.ts), +`pegma.dev-policy-6`, gives Support these five additional human permissions: + +| Published `supportPermissions` member | Current human surface | +| --- | --- | +| `engineeringRead` | Source and bounded work metadata | +| `engineeringEvidenceSubmit` | Explicit enrollment and staff-verified failure evidence | +| `engineeringReview` | Repository selection and exact proposal approval or rejection | +| `engineeringWithdraw` | Withdrawal and evidence/product/check-policy invalidation | +| `engineeringPolicyRead` | Current repository policy metadata | + +All HTTP operations also require current Support queue-read authority. Admin +adds `engineeringPolicyRead` and `engineeringPolicyManage`; it does not imply +Support or queue-read. Policy HTTP operations require **Admin + Support**. +Neither role gains processing, reconciliation, restricted-source read, security +review or issue-dispatch authority from these additions. Knowledge and customer +permissions do not establish Support authority. Local-agent delegation remains +exactly KB draft-read, draft-write and evidence-submit; there is no new engineering +scope. + +The router requires both a configured dependency bundle and a current strict +`true` callback. Missing, false or throwing flags return an owned 404 before any +legacy Support route; unknown engineering subpaths cannot fall through. Direct +adapter calls report disabled operation as 503. These are different boundaries, +not signals that a source is absent. See the +[router tests](../worker/src/support-engineering-router.test.ts). + +Human intake and policy controls must remain independent of model-processing +readiness. The runtime's `processingEnabled` gate stops worker processing; it +must not be substituted for a configured human withdrawal or policy-disable +surface. Missing purpose ports remain unavailable. The existing +[Support factory](../worker/src/support-desk.ts) accepts optional engineering +application options without changing its absent-option defaults. The +[runtime tests](../worker/src/support-engineering.test.ts) exercise these +separations through the actual SDK. + +## Browser HTTP operations + +Let **T** be `/api/support/admin/tickets/:ticketId/engineering` and **P** be +`/api/support/admin/engineering/policy`. The optional router owns these paths before legacy Support commands. + +| Method/path | Closed request body or query | +| --- | --- | +| `GET T` | No body/query | +| `GET T/work` | Exactly `sourceGeneration=N`, canonical positive safe integer | +| `GET T/proposal` | Exactly `sourceGeneration=N`, canonical positive safe integer | +| `POST T/review` | Only `intent`, the complete actor-bound SDK command | +| `POST T/enroll` | `commandId`, `expectedRevision` | +| `POST T/evidence` | `commandId`, `expectedRevision`, `expectedBehavior`, `actualBehavior`, `reproductionSteps`, `visibleMessageIds`, `verificationReference`, `security` | +| `POST T/repository` | `commandId`, `sourceGeneration`, `expectedWorkGeneration`, `repositoryKey`, `policyGeneration`, `policyHash`, `reason` | +| `POST T/withdraw` | `commandId`, `reason` | +| `POST T/invalidate` | `commandId`, `reason` | +| `GET P` | No body/query | +| `POST P/prepare` | `commandId`, `expectedGeneration`, `enabled`, `repositoryKeys` | +| `POST P` | Only `intent`, the complete server-prepared snapshot | +| `POST P/disable` | `commandId`, `expectedGeneration` | + +These use the existing authenticated browser session, same-origin protections +and current `X-Pegma-CSRF`; bearer and agent credentials do not substitute. +Success is `{result, csrfToken}` with no-store responses. Current Identity, +session, stored roles and original request-header bindings are checked across +awaits and before responses. A closing denial can withhold an ACK after a real +SDK commit; it does not undo that commit. Errors expose bounded codes, not private +proof or raw dependency messages. Honor `Retry-After`. + +Ordinary bodies, including preparation, use the existing **64 KiB / 10-second** +reader. Only full policy submission uses **128 KiB / 10 seconds**; its prepared +response is also bounded. Scalar command IDs remain case-preserved and bounded +to 200 characters; repository keys to 100, with at most 20 configured entries. +Expected/actual behavior are each at most 2,000 characters. Evidence requires +1–16 reproduction steps of at most 1,000 characters each and 1–16 unique actual +customer-visible message IDs. Validate the complete UTF-8 packet, not just each +field. The [HTTP tests](../worker/src/support-engineering-handlers.test.ts) +include a genuine legal multibyte full intent above 64 KiB. + +Withdrawal reasons are `privacy_withdrawal`, `source_access_revoked` and +`source_deleted`; invalidation reasons are `evidence_revoked`, +`product_binding_revoked` and `check_policy_revoked`. + +Source and work results contain bounded operational metadata. The separate +proposal read projects the complete checked outbound request for explicit human +inspection. Review uses a retained full command with its exact actor, ticket, +source and work generations, proposal hash, decision and command identity. +The current SDK receipt lookup precedes mutable export proofs. Exact accepted +replay therefore survives source withdrawal or unavailable repository facts. + +The runtime passes its fresh staff check and original-browser callback through +the public coordinator's `verifyBeforeCommit` option. The coordinator retains +the final synchronous proof assertion for the Application transaction boundary. +Both approval and rejection require this current-human guard. New approval also +requires the configured read-only routing, checks and repository proof ports. +The independent review switch defaults OFF. + +An unresolved engineering review retains its original full command. The public +SDK exposes receipt-first replay through `reviewProposal`. A never-accepted +stale command remains held until an authoritative resolution is available. +Current reads and transport errors preserve that unknown owner. + +## Generation zero and verified failure evidence + +An initial source can be `sourceGeneration:0`, `state:unverified`, +`security:uncertain`. Ordinary Support can receive 403 for that source because it +has no restricted-read grant. Neither 403 nor 404 establishes absence, +ordinary sensitivity or evidence eligibility. + +The panel requires an explicit known enrollment ACK, then a **new same-actor +staff-ticket read started after that ACK**, before permitting initial evidence +when the source remains protected. Evidence uses that current ticket revision +and explicitly selected existing public messages. It does not require generation +1 before the evidence that creates it. Unknown enrollment cannot admit another +intent. This exact source-zero/403 path runs through real browser authority and +the actual SDK in the +[browser integration tests](../src/support-engineering-integration.test.ts). + +Staff evidence is `staff_verified_failure`: expected and observed behavior, +reproduction steps, public message references and a verification reference. +Sensitivity must be explicitly `ordinary`, `restricted` or `uncertain`, with no +ordinary default. The server supplies authenticated actor/time and independently +trusted product context; a typed verification reference is not a trusted automated +test receipt. Missing product proof can hold the source without creating work. +Restricted/uncertain evidence does not become ordinary through a Support-only +form. Internal notes are not public message choices. See the +[HTTP fixture](../worker/src/support-engineering-http-fixtures.ts) and +[panel tests](../src/support-engineering-ui.test.ts). + +## Immutable policy intent and recovery + +Policy GET distinguishes saved mapped entries, `unmappedRepositoryCount` and the +full configured `catalog`, including unselected entries. Empty catalog does not +mean empty saved policy. Show unmapped saved rows, block ordinary replacement +rather than silently dropping them, and retain explicit authorized disable. + +Preparation returns an opaque version-1 intent containing `actorId`, exact +`commandId`, `expectedGeneration`, ordered `repositoryKeys` and the complete +ordered policy descriptors. Preparation does not write a policy. Retain that +full JSON unchanged and submit only `{intent}`; it is not a token or permission. +Keep it out of DOM, URLs, logs and browser storage. Do not reconstruct it from a +later catalog. Current Admin + Support and browser authority are still required +on every preparation, submission and replay. + +At the expected current head, the adapter compares the prepared snapshot with +current trusted configuration. A future generation is rejected. At a newer +**monotonic SDK head**, the exact retained command can reach receipt-first +replay before the stale expected-generation CAS: changed descriptors or removed +keys cannot strand an already committed ACK. Missing/pruned receipts cannot +create a new commit under that stale generation. Do not reset/reuse policy +heads or edit SDK policy rows outside supported operations. Complete normalized +intent bytes, including wrapper keys and ordering, bind the server-derived +correlation identity. Altering a snapshot while reusing an ID is a conflict, +not a corrected retry. + +The [actual HTTP policy cases](../worker/src/support-engineering-handlers.test.ts) +cover changed/removed catalogs, altered wrappers, future heads, missing/pruned +receipts, current-role revocation and CAS races. Repository keys only select +immutable server-configured descriptors; never rebind an existing key to a +different repository. A saved descriptor or enabled policy does not prove +installation access, current remote visibility/metadata, routing calibration, +independent checks or publication authority. Those remain later SDK gates. + +For any sent mutation, preserve the original actor, domain/ticket, method, +route, complete packet and command identity. A timeout, malformed ACK or +postcommit denial remains uncertain. No successful GET or apparent state change +acknowledges an unknown write. Explicit retries reuse the exact packet and ID +with current browser authority; never blindly mint a replacement. Once a bound +ACK is known, recovery becomes matching fresh reads only, not another mutation. + +The standalone panel keeps separate pending owners for ticket and policy +operations. Its `pendingOwners()` callback inventory is the recovery authority; +a selected ticket must never replace another ticket's retained owner. Access, +feature loss and view changes clear private presentation while preserving those +owners for their original account. Full-page unload loses in-memory packets. +The controller keeps one panel lifecycle and offers sign-in in another tab. +Its retained-owner controls preserve the original account and ticket coordinates. +Global repository-policy recovery uses current account authority independently +of ticket selection. + +## Qualification and configuration + +The earlier standalone source checkpoint passed its 1,142-test suite with +1,066 Node cases, 74 Native D1 cases and two benchmark cases. Its five focused +engineering HTTP scenarios passed the 50-binding-call and 100-parameter test +ceilings. Those results describe the earlier standalone assembly. + +The combined current-parent root, controller and review changes require fresh +format, types, full Node 22 and 24 tests, build and current-head CI and review. +Actual registered-route Native D1 measurements must cover intake, policy, +proposal, review, recovery and late current-authority denial. The measurements +include the real Identity, sessions, role checks and durable limiter. + +Trusted configuration supplies product/build evidence, the immutable repository +catalog and current read-only review proof ports. Processing and export require +separate provider, usage, calibration, independent checks and GitHub connector +qualification. The human composition keeps processing OFF. Customer AI and +provider activation remain OFF while their own operational gates are pending. diff --git a/public/staff-support-engineering.js b/public/staff-support-engineering.js new file mode 100644 index 0000000..2773ec6 --- /dev/null +++ b/public/staff-support-engineering.js @@ -0,0 +1,511 @@ +/* Optional engineering intake and repository-policy panel. The host injects its + * existing bounded authenticated request/session/current-ticket readers. This + * module registers no route, job, provider, permission or persistent cache. */ +(function () { + const policyPath = '/api/support/admin/engineering/policy'; + const states = ['unverified', 'eligible', 'held', 'restricted', 'withdrawn']; + const securityValues = ['ordinary', 'restricted', 'uncertain']; + const withdrawals = ['privacy_withdrawal', 'source_access_revoked', 'source_deleted']; + const invalidations = ['evidence_revoked', 'product_binding_revoked', 'check_policy_revoked']; + const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); + const invalid = () => Object.assign(new Error('invalid_response'), { status: 502 }); + function text(value, maximum = 200, multiline = false) { + if (typeof value !== 'string' || value.trim().length === 0 || value.length > maximum || + (multiline ? /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u : /[\u0000-\u001f\u007f-\u009f]/u).test(value)) + throw new Error('invalid_input'); + return value; + } + function counter(value, minimum = 0) { + if (!Number.isSafeInteger(value) || value < minimum) throw invalid(); + return value; + } + function hash(value) { + if (typeof value !== 'string' || !/^[0-9a-f]{64}$/u.test(value)) throw invalid(); + return value; + } + function copy(value) { return JSON.parse(JSON.stringify(value)); } + /** + * request(path, init) returns the existing {result, csrfToken} envelope. + * readSession() returns current {subject, csrfToken}; readCurrentTicket(id) + * returns the actual current staff {ticket, messages, csrfToken} view. + * Those host readers remain bounded and enforce original browser authority. + * isEnabled defaults OFF; canRequest may narrow current controller admission. + * onPendingChange receives body-free owner coordinates, never command data. + * The host calls suspend before changing/hiding the ticket or losing access. + */ + function createPanel(options) { + const { root, request, readSession, readCurrentTicket } = options; + if (!root || [request, readSession, readCurrentTicket].some((fn) => typeof fn !== 'function')) + throw new TypeError('Engineering panel requires existing host authority readers.'); + const document = options.document ?? globalThis.document; + const now = options.now ?? (() => Date.now()); + const nextId = options.commandId ?? (() => crypto.randomUUID()); + const pending = new Map(); + const enrolled = new Map(); + let epoch = 0, context = null, session = null, ticket = null, source = null, work = null, policy = null, proposal = null; + let busy = false, preparedPolicy = null, retryAt = 0; + const controllers = new Set(); + const inputs = []; + const buttons = []; + const node = (tag, value) => { + const result = document.createElement(tag); + if (value !== undefined) result.textContent = value; + return result; + }; + const button = (key, label, run) => { + const result = node('button', label); result.type = 'button'; result.dataset.engineeringAction = key; + result.addEventListener('click', () => { void run(); }); buttons.push(result); return result; + }; + const field = (key, label, maximum, multiline = false) => { + const wrapper = node('label', label + ' '); const result = node(multiline ? 'textarea' : 'input'); + result.dataset.engineeringField = key; result.maxLength = maximum; result.autocomplete = 'off'; + if (!multiline) result.type = 'text'; wrapper.append(result); inputs.push(result); return { wrapper, input: result }; + }; + const select = (key, label, values) => { + const wrapper = node('label', label + ' '); const result = node('select'); result.dataset.engineeringField = key; + for (const [value, caption] of values) { const item = node('option', caption); item.value = value; result.append(item); } + result.value = values[0]?.[0] ?? ''; wrapper.append(result); inputs.push(result); return { wrapper, input: result }; + }; + const status = node('p', 'Engineering tools are not loaded.'); status.role = 'status'; status.ariaLive = 'polite'; + const sourceText = node('pre'); sourceText.className = 'support-message-body'; + const workText = node('pre'); workText.className = 'support-message-body'; + const proposalText = node('pre'); proposalText.className = 'support-message-body'; + const messageChoices = node('section'); const repository = select('repository', 'Repository key', [['', 'Select a configured repository']]); + const expected = field('expected', 'Expected behavior', 2000, true); + const actual = field('actual', 'Actual behavior', 2000, true); + const steps = field('steps', 'Reproduction steps (one per line)', 16016, true); + const reference = field('verification', 'Staff verification reference', 200); + const sensitivity = select('security', 'Sensitivity (choose explicitly)', [['', 'Choose sensitivity'], + ...securityValues.map((value) => [value, value])]); + const reason = field('repository-reason', 'Repository selection reason', 200); + const withdrawal = select('withdraw-reason', 'Withdrawal reason', withdrawals.map((value) => [value, value])); + const invalidation = select('invalidate-reason', 'Invalidation reason', invalidations.map((value) => [value, value])); + const refreshButton = button('refresh', 'Read current engineering state', () => refresh()); + const workButton = button('work', 'Read engineering work metadata', () => readWork()); + const proposalButton = button('proposal', 'Read checked issue proposal', () => readProposal()); + const approveButton = button('approve', 'Approve this exact checked proposal', () => approveProposal('approve')); + const rejectButton = button('reject', 'Reject checked issue proposal', () => approveProposal('reject')); + const enrollButton = button('enroll', 'Confirm or enroll engineering intake', () => mutate('enroll')); + const evidenceButton = button('evidence', 'Record verified failure', () => mutate('evidence')); + const selectButton = button('repository', 'Select this repository', () => mutate('repository')); + const withdrawButton = button('withdraw', 'Withdraw engineering source', () => mutate('withdraw')); + const invalidateButton = button('invalidate', 'Invalidate engineering evidence', () => mutate('invalidate')); + const retryTicket = button('retry-ticket', 'Recover the retained ticket command', () => retry('ticket')); + const policyButton = button('policy-read', 'Read repository policy (Admin + Support)', () => readPolicy()); + const policyPanel = node('details'); policyPanel.hidden = true; + const policyStatus = node('p'); const catalog = node('section'); + const enabledLabel = node('label', ' Enable repository policy '); const enabledInput = node('input'); + enabledInput.type = 'checkbox'; enabledInput.dataset.engineeringField = 'policy-enabled'; enabledLabel.append(enabledInput); + const prepareButton = button('policy-prepare', 'Prepare policy change', () => preparePolicy()); + const saveButton = button('policy-save', 'Save prepared policy change', () => savePolicy()); + const disableButton = button('policy-disable', 'Disable repository policy', () => mutate('policy-disable')); + const retryPolicy = button('retry-policy', 'Recover the retained policy command', () => retry('policy')); + policyPanel.append(node('summary', 'Repository policy (Admin + Support)'), policyStatus, catalog, + enabledLabel, prepareButton, saveButton, disableButton); + root.replaceChildren(node('h2', 'Engineering intake'), + node('p', 'Record verified failure evidence and select an allowed repository. Approval records this exact checked proposal; these controls never file an issue.'), + node('p', 'Changing an existing restriction still requires separate security review.'), + node('p', 'Proposal review requires current human review access and explicit configured proof ports.'), + status, refreshButton, sourceText, workText, workButton, proposalButton, proposalText, approveButton, rejectButton, enrollButton, + expected.wrapper, actual.wrapper, steps.wrapper, messageChoices, reference.wrapper, sensitivity.wrapper, evidenceButton, + repository.wrapper, reason.wrapper, selectButton, withdrawal.wrapper, withdrawButton, + invalidation.wrapper, invalidateButton, retryTicket, policyButton, policyPanel, retryPolicy); + const enabled = () => { try { return options.isEnabled?.() === true; } catch { return false; } }; + const reviewEnabled = () => { try { return options.isReviewEnabled?.() === true; } catch { return false; } }; + const ticketNodes = [sourceText, workText, workButton, proposalButton, proposalText, approveButton, rejectButton, enrollButton, expected.wrapper, actual.wrapper, steps.wrapper, + messageChoices, reference.wrapper, sensitivity.wrapper, evidenceButton, repository.wrapper, reason.wrapper, + selectButton, withdrawal.wrapper, withdrawButton, invalidation.wrapper, invalidateButton, retryTicket]; + const key = (domain, actor = context?.actorSubject, ticketId = context?.ticketId) => + JSON.stringify(domain === 'policy' ? ['policy', actor] : ['ticket', actor, ticketId]); + const owner = (domain) => context === null ? undefined : pending.get(key(domain)); + const owners = () => Object.freeze([...pending.values()].map((entry) => Object.freeze({ + domain: entry.domain, actorSubject: entry.actorSubject, ...(entry.ticketId === undefined ? {} : { ticketId: entry.ticketId }), + acknowledged: entry.ack !== null }))); + function changed() { try { options.onPendingChange?.(owners()); } catch { /* No callback can settle a packet. */ } } + function activity() { try { options.onBusyChange?.(busy); } catch { /* Host presentation is not authority. */ } } + function notice(value) { status.textContent = value; } + function clearPrivate() { + source = null; work = null; policy = null; proposal = null; preparedPolicy = null; session = null; + sourceText.textContent = ''; workText.textContent = ''; proposalText.textContent = ''; catalog.replaceChildren(); policyStatus.textContent = ''; + policyPanel.hidden = true; messageChoices.replaceChildren(); repository.input.replaceChildren(); repository.input.value = ''; + enabledInput.checked = false; + for (const input of inputs) input.value = ''; + withdrawal.input.value = withdrawals[0]; invalidation.input.value = invalidations[0]; + } + function controls() { + const active = context !== null && enabled(); + for (const item of ticketNodes) item.hidden = context?.ticketId === null; + root.hidden = !active; + for (const item of buttons) item.disabled = !active || busy; + const held = owner('ticket'); const policyHeld = owner('policy'); + const canWrite = active && !busy && ticket !== null && held === undefined; + // Private-read denial does not establish absence. Explicit enrollment is + // a separately authorized SDK command which can confirm existing intake. + enrollButton.disabled ||= !canWrite || source !== null || enrolled.has(key('ticket')); + evidenceButton.disabled ||= !canWrite || (source?.state === 'withdrawn' || enrolled.get(key('ticket'))?.state === 'withdrawn') || !(source !== null || enrolled.has(key('ticket'))); + workButton.disabled ||= source === null || source.sourceGeneration <= 0; + proposalButton.disabled ||= !reviewEnabled() || workButton.disabled || held !== undefined; + approveButton.disabled ||= !reviewEnabled() || !canWrite || proposal?.approvable !== true; + rejectButton.disabled ||= !reviewEnabled() || !canWrite || proposal?.rejectionAvailable !== true; + selectButton.disabled ||= !canWrite || work?.selection === undefined || work.selection.repositoryKeys.length === 0; + withdrawButton.disabled ||= !canWrite || !(source !== null || enrolled.has(key('ticket'))); + invalidateButton.disabled ||= withdrawButton.disabled; + prepareButton.disabled ||= policy === null || policy.unmappedRepositoryCount !== 0 || policy.catalog.length === 0 || policyHeld !== undefined; + saveButton.disabled ||= preparedPolicy === null || policyHeld !== undefined; + disableButton.disabled ||= policy === null || policyHeld !== undefined; + retryTicket.hidden = held === undefined; retryPolicy.hidden = policyHeld === undefined; + retryTicket.disabled ||= held === undefined; retryPolicy.disabled ||= policyHeld === undefined; + retryTicket.textContent = held?.ack ? 'Refresh acknowledged ticket command' : 'Retry the exact ticket command'; + retryPolicy.textContent = policyHeld?.ack ? 'Refresh acknowledged policy command' : 'Retry the exact policy command'; + } + function guard(observation) { + if (!enabled()) { clearPrivate(); ticket = null; controls(); } + if (observation !== epoch || context === null || !enabled() || options.canRequest?.() === false) + throw Object.assign(new Error('stale_view'), { stale: true }); + } + async function viewer(observation, original) { + guard(observation); const raw = await readSession(); guard(observation); + const value = { subject: text(raw?.subject ?? raw?.account?.subject), csrfToken: text(raw?.csrfToken, 2000) }; + if (value.subject !== context.actorSubject || (original && + (value.subject !== original.subject || value.csrfToken !== original.csrfToken))) + throw Object.assign(new Error('session_changed'), { status: 401 }); + return value; + } + async function call(path, init, observation, actor, observeResult) { + guard(observation); const controller = new AbortController(); controllers.add(controller); + try { + const value = await request(path, { ...init, signal: controller.signal, + headers: { ...(init?.headers ?? {}), 'X-Pegma-CSRF': actor.csrfToken } }); + if (!object(value) || !Object.prototype.hasOwnProperty.call(value, 'result') || value.csrfToken !== actor.csrfToken) throw invalid(); + observeResult?.(value.result); + guard(observation); + return value.result; + } finally { controllers.delete(controller); } + } + const base = () => '/api/support/admin/tickets/' + encodeURIComponent(context.ticketId) + '/engineering'; + function failure(error, observation) { + if (observation !== epoch) return; + clearPrivate(); ticket = null; + if (error?.status === 429) retryAt = Math.max(retryAt, Number.isSafeInteger(error.retryAt) ? error.retryAt : now() + 30000); + notice(pending.size ? 'A command is retained. Restore current access, then explicitly recover its original packet.' + : 'Current engineering access or state could not be confirmed. Refresh before another action.'); + if ([401, 403].includes(error?.status)) { + try { options.onAccessLost?.({ status: error.status, owners: owners() }); } catch { /* Retain ownership. */ } + } + } + async function operation(run) { + if (busy || context === null) return; + if (!enabled()) { clearPrivate(); ticket = null; controls(); return; } + const observation = epoch; busy = true; activity(); controls(); + try { await run(observation); } + catch (error) { if (!error?.stale) failure(error, observation); } + finally { if (observation === epoch) { busy = false; activity(); controls(); } } + } + async function currentTicket(observation, actor) { + guard(observation); const value = await readCurrentTicket(context.ticketId); guard(observation); + await viewer(observation, actor); + if (!object(value?.ticket) || value.ticket.id !== context.ticketId || !Array.isArray(value.messages) || value.csrfToken !== actor.csrfToken) throw invalid(); + counter(value.ticket.revision, 1); + const messages = value.messages.filter((message) => object(message) && message.ticketId === context.ticketId && message.visibility === 'customer'); + const ids = messages.map((message) => text(message.id)); + if (new Set(ids).size !== ids.length) throw invalid(); + ticket = { revision: value.ticket.revision, visibleMessageIds: ids }; + messageChoices.replaceChildren(node('p', 'Select actual customer-visible messages:')); + for (const id of ids) { + const label = node('label', id + ' '); const input = node('input'); input.type = 'checkbox'; + input.value = id; input.dataset.engineeringMessage = id; label.append(input); messageChoices.append(label); + } + return ticket; + } + function sourceValue(value) { + if (!object(value) || value.ticketId !== context.ticketId || !states.includes(value.state) || + !securityValues.includes(value.security) || ['hasEvidence', 'hasProductContext', 'reconciliationPending'].some((key) => typeof value[key] !== 'boolean')) throw invalid(); + counter(value.sourceGeneration); counter(value.workGeneration); counter(value.destinationCount); + return { ticketId: value.ticketId, sourceGeneration: value.sourceGeneration, workGeneration: value.workGeneration, + state: value.state, security: value.security, hasEvidence: value.hasEvidence, hasProductContext: value.hasProductContext, + destinationCount: value.destinationCount, reconciliationPending: value.reconciliationPending }; + } + async function refreshSource(observation, actor, acknowledged) { + source = null; work = null; sourceText.textContent = ''; workText.textContent = ''; + try { + const value = sourceValue(await call(base(), { method: 'GET' }, observation, actor)); + await viewer(observation, actor); source = value; sourceText.textContent = JSON.stringify(value, null, 2); + } catch (error) { + if (![403, 404].includes(error?.status)) throw error; + await viewer(observation, actor); + notice(error.status === 403 ? 'Source details are unavailable with current access.' : 'No source details were returned; explicit enrollment is checked by the server.'); + // A 403 is never absence or RestrictedRead. Only our bound known enroll + // ACK plus a NEW current same-actor staff-ticket read admits evidence. + if (acknowledged?.action === 'enroll') { + await currentTicket(observation, actor); enrolled.set(key('ticket'), copy(acknowledged.ack)); + pending.delete(acknowledged.key); changed(); + notice('Enrollment acknowledged. Current staff ticket refreshed; record evidence explicitly. Source details remain protected.'); + return; + } + if (acknowledged) return; + } + if (acknowledged && acknowledged.action !== 'repository' && source !== null && pending.get(acknowledged.key) === acknowledged) { + pending.delete(acknowledged.key); changed(); notice('Ticket command acknowledged and current engineering state read.'); + } + } + async function refresh() { + if (context?.ticketId === null) return readPolicy(); + return operation(async (observation) => { + clearPrivate(); const actor = await viewer(observation); session = actor; + await currentTicket(observation, actor); + const retained = owner('ticket'); const ack = retained?.ack ? retained : undefined; + await refreshSource(observation, actor, ack); guard(observation); + if (retained && !retained.ack) notice('The original ticket command is unresolved. A read cannot acknowledge it.'); + }); + } + async function readWork() { + if (!source || source.sourceGeneration <= 0) return; + proposal = null; proposalText.textContent = ''; controls(); + const generation = source.sourceGeneration; + return operation(async (observation) => { + const actor = await viewer(observation, session); + const value = await call(base() + '/work?sourceGeneration=' + generation, { method: 'GET' }, observation, actor); + if (!object(value) || value.ticketId !== context.ticketId || value.sourceGeneration !== generation || !securityValues.includes(value.security)) throw invalid(); + counter(value.workGeneration, 1); text(value.status); text(value.stage); + for (const key of ['hasCandidate', 'hasPreparedProposal', 'hasApproval', 'hasDispatch']) if (typeof value[key] !== 'boolean') throw invalid(); + const selected = value.selection; + if (selected !== undefined && (!object(selected) || !Array.isArray(selected.repositoryKeys) || selected.repositoryKeys.length > 20 || + new Set(selected.repositoryKeys).size !== selected.repositoryKeys.length)) throw invalid(); + if (selected) { counter(selected.policyGeneration); hash(selected.policyHash); selected.repositoryKeys.forEach((key) => text(key, 100)); } + await viewer(observation, actor); work = copy(value); session = actor; + workText.textContent = JSON.stringify({ sourceGeneration: value.sourceGeneration, workGeneration: value.workGeneration, + status: value.status, stage: value.stage, security: value.security, hasCandidate: value.hasCandidate, + hasPreparedProposal: value.hasPreparedProposal, hasApproval: value.hasApproval, hasDispatch: value.hasDispatch }, null, 2); + repository.input.replaceChildren(); + const empty = node('option', 'Select an allowed repository'); empty.value = ''; repository.input.append(empty); + for (const key of selected?.repositoryKeys ?? []) { const item = node('option', key); item.value = key; repository.input.append(item); } + repository.input.value = ''; notice('Current engineering work metadata read. Selection does not approve an issue.'); + }); + } + function proposalValue(value) { + if (!object(value) || value.ticketId !== context.ticketId || typeof value.approvable !== 'boolean' || + typeof value.rejectionAvailable !== 'boolean' || !object(value.request) || !object(value.intent) || !object(value.intent.command)) throw invalid(); + counter(value.sourceGeneration, 1); counter(value.workGeneration, 1); hash(value.proposalHash); text(value.status); + const command = value.intent.command; + if (value.intent.actorId !== context.actorSubject || command.ticketId !== value.ticketId || + command.sourceGeneration !== value.sourceGeneration || command.expectedWorkGeneration !== value.workGeneration || + command.proposalHash !== value.proposalHash || command.decision !== 'approve' || + JSON.stringify(Object.keys(command).sort()) !== JSON.stringify(['commandId', 'correlationId', 'decision', 'expectedWorkGeneration', 'proposalHash', 'sourceGeneration', 'ticketId'])) throw invalid(); + text(command.commandId); text(command.correlationId); + const request = value.request; const repository = request.repository; const bundle = request.bundle; + if (!object(repository) || !object(bundle) || !['public', 'private'].includes(repository.visibility) || + !['create_issue', 'link_existing_issue'].includes(request.operation) || !Array.isArray(bundle.labels) || + !Array.isArray(bundle.evidenceReferences) || bundle.labels.length > 256 || bundle.evidenceReferences.length > 256) throw invalid(); + for (const field of ['repositoryId', 'owner', 'name']) text(repository[field], 65536); + text(bundle.title, 65536, true); text(bundle.body, 65536, true); text(bundle.exportMarker, 65536); + for (const entry of [...bundle.labels, ...bundle.evidenceReferences]) text(entry, 65536, true); + if (bundle.templateId !== undefined) text(bundle.templateId, 65536); + if (request.operation === 'link_existing_issue') { text(request.issueId); counter(request.issueNumber, 1); } + if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 65536) throw invalid(); + return copy(value); + } + async function readProposal() { + if (!reviewEnabled() || !source || source.sourceGeneration <= 0 || owner('ticket')) return; + const generation = source.sourceGeneration; + // Remove the old render before awaiting a replacement. + proposal = null; proposalText.textContent = ''; controls(); + return operation(async (observation) => { + const actor = await viewer(observation, session); + const value = proposalValue(await call(base() + '/proposal?sourceGeneration=' + generation, + { method: 'GET' }, observation, actor)); + if (value.sourceGeneration !== generation) throw invalid(); + await viewer(observation, actor); proposal = value; session = actor; + // Inert checked outbound fields only. The full private Work and opaque + // retained command never enter rendered content or owner callbacks. + proposalText.textContent = JSON.stringify({ sourceGeneration: value.sourceGeneration, + workGeneration: value.workGeneration, proposalHash: value.proposalHash, request: value.request }, null, 2); + notice(value.approvable ? 'Review the exact checked request, then approve explicitly. Approval does not file an issue.' + : 'Historical checked proposal read. It is not available for a new approval.'); + }); + } + async function approveProposal(decision) { + if (!['approve', 'reject'].includes(decision) || !reviewEnabled() || + !(decision === 'approve' ? proposal?.approvable : proposal?.rejectionAvailable) || owner('ticket') || !ticket) return; + const original = copy(proposal.intent); + original.command.decision = decision; + return operation(async (observation) => { + await viewer(observation, session); + const retained = retain('ticket', 'review', base() + '/review', { intent: original }, + { sourceGeneration: original.command.sourceGeneration, expectedWorkGeneration: original.command.expectedWorkGeneration }); + proposal = null; proposalText.textContent = ''; + await send(retained, observation); + }); + } + function policyValue(value) { + if (!object(value) || typeof value.enabled !== 'boolean' || !Array.isArray(value.catalog) || value.catalog.length > 20 || + !Array.isArray(value.repositories) || value.repositories.length > 20) throw invalid(); + counter(value.generation); hash(value.policyHash); counter(value.unmappedRepositoryCount); + for (const list of [value.catalog, value.repositories]) { + const keys = list.map((entry) => { if (!object(entry) || typeof entry.enabled !== 'boolean') throw invalid(); return text(entry.key, 100); }); + if (new Set(keys).size !== keys.length) throw invalid(); + } + if (value.repositories.some((entry) => !value.catalog.some((configured) => configured.key === entry.key))) throw invalid(); + return copy(value); + } + async function policyRead(observation, actor, acknowledged) { + const value = policyValue(await call(policyPath, { method: 'GET' }, observation, actor)); + await viewer(observation, actor); policy = value; session = actor; policyPanel.hidden = false; + catalog.replaceChildren(); enabledInput.checked = value.enabled; + policyStatus.textContent = (value.catalog.length === 0 ? 'No server-configured repositories. ' : '') + + (value.unmappedRepositoryCount ? `${value.unmappedRepositoryCount} saved repositories are unmapped. Replacement is blocked; explicit disable remains available.` + : 'Current authorized repository policy. Configuration does not establish remote availability or dispatch approval.'); + for (const entry of value.catalog) { + const saved = value.repositories.find((item) => item.key === entry.key); + const label = node('label', entry.key + (entry.enabled ? ' (configured enabled)' : ' (configured disabled)') + + (saved ? saved.enabled ? ' (saved enabled) ' : ' (saved disabled) ' : ' (not selected) ')); const input = node('input'); + input.type = 'checkbox'; input.dataset.engineeringRepository = entry.key; + input.checked = value.repositories.some((saved) => saved.key === entry.key); label.append(input); catalog.append(label); + input.addEventListener('change', () => { preparedPolicy = null; controls(); }); + } + if (acknowledged && pending.get(acknowledged.key) === acknowledged) { pending.delete(acknowledged.key); changed(); } + } + async function readPolicy() { + return operation(async (observation) => { + const actor = await viewer(observation); const retained = owner('policy'); + policyPanel.hidden = true; preparedPolicy = null; + await policyRead(observation, actor, retained?.ack ? retained : undefined); + if (retained && !retained.ack) notice('The original policy command remains unresolved. This read does not acknowledge it.'); + }); + } + enabledInput.addEventListener('change', () => { preparedPolicy = null; controls(); }); + async function preparePolicy() { + if (!policy || owner('policy') || policy.unmappedRepositoryCount || !policy.catalog.length) return; + const keys = [...catalog.querySelectorAll('input')].filter((item) => item.checked).map((item) => item.dataset.engineeringRepository); + // Current host SDK policy admission allows eight repositories; the full + // configured catalog can contain twenty choices. The server still checks. + if (keys.length > 8) { notice('Choose at most eight configured repositories. No policy command was sent.'); return; } + const expectedGeneration = policy.generation; const active = enabledInput.checked === true; + return operation(async (observation) => { + const actor = await viewer(observation, session); + const commandId = text(nextId()); const packet = { commandId, expectedGeneration, + enabled: active, repositoryKeys: keys }; + const value = await call(policyPath + '/prepare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(packet) }, observation, actor); + const intent = value?.intent; + if (!object(intent) || intent.version !== 1 || intent.actorId !== actor.subject || intent.commandId !== commandId || + intent.expectedGeneration !== packet.expectedGeneration || JSON.stringify(intent.repositoryKeys) !== JSON.stringify(keys) || + !object(intent.policy) || intent.policy.enabled !== packet.enabled || !Array.isArray(intent.policy.repositories) || + intent.policy.repositories.length !== keys.length || new TextEncoder().encode(JSON.stringify({ intent })).byteLength > 131072) throw invalid(); + await viewer(observation, actor); + preparedPolicy = { actorSubject: actor.subject, body: JSON.stringify({ intent: copy(intent) }) }; + notice('Policy change prepared. Save explicitly; its opaque intent is retained but never displayed.'); + }); + } + function ack(value, retained) { + if (!object(value)) return false; + if (retained.domain === 'policy') return Number.isSafeInteger(value.generation) && value.generation >= 0 && + typeof value.enabled === 'boolean' && typeof value.policyHash === 'string' && /^[0-9a-f]{64}$/u.test(value.policyHash); + if (value.ticketId !== retained.ticketId || !Number.isSafeInteger(value.sourceGeneration) || value.sourceGeneration < 0) return false; + if (retained.action === 'review') return value.sourceGeneration === retained.sourceGeneration && + value.workGeneration === retained.expectedWorkGeneration + 1 && value.status === 'approved'; + if (retained.action === 'repository') return value.sourceGeneration === retained.sourceGeneration && + Number.isSafeInteger(value.workGeneration) && value.workGeneration > 0 && typeof value.status === 'string'; + return states.includes(value.state) && securityValues.includes(value.security); + } + async function send(retained, observation) { + if (now() < retryAt) { notice('Wait for the server retry delay before explicit recovery.'); return; } + if (retained.action === 'review' && !reviewEnabled()) throw Object.assign(new Error('review_disabled'), { status: 503 }); + const actor = await viewer(observation); + if (actor.subject !== retained.actorSubject || (retained.domain === 'ticket' && retained.ticketId !== context.ticketId)) throw invalid(); + if (retained.ack === null) { + const value = await call(retained.path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: retained.body }, observation, actor, + (result) => { if (ack(result, retained)) { retained.ack = copy(result); changed(); } }); + if (!ack(value, retained)) throw invalid(); + retained.ack = copy(value); changed(); + } + await viewer(observation, actor); + if (retained.domain === 'policy') await policyRead(observation, actor, retained); + else { + await currentTicket(observation, actor); + await refreshSource(observation, actor, retained); + if (retained.action === 'repository') { + const current = await call(base() + '/work?sourceGeneration=' + retained.sourceGeneration, + { method: 'GET' }, observation, actor); + if (!object(current) || current.ticketId !== retained.ticketId || current.sourceGeneration !== retained.sourceGeneration || + !Number.isSafeInteger(current.workGeneration) || current.workGeneration < retained.ack.workGeneration) throw invalid(); + await viewer(observation, actor); pending.delete(retained.key); changed(); + } + if (retained.action === 'enroll') enrolled.set(retained.key, copy(retained.ack)); + } + if (pending.get(retained.key) === retained) notice('The command was acknowledged. Refresh current state; do not resend it.'); + else notice('Command acknowledged and current authorized state refreshed. No issue was filed.'); + } + function retain(domain, action, path, packet, extra = {}) { + const body = JSON.stringify(packet); + if (new TextEncoder().encode(body).byteLength > (action === 'policy-save' ? 131072 : 65536)) throw new Error('invalid_input'); + const value = { key: key(domain), domain, actorSubject: context.actorSubject, + ...(domain === 'ticket' ? { ticketId: context.ticketId } : {}), action, path, body, ack: null, ...extra }; + pending.set(value.key, value); changed(); return value; + } + async function savePolicy() { + if (!preparedPolicy || owner('policy') || preparedPolicy.actorSubject !== context?.actorSubject) return; + const prepared = preparedPolicy; + return operation(async (observation) => { + await viewer(observation, session); + const retained = retain('policy', 'policy-save', policyPath, JSON.parse(prepared.body)); + preparedPolicy = null; await send(retained, observation); + }); + } + async function mutate(action) { + const domain = action === 'policy-disable' ? 'policy' : 'ticket'; + if (!context || owner(domain) || (domain === 'ticket' && !ticket) || (domain === 'policy' && !policy)) return; + let fields; + try { + if (action === 'enroll') fields = { expectedRevision: ticket.revision }; + else if (action === 'evidence') { + if ((source?.state === 'withdrawn' || enrolled.get(key('ticket'))?.state === 'withdrawn') || !(source || enrolled.has(key('ticket'))) || !securityValues.includes(sensitivity.input.value)) throw new Error('invalid_input'); + const reproductionSteps = steps.input.value.split(/\r?\n/u).map((entry) => text(entry, 1000, true)); + const selected = [...messageChoices.querySelectorAll('input')].filter((item) => item.checked).map((item) => item.value); + if (!selected.length || selected.length > 16 || selected.some((id) => !ticket.visibleMessageIds.includes(id)) || + new Set(selected).size !== selected.length || !reproductionSteps.length || reproductionSteps.length > 16) throw new Error('invalid_input'); + fields = { expectedRevision: ticket.revision, expectedBehavior: text(expected.input.value, 2000, true), + actualBehavior: text(actual.input.value, 2000, true), reproductionSteps, visibleMessageIds: selected, + verificationReference: text(reference.input.value), security: sensitivity.input.value }; + } else if (action === 'repository') { + if (!work?.selection?.repositoryKeys.includes(repository.input.value)) throw new Error('invalid_input'); + fields = { sourceGeneration: work.sourceGeneration, expectedWorkGeneration: work.workGeneration, + repositoryKey: repository.input.value, policyGeneration: work.selection.policyGeneration, + policyHash: work.selection.policyHash, reason: text(reason.input.value) }; + } else if (action === 'withdraw' && withdrawals.includes(withdrawal.input.value)) fields = { reason: withdrawal.input.value }; + else if (action === 'invalidate' && invalidations.includes(invalidation.input.value)) fields = { reason: invalidation.input.value }; + else if (action === 'policy-disable') fields = { expectedGeneration: policy.generation }; + else throw new Error('invalid_input'); + } catch { notice('Complete the bounded required fields and choose sensitivity explicitly. No command was sent.'); return; } + return operation(async (observation) => { + await viewer(observation, session); + const packet = { commandId: text(nextId()), ...fields }; + const retained = retain(domain, action, domain === 'policy' ? policyPath + '/disable' : base() + '/' + action, + packet, action === 'repository' ? { sourceGeneration: fields.sourceGeneration } : {}); + await send(retained, observation); + }); + } + async function retry(domain) { const retained = owner(domain); if (!retained) return; return operation((observation) => send(retained, observation)); } + function suspend() { + ++epoch; for (const controller of controllers) controller.abort(); controllers.clear(); + context = null; ticket = null; busy = false; activity(); clearPrivate(); notice('Engineering view cleared; retained commands keep their original owners.'); controls(); + } + async function showTicket(value) { + suspend(); if (!enabled()) return; + try { + const ticketId = text(value?.ticketId); if (!/^[A-Za-z0-9._~-]{1,200}$/u.test(ticketId)) throw invalid(); + context = { ticketId, actorSubject: text(value.actorSubject) }; counter(value.revision, 1); + } catch { context = null; notice('A current staff ticket is required.'); controls(); return; } + controls(); return refresh(); + } + async function showPolicy(value) { + suspend(); if (!enabled()) return; + try { context = { ticketId: null, actorSubject: text(value?.actorSubject) }; } + catch { context = null; controls(); return; } + controls(); return readPolicy(); + } + controls(); + return Object.freeze({ showTicket, showPolicy, refresh, readPolicy, suspend, + hasPending: () => pending.size > 0, pendingOwners: owners, isBusy: () => busy }); + } + globalThis.PegmaSupportEngineering = Object.freeze({ createPanel }); +})(); diff --git a/public/staff-support-ticket.js b/public/staff-support-ticket.js index 8c230bb..141f2d6 100644 --- a/public/staff-support-ticket.js +++ b/public/staff-support-ticket.js @@ -20,6 +20,17 @@ const handoffPanel = select('#staff-handoff'); 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 engineeringRecovery = select('#staff-engineering-recovery'); +const engineeringOwnerList = select('#staff-engineering-recovery-owners'); +const engineeringRecoveryStatus = select('#staff-engineering-recovery-status'); +let engineering = null; +let engineeringRequests = 0; +let engineeringBusy = false; +let engineeringOwners = Object.freeze([]); +let engineeringOwnershipInvalid = false; +let engineeringPolicyRecovery = null; +let engineeringAccountRecovery = false; const ticketId = new URL(window.location.href).searchParams.get('id') ?? ''; let learning = null; let learningRequests = 0; @@ -52,7 +63,8 @@ function onThisTicket() { return new URL(window.location.href).searchParams.get('id') === ticketId; } function isCurrent(generation) { - return generation === readGeneration && onThisTicket() && !suspended; + return generation === readGeneration && !suspended && + (onThisTicket() || engineeringPolicyRecovery !== null || engineeringAccountRecovery); } function guard(generation) { if (!isCurrent(generation)) @@ -67,6 +79,10 @@ function beginOperation() { // ordinary mutation or current-ticket reload can await anything. learning?.suspend(); if (learningRoot !== null) learningRoot.hidden = true; + engineeringPolicyRecovery = null; + engineering?.suspend(); + if (engineeringRoot !== null) engineeringRoot.hidden = true; + renderEngineeringRecovery(); suspended = false; const operation = { generation: ++readGeneration }; cancelRequests(); @@ -88,6 +104,10 @@ function clearHandoff() { function hideAll() { learning?.suspend(); if (learningRoot !== null) learningRoot.hidden = true; + engineeringPolicyRecovery = null; + engineering?.suspend(); + if (engineeringRoot !== null) engineeringRoot.hidden = true; + renderEngineeringRecovery(); currentView = null; signedOut.hidden = true; forbidden.hidden = true; @@ -136,15 +156,15 @@ function selectedComposeMode() { function updateControls() { composeForm.noValidate = ordinaryPacket !== null && ordinaryPacket.kind !== 'patch'; for (const link of signInLinks) { - link.node.target = ordinaryPacket === null && !learningPending() ? link.target : '_blank'; - link.node.rel = ordinaryPacket === null && !learningPending() ? link.rel : 'noopener noreferrer'; + link.node.target = ordinaryPacket === null && !learningPending() && !engineeringPending() ? link.target : '_blank'; + link.node.rel = ordinaryPacket === null && !learningPending() && !engineeringPending() ? link.rel : 'noopener noreferrer'; } const ticket = currentView?.ticket; const terminal = ticket?.status === 'resolved' || ticket?.status === 'closed'; const state = ticket === undefined ? '' : effectiveHandling(ticket).state; const seconds = retrySeconds(); const blocked = - learningOccupied() || + extensionOccupied() || busy !== null || viewer === null || authorityReloadRequired || @@ -316,7 +336,9 @@ function validateView(view) { view.csrfToken !== viewer?.csrfToken ) throw Object.assign(new Error('invalid_response'), { status: 502 }); - if ((view.learningReviewRecoveryEnabled !== undefined && typeof view.learningReviewRecoveryEnabled !== 'boolean') || + if ((view.engineeringEnabled !== undefined && typeof view.engineeringEnabled !== 'boolean') || + (view.engineeringReviewEnabled !== undefined && typeof view.engineeringReviewEnabled !== 'boolean') || + (view.learningReviewRecoveryEnabled !== undefined && typeof view.learningReviewRecoveryEnabled !== 'boolean') || (view.learningEnabled !== undefined && typeof view.learningEnabled !== 'boolean') || (view.learningStagedReviewEnabled !== undefined && typeof view.learningStagedReviewEnabled !== 'boolean')) throw Object.assign(new Error('invalid_response'), { status: 502 }); @@ -415,7 +437,7 @@ function failure(error, action, generation) { } else showStatus( error.status === 401 - ? ordinaryPacket !== null || learningPending() + ? ordinaryPacket !== null || learningPending() || engineeringPending() ? 'Sign in to the original account in another tab, then return here and reload this ticket. The action already sent may have completed.' : 'Sign in, then reload this ticket. Any request already sent may have completed.' : error.status === 403 @@ -535,7 +557,7 @@ async function loadTicket() { // Private handoff availability does not lock a fully refreshed ticket view. finishOperation(operation); // Admission opens only after the ACK (if any) and this complete current GET. - syncLearning(view); + void syncExtensions(view); await loadHandoff(); return { generation, @@ -609,7 +631,7 @@ async function sendOrdinaryPacket(packet, label) { } async function patchTicket(action, extra = {}) { if ( - learningOccupied() || + extensionOccupied() || busy !== null || retrySeconds() > 0 || suspended || @@ -641,7 +663,7 @@ async function patchTicket(action, extra = {}) { } takeoverButton.addEventListener('click', async () => { if ( - learningOccupied() || + extensionOccupied() || busy !== null || retrySeconds() > 0 || suspended || @@ -724,7 +746,7 @@ composeForm.addEventListener('submit', async (event) => { const mode = selectedComposeMode(); const body = composeBody.value.trim(); if ( - learningOccupied() || + extensionOccupied() || busy !== null || retrySeconds() > 0 || suspended || @@ -766,7 +788,7 @@ composeForm.addEventListener('submit', async (event) => { ); }); select('#staff-ticket-reload').addEventListener('click', () => { - if (!onThisTicket() && learningPending()) { + if (!onThisTicket() && (learningPending() || engineeringPending())) { invalidate(); showStatus('Return to the original ticket address before reloading. An earlier learning action may have completed.', true); } else if (!onThisTicket()) window.location.reload(); @@ -782,7 +804,7 @@ function learningOccupied() { return learningRequests > 0 || learningPending(); } function requireLearningAdmission(reviewRecovery = false) { - if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || + if (engineeringOccupied() || busy !== null || ordinaryPacket !== null || takeoverPacket !== null || ordinaryAcknowledged || suspended || authorityReloadRequired || viewer === null || currentView === null || (currentView.learningEnabled !== true && !(reviewRecovery && learning?.hasPendingReview?.() === true && @@ -803,14 +825,14 @@ async function learningRequest(run, reviewRecovery = false) { } function syncLearning(view) { if (learning === null || learningRoot === null) return; - if (busy !== null || (view.learningEnabled !== true && !(learning.hasPendingReview?.() === true && + if (engineeringOccupied() || busy !== null || (view.learningEnabled !== true && !(learning.hasPendingReview?.() === true && view.learningReviewRecoveryEnabled === true)) || ordinaryPacket !== null || takeoverPacket !== null) { learning.suspend(); learningRoot.hidden = true; return; } learningRoot.hidden = false; - void learning.showTicket({ ticketId: view.ticket.id, revision: view.ticket.revision, + return learning.showTicket({ ticketId: view.ticket.id, revision: view.ticket.revision, actorSubject: viewer.subject, status: view.ticket.status, resolvedAt: view.ticket.resolvedAt }, { recoveryOnly: view.learningEnabled !== true }); } @@ -846,8 +868,119 @@ if (learningRoot !== null && typeof globalThis.PegmaSupportLearning?.createPanel }, }); } +function engineeringPending() { + return engineeringOwnershipInvalid || engineeringOwners.length > 0; +} +function engineeringOccupied() { + return engineeringPending() || engineeringBusy || engineeringRequests > 0; +} +function extensionOccupied() { return learningOccupied() || engineeringOccupied(); } +function renderEngineeringRecovery() { + if (!engineeringRecovery || !engineeringOwnerList || !engineeringRecoveryStatus) return; + engineeringRecovery.hidden = !engineeringPending(); + engineeringOwnerList.replaceChildren(); + engineeringRecoveryStatus.textContent = engineeringOwnershipInvalid + ? 'Retained owner metadata could not be confirmed. Keep this tab open.' + : 'Keep this tab open. Restore the original account, then choose its retained owner. Reads never settle unknown commands.'; + for (const owner of engineeringOwners) { + // No different account sees an owner's ticket, body, or recovery controls. + if (viewer?.subject !== owner.actorSubject) continue; + const button = document.createElement('button'); button.type = 'button'; + button.textContent = owner.domain === 'policy' ? 'Recover repository policy command' + : 'Recover engineering command for ' + owner.ticketId; + button.disabled = busy !== null || engineeringBusy || engineeringRequests > 0 || learningOccupied(); + button.addEventListener('click', () => { void recoverEngineeringOwner(owner); }); + engineeringOwnerList.append(button); + } +} +function requireEngineeringAdmission() { + const policyMode = engineeringPolicyRecovery !== null; + if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || ordinaryAcknowledged || + learningOccupied() || suspended || authorityReloadRequired || viewer === null || + (!policyMode && (currentView?.engineeringEnabled !== true || !onThisTicket())) || + (policyMode && viewer.subject !== engineeringPolicyRecovery.actorSubject)) + throw Object.assign(new Error('engineering_suspended'), { stale: true }); +} +async function engineeringRequest(run) { + requireEngineeringAdmission(); const generation = readGeneration; + ++engineeringRequests; updateControls(); + try { const value = await run(); guard(generation); requireEngineeringAdmission(); return value; } + finally { --engineeringRequests; updateControls(); renderEngineeringRecovery(); } +} +async function syncExtensions(view) { + const generation = readGeneration; + await syncLearning(view); + if (!isCurrent(generation) || currentView !== view || engineering === null) return; + if (busy !== null || ordinaryPacket !== null || takeoverPacket !== null || learningOccupied() || view.engineeringEnabled !== true) { + engineering.suspend(); engineeringRoot.hidden = true; renderEngineeringRecovery(); return; + } + engineeringPolicyRecovery = null; engineeringRoot.hidden = false; + await engineering.showTicket({ ticketId: view.ticket.id, revision: view.ticket.revision, actorSubject: viewer.subject }); + renderEngineeringRecovery(); +} +async function readEngineeringRecoveryAccount() { + if (engineeringAccountRecovery || !engineeringPending() || busy !== null || ordinaryPacket !== null || takeoverPacket !== null || learningOccupied()) return; + const generation = ++readGeneration; suspended = false; cancelRequests(); hideAll(); + viewer = null; csrfToken = ''; engineeringAccountRecovery = true; ++engineeringRequests; renderEngineeringRecovery(); updateControls(); + try { await readViewer(generation, null); authorityReloadRequired = false; } + catch { if (generation === readGeneration) { viewer = null; csrfToken = ''; engineering?.suspend(); } } + finally { engineeringAccountRecovery = false; --engineeringRequests; } + renderEngineeringRecovery(); updateControls(); +} +async function recoverEngineeringOwner(owner) { + if (!engineeringOwners.includes(owner) || viewer?.subject !== owner.actorSubject || learningOccupied() || + ordinaryPacket !== null || takeoverPacket !== null || busy !== null) return; + if (owner.domain === 'policy') { + // Global owner recovery needs no old ticket, source, selection or cached + // permission. The actual policy GET checks the strict bundle/flag and the + // current Admin+Support roles before any editor or mutation is admitted. + ++readGeneration; cancelRequests(); suspended = false; + engineeringPolicyRecovery = owner; engineeringRoot.hidden = false; + await engineering.showPolicy({ actorSubject: owner.actorSubject }); + } else { + if (owner.ticketId !== ticketId || !onThisTicket()) { + engineeringRecoveryStatus.textContent = 'Return to the original ticket address in this same tab before recovery.'; + return; + } + await loadTicket(); + } + renderEngineeringRecovery(); +} +if (engineeringRoot !== null && typeof globalThis.PegmaSupportEngineering?.createPanel === 'function') { + engineering = globalThis.PegmaSupportEngineering.createPanel({ + root: engineeringRoot, + isEnabled: () => engineeringPolicyRecovery !== null || currentView?.engineeringEnabled === true, + isReviewEnabled: () => currentView?.engineeringReviewEnabled === true, + canRequest: () => busy === null && ordinaryPacket === null && takeoverPacket === null && + !ordinaryAcknowledged && !learningOccupied() && !suspended && !authorityReloadRequired, + request: (path, init) => engineeringRequest(() => api(path, init)), + readSession: () => engineeringRequest(() => readViewer(readGeneration)), + readCurrentTicket: (id) => engineeringRequest(async () => { + if (id !== ticketId || !onThisTicket()) throw Object.assign(new Error('stale_view'), { stale: true }); + const generation = readGeneration; const original = await readViewer(generation); + const value = await api('/api/support/admin/tickets/' + encodeURIComponent(id)); + guard(generation); validateView(value); await readViewer(generation, original); return value; + }), + onPendingChange: (owners) => { + if (!Array.isArray(owners) || owners.some((owner) => !owner || + !['ticket', 'policy'].includes(owner.domain) || typeof owner.actorSubject !== 'string' || + typeof owner.acknowledged !== 'boolean' || (owner.domain === 'ticket' && typeof owner.ticketId !== 'string'))) { + engineeringOwnershipInvalid = true; + } else { engineeringOwners = Object.freeze([...owners]); engineeringOwnershipInvalid = false; } + updateControls(); renderEngineeringRecovery(); + }, + onBusyChange: (value) => { engineeringBusy = value === true; updateControls(); renderEngineeringRecovery(); }, + onAccessLost: ({ status }) => { + ++readGeneration; cancelRequests(); busy = null; viewer = null; csrfToken = ''; + authorityReloadRequired = true; hideAll(); signedOut.hidden = status !== 401; forbidden.hidden = status !== 403; + showStatus('Current engineering access could not be confirmed. Keep this tab open and sign in to the original account in another tab.', true); + renderEngineeringRecovery(); updateControls(); + }, + }); + select('#staff-engineering-check-access')?.addEventListener('click', () => { void readEngineeringRecoveryAccount(); }); +} window.addEventListener('beforeunload', (event) => { - if (!learningPending()) return; + if (!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 c68044a..2793315 100644 --- a/src/pages/staff/support/ticket.astro +++ b/src/pages/staff/support/ticket.astro @@ -137,6 +137,15 @@ import Base from '../../../layouts/Base.astro'; + + + diff --git a/src/support-engineering-controller.test.ts b/src/support-engineering-controller.test.ts new file mode 100644 index 0000000..e22cab6 --- /dev/null +++ b/src/support-engineering-controller.test.ts @@ -0,0 +1,172 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createContext, runInContext } from 'node:vm'; +import { afterEach, describe, expect, it } from 'vitest'; +import { authenticate } from '../worker/src/api-auth'; +import { IDENTITY_ISSUER } from '../worker/src/identity-api'; +import { createSupportApi } from '../worker/src/support-api'; +import { engineeringTicketId } from '../worker/src/support-engineering-fixtures'; +import { createSupportEngineeringHttpFixture, type EngineeringHttpActor } from '../worker/src/support-engineering-http-fixtures'; +import { BrowserNode, browserGate } from './test-support-browser'; + +// The real template and all three real scripts run over real HTTP/auth/SDK +// factories. This inert DOM models event ordering for a fictional ticket. +function documentFromTemplate() { + const template = readFileSync(new URL('./pages/staff/support/ticket.astro', import.meta.url), 'utf8'); + const root = new BrowserNode('document'); const stack = [root]; + const voidTags = new Set(['input', 'img', 'link', 'meta', 'br', 'hr']); + for (const match of template.matchAll(/<(\/?)([a-z][a-z0-9-]*)([^>]*?)>/giu)) { + const tag = match[2]?.toLowerCase() ?? ''; + if (match[1]) { const last = stack.findLastIndex((node) => node.tagName === tag); if (last > 0) stack.splice(last); continue; } + const node = new BrowserNode(tag); const attributes = match[3] ?? ''; + for (const attr of attributes.matchAll(/([\w:-]+)(?:="([^"]*)")?/gu)) if (attr[1]) node.attributes.set(attr[1], attr[2] ?? ''); + node.hidden = node.attributes.has('hidden'); node.disabled = node.attributes.has('disabled'); + node.checked = node.attributes.has('checked'); node.value = node.attributes.get('value') ?? ''; + stack.at(-1)?.append(node); + if (!voidTags.has(tag) && !attributes.endsWith('/')) stack.push(node); + } + for (const node of root.all().filter((value) => value.tagName === 'select')) + node.value = node.all().find((value) => value.tagName === 'option')?.value ?? ''; + return Object.assign(root, { createElement: (tag: string) => new BrowserNode(tag) }); +} +const disposers = new Set<() => void>(); +afterEach(() => { for (const dispose of [...disposers]) dispose(); }); +async function until(check: () => boolean) { + for (let attempt = 0; attempt < 1500; attempt++) { + if (check()) return; + await new Promise((resolve) => setTimeout(resolve, 2)); + } + throw new Error('Actual engineering controller did not settle'); +} +async function fixture() { + const f = await createSupportEngineeringHttpFixture(); await f.legacyTicket(); + const state = { actor: 'staff' as EngineeringHttpActor, loseEngineering: false, + holdOrdinary: undefined as ReturnType> | undefined, + ordinaryResponse: undefined as ReturnType> | undefined }; + const api = createSupportApi({ ...f.options, application: f.engineering.application, + createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter, + engineering: { enabled: () => true, configuration: f.options } }); + const document = documentFromTemplate(); const calls: { path: string; method: string; body?: string }[] = []; + const window = Object.assign(new EventTarget(), { location: { + href: IDENTITY_ISSUER + '/staff/support/ticket/?id=' + engineeringTicketId, + reload() { throw new Error('Retained owner must remain in this page'); }, + } }); + let active = 0; + const timers = new Set>(); + class FormDataAdapter { + constructor(readonly form: BrowserNode) {} + get(name: string) { return this.form.all().find((node) => node.attributes.get('name') === name)?.value ?? null; } + } + const context = createContext({ document, window, URL, URLSearchParams, Headers, Date, AbortController, TextEncoder, + FormData: FormDataAdapter, crypto: { randomUUID: () => randomUUID().toUpperCase() }, + setTimeout(run: () => void, duration: number) { + const timer = setTimeout(() => { timers.delete(timer); run(); }, duration); timers.add(timer); return timer; + }, + clearTimeout(timer: ReturnType) { timers.delete(timer); clearTimeout(timer); }, + async fetch(path: string, init: RequestInit = {}) { + ++active; + try { + const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get(state.actor)!); + const method = init.method ?? 'GET'; + if (method === 'POST' || method === 'PATCH') { headers.set('Origin', IDENTITY_ISSUER); headers.set('Sec-Fetch-Site', 'same-origin'); } + calls.push({ path, method, ...(typeof init.body === 'string' ? { body: init.body } : {}) }); + const request = new Request(IDENTITY_ISSUER + path, { ...init, headers }); + let response: Response; + if (path === '/api/identity/session') { + const value = await authenticate(request, f.options); + response = value === null ? Response.json({ error: 'authentication_required' }, { status: 401 }) + : Response.json({ account: { subject: value.link.subject }, csrfToken: value.csrfToken }); + } else response = await api(request); + if (method === 'POST' && path.endsWith('/messages') && state.holdOrdinary) { + state.ordinaryResponse?.resolve(response); + await state.holdOrdinary.promise; + } + if (method === 'POST' && path.includes('/engineering/') && response.ok && state.loseEngineering) { + state.loseEngineering = false; return Response.json({ error: 'synthetic_lost_ack' }, { status: 503 }); + } + return response; + } finally { --active; } + }, + }); + for (const name of ['staff-support-learning.js', 'staff-support-engineering.js', 'staff-support-ticket.js']) + runInContext(readFileSync(new URL('../public/' + name, import.meta.url), 'utf8'), context, { filename: name }); + const node = (id: string) => { + const value = document.querySelector('#' + id); if (!value) throw new Error('Missing actual page node ' + id); return value; + }; + const control = (action: string) => { + const value = node('staff-engineering-panel').all().find((item) => item.dataset.engineeringAction === action); + if (!value) throw new Error('Missing engineering action ' + action); return value; + }; + const dispose = () => { window.dispatchEvent(new Event('pagehide')); for (const timer of timers) clearTimeout(timer); timers.clear(); disposers.delete(dispose); }; + disposers.add(dispose); + const idle = () => until(() => active === 0 && !control('refresh').disabled); + await until(() => !node('staff-engineering-panel').hidden && !control('refresh').disabled && active === 0); + return { f, state, api, calls, node, control, idle, window }; +} + +describe('registered staff controller and engineering panel composition', () => { + it('admits source-zero evidence only after actual enrollment and a fresh same-actor staff detail', async () => { + const h = await fixture(); + expect(h.control('enroll').disabled).toBe(false); expect(h.control('evidence').disabled).toBe(true); + h.control('enroll').fire('click'); await h.idle(); + expect(h.control('evidence').disabled).toBe(false); + const index = h.calls.findIndex((call) => call.method === 'POST' && call.path.endsWith('/engineering/enroll')); + expect(index).toBeGreaterThanOrEqual(0); + expect(h.calls.slice(index + 1).some((call) => call.path === '/api/support/admin/tickets/' + engineeringTicketId)).toBe(true); + expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('holds ordinary writes during a committed engineering ACK and recovers the exact original packet', async () => { + const h = await fixture(); const entered = browserGate(); const release = browserGate(); + h.f.hooks.commit = async () => { entered.resolve(); await release.promise; }; + h.state.loseEngineering = true; h.control('enroll').fire('click'); + try { + await entered.promise; + const before = h.calls.length; h.node('compose-body').value = 'A fictional reply retained while engineering is pending.'; + h.node('staff-compose-form').fire('submit'); + expect(h.calls).toHaveLength(before); expect(h.node('compose-submit').disabled).toBe(true); + } finally { delete h.f.hooks.commit; release.resolve(); } + await until(() => !h.control('retry-ticket').hidden && !h.control('retry-ticket').disabled); + const original = h.calls.find((call) => call.method === 'POST' && call.path.endsWith('/engineering/enroll')); + if (!original) throw new Error('Missing actual retained enrollment'); + const rows = await h.f.rows(); h.control('retry-ticket').fire('click'); await h.idle(); + expect(h.calls.filter((call) => call.method === 'POST' && call.path === original.path)).toEqual([original, original]); + expect(await h.f.rows()).toEqual(rows); + expect(h.node('compose-body').value).toBe('A fictional reply retained while engineering is pending.'); + expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('holds engineering admission while an ordinary real SDK reply awaits its ACK', async () => { + const h = await fixture(); const release = browserGate(); const returned = browserGate(); + h.state.holdOrdinary = release; h.state.ordinaryResponse = returned; + const form = h.node('staff-compose-form'); + h.node('compose-body').value = 'A fictional current staff reply.'; + form.fire('input'); + expect(h.node('compose-submit').disabled).toBe(true); + // The real page deliberately has no default public/internal compose mode. + for (const input of form.all()) + if (input.attributes.get('name') === 'composeMode') input.checked = input.value === 'public'; + form.fire('change'); + expect(h.node('compose-submit').disabled).toBe(false); + form.fire('submit'); + let ordinary: (typeof h.calls)[number] | undefined; + let committedRows: Awaited> | undefined; + try { + // Hold only the transport ACK after the actual HTTP/SDK mutation returns. + expect((await returned.promise).status).toBe(201); + ordinary = h.calls.find((call) => call.method === 'POST' && call.path.endsWith('/messages')); + expect(ordinary).toBeDefined(); + committedRows = await h.f.rows(); + expect(committedRows.some((row) => row.kind === 'message' && row.message.body === 'A fictional current staff reply.')).toBe(true); + expect(h.node('compose-submit').disabled).toBe(true); + const writes = h.calls.filter((call) => call.method === 'POST').length; + h.control('enroll').fire('click'); + expect(h.calls.filter((call) => call.method === 'POST')).toHaveLength(writes); + expect(h.calls.some((call) => call.method === 'POST' && call.path.endsWith('/engineering/enroll'))).toBe(false); + } finally { h.state.holdOrdinary = undefined; h.state.ordinaryResponse = undefined; release.resolve(); } + await h.idle(); + expect(h.calls.filter((call) => call.method === 'POST' && call.path.endsWith('/messages'))).toEqual([ordinary]); + expect(await h.f.rows()).toEqual(committedRows); + expect(h.f.engineering.state.modelCalls).toBe(0); + }); +}); diff --git a/src/support-engineering-integration.test.ts b/src/support-engineering-integration.test.ts new file mode 100644 index 0000000..5d69760 --- /dev/null +++ b/src/support-engineering-integration.test.ts @@ -0,0 +1,235 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { supportPermissions } from '@pegma/support-desk-application'; +import { describe, expect, it } from 'vitest'; +import { authenticate } from '../worker/src/api-auth'; +import { IDENTITY_ISSUER } from '../worker/src/identity-api'; +import { createSupportApi } from '../worker/src/support-api'; +import { SUPPORT_ROLE } from '../worker/src/support-access'; +import { engineeringCanary, engineeringTicketId } from '../worker/src/support-engineering-fixtures'; +import { createSupportEngineeringHandlers } from '../worker/src/support-engineering-handlers'; +import { createSupportEngineeringHttpFixture, type EngineeringHttpActor } from '../worker/src/support-engineering-http-fixtures'; +import { BrowserNode } from './test-support-browser'; + +interface Owner { domain: string; actorSubject: string; ticketId?: string; acknowledged: boolean } +interface Panel { + showTicket(value: { ticketId: string; revision: number; actorSubject: string }): Promise; + refresh(): Promise; suspend(): void; pendingOwners(): readonly Owner[]; hasPending(): boolean; +} +async function harness(autoEnrolled = false) { + const f = await createSupportEngineeringHttpFixture(); + const ticket = autoEnrolled ? await f.engineering.createTicket() : await f.legacyTicket(); + const support = createSupportApi({ ...f.options, application: f.engineering.application, + createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); + const root = new BrowserNode('section'); + const calls: { path: string; method: string; body?: string; serverStatus?: number }[] = []; + const ownership: (readonly Owner[])[] = []; + const state = { actor: 'staff' as EngineeringHttpActor, enabled: true, ids: 0, handle: f.handle, + fault: undefined as ((path: string, response: Response) => Promise) | undefined }; + function incoming(path: string, init: RequestInit = {}) { + const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get(state.actor)!); + if (init.method === 'POST') { headers.set('Origin', IDENTITY_ISSUER); headers.set('Sec-Fetch-Site', 'same-origin'); } + return new Request(IDENTITY_ISSUER + path, { ...init, headers }); + } + async function request(path: string, init: RequestInit = {}) { + const call = { path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}), serverStatus: 0 }; + calls.push(call); + const pathname = new URL(path, IDENTITY_ISSUER).pathname; + const engineering = /^\/api\/support\/admin\/tickets\/[^/]+\/engineering(?:\/|$)/u.test(pathname) || + /^\/api\/support\/admin\/engineering(?:\/|$)/u.test(pathname); + const response = engineering ? await state.handle(incoming(path, init)) : await support(incoming(path, init)); + if (response === null) throw new Error('Expected an owned HTTP route'); + call.serverStatus = response.status; await state.fault?.(path, response); + if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status }); + return response.json(); + } + const readSession = async () => { + const value = await authenticate(incoming('/api/identity/session'), f.options); + if (value === null) throw Object.assign(new Error('session_required'), { status: 401 }); + return { subject: value.link.subject, csrfToken: value.csrfToken }; + }; + const vm: Record = { document: { createElement: (tag: string) => new BrowserNode(tag) }, AbortController, TextEncoder }; + runInNewContext(readFileSync(new URL('../public/staff-support-engineering.js', import.meta.url), 'utf8'), vm); + const panel = (vm.PegmaSupportEngineering as { createPanel(options: unknown): Panel }).createPanel({ + root, request, readSession, readCurrentTicket: (id: string) => request('/api/support/admin/tickets/' + encodeURIComponent(id)), + isEnabled: () => state.enabled, commandId: () => 'ENGINEERING-INTEGRATION-UPPERCASE-' + ++state.ids, + onPendingChange: (owners: readonly Owner[]) => ownership.push(owners) }); + function node(key: string, field = false) { + const value = root.all().find((item) => item.dataset[field ? 'engineeringField' : 'engineeringAction'] === key); + if (!value) throw new Error('Missing engineering control ' + key); return value; + } + async function settle() { + for (let attempt = 0; attempt < 1200; attempt++) { + if (!node('refresh').disabled) return; + await new Promise((resolve) => setTimeout(resolve, 2)); + } + throw new Error('Actual engineering event did not settle'); + } + const action = async (key: string) => { node(key).fire('click'); await settle(); }; + const open = () => panel.showTicket({ ticketId: engineeringTicketId, revision: ticket.revision, actorSubject: f.principals[state.actor] }); + function evidence(security = 'ordinary') { + node('expected', true).value = 'The fictional export contains its rows.'; + node('actual', true).value = 'The fictional downloaded file is empty.'; + node('steps', true).value = 'Open the fictional workspace.\nExport and inspect the file.'; + node('verification', true).value = 'PUBLIC-INTEGRATION-STAFF-VERIFICATION'; + node('security', true).value = security; + const message = root.all().find((item) => item.dataset.engineeringMessage === 'engineering-question'); + if (!message) throw new Error('Expected actual customer-visible message choice'); message.checked = true; + } + return { f, root, state, panel, calls, ownership, node, action, open, evidence, + writes: () => calls.filter((call) => call.method === 'POST') }; +} + +describe('public engineering panel through actual Memory SDK and HTTP authority', () => { + it('keeps an engineering-prefixed ticket ID on the actual staff detail route before engineering intake', async () => { + const h = await harness(); await h.open(); + expect(h.calls.find((call) => call.path === '/api/support/admin/tickets/' + engineeringTicketId)?.serverStatus).toBe(200); + expect(h.calls.find((call) => call.path.endsWith('/engineering'))?.serverStatus).toBe(404); + expect(h.node('enroll').disabled).toBe(false); expect(h.writes()).toEqual([]); + expect(h.root.all().some((item) => item.dataset.engineeringMessage === 'engineering-question')).toBe(true); + }); + it('requires an explicit SDK enrollment confirmation before evidence when an auto-enrolled source0 read is protected', async () => { + const h = await harness(true); await h.open(); + expect(h.calls.some((call) => call.path.endsWith('/engineering') && call.serverStatus === 403)).toBe(true); + expect(h.node('evidence').disabled).toBe(true); + expect(h.node('enroll').disabled).toBe(false); + await h.action('enroll'); expect(h.panel.hasPending()).toBe(false); + expect(h.node('evidence').disabled).toBe(false); + h.evidence(); await h.action('evidence'); expect((await h.f.engineering.source()).state).toBe('eligible'); + expect((await h.f.resolve(h.f.principals.staff))?.permissions).not.toContain(supportPermissions.engineeringRestrictedRead); + }); + it('recovers known enrollment0 through protected source403 and a NEW real same-actor staff-ticket read before explicit evidence', async () => { + const h = await harness(); await h.open(); + expect(h.node('enroll').disabled).toBe(false); expect(h.node('evidence').disabled).toBe(true); + await h.action('enroll'); const start = h.calls.findIndex((call) => call.path.endsWith('/engineering/enroll')); + expect(h.calls[start]?.serverStatus).toBe(200); + expect(h.calls.slice(start + 1).some((call) => call.path.endsWith('/engineering') && call.serverStatus === 403)).toBe(true); + expect(h.calls.slice(start + 1).some((call) => call.path === '/api/support/admin/tickets/' + engineeringTicketId && call.serverStatus === 200)).toBe(true); + const enrolled = await h.f.engineering.source(); + expect(enrolled).toMatchObject({ sourceGeneration: 0, state: 'unverified', security: 'uncertain' }); + const current = await h.f.resolve(h.f.principals.staff); + expect(current?.permissions).not.toContain(supportPermissions.engineeringRestrictedRead); + expect(h.panel.hasPending()).toBe(false); expect(h.node('evidence').disabled).toBe(false); + h.evidence(); await h.action('evidence'); + const source = await h.f.engineering.source(); expect(source.state).toBe('eligible'); + expect(source.evidence).toMatchObject({ kind: 'staff_verified_failure', actorId: h.f.principals.staff }); + expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); + expect(h.root.textContent).not.toContain(engineeringCanary); + }); + + it('keeps a real product hold distinct from eligibility and never starts processing', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); h.f.engineering.state.product = 'missing'; + h.evidence(); await h.action('evidence'); + expect((await h.f.engineering.source()).state).toBe('held'); + expect((await h.f.rows()).filter((row) => row.kind === 'engineering_work')).toEqual([]); + expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('retains the exact uppercase unknown evidence packet across actual withdrawal and replay without a new command', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); h.evidence(); + let lose = true; + h.state.fault = async (path, response) => { + if (lose && path.endsWith('/evidence') && response.ok) { lose = false; throw Object.assign(new Error('Synthetic committed ACK loss'), { status: 503 }); } + }; + await h.action('evidence'); const original = h.writes().at(-1)!; expect(h.panel.hasPending()).toBe(true); + await h.f.engineering.application.withdrawEngineeringSource(h.f.engineering.actors.staff, + { ...h.f.engineering.command('ui-withdraw-after-ack-loss'), ticketId: engineeringTicketId, reason: 'privacy_withdrawal' }); + const before = await h.f.rows(); h.state.fault = undefined; + await h.open(); expect(h.panel.hasPending()).toBe(true); await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original.body); expect(h.state.ids).toBe(2); + expect(await h.f.rows()).toEqual(before); expect((await h.f.engineering.source()).state).toBe('withdrawn'); + expect(h.panel.hasPending()).toBe(false); + }); + + it('uses GET-only recovery after a genuine enrollment ACK followed by a transport failure', async () => { + const h = await harness(); await h.open(); + let fail = false; + h.state.fault = async (path, response) => { + if (path.endsWith('/enroll') && response.ok) fail = true; + else if (fail && path.endsWith('/engineering')) throw Object.assign(new Error('Synthetic post-ACK read failure'), { status: 503 }); + }; + await h.action('enroll'); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(true); + const before = await h.f.rows(); h.state.fault = undefined; const posts = h.writes().length; + await h.action('retry-ticket'); expect(h.writes()).toHaveLength(posts); + expect(h.panel.hasPending()).toBe(false); expect(await h.f.rows()).toEqual(before); + expect(h.node('evidence').disabled).toBe(false); + }); + + it('replays the original opaque policy intent after lost ACK and a removed catalog without rendering it', async () => { + const h = await harness(); h.state.actor = 'both'; await h.open(); await h.action('policy-read'); + await h.action('policy-prepare'); let lose = true; + h.state.fault = async (path, response) => { + if (lose && path === '/api/support/admin/engineering/policy' && response.ok) { + // This transport fault is armed only for the already prepared POST. + lose = false; throw Object.assign(new Error('Synthetic policy response loss'), { status: 503 }); + } + }; + await h.action('policy-save'); const original = h.writes().at(-1)!; + expect(h.panel.hasPending()).toBe(true); const before = await h.f.policyRows(); + h.state.fault = undefined; + h.state.handle = createSupportEngineeringHandlers({ ...h.f.options, repositories: [] }); + await h.action('retry-policy'); + expect(h.writes().at(-1)?.body).toBe(original.body); expect(await h.f.policyRows()).toEqual(before); + expect(h.panel.hasPending()).toBe(false); expect(h.node('policy-prepare').disabled).toBe(true); + expect(h.root.textContent).toContain('No server-configured repositories.'); + expect(h.root.textContent).toContain('saved repositories are unmapped'); + expect(h.node('policy-disable').disabled).toBe(false); + for (const secret of ['responsibilities', 'allowedTemplates', 'actorId', 'installationBinding']) expect(h.root.textContent).not.toContain(secret); + }); + + it('performs GET-only policy recovery after a bound ACK and a failed current policy read', async () => { + const h = await harness(); h.state.actor = 'both'; await h.open(); await h.action('policy-read'); await h.action('policy-prepare'); + let committed = false; + h.state.fault = async (path, response) => { + if (path !== '/api/support/admin/engineering/policy' || !response.ok) return; + if (h.calls.at(-1)?.method === 'POST') committed = true; + else if (committed) throw Object.assign(new Error('Synthetic current policy read outage'), { status: 503 }); + }; + await h.action('policy-save'); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(true); + const posts = h.writes().length; const before = await h.f.policyRows(); h.state.fault = undefined; + await h.action('retry-policy'); expect(h.writes()).toHaveLength(posts); + expect(h.panel.hasPending()).toBe(false); expect(await h.f.policyRows()).toEqual(before); + }); + + it('keeps a restricted evidence ACK known while protected GET recovery remains unreadable', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); h.evidence('uncertain'); await h.action('evidence'); + expect((await h.f.engineering.source()).state).toBe('restricted'); + expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(true); + const posts = h.writes().length; await h.action('retry-ticket'); + expect(h.writes()).toHaveLength(posts); expect(h.panel.hasPending()).toBe(true); + expect(h.node('evidence').disabled).toBe(true); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('retains owner A across A to peer B to A and never submits A under B credentials', async () => { + const h = await harness(); await h.open(); + h.state.fault = async (path, response) => { if (path.endsWith('/enroll') && response.ok) throw Object.assign(new Error('Synthetic ACK loss'), { status: 503 }); }; + await h.action('enroll'); const original = h.writes()[0]!; + h.state.actor = 'peer'; h.state.fault = undefined; await h.open(); await h.action('retry-ticket'); + expect(h.writes()).toHaveLength(1); expect(h.panel.pendingOwners()[0]?.actorSubject).toBe(h.f.principals.staff); + h.state.actor = 'staff'; await h.open(); await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original.body); expect(h.panel.hasPending()).toBe(false); + }); + + it('keeps ticket A ownership while another actual ticket is selected and never replays under ticket B', async () => { + const h = await harness(); await h.open(); + h.state.fault = async (path, response) => { if (path.endsWith('/enroll') && response.ok) throw Object.assign(new Error('Synthetic ACK loss'), { status: 503 }); }; + await h.action('enroll'); const original = h.writes()[0]!; h.state.fault = undefined; + await h.f.engineering.application.createCustomerTicket(h.f.engineering.actors.customer, + { ...h.f.engineering.command('second-ui-ticket'), ticketId: 'engineering-other-ticket', messageId: 'other-question', subject: 'Another fictional question', body: 'A separate public question.' }); + const second = await h.f.engineering.application.readStaffTicket(h.f.engineering.actors.staff, 'engineering-other-ticket'); + await h.panel.showTicket({ ticketId: second.ticket.id, revision: second.ticket.revision, actorSubject: h.f.principals.staff }); + await h.action('retry-ticket'); expect(h.writes()).toHaveLength(1); + expect(h.panel.pendingOwners()[0]?.ticketId).toBe(engineeringTicketId); + await h.open(); await h.action('retry-ticket'); + expect(h.writes().at(-1)?.path).toBe(original.path); expect(h.writes().at(-1)?.body).toBe(original.body); + }); + + it('withholds a genuine committed ACK after actual Support revocation and retains the original owner', async () => { + const h = await harness(); await h.open(); + h.f.hooks.commit = async () => { delete h.f.hooks.commit; await h.f.revoke('staff', SUPPORT_ROLE); }; + await h.action('enroll'); expect(h.panel.hasPending()).toBe(true); + expect((await h.f.engineering.source()).sourceGeneration).toBe(0); + expect(h.root.textContent).not.toContain(engineeringCanary); expect(h.node('evidence').disabled).toBe(true); + expect(h.panel.pendingOwners()[0]?.actorSubject).toBe(h.f.principals.staff); + }); +}); diff --git a/src/support-engineering-policy-recovery.test.ts b/src/support-engineering-policy-recovery.test.ts new file mode 100644 index 0000000..7ccd3e4 --- /dev/null +++ b/src/support-engineering-policy-recovery.test.ts @@ -0,0 +1,87 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it } from 'vitest'; +import { authenticate } from '../worker/src/api-auth'; +import { IDENTITY_ISSUER } from '../worker/src/identity-api'; +import { createSupportApi } from '../worker/src/support-api'; +import { composeSupportEngineeringHuman } from '../worker/src/support-engineering-composition'; +import { createSupportEngineeringHttpFixture } from '../worker/src/support-engineering-http-fixtures'; +import { BrowserNode } from './test-support-browser'; + +interface Panel { + showPolicy(value: { actorSubject: string }): Promise; + suspend(): void; hasPending(): boolean; + pendingOwners(): readonly { domain: string; actorSubject: string; ticketId?: string; acknowledged: boolean }[]; +} +async function fixture() { + // Deliberately never create a ticket: global policy recovery cannot depend + // on an old ticket, selected source or invented staff-ticket context. + const f = await createSupportEngineeringHttpFixture(); + const state = { enabled: true, lose: false, ids: 0, ticketReads: 0 }; + const shared = { ...f.host, application: f.engineering.application }; + const human = { enabled: () => state.enabled, + configuration: { application: { enabled: true }, repositories: f.options.repositories } }; + const api = createSupportApi({ ...f.options, application: shared.application, + createLimiter: shared.createLimiter, replyLimiter: shared.replyLimiter, + engineering: composeSupportEngineeringHuman(shared, f.options.logger, human) }); + const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string }[] = []; + function requestFor(path: string, init: RequestInit = {}) { + const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get('both')!); + if (init.method === 'POST') { headers.set('Origin', IDENTITY_ISSUER); headers.set('Sec-Fetch-Site', 'same-origin'); } + return new Request(IDENTITY_ISSUER + path, { ...init, headers }); + } + const vm: Record = { document: { createElement: (tag: string) => new BrowserNode(tag) }, AbortController, TextEncoder }; + runInNewContext(readFileSync(new URL('../public/staff-support-engineering.js', import.meta.url), 'utf8'), vm); + const panel = (vm.PegmaSupportEngineering as { createPanel(options: unknown): Panel }).createPanel({ root, + isEnabled: () => state.enabled, + async readSession() { + const value = await authenticate(requestFor('/api/identity/session'), f.options); + if (value === null) throw Object.assign(new Error('session_required'), { status: 401 }); + return { subject: value.link.subject, csrfToken: value.csrfToken }; + }, + async readCurrentTicket() { ++state.ticketReads; throw new Error('Global policy recovery must not read a ticket'); }, + async request(path: string, init: RequestInit = {}) { + calls.push({ path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}) }); + const response = await api(requestFor(path, init)); + if (path === '/api/support/admin/engineering/policy' && init.method === 'POST' && response.ok && state.lose) { + state.lose = false; throw Object.assign(new Error('Synthetic committed policy ACK loss'), { status: 503 }); + } + if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status }); + return response.json(); + }, commandId: () => 'GLOBAL-POLICY-EXACT-UPPERCASE-' + ++state.ids, + }); + const node = (key: string) => { + const value = root.all().find((item) => item.dataset.engineeringAction === key); + if (!value) throw new Error('Missing engineering control ' + key); return value; + }; + async function action(key: string) { + node(key).fire('click'); + for (let attempt = 0; attempt < 1200; attempt++) { + if (!node('policy-read').disabled) return; + await new Promise((resolve) => setTimeout(resolve, 2)); + } + throw new Error('Actual global policy event did not settle'); + } + return { f, state, panel, root, calls, node, action }; +} + +describe('global public engineering owner recovery', () => { + it('recovers exact policy intent through real root auth/SDK with no ticket or selection', async () => { + const h = await fixture(); await h.panel.showPolicy({ actorSubject: h.f.principals.both }); + expect(h.node('evidence').hidden).toBe(true); expect(h.node('enroll').hidden).toBe(true); + await h.action('policy-prepare'); h.state.lose = true; await h.action('policy-save'); + const original = h.calls.find((call) => call.method === 'POST' && call.path === '/api/support/admin/engineering/policy')!; + expect(h.panel.hasPending()).toBe(true); + expect(h.panel.pendingOwners()).toEqual([{ domain: 'policy', actorSubject: h.f.principals.both, acknowledged: false }]); + const before = await h.f.policyRows(); h.panel.suspend(); + await h.panel.showPolicy({ actorSubject: h.f.principals.both }); + expect(h.panel.hasPending()).toBe(true); await h.action('retry-policy'); + expect(h.panel.hasPending()).toBe(false); expect(await h.f.policyRows()).toEqual(before); + expect(h.calls.filter((call) => call.method === 'POST' && call.path === original.path).every((call) => call.body === original.body)).toBe(true); + expect(h.state.ids).toBe(1); expect(h.state.ticketReads).toBe(0); + expect(h.calls.every((call) => !call.path.includes('/tickets/'))).toBe(true); + expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); + for (const privateField of ['responsibilities', 'actorId', 'allowedTemplates', 'installationBinding']) + expect(h.root.textContent).not.toContain(privateField); + }); +}); diff --git a/src/support-engineering-review.test.ts b/src/support-engineering-review.test.ts new file mode 100644 index 0000000..122619f --- /dev/null +++ b/src/support-engineering-review.test.ts @@ -0,0 +1,172 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it } from 'vitest'; +import { authenticate } from '../worker/src/api-auth'; +import { IDENTITY_ISSUER } from '../worker/src/identity-api'; +import { createSupportApi } from '../worker/src/support-api'; +import { engineeringTicketId } from '../worker/src/support-engineering-fixtures'; +import { createSupportEngineeringHttpFixture, type EngineeringHttpActor } from '../worker/src/support-engineering-http-fixtures'; +import { createSupportEngineeringRuntime } from '../worker/src/support-engineering'; +import { BrowserNode } from './test-support-browser'; + +interface Panel { + showTicket(value: { ticketId: string; revision: number; actorSubject: string }): Promise; + refresh(): Promise; suspend(): void; hasPending(): boolean; + pendingOwners(): readonly { domain: string; actorSubject: string; ticketId?: string; acknowledged: boolean }[]; +} +async function harness() { + const f = await createSupportEngineeringHttpFixture(); + Object.assign(f.options, { reviewEnabled: () => true }); + await f.verified(); const checked = await f.prepared(); + const ticket = (await f.engineering.application.readStaffTicket(f.engineering.actors.staff, engineeringTicketId)).ticket; + const support = createSupportApi({ ...f.options, application: f.engineering.application, + createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); + const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string }[] = []; + const changes: unknown[] = []; + const state = { actor: 'staff' as EngineeringHttpActor, enabled: true, reviewEnabled: true, + fault: undefined as ((path: string, response: Response) => Promise) | undefined }; + function incoming(path: string, init: RequestInit = {}) { + const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get(state.actor)!); + if (init.method === 'POST') { headers.set('Origin', IDENTITY_ISSUER); headers.set('Sec-Fetch-Site', 'same-origin'); } + return new Request(IDENTITY_ISSUER + path, { ...init, headers }); + } + async function request(path: string, init: RequestInit = {}) { + calls.push({ path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}) }); + const original = incoming(path, init); + const response = /\/engineering(?:\/|$)/u.test(new URL(original.url).pathname) + ? await f.handle(original) : await support(original); + if (response === null) throw new Error('Expected an actual registered HTTP adapter'); + await state.fault?.(path, response); + if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status }); + return response.json(); + } + async function readSession() { + const value = await authenticate(incoming('/api/identity/session'), f.options); + if (value === null) throw Object.assign(new Error('session_required'), { status: 401 }); + return { subject: value.link.subject, csrfToken: value.csrfToken }; + } + const vm: Record = { document: { createElement: (tag: string) => new BrowserNode(tag) }, + AbortController, TextEncoder }; + runInNewContext(readFileSync(new URL('../public/staff-support-engineering.js', import.meta.url), 'utf8'), vm); + const factory = vm.PegmaSupportEngineering as { createPanel(options: unknown): Panel }; + const panel = factory.createPanel({ root, request, readSession, + readCurrentTicket: (id: string) => request('/api/support/admin/tickets/' + encodeURIComponent(id)), + isEnabled: () => state.enabled, isReviewEnabled: () => state.reviewEnabled, onPendingChange: (owners: unknown) => changes.push(owners) }); + function node(key: string) { + const found = root.all().find((item) => item.dataset.engineeringAction === key); + if (found === undefined) throw new Error('Missing engineering action ' + key); return found; + } + async function action(key: string) { + node(key).fire('click'); + for (let attempt = 0; attempt < 1200; attempt++) { + if (!node('refresh').disabled) return; + await new Promise((resolve) => setTimeout(resolve, 2)); + } + throw new Error('Actual engineering event failed to settle'); + } + const open = () => panel.showTicket({ ticketId: engineeringTicketId, revision: ticket.revision, actorSubject: f.principals[state.actor] }); + return { f, checked, root, state, calls, changes, panel, node, action, open, + writes: () => calls.filter((item) => item.method === 'POST') }; +} + +describe('checked human engineering review panel through real SDK and HTTP adapters', () => { + it('renders only the exact checked proposal as inert text and requires an explicit approve action', async () => { + const h = await harness(); expect(h.calls).toEqual([]); expect(h.node('approve').disabled).toBe(true); + await h.open(); expect(h.node('approve').disabled).toBe(true); await h.action('proposal'); + expect(h.writes()).toEqual([]); expect(h.node('approve').disabled).toBe(false); expect(h.node('reject').disabled).toBe(false); + const proposal = h.checked.proposal; if (proposal === undefined) throw new Error('Real proposal missing'); + expect(h.root.textContent).toContain(proposal.request.bundle.title); + for (const privateText of [proposal.checksReceipt, proposal.request.repository.installationBinding, + h.f.engineering.configuration.dataControls.accountRef, 'expectedWorkGeneration', 'correlationId', 'modelAttempts']) + expect(h.root.textContent).not.toContain(privateText); + expect(h.root.all().some((item) => item.tagName === 'img' || item.tagName === 'a')).toBe(false); + const calls = h.f.engineering.state.modelCalls; + await h.action('approve'); expect(h.writes()).toHaveLength(1); expect(h.writes()[0]?.path.endsWith('/review')).toBe(true); + const packet = JSON.parse(h.writes()[0]?.body ?? '{}'); + expect(packet.intent.command).toMatchObject({ decision: 'approve', proposalHash: proposal.proposalHash, + expectedWorkGeneration: h.checked.workGeneration, sourceGeneration: h.checked.sourceGeneration }); + expect(typeof packet.intent.command.commandId).toBe('string'); expect(typeof packet.intent.command.correlationId).toBe('string'); + expect((await h.f.work()).status).toBe('approved'); expect(h.panel.hasPending()).toBe(false); + expect(h.f.engineering.state.modelCalls).toBe(calls); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('requires an explicit reject and retains the complete chosen SDK command', async () => { + const h = await harness(); await h.open(); await h.action('proposal'); + expect(h.writes()).toEqual([]); await h.action('reject'); + expect(h.writes()).toHaveLength(1); + const body = JSON.parse(h.writes()[0]?.body ?? '{}'); + expect(body.intent.command).toMatchObject({ decision: 'reject', proposalHash: h.checked.proposal?.proposalHash, + expectedWorkGeneration: h.checked.workGeneration, sourceGeneration: h.checked.sourceGeneration }); + expect((await h.f.work()).approval).toMatchObject({ decision: 'reject' }); + expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('retains byte-identical complete command after an actually committed review loses its HTTP acknowledgement', async () => { + const h = await harness(); await h.open(); await h.action('proposal'); + h.state.fault = async (path, response) => { + if (path.endsWith('/review') && response.ok) throw Object.assign(new Error('Synthetic lost response AFTER SDK commit'), { status: 503 }); + }; + await h.action('approve'); const original = h.writes()[0]?.body; + expect((await h.f.work()).status).toBe('approved'); expect(h.panel.hasPending()).toBe(true); + expect(h.panel.pendingOwners()).toEqual([{ domain: 'ticket', actorSubject: h.f.principals.staff, + ticketId: engineeringTicketId, acknowledged: false }]); + h.f.engineering.metadata.clear(); h.f.engineering.state.checksReadable = false; + h.state.fault = undefined; h.panel.suspend(); await h.open(); + const before = h.calls.length; const rows = await h.f.rows(); + await h.action('retry-ticket'); + expect(h.calls[before]).toMatchObject({ method: 'POST', body: original }); + expect(h.calls[before]?.path.endsWith('/review')).toBe(true); + expect(h.writes().at(-1)?.body).toBe(original); expect(h.panel.hasPending()).toBe(false); + expect(await h.f.rows()).toEqual(rows); expect(h.f.engineering.state.creates).toEqual([]); + expect(JSON.stringify(h.changes)).not.toContain('proposalHash'); expect(JSON.stringify(h.changes)).not.toContain('commandId'); + }); + + it('keeps an unavailable, never-accepted review unknown across GET refresh and never fabricates cancellation', async () => { + const h = await harness(); await h.open(); await h.action('proposal'); + h.f.state.runtime = createSupportEngineeringRuntime({ application: h.f.engineering.application, clock: h.f.engineering.clock, + staffAccess: { resolve: (id) => h.f.resolve(id) } }); + const rows = await h.f.rows(); await h.action('approve'); const original = h.writes()[0]?.body; + expect(h.panel.hasPending()).toBe(true); expect(await h.f.rows()).toEqual(rows); + await h.panel.refresh(); expect(h.panel.hasPending()).toBe(true); + expect(h.node('approve').disabled).toBe(true); expect(h.node('proposal').disabled).toBe(true); + await h.action('reject'); expect(h.writes()).toHaveLength(1); + await h.action('retry-ticket'); expect(h.writes().at(-1)?.body).toBe(original); + expect(h.panel.hasPending()).toBe(true); expect(await h.f.rows()).toEqual(rows); + }); + + it('clears proposal bytes and blocks approve if the closing actual session is destroyed during its GET', async () => { + const h = await harness(); await h.open(); const rows = await h.f.rows(); + h.state.fault = async (path, response) => { if (path.includes('/proposal?') && response.ok) await h.f.destroy('staff'); }; + await h.action('proposal'); expect(h.node('approve').disabled).toBe(true); + const title = h.checked.proposal?.request.bundle.title; + if (title === undefined) throw new Error('Actual proposal title missing'); + expect(h.root.textContent).not.toContain(title); + expect(h.writes()).toEqual([]); expect(h.panel.hasPending()).toBe(false); expect(await h.f.rows()).toEqual(rows); + }); + + it('never lends an unresolved actor-owned review packet to another current staff actor', async () => { + const h = await harness(); await h.open(); await h.action('proposal'); + h.state.fault = async (path, response) => { if (path.endsWith('/review') && response.ok) + throw Object.assign(new Error('lost_ack'), { status: 503 }); }; + await h.action('approve'); const original = h.writes()[0]?.body; + h.state.fault = undefined; h.state.actor = 'peer'; await h.open(); + expect(h.node('retry-ticket').hidden).toBe(true); await h.action('retry-ticket'); expect(h.writes()).toHaveLength(1); + expect(h.panel.pendingOwners()[0]).toMatchObject({ actorSubject: h.f.principals.staff, acknowledged: false }); + h.state.actor = 'staff'; await h.open(); await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original); expect(h.panel.hasPending()).toBe(false); + }); + + it('the independent review switch is OFF while ordinary engineering intake remains enabled', async () => { + const h = await harness(); h.state.reviewEnabled = false; await h.open(); + const count = h.calls.length; expect(h.node('proposal').disabled).toBe(true); expect(h.node('approve').disabled).toBe(true); + await h.action('proposal'); await h.action('approve'); expect(h.calls).toHaveLength(count); + expect(h.writes()).toEqual([]); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('default intake OFF causes no requests or model work', async () => { + const h = await harness(); const modelCalls = h.f.engineering.state.modelCalls; + h.state.enabled = false; await h.open(); expect(h.calls).toEqual([]); expect(h.root.hidden).toBe(true); + expect(h.node('approve').disabled).toBe(true); expect(h.node('reject').disabled).toBe(true); + expect(h.f.engineering.state.modelCalls).toBe(modelCalls); expect(h.f.engineering.state.creates).toEqual([]); + }); +}); diff --git a/src/support-engineering-ui.test.ts b/src/support-engineering-ui.test.ts new file mode 100644 index 0000000..fd8fde2 --- /dev/null +++ b/src/support-engineering-ui.test.ts @@ -0,0 +1,136 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it } from 'vitest'; +import { authenticate } from '../worker/src/api-auth'; +import { IDENTITY_ISSUER } from '../worker/src/identity-api'; +import { createSupportApi } from '../worker/src/support-api'; +import { engineeringTicketId } from '../worker/src/support-engineering-fixtures'; +import { createSupportEngineeringHttpFixture, type EngineeringHttpActor } from '../worker/src/support-engineering-http-fixtures'; +import { BrowserNode } from './test-support-browser'; + +interface Panel { + showTicket(value: { ticketId: string; revision: number; actorSubject: string }): Promise; + refresh(): Promise; readPolicy(): Promise; suspend(): void; hasPending(): boolean; + pendingOwners(): readonly { domain: string; actorSubject: string; ticketId?: string; acknowledged: boolean }[]; +} +async function harness() { + const f = await createSupportEngineeringHttpFixture(); const ticket = await f.legacyTicket(); + const support = createSupportApi({ ...f.options, application: f.engineering.application, + createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); + const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string }[] = []; + const changes: unknown[] = []; + const state = { actor: 'staff' as EngineeringHttpActor, enabled: true, ids: 0, sessionReads: 0, + fault: undefined as ((path: string, response: Response) => Promise) | undefined }; + function incoming(path: string, init: RequestInit = {}) { + const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get(state.actor)!); + if (init.method === 'POST') { headers.set('Origin', IDENTITY_ISSUER); headers.set('Sec-Fetch-Site', 'same-origin'); } + return new Request(IDENTITY_ISSUER + path, { ...init, headers }); + } + async function request(path: string, init: RequestInit = {}) { + calls.push({ path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}) }); + const request = incoming(path, init); + const pathname = new URL(path, IDENTITY_ISSUER).pathname; + const engineering = /^\/api\/support\/admin\/tickets\/[^/]+\/engineering(?:\/|$)/u.test(pathname) || + /^\/api\/support\/admin\/engineering(?:\/|$)/u.test(pathname); + const response = engineering ? await f.handle(request) : await support(request); + if (response === null) throw new Error('Expected a registered adapter path'); + await state.fault?.(path, response); + if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status }); + return response.json(); + } + async function readSession() { + state.sessionReads += 1; + const value = await authenticate(incoming('/api/identity/session'), f.options); + if (value === null) throw Object.assign(new Error('session_required'), { status: 401 }); + return { subject: value.link.subject, csrfToken: value.csrfToken }; + } + const vm: Record = { document: { createElement: (tag: string) => new BrowserNode(tag) }, + AbortController, TextEncoder }; + runInNewContext(readFileSync(new URL('../public/staff-support-engineering.js', import.meta.url), 'utf8'), vm); + const factory = vm.PegmaSupportEngineering as { createPanel(options: unknown): Panel }; + const panel = factory.createPanel({ root, request, readSession, + readCurrentTicket: (id: string) => request('/api/support/admin/tickets/' + encodeURIComponent(id)), + isEnabled: () => state.enabled, commandId: () => 'PUBLIC-ENGINEERING-UPPERCASE-' + ++state.ids, + onPendingChange: (owners: unknown) => changes.push(owners) }); + function node(key: string, field = false) { + const found = root.all().find((item) => item.dataset[field ? 'engineeringField' : 'engineeringAction'] === key); + if (!found) throw new Error('Missing engineering control ' + key); return found; + } + async function settle() { + for (let attempt = 0; attempt < 1200; attempt++) { + if (!node('refresh').disabled) return; + await new Promise((resolve) => setTimeout(resolve, 2)); + } + throw new Error('Engineering event did not settle'); + } + async function action(key: string) { node(key).fire('click'); await settle(); } + const open = () => panel.showTicket({ ticketId: engineeringTicketId, revision: ticket.revision, actorSubject: f.principals[state.actor] }); + return { f, root, calls, changes, state, panel, node, action, open, + writes: () => calls.filter((call) => call.method === 'POST'), + field: (key: string) => node(key, true), + message: () => root.all().find((item) => item.dataset.engineeringMessage === 'engineering-question')! }; +} + +describe('standalone public engineering panel with actual authority adapters', () => { + it('is inert before current feature and staff-ticket callbacks, without processor or dispatch controls', async () => { + const h = await harness(); expect(h.calls).toEqual([]); + h.state.enabled = false; await h.open(); expect(h.calls).toEqual([]); expect(h.root.hidden).toBe(true); + expect(h.state.sessionReads).toBe(0); + const actions = h.root.all().map((node) => node.dataset.engineeringAction).filter(Boolean); + for (const forbidden of ['process', 'dispatch', 'file']) expect(actions).not.toContain(forbidden); + expect(h.node('approve').disabled).toBe(true); expect(h.node('reject').disabled).toBe(true); + expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('requires explicit sensitivity and actual public message selections before minting evidence IDs', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); + expect(h.root.all().some((item) => item.dataset.engineeringMessage === 'engineering-note')).toBe(false); + h.field('expected').value = 'Rows should export.'; h.field('actual').value = 'The file is empty.'; + h.field('steps').value = 'Export the workspace.'; h.field('verification').value = 'PUBLIC-STAFF-ATTESTATION'; + h.message().checked = true; + const before = h.writes().length; const ids = h.state.ids; + await h.action('evidence'); expect(h.writes()).toHaveLength(before); expect(h.state.ids).toBe(ids); + h.field('security').value = 'ordinary'; h.message().value = 'engineering-note'; + await h.action('evidence'); expect(h.writes()).toHaveLength(before); expect(h.state.ids).toBe(ids); + h.message().value = 'engineering-question'; await h.action('evidence'); + const packet = JSON.parse(h.writes().at(-1)?.body ?? '{}'); + expect(packet).toMatchObject({ security: 'ordinary', visibleMessageIds: ['engineering-question'], commandId: 'PUBLIC-ENGINEERING-UPPERCASE-2' }); + expect((await h.f.engineering.source()).state).toBe('eligible'); + expect(h.f.engineering.state.modelCalls).toBe(0); + }); + + it('hides policy editing until current Admin and Support policy GET succeeds', async () => { + const h = await harness(); await h.open(); await h.action('policy-read'); + expect(h.node('policy-save').disabled).toBe(true); + expect(h.root.textContent).not.toContain('synthetic-repository-101'); + h.state.actor = 'admin'; await h.open(); await h.action('policy-read'); + expect(h.node('policy-save').disabled).toBe(true); expect(h.root.textContent).not.toContain('synthetic-repository-101'); + h.state.actor = 'both'; h.f.engineering.state.enabled = false; await h.open(); await h.action('policy-read'); + expect(h.root.textContent).toContain('synthetic-repository-101'); + expect(h.node('policy-prepare').disabled).toBe(false); + expect(h.node('policy-save').disabled).toBe(true); + await h.action('policy-prepare'); + expect(h.node('policy-save').disabled).toBe(false); + for (const opaque of ['installationBinding', 'responsibilities', 'allowedTemplates', 'actorId', 'expectedGeneration']) + expect(h.root.textContent).not.toContain(opaque); + const prepared = h.writes().at(-1)!; expect(prepared.path.endsWith('/policy/prepare')).toBe(true); + await h.action('policy-save'); + const saved = JSON.parse(h.writes().at(-1)?.body ?? '{}'); + expect(Object.keys(saved)).toEqual(['intent']); + expect(saved.intent.commandId).toBe(JSON.parse(prepared.body ?? '{}').commandId); + expect(h.panel.hasPending()).toBe(false); + expect(h.f.engineering.state.modelCalls).toBe(0); + }); + + it('clears private presentation after feature loss while retaining the unresolved owned packet', async () => { + const h = await harness(); await h.open(); + h.state.fault = async (path, response) => { if (path.endsWith('/enroll') && response.ok) throw Object.assign(new Error('lost_ack'), { status: 503 }); }; + await h.action('enroll'); const original = h.writes()[0]?.body; + expect(h.panel.pendingOwners()).toEqual([{ domain: 'ticket', actorSubject: h.f.principals.staff, ticketId: engineeringTicketId, acknowledged: false }]); + h.state.enabled = false; await h.panel.refresh(); + expect(h.root.hidden).toBe(true); expect(h.panel.hasPending()).toBe(true); + h.state.enabled = true; h.state.fault = undefined; await h.open(); await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original); expect(h.panel.hasPending()).toBe(false); + expect(JSON.stringify(h.changes)).not.toContain('commandId'); + }); +}); diff --git a/worker/src/api-auth.ts b/worker/src/api-auth.ts index be4250e..5ac1b19 100644 --- a/worker/src/api-auth.ts +++ b/worker/src/api-auth.ts @@ -170,8 +170,12 @@ export function boundedString( export async function readJson( request: Request, - options?: { timeoutMs: number }, + options?: { timeoutMs?: number; maxBytes?: number }, ): Promise { + const maxBytes = options?.maxBytes ?? JSON_LIMIT; + if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > 128 * 1024) { + throw new RangeError('Invalid JSON body limit'); + } const contentType = request.headers.get('Content-Type')?.split(';', 1)[0]; if (contentType?.trim().toLowerCase() !== 'application/json') { throw new ApiError(415, 'json_required'); @@ -179,7 +183,7 @@ export async function readJson( const declaredLength = request.headers.get('Content-Length'); if ( declaredLength !== null && - (!/^\d+$/u.test(declaredLength) || Number(declaredLength) > JSON_LIMIT) + (!/^\d+$/u.test(declaredLength) || Number(declaredLength) > maxBytes) ) { throw new ApiError(413, 'request_too_large'); } @@ -246,7 +250,7 @@ export async function readJson( break; } length += chunk.value.byteLength; - if (length > JSON_LIMIT) { + if (length > maxBytes) { if (deadline === undefined) await reader.cancel(); throw new ApiError(413, 'request_too_large'); } diff --git a/worker/src/api-json-limits.test.ts b/worker/src/api-json-limits.test.ts new file mode 100644 index 0000000..7f2f2c1 --- /dev/null +++ b/worker/src/api-json-limits.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { JSON_LIMIT, readJson } from './api-auth'; + +function request(body: string, declaredLength?: number): Request { + return new Request('https://pegma.dev/api/support/admin/engineering/policy', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(declaredLength === undefined + ? {} + : { 'Content-Length': String(declaredLength) }), + }, + body, + }); +} + +describe('explicit JSON byte limits', () => { + it('keeps the existing default while allowing a bounded larger policy snapshot', async () => { + const text = '界'.repeat(24_000); + const body = JSON.stringify(text); + expect(body.length).toBeLessThan(JSON_LIMIT); + expect(new TextEncoder().encode(body).byteLength).toBeGreaterThan(JSON_LIMIT); + await expect(readJson(request(body), { timeoutMs: 1_000 })).rejects.toMatchObject({ + status: 413, + code: 'request_too_large', + }); + await expect( + readJson(request(body), { timeoutMs: 1_000, maxBytes: 128 * 1024 }), + ).resolves.toBe(text); + }); + + it('checks streamed bytes even when Content-Length declares a smaller body', async () => { + const body = JSON.stringify('x'.repeat(128 * 1024 - 1)); + await expect( + readJson(request(body, 2), { timeoutMs: 1_000, maxBytes: 128 * 1024 }), + ).rejects.toMatchObject({ status: 413, code: 'request_too_large' }); + }); + + it('accepts the exact explicit boundary and rejects a larger declared length', async () => { + const limit = 128 * 1024; + const text = 'x'.repeat(limit - 2); + await expect( + readJson(request(JSON.stringify(text), limit), { + timeoutMs: 1_000, + maxBytes: limit, + }), + ).resolves.toBe(text); + await expect( + readJson(request('{}', limit + 1), { timeoutMs: 1_000, maxBytes: limit }), + ).rejects.toMatchObject({ status: 413, code: 'request_too_large' }); + }); + + it.each([0, -1, 1.5, NaN, Infinity, 128 * 1024 + 1])( + 'refuses an invalid or unbounded configured limit: %s', + async (maxBytes) => { + await expect(readJson(request('{}'), { maxBytes })).rejects.toBeInstanceOf( + RangeError, + ); + }, + ); +}); diff --git a/worker/src/index.ts b/worker/src/index.ts index b00014c..2f90875 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -1,3 +1,6 @@ +import { composeSupportEngineeringHuman, supportEngineeringHumanEnabled, supportEngineeringIntakeOptions, + type SupportEngineeringHumanComposition } from './support-engineering-composition'; +import { isSupportEngineeringRequest } from './support-engineering-router'; import { createDetailCheck, createProcessCheck, @@ -34,6 +37,7 @@ import { createAdminLookupLimiter, createAdminMutationLimiter, createProductionSupportRuntime, + createSupportRuntime, createProductionSupportMaintenanceRuntime, probeSupportStore, supportHealthProbeEnabled, @@ -71,7 +75,8 @@ type AppEnv = Omit & /** Trusted source composition only; no product/check/source ports are invented here. */ export interface SupportLearningReviewWorkerComposition { readonly enabled: () => boolean; - create(environment: AppEnv, logger: ReturnType): { + create(environment: AppEnv, logger: ReturnType, + engineering?: SupportEngineeringHumanComposition): { /** The actual configured Support API, including its fresh staff-detail hints. */ readonly api: (request: Request) => Promise; readonly queue: ReturnType; @@ -105,14 +110,21 @@ function createKnowledgeProjectionStore(environment: { function createSupportHandler( env: AppEnv, logger: ReturnType, + engineering: SupportEngineeringHumanComposition = {}, ) { - const identityRuntime = createProductionIdentityRuntime(env, logger); - const supportRuntime = createProductionSupportRuntime(env, { + const configured = supportEngineeringHumanEnabled(engineering); + const identityRuntime = createProductionIdentityRuntime(env, logger, configured ? 512 : undefined); + const intake = supportEngineeringIntakeOptions(engineering); + const dependencies = { sessions: identityRuntime.sessions, identity: identityRuntime.identity, identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, logger, - }); + ...(intake === undefined ? {} : { engineering: intake }), + }; + const supportRuntime = configured + ? createSupportRuntime({ ...dependencies, store: identityRuntime.store }) + : createProductionSupportRuntime(env, dependencies); const api = createSupportApi({ application: supportRuntime.application, sessions: supportRuntime.sessions, @@ -121,6 +133,7 @@ function createSupportHandler( createLimiter: supportRuntime.createLimiter, replyLimiter: supportRuntime.replyLimiter, logger, + ...(configured ? { engineering: composeSupportEngineeringHuman(supportRuntime, logger, engineering) } : {}), // The stored Support ROLE is the only staff gate (fail closed). roleStore: supportRuntime.roleStore, bootstrapPrincipals: parseBootstrapPrincipals(env), @@ -141,12 +154,25 @@ function createSupportHandler( return { supportRuntime, api, adminApi }; } +/** Request-local optional human composition used by the registered Worker route. */ +export function createSupportRequestHandler(env: AppEnv, logger: ReturnType, + engineering: SupportEngineeringHumanComposition = {}) { + return async (request: Request): Promise => { + if (isSupportEngineeringRequest(new URL(request.url).pathname) && !supportEngineeringHumanEnabled(engineering)) + return Response.json({ error: 'not_found' }, { status: 404, headers: { 'Cache-Control': 'no-store' } }); + return createSupportHandler(env, logger, engineering).api(request); + }; +} + /** * Thin Workers slice that proves pegma.dev's Pegma Logger wiring: * Cloudflare Workers Logs (via @pegma/logger-cloudflare + observability) * teed with Datadog when DATADOG_API_KEY is set. */ -export function createWorker(options: { readonly learningReviews?: SupportLearningReviewWorkerComposition } = {}) { +export function createWorker(options: { + readonly learningReviews?: SupportLearningReviewWorkerComposition; + readonly engineering?: SupportEngineeringHumanComposition; +} = {}) { return { async fetch( request: Request, @@ -401,10 +427,12 @@ return { if (path.startsWith('/api/support/')) { try { + if (isSupportEngineeringRequest(path)) + return await createSupportRequestHandler(env, logger, options.engineering)(request); const reviews = options.learningReviews; if (reviews !== undefined && learningReviewsEnabled(env, reviews)) - return await reviews.create(env, logger).api(request); - return await createSupportHandler(env, logger).api(request); + return await reviews.create(env, logger, options.engineering).api(request); + return await createSupportRequestHandler(env, logger, options.engineering)(request); } catch (error) { logger.log('error', 'support.runtime_unavailable', { error: error instanceof Error ? error.name : 'unknown', diff --git a/worker/src/support-access.test.ts b/worker/src/support-access.test.ts index ebb83d5..3e02ac1 100644 --- a/worker/src/support-access.test.ts +++ b/worker/src/support-access.test.ts @@ -37,6 +37,11 @@ const staffPermissions = [ supportPermissions.learningEvidenceSubmit, supportPermissions.learningReview, supportPermissions.learningWithdraw, + supportPermissions.engineeringRead, + supportPermissions.engineeringEvidenceSubmit, + supportPermissions.engineeringReview, + supportPermissions.engineeringWithdraw, + supportPermissions.engineeringPolicyRead, ]; function roleStore() { @@ -111,7 +116,13 @@ describe('Support human-control grants', () => { staff?.permissions .filter((permission) => permission.startsWith('support.')) .sort(), - ).toEqual([...customerPermissions, ...staffPermissions].sort()); + ).toEqual([ + ...customerPermissions, + ...staffPermissions, + ...(roles.some((role) => role === ADMIN_ROLE) + ? [supportPermissions.engineeringPolicyManage] + : []), + ].sort()); expect(staff?.permissions).not.toContain(supportPermissions.learningProcess); const current = await store.getRoleAssignment( diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts index 33e7091..f7024be 100644 --- a/worker/src/support-access.ts +++ b/worker/src/support-access.ts @@ -31,6 +31,11 @@ export const SUPPORT_STAFF_PERMISSIONS = Object.freeze([ supportPermissions.learningEvidenceSubmit, supportPermissions.learningReview, supportPermissions.learningWithdraw, + supportPermissions.engineeringRead, + supportPermissions.engineeringEvidenceSubmit, + supportPermissions.engineeringReview, + supportPermissions.engineeringWithdraw, + supportPermissions.engineeringPolicyRead, ] as const); /** The support-operator role name (docs/ROLE_ADOPTION_PLAN.md). */ @@ -108,10 +113,11 @@ export const APPLICATION_SCOPE = Object.freeze({ * administrator-only agent linking without replacing any stored assignment. * Version 4 adds owned human requests and explicit Support takeover. * Version 5 adds human learning review; processing and KB grants stay separate. + * Version 6 adds human engineering intake and explicit repository policy grants. */ export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({ schemaVersion: 1, - version: 'pegma.dev-policy-5', + version: 'pegma.dev-policy-6', defaults: [...SUPPORT_CUSTOMER_PERMISSIONS, knowledgePermissions.articleRead], roles: Object.freeze({ [SUPPORT_ROLE]: [...SUPPORT_STAFF_PERMISSIONS], @@ -120,6 +126,8 @@ export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({ ...ADMIN_PERMISSIONS, AGENT_LINK_PERMISSION, ...KNOWLEDGE_ADMIN_PERMISSIONS, + supportPermissions.engineeringPolicyRead, + supportPermissions.engineeringPolicyManage, ], }), }); diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index ee56431..b20351f 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -1,3 +1,4 @@ +import { createSupportEngineeringRouter, type SupportEngineeringRouterOptions } from './support-engineering-router'; import type { Logger, PrincipalId } from '@pegma/spine'; import type { SessionStore } from '@pegma/sessions'; import type { DurableRateLimiter } from '@pegma/rate-limit'; @@ -139,6 +140,7 @@ interface SupportApiOptions { readonly learningEnabled?: () => boolean; /** Additive trusted staged-review capability; it never enables learning itself. */ readonly learningStagedReviewsEnabled?: () => boolean; + readonly engineering?: SupportEngineeringRouterOptions; } async function requireAuthentication( @@ -753,6 +755,15 @@ async function stableBrowserMutation( export function createSupportApi( options: SupportApiOptions, ): (request: Request) => Promise { + const engineeringRouter = createSupportEngineeringRouter(options.engineering); + const engineeringReady = (): boolean => { + if (options.engineering?.configuration === undefined) return false; + try { return options.engineering.enabled?.() === true; } catch { return false; } + }; + const engineeringReviewReady = (): boolean => { + if (!engineeringReady()) return false; + try { return options.engineering?.configuration?.reviewEnabled?.() === true; } catch { return false; } + }; if (options.learningHandler !== undefined && options.learningRuntime !== undefined) throw new TypeError('Choose one trusted Support learning composition'); const learningHandler = options.learningHandler ?? ( @@ -780,6 +791,8 @@ export function createSupportApi( const url = new URL(request.url); const path = url.pathname; try { + const engineeringResponse = await engineeringRouter(request); + if (engineeringResponse !== null) return engineeringResponse; if (LEARNING_NAMESPACE.test(path)) { if (!learningReady()) throw new ApiError(404, 'not_found'); let response: Response | null; @@ -950,7 +963,7 @@ export function createSupportApi( request.method === 'GET' ) { const ticketId = adminMatch[1]!; - if (typeof options.learningEnabled === 'function') { + if (typeof options.learningEnabled === 'function' || options.engineering !== undefined) { // This optional hint comes from current real stored Support authority, // active Identity and the same live session, never browser role fields. const browser = supportHumanBrowser(request, { @@ -967,6 +980,14 @@ export function createSupportApi( return json({ ...staffTicketView(view), csrfToken: final.authenticated.csrfToken, + ...(options.engineering === undefined ? {} : { + engineeringEnabled: engineeringReady() && [supportPermissions.engineeringRead, + supportPermissions.engineeringEvidenceSubmit, supportPermissions.engineeringWithdraw, + supportPermissions.engineeringPolicyRead, supportPermissions.engineeringPolicyManage] + .some((permission) => hasPermission(final.access, permission)), + engineeringReviewEnabled: engineeringReviewReady() && + hasPermission(final.access, supportPermissions.engineeringReview), + }), learningEnabled: learningReady() && hasPermission(final.access, supportPermissions.learningRead), learningReviewRecoveryEnabled: learningReady() && hasPermission(final.access, supportPermissions.learningReview) && diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index 4da02fd..d766f06 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -23,6 +23,7 @@ import { ticketNumbers, type SupportDeskApplication, type ResolutionLearningOptions, + type EngineeringOptions, } from '@pegma/support-desk-application'; import { defineTemplate } from '@pegma/support-desk-templates'; import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; @@ -182,6 +183,7 @@ export interface SupportCompositionOptions { readonly createLimiter?: DurableRateLimiter; readonly replyLimiter?: DurableRateLimiter; readonly resolutionLearning?: ResolutionLearningOptions; + readonly engineering?: EngineeringOptions; } export interface SupportRuntime { @@ -327,6 +329,7 @@ export function createSupportRuntime( allowedCategories: PEGMA_SUPPORT_CATEGORIES, queueTerminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, ...(options.resolutionLearning === undefined ? {} : { resolutionLearning: options.resolutionLearning }), + ...(options.engineering === undefined ? {} : { engineering: options.engineering }), }); // Audited role store on the SAME Store, partitioned by this host's diff --git a/worker/src/support-engineering-composition.test.ts b/worker/src/support-engineering-composition.test.ts new file mode 100644 index 0000000..845a545 --- /dev/null +++ b/worker/src/support-engineering-composition.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import { createSupportApi } from './support-api'; +import { createSupportRuntime } from './support-desk'; +import { SUPPORT_ROLE } from './support-access'; +import { createWorker, createSupportRequestHandler } from './index'; +import { composeSupportEngineeringHuman, supportEngineeringIntakeOptions } from './support-engineering-composition'; +import { createSupportEngineeringHttpFixture, engineeringHttpObject, engineeringHttpResult } from './support-engineering-http-fixtures'; +import { engineeringTicketId } from './support-engineering-fixtures'; + +async function fixture() { + const f = await createSupportEngineeringHttpFixture(); const ticket = await f.legacyTicket(); + const state = { enabled: true }; + const human = { enabled: () => state.enabled, configuration: { application: { enabled: true }, repositories: f.options.repositories } }; + const intake = supportEngineeringIntakeOptions(human); + if (intake === undefined) throw new Error('Expected explicit synthetic human intake configuration'); + const runtime = createSupportRuntime({ store: f.host.store, identity: f.identity, sessions: f.sessions, + identityLinkFromClaims: f.options.identityLinkFromClaims, logger: f.options.logger, + engineering: intake }); + const engineering = composeSupportEngineeringHuman(runtime, f.options.logger, human); + const api = createSupportApi({ ...f.options, application: runtime.application, roleStore: runtime.roleStore, createLimiter: runtime.createLimiter, + replyLimiter: runtime.replyLimiter, engineering }); + return { f, ticket, state, human, runtime, engineering, api }; +} + +describe('optional public engineering root composition', () => { + it.each(['absent', 'flag-only', 'false', 'throwing'] as const)('keeps %s entry composition OFF before any production dependencies', async (mode) => { + const configuration = { application: { enabled: true }, repositories: [] }; + const options = mode === 'absent' ? {} : mode === 'flag-only' ? { enabled: () => true } + : { configuration, enabled: () => { if (mode === 'throwing') throw new Error('Synthetic flag outage'); return false; } }; + // No fake Store/auth: a disabled path must not touch these absent bindings. + const env = {} as Parameters[0]; + const route = createSupportRequestHandler(env, { log() {} }, options); + for (const suffix of ['', '/evidence', '/unknown']) { + const response = await route(new Request('https://pegma.dev/api/support/admin/tickets/engineering-ticket/engineering' + suffix)); + expect(response.status).toBe(404); expect(await response.json()).toEqual({ error: 'not_found' }); + } + }); + + it('keeps the registered Worker engineering namespace OFF before absent production bindings', async () => { + const worker = createWorker(); + const env = {} as Parameters[1]; + const pending: Promise[] = []; + const context: ExecutionContext = { + waitUntil(promise) { pending.push(promise); }, + passThroughOnException() { throw new Error('Disabled engineering must finish in its own handler'); }, + get exports(): Cloudflare.Exports { throw new Error('Disabled engineering must not read Worker exports'); }, + props: {}, + get tracing(): Tracing { throw new Error('Disabled engineering must not initialize tracing'); }, + }; + const response = await worker.fetch(new Request('https://pegma.dev/api/support/admin/engineering/policy'), env, context); + await Promise.all(pending); + expect(response.status).toBe(404); expect(await response.json()).toEqual({ error: 'not_found' }); + }); + + it('uses the real shared Store, application, Identity/session roles and limiter for actual human enrollment', async () => { + const { f, ticket, runtime, api } = await fixture(); + expect(runtime.store).toBe(f.host.store); expect(runtime.sessions).toBe(f.sessions); expect(runtime.identity).toBe(f.identity); + const response = await api(f.request('enroll', { commandId: 'ROOT-ENROLL-EXACT-UPPERCASE', expectedRevision: ticket.revision })); + expect(response.status).toBe(200); + expect(engineeringHttpResult(await engineeringHttpObject(response))).toMatchObject({ ticketId: engineeringTicketId, sourceGeneration: 0 }); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it('computes capability from fresh real staff authority and retains both independent defaults', async () => { + const { f, state, api } = await fixture(); + const detail = () => api(new Request('https://pegma.dev/api/support/admin/tickets/' + engineeringTicketId, + { headers: { Cookie: f.cookies.get('staff')! } })); + const enabled = await detail(); expect(enabled.status).toBe(200); + expect(await enabled.json()).toMatchObject({ engineeringEnabled: true }); + state.enabled = false; + expect(await (await detail()).json()).toMatchObject({ engineeringEnabled: false }); + state.enabled = true; await f.revoke('staff', SUPPORT_ROLE); + expect((await detail()).status).toBe(403); + expect(f.engineering.state.modelCalls).toBe(0); + }); + + it('keeps unknown engineering subpaths owned and leaves model-OFF policy disable available to current Admin+Support', async () => { + const { f, api } = await fixture(); f.engineering.state.enabled = false; + const unknown = await api(new Request('https://pegma.dev/api/support/admin/tickets/' + engineeringTicketId + '/engineering/dispatch')); + expect(unknown.status).toBe(404); + const current = await api(f.request('policy', undefined, 'both')); + expect(current.status).toBe(200); const value = engineeringHttpResult(await engineeringHttpObject(current)); + const response = await api(f.request('policy/disable', { commandId: 'ROOT-DISABLE-EXACT-UPPERCASE', expectedGeneration: value.generation }, 'both')); + expect(response.status).toBe(200); expect(engineeringHttpResult(await engineeringHttpObject(response)).enabled).toBe(false); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); +}); diff --git a/worker/src/support-engineering-composition.ts b/worker/src/support-engineering-composition.ts new file mode 100644 index 0000000..f2fb934 --- /dev/null +++ b/worker/src/support-engineering-composition.ts @@ -0,0 +1,46 @@ +import type { EngineeringOptions } from '@pegma/support-desk-application'; +import type { Logger } from '@pegma/spine'; +import { createAgentPrincipalResolver } from './agent-authority'; +import type { SupportRuntime } from './support-desk'; +import type { EngineeringHttpRepository } from './support-engineering-handlers'; +import type { SupportEngineeringRouterOptions } from './support-engineering-router'; +import { createSupportEngineeringRuntime, supportEngineeringApplicationOptions, + type SupportEngineeringReviewProofs } from './support-engineering'; + +/** Trusted human surface only. No model, processing or GitHub mutation ports. */ +export interface SupportEngineeringHumanComposition { + readonly enabled?: () => boolean; + /** Separate current human review gate, with strict false as the default. */ + readonly reviewEnabled?: () => boolean; + readonly configuration?: { + readonly application: EngineeringOptions; + readonly repositories: readonly EngineeringHttpRepository[]; + /** Explicit current read-only proof ports; absence holds NEW approvals. */ + readonly reviewProofs?: SupportEngineeringReviewProofs; + }; +} +export function supportEngineeringHumanEnabled(options: SupportEngineeringHumanComposition = {}): boolean { + if (options.configuration === undefined) return false; + try { return options.enabled?.() === true; } catch { return false; } +} +/** Called before the existing application factory; omission keeps intake OFF. */ +export function supportEngineeringIntakeOptions(options: SupportEngineeringHumanComposition = {}) { + return supportEngineeringHumanEnabled(options) + ? supportEngineeringApplicationOptions(options.configuration!.application) : undefined; +} +/** Same real application/Store/Identity/Sessions/RoleStore/limiter as Support. */ +export function composeSupportEngineeringHuman(runtime: SupportRuntime, logger: Logger, + options: SupportEngineeringHumanComposition = {}): SupportEngineeringRouterOptions { + if (!supportEngineeringHumanEnabled(options)) return {}; + const authority = { identity: runtime.identity, sessions: runtime.sessions, + identityLinkFromClaims: runtime.identityLinkFromClaims, roleStore: runtime.roleStore, logger }; + const resolve = createAgentPrincipalResolver(authority); + return { enabled: () => supportEngineeringHumanEnabled(options), configuration: { + ...authority, limiter: runtime.replyLimiter, repositories: options.configuration!.repositories, + reviewEnabled: () => { try { return options.reviewEnabled?.() === true; } catch { return false; } }, + runtime: () => createSupportEngineeringRuntime({ application: runtime.application, + clock: runtime.clock, staffAccess: { resolve }, processingEnabled: () => false, + ...(options.configuration!.reviewProofs === undefined ? {} : { reviewProofs: options.configuration!.reviewProofs }), + }), + } }; +} diff --git a/worker/src/support-engineering-fixtures.ts b/worker/src/support-engineering-fixtures.ts new file mode 100644 index 0000000..5c72ef8 --- /dev/null +++ b/worker/src/support-engineering-fixtures.ts @@ -0,0 +1,342 @@ +import { resolveAccess } from '@pegma/authorization-core'; +import { createRoleStore } from '@pegma/authorization-storage'; +import type { Store } from '@pegma/storage-core'; +import { isDeepStrictEqual } from 'node:util'; +import { + createSupportDeskApplication, supportPermissions, supportRecords, + type EngineeringCandidate, type EngineeringDispatchProofBinding, + type EngineeringExportRequest, type EngineeringIssueAcknowledgement, + type EngineeringKey, type EngineeringRepositoryDescriptor, + type EngineeringRepositoryObservation, type EngineeringSecurity, + type VerifiedEngineeringDispatchResult, type VerifiedEngineeringExportChecks, + type VerifiedEngineeringRouting, +} from '@pegma/support-desk-application'; +import type { + EngineeringChecksPort, EngineeringGitHubPort, EngineeringModelInput, + EngineeringProposalPort, EngineeringRoutingPort, VerifiedEngineeringConfiguration, +} from '@pegma/support-desk-ai'; +import { + createSupportEngineeringRuntime, supportEngineeringApplicationOptions, + type EngineeringFailurePacket, +} from './support-engineering'; +import type { SupportEngineeringPorts } from './support-engineering-ports'; + +export const engineeringTicketId = 'engineering-ticket'; +export const engineeringCanary = 'SYNTHETIC_PRIVATE_ENGINEERING_NOTE'; +export const engineeringProofReference = 'SYNTHETIC_PRIVATE_FAILURE_REFERENCE'; +const scope = { kind: 'application' } as const; +type Actor = 'customer' | 'staff' | 'security' | 'admin' | 'processor' | 'reconciler'; +export const engineeringRepositories: readonly EngineeringRepositoryDescriptor[] = [ + { repositoryId: 'synthetic-repository-101', owner: 'synthetic-org', name: 'workspace-core', visibility: 'public', + responsibilities: 'Workspace export creation and file generation.', product: 'workspace', component: 'export', + version: '2.x', allowedLabels: ['bug', 'export'], allowedTemplates: ['bug-report'], publicationMode: 'approval_required', enabled: true }, + { repositoryId: 'synthetic-repository-202', owner: 'synthetic-org', name: 'workspace-api', visibility: 'private', + responsibilities: 'Workspace export requests and downloads.', product: 'workspace', component: 'api', + version: '2.x', allowedLabels: ['bug'], allowedTemplates: ['bug-report'], publicationMode: 'approval_required', enabled: true }, +]; + +/** Real SDK persistence/roles; only trusted external systems are fictional. */ +export async function createSupportEngineeringFixture(store: Store, options: { + readonly intake?: boolean; readonly processing?: boolean; +} = {}) { + let milliseconds = Date.parse('2026-11-10T12:00:00.000Z'); + const clock = { now: () => new Date(milliseconds).toISOString() }; + let ordinal = 0; + const next = (label: string) => 'synthetic-engineering-' + label + '-' + ++ordinal; + const command = (label: string) => ({ commandId: next(label), correlationId: 'synthetic-engineering-fixture' }); + const ordinary = [supportPermissions.queueRead, supportPermissions.engineeringRead, + supportPermissions.engineeringEvidenceSubmit, supportPermissions.engineeringReview, + supportPermissions.engineeringWithdraw, supportPermissions.engineeringPolicyRead, + supportPermissions.replyAny, supportPermissions.note, supportPermissions.manage]; + const permissions: Record = { + customer: [supportPermissions.create, supportPermissions.readOwn, supportPermissions.replyOwn], + staff: ordinary, + security: [...ordinary, supportPermissions.engineeringRestrictedRead, supportPermissions.engineeringSecurityReview], + admin: [supportPermissions.queueRead, supportPermissions.engineeringPolicyRead, supportPermissions.engineeringPolicyManage], + processor: [supportPermissions.queueRead, supportPermissions.engineeringRead, supportPermissions.engineeringProcess], + reconciler: [supportPermissions.queueRead, supportPermissions.engineeringRead, supportPermissions.engineeringReconcile], + }; + const roleStore = createRoleStore(store, 'pegma-engineering-fixture'); + const policy = { version: 'synthetic-engineering-fixture-v1', roles: permissions }; + for (const actor of Object.keys(permissions) as Actor[]) await roleStore.grantRoleAssignmentWithAudit({ + assignment: { id: 'engineering-role-' + actor, principalId: 'engineering-' + actor, role: actor, scope, + grantedBy: { kind: 'system', systemId: 'synthetic-engineering-fixture' }, grantedAtEpochMs: milliseconds, status: 'active' }, + auditEventId: 'engineering-grant-' + actor, + }); + async function resolve(principalId: string) { + const assignments = await roleStore.listActiveRoleAssignments(principalId, scope); + return resolveAccess({ principalId, roles: assignments.map((row) => row.role) }, policy); + } + const actors = { customer: await resolve('engineering-customer'), staff: await resolve('engineering-staff'), + security: await resolve('engineering-security'), admin: await resolve('engineering-admin') }; + const state = { + enabled: options.processing ?? true, + product: 'ready' as 'ready' | 'missing' | 'expired', + configuration: 'ready' as 'ready' | 'disabled', + calibrationReady: true, + calibrationPolicyHash: '', + routing: 'checked' as 'checked' | 'human_required' | 'restricted', + checks: 'checked' as 'checked' | 'held' | 'restricted', + checksReadable: true, + publicReproduction: 'passed' as 'passed' | 'not_applicable', + modelSecurity: 'ordinary' as EngineeringSecurity, + modelRouting: 'selected' as 'selected' | 'ambiguous' | 'out_of_scope', + modelRepositoryId: engineeringRepositories[0]!.repositoryId, + modelCalls: 0, + modelInputs: [] as EngineeringModelInput[], + modelHook: undefined as (() => Promise) | undefined, + duplicateQuery: 'workspace export empty file' as string | null, + duplicates: [] as Awaited>['issues'], + searches: [] as Parameters[0][], + linkExisting: false, + createMode: 'accept' as 'accept' | 'accept_then_lose' | 'unknown', + reconciliation: 'known' as 'known' | 'unknown', + creates: [] as EngineeringExportRequest[], + reservations: [] as string[], + accounting: [] as string[], + installationActive: true, + }; + const validUntil = new Date(milliseconds + 3_600_000).toISOString(); + const metadata = new Map(engineeringRepositories.map((repository) => [repository.repositoryId, + { repositoryId: repository.repositoryId, owner: repository.owner, name: repository.name, visibility: repository.visibility, + installationBinding: 'synthetic-installation-' + repository.repositoryId, metadataVersion: 'synthetic-metadata-v1' }])); + const issuedRouting = new Map(); + const issuedChecks = new Map(); + const issuedDispatch: VerifiedEngineeringDispatchResult[] = []; + const remote = new Map(); + const routing: EngineeringRoutingPort = { + async resolve() { + if (!state.calibrationReady) return { outcome: 'unavailable' }; + return { outcome: 'ready', calibration: { version: 'synthetic-calibration-v1', artifactRef: 'synthetic-calibration-artifact', + rubricVersion: 'synthetic-rubric-v1', evaluationRef: 'synthetic-labeled-evaluation', modelVersion: 'synthetic-model-v1', + promptVersion: 'synthetic-prompt-v1', parserVersion: 'synthetic-parser-v1', policyHash: state.calibrationPolicyHash, + verifiedAt: clock.now(), validUntil } }; + }, + async check({ binding }) { + if (state.routing !== 'checked') return { outcome: state.routing }; + const receipt = next('routing'); + issuedRouting.set(receipt, { binding: structuredClone(binding), outcome: 'accepted', verifierReceiptId: receipt, + verifierVersion: 'synthetic-routing-verifier-v1', verifiedAt: clock.now(), validUntil }); + return { outcome: 'checked', receipt }; + }, + async verify(receipt, binding) { + const proof = issuedRouting.get(receipt); + return proof !== undefined && isDeepStrictEqual(proof.binding, binding) ? structuredClone(proof) : null; + }, + }; + const checks: EngineeringChecksPort = { + async resolvePolicy() { return { outcome: 'ready', policy: { version: 'synthetic-check-policy-v1', + binding: 'synthetic-independent-check-binding', verifiedAt: clock.now(), validUntil } }; }, + async check({ binding, exactRequest }) { + if (state.checks !== 'checked') return { outcome: state.checks }; + if (JSON.stringify(exactRequest).includes(engineeringCanary) || JSON.stringify(exactRequest).includes(engineeringProofReference)) + return { outcome: 'held' }; + const receipt = next('check'); + issuedChecks.set(receipt, { binding: structuredClone(binding), privacy: 'passed', factual: 'passed', security: 'clear', + publicReproduction: exactRequest.repository.visibility === 'public' ? state.publicReproduction : 'not_applicable', + verifierReceiptId: receipt, verifierVersion: 'synthetic-check-verifier-v1', verifiedAt: clock.now(), validUntil }); + return { outcome: 'checked', receipt }; + }, + async verify(receipt, binding) { + const proof = issuedChecks.get(receipt); + return state.checksReadable && proof !== undefined && isDeepStrictEqual(proof.binding, binding) ? structuredClone(proof) : null; + }, + }; + const application = createSupportDeskApplication({ store, clock, engineering: supportEngineeringApplicationOptions({ + enabled: options.intake ?? true, maxModelAttempts: 1, routing, checks, + productContext: { async resolve(context, signal) { + if (signal.aborted || state.product === 'missing') return null; + return { productId: 'workspace', version: '2.3.0', buildId: 'synthetic-build-230', binding: 'synthetic-workspace-230-binding', + contextVersion: 'synthetic-product-context-v1', receiptId: next('product'), verifiedAt: context.acceptedAt, + validUntil: state.product === 'expired' ? new Date(milliseconds - 1).toISOString() : validUntil }; + } }, + repositoryMetadata: { async resolve(id, signal) { + const observation = metadata.get(id); + return signal.aborted || !state.installationActive || observation === undefined ? null : structuredClone(observation); + } }, + dispatchResults: { async verify(binding, signal) { + const proof = issuedDispatch.find((item) => isDeepStrictEqual(item.binding, binding)); + return signal.aborted || proof === undefined ? null : structuredClone(proof); + } }, + }) }); + function dispatchProof(binding: EngineeringDispatchProofBinding) { + const value: VerifiedEngineeringDispatchResult = { binding: structuredClone(binding), verifierReceiptId: next('dispatch-proof'), + verifierVersion: 'synthetic-github-verifier-v1', verifiedAt: clock.now(), validUntil }; + issuedDispatch.push(value); + } + const github: EngineeringGitHubPort = { + async getMetadata(id) { + const repository = metadata.get(id); + return !state.installationActive || repository === undefined ? null : { repository: structuredClone(repository), + authority: { active: true, binding: repository.installationBinding, validUntil } }; + }, + async searchDuplicates(input) { + state.searches.push(structuredClone(input)); + return { issues: structuredClone(state.duplicates), physicalResults: state.duplicates.length }; + }, + async createIssue(request, context) { + // The external fake checks the actual durable SDK dispatch first. It does + // not create or edit any producer row or call a real GitHub endpoint. + const work = await application.readEngineeringWork(actors.security, { + ticketId: context.sourceFence.ticketId, sourceGeneration: context.sourceFence.sourceGeneration }); + if (work.dispatch?.dispatchId !== context.dispatchId || work.proposal === undefined || + work.dispatch.requestHash !== context.requestHash) + throw new Error('Synthetic GitHub call preceded actual durable dispatch'); + state.creates.push(structuredClone(request)); + if (state.createMode === 'unknown') throw new Error('Synthetic unknown external acceptance'); + const acknowledgement = { repositoryId: request.repository.repositoryId, issueId: 'synthetic-issue-' + state.creates.length, + issueNumber: state.creates.length }; + const binding: EngineeringDispatchProofBinding = { ...context.sourceFence, repositoryId: request.repository.repositoryId, + repositoryMetadataHash: work.proposal.repositoryMetadataHash, dispatchId: context.dispatchId, requestHash: context.requestHash, + exportMarker: request.bundle.exportMarker, operation: 'create_issue', result: { outcome: 'accepted', acknowledgement } }; + remote.set(request.bundle.exportMarker, { acknowledgement, binding }); dispatchProof(binding); + if (state.createMode === 'accept_then_lose') throw new Error('Synthetic accepted response loss'); + return acknowledgement; + }, + async reconcile(input) { + if (state.reconciliation === 'unknown' || input.sourceFence === undefined || input.repositoryMetadataHash === undefined) + return { outcome: 'unknown' }; + if (input.operation === 'link_existing_issue') { + const issue = state.duplicates.find((row) => row.repositoryId === input.repositoryId && row.issueId === input.issueId && row.issueNumber === input.issueNumber); + if (issue === undefined) return { outcome: 'unknown' }; + const acknowledgement = { repositoryId: issue.repositoryId, issueId: issue.issueId, issueNumber: issue.issueNumber }; + dispatchProof({ ...input.sourceFence, repositoryId: input.repositoryId, repositoryMetadataHash: input.repositoryMetadataHash, + dispatchId: input.dispatchId, requestHash: input.requestHash, exportMarker: input.exportMarker, + operation: 'link_existing_issue', result: { outcome: 'accepted', acknowledgement } }); + return { outcome: 'accepted', acknowledgement, proof: 'synthetic-existing-issue-proof' }; + } + const accepted = remote.get(input.exportMarker); + if (accepted === undefined || accepted.binding.repositoryId !== input.repositoryId || accepted.binding.dispatchId !== input.dispatchId || + accepted.binding.requestHash !== input.requestHash || accepted.binding.repositoryMetadataHash !== input.repositoryMetadataHash || + !isDeepStrictEqual(input.sourceFence, { ticketId: accepted.binding.ticketId, sourceGeneration: accepted.binding.sourceGeneration, + sourceBindingHash: accepted.binding.sourceBindingHash })) return { outcome: 'unknown' }; + dispatchProof(accepted.binding); + return { outcome: 'accepted', acknowledgement: structuredClone(accepted.acknowledgement), proof: 'synthetic-unique-acceptance-proof' }; + }, + }; + const configuration: VerifiedEngineeringConfiguration = { purpose: 'support_bug_assessment', version: 'synthetic-config-v1', + promptVersion: 'synthetic-prompt-v1', modelVersion: 'synthetic-model-v1', parserVersion: 'synthetic-parser-v1', + provider: 'synthetic-provider', model: 'synthetic-model', pricingRef: 'synthetic-price-v1', + trustedInstructions: 'Assess only the verified fictional failure and allowed repositories.', framingTokens: 20, + budgets: { maxMessages: 10, maxInputBytes: 32_768, maxInputTokens: 12_000, maxContextTokens: 16_000, + maxOutputBytes: 16_000, maxOutputTokens: 1_500, maxCandidateBytes: 16_000, maxDurationMilliseconds: 5_000, + maxCostMicros: 1_000, currency: 'USD', maxAttempts: 1, maxRepositories: 2, maxRepositoryBytes: 10_000 }, + dataControls: { status: 'verified', purpose: 'support_bug_assessment', configurationBinding: 'synthetic-config-v1', + accountRef: 'synthetic-account', projectRef: 'synthetic-project', endpointRef: 'synthetic-endpoint', + modelRef: 'synthetic-model-route', featuresRef: 'synthetic-features', exceptionsRef: 'synthetic-exceptions', + intermediaryRefs: ['synthetic-intermediary'], verifiedAt: clock.now(), validUntil } }; + function candidate(): EngineeringCandidate { + return { title: 'Workspace export produces an empty file', summary: 'A fictional workspace export omits its rows.', + expectedBehavior: 'The export contains the workspace rows.', actualBehavior: 'The downloaded export is empty.', + reproductionSteps: ['Create a fictional workspace with one row.', 'Export it and inspect the file.'], + applicability: { productId: 'workspace', version: '2.3.0', buildId: 'synthetic-build-230' }, security: state.modelSecurity, + routing: state.modelRouting === 'selected' ? { outcome: 'selected', repositoryId: state.modelRepositoryId, + alternativeRepositoryIds: [], rationale: 'The allowlisted core owns file generation.' } : { + outcome: state.modelRouting, alternativeRepositoryIds: engineeringRepositories.map((row) => row.repositoryId), + rationale: 'Staff must choose between the two allowed components.' } }; + } + const proposals: EngineeringProposalPort = { + async duplicateQuery() { return state.duplicateQuery; }, + async prepare(input) { + const previous = input.previousRequest; + const bundle = previous === undefined ? { title: input.candidate.title, + body: [input.candidate.summary, 'Expected: ' + input.candidate.expectedBehavior, + 'Actual: ' + input.candidate.actualBehavior, ...input.candidate.reproductionSteps, + 'Export marker: ' + input.exportMarker].join('\n\n'), labels: ['bug'], templateId: 'bug-report', + evidenceReferences: ['synthetic-approved-public-reproduction'], exportMarker: input.exportMarker } : { + ...previous.bundle, body: previous.bundle.body.replaceAll(previous.bundle.exportMarker, input.exportMarker), + exportMarker: input.exportMarker }; + if (state.linkExisting) { + const issue = input.duplicates[0]; + if (issue === undefined) return { outcome: 'held' }; + return { outcome: 'prepared', request: { operation: 'link_existing_issue', repository: input.repository, bundle, + issueId: issue.issueId, issueNumber: issue.issueNumber } }; + } + return { outcome: 'prepared', request: { operation: 'create_issue', repository: input.repository, bundle } }; + }, + }; + const ports: SupportEngineeringPorts = { + serviceAccess: { async resolve(signal) { + if (signal.aborted) return { outcome: 'inactive' }; + return { outcome: 'ready', authority: { access: await resolve('engineering-processor'), + authorityVersion: 'synthetic-processor-v1', usageScopeRef: 'synthetic-engineering-budget' } }; + } }, + reconciliationAccess: { async resolve(signal) { + if (signal.aborted) return { outcome: 'inactive' }; + return { outcome: 'ready', authority: { access: await resolve('engineering-reconciler'), + authorityVersion: 'synthetic-reconciler-v1', usageScopeRef: 'synthetic-engineering-reconciliation' } }; + } }, + configuration: { async resolve() { return state.configuration === 'ready' + ? { outcome: 'ready', configuration: structuredClone(configuration) } : { outcome: 'disabled' }; } }, + routing, checks, github, proposals, + model: { async generate(input, _context, configured) { + state.modelCalls += 1; state.modelInputs.push(structuredClone(input)); await state.modelHook?.(); + return { outputJson: JSON.stringify(candidate()), provider: configured.provider, model: configured.model, + requestId: 'synthetic-model-request', usage: { inputTokens: 100, outputTokens: 100, costMicros: 10, currency: 'USD' } }; + } }, + // Scripted external budget behavior only, not a host durable-budget claim. + usage: { async reserve(context) { state.reservations.push(context.usageReservationId); + return { outcome: 'reserved', usageReservationId: context.usageReservationId }; }, + async reconcile(_identity, observation) { state.accounting.push(observation.state); return 'reconciled'; } }, + tokenCounter: { count: (value) => Math.max(1, Math.ceil(new TextEncoder().encode(value).byteLength / 4)) }, + }; + const runtime = createSupportEngineeringRuntime({ application, clock, staffAccess: { resolve: (id) => resolve(id) }, + processingEnabled: () => state.enabled, ports }); + const initialPolicy = await runtime.putPolicy(actors.admin, { clientCommandId: 'POLICY-EXACT', expectedGeneration: 0, + policy: { enabled: true, repositories: engineeringRepositories } }); + state.calibrationPolicyHash = initialPolicy.policyHash; + let acceptedKey: EngineeringKey | undefined; + async function createTicket() { + await application.createCustomerTicket(actors.customer, { ...command('ticket'), ticketId: engineeringTicketId, + messageId: 'engineering-question', subject: 'Workspace export is empty', body: 'Exporting a fictional workspace produces an empty file.' }); + await application.addNote(actors.staff, { ...command('note'), ticketId: engineeringTicketId, + messageId: 'engineering-note', body: engineeringCanary }); + return (await application.readStaffTicket(actors.staff, engineeringTicketId)).ticket; + } + async function eligible(security: EngineeringSecurity = 'ordinary') { + const ticket = await createTicket(); + await runtime.enroll(actors.staff, { ticketId: engineeringTicketId, clientCommandId: 'ENROLL-EXACT', expectedRevision: ticket.revision }); + const packet: EngineeringFailurePacket = { ticketId: engineeringTicketId, clientCommandId: 'FAILURE-EXACT', + expectedRevision: ticket.revision, security, evidence: { kind: 'staff_verified_failure', + expectedBehavior: 'The export contains the workspace rows.', actualBehavior: 'The downloaded export is empty.', + reproductionSteps: ['Create a fictional workspace with one row.', 'Export it and inspect the file.'], + visibleMessageIds: ['engineering-question'], verificationReference: engineeringProofReference } }; + const source = await runtime.submitVerifiedFailure(actors.staff, packet); + acceptedKey = { ticketId: engineeringTicketId, sourceGeneration: source.sourceGeneration }; + return { source, packet, key: structuredClone(acceptedKey) }; + } + function key() { if (acceptedKey === undefined) throw new Error('No actual accepted engineering key'); return structuredClone(acceptedKey); } + const work = () => runtime.readWork(actors.security, key()); + const process = () => runtime.processWork({ ...key(), workerId: 'synthetic-engineering-worker', leaseMilliseconds: 30_000 }); + async function prepared() { + const assessed = await process(); + if (assessed.outcome !== 'candidate') throw new Error('Synthetic assessment unavailable: ' + assessed.outcome); + const result = await process(); + if (result.outcome !== 'prepared') throw new Error('Synthetic proposal unavailable: ' + result.outcome); + const current = await work(); + if (current.proposal === undefined) throw new Error('Actual prepared proposal missing'); + return current; + } + async function approve() { + const current = await work(); + if (current.proposal === undefined) throw new Error('Actual proposal required for review'); + const packet = { ...key(), clientCommandId: 'REVIEW-EXACT', expectedWorkGeneration: current.workGeneration, + proposalHash: current.proposal.proposalHash, decision: 'approve' as const }; + await runtime.reviewProposal(actors.staff, packet); return packet; + } + return { store, clock, state, application, actors, runtime, ports, metadata, configuration, + command, createTicket, eligible, key, work, process, prepared, approve, resolve, + rows: () => store.collection(supportRecords).list(engineeringTicketId), + source: () => runtime.readSource(actors.security, engineeringTicketId), + advance: (value: number) => { milliseconds += value; }, + async revoke(actor: Actor) { + const row = await roleStore.getRoleAssignment('engineering-role-' + actor); + if (row === null) throw new Error('Actual role assignment missing'); + return roleStore.revokeRoleAssignmentWithAudit({ assignmentId: 'engineering-role-' + actor, + expectedConcurrencyToken: row.concurrencyToken, revokedBy: { kind: 'system', systemId: 'synthetic-engineering-fixture' }, + revokedAtEpochMs: milliseconds, auditEventId: next('revoke') }); + }, + }; +} + +export type SupportEngineeringFixture = Awaited>; diff --git a/worker/src/support-engineering-handlers.test.ts b/worker/src/support-engineering-handlers.test.ts new file mode 100644 index 0000000..996d091 --- /dev/null +++ b/worker/src/support-engineering-handlers.test.ts @@ -0,0 +1,623 @@ +import { supportPermissions } from '@pegma/support-desk-application'; +import { describe, expect, it, vi } from 'vitest'; +import { IDENTITY_ISSUER } from './identity-api'; +import { isPlainObject } from './api-auth'; +import { ADMIN_ROLE, APPLICATION_SCOPE, SUPPORT_ROLE } from './support-access'; +import { controlledHumanBody } from './support-human-control-fixtures'; +import { engineeringCanary, engineeringProofReference, engineeringRepositories, engineeringTicketId } from './support-engineering-fixtures'; +import { createSupportEngineeringHandlers } from './support-engineering-handlers'; +import { + createSupportEngineeringHttpFixture, engineeringHttpCommand, engineeringHttpNumber, + engineeringHttpObject, engineeringHttpResult, engineeringHttpRoute, +} from './support-engineering-http-fixtures'; + +const fixture = createSupportEngineeringHttpFixture; +const object = engineeringHttpObject; +const result = engineeringHttpResult; +const number = engineeringHttpNumber; + +function firstIntentRepository(packet: { intent: Record }) { + const policy = packet.intent.policy; + if (!isPlainObject(policy) || !Array.isArray(policy.repositories)) throw new Error('Expected prepared full policy'); + const first: unknown = policy.repositories[0]; + if (!isPlainObject(first)) throw new Error('Expected prepared repository snapshot'); + return first; +} + +describe('unregistered engineering HTTP through current real host authority', () => { + it('defaults human routes OFF before lazy runtime construction and leaves worker routes unclaimed', async () => { + const f = await fixture(); const { enabled, ...options } = f.options; void enabled; + const handle = createSupportEngineeringHandlers(options); + expect((await handle(f.request()))?.status).toBe(503); expect(f.state.runtimeCalls).toBe(0); + for (const suffix of ['proposal', 'review']) { + const response = await handle(new Request(IDENTITY_ISSUER + engineeringHttpRoute + '/' + suffix)); + expect(response?.status).toBe(503); + if (response === null) throw new Error('Expected owned human engineering route'); + expect(await object(response)).toEqual({ error: 'support_engineering_disabled' }); + } + for (const suffix of ['dispatch', 'process']) + expect(await handle(new Request(IDENTITY_ISSUER + engineeringHttpRoute + '/' + suffix))).toBeNull(); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it('keeps human, administrator, Knowledge and service capabilities separate in the real role policy', async () => { + const f = await fixture(); const staff = await f.resolve(f.principals.staff); + const admin = await f.resolve(f.principals.admin); const both = await f.resolve(f.principals.both); + expect(staff?.permissions).toContain(supportPermissions.engineeringRead); + expect(staff?.permissions).not.toContain(supportPermissions.engineeringProcess); + expect(staff?.permissions).not.toContain(supportPermissions.engineeringReconcile); + expect(staff?.permissions).not.toContain(supportPermissions.engineeringRestrictedRead); + expect(staff?.permissions).not.toContain(supportPermissions.engineeringSecurityReview); + expect(admin?.permissions).not.toContain(supportPermissions.queueRead); + expect(admin?.permissions).not.toContain(supportPermissions.engineeringRead); + expect(both?.permissions).toContain(supportPermissions.engineeringPolicyManage); + expect(both?.permissions).toContain(supportPermissions.queueRead); + }); + + it.each(['admin', 'knowledge', 'customer'] as const)('denies %s before a staff source factory call', async (actor) => { + const f = await fixture(); expect((await f.send(f.request('', undefined, actor))).status).toBe(403); + expect(f.state.runtimeCalls).toBe(0); + }); + + it.each(['staff', 'admin', 'knowledge', 'customer'] as const)('denies policy access to %s without both current roles and SDK rights', async (actor) => { + const f = await fixture(); expect((await f.send(f.request('policy', undefined, actor))).status).toBe(403); + expect(f.state.runtimeCalls).toBe(0); + }); + + it('enrolls and records an actual verified failure with exact uppercase command replay', async () => { + const f = await fixture(); const original = f.state.runtime; + f.state.runtime = { ...original, async enroll(access, packet) { + f.state.captured.push(packet.clientCommandId); return original.enroll(access, packet); + } }; + const ticket = await f.engineering.createTicket(); + const packet = { commandId: engineeringHttpCommand, expectedRevision: ticket.revision }; + const accepted = await object(await f.send(f.request('enroll', packet))); const enrolledRows = await f.rows(); + expect(await object(await f.send(f.request('enroll', packet)))).toEqual(accepted); + expect(await f.rows()).toEqual(enrolledRows); + expect(f.state.captured).toEqual([engineeringHttpCommand, engineeringHttpCommand]); + const evidence = { commandId: 'HTTP-FAILURE-EXACT', expectedRevision: ticket.revision, security: 'ordinary', + expectedBehavior: 'The export contains rows.', actualBehavior: 'The downloaded file is empty.', + reproductionSteps: ['Export the fictional workspace.'], visibleMessageIds: ['engineering-question'], + verificationReference: engineeringProofReference }; + const first = await object(await f.send(f.request('evidence', evidence))); const rows = await f.rows(); + expect(result(first)).toMatchObject({ state: 'eligible', security: 'ordinary' }); + expect(await object(await f.send(f.request('evidence', evidence)))).toEqual(first); + expect(await f.rows()).toEqual(rows); + expect((await f.engineering.source()).evidence?.actorId).toBe(f.principals.staff); + expect(JSON.stringify(first)).not.toContain(engineeringProofReference); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it('projects only operational fields from actual source and checked work records', async () => { + const f = await fixture(); const accepted = await f.verified(); await f.prepared(); + const source = await object(await f.send(f.request())); + const work = await object(await f.send(f.request('work', undefined, 'staff', '?sourceGeneration=' + accepted.key.sourceGeneration))); + expect(result(source)).toMatchObject({ hasEvidence: true, hasProductContext: true }); + expect(result(work)).toMatchObject({ hasPreparedProposal: true, hasApproval: false, hasDispatch: false }); + for (const value of [source, work]) { + for (const key of ['evidence', 'product', 'candidate', 'proposal', 'exactRequest', 'approval', 'dispatch', 'heldReason']) + expect(result(value)).not.toHaveProperty(key); + for (const privateText of [engineeringCanary, engineeringProofReference, 'Workspace export produces an empty file', + 'synthetic-approved-public-reproduction', 'checksReceipt', 'installationBinding']) + expect(JSON.stringify(value)).not.toContain(privateText); + } + expect(f.engineering.state.creates).toEqual([]); + }); + + it('keeps uncertain evidence private even when the ordinary staff submitted it', async () => { + const f = await fixture(); const accepted = await f.verified('uncertain'); + expect(accepted.source.state).toBe('restricted'); + for (const incoming of [f.request(), f.request('work', undefined, 'staff', '?sourceGeneration=' + accepted.key.sourceGeneration)]) { + const response = await f.send(incoming); expect(response.status).toBe(403); + expect(await object(response)).toEqual({ error: 'forbidden' }); + } + expect((await f.rows()).filter((row) => row.kind === 'engineering_work')).toEqual([]); + expect(f.engineering.state.modelCalls).toBe(0); + }); + + it('retains the actual trusted-product hold rather than accepting browser product claims', async () => { + const f = await fixture(); f.engineering.state.product = 'missing'; + const accepted = await f.verified(); expect(accepted.source.state).toBe('held'); + expect((await f.rows()).filter((row) => row.kind === 'engineering_work')).toEqual([]); + expect(f.engineering.state.modelCalls).toBe(0); + }); + + it.each(['Origin', 'Authorization', 'X-Pegma-CSRF', 'Cookie'] as const)('refuses invalid browser %s before an engineering write', async (header) => { + const f = await fixture(); const ticket = await f.engineering.createTicket(); const before = await f.rows(); + const incoming = f.request('enroll', { commandId: 'BAD-BROWSER', expectedRevision: ticket.revision }); + incoming.headers.set(header, header === 'Origin' ? 'https://foreign.example' : header === 'Authorization' ? 'Bearer synthetic' : 'invalid'); + expect([401, 403]).toContain((await f.send(incoming)).status); expect(await f.rows()).toEqual(before); + }); + + it.each([{ actorId: 'forged' }, { productId: 'forged' }, { buildId: 'forged' }, { calibration: 'forged' }, + { verifiedAt: '2026-11-10T12:00:00Z' }, { correlationId: 'forged' }, { providerUrl: 'https://foreign.example' }])( + 'rejects authority/proof fields in the closed enrollment packet: %j', async (extra) => { + const f = await fixture(); const ticket = await f.engineering.createTicket(); const before = await f.rows(); + expect((await f.send(f.request('enroll', { commandId: 'CLOSED-EXACT', expectedRevision: ticket.revision, ...extra }))).status).toBe(400); + expect(await f.rows()).toEqual(before); expect(f.state.runtimeCalls).toBe(0); + }); + + it.each(['?sourceGeneration=0', '?sourceGeneration=1&sourceGeneration=1', '?sourceGeneration=9007199254740992', + '?sourceGeneration=1&role=Admin'])('bounds a work key before runtime access: %s', async (query) => { + const f = await fixture(); + expect((await f.send(f.request('work', undefined, 'staff', query))).status).toBe(400); + expect(f.state.runtimeCalls).toBe(0); + }); + + it('rejects private visible-message references and changed fields under a retained command', async () => { + const f = await fixture(); const accepted = await f.verified(); const before = await f.rows(); + expect((await f.send(f.request('evidence', { ...accepted.packet, actualBehavior: 'A changed report.' }))).status).toBe(409); + expect((await f.send(f.request('evidence', { ...accepted.packet, commandId: 'PRIVATE-NOTE-DENIED', + visibleMessageIds: ['engineering-note'] }))).status).toBe(409); + expect(await f.rows()).toEqual(before); + }); + + it('uses exact selection fences and SDK receipt-first replay after current policy changes', async () => { + const f = await fixture(); const accepted = await f.verified(); f.engineering.state.modelRouting = 'ambiguous'; + expect((await f.process()).outcome).toBe('candidate'); + const response = await f.send(f.request('work', undefined, 'staff', '?sourceGeneration=' + accepted.key.sourceGeneration)); + const view = result(await object(response)); + if (typeof view.selection !== 'object' || view.selection === null || !('policyGeneration' in view.selection) || + !('policyHash' in view.selection)) throw new Error('Missing actual selection policy fences'); + const packet = { commandId: 'SELECT-EXACT', sourceGeneration: accepted.key.sourceGeneration, + expectedWorkGeneration: number(view.workGeneration), repositoryKey: engineeringRepositories[1]!.repositoryId, + policyGeneration: view.selection.policyGeneration, policyHash: view.selection.policyHash, + reason: 'Select the allowlisted download API.' }; + const first = await object(await f.send(f.request('repository', packet))); + expect(result(first).status).toBe('candidate'); + const policy = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + await f.engineering.runtime.disableExports(f.engineering.actors.admin, { clientCommandId: 'DISABLE-AFTER-SELECTION', expectedGeneration: policy.generation }); + const rows = await f.rows(); + expect(await object(await f.send(f.request('repository', packet)))).toEqual(first); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.modelCalls).toBe(1); + expect(f.engineering.state.creates).toEqual([]); + }); + + it('rejects arbitrary repository URLs or identities before changing a work target', async () => { + const f = await fixture(); const accepted = await f.verified(); expect((await f.process()).outcome).toBe('candidate'); + const work = await f.work(); const policy = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); const before = await f.rows(); + const packet = { commandId: 'UNKNOWN-REPOSITORY', sourceGeneration: accepted.key.sourceGeneration, + expectedWorkGeneration: work.workGeneration, repositoryKey: 'https://foreign.example/repository', + policyGeneration: policy.generation, policyHash: policy.policyHash, reason: 'Unapproved destination.' }; + expect((await f.send(f.request('repository', packet))).status).toBe(400); + expect(await f.rows()).toEqual(before); + }); + + it('uses declarative server-only policy descriptors and replays independently of live metadata availability', async () => { + const f = await fixture(); const policy = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + const packet = { commandId: 'POLICY-EXACT-HTTP', expectedGeneration: policy.generation, enabled: true, + repositoryKeys: [engineeringRepositories[0]!.repositoryId] }; + const retained = await f.preparePolicy(packet); + const first = await object(await f.send(f.request('policy', retained, 'both'))); + expect(result(first).enabled).toBe(true); + const actual = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + expect(actual.policy.repositories).toEqual([engineeringRepositories[0]]); + f.engineering.state.installationActive = false; + const rows = await f.policyRows(); + expect(await object(await f.send(f.request('policy', retained, 'both')))).toEqual(first); + expect(await f.policyRows()).toEqual(rows); + const view = result(await object(await f.send(f.request('policy', undefined, 'both')))); + expect(view.repositories).toEqual([{ key: engineeringRepositories[0]!.repositoryId, enabled: true }]); + expect(view.catalog).toEqual(engineeringRepositories.map((descriptor) => ({ key: descriptor.repositoryId, enabled: true }))); + expect(JSON.stringify(view)).not.toContain('responsibilities'); expect(JSON.stringify(view)).not.toContain('installationBinding'); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it('returns the full configured catalog after the actual durable policy is emptied', async () => { + const f = await fixture(); + const retained = await f.preparePolicy({ commandId: 'EMPTY-POLICY-EXACT', expectedGeneration: 1, + enabled: false, repositoryKeys: [] }); + const saved = await f.send(f.request('policy', retained, 'both')); + expect(saved.status).toBe(200); const rows = await f.policyRows(); + const response = await f.send(f.request('policy', undefined, 'both')); + expect(response.status).toBe(200); + const view = result(await object(response)); + expect(view.repositories).toEqual([]); expect(view.unmappedRepositoryCount).toBe(0); + expect(view.catalog).toEqual(engineeringRepositories.map((descriptor) => ({ key: descriptor.repositoryId, enabled: true }))); + expect(view.enabled).toBe(false); expect(await f.policyRows()).toEqual(rows); + for (const field of ['owner', 'name', 'descriptor', 'visibility', 'installationBinding', 'responsibilities']) + expect(JSON.stringify(view)).not.toContain('"' + field + '"'); + }); + + it('prepares a complete actor-bound immutable policy packet without SDK policy/source writes', async () => { + const f = await fixture(); const before = await f.policyRows(); const supportRows = await f.rows(); + const input = { commandId: engineeringHttpCommand, expectedGeneration: 1, enabled: true, + repositoryKeys: [engineeringRepositories[1]!.repositoryId, engineeringRepositories[0]!.repositoryId] }; + const packet = await f.preparePolicy(input); + expect(packet.intent).toEqual({ version: 1, actorId: f.principals.both, commandId: engineeringHttpCommand, + expectedGeneration: 1, repositoryKeys: input.repositoryKeys, + policy: { enabled: true, repositories: [engineeringRepositories[1], engineeringRepositories[0]] } }); + expect(await f.preparePolicy(input)).toEqual(packet); + expect(await f.policyRows()).toEqual(before); expect(await f.rows()).toEqual(supportRows); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it('refuses a keys-only submit instead of reconstructing a mutable policy packet', async () => { + const f = await fixture(); const before = await f.policyRows(); + const response = await f.send(f.request('policy', { commandId: 'OLD-KEYS-ONLY', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }, 'both')); + expect(response.status).toBe(400); expect(await f.policyRows()).toEqual(before); + expect(f.state.runtimeCalls).toBe(0); + }); + + it.each(['staff', 'admin', 'knowledge', 'customer'] as const)('does not disclose a full prepared policy to %s', async (actor) => { + const f = await fixture(); const before = await f.policyRows(); + const response = await f.send(f.request('policy/prepare', { commandId: 'PREPARE-DENIED', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }, actor)); + expect(response.status).toBe(403); expect(await object(response)).toEqual({ error: 'forbidden' }); + expect(f.state.runtimeCalls).toBe(0); expect(await f.policyRows()).toEqual(before); + }); + + it.each(['changed-descriptor', 'removed-key'] as const)('recovers the exact lost policy ACK after deployment %s', async (change) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'POLICY-LOST-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const original = f.state.runtime; let lose = true; + let accepted: Awaited> | undefined; + f.state.runtime = { ...original, async putPolicy(access, packet, binding) { + const value = await original.putPolicy(access, packet, binding); accepted = value; + if (lose) { lose = false; throw new Error('Synthetic committed policy ACK loss'); } return value; + } }; + expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(503); + const before = await f.policyRows(); + const repositories = change === 'removed-key' ? [] : f.options.repositories.map((entry) => ({ ...entry, + descriptor: { ...entry.descriptor, responsibilities: 'A changed current deployment description.' } })); + const later = createSupportEngineeringHandlers({ ...f.options, repositories }); + const replay = await later(f.request('policy', retained, 'both')); + expect(replay?.status).toBe(200); if (replay === null) throw new Error('Expected policy route'); + expect(result(await object(replay))).toEqual(accepted); + expect(await f.policyRows()).toEqual(before); + expect((await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).policy.repositories) + .toEqual([engineeringRepositories[0]]); + }); + + it('binds stale wrapper keys and their order to the actual SDK receipt without changing command identity', async () => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'FULL-INTENT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: engineeringRepositories.map((entry) => entry.repositoryId) }); + const first = await object(await f.send(f.request('policy', retained, 'both'))); const before = await f.policyRows(); + const changed = structuredClone(retained); + changed.intent.repositoryKeys = [engineeringRepositories[1]!.repositoryId, engineeringRepositories[0]!.repositoryId]; + expect((await f.send(f.request('policy', changed, 'both'))).status).toBe(409); + expect(await f.policyRows()).toEqual(before); + expect(await object(await f.send(f.request('policy', retained, 'both')))).toEqual(first); + expect(await f.policyRows()).toEqual(before); + }); + + it.each(['snapshot', 'key', 'actor', 'version', 'extra-field'] as const)('rejects a fresh altered policy intent %s', async (change) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'FRESH-INTENT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const changed = structuredClone(retained); const before = await f.policyRows(); + if (change === 'snapshot') firstIntentRepository(changed).responsibilities = 'An unapproved descriptor.'; + else if (change === 'key') changed.intent.repositoryKeys = [engineeringRepositories[1]!.repositoryId]; + else if (change === 'actor') changed.intent.actorId = f.principals.staff; + else if (change === 'version') changed.intent.version = 2; + else firstIntentRepository(changed).installationProof = 'forged'; + const response = await f.send(f.request('policy', changed, 'both')); + expect(response.status).toBe(change === 'actor' ? 403 : change === 'version' || change === 'extra-field' ? 400 : 409); + expect(await f.policyRows()).toEqual(before); + }); + + it('does not submit an old-catalog snapshot as a fresh policy when no earlier receipt committed', async () => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'FRESH-OLD-CATALOG', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const later = createSupportEngineeringHandlers({ ...f.options, repositories: f.options.repositories.map((entry) => ({ ...entry, + descriptor: { ...entry.descriptor, component: 'a-new-component' } })) }); + const before = await f.policyRows(); const response = await later(f.request('policy', retained, 'both')); + expect(response?.status).toBe(409); expect(await f.policyRows()).toEqual(before); + }); + + it('rejects a future generation and a reordered full snapshot without a policy write', async () => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'ORDERED-INTENT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: engineeringRepositories.map((entry) => entry.repositoryId) }); + const before = await f.policyRows(); const future = structuredClone(retained); future.intent.expectedGeneration = 2; + expect((await f.send(f.request('policy', future, 'both'))).status).toBe(409); + const reordered = structuredClone(retained); + if (!isPlainObject(reordered.intent.policy) || !Array.isArray(reordered.intent.policy.repositories)) + throw new Error('Expected actual full prepared snapshot'); + reordered.intent.policy.repositories.reverse(); + expect((await f.send(f.request('policy', reordered, 'both'))).status).toBe(409); + expect(await f.policyRows()).toEqual(before); + }); + + it.each(['missing', 'pruned'] as const)('keeps an old %s policy receipt from creating a new commit', async (kind) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'OLD-RECEIPT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + if (kind === 'pruned') { + expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(200); + f.engineering.advance(31 * 24 * 60 * 60 * 1_000); + const pruned = await f.engineering.application.pruneRepositoryPolicyHistory(f.engineering.actors.admin, { limit: 64 }); + expect(pruned.deletedPairs).toBeGreaterThan(0); + expect((await f.policyRows()).filter((row) => row.kind === 'engineering_policy_command')).toEqual([]); + } else { + await f.engineering.runtime.disableExports(f.engineering.actors.admin, { clientCommandId: 'OTHER-POLICY-ADVANCE', expectedGeneration: 1 }); + } + const before = await f.policyRows(); + expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(409); + expect(await f.policyRows()).toEqual(before); + }); + + it('lets the actual SDK CAS reject a head advance after the fresh-catalog observation', async () => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'CAS-INTENT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const original = f.state.runtime; let advanced = false; + let racedRows: Awaited> | undefined; + f.state.runtime = { ...original, async readPolicy(access) { + const observed = await original.readPolicy(access); + if (!advanced) { + advanced = true; + await f.engineering.runtime.disableExports(f.engineering.actors.admin, { clientCommandId: 'CAS-COMPETITOR', expectedGeneration: observed.generation }); + racedRows = await f.policyRows(); + } + return observed; + } }; + expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(409); + expect(advanced).toBe(true); expect(await f.policyRows()).toEqual(racedRows); + }); + + it.each([ADMIN_ROLE, SUPPORT_ROLE])('requires still-current %s before submitting a retained policy intent', async (role) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'REVOKED-INTENT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: [] }); const before = await f.policyRows(); + await f.revoke('both', role); + expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(403); + expect(await f.policyRows()).toEqual(before); + }); + + it.each(['logout', 'admin', 'queue', 'cookie'] as const)('rechecks %s after a retained policy body before its SDK head read', async (change) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'POLICY-BODY-IDENTITY-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const before = await f.policyRows(); const calls = f.state.runtimeCalls; + const body = await controlledHumanBody(f.request('policy', retained, 'both')); const pending = f.send(body.request); + try { + await body.waitFor(pending); + if (change === 'logout') await f.destroy('both'); + else if (change === 'admin') await f.revoke('both', ADMIN_ROLE); + else if (change === 'queue') await f.revoke('both', SUPPORT_ROLE); + else body.request.headers.set('Cookie', f.cookies.get('peer')!); + } finally { body.complete(); } + const response = await pending; + expect(response.status).toBe(change === 'logout' ? 401 : 403); + expect(await f.policyRows()).toEqual(before); expect(f.state.runtimeCalls).toBe(calls); + expect(await object(response)).not.toHaveProperty('result'); + }); + + it('accepts a genuine legal eight-repository UTF8 intent above64KiB through the policy-only128KiB reader', async () => { + const f = await fixture(); const repositories = Array.from({ length: 8 }, (_value, index) => ({ key: 'Wide-' + index, + descriptor: { ...engineeringRepositories[0]!, repositoryId: 'synthetic-wide-' + index, + responsibilities: '界'.repeat(2_000), product: '界'.repeat(750) } })); + const handle = createSupportEngineeringHandlers({ ...f.options, repositories }); + const prepared = await handle(f.request('policy/prepare', { commandId: 'WIDE-INTENT-EXACT', expectedGeneration: 1, + enabled: true, repositoryKeys: repositories.map((entry) => entry.key) }, 'both')); + expect(prepared?.status).toBe(200); if (prepared === null) throw new Error('Expected prepare route'); + const value = result(await object(prepared)); if (!isPlainObject(value.intent)) throw new Error('Expected full intent'); + const retained = { intent: value.intent }; + const bytes = new TextEncoder().encode(JSON.stringify(retained)).byteLength; + expect(bytes).toBeGreaterThan(65_536); expect(bytes).toBeLessThanOrEqual(131_072); + expect((await handle(f.request('policy', retained, 'both')))?.status).toBe(200); + expect((await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).policy.repositories).toHaveLength(8); + }); + + it('keeps policy submit physically bounded and requires CSRF even for read-only preparation', async () => { + const f = await fixture(); const before = await f.policyRows(); + const incoming = f.request('policy/prepare', { commandId: 'PREPARE-CSRF', expectedGeneration: 1, enabled: true, repositoryKeys: [] }, 'both'); + incoming.headers.delete('X-Pegma-CSRF'); expect((await f.send(incoming)).status).toBe(403); + expect((await f.send(f.request('policy', { intent: 'x'.repeat(131_073) }, 'both'))).status).toBe(413); + expect(await f.policyRows()).toEqual(before); + }); + + it('reports an absent configured catalog and unmapped durable rows without silently rewriting them', async () => { + const f = await fixture(); const before = await f.policyRows(); + const handle = createSupportEngineeringHandlers({ ...f.options, repositories: [] }); + const response = await handle(f.request('policy', undefined, 'both')); + expect(response?.status).toBe(200); + if (response === null) throw new Error('Expected owned policy route'); + const view = result(await object(response)); + expect(view.catalog).toEqual([]); expect(view.repositories).toEqual([]); + expect(view.unmappedRepositoryCount).toBe(2); expect(await f.policyRows()).toEqual(before); + }); + + it('preserves catalog key case and accepts exactly twenty unique server entries without a policy write', async () => { + const f = await fixture(); const before = await f.policyRows(); + const repositories = [ + { key: 'Core-V1', descriptor: engineeringRepositories[0]! }, + { key: 'API-v1', descriptor: engineeringRepositories[1]! }, + ...Array.from({ length: 18 }, (_value, index) => ({ key: 'Unused-' + index, + descriptor: { ...engineeringRepositories[0]!, repositoryId: 'synthetic-unused-' + index } })), + ]; + const handle = createSupportEngineeringHandlers({ ...f.options, repositories }); + const response = await handle(f.request('policy', undefined, 'both')); + expect(response?.status).toBe(200); + if (response === null) throw new Error('Expected owned policy route'); + const view = result(await object(response)); + expect(view.catalog).toEqual(repositories.map((entry) => ({ key: entry.key, enabled: true }))); + expect(view.repositories).toEqual([{ key: 'Core-V1', enabled: true }, { key: 'API-v1', enabled: true }]); + expect(await f.policyRows()).toEqual(before); + }); + + it.each(['duplicate-key', 'duplicate-id', 'over-limit', 'empty-key', 'wide-key', 'control-key', 'empty-id'] as const)( + 'refuses invalid trusted catalog %s before a runtime or policy mutation', async (kind) => { + const f = await fixture(); const before = await f.policyRows(); + const first = engineeringRepositories[0]!; const second = engineeringRepositories[1]!; + const repositories = kind === 'duplicate-key' ? [{ key: 'same', descriptor: first }, { key: 'same', descriptor: second }] + : kind === 'duplicate-id' ? [{ key: 'one', descriptor: first }, { key: 'two', descriptor: first }] + : kind === 'over-limit' ? Array.from({ length: 21 }, (_value, index) => ({ key: 'entry-' + index, + descriptor: { ...first, repositoryId: 'synthetic-entry-' + index } })) + : [{ key: kind === 'empty-key' ? '' : kind === 'wide-key' ? 'x'.repeat(101) : kind === 'control-key' ? 'bad\u0000key' : 'valid-key', + descriptor: kind === 'empty-id' ? { ...first, repositoryId: '' } : first }]; + expect(() => createSupportEngineeringHandlers({ ...f.options, repositories })).toThrow(TypeError); + expect(f.state.runtimeCalls).toBe(0); expect(await f.policyRows()).toEqual(before); + }); + + it.each([{ publicationMode: 'automatic' }, { repositoryUrl: 'https://foreign.example' }, { metadataProof: 'forged' }])( + 'refuses client publication/routing authority in policy configuration: %j', async (extra) => { + const f = await fixture(); const before = await f.policyRows(); + expect((await f.send(f.request('policy/prepare', { commandId: 'POLICY-DENIED', expectedGeneration: 1, enabled: true, + repositoryKeys: [engineeringRepositories[0]!.repositoryId], ...extra }, 'both'))).status).toBe(400); + expect(await f.policyRows()).toEqual(before); expect(f.engineering.state.creates).toEqual([]); + }); + + it('rejects unknown or duplicate server policy keys and stale generation without a write', async () => { + const f = await fixture(); const before = await f.policyRows(); + for (const packet of [ + { commandId: 'POLICY-UNKNOWN', expectedGeneration: 1, enabled: true, repositoryKeys: ['not-configured'] }, + { commandId: 'POLICY-DUPLICATE', expectedGeneration: 1, enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId, engineeringRepositories[0]!.repositoryId] }, + { commandId: 'POLICY-STALE', expectedGeneration: 0, enabled: true, repositoryKeys: [] }, + ]) expect((await f.send(f.request('policy/prepare', packet, 'both'))).status).toBe(packet.commandId === 'POLICY-STALE' ? 409 : 400); + expect(await f.policyRows()).toEqual(before); + }); + + it('keeps current metadata mandatory in the actual SDK after a declarative allowlist is configured', async () => { + const f = await fixture(); await f.verified(); expect((await f.process()).outcome).toBe('candidate'); + f.engineering.state.installationActive = false; + expect((await f.process()).outcome).toBe('held'); + expect((await f.work()).proposal).toBeUndefined(); expect(f.engineering.state.creates).toEqual([]); + }); + + it('disables exports through the SDK while model configuration is OFF', async () => { + const f = await fixture(); f.engineering.state.enabled = false; f.engineering.state.configuration = 'disabled'; + const before = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + const response = await f.send(f.request('policy/disable', { commandId: 'DISABLE-EXACT', expectedGeneration: before.generation }, 'both')); + expect(response.status).toBe(200); expect(result(await object(response)).enabled).toBe(false); + expect((await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).policy.enabled).toBe(false); + }); + + it.each(['logout', 'role', 'header'] as const)('rechecks %s after a delayed body before enrollment', async (change) => { + const f = await fixture(); const ticket = await f.engineering.createTicket(); const before = await f.rows(); + const body = await controlledHumanBody(f.request('enroll', { commandId: 'BODY-RACE', expectedRevision: ticket.revision })); + const pending = f.send(body.request); + try { + await body.waitFor(pending); + if (change === 'logout') await f.destroy('staff'); + else if (change === 'role') await f.revoke('staff', SUPPORT_ROLE); + else body.request.headers.set('Cookie', f.cookies.get('peer')!); + } finally { body.complete(); } + expect([401, 403]).toContain((await pending).status); expect(await f.rows()).toEqual(before); + }); + + it('rechecks current authority after the real limiter before beginning the protected body/SDK operation', async () => { + const f = await fixture(); const ticket = await f.legacyTicket(); const before = await f.rows(); + let revoked = false; + const limiter = { ...f.options.limiter, async allow(...args: Parameters) { + const decision = await f.options.limiter.allow(...args); + if (!revoked) { revoked = true; await f.revoke('staff', SUPPORT_ROLE); } + return decision; + } }; + const handle = createSupportEngineeringHandlers({ ...f.options, limiter }); + const response = await handle(f.request('enroll', { commandId: 'LIMITER-HANDOFF-EXACT', expectedRevision: ticket.revision })); + expect(response?.status).toBe(403); expect(revoked).toBe(true); + expect(await f.rows()).toEqual(before); expect(f.state.runtimeCalls).toBe(0); + }); + + it.each([ADMIN_ROLE, SUPPORT_ROLE])('rechecks %s after an actual policy head read before any policy write', async (role) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'HEAD-AUTH-HANDOFF', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const original = f.state.runtime; let revoked = false; const before = await f.policyRows(); + f.state.runtime = { ...original, async readPolicy(access) { + const head = await original.readPolicy(access); + if (!revoked) { revoked = true; await f.revoke('both', role); } + return head; + } }; + expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(403); + expect(revoked).toBe(true); expect(await f.policyRows()).toEqual(before); + }); + + it.each([ADMIN_ROLE, SUPPORT_ROLE])('rechecks %s after local intent hashing before any policy write', async (role) => { + const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'DIGEST-AUTH-HANDOFF', expectedGeneration: 1, + enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); + const before = await f.policyRows(); const original = f.state.runtime; let puts = 0; + f.state.runtime = { ...original, async putPolicy(...args: Parameters) { + puts += 1; return original.putPolicy(...args); + } }; + let entered = false; let release = () => {}; + const hold = new Promise((resolve) => { release = resolve; }); + const target = JSON.stringify(retained.intent); const digest = crypto.subtle.digest.bind(crypto.subtle); + const spy = vi.spyOn(crypto.subtle, 'digest').mockImplementation(async (algorithm, bytes) => { + if (!entered && new TextDecoder().decode(bytes) === target) { entered = true; await hold; } + return digest(algorithm, bytes); + }); + const pending = f.send(f.request('policy', retained, 'both')); + try { + await vi.waitFor(() => expect(entered).toBe(true), { timeout: 3_000 }); + await f.revoke('both', role); release(); + const response = await pending; + expect(response.status).toBe(403); expect(puts).toBe(0); + expect(await f.policyRows()).toEqual(before); expect(await object(response)).not.toHaveProperty('result'); + } finally { release(); try { await pending; } finally { spy.mockRestore(); } } + }); + + it('withholds a committed enrollment ACK after actual role revocation without inventing rollback', async () => { + const f = await fixture(); const ticket = await f.legacyTicket(); + expect((await f.rows()).some((row) => row.kind === 'engineering_source')).toBe(false); + let commits = 0; + f.hooks.commit = async () => { commits += 1; if (commits === 1) await f.revoke('staff', SUPPORT_ROLE); }; + const packet = { commandId: 'COMMITTED-ENROLLMENT', expectedRevision: ticket.revision }; + expect((await f.send(f.request('enroll', packet))).status).toBe(403); + expect(commits).toBe(1); + const committed = await f.rows(); + expect(committed.filter((row) => row.kind === 'engineering_source')).toHaveLength(1); + expect(committed.filter((row) => row.kind === 'engineering_receipt')).toHaveLength(1); + // A new real audited grant restores current authority; an exact SDK replay + // returns the retained ACK without another Source/receipt transaction. + await f.host.roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'engineering-http-restored-staff-Support', principalId: f.principals.staff, role: SUPPORT_ROLE, + scope: APPLICATION_SCOPE, grantedBy: { kind: 'system', systemId: 'synthetic-engineering-http' }, + grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'engineering-http-restored-staff-grant' }); + expect((await f.send(f.request('enroll', packet))).status).toBe(200); + expect(commits).toBe(1); expect(await f.rows()).toEqual(committed); + }); + + it('withholds a committed policy ACK after real Admin revocation while preserving the SDK mutation', async () => { + const f = await fixture(); f.hooks.policy = async () => { delete f.hooks.policy; await f.revoke('both', ADMIN_ROLE); }; + const response = await f.send(f.request('policy/disable', { commandId: 'COMMITTED-POLICY', expectedGeneration: 1 }, 'both')); + expect(response.status).toBe(403); + expect((await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).policy.enabled).toBe(false); + }); + + it('recovers the exact SDK enrollment receipt after a synthetic post-commit response loss', async () => { + const f = await fixture(); const ticket = await f.engineering.createTicket(); const original = f.state.runtime; let lose = true; + f.state.runtime = { ...original, async enroll(access, packet) { + const value = await original.enroll(access, packet); if (lose) { lose = false; throw new Error('Synthetic response loss'); } return value; + } }; + const packet = { commandId: 'LOST-ACK-EXACT', expectedRevision: ticket.revision }; + expect((await f.send(f.request('enroll', packet))).status).toBe(503); const rows = await f.rows(); + expect((await f.send(f.request('enroll', packet))).status).toBe(200); expect(await f.rows()).toEqual(rows); + }); + + it.each([false, true])('applies final original-session checks to a private read or failed read (failure=%s)', async (fail) => { + const f = await fixture(); await f.verified(); const original = f.state.runtime; + f.state.runtime = { ...original, async readSource(access, ticketId) { + const value = await original.readSource(access, ticketId); await f.destroy('staff'); + if (fail) throw new Error('SYNTHETIC_PRIVATE_DEPENDENCY_FAILURE'); return value; + } }; + const response = await f.send(f.request()); expect(response.status).toBe(401); + expect(await object(response)).toEqual({ error: 'authentication_required' }); + }); + + it.each(['invalidate', 'withdraw'] as const)('keeps authorized %s available with processing OFF', async (operation) => { + const f = await fixture(); await f.verified(); f.engineering.state.enabled = false; + const response = await f.send(f.request(operation, { commandId: operation.toUpperCase() + '-EXACT', + reason: operation === 'withdraw' ? 'privacy_withdrawal' : 'evidence_revoked' })); + expect(response.status).toBe(200); + expect(result(await object(response)).state).toBe(operation === 'withdraw' ? 'withdrawn' : 'held'); + expect(f.engineering.state.modelCalls).toBe(0); + }); + + it('shares the existing durable limiter and returns its Retry-After without a private factory call', async () => { + const f = await fixture(); for (let index = 0; index < 30; index += 1) await f.host.replyLimiter.allow(f.principals.staff); + const response = await f.send(f.request()); expect(response.status).toBe(429); + expect(Number(response.headers.get('Retry-After'))).toBeGreaterThan(0); + expect(await object(response)).toEqual({ error: 'rate_limited' }); expect(f.state.runtimeCalls).toBe(0); + }); + + it('enforces existing byte/scalar limits and the finite delayed-body deadline', async () => { + const f = await fixture(); const ticket = await f.engineering.createTicket(); const before = await f.rows(); + expect((await f.send(f.request('enroll', { commandId: 'x'.repeat(201), expectedRevision: ticket.revision }))).status).toBe(400); + expect((await f.send(f.request('enroll', { commandId: 'x'.repeat(65_536), expectedRevision: ticket.revision }))).status).toBe(413); + const body = await controlledHumanBody(f.request('enroll', { commandId: 'UNFINISHED', expectedRevision: ticket.revision })); + vi.useFakeTimers(); const pending = f.send(body.request); + try { + await body.waitFor(pending); await vi.advanceTimersByTimeAsync(10_001); + expect((await pending).status).toBe(408); expect(body.cancellations).toBeGreaterThan(0); + expect(await f.rows()).toEqual(before); + } finally { body.complete(); vi.useRealTimers(); } + }); +}); diff --git a/worker/src/support-engineering-handlers.ts b/worker/src/support-engineering-handlers.ts new file mode 100644 index 0000000..72b0ce6 --- /dev/null +++ b/worker/src/support-engineering-handlers.ts @@ -0,0 +1,402 @@ +import { hasPermission, type AccessContext } from '@pegma/authorization-core'; +import type { DurableRateLimiter } from '@pegma/rate-limit'; +import { + supportPermissions, + engineeringPolicyRecords, + type EngineeringRepositoryPolicy, + type EngineeringRepositoryDescriptor, + type EngineeringSourceResult, + type EngineeringStepResult, + type EngineeringSourceRecord, + type EngineeringWorkRecord, +} from '@pegma/support-desk-application'; +import { createAgentPrincipalResolver, type AgentBrowserOptions } from './agent-authority'; +import { + ApiError, authenticate, boundedString, enforceRateLimit, exactObject, json, readJson, +} from './api-auth'; +import { ADMIN_ROLE } from './support-access'; +import { mapSupportError } from './support-desk'; +import { supportHumanBrowser } from './support-human-auth'; +import type { EngineeringFailurePacket, SupportEngineeringRuntime } from './support-engineering'; +import { engineeringProposalView, engineeringReviewIntent } from './support-engineering-review'; + +/** Immutable server configuration. A key must never be rebound to another repository. */ +export interface EngineeringHttpRepository { + readonly key: string; + readonly descriptor: EngineeringRepositoryDescriptor; +} + +/** Opaque retained JSON, not a token or authority. Never display or log it. */ +export interface EngineeringPolicyIntent { + readonly version: 1; + readonly actorId: string; + readonly commandId: string; + readonly expectedGeneration: number; + readonly repositoryKeys: readonly string[]; + readonly policy: EngineeringRepositoryPolicy; +} +const policyIntentBytes = 131_072; + +function policyKeys(value: unknown): string[] { + if (!Array.isArray(value) || value.length > 20) throw new ApiError(400, 'invalid_request'); + const keys = value.map((key) => boundedString(key, 1, 100)); + if (new Set(keys).size !== keys.length || keys.some((key) => key.trim() !== key)) + throw new ApiError(400, 'invalid_request'); + return keys; +} + +function normalizedPolicy(raw: unknown): EngineeringRepositoryPolicy { + try { + // Public schema validation only. This synthetic envelope is never persisted + // or claimed to be a real head, generation, digest or authorization proof. + // Minimum legal generation avoids falsely rejecting an old accepted policy + // merely because a current generation occupies more serialized digits. + const value = engineeringPolicyRecords.codec.decode({ partition: 'instance', id: 'policy', json: JSON.stringify({ + kind: 'engineering_policy', partition: 'instance', id: 'policy', generation: 1, + policyHash: '0'.repeat(64), policy: raw, + }) }); + if (value.kind !== 'engineering_policy') throw new TypeError('Invalid validation result'); + return value.policy; + } catch { throw new ApiError(400, 'invalid_request'); } +} + +function policyIntent(raw: unknown): EngineeringPolicyIntent { + const value = exactObject(raw, ['version', 'actorId', 'commandId', 'expectedGeneration', 'repositoryKeys', 'policy']); + if (value.version !== 1) throw new ApiError(400, 'invalid_request'); + const policy = normalizedPolicy(value.policy); + const repositoryKeys = policyKeys(value.repositoryKeys); + if (repositoryKeys.length !== policy.repositories.length) throw new ApiError(400, 'invalid_request'); + const intent: EngineeringPolicyIntent = { version: 1, actorId: boundedString(value.actorId, 1, 200), + commandId: boundedString(value.commandId, 1, 200), expectedGeneration: integer(value.expectedGeneration, 0), + repositoryKeys, policy }; + if (new TextEncoder().encode(JSON.stringify({ intent })).byteLength > policyIntentBytes) + throw new ApiError(413, 'request_too_large'); + return intent; +} + +async function intentFingerprint(intent: EngineeringPolicyIntent): Promise { + const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(intent))); + return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +/** Inert assembly only. No route, scheduler, Store or outbound client is registered. */ +export interface SupportEngineeringHandlerOptions extends AgentBrowserOptions { + readonly enabled?: () => boolean; + /** Separate current human review gate, with strict false as the default. */ + readonly reviewEnabled?: () => boolean; + readonly runtime: () => SupportEngineeringRuntime; + readonly limiter: DurableRateLimiter; + readonly repositories?: readonly EngineeringHttpRepository[]; +} + +type Operation = 'source' | 'work' | 'proposal' | 'review' | 'enroll' | 'evidence' | 'withdraw' | 'invalidate' | 'repository' | + 'policy_read' | 'policy_prepare' | 'policy_put' | 'policy_disable'; +const ticketPath = /^\/api\/support\/admin\/tickets\/([A-Za-z0-9._~-]{1,200})\/engineering(?:\/(work|proposal|review|enroll|evidence|withdraw|invalidate|repository))?$/u; +const policyPath = '/api/support/admin/engineering/policy'; + +function integer(value: unknown, minimum = 1): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum) + throw new ApiError(400, 'invalid_request'); + return value; +} +function fingerprint(value: unknown): string { + const text = boundedString(value, 64, 64); + if (!/^[a-f0-9]{64}$/u.test(text)) throw new ApiError(400, 'invalid_request'); + return text; +} +function strings(value: unknown, maximum: number, characters: number, multiline = false): string[] { + if (!Array.isArray(value) || value.length === 0 || value.length > maximum) + throw new ApiError(400, 'invalid_request'); + const result = value.map((entry) => boundedString(entry, 1, characters, { allowMultiline: multiline })); + if (!multiline && new Set(result).size !== result.length) throw new ApiError(400, 'invalid_request'); + return result; +} +function generation(url: URL): number { + if (url.searchParams.size !== 1 || url.searchParams.getAll('sourceGeneration').length !== 1) + throw new ApiError(400, 'invalid_request'); + const value = url.searchParams.get('sourceGeneration'); + if (value === null || !/^[1-9][0-9]*$/u.test(value)) throw new ApiError(400, 'invalid_request'); + return integer(Number(value)); +} +function permission(operation: Operation): string { + if (operation === 'enroll' || operation === 'evidence') return supportPermissions.engineeringEvidenceSubmit; + if (operation === 'withdraw' || operation === 'invalidate') return supportPermissions.engineeringWithdraw; + if (operation === 'repository' || operation === 'review') return supportPermissions.engineeringReview; + if (operation === 'policy_read') return supportPermissions.engineeringPolicyRead; + if (operation === 'policy_prepare' || operation === 'policy_put' || operation === 'policy_disable') return supportPermissions.engineeringPolicyManage; + return supportPermissions.engineeringRead; +} +function sourceDto(source: EngineeringSourceRecord) { + return { ticketId: source.ticketId, sourceGeneration: source.sourceGeneration, + workGeneration: source.workGeneration, state: source.state, security: source.security, + hasEvidence: source.evidence !== undefined, hasProductContext: source.product !== undefined, + destinationCount: source.destinations.length, reconciliationPending: source.reconciliationPending }; +} +function workDto(work: EngineeringWorkRecord) { + return { ticketId: work.ticketId, sourceGeneration: work.sourceGeneration, workGeneration: work.workGeneration, + status: work.status, stage: work.stage, security: work.security, hasCandidate: work.candidateHash !== undefined, + hasPreparedProposal: work.proposal !== undefined, hasApproval: work.approval !== undefined, + hasDispatch: work.dispatch !== undefined }; +} +function sourceResultDto(value: EngineeringSourceResult) { + return { ticketId: value.ticketId, sourceGeneration: value.sourceGeneration, state: value.state, security: value.security }; +} +function stepDto(value: EngineeringStepResult) { + return { ticketId: value.ticketId, sourceGeneration: value.sourceGeneration, + workGeneration: value.workGeneration, status: value.status }; +} +function mapped(error: unknown): ApiError { + if (error instanceof ApiError) return error; + const result = mapSupportError(error); + return new ApiError(result.status >= 500 ? 503 : result.status, + result.status >= 500 ? 'support_engineering_unavailable' : result.code, result.retryAfterSeconds); +} + +/** + * Checked proposal reads and explicit approval or rejection require current + * human authority. The original full SDK command supports receipt-first retry. + * The public coordinator carries the fresh browser guard to the commit boundary. + * Worker processing and dispatch use their separate SDK paths. + */ +export function createSupportEngineeringHandlers(options: SupportEngineeringHandlerOptions) { + const resolve = createAgentPrincipalResolver(options); + const configured = structuredClone(options.repositories ?? []); + if (!Array.isArray(configured) || configured.length > 20) + throw new TypeError('Invalid engineering repository catalog'); + const keys = new Set(); + const identities = new Set(); + for (const entry of configured) { + const key = entry?.key; + const id = entry?.descriptor?.repositoryId; + if (typeof key !== 'string' || key.length < 1 || key.length > 100 || key.trim() !== key || + /[\u0000-\u001F\u007F-\u009F]/u.test(key) || keys.has(key) || + typeof id !== 'string' || id.length < 1 || id.length > 200 || id.trim() !== id || id.includes('://') || + /[\u0000-\u001F\u007F-\u009F]/u.test(id) || identities.has(id) || + typeof entry.descriptor.enabled !== 'boolean' || entry.descriptor.publicationMode !== 'approval_required') + throw new TypeError('Invalid engineering repository catalog'); + keys.add(key); identities.add(id); + } + function enabled() { try { return options.enabled?.() === true; } catch { return false; } } + function repository(key: unknown): EngineeringHttpRepository { + const name = boundedString(key, 1, 100); + if (configured.length === 0) throw new ApiError(503, 'repository_configuration_unavailable'); + const found = configured.filter((entry) => entry.key === name); + if (found.length !== 1) throw new ApiError(400, 'invalid_request'); + return found[0]!; + } + return async function handle(request: Request): Promise { + const url = new URL(request.url); + const match = ticketPath.exec(url.pathname); + const policy = url.pathname === policyPath || url.pathname === policyPath + '/disable' || url.pathname === policyPath + '/prepare'; + if (match === null && !policy) return null; + if (!enabled()) return json({ error: 'support_engineering_disabled' }, { status: 503 }); + const ticketId = match?.[1]; + const suffix = match?.[2]; + const operation: Operation = policy + ? url.pathname.endsWith('/disable') ? 'policy_disable' : url.pathname.endsWith('/prepare') ? 'policy_prepare' + : request.method === 'GET' ? 'policy_read' : 'policy_put' + : suffix === 'work' || suffix === 'proposal' || suffix === 'review' || suffix === 'enroll' || suffix === 'evidence' || suffix === 'withdraw' || + suffix === 'invalidate' || suffix === 'repository' ? suffix : 'source'; + if (operation === 'proposal' || operation === 'review') { + let admitted = false; + try { admitted = options.reviewEnabled?.() === true; } catch { /* Default OFF. */ } + if (!admitted) return json({ error: 'support_engineering_review_disabled' }, { status: 503 }); + } + const mutation = !['source', 'work', 'proposal', 'policy_read'].includes(operation); + const required = permission(operation); + const browser = supportHumanBrowser(request, { + sessions: options.sessions, mutation, permission: required, + async authenticate(incoming) { + const value = await authenticate(incoming, options); + if (value === null) throw new ApiError(401, 'authentication_required'); + return value; + }, + async access(authenticated) { + const value = await resolve(authenticated.link.subject); + if (value === null) throw new ApiError(401, 'authentication_required'); + return value; + }, + }); + let ceiling: AccessContext | undefined; + async function current() { + if (!enabled()) throw new ApiError(503, 'support_engineering_disabled'); + const reviewIsCurrent = () => { + if (operation !== 'proposal' && operation !== 'review') return; + let admitted = false; + try { admitted = options.reviewEnabled?.() === true; } catch { /* Default OFF. */ } + if (!admitted) throw new ApiError(503, 'support_engineering_review_disabled'); + }; + reviewIsCurrent(); + const fresh = await browser.current(); + reviewIsCurrent(); + if (!enabled()) throw new ApiError(503, 'support_engineering_disabled'); + ceiling ??= structuredClone(fresh.access); + const access: AccessContext = { principalId: ceiling.principalId, policyVersion: fresh.access.policyVersion, + roles: fresh.access.roles.filter((entry) => ceiling?.roles.includes(entry)), + entitlements: fresh.access.entitlements.filter((entry) => ceiling?.entitlements.includes(entry)), + permissions: fresh.access.permissions.filter((entry) => ceiling?.permissions.includes(entry)) }; + for (const needed of [required, supportPermissions.queueRead]) + if (!hasPermission(access, needed)) throw new ApiError(403, 'forbidden'); + if (policy && !access.roles.includes(ADMIN_ROLE)) throw new ApiError(403, 'forbidden'); + return { access, csrfToken: fresh.authenticated.csrfToken }; + } + async function awaited(run: (access: AccessContext) => Promise): Promise { + // Each protected operation starts with current authority. Its successor + // repeats that fence; the final/catch fence protects every response. + // Between them, callers only validate/project locally: no output, SDK + // write or external operation may occur without its own fresh precheck. + const actor = await current(); return run(actor.access); + } + try { + if (request.method !== (mutation ? 'POST' : 'GET')) throw new ApiError(405, 'method_not_allowed'); + if (url.hash !== '' || (!['work', 'proposal'].includes(operation) && url.search !== '')) throw new ApiError(400, 'invalid_request'); + const initial = await current(); + const principalId = initial.access.principalId; + await enforceRateLimit(options.limiter, principalId); + let result: unknown; + if (operation === 'policy_read') { + const value = await awaited((access) => options.runtime().readPolicy(access)); + const repositories = value.policy.repositories.flatMap((descriptor) => { + const entry = configured.find((item) => item.descriptor.repositoryId === descriptor.repositoryId); + return entry === undefined ? [] : [{ key: entry.key, enabled: descriptor.enabled }]; + }); + result = { generation: value.generation, policyHash: value.policyHash, enabled: value.policy.enabled, + repositories, unmappedRepositoryCount: value.policy.repositories.length - repositories.length, + // Full server configuration, including unselected entries. This is + // not installation, visibility, calibration or export authority. + catalog: configured.map((entry) => ({ key: entry.key, enabled: entry.descriptor.enabled })) }; + } else if (operation === 'source') { + if (ticketId === undefined) throw new ApiError(400, 'invalid_request'); + result = sourceDto(await awaited((access) => options.runtime().readSource(access, ticketId))); + } else if (operation === 'proposal') { + if (ticketId === undefined) throw new ApiError(400, 'invalid_request'); + const work = await awaited((access) => options.runtime().readWork(access, { ticketId, sourceGeneration: generation(url) })); + const actor = await current(); + if (!hasPermission(actor.access, supportPermissions.engineeringReview)) throw new ApiError(403, 'forbidden'); + result = await engineeringProposalView(work, actor.access.principalId); + } else if (operation === 'work') { + if (ticketId === undefined) throw new ApiError(400, 'invalid_request'); + const sourceGeneration = generation(url); + const work = await awaited((access) => options.runtime().readWork(access, { ticketId, sourceGeneration })); + const actor = await current(); + const choice = hasPermission(actor.access, supportPermissions.engineeringReview) && + hasPermission(actor.access, supportPermissions.engineeringPolicyRead) + ? await awaited((access) => options.runtime().readPolicy(access)) : null; + result = { ...workDto(work), ...(choice === null ? {} : { selection: { + policyGeneration: choice.generation, policyHash: choice.policyHash, + repositoryKeys: configured.filter((entry) => choice.policy.repositories.some((allowed) => + allowed.repositoryId === entry.descriptor.repositoryId && allowed.enabled)).map((entry) => entry.key), + } }) }; + } else { + const body = await awaited(() => readJson(request, { timeoutMs: 10_000, + ...(operation === 'policy_put' ? { maxBytes: policyIntentBytes } : {}) })); + if (operation === 'policy_prepare') { + const packet = exactObject(body, ['commandId', 'expectedGeneration', 'enabled', 'repositoryKeys']); + const commandId = boundedString(packet.commandId, 1, 200); + const expectedGeneration = integer(packet.expectedGeneration, 0); + if (typeof packet.enabled !== 'boolean') throw new ApiError(400, 'invalid_request'); + const active = packet.enabled; + const keys = policyKeys(packet.repositoryKeys); + const currentPolicy = await awaited((access) => options.runtime().readPolicy(access)); + if (currentPolicy.generation !== expectedGeneration) throw new ApiError(409, 'policy_changed'); + const actor = await current(); + result = { intent: policyIntent({ version: 1, actorId: actor.access.principalId, commandId, expectedGeneration, + repositoryKeys: keys, policy: { enabled: active, repositories: keys.map((key) => repository(key).descriptor) } }) }; + } else if (operation === 'policy_put') { + const packet = exactObject(body, ['intent']); + const intent = policyIntent(packet.intent); + // Identity equality only: never reuse admission roles/permissions. + // The immediately following head read performs fresh browser auth. + if (intent.actorId !== principalId) throw new ApiError(403, 'forbidden'); + const currentPolicy = await awaited((access) => options.runtime().readPolicy(access)); + if (currentPolicy.generation < intent.expectedGeneration) throw new ApiError(409, 'policy_changed'); + if (currentPolicy.generation === intent.expectedGeneration) { + const currentPolicyPacket = normalizedPolicy({ enabled: intent.policy.enabled, + repositories: intent.repositoryKeys.map((key) => repository(key).descriptor) }); + if (JSON.stringify(currentPolicyPacket) !== JSON.stringify(intent.policy)) + throw new ApiError(409, 'policy_intent_changed'); + } + // A monotonic newer head makes this receipt-only: the public SDK + // replays an exact receipt before CAS; no missing/pruned receipt can + // write under the stale generation. Never reconstruct old snapshots + // from a changed/removed catalog or add a mutable metadata gate. + // Local hashing carries no authority; the write refreshes after it. + const binding = await intentFingerprint(intent); + const value = await awaited((access) => options.runtime().putPolicy(access, { + clientCommandId: intent.commandId, expectedGeneration: intent.expectedGeneration, policy: intent.policy, + }, binding)); + result = { generation: value.generation, policyHash: value.policyHash, enabled: value.enabled }; + } else if (operation === 'policy_disable') { + const packet = exactObject(body, ['commandId', 'expectedGeneration']); + const value = await awaited((access) => options.runtime().disableExports(access, { + clientCommandId: boundedString(packet.commandId, 1, 200), expectedGeneration: integer(packet.expectedGeneration, 0), + })); + result = { generation: value.generation, policyHash: value.policyHash, enabled: value.enabled }; + } else { + if (ticketId === undefined) throw new ApiError(400, 'invalid_request'); + if (operation === 'review') { + const packet = exactObject(body, ['intent']); + const intent = engineeringReviewIntent(packet.intent, ticketId); + if (intent.actorId !== principalId) throw new ApiError(403, 'forbidden'); + // No Work, Source, repository catalog or policy pre-read here. A + // committed historical ACK must survive changes to those resources. + result = stepDto(await awaited((access) => options.runtime().reviewCommand(access, intent.command, + async () => { await current(); }))); + } else if (operation === 'enroll') { + const packet = exactObject(body, ['commandId', 'expectedRevision']); + result = sourceResultDto(await awaited((access) => options.runtime().enroll(access, { ticketId, + clientCommandId: boundedString(packet.commandId, 1, 200), expectedRevision: integer(packet.expectedRevision) }))); + } else if (operation === 'evidence') { + const packet = exactObject(body, ['commandId', 'expectedRevision', 'expectedBehavior', 'actualBehavior', + 'reproductionSteps', 'visibleMessageIds', 'verificationReference', 'security']); + if (packet.security !== 'ordinary' && packet.security !== 'restricted' && packet.security !== 'uncertain') + throw new ApiError(400, 'invalid_request'); + const input: EngineeringFailurePacket = { ticketId, clientCommandId: boundedString(packet.commandId, 1, 200), + expectedRevision: integer(packet.expectedRevision), security: packet.security, + evidence: { kind: 'staff_verified_failure' as const, + expectedBehavior: boundedString(packet.expectedBehavior, 1, 2_000, { allowMultiline: true }), + actualBehavior: boundedString(packet.actualBehavior, 1, 2_000, { allowMultiline: true }), + reproductionSteps: strings(packet.reproductionSteps, 16, 1_000, true), + visibleMessageIds: strings(packet.visibleMessageIds, 16, 200), + verificationReference: boundedString(packet.verificationReference, 1, 200) } }; + result = sourceResultDto(await awaited((access) => options.runtime().submitVerifiedFailure(access, input))); + } else if (operation === 'repository') { + const packet = exactObject(body, ['commandId', 'sourceGeneration', 'expectedWorkGeneration', + 'repositoryKey', 'policyGeneration', 'policyHash', 'reason']); + const selected = repository(packet.repositoryKey); + result = stepDto(await awaited((access) => options.runtime().selectRepository(access, { ticketId, + clientCommandId: boundedString(packet.commandId, 1, 200), sourceGeneration: integer(packet.sourceGeneration), + expectedWorkGeneration: integer(packet.expectedWorkGeneration), repositoryId: selected.descriptor.repositoryId, + policyGeneration: integer(packet.policyGeneration, 0), policyHash: fingerprint(packet.policyHash), + reason: boundedString(packet.reason, 1, 200) }))); + } else if (operation === 'invalidate') { + const packet = exactObject(body, ['commandId', 'reason']); + if (packet.reason !== 'evidence_revoked' && packet.reason !== 'product_binding_revoked' && packet.reason !== 'check_policy_revoked') + throw new ApiError(400, 'invalid_request'); + const reason = packet.reason; + result = sourceResultDto(await awaited((access) => options.runtime().invalidate(access, { ticketId, + clientCommandId: boundedString(packet.commandId, 1, 200), reason }))); + } else { + const packet = exactObject(body, ['commandId', 'reason']); + if (packet.reason !== 'privacy_withdrawal' && packet.reason !== 'source_access_revoked' && packet.reason !== 'source_deleted') + throw new ApiError(400, 'invalid_request'); + const reason = packet.reason; + result = sourceResultDto(await awaited((access) => options.runtime().withdraw(access, { ticketId, + clientCommandId: boundedString(packet.commandId, 1, 200), reason }))); + } + } + } + const final = await current(); + if (operation === 'policy_prepare' && + new TextEncoder().encode(JSON.stringify({ result, csrfToken: final.csrfToken })).byteLength > policyIntentBytes) + throw new ApiError(413, 'request_too_large'); + return json({ result, csrfToken: final.csrfToken }); + } catch (error) { + let failure = error; + try { await current(); } catch (authorityError) { failure = authorityError; } + const value = mapped(failure); + return json({ error: value.code }, { status: value.status, + headers: value.retryAfterSeconds === undefined ? {} : { 'Retry-After': String(value.retryAfterSeconds) } }); + } + }; +} diff --git a/worker/src/support-engineering-http-fixtures.ts b/worker/src/support-engineering-http-fixtures.ts new file mode 100644 index 0000000..8583ad6 --- /dev/null +++ b/worker/src/support-engineering-http-fixtures.ts @@ -0,0 +1,167 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createMemoryStore, type CollectionDefinition, type CollectionStore, type Store } from '@pegma/storage-core'; +import { createSupportDeskApplication, engineeringPolicyRecords, supportRecords } from '@pegma/support-desk-application'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { ADMIN_ROLE, APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE } from './support-access'; +import { createSupportRuntime } from './support-desk'; +import { createSupportEngineeringRuntime } from './support-engineering'; +import { + createSupportEngineeringFixture, engineeringProofReference, engineeringRepositories, engineeringTicketId, +} from './support-engineering-fixtures'; +import { createSupportEngineeringHandlers } from './support-engineering-handlers'; + +export type EngineeringHttpActor = 'staff' | 'admin' | 'both' | 'knowledge' | 'customer' | 'peer'; +export const engineeringHttpRoute = '/api/support/admin/tickets/' + engineeringTicketId + '/engineering'; +export const engineeringHttpPolicyRoute = '/api/support/admin/engineering/policy'; +export const engineeringHttpCommand = 'ABCDEFAB-1234-4ABC-8DEF-ABCDEF123456'; + +export async function engineeringHttpObject(response: Response) { + const value: unknown = await response.json(); + if (!isPlainObject(value)) throw new Error('Expected a synthetic JSON response'); + return value; +} +export function engineeringHttpResult(value: Record) { + if (!isPlainObject(value.result)) throw new Error('Expected an operational SDK result'); + return value.result; +} +export function engineeringHttpNumber(value: unknown) { + if (typeof value !== 'number') throw new Error('Expected an actual numeric SDK fence'); + return value; +} + +/** Actual Identity, Sessions, host RoleStore, durable limiter and Support SDK. */ +export async function createSupportEngineeringHttpFixture(backing: Store = createMemoryStore()) { + const hooks: { commit?: () => Promise; policy?: () => Promise } = {}; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const actual = backing.collection(definition); + if (definition.name !== supportRecords.name && definition.name !== engineeringPolicyRecords.name) return actual; + return { ...actual, async transact(partition, actions) { + const value = await actual.transact(partition, actions); + if (value.committed) { + if (definition.name === supportRecords.name && partition === engineeringTicketId) await hooks.commit?.(); + if (definition.name === engineeringPolicyRecords.name) await hooks.policy?.(); + } + return value; + } }; + }, + }; + const engineering = await createSupportEngineeringFixture(store); + const logger = { log() {} }; + const identityRuntime = createIdentityRuntime({ store, emailCodeSecretBase64: btoa('e'.repeat(32)), + emailFrom: 'Pegma ', emailEnabled: false }, logger); + const { identity, sessions } = identityRuntime; + const host = createSupportRuntime({ store, identity, sessions, logger, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }); + const principals = { staff: engineering.actors.staff.principalId, admin: 'engineering-http-admin', + both: 'engineering-http-admin-support', knowledge: 'engineering-http-knowledge', + customer: engineering.actors.customer.principalId, peer: 'engineering-http-peer' }; + const cookies = new Map(); + const csrf = new Map(); + const sessionIds = new Map(); + for (const [index, actor] of (Object.keys(principals) as EngineeringHttpActor[]).entries()) { + const principalId = principals[actor]; + await identity.provisionVerifiedUser({ principalId, email: actor + '@example.test' }); + const sessionId = String(index + 1).repeat(43); const token = String.fromCharCode(97 + index).repeat(43); + await sessions.create(sessionId, { principalId, data: JSON.stringify({ version: 1, + csrfToken: token, issuer: IDENTITY_ISSUER, subject: principalId }) }); + cookies.set(actor, SESSION_COOKIE + '=' + sessionId); csrf.set(actor, token); sessionIds.set(actor, sessionId); + const roles = actor === 'both' ? [ADMIN_ROLE, SUPPORT_ROLE] : actor === 'admin' ? [ADMIN_ROLE] + : actor === 'knowledge' ? [KNOWLEDGE_ROLE] : actor === 'staff' || actor === 'peer' ? [SUPPORT_ROLE] : []; + for (const role of roles) await host.roleStore.grantRoleAssignmentWithAudit({ assignment: { + id: 'engineering-http-' + actor + '-' + role, principalId, role, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-engineering-http' }, grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'engineering-http-grant-' + actor + '-' + role }); + } + const authority = { identity, sessions, logger, roleStore: host.roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims }; + const resolve = createAgentPrincipalResolver(authority); + const runtime = createSupportEngineeringRuntime({ application: engineering.application, clock: engineering.clock, + ports: engineering.ports, staffAccess: { resolve: (principalId) => resolve(principalId) }, + processingEnabled: () => engineering.state.enabled }); + const state = { enabled: true, runtimeCalls: 0, runtime, captured: [] as string[] }; + const options = { ...authority, enabled: () => state.enabled, limiter: host.replyLimiter, + runtime: () => { state.runtimeCalls += 1; return state.runtime; }, + repositories: engineeringRepositories.map((descriptor) => ({ key: descriptor.repositoryId, descriptor })) }; + const handle = createSupportEngineeringHandlers(options); + function request(operation = '', body?: unknown, actor: EngineeringHttpActor = 'staff', query = '') { + const headers: Record = { Cookie: cookies.get(actor)! }; + if (body !== undefined) Object.assign(headers, { Origin: IDENTITY_ISSUER, 'X-Pegma-CSRF': csrf.get(actor)!, + 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' }); + const target = operation === 'policy' || operation === 'policy/disable' || operation === 'policy/prepare' + ? engineeringHttpPolicyRoute + (operation === 'policy/disable' ? '/disable' : operation === 'policy/prepare' ? '/prepare' : '') + : engineeringHttpRoute + (operation === '' ? '' : '/' + operation); + return new Request(IDENTITY_ISSUER + target + query, { method: body === undefined ? 'GET' : 'POST', headers, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + } + async function send(incoming: Request) { + const response = await handle(incoming); + if (response === null) throw new Error('Expected an owned engineering HTTP route'); + return response; + } + async function revoke(actor: EngineeringHttpActor, role: string) { + const assignmentId = 'engineering-http-' + actor + '-' + role; + const row = await host.roleStore.getRoleAssignment(assignmentId); + if (row === null) throw new Error('Missing actual host role assignment'); + return host.roleStore.revokeRoleAssignmentWithAudit({ assignmentId, expectedConcurrencyToken: row.concurrencyToken, + revokedBy: { kind: 'system', systemId: 'synthetic-engineering-http' }, revokedAtEpochMs: Date.now(), + auditEventId: 'engineering-http-revoke-' + actor + '-' + role }); + } + async function preparePolicy(packet: unknown, actor: EngineeringHttpActor = 'both') { + const response = await send(request('policy/prepare', packet, actor)); + if (response.status !== 200) throw new Error('Actual policy preparation failed: ' + response.status); + const value = engineeringHttpResult(await engineeringHttpObject(response)); + if (!isPlainObject(value.intent)) throw new Error('Expected an actual prepared policy intent'); + return { intent: value.intent }; + } + async function enrolled() { + const ticket = await engineering.createTicket(); + const response = await send(request('enroll', { commandId: engineeringHttpCommand, expectedRevision: ticket.revision })); + if (response.status !== 200) throw new Error('Actual HTTP enrollment failed: ' + response.status); + return ticket; + } + async function legacyTicket() { + // The enabled producer auto-enrolls during creation. Use the actual default- + // disabled SDK factory to make a real legacy ticket so explicit enrollment + // must perform its own Source/Audit/receipt transaction. + const legacy = createSupportDeskApplication({ store, clock: engineering.clock }); + await legacy.createCustomerTicket(engineering.actors.customer, { ...engineering.command('legacy-ticket'), + ticketId: engineeringTicketId, messageId: 'engineering-question', subject: 'Fictional legacy export question', + body: 'A fictional export is empty.' }); + return (await engineering.application.readStaffTicket(engineering.actors.staff, engineeringTicketId)).ticket; + } + let acceptedKey: { ticketId: string; sourceGeneration: number } | undefined; + async function verified(security: 'ordinary' | 'restricted' | 'uncertain' = 'ordinary') { + const ticket = await enrolled(); + const packet = { commandId: 'EVIDENCE-EXACT', expectedRevision: ticket.revision, + expectedBehavior: 'The export contains the workspace rows.', actualBehavior: 'The downloaded export is empty.', + reproductionSteps: ['Create a fictional workspace with one row.', 'Export it and inspect the file.'], + visibleMessageIds: ['engineering-question'], verificationReference: engineeringProofReference, security }; + const response = await send(request('evidence', packet)); + if (response.status !== 200) throw new Error('Actual HTTP evidence failed: ' + response.status); + const source = engineeringHttpResult(await engineeringHttpObject(response)); + acceptedKey = { ticketId: engineeringTicketId, sourceGeneration: engineeringHttpNumber(source.sourceGeneration) }; + return { source, packet, key: { ...acceptedKey } }; + } + function key() { + if (acceptedKey === undefined) throw new Error('No actual HTTP accepted work key'); + return { ...acceptedKey }; + } + const process = () => runtime.processWork({ ...key(), workerId: 'synthetic-http-engineering-worker', leaseMilliseconds: 30_000 }); + const work = () => engineering.application.readEngineeringWork(engineering.actors.security, key()); + async function prepared() { + const candidate = await process(); if (candidate.outcome !== 'candidate') throw new Error('Actual candidate unavailable: ' + candidate.outcome); + const proposal = await process(); if (proposal.outcome !== 'prepared') throw new Error('Actual proposal unavailable: ' + proposal.outcome); + return work(); + } + return { engineering, host, identity, sessions, principals, cookies, csrf, hooks, state, options, resolve, handle, + request, send, revoke, preparePolicy, enrolled, legacyTicket, verified, key, process, work, prepared, + rows: engineering.rows, policyRows: () => store.collection(engineeringPolicyRecords).list('instance'), + async destroy(actor: EngineeringHttpActor) { + const sessionId = sessionIds.get(actor); if (sessionId === undefined) throw new Error('Missing fixture session'); + return sessions.destroy(sessionId); + } }; +} diff --git a/worker/src/support-engineering-http.d1.test.ts b/worker/src/support-engineering-http.d1.test.ts new file mode 100644 index 0000000..7243735 --- /dev/null +++ b/worker/src/support-engineering-http.d1.test.ts @@ -0,0 +1,319 @@ +/// + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { env } from 'cloudflare:workers'; +import { createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'; +import { createWorker } from './index'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { supportRecords } from '@pegma/support-desk-application'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER } from './identity-api'; +import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access'; +import { createSupportApi } from './support-api'; +import { engineeringCanary, engineeringProofReference, engineeringRepositories } from './support-engineering-fixtures'; +import { + createSupportEngineeringHttpFixture, engineeringHttpCommand, + engineeringHttpObject, engineeringHttpResult, engineeringHttpRoute, +} from './support-engineering-http-fixtures'; +import { createSupportEngineeringRouter } from './support-engineering-router'; + +interface Budget { + readonly operation: string; + calls: number; + executed: number; + statements: number; + batches: number; + maximumParameters: number; + blocked: number; + status?: number; +} +const profiles: Budget[][] = []; + +beforeAll(async () => { + expect(String(env.IDENTITY_EMAIL_ENABLED)).toBe('false'); + // Test schema only, through the genuine adapter, outside measured requests. + const store = createCloudflareD1Store({ database: env.IDENTITY_DB }); + await store.collection(supportRecords).get({ partition: 'engineering-http-schema-probe', id: 'absent' }); +}); +beforeEach(async () => { + profiles.length = 0; + // Per-file isolated D1 pool reset, matching existing Native suites. + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); +afterEach(({ task }) => { + Object.assign(task.meta, { supportEngineeringHttpD1Budget: structuredClone(profiles.flat()) }); + console.info('support-engineering-http-d1-budgets', JSON.stringify(profiles.flat())); +}); + +/** Observe actual binding calls, never SQL, results, codecs or Store decisions. + * A D1 batch counts one call; each statement keeps its real bound-parameter + * count. A refused 51st attempt is recorded but never delegated to D1. */ +function meter(backing: D1Database) { + const scope = new AsyncLocalStorage(); + const budgets: Budget[] = []; profiles.push(budgets); + const originals = new WeakMap(); + const parameters = new WeakMap(); + function charge(statements: readonly D1PreparedStatement[]) { + const budget = scope.getStore(); if (budget === undefined) return; + budget.calls += 1; budget.statements += statements.length; + budget.maximumParameters = Math.max(budget.maximumParameters, + ...statements.map((statement) => parameters.get(statement) ?? 0)); + if (budget.calls > 50 || budget.maximumParameters > 100) { + budget.blocked += 1; + throw new Error('Synthetic Workers Free engineering binding guard refused execution.'); + } + budget.executed += 1; + } + function observed(original: D1PreparedStatement, count = 0): D1PreparedStatement { + const statement: D1PreparedStatement = { + bind(...values: unknown[]) { return observed(original.bind(...values), values.length); }, + first>(column?: string): Promise { + charge([statement]); return column === undefined ? original.first() : original.first(column); + }, + all>() { charge([statement]); return original.all(); }, + run>() { charge([statement]); return original.run(); }, + raw: original.raw, + }; + statement.raw = new Proxy(original.raw, { apply(target, _receiver, args) { + charge([statement]); return Reflect.apply(target, original, args); + } }); + originals.set(statement, original); parameters.set(statement, count); return statement; + } + const database: D1Database = { + prepare(query) { return observed(backing.prepare(query)); }, + async batch(statements: D1PreparedStatement[]) { + charge(statements); const budget = scope.getStore(); if (budget !== undefined) budget.batches += 1; + const native = statements.map((statement) => { + const actual = originals.get(statement); + if (actual === undefined) throw new Error('Expected an observed genuine D1 statement.'); + return actual; + }); + return backing.batch(native); + }, + exec() { throw new Error('Runtime schema work is excluded from engineering request profiles.'); }, + dump() { throw new Error('Runtime D1 dump is excluded from engineering request profiles.'); }, + withSession() { throw new Error('The public adapter uses the direct D1 binding.'); }, + }; + return { + database, + budgets, + run(operation: string, action: () => Promise) { + const budget: Budget = { operation, calls: 0, executed: 0, statements: 0, + batches: 0, maximumParameters: 0, blocked: 0 }; + budgets.push(budget); + return scope.run(budget, async () => { + const response = await action(); + await response.clone().arrayBuffer(); + budget.status = response.status; + return response; + }); + }, + assertBounds() { + for (const budget of budgets) { + const detail = JSON.stringify(budget); + expect(budget.calls, detail).toBeLessThanOrEqual(50); + expect(budget.executed, detail).toBe(budget.calls); + expect(budget.maximumParameters, detail).toBeLessThanOrEqual(100); + expect(budget.blocked, detail).toBe(0); + } + }, + }; +} + +async function fixture() { + const budget = meter(env.IDENTITY_DB); + const store = createCloudflareD1Store({ database: budget.database, + createSchemaIfMissing: false, readBatchSize: 512 }); + const f = await createSupportEngineeringHttpFixture(store); + const { enabled, ...configuration } = f.options; void enabled; + const legacy = createSupportApi({ application: f.engineering.application, sessions: f.sessions, + identity: f.identity, identityLinkFromClaims: f.options.identityLinkFromClaims, + logger: f.options.logger, roleStore: f.host.roleStore, + createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); + function router(repositories = configuration.repositories) { + return createSupportEngineeringRouter({ enabled: () => f.state.enabled, + configuration: { ...configuration, repositories } }); + } + const defaultRouter = router(); + async function invoke(operation: string, incoming: Request, route = defaultRouter) { + return budget.run(operation, async () => (await route(incoming)) ?? legacy(incoming)); + } + async function prepare(commandId: string, expectedGeneration: number) { + const response = await invoke('policy.prepare', f.request('policy/prepare', { + commandId, expectedGeneration, enabled: true, + repositoryKeys: [engineeringRepositories[0]!.repositoryId], + }, 'both')); + expect(response.status).toBe(200); + const value = engineeringHttpResult(await engineeringHttpObject(response)); + if (!isPlainObject(value.intent)) throw new Error('Expected the actual full policy intent.'); + return { intent: value.intent }; + } + return { ...f, budget, invoke, router, prepare }; +} + +/** Keep the fixture's exact JSON POST bytes and browser headers while avoiding + * clone()'s widened Cloudflare metadata generic at the handler boundary. */ +async function retainedPost(request: Request): Promise { + const body = await request.clone().text(); + return new Request(request.url, { + method: request.method, headers: new Headers(request.headers), body, + }); +} + +function evidence(revision: number) { + return { + commandId: 'NATIVE-HTTP-EVIDENCE-EXACT', expectedRevision: revision, security: 'ordinary', + expectedBehavior: 'The export contains the workspace rows.', actualBehavior: 'The downloaded export is empty.', + reproductionSteps: ['Create a fictional workspace with one row.', 'Export it and inspect the file.'], + visibleMessageIds: ['engineering-question'], verificationReference: engineeringProofReference, + }; +} + +describe('enabled human engineering router and HTTP over genuine D1', () => { + it('enrolls a real legacy source0, keeps its uncertain read forbidden, then accepts exact visible evidence within each request budget', async () => { + const f = await fixture(); const ticket = await f.legacyTicket(); const before = await f.rows(); + expect(before.some((row) => row.kind === 'engineering_source')).toBe(false); + const request = f.request('enroll', { commandId: engineeringHttpCommand, expectedRevision: ticket.revision }); + const accepted = await f.invoke('enroll.source0', await retainedPost(request)); + expect(accepted.status).toBe(200); + const enrolled = await engineeringHttpObject(accepted); + expect(enrolled.csrfToken).toBe(f.csrf.get('staff')); + expect(engineeringHttpResult(enrolled)).toMatchObject({ sourceGeneration: 0, state: 'unverified' }); + const committed = await f.rows(); + expect(committed.filter((row) => row.kind === 'engineering_receipt')).toHaveLength(1); + const unreadable = await f.invoke('source0.ordinary-denied', f.request()); + expect(unreadable.status).toBe(403); + expect(await engineeringHttpObject(unreadable)).toEqual({ error: 'forbidden' }); + const replay = await f.invoke('enroll.exact-replay', await retainedPost(request)); + expect(replay.status).toBe(200); expect(await engineeringHttpObject(replay)).toEqual(enrolled); + expect(await f.rows()).toEqual(committed); + const verified = await f.invoke('evidence.intake', f.request('evidence', evidence(ticket.revision))); + expect(verified.status).toBe(200); + const source = engineeringHttpResult(await engineeringHttpObject(verified)); + expect(source.state).toBe('eligible'); expect(source.sourceGeneration).toBeGreaterThan(0); + const read = await f.invoke('source.eligible-read', f.request()); expect(read.status).toBe(200); + const body = JSON.stringify(await engineeringHttpObject(read)); + expect(body).not.toContain(engineeringCanary); expect(body).not.toContain(engineeringProofReference); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + f.budget.assertBounds(); + }); + + it.each(['changed-descriptor', 'removed-key'] as const)( + 'prepares a full policy, loses a real committed ACK and exactly recovers after catalog %s without another policy write', + async (change) => { + const f = await fixture(); + const initial = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + const before = await f.policyRows(); + const retained = await f.prepare('NATIVE-POLICY-LOST-EXACT', initial.generation); + // Keep an independent NEVER-submitted intent at the same original head. + // After A commits, B must take the stale/no-receipt branch, not a fresh + // same-generation catalog-admission branch. + const fresh = await f.prepare('NATIVE-FRESH-OBSOLETE-CATALOG', initial.generation); + expect(await f.policyRows()).toEqual(before); + const request = f.request('policy', retained, 'both'); + const originalBytes = await request.clone().text(); + const original = f.state.runtime; let lose = true; + let acknowledgement: Awaited> | undefined; + f.state.runtime = { ...original, async putPolicy(...args: Parameters) { + const value = await original.putPolicy(...args); acknowledgement ??= value; + if (lose) { lose = false; throw new Error('Synthetic real committed policy transport ACK loss'); } + return value; + } }; + const unknown = await f.invoke('policy.commit-lost-ack', await retainedPost(request)); + expect(unknown.status).toBe(503); + expect(await engineeringHttpObject(unknown)).toEqual({ error: 'support_engineering_unavailable' }); + const committed = await f.policyRows(); expect(committed).not.toEqual(before); + const actual = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + expect(actual.generation).toBe(initial.generation + 1); + const repositories = change === 'removed-key' ? [] : f.options.repositories.map((entry) => ({ ...entry, + descriptor: { ...entry.descriptor, responsibilities: 'A different current deployment responsibility.' } })); + const later = f.router(repositories); + expect(await request.clone().text()).toBe(originalBytes); + const replay = await f.invoke('policy.catalog-drift-exact-replay', await retainedPost(request), later); + expect(replay.status).toBe(200); + expect(acknowledgement).toBeDefined(); + expect(engineeringHttpResult(await engineeringHttpObject(replay))).toEqual(acknowledgement); + expect(await f.policyRows()).toEqual(committed); + // A different original intent without a retained receipt cannot use the + // replay branch to commit an obsolete catalog snapshot. + const refused = await f.invoke('policy.unaccepted-old-catalog-refused', f.request('policy', fresh, 'both'), later); + expect(refused.status).toBe(409); expect(await f.policyRows()).toEqual(committed); + expect(f.engineering.state.creates).toEqual([]); expect(f.engineering.state.modelCalls).toBe(0); + f.budget.assertBounds(); + }, + ); + + it('rechecks actual stored Support and Admin role revocation on successive private router requests', async () => { + const f = await fixture(); const ticket = await f.legacyTicket(); + expect((await f.invoke('enroll.before-role-revocation', f.request('enroll', { + commandId: 'NATIVE-ROLE-ENROLL', expectedRevision: ticket.revision, + }))).status).toBe(200); + expect((await f.invoke('evidence.before-role-revocation', f.request('evidence', evidence(ticket.revision)))).status).toBe(200); + expect((await f.invoke('source.before-role-revocation', f.request())).status).toBe(200); + await f.revoke('staff', SUPPORT_ROLE); + const before = await f.rows(); + const denied = await f.invoke('source.after-support-revocation', f.request()); + expect(denied.status).toBe(403); expect(await engineeringHttpObject(denied)).toEqual({ error: 'forbidden' }); + expect(await f.rows()).toEqual(before); + expect((await f.invoke('policy.before-admin-revocation', f.request('policy', undefined, 'both'))).status).toBe(200); + await f.revoke('both', ADMIN_ROLE); + const policyRows = await f.policyRows(); + const policyDenied = await f.invoke('policy.after-admin-revocation', f.request('policy', undefined, 'both')); + expect(policyDenied.status).toBe(403); expect(await engineeringHttpObject(policyDenied)).toEqual({ error: 'forbidden' }); + expect(await f.policyRows()).toEqual(policyRows); + f.budget.assertBounds(); + }); + + it('keeps disabled or excluded router paths inert and rejects a bearer on the enabled browser surface', async () => { + const f = await fixture(); const before = await f.policyRows(); + f.state.enabled = false; + const disabled = await f.invoke('router.disabled', f.request('policy', undefined, 'both')); + expect(disabled.status).toBe(404); + f.state.enabled = true; + const excluded = await f.invoke('router.excluded-dispatch', new Request(IDENTITY_ISSUER + engineeringHttpRoute + '/dispatch', { + method: 'POST', headers: { 'X-Pegma-Support-Command': '1' }, body: '{}', + })); + expect(excluded.status).toBe(404); + const bearer = f.request('policy', undefined, 'both'); bearer.headers.set('Authorization', 'Bearer synthetic-not-browser'); + const denied = await f.invoke('router.bearer-denied', bearer); expect(denied.status).toBe(403); + expect(await f.policyRows()).toEqual(before); + expect(f.state.runtimeCalls).toBe(0); + expect(f.engineering.state.modelCalls).toBe(0); + f.budget.assertBounds(); + }); +}); + + +describe('registered optional engineering Worker route over genuine D1', () => { + it('meters cold root enrollment, exact replay, current capability and Admin+Support policy reads', async () => { + const f = await fixture(); const ticket = await f.legacyTicket(); + const human = { enabled: () => true, + configuration: { application: { enabled: true }, repositories: f.options.repositories } }; + const worker = createWorker({ engineering: human }); + const environment = { ...env, IDENTITY_DB: f.budget.database, + IDENTITY_EMAIL_CODE_SECRET_BASE64: btoa('e'.repeat(32)) }; + const invoke = (label: string, request: Request) => f.budget.run(label, async () => { + const context = createExecutionContext(); + try { return await worker.fetch(request, environment, context); } + finally { await waitOnExecutionContext(context); } + }); + const original = f.request('enroll', { commandId: 'NATIVE-ROOT-EXACT-UPPERCASE', expectedRevision: ticket.revision }); + const accepted = await invoke('root.enroll', await retainedPost(original)); + expect(accepted.status).toBe(200); const acknowledgement = await engineeringHttpObject(accepted); + expect(engineeringHttpResult(acknowledgement)).toMatchObject({ sourceGeneration: 0, state: 'unverified' }); + const rows = await f.rows(); + const replay = await invoke('root.enroll.exact-replay', await retainedPost(original)); + expect(replay.status).toBe(200); expect(await replay.json()).toEqual(acknowledgement); + expect(await f.rows()).toEqual(rows); + const detail = await invoke('root.detail.capability', new Request(IDENTITY_ISSUER + '/api/support/admin/tickets/' + ticket.id, + { headers: { Cookie: f.cookies.get('staff')! } })); + expect(detail.status).toBe(200); + expect(await detail.json()).toMatchObject({ engineeringEnabled: true, engineeringReviewEnabled: false }); + const policy = await invoke('root.policy.current', f.request('policy', undefined, 'both')); + expect(policy.status).toBe(200); + expect(engineeringHttpResult(await engineeringHttpObject(policy)).catalog).toHaveLength(f.options.repositories.length); + f.budget.assertBounds(); expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); +}); diff --git a/worker/src/support-engineering-ports.ts b/worker/src/support-engineering-ports.ts new file mode 100644 index 0000000..e46362c --- /dev/null +++ b/worker/src/support-engineering-ports.ts @@ -0,0 +1,42 @@ +import type { AccessContext } from '@pegma/authorization-core'; +import type { SupportDeskEngineeringOptions } from '@pegma/support-desk-ai'; + +/** Current host authority, resolved from stored grants, never ticket claims. */ +export interface SupportEngineeringStaffAccess { + resolve(principalId: string, signal: AbortSignal): Promise; +} + +/** Purpose-specific trusted ports. Policy and durable state remain SDK-owned. */ +export type SupportEngineeringPorts = Pick; + +export type SupportEngineeringOperation = 'enroll' | 'failure' | 'select' | + 'review' | 'invalidate' | 'withdraw' | 'policy_put' | 'policy_disable'; + +function identifier(value: string): string { + if (typeof value !== 'string' || value.length === 0 || value.length > 200 || + /[\u0000-\u001F\u007F]/u.test(value)) + throw new TypeError('Invalid engineering command identity'); + return value; +} + +/** Exact client bytes are retained; the digest is correlation, not authority. */ +export async function supportEngineeringCommandIdentity(input: { + readonly principalId: string; + readonly ticketId: string; + readonly operation: SupportEngineeringOperation; + readonly clientCommandId: string; +}): Promise<{ readonly commandId: string; readonly correlationId: string }> { + const actor = identifier(input.principalId); + const ticket = identifier(input.ticketId); + const commandId = identifier(input.clientCommandId); + if (!['enroll', 'failure', 'select', 'review', 'invalidate', 'withdraw', + 'policy_put', 'policy_disable'].includes(input.operation)) + throw new TypeError('Invalid engineering operation'); + const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode( + JSON.stringify(['pegma.support-engineering.command.v1', actor, input.operation, ticket, commandId]), + ))); + return Object.freeze({ commandId, + correlationId: 'engineering:' + [...hash].map((byte) => byte.toString(16).padStart(2, '0')).join('') }); +} diff --git a/worker/src/support-engineering-review.test.ts b/worker/src/support-engineering-review.test.ts new file mode 100644 index 0000000..93d7ce9 --- /dev/null +++ b/worker/src/support-engineering-review.test.ts @@ -0,0 +1,226 @@ +import { describe, expect, it } from 'vitest'; +import { SUPPORT_ROLE } from './support-access'; +import { createSupportEngineeringRuntime } from './support-engineering'; +import { createSupportEngineeringHandlers } from './support-engineering-handlers'; +import { createSupportEngineeringRouter } from './support-engineering-router'; +import { + createSupportEngineeringHttpFixture, engineeringHttpObject, engineeringHttpResult, +} from './support-engineering-http-fixtures'; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} +async function prepared(linkExisting = false) { + const f = await createSupportEngineeringHttpFixture(); + Object.assign(f.options, { reviewEnabled: () => true }); + await f.verified(); + if (linkExisting) { + const id = f.engineering.metadata.keys().next().value; + if (id === undefined) throw new Error('Actual configured repository missing'); + f.engineering.state.linkExisting = true; + f.engineering.state.duplicates = [{ repositoryId: id, issueId: 'fictional-existing-42', issueNumber: 42, + title: 'Workspace export loses rows', body: 'A fictional existing issue.' }]; + } + const work = await f.prepared(); + const response = await f.send(f.request('proposal', undefined, 'staff', '?sourceGeneration=' + f.key().sourceGeneration)); + expect(response.status).toBe(200); + const view = engineeringHttpResult(await engineeringHttpObject(response)); + if (typeof view.intent !== 'object' || view.intent === null) throw new Error('Expected minted SDK command'); + const packet = { intent: view.intent }; + return { f, work, view, packet }; +} + +describe('human engineering proposal view and exact public review command', () => { + it('projects only the checked outbound request and mints a complete actor-bound original command', async () => { + const { f, work, view } = await prepared(); + const proposal = work.proposal; + if (proposal === undefined) throw new Error('Actual SDK proposal missing'); + expect(view).toMatchObject({ ticketId: work.ticketId, sourceGeneration: work.sourceGeneration, + workGeneration: work.workGeneration, proposalHash: proposal.proposalHash, approvable: true, rejectionAvailable: true, + request: { operation: proposal.request.operation, repository: { repositoryId: proposal.request.repository.repositoryId, + owner: proposal.request.repository.owner, name: proposal.request.repository.name, visibility: proposal.request.repository.visibility }, + bundle: proposal.request.bundle }, + intent: { actorId: f.principals.staff, command: { ticketId: work.ticketId, sourceGeneration: work.sourceGeneration, + expectedWorkGeneration: work.workGeneration, proposalHash: proposal.proposalHash, decision: 'approve' } } }); + const encoded = JSON.stringify(view); + for (const privateName of ['installationBinding', 'metadataVersion', 'checksReceipt', 'checksBinding', + 'routingReceipt', 'routingBinding', 'candidate', 'evidence', 'product', 'modelAttempts']) + expect(encoded).not.toContain(JSON.stringify(privateName) + ':'); + expect(encoded).not.toContain(proposal.checksReceipt); + expect(encoded).not.toContain(proposal.request.repository.installationBinding); + if (proposal.routingReceipt !== undefined) expect(encoded).not.toContain(proposal.routingReceipt); + expect(new TextEncoder().encode(encoded).byteLength).toBeLessThanOrEqual(65536); + expect(f.engineering.state.creates).toEqual([]); + }); + + it('shows the exact existing issue coordinates without creating an issue or linking automatically', async () => { + const { f, view, work } = await prepared(true); + expect(view.request).toMatchObject({ operation: 'link_existing_issue', issueId: 'fictional-existing-42', issueNumber: 42 }); + expect(work.approval).toBeUndefined(); expect(work.dispatch).toBeUndefined(); expect(f.engineering.state.creates).toEqual([]); + }); + + it('approves using only explicit read-only proof ports while generation remains OFF', async () => { + const { f, work, packet } = await prepared(); + const priorCalls = f.engineering.state.modelCalls; + const ports = f.engineering.ports; + f.state.runtime = createSupportEngineeringRuntime({ application: f.engineering.application, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, processingEnabled: () => false, + reviewProofs: { serviceAccess: ports.serviceAccess, + routing: { resolve: ports.routing.resolve, verify: ports.routing.verify }, + checks: { resolvePolicy: ports.checks.resolvePolicy, verify: ports.checks.verify }, + github: { getMetadata: ports.github.getMetadata } } }); + const response = await f.send(f.request('review', packet)); + expect(response.status).toBe(200); + expect(engineeringHttpResult(await engineeringHttpObject(response))).toEqual({ ticketId: work.ticketId, + sourceGeneration: work.sourceGeneration, workGeneration: work.workGeneration + 1, status: 'approved' }); + const accepted = await f.work(); + expect(accepted.approval).toMatchObject({ decision: 'approve', reviewedBy: f.principals.staff, + proposalHash: work.proposal?.proposalHash }); + expect(accepted.dispatch).toBeUndefined(); + expect(f.engineering.state.modelCalls).toBe(priorCalls); expect(f.engineering.state.creates).toEqual([]); + const rows = await f.rows(); + const replay = await f.send(f.request('review', packet)); expect(replay.status).toBe(200); + expect(await f.rows()).toEqual(rows); + }); + + it('missing read-only proof composition holds new approval without model calls or mutations', async () => { + const { f, packet } = await prepared(); const rows = await f.rows(); + const calls = f.engineering.state.modelCalls; + f.state.runtime = createSupportEngineeringRuntime({ application: f.engineering.application, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, processingEnabled: () => false }); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.modelCalls).toBe(calls); + expect(f.engineering.state.creates).toEqual([]); + }); + + it.each(['source', 'policy', 'repository'] as const)('recovers the original committed review after lost HTTP ACK and %s drift', async (drift) => { + const { f, work, packet } = await prepared(); + f.hooks.commit = async () => { f.state.enabled = false; throw new Error('Synthetic loss AFTER real commit'); }; + expect((await f.send(f.request('review', packet))).status).toBe(503); + delete f.hooks.commit; + const accepted = await f.work(); expect(accepted.status).toBe('approved'); + if (drift === 'source') await f.engineering.runtime.withdraw(f.engineering.actors.staff, + { ticketId: work.ticketId, clientCommandId: 'AFTER-REVIEW-WITHDRAW', reason: 'privacy_withdrawal' }); + else if (drift === 'policy') await f.engineering.runtime.disableExports(f.engineering.actors.admin, + { clientCommandId: 'AFTER-REVIEW-DISABLE', expectedGeneration: (await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).generation }); + else { f.engineering.metadata.clear(); f.engineering.state.installationActive = false; } + const rows = await f.rows(); const calls = f.engineering.state.modelCalls; + f.state.enabled = true; + // Receipt-first SDK recovery must not call any now-unavailable external fact. + f.engineering.state.configuration = 'disabled'; f.engineering.state.checksReadable = false; + const response = await f.send(f.request('review', packet)); expect(response.status).toBe(200); + expect(engineeringHttpResult(await engineeringHttpObject(response))).toEqual({ ticketId: work.ticketId, + sourceGeneration: work.sourceGeneration, workGeneration: work.workGeneration + 1, status: 'approved' }); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.modelCalls).toBe(calls); + expect(f.engineering.state.creates).toEqual([]); + }); + + it.each(['session', 'role'] as const)('rejects new approval when %s is revoked during the real lazy proof guard', async (kind) => { + const { f, packet } = await prepared(); const entered = deferred(); const release = deferred(); + const actual = f.engineering.ports; const rows = await f.rows(); + f.state.runtime = createSupportEngineeringRuntime({ application: f.engineering.application, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, ports: { ...actual, routing: { ...actual.routing, + async resolve(...args) { entered.resolve(); await release.promise; return actual.routing.resolve(...args); } } } }); + const response = f.send(f.request('review', packet)); + try { + await entered.promise; + if (kind === 'session') await f.destroy('staff'); else await f.revoke('staff', SUPPORT_ROLE); + } finally { release.resolve(); } + expect((await response).status).toBe(kind === 'session' ? 401 : 403); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.creates).toEqual([]); + }); + + it('a never-accepted stale proposal is held, not silently rebuilt or presented as cancelled', async () => { + const { f, work, packet } = await prepared(); + await f.engineering.runtime.withdraw(f.engineering.actors.staff, + { ticketId: work.ticketId, clientCommandId: 'WITHDRAW-BEFORE-REVIEW', reason: 'privacy_withdrawal' }); + const rows = await f.rows(); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.creates).toEqual([]); + }); + + it('rejects through the current browser commit guard and replays the complete original command', async () => { + const { f, packet } = await prepared(); + const rejected = structuredClone(packet); + const value = rejected.intent; + if (!('command' in value) || typeof value.command !== 'object' || value.command === null) throw new Error('Missing command'); + Object.assign(value.command, { decision: 'reject' }); + const response = await f.send(f.request('review', rejected)); + expect(response.status).toBe(200); + expect((await f.work()).approval).toMatchObject({ decision: 'reject', reviewedBy: f.principals.staff }); + const rows = await f.rows(); + expect((await f.send(f.request('review', rejected))).status).toBe(200); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.creates).toEqual([]); + }); + + it.each(['approve', 'reject'] as const)('refreshes the original browser at the actual Application %s commit guard', async (decision) => { + const { f, packet } = await prepared(); const rows = await f.rows(); + const actual = f.engineering.application; let guardEntered = 0; + const body = structuredClone(packet); + if (typeof body.intent !== 'object' || body.intent === null || !('command' in body.intent) || + typeof body.intent.command !== 'object' || body.intent.command === null) throw new Error('Missing actual command'); + Object.assign(body.intent.command, { decision }); + f.state.runtime = createSupportEngineeringRuntime({ application: { ...actual, + reviewEngineeringProposal(actor, command, guard) { + return actual.reviewEngineeringProposal(actor, command, async () => { + ++guardEntered; await f.destroy('staff'); return guard?.(); + }); + }, + }, clock: f.engineering.clock, staffAccess: { resolve: (id) => f.resolve(id) }, ports: f.engineering.ports }); + const response = await f.send(f.request('review', body)); + expect(guardEntered).toBeGreaterThan(0); expect(response.status).toBe(401); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.creates).toEqual([]); + }); + + it('preserves the SDK synchronous proof assertion through the last Application handoff', async () => { + const { f, packet } = await prepared(); const rows = await f.rows(); const actual = f.engineering.application; + let assertions = 0; + f.state.runtime = createSupportEngineeringRuntime({ application: { ...actual, + reviewEngineeringProposal(actor, command, guard) { + return actual.reviewEngineeringProposal(actor, command, async () => { + const assertion = await guard?.(); + if (typeof assertion !== 'function') throw new Error('Expected genuine SDK final proof assertion'); + ++assertions; f.engineering.advance(3_600_001); return assertion; + }); + }, + }, clock: f.engineering.clock, staffAccess: { resolve: (id) => f.resolve(id) }, ports: f.engineering.ports }); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect(assertions).toBeGreaterThan(0); expect(await f.rows()).toEqual(rows); + expect(f.engineering.state.creates).toEqual([]); + }); + + it('keeps human identity, CSRF, closed input, and current review grants on original receipt retry', async () => { + const { f, packet } = await prepared(); const rows = await f.rows(); + expect((await f.send(f.request('review', { ...packet, source: {} }))).status).toBe(400); + expect((await f.send(f.request('review', packet, 'peer'))).status).toBe(403); + expect((await f.send(f.request('review', packet, 'knowledge'))).status).toBe(403); + const missing = f.request('review', packet); missing.headers.delete('X-Pegma-CSRF'); + expect((await f.send(missing)).status).toBe(403); + expect(await f.rows()).toEqual(rows); + const accepted = await f.send(f.request('review', packet)); expect(accepted.status).toBe(200); + await f.revoke('staff', SUPPORT_ROLE); const committed = await f.rows(); + expect((await f.send(f.request('review', packet))).status).toBe(403); expect(await f.rows()).toEqual(committed); + }); + + it('review admission is independently OFF and exceptions fail closed before runtime access', async () => { + const { f, packet } = await prepared(); const rows = await f.rows(); const calls = f.state.runtimeCalls; + Object.assign(f.options, { reviewEnabled: () => false }); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect((await f.send(f.request('proposal', undefined, 'staff', '?sourceGeneration=' + f.key().sourceGeneration))).status).toBe(503); + Object.assign(f.options, { reviewEnabled: () => { throw new Error('Synthetic flag outage'); } }); + expect((await f.send(f.request('review', packet))).status).toBe(503); + expect(f.state.runtimeCalls).toBe(calls); expect(await f.rows()).toEqual(rows); + }); + + it('default-disabled router stays inert and never exposes processor or dispatch routes', async () => { + const { f, packet } = await prepared(); const rows = await f.rows(); + expect((await createSupportEngineeringRouter()(f.request('review', packet)))?.status).toBe(404); + const route = createSupportEngineeringRouter({ enabled: () => true, configuration: f.options }); + for (const excluded of ['process', 'dispatch', 'file']) + expect((await route(f.request(excluded, packet)))?.status).toBe(404); + expect(await createSupportEngineeringHandlers(f.options)(f.request('file', packet))).toBeNull(); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.creates).toEqual([]); + }); +}); diff --git a/worker/src/support-engineering-review.ts b/worker/src/support-engineering-review.ts new file mode 100644 index 0000000..9b6f74e --- /dev/null +++ b/worker/src/support-engineering-review.ts @@ -0,0 +1,71 @@ +import type { EngineeringWorkRecord, ReviewEngineeringProposalCommand } from '@pegma/support-desk-application'; +import { ApiError, boundedString, exactObject, optionalKeysObject } from './api-auth'; +import { supportEngineeringCommandIdentity } from './support-engineering-ports'; + +/** A complete retained SDK command. Its actor binding is identity, never authority. */ +export interface EngineeringReviewIntent { + readonly actorId: string; + readonly command: ReviewEngineeringProposalCommand; +} +const projectionBytes = 65_536; + +/** Allowlist only the already checked outbound request, never full private Work. */ +export async function engineeringProposalView(work: EngineeringWorkRecord, actorId: string) { + const proposal = work.proposal; + if (proposal === undefined || work.security !== 'ordinary') + throw new ApiError(409, 'engineering_proposal_unavailable'); + const request = proposal.request; + const repository = request.repository; + const bundle = request.bundle; + const identity = await supportEngineeringCommandIdentity({ principalId: actorId, + ticketId: work.ticketId, operation: 'review', clientCommandId: crypto.randomUUID() }); + const intent: EngineeringReviewIntent = { actorId, command: { ...identity, + ticketId: work.ticketId, sourceGeneration: work.sourceGeneration, + expectedWorkGeneration: work.workGeneration, proposalHash: proposal.proposalHash, decision: 'approve' } }; + const value = { + ticketId: work.ticketId, sourceGeneration: work.sourceGeneration, workGeneration: work.workGeneration, + status: work.status, proposalHash: proposal.proposalHash, + approvable: work.status === 'prepared' && work.dispatch === undefined && work.approval === undefined && + work.proposalNeedsRebuild !== true, + rejectionAvailable: work.status === 'prepared' && work.dispatch === undefined && work.approval === undefined && + work.proposalNeedsRebuild !== true, + request: { + operation: request.operation, + repository: { repositoryId: repository.repositoryId, owner: repository.owner, + name: repository.name, visibility: repository.visibility }, + bundle: { title: bundle.title, body: bundle.body, labels: [...bundle.labels], + ...(bundle.templateId === undefined ? {} : { templateId: bundle.templateId }), + // These are the checked outbound references, not source evidence/receipts. + evidenceReferences: [...bundle.evidenceReferences], exportMarker: bundle.exportMarker }, + ...(request.operation === 'link_existing_issue' ? { issueId: request.issueId, issueNumber: request.issueNumber } : {}), + }, + intent, + }; + // Refuse oversized views; never silently truncate what a human approves. + if (new TextEncoder().encode(JSON.stringify(value)).byteLength > projectionBytes) + throw new ApiError(503, 'engineering_proposal_unavailable'); + return value; +} + +function positive(value: unknown): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) + throw new ApiError(400, 'invalid_request'); + return value; +} + +/** Only immutable command validation occurs before the SDK receipt lookup. */ +export function engineeringReviewIntent(raw: unknown, ticketId: string): EngineeringReviewIntent { + const value = exactObject(raw, ['actorId', 'command']); + const command = optionalKeysObject(value.command, + ['ticketId', 'sourceGeneration', 'commandId', 'correlationId', 'expectedWorkGeneration', 'proposalHash', 'decision'], ['reason']); + if (command.ticketId !== ticketId || (command.decision !== 'approve' && command.decision !== 'reject')) + throw new ApiError(400, 'invalid_request'); + const proposalHash = boundedString(command.proposalHash, 64, 64); + if (!/^[a-f0-9]{64}$/u.test(proposalHash)) throw new ApiError(400, 'invalid_request'); + return { actorId: boundedString(value.actorId, 1, 200), command: { + ticketId, sourceGeneration: positive(command.sourceGeneration), + commandId: boundedString(command.commandId, 1, 200), correlationId: boundedString(command.correlationId, 1, 200), + expectedWorkGeneration: positive(command.expectedWorkGeneration), proposalHash, decision: command.decision, + ...(command.reason === undefined ? {} : { reason: boundedString(command.reason, 1, 200) }), + } }; +} diff --git a/worker/src/support-engineering-router.test.ts b/worker/src/support-engineering-router.test.ts new file mode 100644 index 0000000..40c1a99 --- /dev/null +++ b/worker/src/support-engineering-router.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from 'vitest'; +import { IDENTITY_ISSUER } from './identity-api'; +import { SUPPORT_ROLE } from './support-access'; +import { createSupportApi } from './support-api'; +import { engineeringTicketId } from './support-engineering-fixtures'; +import { + createSupportEngineeringHttpFixture, engineeringHttpCommand, engineeringHttpObject, + engineeringHttpPolicyRoute, engineeringHttpResult, engineeringHttpRoute, +} from './support-engineering-http-fixtures'; +import { createSupportEngineeringRouter, isSupportEngineeringRequest } from './support-engineering-router'; + +async function fixture() { + const f = await createSupportEngineeringHttpFixture(); + const { enabled, ...configuration } = f.options; void enabled; + const router = createSupportEngineeringRouter({ configuration, enabled: () => f.state.enabled }); + const legacy = createSupportApi({ application: f.engineering.application, sessions: f.sessions, + identity: f.identity, identityLinkFromClaims: f.options.identityLinkFromClaims, logger: f.options.logger, + roleStore: f.host.roleStore, createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); + async function routed(request: Request) { return (await router(request)) ?? legacy(request); } + return { ...f, configuration, router, legacy, routed }; +} + +describe('opt-in engineering namespace composition', () => { + it('defaults OFF without dependencies and leaves unrelated paths unclaimed', async () => { + const router = createSupportEngineeringRouter(); + for (const pathname of [engineeringHttpRoute, engineeringHttpRoute + '/enroll', engineeringHttpPolicyRoute]) { + const response = await router(new Request(IDENTITY_ISSUER + pathname)); + expect(response?.status).toBe(404); + if (response === null) throw new Error('Expected owned disabled namespace'); + expect(await engineeringHttpObject(response)).toEqual({ error: 'not_found' }); + expect(response.headers.get('Cache-Control')).toContain('no-store'); + } + expect(await router(new Request(IDENTITY_ISSUER + '/api/support/tickets'))).toBeNull(); + }); + + it.each(['absent', 'flag-only', 'configuration-only', 'false', 'throws'] as const)( + 'keeps %s composition absent404 before runtime/auth despite the old command header', async (mode) => { + const f = await fixture(); + const enabled = () => { if (mode === 'throws') throw new Error('Synthetic unavailable flag'); return mode !== 'false'; }; + const options = mode === 'absent' ? {} : mode === 'flag-only' ? { enabled } + : mode === 'configuration-only' ? { configuration: f.configuration } : { enabled, configuration: f.configuration }; + const router = createSupportEngineeringRouter(options); + const incoming = f.request('enroll', { commandId: 'DISABLED-EXACT', expectedRevision: 1 }); + incoming.headers.set('X-Pegma-Support-Command', '1'); + const response = await router(incoming); + expect(response?.status).toBe(404); expect(f.state.runtimeCalls).toBe(0); + if (response === null) throw new Error('Expected owned engineering namespace'); + expect(await engineeringHttpObject(response)).toEqual({ error: 'not_found' }); + expect(f.engineering.state.modelCalls).toBe(0); + }); + + it('owns unknown and excluded engineering subpaths before legacy Support routing', async () => { + const f = await fixture(); + for (const pathname of [engineeringHttpRoute + '/dispatch', engineeringHttpRoute + '/process', engineeringHttpPolicyRoute + '/unknown']) { + expect(isSupportEngineeringRequest(pathname)).toBe(true); + const response = await f.routed(new Request(IDENTITY_ISSUER + pathname, { + method: 'POST', headers: { 'X-Pegma-Support-Command': '1' }, body: '{}' })); + expect(response.status).toBe(404); expect(await engineeringHttpObject(response)).toEqual({ error: 'not_found' }); + } + for (const pathname of [engineeringHttpRoute + '/review', engineeringHttpRoute + '/proposal']) { + expect(isSupportEngineeringRequest(pathname)).toBe(true); + const response = await f.routed(new Request(IDENTITY_ISSUER + pathname, { + method: 'POST', headers: { 'X-Pegma-Support-Command': '1' }, body: '{}' })); + expect(response.status).toBe(503); + expect(await engineeringHttpObject(response)).toEqual({ error: 'support_engineering_review_disabled' }); + } + expect(f.state.runtimeCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it('fails closed on an invalid trusted catalog without constructing the private runtime', async () => { + const f = await fixture(); const first = f.configuration.repositories[0]!; + const router = createSupportEngineeringRouter({ enabled: () => true, + configuration: { ...f.configuration, repositories: [first, first] } }); + const response = await router(f.request()); expect(response?.status).toBe(503); + if (response === null) throw new Error('Expected owned engineering namespace'); + expect(await engineeringHttpObject(response)).toEqual({ error: 'support_engineering_unavailable' }); + expect(f.state.runtimeCalls).toBe(0); + }); + + it('keeps actual existing customer and staff ticket detail responses unchanged', async () => { + const f = await fixture(); await f.engineering.createTicket(); + for (const [pathname, actor] of [ + ['/api/support/tickets/' + engineeringTicketId, 'customer'], + ['/api/support/admin/tickets/' + engineeringTicketId, 'staff'], + ] as const) { + const request = () => new Request(IDENTITY_ISSUER + pathname, { headers: { Cookie: f.cookies.get(actor)! } }); + const original = await f.legacy(request()); const throughRouter = await f.routed(request()); + expect(original.status).toBe(200); expect(throughRouter.status).toBe(200); + const value = await engineeringHttpObject(throughRouter); + expect(value).toEqual(await engineeringHttpObject(original)); + expect(value).not.toHaveProperty('engineeringEnabled'); + expect(value).not.toHaveProperty('engineering'); + } + expect(f.state.runtimeCalls).toBe(0); + }); + + it('delegates real legacy enrollment and exact replay to the authenticated SDK handler', async () => { + const f = await fixture(); const ticket = await f.legacyTicket(); + const packet = { commandId: engineeringHttpCommand, expectedRevision: ticket.revision }; + const first = await f.routed(f.request('enroll', packet)); + expect(first.status).toBe(200); + const value = await engineeringHttpObject(first); + expect(value.csrfToken).toBe(f.csrf.get('staff')); + expect(engineeringHttpResult(value)).toMatchObject({ ticketId: engineeringTicketId, state: 'unverified' }); + const rows = await f.rows(); expect(rows.filter((row) => row.kind === 'engineering_receipt')).toHaveLength(1); + const replay = await f.routed(f.request('enroll', packet)); + expect(replay.status).toBe(200); expect(await engineeringHttpObject(replay)).toEqual(value); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.modelCalls).toBe(0); + }); + + it.each(['admin', 'knowledge', 'customer'] as const)('preserves current %s staff denial through the router', async (actor) => { + const f = await fixture(); const response = await f.routed(f.request('', undefined, actor)); + expect(response.status).toBe(403); expect(await engineeringHttpObject(response)).toEqual({ error: 'forbidden' }); + expect(f.state.runtimeCalls).toBe(0); + }); + + it.each(['Origin', 'Authorization'] as const)('preserves the existing browser %s fence on a real mutation', async (header) => { + const f = await fixture(); const ticket = await f.legacyTicket(); const before = await f.rows(); + const incoming = f.request('enroll', { commandId: 'BROWSER-EXACT', expectedRevision: ticket.revision }); + incoming.headers.set(header, header === 'Origin' ? 'https://foreign.example' : 'Bearer synthetic'); + expect((await f.routed(incoming)).status).toBe(403); expect(await f.rows()).toEqual(before); + }); + + it('observes fresh stored-role revocation across successive router invocations', async () => { + const f = await fixture(); await f.verified(); + expect((await f.routed(f.request())).status).toBe(200); + await f.revoke('staff', SUPPORT_ROLE); + expect((await f.routed(f.request())).status).toBe(403); + }); + + it('withholds an awaited private result if the current server flag turns OFF', async () => { + const f = await fixture(); await f.verified(); const original = f.state.runtime; + f.state.runtime = { ...original, async readSource(access, ticketId) { + const value = await original.readSource(access, ticketId); f.state.enabled = false; return value; + } }; + const response = await f.routed(f.request()); + expect(response.status).toBe(404); expect(await engineeringHttpObject(response)).toEqual({ error: 'not_found' }); + }); + + it('preserves the final original-session fence after the real source read', async () => { + const f = await fixture(); await f.verified(); const original = f.state.runtime; + f.state.runtime = { ...original, async readSource(access, ticketId) { + const value = await original.readSource(access, ticketId); await f.destroy('staff'); return value; + } }; + const response = await f.routed(f.request()); + expect(response.status).toBe(401); expect(await engineeringHttpObject(response)).toEqual({ error: 'authentication_required' }); + }); + + it('routes declarative policy controls only through actual current Admin plus Support authority', async () => { + const f = await fixture(); + expect((await f.routed(f.request('policy', undefined, 'admin'))).status).toBe(403); + const read = await f.routed(f.request('policy', undefined, 'both')); + expect(read.status).toBe(200); + const before = engineeringHttpResult(await engineeringHttpObject(read)); + const rows = await f.policyRows(); + const prepare = await f.routed(f.request('policy/prepare', { commandId: 'ROUTED-PREPARE-EXACT', + expectedGeneration: before.generation, enabled: false, repositoryKeys: [] }, 'both')); + expect(prepare.status).toBe(200); + expect(engineeringHttpResult(await engineeringHttpObject(prepare))).toHaveProperty('intent'); + expect(await f.policyRows()).toEqual(rows); + const packet = { commandId: 'ROUTED-DISABLE-EXACT', expectedGeneration: before.generation }; + const disabled = await f.routed(f.request('policy/disable', packet, 'both')); + expect(disabled.status).toBe(200); + expect(engineeringHttpResult(await engineeringHttpObject(disabled)).enabled).toBe(false); + expect((await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).policy.enabled).toBe(false); + expect(f.engineering.state.creates).toEqual([]); + }); +}); diff --git a/worker/src/support-engineering-router.ts b/worker/src/support-engineering-router.ts new file mode 100644 index 0000000..e9bd8eb --- /dev/null +++ b/worker/src/support-engineering-router.ts @@ -0,0 +1,52 @@ +import { json } from './api-auth'; +import { + createSupportEngineeringHandlers, + type SupportEngineeringHandlerOptions, +} from './support-engineering-handlers'; + +export interface SupportEngineeringRouterOptions { + /** Strict current server flag. Absence and exceptions remain OFF. */ + readonly enabled?: () => boolean; + /** Existing request-scoped host dependencies; no default authority or clients. */ + readonly configuration?: Omit; +} + +const ticketNamespace = /^\/api\/support\/admin\/tickets\/[A-Za-z0-9._~-]{1,200}\/engineering(?:\/|$)/u; +const policyNamespace = /^\/api\/support\/admin\/engineering(?:\/|$)/u; + +/** Own unknown subpaths too, so they cannot fall through to legacy commands. */ +export function isSupportEngineeringRequest(pathname: string): boolean { + return ticketNamespace.test(pathname) || policyNamespace.test(pathname); +} + +function notFound(): Response { + return json({ error: 'not_found' }, { status: 404 }); +} + +/** + * Optional router, not an entrypoint registration. Call before the existing + * Support API and use its fallback only for null. No Store, runtime, provider, + * route or global authorization/cache is created by this factory. + */ +export function createSupportEngineeringRouter(options: SupportEngineeringRouterOptions = {}) { + const configuration = options.configuration; + function enabled() { + if (configuration === undefined) return false; + try { return options.enabled?.() === true; } catch { return false; } + } + return async function route(request: Request): Promise { + if (!isSupportEngineeringRequest(new URL(request.url).pathname)) return null; + if (configuration === undefined || !enabled()) return notFound(); + try { + // Handler state and browser credential fences belong to this dispatch, + // never to a shared router instance or another HTTP invocation. + const handle = createSupportEngineeringHandlers({ ...configuration, enabled }); + const response = await handle(request); + if (!enabled()) return notFound(); + return response ?? notFound(); + } catch { + if (!enabled()) return notFound(); + return json({ error: 'support_engineering_unavailable' }, { status: 503 }); + } + }; +} diff --git a/worker/src/support-engineering.d1.test.ts b/worker/src/support-engineering.d1.test.ts new file mode 100644 index 0000000..b48d60d --- /dev/null +++ b/worker/src/support-engineering.d1.test.ts @@ -0,0 +1,89 @@ +import { env } from 'cloudflare:workers'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { SupportDeskAuthorizationError, supportRecords } from '@pegma/support-desk-application'; +import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { + createSupportEngineeringFixture, engineeringCanary, engineeringProofReference, engineeringTicketId, +} from './support-engineering-fixtures'; + +beforeAll(async () => { + // Test-only schema initialization through the actual public adapter. The + // production Worker composition and migration flags are not invoked here. + const store = createCloudflareD1Store({ database: env.IDENTITY_DB }); + await store.collection(supportRecords).get({ partition: 'engineering-schema-probe', id: 'probe' }); +}); + +beforeEach(async () => { + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +function fixture(options?: Parameters[1]) { + return createSupportEngineeringFixture(createCloudflareD1Store({ + database: env.IDENTITY_DB, createSchemaIfMissing: false, readBatchSize: 512, + }), options); +} + +describe('engineering assembly on the actual D1 binding', () => { + it('checks and exactly approves one private proposal before a single acknowledged dispatch', async () => { + const f = await fixture(); const accepted = await f.eligible(); const initial = await f.rows(); + await f.runtime.submitVerifiedFailure(f.actors.staff, structuredClone(accepted.packet)); + expect(await f.rows()).toEqual(initial); + const work = await f.prepared(); expect(work.status).toBe('prepared'); expect(f.state.creates).toEqual([]); + const packet = await f.approve(); const reviewed = await f.rows(); + await f.runtime.reviewProposal(f.actors.staff, structuredClone(packet)); + expect(await f.rows()).toEqual(reviewed); + expect((await f.process()).outcome).toBe('dispatched'); + expect((await f.work()).status).toBe('accepted'); + expect((await f.source()).destinations).toMatchObject([{ outcome: 'accepted', reconciliation: 'confirmed' }]); + await f.process(); expect(f.state.creates).toHaveLength(1); expect(f.state.modelCalls).toBe(1); + for (const value of [f.state.modelInputs, f.state.searches, f.state.creates]) { + expect(JSON.stringify(value)).not.toContain(engineeringCanary); + expect(JSON.stringify(value)).not.toContain(engineeringProofReference); + } + }); + + it('keeps uncertain failures private and outside ordinary worker and reviewer discovery', async () => { + const f = await fixture(); await f.eligible('uncertain'); + await expect(f.runtime.readSource(f.actors.staff, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + expect((await f.source()).state).toBe('restricted'); + expect((await f.rows()).filter((row) => row.kind === 'engineering_work')).toEqual([]); + expect((await f.runtime.scanReview(f.actors.staff, { limit: 64 })).reviewSources).toEqual([]); + expect((await f.runtime.scanReview(f.actors.security, { limit: 64 })).reviewSources).toContain(engineeringTicketId); + const scanned = await f.runtime.scanCandidates({ limit: 64 }); + expect('candidates' in scanned && scanned.candidates).toEqual([]); + expect(f.state.modelCalls).toBe(0); expect(f.state.creates).toEqual([]); + }); + + it('holds missing calibration before any paid call on an actual stored work item', async () => { + const f = await fixture(); await f.eligible(); f.state.calibrationReady = false; + expect((await f.process()).outcome).toBe('held'); + expect((await f.work()).status).toBe('held'); + expect(f.state.modelCalls).toBe(0); expect(f.state.reservations).toEqual([]); + }); + + it('withdraws private bodies and reconciles a lost accepted response with generation OFF', async () => { + const f = await fixture(); await f.eligible(); await f.prepared(); await f.approve(); + f.state.createMode = 'accept_then_lose'; + expect(await f.process()).toEqual({ outcome: 'pending', stage: 'dispatch' }); + expect((await f.work()).status).toBe('unknown'); + f.state.enabled = false; f.state.configuration = 'disabled'; + await f.runtime.withdraw(f.actors.staff, { ticketId: engineeringTicketId, + clientCommandId: 'NATIVE-WITHDRAW-EXACT', reason: 'privacy_withdrawal' }); + const work = await f.work(); const source = await f.source(); + expect(source.state).toBe('withdrawn'); expect(source.evidence).toBeUndefined(); + expect(work.proposal).toBeUndefined(); expect(work.evidence).toBeUndefined(); + expect(work.withdrawnRequest).toBeDefined(); expect(work.dispatch).toBeDefined(); + expect(JSON.stringify((await f.rows()).filter((row) => row.kind.startsWith('engineering_')))) + .not.toContain(engineeringProofReference); + expect((await f.runtime.reconcileSource(engineeringTicketId)).outcome).toBe('reconciled'); + expect((await f.work()).status).toBe('accepted'); + expect(f.state.creates).toHaveLength(1); expect(f.state.modelCalls).toBe(1); + }); + + it('refuses a private source read after actual audited staff-role revocation', async () => { + const f = await fixture(); await f.eligible(); await f.revoke('staff'); const before = await f.rows(); + await expect(f.runtime.readSource(f.actors.staff, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + expect(await f.rows()).toEqual(before); + }); +}); diff --git a/worker/src/support-engineering.test.ts b/worker/src/support-engineering.test.ts new file mode 100644 index 0000000..8ef62d0 --- /dev/null +++ b/worker/src/support-engineering.test.ts @@ -0,0 +1,524 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { createSupportDeskApplication, SupportDeskAuthorizationError, supportPermissions } from '@pegma/support-desk-application'; +import { describe, expect, it, vi } from 'vitest'; +import { createSupportEngineeringRuntime, SupportEngineeringUnavailableError, supportEngineeringApplicationOptions } from './support-engineering'; +import { supportEngineeringCommandIdentity } from './support-engineering-ports'; +import { + createSupportEngineeringFixture, engineeringCanary, engineeringProofReference, + engineeringRepositories, engineeringTicketId, type SupportEngineeringFixture, +} from './support-engineering-fixtures'; + +function fixture(options?: Parameters[1]) { + return createSupportEngineeringFixture(createMemoryStore(), options); +} + +async function reviewHints(f: SupportEngineeringFixture, restricted: boolean) { + const sources = new Set(); + const work: { ticketId: string; sourceGeneration: number }[] = []; + let cursor: string | undefined; + for (let page = 0; page < 64; page += 1) { + const result = await f.runtime.scanReview(restricted ? f.actors.security : f.actors.staff, + { limit: 2, ...(cursor === undefined ? {} : { cursor }) }); + expect(result.physicalRows).toBeLessThanOrEqual(2); + expect(result.pages).toBe(1); + expect(result.candidates).toEqual([]); + result.reviewSources.forEach((id) => sources.add(id)); + work.push(...result.reviewCandidates); + if (result.nextCursor === null) return { sources: [...sources], work }; + cursor = result.nextCursor; + } + throw new Error('Synthetic engineering scan did not terminate'); +} + +function barrier() { + let enter!: () => void; + let release!: () => void; + const entered = new Promise((resolve) => { enter = resolve; }); + const resumed = new Promise((resolve) => { release = resolve; }); + return { entered, release, async wait() { enter(); await resumed; } }; +} + +describe('published engineering assembly', () => { + it('retains exact client command bytes and stable actor, operation and ticket correlation', async () => { + const input = { principalId: 'staff-one', ticketId: 'ticket-one', operation: 'failure' as const, + clientCommandId: 'ABCDEF12-1234-4ABC-8DEF-ABCDEF123456' }; + const packet = await supportEngineeringCommandIdentity(input); + expect(await supportEngineeringCommandIdentity({ ...input })).toEqual(packet); + expect(packet.commandId).toBe(input.clientCommandId); + for (const changed of [{ ...input, principalId: 'staff-two' }, { ...input, ticketId: 'ticket-two' }, + { ...input, operation: 'review' as const }, { ...input, clientCommandId: input.clientCommandId.toLowerCase() }]) + expect((await supportEngineeringCommandIdentity(changed)).correlationId).not.toBe(packet.correlationId); + }); + + it('defaults intake OFF without creating an engineering source', async () => { + expect(supportEngineeringApplicationOptions().enabled).toBe(false); + const f = await fixture({ intake: false }); + const ticket = await f.createTicket(); const before = await f.rows(); + await expect(f.runtime.enroll(f.actors.staff, { ticketId: engineeringTicketId, + clientCommandId: 'disabled-enrollment', expectedRevision: ticket.revision })).rejects.toThrow(); + expect(await f.rows()).toEqual(before); + }); + + it('keeps worker admission OFF independently of accepted evidence and staff reads', async () => { + const f = await fixture({ processing: false }); await f.eligible(); + expect((await f.runtime.readSource(f.actors.staff, engineeringTicketId)).state).toBe('eligible'); + const before = await f.rows(); + expect(await f.process()).toEqual({ outcome: 'held', reason: 'engineering_disabled' }); + expect(await f.runtime.scanCandidates({ limit: 8 })).toEqual({ outcome: 'held', reason: 'engineering_disabled' }); + expect(f.state.modelCalls).toBe(0); expect(await f.rows()).toEqual(before); + }); + + it('holds a runtime with no service ports before a claim, reservation or paid call', async () => { + const f = await fixture(); await f.eligible(); const before = await f.rows(); + const runtime = createSupportEngineeringRuntime({ application: f.application, clock: f.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, processingEnabled: () => true }); + expect(await runtime.processWork({ ...f.key(), workerId: 'unconfigured-worker', leaseMilliseconds: 30_000 })) + .toEqual({ outcome: 'held', reason: 'engineering_unavailable' }); + expect(await runtime.scanCandidates({ limit: 8 })).toEqual({ outcome: 'held', reason: 'engineering_unavailable' }); + expect(f.state.reservations).toEqual([]); expect(await f.rows()).toEqual(before); + }); + + it('separates current human, policy administrator and worker grants', async () => { + const f = await fixture(); await f.eligible(); + const processor = await f.resolve('engineering-processor'); + expect(processor.permissions).not.toContain(supportPermissions.engineeringReview); + expect(processor.permissions).not.toContain(supportPermissions.engineeringRestrictedRead); + expect(f.actors.staff.permissions).not.toContain(supportPermissions.engineeringProcess); + await expect(f.runtime.readSource(f.actors.admin, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + await expect(f.runtime.disableExports(f.actors.staff, { clientCommandId: 'staff-policy-denied', expectedGeneration: 1 })) + .rejects.toThrow(SupportDeskAuthorizationError); + await expect(f.runtime.scanReview(processor, { limit: 8 })).rejects.toThrow(SupportDeskAuthorizationError); + }); + + it('does not broaden an original restricted caller after rereading its current stored role', async () => { + const f = await fixture(); await f.eligible(); + const restricted = { ...f.actors.staff, + permissions: f.actors.staff.permissions.filter((entry) => entry !== supportPermissions.engineeringRead) }; + await expect(f.runtime.readSource(restricted, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + }); + + it('refuses the private response after actual role revocation at the final authority read', async () => { + const f = await fixture(); await f.eligible(); let resolves = 0; + const runtime = createSupportEngineeringRuntime({ application: f.application, clock: f.clock, + staffAccess: { async resolve(id) { + resolves += 1; if (resolves === 2) await f.revoke('staff'); return f.resolve(id); + } } }); + const before = await f.rows(); + await expect(runtime.readSource(f.actors.staff, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + expect(await f.rows()).toEqual(before); + }); + + it('records an actual staff-verified failure and exactly replays its immutable packet', async () => { + const f = await fixture(); const accepted = await f.eligible(); const before = await f.rows(); + expect(await f.runtime.submitVerifiedFailure(f.actors.staff, structuredClone(accepted.packet))).toEqual(accepted.source); + expect(await f.rows()).toEqual(before); + const source = await f.source(); + expect(source.evidence).toMatchObject({ kind: 'staff_verified_failure', actorId: f.actors.staff.principalId }); + expect(source.product).toMatchObject({ productId: 'workspace', buildId: 'synthetic-build-230' }); + expect((await f.work()).status).toBe('pending'); expect(f.state.modelCalls).toBe(0); + }); + + it('rejects a private note as visible evidence without altering accepted authority', async () => { + const f = await fixture(); const accepted = await f.eligible(); const before = await f.rows(); + await expect(f.runtime.submitVerifiedFailure(f.actors.staff, { ...accepted.packet, + clientCommandId: 'private-evidence-denied', evidence: { ...accepted.packet.evidence, visibleMessageIds: ['engineering-note'] } })) + .rejects.toThrow(); + expect(await f.rows()).toEqual(before); + }); + + it.each(['missing', 'expired'] as const)('holds %s trusted product evidence without model work', async (product) => { + const f = await fixture(); f.state.product = product; + const result = await f.eligible(); expect(result.source.state).toBe('held'); + expect((await f.rows()).filter((row) => row.kind === 'engineering_work')).toEqual([]); + expect(f.state.modelCalls).toBe(0); expect(f.state.reservations).toEqual([]); + expect((await reviewHints(f, false)).sources).toContain(engineeringTicketId); + }); + + it('keeps initial uncertain sources private during actual cursor-based review discovery', async () => { + const f = await fixture(); const ticket = await f.createTicket(); + await f.runtime.enroll(f.actors.staff, { ticketId: engineeringTicketId, + clientCommandId: 'unverified-source', expectedRevision: ticket.revision }); + await expect(f.runtime.readSource(f.actors.staff, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + expect((await f.source()).security).toBe('uncertain'); + expect((await reviewHints(f, false)).sources).toEqual([]); + expect((await reviewHints(f, true)).sources).toContain(engineeringTicketId); + }); + + it.each(['restricted', 'uncertain'] as const)('does not queue or expose a %s verified source to the ordinary worker', async (security) => { + const f = await fixture(); const accepted = await f.eligible(security); + expect(accepted.source.state).toBe('restricted'); + await expect(f.runtime.readSource(f.actors.staff, engineeringTicketId)).rejects.toThrow(SupportDeskAuthorizationError); + expect((await f.rows()).filter((row) => row.kind === 'engineering_work')).toEqual([]); + const scan = await f.runtime.scanCandidates({ limit: 64 }); + expect('candidates' in scan && scan.candidates).toEqual([]); + expect((await reviewHints(f, true)).sources).toContain(engineeringTicketId); + expect(f.state.modelCalls).toBe(0); expect(f.state.creates).toEqual([]); + }); + + it('requires current calibrated routing before a paid assessment', async () => { + const f = await fixture(); await f.eligible(); f.state.calibrationReady = false; + expect((await f.process()).outcome).toBe('held'); + expect((await f.work()).candidate).toBeUndefined(); + expect(f.state.modelCalls).toBe(0); expect(f.state.reservations).toEqual([]); + }); + + it('requires an exact checked request and staff approval before one physical issue creation', async () => { + const f = await fixture(); await f.eligible(); const prepared = await f.prepared(); + expect(prepared.status).toBe('prepared'); expect(prepared.approval).toBeUndefined(); + expect(f.state.creates).toEqual([]); + const packet = await f.approve(); const approved = await f.rows(); + await f.runtime.reviewProposal(f.actors.staff, structuredClone(packet)); + expect(await f.rows()).toEqual(approved); + expect((await f.process()).outcome).toBe('dispatched'); + expect((await f.work()).status).toBe('accepted'); + expect((await f.source()).destinations).toMatchObject([{ outcome: 'accepted', reconciliation: 'confirmed' }]); + await f.process(); expect(f.state.creates).toHaveLength(1); expect(f.state.modelCalls).toBe(1); + for (const value of [f.state.modelInputs, f.state.searches, f.state.creates]) { + expect(JSON.stringify(value)).not.toContain(engineeringCanary); + expect(JSON.stringify(value)).not.toContain(engineeringProofReference); + } + expect(f.state.searches).toMatchObject([{ query: 'workspace export empty file', limit: 5 }]); + }); + + it('refuses a changed proposal hash without changing review or dispatch state', async () => { + const f = await fixture(); await f.eligible(); const work = await f.prepared(); const before = await f.rows(); + await expect(f.runtime.reviewProposal(f.actors.staff, { ...f.key(), clientCommandId: 'wrong-review', + expectedWorkGeneration: work.workGeneration, proposalHash: '0'.repeat(64), decision: 'approve' })).rejects.toThrow(); + expect(await f.rows()).toEqual(before); expect(f.state.creates).toEqual([]); + }); + + it.each(['held', 'restricted'] as const)('holds a final independent check outcome of %s', async (outcome) => { + const f = await fixture(); await f.eligible(); + expect((await f.process()).outcome).toBe('candidate'); f.state.checks = outcome; + const result = await f.process(); expect(result.outcome).toBe(outcome); + expect((await f.work()).proposal).toBeUndefined(); expect(f.state.creates).toEqual([]); + if (outcome === 'restricted') + await expect(f.runtime.readWork(f.actors.staff, f.key())).rejects.toThrow(SupportDeskAuthorizationError); + }); + + it('requires independently approved public reproduction for a public repository', async () => { + const f = await fixture(); await f.eligible(); + expect((await f.process()).outcome).toBe('candidate'); f.state.publicReproduction = 'not_applicable'; + expect((await f.process()).outcome).toBe('held'); + expect((await f.work()).proposal).toBeUndefined(); expect(f.state.creates).toEqual([]); + }); + + it('keeps model security classification private and unclaimable on its original work key', async () => { + const f = await fixture(); await f.eligible(); f.state.modelSecurity = 'restricted'; + expect((await f.process()).outcome).toBe('restricted'); + const source = await f.source(); const work = await f.work(); + expect(source.sourceGeneration).toBeGreaterThan(work.sourceGeneration); + expect(work.status).toBe('restricted'); + await expect(f.runtime.readWork(f.actors.staff, f.key())).rejects.toThrow(SupportDeskAuthorizationError); + expect((await reviewHints(f, false)).work).toEqual([]); + expect((await reviewHints(f, true)).work).toContainEqual(f.key()); + expect((await f.process()).outcome).toBe('not_claimed'); expect(f.state.modelCalls).toBe(1); + expect(f.state.creates).toEqual([]); + }); + + it('does not export a model-selected repository outside the actual allowlist', async () => { + const f = await fixture(); await f.eligible(); f.state.modelRepositoryId = 'not-allowlisted'; + expect((await f.process()).outcome).toBe('candidate'); + expect((await f.work()).candidate?.routing.outcome).toBe('out_of_scope'); + expect((await f.process()).outcome).toBe('held'); + expect((await f.work()).proposal).toBeUndefined(); expect(f.state.creates).toEqual([]); + }); + + it('allows exact staff selection after ambiguous routing without another model call', async () => { + const f = await fixture(); await f.eligible(); f.state.modelRouting = 'ambiguous'; + expect((await f.process()).outcome).toBe('candidate'); + expect((await f.process()).outcome).toBe('held'); + expect((await reviewHints(f, false)).work).toContainEqual(f.key()); + const work = await f.work(); const policy = await f.runtime.readPolicy(f.actors.staff); + const packet = { ...f.key(), clientCommandId: 'SELECT-EXACT', expectedWorkGeneration: work.workGeneration, + repositoryId: engineeringRepositories[1]!.repositoryId, policyGeneration: policy.generation, + policyHash: policy.policyHash, reason: 'The verified failure concerns the allowlisted download API.' }; + const before = await f.rows(); + await expect(f.runtime.selectRepository(f.actors.staff, { ...packet, repositoryId: 'not-allowlisted' })).rejects.toThrow(); + expect(await f.rows()).toEqual(before); + await f.runtime.selectRepository(f.actors.staff, packet); + expect((await f.process()).outcome).toBe('prepared'); + await f.approve(); expect((await f.process()).outcome).toBe('dispatched'); + expect(f.state.creates).toMatchObject([{ repository: { repositoryId: engineeringRepositories[1]!.repositoryId } }]); + expect(f.state.modelCalls).toBe(1); + }); + + it('does not replace a missing trusted duplicate query with raw ticket text', async () => { + const f = await fixture(); await f.eligible(); + expect((await f.process()).outcome).toBe('candidate'); f.state.duplicateQuery = null; + expect((await f.process()).outcome).toBe('held'); + expect(f.state.searches).toEqual([]); expect(f.state.creates).toEqual([]); + }); + + it('revokes export authority when the actual repository policy is disabled after approval', async () => { + const f = await fixture(); await f.eligible(); await f.prepared(); await f.approve(); + const policy = await f.runtime.readPolicy(f.actors.admin); + await f.runtime.disableExports(f.actors.admin, { clientCommandId: 'disable-current-policy', expectedGeneration: policy.generation }); + await f.process(); expect(f.state.creates).toEqual([]); + expect((await f.work()).dispatch).toBeUndefined(); + }); + + it('refuses changed current repository visibility and revoked independent checks', async () => { + const f = await fixture(); await f.eligible(); await f.prepared(); + f.state.checksReadable = false; + await expect(f.approve()).rejects.toThrow(); + expect((await f.work()).approval).toBeUndefined(); + f.state.checksReadable = true; await f.approve(); + const repository = f.metadata.get(engineeringRepositories[0]!.repositoryId); + if (repository === undefined) throw new Error('Synthetic repository metadata missing'); + f.metadata.set(repository.repositoryId, { ...repository, visibility: 'private', metadataVersion: 'synthetic-metadata-v2' }); + await f.process(); expect(f.state.creates).toEqual([]); expect((await f.work()).dispatch).toBeUndefined(); + }); + + it('keeps an empty remote observation unknown without a second creation call', async () => { + const f = await fixture(); await f.eligible(); await f.prepared(); await f.approve(); + f.state.createMode = 'unknown'; + expect(await f.process()).toEqual({ outcome: 'pending', stage: 'dispatch' }); + expect((await f.work()).status).toBe('unknown'); + f.advance(60_000); await f.process(); await f.runtime.reconcileSource(engineeringTicketId); + expect((await f.work()).status).toBe('unknown'); + expect((await f.source()).destinations[0]?.outcome).toBe('unknown'); + expect(f.state.creates).toHaveLength(1); expect(f.state.modelCalls).toBe(1); + }); + + it('reconciles a lost accepted response with independent authority while generation is OFF', async () => { + const f = await fixture(); await f.eligible(); await f.prepared(); await f.approve(); + f.state.createMode = 'accept_then_lose'; + expect(await f.process()).toEqual({ outcome: 'pending', stage: 'dispatch' }); + f.state.enabled = false; f.state.configuration = 'disabled'; + expect((await f.runtime.reconcileSource(engineeringTicketId)).outcome).toBe('reconciled'); + expect((await f.work()).status).toBe('accepted'); + expect(f.state.creates).toHaveLength(1); expect(f.state.modelCalls).toBe(1); + }); + + it('scrubs engineering bodies on privacy withdrawal and reconciles retained opaque identities', async () => { + const f = await fixture(); await f.eligible(); const prepared = await f.prepared(); await f.approve(); + f.state.createMode = 'accept_then_lose'; await f.process(); + const dispatchId = (await f.work()).dispatch?.dispatchId; + f.state.enabled = false; f.state.configuration = 'disabled'; + await f.runtime.withdraw(f.actors.staff, { ticketId: engineeringTicketId, + clientCommandId: 'privacy-withdrawal', reason: 'privacy_withdrawal' }); + const source = await f.source(); const work = await f.work(); + expect(source.state).toBe('withdrawn'); expect(source.evidence).toBeUndefined(); expect(source.product).toBeUndefined(); + expect(work.evidence).toBeUndefined(); expect(work.candidate).toBeUndefined(); expect(work.proposal).toBeUndefined(); + expect(work.dispatch?.dispatchId).toBe(dispatchId); + expect(work.withdrawnRequest?.exportMarker).toBe(prepared.proposal?.request.bundle.exportMarker); + const engineeringRows = (await f.rows()).filter((row) => row.kind.startsWith('engineering_')); + expect(JSON.stringify(engineeringRows)).not.toContain(engineeringProofReference); + expect(JSON.stringify(engineeringRows)).not.toContain('A fictional workspace export omits its rows.'); + expect(JSON.stringify(await f.rows())).toContain(engineeringCanary); + expect((await f.runtime.reconcileSource(engineeringTicketId)).outcome).toBe('reconciled'); + expect((await f.work()).status).toBe('accepted'); expect(f.state.creates).toHaveLength(1); + }); + + it('links an existing issue only as a private checked association without a GitHub write', async () => { + const f = await fixture(); await f.eligible(); f.state.linkExisting = true; + f.state.duplicates = [{ repositoryId: engineeringRepositories[0]!.repositoryId, issueId: 'synthetic-existing-42', + issueNumber: 42, title: 'Workspace export loses rows', body: 'A synthetic existing report.' }]; + await f.prepared(); await f.approve(); + expect((await f.process()).outcome).toBe('dispatched'); + expect((await f.work()).acknowledgement?.issueId).toBe('synthetic-existing-42'); + expect(f.state.creates).toEqual([]); expect(f.state.modelCalls).toBe(1); + }); + + it('uses actual claim fencing when two workers overlap a paid model call', async () => { + const f = await fixture(); await f.eligible(); const gate = barrier(); f.state.modelHook = gate.wait; + const first = f.process(); + try { + await Promise.race([gate.entered, first.then((result) => { + throw new Error('Synthetic model barrier was not reached: ' + result.outcome); + })]); + expect(await f.runtime.processWork({ ...f.key(), workerId: 'synthetic-second-worker', leaseMilliseconds: 30_000 })) + .toEqual({ outcome: 'not_claimed' }); + } finally { gate.release(); } + expect((await first).outcome).toBe('candidate'); + expect(f.state.modelCalls).toBe(1); expect(f.state.reservations).toHaveLength(1); + }); + + it('invalidates a reviewed source on an actual visible customer reply before export', async () => { + const f = await fixture(); await f.eligible(); await f.prepared(); await f.approve(); + await f.application.replyToCustomerTicket(f.actors.customer, { ...f.command('new-visible-evidence'), ticketId: engineeringTicketId, + messageId: 'engineering-new-observation', body: 'A new fictional observation changes the report.' }); + expect((await f.source()).state).toBe('held'); + expect((await f.work()).status).toBe('superseded'); + expect((await f.process()).outcome).toBe('not_claimed'); expect(f.state.creates).toEqual([]); + }); +}); + + +describe('one engineering staff operation deadline', () => { + it('bounds an abort-ignoring actual SDK read within the time left after initial authority', async () => { + const f = await fixture(); await f.eligible(); + const before = await f.rows(); const initial = barrier(); const read = barrier(); + let completeRead!: () => void; + const readCompleted = new Promise((resolve) => { completeRead = resolve; }); + let authoritySignal: AbortSignal | undefined; let resolves = 0; let returned = false; + const runtime = createSupportEngineeringRuntime({ clock: f.clock, + application: { ...f.application, async readEngineeringSource(...args: Parameters) { + try { + const actual = await f.application.readEngineeringSource(...args); + await read.wait(); returned = true; return actual; + } finally { completeRead(); } + } }, + staffAccess: { async resolve(id, signal) { + authoritySignal = signal; resolves += 1; + if (resolves === 1) await initial.wait(); + return f.resolve(id); + } }, + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const pending = runtime.readSource(f.actors.staff, engineeringTicketId); + let settled = false; + const observed = pending.then((value) => { settled = true; return { kind: 'returned' as const, value }; }, + (error: unknown) => { settled = true; return { kind: 'failed' as const, error }; }); + try { + await initial.entered; + await vi.advanceTimersByTimeAsync(9_000); initial.release(); + await Promise.race([read.entered, pending.then(() => { throw new Error('Actual read did not reach its barrier'); })]); + expect(authoritySignal?.aborted).toBe(false); + await vi.advanceTimersByTimeAsync(16_001); + expect(settled).toBe(true); + const result = await observed; + expect(result.kind).toBe('failed'); + if (result.kind !== 'failed') throw new Error('Private SDK result escaped the staff deadline'); + expect(result.error).toBeInstanceOf(SupportEngineeringUnavailableError); + expect(authoritySignal?.aborted).toBe(true); + expect(returned).toBe(false); + expect(await f.rows()).toEqual(before); + } finally { + initial.release(); read.release(); await readCompleted; vi.useRealTimers(); + } + expect(returned).toBe(true); + expect(resolves).toBe(1); + expect((await observed).kind).toBe('failed'); + expect(await f.rows()).toEqual(before); + }); + + it('withholds a delayed real commit acknowledgement and recovers only the original immutable packet', async () => { + // Intake was disabled when this real ticket was created. Enrolling through + // a newly enabled factory over the SAME Store must therefore mutate it. + const f = await fixture({ intake: false }); const ticket = await f.createTicket(); + const application = createSupportDeskApplication({ store: f.store, clock: f.clock, + engineering: supportEngineeringApplicationOptions({ enabled: true }) }); + const before = await f.rows(); const committed = barrier(); + expect(before.some((row) => row.kind === 'engineering_source')).toBe(false); + let complete!: () => void; + const completed = new Promise((resolve) => { complete = resolve; }); + let acknowledgement: Awaited> | undefined; + let authoritySignal: AbortSignal | undefined; + const runtime = createSupportEngineeringRuntime({ clock: f.clock, + application: { ...application, async enrollEngineeringSource(...args: Parameters) { + try { + const actual = await application.enrollEngineeringSource(...args); + acknowledgement ??= actual; + await committed.wait(); return actual; + } finally { complete(); } + } }, + staffAccess: { resolve(id, signal) { authoritySignal = signal; return f.resolve(id); } }, + }); + const packet = { ticketId: engineeringTicketId, + clientCommandId: 'DEADLINE-COMMIT-EXACT', expectedRevision: ticket.revision }; + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const pending = runtime.enroll(f.actors.staff, packet); + let settled = false; + const observed = pending.then((value) => { settled = true; return { kind: 'returned' as const, value }; }, + (error: unknown) => { settled = true; return { kind: 'failed' as const, error }; }); + let committedRows: Awaited> = []; + try { + await Promise.race([committed.entered, pending.then(() => { throw new Error('Real commit acknowledgement was not delayed'); })]); + committedRows = await f.rows(); + expect(committedRows).not.toEqual(before); + expect(committedRows).toHaveLength(before.length + 3); + expect(committedRows.filter((row) => row.kind === 'engineering_receipt')).toHaveLength(1); + expect(committedRows.some((row) => row.kind === 'audit' && + row.event.action === 'support.engineering.enrolled' && + row.event.details?.commandId === packet.clientCommandId)).toBe(true); + await vi.advanceTimersByTimeAsync(25_001); + expect(settled).toBe(true); + const result = await observed; + expect(result.kind).toBe('failed'); + if (result.kind !== 'failed') throw new Error('Committed SDK acknowledgement escaped the deadline'); + expect(result.error).toBeInstanceOf(SupportEngineeringUnavailableError); + expect(authoritySignal?.aborted).toBe(true); + expect(await f.rows()).toEqual(committedRows); + } finally { + committed.release(); await completed; vi.useRealTimers(); + } + expect(acknowledgement).toBeDefined(); + expect(await runtime.enroll(f.actors.staff, structuredClone(packet))).toEqual(acknowledgement); + expect(await f.rows()).toEqual(committedRows); + expect(f.state.modelCalls).toBe(0); expect(f.state.creates).toEqual([]); + }); + + it('uses the same remaining deadline for final authority after an actual SDK read', async () => { + const f = await fixture(); await f.eligible(); const before = await f.rows(); + const initial = barrier(); const final = barrier(); let resolves = 0; + let finalSignal: AbortSignal | undefined; + const runtime = createSupportEngineeringRuntime({ application: f.application, clock: f.clock, + staffAccess: { async resolve(id, signal) { + resolves += 1; + if (resolves === 1) await initial.wait(); + else { finalSignal = signal; await final.wait(); } + return f.resolve(id); + } }, + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const pending = runtime.readSource(f.actors.staff, engineeringTicketId); + let settled = false; + const observed = pending.then((value) => { settled = true; return { kind: 'returned' as const, value }; }, + (error: unknown) => { settled = true; return { kind: 'failed' as const, error }; }); + try { + await initial.entered; await vi.advanceTimersByTimeAsync(9_000); initial.release(); + await Promise.race([final.entered, pending.then(() => { throw new Error('Actual read did not reach final authority'); })]); + await vi.advanceTimersByTimeAsync(16_001); + expect(settled).toBe(true); + const result = await observed; + expect(result.kind).toBe('failed'); + if (result.kind !== 'failed') throw new Error('SDK result escaped final authority deadline'); + expect(result.error).toBeInstanceOf(SupportEngineeringUnavailableError); + expect(finalSignal?.aborted).toBe(true); + } finally { initial.release(); final.release(); vi.useRealTimers(); } + expect(await f.rows()).toEqual(before); + expect((await observed).kind).toBe('failed'); + }); + + it('honors an earlier real SDK review deadline and abort cleanup for an uncooperative policy port', async () => { + const f = await fixture(); await f.eligible(); const work = await f.prepared(); + if (work.proposal === undefined) throw new Error('Actual checked proposal required'); + const before = await f.rows(); const policy = barrier(); + let authoritySignal: AbortSignal | undefined; let sdkSignal: AbortSignal | undefined; + const runtime = createSupportEngineeringRuntime({ application: f.application, clock: f.clock, + staffAccess: { resolve(id, signal) { authoritySignal = signal; return f.resolve(id); } }, + ports: { ...f.ports, checks: { ...f.ports.checks, async resolvePolicy(expectedVersion, signal) { + const actual = await f.ports.checks.resolvePolicy(expectedVersion, signal); + sdkSignal = signal; await policy.wait(); return actual; + } } }, + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const pending = runtime.reviewProposal(f.actors.staff, { ...f.key(), + clientCommandId: 'REVIEW-DEADLINE-EXACT', expectedWorkGeneration: work.workGeneration, + proposalHash: work.proposal.proposalHash, decision: 'approve' }); + let settled = false; + const observed = pending.then((value) => { settled = true; return { kind: 'returned' as const, value }; }, + (error: unknown) => { settled = true; return { kind: 'failed' as const, error }; }); + try { + await Promise.race([policy.entered, pending.then(() => { throw new Error('Actual SDK review did not reach its policy port'); })]); + expect(sdkSignal?.aborted).toBe(false); + await vi.advanceTimersByTimeAsync(25_001); + expect(settled).toBe(true); + const result = await observed; + expect(result.kind).toBe('failed'); + if (result.kind !== 'failed') throw new Error('Unverified engineering review escaped its deadline'); + // SDK runtime.within floors its remaining timer and may reject before + // the outer host timer. Its review guard preserves this exact deadline + // category; it is not a host-unavailable error or proof of noncommit. + expect(result.error).toBeInstanceOf(Error); + expect(result.error).toMatchObject({ name: 'AssistantBoundaryError', category: 'deadline' }); + expect(authoritySignal?.aborted).toBe(true); + expect(sdkSignal?.aborted).toBe(true); + } finally { policy.release(); vi.useRealTimers(); } + expect(await f.rows()).toEqual(before); + expect(f.state.creates).toEqual([]); + expect(f.state.modelCalls).toBe(1); + }); +}); diff --git a/worker/src/support-engineering.ts b/worker/src/support-engineering.ts new file mode 100644 index 0000000..6e2ba32 --- /dev/null +++ b/worker/src/support-engineering.ts @@ -0,0 +1,267 @@ +import { hasPermission, type AccessContext } from '@pegma/authorization-core'; +import type { Clock } from '@pegma/spine'; +import { + createSupportDeskEngineering, + type EngineeringProcessResult, + type SupportDeskEngineering, + type SupportDeskEngineeringOptions, +} from '@pegma/support-desk-ai'; +import { + SupportDeskAuthorizationError, + supportPermissions, + type EngineeringApplication, + type EngineeringPolicyApplication, + type EngineeringOptions, + type EngineeringKey, + type EnrollEngineeringSourceCommand, + type SubmitEngineeringEvidenceCommand, + type SelectEngineeringRepositoryCommand, + type ReviewEngineeringProposalCommand, + type InvalidateEngineeringSourceCommand, + type WithdrawEngineeringSourceCommand, + type PutEngineeringPolicyCommand, + type EngineeringPolicyCommand, +} from '@pegma/support-desk-application'; +import { + supportEngineeringCommandIdentity, + type SupportEngineeringOperation, + type SupportEngineeringPorts, + type SupportEngineeringStaffAccess, +} from './support-engineering-ports'; + +type Packet = Omit & { readonly clientCommandId: string }; +export type EngineeringEnrollmentPacket = Packet; +export type EngineeringFailurePacket = Packet & { + readonly evidence: Extract; +}>; +export type EngineeringSelectionPacket = Packet; +export type EngineeringReviewPacket = Packet; +export type EngineeringInvalidationPacket = Packet; +export type EngineeringWithdrawalPacket = Packet; +export type EngineeringPolicyPacket = Packet; +export type EngineeringDisablePacket = Packet; + +/** Read-only facts required for a NEW approval; no processing or dispatch ports. */ +export interface SupportEngineeringReviewProofs { + readonly serviceAccess: SupportEngineeringPorts['serviceAccess']; + readonly routing: Pick; + readonly checks: Pick; + readonly github: Pick; +} + +export interface SupportEngineeringRuntimeOptions { + readonly application: EngineeringApplication & EngineeringPolicyApplication; + readonly clock: Clock; + readonly staffAccess: SupportEngineeringStaffAccess; + /** Worker admission only. Generation configuration and export policy are separate. */ + readonly processingEnabled?: () => boolean; + readonly ports?: Partial; + readonly reviewProofs?: SupportEngineeringReviewProofs; +} + +export class SupportEngineeringUnavailableError extends Error { + readonly code = 'support_engineering_unavailable'; + constructor() { super('Support engineering is unavailable'); this.name = 'SupportEngineeringUnavailableError'; } +} + +/** Pass explicitly to the existing Support factory; intake defaults OFF. */ +export function supportEngineeringApplicationOptions(options: EngineeringOptions = {}): EngineeringOptions { + return Object.freeze({ ...options, enabled: options.enabled === true }); +} + +const staffOperationMilliseconds = 25_000; + +type Held = { readonly outcome: 'held'; readonly reason: 'engineering_disabled' | 'engineering_unavailable' }; +export type SupportEngineeringProcessResult = EngineeringProcessResult | Held; + +/** No application, Store, auth, HTTP, policy ledger or scheduler is created. */ +export function createSupportEngineeringRuntime(options: SupportEngineeringRuntimeOptions) { + const application = options.application; + const ports = options.ports ?? {}; + const enabled = () => { try { return options.processingEnabled?.() === true; } catch { return false; } }; + const unavailable = async (): Promise => { throw new SupportEngineeringUnavailableError(); }; + const base: SupportDeskEngineeringOptions = { + application, clock: options.clock, + policy: { resolve: (access) => application.readRepositoryPolicy(access) }, + serviceAccess: ports.serviceAccess ?? { resolve: async () => ({ outcome: 'inactive' }) }, + reconciliationAccess: ports.reconciliationAccess ?? { resolve: async () => ({ outcome: 'inactive' }) }, + configuration: ports.configuration ?? { resolve: async () => ({ outcome: 'disabled' }) }, + routing: ports.routing ?? { resolve: async () => ({ outcome: 'unavailable' }), + check: async () => ({ outcome: 'unavailable' }), verify: async () => null }, + checks: ports.checks ?? { resolvePolicy: async () => ({ outcome: 'disabled' }), + check: async () => ({ outcome: 'held' }), verify: async () => null }, + model: ports.model ?? { generate: unavailable }, + usage: ports.usage ?? { reserve: async () => ({ outcome: 'unavailable' }), reconcile: async () => 'pending' }, + tokenCounter: ports.tokenCounter ?? { count() { throw new SupportEngineeringUnavailableError(); } }, + github: ports.github ?? { getMetadata: async () => null, searchDuplicates: unavailable, + createIssue: unavailable, reconcile: async () => ({ outcome: 'unknown' }) }, + proposals: ports.proposals ?? { duplicateQuery: async () => null, prepare: async () => ({ outcome: 'held' }) }, + maxOperationMilliseconds: 25_000, storageCommandAttempts: 2, + }; + const proofs = options.reviewProofs; + const reviewBase: SupportDeskEngineeringOptions = proofs === undefined ? base : { + ...base, serviceAccess: proofs.serviceAccess, + routing: { ...base.routing, resolve: (...args) => proofs.routing.resolve(...args), + verify: (...args) => proofs.routing.verify(...args) }, + checks: { ...base.checks, resolvePolicy: (...args) => proofs.checks.resolvePolicy(...args), + verify: (...args) => proofs.checks.verify(...args) }, + github: { ...base.github, getMetadata: (...args) => proofs.github.getMetadata(...args) }, + }; + const coordinator = createSupportDeskEngineering(base); + const processing = createSupportDeskEngineering({ ...base, serviceAccess: { + async resolve(signal) { + if (!enabled()) return { outcome: 'inactive' }; + const value = await base.serviceAccess.resolve(signal); + return enabled() ? value : { outcome: 'inactive' }; + }, + } }); + + async function staff(original: AccessContext, permission: string, + run: (access: AccessContext, refresh: () => Promise, signal: AbortSignal) => Promise): Promise { + const bound = structuredClone(original); + const started = performance.now(); + const controller = new AbortController(); + const ensure = (): void => { + if (controller.signal.aborted || performance.now() - started >= staffOperationMilliseconds) + throw new SupportEngineeringUnavailableError(); + }; + let rejectDeadline: (error: Error) => void = () => {}; + const deadline = new Promise((_resolve, reject) => { rejectDeadline = reject; }); + const timer = setTimeout(() => { + rejectDeadline(new SupportEngineeringUnavailableError()); + controller.abort(); + }, staffOperationMilliseconds); + const within = async (action: () => Promise): Promise => { + const value = await Promise.race([ + Promise.resolve().then(() => { ensure(); return action(); }), + deadline, + ]); + ensure(); + return value; + }; + async function refresh(): Promise { + ensure(); + if (original.principalId !== bound.principalId) + throw new SupportDeskAuthorizationError(permission); + let current: AccessContext | null; + try { current = await within(() => options.staffAccess.resolve(bound.principalId, controller.signal)); } + catch { ensure(); throw new SupportEngineeringUnavailableError(); } + if (current === null || current.principalId !== bound.principalId || + original.principalId !== bound.principalId) + throw new SupportDeskAuthorizationError(permission); + const access: AccessContext = { principalId: bound.principalId, policyVersion: current.policyVersion, + roles: current.roles.filter((role) => bound.roles.includes(role)), + entitlements: current.entitlements.filter((entry) => bound.entitlements.includes(entry)), + permissions: current.permissions.filter((entry) => bound.permissions.includes(entry)) }; + for (const required of [permission, supportPermissions.queueRead]) + if (!hasPermission(access, required)) throw new SupportDeskAuthorizationError(required); + return access; + } + try { + const current = await refresh(); + const value = await within(() => run(current, refresh, controller.signal)); + // A direct SDK mutation may commit after this boundary stops waiting. + // Withhold its unknown acknowledgement; only exact packet replay can + // recover it. Timeout never proves nonacceptance or rolls it back. + await refresh(); + return value; + } finally { + clearTimeout(timer); + controller.abort(); + } + } + + async function command(access: AccessContext, + permission: string, operation: SupportEngineeringOperation, ticketId: string, input: Input, + invoke: (current: AccessContext, packet: Omit & { commandId: string; correlationId: string }, + refresh: () => Promise, signal: AbortSignal) => Promise): Promise { + const packet = structuredClone(input); + const principalId = access.principalId; + return staff(access, permission, async (_current, refresh, signal) => { + const { clientCommandId, ...fields } = packet; + const identity = await supportEngineeringCommandIdentity({ principalId, ticketId, operation, clientCommandId }); + return invoke(await refresh(), { ...fields, ...identity }, refresh, signal); + }); + } + + async function reviewCommand(access: AccessContext, input: ReviewEngineeringProposalCommand, + beforeCommit?: () => Promise) { + const packet = structuredClone(input); + if (beforeCommit !== undefined && typeof beforeCommit !== 'function') + throw new TypeError('Expected an engineering browser commit guard'); + return staff(access, supportPermissions.engineeringReview, async (current, refresh, signal) => { + const reviewing = createSupportDeskEngineering(reviewBase); + return reviewing.reviewProposal(current, packet, { signal, + verifyBeforeCommit: async () => { await refresh(); await beforeCommit?.(); }, + }); + }); + } + + return Object.freeze({ + reviewCommand, + enroll: (access: AccessContext, input: EngineeringEnrollmentPacket) => + command(access, supportPermissions.engineeringEvidenceSubmit, 'enroll', input.ticketId, input, + (current, packet) => application.enrollEngineeringSource(current, packet)), + submitVerifiedFailure: (access: AccessContext, input: EngineeringFailurePacket) => + command(access, supportPermissions.engineeringEvidenceSubmit, 'failure', input.ticketId, input, + (current, packet) => application.submitEngineeringEvidence(current, packet)), + selectRepository: (access: AccessContext, input: EngineeringSelectionPacket) => + command(access, supportPermissions.engineeringReview, 'select', input.ticketId, input, + (current, packet) => application.selectEngineeringRepository(current, packet)), + reviewProposal: (access: AccessContext, input: EngineeringReviewPacket) => + command(access, supportPermissions.engineeringReview, 'review', input.ticketId, input, + async (current, packet, refresh, signal) => { + return coordinator.reviewProposal(current, packet, { signal, + verifyBeforeCommit: async () => { await refresh(); }, + }); + }), + invalidate: (access: AccessContext, input: EngineeringInvalidationPacket) => + command(access, supportPermissions.engineeringWithdraw, 'invalidate', input.ticketId, input, + (current, packet) => application.invalidateEngineeringSource(current, packet)), + withdraw: (access: AccessContext, input: EngineeringWithdrawalPacket) => + command(access, supportPermissions.engineeringWithdraw, 'withdraw', input.ticketId, input, + (current, packet) => application.withdrawEngineeringSource(current, packet)), + readSource: (access: AccessContext, ticketId: string) => + staff(access, supportPermissions.engineeringRead, (current) => application.readEngineeringSource(current, ticketId)), + readWork(access: AccessContext, input: EngineeringKey) { + const key = structuredClone(input); + return staff(access, supportPermissions.engineeringRead, (current) => application.readEngineeringWork(current, key)); + }, + readPolicy: (access: AccessContext) => + staff(access, supportPermissions.engineeringPolicyRead, (current) => application.readRepositoryPolicy(current)), + putPolicy: (access: AccessContext, input: EngineeringPolicyPacket, intentFingerprint?: string) => + command(access, supportPermissions.engineeringPolicyManage, 'policy_put', 'policy-instance', input, + (current, packet) => { + if (intentFingerprint !== undefined && !/^[a-f0-9]{64}$/u.test(intentFingerprint)) + throw new TypeError('Invalid engineering policy intent fingerprint'); + return application.putRepositoryPolicy(current, { + ...packet, + ...(intentFingerprint === undefined ? {} : { + correlationId: 'engineering-policy-intent:' + intentFingerprint, + }), + }); + }), + disableExports: (access: AccessContext, input: EngineeringDisablePacket) => + command(access, supportPermissions.engineeringPolicyManage, 'policy_disable', 'policy-instance', input, + (current, packet) => application.disableEngineeringExports(current, packet)), + scanReview(access: AccessContext, input: Parameters[1]) { + const bounds = structuredClone(input); + return staff(access, supportPermissions.engineeringReview, (current) => application.scanEngineeringCandidates(current, bounds)); + }, + async scanCandidates(input: Parameters[0]) { + if (!enabled()) return { outcome: 'held' as const, reason: 'engineering_disabled' as const }; + if (ports.serviceAccess === undefined) return { outcome: 'held' as const, reason: 'engineering_unavailable' as const }; + try { return await processing.scanCandidates(structuredClone(input)); } + catch { return { outcome: 'held' as const, reason: 'engineering_unavailable' as const }; } + }, + async processWork(input: Parameters[0]): Promise { + if (!enabled()) return { outcome: 'held', reason: 'engineering_disabled' }; + if (ports.serviceAccess === undefined) return { outcome: 'held', reason: 'engineering_unavailable' }; + return processing.processWork(structuredClone(input)); + }, + // Separate authority and no generation-config prerequisite, including after withdrawal. + reconcileSource: (ticketId: string) => coordinator.reconcileSource(ticketId), + }); +} + +export type SupportEngineeringRuntime = ReturnType; diff --git a/worker/src/support-learning-http.d1.test.ts b/worker/src/support-learning-http.d1.test.ts index d1657be..dfa11f7 100644 --- a/worker/src/support-learning-http.d1.test.ts +++ b/worker/src/support-learning-http.d1.test.ts @@ -16,6 +16,7 @@ import { createIdentityRuntime } from './identity-runtime'; import { APPLICATION_SCOPE, KNOWLEDGE_ROLE, SUPPORT_ROLE } from './support-access'; import { createSupportApi } from './support-api'; import { createSupportRuntime } from './support-desk'; +import { composeSupportEngineeringHuman, type SupportEngineeringHumanComposition } from './support-engineering-composition'; import { createWorker } from './index'; import { createSupportLearningRuntime, type SupportLearningRuntimeOptions } from './support-learning'; import { createSupportLearningReviewQueue, type SupportLearningReviewQueueMessage } from './support-learning-review-queue'; @@ -211,7 +212,7 @@ function meter(backing: D1Database) { }; } -async function fixture() { +async function fixture(withEngineering = false) { const binding = meter(env.IDENTITY_DB); const backing = createCloudflareD1Store({ database: binding.database, createSchemaIfMissing: false, readBatchSize: 512, @@ -369,12 +370,21 @@ async function fixture() { await hooks.afterLimiter?.(); return result; } }; - const api = createSupportApi({ + const api = (engineering?: SupportEngineeringHumanComposition) => createSupportApi({ ...authority, application: learning.application, createLimiter: host.createLimiter, replyLimiter: limiter, learningRuntime, learningEnabled: enabled, learningStagedReviewsEnabled: enabled, + ...(engineering === undefined ? {} : { + engineering: composeSupportEngineeringHuman({ ...host, application: learning.application }, logger, engineering), + }), + }); + const engineeringState = { enabled: true }; + const engineering = { enabled: () => engineeringState.enabled, + configuration: { application: { enabled: true }, repositories: [] } }; + const worker = () => createWorker({ + ...(withEngineering ? { engineering } : {}), + learningReviews: { enabled, create: (_environment, _logger, engineering) => ({ api: api(engineering), queue }) }, }); - const worker = () => createWorker({ learningReviews: { enabled, create: () => ({ api, queue }) } }); const broker: Queue = { async metrics() { return { backlogCount: messages.length, backlogBytes: 0 }; }, async send(message) { @@ -479,7 +489,7 @@ async function fixture() { }); } return { learning, principalId, invoke, request, send, deliver, revokeKnowledge, revokeRole, - grantRole, destroySession, prepareSdk, runtime, hooks, rewriteTicketVersion }; + grantRole, destroySession, prepareSdk, runtime, hooks, rewriteTicketVersion, engineeringState }; } @@ -919,3 +929,51 @@ describe('enabled learning HTTP namespace on real Native D1', () => { }); } }); + + +describe('combined registered staged-learning and human engineering composition', () => { + it('emits both current capabilities and preserves both routed SDK paths within each physical budget', async () => { + const f = await fixture(true); await f.learning.enrollAndVerify(); + const delivered = await f.learning.delivered(); + const ticketPath = '/api/support/admin/tickets/' + learningTicketId; + const detailRequest = () => new Request(IDENTITY_ISSUER + ticketPath, + { headers: new Headers(f.request('').headers) }); + const current = await f.send('combined.detail', detailRequest()); + expect(current.status).toBe(200); + expect(await envelope(current)).toMatchObject({ learningEnabled: true, + learningStagedReviewEnabled: true, engineeringEnabled: true, engineeringReviewEnabled: false }); + const inspected = await inspect(f, delivered, 'COMBINED-EXACT-UPPERCASE-REVIEW'); + expect(inspected.intent).toMatchObject({ ticketId: learningTicketId, reviewerId: f.principalId }); + const ticket = (await f.learning.application.readStaffTicket(f.learning.actors.staff, learningTicketId)).ticket; + const enrollment = JSON.stringify({ commandId: 'COMBINED-EXACT-UPPERCASE-ENROLL', expectedRevision: ticket.revision }); + const enrollRequest = () => new Request(IDENTITY_ISSUER + ticketPath + '/engineering/enroll', + { method: 'POST', headers: new Headers(f.request('', enrollment).headers), body: enrollment }); + const accepted = await f.send('combined.engineering.enroll', enrollRequest()); + expect(accepted.status).toBe(200); const acknowledgement = await envelope(accepted); + const rows = await f.learning.rows(); + const replay = await f.send('combined.engineering.replay', enrollRequest()); + expect(replay.status).toBe(200); expect(await envelope(replay)).toEqual(acknowledgement); + expect(await f.learning.rows()).toEqual(rows); + f.engineeringState.enabled = false; + const learningOnly = await f.send('combined.detail.engineering-off', detailRequest()); + expect(learningOnly.status).toBe(200); + expect(await envelope(learningOnly)).toMatchObject({ learningEnabled: true, + learningStagedReviewEnabled: true, engineeringEnabled: false, engineeringReviewEnabled: false }); + expect(f.learning.state.modelCalls).toBe(1); expect(await f.learning.rows()).toEqual(rows); + }); + + it('requires current stored Support authority on both surfaces after either factory observed it', async () => { + const f = await fixture(true); await f.learning.enrollAndVerify(); await f.learning.delivered(); + const path = '/api/support/admin/tickets/' + learningTicketId; + const current = await f.send('combined.detail.before-revoke', new Request(IDENTITY_ISSUER + path, + { headers: new Headers(f.request('').headers) })); + expect(current.status).toBe(200); expect(await envelope(current)).toMatchObject({ engineeringEnabled: true }); + await f.revokeRole(SUPPORT_ROLE); const rows = await f.learning.rows(); + for (const suffix of ['', '/engineering']) { + const denied = await f.send('combined.role-denied' + suffix, new Request(IDENTITY_ISSUER + path + suffix, + { headers: new Headers(f.request('').headers) })); + expect(denied.status).toBe(403); expect(await envelope(denied)).not.toHaveProperty('result'); + } + expect(await f.learning.rows()).toEqual(rows); expect(f.learning.state.modelCalls).toBe(1); + }); +}); From 756f0fb08eb0bedd732955872466f705dd6fc8ea Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 15:13:40 -0500 Subject: [PATCH 2/7] Guard engineering mutations and recover immutable selections --- docs/SUPPORT_ENGINEERING.md | 65 +++++-- package.json | 10 +- pnpm-lock.yaml | 58 +++--- public/staff-support-engineering.js | 56 ++++-- src/pages/staff/support/ticket.astro | 29 +++ src/support-engineering-integration.test.ts | 180 +++++++++++++++++- src/support-engineering-review.test.ts | 2 + src/support-engineering-ui.test.ts | 39 +++- worker/README.md | 16 +- worker/src/index.ts | 2 +- worker/src/maintenance-cursors.d1.test.ts | 50 ++++- worker/src/maintenance-schedule.test.ts | 21 +- worker/src/maintenance-schedule.ts | 9 +- worker/src/support-desk.ts | 32 +++- .../support-engineering-composition.test.ts | 62 +++++- worker/src/support-engineering-composition.ts | 3 +- .../src/support-engineering-handlers.test.ts | 93 +++++---- worker/src/support-engineering-handlers.ts | 82 +++++--- .../src/support-engineering-http-fixtures.ts | 3 +- .../src/support-engineering-http.d1.test.ts | 145 +++++++++++++- ...upport-engineering-human-mutations.test.ts | 124 ++++++++++++ worker/src/support-engineering.ts | 87 ++++++--- 22 files changed, 970 insertions(+), 198 deletions(-) create mode 100644 worker/src/support-engineering-human-mutations.test.ts diff --git a/docs/SUPPORT_ENGINEERING.md b/docs/SUPPORT_ENGINEERING.md index 925885a..d2c23c2 100644 --- a/docs/SUPPORT_ENGINEERING.md +++ b/docs/SUPPORT_ENGINEERING.md @@ -3,13 +3,14 @@ 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. +configuration, so engineering intake and review remain OFF. This assembly uses +the five published Support Desk packages at exact version `0.2.6`. The [runtime](../worker/src/support-engineering.ts), [HTTP adapter](../worker/src/support-engineering-handlers.ts), [router](../worker/src/support-engineering-router.ts) and [panel](../public/staff-support-engineering.js) reuse the host's existing -Support application, Identity, sessions, stored roles and durable limiter. +Support application, Identity, sessions, stored roles and durable limiters. 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. @@ -65,7 +66,7 @@ Let **T** be `/api/support/admin/tickets/:ticketId/engineering` and **P** be | `POST T/review` | Only `intent`, the complete actor-bound SDK command | | `POST T/enroll` | `commandId`, `expectedRevision` | | `POST T/evidence` | `commandId`, `expectedRevision`, `expectedBehavior`, `actualBehavior`, `reproductionSteps`, `visibleMessageIds`, `verificationReference`, `security` | -| `POST T/repository` | `commandId`, `sourceGeneration`, `expectedWorkGeneration`, `repositoryKey`, `policyGeneration`, `policyHash`, `reason` | +| `POST T/repository` | `commandId`, `sourceGeneration`, `expectedWorkGeneration`, `repositoryKey`, `repositoryId`, `repositoryDescriptorHash`, `policyGeneration`, `policyHash`, `reason` | | `POST T/withdraw` | `commandId`, `reason` | | `POST T/invalidate` | `commandId`, `reason` | | `GET P` | No body/query | @@ -81,6 +82,14 @@ awaits and before responses. A closing denial can withhold an ACK after a real SDK commit; it does not undo that commit. Errors expose bounded codes, not private proof or raw dependency messages. Honor `Retry-After`. +Engineering reads have their own durable 120-per-hour policy; engineering +mutations have a separate 30-per-hour policy, both keyed by the current human +principal. These counters share the existing Store but consume neither the +ordinary ticket-reply quota nor each other's quota. Their expired windows are +swept in separate rotating cleanup invocations. A denied request returns the +actual limiter's `Retry-After`; crossing that deadline permits an explicit +retry and never schedules a command automatically. + Ordinary bodies, including preparation, use the existing **64 KiB / 10-second** reader. Only full policy submission uses **128 KiB / 10 seconds**; its prepared response is also bounded. Scalar command IDs remain case-preserved and bounded @@ -103,11 +112,14 @@ The current SDK receipt lookup precedes mutable export proofs. Exact accepted replay therefore survives source withdrawal or unavailable repository facts. The runtime passes its fresh staff check and original-browser callback through -the public coordinator's `verifyBeforeCommit` option. The coordinator retains -the final synchronous proof assertion for the Application transaction boundary. -Both approval and rejection require this current-human guard. New approval also -requires the configured read-only routing, checks and repository proof ports. -The independent review switch defaults OFF. +the public SDK's `verifyBeforeCommit` option for all seven human intake and +policy mutations. The SDK looks for an exact accepted receipt before invoking +the new-command guard; that guard supplies the final synchronous deadline and +principal assertion at the Application transaction boundary. Current browser +and role checks still protect every replay and response. The separate proposal +review guard applies to both approval and rejection. New approval also requires +the configured read-only routing, checks and repository proof ports. The +independent review switch defaults OFF. An unresolved engineering review retains its original full command. The public SDK exposes receipt-first replay through `reviewProposal`. A never-accepted @@ -141,6 +153,13 @@ form. Internal notes are not public message choices. See the [HTTP fixture](../worker/src/support-engineering-http-fixtures.ts) and [panel tests](../src/support-engineering-ui.test.ts). +A known, bound evidence ACK can settle after a new same-actor staff-ticket +read even when the private source still returns 403. This does not grant +restricted-read permission or prove the current source state. In that case +the panel permits explicit withdrawal, while evidence reclassification and +invalidation remain unavailable. Unknown commands stay retained; a denial +alone cannot acknowledge them. + ## Immutable policy intent and recovery Policy GET distinguishes saved mapped entries, `unmappedRepositoryCount` and the @@ -156,16 +175,26 @@ Keep it out of DOM, URLs, logs and browser storage. Do not reconstruct it from a later catalog. Current Admin + Support and browser authority are still required on every preparation, submission and replay. -At the expected current head, the adapter compares the prepared snapshot with -current trusted configuration. A future generation is rejected. At a newer -**monotonic SDK head**, the exact retained command can reach receipt-first -replay before the stale expected-generation CAS: changed descriptors or removed -keys cannot strand an already committed ACK. Missing/pruned receipts cannot -create a new commit under that stale generation. Do not reset/reuse policy -heads or edit SDK policy rows outside supported operations. Complete normalized -intent bytes, including wrapper keys and ordering, bind the server-derived -correlation identity. Altering a snapshot while reusing an ID is a conflict, -not a corrected retry. +The SDK checks the complete retained command for an accepted receipt before +new-command policy and catalog checks. Only a new command must match current +trusted configuration and pass the SDK's expected-generation CAS. Changed +descriptors or removed keys cannot strand an already committed ACK. A missing +or pruned receipt cannot create a new commit under a stale generation. Do not +reset/reuse policy heads or edit SDK policy rows outside supported operations. +Complete normalized intent bytes, including wrapper keys and ordering, bind the +server-derived correlation identity. Altering a snapshot while reusing an ID +is a conflict, not a corrected retry. + +Repository selection follows the same boundary. The checked work response +provides ordered `repositoryChoices` containing each friendly key, immutable +repository ID and full normalized descriptor hash, together with the current +policy generation and hash. Retain the chosen pair, descriptor hash and policy +fences in the original command. Only the friendly key is displayed; descriptors +and installation bindings are not browser fields. New selections must match the +current configured descriptor and SDK policy. Exact accepted replay bypasses +obsolete catalog facts while still requiring current browser and Support +review authority. A removed key or changed descriptor without an accepted +receipt cannot authorize a new selection. The [actual HTTP policy cases](../worker/src/support-engineering-handlers.test.ts) cover changed/removed catalogs, altered wrappers, future heads, missing/pruned diff --git a/package.json b/package.json index ba4818a..41813f9 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.5", - "@pegma/support-desk-application": "0.2.5", - "@pegma/support-desk-contracts": "0.2.5", - "@pegma/support-desk-core": "0.2.5", - "@pegma/support-desk-templates": "0.2.5", + "@pegma/support-desk-ai": "0.2.6", + "@pegma/support-desk-application": "0.2.6", + "@pegma/support-desk-contracts": "0.2.6", + "@pegma/support-desk-core": "0.2.6", + "@pegma/support-desk-templates": "0.2.6", "@pegma/webhooks": "0.1.1", "agents": "^0.20.1", "zod": "^4.4.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a36c60d..a07bbf8 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.5 - version: 0.2.5 + specifier: 0.2.6 + version: 0.2.6 '@pegma/support-desk-application': - specifier: 0.2.5 - version: 0.2.5 + specifier: 0.2.6 + version: 0.2.6 '@pegma/support-desk-contracts': - specifier: 0.2.5 - version: 0.2.5 + specifier: 0.2.6 + version: 0.2.6 '@pegma/support-desk-core': - specifier: 0.2.5 - version: 0.2.5 + specifier: 0.2.6 + version: 0.2.6 '@pegma/support-desk-templates': - specifier: 0.2.5 - version: 0.2.5 + specifier: 0.2.6 + version: 0.2.6 '@pegma/webhooks': specifier: 0.1.1 version: 0.1.1 @@ -1239,24 +1239,24 @@ packages: resolution: {integrity: sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==} engines: {node: '>=22'} - '@pegma/support-desk-ai@0.2.5': - resolution: {integrity: sha512-N2IFpoiD1g8tAgZjmBb3OcNxZiAZNDwNMVxxUy/1SkVZOT0r+THDw/R21MWw1raF6LsZdurnAZ8AyZFLX+RaCw==} + '@pegma/support-desk-ai@0.2.6': + resolution: {integrity: sha512-KEYGWcLonL+m4IUJrbfCFFzXm2l7CLBzRAUdAu3jX99OU0+iR+dqjF/sWaj61JDLj2s1T3VwAGLd1i00+RAYKg==} engines: {node: '>=22'} - '@pegma/support-desk-application@0.2.5': - resolution: {integrity: sha512-RwDvWkelRKYTyKxx/8xp8FFTtV2nKjLlsHFD3y6a2hU0ZOeeigbWpmyflY0eB/qwlIEFaCn1MPSfCykNgP4ZOg==} + '@pegma/support-desk-application@0.2.6': + resolution: {integrity: sha512-jqecCURuVcasRZGXFdwiDtQk3yM/P03Ij/JmQovw9nYrhXOzGeIYB3+Ro19IDKgMkH+XF4MghVFUZ+b7BPMDIg==} engines: {node: '>=22'} - '@pegma/support-desk-contracts@0.2.5': - resolution: {integrity: sha512-XKzPVnhOpd0PUmzcNjeYE1bh5+RFWM9O+rHwqCDaVR9a+jUvh7u2ENoGSSxg6GG1FYRwqhoWCpTMCY3wEAZwZw==} + '@pegma/support-desk-contracts@0.2.6': + resolution: {integrity: sha512-blhLS3iUXK0dDz2k/uw2fN0as2Tnvjx/XLMc8OGg/0Njiox+0YHdotYewx/yIrzI6XQkUWBzz/CyVyNI+ObUAA==} engines: {node: '>=22'} - '@pegma/support-desk-core@0.2.5': - resolution: {integrity: sha512-9hXyfL15CqJfSPSmgeJZ8xbGD8ZuBCQsceci5RlesP3wEjhdqVZHYC9fEDj6PuL1locvoanmTBXsIVkU52LWQw==} + '@pegma/support-desk-core@0.2.6': + resolution: {integrity: sha512-Gc5L7/mniQnOsi+sLGYDINEgXJE6ilgC3ghleQ6QIYNfOMJ94WIZ1v/mEI7w9kRPBjsk+TISxRAiQPjRaQC9Ow==} engines: {node: '>=22'} - '@pegma/support-desk-templates@0.2.5': - resolution: {integrity: sha512-W9DXJJ465b3BCnn9AgViRXqSd0fIHTRD/w6TU+1cmHj7C61zcg7vg5Qk7CEZ4raPwrWsp1JvNQxtAHRMNSeOjw==} + '@pegma/support-desk-templates@0.2.6': + resolution: {integrity: sha512-94ZgKYa4K4gu//7aHohyJhjfDbX+hUJPOKCIL9XbhdAsX5FZK+uXTrDszGZwJiO4aGSvZUrQ/Ju5cDDIyhW/7w==} engines: {node: '>=22'} '@pegma/webhooks@0.1.1': @@ -4260,33 +4260,33 @@ snapshots: '@pegma/storage-core@0.4.0': {} - '@pegma/support-desk-ai@0.2.5': + '@pegma/support-desk-ai@0.2.6': dependencies: '@pegma/authorization-core': 0.4.0 '@pegma/knowledge-base-application': 0.1.5 '@pegma/knowledge-base-contracts': 0.1.5 '@pegma/spine': 0.1.2 - '@pegma/support-desk-application': 0.2.5 + '@pegma/support-desk-application': 0.2.6 - '@pegma/support-desk-application@0.2.5': + '@pegma/support-desk-application@0.2.6': 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.5 - '@pegma/support-desk-core': 0.2.5 + '@pegma/support-desk-contracts': 0.2.6 + '@pegma/support-desk-core': 0.2.6 - '@pegma/support-desk-contracts@0.2.5': + '@pegma/support-desk-contracts@0.2.6': dependencies: '@pegma/spine': 0.1.2 - '@pegma/support-desk-core@0.2.5': + '@pegma/support-desk-core@0.2.6': dependencies: - '@pegma/support-desk-contracts': 0.2.5 + '@pegma/support-desk-contracts': 0.2.6 - '@pegma/support-desk-templates@0.2.5': {} + '@pegma/support-desk-templates@0.2.6': {} '@pegma/webhooks@0.1.1': dependencies: diff --git a/public/staff-support-engineering.js b/public/staff-support-engineering.js index 2773ec6..7738812 100644 --- a/public/staff-support-engineering.js +++ b/public/staff-support-engineering.js @@ -132,6 +132,10 @@ for (const input of inputs) input.value = ''; withdrawal.input.value = withdrawals[0]; invalidation.input.value = invalidations[0]; } + function evidenceLocked() { + const intake = source ?? enrolled.get(key('ticket')); + return intake?.withdrawalOnly === true || ['restricted', 'withdrawn'].includes(intake?.state); + } function controls() { const active = context !== null && enabled(); for (const item of ticketNodes) item.hidden = context?.ticketId === null; @@ -142,14 +146,14 @@ // Private-read denial does not establish absence. Explicit enrollment is // a separately authorized SDK command which can confirm existing intake. enrollButton.disabled ||= !canWrite || source !== null || enrolled.has(key('ticket')); - evidenceButton.disabled ||= !canWrite || (source?.state === 'withdrawn' || enrolled.get(key('ticket'))?.state === 'withdrawn') || !(source !== null || enrolled.has(key('ticket'))); + evidenceButton.disabled ||= !canWrite || evidenceLocked() || !(source !== null || enrolled.has(key('ticket'))); workButton.disabled ||= source === null || source.sourceGeneration <= 0; proposalButton.disabled ||= !reviewEnabled() || workButton.disabled || held !== undefined; approveButton.disabled ||= !reviewEnabled() || !canWrite || proposal?.approvable !== true; rejectButton.disabled ||= !reviewEnabled() || !canWrite || proposal?.rejectionAvailable !== true; selectButton.disabled ||= !canWrite || work?.selection === undefined || work.selection.repositoryKeys.length === 0; withdrawButton.disabled ||= !canWrite || !(source !== null || enrolled.has(key('ticket'))); - invalidateButton.disabled ||= withdrawButton.disabled; + invalidateButton.disabled ||= withdrawButton.disabled || evidenceLocked(); prepareButton.disabled ||= policy === null || policy.unmappedRepositoryCount !== 0 || policy.catalog.length === 0 || policyHeld !== undefined; saveButton.disabled ||= preparedPolicy === null || policyHeld !== undefined; disableButton.disabled ||= policy === null || policyHeld !== undefined; @@ -234,12 +238,18 @@ if (![403, 404].includes(error?.status)) throw error; await viewer(observation, actor); notice(error.status === 403 ? 'Source details are unavailable with current access.' : 'No source details were returned; explicit enrollment is checked by the server.'); - // A 403 is never absence or RestrictedRead. Only our bound known enroll - // ACK plus a NEW current same-actor staff-ticket read admits evidence. - if (acknowledged?.action === 'enroll') { - await currentTicket(observation, actor); enrolled.set(key('ticket'), copy(acknowledged.ack)); + // Denial is never absence or RestrictedRead. A bound source-command + // ACK plus a NEW current same-actor staff-ticket read can settle that + // command. Only enrollment admits evidence; other protected ACKs admit + // explicit withdrawal, without asserting the current private state. + if (acknowledged && ['enroll', 'evidence', 'withdraw'].includes(acknowledged.action) && + pending.get(acknowledged.key) === acknowledged && ack(acknowledged.ack, acknowledged)) { + await currentTicket(observation, actor); + enrolled.set(key('ticket'), { ...copy(acknowledged.ack), withdrawalOnly: acknowledged.action !== 'enroll' }); pending.delete(acknowledged.key); changed(); - notice('Enrollment acknowledged. Current staff ticket refreshed; record evidence explicitly. Source details remain protected.'); + notice(acknowledged.action === 'enroll' && !evidenceLocked() + ? 'Enrollment acknowledged. Current staff ticket refreshed; record evidence explicitly. Source details remain protected.' + : 'Command acknowledged. Current staff ticket refreshed; source details remain protected. Explicit withdrawal remains available.'); return; } if (acknowledged) return; @@ -269,9 +279,20 @@ counter(value.workGeneration, 1); text(value.status); text(value.stage); for (const key of ['hasCandidate', 'hasPreparedProposal', 'hasApproval', 'hasDispatch']) if (typeof value[key] !== 'boolean') throw invalid(); const selected = value.selection; - if (selected !== undefined && (!object(selected) || !Array.isArray(selected.repositoryKeys) || selected.repositoryKeys.length > 20 || - new Set(selected.repositoryKeys).size !== selected.repositoryKeys.length)) throw invalid(); - if (selected) { counter(selected.policyGeneration); hash(selected.policyHash); selected.repositoryKeys.forEach((key) => text(key, 100)); } + if (selected !== undefined) { + if (!object(selected) || !Array.isArray(selected.repositoryKeys) || !Array.isArray(selected.repositoryChoices) || + selected.repositoryKeys.length > 20 || selected.repositoryChoices.length !== selected.repositoryKeys.length || + new Set(selected.repositoryKeys).size !== selected.repositoryKeys.length) throw invalid(); + counter(selected.policyGeneration); hash(selected.policyHash); selected.repositoryKeys.forEach((key) => text(key, 100)); + const identities = new Set(); + selected.repositoryChoices.forEach((choice, index) => { + if (!object(choice) || JSON.stringify(Object.keys(choice).sort()) !== JSON.stringify(['descriptorHash', 'key', 'repositoryId']) || + choice.key !== selected.repositoryKeys[index]) throw invalid(); + text(choice.repositoryId); hash(choice.descriptorHash); + if (identities.has(choice.repositoryId)) throw invalid(); + identities.add(choice.repositoryId); + }); + } await viewer(observation, actor); work = copy(value); session = actor; workText.textContent = JSON.stringify({ sourceGeneration: value.sourceGeneration, workGeneration: value.workGeneration, status: value.status, stage: value.stage, security: value.security, hasCandidate: value.hasCandidate, @@ -331,7 +352,7 @@ return operation(async (observation) => { await viewer(observation, session); const retained = retain('ticket', 'review', base() + '/review', { intent: original }, - { sourceGeneration: original.command.sourceGeneration, expectedWorkGeneration: original.command.expectedWorkGeneration }); + { sourceGeneration: original.command.sourceGeneration, expectedWorkGeneration: original.command.expectedWorkGeneration, decision }); proposal = null; proposalText.textContent = ''; await send(retained, observation); }); @@ -402,7 +423,8 @@ typeof value.enabled === 'boolean' && typeof value.policyHash === 'string' && /^[0-9a-f]{64}$/u.test(value.policyHash); if (value.ticketId !== retained.ticketId || !Number.isSafeInteger(value.sourceGeneration) || value.sourceGeneration < 0) return false; if (retained.action === 'review') return value.sourceGeneration === retained.sourceGeneration && - value.workGeneration === retained.expectedWorkGeneration + 1 && value.status === 'approved'; + value.workGeneration === retained.expectedWorkGeneration + 1 && + ((retained.decision === 'approve' && value.status === 'approved') || (retained.decision === 'reject' && value.status === 'held')); if (retained.action === 'repository') return value.sourceGeneration === retained.sourceGeneration && Number.isSafeInteger(value.workGeneration) && value.workGeneration > 0 && typeof value.status === 'string'; return states.includes(value.state) && securityValues.includes(value.security); @@ -458,7 +480,7 @@ try { if (action === 'enroll') fields = { expectedRevision: ticket.revision }; else if (action === 'evidence') { - if ((source?.state === 'withdrawn' || enrolled.get(key('ticket'))?.state === 'withdrawn') || !(source || enrolled.has(key('ticket'))) || !securityValues.includes(sensitivity.input.value)) throw new Error('invalid_input'); + if (evidenceLocked() || !(source || enrolled.has(key('ticket'))) || !securityValues.includes(sensitivity.input.value)) throw new Error('invalid_input'); const reproductionSteps = steps.input.value.split(/\r?\n/u).map((entry) => text(entry, 1000, true)); const selected = [...messageChoices.querySelectorAll('input')].filter((item) => item.checked).map((item) => item.value); if (!selected.length || selected.length > 16 || selected.some((id) => !ticket.visibleMessageIds.includes(id)) || @@ -467,12 +489,14 @@ actualBehavior: text(actual.input.value, 2000, true), reproductionSteps, visibleMessageIds: selected, verificationReference: text(reference.input.value), security: sensitivity.input.value }; } else if (action === 'repository') { - if (!work?.selection?.repositoryKeys.includes(repository.input.value)) throw new Error('invalid_input'); + const choice = work?.selection?.repositoryChoices.find((entry) => entry.key === repository.input.value); + if (!choice) throw new Error('invalid_input'); fields = { sourceGeneration: work.sourceGeneration, expectedWorkGeneration: work.workGeneration, - repositoryKey: repository.input.value, policyGeneration: work.selection.policyGeneration, + repositoryKey: choice.key, repositoryId: choice.repositoryId, repositoryDescriptorHash: choice.descriptorHash, + policyGeneration: work.selection.policyGeneration, policyHash: work.selection.policyHash, reason: text(reason.input.value) }; } else if (action === 'withdraw' && withdrawals.includes(withdrawal.input.value)) fields = { reason: withdrawal.input.value }; - else if (action === 'invalidate' && invalidations.includes(invalidation.input.value)) fields = { reason: invalidation.input.value }; + else if (action === 'invalidate' && !evidenceLocked() && invalidations.includes(invalidation.input.value)) fields = { reason: invalidation.input.value }; else if (action === 'policy-disable') fields = { expectedGeneration: policy.generation }; else throw new Error('invalid_input'); } catch { notice('Complete the bounded required fields and choose sensitivity explicitly. No command was sent.'); return; } diff --git a/src/pages/staff/support/ticket.astro b/src/pages/staff/support/ticket.astro index 2793315..f1d2774 100644 --- a/src/pages/staff/support/ticket.astro +++ b/src/pages/staff/support/ticket.astro @@ -149,3 +149,32 @@ import Base from '../../../layouts/Base.astro'; + + diff --git a/src/support-engineering-integration.test.ts b/src/support-engineering-integration.test.ts index 5d69760..1ef2fc7 100644 --- a/src/support-engineering-integration.test.ts +++ b/src/support-engineering-integration.test.ts @@ -80,6 +80,24 @@ async function harness(autoEnrolled = false) { writes: () => calls.filter((call) => call.method === 'POST') }; } +async function readySelection(h: Awaited>) { + const catalog = h.f.options.repositories.map((entry, index) => ({ ...entry, key: 'public-repository-choice-' + index })); + h.state.handle = createSupportEngineeringHandlers({ ...h.f.options, repositories: catalog }); + await h.open(); await h.action('enroll'); h.evidence(); await h.action('evidence'); + const source = await h.f.engineering.source(); + h.f.engineering.state.modelRouting = 'ambiguous'; + expect((await h.f.state.runtime.processWork({ ticketId: engineeringTicketId, sourceGeneration: source.sourceGeneration, + workerId: 'synthetic-ui-selection-worker', leaseMilliseconds: 30_000 })).outcome).toBe('candidate'); + await h.action('work'); + const response = await h.state.handle(h.f.request('work', undefined, 'staff', '?sourceGeneration=' + source.sourceGeneration)); + if (response === null || !response.ok) throw new Error('Actual immutable selection read unavailable'); + const envelope = await response.json() as { result: { selection: { repositoryChoices: { key: string; repositoryId: string; descriptorHash: string }[] } } }; + const choice = envelope.result.selection.repositoryChoices[1]; + if (choice === undefined) throw new Error('Actual immutable repository choice missing'); + h.node('repository', true).value = choice.key; h.node('repository-reason', true).value = 'The verified failure concerns the configured download API.'; + return { catalog, choice }; +} + describe('public engineering panel through actual Memory SDK and HTTP authority', () => { it('keeps an engineering-prefixed ticket ID on the actual staff detail route before engineering intake', async () => { const h = await harness(); await h.open(); @@ -125,6 +143,103 @@ describe('public engineering panel through actual Memory SDK and HTTP authority' expect(h.f.engineering.state.modelCalls).toBe(0); expect(h.f.engineering.state.creates).toEqual([]); }); + it('replays the immutable real SDK repository selection after committed ACK loss and catalog removal without rebuilding its packet', async () => { + const h = await harness(); const { choice } = await readySelection(h); + const rendered = JSON.stringify(h.root.all().map((item) => ({ text: item.textContent, value: item.value, + dataset: item.dataset, attributes: [...item.attributes] }))); + for (const opaque of [choice.repositoryId, choice.descriptorHash, 'repositoryId', 'descriptorHash', 'installationBinding']) + expect(rendered).not.toContain(opaque); + let lose = true; + h.state.fault = async (path, response) => { + if (lose && path.endsWith('/repository') && response.ok) { + lose = false; throw Object.assign(new Error('Synthetic selection ACK loss AFTER actual SDK commit'), { status: 503 }); + } + }; + await h.action('repository'); const original = h.writes().at(-1)!; + expect(original.serverStatus).toBe(200); + expect(JSON.parse(original.body ?? '{}')).toMatchObject({ repositoryKey: choice.key, repositoryId: choice.repositoryId, + repositoryDescriptorHash: choice.descriptorHash }); + expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); + const source = await h.f.engineering.source(); + const committed = await h.f.engineering.application.readEngineeringWork(h.f.engineering.actors.security, + { ticketId: engineeringTicketId, sourceGeneration: source.sourceGeneration }); + expect(committed.staffSelection).toMatchObject({ repositoryId: choice.repositoryId, + reason: 'The verified failure concerns the configured download API.' }); + const rows = await h.f.rows(); const modelCalls = h.f.engineering.state.modelCalls; const ids = h.state.ids; + h.state.fault = undefined; + h.state.handle = createSupportEngineeringHandlers({ ...h.f.options, repositories: [] }); + await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original.body); expect(h.writes().at(-1)?.serverStatus).toBe(200); + expect(h.state.ids).toBe(ids); expect(await h.f.rows()).toEqual(rows); + expect(h.f.engineering.state.modelCalls).toBe(modelCalls); expect(h.f.engineering.state.creates).toEqual([]); + expect(h.panel.hasPending()).toBe(false); + for (const opaque of [choice.repositoryId, choice.descriptorHash, 'repositoryDescriptorHash']) + expect(JSON.stringify(h.ownership)).not.toContain(opaque); + }); + + it('keeps an unaccepted immutable repository packet unknown after its key is removed and retries only those original bytes', async () => { + const h = await harness(); const { catalog, choice } = await readySelection(h); + h.state.handle = createSupportEngineeringHandlers({ ...h.f.options, repositories: catalog.filter((entry) => entry.key !== choice.key) }); + const rows = await h.f.rows(); const modelCalls = h.f.engineering.state.modelCalls; + await h.action('repository'); const original = h.writes().at(-1)!; const ids = h.state.ids; + expect(original.serverStatus).toBe(409); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); + expect(JSON.parse(original.body ?? '{}')).toMatchObject({ repositoryKey: choice.key, repositoryId: choice.repositoryId, + repositoryDescriptorHash: choice.descriptorHash }); + await h.panel.refresh(); expect(h.panel.hasPending()).toBe(true); + await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original.body); expect(h.writes().at(-1)?.serverStatus).toBe(409); + expect(h.state.ids).toBe(ids); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); + expect(await h.f.rows()).toEqual(rows); expect(h.f.engineering.state.modelCalls).toBe(modelCalls); + expect(h.f.engineering.state.creates).toEqual([]); + }); + + it.each(['missing choices', 'mismatched key', 'duplicate key', 'duplicate identity', 'malformed hash', 'extra choice field', 'too many choices', 'null selection'])( + 'rejects a corrupted real HTTP selection response with %s before allowing any repository command', async (fault) => { + const h = await harness(); await readySelection(h); const posts = h.writes().length; const ids = h.state.ids; + const modelCalls = h.f.engineering.state.modelCalls; + h.state.fault = async (path, response) => { + if (!path.includes('/work?') || !response.ok) return; + // Explicit transport corruption of a genuine protected HTTP response. + const envelope = await response.clone().json() as { result: { selection: { + repositoryKeys: string[]; repositoryChoices?: { key: string; repositoryId: string; descriptorHash: string; extra?: string }[]; + } | null } }; + const selection = envelope.result.selection; + if (!selection?.repositoryChoices?.[0] || !selection.repositoryChoices[1]) throw new Error('Actual selection choices missing before corruption'); + if (fault === 'missing choices') delete selection.repositoryChoices; + else if (fault === 'mismatched key') selection.repositoryChoices[0].key = 'not-the-listed-key'; + else if (fault === 'duplicate key') { + selection.repositoryKeys[1] = selection.repositoryKeys[0]!; + selection.repositoryChoices[1].key = selection.repositoryChoices[0].key; + } else if (fault === 'duplicate identity') selection.repositoryChoices[1].repositoryId = selection.repositoryChoices[0].repositoryId; + else if (fault === 'malformed hash') selection.repositoryChoices[0].descriptorHash = 'not-a-descriptor-hash'; + else if (fault === 'extra choice field') selection.repositoryChoices[0].extra = 'untrusted opaque field'; + else if (fault === 'too many choices') { + const descriptorHash = selection.repositoryChoices[0].descriptorHash; + selection.repositoryChoices = Array.from({ length: 21 }, (_, index) => ({ key: 'key-' + index, repositoryId: 'id-' + index, descriptorHash })); + selection.repositoryKeys = selection.repositoryChoices.map((choice) => choice.key); + } else envelope.result.selection = null; + response.json = async () => envelope; + }; + await h.action('work'); expect(h.node('repository').disabled).toBe(true); + await h.action('repository'); expect(h.writes()).toHaveLength(posts); expect(h.state.ids).toBe(ids); + expect(h.panel.hasPending()).toBe(false); expect(h.f.engineering.state.modelCalls).toBe(modelCalls); + expect(h.f.engineering.state.creates).toEqual([]); + }, + ); + + it('reads real work metadata without repository admission when the HTTP DTO has no selection object', async () => { + const h = await harness(); await readySelection(h); const posts = h.writes().length; const ids = h.state.ids; + h.state.fault = async (path, response) => { + if (!path.includes('/work?') || !response.ok) return; + const envelope = await response.clone().json() as { result: { selection?: unknown } }; + delete envelope.result.selection; response.json = async () => envelope; + }; + await h.action('work'); expect(h.root.textContent).toContain('"hasCandidate": true'); + expect(h.node('repository').disabled).toBe(true); await h.action('repository'); + expect(h.writes()).toHaveLength(posts); expect(h.state.ids).toBe(ids); expect(h.panel.hasPending()).toBe(false); + expect(h.f.engineering.state.creates).toEqual([]); + }); + it('retains the exact uppercase unknown evidence packet across actual withdrawal and replay without a new command', async () => { const h = await harness(); await h.open(); await h.action('enroll'); h.evidence(); let lose = true; @@ -191,13 +306,70 @@ describe('public engineering panel through actual Memory SDK and HTTP authority' expect(h.panel.hasPending()).toBe(false); expect(await h.f.policyRows()).toEqual(before); }); - it('keeps a restricted evidence ACK known while protected GET recovery remains unreadable', async () => { + it('settles a restricted evidence ACK with fresh staff authority and allows only explicit withdrawal while source GET remains protected', async () => { const h = await harness(); await h.open(); await h.action('enroll'); h.evidence('uncertain'); await h.action('evidence'); expect((await h.f.engineering.source()).state).toBe('restricted'); + const evidence = h.calls.findIndex((call) => call.path.endsWith('/evidence')); + const protectedRead = h.calls.findIndex((call, index) => index > evidence && call.path.endsWith('/engineering') && call.serverStatus === 403); + expect(protectedRead).toBeGreaterThan(evidence); + expect(h.calls.slice(protectedRead + 1).some((call) => call.path === '/api/support/admin/tickets/' + engineeringTicketId && call.serverStatus === 200)).toBe(true); + expect((await h.f.resolve(h.f.principals.staff))?.permissions).not.toContain(supportPermissions.engineeringRestrictedRead); + expect(h.panel.hasPending()).toBe(false); + expect(h.node('evidence').disabled).toBe(true); expect(h.node('invalidate').disabled).toBe(true); + expect(h.node('withdraw').disabled).toBe(false); + const posts = h.writes().length; + await h.action('evidence'); await h.action('invalidate'); expect(h.writes()).toHaveLength(posts); + await h.action('withdraw'); expect(h.writes()).toHaveLength(posts + 1); + expect(JSON.parse(h.writes().at(-1)?.body ?? '{}').reason).toBe('privacy_withdrawal'); + expect((await h.f.engineering.source()).state).toBe('withdrawn'); expect(h.panel.hasPending()).toBe(false); + expect(h.node('evidence').disabled).toBe(true); expect(h.root.textContent).not.toContain(engineeringCanary); + expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('retains a known restricted evidence ACK until a NEW same-actor staff-ticket read succeeds, then recovers by GET only', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); h.evidence('restricted'); + let accepted = false; + h.state.fault = async (path, response) => { + if (path.endsWith('/evidence') && response.ok) accepted = true; + else if (accepted && path === '/api/support/admin/tickets/' + engineeringTicketId) + throw Object.assign(new Error('Synthetic current staff ticket outage AFTER accepted evidence'), { status: 503 }); + }; + await h.action('evidence'); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(true); + expect(h.node('withdraw').disabled).toBe(true); const posts = h.writes().length; const rows = await h.f.rows(); + h.state.fault = undefined; await h.action('retry-ticket'); + expect(h.writes()).toHaveLength(posts); expect(await h.f.rows()).toEqual(rows); + expect(h.panel.hasPending()).toBe(false); expect(h.node('withdraw').disabled).toBe(false); + expect(h.node('evidence').disabled).toBe(true); expect(h.node('invalidate').disabled).toBe(true); + expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('never settles unknown restricted evidence from a protected GET and replays its exact packet only explicitly', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); h.evidence('restricted'); + h.state.fault = async (path, response) => { + if (path.endsWith('/evidence') && response.ok) + throw Object.assign(new Error('Synthetic restricted evidence ACK loss AFTER SDK commit'), { status: 503 }); + }; + await h.action('evidence'); const original = h.writes().at(-1)?.body; const posts = h.writes().length; + expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); const rows = await h.f.rows(); + h.state.fault = undefined; await h.panel.refresh(); + expect(h.writes()).toHaveLength(posts); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); + expect(h.node('withdraw').disabled).toBe(true); expect(h.node('evidence').disabled).toBe(true); + await h.action('retry-ticket'); expect(h.writes().at(-1)?.body).toBe(original); + expect(h.state.ids).toBe(2); expect(await h.f.rows()).toEqual(rows); + expect(h.panel.hasPending()).toBe(false); expect(h.node('withdraw').disabled).toBe(false); + expect(h.node('evidence').disabled).toBe(true); expect(h.node('invalidate').disabled).toBe(true); + expect(h.f.engineering.state.creates).toEqual([]); + }); + + it('retains a known restricted evidence ACK when its closing actual session is destroyed during the protected GET', async () => { + const h = await harness(); await h.open(); await h.action('enroll'); h.evidence('restricted'); + h.state.fault = async (path, response) => { + if (path.endsWith('/engineering') && response.status === 403) await h.f.destroy('staff'); + }; + await h.action('evidence'); expect((await h.f.engineering.source()).state).toBe('restricted'); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(true); - const posts = h.writes().length; await h.action('retry-ticket'); - expect(h.writes()).toHaveLength(posts); expect(h.panel.hasPending()).toBe(true); - expect(h.node('evidence').disabled).toBe(true); expect(h.f.engineering.state.creates).toEqual([]); + expect(h.node('withdraw').disabled).toBe(true); expect(h.node('evidence').disabled).toBe(true); + expect(h.root.textContent).not.toContain(engineeringCanary); expect(h.f.engineering.state.creates).toEqual([]); }); it('retains owner A across A to peer B to A and never submits A under B credentials', async () => { diff --git a/src/support-engineering-review.test.ts b/src/support-engineering-review.test.ts index 122619f..b18d496 100644 --- a/src/support-engineering-review.test.ts +++ b/src/support-engineering-review.test.ts @@ -98,6 +98,8 @@ describe('checked human engineering review panel through real SDK and HTTP adapt expect(body.intent.command).toMatchObject({ decision: 'reject', proposalHash: h.checked.proposal?.proposalHash, expectedWorkGeneration: h.checked.workGeneration, sourceGeneration: h.checked.sourceGeneration }); expect((await h.f.work()).approval).toMatchObject({ decision: 'reject' }); + expect((await h.f.work()).status).toBe('held'); + expect(h.panel.hasPending()).toBe(false); expect(h.f.engineering.state.creates).toEqual([]); }); diff --git a/src/support-engineering-ui.test.ts b/src/support-engineering-ui.test.ts index fd8fde2..5c2174b 100644 --- a/src/support-engineering-ui.test.ts +++ b/src/support-engineering-ui.test.ts @@ -1,5 +1,6 @@ import { readFileSync } from 'node:fs'; import { runInNewContext } from 'node:vm'; +import { createDurableLimiter, defineRateLimitPolicy } from '@pegma/rate-limit'; import { describe, expect, it } from 'vitest'; import { authenticate } from '../worker/src/api-auth'; import { IDENTITY_ISSUER } from '../worker/src/identity-api'; @@ -17,9 +18,9 @@ async function harness() { const f = await createSupportEngineeringHttpFixture(); const ticket = await f.legacyTicket(); const support = createSupportApi({ ...f.options, application: f.engineering.application, createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); - const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string }[] = []; + const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string; serverStatus?: number; retryAfter?: string | null }[] = []; const changes: unknown[] = []; - const state = { actor: 'staff' as EngineeringHttpActor, enabled: true, ids: 0, sessionReads: 0, + const state = { actor: 'staff' as EngineeringHttpActor, enabled: true, ids: 0, sessionReads: 0, time: Date.now(), fault: undefined as ((path: string, response: Response) => Promise) | undefined }; function incoming(path: string, init: RequestInit = {}) { const headers = new Headers(init.headers); headers.set('Cookie', f.cookies.get(state.actor)!); @@ -27,15 +28,19 @@ async function harness() { return new Request(IDENTITY_ISSUER + path, { ...init, headers }); } async function request(path: string, init: RequestInit = {}) { - calls.push({ path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}) }); + const call = { path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}), + serverStatus: 0, retryAfter: null as string | null }; + calls.push(call); const request = incoming(path, init); const pathname = new URL(path, IDENTITY_ISSUER).pathname; const engineering = /^\/api\/support\/admin\/tickets\/[^/]+\/engineering(?:\/|$)/u.test(pathname) || /^\/api\/support\/admin\/engineering(?:\/|$)/u.test(pathname); const response = engineering ? await f.handle(request) : await support(request); if (response === null) throw new Error('Expected a registered adapter path'); + call.serverStatus = response.status; call.retryAfter = response.headers.get('Retry-After'); await state.fault?.(path, response); - if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status }); + if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status, + ...(response.status === 429 ? { retryAt: state.time + Number(call.retryAfter) * 1000 } : {}) }); return response.json(); } async function readSession() { @@ -50,7 +55,7 @@ async function harness() { const factory = vm.PegmaSupportEngineering as { createPanel(options: unknown): Panel }; const panel = factory.createPanel({ root, request, readSession, readCurrentTicket: (id: string) => request('/api/support/admin/tickets/' + encodeURIComponent(id)), - isEnabled: () => state.enabled, commandId: () => 'PUBLIC-ENGINEERING-UPPERCASE-' + ++state.ids, + isEnabled: () => state.enabled, now: () => state.time, commandId: () => 'PUBLIC-ENGINEERING-UPPERCASE-' + ++state.ids, onPendingChange: (owners: unknown) => changes.push(owners) }); function node(key: string, field = false) { const found = root.all().find((item) => item.dataset[field ? 'engineeringField' : 'engineeringAction'] === key); @@ -133,4 +138,28 @@ describe('standalone public engineering panel with actual authority adapters', ( expect(h.writes().at(-1)?.body).toBe(original); expect(h.panel.hasPending()).toBe(false); expect(JSON.stringify(h.changes)).not.toContain('commandId'); }); + + it('honors actual HTTP Retry-After without a premature probe and explicitly recovers the same packet when its deadline elapses', async () => { + const h = await harness(); await h.open(); + h.state.time = Math.ceil(h.state.time / 30_000) * 30_000; + const limiter = createDurableLimiter(defineRateLimitPolicy({ name: 'public-engineering-ui-retry', limit: 10, windowMs: 30_000 }), + h.f.engineering.store, { clock: { now: () => new Date(h.state.time).toISOString() } }); + Object.assign(h.f.options, { mutationLimiter: limiter }); + for (let index = 0; index < 10; index++) await limiter.allow(h.f.principals.staff); + const rows = await h.f.rows(); const ids = h.state.ids; + await h.action('enroll'); const original = h.writes().at(-1)!; + expect(original.serverStatus).toBe(429); expect(original.retryAfter).toBe('30'); + expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); expect(await h.f.rows()).toEqual(rows); + expect(h.node('retry-ticket').disabled).toBe(false); + const calls = h.calls.length; const sessions = h.state.sessionReads; const deadline = h.state.time + 30_000; + await h.action('retry-ticket'); h.state.time = deadline - 1; await h.action('retry-ticket'); + expect(h.calls).toHaveLength(calls); expect(h.state.sessionReads).toBe(sessions); + expect(h.state.ids).toBe(ids + 1); expect(h.panel.hasPending()).toBe(true); + h.state.time = deadline; + expect(h.calls).toHaveLength(calls); // Advancing time does not retry automatically. + await h.action('retry-ticket'); + expect(h.writes().at(-1)?.body).toBe(original.body); expect(h.writes().at(-1)?.serverStatus).toBe(200); + expect(h.state.ids).toBe(ids + 1); expect(h.panel.hasPending()).toBe(false); + expect(h.node('evidence').disabled).toBe(false); expect(h.f.engineering.state.creates).toEqual([]); + }); }); diff --git a/worker/README.md b/worker/README.md index 4343133..1201a59 100644 --- a/worker/README.md +++ b/worker/README.md @@ -216,10 +216,10 @@ Idle runs do not import an unused HMAC key; secret validation remains eager. A s `0-58 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup, email-operation repair, Mail retention, expired Sessions, each of the four Identity rate-limit policies, Support queue repair/inactive sweep, and each of -the four Support/Admin rate-limit policies, Knowledge maintenance and the -separately gated learning-review discovery lane. The 16 lanes rotate through +the six Support/Admin/engineering rate-limit policies, Knowledge maintenance and the +separately gated learning-review discovery lane. The 18 lanes rotate through eligible scheduled UTC ticks, including across hour boundaries, so each runs -every 16 ticks (a nominal 16-17 minutes because minute 59 is omitted). This gives cleanup its own invocation CPU budget instead of +every 18 ticks (a nominal 18-19 minutes because minute 59 is omitted). This gives cleanup its own invocation CPU budget instead of combining every task under the Workers Free 10 ms limit. Authentication and rate-limit checks still enforce expiry on access; cleanup only reclaims or repairs stored data. Paged Identity and Support cleanup also consumes at most @@ -247,7 +247,7 @@ public acknowledgement endpoint. ## Support Desk composition -Authenticated product feedback composes exact `0.2.5` versions of +Authenticated product feedback composes exact `0.2.6` versions of `@pegma/support-desk-contracts`, `@pegma/support-desk-core`, `@pegma/support-desk-application`, and `@pegma/support-desk-templates` over the same `IDENTITY_DB` D1 binding. Support Desk collections @@ -258,9 +258,9 @@ via AccessContext defaults (not a paid entitlement). Categories: `feedback`, `bug`, `feature_request`, `documentation`, `question`. Subject marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/ticket/?id=…`. -The optional `@pegma/support-desk-ai@0.2.5` package is installed for the +The optional `@pegma/support-desk-ai@0.2.6` package is installed for the [isolated scripted answering stage](../docs/SUPPORT_ASSISTANT_STAGE.md). The -normal public `0.2.5` graph passed the 1,125-test local/CI +earlier public `0.2.5` graph passed the 1,125-test local/CI [adoption checkpoint](../docs/KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint); review and deployment acceptance remain pending for the changed source. @@ -366,8 +366,8 @@ the Workers Free 10 ms allowance; they cannot guarantee an absolute CPU ceiling. One-record pages trade throughput for headroom: mail scans at most 60 send and 59 reconciliation operation records per hour, including retained terminal records. A full scan must remain comfortably shorter than the email-code lifetime; inspect scan -backlogs as usage grows. Cleanup pages advance once per lane every 16 eligible -ticks (a nominal 16-17 minutes). The published Sessions and rate-limit packages still expose +backlogs as usage grows. Cleanup pages advance once per lane every 18 eligible +ticks (a nominal 18-19 minutes). The published Sessions and rate-limit packages still expose whole-partition sweeps, so their work grows with partition size. Sustained backlogs need indexed discovery and paginated component APIs, or a larger CPU allowance. Reducing frequency alone does not raise the per-invocation limit. diff --git a/worker/src/index.ts b/worker/src/index.ts index 2f90875..d30ae2e 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -245,7 +245,7 @@ return { probe: 'disabled' | 'ok' | 'fail'; } = { storage: 'cloudflare-d1', - packages: '@pegma/support-desk-application@0.2.5', + packages: '@pegma/support-desk-application@0.2.6', probe: 'disabled', }; if (supportHealthProbeEnabled(env)) { diff --git a/worker/src/maintenance-cursors.d1.test.ts b/worker/src/maintenance-cursors.d1.test.ts index 8f2a162..cfbb01a 100644 --- a/worker/src/maintenance-cursors.d1.test.ts +++ b/worker/src/maintenance-cursors.d1.test.ts @@ -3,7 +3,7 @@ import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; import { createSessionStore } from '@pegma/sessions'; import { createDurableLimiter } from '@pegma/rate-limit-paged'; import { systemClock, type Logger } from '@pegma/spine'; -import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { runIdentityMaintenance, type IdentityMaintenanceRuntime, @@ -22,12 +22,20 @@ import { import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; import { cleanupLaneAt, + CLEANUP_LANE_COUNT, + CLEANUP_CRON, rateKnowledgeLaneAt, RATE_LIMIT_CRON, } from './maintenance-schedule'; import worker from './index'; const logger: Logger = { log: vi.fn() }; +let engineeringCleanupBudget: { limiterIndex: number; physicalCalls: number; + expiredWindowsSwept: number; otherPurposeWindowsRetained: number } | undefined; +afterEach(({ task }) => { + if (engineeringCleanupBudget !== undefined) + Object.assign(task.meta, { engineeringLimiterCleanupD1Budget: engineeringCleanupBudget }); +}); /** Semantically matches worker/migrations/0001_pegma_storage.sql. */ const SCHEMA_STATEMENTS = [ `CREATE TABLE IF NOT EXISTS RECORDS ( @@ -67,6 +75,7 @@ beforeAll(async () => { } }); beforeEach(async () => { + engineeringCleanupBudget = undefined; vi.clearAllMocks(); await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); @@ -184,6 +193,43 @@ function fixture() { } describe('maintenance cursor writes over D1', () => { + it.each([4, 5])('runs only engineering limiter %s through the real scheduled root within the physical D1 budget', async (limiterIndex) => { + const setup = createProductionSupportMaintenanceRuntime(env); + const expired = new Date(Date.now() - 2 * 60 * 60_000).toISOString(); + for (const index of [4, 5]) { + for (let subject = 0; subject < 24; subject += 1) + expect((await setup.limiters[index]!.allow('engineering-cleanup-staff-' + subject, expired)).allowed).toBe(true); + } + const count = () => env.IDENTITY_DB.prepare('SELECT COUNT(*) AS count FROM RECORDS WHERE deleted = 0').first('count'); + expect(await count()).toBe(48); + const metered = limitedD1(env.IDENTITY_DB); + const pending: Promise[] = []; + const secretRead = vi.fn(() => { throw new Error('Support rate cleanup must not initialize Identity.'); }); + const environment: Parameters[1] = { + ...env, IDENTITY_DB: metered.database, DATADOG_API_KEY: undefined, + PEGMA_KNOWLEDGE_ENABLED: 'false', PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: 'false', + get IDENTITY_EMAIL_CODE_SECRET_BASE64(): string { return secretRead(); }, + }; + const start = Math.floor(Date.now() / 60_000) * 60_000; + const scheduledTime = Array.from({ length: 120 }, (_, offset) => start + offset * 60_000).find((time) => { + const lane = cleanupLaneAt(time); + return new Date(time).getUTCMinutes() <= 58 && lane.kind === 'support' && + lane.task === 'rate_limits' && lane.limiterIndex === limiterIndex; + }); + if (scheduledTime === undefined) throw new Error('Expected the bounded exclusive engineering cleanup lane'); + worker.scheduled({ cron: CLEANUP_CRON, scheduledTime, noRetry() {} }, environment, + { waitUntil: (promise: Promise) => { pending.push(promise); }, + passThroughOnException() {}, props: {}, exports: {} } as ExecutionContext); + await Promise.all(pending); + expect(pending).toHaveLength(1); expect(secretRead).not.toHaveBeenCalled(); + expect(metered.calls()).toBeGreaterThan(0); expect(metered.calls()).toBeLessThanOrEqual(50); + // One complete purpose was swept; the other 24 genuine expired windows + // remain for their own physical invocation rather than sharing its budget. + expect(await count()).toBe(24); + engineeringCleanupBudget = { limiterIndex, physicalCalls: metered.calls(), + expiredWindowsSwept: 24, otherPurposeWindowsRetained: 24 }; + }); + it('runs two actual isolated scheduled pages within 50 D1 calls each and persists their continuation', async () => { const { store } = fixture(); const start = new Date(Date.now() - 180_000).toISOString(); @@ -380,7 +426,7 @@ describe('maintenance cursor writes over D1', () => { expect( createProductionSupportMaintenanceRuntime(env).limiters, ).toHaveLength(supportLimiters.length); - const lanes = Array.from({ length: 16 }, (_, index) => + const lanes = Array.from({ length: CLEANUP_LANE_COUNT }, (_, index) => cleanupLaneAt(Date.parse('2026-10-15T12:01:00Z') + index * 60_000), ); for (const [kind, limiters] of [ diff --git a/worker/src/maintenance-schedule.test.ts b/worker/src/maintenance-schedule.test.ts index 4fa7e3f..b572890 100644 --- a/worker/src/maintenance-schedule.test.ts +++ b/worker/src/maintenance-schedule.test.ts @@ -7,6 +7,7 @@ import { CLEANUP_CRON, RATE_LIMIT_CRON, cleanupLaneAt, + CLEANUP_LANE_COUNT, rateKnowledgeLaneAt, } from './maintenance-schedule'; import { @@ -47,13 +48,13 @@ vi.mock('./support-desk', () => ({ createProductionSupportMaintenanceRuntime: () => ({ store: {}, clock: {}, - limiters: [{}, {}, {}, {}], + limiters: [{}, {}, {}, {}, {}, {}], terminalRetentionMilliseconds: 1, }), createProductionSupportRuntime: () => ({ store: {}, clock: {}, - limiters: [{}, {}], + limiters: [{}, {}, {}, {}], terminalRetentionMilliseconds: 1, }), createAdminMutationLimiter: () => ({}), @@ -174,8 +175,8 @@ describe('maintenance dispatch', () => { observed.push(JSON.stringify(cleanupLaneAt(time))); } } - const cycle = observed.slice(0, 16); - expect(new Set(cycle).size).toBe(16); + const cycle = observed.slice(0, CLEANUP_LANE_COUNT); + expect(new Set(cycle).size).toBe(18); for (let index = 0; index < observed.length; index++) { expect(observed[index]).toBe(cycle[index % cycle.length]); } @@ -207,10 +208,10 @@ describe('maintenance dispatch', () => { expect(runReleaseReconciliation).not.toHaveBeenCalled(); }); - it('preserves all 16 cleanup lanes across a UTC day boundary without sharing the global rate job', async () => { + it('preserves all 18 cleanup lanes across a UTC day boundary without sharing the global rate job', async () => { const lanes = []; const start = Date.parse('2026-10-15T23:53:00Z'); - for (let minute = 0; minute < 17; minute++) { + for (let minute = 0; minute < CLEANUP_LANE_COUNT + 1; minute++) { const time = start + minute * 60_000; if (new Date(time).getUTCMinutes() === 59) continue; const lane = cleanupLaneAt(time); @@ -239,7 +240,7 @@ describe('maintenance dispatch', () => { } expect(runReleaseReconciliation).not.toHaveBeenCalled(); } - expect(new Set(lanes).size).toBe(16); + expect(new Set(lanes).size).toBe(18); expect( lanes.filter( (lane) => @@ -251,7 +252,7 @@ describe('maintenance dispatch', () => { ), ).toHaveLength(1); for (const kind of ['identity', 'support']) { - for (let limiterIndex = 0; limiterIndex < 4; limiterIndex++) { + for (let limiterIndex = 0; limiterIndex < (kind === 'support' ? 6 : 4); limiterIndex++) { expect(lanes).toContain( JSON.stringify({ kind, task: 'rate_limits', limiterIndex }), ); @@ -261,7 +262,7 @@ describe('maintenance dispatch', () => { it('leaves the learning dispatch lane port-free when trusted review composition is absent', async () => { const start = Date.parse('2026-10-15T00:00:00Z'); - const offset = Array.from({ length: 16 }, (_, minute) => minute).find( + const offset = Array.from({ length: CLEANUP_LANE_COUNT }, (_, minute) => minute).find( (minute) => cleanupLaneAt(start + minute * 60_000).kind === 'learning_reviews', ); if (offset === undefined) throw new Error('Expected the exclusive review dispatch lane'); @@ -323,7 +324,7 @@ describe('maintenance dispatch', () => { it('isolates a failed rate invocation from later identity and support cleanup invocations', async () => { const start = Date.parse('2026-10-15T00:00:00Z'); for (const kind of ['identity', 'support'] as const) { - const offset = Array.from({ length: 16 }, (_, minute) => minute).find( + const offset = Array.from({ length: CLEANUP_LANE_COUNT }, (_, minute) => minute).find( (minute) => cleanupLaneAt(start + minute * 60_000).kind === kind, ); if (offset === undefined) diff --git a/worker/src/maintenance-schedule.ts b/worker/src/maintenance-schedule.ts index 9793ef7..0187939 100644 --- a/worker/src/maintenance-schedule.ts +++ b/worker/src/maintenance-schedule.ts @@ -5,7 +5,7 @@ import type { SupportMaintenanceTask } from './support-maintenance'; export const MAIL_CRON = '* * * * *'; // Skip minute zero so every trigger has a distinct schedule. export const MAIL_RECONCILE_CRON = '1-59 * * * *'; -// Cleanup skips minute 59 and rotates through 16 exclusive small lanes. +// Cleanup skips minute 59 and rotates through 18 exclusive small lanes. export const CLEANUP_CRON = '0-58 * * * *'; // Two ticks clean rate windows, then one advances a ready KB hint. export const RATE_LIMIT_CRON = '0-57 * * * *'; @@ -39,7 +39,7 @@ const CLEANUP_LANES: readonly CleanupLane[] = [ })), { kind: 'support', task: 'queue_repair' }, { kind: 'support', task: 'queue_inactive_sweep' }, - ...[0, 1, 2, 3].map((limiterIndex) => ({ + ...[0, 1, 2, 3, 4, 5].map((limiterIndex) => ({ kind: 'support' as const, task: 'rate_limits' as const, limiterIndex, @@ -48,12 +48,15 @@ const CLEANUP_LANES: readonly CleanupLane[] = [ { kind: 'learning_reviews' }, ]; +/** Shared with optional compositions that alternate an exclusive cleanup lane. */ +export const CLEANUP_LANE_COUNT = CLEANUP_LANES.length; + /** Deterministic across cold starts, delayed delivery, and UTC hour boundaries. */ export function cleanupLaneAt(scheduledTime: number): CleanupLane { const minute = Math.floor(scheduledTime / 60_000); // Count only eligible minutes so skipping minute 59 never skips a lane. const tick = minute - Math.floor((minute + 1) / 60); - const length = CLEANUP_LANES.length; + const length = CLEANUP_LANE_COUNT; return CLEANUP_LANES[((tick % length) + length) % length]!; } diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index d766f06..c711ded 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -51,6 +51,10 @@ export const PEGMA_SUPPORT_CATEGORY_SET: ReadonlySet = new Set( /** Durable rate-limit policy names (separate from Identity). */ export const SUPPORT_CREATE_LIMIT_POLICY = 'pegma.support.ticket.create'; export const SUPPORT_REPLY_LIMIT_POLICY = 'pegma.support.ticket.reply'; +export const SUPPORT_ENGINEERING_READ_LIMIT_POLICY = 'pegma.support.engineering.read'; +export const SUPPORT_ENGINEERING_MUTATION_LIMIT_POLICY = 'pegma.support.engineering.mutate'; +export const SUPPORT_ENGINEERING_READ_LIMIT = 120; +export const SUPPORT_ENGINEERING_MUTATION_LIMIT = 30; export const SUPPORT_TERMINAL_RETENTION_MS = defaultQueueTerminalRetentionMilliseconds; @@ -182,6 +186,8 @@ export interface SupportCompositionOptions { readonly clock?: Clock; readonly createLimiter?: DurableRateLimiter; readonly replyLimiter?: DurableRateLimiter; + readonly engineeringReadLimiter?: DurableRateLimiter; + readonly engineeringMutationLimiter?: DurableRateLimiter; readonly resolutionLearning?: ResolutionLearningOptions; readonly engineering?: EngineeringOptions; } @@ -195,6 +201,8 @@ export interface SupportRuntime { readonly clock: Clock; readonly createLimiter: DurableRateLimiter; readonly replyLimiter: DurableRateLimiter; + readonly engineeringReadLimiter: DurableRateLimiter; + readonly engineeringMutationLimiter: DurableRateLimiter; readonly limiters: readonly DurableRateLimiter[]; readonly terminalRetentionMilliseconds: number; readonly sessions: SessionStore; @@ -267,6 +275,20 @@ function createSupportLimiters(store: Store, clock: Clock) { 60 * 60_000, clock, ), + engineeringReadLimiter: durableLimiter( + store, + SUPPORT_ENGINEERING_READ_LIMIT_POLICY, + SUPPORT_ENGINEERING_READ_LIMIT, + 60 * 60_000, + clock, + ), + engineeringMutationLimiter: durableLimiter( + store, + SUPPORT_ENGINEERING_MUTATION_LIMIT_POLICY, + SUPPORT_ENGINEERING_MUTATION_LIMIT, + 60 * 60_000, + clock, + ), }; } @@ -279,7 +301,7 @@ export function createProductionSupportMaintenanceRuntime( createSchemaIfMissing: false, }); const clock = systemClock; - const { createLimiter, replyLimiter } = createSupportLimiters(store, clock); + const { createLimiter, replyLimiter, engineeringReadLimiter, engineeringMutationLimiter } = createSupportLimiters(store, clock); return { store, clock, @@ -289,6 +311,8 @@ export function createProductionSupportMaintenanceRuntime( replyLimiter, createAdminMutationLimiter(store, clock), createAdminLookupLimiter(store, clock), + engineeringReadLimiter, + engineeringMutationLimiter, ], }; } @@ -320,6 +344,8 @@ export function createSupportRuntime( const defaults = createSupportLimiters(store, clock); const createLimiter = options.createLimiter ?? defaults.createLimiter; const replyLimiter = options.replyLimiter ?? defaults.replyLimiter; + const engineeringReadLimiter = options.engineeringReadLimiter ?? defaults.engineeringReadLimiter; + const engineeringMutationLimiter = options.engineeringMutationLimiter ?? defaults.engineeringMutationLimiter; const application = createSupportDeskApplication({ store, @@ -343,7 +369,9 @@ export function createSupportRuntime( clock, createLimiter, replyLimiter, - limiters: Object.freeze([createLimiter, replyLimiter]), + engineeringReadLimiter, + engineeringMutationLimiter, + limiters: Object.freeze([createLimiter, replyLimiter, engineeringReadLimiter, engineeringMutationLimiter]), terminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, sessions: options.sessions, identity: options.identity, diff --git a/worker/src/support-engineering-composition.test.ts b/worker/src/support-engineering-composition.test.ts index 845a545..4256f3e 100644 --- a/worker/src/support-engineering-composition.test.ts +++ b/worker/src/support-engineering-composition.test.ts @@ -1,13 +1,15 @@ import { describe, expect, it } from 'vitest'; +import type { Clock } from '@pegma/spine'; import { createSupportApi } from './support-api'; -import { createSupportRuntime } from './support-desk'; +import { createSupportRuntime, SUPPORT_ENGINEERING_READ_LIMIT, + SUPPORT_ENGINEERING_MUTATION_LIMIT } from './support-desk'; import { SUPPORT_ROLE } from './support-access'; import { createWorker, createSupportRequestHandler } from './index'; import { composeSupportEngineeringHuman, supportEngineeringIntakeOptions } from './support-engineering-composition'; import { createSupportEngineeringHttpFixture, engineeringHttpObject, engineeringHttpResult } from './support-engineering-http-fixtures'; import { engineeringTicketId } from './support-engineering-fixtures'; -async function fixture() { +async function fixture(clock?: Clock) { const f = await createSupportEngineeringHttpFixture(); const ticket = await f.legacyTicket(); const state = { enabled: true }; const human = { enabled: () => state.enabled, configuration: { application: { enabled: true }, repositories: f.options.repositories } }; @@ -15,7 +17,7 @@ async function fixture() { if (intake === undefined) throw new Error('Expected explicit synthetic human intake configuration'); const runtime = createSupportRuntime({ store: f.host.store, identity: f.identity, sessions: f.sessions, identityLinkFromClaims: f.options.identityLinkFromClaims, logger: f.options.logger, - engineering: intake }); + engineering: intake, ...(clock === undefined ? {} : { clock }) }); const engineering = composeSupportEngineeringHuman(runtime, f.options.logger, human); const api = createSupportApi({ ...f.options, application: runtime.application, roleStore: runtime.roleStore, createLimiter: runtime.createLimiter, replyLimiter: runtime.replyLimiter, engineering }); @@ -61,6 +63,60 @@ describe('optional public engineering root composition', () => { expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); }); + it('keeps engineering reads and enrollment available after the ordinary reply quota is exhausted', async () => { + const { f, ticket, runtime, api } = await fixture(); + for (let index = 0; index < 30; index += 1) + expect((await runtime.replyLimiter.allow(f.principals.staff)).allowed).toBe(true); + expect((await runtime.replyLimiter.allow(f.principals.staff)).allowed).toBe(false); + expect((await api(f.request())).status).toBe(404); + expect((await api(f.request('enroll', { commandId: 'SEPARATE-ENGINEERING-ENROLL', + expectedRevision: ticket.revision }))).status).toBe(200); + }); + + it('keeps ordinary replies and engineering writes independent of repeated engineering reads', async () => { + const { f, ticket, runtime, api } = await fixture(); + for (let index = 0; index < 31; index += 1) + expect((await api(f.request())).status).toBe(404); + expect((await runtime.replyLimiter.allow(f.principals.staff)).allowed).toBe(true); + expect((await api(f.request('enroll', { commandId: 'READS-DO-NOT-SPEND-WRITES', + expectedRevision: ticket.revision }))).status).toBe(200); + }); + + it('retains dedicated read exhaustion across cold compositions, returns real Retry-After and restores access after expiry', async () => { + let milliseconds = Date.now(); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const { f, ticket, human, runtime, api } = await fixture(clock); + for (let index = 0; index < SUPPORT_ENGINEERING_READ_LIMIT; index += 1) + expect((await runtime.engineeringReadLimiter.allow(f.principals.staff)).allowed).toBe(true); + const denied = await api(f.request()); expect(denied.status).toBe(429); + expect(Number(denied.headers.get('Retry-After'))).toBeGreaterThan(0); + expect(Number(denied.headers.get('Retry-After'))).toBeLessThanOrEqual(3600); + const restarted = createSupportRuntime({ store: runtime.store, identity: runtime.identity, + sessions: runtime.sessions, identityLinkFromClaims: runtime.identityLinkFromClaims, + logger: f.options.logger, clock, engineering: supportEngineeringIntakeOptions(human) }); + const current = createSupportApi({ ...f.options, application: restarted.application, + createLimiter: restarted.createLimiter, replyLimiter: restarted.replyLimiter, + engineering: composeSupportEngineeringHuman(restarted, f.options.logger, human) }); + expect((await current(f.request())).status).toBe(429); + expect((await current(f.request('enroll', { commandId: 'READ-QUOTA-DOES-NOT-BLOCK-WITHDRAWAL-INTAKE', + expectedRevision: ticket.revision }))).status).toBe(200); + expect((await restarted.replyLimiter.allow(f.principals.staff)).allowed).toBe(true); + milliseconds += 60 * 60_000 + 1; + // The actual source is protected. Expiry restores its real authorization + // result; a limiter success must never fabricate source-read permission. + expect((await current(f.request())).status).toBe(403); + }); + + it('exhausts engineering writes independently while reads and ordinary replies remain available', async () => { + const { f, ticket, runtime, api } = await fixture(); + for (let index = 0; index < SUPPORT_ENGINEERING_MUTATION_LIMIT; index += 1) + expect((await runtime.engineeringMutationLimiter.allow(f.principals.staff)).allowed).toBe(true); + const denied = await api(f.request('enroll', { commandId: 'ACTUAL-WRITE-QUOTA-DENIAL', expectedRevision: ticket.revision })); + expect(denied.status).toBe(429); expect(Number(denied.headers.get('Retry-After'))).toBeGreaterThan(0); + expect((await api(f.request())).status).toBe(404); + expect((await runtime.replyLimiter.allow(f.principals.staff)).allowed).toBe(true); + }); + it('computes capability from fresh real staff authority and retains both independent defaults', async () => { const { f, state, api } = await fixture(); const detail = () => api(new Request('https://pegma.dev/api/support/admin/tickets/' + engineeringTicketId, diff --git a/worker/src/support-engineering-composition.ts b/worker/src/support-engineering-composition.ts index f2fb934..78d8932 100644 --- a/worker/src/support-engineering-composition.ts +++ b/worker/src/support-engineering-composition.ts @@ -36,7 +36,8 @@ export function composeSupportEngineeringHuman(runtime: SupportRuntime, logger: identityLinkFromClaims: runtime.identityLinkFromClaims, roleStore: runtime.roleStore, logger }; const resolve = createAgentPrincipalResolver(authority); return { enabled: () => supportEngineeringHumanEnabled(options), configuration: { - ...authority, limiter: runtime.replyLimiter, repositories: options.configuration!.repositories, + ...authority, readLimiter: runtime.engineeringReadLimiter, + mutationLimiter: runtime.engineeringMutationLimiter, repositories: options.configuration!.repositories, reviewEnabled: () => { try { return options.reviewEnabled?.() === true; } catch { return false; } }, runtime: () => createSupportEngineeringRuntime({ application: runtime.application, clock: runtime.clock, staffAccess: { resolve }, processingEnabled: () => false, diff --git a/worker/src/support-engineering-handlers.test.ts b/worker/src/support-engineering-handlers.test.ts index 996d091..eb13443 100644 --- a/worker/src/support-engineering-handlers.test.ts +++ b/worker/src/support-engineering-handlers.test.ts @@ -6,6 +6,7 @@ import { ADMIN_ROLE, APPLICATION_SCOPE, SUPPORT_ROLE } from './support-access'; import { controlledHumanBody } from './support-human-control-fixtures'; import { engineeringCanary, engineeringProofReference, engineeringRepositories, engineeringTicketId } from './support-engineering-fixtures'; import { createSupportEngineeringHandlers } from './support-engineering-handlers'; +import { createSupportEngineeringRuntime } from './support-engineering'; import { createSupportEngineeringHttpFixture, engineeringHttpCommand, engineeringHttpNumber, engineeringHttpObject, engineeringHttpResult, engineeringHttpRoute, @@ -16,6 +17,23 @@ const object = engineeringHttpObject; const result = engineeringHttpResult; const number = engineeringHttpNumber; +function selectionPacket(work: Record, key: string) { + const selected = work.selection; + if (!isPlainObject(selected) || !Array.isArray(selected.repositoryChoices)) + throw new Error('Expected actual immutable repository choices'); + const choice: unknown = selected.repositoryChoices.find((value: unknown) => isPlainObject(value) && value.key === key); + if (!isPlainObject(choice)) throw new Error('Expected the configured choice'); + return { repositoryKey: choice.key, repositoryId: choice.repositoryId, + repositoryDescriptorHash: choice.descriptorHash, + policyGeneration: selected.policyGeneration, policyHash: selected.policyHash }; +} + +function useApplication(f: Awaited>, application: typeof f.engineering.application) { + f.state.runtime = createSupportEngineeringRuntime({ application, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, ports: f.engineering.ports, + processingEnabled: () => false }); +} + function firstIntentRepository(packet: { intent: Record }) { const policy = packet.intent.policy; if (!isPlainObject(policy) || !Array.isArray(policy.repositories)) throw new Error('Expected prepared full policy'); @@ -66,8 +84,8 @@ describe('unregistered engineering HTTP through current real host authority', () it('enrolls and records an actual verified failure with exact uppercase command replay', async () => { const f = await fixture(); const original = f.state.runtime; - f.state.runtime = { ...original, async enroll(access, packet) { - f.state.captured.push(packet.clientCommandId); return original.enroll(access, packet); + f.state.runtime = { ...original, async enroll(...args: Parameters) { + f.state.captured.push(args[1].clientCommandId); return original.enroll(...args); } }; const ticket = await f.engineering.createTicket(); const packet = { commandId: engineeringHttpCommand, expectedRevision: ticket.revision }; @@ -157,11 +175,8 @@ describe('unregistered engineering HTTP through current real host authority', () expect((await f.process()).outcome).toBe('candidate'); const response = await f.send(f.request('work', undefined, 'staff', '?sourceGeneration=' + accepted.key.sourceGeneration)); const view = result(await object(response)); - if (typeof view.selection !== 'object' || view.selection === null || !('policyGeneration' in view.selection) || - !('policyHash' in view.selection)) throw new Error('Missing actual selection policy fences'); const packet = { commandId: 'SELECT-EXACT', sourceGeneration: accepted.key.sourceGeneration, - expectedWorkGeneration: number(view.workGeneration), repositoryKey: engineeringRepositories[1]!.repositoryId, - policyGeneration: view.selection.policyGeneration, policyHash: view.selection.policyHash, + expectedWorkGeneration: number(view.workGeneration), ...selectionPacket(view, engineeringRepositories[1]!.repositoryId), reason: 'Select the allowlisted download API.' }; const first = await object(await f.send(f.request('repository', packet))); expect(result(first).status).toBe('candidate'); @@ -175,14 +190,16 @@ describe('unregistered engineering HTTP through current real host authority', () it('rejects arbitrary repository URLs or identities before changing a work target', async () => { const f = await fixture(); const accepted = await f.verified(); expect((await f.process()).outcome).toBe('candidate'); - const work = await f.work(); const policy = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); const before = await f.rows(); + const work = await f.work(); const before = await f.rows(); + const view = result(await object(await f.send(f.request('work', undefined, 'staff', '?sourceGeneration=' + accepted.key.sourceGeneration)))); const packet = { commandId: 'UNKNOWN-REPOSITORY', sourceGeneration: accepted.key.sourceGeneration, - expectedWorkGeneration: work.workGeneration, repositoryKey: 'https://foreign.example/repository', - policyGeneration: policy.generation, policyHash: policy.policyHash, reason: 'Unapproved destination.' }; - expect((await f.send(f.request('repository', packet))).status).toBe(400); + expectedWorkGeneration: work.workGeneration, ...selectionPacket(view, engineeringRepositories[0]!.repositoryId), + repositoryKey: 'https://foreign.example/repository', reason: 'Unapproved destination.' }; + expect((await f.send(f.request('repository', packet))).status).toBe(409); expect(await f.rows()).toEqual(before); }); + it('uses declarative server-only policy descriptors and replays independently of live metadata availability', async () => { const f = await fixture(); const policy = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); const packet = { commandId: 'POLICY-EXACT-HTTP', expectedGeneration: policy.generation, enabled: true, @@ -253,8 +270,8 @@ describe('unregistered engineering HTTP through current real host authority', () enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); const original = f.state.runtime; let lose = true; let accepted: Awaited> | undefined; - f.state.runtime = { ...original, async putPolicy(access, packet, binding) { - const value = await original.putPolicy(access, packet, binding); accepted = value; + f.state.runtime = { ...original, async putPolicy(...args: Parameters) { + const value = await original.putPolicy(...args); accepted = value; if (lose) { lose = false; throw new Error('Synthetic committed policy ACK loss'); } return value; } }; expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(503); @@ -335,20 +352,22 @@ describe('unregistered engineering HTTP through current real host authority', () expect(await f.policyRows()).toEqual(before); }); - it('lets the actual SDK CAS reject a head advance after the fresh-catalog observation', async () => { + it('lets the actual SDK CAS reject a head advance after the actual late catalog guard', async () => { const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'CAS-INTENT-EXACT', expectedGeneration: 1, enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); - const original = f.state.runtime; let advanced = false; + const application = f.engineering.application; let advanced = false; let racedRows: Awaited> | undefined; - f.state.runtime = { ...original, async readPolicy(access) { - const observed = await original.readPolicy(access); - if (!advanced) { - advanced = true; - await f.engineering.runtime.disableExports(f.engineering.actors.admin, { clientCommandId: 'CAS-COMPETITOR', expectedGeneration: observed.generation }); - racedRows = await f.policyRows(); - } - return observed; - } }; + useApplication(f, { ...application, putRepositoryPolicy: (access, command, control) => + application.putRepositoryPolicy(access, command, { ...control, verifyBeforeCommit: async () => { + const assertion = await control?.verifyBeforeCommit?.(); + if (!advanced) { + advanced = true; + await f.engineering.runtime.disableExports(f.engineering.actors.admin, + { clientCommandId: 'CAS-COMPETITOR', expectedGeneration: command.expectedGeneration }); + racedRows = await f.policyRows(); + } + return assertion; + } }) }); expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(409); expect(advanced).toBe(true); expect(await f.policyRows()).toEqual(racedRows); }); @@ -495,26 +514,26 @@ describe('unregistered engineering HTTP through current real host authority', () it('rechecks current authority after the real limiter before beginning the protected body/SDK operation', async () => { const f = await fixture(); const ticket = await f.legacyTicket(); const before = await f.rows(); let revoked = false; - const limiter = { ...f.options.limiter, async allow(...args: Parameters) { - const decision = await f.options.limiter.allow(...args); + const mutationLimiter = { ...f.options.mutationLimiter, async allow(...args: Parameters) { + const decision = await f.options.mutationLimiter.allow(...args); if (!revoked) { revoked = true; await f.revoke('staff', SUPPORT_ROLE); } return decision; } }; - const handle = createSupportEngineeringHandlers({ ...f.options, limiter }); + const handle = createSupportEngineeringHandlers({ ...f.options, mutationLimiter }); const response = await handle(f.request('enroll', { commandId: 'LIMITER-HANDOFF-EXACT', expectedRevision: ticket.revision })); expect(response?.status).toBe(403); expect(revoked).toBe(true); expect(await f.rows()).toEqual(before); expect(f.state.runtimeCalls).toBe(0); }); - it.each([ADMIN_ROLE, SUPPORT_ROLE])('rechecks %s after an actual policy head read before any policy write', async (role) => { + it.each([ADMIN_ROLE, SUPPORT_ROLE])('rechecks %s at the actual policy commit callback after its head read', async (role) => { const f = await fixture(); const retained = await f.preparePolicy({ commandId: 'HEAD-AUTH-HANDOFF', expectedGeneration: 1, enabled: true, repositoryKeys: [engineeringRepositories[0]!.repositoryId] }); - const original = f.state.runtime; let revoked = false; const before = await f.policyRows(); - f.state.runtime = { ...original, async readPolicy(access) { - const head = await original.readPolicy(access); - if (!revoked) { revoked = true; await f.revoke('both', role); } - return head; - } }; + const application = f.engineering.application; let revoked = false; const before = await f.policyRows(); + useApplication(f, { ...application, putRepositoryPolicy: (access, command, control) => + application.putRepositoryPolicy(access, command, { ...control, verifyBeforeCommit: async () => { + if (!revoked) { revoked = true; await f.revoke('both', role); } + return control?.verifyBeforeCommit?.(); + } }) }); expect((await f.send(f.request('policy', retained, 'both'))).status).toBe(403); expect(revoked).toBe(true); expect(await f.policyRows()).toEqual(before); }); @@ -574,8 +593,8 @@ describe('unregistered engineering HTTP through current real host authority', () it('recovers the exact SDK enrollment receipt after a synthetic post-commit response loss', async () => { const f = await fixture(); const ticket = await f.engineering.createTicket(); const original = f.state.runtime; let lose = true; - f.state.runtime = { ...original, async enroll(access, packet) { - const value = await original.enroll(access, packet); if (lose) { lose = false; throw new Error('Synthetic response loss'); } return value; + f.state.runtime = { ...original, async enroll(...args: Parameters) { + const value = await original.enroll(...args); if (lose) { lose = false; throw new Error('Synthetic response loss'); } return value; } }; const packet = { commandId: 'LOST-ACK-EXACT', expectedRevision: ticket.revision }; expect((await f.send(f.request('enroll', packet))).status).toBe(503); const rows = await f.rows(); @@ -601,8 +620,8 @@ describe('unregistered engineering HTTP through current real host authority', () expect(f.engineering.state.modelCalls).toBe(0); }); - it('shares the existing durable limiter and returns its Retry-After without a private factory call', async () => { - const f = await fixture(); for (let index = 0; index < 30; index += 1) await f.host.replyLimiter.allow(f.principals.staff); + it('returns the dedicated durable read quota Retry-After without a private factory call', async () => { + const f = await fixture(); for (let index = 0; index < 120; index += 1) await f.host.engineeringReadLimiter.allow(f.principals.staff); const response = await f.send(f.request()); expect(response.status).toBe(429); expect(Number(response.headers.get('Retry-After'))).toBeGreaterThan(0); expect(await object(response)).toEqual({ error: 'rate_limited' }); expect(f.state.runtimeCalls).toBe(0); diff --git a/worker/src/support-engineering-handlers.ts b/worker/src/support-engineering-handlers.ts index 72b0ce6..d51b621 100644 --- a/worker/src/support-engineering-handlers.ts +++ b/worker/src/support-engineering-handlers.ts @@ -74,7 +74,7 @@ function policyIntent(raw: unknown): EngineeringPolicyIntent { return intent; } -async function intentFingerprint(intent: EngineeringPolicyIntent): Promise { +async function intentFingerprint(intent: unknown): Promise { const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(intent))); return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); } @@ -85,7 +85,8 @@ export interface SupportEngineeringHandlerOptions extends AgentBrowserOptions { /** Separate current human review gate, with strict false as the default. */ readonly reviewEnabled?: () => boolean; readonly runtime: () => SupportEngineeringRuntime; - readonly limiter: DurableRateLimiter; + readonly readLimiter: DurableRateLimiter; + readonly mutationLimiter: DurableRateLimiter; readonly repositories?: readonly EngineeringHttpRepository[]; } @@ -252,7 +253,7 @@ export function createSupportEngineeringHandlers(options: SupportEngineeringHand if (url.hash !== '' || (!['work', 'proposal'].includes(operation) && url.search !== '')) throw new ApiError(400, 'invalid_request'); const initial = await current(); const principalId = initial.access.principalId; - await enforceRateLimit(options.limiter, principalId); + await enforceRateLimit(mutation ? options.mutationLimiter : options.readLimiter, principalId); let result: unknown; if (operation === 'policy_read') { const value = await awaited((access) => options.runtime().readPolicy(access)); @@ -282,10 +283,17 @@ export function createSupportEngineeringHandlers(options: SupportEngineeringHand const choice = hasPermission(actor.access, supportPermissions.engineeringReview) && hasPermission(actor.access, supportPermissions.engineeringPolicyRead) ? await awaited((access) => options.runtime().readPolicy(access)) : null; + const repositoryChoices = choice === null ? [] : await Promise.all(configured.flatMap((entry) => { + const allowed = choice.policy.repositories.find((descriptor) => descriptor.repositoryId === entry.descriptor.repositoryId); + if (!entry.descriptor.enabled || allowed?.enabled !== true) return []; + const declared = normalizedPolicy({ enabled: true, repositories: [entry.descriptor] }).repositories[0]!; + if (JSON.stringify(declared) !== JSON.stringify(allowed)) return []; + return [intentFingerprint(declared).then((descriptorHash) => ({ key: entry.key, + repositoryId: entry.descriptor.repositoryId, descriptorHash }))]; + })); result = { ...workDto(work), ...(choice === null ? {} : { selection: { policyGeneration: choice.generation, policyHash: choice.policyHash, - repositoryKeys: configured.filter((entry) => choice.policy.repositories.some((allowed) => - allowed.repositoryId === entry.descriptor.repositoryId && allowed.enabled)).map((entry) => entry.key), + repositoryKeys: repositoryChoices.map((entry) => entry.key), repositoryChoices, } }) }; } else { const body = await awaited(() => readJson(request, { timeoutMs: 10_000, @@ -306,31 +314,28 @@ export function createSupportEngineeringHandlers(options: SupportEngineeringHand const packet = exactObject(body, ['intent']); const intent = policyIntent(packet.intent); // Identity equality only: never reuse admission roles/permissions. - // The immediately following head read performs fresh browser auth. + // The following protected SDK call performs fresh browser auth. if (intent.actorId !== principalId) throw new ApiError(403, 'forbidden'); - const currentPolicy = await awaited((access) => options.runtime().readPolicy(access)); - if (currentPolicy.generation < intent.expectedGeneration) throw new ApiError(409, 'policy_changed'); - if (currentPolicy.generation === intent.expectedGeneration) { - const currentPolicyPacket = normalizedPolicy({ enabled: intent.policy.enabled, - repositories: intent.repositoryKeys.map((key) => repository(key).descriptor) }); - if (JSON.stringify(currentPolicyPacket) !== JSON.stringify(intent.policy)) - throw new ApiError(409, 'policy_intent_changed'); - } - // A monotonic newer head makes this receipt-only: the public SDK - // replays an exact receipt before CAS; no missing/pruned receipt can - // write under the stale generation. Never reconstruct old snapshots - // from a changed/removed catalog or add a mutable metadata gate. - // Local hashing carries no authority; the write refreshes after it. + // Immutable validation and hashing precede the public SDK receipt. + // Only a NEW command reaches the actual026 catalog/browser guard. const binding = await intentFingerprint(intent); const value = await awaited((access) => options.runtime().putPolicy(access, { clientCommandId: intent.commandId, expectedGeneration: intent.expectedGeneration, policy: intent.policy, - }, binding)); + }, binding, async () => { + let declared: EngineeringRepositoryPolicy; + try { declared = normalizedPolicy({ enabled: intent.policy.enabled, + repositories: intent.repositoryKeys.map((key) => repository(key).descriptor) }); } + catch { throw new ApiError(409, 'policy_intent_changed'); } + if (JSON.stringify(declared) !== JSON.stringify(intent.policy)) + throw new ApiError(409, 'policy_intent_changed'); + return (await current()).access; + })); result = { generation: value.generation, policyHash: value.policyHash, enabled: value.enabled }; } else if (operation === 'policy_disable') { const packet = exactObject(body, ['commandId', 'expectedGeneration']); const value = await awaited((access) => options.runtime().disableExports(access, { clientCommandId: boundedString(packet.commandId, 1, 200), expectedGeneration: integer(packet.expectedGeneration, 0), - })); + }, async () => (await current()).access)); result = { generation: value.generation, policyHash: value.policyHash, enabled: value.enabled }; } else { if (ticketId === undefined) throw new ApiError(400, 'invalid_request'); @@ -345,7 +350,8 @@ export function createSupportEngineeringHandlers(options: SupportEngineeringHand } else if (operation === 'enroll') { const packet = exactObject(body, ['commandId', 'expectedRevision']); result = sourceResultDto(await awaited((access) => options.runtime().enroll(access, { ticketId, - clientCommandId: boundedString(packet.commandId, 1, 200), expectedRevision: integer(packet.expectedRevision) }))); + clientCommandId: boundedString(packet.commandId, 1, 200), expectedRevision: integer(packet.expectedRevision) }, + async () => (await current()).access))); } else if (operation === 'evidence') { const packet = exactObject(body, ['commandId', 'expectedRevision', 'expectedBehavior', 'actualBehavior', 'reproductionSteps', 'visibleMessageIds', 'verificationReference', 'security']); @@ -359,30 +365,46 @@ export function createSupportEngineeringHandlers(options: SupportEngineeringHand reproductionSteps: strings(packet.reproductionSteps, 16, 1_000, true), visibleMessageIds: strings(packet.visibleMessageIds, 16, 200), verificationReference: boundedString(packet.verificationReference, 1, 200) } }; - result = sourceResultDto(await awaited((access) => options.runtime().submitVerifiedFailure(access, input))); + result = sourceResultDto(await awaited((access) => options.runtime().submitVerifiedFailure(access, input, + async () => (await current()).access))); } else if (operation === 'repository') { const packet = exactObject(body, ['commandId', 'sourceGeneration', 'expectedWorkGeneration', - 'repositoryKey', 'policyGeneration', 'policyHash', 'reason']); - const selected = repository(packet.repositoryKey); - result = stepDto(await awaited((access) => options.runtime().selectRepository(access, { ticketId, + 'repositoryKey', 'repositoryId', 'repositoryDescriptorHash', 'policyGeneration', 'policyHash', 'reason']); + const repositoryKey = boundedString(packet.repositoryKey, 1, 100); + const repositoryDescriptorHash = fingerprint(packet.repositoryDescriptorHash); + const input = { ticketId, clientCommandId: boundedString(packet.commandId, 1, 200), sourceGeneration: integer(packet.sourceGeneration), - expectedWorkGeneration: integer(packet.expectedWorkGeneration), repositoryId: selected.descriptor.repositoryId, + expectedWorkGeneration: integer(packet.expectedWorkGeneration), repositoryId: boundedString(packet.repositoryId, 1, 200), policyGeneration: integer(packet.policyGeneration, 0), policyHash: fingerprint(packet.policyHash), - reason: boundedString(packet.reason, 1, 200) }))); + reason: boundedString(packet.reason, 1, 200) }; + const binding = await intentFingerprint({ actorId: principalId, repositoryKey, repositoryDescriptorHash, input }); + result = stepDto(await awaited((access) => options.runtime().selectRepository(access, input, { + intentFingerprint: binding, beforeCommit: async () => { + const entry = configured.find((candidate) => candidate.key === repositoryKey); + if (entry === undefined || !entry.descriptor.enabled || entry.descriptor.repositoryId !== input.repositoryId) + throw new ApiError(409, 'engineering_selection_changed'); + const declared = normalizedPolicy({ enabled: true, repositories: [entry.descriptor] }).repositories[0]!; + if (await intentFingerprint(declared) !== repositoryDescriptorHash) + throw new ApiError(409, 'engineering_selection_changed'); + // SDK policy generation/hash checks have already followed its + // receipt lookup. This final browser read follows local hashing. + return (await current()).access; + }, + }))); } else if (operation === 'invalidate') { const packet = exactObject(body, ['commandId', 'reason']); if (packet.reason !== 'evidence_revoked' && packet.reason !== 'product_binding_revoked' && packet.reason !== 'check_policy_revoked') throw new ApiError(400, 'invalid_request'); const reason = packet.reason; result = sourceResultDto(await awaited((access) => options.runtime().invalidate(access, { ticketId, - clientCommandId: boundedString(packet.commandId, 1, 200), reason }))); + clientCommandId: boundedString(packet.commandId, 1, 200), reason }, async () => (await current()).access))); } else { const packet = exactObject(body, ['commandId', 'reason']); if (packet.reason !== 'privacy_withdrawal' && packet.reason !== 'source_access_revoked' && packet.reason !== 'source_deleted') throw new ApiError(400, 'invalid_request'); const reason = packet.reason; result = sourceResultDto(await awaited((access) => options.runtime().withdraw(access, { ticketId, - clientCommandId: boundedString(packet.commandId, 1, 200), reason }))); + clientCommandId: boundedString(packet.commandId, 1, 200), reason }, async () => (await current()).access))); } } } diff --git a/worker/src/support-engineering-http-fixtures.ts b/worker/src/support-engineering-http-fixtures.ts index 8583ad6..f8a5e86 100644 --- a/worker/src/support-engineering-http-fixtures.ts +++ b/worker/src/support-engineering-http-fixtures.ts @@ -83,7 +83,8 @@ export async function createSupportEngineeringHttpFixture(backing: Store = creat ports: engineering.ports, staffAccess: { resolve: (principalId) => resolve(principalId) }, processingEnabled: () => engineering.state.enabled }); const state = { enabled: true, runtimeCalls: 0, runtime, captured: [] as string[] }; - const options = { ...authority, enabled: () => state.enabled, limiter: host.replyLimiter, + const options = { ...authority, enabled: () => state.enabled, + readLimiter: host.engineeringReadLimiter, mutationLimiter: host.engineeringMutationLimiter, runtime: () => { state.runtimeCalls += 1; return state.runtime; }, repositories: engineeringRepositories.map((descriptor) => ({ key: descriptor.repositoryId, descriptor })) }; const handle = createSupportEngineeringHandlers(options); diff --git a/worker/src/support-engineering-http.d1.test.ts b/worker/src/support-engineering-http.d1.test.ts index 7243735..8991a33 100644 --- a/worker/src/support-engineering-http.d1.test.ts +++ b/worker/src/support-engineering-http.d1.test.ts @@ -14,7 +14,7 @@ import { createSupportApi } from './support-api'; import { engineeringCanary, engineeringProofReference, engineeringRepositories } from './support-engineering-fixtures'; import { createSupportEngineeringHttpFixture, engineeringHttpCommand, - engineeringHttpObject, engineeringHttpResult, engineeringHttpRoute, + engineeringHttpNumber, engineeringHttpObject, engineeringHttpResult, engineeringHttpRoute, } from './support-engineering-http-fixtures'; import { createSupportEngineeringRouter } from './support-engineering-router'; @@ -171,6 +171,46 @@ function evidence(revision: number) { }; } +async function selection(f: Awaited>) { + const catalog = f.options.repositories.map((entry, index) => ({ ...entry, key: 'native-repository-choice-' + index })); + const route = f.router(catalog); const ticket = await f.legacyTicket(); + expect((await f.invoke('selection.setup.enroll', f.request('enroll', { + commandId: 'NATIVE-SELECTION-ENROLL', expectedRevision: ticket.revision, + }), route)).status).toBe(200); + const verified = await f.invoke('selection.setup.evidence', f.request('evidence', evidence(ticket.revision)), route); + expect(verified.status).toBe(200); + const source = engineeringHttpResult(await engineeringHttpObject(verified)); + expect(source.state).toBe('eligible'); + const key = { ticketId: ticket.id, sourceGeneration: engineeringHttpNumber(source.sourceGeneration) }; + f.engineering.state.modelRouting = 'ambiguous'; + // Genuine trusted processor preparation is fixture setup, outside the human + // HTTP binding profiles. The next request reads its actual persisted Work. + expect((await f.state.runtime.processWork({ ...key, workerId: 'synthetic-native-selection-worker', + leaseMilliseconds: 30_000 })).outcome).toBe('candidate'); + const response = await f.invoke('selection.work.immutable-choices', + f.request('work', undefined, 'staff', '?sourceGeneration=' + key.sourceGeneration), route); + expect(response.status).toBe(200); + const work = engineeringHttpResult(await engineeringHttpObject(response)); + if (!isPlainObject(work.selection) || !Array.isArray(work.selection.repositoryChoices)) + throw new Error('Expected actual immutable repository choices.'); + const choices = work.selection.repositoryChoices; + function choice(index: number) { + const value: unknown = choices[index]; + if (!isPlainObject(value) || typeof value.key !== 'string' || typeof value.repositoryId !== 'string' || + typeof value.descriptorHash !== 'string' || !/^[a-f0-9]{64}$/u.test(value.descriptorHash)) + throw new Error('Expected an actual bounded immutable repository choice.'); + return { key: value.key, repositoryId: value.repositoryId, descriptorHash: value.descriptorHash }; + } + const chosen = choice(1); const other = choice(0); + if (typeof work.selection.policyHash !== 'string') throw new Error('Expected an actual selection policy hash.'); + const packet = { commandId: 'NATIVE-IMMUTABLE-SELECTION-EXACT', sourceGeneration: key.sourceGeneration, + expectedWorkGeneration: engineeringHttpNumber(work.workGeneration), repositoryKey: chosen.key, + repositoryId: chosen.repositoryId, repositoryDescriptorHash: chosen.descriptorHash, + policyGeneration: engineeringHttpNumber(work.selection.policyGeneration), policyHash: work.selection.policyHash, + reason: 'The verified failure concerns the configured download API.' }; + return { key, catalog, route, chosen, other, packet }; +} + describe('enabled human engineering router and HTTP over genuine D1', () => { it('enrolls a real legacy source0, keeps its uncertain read forbidden, then accepts exact visible evidence within each request budget', async () => { const f = await fixture(); const ticket = await f.legacyTicket(); const before = await f.rows(); @@ -245,6 +285,109 @@ describe('enabled human engineering router and HTTP over genuine D1', () => { }, ); + it('recovers a genuinely committed immutable selection after ACK loss and catalog removal, while altered same-command coordinates cannot fake its ACK', async () => { + const f = await fixture(); const prepared = await selection(f); + const request = f.request('repository', prepared.packet); const originalBytes = await request.clone().text(); + const before = await f.rows(); const original = f.state.runtime; let lose = true; + let acknowledgement: Awaited> | undefined; + f.state.runtime = { ...original, async selectRepository(...args: Parameters) { + const value = await original.selectRepository(...args); acknowledgement ??= value; + if (lose) { lose = false; throw new Error('Synthetic real committed selection transport ACK loss'); } + return value; + } }; + const unknown = await f.invoke('selection.commit-lost-ack', await retainedPost(request), prepared.route); + expect(unknown.status).toBe(503); + expect(await engineeringHttpObject(unknown)).toEqual({ error: 'support_engineering_unavailable' }); + const committed = await f.rows(); expect(committed).not.toEqual(before); + expect(committed.filter((row) => row.kind === 'engineering_receipt')).toHaveLength( + before.filter((row) => row.kind === 'engineering_receipt').length + 1); + const work = await f.engineering.application.readEngineeringWork(f.engineering.actors.security, prepared.key); + expect(work.staffSelection).toMatchObject({ repositoryId: prepared.chosen.repositoryId, reason: prepared.packet.reason }); + const modelCalls = f.engineering.state.modelCalls; const removed = f.router([]); + expect(await request.clone().text()).toBe(originalBytes); + const replay = await f.invoke('selection.removed-catalog.exact-replay', await retainedPost(request), removed); + expect(replay.status).toBe(200); expect(acknowledgement).toBeDefined(); + if (acknowledgement === undefined) throw new Error('Expected the actual committed SDK selection acknowledgement.'); + const replayBody = await engineeringHttpObject(replay); + expect(engineeringHttpResult(replayBody)).toEqual({ ticketId: acknowledgement.ticketId, + sourceGeneration: acknowledgement.sourceGeneration, workGeneration: acknowledgement.workGeneration, status: acknowledgement.status }); + for (const privateText of [engineeringCanary, engineeringProofReference]) + expect(JSON.stringify(replayBody)).not.toContain(privateText); + expect(await f.rows()).toEqual(committed); + const altered = [ + { label: 'key', packet: { ...prepared.packet, repositoryKey: prepared.other.key } }, + { label: 'identity', packet: { ...prepared.packet, repositoryId: prepared.other.repositoryId } }, + { label: 'descriptor-hash', packet: { ...prepared.packet, + repositoryDescriptorHash: (prepared.chosen.descriptorHash[0] === '0' ? '1' : '0') + prepared.chosen.descriptorHash.slice(1) } }, + ]; + for (const change of altered) { + const denied = await f.invoke('selection.same-command.changed-' + change.label, + f.request('repository', change.packet), removed); + expect(denied.status).toBe(409); expect(await engineeringHttpObject(denied)).not.toHaveProperty('result'); + expect(await f.rows()).toEqual(committed); + } + expect(f.engineering.state.modelCalls).toBe(modelCalls); expect(f.engineering.state.creates).toEqual([]); + f.budget.assertBounds(); + }); + + it('denies a never-accepted immutable selection after its key disappears and keeps exact retries free of writes', async () => { + const f = await fixture(); const prepared = await selection(f); + const request = f.request('repository', prepared.packet); const originalBytes = await request.clone().text(); + const later = f.router(prepared.catalog.filter((entry) => entry.key !== prepared.chosen.key)); + const before = await f.rows(); const modelCalls = f.engineering.state.modelCalls; + const refused = await f.invoke('selection.unaccepted.removed-key', await retainedPost(request), later); + expect(refused.status).toBe(409); + expect(await engineeringHttpObject(refused)).toEqual({ error: 'engineering_selection_changed' }); + expect(await f.rows()).toEqual(before); + expect(await request.clone().text()).toBe(originalBytes); + const retry = await f.invoke('selection.unaccepted.removed-key.exact-retry', await retainedPost(request), later); + expect(retry.status).toBe(409); + expect(await engineeringHttpObject(retry)).toEqual({ error: 'engineering_selection_changed' }); + expect(await f.rows()).toEqual(before); + const work = await f.engineering.application.readEngineeringWork(f.engineering.actors.security, prepared.key); + expect(work.staffSelection).toBeUndefined(); expect(f.engineering.state.modelCalls).toBe(modelCalls); + expect(f.engineering.state.creates).toEqual([]); f.budget.assertBounds(); + }); + + it.each(['invalidate', 'withdraw'] as const)('commits genuine %s source controls and recovers their exact acknowledgements without another D1 mutation', async (operation) => { + const f = await fixture(); await f.verified(); const before = await f.rows(); + const request = f.request(operation, { commandId: 'NATIVE-' + operation.toUpperCase() + '-EXACT', + reason: operation === 'withdraw' ? 'privacy_withdrawal' : 'evidence_revoked' }); + const originalBytes = await request.clone().text(); + const accepted = await f.invoke(operation + '.commit', await retainedPost(request)); expect(accepted.status).toBe(200); + const acknowledgement = await engineeringHttpObject(accepted); + expect(acknowledgement.csrfToken).toBe(f.csrf.get('staff')); + expect(engineeringHttpResult(acknowledgement).state).toBe(operation === 'withdraw' ? 'withdrawn' : 'held'); + const committed = await f.rows(); expect(committed).not.toEqual(before); + expect(committed.filter((row) => row.kind === 'engineering_receipt')).toHaveLength( + before.filter((row) => row.kind === 'engineering_receipt').length + 1); + expect(await request.clone().text()).toBe(originalBytes); + const replay = await f.invoke(operation + '.exact-replay', await retainedPost(request)); expect(replay.status).toBe(200); + expect(await engineeringHttpObject(replay)).toEqual(acknowledgement); expect(await f.rows()).toEqual(committed); + const source = await f.engineering.source(); expect(source.state).toBe(operation === 'withdraw' ? 'withdrawn' : 'held'); + if (operation === 'withdraw') { expect(source.evidence).toBeUndefined(); expect(source.product).toBeUndefined(); } + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + f.budget.assertBounds(); + }); + + it('commits the actual guarded policy disable and exactly replays its original acknowledgement without another policy write', async () => { + const f = await fixture(); const initial = await f.engineering.runtime.readPolicy(f.engineering.actors.admin); + expect(initial.policy.enabled).toBe(true); const before = await f.policyRows(); + const request = f.request('policy/disable', { commandId: 'NATIVE-POLICY-DISABLE-EXACT', expectedGeneration: initial.generation }, 'both'); + const originalBytes = await request.clone().text(); + const accepted = await f.invoke('policy.disable.commit', await retainedPost(request)); expect(accepted.status).toBe(200); + const acknowledgement = await engineeringHttpObject(accepted); + expect(acknowledgement.csrfToken).toBe(f.csrf.get('both')); + expect(engineeringHttpResult(acknowledgement)).toMatchObject({ generation: initial.generation + 1, enabled: false }); + const committed = await f.policyRows(); expect(committed).not.toEqual(before); + expect(await request.clone().text()).toBe(originalBytes); + const replay = await f.invoke('policy.disable.exact-replay', await retainedPost(request)); expect(replay.status).toBe(200); + expect(await engineeringHttpObject(replay)).toEqual(acknowledgement); expect(await f.policyRows()).toEqual(committed); + expect((await f.engineering.runtime.readPolicy(f.engineering.actors.admin)).policy.enabled).toBe(false); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + f.budget.assertBounds(); + }); + it('rechecks actual stored Support and Admin role revocation on successive private router requests', async () => { const f = await fixture(); const ticket = await f.legacyTicket(); expect((await f.invoke('enroll.before-role-revocation', f.request('enroll', { diff --git a/worker/src/support-engineering-human-mutations.test.ts b/worker/src/support-engineering-human-mutations.test.ts new file mode 100644 index 0000000..f1774d7 --- /dev/null +++ b/worker/src/support-engineering-human-mutations.test.ts @@ -0,0 +1,124 @@ +import type { AccessContext } from '@pegma/authorization-core'; +import type { EngineeringMutationOptions } from '@pegma/support-desk-application'; +import { describe, expect, it } from 'vitest'; +import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access'; +import { createSupportEngineeringRuntime } from './support-engineering'; +import { engineeringRepositories } from './support-engineering-fixtures'; +import { createSupportEngineeringHttpFixture, engineeringHttpObject, engineeringHttpResult } from './support-engineering-http-fixtures'; + +type Operation = 'enroll' | 'evidence' | 'repository' | 'invalidate' | 'withdraw' | 'policy' | 'policy/disable'; + +function barrier() { + let enter!: () => void; + let resume!: () => void; + const entered = new Promise((resolve) => { enter = resolve; }); + const resumed = new Promise((resolve) => { resume = resolve; }); + return { entered, resume, async wait() { enter(); await resumed; } }; +} + +async function scenario(operation: Operation) { + const f = await createSupportEngineeringHttpFixture(); + const actor = operation.startsWith('policy') ? 'both' as const : 'staff' as const; + let body: unknown; + if (operation === 'enroll') { + const ticket = await f.legacyTicket(); + body = { commandId: 'LATE-ENROLL-EXACT', expectedRevision: ticket.revision }; + } else if (operation === 'evidence') { + const ticket = await f.enrolled(); + body = { commandId: 'LATE-EVIDENCE-EXACT', expectedRevision: ticket.revision, security: 'ordinary', + expectedBehavior: 'The fictional export contains rows.', actualBehavior: 'The fictional export is empty.', + reproductionSteps: ['Export the fictional workspace.'], visibleMessageIds: ['engineering-question'], + verificationReference: 'public-late-guard-reproduction' }; + } else if (operation === 'repository') { + await f.verified(); f.engineering.state.modelRouting = 'ambiguous'; + expect((await f.process()).outcome).toBe('candidate'); + const response = await f.send(f.request('work', undefined, actor, '?sourceGeneration=' + f.key().sourceGeneration)); + expect(response.status).toBe(200); + const work = engineeringHttpResult(await engineeringHttpObject(response)); + const selection = work.selection; + if (typeof selection !== 'object' || selection === null || !('repositoryChoices' in selection) || + !Array.isArray(selection.repositoryChoices)) throw new Error('Expected actual checked repository choices'); + const choice = selection.repositoryChoices[0]; + body = { commandId: 'LATE-SELECTION-EXACT', sourceGeneration: work.sourceGeneration, + expectedWorkGeneration: work.workGeneration, repositoryKey: choice.key, repositoryId: choice.repositoryId, + repositoryDescriptorHash: choice.descriptorHash, + policyGeneration: 'policyGeneration' in selection ? selection.policyGeneration : undefined, + policyHash: 'policyHash' in selection ? selection.policyHash : undefined, reason: 'The checked fictional API owns this bug.' }; + } else if (operation === 'policy') { + body = await f.preparePolicy({ commandId: 'LATE-POLICY-EXACT', expectedGeneration: 1, enabled: true, + repositoryKeys: [engineeringRepositories[0]!.repositoryId] }, actor); + } else if (operation === 'policy/disable') { + body = { commandId: 'LATE-DISABLE-EXACT', expectedGeneration: 1 }; + } else { + await f.verified(); + body = { commandId: 'LATE-' + operation.toUpperCase() + '-EXACT', + reason: operation === 'withdraw' ? 'privacy_withdrawal' : 'evidence_revoked' }; + } + const boundary = barrier(); + const application = f.engineering.application; + // Instrument only the actual public callback: all SDK validation, reads, + // receipts, optimistic transactions and results are delegated unchanged. + function paused(run: (access: AccessContext, input: Command, + control?: EngineeringMutationOptions) => Promise) { + return (access: AccessContext, input: Command, control?: EngineeringMutationOptions) => run(access, input, { + ...control, verifyBeforeCommit: async () => { + await boundary.wait(); + return control?.verifyBeforeCommit?.(); + }, + }); + } + const guardedApplication = { ...application, + enrollEngineeringSource: paused(application.enrollEngineeringSource), + submitEngineeringEvidence: paused(application.submitEngineeringEvidence), + selectEngineeringRepository: paused(application.selectEngineeringRepository), + invalidateEngineeringSource: paused(application.invalidateEngineeringSource), + withdrawEngineeringSource: paused(application.withdrawEngineeringSource), + putRepositoryPolicy: paused(application.putRepositoryPolicy), + disableEngineeringExports: paused(application.disableEngineeringExports), + }; + f.state.runtime = createSupportEngineeringRuntime({ application: guardedApplication, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, ports: f.engineering.ports, processingEnabled: () => false }); + return { f, actor, body, boundary }; +} + +describe('actual026 late human engineering mutation guards', () => { + for (const operation of ['enroll', 'evidence', 'repository', 'invalidate', 'withdraw', 'policy', 'policy/disable'] as const) { + it.each(['session', 'support-role'] as const)('prevents NEW ' + operation + ' after %s loss at the actual SDK commit callback', async (change) => { + const { f, actor, body, boundary } = await scenario(operation); + const sourceBefore = await f.rows(); const policyBefore = await f.policyRows(); + const modelCalls = f.engineering.state.modelCalls; + const pending = f.send(f.request(operation, body, actor)); + await Promise.race([boundary.entered, pending.then(() => { throw new Error('Expected the actual public late callback'); })]); + try { + if (change === 'session') await f.destroy(actor); + else await f.revoke(actor, SUPPORT_ROLE); + } finally { boundary.resume(); } + const response = await pending; expect([401, 403]).toContain(response.status); + expect(await f.rows()).toEqual(sourceBefore); expect(await f.policyRows()).toEqual(policyBefore); + expect(f.engineering.state.modelCalls).toBe(modelCalls); expect(f.engineering.state.creates).toEqual([]); + }); + } + + it.each([ADMIN_ROLE, SUPPORT_ROLE])('rechecks trusted direct callers without a browser callback after %s loss', async (role) => { + const { f, boundary } = await scenario('policy/disable'); + const access = await f.resolve(f.principals.both); + if (access === null) throw new Error('Expected current actual Admin + Support authority'); + const before = await f.policyRows(); + const pending = f.state.runtime.disableExports(access, { + clientCommandId: 'DIRECT-LATE-DISABLE', expectedGeneration: 1, + }); + await Promise.race([boundary.entered, pending.then(() => { throw new Error('Expected the actual public late callback'); })]); + try { await f.revoke('both', role); } finally { boundary.resume(); } + await expect(pending).rejects.toThrow(); + expect(await f.policyRows()).toEqual(before); + expect(f.engineering.state.modelCalls).toBe(0); expect(f.engineering.state.creates).toEqual([]); + }); + + it.each(['policy', 'policy/disable'] as const)('requires current Admin authority for NEW %s at the same late boundary', async (operation) => { + const { f, actor, body, boundary } = await scenario(operation); + const before = await f.policyRows(); const pending = f.send(f.request(operation, body, actor)); + await Promise.race([boundary.entered, pending.then(() => { throw new Error('Expected the actual public late callback'); })]); + try { await f.revoke(actor, ADMIN_ROLE); } finally { boundary.resume(); } + expect((await pending).status).toBe(403); expect(await f.policyRows()).toEqual(before); + }); +}); diff --git a/worker/src/support-engineering.ts b/worker/src/support-engineering.ts index 6e2ba32..3927a7a 100644 --- a/worker/src/support-engineering.ts +++ b/worker/src/support-engineering.ts @@ -21,6 +21,7 @@ import { type WithdrawEngineeringSourceCommand, type PutEngineeringPolicyCommand, type EngineeringPolicyCommand, + type EngineeringMutationOptions, } from '@pegma/support-desk-application'; import { supportEngineeringCommandIdentity, @@ -40,6 +41,12 @@ export type EngineeringInvalidationPacket = Packet; export type EngineeringPolicyPacket = Packet; export type EngineeringDisablePacket = Packet; +/** The HTTP host resolves the original browser and current human authority. */ +export type SupportEngineeringHumanCommitGuard = () => Promise; +export interface SupportEngineeringSelectionControl { + readonly beforeCommit?: SupportEngineeringHumanCommitGuard; + readonly intentFingerprint?: string; +} /** Read-only facts required for a NEW approval; no processing or dispatch ports. */ export interface SupportEngineeringReviewProofs { @@ -117,7 +124,8 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti } }); async function staff(original: AccessContext, permission: string, - run: (access: AccessContext, refresh: () => Promise, signal: AbortSignal) => Promise): Promise { + run: (access: AccessContext, refresh: () => Promise, signal: AbortSignal, + assertCurrent: () => true) => Promise): Promise { const bound = structuredClone(original); const started = performance.now(); const controller = new AbortController(); @@ -125,6 +133,12 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti if (controller.signal.aborted || performance.now() - started >= staffOperationMilliseconds) throw new SupportEngineeringUnavailableError(); }; + const assertCurrent = (): true => { + ensure(); + if (original.principalId !== bound.principalId) + throw new SupportDeskAuthorizationError(permission); + return true; + }; let rejectDeadline: (error: Error) => void = () => {}; const deadline = new Promise((_resolve, reject) => { rejectDeadline = reject; }); const timer = setTimeout(() => { @@ -159,7 +173,7 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti } try { const current = await refresh(); - const value = await within(() => run(current, refresh, controller.signal)); + const value = await within(() => run(current, refresh, controller.signal, assertCurrent)); // A direct SDK mutation may commit after this boundary stops waiting. // Withhold its unknown acknowledgement; only exact packet replay can // recover it. Timeout never proves nonacceptance or rolls it back. @@ -174,13 +188,31 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti async function command(access: AccessContext, permission: string, operation: SupportEngineeringOperation, ticketId: string, input: Input, invoke: (current: AccessContext, packet: Omit & { commandId: string; correlationId: string }, - refresh: () => Promise, signal: AbortSignal) => Promise): Promise { + refresh: () => Promise, signal: AbortSignal, control: EngineeringMutationOptions) => Promise, + beforeCommit?: SupportEngineeringHumanCommitGuard): Promise { const packet = structuredClone(input); const principalId = access.principalId; - return staff(access, permission, async (_current, refresh, signal) => { + const ceiling = structuredClone(access); + if (beforeCommit !== undefined && typeof beforeCommit !== 'function') + throw new TypeError('Expected an engineering human commit guard'); + return staff(access, permission, async (_current, refresh, signal, assertCurrent) => { const { clientCommandId, ...fields } = packet; const identity = await supportEngineeringCommandIdentity({ principalId, ticketId, operation, clientCommandId }); - return invoke(await refresh(), { ...fields, ...identity }, refresh, signal); + const control: EngineeringMutationOptions = { signal, verifyBeforeCommit: async () => { + // A complete current browser guard already resolves current staff roles. + // Trusted direct callers use the same current-role resolver instead. + const current = beforeCommit === undefined ? await refresh() : await beforeCommit(); + assertCurrent(); + if (current.principalId !== principalId) throw new SupportDeskAuthorizationError(permission); + const bounded: AccessContext = { principalId, policyVersion: current.policyVersion, + roles: current.roles.filter((entry) => ceiling.roles.includes(entry)), + entitlements: current.entitlements.filter((entry) => ceiling.entitlements.includes(entry)), + permissions: current.permissions.filter((entry) => ceiling.permissions.includes(entry)) }; + for (const required of [permission, supportPermissions.queueRead]) + if (!hasPermission(bounded, required)) throw new SupportDeskAuthorizationError(required); + return assertCurrent; + } }; + return invoke(await refresh(), { ...fields, ...identity }, refresh, signal, control); }); } @@ -199,15 +231,25 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti return Object.freeze({ reviewCommand, - enroll: (access: AccessContext, input: EngineeringEnrollmentPacket) => + enroll: (access: AccessContext, input: EngineeringEnrollmentPacket, beforeCommit?: SupportEngineeringHumanCommitGuard) => command(access, supportPermissions.engineeringEvidenceSubmit, 'enroll', input.ticketId, input, - (current, packet) => application.enrollEngineeringSource(current, packet)), - submitVerifiedFailure: (access: AccessContext, input: EngineeringFailurePacket) => + (current, packet, _refresh, _signal, control) => application.enrollEngineeringSource(current, packet, control), beforeCommit), + submitVerifiedFailure: (access: AccessContext, input: EngineeringFailurePacket, beforeCommit?: SupportEngineeringHumanCommitGuard) => command(access, supportPermissions.engineeringEvidenceSubmit, 'failure', input.ticketId, input, - (current, packet) => application.submitEngineeringEvidence(current, packet)), - selectRepository: (access: AccessContext, input: EngineeringSelectionPacket) => - command(access, supportPermissions.engineeringReview, 'select', input.ticketId, input, - (current, packet) => application.selectEngineeringRepository(current, packet)), + (current, packet, _refresh, _signal, control) => application.submitEngineeringEvidence(current, packet, control), beforeCommit), + selectRepository(access: AccessContext, input: EngineeringSelectionPacket, options: SupportEngineeringSelectionControl = {}) { + const { intentFingerprint, beforeCommit } = options; + return command(access, supportPermissions.engineeringReview, 'select', input.ticketId, input, + (current, packet, _refresh, _signal, control) => { + if (intentFingerprint !== undefined && !/^[a-f0-9]{64}$/u.test(intentFingerprint)) + throw new TypeError('Invalid engineering selection intent fingerprint'); + return application.selectEngineeringRepository(current, { ...packet, + ...(intentFingerprint === undefined ? {} : { + correlationId: 'engineering-selection-intent:' + intentFingerprint, + }), + }, control); + }, beforeCommit); + }, reviewProposal: (access: AccessContext, input: EngineeringReviewPacket) => command(access, supportPermissions.engineeringReview, 'review', input.ticketId, input, async (current, packet, refresh, signal) => { @@ -215,12 +257,12 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti verifyBeforeCommit: async () => { await refresh(); }, }); }), - invalidate: (access: AccessContext, input: EngineeringInvalidationPacket) => + invalidate: (access: AccessContext, input: EngineeringInvalidationPacket, beforeCommit?: SupportEngineeringHumanCommitGuard) => command(access, supportPermissions.engineeringWithdraw, 'invalidate', input.ticketId, input, - (current, packet) => application.invalidateEngineeringSource(current, packet)), - withdraw: (access: AccessContext, input: EngineeringWithdrawalPacket) => + (current, packet, _refresh, _signal, control) => application.invalidateEngineeringSource(current, packet, control), beforeCommit), + withdraw: (access: AccessContext, input: EngineeringWithdrawalPacket, beforeCommit?: SupportEngineeringHumanCommitGuard) => command(access, supportPermissions.engineeringWithdraw, 'withdraw', input.ticketId, input, - (current, packet) => application.withdrawEngineeringSource(current, packet)), + (current, packet, _refresh, _signal, control) => application.withdrawEngineeringSource(current, packet, control), beforeCommit), readSource: (access: AccessContext, ticketId: string) => staff(access, supportPermissions.engineeringRead, (current) => application.readEngineeringSource(current, ticketId)), readWork(access: AccessContext, input: EngineeringKey) { @@ -229,9 +271,10 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti }, readPolicy: (access: AccessContext) => staff(access, supportPermissions.engineeringPolicyRead, (current) => application.readRepositoryPolicy(current)), - putPolicy: (access: AccessContext, input: EngineeringPolicyPacket, intentFingerprint?: string) => + putPolicy: (access: AccessContext, input: EngineeringPolicyPacket, intentFingerprint?: string, + beforeCommit?: SupportEngineeringHumanCommitGuard) => command(access, supportPermissions.engineeringPolicyManage, 'policy_put', 'policy-instance', input, - (current, packet) => { + (current, packet, _refresh, _signal, control) => { if (intentFingerprint !== undefined && !/^[a-f0-9]{64}$/u.test(intentFingerprint)) throw new TypeError('Invalid engineering policy intent fingerprint'); return application.putRepositoryPolicy(current, { @@ -239,11 +282,11 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti ...(intentFingerprint === undefined ? {} : { correlationId: 'engineering-policy-intent:' + intentFingerprint, }), - }); - }), - disableExports: (access: AccessContext, input: EngineeringDisablePacket) => + }, control); + }, beforeCommit), + disableExports: (access: AccessContext, input: EngineeringDisablePacket, beforeCommit?: SupportEngineeringHumanCommitGuard) => command(access, supportPermissions.engineeringPolicyManage, 'policy_disable', 'policy-instance', input, - (current, packet) => application.disableEngineeringExports(current, packet)), + (current, packet, _refresh, _signal, control) => application.disableEngineeringExports(current, packet, control), beforeCommit), scanReview(access: AccessContext, input: Parameters[1]) { const bounds = structuredClone(input); return staff(access, supportPermissions.engineeringReview, (current) => application.scanEngineeringCandidates(current, bounds)); From ec0058b34fa5f8bceb2f9dd1d1e07e27f6186de9 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 15:18:13 -0500 Subject: [PATCH 3/7] Align engineering fixtures with current Worker types --- worker/src/maintenance-cursors.d1.test.ts | 7 ++++++- worker/src/support-engineering-composition.test.ts | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/worker/src/maintenance-cursors.d1.test.ts b/worker/src/maintenance-cursors.d1.test.ts index cfbb01a..58c00a0 100644 --- a/worker/src/maintenance-cursors.d1.test.ts +++ b/worker/src/maintenance-cursors.d1.test.ts @@ -207,9 +207,14 @@ describe('maintenance cursor writes over D1', () => { const secretRead = vi.fn(() => { throw new Error('Support rate cleanup must not initialize Identity.'); }); const environment: Parameters[1] = { ...env, IDENTITY_DB: metered.database, DATADOG_API_KEY: undefined, - PEGMA_KNOWLEDGE_ENABLED: 'false', PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: 'false', + PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED: 'false', get IDENTITY_EMAIL_CODE_SECRET_BASE64(): string { return secretRead(); }, }; + // Match the generated deployment literal while explicitly testing an + // isolated disabled cleanup invocation, as the parent root fixtures do. + Object.defineProperty(environment, 'PEGMA_KNOWLEDGE_ENABLED', { + value: 'false', writable: true, enumerable: true, configurable: true, + }); const start = Math.floor(Date.now() / 60_000) * 60_000; const scheduledTime = Array.from({ length: 120 }, (_, offset) => start + offset * 60_000).find((time) => { const lane = cleanupLaneAt(time); diff --git a/worker/src/support-engineering-composition.test.ts b/worker/src/support-engineering-composition.test.ts index 4256f3e..c28941c 100644 --- a/worker/src/support-engineering-composition.test.ts +++ b/worker/src/support-engineering-composition.test.ts @@ -48,6 +48,7 @@ describe('optional public engineering root composition', () => { get exports(): Cloudflare.Exports { throw new Error('Disabled engineering must not read Worker exports'); }, props: {}, get tracing(): Tracing { throw new Error('Disabled engineering must not initialize tracing'); }, + abort() { throw new Error('Disabled engineering must not abort its Worker context'); }, }; const response = await worker.fetch(new Request('https://pegma.dev/api/support/admin/engineering/policy'), env, context); await Promise.all(pending); From d84f68e94fde4fb078d0ed26dea0677d44371887 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 17:36:30 -0500 Subject: [PATCH 4/7] Fix engineering review controls and adopt Sessions 0.2.1 --- docs/KNOWLEDGE_COMPOSITION.md | 28 +++-- docs/SUPPORT_ASSISTANT_STAGE.md | 9 +- docs/SUPPORT_COMPOSITION.md | 64 ++++++----- docs/SUPPORT_ENGINEERING.md | 13 ++- docs/SUPPORT_LEARNING.md | 12 +- package.json | 2 +- pnpm-lock.yaml | 10 +- public/staff-support-engineering.js | 27 +++-- public/staff-support-ticket.js | 2 +- src/support-engineering-controller.test.ts | 11 ++ src/support-engineering-review.test.ts | 24 +++- src/support-engineering-ui.test.ts | 49 ++++++++- worker/src/support-engineering-handlers.ts | 2 +- .../src/support-engineering-http.d1.test.ts | 103 +++++++++++++++++- worker/src/support-engineering-review.test.ts | 49 +++++++++ worker/src/support-engineering.ts | 25 ++++- worker/src/support-learning-ports.ts | 2 +- 17 files changed, 356 insertions(+), 76 deletions(-) diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index 5803377..41e1820 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -21,9 +21,9 @@ at signed source passed independent exact-byte, signature/provenance and registry-consumer verification. Existing Identity and Support Desk keep their `@pegma/rate-limit@0.2.0` dependency. The current host selects all five Support -Desk packages at `0.2.5`, including the optional AI coordinator. The separate +Desk packages at `0.2.6`, including the optional AI coordinator. The separate synthetic stage remains default-disabled. The -[verified Support Desk `0.2.5` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5) +[verified Support Desk `0.2.6` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.6) pins its optional AI dependency on KB application/contracts `0.1.5`. The learning port forwards actual KB errors without the obsolete `0.1.2` @@ -90,6 +90,9 @@ PG-01's full review, CI and automatic deployment passed at that earlier checkpoi ### Public 0.2.5 adoption checkpoint +Release evidence for this historical checkpoint is the +[verified Support Desk `0.2.5` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5). + On 2026-11-11, the normal public Support `0.2.5` / D1 `0.4.7` graph passed local Node `22.18.0` checks, all 1,125 tests, the static build and the main-Worker packaging dry run. The normal suites comprised 1,002 Node tests across 62 files, @@ -216,9 +219,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 under policy `pegma.dev-policy-5`. - Learning processing is not granted. Existing assignments are not migrated - or silently granted KB powers. + 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 + is not granted. Existing assignments are not migrated or silently granted KB + powers. - `Knowledge` is a separately assigned role for collection reads, draft and evidence work, human report review, publication and withdrawal. Admin-only collection/governance mutation controls remain separate. @@ -399,10 +404,13 @@ two isolated rate invocations followed by one ready-hint invocation: remain a latency aid, with atomic SDK jobs and physical recovery preserved. The original four other expressions remain in place. The cleanup rotation -retains its original 15 lanes and adds one separately gated learning-review -discovery lane, for 16 exclusive lanes. That lane emits queue hints only; a -review phase runs in a later Queue invocation. The default root supplies no -trusted learning bundle and keeps the review flag off. Minutes 58 and 59 have no `RATE_LIMIT_CRON` invocation. Before +retains its original 15 lanes, the separately gated learning-review discovery +lane and two engineering limiter lanes, for 18 exclusive lanes. Each lane runs +once per 18 eligible ticks, a nominal 18-19 minutes because minute 59 is +omitted. The learning lane emits queue hints only; a review phase runs in a +later Queue invocation. The default root supplies no trusted learning bundle +and keeps the review flag off. Minutes 58 and 59 have no `RATE_LIMIT_CRON` +invocation. Before merging, inventory every Worker's current cron triggers in the deployment account: pushes to `main` deploy these schedules regardless of the Knowledge flag. Deployment replaces this Worker's existing expressions with these @@ -472,7 +480,7 @@ completions cannot overwrite a newer generation. Already committed projection writes are not rolled back after acknowledgement uncertainty. The existing Knowledge turn in the -[16-lane cleanup schedule](../worker/src/maintenance-schedule.ts) independently +[18-lane cleanup schedule](../worker/src/maintenance-schedule.ts) independently calls `repairRetrievalPage` with `limit:1` and `maxBatches:1`. Complete physical cycles and the SDK's existing atomic article-change jobs remain the recovery path for a lost hint, collection/policy changes and unfinished work. The ready diff --git a/docs/SUPPORT_ASSISTANT_STAGE.md b/docs/SUPPORT_ASSISTANT_STAGE.md index cc349d7..cf7959f 100644 --- a/docs/SUPPORT_ASSISTANT_STAGE.md +++ b/docs/SUPPORT_ASSISTANT_STAGE.md @@ -51,7 +51,7 @@ checked during cloud qualification. See ## Run the local checks Use the repository's supported Node version and frozen dependency install. -The current package selection is Support Desk `0.2.5` with direct Knowledge Base +The current package selection is Support Desk `0.2.6` with direct Knowledge Base `0.1.5`; [package.json](../package.json) is authoritative. From the repository root: @@ -87,11 +87,12 @@ on Node 22.18.0. Recovery profiles recorded 31 physical D1 calls for preparation and 50 for answering, with zero blocked calls. Preparation made zero model or reservation calls. Answering used one model call, one reservation and one reconciliation, with the persisted ledger stable across later duplicates. -These historical results apply to that fictional fixture. The current public +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). -Deployed broker timing, retry delivery, CPU use and wider workloads retain -their qualification gates. +That checkpoint does not qualify the current `0.2.6` graph. Current host +validation remains pending. Deployed broker timing, retry delivery, CPU use and +wider workloads retain their qualification gates. ## Generate a fictional seed locally diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index d51bd88..2aabe98 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -17,11 +17,11 @@ provider and customer activation retain their acceptance gates. See the Exact published versions: -- `@pegma/support-desk-application@0.2.5` -- `@pegma/support-desk-contracts@0.2.5` -- `@pegma/support-desk-core@0.2.5` -- `@pegma/support-desk-templates@0.2.5` -- `@pegma/support-desk-ai@0.2.5` (optional coordinator) +- `@pegma/support-desk-application@0.2.6` +- `@pegma/support-desk-contracts@0.2.6` +- `@pegma/support-desk-core@0.2.6` +- `@pegma/support-desk-templates@0.2.6` +- `@pegma/support-desk-ai@0.2.6` (optional coordinator) - `@pegma/authorization-admin@0.4.0` (role administration service) - `@pegma/authorization-core@0.4.0` (AccessContext resolution) - `@pegma/authorization-policy@0.4.0` (PolicyDocumentV1 schema validation) @@ -31,11 +31,11 @@ All five Support Desk packages have completed producer publication and registry qualification. The optional AI package selects exact KB application and contracts `0.1.5`; the host selects all four KB packages at that version. Producer qualification and installation do not complete host or provider -acceptance. [Verified Support Desk `0.2.5` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5), +acceptance. [Verified Support Desk `0.2.6` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.6), [verified KB `0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5). Peers already present on the host: `@pegma/storage-core@0.4.0`, -`@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.2.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`. 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 @@ -45,9 +45,13 @@ The earlier [qualified Support 0.2.2 release](https://github.com/pegma-dev/suppo uses signed source [`99cf4e67da1d2357d99fd80389a96318a6e2cc93`](https://github.com/pegma-dev/support-desk/commit/99cf4e67da1d2357d99fd80389a96318a6e2cc93). [Strict release verification](https://github.com/pegma-dev/support-desk/actions/runs/42907283767/job/130161276758) -qualifies those historical producer packages. The current public `0.2.5` graph -has passed the [normal local and CI validation checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint). -Review and deployment acceptance remain pending for the changed host. +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.6` 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 +concurrency defect under a consistent advancing clock. ## Storage namespace @@ -103,8 +107,13 @@ The `Support` role maps to: - `support.learning.evidence.submit` - `support.learning.review` - `support.learning.withdraw` +- `support.engineering.read` +- `support.engineering.evidence.submit` +- `support.engineering.review` +- `support.engineering.withdraw` +- `support.engineering.policy.read` -`Admin` and `Knowledge` alone do not grant Support permissions. Taking over +`Admin` and `Knowledge` alone do not grant Support queue authority. Taking over changes handling authority; the existing assignment action remains separate. **Bootstrap (one-time seeding).** `PEGMA_SUPPORT_BOOTSTRAP_PRINCIPALS` @@ -259,8 +268,10 @@ Durable rate-limit policies (separate from Identity): request-person and takeover, including retries) - `pegma.admin.role.mutate` (assign / revoke, 30/h per operator) - `pegma.admin.principal.lookup` (directory lookups, 120/h per operator) +- `pegma.support.engineering.read` (engineering reads, 120/h per operator) +- `pegma.support.engineering.mutate` (engineering mutations, 30/h per operator) -All four are swept by the same rotating cleanup schedule, one policy per +All six are swept by the same rotating cleanup schedule, one policy per invocation. ## Site pages @@ -275,8 +286,8 @@ invocation. ## Optional resolution learning -The current source selects all five published Support Desk `0.2.5` packages -with the four direct KB `0.1.5` packages. AI `0.2.5` also declares exact KB +The current source selects all five published Support Desk `0.2.6` packages +with the four direct KB `0.1.5` packages. AI `0.2.6` also declares exact KB `0.1.5` dependencies. The public forwarding port preserves KB error instances; no KB `0.1.2` alias, translation shim, second Store, override or private SDK import supplies this assembly. The earlier Support `0.2.1` / nested KB `0.1.2` @@ -284,10 +295,11 @@ compatibility assembly and its failed isolated production-layout diagnostic are historical, not current graph or host-acceptance evidence. The staged learning review admission and Queue worker retained in this branch -use the published, strictly verified Support Desk `0.2.5` APIs. The combined -public graph passed normal local and CI validation; review and deployment -acceptance remain pending. Runtime availability and feature activation retain -their existing trusted composition and readiness controls. +use the published, strictly verified Support Desk `0.2.6` APIs. 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 +controls. [Learning intake and processing](../worker/src/support-learning.ts) are separate, default-disabled SDK boundaries. A real source verifier, current service/staff @@ -301,9 +313,11 @@ and staff approval of the exact checked KB target remain separate. Neither approval nor delivery publishes a guide: ordinary KB evidence, review and publication gates still apply. -Policy `pegma.dev-policy-5` adds four explicit learning permissions to `Support`; -it grants neither learning processing nor KB staff access. Private proposal -reads and new review commits also require separately current KB `draftRead` and +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 +separate. Private proposal reads and new review commits also require separately +current KB `draftRead` and `provenanceRead`, normally through `Knowledge` or `Admin`. Browser submissions and trusted direct SDK reviews enforce fresh KB and learning review/queue permissions before and after the actual SDK proof. HTTP requires the complete @@ -354,7 +368,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.5` selection; omission remains monolithic. The preparation attempt retrieves authorized sources and records a +`0.2.6` selection; omission remains monolithic. The preparation attempt retrieves authorized sources and records a bounded no-call request without reserving paid usage. Only its durably acknowledged finish returns `prepared`. The host must return and schedule a genuinely later physical invocation at or after `nextAttemptAt`, never loop or @@ -374,9 +388,9 @@ provider or activation result. The separate cleanup cron (`0-58 * * * *`) runs one rotating task per invocation, including Support Desk queue repair, inactive projection sweep, each Support/Admin rate-limit policy and the separately gated learning-review -discovery lane. Each task runs once per sixteen eligible ticks (minute 59 is -omitted), with independent queue cursors and no -writes for unchanged bookmarks. +discovery lane, for 18 exclusive lanes. Each task runs once per 18 eligible +ticks, a nominal 18-19 minutes because minute 59 is omitted, with independent +queue cursors and no writes for unchanged bookmarks. Identity Mail send and reconciliation have separate invocations (`* * * * *` and `1-59 * * * *`); KB ready hints and their isolated rate cleanup use the existing `0-57 * * * *` lane. No cron is added for human controls. diff --git a/docs/SUPPORT_ENGINEERING.md b/docs/SUPPORT_ENGINEERING.md index d2c23c2..e49da1f 100644 --- a/docs/SUPPORT_ENGINEERING.md +++ b/docs/SUPPORT_ENGINEERING.md @@ -114,9 +114,10 @@ replay therefore survives source withdrawal or unavailable repository facts. The runtime passes its fresh staff check and original-browser callback through the public SDK's `verifyBeforeCommit` option for all seven human intake and policy mutations. The SDK looks for an exact accepted receipt before invoking -the new-command guard; that guard supplies the final synchronous deadline and -principal assertion at the Application transaction boundary. Current browser -and role checks still protect every replay and response. The separate proposal +the new-command guard. Its async check resolves current browser and human +roles; the final synchronous fence checks abort/deadline and the original +caller's bound principal at the Application transaction boundary. Current +browser and role checks still protect every replay and response. The separate proposal review guard applies to both approval and rejection. New approval also requires the configured read-only routing, checks and repository proof ports. The independent review switch defaults OFF. @@ -228,6 +229,12 @@ 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 +snapshots under a consistent advancing clock. Explicit caller instants retain +their semantics, and future idle anchors from rollback or skew still fail closed. + The combined current-parent root, controller and review changes require fresh format, types, full Node 22 and 24 tests, build and current-head CI and review. Actual registered-route Native D1 measurements must cover intake, policy, diff --git a/docs/SUPPORT_LEARNING.md b/docs/SUPPORT_LEARNING.md index 29ba8dc..07c4cf8 100644 --- a/docs/SUPPORT_LEARNING.md +++ b/docs/SUPPORT_LEARNING.md @@ -15,9 +15,9 @@ activation evidence. ## Packages and authority -The host selects all five published Support Desk packages at **0.2.5** and its +The host selects all five published Support Desk packages at **0.2.6** and its four direct Knowledge Base packages at **0.1.5**. The qualified -[Support 0.2.5 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.5) +[Support 0.2.6 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.6) also uses exact KB **0.1.5** public contracts. The [public forwarding port](../worker/src/support-learning-ports.ts) preserves the actual KB error instances; the obsolete KB 0.1.2 constructor alias and translation @@ -29,7 +29,7 @@ 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.5 graph. +ordinary fixture passes nor that failure qualifies the current 0.2.6 graph. The current [host policy](../worker/src/support-access.ts) grants four human learning permissions through the actual stored, audited **Support** role: @@ -324,9 +324,9 @@ surface passed **39 cases**. That earlier focused browser/backend run passed cases, with zero errors in its Astro, Worker and recipe check. These historical counts overlap the assembly baseline. They predate the earlier 0.2.2 adoption and full-intent/commit-guard changes and do not qualify the current host source. -The normal public `0.2.5` [adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint) -passed 1,125 tests locally and in CI. Current review and deployment acceptance -remain pending. +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.6` +graph. Current host validation, review and deployment acceptance remain pending. Relevant executable sources are the [Memory assembly](../worker/src/support-learning.test.ts), diff --git a/package.json b/package.json index 41813f9..32a95e2 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "@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.0", + "@pegma/sessions": "0.2.1", "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.7", "@pegma/storage-core": "0.4.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a07bbf8..02c39ee 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -69,8 +69,8 @@ importers: specifier: npm:@pegma/rate-limit@0.3.3 version: '@pegma/rate-limit@0.3.3' '@pegma/sessions': - specifier: 0.2.0 - version: 0.2.0 + specifier: 0.2.1 + version: 0.2.1 '@pegma/spine': specifier: ^0.1.1 version: 0.1.1 @@ -1219,8 +1219,8 @@ packages: resolution: {integrity: sha512-Bu2t3WjD4VsQj5lWnz+XZ0KQ/F2rbs1CkDmH6aSl9kCg1cYNZHviL9o5XJhbsA7siFo9G+FOJXK2REnnzWtk9Q==} engines: {node: '>=22'} - '@pegma/sessions@0.2.0': - resolution: {integrity: sha512-dHGmFzQjHe9O+arGEQUcwutLuZ9+cA409hetiqxzQUXIOHOulOsA4/ywlDDRGiskMijyXLVlxvmGryjxV8NxZQ==} + '@pegma/sessions@0.2.1': + resolution: {integrity: sha512-GOpwpL0S7/wXpUFuuR0aza+2enGDuUdFrgvOKAbUljDABSj1g/+QOzwQPbe9QYsGI7AImlk4El8cc5qzguNP9Q==} engines: {node: '>=22'} '@pegma/spine@0.1.1': @@ -4245,7 +4245,7 @@ snapshots: '@pegma/spine': 0.1.1 '@pegma/storage-core': 0.4.0 - '@pegma/sessions@0.2.0': + '@pegma/sessions@0.2.1': dependencies: '@pegma/spine': 0.1.1 '@pegma/storage-core': 0.4.0 diff --git a/public/staff-support-engineering.js b/public/staff-support-engineering.js index 7738812..be68d16 100644 --- a/public/staff-support-engineering.js +++ b/public/staff-support-engineering.js @@ -43,7 +43,8 @@ const pending = new Map(); const enrolled = new Map(); let epoch = 0, context = null, session = null, ticket = null, source = null, work = null, policy = null, proposal = null; - let busy = false, preparedPolicy = null, retryAt = 0; + let busy = false, preparedPolicy = null, policyEditorRevision = 0; + const retryAt = { read: 0, mutation: 0 }; const controllers = new Set(); const inputs = []; const buttons = []; @@ -125,6 +126,7 @@ function activity() { try { options.onBusyChange?.(busy); } catch { /* Host presentation is not authority. */ } } function notice(value) { status.textContent = value; } function clearPrivate() { + ++policyEditorRevision; source = null; work = null; policy = null; proposal = null; preparedPolicy = null; session = null; sourceText.textContent = ''; workText.textContent = ''; proposalText.textContent = ''; catalog.replaceChildren(); policyStatus.textContent = ''; policyPanel.hidden = true; messageChoices.replaceChildren(); repository.input.replaceChildren(); repository.input.value = ''; @@ -176,7 +178,10 @@ return value; } async function call(path, init, observation, actor, observeResult) { - guard(observation); const controller = new AbortController(); controllers.add(controller); + guard(observation); + const purpose = init?.method === 'POST' ? 'mutation' : 'read'; + if (now() < retryAt[purpose]) throw Object.assign(new Error('retry_delay'), { retryPurpose: purpose }); + const controller = new AbortController(); controllers.add(controller); try { const value = await request(path, { ...init, signal: controller.signal, headers: { ...(init?.headers ?? {}), 'X-Pegma-CSRF': actor.csrfToken } }); @@ -184,14 +189,17 @@ observeResult?.(value.result); guard(observation); return value.result; + } catch (error) { + if (error?.status === 429) retryAt[purpose] = Math.max(retryAt[purpose], Number.isSafeInteger(error.retryAt) ? error.retryAt : now() + 30000); + throw error; } finally { controllers.delete(controller); } } const base = () => '/api/support/admin/tickets/' + encodeURIComponent(context.ticketId) + '/engineering'; function failure(error, observation) { if (observation !== epoch) return; clearPrivate(); ticket = null; - if (error?.status === 429) retryAt = Math.max(retryAt, Number.isSafeInteger(error.retryAt) ? error.retryAt : now() + 30000); - notice(pending.size ? 'A command is retained. Restore current access, then explicitly recover its original packet.' + notice(error?.retryPurpose === 'read' ? 'Wait for the server read retry delay before refreshing current engineering state.' + : pending.size ? 'A command is retained. Restore current access, then explicitly recover its original packet.' : 'Current engineering access or state could not be confirmed. Refresh before another action.'); if ([401, 403].includes(error?.status)) { try { options.onAccessLost?.({ status: error.status, owners: owners() }); } catch { /* Retain ownership. */ } @@ -230,7 +238,7 @@ destinationCount: value.destinationCount, reconciliationPending: value.reconciliationPending }; } async function refreshSource(observation, actor, acknowledged) { - source = null; work = null; sourceText.textContent = ''; workText.textContent = ''; + source = null; work = null; proposal = null; sourceText.textContent = ''; workText.textContent = ''; proposalText.textContent = ''; try { const value = sourceValue(await call(base(), { method: 'GET' }, observation, actor)); await viewer(observation, actor); source = value; sourceText.textContent = JSON.stringify(value, null, 2); @@ -381,7 +389,7 @@ (saved ? saved.enabled ? ' (saved enabled) ' : ' (saved disabled) ' : ' (not selected) ')); const input = node('input'); input.type = 'checkbox'; input.dataset.engineeringRepository = entry.key; input.checked = value.repositories.some((saved) => saved.key === entry.key); label.append(input); catalog.append(label); - input.addEventListener('change', () => { preparedPolicy = null; controls(); }); + input.addEventListener('change', policyEdited); } if (acknowledged && pending.get(acknowledged.key) === acknowledged) { pending.delete(acknowledged.key); changed(); } } @@ -393,7 +401,8 @@ if (retained && !retained.ack) notice('The original policy command remains unresolved. This read does not acknowledge it.'); }); } - enabledInput.addEventListener('change', () => { preparedPolicy = null; controls(); }); + function policyEdited() { ++policyEditorRevision; preparedPolicy = null; controls(); } + enabledInput.addEventListener('change', policyEdited); async function preparePolicy() { if (!policy || owner('policy') || policy.unmappedRepositoryCount || !policy.catalog.length) return; const keys = [...catalog.querySelectorAll('input')].filter((item) => item.checked).map((item) => item.dataset.engineeringRepository); @@ -401,6 +410,7 @@ // configured catalog can contain twenty choices. The server still checks. if (keys.length > 8) { notice('Choose at most eight configured repositories. No policy command was sent.'); return; } const expectedGeneration = policy.generation; const active = enabledInput.checked === true; + const editorRevision = policyEditorRevision; return operation(async (observation) => { const actor = await viewer(observation, session); const commandId = text(nextId()); const packet = { commandId, expectedGeneration, @@ -413,6 +423,7 @@ !object(intent.policy) || intent.policy.enabled !== packet.enabled || !Array.isArray(intent.policy.repositories) || intent.policy.repositories.length !== keys.length || new TextEncoder().encode(JSON.stringify({ intent })).byteLength > 131072) throw invalid(); await viewer(observation, actor); + if (editorRevision !== policyEditorRevision) { notice('Policy choices changed. Prepare the displayed policy again before saving.'); return; } preparedPolicy = { actorSubject: actor.subject, body: JSON.stringify({ intent: copy(intent) }) }; notice('Policy change prepared. Save explicitly; its opaque intent is retained but never displayed.'); }); @@ -430,7 +441,7 @@ return states.includes(value.state) && securityValues.includes(value.security); } async function send(retained, observation) { - if (now() < retryAt) { notice('Wait for the server retry delay before explicit recovery.'); return; } + if (retained.ack === null && now() < retryAt.mutation) { notice('Wait for the server mutation retry delay before explicit recovery.'); return; } if (retained.action === 'review' && !reviewEnabled()) throw Object.assign(new Error('review_disabled'), { status: 503 }); const actor = await viewer(observation); if (actor.subject !== retained.actorSubject || (retained.domain === 'ticket' && retained.ticketId !== context.ticketId)) throw invalid(); diff --git a/public/staff-support-ticket.js b/public/staff-support-ticket.js index 141f2d6..608a034 100644 --- a/public/staff-support-ticket.js +++ b/public/staff-support-ticket.js @@ -790,7 +790,7 @@ composeForm.addEventListener('submit', async (event) => { select('#staff-ticket-reload').addEventListener('click', () => { if (!onThisTicket() && (learningPending() || engineeringPending())) { invalidate(); - showStatus('Return to the original ticket address before reloading. An earlier learning action may have completed.', true); + showStatus('Return to the original ticket address before reloading. An earlier retained action may have completed.', true); } else if (!onThisTicket()) window.location.reload(); else void loadTicket(); }); diff --git a/src/support-engineering-controller.test.ts b/src/support-engineering-controller.test.ts index e22cab6..c2f4724 100644 --- a/src/support-engineering-controller.test.ts +++ b/src/support-engineering-controller.test.ts @@ -169,4 +169,15 @@ describe('registered staff controller and engineering panel composition', () => expect(await h.f.rows()).toEqual(committedRows); expect(h.f.engineering.state.modelCalls).toBe(0); }); + + it('identifies a retained engineering action generically when Reload is used from another ticket address', async () => { + const h = await fixture(); h.state.loseEngineering = true; h.control('enroll').fire('click'); + await until(() => !h.control('retry-ticket').hidden && !h.control('retry-ticket').disabled); + const before = h.calls.length; + h.window.location.href = IDENTITY_ISSUER + '/staff/support/ticket/?id=another-fictional-ticket'; + h.node('staff-ticket-reload').fire('click'); + expect(h.calls).toHaveLength(before); + expect(h.node('staff-ticket-status').textContent).toContain('An earlier retained action may have completed.'); + expect(h.node('staff-ticket-status').textContent).not.toContain('learning action'); + }); }); diff --git a/src/support-engineering-review.test.ts b/src/support-engineering-review.test.ts index b18d496..359f0b2 100644 --- a/src/support-engineering-review.test.ts +++ b/src/support-engineering-review.test.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; import { runInNewContext } from 'node:vm'; import { describe, expect, it } from 'vitest'; import { authenticate } from '../worker/src/api-auth'; @@ -21,7 +22,7 @@ async function harness() { const ticket = (await f.engineering.application.readStaffTicket(f.engineering.actors.staff, engineeringTicketId)).ticket; const support = createSupportApi({ ...f.options, application: f.engineering.application, createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); - const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string }[] = []; + const root = new BrowserNode('section'); const calls: { path: string; method: string; body?: string; serverStatus?: number }[] = []; const changes: unknown[] = []; const state = { actor: 'staff' as EngineeringHttpActor, enabled: true, reviewEnabled: true, fault: undefined as ((path: string, response: Response) => Promise) | undefined }; @@ -31,11 +32,13 @@ async function harness() { return new Request(IDENTITY_ISSUER + path, { ...init, headers }); } async function request(path: string, init: RequestInit = {}) { - calls.push({ path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}) }); + const call = { path, method: init.method ?? 'GET', ...(typeof init.body === 'string' ? { body: init.body } : {}), serverStatus: 0 }; + calls.push(call); const original = incoming(path, init); const response = /\/engineering(?:\/|$)/u.test(new URL(original.url).pathname) ? await f.handle(original) : await support(original); if (response === null) throw new Error('Expected an actual registered HTTP adapter'); + call.serverStatus = response.status; await state.fault?.(path, response); if (!response.ok) throw Object.assign(new Error('request_failed'), { status: response.status }); return response.json(); @@ -46,7 +49,7 @@ async function harness() { return { subject: value.link.subject, csrfToken: value.csrfToken }; } const vm: Record = { document: { createElement: (tag: string) => new BrowserNode(tag) }, - AbortController, TextEncoder }; + AbortController, TextEncoder, crypto: { randomUUID } }; runInNewContext(readFileSync(new URL('../public/staff-support-engineering.js', import.meta.url), 'utf8'), vm); const factory = vm.PegmaSupportEngineering as { createPanel(options: unknown): Panel }; const panel = factory.createPanel({ root, request, readSession, @@ -103,6 +106,21 @@ describe('checked human engineering review panel through real SDK and HTTP adapt expect(h.f.engineering.state.creates).toEqual([]); }); + it.each(['invalidate', 'withdraw'] as const)('retires an unsent checked proposal after actual source %s without retaining a stale review', async (action) => { + const h = await harness(); await h.open(); await h.action('proposal'); + const title = h.checked.proposal?.request.bundle.title; + if (title === undefined) throw new Error('Actual checked proposal title missing'); + expect(h.root.textContent).toContain(title); expect(h.node('approve').disabled).toBe(false); + const modelCalls = h.f.engineering.state.modelCalls; + expect(h.node(action).disabled).toBe(false); + await h.action(action); expect(h.writes().at(-1)?.serverStatus).toBe(200); + expect((await h.f.engineering.source()).state).toBe(action === 'withdraw' ? 'withdrawn' : 'held'); + expect(h.root.textContent).not.toContain(title); expect(h.node('approve').disabled).toBe(true); expect(h.node('reject').disabled).toBe(true); + const writes = h.writes().length; await h.action('approve'); await h.action('reject'); + expect(h.writes()).toHaveLength(writes); expect(h.panel.hasPending()).toBe(false); + expect(h.f.engineering.state.modelCalls).toBe(modelCalls); expect(h.f.engineering.state.creates).toEqual([]); + }); + it('retains byte-identical complete command after an actually committed review loses its HTTP acknowledgement', async () => { const h = await harness(); await h.open(); await h.action('proposal'); h.state.fault = async (path, response) => { diff --git a/src/support-engineering-ui.test.ts b/src/support-engineering-ui.test.ts index 5c2174b..a912e2b 100644 --- a/src/support-engineering-ui.test.ts +++ b/src/support-engineering-ui.test.ts @@ -7,7 +7,7 @@ import { IDENTITY_ISSUER } from '../worker/src/identity-api'; import { createSupportApi } from '../worker/src/support-api'; import { engineeringTicketId } from '../worker/src/support-engineering-fixtures'; import { createSupportEngineeringHttpFixture, type EngineeringHttpActor } from '../worker/src/support-engineering-http-fixtures'; -import { BrowserNode } from './test-support-browser'; +import { BrowserNode, browserGate } from './test-support-browser'; interface Panel { showTicket(value: { ticketId: string; revision: number; actorSubject: string }): Promise; @@ -139,6 +139,53 @@ describe('standalone public engineering panel with actual authority adapters', ( expect(JSON.stringify(h.changes)).not.toContain('commandId'); }); + it.each(['repository', 'enabled'] as const)('discards an in-flight prepared policy after the displayed %s choice changes', async (changed) => { + const h = await harness(); h.state.actor = 'both'; await h.open(); await h.action('policy-read'); + const entered = browserGate(); const release = browserGate(); + h.state.fault = async (path, response) => { + if (path.endsWith('/policy/prepare') && response.ok) { entered.resolve(); await release.promise; } + }; + const preparing = h.action('policy-prepare'); + try { + await entered.promise; + if (changed === 'repository') { + const choice = h.root.all().find((item) => item.dataset.engineeringRepository); + if (choice === undefined) throw new Error('Actual configured policy checkbox missing'); + choice.checked = false; choice.fire('change'); + } else { h.field('policy-enabled').checked = false; h.field('policy-enabled').fire('change'); } + } finally { release.resolve(); } + await preparing; expect(h.node('policy-save').disabled).toBe(true); + const posts = h.writes().length; await h.action('policy-save'); expect(h.writes()).toHaveLength(posts); + expect(h.panel.hasPending()).toBe(false); + h.state.fault = undefined; await h.action('policy-prepare'); expect(h.node('policy-save').disabled).toBe(false); + await h.action('policy-save'); + const saved = JSON.parse(h.writes().at(-1)?.body ?? '{}'); + expect(saved.intent.policy.enabled).toBe(changed === 'repository'); + expect(saved.intent.repositoryKeys).toHaveLength(changed === 'repository' ? 1 : 2); + expect(h.panel.hasPending()).toBe(false); + }); + + it('recovers an unknown mutation through its independent quota while a real read Retry-After remains active', async () => { + const h = await harness(); await h.open(); + h.state.fault = async (path, response) => { + if (path.endsWith('/enroll') && response.ok) throw Object.assign(new Error('Synthetic committed enrollment ACK loss'), { status: 503 }); + }; + await h.action('enroll'); const original = h.writes().at(-1)!; const rows = await h.f.rows(); + expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(false); h.state.fault = undefined; + h.state.time = Math.ceil(h.state.time / 30_000) * 30_000; + const limiter = createDurableLimiter(defineRateLimitPolicy({ name: 'public-engineering-independent-read-retry', limit: 1, windowMs: 30_000 }), + h.f.engineering.store, { clock: { now: () => new Date(h.state.time).toISOString() } }); + Object.assign(h.f.options, { readLimiter: limiter }); await limiter.allow(h.f.principals.staff); + await h.panel.refresh(); expect(h.calls.at(-1)?.serverStatus).toBe(429); expect(h.calls.at(-1)?.retryAfter).toBe('30'); + const posts = h.writes().length; await h.action('retry-ticket'); + expect(h.writes()).toHaveLength(posts + 1); expect(h.writes().at(-1)?.body).toBe(original.body); + expect(h.writes().at(-1)?.serverStatus).toBe(200); expect(h.panel.pendingOwners()[0]?.acknowledged).toBe(true); + expect(await h.f.rows()).toEqual(rows); + h.state.time += 30_000; await h.action('retry-ticket'); + expect(h.writes()).toHaveLength(posts + 1); expect(h.panel.hasPending()).toBe(false); + expect(await h.f.rows()).toEqual(rows); + }); + it('honors actual HTTP Retry-After without a premature probe and explicitly recovers the same packet when its deadline elapses', async () => { const h = await harness(); await h.open(); h.state.time = Math.ceil(h.state.time / 30_000) * 30_000; diff --git a/worker/src/support-engineering-handlers.ts b/worker/src/support-engineering-handlers.ts index d51b621..4b67dcc 100644 --- a/worker/src/support-engineering-handlers.ts +++ b/worker/src/support-engineering-handlers.ts @@ -346,7 +346,7 @@ export function createSupportEngineeringHandlers(options: SupportEngineeringHand // No Work, Source, repository catalog or policy pre-read here. A // committed historical ACK must survive changes to those resources. result = stepDto(await awaited((access) => options.runtime().reviewCommand(access, intent.command, - async () => { await current(); }))); + async () => (await current()).access))); } else if (operation === 'enroll') { const packet = exactObject(body, ['commandId', 'expectedRevision']); result = sourceResultDto(await awaited((access) => options.runtime().enroll(access, { ticketId, diff --git a/worker/src/support-engineering-http.d1.test.ts b/worker/src/support-engineering-http.d1.test.ts index 8991a33..b038734 100644 --- a/worker/src/support-engineering-http.d1.test.ts +++ b/worker/src/support-engineering-http.d1.test.ts @@ -9,7 +9,8 @@ import { supportRecords } from '@pegma/support-desk-application'; import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { isPlainObject } from './api-auth'; import { IDENTITY_ISSUER } from './identity-api'; -import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access'; +import { ADMIN_ROLE, APPLICATION_SCOPE, SUPPORT_ROLE } from './support-access'; +import { createSupportEngineeringRuntime } from './support-engineering'; import { createSupportApi } from './support-api'; import { engineeringCanary, engineeringProofReference, engineeringRepositories } from './support-engineering-fixtures'; import { @@ -58,6 +59,7 @@ function meter(backing: D1Database) { function charge(statements: readonly D1PreparedStatement[]) { const budget = scope.getStore(); if (budget === undefined) return; budget.calls += 1; budget.statements += statements.length; + budget.maximumParameters = Math.max(budget.maximumParameters, ...statements.map((statement) => parameters.get(statement) ?? 0)); if (budget.calls > 50 || budget.maximumParameters > 100) { @@ -132,9 +134,9 @@ async function fixture() { identity: f.identity, identityLinkFromClaims: f.options.identityLinkFromClaims, logger: f.options.logger, roleStore: f.host.roleStore, createLimiter: f.host.createLimiter, replyLimiter: f.host.replyLimiter }); - function router(repositories = configuration.repositories) { + function router(repositories = configuration.repositories, reviewEnabled = false) { return createSupportEngineeringRouter({ enabled: () => f.state.enabled, - configuration: { ...configuration, repositories } }); + configuration: { ...configuration, repositories, reviewEnabled: () => reviewEnabled } }); } const defaultRouter = router(); async function invoke(operation: string, incoming: Request, route = defaultRouter) { @@ -211,6 +213,27 @@ async function selection(f: Awaited>) { return { key, catalog, route, chosen, other, packet }; } +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} +async function review(f: Awaited>, decision: 'approve' | 'reject' = 'approve') { + await f.verified(); const work = await f.prepared(); + const route = f.router(f.options.repositories, true); + const response = await f.invoke('review.proposal.read', f.request('proposal', undefined, 'staff', + '?sourceGeneration=' + f.key().sourceGeneration), route); + expect(response.status).toBe(200); const view = engineeringHttpResult(await engineeringHttpObject(response)); + if (!isPlainObject(view.intent) || !isPlainObject(view.intent.command)) throw new Error('Expected actual actor-bound review intent'); + expect(view.approvable).toBe(true); expect(JSON.stringify(view)).not.toContain(engineeringCanary); + expect(JSON.stringify(view)).not.toContain(engineeringProofReference); + expect(new TextEncoder().encode(JSON.stringify(view)).byteLength).toBeLessThanOrEqual(65536); + const intent = structuredClone(view.intent); + if (!isPlainObject(intent.command)) throw new Error('Expected cloned complete command'); + Object.assign(intent.command, { decision }); + return { work, route, body: { intent } }; +} + describe('enabled human engineering router and HTTP over genuine D1', () => { it('enrolls a real legacy source0, keeps its uncertain read forbidden, then accepts exact visible evidence within each request budget', async () => { const f = await fixture(); const ticket = await f.legacyTicket(); const before = await f.rows(); @@ -388,6 +411,80 @@ describe('enabled human engineering router and HTTP over genuine D1', () => { f.budget.assertBounds(); }); + it.each(['approve', 'reject'] as const)('meters actual proposal, %s and receipt-first replay after source withdrawal', async (decision) => { + const f = await fixture(); const prepared = await review(f, decision); const before = await f.rows(); + const modelCalls = f.engineering.state.modelCalls; const request = f.request('review', prepared.body); + const accepted = await f.invoke('review.' + decision + '.commit', await retainedPost(request), prepared.route); + expect(accepted.status).toBe(200); const acknowledgement = await engineeringHttpObject(accepted); + expect(engineeringHttpResult(acknowledgement)).toEqual({ ticketId: prepared.work.ticketId, + sourceGeneration: prepared.work.sourceGeneration, workGeneration: prepared.work.workGeneration + 1, + status: decision === 'approve' ? 'approved' : 'held' }); + const committed = await f.rows(); expect(committed).not.toEqual(before); + expect(committed.filter((row) => row.kind === 'engineering_receipt')).toHaveLength( + before.filter((row) => row.kind === 'engineering_receipt').length + 1); + expect((await f.work()).approval).toMatchObject({ decision, reviewedBy: f.principals.staff }); + await f.engineering.runtime.withdraw(f.engineering.actors.staff, { ticketId: prepared.work.ticketId, + clientCommandId: 'NATIVE-POST-' + decision.toUpperCase() + '-WITHDRAW', reason: 'privacy_withdrawal' }); + f.engineering.state.installationActive = false; f.engineering.metadata.clear(); + const afterWithdrawal = await f.rows(); + const replay = await f.invoke('review.' + decision + '.exact-replay', await retainedPost(request), prepared.route); + expect(replay.status).toBe(200); expect(await engineeringHttpObject(replay)).toEqual(acknowledgement); + expect(await f.rows()).toEqual(afterWithdrawal); expect(f.engineering.state.modelCalls).toBe(modelCalls); + expect(f.engineering.state.creates).toEqual([]); f.budget.assertBounds(); + }); + + it('meters a forged review actor denial before any SDK mutation', async () => { + const f = await fixture(); const prepared = await review(f); const before = await f.rows(); + const body = structuredClone(prepared.body); body.intent.actorId = f.principals.peer; + const response = await f.invoke('review.actor-mismatch', f.request('review', body), prepared.route); + expect(response.status).toBe(403); expect(await engineeringHttpObject(response)).toEqual({ error: 'forbidden' }); + expect(await f.rows()).toEqual(before); expect(f.engineering.state.creates).toEqual([]); f.budget.assertBounds(); + }); + + it.each(['session', 'role'] as const)('meters late %s denial during genuine read-only approval proof without a commit', async (change) => { + const f = await fixture(); const prepared = await review(f); const entered = deferred(); const resume = deferred(); + const ports = f.engineering.ports; const before = await f.rows(); const modelCalls = f.engineering.state.modelCalls; + f.state.runtime = createSupportEngineeringRuntime({ application: f.engineering.application, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, processingEnabled: () => false, + reviewProofs: { serviceAccess: ports.serviceAccess, routing: { resolve: ports.routing.resolve, verify: ports.routing.verify }, + checks: { resolvePolicy: ports.checks.resolvePolicy, verify: ports.checks.verify }, github: { + async getMetadata(...args) { const actual = await ports.github.getMetadata(...args); entered.resolve(); await resume.promise; return actual; }, + } } }); + const pending = f.invoke('review.late-' + change + '-denial', f.request('review', prepared.body), prepared.route); + await Promise.race([entered.promise, pending.then(() => { throw new Error('Expected actual SDK read-only proof boundary'); })]); + // The actual peer revocation is another invocation, outside this request's + // AsyncLocalStorage meter, matching normal separate-request role changes. + try { if (change === 'session') await f.destroy('staff'); else await f.revoke('staff', SUPPORT_ROLE); } + finally { resume.resolve(); } + const response = await pending; expect(response.status).toBe(change === 'session' ? 401 : 403); + expect(await engineeringHttpObject(response)).not.toHaveProperty('result'); expect(await f.rows()).toEqual(before); + expect(f.engineering.state.modelCalls).toBe(modelCalls); expect(f.engineering.state.creates).toEqual([]); f.budget.assertBounds(); + }); + + it('meters closing role denial after actual approval and recovers its receipt after authority restoration', async () => { + const f = await fixture(); const prepared = await review(f); const entered = deferred(); const resume = deferred(); + const modelCalls = f.engineering.state.modelCalls; const request = f.request('review', prepared.body); + f.hooks.commit = async () => { entered.resolve(); await resume.promise; }; + const pending = f.invoke('review.committed-closing-denial', await retainedPost(request), prepared.route); + await Promise.race([entered.promise, pending.then(() => { throw new Error('Expected actual committed SDK transaction'); })]); + const committed = await f.rows(); + try { await f.revoke('staff', SUPPORT_ROLE); } finally { delete f.hooks.commit; resume.resolve(); } + const response = await pending; expect(response.status).toBe(403); + expect(await engineeringHttpObject(response)).not.toHaveProperty('result'); expect(await f.rows()).toEqual(committed); + expect((await f.engineering.application.readEngineeringWork(f.engineering.actors.security, f.key())).status).toBe('approved'); + await f.host.roleStore.grantRoleAssignmentWithAudit({ assignment: { id: 'native-review-restored-support', + principalId: f.principals.staff, role: SUPPORT_ROLE, scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-native-review' }, grantedAtEpochMs: Date.now(), status: 'active', + }, auditEventId: 'native-review-restored-support-audit' }); + f.engineering.state.installationActive = false; f.engineering.metadata.clear(); + const replay = await f.invoke('review.closing-denial.exact-replay', await retainedPost(request), prepared.route); + expect(replay.status).toBe(200); expect(engineeringHttpResult(await engineeringHttpObject(replay))).toEqual({ + ticketId: prepared.work.ticketId, sourceGeneration: prepared.work.sourceGeneration, + workGeneration: prepared.work.workGeneration + 1, status: 'approved' }); + expect(await f.rows()).toEqual(committed); expect(f.engineering.state.modelCalls).toBe(modelCalls); + expect(f.engineering.state.creates).toEqual([]); f.budget.assertBounds(); + }); + it('rechecks actual stored Support and Admin role revocation on successive private router requests', async () => { const f = await fixture(); const ticket = await f.legacyTicket(); expect((await f.invoke('enroll.before-role-revocation', f.request('enroll', { diff --git a/worker/src/support-engineering-review.test.ts b/worker/src/support-engineering-review.test.ts index 93d7ce9..a1cca3c 100644 --- a/worker/src/support-engineering-review.test.ts +++ b/worker/src/support-engineering-review.test.ts @@ -85,6 +85,55 @@ describe('human engineering proposal view and exact public review command', () = expect(await f.rows()).toEqual(rows); }); + it('uses explicit read-only proof ports for trusted direct approval and receipt-first recovery', async () => { + const { f, work } = await prepared(); const ports = f.engineering.ports; + const runtime = createSupportEngineeringRuntime({ application: f.engineering.application, clock: f.engineering.clock, + staffAccess: { resolve: (id) => f.resolve(id) }, processingEnabled: () => false, + reviewProofs: { serviceAccess: ports.serviceAccess, routing: { resolve: ports.routing.resolve, verify: ports.routing.verify }, + checks: { resolvePolicy: ports.checks.resolvePolicy, verify: ports.checks.verify }, github: { getMetadata: ports.github.getMetadata } } }); + if (work.proposal === undefined) throw new Error('Expected actual prepared proposal'); + const access = await f.resolve(f.principals.staff); if (access === null) throw new Error('Expected current staff'); + const packet = { ...f.key(), clientCommandId: 'DIRECT-READ-ONLY-PROOFS', expectedWorkGeneration: work.workGeneration, + proposalHash: work.proposal.proposalHash, decision: 'approve' as const }; + const modelCalls = f.engineering.state.modelCalls; + const accepted = await runtime.reviewProposal(access, packet); + expect(accepted.status).toBe('approved'); expect((await f.work()).approval?.reviewedBy).toBe(f.principals.staff); + expect(await runtime.scanCandidates({ limit: 1 })).toEqual({ outcome: 'held', reason: 'engineering_disabled' }); + const rows = await f.rows(); f.engineering.state.installationActive = false; f.engineering.metadata.clear(); + expect(await runtime.reviewProposal(access, structuredClone(packet))).toEqual(accepted); + expect(await f.rows()).toEqual(rows); expect(f.engineering.state.modelCalls).toBe(modelCalls); expect(f.engineering.state.creates).toEqual([]); + }); + + it('retains fresh-role enforcement for legacy void review callbacks', async () => { + const { f, packet } = await prepared(); const before = await f.rows(); + if (!('command' in packet.intent) || typeof packet.intent.command !== 'object' || packet.intent.command === null) + throw new Error('Expected actual complete command'); + const current = await f.resolve(f.principals.staff); if (current === null) throw new Error('Expected current staff'); + const input = packet.intent.command as Parameters[1]; + await expect(f.state.runtime.reviewCommand(current, input, async () => { + await f.revoke('staff', SUPPORT_ROLE); + })).rejects.toThrow(); + expect(await f.rows()).toEqual(before); expect((await f.work()).approval).toBeUndefined(); + }); + + it('synchronously rejects a changed original caller principal after the real late authority check', async () => { + const f = await createSupportEngineeringHttpFixture(); + const current = await f.resolve(f.principals.both); if (current === null) throw new Error('Expected current Admin + Support'); + const original = { ...current }; const actual = f.engineering.application; let asserted = false; + const runtime = createSupportEngineeringRuntime({ application: { ...actual, + disableEngineeringExports: (access, packet, options) => actual.disableEngineeringExports(access, packet, { + ...options, verifyBeforeCommit: async () => { + const proof = await options?.verifyBeforeCommit?.(); + original.principalId = 'synthetic-changed-original-caller'; + return () => { asserted = true; return proof?.() ?? true; }; + }, + }), + }, clock: f.engineering.clock, staffAccess: { resolve: (id) => f.resolve(id) }, processingEnabled: () => false }); + const rows = await f.policyRows(); + await expect(runtime.disableExports(original, { clientCommandId: 'BOUND-ORIGINAL-PRINCIPAL', expectedGeneration: 1 })).rejects.toThrow(); + expect(asserted).toBe(true); expect(await f.policyRows()).toEqual(rows); + }); + it('missing read-only proof composition holds new approval without model calls or mutations', async () => { const { f, packet } = await prepared(); const rows = await f.rows(); const calls = f.engineering.state.modelCalls; diff --git a/worker/src/support-engineering.ts b/worker/src/support-engineering.ts index 3927a7a..004fe4d 100644 --- a/worker/src/support-engineering.ts +++ b/worker/src/support-engineering.ts @@ -133,6 +133,8 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti if (controller.signal.aborted || performance.now() - started >= staffOperationMilliseconds) throw new SupportEngineeringUnavailableError(); }; + // Live authority is resolved asynchronously before commit. This final + // synchronous fence binds the original caller reference and deadline. const assertCurrent = (): true => { ensure(); if (original.principalId !== bound.principalId) @@ -217,14 +219,29 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti } async function reviewCommand(access: AccessContext, input: ReviewEngineeringProposalCommand, - beforeCommit?: () => Promise) { + beforeCommit?: () => Promise) { const packet = structuredClone(input); + const ceiling = structuredClone(access); if (beforeCommit !== undefined && typeof beforeCommit !== 'function') throw new TypeError('Expected an engineering browser commit guard'); - return staff(access, supportPermissions.engineeringReview, async (current, refresh, signal) => { + return staff(access, supportPermissions.engineeringReview, async (current, refresh, signal, assertCurrent) => { const reviewing = createSupportDeskEngineering(reviewBase); return reviewing.reviewProposal(current, packet, { signal, - verifyBeforeCommit: async () => { await refresh(); await beforeCommit?.(); }, + verifyBeforeCommit: async () => { + // The complete original-browser fence already fetches current roles + // and Identity. Trusted direct callers use the runtime resolver. + const observed = await beforeCommit?.(); + const fresh = observed === undefined ? await refresh() : observed; + assertCurrent(); + if (fresh.principalId !== ceiling.principalId) + throw new SupportDeskAuthorizationError(supportPermissions.engineeringReview); + const bounded: AccessContext = { principalId: ceiling.principalId, policyVersion: fresh.policyVersion, + roles: fresh.roles.filter((entry) => ceiling.roles.includes(entry)), + entitlements: fresh.entitlements.filter((entry) => ceiling.entitlements.includes(entry)), + permissions: fresh.permissions.filter((entry) => ceiling.permissions.includes(entry)) }; + for (const required of [supportPermissions.engineeringReview, supportPermissions.queueRead]) + if (!hasPermission(bounded, required)) throw new SupportDeskAuthorizationError(required); + }, }); }); } @@ -253,7 +270,7 @@ export function createSupportEngineeringRuntime(options: SupportEngineeringRunti reviewProposal: (access: AccessContext, input: EngineeringReviewPacket) => command(access, supportPermissions.engineeringReview, 'review', input.ticketId, input, async (current, packet, refresh, signal) => { - return coordinator.reviewProposal(current, packet, { signal, + return createSupportDeskEngineering(reviewBase).reviewProposal(current, packet, { signal, verifyBeforeCommit: async () => { await refresh(); }, }); }), diff --git a/worker/src/support-learning-ports.ts b/worker/src/support-learning-ports.ts index 28a423a..e134ba5 100644 --- a/worker/src/support-learning-ports.ts +++ b/worker/src/support-learning-ports.ts @@ -40,7 +40,7 @@ export type DirectLearningKnowledge = Pick< >; /** - * Support 0.2.5 uses the same exact KB 0.1.5 public contracts as this host. + * Support 0.2.6 uses the same exact KB 0.1.5 public contracts as this host. * Forward the narrow capability surface and preserve actual error identity. */ export function createSupportLearningKnowledgePort( From 23fcfb7c194788af37298b033b1baced7bdbadd6 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 20:48:43 -0500 Subject: [PATCH 5/7] Adopt verified Support Desk 0.2.7 and Knowledge Base 0.1.6 --- docs/KNOWLEDGE_COMPOSITION.md | 21 +++--- docs/SUPPORT_ASSISTANT_STAGE.md | 6 +- docs/SUPPORT_COMPOSITION.md | 28 ++++---- docs/SUPPORT_ENGINEERING.md | 2 +- docs/SUPPORT_LEARNING.md | 12 ++-- package.json | 18 ++--- pnpm-lock.yaml | 114 ++++++++++++++++---------------- 7 files changed, 101 insertions(+), 100 deletions(-) diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index 41e1820..959cf79 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -8,7 +8,7 @@ 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.5`, over its existing Identity, +`@pegma/knowledge-base-*` packages at `0.1.6`, over its existing Identity, Sessions, stored roles and D1 Store. The public catalog at `/api/mcp` remains separate from protected article authoring. @@ -21,23 +21,24 @@ at signed source passed independent exact-byte, signature/provenance and registry-consumer verification. Existing Identity and Support Desk keep their `@pegma/rate-limit@0.2.0` dependency. The current host selects all five Support -Desk packages at `0.2.6`, including the optional AI coordinator. The separate +Desk packages at `0.2.7`, including the optional AI coordinator. The separate synthetic stage remains default-disabled. The -[verified Support Desk `0.2.6` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.6) -pins its optional AI dependency on KB application/contracts `0.1.5`. +[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`. The learning port forwards actual KB errors without the obsolete `0.1.2` constructor alias or class-translation shim. The earlier `0.2.1` / nested `0.1.2` assembly and its failed isolated production-layout diagnostic remain historical; they neither establish nor replace current-graph qualification. -All four exact KB `0.1.5` packages are installed in the manifest and lockfile. -The answering read-batching release retains the shared report factory and -governed authoring-context/report-query APIs. Its producer verification covers +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 original registry bytes, signatures/source provenance and public-consumer checks at signed source -[`6dae20df8dace50ad961d9c5fe8d28c90bf4918f`](https://github.com/pegma-dev/knowledge-base/commit/6dae20df8dace50ad961d9c5fe8d28c90bf4918f). -[Verified KB `0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5). +[`b2946e149078e0ef460f970c2271c196ea9fc759`](https://github.com/pegma-dev/knowledge-base/commit/b2946e149078e0ef460f970c2271c196ea9fc759). +[Verified KB `0.1.6` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6). The historical [verified `0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) @@ -59,7 +60,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.5`, +The current manifest and lockfile pin released KB `0.1.6`, `@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 diff --git a/docs/SUPPORT_ASSISTANT_STAGE.md b/docs/SUPPORT_ASSISTANT_STAGE.md index cf7959f..41ae20d 100644 --- a/docs/SUPPORT_ASSISTANT_STAGE.md +++ b/docs/SUPPORT_ASSISTANT_STAGE.md @@ -51,8 +51,8 @@ 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.6` with direct Knowledge Base -`0.1.5`; [package.json](../package.json) is authoritative. +The current package selection is Support Desk `0.2.7` with direct Knowledge Base +`0.1.6`; [package.json](../package.json) is authoritative. From the repository root: @@ -90,7 +90,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.6` graph. Current host +That checkpoint does not qualify the current `0.2.7` 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 2aabe98..6775838 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -17,11 +17,11 @@ provider and customer activation retain their acceptance gates. See the Exact published versions: -- `@pegma/support-desk-application@0.2.6` -- `@pegma/support-desk-contracts@0.2.6` -- `@pegma/support-desk-core@0.2.6` -- `@pegma/support-desk-templates@0.2.6` -- `@pegma/support-desk-ai@0.2.6` (optional coordinator) +- `@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) - `@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) @@ -29,10 +29,10 @@ 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.5`; the host selects all four KB packages at that version. +and contracts `0.1.6`; 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.6` release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.6), -[verified KB `0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5). +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). Peers already present on the host: `@pegma/storage-core@0.4.0`, `@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.2.1`, @@ -47,7 +47,7 @@ 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.6` host graph. Current host +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 @@ -286,16 +286,16 @@ invocation. ## Optional resolution learning -The current source selects all five published Support Desk `0.2.6` packages -with the four direct KB `0.1.5` packages. AI `0.2.6` also declares exact KB -`0.1.5` dependencies. The public forwarding port preserves KB error instances; +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; 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.6` APIs. The earlier +use the published, strictly verified Support Desk `0.2.7` APIs. 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 @@ -368,7 +368,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.6` selection; omission remains monolithic. The preparation attempt retrieves authorized sources and records a +`0.2.7` selection; omission remains monolithic. The preparation attempt retrieves authorized sources and records a bounded no-call request without reserving paid usage. Only its durably acknowledged finish returns `prepared`. The host must return and schedule a genuinely later physical invocation at or after `nextAttemptAt`, never loop or diff --git a/docs/SUPPORT_ENGINEERING.md b/docs/SUPPORT_ENGINEERING.md index e49da1f..f9d751d 100644 --- a/docs/SUPPORT_ENGINEERING.md +++ b/docs/SUPPORT_ENGINEERING.md @@ -4,7 +4,7 @@ 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.6`. +the five published Support Desk packages at exact version `0.2.7`. The [runtime](../worker/src/support-engineering.ts), [HTTP adapter](../worker/src/support-engineering-handlers.ts), diff --git a/docs/SUPPORT_LEARNING.md b/docs/SUPPORT_LEARNING.md index 07c4cf8..3ba6450 100644 --- a/docs/SUPPORT_LEARNING.md +++ b/docs/SUPPORT_LEARNING.md @@ -15,10 +15,10 @@ activation evidence. ## Packages and authority -The host selects all five published Support Desk packages at **0.2.6** and its -four direct Knowledge Base packages at **0.1.5**. The qualified -[Support 0.2.6 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.6) -also uses exact KB **0.1.5** public contracts. The +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 [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,7 +29,7 @@ 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.6 graph. +ordinary fixture passes nor that failure qualifies the current 0.2.7 graph. The current [host policy](../worker/src/support-access.ts) grants four human learning permissions through the actual stored, audited **Support** role: @@ -325,7 +325,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.6` +passed 1,125 tests locally and in CI. It does not qualify the current `0.2.7` graph. Current host validation, review and deployment acceptance remain pending. Relevant executable sources are the diff --git a/package.json b/package.json index 32a95e2..0db85af 100644 --- a/package.json +++ b/package.json @@ -32,10 +32,10 @@ "@pegma/authorization-storage": "0.4.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", - "@pegma/knowledge-base-application": "0.1.5", - "@pegma/knowledge-base-contracts": "0.1.5", - "@pegma/knowledge-base-core": "0.1.5", - "@pegma/knowledge-base-mcp": "0.1.5", + "@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/logger-cloudflare": "^0.1.1", "@pegma/logger-datadog": "^0.1.1", "@pegma/logger-tee": "^0.1.1", @@ -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.6", - "@pegma/support-desk-application": "0.2.6", - "@pegma/support-desk-contracts": "0.2.6", - "@pegma/support-desk-core": "0.2.6", - "@pegma/support-desk-templates": "0.2.6", + "@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/webhooks": "0.1.1", "agents": "^0.20.1", "zod": "^4.4.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 02c39ee..5522bc8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,17 +39,17 @@ importers: specifier: 0.1.2 version: 0.1.2 '@pegma/knowledge-base-application': - specifier: 0.1.5 - version: 0.1.5 + specifier: 0.1.6 + version: 0.1.6 '@pegma/knowledge-base-contracts': - specifier: 0.1.5 - version: 0.1.5 + specifier: 0.1.6 + version: 0.1.6 '@pegma/knowledge-base-core': - specifier: 0.1.5 - version: 0.1.5 + specifier: 0.1.6 + version: 0.1.6 '@pegma/knowledge-base-mcp': - specifier: 0.1.5 - version: 0.1.5 + specifier: 0.1.6 + version: 0.1.6 '@pegma/logger-cloudflare': specifier: ^0.1.1 version: 0.1.1 @@ -81,20 +81,20 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.6 - version: 0.2.6 + specifier: 0.2.7 + version: 0.2.7 '@pegma/support-desk-application': - specifier: 0.2.6 - version: 0.2.6 + specifier: 0.2.7 + version: 0.2.7 '@pegma/support-desk-contracts': - specifier: 0.2.6 - version: 0.2.6 + specifier: 0.2.7 + version: 0.2.7 '@pegma/support-desk-core': - specifier: 0.2.6 - version: 0.2.6 + specifier: 0.2.7 + version: 0.2.7 '@pegma/support-desk-templates': - specifier: 0.2.6 - version: 0.2.6 + specifier: 0.2.7 + version: 0.2.7 '@pegma/webhooks': specifier: 0.1.1 version: 0.1.1 @@ -1179,20 +1179,20 @@ packages: resolution: {integrity: sha512-r8AsVTnwCSBU2LZZjieW5FgIJ2TUWi5DlU9kp+4tuaWDFfl85EezkD6F5omAFjTnaFqCRN1T2d/KsHoESarB2A==} engines: {node: '>=22'} - '@pegma/knowledge-base-application@0.1.5': - resolution: {integrity: sha512-tH9Hw+BSVmLzQPzdyhK9YaiAthWEwgYuG0Ef2kxT7FohMqYq4iaW/vDOHQdGa/gIMAlULqS/p0vCOPr7rPQfdA==} + '@pegma/knowledge-base-application@0.1.6': + resolution: {integrity: sha512-i7rD3uWz4XSuii7Kx3Y2l1tn3TK6WHfjBpJxkmdxYLVes2cBYaaQ3KgCjSbU5m0W01w0SmDPDOLsvFWdHGFDow==} engines: {node: '>=22'} - '@pegma/knowledge-base-contracts@0.1.5': - resolution: {integrity: sha512-TgK0HNLlBJ6a3EYS0aBmF+UO9v2ykK0xVYPo51Cmcn1ET15Fj90w3dpyzBX7dRomi1aGBAW3FX4X+djrayqbzg==} + '@pegma/knowledge-base-contracts@0.1.6': + resolution: {integrity: sha512-/jntfNSu0OGrDpaEg+Mhi1kv9ek8thbEBObT9WYmeo6laPr4jEmYqiLi+zBT52SinMmnGEUGU3f0dzeM9i2CQQ==} engines: {node: '>=22'} - '@pegma/knowledge-base-core@0.1.5': - resolution: {integrity: sha512-ZuaXkuuyuMN+n1xGfPcXvInvwdNsCQpjo8m9GhFmc0fu1reisj0oeVzF4i9DvYbhHqMA6QoZgIUBUCVijLd9ug==} + '@pegma/knowledge-base-core@0.1.6': + resolution: {integrity: sha512-VKK5r8vNed9b2BZJQTAf68faW6mjjR/SLCooOtLvQsw5xhYjvNwfkri2cqPLVSZ44xMQXNRlx1nD1DfddNkoKw==} engines: {node: '>=22'} - '@pegma/knowledge-base-mcp@0.1.5': - resolution: {integrity: sha512-IBdsjzxVhGeMGViJpWLwzKTXGr2iOLeVylaBRnT9Bn+oSeAKxe1yMez+/eg7Nu19Ru/bweIrmUb0JuqIxem0Nw==} + '@pegma/knowledge-base-mcp@0.1.6': + resolution: {integrity: sha512-e1LIDIElZPa+JyyuYrw0VmqTzK4OULmxQBI1eZWIupu6PonDvIRQLbMSlI8KPFEGRuoMnEP3IbXoQCzmtf//aA==} engines: {node: '>=22'} '@pegma/logger-cloudflare@0.1.1': @@ -1239,24 +1239,24 @@ packages: resolution: {integrity: sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==} engines: {node: '>=22'} - '@pegma/support-desk-ai@0.2.6': - resolution: {integrity: sha512-KEYGWcLonL+m4IUJrbfCFFzXm2l7CLBzRAUdAu3jX99OU0+iR+dqjF/sWaj61JDLj2s1T3VwAGLd1i00+RAYKg==} + '@pegma/support-desk-ai@0.2.7': + resolution: {integrity: sha512-Ra6k3a0JEERXeIfDbRlUMOa9F4/o4W0l54yjMDBcoM16tjUUmGrifc8oxWrSNir0p7a8TLyevVkfNxs+T6szUA==} engines: {node: '>=22'} - '@pegma/support-desk-application@0.2.6': - resolution: {integrity: sha512-jqecCURuVcasRZGXFdwiDtQk3yM/P03Ij/JmQovw9nYrhXOzGeIYB3+Ro19IDKgMkH+XF4MghVFUZ+b7BPMDIg==} + '@pegma/support-desk-application@0.2.7': + resolution: {integrity: sha512-t0asEJYY7Xmndz1GTp/7j5RUVzXYIs0a8uZ+hRUq5fwgPmqfMoPVJ9xSA7xPhbhDtZUq3B2tRD4tG91Fn6XA0g==} engines: {node: '>=22'} - '@pegma/support-desk-contracts@0.2.6': - resolution: {integrity: sha512-blhLS3iUXK0dDz2k/uw2fN0as2Tnvjx/XLMc8OGg/0Njiox+0YHdotYewx/yIrzI6XQkUWBzz/CyVyNI+ObUAA==} + '@pegma/support-desk-contracts@0.2.7': + resolution: {integrity: sha512-/9Zz473fyItEjJWLEzyXBzIR2poCqhvsqwdxU1yQOchy2++E9fdj/ErklGmea4VouUdnouhx2mRpIJJ0+gn+0A==} engines: {node: '>=22'} - '@pegma/support-desk-core@0.2.6': - resolution: {integrity: sha512-Gc5L7/mniQnOsi+sLGYDINEgXJE6ilgC3ghleQ6QIYNfOMJ94WIZ1v/mEI7w9kRPBjsk+TISxRAiQPjRaQC9Ow==} + '@pegma/support-desk-core@0.2.7': + resolution: {integrity: sha512-3+8e2ZS1J2om0ePn2ioQ1wpqdY5f9NA6svEPl4RPVpmCdXwwiJxLbocLHtjcGJNbW37MnyOZKY97X5jdrMXSAw==} engines: {node: '>=22'} - '@pegma/support-desk-templates@0.2.6': - resolution: {integrity: sha512-94ZgKYa4K4gu//7aHohyJhjfDbX+hUJPOKCIL9XbhdAsX5FZK+uXTrDszGZwJiO4aGSvZUrQ/Ju5cDDIyhW/7w==} + '@pegma/support-desk-templates@0.2.7': + resolution: {integrity: sha512-4mDF2e4ZzYjSlIQYu4FWpjr1cUUU2N7jJUfGTTMnYG6Gf5UN45j7q7ueOFJjlcgC7D0+TqKludaKDYZf0nqTjg==} engines: {node: '>=22'} '@pegma/webhooks@0.1.1': @@ -4189,31 +4189,31 @@ snapshots: unicode-case-folding: 1.1.1 unorm: 1.6.0 - '@pegma/knowledge-base-application@0.1.5': + '@pegma/knowledge-base-application@0.1.6': dependencies: '@pegma/audit': 0.2.0 '@pegma/authorization-core': 0.4.0 - '@pegma/knowledge-base-contracts': 0.1.5 - '@pegma/knowledge-base-core': 0.1.5 + '@pegma/knowledge-base-contracts': 0.1.6 + '@pegma/knowledge-base-core': 0.1.6 '@pegma/spine': 0.1.2 '@pegma/storage-core': 0.4.0 - '@pegma/knowledge-base-contracts@0.1.5': + '@pegma/knowledge-base-contracts@0.1.6': dependencies: '@pegma/spine': 0.1.2 - '@pegma/knowledge-base-core@0.1.5': + '@pegma/knowledge-base-core@0.1.6': dependencies: - '@pegma/knowledge-base-contracts': 0.1.5 + '@pegma/knowledge-base-contracts': 0.1.6 - '@pegma/knowledge-base-mcp@0.1.5': + '@pegma/knowledge-base-mcp@0.1.6': 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.5 - '@pegma/knowledge-base-contracts': 0.1.5 - '@pegma/knowledge-base-core': 0.1.5 + '@pegma/knowledge-base-application': 0.1.6 + '@pegma/knowledge-base-contracts': 0.1.6 + '@pegma/knowledge-base-core': 0.1.6 zod: 4.6.7 transitivePeerDependencies: - supports-color @@ -4260,33 +4260,33 @@ snapshots: '@pegma/storage-core@0.4.0': {} - '@pegma/support-desk-ai@0.2.6': + '@pegma/support-desk-ai@0.2.7': dependencies: '@pegma/authorization-core': 0.4.0 - '@pegma/knowledge-base-application': 0.1.5 - '@pegma/knowledge-base-contracts': 0.1.5 + '@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.6 + '@pegma/support-desk-application': 0.2.7 - '@pegma/support-desk-application@0.2.6': + '@pegma/support-desk-application@0.2.7': 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.6 - '@pegma/support-desk-core': 0.2.6 + '@pegma/support-desk-contracts': 0.2.7 + '@pegma/support-desk-core': 0.2.7 - '@pegma/support-desk-contracts@0.2.6': + '@pegma/support-desk-contracts@0.2.7': dependencies: '@pegma/spine': 0.1.2 - '@pegma/support-desk-core@0.2.6': + '@pegma/support-desk-core@0.2.7': dependencies: - '@pegma/support-desk-contracts': 0.2.6 + '@pegma/support-desk-contracts': 0.2.7 - '@pegma/support-desk-templates@0.2.6': {} + '@pegma/support-desk-templates@0.2.7': {} '@pegma/webhooks@0.1.1': dependencies: From c784b16e09ec6649354f3602c9d5ac529cd2cc03 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 21:05:45 -0500 Subject: [PATCH 6/7] Report actual composed package versions in health and guides --- README.md | 9 +++--- worker/README.md | 6 ++-- worker/src/index.ts | 4 +-- .../support-engineering-composition.test.ts | 28 +++++++++++++++++++ worker/src/support-learning-ports.ts | 2 +- 5 files changed, 38 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 8bcd598..5541cba 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,10 @@ 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 - `@pegma/storage-cloudflare-d1` and exact `@pegma/sessions@0.1.0` today. - Identity and its Authorization adapter remain fail-closed injected ports - until their first exact public versions can replace the release boundary in - `worker/src/identity-runtime.ts`. +- The **portability exhibit**: the account API composes exact + `@pegma/storage-cloudflare-d1@0.4.7`, `@pegma/sessions@0.2.1`, + `@pegma/identity@0.1.2`, and `@pegma/authorization-identity@0.4.0` + through `worker/src/identity-runtime.ts`. - **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/worker/README.md b/worker/README.md index 1201a59..aad4bf2 100644 --- a/worker/README.md +++ b/worker/README.md @@ -97,7 +97,7 @@ The queue and dead-letter queue are provisioned in the deployment account. The account boundary is fixed to issuer `https://pegma.dev` and WebAuthn RP ID `pegma.dev`. Cloudflare D1 is consumed only through -`@pegma/storage-cloudflare-d1`; `@pegma/sessions@0.2.0` stores SHA-256-hashed +`@pegma/storage-cloudflare-d1`; `@pegma/sessions@0.2.1` stores SHA-256-hashed opaque session identifiers. The browser receives a cryptographically random `__Host-pegma_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, and `Path=/`. @@ -247,7 +247,7 @@ public acknowledgement endpoint. ## Support Desk composition -Authenticated product feedback composes exact `0.2.6` versions of +Authenticated product feedback composes exact `0.2.7` versions of `@pegma/support-desk-contracts`, `@pegma/support-desk-core`, `@pegma/support-desk-application`, and `@pegma/support-desk-templates` over the same `IDENTITY_DB` D1 binding. Support Desk collections @@ -258,7 +258,7 @@ via AccessContext defaults (not a paid entitlement). Categories: `feedback`, `bug`, `feature_request`, `documentation`, `question`. Subject marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/ticket/?id=…`. -The optional `@pegma/support-desk-ai@0.2.6` package is installed for the +The optional `@pegma/support-desk-ai@0.2.7` package is installed for the [isolated scripted answering stage](../docs/SUPPORT_ASSISTANT_STAGE.md). The earlier public `0.2.5` graph passed the 1,125-test local/CI [adoption checkpoint](../docs/KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint); diff --git a/worker/src/index.ts b/worker/src/index.ts index d30ae2e..c0b5082 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -245,7 +245,7 @@ return { probe: 'disabled' | 'ok' | 'fail'; } = { storage: 'cloudflare-d1', - packages: '@pegma/support-desk-application@0.2.6', + packages: '@pegma/support-desk-application@0.2.7', probe: 'disabled', }; if (supportHealthProbeEnabled(env)) { @@ -278,7 +278,7 @@ return { }), createDetailCheck('identity', { storage: 'cloudflare-d1', - sessions: '@pegma/sessions@0.2.0', + sessions: '@pegma/sessions@0.2.1', runtime: '@pegma/identity@0.1.2', authorizationAdapter: '@pegma/authorization-identity@0.4.0', emailDelivery: diff --git a/worker/src/support-engineering-composition.test.ts b/worker/src/support-engineering-composition.test.ts index c28941c..0268dcd 100644 --- a/worker/src/support-engineering-composition.test.ts +++ b/worker/src/support-engineering-composition.test.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; import type { Clock } from '@pegma/spine'; import { createSupportApi } from './support-api'; @@ -25,6 +26,33 @@ async function fixture(clock?: Clock) { } describe('optional public engineering root composition', () => { + it('reports the current package pins through the normal health entrypoint', async () => { + const { dependencies } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')); + const worker = createWorker(); + const env = {} as Parameters[1]; + const pending: Promise[] = []; + const unavailable = (): never => { throw new Error('Health detail must not access context authority.'); }; + const context: ExecutionContext = { + waitUntil(promise) { pending.push(promise); }, + passThroughOnException: unavailable, + props: {}, + get exports(): Cloudflare.Exports { return unavailable(); }, + get tracing(): Tracing { return unavailable(); }, + abort: unavailable, + }; + const response = await worker.fetch(new Request('https://pegma.dev/api/health'), env, context); + await Promise.all(pending); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ checks: { + supportDesk: { detail: { packages: '@pegma/support-desk-application@' + dependencies['@pegma/support-desk-application'] } }, + identity: { detail: { + sessions: '@pegma/sessions@' + dependencies['@pegma/sessions'], + runtime: '@pegma/identity@' + dependencies['@pegma/identity'], + authorizationAdapter: '@pegma/authorization-identity@' + dependencies['@pegma/authorization-identity'], + } }, + } }); + }); + it.each(['absent', 'flag-only', 'false', 'throwing'] as const)('keeps %s entry composition OFF before any production dependencies', async (mode) => { const configuration = { application: { enabled: true }, repositories: [] }; const options = mode === 'absent' ? {} : mode === 'flag-only' ? { enabled: () => true } diff --git a/worker/src/support-learning-ports.ts b/worker/src/support-learning-ports.ts index e134ba5..7ded95c 100644 --- a/worker/src/support-learning-ports.ts +++ b/worker/src/support-learning-ports.ts @@ -40,7 +40,7 @@ export type DirectLearningKnowledge = Pick< >; /** - * Support 0.2.6 uses the same exact KB 0.1.5 public contracts as this host. + * Support 0.2.7 uses the same exact KB 0.1.6 public contracts as this host. * Forward the narrow capability surface and preserve actual error identity. */ export function createSupportLearningKnowledgePort( From 97195a0f15f3ea671c264ccaa01daa4fe02ace77 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 21:36:40 -0500 Subject: [PATCH 7/7] Align executable recipe metadata with its installed package graph --- evals/assembly-eval.test.ts | 17 ++--- src/data/compile-catalog.test.ts | 116 ++++++++++++++++++++++++++++++- src/data/recipe-backlog.ts | 12 ++-- 3 files changed, 130 insertions(+), 15 deletions(-) diff --git a/evals/assembly-eval.test.ts b/evals/assembly-eval.test.ts index 4f3a71a..7987b80 100644 --- a/evals/assembly-eval.test.ts +++ b/evals/assembly-eval.test.ts @@ -14,15 +14,16 @@ const NO_STAGES: Record = Object.fromEntries( ); /** - * Deterministic released-version fixture for recipe/catalog evaluations. - * The site's manifest/lockfile define its separate installed graph; these - * recipe pins are not a claim about that graph. Never hits the network. + * Deterministic publication data for recipe/catalog evaluations. Current + * CI-executed recipe dependencies match their root-resolved imports; other + * component releases remain independent fixture data. Never hits the network + * or claims that every live catalog package is ready. */ const EVAL_NPM: Record = { '@pegma/spine': '0.1.1', '@pegma/storage-core': '0.4.0', '@pegma/storage-azure-tables': '0.4.0', - '@pegma/storage-cloudflare-d1': '0.4.6', + '@pegma/storage-cloudflare-d1': '0.4.7', '@pegma/storage-dynamodb': '0.4.5', '@pegma/storage-blobs': '0.1.0', '@pegma/storage-azure-blob': '0.1.0', @@ -38,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.1.1', - '@pegma/support-desk-core': '0.1.1', - '@pegma/support-desk-application': '0.1.1', + '@pegma/support-desk-contracts': '0.2.7', + '@pegma/support-desk-core': '0.2.7', + '@pegma/support-desk-application': '0.2.7', '@pegma/support-desk-templates': '0.1.1', '@pegma/webhooks': '0.1.1', - '@pegma/sessions': '0.2.0', + '@pegma/sessions': '0.2.1', '@pegma/mail': '0.1.1', '@pegma/billing-core': '0.1.1', '@pegma/billing-stripe': '0.1.1', diff --git a/src/data/compile-catalog.test.ts b/src/data/compile-catalog.test.ts index b9ca31e..169696e 100644 --- a/src/data/compile-catalog.test.ts +++ b/src/data/compile-catalog.test.ts @@ -1,11 +1,17 @@ +import { existsSync, readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; import { clearNpmVersionCache, compileCompositionCatalog, } from './compile-catalog'; -import { CATALOG_SCHEMA_VERSION } from './catalog-schema'; +import { + CATALOG_SCHEMA_VERSION, + parsePackageSpecifier, + recipePackagesReady, +} from './catalog-schema'; import { components, SNAPSHOT_DATE } from './components'; import { RECIPE_BACKLOG } from './recipe-backlog'; +import { getRecipe, planComposition } from './mcp-tools'; const FIXED_AT = '2026-07-29T00:00:00.000Z'; /** Empty stage map → no GitHub plan fetches in unit tests. */ @@ -31,6 +37,114 @@ function compile(npm: Record) { } describe('compileCompositionCatalog', () => { + it.each([ + { + id: 'cf-passkey-accounts', + source: '../../recipes/cf-passkey-accounts/composition.ts', + imports: ['@pegma/sessions'], + pins: ['@pegma/sessions', '@pegma/storage-cloudflare-d1'], + }, + { + id: 'support-queue-slice', + source: '../../recipes/bench-ticket/composition.ts', + imports: ['@pegma/sessions', '@pegma/support-desk-application'], + pins: [ + '@pegma/sessions', + '@pegma/support-desk-application', + '@pegma/support-desk-core', + '@pegma/support-desk-contracts', + ], + }, + ])( + 'ties the current $id fixture and its catalog pins to the installed root composition', + async ({ id, source, imports, pins }) => { + const { dependencies } = JSON.parse( + readFileSync(new URL('../../package.json', import.meta.url), 'utf8'), + ); + const fixtureUrl = new URL(source, import.meta.url); + const fixture = readFileSync(fixtureUrl, 'utf8'); + expect(existsSync(new URL('./package.json', fixtureUrl))).toBe(false); + for (const name of imports) { + expect(fixture).toContain("from '" + name + "'"); + const installed = JSON.parse( + readFileSync(new URL('../package.json', import.meta.resolve(name)), 'utf8'), + ); + expect(installed).toMatchObject({ name, version: dependencies[name] }); + } + const catalog = await compile({}); + const recipe = getRecipe(catalog, id); + expect(recipe?.fixture.status).toBe('green'); + for (const name of pins) expect(recipe?.packages).toContain(name + '@' + dependencies[name]); + if (id === 'cf-passkey-accounts') { + // The recipe tests a Store injection with Memory, not the D1 adapter. + // Its declared deployment adapter follows the actual host manifest. + expect(fixture).toContain('Production Workers should inject'); + const adapter = JSON.parse( + readFileSync( + new URL('../package.json', import.meta.resolve('@pegma/storage-cloudflare-d1')), + 'utf8', + ), + ); + expect(adapter).toMatchObject({ + name: '@pegma/storage-cloudflare-d1', + version: dependencies['@pegma/storage-cloudflare-d1'], + }); + expect(readFileSync(new URL('../../README.md', import.meta.url), 'utf8')).toContain( + '@pegma/storage-cloudflare-d1@' + dependencies['@pegma/storage-cloudflare-d1'], + ); + } + }, + ); + + it.each(['matching', 'older-session', 'unmatched-session'] as const)( + 'preserves exact publication readiness through compiled MCP plans for %s metadata', + async (mode) => { + const { dependencies } = JSON.parse( + readFileSync(new URL('../../package.json', import.meta.url), 'utf8'), + ); + // A deterministic publication fixture, not an assertion of npm's live + // latest versions. Independent recipe/component releases remain intact. + const published = Object.fromEntries( + RECIPE_BACKLOG.flatMap((recipe) => + recipe.packages + .map(parsePackageSpecifier) + .filter((pin) => pin.version) + .map((pin) => [pin.name, pin.version]), + ), + ); + for (const name of [ + '@pegma/sessions', + '@pegma/storage-cloudflare-d1', + '@pegma/support-desk-application', + '@pegma/support-desk-contracts', + '@pegma/support-desk-core', + ]) + published[name] = dependencies[name]; + if (mode !== 'matching') + published['@pegma/sessions'] = mode === 'older-session' ? '0.2.0' : '9.9.9'; + const catalog = await compile(published); + for (const id of ['cf-passkey-accounts', 'support-queue-slice']) { + const recipe = getRecipe(catalog, id); + if (!recipe) throw new Error('Expected the actual compiled recipe.'); + expect(recipePackagesReady(catalog, recipe)).toBe(mode === 'matching'); + const plan = planComposition(catalog, { + capabilityTags: recipe.capabilityTags, + host: 'cloudflare', + productionOnly: true, + }); + if (mode === 'matching') expect(plan.recipes.map((entry) => entry.id)).toContain(id); + else { + expect(plan.recipes.map((entry) => entry.id)).not.toContain(id); + expect(plan.skipped).toContainEqual({ + id, + kind: 'recipe', + reason: 'recipe packages not published with pins', + }); + } + } + }, + ); + it('lists sixteen registry components including published cache, flags, and billing', () => { expect(SNAPSHOT_DATE).toBe('2026-08-15'); expect(components).toHaveLength(16); diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index ddd3038..bff5279 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -16,12 +16,12 @@ 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.0', + '@pegma/sessions@0.2.1', '@pegma/mail@0.1.1', '@pegma/rate-limit@0.2.0', '@pegma/authorization-identity@0.4.0', '@pegma/storage-core@0.4.0', - '@pegma/storage-cloudflare-d1@0.4.6', + '@pegma/storage-cloudflare-d1@0.4.7', '@pegma/spine@0.1.1', ], adapters: [{ componentId: 'storage-core', adapterId: 'cloudflare-d1' }], @@ -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.0', + '@pegma/sessions@0.2.1', '@pegma/mail@0.1.1', '@pegma/rate-limit@0.2.0', '@pegma/health@0.2.0', - '@pegma/support-desk-application@0.1.1', - '@pegma/support-desk-contracts@0.1.1', - '@pegma/support-desk-core@0.1.1', + '@pegma/support-desk-application@0.2.7', + '@pegma/support-desk-contracts@0.2.7', + '@pegma/support-desk-core@0.2.7', '@pegma/authorization-core@0.4.0', '@pegma/storage-core@0.4.0', '@pegma/spine@0.1.1',