ИИшка / Orchestration / 06 of 10

MCP/API контракты

Публичный контракт Orchestration должен быть engine-neutral: клиент работает с canonical workflow/run/task объектами, а Temporal, Prefect, LangGraph, Kestra или собственный runner остаются сменяемыми execution adapters.

Ключевой принцип: API оркестратора координирует жизненный цикл и handoff, но не выдаёт доменные права Writer, Curator, Skeptic, Investigator или Experiment за права самого Orchestration.
Public surface

Canonical MCP/API

WORKFLOWS
orchestration.workflow.create
orchestration.workflow.get
orchestration.workflow.list
orchestration.workflow.update
orchestration.workflow.validate
orchestration.workflow.publish
orchestration.workflow.deprecate

RUNS
orchestration.run.start
orchestration.run.get
orchestration.run.list
orchestration.run.pause
orchestration.run.resume
orchestration.run.cancel
orchestration.run.retry_failed
orchestration.run.recover
orchestration.run.export

TASKS / STEPS
orchestration.task.get
orchestration.task.list
orchestration.task.claim
orchestration.task.heartbeat
orchestration.task.complete
orchestration.task.fail
orchestration.task.defer
orchestration.task.release

HANDOFF
orchestration.handoff.create
orchestration.handoff.get
orchestration.handoff.accept
orchestration.handoff.reject
orchestration.handoff.return

HUMAN GATES
orchestration.approval.request
orchestration.approval.get
orchestration.approval.approve
orchestration.approval.reject
orchestration.approval.expire

OBSERVABILITY / AUDIT
orchestration.events.list
orchestration.audit.get
orchestration.timeline.get
orchestration.health.get
LayerOwnsDoes not own
Orchestration APIrun state, task delivery, routing, retry, timeout, approvals, cancellation, audittruth, publication quality, causal verdict, experiment validity, permanent RAG promotion
Domain module APImodule-specific decision + canonical objectsglobal workflow scheduling
Engine adapterexecution mechanicscanonical IDs, domain policy, authorization model
Lifecycle contracts

WorkflowRun не равен engine run

WorkflowRun.status:
CREATED -> READY -> RUNNING
                  -> WAITING_MODULE
                  -> WAITING_HUMAN
                  -> PAUSED
                  -> RECOVERING
                  -> COMPLETED
                  -> FAILED
                  -> CANCELLED
                  -> PARTIALLY_COMPENSATED

engine_run_id = metadata only
canonical run_id = source of truth

Каждая мутация protected state принимает expected_revision. Изменение workflow definition после старта не переписывает уже запущенный run: он остаётся привязан к workflow_version.

start

Фиксирует immutable input refs, workflow version, actor, policy refs, resource class и correlation IDs.

pause/resume

Не теряет lease/task state; resume проходит canonical validation.

recover

Используется при UNKNOWN/ambiguous engine state; не маркирует run успешным без reconciliation.

Dispatch & handoff

Межмодульный вызов — отдельный объект

ModuleHandoff {
  handoff_id,
  run_id,
  from_module,
  to_module,
  contract_name,
  input_refs[],
  expected_output_schema,
  permission_scope,
  idempotency_key,
  deadline_at?,
  status,
  created_by,
  policy_version,
  revision
}

Handoff не должен передавать сырой системный prompt другого модуля или секреты. Вход — только минимально необходимый canonical context + refs. Получатель возвращает typed result/ref, а Orchestration решает только следующий transition согласно workflow policy.

RouteTypical purposeMandatory guard
Researchermissing evidence / web researchno permanent write
Skepticclaim/draft verificationcannot silently publish
Investigatorcausal investigationcorrelation != cause
Experimentcontrolled discriminating testdesign/run policy + reproducibility
Curatorpromotion decisiononly Curator path may authorize permanent RAG write
Writerdraft generation/editingread-only knowledge access
Workers

Claim, lease, heartbeat

TaskLease {
  task_id,
  lease_id,
  worker_id,
  claimed_at,
  expires_at,
  heartbeat_at,
  attempt,
  idempotency_key,
  input_hash,
  execution_engine_ref?
}
Side-effect rule: внешний эффект должен иметь собственный idempotency key либо transactional outbox/inbox. Retry без этого запрещён для irreversible операций.
Retry / timeout

Повтор — policy, не reflex

RetryPolicy:
  retryable_error_classes[]
  max_attempts
  backoff
  jitter
  timeout_per_attempt
  total_deadline
  requires_reconciliation
  compensation_on_exhaustion

NEVER_AUTO_RETRY examples:
  permission_denied
  schema_violation
  policy_block
  human_rejection
  unknown_irreversible_side_effect

Engine-specific retry settings переводятся в canonical policy. Orchestration хранит причину каждого attempt и не маскирует retry-exhausted как generic success.

Human gates

Approval — version-scoped capability

ApprovalRequest {
  approval_id,
  run_id,
  gate_id,
  protected_input_hash,
  requested_action,
  approver_role,
  status: PENDING|APPROVED|REJECTED|EXPIRED|INVALIDATED,
  expires_at?,
  policy_version,
  decision_reason,
  decided_by,
  decided_at
}
Cancellation & compensation

Cancel ≠ rollback

ActionMeaning
cancelзапретить дальнейшие planned steps
terminateаварийно остановить worker/engine execution
compensateвыполнить явные inverse/mitigation actions
reconcileустановить фактическое состояние внешних side effects
CompensationRecord:
  compensation_id
  original_step_ref
  action
  status
  reversible: true|false|partial
  evidence_refs[]
  completed_at

Если часть эффектов необратима, итоговый статус обязан это отражать: например PARTIALLY_COMPENSATED, а не ложный CANCELLED_CLEAN.

Security boundaries

Least privilege by route

Qwen 30B: может предложить route/next action в structured form, но итоговый dispatch проходит deterministic policy + permissions + schema validation.
Audit & observability

Каждый transition объясним

AuditEvent {
  event_id,
  run_id,
  task_id?,
  handoff_id?,
  event_type,
  actor_type,
  actor_id,
  from_state?,
  to_state?,
  reason_code,
  input_refs[],
  output_refs[],
  policy_version,
  engine_ref?,
  correlation_id,
  created_at
}

Audit append-only. Engine logs дополняют, но не заменяют canonical audit. Для replay/debug должны быть доступны workflow version, inputs, outputs, handoffs, attempts, approvals, failures и compensation records.

Server2 observability

Contract tests

Golden / zero-tolerance gates

unauthorized module route accepted                  = 0
Curator permanent-write bypass                      = 0
mandatory Skeptic/human gate bypass                 = 0
stale approval accepted after protected input change= 0
duplicate irreversible side effect after retry      = 0
expired lease completing protected task             = 0
engine callback mutating canonical state unchecked  = 0
workflow version silently changed mid-run           = 0
Qwen output treated as authorization                 = 0
secret leaked into prompt/audit/engine metadata      = 0
cancel reported as rollback without compensation    = 0
cross-scope handoff without permission               = 0
terminal run without audit trail                     = 0

Minimum positive tests

Архитектурный итог №6: публичная поверхность должна принадлежать ИИшке. Execution engine — внутренний адаптер; domain modules — отдельные policy authorities; Orchestration — coordinator with durable, auditable contracts.
Next

Следующий документ

AI_orchestration_7_execution_recovery_и_observability.html