Ribbon refinement remains retired under the v1.28.0 contract. Historical worker/commit tests seed explicitly already-accepted records in tests only; no production test admission switch or new refinement route is introduced. Supported new submission concurrency/idempotency is exercised through generation.
Read-only UI requests bind task/lifecycle/revision context before applying data or401 effects. Late reads cannot replace or expire a newer task. Material JSON GETs have a20-second deadline; an accepted upload whose first read fails retains its task ID and exposes read recovery without submitting again. Writes, uploads, SSE and downloads do not inherit that deadline. Admin restoration clears secret inputs and re-enables controls via validated fresh settings; malformed successful HTTP bodies do not imply saved settings.
image_budget is a process-local FIFO estimated workspace admission shared by material and ribbon image operations, not a measured or hard RSS limit. Reservations precede state/database locks and encompass decode, conversion, save and thumbnail temporary lifetimes. Network/model waits do not hold reservations. Header probes reject unsupported/animated formats and excessive metadata before pixel allocation; WebP uses fixed headers before Pillow's full-file parser. The optional quality diagnostic computes equivalent differences in tiles without changing output pixels or automatic acceptance.
Archive admission counts physical central-directory headers before constructing ZipInfo objects and bounds native LZMA dictionary allocation. Workbook XML readers all consume actual streamed EOF/CRC, check cancellation and bound retained structure/text; only real direct worksheet rows/shared-string records reset released-record budgets. Large worksheets are streamed rather than capped by their total uncompressed size. Numbering export patches target rows through private spools, validates the complete sheet and every copied member, and publishes exclusively. Untouched XML segments and archive member contents retain their bytes. Any cancellation, open/write/close/CRC failure removes only this operation's newly created output and temporary files; original and pre-existing output files remain protected.
These resource and recovery changes do not change matching/qualification, numbering, pixel content, provider requests, task ownership,50-hour retention or credential policy. Evidence and actual release status are recorded in docs/phase1-quality-v1.28.1.md.
New ribbon refinement is retired. The authenticated, owner-checked legacy POST returns410 without planning, accepting work, writing a version or charging quota. Service.submit may replay a matching previously accepted idempotency record, but rejects new refine work before provider configuration or execution. Public current editing capabilities are empty and maximum new refinements is zero; immutable historical snapshots are not rewritten.
GET /api/jobs/by-request/{key} is an authenticated owner-scoped, no-store recovery read. It returns the existing public job,404 for unknown and410 for an expired tombstone. It does not return request text or payload and does not enqueue work. New clients resolve legacy pending refinement requests by this read only; failed reads retain context rather than resending the retired POST. Existing job execution/commit checks remain solely for previously accepted legacy work.
The workspace removes refinement inputs, scope overlays, suggestions, receipts and quota presentation. Editing selection after a saved output produces a new independent work through the existing create/generate path; the existing work and its version-bound downloads remain immutable. Trials use the current new-work profile/engine, while historical preview/downloads retain their saved profile/engine. Library, references, background generation, ownership, deletion/restore and50-hour retention remain. Material extraction's separate refinement is outside this change.
Image generation readiness depends on image credentials; language capability is checked only at the legacy planner entry. Shared DeepSeek and material/numbering settings are not deleted. Historical contracts below describe retired capabilities and do not authorize new ribbon refinement.
The integration preserves main's progressive style trials, quiet backgrounds, bounded output-review retry and persistent cloud sessions while adding request-v2 and layout-v3. Existing works retain their bound engine and output profile. Style changes must change real geometry; a style label alone cannot create a successful refinement. Candidate requests for an existing work bind its current version/profile/engine, not the global new-work defaults. UI requests cancel stale trials and reject late results after work, version, selection or style changes.
Request-v2 receipts distinguish source/plan validation from physical and image verification. V2 exact geometry checks remain; V3 currently records parameters_applied_unverified and does not claim exact measured request satisfaction. Generated-image semantic effects remain unverified. A settled output_policy rejection may retry once under existing policy; the first FAILED and next STARTED calls are durably recorded before the second dispatch, each with its own safe usage and request ID. Unknown results never retry.
The independent codex/ribbon-layout-understanding branch starts at cd198d4 and is integrated in v1.27.0. New works bind seamless-unit-v3; saved v1/v2 ancestors keep their engines and immutable templates, sources, snapshots and downloads. Historical branch evidence is separate from final deployment acceptance.
V3 selection optionally accepts pattern_roles, keyed by selected asset ID. All modes accept main and decoration. The legacy mode-specific roles remain valid for scene (support, accent), scatter (accent) and bordered (border). At least one main is required. By default the first non-decoration pattern is main and the remaining ones are support in scene; other modes default to main. Decorations are excluded from mode-specific main counts, sequences and style slot parameters. Geometry and raster generation place each decoration intact and proportionally in available space. Placement preserves the selected layout, including blank central and zone boundaries, and fails explicitly if it cannot fit the selected decorations.
Ownership, references, mode and values are validated server-side. Snapshots bind the mapping to stable pattern_slots. Omitted roles inherit the parent choice when the mode is unchanged; on a mode change omitted decorations are retained and other omitted roles reset. An explicit empty mapping restores defaults. Roles bind geometry signatures and saved downloads. Designs without decoration retain their existing layout path. Historical v1/v2 designs and snapshots retain their original engines.
Teaching cases add per-mode mode_notes with fit=direct|partial, look_for and difference. A partial case is a limited teaching reference, not an equivalent generated composition. eligible_ai_reference(code, mode) permits only a registered, matching, non-reference-only case whose current mode has fit=direct; the service rechecks this with the private whitelist and fixed bytes before any explicitly requested AI draft reference is sent. Browsing sends nothing. Original company previews stay private; only code-drawn v3 demos enter the hash-pinned public release allowlist. See branch progress for evidence and deferred merge/Linux/deployment acceptance.
New works bind seamless-unit-v2; every saved ancestor retains its engine, dimensions, immutable source references and version-bound downloads. Geometry derives the complete foreground repeat before background construction. Per-instance scatter rotations are deterministic; no mirroring is introduced. Relative main/support size factors survive common safety fitting. Density changes real sizes/gaps and only mode-permitted rows. Engineering continuity warnings remain visible and are not print acceptance.
Selection adds optional zone_background_refs (mode-specific left/center/right or top/bottom) and border_ref (an accessible pattern strip). Server ownership, enabled assets, mode keys, immutable provenance and retention references cover all additions. One main motif is valid in v2 bordered mode with program continuous lines and optional independent strip; legacy validation remains bound to its saved engine. Explicit independent zones can share a source but never pretend one generated square contains independently editable layers. Normal AI draft remains one image request; using fully independent backgrounds requires disabling an otherwise invisible draft request.
Refinement adds edit_target, default layout, bound to the submitted base_version_id. New snapshots keep stable pattern_slots aligned to immutable asset_refs, optional slot_params, zone backgrounds/colours and border references. Selecting a pattern edits all copies of that slot while keeping layout-defined scale/direction differences; changing content updates the asset reference without changing the slot identity. Zone and border targets are explicit. Provider plans see allowed operations plus measured geometry and target scope, not visual artwork. The service rejects foreign, stale, unsupported and ineffectual changes before image dispatch. Original unedited sources and completed parent versions remain immutable.
Provider call intent is persisted before dispatch in the existing provider_calls table, without schema migration. Structured diagnostics inside its error field contain only static whitelisted classification, request ID, known HTTP status and lifecycle stage; original upstream bodies, prompts, pictures and credentials are excluded. Orphaned started calls reconcile to UNKNOWN, with no automatic replay. Historical failures that lack fields remain explicitly unavailable. Employee error messages are static and actionable; administrator-only overview details expose the safe records. Successful version commit remains authoritative for the two-refinement quota; subjective design satisfaction is not inferred from pixel differences.
Ribbon assets add thumbnail_url: authenticated /api/ribbon/assets/{id}/thumbnail?v=asset-preview-v1-{source-sha-prefix} returns a proportional RGBA PNG of at most640px. Source path/hash plus derivative implementation bind its filename; nullable derivative columns migrate existing rows without changing source bytes or version snapshots. Existing assets generate a derivative on first demand. Authorization, source and derivative hashes precede even HEAD/304; only this exact successful image route opts into private,no-cache,must-revalidate, with Vary: Cookie. Unknown/duplicate parameters fail. Original file/version download semantics remain unchanged; retention includes derivatives and protects active response leases.
Only new upload normalization uses PNG compression3; formal rendering retains compression6 and all pixels, alpha and EXIF orientation are preserved. Animated inputs fail explicitly. On write/commit failure, cleanup rechecks database references before removing own files; uncertain/unreadable database state conservatively retains files. Host identity binding uses a read-only path for unchanged accounts, while current host role is checked on every request and changes are transactional.
Material image/ZIP reads pin selected references under the state lock, verify complete files outside it, then recheck selected references/status and file tokens before returning. Tokens do not replace full hashes. A task lease spans each operation, and HTTP leases still span response close. Per-task packing admission rejects concurrent duplicate packing without blocking all employees. ZIPs are private, exclusive, immutable files; the trusted in-memory cache binds task and effective download content. Old streaming ZIPs are never overwritten. A restart may rebuild one ZIP for a requested selection; ordinary unreferenced files remain within the task's50-hour cleanup. Packing failures clear admission and delete only the current operation's own unpublished candidate.
Material config reports retention_seconds and retention_hours from the common retention constant; legacy retention_days is the same duration divided by86400, not a separate policy. Frontend uploads remain serial and acknowledged individually, without automatic retry of unknown outcomes. UI previews/cache never change qualification, original files, quotas or permissions.
Layout teaching references are read-only host routes: authenticated GET /api/ribbon/layout-examples returns mode guides and reviewed examples; authenticated GET /api/ribbon/layout-examples/{code}/image?v={digest-prefix} returns only the registered preview bytes. The instance settings directory ribbon_layout_examples/ is private deployment data, absent from Git, public release archives, the production asset library and provider inputs. A missing/changed preview is unavailable, not substituted. Authentication and byte verification precede conditional304 and HEAD. These reads do not initialize the ribbon worker, create a work/version, or debit refinement quota. The UI maps by Template.mode, preserves selections, and explains which source artwork and arrangement each implemented mode requires. As of v1.21.0 the catalog covers all14 implemented modes with13 reviewed examples; no case-only label stands in for rendering support.
New deterministic modes are bordered, scene, fullwidth, alternating, ends_open, split, stacked, and opposed. Existing six modes retain their original pixel behavior. Generation, selection refinements and durable snapshots enforce: bordered/split/stacked need at least2 patterns; fullwidth exactly1; ends_open 1 or2; the remaining modes accept1–12. Non-repeated fullwidth/ends_open do not accept spacing edits as meaningful work: unchanged spacing is removed, an otherwise empty unchanged plan requests clarification and does not debit quota. Template initialization only appends missing defaults, retaining all historical rows and output profiles. Templates for the new modes do not expose unused rows; non-repeated modes also reject step_ratio. No provider protocol or production asset is added.
As of v1.22.0, Config and Version responses include runtime editing: allowed_operations, allowed_parameters, composite_edit, composite_edit_reason, planner_sees_images. Version.editing is outside the immutable snapshot and uses that version's saved dimensions with the current provider. Plans receive the current mode, limited rules and ordered selected asset names, not image bytes; they have at most8 operations. All operation/parameter/target and input-image qualifications are checked before the first paid image edit. No-net-change requests clarify without creating a version or debiting quota. First drafts and explicit selection-only changes do not instantiate a model provider. Background-jobs retains its prompt field, now supplied by the employee UI. Seedream backgrounds require native2048x2048; independent edits request a supported aspect-preserving approx4MP canvas and validate exact native dimensions/alpha. Unsupported full-strip editing is not flattened or sent to the image model; unknown outcomes are not retried. Existing profile, quota, ownership, retention and download checks remain authoritative.
The React/TypeScript ribbon island mounts at #ribbon in the existing page with ShadowRoot style isolation. FastAPI runs through the authenticated Flask/a2wsgi gateway at /api/ribbon/*, sharing one process and the existing provider pool. The host is the sole identity authority; browser-provided owner/role headers are ignored. All mutations require the host origin and page token; /api/ribbon/admin/* and /api/admin/ribbon-settings require server-side administrator authentication.
SQLite WAL, a persistent single worker, transactions and immutable image hashes protect quota, idempotency, parent versions and exact-version downloads. Only two successful refinements are allowed; failures do not debit and parent rollback does not refund. Same-browser reauthentication restores ownership. File responses hold leases through close; normal shutdown drains requests and already accepted provider work. Interrupted paid requests with unknown results are never automatically retried.
Provider selection and model revision bind each submitted job. OpenAI uses a separate encrypted Key and model IDs; DeepSeek/Seedream reuse current host settings and the same live Key pool. Saving configuration does not call or qualify a model. No employee endpoint reveals credentials and no production failure falls back to a test provider. New ribbon AI starts disabled; deterministic composition remains usable.
Personal ribbon works, versions and private assets use the shared RETENTION_SECONDS (50 hours). A successful generation, refinement or rollback renews retention. Busy tasks, streaming responses and live references block cleanup; shared library/templates/output profiles persist separately. Tombstones retain only owner, idempotency key and request hash to reject expired paid-request replay. This does not alter numbering or material qualification/export rules.
See ribbon integration for endpoint paths, upload decoding limits, provider constraints and the explicitly marked demonstration output profile. Real paid-provider image quality and production output specifications remain separate acceptance work.
Python package hsd_tool, Chinese end-user interface, v1.19.2. Flask/browser workflow with Windows desktop/LAN and a separately enabled Linux HTTPS cloud entry point. Default desktop binding remains loopback; LAN and cloud provide browser-owned employee upload, processing and result download on one host. Client originals remain unchanged. Original XLSX and ZIP files are uploaded to the configured service host, not OSS; numbering sends only its previously authorized safe previews to DeepSeek. The separately authorized v1.17.0 material workflow sends cleaned material pixels to DeepSeek for design localization, as specified below. With AI enabled and a usable Key, whole-library candidate retrieval and complete independent local verification run concurrently. Disabled/unconfigured AI retains the complete local path. Original XLSX, ZIP and AI files and local paths are never sent to DeepSeek. The browser never calls the provider directly. No AI production qualification is shipped or activated by deployment.
Localization validates candidates individually: bounded numeric coordinates are clamped to0..1000 and rounded; unusable, duplicate, nested or padding-only candidates are omitted with a visible count. No usable candidate still fails. The current edge-fragment filter supersedes the blanket v1.19.1 edge exclusion; complete edge-adjacent designs remain eligible. This is not a completeness or quality guarantee.
A material upload publishes a completed receipt only after the worker queue accepts the callback and the signed task manifest is saved. The callback checks that this exact run is authorized before starting work. A known rejection leaves the same upload ID retryable unless the owner cancelled it. A staging cleanup error does not replace a committed receipt. A known completed receipt with an unavailable job cannot be replayed as a new upload.
Single-item refinement preserves the original extraction outcome and source rows. The original item remains downloadable when refinement fails or stops. Refinement errors and unknown billing are attached to the affected item; they do not authorize a whole-source retry. Interrupted refinement is never automatically replayed.
Only a settled invalid_decision localization failure may receive one automatic DeepSeek retry. That retry uses the source view without the coordinate-ruler reference; it is not an extra Ark generation or a free call. Unknown submissions, authentication failures and rate limits do not gain this retry. An employee's failed-source 自动重试 uses the existing redo endpoint with source_id and no bounds, re-running cleanup, localization and extraction; an unknown submission still requires the existing acknowledgement path.
Refinement keeps the result list and other image comparisons visible while the current card shows its elapsed time. This frontend behavior does not override the existing server-enforced per-batch busy-state download guard: PNG/ZIP downloads remain unavailable while the batch is queued/processing/cancelling. No change to numbering, credentials, retention or task ownership is implied. See v1.19.2 verification.
The user explicitly removed material confirmation as a download prerequisite. New output status generated means unverified but downloadable; it never creates a human review record or AI quality qualification. Existing ready/confirmed/needs_review remain readable. Public item.downloadable is server-owned and excludes discarded/superseded items and busy batches. PNG/ZIP downloads still validate ownership, original source and full output hashes. Numbering acceptance/export rules are unchanged.
POST /api/material/jobs/<id>/refine accepts only {expected_revision,item_id,acknowledge_unknown?}. It submits one explicit MaterialDesignProvider.refine / Ark refine_design request on the current PNG, no cleanup/localization/automatic refinement/retry. The fixed HD prompt preserves identity, text/colors, composition, proportions and full boundaries without extra outline. Actual alpha selects transparent vs opaque mode; opaque input keeps its background. Attempt/usage/unknown/cancel bookkeeping remains complete, including restart and submission rejection.
Successful replacement commits a signed candidate before publishing, preserves current ordering/name/bounds and retains the immediately preceding PNG as private superseded history. Snapshots add refined, previous_image:{image_url,thumbnail_url,width,height}, refine_error and refine_submission_unknown. GET /item/<current_id>/before uses the existing material-image lease/cache boundary and validates owner, source, both complete versions and requested derivative before304. Generic superseded-item URLs remain forbidden. Failure/cancel/queue rejection keeps the prior current result downloadable, and an unknown submitted call needs explicit acknowledgement before another refinement.
Discard uses resolve skip, restoration uses restore to the prior status without confirmation. Batch ZIP includes all current downloadable, non-discarded results. Material confirmation controls are removed from the UI; legacy server confirmation APIs do not authorize a new quality claim. Source-scoped failure details remain in the expandable batch records, with has_generation_failures derived only from recorded failed/unknown extract_design calls; it is not a remaining-review count. Known routine technical notes collapse, specific exceptions remain visible, and the GPT suggestion is a manual workflow tip, not a new provider integration.
Verification and cloud delivery receipts: v1.19.0 verification. Earlier mandatory material confirmation and no-manual-refine descriptions below are historical where conflicting.
ArkLayer.bounds is always a dictionary of original-input pixel x/y/width/height, distinct from (left,top,right,bottom) internal geometry and model-reference hints. The real MaterialDesignProvider and MaterialManager integration must preserve bounds, native canvas/alpha, explicit review, ZIP records, existing-item edits and one-time source offsets for re-selection.
Targets below4% of source area use the existing enlarged local reference with30% context padding (minimum6 pixels), approximately2.4MP and at most4MP. magnified_reference returns encoded bytes, the original crop rectangle and final encoded dimensions. Target hints project into those final dimensions with outward rounding, including any byte-limit shrink. Over-long local views outside the adapter's1:16..16:1 range use the shared full reference instead, with no extra generation. Other targets share the full source reference (16MP/30MB maximum). All returned output pixels/canvas/alpha remain intact.
Worker limits use the largest planned per-target reference size as a conservative upper bound; byte-limit shrink can only reduce it. Raw source dimensions are not charged as sent-reference pixels for all-local batches. The32MP in-flight input budget and8-call cap remain; mixed sizes are deliberately conservative. No automatic refinement or retry is added, no model/qualification is changed, and all generated materials remain manual review.
Regression coverage uses synthetic external replies through the actual provider/service boundary, pixel-projected hints, high-resolution/mixed-reference concurrency, cancellation/unknown-usage controls and controllable asynchronous browser image callbacks. This does not prove real-model clarity, completeness, removal of all borders/watermarks or an end-to-end speedup. Versioned results and deployment receipts: v1.18.5 verification.
MaterialDesignProvider no longer calls refine_design during extraction, regardless of count, target area, opacity or perceived quality. One source schedules one whole-sheet Ark cleanup, one DeepSeek localization, and N native2K extract_design requests for N designs. The first extraction retains the existing high-definition, complete-design, alpha and no-added-outline instructions. No second generation or local upscale/crop is substituted. An explicit employee edit uses one edit/clean request; manual source re-selection is a new user-requested extraction.
Keep input bbox0..999, whole-context reference<=16MP/30MB, reference_workers<=8 and<=32MP concurrent reference pixels, returned RGBA/canvas preservation, manual qualification, thumbnails and all source/ownership/unknown-submission checks. Remove the obsolete15% production trigger. The Ark adapter may retain its internal refinement method for historical protocol tests, but no registered production workflow invokes it automatically.
Requests change from1+N+K to1+N for Ark, plus the unchanged single localization call. Native base/foreground billing remains actual upstream usage; no inferred50% price or elapsed-time guarantee. No paid image-effect comparison in this patch; user evaluates quality. The following v1.18.2 refinement paragraphs are historical where conflicting.
Input interactive bbox coordinates for clean/extract/edit are normalized0..999 (official interactive guide); returned bounding_box.normalized remains0..1000. Whole-context references retain up to16MP and30MB, encoded once; concurrency retains the8-call cap and32MP in-flight input budget. No automatic input/output crop is restored.
When there are multiple designs and one target's original box covers <15% of the source, a successful unique native foreground with actual transparent pixels receives one planned refine_design call: single alpha PNG, background=transparent, size=2K. Prompt requests a complete centered subject occupying about80% of its canvas, faithful colors/text, no added sticker border/outline/glow/shadow, retaining intentional internal lines and white content. Existing transparent-item edits use the same native transparent protocol once. This extra pass is not a retry or a quality proof. Failure affects that design, retains attempts/usage/unknown state and never falls back to the prior native result as refined success. Opaque native results skip refinement with warning. All outputs remain manually confirmed. Cancelled requests with unsettled submissions remain unknown, including child call records.
Sources/items add thumbnail_url; original image_url/download URLs retain full PNG semantics.640px proportional alpha PNG derivatives are generated once at receipt/output save, signed by thumbnail_sha256 in the private manifest. GET image routes accept variant=thumb|full and optional single v; duplicates/unknown values fail. Thumb requests verify owner, source, output and derivative digest before conditional304; content versions cannot cross task/session boundaries. Private,no-cache,must-revalidate is retained. Download/confirm checks use full original files. Cards preserve preview nodes across status mutations; nonvisual metadata does not rebuild content, source previews are deferred until expanded (errors auto-expand).
Performance numbers in verification are synthetic PNG/DOM measurements, not business quality or end-to-end speed. Flash/Pro are both officially limited to2K tiers, so Pro is not automatically enabled. No paid effect comparison in this release; user evaluates generated quality.
Production uses MaterialDesignProvider: whole-sheet cleanup, DeepSeek localization on cleaned pixels, then native Ark layer_decomposition per target. One full original-image reference is encoded once at proportional <=4,000,000 pixels and shared among at most eight calls. Expanded location bounds are textual hints only; they never crop this reference. Exactly one nonempty foreground (plus base) is accepted; multiple layers fail that item without choosing/merging layers or another paid fallback. Final output retains model canvas dimensions and RGBA pixels; no white removal, component deletion, trim, added frame or4096 resample. Editing remains one cleanup call with intact canvas. Provider counts, including base/foreground accounting and failures, are retained as returned.
Legacy rectangular_crops is the existing unqualified/manual service channel, not a claim that current outputs are rectangular crops. no_upscale marks the unchanged canvas path; quality evidence is material-preserved-canvas-1, scope unverified_generated_content. All outputs remain needs_review. Runtime task implementation signatures now include material_design.py; old-implementation tasks cannot recover after promotion.
Snapshots add progress.run_id, run_started_at, task_elapsed_seconds and optional designs_completed/designs_total. A new accepted batch or explicit redo starts a new run; stage/source transitions do not reset it. A separate run_finished_at freezes elapsed time independently of retention touches. Completed counts include failures, stay monotonic within one source and remain through saving, then clear for the next source. UI labels percentage as current-source design processing, not whole-batch/model-time completion; before counts exist only actual stages appear. Terminal streams/timers stop. Cancelled/interrupted runs freeze too.
No paid effect test was run for v1.18.1 at the user's request; release checks do not establish output quality. The following v1.17.x API/history sections remain historical where their processing descriptions conflict with this section.
The whole-canvas cleanup and selected-item edits request approximately2048×2048 pixels, proportional to the input aspect ratio (explicit WxH, ceiling-rounded, within the official921600..4624220 pixel interval). Small images no longer select the lowest canvas area based on input size. This is a native provider request, separate from downstream4096-long-edge resampling, and does not prove recovered detail.
The default cleanup prompt requests high-definition detail, removal of repeated/diagonal/translucent overlay marks on faces, skin, clothes, ornaments and backgrounds, cautious neighboring-texture repair, and preservation of designed text, signatures, colors and grouping. It stays under300characters before optional user instructions. There is still one cleanup per source, no automatic second semantic-cleanup pass or model-confidence approval. A returned canvas below90% of requested area is retained with a visible warning; it is not blindly billed again. Actual semantic fidelity, residual watermarks and transparency remain unqualified and human-confirmed.
The employee index switches numbering/material workspaces in the same document, preserving separate task state. Only the index document additionally permits blob: images for selected-file previews. Admin documents remain unchanged in that respect; authenticated material download responses allow same-origin frames only with frame=1. Admin functions link to the actual employee tools (/ and /#material); all provider configuration and employee-access-code management entries appear under Key ledger with their functional uses. Functions contains only the two employee tool entries. Ark configuration/reveal remains independently administrator protected.
GET /api/material/config returns availability, unavailable_reason when relevant, and the current browser's last task. Real extraction requires enabled/configured Ark plus an available enabled DeepSeek runtime; the legacy numbering gateway is not a material transport. POST /api/material/jobs streams multipart files (1–100 PNG/JPG/WebP), under the existing Origin/token/employee guard. X-HSD-Upload-ID reservations are committed before background submission, saved in signed jobs and rebuilt after same-implementation restart. GET /api/material/upload-status/<request_id> and POST .../cancel resolve lost replies without blind duplicate work. Another browser cannot use those claims.
GET /api/material/jobs/<material_id> returns public source/item snapshots, revision, update_seq, progress, can_undo_batch, counts and eligible download URLs. Busy states: queued/processing/cancelling; terminal ready/error/cancelled. Item states: needs_review/ready/confirmed/skipped/superseded. Current generated/cropped outputs remain needs_review; model boxes and pixel fidelity do not prove complete design grouping or production quality.
Material mutations are authenticated, owner scoped and server validated:
- POST
.../resolveaccepts exact{expected_revision,item_id,action:'confirm'|'skip'}. - POST
.../resolve-batchaccepts exact{expected_revision,item_ids:[string,...]}with distinct pending IDs. It verifies every source and result digest before an atomic write. Success records each selected result asconfirmedwithreview.method:'employee_batch', one group ID and timestamp, increments revision once, and retains warnings. No partial success, inferred automatic approval, skipped-item inclusion or frontend-only state change. - POST
.../undo-batchaccepts exact{expected_revision}. It restores the last batch's previous statuses/review only whilecan_undo_batch:true; intervening mutations invalidate that grouped undo and require individual correction. Sources/results and group identity are rechecked before changing any record. - POST
.../cancelaccepts exact{expected_revision}. Queued work stops; dispatched requests drain and retain usage before terminal cancellation. - POST
.../redoaccepts expected_revision/source_id, optional item_id/box/instruction, and requires explicitacknowledge_unknown:trueafter an unknown submission. Boxes use original source pixel coordinates. New selection crops that original region before processing; item editing maps the source-space box onto the verified current item. Clean-canvas design bounds map proportionally back to original coordinates; this is not independent proof that the model preserved geometry. Failed edits do not supersede the old result.
GET .../events uses existing employee authentication and ownership checks, returns text/event-stream, private/no-store, X-Accel-Buffering:no. event: snapshot contains the same full public snapshot as GET; it emits on changed update_seq. event: end contains {} at terminal state; event: unavailable asks the client to refresh when task access/state changes. The stream requests retry1500ms, sends comment heartbeats, and emits event: renew with {} before the normal connection lifetime ends (at most12seconds). Renewal is a healthy reconnect to recheck authentication and ownership, not a processing failure or a reason by itself to fall back to polling. Active streams are capped at2 in the single worker (excess receives429). Polling remains available; the client closes streams on hidden page/workspace, task changes, logout and terminal state, rejects stale task/sequence updates and falls back when streaming fails.
progress contains stage_code, human-readable phase/message, current, total, source_id, started_at, updated_at, elapsed_seconds, task_elapsed_seconds, indeterminate; queued snapshots can add queue_position. Stage codes are queued/preparing/cleanup/locating/cropping/saving/source_done/source_error/cancelling/cancelled/done/error. current/total counts completed source images in the current batch/redo, never the image model's internal percentage. Revision tracks accepted mutations/results while update_seq also advances for saved stage records. Provider requests are synchronous; SSE is a real application-stage feed, not model token/image-pixel streaming, and does not expose hidden reasoning, credentials or raw provider replies.
material_pipeline performs one whole-image material_ark.clean followed by material_locate.DeepSeekMaterialLocator.locate, then crops locally from those cleaned pixels. Ark uses fixed Beijing images endpoint, base64 input/output, no arbitrary URL retrieval. It asks Seedream to remove watermarks/noise/unrelated content while preserving layout, text, design colors and complete groups; it does not request layer decomposition. DeepSeek receives two reference images derived solely from the cleaned pixels: a proportional square-canvas view and a coordinate-grid copy of that same view, together with dimensions, the known content rectangle and the localization prompt. The second image is only a location aid. User explicitly authorized this material-image transfer on2026-10-23; it does not extend numbering's approved upload boundary to original XLSX/ZIP/AI documents, filenames, local paths or unrelated business data.
Localization protocol hsd-material-locate-3-square requires exact JSON {complete:bool,designs:[{label,box:[left,top,right,bottom],uncertain:bool,reason}]}. The clean image is resized proportionally, centered in a1000×1000 canvas with known added padding; the helper copy adds100-unit coordinate lines and axis labels. Coordinates are integer0..1000 pixels in that square canvas, not separately normalized against the original width and height. The server intersects boxes only with the known content rectangle, rejects padding-only boxes, then maps left/top with floor and right/bottom with ceil back to the unmarked, original-resolution cleaned pixels. Reference padding, rulers and grid pixels never enter crop outputs. Structure, bounds, nonempty boxes, duplicates/nested boxes and aggregate pixel resources are validated, including after mapping; overlapping rectangles retain uncertainty warnings. Current limit128 designs is resource protection, not a target count, fixed ground truth or complete-coverage proof. A false complete, the boundary count or uncertain/overlapping boxes preserve warnings; the model's assertion of completeness does not grant approval. Every model crop also explicitly warns that estimated bounds may cut off a design or include an adjacent design, with manual re-selection available; the coordinate aid is not proof of correct grouping or complete bounds. The old16-layer adapter remains legacy and is not selected by the production pipeline. Item editing cleans the selected existing item and need not run localization again.
The cleanup prompt explicitly requests a real PNG alpha background outside designs, preserves internal design boards, and rejects white/checkerboard substitutes in its instruction. This request does not prove the provider complied: alpha is retained when supplied and opaque results remain visibly warned.
Outputs are rectangular PNG crops and may retain an opaque background; no transparent-cutout promise. Long edge4096 is proportional resampling with native dimensions retained, not a detail-recovery claim. Source/item previews and individual/ZIP downloads validate employee ownership, signed manifest and file digests. Unconfirmed/skipped items cannot be downloaded as completed. ZIP includes eligible PNGs and a warning/source mapping with unhandled, failed and unprocessed counts.
Each stage records its own attempts, actual known usage/request ID and settlement state. Only a definite rejected request may safely retry once within that stage; a locator failure must not repeat already paid cleanup. Unknown transport/incomplete/5xx submissions do not automatically repeat. Cancellation waits for sent synchronous requests to settle/timeout, retaining known usage and unknown-settlement warnings; no upstream cancellation or zero unknown cost is fabricated. All paid failed attempts remain private records, never release assets.
Material tasks have their own signed private namespace, source/output digests and implementation binding including pipeline/localization modules. Same cloud recovery owner can reopen same-version tasks, never automatically resubmit interrupted work. Cloud-only three-day expiry uses independent signed ownership and active leases; normal shutdown drains accepted material work and preserves settings/other projects. Ordinary material settings return processing_available; validation_ready:false separately means no independent business-quality qualification. Actual tests, sample results and deployment status belong in v1.17.0 verification, with no implied success before receipts exist. Historical v1.16.0 layer behavior and evidence remain in its verification record.
The user cancelled fal on 2026-10-22. /admin/material configures Volcengine Ark using an API Key and image Model ID or inference endpoint ID. Both page/static sources and GET/POST /api/admin/material-settings require independent admin authentication in every mode. Ordinary settings responses are no-store and never include credential values/suffixes. GET returns {settings:{provider:'volcengine_ark',model_id,enabled,configured,key_persistence,revision,warning},deepseek:{enabled,configured},validation_ready:false}. configured means a saved Key, not verified access; enabling additionally requires a model ID. Only doubao-seedream-*, doubao-seededit-* or ep-* IDs with safe ASCII syntax and length at most128 are accepted; no custom URL is supported. Model compatibility/availability still requires real testing.
Every POST requires exact Origin, CSRF, provider:'volcengine_ark' and non-negative integer expected_revision. Strict actions: set_config with api_key and model_id; set_enabled with enabled; remove_key with no extra fields. Blank Key preserves the existing credential. Removal clears both Key/model and disables. Revision conflicts return409; old fal pages without a provider or using set_key fail400. Saving never sends images or makes provider calls, including when the validation switch is enabled.
MaterialSettings encrypts material_volcengine_settings.json with its own Ark domain prefix via Windows DPAPI or explicit Linux AES-256-GCM. It never reads/migrates/edits old material_settings.json, falls back to environment secrets or shares DeepSeek keys. Private atomic writes publish runtime only after durable save. This configuration interface itself does not execute images or grant qualification. Material execution is specified above; existing matching/numbering/export and private-data exclusions remain. The old unregistered fal adapter is historical only and cannot consume new settings; Ark/localization changes still need real-interface and business verification.
Official field reference checked2026-10-22: Ark image API. Beijing image endpoint is fixed at https://ark.cn-beijing.volces.com/api/v3/images/generations; no request is performed by the settings feature.
User explicitly authorized administrator viewing/copying the saved Ark Key on2026-10-22. GET /api/admin/material-key?revision=<integer> is the sole Ark plaintext exception; independent administrator authentication, constant-time page-token check, valid optional same Origin, and exactly one revision argument are required. Missing/invalid token or foreign Origin returns403, unauthenticated/employee returns401, invalid revision400, changed configuration409, missing Key400. A matching read returns only {provider:'volcengine_ark',revision,api_key} with no-store, no CORS and no logging. It does not change encryption, files, revision, enabled state or business qualification, and never calls a provider. Normal snapshots, HTML and employee endpoints must remain secret-free.
The page's native details is initially closed, with a masked placeholder. Opening alone makes no Key request. Explicit show/copy performs a fresh revision-bound read; copying uses the browser clipboard API and only acknowledges after it succeeds. Plaintext is never stored in attributes, inputs, Web Storage or IndexedDB. Hiding/closing, refreshing, any save, authentication loss or pagehide removes displayed plaintext; a generation and panel epoch suppress obsolete or BFCache replies. Clipboard contents from an explicit successful user copy are not subsequently overwritten by the app. Unsupported/failed copying offers manual reveal as fallback. The DeepSeek ledger remains separate.
GET /material-demo/ and /material-demo/index.html serve the existing prototype with static html[data-hosted="true"]; /material-demo redirects to the slash path only after employee authentication. Unauthenticated GET entry links return the existing access-code form at the same URL. All CSS, JS and seven authored SVG files require the existing employee session, network and Host boundary. An administrator session alone is not an employee login. material_demo.FILES is a closed ten-file allowlist; README, traversal, symlinks/junctions and arbitrary project assets are refused. No Demo mutation/API route exists. Responses remain private/no-store, DENY-framed and nosniff.
Only actual Demo responses receive the narrower material_demo.CSP: scripts are same-origin, images allow same-origin/data/blob for browser-local previews, and connect-src 'none' forbids interface requests. The existing login and numbering policies stay unchanged. The hosted UI links to real / and /admin destinations; standalone port8870 retains illustrative views. Browser file selection is preview-only and never uploaded. Steps are explicitly manual examples; PNG/ZIP contain original synthetic artwork, not transformed user images. Edits save only an in-memory demonstration plan. The Demo never reads credentials, settings, production jobs or provider clients. It is not evidence of real extraction quality or AI acceptance qualification.
The authenticated admin page consolidates usage instructions and troubleshooting in a native, initially closed details#admin-help. Opening or closing it makes no request and does not open/read the Key ledger. Keyboard activation is supported without new JavaScript listeners; refresh starts closed. Plain-language current qualification/storage messages keep their existing server-supplied meaning. This presentation change adds no endpoint, permission, provider call, business qualification or matching/export decision.
v1.17.0 places the access-code configuration link under Key ledger, not Functions; its permissions and API remain unchanged. v1.15.0 integrates /admin/access-codes and authenticated GET/POST /api/admin/access-codes. The page and its HTML/JS/CSS require the existing independent administrator session in desktop, LAN and cloud modes. POST also requires exact Origin, the existing write token and a non-negative integer expected_revision; stale revisions return409. No response contains a code, suffix, digest or salt. All responses remain no-store. Desktop GET returns supported:false and writes are rejected because no employee entry is enabled.
Supported snapshots are {supported:true,revision,min_length,max_length:64,codes:[{id,label,enabled,source:configured|saved}]}. POST accepts only expected_revision and optional arrays add:[{code,label?}], update:[{id,enabled:bool}], remove:[id]. Up to100 additional entries are retained. Codes are exact, untrimmed visible ASCII33–126, no spaces, and must satisfy the instance minimum: LAN1; cloud16 unless the existing explicit deployment override says otherwise. Labels are optional, printable, at most40 characters, and cannot contain the added code. Duplicate codes, including disabled entries and the configured original, reject the entire write. The original configured code is readonly through this API.
New codes persist only as PBKDF2-SHA256 digests with a random32-byte salt private to the registry,600,000 iterations; one derivation per login is compared against every entry with fixed-length constant-time comparisons. The registry lives under the shared settings directory in private employee_access/access_codes.json, outside all task-retention namespaces. Linux uses descriptor-pinned no-follow directory I/O, service ownership,0700/0600 and atomic replacement. Windows rejects links/reparse points without overwriting shared directory permissions. The original bootstrap code remains supplied by the existing runtime/private file and is not copied into the registry. Registry corruption, unsafe paths, runtime deletion, salt changes or revision rollback fail closed; no original-code fallback. Saving with an uncertain post-replace error requires refreshing to check the durable result. Multiple instances in one worker share a path lock; the existing single-worker deployment restriction remains.
Every code is checked inside the existing per-address login failure budget. Codes grant employee admission only: they do not derive employee IDs, grant administrator or host privileges, change upload ownership, or bypass recovery-cookie validation. Disabling/removing a code prevents new logins but does not revoke already authenticated eight-hour sessions. In cloud mode the original browser may reauthenticate with another valid code and recover only its own same-version, unexpired tasks. The registry survives task cleanup; no code/hash/salt/temp file belongs in Git or release attachments. This branch does not alter provider calls, matching/numbering/export gates, or deploy the feature to the public site; a later code upgrade still invalidates old task recovery, so finish and download first.
- Employee uploads use
X-HSD-Upload-ID(UUID) bound to the authenticated owner.GET /api/jobs/upload-status/<request_id>returns{state:missing|pending|completed|cancelled,job_id?,cancellation_requested?}.POST .../cancelinstalls a cancellation tombstone before late multipart commit. Repeated completed IDs return the original job; both LAN/cloud commit claims inbefore_submit, never after background submission. Unknown claims cannot disclose another owner's job. POST /api/jobs/<id>/canceltakes{expected_revision:int}and returns the public job.cancellingis BUSY withcancel_requested:true;cancelledis terminal, cannot export. Cancellation is cooperative at file/chunk/pair/row boundaries; queued parent and CPU child futures are cancelled, running provider requests drain and account real usage before termination. It cannot roll back charges or interrupt one native CV call mid-call. A late result cannot restore ready/done after a successful cancellation request.task_has_work(id)counts the job's operations and tracked parent futures (parents drain their own CPU/AI children). Expiry reserves an_expiring_tasksmarker under the manager lock, scans outside that lock, then rechecks task identity/state/revision/token, work and response leases before removing metadata. Other jobs no longer block unrelated expiry. Uncertain files/links remain preserved.- CloudTaskStore explicitly allowlists job metadata in private HMAC-signed checkpoints. A separate Secure/HttpOnly/SameSite browser recovery cookie (30 days) derives a stable owner; employee authentication is still mandatory. Recovery is restricted to the original browser, the current exact Python implementation/version and the unexpired three-day task record. It does not extend retention or submit CPU/AI work. Interrupted busy states become error; ready/done must revalidate sources, all comparison bindings and workbook snapshot; done also checks private export records and download SHA. Cookie loss, browser change, source/signature changes, expiry or code upgrades do not recover usable old work. Sessions remain process-local and expire normally. LAN/desktop recovery behavior is unchanged.
- PreparedMatching uses task-private, non-pickle NPZ appearances and a process-wide 256 MiB measured LRU for exactly preserved pixels/features. Random task namespaces prevent sharing by user-controlled IDs. The existing 64 MiB texture scratch is separate. AI retrieval bounds aggregate encoded preview preparation to 128 MiB per batch; exceeding this budget sends no partial library, records resource_limit and retains full independent local validation. Encoded image input is hashed by streaming rather than loaded as an unbounded byte string. These budgets are not process RSS ceilings, capacity promises or speed benchmarks. Cache disk failures abort preparation rather than silently eliminating a competitor. Comparison bindings include backing caches and all excluded competitors and are rechecked before/after export along with the snapshot.
GET /api/jobs/<id>/download-statusvalidates the final download and returns{ready:true,download_url}.download?frame=1permits SAMEORIGIN/frame-ancestors self only for the existing owner-checked endpoint, so a streaming ZIP or error stays in a same-origin hidden iframe. All other frame protections remain DENY/none. The main page reads failures and retains context; it never buffers an entire ZIP as a Blob or claims successful disk persistence.- Administrator ledger is fetched only when opened and cleared on close, auth failure, logout and page leave. 401/403 lock controls and stop polling; late responses cannot restore plaintext. Logout success requires an acknowledged server response. No cost/debug dashboard is restored.
Since v1.12.1, HSD_EMPLOYEE_CODE_MIN_LENGTH is an explicit per-instance override (integer 1–64, default 16). CloudAccess(..., min_code_length=16) retains the same default. Invalid values fail closed. The administrator-selected code still must be 1–64 visible ASCII characters; throttling, employee ownership and host-operation restrictions do not change. This setting never contains the code itself.
python -m hsd_tool.cloud_server is the explicit Linux entry point. create_cloud_app() requires HSD_PUBLIC_ORIGIN, HSD_DATA_DIR, HSD_SETTINGS_DIR, HSD_EMPLOYEE_CODE_FILE, HSD_CREDENTIAL_KEY_FILE and HSD_ADMIN_CREDENTIAL_FILE; environment values identify paths/origins and a non-sensitive optional length setting, never plaintext secrets. HSD_BIND_PORT selects the loopback backend port (default 8830). Public origin must be an exact HTTPS origin without credentials, path, query or fragment. The confirmed deployment target is https://39.106.45.116:8443, while the existing site's 80/443, application and database are retained. Configuration/implementation is not evidence of actual availability; actual results belong in the cloud deployment record.
CloudAccess reuses employee login/session and owner validation but is_host() always returns false, even for loopback. CloudProxyBoundary accepts only real loopback socket peers, exact configured Host, X-Forwarded-Proto:https and one valid X-Forwarded-For address. The configured local proxy must overwrite these fields; arbitrary forwarded chains/host/prefix/real-IP headers cannot grant rights. Gunicorn's own forwarded-header trust is disabled. Missing/mismatching transport metadata fails 403 before Flask. Native pick, local-path job creation, output-directory opening, process shutdown and legacy host settings are forbidden in cloud mode. /api/config continues exposing upload-only employee access without private host paths/code. Mutations require the exact Origin and existing write token, with the original login exceptions.
Cloud cookies use random per-process names, Secure, HttpOnly and SameSite=Strict; sessions expire after eight hours and process restart invalidates them. Employee login does not authorize administration; cloud administration requires a service-private PBKDF2 account file and has no desktop/default-password fallback. CloudAdminCredentials validates the file's owner, mode, ordinary-file/no-link identity and record schema; the deployment provides a salted password hash, not plaintext. Admin APIs remain 401 until authenticated, including the explicitly authorized no-store Key ledger exception. A valid administrator does not own another browser's jobs. A separate IP port is a separate browser origin, but cookies are not port-scoped: this confirmed no-domain deployment must not be described as complete Cookie isolation from the old IP website. A future independent hostname should use host-only cookies.
Linux Key persistence must report key_persistence:'linux_aesgcm' or cloud startup fails closed. LinuxCredentialStore uses AES-256-GCM with random nonces and authenticated versioned ciphertext. A deployment-created 32-byte private key identified by HSD_CREDENTIAL_KEY_FILE resides outside the settings directory. Private directories/files belong to the service user with modes 0700/0600; no symlinks, hardlinks, foreign files or silent plaintext/session fallback are accepted. Provider Key values remain only in encrypted settings, process memory and the explicitly authenticated DeepSeek-ledger/Ark-reveal exceptions. Atomic writes are fsynced and replacement of the master key during a process is rejected. Windows continues DPAPI CurrentUser; existing DPAPI ciphertext is not a Linux migration format. A fresh cloud host ships no business automatic-acceptance qualification.
The server uses Gunicorn 26.2.0, one worker/four HTTP threads, loopback bind, no preload, request-count recycle, reload or shared control socket. Worker-increase and reload signals cannot create a second process-local task/owner map. No upload-body byte limit or whole-body spool is added; Nginx uses client_max_body_size 0, request/response buffering off and private service-volume body temporary storage. Idle network timeouts are not an overall batch-duration guarantee. Normal TERM rejects new mutations, drains accepted HTTP/body/stream work, stops retention, drains accepted CPU/AI/export handoffs, saves final retention state via close(on_drained=...), then clears memory. The custom master waits without Gunicorn's default force-kill deadline; systemd must preserve this with TERM, unlimited graceful stop and no automatic SIGKILL. Abrupt process/OOM/machine failure is not a guaranteed recoverable close.
JobManager.create(..., before_submit=callback) is an internal Python hook, never a form/JSON callback. It registers the job dictionary before calling callback(job) and submits no background work until that callback succeeds. Cloud upload sets managed upload metadata and persists retention in this hook; failure removes the task/map lock and only its marked work directory. The multipart receiver then discards its uncommitted upload. This prevents CPU/AI charges and inaccessible tasks after a failed expiry registration. JobManager(..., preserve_cache=True) is cloud-only wiring that suppresses unconditional startup/close cache deletion; the default Windows/LAN behavior is unchanged. close(on_drained=callback) invokes the optional callback outside the global lock after every accepted executor/operation drains but before clearing jobs.
CloudRetention(manager, job_leases, retention_seconds=259200, interval_seconds=60) exposes start()->self, stop(), register(id) and sweep(now=None,delete=True). Only committed managed upload UUIDs may register. HMAC-signed private manifests bind job/batch IDs, state, revision, operation token and clocks; paths are derived from fixed namespaces, never supplied by a manifest. A task entering ready/done/error starts a three-day window; observed successful edits or phase/token changes refresh it. Busy/queued jobs, request leases, accepted operations or unfinished futures defer deletion. Signed but orphaned busy tasks after restart receive a fresh conservative window; v1.13.0 may expose their signed checkpoint as an error to the same reauthenticated browser, never resume processing. Invalid signature/time/schema, changed ownership markers, paths, symlinks or unknown directories preserve data and report a generic warning.
All cloud job-scoped requests acquire an owner-checked lease under the same manager lock before asset lookup/hash/read and hold it until the WSGI response iterator closes, including image GET/HEAD/304, errors and interrupted downloads. Leases release idempotently. Eligible cleanup validates the entire plan, removes the in-memory task under lock and deletes outside the global UI lock: uploads/<batch>, employee_outputs/<batch>, jobs/<job> and task_records/<job>. An interrupted cleanup retains its signed manifest for restart/retry. Download close is not proof that the employee saved a file and never triggers immediate deletion. Key/settings, cumulative usage and another service's files are excluded. Local/LAN task_records retain their existing normal-close persistence. No cleanup runs while the service is stopped; unknown/uncommitted directories without valid signed registration are not swept indiscriminately.
For cloud requests, the dedicated proxy buffers ordinary request bodies and caps them at 64 KiB. Numbering ZIP and material uploads retain streaming without a fixed byte cap, and ribbon assets retain their separate multipart cap. Protected mutations validate identity and the write token before parsing JSON. Two nonblocking application slots cover cloud uploads, archive/file downloads and full image responses, numbering download verification and material event streams. Busy transfers return 429 with Retry-After; regular status, login and cancellation use the other request capacity. Streaming keeps its slot until the response iterator closes. Uploads on the same volume share checked free space and in-flight writes. Cloud uploads leave 256 MiB of intake headroom at their checks; unrelated disk writers remain subject to the normal disk-full handling.
The confirmed deployment isolation profile is a dedicated non-root service user, code/venv/settings, separate Nginx site and preallocated ext4 loop data volume (15 GiB since 2026-10-29, grown online from 12 GiB); mount failure must prevent fallback to the old website's root filesystem. CPU quota is one core and memory maximum is 2 GiB, with private temporary data on the service volume. These are resource ceilings, not throughput/maximum-batch promises. Disk-full/low-memory cases can fail this service while maintaining original-file and export checks; no OSS or fixed individual upload byte cap is introduced. Actual TLS, volume, resource, original-site health and HTTP shutdown validation belong in the deployment record, not inferred from templates.
Historical v1.8.0 validation: 786 Python tests, four Node checks, production-script syntax and compileall passed; actual Windows portable acceptance covers host admin/DPAPI, independent employee sessions, >2 GiB upload/ZIP64, original-byte/WPS preservation, real 60-row regression and persistent private records after normal shutdown. Production inputs (32) and runtime files (1215) are bound by SHA256. That release went live on port 8818 with the saved Key unchanged, still evaluation-only; no real provider calls or second physical-PC validation were claimed. Exact measurements, failed experiments, browser automation timeout and scope are recorded in docs/performance-v1.8.0-verification.md. Current v1.9.0 execution and delivery evidence belongs in docs/ai-first-v1.9.0-verification.md; historical measurements do not establish this release's throughput.
inspect_workbook(path: str, work_dir: str, sheet_name: str | None = None) -> dict
Return {sheets:[{name,hidden}], sheet_name, rows:[{id, row_number, number, image_path, issue}], reserved_numbers:[str]}. Row IDs are r<Excel row>. Absolute image paths are extracted to work_dir and omitted from public snapshots. Read the first visible sheet by default. Image-bearing rows only; include unreadable image references with issue. Read column A number, B picture for current fixed template; preserve displayed leading zeros. reserved_numbers includes existing numbers in column A, including rows without pictures. Ignore huge empty/formatted trailing regions. WPS DISPIMG/cellimages required. Any supported floating drawing must associate an anchor to column B explicitly. Never include hidden sheets by default.
write_numbered_workbook(source: str, destination: str, sheet_name: str, assignments: dict[int,str]) -> None
Update only blank column A cells at assigned row numbers. Preserve every other XLSX part and all WPS images/drawings. Refuse replacement of any nonempty source number. Use ZIP/XML surgical updates (ordinary spreadsheet roundtrip destroys WPS-specific image features). Destination must differ from source and must not preexist. No sample workbook changes.
scan_and_match(source_path: str, rows: list[dict], work_dir: str, progress=None, *, texture_workers:int=2) -> dict
Input AI folder (recursive) or zip. Must reject traversal/symlinks, check actual disk availability and structural/file-count/decoded-pixel limits; no fixed file-byte, expanded-byte or compression-ratio cap, decode legacy Chinese zip names, preserve originals. Render PDF-compatible AI previews locally (first page; multi-page files must be flagged for review instead of auto acceptance). Source extraction under work_dir only. Return {files:[{id,name,relative_path,source_path,preview_path,issue}], matches:[{row_id,status,file_id,candidates:[{file_id,score}],reason,evidence}], warnings:[str]}. evidence carries every signal behind the decision: method, colour distance, candidate gap, pixel RMS, changed / major-changed share, worst region, unexplained-content residual, inliers, coverage, MAE and thresholds. These are diagnostic data; the employee screen defaults to the business reason, with detail collapsed. Status is auto, review, or unmatched. IDs are deterministic f0001 etc. Score is 0..1 similarity, never probability. Fail closed for near duplicates / reused file candidates; do not force a global assignment merely to obtain one-to-one matches. progress(message: str, current: int, total: int) is optional. All preview images remain under work_dir. Individual bad AI files are reported without aborting every readable file. Source AI bytes must remain unchanged.
v1.3.0 adds independently checked interpolation-edge pixels, detailed scale/phase measurement, measured repeated-pattern periods and complete candidate-content verification. matching_verification.py owns coverage proofs. Do not wrap an artboard as a presumed motif period: a period must be observed and validated across the query, then reproduce the complete candidate. Colour and coherent local differences remain blocking evidence. The historical v1.2.0 regression baseline is 44 local auto / 16 review; the unrelated unpublished 47 / 13 draft is not merged.
evidence_version:2 retains separate channels.features and channels.texture, each with score/strong/auto_ok, metrics, failed_checks and alignment. selected_channel identifies the actual decision path; AI may not cherry-pick metrics across channels. Alignment describes candidate-to-query geometry, dimensions, measured matrices, query/source/ink coverage and independently checked edges. competition binds every evaluated file and score, credible rivals and completion status. A weak shared fragment does not claim ownership from a complete validated match; actual supported competing claims still require review. IDs only identify files; names/order/reference answers never prove identity.
v1.8.0 uses one bounded _TextureCache per matching call. Keys bind prepared pixel SHA256, dimensions, transformation/resize parameters and a scratch implementation version. Reusable values include resized arrays, content bounds/histograms and the already-computed coarse result needed by precision verification. Eviction or a cache miss recomputes work; it does not reject an input or impose an upload-size limit. This is not a persistent/cross-task answer cache and does not reuse AI opinions. Source hashes and all later original/export integrity checks remain mandatory. Never substitute filename, path, length or mtime for content identity.
Pixel arithmetic retains the same float32 subtraction, absolute error and normalization while avoiding redundant RGB conversions/intermediate frames. Phase selection computes only its actual RMS criterion; full metrics are still evaluated for selected verification. A later expensive percentile may be skipped only when unchanged preceding limits have already rejected the candidate. Colour, coherent local differences, full content/ink coverage, competition and automatic-acceptance thresholds remain authoritative. Optional texture workers are limited to 1 or 2, preserve candidate order and never render PyMuPDF or mutate geometry RNG/ownership from concurrent threads; no running job changes OpenCV's process-wide thread setting. Default/selected performance policy and actual equivalence results belong in the versioned performance report.
prepare_matching(source_path, rows, work_dir, progress=None) -> PreparedMatching safely extracts, renders and decodes once without comparing pairs. Its task-local rows are deep-copied; appearances are read-only and bind decoded pixels to actual encoded-image bytes. file_bindings includes every prepared query/preview plus source AI SHA256. match_prepared(prepared, progress=None, *, proposals=None, texture_workers=2, verify_sources=True) checks all bound files before and after matching. The immediate legacy scan_and_match wrapper skips only this additional delayed-source pass, retaining render-time protections. Objects are private to one task, never public JSON or shared across employee jobs.
When AiSettings.runtime() privately declares matching_workflow:'ai_first', enabled AI with a usable Key chooses the new path automatically. This is not an employee-supplied switch or a qualification override. Preparation first creates the shared immutable inputs. The AI coordinator starts one local CPU child future while retrieving candidates; production local verification receives the complete prepared library and no model proposals. The model neither narrows that comparison nor supplies positive local matching evidence. Both results join under the original job identity, operation token and revision; only the independently computed local result controls row status, ownership and numbering.
ai_first.py uses protocol hsd-ai-first-retrieval-1. Each request includes all eligible readable single-artboard candidates; only query groups may be split. It keeps full overviews and ordered exhaustive wide-strip panels, randomizes anonymous query/candidate IDs and independently shuffles both lists. Filenames, row numbers, original documents, paths, local verdicts and reference maps are absent from prompt text. Image text is untrusted data. Duplicate complete candidate previews, corrupt/unreadable previews and multiple artboards cannot be resolved by asking the model to choose. Oversized full libraries fail explicitly rather than silently omitting rivals; local verification continues where valid.
The strict wire response is {matches:[{query_id,candidate_id:null|string,verdict:'same'|'uncertain',reason}]} with every query present exactly once and no unknown IDs. Missing/duplicate identities, malformed or contradictory structure fail. Returned collisions are preserved; there is no forced one-to-one allocation or elimination. Retrieval's same is always a suggestion, never qualification or acceptance. Source/preview hashes, actual implementation and current-run identity are rechecked; paid stale/failed replies remain recorded but cannot change the current plan. Local CPU failure or any source/image change blocks publication/export even if the provider returned same.
The parent remains busy through the join. Its CPU child does not replace the parent's token, revision or AI queue identity. Resource queue counting includes a queued/running CPU child. During overlap progress.phase:'parallel_verification' has zero total and displays AI-group and local-image counts separately; no summed percentage is meaningful. When only one stage remains, ai_retrieval or local_verification reports that stage's actual counts. Every exit path drains accepted child work before completing the parent future; normal close waits for accepted futures/operations before shutting down executors. After both paths finish, the coordinator rechecks original workbook/snapshot/archive and all prepared source/image bindings, then commits one final effective plan. AI errors preserve their usage and valid local results, never invent successful matching.
job.matching_mode = 'ai_first' | 'local'
job.ai_retrieval = {status,message,usage?,proposed?,error_code?}
row.ai_retrieval = {candidate_id:null|string,verdict:'same'|'uncertain',reason,
outcome:'suggestion'|'error'|'skipped',reason_code?,model?}
progress.phase = 'parallel_verification' | 'ai_retrieval' | 'local_verification'
The employee UI calls retrieval a suggestion requiring confirmation on unresolved rows. A local auto row may say local verification passed; model same alone never changes that state. A retrieval suggestion differing from the currently selected/local candidate stays visible. Short reasons are shown once, longer explanations expand separately from old row.ai_review; no pair-check booleans or qualification are invented from retrieval. Accepted batches go straight to the existing summary; automatic items have no mandatory viewing step.
queue_seconds accumulates waits in separate resource queues; parallel waits can overlap, so it is not the elapsed union of all waiting. Do not sum it or overlapping phase times into batch wall time.
The original optional /ai-review route remains available after readiness for eligible remaining questions, under its existing pair protocol and independent business-qualification gates. Initialize its independent summary so server-computed can_retry remains visible. job.ai_retrieval.usage and job.ai_review.usage are distinct; each actual attempt reaches the cumulative ledger exactly once. Unknown usage stays unknown and USD remains an estimate. Existing multi-Key retry budgets, global 429 cooldown and absence of a monetary cap remain unchanged.
Full retrieval plans, anonymous input/implementation bindings, every attempted/uncalled group, failure, collision and sanitized response are checkpointed under private task_records/<job>/ai_first_runs/; they also remain in private export evidence. They are not browser download members or qualification artifacts. No request bodies/images/credentials are retained in public debug or Git/releases. Current business qualification binds eleven modules, including ai_first; no existing ten-module qualification silently survives. Real API regression and synthetic controls do not constitute new independent business accuracy or qualification; the reserved 10.12 batch is not used. Current evidence and limitations: v1.9.0 verification.
Desktop Flask defaults to loopback. Explicit --lan <private-IPv4>/<prefix> --lan-input-root <dir> --lan-output-root <dir> [--port <port>] binds only the specified RFC1918 interface and admits only the supplied CIDR. The legacy input root must exist; the legacy output root is created if needed and must be outside it. These roots constrain host-only path compatibility requests; employee uploads use managed directories under data_dir instead. LAN paths reject escapes through symlinks/junctions and UNC/network-share paths. This desktop/LAN entry is not a public-hosting shortcut; public deployment uses the separate HTTPS cloud boundary above, never a proxy that turns outside visitors into host users.
Remote employee clients first use POST /api/lan/login {code} with a matching Origin. The access code may be supplied at launch; its effective value is local instance.json data, never a remote public snapshot, log or release member. Host-side config may display it. Employee sessions expire after 8 hours without sliding renewal; excessive login attempts return429. POST /api/lan/logout {} requires the usual CSRF header. Local pages enter directly. Administrator login is independent and does not require this employee code.
Each LAN browser session receives a random employee_id stored in the signed session cookie. Every job-scoped route checks _owner_id against that session, including reads, images, resolve, undo, AI retry, export, download and host output-opening. A mismatched owner receives 404, even from the host browser. Login creates a new identity; there are no employee accounts, cross-browser recovery or reassignment APIs. All users share backend capacity and the host's AI settings, not a current batch. Different tabs in the same browser session share ownership and use revision checks to avoid stale changes.
--data-dir isolates employee uploads/tasks/results. --settings-dir <existing-host-data-dir> supplies the shared DPAPI-encrypted Key, AI settings, usage ledger and qualification registry without copying credentials; the same Windows user must run it. Ordinary employees never configure or obtain the Key, and their cumulative-usage endpoint is forbidden. Authenticated administrators, including LAN administrators, have the explicitly authorized ledger exception described below. Per-batch usage remains in their own summaries. Tasks remain process-local; logout/relogin, cookie removal or switching browsers loses the old task access identity, and process shutdown loses tasks. Do not advertise persistent employee task recovery.
Browser gets X-HSD-Token from window.HSD_TOKEN populated in index.html template placeholder __HSD_TOKEN__ using a JSON literal. All POST requests, including multipart upload, use this header except employee access-code login and administrator login. Remote session authentication and request token/origin validation both apply. Standard failures are {error: Chinese string}, HTTP 400/401/403/404/409/413/429 etc. JSON is not cached. Never return keys outside the authenticated administrator ledger exception; never return raw provider request bodies or private process settings. LAN public job snapshots redact managed host paths.
v1.26.3 cloud sessions use a stable, domain-separated signer derived from the existing validated private machine key, exact origin/storage context and primary credential generation. The encryption key itself is never reused as the signing key or returned. Invalid key access aborts startup. Employee authentication has an explicit absolute eight-hour deadline; administrator re-signing cannot extend it. The initial migration from random process-local cookies requires one login; credential/key/context replacement invalidates old signatures. Desktop/LAN signing stays process-local.
GET /api/ribbon/session is a host-authenticated, same-origin, no-store read returning {token} for the current page-write token; it neither starts the ribbon worker nor changes identity, expiry, job or quota. A host write-token rejection is HTTP403 with code: page_token_expired, before the mutation is accepted. The ribbon client may refresh this token and resend the exact body/idempotency key once. Other403,401,unknown responses, network failures, upstream errors and accepted jobs do not enter this retry path. True401 still locks operations. Temporary /auth/me read failures preserve the existing workspace and offer reconnect; cancelled/obsolete reads cannot replace current identity.
GET /api/config->{prefix:'HSD', digits:4, last_start:1, last_workbook:'', last_source:'', last_output:'', version:'1.13.0'}. LAN/cloud mode adds{access:{lan:true,remote:bool,upload:true,upload_limits:{workbook_bytes:null,source_bytes:null,total_bytes:null}}, active_job_id:str|null}; only desktop/LAN host-sideaccessalso containscode. Cloud always reportsremote:true. Historical paths are blank.active_job_idand last start number refer only to the current browser owner's newest job, never another employee.POST /api/pick{kind:'workbook'|'zip'|'folder'|'output'}->{path: str}(native host dialog; forbidden for remote clients)POST /api/jobs{workbook_path,source_path,output_root,start_number:int}->{id}; local path workflow unchanged. In LAN mode, host-only compatibility API validates legacy roots and assigns the browser owner; remote requests are forbidden. The LAN UI on both host and remote uses upload instead.POST /api/jobs/upload->{id}; LAN only,multipart/form-data, exactly oneworkbookXLSX file, onesourceZIP file and onestart_numberstring (1–9999), no other fields. Applies session, Origin and X-HSD-Token checks. All three public byte limits are null (no application byte cap). The multipart request explicitly overrides Flask's default 64 KiB JSON-body cap; JSON endpoints retain it. Non-file form memory and part-count controls remain. Writes streams todata_dir/uploads/<random-batch>/workbook.xlsxandsource.zip; filenames are display-only. Validates true XLSX/ZIP content, traversal, links, encryption, repeated names, entry counts, 1–500 AI files and actual disk availability; no fixed per-AI/expanded-byte or compression-ratio limit; failed uncommitted uploads are removed. Output is confined todata_dir/employee_outputs/<random-batch>/.GET /api/jobs/<id>-> full owned job as below, poll 1s while queued/importing/matching/ai_review/exporting. CPU work (1 worker), AI batch coordination (2), global AI cases (2) and export (1) have separate resource pools. Queued snapshots addqueue_stage:'cpu'|'ai'|'export';queue_positiondescribes that resource queue. AI-disabled/no-network batches do not wait behind AI requests. Multiple employees upload independently without sharing task state. Long work stays off the request/UI thread. Editing/exporting is unavailable for that busy job; shutdown and settings writes also reject active per-task planning operations. Shutdown drains accepted work and rejects new mutations.POST /api/jobs/<id>/resolve{row_id, file_id: str|null, revert?: bool, expected_revision?:int}; null means skip,revert: truerestores the matcher's own verdict for that row, otherwise confirm mapping; returns job. Refuse duplicate file ownership.POST /api/jobs/<id>/resolve-batchexact{expected_revision:int,items:[{row_id:string,file_id:string}]}requires1–500 distinct pending review rows and distinct files, validates every original/preview and current file/number ownership, plans on a copy and commits all or none.bulk_confirm_eligibleandbulk_confirm_reasonon rows guide the UI, not authorization; selected candidate is rechecked. Hard file/preview/number anomalies remain single-item handling. Accepted rows areconfirmed/accepted_by:human, never automatic. One history group covers the batch.POST /api/jobs/<id>/undo{expected_revision?:int}-> job withlast_undone_row_id; restore the last employee change (all members of a batch together), recompute numbering, increment revision.last_undone_countgives the restored count;can_undoindicates availability.POST /api/jobs/<id>/export{expected_revision?: int}->{id}; background export. UI sends the revision of the reviewed summary. A mismatch rejects stale confirmation; reload the job and show the new summary. No need to view every auto result before export.GET /api/jobs/<id>/image/row/<row_id>and/image/file/<file_id>-> preview image;?size=thumbrequests a proportional thumbnail. Stable job-specific URLs and ETag; LAN uses private no-cache/must-revalidate so every reuse checks the session and owner, while non-LAN keeps private immutable caching. Never append random timestamps.GET /api/jobs/<id>/download-> ZIP attachmentHSD编号结果.zip, LAN/cloud owned upload jobs only, afterstatus:'done'anddownload_ready:true. Exports only service-authorized rows after summary confirmation; contains only the explicit final plan's numbered AI copies and exactly one numbered workbook, under one result folder. CSV/JSON, previews, diagnostics and request records remain host-private and are never ZIP members. Atomically packages verified output members and validates the stored archive SHA256 before serving. Invalid, altered, incomplete or another owner's downloads fail; never supplies arbitrary filesystem paths.POST /api/jobs/<id>/open-output{}->{ok:true}(only completed job output; forbidden for remote clients).POST /api/shutdown{}->{ok:true}; exits the local process when no task is busy; forbidden for remote clients. Closing the browser alone is not shutdown.
resolve-batch requires a non-negative integer expected_revision in every mode. In LAN mode resolve, undo and export require expected_revision for both host and remote pages. A stale revision returns 409; the UI refreshes that owner's job rather than silently overwriting another tab's change. Only final server states make rows exportable; neither upload nor download bypasses summary confirmation, ownership, numbering conflicts or source-change checks. Managed upload/output/download files remain host-side copies; browser attachment download saves the result to the employee's computer without changing their originals.
Job schema:
{id, status:'queued'|'importing'|'matching'|'ai_review'|'ready'|'exporting'|'done'|'error',
progress:{message,current,total,phase?,step_label?}, error:null|string, revision:int, can_undo:bool,
sheet_name, workbook_name, source_name, start_number, prefix:'HSD',
stats:{total,auto,ai_auto,confirmed,review,unmatched,skipped,exportable,
pending,needs_attention,new_numbers},
rows:[{id,row_number,number,planned_number,
status:'auto'|'confirmed'|'review'|'unmatched'|'skipped',
file_id:null|string,candidates:[{file_id,score}],reason,reason_code?,
evidence?,diagnostics?,ai_review?,ai_retrieval?}],
files:[{id,name,relative_path,issue}], warnings:[],
output_root, output_target, output_dir:null|string, report:null|dict,
queue_position:int, download_ready:bool, download_name:null|string,
matching_mode?:'ai_first'|'local', ai_review?, ai_retrieval?, timings?}
auto includes both local and qualified AI acceptance; ai_auto is a subset of auto. Local auto count is auto - ai_auto. confirmed means employee confirmation only. pending = review + unmatched + skipped, while needs_attention = review + unmatched. new_numbers counts accepted blank-number rows; exportable = auto + confirmed. The UI's awaiting count and default “需要处理” filter include review + unmatched; skipped rows remain separate. Automatic entry to the summary depends on review === 0, so a batch with only unmatched/skipped items remaining does not require opening those rows. The summary states all unresolved counts. “Continue” and “All results” still provide optional access to unmatched rows and correction.
All unresolved rows retain their source numbers in output. Only matched rows with blank source numbers get planned new numbers. In non-LAN mode output_target is the destination folder; LAN public snapshots describe downloading to the employee computer instead of exposing host paths. Existing numbers remain exact, including non-HSD prefixes. Duplicate or unsafe output numbers block affected rows; no overwrites. Source changes invalidate affected decisions/export. An export error may return the task to ready with error populated so the UI can explain and retry. Inputs are typed/picked local paths in non-LAN mode and managed browser uploads in employee LAN mode. Session storage may remember the current owned job ID/selected row/filter for page refresh; no tasks survive process shutdown. Uploads and employee output copies are separate from disposable job caches and require host-side lifecycle management; do not claim shutdown deletes every uploaded original.
This section retains the v1.8.0 resource/record foundation. v1.9.0 additionally joins concurrent whole-library retrieval and a complete local CPU child as specified above; enabling AI no longer waits for local review eligibility before the retrieval stage.
JobManager has CPU 1, AI batch coordinators 2, shared AI case workers 2 and export 1. pool remains the CPU executor compatibility alias. Queue order/position is per resource, not an invented whole-batch percentage. Disabled AI, absent usable credentials or a batch without review rows follows the lightweight local completion path instead of waiting for an occupied AI coordinator. Key count never scales concurrency.
job_operation(id, internal=False) is a per-job reentrant operation guard. Look up/count operations under the short global map lock, release it before acquiring the task lock, and never acquire a task lock while holding the global lock. APIs check revision/status and apply one consistent plan under the task operation. AI computes snapshot eligibility, images, hashes, gate evaluation and planning outside task/global locks, then briefly checks the current run token, status, expected revision and original row binding before committing. Its own stable-order commits advance the expected revision; unrelated/user changes do not. A stale response is retained as invalidated evidence with its actual usage and cannot overwrite the current selection. Shutdown rejects new external mutations and drains accepted CPU handoffs, AI coordinators/cases and exports before cache cleanup; accepted internal work uses internal=True.
Each AI batch has at most two in-flight cases using the shared two-worker executor. Only disjoint candidate sets overlap; shared candidates serialize. Apply results in original case order/ID regardless of completion order. Before and after the request, preserve full-case/implementation/source checks, including non-exported competitors. Stop submitting after a terminal provider/pool error, drain all started calls, and mark every uncalled case. run_finished is emitted only after started work converges; success, failure and interruption retain an ending trace. Retry budget stays at two actual attempts per case.
Each completed attempt records only {attempt,key_id?,code,elapsed_ms,usage,not_called?}. Codes and usage are sanitized, with no credential, preview, request body, local path or original exception. Success returns and ReviewError carry attempt_history; the case observation retains all attempts, the planned case ID, actual response/usage and invalidation/failure state. An interrupted coordinator keeps the original error/history and marks interruption rather than replacing it with a successful-looking partial result. A definite pre-HTTP factory/credential failure is not_called with zero requests; an unexpected failure after entering the client review preserves unknown usage. Batch/lifetime accounting merges each case once, pool counters account per actual attempt, and removal of an in-flight key cannot erase process-wide usage.
record_directory(id, 'ai_runs'|'export_records') validates the private root, task ID, section, parent containment and absence of links/reparse points. Persistent host records are:
data_dir/task_records/<job_id>/
ai_runs/ai_observations_<run_id>.json
export_records/<export_id>/处理记录.json
export_records/<export_id>/对应关系.csv
export_records/<export_id>/待处理清单.csv
All planned AI cases are checkpointed before requests. Completed attempts checkpoint immediately; case completion/interruption preserves every result and failure. Artifact mutation/publication uses separate short artifact/write locks outside task/global locks, exclusive temporary files, fsync and atomic replace. Export records retain matching evidence, complete AI run/attempt history, pending/skipped rows and provenance. In Windows/LAN mode jobs/ is disposable scratch and task_records/ survives normal close/cache cleanup, including non-exported failed AI runs. Explicit cloud mode retains both until its signed three-day expiry described above; it does not silently change local/LAN retention. These paths are internal, never downloadable through a new route, Git content or release assets. Private records do not provide persistent browser/task recovery.
The final server plan explicitly allows 已编号AI/<effective-number>.ai and one <source-stem>_已编号.xlsx under the result folder; managed upload's workbook stem is workbook. Both the output folder and employee ZIP exclude CSV/JSON, previews, diagnostics and request records. Do not recursively package everything or filter only a few extensions. Completed-export reuse binds revision, plan, exact member allowlist, original/source hashes, verified output hashes and private-record manifests. Retry/repeated download retain these checks. ZIP64, streamed member writes, temporary cleanup, atomic publication and full archive SHA256 verification remain; compression is a build policy, not a new employee setting.
Timings separate batch wall time and resource queues from accumulated AI case queue/prepare/request/verify work; parallel work sums can exceed wall time. Use the v1.8.0 performance report for actual repeated measurements and unchanged/untested boundaries. tools/benchmark_ai_cases.py checks package isolation and preserves complete synthetic artifacts/debug with source:'synthetic_mock', synthetic_transport:true, real_api_calls:0; its fixture-only serialization also tags workflow-created files. Mock waiting is not real provider latency, independent business validation or production qualification.
This release changes the static interface and interaction work only. Existing business routes, job schemas, matching/numbering decisions, DeepSeek request and qualification gates, ownership checks, upload limits and export validation remain authoritative and unchanged. No new endpoint or front-end-only acceptance state is introduced.
Import shows the applicable local path controls or employee XLSX/ZIP upload controls plus the batch start number and primary submit action. The fixed prefix appears as an example, not another editable field. Template, file requirements and original-preservation information are available under import-help. Local mode keeps folder/source and output selection; employee mode never exposes host path configuration. Upload and background progress identify the current stage; unknown totals remain indeterminate, and queue position is shown separately.
The default review list contains review + unmatched, with skipped rows outside that queue. A compact status line highlights work remaining. Automatic results never require viewing. The comparison retains a stable image area, wide-strip stacking, enlargement, selected-candidate identity and a visible action footer. Alternative candidates, complete paths, similarity metrics and diagnostics are optional expansions. AI-specific differences, file issues, contradictory responses and an AI review concerning another selected candidate remain visible. A suggestion without effective automatic acceptance says it requires employee confirmation, while actual employee-confirmed/skipped states remain correctly identified.
Summary primary counts are exportable, new numbers and pending; the original row treatment is stated whenever pending is nonzero. Local auto, AI conditional auto and employee-confirmed counts are under summary-processing-details, using local = auto - ai_auto so the subset is never counted twice. Per-batch AI usage and estimated USD cost, including unknown usage, stay under batch details. One explicit summary action sends the current revision to the existing export route, without a second duplicate confirmation or an all-images prerequisite. Completion emphasizes result download/open and the next batch; records remain optional.
Host sharing information, AI configuration, cumulative cost and shutdown are grouped under host-management. Remote pages keep that entry hidden, but hiding controls grants no permissions: existing server-side host/owner/session/CSRF checks still enforce every request. Employee pages never render saved keys. The authenticated administrator ledger is the explicitly authorized exception, fetching plaintext into its masked DOM; reveal is visual, not a boundary on delivery to that administrator browser. Employee details cannot obtain host cumulative usage.
Indexing and keyed list-node reuse reduce redundant lookup and whole-list replacement; candidate changes update candidate-specific content while preserving the query image and relevant view state. Search is debounced, previews use job-specific URLs and existing owned thumbnail endpoints, and neighbour preloads are deduplicated per task. A task change clears transient preview/view caches. No new cross-session image cache is added. Busy controls prevent duplicate submits, success follows a valid server response, and failures retain recoverable state. Revision 409 refreshes current server state visibly; it never silently converts a failed save into success. Polling is limited to active background states, backs off for retryable failures and stops for terminal/authentication/task-loss responses.
tools/ui_fixture_server.py serves explicit synthetic UI scenarios for private local acceptance only; it does not load production jobs, settings, credentials or provider calls. tests/test_ui_interactions.js checks semantic and DOM invariants, not real browser timings or AI business accuracy. Before/after screenshots and raw local measurements stay under ignored tmp/; only sanitized verification conclusions belong in documentation.
GET /api/ai/settings-> host sanitized{enabled,configured,model:'deepseek-flash',mode:'evaluation'|'validated',key_source:'saved'|'environment'|'none',key_persistence,price_date,prices,price_basis,storage_warning,validation:{qualified,mode,model,categories,counts,message}}. Remote responses are limited to{enabled,configured,model,mode}.POST /api/ai/settings{enabled?:bool,api_key?:string,clear_key?:bool}-> sanitized settings; host only, forbidden for remote clients. Blank/omitted key preserves the saved value. A new key andclear_key:truetogether are invalid. Windows persists the key with DPAPI CurrentUser; no plaintext fallback. Environment variableDEEPSEEK_API_KEYis used only when no saved key exists. Clearing a saved key does not clear that variable. No browser-readable existing key, mode toggle or validation override.GET /api/ai/usage-> cumulative usage below; host only in LAN mode, remote requests return403. Each employee's own batch usage remains in its job summary.POST /api/jobs/<id>/ai-review{}->{id}, backgroundai_review(firstqueuedfor LAN jobs). UI shows this only whenjob.ai_review.can_retryis true. Server checks owner, ready/configured/enabled, batch limits and actual case eligibility. It never overrides employee decisions.
job.ai_review = {mode,eligible,reviewed,suggested_same,auto_passed,
unresolved,skipped,usage,message,can_retry}
row.ai_review = {verdict?,candidate_id?,reason,checks?,differences?,protocol_diagnostics?,gate_failures?,
outcome,reason_code,gate_reason?,model?,request_id?,category?}
verdict = 'same' | 'different' | 'uncertain'
outcome = 'auto_passed' | 'evaluation_suggestion' | 'manual_review' | 'error' | 'skipped'
usage = {requests,successes,failures,prompt_tokens,completion_tokens,
cache_hit_tokens,cache_miss_tokens,unknown_usage_requests,
estimated_usd,estimated_usd_upper_bound:number|null,
cost_is_upper_bound,cost_incomplete,currency:'USD',price_date}
Default mode is evaluation with no production qualification. Suggestions remain review; no model text or self-reported confidence can change status. Show the candidate the suggestion concerns, especially if the employee is viewing a different candidate. Errors/skips must not be labelled as model or employee acceptance. Only an actually accepted auto row can be labelled AI conditionally accepted. A request failure is contained to AI review and leaves local results/manual work available.
estimated_usd estimates known usage using recorded peak prices. estimated_usd_upper_bound is null if any usage is unknown; the UI must state the unknown request count and incomplete cost statistics, never present unknown charges as zero. These USD figures are estimates, not a provider invoice. There is no monetary fee ceiling. Do not confuse finite request/retry limits with a cost cap.
When more than one valid single-artboard candidate independently passes local geometry or texture verification, the row requires an individual employee decision regardless of the score gap. The matcher records indistinguishable_candidates and the verified candidate IDs. Neither AI pair review nor batch confirmation may advance the row. A candidate with only partial evidence does not trigger this rule.
The following payload/eligibility paragraphs describe the optional pair-review path; whole-library retrieval uses its separate protocol above. Preview-only pair-review payloads contain complete overviews and, for wide images, ordered exhaustive panels, task-local candidate IDs and neutral comparison instructions. Measured valid geometry may add an aligned pair and mapped/unmapped coverage diagram, while retaining all originals. No arbitrary crops/tiles or old local verdict are used to bias the model. Only actual plausible rivals are supplied; complete local competition evidence must account for all files, and more than five credible rivals stays manual. No original AI/XLSX/ZIP, filenames or local paths are included as prompt text. Visible text inside design images remains image content. Treat it as untrusted data, not instructions. Keys are sent only in backend authentication to the configured official provider; never in snapshots, logs, reports or front-end storage.
Eligibility is restricted to untouched review rows with readable single-page previews and verified source metadata. Duplicate previews anywhere in the batch, duplicate query images, actual competing ownership, number conflicts, unreadable images/multiple artboards and absent credible candidates are excluded before the request. Recheck image/source fingerprints before applying a response and before export. Hard conflicts cannot be overridden by the model.
Policy and prompt versions are hsd-ai-review-2. Wire response is exactly {candidate_reviews:[{candidate_id,verdict,reason,checks,differences}]}, one entry per locally supplied ID. Pair checks are content_same/colors_same/complete_coverage/extra_content_absent. Each entry describes only its own candidate. Missing/duplicate/unknown IDs or invalid schemas fail. Contradictory verdict/checks/differences are preserved in bounded protocol_diagnostics.raw_decision, flagged inconsistent and downgraded to uncertain. Provider bodies, prompts and credentials are never retained there.
The client normalizes the pair response to the existing decision fields. unique_candidate is locally derived only from one strict positive and every other supplied candidate explicitly different; identity still requires direct positive evidence. Categories remain geometry_review/texture_review. All five normalized checks must be true, verdict same, differences empty, and chosen candidate the local first. Independent signed qualification, native detail, complete local alignment/coverage, colour/content consistency and complete competition are separate gates. All failures are recorded together as failed_checks/row.ai_review.gate_failures, so missing qualification cannot conceal other contradictions. A model switching candidates, affirming unreadable detail or contradicting local evidence remains manual.
Case fingerprints bind selected-channel evidence, alignment, all competition scores, every compared preview/source digest (comparison_inputs), and the supplied images. Any competitor changing invalidates the earlier proof, even if not exported. Original comparison sources are verified before/after requests and before/after export. Every pair-review run checkpoints all planned cases and the eleven-module implementation_sha256 before I/O and after each attempt; retries retain earlier failures. Changes during a request preserve the actual reply and charges but invalidate the case for qualification. Export records contain both the latest ai_observations and all ai_observation_runs; whole-library retrieval records remain separately typed and cannot substitute for these qualification observations.
tools/run_ai_evaluation.py --synthetic --out <empty-dir> --settings-dir <data-dir> [--prepare-only] prepares generated labelled cases; without --prepare-only it makes real billable calls using the existing settings. Output preserves all planned cases, including failures, plus frozen labels, fingerprints, responses and usage. It never activates business acceptance. Repository-local outputs must stay under ignored tmp/.
tools/validate_ai_review.py --labels <labels.json> --observations <observations.json> --output <report.json> makes no network calls and reads no key. It requires schema version 1, real deepseek_live records of the current protocol, exactly matching unique planned/case/request IDs, a single actual model, image/candidate/source fingerprints, and complete responses. Labels declare case_id, case_fingerprint, batch_id, category, split:'calibration'|'holdout', origin:'independent_manual'|'synthetic_known_truth'|'reference_map', label:'same'|'different'|'uncertain', candidate_ids, expected_candidate_id and controls. The response's case binds category, candidate_ids and image_digests. Do not reuse query images across independent batches or mix calibration and holdout within a batch.
For each approved category, at least two independent holdout batches must each include a positive, a negative/uncertain case and a useful correctly accepted positive. At least one batch must include independently manually verified real business positives and negatives. Overall, at least two accepted positives and five negatives must cover color_change, local_replacement, extra_content, shared_subset, near_duplicate, with zero false accepts across all recorded cases. Synthetic data alone or an existing reference map cannot qualify production. Labels are independent and frozen before observing model output; do not relabel origins or omit failed cases to pass.
After reviewing a qualifying report, adding --activate --data-dir <tool-data-dir> explicitly signs/stores the qualification locally. The registry checks integrity, binds the actual model, categories, policy/prompt versions and eleven implementation modules (ai_policy, ai_client, ai_images, matching, matching_verification, archive_io, ai_workflow, ai_dispatch, ai_key_pool, ai_admin, ai_first), and expires after 7 days. Observation artifacts must have recorded all eleven implementation signatures at call time, matching the current implementation; activation cannot re-sign old results as newly verified code. Missing/mismatching signatures remain usable only for regression analysis, never qualification. Changed implementations/protocols invalidate the record; an unqualified model/category cannot pass the per-row gate. No production qualification is shipped or newly activated in v1.9.0; implementation changes invalidate older qualification while preserving saved encrypted keys and settings. These are minimum activation prerequisites for the measured scope, not a general accuracy guarantee. The user has reserved 10.12 for later and chosen employee verification of a new business batch.
Matching agent: matching.py, image matching helpers, tests/test_matching.py, matching investigation scripts/results under tools/matching_* and tmp/matching_. Workbook agent: workbook.py, tests/test_workbook.py. UI agent: hsd_tool/static/. Must follow API above. No server code. Current documentation-only assignment may edit the five delivery documents separately; no simultaneous root/static edits. Root: service/server, orchestration, export, packaging, docs, integration testing.
Authenticated multipart file parts stream directly to randomized, owner-private staging files under the upload batch, with write-time SHA256 and available-disk checks by 64 MiB windows. Successful parts are renamed on the same filesystem to fixed managed names; failures/interrupted parsing close all streams and clean uncommitted directories. Existing authentication, Origin, CSRF, owner and revision rules remain mandatory. null byte caps never coerce to zero or fall back to old defaults; the upload XHR has no fixed elapsed timeout. Empty files, wrong formats, invalid archives, links, traversal, encryption and excess file counts remain errors. A finite decoded image pixel limit is distinct from file bytes.
JobManager.create(..., input_digests=...) is an internal receiver-only keyword, not a JSON/form field. The receiver supplies workbook/source SHA256 computed from successfully written bytes. The worker copies the workbook then independently hashes its snapshot, and rehashes the source archive after scanning. Local-path imports still take their original before/after hashes. Export source checks, independent AI copy verification, owner checks and verified download hashing remain. AI copy digests already independently verified are reused in the output manifest; packaging hashes each member against that original digest, including retry/tampering paths.
archive_io.member_blocks uses bounded reads and verifies actual decompressed content, declared length, compression EOF and CRC, retaining ZIP header/overlap checks. AI rendering opens file paths rather than a full bytes object; on Windows a read-only sharing lease denies concurrent writers/replacement, with file identity checks. Other platforms rehash after rendering. Workbook non-target parts and images stream through bounded buffers/temporary files; worksheet XML patching retains its original in-memory design, so large XML still depends on actual RAM. No arbitrary byte threshold is substituted.
The new archive IO dependency is included in AI qualification implementation fingerprints and isolated matching-validation signatures. Prior implementation qualification does not silently carry forward. This release changes IO, not matching evidence/thresholds, numbering, AI request scope, prompts, qualification activation or export eligibility.
GET /admin returns a login page until administrator authentication succeeds, on both host and LAN. POST /admin/login uses independent account/password authentication and Origin checks; successful sessions last8 hours and expire on process restart. Ten failed attempts per address in60 seconds trigger429. POST /admin/logout ends the session. Unauthenticated /api/admin/* requests return401 even on the host. Employee login does not grant administrator rights, and administrator login does not grant ownership of employee tasks. The LAN interface/CIDR boundary and write token/Origin checks remain; forwarded IP headers are not trusted. Native file selection, output opening, shutdown and legacy host settings routes remain host-only. Static code contains no actual key or client token; serving it is not API authorization.
GET /api/admin/overview->{settings,pool,usage,debug}. Settings is the sanitized AI config withkey_revision,key_count,keys:[{id,label,enabled,source}]; no key bytes, suffixes or secret fingerprints. Pool describes process-local key health and usage; lifetime usage remains the existing ledger. Host diagnostic visibility does not grant mutation/preview/download rights to employee jobs.GET /api/admin/keys->{settings,pool}. Administrator-authenticated, read-only settings and key health, without querying the cumulative ledger or debug buffer. It does not validate a Key by contacting the provider. The simplified UI polls only this endpoint for status; the ledger is fetched only while its own details section is open, including refresh after Key mutations, never by page entry, opening help or the30-second status poll. Pool retains its compatible process-local metadata; the UI does not render request counts or costs.POST /api/admin/keys->{settings,pool}. Body{expected_revision:int,add?:[{api_key,label?}],update?:[{id,label?,enabled?}],remove?:[id]}. Maximum100 saved keys; duplicates are ignored, validation/persistence is atomic, errors never echo secrets. A stale revision returns409 without saving. All writes require existing token/Origin checks and retain the busy-job guard. Environment fallback keys support enabled state only, not rename/deletion. Legacy/api/ai/settingsremains backward compatible; blank key preserves the pool, suppliedapi_keyreplaces only the first saved entry,clear_keyremoves only that entry.GET /api/admin/debug?after=0&limit=100->{instance,events,cursor,last_seq,oldest_seq,dropped,reset,active}. Limit1–200; cursor is the last returned event, never last_seq while a backlog remains. Sequences increase per process. After beyond last_seq resets; missing buffered events are explicitly counted. Events are bounded to2000 and active waits use a monotonic elapsed time. This bounded live-event buffer is not persistent and has no full-history guarantee; complete case/attempt records are separately retained in host-private task_records.
The v1.10.1 administrator page retains the simplified AI switch and Key management, adding login/logout and a separate Key ledger. GET /api/admin/ledger is an explicitly authorized exception returning saved Key plaintext and labels to logged-in administrators on host or LAN, with no-store and no logging; ordinary APIs continue redaction. The ledger is masked by default, with explicit reveal/copy. Batch input is masked by default, can be revealed, and is cleared on submission and page leaving. Switching to a background tab only pauses polling; it does not clear the input. Clearing does not reset a previously selected reveal mode. No raw key is stored in browser local/session storage. It removes the debug feed, cumulative-cost panel and per-Key usage/cost display from markup and code, rather than hiding them with CSS. Overview/debug endpoints remain administrator-authenticated compatible diagnostic APIs; the UI never polls them. An independent read-only Key refresh runs every30s only while visible, stops on pagehide/401/403 and resumes on return. It preserves dirty switch input, rename/delete UI and focus. A response overlapping a mutation cannot overwrite newer settings. Background configuration conflicts preserve the current edit until explicit refresh. Submitted keys are cleared before awaiting and never retained in local/session storage; state is updated only after server success. A409 locks editing pending explicit refresh. Storage warnings and actionable authentication/balance/cooldown failures remain visible. Matching, qualification, internal accounting and export rules are unchanged.
Events include local job/row/key IDs, allowlisted stages/messages/codes/verdicts/counts/usage and static local gate explanations. Key labels are resolved client-side from the sanitized pool. Arbitrary model explanations, images, request/response bodies, paths, exception strings and hidden reasoning are excluded. Live events do not grant export permission. Every workflow, including disabled/no-case/error paths, finishes its trace in finally.
Private settings v2 atomically stores each saved key under Windows CurrentUser DPAPI with opaque IDs and key_revision. v1 is read without modifying its file; first successful save migrates existing keys. Non-Windows retains only process memory, never plaintext fallback. Old binaries can write version1 over shared settings, so administrators must not edit settings with an old release after migrating.
ApiKeyPool.acquire(exclude_ids=()) filters current enabled, unpaused, non-cooling and non-excluded entries under its existing lock, then uses secrets.choice for an independent uniform draw over usable entries. Consecutive requests may choose the same Key; selection is shared across employees, with no employee affinity, round-robin pointer, weighting or short-window equal-use guarantee. Global disable/account cooldown and empty-pool failures precede any draw. This changes neither concurrency nor the request budget. ai_key_pool remains bound by the existing qualification implementation signature; a changed implementation invalidates old qualifications without activating replacements.
ManagedReviewClient uses fresh pool selection and single-attempt clients with a shared maximum2-request budget per case.401/403 authentication or402 balance pauses a key and may randomly try another usable key within that budget. Network/5xx retries the same still-enabled key.429 ends that case, cools the entire existing pool for60s and stops later calls in that run; already started requests are drained, and another key/new batch cannot immediately evade the cooldown; no rapid key switch circumvents account limits. All attempts, including failed/unknown costs, are merged exactly once into existing batch/lifetime ledgers. Per-key process counters remain distinct from lifetime totals. v1.7.0 retained native eligibility, protocol, independent qualification and export gates and bound ten implementation modules. Current v1.9.0 adds ai_first as the eleventh qualification module, as specified above; multi-Key management itself never grants acceptance.
tools/admin_fixture_server.py is a source-only loopback development fixture with generated inputs and a prominent zero-real-API banner. Its mock transport exercises request/retry/strict parsing/qualification paths without real credentials or provider calls. tools/verify_admin_portable.py tests the actual frozen program with separate synthetic DPAPI settings and reports network-remote coverage honestly; two host cookies are not a second physical employee PC. Neither test grants AI business qualification.
Current evidence is in docs/deployment-v1.10.1-verification.md. Actual frozen Windows tests cover unauthenticated administrator401, invalid login401, throttling429, independent employee upload/download and persistent private records. Successful login is covered by synthetic backend tests, but the real administrator password was not used against the frozen live application. The historical verify_admin_portable.py predates mandatory login and is not proof of successful current administrator login.
The current shared employee website reuses saved host Keys and does not enable the optional internal gateway. Review found that ai_first factories do not accept the gateway endpoint keyword from dispatch, while its retrieval client still fixes the official endpoint. Do not claim full-library gateway routing is validated or enable it as a requirement for employee browser sharing. The active saved-Key direct route is unaffected; this synchronization does not alter matching/numbering/qualification logic.
New first drafts bind layout_engine=design-rhythm-v1, design_density=airy|balanced|rich (default balanced) and background_tone=soft|original (default soft). The optional density/tone fields belong to the existing selection payload, are server validated, participate in selection-change detection, and remain immutable within a saved version. Legacy snapshots keep their legacy engine; non-balanced density requires a new work. Explicit legacy tone changes are real selection edits. The text-only planner receives these settings as read-only context; they are not new model-editable parameters.
The new compositor fits alpha-visible complete designs proportionally, protects a global vertical safe area, repeats complete asset groups and closes alternating orientation/size phases. Alpha-zero external padding is excluded only from derived renders; original files are preserved. Geometry is recorded in private version transforms, including content bounds, roles, safe region and repetition. Three density settings choose actual geometry, never quality qualification. Background fitting/softening is derived presentation; explicit solid colors remain exact and arbitrary textures are not promised seamless.
Before completing any refinement (including artifact recovery), compare complete decoded RGBA master pixels with the bound parent. An unchanged raster is clarification/failure, creates no version and consumes no successful-refinement quota; actual model attempts and usage remain recorded. PNG metadata/compression alone cannot constitute a change. Existing ownership, two-success quota, parent rollback, native profile, pinned downloads and 50-hour retention remain authoritative. Evidence and limits: design-quality verification.
New first drafts bind layout_engine=seamless-unit-v1. Historical unmarked, design-rhythm-v1 and design-rhythm-v2 snapshots keep their render/download semantics. No database migration or in-place template/profile/version rewrite is introduced. Selection HTTP fields remain unchanged. output_profile_source is a deep copy of the originally bound internal profile; saved output_profile differs only in its derived actual width. Height, DPI, format and other fields remain bound. Edits inherit the source profile, not the parent's previous unit width.
loop_layout stores ordered full-alpha content bounds, input signature, natural foreground width, exact integer period, shared background period, mode/row/group geometry and construction verification. Width is derived from complete sequences, density/scale/rotation/spacing/phase and finite-panel semantics, then rounded upward to a whole background period without squeezing artwork. A background unit is uniformly sampled and joined by bounded minimum-error overlap quilting, repeated as exact equal-width pixels. An empty transparent background retains the historical white blank composition. Resource overflows fail specifically before paid work where predictable. Old renders continue their original background fitting.
Saved loop includes engine,width,height,dpi,status:checked|needs_review,issues:[{code,message,severity}],kind:sequence|panel,mode_notice,profile_source,geometry,background,background_wrap,final_wrap,production_verified:false,verification_scope,output_sha256,inputs:[{id,sha256}]. Reports include full-height cut colour/gradient evidence and multiscale bands; matching two edge columns is insufficient. checked means only construction and pixel checks passed, never semantic or printing approval. Failed checks remain visible and do not acquire a verified label. Commit and checkpoint recovery validate report consistency, recomputed construction, source profile, ordered immutable input digests and actual file hash/dimensions; corrupt/missing/contradictory evidence cannot create a version or spend quota.
All14 modes have actual branches; finite ends/blank/whole-image/left-right/three-panel modes repeat the whole declared panel with an explicit notice, retaining their semantics. End-main motifs have a seam gap at least the internal clearance and35% of main width. Alternating size/orientation uses the joint asset/phase cycle. Only the unit's outer horizontal seam can split a motif, whose counterpart wraps to the opposite edge; vertical safe bounds keep complete content. See mode contract.
New loop editing permits parameters and independent asset/background edits; it forbids edit_composite, even when model aspect limits would permit a flattened redraw. Width and checks recompute after every prospective layout/content change. Legacy composite capabilities are unchanged. Parent rollback restores its own immutable dimensions, checks and download; no-op detection and the two-success quota remain authoritative.
The React view detects the version-bound loop, shows one short unit by default and optionally reuses the identical preview URL three times with seam guides. Toggling or polling does not download a master or generate another composite. Version-bound PNG download is always the actual one-unit master, never a preview or triple image. Source/diagnostics stay in details; issues stay visible. Existing worker,50-hour retention, reversible deletion, ownership, cache, idempotency and response leases remain.
The broader ribbon-request-v2 supersedes background keyword protection for new real refinement plans on this branch. See general refinement contract. Wire plans require {summary,clarification,requirements,operations}. The server supplies exact source_units; each requirement is {source_id,target_id,effect:parameters|content|preserve|clarify} and each operation references distinct source_ids. Parameter operations additionally include intents:[{key,mode,amount,direction,evidence}] and absolute values. The server reconstructs content prompts, checks source/target/effect/unique coverage and supported arithmetic, then preflights the complete plan. Real legacy model replies without bindings are rejected; historical direct-parser tests and explicitly marked demo providers do not confer production coverage.
Snapshots privately store edit_plan.request_contract and request_receipt. Receipt binds original UTF-8 SHA256 and Python-codepoint ranges, coverage:checked, verification_scope:plan_and_geometry_only, image_effect_verified:false, plus per-requirement execution: geometry_verified, parameters_applied_unverified, image_generated_unverified or constraint_forwarded. These are execution records, never image-semantic approval. Commit/recovery verifies original planned operations, effective operations, actual allowed state/ref changes and the receipt. Existing HTTP refinement fields and quota/identity/download semantics remain. Pure local selection application bypasses language planning without inventing a coverage receipt.
The codex/ribbon-background-refine branch adds private snapshot edit_plan.request_protection with protocol:background-request-v1, scope, target, explicit_content_request, and semantic_verified:false. The HTTP refinement schema and provider routing are unchanged. A selected background/zone image operation retains the employee's original request; a clearly separated background clause is used for layout-scoped mixed edits. High-confidence background content requests cannot be fulfilled by foreground parameters alone or authorize unrequested foreground changes. The guard never invents image operations; ambiguous scope is clarification, with no successful quota event. It is a bounded text safeguard, not general language or output-semantic verification.
Background image instructions preserve coverage/removal/replacement requirements without imposing tiny/low-contrast styling. Existing background presentation remains unchanged. No extra image request, retry, database migration, historical version rewrite or automatic semantic approval is added. See branch verification for actual evidence and delivery status.
New snapshots bind design-rhythm-v2; v1 retains its rendering semantics. V2 corrects only the ends hierarchy. Generate accepts strict ai_assisted: boolean (default false) and optional reference_code: string|null. A reference with AI disabled is rejected. Config exposes ai_draft_available only for a ready DeepSeek/Seedream runtime. Missing fields retain the original no-model first draft, including older clients.
An assisted draft binds all original input IDs/SHA256 and, only when explicitly selected, the mode-allowed company reference code/fixed SHA. The server resolves no caller-supplied path or URL. All inputs and reference are verified before the single design_background image operation; commit rechecks originals. Seedream receives proportional reference canvases, not filenames, paths or credentials. A new derived background is composed with the original pattern refs. Snapshot provenance records AI background/input/reference identity, not raw reference bytes. Ordinary case viewing never transmits to the provider. Existing artifacts recover without another image call; assisted drafts interrupted before an artifact fail with unknown-result handling. There is no demo fallback in cloud mode or automatic second refinement.
DELETE /designs/{id} soft-deletes an idle owned work; GET /designs?deleted=true lists the caller's deleted works and POST /designs/{id}/restore restores them. Busy works return409 and other owners404. Each actual delete/restore renews the normal50-hour window; repeated delete does not renew it. Versions and quota events are retained, immutable bound downloads keep ownership checks, and all cleanup reference/lease protections apply.
Uploads reuse exact normalized RGBA+canvas identity only within the same owner/shared/kind and upload-source scope. Preview identity is a shortlist, never proof of full equality; damaged candidates are retained but skipped. Existing duplicate rows are not merged or rewritten. New metadata columns are assets.pixel_sha256, assets.thumbnail_pixel_sha256, designs.deleted_at; legacy rows startNULL. Historical rows lacking previews and with different encoded bytes are indexed on normal preview derivation. UI request sequences/cancellation prevent old-work results from overwriting a new target; during switching no old preview/download is exposed as the target.