Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -702,8 +702,8 @@ one-line reminder in every session. The same `PYTHONPATH` limit as for the
| `SessionStart` | `session_start` | Explains that the first Daem0n call establishes the session and brief; `session_brief` returns the full brief | `CLAUDE_PROJECT_DIR` env | Yes |
| `PreToolUse` (`Edit\|Write\|NotebookEdit`) | `pre_edit` | Inside a Daem0n project, adds a one-line `additionalContext` reminder to call `daem0n_tool_call` targeting `memory_recall_file`; silent elsewhere | stdin event | Yes |
| `PreToolUse` (`Bash`) | `pre_bash` | Checks the command against active Daem0n rules (`governance_rules` / `rules`) in read-only SQLite mode and emits matching `additionalContext` reminders | stdin event (`TOOL_INPUT` fallback) | Yes (always exits 0) |
| `PostToolUse` (`mcp__.*__edit_preflight`) | `post_edit_preflight` | Edit-bridge plumbing: stages an `edit_preflight` receipt for a bridge edit request when the project is paired with `--enable-edit-bridge` | stdin event | Yes |
| `PostToolUse` (`Edit\|Write\|NotebookEdit`) | `post_edit` | Edit-bridge plumbing: reports a bridge-approved edit as a capture candidate. Only loads the bridge when the project is paired | stdin event | Yes |
| `PostToolUse` (`mcp__.*__edit_preflight`) | `post_edit_preflight` | Retained edit-bridge plumbing: stages a receipt for an explicit host-created request. The current remind-only hooks create no requests, so pairing alone does not activate this flow | stdin event | Yes |
| `PostToolUse` (`Edit\|Write\|NotebookEdit`) | `post_edit` | Retained edit-bridge plumbing: reports an approved edit as a capture candidate. The current remind-only hooks create no requests, so ordinary client edits produce no bridge capture | stdin event | Yes |
| `Stop`, `SubagentStop` | `stop` | When the transcript shows a finished task with no recorded outcome, suggests direct `memory_store` and `memory_record_outcome` calls with counsel-challenge retry guidance as a `systemMessage`. Never writes memory | stdin event (`transcript_path`) | Yes |

No hook blocks a tool call or keeps the agent running: every hook exits 0 and none
Expand Down Expand Up @@ -739,6 +739,11 @@ A Claude Code skill is included at `.claude/skills/daem0nmcp-protocol/SKILL.md`

OpenCode connects to Daem0n-MCP via the same MCP server. No server changes required -- the daemon serves all clients equally.

The V1 plugin provides Covenant guidance and edit/Bash reminders. Its installed
hooks do not create native edit-bridge requests or enforce a
deny/preflight/retry flow; bridge API acceptance is separate from this
remind-only client integration.

### Configuration

Create `opencode.json` at your project root:
Expand Down Expand Up @@ -1003,9 +1008,9 @@ daem0nmcp/
├── claude_hooks/ # Claude Code native hooks
│ ├── install.py # install/uninstall-claude-hooks CLI
│ ├── session_start.py # Suggest scoped v7 briefing
│ ├── pre_edit.py # Fail-closed v7 preflight guidance
│ ├── pre_bash.py # Rule enforcement on commands
│ ├── post_edit.py # Significance detection
│ ├── pre_edit.py # Remind-only file recall guidance
│ ├── pre_bash.py # Read-only command-rule reminders
│ ├── post_edit.py # Retained edit-bridge capture reporting
│ ├── stop.py # Read-only outcome/memory suggestions
│ └── _client.py # Hook helper utilities
├── compression/ # LLMLingua-2 context compression
Expand Down
37 changes: 22 additions & 15 deletions daem0nmcp/api/v7/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,28 @@ def run_server(

if not isinstance(options, ServerOptions):
raise ValueError("server options are required")
if options.transport == "stdio":
run_strict_stdio(server)
return
validate_security(options.host, getattr(server, "auth", None))
origin_middleware = build_origin_middleware(options.host, options.port)
from ...transport_security import build_uvicorn_security_config

server.run(
transport="streamable-http",
host=options.host,
port=options.port,
middleware=origin_middleware,
stateless_http=False,
uvicorn_config=build_uvicorn_security_config(),
)
if options.transport != "stdio":
validate_security(options.host, getattr(server, "auth", None))
from ...tracing import configure_tracing, shutdown_tracing

tracing_provider = configure_tracing()
try:
if options.transport == "stdio":
run_strict_stdio(server)
return
origin_middleware = build_origin_middleware(options.host, options.port)
from ...transport_security import build_uvicorn_security_config

server.run(
transport="streamable-http",
host=options.host,
port=options.port,
middleware=origin_middleware,
stateless_http=False,
uvicorn_config=build_uvicorn_security_config(),
)
finally:
shutdown_tracing(tracing_provider)


__all__ = [
Expand Down
10 changes: 7 additions & 3 deletions daem0nmcp/api/v7/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,9 @@ async def aclose(self) -> None:
# Only entry points the profile's own extra installs; a module from another
# profile would fail here and degrade a working one.
_NATIVE_PROFILE_MODULES = {
"local": ("qdrant_client",),
"models-local": ("sentence_transformers", "onnx", "onnxruntime"),
"local": ("numpy", "qdrant_client"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: numpy is not declared by the local extra or by PROFILES["local"], so readiness and the preload now disagree

PROFILES["local"].distributions is ("qdrant-client",) (daem0nmcp/capabilities.py:36) and the local extra installs only qdrant-client, yet this tuple now requires numpy to import. The capability registry therefore reports local: ready while the Windows preload additionally demands a working numpy, so the same install reports two different capability states depending on the platform.

Either declare numpy in the local extra and in PROFILES["local"].distributions so both sources agree, or drop numpy from the local tuple and rely on models-local/late-interaction, whose extras do declare it.

"models-local": ("numpy", "sentence_transformers", "onnx", "onnxruntime"),
"late-interaction": ("numpy",),
"graph": ("networkx", "igraph", "leidenalg"),
}

Expand Down Expand Up @@ -278,7 +279,10 @@ def start(self) -> None:
# broken native DLLs degrade upfront; auto-enabled profiles use
# lightweight spec checks to avoid multi-second startup imports.
try:
if eager:
# Windows can deadlock when a worker loads NumPy's DLLs
# while the main thread starts another worker. Initialize
# that shared prerequisite before any provider runs.
if eager or (os.name == "nt" and module == "numpy"):
importlib.import_module(module)
elif importlib.util.find_spec(module) is None:
raise ModuleNotFoundError(module)
Expand Down
25 changes: 5 additions & 20 deletions daem0nmcp/claude_hooks/pre_bash.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pathlib import Path

from ..similarity import TFIDFIndex
from ..storage_activation import PointerValidationError, resolve_active_database
from ._client import (
block,
find_project_root,
Expand Down Expand Up @@ -63,26 +64,10 @@ def _resolve_db_file(project_path: str) -> Path | None:
storage_dir = Path(project_path) / ".daem0nmcp" / "storage"
if not storage_dir.is_dir():
return None
pointer_path = storage_dir / "active.json"
if pointer_path.is_file():
try:
pointer = json.loads(pointer_path.read_text(encoding="utf-8"))
candidate = (
pointer.get("active_generation") if isinstance(pointer, dict) else None
)
if (
isinstance(candidate, str)
and candidate
and "/" not in candidate
and "\\" not in candidate
):
candidate_path = storage_dir / candidate
if candidate_path.is_file():
return candidate_path
except (OSError, ValueError):
pass
default_db = storage_dir / "daem0nmcp.db"
return default_db if default_db.is_file() else None
try:
return resolve_active_database(storage_dir).path

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The resolved v7 database is WAL-mode, and the connect below opens it with a bare ?mode=ro URI

resolve_active_database() now returns the active generation database (for a migrated store: migrations/v7/<run>/candidate.db), and every Daem0n database is WAL-mode (daem0nmcp/database.py:104). Opening a WAL-mode file read-only without immutable=1 lets SQLite create -wal/-shm sidecars inside the user's storage directory; when it cannot create them the read fails with SQLITE_CANTOPEN, which _load_active_rules swallows, so the hook enforces no rules at all (fail-open).

The repo already has the correct helper in the module this file imports: use sqlite3.connect(readonly_database_uri(db_file), uri=True, timeout=2.0) and add readonly_database_uri to the ..storage_activation import. It adds immutable=1 when no sidecars exist, which is the "offline inspection must leave no sidecars" policy in daem0nmcp/workspace.py:383-390.

except (OSError, PointerValidationError):
return None


def _load_active_rules(project_path: str) -> list[_RuleCandidate]:
Expand Down
133 changes: 120 additions & 13 deletions daem0nmcp/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,143 @@
FastMCP 3.0 has native OpenTelemetry support. This module provides
configuration and helper utilities for Daem0n-specific tracing.

Enable by setting:
Install the observability extra and enable by setting:
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
OTEL_SERVICE_NAME=daem0nmcp

The default OTLP protocol is grpc; set OTEL_EXPORTER_OTLP_PROTOCOL to
http/protobuf for an HTTP collector. Configuration failures warn on stderr
and leave the core server available.
"""

from __future__ import annotations

import logging
import os
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from opentelemetry.sdk.trace import TracerProvider

logger = logging.getLogger(__name__)

_TRACING_ENABLED: bool | None = None


def is_tracing_enabled() -> bool:
"""Check if tracing is configured."""
"""Return whether startup installed or found an active tracing provider."""
return _TRACING_ENABLED is True


def get_service_name() -> str:
"""Get the service name for tracing."""
return os.environ.get("OTEL_SERVICE_NAME", "daem0nmcp")


def configure_tracing() -> TracerProvider | None:
"""Configure requested OTLP export and return only a provider we own."""
global _TRACING_ENABLED
_TRACING_ENABLED = False
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") or os.environ.get(
"OTEL_EXPORTER_OTLP_ENDPOINT"
)
if not endpoint or os.environ.get("OTEL_SDK_DISABLED", "").lower() == "true":
return None

if _TRACING_ENABLED is not None:
return _TRACING_ENABLED
from .capabilities import CapabilityRegistry

# Check for OTLP endpoint configuration
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
_TRACING_ENABLED = endpoint is not None and len(endpoint) > 0
capability = CapabilityRegistry().get("observability")
if (
capability["status"] == "disabled"
and capability["remediation"]["action"] == "enable_configuration"
):
return None
try:
from opentelemetry import trace
except ImportError:
logger.warning(
'OpenTelemetry tracing unavailable; install "daem0nmcp[observability]".'
)
return None
try:
existing_provider = trace.get_tracer_provider()
except Exception:
logger.warning(
"OpenTelemetry tracing unavailable; check the configured tracing provider."
)
return None
if not isinstance(existing_provider, trace.ProxyTracerProvider):
_TRACING_ENABLED = True
return None
protocol = (
(
os.environ.get("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")
or os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL")
or "grpc"
)
.strip()
.lower()
)
if protocol not in {"grpc", "http/protobuf"}:
logger.warning(
"OpenTelemetry tracing unavailable; set OTEL_EXPORTER_OTLP_PROTOCOL "
"or OTEL_EXPORTER_OTLP_TRACES_PROTOCOL to grpc or http/protobuf."
)
return None
if capability["status"] != "ready":
logger.warning(
"OpenTelemetry tracing unavailable; enable the observability profile "
'and install "daem0nmcp[observability]".'
)
return None

if _TRACING_ENABLED:
logger.info(f"OpenTelemetry tracing enabled: {endpoint}")
provider = None
try:
from opentelemetry.sdk.resources import OTELResourceDetector, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

return _TRACING_ENABLED
if protocol == "http/protobuf":
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter,
)
else:
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
OTLPSpanExporter,
)
resource = Resource.create({"service.name": "daem0nmcp"}).merge(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Reuse get_service_name() instead of the hardcoded service name

This module already resolves the service name in one place (get_service_name()), but the resource hardcodes "daem0nmcp" and then re-merges the environment to undo it. Resource.create() already applies OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME, so resource = Resource.create({"service.name": get_service_name()}) yields the same resource (OTEL_SERVICE_NAME wins over OTEL_RESOURCE_ATTRIBUTES per the OTel spec) with one merge instead of two, and the two service-name sources can no longer drift.

OTELResourceDetector().detect()
)
provider = TracerProvider(resource=resource, shutdown_on_exit=False)
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
if trace.get_tracer_provider() is not provider:
shutdown_tracing(provider)
return None
except Exception:
shutdown_tracing(provider)
logger.warning(
"OpenTelemetry tracing unavailable; check the observability "
"installation and OTLP exporter configuration."
)
return None
_TRACING_ENABLED = True
logger.info("OpenTelemetry tracing enabled.")
return provider


def get_service_name() -> str:
"""Get the service name for tracing."""
return os.environ.get("OTEL_SERVICE_NAME", "daem0nmcp")
def shutdown_tracing(provider: TracerProvider | None) -> None:
"""Flush owned spans without allowing telemetry errors to mask shutdown."""
global _TRACING_ENABLED
if provider is None:
return
_TRACING_ENABLED = False
try:
if not provider.force_flush(timeout_millis=5000):
logger.warning("OpenTelemetry trace flush timed out.")
except Exception:
logger.warning("OpenTelemetry trace flush failed.")
try:
provider.shutdown()
except Exception:
logger.warning("OpenTelemetry tracing shutdown failed.")
10 changes: 6 additions & 4 deletions daem0nmcp/ui/static/renderers/community.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@
svg.setAttribute("aria-label", "Memory communities");
const details = ui.element("aside", "community-details", "Select a community for details.");
details.hidden = true;
if (data.communities.length && globalThis.D3) {
const root = globalThis.D3.hierarchy(hierarchy(data)).sum(value => value.value || 0);
globalThis.D3.treemap().size([960, 540]).padding(3)(root);
if (data.communities.length && globalThis.d3) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: A missing D3 bundle now renders "No communities found."

After this fix the else branch is reachable with populated data whenever the bundle fails to load, and it states that there are no communities — a false statement about the data rather than a load failure. Split the conditions: keep "No communities found." for an empty data.communities, and show a distinct message (e.g. "Community map is unavailable.") when globalThis.d3 is missing.

const root = globalThis.d3.hierarchy(hierarchy(data)).sum(value => value.value || 0);
globalThis.d3.treemap().size([960, 540]).padding(3)(root);
for (const leaf of root.leaves()) {
const item = leaf.data.item;
if (!item) continue;
Expand Down Expand Up @@ -121,7 +121,9 @@
message.setAttribute("x", "480");
message.setAttribute("y", "270");
message.setAttribute("text-anchor", "middle");
message.textContent = "No communities found.";
message.textContent = data.communities.length
? "Community map is unavailable."
: "No communities found.";
svg.append(message);
}
frame.append(svg, details);
Expand Down
14 changes: 7 additions & 7 deletions daem0nmcp/ui/static/renderers/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
mount.replaceChildren(header, controls, frame);

const context = canvas.getContext("2d");
if (!context || !globalThis.D3) {
if (!context || !globalThis.d3) {
loading.hidden = true;
return;
}
Expand Down Expand Up @@ -252,20 +252,20 @@
canvas.height = Math.round(height * pixelRatio);
clampPan();
if (simulation) {
simulation.force("center", globalThis.D3.forceCenter(width / 2, height / 2));
simulation.force("center", globalThis.d3.forceCenter(width / 2, height / 2));
simulation.alpha(0.25).restart();
}
draw();
}

const progressive = nodes.length > progressiveThreshold;
activeNodes = progressive ? [] : nodes;
const linkForce = globalThis.D3.forceLink([]).id(node => ui.idKey(node.id)).distance(80);
simulation = globalThis.D3.forceSimulation(activeNodes)
const linkForce = globalThis.d3.forceLink([]).id(node => ui.idKey(node.id)).distance(80);
simulation = globalThis.d3.forceSimulation(activeNodes)
.force("link", linkForce)
.force("charge", globalThis.D3.forceManyBody().strength(-120))
.force("center", globalThis.D3.forceCenter(width / 2, height / 2))
.force("collision", globalThis.D3.forceCollide(14))
.force("charge", globalThis.d3.forceManyBody().strength(-120))
.force("center", globalThis.d3.forceCenter(width / 2, height / 2))
.force("collision", globalThis.d3.forceCollide(14))
.on("tick", draw);

function rebuildLinks() {
Expand Down
Loading
Loading