Files
NexusOS/synapse/playbook_manager.py
T
Athena 26b471d259 Merge origin/main (v1.2.0: Projects, modules, in-app updates)
Reconciles 17 commits of this session's work (self-alteration tools,
vendored Curry, slash-command dispatch, Windows toolchain/gate fixes)
against origin/main's v1.2.0 sync (Projects/RAG scoping, a new modules/
system for mail and network, in-app updates, the standalone memory
microservice folded into an in-process curator, KDE desktop theme
overhaul). Nine real conflicts, each resolved by hand after reading both
sides' actual diffs rather than picking one side wholesale:

- synapse/tools.py, tests/test_tools.py: origin/main's diff here was
  small and clean (read_file/list_files, two new tests) despite git's
  diff3 flagging the whole file as one conflict blob -- reset to this
  branch's version and hand-spliced their addition in at the same
  points they used, rather than trying to reconcile a false 800-line
  conflict. Found and fixed a real bug while verifying: _list_files
  returned backslash-separated paths on Windows, which don't match the
  forward-slash glob patterns the tool's own schema documents.
- synapse/main.py: kept this branch's cue-based standing advertisement
  of render_preview/run_snippet (independent of any playbook granting
  them) AND adopted origin/main's fix for routed reference playbooks
  not bringing their own tools along -- dropping either would have been
  a real regression, not just a style difference. Also: the standalone
  memory service (port 8001) is gone upstream, so its dead CORS/kill-
  target entries were removed; NEXUS_BACKEND_PORT parameterization and
  the manage_ollama-conditional kill logic (this branch's remote-Ollama
  support) were kept over origin/main's hardcoded equivalents.
- synapse/memory/store.py: kept this branch's _delete_message_vectors
  helper (already reused elsewhere, batches to stay under SQLite's
  variable limit) over origin/main's inline duplicate of the same fix.
- synapse/nexus_config.py, nexusos_cli/ncp.py: dropped the now-dead
  memory-service port/service entries; kept NEXUS_BACKEND_PORT env
  override and the manage_ollama-conditional kill-target list.
- CLAUDE.md, README.md: merged both sides' additions, no real conflict.

Found and fixed three more issues while independently verifying the
merged tree, none of them mine or origin/main's alone -- only visible
once both sides actually ran together:

- modules/ (the new mail+network package) was never added to
  pyproject.toml's wheel `packages` list OR the sdist's `include`
  allowlist, so `from modules.registry import ROUTERS` in main.py would
  ImportError on any wheel install. Fixed both; bin/check.sh's
  packaging gate now asserts modules/ actually ships. tests/
  test_packaging_deps.py's FIRST_PARTY/SHIPPED_PACKAGES sets were
  updated to recognize the new package.
- tests/test_mail_creds.py's 0600-mode assertions are POSIX-only --
  NTFS has no equivalent permission bits, so os.open(path, 0o600) on
  Windows just creates a normal file and stat.S_IMODE reports 0o666
  regardless. Made the assertions platform-aware rather than skip real
  coverage (the temp-file-cleanup and password round-trip checks in the
  same test still run on Windows) or paper over a genuine OS
  limitation with a fake pass.
- tests/test_kde_theme.py used bare Path.read_text() in fifteen places;
  Windows' default locale encoding (cp1252, not UTF-8) can't decode a
  real UTF-8 byte in the QML it reads, and did fail on one of the
  fifteen. Fixed all fifteen, not just the one that happened to trip
  today, since the other fourteen were equally fragile.

Verified: full bin/check.sh reports OK end-to-end on this Windows
checkout -- pytest (tests + management): 295 passed, 0 failed, 9
skipped; eslint clean; frontend node:test 57/57; PowerShell/shell
parse clean; wheel + sdist pass twine check and now correctly carry
modules/ (60 files, up from 52 pre-merge). synapse.main:app builds
with 74 routes (up from 54 pre-merge, matching the new Projects/mail/
network endpoints).
2026-08-26 02:09:23 -05:00

83 lines
3.4 KiB
Python

from typing import List
from uuid import uuid4
from .playbooks.store import playbook_store, PlaybookItem
# Fields a caller can supply; anything else in a persist dict is ignored.
# `order` is deliberately excluded — see persist_playbook.
_EDITABLE_FIELDS = ("title", "goal", "instructions", "tags", "tools", "model")
_FIELD_DEFAULTS = {"title": "", "goal": "", "instructions": "", "tags": [], "tools": [], "model": ""}
def persist_playbook(data: dict, *, merge: bool) -> dict:
"""Write a playbook dict to the store, returning it as a plain dict.
`merge=False` is today's behavior (main.py's HTTP form handlers): a full
replace, with pydantic defaults for anything omitted. `merge=True` (used by
the edit_playbook tool) instead keeps each field's *existing* value when the
caller's dict doesn't supply it — a model calling with a partial argument
set must not silently blank out the fields it didn't mention.
`order` is never taken from `data` in merge mode: it is preserved from the
existing playbook on update, or appended at the tail on create. Position 0
is unconditionally the active system prompt (see get_main_playbook) — moving
a playbook there is `make_main`'s job, never an accidental side effect of an
ordinary field edit.
"""
existing_id = str(data.get("id") or "")
existing = playbook_store.get_playbook(existing_id) if existing_id else None
if merge:
fields = {}
for key in _EDITABLE_FIELDS:
if key in data and data[key] is not None:
fields[key] = data[key]
elif existing is not None:
fields[key] = getattr(existing, key)
else:
fields[key] = _FIELD_DEFAULTS[key]
if existing is None and not (fields["title"] and fields["goal"] and fields["instructions"]):
raise ValueError("title, goal, and instructions are required to create a new playbook")
else:
fields = {key: data.get(key, _FIELD_DEFAULTS[key]) for key in _EDITABLE_FIELDS}
order = existing.order if existing else data.get("order", len(playbook_store.all_playbooks()))
item = PlaybookItem(id=existing_id or str(uuid4()), order=order, **fields)
playbook_store.add_playbook(item)
return item.model_dump()
def make_main(playbook_id: str) -> None:
"""Reorder so `playbook_id` is position 0 (the active system prompt)."""
all_ids = [p.id for p in playbook_store.all_playbooks()]
if playbook_id not in all_ids:
raise ValueError(f"no playbook with id {playbook_id!r}")
ordered = [playbook_id] + [pid for pid in all_ids if pid != playbook_id]
playbook_store.reorder_playbooks(ordered)
def _all() -> List[PlaybookItem]:
"""Return all playbooks sorted by order (position 0 is always main)."""
return playbook_store.all_playbooks()
def get_main_playbook() -> PlaybookItem | None:
playbooks = _all()
return playbooks[0] if playbooks else None
def get_context_playbooks() -> List[PlaybookItem]:
"""All playbooks after the first — injected as reference context."""
playbooks = _all()
return playbooks[1:] if len(playbooks) > 1 else []
def get_system_prompt() -> str:
playbook = get_main_playbook()
if not playbook:
return ""
goal = (getattr(playbook, "goal", "") or "").strip()
instructions = (getattr(playbook, "instructions", "") or "").strip()
if goal and instructions:
return f"{goal}\n\n{instructions}"
return goal or instructions