МАТЧАСТЬMASTER PLAN 14 · DEPLOY & RELEASE QUEUE

Порядок выполнения уточнён

Эта глава входит в готовый комплект из 26 документов. Статус реализации хранится в журнале; требования главы сами по себе не являются выполненной работой.

[14.1] REL-01 — карточка выполнения. Весь план и его состояние.

Уточнения для этой главы

[14.0.7] Сохранён исходный default publish_mode=direct. Он определяет режим уже разрешённого выпуска и не даёт сам по себе права на production. Разработка, тесты и staging идут по команде запуска плана; production, платные интеграции и увеличение партии требуют существующего явного разрешения нужного масштаба. Повторно разрешение на уже согласованное действие не запрашивать.

[14.0.8] Каждый downstream шаг создаёт новый запечатанный пакет с parent hash. После изменения текста, подписи, картинки или связей инвалидировать относящиеся к ним QA/SEO/approval результаты. На выпуск передаются проверки именно итогового hash, а не раннего текста.

[14.0.9] SHA-256 считается по точным bytes файлов. Manifest включает относительный путь, длину и sha256 каждого payload, но не собственный hash. Package hash — SHA-256 manifest bytes; detached seal хранит его отдельно. Проверять traversal, symlink escape, missing/extra files и повторные имена.

[14.0.11] На первом проходе разрешено ноль knowledge/related ссылок, если подходящих опубликованных целей нет. Резервирование URL не означает доступную страницу. Новая цель допустима лишь в том же атомарном release; sitemap и ссылки строятся из состава выбранного release.

[14.0.12] Staging всегда закрыт от индексации. SEO проверяет отдельно будущую production policy и фактическую staging policy; staging noindex не является ошибкой SEO. Сначала production smoke, затем IndexNow. Индексирование поисковиком не обещается и не заменяет проверку выпуска.

[14.0.13] Текущий production current — физический каталог; не применять команду замены symlink, пока не разработан и не проверен переход. REL-06/08 обязаны сначала доказать activation/rollback в отдельном staging root. Failure injection выполняется в staging; намеренно повреждённый релиз не отправлять на живой сайт.

Mathchast / Deploy & Release Queue / 14

RELEASE
WITHOUT
GAMBLING.

Публикация должна быть отдельной управляемой транзакцией: подготовить, проверить, переключить атомарно, проверить production и откатить при необходимости.

Static production не означает «скопировать файлы и надеяться». Release Queue отделяет готовность статьи от физического deploy и сохраняет воспроизводимую историю релизов.

ONLY DEPLOYER KNOWS THE PHYSICAL PRODUCTION LAYOUT.
SEO-ready package → Release Queue → approval if needed → staging → atomic activation → production smoke → IndexNow.

Separate readiness
from activation.

Release subsystem принимает только sealed SEO-ready Article Package, создаёт immutable release item, соблюдает publish mode, собирает staging artifact, выполняет atomic production activation, smoke и rollback.

PRIMARY OUTCOME
Known-good live release.

Каждая опубликованная article version связана с release manifest, production state, smoke report and rollback target.

STATIC PROD
Atomic, not partial.

Пользователь не должен увидеть новый HTML со старыми assets или новый sitemap раньше самой статьи.

REVIEW MODE
Approval boundary.

Если пользователь заранее запросил review, готовый release item ждёт explicit approval до production activation.

DIRECT MODE
Gates then publish.

Без запрошенного review релиз может идти автоматически после всех предыдущих gates и release preflight.

BoundaryWriter, Builder, SEO и Work не должны знать, куда физически копировать production files. Этим knowledge владеет только Deployer.

Audit current release
before creating another.

DEPLOY CAPABILITY AUDIT 1. Inspect production: https://mathchast.com/ nginx/static configuration current release/root mechanics Known current static root: PUBLIC_ROOT 2. Inspect existing deploy scripts: copy / rsync / symlink / rename / version dirs permissions / ownership cache behavior rollback scripts nginx reload needs, if any 3. Inspect existing staging/work artifacts: WORK_ROOT any preview/staging mechanisms 4. Inspect sitemap / redirects / IndexNow paths. 5. Inspect editorial.task / workflow / task_event and existing queue/lease patterns. 6. Search repo: deploy, release, publish, rollback, staging, smoke, rsync, symlink, current, nginx, indexnow. 7. Find tests / runbooks / operators. 8. Classify: REUSE → EXTEND → WRAP → MIGRATE → NEW 9. Only after audit freeze physical directories and deploy commands.
✓
Reuse existing safe atomic mechanism if one already exists.
✓
Reuse task/queue/event authority where suitable instead of a second generic queue.
×
Не hardcode предполагаемый releases/staging path в других modules до deploy audit.

One queue.
Immutable release inputs.

release item (logical) release_item_id article_id article_version_id seo_package_id / hash publish_mode = review | direct canonical_url release_type = NEW | UPDATE | FOLLOW_UP | ROLLBACK asset_manifest_ref redirect_plan_ref sitemap_entry_ref indexnow_ref requested_at requested_by config_hash status failure_reason? approved_at / approved_by? release_batch_id?
IMMUTABLE INPUT
Queue item pin-ится к exact article/SEO package hash. Новая content/meta version создаёт новый release item, не мутирует старый.
IDEMPOTENCY
Повтор enqueue того же article version/package не создаёт два независимых production releases.
ORDERING
Для одного article/canonical URL release versions сериализуются; нельзя выпустить N+2 раньше N+1 без explicit supersede decision.
BATCH
100 статей могут идти как batch, но каждый release item сохраняет independent success/failure state.

State machine,
not shell-script folklore.

READY_FOR_RELEASE ↓ QUEUED ↓ WAITING_APPROVAL (review mode only) ↓ approved PREFLIGHT ↓ STAGING_BUILD ↓ STAGING_SMOKE ↓ ACTIVATING ↓ PRODUCTION_SMOKE ├─ PASS → RELEASED │ ↓ │ INDEX_NOTIFY_PENDING / DONE └─ FAIL → ROLLBACK_PENDING ↓ ROLLED_BACK or NEED_REVIEW Other: CANCELLED SUPERSEDED FAILED_RETRYABLE FAILED_FINAL
NO FAKE RELEASED
Status RELEASED только после successful production smoke, не после file copy command exit=0.
EVENTS
Все переходы имеют task/release events with operator/agent/config provenance.
RETRY
Retry resumes from safe boundary and respects idempotency; не запускает второй overlapping activation.

Review stops
at one clear boundary.

REVIEW
Release item проходит pre-release preparation as policy allows, но production activation требует explicit user approval.
WHAT USER SEES
Article preview/version, key QA/SEO status, URL, image set, update diff if applicable and release summary.
APPROVAL PIN
Approval относится к exact article/SEO package hash. Любое substantive change invalidates approval.
DIRECT
Direct mode skips human approval only; it does not skip preflight, staging smoke, atomic activation or production smoke.

Deploy from a manifest.
Not from loose files.

release-manifest.json release_id release_item_id / batch_id article_id / version seo_package_hash canonical_url files[]: logical_role source_artifact_ref content_hash destination_key assets[]: asset_id hash destination_key redirects[] sitemap_changes[] indexnow_urls[] previous_release_id deployer_version config_hash created_at
DESTINATION KEY
Logical destination is resolved by Deployer to physical path; upstream packages do not know filesystem layout.
HASH
Every deployed file/asset has expected content hash; staging/production verification can detect partial/corrupt copy.
PREVIOUS
Manifest points to previous known-good release for rollback planning.

Fail cheap
before touching production.

CheckPass condition
package hashSealed SEO-ready package unchanged since gate PASS/approval.
article stateNo newer accepted article/release supersedes this item.
assetsAll required logical asset refs resolvable and hashes present.
URLCanonical/redirect plan consistent with current production state.
sitemapEntry/change can be applied without duplicate/conflict.
diskDestination volumes above safe watermarks for staging + rollback headroom.
permissionsDeployer can write/activate target release safely.
lockNo incompatible production activation already in progress.
DISK WATERMARKS
Reuse Settings policy: warn ~70%, high ~82%, critical ~92%, tuned per volume. Critical state blocks unsafe staging/deploy.
NO MUTATION
Preflight does not "fix" article artifacts; it returns blocker to owning stage.

Stage the same thing
you will activate.

STAGING BUILD release manifest ↓ resolve logical destinations ↓ assemble page + assets + redirect/sitemap candidate state ↓ verify hashes ↓ render through production-equivalent static layout ↓ staging smoke: HTML canonical/meta assets internal links sitemap consistency redirects representative mobile/render ↓ STAGING PASS
NO SECOND BUILD
После staging PASS production should activate/copy the same staged artifacts where architecture permits, not regenerate them through another uncontrolled path.
ISOLATION
Staging release does not overwrite current production files.
BATCH
Batch staging can share release snapshot, but item-level manifest/health remains traceable.

Switch state
as one operation.

ACTIVATION PRINCIPLE previous known-good production ↓ prepared staged release ↓ acquire deploy lock ↓ final pre-activation hash/state check ↓ atomic activation mechanism (exact mechanism determined by audit: version-dir switch / rename / symlink swap / equivalent safe static release pattern) ↓ release state points to new version ↓ production smoke immediately ↓ unlock only after success or rollback action
NO ASSUMPTION
Plan does not prescribe symlink vs rename until actual nginx/filesystem/deploy audit.
COHERENCE
HTML, assets, redirect state and sitemap changes should activate coherently wherever architecture permits.
LOCK
Only one incompatible activation against shared production state at a time.
DURABILITY
Release event records old/new production identifiers before/after switch.

Verify the public URL.
Not the local folder.

PRODUCTION SMOKE canonical public URL ✓ HTTP success intent / redirect behavior ✓ final canonical ✓ title / description / robots ✓ main article content marker ✓ required assets load ✓ JSON-LD parses ✓ key internal links resolve ✓ sitemap contains correct canonical state ✓ redirect plan behaves as expected ✓ representative mobile/render sanity ✓ content/version release marker if available For UPDATE: ✓ old canonical still canonical unless explicit migration For URL migration: ✓ old URL redirects correctly ✓ no loop / chain regression
PUBLIC
Smoke targets `https://mathchast.com/` public behavior, not only localhost or filesystem.
TIMEOUT
Bounded retry window may account for local cache propagation if current architecture needs it; no indefinite waiting.
PASS
Only production smoke PASS moves release to RELEASED.

Rollback is
part of deploy design.

PRODUCTION SMOKE FAIL ↓ classify: page / asset / redirect / sitemap / permission / integrity / runtime ↓ if safe immediate fix exists? usually NO during activation window ↓ activate previous known-good release ↓ rollback smoke ↓ mark failed release ↓ return blocker to owning stage ↓ new release item after fix
PREVIOUS STATE
Rollback uses recorded previous release, not reconstructed best-effort files.
NO PATCH LIVE
Не чинить production вручную поверх failed release так, что release history перестаёт соответствовать filesystem.
ROLLBACK FAILURE
Critical incident state + operator alert/runbook; preserve both manifests and diagnostics.
INDEXNOW
No IndexNow notification for failed/rolled-back target URL state.

Release first.
Notify second.

INDEXNOW
After RELEASED, enqueue/send prepared IndexNow notification for relevant URLs.
FAILURE
IndexNow/network failure creates retryable task and does not roll back healthy content.
TRACE
Store release_id, URL, notification attempt/result/time and retry state.
LEARNING
Later indexing/traffic signals feed learning memory, not Release Queue decision retroactively.

One bad article
must not kill 99 good ones.

ITEM STATE
Каждая статья имеет собственный queue/release result and blocker.
SHARED RELEASE
Если deployment architecture activates a shared snapshot, batch assembler excludes failed preflight items before sealing the release snapshot.
POST-ACTIVATION
Если one-item smoke failure implies shared snapshot corruption, rollback whole atomic snapshot; if isolated and architecture supports independent atomicity, policy follows proven deploy model.
NO CASCADE
Research/Writer/QA failure of one item never marks unrelated queued items failed.
RAMP
Release concurrency/batch size increases only after 1→5→20 production-ready pilots prove smoke/rollback reliability.

Know what was live
at any moment.

release history (logical) release_id release_item/batch refs activated_at production_snapshot_id / version previous_release_id article versions[] asset hashes[] redirect state sitemap state smoke report rollback relation? operator/agent git SHA / config_hash / deployer version status
AUDIT
Reuse/extend `platform.audit_event` and task events where contracts fit.
GIT
Release records code/config Git SHA where available, but deploy history does not rely on an hourly auto-commit.
ARTICLE
Article version knows which release first/last activated it.

Small blast radius.
Least privilege.

WRITE ACCESS
Only Deployer identity/process receives required production write/activation permissions.
INPUT TRUST
Deployer only consumes validated manifests and resolves logical destinations through allowlisted mapping.
PATH SAFETY
No arbitrary path traversal/destination from Writer/article metadata.
SECRETS
Credentials/tokens remain outside release manifests/logs/Work UI; IndexNow secret material handled separately.
COMMANDS
No shell interpolation of article-controlled values without safe argument handling/validation.

Release policy
is explicit.

Setting familyPurpose
release.default_publish_modeDirect unless user explicitly requested review; task value remains pinned.
release.max_batch_sizeBound shared release scope; tuned during 1→5→20 ramp.
release.activation_concurrencyUsually one shared production activation at a time unless architecture proves otherwise.
release.smoke_policyRequired public checks, retries and timeout bounds.
release.rollback_policyAutomatic/manual escalation thresholds and smoke after rollback.
release.retentionKnown-good release snapshots/manifests needed for rollback/history.
release.disk_watermarksReferences canonical storage watermark settings, no duplicated authority.
release.indexnow_retryPost-release notification retry/backoff.

See every transition
and every rollback.

QUEUE
queued/waiting approval/preflight/staging/activating/released/failed/superseded counts and age.
LATENCY
Ready→queue, queue→approval, staging duration, activation duration, production smoke duration.
FAILURES
Preflight/staging/activation/smoke/rollback reason distributions.
ROLLBACK
Rollback rate, rollback success, release-to-rollback latency.
BATCH
Batch success distribution, isolated item failures, excluded items, shared snapshot rollback events.
TRACE
release item/batch, article/version, production release id, manifest hash, deployer version, operator/agent, git SHA, config_hash.

Audit production.
Prove rollback.

REL-01

Audit current deploy path

nginx/static root, current release mechanics, scripts, permissions, sitemap/redirect/indexing hooks, rollback options, Work staging and tests.
DONE: actual physical release model documented and reusable pieces classified.
REL-02

Freeze Release Queue contract

Immutable release item/batch schema, states, idempotency, article ordering and publish-mode approval semantics.
DONE: duplicate enqueue/concurrent same-article release tests green.
REL-03

Freeze release manifest

Logical destinations, hashes, assets, redirects, sitemap, IndexNow refs, previous release and deployer/config versions.
DONE: no upstream artifact contains physical production paths.
REL-04

Implement preflight

Package/hash/state/assets/URL/sitemap/disk/permission/lock checks before staging.
DONE: unsafe deploy fails before production mutation.
REL-05

Implement staging assembler

Build exact release artifact with production-equivalent layout and staging smoke from release manifest.
DONE: staged hashes match manifest.
REL-06

Implement atomic activation

Use audited safe mechanism, production lock and durable old/new release recording.
DONE: failure injection cannot leave known half-activated state.
REL-07

Production smoke suite

Public URL/status/canonical/head/content/assets/JSON-LD/internal links/sitemap/redirect/mobile checks.
DONE: RELEASED only after public smoke PASS.
REL-08

Rollback path

Activate previous known-good release automatically/by policy, rollback smoke and failure event trail.
DONE: induced bad release returns production to known-good state.
REL-09

Approval + direct pilots

One review-mode release requiring approval and one direct-mode release using identical technical gates.
DONE: approval pins exact package; direct skips only human approval.
REL-10

IndexNow post-release

Send/retry notification only after release smoke; notification failure decoupled from article health.
DONE: failed notification does not trigger content rollback.
REL-11

Batch isolation pilot

5-item representative release with one intentional preflight failure; healthy items proceed according to proven atomic model.
DONE: one bad item does not poison unrelated ready items.
REL-12

Work + checkpoint

Release Queue, approvals, staging/smoke/rollback/history visible in Work; HANDOFF/Project State sync and exact next branch.
DONE: checkpoint 14 PASS.
Split ruleЕсли actual deploy audit выявит сложную отдельную static-release architecture, вынести physical Deployer implementation в 14.x. Release Queue/manifest/state/approval contracts должны остаться общими.

Prove failure
before trusting success.

TestExpected result
same package queued twiceIdempotent single logical release item.
two releases for same article concurrentlyOrdering/lock prevents conflicting activation.
review mode without approvalCannot activate production.
package changes after approvalApproval invalidated; new review required.
missing required assetPreflight/staging fails before production.
critical disk watermarkStaging/deploy blocked safely.
activation interruptedSystem detects state and recovers/rolls back according to audited mechanism.
production canonical wrongSmoke fails → rollback.
asset 404 after activationSmoke fails → rollback or critical policy action.
rollback invokedPrevious manifest/state restored and rollback smoke passes.
IndexNow downRelease remains RELEASED; notification retries.
5-item batch, 1 bad preflightBad item isolated; healthy set not marked failed.
stale release item after newer article versionSuperseded, cannot publish old version accidentally.
path traversal destination attemptRejected by allowlisted logical destination resolver.
×
Не считать successful rsync/copy достаточным deploy PASS.
×
Не чинить failed production release вручную в обход manifest/history.
×
Не отправлять IndexNow до public smoke PASS.
×
Не давать Writer/SEO layer физический production path contract.

Publishing is
atomic and reversible.

CHECKPOINT 14 PASS WHEN: ✓ current nginx/static deploy reality audited reuse-first ✓ canonical Release Queue exists ✓ release items pin exact article/SEO package hashes ✓ review/direct approval behavior is tested ✓ approval is invalidated by substantive package change ✓ release manifest uses logical destinations ✓ only Deployer resolves physical production paths ✓ preflight blocks unsafe releases cheaply ✓ staging builds exact release artifact ✓ staging smoke is green before activation ✓ atomic activation mechanism is proven on actual architecture ✓ RELEASED requires successful public production smoke ✓ rollback to previous known-good release is tested ✓ rollback smoke is tested ✓ sitemap/redirect state is coherent with article activation ✓ IndexNow runs only after successful release smoke ✓ IndexNow failure does not roll back healthy release ✓ batch/item failure isolation is proven ✓ release history is durable and auditable ✓ Work exposes queue/approval/smoke/rollback/history ✓ HANDOFF points to Work Control Center & Operations next

Продолжить выполнение

Следующий шаг выбирает журнал задач. Все главы уже подготовлены.

[14.1] REL-01 — карточка выполнения