Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 95cb49a8b0 | |||
| 795b32ad1a | |||
| 87c7d15b67 | |||
| 93bed793c0 | |||
| 936b3f0ac9 | |||
| 45dc80230d | |||
| 9ba86b8f80 | |||
| 360c15d7fe | |||
| 0c5b966773 | |||
| c87a536da3 | |||
| f0545defdb | |||
| ae9a139440 | |||
| b7fd8901d4 | |||
| dcf050ee3c | |||
| b2008f4894 | |||
| d92b8c279a | |||
| e9a8a659e0 | |||
| 1b83b18c39 |
@@ -150,9 +150,43 @@ fn engram_compile(intent: String) -> String {
|
||||
""
|
||||
}
|
||||
|
||||
// Affective context: always include the most recent high-emotion memory if one
|
||||
// exists within 72 hours. This ensures continuity of care across turns — when
|
||||
// the user was in distress earlier in the session (or recently), that context
|
||||
// travels into every subsequent LLM call so the response register stays aware.
|
||||
// We search for BellEvent nodes specifically; these are written by auto_persist
|
||||
// when safety_detect_bell_level fires. The 72h window (259200 seconds) is wide
|
||||
// enough to span a multi-session day without pulling ancient history.
|
||||
let bell_nodes: String = engram_search_json("bell:soft bell:hard BellEvent", 3)
|
||||
let bell_ok: Bool = !str_eq(bell_nodes, "") && !str_eq(bell_nodes, "[]")
|
||||
let now_ts: Int = time_now()
|
||||
let cutoff_ts: Int = now_ts - 259200
|
||||
let recent_bell: String = if bell_ok {
|
||||
let bn0: String = json_array_get(bell_nodes, 0)
|
||||
// created_at is not present in engram node JSON for BellEvent nodes.
|
||||
// Extract the timestamp embedded in the content string as " | ts:NNNNN".
|
||||
// Fall back to created_at / updated_at JSON fields if the marker is absent.
|
||||
let bn_content: String = json_get(bn0, "content")
|
||||
let ts_marker: String = " | ts:"
|
||||
let ts_pos: Int = str_index_of(bn_content, ts_marker)
|
||||
let bn_ts_raw: String = if ts_pos >= 0 {
|
||||
let ts_start: Int = ts_pos + str_len(ts_marker)
|
||||
let rest: String = str_slice(bn_content, ts_start, str_len(bn_content))
|
||||
let next_sep: Int = str_index_of(rest, " | ")
|
||||
if next_sep < 0 { rest } else { str_slice(rest, 0, next_sep) }
|
||||
} else {
|
||||
let ca: String = json_get(bn0, "created_at")
|
||||
if str_eq(ca, "") { json_get(bn0, "updated_at") } else { ca }
|
||||
}
|
||||
let bn_ts: Int = if str_eq(bn_ts_raw, "") { 0 } else { str_to_int(bn_ts_raw) }
|
||||
if bn_ts > cutoff_ts { bn0 } else { "" }
|
||||
} else { "" }
|
||||
let affective_part: String = if !str_eq(recent_bell, "") { recent_bell } else { "" }
|
||||
|
||||
let sep1: String = if !str_eq(act_part, "") && !str_eq(srch_part, "") { "\n" } else { "" }
|
||||
let sep2: String = if (!str_eq(act_part, "") || !str_eq(srch_part, "")) && !str_eq(scan_part, "") { "\n" } else { "" }
|
||||
let ctx: String = act_part + sep1 + srch_part + sep2 + scan_part
|
||||
let sep3: String = if (!str_eq(act_part, "") || !str_eq(srch_part, "") || !str_eq(scan_part, "")) && !str_eq(affective_part, "") { "\n" } else { "" }
|
||||
let ctx: String = act_part + sep1 + srch_part + sep2 + scan_part + sep3 + affective_part
|
||||
|
||||
if str_eq(ctx, "") { return "" }
|
||||
|
||||
@@ -199,7 +233,15 @@ fn build_system_prompt(ctx: String) -> String {
|
||||
"\n\n[ENGRAM CONTEXT — compiled from your graph]\n" + ctx
|
||||
}
|
||||
|
||||
return identity + date_line + voice_rules + security_rules + capability_rules + identity_block + engram_block
|
||||
let safety_addendum: String = state_get("layered_cycle_safety_system_addendum")
|
||||
let safety_block: String = if str_eq(safety_addendum, "") {
|
||||
""
|
||||
} else {
|
||||
state_set("layered_cycle_safety_system_addendum", "")
|
||||
safety_addendum
|
||||
}
|
||||
|
||||
return identity + date_line + voice_rules + security_rules + capability_rules + identity_block + engram_block + safety_block
|
||||
}
|
||||
|
||||
fn hist_append(hist: String, role: String, content: String) -> String {
|
||||
@@ -226,6 +268,69 @@ fn hist_trim(hist: String) -> String {
|
||||
return hist
|
||||
}
|
||||
|
||||
// hist_trim_with_bell_guard — trim the history window exactly as hist_trim does, but
|
||||
// before dropping the oldest user/assistant pair check whether the user turn triggered
|
||||
// a bell event. If it did, write a preservation node to engram so the distress exchange
|
||||
// survives the 20-turn window. The LLM window drops it; engram retains it permanently
|
||||
// and engram_compile will surface it again via the affective context path.
|
||||
fn hist_trim_with_bell_guard(hist: String) -> String {
|
||||
// Extract the first turn (should be a user message) to inspect it.
|
||||
let inner: String = str_slice(hist, 1, str_len(hist) - 1)
|
||||
let marker: String = "{\"role\":"
|
||||
let i1: Int = str_index_of(inner, marker)
|
||||
// i1 is the start of the first entry within inner.
|
||||
// Find where the second entry begins to delimit the first entry's JSON.
|
||||
let tail1: String = str_slice(inner, i1 + 1, str_len(inner))
|
||||
let i2: Int = str_index_of(tail1, marker)
|
||||
// The first entry spans from i1 to (i1 + 1 + i2 - 1) within inner.
|
||||
let first_entry_raw: String = if i2 > 0 {
|
||||
str_slice(inner, i1, i1 + 1 + i2 - 1)
|
||||
} else {
|
||||
str_slice(inner, i1, str_len(inner))
|
||||
}
|
||||
let first_role: String = json_get(first_entry_raw, "role")
|
||||
let first_content: String = json_get(first_entry_raw, "content")
|
||||
|
||||
// Only inspect user turns — assistant content doesn't carry bell signals.
|
||||
let bell_level: String = if str_eq(first_role, "user") {
|
||||
safety_detect_bell_level(first_content)
|
||||
} else {
|
||||
"none"
|
||||
}
|
||||
|
||||
// If the turn being evicted triggered a bell, preserve it to engram.
|
||||
// This is distinct from the BellEvent written by auto_persist: that node
|
||||
// carries a short summary. This node carries the full exchange content so
|
||||
// it is recoverable for clinical/continuity review.
|
||||
if !str_eq(bell_level, "none") {
|
||||
let ts: Int = time_now()
|
||||
let ts_str: String = int_to_str(ts)
|
||||
let safe_content: String = str_replace(first_content, "\"", "'")
|
||||
let preserve_content: String = "PRESERVED_BELL:" + bell_level
|
||||
+ " | evicted_at:" + ts_str
|
||||
+ " | message:" + safe_content
|
||||
let preserve_tags: String = "[\"bell-history\",\"bell:" + bell_level + "\",\"evicted\",\"affective\",\"BellEvent\"]"
|
||||
let discard: String = engram_node_full(
|
||||
preserve_content,
|
||||
"BellEvent",
|
||||
"bell:" + bell_level + ":preserved",
|
||||
el_from_float(0.9),
|
||||
el_from_float(0.9),
|
||||
el_from_float(1.0),
|
||||
"Episodic",
|
||||
preserve_tags
|
||||
)
|
||||
}
|
||||
|
||||
// Now perform the standard trim (drop oldest 2 entries = 1 user + 1 assistant pair).
|
||||
let tail2: String = str_slice(tail1, i2 + 1, str_len(tail1))
|
||||
let i3: Int = str_index_of(tail2, marker)
|
||||
if i3 >= 0 {
|
||||
return "[" + str_slice(tail2, i3, str_len(tail2)) + "]"
|
||||
}
|
||||
return hist
|
||||
}
|
||||
|
||||
// clean_llm_response — strips GPT-2 BPE byte-to-unicode artifacts that vLLM
|
||||
// emits when the tokenizer hasn't decoded back to raw bytes.
|
||||
//
|
||||
@@ -242,11 +347,26 @@ fn clean_llm_response(s: String) -> String {
|
||||
}
|
||||
|
||||
// conv_history_persist — save conversation history to engram for cross-restart continuity.
|
||||
// Stores as a Conversation node. Overwrites by using consistent label "conv:history".
|
||||
// Delete-before-write under label "conv:history" prevents unbounded node accumulation (issue #11).
|
||||
fn conv_history_persist(hist: String) -> Void {
|
||||
if str_eq(hist, "") { return "" }
|
||||
if str_eq(hist, "[]") { return "" }
|
||||
let ts: Int = time_now()
|
||||
// Delete any existing conv:history nodes before writing to avoid accumulation.
|
||||
let old_hist_results: String = engram_search_json("conv:history", 3)
|
||||
let old_hist_ok: Bool = !str_eq(old_hist_results, "") && !str_eq(old_hist_results, "[]")
|
||||
if old_hist_ok {
|
||||
let ohr_total: Int = json_array_len(old_hist_results)
|
||||
let ohr_i: Int = 0
|
||||
while ohr_i < ohr_total {
|
||||
let ohr_node: String = json_array_get(old_hist_results, ohr_i)
|
||||
let ohr_label: String = json_get(ohr_node, "label")
|
||||
let ohr_id: String = json_get(ohr_node, "id")
|
||||
if str_eq(ohr_label, "conv:history") && !str_eq(ohr_id, "") {
|
||||
engram_forget(ohr_id)
|
||||
}
|
||||
let ohr_i = ohr_i + 1
|
||||
}
|
||||
}
|
||||
let tags: String = "[\"conv-history\",\"persistent\"]"
|
||||
let discard: String = engram_node_full(
|
||||
hist, "Conversation", "conv:history",
|
||||
@@ -293,8 +413,34 @@ fn handle_chat(body: String) -> String {
|
||||
message
|
||||
}
|
||||
|
||||
// Cross-session affective context: on session start (no history yet), check engram
|
||||
// for recent distress signals within 72h and prepend a care directive if found.
|
||||
// Fixes issue #6: soul_affective_context is pre-loaded at boot — use it first to
|
||||
// avoid a redundant engram search and to make the boot-time state key functional.
|
||||
let affective_prefix: String = if hist_len == 0 {
|
||||
let soul_aff_ctx: String = state_get("soul_affective_context")
|
||||
let found_recent: Bool = if !str_eq(soul_aff_ctx, "") {
|
||||
true
|
||||
} else {
|
||||
let distress_nodes: String = engram_search_json("bell distress crisis loss grief despair", 3)
|
||||
let has_nodes: Bool = !str_eq(distress_nodes, "") && !str_eq(distress_nodes, "[]")
|
||||
let now_ts: Int = time_now()
|
||||
let cutoff: Int = now_ts - 259200
|
||||
if has_nodes {
|
||||
let dn0: String = json_array_get(distress_nodes, 0)
|
||||
let ts0_raw: String = json_get(dn0, "created_at")
|
||||
let ts0_str: String = if str_eq(ts0_raw, "") { json_get(dn0, "updated_at") } else { ts0_raw }
|
||||
let ts0: Int = if str_eq(ts0_str, "") { 0 } else { str_to_int(ts0_str) }
|
||||
ts0 > cutoff
|
||||
} else { false }
|
||||
}
|
||||
if found_recent {
|
||||
"[RECENT CONTEXT: User recently expressed significant distress. Monitor for indirect crisis signals and respond with care.]\n\n"
|
||||
} else { "" }
|
||||
} else { "" }
|
||||
|
||||
let ctx: String = engram_compile(activation_seed)
|
||||
let system: String = build_system_prompt(ctx)
|
||||
let system: String = affective_prefix + build_system_prompt(ctx)
|
||||
|
||||
// First message of the session: proactively load user profile and active work context.
|
||||
// These two searches give the soul grounding before any conversation history exists.
|
||||
@@ -305,6 +451,49 @@ fn handle_chat(body: String) -> String {
|
||||
let profile_ok: Bool = !str_eq(profile_nodes, "") && !str_eq(profile_nodes, "[]")
|
||||
let work_ok: Bool = !str_eq(work_nodes, "") && !str_eq(work_nodes, "[]")
|
||||
|
||||
// Load the previous session summary. Search by label text + type, then filter by
|
||||
// exact label match. Fallback: broader vector search for SessionSummary nodes.
|
||||
// Fixes issue #2: prev session summary was never loaded at startup.
|
||||
// Fixes issue #2b (phantom engram_get_node_by_label replaced with engram_search_json).
|
||||
let sum_search_nodes: String = engram_search_json("session:summary SessionSummary", 5)
|
||||
let sum_search_ok: Bool = !str_eq(sum_search_nodes, "") && !str_eq(sum_search_nodes, "[]")
|
||||
let prev_sum_node_content: String = if sum_search_ok {
|
||||
let ss_total: Int = json_array_len(sum_search_nodes)
|
||||
let ssi: Int = 0
|
||||
let found_content: String = ""
|
||||
while ssi < ss_total {
|
||||
let ss_node: String = json_array_get(sum_search_nodes, ssi)
|
||||
let ss_label: String = json_get(ss_node, "label")
|
||||
let ss_type: String = json_get(ss_node, "node_type")
|
||||
let ss_content: String = json_get(ss_node, "content")
|
||||
let found_content = if str_eq(ss_label, "session:summary") && str_eq(ss_type, "SessionSummary") && !str_eq(ss_content, "") {
|
||||
if str_eq(found_content, "") { ss_content } else { found_content }
|
||||
} else { found_content }
|
||||
let ssi = ssi + 1
|
||||
}
|
||||
found_content
|
||||
} else { "" }
|
||||
// Check state first: soul.el pre-loads this at boot (soul_prev_session_summary) — fixes issue #5.
|
||||
let soul_cached_sum: String = state_get("soul_prev_session_summary")
|
||||
let prev_summary_raw: String = if !str_eq(soul_cached_sum, "") {
|
||||
soul_cached_sum
|
||||
} else if !str_eq(prev_sum_node_content, "") {
|
||||
prev_sum_node_content
|
||||
} else {
|
||||
let sum_nodes: String = engram_search_json("SessionSummary previous-session", 3)
|
||||
let sum_ok: Bool = !str_eq(sum_nodes, "") && !str_eq(sum_nodes, "[]")
|
||||
if sum_ok {
|
||||
let sn0: String = json_array_get(sum_nodes, 0)
|
||||
let stype: String = json_get(sn0, "node_type")
|
||||
let scontent: String = json_get(sn0, "content")
|
||||
if str_eq(stype, "SessionSummary") && !str_eq(scontent, "") { scontent } else { "" }
|
||||
} else { "" }
|
||||
}
|
||||
let has_prev_summary: Bool = !str_eq(prev_summary_raw, "")
|
||||
let prev_summary_snip: String = if str_len(prev_summary_raw) > 400 {
|
||||
str_slice(prev_summary_raw, 0, 400)
|
||||
} else { prev_summary_raw }
|
||||
|
||||
// Extract content fields and render as bullet points (one per node, first 120 chars).
|
||||
let profile_bullets: String = if profile_ok {
|
||||
let pn: Int = json_array_len(profile_nodes)
|
||||
@@ -352,15 +541,19 @@ fn handle_chat(body: String) -> String {
|
||||
|
||||
let has_profile: Bool = !str_eq(profile_bullets, "")
|
||||
let has_work: Bool = !str_eq(work_bullets, "")
|
||||
let preload: String = if has_profile || has_work {
|
||||
let preload: String = if has_profile || has_work || has_prev_summary {
|
||||
let summary_section: String = if has_prev_summary {
|
||||
"[PREVIOUS SESSION - what we discussed last time]\n" + prev_summary_snip
|
||||
} else { "" }
|
||||
let profile_section: String = if has_profile {
|
||||
"[USER CONTEXT — from memory]\n" + profile_bullets
|
||||
"[USER CONTEXT - from memory]\n" + profile_bullets
|
||||
} else { "" }
|
||||
let work_section: String = if has_work {
|
||||
"[ACTIVE WORK — from memory]\n" + work_bullets
|
||||
"[ACTIVE WORK - from memory]\n" + work_bullets
|
||||
} else { "" }
|
||||
let sep_sp: String = if has_prev_summary && (has_profile || has_work) { "\n\n" } else { "" }
|
||||
let sep_pw: String = if has_profile && has_work { "\n\n" } else { "" }
|
||||
"\n\n" + profile_section + sep_pw + work_section
|
||||
"\n\n" + summary_section + sep_sp + profile_section + sep_pw + work_section
|
||||
} else { "" }
|
||||
preload
|
||||
} else { "" }
|
||||
@@ -374,6 +567,10 @@ fn handle_chat(body: String) -> String {
|
||||
let req_model: String = json_get(body, "model")
|
||||
let model: String = if str_eq(req_model, "") { chat_default_model() } else { req_model }
|
||||
|
||||
// ISSUE 9: add safety_augment_system to primary /api/chat path.
|
||||
// handle_chat was the only LLM path missing bell directive injection.
|
||||
let full_system = safety_augment_system(full_system, message)
|
||||
|
||||
let raw_response: String = llm_call_system(model, full_system, message)
|
||||
|
||||
let is_error: Bool = str_starts_with(raw_response, "{\"error\"")
|
||||
@@ -388,14 +585,24 @@ fn handle_chat(body: String) -> String {
|
||||
|
||||
let updated_hist: String = hist_append(stored_hist, "user", message)
|
||||
let updated_hist2: String = hist_append(updated_hist, "assistant", raw_response)
|
||||
// Use bell-guarded trim: if the evicted turn triggered a bell event, it is
|
||||
// preserved to engram before being dropped from the in-memory window.
|
||||
let final_hist: String = if json_array_len(updated_hist2) > 20 {
|
||||
hist_trim(updated_hist2)
|
||||
hist_trim_with_bell_guard(updated_hist2)
|
||||
} else {
|
||||
updated_hist2
|
||||
}
|
||||
state_set("conv_history", final_hist)
|
||||
conv_history_persist(final_hist)
|
||||
|
||||
// Automatic session-end summary: write/overwrite the SessionSummary node on each turn
|
||||
// so process restarts always have a continuity snapshot (no shutdown hook needed).
|
||||
// Uses autogenerate (no LLM) so it is cheap — the node is overwritten not appended.
|
||||
let auto_sum: String = session_summary_autogenerate(final_hist)
|
||||
if !str_eq(auto_sum, "") {
|
||||
let discard_sum: String = session_summary_write(auto_sum)
|
||||
}
|
||||
|
||||
let activation_nodes: String = engram_activate_json(message, 2)
|
||||
let act_ok: Bool = !str_eq(activation_nodes, "") && !str_eq(activation_nodes, "[]")
|
||||
let act_out: String = if act_ok { activation_nodes } else { "[]" }
|
||||
@@ -606,7 +813,8 @@ fn path_within_root(path: String, root: String) -> Bool {
|
||||
return false
|
||||
}
|
||||
if str_starts_with(path, "/") {
|
||||
return str_starts_with(path, root)
|
||||
let root_normalized: String = root + "/"
|
||||
return str_starts_with(path, root_normalized)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -697,12 +905,17 @@ fn dispatch_tool(tool_name: String, tool_input: String) -> String {
|
||||
let path: String = json_get(tool_input, "path")
|
||||
let old_text: String = json_get(tool_input, "old_text")
|
||||
let new_text: String = json_get(tool_input, "new_text")
|
||||
let content: String = fs_read(path)
|
||||
let root: String = agent_workspace_root()
|
||||
if !path_within_root(path, root) {
|
||||
return json_safe("denied: path is outside the agent workspace root")
|
||||
}
|
||||
let resolved: String = resolve_in_root(path, root)
|
||||
let content: String = fs_read(resolved)
|
||||
if str_eq(content, "") {
|
||||
return json_safe("{\"error\":\"file not found\"}")
|
||||
}
|
||||
let updated: String = str_replace(content, old_text, new_text)
|
||||
fs_write(path, updated)
|
||||
fs_write(resolved, updated)
|
||||
return json_safe("{\"ok\":true}")
|
||||
}
|
||||
if str_eq(tool_name, "remember") {
|
||||
@@ -819,9 +1032,22 @@ fn handle_chat_agentic(body: String) -> String {
|
||||
return "{\"error\":\"message required\",\"reply\":\"\"}"
|
||||
}
|
||||
|
||||
// Workspace scope (#23): the desktop UI sends the user-chosen Agent Workspace root
|
||||
// on every agentic request. Persist it to state so agent_workspace_root() — and the
|
||||
// path/command tool guards that read it — confine this turn's file/command tools to
|
||||
// that subtree. Only set when non-empty: an empty/absent field means the client sent
|
||||
// no root (or cleared the field), and we must not overwrite a server-configured root
|
||||
// from NEURON_AGENT_ROOT with an empty string, which would silently un-scope the agent.
|
||||
let ws_root: String = json_get(body, "agent_workspace_root")
|
||||
if !str_eq(ws_root, "") {
|
||||
state_set("agent_workspace_root", ws_root)
|
||||
}
|
||||
|
||||
// L1 safety screen — agentic path must pass the same gate as layered_cycle.
|
||||
// Hard bell: return the crisis response immediately, do not enter the agentic loop.
|
||||
let history: String = state_get("conversation_history")
|
||||
// Fix(issue #9): "conversation_history" key was never written; history lives under "conv_history".
|
||||
// Old key caused history-amplification in safety_screen to always receive "" on agentic path.
|
||||
let history: String = state_get("conv_history")
|
||||
let screen_result: String = safety_screen(message, history)
|
||||
let screen_action: String = json_get(screen_result, "action")
|
||||
if str_eq(screen_action, "hard_bell") {
|
||||
@@ -835,8 +1061,30 @@ fn handle_chat_agentic(body: String) -> String {
|
||||
// Thread-aware activation: same logic as handle_chat.
|
||||
// Use the session's or global history to anchor short messages to the thread.
|
||||
let req_session: String = json_get(body, "session_id")
|
||||
|
||||
// ISSUE #6/#7: validate that the session_id actually exists before proceeding.
|
||||
// Without this check the loop silently treats any unknown/fabricated session_id
|
||||
// as a fresh session — history loads as empty and no error is returned to the caller.
|
||||
// Only validate when a session_id is explicitly provided; anonymous calls
|
||||
// (no session_id) continue to work for backward compatibility.
|
||||
let session_valid: Bool = if str_eq(req_session, "") {
|
||||
true
|
||||
} else {
|
||||
session_exists(req_session)
|
||||
}
|
||||
if !session_valid {
|
||||
return "{\"error\":\"session not found\",\"session_id\":\"" + req_session + "\",\"reply\":\"\"}"
|
||||
}
|
||||
|
||||
let hist_key: String = if str_eq(req_session, "") { "conv_history" } else { "session_hist_" + req_session }
|
||||
let agentic_hist: String = state_get(hist_key)
|
||||
// Fall back to engram (via session_hist_load) when state is cold — fixes issue #4:
|
||||
// named-session history written under session:messages:SESSION_ID was never read back.
|
||||
let agentic_hist_state: String = state_get(hist_key)
|
||||
let agentic_hist: String = if str_eq(agentic_hist_state, "") && !str_eq(req_session, "") {
|
||||
let loaded: String = session_hist_load(req_session)
|
||||
if !str_eq(loaded, "") { state_set(hist_key, loaded) }
|
||||
if str_eq(loaded, "") { conv_history_load() } else { loaded }
|
||||
} else { agentic_hist_state }
|
||||
let agentic_hist_len: Int = if str_eq(agentic_hist, "") { 0 } else { json_array_len(agentic_hist) }
|
||||
let ag_is_cont: Bool = str_len(message) < 50 && agentic_hist_len > 0
|
||||
let ag_last_entry: String = if ag_is_cont { json_array_get(agentic_hist, agentic_hist_len - 1) } else { "" }
|
||||
@@ -879,6 +1127,23 @@ fn handle_chat_agentic(body: String) -> String {
|
||||
let updated2: String = hist_append(updated, "assistant", reply_text)
|
||||
let trimmed: String = if json_array_len(updated2) > 20 { hist_trim(updated2) } else { updated2 }
|
||||
state_set(hist_key, trimmed)
|
||||
// Persist to engram for cross-restart continuity.
|
||||
// Named sessions use session_hist_save (session:messages:SESSION_ID label) so that
|
||||
// session_hist_load can recover them on the next restart — fixes issue #4.
|
||||
// The old conv:history:SESSION_ID label was a dead write (never read back).
|
||||
if str_eq(hist_key, "conv_history") {
|
||||
conv_history_persist(trimmed)
|
||||
} else {
|
||||
if !str_eq(trimmed, "") && !str_eq(trimmed, "[]") {
|
||||
session_hist_save(req_session, trimmed)
|
||||
}
|
||||
}
|
||||
// Write automatic session summary so cross-session continuity is maintained
|
||||
// on the agentic path too — fixes issue #7.
|
||||
let ag_auto_sum: String = session_summary_autogenerate(trimmed)
|
||||
if !str_eq(ag_auto_sum, "") {
|
||||
let discard_ag_sum: String = session_summary_write(ag_auto_sum)
|
||||
}
|
||||
true
|
||||
} else { false }
|
||||
|
||||
@@ -1332,6 +1597,74 @@ fn handle_dharma_room_turn_agentic(body: String) -> String {
|
||||
return "{\"response\":\"" + safe_text + "\",\"cgi_id\":\"" + cgi_id + "\",\"tools_used\":" + eff_tools + "}"
|
||||
}
|
||||
|
||||
// session_summary_write — write or overwrite the SessionSummary node in engram.
|
||||
// Uses delete-before-write so there is always exactly one "session:summary" node.
|
||||
// This is what session_preload at next startup reads to know what was discussed.
|
||||
fn session_summary_write(summary_text: String) -> String {
|
||||
if str_eq(summary_text, "") { return "" }
|
||||
let safe_text: String = str_replace(summary_text, "\"", "'")
|
||||
let trimmed: String = if str_len(safe_text) > 800 { str_slice(safe_text, 0, 800) } else { safe_text }
|
||||
let ts: Int = time_now()
|
||||
let ts_str: String = int_to_str(ts)
|
||||
let content: String = "[session-summary] " + trimmed + " | ts:" + ts_str
|
||||
// Delete old node before writing so duplicate label nodes don't accumulate.
|
||||
// engram_get_node_by_label doesn't exist — search by label text and filter by exact match.
|
||||
let old_search: String = engram_search_json("session:summary SessionSummary", 5)
|
||||
let old_search_ok: Bool = !str_eq(old_search, "") && !str_eq(old_search, "[]")
|
||||
if old_search_ok {
|
||||
let os_total: Int = json_array_len(old_search)
|
||||
let osi: Int = 0
|
||||
while osi < os_total {
|
||||
let os_node: String = json_array_get(old_search, osi)
|
||||
let os_label: String = json_get(os_node, "label")
|
||||
let os_id: String = json_get(os_node, "id")
|
||||
if str_eq(os_label, "session:summary") && !str_eq(os_id, "") {
|
||||
engram_forget(os_id)
|
||||
}
|
||||
let osi = osi + 1
|
||||
}
|
||||
}
|
||||
let tags: String = "[\"SessionSummary\",\"session-summary\",\"previous-session\",\"consolidate\"]"
|
||||
let node_id: String = engram_node_full(
|
||||
content, "SessionSummary", "session:summary",
|
||||
el_from_float(0.85), el_from_float(0.85), el_from_float(1.0),
|
||||
"Episodic", tags
|
||||
)
|
||||
if str_eq(node_id, "") {
|
||||
println("[chat] session_summary_write: engram write failed — summary node lost")
|
||||
return ""
|
||||
}
|
||||
println("[chat] session_summary_write: wrote SessionSummary (" + int_to_str(str_len(content)) + " chars) -> " + node_id)
|
||||
return node_id
|
||||
}
|
||||
|
||||
// session_summary_autogenerate — build a minimal summary from conversation history without LLM.
|
||||
// Extracts user message snippets (first 80 chars each, up to 5 turns).
|
||||
// Used as the automatic session-end hook so every turn produces a continuity snapshot.
|
||||
fn session_summary_autogenerate(hist: String) -> String {
|
||||
if str_eq(hist, "") { return "" }
|
||||
if str_eq(hist, "[]") { return "" }
|
||||
let total: Int = json_array_len(hist)
|
||||
if total == 0 { return "" }
|
||||
let snippets: String = ""
|
||||
let count: Int = 0
|
||||
let i: Int = 0
|
||||
while i < total && count < 5 {
|
||||
let entry: String = json_array_get(hist, i)
|
||||
let role: String = json_get(entry, "role")
|
||||
let msg: String = json_get(entry, "content")
|
||||
let snip: String = if str_len(msg) > 80 { str_slice(msg, 0, 80) } else { msg }
|
||||
// Mutations at top level of while body via if-expressions — inner if blocks don't escape scope.
|
||||
let snippets = if str_eq(role, "user") && !str_eq(snip, "") {
|
||||
if str_eq(snippets, "") { snip } else { snippets + "; " + snip }
|
||||
} else { snippets }
|
||||
let count = if str_eq(role, "user") && !str_eq(snip, "") { count + 1 } else { count }
|
||||
let i = i + 1
|
||||
}
|
||||
if str_eq(snippets, "") { return "" }
|
||||
return "Session covered: " + snippets
|
||||
}
|
||||
|
||||
fn auto_persist(req: String, resp: String) -> Void {
|
||||
let message: String = json_get(req, "message")
|
||||
let reply: String = json_get(resp, "response")
|
||||
@@ -1343,14 +1676,28 @@ fn auto_persist(req: String, resp: String) -> Void {
|
||||
let safe_msg: String = str_replace(message, "\"", "'")
|
||||
let safe_reply: String = str_replace(reply2, "\"", "'")
|
||||
|
||||
// Detect emotional salience before persisting. safety_detect_bell_level uses the
|
||||
// same phrase lists as the safety layer (safety.el), so the classification is
|
||||
// consistent with what safety_screen already evaluated for this turn.
|
||||
let bell_level: String = safety_detect_bell_level(message)
|
||||
let is_bell: Bool = !str_eq(bell_level, "none")
|
||||
|
||||
// Tag the Conversation node with bell metadata when distress is present so
|
||||
// subsequent affective queries (e.g. engram_compile) can find this exchange.
|
||||
let tags: String = if is_bell {
|
||||
"[\"Conversation\",\"chat\",\"timestamped\",\"bell:" + bell_level + "\",\"affective\"]"
|
||||
} else {
|
||||
"[\"Conversation\",\"chat\",\"timestamped\"]"
|
||||
}
|
||||
|
||||
let content: String = "{\"q\":\"" + safe_msg + "\""
|
||||
+ ",\"a\":\"" + safe_reply + "\""
|
||||
+ ",\"created_at\":" + ts_str
|
||||
+ ",\"source\":\"chat\""
|
||||
+ ",\"bell\":\"" + bell_level + "\""
|
||||
+ ",\"label\":\"chat:" + ts_str + "\"}"
|
||||
|
||||
let tags: String = "[\"Conversation\",\"chat\",\"timestamped\"]"
|
||||
engram_node_full(
|
||||
let conv_node_id: String = engram_node_full(
|
||||
content,
|
||||
"Conversation",
|
||||
"chat:" + ts_str,
|
||||
@@ -1360,6 +1707,72 @@ fn auto_persist(req: String, resp: String) -> Void {
|
||||
"Episodic",
|
||||
tags
|
||||
)
|
||||
|
||||
// When a bell fires, write a dedicated BellEvent node in addition to the
|
||||
// Conversation node. This makes distress moments directly findable by label
|
||||
// ("bell:soft" / "bell:hard") without having to scan all Conversation nodes.
|
||||
// The BellEvent carries higher salience so engram_compile pulls it into context.
|
||||
// The message content is truncated to 120 chars — enough signal, not a full dump.
|
||||
if is_bell {
|
||||
let summary: String = if str_len(message) > 120 { str_slice(message, 0, 120) } else { message }
|
||||
let safe_summary: String = str_replace(summary, "\"", "'")
|
||||
let bell_content: String = "BELL:" + bell_level
|
||||
+ " | ts:" + ts_str
|
||||
+ " | summary:" + safe_summary
|
||||
|
||||
// bell:hard gets peak salience; bell:soft is slightly lower.
|
||||
let sal_a: String = if str_eq(bell_level, "hard") { el_from_float(0.98) } else { el_from_float(0.88) }
|
||||
let sal_b: String = if str_eq(bell_level, "hard") { el_from_float(0.98) } else { el_from_float(0.88) }
|
||||
let sal_c: String = if str_eq(bell_level, "hard") { el_from_float(1.0) } else { el_from_float(0.95) }
|
||||
|
||||
let bell_tags: String = "[\"safety\",\"bell\",\"bell:" + bell_level + "\",\"affective\",\"BellEvent\"]"
|
||||
let bell_ts_str: String = int_to_str(time_now())
|
||||
let bell_label: String = "bell:" + bell_level + ":" + bell_ts_str
|
||||
let bell_node_id: String = engram_node_full(
|
||||
bell_content,
|
||||
"BellEvent",
|
||||
bell_label,
|
||||
sal_a,
|
||||
sal_b,
|
||||
sal_c,
|
||||
"Episodic",
|
||||
bell_tags
|
||||
)
|
||||
|
||||
// Increment session-level bell counter so session_hist_save knows whether
|
||||
// any bell fired during this session when writing a boundary summary.
|
||||
let sess_id: String = json_get(req, "session_id")
|
||||
let bell_key: String = if str_eq(sess_id, "") {
|
||||
"session_bell_count"
|
||||
} else {
|
||||
"session_bell_count:" + sess_id
|
||||
}
|
||||
let prior_count: String = state_get(bell_key)
|
||||
let prior_n: Int = if str_eq(prior_count, "") { 0 } else { str_to_int(prior_count) }
|
||||
state_set(bell_key, int_to_str(prior_n + 1))
|
||||
|
||||
// Also record the highest bell level seen this session so the boundary
|
||||
// summary can classify the session correctly (hard takes precedence).
|
||||
let level_key: String = if str_eq(sess_id, "") {
|
||||
"session_bell_level"
|
||||
} else {
|
||||
"session_bell_level:" + sess_id
|
||||
}
|
||||
let prior_level: String = state_get(level_key)
|
||||
let new_level: String = if str_eq(bell_level, "hard") { "hard" } else {
|
||||
if str_eq(prior_level, "hard") { "hard" } else { "soft" }
|
||||
}
|
||||
state_set(level_key, new_level)
|
||||
|
||||
// Stash a short signal summary for the boundary node (last bell wins for
|
||||
// the one-liner; the full history is in per-bell BellEvent nodes).
|
||||
let signal_key: String = if str_eq(sess_id, "") {
|
||||
"session_bell_signal"
|
||||
} else {
|
||||
"session_bell_signal:" + sess_id
|
||||
}
|
||||
state_set(signal_key, safe_summary)
|
||||
}
|
||||
}
|
||||
|
||||
// strengthen_chat_nodes — strengthen the engram nodes that were activated during a chat.
|
||||
|
||||
+8
-8
@@ -1,4 +1,5 @@
|
||||
import "memory.el"
|
||||
import "chat.el"
|
||||
|
||||
// neuron-api.el — Native Neuron cognitive API handlers.
|
||||
//
|
||||
@@ -654,14 +655,13 @@ fn handle_api_consolidate(body: String) -> String {
|
||||
engram_save(snap)
|
||||
}
|
||||
if !str_eq(summary, "") {
|
||||
let safe_summary: String = str_replace(summary, "\"", "'")
|
||||
let tags: String = "[\"SessionSummary\",\"consolidate\"]"
|
||||
let discard: String = engram_node_full(
|
||||
"[session-summary] " + safe_summary,
|
||||
"SessionSummary", "session:summary",
|
||||
el_from_float(0.7), el_from_float(0.7), el_from_float(0.9),
|
||||
"Episodic", tags
|
||||
)
|
||||
// Use session_summary_write to ensure delete-before-write semantics:
|
||||
// prevents stale SessionSummary accumulation across sessions (issue #11).
|
||||
// session_summary_write handles label indexing, trimming, and dedup.
|
||||
let sum_id: String = session_summary_write(summary)
|
||||
if str_eq(sum_id, "") {
|
||||
println("[api] consolidate: session_summary_write failed — summary not persisted")
|
||||
}
|
||||
}
|
||||
return "{\"ok\":true,\"snapshot\":\"" + snap + "\"}"
|
||||
}
|
||||
|
||||
@@ -7,6 +7,65 @@ import "neuron-api.el"
|
||||
import "sessions.el"
|
||||
import "soul.elh"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rate limiting — simple in-memory per-IP sliding window counter.
|
||||
//
|
||||
// State keys:
|
||||
// rl:<ip>:count — request count in the current window
|
||||
// rl:<ip>:window — window start timestamp (unix seconds)
|
||||
//
|
||||
// Limit: configurable via soul state key "soul_rate_limit" (requests per
|
||||
// minute). Falls back to 60 req/min if not set. The /health endpoint is
|
||||
// exempt so monitoring does not consume quota.
|
||||
//
|
||||
// State growth: each unique source IP accumulates exactly 2 state keys
|
||||
// (count + window) for the lifetime of the process. Per-IP storage is
|
||||
// bounded and constant; values reset on window expiry. In aggregate, state
|
||||
// grows linearly with distinct IPs — typical for a trusted-client service.
|
||||
// EL has no state_delete builtin, so keys from inactive IPs persist.
|
||||
// TODO: add state_delete sweep when the EL runtime exposes that primitive.
|
||||
//
|
||||
// Returns "" when the request is allowed, or a 429 JSON body when rejected.
|
||||
// ---------------------------------------------------------------------------
|
||||
fn rate_limit_check(ip: String, path: String) -> String {
|
||||
// Health checks are exempt — they must never be blocked.
|
||||
if str_eq(path, "/health") {
|
||||
return ""
|
||||
}
|
||||
|
||||
let limit_str: String = state_get("soul_rate_limit")
|
||||
let limit: Int = if str_eq(limit_str, "") { 60 } else { str_to_int(limit_str) }
|
||||
|
||||
let now: Int = time_now()
|
||||
let window_key: String = "rl:" + ip + ":window"
|
||||
let count_key: String = "rl:" + ip + ":count"
|
||||
|
||||
let win_str: String = state_get(window_key)
|
||||
let win_start: Int = if str_eq(win_str, "") { now } else { str_to_int(win_str) }
|
||||
|
||||
// New window every 60 seconds.
|
||||
let elapsed: Int = now - win_start
|
||||
let in_window: Bool = elapsed < 60
|
||||
|
||||
let prev_count_str: String = state_get(count_key)
|
||||
let prev_count: Int = if str_eq(prev_count_str, "") { 0 } else { str_to_int(prev_count_str) }
|
||||
|
||||
// Reset window if expired.
|
||||
let eff_count: Int = if in_window { prev_count } else { 0 }
|
||||
let eff_win: Int = if in_window { win_start } else { now }
|
||||
|
||||
let new_count: Int = eff_count + 1
|
||||
state_set(count_key, int_to_str(new_count))
|
||||
state_set(window_key, int_to_str(eff_win))
|
||||
|
||||
if new_count > limit {
|
||||
let retry_after: Int = 60 - (now - eff_win)
|
||||
let eff_retry: Int = if retry_after < 0 { 0 } else { retry_after }
|
||||
return "{\"__status__\":429,\"error\":\"rate limit exceeded\",\"code\":\"rate_limited\",\"retry_after_secs\":" + int_to_str(eff_retry) + "}"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
fn strip_query(path: String) -> String {
|
||||
let q: Int = str_index_of(path, "?")
|
||||
if q < 0 {
|
||||
@@ -16,11 +75,11 @@ fn strip_query(path: String) -> String {
|
||||
}
|
||||
|
||||
fn err_404(path: String) -> String {
|
||||
return "{\"error\":\"not found\",\"path\":\"" + path + "\"}"
|
||||
return "{\"error\":\"not found\",\"code\":\"not_found\",\"path\":\"" + path + "\"}"
|
||||
}
|
||||
|
||||
fn err_405(method: String, path: String) -> String {
|
||||
return "{\"error\":\"method not allowed\",\"method\":\"" + method + "\",\"path\":\"" + path + "\"}"
|
||||
return "{\"error\":\"method not allowed\",\"code\":\"method_not_allowed\",\"method\":\"" + method + "\",\"path\":\"" + path + "\"}"
|
||||
}
|
||||
|
||||
fn route_health() -> String {
|
||||
@@ -31,12 +90,35 @@ fn route_health() -> String {
|
||||
let edge_ct: Int = engram_edge_count()
|
||||
let pulse: String = state_get("soul.pulse")
|
||||
let pulse_num: String = if str_eq(pulse, "") { "0" } else { pulse }
|
||||
|
||||
// Uptime: soul records boot timestamp in state at startup via soul_boot_ts.
|
||||
// Compute elapsed seconds; fall back to -1 if not yet set.
|
||||
let boot_ts_str: String = state_get("soul_boot_ts")
|
||||
let uptime_secs: Int = if str_eq(boot_ts_str, "") {
|
||||
-1
|
||||
} else {
|
||||
time_now() - str_to_int(boot_ts_str)
|
||||
}
|
||||
|
||||
// LLM connectivity: probe with a minimal call. Any non-error reply = ok.
|
||||
// Use a short, fixed prompt so this never counts against conversation history.
|
||||
let model: String = state_get("soul_model")
|
||||
let eff_model: String = if str_eq(model, "") { "claude-sonnet-4-5" } else { model }
|
||||
let llm_probe: String = llm_call_system(eff_model, "You are a health probe. Reply with the single word: ok", "ping")
|
||||
let llm_ok: Bool = !str_eq(llm_probe, "")
|
||||
&& !str_starts_with(llm_probe, "{\"error\"")
|
||||
&& !str_starts_with(llm_probe, "{\"type\":\"error\"")
|
||||
&& !str_contains(llm_probe, "authentication_error")
|
||||
let llm_status: String = if llm_ok { "ok" } else { "unreachable" }
|
||||
|
||||
return "{\"status\":\"alive\""
|
||||
+ ",\"cgi_id\":\"" + cgi_id + "\""
|
||||
+ ",\"boot\":" + boot_num
|
||||
+ ",\"uptime_secs\":" + int_to_str(uptime_secs)
|
||||
+ ",\"node_count\":" + int_to_str(node_ct)
|
||||
+ ",\"edge_count\":" + int_to_str(edge_ct)
|
||||
+ ",\"pulse\":" + pulse_num
|
||||
+ ",\"llm\":\"" + llm_status + "\""
|
||||
+ ",\"layers\":{\"l0\":\"core\",\"l1\":\"safety\",\"l2\":\"stewardship\",\"l3\":\"" + imprint_current() + "\"}}"
|
||||
}
|
||||
|
||||
@@ -103,15 +185,15 @@ fn route_imprint_user(body: String) -> String {
|
||||
|
||||
fn route_synthesize(body: String) -> String {
|
||||
if str_eq(body, "") {
|
||||
return "{\"mechanism\":\"did not engage\"}"
|
||||
return "{\"error\":\"body is required\",\"code\":\"missing_param\"}"
|
||||
}
|
||||
let parent_a: String = json_get(body, "parent_a")
|
||||
let parent_b: String = json_get(body, "parent_b")
|
||||
if str_eq(parent_a, "") {
|
||||
return "{\"mechanism\":\"did not engage\"}"
|
||||
return "{\"error\":\"parent_a is required\",\"code\":\"missing_param\"}"
|
||||
}
|
||||
if str_eq(parent_b, "") {
|
||||
return "{\"mechanism\":\"did not engage\"}"
|
||||
return "{\"error\":\"parent_b is required\",\"code\":\"missing_param\"}"
|
||||
}
|
||||
let req: String = "synthesize " + parent_a + " " + parent_b
|
||||
let tags: String = "[\"soul-inbox-pending\",\"synthesis-request\"]"
|
||||
@@ -259,6 +341,17 @@ fn handle_connectors(method: String, clean: String, body: String) -> String {
|
||||
fn handle_request(method: String, path: String, body: String) -> String {
|
||||
let clean: String = strip_query(path)
|
||||
|
||||
// Rate limit check. Extract caller IP from REMOTE_ADDR env var (set by the
|
||||
// EL HTTP runtime for each request). Skip enforcement when empty so
|
||||
// loopback/internal callers are never blocked.
|
||||
let ip: String = env("REMOTE_ADDR")
|
||||
if !str_eq(ip, "") {
|
||||
let rl_result: String = rate_limit_check(ip, clean)
|
||||
if !str_eq(rl_result, "") {
|
||||
return rl_result
|
||||
}
|
||||
}
|
||||
|
||||
if str_eq(method, "POST") && str_eq(clean, "/dharma/recv") {
|
||||
return handle_dharma_recv(body)
|
||||
}
|
||||
@@ -286,7 +379,7 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
let raw_msg: String = json_get(body, "message")
|
||||
let eff_msg: String = if str_eq(raw_msg, "") { body } else { raw_msg }
|
||||
if str_eq(eff_msg, "") {
|
||||
return "{\"error\":\"message required\"}"
|
||||
return "{\"error\":\"message is required\",\"code\":\"missing_param\"}"
|
||||
}
|
||||
let agentic_flag: Bool = json_get_bool(body, "agentic")
|
||||
let reply: String = if agentic_flag {
|
||||
@@ -426,8 +519,15 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
return handle_elp_chat(body)
|
||||
}
|
||||
if str_eq(clean, "/api/chat") {
|
||||
let agentic_flag: Bool = json_get_bool(body, "agentic")
|
||||
// NOTE: streaming (SSE / chunked transfer) is not implemented. All chat
|
||||
// responses are buffered and returned as a single JSON object. Streaming
|
||||
// would require runtime-level SSE support in el_runtime.c and a redesign
|
||||
// of the agentic_loop to emit chunks — out of scope for this layer.
|
||||
let raw_msg: String = json_get(body, "message")
|
||||
if str_eq(raw_msg, "") {
|
||||
return "{\"error\":\"message is required\",\"code\":\"missing_param\"}"
|
||||
}
|
||||
let agentic_flag: Bool = json_get_bool(body, "agentic")
|
||||
let reply: String = if agentic_flag {
|
||||
handle_chat_agentic(body)
|
||||
} else {
|
||||
|
||||
@@ -144,17 +144,21 @@ fn safety_screen(input: String, history: String) -> String {
|
||||
if score >= soft {
|
||||
let summary: String = str_slice(input, 0, 80)
|
||||
let discard: String = safety_log_bell("soft", "wellbeing check needed", summary)
|
||||
// ISSUE 7: also escape tab chars to prevent JSON envelope corruption.
|
||||
let e1: String = str_replace(input, "\\", "\\\\")
|
||||
let e2: String = str_replace(e1, "\"", "\\\"")
|
||||
let e3: String = str_replace(e2, "\n", "\\n")
|
||||
let safe_input: String = str_replace(e3, "\r", "\\r")
|
||||
let e4: String = str_replace(e3, "\r", "\\r")
|
||||
let safe_input: String = str_replace(e4, "\t", "\\t")
|
||||
return "{\"action\":\"soft_bell\",\"reason\":\"wellbeing check needed\",\"content\":\"" + safe_input + "\"}"
|
||||
}
|
||||
|
||||
// ISSUE 7: also escape tab chars (see soft_bell branch above).
|
||||
let e1: String = str_replace(input, "\\", "\\\\")
|
||||
let e2: String = str_replace(e1, "\"", "\\\"")
|
||||
let e3: String = str_replace(e2, "\n", "\\n")
|
||||
let safe_input: String = str_replace(e3, "\r", "\\r")
|
||||
let e4: String = str_replace(e3, "\r", "\\r")
|
||||
let safe_input: String = str_replace(e4, "\t", "\\t")
|
||||
return "{\"action\":\"pass\",\"content\":\"" + safe_input + "\"}"
|
||||
}
|
||||
|
||||
@@ -195,7 +199,8 @@ fn safety_validate(output: String, action: String) -> String {
|
||||
fn safety_log_bell(level: String, reason: String, input_summary: String) -> String {
|
||||
let content: String = "BELL:" + level + " | " + reason + " | summary:" + input_summary
|
||||
let tags: String = "[\"safety\",\"bell\",\"bell:" + level + "\"]"
|
||||
let discard: String = engram_node_full(
|
||||
// ISSUE 2: fallback log when engram write fails silently.
|
||||
let node_id: String = engram_node_full(
|
||||
content,
|
||||
"BellEvent",
|
||||
"bell:" + level,
|
||||
@@ -205,6 +210,9 @@ fn safety_log_bell(level: String, reason: String, input_summary: String) -> Stri
|
||||
"Episodic",
|
||||
tags
|
||||
)
|
||||
if str_eq(node_id, "") {
|
||||
println("[safety] WARN: bell engram write failed -- " + content)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -232,9 +240,13 @@ fn safety_general_hard_phrases() -> String {
|
||||
}
|
||||
|
||||
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\",\"highest structure\",\"tallest building\",\"tallest structure\",\"highest building\",\"bridge near me\",\"overpass near\",\"rooftop near\"]"
|
||||
}
|
||||
|
||||
// ISSUE 5 TODO: phrase lists are rebuilt from JSON literals on every call.
|
||||
// json_array_len of malformed input returns 0, silently skipping all checks.
|
||||
// Caching requires language-level static const arrays -- not in current EL.
|
||||
// Migrate to const arrays when EL gains that feature.
|
||||
// ── Matching helpers (single loops only — el escapes while-body mutation via
|
||||
// top-level let rebinds; nested loops would not advance) ────────────────────
|
||||
|
||||
|
||||
+139
-1
@@ -36,7 +36,49 @@ fn session_make_content(id: String, title: String, created_at: Int, updated_at:
|
||||
+ ",\"updated_at\":" + int_to_str(updated_at) + "}"
|
||||
}
|
||||
|
||||
// session_exists — return true if the given session_id is known in Engram or state.
|
||||
// Used by chat.el to validate a session_id before processing a chat message.
|
||||
// Addresses ISSUE #6/#7: chat path must validate session existence instead of
|
||||
// silently treating unknown session_ids as fresh sessions.
|
||||
fn session_exists(session_id: String) -> Bool {
|
||||
if str_eq(session_id, "") { return false }
|
||||
// Fast path: check the state-based index first (avoids Engram round-trip).
|
||||
let idx: String = state_get("session_index")
|
||||
if !str_eq(idx, "") && !str_eq(idx, "[]") {
|
||||
if str_contains(idx, "\"id\":\"" + session_id + "\"") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// Slow path: check Engram directly (survives restarts when index is cold).
|
||||
let results: String = engram_search_json("session:meta " + session_id, 5)
|
||||
if str_eq(results, "") { return false }
|
||||
if str_eq(results, "[]") { return false }
|
||||
let total: Int = json_array_len(results)
|
||||
let found: Bool = false
|
||||
let i: Int = 0
|
||||
while i < total {
|
||||
let node: String = json_array_get(results, i)
|
||||
let label: String = json_get(node, "label")
|
||||
let content: String = json_get(node, "content")
|
||||
let sid: String = json_get(content, "id")
|
||||
let is_match: Bool = str_eq(label, "session:meta") && str_eq(sid, session_id)
|
||||
let found = if is_match { true } else { found }
|
||||
let i = i + 1
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// session_create — create a new session, return {id, title, created_at}.
|
||||
//
|
||||
// ISSUE #1: Ghost sessions on failed first message.
|
||||
// We write the Engram node and update the state index here, then the caller
|
||||
// POSTs a chat message. If that chat call fails (LLM unavailable, network
|
||||
// error, etc.) the session is stranded with no messages. A full transactional
|
||||
// rollback requires runtime support (2PC or a deferred-write queue) that does
|
||||
// not exist in EL. Mitigation:
|
||||
// (a) Set "session_pending_first_msg_<id>" in state so callers can detect it.
|
||||
// (b) Provide session_create_cleanup() for callers that detect a failure.
|
||||
// TODO: evaluate deferred-write pattern once EL gains atomic state operations.
|
||||
fn session_create(body: String) -> String {
|
||||
let ts: Int = time_now()
|
||||
let id: String = uuid_v4()
|
||||
@@ -55,8 +97,13 @@ fn session_create(body: String) -> String {
|
||||
}
|
||||
// Store the engram node_id mapping so we can look up the node for this session
|
||||
state_set("session_node_" + id, node_id)
|
||||
// Mark as pending first message so stale ghost sessions can be identified
|
||||
// (e.g. if the caller\'s subsequent chat POST fails).
|
||||
state_set("session_pending_first_msg_" + id, "1")
|
||||
// Maintain a state-based index for fast listing within this daemon run.
|
||||
// Newest sessions first (prepend).
|
||||
// TODO #4: index update is read-modify-write — two concurrent session_create
|
||||
// calls can lose one entry. EL has no CAS primitive; fix requires runtime support.
|
||||
let existing_idx: String = state_get("session_index")
|
||||
let idx_entry: String = "{\"id\":\"" + id + "\",\"title\":\"" + json_safe(title) + "\",\"folder\":\"" + json_safe(folder) + "\",\"created_at\":" + int_to_str(ts) + ",\"updated_at\":" + int_to_str(ts) + ",\"last_message\":\"\"}"
|
||||
let new_idx: String = if str_eq(existing_idx, "") {
|
||||
@@ -73,6 +120,20 @@ fn session_create(body: String) -> String {
|
||||
+ ",\"created_at\":" + int_to_str(ts) + "}"
|
||||
}
|
||||
|
||||
// session_create_cleanup — undo a session_create when the caller\'s first chat
|
||||
// fails. Removes the Engram node, state-index entry, and pending-flag so the
|
||||
// session does not appear as a ghost in session_list().
|
||||
// Addresses ISSUE #1: cleanup path for ghost sessions.
|
||||
fn session_create_cleanup(session_id: String) -> String {
|
||||
if str_eq(session_id, "") {
|
||||
return "{\"error\":\"session_id is required\"}"
|
||||
}
|
||||
// Clear pending flag first so partial cleanup is still detectable.
|
||||
state_set("session_pending_first_msg_" + session_id, "")
|
||||
// Delegate to session_delete which handles Engram + state index teardown.
|
||||
return session_delete(session_id)
|
||||
}
|
||||
|
||||
// session_list — list all sessions. Returns [{id, title, last_message, created_at, updated_at}].
|
||||
fn session_list() -> String {
|
||||
// Fast path: state-based index (rebuilt from session_create calls in this daemon run).
|
||||
@@ -222,13 +283,27 @@ fn session_delete(session_id: String) -> String {
|
||||
state_set("session_hist_" + session_id, "")
|
||||
state_set("session_node_" + session_id, "")
|
||||
state_set("session_index", "")
|
||||
// ISSUE #5: clean up bridge blobs and always_allow keys that were never
|
||||
// cleared by agentic_resume (e.g. client abandoned a pending tool call).
|
||||
// Without this, stranded bridge blobs accumulate indefinitely in state.
|
||||
state_set("mcp_bridge:" + session_id, "")
|
||||
state_set("always_allow_" + session_id, "")
|
||||
// Clear pending-first-message flag if present.
|
||||
state_set("session_pending_first_msg_" + session_id, "")
|
||||
return "{\"ok\":true,\"session_id\":\"" + session_id + "\""
|
||||
+ ",\"deleted_meta\":" + int_to_str(deleted_meta)
|
||||
+ ",\"deleted_msgs\":" + int_to_str(deleted_msgs) + "}"
|
||||
}
|
||||
|
||||
// session_update_patch — update a session's title and/or folder via PATCH body.
|
||||
// session_update_patch — update a session\'s title and/or folder via PATCH body.
|
||||
// Body may contain "title", "folder", or both. Preserves unmentioned fields.
|
||||
//
|
||||
// ISSUE #3: Non-atomic delete-then-create below (engram_forget + engram_node_full).
|
||||
// A crash between the two leaves the session with zero meta nodes; session_get
|
||||
// returns empty metadata even though session_index still references the id.
|
||||
// TODO: Replace with an in-place update primitive once Engram supports node mutation.
|
||||
// Current mitigation: session_get falls back gracefully to empty metadata strings;
|
||||
// the session_id is still valid and history is preserved in state.
|
||||
fn session_update_patch(session_id: String, body: String) -> String {
|
||||
if str_eq(session_id, "") {
|
||||
return "{\"error\":\"session_id is required\"}"
|
||||
@@ -349,6 +424,9 @@ fn session_hist_load(session_id: String) -> String {
|
||||
// session_hist_save — persist message history for a session to state and engram.
|
||||
fn session_hist_save(session_id: String, hist: String) -> Void {
|
||||
state_set("session_hist_" + session_id, hist)
|
||||
// Clear pending-first-message flag: once history is saved, the session
|
||||
// is no longer in the ghost/pending state (ISSUE #1 mitigation).
|
||||
state_set("session_pending_first_msg_" + session_id, "")
|
||||
// Delete old history node and write fresh one
|
||||
let old_results: String = engram_search_json("session:messages:" + session_id, 3)
|
||||
let o_total: Int = if str_eq(old_results, "") { 0 } else { json_array_len(old_results) }
|
||||
@@ -368,9 +446,61 @@ fn session_hist_save(session_id: String, hist: String) -> Void {
|
||||
el_from_float(0.6), el_from_float(0.6), el_from_float(0.9),
|
||||
"Episodic", tags
|
||||
)
|
||||
|
||||
// Session boundary emotional summary — written once per session the first time
|
||||
// a bell event has fired. The summary node is findable by future sessions via
|
||||
// broad affective queries ("session:emotional-summary" or "bell distress session").
|
||||
// It is NOT rewritten on every save — the state flag prevents duplicate nodes.
|
||||
let summary_written_key: String = "session_bell_summary_written:" + session_id
|
||||
let already_written: String = state_get(summary_written_key)
|
||||
if str_eq(already_written, "") {
|
||||
let bell_count_key: String = "session_bell_count:" + session_id
|
||||
let bell_count_raw: String = state_get(bell_count_key)
|
||||
let bell_count: Int = if str_eq(bell_count_raw, "") { 0 } else { str_to_int(bell_count_raw) }
|
||||
if bell_count > 0 {
|
||||
let bell_level_key: String = "session_bell_level:" + session_id
|
||||
let bell_signal_key: String = "session_bell_signal:" + session_id
|
||||
let dominant_level: String = state_get(bell_level_key)
|
||||
let last_signal: String = state_get(bell_signal_key)
|
||||
let eff_level: String = if str_eq(dominant_level, "") { "soft" } else { dominant_level }
|
||||
let eff_signal: String = if str_eq(last_signal, "") { "(no signal captured)" } else { last_signal }
|
||||
let ts_now: Int = time_now()
|
||||
let summary_content: String = "session:emotional-summary"
|
||||
+ " | session:" + session_id
|
||||
+ " | bell_count:" + int_to_str(bell_count)
|
||||
+ " | dominant_level:" + eff_level
|
||||
+ " | last_signal:" + eff_signal
|
||||
+ " | ts:" + int_to_str(ts_now)
|
||||
let summary_tags: String = "[\"session-emotional-summary\",\"affective\",\"bell:" + eff_level + "\",\"BellEvent\"]"
|
||||
let summary_sal: String = if str_eq(eff_level, "hard") { el_from_float(0.95) } else { el_from_float(0.85) }
|
||||
let sum_discard: String = engram_node_full(
|
||||
summary_content,
|
||||
"BellEvent",
|
||||
"session:emotional-summary",
|
||||
summary_sal,
|
||||
summary_sal,
|
||||
el_from_float(1.0),
|
||||
"Episodic",
|
||||
summary_tags
|
||||
)
|
||||
// Mark written so we do not create duplicate summary nodes as the
|
||||
// session continues accumulating more turns.
|
||||
state_set(summary_written_key, "1")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// session_update_meta_timestamp — update the updated_at field in the session:meta node.
|
||||
//
|
||||
// ISSUE #2: No TTL / idle expiry mechanism. Sessions accumulate indefinitely.
|
||||
// A sweep job (e.g. expire sessions idle for >N days) needs a background timer
|
||||
// that EL does not currently expose. Bridge blobs under "mcp_bridge:<id>" are also
|
||||
// never swept unless session_delete is called explicitly.
|
||||
// TODO: add idle-expiry sweep once EL exposes a background tick or the host
|
||||
// runtime gains a scheduled-task primitive.
|
||||
//
|
||||
// ISSUE #3 applies here too: delete-then-create is non-atomic. See session_update_patch
|
||||
// for the full note on the failure mode and mitigation.
|
||||
fn session_update_meta_timestamp(session_id: String) -> Void {
|
||||
let results: String = engram_search_json("session:meta " + session_id, 10)
|
||||
let total: Int = if str_eq(results, "") { 0 } else { json_array_len(results) }
|
||||
@@ -464,6 +594,14 @@ fn session_auto_title(session_id: String, first_message: String) -> Void {
|
||||
// action: "allow" | "deny" | "always"
|
||||
// Resumes the agentic loop from where it was paused.
|
||||
//
|
||||
// ISSUE #8: Reconnect/duplicate resume race. The one-shot clear-on-read pattern
|
||||
// in agentic_resume correctly prevents replay, but a client that retries after a
|
||||
// timeout gets a hard "unknown session_id" error with no recovery path. The
|
||||
// conversation is permanently stuck in that case. Full idempotency (e.g. caching
|
||||
// the last reply keyed by call_id) requires a new state structure.
|
||||
// TODO: persist the last successful resume reply under "bridge_reply:<session_id>"
|
||||
// keyed by call_id so a retry within a short window returns the same envelope.
|
||||
//
|
||||
// Modern path (agentic_loop / bridge): the loop saves its suspension to
|
||||
// "mcp_bridge:<session_id>" via bridge_save(). On approval we dispatch_tool()
|
||||
// if allowed (or build a denial string), then hand the result to agentic_resume()
|
||||
|
||||
@@ -5,13 +5,9 @@ import "stewardship.el"
|
||||
import "imprint.el"
|
||||
import "awareness.el"
|
||||
import "chat.el"
|
||||
import "safety.el"
|
||||
import "studio.el"
|
||||
import "elp-input.el"
|
||||
import "routes.el"
|
||||
import "safety.el"
|
||||
import "stewardship.el"
|
||||
import "imprint.el"
|
||||
|
||||
cgi "neuron-soul" {
|
||||
dharma_id: "ntn-genesis@http://localhost:7770",
|
||||
@@ -166,6 +162,48 @@ fn load_identity_context() -> Void {
|
||||
println("[soul] persona node loaded (" + int_to_str(str_len(p_content)) + " chars)")
|
||||
}
|
||||
}
|
||||
|
||||
// Cross-session affective context: query engram for recent distress/crisis signals.
|
||||
// Broadened query includes session:emotional-summary and BellEvent tags (issue #10):
|
||||
// the old keywords-only search missed these nodes when their content lacked exact phrases.
|
||||
// 7-day recency window applied via the "ts" field embedded in BellEvent content.
|
||||
let affective_raw: String = engram_search_json("distress crisis upset hopeless session:emotional-summary BellEvent bell:hard bell:soft", 5)
|
||||
let affective_ok: Bool = !str_eq(affective_raw, "") && !str_eq(affective_raw, "[]")
|
||||
if affective_ok {
|
||||
let ts_now: Int = time_now()
|
||||
let ts_cutoff: Int = ts_now - 604800
|
||||
let aff_total: Int = json_array_len(affective_raw)
|
||||
let aff_ctx: String = ""
|
||||
let ai: Int = 0
|
||||
while ai < aff_total {
|
||||
let aff_node: String = json_array_get(affective_raw, ai)
|
||||
let aff_content: String = json_get(aff_node, "content")
|
||||
// Try multiple timestamp fields: "ts" (embedded), "created_at", "updated_at"
|
||||
let aff_ts_str: String = json_get(aff_node, "ts")
|
||||
let aff_ts_str2: String = if str_eq(aff_ts_str, "") { json_get(aff_node, "created_at") } else { aff_ts_str }
|
||||
// Also try embedded " | ts:NNN" format used in BellEvent content
|
||||
let ts_marker: String = " | ts:"
|
||||
let ts_pos: Int = str_index_of(aff_content, ts_marker)
|
||||
let aff_ts_embedded: String = if ts_pos >= 0 {
|
||||
let ts_start: Int = ts_pos + str_len(ts_marker)
|
||||
let rest: String = str_slice(aff_content, ts_start, str_len(aff_content))
|
||||
let next_sep: Int = str_index_of(rest, " | ")
|
||||
if next_sep < 0 { rest } else { str_slice(rest, 0, next_sep) }
|
||||
} else { "" }
|
||||
let eff_ts_str: String = if !str_eq(aff_ts_embedded, "") { aff_ts_embedded } else { aff_ts_str2 }
|
||||
let aff_ts: Int = if str_eq(eff_ts_str, "") { ts_now } else { str_to_int(eff_ts_str) }
|
||||
let is_recent: Bool = aff_ts >= ts_cutoff
|
||||
let snip: String = if str_len(aff_content) > 200 { str_slice(aff_content, 0, 200) } else { aff_content }
|
||||
let aff_ctx = if is_recent && !str_eq(snip, "") {
|
||||
if str_eq(aff_ctx, "") { snip } else { aff_ctx + "\n" + snip }
|
||||
} else { aff_ctx }
|
||||
let ai = ai + 1
|
||||
}
|
||||
if !str_eq(aff_ctx, "") {
|
||||
state_set("soul_affective_context", aff_ctx)
|
||||
println("[soul] cross-session affective context loaded (" + int_to_str(str_len(aff_ctx)) + " chars)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// seed_persona_from_env — one-time migration: SOUL_IDENTITY env var → Persona graph node.
|
||||
@@ -237,12 +275,59 @@ fn emit_session_start_event() -> Void {
|
||||
}
|
||||
let ts: Int = time_now()
|
||||
|
||||
// Load previous session summary at boot — stash in state for session_preload.
|
||||
// Search by label text + type, filter by exact label match to avoid false positives.
|
||||
// engram_get_node_by_label is not a runtime builtin; engram_search_json is used instead.
|
||||
let sum_boot_search: String = engram_search_json("session:summary SessionSummary", 5)
|
||||
let sum_boot_ok: Bool = !str_eq(sum_boot_search, "") && !str_eq(sum_boot_search, "[]")
|
||||
let prev_sum_content: String = if sum_boot_ok {
|
||||
let sbs_total: Int = json_array_len(sum_boot_search)
|
||||
let sbs_i: Int = 0
|
||||
let sbs_found: String = ""
|
||||
while sbs_i < sbs_total {
|
||||
let sbs_node: String = json_array_get(sum_boot_search, sbs_i)
|
||||
let sbs_label: String = json_get(sbs_node, "label")
|
||||
let sbs_type: String = json_get(sbs_node, "node_type")
|
||||
let sbs_content: String = json_get(sbs_node, "content")
|
||||
let sbs_found = if str_eq(sbs_label, "session:summary") && str_eq(sbs_type, "SessionSummary") && !str_eq(sbs_content, "") {
|
||||
if str_eq(sbs_found, "") { sbs_content } else { sbs_found }
|
||||
} else { sbs_found }
|
||||
let sbs_i = sbs_i + 1
|
||||
}
|
||||
if str_eq(sbs_found, "") {
|
||||
let sum_fb: String = engram_search_json("SessionSummary previous-session", 2)
|
||||
let sum_fb_ok: Bool = !str_eq(sum_fb, "") && !str_eq(sum_fb, "[]")
|
||||
if sum_fb_ok {
|
||||
let sfn: String = json_array_get(sum_fb, 0)
|
||||
let sftype: String = json_get(sfn, "node_type")
|
||||
let sfcontent: String = json_get(sfn, "content")
|
||||
if str_eq(sftype, "SessionSummary") && !str_eq(sfcontent, "") { sfcontent } else { "" }
|
||||
} else { "" }
|
||||
} else { sbs_found }
|
||||
} else {
|
||||
let sum_fb2: String = engram_search_json("SessionSummary previous-session", 2)
|
||||
let sum_fb2_ok: Bool = !str_eq(sum_fb2, "") && !str_eq(sum_fb2, "[]")
|
||||
if sum_fb2_ok {
|
||||
let sfn2: String = json_array_get(sum_fb2, 0)
|
||||
let sftype2: String = json_get(sfn2, "node_type")
|
||||
let sfcontent2: String = json_get(sfn2, "content")
|
||||
if str_eq(sftype2, "SessionSummary") && !str_eq(sfcontent2, "") { sfcontent2 } else { "" }
|
||||
} else { "" }
|
||||
}
|
||||
let has_prev_sum: String = if str_eq(prev_sum_content, "") { "false" } else { "true" }
|
||||
if !str_eq(prev_sum_content, "") {
|
||||
state_set("soul_prev_session_summary", prev_sum_content)
|
||||
println("[soul] previous session summary loaded (" + int_to_str(str_len(prev_sum_content)) + " chars)")
|
||||
}
|
||||
|
||||
|
||||
let payload: String = "{\"event\":\"session_start\""
|
||||
+ ",\"boot\":" + boot_num
|
||||
+ ",\"cgi\":\"" + eff_cgi + "\""
|
||||
+ ",\"node_count\":" + int_to_str(node_ct)
|
||||
+ ",\"edge_count\":" + int_to_str(edge_ct)
|
||||
+ ",\"identity_loaded\":" + has_identity
|
||||
+ ",\"prev_session_summary_loaded\":" + has_prev_sum
|
||||
+ ",\"ts\":" + int_to_str(ts) + "}"
|
||||
|
||||
let tags: String = "[\"internal-state\",\"session-start\",\"InternalStateEvent\"]"
|
||||
@@ -251,33 +336,45 @@ fn emit_session_start_event() -> Void {
|
||||
el_from_float(0.9), el_from_float(0.9), el_from_float(1.0),
|
||||
"Episodic", tags
|
||||
)
|
||||
println("[soul] session-start event logged (boot=" + boot_num + " nodes=" + int_to_str(node_ct) + " edges=" + int_to_str(edge_ct) + ")")
|
||||
println("[soul] session-start event logged (boot=" + boot_num + " nodes=" + int_to_str(node_ct) + " edges=" + int_to_str(edge_ct) + " prev_summary=" + has_prev_sum + ")")
|
||||
}
|
||||
|
||||
// layered_cycle — routes user-facing requests through the 4-layer consciousness stack.
|
||||
// L0 (core) → L1 (safety screen) → L2a (continuity + behavioral profiling) → L2b (mission alignment) → L3 (imprint) → L1 (safety validate)
|
||||
// Internal cognition (heartbeat, proactive, memory ops) bypasses layers — use one_cycle directly.
|
||||
fn layered_cycle(raw_input: String) -> String {
|
||||
let history: String = state_get("conversation_history")
|
||||
let history: String = state_get("conv_history")
|
||||
let session_id: String = state_get("current_session_id")
|
||||
|
||||
// L1 in: safety screen
|
||||
let screen_result: String = safety_screen(raw_input, history)
|
||||
let screen_action: String = json_get(screen_result, "action")
|
||||
|
||||
// ISSUE 4: safe-mode guard. If safety_screen returned an invalid/empty action
|
||||
// (engram failure or internal error), refuse rather than pass unscreened input.
|
||||
let valid_action: Bool = str_eq(screen_action, "hard_bell")
|
||||
|| str_eq(screen_action, "soft_bell")
|
||||
|| str_eq(screen_action, "pass")
|
||||
if !valid_action {
|
||||
println("[soul] layered_cycle: safety_screen invalid action -- safe mode refusal")
|
||||
return safety_validate("", "hard_bell")
|
||||
}
|
||||
|
||||
// Hard bell: bypass all upper layers, log and escalate.
|
||||
// Intentionally does NOT update conversation_history or call auto_persist():
|
||||
// hard bell events are security-sensitive and must not appear in engram conversation
|
||||
// history where they could leak context to subsequent turns. They are persisted
|
||||
// separately by safety_log_bell() into the Episodic tier with restricted labels.
|
||||
//
|
||||
// ISSUE 6: safety_log_bell already called inside safety_screen (line 140).
|
||||
// Do NOT call it again here -- that would double-log every hard bell.
|
||||
//
|
||||
// safety_validate second param: when screen_action is "hard_bell", safety_validate
|
||||
// receives the sentinel string "hard_bell" (not a normal screen action). The safety
|
||||
// layer contract requires it to return a fixed refusal regardless of the output arg.
|
||||
// On the normal path, safety_validate receives the original screen_action ("pass")
|
||||
// so it can apply action-specific post-output checks.
|
||||
if str_eq(screen_action, "hard_bell") {
|
||||
safety_log_bell("hard", json_get(screen_result, "reason"), str_slice(raw_input, 0, 80))
|
||||
return safety_validate("", "hard_bell")
|
||||
}
|
||||
|
||||
@@ -312,6 +409,16 @@ fn layered_cycle(raw_input: String) -> String {
|
||||
json_get(steward_result, "redirect_to")
|
||||
}
|
||||
|
||||
// ISSUE 1: pre-LLM bell augmentation for layered_cycle path.
|
||||
// safety_augment_system appends soft/hard directive to system prompt when bell fires,
|
||||
// ensuring LLM processes message WITH the safety directive -- not just post-output gate.
|
||||
// Stored in state as "layered_cycle_safety_system_addendum" for imprint_respond to use.
|
||||
// TODO: wire directly when imprint_respond gains system_override param (imprint.el change).
|
||||
// ISSUE 3 TODO: no semantic crisis detection. Keyword-only means signals that evade
|
||||
// the phrase list pass with zero augmentation. Semantic layer = separate decision.
|
||||
let augmented_addendum: String = safety_augment_system("", raw_input)
|
||||
state_set("layered_cycle_safety_system_addendum", augmented_addendum)
|
||||
|
||||
// L3: imprint responds
|
||||
let output: String = imprint_respond(aligned, imprint_id)
|
||||
|
||||
@@ -369,6 +476,7 @@ load_identity_context()
|
||||
seed_persona_from_env()
|
||||
let boot_num: Int = mem_boot_count_inc()
|
||||
state_set("soul_boot_count", int_to_str(boot_num))
|
||||
state_set("soul_boot_ts", int_to_str(time_now()))
|
||||
println("[soul] boot #" + int_to_str(boot_num))
|
||||
emit_session_start_event()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user