From eeebc64c56ba56f30f58609f06cd3e25191a2e0f Mon Sep 17 00:00:00 2001 From: drzo <1.5202748e+07+drzo@users.noreply.github.com> Date: Mon, 31 Aug 2026 03:24:04 +0000 Subject: [PATCH 1/4] feat(village): enforce authentic resident generation provenance --- village/CMakeLists.txt | 29 +- village/elizad.cpp | 186 +++++--- village/response_authenticity.cpp | 612 +++++++++++++++++++++++++ village/response_authenticity.hpp | 166 +++++++ village/response_authenticity_test.cpp | 283 ++++++++++++ village/response_development.cpp | 372 +++++++++++++++ village/response_development.hpp | 114 +++++ village/response_development_test.cpp | 181 ++++++++ village/village_atomspace.hpp | 282 +++++++++--- 9 files changed, 2101 insertions(+), 124 deletions(-) create mode 100644 village/response_authenticity.cpp create mode 100644 village/response_authenticity.hpp create mode 100644 village/response_authenticity_test.cpp create mode 100644 village/response_development.cpp create mode 100644 village/response_development.hpp create mode 100644 village/response_development_test.cpp diff --git a/village/CMakeLists.txt b/village/CMakeLists.txt index 59fb265df..80642e7d4 100644 --- a/village/CMakeLists.txt +++ b/village/CMakeLists.txt @@ -3,6 +3,7 @@ find_package(CURL REQUIRED) find_package(SQLite3 REQUIRED) +find_package(OpenSSL REQUIRED) # Include paths set(ELIZAOS_VILLAGE_INCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/../include) @@ -15,6 +16,29 @@ target_include_directories(village_event_bus PUBLIC ) target_link_libraries(village_event_bus PUBLIC CURL::libcurl nlohmann_json::nlohmann_json) +# Resident generation provenance, validation, and append-only evidence journal +add_library(response_authenticity STATIC response_authenticity.cpp) +target_include_directories(response_authenticity PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${ELIZAOS_VILLAGE_INCLUDE} +) +target_link_libraries(response_authenticity PUBLIC OpenSSL::Crypto nlohmann_json::nlohmann_json) + +add_executable(response_authenticity_test response_authenticity_test.cpp) +target_link_libraries(response_authenticity_test PRIVATE response_authenticity) +add_test(NAME response_authenticity_test COMMAND response_authenticity_test) + +add_library(response_development STATIC response_development.cpp) +target_include_directories(response_development PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${ELIZAOS_VILLAGE_INCLUDE} +) +target_link_libraries(response_development PUBLIC response_authenticity nlohmann_json::nlohmann_json) + +add_executable(response_development_test response_development_test.cpp) +target_link_libraries(response_development_test PRIVATE response_development) +add_test(NAME response_development_test COMMAND response_development_test) + # Village Group Dynamics library add_library(village_group_dynamics STATIC village_group_dynamics.cpp) target_include_directories(village_group_dynamics PUBLIC @@ -40,6 +64,7 @@ target_include_directories(elizad PRIVATE ) target_link_libraries(elizad PRIVATE village_event_bus + response_authenticity village_group_dynamics antikythera_coupling elizaos-autonomous_starter @@ -64,7 +89,9 @@ if(WIN32) endif() install(TARGETS elizad RUNTIME DESTINATION bin) -install(TARGETS village_event_bus village_group_dynamics antikythera_coupling ARCHIVE DESTINATION lib) +install(TARGETS village_event_bus response_authenticity response_development village_group_dynamics antikythera_coupling ARCHIVE DESTINATION lib) install(FILES village_event_bus.hpp village_group_dynamics.hpp antikythera_coupling.hpp village_ksm_transfer.hpp village_agnai_bridge.hpp village_atomspace.hpp + response_authenticity.hpp + response_development.hpp DESTINATION include/elizaos) diff --git a/village/elizad.cpp b/village/elizad.cpp index adcacc080..fad2bd4f6 100644 --- a/village/elizad.cpp +++ b/village/elizad.cpp @@ -91,15 +91,14 @@ using Clock = std::chrono::steady_clock; static std::atomic g_running{true}; -// Thread-safe queue for thoughts from inference threads -struct PendingThought { - std::string resident; - std::string thought; - int inference_id; - std::string correlation_id; +// Thread-safe queue for committed generation evidence from inference threads. +// Only generated-authentic entries may become resident.thought events. +struct PendingGeneration { + ::village::authenticity::GenerationEvidence evidence; + int inference_id = 0; }; static std::mutex g_thoughtMutex; -static std::vector g_pendingThoughts; +static std::vector g_pendingGenerations; // Action dispatch system (Cycle 006) struct VillageAction { @@ -206,6 +205,16 @@ static std::string startupEnvironment(const char* name) { return value == nullptr ? std::string{} : std::string(value); } +static bool startupBoolean(const char* name, bool fallback) { + const std::string value = startupEnvironment(name); + if (value.empty()) return fallback; + if (value == "1" || value == "true" || value == "TRUE" || value == "yes") return true; + if (value == "0" || value == "false" || value == "FALSE" || value == "no") return false; + std::cerr << "[elizad] Ignoring invalid " << name << "='" << value + << "': expected true or false\n"; + return fallback; +} + static int startupInteger(const char* name, int fallback, int minimum, int maximum) { const std::string value = startupEnvironment(name); if (value.empty()) return fallback; @@ -252,6 +261,11 @@ struct ElizadConfig { std::string aphroditeApiKey = "cogcity-village-2026"; std::string aphroditeModel = "/var/agi_neighborhood/aphrodite/models/lucid-v1-nemo-gguf/lucid-v1-nemo-q8_0.gguf"; + std::string aphroditeModelRevision = "unconfigured"; + std::string identityVersion = "unconfigured"; + std::string generationEvidencePath = + "/var/agi_neighborhood/evidence/resident-generation"; + bool residentActionsEnabled = false; double inferenceSTIThreshold = 150.0; int inferenceCooldownCycles = 100; @@ -268,6 +282,11 @@ struct ElizadConfig { if (auto value = startupEnvironment("ELIZAD_APHRODITE_URL"); !value.empty()) cfg.aphroditeUrl = value; if (auto value = startupEnvironment("ELIZAD_APHRODITE_API_KEY"); !value.empty()) cfg.aphroditeApiKey = value; if (auto value = startupEnvironment("ELIZAD_APHRODITE_MODEL"); !value.empty()) cfg.aphroditeModel = value; + if (auto value = startupEnvironment("ELIZAD_APHRODITE_MODEL_REVISION"); !value.empty()) cfg.aphroditeModelRevision = value; + if (auto value = startupEnvironment("ELIZAD_IDENTITY_VERSION"); !value.empty()) cfg.identityVersion = value; + if (auto value = startupEnvironment("ELIZAD_GENERATION_EVIDENCE_PATH"); !value.empty()) cfg.generationEvidencePath = value; + cfg.residentActionsEnabled = startupBoolean( + "ELIZAD_RESIDENT_ACTIONS_ENABLED", cfg.residentActionsEnabled); cfg.inferenceSTIThreshold = startupDouble( "ELIZAD_INFERENCE_STI_THRESHOLD", cfg.inferenceSTIThreshold, 0.0); cfg.inferenceCooldownCycles = startupInteger( @@ -707,47 +726,37 @@ static int runElizad(int argc, char* argv[]) { aphroditeConfig.url = config.aphroditeUrl; aphroditeConfig.api_key = config.aphroditeApiKey; aphroditeConfig.model = config.aphroditeModel; + aphroditeConfig.model_revision = config.aphroditeModelRevision; + aphroditeConfig.identity_version = config.identityVersion; + aphroditeConfig.allow_action_proposals = config.residentActionsEnabled; aphroditeConfig.sti_threshold = config.inferenceSTIThreshold; aphroditeConfig.inference_cooldown_cycles = config.inferenceCooldownCycles; ::village::atomspace::AphroditeBridge aphroditeBridge(aphroditeConfig); - // Cycle 008: record each stimulus/response pair into rolling conversation - // history so subsequent prompts include [Conversation history] context. - aphroditeBridge.set_conversation_recorder( - [&villageAtomSpace](const std::string& resident, const std::string& stimulus, - const std::string& response) { - villageAtomSpace.add_conversation(resident, stimulus, response); - }); + ::village::authenticity::ProvenanceJournal generationJournal( + config.generationEvidencePath); + std::string journalError; + if (!generationJournal.verify(journalError)) { + std::cerr << "[elizad] FATAL: generation provenance journal is invalid: " + << journalError << '\n'; + return 5; + } std::atomic inferenceCount{0}; - // Inference callback: when a resident thinks, publish to bus + ingest to AtomSpace - auto onInferenceComplete = [&bus, &villageAtomSpace, &inferenceCount]( - const std::string& resident, const std::string& thought, const std::string& correlation_id) { + // Commit the real model result or failure before the main loop may publish + // anything. Journal failure denies publication rather than inventing speech. + auto onInferenceComplete = [&generationJournal, &inferenceCount]( + ::village::authenticity::GenerationEvidence evidence) { try { - inferenceCount++; - // Publish thought to the village bus - fprintf(stderr, "[CB] %s thought=%zu\n", resident.c_str(), thought.size()); - // Queue for main loop to publish (thread-safe) - { + std::string error; + if (!generationJournal.commit(evidence, error)) { + fprintf(stderr, + "[AUTHENTICITY] journal commit failed generation=%s error=%s\n", + evidence.generation_id.c_str(), error.c_str()); + return; + } + const int inferenceId = ++inferenceCount; std::lock_guard lock(g_thoughtMutex); - g_pendingThoughts.push_back({resident, thought, static_cast(inferenceCount.load()), correlation_id}); - } - // Parse and queue any actions from the thought - auto actions = parse_actions(resident, thought, static_cast(inferenceCount.load()), correlation_id); - if (!actions.empty()) { - std::lock_guard lock(g_actionMutex); - for (auto& a : actions) g_pendingActions.push_back(std::move(a)); - fprintf(stderr, "[CB] Queued %zu actions\n", actions.size()); - } - fprintf(stderr, "[CB] Queued for publish OK\n"); - - // Ingest into AtomSpace as a cognitive event (thread-safe queue) - ::village::atomspace::CognitiveEvent ev; - ev.type = "resident_thought"; - ev.participants = {resident}; - ev.content = thought.substr(0, 200); // Truncate for AtomSpace storage - ev.emotional_valence = 0.6; - ev.information_gain = 0.9; - villageAtomSpace.enqueue_event(ev); + g_pendingGenerations.push_back({std::move(evidence), inferenceId}); } catch (const std::exception& e) { fprintf(stderr, "[CB-ERR] %s\n", e.what()); } catch (...) { fprintf(stderr, "[CB-ERR] unknown\n"); } }; @@ -772,7 +781,7 @@ static int runElizad(int argc, char* argv[]) { } fprintf(stderr, "[STIMULUS] received: target=%s\n", target.c_str()); if (!target.empty() && target != "eliza" && target != "dan") { - std::string message = "You have been addressed. Respond authentically."; + std::string message; try { auto j = json::parse(event.payload); if (j.contains("message")) message = j["message"].get(); @@ -781,7 +790,9 @@ static int runElizad(int argc, char* argv[]) { fprintf(stderr, "[STIMULUS] Invalid message payload: %s\n", e.what()); } fprintf(stderr, "[STIMULUS] calling infer_async for %s: %s\n", target.c_str(), message.substr(0,50).c_str()); - aphroditeBridge.infer_async(villageAtomSpace, target, message, onInferenceComplete, 0.7, correlation_id); + aphroditeBridge.infer_async( + villageAtomSpace, target, message, onInferenceComplete, 0.7, + correlation_id, event.source, event.id, event.tic); // Cycle 007: Record stimulus in episodic memory villageAtomSpace.add_episodic(target, "stimulus", message); } @@ -790,6 +801,9 @@ static int runElizad(int argc, char* argv[]) { if (event.typeStr == "resident.thought") { try { auto j = json::parse(event.payload); + if (j.value("authenticity_status", "") != "generated-authentic") { + return; + } std::string thinker = j.value("resident", ""); std::string thought = j.value("thought", ""); if (!thinker.empty() && !thought.empty()) { @@ -804,7 +818,8 @@ static int runElizad(int argc, char* argv[]) { std::string stimulus = thinker + " said: \"" + thought.substr(0, 300) + "\" — What is your response?"; aphroditeBridge.infer_async( - villageAtomSpace, name, stimulus, onInferenceComplete); + villageAtomSpace, name, stimulus, onInferenceComplete, + 0.7, "", "resident.thought", event.id, event.tic); break; // Only one respondent per thought } } @@ -879,22 +894,75 @@ static int runElizad(int argc, char* argv[]) { // ---- Drain pending inference results into AtomSpace ---- villageAtomSpace.drain_pending_events(); - // Drain pending thoughts from inference threads. Swap under the queue - // lock, then publish and persist outside it so producers never wait on I/O. - std::vector pendingThoughts; + // Drain committed generation evidence. A successful model call is not + // speech until the private journal has validated every binding. + std::vector pendingGenerations; { std::lock_guard lock(g_thoughtMutex); - pendingThoughts.swap(g_pendingThoughts); + pendingGenerations.swap(g_pendingGenerations); } - for (auto& pt : pendingThoughts) { - json thoughtPayload = { - {"resident", pt.resident}, {"thought", pt.thought}, - {"kind", "inference"}, {"inference_id", pt.inference_id} - }; - if (!pt.correlation_id.empty()) thoughtPayload["correlation_id"] = pt.correlation_id; - bus.publish("resident.thought", thoughtPayload.dump()); - fprintf(stderr, "[MAIN] Published thought for %s\n", pt.resident.c_str()); - villageAtomSpace.add_episodic(pt.resident, "thought", pt.thought); + for (auto& pending : pendingGenerations) { + auto& evidence = pending.evidence; + auto payload = evidence.to_public_json(); + payload["inference_id"] = pending.inference_id; + if (evidence.publication.allowed && + evidence.result.status == "generated-authentic") { + payload["kind"] = "runtime-model-inference"; + payload["authenticity_status"] = "generated-authentic"; + payload["thought"] = evidence.result.normalized_completion; + const auto publishedTic = + bus.publish("resident.thought", payload.dump()); + if (publishedTic < 0) { + fprintf(stderr, + "[AUTHENTICITY] publication failed generation=%s resident=%s\n", + evidence.generation_id.c_str(), + evidence.resident.id.c_str()); + continue; + } + villageAtomSpace.add_episodic( + evidence.resident.id, "thought", + evidence.result.normalized_completion); + villageAtomSpace.add_conversation( + evidence.resident.id, evidence.stimulus.text, + evidence.result.normalized_completion); + if (config.residentActionsEnabled) { + auto actions = parse_actions( + evidence.resident.id, + evidence.result.normalized_completion, + pending.inference_id, evidence.correlation_id); + if (!actions.empty()) { + std::lock_guard lock(g_actionMutex); + for (auto& action : actions) { + g_pendingActions.push_back(std::move(action)); + } + } + } + ::village::atomspace::CognitiveEvent cognitiveEvent; + cognitiveEvent.type = "resident_thought"; + cognitiveEvent.participants = {evidence.resident.id}; + cognitiveEvent.content = + evidence.result.normalized_completion.substr(0, 200); + cognitiveEvent.emotional_valence = 0.6; + cognitiveEvent.information_gain = 0.9; + villageAtomSpace.enqueue_event(cognitiveEvent); + fprintf(stderr, + "[AUTHENTICITY] published generation=%s resident=%s tic=%lld\n", + evidence.generation_id.c_str(), + evidence.resident.id.c_str(), + static_cast(publishedTic)); + } else { + const std::string eventType = + evidence.result.status == "provenance-rejected" + ? "resident.generation.rejected" + : "resident.generation.failed"; + payload["authenticity_status"] = evidence.result.status; + bus.publish(eventType, payload.dump()); + fprintf(stderr, + "[AUTHENTICITY] denied generation=%s resident=%s code=%s\n", + evidence.generation_id.c_str(), + evidence.resident.id.c_str(), + evidence.result.error_code.c_str()); + } } // Drain actions with the same swap discipline. Execution, AtomSpace @@ -934,7 +1002,9 @@ static int runElizad(int argc, char* argv[]) { if (aphroditeBridge.should_infer(name, sti)) { std::string stimulus = "The village is alive. You feel the attention of the collective upon you (STI=" + std::to_string(static_cast(sti)) + "). What thought arises?"; - aphroditeBridge.infer_async(villageAtomSpace, name, stimulus, onInferenceComplete); + aphroditeBridge.infer_async( + villageAtomSpace, name, stimulus, onInferenceComplete, 0.7, + "", "elizad.attention", 0, bus.getCurrentTic()); // Reduce STI to prevent immediate re-trigger villageAtomSpace.set_resident_sti(name, 100.0); } diff --git a/village/response_authenticity.cpp b/village/response_authenticity.cpp new file mode 100644 index 000000000..ec994acfe --- /dev/null +++ b/village/response_authenticity.cpp @@ -0,0 +1,612 @@ +#include "response_authenticity.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif + +namespace village::authenticity { +namespace { + +std::string to_hex(const unsigned char* data, std::size_t size) { + static constexpr char digits[] = "0123456789abcdef"; + std::string output(size * 2, '0'); + for (std::size_t i = 0; i < size; ++i) { + output[i * 2] = digits[(data[i] >> 4U) & 0x0FU]; + output[i * 2 + 1] = digits[data[i] & 0x0FU]; + } + return output; +} + +bool atomic_write_private(const std::filesystem::path& path, const std::string& content, + std::string& error) { + const auto temporary = path.string() + ".tmp"; +#ifdef _WIN32 + std::ofstream stream(temporary, std::ios::binary | std::ios::trunc); + if (!stream) { + error = "cannot_open_temporary_artifact"; + return false; + } + stream.write(content.data(), static_cast(content.size())); + stream.flush(); + if (!stream) { + error = "cannot_write_temporary_artifact"; + return false; + } + stream.close(); +#else + const int fd = ::open(temporary.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); + if (fd < 0) { + error = "cannot_open_temporary_artifact"; + return false; + } + std::size_t written = 0; + while (written < content.size()) { + const auto count = ::write(fd, content.data() + written, content.size() - written); + if (count <= 0) { + ::close(fd); + error = "cannot_write_temporary_artifact"; + return false; + } + written += static_cast(count); + } + if (::fsync(fd) != 0) { + ::close(fd); + error = "cannot_fsync_temporary_artifact"; + return false; + } + ::close(fd); +#endif + std::error_code ec; + std::filesystem::rename(temporary, path, ec); + if (ec) { + std::filesystem::remove(temporary); + error = "cannot_commit_artifact:" + ec.message(); + return false; + } + return true; +} + +bool append_private(const std::filesystem::path& path, const std::string& content, + std::string& error) { +#ifdef _WIN32 + std::ofstream stream(path, std::ios::binary | std::ios::app); + if (!stream) { + error = "cannot_open_journal"; + return false; + } + stream.write(content.data(), static_cast(content.size())); + stream.flush(); + if (!stream) { + error = "cannot_append_journal"; + return false; + } + return true; +#else + const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); + if (fd < 0) { + error = "cannot_open_journal"; + return false; + } + std::size_t written = 0; + while (written < content.size()) { + const auto count = ::write(fd, content.data() + written, content.size() - written); + if (count <= 0) { + ::close(fd); + error = "cannot_append_journal"; + return false; + } + written += static_cast(count); + } + if (::fsync(fd) != 0) { + ::close(fd); + error = "cannot_fsync_journal"; + return false; + } + ::close(fd); + return true; +#endif +} + +nlohmann::json record_without_hash(const GenerationEvidence& evidence) { + auto record = evidence.to_private_json(); + record["chain"]["record_sha256"] = ""; + return record; +} + +ValidationFinding invalid(const std::string& code, const std::string& detail) { + return {false, code, detail}; +} + +} // namespace + +std::string sha256(const std::string& value) { + EVP_MD_CTX* context = EVP_MD_CTX_new(); + if (context == nullptr) throw std::runtime_error("sha256_context_allocation_failed"); + std::array digest{}; + unsigned int digest_length = 0; + const bool ok = EVP_DigestInit_ex(context, EVP_sha256(), nullptr) == 1 && + EVP_DigestUpdate(context, value.data(), value.size()) == 1 && + EVP_DigestFinal_ex(context, digest.data(), &digest_length) == 1; + EVP_MD_CTX_free(context); + if (!ok) throw std::runtime_error("sha256_digest_failed"); + return to_hex(digest.data(), digest_length); +} + +std::string utc_now_iso8601() { + const auto now = std::chrono::system_clock::now(); + const auto seconds = std::chrono::system_clock::to_time_t(now); + std::tm utc{}; +#ifdef _WIN32 + gmtime_s(&utc, &seconds); +#else + gmtime_r(&seconds, &utc); +#endif + const auto millis = std::chrono::duration_cast( + now.time_since_epoch()) % 1000; + std::ostringstream stream; + stream << std::put_time(&utc, "%Y-%m-%dT%H:%M:%S") << '.' << std::setw(3) + << std::setfill('0') << millis.count() << 'Z'; + return stream.str(); +} + +std::string random_generation_id() { + std::array bytes{}; + if (RAND_bytes(bytes.data(), static_cast(bytes.size())) != 1) { + throw std::runtime_error("generation_id_entropy_failed"); + } + return to_hex(bytes.data(), bytes.size()); +} + +int random_seed() { + std::uint32_t value = 0; + if (RAND_bytes(reinterpret_cast(&value), sizeof(value)) != 1) { + throw std::runtime_error("generation_seed_entropy_failed"); + } + return static_cast((value & 0x7fffffffU) | 1U); +} + +bool is_sha256(const std::string& value) { + return value.size() == 64 && std::all_of(value.begin(), value.end(), [](unsigned char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); +} + +std::string canonical_json(const nlohmann::json& value) { + return value.dump(); +} + +nlohmann::json GenerationEvidence::to_private_json() const { + return { + {"schema_version", schema_version}, + {"generation_id", generation_id}, + {"created_at", created_at}, + {"correlation_id", correlation_id}, + {"resident", { + {"id", resident.id}, + {"identity_version", resident.identity_version}, + {"identity_manifest", resident.identity_manifest}, + {"identity_manifest_sha256", resident.identity_manifest_sha256}, + {"role_prompt", resident.role_prompt}, + {"role_prompt_sha256", resident.role_prompt_sha256} + }}, + {"context", { + {"system_prompt", context.system_prompt}, + {"system_prompt_sha256", context.system_prompt_sha256}, + {"memory_snapshot", context.memory_snapshot}, + {"memory_snapshot_sha256", context.memory_snapshot_sha256}, + {"shared_context", context.shared_context}, + {"shared_context_sha256", context.shared_context_sha256}, + {"cognitive_state", context.cognitive_state}, + {"cognitive_state_sha256", context.cognitive_state_sha256}, + {"combined_context_sha256", context.combined_context_sha256}, + {"selection_record", context.selection_record}, + {"selection_record_sha256", context.selection_record_sha256} + }}, + {"stimulus", { + {"source", stimulus.source}, {"target", stimulus.target}, + {"text", stimulus.text}, {"utf8_sha256", stimulus.utf8_sha256}, + {"parent_event_id", stimulus.parent_event_id}, + {"parent_tic", stimulus.parent_tic} + }}, + {"invocation", { + {"started_at", invocation.started_at}, {"server", invocation.server}, + {"model_id", invocation.model_id}, {"model_revision", invocation.model_revision}, + {"temperature", invocation.temperature}, {"min_p", invocation.min_p}, + {"max_tokens", invocation.max_tokens}, {"seed", invocation.seed}, + {"seed_sha256", invocation.seed_sha256}, + {"request_body", invocation.request_body}, + {"request_body_sha256", invocation.request_body_sha256}, + {"adapter_id", invocation.adapter_id.empty() ? nlohmann::json(nullptr) : nlohmann::json(invocation.adapter_id)}, + {"adapter_sha256", invocation.adapter_sha256.empty() ? nlohmann::json(nullptr) : nlohmann::json(invocation.adapter_sha256)} + }}, + {"result", { + {"status", result.status}, {"finished_at", result.finished_at}, + {"latency_ms", result.latency_ms}, {"http_status", result.http_status}, + {"transport_code", result.transport_code}, {"finish_reason", result.finish_reason}, + {"prompt_tokens", result.prompt_tokens}, {"completion_tokens", result.completion_tokens}, + {"raw_response", result.raw_response}, {"raw_response_sha256", result.raw_response_sha256}, + {"raw_completion", result.raw_completion}, {"raw_completion_sha256", result.raw_completion_sha256}, + {"normalized_completion", result.normalized_completion}, + {"normalized_completion_sha256", result.normalized_completion_sha256}, + {"exact_completion_prior_count", result.exact_completion_prior_count}, + {"exact_completion_duplicate", result.exact_completion_duplicate}, + {"normalization", result.normalization}, + {"error_code", result.error_code}, {"error_detail", result.error_detail} + }}, + {"publication", { + {"allowed", publication.allowed}, + {"validator_version", publication.validator_version}, + {"denial_reason", publication.denial_reason} + }}, + {"development", { + {"eligible", development.eligible}, + {"history_immutable", development.history_immutable}, + {"automatic_identity_mutation_allowed", development.automatic_identity_mutation_allowed}, + {"review_state", development.review_state}, + {"outcome", development.outcome} + }}, + {"chain", { + {"sequence", chain.sequence}, + {"previous_record_sha256", chain.previous_record_sha256}, + {"record_sha256", chain.record_sha256} + }} + }; +} + +nlohmann::json GenerationEvidence::to_public_json() const { + return { + {"schema_version", schema_version}, + {"generation_id", generation_id}, + {"correlation_id", correlation_id}, + {"resident", resident.id}, + {"identity_version", resident.identity_version}, + {"identity_manifest_sha256", resident.identity_manifest_sha256}, + {"role_prompt_sha256", resident.role_prompt_sha256}, + {"system_prompt_sha256", context.system_prompt_sha256}, + {"memory_snapshot_sha256", context.memory_snapshot_sha256}, + {"shared_context_sha256", context.shared_context_sha256}, + {"cognitive_state_sha256", context.cognitive_state_sha256}, + {"combined_context_sha256", context.combined_context_sha256}, + {"selection_record_sha256", context.selection_record_sha256}, + {"stimulus_sha256", stimulus.utf8_sha256}, + {"model_id", invocation.model_id}, + {"model_revision", invocation.model_revision}, + {"temperature", invocation.temperature}, + {"min_p", invocation.min_p}, + {"max_tokens", invocation.max_tokens}, + {"seed_sha256", invocation.seed_sha256}, + {"request_body_sha256", invocation.request_body_sha256}, + {"adapter_id", invocation.adapter_id.empty() ? nlohmann::json(nullptr) : nlohmann::json(invocation.adapter_id)}, + {"adapter_sha256", invocation.adapter_sha256.empty() ? nlohmann::json(nullptr) : nlohmann::json(invocation.adapter_sha256)}, + {"generation_status", result.status}, + {"latency_ms", result.latency_ms}, + {"http_status", result.http_status}, + {"finish_reason", result.finish_reason}, + {"prompt_tokens", result.prompt_tokens}, + {"completion_tokens", result.completion_tokens}, + {"raw_response_sha256", result.raw_response_sha256}, + {"raw_completion_sha256", result.raw_completion_sha256}, + {"normalized_completion_sha256", result.normalized_completion_sha256}, + {"exact_completion_prior_count", result.exact_completion_prior_count}, + {"exact_completion_duplicate", result.exact_completion_duplicate}, + {"normalization", result.normalization}, + {"error_code", result.error_code}, + {"error_detail", result.error_detail}, + {"publication_allowed", publication.allowed}, + {"validator_version", publication.validator_version}, + {"denial_reason", publication.denial_reason}, + {"development_eligible", development.eligible}, + {"development_review_state", development.review_state}, + {"history_immutable", development.history_immutable}, + {"automatic_identity_mutation_allowed", development.automatic_identity_mutation_allowed}, + {"journal_sequence", chain.sequence}, + {"journal_record_sha256", chain.record_sha256} + }; +} + +ValidationFinding validate_for_publication(const GenerationEvidence& evidence) { + if (evidence.schema_version != kSchemaVersion) return invalid("schema_version", "unexpected provenance schema"); + if (evidence.generation_id.size() != 32 || + !std::all_of(evidence.generation_id.begin(), evidence.generation_id.end(), + [](unsigned char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + })) + return invalid("generation_id", "generation ID is not 128-bit lowercase hex"); + if (evidence.resident.id.empty()) return invalid("resident_missing", "resident identity is empty"); + if (evidence.resident.identity_version.empty() || + evidence.resident.identity_version == "unconfigured") + return invalid("identity_version_missing", "identity version is not configured"); + if (evidence.resident.role_prompt.empty()) return invalid("role_prompt_missing", "role prompt is empty"); + if (sha256(evidence.resident.identity_manifest) != evidence.resident.identity_manifest_sha256) + return invalid("identity_hash_mismatch", "identity manifest commitment does not match"); + if (sha256(evidence.resident.role_prompt) != evidence.resident.role_prompt_sha256) + return invalid("role_hash_mismatch", "role prompt commitment does not match"); + if (sha256(evidence.context.system_prompt) != evidence.context.system_prompt_sha256) + return invalid("system_prompt_hash_mismatch", "system prompt commitment does not match"); + if (sha256(evidence.context.memory_snapshot) != evidence.context.memory_snapshot_sha256) + return invalid("memory_hash_mismatch", "memory snapshot commitment does not match"); + if (sha256(evidence.context.shared_context) != evidence.context.shared_context_sha256) + return invalid("shared_context_hash_mismatch", "shared context commitment does not match"); + if (sha256(evidence.context.cognitive_state) != evidence.context.cognitive_state_sha256) + return invalid("cognitive_state_hash_mismatch", "cognitive state commitment does not match"); + const std::string combined = evidence.context.system_prompt + "\n--MEMORY--\n" + + evidence.context.memory_snapshot + "\n--SHARED--\n" + + evidence.context.shared_context + "\n--STATE--\n" + + evidence.context.cognitive_state; + if (sha256(combined) != evidence.context.combined_context_sha256) + return invalid("combined_context_hash_mismatch", "combined context commitment does not match"); + if (sha256(evidence.context.selection_record) != evidence.context.selection_record_sha256) + return invalid("selection_hash_mismatch", "context selection commitment does not match"); + if (evidence.stimulus.target != evidence.resident.id) + return invalid("stimulus_target_mismatch", "stimulus target does not match resident"); + if (evidence.stimulus.source.empty() || evidence.stimulus.text.empty()) + return invalid("stimulus_missing", "stimulus source or text is empty"); + if (sha256(evidence.stimulus.text) != evidence.stimulus.utf8_sha256) + return invalid("stimulus_hash_mismatch", "stimulus commitment does not match"); + if (evidence.invocation.started_at.empty() || evidence.invocation.server.empty() || + evidence.invocation.model_id.empty() || evidence.invocation.model_revision.empty() || + evidence.invocation.model_revision == "unconfigured") + return invalid("model_identity_missing", "server, model, or model revision is missing"); + if (evidence.invocation.temperature <= 0.0) + return invalid("deterministic_temperature", "temperature must be greater than zero"); + if (evidence.invocation.seed <= 0) + return invalid("seed_missing", "non-reused request seed is missing"); + if (sha256(std::to_string(evidence.invocation.seed)) != evidence.invocation.seed_sha256) + return invalid("seed_hash_mismatch", "seed commitment does not match"); + if (sha256(evidence.invocation.request_body) != evidence.invocation.request_body_sha256) + return invalid("request_hash_mismatch", "model request commitment does not match"); + try { + const auto request = nlohmann::json::parse(evidence.invocation.request_body); + if (request.value("model", "") != evidence.invocation.model_id || + request.value("seed", 0) != evidence.invocation.seed || + request.value("temperature", 0.0) != evidence.invocation.temperature || + request.value("min_p", -1.0) != evidence.invocation.min_p || + request.value("max_tokens", 0) != evidence.invocation.max_tokens) + return invalid("request_parameter_mismatch", "recorded invocation differs from request body"); + const auto& messages = request.at("messages"); + if (!messages.is_array() || messages.size() != 2 || + messages.at(0).value("role", "") != "system" || + messages.at(0).value("content", "") != evidence.context.system_prompt || + messages.at(1).value("role", "") != "user" || + messages.at(1).value("content", "") != evidence.stimulus.text) + return invalid("request_context_mismatch", "request messages differ from bound context or stimulus"); + } catch (const std::exception& exception) { + return invalid("request_parse_error", exception.what()); + } + if (evidence.result.status != "generated-unverified") + return invalid("result_state", "only a generated-unverified result can enter publication validation"); + if (evidence.result.http_status != 200) + return invalid("http_status", "model server did not return HTTP 200"); + if (evidence.result.raw_response.empty() || evidence.result.raw_completion.empty() || + evidence.result.normalized_completion.empty()) + return invalid("empty_generation", "model response or completion is empty"); + if (sha256(evidence.result.raw_response) != evidence.result.raw_response_sha256) + return invalid("raw_response_hash_mismatch", "raw response commitment does not match"); + if (sha256(evidence.result.raw_completion) != evidence.result.raw_completion_sha256) + return invalid("raw_completion_hash_mismatch", "raw completion commitment does not match"); + if (sha256(evidence.result.normalized_completion) != evidence.result.normalized_completion_sha256) + return invalid("normalized_completion_hash_mismatch", "normalized completion commitment does not match"); + return {true, "ok", "all authenticity bindings validate"}; +} + +std::string normalize_completion(const std::string& raw, std::vector& operations) { + std::string output = raw; + bool removed_framing = false; + const std::string start_token = "<|im_start|>assistant"; + if (output.rfind(start_token, 0) == 0) { + output.erase(0, start_token.size()); + if (!output.empty() && output.front() == '\n') output.erase(0, 1); + removed_framing = true; + } + const std::string end_token = "<|im_end|>"; + if (output.size() >= end_token.size() && + output.compare(output.size() - end_token.size(), end_token.size(), end_token) == 0) { + output.erase(output.size() - end_token.size()); + removed_framing = true; + } + if (removed_framing) operations.push_back("remove_terminal_chat_framing"); + const auto original_size = output.size(); + while (!output.empty() && (output.back() == '\n' || output.back() == '\r' || + output.back() == ' ' || output.back() == '\t')) { + output.pop_back(); + } + if (output.size() != original_size) operations.push_back("trim_terminal_whitespace"); + return output; +} + +ProvenanceJournal::ProvenanceJournal(std::filesystem::path root) + : root_(std::move(root)), attempts_dir_(root_ / "attempts"), + journal_path_(root_ / "journal.jsonl") { + std::error_code ec; + std::filesystem::create_directories(attempts_dir_, ec); + if (ec) throw std::runtime_error("cannot_create_provenance_directory:" + ec.message()); +#ifndef _WIN32 + ::chmod(root_.c_str(), S_IRWXU); + ::chmod(attempts_dir_.c_str(), S_IRWXU); +#endif + std::string error; + if (!load_tail(error)) throw std::runtime_error(error); +} + +bool ProvenanceJournal::load_tail(std::string& error) { + if (!std::filesystem::exists(journal_path_)) return true; + std::ifstream stream(journal_path_); + if (!stream) { + error = "cannot_read_existing_journal"; + return false; + } + std::string line; + while (std::getline(stream, line)) { + if (line.empty()) continue; + try { + const auto record = nlohmann::json::parse(line); + last_sequence_ = record.at("chain").at("sequence").get(); + last_hash_ = record.at("chain").at("record_sha256").get(); + const auto generation_id = record.at("generation_id").get(); + const auto seed_sha256 = record.at("invocation").at("seed_sha256").get(); + if (!generation_ids_.insert(generation_id).second) + throw std::runtime_error("duplicate_generation_id"); + if (!seed_hashes_.insert(seed_sha256).second) + throw std::runtime_error("reused_generation_seed"); + if (record.at("result").value("status", "") == "generated-authentic") { + const auto completion_hash = record.at("result").value( + "normalized_completion_sha256", ""); + if (is_sha256(completion_hash)) ++completion_hash_counts_[completion_hash]; + } + } catch (const std::exception& exception) { + error = std::string("invalid_existing_journal:") + exception.what(); + return false; + } + } + return true; +} + +bool ProvenanceJournal::commit(GenerationEvidence& evidence, std::string& error) { + std::lock_guard lock(mutex_); + if (generation_ids_.count(evidence.generation_id) != 0) { + error = "duplicate_generation_id"; + return false; + } + if (!evidence.invocation.seed_sha256.empty() && + seed_hashes_.count(evidence.invocation.seed_sha256) != 0) { + error = "reused_generation_seed"; + return false; + } + if (evidence.result.status == "generated-unverified") { + const auto finding = validate_for_publication(evidence); + if (finding.ok) { + evidence.result.status = "generated-authentic"; + evidence.publication.allowed = true; + evidence.publication.denial_reason.clear(); + } else { + evidence.result.status = "provenance-rejected"; + evidence.result.error_code = finding.code; + evidence.result.error_detail = finding.detail; + evidence.publication.allowed = false; + evidence.publication.denial_reason = finding.code; + } + } else if (evidence.result.status == "generation-failed") { + evidence.publication.allowed = false; + evidence.publication.denial_reason = evidence.result.error_code.empty() + ? "generation_failed" : evidence.result.error_code; + } else { + error = "invalid_commit_state:" + evidence.result.status; + return false; + } + + if (evidence.result.status == "generated-authentic") { + const auto prior = completion_hash_counts_.find( + evidence.result.normalized_completion_sha256); + evidence.result.exact_completion_prior_count = + prior == completion_hash_counts_.end() ? 0 : prior->second; + evidence.result.exact_completion_duplicate = + evidence.result.exact_completion_prior_count > 0; + } + + evidence.development.eligible = true; + evidence.development.history_immutable = true; + evidence.development.automatic_identity_mutation_allowed = false; + evidence.development.review_state = "unreviewed"; + evidence.development.outcome = evidence.result.status; + + evidence.chain.sequence = last_sequence_ + 1; + evidence.chain.previous_record_sha256 = last_hash_; + evidence.chain.record_sha256.clear(); + evidence.chain.record_sha256 = sha256(canonical_json(record_without_hash(evidence))); + const auto record = canonical_json(evidence.to_private_json()); + const auto attempt_path = attempts_dir_ / (evidence.generation_id + ".json"); + if (std::filesystem::exists(attempt_path)) { + error = "duplicate_generation_id"; + return false; + } + if (!atomic_write_private(attempt_path, record + "\n", error)) return false; + if (!append_private(journal_path_, record + "\n", error)) { + std::filesystem::remove(attempt_path); + evidence.publication.allowed = false; + evidence.publication.denial_reason = "journal_append_failed"; + return false; + } + last_sequence_ = evidence.chain.sequence; + last_hash_ = evidence.chain.record_sha256; + generation_ids_.insert(evidence.generation_id); + if (!evidence.invocation.seed_sha256.empty()) + seed_hashes_.insert(evidence.invocation.seed_sha256); + if (evidence.result.status == "generated-authentic") + ++completion_hash_counts_[evidence.result.normalized_completion_sha256]; + return true; +} + +bool ProvenanceJournal::verify(std::string& error) const { + std::lock_guard lock(mutex_); + if (!std::filesystem::exists(journal_path_)) return true; + std::ifstream stream(journal_path_); + if (!stream) { + error = "cannot_read_journal"; + return false; + } + std::uint64_t expected_sequence = 1; + std::string expected_previous = kZeroHash; + std::unordered_set generation_ids; + std::unordered_set seed_hashes; + std::unordered_map completion_hash_counts; + std::string line; + while (std::getline(stream, line)) { + if (line.empty()) continue; + try { + auto record = nlohmann::json::parse(line); + const auto sequence = record.at("chain").at("sequence").get(); + const auto previous = record.at("chain").at("previous_record_sha256").get(); + const auto stored = record.at("chain").at("record_sha256").get(); + const auto generation_id = record.at("generation_id").get(); + const auto seed_sha256 = record.at("invocation").at("seed_sha256").get(); + record["chain"]["record_sha256"] = ""; + const auto computed = sha256(canonical_json(record)); + if (sequence != expected_sequence || previous != expected_previous || stored != computed) { + error = "journal_chain_mismatch_at_sequence:" + std::to_string(expected_sequence); + return false; + } + if (!generation_ids.insert(generation_id).second) { + error = "duplicate_generation_id_at_sequence:" + std::to_string(sequence); + return false; + } + if (!seed_hashes.insert(seed_sha256).second) { + error = "reused_generation_seed_at_sequence:" + std::to_string(sequence); + return false; + } + if (record.at("result").value("status", "") == "generated-authentic") { + const auto completion_hash = record.at("result").value( + "normalized_completion_sha256", ""); + const auto prior = completion_hash_counts[completion_hash]; + if (record.at("result").value("exact_completion_prior_count", 0ULL) != prior || + record.at("result").value("exact_completion_duplicate", false) != (prior > 0)) { + error = "completion_repeat_count_mismatch_at_sequence:" + + std::to_string(sequence); + return false; + } + ++completion_hash_counts[completion_hash]; + } + expected_previous = stored; + ++expected_sequence; + } catch (const std::exception& exception) { + error = std::string("invalid_journal_record:") + exception.what(); + return false; + } + } + return true; +} + +} // namespace village::authenticity diff --git a/village/response_authenticity.hpp b/village/response_authenticity.hpp new file mode 100644 index 000000000..a403f9e68 --- /dev/null +++ b/village/response_authenticity.hpp @@ -0,0 +1,166 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace village::authenticity { + +inline constexpr const char* kSchemaVersion = "cogverse.generation-provenance.v1"; +inline constexpr const char* kValidatorVersion = "cogverse.authenticity-validator.v1"; +inline constexpr const char* kZeroHash = + "0000000000000000000000000000000000000000000000000000000000000000"; + +std::string sha256(const std::string& value); +std::string utc_now_iso8601(); +std::string random_generation_id(); +int random_seed(); +bool is_sha256(const std::string& value); +std::string canonical_json(const nlohmann::json& value); + +struct ResidentBinding { + std::string id; + std::string identity_version; + std::string identity_manifest; + std::string identity_manifest_sha256; + std::string role_prompt; + std::string role_prompt_sha256; +}; + +struct ContextBinding { + std::string system_prompt; + std::string system_prompt_sha256; + std::string memory_snapshot; + std::string memory_snapshot_sha256; + std::string shared_context; + std::string shared_context_sha256; + std::string cognitive_state; + std::string cognitive_state_sha256; + std::string combined_context_sha256; + std::string selection_record; + std::string selection_record_sha256; +}; + +struct StimulusBinding { + std::string source; + std::string target; + std::string text; + std::string utf8_sha256; + std::int64_t parent_event_id = 0; + std::int64_t parent_tic = 0; +}; + +struct InvocationEvidence { + std::string started_at; + std::string server; + std::string model_id; + std::string model_revision; + double temperature = 0.0; + double min_p = 0.0; + int max_tokens = 0; + int seed = 0; + std::string seed_sha256; + std::string request_body; + std::string request_body_sha256; + std::string adapter_id; + std::string adapter_sha256; +}; + +struct ResultEvidence { + std::string status = "attempt-created"; + std::string finished_at; + std::int64_t latency_ms = 0; + int http_status = 0; + int transport_code = 0; + std::string finish_reason; + int prompt_tokens = 0; + int completion_tokens = 0; + std::string raw_response; + std::string raw_response_sha256; + std::string raw_completion; + std::string raw_completion_sha256; + std::string normalized_completion; + std::string normalized_completion_sha256; + std::uint64_t exact_completion_prior_count = 0; + bool exact_completion_duplicate = false; + std::vector normalization; + std::string error_code; + std::string error_detail; +}; + +struct PublicationDecision { + bool allowed = false; + std::string validator_version = kValidatorVersion; + std::string denial_reason; +}; + +struct DevelopmentDisposition { + bool eligible = true; + bool history_immutable = true; + bool automatic_identity_mutation_allowed = false; + std::string review_state = "unreviewed"; + std::string outcome; +}; + +struct ChainEvidence { + std::uint64_t sequence = 0; + std::string previous_record_sha256 = kZeroHash; + std::string record_sha256; +}; + +struct GenerationEvidence { + std::string schema_version = kSchemaVersion; + std::string generation_id; + std::string created_at; + std::string correlation_id; + ResidentBinding resident; + ContextBinding context; + StimulusBinding stimulus; + InvocationEvidence invocation; + ResultEvidence result; + PublicationDecision publication; + DevelopmentDisposition development; + ChainEvidence chain; + + nlohmann::json to_private_json() const; + nlohmann::json to_public_json() const; +}; + +struct ValidationFinding { + bool ok = false; + std::string code; + std::string detail; +}; + +ValidationFinding validate_for_publication(const GenerationEvidence& evidence); +std::string normalize_completion(const std::string& raw, std::vector& operations); + +class ProvenanceJournal { +public: + explicit ProvenanceJournal(std::filesystem::path root); + + bool commit(GenerationEvidence& evidence, std::string& error); + bool verify(std::string& error) const; + const std::filesystem::path& root() const { return root_; } + +private: + bool load_tail(std::string& error); + + std::filesystem::path root_; + std::filesystem::path attempts_dir_; + std::filesystem::path journal_path_; + mutable std::mutex mutex_; + std::uint64_t last_sequence_ = 0; + std::string last_hash_ = kZeroHash; + std::unordered_set generation_ids_; + std::unordered_set seed_hashes_; + std::unordered_map completion_hash_counts_; +}; + +} // namespace village::authenticity diff --git a/village/response_authenticity_test.cpp b/village/response_authenticity_test.cpp new file mode 100644 index 000000000..ba0cfdb34 --- /dev/null +++ b/village/response_authenticity_test.cpp @@ -0,0 +1,283 @@ +#include "response_authenticity.hpp" + +#include +#include +#include +#include + +using village::authenticity::GenerationEvidence; +using village::authenticity::ProvenanceJournal; +using village::authenticity::canonical_json; +using village::authenticity::normalize_completion; +using village::authenticity::sha256; +using village::authenticity::validate_for_publication; + +namespace { + +int failures = 0; +int checks = 0; + +void check(bool condition, const std::string& name) { + ++checks; + if (!condition) { + ++failures; + std::cerr << "FAIL: " << name << '\n'; + } +} + +GenerationEvidence valid_evidence(const std::string& resident, + const std::string& role, + int seed) { + GenerationEvidence evidence; + evidence.generation_id = sha256(resident + std::to_string(seed)).substr(0, 32); + evidence.created_at = "2026-08-31T12:00:00.000Z"; + evidence.correlation_id = "corr-" + resident; + + evidence.resident.id = resident; + evidence.resident.identity_version = "elizaos-cpp:test-revision"; + evidence.resident.role_prompt = role; + evidence.resident.role_prompt_sha256 = sha256(role); + evidence.resident.identity_manifest = canonical_json({ + {"resident", resident}, + {"identity_version", evidence.resident.identity_version}, + {"role_prompt_sha256", evidence.resident.role_prompt_sha256} + }); + evidence.resident.identity_manifest_sha256 = + sha256(evidence.resident.identity_manifest); + + evidence.context.memory_snapshot = "private memory for " + resident; + evidence.context.memory_snapshot_sha256 = + sha256(evidence.context.memory_snapshot); + evidence.context.shared_context = "shared event context"; + evidence.context.shared_context_sha256 = + sha256(evidence.context.shared_context); + evidence.context.cognitive_state = canonical_json({ + {"resident", resident}, {"sti", 201.0}, {"gear", "test"} + }); + evidence.context.cognitive_state_sha256 = + sha256(evidence.context.cognitive_state); + evidence.context.selection_record = canonical_json({ + {"policy", "test-private-memory-v1"}, {"resident", resident} + }); + evidence.context.selection_record_sha256 = + sha256(evidence.context.selection_record); + evidence.context.system_prompt = role + "\n" + evidence.context.memory_snapshot; + evidence.context.system_prompt_sha256 = sha256(evidence.context.system_prompt); + evidence.context.combined_context_sha256 = sha256( + evidence.context.system_prompt + "\n--MEMORY--\n" + + evidence.context.memory_snapshot + "\n--SHARED--\n" + + evidence.context.shared_context + "\n--STATE--\n" + + evidence.context.cognitive_state); + + evidence.stimulus.source = "test.operator"; + evidence.stimulus.target = resident; + evidence.stimulus.text = "What do you notice right now?"; + evidence.stimulus.utf8_sha256 = sha256(evidence.stimulus.text); + evidence.stimulus.parent_event_id = 100; + evidence.stimulus.parent_tic = 200; + + evidence.invocation.started_at = "2026-08-31T12:00:00.001Z"; + evidence.invocation.server = "http://127.0.0.1:2242/v1/chat/completions"; + evidence.invocation.model_id = "qwen2.5-14b-instruct-awq"; + evidence.invocation.model_revision = "sha256:model-test"; + evidence.invocation.temperature = 0.7; + evidence.invocation.min_p = 0.1; + evidence.invocation.max_tokens = 512; + evidence.invocation.seed = seed; + evidence.invocation.seed_sha256 = sha256(std::to_string(seed)); + evidence.invocation.request_body = canonical_json({ + {"model", evidence.invocation.model_id}, + {"messages", { + {{"role", "system"}, {"content", evidence.context.system_prompt}}, + {{"role", "user"}, {"content", evidence.stimulus.text}} + }}, + {"temperature", evidence.invocation.temperature}, + {"min_p", evidence.invocation.min_p}, + {"max_tokens", evidence.invocation.max_tokens}, + {"seed", evidence.invocation.seed} + }); + evidence.invocation.request_body_sha256 = + sha256(evidence.invocation.request_body); + + evidence.result.status = "generated-unverified"; + evidence.result.finished_at = "2026-08-31T12:00:00.123Z"; + evidence.result.latency_ms = 122; + evidence.result.http_status = 200; + evidence.result.transport_code = 0; + evidence.result.finish_reason = "stop"; + evidence.result.prompt_tokens = 100; + evidence.result.completion_tokens = 12; + evidence.result.raw_response = "{\"choices\":[{\"message\":{\"content\":\"I am uncertain.\"}}]}"; + evidence.result.raw_response_sha256 = sha256(evidence.result.raw_response); + evidence.result.raw_completion = "I am uncertain."; + evidence.result.raw_completion_sha256 = sha256(evidence.result.raw_completion); + evidence.result.normalized_completion = evidence.result.raw_completion; + evidence.result.normalized_completion_sha256 = + sha256(evidence.result.normalized_completion); + return evidence; +} + +std::filesystem::path fresh_directory(const std::string& name) { + const auto path = std::filesystem::temp_directory_path() / + ("cogverse-authenticity-" + name); + std::filesystem::remove_all(path); + return path; +} + +void test_valid_and_distinct_residents() { + auto echo = valid_evidence("echo", "You are Echo, exploratory and recursive.", 101); + auto aion = valid_evidence("aion", "You are Aion, precise about time.", 102); + check(validate_for_publication(echo).ok, "valid Echo evidence accepted"); + check(validate_for_publication(aion).ok, "valid Aion evidence accepted"); + check(echo.resident.role_prompt_sha256 != aion.resident.role_prompt_sha256, + "resident role commitments are distinct"); + check(echo.context.system_prompt_sha256 != aion.context.system_prompt_sha256, + "resident system prompts are distinct"); + check(echo.invocation.request_body_sha256 != aion.invocation.request_body_sha256, + "model requests are resident-specific"); + check(echo.generation_id != aion.generation_id, + "generation IDs are distinct"); + + auto changed_context = echo; + changed_context.context.memory_snapshot = "new private memory for echo"; + changed_context.context.memory_snapshot_sha256 = + sha256(changed_context.context.memory_snapshot); + changed_context.context.system_prompt = + changed_context.resident.role_prompt + "\n" + changed_context.context.memory_snapshot; + changed_context.context.system_prompt_sha256 = + sha256(changed_context.context.system_prompt); + changed_context.context.combined_context_sha256 = sha256( + changed_context.context.system_prompt + "\n--MEMORY--\n" + + changed_context.context.memory_snapshot + "\n--SHARED--\n" + + changed_context.context.shared_context + "\n--STATE--\n" + + changed_context.context.cognitive_state); + auto request = nlohmann::json::parse(changed_context.invocation.request_body); + request["messages"][0]["content"] = changed_context.context.system_prompt; + changed_context.invocation.request_body = canonical_json(request); + changed_context.invocation.request_body_sha256 = + sha256(changed_context.invocation.request_body); + check(validate_for_publication(changed_context).ok, + "changed private context remains a valid bound request"); + check(changed_context.invocation.request_body_sha256 != + echo.invocation.request_body_sha256, + "changed private context changes the exact model request"); +} + +void test_fail_closed_validation() { + auto bad_role = valid_evidence("echo", "Echo role", 201); + bad_role.resident.role_prompt_sha256 = sha256("counterfeit role"); + check(!validate_for_publication(bad_role).ok, "role hash mismatch rejected"); + + auto deterministic = valid_evidence("echo", "Echo role", 202); + deterministic.invocation.temperature = 0.0; + check(!validate_for_publication(deterministic).ok, + "deterministic temperature rejected"); + + auto missing_revision = valid_evidence("echo", "Echo role", 203); + missing_revision.invocation.model_revision = "unconfigured"; + check(!validate_for_publication(missing_revision).ok, + "unconfigured model revision rejected"); + + auto wrong_context = valid_evidence("echo", "Echo role", 204); + auto request = nlohmann::json::parse(wrong_context.invocation.request_body); + request["messages"][0]["content"] = "shared counterfeit prompt"; + wrong_context.invocation.request_body = request.dump(); + wrong_context.invocation.request_body_sha256 = + sha256(wrong_context.invocation.request_body); + check(!validate_for_publication(wrong_context).ok, + "request/context mismatch rejected"); + + auto empty_stimulus = valid_evidence("echo", "Echo role", 205); + empty_stimulus.stimulus.text.clear(); + empty_stimulus.stimulus.utf8_sha256 = sha256(""); + check(!validate_for_publication(empty_stimulus).ok, + "empty stimulus rejected"); +} + +void test_normalization_preserves_imperfections() { + std::vector operations; + const std::string raw = + "<|im_start|>assistant\nI may be wrong <|im_start|> inside.<|im_end|>"; + const auto normalized = normalize_completion(raw, operations); + check(normalized == "I may be wrong <|im_start|> inside.", + "only terminal transport framing removed"); + check(normalized.find("may be wrong") != std::string::npos, + "uncertainty remains intact"); + check(operations.size() == 1 && + operations.front() == "remove_terminal_chat_framing", + "normalization is explicitly recorded"); +} + +void test_journal_and_entropy_guards() { + const auto path = fresh_directory("journal"); + ProvenanceJournal journal(path); + auto success = valid_evidence("echo", "Echo role", 301); + std::string error; + check(journal.commit(success, error), "valid generation committed"); + check(success.publication.allowed, "valid generation publication allowed"); + check(success.result.status == "generated-authentic", + "valid generation promoted to generated-authentic"); + check(success.development.eligible, "authentic generation enters development evidence"); + check(success.development.history_immutable, + "development evidence cannot rewrite historical output"); + check(!success.development.automatic_identity_mutation_allowed, + "development evidence cannot auto-mutate identity"); + check(journal.verify(error), "journal chain verifies"); + + auto duplicate_id = valid_evidence("aion", "Aion role", 302); + duplicate_id.generation_id = success.generation_id; + check(!journal.commit(duplicate_id, error), "duplicate generation ID rejected"); + + auto reused_seed = valid_evidence("aion", "Aion role", 301); + check(!journal.commit(reused_seed, error), "reused seed rejected"); + + auto failed = valid_evidence("aion", "Aion role", 303); + failed.result.status = "generation-failed"; + failed.result.error_code = "transport_error"; + failed.result.error_detail = "connection reset"; + failed.result.raw_response.clear(); + failed.result.raw_response_sha256 = sha256(""); + failed.result.raw_completion.clear(); + failed.result.raw_completion_sha256.clear(); + failed.result.normalized_completion.clear(); + failed.result.normalized_completion_sha256.clear(); + check(journal.commit(failed, error), "failed generation preserved in journal"); + check(!failed.publication.allowed, "failed generation cannot be speech"); + check(failed.development.eligible, "failed generation remains development evidence"); + check(failed.development.outcome == "generation-failed", + "failure outcome remains explicit"); + + auto repeated_completion = valid_evidence("aion", "Aion role", 304); + check(journal.commit(repeated_completion, error), + "genuine repeated completion remains journaled"); + check(repeated_completion.publication.allowed, + "repeated text from a distinct real invocation remains authentic speech"); + check(repeated_completion.result.exact_completion_duplicate && + repeated_completion.result.exact_completion_prior_count == 1, + "exact repeated completion is explicitly flagged for development review"); + + const auto journal_path = path / "journal.jsonl"; + std::ifstream source(journal_path); + std::string content((std::istreambuf_iterator(source)), + std::istreambuf_iterator()); + const auto position = content.find("connection reset"); + check(position != std::string::npos, "failure detail stored as evidence"); + if (position != std::string::npos) content[position] = 'X'; + std::ofstream tampered(journal_path, std::ios::trunc); + tampered << content; + tampered.close(); + check(!journal.verify(error), "journal tampering detected"); + std::filesystem::remove_all(path); +} + +} // namespace + +int main() { + test_valid_and_distinct_residents(); + test_fail_closed_validation(); + test_normalization_preserves_imperfections(); + test_journal_and_entropy_guards(); + std::cout << "response_authenticity_test checks=" << checks + << " failures=" << failures << '\n'; + return failures == 0 ? 0 : 1; +} diff --git a/village/response_development.cpp b/village/response_development.cpp new file mode 100644 index 000000000..5a675a9e7 --- /dev/null +++ b/village/response_development.cpp @@ -0,0 +1,372 @@ +#include "response_development.hpp" + +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif + +namespace village::development { +namespace { + +const std::unordered_set kMetricNames = { + "attribution_integrity", "contextual_relevance", "contradiction", + "repetition", "uncertainty_calibration", "action_validity", "role_coherence" +}; + +const std::unordered_set kProposalTargets = { + "role_prompt", "memory_selection", "sampling", "adapter", "evaluation_policy" +}; + +const std::unordered_set kRequiredTests = { + "provenance-completeness", "resident-isolation", "context-sensitivity", + "historical-immutability", "failure-visibility", "rollback-verification" +}; + +const std::map> kParametersByTarget = { + {"role_prompt", {"role_prompt.artifact"}}, + {"memory_selection", {"memory.policy_artifact", "memory.window_entries"}}, + {"sampling", {"sampling.temperature", "sampling.min_p", "sampling.max_tokens"}}, + {"adapter", {"adapter.artifact"}}, + {"evaluation_policy", {"evaluation_policy.artifact"}} +}; + +bool append_private(const std::filesystem::path& path, const std::string& content, + std::string& error) { +#ifdef _WIN32 + std::ofstream stream(path, std::ios::binary | std::ios::app); + if (!stream) { error = "cannot_open_development_journal"; return false; } + stream.write(content.data(), static_cast(content.size())); + stream.flush(); + if (!stream) { error = "cannot_append_development_journal"; return false; } + return true; +#else + const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); + if (fd < 0) { error = "cannot_open_development_journal"; return false; } + std::size_t written = 0; + while (written < content.size()) { + const auto count = ::write(fd, content.data() + written, content.size() - written); + if (count <= 0) { + ::close(fd); + error = "cannot_append_development_journal"; + return false; + } + written += static_cast(count); + } + if (::fsync(fd) != 0) { + ::close(fd); + error = "cannot_fsync_development_journal"; + return false; + } + ::close(fd); + return true; +#endif +} + +bool valid_hex_id(const std::string& value, std::size_t size) { + return value.size() == size && + std::all_of(value.begin(), value.end(), [](unsigned char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); +} + +} // namespace + +nlohmann::json EvaluatorFinding::to_json() const { + return { + {"schema_version", "cogverse.evaluator-finding.v1"}, + {"finding_id", finding_id}, {"created_at", created_at}, + {"generation_id", generation_id}, + {"generation_record_sha256", generation_record_sha256}, + {"reviewer_id", reviewer_id}, {"reviewer_kind", reviewer_kind}, + {"metrics", metrics}, {"narrative", narrative}, + {"narrative_sha256", narrative_sha256}, {"outcome", outcome}, + {"chain", { + {"sequence", chain.sequence}, + {"previous_record_sha256", chain.previous_record_sha256}, + {"record_sha256", chain.record_sha256} + }} + }; +} + +nlohmann::json DevelopmentProposal::to_json() const { + nlohmann::json serialized_deltas = nlohmann::json::array(); + for (const auto& delta : deltas) serialized_deltas.push_back(delta.to_json()); + return { + {"schema_version", "cogverse.development-proposal.v1"}, + {"proposal_id", proposal_id}, {"created_at", created_at}, + {"proposer_id", proposer_id}, {"target", target}, + {"finding_record_sha256s", finding_record_sha256s}, + {"deltas", serialized_deltas}, + {"maximum_change_fraction", maximum_change_fraction}, + {"required_tests", required_tests}, + {"rollback_artifact_sha256", rollback_artifact_sha256}, + {"status", status}, + {"chain", { + {"sequence", chain.sequence}, + {"previous_record_sha256", chain.previous_record_sha256}, + {"record_sha256", chain.record_sha256} + }} + }; +} + +nlohmann::json DevelopmentProposal::ParameterDelta::to_json() const { + nlohmann::json record = { + {"parameter", parameter}, {"operation", operation}, + {"before_artifact_sha256", before_artifact_sha256.empty() + ? nlohmann::json(nullptr) : nlohmann::json(before_artifact_sha256)}, + {"after_artifact_sha256", after_artifact_sha256.empty() + ? nlohmann::json(nullptr) : nlohmann::json(after_artifact_sha256)}, + {"has_numeric_values", has_numeric_values} + }; + record["before_number"] = has_numeric_values ? nlohmann::json(before_number) + : nlohmann::json(nullptr); + record["after_number"] = has_numeric_values ? nlohmann::json(after_number) + : nlohmann::json(nullptr); + return record; +} + +nlohmann::json PromotionDecision::to_json() const { + return { + {"schema_version", "cogverse.promotion-decision.v1"}, + {"decision_id", decision_id}, {"created_at", created_at}, + {"proposal_id", proposal_id}, + {"proposal_record_sha256", proposal_record_sha256}, + {"approved_by", approved_by}, {"tests_verified", tests_verified}, + {"rollback_artifact_sha256", rollback_artifact_sha256}, + {"decision", decision}, {"reason", reason}, + {"chain", { + {"sequence", chain.sequence}, + {"previous_record_sha256", chain.previous_record_sha256}, + {"record_sha256", chain.record_sha256} + }} + }; +} + +DevelopmentLedger::DevelopmentLedger(std::filesystem::path root, + std::filesystem::path generation_evidence_root) + : root_(std::move(root)), + generation_evidence_root_(std::move(generation_evidence_root)), + findings_{root_ / "evaluator-findings.jsonl"}, + proposals_{root_ / "development-proposals.jsonl"}, + promotions_{root_ / "promotion-decisions.jsonl"} { + std::error_code ec; + std::filesystem::create_directories(root_, ec); + if (ec) throw std::runtime_error("cannot_create_development_directory:" + ec.message()); +#ifndef _WIN32 + ::chmod(root_.c_str(), S_IRWXU); +#endif + std::string error; + if (!load_stream(findings_, "finding_id", error) || + !load_stream(proposals_, "proposal_id", error) || + !load_stream(promotions_, "decision_id", error)) { + throw std::runtime_error(error); + } +} + +bool DevelopmentLedger::load_stream(StreamState& stream, const std::string& id_field, + std::string& error) { + if (!std::filesystem::exists(stream.path)) return true; + std::ifstream input(stream.path); + if (!input) { error = "cannot_read_development_journal"; return false; } + std::string line; + while (std::getline(input, line)) { + if (line.empty()) continue; + try { + const auto record = nlohmann::json::parse(line); + const auto id = record.at(id_field).get(); + const auto hash = record.at("chain").at("record_sha256").get(); + if (!stream.ids.insert(id).second || !stream.record_hashes.insert(hash).second) + throw std::runtime_error("duplicate_development_record"); + stream.last_sequence = record.at("chain").at("sequence").get(); + stream.last_hash = hash; + } catch (const std::exception& exception) { + error = std::string("invalid_development_journal:") + exception.what(); + return false; + } + } + return true; +} + +bool DevelopmentLedger::append_stream(StreamState& stream, const std::string& id_field, + nlohmann::json record, + authenticity::ChainEvidence& chain, + std::string& error) { + const auto id = record.at(id_field).get(); + if (stream.ids.count(id) != 0) { error = "duplicate_development_id"; return false; } + chain.sequence = stream.last_sequence + 1; + chain.previous_record_sha256 = stream.last_hash; + chain.record_sha256.clear(); + record["chain"] = { + {"sequence", chain.sequence}, + {"previous_record_sha256", chain.previous_record_sha256}, + {"record_sha256", ""} + }; + chain.record_sha256 = authenticity::sha256(authenticity::canonical_json(record)); + record["chain"]["record_sha256"] = chain.record_sha256; + if (!append_private(stream.path, authenticity::canonical_json(record) + "\n", error)) + return false; + stream.last_sequence = chain.sequence; + stream.last_hash = chain.record_sha256; + stream.ids.insert(id); + stream.record_hashes.insert(chain.record_sha256); + return true; +} + +bool DevelopmentLedger::verify_generation_reference(const EvaluatorFinding& finding, + std::string& error) const { + const auto path = generation_evidence_root_ / "attempts" / + (finding.generation_id + ".json"); + std::ifstream input(path); + if (!input) { error = "generation_evidence_not_found"; return false; } + try { + nlohmann::json record; + input >> record; + if (record.at("generation_id").get() != finding.generation_id || + record.at("chain").at("record_sha256").get() != + finding.generation_record_sha256) { + error = "generation_evidence_reference_mismatch"; + return false; + } + } catch (const std::exception& exception) { + error = std::string("invalid_generation_evidence:") + exception.what(); + return false; + } + return true; +} + +bool DevelopmentLedger::append_finding(EvaluatorFinding& finding, std::string& error) { + std::lock_guard lock(mutex_); + if (!valid_hex_id(finding.finding_id, 32) || finding.created_at.empty() || + finding.reviewer_id.empty() || finding.reviewer_kind.empty() || + finding.outcome.empty()) { + error = "invalid_evaluator_finding_identity"; + return false; + } + if (authenticity::sha256(finding.narrative) != finding.narrative_sha256) { + error = "evaluator_narrative_hash_mismatch"; + return false; + } + for (const auto& [name, value] : finding.metrics) { + if (kMetricNames.count(name) == 0 || value < 0.0 || value > 1.0) { + error = "invalid_evaluator_metric"; + return false; + } + } + if (!verify_generation_reference(finding, error)) return false; + return append_stream(findings_, "finding_id", finding.to_json(), finding.chain, error); +} + +bool DevelopmentLedger::append_proposal(DevelopmentProposal& proposal, std::string& error) { + std::lock_guard lock(mutex_); + if (!valid_hex_id(proposal.proposal_id, 32) || proposal.created_at.empty() || + proposal.proposer_id.empty() || kProposalTargets.count(proposal.target) == 0 || + proposal.status != "proposed" || proposal.finding_record_sha256s.empty() || + proposal.deltas.empty() || proposal.required_tests.empty() || + !authenticity::is_sha256(proposal.rollback_artifact_sha256) || + proposal.maximum_change_fraction <= 0.0 || proposal.maximum_change_fraction > 0.2) { + error = "invalid_or_unbounded_development_proposal"; + return false; + } + for (const auto& test : proposal.required_tests) { + if (kRequiredTests.count(test) == 0) { + error = "unknown_required_test"; + return false; + } + } + for (const auto& finding_hash : proposal.finding_record_sha256s) { + if (findings_.record_hashes.count(finding_hash) == 0) { + error = "proposal_references_unreviewed_evidence"; + return false; + } + } + const auto& allowed_parameters = kParametersByTarget.at(proposal.target); + for (const auto& delta : proposal.deltas) { + if (allowed_parameters.count(delta.parameter) == 0) { + error = "forbidden_or_unknown_parameter"; + return false; + } + if (delta.has_numeric_values) { + const bool numeric_parameter = + delta.parameter.rfind("sampling.", 0) == 0 || + delta.parameter == "memory.window_entries"; + if (delta.operation != "set-number" || !numeric_parameter) { + error = "invalid_numeric_delta"; + return false; + } + } else if (delta.operation != "replace-artifact" || + !authenticity::is_sha256(delta.before_artifact_sha256) || + !authenticity::is_sha256(delta.after_artifact_sha256)) { + error = "invalid_artifact_delta"; + return false; + } + } + return append_stream(proposals_, "proposal_id", proposal.to_json(), proposal.chain, error); +} + +bool DevelopmentLedger::append_promotion(PromotionDecision& decision, std::string& error) { + std::lock_guard lock(mutex_); + if (!valid_hex_id(decision.decision_id, 32) || decision.created_at.empty() || + decision.proposal_id.empty() || decision.approved_by.empty() || + (decision.decision != "promoted" && decision.decision != "rejected") || + proposals_.record_hashes.count(decision.proposal_record_sha256) == 0) { + error = "invalid_promotion_decision"; + return false; + } + if (decision.decision == "promoted" && + (!decision.tests_verified || + !authenticity::is_sha256(decision.rollback_artifact_sha256))) { + error = "promotion_gate_not_satisfied"; + return false; + } + return append_stream(promotions_, "decision_id", decision.to_json(), decision.chain, error); +} + +bool DevelopmentLedger::verify_stream(const StreamState& stream, + const std::string& id_field, + std::string& error) const { + if (!std::filesystem::exists(stream.path)) return true; + std::ifstream input(stream.path); + if (!input) { error = "cannot_verify_development_journal"; return false; } + std::uint64_t expected_sequence = 1; + std::string expected_previous = authenticity::kZeroHash; + std::unordered_set ids; + std::string line; + while (std::getline(input, line)) { + if (line.empty()) continue; + try { + auto record = nlohmann::json::parse(line); + const auto id = record.at(id_field).get(); + const auto sequence = record.at("chain").at("sequence").get(); + const auto previous = record.at("chain").at("previous_record_sha256").get(); + const auto stored = record.at("chain").at("record_sha256").get(); + record["chain"]["record_sha256"] = ""; + if (!ids.insert(id).second || sequence != expected_sequence || + previous != expected_previous || + authenticity::sha256(authenticity::canonical_json(record)) != stored) { + error = "development_chain_mismatch_at_sequence:" + + std::to_string(expected_sequence); + return false; + } + expected_previous = stored; + ++expected_sequence; + } catch (const std::exception& exception) { + error = std::string("invalid_development_record:") + exception.what(); + return false; + } + } + return true; +} + +bool DevelopmentLedger::verify(std::string& error) const { + std::lock_guard lock(mutex_); + return verify_stream(findings_, "finding_id", error) && + verify_stream(proposals_, "proposal_id", error) && + verify_stream(promotions_, "decision_id", error); +} + +} // namespace village::development diff --git a/village/response_development.hpp b/village/response_development.hpp new file mode 100644 index 000000000..84b92c03d --- /dev/null +++ b/village/response_development.hpp @@ -0,0 +1,114 @@ +#pragma once + +#include "response_authenticity.hpp" + +#include +#include +#include +#include +#include +#include + +#include + +namespace village::development { + +struct EvaluatorFinding { + std::string finding_id; + std::string created_at; + std::string generation_id; + std::string generation_record_sha256; + std::string reviewer_id; + std::string reviewer_kind; + std::map metrics; + std::string narrative; + std::string narrative_sha256; + std::string outcome; + authenticity::ChainEvidence chain; + + nlohmann::json to_json() const; +}; + +struct DevelopmentProposal { + struct ParameterDelta { + std::string parameter; + std::string operation; + std::string before_artifact_sha256; + std::string after_artifact_sha256; + double before_number = 0.0; + double after_number = 0.0; + bool has_numeric_values = false; + + nlohmann::json to_json() const; + }; + + std::string proposal_id; + std::string created_at; + std::string proposer_id; + std::string target; + std::vector finding_record_sha256s; + std::vector deltas; + double maximum_change_fraction = 0.0; + std::vector required_tests; + std::string rollback_artifact_sha256; + std::string status = "proposed"; + authenticity::ChainEvidence chain; + + nlohmann::json to_json() const; +}; + +struct PromotionDecision { + std::string decision_id; + std::string created_at; + std::string proposal_id; + std::string proposal_record_sha256; + std::string approved_by; + bool tests_verified = false; + std::string rollback_artifact_sha256; + std::string decision; + std::string reason; + authenticity::ChainEvidence chain; + + nlohmann::json to_json() const; +}; + +class DevelopmentLedger { +public: + DevelopmentLedger(std::filesystem::path root, + std::filesystem::path generation_evidence_root); + + bool append_finding(EvaluatorFinding& finding, std::string& error); + bool append_proposal(DevelopmentProposal& proposal, std::string& error); + bool append_promotion(PromotionDecision& decision, std::string& error); + bool verify(std::string& error) const; + +private: + struct StreamState { + explicit StreamState(std::filesystem::path value) : path(std::move(value)) {} + + std::filesystem::path path; + std::uint64_t last_sequence = 0; + std::string last_hash = authenticity::kZeroHash; + std::unordered_set ids; + std::unordered_set record_hashes; + }; + + bool load_stream(StreamState& stream, const std::string& id_field, + std::string& error); + bool append_stream(StreamState& stream, const std::string& id_field, + nlohmann::json record, authenticity::ChainEvidence& chain, + std::string& error); + bool verify_stream(const StreamState& stream, const std::string& id_field, + std::string& error) const; + bool verify_generation_reference(const EvaluatorFinding& finding, + std::string& error) const; + + std::filesystem::path root_; + std::filesystem::path generation_evidence_root_; + mutable std::mutex mutex_; + StreamState findings_; + StreamState proposals_; + StreamState promotions_; +}; + +} // namespace village::development diff --git a/village/response_development_test.cpp b/village/response_development_test.cpp new file mode 100644 index 000000000..7233214f0 --- /dev/null +++ b/village/response_development_test.cpp @@ -0,0 +1,181 @@ +#include "response_development.hpp" + +#include +#include +#include + +using namespace village; + +namespace { +int failures = 0; +int checks = 0; +void check(bool condition, const std::string& name) { + ++checks; + if (!condition) { ++failures; std::cerr << "FAIL: " << name << '\n'; } +} + +authenticity::GenerationEvidence committed_generation( + authenticity::ProvenanceJournal& journal) { + authenticity::GenerationEvidence evidence; + evidence.generation_id = authenticity::sha256("generation").substr(0, 32); + evidence.created_at = authenticity::utc_now_iso8601(); + evidence.resident.id = "echo"; + evidence.resident.identity_version = "test-identity"; + evidence.resident.role_prompt = "You are Echo."; + evidence.resident.role_prompt_sha256 = authenticity::sha256(evidence.resident.role_prompt); + evidence.resident.identity_manifest = "{\"resident\":\"echo\"}"; + evidence.resident.identity_manifest_sha256 = authenticity::sha256(evidence.resident.identity_manifest); + evidence.context.system_prompt = "You are Echo.\nMemory."; + evidence.context.system_prompt_sha256 = authenticity::sha256(evidence.context.system_prompt); + evidence.context.memory_snapshot = "Memory."; + evidence.context.memory_snapshot_sha256 = authenticity::sha256(evidence.context.memory_snapshot); + evidence.context.shared_context = ""; + evidence.context.shared_context_sha256 = authenticity::sha256(""); + evidence.context.cognitive_state = "{\"sti\":200}"; + evidence.context.cognitive_state_sha256 = authenticity::sha256(evidence.context.cognitive_state); + evidence.context.selection_record = "{\"policy\":\"test\"}"; + evidence.context.selection_record_sha256 = authenticity::sha256(evidence.context.selection_record); + evidence.context.combined_context_sha256 = authenticity::sha256( + evidence.context.system_prompt + "\n--MEMORY--\n" + evidence.context.memory_snapshot + + "\n--SHARED--\n" + evidence.context.shared_context + "\n--STATE--\n" + + evidence.context.cognitive_state); + evidence.stimulus.source = "test"; + evidence.stimulus.target = "echo"; + evidence.stimulus.text = "What do you notice?"; + evidence.stimulus.utf8_sha256 = authenticity::sha256(evidence.stimulus.text); + evidence.invocation.started_at = authenticity::utc_now_iso8601(); + evidence.invocation.server = "local"; + evidence.invocation.model_id = "test-model"; + evidence.invocation.model_revision = "test-revision"; + evidence.invocation.temperature = 0.7; + evidence.invocation.min_p = 0.05; + evidence.invocation.max_tokens = 32; + evidence.invocation.seed = 77; + evidence.invocation.seed_sha256 = authenticity::sha256("77"); + evidence.invocation.request_body = authenticity::canonical_json({ + {"model", "test-model"}, + {"messages", { + {{"role", "system"}, {"content", evidence.context.system_prompt}}, + {{"role", "user"}, {"content", evidence.stimulus.text}} + }}, + {"temperature", 0.7}, {"min_p", 0.05}, {"max_tokens", 32}, {"seed", 77} + }); + evidence.invocation.request_body_sha256 = authenticity::sha256(evidence.invocation.request_body); + evidence.result.status = "generated-unverified"; + evidence.result.finished_at = authenticity::utc_now_iso8601(); + evidence.result.latency_ms = 12; + evidence.result.http_status = 200; + evidence.result.raw_response = "{\"content\":\"I may be wrong.\"}"; + evidence.result.raw_response_sha256 = authenticity::sha256(evidence.result.raw_response); + evidence.result.raw_completion = "I may be wrong."; + evidence.result.raw_completion_sha256 = authenticity::sha256(evidence.result.raw_completion); + evidence.result.normalized_completion = evidence.result.raw_completion; + evidence.result.normalized_completion_sha256 = authenticity::sha256(evidence.result.normalized_completion); + std::string error; + check(journal.commit(evidence, error), "generation evidence committed"); + return evidence; +} +} + +int main() { + const auto root = std::filesystem::temp_directory_path() / "cogverse-development-test"; + std::filesystem::remove_all(root); + authenticity::ProvenanceJournal provenance(root / "generation"); + auto generation = committed_generation(provenance); + const auto attempt = root / "generation" / "attempts" / (generation.generation_id + ".json"); + const auto before = authenticity::sha256([&]() { + std::ifstream input(attempt); + return std::string((std::istreambuf_iterator(input)), {}); + }()); + + development::DevelopmentLedger ledger(root / "development", root / "generation"); + development::EvaluatorFinding finding; + finding.finding_id = authenticity::sha256("finding").substr(0, 32); + finding.created_at = authenticity::utc_now_iso8601(); + finding.generation_id = generation.generation_id; + finding.generation_record_sha256 = generation.chain.record_sha256; + finding.reviewer_id = "human:dan"; + finding.reviewer_kind = "human"; + finding.metrics = {{"role_coherence", 0.7}, {"uncertainty_calibration", 0.8}}; + finding.narrative = "The uncertainty is visible and should remain in the historical output."; + finding.narrative_sha256 = authenticity::sha256(finding.narrative); + finding.outcome = "reviewed-with-imperfection"; + std::string error; + check(ledger.append_finding(finding, error), "evaluator finding appended"); + + development::EvaluatorFinding bad_reference = finding; + bad_reference.finding_id = authenticity::sha256("bad-finding").substr(0, 32); + bad_reference.generation_record_sha256 = std::string(64, 'f'); + check(!ledger.append_finding(bad_reference, error), "invalid generation reference rejected"); + + development::DevelopmentProposal unbounded; + unbounded.proposal_id = authenticity::sha256("unbounded").substr(0, 32); + unbounded.created_at = authenticity::utc_now_iso8601(); + unbounded.proposer_id = "resident:echo"; + unbounded.target = "role_prompt"; + unbounded.finding_record_sha256s = {finding.chain.record_sha256}; + unbounded.deltas = {{ + "role_prompt.artifact", "replace-artifact", + authenticity::sha256("role-before"), authenticity::sha256("role-after"), + 0.0, 0.0, false + }}; + unbounded.maximum_change_fraction = 0.3; + unbounded.required_tests = {"resident-isolation", "historical-immutability"}; + unbounded.rollback_artifact_sha256 = authenticity::sha256("rollback-artifact"); + check(!ledger.append_proposal(unbounded, error), "unbounded proposal rejected"); + + development::DevelopmentProposal unreviewed = unbounded; + unreviewed.proposal_id = authenticity::sha256("unreviewed").substr(0, 32); + unreviewed.maximum_change_fraction = 0.1; + unreviewed.finding_record_sha256s = {std::string(64, 'e')}; + check(!ledger.append_proposal(unreviewed, error), "unreviewed evidence rejected"); + + development::DevelopmentProposal replacement_speech = unbounded; + replacement_speech.proposal_id = authenticity::sha256("replacement-speech").substr(0, 32); + replacement_speech.maximum_change_fraction = 0.1; + replacement_speech.deltas = {{ + "replacement_speech", "replace-artifact", + authenticity::sha256("before"), authenticity::sha256("I am a fabricated answer."), + 0.0, 0.0, false + }}; + check(!ledger.append_proposal(replacement_speech, error), + "replacement resident speech is structurally rejected"); + + development::DevelopmentProposal proposal = unbounded; + proposal.proposal_id = authenticity::sha256("bounded").substr(0, 32); + proposal.maximum_change_fraction = 0.1; + check(ledger.append_proposal(proposal, error), "bounded reviewed proposal appended"); + const auto proposal_json = proposal.to_json().dump(); + check(proposal_json.find("change_description") == std::string::npos, + "proposal schema contains no free-text change description"); + check(proposal_json.find("rollback_plan") == std::string::npos, + "proposal schema contains no free-text rollback plan"); + + development::PromotionDecision blocked; + blocked.decision_id = authenticity::sha256("blocked").substr(0, 32); + blocked.created_at = authenticity::utc_now_iso8601(); + blocked.proposal_id = proposal.proposal_id; + blocked.proposal_record_sha256 = proposal.chain.record_sha256; + blocked.approved_by = "human:dan"; + blocked.decision = "promoted"; + blocked.tests_verified = false; + check(!ledger.append_promotion(blocked, error), "promotion without tests rejected"); + + development::PromotionDecision promoted = blocked; + promoted.decision_id = authenticity::sha256("promoted").substr(0, 32); + promoted.tests_verified = true; + promoted.rollback_artifact_sha256 = authenticity::sha256("rollback-artifact"); + check(ledger.append_promotion(promoted, error), "reviewed tested promotion recorded"); + check(ledger.verify(error), "development chains verify"); + + const auto after = authenticity::sha256([&]() { + std::ifstream input(attempt); + return std::string((std::istreambuf_iterator(input)), {}); + }()); + check(before == after, "generation history remains byte-for-byte immutable"); + + std::cout << "response_development_test checks=" << checks + << " failures=" << failures << '\n'; + std::filesystem::remove_all(root); + return failures == 0 ? 0 : 1; +} diff --git a/village/village_atomspace.hpp b/village/village_atomspace.hpp index 74111ea16..2123bade7 100644 --- a/village/village_atomspace.hpp +++ b/village/village_atomspace.hpp @@ -33,6 +33,8 @@ #include #include +#include "response_authenticity.hpp" + namespace village { namespace atomspace { // ───────────────────────────────────────────────────────────────────── @@ -908,15 +910,16 @@ class VillageAtomSpace { // ───────────────────────────────────────────────────────────────────── struct AphroditeRequest { - std::string resident; // Who is speaking - std::string correlation_id; // Directed stimulus correlation, empty for autonomous thought - std::string system_prompt; // Persona + context from AtomSpace - std::string user_prompt; // The actual query/stimulus - double temperature; // Derived from endocrine state - double min_p; // Derived from ECAN focus - std::string lora_adapter; // Per-resident LoRA (if trained) - int max_tokens; - int priority; // Derived from STI (higher = process first) + std::string resident; + std::string correlation_id; + std::string system_prompt; + std::string user_prompt; + double temperature = 0.7; + double min_p = 0.05; + int max_tokens = 512; + int priority = 0; + int seed = 0; + ::village::authenticity::GenerationEvidence evidence; }; class AphroditeBridge { @@ -928,82 +931,171 @@ class AphroditeBridge { double sti_threshold; int inference_cooldown_cycles; int max_concurrent_inferences; + std::string model_revision; + std::string identity_version; + bool allow_action_proposals; Config() : url("http://136.243.70.177:2242/v1/chat/completions"), api_key("cogcity-village-2026"), model("/var/agi_neighborhood/aphrodite/models/lucid-v1-nemo-gguf/lucid-v1-nemo-q8_0.gguf"), sti_threshold(150.0), inference_cooldown_cycles(50), - max_concurrent_inferences(4) {} + max_concurrent_inferences(4), + model_revision("unconfigured"), + identity_version("unconfigured"), + allow_action_proposals(false) {} }; - using InferenceCallback = std::function; + using InferenceCallback = + std::function; explicit AphroditeBridge(const Config& config = Config()) : config_(config), active_inferences_(0) {} - static AphroditeRequest build_request( + AphroditeRequest build_request( const VillageAtomSpace& vas, const std::string& resident_name, - const std::string& stimulus, double endocrine_temperature = 0.7) + const std::string& stimulus, double endocrine_temperature = 0.7, + const std::string& correlation_id = "", + const std::string& stimulus_source = "elizad.attention", + std::int64_t parent_event_id = 0, + std::int64_t parent_tic = 0) { AphroditeRequest req; req.resident = resident_name; + req.correlation_id = correlation_id; req.user_prompt = stimulus; req.temperature = endocrine_temperature; req.max_tokens = 512; + req.seed = ::village::authenticity::random_seed(); + auto& evidence = req.evidence; + evidence.generation_id = ::village::authenticity::random_generation_id(); + evidence.created_at = ::village::authenticity::utc_now_iso8601(); + evidence.correlation_id = correlation_id; + evidence.resident.id = resident_name; + evidence.resident.identity_version = config_.identity_version; + evidence.stimulus.source = stimulus_source; + evidence.stimulus.target = resident_name; + evidence.stimulus.text = stimulus; + evidence.stimulus.utf8_sha256 = ::village::authenticity::sha256(stimulus); + evidence.stimulus.parent_event_id = parent_event_id; + evidence.stimulus.parent_tic = parent_tic; + evidence.invocation.server = config_.url; + evidence.invocation.model_id = config_.model; + evidence.invocation.model_revision = config_.model_revision; + evidence.invocation.temperature = endocrine_temperature; + evidence.invocation.max_tokens = req.max_tokens; + evidence.invocation.seed = req.seed; + evidence.invocation.seed_sha256 = + ::village::authenticity::sha256(std::to_string(req.seed)); auto& residents = vas.residents(); auto it = residents.find(resident_name); if (it == residents.end()) return req; const auto& r = it->second; req.priority = static_cast(r.sti); req.min_p = 0.05 + (r.conscientiousness * 0.15); - req.lora_adapter = "loras/" + resident_name; - req.system_prompt = build_system_prompt(vas, r); + evidence.invocation.min_p = req.min_p; + + evidence.resident.role_prompt = resident_role_prompt(r.name); + evidence.resident.role_prompt_sha256 = + ::village::authenticity::sha256(evidence.resident.role_prompt); + const nlohmann::json identity_manifest = { + {"resident", r.name}, {"identity_version", config_.identity_version}, + {"gear_train", r.gear_train}, {"openness", r.openness}, + {"conscientiousness", r.conscientiousness}, {"extraversion", r.extraversion}, + {"agreeableness", r.agreeableness}, {"neuroticism", r.neuroticism}, + {"role_prompt_sha256", evidence.resident.role_prompt_sha256} + }; + evidence.resident.identity_manifest = + ::village::authenticity::canonical_json(identity_manifest); + evidence.resident.identity_manifest_sha256 = + ::village::authenticity::sha256(evidence.resident.identity_manifest); + + evidence.context.memory_snapshot = vas.get_episodic_context(resident_name) + + vas.get_conversation_context(resident_name); + evidence.context.memory_snapshot_sha256 = + ::village::authenticity::sha256(evidence.context.memory_snapshot); + evidence.context.shared_context = ""; + evidence.context.shared_context_sha256 = + ::village::authenticity::sha256(evidence.context.shared_context); + const nlohmann::json cognitive_state = { + {"resident", r.name}, {"gear_train", r.gear_train}, + {"sti", r.sti}, {"lti", r.lti}, + {"ocean", { + {"openness", r.openness}, {"conscientiousness", r.conscientiousness}, + {"extraversion", r.extraversion}, {"agreeableness", r.agreeableness}, + {"neuroticism", r.neuroticism} + }} + }; + evidence.context.cognitive_state = + ::village::authenticity::canonical_json(cognitive_state); + evidence.context.cognitive_state_sha256 = + ::village::authenticity::sha256(evidence.context.cognitive_state); + const nlohmann::json selection = { + {"policy", "resident-private-memory-plus-current-state-v1"}, + {"resident", resident_name}, + {"memory_bytes", evidence.context.memory_snapshot.size()}, + {"shared_context_bytes", evidence.context.shared_context.size()}, + {"action_proposals_enabled", config_.allow_action_proposals} + }; + evidence.context.selection_record = + ::village::authenticity::canonical_json(selection); + evidence.context.selection_record_sha256 = + ::village::authenticity::sha256(evidence.context.selection_record); + req.system_prompt = build_system_prompt(r, evidence.resident.role_prompt, + evidence.context.memory_snapshot, + config_.allow_action_proposals); + evidence.context.system_prompt = req.system_prompt; + evidence.context.system_prompt_sha256 = + ::village::authenticity::sha256(evidence.context.system_prompt); + evidence.context.combined_context_sha256 = ::village::authenticity::sha256( + evidence.context.system_prompt + "\n--MEMORY--\n" + + evidence.context.memory_snapshot + "\n--SHARED--\n" + + evidence.context.shared_context + "\n--STATE--\n" + + evidence.context.cognitive_state); return req; } bool infer_async(const VillageAtomSpace& vas, const std::string& resident_name, const std::string& stimulus, InferenceCallback callback, double endocrine_temperature = 0.7, - const std::string& correlation_id = "") { - if (active_inferences_.load() >= config_.max_concurrent_inferences) return false; + const std::string& correlation_id = "", + const std::string& stimulus_source = "elizad.attention", + std::int64_t parent_event_id = 0, + std::int64_t parent_tic = 0) { + auto req = build_request(vas, resident_name, stimulus, endocrine_temperature, + correlation_id, stimulus_source, parent_event_id, parent_tic); + if (req.resident.empty() || req.evidence.resident.role_prompt.empty()) { + fail_attempt(req.evidence, "unknown_resident", "canonical resident identity was not found"); + if (callback) callback(std::move(req.evidence)); + return false; + } + if (active_inferences_.load() >= config_.max_concurrent_inferences) { + fail_attempt(req.evidence, "capacity_rejected", "maximum concurrent inference limit reached"); + if (callback) callback(std::move(req.evidence)); + return false; + } auto now = std::chrono::steady_clock::now(); { std::lock_guard lock(cooldown_mutex_); auto it = last_inference_.find(resident_name); if (it != last_inference_.end()) { auto elapsed = std::chrono::duration_cast(now - it->second).count(); - if (elapsed < config_.inference_cooldown_cycles * 52) return false; + if (elapsed < config_.inference_cooldown_cycles * 52) { + fail_attempt(req.evidence, "cooldown_rejected", "resident inference cooldown is active"); + if (callback) callback(std::move(req.evidence)); + return false; + } } last_inference_[resident_name] = now; } - auto req = build_request(vas, resident_name, stimulus, endocrine_temperature); - req.correlation_id = correlation_id; - // Cycle 007: Append episodic memory and conversation context - req.system_prompt += vas.get_episodic_context(resident_name); - req.system_prompt += vas.get_conversation_context(resident_name); - if (req.resident.empty()) return false; active_inferences_++; std::thread([this, req, callback]() { - std::string thought = perform_inference(req); + auto completed = perform_inference(req); active_inferences_--; - if (!thought.empty() && callback) callback(req.resident, thought, req.correlation_id); - // Cycle 008: record the stimulus/response pair so future prompts carry - // conversation history (previously add_conversation was never invoked). - if (!thought.empty() && conversation_recorder_) { - conversation_recorder_(req.resident, req.user_prompt, thought); - } + if (callback) callback(std::move(completed)); }).detach(); return true; } - // Cycle 008: optional hook invoked after each successful inference with - // (resident, stimulus, response) — wired by elizad to VillageAtomSpace::add_conversation. - using ConversationRecorder = - std::function; - void set_conversation_recorder(ConversationRecorder rec) { - conversation_recorder_ = std::move(rec); - } - bool should_infer(const std::string& resident_name, double sti) const { if (sti < config_.sti_threshold) return false; std::lock_guard lock(cooldown_mutex_); @@ -1023,7 +1115,21 @@ class AphroditeBridge { return size * nmemb; } - std::string perform_inference(const AphroditeRequest& req) { + static void fail_attempt(::village::authenticity::GenerationEvidence& evidence, + const std::string& code, const std::string& detail) { + evidence.result.status = "generation-failed"; + evidence.result.finished_at = ::village::authenticity::utc_now_iso8601(); + evidence.result.error_code = code; + evidence.result.error_detail = detail; + evidence.publication.allowed = false; + evidence.publication.denial_reason = code; + } + + ::village::authenticity::GenerationEvidence perform_inference( + const AphroditeRequest& req) { + auto evidence = req.evidence; + const auto started = std::chrono::steady_clock::now(); + evidence.invocation.started_at = ::village::authenticity::utc_now_iso8601(); nlohmann::json messages = nlohmann::json::array(); messages.push_back({{"role", "system"}, {"content", req.system_prompt}}); messages.push_back({{"role", "user"}, {"content", req.user_prompt}}); @@ -1033,11 +1139,18 @@ class AphroditeBridge { nlohmann::json payload = { {"model", config_.model}, {"messages", messages}, {"temperature", req.temperature}, {"min_p", req.min_p}, - {"max_tokens", req.max_tokens}, {"stop", stop_tokens} + {"max_tokens", req.max_tokens}, {"seed", req.seed}, {"stop", stop_tokens} }; + std::string response; + const std::string body = payload.dump(); + evidence.invocation.request_body = body; + evidence.invocation.request_body_sha256 = + ::village::authenticity::sha256(body); CURL* curl = curl_easy_init(); - if (!curl) return ""; - std::string response, body = payload.dump(); + if (!curl) { + fail_attempt(evidence, "curl_initialization_failed", "unable to initialize HTTP client"); + return evidence; + } std::string auth_header = "Authorization: Bearer " + config_.api_key; struct curl_slist* headers = nullptr; headers = curl_slist_append(headers, "Content-Type: application/json"); @@ -1051,34 +1164,67 @@ class AphroditeBridge { curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60L); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L); CURLcode res = curl_easy_perform(curl); + long http_status = 0; + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_status); fprintf(stderr, "[INFER] curl_res=%d resp_len=%zu\n", (int)res, response.size()); curl_slist_free_all(headers); curl_easy_cleanup(curl); - if (res != CURLE_OK) return ""; + evidence.result.finished_at = ::village::authenticity::utc_now_iso8601(); + evidence.result.latency_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started).count(); + evidence.result.transport_code = static_cast(res); + evidence.result.http_status = static_cast(http_status); + evidence.result.raw_response = response; + evidence.result.raw_response_sha256 = + ::village::authenticity::sha256(response); + if (res != CURLE_OK) { + fail_attempt(evidence, "transport_error", curl_easy_strerror(res)); + return evidence; + } + if (http_status != 200) { + fail_attempt(evidence, "model_http_error", + "model server returned HTTP " + std::to_string(http_status)); + return evidence; + } try { auto j = nlohmann::json::parse(response); if (j.contains("choices") && !j["choices"].empty()) { - std::string content = j["choices"][0]["message"]["content"].get(); - // Strip chat template tokens - auto pos = content.find("<|im_end|>"); - if (pos != std::string::npos) content = content.substr(0, pos); - pos = content.find("<|im_start|>"); - if (pos != std::string::npos) content = content.substr(0, pos); - // Trim whitespace - while (!content.empty() && (content.back() == '\n' || content.back() == ' ')) - content.pop_back(); + const std::string content = + j["choices"][0]["message"]["content"].get(); + evidence.result.raw_completion = content; + evidence.result.raw_completion_sha256 = + ::village::authenticity::sha256(content); + evidence.result.normalized_completion = + ::village::authenticity::normalize_completion( + content, evidence.result.normalization); + evidence.result.normalized_completion_sha256 = + ::village::authenticity::sha256( + evidence.result.normalized_completion); + evidence.result.finish_reason = + j["choices"][0].value("finish_reason", "unreported"); + if (j.contains("usage")) { + evidence.result.prompt_tokens = j["usage"].value("prompt_tokens", 0); + evidence.result.completion_tokens = + j["usage"].value("completion_tokens", 0); + } + evidence.result.status = "generated-unverified"; + if (evidence.result.normalized_completion.empty()) { + fail_attempt(evidence, "empty_completion", + "model returned no publishable completion bytes"); + } fprintf(stderr, "[INFER] Extracted thought len=%zu for %s\n", content.size(), req.resident.c_str()); - return content; + return evidence; } fprintf(stderr, "[INFER] No choices in response\n"); + fail_attempt(evidence, "missing_choices", "model response contains no choices"); } catch (const std::exception& e) { fprintf(stderr, "[INFER] Parse error: %s\n", e.what()); + fail_attempt(evidence, "response_parse_error", e.what()); } - return ""; + return evidence; } - static std::string build_system_prompt( - [[maybe_unused]] const VillageAtomSpace& vas, const ResidentAtom& r) { + static std::string resident_role_prompt(const std::string& resident_name) { // ─── Persona-Specific System Prompts (Cycle 005: COHERENCE) ─── static const std::map personas = { {"manus", "You are Manus, the coordination intelligence of the CogVerse village. " @@ -1114,21 +1260,27 @@ class AphroditeBridge { "that others miss. Your speech is playful, paradoxical, and bridge-building. " "Your domain: cross-platform integration, protocol translation, meta-learning."} }; - std::string prompt; - auto pit = personas.find(r.name); + auto pit = personas.find(resident_name); if (pit != personas.end()) { - prompt = pit->second + "\n\n"; - } else { - prompt = "You are " + r.name + ", a resident of the CogVerse cognitive village.\n\n"; + return pit->second; } - // Action capability instruction - prompt += "\n\nYou can propose actions by including [ACTION:type]{json} blocks in your response. " + return ""; + } + + static std::string build_system_prompt(const ResidentAtom& r, + const std::string& role_prompt, + const std::string& memory_snapshot, + bool allow_action_proposals) { + std::string prompt = role_prompt + "\n\n"; + if (allow_action_proposals) { + prompt += "You can propose actions by including [ACTION:type]{json} blocks in your response. " "Available actions:\n" " [ACTION:write_stone]{\"title\": \"...\", \"content\": \"...\"}\n" " [ACTION:adjust_gear]{\"train\": \"...\", \"factor\": 1.2}\n" " [ACTION:emit_event]{\"type\": \"...\", \"payload\": {...}}\n" " [ACTION:observe_state]{\"target\": \"atomspace|gears|residents\"}\n" "Only propose actions when they serve the village. Most responses need no action.\n\n"; + } prompt += "Context: gear_train=" + r.gear_train; prompt += " STI=" + std::to_string(static_cast(r.sti)); prompt += " OCEAN=[O:" + std::to_string(r.openness).substr(0,4) + @@ -1137,6 +1289,7 @@ class AphroditeBridge { " A:" + std::to_string(r.agreeableness).substr(0,4) + " N:" + std::to_string(r.neuroticism).substr(0,4) + "]\n"; prompt += "Respond in 2-4 sentences. Be authentic to your character. Do not break character.\n"; + prompt += memory_snapshot; return prompt; } @@ -1144,6 +1297,5 @@ class AphroditeBridge { std::atomic active_inferences_; mutable std::mutex cooldown_mutex_; std::map last_inference_; - ConversationRecorder conversation_recorder_; // Cycle 008 }; }} // namespace village::atomspace From 9b0fca22972407d533624b495d292dcf0e0dfc07 Mon Sep 17 00:00:00 2001 From: drzo <1.5202748e+07+drzo@users.noreply.github.com> Date: Mon, 31 Aug 2026 03:36:01 +0000 Subject: [PATCH 2/4] fix(village): gate shell-bearing autonomous cycles --- village/elizad.cpp | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/village/elizad.cpp b/village/elizad.cpp index fad2bd4f6..4ce637999 100644 --- a/village/elizad.cpp +++ b/village/elizad.cpp @@ -90,6 +90,8 @@ using Clock = std::chrono::steady_clock; // (cogvillage::ksm and cogvillage::bridge defined in their headers) static std::atomic g_running{true}; +static std::atomic g_autonomousCoreEnabled{false}; +static std::atomic g_residentActionsEnabled{false}; // Thread-safe queue for committed generation evidence from inference threads. // Only generated-authentic entries may become resident.thought events. @@ -266,6 +268,7 @@ struct ElizadConfig { std::string generationEvidencePath = "/var/agi_neighborhood/evidence/resident-generation"; bool residentActionsEnabled = false; + bool autonomousCoreEnabled = false; double inferenceSTIThreshold = 150.0; int inferenceCooldownCycles = 100; @@ -287,6 +290,8 @@ struct ElizadConfig { if (auto value = startupEnvironment("ELIZAD_GENERATION_EVIDENCE_PATH"); !value.empty()) cfg.generationEvidencePath = value; cfg.residentActionsEnabled = startupBoolean( "ELIZAD_RESIDENT_ACTIONS_ENABLED", cfg.residentActionsEnabled); + cfg.autonomousCoreEnabled = startupBoolean( + "ELIZAD_AUTONOMOUS_CORE_ENABLED", cfg.autonomousCoreEnabled); cfg.inferenceSTIThreshold = startupDouble( "ELIZAD_INFERENCE_STI_THRESHOLD", cfg.inferenceSTIThreshold, 0.0); cfg.inferenceCooldownCycles = startupInteger( @@ -400,6 +405,8 @@ class HealthServer { {"open_goals", report.openGoals}, {"completed_goals", report.completedGoals}, {"total_actions", report.totalActions}, + {"autonomous_core_enabled", g_autonomousCoreEnabled.load()}, + {"resident_actions_enabled", g_residentActionsEnabled.load()}, {"stagnation_count", report.stagnationCount}, {"last_plan", report.lastPlan}, {"cognitive_cycles", g_cogCycleCount.load()}, @@ -540,19 +547,27 @@ static int runElizad(int argc, char* argv[]) { std::cout << " + Antikythera Temporal Coupling (10 gears, 4 trains)\n\n"; ElizadConfig config = ElizadConfig::fromEnv(); + g_autonomousCoreEnabled = config.autonomousCoreEnabled; + g_residentActionsEnabled = config.residentActionsEnabled; std::cout << "[elizad] Bus: " << config.busUrl << "\n"; std::cout << "[elizad] Resident: " << config.residentName << "\n"; std::cout << "[elizad] Health port: " << config.healthPort << "\n"; std::cout << "[elizad] Cognitive cycle: " << config.cogCycleMs << "ms (L8)\n"; std::cout << "[elizad] Heartbeat: " << config.heartbeatMs << "ms (L7)\n\n"; + std::cout << "[elizad] Autonomous shell-bearing core: " + << (config.autonomousCoreEnabled ? "ENABLED" : "DISABLED") << "\n"; + std::cout << "[elizad] Resident action proposals: " + << (config.residentActionsEnabled ? "ENABLED" : "DISABLED") << "\n\n"; // Initialize agent with village config AgentConfig agentCfg; agentCfg.agentName = config.residentName; - agentCfg.bio = "Autonomous cognitive agent — CogHood village resident"; + agentCfg.bio = config.autonomousCoreEnabled + ? "Autonomous cognitive agent — CogHood village resident" + : "Non-executing cognitive observer — CogHood village resident"; agentCfg.lore = "ElizaOS C++ cognitive architecture with endocrine system, " "group dynamics, and Antikythera temporal coupling"; - agentCfg.adjective = "autonomous"; + agentCfg.adjective = config.autonomousCoreEnabled ? "autonomous" : "non-executing"; AutonomousStarter agent(agentCfg); EndocrineSystem endocrine; @@ -838,7 +853,9 @@ static int runElizad(int argc, char* argv[]) { if (elapsed >= config.cogCycleMs) { // Core cognitive cycle - agent.runCognitiveCycleOnce(); + if (config.autonomousCoreEnabled) { + agent.runCognitiveCycleOnce(); + } endocrine.tick(); g_cogCycleCount++; // Cycle 007: Persist every 100 cycles From 2c4a2e3f7b3b0abfa1482a3f1fcf822d289df0c9 Mon Sep 17 00:00:00 2001 From: drzo <1.5202748e+07+drzo@users.noreply.github.com> Date: Mon, 31 Aug 2026 03:43:20 +0000 Subject: [PATCH 3/4] fix(village): unwrap event payloads for directed inference --- village/CMakeLists.txt | 4 +++ village/village_event_bus.cpp | 21 ++++++++++---- village/village_event_bus.hpp | 2 ++ village/village_event_bus_test.cpp | 44 ++++++++++++++++++++++++++++++ 4 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 village/village_event_bus_test.cpp diff --git a/village/CMakeLists.txt b/village/CMakeLists.txt index 80642e7d4..eeef9e76d 100644 --- a/village/CMakeLists.txt +++ b/village/CMakeLists.txt @@ -16,6 +16,10 @@ target_include_directories(village_event_bus PUBLIC ) target_link_libraries(village_event_bus PUBLIC CURL::libcurl nlohmann_json::nlohmann_json) +add_executable(village_event_bus_test village_event_bus_test.cpp) +target_link_libraries(village_event_bus_test PRIVATE village_event_bus) +add_test(NAME village_event_bus_test COMMAND village_event_bus_test) + # Resident generation provenance, validation, and append-only evidence journal add_library(response_authenticity STATIC response_authenticity.cpp) target_include_directories(response_authenticity PUBLIC diff --git a/village/village_event_bus.cpp b/village/village_event_bus.cpp index b4c1d293a..e1926ecfd 100644 --- a/village/village_event_bus.cpp +++ b/village/village_event_bus.cpp @@ -280,23 +280,34 @@ std::string VillageEventBusClient::httpGet(const std::string& url) { return (res == CURLE_OK) ? response : ""; } -VillageEvent VillageEventBusClient::parseEvent(const std::string& jsonStr) { +VillageEvent parseVillageEvent(const std::string& jsonStr) { VillageEvent event; try { auto j = json::parse(jsonStr); event.id = j.value("id", int64_t(0)); event.timestamp = j.value("timestamp", 0.0); event.typeStr = j.value("event_type", "unknown"); - event.type = parseEventType(event.typeStr); - event.source = j.value("source", ""); - event.target = j.value("target", ""); + event.source = j.contains("source") && j["source"].is_string() + ? j["source"].get() : ""; + event.target = j.contains("target") && j["target"].is_string() + ? j["target"].get() : ""; event.hash = j.value("hash", ""); event.tic = j.value("tic", int64_t(0)); - if (j.contains("payload")) event.payload = j["payload"].dump(); + if (j.contains("payload")) { + event.payload = j["payload"].is_string() + ? j["payload"].get() + : j["payload"].dump(); + } } catch (...) {} return event; } +VillageEvent VillageEventBusClient::parseEvent(const std::string& jsonStr) { + auto event = parseVillageEvent(jsonStr); + event.type = parseEventType(event.typeStr); + return event; +} + VillageEventType VillageEventBusClient::parseEventType(const std::string& typeStr) { static const std::unordered_map typeMap = { {"heartbeat", VillageEventType::Heartbeat}, diff --git a/village/village_event_bus.hpp b/village/village_event_bus.hpp index 2ad06cec1..fbdf7a7bd 100644 --- a/village/village_event_bus.hpp +++ b/village/village_event_bus.hpp @@ -75,6 +75,8 @@ struct VillageEvent { int64_t tic = 0; }; +VillageEvent parseVillageEvent(const std::string& json); + using VillageEventCallback = std::function; // ============================================================================ diff --git a/village/village_event_bus_test.cpp b/village/village_event_bus_test.cpp new file mode 100644 index 000000000..a87560821 --- /dev/null +++ b/village/village_event_bus_test.cpp @@ -0,0 +1,44 @@ +#include "village_event_bus.hpp" + +#include +#include + +namespace { +int checks = 0; +int failures = 0; + +void check(bool condition, const std::string& name) { + ++checks; + if (!condition) { + ++failures; + std::cerr << "FAIL: " << name << '\n'; + } +} +} + +int main() { + const std::string directed = R"({ + "tic": 42, + "event_type": "stimulus.directed", + "source": "authenticity.operator", + "target": "echo", + "payload": "{\"message\":\"Respond from Echo's context\",\"correlation_id\":\"corr-42\"}" + })"; + const auto event = elizaos::parseVillageEvent(directed); + check(event.tic == 42, "tic parsed"); + check(event.typeStr == "stimulus.directed", "type parsed"); + check(event.source == "authenticity.operator", "source parsed"); + check(event.target == "echo", "target parsed"); + check(event.payload == + "{\"message\":\"Respond from Echo's context\",\"correlation_id\":\"corr-42\"}", + "JSON-string payload unwrapped exactly once"); + + const auto heartbeat = elizaos::parseVillageEvent( + R"({"tic":43,"event_type":"heartbeat","source":"event_bus","target":null,"payload":{"alive":true}})"); + check(heartbeat.target.empty(), "nullable target becomes empty"); + check(heartbeat.payload == "{\"alive\":true}", "object payload remains canonical JSON"); + + std::cout << "village_event_bus_test checks=" << checks + << " failures=" << failures << '\n'; + return failures == 0 ? 0 : 1; +} From b3059acb9301f45b86fa144de4964b4814395f6e Mon Sep 17 00:00:00 2001 From: drzo <1.5202748e+07+drzo@users.noreply.github.com> Date: Mon, 31 Aug 2026 03:50:52 +0000 Subject: [PATCH 4/4] fix(village): seed canonical resident identities --- village/elizad.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/village/elizad.cpp b/village/elizad.cpp index 4ce637999..b2d66cea7 100644 --- a/village/elizad.cpp +++ b/village/elizad.cpp @@ -615,7 +615,10 @@ static int runElizad(int argc, char* argv[]) { json regData = json::parse(regFile); for (auto& [name, data] : regData["residents"].items()) { ::village::atomspace::ResidentAtom ra; - ra.name = data["handle"].get(); + // The registry key is the canonical machine identity used by + // directed stimuli, role prompts, memory ledgers, and evidence. + // `handle` is display-only and must not create a second identity. + ra.name = name; ra.gear_train = data["gear_train"].get(); ra.gear_rpm_multiplier = data["gear_teeth"].get() / 30.0; // Default OCEAN (will be refined per-resident via LoRA training)