cmvr-visual/docs/api-contract.md

272 lines
55 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Shared API contract
All endpoints use `/api`. JSON errors: `{detail:{code,message}}`; normal FastAPI validation errors may additionally contain field locations. Session cookie `cmvr_session` is HttpOnly, same-origin. POST/PATCH/DELETE except login need `X-CSRF-Token` from auth response. Never expose inference keys or absolute server paths.
Private resources are owner-scoped for both regular users and `admin`: private assets, jobs, workflow drafts/runs and batches never become cross-user readable through the admin role. Explicit `/shared-assets` reads are authenticated cross-user reads of active publications. User administration does not grant access to another user's private content.
## Authentication
- POST `/auth/login` `{username,password}` → `{user:{id,username,display_name,role},csrf_token}` plus session cookie.
- GET `/auth/me` → same shape; 401 when signed out.
- POST `/auth/logout` → 204; close SSE on frontend.
- Admin POST `/auth/users` `{username,display_name,password}` → user. Initial passwords allow 6–256 characters, including six digits.
## Capabilities and resources
- GET `/capabilities` → `{items:Capability[],scheduler:Scheduler}`.
- GET `/system/status` → `{inference_online:boolean,scheduler:Scheduler,models:Capability[]}`.
- Capability: `{task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}`.
- Scheduler: `{available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}`. No PID or user identity.
- Types: `image.generate`, `image.reference.generate`, `video.generate`, `video.people.analyze`, `video.replace`, `defect.generate`, `audio.transcribe`, `math.solve`, `media.structure`, `video.compose`, optional `audio.speech` (only available when a real provider is configured). Video editing availability requires both business/inference enablement and the pinned operator validation receipt; constraints are the smaller local/remote budgets.
## Assets
- POST `/assets` multipart field `file`, optional `name` → Asset.
- GET `/assets?page=1&page_size=24&kind=&q=&tag=&origin=&favorite=` → `{items:Asset[],total,page,page_size}`. Returns only the caller's active, ready, private assets. `origin` accepts `upload`, `generated`, or `shared`; omit `favorite` for no favorite filter.
- GET `/assets/{id}` → Asset.
- PATCH `/assets/{id}` `{name?,tags?:string[],favorite?:boolean}` → Asset.
- DELETE `/assets/{id}` → 204 after soft deletion. Workflow references or active input use reject with `409 asset_in_use`; resolve references/control the owning record first. Physical files are retained until explicit eligible GC.
- GET `/assets/{id}/content` inline, Range supported; `?download=1` attachment.
- GET `/assets/{id}/thumbnail` authenticated image preview (fallback image content when no separate thumbnail).
- Asset: `{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated'|'shared',tags:string[],favorite:boolean,created_at:string}`. A retained generated asset may keep `source_job_id` after its source job is archived; that identifier does not guarantee an accessible job.
## Logical folders (schema 006)
- GET `/folders` → `{items:Folder[]}`. Folder: `{id,name,parent_id:null|string,created_at,updated_at}`; private to the current owner.
- POST `/folders` `{name,parent_id?}` → 201 Folder. PATCH `/folders/{id}` `{name?,parent_id?}` → Folder. Same-parent duplicate names and parent cycles are rejected.
- DELETE `/folders/{id}` → 204. Removes this category and descendants; preserves all assets, jobs, drafts, runs and physical files. Remaining memberships in other folders survive.
- POST `/folders/assign` `{kind:'assets'|'jobs'|'drafts'|'runs',ids:string[],folder_id:null|string,mode?:'move'|'add'}` → `{updated,kind,folder_id}`. At most 200 requested IDs; all owner checks are atomic. `add` applies only to assets; `move` replaces memberships/classification. Moving a job does not change its frozen output target.
- Asset DTO adds `folder_ids:string[]`. Asset PATCH accepts `folder_ids`; upload multipart accepts `folder_id`; shared import optionally accepts `{folder_id}` while no-body calls remain valid.
- Jobs add `folder_id` and `output_folder_id`; drafts/stories add `folder_id`; runs add both. Asset/job/story/workflow/run list endpoints accept `folder_id`: omitted/empty means all, `unclassified` means no category, otherwise an owned folder ID.
- Submit accepts `folder_id` and `output_folder_id`; omitted output inherits classification, explicit null selects unclassified. Candidate/batch-candidate, story render and workflow RunCreate accept `output_folder_id`, defaulting to the draft's folder when omitted. Batch items carry the corresponding metadata on each item.
- StoryCreate optionally accepts `folder_id` and `create_folder` (default true). Omitted folder creates a unique same-name folder; explicit null or `create_folder:false` opts out. Draft/Story PATCH accepts `folder_id`.
- Output targets are persisted at submission; later draft moves do not alter queued destinations. Folder deletion falls back to unclassified during collection. Folder metadata never enters upstream model parameters or generation hashes. Legacy requests without the new fields preserve their idempotency fingerprints.
- New directory events are `folder.created`, `folder.updated`, `folder.deleted`, `folder.contents_changed`; affected assets/jobs/stories/runs also use their existing update events. Machine directory access uses `folders:read` / `folders:write`, separate from asset reads and task execution privileges.
- Bulk publish/delete in the UI uses the existing per-asset endpoints, bounded to three concurrent calls, and reports individual failures. It does not bypass reference protection or change publication-copy behavior.
## Shared assets
Shared publications are independent file and metadata snapshots, separate from private Asset DTOs. All logged-in users may read active publications, including their content and thumbnails. Shared content is read-only; import it before using it as a private job/workflow input. Bearer-token reads require `assets:read`; publish/import/withdraw require `assets:write`, and ownership still applies.
- POST `/assets/{id}/publish` → **201 SharedAsset**, publishing only a caller-owned private asset. Optional body is absent or `{}`; extra fields are rejected. Repeating publication of a source with an active publication returns that existing snapshot. Editing/deleting the private source does not update/delete its publication.
- GET `/shared-assets?page=1&page_size=24&q=&kind=&tag=&mine=false` → `{items:SharedAsset[],total,page,page_size}`. `mine=true` restricts to the caller's publications; page starts at1 and page_size is1–100.
- GET `/shared-assets/{id}` → SharedAsset.
- GET `/shared-assets/{id}/content` → authenticated inline content with Range support; `?download=1` downloads the snapshot.
- GET `/shared-assets/{id}/thumbnail` → authenticated thumbnail, falling back to original content for an image without a separate thumbnail.
- POST `/shared-assets/{id}/import` → **201 Asset**. Optional body is absent or `{}`. Copies bytes into a new caller-owned private asset with a new asset ID, `origin:'shared'`, `source_job_id:null`, and `favorite:false`. The publication ID is not a valid private input ID. Each new import without replay creates an independent copy.
- DELETE `/shared-assets/{id}` → **204**, publisher-only, idempotent withdrawal. A publication not owned by the caller returns404. Withdrawal makes shared metadata/content unavailable to further reads/imports; unavailable publications return `404 shared_asset_not_found`. Existing private imports survive withdrawal and source deletion.
- SharedAsset: `{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,tags:string[],created_at:string,publisher_id,publisher_name,is_owner:boolean,version:number,preview_url,thumbnail_url:null|string,download_url}`. `id` is the publication ID; media URLs use `/api/shared-assets/{id}/...`. This DTO omits private source asset/job IDs, hidden snapshot asset IDs, favorite state and storage paths.
Publish and import accept optional `Idempotency-Key` headers under operations `assets.publish` and `shared.import`. Reuse the same key for the same operation and source ID after a lost response; a changed source ID with that key returns `409 idempotency_conflict`. Replaying `assets.publish` after its publication is withdrawn, or `shared.import` after its imported private asset is deleted, returns `410 resource_purged`. Publication copies charge the publisher's storage budget; private imports charge the importer. Soft-deleted retained files still consume quota until physically collected. Copy operations can fail with `429 quota_exceeded` or `503 storage_insufficient`.
## Record deletion and retention
The following commands are caller-owned soft archival, each returning **200** with `{deleted:{job_ids:string[],run_ids:string[],draft_ids:string[],batch_ids:string[]}}`; arrays describe the complete archived tree, including empty arrays. They accept optional `If-Match: <version>`, not a request body. An already archived owned root returns the same tree without a new archival action. Missing/foreign records return404; a non-archived root with a mismatched version returns `409 version_conflict`.
| Command | Cascade and retained resources |
| --- | --- |
| DELETE `/jobs/{id}` | Archives an independent terminal job; all generated assets remain in its owner's private library |
| DELETE `/workflows/{id}` | Archives the draft, its runs and their child jobs; generated assets remain |
| DELETE `/workflow-runs/{id}` | Archives the run and its child jobs; preserves the draft and generated assets, clearing the draft's current-run pointer when applicable |
| DELETE `/batches/{id}` | Archives the batch, member runs and jobs; preserves workflow drafts and generated assets |
Archival removes resources from ordinary list/detail/control APIs while retaining audit rows. It releases obsolete job/input and snapshot references; it does not delete media or restore a cancelled run. The complete tree is validated before archival, so conflicts do not partially delete it.
- `409 parent_control_required`: a job belongs to a run/batch, a run belongs to a batch, or a draft still has runs belonging to a live batch. Delete through the required parent; delete the related batch before its draft.
- `409 deletion_requires_terminal`: a non-archived member is still active. Cancel first, then wait for terminal state. Allowed job terminal states are `succeeded|failed|cancelled|timed_out`; run terminal states are `succeeded|failed|cancelled`; batch terminal states are `succeeded|cancelled|completed_with_errors`.
- `409 cleanup_pending`: an execution has not reached `exited` or `results_ready`. Wait for confirmed execution exit/cleanup, even if the business record is already terminal.
- `409 resource_in_use`: another live run still selects a job in the proposed deletion tree for reuse. Delete the dependent run first. Private asset deletion uses the separate `asset_in_use` error above.
- `GET /submissions/{key}?operation=...` and replay of an archived record's original command return `410 resource_purged`. An old idempotency key cannot resurrect deleted records; intentionally creating new work requires a new submission.
Asset DELETE and shared withdrawal now remove the owned original/thumbnail files and hard-delete their Asset rows; withdrawal also removes the publication row. Independent published/imported copies survive. Missing files are accepted for retries, unsafe paths return `409 unsafe_asset_path`, and filesystem failures return `503 asset_delete_failed` without a false success; remaining DB rows allow retry. Active producers/consumers and unresolved executions return `409 asset_in_use`. Legacy soft-deleted files retain the conservative dry-run-first maintenance GC path. Model caches and historical task audit records remain independently managed.
## Jobs
`MAX_INTERACTIVE_GPU_JOBS` defaults to `0`, which disables the per-owner unfinished interactive GPU queue cap. Direct submissions, standalone retries, workflow step retries and automatic workflow replenishment use the same rule. Positive values explicitly enable that optional cap; negative values are invalid. Creation-rate, total unfinished-job, storage and execution-resource limits still apply. This is not a lifetime video count or a GPU concurrency setting.
- POST `/jobs`, optional `Idempotency-Key`, body `{task_type,input:{prompt?,negative_prompt?,image_asset_id?,audio_asset_id?,asset_id?,asset_ids?:string[]},parameters:object,count?:1..4,scheduled_at?:ISO8601|null}` → `{jobs:Job[]}`. Batch only for image/defect; each gets its own independent upstream job. Composition clip order and trims live in `parameters.clips:[{asset_id,start_seconds?,end_seconds?}]`, optional `audio_asset_id`, `subtitles:[{start,end,text}]`, width/height/fps. Server resolves owned assets only.
- GET `/jobs?page=1&page_size=24&task_type=&state=` → `{items:Job[],total,page,page_size,cursor:number}`.
- GET `/jobs/{id}` → Job.
- POST `/jobs/{id}/cancel` → Job, cancellation may remain pending.
- POST `/jobs/{id}/retry` → `{jobs:Job[]}` (user requested new generation, new business ID).
- Job: `{id,task_type,state,phase,version,prompt:string,parameters:object,input_asset_ids:string[],result_assets:Asset[],result:object|null,progress:number|null,queue_position:number|null,upstream_id:string|null,attempt_count:number,preemptions:number,last_preempted_reason:string|null,cancel_requested:boolean,error:null|{code,message,retriable},sync_warning:string|null,created_at:string,scheduled_at:string|null,started_at:string|null,finished_at:string|null}`.
- States: `scheduled,submitting,queued,running,collecting,cancelling,succeeded,failed,cancelled,timed_out`. Remote sync failures do not invent terminal failures; set sync_warning. Requeue is the same job ID and may go running→queued.
- Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly `num_inference_steps`. Video accepts5–361 integer frames with `num_frames % 4 == 1`, fixed24fps. The web duration input supports1–15 whole seconds and submits `24 * seconds + 1` frames; default5 seconds remains121 frames. A15-second native source contains361 frames (15.041667 seconds), not interpolated or slowed-down footage. No fake generation percentage.
- ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result `subjects,scene,ocr,tags,frames?`, timestamps reflect actual sampled frames. Math result `{text}`; ASR result `{text,segments}`; composition produces video asset.
### Creation image and multi-person video editing
These use the existing `POST /jobs`, owner-scoped assets, idempotency keys and durable SSE events. No new business tables or public media paths. Generated Asset DTOs additionally expose `source_output_index:number|null`; map analysis previews by this index, never by current array position, since a preview may have been deleted independently.
- `image.reference.generate`: input `{prompt,negative_prompt?,reference_asset_ids:string[]}` with 1–3 ordered, distinct private images. Parameters use `profile:'qwen-image-edit-2511-v1'`, sizes1024×1024/1280×704/704×1280, defaults `num_inference_steps:40,guidance_scale:1,true_cfg_scale:4,max_sequence_length:1024,seed:42`. `count:1..4` creates independent jobs with all reference images preserved. Profile/model mismatch or unavailable capability fails rather than falling back to text-only generation.
- `video.people.analyze`: input `{video_asset_id}`; parameters `{profile:'wan-animate-replace-v1',max_pixels:399360,fps:24}`. `count` must be1. Result `{profile,analysis_token,source_sha256,video:{width,height,fps,frames,duration_seconds},poster_output_index,people:[{id,label,thumbnail_output_index,first_frame,last_frame,confidence,samples:[{frame,bbox:[x1,y1,x2,y2]}]}],warnings:[]}`. Bbox coordinates are normalized0..1 against the display-oriented, square-pixel output; frame indexes start at0. Detection IDs are per-video tracks, not real identities.
- `video.replace`: input `{video_asset_id,analysis_job_id,prompt,negative_prompt?,replacements:[{person_id,reference_asset_id,prompt?:string}]}`. Global `prompt` must contain non-whitespace text; each selected person must be distinct and belong to that successful analysis. Parameters `{profile:'wan-animate-replace-v1',max_pixels:399360,fps:24,num_inference_steps:20,guidance_scale:1,seed:42,preserve_audio:true,mask_expand_pixels:8,mask_feather_pixels:4}`; both mask controls are integers0..64. `count` must be1. Public Job.result includes `{profile,person_ids,source_frames,output_frames,fps,width,height,warnings,final_output_indices}` plus the private video asset. The frozen source hash, actor/reference mapping and upstream execution proof remain in internal persistence; the lower-level inference result additionally contains `actor_mapping`, source SHA and duration/audio parameters.
Analysis must be successful, active and owned by the caller, reference the identical source asset/hash and use matching profile/fps/max_pixels. The server resolves its trusted upstream analysis ID/token; clients cannot supply mask files, arbitrary paths or another owner's analysis. Every selected identity image is held as a job input reference. Video-stream timeline, not a longer container audio tail, determines duration admission and binding. Original audio duration is frozen independently and optionally remuxed; no voice/face identity guarantee or new audio synthesis is implied.
Default configurable video budgets are120seconds/12people/399360pixels;720p budget921600 is accepted only if both sides explicitly support it. Replacing multiple people runs temporal model passes sequentially within one job and combines their visible masks into one output while protecting other actors/background. Ambiguous tracking fails closed. Close/disconnect has no cancellation semantics; use the existing explicit cancel command and wait for process cleanup.
## Events
- GET `/events?after=0` authenticated EventSource. `Last-Event-ID` header overrides query on reconnect.
- Durable event: `id: <integer>\nevent: job.updated\ndata: {"job":Job}\n\n`.
- Other events: `asset.created` data `{asset:Asset}`, `asset.updated` same; `asset.deleted` `{id}`, `reset` asks client to refetch snapshots. Heartbeat comments do not change cursor. Stream owner-filtered; logout/expiry ends stream.
- Record archival emits `job.deleted`, `workflow.deleted` (a run), `draft.deleted`, and `batch.deleted`, each with `{id,version}`. Cascades emit an event for each newly archived record. Treat these IDs as tombstones so delayed HTTP responses or older updates cannot reinsert deleted records; clear session state/tombstones on owner change. A surviving draft whose current run is deleted also receives `draft.updated`.
- Fetch jobs snapshot and cursor before opening stream; after reconnection refresh HTTP state as well. Ignore Job versions older than or equal to the current version.
## Backend provider interface
Implemented in `app/providers.py` and `app/media.py`, independent of database models.
`Provider(settings)` methods (async):
- `health() -> bool`
- `scheduler_status() -> dict` sanitized Scheduler above.
- `prepare_gpu_payload(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> dict` validated original upstream payload `{task_type,input,parameters,timeout_seconds}`. Input paths must be within shared workspace. Preprocess video ASR as needed.
- `submit(payload:dict,idempotency_key:str) -> dict` original upstream job response; retry only same immutable payload/key.
- `query(upstream_id:str) -> dict`, `cancel(upstream_id:str) -> dict`.
- `download(upstream_id:str,index:int,destination:Path) -> None` atomic streamed output, size bounded.
- `run_cpu(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> CpuResult`.
- `aclose() -> None`.
- `CpuResult` dataclass: `outputs:list[Path]`, `result:dict`, `metadata:dict`.
- `ProviderError(code,message,retriable=False)` has those attributes; no secret/path leaks in public messages.
- Settings attributes consumed: `inference_base_url,inference_api_key,inference_api_key_file,workspace_root,asset_root,job_work_root,gpu_status_path,gpu_scheduler_path,qwen_base_url,qwen_model,qwen_api_key,ffmpeg_bin,ffprobe_bin,tts_base_url,tts_model,tts_api_key,request_timeout_seconds,max_output_bytes`.
- `app/media.py`: `inspect_media(path:Path,settings)->dict` (kind,mime_type,width,height,duration_seconds); `make_thumbnail(path:Path,destination:Path,settings)->Path|None`. These are async, subprocess is fixed argv, bounded time/resources; no shell. Image validation can use Pillow. JSON/text generated outputs supported.
- `capabilities(settings)->list[dict]` returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible `/audio/speech` if selected later.
Production files live under `/workspace/cmvr-visual`. The website's business database is MySQL `192.168.28.10:3306/cmvr-visual`; media originals/thumbnails live on the host at `/data/llmusers/llmuser/workspace/cmvr-visual/assets`, mounted as `/workspace/cmvr-visual/assets`. The inference service's SQLite is an independent GPU scheduling/recovery store, not the website business database. Database and media backups must be coordinated. These are operator deployment locations, not fields exposed in public resource DTOs.
Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt.
## V2 additions
HTTP remains the command/query channel, SSE the owner-scoped notification channel. `execution_policy` is returned by capabilities/status: `{timezone:'Asia/Shanghai',start:'21:00',end:'08:00',batch_open,next_batch_at,close_behavior:'finish_current'}`. The server accepts and persists batch commands all day; only new compute phases are gated. Current work is never killed by the clock or a browser disconnect.
- GET `/live` process liveness; GET `/ready` 200/503 with database, coordinator, upstream_protocol and accepting checks. GPU capacity does not affect readiness.
- User DTO adds `disabled,must_change_password`; GET/PATCH `/auth/users[/{id}]` administer users, POST `/auth/password` `{current_password,new_password}` revokes sessions and requires relogin.
- Session POST `/auth/username` `{username,current_password}` → current User DTO. The normalized login username must be unique and match 3–64 lowercase letters/digits/`_.-`; a correct current password is required. User ID, role, resources and existing sessions remain unchanged. Renaming the bootstrap administrator does not recreate the old administrator on restart.
- User management requires a current administrator session and CSRF on writes. Disabling revokes browser sessions and suspends admission without deleting resources; re-enabling clears only `admin_suspend` and preserves manual holds. Bearer access is denied while disabled.
- Admin DELETE `/auth/users/{id}` removes the account and its owned records, assets, thumbnails, publications and local job files, preserving independent copies imported by other users. It returns 204 only after cleanup. Active execution, upload or file writes first cause durable disable/cancel and 409 `cleanup_pending`; retry after confirmed cleanup. Self-deletion is rejected. Unsafe paths return 409 `unsafe_user_path`, foreign resource consumers return 409 `resource_in_use`, and file failures return 503 `user_delete_failed` while retaining the disabled account for retry.
- GET/POST `/auth/tokens`, DELETE `/auth/tokens/{id}`. POST `{name,scopes,expires_at?}` returns `{token,record}` once. Use `Authorization: Bearer ...` for machine calls; tokens never grant admin authority. Interactive use additionally requires `interactive:write`.
- POST `/jobs` adds `execution_mode:'interactive'|'batch'`; new UI always persists and supplies an Idempotency-Key. GET list adds `root_only=true` to exclude workflow children. Job DTO adds `run_id,step_key,batch_id,batch_item_index,execution_mode,explicit_attempt,desired_state,hold_reasons,current_execution_id`. States additionally include `paused,pausing,needs_attention`.
- POST `/jobs/{id}/retry` honors Idempotency-Key; legacy callers omitting it explicitly create a fresh attempt without replay guarantees. Parent-owned children require their parent retry/control APIs.
- GET `/submissions/{key}?operation=jobs.create|jobs.retry|workflow.run|workflow.retry|workflow.pause|workflow.resume|workflow.cancel|batch.create|batch.control|assets.publish|shared.import` recovers owned resources. Replaying the original key and immutable JSON is safe after a lost response while its resources remain available; 404 alone does not prove an in-flight command was rejected. Archived resources return410 as specified above.
- POST/GET `/workflows`; GET/PATCH `/workflows/{id}`. PATCH requires `If-Match: <version>`. Draft edits increment revision; new Runs freeze a snapshot.
- POST `/workflows/{id}/runs` `{draft_revision,expected_version,execution_mode?,reuse_run_id?}` plus Idempotency-Key → `{draft,run,steps,jobs,cursor}`. GET `/workflow-runs` is paginated; GET `/{id}` returns the consistent snapshot.
- POST `/workflow-runs/{id}/pause|resume|cancel` `{expected_version?}` plus Idempotency-Key. Pause closes future admission and drains current work. Cancel remains pending until cleanup/completion is known.
- POST `/workflow-runs/{id}/steps/{step_key}/retry` `{expected_run_version,target_job_id}` plus Idempotency-Key retries only the selected failed step, preserving other successful shots and inherited mode/holds.
- POST `/batches` `{name?,items:[{kind:'workflow',draft_id,draft_revision,expected_version}|{kind:'job',task_type,input,parameters?,count?}]}` plus Idempotency-Key. Maximum100 items, fixed `batch` mode, one active member per batch. GET list and `/{id}` snapshots; POST `/{id}/control` `{desired_state:'run'|'pause'|'cancel',expected_version?}` plus Idempotency-Key.
- Asset list additionally accepts `favorite` and `origin` SQL filters. Workflow references protect frozen inputs/outputs from physical deletion.
- SSE adds `draft.updated:{draft}`, `workflow.updated:{run,steps,jobs}`, `batch.updated:{batch,items}` with object versions. Ignore older/equal versions; reconnect/reset refreshes HTTP snapshots. Machine SSE requires `events:read` and Authorization, never tokens in URLs.
Legacy workflow spec schema1 remains exactly ordered `shot_1,shot_2,shot_3`, each `{key,prompt,image_asset_id:null|string,parameters:{seed}}`, with360 frames at24fps. Its serialization and generation hashes remain compatible.
## Story studio v3 additions
Stories use independent `/stories` endpoints and `WorkflowDraft.kind=story_v3`; legacy `/workflows` excludes these records. The full field/endpoint contract is [Story studio specification](design/2026-11-11-story-studio.md); executable usage is in [API examples](API-examples.md). MySQL revision005 adds `visual_shot_candidates` and append-only `visual_shot_selections` without changing historical001–004.
GET `/stories/{id}/film` returns `{asset, draft_revision}` for the latest successful, accessible final video in the caller's story, across manual and automatic runs. Play the authenticated `asset.preview_url` or download `asset.download_url`. An existing story with no completed film returns HTTP 200 and JSON `null`.
DELETE `/stories/{id}` accepts the current story version in `If-Match`. Confirm the destructive action once before issuing it. The service archives the story, its runs and candidates, and removes private, unfavorited assets exclusive to that story, including their files and thumbnails. Favorites, other works’ assets and references, and independent published copies remain available. A completed deletion returns HTTP 200 with the removed IDs in `deleted`, including `asset_ids`. HTTP 202 means the request was recorded and the story has been removed from the list. The coordinator cancels outstanding work and completes cleanup automatically. Individual candidate, workflow-history and folder deletion have their own contracts.
- The v3 spec contains story context, scenes, entities with forms/appearances, stable shot IDs and cast references, frame/video parameters, per-shot trim, and the existing audio/subtitle render settings. Plain JSON contains intent, never trusted approvals. PATCH uses `If-Match`; commands freeze `expected_version` and an Idempotency-Key.
- Reference inputs are the first-occurrence ordered unique private asset IDs. The compiled prompt binds Picture numbers and unique subject aliases to the same ordered files; forms/appearances name their owning subject. `image.reference.generate` requires the enabled identical profile at both API and upstream, accepts at most3 pictures by default, and never silently falls back. Explicit text mode removes the attached-picture instructions and actually sends no images.
- Candidate DTO `input_summary` exposes `reference_mode`, `actual_reference_asset_ids`, `model_profile`, `seed`, `prompt` and optional `first_frame_asset_id`; it does not expose filesystem paths or credentials. Readiness and selection reject stale/missing/deleted/inaccessible results. Completion never selects a candidate automatically.
- Generated video requires an approved current first frame; its requested source length is1–15seconds and must cover trim before dispatch. Manual video needs neither a frame nor a generation prompt, and checks its actual source independently of unused generation parameters. Start frame is nonnegative, each selected clip is24–360frames, final source bounds are verified against real decoded media.
- V3 Runs freeze the story and ordered selected asset/SHA/trim/audio/subtitle inputs and contain only a compose step. Historical Runs do not recompile current draft intent. Deleting a shot appends empty current selections while retaining prior approval audit; reintroducing its ID cannot resurrect old approvals.
- New owner events: `story.updated`, `candidate.updated`, `selection.updated`. Reset/reconnect refetches complete loaded scopes with version/session/tombstone guards; it never resubmits generation. Machine-token scopes map stories and `story.*` submission recovery to `workflows`.
- Pending candidate plans have separate owner/global budgets4000/16000; internal bounded admission uses existing active Job quotas. Creation/retry/render commands share the existing per-minute budget and immutable replay rules. No per-user8-video limit is introduced.
Schema2 accepts1–1000 sequentially ordered `shot_N` entries with additional `duration_frames` (strict integer24–360, default120). New submissions are additionally bounded by the operator's configured shot limit. `profile=landscape_1080_v1|portrait_1080_v1`; `render={fps:24,total_frames?:integer,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}`. Omitted total_frames is derived from shots; a supplied unequal value fails validation. Each shot generates `max(121, 4 * ceil(duration_frames / 4) + 1)` source frames and composition trims to the requested frame count. A5/10/15-second workflow requests121/241/361-frame sources and produces720 final frames (30 seconds). Schema1 retains its original3×5-second contract. Audio must fit the entire dynamic timeline explicitly and subtitles use whole-film half-open frame intervals. Run total_steps is shot count+1, and steps/compose inputs follow snapshot order, including shot_10. New draft kind is multi_shot; three_shot remains accepted.
Capabilities and system/status include `workflow_limits={max_shots,source_frames:121,default_source_frames:121,max_source_frames:361,default_clip_frames:120,max_clip_frames:360,fps:24}` and `execution_policy.batch_window_enabled`, `configuration_error`, nullable `next_batch_at`. `source_frames` remains a legacy default; it is not the maximum. New snapshots freeze `compiled.shot_generation_parameters` keyed by shot; legacy snapshots without that map use their original frozen shared parameters. Long-source frame counts participate in reuse/retry semantic hashes, so a short source cannot satisfy a longer shot. The backend environment variable `GPU_WINDOW_ENABLED` now owns the project window. It defaults to true in production; real local development explicitly sets false in `.env.local`, independently of `CMVR_MODE`. Both interactive and batch use the same Asia/Shanghai 21:00–08:00 admission window. Changing this environment setting requires an API restart; deploy after draining active work. The legacy HTTP fields `execution_policy.batch_window_enabled` and `batch_open` expose the effective project setting rather than a batch-only exemption. The operator-owned `RUNTIME_POLICY_FILE` remains hot-read for workflow limits, configuration validity and legacy inference requests; remote mirroring must not overwrite the project environment switch. Malformed/unavailable policy still fails closed for new compute in both modes. Closing the clock window lets the currently admitted phase finish and defers later phases.
Manual video.compose no longer has a24-clip or1800-second final-duration cap. New commands respect the same configured clip-count limit; source cuts stay within decoded media and a86400-second source bound. Output/intermediate size, storage, process and overall execution time budgets still apply.
Private inference protocol2 carries server-generated `scheduling={execution_mode,principal_id,batch_id?,run_id?,step_key?,policy_version:'night-v1',gpu_window_enabled?:boolean}`. The optional window snapshot is a strict boolean supplied only by the trusted business backend; browser-facing job requests do not accept this field. `/capabilities.features.project_gpu_window=true` certifies support. Inference selection and final launch apply the per-job snapshot to either queue mode, allowing isolated local and production backends to share a worker. A request without the new field keeps its old normalized shape/hash and falls back to the legacy operator-file window, which also applies to both modes. Enabled production backends fail closed against an upstream missing this feature; disabled development can retain the old protocol but cannot thereby override an old worker global window. Already frozen payloads are not rewritten: unsafe unbound production packets enter needs_attention with outcome-unknown guidance, preserving their idempotency keys and cancellation intent. The service also reports admission_pause/control_versions/final_output_indices. GPU result metadata identifies final enhanced output indices; workflows never choose the native intermediate by list order. Internal phase callbacks acquire separate `new_gpu`, `cpu_media`, `qwen_http` slots. No endpoint accepts arbitrary PIDs, Docker IDs, FFmpeg scripts or server filesystem paths from web users.
## Editable production (007)
`GET /editors/{draft_id}` returns `{draft_id,name,version,revision,manifest,issues,assets}` for the current owner. A legacy draft is converted without writing. New editor writes require a live session, CSRF, transactional session recheck, and draft version CAS. Existing story spec writes/runs return409 `editor_required` while automatic mode is active; an explicit switch to manual permits the synchronized manual interfaces.
- `POST /editors/{id}/save` `{expected_version,manifest,name?}` + Idempotency-Key; server resolves private asset identities and SHA, reconstructs all draft references, and saves structurally valid authoring conflicts as issues. Optional name is trimmed, nonblank and at most255 characters; omitted/null keeps the existing name. Name and manifest commit atomically with one version increment. `capabilities.name_edit=true` declares support; old clients and old no-name idempotency receipts remain compatible. Historical Run inputs do not change when a draft is renamed.
- `POST /editors/{id}/from-run` `{expected_version,run_id}` + key restores an owned same-draft frozen configuration and resolved assets; it is an explicit whole-version restore.
- `POST /editors/{id}/plan` `{expected_version,output_goal:media|film,targets:[],force:[],execution_mode,output_folder_id?}` returns `{plan_hash,source_version,steps,issues}`; no model executes.
- `POST /editors/{id}/runs` adds `expected_plan_hash` and an idempotency key;202 returns RunSnapshot. The server recompiles the plan under the acceptance transaction. Binding targets use `frame:<stable_id>`, `video:<stable_id>`, `audio:<segment_id>`, plus `script/captions`. Fresh seeds are accepted once; retries preserve frozen inputs.
- `POST /editors/{id}/apply` `{expected_version,run_id}` + key only accepts a succeeded Run whose source draft version still matches. A stale result is preserved and returns a conflict, rather than replacing later edits.
The independent `editor_manifest.schema_version=1` contains source spec, stable shot IDs, private asset bindings, audio mode/segments and caption cues. Old workflow/story schemas remain1/2/3. Incoming manual bindings may omit SHA; persisted bindings always use server facts. Text and timing overrides are independent. Final composition alone projects relative cue anchors to existing24fps absolute subtitles and a single selected audio track.
Auto runs use `story_auto/workflow_auto`, target-driven typed Steps and direct Jobs; they do not write manual ShotSelection/ShotCandidate. `output_goal=media` publishes target assets without changing the film pointer. `film` requires compose success. Source and step-input snapshots remain immutable, `result_manifest` records resolved editable results, and `apply_state=conflict` leaves subsequent authoring untouched. Output references belong independently to each draft/run; reuse points to asset+SHA, not an old selected Job.
New CPU tasks: `text.script.generate` uses the shared Qwen HTTP resource pool and returns per-shot JSON; `audio.assemble` consumes owned segments at frame offsets, normalizes48kHz and writes an exact-length WAV. `audio.speech` supports an optional frozen model check and independent timeouts. Speech health only confirms configured/reachable protocol; it does not certify model quality. Unknown execution outcomes remain blocked until reconciled.
Stories support reversible editing modes without a schema migration. `EditorManifest.editing_mode` is `auto|manual` (existing manifests default to `auto`; drafts without a manifest are manual). StoryDTO and EditorDTO expose `editing_mode` and `capabilities.mode_switch`. `POST /editors/{id}/mode` accepts `{expected_version,mode}` with session/CSRF and `Idempotency-Key` (`editor.mode`), and returns EditorDTO plus the complete authoritative `story`. Only story_v3 is supported. The command checks owner, CAS and unresolved work, advances the draft version, and retains the manifest and run history. Auto bindings become unapproved manual candidates with provenance; no approval is fabricated. Manual PATCH/confirm/clear synchronize the manifest and references. Auto-only writes reject manual mode; callers cannot change modes by posting a manifest field. Legacy first editor.save remains compatible but checks idle work before conversion.
New automatic story composition inputs freeze decoded source width, height, fps and source frame count, plus the selected audio SHA. Historical inputs missing video dimensions are executed by verifying the frozen video SHA before deriving missing dimensions from those exact bytes; stored Job/Step inputs remain unchanged. Existing dimension, fps, duration and SHA conflicts still reject execution.
## Dialogue production (Story V5 / Editor V3)
Dialogue authoring is independently versioned; it does not replace historical story or workflow contracts. `POST /editors/{draft_id}/dialogue/enable` accepts `{expected_version}` plus Idempotency-Key (`editor.dialogue.enable`) and returns EditorDTO. It requires an idle owned story, a live session and CSRF, upgrades the story to schema5 and the editor manifest to schema3, and retains the stable shot IDs and existing media. New enabling and explicit upgrading of an old V5 story now set `dialogue.generation=native_av` and `language=Chinese`; merely reading an old story does not upgrade it. Switching editing modes preserves dialogue data. The following legacy preparation/rendering details describe already-frozen historical runs; new execution uses the native contract below.
- Story V5 contains `dialogue.speakers`, `dialogue.utterances`, `dialogue.sequences` and each shot's `performance`. Speakers bind their own voice configuration/reference and visual entity. Utterance text is separate from shot motion intent. Fixed reference audio determines a cloned voice; a different `voice` alias alone is not proof of a different timbre. Kokoro continues to synthesize the selected preset; its independent reference is for verification.
- The existing editor plan/run/apply APIs accept dialogue manifests and typed targets including `speech:<utterance_id>`, `base_video:<shot_id>`, `face_tracks:<shot_id>` and `synced_video:<shot_id>`. Preparation resolves normalized48kHz speech and placements before materializing visual Steps. One24fps frame is2000 audio samples; half-open sample/frame bounds remain exact across cuts, stems, mix and captions. Manual subtitle text/timing protection remains independent of regenerated speech.
- `POST /editors/{draft_id}/dialogue/fork-prepared` accepts `{expected_version,run_id,name}` plus key (`editor.dialogue.fork_prepared`) and returns201 EditorDTO with `origin:{source_draft_id,source_run_id}`. It creates an independent owned draft from an owned same-story V5 run whose production structure and timing have materialized. Source version CAS still applies; missing structure returns409 `preparation_incomplete`. It retains the source story/run and does not report the unfinished run as a completed movie.
- Business `GET /capabilities` exposes `dialogue` and `editable_production.dialogue`: `{authoring_available,available,production_available,supports_single_face,supports_two_faces,max_visible_speakers,reason}`. Authoring may remain available when production is blocked. Single-person readiness requires all corresponding local flags and measured phase certificates; two-person readiness additionally requires the local two-face flag and at least two certified visible people for analyze/render/inspect. Clients must use the reported bound, not infer support from the schema accepting two roles.
### Silence policy and measured evidence
New dialogue plans freeze `final_render_contract.speech_silence_policy='source-rest-v2'`, the adapter profiles/revisions, `mouth_blend_policy='semantic-skin-ellipse-v1'` and `audio_context_shift_policy='bounded-feature-shift-v1'`. New render and inspect requests explicitly carry the frozen silence policy. Historical graphs keep their original parameters and semantic hashes; an omitted historical policy is expanded to `neutral-rest-v1` only at the provider transport boundary.
The private inference capability document can publish both measured policy sets at once:
| Evidence path under private `dialogue` | Consumer |
| --- | --- |
| `lipsync`, `inspect` | Legacy flat `neutral-rest-v1` certificates remain compatible with old consumers |
| `silence_policies.neutral-rest-v1.lipsync` / `.inspect` | Exact v1 requests and historical frozen graphs |
| `silence_policies.source-rest-v2.lipsync` / `.inspect` | New v2 plans and explicit v2 requests |
When `silence_policies` is present, the backend selects only the requested policy's nested task evidence. A missing, malformed or unavailable nested entry fails closed; it cannot borrow the flat certificate or the other policy. An older upstream without this map can satisfy a request only if its flat evidence exactly matches that request's policy. In either shape, admission checks the task/profile, pinned revision, adapter contract, decision, report SHA, mouth policy, feature-shift policy where required, and certified people limit. Evidence is derived from actual successful queue jobs and measured controls; clients cannot submit an `available` or certification override. Experimental preview profiles do not satisfy the production MuseTalk certificates.
For v2, silent actor frames retain the source mouth rather than running a synthetic neutral-rest patch. Render receipts include `speech_silence_policy`, `base_sha256`, `synced_sha256`, per-speaker `source_rest_frames`, and the frozen mouth/shift policies and shift value. Inspection includes `source_rest_checks`, `rest_checks` and `silent_mouth_source_checks`, with per-speaker silent intervals and source/output evidence. The collector verifies the frozen base and candidate SHA, speaker coverage, policy and interval consistency before publication. Insufficient evidence is indeterminate; a QA pass is not a guarantee of subjective likeness, fine facial texture or satisfactory acting.
`performance.audio_context_shift_frames` is an integer from−6 to6. Positive values advance acoustic feature conditioning; negative values delay it. Audio PCM, subtitle positions and video frame timing are not shifted. Automatic compensation is bounded and requires sufficiently strong single-speaker offset evidence, passing source-rest checks, remaining repair budget and matching independent reinspection. A definite `source_speaking_during_silence` rejection can instead select the source-video repair root; uncertain source evidence does not authorize repeated generation. Locks and frozen TP2 authorization remain enforced.
### Pre-lipsync visual review and repair
For a v2 shot with `lip_sync='required'` and an actual downstream v2 inspect step, `video.dialogue.review` uses `input.expected.source_visual_policy='pre-lipsync-visual-v1'`; its report echoes `source_visual_policy`. This phase checks identity, clothing/composition, obvious face or mouth deformation, non-mouth action continuity, black frames and freezing. It does not decide speech-window timing or reject a raw source solely because lips are slightly open, moving, or naturally expressive. The downstream audio-window and source/output mouth inspection still performs that separate check. Missing/mismatched policy evidence cannot be accepted as the new review result.
For these source-v2 speaking shots, a rejected visual review repairs the source-video step while retaining the selected first frame. The frame and speech stems are not automatically regenerated for a timing or resting-mouth issue. Existing locked base/final/downstream bindings still prevent automatic overwrite. A new frame is an explicit authoring action; unsuccessful or indeterminate checks preserve prior completed movies and accepted resources.
### H3 native dialogue (local implementation)
This contract is implemented in the local checkout. It is not a claim that the deployed inference service has been upgraded or certified. New submissions fail closed until the independent native capabilities are available.
- Story V5 / Editor V3 remain unchanged in version. Optional fields are `dialogue.generation='native_av'`, `dialogue.language`, `speaker.native_voice` and `shot.performance.native_utterance_ids`. Absent optional fields preserve historical serialization. The existing utterance `source='tts'` tag represents text-authored lines in native mode; it does not schedule a TTS Step. Native voice descriptions guide generation; they do not guarantee reference-voice cloning or identical timbre across shots. Recorded utterance inputs and old reference recordings require an explicit user conversion/removal, never silent omission.
- The native DAG is first frame → `video.generate` → `audio.dialogue.extract` → `audio.dialogue.inspect` and `video.dialogue.review` → internal `dialogue.accepted` → `audio.mix`, `captions.compile`, `video.compose`. New native runs create neither `audio.speech` nor MuseTalk rendering Steps. Previously frozen legacy runs retain their original Steps and recovery semantics. New legacy creation requires an explicit native upgrade.
- Each shot uses one speaking role and at most one visible person. Assign each whole utterance exactly once; multi-shot sequences require explicit allocation, and `[]` means a silent reaction shot. Overlong or unassigned lines block admission. Fixed timing uses a whole native clip from frame zero; it cannot trim a sentence. Certified authoring currently supports Chinese, normal cuts and first-frame conditioning. Unsupported two-person scenes, continuous endpoints or other unvalidated combinations fail with actionable issues.
- Native profiles are `minimax-h3-fl2va-native-av-v1` and `minimax-h3-fl2va-native-av-tp2-v1`, distinct from silent profiles. They use 24fps full-native video, no upscale, 124..345 frames in steps of17 for single GPU, or124/141/158 for TP2. Outputs include an MP4 and the complete 32kHz stereo PCM WAV. The 40Hz audio latent grid may differ from video duration by at most12.5ms in either direction. The source WAV remains archived and referenced independently; no blind `-shortest` or audio stretching is permitted.
- Extraction uses `audio_policy='native_av_v1'` and prefers the original WAV sidecar over AAC decoding. Normalized audio is48kHz stereo. Spoken native inspection uses `native_av_policy='native_av_v1'`, actual Whisper word timestamps and exact normalized text matching. Independently executed SenseVoice confirms the same source selection without receiving the script. Required spoken evidence includes `content_verification_policy='whisper-sensevoice-consensus-v1'`, `secondary_status='completed'`, both actual transcripts, zero secondary content error and pinned secondary model/runtime revisions. Missing or disagreeing spoken evidence blocks acceptance. Reports include source SHA, timestamps and offsets; expected author text never replaces ASR output. Caption projection retains actual word/sample boundaries and text normalization; protected manual text and timing remain independently checked.
- Only genuinely empty expected dialogue may use `silero-sensevoice-verified-silence-v1`: pinned Silero CPU VAD reads the same original WAV, independently resamples and checks every channel/window, and requires no-speech probabilities below0.35 on both channels plus a completed genuinely empty SenseVoice result. Full source SHA/sample bounds, channel probabilities and their per-window maxima are verified. Whisper's actual hallucination, content error and invalid word timestamps remain in the report; silence creates no fictional word alignment. Nonempty expected dialogue cannot use this policy. Missing weights, changed source, uncertain evidence or detected speech blocks acceptance.
- `GET /capabilities` exposes `dialogue.native_av` with strict native readiness and supported languages. Business settings `NATIVE_DIALOGUE_ENABLED` and `NATIVE_DIALOGUE_TP2_ENABLED`, upstream settings `native_dialogue_enabled` / `native_dialogue_tp2_enabled`, independent profile evidence and native word-alignment evidence must agree. Silent H3 or MuseTalk certificates cannot enable native generation. Frame-only closures do not depend on speech readiness. GPU windows still apply to interactive and batch alike.
- Each native `items[video.generate].video_profiles[]` option exposes its audited `canvases`, a nonempty ordered subset only when certified. `available=true` does not authorize other geometries. Frontend, business payload preparation and final inference admission enforce that exact scope; a new explicit native request outside it returns422 `native_canvas_uncertified` at the business API. The initial production release certifies only TP2 `[[1344,768]]`; portrait native and single-GPU native remain closed. Replaying a previously accepted identical request/key returns its existing Job even after a certificate narrows; it never creates an uncertified job, and worker checks still block execution outside current scope.
- Supported targets include `frame:<shot_id>`, `video:<shot_id>`, `native_alignment:<shot_id>` and `captions`. A video target includes its acceptance closure. Forcing native alignment reruns ASR/acceptance, not H3. Text, voice, language or image changes invalidate the corresponding generated clip; caption-only and BGM-only changes reuse unchanged H3 outputs. Native BGM is a separate film-wide layer, never independently generated into each shot. Old standalone narration is explicitly disabled or converted to dialogue before native film generation.
- Server-managed `native_audio`, `native_report` and `native_alignment` bindings use stable shot IDs and are read-only to clients. Source video plus WAV, inspection report and visual review are SHA/owner checked. Existing locks, expected-version/plan-hash CAS, idempotent replay, cancellation, disabled-user checks, immutable snapshots and history asset references remain effective. No client-supplied certification bypass is accepted.
- Manually imported video is retained for preview but cannot be declared native by posting provenance. The native plan requires an explicit force-regeneration action to replace it; otherwise `native_import_unsupported` blocks submission. Frame-only generation preserves authored timing for the whole story. Silent reaction and off-screen speech reviews require resting closed lips on screen; only a visible active speaker is expected to articulate. These visual expectations participate in the review context hash.
### Owner-protected recovery of a legacy manual frame
`POST /workflow-runs/{run_id}/steps/{frame_step_key}/restore-manual-frame` accepts the following strict body plus Idempotency-Key (`workflow.restore_manual_frame`), and returns the usual RunSnapshot with HTTP200:
| Field | Meaning |
| --- | --- |
| `expected_run_version` | Required positive run-version CAS |
| `target_job_id` | The currently selected replacement-frame generation job, already cancelled and fully cleaned up |
| `rejected_review_job_id` |32hex ID of the exact latest rejected legacy visual review that requested this repair |
| `frame_asset_id` |32hex ID of the frozen manual first-frame asset to restore |
| `frame_sha256` |64hex SHA256 of that same frozen asset |
This narrow command recovers a manual input removed by an old review's frame-repair branch; it is not a general frame override or QA approval. The run must belong to the caller, remain desired `run`, and be `running`, `queued`, or blocked at this frame step. The frozen frame must be manual and match both supplied identity and SHA. The latest matching assessment must be a rejected `repair_requested` variant from the old review policy. The selected replacement frame Job must match this run/step/attempt, be `cancelled` with cancellation requested, and have no execution awaiting exit; the normal owned Job cancellation API performs cancellation before recovery. The source video and affected downstream steps must still be waiting without selected jobs, and all existing locks remain effective.
On success, the frozen manual frame is restored, its frame Step becomes succeeded, only the still-waiting source-video branch is reset, and the run continues. A `manual_frame_recovery` provenance record retains the cancelled Job, rejected review, restored SHA and video-step linkage; old Jobs, assessments and the repair count remain intact. There is no replacement upload, manufactured QA pass, cross-owner access or rewrite of completed media. Machine callers retain normal scopes, including `interactive:write` for interactive runs. Failure codes include409 `run_version_conflict`, `frame_recovery_unavailable`, `cleanup_pending`, `dependency_changed` and `quality_repair_locked`; foreign resources remain404. Replaying the same accepted key/body is safe, while a changed body conflicts under the existing submission contract.