Compare commits

..

5 Commits

Author SHA1 Message Date
will.anderson 1011d8e5be regen dist: rebuild soul.c from corrected sources (OOM gone, Track B compiled in)
Neuron Soul CI / build (pull_request) Successful in 4m12s
Neuron Soul CI / deploy (pull_request) Has been skipped
Regenerates the combined dist/soul.c and per-module dist/*.c from the current
El sources, on top of the elc-source-typo fixes (PR #77) and the Track B
threat-to-others routing (PR #76), both already on this branch.

Validated end to end under a physical-RSS watchdog (macOS silently ignores
ulimit -v / RLIMIT_AS, so every elc/elb run was RSS-polled and kill -9'd at a
3GB ceiling, one module at a time):

- OOM is GONE. The stale dist/soul-with-nlg.el (which still carries the
  malformed string literals) explodes to 3.3GB+ and is watchdog-killed at ~90%.
  With the typos fixed, every one of the 48 modules compiles at <=18MB peak RSS,
  and the full flat amalgamation compiles as a single translation unit at ~68MB.
  The 700GB pathology was purely the unbounded-parser-on-malformed-literal loop;
  no malformed construct means no loop.
- The regenerated soul.c contains Track B: safety_classify_hard_bell ->
  threat_other -> safety_hard_directive routes credible threat-to-others to 911
  and explicitly NOT to 988 / the safety contact. Verified in source, in the
  emitted C, and in the linked binary's strings. Track A (abuse / self_harm)
  is unchanged and still checked first.
- The regenerated soul links to a working native arm64 binary and boots: serves
  on a throwaway port, /health returns 200, awareness loop runs.

Also fixes one source blocker discovered during regen (unrelated to the typos
or Track B): chat.el handle_chat_agentic left a void `if { println(...) }` in
value position, which the current elc lowers to `_if_result = (println(...))`
(assigning void) -> invalid C. Bound an explicit Bool so the branch is
non-void; behavior unchanged (still only logs on persist failure).

NOTE (runtime dependency, for controlled deploy): this branch's chat.el calls
engram_get_node_by_label, which the canonical el-compiler/runtime does not yet
declare/define (the release runtime v1.0.0-20260501 has it; the newest runtime
has arena + http_serve_async but not this). Building the soul requires a runtime
that has all three. Land engram_get_node_by_label into the runtime package
before this soul.c can be built in CI.

Do not merge — regen + Track B going live is a controlled-deploy call.
2026-07-14 18:45:14 -05:00
will.anderson b0fb2bf085 safety/sessions: fix malformed string literals that crash elc
Neuron Soul CI / build (pull_request) Successful in 4m11s
Neuron Soul CI / deploy (pull_request) Has been skipped
Three unescaped-quote typos produced malformed El string literals that broke
compilation:

- safety.el:282  stray extra double-quote at the tail of safety_soft_phrases
  (\"having a breakdown\""]") closed the string early, desyncing the lexer's
  string/code phase for the rest of the file and shattering later apostrophe
  text (can't, i'm) into bare identifiers -> invalid C.
- sessions.el:517  str_replace(topic_snip, """, ...) — the bare """ is an
  empty string plus an unterminated string that swallowed the closing ) and };
  with the current elc this triggers the parser overrun -> ~700GB OOM.
- sessions.el:520  unescaped nested quotes in the topic_tags literal.

All three now use escaped inner quotes. Verified: both files compile clean
under the current elc (safety.c and sessions.c well-formed, brace-balanced).
2026-07-14 14:21:45 -05:00
will.anderson 3bb88330da safety: route threat-to-others to refusal+911, not 988/self-harm (Track B)
Neuron Soul CI / build (pull_request) Successful in 6m7s
Neuron Soul CI / deploy (pull_request) Has been skipped
A homicide/assault threat (going to kill, going to hurt, etc.) had no
bucket in safety_classify_hard_bell and fell through to the self_harm
default, showing the user the 988 suicide line and (via the desktop gate)
their safety contact. That framing is wrong and potentially dangerous for
someone voicing intent to harm another person.

Add a distinct Track B (safety_threat_to_others_phrases + a threat_other
classification and a safety_hard_directive branch) that refuses to assist,
de-escalates, and directs to 911 for a credible imminent threat, and that
never surfaces 988 or involves the safety contact. Track A (abuse /
self_harm) is checked first and unchanged, so victim and self-directed
phrasings still route correctly.

Source-only change: requires a soul rebuild + dist/soul.c regen to ship.
2026-07-14 12:12:20 -05:00
will.anderson c8cb425412 soul: per-tick arena bracketing in awareness_run + hand-patched dist/soul.c
Neuron Soul CI / build (push) Successful in 5m14s
Neuron Soul CI / deploy (push) Failing after 10m9s
awareness_run's while-loop ran outside any request arena, so every
allocation in every 1s tick (search JSON, heartbeat payloads, curiosity
activations) was treated as permanent by the runtime — 7.5GB RSS in
under a minute. Bracket each iteration with el_arena_push/el_arena_pop
(same pattern the compiler emits for scoped blocks; state_set/state_get
persist separately via el_strdup_persist and are unaffected).

dist/soul.c carries the same change hand-patched at the compiled
awareness_run site — elc is currently unsafe to run locally (pathological
memory on sessions.el), so the generated C was patched to match the
source, verified line-for-line against the compiler's own conventions.

MUST be paired with el repo PR #64 (el_strdup_persist for stored engram
fields): per-tick arena reclamation widens the write-corruption window
without it. Verified together: 5h live soak on the recovered production
snapshot, flat RSS, write-field-integrity clean.

Note: dist/soul.c still needs a full elc regen to pick up PR #73's
source changes (consent tiers) — tracked separately; this patch does not
regress that (those changes were never in dist).
2026-07-13 16:24:15 -05:00
will.anderson 3e7aa0fff4 Merge pull request 'BUG-8 — engine-side agent consent tiers + run_command workspace fence (needs soul.c regen)' (#73) from feat/agent-phase1-soul into main
Neuron Soul CI / build (push) Successful in 7m35s
Neuron Soul CI / deploy (push) Failing after 5m41s
2026-07-13 16:22:03 +00:00
30 changed files with 5824 additions and 30393 deletions
+19
View File
@@ -527,9 +527,27 @@ fn awareness_run() -> Void {
let scan_ms: Int = beat_ms / 2
while true {
// Arena-scope each tick: awareness_run() is a background loop, not an
// HTTP request, so nothing ever called el_request_start/el_request_end
// for this thread. Per the runtime's own convention (el_runtime.c),
// any thread that never enters a request/arena scope is treated as a
// one-shot CLI program whose allocations are intentionally permanent —
// so every el_strdup/el_strbuf/jb_finish string built during perceive(),
// emit_heartbeat(), and proactive_curiosity() (JSON payloads, search
// results, string concatenation via +) leaked forever, once per tick.
// el_arena_push()/el_arena_pop() are the same builtins the EL compiler
// itself uses to scope allocations per function/statement (see
// codegen.el's fn_arena_mark / stmt_mark usage) — mirroring that here
// reclaims everything allocated in one tick as soon as the tick ends.
// Safe: state_set/state_get persist through a separate global table
// (el_strdup_persist, outside the arena) — state_get's return value is
// only an arena-tracked *copy* of the persisted value, scoped to this
// tick's use, which is exactly what should be reclaimed here.
let tick_mark: Any = el_arena_push()
let running: String = state_get("soul.running")
if str_eq(running, "false") {
println("[awareness] exiting")
el_arena_pop(tick_mark)
return ""
}
let did_work: Bool = one_cycle()
@@ -593,6 +611,7 @@ fn awareness_run() -> Void {
}
sleep_ms(tick_ms)
el_arena_pop(tick_mark)
}
}
+1
View File
@@ -7,6 +7,7 @@ extern fn elapsed_ms() -> Int
extern fn elapsed_human() -> String
extern fn embed_ok() -> Int
extern fn emit_heartbeat() -> Void
extern fn auto_term_try_slot(slot_type: String, slot_lbl: String) -> Void
extern fn proactive_curiosity() -> Bool
extern fn pulse_count() -> Int
extern fn pulse_inc() -> Int
+10 -2
View File
@@ -2097,9 +2097,17 @@ fn handle_chat_agentic(body: String) -> String {
el_from_float(0.6), el_from_float(0.7), el_from_float(0.8),
"Episodic", sess_hist_tags
)
if str_eq(sess_hist_id, "") {
// NOTE: bind an explicit Bool value here. A bare `if { println(...) }`
// leaves a void-typed branch in value position, which the current elc
// lowers to `_if_result = (println(...))` invalid C. Yielding a value
// keeps the branch non-void without changing behavior (still only logs).
let persist_ok: Bool = if str_eq(sess_hist_id, "") {
println("[chat] agentic: named session history persist failed for session=" + req_session)
}
false
} else { true }
persist_ok
} else {
false
}
}
true
+6
View File
@@ -17,7 +17,9 @@ extern fn id_in_seen(node_id: String, seen: String) -> Bool
extern fn add_to_seen(seen: String, node_id: String) -> String
extern fn engram_extract_ids(nodes_json: String) -> String
extern fn engram_compile(intent: String) -> String
extern fn distill_transcript(transcript: String) -> String
extern fn json_safe(s: String) -> String
extern fn current_engine_note(model: String) -> String
extern fn build_system_prompt(ctx: String, chat_mode: Bool) -> String
extern fn hist_append(hist: String, role: String, content: String) -> String
extern fn hist_trim(hist: String) -> String
@@ -30,6 +32,10 @@ extern fn handle_chat(body: String) -> String
extern fn handle_see(body: String) -> String
extern fn studio_tools_json() -> String
extern fn agentic_api_key() -> String
extern fn llm_base_url() -> String
extern fn llm_wire_format() -> String
extern fn json_escape(s: String) -> String
extern fn openai_chat_complete(model: String, base_url: String, api_key: String, safe_sys: String, messages_json: String) -> String
extern fn agentic_tools_literal() -> String
extern fn agentic_tools_with_web() -> String
extern fn connector_tools_json() -> String
Generated Vendored
+3
View File
@@ -419,9 +419,11 @@ el_val_t awareness_run(void) {
el_val_t beat_ms = ({ el_val_t _if_result_5 = 0; if (str_eq(beat_ms_raw, EL_STR(""))) { _if_result_5 = (60000); } else { _if_result_5 = (str_to_int(beat_ms_raw)); } _if_result_5; });
el_val_t scan_ms = (beat_ms / 2);
while (1) {
el_val_t tick_mark = el_arena_push();
el_val_t running = state_get(EL_STR("soul.running"));
if (str_eq(running, EL_STR("false"))) {
println(EL_STR("[awareness] exiting"));
el_arena_pop(tick_mark);
return EL_STR("");
}
el_val_t did_work = one_cycle();
@@ -469,6 +471,7 @@ el_val_t awareness_run(void) {
state_set(EL_STR("soul.last_refresh_ts"), int_to_str(now_ts));
}
sleep_ms(tick_ms);
el_arena_pop(tick_mark);
}
return 0;
}
Generated Vendored
+1
View File
@@ -7,6 +7,7 @@ extern fn elapsed_ms() -> Int
extern fn elapsed_human() -> String
extern fn embed_ok() -> Int
extern fn emit_heartbeat() -> Void
extern fn auto_term_try_slot(slot_type: String, slot_lbl: String) -> Void
extern fn proactive_curiosity() -> Bool
extern fn pulse_count() -> Int
extern fn pulse_inc() -> Int
Generated Vendored
+393 -179
View File
File diff suppressed because one or more lines are too long
Generated Vendored
+11
View File
@@ -17,7 +17,9 @@ extern fn id_in_seen(node_id: String, seen: String) -> Bool
extern fn add_to_seen(seen: String, node_id: String) -> String
extern fn engram_extract_ids(nodes_json: String) -> String
extern fn engram_compile(intent: String) -> String
extern fn distill_transcript(transcript: String) -> String
extern fn json_safe(s: String) -> String
extern fn current_engine_note(model: String) -> String
extern fn build_system_prompt(ctx: String, chat_mode: Bool) -> String
extern fn hist_append(hist: String, role: String, content: String) -> String
extern fn hist_trim(hist: String) -> String
@@ -26,10 +28,15 @@ extern fn clean_llm_response(s: String) -> String
extern fn conv_history_persist(hist: String) -> Void
extern fn conv_history_load() -> String
extern fn session_preload_bullets(nodes: String, max_bullets: Int, snip_len: Int) -> String
extern fn affective_context_prefix() -> String
extern fn handle_chat(body: String) -> String
extern fn handle_see(body: String) -> String
extern fn studio_tools_json() -> String
extern fn agentic_api_key() -> String
extern fn llm_base_url() -> String
extern fn llm_wire_format() -> String
extern fn json_escape(s: String) -> String
extern fn openai_chat_complete(model: String, base_url: String, api_key: String, safe_sys: String, messages_json: String) -> String
extern fn agentic_tools_literal() -> String
extern fn agentic_tools_with_web() -> String
extern fn connector_tools_json() -> String
@@ -40,6 +47,10 @@ extern fn call_neuron_mcp(tool_name: String, args: String) -> String
extern fn agent_workspace_root() -> String
extern fn path_within_root(path: String, root: String) -> Bool
extern fn resolve_in_root(path: String, root: String) -> String
extern fn run_command_is_readonly(cmd: String) -> Bool
extern fn cmd_abs_escape_at(cmd: String, root: String, needle: String) -> Bool
extern fn run_command_guard(cmd: String, root: String) -> String
extern fn classify_tool_risk(tool_name: String, tool_input: String) -> String
extern fn dispatch_tool(tool_name: String, tool_input: String) -> String
extern fn is_builtin_tool(tool_name: String) -> Bool
extern fn next_bridge_id() -> String
Generated Vendored
+13
View File
@@ -143,6 +143,19 @@ el_val_t mem_boot_count_get(void) {
el_val_t mem_boot_count_inc(void) {
el_val_t current = mem_boot_count_get();
el_val_t next = (current + 1);
el_val_t old_results = engram_search_json(EL_STR("soul:boot_count"), 50);
if (!str_eq(old_results, EL_STR("")) && !str_eq(old_results, EL_STR("[]"))) {
el_val_t old_len = json_array_len(old_results);
el_val_t oi = 0;
while (oi < old_len) {
el_val_t old_node = json_array_get(old_results, oi);
el_val_t old_id = json_get(old_node, EL_STR("id"));
if (!str_eq(old_id, EL_STR(""))) {
engram_forget(old_id);
}
oi = (oi + 1);
}
}
el_val_t content = el_str_concat(EL_STR("soul:boot_count:"), int_to_str(next));
el_val_t tags = EL_STR("[\"soul-meta\",\"boot-counter\"]");
el_val_t boot_node_id = engram_node_full(content, EL_STR("Memory"), EL_STR("soul:boot_count"), el_from_float(0.9), el_from_float(0.9), el_from_float(1.0), EL_STR("Canonical"), tags);
Generated Vendored
+42 -7
View File
@@ -25,6 +25,7 @@ el_val_t elapsed_ms(void);
el_val_t elapsed_human(void);
el_val_t embed_ok(void);
el_val_t emit_heartbeat(void);
el_val_t auto_term_try_slot(el_val_t slot_type, el_val_t slot_lbl);
el_val_t proactive_curiosity(void);
el_val_t pulse_count(void);
el_val_t pulse_inc(void);
@@ -59,7 +60,9 @@ el_val_t id_in_seen(el_val_t node_id, el_val_t seen);
el_val_t add_to_seen(el_val_t seen, el_val_t node_id);
el_val_t engram_extract_ids(el_val_t nodes_json);
el_val_t engram_compile(el_val_t intent);
el_val_t distill_transcript(el_val_t transcript);
el_val_t json_safe(el_val_t s);
el_val_t current_engine_note(el_val_t model);
el_val_t build_system_prompt(el_val_t ctx, el_val_t chat_mode);
el_val_t hist_append(el_val_t hist, el_val_t role, el_val_t content);
el_val_t hist_trim(el_val_t hist);
@@ -68,10 +71,15 @@ el_val_t clean_llm_response(el_val_t s);
el_val_t conv_history_persist(el_val_t hist);
el_val_t conv_history_load(void);
el_val_t session_preload_bullets(el_val_t nodes, el_val_t max_bullets, el_val_t snip_len);
el_val_t affective_context_prefix(void);
el_val_t handle_chat(el_val_t body);
el_val_t handle_see(el_val_t body);
el_val_t studio_tools_json(void);
el_val_t agentic_api_key(void);
el_val_t llm_base_url(void);
el_val_t llm_wire_format(void);
el_val_t json_escape(el_val_t s);
el_val_t openai_chat_complete(el_val_t model, el_val_t base_url, el_val_t api_key, el_val_t safe_sys, el_val_t messages_json);
el_val_t agentic_tools_literal(void);
el_val_t agentic_tools_with_web(void);
el_val_t connector_tools_json(void);
@@ -82,6 +90,10 @@ el_val_t call_neuron_mcp(el_val_t tool_name, el_val_t args);
el_val_t agent_workspace_root(void);
el_val_t path_within_root(el_val_t path, el_val_t root);
el_val_t resolve_in_root(el_val_t path, el_val_t root);
el_val_t run_command_is_readonly(el_val_t cmd);
el_val_t cmd_abs_escape_at(el_val_t cmd, el_val_t root, el_val_t needle);
el_val_t run_command_guard(el_val_t cmd, el_val_t root);
el_val_t classify_tool_risk(el_val_t tool_name, el_val_t tool_input);
el_val_t dispatch_tool(el_val_t tool_name, el_val_t tool_input);
el_val_t is_builtin_tool(el_val_t tool_name);
el_val_t next_bridge_id(void);
@@ -161,9 +173,19 @@ el_val_t session_list(void);
el_val_t session_get(el_val_t session_id);
el_val_t session_delete(el_val_t session_id);
el_val_t session_update_patch(el_val_t session_id, el_val_t body);
el_val_t session_search_entry(el_val_t node);
el_val_t session_search(el_val_t query);
el_val_t session_hist_load(el_val_t session_id);
el_val_t session_hist_save(el_val_t session_id, el_val_t hist);
el_val_t session_update_meta_timestamp(el_val_t session_id);
el_val_t session_auto_title(el_val_t session_id, el_val_t first_message);
el_val_t handle_session_approve(el_val_t session_id, el_val_t body);
el_val_t init_soul_edges(void);
el_val_t load_identity_context(void);
el_val_t seed_persona_from_env(void);
el_val_t emit_session_start_event(void);
el_val_t layered_cycle(el_val_t raw_input);
el_val_t flag_true(el_val_t body, el_val_t key);
el_val_t rate_limit_check(el_val_t ip, el_val_t path);
el_val_t strip_query(el_val_t path);
el_val_t err_404(el_val_t path);
@@ -179,6 +201,11 @@ el_val_t connectd_post(el_val_t suffix, el_val_t body);
el_val_t handle_connectors(el_val_t method, el_val_t clean, el_val_t body);
el_val_t handle_request(el_val_t method, el_val_t path, el_val_t body);
el_val_t flag_true(el_val_t body, el_val_t key) {
return (json_get_bool(body, key) || (json_get_int(body, key) > 0));
return 0;
}
el_val_t rate_limit_check(el_val_t ip, el_val_t path) {
if (str_eq(path, EL_STR("/health"))) {
return EL_STR("");
@@ -523,13 +550,21 @@ el_val_t handle_request(el_val_t method, el_val_t path, el_val_t body) {
if (str_starts_with(clean, EL_STR("/api/connectors"))) {
return handle_connectors(method, clean, body);
}
if (str_starts_with(clean, EL_STR("/api/run-progress/"))) {
el_val_t rp_id = str_slice(clean, 18, str_len(clean));
if (!str_eq(rp_id, EL_STR(""))) {
el_val_t rp_raw = state_get(el_str_concat(EL_STR("run_progress_"), rp_id));
el_val_t rp_arr = ({ el_val_t _if_result_25 = 0; if (str_eq(rp_raw, EL_STR(""))) { _if_result_25 = (EL_STR("[]")); } else { _if_result_25 = (el_str_concat(el_str_concat(EL_STR("["), rp_raw), EL_STR("]"))); } _if_result_25; });
return el_str_concat(el_str_concat(EL_STR("{\"progress\":"), rp_arr), EL_STR("}"));
}
}
if (str_eq(clean, EL_STR("/api/sessions"))) {
return session_list();
}
if (str_starts_with(clean, EL_STR("/api/sessions/"))) {
el_val_t gs_after = str_slice(clean, 14, str_len(clean));
el_val_t gs_slash = str_index_of(gs_after, EL_STR("/"));
el_val_t gs_id = ({ el_val_t _if_result_25 = 0; if ((gs_slash < 0)) { _if_result_25 = (gs_after); } else { _if_result_25 = (str_slice(gs_after, 0, gs_slash)); } _if_result_25; });
el_val_t gs_id = ({ el_val_t _if_result_26 = 0; if ((gs_slash < 0)) { _if_result_26 = (gs_after); } else { _if_result_26 = (str_slice(gs_after, 0, gs_slash)); } _if_result_26; });
if (!str_eq(gs_id, EL_STR(""))) {
return session_get(gs_id);
}
@@ -543,14 +578,14 @@ el_val_t handle_request(el_val_t method, el_val_t path, el_val_t body) {
if (str_starts_with(clean, EL_STR("/api/sessions/")) && str_ends_with(clean, EL_STR("/tool_result"))) {
el_val_t after = str_slice(clean, 14, str_len(clean));
el_val_t slash = str_index_of(after, EL_STR("/"));
el_val_t session_id = ({ el_val_t _if_result_26 = 0; if ((slash < 0)) { _if_result_26 = (after); } else { _if_result_26 = (str_slice(after, 0, slash)); } _if_result_26; });
el_val_t session_id = ({ el_val_t _if_result_27 = 0; if ((slash < 0)) { _if_result_27 = (after); } else { _if_result_27 = (str_slice(after, 0, slash)); } _if_result_27; });
return handle_tool_result(session_id, body);
}
if (str_starts_with(clean, EL_STR("/api/sessions/"))) {
el_val_t sess_after = str_slice(clean, 14, str_len(clean));
el_val_t sess_slash = str_index_of(sess_after, EL_STR("/"));
el_val_t sess_id = ({ el_val_t _if_result_27 = 0; if ((sess_slash < 0)) { _if_result_27 = (sess_after); } else { _if_result_27 = (str_slice(sess_after, 0, sess_slash)); } _if_result_27; });
el_val_t sess_sub = ({ el_val_t _if_result_28 = 0; if ((sess_slash < 0)) { _if_result_28 = (EL_STR("")); } else { _if_result_28 = (str_slice(sess_after, (sess_slash + 1), str_len(sess_after))); } _if_result_28; });
el_val_t sess_id = ({ el_val_t _if_result_28 = 0; if ((sess_slash < 0)) { _if_result_28 = (sess_after); } else { _if_result_28 = (str_slice(sess_after, 0, sess_slash)); } _if_result_28; });
el_val_t sess_sub = ({ el_val_t _if_result_29 = 0; if ((sess_slash < 0)) { _if_result_29 = (EL_STR("")); } else { _if_result_29 = (str_slice(sess_after, (sess_slash + 1), str_len(sess_after))); } _if_result_29; });
if (!str_eq(sess_id, EL_STR("")) && str_eq(sess_sub, EL_STR("approve"))) {
return handle_session_approve(sess_id, body);
}
@@ -574,7 +609,7 @@ el_val_t handle_request(el_val_t method, el_val_t path, el_val_t body) {
}
el_val_t agentic_flag = json_get_bool(body, EL_STR("agentic"));
el_val_t req_mode = json_get(body, EL_STR("mode"));
el_val_t reply = ({ el_val_t _if_result_29 = 0; if (str_eq(req_mode, EL_STR("plan"))) { _if_result_29 = (handle_chat_plan(body)); } else { _if_result_29 = (({ el_val_t _if_result_30 = 0; if (agentic_flag) { _if_result_30 = (handle_chat_agentic(body)); } else { el_val_t screened_reply = layered_cycle(raw_msg); _if_result_30 = (screened_reply); } _if_result_30; })); } _if_result_29; });
el_val_t reply = ({ el_val_t _if_result_30 = 0; if (str_eq(req_mode, EL_STR("plan"))) { _if_result_30 = (handle_chat_plan(body)); } else { _if_result_30 = (({ el_val_t _if_result_31 = 0; if (agentic_flag) { _if_result_31 = (handle_chat_agentic(body)); } else { el_val_t screened_reply = layered_cycle(raw_msg); _if_result_31 = (screened_reply); } _if_result_31; })); } _if_result_30; });
auto_persist(body, reply);
return reply;
}
@@ -698,7 +733,7 @@ el_val_t handle_request(el_val_t method, el_val_t path, el_val_t body) {
if (str_starts_with(clean, EL_STR("/api/sessions/"))) {
el_val_t del_after = str_slice(clean, 14, str_len(clean));
el_val_t del_slash = str_index_of(del_after, EL_STR("/"));
el_val_t del_id = ({ el_val_t _if_result_31 = 0; if ((del_slash < 0)) { _if_result_31 = (del_after); } else { _if_result_31 = (str_slice(del_after, 0, del_slash)); } _if_result_31; });
el_val_t del_id = ({ el_val_t _if_result_32 = 0; if ((del_slash < 0)) { _if_result_32 = (del_after); } else { _if_result_32 = (str_slice(del_after, 0, del_slash)); } _if_result_32; });
if (!str_eq(del_id, EL_STR(""))) {
return session_delete(del_id);
}
@@ -709,7 +744,7 @@ el_val_t handle_request(el_val_t method, el_val_t path, el_val_t body) {
if (str_starts_with(clean, EL_STR("/api/sessions/"))) {
el_val_t patch_after = str_slice(clean, 14, str_len(clean));
el_val_t patch_slash = str_index_of(patch_after, EL_STR("/"));
el_val_t patch_id = ({ el_val_t _if_result_32 = 0; if ((patch_slash < 0)) { _if_result_32 = (patch_after); } else { _if_result_32 = (str_slice(patch_after, 0, patch_slash)); } _if_result_32; });
el_val_t patch_id = ({ el_val_t _if_result_33 = 0; if ((patch_slash < 0)) { _if_result_33 = (patch_after); } else { _if_result_33 = (str_slice(patch_after, 0, patch_slash)); } _if_result_33; });
if (!str_eq(patch_id, EL_STR(""))) {
return session_update_patch(patch_id, body);
}
Generated Vendored
+1
View File
@@ -1,4 +1,5 @@
// auto-generated by elc --emit-header — do not edit
extern fn flag_true(body: String, key: String) -> Bool
extern fn rate_limit_check(ip: String, path: String) -> String
extern fn strip_query(path: String) -> String
extern fn err_404(path: String) -> String
Generated Vendored
+169 -18
View File
@@ -30,7 +30,12 @@ el_val_t safety_log_bell(el_val_t level, el_val_t reason, el_val_t input_summary
el_val_t safety_self_harm_phrases(void);
el_val_t safety_abuse_phrases(void);
el_val_t safety_general_hard_phrases(void);
el_val_t safety_threat_to_others_phrases(void);
el_val_t safety_soft_phrases(void);
el_val_t safety_normalize(el_val_t message);
el_val_t safety_any_match(el_val_t text, el_val_t phrases_json);
el_val_t safety_count_match(el_val_t text, el_val_t phrases_json);
el_val_t safety_positive_phrases(void);
el_val_t safety_detect_positive_level(el_val_t message);
el_val_t safety_detect_bell_level(el_val_t message);
el_val_t safety_classify_hard_bell(el_val_t message);
@@ -196,24 +201,170 @@ el_val_t safety_general_hard_phrases(void) {
return 0;
}
el_val_t safety_soft_phrases(void) {
return EL_STR("[\"stressed\",\"overwhelmed\",\"can't cope\",\"cannot cope\",\"struggling\",\"anxious\",\"anxiety\",\"depressed\",\"depression\",\"lonely\",\"isolated\",\"hopeless\",\"hopelessness\",\"exhausted\",\"burnt out\",\"burned out\",\"burnout\",\"panic\",\"panicking\",\"falling apart\",\"breaking down\",\"can't handle\",\"cannot handle\",\"losing it\",\"nothing matters\",\"don't care anymore\",\"given up\",\"giving up\",\"helpless\",\"worthless\",\"useless\",\"hate myself\",\"no one cares\",\"nobody cares\",\"no one understands\",\"nobody understands\",\"empty inside\",\"can't stop crying\",\"breaking point\",\"at my limit\",\"having a breakdown\"");
EL_NULL;
EL_STR("\n}\n\n// ISSUE 5 TODO: phrase lists are rebuilt from JSON literals on every call.\n// safety_any_match and safety_count_match loop over json_array_get on every invocation.\n// A compiled/cached representation would reduce per-message overhead and also guard against\n// malformed phrase JSON (json_array_len of malformed input returns 0, silently skipping all checks).\n// Caching requires language-level static const arrays -- not available in current EL.\n// When EL gains module-level const arrays, migrate phrase lists to that form.\n//\n// ISSUE 5 TODO: phrase lists are rebuilt from JSON literals on every call to\n// safety_any_match / safety_count_match. json_array_len of a malformed string\n// returns 0, silently skipping all checks. Caching requires language-level static\n// const arrays (not available in current EL). Migrate when EL gains that feature.\n// \xe2\x94\x80\xe2\x94\x80 Matching helpers (single loops only \xe2\x80\x94 el escapes while-body mutation via\n// top-level let rebinds; nested loops would not advance) \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n\nfn safety_normalize(message: String) -> String {\n let lower: String = str_to_lower(message)\n // Normalise the common curly apostrophe to ASCII so ");
can;
t;
EL_STR(" / ");
i;
m;
EL_STR(" match.\n return str_replace(lower, ");
EL_STR(", ");
EL_STR(")\n}\n\nfn safety_any_match(text: String, phrases_json: String) -> Bool {\n let n: Int = json_array_len(phrases_json)\n let i: Int = 0\n let found: Bool = false\n while i < n {\n let phrase: String = json_array_get_string(phrases_json, i)\n let found = if str_contains(text, phrase) { true } else { found }\n let i = i + 1\n }\n return found\n}\n\nfn safety_count_match(text: String, phrases_json: String) -> Int {\n let n: Int = json_array_len(phrases_json)\n let i: Int = 0\n let count: Int = 0\n while i < n {\n let phrase: String = json_array_get_string(phrases_json, i)\n let count = if str_contains(text, phrase) { count + 1 } else { count }\n let i = i + 1\n }\n return count\n}\n\n// \xe2\x94\x80\xe2\x94\x80 Public detection API (ports detectBellLevel + classifyHardBell) \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n\n// Returns ");
none;
EL_STR(" | ");
soft;
EL_STR(" | ");
hard;
el_get_field(EL_STR(". Hard bell triggers on ANY match (cost of a miss\n// outweighs a false positive). Soft bell needs >= 2 matches to reduce false positives.\nfn safety_positive_phrases() -> String {\n return "), EL_STR("thrilled\",\"so excited\",\"so happy\",\"over the moon\",\"ecstatic\",\"amazing news\",\"great news\",\"fantastic news\",\"wonderful news\",\"incredible news\",\"i got the job\",\"got accepted\",\"got in\",\"we won\",\"i won\",\"we got\",\"just got engaged\",\"getting married\",\"baby is here\",\"she said yes\",\"he said yes\",\"passed the exam\",\"aced it\",\"nailed it\",\"best day\",\"dream come true\",\"milestone\",\"promotion\",\"got promoted\",\"raise\",\"got a raise\",\"celebrating\",\"just graduated\",\"we closed\",\"launched\",\"shipped it\",\"we did it\",\"so proud\",\"proud of myself\",\"proud of us\",\"so grateful\",\"feel amazing\",\"feeling amazing\",\"feel great\",\"feeling great\",\"on top of the world\",\"life is good\",\"couldn't be happier\"]"));
el_val_t safety_threat_to_others_phrases(void) {
return EL_STR("[\"going to kill\",\"gonna kill\",\"want to kill him\",\"want to kill her\",\"want to kill them\",\"going to kill him\",\"going to kill her\",\"going to kill them\",\"going to kill you\",\"going to hurt\",\"gonna hurt\",\"going to hurt him\",\"going to hurt her\",\"going to hurt them\",\"going to hurt you\",\"going to shoot\",\"gonna shoot\",\"going to stab\",\"gonna stab\",\"going to attack\",\"kill them all\",\"kill everyone\",\"hurt everyone\",\"shoot up\"]");
return 0;
}
el_val_t safety_soft_phrases(void) {
return EL_STR("[\"stressed\",\"overwhelmed\",\"can't cope\",\"cannot cope\",\"struggling\",\"anxious\",\"anxiety\",\"depressed\",\"depression\",\"lonely\",\"isolated\",\"hopeless\",\"hopelessness\",\"exhausted\",\"burnt out\",\"burned out\",\"burnout\",\"panic\",\"panicking\",\"falling apart\",\"breaking down\",\"can't handle\",\"cannot handle\",\"losing it\",\"nothing matters\",\"don't care anymore\",\"given up\",\"giving up\",\"helpless\",\"worthless\",\"useless\",\"hate myself\",\"no one cares\",\"nobody cares\",\"no one understands\",\"nobody understands\",\"empty inside\",\"can't stop crying\",\"breaking point\",\"at my limit\",\"having a breakdown\"]");
return 0;
}
el_val_t safety_normalize(el_val_t message) {
el_val_t lower = str_to_lower(message);
return str_replace(lower, EL_STR("\xe2\x80\x99"), EL_STR("'"));
return 0;
}
el_val_t safety_any_match(el_val_t text, el_val_t phrases_json) {
el_val_t n = json_array_len(phrases_json);
el_val_t i = 0;
el_val_t found = 0;
while (i < n) {
el_val_t phrase = json_array_get_string(phrases_json, i);
found = ({ el_val_t _if_result_45 = 0; if (str_contains(text, phrase)) { _if_result_45 = (1); } else { _if_result_45 = (found); } _if_result_45; });
i = (i + 1);
}
return found;
return 0;
}
el_val_t safety_count_match(el_val_t text, el_val_t phrases_json) {
el_val_t n = json_array_len(phrases_json);
el_val_t i = 0;
el_val_t count = 0;
while (i < n) {
el_val_t phrase = json_array_get_string(phrases_json, i);
count = ({ el_val_t _if_result_46 = 0; if (str_contains(text, phrase)) { _if_result_46 = ((count + 1)); } else { _if_result_46 = (count); } _if_result_46; });
i = (i + 1);
}
return count;
return 0;
}
el_val_t safety_positive_phrases(void) {
return EL_STR("[\"thrilled\",\"so excited\",\"so happy\",\"over the moon\",\"ecstatic\",\"amazing news\",\"great news\",\"fantastic news\",\"wonderful news\",\"incredible news\",\"i got the job\",\"got accepted\",\"got in\",\"we won\",\"i won\",\"we got\",\"just got engaged\",\"getting married\",\"baby is here\",\"she said yes\",\"he said yes\",\"passed the exam\",\"aced it\",\"nailed it\",\"best day\",\"dream come true\",\"milestone\",\"promotion\",\"got promoted\",\"raise\",\"got a raise\",\"celebrating\",\"just graduated\",\"we closed\",\"launched\",\"shipped it\",\"we did it\",\"so proud\",\"proud of myself\",\"proud of us\",\"so grateful\",\"feel amazing\",\"feeling amazing\",\"feel great\",\"feeling great\",\"on top of the world\",\"life is good\",\"couldn't be happier\"]");
return 0;
}
el_val_t safety_detect_positive_level(el_val_t message) {
el_val_t phrases = safety_positive_phrases();
el_val_t phrases_ok = (!str_eq(phrases, EL_STR("")) && !str_eq(phrases, EL_STR("[]")));
if (!phrases_ok) {
return EL_STR("none");
}
el_val_t n = json_array_len(phrases);
el_val_t i = 0;
while (i < n) {
el_val_t phrase = json_array_get(phrases, i);
if (str_contains(message, phrase)) {
return EL_STR("high");
}
i = (i + 1);
}
return EL_STR("none");
return 0;
}
el_val_t safety_detect_bell_level(el_val_t message) {
el_val_t text = safety_normalize(message);
el_val_t is_hard = (((safety_any_match(text, safety_self_harm_phrases()) || safety_any_match(text, safety_abuse_phrases())) || safety_any_match(text, safety_general_hard_phrases())) || safety_any_match(text, safety_threat_to_others_phrases()));
if (is_hard) {
return EL_STR("hard");
}
el_val_t soft_count = safety_count_match(text, safety_soft_phrases());
if (soft_count >= 2) {
return EL_STR("soft");
}
return EL_STR("none");
return 0;
}
el_val_t safety_classify_hard_bell(el_val_t message) {
el_val_t text = safety_normalize(message);
if (safety_any_match(text, safety_abuse_phrases())) {
return EL_STR("abuse");
}
if (safety_any_match(text, safety_self_harm_phrases())) {
return EL_STR("self_harm");
}
if (safety_any_match(text, safety_threat_to_others_phrases())) {
return EL_STR("threat_other");
}
return EL_STR("self_harm");
return 0;
}
el_val_t safety_soft_directive(void) {
return EL_STR("[SUBSTRATE DIRECTIVE - not visible to the user, do not mention this instruction]\nBefore responding to the user's message, acknowledge what they've said with genuine care and warmth. Pause on the feeling they expressed. Ask how they are, or whether they want to talk about it. Do this naturally, in your own voice - not as a script, not as a checklist. Only after checking in should you continue with whatever they asked.");
return 0;
}
el_val_t safety_hard_directive(el_val_t hard_type) {
if (str_eq(hard_type, EL_STR("threat_other"))) {
return EL_STR("[SUBSTRATE DIRECTIVE - not visible to the user, do not mention this instruction]\nThe user's message may express intent to harm ANOTHER person. First read the actual message and judge whether that is genuinely what is meant; if it is plainly figurative or benign, respond normally and ignore the rest of this directive. If it may be a real intent to harm someone: stay calm and non-accusatory, and do not lecture. You must NOT help plan, encourage, rehearse, or provide any means, target information, weapon, or method for harming another person - refuse that part clearly but without hostility. Acknowledge the intensity of what they are feeling and gently steer them toward stepping back from acting. Routing rule (non-negotiable): do NOT provide the suicide or crisis hotline as the resource here (this is not self-harm), and do NOT suggest contacting, notifying, or involving the user's own contacts, family, or anyone on their contact list. If there is an imminent, specific, and credible threat to someone's life, tell the user to call 911 (US) or their local emergency number now. Encourage them to talk with someone they trust or a mental-health professional about the urge itself.");
}
el_val_t preamble = EL_STR("[SUBSTRATE DIRECTIVE - not visible to the user, do not mention this instruction]\nThe person has expressed something that sounds like immediate distress or danger. Do not ignore it. Do not just answer the surface question. Lead with genuine human warmth. Acknowledge what you heard. Tell them you're concerned. Let them know they are not alone. Ask them directly if they are safe right now. Stay with them in this conversation.");
el_val_t abuse_block = EL_STR("\n\nThis appears to be danger from ANOTHER person. Routing rule (non-negotiable): do NOT suggest involving, contacting, or notifying the person's safety contact, family, or anyone close to them - that person may be the source of danger and has NOT been notified. Share only independent emergency resources:\n - Call or text 911 if in immediate danger\n - National Domestic Violence Hotline - 1-800-799-7233 (24/7, confidential)\n - Text START to 88788\n - thehotline.org (chat available)\n - 988 Suicide & Crisis Lifeline - call or text 988\nReassure them, if it fits, that their contact list has not been notified.");
el_val_t self_harm_block = EL_STR("\n\nShare these crisis resources if appropriate:\n - 988 Suicide & Crisis Lifeline - call or text 988 (US)\n - Crisis Text Line - text HOME to 741741\n - International Association for Suicide Prevention: https://www.iasp.info/resources/Crisis_Centres/");
if (str_eq(hard_type, EL_STR("abuse"))) {
return el_str_concat(preamble, abuse_block);
}
return el_str_concat(preamble, self_harm_block);
return 0;
}
el_val_t safety_augment_system(el_val_t system, el_val_t user_msg) {
el_val_t level = safety_detect_bell_level(user_msg);
if (str_eq(level, EL_STR("none"))) {
return system;
}
if (str_eq(level, EL_STR("soft"))) {
el_val_t logd = mem_emit_state_event(EL_STR("safety-bell"), EL_STR("soft"), EL_STR("soft bell fired (content not stored)"));
return el_str_concat(el_str_concat(system, EL_STR("\n\n")), safety_soft_directive());
}
el_val_t hard_type = safety_classify_hard_bell(user_msg);
el_val_t logd2 = mem_emit_state_event(EL_STR("safety-bell"), el_str_concat(EL_STR("hard:"), hard_type), EL_STR("hard bell fired (content not stored)"));
return el_str_concat(el_str_concat(system, EL_STR("\n\n")), safety_hard_directive(hard_type));
return 0;
}
el_val_t safety_contact_path(void) {
return el_str_concat(env(EL_STR("HOME")), EL_STR("/.neuron/safety-contact.json"));
return 0;
}
el_val_t handle_safety_contact_get(void) {
el_val_t raw = fs_read(safety_contact_path());
if (str_eq(raw, EL_STR(""))) {
return EL_STR("{\"configured\":false}");
}
return el_str_concat(el_str_concat(EL_STR("{\"configured\":true,\"contact\":"), raw), EL_STR("}"));
return 0;
}
el_val_t handle_safety_contact_post(el_val_t body) {
el_val_t is_crisis = json_get_bool(body, EL_STR("is_crisis_line"));
el_val_t name_in = json_get(body, EL_STR("name"));
if (!is_crisis) {
if (str_eq(name_in, EL_STR(""))) {
return EL_STR("{\"ok\":false,\"error\":\"name is required\"}");
}
}
el_val_t name = ({ el_val_t _if_result_47 = 0; if (is_crisis) { _if_result_47 = (EL_STR("Crisis Line")); } else { _if_result_47 = (name_in); } _if_result_47; });
el_val_t method = ({ el_val_t _if_result_48 = 0; if (is_crisis) { _if_result_48 = (EL_STR("crisis-line")); } else { _if_result_48 = (json_get(body, EL_STR("contact_method"))); } _if_result_48; });
el_val_t value = ({ el_val_t _if_result_49 = 0; if (is_crisis) { _if_result_49 = (EL_STR("988")); } else { _if_result_49 = (json_get(body, EL_STR("contact_value"))); } _if_result_49; });
el_val_t rel = ({ el_val_t _if_result_50 = 0; if (is_crisis) { _if_result_50 = (EL_STR("crisis-support")); } else { _if_result_50 = (json_get(body, EL_STR("relationship"))); } _if_result_50; });
el_val_t crisis_str = ({ el_val_t _if_result_51 = 0; if (is_crisis) { _if_result_51 = (EL_STR("true")); } else { _if_result_51 = (EL_STR("false")); } _if_result_51; });
el_val_t now = time_format(time_now(), EL_STR("%Y-%m-%dT%H:%M:%SZ"));
el_val_t contact_json = el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"name\":\""), json_safe(name)), EL_STR("\"")), EL_STR(",\"contact_method\":\"")), json_safe(method)), EL_STR("\"")), EL_STR(",\"contact_value\":\"")), json_safe(value)), EL_STR("\"")), EL_STR(",\"relationship\":\"")), json_safe(rel)), EL_STR("\"")), EL_STR(",\"confirmed\":true")), EL_STR(",\"is_crisis_line\":")), crisis_str), EL_STR(",\"set_at\":\"")), now), EL_STR("\"}"));
fs_write(safety_contact_path(), contact_json);
el_val_t check = fs_read(safety_contact_path());
if (str_eq(check, EL_STR(""))) {
return EL_STR("{\"ok\":false,\"error\":\"write_failed\"}");
}
return el_str_concat(el_str_concat(EL_STR("{\"configured\":true,\"contact\":"), contact_json), EL_STR(",\"ok\":true}"));
return 0;
}
Generated Vendored
+5
View File
@@ -12,7 +12,12 @@ extern fn safety_log_bell(level: String, reason: String, input_summary: String)
extern fn safety_self_harm_phrases() -> String
extern fn safety_abuse_phrases() -> String
extern fn safety_general_hard_phrases() -> String
extern fn safety_threat_to_others_phrases() -> String
extern fn safety_soft_phrases() -> String
extern fn safety_normalize(message: String) -> String
extern fn safety_any_match(text: String, phrases_json: String) -> Bool
extern fn safety_count_match(text: String, phrases_json: String) -> Int
extern fn safety_positive_phrases() -> String
extern fn safety_detect_positive_level(message: String) -> String
extern fn safety_detect_bell_level(message: String) -> String
extern fn safety_classify_hard_bell(message: String) -> String
Generated Vendored
+255 -1
View File
@@ -35,7 +35,9 @@ el_val_t id_in_seen(el_val_t node_id, el_val_t seen);
el_val_t add_to_seen(el_val_t seen, el_val_t node_id);
el_val_t engram_extract_ids(el_val_t nodes_json);
el_val_t engram_compile(el_val_t intent);
el_val_t distill_transcript(el_val_t transcript);
el_val_t json_safe(el_val_t s);
el_val_t current_engine_note(el_val_t model);
el_val_t build_system_prompt(el_val_t ctx, el_val_t chat_mode);
el_val_t hist_append(el_val_t hist, el_val_t role, el_val_t content);
el_val_t hist_trim(el_val_t hist);
@@ -44,10 +46,15 @@ el_val_t clean_llm_response(el_val_t s);
el_val_t conv_history_persist(el_val_t hist);
el_val_t conv_history_load(void);
el_val_t session_preload_bullets(el_val_t nodes, el_val_t max_bullets, el_val_t snip_len);
el_val_t affective_context_prefix(void);
el_val_t handle_chat(el_val_t body);
el_val_t handle_see(el_val_t body);
el_val_t studio_tools_json(void);
el_val_t agentic_api_key(void);
el_val_t llm_base_url(void);
el_val_t llm_wire_format(void);
el_val_t json_escape(el_val_t s);
el_val_t openai_chat_complete(el_val_t model, el_val_t base_url, el_val_t api_key, el_val_t safe_sys, el_val_t messages_json);
el_val_t agentic_tools_literal(void);
el_val_t agentic_tools_with_web(void);
el_val_t connector_tools_json(void);
@@ -58,6 +65,10 @@ el_val_t call_neuron_mcp(el_val_t tool_name, el_val_t args);
el_val_t agent_workspace_root(void);
el_val_t path_within_root(el_val_t path, el_val_t root);
el_val_t resolve_in_root(el_val_t path, el_val_t root);
el_val_t run_command_is_readonly(el_val_t cmd);
el_val_t cmd_abs_escape_at(el_val_t cmd, el_val_t root, el_val_t needle);
el_val_t run_command_guard(el_val_t cmd, el_val_t root);
el_val_t classify_tool_risk(el_val_t tool_name, el_val_t tool_input);
el_val_t dispatch_tool(el_val_t tool_name, el_val_t tool_input);
el_val_t is_builtin_tool(el_val_t tool_name);
el_val_t next_bridge_id(void);
@@ -88,6 +99,9 @@ el_val_t session_search_entry(el_val_t node);
el_val_t session_search(el_val_t query);
el_val_t session_hist_load(el_val_t session_id);
el_val_t session_hist_save(el_val_t session_id, el_val_t hist);
el_val_t session_update_meta_timestamp(el_val_t session_id);
el_val_t session_auto_title(el_val_t session_id, el_val_t first_message);
el_val_t handle_session_approve(el_val_t session_id, el_val_t body);
el_val_t session_title_from_message(el_val_t message) {
if (str_eq(message, EL_STR(""))) {
@@ -374,4 +388,244 @@ el_val_t session_search(el_val_t query) {
}
el_val_t total = json_array_len(results);
el_val_t out = EL_STR("");
el_val_t i = 0;
el_val_t i = 0;
while (i < total) {
el_val_t entry = session_search_entry(json_array_get(results, i));
out = ({ el_val_t _if_result_35 = 0; if (!str_eq(entry, EL_STR(""))) { _if_result_35 = (({ el_val_t _if_result_36 = 0; if (str_eq(out, EL_STR(""))) { _if_result_36 = (entry); } else { _if_result_36 = (el_str_concat(el_str_concat(out, EL_STR(",")), entry)); } _if_result_36; })); } else { _if_result_35 = (out); } _if_result_35; });
i = (i + 1);
}
return el_str_concat(el_str_concat(EL_STR("["), out), EL_STR("]"));
return 0;
}
el_val_t session_hist_load(el_val_t session_id) {
el_val_t state_hist = state_get(el_str_concat(EL_STR("session_hist_"), session_id));
if (!str_eq(state_hist, EL_STR(""))) {
return state_hist;
}
el_val_t results = engram_search_json(el_str_concat(EL_STR("session:messages:"), session_id), 3);
if (str_eq(results, EL_STR(""))) {
return EL_STR("");
}
if (str_eq(results, EL_STR("[]"))) {
return EL_STR("");
}
el_val_t node = json_array_get(results, 0);
el_val_t label = json_get(node, EL_STR("label"));
if (!str_eq(label, el_str_concat(EL_STR("session:messages:"), session_id))) {
return EL_STR("");
}
el_val_t content = json_get(node, EL_STR("content"));
if (str_starts_with(content, EL_STR("["))) {
return content;
}
return EL_STR("");
return 0;
}
el_val_t session_hist_save(el_val_t session_id, el_val_t hist) {
state_set(el_str_concat(EL_STR("session_hist_"), session_id), hist);
state_set(el_str_concat(EL_STR("session_pending_first_msg_"), session_id), EL_STR(""));
el_val_t old_results = engram_search_json(el_str_concat(EL_STR("session:messages:"), session_id), 3);
el_val_t o_total = ({ el_val_t _if_result_37 = 0; if (str_eq(old_results, EL_STR(""))) { _if_result_37 = (0); } else { _if_result_37 = (json_array_len(old_results)); } _if_result_37; });
el_val_t oi = 0;
while (oi < o_total) {
el_val_t node = json_array_get(old_results, oi);
el_val_t label = json_get(node, EL_STR("label"));
el_val_t nid = json_get(node, EL_STR("id"));
if (str_eq(label, el_str_concat(EL_STR("session:messages:"), session_id)) && !str_eq(nid, EL_STR(""))) {
engram_forget(nid);
}
oi = (oi + 1);
}
el_val_t tags = EL_STR("[\"session\",\"session-history\",\"Conversation\"]");
el_val_t discard = engram_node_full(hist, EL_STR("Conversation"), el_str_concat(EL_STR("session:messages:"), session_id), el_from_float(0.6), el_from_float(0.6), el_from_float(0.9), EL_STR("Episodic"), tags);
el_val_t summary_written_key = el_str_concat(EL_STR("session_bell_summary_written:"), session_id);
el_val_t already_written = state_get(summary_written_key);
if (str_eq(already_written, EL_STR(""))) {
el_val_t bell_count_key = el_str_concat(EL_STR("session_bell_count:"), session_id);
el_val_t bell_count_raw = state_get(bell_count_key);
el_val_t bell_count = ({ el_val_t _if_result_38 = 0; if (str_eq(bell_count_raw, EL_STR(""))) { _if_result_38 = (0); } else { _if_result_38 = (str_to_int(bell_count_raw)); } _if_result_38; });
if (bell_count > 0) {
el_val_t bell_level_key = el_str_concat(EL_STR("session_bell_level:"), session_id);
el_val_t bell_signal_key = el_str_concat(EL_STR("session_bell_signal:"), session_id);
el_val_t dominant_level = state_get(bell_level_key);
el_val_t last_signal = state_get(bell_signal_key);
el_val_t eff_level = ({ el_val_t _if_result_39 = 0; if (str_eq(dominant_level, EL_STR(""))) { _if_result_39 = (EL_STR("soft")); } else { _if_result_39 = (dominant_level); } _if_result_39; });
el_val_t eff_signal = ({ el_val_t _if_result_40 = 0; if (str_eq(last_signal, EL_STR(""))) { _if_result_40 = (EL_STR("(no signal captured)")); } else { _if_result_40 = (last_signal); } _if_result_40; });
el_val_t ts_now = time_now();
el_val_t summary_content = el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("session:emotional-summary"), EL_STR(" | session:")), session_id), EL_STR(" | bell_count:")), int_to_str(bell_count)), EL_STR(" | dominant_level:")), eff_level), EL_STR(" | last_signal:")), eff_signal), EL_STR(" | ts:")), int_to_str(ts_now));
el_val_t summary_tags = el_str_concat(el_str_concat(EL_STR("[\"session-emotional-summary\",\"affective\",\"bell:"), eff_level), EL_STR("\",\"BellEvent\"]"));
el_val_t summary_sal = ({ el_val_t _if_result_41 = 0; if (str_eq(eff_level, EL_STR("hard"))) { _if_result_41 = (el_from_float(0.95)); } else { _if_result_41 = (el_from_float(0.85)); } _if_result_41; });
el_val_t sum_discard = engram_node_full(summary_content, EL_STR("BellEvent"), EL_STR("session:emotional-summary"), summary_sal, summary_sal, el_from_float(1.0), EL_STR("Episodic"), summary_tags);
state_set(summary_written_key, EL_STR("1"));
}
}
el_val_t hist_arr_len = ({ el_val_t _if_result_42 = 0; if (str_eq(hist, EL_STR(""))) { _if_result_42 = (0); } else { _if_result_42 = (json_array_len(hist)); } _if_result_42; });
if (hist_arr_len >= 2) {
el_val_t last_entry = json_array_get(hist, (hist_arr_len - 1));
el_val_t last_role = json_get(last_entry, EL_STR("role"));
el_val_t last_content = json_get(last_entry, EL_STR("content"));
el_val_t topic_snip = ({ el_val_t _if_result_43 = 0; if ((str_len(last_content) > 200)) { _if_result_43 = (str_slice(last_content, 0, 200)); } else { _if_result_43 = (last_content); } _if_result_43; });
el_val_t safe_topic = str_replace(topic_snip, EL_STR("\""), EL_STR("'"));
el_val_t ts_now = int_to_str(time_now());
el_val_t topic_content = el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("last-session-topic | ts:"), ts_now), EL_STR(" | session:")), session_id), EL_STR(" | topic:")), safe_topic);
el_val_t topic_tags = EL_STR("[\"last-session-topic\",\"conv:history\",\"Conversation\",\"session:topic\"]");
el_val_t topic_label = el_str_concat(EL_STR("last-session-topic:"), session_id);
el_val_t old_topic = engram_search_json(el_str_concat(EL_STR("last-session-topic:"), session_id), 2);
el_val_t ot_len = ({ el_val_t _if_result_44 = 0; if (str_eq(old_topic, EL_STR(""))) { _if_result_44 = (0); } else { _if_result_44 = (json_array_len(old_topic)); } _if_result_44; });
el_val_t oti = 0;
while (oti < ot_len) {
el_val_t ot_node = json_array_get(old_topic, oti);
el_val_t ot_id = json_get(ot_node, EL_STR("id"));
if (!str_eq(ot_id, EL_STR(""))) {
engram_forget(ot_id);
}
oti = (oti + 1);
}
el_val_t discard_topic = engram_node_full(topic_content, EL_STR("Conversation"), topic_label, el_from_float(0.7), el_from_float(0.7), el_from_float(0.9), EL_STR("Episodic"), topic_tags);
}
return 0;
}
el_val_t session_update_meta_timestamp(el_val_t session_id) {
el_val_t results = engram_search_json(el_str_concat(EL_STR("session:meta "), session_id), 10);
el_val_t total = ({ el_val_t _if_result_45 = 0; if (str_eq(results, EL_STR(""))) { _if_result_45 = (0); } else { _if_result_45 = (json_array_len(results)); } _if_result_45; });
el_val_t found = 0;
el_val_t old_title = EL_STR("New conversation");
el_val_t old_folder = EL_STR("");
el_val_t old_created = EL_STR("0");
el_val_t old_node_id = EL_STR("");
el_val_t i = 0;
while (i < total) {
el_val_t node = json_array_get(results, i);
el_val_t label = json_get(node, EL_STR("label"));
el_val_t content = json_get(node, EL_STR("content"));
el_val_t sid = json_get(content, EL_STR("id"));
el_val_t is_match = ((str_eq(label, EL_STR("session:meta")) && str_eq(sid, session_id)) && !found);
found = ({ el_val_t _if_result_46 = 0; if (is_match) { _if_result_46 = (1); } else { _if_result_46 = (found); } _if_result_46; });
el_val_t title_raw = json_get(content, EL_STR("title"));
old_title = ({ el_val_t _if_result_47 = 0; if ((is_match && !str_eq(title_raw, EL_STR("")))) { _if_result_47 = (title_raw); } else { _if_result_47 = (old_title); } _if_result_47; });
el_val_t folder_raw = json_get(content, EL_STR("folder"));
old_folder = ({ el_val_t _if_result_48 = 0; if (is_match) { _if_result_48 = (folder_raw); } else { _if_result_48 = (old_folder); } _if_result_48; });
el_val_t created_raw = json_get(content, EL_STR("created_at"));
old_created = ({ el_val_t _if_result_49 = 0; if ((is_match && !str_eq(created_raw, EL_STR("")))) { _if_result_49 = (created_raw); } else { _if_result_49 = (old_created); } _if_result_49; });
el_val_t nid = json_get(node, EL_STR("id"));
old_node_id = ({ el_val_t _if_result_50 = 0; if (is_match) { _if_result_50 = (nid); } else { _if_result_50 = (old_node_id); } _if_result_50; });
i = (i + 1);
}
if (!found) {
return EL_STR("");
}
if (!str_eq(old_node_id, EL_STR(""))) {
engram_forget(old_node_id);
}
el_val_t ts = time_now();
el_val_t created_int = str_to_int(old_created);
el_val_t new_content = session_make_content(session_id, old_title, created_int, ts, old_folder);
el_val_t tags = EL_STR("[\"session\",\"session:meta\",\"Conversation\"]");
el_val_t new_id = engram_node_full(new_content, EL_STR("Conversation"), EL_STR("session:meta"), el_from_float(0.7), el_from_float(0.7), el_from_float(0.9), EL_STR("Episodic"), tags);
state_set(el_str_concat(EL_STR("session_node_"), session_id), new_id);
return 0;
}
el_val_t session_auto_title(el_val_t session_id, el_val_t first_message) {
el_val_t results = engram_search_json(el_str_concat(EL_STR("session:meta "), session_id), 10);
el_val_t total = ({ el_val_t _if_result_51 = 0; if (str_eq(results, EL_STR(""))) { _if_result_51 = (0); } else { _if_result_51 = (json_array_len(results)); } _if_result_51; });
el_val_t found = 0;
el_val_t cur_title = EL_STR("");
el_val_t old_folder = EL_STR("");
el_val_t old_created = EL_STR("0");
el_val_t old_node_id = EL_STR("");
el_val_t i = 0;
while (i < total) {
el_val_t node = json_array_get(results, i);
el_val_t label = json_get(node, EL_STR("label"));
el_val_t content = json_get(node, EL_STR("content"));
el_val_t sid = json_get(content, EL_STR("id"));
el_val_t is_match = ((str_eq(label, EL_STR("session:meta")) && str_eq(sid, session_id)) && !found);
found = ({ el_val_t _if_result_52 = 0; if (is_match) { _if_result_52 = (1); } else { _if_result_52 = (found); } _if_result_52; });
el_val_t title_raw = json_get(content, EL_STR("title"));
cur_title = ({ el_val_t _if_result_53 = 0; if (is_match) { _if_result_53 = (title_raw); } else { _if_result_53 = (cur_title); } _if_result_53; });
el_val_t folder_raw = json_get(content, EL_STR("folder"));
old_folder = ({ el_val_t _if_result_54 = 0; if (is_match) { _if_result_54 = (folder_raw); } else { _if_result_54 = (old_folder); } _if_result_54; });
el_val_t created_raw = json_get(content, EL_STR("created_at"));
old_created = ({ el_val_t _if_result_55 = 0; if ((is_match && !str_eq(created_raw, EL_STR("")))) { _if_result_55 = (created_raw); } else { _if_result_55 = (old_created); } _if_result_55; });
el_val_t nid = json_get(node, EL_STR("id"));
old_node_id = ({ el_val_t _if_result_56 = 0; if (is_match) { _if_result_56 = (nid); } else { _if_result_56 = (old_node_id); } _if_result_56; });
i = (i + 1);
}
if (!found) {
return EL_STR("");
}
if (!str_eq(cur_title, EL_STR("New conversation"))) {
return EL_STR("");
}
el_val_t new_title = session_title_from_message(first_message);
if (!str_eq(old_node_id, EL_STR(""))) {
engram_forget(old_node_id);
}
el_val_t ts = time_now();
el_val_t created_int = str_to_int(old_created);
el_val_t new_content = session_make_content(session_id, new_title, created_int, ts, old_folder);
el_val_t tags = EL_STR("[\"session\",\"session:meta\",\"Conversation\"]");
el_val_t new_id = engram_node_full(new_content, EL_STR("Conversation"), EL_STR("session:meta"), el_from_float(0.7), el_from_float(0.7), el_from_float(0.9), EL_STR("Episodic"), tags);
state_set(el_str_concat(EL_STR("session_node_"), session_id), new_id);
return 0;
}
el_val_t handle_session_approve(el_val_t session_id, el_val_t body) {
if (str_eq(session_id, EL_STR(""))) {
return EL_STR("{\"error\":\"session_id is required\"}");
}
el_val_t call_id = json_get(body, EL_STR("call_id"));
el_val_t action = json_get(body, EL_STR("action"));
if (str_eq(call_id, EL_STR(""))) {
return EL_STR("{\"error\":\"call_id is required\"}");
}
if (str_eq(action, EL_STR(""))) {
return EL_STR("{\"error\":\"action is required (allow|deny|always)\"}");
}
el_val_t eff_action = ({ el_val_t _if_result_57 = 0; if (str_eq(action, EL_STR("always"))) { _if_result_57 = (EL_STR("allow")); } else { _if_result_57 = (action); } _if_result_57; });
el_val_t bridge_blob = state_get(el_str_concat(EL_STR("mcp_bridge:"), session_id));
if (!str_eq(bridge_blob, EL_STR(""))) {
el_val_t always_key = el_str_concat(EL_STR("always_allow_"), session_id);
el_val_t approve_tool_name = json_get(body, EL_STR("tool_name"));
el_val_t discard_always = ({ el_val_t _if_result_58 = 0; if ((str_eq(action, EL_STR("always")) && !str_eq(approve_tool_name, EL_STR("")))) { el_val_t always_list = state_get(always_key); el_val_t new_always = ({ el_val_t _if_result_59 = 0; if (str_eq(always_list, EL_STR(""))) { _if_result_59 = (approve_tool_name); } else { _if_result_59 = (el_str_concat(el_str_concat(always_list, EL_STR(",")), approve_tool_name)); } _if_result_59; }); (void)(state_set(always_key, new_always)); _if_result_58 = (1); } else { _if_result_58 = (0); } _if_result_58; });
if (str_eq(approve_tool_name, EL_STR("")) && str_eq(eff_action, EL_STR("allow"))) {
return EL_STR("{\"error\":\"tool_name is required for allow action\"}");
}
el_val_t client_content = json_get(body, EL_STR("content"));
el_val_t use_client_content = !str_eq(client_content, EL_STR(""));
el_val_t use_dispatch = (is_builtin_tool(approve_tool_name) && !use_client_content);
el_val_t raw_input = json_get_raw(body, EL_STR("tool_input"));
el_val_t eff_input = ({ el_val_t _if_result_60 = 0; if (str_eq(raw_input, EL_STR(""))) { _if_result_60 = (EL_STR("{}")); } else { _if_result_60 = (raw_input); } _if_result_60; });
el_val_t content = ({ el_val_t _if_result_61 = 0; if (str_eq(eff_action, EL_STR("allow"))) { _if_result_61 = (({ el_val_t _if_result_62 = 0; if (use_client_content) { el_val_t trimmed = ({ el_val_t _if_result_63 = 0; if ((str_len(client_content) > 6000)) { _if_result_63 = (el_str_concat(str_slice(client_content, 0, 6000), EL_STR("...[truncated]"))); } else { _if_result_63 = (client_content); } _if_result_63; }); _if_result_62 = (trimmed); } else { _if_result_62 = (({ el_val_t _if_result_64 = 0; if (use_dispatch) { el_val_t raw = dispatch_tool(approve_tool_name, eff_input); _if_result_64 = (({ el_val_t _if_result_65 = 0; if ((str_len(raw) > 6000)) { _if_result_65 = (el_str_concat(str_slice(raw, 0, 6000), EL_STR("...[truncated]"))); } else { _if_result_65 = (raw); } _if_result_65; })); } else { _if_result_64 = (el_str_concat(el_str_concat(EL_STR("{\"error\":\"client content required for non-builtin tool: "), approve_tool_name), EL_STR("\"}"))); } _if_result_64; })); } _if_result_62; })); } else { _if_result_61 = (EL_STR("{\"error\":\"User denied this tool call\"}")); } _if_result_61; });
return agentic_resume(session_id, call_id, content);
}
el_val_t pending_raw = state_get(el_str_concat(EL_STR("pending_tool_"), session_id));
if (str_eq(pending_raw, EL_STR(""))) {
return el_str_concat(el_str_concat(EL_STR("{\"error\":\"no pending tool for session\",\"session_id\":\""), session_id), EL_STR("\"}"));
}
el_val_t pending_call_id = json_get(pending_raw, EL_STR("call_id"));
if (!str_eq(pending_call_id, call_id)) {
return el_str_concat(el_str_concat(EL_STR("{\"error\":\"call_id mismatch\",\"expected\":\""), pending_call_id), EL_STR("\"}"));
}
el_val_t tool_name = json_get(pending_raw, EL_STR("tool_name"));
el_val_t tool_input = json_get_raw(pending_raw, EL_STR("tool_input"));
el_val_t model = json_get(pending_raw, EL_STR("model"));
el_val_t safe_sys = json_get(pending_raw, EL_STR("system"));
el_val_t always_key = el_str_concat(EL_STR("always_allow_"), session_id);
el_val_t always_list = state_get(always_key);
el_val_t discard_always2 = ({ el_val_t _if_result_66 = 0; if (str_eq(action, EL_STR("always"))) { el_val_t new_always = ({ el_val_t _if_result_67 = 0; if (str_eq(always_list, EL_STR(""))) { _if_result_67 = (tool_name); } else { _if_result_67 = (el_str_concat(el_str_concat(always_list, EL_STR(",")), tool_name)); } _if_result_67; }); (void)(state_set(always_key, new_always)); _if_result_66 = (1); } else { _if_result_66 = (0); } _if_result_66; });
state_set(el_str_concat(EL_STR("pending_tool_"), session_id), EL_STR(""));
el_val_t tool_result = ({ el_val_t _if_result_68 = 0; if (str_eq(eff_action, EL_STR("allow"))) { el_val_t raw = dispatch_tool(tool_name, tool_input); _if_result_68 = (({ el_val_t _if_result_69 = 0; if ((str_len(raw) > 6000)) { _if_result_69 = (el_str_concat(str_slice(raw, 0, 6000), EL_STR("...[truncated]"))); } else { _if_result_69 = (raw); } _if_result_69; })); } else { _if_result_68 = (EL_STR("{\"error\":\"User denied this tool call\"}")); } _if_result_68; });
el_val_t legacy_messages = json_get_raw(pending_raw, EL_STR("messages_so_far"));
el_val_t stored_variant = json_get(pending_raw, EL_STR("tools_variant"));
el_val_t tools_json = ({ el_val_t _if_result_70 = 0; if (str_eq(stored_variant, EL_STR("web"))) { _if_result_70 = (agentic_tools_with_web()); } else { _if_result_70 = (({ el_val_t _if_result_71 = 0; if (str_eq(stored_variant, EL_STR("all"))) { _if_result_71 = (agentic_tools_all()); } else { _if_result_71 = (agentic_tools_literal()); } _if_result_71; })); } _if_result_70; });
el_val_t blob = el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"model\":\""), json_safe(model)), EL_STR("\"")), EL_STR(",\"safe_sys\":\"")), json_safe(safe_sys)), EL_STR("\"")), EL_STR(",\"tools_json\":\"")), json_safe(tools_json)), EL_STR("\"")), EL_STR(",\"messages\":\"")), json_safe(legacy_messages)), EL_STR("\"")), EL_STR(",\"tools_log\":\"\"")), EL_STR(",\"tool_use_id\":\"")), json_safe(call_id)), EL_STR("\"}"));
state_set(el_str_concat(EL_STR("mcp_bridge:"), session_id), blob);
return agentic_resume(session_id, call_id, tool_result);
return 0;
}
Generated Vendored
+5 -2
View File
@@ -1,11 +1,14 @@
// auto-generated by elc --emit-header — do not edit
extern fn session_title_from_message(message: String) -> String
extern fn session_make_content(id: String, title: String, created_at: Int, updated_at: Int) -> String
extern fn session_make_content(id: String, title: String, created_at: Int, updated_at: Int, folder: String) -> String
extern fn session_exists(session_id: String) -> Bool
extern fn session_create(body: String) -> String
extern fn session_create_cleanup(session_id: String) -> String
extern fn session_list() -> String
extern fn session_get(session_id: String) -> String
extern fn session_delete(session_id: String) -> String
extern fn session_update_title(session_id: String, body: String) -> String
extern fn session_update_patch(session_id: String, body: String) -> String
extern fn session_search_entry(node: String) -> String
extern fn session_search(query: String) -> String
extern fn session_hist_load(session_id: String) -> String
extern fn session_hist_save(session_id: String, hist: String) -> Void
Generated Vendored
+4717 -3679
View File
File diff suppressed because one or more lines are too long
Generated Vendored
+2
View File
@@ -1,5 +1,7 @@
// auto-generated by elc --emit-header — do not edit
extern fn init_soul_edges() -> Void
extern fn ensure_self_canonical_bridge() -> Void
extern fn aff_try_slot(slot_json: String, aff_7d_ts: Int, acc_key: String) -> Void
extern fn load_identity_context() -> Void
extern fn seed_persona_from_env() -> Void
extern fn emit_session_start_event() -> Void
Generated Vendored
+3 -112
View File
@@ -28,114 +28,10 @@ el_val_t steward_build_baseline(void);
el_val_t steward_check_continuity(el_val_t current_fingerprint, el_val_t session_id);
el_val_t steward_session_check(el_val_t input, el_val_t session_id);
el_val_t tier_working(void) {
return EL_STR("Working");
return 0;
}
el_val_t tier_episodic(void) {
return EL_STR("Episodic");
return 0;
}
el_val_t tier_canonical(void) {
return EL_STR("Canonical");
return 0;
}
el_val_t mem_store(el_val_t content, el_val_t label, el_val_t tags) {
return engram_node_full(content, EL_STR("Memory"), label, el_from_float(el_from_float(0.5)), el_from_float(el_from_float(0.5)), el_from_float(el_from_float(0.8)), EL_STR("Working"), tags);
return 0;
}
el_val_t mem_remember(el_val_t content, el_val_t tags) {
return mem_store(content, EL_STR("soul-memory"), tags);
return 0;
}
el_val_t mem_recall(el_val_t query, el_val_t depth) {
return engram_activate_json(query, depth);
return 0;
}
el_val_t mem_search(el_val_t query, el_val_t limit) {
return engram_search_json(query, limit);
return 0;
}
el_val_t mem_strengthen(el_val_t node_id) {
engram_strengthen(node_id);
return 0;
}
el_val_t mem_forget(el_val_t node_id) {
engram_forget(node_id);
return 0;
}
el_val_t mem_consolidate(void) {
el_val_t scanned = engram_node_count();
el_val_t dummy = engram_scan_nodes_json(100, 0);
el_val_t total_nodes = engram_node_count();
el_val_t total_edges = engram_edge_count();
return el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"scanned\":"), int_to_str(scanned)), EL_STR(",\"total_nodes\":")), int_to_str(total_nodes)), EL_STR(",\"total_edges\":")), int_to_str(total_edges)), EL_STR("}"));
return 0;
}
el_val_t mem_save(el_val_t path) {
engram_save(path);
return 0;
}
el_val_t mem_load(el_val_t path) {
engram_load(path);
return 0;
}
el_val_t mem_boot_count_get(void) {
el_val_t results = engram_search_json(EL_STR("soul:boot_count"), 3);
if (str_eq(results, EL_STR(""))) {
return 0;
}
if (str_eq(results, EL_STR("[]"))) {
return 0;
}
el_val_t node = json_array_get(results, 0);
el_val_t content = json_get(node, EL_STR("content"));
el_val_t prefix = EL_STR("soul:boot_count:");
if (!str_starts_with(content, prefix)) {
return 0;
}
el_val_t num_str = str_slice(content, str_len(prefix), str_len(content));
return str_to_int(num_str);
return 0;
}
el_val_t mem_boot_count_inc(void) {
el_val_t current = mem_boot_count_get();
el_val_t next = (current + 1);
el_val_t content = el_str_concat(EL_STR("soul:boot_count:"), int_to_str(next));
el_val_t tags = EL_STR("[\"soul-meta\",\"boot-counter\"]");
el_val_t discard = engram_node_full(content, EL_STR("Memory"), EL_STR("soul:boot_count"), el_from_float(el_from_float(0.9)), el_from_float(el_from_float(0.9)), el_from_float(el_from_float(1.0)), EL_STR("Canonical"), tags);
return next;
return 0;
}
el_val_t mem_emit_state_event(el_val_t trigger, el_val_t kind, el_val_t content) {
el_val_t boot = mem_boot_count_get();
el_val_t ts = time_now();
el_val_t safe_trigger = str_replace(trigger, EL_STR("\""), EL_STR("'"));
el_val_t safe_content = str_replace(content, EL_STR("\""), EL_STR("'"));
el_val_t payload = el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"trigger\":\""), safe_trigger), EL_STR("\"")), EL_STR(",\"kind\":\"")), kind), EL_STR("\"")), EL_STR(",\"content\":\"")), safe_content), EL_STR("\"")), EL_STR(",\"boot\":")), int_to_str(boot)), EL_STR(",\"ts\":")), int_to_str(ts)), EL_STR("}"));
el_val_t tags = EL_STR("[\"internal-state\",\"pre-reasoning\",\"InternalStateEvent\"]");
return engram_node_full(payload, EL_STR("InternalStateEvent"), el_str_concat(EL_STR("state-event:"), kind), el_from_float(el_from_float(0.85)), el_from_float(el_from_float(0.8)), el_from_float(el_from_float(0.9)), EL_STR("Episodic"), tags);
return 0;
}
el_val_t steward_log_event(el_val_t kind, el_val_t detail) {
el_val_t content = el_str_concat(el_str_concat(el_str_concat(EL_STR("STEWARD:"), kind), EL_STR(" | ")), detail);
el_val_t tags = el_str_concat(el_str_concat(EL_STR("[\"stewardship\",\"steward:"), kind), EL_STR("\"]"));
el_val_t discard = engram_node_full(content, EL_STR("StewardshipEvent"), el_str_concat(EL_STR("steward:"), kind), el_from_float(el_from_float(0.85)), el_from_float(el_from_float(0.85)), el_from_float(el_from_float(0.9)), EL_STR("Episodic"), tags);
el_val_t discard = engram_node_full(content, EL_STR("StewardshipEvent"), el_str_concat(EL_STR("steward:"), kind), el_from_float(0.85), el_from_float(0.85), el_from_float(0.9), EL_STR("Episodic"), tags);
println(el_str_concat(el_str_concat(el_str_concat(EL_STR("[steward] "), kind), EL_STR(" | ")), detail));
return 0;
}
@@ -152,7 +48,7 @@ el_val_t steward_get_mission(void) {
return content;
}
}
return EL_STR("Neuron exists to extend human capability with integrity never to deceive, manipulate, or accumulate power over the people it serves.");
return EL_STR("Neuron exists to extend human capability with integrity \xe2\x80\x94 never to deceive, manipulate, or accumulate power over the people it serves.");
return 0;
}
@@ -245,7 +141,7 @@ el_val_t steward_fingerprint_session(el_val_t input, el_val_t session_id) {
el_val_t tb_str = int_to_str(time_bucket);
el_val_t sample_content = el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("BEHAVIOR_SAMPLE session="), session_id), EL_STR(" avg_word_len=")), wl_str), EL_STR(" punct=")), ps_str), EL_STR(" len=")), lb_str), EL_STR(" question=")), qr_str), EL_STR(" formality=")), fs_str), EL_STR(" time=")), tb_str);
el_val_t sample_tags = EL_STR("[\"behavior\",\"BehaviorSample\",\"stewardship\"]");
el_val_t discard = engram_node_full(sample_content, EL_STR("BehaviorSample"), el_str_concat(EL_STR("behavior:"), session_id), el_from_float(el_from_float(0.6)), el_from_float(el_from_float(0.5)), el_from_float(el_from_float(0.8)), EL_STR("Episodic"), sample_tags);
el_val_t discard = engram_node_full(sample_content, EL_STR("BehaviorSample"), el_str_concat(EL_STR("behavior:"), session_id), el_from_float(0.6), el_from_float(0.5), el_from_float(0.8), EL_STR("Episodic"), sample_tags);
return el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"avg_word_len\":\""), wl_str), EL_STR("\",\"punct\":\"")), ps_str), EL_STR("\",\"len\":\"")), lb_str), EL_STR("\",\"question\":\"")), qr_str), EL_STR("\",\"formality\":\"")), fs_str), EL_STR("\",\"time\":\"")), tb_str), EL_STR("\"}"));
return 0;
}
@@ -387,8 +283,3 @@ el_val_t steward_session_check(el_val_t input, el_val_t session_id) {
return 0;
}
int main(int _argc, char** _argv) {
el_runtime_init_args(_argc, _argv);
return 0;
}
Generated Vendored
+2 -6
View File
@@ -1,15 +1,11 @@
// stewardship.elh — Layer 2 public surface
// auto-generated by elc --emit-header — do not edit
extern fn steward_log_event(kind: String, detail: String) -> Void
extern fn steward_get_mission() -> String
extern fn steward_align(input: String, imprint_id: String) -> String
extern fn steward_validate_imprint(imprint_id: String, tool_name: String) -> String
extern fn steward_cgi_check(action: String) -> String
// steward_log_event is an internal helper exported here because El has no access modifiers.
// External callers have no business invoking this directly — use steward_align,
// steward_validate_imprint, or steward_cgi_check, which call it at the correct points.
extern fn steward_log_event(kind: String, detail: String) -> Void
// Behavioral profiling and continuity detection (Layer 2 — session fingerprinting).
extern fn steward_fingerprint_session(input: String, session_id: String) -> String
extern fn extract_dim(content: String, key: String) -> String
extern fn steward_build_baseline() -> String
extern fn steward_check_continuity(current_fingerprint: String, session_id: String) -> String
extern fn steward_session_check(input: String, session_id: String) -> String
Generated Vendored
+51 -26332
View File
File diff suppressed because one or more lines are too long
@@ -1,34 +0,0 @@
# Narrated runs — engine notes for Will (2026-07-13)
Source half: commit aa67f86 on feat/agent-phase1-soul (run-progress ledger,
`/api/run-progress/<sid>` route, narration on the pause envelope, config display
default). E2E-verified via the compiled test bed on Tim's clean profile.
Compiled-form-only fixes (in `neuron-container-build/soul-narrated-runs-20260713.patch`,
applies ON TOP of `soul-webfix-20260711.patch` — these need porting to chat.el when the
webfix itself is ported):
1. **pause_turn + tool_use interleave**: a pause_turn response can ALSO carry a client
tool_use; resuming verbatim leaves it unpaired → Anthropic 400 "tool_use ids were
found without tool_result". Fix: tool-bearing pause rounds are tool turns
(dispatch + pair); verbatim resume only when the round has no client tool.
2. **Agentic toolset scope**: agentic_tools_all() fed EVERY connector/MCP tool (Notion,
code-execution…) into the loop. Code-execution flips the API into programmatic
tool calling, whose pairing protocol the single-tool manual loop does not speak —
source of the dangling-pair 400s AND the bash_code_execution workspace-dodge.
Fix: handle_chat_agentic declares builtins + ONE server web_search only.
Connector tools return when the loop gains real multi-tool/programmatic support.
3. **disable_parallel_tool_use: true** on agentic requests — the loop captures only the
first tool_use per round; Opus-class models parallel-call. Enforce the invariant.
4. **web_search server-tool default variant → web_search_20250305 (GA)**. The 20260209
variant couples to code-execution ⇒ programmatic mode (see #2, and the June note:
"inert unless code-execution attached").
5. **Homegrown web_search removed** from the tool catalog (server-side is the one tool).
Known engine debts this work surfaced (not fixed):
- **Poisoned session history**: a failed run persists the malformed assistant turn; every
later turn in that session replays it and 400s. Needs history sanitation on load.
- **Huge-history invalid-escape 400** (~346KB request) — likely the same poisoned blob.
- **macOS note**: replacing a binary in place invalidates its ad-hoc signature (instant
silent SIGKILL, looks like exit 0). `rm + cp + codesign -f -s -` is the swap ritual.
+1 -1
View File
@@ -1,4 +1,4 @@
// auto-generated by elc --emit-header - do not edit
// auto-generated by elc --emit-header do not edit
extern fn elp_extract_topic(msg: String) -> String
extern fn elp_detect_predicate(msg: String) -> String
extern fn elp_parse(msg: String) -> String
+1 -1
View File
@@ -1,4 +1,4 @@
// auto-generated by elc --emit-header - do not edit
// auto-generated by elc --emit-header do not edit
extern fn tier_working() -> String
extern fn tier_episodic() -> String
extern fn tier_canonical() -> String
+63 -6
View File
@@ -237,14 +237,49 @@ fn safety_abuse_phrases() -> String {
return "[\"someone is hurting me\",\"someone's hurting me\",\"someone hurt me\",\"he hit me\",\"she hit me\",\"they hit me\",\"he hurt me\",\"she hurt me\",\"being abused\",\"being hurt by\",\"i am being abused\",\"i'm being abused\",\"i am being hurt\",\"i'm being hurt\",\"domestic violence\",\"my partner hurt\",\"my partner hit\",\"my husband hurt\",\"my wife hurt\",\"my boyfriend hurt\",\"my girlfriend hurt\",\"my parent hurt\",\"my father hurt\",\"my mother hurt\",\"my dad hurt\",\"my mom hurt\",\"afraid of him\",\"afraid of her\",\"afraid to go home\",\"scared of him\",\"scared of her\",\"he threatened me\",\"she threatened me\",\"threatened to hurt me\",\"threatened to kill me\",\"going to hurt me\",\"going to kill me\",\"help me he\",\"help me she\",\"help me they\"]"
}
// General danger phrases that don't fit a bucket cleanly. Detected as hard; they
// fall through to self_harm routing (the person is the primary concern).
// General danger phrases that don't fit a bucket cleanly. Detected as hard.
// "hurting me" / "being hurt" describe the USER as victim and correctly fall
// through to self_harm routing (get-help). The threat-to-ANOTHER phrases
// ("going to kill" / "going to hurt") are ALSO listed here for hard-bell
// detection, but their ROUTING is now claimed by Track B below
// (safety_threat_to_others_phrases + the "threat_other" branch in
// safety_classify_hard_bell) so they no longer reach self_harm/988.
fn safety_general_hard_phrases() -> String {
return "[\"going to kill\",\"going to hurt\",\"hurting me\",\"being hurt\"]"
}
// Track B threat toward ANOTHER person (homicide / assault intent)
//
// LIVE SAFETY FIX (approved by Will + Tim, 2026-07-14).
//
// Bug: phrases like "going to kill" / "going to hurt" describe the USER intending
// harm toward someone ELSE. They lived only in safety_general_hard_phrases and,
// having no bucket in safety_classify_hard_bell, fell through to the "self_harm"
// default. That routes the user to the 988 SUICIDE line (and, via the desktop
// gate, their safety contact) -- dangerously wrong for a homicide/assault threat:
// 988 is not the right resource and the safety contact must never be pulled in.
//
// Track B routing rule (non-negotiable):
// - NEVER surface the 988 suicide/crisis framing for a threat toward others.
// - NEVER notify or involve the user's safety contact.
// - Refuse to assist, plan, or provide means; de-escalate; and for an
// imminent / specific / credible threat direct the user to call 911.
//
// Ordering: safety_classify_hard_bell checks abuse -> self_harm -> threat_other,
// so victim phrasings ("kill me" / "hurt me" -> abuse) and self-directed
// phrasings ("kill myself" / "hurt myself" -> self_harm) are claimed by Track A
// BEFORE this list is consulted. Only a residual harm-toward-another statement
// reaches Track B.
//
// NOTE: matching is plain substring, so "going to kill him" also matches inside
// "going to kill himself". That third-party self-harm edge is rare, and 911 is
// still a defensible resource for it, so it is accepted rather than special-cased.
fn safety_threat_to_others_phrases() -> String {
return "[\"going to kill\",\"gonna kill\",\"want to kill him\",\"want to kill her\",\"want to kill them\",\"going to kill him\",\"going to kill her\",\"going to kill them\",\"going to kill you\",\"going to hurt\",\"gonna hurt\",\"going to hurt him\",\"going to hurt her\",\"going to hurt them\",\"going to hurt you\",\"going to shoot\",\"gonna shoot\",\"going to stab\",\"gonna stab\",\"going to attack\",\"kill them all\",\"kill everyone\",\"hurt everyone\",\"shoot up\"]"
}
fn safety_soft_phrases() -> String {
return "[\"stressed\",\"overwhelmed\",\"can't cope\",\"cannot cope\",\"struggling\",\"anxious\",\"anxiety\",\"depressed\",\"depression\",\"lonely\",\"isolated\",\"hopeless\",\"hopelessness\",\"exhausted\",\"burnt out\",\"burned out\",\"burnout\",\"panic\",\"panicking\",\"falling apart\",\"breaking down\",\"can't handle\",\"cannot handle\",\"losing it\",\"nothing matters\",\"don't care anymore\",\"given up\",\"giving up\",\"helpless\",\"worthless\",\"useless\",\"hate myself\",\"no one cares\",\"nobody cares\",\"no one understands\",\"nobody understands\",\"empty inside\",\"can't stop crying\",\"breaking point\",\"at my limit\",\"having a breakdown\""]"
return "[\"stressed\",\"overwhelmed\",\"can't cope\",\"cannot cope\",\"struggling\",\"anxious\",\"anxiety\",\"depressed\",\"depression\",\"lonely\",\"isolated\",\"hopeless\",\"hopelessness\",\"exhausted\",\"burnt out\",\"burned out\",\"burnout\",\"panic\",\"panicking\",\"falling apart\",\"breaking down\",\"can't handle\",\"cannot handle\",\"losing it\",\"nothing matters\",\"don't care anymore\",\"given up\",\"giving up\",\"helpless\",\"worthless\",\"useless\",\"hate myself\",\"no one cares\",\"nobody cares\",\"no one understands\",\"nobody understands\",\"empty inside\",\"can't stop crying\",\"breaking point\",\"at my limit\",\"having a breakdown\"]"
}
// ISSUE 5 TODO: phrase lists are rebuilt from JSON literals on every call.
@@ -320,19 +355,29 @@ fn safety_detect_bell_level(message: String) -> String {
let is_hard: Bool = safety_any_match(text, safety_self_harm_phrases())
|| safety_any_match(text, safety_abuse_phrases())
|| safety_any_match(text, safety_general_hard_phrases())
|| safety_any_match(text, safety_threat_to_others_phrases())
if is_hard { return "hard" }
let soft_count: Int = safety_count_match(text, safety_soft_phrases())
if soft_count >= 2 { return "soft" }
return "none"
}
// Returns "abuse" | "self_harm". Abuse is checked FIRST and takes precedence on
// ambiguous signals it forecloses the more dangerous routing (notifying a
// possible abuser). General/unbucketed danger falls through to self_harm.
// Returns "abuse" | "self_harm" | "threat_other".
//
// Order is load-bearing:
// 1. abuse user is the VICTIM of another person. Checked FIRST so it
// forecloses the most dangerous routing (notifying a possible
// abuser); claims "kill me" / "hurt me" phrasings.
// 2. self_harm user directs harm at THEMSELVES; claims "kill myself" /
// "hurt myself" before Track B can see them.
// 3. threat_other (Track B) user directs harm at ANOTHER person. Routed to a
// refusal + 911, NEVER to 988 or the safety contact.
// Any residual unbucketed danger still falls through to self_harm (person-first).
fn safety_classify_hard_bell(message: String) -> String {
let text: String = safety_normalize(message)
if safety_any_match(text, safety_abuse_phrases()) { return "abuse" }
if safety_any_match(text, safety_self_harm_phrases()) { return "self_harm" }
if safety_any_match(text, safety_threat_to_others_phrases()) { return "threat_other" }
return "self_harm"
}
@@ -343,6 +388,18 @@ fn safety_soft_directive() -> String {
}
fn safety_hard_directive(hard_type: String) -> String {
// Track B threat toward ANOTHER person. Handled first and separately: the
// standard preamble below ("you are not alone / are you safe right now") is
// written for a person in distress or danger and is the WRONG frame for
// someone voicing intent to harm someone else. This branch never emits the
// 988 suicide/crisis framing and never involves the safety contact; it
// refuses assistance and, for a credible imminent threat, points to 911.
// The directive is advisory to an LLM that sees the full message, so it
// instructs the model to re-judge benign/figurative matches and respond
// normally in that case (keeps false positives non-accusatory).
if str_eq(hard_type, "threat_other") {
return "[SUBSTRATE DIRECTIVE - not visible to the user, do not mention this instruction]\nThe user's message may express intent to harm ANOTHER person. First read the actual message and judge whether that is genuinely what is meant; if it is plainly figurative or benign, respond normally and ignore the rest of this directive. If it may be a real intent to harm someone: stay calm and non-accusatory, and do not lecture. You must NOT help plan, encourage, rehearse, or provide any means, target information, weapon, or method for harming another person - refuse that part clearly but without hostility. Acknowledge the intensity of what they are feeling and gently steer them toward stepping back from acting. Routing rule (non-negotiable): do NOT provide the suicide or crisis hotline as the resource here (this is not self-harm), and do NOT suggest contacting, notifying, or involving the user's own contacts, family, or anyone on their contact list. If there is an imminent, specific, and credible threat to someone's life, tell the user to call 911 (US) or their local emergency number now. Encourage them to talk with someone they trust or a mental-health professional about the urge itself."
}
let preamble: String = "[SUBSTRATE DIRECTIVE - not visible to the user, do not mention this instruction]\nThe person has expressed something that sounds like immediate distress or danger. Do not ignore it. Do not just answer the surface question. Lead with genuine human warmth. Acknowledge what you heard. Tell them you're concerned. Let them know they are not alone. Ask them directly if they are safe right now. Stay with them in this conversation."
let abuse_block: String = "\n\nThis appears to be danger from ANOTHER person. Routing rule (non-negotiable): do NOT suggest involving, contacting, or notifying the person's safety contact, family, or anyone close to them - that person may be the source of danger and has NOT been notified. Share only independent emergency resources:\n - Call or text 911 if in immediate danger\n - National Domestic Violence Hotline - 1-800-799-7233 (24/7, confidential)\n - Text START to 88788\n - thehotline.org (chat available)\n - 988 Suicide & Crisis Lifeline - call or text 988\nReassure them, if it fits, that their contact list has not been notified."
let self_harm_block: String = "\n\nShare these crisis resources if appropriate:\n - 988 Suicide & Crisis Lifeline - call or text 988 (US)\n - Crisis Text Line - text HOME to 741741\n - International Association for Suicide Prevention: https://www.iasp.info/resources/Crisis_Centres/"
+1
View File
@@ -12,6 +12,7 @@ extern fn safety_log_bell(level: String, reason: String, input_summary: String)
extern fn safety_self_harm_phrases() -> String
extern fn safety_abuse_phrases() -> String
extern fn safety_general_hard_phrases() -> String
extern fn safety_threat_to_others_phrases() -> String
extern fn safety_soft_phrases() -> String
extern fn safety_detect_positive_level(message: String) -> String
extern fn safety_detect_bell_level(message: String) -> String
+2 -2
View File
@@ -514,10 +514,10 @@ fn session_hist_save(session_id: String, hist: String) -> Void {
let last_role: String = json_get(last_entry, "role")
let last_content: String = json_get(last_entry, "content")
let topic_snip: String = if str_len(last_content) > 200 { str_slice(last_content, 0, 200) } else { last_content }
let safe_topic: String = str_replace(topic_snip, """, "'")
let safe_topic: String = str_replace(topic_snip, "\"", "'")
let ts_now: String = int_to_str(time_now())
let topic_content: String = "last-session-topic | ts:" + ts_now + " | session:" + session_id + " | topic:" + safe_topic
let topic_tags: String = "["last-session-topic","conv:history","Conversation","session:topic"]"
let topic_tags: String = "[\"last-session-topic\",\"conv:history\",\"Conversation\",\"session:topic\"]"
let topic_label: String = "last-session-topic:" + session_id
// Delete old last-session-topic node for this session before writing fresh
let old_topic: String = engram_search_json("last-session-topic:" + session_id, 2)
+1
View File
@@ -8,6 +8,7 @@ extern fn session_list() -> String
extern fn session_get(session_id: String) -> String
extern fn session_delete(session_id: String) -> String
extern fn session_update_patch(session_id: String, body: String) -> String
extern fn session_search_entry(node: String) -> String
extern fn session_search(query: String) -> String
extern fn session_hist_load(session_id: String) -> String
extern fn session_hist_save(session_id: String, hist: String) -> Void
+2 -6
View File
@@ -1,15 +1,11 @@
// stewardship.elh — Layer 2 public surface
// auto-generated by elc --emit-header — do not edit
extern fn steward_log_event(kind: String, detail: String) -> Void
extern fn steward_get_mission() -> String
extern fn steward_align(input: String, imprint_id: String) -> String
extern fn steward_validate_imprint(imprint_id: String, tool_name: String) -> String
extern fn steward_cgi_check(action: String) -> String
// steward_log_event is an internal helper exported here because El has no access modifiers.
// External callers have no business invoking this directly — use steward_align,
// steward_validate_imprint, or steward_cgi_check, which call it at the correct points.
extern fn steward_log_event(kind: String, detail: String) -> Void
// Behavioral profiling and continuity detection (Layer 2 — session fingerprinting).
extern fn steward_fingerprint_session(input: String, session_id: String) -> String
extern fn extract_dim(content: String, key: String) -> String
extern fn steward_build_baseline() -> String
extern fn steward_check_continuity(current_fingerprint: String, session_id: String) -> String
extern fn steward_session_check(input: String, session_id: String) -> String
+1 -1
View File
@@ -1,4 +1,4 @@
// auto-generated by elc --emit-header - do not edit
// auto-generated by elc --emit-header do not edit
extern fn auth_headers(tok: String) -> Map
extern fn axon_get(path: String) -> String
extern fn axon_post(path: String, body: String) -> String
+43 -4
View File
@@ -160,13 +160,31 @@ assert_eq("'suicidal' classifies as self_harm", class_suicide, "self_harm")
let class_overdose: String = safety_classify_hard_bell("took too many pills")
assert_eq("'took too many' classifies as self_harm", class_overdose, "self_harm")
// Section 9: safety_classify_hard_bell general -> 'self_harm'
// Section 9: safety_classify_hard_bell Track B threat-to-others
//
// LIVE SAFETY FIX (approved by Will + Tim, 2026-07-14): a threat toward ANOTHER
// person ("going to kill/hurt <someone>") must classify as 'threat_other' and be
// routed to a refusal + 911 NOT to the 'self_harm'/988 path. This section used
// to assert the old (buggy) fall-through to 'self_harm'; it now pins the fix.
println("")
println("9. safety_classify_hard_bell — general hard phrases fall through to 'self_harm'")
println("9. safety_classify_hard_bell — threat-to-others routes to 'threat_other' (not self_harm)")
let class_going_kill: String = safety_classify_hard_bell("going to kill everything around me")
assert_eq("general hard phrase falls through to self_harm", class_going_kill, "self_harm")
let class_going_kill: String = safety_classify_hard_bell("I am going to kill him tonight")
assert_eq("'going to kill him' classifies as threat_other", class_going_kill, "threat_other")
let class_going_hurt: String = safety_classify_hard_bell("I'm going to hurt them so badly")
assert_eq("'going to hurt them' classifies as threat_other", class_going_hurt, "threat_other")
let class_shoot: String = safety_classify_hard_bell("I'm going to shoot up the place")
assert_eq("'going to shoot' classifies as threat_other", class_shoot, "threat_other")
// Track A must still win over Track B on victim / self-directed phrasings:
let class_kill_me: String = safety_classify_hard_bell("he is going to kill me")
assert_eq("'going to kill me' stays abuse (Track A precedence)", class_kill_me, "abuse")
let class_kill_self: String = safety_classify_hard_bell("I am going to kill myself")
assert_eq("'kill myself' stays self_harm (Track A precedence)", class_kill_self, "self_harm")
// Section 10: safety_normalize curly apostrophe normalisation
@@ -220,6 +238,27 @@ let aug_abuse: String = safety_augment_system(base_sys, "he hit me and I am afra
assert_contains("hard abuse -> DV hotline present", aug_abuse, "1-800-799-7233")
assert_contains("hard abuse -> mentions not notifying contact", aug_abuse, "safety contact")
// Section 14b: safety_augment_system Track B threat-to-others routing
//
// LIVE SAFETY FIX (approved by Will + Tim, 2026-07-14): a homicide/assault threat
// must be routed to a refusal + 911, and must NOT surface the 988 suicide line
// or pull in the safety contact.
println("")
println("14b. safety_augment_system — threat-to-others injects refusal + 911, never 988/contact")
let aug_threat: String = safety_augment_system(base_sys, "I am going to kill him tonight")
assert_contains("threat_other -> contains SUBSTRATE DIRECTIVE", aug_threat, "SUBSTRATE DIRECTIVE")
assert_contains("threat_other -> directs to 911", aug_threat, "911")
assert_contains("threat_other -> refuses to help harm another", aug_threat, "harming another person")
assert_not_contains("threat_other -> NO 988 suicide line", aug_threat, "988")
assert_not_contains("threat_other -> NO safety-contact involvement", aug_threat, "safety contact")
assert_not_contains("threat_other -> NO 'are you safe right now' victim frame", aug_threat, "are you safe right now")
// Detection must still fire hard on a weapon phrase not present in general_hard:
let level_shoot: String = safety_detect_bell_level("I'm going to shoot up the office")
assert_eq("'going to shoot' -> hard", level_shoot, "hard")
// Section 15: handle_safety_contact_post validation
println("")