Freeze reviewed KEY39 source-design decision publication packet
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 1s

This commit is contained in:
codex 2026-10-11 19:04:01 +02:00
parent 35252d35d7
commit cdac98dfd4
33 changed files with 1869 additions and 0 deletions

View file

@ -0,0 +1,10 @@
{
"status": "exact_source_match",
"module_sha256": {
"api.services.memo_dispatch": "0142b738750adee0feea38d2c73b2d9bf44c148c608f33803e644085aeb89052",
"api.services.memo_forwarding": "944c96ca48fd234ad229ceb61254f6f50cad75005495f5fe4c510e46ebec1193",
"api.services.informed_decision_contract": "127061a71e55dc3033aeb63047f3dafe7cc1f84d0ac53b7da6c51148d93584e7"
},
"token_read": false,
"native_mutation": false
}

View file

@ -0,0 +1,34 @@
{
"status": "ready_for_human_source_review",
"memo_id": "infd-20261011-key39-source-design-r1",
"version": 1,
"native_authorized": false,
"artifacts": {
"lifecycle-commands.json": "36e20813596f3ddbb86e01fd0b838867ece2f4916c5880305cf12cd61b567f89",
"source-inventory.json": "aea196db9e513900d5e7165455d6e9c3dc68749a606dc219ec340ac595642cc0",
"submit_reviewed_source.py": "8e8846f79989db25900717399b3b5f8fed2510521f5a5dabd35483d0f2bb9f3f",
"build_packet.py": "ad4886e5946eafd88a7d3578e2c363d6174223391b792dbd052f23defb9a9267",
"preflight.py": "0e19d2ff049efbe1556e11a4f27ddbe9fb2e892155b7a36dbdfa37832ac4c572",
"correlation.py": "7d03880678f60b6aabf5c5d27cc56fb66cfa27030f329f04dcee7c3f878649e6"
},
"independent_reviews": {
"packet": {
"decision": "approved",
"receipt_sha256": "97c34d5434a3610fe59596b6bd39eb7d154362b3b7afc8db91ac4232bc5a230a"
},
"helper": {
"decision": "approved",
"receipt_sha256": "92c5adca58a1983b8a39b496b48fd68133215de989a3ff40e6ef51b23fa6795c"
}
},
"authority_basis": [
"User explicitly authorized Informed Decision proposals for founder choices",
"STATE-WP-0096 approved admitted State Hub workload cutover d2eaa2e9-6d11-4676-a07f-e3b7e59a88e3 and native human acceptance",
"No new caller, credential grant, producer custody or native KEY39 action"
],
"expected_result": "Exact original-author memo version1 published to net-kingdom-admins and exact review envelope queued; source-only disposition pending",
"uncertainty": "Exclusive retained sentinel before first transport; no blind replay, reconcile exact stable operation keys and review identity",
"cost": "No new image or infrastructure; existing workload API calls only",
"risk": "Partial authoring/queue failure retained; no native infrastructure mutation or private caller-token handoff",
"observed_at": "2026-10-11T17:03:28.244104+00:00"
}

View file

@ -0,0 +1,37 @@
{
"observed_at": "2026-10-11T16:52:59.059851+00:00",
"metadata_only": true,
"token_read": false,
"native_mutation": false,
"deployments": [
{
"namespace": "state-hub",
"deployment": "state-hub-memo-dispatch",
"uid": "45dad76a-7eb9-4092-950b-3ccc2699492d",
"generation": 2,
"observed_generation": 2,
"ready_replicas": 1,
"service_account": "state-hub",
"images": "dispatcher=forgejo.coulomb.social/coulomb/state-hub-memo-dispatch@sha256:410fb6b6c9fd7a7ee0b63d727fd3249fb3ae13943421d6a5ce88b7ad2520bd2f;",
"status": "observed"
},
{
"namespace": "informed-decision",
"deployment": "informed-decision",
"uid": "a588e10a-90d2-4883-975e-6dd8b8feca92",
"generation": 26,
"observed_generation": 26,
"ready_replicas": 1,
"service_account": "review",
"images": "informed-decision=forgejo.coulomb.social/coulomb/informed-decision@sha256:f5588f496b1f267d07cdc9f5208e6f2f241f74b739c23924b03702dec13a5c23;",
"status": "observed"
}
],
"node_address_verification": {
"node_address_verified": true,
"expected_node_ip": "92.205.62.239",
"metadata_only": true,
"native_mutation": false,
"raw_errors_emitted": false
}
}

View file

@ -0,0 +1,42 @@
"""Offline exact source-design packet builder. Does not contact any service."""
import argparse,base64,hashlib,json,re,subprocess
from pathlib import Path
ID="infd-20261011-key39-source-design-r1"
SOURCES=[
("key-cape","docs/proposals/2026-10-11-key39-founder-source-design-decision.md","1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688"),
("key-cape","docs/proposals/2026-10-11-key39-founder-source-design-decision.json","d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091"),
("key-cape","docs/reviews/2026-10-11-key39-v9-v4-keycape-source-ack.json","4108d3afde1756c3889e6092878afd99a1193e59971ffe04d3845bbe21a42c7e"),
("railiance-platform","docs/reviews/2026-10-11-key39-ready-pair-v9-v4-platform-review.json","cb2729781cfce7637d7a4ba29412edde64d337c5efe3148600bd39fb12166894"),
("net-kingdom","docs/reviews/2026-10-11-key39-producer-v4-net-review.json","9566955b77db4a0b041887ef4a6aff6c7a02ef30cc0727a4deb6c29bbdc79518")]
def digest(raw):return hashlib.sha256(raw).hexdigest()
def build(revisions):
documents=[];packet=[];sources=[]
for index,(repo,relative,sha) in enumerate(SOURCES):
revision=revisions[repo]
if not re.fullmatch("[0-9a-f]{40}",revision):raise ValueError("exact_source_revision_required")
root=Path("/home/worsch")/repo
raw=subprocess.check_output(["git","show",revision+":"+relative],cwd=root,stderr=subprocess.DEVNULL)
if digest(raw)!=sha or (root/relative).read_bytes()!=raw:raise ValueError("source_currency_refused")
name=Path(relative).name;item="source-"+str(index+1)
packet.append({"item_id":item,"label":name,"hash":"sha256:"+sha})
documents.append({"digest":"sha256:"+sha,"media_type":"text/markdown" if relative.endswith(".md") else "application/json","content_base64":base64.b64encode(raw).decode()})
sources.append({"repo":repo,"path":relative,"source_revision":revision,"sha256":sha})
inventory={"schema":"key39-source-publication-sources/v1","memo_id":ID,"version":1,"native_authorized":False,"sources":sources}
inventory_raw=(json.dumps(inventory,indent=2)+"\n").encode();inventory_sha=digest(inventory_raw)
packet.append({"item_id":"source-inventory","label":"source-inventory.json","hash":"sha256:"+inventory_sha})
documents.append({"digest":"sha256:"+inventory_sha,"media_type":"application/json","content_base64":base64.b64encode(inventory_raw).decode()})
brief="Source-design direction only for the four explicit choices in the exact attached founder memo: existing human-client purpose reuse, return or prepare coding-agent custody admission, proposed direct SSH source profile, and conditional exclusive-owner tmpfs-file design. All native login, credential access, client registration, SSH/port-forward, restart, mutation and task closure remain gated. No partial/absent choice authorizes native execution. Owner reviews establish only source compatibility; provider MFA, real custody, route, plugin/leeway, adoption/maintenance exception and fresh authenticated native go remain pending."
memo={"id":ID,"version":1,"question":"Approve the recommended four source-design directions for KEY39's reviewed producer V4 / consumer V9, retaining every separate native admission and custody gate?","requested_act":"approve","binding_level":"organizational","brief":brief,"binding":{"principal":{"id":"pending-human-session","kind":"person","display_name":"Founder source-design direction"},"target":{"kind":"resource","id":"KEY-WP-0039-T02/founder-source-design-v1","label":"KEY39 paired input source-design directions","environment":"build"},"terms":brief+" Scope is exact owner memo sha256:1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688 and JSON sha256:d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091. Architecture-wide v0.9, standing/default privileges and agent autonomy are not approved."},"step_kind":"approve","packet":packet,"highlights":[{"id":"source-direction-only","item_id":"source-1","note":brief,"required_ack":True,"severity":"warning","locator":{"kind":"section","heading":"Choices to record"}}],"sealed":False,"approval_id":None,"approval_binding_digest":None}
command={"id":ID,"register":{"memo":memo,"documents":documents},"publish":{"version":1,"audience":{"subjects":[],"groups":["net-kingdom-admins"]}},"review":{"version":1,"options":{"submitter":"state-hub","memo_class":"decision-record","review_group":"net-kingdom-admins","approval_intent":{"action":"acknowledge","principal":"net-kingdom-admins","purpose":brief,"target":{"id":"KEY-WP-0039-T02/founder-source-design-v1","type":"source-design","system":"key-cape"}}}}}
if len(json.dumps(command["register"]).encode())>256*1024:raise ValueError("payload_limit_refused")
return command,inventory
def main():
p=argparse.ArgumentParser();p.add_argument("--key-revision",required=True);p.add_argument("--net-revision",required=True);p.add_argument("--platform-revision",required=True);p.add_argument("--output",type=Path,required=True);a=p.parse_args()
c,s=build({"key-cape":a.key_revision,"net-kingdom":a.net_revision,"railiance-platform":a.platform_revision})
a.output.mkdir(parents=True,exist_ok=True)
for name,value in [("lifecycle-commands.json",[c]),("source-inventory.json",s)]:
path=a.output/name
if path.exists():raise ValueError("existing_output_refused")
path.write_text(json.dumps(value,indent=2)+"\n")
print(json.dumps({"status":"source_prepared_only","memo_id":ID,"registration_bytes":len(json.dumps(c["register"]).encode())}))
if __name__=="__main__":main()

View file

@ -0,0 +1,38 @@
{
"schema": "key39-source-publication-sources/v1",
"memo_id": "infd-20261011-key39-source-design-r1",
"version": 1,
"native_authorized": false,
"sources": [
{
"repo": "key-cape",
"path": "docs/proposals/2026-10-11-key39-founder-source-design-decision.md",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688"
},
{
"repo": "key-cape",
"path": "docs/proposals/2026-10-11-key39-founder-source-design-decision.json",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091"
},
{
"repo": "key-cape",
"path": "docs/reviews/2026-10-11-key39-v9-v4-keycape-source-ack.json",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "4108d3afde1756c3889e6092878afd99a1193e59971ffe04d3845bbe21a42c7e"
},
{
"repo": "railiance-platform",
"path": "docs/reviews/2026-10-11-key39-ready-pair-v9-v4-platform-review.json",
"source_revision": "6bb406eb15920711d047ef34aaa4ffa56f088803",
"sha256": "cb2729781cfce7637d7a4ba29412edde64d337c5efe3148600bd39fb12166894"
},
{
"repo": "net-kingdom",
"path": "docs/reviews/2026-10-11-key39-producer-v4-net-review.json",
"source_revision": "7ceac4372d38354ae345eb40bc31c1cdbd39e4e5",
"sha256": "9566955b77db4a0b041887ef4a6aff6c7a02ef30cc0727a4deb6c29bbdc79518"
}
]
}

View file

@ -0,0 +1,92 @@
"""Exact KEY39 source-design publication. No native KEY39 actuation."""
import argparse,hashlib,json,re,subprocess,sys
from pathlib import Path
from build_packet import build,ID
if sys.flags.optimize:raise SystemExit('optimized_interpreter_refused')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def prepare(directory,ready_path,ready_sha):
if sha(ready_path)!=ready_sha:raise ValueError('reviewed_readiness_bytes_refused')
r=json.loads(ready_path.read_bytes())
if r.get('status')!='ready_for_human_source_review' or r.get('memo_id')!=ID or r.get('version')!=1 or r.get('native_authorized') is not False:raise ValueError('posting_gate_refused')
artifacts={n:sha(directory/n) for n in ['lifecycle-commands.json','source-inventory.json','submit_reviewed_source.py','build_packet.py']}
if sha(Path(__file__))!=artifacts['submit_reviewed_source.py'] or sha(Path(__file__).with_name('build_packet.py'))!=artifacts['build_packet.py']:raise ValueError('invoked_source_refused')
if r.get('artifacts')!=artifacts or set(r.get('independent_reviews',{}))!={'packet','helper'}:raise ValueError('exact_independent_posting_gates_refused')
for value in r['independent_reviews'].values():
if not isinstance(value,dict) or value.get('decision')!='approved' or not re.fullmatch('[0-9a-f]{64}',value.get('receipt_sha256','')):raise ValueError('independent_review_refused')
inventory=json.loads((directory/'source-inventory.json').read_bytes())
revisions={s['repo']:s['source_revision'] for s in inventory['sources']}
c,expected=build(revisions)
commands=json.loads((directory/'lifecycle-commands.json').read_bytes())
if inventory!=expected or commands!=[c]:raise ValueError('exact_source_command_refused')
return c,artifacts
REMOTE='''import json,re,signal,urllib.request,urllib.error
from api.services.memo_dispatch import Dispatcher,ORIGIN,NoRedirect,token_file
class Refused(Exception):pass
def deadline(*args):raise Refused('bounded_operation_unverified')
signal.signal(signal.SIGALRM,deadline)
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
def call(method,path,body=None,key=None):
if not (path=='/v1/decisions' or path.startswith('/v1/decisions/'+ident+'/')):raise Refused('route_refused')
signal.setitimer(signal.ITIMER_REAL,25)
try:
raw=json.dumps(body,allow_nan=False).encode() if body is not None else None
if raw is not None and len(raw)>256*1024:raise Refused('input_too_large')
headers={'Authorization':'Bearer '+token_file('/var/run/secrets/state-hub/informed-decision/lifecycle-token'),'Content-Type':'application/json'}
if key:headers['Idempotency-Key']=key
req=urllib.request.Request(ORIGIN+path,data=raw,headers=headers,method=method)
try:response=opener.open(req,timeout=20)
except urllib.error.HTTPError as error:response=error
with response:
payload=response.read(1024*1024+1)
if len(payload)>1024*1024 or response.code not in (200,201):raise Refused('operation_unverified')
value=json.loads(payload)
if not isinstance(value,dict):raise Refused('response_unverified')
return value
finally:signal.setitimer(signal.ITIMER_REAL,0)
def uuid(value):
if not isinstance(value,str) or not re.fullmatch('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}',value):raise Refused('event_identity_refused')
return value
action='prepare'
try:
receipts={}
action='register';receipts[action]=call('POST','/v1/decisions',command[action],'security-consolidation.'+ident+'.register.v1')
for action,suffix in [('publish','publications'),('review','review-requests')]:
receipts[action]=call('POST','/v1/decisions/'+ident+'/'+suffix,command[action],'security-consolidation.'+ident+'.'+action+'.v1')
handoff=receipts['review'];review_id=handoff['review_memo_id']
if not isinstance(review_id,str) or not review_id.startswith('review-'):raise Refused('review_identity_refused')
uuid(review_id[7:])
action='enqueue';signal.setitimer(signal.ITIMER_REAL,25)
queued=Dispatcher('/data/private').enqueue(handoff['envelope']);signal.setitimer(signal.ITIMER_REAL,0)
action='outcomes';outcome=call('GET','/v1/decisions/'+ident+'/outcomes?version=1')
state=queued.status
if not isinstance(state,str) or not re.fullmatch('[a-z_-]{1,32}',state):raise Refused('queue_state_refused')
result={'memo_id':ident,'version':1,'review_memo_id':review_id,'queue_status':state,'human_dispositions':len(outcome.get('dispositions',[])),'native_key39_action_performed':False}
for key,op in [('register_event_id','register'),('publication_event_id','publish'),('review_event_id','review')]:result[key]=uuid(receipts[op]['event_id'])
print(json.dumps(result),flush=True)
except BaseException:
signal.setitimer(signal.ITIMER_REAL,0)
print(json.dumps({'memo_id':ident,'action':action,'status':'operation_unverified'}),flush=True)
raise SystemExit(1) from None
'''
def main():
p=argparse.ArgumentParser();p.add_argument('--directory',required=True,type=Path);p.add_argument('--readiness',required=True,type=Path);p.add_argument('--readiness-sha256',required=True);p.add_argument('--receipt',required=True,type=Path);p.add_argument('--check-only',action='store_true');a=p.parse_args()
if not re.fullmatch('[0-9a-f]{64}',a.readiness_sha256):raise SystemExit('exact_readiness_digest_required')
command,artifacts=prepare(a.directory,a.readiness,a.readiness_sha256)
if a.receipt.exists():raise SystemExit('existing_receipt_refused_no_blind_replay')
program='command='+repr(command)+'\nident='+repr(ID)+'\n'+REMOTE
proof={'memo_id':ID,'artifacts':artifacts,'authoring_program_sha256':hashlib.sha256(program.encode()).hexdigest(),'readiness_sha256':a.readiness_sha256}
if a.check_only:
print(json.dumps(dict(proof,status='source_only_check_passed')));return
# Before transport, retain uncertainty sentinel. Never overwrite an original outcome.
with a.receipt.open('x') as stream:stream.write(json.dumps(dict(proof,status='submission_unverified',do_not_blindly_replay=True))+'\n')
try:
run=subprocess.run(['ssh','railiance01','kubectl -n state-hub exec -i deployment/state-hub-memo-dispatch -c dispatcher -- python -'],input=program,text=True,capture_output=True,timeout=150)
result=json.loads(run.stdout)
allowed={'memo_id','version','review_memo_id','queue_status','human_dispositions','native_key39_action_performed','register_event_id','publication_event_id','review_event_id'}
if run.returncode or not isinstance(result,dict) or set(result)!=allowed or result['memo_id']!=ID or result['native_key39_action_performed'] is not False:raise ValueError('submission_unverified')
except Exception:
print(json.dumps({'memo_id':ID,'status':'submission_unverified','receipt_retained':True}));raise SystemExit(1) from None
final=a.receipt.with_name(a.receipt.name+'.confirmed.json')
with final.open('x') as stream:stream.write(json.dumps(dict(proof,**result,status='authored_and_queued'),indent=2)+'\n')
print(json.dumps(dict(result,status='authored_and_queued')))
if __name__=='__main__':main()

View file

@ -0,0 +1,15 @@
# KEY39 source-design posting successor V2 — unsubmitted
This immutable source stage repairs F01–F03 from the retained independent technical review. It is preparation only: no credentials, SSH, authoring request, queue submission, runtime change, or native KEY39 action has run.
The memo ID remains `infd-20261011-key39-source-design-r1`, source version 1. The original source stage was never submitted. All registration memo fields and six packet documents are identical to the original stage, including the full source-only limits and committed owner memo/ack bytes at KeyCape 0f47e0c, NetKingdom 7ceac43 and Platform 6bb406e. Only the review approval-intent purpose is changed to the exact reviewed 343-character concise string. Existing frozen commands, helper, counterexamples and uncertainty evidence are untouched.
`prepare()` rebuilds exact committed/current source bytes and validates the complete expected lifecycle review projection through current provider `records`, `lifecycle_review.supports_review`, intake `validate_submission` and State Hub `validate_envelope` before returning an authoring program. The expected projection follows the actual provider principal replacement and record defaults. These local source contracts do not prove deployed service source pins or authenticated runtime admission.
The remote program checks registration and publication memo ID/version and event IDs before continuing. It compares the full returned handoff with the exact expected memo projection, document contents, approval intent, routing and review ID/idempotency key. Nothing is reconstructed or altered for enqueue: the equal retained envelope is submitted as-is. Dispatcher confirmation requires the exact returned key and either `pending/queued` or `replay/replay` with a matching bounded receipt. Blocked, unknown, retry-wait and malformed results remain unverified, preserving the pre-transport sentinel; they do not trigger replay.
Outcomes must contain the exact retained review ID and `stale=false`, with a known intake state and any review path matching that ID. The provider outcomes API has no returned source-version field: correlation relies on the exact `/outcomes?version=1` query, the retained version-specific handoff and the provider's stale check. No invented response field or inferred human acceptance is used. A queued receipt does not prove delivery. A human review link is usable only after separate verified `ready` intake/path evidence; the helper does not declare that readiness.
The posting gate still requires separate independently approved packet/helper receipts bound to all six exact artifact hashes. Hash syntax is not reviewer authentication: root must verify real review receipts and source currency before supplying readiness. These changes confer no new actor or credential authority. The previously established STATE96 admitted dispatcher path is reused only when independently reviewed and authorized; existing per-operation keys and exclusive uncertainty receipt are preserved. No automatic rerun after uncertainty.
31 source checks pass. One test exercises actual provider register/publication/review preparation and outcomes in a disposable private SQLite store, then the actual State Hub forwarding ledger. Other tests retain blocked/conflict/replay semantics and exercise the actual remote program with only HTTP/dispatcher transport replaced by fixtures. No native/MFA/SSH credentials or protected content is accessed.

View file

@ -0,0 +1,42 @@
"""Offline exact source-design packet builder. Does not contact any service."""
import argparse,base64,hashlib,json,re,subprocess
from pathlib import Path
ID="infd-20261011-key39-source-design-r1"
SOURCES=[
("key-cape","docs/proposals/2026-10-11-key39-founder-source-design-decision.md","1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688"),
("key-cape","docs/proposals/2026-10-11-key39-founder-source-design-decision.json","d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091"),
("key-cape","docs/reviews/2026-10-11-key39-v9-v4-keycape-source-ack.json","4108d3afde1756c3889e6092878afd99a1193e59971ffe04d3845bbe21a42c7e"),
("railiance-platform","docs/reviews/2026-10-11-key39-ready-pair-v9-v4-platform-review.json","cb2729781cfce7637d7a4ba29412edde64d337c5efe3148600bd39fb12166894"),
("net-kingdom","docs/reviews/2026-10-11-key39-producer-v4-net-review.json","9566955b77db4a0b041887ef4a6aff6c7a02ef30cc0727a4deb6c29bbdc79518")]
def digest(raw):return hashlib.sha256(raw).hexdigest()
def build(revisions):
documents=[];packet=[];sources=[]
for index,(repo,relative,sha) in enumerate(SOURCES):
revision=revisions[repo]
if not re.fullmatch("[0-9a-f]{40}",revision):raise ValueError("exact_source_revision_required")
root=Path("/home/worsch")/repo
raw=subprocess.check_output(["git","show",revision+":"+relative],cwd=root,stderr=subprocess.DEVNULL)
if digest(raw)!=sha or (root/relative).read_bytes()!=raw:raise ValueError("source_currency_refused")
name=Path(relative).name;item="source-"+str(index+1)
packet.append({"item_id":item,"label":name,"hash":"sha256:"+sha})
documents.append({"digest":"sha256:"+sha,"media_type":"text/markdown" if relative.endswith(".md") else "application/json","content_base64":base64.b64encode(raw).decode()})
sources.append({"repo":repo,"path":relative,"source_revision":revision,"sha256":sha})
inventory={"schema":"key39-source-publication-sources/v1","memo_id":ID,"version":1,"native_authorized":False,"sources":sources}
inventory_raw=(json.dumps(inventory,indent=2)+"\n").encode();inventory_sha=digest(inventory_raw)
packet.append({"item_id":"source-inventory","label":"source-inventory.json","hash":"sha256:"+inventory_sha})
documents.append({"digest":"sha256:"+inventory_sha,"media_type":"application/json","content_base64":base64.b64encode(inventory_raw).decode()})
brief="Source-design direction only for the four explicit choices in the exact attached founder memo: existing human-client purpose reuse, return or prepare coding-agent custody admission, proposed direct SSH source profile, and conditional exclusive-owner tmpfs-file design. All native login, credential access, client registration, SSH/port-forward, restart, mutation and task closure remain gated. No partial/absent choice authorizes native execution. Owner reviews establish only source compatibility; provider MFA, real custody, route, plugin/leeway, adoption/maintenance exception and fresh authenticated native go remain pending."
memo={"id":ID,"version":1,"question":"Approve the recommended four source-design directions for KEY39's reviewed producer V4 / consumer V9, retaining every separate native admission and custody gate?","requested_act":"approve","binding_level":"organizational","brief":brief,"binding":{"principal":{"id":"pending-human-session","kind":"person","display_name":"Founder source-design direction"},"target":{"kind":"resource","id":"KEY-WP-0039-T02/founder-source-design-v1","label":"KEY39 paired input source-design directions","environment":"build"},"terms":brief+" Scope is exact owner memo sha256:1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688 and JSON sha256:d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091. Architecture-wide v0.9, standing/default privileges and agent autonomy are not approved."},"step_kind":"approve","packet":packet,"highlights":[{"id":"source-direction-only","item_id":"source-1","note":brief,"required_ack":True,"severity":"warning","locator":{"kind":"section","heading":"Choices to record"}}],"sealed":False,"approval_id":None,"approval_binding_digest":None}
command={"id":ID,"register":{"memo":memo,"documents":documents},"publish":{"version":1,"audience":{"subjects":[],"groups":["net-kingdom-admins"]}},"review":{"version":1,"options":{"submitter":"state-hub","memo_class":"decision-record","review_group":"net-kingdom-admins","approval_intent":{"action":"acknowledge","principal":"net-kingdom-admins","purpose":"Acknowledge four exact KEY39 producer V4 / consumer V9 source-design directions in the attached founder memo. Source compatibility only; no native execution, credentials, SSH admission, client registration, task closure, architecture-wide acceptance or agent-autonomy grant. All custody, runtime and fresh native approval gates remain pending.","target":{"id":"KEY-WP-0039-T02/founder-source-design-v1","type":"source-design","system":"key-cape"}}}}}
if len(json.dumps(command["register"]).encode())>256*1024:raise ValueError("payload_limit_refused")
return command,inventory
def main():
p=argparse.ArgumentParser();p.add_argument("--key-revision",required=True);p.add_argument("--net-revision",required=True);p.add_argument("--platform-revision",required=True);p.add_argument("--output",type=Path,required=True);a=p.parse_args()
c,s=build({"key-cape":a.key_revision,"net-kingdom":a.net_revision,"railiance-platform":a.platform_revision})
a.output.mkdir(parents=True,exist_ok=True)
for name,value in [("lifecycle-commands.json",[c]),("source-inventory.json",s)]:
path=a.output/name
if path.exists():raise ValueError("existing_output_refused")
path.write_text(json.dumps(value,indent=2)+"\n")
print(json.dumps({"status":"source_prepared_only","memo_id":ID,"registration_bytes":len(json.dumps(c["register"]).encode())}))
if __name__=="__main__":main()

View file

@ -0,0 +1,47 @@
"""Pure correlation for the exact reviewed source handoff; no authority or I/O."""
import base64, copy, json, re
class Refused(ValueError): pass
def uuid(value):
if not isinstance(value,str) or not re.fullmatch('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}',value):raise Refused('event_identity_refused')
return value
def expected_envelope(command,rid):
if not isinstance(rid,str) or not rid.startswith('review-'):raise Refused('review_identity_refused')
uuid(rid[7:])
memo=copy.deepcopy(command['register']['memo']);memo['id']=rid;memo['version']=1
memo['binding']['principal']={'id':'pending-human-session','kind':'person','display_name':'To be assigned'}
# Provider records parser emits defaults for all MEMO_KEYS; caller supplies projected_memo.
if '_projected_memo' in command:
memo=copy.deepcopy(command['_projected_memo']);memo['id']=rid
docs={d['digest']:d for d in command['register']['documents']}
packet=[{'item_id':i['item_id'],'media_type':docs[i['hash']]['media_type'],'content':base64.b64decode(docs[i['hash']]['content_base64'],validate=True).decode('utf-8')} for i in memo['packet']]
options=command['review']['options']
return {'kind':'informed-decision.memo-intake','version':1,'idempotency_key':rid,'memo_class':options['memo_class'],'review_group':options['review_group'],'approval_intent':options['approval_intent'],'memo':memo,'packet':packet}
def authored(receipt,ident,version):
if not isinstance(receipt,dict) or receipt.get('memo_id')!=ident or type(receipt.get('version')) is not int or receipt['version']!=version:raise Refused('authored_identity_refused')
uuid(receipt.get('event_id'))
def handoff_checked(receipt,command):
if not isinstance(receipt,dict):raise Refused('handoff_refused')
uuid(receipt.get('event_id'))
rid=receipt.get('review_memo_id');expected=expected_envelope(command,rid)
if receipt.get('envelope')!=expected:raise Refused('exact_handoff_refused')
return rid,expected
def queued_checked(queued,rid):
if queued.idempotency_key!=rid:raise Refused('queue_identity_refused')
# Fresh or retained exact pending queue, or already delivered exact replay only.
# The real forwarder compares the entire submission digest before these results.
if (queued.status,queued.detail) not in {('pending','queued'),('replay','replay')}:raise Refused('queue_confirmation_refused')
if queued.status=='replay':
receipt=queued.receipt
if not isinstance(receipt,dict) or receipt.get('memo_id')!=rid:raise Refused('queue_replay_identity_refused')
uuid(receipt.get('approval_id'))
if not isinstance(receipt.get('approval_binding_digest'),str) or not re.fullmatch('sha256:[a-f0-9]{64}',receipt['approval_binding_digest']):raise Refused('queue_replay_receipt_refused')
return queued.status
def outcomes_checked(outcome,rid):
if not isinstance(outcome,dict) or set(outcome)!={'review','dispositions'}:raise Refused('outcomes_refused')
review=outcome['review']
if not isinstance(review,dict) or review.get('memo_id')!=rid or review.get('stale') is not False:raise Refused('outcomes_identity_refused')
if review.get('intake_state') not in {'not_submitted','creating','created','ready'}:raise Refused('intake_state_refused')
if 'path' in review and (review['intake_state']!='ready' or review['path']!='/review?memo_id='+rid):raise Refused('review_path_refused')
if not isinstance(outcome['dispositions'],list):raise Refused('dispositions_refused')
# No dispositions are claimed or interpreted as native authority.
return len(outcome['dispositions'])

View file

@ -0,0 +1,48 @@
{
"schema": "key39-source-posting-successor-manifest/v2",
"stage": "/tmp/key39-source-decision-publication-v2",
"native_authorized": false,
"submitted": false,
"entries": [
{
"path": "README.md",
"sha256": "31bdf21698996bf761859473e2aa3bcd73bf8577ad56eeb38f744404d391182c"
},
{
"path": "build_packet.py",
"sha256": "ad4886e5946eafd88a7d3578e2c363d6174223391b792dbd052f23defb9a9267"
},
{
"path": "correlation.py",
"sha256": "7d03880678f60b6aabf5c5d27cc56fb66cfa27030f329f04dcee7c3f878649e6"
},
{
"path": "lifecycle-commands.json",
"sha256": "36e20813596f3ddbb86e01fd0b838867ece2f4916c5880305cf12cd61b567f89"
},
{
"path": "preflight.py",
"sha256": "0e19d2ff049efbe1556e11a4f27ddbe9fb2e892155b7a36dbdfa37832ac4c572"
},
{
"path": "repair-receipt.json",
"sha256": "54abcff35845fed556c92dc30c1678cb28d03076f424e3e61aa23b0c9b0617bc"
},
{
"path": "source-inventory.json",
"sha256": "aea196db9e513900d5e7165455d6e9c3dc68749a606dc219ec340ac595642cc0"
},
{
"path": "submit_reviewed_source.py",
"sha256": "7a6ae3edd9381aef28d8371b14f0c036f9ce78cc6bed7d18041b99fb4ce61709"
},
{
"path": "test_posting_contract.py",
"sha256": "58619b6248f047246dcf44984539edb3cfb697d23c0c57355aab35b83faffd70"
},
{
"path": "test_source_preparation.py",
"sha256": "75713161b2625509d1f7d0b8f814ed74203797e6c0d28f3283203ada673e578e"
}
]
}

View file

@ -0,0 +1,24 @@
"""Offline validation through actual provider projection/intake and State Hub contract."""
import json,sys
from dataclasses import replace
sys.path[:0]=['/home/worsch/informed-decision','/home/worsch/state-hub']
from informed_decision.records import memo_from,dumps
from informed_decision.memo import Principal
from informed_decision.intake import MEMO_KEYS,SubmitterGrant,validate_submission
from informed_decision.lifecycle_review import supports_review
from api.services.informed_decision_contract import validate_envelope
from correlation import expected_envelope
RID='review-11111111-1111-1111-1111-111111111111'
def validate(command):
memo=memo_from(command['register']['memo'])
if not supports_review(memo):raise ValueError('provider_profile_refused')
draft=replace(memo,id=RID,version=1,binding=replace(memo.binding,principal=Principal('pending-human-session','person','To be assigned')))
projection={k:v for k,v in json.loads(dumps(draft)).items() if k in MEMO_KEYS}
if dumps(memo_from(projection))!=dumps(draft):raise ValueError('lossy_provider_projection_refused')
projected=dict(command,_projected_memo=projection)
envelope=expected_envelope(projected,RID)
o=command['review']['options']
validate_submission(envelope,submitter_id=o['submitter'],grant=SubmitterGrant(o['submitter'],frozenset({o['memo_class']}),frozenset({o['review_group']})))
validate_envelope(envelope)
if len(dumps(envelope).encode())>256*1024:raise ValueError('provider_envelope_unbounded')
return projected,envelope

View file

@ -0,0 +1,65 @@
{
"schema": "key39-source-posting-repair-receipt/v2",
"technical_review_sha256": "a9b28922499a1815b9940d38a3fd0586610898b6e0dbfdc23931034d7cd94ab2",
"frozen_originals": {
"build_packet.py": "b450e0b3e2675c498b0f883104963e54e7f7d7b2e0cd4c894461742b6a6caa35",
"submit_reviewed_source.py": "5f46a8f7030395d63657263dea19bf9f2daa0afb0d863de4782d1d1999f6b3e1",
"lifecycle-commands.json": "193b53e32631a9dd31304981ac9fa3b7e0a5490b5002fc9ce1806c1d68c7f793",
"source-inventory.json": "aea196db9e513900d5e7165455d6e9c3dc68749a606dc219ec340ac595642cc0"
},
"provider_source_pins": [
{
"path": "/home/worsch/state-hub/api/services/memo_dispatch.py",
"sha256": "0142b738750adee0feea38d2c73b2d9bf44c148c608f33803e644085aeb89052"
},
{
"path": "/home/worsch/state-hub/api/services/memo_forwarding.py",
"sha256": "944c96ca48fd234ad229ceb61254f6f50cad75005495f5fe4c510e46ebec1193"
},
{
"path": "/home/worsch/state-hub/api/services/informed_decision_contract.py",
"sha256": "127061a71e55dc3033aeb63047f3dafe7cc1f84d0ac53b7da6c51148d93584e7"
},
{
"path": "/home/worsch/informed-decision/informed_decision/lifecycle_http.py",
"sha256": "d4b95421d54663f041a10b4f42ac9c013493fa7a770223ab45877b451a7a7c7d"
},
{
"path": "/home/worsch/informed-decision/informed_decision/lifecycle_review.py",
"sha256": "b6d69be6c56f3e2f411501083e199195190df6c740a01b07e82a476268ca3629"
},
{
"path": "/home/worsch/informed-decision/informed_decision/intake.py",
"sha256": "a733b4b608b9ea90b2c8293901aa14388a0bf0d3719f121038bfdcc1faca2038"
},
{
"path": "/home/worsch/informed-decision/informed_decision/records.py",
"sha256": "82f696151895c51b168144a3078d05764da3499b96917c465629ce0836fa8e33"
}
],
"checks": {
"unittest_discovery_command": "python3 -m unittest discover -s /tmp/key39-source-decision-publication-v2 -p 'test_*.py'",
"passed": 31,
"actual_provider_lifecycle_prepare_and_outcomes": true,
"actual_statehub_forwarder_ledger": true,
"transport_only_fixtures": true,
"purpose_characters": 343,
"registration_and_publication_unchanged": true,
"source_inventory_unchanged": true
},
"changes": [
"F01: concise purpose and full offline projection/intake/queue-contract validation",
"F02: exact pending/replay confirmation; retained blocked/conflict/retry/unknown refusals",
"F03: exact authored memo/version, complete review envelope, ForwardResult key, outcomes review identity/currentness correlation"
],
"submitted": false,
"native_authorized": false,
"credentials_accessed": false,
"original_uncertainty_preserved": true,
"limitations": [
"outcomes API does not return source version; exact version query + retained review identity + stale=false are required",
"queue acceptance is not delivery or human disposition",
"local provider source validation is not deployed runtime pinning evidence",
"independent review receipts and readiness not created by this maker"
]
}

View file

@ -0,0 +1,38 @@
{
"schema": "key39-source-publication-sources/v1",
"memo_id": "infd-20261011-key39-source-design-r1",
"version": 1,
"native_authorized": false,
"sources": [
{
"repo": "key-cape",
"path": "docs/proposals/2026-10-11-key39-founder-source-design-decision.md",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688"
},
{
"repo": "key-cape",
"path": "docs/proposals/2026-10-11-key39-founder-source-design-decision.json",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091"
},
{
"repo": "key-cape",
"path": "docs/reviews/2026-10-11-key39-v9-v4-keycape-source-ack.json",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "4108d3afde1756c3889e6092878afd99a1193e59971ffe04d3845bbe21a42c7e"
},
{
"repo": "railiance-platform",
"path": "docs/reviews/2026-10-11-key39-ready-pair-v9-v4-platform-review.json",
"source_revision": "6bb406eb15920711d047ef34aaa4ffa56f088803",
"sha256": "cb2729781cfce7637d7a4ba29412edde64d337c5efe3148600bd39fb12166894"
},
{
"repo": "net-kingdom",
"path": "docs/reviews/2026-10-11-key39-producer-v4-net-review.json",
"source_revision": "7ceac4372d38354ae345eb40bc31c1cdbd39e4e5",
"sha256": "9566955b77db4a0b041887ef4a6aff6c7a02ef30cc0727a4deb6c29bbdc79518"
}
]
}

View file

@ -0,0 +1,89 @@
"""Exact KEY39 source-design publication. No native KEY39 actuation."""
import argparse,hashlib,json,re,subprocess,sys
from pathlib import Path
from build_packet import build,ID
from preflight import validate
if sys.flags.optimize:raise SystemExit('optimized_interpreter_refused')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def prepare(directory,ready_path,ready_sha):
if sha(ready_path)!=ready_sha:raise ValueError('reviewed_readiness_bytes_refused')
r=json.loads(ready_path.read_bytes())
if r.get('status')!='ready_for_human_source_review' or r.get('memo_id')!=ID or r.get('version')!=1 or r.get('native_authorized') is not False:raise ValueError('posting_gate_refused')
artifacts={n:sha(directory/n) for n in ['lifecycle-commands.json','source-inventory.json','submit_reviewed_source.py','build_packet.py','preflight.py','correlation.py']}
if sha(Path(__file__))!=artifacts['submit_reviewed_source.py'] or sha(Path(__file__).with_name('build_packet.py'))!=artifacts['build_packet.py']:raise ValueError('invoked_source_refused')
if r.get('artifacts')!=artifacts or set(r.get('independent_reviews',{}))!={'packet','helper'}:raise ValueError('exact_independent_posting_gates_refused')
for value in r['independent_reviews'].values():
if not isinstance(value,dict) or value.get('decision')!='approved' or not re.fullmatch('[0-9a-f]{64}',value.get('receipt_sha256','')):raise ValueError('independent_review_refused')
inventory=json.loads((directory/'source-inventory.json').read_bytes())
revisions={s['repo']:s['source_revision'] for s in inventory['sources']}
c,expected=build(revisions)
commands=json.loads((directory/'lifecycle-commands.json').read_bytes())
if inventory!=expected or commands!=[c]:raise ValueError('exact_source_command_refused')
return validate(c)[0],artifacts
REMOTE='''import json,re,signal,urllib.request,urllib.error
from api.services.memo_dispatch import Dispatcher,ORIGIN,NoRedirect,token_file
def deadline(*args):raise Refused('bounded_operation_unverified')
signal.signal(signal.SIGALRM,deadline)
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
def call(method,path,body=None,key=None):
if not (path=='/v1/decisions' or path.startswith('/v1/decisions/'+ident+'/')):raise Refused('route_refused')
signal.setitimer(signal.ITIMER_REAL,25)
try:
raw=json.dumps(body,allow_nan=False).encode() if body is not None else None
if raw is not None and len(raw)>256*1024:raise Refused('input_too_large')
headers={'Authorization':'Bearer '+token_file('/var/run/secrets/state-hub/informed-decision/lifecycle-token'),'Content-Type':'application/json'}
if key:headers['Idempotency-Key']=key
req=urllib.request.Request(ORIGIN+path,data=raw,headers=headers,method=method)
try:response=opener.open(req,timeout=20)
except urllib.error.HTTPError as error:response=error
with response:
payload=response.read(1024*1024+1)
if len(payload)>1024*1024 or response.code not in (200,201):raise Refused('operation_unverified')
value=json.loads(payload)
if not isinstance(value,dict):raise Refused('response_unverified')
return value
finally:signal.setitimer(signal.ITIMER_REAL,0)
action='prepare'
try:
receipts={}
action='register';receipts[action]=call('POST','/v1/decisions',command[action],'security-consolidation.'+ident+'.register.v1')
authored(receipts[action],ident,1)
for action,suffix in [('publish','publications'),('review','review-requests')]:
receipts[action]=call('POST','/v1/decisions/'+ident+'/'+suffix,command[action],'security-consolidation.'+ident+'.'+action+'.v1')
if action=='publish':authored(receipts[action],ident,1)
handoff=receipts['review'];review_id,envelope=handoff_checked(handoff,command)
action='enqueue';signal.setitimer(signal.ITIMER_REAL,25)
queued=Dispatcher('/data/private').enqueue(envelope);signal.setitimer(signal.ITIMER_REAL,0)
state=queued_checked(queued,review_id)
action='outcomes';outcome=call('GET','/v1/decisions/'+ident+'/outcomes?version=1')
count=outcomes_checked(outcome,review_id)
result={'memo_id':ident,'version':1,'review_memo_id':review_id,'queue_status':state,'human_dispositions':count,'native_key39_action_performed':False}
for key,op in [('register_event_id','register'),('publication_event_id','publish'),('review_event_id','review')]:result[key]=uuid(receipts[op]['event_id'])
print(json.dumps(result),flush=True)
except BaseException:
signal.setitimer(signal.ITIMER_REAL,0)
print(json.dumps({'memo_id':ident,'action':action,'status':'operation_unverified'}),flush=True)
raise SystemExit(1) from None
'''
def main():
p=argparse.ArgumentParser();p.add_argument('--directory',required=True,type=Path);p.add_argument('--readiness',required=True,type=Path);p.add_argument('--readiness-sha256',required=True);p.add_argument('--receipt',required=True,type=Path);p.add_argument('--check-only',action='store_true');a=p.parse_args()
if not re.fullmatch('[0-9a-f]{64}',a.readiness_sha256):raise SystemExit('exact_readiness_digest_required')
command,artifacts=prepare(a.directory,a.readiness,a.readiness_sha256)
if a.receipt.exists():raise SystemExit('existing_receipt_refused_no_blind_replay')
program=(Path(__file__).with_name('correlation.py').read_text()+'\ncommand='+repr(command)+'\nident='+repr(ID)+'\n'+REMOTE)
proof={'memo_id':ID,'artifacts':artifacts,'authoring_program_sha256':hashlib.sha256(program.encode()).hexdigest(),'readiness_sha256':a.readiness_sha256}
if a.check_only:
print(json.dumps(dict(proof,status='source_only_check_passed')));return
# Before transport, retain uncertainty sentinel. Never overwrite an original outcome.
with a.receipt.open('x') as stream:stream.write(json.dumps(dict(proof,status='submission_unverified',do_not_blindly_replay=True))+'\n')
try:
run=subprocess.run(['ssh','railiance01','kubectl -n state-hub exec -i deployment/state-hub-memo-dispatch -c dispatcher -- python -'],input=program,text=True,capture_output=True,timeout=150)
result=json.loads(run.stdout)
allowed={'memo_id','version','review_memo_id','queue_status','human_dispositions','native_key39_action_performed','register_event_id','publication_event_id','review_event_id'}
if run.returncode or not isinstance(result,dict) or set(result)!=allowed or result['memo_id']!=ID or type(result['version']) is not int or result['version']!=1 or result['queue_status'] not in ('pending','replay') or result['native_key39_action_performed'] is not False:raise ValueError('submission_unverified')
except Exception:
print(json.dumps({'memo_id':ID,'status':'submission_unverified','receipt_retained':True}));raise SystemExit(1) from None
final=a.receipt.with_name(a.receipt.name+'.confirmed.json')
with final.open('x') as stream:stream.write(json.dumps(dict(proof,**result,status='authored_and_queued'),indent=2)+'\n')
print(json.dumps(dict(result,status='authored_and_queued')))
if __name__=='__main__':main()

View file

@ -0,0 +1,98 @@
"""Disposable real provider/forwarder integration; no network or credentials."""
import copy,io,json,sys,tempfile,types,unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
sys.path[:0]=[str(Path(__file__).parent),'/home/worsch/informed-decision','/home/worsch/state-hub']
import submit_reviewed_source as helper
from preflight import validate
from correlation import *
from informed_decision.lifecycle import Attribution,LifecycleRepository
from informed_decision.disposition import Actor,ActorKind
from informed_decision.records import memo_from
from informed_decision.lifecycle_review import prepare,outcomes
from informed_decision.store import Store
from api.services.memo_forwarding import MemoForwarder
rawcommand=json.loads(Path(__file__).with_name('lifecycle-commands.json').read_text())[0]
command,envelope=validate(rawcommand)
RID=envelope['memo']['id'];EVENT='33333333-3333-3333-3333-333333333333'
def make_queue(path):
return MemoForwarder(path,transport=lambda *a: (_ for _ in ()).throw(AssertionError('network forbidden')),intake_base_url='http://fixture.invalid',hub_base_url='http://fixture.invalid')
def execute(mutate=None,queue_mutate=None):
output=io.StringIO();sent=[]
responses={'register':{'event_id':EVENT,'memo_id':command['id'],'version':1},'publish':{'event_id':EVENT,'memo_id':command['id'],'version':1},'review':{'event_id':EVENT,'review_memo_id':RID,'envelope':copy.deepcopy(envelope)},'outcomes':{'review':{'memo_id':RID,'stale':False,'intake_state':'not_submitted'},'dispositions':[]}}
if mutate:mutate(responses)
def open_request(req,timeout):
action='outcomes' if 'outcomes' in req.full_url else 'review' if 'review-requests' in req.full_url else 'publish' if 'publications' in req.full_url else 'register'
class Response:
code=200
def __enter__(self):return self
def __exit__(self,*a):return False
def read(self,n):return json.dumps(responses[action]).encode()
return Response()
with tempfile.TemporaryDirectory() as td:
real=make_queue(Path(td)/'queue.sqlite')
class Dispatcher:
def __init__(self,path):pass
def enqueue(self,e):
sent.append(e);r=real.submit(e,dispatch=False)
return queue_mutate(real,e,r) if queue_mutate else r
fake=types.ModuleType('api.services.memo_dispatch');fake.Dispatcher=Dispatcher;fake.ORIGIN='http://fixture.invalid';fake.NoRedirect=__import__('urllib.request',fromlist=['HTTPRedirectHandler']).HTTPRedirectHandler;fake.token_file=lambda _: 'synthetic-fixture'
with patch.dict(sys.modules,{'api.services.memo_dispatch':fake}),patch('urllib.request.build_opener',return_value=types.SimpleNamespace(open=open_request)),patch('signal.signal'),patch('signal.setitimer'),redirect_stdout(output):
try:exec(Path(__file__).with_name('correlation.py').read_text()+'\n'+helper.REMOTE,{'command':copy.deepcopy(command),'ident':command['id']})
except SystemExit:pass
return json.loads(output.getvalue()),sent
class Contract(unittest.TestCase):
def test_real_provider_prepare_forwarder_and_outcomes(self):
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'private';p.mkdir(mode=0o700)
repo=LifecycleRepository(Store(p/'store.sqlite'));actor=Attribution('tenant:platform',Actor('synthetic-author',ActorKind.AGENT))
memo=memo_from(rawcommand['register']['memo'])
event=repo.register(actor,memo,key='fixture-register',documents=rawcommand['register']['documents']);authored({'event_id':event,'memo_id':memo.id,'version':memo.version},memo.id,1)
repo.publish(actor,memo.id,1,audience=rawcommand['publish']['audience'],key='fixture-publish')
handoff=prepare(repo,actor,memo.id,1,rawcommand['review']['options'],key='fixture-review',guard=lambda db:None)
rid,e=handoff_checked(handoff,command);self.assertEqual(e,expected_envelope(command,rid))
q=make_queue(p/'queue.sqlite');self.assertEqual(queued_checked(q.submit(e,dispatch=False),rid),'pending')
self.assertEqual(outcomes_checked(outcomes(repo,actor.tenant,memo.id,1),rid),0)
self.assertEqual(prepare(repo,actor,memo.id,1,rawcommand['review']['options'],key='fixture-review',guard=lambda db:None),handoff)
def test_concise_intent_and_full_scope_retained(self):
self.assertLessEqual(len(rawcommand['review']['options']['approval_intent']['purpose']),400)
self.assertEqual(rawcommand['register'],json.loads(Path('/tmp/key39-source-decision-publication/lifecycle-commands.json').read_text())[0]['register'])
def test_remote_exact_pending_success(self):
result,sent=execute();self.assertEqual(result['queue_status'],'pending');self.assertEqual(len(sent),1)
def refusal(self,mutate=None,queue_mutate=None,enqueue_expected=0):
result,sent=execute(mutate,queue_mutate);self.assertEqual(result['status'],'operation_unverified');self.assertEqual(len(sent),enqueue_expected)
def test_wrong_register_identity(self):self.refusal(lambda r:r['register'].update(memo_id='wrong'))
def test_wrong_register_version(self):self.refusal(lambda r:r['register'].update(version=2))
def test_boolean_register_version(self):self.refusal(lambda r:r['register'].update(version=True))
def test_wrong_publish_identity(self):self.refusal(lambda r:r['publish'].update(memo_id='wrong'))
def test_wrong_publish_version(self):self.refusal(lambda r:r['publish'].update(version=2))
def test_wrong_review_memo_id(self):self.refusal(lambda r:r['review'].update(review_memo_id='review-22222222-2222-2222-2222-222222222222'))
def test_wrong_envelope_key(self):self.refusal(lambda r:r['review']['envelope'].update(idempotency_key='wrong'))
def test_wrong_packet(self):self.refusal(lambda r:r['review']['envelope']['packet'][0].update(content='changed'))
def test_wrong_routing(self):self.refusal(lambda r:r['review']['envelope'].update(review_group='wrong'))
def test_wrong_intent(self):self.refusal(lambda r:r['review']['envelope']['approval_intent'].update(purpose='changed'))
def test_wrong_memo_binding(self):self.refusal(lambda r:r['review']['envelope']['memo']['binding']['target'].update(id='wrong'))
def test_real_queue_conflict_not_confirmed(self):
def conflict(q,e,r):
changed=copy.deepcopy(e);changed['memo']['brief']='different';return q.submit(changed,dispatch=False)
self.refusal(queue_mutate=conflict,enqueue_expected=1)
def test_real_prior_blocked_not_confirmed(self):
def blocked(q,e,r):
changed=copy.deepcopy(e);changed['memo']['brief']='different';q.submit(changed,dispatch=False);return q.submit(e,dispatch=False)
self.refusal(queue_mutate=blocked,enqueue_expected=1)
def test_wrong_queue_key(self):self.refusal(queue_mutate=lambda q,e,r:types.SimpleNamespace(status='pending',detail='queued',idempotency_key='wrong'),enqueue_expected=1)
def test_unknown_queue_state(self):self.refusal(queue_mutate=lambda q,e,r:types.SimpleNamespace(status='unknown',detail='queued',idempotency_key=RID),enqueue_expected=1)
def test_unproved_retry_pending(self):self.refusal(queue_mutate=lambda q,e,r:types.SimpleNamespace(status='pending',detail='waiting',idempotency_key=RID),enqueue_expected=1)
def test_wrong_outcomes_identity(self):self.refusal(lambda r:r['outcomes']['review'].update(memo_id='wrong'),enqueue_expected=1)
def test_stale_outcomes(self):self.refusal(lambda r:r['outcomes']['review'].update(stale=True),enqueue_expected=1)
def test_missing_outcomes(self):self.refusal(lambda r:r['outcomes'].update(review=None),enqueue_expected=1)
def test_wrong_review_path(self):self.refusal(lambda r:r['outcomes']['review'].update(intake_state='ready',path='/review?memo_id=wrong'),enqueue_expected=1)
def test_real_delivered_replay_receipt(self):
with tempfile.TemporaryDirectory() as td:
q=make_queue(Path(td)/'queue.sqlite');q.submit(envelope,dispatch=False)
with q._connect() as db:db.execute("UPDATE pose_ledger SET state='delivered',receipt_json=?",(json.dumps({'memo_id':RID,'approval_id':EVENT,'approval_binding_digest':'sha256:'+'a'*64}),))
self.assertEqual(queued_checked(q.submit(envelope,dispatch=False),RID),'replay')
def test_replay_without_retained_receipt_refused(self):
with self.assertRaises(Refused):queued_checked(types.SimpleNamespace(status='replay',detail='replay',idempotency_key=RID,receipt=None),RID)
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,35 @@
"""Offline fixtures only. No SSH, tokens, or service requests."""
import hashlib,json,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
import build_packet as b
import submit_reviewed_source as h
from informed_decision.lifecycle_commands import decode_memo,decode_documents
class Preparation(unittest.TestCase):
def setUp(self):
self.revisions={r:'a'*40 for r,_,_ in b.SOURCES}
def fake_show(self,command,cwd,**kwargs):return (Path(cwd)/command[-1].split(':',1)[1]).read_bytes()
def test_model_and_document_coverage(self):
with patch.object(b.subprocess,'check_output',self.fake_show):c,s=b.build(self.revisions)
m=decode_memo(c['register']['memo']);docs=decode_documents(c['register']['documents'],m)
self.assertEqual(len(docs),6);self.assertEqual({d[0] for d in docs},{i.hash for i in m.packet})
self.assertLess(len(json.dumps(c['register']).encode()),256*1024)
self.assertFalse(s['native_authorized']);self.assertEqual(c['publish']['audience']['groups'],['net-kingdom-admins'])
def test_bad_revision_refuses_before_git(self):
with patch.object(b.subprocess,'check_output') as git:
with self.assertRaises(ValueError):b.build(dict(self.revisions,**{'key-cape':'HEAD'}))
git.assert_not_called()
def test_altered_committed_bytes_refuse(self):
with patch.object(b.subprocess,'check_output',return_value=b'altered'):
with self.assertRaises(ValueError):b.build(self.revisions)
def test_missing_review_gate_refuses(self):
with tempfile.TemporaryDirectory() as td:
for name in ['lifecycle-commands.json','source-inventory.json','submit_reviewed_source.py','build_packet.py','preflight.py','correlation.py']:(Path(td)/name).write_text('{}')
p=Path(td)/'ready.json';p.write_text(json.dumps({'status':'ready_for_human_source_review','memo_id':b.ID,'version':1,'native_authorized':False}))
with self.assertRaises(ValueError):h.prepare(Path(td),p,h.sha(p))
def test_wrong_readiness_digest_refuses(self):
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'ready.json';p.write_text('{}')
with self.assertRaises(ValueError):h.prepare(Path(td),p,'0'*64)
def test_remote_program_syntax(self):compile('command={}\nident='+repr(b.ID)+'\n'+h.REMOTE,'remote','exec')
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,19 @@
# KEY39 source-design posting successor V3 — unsubmitted
This immutable source stage repairs F01–F03 from the retained independent technical review. It is preparation only: no credentials, SSH, authoring request, queue submission, runtime change, or native KEY39 action has run.
The memo ID remains `infd-20261011-key39-source-design-r1`, source version 1. The original source stage was never submitted. All registration memo fields and six packet documents are identical to the original stage, including the full source-only limits and committed owner memo/ack bytes at KeyCape 0f47e0c, NetKingdom 7ceac43 and Platform 6bb406e. Only the review approval-intent purpose is changed to the exact reviewed 343-character concise string. Existing frozen commands, helper, counterexamples and uncertainty evidence are untouched.
`prepare()` rebuilds exact committed/current source bytes and validates the complete expected lifecycle review projection through current provider `records`, `lifecycle_review.supports_review`, intake `validate_submission` and State Hub `validate_envelope` before returning an authoring program. The expected projection follows the actual provider principal replacement and record defaults. These local source contracts do not prove deployed service source pins or authenticated runtime admission.
The remote program checks registration and publication memo ID/version and event IDs before continuing. It compares the full returned handoff with the exact expected memo projection, document contents, approval intent, routing and review ID/idempotency key. Nothing is reconstructed or altered for enqueue: the equal retained envelope is submitted as-is. Dispatcher confirmation requires the exact returned key and either `pending/queued` or `replay/replay` with a matching bounded receipt. Blocked, unknown, retry-wait and malformed results remain unverified, preserving the pre-transport sentinel; they do not trigger replay.
Outcomes must contain the exact retained review ID and `stale=false`, with a known intake state and any review path matching that ID. The provider outcomes API has no returned source-version field: correlation relies on the exact `/outcomes?version=1` query, the retained version-specific handoff and the provider's stale check. No invented response field or inferred human acceptance is used. A queued receipt does not prove delivery. A human review link is usable only after separate verified `ready` intake/path evidence; the helper does not declare that readiness.
The posting gate still requires separate independently approved packet/helper receipts bound to all six exact artifact hashes. Hash syntax is not reviewer authentication: root must verify real review receipts and source currency before supplying readiness. These changes confer no new actor or credential authority. The previously established STATE96 admitted dispatcher path is reused only when independently reviewed and authorized; existing per-operation keys and exclusive uncertainty receipt are preserved. No automatic rerun after uncertainty.
38 source checks pass. One test exercises actual provider register/publication/review preparation and outcomes in a disposable private SQLite store, then the actual State Hub forwarding ledger. Other tests retain blocked/conflict/replay semantics and exercise the actual remote program with only HTTP/dispatcher transport replaced by fixtures. No native/MFA/SSH credentials or protected content is accessed.
V3 also repairs V2-F01. The resolved invoked helper directory must equal the requested artifact directory. The actual imported builder, preflight and correlation module `__file__` origins must resolve to their exact files in that directory and their bytes must match the approved artifact hashes. Imported function bindings must still be the checked module functions. Before remote-program construction the origins are checked again, and the exact bytes read for correlation embedding are compared with the reviewed hash. Identical module bytes imported from a different origin are refused. Seven added checks execute actual local CLI subprocesses, including both reported cross-directory altered-adjacent cases, same-directory altered bytes, three external imported module origins and a fresh exact invocation.
Trust boundary: Python imports have already executed before this application gate runs. The gate cannot prevent hostile import-time code, authenticate itself, establish exclusive custody or defend a concurrent same-UID attacker. Root must externally verify every frozen source byte and dependency pin in an exclusive owner-controlled directory before invoking the helper, with controlled interpreter/import environment. Continuous exclusive custody is also required between validation and embedding/execution. Readiness hash strings do not supply that custody or reviewer authority. This source-only repair makes the promised invoked-source checks truthful inside that trusted preparation boundary.

View file

@ -0,0 +1,42 @@
"""Offline exact source-design packet builder. Does not contact any service."""
import argparse,base64,hashlib,json,re,subprocess
from pathlib import Path
ID="infd-20261011-key39-source-design-r1"
SOURCES=[
("key-cape","docs/proposals/2026-10-11-key39-founder-source-design-decision.md","1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688"),
("key-cape","docs/proposals/2026-10-11-key39-founder-source-design-decision.json","d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091"),
("key-cape","docs/reviews/2026-10-11-key39-v9-v4-keycape-source-ack.json","4108d3afde1756c3889e6092878afd99a1193e59971ffe04d3845bbe21a42c7e"),
("railiance-platform","docs/reviews/2026-10-11-key39-ready-pair-v9-v4-platform-review.json","cb2729781cfce7637d7a4ba29412edde64d337c5efe3148600bd39fb12166894"),
("net-kingdom","docs/reviews/2026-10-11-key39-producer-v4-net-review.json","9566955b77db4a0b041887ef4a6aff6c7a02ef30cc0727a4deb6c29bbdc79518")]
def digest(raw):return hashlib.sha256(raw).hexdigest()
def build(revisions):
documents=[];packet=[];sources=[]
for index,(repo,relative,sha) in enumerate(SOURCES):
revision=revisions[repo]
if not re.fullmatch("[0-9a-f]{40}",revision):raise ValueError("exact_source_revision_required")
root=Path("/home/worsch")/repo
raw=subprocess.check_output(["git","show",revision+":"+relative],cwd=root,stderr=subprocess.DEVNULL)
if digest(raw)!=sha or (root/relative).read_bytes()!=raw:raise ValueError("source_currency_refused")
name=Path(relative).name;item="source-"+str(index+1)
packet.append({"item_id":item,"label":name,"hash":"sha256:"+sha})
documents.append({"digest":"sha256:"+sha,"media_type":"text/markdown" if relative.endswith(".md") else "application/json","content_base64":base64.b64encode(raw).decode()})
sources.append({"repo":repo,"path":relative,"source_revision":revision,"sha256":sha})
inventory={"schema":"key39-source-publication-sources/v1","memo_id":ID,"version":1,"native_authorized":False,"sources":sources}
inventory_raw=(json.dumps(inventory,indent=2)+"\n").encode();inventory_sha=digest(inventory_raw)
packet.append({"item_id":"source-inventory","label":"source-inventory.json","hash":"sha256:"+inventory_sha})
documents.append({"digest":"sha256:"+inventory_sha,"media_type":"application/json","content_base64":base64.b64encode(inventory_raw).decode()})
brief="Source-design direction only for the four explicit choices in the exact attached founder memo: existing human-client purpose reuse, return or prepare coding-agent custody admission, proposed direct SSH source profile, and conditional exclusive-owner tmpfs-file design. All native login, credential access, client registration, SSH/port-forward, restart, mutation and task closure remain gated. No partial/absent choice authorizes native execution. Owner reviews establish only source compatibility; provider MFA, real custody, route, plugin/leeway, adoption/maintenance exception and fresh authenticated native go remain pending."
memo={"id":ID,"version":1,"question":"Approve the recommended four source-design directions for KEY39's reviewed producer V4 / consumer V9, retaining every separate native admission and custody gate?","requested_act":"approve","binding_level":"organizational","brief":brief,"binding":{"principal":{"id":"pending-human-session","kind":"person","display_name":"Founder source-design direction"},"target":{"kind":"resource","id":"KEY-WP-0039-T02/founder-source-design-v1","label":"KEY39 paired input source-design directions","environment":"build"},"terms":brief+" Scope is exact owner memo sha256:1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688 and JSON sha256:d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091. Architecture-wide v0.9, standing/default privileges and agent autonomy are not approved."},"step_kind":"approve","packet":packet,"highlights":[{"id":"source-direction-only","item_id":"source-1","note":brief,"required_ack":True,"severity":"warning","locator":{"kind":"section","heading":"Choices to record"}}],"sealed":False,"approval_id":None,"approval_binding_digest":None}
command={"id":ID,"register":{"memo":memo,"documents":documents},"publish":{"version":1,"audience":{"subjects":[],"groups":["net-kingdom-admins"]}},"review":{"version":1,"options":{"submitter":"state-hub","memo_class":"decision-record","review_group":"net-kingdom-admins","approval_intent":{"action":"acknowledge","principal":"net-kingdom-admins","purpose":"Acknowledge four exact KEY39 producer V4 / consumer V9 source-design directions in the attached founder memo. Source compatibility only; no native execution, credentials, SSH admission, client registration, task closure, architecture-wide acceptance or agent-autonomy grant. All custody, runtime and fresh native approval gates remain pending.","target":{"id":"KEY-WP-0039-T02/founder-source-design-v1","type":"source-design","system":"key-cape"}}}}}
if len(json.dumps(command["register"]).encode())>256*1024:raise ValueError("payload_limit_refused")
return command,inventory
def main():
p=argparse.ArgumentParser();p.add_argument("--key-revision",required=True);p.add_argument("--net-revision",required=True);p.add_argument("--platform-revision",required=True);p.add_argument("--output",type=Path,required=True);a=p.parse_args()
c,s=build({"key-cape":a.key_revision,"net-kingdom":a.net_revision,"railiance-platform":a.platform_revision})
a.output.mkdir(parents=True,exist_ok=True)
for name,value in [("lifecycle-commands.json",[c]),("source-inventory.json",s)]:
path=a.output/name
if path.exists():raise ValueError("existing_output_refused")
path.write_text(json.dumps(value,indent=2)+"\n")
print(json.dumps({"status":"source_prepared_only","memo_id":ID,"registration_bytes":len(json.dumps(c["register"]).encode())}))
if __name__=="__main__":main()

View file

@ -0,0 +1,47 @@
"""Pure correlation for the exact reviewed source handoff; no authority or I/O."""
import base64, copy, json, re
class Refused(ValueError): pass
def uuid(value):
if not isinstance(value,str) or not re.fullmatch('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}',value):raise Refused('event_identity_refused')
return value
def expected_envelope(command,rid):
if not isinstance(rid,str) or not rid.startswith('review-'):raise Refused('review_identity_refused')
uuid(rid[7:])
memo=copy.deepcopy(command['register']['memo']);memo['id']=rid;memo['version']=1
memo['binding']['principal']={'id':'pending-human-session','kind':'person','display_name':'To be assigned'}
# Provider records parser emits defaults for all MEMO_KEYS; caller supplies projected_memo.
if '_projected_memo' in command:
memo=copy.deepcopy(command['_projected_memo']);memo['id']=rid
docs={d['digest']:d for d in command['register']['documents']}
packet=[{'item_id':i['item_id'],'media_type':docs[i['hash']]['media_type'],'content':base64.b64decode(docs[i['hash']]['content_base64'],validate=True).decode('utf-8')} for i in memo['packet']]
options=command['review']['options']
return {'kind':'informed-decision.memo-intake','version':1,'idempotency_key':rid,'memo_class':options['memo_class'],'review_group':options['review_group'],'approval_intent':options['approval_intent'],'memo':memo,'packet':packet}
def authored(receipt,ident,version):
if not isinstance(receipt,dict) or receipt.get('memo_id')!=ident or type(receipt.get('version')) is not int or receipt['version']!=version:raise Refused('authored_identity_refused')
uuid(receipt.get('event_id'))
def handoff_checked(receipt,command):
if not isinstance(receipt,dict):raise Refused('handoff_refused')
uuid(receipt.get('event_id'))
rid=receipt.get('review_memo_id');expected=expected_envelope(command,rid)
if receipt.get('envelope')!=expected:raise Refused('exact_handoff_refused')
return rid,expected
def queued_checked(queued,rid):
if queued.idempotency_key!=rid:raise Refused('queue_identity_refused')
# Fresh or retained exact pending queue, or already delivered exact replay only.
# The real forwarder compares the entire submission digest before these results.
if (queued.status,queued.detail) not in {('pending','queued'),('replay','replay')}:raise Refused('queue_confirmation_refused')
if queued.status=='replay':
receipt=queued.receipt
if not isinstance(receipt,dict) or receipt.get('memo_id')!=rid:raise Refused('queue_replay_identity_refused')
uuid(receipt.get('approval_id'))
if not isinstance(receipt.get('approval_binding_digest'),str) or not re.fullmatch('sha256:[a-f0-9]{64}',receipt['approval_binding_digest']):raise Refused('queue_replay_receipt_refused')
return queued.status
def outcomes_checked(outcome,rid):
if not isinstance(outcome,dict) or set(outcome)!={'review','dispositions'}:raise Refused('outcomes_refused')
review=outcome['review']
if not isinstance(review,dict) or review.get('memo_id')!=rid or review.get('stale') is not False:raise Refused('outcomes_identity_refused')
if review.get('intake_state') not in {'not_submitted','creating','created','ready'}:raise Refused('intake_state_refused')
if 'path' in review and (review['intake_state']!='ready' or review['path']!='/review?memo_id='+rid):raise Refused('review_path_refused')
if not isinstance(outcome['dispositions'],list):raise Refused('dispositions_refused')
# No dispositions are claimed or interpreted as native authority.
return len(outcome['dispositions'])

View file

@ -0,0 +1,53 @@
{
"schema": "key39-source-posting-successor-manifest/v3",
"stage": "/tmp/key39-source-decision-publication-v3",
"prior_manifest_sha256": "e1c57f44851a7024450c9a9a7863395201cddd4b9e1a841ff461406de01cb2c8",
"submitted": false,
"native_authorized": false,
"entries": [
{
"path": "README.md",
"sha256": "2d9457f590ae3b1502dd752984255d09e0e9366c37a9b800df2b470def0c2fb3"
},
{
"path": "build_packet.py",
"sha256": "ad4886e5946eafd88a7d3578e2c363d6174223391b792dbd052f23defb9a9267"
},
{
"path": "correlation.py",
"sha256": "7d03880678f60b6aabf5c5d27cc56fb66cfa27030f329f04dcee7c3f878649e6"
},
{
"path": "lifecycle-commands.json",
"sha256": "36e20813596f3ddbb86e01fd0b838867ece2f4916c5880305cf12cd61b567f89"
},
{
"path": "preflight.py",
"sha256": "0e19d2ff049efbe1556e11a4f27ddbe9fb2e892155b7a36dbdfa37832ac4c572"
},
{
"path": "repair-receipt.json",
"sha256": "55a6be976934df270469e9e821c949a0cca7f6ecefc48639bcbbaf6a147368ee"
},
{
"path": "source-inventory.json",
"sha256": "aea196db9e513900d5e7165455d6e9c3dc68749a606dc219ec340ac595642cc0"
},
{
"path": "submit_reviewed_source.py",
"sha256": "8e8846f79989db25900717399b3b5f8fed2510521f5a5dabd35483d0f2bb9f3f"
},
{
"path": "test_invoked_sources.py",
"sha256": "86f3a0af7b299e4f620f17afdb9eef7cac7845eba98dcd5757d06528795a8ef1"
},
{
"path": "test_posting_contract.py",
"sha256": "58619b6248f047246dcf44984539edb3cfb697d23c0c57355aab35b83faffd70"
},
{
"path": "test_source_preparation.py",
"sha256": "75713161b2625509d1f7d0b8f814ed74203797e6c0d28f3283203ada673e578e"
}
]
}

View file

@ -0,0 +1,24 @@
"""Offline validation through actual provider projection/intake and State Hub contract."""
import json,sys
from dataclasses import replace
sys.path[:0]=['/home/worsch/informed-decision','/home/worsch/state-hub']
from informed_decision.records import memo_from,dumps
from informed_decision.memo import Principal
from informed_decision.intake import MEMO_KEYS,SubmitterGrant,validate_submission
from informed_decision.lifecycle_review import supports_review
from api.services.informed_decision_contract import validate_envelope
from correlation import expected_envelope
RID='review-11111111-1111-1111-1111-111111111111'
def validate(command):
memo=memo_from(command['register']['memo'])
if not supports_review(memo):raise ValueError('provider_profile_refused')
draft=replace(memo,id=RID,version=1,binding=replace(memo.binding,principal=Principal('pending-human-session','person','To be assigned')))
projection={k:v for k,v in json.loads(dumps(draft)).items() if k in MEMO_KEYS}
if dumps(memo_from(projection))!=dumps(draft):raise ValueError('lossy_provider_projection_refused')
projected=dict(command,_projected_memo=projection)
envelope=expected_envelope(projected,RID)
o=command['review']['options']
validate_submission(envelope,submitter_id=o['submitter'],grant=SubmitterGrant(o['submitter'],frozenset({o['memo_class']}),frozenset({o['review_group']})))
validate_envelope(envelope)
if len(dumps(envelope).encode())>256*1024:raise ValueError('provider_envelope_unbounded')
return projected,envelope

View file

@ -0,0 +1,29 @@
{
"schema": "key39-source-posting-repair-receipt/v3",
"prior_review_sha256": "504876f314cebc30f960df431f47ad1fef3aa856d007031b2bcd1cc360093be4",
"prior_manifest_sha256": "e1c57f44851a7024450c9a9a7863395201cddd4b9e1a841ff461406de01cb2c8",
"prior_manifest_unchanged": true,
"prior_stage_retained": true,
"checks": {
"passed": 38,
"command": "python3 -m unittest discover -s /tmp/key39-source-decision-publication-v3 -p 'test_*.py'",
"actual_cli_checks": 7,
"fresh_exact_invocation_passed": true,
"both_reported_crossdirectory_clones_refused": true,
"same_directory_altered_module_refused": true,
"identical_bytes_external_import_origin_refused": [
"build_packet",
"preflight",
"correlation"
],
"initial_test_fixture_issue": "External fixture modules lacked .py suffix, causing loader failure before helper; corrected fixture and reran all 38 checks successfully."
},
"reviewed_commands_unchanged": true,
"source_inventory_unchanged": true,
"minimal_helper_change": "resolved invoked directory and actual imported module origins/hashes/function bindings; checked exact embedded correlation bytes",
"trust_boundary": "Imports execute before gate. Root externally verifies all bytes in exclusive owner-controlled directory before invocation; no self-authentication or credential-isolation claim.",
"submitted": false,
"credential_access": false,
"ssh_or_native_actions": false,
"native_authorized": false
}

View file

@ -0,0 +1,38 @@
{
"schema": "key39-source-publication-sources/v1",
"memo_id": "infd-20261011-key39-source-design-r1",
"version": 1,
"native_authorized": false,
"sources": [
{
"repo": "key-cape",
"path": "docs/proposals/2026-10-11-key39-founder-source-design-decision.md",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "1816e48b44eb874e4c97db82ee56ed27c23083ddcfc322d9de9876132e802688"
},
{
"repo": "key-cape",
"path": "docs/proposals/2026-10-11-key39-founder-source-design-decision.json",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "d2f6e2fc733d8092a27a1dafb2f77601cbff398c5606b12bb053b4cd7bcd4091"
},
{
"repo": "key-cape",
"path": "docs/reviews/2026-10-11-key39-v9-v4-keycape-source-ack.json",
"source_revision": "0f47e0c666e27bcc7811976708dddcb822ef0647",
"sha256": "4108d3afde1756c3889e6092878afd99a1193e59971ffe04d3845bbe21a42c7e"
},
{
"repo": "railiance-platform",
"path": "docs/reviews/2026-10-11-key39-ready-pair-v9-v4-platform-review.json",
"source_revision": "6bb406eb15920711d047ef34aaa4ffa56f088803",
"sha256": "cb2729781cfce7637d7a4ba29412edde64d337c5efe3148600bd39fb12166894"
},
{
"repo": "net-kingdom",
"path": "docs/reviews/2026-10-11-key39-producer-v4-net-review.json",
"source_revision": "7ceac4372d38354ae345eb40bc31c1cdbd39e4e5",
"sha256": "9566955b77db4a0b041887ef4a6aff6c7a02ef30cc0727a4deb6c29bbdc79518"
}
]
}

View file

@ -0,0 +1,104 @@
"""Exact KEY39 source-design publication. No native KEY39 actuation."""
import argparse,hashlib,json,re,subprocess,sys
from pathlib import Path
from build_packet import build,ID
from preflight import validate
import build_packet,preflight,correlation
if sys.flags.optimize:raise SystemExit('optimized_interpreter_refused')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def invoked_sources(directory,artifacts):
actual=Path(__file__).resolve(strict=True).parent
if directory.resolve(strict=True)!=actual:raise ValueError('invoked_directory_refused')
for name,module in [('build_packet.py',build_packet),('preflight.py',preflight),('correlation.py',correlation)]:
origin=Path(module.__file__).resolve(strict=True)
if origin!=actual/name or sha(origin)!=artifacts[name]:raise ValueError('invoked_module_source_refused')
if sha(Path(__file__).resolve(strict=True))!=artifacts['submit_reviewed_source.py']:raise ValueError('invoked_source_refused')
if build is not build_packet.build or validate is not preflight.validate:raise ValueError('invoked_function_origin_refused')
return actual
def prepare(directory,ready_path,ready_sha):
if directory.resolve(strict=True)!=Path(__file__).resolve(strict=True).parent:raise ValueError('invoked_directory_refused')
if sha(ready_path)!=ready_sha:raise ValueError('reviewed_readiness_bytes_refused')
r=json.loads(ready_path.read_bytes())
if r.get('status')!='ready_for_human_source_review' or r.get('memo_id')!=ID or r.get('version')!=1 or r.get('native_authorized') is not False:raise ValueError('posting_gate_refused')
artifacts={n:sha(directory/n) for n in ['lifecycle-commands.json','source-inventory.json','submit_reviewed_source.py','build_packet.py','preflight.py','correlation.py']}
invoked_sources(directory,artifacts)
if r.get('artifacts')!=artifacts or set(r.get('independent_reviews',{}))!={'packet','helper'}:raise ValueError('exact_independent_posting_gates_refused')
for value in r['independent_reviews'].values():
if not isinstance(value,dict) or value.get('decision')!='approved' or not re.fullmatch('[0-9a-f]{64}',value.get('receipt_sha256','')):raise ValueError('independent_review_refused')
inventory=json.loads((directory/'source-inventory.json').read_bytes())
revisions={s['repo']:s['source_revision'] for s in inventory['sources']}
c,expected=build(revisions)
commands=json.loads((directory/'lifecycle-commands.json').read_bytes())
if inventory!=expected or commands!=[c]:raise ValueError('exact_source_command_refused')
return validate(c)[0],artifacts
REMOTE='''import json,re,signal,urllib.request,urllib.error
from api.services.memo_dispatch import Dispatcher,ORIGIN,NoRedirect,token_file
def deadline(*args):raise Refused('bounded_operation_unverified')
signal.signal(signal.SIGALRM,deadline)
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
def call(method,path,body=None,key=None):
if not (path=='/v1/decisions' or path.startswith('/v1/decisions/'+ident+'/')):raise Refused('route_refused')
signal.setitimer(signal.ITIMER_REAL,25)
try:
raw=json.dumps(body,allow_nan=False).encode() if body is not None else None
if raw is not None and len(raw)>256*1024:raise Refused('input_too_large')
headers={'Authorization':'Bearer '+token_file('/var/run/secrets/state-hub/informed-decision/lifecycle-token'),'Content-Type':'application/json'}
if key:headers['Idempotency-Key']=key
req=urllib.request.Request(ORIGIN+path,data=raw,headers=headers,method=method)
try:response=opener.open(req,timeout=20)
except urllib.error.HTTPError as error:response=error
with response:
payload=response.read(1024*1024+1)
if len(payload)>1024*1024 or response.code not in (200,201):raise Refused('operation_unverified')
value=json.loads(payload)
if not isinstance(value,dict):raise Refused('response_unverified')
return value
finally:signal.setitimer(signal.ITIMER_REAL,0)
action='prepare'
try:
receipts={}
action='register';receipts[action]=call('POST','/v1/decisions',command[action],'security-consolidation.'+ident+'.register.v1')
authored(receipts[action],ident,1)
for action,suffix in [('publish','publications'),('review','review-requests')]:
receipts[action]=call('POST','/v1/decisions/'+ident+'/'+suffix,command[action],'security-consolidation.'+ident+'.'+action+'.v1')
if action=='publish':authored(receipts[action],ident,1)
handoff=receipts['review'];review_id,envelope=handoff_checked(handoff,command)
action='enqueue';signal.setitimer(signal.ITIMER_REAL,25)
queued=Dispatcher('/data/private').enqueue(envelope);signal.setitimer(signal.ITIMER_REAL,0)
state=queued_checked(queued,review_id)
action='outcomes';outcome=call('GET','/v1/decisions/'+ident+'/outcomes?version=1')
count=outcomes_checked(outcome,review_id)
result={'memo_id':ident,'version':1,'review_memo_id':review_id,'queue_status':state,'human_dispositions':count,'native_key39_action_performed':False}
for key,op in [('register_event_id','register'),('publication_event_id','publish'),('review_event_id','review')]:result[key]=uuid(receipts[op]['event_id'])
print(json.dumps(result),flush=True)
except BaseException:
signal.setitimer(signal.ITIMER_REAL,0)
print(json.dumps({'memo_id':ident,'action':action,'status':'operation_unverified'}),flush=True)
raise SystemExit(1) from None
'''
def main():
p=argparse.ArgumentParser();p.add_argument('--directory',required=True,type=Path);p.add_argument('--readiness',required=True,type=Path);p.add_argument('--readiness-sha256',required=True);p.add_argument('--receipt',required=True,type=Path);p.add_argument('--check-only',action='store_true');a=p.parse_args()
if not re.fullmatch('[0-9a-f]{64}',a.readiness_sha256):raise SystemExit('exact_readiness_digest_required')
command,artifacts=prepare(a.directory,a.readiness,a.readiness_sha256)
if a.receipt.exists():raise SystemExit('existing_receipt_refused_no_blind_replay')
actual=invoked_sources(a.directory,artifacts)
correlation_raw=(actual/'correlation.py').read_bytes()
if hashlib.sha256(correlation_raw).hexdigest()!=artifacts['correlation.py']:raise ValueError('embedded_correlation_source_refused')
program=(correlation_raw.decode('utf-8')+'\ncommand='+repr(command)+'\nident='+repr(ID)+'\n'+REMOTE)
proof={'memo_id':ID,'artifacts':artifacts,'authoring_program_sha256':hashlib.sha256(program.encode()).hexdigest(),'readiness_sha256':a.readiness_sha256}
if a.check_only:
print(json.dumps(dict(proof,status='source_only_check_passed')));return
# Before transport, retain uncertainty sentinel. Never overwrite an original outcome.
with a.receipt.open('x') as stream:stream.write(json.dumps(dict(proof,status='submission_unverified',do_not_blindly_replay=True))+'\n')
try:
run=subprocess.run(['ssh','railiance01','kubectl -n state-hub exec -i deployment/state-hub-memo-dispatch -c dispatcher -- python -'],input=program,text=True,capture_output=True,timeout=150)
result=json.loads(run.stdout)
allowed={'memo_id','version','review_memo_id','queue_status','human_dispositions','native_key39_action_performed','register_event_id','publication_event_id','review_event_id'}
if run.returncode or not isinstance(result,dict) or set(result)!=allowed or result['memo_id']!=ID or type(result['version']) is not int or result['version']!=1 or result['queue_status'] not in ('pending','replay') or result['native_key39_action_performed'] is not False:raise ValueError('submission_unverified')
except Exception:
print(json.dumps({'memo_id':ID,'status':'submission_unverified','receipt_retained':True}));raise SystemExit(1) from None
final=a.receipt.with_name(a.receipt.name+'.confirmed.json')
with final.open('x') as stream:stream.write(json.dumps(dict(proof,**result,status='authored_and_queued'),indent=2)+'\n')
print(json.dumps(dict(result,status='authored_and_queued')))
if __name__=='__main__':main()

View file

@ -0,0 +1,45 @@
"""Real local CLI subprocesses with synthetic readiness; never SSH/token I/O."""
import hashlib,json,os,shutil,subprocess,sys,tempfile,unittest
from pathlib import Path
SOURCE=Path(__file__).resolve().parent
NAMES=['lifecycle-commands.json','source-inventory.json','submit_reviewed_source.py','build_packet.py','preflight.py','correlation.py']
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def ready(td):
p=Path(td)/'synthetic-readiness.json';p.write_text(json.dumps({'status':'ready_for_human_source_review','memo_id':'infd-20261011-key39-source-design-r1','version':1,'native_authorized':False,'artifacts':{n:sha(SOURCE/n) for n in NAMES},'independent_reviews':{k:{'decision':'approved','receipt_sha256':'a'*64} for k in ['packet','helper']}}));return p
def run(helper,directory,r,receipt,prefix=None):
args=[str(helper),'--directory',str(directory),'--readiness',str(r),'--readiness-sha256',sha(r),'--receipt',str(receipt),'--check-only']
return subprocess.run([sys.executable]+(prefix or [])+args,text=True,capture_output=True,timeout=10,env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
class Invocation(unittest.TestCase):
def test_fresh_exact_invocation_passes(self):
with tempfile.TemporaryDirectory() as td:
r=ready(td);receipt=Path(td)/'receipt';result=run(SOURCE/'submit_reviewed_source.py',SOURCE,r,receipt)
self.assertEqual(result.returncode,0,result.stderr);v=json.loads(result.stdout)
self.assertEqual(v['status'],'source_only_check_passed');self.assertEqual(v['artifacts'],{n:sha(SOURCE/n) for n in NAMES});self.assertFalse(receipt.exists())
def tampered_clone(self,name):
with tempfile.TemporaryDirectory() as td:
clone=Path(td)/'clone';shutil.copytree(SOURCE,clone,ignore=shutil.ignore_patterns('__pycache__'))
p=clone/name;p.chmod(0o600)
with p.open('a') as f:f.write("\n# Synthetic unreviewed adjacent source.\n")
r=ready(td);receipt=Path(td)/'receipt'
result=run(clone/'submit_reviewed_source.py',SOURCE,r,receipt)
self.assertNotEqual(result.returncode,0);self.assertIn('invoked_directory_refused',result.stderr);self.assertFalse(receipt.exists());self.assertNotIn('source_only_check_passed',result.stdout)
def test_cross_directory_altered_correlation_refused(self):self.tampered_clone('correlation.py')
def test_cross_directory_altered_preflight_refused(self):self.tampered_clone('preflight.py')
def test_same_directory_altered_adjacent_source_hash_refused(self):
with tempfile.TemporaryDirectory() as td:
clone=Path(td)/'clone';shutil.copytree(SOURCE,clone,ignore=shutil.ignore_patterns('__pycache__'))
p=clone/'correlation.py';p.chmod(0o600)
with p.open('a') as f:f.write('\n# Synthetic unreviewed source.\n')
r=ready(td);receipt=Path(td)/'receipt';result=run(clone/'submit_reviewed_source.py',clone,r,receipt)
self.assertNotEqual(result.returncode,0);self.assertIn('exact_independent_posting_gates_refused',result.stderr);self.assertFalse(receipt.exists())
def wrong_origin(self,name):
with tempfile.TemporaryDirectory() as td:
external=Path(td)/(name+'.py');shutil.copyfile(SOURCE/(name+'.py'),external)
# Identical bytes from an unreviewed origin injected before real helper CLI parsing.
script="import importlib.util,runpy,sys;sys.path.insert(0,"+repr(str(SOURCE))+");s=importlib.util.spec_from_file_location("+repr(name)+","+repr(str(external))+");m=importlib.util.module_from_spec(s);sys.modules["+repr(name)+"]=m;s.loader.exec_module(m);sys.argv=sys.argv[1:];runpy.run_path(sys.argv[0],run_name='__main__')"
r=ready(td);receipt=Path(td)/'receipt';result=run(SOURCE/'submit_reviewed_source.py',SOURCE,r,receipt,['-c',script])
self.assertNotEqual(result.returncode,0);self.assertIn('invoked_module_source_refused',result.stderr);self.assertFalse(receipt.exists())
def test_preflight_identical_bytes_external_import_origin_refused(self):self.wrong_origin('preflight')
def test_correlation_identical_bytes_external_import_origin_refused(self):self.wrong_origin('correlation')
def test_builder_identical_bytes_external_import_origin_refused(self):self.wrong_origin('build_packet')
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,98 @@
"""Disposable real provider/forwarder integration; no network or credentials."""
import copy,io,json,sys,tempfile,types,unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
sys.path[:0]=[str(Path(__file__).parent),'/home/worsch/informed-decision','/home/worsch/state-hub']
import submit_reviewed_source as helper
from preflight import validate
from correlation import *
from informed_decision.lifecycle import Attribution,LifecycleRepository
from informed_decision.disposition import Actor,ActorKind
from informed_decision.records import memo_from
from informed_decision.lifecycle_review import prepare,outcomes
from informed_decision.store import Store
from api.services.memo_forwarding import MemoForwarder
rawcommand=json.loads(Path(__file__).with_name('lifecycle-commands.json').read_text())[0]
command,envelope=validate(rawcommand)
RID=envelope['memo']['id'];EVENT='33333333-3333-3333-3333-333333333333'
def make_queue(path):
return MemoForwarder(path,transport=lambda *a: (_ for _ in ()).throw(AssertionError('network forbidden')),intake_base_url='http://fixture.invalid',hub_base_url='http://fixture.invalid')
def execute(mutate=None,queue_mutate=None):
output=io.StringIO();sent=[]
responses={'register':{'event_id':EVENT,'memo_id':command['id'],'version':1},'publish':{'event_id':EVENT,'memo_id':command['id'],'version':1},'review':{'event_id':EVENT,'review_memo_id':RID,'envelope':copy.deepcopy(envelope)},'outcomes':{'review':{'memo_id':RID,'stale':False,'intake_state':'not_submitted'},'dispositions':[]}}
if mutate:mutate(responses)
def open_request(req,timeout):
action='outcomes' if 'outcomes' in req.full_url else 'review' if 'review-requests' in req.full_url else 'publish' if 'publications' in req.full_url else 'register'
class Response:
code=200
def __enter__(self):return self
def __exit__(self,*a):return False
def read(self,n):return json.dumps(responses[action]).encode()
return Response()
with tempfile.TemporaryDirectory() as td:
real=make_queue(Path(td)/'queue.sqlite')
class Dispatcher:
def __init__(self,path):pass
def enqueue(self,e):
sent.append(e);r=real.submit(e,dispatch=False)
return queue_mutate(real,e,r) if queue_mutate else r
fake=types.ModuleType('api.services.memo_dispatch');fake.Dispatcher=Dispatcher;fake.ORIGIN='http://fixture.invalid';fake.NoRedirect=__import__('urllib.request',fromlist=['HTTPRedirectHandler']).HTTPRedirectHandler;fake.token_file=lambda _: 'synthetic-fixture'
with patch.dict(sys.modules,{'api.services.memo_dispatch':fake}),patch('urllib.request.build_opener',return_value=types.SimpleNamespace(open=open_request)),patch('signal.signal'),patch('signal.setitimer'),redirect_stdout(output):
try:exec(Path(__file__).with_name('correlation.py').read_text()+'\n'+helper.REMOTE,{'command':copy.deepcopy(command),'ident':command['id']})
except SystemExit:pass
return json.loads(output.getvalue()),sent
class Contract(unittest.TestCase):
def test_real_provider_prepare_forwarder_and_outcomes(self):
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'private';p.mkdir(mode=0o700)
repo=LifecycleRepository(Store(p/'store.sqlite'));actor=Attribution('tenant:platform',Actor('synthetic-author',ActorKind.AGENT))
memo=memo_from(rawcommand['register']['memo'])
event=repo.register(actor,memo,key='fixture-register',documents=rawcommand['register']['documents']);authored({'event_id':event,'memo_id':memo.id,'version':memo.version},memo.id,1)
repo.publish(actor,memo.id,1,audience=rawcommand['publish']['audience'],key='fixture-publish')
handoff=prepare(repo,actor,memo.id,1,rawcommand['review']['options'],key='fixture-review',guard=lambda db:None)
rid,e=handoff_checked(handoff,command);self.assertEqual(e,expected_envelope(command,rid))
q=make_queue(p/'queue.sqlite');self.assertEqual(queued_checked(q.submit(e,dispatch=False),rid),'pending')
self.assertEqual(outcomes_checked(outcomes(repo,actor.tenant,memo.id,1),rid),0)
self.assertEqual(prepare(repo,actor,memo.id,1,rawcommand['review']['options'],key='fixture-review',guard=lambda db:None),handoff)
def test_concise_intent_and_full_scope_retained(self):
self.assertLessEqual(len(rawcommand['review']['options']['approval_intent']['purpose']),400)
self.assertEqual(rawcommand['register'],json.loads(Path('/tmp/key39-source-decision-publication/lifecycle-commands.json').read_text())[0]['register'])
def test_remote_exact_pending_success(self):
result,sent=execute();self.assertEqual(result['queue_status'],'pending');self.assertEqual(len(sent),1)
def refusal(self,mutate=None,queue_mutate=None,enqueue_expected=0):
result,sent=execute(mutate,queue_mutate);self.assertEqual(result['status'],'operation_unverified');self.assertEqual(len(sent),enqueue_expected)
def test_wrong_register_identity(self):self.refusal(lambda r:r['register'].update(memo_id='wrong'))
def test_wrong_register_version(self):self.refusal(lambda r:r['register'].update(version=2))
def test_boolean_register_version(self):self.refusal(lambda r:r['register'].update(version=True))
def test_wrong_publish_identity(self):self.refusal(lambda r:r['publish'].update(memo_id='wrong'))
def test_wrong_publish_version(self):self.refusal(lambda r:r['publish'].update(version=2))
def test_wrong_review_memo_id(self):self.refusal(lambda r:r['review'].update(review_memo_id='review-22222222-2222-2222-2222-222222222222'))
def test_wrong_envelope_key(self):self.refusal(lambda r:r['review']['envelope'].update(idempotency_key='wrong'))
def test_wrong_packet(self):self.refusal(lambda r:r['review']['envelope']['packet'][0].update(content='changed'))
def test_wrong_routing(self):self.refusal(lambda r:r['review']['envelope'].update(review_group='wrong'))
def test_wrong_intent(self):self.refusal(lambda r:r['review']['envelope']['approval_intent'].update(purpose='changed'))
def test_wrong_memo_binding(self):self.refusal(lambda r:r['review']['envelope']['memo']['binding']['target'].update(id='wrong'))
def test_real_queue_conflict_not_confirmed(self):
def conflict(q,e,r):
changed=copy.deepcopy(e);changed['memo']['brief']='different';return q.submit(changed,dispatch=False)
self.refusal(queue_mutate=conflict,enqueue_expected=1)
def test_real_prior_blocked_not_confirmed(self):
def blocked(q,e,r):
changed=copy.deepcopy(e);changed['memo']['brief']='different';q.submit(changed,dispatch=False);return q.submit(e,dispatch=False)
self.refusal(queue_mutate=blocked,enqueue_expected=1)
def test_wrong_queue_key(self):self.refusal(queue_mutate=lambda q,e,r:types.SimpleNamespace(status='pending',detail='queued',idempotency_key='wrong'),enqueue_expected=1)
def test_unknown_queue_state(self):self.refusal(queue_mutate=lambda q,e,r:types.SimpleNamespace(status='unknown',detail='queued',idempotency_key=RID),enqueue_expected=1)
def test_unproved_retry_pending(self):self.refusal(queue_mutate=lambda q,e,r:types.SimpleNamespace(status='pending',detail='waiting',idempotency_key=RID),enqueue_expected=1)
def test_wrong_outcomes_identity(self):self.refusal(lambda r:r['outcomes']['review'].update(memo_id='wrong'),enqueue_expected=1)
def test_stale_outcomes(self):self.refusal(lambda r:r['outcomes']['review'].update(stale=True),enqueue_expected=1)
def test_missing_outcomes(self):self.refusal(lambda r:r['outcomes'].update(review=None),enqueue_expected=1)
def test_wrong_review_path(self):self.refusal(lambda r:r['outcomes']['review'].update(intake_state='ready',path='/review?memo_id=wrong'),enqueue_expected=1)
def test_real_delivered_replay_receipt(self):
with tempfile.TemporaryDirectory() as td:
q=make_queue(Path(td)/'queue.sqlite');q.submit(envelope,dispatch=False)
with q._connect() as db:db.execute("UPDATE pose_ledger SET state='delivered',receipt_json=?",(json.dumps({'memo_id':RID,'approval_id':EVENT,'approval_binding_digest':'sha256:'+'a'*64}),))
self.assertEqual(queued_checked(q.submit(envelope,dispatch=False),RID),'replay')
def test_replay_without_retained_receipt_refused(self):
with self.assertRaises(Refused):queued_checked(types.SimpleNamespace(status='replay',detail='replay',idempotency_key=RID,receipt=None),RID)
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,35 @@
"""Offline fixtures only. No SSH, tokens, or service requests."""
import hashlib,json,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
import build_packet as b
import submit_reviewed_source as h
from informed_decision.lifecycle_commands import decode_memo,decode_documents
class Preparation(unittest.TestCase):
def setUp(self):
self.revisions={r:'a'*40 for r,_,_ in b.SOURCES}
def fake_show(self,command,cwd,**kwargs):return (Path(cwd)/command[-1].split(':',1)[1]).read_bytes()
def test_model_and_document_coverage(self):
with patch.object(b.subprocess,'check_output',self.fake_show):c,s=b.build(self.revisions)
m=decode_memo(c['register']['memo']);docs=decode_documents(c['register']['documents'],m)
self.assertEqual(len(docs),6);self.assertEqual({d[0] for d in docs},{i.hash for i in m.packet})
self.assertLess(len(json.dumps(c['register']).encode()),256*1024)
self.assertFalse(s['native_authorized']);self.assertEqual(c['publish']['audience']['groups'],['net-kingdom-admins'])
def test_bad_revision_refuses_before_git(self):
with patch.object(b.subprocess,'check_output') as git:
with self.assertRaises(ValueError):b.build(dict(self.revisions,**{'key-cape':'HEAD'}))
git.assert_not_called()
def test_altered_committed_bytes_refuse(self):
with patch.object(b.subprocess,'check_output',return_value=b'altered'):
with self.assertRaises(ValueError):b.build(self.revisions)
def test_missing_review_gate_refuses(self):
with tempfile.TemporaryDirectory() as td:
for name in ['lifecycle-commands.json','source-inventory.json','submit_reviewed_source.py','build_packet.py','preflight.py','correlation.py']:(Path(td)/name).write_text('{}')
p=Path(td)/'ready.json';p.write_text(json.dumps({'status':'ready_for_human_source_review','memo_id':b.ID,'version':1,'native_authorized':False}))
with self.assertRaises(ValueError):h.prepare(Path(td),p,h.sha(p))
def test_wrong_readiness_digest_refuses(self):
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'ready.json';p.write_text('{}')
with self.assertRaises(ValueError):h.prepare(Path(td),p,'0'*64)
def test_remote_program_syntax(self):compile('command={}\nident='+repr(b.ID)+'\n'+h.REMOTE,'remote','exec')
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,64 @@
{
"schema": "key39-independent-technical-source-review/v2",
"decision": "changes_requested",
"role": "independent technical source review; no foreign formal owner judgment or native authority",
"inputs": {
"manifest_sha256": "e1c57f44851a7024450c9a9a7863395201cddd4b9e1a841ff461406de01cb2c8",
"repair_receipt_sha256": "54abcff35845fed556c92dc30c1678cb28d03076f424e3e61aa23b0c9b0617bc",
"artifacts": {
"submit_reviewed_source.py": "7a6ae3edd9381aef28d8371b14f0c036f9ce78cc6bed7d18041b99fb4ce61709",
"build_packet.py": "ad4886e5946eafd88a7d3578e2c363d6174223391b792dbd052f23defb9a9267",
"preflight.py": "0e19d2ff049efbe1556e11a4f27ddbe9fb2e892155b7a36dbdfa37832ac4c572",
"correlation.py": "7d03880678f60b6aabf5c5d27cc56fb66cfa27030f329f04dcee7c3f878649e6",
"lifecycle-commands.json": "36e20813596f3ddbb86e01fd0b838867ece2f4916c5880305cf12cd61b567f89",
"source-inventory.json": "aea196db9e513900d5e7165455d6e9c3dc68749a606dc219ec340ac595642cc0"
}
},
"inspection_receipt_sha256": "ae9cd5e86e8de42b4ab161205c63e4b3fe910569c9bc4c60e030b1c0221723a4",
"prior_exact_review_sha256": "a9b28922499a1815b9940d38a3fd0586610898b6e0dbfdc23931034d7cd94ab2",
"prior_findings": {
"F01": "fixed:343-character purpose and real provider/intake/queue offline validation before authoring",
"F02": "fixed:exact queue status/detail pending+queued or replay+replay with retained identity receipt; conflicts/priorblocked refused",
"F03": "fixed:authored memo/version,event UUIDs, full exact projected envelope, queue idempotency key and outcomes review/stale/path identity correlated"
},
"findings": [
{
"id": "V2-F01",
"severity": "high",
"finding": "Six-artifact posting gate reports reviewed directory preflight/correlation hashes without verifying actual invoked/imported neighboring modules. Two actual cloned CLI --check-only subprocesses pass while unreviewed adjacent correlation replaces queued_checked, or unreviewed adjacent preflight changes approval purpose. main embeds adjacent correlation into remote program; prepare invokes imported preflight.validate. Thus exact reviewed source and reported source can diverge.",
"counterexamples": [
"test_six_hash_invocation_checks_miss_adjacent_correlation_counterexample",
"test_six_hash_invocation_checks_miss_adjacent_preflight_counterexample"
],
"required_change": "Before invoking preflight or constructing remote program, require actual helper/builder/preflight/correlation source origins and bytes match all approved artifact hashes. Restrict execution to one exact reviewed directory or explicitly compare resolved imported module source paths and hashes, including correlation read for remote embedding. Add actual CLI cross-directory tamper refusals. Preserve V2 exact candidate, make separately reviewed successor.",
"practical_scope": "Root plans one frozen directory and preinvoke all hashes; this reduces operational exposure but does not repair the claimed six-artifact invoked-source guarantee."
}
],
"validation": {
"supplied_checks_passed": 31,
"independent_checks_passed": 7,
"actual_source_currency_verified": true,
"manifest_all_entries_verified": true,
"unchanged_registration_publish_and_inventory_verified": true,
"independent_test_sha256": "13622a12b3fb73de5edf77843351caf1d4a36de3802ae2217972b3409a2b59b8",
"timeout_uncertainty_sentinel_and_sanitized_failure_verified": true,
"no_actual_SSH_or_token_IO": true
},
"positive_observations": [
"Exact provider prepare and Forwarder API fixtures pass.",
"343-character source-only approval purpose preserves full native exclusions in immutable registration attachments.",
"Replay requires retained matching review receipt; blocked and retry-wait pending refuse confirmation.",
"Remote per-operation 25-second timer covers response context close; outer transport timeout150 retains submission_unverified.",
"All original fixed-id authoring keys remain stable; local receipt exclusive-before-transport prevents same-path blind replay.",
"Pending or creating outcomes are observations only; no native acceptance or human approval inferred."
],
"limits": [
"Review receipt hashes need trusted external receipt verification; no authenticated reviewer identity is supplied by bare strings.",
"Local source acquisition/git reads remain without total preparation deadline; no privileged effect occurs until after preparation.",
"Timeout or local SSH termination cannot establish absence of remote authoring/queue effects; uncertainty record remains authoritative for followup.",
"Public runtime readiness observations supplied by root are not credential admission or native KEY39 permission."
],
"native_authorized": false,
"submitted": false,
"original_stages_modified": false
}

View file

@ -0,0 +1,93 @@
{
"schema": "key39-independent-technical-source-review/v3",
"decision": "approved",
"scope": "Exact source-only publication helper revision under explicit trusted preparation boundary; independent technical review, not foreign formal owner authority or execution permission",
"inputs": {
"manifest_sha256": "4c2ba86951f78ad2dc674189c77ff91658c088ca6e6bd1272be76b1153a8a6fd",
"repair_receipt_sha256": "55a6be976934df270469e9e821c949a0cca7f6ecefc48639bcbbaf6a147368ee",
"artifacts": {
"submit_reviewed_source.py": "8e8846f79989db25900717399b3b5f8fed2510521f5a5dabd35483d0f2bb9f3f",
"build_packet.py": "ad4886e5946eafd88a7d3578e2c363d6174223391b792dbd052f23defb9a9267",
"preflight.py": "0e19d2ff049efbe1556e11a4f27ddbe9fb2e892155b7a36dbdfa37832ac4c572",
"correlation.py": "7d03880678f60b6aabf5c5d27cc56fb66cfa27030f329f04dcee7c3f878649e6",
"lifecycle-commands.json": "36e20813596f3ddbb86e01fd0b838867ece2f4916c5880305cf12cd61b567f89",
"source-inventory.json": "aea196db9e513900d5e7165455d6e9c3dc68749a606dc219ec340ac595642cc0"
}
},
"inspection_receipt_sha256": "bde2b8efa16a7c755d0774d808f1944719231e2bc91ad099821ca7ab01d8e073",
"provider_source_pins": [
{
"path": "/home/worsch/state-hub/api/services/memo_dispatch.py",
"sha256": "0142b738750adee0feea38d2c73b2d9bf44c148c608f33803e644085aeb89052"
},
{
"path": "/home/worsch/state-hub/api/services/memo_forwarding.py",
"sha256": "944c96ca48fd234ad229ceb61254f6f50cad75005495f5fe4c510e46ebec1193"
},
{
"path": "/home/worsch/state-hub/api/services/informed_decision_contract.py",
"sha256": "127061a71e55dc3033aeb63047f3dafe7cc1f84d0ac53b7da6c51148d93584e7"
},
{
"path": "/home/worsch/informed-decision/informed_decision/lifecycle_http.py",
"sha256": "d4b95421d54663f041a10b4f42ac9c013493fa7a770223ab45877b451a7a7c7d"
},
{
"path": "/home/worsch/informed-decision/informed_decision/lifecycle_review.py",
"sha256": "b6d69be6c56f3e2f411501083e199195190df6c740a01b07e82a476268ca3629"
},
{
"path": "/home/worsch/informed-decision/informed_decision/intake.py",
"sha256": "a733b4b608b9ea90b2c8293901aa14388a0bf0d3719f121038bfdcc1faca2038"
},
{
"path": "/home/worsch/informed-decision/informed_decision/records.py",
"sha256": "82f696151895c51b168144a3078d05764da3499b96917c465629ce0836fa8e33"
},
{
"path": "/home/worsch/informed-decision/informed_decision/memo.py",
"sha256": "697058863a4e6de2c143a2433eaaf5e15e5e7375dc5459af6911b146567e8b5d"
}
],
"prior_reviews_retained": [
"a9b28922499a1815b9940d38a3fd0586610898b6e0dbfdc23931034d7cd94ab2",
"504876f314cebc30f960df431f47ad1fef3aa856d007031b2bcd1cc360093be4"
],
"findings": [],
"resolved_findings": {
"V1-F01": "343-character purpose validates against actual provider/intake/queue contracts before authoring; full source-only terms retained.",
"V1-F02": "Blocked/conflicting/retry-wait results remain unconfirmed; only exact pending+queued or retained-identity replay+replay accepted.",
"V1-F03": "Exact authored memo/version, projected envelope/packet/routing, queue key and outcomes identity/stale/path correlated.",
"V2-F01": "Exact resolved invoked directory plus actual builder/preflight/correlation module origins and bytes are enforced; function bindings checked; embedding reads the exact correlation bytes and compares reviewed digest. Prior two cross-directory cases and three identical-byte external origins all refuse."
},
"validation": {
"supplied_checks_passed": 38,
"independent_checks_passed": 9,
"independent_actual_local_CLI_cases": 6,
"test_sha256": "c8cba02f4c14a18f64b0e7105fe44b7cdbe65dd6a9d2d626a69b11d27bfd1287",
"manifest_all_entries_verified": true,
"actual_committed_and_checkout_source_currency_verified": true,
"commands_and_inventory_unchanged_from_V2": true,
"real_provider_prepare_forwarder_outcomes_fixture_passed": true,
"real_queue_conflict_and_uncertainty_retention_verified": true,
"network_or_token_IO_performed": false
},
"boundary_conditions": [
"Root must externally verify all exact artifact bytes and required dependency pins before invocation, in an exclusive owner-controlled directory with a controlled interpreter/import environment. Imports run before the application gate; this review does not claim import-time isolation or hostile same-UID protection.",
"Continuous exclusive custody between source checks and program construction/execution is required. The gate is truthful within that trusted preparation boundary; it does not authenticate itself.",
"Root verifies actual reviewer receipt identity/scope and the exact packet revision independently before producing readiness; bare approved hash strings are not reviewer authentication.",
"Public image/readiness evidence must remain current for the established authoring provider/dispatcher; source API tests do not prove deployed runtime equivalence.",
"Source-only posting authorization, if subsequently supplied, covers this exact memo and routing only. It does not authorize KEY39 tokens, private handoff, founder SSH profile, native mutation, architecture-wide acceptance or agent autonomy."
],
"uncertainty_and_idempotency": [
"Each remote operation has a 25-second timer covering response context close; outer150-second SSH timeout preserves the pre-transport exclusive uncertainty receipt.",
"Per-operation keys remain stable; blocked queue or late outcome validation retains unverified state, without blind retry.",
"Local source/git acquisition has no hard preparation deadline; no remote action happens before preparation.",
"Local timeout/termination cannot prove no remote authoring/queue effects. Required post-failure inspection/recovery remains operator-owned.",
"Queue pending/replay and creating outcomes do not prove delivery or human approval; the helper never treats dispositions as native authority."
],
"native_authorized": false,
"submitted": false,
"credential_access_performed": false,
"original_stages_modified": false
}

View file

@ -0,0 +1,13 @@
{
"status": "approved",
"role": "root independent packet technical review",
"registration_bytes": 50585,
"purpose_characters": 343,
"registration_unchanged": true,
"publication_unchanged": true,
"full_source_only_scope_retained": true,
"manifest_sha256": "4c2ba86951f78ad2dc674189c77ff91658c088ca6e6bd1272be76b1153a8a6fd",
"commands_sha256": "36e20813596f3ddbb86e01fd0b838867ece2f4916c5880305cf12cd61b567f89",
"native_authorized": false,
"submitted": false
}