Release 11.0 (full): passage readings held back when the sentence leaves out a question word, the judge names the step it refused, the part format v1, anyone's sealed test, the sleep cycle, and the six orbiters as files in the pack (part 2)
Browse filesHead oracle_release_runtime_w575. Root 5985f38d66bcdedbdedb74db90432675a32ddce9dfe2d196b3282c40581d889b. Solana anchor: pending Ben's signature. Internal week (seven simulated nights): 0 parts admitted, 0 new wrong, published as measured. Full changelog: CHANGELOG_11.md.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- orbiters/chameleon/scripts/laya_worker.pyAdded+223
- orbiters/chameleon/scripts/linux_worker_bootstrap.pyAdded+26
- orbiters/chameleon/scripts/list_filter_artifact.mjsAdded+46
- orbiters/chameleon/scripts/list_filter_artifact.test.mjsAdded+38
- orbiters/chameleon/scripts/list_filter_observation.mjsAdded+62
- orbiters/chameleon/scripts/list_filter_observation.test.mjsAdded+42
- orbiters/chameleon/scripts/list_filter_operator.mjsAdded+51
- orbiters/chameleon/scripts/list_filter_operator.test.mjsAdded+75
- orbiters/chameleon/scripts/local.pyAdded+140
- orbiters/chameleon/scripts/lock_laya_runtime.pyAdded+30
- orbiters/chameleon/scripts/metafold_acceptance.mjsAdded+29
- orbiters/chameleon/scripts/metafold_acceptance.test.mjsAdded+27
- orbiters/chameleon/scripts/metafold_arithmetic_candidate.mjsAdded+130
- orbiters/chameleon/scripts/metafold_arithmetic_candidate.test.mjsAdded+98
- orbiters/chameleon/scripts/metafold_clone.mjsAdded+50
- orbiters/chameleon/scripts/metafold_clone.test.mjsAdded+59
- orbiters/chameleon/scripts/metafold_correspondence.mjsAdded+45
- orbiters/chameleon/scripts/metafold_correspondence.test.mjsAdded+36
- orbiters/chameleon/scripts/metafold_dependencies.test.mjsAdded+20
- orbiters/chameleon/scripts/metafold_laya_shadow.mjsAdded+28
- orbiters/chameleon/scripts/metafold_laya_shadow.test.mjsAdded+13
- orbiters/chameleon/scripts/metafold_observation.mjsAdded+22
- orbiters/chameleon/scripts/metafold_observation.test.mjsAdded+21
- orbiters/chameleon/scripts/metafold_package.mjsAdded+85
- orbiters/chameleon/scripts/metafold_trafficcop_shadow.mjsAdded+22
- orbiters/chameleon/scripts/migrate_local_behavior.pyAdded+80
- orbiters/chameleon/scripts/module_dependencies.mjsAdded+52
- orbiters/chameleon/scripts/module_dependencies.test.mjsAdded+22
- orbiters/chameleon/scripts/module_dependency_driver.mjsAdded+4
- orbiters/chameleon/scripts/module_references.mjsAdded+40
- orbiters/chameleon/scripts/module_references.test.mjsAdded+24
- orbiters/chameleon/scripts/multipage_contract.test.mjsAdded+36
- orbiters/chameleon/scripts/package_backend_release.pyAdded+22
- orbiters/chameleon/scripts/package_cli.pyAdded+17
- orbiters/chameleon/scripts/package_curated_2048.pyAdded+43
- orbiters/chameleon/scripts/package_gallery_six.pyAdded+35
- orbiters/chameleon/scripts/package_repository_pilot.pyAdded+80
- orbiters/chameleon/scripts/package_saved_demos.pyAdded+48
- orbiters/chameleon/scripts/plan_dom_dependencies.pyAdded+87
- orbiters/chameleon/scripts/plan_saved_build.pyAdded+29
- orbiters/chameleon/scripts/plan_saved_mount.pyAdded+38
- orbiters/chameleon/scripts/prepare_jev_presentation.mjsAdded+32
- orbiters/chameleon/scripts/prepare_laya_artifact.pyAdded+119
- orbiters/chameleon/scripts/prepare_verifier_tunnel.pyAdded+29
- orbiters/chameleon/scripts/probe_repository_contracts.pyAdded+81
- orbiters/chameleon/scripts/provision_box_a.pyAdded+210
- orbiters/chameleon/scripts/provision_production_verifier.pyAdded+30
- orbiters/chameleon/scripts/provision_rehearsal_verifier.pyAdded+31
- orbiters/chameleon/scripts/publish_source_style_gallery.pyAdded+48
69 unmodified lines707172737469 unmodified linesroot/organs10/kqa/kb.json filter=lfs diff=lfs merge=lfs -textroot/organs10/kqa/train.json filter=lfs diff=lfs merge=lfs -textroot/organs10/kqa/val.json filter=lfs diff=lfs merge=lfs -textorbiters/deepspace/oracle7-deepspace.pdf filter=lfs diff=lfs merge=lfs -textorbiters/deepspace/paper/oracle7-deepspace.pdf filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Opt-in local JSONL worker. No web registration, source effects or dispatch authority."""
import ctypesimport hashlibimport importlib.metadataimport jsonimport osimport socketimport subprocessimport sysimport timefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]REV = "1c5edc17a7acd8701df6fc341c0d179f1c62c982"SDK = "42626c348753fbb17572a813127df2278a1ec527"ARTIFACT = ROOT / ".local/laya-artifacts" / REVMANIFEST_SHA = "2a243c7e2fcebdc6485d5ff102078a2c80933344808e8b3088478c3350b5f82d"LOCK_SHA = "694789eb1f9fff5825e55b0437cdf539d0e12da6e9b918b81a507c29ceb0d4e5"HEADROOM = 3_601_526_354
def sha(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest()
def memory_available(): if os.name != "nt": raise RuntimeError("This runtime lock is Windows-only")
class Memory(ctypes.Structure): _fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong)] + [ (name, ctypes.c_ulonglong) for name in ( "total", "available", "page_total", "page_available", "virtual_total", "virtual_available", "extended", ) ]
value = Memory() value.length = ctypes.sizeof(value) if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(value)): raise RuntimeError("Memory inspection failed") return value.available
def preflight(): lock = ROOT / "docs/evidence-laya/runtime-windows.lock.txt" if sha(lock) != LOCK_SHA or sha(ARTIFACT / "manifest.json") != MANIFEST_SHA: raise RuntimeError("Pinned manifest or dependency lock changed") manifest = json.loads((ARTIFACT / "manifest.json").read_text()) for name, record in manifest["files"].items(): if sha(ARTIFACT / "runtime" / name) != record["runtime_sha256"]: raise RuntimeError("Runtime artifact hash mismatch: " + name) for line in lock.read_text().splitlines(): if line.startswith("#") or not line: continue name, version = line.split(" @ ", 1)[0], line.rsplit(" # ", 1)[1] if importlib.metadata.version(name) != version: raise RuntimeError("Installed dependency version drift: " + name) source = ROOT / ".local/laya-sdk" if ( subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip() != SDK or subprocess.check_output(["git", "-C", str(source), "status", "--porcelain"], text=True).strip() ): raise RuntimeError("SDK source drift") available = memory_available() return { "status": "READY_FOR_LOAD" if available >= HEADROOM else "INSUFFICIENT_LOAD_HEADROOM", "available_bytes": available, "required_bytes": HEADROOM, "artifact_revision": REV, "lock_sha256": LOCK_SHA, "weights_loaded": False, }
def main(): checked = preflight() if "--preflight" in sys.argv: print(json.dumps(checked)) return tokenizer_only = "--tokenizer-only" in sys.argv if not tokenizer_only and checked["status"] != "READY_FOR_LOAD": print(json.dumps(checked)) return os.environ.update( HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", TOKENIZERS_PARALLELISM="false", OMP_NUM_THREADS="1" )
def deny(*_args, **_kwargs): raise RuntimeError("Worker outbound networking disabled")
socket.socket.connect = deny socket.socket.connect_ex = deny socket.getaddrinfo = deny sys.path[:0] = [str(ROOT / "packages/core"), str(ROOT / ".local/laya-sdk")] import torch from chameleon_core.contracts import digest from chameleon_core.laya_contract import DecisionRequest, normalize, prepare from chameleon_core.laya_input_budget import check_sequence from laya import load from laya.common import build_sequence, render_options, serialize_state from transformers import AutoTokenizer
torch.set_num_threads(1) torch.set_num_interop_threads(1) config = json.loads((ARTIFACT / "runtime/rl_agent_config.json").read_text()) tokenizer = AutoTokenizer.from_pretrained( ARTIFACT / "runtime/tokenizer", local_files_only=True, trust_remote_code=False ) agent = None if not tokenizer_only: if memory_available() < HEADROOM: print(json.dumps({"status": "INSUFFICIENT_LOAD_HEADROOM", "weights_loaded": False})) return agent = load(str(ARTIFACT / "runtime"), device="cpu") for _ in range(16): line = sys.stdin.buffer.readline(65537) if not line: break try: if len(line) > 65536: raise ValueError("REQUEST_BYTE_BUDGET") envelope = json.loads(line) if ( set(envelope) != {"request", "budget_ms"} or type(envelope["budget_ms"]) is not int or not 1 <= envelope["budget_ms"] <= 30000 ): raise ValueError("REQUEST_ENVELOPE") body = envelope["request"] if "deadline_monotonic" in body: raise ValueError("FOREIGN_MONOTONIC_CLOCK") body["deadline_monotonic"] = time.monotonic() + envelope["budget_ms"] / 1000 request = DecisionRequest.model_validate_json(json.dumps(body)) prepared = prepare(request) occupancy = {} for key, question in prepared["questions"].items(): occupancy[key] = check_sequence( tokenizer, request.state, { "t": question["type"], "ins": question["instructions"], "crit": question.get("criteria"), }, max_len=config["max_len"], head_max_len=config["head_max_len"], build_sequence=build_sequence, render_options=render_options, serialize_state=serialize_state, ) if any(not value["accepted"] for value in occupancy.values()): print( json.dumps( { "status": "INPUT_TRUNCATED", "request_id": request.request_id, "occupancy": occupancy, "inference_executed": False, } ), flush=True, ) continue if time.monotonic() >= request.deadline_monotonic: raise ValueError("LAYA_DEADLINE_EXPIRED") if tokenizer_only: result = { "status": "TOKENIZER_CHECK_ONLY", "request_id": request.request_id, "occupancy": occupancy, "inference_executed": False, } else: started = time.monotonic() raw = agent.predict(request.state, prepared["questions"]) if prepared["questions"] else None binding = { key: getattr(request, key) for key in ( "request_id", "run_id", "instance_id", "form_version", "state_version", "observation_hash", ) } result = normalize( request, raw, expected_input_hash=prepared["input_hash"], current_binding=binding, now_monotonic=time.monotonic(), artifact_id=MANIFEST_SHA, actual_device=agent.device.type, actual_dtype=str(agent.dtype).replace("torch.", ""), ) result.update( status="COMPLETED", prediction_wall_seconds=time.monotonic() - started, occupancy=occupancy, ) result["request_digest"] = digest(request.model_dump(exclude={"deadline_monotonic"})) print(json.dumps(result, allow_nan=False), flush=True) except (ValueError, KeyError, TypeError, RuntimeError, OverflowError) as exc: print( json.dumps({"status": "REJECTED", "error": str(exc)[:500], "action_dispatch": False}), flush=True, ) if len(line) > 65536: break
if __name__ == "__main__": main()1234567891011121314151617181920212223242526"""Enter the service's delegated cgroup subtree, then run the trusted verifier."""import osfrom pathlib import Pathimport runpyimport sys
def prepare(): if sys.platform != 'linux' or os.getuid() == 0: raise RuntimeError('NON_ROOT_LINUX_WORKER_REQUIRED') relative = next(line[3:] for line in Path('/proc/self/cgroup').read_text().splitlines() if line.startswith('0::')) parent = Path('/sys/fs/cgroup') / relative.lstrip('/') if not parent.name.startswith('chameleon-verifier') or not parent.name.endswith('.service'): raise RuntimeError('DEDICATED_VERIFIER_SERVICE_REQUIRED') leaf = parent/'supervisor' leaf.mkdir(exist_ok=True) (leaf/'cgroup.procs').write_text(str(os.getpid())) (parent/'cgroup.subtree_control').write_text('+cpu +memory +pids') os.environ['CHAMELEON_CGROUP_ROOT'] = str(parent)
if __name__ == '__main__': prepare() sys.argv = [str(Path(__file__).with_name('verification_worker.py')), *sys.argv[1:]] runpy.run_path(sys.argv[0], run_name='__main__')12345678910111213141516171819202122232425262728293031323334353637383940414243444546/** Portable trusted-operator artifact; not an arbitrary JavaScript upload format. */import {createHash} from 'node:crypto';import {installListFilter} from './list_filter_operator.mjs';import {selectObservedListFilter} from './list_filter_observation.mjs';const sha=s=>createHash('sha256').update(s).digest('hex');
function runtime(plan) { // The executable is fixed reviewed code; target strings remain serialized data. const data=JSON.stringify(plan).replaceAll('<','\\u003c').replaceAll('\u2028','\\u2028').replaceAll('\u2029','\\u2029'); return '"use strict";\n('+installListFilter.toString()+')('+data+');\n';}
export function buildListFilterArtifact({sourceDigest,plan,receipt}) { if(!/^[a-f0-9]{64}$/.test(sourceDigest)||!selectObservedListFilter(plan,receipt,sourceDigest)) throw Error('NO_OBSERVED_COMPATIBLE_OPERATOR'); if(plan.status!=='APPLICABLE'||plan.version!=='local-list-filter-v1' ||typeof plan.inputId!=='string'||typeof plan.listId!=='string' ||!plan.inputId.length||!plan.listId.length||plan.inputId.length>200||plan.listId.length>200) throw Error('INVALID_ARTIFACT_BINDING'); const binding={status:'APPLICABLE',version:'local-list-filter-v1',inputId:plan.inputId,listId:plan.listId}; const script=runtime(binding); return {version:'trusted-list-filter-artifact-v1',sourceDigest,observationDigest:receipt.receiptDigest, plan:binding,script,scriptDigest:sha(script), scope:'Derived static-list behavior supported by finite local observations. Load only in an isolated counterpart after removing original active handlers. Not public executable admission.'};}
export function verifyListFilterArtifact(artifact,{sourceDigest,receipt}) { if(!artifact||artifact.version!=='trusted-list-filter-artifact-v1'||artifact.sourceDigest!==sourceDigest ||artifact.observationDigest!==receipt?.receiptDigest)throw Error('ARTIFACT_BINDING_MISMATCH'); const expected=buildListFilterArtifact({sourceDigest,plan:artifact.plan,receipt}); if(artifact.script!==expected.script || artifact.scriptDigest!==expected.scriptDigest) throw Error('ARTIFACT_RUNTIME_MISMATCH'); return expected;}
export function listFilterOverlay(artifact,receipt,pkg,scriptPath) { const checked=verifyListFilterArtifact(artifact,{sourceDigest:pkg?.digest,receipt}); const original=pkg?.repository?.files?.[scriptPath]; if(typeof scriptPath!=='string'||!scriptPath.endsWith('.js')||!original ||sha(Buffer.from(original.base64,'base64'))!==original.sha256) throw Error('EXISTING_SCRIPT_BINDING_REQUIRED'); if(Buffer.byteLength(checked.script)>12000)throw Error('OVERLAY_BUDGET'); return {version:'derived-file-v1',source_digest:pkg.digest,path:scriptPath, before_sha256:original.sha256,after_base64:Buffer.from(checked.script).toString('base64'), after_sha256:checked.scriptDigest,operator:'observed-local-list-filter-v1'};}1234567891011121314151617181920212223242526272829303132333435363738import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';import {chromium} from '@playwright/test';import {discoverListFilter} from './list_filter_operator.mjs';import {observeListFilter} from './list_filter_observation.mjs';import {buildListFilterArtifact,verifyListFilterArtifact} from './list_filter_artifact.mjs';
test('observed source becomes portable runtime; reload installs on fresh derived DOM; tampering refuses',async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); try { const context=await browser.newContext({serviceWorkers:'block'});await context.route('**/*',r=>r.abort()); const page=await context.newPage(); const html='<input id="find" type="search" aria-controls="list"><ul id="list"><li>Amber</li><li>Birch</li></ul>'; const sourceDigest=createHash('sha256').update(html).digest('hex'); await page.setContent(html); await page.evaluate(()=>document.getElementById('find').addEventListener('input',event=>{ const q=event.target.value.trim().toLowerCase(); document.querySelectorAll('li').forEach(e=>e.hidden=!e.textContent.toLowerCase().includes(q)); })); const plan=await page.evaluate(discoverListFilter),receipt=await observeListFilter(page,plan,sourceDigest); const artifact=JSON.parse(JSON.stringify(buildListFilterArtifact({sourceDigest,plan,receipt}))); const checked=verifyListFilterArtifact(artifact,{sourceDigest,receipt}); // Two independent counterpart loads; no source listener survives into either. for(let n=0;n<2;n++) { const derived=await context.newPage();await derived.setContent(html); await derived.addScriptTag({content:checked.script}); await derived.locator('#find').fill('irc'); assert.deepEqual(await derived.locator('li:visible').allTextContents(),['Birch']); await derived.close(); } const tampered={...artifact,script:artifact.script+'\nwindow.compromised=true;'}; tampered.scriptDigest=createHash('sha256').update(tampered.script).digest('hex'); assert.throws(()=>verifyListFilterArtifact(tampered,{sourceDigest,receipt}),/RUNTIME_MISMATCH/); assert.throws(()=>verifyListFilterArtifact(artifact,{sourceDigest:'b'.repeat(64),receipt}),/BINDING_MISMATCH/); assert.throws(()=>buildListFilterArtifact({sourceDigest,plan,receipt:{...receipt,status:'BEHAVIOR_MISMATCH'}})); }finally{await browser.close();}});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162/** Trusted adapter for an already isolated LOCAL source replay, never a live website. * Caller owns sandbox/network/resource supervision. No navigation or code injection here. */import {createHash} from 'node:crypto';const normalize=s=>s.normalize('NFKC').toLowerCase().trim();const hash=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex');
export async function observeListFilter(page, plan, sourceDigest) { if(!/^[a-f0-9]{64}$/.test(sourceDigest) || plan?.status!=='APPLICABLE' || plan.version!=='local-list-filter-v1')throw Error('INVALID_OBSERVATION_BINDING'); // IDs remain data, not selectors. Match the explicit binding on every snapshot. const snapshot=()=>page.evaluate(({inputId,listId})=>{ const byId=id=>[...document.querySelectorAll('[id]')].filter(e=>e.id===id); const inputs=byId(inputId),lists=byId(listId); if(inputs.length!==1||lists.length!==1||inputs[0].getAttribute('aria-controls')!==listId) throw Error('OBSERVATION_BINDING_CHANGED'); const nodes=[...lists[0].children]; if(nodes.length>500)throw Error('OBSERVATION_ITEM_BUDGET'); return {value:inputs[0].value,items:nodes.map(e=>{ if(e.textContent.length>10000)throw Error('OBSERVATION_TEXT_BUDGET'); const style=getComputedStyle(e); return {text:e.textContent,visible:style.visibility!=='hidden'&&style.display!=='none'&&e.getClientRects().length>0}; })}; },plan); // Use a locator escaped by the browser's CSS.escape, never interpolate raw IDs. const selector=await page.evaluate(id=>'#'+CSS.escape(id),plan.inputId); const control=page.locator(selector); const before=await snapshot(), observations=[]; let baseline; try { await control.fill('',{timeout:2000});baseline=await snapshot(); const sample=baseline.items.find(i=>i.visible && normalize(i.text).length>=4)?.text; if(!sample)return {status:'INSUFFICIENT_EVIDENCE',sourceDigest,reason:'NO_DISCRIMINATING_TEXT'}; const word=normalize(sample),middle=word.slice(1,-1); let absent='chameleon-nonmatch'; while(baseline.items.some(i=>normalize(i.text).includes(absent)))absent+='x'; const queries=[middle,' '+word.toUpperCase()+' ',absent,'']; for(const query of queries){ await control.fill(query,{timeout:2000});const current=await snapshot(); const stable=current.items.length===baseline.items.length &¤t.items.every((i,n)=>i.text===baseline.items[n].text); const expected=baseline.items.map(i=>i.visible&&normalize(i.text).includes(normalize(query))); const actual=current.items.map(i=>i.visible); observations.push({query,expected,actual,stable}); } const compatible=observations.every(o=>o.stable&&o.actual.every((v,i)=>v===o.expected[i])); const receipt={version:'list-filter-observation-v1',sourceDigest, binding:{inputId:plan.inputId,listId:plan.listId},baseline,observations, status:compatible?'SUPPORTED_BY_PROBES':'BEHAVIOR_MISMATCH', scope:'Finite local replay probes, not full semantic equivalence; synchronous static-list profile only.'}; return {...receipt,receiptDigest:hash(receipt)}; } finally {await control.fill(before.value,{timeout:2000});}}
export function selectObservedListFilter(plan,receipt,sourceDigest) { if(!receipt || receipt.status!=='SUPPORTED_BY_PROBES')return null; const {receiptDigest,...body}=receipt; if(hash(body)!==receiptDigest || receipt.sourceDigest!==sourceDigest || receipt.binding.inputId!==plan.inputId || receipt.binding.listId!==plan.listId)return null; // This binding guards accidental stale/mutated receipts, not malicious receipt fabrication. return {operator:'local-list-filter-v1',plan:structuredClone(plan),sourceDigest,receiptDigest};}123456789101112131415161718192021222324252627282930313233343536373839404142import test from 'node:test';import assert from 'node:assert/strict';import {chromium} from '@playwright/test';import {discoverListFilter,installListFilter} from './list_filter_operator.mjs';import {observeListFilter,selectObservedListFilter} from './list_filter_observation.mjs';
const html='<input type="search" id="q" aria-controls="items"><ul id="items"><li>Amber</li><li>Birch</li></ul>';for(const mode of ['substring','prefix','exact','inert'])test('source observation discriminates '+mode,async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); try {const context=await browser.newContext({serviceWorkers:'block'});await context.route('**/*',r=>r.abort()); const page=await context.newPage();await page.setContent(html); // Independent authored reference behavior, not the reconstruction operator. await page.evaluate(mode=>{ const q=document.getElementById('q'),items=[...document.querySelectorAll('li')]; q.addEventListener('input',()=>{ if(mode==='inert')return; const key=q.value.trim().toLowerCase(); items.forEach(item=>{const text=item.textContent.toLowerCase(); item.hidden=key!=='' && !(mode==='substring'?text.includes(key):mode==='prefix'?text.startsWith(key):text===key);}); }); },mode); const plan=await page.evaluate(discoverListFilter); await page.locator('#q').fill('Birch'); const receipt=await observeListFilter(page,plan,'a'.repeat(64)); assert.equal(await page.locator('#q').inputValue(),'Birch'); assert.equal(receipt.status,mode==='substring'?'SUPPORTED_BY_PROBES':'BEHAVIOR_MISMATCH'); assert.equal(Boolean(selectObservedListFilter(plan,receipt,'a'.repeat(64))),mode==='substring'); if(mode==='substring') { const selected=selectObservedListFilter(plan,receipt,'a'.repeat(64)); // Fresh derived DOM has no source listeners; apply only the observed-compatible operator. const derived=await context.newPage();await derived.setContent(html); await derived.evaluate(installListFilter,selected.plan); await derived.locator('#q').fill('irc'); assert.deepEqual(await derived.locator('li:visible').allTextContents(),['Birch']); await derived.locator('#q').fill(''); assert.equal(await derived.locator('li:visible').count(),2); assert.equal(selectObservedListFilter(plan,receipt,'b'.repeat(64)),null); receipt.observations[0].actual=[false,false]; assert.equal(selectObservedListFilter(plan,receipt,'a'.repeat(64)),null); } }finally{await browser.close();}});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051/** Trusted local derived-counterpart operator. Never install in the source website. * The caller explicitly requests local case-insensitive substring filtering. * aria-controls supplies the binding, NOT proof that the source used this behavior. */export function discoverListFilter() { const controls = [...document.querySelectorAll('input[type="search"],input[role="searchbox"]')]; if (controls.length !== 1) return {status:'UNSUPPORTED',reason:'AMBIGUOUS_SEARCH_CONTROL'}; const input = controls[0]; const target = input.getAttribute('aria-controls'); if (!input.id || !target || /\s/.test(target)) return {status:'UNSUPPORTED',reason:'EXPLICIT_BINDING_REQUIRED'}; const unique = id => [...document.querySelectorAll('[id]')].filter(e=>e.id===id); const lists = unique(target); if (unique(input.id).length!==1 || lists.length!==1) return {status:'UNSUPPORTED',reason:'NON_UNIQUE_BINDING'}; const list = lists[0]; if (!list.matches('ul,ol,[role="list"]') || list.contains(input) || input.disabled || input.readOnly || input.hasAttribute('oninput') || input.hasAttribute('onchange')) return {status:'UNSUPPORTED',reason:'UNSUPPORTED_CONTROL_OR_LIST'}; const items = [...list.children]; if (items.length>500 || items.some(e=>!e.matches('li,[role="listitem"]') || e.textContent.length>10000)) return {status:'UNSUPPORTED',reason:'UNSUPPORTED_ITEMS_OR_BUDGET'}; return {status:'APPLICABLE',version:'local-list-filter-v1',inputId:input.id,listId:list.id, scope:'Requested local substring filter; source equivalence requires separate observations.'};}
export function installListFilter(plan) { if (!plan || plan.status!=='APPLICABLE' || plan.version!=='local-list-filter-v1') throw Error('INVALID_FILTER_PLAN'); const unique = id => [...document.querySelectorAll('[id]')].filter(e=>e.id===id); const inputs=unique(plan.inputId), lists=unique(plan.listId); if(inputs.length!==1 || lists.length!==1) throw Error('STALE_FILTER_BINDING'); const input=inputs[0],list=lists[0]; if (!input.matches('input[type="search"],input[role="searchbox"]') || input.getAttribute('aria-controls')!==list.id || !list.matches('ul,ol,[role="list"]') || list.contains(input) || input.disabled || input.readOnly || input.hasAttribute('oninput') || input.hasAttribute('onchange')) throw Error('STALE_FILTER_BINDING'); const items=[...list.children]; if(items.length>500 || items.some(e=>!e.matches('li,[role="listitem"]') || e.textContent.length>10000)) throw Error('FILTER_BUDGET'); // A caller-owned isolated DOM only: do not modify labels, markup, styles, or baseline-hidden items. const marker=Symbol.for('chameleon.local-list-filter-v1'); if(input[marker]) throw Error('FILTER_ALREADY_INSTALLED'); const baseline=items.map(e=>({element:e,hidden:e.hidden})); const normalize=value=>value.normalize('NFKC').toLowerCase().trim(); const update=()=>{ const query=normalize(input.value); for(const {element,hidden} of baseline) element.hidden=hidden || !normalize(element.textContent).includes(query); }; input.addEventListener('input',update); input[marker]=true; update(); return {status:'INSTALLED',operator:'local-list-filter-v1',items:items.length};}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';import {chromium} from '@playwright/test';import {discoverListFilter,installListFilter} from './list_filter_operator.mjs';import {evaluateContract} from './browser_contract.mjs';import {benchmarkClones} from './clone_benchmark.mjs';
const hash=s=>createHash('sha256').update(s).digest('hex');const fixtures=[ '<input id="query" type="search" aria-controls="catalog"><ul id="catalog"><li>Amber</li><li>Birch</li><li hidden>private</li></ul>', '<section><input id="term" role="searchbox" aria-controls="results"><div id="results" role="list"><article role="listitem">Amber</article><article role="listitem">Birch</article><article role="listitem" hidden>private</article></div></section>', '<main><label>Find <input id="q" type="search" aria-controls="stock"></label><ol id="stock"><li><strong>Amber</strong></li><li><span>Birch</span></li><li hidden>private</li></ol></main>',];const ids=[['query','catalog'],['term','results'],['q','stock']];const contract=(name,input,list,value,count)=>({version:'browser-contract-v1',name,steps:[ {op:'fill',selector:'#'+input,value},{op:'count',selector:'#'+list+' > :visible',equals:count}]});
test('one operator transfers across three DOM shapes through MetaFold and independent checks',async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); try { const evaluate=async(candidate,c)=>{ const {html,plan}=JSON.parse(candidate),context=await browser.newContext({serviceWorkers:'block'}); await context.route('**/*',r=>r.abort()); try {const page=await context.newPage();await page.setContent(html); if(plan)await page.evaluate(installListFilter,plan); return await evaluateContract(page,c); } finally {await context.close();} }; const targets=fixtures.map((html,i)=>({id:'shape-'+i,family:'lists',mode:'observed-page', evidenceClass:'synthetic-control',sourceDigest:hash(html),initial:JSON.stringify({html}), contracts:[contract('filter',...ids[i],'Amber',1)], finalContracts:[contract('case and whitespace',...ids[i],' BIRCH ',1), contract('missing item',...ids[i],'zzz',0),contract('reset',...ids[i],'',2)]})); const report=await benchmarkClones({targets,engineDigest:hash(discoverListFilter.toString()+installListFilter.toString()), evaluate,evaluateFinal:evaluate,repair:async({candidate})=>{ const parsed=JSON.parse(candidate);if(parsed.plan)return null; const context=await browser.newContext({serviceWorkers:'block'});await context.route('**/*',r=>r.abort()); try {const page=await context.newPage();await page.setContent(parsed.html); const plan=await page.evaluate(discoverListFilter); return plan.status==='APPLICABLE'?JSON.stringify({...parsed,plan}):null; } finally {await context.close();} }}); assert.equal(report.groups[0].firstPassComplete,0); assert.equal(report.groups[0].finalComplete,3); assert.equal(report.groups[0].independentComplete,3); assert.equal(report.groups[0].independentPassChecks,9); for(const row of report.results)assert.equal(row.resources.repairCalls,1); } finally {await browser.close();}});
test('missing/ambiguous binding and inline handler refuse; stale plan refuses',async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); try {const page=await browser.newPage(); for(const html of [fixtures[0].replace('aria-controls="catalog"',''), fixtures[0]+'<input type="search">',fixtures[0]+'<ul id="catalog"></ul>', fixtures[0].replace('type="search"','type="search" oninput="void 0"')]) { await page.setContent(html);assert.equal((await page.evaluate(discoverListFilter)).status,'UNSUPPORTED'); } await page.setContent(fixtures[0]);const plan=await page.evaluate(discoverListFilter); await page.locator('#query').evaluate(e=>e.setAttribute('aria-controls','elsewhere')); await assert.rejects(page.evaluate(installListFilter,plan),/STALE_FILTER_BINDING/); }finally{await browser.close();}});
test('clear restores only originally visible items; installation cannot duplicate',async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); try {const page=await browser.newPage();await page.setContent(fixtures[0]); const plan=await page.evaluate(discoverListFilter);await page.evaluate(installListFilter,plan); await page.locator('#query').fill('none');assert.equal(await page.locator('li:visible').count(),0); await page.locator('#query').fill('');assert.equal(await page.locator('li:visible').count(),2); assert.equal(await page.locator('li').last().getAttribute('hidden'),''); await assert.rejects(page.evaluate(installListFilter,plan),/FILTER_ALREADY_INSTALLED/); }finally{await browser.close();}});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Workspace-only runtime provisioning; never registers a Windows service."""
import argparseimport jsonimport osimport secretsimport subprocessimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]LOCAL = ROOT / ".local"BIN = LOCAL / "postgres/pgsql/bin"
def env(): value = dict(os.environ) value["PYTHONPATH"] = os.pathsep.join( str(ROOT / p) for p in ["packages/core", "packages/adapters", "apps/api", "apps/worker"] ) return value
def call(args, **kwargs): return subprocess.run([str(x) for x in args], cwd=ROOT, env=env(), check=True, **kwargs)
def setup(): LOCAL.mkdir(exist_ok=True) path = LOCAL / "runtime.json" if not path.exists(): password = secrets.token_hex(24) data = { "database_url": f"postgresql+psycopg://chameleon:{password}@127.0.0.1:55432/chameleon", "fixture_key": secrets.token_urlsafe(40), } with path.open("x") as f: json.dump(data, f) (LOCAL / "db-password").write_text(password) if not (LOCAL / "pgdata/PG_VERSION").exists(): if not (BIN / "initdb.exe").exists(): raise SystemExit("Official portable PostgreSQL binaries missing; see README") call( [ BIN / "initdb.exe", "-D", LOCAL / "pgdata", "-U", "chameleon", "--encoding=UTF8", "--locale=C", "--auth=scram-sha-256", "--pwfile", LOCAL / "db-password", ], capture_output=True, ) status = subprocess.run( [str(BIN / "pg_ctl.exe"), "-D", str(LOCAL / "pgdata"), "status"], capture_output=True, check=False ) if status.returncode: call( [ BIN / "pg_ctl.exe", "-D", LOCAL / "pgdata", "-l", LOCAL / "postgres.log", "-o", "-h 127.0.0.1 -p 55432 -c max_connections=40 -c shared_buffers=64MB", "-w", "start", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) import psycopg from psycopg import sql
cfg = json.loads(path.read_text()) admin = cfg["database_url"].replace("postgresql+psycopg", "postgresql").rsplit("/", 1)[0] + "/postgres" with psycopg.connect(admin, autocommit=True) as conn: for name in ["chameleon", "chameleon_test"]: if not conn.execute("select 1 from pg_database where datname=%s", [name]).fetchone(): conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(name))) call([sys.executable, "-m", "alembic", "upgrade", "head"]) print( "Local PostgreSQL ready on 127.0.0.1:55432; migration applied; credentials kept under ignored .local" )
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "command", choices=[ "setup", "api", "fixture", "test", "lint", "typecheck", "replay", "demo", "export-demo", "stop-db", ], ) parser.add_argument("--run") args = parser.parse_args() if args.command == "setup": setup() elif args.command in {"api", "fixture"}: module = "chameleon_api.app:factory" if args.command == "api" else "chameleon_api.fixture:factory" call( [ sys.executable, "-m", "uvicorn", module, "--factory", "--host", "127.0.0.1", "--port", "8120" if args.command == "api" else "8121", "--no-access-log", ] ) elif args.command == "test": call([sys.executable, "-m", "pytest", "-q", "--tb=short", "--junitxml=.local/test-results.xml"]) elif args.command == "lint": call( [sys.executable, "-m", "ruff", "check", "packages", "apps/api", "apps/worker", "tests", "scripts"] ) elif args.command == "typecheck": call([sys.executable, "-m", "mypy", "packages/core", "packages/adapters", "apps/api", "apps/worker"]) elif args.command == "stop-db": call([BIN / "pg_ctl.exe", "-D", LOCAL / "pgdata", "-m", "fast", "stop"]) else: call([sys.executable, "scripts/demo.py", args.command] + (["--run", args.run] if args.run else []))123456789101112131415161718192021222324252627282930"""Freeze resolved Windows wheels and hashes from successful pip installation receipts."""
import hashlibimport importlib.metadataimport jsonfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]entries = {}for name in ("laya-install-cpu.json", "laya-install-transformers.json"): report = json.loads((ROOT / ".local" / name).read_text(encoding="utf-8")) for item in report["install"]: metadata, download = item["metadata"], item["download_info"] if importlib.metadata.version(metadata["name"]) != metadata["version"]: raise RuntimeError("Receipt does not match installed version") entries[metadata["name"].lower()] = ( metadata["name"], metadata["version"], download["url"], download["archive_info"]["hashes"]["sha256"], )lines = [ "# Windows CPython 3.12 wheel lock. Install with --require-hashes --no-deps.", "# Laya SDK is the separately pinned, checked source checkout; no remote code loading.",]for name, version, url, sha in sorted(entries.values()): lines.append(f"{name} @ {url} --hash=sha256:{sha} # {version}")path = ROOT / "docs/evidence-laya/runtime-windows.lock.txt"path.write_text("\n".join(lines) + "\n", encoding="utf-8")print(json.dumps({"packages": len(entries), "lock_sha256": hashlib.sha256(path.read_bytes()).hexdigest()}))1234567891011121314151617181920212223242526272829/** Final contracts are evaluated after repair ends, never supplied to its callback. */import {createHash} from 'node:crypto';import {validateContract} from './browser_contract.mjs';
export async function evaluateAcceptance(development, contracts, evaluate) { if (!Array.isArray(contracts) || !contracts.length || contracts.length > 12) throw Error('INVALID_ACCEPTANCE_CONTRACT_SET'); const held = contracts.map(validateContract); const contractDigest = createHash('sha256').update(JSON.stringify(held)).digest('hex'); const result = {version:'metafold-acceptance-v1', contractDigest, candidateDigest:development.winner?.candidateDigest ?? null, status:'NOT_RUN', checks:[], scope:'Supplied final behavior checks only; not whole-application equivalence.'}; if (development.status !== 'PASS' || !development.winner) return result; for (const [index, contract] of held.entries()) { try { const receipt = await evaluate(development.winner.candidate, structuredClone(contract)); const passed = receipt?.status === 'PASS' && receipt.steps?.length === contract.steps.length && receipt.steps.every((s,i)=>s.step===i && s.op===contract.steps[i].op && s.status==='PASS'); result.checks.push({index,name:contract.name,status:passed?'PASS':'FAIL', reason:passed?null:'INVALID_EVALUATOR_RECEIPT'}); } catch(error) { result.checks.push({index,name:contract.name,status:'FAIL', reason:error?.assertion?'BEHAVIOR_MISMATCH':'EXECUTION_OR_OBSERVATION_FAILURE', message:String(error?.message ?? error).slice(0,500)}); } } result.status = result.checks.every(c=>c.status==='PASS') ? 'PASS' : 'FAIL'; return result;}123456789101112131415161718192021222324252627import test from 'node:test';import assert from 'node:assert/strict';import {evaluateAcceptance} from './metafold_acceptance.mjs';const contracts=[{version:'browser-contract-v1',name:'Final check',steps:[{op:'text',selector:'#result',equals:'5'}]}];const winner={status:'PASS',winner:{candidate:'frozen',candidateDigest:'abc'}};test('no development winner cannot enter acceptance',async()=>{ const result=await evaluateAcceptance({status:'FAIL'},contracts,()=>{throw Error('must not run');}); assert.equal(result.status,'NOT_RUN');});test('final mismatch rejects development winner without repair or contract mutation',async()=>{ const original=JSON.stringify(contracts); const result=await evaluateAcceptance(winner,contracts,async(candidate,contract)=>{ assert.equal(candidate,'frozen'); contract.steps[0].equals='mutated'; throw Object.assign(Error('wrong output'),{assertion:{actual:'4'}}); }); assert.equal(result.status,'FAIL');assert.equal(result.checks[0].reason,'BEHAVIOR_MISMATCH'); assert.equal(JSON.stringify(contracts),original);});test('complete receipts required and remaining checks run after failure',async()=>{ let calls=0; const result=await evaluateAcceptance(winner,[...contracts,...contracts],async()=>{ calls++; return calls===1?{status:'PASS',steps:[]}:{status:'PASS',steps:[{step:0,op:'text',status:'PASS'}]}; }); assert.equal(calls,2); assert.equal(result.status,'FAIL');assert.equal(result.checks[1].status,'PASS'); const pass=await evaluateAcceptance(winner,contracts,async()=>({status:'PASS',steps:[{step:0,op:'text',status:'PASS'}]})); assert.equal(pass.status,'PASS');});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130/** Bounded compatibility candidate construction; no target code execution. */import {createHash} from 'node:crypto';import {createRequire} from 'node:module';import {pathToFileURL} from 'node:url';import {arithmeticExpression} from './arithmetic_expression.mjs';import {validateContract} from './browser_contract.mjs';const require=createRequire(import.meta.url);const viteRequire=createRequire(require.resolve('vite/package.json'));const {parseAst}=await import(pathToFileURL(viteRequire.resolve('rolldown/parseAst')).href);const sha=bytes=>createHash('sha256').update(bytes).digest('hex');const canonical=value=>JSON.stringify(value,(_,v)=>v&&typeof v==='object'&&!Array.isArray(v) ?Object.fromEntries(Object.keys(v).sort().map(key=>[key,v[key]])):v);const failure=reason=>({candidate:null,reason});const operator='syntax-dom-text-arithmetic-compatibility-v1';
function checkedPackage(pkg){ if(!pkg||typeof pkg!=='object'||!pkg.repository||pkg.repository.version!=='frozen-public-repository-v1'|| !/^[a-f0-9]{64}$/.test(pkg.digest)||sha(canonical(pkg.repository))!==pkg.digest)throw Error('ARITHMETIC_PACKAGE_DIGEST_MISMATCH'); const records=pkg.repository.files; if(!records||typeof records!=='object'||Array.isArray(records)||Object.keys(records).length<1||Object.keys(records).length>128)throw Error('ARITHMETIC_PACKAGE_BUDGET'); const files=new Map(),seen=new Set();let total=0; for(const [name,file]of Object.entries(records)){ if(typeof name!=='string'||name.length>240||/[\\:\x00-\x1f<>"|?*]/.test(name)||name.split('/').some(part=>!part||part==='.'||part==='..')||seen.has(name.toLowerCase()))throw Error('ARITHMETIC_SOURCE_PATH_INVALID'); seen.add(name.toLowerCase()); if(typeof file.base64!=='string'||file.base64.length>699052)throw Error('ARITHMETIC_PACKAGE_BUDGET'); const body=Buffer.from(file.base64,'base64'); if(body.toString('base64')!==file.base64||body.length!==file.bytes||body.length>524288||sha(body)!==file.sha256|| createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${body.length}\0`),body])).digest('hex')!==file.git_blob_sha)throw Error('ARITHMETIC_SOURCE_BYTES_MISMATCH'); total+=body.length;if(total>4*1024*1024)throw Error('ARITHMETIC_PACKAGE_BUDGET'); files.set(name,body); } if(!files.has(pkg.repository.entry)||!Array.isArray(pkg.repository.license_files)||!pkg.repository.license_files.length||pkg.repository.license_files.some(name=>!files.has(name)))throw Error('ARITHMETIC_SOURCE_PROVENANCE_MISSING'); return files;}
function boundPattern(pattern,name){ if(!pattern)return false; if(pattern.type==='Identifier')return pattern.name===name; if(pattern.type==='RestElement')return boundPattern(pattern.argument,name); if(pattern.type==='AssignmentPattern')return boundPattern(pattern.left,name); if(pattern.type==='ArrayPattern')return pattern.elements.some(item=>boundPattern(item,name)); if(pattern.type==='ObjectPattern')return pattern.properties.some(item=>boundPattern(item.type==='RestElement'?item.argument:item.value,name)); return false;}
function property(node){ return node?.type==='MemberExpression'?(node.computed?node.property?.value:node.property?.name):null;}
function inspect(name,body){ const source=new TextDecoder('utf-8',{fatal:true}).decode(body); if(Buffer.byteLength(source)>262144)throw Error('ARITHMETIC_JS_SOURCE_BUDGET'); const tree=parseAst(source,{},name),stack=[tree],calls=[]; let nodes=0,blocked=null; while(stack.length){ const node=stack.pop();if(!node||typeof node!=='object')continue; if(++nodes>100000)throw Error('ARITHMETIC_AST_BUDGET'); if(node.type==='WithStatement')blocked='ARITHMETIC_DYNAMIC_SCOPE_UNSUPPORTED'; if((node.type==='VariableDeclarator'&&boundPattern(node.id,'eval'))|| (['FunctionDeclaration','FunctionExpression','ArrowFunctionExpression'].includes(node.type)&& (node.id?.name==='eval'||node.params.some(parameter=>boundPattern(parameter,'eval'))))|| (['ClassDeclaration','ClassExpression'].includes(node.type)&&node.id?.name==='eval')|| (node.type==='CatchClause'&&boundPattern(node.param,'eval'))|| (['ImportSpecifier','ImportDefaultSpecifier','ImportNamespaceSpecifier'].includes(node.type)&&node.local?.name==='eval'))blocked='ARITHMETIC_EVAL_BINDING_UNSUPPORTED'; if((['AssignmentExpression','UpdateExpression'].includes(node.type)&& (boundPattern(node.left||node.argument,'eval')||property(node.left||node.argument)==='eval'))|| (node.type==='CallExpression'&&['defineProperty','defineProperties','assign'].includes(property(node.callee))&& node.arguments.some(arg=>arg?.value==='eval'||arg?.type==='ObjectExpression'&&arg.properties.some(p=>(p.key?.name||p.key?.value)==='eval'))))blocked='ARITHMETIC_EVAL_WRITE_UNSUPPORTED'; if(node.type==='CallExpression'&&node.callee?.type==='Identifier'&&node.callee.name==='eval')calls.push(node); for(const child of Object.values(node))if(child&&typeof child==='object'){ if(Array.isArray(child))stack.push(...child);else stack.push(child); } } return {name,body,source,calls,blocked};}
/** Existing repair-loop adapter; contracts and source must exactly match context. * scope:'arithmetic' is an explicit capability request, not a target inference. * A failed visible "error" is a trigger for a candidate, not a causal diagnosis. */export function selectArithmeticRepair(pkg,descriptor,context,{scope,contracts}={}){ if(scope!=='arithmetic')return failure('EXPLICIT_ARITHMETIC_SCOPE_REQUIRED'); if(descriptor?.overlay||descriptor?.dependencies)return failure('ARITHMETIC_ORIGINAL_SOURCE_REQUIRED'); if(descriptor?.digest!==pkg?.digest||context?.sourceDigest!==pkg?.digest|| typeof context?.candidate!=='string'||JSON.stringify(descriptor)!==context.candidate|| context.attempt?.candidateDigest!==sha(context.candidate))return failure('ARITHMETIC_CANDIDATE_BINDING_MISMATCH'); let held,files; try{ if(!Array.isArray(contracts)||!contracts.length||contracts.length>12)throw Error('ARITHMETIC_CONTRACTS_REQUIRED'); held=contracts.map(validateContract); if(sha(JSON.stringify(held))!==context.contractDigest)throw Error('ARITHMETIC_CONTRACT_BINDING_MISMATCH'); files=checkedPackage(pkg); }catch(error){return failure(String(error.message));} const checks=context.attempt?.checks; if(!Array.isArray(checks)||checks.length!==held.length||checks.some((check,i)=>check.contractIndex!==i||check.name!==held[i].name))return failure('ARITHMETIC_CHECK_BINDING_MISMATCH'); const observed=checks.find(check=>{ const assertion=check.residual?.assertion,contract=held[check.contractIndex]; if(check.status!=='FAIL'||check.residual?.kind!=='BEHAVIOR_MISMATCH'||assertion?.actual!=='error'||!Number.isInteger(assertion.step))return false; const step=contract.steps[assertion.step]; return step&&['text','value'].includes(step.op)&&String(step.equals)===assertion.expected; }); if(!observed)return failure('ARITHMETIC_MATCHING_FAILURE_REQUIRED'); const parsed=[]; try{ for(const [name,body]of files)if(/\.(?:js|mjs)$/i.test(name))parsed.push(inspect(name,body)); }catch{return failure('ARITHMETIC_SOURCE_PARSE_UNSUPPORTED');} const blocked=parsed.find(item=>item.blocked); if(blocked)return failure(blocked.blocked); const matches=parsed.flatMap(file=>file.calls.map(call=>({file,call}))); if(matches.length!==1)return failure('ARITHMETIC_UNIQUE_EVAL_CALL_REQUIRED'); const {file,call}=matches[0],argument=call.arguments[0]; if(call.optional||call.arguments.length!==1||argument?.type!=='MemberExpression'||argument.computed|| argument.optional||!['innerText','textContent','value'].includes(argument.property?.name)||argument.object?.type!=='Identifier')return failure('ARITHMETIC_DOM_TEXT_ARGUMENT_REQUIRED'); // Inline the trusted grammar, preserving strict directives and all surrounding bytes. const replacement=`(${arithmeticExpression.toString()})(${file.source.slice(argument.start,argument.end)})`; const beforeText=file.source.slice(call.start,call.end); if(!beforeText.startsWith('eval')||!beforeText.endsWith(')'))return failure('ARITHMETIC_AST_SPAN_INVALID'); const before=Buffer.byteLength(file.source.slice(0,call.start)); const end=Buffer.byteLength(file.source.slice(0,call.end)); const after=Buffer.concat([file.body.subarray(0,before),Buffer.from(replacement),file.body.subarray(end)]); const overlay={version:'derived-file-v1',source_digest:pkg.digest,path:file.name,before_sha256:sha(file.body), after_base64:after.toString('base64'),after_sha256:sha(after),operator}; if(Buffer.byteLength(JSON.stringify(overlay))>18000)return failure('ARITHMETIC_OVERLAY_BUDGET'); return {candidate:JSON.stringify({...descriptor,overlay}),reason:'SYNTAX_BOUND_ARITHMETIC_CANDIDATE',operator, source_file:file.name,source_sha256:overlay.before_sha256, evidence:{source_digest:pkg.digest,contract_digest:context.contractDigest,candidate_digest:context.attempt.candidateDigest, contract_index:observed.contractIndex,assertion_step:observed.residual.assertion.step, start_byte:before,end_byte:end,span_sha256:sha(file.body.subarray(before,end))}, limitation:'Explicit arithmetic compatibility only. Syntactic direct eval of a named object DOM-text property; no claim that object is a DOM node, that eval caused the failure, or that arbitrary JavaScript semantics are preserved. All unchanged contracts must be rerun.'};}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';import {readFile} from 'node:fs/promises';import {selectArithmeticRepair} from './metafold_arithmetic_candidate.mjs';const sha=s=>createHash('sha256').update(s).digest('hex');const canonical=value=>JSON.stringify(value,(_,v)=>v&&typeof v==='object'&&!Array.isArray(v) ?Object.fromEntries(Object.keys(v).sort().map(k=>[k,v[k]])):v);const contracts=[{version:'browser-contract-v1',name:'Independent arithmetic result',steps:[ {op:'click',selector:'#calculate'},{op:'text',selector:'#screen',equals:'18'}]}];
function fixture(source){ const files={'nested/renamed.mjs':Buffer.from(source),'index.html':Buffer.from('<html></html>'),'LICENSE':Buffer.from('MIT authored fixture')}; const repository={version:'frozen-public-repository-v1',entry:'index.html',license_files:['LICENSE'],files:Object.fromEntries(Object.entries(files).map(([name,bytes])=>[name,{ bytes:bytes.length,base64:bytes.toString('base64'),sha256:sha(bytes),git_blob_sha:createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${bytes.length}\0`),bytes])).digest('hex')}]))}; return {digest:sha(canonical(repository)),repository};}function request(pkg,held=contracts){ const descriptor={path:'C:/frozen/package.json',digest:pkg.digest},candidate=JSON.stringify(descriptor); const context={sourceDigest:pkg.digest,contractDigest:sha(JSON.stringify(held)),candidate, attempt:{index:0,candidateDigest:sha(candidate),checks:held.map((contract,contractIndex)=>({contractIndex,name:contract.name,status:'FAIL', residual:{kind:'BEHAVIOR_MISMATCH',assertion:{step:contract.steps.length-1,expected:String(contract.steps.at(-1).equals),actual:'error'}}}))}}; return {descriptor,context,options:{scope:'arithmetic',contracts:held}};}function build(pkg,change){const args=request(pkg);change?.(args);return selectArithmeticRepair(pkg,args.descriptor,args.context,args.options);}
test('source-agnostic AST candidate preserves exact surrounding bytes and uses explicit scope',()=>{ const source='"use strict"; // 🎯 eval(comment.fake)\nconst expressionBox={textContent:"6*(2+1)"};\nconst answer=eval(expressionBox.textContent);'; const pkg=fixture(source),before=structuredClone(pkg),result=build(pkg); assert.equal(result.reason,'SYNTAX_BOUND_ARITHMETIC_CANDIDATE'); const overlay=JSON.parse(result.candidate).overlay,after=Buffer.from(overlay.after_base64,'base64'); assert.equal(overlay.path,'nested/renamed.mjs'); assert.equal(overlay.operator,'syntax-dom-text-arithmetic-compatibility-v1'); assert.equal(sha(after),overlay.after_sha256); assert.equal(overlay.before_sha256,sha(source)); assert.equal(after.toString().startsWith(source.slice(0,source.indexOf('eval(expressionBox'))),true); assert.equal(after.toString().endsWith(')(expressionBox.textContent);'),true); assert.equal(Buffer.from(source).subarray(result.evidence.start_byte,result.evidence.end_byte).toString(),'eval(expressionBox.textContent)'); assert.deepEqual(pkg,before); assert.equal(build(pkg,args=>delete args.options.scope).reason,'EXPLICIT_ARITHMETIC_SCOPE_REQUIRED');});
test('actual frozen calculator bytes select by syntax without reviewed source hash',async()=>{ const pkg=JSON.parse(await readFile('.local/repository-pilot/calculator/frozen.json')); const result=build(pkg); assert.equal(result.reason,'SYNTAX_BOUND_ARITHMETIC_CANDIDATE'); assert.equal(JSON.parse(result.candidate).overlay.path,'js/calculate.js'); assert.equal(result.source_sha256,pkg.repository.files['js/calculate.js'].sha256);});
test('input value access transfers without accepting arbitrary properties',()=>{ const result=build(fixture('const answer=eval(field.value);')); assert.equal(result.reason,'SYNTAX_BOUND_ARITHMETIC_CANDIDATE'); assert.equal(Buffer.from(JSON.parse(result.candidate).overlay.after_base64,'base64').toString().endsWith(')(field.value);'),true); for(const argument of ['field.dataset','field.valueOf()','field["value"]']) assert.equal(build(fixture(`eval(${argument})`)).candidate,null);});
test('comments, string lookalikes, non-DOM args, optional calls and ambiguous calls refuse',()=>{ for(const [source,expected]of [ ['// eval(box.innerText)\nconst s="eval(box.innerText)";','ARITHMETIC_UNIQUE_EVAL_CALL_REQUIRED'], ['eval("6+2")','ARITHMETIC_DOM_TEXT_ARGUMENT_REQUIRED'], ['eval(box["innerText"])','ARITHMETIC_DOM_TEXT_ARGUMENT_REQUIRED'], ['eval?.(box.innerText)','ARITHMETIC_DOM_TEXT_ARGUMENT_REQUIRED'], ['eval(box.innerText);eval(other.textContent)','ARITHMETIC_UNIQUE_EVAL_CALL_REQUIRED'], ['const missing =','ARITHMETIC_SOURCE_PARSE_UNSUPPORTED'], ])assert.equal(build(fixture(source)).reason,expected,source);});
test('eval bindings, scope changes and explicit global writes are refused',()=>{ for(const source of [ 'function f(eval){return eval(box.innerText)}', 'const eval=x=>x;eval(box.innerText)', 'const {renamed:eval}=fake;eval(box.innerText)', 'try{}catch(eval){eval(box.innerText)}', 'import eval from "elsewhere";eval(box.innerText)', 'with(fake){eval(box.innerText)}', 'globalThis.eval=fake;eval(box.innerText)', 'Object.defineProperty(globalThis,"eval",{value:fake});eval(box.innerText)', ])assert.equal(build(fixture(source)).candidate,null,source);});
test('source, contract, candidate and exact failing assertion remain bound',()=>{ const pkg=fixture('eval(box.innerText)'); for(const change of [ args=>args.context.sourceDigest='f'.repeat(64), args=>args.context.contractDigest='f'.repeat(64), args=>args.context.attempt.candidateDigest='f'.repeat(64), args=>args.context.attempt.checks[0].name='Different contract', args=>args.context.attempt.checks[0].residual.assertion.expected='999', args=>args.context.attempt.checks[0].residual.assertion.actual='timeout', args=>args.context.attempt.checks[0].residual.kind='EXECUTION_OR_OBSERVATION_FAILURE', args=>args.descriptor.overlay={}, ])assert.equal(build(pkg,change).candidate,null); const bad=structuredClone(pkg);bad.repository.files['nested/renamed.mjs'].base64=Buffer.from('eval(other.innerText)').toString('base64'); bad.digest=sha(canonical(bad.repository)); assert.equal(build(bad).reason,'ARITHMETIC_SOURCE_BYTES_MISMATCH');});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** Local orchestration only. evaluate/repair must be trusted, resource-bounded adapters. */import {createHash} from 'node:crypto';import {validateContract} from './browser_contract.mjs';
const hash = text => createHash('sha256').update(text).digest('hex');const copy = value => structuredClone(value);
export async function metaFoldClone({sourceDigest, initial, contracts, evaluate, repair, maxAttempts=3}) { if (!/^[a-f0-9]{64}$/.test(sourceDigest) || !Number.isInteger(maxAttempts) || maxAttempts<1 || maxAttempts>10) throw Error('INVALID_CLONE_BUDGET_OR_SOURCE'); if (!Array.isArray(contracts) || !contracts.length || contracts.length>12) throw Error('INVALID_CLONE_CONTRACT_SET'); const held=contracts.map(validateContract); const contractDigest=hash(JSON.stringify(held)); const attempts=[], seen=new Set(); let candidate=initial; const finish=(status,winner=null)=>({version:'metafold-clone-loop-v1',sourceDigest,contractDigest,status,winner,attempts, scope:'Only supplied contracts; no claim of complete clone or autonomous synthesis.'}); for(let index=0;index<maxAttempts;index++) { if(typeof candidate!=='string'||Buffer.byteLength(candidate)>1024*1024)throw Error('INVALID_CLONE_CANDIDATE'); const candidateDigest=hash(candidate); if(seen.has(candidateDigest))return finish('STALLED'); seen.add(candidateDigest); const checks=[]; for(const [contractIndex,contract] of held.entries()) { try { // Run every contract on every candidate, including previously passing checks. const result=await evaluate(candidate,copy(contract)); const complete=result?.status==='PASS' && result?.steps?.length===contract.steps.length && result.steps.every((s,i)=>s.step===i&&s.op===contract.steps[i].op&&s.status==='PASS'); checks.push({contractIndex,name:contract.name,status:complete?'PASS':'FAIL', residual:complete?null:{kind:'INVALID_EVALUATOR_RECEIPT'}}); } catch(error) { checks.push({contractIndex,name:contract.name,status:'FAIL',residual:{ kind:error?.assertion?'BEHAVIOR_MISMATCH':'EXECUTION_OR_OBSERVATION_FAILURE', message:String(error?.message ?? error).slice(0,500), observation:error?.observation ?? null, assertion:error?.assertion?{step:error.assertion.step, expected:String(error.assertion.expected).slice(0,1000), actual:String(error.assertion.actual).slice(0,1000)}:null}}); } } const attempt={index,candidateDigest,checks}; attempts.push(attempt); if(checks.every(c=>c.status==='PASS'))return finish('PASS',{candidate,candidateDigest}); if(index+1===maxAttempts)return finish('BUDGET_EXHAUSTED'); candidate=await repair({candidate,sourceDigest,contractDigest,attempt:copy(attempt),history:copy(attempts)}); if(candidate===null)return finish('NEEDS_IMPLEMENTATION_OR_EVIDENCE'); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import test from 'node:test';import assert from 'node:assert/strict';import {chromium} from '@playwright/test';import {evaluateContract} from './browser_contract.mjs';import {metaFoldClone} from './metafold_clone.mjs';
const contract=(name,steps)=>({version:'browser-contract-v1',name,steps});const contracts=[contract('initial count',[{op:'text',selector:'#count',equals:'0'}]), contract('increment',[{op:'click',selector:'button'},{op:'text',selector:'#count',equals:'1'}])];const html=step=>`<output id="count">0</output><button onclick="document.querySelector('#count').textContent=Number(document.querySelector('#count').textContent)+${step}">Add</button>`;const base={sourceDigest:'a'.repeat(64),contracts,initial:html(0)};
test('real browser: failure drives repair; all contracts rerun; history retained',async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); const calls=[]; try { const evaluate=async(candidate,c)=>{ calls.push(c.name); const context=await browser.newContext({serviceWorkers:'block'}); await context.route('**/*',r=>r.abort()); try {const page=await context.newPage();await page.setContent(candidate);return await evaluateContract(page,c);} finally {await context.close();} }; const result=await metaFoldClone({...base,evaluate,repair:async({attempt,history})=>{ assert.equal(attempt.checks[1].residual.assertion.actual,'0'); assert.equal(history.length,1); return html(1); // Deliberately hand-authored fixture repair, not model synthesis. }}); assert.equal(result.status,'PASS');assert.equal(result.attempts.length,2); assert.equal(result.attempts[0].checks[1].status,'FAIL'); assert.deepEqual(calls,['initial count','increment','initial count','increment']); } finally {await browser.close();}});
test('cannot accept malformed receipt; repeats stall; unavailable repair is explicit',async()=>{ const evaluate=async()=>({status:'PASS'}); assert.equal((await metaFoldClone({...base,evaluate,repair:async({candidate})=>candidate})).status,'STALLED'); assert.equal((await metaFoldClone({...base,evaluate,repair:async()=>null})).status,'NEEDS_IMPLEMENTATION_OR_EVIDENCE'); assert.equal((await metaFoldClone({...base,evaluate,maxAttempts:1,repair:async()=>{throw Error('must not run');}})).status,'BUDGET_EXHAUSTED');});
test('a repair cannot hide a regression',async()=>{ const evaluate=async(candidate,c)=>{ if(!(candidate===base.initial?c.name==='initial count':c.name==='increment'))throw Error('regression'); return {status:'PASS',steps:c.steps.map((s,i)=>({step:i,op:s.op,status:'PASS'}))}; }; const result=await metaFoldClone({...base,evaluate,repair:async()=>html(2),maxAttempts:2}); assert.equal(result.status,'BUDGET_EXHAUSTED');assert.equal(result.winner,null); assert.equal(result.attempts[0].checks[0].status,'PASS'); assert.equal(result.attempts[1].checks[0].status,'FAIL');});
test('evaluation receives copies; attempted contract relaxation does not change next pass',async()=>{ let calls=0; const result=await metaFoldClone({...base,contracts:[contracts[0]],evaluate:async(_,c)=>{ assert.equal(c.steps[0].equals,'0');c.steps[0].equals='anything';calls++;throw Error('no'); },repair:async()=>html(2),maxAttempts:2}); assert.equal(calls,2);assert.equal(result.status,'BUDGET_EXHAUSTED');assert.equal(result.winner,null);});123456789101112131415161718192021222324252627282930313233343536373839404142434445/** Syntax-only source reference locations. Target source is never evaluated. */import {createHash} from 'node:crypto';import {createRequire} from 'node:module';import {pathToFileURL} from 'node:url';const require=createRequire(import.meta.url);const viteRequire=createRequire(require.resolve('vite/package.json'));const {parseAst}=await import(pathToFileURL(viteRequire.resolve('rolldown/parseAst')).href);const sha=value=>createHash('sha256').update(value).digest('hex');
/** Search exact parsed string literals for source-derived selector/id keys. * Even a familiar method name is merely syntax: bindings may be shadowed. * Callers admit package/observation ownership; expectedSha256 binds this file. */export function selectorReferences(filename,source,keys,expectedSha256){ if(typeof source!=='string'||Buffer.byteLength(source)>262144)throw Error('CORRESPONDENCE_JS_BUDGET'); if(!/^[a-f0-9]{64}$/.test(expectedSha256)||sha(Buffer.from(source))!==expectedSha256)throw Error('CORRESPONDENCE_JS_SOURCE_STALE'); if(typeof filename!=='string'||filename.length>500||!Array.isArray(keys)||keys.length>256|| keys.some(key=>typeof key!=='string'||!/^[#.]?[A-Za-z_][A-Za-z0-9_-]{0,100}(?:\.[A-Za-z_][A-Za-z0-9_-]{0,100})?$/.test(key)))throw Error('CORRESPONDENCE_JS_KEYS_INVALID'); const sought=new Set(keys),references=[],stack=[{node:parseAst(source,{},filename),parent:null}]; let visited=0; while(stack.length){ const {node,parent}=stack.pop(); if(!node||typeof node!=='object')continue; if(++visited>100000)throw Error('CORRESPONDENCE_JS_AST_BUDGET'); if(node.type==='Literal'&&typeof node.value==='string'&&sought.has(node.value)){ if(references.length===512)throw Error('CORRESPONDENCE_JS_REFERENCE_BUDGET'); const fragment=source.slice(node.start,node.end),before=source.slice(0,node.start); const start=Buffer.byteLength(before),end=start+Buffer.byteLength(fragment); const callee=parent?.type==='CallExpression'?parent.callee:null; const call=callee?.type==='Identifier'?callee.name:callee?.type==='MemberExpression'&&!callee.computed?callee.property.name:null; references.push({path:filename,file_sha256:expectedSha256,start_byte:start,end_byte:end, span_sha256:sha(Buffer.from(fragment)),line:before.split('\n').length, column:before.length-(before.lastIndexOf('\n')+1)+1,search_key:node.value, syntax_context:parent?.type||null,call_name:call,span_kind:'string_literal', relation:'LEXICAL_REFERENCE_ONLY'}); } for(const child of Object.values(node))if(child&&typeof child==='object'){ if(Array.isArray(child))for(const item of child)stack.push({node:item,parent:node}); else stack.push({node:child,parent:node}); } } references.sort((a,b)=>a.start_byte-b.start_byte); return {version:'metafold-selector-references-v1',path:filename,file_sha256:expectedSha256,references, executed:false,scope:'Exact string-literal references parsed from source. No alias resolution, event-handler attribution, DOM identity, mutation or semantic inference.'};}123456789101112131415161718192021222324252627282930313233343536import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';import {selectorReferences} from './metafold_correspondence.mjs';const sha=s=>createHash('sha256').update(s).digest('hex');
test('source-derived selectors locate syntax references but never execute source',()=>{ const source=`globalThis.__CORRESPONDENCE_EXECUTED=true; // document.querySelector('.fake'); const text="document.querySelector('.fake')"; const node=document.querySelector('.search'); qs('.new-todo'); document.getElementById('go');`; const result=selectorReferences('src/main.js',source,['.search','.fake','.new-todo','go'],sha(source)); assert.deepEqual(result.references.map(r=>r.search_key),['.search','.new-todo','go']); assert.deepEqual(result.references.map(r=>r.call_name),['querySelector','qs','getElementById']); assert.equal(globalThis.__CORRESPONDENCE_EXECUTED,undefined); for(const item of result.references){ const bytes=Buffer.from(source).subarray(item.start_byte,item.end_byte); assert.equal(sha(bytes),item.span_sha256); assert.equal(JSON.parse(bytes.toString().replaceAll("'",'"')),item.search_key); assert.equal(item.relation,'LEXICAL_REFERENCE_ONLY'); }});test('UTF-8 byte spans preserve Unicode preceding a selector',()=>{ const source='const emoji="🎯 日本語"; qs(".search");'; const item=selectorReferences('a.js',source,['.search'],sha(source)).references[0]; assert.equal(Buffer.from(source).subarray(item.start_byte,item.end_byte).toString(),'".search"'); assert.equal(item.start_byte,Buffer.from(source).indexOf(Buffer.from('".search"')));});test('stale source, unsupported key injection and invalid syntax fail closed',()=>{ const source="qs('.search')"; assert.throws(()=>selectorReferences('a.js',source,['.search'],'a'.repeat(64)),/SOURCE_STALE/); assert.throws(()=>selectorReferences('a.js',source,['.search; fetch(evil)'],sha(source)),/KEYS_INVALID/); assert.throws(()=>selectorReferences('a.js','const {',['x'],sha('const {')),/./); assert.throws(()=>selectorReferences('a.js','x'.repeat(262145),[],sha('x'.repeat(262145))),/BUDGET/);});1234567891011121314151617181920import test from 'node:test';import assert from 'node:assert/strict';import {readFile} from 'node:fs/promises';import {randomUUID,createHash} from 'node:crypto';import path from 'node:path';import {createPackageEvaluator} from './metafold_package.mjs';
test('dependency byte and identity pins are enforced before supervised execution',async()=>{ const pkgPath=path.resolve('.local/repository-pilot/todomvc-locked-20260921.json'); const pkg=JSON.parse(await readFile(pkgPath)); const depPath=path.resolve('.local/repository-pilot/todomvc-dependency-verifiable-20260921.json'); const bytes=await readFile(depPath),artifact=JSON.parse(bytes); const contract=JSON.parse(await readFile('docs/contracts/todomvc-create-complete.json')); const dep={path:depPath,digest:artifact.digest,sha256:createHash('sha256').update(bytes).digest('hex')}; const evaluate=await createPackageEvaluator('.local/repository-pilot/dependency-guards-'+randomUUID()); for(const bad of [{...dep,sha256:'0'.repeat(64)},{...dep,digest:'0'.repeat(64)}]){ await assert.rejects(evaluate(JSON.stringify({path:pkgPath,digest:pkg.digest,dependencies:bad}),contract),/DEPENDENCY_DESCRIPTOR_MISMATCH/); } await assert.rejects(evaluate(JSON.stringify({path:pkgPath,digest:pkg.digest,dependencies:{...dep,extra:1}}),contract),/INVALID_DEPENDENCY_DESCRIPTOR/);});12345678910111213141516171819202122232425262728/** Shadow advice cannot alter repair selection or behavioral verification. */import {spawn} from 'node:child_process';import path from 'node:path';import {fileURLToPath} from 'node:url';const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
export function shadowState({sourceDigest,contractDigest,attempt},decision){ return {source_digest:sourceDigest,contract_digest:contractDigest,attempt:attempt.index, candidate_digest:attempt.candidateDigest, checks:attempt.checks.map(c=>({status:c.status,kind:c.residual?.kind??null,assertion:c.residual?.assertion??null})), eligible_repair:decision.candidate?{operator:decision.operator,source_sha256:decision.source_sha256}:null};}
export async function layaShadow(state){ return await new Promise(resolve=>{ const child=spawn(path.join(root,'.venv/Scripts/python.exe'),[path.join(root,'scripts/laya_clone_advice.py')], {cwd:root,windowsHide:true,stdio:['pipe','pipe','pipe']}); let stdout='',stderr='',done=false; const finish=value=>{if(done)return;done=true;clearTimeout(timer);resolve(value);}; const timer=setTimeout(()=>{child.kill();finish({status:'ADVICE_UNAVAILABLE',reason:'TIMEOUT',effect:'shadow_only'});},50000); child.on('error',()=>finish({status:'ADVICE_UNAVAILABLE',reason:'TRANSPORT',effect:'shadow_only'})); child.stdin.on('error',()=>{}); child.stdout.on('data',b=>{stdout+=b;if(stdout.length>65536){child.kill();finish({status:'ADVICE_UNAVAILABLE',reason:'OUTPUT_LIMIT',effect:'shadow_only'});}}); child.stderr.on('data',b=>{stderr=(stderr+b).slice(-2000);}); child.on('close',code=>{try{if(code!==0)throw Error();finish(JSON.parse(stdout));}catch{finish({status:'ADVICE_UNAVAILABLE',reason:'WORKER_REJECTED',detail:stderr,effect:'shadow_only'});}}); child.stdin.end(JSON.stringify(state)); });}12345678910111213import test from 'node:test';import assert from 'node:assert/strict';import {shadowState} from './metafold_laya_shadow.mjs';
test('advisory state binds observed attempt and exposes no executable candidate',()=>{ const context={sourceDigest:'a'.repeat(64),contractDigest:'b'.repeat(64), attempt:{index:0,candidateDigest:'c'.repeat(64),checks:[{status:'FAIL',residual:{kind:'BEHAVIOR_MISMATCH',assertion:{expected:'5',actual:'error'}}}]}}; const state=shadowState(context,{candidate:'SECRET_EXECUTABLE',operator:'reviewed',source_sha256:'d'.repeat(64)}); assert.equal(state.candidate_digest,context.attempt.candidateDigest); assert.equal(state.eligible_repair.operator,'reviewed'); assert.ok(!JSON.stringify(state).includes('SECRET_EXECUTABLE')); assert.equal(shadowState(context,{candidate:null}).eligible_repair,null);});12345678910111213141516171819202122/** Only authenticated, normally terminated driver reports may inform repairs. */export function repairObservation(bound, exit, runtime, behavior) { const clean=bound && !exit.signal && exit.code===1 && runtime.returncode===1 && runtime.remaining_job_processes===0 && runtime.timed_out===false && runtime.cpu_budget_exhausted===false && runtime.output_budget_exhausted===false && behavior.status==='FAIL'; if(!clean)return null; const requests=Array.isArray(behavior.blocked_requests)?behavior.blocked_requests.slice(0,50):[]; return {assertion:behavior.assertion_failure ?? null, observation:{blocked_requests:requests.filter(r=>r?.kind==='request' && typeof r.origin==='string' && typeof r.path==='string').map(r=>({ kind:'request',origin:r.origin.slice(0,200),path:r.path.slice(0,500)})), page_errors:Array.isArray(behavior.page_errors)?behavior.page_errors.slice(0,10).map(e=>String(e).slice(0,500)):[]}};}
export function nextEvidenceAction(observation) { const local=(observation?.blocked_requests ?? []).filter(r=>r.origin==='https://chameleon-package.invalid'); if(local.length)return {kind:'CHECK_PINNED_LOCAL_ASSETS',paths:[...new Set(local.map(r=>r.path))].sort(), scope:'Observation only. Validate against the pinned package before capture; never execute or fetch these paths directly.'}; if(observation?.blocked_requests?.length)return {kind:'EXTERNAL_DEPENDENCY_REQUIRES_REVIEW'}; return {kind:'NO_ASSET_EVIDENCE'};}123456789101112131415161718192021import test from 'node:test';import assert from 'node:assert/strict';import {repairObservation,nextEvidenceAction} from './metafold_observation.mjs';const runtime={returncode:1,remaining_job_processes:0,timed_out:false,cpu_budget_exhausted:false,output_budget_exhausted:false};const behavior={status:'FAIL',assertion_failure:{actual:'error'},blocked_requests:[ {kind:'request',origin:'https://chameleon-package.invalid',path:'/app.js'}, {kind:'request',origin:'https://elsewhere.invalid',path:'/external.js'}]};test('clean failure carries observations; source, signal and resource failures never become repair evidence',()=>{ assert.ok(repairObservation(true,{code:1},runtime,behavior).assertion); for(const changes of [{timed_out:true},{cpu_budget_exhausted:true},{output_budget_exhausted:true},{remaining_job_processes:1},{returncode:9}]) assert.equal(repairObservation(true,{code:1},{...runtime,...changes},behavior),null); assert.equal(repairObservation(false,{code:1},runtime,behavior),null); assert.equal(repairObservation(true,{code:1,signal:'SIGTERM'},runtime,behavior),null);});test('local asset evidence remains separate from external URLs and is deduplicated',()=>{ const evidence=repairObservation(true,{code:1},runtime,behavior); const plan=nextEvidenceAction(evidence.observation); assert.equal(plan.kind,'CHECK_PINNED_LOCAL_ASSETS');assert.deepEqual(plan.paths,['/app.js']); assert.equal(nextEvidenceAction({blocked_requests:[behavior.blocked_requests[1]]}).kind,'EXTERNAL_DEPENDENCY_REQUIRES_REVIEW'); assert.equal(nextEvidenceAction(null).kind,'NO_ASSET_EVIDENCE');});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485/** Trusted local adapter. Repository code runs only in the Python-supervised Chromium Job. */import {readFile,writeFile,mkdir,realpath,stat} from 'node:fs/promises';import path from 'node:path';import {fileURLToPath} from 'node:url';import {spawn} from 'node:child_process';import {createHash} from 'node:crypto';import {validateContract} from './browser_contract.mjs';import {repairObservation} from './metafold_observation.mjs';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');const pilot=path.join(root,'.local','repository-pilot');const hash=s=>createHash('sha256').update(s).digest('hex');const canonical=x=>JSON.stringify(x,(_,v)=>v&&typeof v==='object'&&!Array.isArray(v) ?Object.fromEntries(Object.keys(v).sort().map(k=>[k,v[k]])):v).replace(/[\u007f-\uffff]/g,c=>'\\u'+c.charCodeAt(0).toString(16).padStart(4,'0'));const inside=(base,p)=>p!==base&&!path.relative(base,p).startsWith('..')&&!path.isAbsolute(path.relative(base,p));
export async function createPackageEvaluator(output) { const base=await realpath(pilot); const destination=path.resolve(output); const parent=await realpath(path.dirname(destination)); if(!inside(base,destination)||!(parent===base||inside(base,parent)))throw Error('OUTPUT_OUTSIDE_PILOT'); await mkdir(destination); // Exclusive run directory; never overwrite old evidence. let sequence=0; return async function evaluate(candidate,rawContract) { const descriptor=JSON.parse(candidate); if(!descriptor||!['digest,path','digest,overlay,path','dependencies,digest,path','dependencies,digest,overlay,path'].includes(Object.keys(descriptor).sort().join())||!/^[a-f0-9]{64}$/.test(descriptor.digest))throw Error('INVALID_PACKAGE_DESCRIPTOR'); const input=await realpath(descriptor.path); if(!inside(base,input)||(await stat(input)).size>8*1024*1024)throw Error('PACKAGE_BOUNDARY'); const bytes=await readFile(input); const pkg=JSON.parse(bytes); if(pkg.digest!==descriptor.digest)throw Error('PACKAGE_DESCRIPTOR_MISMATCH'); const contract=validateContract(rawContract),contractText=canonical(contract); if(Buffer.byteLength(contractText)>6000)throw Error('CONTRACT_BUDGET'); const dir=path.join(destination,String(sequence++).padStart(3,'0')); await mkdir(dir); const frozen=path.join(dir,'package.json'), contractPath=path.join(dir,'contract.json'); await writeFile(frozen,bytes,{flag:'wx'}); await writeFile(contractPath,contractText,{flag:'wx'}); let overlayDigest=null,overlayArgs=[]; let dependencyDigest=null,dependencyArgs=[]; if(descriptor.dependencies){ const dep=descriptor.dependencies; if(Object.keys(dep).sort().join()!=='digest,path,sha256'||!['digest','sha256'].every(k=>/^[a-f0-9]{64}$/.test(dep[k])))throw Error('INVALID_DEPENDENCY_DESCRIPTOR'); const depInput=await realpath(dep.path); if(!inside(base,depInput)||(await stat(depInput)).size>16*1024*1024)throw Error('DEPENDENCY_BOUNDARY'); const depBytes=await readFile(depInput),artifact=JSON.parse(depBytes); if(hash(depBytes)!==dep.sha256||artifact.digest!==dep.digest||artifact.bundle.source_package_digest!==pkg.digest)throw Error('DEPENDENCY_DESCRIPTOR_MISMATCH'); const depPath=path.join(dir,'dependencies.json'); await writeFile(depPath,depBytes,{flag:'wx'}); dependencyDigest=dep.digest;dependencyArgs=['--dependencies',depPath]; } if(descriptor.overlay){ const overlayText=canonical(descriptor.overlay); if(Buffer.byteLength(overlayText)>18000)throw Error('OVERLAY_BUDGET'); const overlayPath=path.join(dir,'overlay.json'); await writeFile(overlayPath,overlayText,{flag:'wx'}); overlayDigest=hash(overlayText);overlayArgs=['--overlay',overlayPath]; } await writeFile(path.join(dir,'request.json'),JSON.stringify({package_digest:descriptor.digest, file_digest:hash(bytes),contract_digest:hash(contractText),overlay_digest:overlayDigest,dependency_digest:dependencyDigest}),{flag:'wx'}); const resultDir=path.join(dir,'result'); const exit=await new Promise((resolve,reject)=>{ const child=spawn(path.join(root,'.venv','Scripts','python.exe'), [path.join(root,'scripts','verify_repository_pilot.py'),frozen,'--output',resultDir,'--contract',contractPath,...overlayArgs,...dependencyArgs], {cwd:root,windowsHide:true,stdio:['ignore','ignore','ignore']}); child.once('error',reject);child.once('close',(code,signal)=>resolve({code,signal})); }); await writeFile(path.join(dir,'supervisor-exit.json'),JSON.stringify(exit),{flag:'wx'}); const runtime=JSON.parse(await readFile(path.join(resultDir,'runtime.json'),'utf8')); const behavior=JSON.parse(await readFile(path.join(resultDir,'behavior.json'),'utf8')); const bound=runtime.package_digest===descriptor.digest&&behavior.package_digest===descriptor.digest &&runtime.contract_digest===hash(contractText)&&behavior.contract_digest===hash(contractText) &&runtime.overlay_digest===overlayDigest&&behavior.overlay_digest===overlayDigest &&(runtime.dependency_digest??null)===dependencyDigest&&(behavior.dependency_digest??null)===dependencyDigest; if(exit.code!==0||exit.signal||!bound||runtime.status!=='PASS'||behavior.status!=='PASS' ||runtime.returncode!==0||runtime.remaining_job_processes!==0||runtime.timed_out!==false ||runtime.cpu_budget_exhausted!==false||runtime.output_budget_exhausted!==false){ const error=Error(bound?(behavior.error||'BOUNDED_EXECUTION_FAILED'):'RESULT_BINDING_MISMATCH'); const evidence=repairObservation(bound,exit,runtime,behavior); if(evidence){error.assertion=evidence.assertion;error.observation=evidence.observation;} throw error; } return behavior.cases[0]; };}12345678910111213141516171819202122/** oracle7-trafficcop shadow advice: same state and contract as metafold_laya_shadow.mjs, local and in-process. * Shadow advice cannot alter repair selection or behavioral verification. */import {spawn} from 'node:child_process';import path from 'node:path';import {fileURLToPath} from 'node:url';const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
export async function trafficcopShadow(state){ return await new Promise(resolve=>{ const child=spawn(path.join(root,'.venv/Scripts/python.exe'),[path.join(root,'scripts/trafficcop_clone_advice.py')], {cwd:root,windowsHide:true,stdio:['pipe','pipe','pipe']}); let stdout='',stderr='',done=false; const finish=value=>{if(done)return;done=true;clearTimeout(timer);resolve(value);}; const timer=setTimeout(()=>{child.kill();finish({status:'ADVICE_UNAVAILABLE',reason:'TIMEOUT',effect:'shadow_only'});},10000); child.on('error',()=>finish({status:'ADVICE_UNAVAILABLE',reason:'TRANSPORT',effect:'shadow_only'})); child.stdin.on('error',()=>{}); child.stdout.on('data',b=>{stdout+=b;if(stdout.length>65536){child.kill();finish({status:'ADVICE_UNAVAILABLE',reason:'OUTPUT_LIMIT',effect:'shadow_only'});}}); child.stderr.on('data',b=>{stderr=(stderr+b).slice(-2000);}); child.on('close',code=>{try{if(code!==0)throw Error();finish(JSON.parse(stdout));}catch{finish({status:'ADVICE_UNAVAILABLE',reason:'WORKER_REJECTED',detail:stderr,effect:'shadow_only'});}}); child.stdin.end(JSON.stringify(state)); });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Add behavior storage only to the backed-up dedicated local Chameleon database."""
import argparseimport hashlibimport jsonimport sysfrom datetime import UTC, datetimefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "packages/core"))from alembic import commandfrom alembic.config import Configfrom chameleon_core.config import load_settingsfrom chameleon_core.db import databasefrom chameleon_core.recovery import local_sourcefrom sqlalchemy import text
parser = argparse.ArgumentParser()parser.add_argument("--report", default=".local/behavior-pre-migration-recovery-2.json")parser.add_argument( "--target", choices=[ "0008_behavior_records", "0009_counterpart_bundles", "0011_verification_contract", "0013_dependency_request", "0014_metafold_runs", ], default="0008_behavior_records",)args = parser.parse_args()settings = load_settings()source = local_source(settings.database_url)if source.database != "chameleon": raise SystemExit("Only the ordinary local Chameleon database is supported")report = json.loads((ROOT / args.report).read_text())if ( report["status"] != "PASS" or report["source_database"] != "chameleon" or not report["restored_data_equal"]): raise SystemExit("Verified restore rehearsal required")if not 0 <= (datetime.now(UTC) - datetime.fromisoformat(report["recorded_at"])).total_seconds() < 3600: raise SystemExit("Backup rehearsal is stale")with Path(report["private_archive"]).open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != report["backup_sha256"]: raise SystemExit("Backup archive changed")engine, _ = database(settings.database_url)try: with engine.connect() as connection: before = connection.scalar(text("SELECT version_num FROM alembic_version")) if args.target in {"0013_dependency_request", "0014_metafold_runs"}: for table in ("verification_jobs", "adaptation_jobs"): active = connection.scalar( text(f"SELECT count(*) FROM {table} WHERE status IN ('QUEUED','RUNNING')") ) if active: raise SystemExit("Active jobs: defer migration") revisions = [ "0007_application_saves", "0008_behavior_records", "0009_counterpart_bundles", "0010_verification_jobs", "0011_verification_contract", "0012_verification_assembly", "0013_dependency_request", "0014_metafold_runs", ] if before not in revisions or revisions.index(before) > revisions.index(args.target): raise SystemExit("Unexpected local schema revision") command.upgrade(Config(str(ROOT / "alembic.ini")), args.target) with engine.connect() as connection: after = connection.scalar(text("SELECT version_num FROM alembic_version")) records = connection.scalar(text("SELECT count(*) FROM behavior_records")) print( json.dumps({"before": before, "after": after, "behavior_records": records, "public_changes": False}) )finally: engine.dispose()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/** Parse source as data. Never evaluate, import, resolve or fetch target modules. */import {createRequire} from 'node:module';import {pathToFileURL} from 'node:url';import path from 'node:path';const require=createRequire(import.meta.url);const viteRequire=createRequire(require.resolve('vite/package.json'));const {parseAst}=await import(pathToFileURL(viteRequire.resolve('rolldown/parseAst')).href);
export function moduleDependencies(filename,source){ if(typeof source!=='string'||Buffer.byteLength(source)>262144)throw Error('MODULE_SOURCE_BUDGET'); const tree=parseAst(source,{},filename),stack=[tree],references=[],gaps=[]; let nodes=0; while(stack.length){ const node=stack.pop(); if(!node||typeof node!=='object')continue; if(++nodes>100000)throw Error('MODULE_AST_BUDGET'); let value; if(['ImportDeclaration','ExportNamedDeclaration','ExportAllDeclaration'].includes(node.type)&&node.source)value=node.source.value; if(node.type==='ImportExpression'){ if(typeof node.source?.value==='string')value=node.source.value; else gaps.push({reason:'DYNAMIC_IMPORT_EXPRESSION',offset:node.start}); } if(typeof value==='string'){ if(value.startsWith('./')||value.startsWith('../')||value.startsWith('/')){ if(value.startsWith('//'))gaps.push({reason:'EXTERNAL_MODULE',reference:value}); else{ const url=new URL(value,'https://chameleon-package.invalid/'+filename); const name=decodeURIComponent(url.pathname.slice(1)); if(!name||name.includes('\\')||name.includes('\0')||name.split('/').some(p=>p==='..'||p==='.'))throw Error('MODULE_PATH_INVALID'); references.push({reference:value,path:name}); } }else gaps.push({reason:/^[a-z][a-z0-9+.-]*:/i.test(value)?'EXTERNAL_MODULE':'BARE_MODULE_SPECIFIER',reference:value}); } for(const child of Object.values(node))if(child&&typeof child==='object'){ if(Array.isArray(child))stack.push(...child);else stack.push(child); } } return {references,gaps};}
export function modulePlan(pkg){ const files=pkg.repository.files,paths=new Set(),edges=[],gaps=[]; for(const [name,file]of Object.entries(files)){ if(!['.js','.mjs'].includes(path.posix.extname(name)))continue; const result=moduleDependencies(name,Buffer.from(file.base64,'base64').toString('utf8')); for(const ref of result.references){edges.push({from:name,to:ref.path});if(!Object.hasOwn(files,ref.path))paths.add(ref.path);} gaps.push(...result.gaps.map(gap=>({from:name,...gap}))); } if(paths.size>16)throw Error('MODULE_ADDITIONAL_PATH_BUDGET'); return {version:'module-dependency-plan-v1',package_digest:pkg.digest,paths:[...paths].sort(),edges,gaps, scope:'Parsed import/export specifiers only; no execution, package installation, import-map resolution or external fetch.'};}12345678910111213141516171819202122import test from 'node:test';import assert from 'node:assert/strict';import {moduleDependencies,modulePlan} from './module_dependencies.mjs';
test('syntax parser follows actual imports and exports, not comments or strings',()=>{ const source=`// import './fake.js'; const s="import './also-fake.js'"; import x from './lib.js'; export {x} from '../shared.mjs'; export * from './more.js'; import('./lazy.js'); import(which); import y from 'package-name'; import 'https://external.invalid/a.js';`; const result=moduleDependencies('src/app.js',source); assert.deepEqual(result.references.map(r=>r.path).sort(),['shared.mjs','src/lazy.js','src/lib.js','src/more.js']); assert.deepEqual(result.gaps.map(g=>g.reason).sort(),['BARE_MODULE_SPECIFIER','DYNAMIC_IMPORT_EXPRESSION','EXTERNAL_MODULE']);});test('planner deduplicates missing files and never executes source',()=>{ const source="globalThis.__chameleonExecuted=true; import './lib.js'; export * from './lib.js';"; const pkg={digest:'test',repository:{files:{'app.js':{base64:Buffer.from(source).toString('base64')}}}}; assert.deepEqual(modulePlan(pkg).paths,['lib.js']); assert.equal(globalThis.__chameleonExecuted,undefined); assert.throws(()=>moduleDependencies('app.js','!'.repeat(262145)),/BUDGET/); assert.throws(()=>moduleDependencies('app.js','import {broken'),/./);});1234import {modulePlan} from './module_dependencies.mjs';const chunks=[];let size=0;for await(const chunk of process.stdin){size+=chunk.length;if(size>8*1024*1024)throw Error('MODULE_PACKAGE_BUDGET');chunks.push(chunk);}console.log(JSON.stringify(modulePlan(JSON.parse(Buffer.concat(chunks).toString('utf8')))));12345678910111213141516171819202122232425262728293031323334353637383940/** Static module syntax evidence only. Does not evaluate or rewrite target code. */import {createHash} from 'node:crypto';import {createRequire} from 'node:module';import {pathToFileURL} from 'node:url';import path from 'node:path';const require=createRequire(import.meta.url);const viteRequire=createRequire(require.resolve('vite/package.json'));const {parseAst}=await import(pathToFileURL(viteRequire.resolve('rolldown/parseAst')).href);const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
export function moduleReferences(source){ if(typeof source!=='string'||Buffer.byteLength(source)>262144)throw Error('MODULE_SOURCE_BUDGET'); const tree=parseAst(source),pending=[tree],references=[];let nodes=0,dynamic=0; while(pending.length){ const node=pending.pop();if(!node||typeof node!=='object')continue; if(++nodes>100000)throw Error('MODULE_AST_BUDGET'); if(node.type==='ImportExpression')dynamic++; if(['ImportDeclaration','ExportNamedDeclaration','ExportAllDeclaration'].includes(node.type)&&node.source){ if(typeof node.source.value!=='string')throw Error('MODULE_SPECIFIER_NOT_LITERAL'); if(references.length>=64)throw Error('MODULE_REFERENCE_BUDGET'); const start=Buffer.byteLength(source.slice(0,node.source.start)); const end=Buffer.byteLength(source.slice(0,node.source.end)); references.push({kind:node.type,specifier:node.source.value,start_byte:start,end_byte:end, literal_sha256:sha(Buffer.from(source).subarray(start,end))}); } for(const child of Object.values(node))if(child&&typeof child==='object'){ if(Array.isArray(child))pending.push(...child);else pending.push(child); } } return {version:'static-module-references-v1',source_sha256:sha(source), references:references.sort((a,b)=>a.start_byte-b.start_byte),dynamic_imports:dynamic, scope:'Static declarations only; dynamic imports require separate evidence'};}
if(process.argv[1]&&import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href){ const chunks=[];let size=0; for await(const chunk of process.stdin){size+=chunk.length;if(size>262144)throw Error('MODULE_SOURCE_BUDGET');chunks.push(chunk);} const source=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)); process.stdout.write(JSON.stringify(moduleReferences(source)));}123456789101112131415161718192021222324import test from 'node:test';import assert from 'node:assert/strict';import {moduleReferences} from './module_references.mjs';
test('only actual static module syntax produces references',()=>{ const text='// import fake from "./fake"\nconst s="import x from fake";\nimport main from "./main"; export {x} from "../other.mjs"; export * from "./all.js";'; const result=moduleReferences(text); assert.deepEqual(result.references.map(r=>r.specifier),['./main','../other.mjs','./all.js']); assert.equal(result.dynamic_imports,0);});
test('UTF8 byte spans bind exact literals, with dynamic imports separate',()=>{ const source='// 🌿\nimport "./side"; import(variable); import("./later");'; const result=moduleReferences(source),ref=result.references[0]; assert.equal(Buffer.from(source).subarray(ref.start_byte,ref.end_byte).toString(),'"./side"'); assert.equal(result.dynamic_imports,2); assert.equal(result.references.length,1);});
test('malformed source and budgets refuse rather than use regex fallback',()=>{ assert.throws(()=>moduleReferences('import broken from')); assert.throws(()=>moduleReferences(' '.repeat(262145)),/BUDGET/); assert.throws(()=>moduleReferences(Array.from({length:65},(_,i)=>`import "./m${i}";`).join('\n')),/BUDGET/);});123456789101112131415161718192021222324252627282930313233343536import test from 'node:test';import assert from 'node:assert/strict';import {chromium} from '@playwright/test';import {validateContract,evaluateContract} from './browser_contract.mjs';
const wrap=steps=>({version:'browser-contract-v2',name:'ten-page persisted journey',steps});test('v2 limits and exact-origin assertion reject lookalike routes',async()=>{ for(const equals of ['https://example.com','//example.com','/a b','/a\\b'])assert.throws(()=>validateContract(wrap([{op:'location',equals}]))); assert.throws(()=>validateContract(wrap(Array(81).fill({op:'location',equals:'/'})))); assert.throws(()=>validateContract({...wrap([{op:'location',equals:'/'}]),version:'browser-contract-v1'})); let index=0;const urls=['https://a.invalid/a','https://b.invalid/a']; await assert.rejects(evaluateContract({url:()=>urls[index++]},wrap([{op:'location',equals:'/a'}])),/ORIGIN_ASSERTION_FAILED/);});
test('real browser: ten connected pages retain state, reload, and reject wrong route',async()=>{ const browser=await chromium.launch({chromiumSandbox:true}); try{ const context=await browser.newContext({serviceWorkers:'block',acceptDownloads:false}); await context.route('**/*',route=>{ const u=new URL(route.request().url()),match=u.pathname.match(/^\/page(\d)\.html$/); if(u.origin!=='https://journey.invalid'||!match)return route.abort(); const n=Number(match[1]); return route.fulfill({contentType:'text/html',body:`<h1>Page ${n}</h1><output id="held"></output><a id="next" href="/page${(n+1)%10}.html">Next</a><script>if(${n}===0&&!localStorage.getItem('held'))localStorage.setItem('held','retained');document.querySelector('#held').textContent=localStorage.getItem('held');</script>`}); }); const page=await context.newPage();await page.goto('https://journey.invalid/page0.html'); const steps=[]; for(let n=0;n<10;n++){ steps.push({op:'location',equals:`/page${n}.html`},{op:'text',selector:'h1',equals:`Page ${n}`},{op:'text',selector:'#held',equals:'retained'}); if(n<9)steps.push({op:'click',selector:'#next'}); } steps.push({op:'reload'},{op:'location',equals:'/page9.html'},{op:'text',selector:'#held',equals:'retained'}); const result=await evaluateContract(page,wrap(steps));assert.equal(result.steps.length,42); await assert.rejects(evaluateContract(page,wrap([{op:'location',equals:'/page8.html'}])),/LOCATION_ASSERTION_FAILED/); await context.close(); }finally{await browser.close();}});12345678910111213141516171819202122"""Package current backend only; preserve deployed frontend skin and assets."""import hashlibimport jsonfrom pathlib import Pathimport tarfile
root = Path(__file__).resolve().parents[1]paths = []for directory in ('packages/core', 'packages/adapters', 'apps/api', 'apps/worker', 'migrations', 'scripts', 'docs/contracts'): paths.extend(p for p in (root / directory).rglob('*') if p.is_file() and not {'__pycache__', 'node_modules', '.venv', '.local'} & set(p.relative_to(root).parts) and p.suffix not in {'.pyc', '.pyo'})paths.extend(root / name for name in ('pyproject.toml', 'uv.lock', 'alembic.ini'))output = root / '.local/backend-release-20260922.tar.gz'with tarfile.open(output, 'w:gz') as archive: for path in sorted(set(paths)): archive.add(path, arcname=path.relative_to(root).as_posix(), recursive=False)manifest = {p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(set(paths))}output.with_suffix('.manifest.json').write_text(json.dumps(manifest, indent=2))print(json.dumps({'archive': str(output), 'files': len(manifest), 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()}))1234567891011121314151617"""Build a source-only CLI download; never include sessions, caches or credentials."""
import shutilimport zipfilefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]package = ROOT / "packages/cli"public = ROOT / "apps/web/public"(public / "downloads").mkdir(parents=True, exist_ok=True)(public / "showcase").mkdir(exist_ok=True)files = [package / "pyproject.toml", package / "README.md", *sorted((package / "src/chameleon_cli").glob("*.py"))]with zipfile.ZipFile(public / "downloads/chameleon-harness.zip", "w", zipfile.ZIP_DEFLATED) as archive: for path in files: archive.write(path, "chameleon-harness/" + path.relative_to(package).as_posix())shutil.copyfile(package / "README.md", public / "showcase/CLI_README.txt")print(f"CLI source-only package: {len(files)} files; no local session state")12345678910111213141516171819202122232425262728293031323334353637383940414243"""Retain the approved frozen original source and add its direct example card."""
import jsonimport shutilimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "packages/core"))from chameleon_core.curated_app import render_2048from chameleon_core.repository_capture import verify_package
source = ROOT / ".local/repository-pilot/2048/frozen-verified.json"package = json.loads(source.read_text())render_2048(package, "check", "a" * 32)files = verify_package(package)public = ROOT / "apps/web/public/showcase"shutil.copyfile(source, public / "2048-package.json")(public / "2048-LICENSE.txt").write_bytes(files["LICENSE.txt"])shutil.copyfile(ROOT / "docs/evidence-repository-pilot/2048-desktop.png", public / "2048-source.png")manifest = json.loads((public / "manifest.json").read_text())card = { "source": package["repository"]["source"], "label": "2048, original source", "image": "showcase/2048-source.png", "demo": "showcase/game.html", "kind": "Source-backed interactive application", "provider": "Original MIT-licensed implementation", "captured_at": package["repository"]["captured_at"], "evidence_digest": package["digest"], "pages": 1, "rows": 0, "checked": [ "Original frozen source, styles and game rules", "Keyboard, touch controls and native restart", "Tab-local saved state through isolated storage bridge", "No network or hidden backend reconstruction", ],}manifest["examples"] = [c for c in manifest["examples"] if c["source"] != card["source"]]manifest["examples"].insert(3, card)(public / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")print("Packaged approved 2048 source; production viewer checks still required.")1234567891011121314151617181920212223242526272829303132333435"""Add two explicitly selected public static captures, without private identifiers."""import jsonimport sysfrom pathlib import Pathfrom sqlalchemy import create_engine, select, text
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / 'packages/core'))from chameleon_core.db import LocalTwinfrom chameleon_core.visual_capture import render_page
public = ROOT / 'apps/web/public/showcase'manifest = json.loads((public / 'manifest.json').read_text(encoding='utf-8'))url = json.loads((ROOT / '.local/runtime.json').read_text())['database_url']if '--test-db' in sys.argv: url = url.rsplit('/', 1)[0] + '/chameleon_test'engine = create_engine(url)with engine.connect() as connection: connection.execute(text('SET TRANSACTION READ ONLY')) rows = connection.execute(select(LocalTwin.manifest, LocalTwin.data)).all()for index, source, label in [(4, 'https://example.com/', 'Example Domain — minimal site'), (5, 'https://info.cern.ch/', 'CERN — the original web landmark')]: pages = next(data['pages'] for metadata, data in reversed(rows) if metadata.get('source') == source and data.get('pages')) output = [] for page in pages: render_page(page['visual'], 'validation', '0' * 32) output.append({key: page[key] for key in ('source', 'title', 'captured_at', 'source_digest', 'visual')}) (public / f'demo-{index}.json').write_text(json.dumps({'version': 1, 'label': label, 'pages': output}), encoding='utf-8') manifest['examples'] = [c for c in manifest['examples'] if c['source'] != source] manifest['examples'].append({'source': source, 'label': label, 'image': f'showcase/example-{index}-source-style.png', 'kind': 'Source-style static copy', 'provider': 'chameleon-local-v1', 'captured_at': output[0]['captured_at'], 'evidence_digest': output[0]['source_digest'], 'checked': ['Original captured HTML and styles', 'Saved page opens without contacting the source', 'Static demonstration; outbound destinations are not copied'], 'pages': len(output), 'rows': 0, 'demo': f'showcase/demo.html?example={index}'})manifest['examples'].sort(key=lambda c: not bool(c.get('demo')))for card in manifest['examples']: if card['source'] == 'https://www.python.org/about/': card['label'] = 'Python public website'(public / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')print('Packaged six website examples; separate data example retained.')1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Retain a verified local pilot and an attributed, unchanged source download."""
import argparseimport hashlibimport jsonimport shutilimport sysimport zipfilefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "packages/core"))from chameleon_core.repository_capture import verify_package
parser = argparse.ArgumentParser()parser.add_argument("package")parser.add_argument("run")args = parser.parse_args()package_path, run = Path(args.package).resolve(), Path(args.run).resolve()if not all(p.is_relative_to(ROOT / ".local/repository-pilot") for p in (package_path, run)): raise SystemExit("Use only the isolated local pilot evidence")package = json.loads(package_path.read_text())files = verify_package(package)behavior = json.loads((run / "behavior.json").read_text())runtime = json.loads((run / "runtime.json").read_text())if any( report.get("status") != "PASS" or report.get("package_digest") != package["digest"] for report in (behavior, runtime)): raise SystemExit("Matching passing browser/runtime evidence required")if len(behavior["cases"]) != 6 or any(case["status"] != "PASS" for case in behavior["cases"]): raise SystemExit("Expected all four game behaviors and two controls")if runtime.get("remaining_job_processes") != 0 or runtime["timed_out"]: raise SystemExit("Process cleanup or runtime limit failure")out = ROOT / "docs/evidence-repository-pilot"out.mkdir(exist_ok=True)data = package["repository"]manifest = { "source": data["source"], "commit_sha": data["commit_sha"], "tree_sha": data["tree_sha"], "package_digest": package["digest"], "captured_at": data["captured_at"], "files": { name: {key: value for key, value in record.items() if key != "base64"} for name, record in data["files"].items() }, "license_files": data["license_files"], "acquisition": data["acquisition"], "behavior_scope": behavior["scope"], "claims": { "original_source_preserved": True, "verified_local_static_behavior": True, "arbitrary_backend_clone": False, "public_runtime_deployed": False, "ai_reimplemented_source": False, },}archive = out / "2048-frozen-source-pilot.zip"provenance = "CHAMELEON_CAPTURE.json"if provenance in files: raise SystemExit("Provenance filename collision")with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as zip: for name, body in files.items(): zip.writestr(name, body) zip.writestr(provenance, json.dumps(manifest, indent=2) + "\n")manifest["download_sha256"] = hashlib.sha256(archive.read_bytes()).hexdigest()(out / "source-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")for filename in ("behavior.json", "runtime.json", "2048-desktop.png", "2048-mobile.png"): shutil.copyfile(run / filename, out / filename)print( json.dumps( { "archive": str(archive), "files": len(files), "checks": len(behavior["cases"]), "status": "LOCAL_PILOT_VERIFIED_NOT_DEPLOYED", } ))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Publish only previously verified public example captures, never guest identities."""
import jsonimport sysfrom pathlib import Path
from sqlalchemy import create_engine, select, text
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "packages/core"))from chameleon_core.db import LocalTwinfrom chameleon_core.visual_capture import render_page
public = ROOT / "apps/web/public/showcase"manifest = json.loads((public / "manifest.json").read_text())engine = create_engine(json.loads((ROOT / ".local/runtime.json").read_text())["database_url"])with engine.connect() as connection: connection.execute(text("SET TRANSACTION READ ONLY")) rows = connection.execute(select(LocalTwin.manifest, LocalTwin.data)).all() for index, card in enumerate(manifest["examples"]): if not card["pages"] or card["kind"] != "Source-style static copy": continue candidates = [ data["pages"] for metadata, data in rows if metadata.get("source") == card["source"] and data.get("pages") and all(p.get("visual") for p in data["pages"]) ] if not candidates: raise SystemExit("Missing saved styled example: " + card["source"]) pages = max(candidates, key=lambda p: (len(p), p[0]["captured_at"])) output = [] for page in pages: # Recheck artifact integrity before distributing any captured HTML. render_page(page["visual"], "validation", "0" * 32) output.append( {key: page[key] for key in ("source", "title", "captured_at", "source_digest", "visual")} ) filename = f"demo-{index}.json" (public / filename).write_text( json.dumps({"version": 1, "label": card["label"], "pages": output}), encoding="utf-8" ) card["demo"] = f"showcase/demo.html?example={index}" card["demo_pages"] = len(output) card["demo_captured_at"] = output[0]["captured_at"] print(json.dumps({"source": card["source"], "pages": len(output), "file": filename}))(public / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Read-only missing-control proposals from frozen HTML and inert JS syntax."""import argparseimport base64import jsonimport shutilimport subprocessimport sysfrom html.parser import HTMLParserfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / 'packages/core'))from chameleon_core.repository_capture import verify_package
class Surface(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.ids = set() self.scripts = [] self.current = None self.template_depth = 0
def handle_starttag(self, tag, attrs): attrs = dict(attrs) if tag == 'template': self.template_depth += 1 if self.template_depth: return if attrs.get('id'): self.ids.add(attrs['id']) if tag == 'script' and not attrs.get('src') and attrs.get('type', '').lower() in ( '', 'text/javascript', 'application/javascript', 'module'): self.current = ''
def handle_endtag(self, tag): if tag == 'template': self.template_depth = max(0, self.template_depth - 1) if tag == 'script' and self.current is not None: self.scripts.append(self.current) self.current = None
def handle_data(self, data): if self.current is not None: self.current += data
def plan(package): verify_package(package) entry = package['repository']['entry'] record = package['repository']['files'][entry] body = base64.b64decode(record['base64'], validate=True) if len(body) > 524288: raise ValueError('DOM_HTML_BUDGET') surface = Surface() surface.feed(body.decode('utf-8')) node = shutil.which('node') if node is None: raise RuntimeError('DOM_NODE_UNAVAILABLE') result = subprocess.run([node, str(ROOT / 'scripts/dom_references.mjs')], input=json.dumps(surface.scripts), text=True, capture_output=True, timeout=10, check=True) parsed = json.loads(result.stdout) missing = [dict(ref, script_index=i, script_sha256=script['source_sha256']) for i, script in enumerate(parsed) for ref in script['references'] if ref['id'] not in surface.ids] return {'version': 'dom-dependency-proposal-v1', 'source_digest': package['digest'], 'entry': entry, 'entry_sha256': record['sha256'], 'missing_static_ids': missing, 'status': 'PROPOSED', 'verified_application': False, 'scope': 'Inline literal document ID lookups only. Dynamic DOM, shadowed document, ' 'branch reachability and external scripts are unresolved. Never auto-insert controls.'}
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('package') parser.add_argument('output') args = parser.parse_args() source, output = Path(args.package).resolve(), Path(args.output).resolve() if not source.is_relative_to(ROOT / '.local') or not output.is_relative_to(ROOT / '.local'): raise ValueError('DOM_LOCAL_BOUNDARY') if source.stat().st_size > 8388608: raise ValueError('DOM_PACKAGE_BUDGET') report = plan(json.loads(source.read_text(encoding='utf-8'))) with output.open('x', encoding='utf-8') as stream: json.dump(report, stream, indent=2) print(json.dumps(report))1234567891011121314151617181920212223242526272829"""Source-bound static build declaration inspection; no target script execution."""import argparseimport jsonimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / 'packages/core'))from chameleon_core.build_plan import plan_saved_build
def main(): parser = argparse.ArgumentParser() parser.add_argument('package') parser.add_argument('output') args = parser.parse_args() source, output = Path(args.package).resolve(), Path(args.output).resolve() pilot = ROOT / '.local/repository-pilot' if (not source.is_relative_to(pilot) or source.stat().st_size > 8*1024*1024 or not output.is_relative_to(pilot) or output.exists()): raise ValueError('BUILD_PILOT_BOUNDARY') result = plan_saved_build(json.loads(source.read_text(encoding='utf-8'))) with output.open('x', encoding='utf-8') as stream: json.dump(result, stream, indent=2) print(json.dumps(result['plan']))
if __name__ == '__main__': main()1234567891011121314151617181920212223242526272829303132333435363738"""Inspect one local saved twin and pinned official tree; no source writes/execution."""import argparseimport jsonimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / 'packages/core'))from chameleon_core.config import load_settingsfrom chameleon_core.db import LocalTwin, databasefrom chameleon_core.mount_plan import plan_entry_mountfrom chameleon_core.recovery import local_sourcefrom chameleon_core.repository_capture import fetch_bytes, targetfrom chameleon_core.twins import Twins
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('twin') parser.add_argument('output') args = parser.parse_args() output = Path(args.output).resolve() if not output.is_relative_to(ROOT / '.local') or output.exists(): raise ValueError('FRESH_LOCAL_OUTPUT_REQUIRED') cfg = load_settings() if local_source(cfg.database_url).database != 'chameleon': raise ValueError('NORMAL_LOCAL_DATABASE_REQUIRED') engine, sessions = database(cfg.database_url) try: with sessions() as session: twin = session.get(LocalTwin, args.twin) evidence = Twins(sessions).repository_evidence(twin.owner, twin.id) owner, repo, _ = target(evidence.payload['source']) body = fetch_bytes(f'https://api.github.com/repos/{owner}/{repo}/git/trees/{evidence.payload["tree_sha"]}?recursive=1', 524288) result = plan_entry_mount({'digest': evidence.content_digest, 'repository': evidence.payload}, json.loads(body)) output.write_text(json.dumps(result, indent=2)) print(json.dumps(result)) finally: engine.dispose()1234567891011121314151617181920212223242526272829303132import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';
const root=path.resolve(import.meta.dirname,'..');const stage=path.join(root,'.local/jev-presentation');const copy='The Jev integration is designed to help Ditto choose which eligible pages and assets to inspect next. Its purpose is to reduce redundant work and make site copying more efficient. Ditto handles page capture, asset collection, reconstruction and verification.';function once(text,from,to){if(text.split(from).length!==2)throw Error('Expected exactly one match: '+from.slice(0,100));return text.replace(from,to);}for(const file of ['apps/web/index.html','apps/web/src/DittoWelcome.tsx','apps/web/src/main.tsx']){ const dest=path.join(root,file);let s=fs.readFileSync(dest,'utf8');s=s.replaceAll('with Laya','with Jev'); if(file.endsWith('main.tsx')){ const match=s.match(/<h3>Why Laya\?<\/h3><p>[^<]*<\/p>/g); if(match?.length!==1)throw Error('Source Laya paragraph changed'); s=once(s,match[0],'<h3>Why Jev?</h3><p>'+copy+'</p>'); } fs.writeFileSync(dest,s);}let js=fs.readFileSync(path.join(stage,'live.js'),'utf8');js=once(js,'(0,o.jsx)(`a`,{className:`sidebar-brand`,href:`#workshop`,onClick:e=>{e.preventDefault(),Ve(`chat`)},children:(0,o.jsx)(y,{})})','(0,o.jsxs)(`a`,{className:`sidebar-brand`,href:`#workshop`,"aria-label":`Ditto with Jev`,onClick:e=>{e.preventDefault(),Ve(`chat`)},children:[(0,o.jsx)(y,{}),(0,o.jsx)(`small`,{children:`with Jev`})]})');js=once(js,'className:`welcome`,"aria-label":`Ditto`','className:`welcome`,"aria-label":`Ditto with Jev`');js=once(js,'className:`welcome-title`,children:[`Ditto `,(0,o.jsx)(`em`,{children:`v1.0`})]','className:`welcome-title`,children:[`Ditto `,(0,o.jsx)(`em`,{children:`(with Jev)`})]');js=once(js,'(0,o.jsx)(`h3`,{children:`Same source. Its own style.`})','(0,o.jsx)(`h3`,{children:`Why Jev?`}),(0,o.jsx)(`p`,{children:'+JSON.stringify(copy)+'}),(0,o.jsx)(`h3`,{children:`Same source. Its own style.`})');const css=fs.readFileSync(path.join(stage,'live.css'),'utf8')+'\nhtml[data-product=ditto] .sidebar-brand small{display:block;margin-left:6px;color:var(--text-3);font:500 10px/1 var(--mono);letter-spacing:.02em;white-space:nowrap}\n';const hash=s=>crypto.createHash('sha256').update(s).digest('hex');const jsName='ditto-jev-'+hash(js).slice(0,12)+'.js',cssName='ditto-jev-'+hash(css).slice(0,12)+'.css';const original=fs.readFileSync(path.join(stage,'index.html'),'utf8');let html=once(original,'<title>Ditto · What do you want to clone?</title>','<title>Ditto with Jev · What do you want to clone?</title>');html=once(html,'index-BnUugTYS.js',jsName);html=once(html,'index-DOlH23NG.css',cssName);fs.mkdirSync(path.join(stage,'release/assets'),{recursive:true});fs.writeFileSync(path.join(stage,'release/assets',jsName),js);fs.writeFileSync(path.join(stage,'release/assets',cssName),css);fs.writeFileSync(path.join(stage,'release/index.html'),html);fs.writeFileSync(path.join(stage,'manifest.json'),JSON.stringify({baseline:hash(original),index:hash(html),jsName,cssName,copy},null,2));console.log(JSON.stringify({jsName,cssName,index:hash(html)}));123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Prepare public pinned model bytes only. Does not import or execute the model."""
import hashlibimport jsonimport shutilimport subprocessimport urllib.requestfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]REVISION = "1c5edc17a7acd8701df6fc341c0d179f1c62c982"SDK = "42626c348753fbb17572a813127df2278a1ec527"FILES = ( "README.md", "encoder/config.json", "rl_agent_config.json", "model.safetensors", "tokenizer/tokenizer.json", "tokenizer/tokenizer_config.json",)BASE = "https://huggingface.co/convaiinnovations/laya"
def checksum(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest()
def prepare(): sdk = ROOT / ".local/laya-sdk" actual = subprocess.check_output(["git", "-C", str(sdk), "rev-parse", "HEAD"], text=True).strip() if actual != SDK: raise RuntimeError("SDK revision differs from reviewed revision") if subprocess.check_output(["git", "-C", str(sdk), "status", "--porcelain"], text=True).strip(): raise RuntimeError("SDK checkout has local changes") with urllib.request.urlopen( f"https://huggingface.co/api/models/convaiinnovations/laya/tree/{REVISION}?recursive=true", timeout=30 ) as response: metadata = {entry["path"]: entry for entry in json.load(response)} if sum(metadata[name]["size"] for name in FILES) > 900_000_000: raise RuntimeError("Artifact exceeds explicit 900 MB budget") destination = ROOT / ".local/laya-artifacts" / REVISION original, runtime = destination / "original", destination / "runtime" if shutil.disk_usage(ROOT).free < 2_000_000_000: raise RuntimeError("Insufficient disk headroom for original and isolated runtime copies") records = {} for name in FILES: entry = metadata[name] path = original / name path.parent.mkdir(parents=True, exist_ok=True) if not path.exists(): pending = path.with_suffix(path.suffix + ".partial") size = 0 with ( urllib.request.urlopen(f"{BASE}/resolve/{REVISION}/{name}", timeout=60) as response, pending.open("wb") as output, ): while chunk := response.read(1024 * 1024): size += len(chunk) if size > entry["size"]: raise RuntimeError("Source exceeded declared size") output.write(chunk) if size != entry["size"]: raise RuntimeError("Incomplete artifact file") pending.replace(path) if path.stat().st_size != entry["size"]: raise RuntimeError("Stored artifact size mismatch") sha = checksum(path) if entry.get("lfs"): if sha != entry["lfs"]["oid"]: raise RuntimeError("LFS content checksum mismatch") else: blob = hashlib.sha1(f"blob {entry['size']}\0".encode() + path.read_bytes()).hexdigest() if blob != entry["oid"]: raise RuntimeError("Git blob checksum mismatch") target = runtime / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target) records[name] = {"bytes": entry["size"], "original_sha256": sha, "runtime_sha256": sha} print(f"Verified {name}: {entry['size']} bytes", flush=True) # Same compatibility normalization as the reviewed SDK, applied only to a copy. path = runtime / "tokenizer/tokenizer_config.json" config = json.loads(path.read_text(encoding="utf-8")) transformations = [] if config.get("tokenizer_class") in (None, "TokenizersBackend"): config["tokenizer_class"] = "PreTrainedTokenizerFast" config.pop("backend", None) config.pop("is_local", None) transformations.append("tokenizer_class compatibility") if isinstance(config.get("extra_special_tokens"), list): config["extra_special_tokens"] = { f"extra_{i}": value for i, value in enumerate(config["extra_special_tokens"]) } transformations.append("extra_special_tokens list to mapping") if transformations: path.write_text(json.dumps(config, indent=2), encoding="utf-8") records["tokenizer/tokenizer_config.json"]["runtime_sha256"] = checksum(path) shutil.copy2(sdk / "LICENSE", destination / "SDK_LICENSE.txt") manifest = { "repository": "convaiinnovations/laya", "revision": REVISION, "sdk_revision": SDK, "checkpoint": "English root", "files": records, "transformations": transformations, "device_requested": "cpu", "dtype_requested": "float32", "status": "BYTES_VERIFIED_NOT_RUNTIME_VALIDATED", "dependency_lock": None, "inference_executed": False, "model_license_reference": "original/README.md", "sdk_license": "SDK_LICENSE.txt", } (destination / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") print(json.dumps({"status": manifest["status"], "manifest": str(destination / "manifest.json")}))
if __name__ == "__main__": prepare()1234567891011121314151617181920212223242526272829"""Dedicated forwarding identity setup; never prints private key material."""from pathlib import Pathimport subprocessimport sys
def run(*args): subprocess.run(args,check=True)
if sys.argv[1] == 'key': root=Path('/opt/chameleon-verifier/ssh') root.mkdir(mode=0o700,exist_ok=True) key=root/'database_ed25519' if not key.exists(): run('ssh-keygen','-q','-t','ed25519','-N','','-f',str(key)) run('chown','-R','chameleon-verifier:chameleon-verifier',str(root))elif sys.argv[1] == 'authorize': key=Path('/tmp/chameleon-database.pub').read_text().strip() if not key.startswith('ssh-ed25519 ') or '\n' in key: raise ValueError('Expected one ed25519 public key') if subprocess.run(['id','chameleon-tunnel'],capture_output=True).returncode: run('useradd','--system','--create-home','--home-dir','/var/lib/chameleon-tunnel','--shell','/bin/false','chameleon-tunnel') folder=Path('/var/lib/chameleon-tunnel/.ssh') folder.mkdir(mode=0o700,exist_ok=True) auth=folder/'authorized_keys' if auth.exists(): raise RuntimeError('Existing forwarding identity requires inspection') auth.write_text('restrict,port-forwarding,permitopen="127.0.0.1:55433",command="/bin/false" '+key+'\n') auth.chmod(0o600) run('chown','-R','chameleon-tunnel:chameleon-tunnel',str(folder))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Operator-local all-contract diagnostics. Never relax the release gate."""import argparseimport jsonimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path[:0] = [str(ROOT / "packages/core")]from chameleon_core.browser_contract import validate_contractfrom chameleon_core.config import load_settingsfrom chameleon_core.db import LocalTwin, databasefrom chameleon_core.recovery import local_sourcefrom chameleon_core.twins import Twinsfrom verify_saved_repository import verify_saved
def summarize(contract, result, behavior, runtime): case = next((c for c in behavior.get("cases", []) if c.get("name") == contract["name"]), {}) steps = case.get("steps", []) complete = (case.get("status") == "PASS" and len(steps) == len(contract["steps"]) and all(s.get("status") == "PASS" and s.get("step") == i and s.get("op") == contract["steps"][i]["op"] for i, s in enumerate(steps))) return {"name": contract["name"], "status": result["status"], "interaction_passed": complete, "record_id": result["record_id"], "error": behavior.get("error"), "page_errors": behavior.get("page_error_details", []), "job_cpu_seconds": runtime.get("job_cpu_seconds"), "supervised_wall_seconds": runtime.get("wall_seconds")}
def main(): parser = argparse.ArgumentParser() parser.add_argument("--twin", required=True) parser.add_argument("--request", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() source = Path(args.request) if source.stat().st_size > 32000: raise ValueError("CONTRACT_SET_BUDGET") request = json.loads(source.read_text()) raw = request["contracts"] if isinstance(request, dict) else request if not isinstance(raw, list) or not 1 <= len(raw) <= 12: raise ValueError("CONTRACT_SET_BUDGET") contracts = [validate_contract(c)[0] for c in raw] output = Path(args.output).resolve() base = ROOT / ".local/repository-pilot" if output == base or not output.is_relative_to(base): raise ValueError("OUTPUT_OUTSIDE_PILOT") cfg = load_settings() if cfg.profile != "synthetic" or local_source(cfg.database_url).database != "chameleon": raise ValueError("NORMAL_LOCAL_DATABASE_REQUIRED") engine, sessions = database(cfg.database_url) try: with sessions() as session: twin = session.get(LocalTwin, args.twin) if twin is None: raise ValueError("TWIN_NOT_FOUND") owner = twin.owner evidence = Twins(sessions).repository_evidence(owner, args.twin) output.mkdir(exist_ok=False) report = {"source_digest": evidence.content_digest, "twin_id": args.twin, "scope": "Diagnostic interaction coverage; overall failures remain failures", "contracts": [], "status": "RUNNING"} for i, contract in enumerate(contracts): destination = output / str(i) if Twins(sessions).repository_evidence(owner, args.twin).content_digest != evidence.content_digest: raise ValueError("SOURCE_CHANGED") result = verify_saved(sessions, owner, args.twin, contract, destination) behavior = json.loads((destination / "result/behavior.json").read_text()) runtime = json.loads((destination / "result/runtime.json").read_text()) report["contracts"].append(summarize(contract, result, behavior, runtime)) (output / "summary.json").write_text(json.dumps(report, indent=2)) report["status"] = "PASS" if all(c["status"] == "PASS" for c in report["contracts"]) else "FAIL" (output / "summary.json").write_text(json.dumps(report, indent=2)) print(json.dumps(report, indent=2)) return 0 if report["status"] == "PASS" else 1 finally: engine.dispose()
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210"""Run ONLY on the user-authorized Box A. Isolated first-install; no nginx edits here."""
import jsonimport osimport secretsimport shutilimport socketimport subprocessimport timefrom pathlib import Path
ROOT = Path("/opt/chameleon")RELEASE = ROOT / "releases/stage-20260920"DATA = Path("/var/lib/chameleon")
def run(args, **kwargs): return subprocess.run([str(x) for x in args], check=True, **kwargs)
def write_new(path, value, mode=0o644): fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode) with os.fdopen(fd, "w") as stream: stream.write(value)
if os.geteuid() != 0 or socket.gethostname() != "ubuntu-4gb-hel1-2": raise SystemExit("Refuse installation outside authorized Box A")if not (RELEASE / "pyproject.toml").exists(): raise SystemExit("Staging release has not been uploaded")if Path("/etc/chameleon-stage.env").exists(): raise SystemExit("Existing installation: inspect and upgrade explicitly, never re-provision")if shutil.disk_usage("/").free < 1_500_000_000: raise SystemExit("Insufficient safe staging disk headroom")memory = dict(line.split(":", 1) for line in Path("/proc/meminfo").read_text().splitlines())if int(memory["MemAvailable"].split()[0]) < 750_000: raise SystemExit("Insufficient safe memory headroom; no services changed")for port in (55433, 8320): with socket.socket() as sock: sock.bind(("127.0.0.1", port))if subprocess.run(["getent", "passwd", "chameleon"], capture_output=True, check=False).returncode == 0: raise SystemExit("Existing chameleon account needs explicit inspection")run( [ "useradd", "--system", "--user-group", "--home-dir", str(DATA), "--shell", "/usr/sbin/nologin", "chameleon", ])DATA.mkdir(mode=0o700)run(["chown", "chameleon:chameleon", DATA])run(["python3", "-m", "venv", ROOT / "tooling"])run([ROOT / "tooling/bin/python", "-m", "pip", "install", "--disable-pip-version-check", "uv==0.12.17"])uv = ROOT / "tooling/bin/uv"run([uv, "python", "install", "3.12.14", "--install-dir", ROOT / "python", "--no-bin"])env = {**os.environ, "UV_PYTHON_INSTALL_DIR": str(ROOT / "python")}run([uv, "sync", "--frozen", "--no-dev", "--python", "3.12.14"], cwd=RELEASE, env=env)packages = ROOT / "postgres-packages"packages.mkdir()# Download/extract official Ubuntu packages without installing a global service or replacing libraries.run(["apt-get", "download", "postgresql-14", "postgresql-client-14"], cwd=packages)for package in packages.glob("*.deb"): run(["dpkg-deb", "-x", package, ROOT / "postgres"])pg = ROOT / "postgres/usr/lib/postgresql/14/bin"libraries = run(["ldd", pg / "postgres"], capture_output=True, text=True).stdoutif "not found" in libraries: raise SystemExit("Private PostgreSQL needs additional libraries; no existing services changed")password = secrets.token_hex(32)password_file = DATA / "pg-init-password"write_new(password_file, password + "\n", 0o600)run(["chown", "chameleon:chameleon", password_file])run( [ "runuser", "-u", "chameleon", "--", pg / "initdb", "-D", DATA / "pgdata", "-U", "chameleon", "--auth=scram-sha-256", "--pwfile=" + str(password_file), "--encoding=UTF8", "--locale=C", "-L", ROOT / "postgres/usr/share/postgresql/14", ], capture_output=True,)(DATA / "run").mkdir()run(["chown", "chameleon:chameleon", DATA / "run"])write_new( Path("/etc/systemd/system/chameleon-stage.slice"), """[Unit]Description=Chameleon isolated staging resource budget[Slice]CPUQuota=50%MemoryHigh=512MMemoryMax=640MTasksMax=100""",)hardening = """User=chameleonGroup=chameleonSlice=chameleon-stage.sliceNoNewPrivileges=truePrivateTmp=trueProtectSystem=strictProtectHome=trueReadWritePaths=/var/lib/chameleonRestart=on-failureRestartSec=5UMask=0077"""write_new( Path("/etc/systemd/system/chameleon-stage-db.service"), f"""[Unit]Description=Chameleon dedicated PostgreSQL staging databaseAfter=network.target[Service]{hardening}ExecStart={pg}/postgres -D {DATA}/pgdata -h 127.0.0.1 -p 55433 -c unix_socket_directories={DATA}/run -c shared_buffers=32MB -c max_connections=24 -c timezone=UTCMemoryMax=192M[Install]WantedBy=multi-user.target""",)run(["systemctl", "daemon-reload"])run(["systemctl", "start", "chameleon-stage-db.service"])for attempt in range(30): if ( subprocess.run( [pg / "pg_isready", "-h", "127.0.0.1", "-p", "55433"], capture_output=True, check=False ).returncode == 0 ): break time.sleep(1)else: raise SystemExit("Private database did not start")pg_env = {**env, "PGPASSWORD": password, "PGCONNECT_TIMEOUT": "5"}run( [pg / "createdb", "-h", "127.0.0.1", "-p", "55433", "-U", "chameleon", "chameleon_stage"], env=pg_env, capture_output=True,)password_file.unlink() # Only the single initialization secret created by this installer.settings = { "CHAMELEON_PROFILE": "public-preview", "CHAMELEON_ORIGIN": "https://prometheus7.com", "CHAMELEON_BASE_PATH": "/chameleonAI", "CHAMELEON_WORKER_SLOT": "box-a-stage", "CHAMELEON_DATABASE_URL": f"postgresql+psycopg://chameleon:{password}@127.0.0.1:55433/chameleon_stage", "CHAMELEON_MAX_USERS": "100", "CHAMELEON_NEW_SESSIONS_PER_MINUTE": "10", "CHAMELEON_MAX_PENDING_JOBS": "8", "CHAMELEON_MAX_RUNNING_JOBS": "1", "CHAMELEON_MAX_STORED_JOBS": "1000", "PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": ":".join( str(RELEASE / p) for p in ("packages/core", "packages/adapters", "apps/api", "apps/worker") ),}write_new(Path("/etc/chameleon-stage.env"), "".join(k + "=" + v + "\n" for k, v in settings.items()), 0o600)run( [RELEASE / ".venv/bin/alembic", "upgrade", "head"], cwd=RELEASE, env={**env, **settings}, capture_output=True,)for kind, command in { "api": f"{RELEASE}/.venv/bin/uvicorn chameleon_api.app:factory --factory --host 127.0.0.1 --port 8320 --no-access-log --forwarded-allow-ips=127.0.0.1", "worker": f"{RELEASE}/.venv/bin/python {RELEASE}/scripts/serve.py worker",}.items(): write_new( Path(f"/etc/systemd/system/chameleon-stage-{kind}.service"), f"""[Unit]Description=Chameleon staging {kind}After=chameleon-stage-db.service network-online.targetRequires=chameleon-stage-db.service[Service]{hardening}WorkingDirectory={RELEASE}EnvironmentFile=/etc/chameleon-stage.envExecStart={command}MemoryMax=224M[Install]WantedBy=multi-user.target""", )run(["systemctl", "daemon-reload"])run(["systemctl", "start", "chameleon-stage-api.service", "chameleon-stage-worker.service"])print( json.dumps( { "private_runtime_started": True, "public_route_installed": False, "existing_services_restarted": False, "aggregate_memory_max_mb": 640, "aggregate_cpu_quota_percent": 50, "postgres_port": 55433, "api_port": 8320, } ))123456789101112131415161718192021222324252627282930"""Provision the dedicated production verifier, without enabling public intake."""import jsonfrom pathlib import Pathimport secretsfrom sqlalchemy import create_engine, textfrom sqlalchemy.engine import make_url
destination = Path('/opt/chameleon/verifier-production.env')assert not destination.exists(), 'Do not overwrite existing credentials'settings = dict(line.split('=', 1) for line in Path('/etc/chameleon-stage.env').read_text().splitlines() if '=' in line)source = make_url(settings['CHAMELEON_DATABASE_URL'])assert source.host == '127.0.0.1' and source.port == 55433role = 'chameleon_verifier_production'password = secrets.token_hex(32)engine = create_engine(source)with engine.begin() as connection: assert connection.scalar(text('SELECT version_num FROM alembic_version')) == '0014_metafold_runs' connection.exec_driver_sql(f"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION") connection.exec_driver_sql(f'GRANT USAGE ON SCHEMA public TO {role}') connection.exec_driver_sql(f'GRANT SELECT ON users, agents, adaptation_jobs, local_twins, behavior_records, counterpart_bundles, verification_jobs TO {role}') connection.exec_driver_sql(f'GRANT UPDATE ON verification_jobs TO {role}') # PostgreSQL SELECT FOR UPDATE requires UPDATE privilege on a column. connection.exec_driver_sql(f'GRANT UPDATE (revision) ON local_twins TO {role}') connection.exec_driver_sql(f'GRANT INSERT ON behavior_records, counterpart_bundles TO {role}')engine.dispose()with destination.open('x') as output: destination.chmod(0o600) output.write('CHAMELEON_DATABASE_URL=' + source.set(username=role, password=password, port=55434).render_as_string(hide_password=False) + '\n') output.write('CHAMELEON_PROFILE=public-preview\nCHAMELEON_VERIFICATION_ENABLED=1\n')print(json.dumps({'status': 'PROVISIONED', 'public_intake_enabled': False}))12345678910111213141516171819202122232425262728293031"""Provision a rehearsal-only login; output contains no credentials."""import jsonfrom pathlib import Pathimport secretsfrom sqlalchemy import create_engine, textfrom sqlalchemy.engine import make_url
DATABASE = 'chameleon_rehearsal_bd671577de2a'ROLE = 'chameleon_verifier_rehearsal'destination = Path('/opt/chameleon/rehearsals/verifier.env')assert not destination.exists(), 'Existing credential must be inspected, not replaced'settings = dict(line.split('=', 1) for line in Path('/etc/chameleon-stage.env').read_text().splitlines() if '=' in line)source = make_url(settings['CHAMELEON_DATABASE_URL'])assert source.host == '127.0.0.1' and source.port == 55433password = secrets.token_hex(32)engine = create_engine(source.set(database=DATABASE))with engine.begin() as connection: assert connection.scalar(text('SELECT version_num FROM alembic_version')) == '0014_metafold_runs' # Names are fixed constants; password is hex generated locally, never user input. connection.exec_driver_sql(f"CREATE ROLE {ROLE} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION") connection.exec_driver_sql(f'GRANT CONNECT ON DATABASE {DATABASE} TO {ROLE}') connection.exec_driver_sql(f'GRANT USAGE ON SCHEMA public TO {ROLE}') connection.exec_driver_sql(f'GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {ROLE}') connection.exec_driver_sql(f'GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {ROLE}')engine.dispose()url = source.set(database=DATABASE, username=ROLE, password=password, port=55434)with destination.open('x') as output: destination.chmod(0o600) output.write('CHAMELEON_DATABASE_URL=' + url.render_as_string(hide_password=False) + '\n') output.write('CHAMELEON_PROFILE=public-preview\nCHAMELEON_VERIFICATION_ENABLED=1\n')print(json.dumps({'provisioned': ROLE, 'database': DATABASE, 'credential_file': str(destination)}))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Build public gallery assets only from passing, recorded staging captures."""
import jsonimport shutilfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]evidence = ROOT / "docs/evidence-source-style-v2/public"public = ROOT / "apps/web/public/showcase"report = json.loads((evidence / "fidelity-results.json").read_text())manifest = json.loads((public / "manifest.json").read_text())if report["status"] != "PASS" or len(report["sources"]) != 3: raise SystemExit("Three passing real-source comparisons are required")for i, result in enumerate(report["sources"]): if ( result.get("visual_sample") != "PASS" or result.get("mobile_sample") != "PASS" or not result.get("navigation", "").startswith("PASS") or result.get("reopen") != "PASS" or not result.get("source_digest") or not result.get("captured_at") ): raise SystemExit("Incomplete provenance or acceptance") card = next(item for item in manifest["examples"] if item["source"] == result["source"]) filename = f"example-{i}-source-style.png" shutil.copyfile(evidence / f"source-{i}-counterpart.png", public / filename) card.update( image=f"showcase/{filename}", kind="Source-style static copy", captured_at=result["captured_at"], evidence_digest=result["source_digest"], pages=2, rows=0, checked=[ "Original static layout, available fonts and images", "Desktop/mobile layout samples independently checked", "Observed source link captured; saved copy reopens", f"{len(result['asset_gaps'])} asset omissions recorded; source scripts disabled", ], )manifest["captured_at"] = report["at"]manifest["website_comparison_scope"] = ( "Sampled geometry/styles against script-disabled sources, not whole-page pixel or backend equivalence. " "Screenshots show each initial page; two pages per copy were saved through observed navigation. " "The data and CLI examples retain their separately dated earlier evidence.")(public / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")print("Updated three source-style gallery cards from actual passing public-stage captures").gitattributes+2
orbiters/chameleon/scripts/laya_worker.pyAdded+223
orbiters/chameleon/scripts/linux_worker_bootstrap.pyAdded+26
orbiters/chameleon/scripts/list_filter_artifact.mjsAdded+46
orbiters/chameleon/scripts/list_filter_artifact.test.mjsAdded+38
orbiters/chameleon/scripts/list_filter_observation.mjsAdded+62
orbiters/chameleon/scripts/list_filter_observation.test.mjsAdded+42
orbiters/chameleon/scripts/list_filter_operator.mjsAdded+51
orbiters/chameleon/scripts/list_filter_operator.test.mjsAdded+75
orbiters/chameleon/scripts/local.pyAdded+140
orbiters/chameleon/scripts/lock_laya_runtime.pyAdded+30
orbiters/chameleon/scripts/metafold_acceptance.mjsAdded+29
orbiters/chameleon/scripts/metafold_acceptance.test.mjsAdded+27
orbiters/chameleon/scripts/metafold_arithmetic_candidate.mjsAdded+130
orbiters/chameleon/scripts/metafold_arithmetic_candidate.test.mjsAdded+98
orbiters/chameleon/scripts/metafold_clone.mjsAdded+50
orbiters/chameleon/scripts/metafold_clone.test.mjsAdded+59
orbiters/chameleon/scripts/metafold_correspondence.mjsAdded+45
orbiters/chameleon/scripts/metafold_correspondence.test.mjsAdded+36
orbiters/chameleon/scripts/metafold_dependencies.test.mjsAdded+20
orbiters/chameleon/scripts/metafold_laya_shadow.mjsAdded+28
orbiters/chameleon/scripts/metafold_laya_shadow.test.mjsAdded+13
orbiters/chameleon/scripts/metafold_observation.mjsAdded+22
orbiters/chameleon/scripts/metafold_observation.test.mjsAdded+21
orbiters/chameleon/scripts/metafold_package.mjsAdded+85
orbiters/chameleon/scripts/metafold_trafficcop_shadow.mjsAdded+22
orbiters/chameleon/scripts/migrate_local_behavior.pyAdded+80
orbiters/chameleon/scripts/module_dependencies.mjsAdded+52
orbiters/chameleon/scripts/module_dependencies.test.mjsAdded+22
orbiters/chameleon/scripts/module_dependency_driver.mjsAdded+4
orbiters/chameleon/scripts/module_references.mjsAdded+40
orbiters/chameleon/scripts/module_references.test.mjsAdded+24
orbiters/chameleon/scripts/multipage_contract.test.mjsAdded+36
orbiters/chameleon/scripts/package_backend_release.pyAdded+22
orbiters/chameleon/scripts/package_cli.pyAdded+17
orbiters/chameleon/scripts/package_curated_2048.pyAdded+43
orbiters/chameleon/scripts/package_gallery_six.pyAdded+35
orbiters/chameleon/scripts/package_repository_pilot.pyAdded+80
orbiters/chameleon/scripts/package_saved_demos.pyAdded+48
orbiters/chameleon/scripts/plan_dom_dependencies.pyAdded+87
orbiters/chameleon/scripts/plan_saved_build.pyAdded+29
orbiters/chameleon/scripts/plan_saved_mount.pyAdded+38
orbiters/chameleon/scripts/prepare_jev_presentation.mjsAdded+32
orbiters/chameleon/scripts/prepare_laya_artifact.pyAdded+119
orbiters/chameleon/scripts/prepare_verifier_tunnel.pyAdded+29
orbiters/chameleon/scripts/probe_repository_contracts.pyAdded+81
orbiters/chameleon/scripts/provision_box_a.pyAdded+210
orbiters/chameleon/scripts/provision_production_verifier.pyAdded+30
orbiters/chameleon/scripts/provision_rehearsal_verifier.pyAdded+31
orbiters/chameleon/scripts/publish_source_style_gallery.pyAdded+48