Customizing software over time requires agreements that survive change. I divided configuration, conversion, diagnostics, compatibility, proposal review and handoff into small pure functions in an independent synthetic module.
All examples are fixed and contain no company configuration or operational records. The viewer displays actual local example output. It performs no database update, external AI request, deployment or production recovery.
Validate settings and conversion proposals first
configuration accepts grammar version one, company identifier, fields and default quantity. Item and quantity are mandatory; memo is optional. Required-field removal, duplicates and unknown keys fail. The result is a copy, not a generated form or persistent company-settings service. A contract for allowed differences is distinct from rendering the interface.
migration_preview maps synthetic version-one qty into version-two quantity and adds draft. Every row is validated before a proposal is returned. Any invalid row stops the whole preview, the input stays unchanged and applied remains false. Current-version input is validated and copied. The function neither infers historical business meaning nor migrates an operational database.
Bound diagnostics and compatibility explicitly
error_record accepts fixed codes, operations and a constrained trace identifier, with no channel for an exception sentence or request body. It is not a log collector, retention policy or audit of other output layers. Format-valid identifiers can still carry meaning supplied by a caller, so real use needs opaque server-generated values and reviewed call sites.
compatibility compares a release’s declared readable schemas and writable schema with a data version. It distinguishes read-only access from permitted writes and blocks unsupported data. This calculates stated contracts rather than measuring executable compatibility. The result remains a preview: it does not deploy code, reverse-convert data or perform a production rollback.
Bind a proposal to its contents and base revision
proposal allows only bounded quantity and memo changes. Company scope, expected revision, author and before/after differences enter its fingerprint. review requires a different reviewer with the declared role and recomputes the proposal from current state. apply_reviewed checks the same basis before calculating the next value. Changing the base or proposed contents invalidates earlier review.
This is not authentication. Identities, roles and review receipts must come from trusted server context, never an unverified client claim. A hash is not a signature. These pure functions provide no durable approval store or concurrency lock. Production integration requires authorization and conditional transactional persistence. An agent-like author identifier does not mean an external model was called.
Explore the implementation
Complete independent synthetic implementation
"""Synthetic preview contracts; callers supply trusted identities and reads."""
from copy import deepcopy
from hashlib import sha256
import json,re
def integer(value,minimum=1,maximum=99):
if type(value) is not int or not minimum<=value<=maximum:raise ValueError('integer')
return value
def identifier(value):
if not isinstance(value,str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,40}',value):raise ValueError('identifier')
return value
def configuration(value):
if not isinstance(value,dict) or set(value)!={'version','company_id','fields','default_quantity'}:raise ValueError('configuration keys')
if type(value['version']) is not int or value['version']!=1:raise ValueError('configuration version')
identifier(value['company_id']);integer(value['default_quantity'])
fields=value['fields']
if not isinstance(fields,list) or any(x not in ('item','quantity','memo') for x in fields) or len(fields)!=len(set(fields)) or not {'item','quantity'}<=set(fields):raise ValueError('required or unknown fields')
return deepcopy(value)
def validate_row(row,version):
keys={'id','qty'} if version==1 else {'id','quantity','status'}
if not isinstance(row,dict) or set(row)!=keys:raise ValueError('row keys')
identifier(row['id']);integer(row['qty'] if version==1 else row['quantity'])
if version==2 and row['status'] not in ('draft','sent'):raise ValueError('row status')
def migration_preview(document):
if not isinstance(document,dict) or set(document)!={'schema','rows'}:raise ValueError('document keys')
version=document['schema']
if type(version) is not int or version not in (1,2):raise ValueError('unsupported schema')
rows=document['rows']
if not isinstance(rows,list) or len(rows)>100:raise ValueError('rows')
for row in rows:validate_row(row,version)
if len({r['id'] for r in rows})!=len(rows):raise ValueError('duplicate id')
result=deepcopy(document) if version==2 else {'schema':2,'rows':[{'id':r['id'],'quantity':r['qty'],'status':'draft'} for r in rows]}
return {'from_schema':version,'to_schema':2,'changed':version!=2,'proposed':result,'applied':False}
def error_record(code,operation,trace_id):
if code not in ('INVALID_INPUT','VERSION_CONFLICT','ACCESS_DENIED','UNEXPECTED'):raise ValueError('error code')
if operation not in ('read','save','preview'):raise ValueError('operation')
return {'code':code,'operation':operation,'trace_id':identifier(trace_id),'retry':code=='UNEXPECTED'}
def compatibility(code,data_schema):
if not isinstance(code,dict) or set(code)!={'release','reads','writes'}:raise ValueError('release keys')
identifier(code['release']);integer(data_schema,1,2);integer(code['writes'],1,2)
reads=code['reads']
if not isinstance(reads,list) or not reads or any(type(x) is not int or x not in (1,2) for x in reads) or len(reads)!=len(set(reads)) or code['writes'] not in reads:raise ValueError('read schemas')
readable=data_schema in reads
# A writer of another schema is not permitted to overwrite this data.
writable=readable and data_schema==code['writes']
return {'release':code['release'],'readable':readable,'writable':writable,'mode':'read_write' if writable else ('read_only' if readable else 'blocked'),'executed':False}
def validate_state(state):
if not isinstance(state,dict) or set(state)!={'company_id','revision','quantity','memo'}:raise ValueError('state keys')
identifier(state['company_id']);integer(state['revision'],1,1000000);integer(state['quantity'])
if not isinstance(state['memo'],str) or not re.fullmatch(r'[A-Za-z0-9 _-]{0,40}',state['memo']):raise ValueError('memo')
def proposal(state,changes,author):
validate_state(state);identifier(author)
if not isinstance(changes,dict) or not changes or not set(changes)<={'quantity','memo'}:raise ValueError('change fields')
after={**state,**changes};validate_state(after)
diff={k:{'before':state[k],'after':changes[k]} for k in sorted(changes) if changes[k]!=state[k]}
if not diff:raise ValueError('no change')
payload={'company_id':state['company_id'],'expected_revision':state['revision'],'author':author,'diff':diff}
digest=sha256(json.dumps(payload,sort_keys=True,separators=(',',':')).encode()).hexdigest()
return {**payload,'fingerprint':digest}
def review(state,proposed,reviewer,role):
identifier(reviewer)
if role!='reviewer' or reviewer==proposed['author']:raise ValueError('review role')
expected=proposal(state,{k:v['after'] for k,v in proposed['diff'].items()},proposed['author'])
if proposed!=expected:raise ValueError('changed proposal or base')
return {'fingerprint':expected['fingerprint'],'reviewer':reviewer,'approved':True}
def apply_reviewed(state,proposed,receipt):
# Receipt must come from a trusted review service, not a client-submitted claim.
if not isinstance(receipt,dict) or set(receipt)!={'fingerprint','reviewer','approved'} or receipt['approved'] is not True:raise ValueError('review receipt')
expected=review(state,proposed,receipt['reviewer'],'reviewer')
if receipt!=expected:raise ValueError('receipt mismatch')
out=deepcopy(state)
for field,change in proposed['diff'].items():out[field]=change['after']
out['revision']=integer(out['revision']+1,1,1000000);return out
def handoff_manifest(revision,files,items):
integer(revision,1,1000000)
if not isinstance(files,dict) or not files or len(files)>20:raise ValueError('files')
for name,digest in files.items():
if not isinstance(name,str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,40}\.(?:py|json|txt)',name) or not isinstance(digest,str) or not re.fullmatch(r'[a-f0-9]{64}',digest):raise ValueError('file hash')
if not isinstance(items,list) or not items or len(items)>100:raise ValueError('items')
ids=[]
for item in items:
if not isinstance(item,dict) or set(item)!={'id','status','evidence'}:raise ValueError('item keys')
ids.append(identifier(item['id']))
if item['status'] not in ('todo','done'):raise ValueError('item status')
if not isinstance(item['evidence'],list) or any(x not in files for x in item['evidence']) or (item['status']=='done' and not item['evidence']):raise ValueError('completion evidence')
if len(ids)!=len(set(ids)):raise ValueError('item duplicate')
return {'schema':1,'expected_revision':revision,'files':deepcopy(files),'items':deepcopy(items)}
def verify_handoff(manifest,current_revision,contents):
integer(current_revision,1,1000000)
rebuilt=handoff_manifest(manifest['expected_revision'],manifest['files'],manifest['items'])
if manifest!=rebuilt or current_revision!=manifest['expected_revision']:raise ValueError('state changed')
for name,digest in manifest['files'].items():
if name not in contents or not isinstance(contents[name],bytes) or sha256(contents[name]).hexdigest()!=digest:raise ValueError('artifact changed')
return {'verified':True,'done':sum(x['status']=='done' for x in manifest['items']),'remaining':[x['id'] for x in manifest['items'] if x['status']=='todo'],'executed':False}Check handoff evidence as values
handoff_manifest contains bounded filenames, SHA-256 values, expected data revision, task identities and statuses. Done requires a listed evidence file; todo remains explicitly pending. verify_handoff compares supplied bytes and the caller’s current revision. It does not discover fresh filesystem state or execute instructions contained in a document.
Eighteen local tests passed, including a fresh package extraction. The viewer presents configuration, conversion, error, compatibility, proposal and handoff examples. Evidence existence and evidence sufficiency differ. A trusted source and the actual completion judgment need review. This module checks structure and byte agreement; it cannot certify that every claim in an artifact is true.
Attach operational boundaries before reuse
Start integration by establishing where company scope and roles come from. Moving from preview to application requires a fresh read and an expected-version check inside the write transaction. Hash verification also needs trusted source bytes and a trustworthy reference manifest. A receipt or fingerprint from an arbitrary location must not become a security permission.
The ZIP contains complete implementation, tests, runner, fixed records and guidance, with permission to modify and reuse this independent synthetic code. Separate cross-module checks cover compatibility after conversion and preservation of a newer draft after review conflict. I share explicit agreements about proposals, confirmation and actual execution rather than present a large feature list as evidence that all operational responsibilities are complete.