diff --git a/scripts/qa_001.py b/scripts/qa_001.py index b1507b2..3b91100 100644 --- a/scripts/qa_001.py +++ b/scripts/qa_001.py @@ -57,7 +57,7 @@ def main(): work = Path(temp) site = work / "site" shutil.copytree( - ROOT / "examples/studio-site", site, ignore=shutil.ignore_patterns(".engine") + ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine") ) env = { "SITE_ROOT": str(site), @@ -69,7 +69,7 @@ def main(): "SITE_COOKIE_SECURE": "0", } with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw: - browser = pw.chromium.launch(headless=True, args=["--no-sandbox"]) + browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]) page = browser.new_page(viewport={"width": 1440, "height": 960}) page.on("pageerror", lambda exc: results["console_errors"].append(str(exc))) page.goto(origin + "/admin/login") @@ -82,7 +82,7 @@ def main(): ("/admin/", "overview"), ("/admin/pages", "pages"), ("/admin/pages/index", "page"), - ("/admin/pages/index/blocks/b_hero", "block"), + ("/admin/pages/index/blocks/hero_home", "block"), ("/admin/content", "collections"), ("/admin/content/services", "entries"), ("/admin/content/services/bots", "entry"), @@ -140,24 +140,24 @@ def main(): results["widths"].append([mode + "-dark", width]) page.screenshot(path=str(args.out / "expert-dark-mobile.png")) page.goto(origin + "/admin/publish") - invoker = page.get_by_role( - "button", name="Опубликовать текущий черновик сайта", exact=True - ) + page.locator('[data-pub-action=candidate]').first.click() + page.locator('[data-publication-root][aria-busy=false]').wait_for() + invoker = page.locator('[data-pub-action=publish]') invoker.click() - page.locator("#confirm-dialog").wait_for(state="visible") + page.locator("#publication-modal-root dialog[open]").wait_for(state="visible") for _ in range(4): page.keyboard.press("Tab") - assert page.locator("#confirm-dialog").evaluate( + assert page.locator("#publication-modal-root dialog").evaluate( "(e)=>e.contains(document.activeElement)" ) page.keyboard.press("Escape") - assert not page.locator("#confirm-dialog").is_visible() + assert not page.locator("#publication-modal-root dialog").is_visible() assert invoker.evaluate("(e)=>e===document.activeElement") assert not results["console_errors"], results["console_errors"] browser.close() # Reference is rendered from its own assets, independent of the runtime package. with sync_playwright() as pw: - browser = pw.chromium.launch(headless=True, args=["--no-sandbox"]) + browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]) page = browser.new_page(viewport={"width": 1440, "height": 960}) page.goto((ROOT / "design/antirion-rework.html").as_uri()) page.screenshot(path=str(args.out / "reference-antirion.png"), full_page=True) diff --git a/scripts/qa_content_001.py b/scripts/qa_content_001.py new file mode 100644 index 0000000..d0f25f6 --- /dev/null +++ b/scripts/qa_content_001.py @@ -0,0 +1,468 @@ +"""Original Content design versus real FastAPI: geometry, flows and both preview origins.""" + +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import tempfile +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +from playwright.sync_api import expect, sync_playwright +from qa_001 import PASSWORD, ROOT, serve +from qa_editor_updates import idle, reserve +from starlette.applications import Starlette +from starlette.routing import Mount +from starlette.staticfiles import StaticFiles + +from site_engine.build.pipeline import build_site +from site_engine.services.auth import hash_password +from site_engine.web.app import create_app +from site_engine.web.preview_app import create_preview_app + +OUT = Path(os.environ.get("QA_CONTENT_OUT", "/tmp/site-engine-content-001")) + + +def metrics(page, selectors): + return page.evaluate( + """selectors=>Object.fromEntries(selectors.map(s=>{ + const e=document.querySelector(s),c=getComputedStyle(e),r=e.getBoundingClientRect(); + return [s,{width:r.width,height:r.height,font:c.fontSize,padding:c.padding, + color:c.color,background:c.backgroundColor,columns:c.gridTemplateColumns}]; + }))""", + selectors, + ) + + +def main(): + OUT.mkdir(parents=True, exist_ok=True) + report = { + "runs": [], + "comparisons": [], + "page_errors": [], + "native_dialogs": [], + "console_errors": [], + "expected_errors": [], + } + with sync_playwright() as pw: + browser = pw.chromium.launch( + channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"] + ) + for interactive in (False, True): + run = {"interactive": interactive, "checks": []} + report["runs"].append(run) + with ( + tempfile.TemporaryDirectory(prefix="content-design-qa-") as tmp, + ExitStack() as stack, + ): + work, site = Path(tmp), Path(tmp) / "site" + shutil.copytree( + ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine") + ) + original_file = (site / "content/services/bots.md").read_bytes() + build_site(site, work / "dist") + admin_socket, preview_socket = reserve(), reserve() + admin = "http://127.0.0.1:" + str(admin_socket.getsockname()[1]) + preview = "http://127.0.0.1:" + str(preview_socket.getsockname()[1]) + stack.enter_context( + patch.dict( + os.environ, + { + "SITE_ROOT": str(site), + "SITE_DIST": str(work / "dist"), + "SITE_STATE_DIR": str(work / "state"), + "SITE_ADMIN_LOGIN": "admin", + "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10), + "SITE_SECRET_KEY": "content-browser-secret-" * 4, + "SITE_COOKIE_SECURE": "0", + "SITE_ADMIN_ORIGIN": admin if interactive else "", + "SITE_PREVIEW_ORIGIN": preview if interactive else "", + }, + ) + ) + app, gate = create_app(), {"delay": 0} + + @app.middleware("http") + async def delay(request, call_next, gate=gate): + if ( + request.url.path.endswith("/update") + and request.url.path.startswith("/admin/editor/") + and gate["delay"] + ): + delay, gate["delay"] = gate["delay"], 0 + await asyncio.sleep(delay) + return await call_next(request) + + stack.enter_context(serve(app, admin_socket)) + if interactive: + stack.enter_context(serve(create_preview_app(), preview_socket)) + else: + preview_socket.close() + design_origin = stack.enter_context( + serve( + Starlette( + routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))] + ) + ) + ) + context = browser.new_context( + viewport={"width": 1440, "height": 1050}, reduced_motion="reduce" + ) + stack.callback(context.close) + page, ref = context.new_page(), context.new_page() + page.set_default_timeout(10000) + page.on("pageerror", lambda e: report["page_errors"].append(str(e))) + + def console(message): + if message.type != "error": + return + expected = ( + any(str(code) in message.text for code in (401, 403, 409, 422, 500)) + or "net::ERR_FAILED" in message.text + ) + report["expected_errors" if expected else "console_errors"].append( + {"message": message.text, "url": message.location.get("url")} + ) + + page.on("console", console) + page.on( + "dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss()) + ) + posts = [] + page.on( + "request", + lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None, + ) + page.goto(admin + "/admin/login") + page.locator("[name=login]").fill("admin") + page.locator("[name=password]").fill(PASSWORD) + page.get_by_role("button", name="Войти", exact=True).click() + page.goto(admin + "/admin/content/services/bots") + idle(page) + ref.goto(design_origin + "/content-antirion.html") + if not interactive: + selectors = [ + ".entry-workspace", + ".collection-pane .pane-title", + ".entry-pane .pane-title", + ".entry-tabs button", + ".field-label", + ".preview-pane .pane-title", + ".workspace-footer", + ] + for skin in ("light", "dark"): + page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin) + # Approved dark Antirion tokens; the source has no Antirion dark palette. + for width in (1440, 1280, 1024, 768, 390, 360): + page.set_viewport_size({"width": width, "height": 1050}) + ref.set_viewport_size({"width": width, "height": 1050}) + actual, original = metrics(page, selectors), metrics(ref, selectors) + assert not page.evaluate( + "document.documentElement.scrollWidth>innerWidth+1" + ), (skin, width) + for selector in selectors[1:]: + assert actual[selector]["font"] == original[selector]["font"], ( + selector, + width, + ) + assert ( + actual[selector]["padding"] == original[selector]["padding"] + ), (selector, width) + if width >= 1280: + a, b = ( + actual[".entry-workspace"]["columns"].split(), + original[".entry-workspace"]["columns"].split(), + ) + for i in (0, 1, 3): + assert a[i] == b[i], (width, a, b) + if skin == "light": + for selector in selectors[1:]: + assert ( + actual[selector]["background"] + == original[selector]["background"] + ), (selector, width) + report["comparisons"].append( + { + "skin": skin, + "width": width, + "runtime": actual, + "reference": original, + } + ) + page.screenshot( + path=str(OUT / f"content-{skin}-{width}.png"), full_page=True + ) + if skin == "light": + ref.screenshot( + path=str(OUT / f"reference-{width}.png"), full_page=True + ) + page.evaluate("document.body.dataset.skin='light'") + page.set_viewport_size({"width": 1440, "height": 1050}) + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("original_geometry_fonts_padding_palette_and_responsive") + + # Local filters/tabs send no requests, retain keyboard focus. + before = len(posts) + page.locator("#entry-query").fill("nothing-matches") + expect(page.locator("[data-content-list-empty]")).to_be_visible() + assert page.locator("#entry-query").evaluate("e=>e===document.activeElement") + page.locator("#entry-query").fill("") + page.locator("[data-content-filter=draft]").click() + expect(page.locator("[data-entry=automation]")).to_be_visible() + expect(page.locator("[data-entry=bots]")).to_be_hidden() + page.locator("[data-content-filter=all]").click() + for tab in ("relations", "usage", "schema", "fields"): + page.locator("[data-content-tab=" + tab + "]").click() + expect(page.locator("[data-content-panel=" + tab + "]")).to_be_visible() + assert len(posts) == before + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("local_filter_tabs_and_real_metadata") + + field = page.locator('[name="p.title"]') + field.evaluate("e=>e.__qaInput=true") + page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame=true") + before = len(posts) + field.fill("One background content update") + idle(page) + expect(page.frame_locator("#preview-result iframe").locator("strong")).to_have_text( + "One background content update" + ) + assert posts[before:] == [admin + "/admin/editor/content/services/bots/update"], ( + posts[before:] + ) + assert field.evaluate("e=>e.__qaInput===true&&document.activeElement===e") + assert page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame===true") + assert (site / "content/services/bots.md").read_bytes() == original_file + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("one_post_keeps_field_frame_and_no_autosave") + + gate["delay"] = 1 + field.fill("Delayed candidate") + page.wait_for_function( + "()=>document.getElementById('document-editor').dataset.updating==='true'" + ) + field.fill("Latest candidate during pending POST") + page.locator("[data-content-tab=relations]").click() + expect(page.locator("[data-content-panel=relations]")).to_be_visible() + idle(page) + page.locator("[data-content-tab=fields]").click() + expect(field).to_have_value("Latest candidate during pending POST") + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("typing_and_tabs_do_not_wait_for_delayed_post") + + # Asset/ref dialogs have real options and restore focus with Escape. + picker = page.locator('[data-content-picker="p.hero_asset"]') + picker.click() + expect(page.locator("dialog[open] .asset-option").first).to_be_visible() + page.keyboard.press("Escape") + assert picker.evaluate("e=>e===document.activeElement") + page.locator('[data-content-picker="p.related_scenarios"]').click() + expect(page.locator("dialog[open] .ref-choice")).to_have_count(3) + page.locator("dialog[open] input[type=checkbox]").first.uncheck() + page.locator("dialog[open]").get_by_role( + "button", name="Применить", exact=True + ).click() + idle(page) + page.locator('[data-content-bool="p.featured"]').uncheck() + idle(page) + assert page.evaluate("window.siteDocument.state.model.meta.featured") is False + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("real_asset_ref_picker_and_boolean") + + # Explicit add and remove list rows preserve names and field focus. + page.locator('[data-content-add="p.benefits"]').click() + row = page.locator('[data-list-row="p.benefits.2"] textarea') + row.fill("New list item") + idle(page) + expect(page.locator('[data-list-row="p.benefits.3"]')).to_be_hidden() + page.locator('[data-content-remove="p.benefits.0"]').click() + idle(page) + assert page.evaluate("window.siteDocument.state.model.meta.benefits.length") == 2 + expect(page.locator('[name="p.benefits.1"]')).to_have_value("New list item") + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("explicit_list_add_delete_reindexes_controls") + + page.locator("[data-content-preview=page]").click() + idle(page) + expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text( + "Latest candidate during pending POST" + ) + page.locator("[data-content-version=live]").click() + idle(page) + expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text( + "Telegram-боты" + ) + page.locator("[data-content-preview=card]").click() + idle(page) + expect(page.locator("#preview-result .preview-empty")).to_contain_text("карточка") + page.locator("[data-content-version=workspace]").click() + idle(page) + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("real_workspace_card_page_and_immutable_live_page") + + page.locator("[data-content-validate]").first.click() + expect(page.locator("dialog[open] .review-summary")).to_be_visible() + page.screenshot(path=str(OUT / f"review-{interactive}.png")) + page.keyboard.press("Escape") + page.locator("[data-editor-mode=expert]").click() + expect(page.locator("#expert-pane")).to_be_visible() + page.locator("[data-content-diff]").click() + expect(page.locator("dialog[open] .diff-row.changed").first).to_be_visible() + page.keyboard.press("Escape") + source = page.locator("#document-source").input_value() + page.locator("#document-source").fill("---\ntitle: [\n---\nKeep this source") + page.wait_for_timeout(450) + page.wait_for_function("()=>!window.siteDocument.state.busy") + expect(page.locator("#document-source")).to_have_value( + "---\ntitle: [\n---\nKeep this source" + ) + expect(page.locator("[data-content-source-errors]")).not_to_be_empty() + page.locator("#document-source").fill(source) + idle(page) + page.locator("[data-content-find]").click() + page.locator("[data-source-query]").fill("Latest candidate") + page.locator("dialog[open]").get_by_role("button", name="Найти", exact=True).click() + assert page.locator("#document-source").evaluate( + "e=>e.selectionEnd>e.selectionStart" + ) + page.locator("[data-editor-mode=constructor]").click() + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("review_expert_diff_find_invalid_yaml_recovery") + + # Navigation confirmation uses the original dialog, Escape retains edits. + page.locator("[data-entry=ai]").click() + expect(page.locator("dialog[open]")).to_contain_text("несохранённые") + page.keyboard.press("Escape") + assert page.url.endswith("/services/bots") + page.locator("[data-save-document]").click() + page.wait_for_function( + "()=>!window.siteDocument.state.dirty&&!window.siteDocument.state.busy" + ) + assert b"Latest candidate" in (site / "content/services/bots.md").read_bytes() + assert (work / "dist/current").exists() + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("leave_confirmation_explicit_save_no_publish") + + # Real CAS conflict; local unsaved text survives. + field.fill("My conflict candidate") + idle(page) + server_source = ( + (site / "content/services/bots.md") + .read_text() + .replace("Latest candidate during pending POST", "Server concurrent title") + ) + (site / "content/services/bots.md").write_text(server_source) + page.locator("[data-save-document]").click() + expect(page.locator("dialog[open] .conflict-grid")).to_be_visible() + expect(field).to_have_value("My conflict candidate") + page.screenshot(path=str(OUT / f"conflict-{interactive}.png")) + page.keyboard.press("Escape") + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("real_409_preserves_unsaved_source") + + # Reload is intentional and has no system dialog. + page.reload() + idle(page) + field = page.locator('[name="p.title"]') + field.fill("Copied current editor") + idle(page) + page.locator("[data-content-duplicate]").click() + page.wait_for_url("**/bots-copy") + idle(page) + expect(page.locator('[name="p.title"]')).to_have_value( + "Copied current editor (копия)" + ) + assert "status: draft" in (site / "content/services/bots-copy.md").read_text() + page.locator("[data-content-delete]").click() + expect(page.locator("dialog[open]")).to_contain_text("Удалить запись?") + page.keyboard.press("Escape") + assert (site / "content/services/bots-copy.md").exists() + page.locator("[data-content-delete]").click() + page.locator("dialog[open]").get_by_role( + "button", name="Удалить из workspace", exact=True + ).click() + page.wait_for_url("**/services/ai") + assert not (site / "content/services/bots-copy.md").exists() + idle(page) + page.locator("[data-content-delete]").click() + expect(page.locator("#request-error")).to_contain_text("архивируйте") + page.locator("[data-close-request-error]").click() + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append( + "duplicate_current_candidate_delete_confirmation_and_published_guard" + ) + + # Empty/off collections and a real new draft in an enabled collection. + page.goto(admin + "/admin/content/posts") + expect(page.locator("[data-content-list-empty]")).to_contain_text( + "Записей пока нет" + ) + expect( + page.get_by_role("button", name="Создать запись", exact=True) + ).to_be_disabled() + page.goto(admin + "/admin/content/services") + idle(page) + page.get_by_role("button", name="Создать запись", exact=True).click() + page.wait_for_url("**/services/entry-*") + idle(page) + assert page.locator("#entry-slug").input_value().startswith("entry-") + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("empty_disabled_collection_and_create_real_draft") + + # HTTP and network errors keep the active fields and show a message. + field = page.locator('[name="p.title"]') + page.route( + "**/admin/editor/**/update", + lambda route: route.fulfill( + status=500, + content_type="application/json", + body=json.dumps( + { + "error": { + "code": "qa_failure", + "message": "Проверка HTTP 500", + "request_id": "content-qa", + } + } + ), + ), + ) + field.fill("Keep text after error") + expect(page.locator("#request-error")).to_contain_text("Проверка HTTP 500") + expect(field).to_have_value("Keep text after error") + page.unroute("**/admin/editor/**/update") + field.fill("Recovery after 500") + idle(page) + page.route("**/admin/editor/**/update", lambda route: route.abort()) + field.fill("Keep text offline") + expect(page.locator("#request-error")).to_contain_text("Нет связи") + expect(field).to_have_value("Keep text offline") + page.unroute("**/admin/editor/**/update") + field.fill("Recovered connection") + idle(page) + print("PASS", interactive, len(run["checks"]) + 1, flush=True) + run["checks"].append("500_and_network_errors_visible_and_recoverable") + ref.close() + assert not report["page_errors"], report["page_errors"] + assert not report["native_dialogs"], report["native_dialogs"] + assert not report["console_errors"], report["console_errors"] + browser.close() + (OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2)) + print( + json.dumps( + { + "comparisons": len(report["comparisons"]), + "runs": report["runs"], + "errors": report["page_errors"], + }, + ensure_ascii=False, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/qa_editor_updates.py b/scripts/qa_editor_updates.py index 1306652..4f26511 100644 --- a/scripts/qa_editor_updates.py +++ b/scripts/qa_editor_updates.py @@ -317,6 +317,8 @@ def main(): page.goto(admin + '/admin/content/services/bots') idle(page) + page.locator('[data-content-preview=page]').click() + idle(page) entry = page.locator('[data-inspector] [name="p.title"]') entry.fill('Entry background update') idle(page) diff --git a/scripts/qa_errors_001.py b/scripts/qa_errors_001.py index 5233aed..d3b5011 100644 --- a/scripts/qa_errors_001.py +++ b/scripts/qa_errors_001.py @@ -36,7 +36,7 @@ def main(): work = Path(temp) site, dist = work / "site", work / "dist" shutil.copytree( - ROOT / "examples/ai-studio", site, ignore=shutil.ignore_patterns(".engine") + ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine") ) build_site(site, dist) live = (dist / "current").resolve() @@ -61,6 +61,7 @@ def main(): options = {"headless": True} if kind.name == "chromium": options["args"] = ["--no-sandbox", "--no-proxy-server"] + options["channel"] = "chromium" if kind.name == "firefox": options["firefox_user_prefs"] = {"network.proxy.type": 0} if os.environ.get("QA_BROWSER_EXECUTABLE"): @@ -84,16 +85,13 @@ def main(): page.wait_for_url(origin + "/admin/") page.goto(origin + "/admin/publish") with patch( - "site_engine.web.api.routes.publish", + "site_engine.services.publication.build_site", side_effect=PermissionError("QA publish denied"), ): - page.get_by_role("button", name="Опубликовать текущий черновик сайта").click() with page.expect_response( - lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST" + lambda r: r.url.endswith("/admin/publication/build") and r.request.method == "POST" ) as failed: - page.locator("#confirm-dialog").get_by_role( - "button", name="Продолжить" - ).click() + page.locator('[data-pub-action=candidate]').first.click() response = failed.value assert response.status == 500 correlation = response.headers["x-request-id"] @@ -146,16 +144,22 @@ def main(): page.unroute("**/admin/editor/pages/index/save") checks.append("network_failure_is_visible_and_preserves_unsaved_source") page.get_by_role("button", name="Сохранить документ", exact=True).click() - expect(page.locator("#editor-result")).to_have_attribute("data-saved", "1") + page.wait_for_function( + "expected => window.siteDocument?.state?.saved === expected && !window.siteDocument.state.dirty", + arg=edited, + ) assert (site / "pages/index.md").read_text() == edited assert (dist / "current").resolve() == live checks.append("save_recovers_after_failure_without_publishing") page.goto(origin + "/admin/publish") - page.get_by_role("button", name="Опубликовать текущий черновик сайта").click() + page.locator('[data-pub-action=candidate]').first.click() + page.locator('[data-publication-root][aria-busy=false]').wait_for() + page.locator('[data-pub-action=publish]').click() + page.locator('#release-comment').fill('Error recovery QA release') with page.expect_response( - lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST" + lambda r: r.url.endswith("/admin/publication/activate") and r.request.method == "POST" ) as published: - page.locator("#confirm-dialog").get_by_role("button", name="Продолжить").click() + page.locator('[data-pub-action=confirm-publish]').click() assert published.value.status == 200 assert (dist / "current").resolve() != live expect(page.locator("#request-error")).to_be_hidden() diff --git a/scripts/qa_publication_001.py b/scripts/qa_publication_001.py new file mode 100644 index 0000000..ba0eccc --- /dev/null +++ b/scripts/qa_publication_001.py @@ -0,0 +1,376 @@ +"""Real publication workflow and original design in Chromium; isolated temporary sites.""" + +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import tempfile +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +from playwright.sync_api import expect, sync_playwright +from qa_001 import PASSWORD, ROOT, serve +from qa_editor_updates import reserve +from starlette.applications import Starlette +from starlette.routing import Mount +from starlette.staticfiles import StaticFiles + +from site_engine.build.pipeline import hash_tree +from site_engine.services.auth import hash_password +from site_engine.web.app import create_app +from site_engine.web.preview_app import create_preview_app + +OUT = Path(os.environ.get("QA_PUBLICATION_OUT", "/tmp/site-engine-publication-001")) + + +def metrics(page, selectors): + return page.evaluate( + """selectors=>Object.fromEntries(selectors.map(s=>{ + const e=document.querySelector(s),r=e.getBoundingClientRect(),c=getComputedStyle(e); + return [s,{width:r.width,font:c.fontSize,padding:c.padding,background:c.backgroundColor,columns:c.gridTemplateColumns}]; + }))""", + selectors, + ) + + +def main(): + OUT.mkdir(parents=True, exist_ok=True) + report = { + "comparisons": [], + "runs": [], + "page_errors": [], + "console_errors": [], + "expected_errors": [], + "native_dialogs": [], + } + with sync_playwright() as pw: + browser = pw.chromium.launch( + channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"] + ) + for interactive in (False, True): + with tempfile.TemporaryDirectory(prefix="publication-qa-") as tmp, ExitStack() as stack: + work = Path(tmp) + site = work / "site" + dist = work / "dist" + shutil.copytree( + ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine") + ) + admin_socket, preview_socket = reserve(), reserve() + admin = f"http://127.0.0.1:{admin_socket.getsockname()[1]}" + preview = f"http://127.0.0.1:{preview_socket.getsockname()[1]}" + stack.enter_context( + patch.dict( + os.environ, + { + "SITE_ROOT": str(site), + "SITE_DIST": str(dist), + "SITE_STATE_DIR": str(work / "state"), + "SITE_ADMIN_LOGIN": "admin", + "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10), + "SITE_SECRET_KEY": "publication-browser-secret-" * 3, + "SITE_COOKIE_SECURE": "0", + "SITE_ADMIN_ORIGIN": admin if interactive else "", + "SITE_PREVIEW_ORIGIN": preview if interactive else "", + }, + ) + ) + app = create_app() + gate = {"delay": 0} + + @app.middleware("http") + async def delay(request, call_next, gate=gate): + if request.url.path == "/admin/publication/build" and gate["delay"]: + value, gate["delay"] = gate["delay"], 0 + await asyncio.sleep(value) + return await call_next(request) + + stack.enter_context(serve(app, admin_socket)) + if interactive: + stack.enter_context(serve(create_preview_app(), preview_socket)) + else: + preview_socket.close() + reference = stack.enter_context( + serve( + Starlette( + routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))] + ) + ) + ) + context = browser.new_context( + viewport={"width": 1440, "height": 1050}, reduced_motion="reduce" + ) + stack.callback(context.close) + page, ref = context.new_page(), context.new_page() + page.set_default_timeout(12000) + page.on("pageerror", lambda e: report["page_errors"].append(str(e))) + + def console(message): + if message.type != "error": + return + expected = ( + any(str(code) in message.text for code in (401, 403, 409, 422, 500)) + or "net::ERR_FAILED" in message.text + ) + report["expected_errors" if expected else "console_errors"].append( + {"message": message.text, "url": message.location.get("url")} + ) + + page.on("console", console) + page.on( + "dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss()) + ) + posts = [] + page.on( + "request", + lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None, + ) + checks = [] + report["runs"].append({"interactive": interactive, "checks": checks}) + + def done(name, checks=checks, interactive=interactive): + checks.append(name) + print("PASS", interactive, len(checks), name, flush=True) + + def ready(page=page): + expect(page.locator("[data-publication-root]")).to_have_attribute( + "aria-busy", "false" + ) + + def tab(name, page=page): + page.locator(f'[data-pub-tab="{name}"]').click() + + def action(name, page=page): + page.locator(f'[data-pub-action="{name}"]').first.click() + + def build(page=page, action=action, ready=ready): + action("candidate") + ready() + expect(page.locator("[data-pub-action=publish]")).to_be_visible() + + def publish(comment, page=page, action=action, ready=ready): + action("publish") + page.locator("#release-comment").fill(comment) + action("confirm-publish") + ready() + expect(page.locator("dialog[open]")).to_have_count(0) + + page.goto(admin + "/admin/login") + page.locator("[name=login]").fill("admin") + page.locator("[name=password]").fill(PASSWORD) + page.get_by_role("button", name="Войти", exact=True).click() + page.wait_for_url(admin + "/admin/") + with page.expect_response(lambda r, admin=admin: r.url == admin + "/admin/publish") as opened: + page.locator('#sidebar a[href="/admin/publish"]').click() + assert opened.value.request.headers.get("hx-boosted") == "true" + ready() + expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет") + assert not (dist / "current").exists() + done("real_empty_first_release") + ref.goto(reference + "/publication-antirion.html") + if not interactive: + selectors = [ + ".heading h1", + ".livebar", + ".pipe", + ".panel-header", + ".table th", + ".table td", + ".button.primary", + ".tabs", + ] + for skin in ("light", "dark"): + page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin) + for width in (1440, 1280, 1024, 768, 390, 360): + page.set_viewport_size({"width": width, "height": 1050}) + ref.set_viewport_size({"width": width, "height": 1050}) + a, b = metrics(page, selectors), metrics(ref, selectors) + assert not page.evaluate( + "document.documentElement.scrollWidth>innerWidth+1" + ), (skin, width) + for s in selectors: + assert a[s]["font"] == b[s]["font"], (s, width, a[s], b[s]) + assert a[s]["padding"] == b[s]["padding"], (s, width, a[s], b[s]) + if skin == "light": + assert a[s]["background"] == b[s]["background"], ( + s, + width, + a[s], + b[s], + ) + report["comparisons"].append( + {"skin": skin, "width": width, "runtime": a, "reference": b} + ) + page.screenshot( + path=str(OUT / f"publication-{skin}-{width}.png"), full_page=True + ) + if skin == "light": + ref.screenshot( + path=str(OUT / f"reference-{width}.png"), full_page=True + ) + page.set_viewport_size({"width": 1440, "height": 1050}) + page.evaluate("document.body.dataset.skin='light'") + done("original_geometry_fonts_padding_palette_responsive_12_sets") + before = len(posts) + page.locator("#pub-search").fill("no-such-document") + expect(page.locator(".table tbody")).to_contain_text("Ничего не найдено") + expect(page.locator("#pub-search")).to_be_focused() + page.locator("#pub-search").fill("pages/index.md") + page.locator('[data-pub-select="pages/index.md"]').click() + expect(page.locator(".split>.stack").last).to_contain_text("pages/index.md") + tab("checks") + tab("history") + tab("changes") + assert len(posts) == before + done("local_filters_selection_tabs_no_post") + action("compare-doc") + expect(page.locator("dialog[open]")).to_contain_text("Workspace") + page.keyboard.press("Escape") + expect(page.locator("dialog[open]")).to_have_count(0) + action("doc-history") + expect(page.locator("dialog[open]")).to_contain_text("предыдущих версий пока нет") + action("close-modal") + done("real_compare_and_empty_document_history_designer_dialog") + action("validate") + ready() + expect(page.locator(".summary")).to_contain_text("Проверено") + assert not (dist / "current").exists() + done("real_validate_does_not_publish") + gate["delay"] = 1.5 + action("candidate") + tab("activity") + expect(page.locator("[data-pub-tab=activity]")).to_have_attribute( + "aria-selected", "true" + ) + ready() + tab("candidate") + expect(page.locator("[data-pub-action=publish]")).to_be_enabled() + candidate = json.loads((work / "state/publication/candidate.json").read_text()) + assert not (dist / "current").exists() + original_output = hash_tree(dist / candidate["id"]) + done("background_candidate_does_not_freeze_tabs_or_activate") + action("candidate-diff") + expect(page.locator("dialog[open]")).to_contain_text("pages/index.md") + action("close-modal") + action("preview") + ready() + frame = page.frame_locator(".release-preview") + expect(frame.locator("body")).to_contain_text("Автоматизируем") + assert not page.frames[-1].locator("script").count() + page.screenshot( + path=str(OUT / f"candidate-preview-{interactive}.png"), full_page=True + ) + action("close-modal") + done("immutable_candidate_diff_and_real_passive_preview") + action("publish") + page.locator("#release-comment").fill("Не публиковать") + action("close-modal") + assert not (dist / "current").exists() + publish("Первый проверенный релиз") + first = (dist / "current").resolve().name + assert first == candidate["id"] and hash_tree(dist / first) == original_output + expect(page.locator(".livebar")).to_contain_text(first) + done("cancel_and_explicit_publish_exact_candidate") + path = site / "pages/index.md" + source = path.read_text() + path.write_text(source + "\nИзменение для второго релиза.\n") + tab("changes") + action("refresh-workspace") + ready() + build() + candidate = json.loads((work / "state/publication/candidate.json").read_text()) + action("publish") + page.locator("#release-comment").fill("Устаревший кандидат") + path.write_text(path.read_text() + "\nНовая правка после просмотра.\n") + action("confirm-publish") + ready() + expect(page.locator("#request-error")).to_contain_text("Кандидат устарел") + assert (dist / "current").resolve().name == first + action("close-modal") + page.locator("[data-close-request-error]").click() + tab("candidate") + expect(page.locator("[data-pub-action=publish]")).to_be_disabled() + done("real_stale_candidate_409_visible_and_live_unchanged") + build() + publish("Второй релиз") + second = (dist / "current").resolve().name + assert second != first + source_hash = hash_tree(site) + page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click() + page.screenshot(path=str(OUT / f"rollback-{interactive}.png"), full_page=True) + action("close-modal") + assert (dist / "current").resolve().name == second + page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click() + action("rollback-confirm") + ready() + assert (dist / "current").resolve().name == first and hash_tree(site) == source_hash + done("rollback_cancel_confirm_preserves_workspace") + page.goto(admin + "/admin/publish") + ready() + expect(page.locator(".livebar")).to_contain_text(first) + tab("activity") + expect(page.locator(".timeline")).to_contain_text("release_rollback") + tab("history") + page.locator(f'[data-pub-action=release-details][data-release="{second}"]').click() + expect(page.locator("dialog[open]")).to_contain_text("Второй релиз") + action("close-modal") + done("reload_real_history_comments_and_audit") + with patch( + "site_engine.core.render.Renderer.render", + side_effect=RuntimeError("QA render failure"), + ): + action("candidate") + ready() + expect(page.locator("#request-error")).to_contain_text("Внутренняя ошибка сервера") + expect(page.locator("#publication-panel")).to_contain_text("Ошибка сборки") + action("build-log") + expect(page.locator("dialog[open]")).to_contain_text("ID запроса") + action("close-modal") + assert (dist / "current").resolve().name == first + page.locator("[data-close-request-error]").click() + page.route("**/admin/publication/build", lambda route: route.abort()) + action("candidate") + ready() + expect(page.locator("#request-error")).to_contain_text("Нет связи с сервером") + page.unroute("**/admin/publication/build") + page.locator("[data-close-request-error]").click() + build() + done("500_network_visible_logged_and_recoverable") + page.goto(admin + "/admin/pages/index") + expect(page.locator(".builder")).to_be_visible() + page.goto(admin + "/admin/content/services/bots") + expect(page.locator(".entry-workspace")).to_be_visible() + page.goto(admin + "/admin/theme") + expect(page.locator(".theme-content")).to_be_visible() + page.goto(admin + "/admin/publish") + ready() + tab("checks") + page.locator("[data-pub-tab=checks]").focus() + page.keyboard.press("ArrowRight") + expect(page.locator("[data-pub-tab=candidate]")).to_be_focused() + page.locator("[data-action=profile]").click() + page.locator("#profile-dialog button[type=submit]").click() + expect(page.locator("input[name=login]")).to_be_visible() + done("accepted_screens_keyboard_and_logout") + browser.close() + (OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2)) + assert not report["page_errors"], report["page_errors"] + assert not report["console_errors"], report["console_errors"] + assert not report["native_dialogs"], report["native_dialogs"] + print( + json.dumps( + { + "comparisons": len(report["comparisons"]), + "runs": report["runs"], + "errors": report["page_errors"], + }, + ensure_ascii=False, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/qa_publication_navigation_001.py b/scripts/qa_publication_navigation_001.py new file mode 100644 index 0000000..2f51e07 --- /dev/null +++ b/scripts/qa_publication_navigation_001.py @@ -0,0 +1,132 @@ +"""Publication boot through real htmx links, history and repeated navigation.""" + +from __future__ import annotations + +import json +import os +import shutil +import tempfile +from pathlib import Path +from unittest.mock import patch + +from playwright.sync_api import expect, sync_playwright +from qa_001 import PASSWORD, ROOT, serve + +from site_engine.services.auth import hash_password +from site_engine.web.app import create_app + + +def main(): + out = Path( + os.environ.get("QA_PUBLICATION_NAV_OUT", "/tmp/site-engine-publication-navigation-001") + ) + out.mkdir(parents=True, exist_ok=True) + report = {"checks": [], "page_errors": [], "console_errors": [], "native_dialogs": []} + with tempfile.TemporaryDirectory(prefix="publication-navigation-") as tmp: + work = Path(tmp) + shutil.copytree( + ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine") + ) + env = { + "SITE_ROOT": str(work / "site"), + "SITE_DIST": str(work / "dist"), + "SITE_STATE_DIR": str(work / "state"), + "SITE_ADMIN_LOGIN": "admin", + "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10), + "SITE_SECRET_KEY": "publication-navigation-test-" * 3, + "SITE_COOKIE_SECURE": "0", + "SITE_ADMIN_ORIGIN": "", + "SITE_PREVIEW_ORIGIN": "", + } + with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw: + browser = pw.chromium.launch( + channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"] + ) + context = browser.new_context(viewport={"width": 1440, "height": 960}) + page = context.new_page() + page.set_default_timeout(6000) + page.on( + "pageerror", + lambda exc: report["page_errors"].append({"message": str(exc), "stack": exc.stack}), + ) + page.on( + "console", + lambda msg: ( + report["console_errors"].append(msg.text) if msg.type == "error" else None + ), + ) + page.on( + "dialog", + lambda dialog: (report["native_dialogs"].append(dialog.message), dialog.dismiss()), + ) + + def ready(): + expect(page.locator("[data-publication-root]")).to_have_attribute( + "aria-busy", "false" + ) + expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет") + assert page.evaluate( + "htmx.config.allowScriptTags === false && htmx.config.allowEval === false" + ) + + def nav(path): + if page.viewport_size["width"] < 760: + page.get_by_role("button", name="Открыть меню", exact=True).click() + with page.expect_response( + lambda r: r.request.method == "GET" and r.url == origin + path + ) as response: + page.locator(f'#sidebar a[href="{path}"]').click() + assert response.value.request.headers.get("hx-boosted") == "true" + page.wait_for_url(origin + path) + assert page.evaluate("window.__publicationNavigationDocument") == "preserved" + + try: + page.goto(origin + "/admin/login") + page.locator("[name=login]").fill("admin") + page.locator("[name=password]").fill(PASSWORD) + page.get_by_role("button", name="Войти", exact=True).click() + page.wait_for_url(origin + "/admin/") + for width in (1440, 390): + page.set_viewport_size({"width": width, "height": 960}) + for source in ( + "/admin/pages", + "/admin/content/services/bots", + "/admin/pages/index", + ): + page.goto(origin + source) + page.evaluate("window.__publicationNavigationDocument='preserved'") + nav("/admin/publish") + ready() + report["checks"].append(f"htmx_from_{source}_{width}") + nav("/admin/pages") + nav("/admin/publish") + ready() + page.go_back() + page.wait_for_url(origin + "/admin/pages") + page.go_forward() + page.wait_for_url(origin + "/admin/publish") + ready() + assert ( + page.evaluate("window.__publicationNavigationDocument") == "preserved" + ) + report["checks"].append(f"repeat_and_back_forward_{source}_{width}") + page.reload() + ready() + report["checks"].append(f"direct_reload_{width}") + page.screenshot(path=str(out / f"publication-navigation-{width}.png")) + assert not report["page_errors"], report["page_errors"] + assert not report["console_errors"], report["console_errors"] + assert not report["native_dialogs"], report["native_dialogs"] + assert not (work / "dist/current").exists() + finally: + report["last_url"] = page.url + report["boot_nodes"] = page.locator("[data-publication-boot]").count() + (out / "report.json").write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n" + ) + print(json.dumps(report, ensure_ascii=False), flush=True) + browser.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/qa_shell_001.py b/scripts/qa_shell_001.py index d452780..5bec94a 100644 --- a/scripts/qa_shell_001.py +++ b/scripts/qa_shell_001.py @@ -37,7 +37,7 @@ def main(): report = {"geometry": [], "flows": [], "errors": []} with tempfile.TemporaryDirectory(prefix="cms-shell-") as temp: work = Path(temp) - shutil.copytree(ROOT / "examples/studio-site", work / "site", ignore=shutil.ignore_patterns(".engine")) + shutil.copytree(ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine")) env = { "SITE_ROOT": str(work / "site"), "SITE_DIST": str(work / "dist"), "SITE_STATE_DIR": str(work / "state"), "SITE_ADMIN_LOGIN": "admin", @@ -46,7 +46,7 @@ def main(): "SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "", "SITE_PUBLIC_HOST": "", } with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw: - browser = pw.chromium.launch(headless=True, args=["--no-sandbox"]) + browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]) page = browser.new_page(viewport={"width": 1440, "height": 960}, reduced_motion="reduce") page.on("pageerror", lambda error: report["errors"].append(str(error))) page.on("console", lambda message: report["errors"].append(message.text) if message.type == "error" else None) @@ -121,7 +121,7 @@ def main(): assert page.locator("[data-command-empty]").is_visible() page.locator("#cmd-input").fill("Контент") page.locator("[data-command-result]:visible").click() - page.wait_for_url(origin + "/admin/content") + page.wait_for_url(origin + "/admin/content/**") assert page.locator(".nav-item.active").inner_text() == "Контент" report["flows"].append("Ctrl+K, real pages/sections, empty search, htmx navigation") page.locator('[data-action="profile"]').click() @@ -146,8 +146,11 @@ def main(): assert page.locator(".sidebar.open").count() == 0 page.set_viewport_size({"width": 1440, "height": 960}) page.goto(origin + "/admin/publish") - page.get_by_role("button", name="Опубликовать текущий черновик сайта", exact=True).click() - page.locator("#confirm-dialog button[value=confirm]").click() + page.locator('[data-pub-action=candidate]').first.click() + page.locator('[data-publication-root][aria-busy=false]').wait_for() + page.locator('[data-pub-action=publish]').click() + page.locator('#release-comment').fill('Shell QA release') + page.locator('[data-pub-action=confirm-publish]').click() page.locator(".live-pip:not(.no-release) .mono").wait_for() page.goto(origin + "/admin/pages") assert page.locator(".live-pip .mono").inner_text().strip() diff --git a/scripts/sync_content_design.py b/scripts/sync_content_design.py new file mode 100644 index 0000000..95c683a --- /dev/null +++ b/scripts/sync_content_design.py @@ -0,0 +1,48 @@ +"""Transfer original Content CSS and SVGs; only isolate selectors from the shell.""" + +import json +import re +import sys +from pathlib import Path + +from css_scope import scope_css + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + def emit(path, content): + if "--check" in sys.argv: + if not path.exists() or path.read_text() != content: + raise SystemExit(f"Content design out of date: {path}") + else: + path.write_text(content) + + target = ROOT / "src/site_engine/web/admin" + css = ( + (ROOT / "design/assets/builder.css").read_text() + + "\n" + + (ROOT / "design/assets/content-editor.css").read_text() + ) + css = re.sub(r"(?{%- endmacro %}\n', + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/sync_publication_design.py b/scripts/sync_publication_design.py new file mode 100644 index 0000000..00b3098 --- /dev/null +++ b/scripts/sync_publication_design.py @@ -0,0 +1,41 @@ +"""Reproduce the original publication CSS/SVG, scoped to the accepted runtime shell.""" + +import json +import re +import sys +from pathlib import Path + +from css_scope import scope_css + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + target = ROOT / "src/site_engine/web/admin" + css = (ROOT / "design/assets/publication.css").read_text() + css = re.sub(r"(?{%- endmacro %}\n', + target / "static/publication-icons.json": json.dumps(icons, ensure_ascii=False) + "\n", + } + for path, content in output.items(): + if "--check" in sys.argv: + if not path.exists() or path.read_text() != content: + raise SystemExit(f"Publication design out of date: {path}") + else: + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_package_001.py b/scripts/verify_package_001.py index e447dd0..2470931 100644 --- a/scripts/verify_package_001.py +++ b/scripts/verify_package_001.py @@ -97,7 +97,7 @@ with TestClient(app) as client: assert response.status_code==200 response=client.get('/admin/pages/index') assert response.status_code==200 and 'document-editor' in response.text - for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js'): + for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js','content-editor.css','content-adapter.css','content-editor.js','favicon.svg','publication.css','publication-adapter.css','publication.js','publication-icons.json'): assert client.get('/admin/static/'+name).status_code==200,name assert 'pages-screen' in client.get('/admin/pages').text cookie=client.cookies.get('se_session') @@ -139,8 +139,31 @@ with TestClient(app) as client: result=preview.get(result.json()['url']) assert result.status_code==200 and 'sample-site' in result.text,result.text assert '--color-primary: #a48bfa' in result.text + response=client.get('/admin/content/services/bots') + assert response.status_code==200 and 'entry-workspace' in response.text,response.text + from site_engine.services.entries import EntryService + entry=EntryService(Path(os.environ['SITE_ROOT']),collection='services').get('bots') + result=client.post('/admin/editor/content/services/bots/update',data={'csrf':csrf,'payload':json.dumps({'source':entry.source,'etag':entry.etag,'revision':30,'preview_view':'card'})},headers={'Origin':'http://testserver','HX-Request':'true','Accept':'application/json'}) + assert result.status_code==200 and 'f-entry_card' in result.json()['preview']['html'],result.text + assert 'data-content-tab' in result.json()['projection'] + assert 'data-publication-root' in client.get('/admin/publish').text + def publication(op, payload=None): + return client.post('/admin/publication/'+op,data={'csrf':csrf,'payload':json.dumps(payload or {})},headers={'Origin':'http://testserver','Accept':'application/json'}) + live=(Path(os.environ['SITE_DIST'])/'current').resolve().name + candidate=publication('build') + assert candidate.status_code==200,candidate.text + identity=candidate.json()['id'] + assert (Path(os.environ['SITE_DIST'])/'current').resolve().name==live + passive=publication('preview',{'id':identity,'route':'/'}) + assert passive.status_code==200,passive.text + with TestClient(create_preview_app()) as preview: + result=preview.get(passive.json()['url']) + assert result.status_code==200 and '0 -print('installed wheel: all theme presets, build, widths, static, templates, Theme Manager, API, background update, bridge, separate preview OK; design/ absent') +print('installed wheel: all theme presets, build, widths, static, templates, Theme Manager, Content Editor, Publication candidates/preview/activation, API, background update, bridge, separate preview OK; design/ absent') """ subprocess.run([sys.executable, "-c", program], cwd=work, env=env, check=True) diff --git a/specs/001-antirion-admin/content-backend.md b/specs/001-antirion-admin/content-backend.md new file mode 100644 index 0000000..a4d083c --- /dev/null +++ b/specs/001-antirion-admin/content-backend.md @@ -0,0 +1,17 @@ +# Этап 4: оригинальный Content Editor и серверный контракт + +Источник композиции, размеров, CSS, SVG и сценариев: `design/content-antirion.html`, `design/assets/content-editor.{css,js}` и общие токены `design/assets/builder.css`. Сохраняется ранее принятый общий shell. Перенос не меняет файлы дизайна и контент сайта. + +Необходимые доработки бэкенда: + +1. Реальные коллекции и записи: enabled по feature requirements, количество и файловый статус, маршрут/display, схема, сравнение с текущим релизом. Новые manifest сохраняют `entry_sources` и `entry_routes`; старый релиз без хешей даёт неизвестный результат сравнения, а не ложное «без изменений». +2. Связи: типизированные ref/refs/link, вложенные группы и списки. Обратные зависимости: записи, композиция регионов страниц/display/Entry, fixed layout и SEO. Для запросов используется штатный Resolver с where/ids/order/limit/features и текущей редакцией записи; произвольные строки не считаются ссылками. Это зависимости структурированных данных; ссылки в Markdown, произвольном Jinja и пользовательском JS не индексируются. +3. `POST /collections/{collection}/entries/{id}/check`: проверка текущего source как кандидата к публикации; типы, обязательные поля, ссылки, assets и реальный рендер. Ничего не записывает. Проверка одной записи не заменяет проверку всего релиза. Неполный синтаксически корректный draft по-прежнему можно сохранить. +4. `POST …/duplicate` с source/etag/revision/id: CAS исходного файла и отсутствие целевого под одной SiteLock. Создаётся отдельный файл draft из текущей редакции, оригинал не меняется. `POST …/delete`: CAS, запрет удаления published до отдельного сохранения archived, история перед удалением и аудит. Ошибка аудита после записи/удаления сообщает совершённое действие и request_id. +5. Общий stateless `POST …/update` получает `preview_view: card|page`, `preview_version: workspace|live`. Workspace использует настоящий renderer и overlay; карточка — встроенный `entry_card`. Live полной страницы читает HTML и assets неизменяемого текущего релиза. Snapshot имеет прежние авторизацию/TTL/CSP и пассивный либо отдельный origin. Отдельной карточки в релизе нет: Live/Card показывает явное объяснение, а не данные workspace под видом live. + +Путь запросов остаётся Browser → HTML adapter → AdminApi → JSON FastAPI → сервисы. Парсинг схем и YAML выполняет Python; mock codec и mock storage исходного прототипа не переносятся. Изменения полей остаются в памяти вкладки, обслуживаются общей очередью 003; Save пишет файл с CAS, публикация выполняется отдельно. Создание и дублирование создают настоящий draft-файл. + +Slug — идентификатор файла/маршрута: показывается read-only. Переименование потребует отдельной операции с обновлением ссылок; скрытого rename при изменении поля нет. Схема коллекции доступна только для чтения и показывает серверную модель настоящего манифеста. Подписи полей берутся из `FieldDef.label`, при отсутствии — ключ. + +В интерфейс не добавляются демонстрационные роли, +30 Demo, симуляция 409, mock Live, sessionStorage или localStorage с документами. Диалоги сохраняют композицию stage4-dialog из дизайна; системные alert/confirm/prompt/beforeunload запрещены. diff --git a/specs/001-antirion-admin/design-transfer.md b/specs/001-antirion-admin/design-transfer.md index c9df89b..5a25532 100644 --- a/specs/001-antirion-admin/design-transfer.md +++ b/specs/001-antirion-admin/design-transfer.md @@ -11,10 +11,10 @@ | 1. Общий каркас | Sidebar, группы и пункты навигации, логотип, верхняя панель, быстрый поиск, профиль, темы, сворачивание, мобильное меню | `antirion-rework.html`, `assets/antirion-rework.css`, `assets/antirion-rework.js`: sidebar/topbar/command | Принят пользователем; разрешён этап 2 | | 2. Обзор и страницы | Композиция обзора, счётчики, поиск/фильтры, выбор строки, правый инспектор, создание страницы в модальном окне | Те же исходники: overview/pages/rows/inspector/new | Принят пользователем; разрешён этап 3 | | 3. Редактор страниц | Заголовок с действиями, дерево слева, превью в центре, инспектор справа, Конструктор/Эксперт, каталог блоков, поля и переключения | `builder-antirion.html`, `assets/builder.css`, `assets/builder.js` | Подготовлен к проверке пользователя | -| 4. Контент и записи | Выбор коллекции, список записей, редактор по схеме, превью, вкладки и режим Эксперт | `content-antirion.html`, `assets/content-editor.css`, `assets/content-editor.js` | Ожидает этап 3 | -| 5. Публикация и завершение | Композиция публикации/истории/отката, рабочие состояния и подтверждения; итоговая сверка всех экранов, входа, ошибок и пустых состояний | `publication-antirion.html`, `assets/publication.css`, `assets/publication.js` | Ожидает этап 4 | +| 4. Контент и записи | Выбор коллекции, список записей, редактор по схеме, превью, вкладки и режим Эксперт | `content-antirion.html`, `assets/content-editor.css`, `assets/content-editor.js` | Разрешён переход к этапу 5 пользователем | +| 5. Публикация и завершение | Композиция публикации/истории/отката, рабочие состояния и подтверждения; итоговая сверка всех экранов, входа, ошибок и пустых состояний | `publication-antirion.html`, `assets/publication.css`, `assets/publication.js` | Реализован; подготовлен к проверке пользователя | -Возможности следующей очереди (candidate/diff, RBAC, медиа и прочие) требуют отдельного действующего контракта; их ограничения фиксируются при переносе соответствующего экрана. +Для этапа 5 реализован настоящий candidate/diff и защищённое переключение Live; уточнение объёма — [publication-backend.md](publication-backend.md). RBAC, медиа, durable jobs, идемпотентные операции и интеграция с агентскими changeset остаются следующей очередью. ## Этап 1 — принят пользователем @@ -46,7 +46,7 @@ python scripts/verify_package_001.py Дополнительная регрессия: 239 тестов OK; прежний браузерный сценарий — 8 экранов/60 проверок ширины; установленный wheel без `design/` работает. Эти результаты подтверждают совместимость, но не закрывают визуальную приёмку остальных экранов. -Статус: этапы 1–2 приняты пользователем. Этап 3 подготовлен к проверке; этапы 4–5 ожидают её результата. +Текущий статус на 2026-11-17: пользователь разрешил этап 5 после Content; Publication реализован и подготовлен к его проверке. Общая пользовательская визуальная приёмка не закрывается автоматически. ## Этап 2 — принят пользователем @@ -142,3 +142,23 @@ Chromium открывает оригинал отдельно от настоя ### Выбор секций и подтверждения `scripts/qa_selection_001.py` прошёл в Chromium 158 и Firefox 142; проверяет два режима превью — административный origin без scripts и bridge отдельного origin: дерево → выделение/прокрутка/инспектор, превью → дерево/инспектор, фиксированные блоки только для чтения, ноль POST при чистом выборе, неизменный iframe/снимок/source, отсутствие записи файла и публикации. Повторные правки после локального выбора передают текущий source. Проверяются отмена перехода через селектор/ссылку/выход, подтверждённый переход/выход из Entry, Escape, перезагрузка без системного диалога. Любой нативный диалог проваливает прогон. Артефакты: `/tmp/site-engine-selection-001/` и `/tmp/site-engine-selection-firefox-001/`. + +## Этап 4 — Контент и записи + +Перенесён оригинальный `content-antirion.html` / `assets/content-editor.{css,js}`: четыре панели, заголовок и действия, коллекции/счётчики/OFF, поиск и фильтры записей, форма по схеме, вкладки «Связи», «Где используется», «Схема», режим Expert, оба варианта preview и диалоги stage4-dialog. Сохранены исходные CSS/иконки/breakpoints, принятый shell и его тёмные токены; геометрия viewport адаптирована к фактической высоте shell. Данные/подписи полей берутся из настоящей схемы. + +Обычное изменение свойства использует очередь 003: один update, локальный ввод и вкладки без ожидания ответа, сохранение поля/caret/iframe, обновление существующего preview. Отдельный Save пишет файл; duplicate создаёт draft-копию текущей редакции, delete требует сохранённого archived для published. Создание сразу создаёт draft-файл. Восстанавливаемой autosave-сессии нет. + +Backend и границы: [content-backend.md](content-backend.md). Результаты и воспроизводимые команды: [verification-content.md](verification-content.md). Live/Page использует HTML/assets реального релиза; Live/Card имеет явное объяснение отсутствующего снимка карточки. Slug read-only, схема read-only; roles/+30 Demo/409 Demo/mock storage не переносятся как работающие функции. + +После реализации Content пользователь разрешил переход к этапу 5; его результаты приведены ниже. + +## Этап 5 — Publication (2026-11-17) + +- Перенесены исходные заголовок, livebar, pipeline, таблица/инспектор и вкладки Changes/Checks/Candidate/History/Activity. CSS/SVG воспроизводятся `scripts/sync_publication_design.py --check`, HTML/JS используют реальные данные. Reset/tokens ограничены экраном; тёмная палитра соответствует принятому shell. +- Проверка и сборка не переключают Live. Кандидат фиксирует входные данные и output; preview и diff показывают этот снимок. Публикация с комментарием проверяет source/renderer/base/current и переключает готовый build без повторного рендера. +- История и журнал настоящие; перед откатом показаны реальные изменяемые публичные файлы. Отмена ничего не пишет; подтверждение не меняет workspace. Старые релизы без частных исходников показывают неизвестное сравнение. +- 409/422/500/сеть/истёкшая сессия видимы. Ошибки после фактического переключения отдельно сообщают committed_build, состояние перечитывается, автоматического повтора POST нет. Нативные alert/confirm/prompt не используются. +- Доработки и ограничения — [publication-backend.md](publication-backend.md); полные результаты — [verification-publication.md](verification-publication.md): 397 тестов полной регрессии, затем 16 целевых; 12 визуальных наборов и 25 групп Chromium на двух конфигурациях preview, общие 8 экранов/60 ширин, проверка отказов и установленного wheel. + +Этап передаётся пользователю для визуальной проверки. Docker-образ требует пересборки для обновления Python/templates/static. Переход к следующей самостоятельной работе не считается разрешённым этой технической приёмкой. diff --git a/specs/001-antirion-admin/openapi.json b/specs/001-antirion-admin/openapi.json index d7ebec3..4fac2a4 100644 --- a/specs/001-antirion-admin/openapi.json +++ b/specs/001-antirion-admin/openapi.json @@ -195,6 +195,11 @@ "CollectionRow": { "additionalProperties": false, "properties": { + "enabled": { + "default": true, + "title": "Enabled", + "type": "boolean" + }, "id": { "title": "Id", "type": "string" @@ -306,6 +311,24 @@ "title": "Operations", "type": "array" }, + "preview_version": { + "default": "workspace", + "enum": [ + "workspace", + "live" + ], + "title": "Preview Version", + "type": "string" + }, + "preview_view": { + "default": "page", + "enum": [ + "page", + "card" + ], + "title": "Preview View", + "type": "string" + }, "revision": { "default": 0, "minimum": 0.0, @@ -364,12 +387,50 @@ "collection": { "$ref": "#/components/schemas/CollectionRow" }, + "collections": { + "items": { + "$ref": "#/components/schemas/CollectionRow" + }, + "title": "Collections", + "type": "array" + }, + "comparison_available": { + "default": false, + "title": "Comparison Available", + "type": "boolean" + }, + "display": { + "default": "", + "title": "Display", + "type": "string" + }, "entries": { "items": { "$ref": "#/components/schemas/EntryRow" }, "title": "Entries", "type": "array" + }, + "kind": { + "default": "content", + "title": "Kind", + "type": "string" + }, + "live_build": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Live Build" + }, + "schema_text": { + "default": "", + "title": "Schema Text", + "type": "string" } }, "required": [ @@ -379,6 +440,88 @@ "title": "Entries", "type": "object" }, + "EntryCheck": { + "additionalProperties": false, + "properties": { + "issues": { + "items": { + "$ref": "#/components/schemas/IssueDTO" + }, + "title": "Issues", + "type": "array" + }, + "revision": { + "title": "Revision", + "type": "integer" + } + }, + "required": [ + "revision", + "issues" + ], + "title": "EntryCheck", + "type": "object" + }, + "EntryCopy": { + "additionalProperties": false, + "properties": { + "etag": { + "maxLength": 80, + "minLength": 1, + "title": "Etag", + "type": "string" + }, + "id": { + "maxLength": 200, + "pattern": "^[a-z0-9][a-z0-9_-]*$", + "title": "Id", + "type": "string" + }, + "revision": { + "default": 0, + "minimum": 0.0, + "title": "Revision", + "type": "integer" + }, + "source": { + "maxLength": 524288, + "title": "Source", + "type": "string" + } + }, + "required": [ + "source", + "etag", + "id" + ], + "title": "EntryCopy", + "type": "object" + }, + "EntryDeleted": { + "additionalProperties": false, + "properties": { + "collection": { + "title": "Collection", + "type": "string" + }, + "deleted": { + "const": true, + "title": "Deleted", + "type": "boolean" + }, + "id": { + "title": "Id", + "type": "string" + } + }, + "required": [ + "deleted", + "id", + "collection" + ], + "title": "EntryDeleted", + "type": "object" + }, "EntryFields": { "additionalProperties": false, "properties": { @@ -436,6 +579,17 @@ "EntryRow": { "additionalProperties": false, "properties": { + "changed": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Changed" + }, "file": { "title": "File", "type": "string" @@ -455,6 +609,11 @@ "title": { "title": "Title", "type": "string" + }, + "url": { + "default": "", + "title": "Url", + "type": "string" } }, "required": [ @@ -509,6 +668,17 @@ ], "title": "Committed" }, + "committed_build": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Committed Build" + }, "current": { "anyOf": [ { @@ -523,6 +693,17 @@ ], "title": "Current" }, + "deleted": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Deleted" + }, "issues": { "items": { "$ref": "#/components/schemas/IssueDTO" @@ -899,6 +1080,201 @@ "title": "Preview", "type": "object" }, + "PublicationChange": { + "additionalProperties": false, + "properties": { + "after": { + "anyOf": [ + { + "$ref": "#/components/schemas/PublicationDocument" + }, + { + "type": "null" + } + ] + }, + "before": { + "anyOf": [ + { + "$ref": "#/components/schemas/PublicationDocument" + }, + { + "type": "null" + } + ] + }, + "kind": { + "enum": [ + "new", + "modified", + "deleted", + "unknown" + ], + "title": "Kind", + "type": "string" + }, + "path": { + "title": "Path", + "type": "string" + }, + "status": { + "title": "Status", + "type": "string" + }, + "title": { + "title": "Title", + "type": "string" + }, + "type": { + "title": "Type", + "type": "string" + } + }, + "required": [ + "path", + "title", + "type", + "status", + "kind" + ], + "title": "PublicationChange", + "type": "object" + }, + "PublicationDocument": { + "additionalProperties": false, + "properties": { + "hash": { + "title": "Hash", + "type": "string" + }, + "size": { + "title": "Size", + "type": "integer" + }, + "source": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source" + }, + "status": { + "title": "Status", + "type": "string" + }, + "title": { + "title": "Title", + "type": "string" + }, + "type": { + "title": "Type", + "type": "string" + } + }, + "required": [ + "hash", + "size", + "title", + "status", + "type" + ], + "title": "PublicationDocument", + "type": "object" + }, + "PublicationState": { + "additionalProperties": false, + "properties": { + "activity": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "title": "Activity", + "type": "array" + }, + "builds": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "title": "Builds", + "type": "array" + }, + "candidate": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Candidate" + }, + "changes": { + "items": { + "$ref": "#/components/schemas/PublicationChange" + }, + "title": "Changes", + "type": "array" + }, + "comparison_available": { + "title": "Comparison Available", + "type": "boolean" + }, + "current": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Current" + }, + "history": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "title": "History", + "type": "array" + }, + "source_hash": { + "title": "Source Hash", + "type": "string" + }, + "validation": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Validation" + } + }, + "required": [ + "current", + "source_hash", + "comparison_available", + "changes", + "history", + "builds", + "activity" + ], + "title": "PublicationState", + "type": "object" + }, "Release": { "additionalProperties": false, "properties": { @@ -918,6 +1294,60 @@ "title": "Release", "type": "object" }, + "ReleaseActivate": { + "additionalProperties": false, + "properties": { + "comment": { + "default": "", + "maxLength": 150, + "title": "Comment", + "type": "string" + }, + "expected_live": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Expected Live" + }, + "id": { + "pattern": "^\\d{8}T\\d{6}-[0-9a-f]{8}$", + "title": "Id", + "type": "string" + } + }, + "required": [ + "id", + "expected_live" + ], + "title": "ReleaseActivate", + "type": "object" + }, + "ReleasePreview": { + "additionalProperties": false, + "properties": { + "id": { + "pattern": "^\\d{8}T\\d{6}-[0-9a-f]{8}$", + "title": "Id", + "type": "string" + }, + "route": { + "default": "/", + "maxLength": 2000, + "title": "Route", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "ReleasePreview", + "type": "object" + }, "Releases": { "additionalProperties": false, "properties": { @@ -1918,6 +2348,435 @@ "summary": "Entry Create" } }, + "/admin/api/v1/collections/{collection}/entries/{identity}/check": { + "post": { + "operationId": "entry_check_admin_api_v1_collections__collection__entries__identity__check_post", + "parameters": [ + { + "in": "path", + "name": "collection", + "required": true, + "schema": { + "title": "Collection", + "type": "string" + } + }, + { + "in": "path", + "name": "identity", + "required": true, + "schema": { + "title": "Identity", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Buffer" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EntryCheck" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Entry Check" + } + }, + "/admin/api/v1/collections/{collection}/entries/{identity}/delete": { + "post": { + "operationId": "entry_delete_admin_api_v1_collections__collection__entries__identity__delete_post", + "parameters": [ + { + "in": "path", + "name": "collection", + "required": true, + "schema": { + "title": "Collection", + "type": "string" + } + }, + { + "in": "path", + "name": "identity", + "required": true, + "schema": { + "title": "Identity", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Buffer" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EntryDeleted" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Entry Delete" + } + }, + "/admin/api/v1/collections/{collection}/entries/{identity}/duplicate": { + "post": { + "operationId": "entry_duplicate_admin_api_v1_collections__collection__entries__identity__duplicate_post", + "parameters": [ + { + "in": "path", + "name": "collection", + "required": true, + "schema": { + "title": "Collection", + "type": "string" + } + }, + { + "in": "path", + "name": "identity", + "required": true, + "schema": { + "title": "Identity", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EntryCopy" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Snapshot" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Entry Duplicate" + } + }, "/admin/api/v1/collections/{collection}/entries/{identity}/preview": { "post": { "operationId": "entry_preview_admin_api_v1_collections__collection__entries__identity__preview_post", @@ -6021,6 +6880,1183 @@ "summary": "Preview Html" } }, + "/admin/api/v1/publication": { + "get": { + "operationId": "publication_state_admin_api_v1_publication_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicationState" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication State" + } + }, + "/admin/api/v1/publication/activate": { + "post": { + "operationId": "publication_activate_admin_api_v1_publication_activate_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReleaseActivate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Activate" + } + }, + "/admin/api/v1/publication/build": { + "post": { + "operationId": "publication_build_admin_api_v1_publication_build_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Build" + } + }, + "/admin/api/v1/publication/candidate-diff": { + "get": { + "operationId": "publication_candidate_diff_admin_api_v1_publication_candidate_diff_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Candidate Diff" + } + }, + "/admin/api/v1/publication/compare": { + "get": { + "operationId": "publication_compare_admin_api_v1_publication_compare_get", + "parameters": [ + { + "in": "query", + "name": "path", + "required": true, + "schema": { + "title": "Path", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Compare" + } + }, + "/admin/api/v1/publication/document-history": { + "get": { + "operationId": "publication_document_history_admin_api_v1_publication_document_history_get", + "parameters": [ + { + "in": "query", + "name": "path", + "required": true, + "schema": { + "title": "Path", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Document History" + } + }, + "/admin/api/v1/publication/preview": { + "post": { + "operationId": "publication_preview_admin_api_v1_publication_preview_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReleasePreview" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Preview" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Preview" + } + }, + "/admin/api/v1/publication/release": { + "get": { + "operationId": "publication_release_admin_api_v1_publication_release_get", + "parameters": [ + { + "in": "query", + "name": "id", + "required": true, + "schema": { + "title": "Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Release" + } + }, + "/admin/api/v1/publication/rollback": { + "post": { + "operationId": "publication_rollback_admin_api_v1_publication_rollback_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReleaseActivate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Rollback" + } + }, + "/admin/api/v1/publication/validate": { + "post": { + "operationId": "publication_validate_admin_api_v1_publication_validate_post", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Conflict" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "InternalUiSession": [] + } + ], + "summary": "Publication Validate" + } + }, "/admin/api/v1/publish": { "post": { "operationId": "publish_site_admin_api_v1_publish_post", diff --git a/specs/001-antirion-admin/plan.md b/specs/001-antirion-admin/plan.md index d02b0c0..718afd2 100644 --- a/specs/001-antirion-admin/plan.md +++ b/specs/001-antirion-admin/plan.md @@ -121,7 +121,7 @@ UI-роутеры, использующие AsyncClient, выполняются | Релизы и текущая публикация | `GET /admin/api/v1/releases` | | Текущие publish/rollback | `POST /admin/api/v1/publish`, `POST /admin/api/v1/rollback` | -Фигурная группа действий обозначает отдельный явный маршрут для каждого действия. Вложенные ID Page с `/` поддерживаются и проверяются по Registry; маршрут не принимает произвольный файловый путь. Списки принимают те же q/status/layout, что UI. Create возвращает 201 и DocumentSnapshot; чтение/transform/validate/save/preview — 200 с соответствующим DTO. Publish/rollback возвращают фактический результат действующих сервисов без нового candidate pipeline. +Фигурная группа действий обозначает отдельный явный маршрут для каждого действия. Вложенные ID Page с `/` поддерживаются и проверяются по Registry; маршрут не принимает произвольный файловый путь. Списки принимают те же q/status/layout, что UI. Create возвращает 201 и DocumentSnapshot; чтение/transform/validate/save/preview — 200 с соответствующим DTO. Старые Publish/rollback сохраняют прежний контракт действующих сервисов. Новый candidate workflow повторного этапа 5 описан в publication-backend.md. DTO запросов буфера: `source`, `etag`, `revision`; transform дополнительно содержит дискриминированное типизированное `action`. `revision` — неотрицательное целое, возвращаемое без изменения, `etag` — прежний непрозрачный маркер версии. Схемы запрещают неизвестные служебные поля; пользовательские props проверяет действующая схема фрагмента/коллекции. В JSON не передаются csrf, Principal или произвольный путь записи. @@ -265,10 +265,18 @@ HTTP/browser-проверки добавляются как воспроизво | Номер | Направление | Доработка и результат приёмки | |---|---|---| -| 002 | Релизы | Разделить build/publish; immutable candidate, manifest/hashes, diff, expected_live под общей блокировкой, безопасные повторы; сбой не меняет live, rollback не затирает workspace | +| — | Релизы — расширение | Надёжные фоновые jobs, реестр безопасных повторов, retention/recovery и связь с reviewed changeset. Build/publish, immutable candidate, hashes/diff и expected_live уже реализованы повторным этапом 5 в 001 | | 003 | Медиа, структура, настройки | Безопасная загрузка, файловые metadata, where-used, changeset с recovery до rename, меню/redirect/site/data/theme; перенос каталога не теряет метаданные | | 004 | Доступы и журнал | Пользователи, разрешения, миграции SQLite, сессии и audit UI; отказ прав проверяется сервисом, а не видимостью кнопки | | 005 | Заявки и outbox | Версия формы, submission+outbox одной транзакцией, Telegram/retry, PII grants; сбой доставки не теряет заявку и rollback сохраняет совместимость | | 006 | MCP | Те же сервисы и ошибки, узкие scopes, TTL/revoke, draft-only; отсутствие publish grant исключает публикацию | Это очередность отдельных работ. Их контракты и задачи не считаются реализованными или полностью специфицированными пакетом 001. + +## Уточнение плана: повторный перенос Content (2026-11-17) + +Этап 4 опирается на исходный content-antirion и уже работающую очередь 003. Дополнение сервера: коллекции/зависимости, check, CAS duplicate/delete, entry manifest hashes/routes и настоящий Live/Page. Подробности и ограничения — [content-backend.md](content-backend.md), техническая приёмка — [verification-content.md](verification-content.md). После реализации требуется проверка пользователя до перехода к этапу 5. Новая схема хранения, Node frontend и серверное autosave для этого этапа не требуются. + +## Уточнение плана: Publication (2026-11-17) + +Пользователь разрешил этап 5. Для оригинального publication-antirion потребовалось настоящее разделение build/activate и частное происхождение релиза. Это уточнение прежнего отнесения всего candidate/diff к следующей очереди. Реализация: PublicationService под SiteLock; build_site(activate=False); отдельные API/HTML endpoints; source/render/output hash и expected_live; пассивный snapshot релиза; исходные диалоги и видимые ошибки. Старые CLI/API/обычные формы совместимы. Контракт — [publication-backend.md](publication-backend.md), приёмка — [verification-publication.md](verification-publication.md). Более широкий workflow релизов/агентских changeset не входит в этап. diff --git a/specs/001-antirion-admin/publication-backend.md b/specs/001-antirion-admin/publication-backend.md new file mode 100644 index 0000000..d7e1f07 --- /dev/null +++ b/specs/001-antirion-admin/publication-backend.md @@ -0,0 +1,70 @@ +# Этап 5: Publication и серверный контракт + +Дата: 2026-11-17. Источники — `design/publication-antirion.html`, `design/assets/publication.css` и `publication.js`. Исходная композиция, таблица, инспектор, пять вкладок, карточки Workspace/Candidate/Live и диалоги перенесены в принятый shell. Mock-хранилище, выдуманные роли, симуляция сборок и ремонт демонстрационных данных исключены. Проверки — [verification-publication.md](verification-publication.md). + +## Сценарий + +1. Сохранить необходимые документы в редакторе. Несохранённые правки других вкладок не участвуют в сборке. +2. «Проверить» выполняет настоящие workspace/release-проверки. Исходники и Live не меняются; результат помечается устаревшим при изменении входных файлов или renderer. +3. «Собрать кандидата» строго проверяет и рендерит сайт в неизменяемый каталог релиза, сохраняя текущий Live. Отдельный предварительный запуск «Проверить» не обязателен: сборка сама выполняет строгую проверку. +4. Во вкладке «Кандидат» доступны настоящий снимок страницы, сравнение зафиксированных исходников с базовым Live и журнал сборок. Просмотр не пересобирает сайт. +5. «Опубликовать» открывает исходный диалог с комментарием. Подтверждение переключает `current` на выбранный снимок без повторного рендера. Комментарий обязателен, до 150 символов. +6. «История» показывает существующие каталоги релизов. Перед откатом доступны реальные изменённые публичные файлы, маршруты/формы и подтверждение. Откат переключает Live, сохраняя workspace. + +Поиск, фильтры, выбор документа и вкладки работают локально. Сетевые операции выполняются через fetch в фоне; переключение вкладок остаётся доступным, повторные изменяющие действия блокируются на время запроса. Сборка на сервере синхронная: долговечной очереди заданий и отмены задачи нет. + +## Один контракт FastAPI + +Browser → `/admin/publication/*` (cookie, Origin, CSRF) → `AdminApi/httpx.ASGITransport` → `/admin/api/v1/publication*` → `PublicationService`. Браузер не получает внутренних credentials. Начальные данные передаются в скрытом textarea (`tojson`, чтение `.value`), который сохраняется при htmx swap с `allowScriptTags:false`; script-элементы для хранения этих данных не используются. Права и авторство берутся из проверенной сессии; отдельные API keys/scopes и RBAC пока не реализованы. + +| JSON API относительно `/admin/api/v1` | Назначение | +|---|---| +| `GET /publication` | Реальное состояние, изменения, проверки, кандидат, история, сборки и журнал | +| `POST /publication/validate` | Проверить workspace/release без записи контента | +| `POST /publication/build` | Собрать кандидат без активации | +| `GET /publication/candidate-diff` | Сравнить неизменяемый кандидат с его базовым релизом | +| `GET /publication/compare?path=…` | Сравнить сохранённый файл workspace с частным снимком Live | +| `GET /publication/document-history?path=…` | Существующие версии `.engine/history`, максимум 20; восстановления здесь нет | +| `GET /publication/release?id=…` | Сравнить публичные файлы выбранного релиза и текущего Live перед откатом | +| `POST /publication/preview` | `{id, route}` → защищённый пассивный снимок настоящего релиза | +| `POST /publication/activate` | `{id, expected_live, comment}` → переключение проверенного кандидата | +| `POST /publication/rollback` | `{id, expected_live, comment}` → переключение существующего исторического релиза | + +`expected_live` обязателен; до первой публикации передаётся `null`. HTML adapter читает состояние по `/admin/publication/state`; остальные названия операций совпадают. POST принимает FormData `csrf` и JSON-строку `payload`; ответ — JSON. Читающие операции — GET. Экран открыт по `/admin/publish`; без JavaScript доступна ссылка на обычную форму `/admin/publish/legacy`. Старые POST `/admin/publish`, API `/publish`, `/rollback` и CLI сохраняют прежний сценарий сборки с публикацией. + +## Разделение состояния и файлов + +`PublicationService` не редактирует файлы сайта. Изменения документов остаются ответственностью `ContentService` с CAS/history/audit. Проверки, сборка и переключение выполняются под общим `SiteLock`; в `build_site` добавлен параметр `activate=False`, обычное значение остаётся `True`. Внешние писатели должны соблюдать тот же lock. + +Служебные данные находятся только в `SITE_STATE_DIR/publication/`: + +- `candidate.json`: последний кандидат, базовый Live, хеш входных файлов и renderer, hash публичного output, время/автор/маршруты/диагностика; +- `releases/.json`: частный снимок входных файлов и происхождение релиза, комментарий/автор и факт активации; +- `validation.json`: реальный результат последней проверки и fingerprint его входных данных; +- `builds.json`: последние 40 результатов/ошибок сборки с ID запроса и кратким журналом стадий. + +Список исходников охватывает `pages`, `content`, `menus`, `assets`, `layouts`, `fragments`, `collections`, `display`, `data`, `forms`, root site/theme/redirect YAML и настроенный файл темы. Для UTF-8 текста известных расширений до 512 КиБ сохраняется исходник; для остальных файлов — hash/размер. Скрытые и служебные каталоги исключены, symlink в исходниках отклоняется. Полный hash workspace консервативно инвалидирует кандидата и при изменении иных файлов, включая README; fingerprint renderer учитывает ресурсы движка. + +Частные исходники, включая draft, не копируются в публичный `dist` или manifest. В релиз рендерятся только `published`. Статус `published` в файле не означает, что сохранённая редакция уже находится в Live. + +Старые/CLI-релизы без частного снимка продолжают работать: маршруты, preview и откат доступны, сравнение исходников/автор/комментарий неизвестны и обозначены явно. Ретроспективно придумывать их нельзя. После первой публикации новым workflow сравнение станет доступно для этого релиза. + +Кандидат сравнивается со своей зафиксированной базой, а не с текущими изменениями workspace. Последующие правки требуют новой сборки. Откат сравнивает реальные байты публичных файлов, включая manifest/assets. Никогда не публиковавшиеся кандидаты с известным происхождением через откат выбрать нельзя. + +## Конфликты, ошибки и безопасность + +Перед активацией проверяются `expected_live`, актуальность ID кандидата, hash исходников/renderer/базового Live и неизменность собранных файлов. Нарушение актуальности — HTTP 409 `release_conflict`; повреждённый снимок/валидация — 422; отсутствующий релиз — 404. Отказ строгого рендера сохраняет прежние Live и кандидат. + +JSON-ошибки: `error: {code, message, request_id, …}`. Непредвиденные ошибки и ошибки хранилища логируются со стеком и тем же ID. UI показывает сообщение, код и ID; 409 не закрывает подтверждение и не удаляет комментарий, автоматического повторного POST нет. Сеть и истёкшая сессия также видимы. + +Если ошибка записи служебных данных/аудита произошла после сборки либо переключения, API отвечает 500 `candidate_after_build` или `release_after_commit` с `committed_build`. Сообщение различает «снимок создан, Live не переключён» и «Live уже переключён». UI перечитывает состояние перед повтором; указатель `current` остаётся источником истины. Переключение symlink атомарно, но несколько служебных JSON и audit не являются общей crash-atomic транзакцией. + +Preview читает HTML/assets выбранного build ID, а не workspace, использует существующие TTL/epoch-токены и immutable snapshots. Скрипты удалены, `script-src 'none'` действует также на отдельном preview origin; iframe sandbox запрещает выполнение кода, формы и навигацию верхнего окна. Настроенный preview origin разрешён в frame-src всех страниц shell: CSP исходного документа сохраняется при htmx swap. Браузерные сценарии проверены с обеими конфигурациями origin. + +Журнал показывает настоящие release-события из хвоста аудита: до 80 записей в последних 256 КиБ. Старый аудит не удаляется. Пароли, токены и тела запросов в журнал не добавляются. + +## Границы этапа + +Новый workflow не удаляет кандидаты/релизы автоматически. Прежняя CLI-сборка сохраняет своё `keep=5`; если каталог уже удалён, API сообщает отсутствие, кандидат становится неактуальным. Политика retention и очистка частных снимков требуют отдельной работы. + +Не добавлены durable jobs, реестр идемпотентных операций, changeset/recovery нескольких документов, согласование агентских изменений, RBAC, приём заявок или MCP. Публичные формы по-прежнему отвечают HTTP 501. Исторический релиз без provenance нельзя проверить по исходным входным файлам; UI не выдаёт это за подтверждённое сравнение. diff --git a/specs/001-antirion-admin/runtime.md b/specs/001-antirion-admin/runtime.md index 35a2e65..e9d1186 100644 --- a/specs/001-antirion-admin/runtime.md +++ b/specs/001-antirion-admin/runtime.md @@ -2,7 +2,7 @@ ## Редактор и файлы -Начальный режим — Конструктор. «Применить к буферу» меняет исходник в памяти открытой вкладки; «Сохранить документ» записывает его целиком. Проверка и превью не создают историю контента и не меняют `current`. Публикация отдельно собирает и переключает релиз. В Entry редактируются поля коллекции и Markdown; layout/display доступны для чтения. +Начальный режим — Конструктор. «Применить к буферу» меняет исходник в памяти открытой вкладки; «Сохранить документ» записывает его целиком. Проверка и превью не создают историю контента и не меняют `current`. Новый экран публикации отдельно собирает кандидат, затем переключает его в Live; старые формы/CLI сохраняют build+publish. В Entry редактируются поля коллекции и Markdown; layout/display доступны для чтения. «Эксперт» хранит точный исходник. Переход между режимами без правок не пересобирает YAML; сохранение без изменений сохраняет в том числе CRLF и комментарии. Конструктор предупреждает о пересборке YAML перед первой операцией. До неё можно скачать исходник. Неприменимый YAML остаётся в «Эксперте», последнее корректное дерево доступно для просмотра. В localStorage попадают только тема и ширина навигации; HTML-кеш htmx отключён. @@ -131,10 +131,24 @@ python scripts/verify_package_001.py HTML-проекция содержит серверные шаблоны инспектора для всех блоков. Чистый выбор секции локально обновляет дерево/инспектор/выделение и прокрутку превью: без POST, изменения source/revision, нового снимка или замены iframe. Клик по секции превью выбирает её без дополнительной прокрутки. HTML `/select` остаётся для форм без JS и совместимости; он валидирует переданный исходник и строит инспектор, без записи файла. -Инспектор применяет поля к текущему source после паузы 650 мс; Save/выбор блока/смена режима сначала применяют ожидающую форму. Такой POST transform проверяет и преобразует переданный source, затем обновляет HTML-проекцию; это не сохранение черновика. До явного Save контент не записывается. «Текущая редакция» — память открытой вкладки, без серверного autosave/recovery; `status: draft` — статус файла, исключающий его из релиза. Ошибка формы сохраняет ввод и блокирует последующую запись до исправления. Переходы режимов сохраняют исходные байты. Структурные правки пересобирают YAML без отдельного подтверждения. Для исходника доступны сравнение/отмена, поиск, скачивание и явное форматирование через существующий metadata transform без записи. +После 003 инспектор отправляет один stateless POST update после паузы 200 мс; запрос объединяет изменения, проверку и preview. Save и смена режима дожидаются очереди. Чистый выбор секции остаётся локальным. Запрос не сохраняет черновик; контракт и очередь описаны в ../003-background-editor/runtime.md. До явного Save контент не записывается. «Текущая редакция» — память открытой вкладки, без серверного autosave/recovery; `status: draft` — статус файла, исключающий его из релиза. Ошибка формы сохраняет ввод и блокирует последующую запись до исправления. Переходы режимов сохраняют исходные байты. Структурные правки пересобирают YAML без отдельного подтверждения. Для исходника доступны сравнение/отмена, поиск, скачивание и явное форматирование через существующий metadata transform без записи. Нативные `alert`/`confirm`/`prompt` и `beforeunload`-диалоги не вызываются. Удаление/отмена и внутренний переход с несохранёнными правками подтверждаются в окнах интерфейса; Escape отменяет действие, фокус возвращается к инициатору. При перезагрузке или закрытии вкладки системного подтверждения нет; несохранённая редакция теряется. API `Add` принимает `props`, `BlockAction` — `type: duplicate`. Дублирование копирует поддерево, генерирует новые ID и снимает anchors копий. Ограничения регионов/слотов/циклов/типов остаются серверными. Schema передаёт manifest preview/defaults, choices и названия страниц; клиент не выдумывает значения. HTML-действия проходят прежний серверный API-клиент, credentials остаются на сервере. Переключатель Live в редакторе пока отключён с объяснением. Рабочее превью остаётся настоящим временным снимком, а успешная проверка структуры не заменяет проверку релиза. Сохранение не выполняет publish. Компонентная и сквозная проверка: `PYTHONPATH=src python scripts/qa_builder_001.py` и `PYTHONPATH=src python scripts/qa_editor_001.py`. + +## Content Editor после этапа 4 + +UI `/admin/content/{collection}/{id}` использует оригинальные Content templates/CSS и общую очередь 003. Состав backend-доработок и точные границы: [content-backend.md](content-backend.md); машиночитаемый контракт — [openapi.json](openapi.json). Начальный preview — настоящая карточка `entry_card`, переключатель Page рендерит display/layout. Live/Page читает immutable release; Live/Card показывает отсутствие такого артефакта. Старый manifest без Entry hashes/routes не выдаёт неизвестное сравнение за отсутствие изменений. + +Дополнительная приёмка: `PYTHONPATH=src python -m unittest discover -s tests -p test_content_editor.py -v`, `PYTHONPATH=src python scripts/qa_content_001.py`, `python scripts/sync_content_design.py --check`, `python scripts/verify_package_001.py --site examples/site-studio`. Браузерный сценарий использует временный Site Studio и два режима preview; исходный дизайн открывается отдельно. Отчёт — [verification-content.md](verification-content.md). + +## Publication — повторный этап 5 + +`GET /admin/publish` — оригинальный экран с реальными изменениями, проверками, кандидатом, историей и журналом. Проверить → собрать → preview/diff → опубликовать с комментарием; сборка и отмена подтверждения не переключают Live. При правке входных файлов/renderer/базового Live кандидат устаревает. Публикация требует `{id, expected_live, comment}`, откат — выбранный release и expected_live. Workspace при откате не меняется. + +Browser fetch → `/admin/publication/*` → серверный AdminApi → `/admin/api/v1/publication*` → PublicationService. Локальные вкладки/поиск/выбор не делают POST. Несохранённые данные других вкладок не участвуют в сборке; состояние релизов в localStorage не хранится. История/сравнение берутся из настоящих файлов и частного `SITE_STATE_DIR/publication/`, старые релизы без provenance имеют неизвестное сравнение. + +Все маршруты/ошибки/ограничения — [publication-backend.md](publication-backend.md), результаты — [verification-publication.md](verification-publication.md). На сервере нужен новый wheel/пересборка образа; `design/` для runtime не требуется. Дополнительных env или миграции БД нет, SITE_STATE_DIR должен оставаться приватным постоянным каталогом. diff --git a/specs/001-antirion-admin/spec.md b/specs/001-antirion-admin/spec.md index a72d4f1..9f422ce 100644 --- a/specs/001-antirion-admin/spec.md +++ b/specs/001-antirion-admin/spec.md @@ -81,7 +81,7 @@ JS прототипов описывает UX; его seed-данные, localSt Вход/выход, обзор, список и создание страниц, формы страницы и блока, операции с блоками, коллекции, список/создание/редактирование записей, существующее превью, публикация, история релизов, откат, ошибки и пустые состояния. -Рабочие маршруты и обычные формы сохраняются. Пока новые редакторы не готовы, пользователь сохраняет изменения существующими кнопками форм. На этом этапе оформление публикации соответствует текущей операции «собрать и опубликовать». +Рабочие маршруты и обычные формы сохраняются. Пока новые редакторы не готовы, пользователь сохраняет изменения существующими кнопками форм. При первом переносе оформление публикации соответствовало операции «собрать и опубликовать». Повторный этап 5 уточняет этот контракт: проверка → сборка неизменяемого кандидата → просмотр/diff → отдельное переключение Live с CAS; см. [publication-backend.md](publication-backend.md). ### Этап B — редакторы @@ -91,7 +91,7 @@ JS прототипов описывает UX; его seed-данные, localSt ### Следующая очередь -Отдельные кандидаты релиза, diff с live, медиабиблиотека и загрузки, changeset/rename, редактирование меню/настроек, пользователи/RBAC, заявки/outbox и MCP описываются следующими спецификациями. В 001 не добавляются Node-сборка, новая структура всего Python-пакета или миграция канонического контента в БД. +На повторном этапе 5 по разрешению пользователя в 001 включены реальные кандидаты релиза, diff с Live и проверка expected_live. Расширенный release workflow (durable jobs, безопасные повторы/реестр операций, retention и reviewed changeset), медиабиблиотека и загрузки, changeset/rename, редактирование меню/настроек, пользователи/RBAC, заявки/outbox и MCP остаются следующей очередью. В 001 не добавляются Node-сборка, новая структура всего Python-пакета или миграция канонического контента в БД. ### Контракт интерфейса @@ -185,7 +185,7 @@ API задаёт единый контракт операций и данных. | AC-05 | Две вкладки читают один ETag; первая сохраняет, вторая получает 409 с сохранённым вводом и текущей версией; после ручного объединения сохраняет с новым ETag. | | AC-06 | Превью выбирает нужный вложенный/fixed-блок, соблюдает правила прокрутки и отображает последнюю версию буфера, включая ассеты workspace. | | AC-07 | Неверный/истёкший/отозванный токен, чужой снимок, поддельные origin/source/сообщения и traversal отклоняются; приложение превью не открывает admin/login. | -| AC-08 | Успешная публикация переключает current; неудачная сохраняет live; откат сохраняет workspace. В UI отсутствует имитация ещё не реализованного кандидата. | +| AC-08 | Успешная публикация переключает current; неудачная сохраняет live; откат сохраняет workspace. Сборка кандидата не переключает Live; публикация проверяет его актуальность и expected_live без повторного рендера. | | AC-09 | Основные экраны, ошибки, диалоги и редакторы проходят адаптивную и клавиатурную проверку на заданных размерах. | | AC-10 | Wheel содержит runtime-ресурсы; обычная сборка сайта проходит и не содержит служебной разметки/скриптов preview-режима. | | AC-11 | Реальный FastAPI проверяет запросы и ответы JSON API, единый формат ошибок и OpenAPI. HTML- и API-маршруты не смешивают форматы; UI вызывает API через ASGITransport с проверенным автором. Ошибки/отказ API отражаются в UI без обхода через прямую запись. | diff --git a/specs/001-antirion-admin/tasks.md b/specs/001-antirion-admin/tasks.md index c64acc9..1809410 100644 --- a/specs/001-antirion-admin/tasks.md +++ b/specs/001-antirion-admin/tasks.md @@ -43,8 +43,8 @@ - Проверены q/status/layout, вложенные ID, пустая выдача, выбранный объект и неизвестный ID; представлены реальные file/layout/count/current. - [ ] **T009** Перенести формы Page, Block и Entry и существующие операции блоков. - Сохранены имена полей и URL, создание draft, слоты/привязки, добавление/порядок/видимость/удаление и семантика формы без изменений. -- [ ] **T010** Перенести существующие публикацию, историю и откат с подтверждениями. - - В UI отражены реальные build+publish и rollback; кандидат/diff не имитируются; ошибки сборки и отсутствие релизов отображаются. +- [x] **T010** Перенести существующие публикацию, историю и откат с подтверждениями. + - Исходный Publication, реальные build candidate/activate и rollback; настоящий diff/preview; CAS Live, видимые ошибки и пустые состояния. Техническая приёмка — verification-publication.md; визуальная проверка пользователя отдельно P006. - [x] **T011** Исправить CSP iframe и защищённые ассеты workspace. - Браузер загружает пассивное превью; изображения и зависимые ресурсы берутся из workspace; traversal/выход по symlink отклоняется; binary MIME корректен. - [x] **T012** Сохранить пользовательские значения при 409/422 на существующих формах. @@ -147,10 +147,31 @@ | NFR-03–NFR-04 | T004–T006, T021–T023, T029, T033 | AC-09 | | NFR-05–NFR-06 | T011–T015, T020, T026, T031, T034–T036 | AC-03, AC-05, AC-08, AC-10 | -Релизы, медиа/настройки, доступы, заявки и MCP следующей очереди не входят в список выполнения 001. Их порядок и зависимости перечислены в конце `plan.md`. +Расширенный workflow релизов, медиа/настройки, доступы, заявки и MCP следующей очереди не входят в список выполнения 001; реальный candidate/diff включён уточнением этапа 5. Их порядок и зависимости перечислены в конце `plan.md`. ## Прежняя функциональная проверка (визуальная приёмка открыта повторно) 2026-11-12: 239 тестов; настоящий FastAPI/ASGITransport; 25 сценариев Chromium на двух origin; 8 экранов и 60 проверок ширины, обе темы, клавиатура и reduced motion; validate/build примеров stage7 — 0 ошибок/0 предупреждений, 7 страниц; wheel установлен вне checkout без design/. Подробная матрица требований, команды и ограничения — [verification.md](verification.md); машиночитаемые результаты — [qa-results.json](qa-results.json). -Этапы 1–2 приняты пользователем. Этап 3 (Конструктор/Эксперт Page) подготовлен к проверке: исходные компоненты builder-antirion, реальные дерево/инспектор/каталог/источники, автоматическое применение полей и явное сохранение, дублирование поддерева, перетаскивание, 422 без потери ввода, сравнение/отмена/форматирование исходника. 247 тестов; Chromium — 12 сравнений Конструктора и 6 «Эксперта», 11 групп сценариев; регрессия editor/shell/pages, CLI и установленного wheel — OK. Подробности — [design-transfer.md](design-transfer.md). Этапы 4–5 и общая визуальная приёмка T033/T036 остаются открытыми; переход — после проверки пользователя. +Этапы 1–2 приняты пользователем. Этап 3 (Конструктор/Эксперт Page) подготовлен к проверке: исходные компоненты builder-antirion, реальные дерево/инспектор/каталог/источники, автоматическое применение полей и явное сохранение, дублирование поддерева, перетаскивание, 422 без потери ввода, сравнение/отмена/форматирование исходника. 247 тестов; Chromium — 12 сравнений Конструктора и 6 «Эксперта», 11 групп сценариев; регрессия editor/shell/pages, CLI и установленного wheel — OK. Подробности — [design-transfer.md](design-transfer.md). На момент этой проверки этапы 4–5 оставались открытыми. Их текущий статус приведён ниже; общая пользовательская визуальная приёмка T033/T036 остаётся отдельной. + +## Повторный перенос: этап 4 / Content (2026-11-17) + +- [x] **C001** Перенести исходные четыре панели, формы, Expert, диалоги, CSS/SVG и responsive без самостоятельного дизайна. +- [x] **C002** Подключить настоящие коллекции, поля, связи, использования, схему и поиск/фильтры. +- [x] **C003** Дополнить API проверкой готовности, CAS-дублированием/удалением, сравнением и настоящим Workspace/Card/Page и Live/Page. +- [x] **C004** Подключить общую фоновую очередь 003, явное сохранение, видимые 409/422/500/сеть и исходные подтверждения. +- [x] **C005** Пользователь разрешил переход от Content к этапу 5. + +Технические проверки и ограничения: [verification-content.md](verification-content.md); доработки: [content-backend.md](content-backend.md). Публикация/история/откат реализованы этапом 5 ниже; общая пользовательская визуальная приёмка остаётся отдельной. + +## Повторный перенос: этап 5 / Publication (2026-11-17) + +- [x] **P001** Перенести исходную композицию, CSS/SVG, пять вкладок, таблицу/инспектор и диалоги в принятый shell. +- [x] **P002** Реализовать private provenance, реальные изменения/историю, build без активации и неизменяемое сравнение кандидата. +- [x] **P003** Подключить preview готового релиза, подтверждение с комментарием, source/render/output hashes и expected_live под SiteLock. +- [x] **P004** Подключить действительные историю релизов/аудит, последствия отката и переключение без изменения workspace; видимые ошибки/сеть/конфликты, committed_build и traceback. +- [x] **P005** Проверить контракт, браузер/ширины/две темы/два preview origin, общий UI и установленный wheel; обновить OpenAPI и документацию. +- [ ] **P006** Пользовательская визуальная приёмка Publication и итоговых экранов. + +Границы — [publication-backend.md](publication-backend.md); результаты и команды — [verification-publication.md](verification-publication.md). Общие T004–T009/T013/T033/T036 не закрываются автоматически технической проверкой этого экрана. diff --git a/specs/001-antirion-admin/verification-content.md b/specs/001-antirion-admin/verification-content.md new file mode 100644 index 0000000..61e105f --- /dev/null +++ b/specs/001-antirion-admin/verification-content.md @@ -0,0 +1,59 @@ +# Проверка этапа 4 — Content Editor + +Дата: 2026-11-17. Реализация подготовлена к проверке пользователя. Источники — оригинальные `content-antirion.html`, `assets/content-editor.{css,js}` и общий `builder.css`. Декларации CSS и SVG переносятся воспроизводимым скриптом; принятый shell сохранён. Доработки и границы бэкенда — [content-backend.md](content-backend.md). + +## Сервер и данные + +`tests/test_content_editor.py`: 13 тестовых методов проверяют настоящий FastAPI/HTML adapter на временной копии текущего `examples/site-studio`: + +- исходную композицию, статические ресурсы, пустую выключенную коллекцию; +- один Registry и внутренний API call на update, настоящий рендер карточки и отсутствие записи/history/publish; +- строгую проверку кандидата с required/link/asset и сохранение неполного draft отдельно; +- диагностику невалидного YAML без потери исходника; +- типизированные вложенные ref/link, обратные связи и query membership текущего кандидата; +- typed link/list/refs/boolean через общий парсер полей; +- копирование текущей редакции в draft, неизменность оригинала, CAS источника/цели и запрет traversal; +- запрет удаления published, необходимость сохранённого archive, CAS и историю; +- traceback/request_id и committed/deleted при отказе аудита после фактической операции; +- Live из HTML/assets релиза, отдельный защищённый snapshot/CSP, отсутствие смешивания с workspace; +- сравнение несохранённого source, неизвестное сравнение старого manifest и отсутствие Live/Card; +- пустой новый draft: slug как подпись только в представлении, без выдуманного title в файле; +- JSON-ошибки авторизации/CSRF/DTO. + +13 тестов проходят. Вместе с 12 тестами общей очереди 003 — **25 тестов OK** после последних уточнений. + +Полная регрессия — **384 unittest-теста OK**. Как и в 003, старые тесты требуют удалённый `examples/studio-site`: использовалась временная фикстура из коммита `231490b` с миграцией inline theme в файл schema 1 minimal@1; `tests/helpers.EXAMPLE` указывает на временную копию перед discovery. Примеры не возвращались в репозиторий. Ограничение и схема фикстуры описаны в [003 verification](../003-background-editor/verification.md). Старый тест заполнения `.env.example` исправлен: замена всей строки вместо конкатенации нового хеша с уже записанным пользователем. Сам `.env.example` и настройки входа не менялись. + +## Chromium и оригинал + +`scripts/qa_content_001.py` поднимает настоящий uvicorn на временном Site Studio и отдельно открывает дизайнерский оригинал. Сверяются **12 наборов**: 1440/1280/1024/768/390/360 px × light/dark. Проверяются шрифты/padding устойчивых компонентов, ширины колонок desktop и исходные светлые фоны; dark использует ранее принятую палитру Antirion. Снимки desktop/mobile/dark и реальный конфликт просмотрены визуально. Разные данные и настоящий рендер публичной карточки не сравниваются как попиксельно одинаковые изображения mock. + +Проверяются поиск/фильтры/вкладки без POST, фокус, один update и сохранённые input/iframe, ввод и вкладки при задержанном POST, реальные asset/ref picker и boolean, добавление/удаление/перенумерация списка, Workspace/Card/Page и immutable Live/Page, явное пустое состояние Live/Card, review/Expert/diff/поиск/невалидный YAML/исправление, переход с несохранёнными правками, явный Save без publish, настоящий CAS/409, duplicate из текущей редакции, отмена и подтверждение удаления, guard published, пустая/OFF коллекция, создание draft, видимые HTTP500/сеть и восстановление. + +Полный сценарий прошёл в обоих режимах preview: **13 групп** на пассивном административном origin и **12 групп** на bridge отдельного origin (сравнение геометрии общее). Все **12 визуальных наборов** проверены. Неожиданных JS/console/CSP-ошибок и native dialogs — **0**. В отчёте намеренные 409/422/500/сеть отделены от неожиданных ошибок; native dialogs запрещены. Артефакты: `/tmp/site-engine-content-001/report.json`, `content-{light,dark}-{width}.png`, `reference-{width}.png`, `review-{False,True}.png`, `conflict-{False,True}.png`. + +Дополнительно `scripts/qa_editor_updates.py` прошёл **26 групп** в двух режимах preview: прежние сценарии конструктора, очереди, фокуса/caret, списков, сохранения/конфликта, JS-изоляции и Entry. **0 JS-ошибок, 0 native dialogs**. Подтверждён максимум один update одновременно. В Entry-сценарии явно выбирается Page: начальный вариант Content теперь Card, как в оригинале. Артефакты — `/tmp/site-engine-editor-updates/browser.json`. + +## Сборка и упаковка + +- CLI validate `examples/site-studio`: **0 ошибок, 0 предупреждений**. +- CLI build: **13 страниц**, релиз в `/tmp/site-studio-content-dist/current/`. +- `scripts/verify_package_001.py --site examples/site-studio`: wheel установлен вне checkout без `design/`; проверены Content templates/CSS/JS, настоящее чтение и карточка через HTML adapter/API, прежние Theme Manager/пресеты/сборка/preview/queue. +- `scripts/sync_content_design.py --check`: совпадают исходные декларации CSS и SVG. +- Ruff изменённых Python, `node --check` изменённых JS, `git diff --check`: проходят. + +Основные команды: + +```bash +PYTHONPATH=src python -m unittest discover -s tests -p test_content_editor.py -v +PYTHONPATH=src python scripts/qa_content_001.py +PYTHONPATH=src python scripts/qa_editor_updates.py +python scripts/sync_content_design.py --check +python scripts/verify_package_001.py --site examples/site-studio +PYTHONPATH=src python -m site_engine.cli validate examples/site-studio +PYTHONPATH=src python -m site_engine.cli build examples/site-studio --out /tmp/site-studio-content-dist +``` + +Коммит и развёртывание не выполнялись. Для пользовательской проверки требуется пересборка образа: ресурсы и код находятся в runtime-пакете. Следующий этап публикации UI ожидает проверки Content. Slug rename, редактор схем, RBAC, полноценный индекс ссылок в Markdown/Jinja/JS и отдельный сохранённый Live/Card не добавлены. + +Повторная расширенная проверка перед коммитами — [verification-regression.md](verification-regression.md). diff --git a/specs/001-antirion-admin/verification-publication.md b/specs/001-antirion-admin/verification-publication.md new file mode 100644 index 0000000..9886515 --- /dev/null +++ b/specs/001-antirion-admin/verification-publication.md @@ -0,0 +1,76 @@ +# Проверка этапа 5 — Publication + +Дата: 2026-11-17. Этап реализован и подготовлен к проверке пользователя. Источник — оригинальный `publication-antirion.html` / `assets/publication.{css,js}`; адаптация сохраняет принятый Antirion shell. Контракт, данные и ограничения — [publication-backend.md](publication-backend.md). + +## Проверки сервера + +Полная регрессия: **397 unittest-тестов OK** (384 прежних и 13 Publication на момент запуска). После добавления проверок истории/реального output diff, отказа аудита после сборки и JSON 401 повторно выполнены все **16 Publication-тестов — OK**. На тот момент это соответствовало 400 методам; единый запуск всех 400 не заявлялся. + +Новые тесты используют временный текущий `examples/site-studio`, настоящий FastAPI и HTML adapter. Проверены build без активации, публикация точных байтов без рендера, private/public разделение, source/renderer freshness, подмена output, CAS Live, замена кандидата, запрет отката неопубликованного кандидата, CLI без provenance, immutable diff, реальные версии документов и изменённые файлы релиза, неуспешный strict render, оба preview origin, CSRF/auth/session-expired/traversal/symlink, ошибки после совершённой операции и request_id/traceback. + +Старым тестам нужен удалённый `examples/studio-site`. Для полной регрессии использована временная фикстура из `231490b` с уже мигрированными файловыми настройками темы; `tests/helpers.EXAMPLE` заменялся только в процессе до discovery. Файлы удалённых примеров в checkout не восстанавливались. Схема окружения — [003 verification](../003-background-editor/verification.md); подробный лог запуска — `/tmp/publication-regression.log`. + +## Настоящий Chromium + +`qa_publication_001.py` запускает uvicorn на временной копии Site Studio и оригинальный макет отдельно. Выполнены **12 наборов визуальной сверки**: 1440/1280/1024/768/390/360 px, светлая и тёмная тема. Измеряются шрифты/padding/цвета исходного экрана; runtime использует размеры принятого shell и его тёмную палитру. Это не побайтовое сравнение скриншотов: данные, число файлов и shell оригинала отличаются. Проверены отсутствие горизонтального переполнения и ручная сверка screenshot композиции, preview и отката. + +**25 групп браузерных проверок** на двух конфигурациях preview (13 + 12): + +- первый релиз и пустые состояния, реальные локальные фильтры/выбор/вкладки без POST; +- сравнение документа и существующая/пустая история в исходных диалогах; +- проверка без публикации, фоновая сборка без блокировки вкладок и без переключения Live; +- настоящий immutable diff/preview со стилями и без скриптов; +- отмена и подтверждённая публикация ровно выбранного кандидата; +- устаревший кандидат: видимый 409 и прежний Live; +- отмена/подтверждение отката, сохранение workspace, перечитывание истории/комментариев/аудита; +- намеренные 500/обрыв сети, видимая ошибка и восстановление; +- переходы на ранее перенесённые экраны, клавиатурные вкладки и выход. + +Непредвиденных JS/console/CSP-ошибок и нативных alert/confirm/prompt — **0**. Намеренно вызванные HTTP 409/500 и сетевой отказ перечислены отдельно в отчёте. + +Артефакты: `/tmp/site-engine-publication-001/report.json`, парные `publication-{light,dark}-*.png` / `reference-*.png`, `candidate-preview-{False,True}.png`, `rollback-{False,True}.png`. Они временные и не входят в репозиторий; сценарий воспроизводит их. + +## Общая совместимость + +- `qa_001.py`: **8 экранов / 60 проверок ширины — OK**, `/tmp/site-engine-publication-general/`. +- `qa_shell_001.py`: **12 наборов геометрии / 6 групп сценариев — OK**, включая Ctrl+K, htmx-переходы, мобильный фокус, профиль/выход и Live после настоящей публикации; `/tmp/site-engine-shell-001/report.json`. +- `qa_errors_001.py`: **6 групп — OK**, включая 500 публикации со стеком/ID, desktop/mobile уведомления, 500/сеть сохранения без потери ввода и последующее сохранение/публикацию; `/tmp/cms-errors-qa/report.json`. +- Установленный wheel вне checkout без `design/`: настоящие кандидат/preview/активация, API, шаблоны и новые статические ресурсы — OK; `/tmp/publication-package.log`. + +Проверки генератора CSS/SVG, `node --check`, Ruff и `git diff --check` прошли. CLI: validate — 0 ошибок/0 предупреждений; build — 13 страниц в `/tmp/site-studio-publication-final`. OpenAPI экспортирован заново из приложения. + +## Воспроизводимые команды + +```bash +PYTHONPATH=src python -m unittest discover -s tests -p test_publication.py -v +PYTHONPATH=src python scripts/qa_publication_001.py +PYTHONPATH=src python scripts/qa_001.py --out /tmp/site-engine-publication-general +PYTHONPATH=src python scripts/qa_errors_001.py +PYTHONPATH=src python scripts/qa_shell_001.py +python scripts/verify_package_001.py +python scripts/sync_publication_design.py --check +node --check src/site_engine/web/admin/static/publication.js +PYTHONPATH=src python -m site_engine.cli export-openapi --out specs/001-antirion-admin/openapi.json +PYTHONPATH=src python -m site_engine.cli validate examples/site-studio +PYTHONPATH=src python -m site_engine.cli build examples/site-studio --out /tmp/site-studio-publication-final +``` + +В рабочем окружении использован Python `/tmp/flexly-cms-htmx-check/bin/python`, системный Chromium Playwright с `--no-proxy-server`. Проверки выполнялись на временных сайтах; live `data/`, `.env` и Docker не изменялись. Развёртывание контейнера, долгие нагрузочные испытания, отказ процесса во время нескольких служебных записей и пользовательская визуальная приёмка этим отчётом не подтверждаются. + +## Исправление загрузки через меню (2026-11-17) + +Пользователь обнаружил падение `null.textContent` при первом переходе в Publication. Первоначальный Publication QA открывал экран через `page.goto`, поэтому не покрывал этот сценарий. Утверждение об отсутствии ошибок относилось к фактически выполненным сценариям, а проверка загрузки через htmx была пропущена. + +Причина воспроизведена в Chromium на временном сайте: при `allowScriptTags:false` htmx удаляет также ` + + diff --git a/src/site_engine/web/admin/templates/content.html.j2 b/src/site_engine/web/admin/templates/content.html.j2 new file mode 100644 index 0000000..65cc073 --- /dev/null +++ b/src/site_engine/web/admin/templates/content.html.j2 @@ -0,0 +1,33 @@ +{% extends 'shell.html.j2' %} +{% from '_content_icons.html.j2' import ci %} +{% set data = snap.schema.content if snap else empty_data %} +{% block contentclass %}design-content content-screen{% endblock %} +{% block title %}{{ meta.get('title', snap.id) if snap else 'Контент и коллекции' }} — Site Engine{% endblock %} +{% block content %} +
+
04 / CONTENT OPERATIONS · ENTRY EDITOR

{{ meta.get('title', snap.id) if snap else 'Управление контентом' }}

Нет несохранённых изменений{% if snap %}{{ snap.path }}{% endif %}Pages ≠ Entries
{% if snap %}
{% endif %}
+{% if content_error|default('') %}{% endif %} +
+
Коллекцииcollections/*.yaml
{{ data.collections|length }}
+{% for c in data.collections %}{{ c.name }}{{ c.id }}{{ c.total }}{% if not c.enabled %}OFF{% endif %}{% else %}
Коллекций нет
{% endfor %}
File-first CMS

Контент хранится в Markdown + YAML. SQLite не является источником публичных записей.

+
Записи / {{ data.collection.id if data.collection else '—' }}{{ data.entries|length }} записей · {{ 'активна' if data.collection and data.collection.enabled else 'коллекция выключена' }}
{% if data.collection %}
{% endif %}
+
{{ ci('search') }}
{% for value,label in [('all','Все'),('published','В каталоге'),('draft','Черновики'),('changed','Изменены')] %}{% endfor %}
+
{% for e in data.entries %}{{ ci('file') }}{{ e.title }}{{ e.slug }}{{ {'published':'В каталоге','draft':'Черновик','archived':'Архив'}.get(e.status,e.status) }}{% if e.changed %}● Правки{% endif %}{{ ci('chevron') }}{% endfor %} +
{{ ci('search') }}{{ 'Ничего не найдено' if data.entries else 'Записей пока нет' }}

{{ 'Измените фильтры или создайте запись.' if not data.collection or data.collection.enabled else 'Коллекция выключена: записи не участвуют в публичной сборке.' }}

{{ data.entries|length }} из {{ data.entries|length }}
+
+{% if snap %} +{% include 'entry_editor_result.html.j2' %} +
+ +
SOURCE / ENTRY

{{ snap.path }}

YAML front matter + Markdown body · schema: {{ data.collection.id }}

YAML + MARKDOWNСинхронизирован
{% for issue in snap.issues %}

{{ issue.code }} · {{ issue.message }}

{% endfor %}
+
{% else %}
Выберите запись или активную коллекцию.
{% endif %} +
+
+ +
+
+{% endblock %} diff --git a/src/site_engine/web/admin/templates/entry_editor_result.html.j2 b/src/site_engine/web/admin/templates/entry_editor_result.html.j2 index 3da5805..4d3bdda 100644 --- a/src/site_engine/web/admin/templates/entry_editor_result.html.j2 +++ b/src/site_engine/web/admin/templates/entry_editor_result.html.j2 @@ -1,46 +1,35 @@ -{% from '_fields.html.j2' import field %} -{% macro buffer_fields() %}{% if not compact_update|default(false) %}{% endif %}{% endmacro %} -
- {% if not compact_update|default(false) %}{% endif %} - {% if saved %}

Документ сохранён. Публикация не выполнялась.

{% endif %} - {% if errors %}{% endif %} - {% if submitted_fields %}{% endif %} - {% if snap.issues %}
    {% for i in snap.issues %}
  • {{ i.code }} {{ i.path }}: {{ i.message }}
  • {% endfor %}
{% endif %} - {% if conflict %}{% endif %} -
- {% if snap.model %} -

Структура

-
{{ buffer_fields() }}
- {% for b in fixed + display %}
{{ b.scope }} / {{ b.region }}
{{ buffer_fields() }}
Только чтение · определяется шаблоном
{% endfor %} - {% for b in blocks %} -
- {{ b.region }}
{{ buffer_fields() }}
- {% if b.hidden %}Скрыт: отсутствует в превью{% endif %}{% if b.requires %}Условие: {{ b.requires|join(', ') }}{% endif %} -
- {% else %}

Блоков документа нет.

{% endfor %} - {% if snap.kind == 'page' %}
Добавить блок
{{ buffer_fields() }}
{% endif %} -
-

{{ readonly_selected.fragment if readonly_selected else selected.fragment if selected else 'Свойства документа' }}

- {% if readonly_selected %}

Только чтение · {{ readonly_selected.scope }} / {{ readonly_selected.owner }}

{{ readonly_selected.id }} · {{ readonly_selected.region }}

Props

{{ readonly_selected.get('props', {})|tojson(indent=2) }}

Этот блок определяется шаблоном. Изменение layout/display из редактора документа недоступно.

- {% else %} -
{{ buffer_fields() }} - - {% if selected %}

{{ selected.id }}

- {% for f in fields %}{{ field(f) }}{% endfor %} - - - {% for key, enabled in snap.schema.features.items() %}{% endfor %} - {% else %} - {% if snap.kind == 'page' %} - {% else %}{% for f in fields %}{{ field(f) }}{% endfor %}{% endif %} - - {% if snap.schema.has_body %}{% endif %} - {% endif %} -
- {% if selected %}
{{ buffer_fields() }}
{{ buffer_fields() }}
{% endif %} -

Конструктор пересобирает YAML: комментарии и форматирование могут измениться. Перед первой правкой скачайте исходник.

- {% endif %} -
- {% else %}

Конструктор недоступен: исправьте исходник в режиме «Эксперт». Последнее корректное дерево сохраняется в открытом редакторе.

{% endif %} -
+{% from '_content_icons.html.j2' import ci %} +{% from '_content_fields.html.j2' import cf %} +{% set data = snap.schema.content %} +{% macro slug_field() %}
{% endmacro %} +
+{% if not compact_update|default(false) %}{% endif %} +
+
ENTRY / {{ data.collection.id }}

{{ meta.get('title', snap.id) }}

{{ snap.path }}

+
{% for tab,label in [('fields','Поля'),('relations','Связи'),('usage','Где используется'),('schema','Схема')] %}{% endfor %}
+
+
+{% if errors %}{% endif %} +{% if not snap.model %}
Исправьте исходник в режиме «Эксперт». Ваш текст остаётся в редакторе.
{% else %} +
+ +{% if not compact_update|default(false) %}{% endif %} +

Поля коллекции генерируются по collections/{{ data.collection.id }}.yaml

+{% if not fields|selectattr('key','equalto','title')|list %}{{ slug_field() }}{% endif %} +{% for f in fields %}{{ cf(f) }}{% if f.key == 'title' %}{{ slug_field() }}{% endif %}{% endfor %} + +
+{% if snap.schema.has_body %}

Markdown body

Markdown body хранится отдельно от front matter
{% endif %} +

Файловый статус

+ +
{% endif %}
+ + +
+ + +
diff --git a/src/site_engine/web/admin/templates/publication.html.j2 b/src/site_engine/web/admin/templates/publication.html.j2 new file mode 100644 index 0000000..70eced3 --- /dev/null +++ b/src/site_engine/web/admin/templates/publication.html.j2 @@ -0,0 +1,11 @@ +{% extends 'shell.html.j2' %} +{% block title %}Публикация — админка{% endblock %} +{% block contentclass %}design-content publication-content{% endblock %} +{% block content %} +
+
05 / RELEASE WORKFLOW · ATOMIC SITE RELEASES

Публикация сайта

Загрузка данных публикации…

+ + +
+
+{% endblock %} diff --git a/src/site_engine/web/api/models.py b/src/site_engine/web/api/models.py index c012525..9c70f9b 100644 --- a/src/site_engine/web/api/models.py +++ b/src/site_engine/web/api/models.py @@ -107,9 +107,26 @@ class InspectorEdit(DTO): class EditorUpdate(Buffer): + preview_view: Literal["page", "card"] = "page" + preview_version: Literal["workspace", "live"] = "workspace" operations: list[Action | InspectorEdit] = Field(default_factory=list, max_length=100) +class EntryDeleted(DTO): + deleted: Literal[True] + id: str + collection: str + + +class EntryCheck(DTO): + revision: int + issues: list[IssueDTO] + + +class EntryCopy(Buffer): + id: str = Field(pattern=r"^[a-z0-9][a-z0-9_-]*$", max_length=200) + + class Create(DTO): id: str = Field(min_length=1, max_length=200) title: str = "" @@ -172,6 +189,8 @@ class ErrorBody(DTO): current: Snapshot | ThemeSnapshot | None = None committed: Snapshot | ThemeSnapshot | None = None buffer: Snapshot | None = None + deleted: bool | None = None + committed_build: str | None = None class ErrorEnvelope(DTO): @@ -194,6 +213,8 @@ class PageRow(DTO): class EntryRow(DTO): + changed: bool | None = None + url: str = "" slug: str title: str status: str @@ -202,6 +223,7 @@ class EntryRow(DTO): class CollectionRow(DTO): + enabled: bool = True id: str name: str total: int @@ -226,6 +248,12 @@ class Workspace(DTO): class Entries(DTO): + collections: list[CollectionRow] = Field(default_factory=list) + schema_text: str = "" + display: str = "" + kind: str = "content" + live_build: str | None = None + comparison_available: bool = False collection: CollectionRow entries: list[EntryRow] @@ -272,3 +300,45 @@ def snapshot_dto(value): schema=value.schema, revision=value.revision, ) + + +class PublicationDocument(DTO): + hash: str + size: int + title: str + status: str + type: str + source: str | None = None + + +class PublicationChange(DTO): + path: str + title: str + type: str + status: str + kind: Literal["new", "modified", "deleted", "unknown"] + before: PublicationDocument | None = None + after: PublicationDocument | None = None + + +class PublicationState(DTO): + current: str | None + source_hash: str + comparison_available: bool + changes: list[PublicationChange] + candidate: dict[str, Any] | None = None + validation: dict[str, Any] | None = None + history: list[dict[str, Any]] + builds: list[dict[str, Any]] + activity: list[dict[str, Any]] + + +class ReleaseActivate(DTO): + id: str = Field(pattern=r"^\d{8}T\d{6}-[0-9a-f]{8}$") + expected_live: str | None + comment: str = Field(default="", max_length=150) + + +class ReleasePreview(DTO): + id: str = Field(pattern=r"^\d{8}T\d{6}-[0-9a-f]{8}$") + route: str = Field(default="/", max_length=2000) diff --git a/src/site_engine/web/api/routes.py b/src/site_engine/web/api/routes.py index 06806b9..e70f59e 100644 --- a/src/site_engine/web/api/routes.py +++ b/src/site_engine/web/api/routes.py @@ -12,9 +12,15 @@ from starlette.exceptions import HTTPException as StarletteHTTPException from ...core.models import STATUSES from ...errors import ConflictError, EngineError, UnsafePathError from ...services.documents import AuditCommitError, DocumentMissing, EditorContext -from ...services.entries import EntryService +from ...services.entries import EntryDeleteCommitError, EntryService from ...services.pages import PageService from ...services.preview import asset_path +from ...services.publication import ( + CandidateCommitError, + PublicationService, + ReleaseCommitError, + ReleaseMissing, +) from ...services.publish import publish, rollback from ...services.theme import OnboardingService, ThemeCommitError, ThemeService from ...services.workspace import entries, filter_pages, releases, workspace @@ -27,10 +33,16 @@ from .models import ( EditorUpdate, EditorUpdateResult, Entries, + EntryCheck, + EntryCopy, + EntryDeleted, ErrorEnvelope, OnboardingState, PageRow, Preview, + PublicationState, + ReleaseActivate, + ReleasePreview, Releases, Rollback, Snapshot, @@ -81,7 +93,7 @@ def install_api(app, auth, root, dist, previews): return ( PageService(root, auth.audit) if kind == "page" - else EntryService(root, auth.audit, collection) + else EntryService(root, auth.audit, collection, dist=dist) ) def themes(): @@ -110,7 +122,7 @@ def install_api(app, auth, root, dist, previews): 409, "conflict", exc, - submitted=buf.model_dump(exclude={"action", "operations"}) if buf else None, + submitted=buf.model_dump(include={"source", "etag", "revision"}) if buf else None, current=current, ) except AuditCommitError as exc: @@ -121,6 +133,9 @@ def install_api(app, auth, root, dist, previews): exc, committed=snapshot_dto(exc.snapshot).model_dump(by_alias=True, mode="json"), ) + except EntryDeleteCommitError as exc: + log.exception("entry_delete_after_commit request_id=%s", request_id()) + return error(500, "entry_deleted_audit_failed", exc, deleted=True) except DocumentMissing as exc: return error(404, "not_found", exc) except UnsafePathError as exc: @@ -131,7 +146,7 @@ def install_api(app, auth, root, dist, previews): "validation", exc, issues=[i.to_dict() for i in exc.report.issues], - submitted=buf.model_dump(exclude={"action", "operations"}) if buf else None, + submitted=buf.model_dump(include={"source", "etag", "revision"}) if buf else None, ) except (ValueError, KeyError) as exc: return error(422, "invalid_operation", exc) @@ -235,7 +250,7 @@ def install_api(app, auth, root, dist, previews): def read(): if status and status not in STATUSES: raise EngineError("Некорректный status") - data = entries(root, collection) + data = entries(root, collection, dist) data["entries"] = [ e for e in data["entries"] @@ -246,6 +261,69 @@ def install_api(app, auth, root, dist, previews): return invoke(read) + def publication(): + return PublicationService(root, dist, auth.state_dir, auth.audit) + + def publication_invoke(fn): + try: + return fn() + except ReleaseMissing as exc: + return error(404, "release_not_found", exc) + except CandidateCommitError as exc: + log.exception("candidate_after_build request_id=%s", request_id()) + return error(500, "candidate_after_build", exc, committed_build=exc.build_id) + except ReleaseCommitError as exc: + log.exception("release_after_commit request_id=%s", request_id()) + return error(500, "release_after_commit", exc, committed_build=exc.build_id) + except ConflictError as exc: + return error(409, "release_conflict", exc) + except UnsafePathError as exc: + return error(403, "forbidden", exc) + except EngineError as exc: + return error(422, "release_validation", exc, issues=[i.to_dict() for i in exc.report.issues]) + except ValueError as exc: + return error(422, "invalid_operation", exc) + + @router.get("/publication", response_model=PublicationState) + def publication_state(): + return publication_invoke(lambda: publication().state()) + + @router.post("/publication/validate") + def publication_validate(ctx: Ctx): + return publication_invoke(lambda: publication().validate(ctx)) + + @router.post("/publication/build") + def publication_build(ctx: Ctx): + return publication_invoke(lambda: publication().build(ctx, request_id())) + + @router.post("/publication/activate") + def publication_activate(body: ReleaseActivate, ctx: Ctx): + return publication_invoke(lambda: publication().activate(body.id, body.expected_live, body.comment, ctx)) + + @router.post("/publication/rollback") + def publication_rollback(body: ReleaseActivate, ctx: Ctx): + return publication_invoke(lambda: publication().activate(body.id, body.expected_live, body.comment, ctx, rollback=True)) + + @router.get("/publication/release") + def publication_release(id: str): + return publication_invoke(lambda: publication().release_details(id)) + + @router.get("/publication/candidate-diff") + def publication_candidate_diff(): + return publication_invoke(lambda: publication().candidate_diff()) + + @router.get("/publication/compare") + def publication_compare(path: str): + return publication_invoke(lambda: publication().compare(path)) + + @router.get("/publication/document-history") + def publication_document_history(path: str): + return publication_invoke(lambda: publication().document_history(path)) + + @router.post("/publication/preview", response_model=Preview) + def publication_preview(body: ReleasePreview, ctx: Ctx): + return publication_invoke(lambda: publication().preview(body.id, body.route, previews, ctx.principal)) + @router.get("/releases", response_model=Releases) def release_list(): return releases(dist) @@ -386,7 +464,8 @@ def install_api(app, auth, root, dist, previews): preview, preview_error = None, None try: preview = previews.render_document( - reg, svc, identity, body.revision, ctx.principal, include_html=True + reg, svc, identity, body.revision, ctx.principal, include_html=True, + target=body.preview_view, version=body.preview_version, dist=dist ) except Exception as exc: # noqa: BLE001 - preview failure is an independent result # A failed preview must never roll back accepted in-memory edits. @@ -410,6 +489,21 @@ def install_api(app, auth, root, dist, previews): def entry_update(collection: str, identity: str, body: EditorUpdate, ctx: Ctx): return update("entry", identity, body, ctx, collection) + @router.post("/collections/{collection}/entries/{identity}/check", response_model=EntryCheck) + def entry_check(collection: str, identity: str, body: Buffer, ctx: Ctx): + svc = service("entry", collection) + return invoke(lambda: svc.check(identity, body.source, body.etag, body.revision), svc, identity, body) + + @router.post("/collections/{collection}/entries/{identity}/duplicate", response_model=Snapshot, status_code=201) + def entry_duplicate(collection: str, identity: str, body: EntryCopy, ctx: Ctx): + svc = service("entry", collection) + return invoke(lambda: snapshot_dto(svc.duplicate(identity, body.id, body.source, body.etag, ctx)), svc, identity, body) + + @router.post("/collections/{collection}/entries/{identity}/delete", response_model=EntryDeleted) + def entry_delete(collection: str, identity: str, body: Buffer, ctx: Ctx): + svc = service("entry", collection) + return invoke(lambda: svc.delete(identity, body.etag, ctx), svc, identity, body) + @router.post("/editor/pages/{identity:path}/validate", response_model=Snapshot) @router.post("/pages/{identity:path}/validate", response_model=Snapshot) def page_validate(identity: str, body: Buffer, ctx: Ctx): diff --git a/src/site_engine/web/preview_app.py b/src/site_engine/web/preview_app.py index 3afd312..b5fc33a 100644 --- a/src/site_engine/web/preview_app.py +++ b/src/site_engine/web/preview_app.py @@ -17,7 +17,7 @@ def snapshot_response(store, snapshot, token, asset=None): except (PermissionError, OSError, ValueError, UnsafePathError): return Response("Превью недоступно", status_code=403, headers={"Cache-Control": "no-store"}) config = store.config - script = f"'nonce-{data['nonce']}'" if config else "'none'" + script = f"'nonce-{data['nonce']}'" if config and not data.get("passive") else "'none'" ancestors = config.admin if config else "'self'" headers = { "Cache-Control": "no-store", diff --git a/tests/test_content_editor.py b/tests/test_content_editor.py new file mode 100644 index 0000000..c02de37 --- /dev/null +++ b/tests/test_content_editor.py @@ -0,0 +1,359 @@ +"""Content editor contract: real metadata, stateless readiness, CAS and immutable Live.""" + +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from fastapi.testclient import TestClient + +from site_engine.build.pipeline import build_site +from site_engine.core.registry import load_site +from site_engine.parsing.frontmatter import dumps, parse +from site_engine.parsing.yamlio import dump_yaml, load_yaml +from site_engine.services.auth import hash_password +from site_engine.services.documents import EditorContext +from site_engine.services.entries import EntryService +from site_engine.web.app import create_app + +ROOT = Path(__file__).resolve().parents[1] + + +class ContentEditorTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.password = "content editor test password" + cls.password_hash = hash_password(cls.password, n=2**10) + + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="content-editor-test-") + self.addCleanup(tmp.cleanup) + self.work = Path(tmp.name) + self.site = self.work / "site" + self.dist = self.work / "dist" + shutil.copytree( + ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine") + ) + env = patch.dict( + os.environ, + { + "SITE_ROOT": str(self.site), + "SITE_DIST": str(self.dist), + "SITE_STATE_DIR": str(self.work / "state"), + "SITE_ADMIN_LOGIN": "admin", + "SITE_ADMIN_PASSWORD_HASH": self.password_hash, + "SITE_SECRET_KEY": "content-editor-test-secret-" * 3, + "SITE_COOKIE_SECURE": "0", + "SITE_ADMIN_ORIGIN": "", + "SITE_PREVIEW_ORIGIN": "", + }, + ) + env.start() + self.addCleanup(env.stop) + self.app = create_app() + self.client = TestClient(self.app) + self.addCleanup(self.client.close) + cookie = self.app.state.auth.login("admin", self.password, "testclient") + self.client.cookies.set("se_session", cookie) + self.app.state.api_credentials["test"] = (cookie, "testclient") + self.principal = self.app.state.auth.authenticate(cookie) + self.ctx = EditorContext(self.principal, "testclient") + self.csrf = self.app.state.auth.csrf_token(self.principal) + self.svc = EntryService(self.site, collection="services", dist=self.dist) + self.snap = self.svc.get("bots") + + def payload(self, **extra): + return {"source": self.snap.source, "etag": self.snap.etag, "revision": 7, **extra} + + def api(self, op, payload=None, identity="bots"): + return self.client.post( + f"/admin/api/v1/collections/services/entries/{identity}/{op}", + json=self.payload() if payload is None else payload, + headers={"Authorization": "Bearer test"}, + ) + + def ui(self, op, payload=None, csrf=None): + return self.client.post( + "/admin/editor/content/services/bots/" + op, + data={ + "csrf": self.csrf if csrf is None else csrf, + "payload": json.dumps(self.payload() if payload is None else payload), + }, + headers={ + "Origin": "http://testserver", + "HX-Request": "true", + "Accept": "application/json", + }, + ) + + def test_original_workspace_markup_static_and_empty_disabled_collection(self): + response = self.client.get("/admin/content/services/bots") + self.assertEqual(response.status_code, 200) + for marker in ( + "entry-workspace", + "collection-pane", + "entry-pane", + "editor-content", + "preview-pane", + "entry-tabs", + "source-edit-wrap", + "data-content-picker", + ): + self.assertIn(marker, response.text) + self.assertNotIn("409 Demo", response.text) + for name in ("content-editor.css", "content-adapter.css", "content-editor.js"): + self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200) + empty = self.client.get("/admin/content/posts") + self.assertEqual(empty.status_code, 200) + self.assertIn("Записей пока нет", empty.text) + self.assertIn("OFF", empty.text) + self.assertIn("disabled", empty.text) + + def test_update_has_one_registry_and_api_call_and_no_write(self): + before = (self.site / self.snap.path).read_bytes() + calls = self.app.state.api_calls + payload = self.payload( + preview_view="card", + operations=[{"type": "entry_fields", "values": {"title": "Current candidate"}}], + ) + with patch("site_engine.services.documents.load_site", wraps=load_site) as load: + response = self.ui("update", payload) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(load.call_count, 1) + self.assertEqual(self.app.state.api_calls - calls, 1) + result = response.json() + self.assertIn("Current candidate", result["preview"]["html"]) + self.assertIn("f-entry_card", result["preview"]["html"]) + self.assertIn("data-content-panel", result["projection"]) + self.assertNotIn("name='source'", result["projection"]) + self.assertEqual((self.site / self.snap.path).read_bytes(), before) + self.assertFalse((self.site / ".engine/history").exists()) + self.assertFalse((self.dist / "current").exists()) + + def test_readiness_missing_required_and_render_errors_does_not_block_draft_save(self): + meta, body = parse(self.snap.source) + meta.update( + status="draft", hero_asset="assets/missing.webp", cta={"href": {"page": "missing-page"}} + ) + meta.pop("title") + source = dumps(meta, body) + response = self.ui("check", self.payload(source=source)) + self.assertEqual(response.status_code, 200, response.text) + codes = {i["code"] for i in response.json()["issues"]} + self.assertIn("E_ENTRY_REQUIRED", codes) + self.assertTrue({"E_ASSET_MISSING", "E_LINK_BROKEN"} & codes, codes) + self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source) + self.assertEqual(self.ui("save", self.payload(source=source)).status_code, 200) + self.assertFalse((self.dist / "current").exists()) + + def test_readiness_reports_invalid_yaml_without_rewriting_source(self): + source = "---\ntitle: [\n---\nCurrent text" + response = self.api("check", self.payload(source=source)) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["issues"]) + self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source) + + def test_dependencies_use_candidate_query_membership_and_nested_typed_refs(self): + schema_file = self.site / "collections/cases.yaml" + schema = load_yaml(schema_file.read_text()) + schema["fields"].append( + { + "key": "nested", + "type": "list", + "fields": [ + {"key": "related", "type": "ref", "to": "*"}, + {"key": "link", "type": "link"}, + ], + } + ) + schema_file.write_text(dump_yaml(schema)) + target = self.site / "content/cases/booking.md" + meta, body = parse(target.read_text()) + meta["nested"] = [{"related": "services/bots", "link": {"entry": "services/bots"}}] + target.write_text(dumps(meta, body)) + meta, body = parse(self.snap.source) + result = self.svc.validate_source("bots", self.snap.source, self.snap.etag).schema[ + "content" + ] + self.assertTrue(any(u["field"] == "nested.0.related" for u in result["usages"])) + self.assertTrue(any(u["field"] == "nested.0.link" for u in result["usages"])) + # Home's featured query uses the candidate, not the saved file. + home_before = [u for u in result["usages"] if u["file"] == "pages/index.md"] + self.assertTrue(home_before) + meta["status"] = "draft" + result = self.svc.validate_source("bots", dumps(meta, body), self.snap.etag).schema[ + "content" + ] + self.assertFalse(any(u["file"] == "pages/index.md" for u in result["usages"])) + self.assertTrue(any(r["target"] == "scenarios/legal" for r in result["relations"])) + self.assertFalse(next(c for c in result["collections"] if c["id"] == "posts")["enabled"]) + + def test_typed_form_preserves_link_list_refs_and_optional_boolean(self): + response = self.api( + "update", + self.payload( + operations=[ + { + "type": "inspector", + "fields": { + "operation": ["entry_fields"], + "p.title": ["Typed fields"], + "p.featured": ["false"], + "p.cta.href.kind": ["entry"], + "p.cta.href.target": ["services/ai"], + "p.benefits.0": ["First"], + "p.benefits.1": ["Second"], + "p.benefits.0._del": ["1"], + "p.related_scenarios": ["legal, services"], + "status": ["draft"], + }, + } + ] + ), + ) + self.assertEqual(response.status_code, 200, response.text) + meta = response.json()["snapshot"]["model"]["meta"] + self.assertEqual(meta["benefits"], ["Second"]) + self.assertEqual(meta["cta"]["href"], {"entry": "services/ai"}) + self.assertEqual(meta["related_scenarios"], ["legal", "services"]) + self.assertFalse(meta["featured"]) + + def test_duplicate_uses_current_editor_and_cas_both_files(self): + source = self.snap.source.replace("Telegram-боты", "My candidate", 1) + response = self.ui("duplicate", self.payload(source=source, id="bots-copy")) + self.assertEqual(response.status_code, 200, response.text) + copy = response.json()["snapshot"] + self.assertEqual(copy["model"]["meta"]["status"], "draft") + self.assertEqual(copy["model"]["meta"]["title"], "My candidate (копия)") + self.assertEqual(copy["model"]["meta"]["slug"], "bots-copy") + self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source) + self.assertEqual(self.api("duplicate", self.payload(id="bots-copy")).status_code, 409) + (self.site / self.snap.path).write_text(self.snap.source + "\nchanged") + self.assertEqual(self.api("duplicate", self.payload(id="bots-another")).status_code, 409) + self.assertFalse((self.site / "content/services/bots-another.md").exists()) + self.assertEqual(self.api("duplicate", self.payload(id="../outside")).status_code, 422) + + def test_delete_requires_saved_archive_cas_and_history(self): + self.assertEqual(self.api("delete").status_code, 422) + # Unsaved status does not authorize deleting a published file. + self.assertEqual( + self.api( + "delete", self.payload(source=self.snap.source.replace("published", "archived")) + ).status_code, + 422, + ) + snapshot = self.svc.save_source( + "bots", self.snap.source.replace("published", "archived"), self.snap.etag, self.ctx + ) + self.assertEqual(self.api("delete").status_code, 409) + response = self.api("delete", {"source": snapshot.source, "etag": snapshot.etag}) + self.assertEqual(response.status_code, 200, response.text) + self.assertTrue(response.json()["deleted"]) + self.assertFalse((self.site / self.snap.path).exists()) + history = list((self.site / ".engine/history").rglob("*")) + self.assertTrue(any(p.is_file() for p in history)) + + def test_after_commit_audit_failure_reports_committed_copy_or_deleted_flag(self): + with patch.object( + self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable") + ): + with self.assertLogs("uvicorn.error", level="ERROR") as logs: + response = self.api("duplicate", self.payload(id="bots-copy")) + self.assertEqual(response.status_code, 500) + self.assertEqual(response.json()["error"]["committed"]["id"], "bots-copy") + self.assertTrue(any("Traceback" in item for item in logs.output)) + copy_svc = EntryService(self.site, collection="services") + snapshot = copy_svc.get("bots-copy") + with patch.object( + self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable") + ): + response = self.api( + "delete", {"source": snapshot.source, "etag": snapshot.etag}, identity="bots-copy" + ) + self.assertEqual(response.status_code, 500) + self.assertTrue(response.json()["error"]["deleted"]) + self.assertFalse((self.site / snapshot.path).exists()) + + def test_live_is_release_html_and_assets_not_current_workspace(self): + build_site(self.site, self.dist) + manifest = json.loads((self.dist / "current/manifest.json").read_text()) + self.assertEqual(manifest["entry_routes"]["services/bots"], "/services/bots/") + self.assertIn(self.snap.path, manifest["entry_sources"]) + response = self.api( + "update", + self.payload( + preview_version="live", + preview_view="page", + source=self.snap.source.replace("Telegram-боты", "Only workspace", 1), + ), + ) + self.assertEqual(response.status_code, 200, response.text) + preview = response.json()["preview"] + self.assertIn("Telegram-боты", preview["html"]) + self.assertNotIn("Only workspace", preview["html"]) + result = self.client.get(preview["url"]) + self.assertEqual(result.status_code, 200) + self.assertIn("script-src 'none'", result.headers["content-security-policy"]) + from urllib.parse import parse_qs, urlsplit + + token = parse_qs(urlsplit(preview["url"]).query)["token"][0] + folder, _meta = self.app.state.previews.authorize(preview["snapshot"], token) + self.assertTrue(list((folder / "assets").glob("site.*.css"))) + self.assertEqual(self.client.get(preview["url"].split("?")[0]).status_code, 403) + card = self.api("update", self.payload(preview_version="live", preview_view="card")).json()[ + "preview" + ] + self.assertFalse(card["url"]) + self.assertIn("карточка", card["message"]) + + def test_comparison_uses_unsaved_candidate_and_old_release_is_unknown(self): + build_site(self.site, self.dist) + self.assertFalse( + next( + e for e in self.svc.get("bots").schema["content"]["entries"] if e["slug"] == "bots" + )["changed"] + ) + candidate = self.svc.validate_source("bots", self.snap.source + "\nunsaved", self.snap.etag) + self.assertTrue( + next(e for e in candidate.schema["content"]["entries"] if e["slug"] == "bots")[ + "changed" + ] + ) + manifest_file = self.dist / "current/manifest.json" + manifest = json.loads(manifest_file.read_text()) + del manifest["entry_sources"] + del manifest["entry_routes"] + manifest_file.write_text(json.dumps(manifest)) + result = self.svc.get("bots").schema["content"] + self.assertFalse(result["comparison_available"]) + self.assertIsNone(result["entries"][0]["changed"]) + live = self.api("update", self.payload(preview_version="live")).json()["preview"] + self.assertFalse(live["url"]) + self.assertIn("snapshots", live["message"]) + + def test_empty_new_draft_has_real_card_without_inventing_saved_title(self): + snap = self.svc.create("empty-draft", "", None, self.ctx) + response = self.api( + "update", + {"source": snap.source, "etag": snap.etag, "preview_view": "card"}, + identity="empty-draft", + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertIsNone(response.json()["preview_error"]) + self.assertIn("empty-draft", response.json()["preview"]["html"]) + self.assertNotIn("title", parse((self.site / snap.path).read_text())[0]) + + def test_auth_csrf_and_validation_failures_have_visible_json_contract(self): + response = self.ui("check", csrf="bad") + self.assertEqual(response.status_code, 403) + self.assertTrue(response.json()["error"]["request_id"]) + self.assertEqual(self.api("update", self.payload(preview_view="fake")).status_code, 422) + self.client.cookies.clear() + self.assertEqual(self.ui("delete").status_code, 401) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_publication.py b/tests/test_publication.py new file mode 100644 index 0000000..5f28d25 --- /dev/null +++ b/tests/test_publication.py @@ -0,0 +1,397 @@ +"""Publication contract: real candidates, private provenance, CAS and immutable live.""" + +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from fastapi.testclient import TestClient + +from site_engine.build.pipeline import build_site, hash_tree +from site_engine.services.auth import hash_password +from site_engine.services.documents import EditorContext +from site_engine.services.publication import PublicationService +from site_engine.web.app import create_app + +ROOT = Path(__file__).resolve().parents[1] + + +class PublicationTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.password = "publication test password" + cls.password_hash = hash_password(cls.password, n=2**10) + + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="publication-test-") + self.addCleanup(tmp.cleanup) + self.work = Path(tmp.name) + self.site, self.dist, self.state = (self.work / n for n in ("site", "dist", "state")) + shutil.copytree( + ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine") + ) + env = patch.dict( + os.environ, + { + "SITE_ROOT": str(self.site), + "SITE_DIST": str(self.dist), + "SITE_STATE_DIR": str(self.state), + "SITE_ADMIN_LOGIN": "admin", + "SITE_ADMIN_PASSWORD_HASH": self.password_hash, + "SITE_SECRET_KEY": "publication-test-secret-" * 4, + "SITE_COOKIE_SECURE": "0", + "SITE_ADMIN_ORIGIN": "", + "SITE_PREVIEW_ORIGIN": "", + }, + ) + env.start() + self.addCleanup(env.stop) + self.app = create_app() + self.client = TestClient(self.app) + self.addCleanup(self.client.close) + cookie = self.app.state.auth.login("admin", self.password, "testclient") + self.client.cookies.set("se_session", cookie) + self.app.state.api_credentials["test"] = (cookie, "testclient") + self.principal = self.app.state.auth.authenticate(cookie) + self.ctx = EditorContext(self.principal, "testclient") + self.csrf = self.app.state.auth.csrf_token(self.principal) + self.svc = PublicationService(self.site, self.dist, self.state, self.app.state.auth.audit) + + def api(self, method="GET", path="", payload=None): + return self.client.request( + method, + "/admin/api/v1/publication" + path, + json=payload, + headers={"Authorization": "Bearer test"}, + ) + + def ui(self, operation, payload=None, csrf=None): + return self.client.post( + "/admin/publication/" + operation, + data={ + "csrf": self.csrf if csrf is None else csrf, + "payload": json.dumps(payload or {}), + }, + headers={"Origin": "http://testserver", "Accept": "application/json"}, + ) + + def build(self): + r = self.api("POST", "/build") + self.assertEqual(r.status_code, 200, r.text) + return r.json() + + def activate(self, candidate, base=None, comment="Проверенный релиз"): + return self.api( + "POST", "/activate", {"id": candidate["id"], "expected_live": base, "comment": comment} + ) + + def edit(self, rel="pages/index.md", old="Студия автоматизации", new="Новая студия"): + path = self.site / rel + source = path.read_text() + if old not in source: + source += "\n" + new + else: + source = source.replace(old, new) + path.write_text(source) + + def test_original_screen_and_api_only_adapter_static_and_csrf(self): + r = self.client.get("/admin/publish") + self.assertEqual(r.status_code, 200, r.text) + self.assertIn("data-publication-root", r.text) + for name in ( + "publication.css", + "publication-adapter.css", + "publication.js", + "publication-icons.json", + ): + self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200, name) + before = self.app.state.api_calls + self.assertEqual(self.ui("validate").status_code, 200) + self.assertEqual(self.app.state.api_calls - before, 1) + self.assertEqual(self.ui("build", csrf="bad").status_code, 403) + self.assertEqual(self.client.get("/admin/publication/build").status_code, 405) + self.assertEqual(self.client.get("/admin/publication/unknown").status_code, 404) + + def test_build_never_activates_and_private_snapshots_never_in_dist(self): + initial = hash_tree(self.site) + c = self.build() + self.assertIsNone(self.svc.current()) + self.assertEqual(hash_tree(self.site), initial) + self.assertTrue((self.dist / c["id"] / "index.html").is_file()) + self.assertFalse((self.dist / c["id"] / "pages").exists()) + self.assertFalse((self.dist / c["id"] / "content").exists()) + self.assertNotIn("sources", self.svc.manifest(c["id"])) + self.assertIn("content/services/automation.md", self.svc.provenance(c["id"])["sources"]) + state = self.api().json() + self.assertTrue(state["candidate"]["fresh"]) + self.assertTrue(state["history"][0]["candidate"]) + self.assertEqual(state["builds"][0]["status"], "ready") + + def test_activate_exact_existing_output_and_no_rebuild(self): + c = self.build() + output = hash_tree(self.dist / c["id"]) + with patch( + "site_engine.services.publication.build_site", + side_effect=AssertionError("must not rebuild"), + ): + r = self.activate(c) + self.assertEqual(r.status_code, 200, r.text) + self.assertEqual(self.svc.current(), c["id"]) + self.assertEqual(hash_tree(self.dist / c["id"]), output) + state = self.api().json() + self.assertIsNone(state["candidate"]) + self.assertFalse(state["changes"]) + self.assertEqual(state["history"][0]["comment"], "Проверенный релиз") + + def test_stale_source_and_replaced_candidate_cannot_activate_or_rollback(self): + c = self.build() + self.edit() + self.assertFalse(self.api().json()["candidate"]["fresh"]) + self.assertEqual(self.activate(c).status_code, 409) + self.assertEqual( + self.api("POST", "/rollback", {"id": c["id"], "expected_live": None}).status_code, 422 + ) + newer = self.build() + self.assertNotEqual(c["id"], newer["id"]) + self.assertEqual(self.activate(c).status_code, 409) + self.assertIsNone(self.svc.current()) + + def test_engine_resources_and_output_tampering_invalidate_candidate(self): + c = self.build() + with patch( + "site_engine.services.publication.render_fingerprint", return_value="changed-engine" + ): + self.assertFalse(self.api().json()["candidate"]["fresh"]) + self.assertEqual(self.activate(c).status_code, 409) + (self.dist / c["id"] / "index.html").write_text("tampered") + self.assertEqual(self.activate(c).status_code, 422) + self.assertIsNone(self.svc.current()) + + def test_live_cas_and_rollback_do_not_touch_workspace(self): + a = self.build() + self.assertEqual(self.activate(a).status_code, 200) + self.edit() + b = self.build() + self.assertEqual(self.activate(b, base="20000101T000000-12345678").status_code, 409) + self.assertEqual(self.activate(b, base=a["id"]).status_code, 200) + before = hash_tree(self.site) + r = self.api("POST", "/rollback", {"id": a["id"], "expected_live": b["id"]}) + self.assertEqual(r.status_code, 200, r.text) + self.assertEqual(self.svc.current(), a["id"]) + self.assertEqual(hash_tree(self.site), before) + self.assertEqual( + self.api("POST", "/rollback", {"id": b["id"], "expected_live": b["id"]}).status_code, + 409, + ) + self.assertTrue(self.api().json()["changes"]) + + def test_comparison_actual_text_added_deleted_assets_and_old_release_unknown(self): + a = self.build() + self.activate(a) + self.edit() + (self.site / "assets/new.txt").write_text("new asset") + (self.site / "assets/hero.webp").unlink() + state = self.api().json() + rows = {x["path"]: x for x in state["changes"]} + self.assertEqual(rows["pages/index.md"]["kind"], "modified") + self.assertEqual(rows["assets/new.txt"]["kind"], "new") + self.assertEqual(rows["assets/hero.webp"]["kind"], "deleted") + diff = self.api(path="/compare?path=pages/index.md").json() + self.assertNotEqual(diff["before"]["source"], diff["after"]["source"]) + (self.state / "publication/releases" / f"{a['id']}.json").unlink() + state = self.api().json() + self.assertFalse(state["comparison_available"]) + self.assertTrue(all(x["kind"] == "unknown" for x in state["changes"])) + self.assertIsNone(self.api(path="/compare?path=pages/index.md").json()["before"]) + + def test_candidate_diff_is_immutable_after_workspace_change(self): + a = self.build() + self.activate(a) + self.edit() + self.build() + before = self.api(path="/candidate-diff").json() + (self.site / "assets/not-in-candidate.txt").write_text("later") + after = self.api(path="/candidate-diff").json() + self.assertEqual(before, after) + self.assertNotIn("assets/not-in-candidate.txt", json.dumps(after)) + + def test_validation_and_failed_strict_render_preserve_live_and_previous_candidate(self): + a = self.build() + self.activate(a) + self.edit() + b = self.build() + with ( + patch( + "site_engine.core.render.Renderer.render", + side_effect=RuntimeError("real render probe"), + ), + self.assertLogs("uvicorn.error", level="ERROR") as captured, + ): + r = self.api("POST", "/build") + self.assertEqual(r.status_code, 500) + self.assertIn("real render probe", "\n".join(captured.output)) + self.assertTrue(r.json()["error"]["request_id"]) + state = self.api().json() + self.assertEqual(state["current"], a["id"]) + self.assertEqual(state["candidate"]["id"], b["id"]) + self.assertEqual(state["builds"][0]["status"], "failed") + self.edit( + "pages/index.md", "status: published", "status: published\nlayout: missing-layout" + ) + r = self.api("POST", "/validate") + self.assertEqual(r.status_code, 200, r.text) + self.assertGreater(r.json()["errors"], 0) + self.assertEqual(self.api("POST", "/build").status_code, 422) + self.assertEqual(self.svc.current(), a["id"]) + + def test_passive_snapshot_is_real_build_with_assets_and_no_site_scripts(self): + c = self.build() + self.edit() + r = self.api("POST", "/preview", {"id": c["id"], "route": "/"}) + self.assertEqual(r.status_code, 200, r.text) + preview = r.json() + page = self.client.get(preview["url"]) + self.assertEqual(page.status_code, 200) + self.assertNotIn("