include/entropic/core/constitutional_validator.h¶
include/entropic/core/constitutional_validator.h
entropic::ConstitutionalValidator
Post-generation constitutional compliance validator.
entropic::ConstitutionalValidator::ConstitutionalValidator(const ConstitutionalValidationConfig &config, const std::string &constitution_text)
Construct validator with config and constitution text.
- Parameters
config— Validation pipeline configuration.constitution_text— Full constitution text (from PromptManager).constitution_text— Full constitution text.
entropic_error_t entropic::ConstitutionalValidator::attach(HookInterface *hook_iface, InferenceInterface *inference)
Register this validator as a POST_GENERATE hook.
Register as POST_GENERATE hook via the HookRegistry C API.
- Parameters
hook_iface— HookInterface for registration (via fire_post).inference— InferenceInterface for critique generation.hook_iface— HookInterface with registry pointer.
- Returns
- ENTROPIC_OK on success.
void entropic::ConstitutionalValidator::detach(HookInterface *hook_iface)
Deregister the POST_GENERATE hook.
- Parameters
hook_iface— HookInterface for deregistration.hook_iface— HookInterface with registry pointer.
bool entropic::ConstitutionalValidator::should_validate(const std::string &identity_name) const
Check if validation is enabled for a given identity.
Returns false if the tier is in config_.skip_tiers (e.g. "lead"). Per-identity overrides (set_identity_validation) take precedence. Returns false if the tier is in config_.skip_tiers (e.g. "lead", which streams output before the POST_GENERATE hook fires). Per-identity overrides take precedence over skip_tiers.
- Parameters
identity_name— Identity name to check.
- Returns
- true if validation should run for this identity.
- true if validation should run.
void entropic::ConstitutionalValidator::set_identity_validation(const std::string &identity_name, bool enabled)
Set per-identity validation override.
- Parameters
identity_name— Identity name.enabled— Whether validation is enabled for this identity.enabled— Whether validation is enabled.
void entropic::ConstitutionalValidator::set_tier_rules(const std::string &identity_name, const std::vector< std::string > &rules)
Set per-identity validation rules from frontmatter.
- Parameters
identity_name— Identity/tier name.rules— Validation rules specific to this identity.rules— Validation rules for this identity.
void entropic::ConstitutionalValidator::set_global_enabled(bool enabled)
Toggle the global validation gate at runtime.
Per-identity overrides set via set_identity_validation() still take precedence; this only changes the fallback value used when no per-identity override exists.
- Parameters
enabled— true to enable validation globally, false to disable.enabled— New global enable state.
void entropic::ConstitutionalValidator::set_marker_resolver(std::function< std::pair< std::string, std::string >(const std::string &)> resolver)
Register a per-tier reasoning-delimiter resolver (gh#108).
One validator serves every tier, but thinking format is per-family: Qwen/Nemotron use <think>…</think>, Gemma-4 QAT uses <|channel>…<channel|>. A single fixed pair would be wrong for any config mixing families, so the delimiters are resolved per call from the tier name validate() already receives. The facade supplies the lambda (it can see ChatAdapter); the callback trades in plain strings so core keeps no dependency on inference. Unset, the <think> default applies.
- Parameters
resolver— Maps tier name → {open, close}.
ValidationResult entropic::ConstitutionalValidator::validate(const std::string &content, const std::string &tier, const char *messages_json)
Run the validation pipeline on generated content.
Run the full validation pipeline on generated content. Called from the POST_GENERATE hook callback. Flow: Check per-identity override Run critique generation pass Parse structured JSON verdict If violations and revision enabled, revise Return final (possibly revised) content
- Parameters
content— The generated text to validate.tier— The tier/identity that produced the content.messages_json— The conversation context (for revision).messages_json— Original conversation context.
- Returns
- ValidationResult with final content and critique metadata.
ValidationResult entropic::ConstitutionalValidator::last_result() const
Get the last validation result.
- Returns
- Most recent ValidationResult, or default if none.
- Most recent ValidationResult.
void entropic::ConstitutionalValidator::set_auto_retry(bool enabled)
Enable or disable automatic revision after rejection.
Toggle auto-revision. When disabled, validate() returns immediately on the first failing critique with verdict paused_pending_consumer and caches enough state for resume_retry() to continue the revision loop later. Default: true (preserves pre-2.1.5 behavior).
- Parameters
enabled— Whether auto-revision is enabled.enabled— True to enable auto-revision.
bool entropic::ConstitutionalValidator::auto_retry_enabled() const
Whether auto-revision is currently enabled.
Read auto-revision flag.
- Returns
- true if enabled.
- Current state.
entropic_error_t entropic::ConstitutionalValidator::resume_retry()
Resume the revision pass after a paused validation.
Resume the revision loop after a paused validation. Re-enters apply_revisions() using the state cached by the most recent validate() call that paused on a critique failure. Runs synchronously and updates last_result_. Returns ENTROPIC_ERROR_INVALID_STATE if no validation is paused. Pops the cached pending state, runs apply_revisions() against it ignoring the auto_retry_enabled_ flag for this call, and stores the final result. Returns INVALID_STATE if no pending state exists.
- Returns
- ENTROPIC_OK on success.
- ENTROPIC_OK on success, INVALID_STATE if nothing paused.
entropic_error_t entropic::ConstitutionalValidator::accept_last()
Finalize the cached attempt as the validation result.
Finalize the paused attempt as the consumer-accepted answer. Used after set_auto_retry(false) paused validation: marks the paused attempt as the consumer-accepted answer (verdict becomes passed_consumer_override) and clears the cached pending state. Marks verdict as passed_consumer_override and clears pending state. Returns INVALID_STATE if no pending state exists.
- Returns
- ENTROPIC_OK on success. ENTROPIC_ERROR_INVALID_STATE if no validation is paused.
void entropic::ConstitutionalValidator::set_attempt_boundary_cb(void(*cb)(int attempt_n, void *user_data), void *user_data)
Register the attempt-boundary callback.
Fires immediately before each revision attempt starts. Used by consumers to split rendered output between attempts.
- Parameters
cb— Callback (nullable clears).user_data— Forwarded to cb.cb— Callback fn pointer.
void entropic::ConstitutionalValidator::set_critique_callbacks(void(*start_cb)(void *user_data), void(*end_cb)(void *user_data), void *user_data)
Register the critique start/end callback pair (gh#50).
Register critique start/end callbacks (gh#50, v2.1.12). Fires immediately before and after the synchronous inference_->generate() call inside run_critique(). Gives consumer UIs a visible signal for the 20-30s critique window that previously left AgentState parked at EXECUTING with no observable transition. Both callbacks take only the user_data pointer — consumer correlates timing themselves. Persistent-slot pattern: outlives set_callbacks() shuffles (validator owns its own slot, no entanglement with EngineCallbacks). Same survival contract as set_attempt_boundary_cb and the v2.1.10 state observer. start_cb and end_cb are nullable independently; passing nullptr for both clears the slot. Stored under critique_cbs_mutex_ so a consumer reassigning the slot cannot race with the firing site in run_critique(). Either callback pointer may be nullptr independently — only the non-null ones fire.
- Parameters
start_cb— Fires before the critique generate begins.end_cb— Fires after the critique generate returns.user_data— Forwarded to both callbacks.start_cb— Pre-generate hook.end_cb— Post-generate hook.user_data— Forwarded to both.
- threadsafety
- Thread-safe (guarded by critique_cbs_mutex_).
const ConstitutionalValidationConfig & entropic::ConstitutionalValidator::config() const
Get the config (read-only after construction).
- Returns
- Reference to config.
int entropic::ConstitutionalValidator::hook_callback(entropic_hook_point_t hook_point, const char *context_json, char **modified_json, void *user_data)
POST_GENERATE hook callback for constitutional validation.
POST_GENERATE hook callback. Static function registered with HookRegistry. Extracts ValidationContext from user_data, runs the validation pipeline, and writes modified_json if content was revised.
- Parameters
hook_point— Hook point (POST_GENERATE).context_json— JSON context from engine.modified_json— Output: revised JSON or NULL.user_data— ValidationContext pointer.
- Returns
- 0 (post-hooks cannot cancel).
std::string entropic::ConstitutionalValidator::build_critique_prompt(const std::string &content) const
Build the critique prompt (exposed for testing).
Build the critique prompt string. When per-tier validation_rules exist (from identity frontmatter), those are the PRIMARY evaluation criteria and the constitution is included as background context. This prevents the validator from citing global constitution rule numbers ("Rule 2: Tool calls are mandatory") when the tier has its own specific compliance criteria. When no validation_rules exist, falls back to the constitution as the sole rubric (pre-v2.0.8 behavior). Prepends a tool call manifest (from current_tool_context()) when available so the validator can distinguish grounded claims from ungrounded assertions.
- Parameters
content— Text to critique.content— Text to critique (think blocks already stripped).
- Returns
- Formatted critique prompt string.
void entropic::ConstitutionalValidator::append_turn_evidence(std::string &prompt) const
Append this turn's tool manifest and evidence to a prompt.
Append this turn's tool manifest and evidence to a critique prompt. Extracted at gh#158 (v2.13.0): the per-turn context moved from members to thread-local accessors, and six calls where there had been six field reads put build_critique_prompt over the ABC gate. The two sections belong together anyway — both answer "what did the model actually have in front of it", and both are optional. The evidence half is Issue #5 (v2.1.3): un-pruned tool-result content, so the critique pass can verify file:line citations against what was really returned rather than against the manifest-plus-stubs that pre-2.1.3 produced. The engine surfaces it when messages have been partially pruned.
- Parameters
prompt— Critique prompt under construction (appended in place).prompt— Critique prompt under construction (appended to in place).
CritiqueResult entropic::ConstitutionalValidator::parse_critique(const std::string &json_str)
Parse critique JSON into structured result (exposed for testing).
Parse critique JSON into CritiqueResult.
- Parameters
json_str— Raw JSON string from grammar-constrained generation.json_str— Raw JSON from grammar-constrained generation.
- Returns
- Parsed CritiqueResult. On parse failure, returns default (compliant=true) with raw_json set for diagnostics.
entropic::ConstitutionalValidator::AttemptBoundaryCb
void(* entropic::ConstitutionalValidator::AttemptBoundaryCb::cb) (int, void *)
void* entropic::ConstitutionalValidator::AttemptBoundaryCb::user_data
entropic::ConstitutionalValidator::CritiqueCallbacks
void(* entropic::ConstitutionalValidator::CritiqueCallbacks::start_cb) (void *)
void(* entropic::ConstitutionalValidator::CritiqueCallbacks::end_cb) (void *)
void* entropic::ConstitutionalValidator::CritiqueCallbacks::user_data
entropic::ConstitutionalValidator::PendingValidationState
ValidationResult entropic::ConstitutionalValidator::PendingValidationState::result
Cached partial result.
CritiqueResult entropic::ConstitutionalValidator::PendingValidationState::critique
First failing critique.
std::string entropic::ConstitutionalValidator::PendingValidationState::messages_json
Conversation context to revise against.
std::string entropic::ConstitutionalValidator::PendingValidationState::tier
Originating tier (for log)
std::string entropic::ConstitutionalValidator::PendingValidationState::system_prompt
gh#158: the identity system prompt of the turn that paused.
resume_retry() runs on the CONSUMER's thread, which never saw that turn's thread-local context, so the one value the revision path reads has to travel with the pause.
entropic::ValidationContext
Context passed through hook user_data.
class ConstitutionalValidator* entropic::ValidationContext::validator
Validator instance.
InferenceInterface* entropic::ValidationContext::inference
For critique generation.