feat: decision-log data layer for Decide mode (learning layer)
Storage + tools so Decide mode can learn instead of one-shot tie-breaking: log the call Brian makes, resolve it later with the outcome, recall similar past calls to ground new recommendations in his own track record. - memory: decisions table + Decision dataclass + log/resolve/get/list/recall_decisions (embedding over situation+choice; embed failure never blocks a log) - tools: log_decision / resolve_decision / recall_decisions handlers + specs - tests: 9 covering roundtrip, resolve, open-only filter, similarity rank, tool layer Data layer only — NOT wired into any mode's allow-list or the Decide card yet (the prompt/taste part is left for Brian; see docs/DECISION_LOG.md). No behavior changes until the tools are added to _DECIDE_TOOLS. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+121
@@ -115,6 +115,26 @@ CREATE TABLE IF NOT EXISTS ratings (
|
||||
note TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_ratings_created ON ratings(created_at);
|
||||
|
||||
-- Decisions Lyra helped Brian make (Decide mode's learning layer). Logged when the
|
||||
-- call is made; resolved later with how it actually turned out; recalled by semantic
|
||||
-- similarity so a new call can lean on how similar ones went. embedding covers the
|
||||
-- situation + choice. Resolved rows (with an outcome) are the signal worth recalling.
|
||||
CREATE TABLE IF NOT EXISTS decisions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TEXT NOT NULL,
|
||||
situation TEXT NOT NULL, -- what was being decided
|
||||
options TEXT, -- the alternatives weighed (free text / newline list)
|
||||
choice TEXT NOT NULL, -- the call that was made
|
||||
rationale TEXT, -- why
|
||||
confidence INTEGER, -- 1-5, how sure at the time (nullable)
|
||||
tags TEXT, -- domain: poker | life | build | ... (comma-separated)
|
||||
embedding BLOB,
|
||||
outcome TEXT, -- filled in on resolve: what actually happened
|
||||
outcome_rating INTEGER, -- -1 bad / 0 mixed / +1 good (nullable until resolved)
|
||||
resolved_at TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_decisions_created ON decisions(created_at);
|
||||
"""
|
||||
|
||||
_conn: sqlite3.Connection | None = None
|
||||
@@ -184,6 +204,26 @@ class Era:
|
||||
score: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Decision:
|
||||
id: int
|
||||
created_at: str
|
||||
situation: str
|
||||
choice: str
|
||||
options: str | None = None
|
||||
rationale: str | None = None
|
||||
confidence: int | None = None
|
||||
tags: str | None = None
|
||||
outcome: str | None = None
|
||||
outcome_rating: int | None = None
|
||||
resolved_at: str | None = None
|
||||
score: float | None = None
|
||||
|
||||
@property
|
||||
def resolved(self) -> bool:
|
||||
return self.resolved_at is not None
|
||||
|
||||
|
||||
def _to_blob(vec: list[float]) -> bytes:
|
||||
return np.asarray(vec, dtype=np.float32).tobytes()
|
||||
|
||||
@@ -645,6 +685,87 @@ def backfill_journal_embeddings(limit: int | None = None) -> int:
|
||||
return n
|
||||
|
||||
|
||||
# --- decisions (Decide mode's learning layer) ---------------------------------
|
||||
|
||||
def _row_to_decision(r: sqlite3.Row) -> Decision:
|
||||
return Decision(
|
||||
id=r["id"], created_at=r["created_at"], situation=r["situation"],
|
||||
choice=r["choice"], options=r["options"], rationale=r["rationale"],
|
||||
confidence=r["confidence"], tags=r["tags"], outcome=r["outcome"],
|
||||
outcome_rating=r["outcome_rating"], resolved_at=r["resolved_at"],
|
||||
)
|
||||
|
||||
|
||||
def log_decision(situation: str, choice: str, options: str | None = None,
|
||||
rationale: str | None = None, confidence: int | None = None,
|
||||
tags: str | None = None) -> int:
|
||||
"""Record a decision Brian made. Embeds situation+choice so similar future calls
|
||||
can recall it. Returns the new row id. Resolve it later with resolve_decision."""
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
[emb] = llm.embed([f"{situation}\nChose: {choice}"])
|
||||
blob = _to_blob(emb)
|
||||
except Exception:
|
||||
blob = None # never block logging a decision on the embedder being down
|
||||
conn = _connection()
|
||||
with conn:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO decisions (created_at, situation, options, choice, rationale, "
|
||||
"confidence, tags, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(now, situation, options, choice, rationale, confidence, tags, blob),
|
||||
)
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def resolve_decision(decision_id: int, outcome: str, outcome_rating: int | None = None) -> bool:
|
||||
"""Record how a past decision turned out. Returns False if the id is unknown."""
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
conn = _connection()
|
||||
with conn:
|
||||
cur = conn.execute(
|
||||
"UPDATE decisions SET outcome = ?, outcome_rating = ?, resolved_at = ? WHERE id = ?",
|
||||
(outcome, outcome_rating, now, decision_id),
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def get_decision(decision_id: int) -> Decision | None:
|
||||
r = _connection().execute("SELECT * FROM decisions WHERE id = ?", (decision_id,)).fetchone()
|
||||
return _row_to_decision(r) if r else None
|
||||
|
||||
|
||||
def list_decisions(limit: int = 20, open_only: bool = False) -> list[Decision]:
|
||||
"""Recent decisions, newest first. open_only -> only those not yet resolved."""
|
||||
sql = "SELECT * FROM decisions"
|
||||
if open_only:
|
||||
sql += " WHERE resolved_at IS NULL"
|
||||
sql += " ORDER BY created_at DESC LIMIT ?"
|
||||
rows = _connection().execute(sql, (limit,)).fetchall()
|
||||
return [_row_to_decision(r) for r in rows]
|
||||
|
||||
|
||||
def recall_decisions(query: str, k: int = 5) -> list[Decision]:
|
||||
"""Top-k past decisions semantically similar to `query`, each with a `score` — so a
|
||||
new call can lean on how similar ones went. Resolved rows carry the real signal."""
|
||||
[q_vec] = llm.embed([query])
|
||||
q = np.asarray(q_vec, dtype=np.float32)
|
||||
rows = _connection().execute(
|
||||
"SELECT * FROM decisions WHERE embedding IS NOT NULL"
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return []
|
||||
matrix = np.stack([_from_blob(r["embedding"]) for r in rows])
|
||||
norms = np.linalg.norm(matrix, axis=1)
|
||||
scores = (matrix @ q) / (norms * np.linalg.norm(q) + 1e-9)
|
||||
top_idx = np.argsort(scores)[::-1][:k]
|
||||
out = []
|
||||
for i in top_idx:
|
||||
d = _row_to_decision(rows[i])
|
||||
d.score = float(scores[i])
|
||||
out.append(d)
|
||||
return out
|
||||
|
||||
|
||||
def get_setting(key: str, default: str | None = None) -> str | None:
|
||||
"""A runtime setting value (UI-tunable), or `default` if unset."""
|
||||
r = _connection().execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
|
||||
|
||||
Reference in New Issue
Block a user