runloopable / web /s71_frontend_contracts.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8729c1d verified
Raw History Blame Contribute Delete
41.6 kB
"""Shared host contracts for the Catalog, grid, Map and application owning gates."""
from pathlib import Path
import re
WEB = Path(__file__).resolve().parent
def catalog_host_faults(grid: str, loader: str, map_view: str, catalog: str, host: str) -> list[str]:
# S85-T53: Application resolution lives in customer-grid/applicationHost.ts (`host`).
checks = {
"registry discriminator": 'applicationTemplateSurface(addressedDefinition) === "catalog"' in host
and 'applicationTemplateSurface(resolvedApplication) === "catalog"' in host,
"Map controls withheld before and after Catalog resolution":
'(!applicationRef || (resolvedApplicationMatches && applicationTemplateSurface(resolvedApplication) !== "catalog"))' in grid
and '(!hostOwnsDisplay || !!addressedDefinition)' in grid,
"only registry Routing owns Routes": 'resolvedApplicationMatches && applicationTemplateSurface(resolvedApplication) === "route"' in grid,
"Catalog has no route event listener": bool(re.search(r'useEffect\(\(\) => \{\s*if \(!routeApplicationSurface\) return;\s*const openRoute', grid)),
"cold App lookup precedes row admission": -1 < grid.find('useApplicationHost(') < grid.find('} = useCustomerData(scope,')
and grid.find('const addressedDefinition') < grid.find('} = useCustomerData(scope,')
# S78-T17 (C4): a Competitor watch App also reads no source rows.
and bool(re.search(r'const legacyRowsEnabled = !isPagedOdooApplication && '
r'(?:!isCompetitorWatchApplication &&\s+)?'
r'\(!isApplicationSurface \|\| !!addressedDefinition\)', host))
and 'rowsEnabled: legacyRowsEnabled' in host and 'rowsEnabled: applicationHost.rowsEnabled' in grid,
"Catalog disables legacy rows and subscriptions": 'options.rowsEnabled === false ? EMPTY_APPLICATION_PAYLOAD' in loader
and 'const suppliedPayload = embeddedPayload !== undefined' in loader
and 'if (suppliedPayload || STREAMLIT_COMPONENT) return; // the caller owns refresh' in loader,
"Catalog mount independent of a legacy field": '(applicationHost.paged || fieldByKey.get(lockedKey))' in grid
and 'if (!props.field)' in map_view,
"typed page supplies the real drawer": 'onCatalogData={acceptCatalogData}' in grid
and 'if (applicationHost.paged) return applicationHost.pagedRead?.rows ?? []' in grid
and 'onData={props.onCatalogData}' in map_view and 'onData?.(data.fields, data.allRows)' in catalog,
"Routing shares the paged source admission": 'const isPagedOdooApplication = isCatalogApplication || isRoutingApplication' in host
and '(applicationHost.routing || !serverWindowed)' in grid,
}
return [name for name, ok in checks.items() if not ok]
def catalog_host_scan() -> int:
paths = ['src/customer-grid/CustomerGrid.tsx', 'src/customer-grid/useCustomerData.ts',
'src/customer-grid/MapView.tsx', 'src/apps/catalog/CatalogApp.tsx', 'src/customer-grid/applicationHost.ts']
sources = [(WEB / path).read_text(encoding='utf-8') for path in paths]
faults = catalog_host_faults(*sources)
for name in faults:
print('FAIL S71 Catalog host: ' + name)
controls = [
(0, 'applicationTemplateSurface(resolvedApplication) !== "catalog"', 'true'),
(0, '(!hostOwnsDisplay || !!addressedDefinition)', 'true'),
(0, 'resolvedApplicationMatches && applicationTemplateSurface(resolvedApplication) === "route"', 'true'),
(0, 'if (!routeApplicationSurface) return;\n const openRoute', 'const openRoute'),
(0, 'rowsEnabled: applicationHost.rowsEnabled', 'rowsEnabled: true'),
(0, '(applicationHost.paged || fieldByKey.get(lockedKey))', 'fieldByKey.get(lockedKey)'),
(0, 'onCatalogData={acceptCatalogData}', ''),
(1, 'options.rowsEnabled === false ? EMPTY_APPLICATION_PAYLOAD', 'false ? EMPTY_APPLICATION_PAYLOAD'),
(3, 'onData?.(data.fields, data.allRows)', 'onData?.(data.fields, data.rows)'),
(4, 'const isPagedOdooApplication = isCatalogApplication || isRoutingApplication',
'const isPagedOdooApplication = isCatalogApplication'),
]
for index, old, new in controls:
mutant = sources.copy()
# A control removes every copy of its anchor: a second copy keeps the contract green.
mutant[index] = mutant[index].replace(old, new)
if mutant[index] == sources[index] or not catalog_host_faults(*mutant):
faults.append('control did not fail: ' + old)
print('FAIL NC S71 Catalog host: ' + old)
else:
print('ok NC S71 Catalog host: ' + old)
if not faults:
print('PASS S71 Catalog host: 9 contracts, 10 removal controls')
return int(bool(faults))
def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool = True) -> dict:
"""Cold real Shell opens with held metadata, unavailable legacy rows and served-JS controls."""
import json
from playwright.sync_api import sync_playwright
from verify_w45_data_applications import AppRoutingFixture
from verify_catalog import s76_t09_fixture_record, s76_t09_template_registry
class CatalogHostFixture(AppRoutingFixture):
def __init__(self):
super().__init__()
self.catalog = s76_t09_fixture_record()
self.catalog["pages"][3]["bindings"]["products"] = ["WF-1", "CS-2"]
self.typed_cursors = []
self.named_reads = []
self.fields.extend([{"key": key, "label": key, "type": kind, "source": "odoo"}
for key, kind in (("stock", "text"), ("list_price", "int"),
("category", "text"), ("description", "text"))])
self.applications[0]["fieldMap"].update(sku="stock", price="list_price",
category="category", description="description")
for row in self.rows:
row.update(stock="Mapped sku", list_price=19.975,
category="Mapped category", description="Mapped description")
self.original_workspace = __import__("copy").deepcopy(self.workspace)
def route(self, route):
from urllib.parse import urlsplit
request = route.request
path = urlsplit(request.url).path.removeprefix("/api/v1/")
result = None
if path == "typed/openapi.json":
properties = {field["key"]: {"type": "number" if field["type"] in ("int", "number") else "string"}
for field in self.fields}
properties["pid"] = {"type": "integer"}
result = {"components": {"schemas": {"Record_customer_data": {"properties": properties}}}}
elif path == "typed/databases/customer_data/schema":
result = {"database": "customer_data", "fields": self.fields, "source_kind": "runtime_cache",
"source_sync": "synced", "source_synced_at": None}
elif path == "typed/databases/customer_data/query":
body = request.post_data_json
self.typed_cursors.append(body.get("cursor"))
filters = (body.get("filters") or {}).get("nodes", [])
named = [node for node in filters if node.get("op") == "eq" and node.get("colId") in ("code", "pid")]
if named:
self.named_reads.extend(node["value"] for node in named)
rows = [row for row in self.rows if all(str(row.get(node["colId"])) == str(node["value"]) for node in named)]
more = False
else:
tail = body.get("cursor") == "fixture-next"
rows = self.rows[1:2] if tail else self.rows[:1]
more = bool(self.rows) and not tail
result = {"database": self.database, "fields": self.fields, "records": rows,
"page": {"returned": len(rows), "has_more": more,
"next_cursor": "fixture-next" if more else None}}
elif request.method == "GET" and path == "apps/app-fixture/catalogs":
result = {"catalogs": [self.catalog] if self.catalog else [], "nextCursor": None}
elif request.method == "GET" and path == "catalogs/catalog-six":
result = {"catalog": self.catalog}
elif request.method == "GET" and path == "catalogs/templates":
result = s76_t09_template_registry()
result["kinds"][3]["templates"][0]["slots"] = [
"title", "body", "products", "price", "sku", "category", "description"]
if result is None:
return super().route(route)
self.requests.append({"path": path, "method": request.method})
route.fulfill(status=200, content_type="application/json", body=json.dumps(result))
out_dir.mkdir(parents=True, exist_ok=True)
evidence = {"checks": [], "controls": [], "errors": []}
def check(name, value):
if not value:
raise AssertionError(name)
evidence["checks"].append(name)
def no_controls(page):
return page.locator('.cg-map-settings').count() == 0 and page.get_by_text('Bubble size', exact=True).count() == 0 \
and page.get_by_role('button', name='Routes', exact=True).count() == 0
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=True)
try:
cases = ['catalog', 'empty-source', 'mobile'] + (['settings-discriminator', 'route-listener', 'legacy-loader'] if negative_controls else [])
for case in cases:
fixture = CatalogHostFixture()
if case == 'empty-source':
fixture.rows = []
fixture.catalog = None
fixture.applications[0]['capabilities']['edit'] = True
fixture.legacy_unavailable = True
fixture.hold_registry = True
context = browser.new_context(viewport={"width": 390 if case == 'mobile' else 1440, "height": 1000})
context.add_init_script("""window.catalogRouteListeners = [];
const ordinaryAdd = window.addEventListener;
window.addEventListener = function(type, ...args) {
if (type === 'aios:route-open') window.catalogRouteListeners.push(type);
return ordinaryAdd.call(this, type, ...args);
};""")
context.route('**/api/**', fixture.route)
applied = []
if case in ('settings-discriminator', 'route-listener', 'legacy-loader'):
old, new = ('applicationTemplateSurface(resolvedApplication) !== "catalog"', 'true') if case == 'settings-discriminator' \
else ('rowsEnabled: applicationHost.rowsEnabled', 'rowsEnabled: true') if case == 'legacy-loader' \
else (r'if \(!routeApplicationSurface\) return;\s*const openRoute', 'const openRoute')
def mutate(route):
response = route.fetch()
source = response.text()
if case == 'route-listener':
source, hits = re.subn(old, new, source)
else:
hits = source.count(old)
source = source.replace(old, new, 1)
check('exact mutation target', hits == 1)
applied.append(True)
route.fulfill(response=response, body=source)
context.route('**/src/customer-grid/CustomerGrid.tsx*', mutate)
page = context.new_page()
page.on('pageerror', lambda error: evidence['errors'].append(str(error)))
try:
page.goto(base_url + '/#/app?database=customer_data&application=app-fixture')
page.locator('.shell-side').wait_for(timeout=30000)
if case != 'legacy-loader':
page.locator('.cg-shell').wait_for(timeout=30000)
else:
for _ in range(20):
if any(request['path'] == 'customers' for request in fixture.requests):
break
page.wait_for_timeout(100)
page.wait_for_timeout(400)
check('held registry has no Map/Bubble size/Routes', no_controls(page))
if case == 'route-listener':
check('route-listener guard removal registers a Catalog handler', bool(applied)
and page.evaluate('window.catalogRouteListeners.length') > 0)
evidence['controls'].append(case)
fixture.release_registry()
continue
check('held registry registers no route-open handler', page.evaluate('window.catalogRouteListeners.length') == 0)
early_legacy = any(request['path'] == 'customers' for request in fixture.requests)
if case == 'legacy-loader':
check('legacy loader mutation reaches unavailable endpoint', bool(applied) and early_legacy)
evidence['controls'].append(case)
fixture.release_registry()
continue
check('held registry has no legacy rows', not early_legacy)
fixture.release_registry()
page.locator('.cg-catalog-library').wait_for(timeout=30000)
check('Catalog library withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0)
if case == 'empty-source':
check('empty source opens the empty library', page.get_by_text('No catalogs yet', exact=True).count() == 1
and page.get_by_role('button', name='New catalog', exact=True).count() == 1
and page.locator('.cg-catalog-library-card').count() == 0)
check('empty source preserves the saved View', not fixture.view_events
and fixture.workspace == fixture.original_workspace)
page.screenshot(path=str(out_dir / 'catalog-empty-source.png'), full_page=True)
continue
page.get_by_role('button', name='Open Seasonal collection', exact=True).click()
page.locator('.cg-catalog-page-thumb[data-page-kind="grid"]').click()
page.locator('.cg-catalog-canvas .cg-catalog-product-open').first.wait_for(timeout=30000)
page.wait_for_timeout(600)
if case == 'settings-discriminator':
check('Catalog discriminator removal fails controls absence', bool(applied) and not no_controls(page))
evidence['controls'].append(case)
continue
check('resolved Catalog has no Map/Bubble size/Routes', no_controls(page))
check('resolved Catalog registers no route-open handler', page.evaluate('window.catalogRouteListeners.length') == 0)
check('six editor page kinds remain available',
page.locator('.cg-catalog-page-thumb').evaluate_all("nodes => nodes.map(node => node.dataset.pageKind)")
== ['cover', 'toc', 'product', 'grid', 'section', 'closing'])
check('typed first page never walks the next cursor', None in fixture.typed_cursors
and 'fixture-next' not in fixture.typed_cursors)
check('saved products resolve by named reads', {'WF-1', 'CS-2'}.issubset(set(fixture.named_reads)))
check('saved products from both source pages painted', sorted(page.locator('.cg-catalog-canvas .cg-catalog-product-open').evaluate_all(
"nodes => nodes.map(node => node.getAttribute('aria-label').slice(5))"))
== ['Cedar Supply', 'Willow Floral'])
before = page.locator('.cg-catalog-canvas').inner_text()
evidence['mapped_products'] = before
check('Catalog registry keeps every optional product role',
all(value in before for value in
('19.975', 'Mapped sku', 'Mapped category', 'Mapped description')))
page.evaluate("window.dispatchEvent(new CustomEvent('aios:route-open', {detail:{routeId:'refused-route'}}))")
page.wait_for_timeout(200)
check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-catalog-canvas').inner_text() == before)
check('Catalog editor withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0)
if case == 'mobile':
geometry = page.locator('.cg-catalog-canvas').bounding_box()
check('390px editor keeps a usable full-width canvas', geometry is not None
and geometry['width'] >= 250 and geometry['x'] + geometry['width'] <= 391)
check('390px editor preserves the shared App frame',
page.locator('.cg-app-frame-header').count() == 1
and page.get_by_role('link', name='Back to Apps', exact=True).count() == 1)
heading = page.locator('.cg-catalog-record-head h2').evaluate(
'node => {const range=document.createRange(); range.selectNodeContents(node); const r=range.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};}')
actions = page.locator('.cg-catalog-record-head button').evaluate_all(
'nodes => nodes.map(node => {const r=node.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};})')
check('390px catalog title does not overlap its actions', len(actions) >= 3 and all(
heading['x'] + heading['width'] <= action['x'] or action['x'] + action['width'] <= heading['x']
or heading['y'] + heading['height'] <= action['y'] or action['y'] + action['height'] <= heading['y']
for action in actions))
page.screenshot(path=str(out_dir / 'catalog-editor-390.png'), full_page=True)
page.locator('.cg-catalog-canvas').get_by_role('button', name='Open Cedar Supply', exact=True).click()
page.locator('.cg-record-modal').wait_for(timeout=10000)
check('real typed tail card drawer', 'Cedar Supply' in page.locator('.cg-record-modal').inner_text())
check('unavailable legacy endpoint never requested', not any(request['path'] == 'customers' for request in fixture.requests))
check('saved View bytes and writes preserved', not fixture.view_events and fixture.workspace == fixture.original_workspace)
evidence['requests'] = fixture.requests
page.screenshot(path=str(out_dir / 'catalog-cold-drawer.png'), full_page=True)
finally:
context.close()
for surface in ('data-map', 'route', 'legacy-catalog'):
fixture = CatalogHostFixture() if surface == 'route' else AppRoutingFixture()
fixture.config['display'] = {'mode': 'map'}
fixture.workspace['views'][0]['config']['display'] = {'mode': 'map'}
if surface == 'legacy-catalog':
display = {'mode': 'catalog',
'catalogs': fixture.applications[0]['config']['display']['catalogs']}
fixture.config['display'] = display
fixture.workspace['views'][0]['config']['display'] = display
fixture.original_workspace = __import__('copy').deepcopy(fixture.workspace)
if surface == 'route':
fixture.legacy_unavailable = True
fixture.fields.extend([{'key': 'lat', 'label': 'Latitude', 'type': 'number', 'source': 'odoo'},
{'key': 'lon', 'label': 'Longitude', 'type': 'number', 'source': 'odoo'}])
for index, row in enumerate(fixture.rows):
row.update({'lat': 40.7 + index / 100, 'lon': -74.0 + index / 100})
fixture.applications[0]['templateKind'] = 'route'
fixture.applications[0]['fieldMap'] = {'title': 'name', 'latitude': 'lat', 'longitude': 'lon'}
fixture.applications[0]['config'] = {'display': {'mode': 'map'}}
context = browser.new_context(viewport={"width": 390 if surface == 'legacy-catalog' else 1440, "height": 1000})
context.route('**/api/**', fixture.route)
# Keep the product's offline map; a synthetic transport cannot make an outward tile read.
context.route('https://tile.openstreetmap.org/**', lambda route: route.abort())
page = context.new_page()
try:
page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface != 'route'
else '/#/app?database=customer_data&application=app-fixture'))
if surface == 'legacy-catalog':
page.locator('.cg-cat-stage').wait_for(timeout=30000)
stage = page.locator('.cg-cat-stage').bounding_box()
rail = page.locator('.cg-cat-rail').bounding_box()
check('390px legacy rail collapses above a usable page', stage is not None and rail is not None
and stage['width'] >= 200 and stage['x'] + stage['width'] <= 391
and rail['height'] <= 129 and stage['y'] >= rail['y'] + rail['height'])
check('Data Catalog keeps its own footer', page.locator('.cg-grid-footer').count() == 1)
page.screenshot(path=str(out_dir / 'catalog-legacy-390.png'), full_page=True)
continue
page.locator('.cg-map-settings').wait_for(timeout=30000)
check(surface + ' keeps Map settings', page.get_by_text('Bubble size', exact=True).count() > 0)
if surface == 'route':
page.locator('.cg-mapview.cg-app-route-surface').wait_for(timeout=30000)
page.wait_for_timeout(600)
check('Routing keeps Routes rail', page.get_by_text('Routes', exact=True).count() > 0)
check('cold Routing has no legacy customer request', not any(request['path'] == 'customers' for request in fixture.requests))
check('cold Routing reads one typed page', fixture.typed_cursors == [None])
page.evaluate("window.dispatchEvent(new CustomEvent('aios:route-open', {detail:{routeId:'fixture-route'}}))")
page.wait_for_timeout(200)
check('Routing route event keeps its Map surface', page.locator('.cg-map-settings').count() == 1)
page.screenshot(path=str(out_dir / (surface + '.png')), full_page=True)
finally:
context.close()
check('no uncaught Catalog errors', not evidence['errors'])
finally:
browser.close()
(out_dir / 'catalog-host.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8')
print(f"PASS S71 Catalog host mounted: {len(evidence['checks'])} checks, {len(evidence['controls'])} controls")
return evidence
def client_amend_contracts() -> int:
"""Execute the edited callbacks with held acknowledgements and whole-batch refusals."""
import subprocess
script = r'''
const fs = require("fs"), vm = require("vm"), ts = require("typescript"), assert = require("node:assert/strict");
const grid = ts.createSourceFile("grid.tsx", fs.readFileSync("src/customer-grid/CustomerGrid.tsx", "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const bridge = ts.createSourceFile("bridge.ts", fs.readFileSync("src/customer-grid/apiBridge.ts", "utf8"), ts.ScriptTarget.Latest, true);
const display = ts.createSourceFile("display.ts", fs.readFileSync("src/customer-grid/display.ts", "utf8"), ts.ScriptTarget.Latest, true);
let checks = 0;
function check(value, why) { assert.ok(value, why); checks++; }
function declaration(file, name) {
let found;
function visit(node) {
if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node)) && node.name?.getText(file) === name) found = node;
ts.forEachChild(node, visit);
}
visit(file); assert.ok(found, "missing executable " + name);
return ts.isVariableDeclaration(found) ? "const " + found.getText(file) + ";" : found.getText(file).replace(/^export\s+/, "");
}
function bind(name, context, file = grid) {
const source = declaration(file, name) + "\nglobalThis.subject = " + name + ";";
const js = ts.transpileModule(source, {compilerOptions:{target:ts.ScriptTarget.ES2022, module:ts.ModuleKind.CommonJS}}).outputText;
const box = {useCallback: fn => fn, ...context};
vm.runInNewContext(js, box); return box.subject;
}
function pure(name, context = {}, file = grid) { return bind(name, context, file); }
async function run() {
const numericOrUndefined = pure("numericOrUndefined", {}, display);
const numberWriteRefusal = pure("numberWriteRefusal", {numericOrUndefined}, display);
const numberBatchRefusal = pure("numberBatchRefusal", {numberWriteRefusal});
const number = {key:"amount", label:"Amount", type:"currency", format:{currencySymbol:"EUR", allowNegative:false}};
const fields = [number, {key:"note",label:"Note",type:"text"}];
const writes = [], entries = [], toasts = [];
const ctx = {fields, numberBatchRefusal, currentValue:()=> "before",
patchOverlay:(...args)=>writes.push(args), recordCells:(...args)=>entries.push(args),
TOAST_EVENT:"toast", CustomEvent: class {constructor(type, init) {this.type=type;this.detail=init.detail;}},
window:{dispatchEvent:event=>toasts.push(event)}};
const single = bind("patchAndRecord", ctx), batch = bind("patchManyAndRecord", ctx);
single(1, {amount:"-1",note:"must stay unchanged"});
check(writes.length === 0 && entries.length === 0 && toasts.at(-1).detail.tone === "error", "single negative is a C4 refusal before writes or undo");
batch([{pid:1,updates:{amount:"5"}},{pid:2,updates:{amount:"Infinity"}}], "paste");
check(writes.length === 0 && entries.length === 0, "mixed valid and invalid paste is atomic");
for (const value of ["", "0", "125.6789"]) single(1, {amount:value});
check(writes.length === 3 && entries.length === 3, "blank, zero and unrounded valid writes retain undo");
const changedFields = [{...number, format:{...number.format, allowNegative:true}}];
bind("patchAndRecord", {...ctx,fields:changedFields})(1,{amount:"-5"});
check(writes.length === 4, "current field policy admits a valid negative");
let fetched = 0, closed = 0, busy = 0;
const noop = () => {};
await bind("applyBulkUpdate", {...ctx, bulkField:number,bulkSelectedCount:20,bulkValue:"-2",
clearSelection:noop,dropTableRowsCache:noop,patchManyAndRecord:batch,requestWindow:noop,scope:"ut_fixture",
selectedPids:new Set([1]),serverBulkPending:false,serverFilteredSelection:{token:"selection"},
windowRequest:noop,setServerBulkPending:()=>busy++,setBulkUpdateOpen:()=>closed++,fetch:()=>fetched++})();
check(fetched === 0 && closed === 0 && busy === 0, "server filtered bulk refuses before request, busy state or dialog dismissal");
const buildOverlayField = pure("buildOverlayField", {DEFAULT_SUMMED_TYPES:[],slugify:pure("slugify")});
for (const value of [0,false,""]) check(buildOverlayField("Default","text",[],{defaultValue:value}).defaultValue === value, "falsy default survives constructor");
check(Object.hasOwn(buildOverlayField("Clear","text",[],{defaultValue:null}),"defaultValue"), "explicit default clear retains property presence");
const createdDefinitions = [];
let createdFields = [];
const create = bind("createField",{canAddField:true,scopeChoice:false,isUserTable:true,scope:"ut_fixture",
buildOverlayField,insertColumn:noop,saveField:()=>{throw Error("wrong definition door");},stampFieldEdit:noop,stampFieldDelete:noop,
setFields:update=>{createdFields=update(createdFields);},
addTableField:(_scope,definition)=>{createdDefinitions.push(definition);return new Promise(()=>{});}});
for (const [kind,value] of [["text",""],["int",0],["checkbox",false],["text",null]])
create("Default",kind,null,"end",undefined,undefined,{defaultValue:value});
check(createdDefinitions.slice(0,4).map(field=>JSON.stringify(field.defaultValue)).join() === '"",0,false,null',
"field creation forwards blank, zero, false and explicit clear through the definition body");
create("Choice","select",null,"end",["Active"],undefined,{defaultValue:"Active"});
create("Date","date",null,"end",undefined,undefined,{defaultValue:"2026-10-19"});
check(createdDefinitions[4].defaultValue === "Active" && createdDefinitions[5].defaultValue === "2026-10-19",
"select and date defaults use the same field creation body");
const patches = [];
const old = {key:"amount",label:"Amount",type:"int",source:"overlay",custom:true,defaultValue:0};
const retype = bind("retypeField", {fieldByKey:new Map([["amount",old]]),saveField:()=>{throw Error("wrong definition door");},
scope:"ut_fixture",isUserTable:true,emitHostEvent:noop,isUserSchemaField:()=>true,
patchTableField:async(_scope,_key,patch)=>{patches.push(patch);return null;},setFields:noop,signal:noop});
retype("amount","int"); retype("amount","int",[],{defaultValue:null});
check(patches[0].defaultValue === 0 && patches[1].defaultValue === null, "retype preserves zero or sends explicit clear on the schema PATCH");
let pending = [], overlays = {}, undo = {past:[],future:[]}, resolveAdd, request;
const scope = "ut_fixture", workspaceScopeRef = {current:scope};
const setPendingRows = update => {pending = update(pending);};
const setOverlayEdits = update => {overlays = update(overlays);};
const acceptPendingRow = bind("acceptPendingRow",{scope,workspaceScopeRef,setPendingRows,setOverlayEdits});
const undoBook = {current:{}}, stackFor=()=>undo, pushUndo=(_state,entry)=>{undo={...undo,past:[...undo.past,entry]};return undo;};
const defaults = [{key:"name",type:"text",defaultValue:"base"},{key:"zero",type:"int",defaultValue:0},
{key:"tick",type:"checkbox",defaultValue:false},{key:"choice",type:"select",defaultValue:"Active"},
{key:"starts",type:"date",defaultValue:"2026-11-01"},{key:"date",type:"date",defaultValue:"2026-10-19"},{key:"denied",type:"text",defaultValue:"hidden",denied:true}];
const append = bind("appendRow", {canMutateRecords:true,scope,seedValues:()=>({name:"seed",date:""}),mintRid:()=>7,
fields:defaults,payload:{viewer:{username:"qa"}},mayEditField:field=>!field.denied,
setPendingRows,setNewRowPid:noop,addTableRow:(...args)=>{request=args;return new Promise(resolve=>{resolveAdd=resolve;});},
acceptPendingRow,workspaceScopeRef,undoBook,stackFor,pushUndo});
const adding = append();
check(pending[0].zero === "0" && pending[0].tick === "False" && pending[0].name === "seed" && pending[0].date === "" && pending[0].choice === "Active" && pending[0].starts === "2026-11-01"
&& !Object.hasOwn(pending[0],"denied"), "authorized defaults paint immediately below explicit seeds");
check(request[1].zero === "0" && request[1].tick === "False" && request.length === 3, "append sends painted defaults with ordinary restore=false call");
overlays[7]={name:"typed while pending"};
resolveAdd({rid:"8",pid:8,values:{name:"server",sequence:"51",creator:"qa"}});
await adding;
check(pending[0].pid === 8 && pending[0].sequence === "51" && overlays[8].name === "typed while pending" && !overlays[7],
"acknowledgement supplies generated cells and moves later local overlay to returned identity");
check(undo.past[0].rows[0].values.zero === "0" && undo.past[0].rows[0].rid === "8", "append undo captures defaults and accepted identity");
const stale = [], restores = [], deleted = [];
const restoreEntry = {kind:"rowAdd",table:scope,rows:[{rid:"9",values:{name:"restored",sequence:"old",creator:"forged",modified:"old",modifier:"forged"}}]};
let resolveRestore;
const restoreRowsRef = {current:[]};
const applyEntry = bind("applyEntry", {fields:[{key:"sequence",type:"autonumber"},{key:"creator",type:"created_by"},
{key:"modified",type:"last_modified_time"},{key:"modifier",type:"last_modified_by"}],
AUDIT_FIELD_TYPES:["created_by","last_modified_time","last_modified_by"],directed:entry=>entry,patchOverlay:noop,
withdrawPending:ids=>{pending=pending.filter(row=>!ids.map(Number).includes(row.pid));},emitHostEvent:noop,
acceptPendingRow,workspaceScopeRef,setPendingRows,setOverlayEdits,rowsRef:restoreRowsRef,mintRid:()=>11,addTableRow:(...args)=>{restores.push(args);return new Promise(resolve=>{resolveRestore=resolve;});},
deleteTableRow:async(_table,rid)=>{deleted.push(rid);return true;},signal:(...args)=>stale.push(args),
ROWS_STALE_EVENT:"stale",TOAST_EVENT:"toast",describe:()=>"undo",applyingUndo:{current:false}});
const restoring = applyEntry(restoreEntry,"forward");
const optimistic = pending.find(row=>row.pid === 9);
check(optimistic && Object.keys(optimistic).sort().join() === "name,pid"
&& Object.keys(restores[0][1]).join() === "name" && restores[0][3] === true, "all four generated kinds stay out of restore request and optimistic cells");
resolveRestore({rid:"10",pid:10,values:{sequence:"52",creator:"original",modified:"fresh",modifier:"qa"}});
await restoring;
check(pending.find(row=>row.pid === 10)?.creator === "original" && !stale.some(event=>event[0] === "stale"),
"restored creator, counter and modifier paint from ack without a full refresh");
await applyEntry({...restoreEntry,kind:"rowDelete"},"forward");
check(deleted[0] === "10" && !pending.some(row=>row.pid === 10), "redo deletes the accepted restored identity without a ghost");
restoreRowsRef.current = pending;
const occupied = {kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"other restored row"}}]};
const colliding = applyEntry(occupied,"forward");
check(pending.find(row=>row.pid === 8)?.name === "server" && pending.find(row=>row.pid === 11)?.name === "other restored row",
"occupied restore keeps the existing pending row and paints a separate temporary identity");
resolveRestore({rid:"12",pid:12,values:{sequence:"53",creator:"original"}});
await colliding;
check(pending.some(row=>row.pid === 8) && pending.some(row=>row.pid === 12) && occupied.rows[0].rid === "12",
"collision acknowledgement and next undo retain both real identities");
restoreRowsRef.current = pending;
const refusedRestore=applyEntry({kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"refused"}}]},"forward");
resolveRestore(null); await refusedRestore;
check(pending.some(row=>row.pid === 8) && !pending.some(row=>row.pid === 11),
"a refused collision withdraws only its temporary row and preserves the occupied record");
const linkSelectionPredicate = pure("linkSelectionPredicate");
const restriction = {conj:"and",nodes:[{colId:"status",op:"eq",value:"Active"}]};
const candidate = {filterConj:"or",filters:[{colId:"name",op:"contains",value:"Cedar"},{colId:"name",op:"contains",value:"Willow"}]};
const narrowed = linkSelectionPredicate(candidate,restriction);
check(narrowed.filterConj === "and" && narrowed.filters[0].children === restriction.nodes
&& narrowed.filters[1].conj === "or" && narrowed.filters[1].children === candidate.filters, "candidate OR search remains inside the immutable AND restriction");
check(linkSelectionPredicate({filters:[]},restriction).filters[0].children === restriction.nodes, "clearing search cannot relax link restriction");
const hookSlots = [], windowCalls = [], completions = [];
let cursor = 0, unavailableCondition = false;
const hookContext = {
useRef:initial=>{const i=cursor++;return hookSlots[i]??=( {current:initial} );},
useState:initial=>{const i=cursor++;if (!(i in hookSlots)) hookSlots[i]=initial;
return [hookSlots[i],value=>{hookSlots[i]=typeof value === "function" ? value(hookSlots[i]) : value;}];},
useCallback:fn=>fn,useEffect:()=>{},linkSelectionPredicate,ROWS_STALE_EVENT:"stale",
unresolvedConditions:()=>unavailableCondition ? 1 : 0,window:ctx.window,CustomEvent:ctx.CustomEvent,TOAST_EVENT:"toast",
fetchTableWindow:(table,request)=>{windowCalls.push({table,request});return new Promise(resolve=>completions.push(resolve));}};
const windowHook = pure("useRecordIdWindow",hookContext);
const renderWindow = filter=>{cursor=0;return windowHook("ut_target",undefined,null,undefined,false,false,filter);};
const firstWindow = renderWindow(restriction);
check(firstWindow.payload === null && firstWindow.pending, "restricted picker withholds an unfiltered initial payload");
firstWindow.requestWindow({...candidate,offset:50,limit:50,search:"Cedar"});
check(windowCalls[0].request.filterConj === "and" && windowCalls[0].request.filters[0].children === restriction.nodes
&& windowCalls[0].request.offset === 50 && windowCalls[0].request.search === "Cedar",
"real window callback sends immutable restriction with search and page before server counts");
const changedRestriction={conj:"and",nodes:[{colId:"status",op:"eq",value:"Ready"}]};
const secondWindow=renderWindow(changedRestriction);
completions[0]({rows:[{pid:1}],counts:{matched:99}}); await Promise.resolve();
check(renderWindow(changedRestriction).payload === null, "stale response from an older link condition cannot populate the picker");
secondWindow.requestWindow({offset:0,limit:50,filters:[],search:""});
completions[1]({fields:[{key:"status",type:"text"}],rows:[{pid:2}],counts:{matched:1}}); await Promise.resolve();
check(renderWindow(changedRestriction).payload?.counts.matched === 1, "fresh restricted response owns rows and count");
unavailableCondition = true;
const toastCount = toasts.length;
renderWindow(changedRestriction).requestWindow({offset:0,limit:50,filters:[]});
completions[2]({fields:[],rows:[{pid:3}],counts:{matched:99}}); await Promise.resolve();
check(renderWindow(changedRestriction).payload === null && toasts.length === toastCount + 1 && toasts.at(-1).detail.tone === "error",
"an unavailable restriction withholds broader rows and counts with a C4 refusal");
const posts = [];
let reply = {rid:"12",pid:12,values:{pid:999,zero:0,blank:null,tick:false,private:{secret:"no"}}};
const add = bind("addTableRow", {API_V1:"/api/v1",CREDENTIALS:"include",JSON_HEADERS:{"Content-Type":"application/json"},
fetch:async(_url,init)=>{posts.push(JSON.parse(init.body));return {ok:true};},handledSession:()=>false,
readJson:async()=>reply,dropTableRowsCache:noop,signal:noop,TOAST_EVENT:"toast",DATA_ERROR_EVENT:"error"}, bridge);
const ack = await add(scope,{name:"new"},12);
check(posts[0].restore === false && ack.pid === 12 && ack.values.zero === 0 && ack.values.blank === null && ack.values.tick === "False"
&& !Object.hasOwn(ack.values,"pid") && !Object.hasOwn(ack.values,"private"), "ordinary create sends false and normalizes authorized scalar acknowledgement cells");
reply={rid:"12",pid:12}; const legacy=await add(scope,{},12,true);
check(posts[1].restore === true && !Object.hasOwn(legacy,"values"), "restore transport tolerates an older identity-only acknowledgement");
console.log("PASS W3 client amendments: " + checks + "/" + checks + " checks");
}
run().catch(error=>{console.error(error.stack);process.exitCode=1;});
'''
result = subprocess.run(["node", "-"], input=script, text=True, cwd=WEB, timeout=45)
return result.returncode
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--client", action="store_true")
parser.add_argument("--base-url")
parser.add_argument("--out-dir", type=Path, default=Path("/tmp/aios-w3-host"))
args = parser.parse_args()
if args.client:
result = client_amend_contracts()
if result or not args.base_url:
raise SystemExit(result)
if args.base_url:
from urllib.parse import urlsplit
if urlsplit(args.base_url).hostname not in ("127.0.0.1", "localhost", "::1"):
parser.error("The synthetic fixture requires a local Vite origin")
mounted_catalog_host(args.base_url, args.out_dir)
else:
raise SystemExit(catalog_host_scan())