refactor(nakui-core): KCL → Nickel — kcl_wrapper reemplazado por evaluación in-process

Cierra el plan original. El motor de validación de entities deja
de shellear el binario externo `kcl` y pasa a evaluar Nickel
contracts in-process via la dep nickel-lang (la misma que usa el
brazo de cards). Los 3 schemas de sales/inventory/treasury migran
de .k a .ncl.

nakui-core:
- Nueva dep nickel-lang = "2.0.0".
- Borrado kcl_wrapper.rs.
- Nuevo nickel_validator.rs con vet(schema_path, state, entity)
  que evalúa `let bundle = (import "<schema>") in
  (std.deserialize 'Json m%%"<json>"%%) | bundle.<entity>`.
- executor.rs: KclError → NickelError, KclPre/Post/PostCreate →
  SchemaPre/Post/PostCreate, kcl_check → validate_entity.
  build_schema_bundle ahora emite `(import "X") & (import "Y") & ...`
  en lugar de concatenar bytes (cada .ncl es expresión completa).
- manifest.rs: default schema "schema.ncl", extract_schema_names
  reescrito para sintaxis Nickel record (CapitalCase keys con
  2-space indent).

Schemas migrados:
- sales/schema.ncl: Venta con std.contract.Sequence [record,
  from_predicate] para combinar shape + invariante cross-field
  (total == cantidad * precio_unitario). El patrón directo
  `record | from_predicate` rebota con "missing definition" porque
  el predicate evalúa antes de que el value populate el record;
  documentado en cada schema.
- inventory/schema.ncl, treasury/schema.ncl: idem.
- 3 schema.k viejos borrados; sales/nsmc.json paths actualizados.

Tests: refs Kcl* renombradas; paths .k → .ncl; tests inline que
escribían schema.k cambian a schema.ncl con sintaxis Nickel.
84 tests verdes en nakui-core.

Doc-only borrados:
- crates/core/ente-card/schema/card.k (REFERENCE ONLY).
- crates/core/ente-brain/schema/rule.k (REFERENCE ONLY).

Beneficios: sin dep externa al binario `kcl` (build CI limpio),
errores Nickel en línea con caret pointing al field, mismo motor
que cards (una dep para todo el repo), sin tempfile JSON
intermedio.

Cierra el plan original yahweh + KCL + card.k. Pendientes salen
de nuevo trabajo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sergio
2026-05-10 02:59:48 +00:00
parent b3a99f38dc
commit b05de24c24
23 changed files with 690 additions and 573 deletions
+4
View File
@@ -31,6 +31,10 @@ uuid = { workspace = true, features = ["serde"] }
# por lo que se mantienen inline (versión local).
rhai = { version = "1.20", features = ["serde"] }
petgraph = "0.6"
# Nickel reemplaza a KCL como motor de validación de entities.
# Evaluación in-process (sin shellear binarios), contracts Nickel
# nativos en los `schema.ncl` de cada módulo.
nickel-lang = "2.0.0"
surrealdb = { version = "2", default-features = false, features = ["kv-mem"] }
# Brahman protocol — presencia ante el Init cuando `nakui run` arranca.
+60 -44
View File
@@ -7,7 +7,7 @@ use uuid::Uuid;
use crate::delta::{FieldOp, simulate_on};
use crate::graph::{GraphError, ManifestGraph};
use crate::kcl_wrapper::{self, KclError};
use crate::nickel_validator::{self, NickelError};
use crate::manifest::{ConserveRule, Manifest, ManifestError, MorphismSpec, ValidationError};
use crate::rhai_executor::{RhaiError, RhaiExecutor};
use crate::store::{Store, StoreError};
@@ -50,26 +50,26 @@ pub enum ExecError {
field: String,
message: String,
},
#[error("kcl pre-check failed on `{role}` ({entity}): {source}")]
KclPre {
#[error("schema pre-check failed on `{role}` ({entity}): {source}")]
SchemaPre {
role: String,
entity: String,
#[source]
source: KclError,
source: NickelError,
},
#[error("kcl post-check failed on `{role}` ({entity}): {source}")]
KclPost {
#[error("schema post-check failed on `{role}` ({entity}): {source}")]
SchemaPost {
role: String,
entity: String,
#[source]
source: KclError,
source: NickelError,
},
#[error("kcl post-check failed on created {entity} {id}: {source}")]
KclPostCreate {
#[error("schema post-check failed on created {entity} {id}: {source}")]
SchemaPostCreate {
entity: String,
id: Uuid,
#[source]
source: KclError,
source: NickelError,
},
#[error("rhai: {0}")]
Rhai(#[from] RhaiError),
@@ -95,12 +95,13 @@ pub struct Executor {
/// `load_module`; Drop removes it. `false` for inline-built executors
/// that point at a real schema file owned by the caller (tests).
pub owned_bundle: bool,
/// Per-morphism `schema_hash`: SHA-256 of (kcl bundle + manifest spec
/// + rhai script bytes), computed once at load. The hash is the
/// determinism contract for KCL evolution — `verify_log` uses it to
/// reject logs whose entries were produced under different rules.
/// Per-morphism `schema_hash`: SHA-256 of (Nickel bundle + manifest
/// spec + rhai script bytes), computed once at load. The hash es
/// el determinism contract para evolución de schemas —
/// `verify_log` lo usa para rechazar logs cuyos entries se
/// produjeron bajo reglas distintas.
pub schema_hashes: HashMap<String, [u8; 32]>,
/// Module-wide bundle hash: SHA-256 of just the KCL bundle bytes.
/// Module-wide bundle hash: SHA-256 de los bytes del bundle Nickel.
/// Stamped onto every `LogEntry::Seed` via `seed_and_log` so
/// `verify_log` can flag seeds whose entity schemas have evolved
/// since they were logged. Coarser than `schema_hashes` (any
@@ -252,8 +253,8 @@ impl Executor {
let state = store
.load(&spec_in.entity, id)
.ok_or_else(|| ExecError::EntityMissing(spec_in.entity.clone(), id))?;
self.kcl_check(&spec_in.entity, &state)
.map_err(|e| ExecError::KclPre {
self.validate_entity(&spec_in.entity, &state)
.map_err(|e| ExecError::SchemaPre {
role: spec_in.role.clone(),
entity: spec_in.entity.clone(),
source: e,
@@ -327,8 +328,8 @@ impl Executor {
if let Some(new_state) =
simulate_on(&loaded[&spec_in.role], &spec_in.entity, id, &ops)
{
self.kcl_check(&spec_in.entity, &new_state)
.map_err(|e| ExecError::KclPost {
self.validate_entity(&spec_in.entity, &new_state)
.map_err(|e| ExecError::SchemaPost {
role: spec_in.role.clone(),
entity: spec_in.entity.clone(),
source: e,
@@ -339,8 +340,8 @@ impl Executor {
// 8. Validate every Created record against its entity schema.
for op in &ops {
if let FieldOp::Create { entity, id, data } = op {
self.kcl_check(entity, data)
.map_err(|e| ExecError::KclPostCreate {
self.validate_entity(entity, data)
.map_err(|e| ExecError::SchemaPostCreate {
entity: entity.clone(),
id: *id,
source: e,
@@ -367,26 +368,16 @@ impl Executor {
Ok(ops)
}
fn kcl_check(&self, entity: &str, state: &Value) -> Result<(), KclError> {
let tmp = std::env::temp_dir().join(format!("nakui_{}_{}.json", entity, Uuid::new_v4()));
std::fs::write(&tmp, serde_json::to_vec(state).expect("state serializes"))
.map_err(KclError::Io)?;
let result = kcl_wrapper::vet(&self.schema_path, &tmp, entity);
let _ = std::fs::remove_file(&tmp);
result
fn validate_entity(&self, entity: &str, state: &Value) -> Result<(), NickelError> {
nickel_validator::vet(&self.schema_path, state, entity)
}
}
/// Concatenate every declared `.k` file into a single bundle on disk.
/// `kcl vet` only takes one schema arg, so cross-module modules (e.g. sales
/// referencing both treasury and inventory entities) bundle their imports
/// at load time. The bundle lives in `temp_dir` for the lifetime of the
/// executor; one file per Executor instance.
/// Module-wide hash of just the KCL bundle bytes. Stamped on
/// Module-wide hash of the Nickel bundle bytes. Stamped on
/// `LogEntry::Seed` entries (which don't run through any morphism, so
/// `compute_morphism_schema_hash` doesn't apply). Bumped by any byte
/// change in any schema file the manifest exposes — coarser than a
/// per-entity hash would be, but doesn't require KCL parsing.
/// per-entity hash would be, but doesn't require Nickel parsing.
fn compute_schema_bundle_hash(schema_bundle_bytes: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(b"nakui-bundle-v1\0");
@@ -514,18 +505,43 @@ pub fn normalize_rhai_source(src: &str) -> String {
out
}
fn build_schema_bundle(module_dir: &std::path::Path, schemas: &[String]) -> std::io::Result<PathBuf> {
let mut combined = String::new();
/// Construye un bundle Nickel: en lugar de concatenar contenidos
/// (cada `.ncl` es una expresión record completa, no juntable como
/// texto plano), emite un archivo que mergea via `&` los imports.
///
/// El operador `&` de Nickel mergea records: si las keys son
/// distintas (que es lo esperado entre schemas de módulos distintos)
/// el resultado tiene la unión. Si hay colisión, Nickel rebota con
/// un error claro al evaluar — ya cubierto por `manifest::validate`
/// que chequea duplicados antes de llegar acá.
///
/// Verifica que cada path exista para fallar early con I/O error.
/// El path en el `import "..."` queda absoluto (resuelto desde
/// `module_dir`) para que el evaluator lo encuentre desde el
/// tempdir.
fn build_schema_bundle(
module_dir: &std::path::Path,
schemas: &[String],
) -> std::io::Result<PathBuf> {
let mut imports: Vec<String> = Vec::with_capacity(schemas.len());
for s in schemas {
let p = module_dir.join(s);
let content = std::fs::read_to_string(&p)?;
combined.push_str("# --- ");
combined.push_str(p.to_string_lossy().as_ref());
combined.push_str(" ---\n");
combined.push_str(&content);
combined.push_str("\n\n");
// Verificar existencia + canonicalize para path absoluto
// estable (evita que cwd movimiento rompa el bundle).
let abs = std::fs::canonicalize(&p)?;
let abs_str = abs.display().to_string();
let escaped = abs_str.replace('\\', "\\\\").replace('"', "\\\"");
imports.push(format!("(import \"{escaped}\")"));
}
let bundle = std::env::temp_dir().join(format!("nakui_schema_{}.k", Uuid::new_v4()));
let combined = if imports.is_empty() {
// Bundle vacío = record vacío. Cualquier validación contra
// un entity rebota con "field not found" — comportamiento
// razonable para un módulo sin schemas declarados.
"{}".to_string()
} else {
imports.join(" & ")
};
let bundle = std::env::temp_dir().join(format!("nakui_schema_{}.ncl", Uuid::new_v4()));
std::fs::write(&bundle, combined)?;
Ok(bundle)
}
@@ -1,43 +0,0 @@
use std::path::Path;
use std::process::Command;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum KclError {
#[error("kcl binary not found on PATH (install: https://kcl-lang.io)")]
BinaryMissing,
#[error("kcl validation failed:\n{0}")]
ValidationFailed(String),
#[error("io invoking kcl: {0}")]
Io(#[from] std::io::Error),
}
/// Validate `state_path` (json) against a schema defined in `schema_path` (.k),
/// targeting the named schema.
pub fn vet(schema_path: &Path, state_path: &Path, schema_name: &str) -> Result<(), KclError> {
let out = match Command::new("kcl")
.arg("vet")
.arg(state_path)
.arg(schema_path)
.arg("-s")
.arg(schema_name)
.output()
{
Ok(o) => o,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(KclError::BinaryMissing),
Err(e) => return Err(e.into()),
};
if out.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
let msg = if stderr.trim().is_empty() {
stdout
} else {
stderr
};
Err(KclError::ValidationFailed(msg))
}
}
+1 -1
View File
@@ -3,8 +3,8 @@ pub mod drift;
pub mod event_log;
pub mod executor;
pub mod graph;
pub mod kcl_wrapper;
pub mod manifest;
pub mod nickel_validator;
pub mod rhai_executor;
pub mod run;
pub mod store;
+73 -27
View File
@@ -123,11 +123,12 @@ impl Manifest {
self.morphisms.iter().find(|m| m.name == name)
}
/// Schema files this module exposes. Defaults to `["schema.k"]` when
/// the manifest doesn't declare any explicitly.
/// Schema files this module exposes. Defaults to `["schema.ncl"]`
/// when the manifest doesn't declare any explicitly. Acepta
/// también legacy `.k` para no romper módulos no-migrados.
pub fn effective_schemas(&self) -> Vec<String> {
if self.schemas.is_empty() {
vec!["schema.k".to_string()]
vec!["schema.ncl".to_string()]
} else {
self.schemas.clone()
}
@@ -253,20 +254,47 @@ impl Manifest {
/// at column 0 (top-level). Tolerates inheritance (`schema X(Y):`) and
/// generic params (`schema X[T]:`); ignores comments and string literals
/// because top-level KCL syntax doesn't admit them ambiguously.
/// Extrae los nombres de entities declarados en un schema Nickel.
///
/// Convención de los `schema.ncl` de Nakui: el archivo evalúa a un
/// record top-level cuyas keys son los entity names (CapitalCase).
/// Las helpers locales (`let positive_int = ...`) no matchean
/// porque no están indentadas con 2 spaces ni empiezan con
/// mayúscula.
///
/// Heurística (no parser completo): líneas con exactamente 2 spaces
/// de indent + identifier CapitalCase + `=`. Robusto para los
/// schemas actuales; si futuras convenciones requieren otro
/// indent, flexibilizar acá.
fn extract_schema_names(content: &str) -> Vec<String> {
let mut out = Vec::new();
for line in content.lines() {
// Top-level declarations are not indented in idiomatic KCL.
if line.starts_with("schema ") {
let after = &line["schema ".len()..];
let name: String = after
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if !name.is_empty() {
out.push(name);
}
let trimmed = line.trim_start_matches(' ');
let leading_spaces = line.len() - trimmed.len();
if leading_spaces != 2 {
continue;
}
let first = match trimmed.chars().next() {
Some(c) => c,
None => continue,
};
if !first.is_ascii_uppercase() {
continue;
}
let name: String = trimmed
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if name.is_empty() {
continue;
}
// Después del identifier debe venir `=` (eventualmente
// tras whitespace).
let after = &trimmed[name.len()..];
if !after.trim_start().starts_with('=') {
continue;
}
out.push(name);
}
out
}
@@ -282,25 +310,43 @@ mod tests {
use super::*;
#[test]
fn extract_schema_names_handles_basic_forms() {
fn extract_schema_names_handles_nickel_record_top_level() {
let content = r#"
schema Caja:
saldo: int
let positive_int = std.contract.from_predicate (fun n => n > 0) in
let currency_iso = std.contract.from_predicate (fun s => true) in
schema Movimiento(Base):
monto: int
{
Caja = {
id | String,
saldo | positive_int,
},
# schema Comentario:
schema Generic[T]:
inner: T
Movimiento = {
id | String,
monto | positive_int,
} | std.contract.from_predicate (fun r => true),
schema _Underscore:
x: int
Transferencia = {
id | String,
},
}
"#;
let names = extract_schema_names(content);
assert_eq!(
names,
vec!["Caja", "Movimiento", "Generic", "_Underscore"]
);
assert_eq!(names, vec!["Caja", "Movimiento", "Transferencia"]);
}
#[test]
fn extract_schema_names_skips_let_bindings_and_lowercase() {
// `let x = ...` no debe aparecer; tampoco lowercase keys
// (no son entities por convención).
let content = r#"
let positive_int = ... in
{
Caja = { id | String },
helper = "not an entity",
}
"#;
let names = extract_schema_names(content);
assert_eq!(names, vec!["Caja"]);
}
}
@@ -0,0 +1,255 @@
//! Validador de entities via Nickel contracts (reemplaza el viejo
//! `kcl_wrapper` que shellea el binario `kcl`). Evaluación
//! in-process via `nickel-lang` 2.0.
//!
//! El bundle del módulo (concatenación de los `schema.ncl` que el
//! manifest declara) define un record con un field por entity. Para
//! validar un value V contra el entity E, evaluamos:
//!
//! ```nickel
//! let bundle = (import "<bundle>.ncl") in (V | bundle.E)
//! ```
//!
//! Si Nickel evalúa OK, V cumple el contract. Si rebota con
//! `BlameError` (contract violation), devolvemos
//! `NickelError::ValidationFailed` con el mensaje formateado.
//!
//! El bundle path es exactamente el archivo `.ncl` que arma
//! `Executor::load_module` en tempdir; el snapshot bytes que
//! computa el hash es el mismo archivo, así el `schema_bundle_hash`
//! sigue siendo determinista.
use std::path::Path;
use serde_json::Value;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum NickelError {
#[error("nickel validation failed:\n{0}")]
ValidationFailed(String),
#[error("io durante eval Nickel: {0}")]
Io(#[from] std::io::Error),
#[error("serializar state a Nickel literal: {0}")]
Serialize(#[from] serde_json::Error),
}
/// Valida `state` contra el entity `schema_name` declarado en el
/// bundle Nickel `schema_path`. Devuelve `Ok(())` si el contract
/// pasa, `Err(ValidationFailed(msg))` si rebota.
///
/// El nombre `vet` se preserva por compat con call sites del
/// executor (ex `kcl_wrapper::vet`).
pub fn vet(schema_path: &Path, state: &Value, schema_name: &str) -> Result<(), NickelError> {
// El state se inyecta como JSON literal y Nickel lo deserializa
// con `std.deserialize 'Json`. NO embebemos el state como
// record literal Nickel directo: la sintaxis JSON usa `:` (que
// Nickel no acepta dentro de records — usa `=`), y los keys
// quoted serían parseados como contracts en posición pre-`|`.
//
// El JSON va dentro de un raw string Nickel `m%%"..."%%`. JSON
// no contiene `"%%` literal (no hay forma de generarlo desde
// serde_json), así que el delimiter es seguro sin más
// escaping.
let state_json = serde_json::to_string(state)?;
let schema_path_str = schema_path.display().to_string();
let schema_path_escaped = schema_path_str.replace('\\', "\\\\").replace('"', "\\\"");
let source = format!(
"let bundle = (import \"{schema_path_escaped}\") in\n\
(std.deserialize 'Json m%%\"{state_json}\"%%) | bundle.{schema_name}"
);
let mut ctx = nickel_lang::Context::new()
.with_source_name(format!("nakui-validate-{schema_name}"));
match ctx.eval_deep_for_export(&source) {
Ok(_) => Ok(()),
Err(e) => Err(NickelError::ValidationFailed(format_nickel_error(&e))),
}
}
fn format_nickel_error(err: &nickel_lang::Error) -> String {
let mut buf: Vec<u8> = Vec::new();
if err
.format(&mut buf, nickel_lang::ErrorFormat::Text)
.is_err()
{
return format!("{err:?}");
}
String::from_utf8(buf).unwrap_or_else(|_| format!("{err:?}"))
}
#[cfg(test)]
mod tests {
//! Tests del validador via fixtures inline (write a tempfile,
//! evaluar). Cobertura del happy path + un par de
//! contract-violation cases.
use super::*;
use serde_json::json;
fn write_schema(content: &str) -> std::path::PathBuf {
let p = std::env::temp_dir().join(format!(
"nakui-test-schema-{}-{}.ncl",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&p, content).unwrap();
p
}
#[test]
fn vet_passes_when_state_satisfies_contract() {
let schema = write_schema(
r#"
{
Stock = {
id | String,
cantidad | std.contract.from_predicate (fun n => std.is_number n && n >= 0),
},
}
"#,
);
let state = json!({"id": "abc", "cantidad": 5});
vet(&schema, &state, "Stock").unwrap();
let _ = std::fs::remove_file(&schema);
}
#[test]
fn vet_rejects_when_field_missing() {
let schema = write_schema(
r#"
{
Stock = { id | String, cantidad | Number },
}
"#,
);
let state = json!({"id": "abc"}); // falta cantidad
let err = vet(&schema, &state, "Stock").unwrap_err();
assert!(matches!(err, NickelError::ValidationFailed(_)));
let NickelError::ValidationFailed(msg) = err else { panic!() };
assert!(
msg.to_lowercase().contains("cantidad") || msg.to_lowercase().contains("missing"),
"msg debe mencionar el field missing: {msg}"
);
let _ = std::fs::remove_file(&schema);
}
#[test]
fn vet_rejects_when_predicate_fails() {
let schema = write_schema(
r#"
{
Stock = {
id | String,
cantidad | std.contract.from_predicate (fun n => std.is_number n && n >= 0),
},
}
"#,
);
let state = json!({"id": "abc", "cantidad": -1});
let err = vet(&schema, &state, "Stock").unwrap_err();
assert!(matches!(err, NickelError::ValidationFailed(_)));
let _ = std::fs::remove_file(&schema);
}
/// Repro EXACTO del shape Transferencia del módulo treasury,
/// incluyendo el predicate cross-field. Reproduce el mismo
/// flujo que el rhai script emite.
#[test]
fn vet_transferencia_real_shape_passes() {
let schema = write_schema(
r#"
let positive_int = std.contract.from_predicate (fun n => std.is_number n && n > 0) in
let currency_iso = std.contract.from_predicate (fun s => std.is_string s && std.string.length s == 3) in
{
Transferencia = std.contract.Sequence [
{
id | String,
source_caja_id | String,
dest_caja_id | String,
monto | positive_int,
currency | currency_iso,
timestamp | String,
memo | String | optional,
},
std.contract.from_predicate (fun r =>
r.source_caja_id != r.dest_caja_id
),
],
}
"#,
);
let state = json!({
"currency": "USD",
"dest_caja_id": "8c0b58aa",
"id": "bb34ae84",
"memo": "xf",
"monto": 75000,
"source_caja_id": "233f780f",
"timestamp": "2026-05-04T10:30:00Z"
});
vet(&schema, &state, "Transferencia").unwrap();
let _ = std::fs::remove_file(&schema);
}
/// Repro del issue de la migración: Transferencia con
/// múltiples fields requeridos + uno optional. El contract
/// debería pasar si todos los required están presentes.
#[test]
fn vet_passes_with_optional_field_present_or_absent() {
let schema = write_schema(
r#"
{
Transferencia = {
id | String,
source_caja_id | String,
dest_caja_id | String,
memo | String | optional,
},
}
"#,
);
// Con memo presente.
let state = json!({
"id": "t1",
"source_caja_id": "c1",
"dest_caja_id": "c2",
"memo": "x"
});
vet(&schema, &state, "Transferencia").unwrap();
// Sin memo (opcional).
let state2 = json!({
"id": "t2",
"source_caja_id": "c1",
"dest_caja_id": "c2"
});
vet(&schema, &state2, "Transferencia").unwrap();
let _ = std::fs::remove_file(&schema);
}
#[test]
fn vet_rejects_when_cross_field_invariant_fails() {
let schema = write_schema(
r#"
{
Venta = {
cantidad | Number,
precio_unitario | Number,
total | Number,
} | std.contract.from_predicate (fun r =>
r.total == r.cantidad * r.precio_unitario
),
}
"#,
);
// total mal calculado: 5 * 200 = 1000, no 999.
let state = json!({"cantidad": 5, "precio_unitario": 200, "total": 999});
let err = vet(&schema, &state, "Venta").unwrap_err();
assert!(matches!(err, NickelError::ValidationFailed(_)));
let _ = std::fs::remove_file(&schema);
}
}
+3 -2
View File
@@ -219,8 +219,9 @@ fn executor_load_module_rejects_cyclic_manifest() {
let tmp = std::env::temp_dir().join(format!("nakui_cycle_{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(tmp.join("morphisms")).unwrap();
std::fs::write(
tmp.join("schema.k"),
"schema Caja:\n saldo: int\n check:\n saldo >= 0\n",
tmp.join("schema.ncl"),
// Schema Nickel mínimo (top-level Caja con saldo >= 0).
"{\n Caja = {\n saldo | std.contract.from_predicate (fun n => std.is_number n && n >= 0),\n },\n}\n",
)
.unwrap();
std::fs::write(tmp.join("morphisms/op.rhai"), "[]").unwrap();
+2 -2
View File
@@ -132,11 +132,11 @@ fn overdraw_transfer_blocked_by_kcl_post_check() {
);
match result {
Err(ExecError::KclPost { role, entity, .. }) => {
Err(ExecError::SchemaPost { role, entity, .. }) => {
assert_eq!(role, "source");
assert_eq!(entity, "Stock");
}
other => panic!("expected KclPost on source, got {:?}", other),
other => panic!("expected SchemaPost on source, got {:?}", other),
}
assert_eq!(cantidad(&store, a), 100);
assert_eq!(cantidad(&store, b), 0);
@@ -7,7 +7,7 @@
//! Layers exercised (in pipeline order):
//! 1. CapabilityViolation (untracked write)
//! 2. ConservationViolation (delta sum != 0)
//! 3. KclPostCreate (created record fails its schema)
//! 3. SchemaPostCreate (created record fails its schema)
use std::path::{Path, PathBuf};
@@ -47,7 +47,7 @@ fn build_executor(spec: MorphismSpec) -> Executor {
// schema_path stays on the real treasury schema so we exercise the
// production check blocks. `owned_bundle: false` so Drop leaves it
// alone — it belongs to the source tree.
schema_path: workspace_root().join("modules/treasury/schema.k"),
schema_path: workspace_root().join("modules/treasury/schema.ncl"),
rhai: RhaiExecutor::new_sandboxed(),
owned_bundle: false,
// Inline-built executors don't go through `load_module`, so they
@@ -282,10 +282,10 @@ fn bad_created_record_blocks_negative_movimiento() {
let result = exec.run(&mut store, "evil_create", &[("caja", caja_id)], params);
match result {
Err(ExecError::KclPostCreate { entity, .. }) => {
Err(ExecError::SchemaPostCreate { entity, .. }) => {
assert_eq!(entity, "Movimiento");
}
other => panic!("expected KclPostCreate, got {:?}", other),
other => panic!("expected SchemaPostCreate, got {:?}", other),
}
// Caja unchanged, Movimiento never landed.
@@ -195,25 +195,26 @@ fn rejects_missing_schema_file() {
#[test]
fn rejects_duplicate_schema_across_files() {
// Synthesize a tempdir with two .k files that both declare `schema X`.
// Synthesize a tempdir with two .ncl files that both declare
// `Caja` en el record top-level.
let tmp = std::env::temp_dir().join(format!("nakui_dup_{}", Uuid::new_v4()));
fs::create_dir_all(&tmp).unwrap();
fs::create_dir_all(tmp.join("morphisms")).unwrap();
fs::write(
tmp.join("a.k"),
"schema Caja:\n saldo: int\n check:\n saldo >= 0\n",
tmp.join("a.ncl"),
"{\n Caja = { saldo | Number },\n}\n",
)
.unwrap();
fs::write(
tmp.join("b.k"),
"schema Caja:\n monto: int\n check:\n monto >= 0\n",
tmp.join("b.ncl"),
"{\n Caja = { monto | Number },\n}\n",
)
.unwrap();
fs::write(tmp.join("morphisms/op.rhai"), "[]").unwrap();
let m = Manifest {
module: "dup".into(),
schemas: vec!["a.k".into(), "b.k".into()],
schemas: vec!["a.ncl".into(), "b.ncl".into()],
morphisms: vec![MorphismSpec {
name: "op".into(),
inputs: vec![MorphismInput {
@@ -231,8 +232,8 @@ fn rejects_duplicate_schema_across_files() {
match m.validate(&tmp) {
Err(ValidationError::DuplicateSchema { name, files }) => {
assert_eq!(name, "Caja");
assert!(files.contains(&"a.k".to_string()));
assert!(files.contains(&"b.k".to_string()));
assert!(files.contains(&"a.ncl".to_string()));
assert!(files.contains(&"b.ncl".to_string()));
}
other => panic!("expected DuplicateSchema, got {:?}", other),
}
@@ -247,8 +248,8 @@ fn executor_load_module_runs_validation() {
let tmp = std::env::temp_dir().join(format!("nakui_bad_{}", Uuid::new_v4()));
fs::create_dir_all(&tmp).unwrap();
fs::write(
tmp.join("schema.k"),
"schema Caja:\n saldo: int\n check:\n saldo >= 0\n",
tmp.join("schema.ncl"),
"{\n Caja = {\n saldo | std.contract.from_predicate (fun n => std.is_number n && n >= 0),\n },\n}\n",
)
.unwrap();
fs::write(
+2 -2
View File
@@ -120,11 +120,11 @@ fn overdraw_stock_rejected_by_inventory_post_check() {
);
match result {
Err(ExecError::KclPost { role, entity, .. }) => {
Err(ExecError::SchemaPost { role, entity, .. }) => {
assert_eq!(role, "stock");
assert_eq!(entity, "Stock");
}
other => panic!("expected KclPost on stock, got {:?}", other),
other => panic!("expected SchemaPost on stock, got {:?}", other),
}
assert_eq!(stock_cantidad(&store, stock), 500);
assert_eq!(caja_saldo(&store, caja), 1_000_000);
@@ -348,10 +348,10 @@ fn verify_log_rejects_seed_after_schema_kcl_changes() {
seed_caja(&exec, &mut store, &mut log, id);
}
// Mutate schema.k. Even a comment is enough — bundle hash is byte-
// Mutate schema.ncl. Even a comment is enough — bundle hash is byte-
// level for the same false-positive-over-false-negative reason as
// morphism hashes.
let schema_path = temp.path.join("schema.k");
let schema_path = temp.path.join("schema.ncl");
let original = std::fs::read_to_string(&schema_path).expect("read schema");
std::fs::write(
&schema_path,
@@ -361,7 +361,7 @@ fn verify_log_rejects_seed_after_schema_kcl_changes() {
let exec2 = Executor::load_module(&temp.path).expect("reload v2");
let new_hash = exec2.schema_bundle_hash;
assert_ne!(original_hash, new_hash, "schema.k byte change must move the bundle hash");
assert_ne!(original_hash, new_hash, "schema.ncl byte change must move the bundle hash");
let log = EventLog::open(&log_path).unwrap();
match verify_log(&log, &exec2) {
@@ -410,13 +410,13 @@ fn comment_only_edits_do_not_invalidate_the_hash() {
"comment-only and whitespace-only edits must not move the hash"
);
// Sanity: the bundle hash also stays intact (we didn't touch schema.k).
// Sanity: the bundle hash also stays intact (we didn't touch schema.ncl).
assert_eq!(exec1.schema_bundle_hash, exec2.schema_bundle_hash);
}
#[test]
fn morphism_script_change_does_not_flag_unrelated_seeds() {
// Bundle hash covers schema.k only — a .rhai edit moves the
// Bundle hash covers schema.ncl only — a .rhai edit moves the
// morphism hash but leaves the bundle hash alone. So existing
// seeds verify cleanly even when a morphism's behaviour changed.
let temp = TempModule::from(&treasury_module());