Skip to content

memory_gate

memory_gate

The memory dispatch gate: per-dispatch memory sessions for the baton adapter.

All memory logic the conductor needs at dispatch lives here, so the adapter only makes three small, guarded calls (register/deregister a job, prepare before a backend is acquired, teardown when the dispatch ends).

  • A job without a memory: key never reaches this module: prepare returns None at once and nothing heavy (gateway, endpoint, backend, audit log) exists until the first dispatch that needs one. Those are created lazily.
  • prepare is all-or-nothing: if any attachment fails to open, every session and socket opened for that dispatch so far is closed and a typed :class:MemoryGateError naming the attachment is raised.
  • The harness gets one MCP config file per dispatch, in its own directory <workspace>/.marianne-memory/<hash>/mcp.json (0700/0600), holding the technique servers plus one shim entry per attachment. The file names a socket and nothing else: no principal, scope, grant or session id.
  • teardown never raises into the caller; it reports what it could not stop.
  • Session lifetime is the owner's liveness, read at call time. One threading.Event (the dispatch's "ended" flag) is shared by every session of a dispatch and checked first on every call. It is set, instantly and from the loop, by teardown (before any I/O is queued), deregister_job, shutdown and a done-callback on the owner task. No clock, lease or renewal is involved: a finished or cancelled sheet's sessions refuse the very next call however busy the worker is. A reaper task exists for hygiene only (it enqueues the teardown that a flagged dispatch missed, and ends ownerless dispatches after a grace on the monotonic clock); if it dies, flagged sessions are still refused and only socket and directory cleanup waits for deregister or shutdown.
  • All gate I/O (session open/close with its audit fsync, config write/delete, sweeps) runs on ONE ordered daemon worker thread. One slow job therefore delays opens and cleanups for every dispatch (head-of-line blocking), but it can no longer end a live session: a job that runs longer than SLOW_JOB_SECONDS is logged (memory_gate.slow_job, with its kind).
  • Still on the event loop: endpoint bind/unbind (socket creation, start_unix_server), backend construction and close, the run-directory mkdir in _ensure, the sweep of stale sockets' bookkeeping, the cam endpoint table (set_cam_endpoints rebinds it whole), and all gate dictionaries. None blocks on a lock or an fsync.
  • A failed memory open fails the dispatch; it does not degrade to "no memory". That is intended: the sheet's prompt names tools that must exist. A misconfigured attachment (MemoryConfigError) is stronger still: it fails the sheet at once (MEMORY_CONFIG_ERROR, E301) — it is not retried and does not move along the fallback chain, because no instrument can deliver it.
  • Same-UID limit (stated once): the socket path is passed in the shim's environment rather than argv, which hides it from other users but not from other processes of the same user (/proc/<pid>/environ is readable too), and every job of one conductor shares one principal; so a sheet with a shell can reach another job's session if it finds the path.

Classes

MemoryGateError

MemoryGateError(attachment, reason)

Bases: Exception

A memory attachment could not be delivered. Names the attachment and the reason.

Source code in src/marianne/daemon/baton/memory_gate.py
def __init__(self, attachment: str, reason: str) -> None:
    self.attachment = attachment
    self.reason = reason
    super().__init__(f"memory attachment {attachment!r}: {reason}")

MemoryConfigCollision

MemoryConfigCollision(attachment, reason)

Bases: MemoryGateError

A memory server name is already present in the technique MCP config.

Source code in src/marianne/daemon/baton/memory_gate.py
def __init__(self, attachment: str, reason: str) -> None:
    self.attachment = attachment
    self.reason = reason
    super().__init__(f"memory attachment {attachment!r}: {reason}")

MemoryConfigError

MemoryConfigError(attachment, reason, *, config_key=None)

Bases: MemoryGateError

A memory attachment is misconfigured: no retry and no other instrument can change it.

config_key is the memory_backends.cam.<name> key the refusal points at: the missing endpoint for an unknown endpoint, the attachment's own endpoint for an operator-only setting. It is None when no one key is at fault (an unknown setting, an endpoint that is not a name). The adapter adds the key to the dispatch failure's message when the reason does not already name it.

Source code in src/marianne/daemon/baton/memory_gate.py
def __init__(self, attachment: str, reason: str, *, config_key: str | None = None) -> None:
    self.config_key = config_key
    super().__init__(attachment, reason)

SheetIdentity dataclass

SheetIdentity(num, movement, phase='')

The sheet a dispatch is for: number, movement number and (optional) phase name.

OpenedSession dataclass

OpenedSession(attachment, session_id, socket_path)

One attachment's live session. Conductor-side only; never rendered to a musician.

TeardownReport dataclass

TeardownReport(in_flight=0, errors=())

What teardown left behind: calls still running, and steps that failed.

PreparedMemory dataclass

PreparedMemory(dispatch_id, manifest, mcp_config_path)

What the adapter needs from one dispatch: the text to append and the config to attach.

MemoryDispatchGate

MemoryDispatchGate(*, run_dir, memory_root, audit_dir, user, cam_endpoints=None, clock=time, monotonic=monotonic, shutdown_bound_seconds=SHUTDOWN_BOUND_SECONDS, start_reaper=True, ownerless_grace_seconds=OWNERLESS_GRACE_SECONDS, slow_job_seconds=SLOW_JOB_SECONDS, reap_interval_seconds=REAP_INTERVAL_SECONDS)

Opens and closes the memory sessions of each dispatch, per (job, dispatch).

Concurrency model (see also MEMORY-DISPATCH-GATE-NOTES.md):

  • The loop owns all bookkeeping (_open, _jobs, registered backends) and the cam endpoint table: :meth:set_cam_endpoints rebinds it whole, and the loop is its lock.
  • Every blocking action goes through ONE single-thread worker, in submission order: open a session, close a session, write a config, delete a config, sweep. Because there is one worker, two actions on the same thing can never overlap.
  • A worker job is never cancelled with its awaiter. Its result is applied on the loop by a completion step that runs whether or not anybody still awaits it, and that step decides ownership: every successful open is either recorded in an open dispatch or has a close enqueued (the one-open-one-owner invariant); a config written for a dispatch that is gone is deleted.
Source code in src/marianne/daemon/baton/memory_gate.py
def __init__(
    self, *, run_dir: Path | str, memory_root: Path | str, audit_dir: Path | str,
    user: str, cam_endpoints: Mapping[str, Mapping[str, Any]] | None = None,
    clock: Callable[[], float] = time.time,
    monotonic: Callable[[], float] = time.monotonic,
    shutdown_bound_seconds: float = SHUTDOWN_BOUND_SECONDS, start_reaper: bool = True,
    ownerless_grace_seconds: float = OWNERLESS_GRACE_SECONDS,
    slow_job_seconds: float = SLOW_JOB_SECONDS,
    reap_interval_seconds: float = REAP_INTERVAL_SECONDS,
) -> None:
    self._start_reaper = start_reaper
    self._monotonic = monotonic
    self._ownerless_grace = ownerless_grace_seconds
    self._slow_job_seconds = slow_job_seconds
    self._reap_interval = reap_interval_seconds
    self._reaper: asyncio.Task[None] | None = None
    self._run_dir = Path(run_dir)
    self._memory_root = Path(memory_root)
    self._audit_dir = Path(audit_dir)
    self._user = user
    self._cam_endpoints: dict[str, dict[str, Any]] = {
        name: dict(cfg) for name, cfg in (cam_endpoints or {}).items()
    }
    self._clock = clock
    self._shutdown_bound = shutdown_bound_seconds
    # Heavy members: created on the first dispatch that needs memory.
    self._gateway: Gateway | None = None
    self._endpoint: MemoryEndpoint | None = None
    self._audit: AuditLog | None = None
    self._worker: _Worker | None = None
    self._backend_refs: dict[str, int] = {}  # backend key -> references held
    self._session_backend: dict[str, _BackendRef] = {}  # session id -> its backend reference
    self._jobs: dict[str, _Registration] = {}
    self._open: dict[tuple[str, str], _Open] = {}
    self._workspaces: dict[str, set[Path]] = {}  # job -> workspaces given dispatch dirs
    self._pending: set[asyncio.Future[Any]] = set()  # worker jobs not yet completed
    self._background: set[asyncio.Task[Any]] = set()
    self._closed = False
    self._closing = False
Methods:
set_cam_endpoints
set_cam_endpoints(cam_endpoints)

Replace the cam endpoint table (#573); the next dispatch resolves against it.

The table is replaced whole, on the loop. No lock is taken: the loop is the lock, because the only reader (_cam_settings) runs on the loop with no await between reading the table and building the backend. A session that is already open keeps the backend it was opened with; an endpoint whose settings changed gets a new backend, because the resolved settings are part of the backend key. DaemonConfig validates the section before it reaches the gate, so nothing is checked here.

Source code in src/marianne/daemon/baton/memory_gate.py
def set_cam_endpoints(self, cam_endpoints: Mapping[str, Mapping[str, Any]] | None) -> None:
    """Replace the cam endpoint table (#573); the next dispatch resolves against it.

    The table is replaced whole, on the loop. No lock is taken: the loop is the lock,
    because the only reader (``_cam_settings``) runs on the loop with no ``await`` between
    reading the table and building the backend. A session that is already open keeps the
    backend it was opened with; an endpoint whose settings changed gets a new backend,
    because the resolved settings are part of the backend key. ``DaemonConfig`` validates
    the section before it reaches the gate, so nothing is checked here.
    """
    self._cam_endpoints = {name: dict(cfg) for name, cfg in (cam_endpoints or {}).items()}
deregister_job
deregister_job(job_id)

Forget the job, tear down its open dispatches, then remove its dispatch dirs.

Source code in src/marianne/daemon/baton/memory_gate.py
def deregister_job(self, job_id: str) -> None:
    """Forget the job, tear down its open dispatches, then remove its dispatch dirs."""
    self._jobs.pop(job_id, None)
    stale = [key for key, entry in self._open.items() if entry.job_id == job_id]
    for key in stale:
        self._end(self._open[key])
        self._open[key].cleanup_queued = True
    workspaces = self._workspaces.pop(job_id, set())
    if not stale and not workspaces:
        return
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        _logger.warning(
            "memory_gate.deregister_without_loop",
            extra={"job_id": job_id, "dispatches": len(stale)},
        )
        return

    async def go() -> None:
        for key_job, key_dispatch in stale:
            await self.teardown(key_job, key_dispatch)
        for ws in workspaces:
            with contextlib.suppress(Exception):
                if self._closed:
                    _remove_dispatch_dirs(ws, self._live_dirs)
                else:
                    await self._run(_remove_dispatch_dirs, ws, self._live_dirs)

    task = loop.create_task(go())
    self._background.add(task)
    task.add_done_callback(self._background.discard)
drain async
drain()

Wait for the gate's own background work and queued worker jobs (not callers' tasks).

Source code in src/marianne/daemon/baton/memory_gate.py
async def drain(self) -> None:
    """Wait for the gate's own background work and queued worker jobs (not callers' tasks)."""
    while True:
        pending: list[Any] = [*self._background, *self._pending]
        if not pending:
            return
        await asyncio.gather(*pending, return_exceptions=True)
merge_config
merge_config(job_id, dispatch_id, delivery, existing_path, workspace)

Queue this dispatch's merged MCP config under its own directory.

Returns a future. Its completion step runs on the loop whether or not anybody is still awaiting: if the dispatch is gone by then, the file is queued for deletion.

Source code in src/marianne/daemon/baton/memory_gate.py
def merge_config(
    self, job_id: str, dispatch_id: str, delivery: MemoryDelivery,
    existing_path: Path | str | None, workspace: Path | str,
) -> asyncio.Future[Path]:
    """Queue this dispatch's merged MCP config under its own directory.

    Returns a future. Its completion step runs on the loop whether or not anybody is
    still awaiting: if the dispatch is gone by then, the file is queued for deletion.
    """
    ddir = self._dispatch_dir(Path(workspace), job_id, dispatch_id)
    entry = self._open.get((job_id, dispatch_id))
    if entry is not None:
        entry.dir = ddir
        self._workspaces.setdefault(job_id, set()).add(Path(workspace))
    result: asyncio.Future[Path] = asyncio.get_running_loop().create_future()
    job = self._submit(_write_dispatch_config, existing_path, delivery.mcp_entries, ddir)

    def done(f: asyncio.Future[Path]) -> None:
        e = self._open.get((job_id, dispatch_id))
        if f.cancelled() or f.exception() is not None:
            if not result.done():
                if f.cancelled():
                    result.cancel()
                else:
                    result.set_exception(f.exception() or RuntimeError("config write failed"))
            return
        path = f.result()
        if e is not None and e is entry and not (self._closing or self._closed):
            e.config_path = path
        else:  # the dispatch is gone: nothing owns this file
            self._remove_dir_now_or_queued(ddir)
        if not result.done():
            result.set_result(path)

    job.add_done_callback(done)
    return result
deliver async
deliver(job_id, sheet, *, timeout_seconds, existing_mcp_config, workspace)

prepare + merge_config as one all-or-nothing step for the adapter.

Returns None when the job has no active attachment for this sheet. On any failure everything opened is torn down before the error propagates.

Source code in src/marianne/daemon/baton/memory_gate.py
async def deliver(
    self, job_id: str, sheet: SheetIdentity, *, timeout_seconds: float,
    existing_mcp_config: Path | None, workspace: Path,
) -> PreparedMemory | None:
    """``prepare`` + ``merge_config`` as one all-or-nothing step for the adapter.

    Returns ``None`` when the job has no active attachment for this sheet. On any
    failure everything opened is torn down before the error propagates.
    """
    if job_id not in self._jobs:
        return None
    dispatch_id = f"s{sheet.num}-{uuid.uuid4().hex[:12]}"
    deadline = FAR_FUTURE  # lifetime is the dispatch's flag; see the module docstring
    delivery = await self.prepare(job_id, sheet, dispatch_id, deadline)
    if delivery is None:
        return None
    try:
        path = await asyncio.shield(self.merge_config(
            job_id, dispatch_id, delivery, existing_mcp_config, workspace,
        ))
    except BaseException as exc:
        await self._settle(self.teardown(job_id, dispatch_id))
        if isinstance(exc, Exception) and not isinstance(exc, MemoryGateError):
            raise MemoryGateError("(mcp config)", _reason(exc)) from exc
        raise
    return PreparedMemory(dispatch_id, delivery.manifest, path)
set_owner
set_owner(job_id, dispatch_id, task)

Record the task whose life bounds this dispatch: when it ends, so do the sessions.

Source code in src/marianne/daemon/baton/memory_gate.py
def set_owner(self, job_id: str, dispatch_id: str, task: asyncio.Task[Any]) -> None:
    """Record the task whose life bounds this dispatch: when it ends, so do the sessions."""
    entry = self._open.get((job_id, dispatch_id))
    if entry is None:
        return
    entry.owner = task
    task.add_done_callback(lambda _t: self._end(entry))
tick async
tick()

One hygiene pass; public so a test can drive it with an injected clock.

Enqueues the teardown of a dispatch whose flag is set but whose teardown was never enqueued (a missed one), and ends a dispatch that still has no owner after the grace. Correctness never depends on it: the flag alone refuses calls.

Source code in src/marianne/daemon/baton/memory_gate.py
async def tick(self) -> None:
    """One hygiene pass; public so a test can drive it with an injected clock.

    Enqueues the teardown of a dispatch whose flag is set but whose teardown was never
    enqueued (a missed one), and ends a dispatch that still has no owner after the grace.
    Correctness never depends on it: the flag alone refuses calls.
    """
    now = self._monotonic()
    for (job_id, dispatch_id), entry in list(self._open.items()):
        if entry.cleanup_queued:
            continue
        if not entry.ended.is_set():
            if entry.owner is not None or now - entry.opened_at <= self._ownerless_grace:
                continue
            self._end(entry)
            reason = "no owner within the grace"
        else:
            reason = "owner finished without teardown"
        entry.cleanup_queued = True
        _logger.warning(
            "memory_gate.reaped",
            extra={"job_id": job_id, "dispatch_id": dispatch_id, "reason": reason},
        )
        self._spawn(self.teardown(job_id, dispatch_id))
sweep_stale async
sweep_stale(run_dir=None)

Run :meth:_sweep_sockets on the worker (never on the loop); returns how many.

With no <run_dir>/s directory there is nothing to sweep (no memory job has ever run here): return 0 without starting the worker thread.

Source code in src/marianne/daemon/baton/memory_gate.py
async def sweep_stale(self, run_dir: Path | str | None = None) -> int:
    """Run :meth:`_sweep_sockets` on the worker (never on the loop); returns how many.

    With no ``<run_dir>/s`` directory there is nothing to sweep (no memory job has ever
    run here): return 0 without starting the worker thread.
    """
    base = Path(run_dir) if run_dir is not None else self._run_dir
    if not (base / "s").is_dir():
        return 0
    return int(await self._run(self._sweep_sockets, run_dir))
sweep_stale_configs async
sweep_stale_configs(workspace)

Remove dispatch directories a dead conductor left in workspace; returns how many.

Runs on the worker, and spares every directory of a dispatch this gate has open (asked when the worker reaches it), so it is safe while the recovered job is already running.

Source code in src/marianne/daemon/baton/memory_gate.py
async def sweep_stale_configs(self, workspace: Path | str) -> int:
    """Remove dispatch directories a dead conductor left in ``workspace``; returns how many.

    Runs on the worker, and spares every directory of a dispatch this gate has open (asked
    when the worker reaches it), so it is safe while the recovered job is already running.
    """
    return int(await self._run(_remove_dispatch_dirs, Path(workspace), self._live_dirs))
schedule_config_sweep
schedule_config_sweep(workspaces)

Fire-and-forget :meth:sweep_stale_configs for each workspace (needs a running loop).

Called when a job is recovered after a conductor restart: its sheets' dispatch directories from the previous process are dead, and nothing else would remove them. A failure is logged, never raised.

Source code in src/marianne/daemon/baton/memory_gate.py
def schedule_config_sweep(self, workspaces: Iterable[Path | str]) -> None:
    """Fire-and-forget :meth:`sweep_stale_configs` for each workspace (needs a running loop).

    Called when a job is recovered after a conductor restart: its sheets' dispatch
    directories from the previous process are dead, and nothing else would remove them.
    A failure is logged, never raised.
    """
    paths = list(dict.fromkeys(Path(w) for w in workspaces))
    if not paths:
        return
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return

    async def go() -> None:
        for ws in paths:
            try:
                await self.sweep_stale_configs(ws)
            except Exception:  # noqa: BLE001 — a failed sweep must not touch the job
                _logger.warning(
                    "memory_gate.config_sweep_failed", extra={"workspace": str(ws)},
                    exc_info=True,
                )

    self._spawn(go())
schedule_teardown
schedule_teardown(job_id, dispatch_id)

Fire-and-forget teardown for a done-callback (needs a running loop).

Source code in src/marianne/daemon/baton/memory_gate.py
def schedule_teardown(self, job_id: str, dispatch_id: str) -> None:
    """Fire-and-forget ``teardown`` for a done-callback (needs a running loop)."""
    try:
        self._spawn(self.teardown(job_id, dispatch_id))
    except RuntimeError:
        return
teardown async
teardown(job_id, dispatch_id, *, only=None)

Close sockets and sessions and remove the config. Idempotent; never raises.

Source code in src/marianne/daemon/baton/memory_gate.py
async def teardown(
    self, job_id: str, dispatch_id: str, *, only: _Open | None = None,
) -> TeardownReport:
    """Close sockets and sessions and remove the config. Idempotent; never raises."""
    entry = self._open.get((job_id, dispatch_id))
    if entry is None or (only is not None and entry is not only):
        return TeardownReport()
    self._end(entry)  # first: the sessions refuse from this instant, before any I/O
    del self._open[(job_id, dispatch_id)]
    errors: list[str] = []
    try:
        in_flight, errors = await asyncio.shield(self._close_ids(list(entry.session_ids)))
    except asyncio.CancelledError:
        in_flight = 0  # the shielded close keeps running; the config removal is queued below
        errors.append("teardown cancelled")
    if entry.dir is not None:
        # Ordered after any write still on the worker; the job survives a cancel here.
        removal = self._remove_dir_now_or_queued(entry.dir)
        if removal is not None:
            with contextlib.suppress(asyncio.CancelledError, Exception):
                await asyncio.shield(removal)
            if removal.done() and removal.exception() is not None:  # the gate shut down
                with contextlib.suppress(Exception):
                    _remove_dispatch_dir(entry.dir)
    report = TeardownReport(in_flight, tuple(errors))
    if not report.clean:
        _logger.warning(
            "memory_gate.teardown_incomplete",
            extra={
                "job_id": job_id, "dispatch_id": dispatch_id,
                "in_flight": in_flight, "errors": list(errors),
            },
        )
    return report
shutdown async
shutdown()

Close everything within a bound. Never awaits or cancels a caller's task.

Sets _closing first (no new prepare; an open still in flight is closed by its own completion step), queues a close for every open dispatch, waits for the worker queue to drain up to shutdown_bound_seconds, reports what is still pending, then stops the worker.

Source code in src/marianne/daemon/baton/memory_gate.py
async def shutdown(self) -> TeardownReport:
    """Close everything within a bound. Never awaits or cancels a caller's task.

    Sets ``_closing`` first (no new prepare; an open still in flight is closed by its
    own completion step), queues a close for every open dispatch, waits for the worker
    queue to drain up to ``shutdown_bound_seconds``, reports what is still pending,
    then stops the worker.
    """
    self._closing = True
    for entry in self._open.values():
        self._end(entry)
        entry.cleanup_queued = True
    reaper, self._reaper = self._reaper, None
    if reaper is not None:
        reaper.cancel()  # the gate's own task; never counted as pending work
        with contextlib.suppress(asyncio.CancelledError, Exception):
            await reaper
    in_flight = 0
    errors: list[str] = []
    dirs = [e.dir for e in self._open.values() if e.dir is not None]
    for job_id, dispatch_id in list(self._open):
        self._spawn(self.teardown(job_id, dispatch_id))
    deadline = asyncio.get_running_loop().time() + self._shutdown_bound
    while True:
        pending: list[Any] = [*self._background, *self._pending]
        if not pending:
            break
        left = deadline - asyncio.get_running_loop().time()
        if left <= 0:
            errors.append(f"{len(pending)} gate job(s) still pending at shutdown")
            break
        await asyncio.wait(pending, timeout=left)
    if self._endpoint is not None:
        try:
            remaining = max(deadline - asyncio.get_running_loop().time(), 0.1)
            closed = await asyncio.wait_for(self._endpoint.close(), remaining)
            for sid, left_calls in closed.items():
                in_flight += left_calls
                errors.append(f"session {sid}: {left_calls} call(s) still running")
        except TimeoutError:
            errors.append("endpoint close did not finish within the shutdown bound")
        except Exception as exc:  # noqa: BLE001 — shutdown reports, never raises
            errors.append(f"endpoint close: {_reason(exc)}")
    # From here on nothing is queued: late jobs fail at once, and the cleanup that a stuck
    # worker never reached is done inline, best effort.
    self._closed = True
    for fut in list(self._pending):
        if not fut.done():
            fut.set_exception(MemoryGateError("(gate)", "the memory gate is shut down"))
    for ddir in dirs:
        with contextlib.suppress(Exception):
            _remove_dispatch_dir(ddir)
    if self._worker is not None:
        self._worker.stop()
    return TeardownReport(in_flight, tuple(errors))

Functions:

can_deliver

can_deliver(backend, profile)

Why this backend/instrument cannot be handed an MCP config, or None if it can.

Source code in src/marianne/daemon/baton/memory_gate.py
def can_deliver(backend: Any, profile: Any) -> str | None:
    """Why this backend/instrument cannot be handed an MCP config, or ``None`` if it can."""
    if not callable(getattr(backend, "set_mcp_config", None)):
        return "the backend has no set_mcp_config (it cannot be handed an MCP config)"
    if profile is None:
        return "no instrument profile is available to confirm MCP config delivery"
    if getattr(profile, "kind", None) != "cli":
        return "only CLI instruments can be handed an MCP config"
    command = getattr(getattr(profile, "cli", None), "command", None)
    if command is None:
        return "the profile has no CLI command section"
    if not getattr(command, "mcp_config_flag", None) and not getattr(
        command, "mcp_config_workspace_path", None
    ):
        return "the profile has no mcp_config_flag and no mcp_config_workspace_path"
    return None

lookup_profile

lookup_profile(backend_pool, instrument)

The instrument profile the pool would use, or None when it cannot be read.

Source code in src/marianne/daemon/baton/memory_gate.py
def lookup_profile(backend_pool: Any, instrument: str) -> Any:
    """The instrument profile the pool would use, or ``None`` when it cannot be read."""
    registry = getattr(backend_pool, "_registry", None)
    if registry is None:
        return None
    try:
        return registry.get(instrument)
    except Exception:  # noqa: BLE001 — an unreadable profile means "cannot confirm delivery"
        return None

merge_mcp_config

merge_mcp_config(existing_path, entries, dest_dir, *, name='.memory-mcp.json')

Write dest_dir/name holding the existing config's servers plus entries.

Atomic (temp file in the same directory, fsync, os.replace), mode 0600. A name present in both the existing config and entries is refused, never overwritten. The existing file is only read. (The gate itself writes through :func:_write_dispatch_config, which never follows a symlink.)

Source code in src/marianne/daemon/baton/memory_gate.py
def merge_mcp_config(
    existing_path: Path | str | None,
    entries: Mapping[str, Mapping[str, Any]],
    dest_dir: Path | str,
    *,
    name: str = ".memory-mcp.json",
) -> Path:
    """Write ``dest_dir/name`` holding the existing config's servers plus ``entries``.

    Atomic (temp file in the same directory, fsync, ``os.replace``), mode 0600. A name
    present in both the existing config and ``entries`` is refused, never overwritten.
    The existing file is only read. (The gate itself writes through
    :func:`_write_dispatch_config`, which never follows a symlink.)
    """
    document = _merged_document(existing_path, entries)
    dest = Path(dest_dir)
    dest.mkdir(parents=True, exist_ok=True)
    fd, tmp_name = tempfile.mkstemp(dir=dest, prefix=".memory-mcp-", suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            os.fchmod(handle.fileno(), 0o600)
            handle.write(json.dumps(document, indent=2))
            handle.flush()
            os.fsync(handle.fileno())
        target = dest / name
        os.replace(tmp_name, target)
    except BaseException:
        with contextlib.suppress(OSError):
            os.unlink(tmp_name)
        raise
    return target