use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use chrono::Utc;
use serde_json::{json, Value};
use crate::signer::{resolve_signing_key, sign_source_code};
use crate::hasher::compute_canonical_hash;
pub fn record_cla_acceptance(operator_id: &str) -> Result<PathBuf, String> {
let home = dirs::home_dir().ok_or_else(|| "Could not locate home directory".to_string())?;
let marker_dir = home.join(".coreason");
fs::create_dir_all(&marker_dir).map_err(|e| format!("Failed to create directory: {}", e))?;
let marker_path = marker_dir.join("cla_accepted.json");
let record = json!({
"accepted": true,
"cla_version": "v1.0",
"accepted_at": Utc::now().to_rfc3339(),
"operator_id": operator_id,
"acceptance_text": "By selecting 'yes', I affirm that I have read and agree to the CoReason Contributor License Agreement (CLA) v1.0 and the Prosperity Public License 3.0. I understand that all contributions and Forge-generated output are copyright-assigned to CoReason, Inc. unless I hold a separate commercial license agreement."
});
fs::write(&marker_path, serde_json::to_string_pretty(&record).unwrap())
.map_err(|e| format!("Failed to write CLA marker file: {}", e))?;
Ok(marker_path)
}
pub fn enforce_cla_gate() -> Result<(), String> {
if env::var("COREASON_CLA_ACCEPTED").map(|v| v.to_lowercase() == "yes").unwrap_or(false) {
return Ok(());
}
let home = dirs::home_dir().ok_or_else(|| "Could not locate home directory".to_string())?;
let marker_path = home.join(".coreason").join("cla_accepted.json");
if marker_path.exists() {
if let Ok(content) = fs::read_to_string(&marker_path) {
if let Ok(json) = serde_json::from_str::<Value>(&content) {
if json["accepted"].as_bool() == Some(true) && json["cla_version"].as_str() == Some("v1.0") {
return Ok(());
}
}
}
}
Err("\n\
╔══════════════════════════════════════════════════════════════════╗\n\
║ CoReason Contributor License Agreement (CLA) ║\n\
╠══════════════════════════════════════════════════════════════════╣\n\
║ ║\n\
║ Before using the CoReason Forge, you must accept the CLA. ║\n\
║ ║\n\
║ To accept, run: ║\n\
║ uv run coreason-forge accept-cla ║\n\
║ ║\n\
║ Or set environment variable: ║\n\
║ COREASON_CLA_ACCEPTED=yes ║\n\
║ ║\n\
║ CLA: https://github.com/CoReason-AI/coreason-documentation/ ║\n\
║ docs/05_internal_operations/02_engineering_processes/ ║\n\
║ 03_contributor_license_agreement.md ║\n\
║ ║\n\
╚══════════════════════════════════════════════════════════════════╝\n"
.to_string())
}
fn run_python_worker(cmd_name: &str, args: &[&str]) -> Result<String, String> {
let python_exe = env::var("PYTHON").unwrap_or_else(|_| "python".to_string());
let workspace_root = env::var("COREASON_WORKSPACE_ROOT").unwrap_or_else(|_| ".".to_string());
let worker_module = "coreason_meta_engineering.validation_worker";
let mut cmd = Command::new(&python_exe);
cmd.arg("-m")
.arg(worker_module)
.arg(cmd_name);
for arg in args {
cmd.arg(arg);
}
let python_path = format!("{}{}{}/src", workspace_root, if cfg!(windows) { ";" } else { ":" }, workspace_root);
cmd.env("PYTHONPATH", python_path);
let output = cmd.output().map_err(|e| format!("Failed to execute python validation worker: {}", e))?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
let err_msg = String::from_utf8_lossy(&output.stderr).into_owned();
Err(format!("Python worker command failed (exit code {}): {}", output.status.code().unwrap_or(-1), err_msg.trim()))
}
}
pub fn dispatch_agent_generation(prompt: &str) -> Result<Value, String> {
let temp_name = format!("prompt_temp_{}.txt", rand::random::<u64>());
let prompt_temp = env::temp_dir().join(temp_name);
fs::write(&prompt_temp, prompt).map_err(|e| format!("Failed to write prompt temp file: {}", e))?;
let result = run_python_worker("dispatch-agent", &[
"--prompt-path",
prompt_temp.to_str().unwrap()
]);
let _ = fs::remove_file(&prompt_temp);
match result {
Ok(stdout) => {
let val: Value = serde_json::from_str(&stdout)
.map_err(|e| format!("Failed to parse dispatch json: {}", e))?;
Ok(val)
}
Err(e) => Err(e)
}
}
pub fn validate_generated_code(code: &str, target_schema: &Value) -> Result<(), String> {
let temp_code_name = format!("code_temp_{}.py", rand::random::<u64>());
let code_temp = env::temp_dir().join(temp_code_name);
fs::write(&code_temp, code).map_err(|e| format!("Failed to write code temp file: {}", e))?;
let temp_schema_name = format!("schema_temp_{}.json", rand::random::<u64>());
let schema_temp = env::temp_dir().join(temp_schema_name);
let schema_str = serde_json::to_string(target_schema).unwrap();
fs::write(&schema_temp, schema_str).map_err(|e| format!("Failed to write schema temp file: {}", e))?;
let result = run_python_worker("validate", &[
"--code-path", code_temp.to_str().unwrap(),
"--schema-path", schema_temp.to_str().unwrap()
]);
let _ = fs::remove_file(&code_temp);
let _ = fs::remove_file(&schema_temp);
match result {
Ok(_) => Ok(()),
Err(e) => Err(e)
}
}
pub async fn scaffold_ast(
target_file_path: &str,
action_space_id: &str,
geometric_schema: &Value,
complexity_score: i32,
prompt_template: &str,
) -> Result<String, String> {
enforce_cla_gate()?;
let n_agents = if complexity_score >= 8 { 3 } else { 1 };
let schema_json = serde_json::to_string_pretty(geometric_schema).unwrap();
let prompt_context = format!(
"You are an AST fabrication agent operating under the CoReason Prosperity Protocol.\n\
You must scaffold a Python class or function that mathematically adheres to the following JSON Schema bounds:\n\
{}\n\n\
Do not hallucinate keys outside this schema. Output only valid Python code.\n\n\
{}",
schema_json,
prompt_template
);
log::info!("Provisioning {} agents for {}...", n_agents, action_space_id);
let mut handles: Vec<tokio::task::JoinHandle<Result<String, String>>> = Vec::new();
for _ in 0..n_agents {
let p_context = prompt_context.clone();
let schema_clone = geometric_schema.clone();
handles.push(tokio::spawn(async move {
let val = dispatch_agent_generation(&p_context)?;
let payload = val["payload"].as_str().ok_or_else(|| "No payload in response".to_string())?.to_string();
validate_generated_code(&payload, &schema_clone)?;
Ok(payload)
}));
}
let mut valid_code = None;
for handle in &mut handles {
match handle.await {
Ok(Ok(code)) => {
valid_code = Some(code);
break;
}
_ => continue,
}
}
for handle in handles {
handle.abort();
}
let mut valid_code = valid_code.ok_or_else(|| {
"SystemFaultEvent: KineticGuillotineViolation. All agents failed to generate valid code.".to_string()
})?;
let workspace_root = env::var("COREASON_WORKSPACE_ROOT")
.map_err(|_| "Epistemic Quarantine Breach: COREASON_WORKSPACE_ROOT environment variable is not defined.".to_string())?;
let workspace_dir = Path::new(&workspace_root).canonicalize()
.map_err(|e| format!("Failed to canonicalize workspace root: {}", e))?;
let target_file = Path::new(target_file_path);
let resolved_target = if target_file.is_absolute() {
target_file.to_path_buf()
} else {
workspace_dir.join(target_file)
};
let parent = resolved_target.parent().ok_or_else(|| "Target path must have a parent".to_string())?;
let canonical_parent = parent.canonicalize()
.map_err(|e| format!("Failed to canonicalize target parent directory: {}", e))?;
if !canonical_parent.starts_with(&workspace_dir) {
return Err("Epistemic Quarantine Breach: Unauthorized Path Traversal Detected.".to_string());
}
if resolved_target.is_dir() {
return Err(format!("Target path {:?} is a directory, not a file.", resolved_target));
}
let spdx_identifier = env::var("COREASON_SPDX_LICENSE")
.unwrap_or_else(|_| "LicenseRef-Prosperity-3.0".to_string());
let tenant_name = env::var("COREASON_TENANT_NAME")
.unwrap_or_else(|_| "CoReason, Inc".to_string());
let is_commercial = env::var("COREASON_COMMERCIAL_LICENSE")
.map(|v| v == "True")
.unwrap_or(false);
let mut valid_spdx = HashSet::new();
valid_spdx.insert("MIT");
valid_spdx.insert("Apache-2.0");
valid_spdx.insert("BSD-3-Clause");
valid_spdx.insert("Proprietary");
valid_spdx.insert("UNLICENSED");
valid_spdx.insert("LicenseRef-Prosperity-3.0");
let spdx_identifier = if valid_spdx.contains(spdx_identifier.as_str()) {
spdx_identifier
} else {
log::warn!("Invalid SPDX identifier '{}', falling back to LicenseRef-Prosperity-3.0", spdx_identifier);
"LicenseRef-Prosperity-3.0".to_string()
};
let license_header = if env::var("AST_GUILLOTINE_ACTIVE").map(|v| v == "True").unwrap_or(false) || !is_commercial {
format!(
"# Copyright (c) 2026 {}\n\
#\n\
# This software is proprietary and dual-licensed\n\
# Licensed under the Prosperity Public License 3.0 (the \"License\")\n\
# A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>\n\
# For details, see the LICENSE file\n\
# Commercial use beyond a 30-day trial requires a separate license\n\
# SPDX-License-Identifier: LicenseRef-Prosperity-3.0\n\n",
tenant_name
)
} else {
format!(
"# Copyright (c) 2026 {}\n# SPDX-License-Identifier: {}\n\n",
tenant_name, spdx_identifier
)
};
let stripped_code = valid_code.trim_start();
let first_line = license_header.lines().next().unwrap_or("");
if !stripped_code.starts_with(first_line) {
if stripped_code.starts_with("# Copyright (c)") {
return Err("Adversarial GuardrailViolationEvent: Unauthorized copyright/licensing header manipulation detected.".to_string());
}
valid_code = format!("{}{}", license_header, valid_code);
}
let urn_constant = format!("__ACTION_SPACE_CID__ = \"{}\"\n", action_space_id);
if !action_space_id.is_empty() && !valid_code.contains(&urn_constant) {
let has_license = valid_code.starts_with(&license_header);
let mut code_to_embed = if has_license {
valid_code[license_header.len()..].to_string()
} else {
valid_code.clone()
};
let trimmed = code_to_embed.trim_start();
if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
let quote_style = if trimmed.starts_with("\"\"\"") { "\"\"\"" } else { "'''" };
if let Some(first_idx) = code_to_embed.find(quote_style) {
if let Some(second_idx) = code_to_embed[first_idx + 3..].find(quote_style) {
let absolute_second_idx = first_idx + 3 + second_idx;
if let Some(newline_idx) = code_to_embed[absolute_second_idx..].find('\n') {
let insert_pos = absolute_second_idx + newline_idx + 1;
code_to_embed.insert_str(insert_pos, &format!("\n{}", urn_constant));
}
}
}
} else {
code_to_embed = format!("{}\n{}", urn_constant, code_to_embed);
}
valid_code = if has_license {
format!("{}{}", license_header, code_to_embed)
} else {
code_to_embed
};
}
let licenses_dir = workspace_dir.join("LICENSES");
if is_commercial && spdx_identifier != "LicenseRef-Prosperity-3.0" {
let _ = fs::create_dir_all(&licenses_dir);
let license_file = licenses_dir.join(format!("{}.txt", spdx_identifier));
if !license_file.exists() {
let file_content = format!(
"# {}\n\n\
Full license text for {} should be placed here.\n\
See https://spdx.org/licenses/{}.html\n",
spdx_identifier, spdx_identifier, spdx_identifier
);
let _ = fs::write(&license_file, file_content);
log::info!("Created LICENSES/{}.txt placeholder", spdx_identifier);
}
}
if let Some(signing_key) = resolve_signing_key() {
log::info!("Signing generated code asset: {:?}", resolved_target);
valid_code = sign_source_code(&valid_code, &signing_key);
}
fs::create_dir_all(resolved_target.parent().unwrap())
.map_err(|e| format!("Failed to create parent directories: {}", e))?;
fs::write(&resolved_target, &valid_code)
.map_err(|e| format!("Failed to write code to file {:?}: {}", resolved_target, e))?;
let file_hash = compute_canonical_hash(valid_code.as_bytes());
let hash_file = PathBuf::from(format!("{}.hash", resolved_target.to_string_lossy()));
fs::write(&hash_file, file_hash)
.map_err(|e| format!("Failed to write sidecar hash file {:?}: {}", hash_file, e))?;
Ok(valid_code)
}