Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
eb7d53e
feat(context): add deterministic token-budgeted source assembler
dovvnloading Nov 18, 2026
6fd2812
feat(chat): route provider prompts through the context assembler
dovvnloading Nov 18, 2026
c538eac
fix(context): preserve legacy summary wire shape and bound oversized …
dovvnloading Nov 18, 2026
5c0b7df
feat(context): read-only next-send inspector intent and source proven…
dovvnloading Nov 18, 2026
ffbcb4e
feat(ui): mount read-only Context Inspector next to composer
dovvnloading Nov 18, 2026
12cb11b
fix(context): type ancestor walk and escape untrusted envelope delimi…
dovvnloading Nov 18, 2026
85d6e17
fix(ui): avoid synchronous state updates in inspector effect
dovvnloading Nov 18, 2026
71cc29d
fix(context): type generated summaries and keep tool authority separate
dovvnloading Nov 18, 2026
9578e7d
test(context): verify legacy chat parity, budgeting and injection bou…
dovvnloading Nov 18, 2026
35573da
test(context): inspect next send without provider calls or graph muta…
dovvnloading Nov 18, 2026
416f74f
fix(context): validate canonical typed envelopes and user-owned syste…
dovvnloading Nov 18, 2026
b3f6729
docs(context): prompt trace, source policy, inspector contract and li…
dovvnloading Nov 18, 2026
2b2a9a5
test(ui): context preview, refresh, error, and empty-chat behavior
dovvnloading Nov 18, 2026
fb02cbb
fix(context): retain standalone assistant as legacy newest turn
dovvnloading Nov 18, 2026
3543b55
fix(context): fail closed visibly and bind tool roles and pinned loca…
dovvnloading Nov 18, 2026
4f609dd
fix(context): honor mandatory sources, restore CI parity and theme to…
dovvnloading Nov 18, 2026
030b1a1
perf(ui): code-split Context Inspector to preserve initial chunk budget
dovvnloading Nov 18, 2026
b61da3b
test(context): classify read-only inspector intent and account for re…
dovvnloading Nov 18, 2026
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
8 changes: 8 additions & 0 deletions backend/api/intents_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,14 @@ def _on_partial(partial_text):
)
return node_to_regenerate.id

# C3 preview is read-only: no graph command, provider call or publication.
async def inspect_chat_context(node_id, draft_text=""):
from backend.context_engine.inspector import inspect_next_chat_send
return inspect_next_chat_send(
document, node_id, agent_dispatcher, bus=bus, draft_text=draft_text,
)

bus.register_intent("scene", "inspectChatContext", inspect_chat_context)
bus.register_intent("scene", "sendMessage", send_message)
bus.register_intent("scene", "regenerateResponse", regenerate_response)
# R4.3: per-node cancel for a ConversationNode's in-flight reply. Reuses
Expand Down
19 changes: 19 additions & 0 deletions backend/context_engine/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Deterministic, Qt-free context selection for Graphlink model calls."""

from .assembler import (
ContextAssembler,
ContextBudgetError,
ContextCandidate,
ContextPlan,
typed_context_message,
selected_context_window,
)

__all__ = [
"ContextAssembler",
"ContextBudgetError",
"ContextCandidate",
"ContextPlan",
"typed_context_message",
"selected_context_window",
]
390 changes: 390 additions & 0 deletions backend/context_engine/assembler.py

Large diffs are not rendered by default.

134 changes: 134 additions & 0 deletions backend/context_engine/inspector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""Read-only C3 preview of the NEXT chat send on a graph node.

The preview accepts an explicit unsent draft; it does not consume the composer,
index documents, call a provider, or generate summaries. The real send still
builds ancestors in backend.domain.branches.chat_branch_history and resolves
the system/model in DispatcherCoreOps, which this module calls directly.
"""

from __future__ import annotations

import api_provider
from backend.context_engine import ContextAssembler, ContextBudgetError, selected_context_window
from backend.domain.model import SceneError
from graphlink_chat_agent import ChatAgent
from graphlink_memory import message_tokens


def _branch_origins(document, node_id: str) -> list[str]:
"""Mirror chat_branch_history's structural-parent walk, not raw edges."""
reversed_ids = []
seen = set()
current: str | None = node_id
while current is not None and current not in seen:
seen.add(current)
node = document.nodes.get(current)
if node is None:
break
reversed_ids.append(f"node:{current}")
edge = document._branch_parent_edge(current)
current = edge.source if edge is not None else None
return list(reversed(reversed_ids))


def inspect_next_chat_send(document, node_id: str, dispatcher, *, bus=None, draft_text: str = "") -> dict:
"""Explain the next dispatch from node_id, without mutating anything.

The preview is limited to known history and the supplied draft. Incoming
document/image attachments not yet sent cannot be inferred here. The
existing chat reply path does not auto-inject pinned notes or knowledge
hits; this preview does not invent them or run retrieval on a read.
"""
node = document.nodes.get(node_id)
if node is None or node.kind != "chat":
raise SceneError(f"node is not a chat node: {node_id}")
if not isinstance(draft_text, str):
raise ValueError("draft_text must be a string")
# Keep the full walk and its origins from the same immutable-in-this-call
# graph snapshot; neither operation creates a node or modifies the model.
history = document.chat_branch_history(node_id)
origins = _branch_origins(document, node_id)
if len(history) != len(origins):
raise SceneError("branch history changed during inspection")
history.append({"role": "user", "content": draft_text})
origins.append(f"draft:after:{node_id}")

override = dispatcher._resolve_branch_system_prompt(document, node_id)
persona = override if override is not None else dispatcher.persona()
system_prompt = persona if override is not None else ChatAgent("Graphlink Assistant", persona).system_prompt
system_origin = "system:settings"
if override is not None:
# Match the dispatcher's first connected System Prompt note, using
# structural source identity rather than a long nested expression.
system_origin = "system-note:unknown"
root = document.get_branch_root(node_id)
if root is not None:
for edge in document.edges.values():
if edge.target != root.id:
continue
source = document.nodes.get(edge.source)
if (
source is not None and source.kind == "note"
and getattr(source.state, "is_system_prompt", False)
):
system_origin = f"system-note:{source.id}"
break

model_ref = dispatcher._resolve_model_ref_for_dispatch(document, node_id, bus=bus)
runtime = dispatcher._provider_runtime if dispatcher._provider_runtime is not None else api_provider.DEFAULT_RUNTIME
try:
window = selected_context_window(runtime, model_ref)
except Exception:
window = 8000 # ChatWorker.run's own last-resort fallback
provider, model = dispatcher.active_provider_model(model_ref)
local = provider.lower() in ("ollama", "llama.cpp")
assembler = ContextAssembler()
candidates = assembler.chat_sources(
system_prompt, history, origins=origins, system_origin=system_origin,
)
try:
plan = assembler.assemble(candidates, context_window=window, leaves_device=not local)
except ContextBudgetError as exc:
# A preview must disclose the failure without claiming a send can
# proceed. No provider is called and no context is silently dropped.
# Nothing is dispatched in this case: still enumerate every source
# with its original measured cost, instead of hiding the context
# precisely when the user most needs to inspect it.
reserve = min(4096, window // 4)
return {
"nodeId": node_id,
"provider": provider,
"model": model,
"contextWindow": window,
"outputReserve": reserve,
"promptBudget": window - reserve,
"promptTokens": 0,
"leavesDevice": not local,
"draftIncluded": bool(draft_text),
"error": str(exc),
"sources": [
{
"sourceId": src.source_id,
"origin": src.origin,
"kind": src.kind,
"trust": src.trust,
"tokenCount": message_tokens(src.message, assembler.token_estimator),
"sentTokenCount": 0,
"included": False,
"truncated": False,
"leavesDevice": False,
"reason": "not sent: mandatory context exceeds model budget",
}
for src in candidates
],
}
result = plan.inspect()
result.update({
"nodeId": node_id,
"provider": provider,
"model": model,
"leavesDevice": not local,
"draftIncluded": bool(draft_text),
"notice": "Preview of the supplied draft and persisted branch only. Unsent attachments and model-generated summaries are not available until send. Knowledge search and ordinary notes are not auto-injected by this chat path.",
})
return result
Loading
Loading