def summary_handler(capability: Any) -> Callable[[Any], Any]:
"""Materialize a scoped summary before the JIT compiler reads it."""
async def handle(context: Any) -> StageResult[Any]:
request = getattr(context, "request", None)
if request is None:
return no_change("STM summary received no turn request")
scope = getattr(request, "scope", None) or capability.scope
try:
result = await capability.summary.summarize(STMSummaryRequest(scope=scope))
except Exception as exc: # noqa: BLE001 - learned context may degrade
return no_change(f"STM summary degraded: {type(exc).__name__}")
if getattr(result, "degraded", False) or not getattr(result, "text", ""):
return no_change(getattr(result, "reason", "") or "STM summary is empty")
contribution = MemoryContribution(
contribution_id="memory.stm-summary",
source=ComposedMemorySource(
block=result.text,
revision=result.revision,
scope_path=scope.path,
),
requires_hydration=False,
jit_only=True,
)
return applied(
ResolvedInput(
capability=HMS_CAPABILITY,
value=(contribution_spec(contribution),),
provenance=result.revision,
),
counts={"summarized": 1},
)
return handle