Add Python witness artifact interop

This commit is contained in:
Meta Vens 2026-06-13 22:25:42 +01:00
commit 46adcea7da
5 changed files with 299 additions and 2 deletions

View file

@ -4,8 +4,10 @@ from .messages import (
compute_simulation_claim_hash,
database_subscribe,
database_unsubscribe,
decode_witness_artifact_bundle_payload,
document_delete,
document_put_raw,
encode_witness_artifact_bundle_payload,
hello,
parse_message,
schema_catalog_request,
@ -13,6 +15,7 @@ from .messages import (
shard_log_request,
simulation_observation,
snapshot_request,
witness_artifact_bundle,
)
__all__ = [
@ -20,9 +23,11 @@ __all__ = [
"compute_simulation_claim_hash",
"database_subscribe",
"database_unsubscribe",
"decode_witness_artifact_bundle_payload",
"decode_frame",
"document_delete",
"document_put_raw",
"encode_witness_artifact_bundle_payload",
"encode_frame",
"hello",
"parse_message",
@ -32,5 +37,6 @@ __all__ = [
"shard_log_request",
"simulation_observation",
"snapshot_request",
"witness_artifact_bundle",
"write_frame",
]

View file

@ -50,6 +50,9 @@ INTEROP_FIRE_COMMAND_SCHEMA_VERSION = "cultnet.interop_fire_weapon_command.v0"
INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE = "cultnet.interop-fire-weapon-receipt"
INTEROP_FIRE_RECEIPT_SCHEMA_ID = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-receipt.schema.json"
INTEROP_FIRE_RECEIPT_SCHEMA_VERSION = "cultnet.interop_fire_weapon_receipt.v0"
WITNESS_ARTIFACT_BUNDLE_DOCUMENT_TYPE = "cultnet.witness_artifact_bundle"
WITNESS_ARTIFACT_BUNDLE_SCHEMA_ID = "https://github.com/GameCult/cultnet-ts/contracts/cultnet.witness-artifact-bundle.schema.json"
WITNESS_ARTIFACT_BUNDLE_SCHEMA_VERSION = "cultnet.witness_artifact_bundle.v0"
INTEROP_WIRE_CONTRACT = "cultnet.schema.v0"
DISCOVERY_PROBE_SCHEMA_VERSION = "cultnet.discovery_probe.v0"
DISCOVERY_ANNOUNCE_SCHEMA_VERSION = "cultnet.discovery_announce.v0"
@ -675,6 +678,14 @@ def define_interop_documents(note_schema_id: str, note_schema_json: str) -> dict
"mutationReceipt": binding(INTEROP_MUTATION_RECEIPT_DOCUMENT_TYPE, INTEROP_MUTATION_RECEIPT_SCHEMA_ID, INTEROP_MUTATION_RECEIPT_SCHEMA_VERSION, "{}", mutation_receipt_slots, mutation_receipt_from_slots),
"fireCommand": binding(INTEROP_FIRE_COMMAND_DOCUMENT_TYPE, INTEROP_FIRE_COMMAND_SCHEMA_ID, INTEROP_FIRE_COMMAND_SCHEMA_VERSION, "{}", fire_command_slots, fire_command_from_slots),
"fireReceipt": binding(INTEROP_FIRE_RECEIPT_DOCUMENT_TYPE, INTEROP_FIRE_RECEIPT_SCHEMA_ID, INTEROP_FIRE_RECEIPT_SCHEMA_VERSION, "{}", fire_receipt_slots, fire_receipt_from_slots),
"witnessArtifactBundle": binding(
WITNESS_ARTIFACT_BUNDLE_DOCUMENT_TYPE,
WITNESS_ARTIFACT_BUNDLE_SCHEMA_ID,
WITNESS_ARTIFACT_BUNDLE_SCHEMA_VERSION,
witness_artifact_bundle_schema_json(),
witness_artifact_bundle_slots,
witness_artifact_bundle_from_slots,
),
}
@ -709,7 +720,7 @@ def hello_message(state: PeerState) -> dict[str, Any]:
"runtimeKind": state.runtime_kind,
"agentId": state.agent_id,
"displayName": state.display_name,
"supportedDocumentTypes": [INTEROP_DOCUMENT_TYPE],
"supportedDocumentTypes": [INTEROP_DOCUMENT_TYPE, WITNESS_ARTIFACT_BUNDLE_DOCUMENT_TYPE],
"supportedMutationContracts": [{
"documentType": INTEROP_DOCUMENT_TYPE,
"payloadSchemaVersion": INTEROP_SCHEMA_VERSION,
@ -739,6 +750,17 @@ def catalog_response(state: PeerState, request: dict[str, Any]) -> dict[str, Any
"contentHash": state.note_schema_id,
"schemaJson": state.interop_schema_json if include_schema_json else None,
})
if (not schema_ids or WITNESS_ARTIFACT_BUNDLE_SCHEMA_ID in schema_ids) and (not kinds or "document_payload" in kinds):
schemas.append({
"schemaId": WITNESS_ARTIFACT_BUNDLE_SCHEMA_ID,
"kind": "document_payload",
"schemaVersion": WITNESS_ARTIFACT_BUNDLE_SCHEMA_VERSION,
"documentType": WITNESS_ARTIFACT_BUNDLE_DOCUMENT_TYPE,
"title": "CultNet Witness Artifact Bundle",
"wireContracts": [INTEROP_WIRE_CONTRACT],
"contentHash": WITNESS_ARTIFACT_BUNDLE_SCHEMA_ID,
"schemaJson": witness_artifact_bundle_schema_json() if include_schema_json else None,
})
return {"schemaVersion": "cultnet.schema_catalog_response.v0", "messageId": request.get("messageId", ""), "schemas": schemas}
@ -896,6 +918,116 @@ def fire_receipt_from_slots(slots: list[Any]) -> dict[str, Any]:
return result
def witness_artifact_bundle_slots(value: dict[str, Any]) -> list[Any]:
return [
value["bundleId"],
value["witnessKind"],
value["capturedAt"],
value["subject"],
value["contracts"],
value["artifacts"],
value.get("timingWitnesses", []),
value["provenance"],
]
def witness_artifact_bundle_from_slots(slots: list[Any]) -> dict[str, Any]:
return {
"bundleId": slots[0],
"witnessKind": slots[1],
"capturedAt": slots[2],
"subject": slots[3],
"contracts": slots[4] if len(slots) > 4 and isinstance(slots[4], list) else [],
"artifacts": slots[5] if len(slots) > 5 and isinstance(slots[5], list) else [],
"timingWitnesses": slots[6] if len(slots) > 6 and isinstance(slots[6], list) else [],
"provenance": slots[7] if len(slots) > 7 and isinstance(slots[7], dict) else {},
}
def witness_artifact_bundle_schema_json() -> str:
return json.dumps({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": WITNESS_ARTIFACT_BUNDLE_SCHEMA_ID,
"title": "CultNet Witness Artifact Bundle",
"type": "object",
"required": ["bundleId", "witnessKind", "capturedAt", "subject", "contracts", "artifacts", "timingWitnesses", "provenance"],
"additionalProperties": False,
"properties": {
"bundleId": {"type": "string", "minLength": 1},
"witnessKind": {"type": "string", "minLength": 1},
"capturedAt": {"type": "string", "minLength": 1},
"subject": {"$ref": "#/$defs/subject_pin"},
"contracts": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/contract_pin"}},
"artifacts": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/artifact_entry"}},
"timingWitnesses": {"type": "array", "items": {"$ref": "#/$defs/timing_entry"}},
"provenance": {"$ref": "#/$defs/provenance"},
},
"$defs": {
"subject_pin": {
"type": "object",
"required": ["documentType", "subjectId"],
"additionalProperties": False,
"properties": {
"documentType": {"type": "string", "minLength": 1},
"subjectId": {"type": "string", "minLength": 1},
"schemaVersion": {"type": "string", "minLength": 1},
"schemaId": {"type": "string", "minLength": 1},
"contentHash": {"type": "string", "minLength": 1},
},
},
"contract_pin": {
"type": "object",
"required": ["role", "schemaId"],
"additionalProperties": False,
"properties": {
"role": {"type": "string", "minLength": 1},
"schemaId": {"type": "string", "minLength": 1},
"schemaVersion": {"type": "string", "minLength": 1},
"contentHash": {"type": "string", "minLength": 1},
},
},
"artifact_entry": {
"type": "object",
"required": ["role", "uri", "mediaType"],
"additionalProperties": False,
"properties": {
"role": {"type": "string", "minLength": 1},
"uri": {"type": "string", "minLength": 1},
"mediaType": {"type": "string", "minLength": 1},
"contentHash": {"type": "string", "minLength": 1},
"byteLength": {"type": "integer", "minimum": 0},
"producedAt": {"type": "string", "minLength": 1},
},
},
"timing_entry": {
"type": "object",
"required": ["stage", "startedAt", "completedAt", "latencyMs"],
"additionalProperties": False,
"properties": {
"stage": {"type": "string", "minLength": 1},
"startedAt": {"type": "string", "minLength": 1},
"completedAt": {"type": "string", "minLength": 1},
"latencyMs": {"type": "number", "minimum": 0},
"witnessArtifactUri": {"type": "string", "minLength": 1},
},
},
"provenance": {
"type": "object",
"required": ["pipelineId", "runId", "runtimeId"],
"additionalProperties": False,
"properties": {
"pipelineId": {"type": "string", "minLength": 1},
"runId": {"type": "string", "minLength": 1},
"runtimeId": {"type": "string", "minLength": 1},
"agentId": {"type": "string", "minLength": 1},
"agentRole": {"type": "string", "minLength": 1},
"toolVersion": {"type": "string", "minLength": 1},
},
},
},
}, separators=(",", ":"))
def runtime_store_path(runtime_id: str) -> str:
return str(Path(tempfile.gettempdir()) / f"cultnet-py-interop-{runtime_id}.msgpack")

View file

@ -186,3 +186,55 @@ def simulation_observation(
"cultnet.simulation_observation.v0",
{"messageId": message_id, "observation": observation},
)
def witness_artifact_bundle(
*,
bundle_id: str,
witness_kind: str,
captured_at: str,
subject: dict[str, Any],
contracts: list[dict[str, Any]],
artifacts: list[dict[str, Any]],
provenance: dict[str, Any],
timing_witnesses: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
return {
"bundleId": bundle_id,
"witnessKind": witness_kind,
"capturedAt": captured_at,
"subject": subject,
"contracts": contracts,
"artifacts": artifacts,
"timingWitnesses": timing_witnesses or [],
"provenance": provenance,
}
def encode_witness_artifact_bundle_payload(bundle: dict[str, Any]) -> bytes:
return msgpack.packb([
bundle["bundleId"],
bundle["witnessKind"],
bundle["capturedAt"],
bundle["subject"],
bundle["contracts"],
bundle["artifacts"],
bundle.get("timingWitnesses", []),
bundle["provenance"],
], use_bin_type=True)
def decode_witness_artifact_bundle_payload(payload: bytes) -> dict[str, Any]:
slots = msgpack.unpackb(payload, raw=False)
if not isinstance(slots, list) or len(slots) < 8:
raise ValueError("CultNet witness artifact bundle payload must be an 8-slot MessagePack array")
return {
"bundleId": slots[0],
"witnessKind": slots[1],
"capturedAt": slots[2],
"subject": slots[3],
"contracts": slots[4],
"artifacts": slots[5],
"timingWitnesses": slots[6],
"provenance": slots[7],
}

View file

@ -14,7 +14,7 @@ from cultcache_py import (
define_document_type,
)
from cultcache_py.interop import read_note, write_note
from cultnet_py import compute_simulation_claim_hash, database_subscribe, database_unsubscribe, decode_frame, document_put_raw, encode_frame, hello, parse_message, shard_catalog_request, shard_log_request, simulation_observation
from cultnet_py import compute_simulation_claim_hash, database_subscribe, database_unsubscribe, decode_frame, decode_witness_artifact_bundle_payload, document_put_raw, encode_frame, encode_witness_artifact_bundle_payload, hello, parse_message, shard_catalog_request, shard_log_request, simulation_observation, witness_artifact_bundle
from cultmesh_py import create_node
from cultmesh_py import (
CultMeshPeerCard,
@ -253,6 +253,26 @@ class CultCacheTests(unittest.TestCase):
self.assertEqual(message["observation"]["claimHash"], claim_hash)
self.assertEqual(message["observation"]["weight"], 1.0)
def test_cultnet_witness_artifact_bundle_uses_csharp_slot_order(self) -> None:
bundle = witness_artifact_bundle(
bundle_id="bundle-1",
witness_kind="interop-proof",
captured_at="2026-06-13T00:00:03Z",
subject={"documentType": "cultnet.interop-note", "subjectId": "note:python"},
contracts=[{"role": "payload", "schemaId": "schema-a"}],
artifacts=[{"role": "log", "uri": "cultcache://bundle-1/log", "mediaType": "text/plain"}],
timing_witnesses=[{"stage": "roundtrip", "startedAt": "2026-06-13T00:00:03Z", "completedAt": "2026-06-13T00:00:04Z", "latencyMs": 1.0}],
provenance={"pipelineId": "interop", "runId": "run-1", "runtimeId": "python-test"},
)
payload = encode_witness_artifact_bundle_payload(bundle)
decoded = decode_witness_artifact_bundle_payload(payload)
self.assertEqual(decoded["bundleId"], "bundle-1")
self.assertEqual(decoded["witnessKind"], "interop-proof")
self.assertEqual(decoded["subject"]["subjectId"], "note:python")
self.assertEqual(decoded["contracts"][0]["schemaId"], "schema-a")
self.assertEqual(decoded["artifacts"][0]["mediaType"], "text/plain")
self.assertEqual(decoded["provenance"]["runtimeId"], "python-test")
def test_cultmesh_node_uses_cultcache_store(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
document = define_database_entry_type("mesh.note", [("body", 0)])

View file

@ -29,6 +29,7 @@ const cultnetRsRoot = existsSync(resolve(cultLibRoot, "packages", "cultnet-rs"))
const tsPeerScript = resolve(cultNetTsRoot, "dist-test", "test", "interop", "cultnet-interop-peer.js");
const interopSchemaPath = resolve(cultNetTsRoot, "integration", "contracts", "cultnet.interop-note.schema.json");
const interopNoteSchemaId = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note.schema.json";
const witnessArtifactBundleSchemaId = "https://github.com/GameCult/cultnet-ts/contracts/cultnet.witness-artifact-bundle.schema.json";
const csharpProjectPath = resolve(
cultLibRoot,
"tests",
@ -373,6 +374,45 @@ test("CultNet TS/Rust/C#/Python peers discover each other and exchange raw state
assert.equal(pythonCandidate.hasQuorum, true);
assert.equal(pythonCandidate.confidence, 1);
const pythonWitness = await putAndSnapshotPythonWitnessBundle(pythonPort, {
schemaVersion: "cultnet.document_put_raw.v0",
messageId: "python-witness-put",
document: {
schemaId: witnessArtifactBundleSchemaId,
recordKey: "bundle:ts-python-witness",
storedAt: "2026-06-13T00:00:03Z",
payloadEncoding: "messagepack",
payload: encode([
"bundle:ts-python-witness",
"interop-proof",
"2026-06-13T00:00:03Z",
{
documentType: "cultnet.interop-note",
subjectId: "note:python-peer",
schemaVersion: INTEROP_SCHEMA_VERSION,
schemaId: interopNoteSchemaId,
},
[{ role: "payload", schemaId: interopNoteSchemaId, schemaVersion: INTEROP_SCHEMA_VERSION }],
[{ role: "log", uri: "cultcache://bundle:ts-python-witness/log", mediaType: "text/plain" }],
[{ stage: "roundtrip", startedAt: "2026-06-13T00:00:03Z", completedAt: "2026-06-13T00:00:04Z", latencyMs: 1 }],
{ pipelineId: "interop", runId: "ts-python-witness", runtimeId: "ts-witness", agentId: "ts-agent" },
]),
sourceRuntimeId: "ts-witness",
},
});
assert.equal(pythonWitness.catalog.schemaVersion, "cultnet.schema_catalog_response.v0");
assert.equal(pythonWitness.catalog.schemas[0].schemaId, witnessArtifactBundleSchemaId);
assert.equal(pythonWitness.catalog.schemas[0].documentType, "cultnet.witness_artifact_bundle");
assert.ok(String(pythonWitness.catalog.schemas[0].schemaJson).includes("CultNet Witness Artifact Bundle"));
assert.equal(pythonWitness.snapshot.schemaVersion, "cultnet.snapshot_response_raw.v0");
assert.equal(pythonWitness.snapshot.documents[0].schemaId, witnessArtifactBundleSchemaId);
assert.equal(pythonWitness.snapshot.documents[0].recordKey, "bundle:ts-python-witness");
const witnessSlots = decode(pythonWitness.snapshot.documents[0].payload) as any[];
assert.equal(witnessSlots[0], "bundle:ts-python-witness");
assert.equal(witnessSlots[1], "interop-proof");
assert.equal(witnessSlots[3].subjectId, "note:python-peer");
assert.equal(witnessSlots[7].runtimeId, "ts-witness");
const expectedPeers = ["csharp-peer", "python-peer", "rust-peer", "ts-peer"];
await expectProbePeers("ts-probe", process.execPath, [
@ -689,6 +729,53 @@ function computeSimulationClaimHash(...parts: string[]): string {
return createHash("sha256").update(parts.join("\x1f"), "utf8").digest("hex");
}
async function putAndSnapshotPythonWitnessBundle(port: number, put: Record<string, unknown>): Promise<{ catalog: any; snapshot: any }> {
const socket = connectTcp(port, "127.0.0.1");
const framer = new LengthPrefixedMessageFramer();
await once(socket, "connect");
return await new Promise((resolve, reject) => {
const result: { catalog?: any; snapshot?: any } = {};
const timeout = setTimeout(() => {
socket.destroy();
reject(new Error("Timed out waiting for Python witness artifact bundle roundtrip."));
}, 5000);
socket.on("data", (chunk) => {
for (const frame of framer.push(chunk)) {
const decoded = decode(frame) as any;
if (decoded?.schemaVersion === "cultnet.schema_catalog_response.v0") {
result.catalog = decoded;
socket.write(encodeFrame(encode(put)));
socket.write(encodeFrame(encode({
schemaVersion: "cultnet.snapshot_request.v0",
messageId: "python-witness-snapshot",
schemaIds: [witnessArtifactBundleSchemaId],
recordKeys: ["bundle:ts-python-witness"],
})));
} else if (decoded?.schemaVersion === "cultnet.snapshot_response_raw.v0") {
result.snapshot = decoded;
}
if (result.catalog && result.snapshot) {
clearTimeout(timeout);
socket.end();
resolve({ catalog: result.catalog, snapshot: result.snapshot });
}
}
});
socket.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
socket.write(encodeFrame(encode({
schemaVersion: "cultnet.schema_catalog_request.v0",
messageId: "python-witness-catalog",
includeSchemaJson: true,
schemaIds: [witnessArtifactBundleSchemaId],
})));
});
}
async function stopProcess(processState: RunningServeProcess): Promise<void> {
if (processState.child.killed || processState.child.exitCode !== null) {
return;