# Segmented Site Content Backend

Audience: AI coding agents first.

- **ID:** IPZ-SEGMENTED-SITE-CONTENT-BACKEND-2026-08-15
- **Status:** BLOCKED
- **Task:** SC-BACKEND-01
- **Source request:** Continue every unfinished multilingual Site Content slice through session end. Current contract mapping proves controller queueing and post-resource adaptation both depend on one coordinated dispatch path. Build next independent prerequisite: backward-compatible segmented backend translation and explicit capability metadata.
- **Execution owner:** Current main coordinator only. NEVER delegate implementation or review.

## Outcome

Publish and deploy backend support for bounded `site_content` segmented translation jobs. Preserve existing post, bulk-string, synchronous, asynchronous, billing, callback, retry, and idempotency behavior. Advertise segmented support only after exact request/provider/response validation exists. Do not activate WordPress routes, handlers, dispatch, hooks, schedules, or UI.

## Acceptance

- Accept exactly versioned segmented Site Content requests on current authenticated async job boundary. Do not reinterpret old post or bulk-string requests.
- Require exact `resourceType=site_content`, supported contract version, canonical source/target languages, exact ordered non-empty segment list, unique bounded opaque IDs, exact context/type fields, scalar text, exact source revision, callback URL/secret, client job ID, and attempt token.
- Enforce encoded segmented payload bytes at most 1 MiB, at most 1,000 segments, and total source text at most the backend's current configured asynchronous character limit before credit reservation, persistence, queueing, or provider use. Advertise the effective character limit in capability metadata. Reject unknown or malformed shapes fail-closed.
- Persist enough versioned job data to retry deterministically. Preserve current callback-secret storage/delivery behavior without exposing secrets through payloads, responses, or logs.
- Translate segment text only. Preserve segment ID, order, count, context/type, and non-translatable structural data exactly. Reject provider omissions, additions, duplicates, reorderings, wrong scalar types, or malformed output before completion.
- Keep provider prompt and response bounded. Never log source text, translated text, callback secret, attempt token, or raw provider output.
- Emit callback completion/failure data with exact resource type/version, target language, source revision, and unchanged attempt token. Completion additionally returns exact ordered translated segments. Poll status exposes translated segments and correlation metadata required by the authenticated owning client but MUST NOT expose the attempt token; the WordPress job context retains it locally.
- Preserve existing terminal idempotency, retry, cancellation, reconciliation, credit settlement/refund, character accounting, and callback authentication semantics. Add focused regressions for replay and failed provider output.
- Expose explicit versioned capability metadata from the existing authenticated/public health or metadata seam only after implementation is deployable. Existing response fields remain backward compatible.
- Tests prove limits, exact shape/types/order/IDs/context, placeholder preservation, malformed provider rejection, terminal replay, retry serialization, secret/token redaction, character/credit accounting, old post compatibility, and capability response.
- Add no WordPress production/runtime changes in this slice.
- Run every dependency install, test, lint, typecheck, build, security check, diagnostic, smoke, and related gate only through canonical remote execution on registry-selected `debian1`/`debian2`/`debian3`. NEVER run a local gate, direct SSH, hardcoded normal-run host, local fallback, dev1 test, or dev3 test.

## Preserved WIP / ref / path

- Active worktree: `/home/user/Projects/Press.zone/wordpress/wp-content/.worktrees/site-content-post-handler`
- Branch: `wt/site-content-post-handler`
- Exact base: `aa56fce307a2c02aa34f36c37b5ef006755ea34f`
- Preserved Site Content controller and post-handler candidates: `e9a2c64f6` and `09d3de3ac`. Treat as behavioral evidence only.
- Published dormant handler: implementation `097a5f64b078078896f88de326278d2101263094`, merge `aa56fce307a2c02aa34f36c37b5ef006755ea34f`.

## Allowed paths

- `press-zone-backend/api/src/**` required by exact segmented request, provider, queue, worker, response, and capability seams
- `press-zone-backend/api/package.json` only to expose the package's existing `tsc --noEmit` check to the fail-closed serialized publisher
- Focused backend tests under `press-zone-backend/api/src/__tests__/**`
- Backend schema/migration files only if exact current persistence cannot store the versioned payload safely; prove need before editing
- Backend contract documentation only when public request/response or capability shape changes
- This plan, `docs/plans/INDEX.md`, `2026-08-15-post-translation-resource-handler.md`, `2026-08-14-site-content-translation-resource-handler.md`, and `2026-08-09-multilingual-site-entry-and-layout.md`

## Constraints

- Current backend code and tests are authoritative. Map synchronous, asynchronous, worker, provider, callback, billing, and health paths before editing.
- One discriminated versioned request contract. NEVER bolt segments onto ambiguous legacy structured fields.
- Surgical implementation. Reuse current queue, callback-secret persistence, settlement, reconciliation, and callback seams. Do not create a second job system.
- No arbitrary metadata bags, latest-job inference, hidden mutable handler state, or duplicated finalization path.
- No nested delegation, subagents, external models, or local gates.
- No WordPress activation. Capability deployment alone MUST NOT construct or register dormant WordPress code.

## Execution

1. Map exact backend request schemas, service persistence, worker/provider translation, completion payload, billing, retry/reconciliation, and health metadata.
2. Pin one backward-compatible segmented contract and every bound in focused failing tests.
3. Implement smallest discriminated path through existing service/queue/worker/provider seams.
4. Run focused and applicable broad backend gates remotely only. Address every warning, notice, and hint.
5. Review trust boundaries, billing, idempotency, retry, secret/token handling, malformed provider output, and legacy compatibility directly. Rerun affected remote gates.
6. Normal-commit through installed remote enforcement. Land through serialized isolated publisher. Fetch exact `origin/master` and prove source ancestry/tree.
7. Deploy through canonical backend deployment infrastructure. Verify installed revision and capability/health without translating production content.
8. Publish receipt. Continue coordinated two-resource WordPress dispatch/controller slice.

## Current receipt

Implemented exact `site_content` contract version 1 through existing authenticated async request, persistence, queue, worker, settlement, retry, polling, callback, and health seams. Request validation now rejects unknown fields, unsupported versions, malformed languages/revisions/tokens/segments/contexts/callback identity, oversized JSON, more than 1,000 segments, and source text above configured async limit. Persistence uses canonical versioned Base64 JSON. Provider calls receive synthetic fields containing segment text only; output is reconstructed in source segment order with unchanged IDs/context and rejected on missing, extra, non-string, empty, oversized, or invalid-metric output. Poll metadata excludes attempt authority. Signed completion/failure callbacks echo exact version, target language, source revision, and attempt token.

Direct correctness/security review fixed four residual defects before publication: retry now restores stored exception rules; retry and terminal worker throws expose only generic Site Content failure text so Bull cannot persist provider data; structured provider and payload-transform logs no longer expose provider output, field names, source text, callback secrets, or attempt tokens; callback failure coverage now proves target-language correlation. Focused regression also proves exception placeholders survive provider translation, non-final retry errors remain private, terminal replay avoids provider/billing duplication, source characters drive billing, legacy post/bulk validation remains accepted, and public health advertises exact effective bounds.

Remote-only final receipt on registry-selected `debian2`: focused Jest 7/7 suites and 74/74 tests pass; Prisma 5.22 client generation passes; TypeScript passes. Broad unit/integration gate passes 50/50 suites and 661/661 tests; Prisma generation, TypeScript no-emit, isolated TypeScript build, and monorepo lint complete with zero errors. Remote `git diff --check` passes. Broad lint reports 114 pre-existing warnings only in unchanged legacy declarations/mocks (`mockTranslationStore.ts`, `settingsService.ts`, `translationProvider.ts`, `types/express.d.ts`, and pre-existing enum declarations in touched `types/index.ts`); this slice introduced no remaining lint warning, reducing the prior broad count from 115 to 114. Broad error log lines are expected negative-path output from untouched auth/translation/email/credit tests and contain no private payload. `npm ci` reports existing transitive `inflight`/`glob` deprecations, the existing retired PayPal SDK, and buildbox `allow-scripts` policy notices; zero vulnerabilities were found, explicit Prisma generation succeeded, and replacing payment or dependency infrastructure is outside this contract slice. Earlier concurrent remote invocations collided in the shared remote mirror and were discarded; the authoritative final gates ran sequentially and cleanly. No WordPress runtime seam was activated.

Normal enforced implementation commit `b56f15f26` passed applicable staged checks. Merging current `origin/master` through enforcement produced `101e1cadf` with a clean remote IPZ gate. Direct `land` is incompatible with the repository reference-transaction hook because its automatic rebase rewrites the checked-out ref without a tested-tree claim; both attempts failed closed and changed no branch ref. The canonical serialized publisher then retained the source and rescue ref but failed its independent candidate typecheck floor because the backend package exposed TypeScript only through its build script, not the required `scripts.typecheck` seam. The package now exposes the existing exact `tsc --noEmit` check as `npm run typecheck`; canonical remote execution on registry-selected `debian2` passes. The first remote probe was invalid because the workstation command-rewrite hook converted only the second plain `npm` invocation to the unrelated `fewtok` `ft` binary on the buildbox; it failed closed. The authoritative rerun used system `npm` explicitly and passed. Existing dependency retirement and buildbox script-policy notices are the same already-disposed warnings above.

Normal correction commit `923ed493b3955b10fb5836d62736e4f7d6a7dd4a` passed enforcement. The serialized publisher independently ran candidate typecheck and the configured backend build/test gate, then published merge `a6febe270f37bb5572dc1deb0f9cb9b7be38a80a`. Fresh exact `origin/master` fetch proves both implementation commits are ancestors. Published merge tree `495e7445bfa91900dd2de095fe95f2cfb6da8d1c` exactly equals fetched `origin/master` tree.

Deployment is externally BLOCKED. Current repository instructions expose only direct SSH to the production host; recent project execution history likewise contains only direct SSH. No GitHub deployment workflow, self-hosted runner, repository deployment hook, installed non-SSH controller, or authenticated deployment MCP seam is available. The owner expressly forbids direct SSH and hardcoded production-host execution. Do not bypass that boundary or misrepresent published source as installed code. Public capability remains unverified and WordPress runtime activation remains forbidden. Continue safe dormant WordPress seams while deployment waits for a sanctioned controller.

## Next executable action

Resume deployment only through a newly available sanctioned non-SSH controller. Verify its authenticated target and fail-closed behavior, deploy exact published revision `a6febe270f37bb5572dc1deb0f9cb9b7be38a80a` or a proven descendant, then verify installed revision plus public capability without translation side effects. Until then, keep WordPress runtime activation blocked and continue only dormant coordinated dispatch/controller implementation.
