dandelion-memory 1.0.0rc15__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- benchmarks/__init__.py +3 -0
- benchmarks/adapters/__init__.py +29 -0
- benchmarks/adapters/ablations.py +406 -0
- benchmarks/adapters/base.py +72 -0
- benchmarks/adapters/controlled/__init__.py +13 -0
- benchmarks/adapters/controlled/core_archival.py +115 -0
- benchmarks/adapters/controlled/extract_resolve.py +130 -0
- benchmarks/adapters/controlled/hybrid_rag.py +120 -0
- benchmarks/adapters/controlled/no_late_binding.py +113 -0
- benchmarks/adapters/dandelion.py +94 -0
- benchmarks/adapters/native/__init__.py +31 -0
- benchmarks/adapters/native/base.py +45 -0
- benchmarks/adapters/native/dandelion_native.py +164 -0
- benchmarks/adapters/native/dandelion_native_b0.py +165 -0
- benchmarks/adapters/native/dandelion_native_b1.py +170 -0
- benchmarks/adapters/native/dandelion_native_b2.py +169 -0
- benchmarks/adapters/native/dandelion_native_b3.py +171 -0
- benchmarks/adapters/native/dandelion_native_c4.py +261 -0
- benchmarks/adapters/native/dandelion_native_c4_1.py +281 -0
- benchmarks/adapters/native/dandelion_native_c4_2.py +435 -0
- benchmarks/adapters/native/event_evidence_b2.py +616 -0
- benchmarks/adapters/native/evidence_b2.py +609 -0
- benchmarks/adapters/native/letta_native.py +253 -0
- benchmarks/adapters/native/mem0_native.py +219 -0
- benchmarks/adapters/native/store_vector_b0.py +792 -0
- benchmarks/adapters/native/store_vector_b2.py +808 -0
- benchmarks/agent_adapter_stdio_acceptance.py +86 -0
- benchmarks/bootstrap_cross_stack.py +218 -0
- benchmarks/canonical_profile_instrumentation.py +167 -0
- benchmarks/canonical_public_baseline.py +288 -0
- benchmarks/cli.py +525 -0
- benchmarks/collector_public30_offline.py +1653 -0
- benchmarks/datasets/__init__.py +45 -0
- benchmarks/datasets/conversational_generator.py +238 -0
- benchmarks/datasets/generator.py +283 -0
- benchmarks/datasets/holdout_topology_generator.py +290 -0
- benchmarks/datasets/holdout_topology_generator_v2.py +294 -0
- benchmarks/datasets/multi_world.py +1643 -0
- benchmarks/datasets/scale_generator.py +289 -0
- benchmarks/datasets/schema.py +57 -0
- benchmarks/deep_collision_stress.py +199 -0
- benchmarks/evaluators/__init__.py +12 -0
- benchmarks/evaluators/manifest.py +142 -0
- benchmarks/evaluators/metrics.py +277 -0
- benchmarks/evaluators/runner.py +258 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v1.py +127 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v2.py +127 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v3.py +146 -0
- benchmarks/f1_step0/build_ledger.py +143 -0
- benchmarks/f1_step0/build_ledger_v2.py +296 -0
- benchmarks/f1_step0/compare_dev52_readiness_v1.py +106 -0
- benchmarks/f1_step0/locator_public_smoke.py +172 -0
- benchmarks/f1_step0/prepare_dev52_owner_v1.py +133 -0
- benchmarks/f1_step0/prepare_dev52_owner_v2.py +133 -0
- benchmarks/f1_step0/public_identity_probe.py +191 -0
- benchmarks/f1_step0/public_response_mapper.py +101 -0
- benchmarks/f1_step0/real_source_public_preflight.py +244 -0
- benchmarks/f1_step0/run_exact_fusion_dev_experiment_v1.py +83 -0
- benchmarks/f1_step0/scorer.py +110 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v1.py +627 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v2.py +659 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v3.py +776 -0
- benchmarks/f1_step0/test_public_response_mapper.py +110 -0
- benchmarks/f1_step0/test_real_source_public_preflight.py +25 -0
- benchmarks/f1_step0/test_scorer.py +158 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement.py +189 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement_v2.py +263 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement_v3.py +334 -0
- benchmarks/f1_step0/typed_readback_public_smoke.py +181 -0
- benchmarks/forensic_c4_1_dev.py +258 -0
- benchmarks/forensic_c4_dev.py +255 -0
- benchmarks/forensic_deep25_c4_1.py +478 -0
- benchmarks/legacy_migration_acceptance.py +29 -0
- benchmarks/longmemeval_actor.py +497 -0
- benchmarks/longmemeval_agent_judge.py +593 -0
- benchmarks/longmemeval_budget.py +139 -0
- benchmarks/longmemeval_full.py +410 -0
- benchmarks/longmemeval_judge.py +327 -0
- benchmarks/longmemeval_pilot.py +316 -0
- benchmarks/longmemeval_s.py +318 -0
- benchmarks/memory_bench.py +248 -0
- benchmarks/memory_formation/__init__.py +1 -0
- benchmarks/memory_formation/audit.py +801 -0
- benchmarks/memory_formation/real_audit.py +688 -0
- benchmarks/memory_session_acceptance.py +279 -0
- benchmarks/native_codex_host.py +513 -0
- benchmarks/owner_dense_acceptance.py +126 -0
- benchmarks/pilot_seeker_vault.py +266 -0
- benchmarks/prepare_public30_ripgrep_range_owner.py +115 -0
- benchmarks/profile_canonical.py +373 -0
- benchmarks/profile_canonical_lanes.py +405 -0
- benchmarks/profile_search_chunks.py +351 -0
- benchmarks/public_ranges_faq_proof.py +121 -0
- benchmarks/public_repos/build_history_scope_v3.py +330 -0
- benchmarks/public_repos/build_oracle.py +108 -0
- benchmarks/public_repos/build_oracle_v2.py +169 -0
- benchmarks/public_repos/build_oracle_v3.py +176 -0
- benchmarks/public_repos/map_public_v2.py +296 -0
- benchmarks/public_repos/project_prompts_v2.py +31 -0
- benchmarks/public_repos/project_prompts_v3.py +29 -0
- benchmarks/public_repos/ready_admin_v2.py +214 -0
- benchmarks/public_repos/score_public_v2.py +258 -0
- benchmarks/public_repos/test_map_public_v2.py +171 -0
- benchmarks/public_repos/test_public_repo_v2.py +44 -0
- benchmarks/public_repos/test_public_repo_v3.py +46 -0
- benchmarks/public_repos/test_ready_admin_v2.py +117 -0
- benchmarks/public_repos/test_score_public_v2.py +163 -0
- benchmarks/public_repos/test_wire_v2.py +292 -0
- benchmarks/public_repos/wire_v2.py +603 -0
- benchmarks/real_blocker_fix_acceptance.py +155 -0
- benchmarks/real_scan_rescan_acceptance.py +41 -0
- benchmarks/recall_v2_20k_smoke.py +112 -0
- benchmarks/recall_v2_e1_retrieve.py +70 -0
- benchmarks/recall_v2_e1_score.py +271 -0
- benchmarks/recall_v2_e2_prepare.py +69 -0
- benchmarks/recall_v2_e2_public_score.py +91 -0
- benchmarks/recall_v2_e2_score.py +108 -0
- benchmarks/recall_v2_navigation_mcp_replay.py +308 -0
- benchmarks/recall_v2_reader_capture.py +118 -0
- benchmarks/recall_v2_reader_replay.py +136 -0
- benchmarks/run_blind_h10_holdout.py +284 -0
- benchmarks/run_blind_h9_holdout.py +275 -0
- benchmarks/run_c4_2_nightly_scale.py +446 -0
- benchmarks/run_context_scale_simulation.py +189 -0
- benchmarks/run_conversational_bench.py +170 -0
- benchmarks/run_h11_evaluation.py +316 -0
- benchmarks/run_h11_v2_evaluation.py +431 -0
- benchmarks/run_native_fixed12.py +469 -0
- benchmarks/run_native_preflight.py +280 -0
- benchmarks/run_scale_stress.py +225 -0
- benchmarks/solanazation_brownfield_01/build_oracle.py +970 -0
- benchmarks/solanazation_brownfield_01/check_level_a.py +78 -0
- benchmarks/solanazation_brownfield_01/debug_scope.py +13 -0
- benchmarks/solanazation_brownfield_01/evaluate_bootstrap_02.py +570 -0
- benchmarks/solanazation_brownfield_01/evaluate_first_pass.py +306 -0
- benchmarks/solanazation_brownfield_01/generate_dryrun_report.py +222 -0
- benchmarks/solanazation_brownfield_01/generate_manifests.py +146 -0
- benchmarks/solanazation_brownfield_01/inspect_misses.py +29 -0
- benchmarks/solanazation_brownfield_01/run_miss_forensic.py +206 -0
- benchmarks/solanazation_brownfield_01/test_facts.py +15 -0
- benchmarks/statistics/__init__.py +15 -0
- benchmarks/statistics/significance.py +326 -0
- benchmarks/test_native_mcp_preflight.py +229 -0
- benchmarks/test_prepare_public30_range_owner.py +35 -0
- benchmarks/test_public30_source_reference.py +698 -0
- benchmarks/test_recall_v2_e1_reader_input.py +89 -0
- benchmarks/test_recall_v2_navigation_mcp_replay.py +155 -0
- benchmarks/test_recall_v2_reader_replay.py +41 -0
- dandelion/__init__.py +3 -0
- dandelion/__main__.py +11 -0
- dandelion/agent_adapter.py +2369 -0
- dandelion/bootstrap/__init__.py +872 -0
- dandelion/bootstrap/alias_policy.py +50 -0
- dandelion/bootstrap/authority.py +225 -0
- dandelion/bootstrap/canonical_history.py +412 -0
- dandelion/bootstrap/classifier.py +403 -0
- dandelion/bootstrap/component_graph.py +280 -0
- dandelion/bootstrap/discovery.py +279 -0
- dandelion/bootstrap/domain_induction.py +180 -0
- dandelion/bootstrap/domain_topology.py +673 -0
- dandelion/bootstrap/evidence_envelope.py +132 -0
- dandelion/bootstrap/extractors/base.py +171 -0
- dandelion/bootstrap/extractors/exact.py +1234 -0
- dandelion/bootstrap/extractors/generic.py +100 -0
- dandelion/bootstrap/extractors/git_temporal.py +111 -0
- dandelion/bootstrap/extractors/registry.py +345 -0
- dandelion/bootstrap/extractors/relations.py +89 -0
- dandelion/bootstrap/extractors/semantic.py +424 -0
- dandelion/bootstrap/extractors/status.py +218 -0
- dandelion/bootstrap/git_sweeper.py +135 -0
- dandelion/bootstrap/manifest.py +246 -0
- dandelion/bootstrap/quarantine.py +264 -0
- dandelion/bootstrap/report.py +259 -0
- dandelion/bootstrap/root_resolver.py +221 -0
- dandelion/bootstrap/tech_profiler.py +125 -0
- dandelion/bootstrap/topology.py +75 -0
- dandelion/bootstrap/topology_index.py +110 -0
- dandelion/bootstrap/transaction.py +315 -0
- dandelion/canonical_bootstrap.py +257 -0
- dandelion/canonical_memory.py +4130 -0
- dandelion/captured_input.py +295 -0
- dandelion/cli.py +767 -0
- dandelion/config.py +40 -0
- dandelion/derived_index.py +745 -0
- dandelion/domains.py +706 -0
- dandelion/embedder.py +229 -0
- dandelion/event_evidence.py +571 -0
- dandelion/evidence.py +812 -0
- dandelion/evidence_response.py +453 -0
- dandelion/evidence_workspace.py +2360 -0
- dandelion/exact_context.py +129 -0
- dandelion/hydrator.py +124 -0
- dandelion/inspector.py +442 -0
- dandelion/inspector_assets/dandelion-mark.svg +33 -0
- dandelion/inspector_assets/dandelion_graph.js +361 -0
- dandelion/inspector_assets/inspector.css +223 -0
- dandelion/inspector_assets/inspector.html +135 -0
- dandelion/inspector_assets/inspector.js +1059 -0
- dandelion/legacy_import.py +431 -0
- dandelion/live_source_grants.py +133 -0
- dandelion/local_owner.py +114 -0
- dandelion/memory_client.py +252 -0
- dandelion/memory_contract.py +107 -0
- dandelion/memory_owner.py +560 -0
- dandelion/reader_providers.py +118 -0
- dandelion/recall_v2.py +767 -0
- dandelion/reconciler.py +219 -0
- dandelion/request_budget.py +125 -0
- dandelion/retained_basis.py +223 -0
- dandelion/retrieval.py +485 -0
- dandelion/router.py +405 -0
- dandelion/search_terms.py +53 -0
- dandelion/security.py +124 -0
- dandelion/server.py +810 -0
- dandelion/source_content_fts.py +219 -0
- dandelion/source_delivery.py +89 -0
- dandelion/source_history.py +241 -0
- dandelion/source_identity.py +88 -0
- dandelion/source_navigator.py +5 -0
- dandelion/source_reader.py +444 -0
- dandelion/source_references.py +379 -0
- dandelion/source_sections.py +265 -0
- dandelion/store_kv.py +684 -0
- dandelion/store_vector.py +1289 -0
- dandelion/studio.py +325 -0
- dandelion/wal.py +227 -0
- dandelion_memory-1.0.0rc15.dist-info/METADATA +48 -0
- dandelion_memory-1.0.0rc15.dist-info/RECORD +232 -0
- dandelion_memory-1.0.0rc15.dist-info/WHEEL +5 -0
- dandelion_memory-1.0.0rc15.dist-info/entry_points.txt +5 -0
- dandelion_memory-1.0.0rc15.dist-info/licenses/LICENSE +21 -0
- dandelion_memory-1.0.0rc15.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""Opt-in native MCP host for bounded reference sessions.
|
|
2
|
+
|
|
3
|
+
The native actor connects to an actual loopback Streamable HTTP MCP server.
|
|
4
|
+
Source tools retain their existing adapter closures and schemas. The host owns
|
|
5
|
+
the listener, numeric page selectors and final hydration; no model command or
|
|
6
|
+
source grant is accepted from actor output.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import secrets
|
|
18
|
+
import socket
|
|
19
|
+
import sys
|
|
20
|
+
import time
|
|
21
|
+
|
|
22
|
+
from fastmcp import Client, FastMCP
|
|
23
|
+
from fastmcp.exceptions import ToolError
|
|
24
|
+
from fastmcp.server.middleware import Middleware
|
|
25
|
+
from fastmcp.tools import ToolResult
|
|
26
|
+
from mcp.types import TextContent
|
|
27
|
+
import uvicorn
|
|
28
|
+
|
|
29
|
+
from benchmarks.collector_public30_offline import (
|
|
30
|
+
QUESTION_SHA, TERMS_SHA, _hydrate_selected_evidence_citations,
|
|
31
|
+
_mcp_json_payload, _mcp_recall, reference_answer_prompt, reference_search,
|
|
32
|
+
sha, write,
|
|
33
|
+
)
|
|
34
|
+
from dandelion.evidence_response import packed_literal_evidence_pages
|
|
35
|
+
from dandelion.request_budget import OperationDeadline
|
|
36
|
+
from dandelion.source_navigator import NavigationLimits
|
|
37
|
+
from dandelion.source_references import DeliveredEvidencePages
|
|
38
|
+
from dandelion.source_identity import literal_page_identities
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
SOURCE_TOOLS = frozenset({"source_catalog", "source_read", "source_history"})
|
|
42
|
+
NATIVE_SOURCE_TOOLS = SOURCE_TOOLS | {"reference_search"}
|
|
43
|
+
NATIVE_SERVER_NAME = "dandelion"
|
|
44
|
+
DISABLED_FEATURES = ("shell_tool", "apps", "plugins", "multi_agent", "view_image",
|
|
45
|
+
"browser_use", "computer_use", "image_generation")
|
|
46
|
+
FINAL_SCHEMA = {
|
|
47
|
+
"type": "object", "additionalProperties": False,
|
|
48
|
+
"properties": {
|
|
49
|
+
"answer": {"type": "string", "maxLength": 8192},
|
|
50
|
+
"citations": {"type": "array", "maxItems": 32,
|
|
51
|
+
"items": {"type": "integer", "minimum": 1}},
|
|
52
|
+
"abstained": {"type": "boolean"},
|
|
53
|
+
},
|
|
54
|
+
"required": ["answer", "citations", "abstained"],
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _ActorTools(Middleware):
|
|
59
|
+
def __init__(self, host):
|
|
60
|
+
self.host = host
|
|
61
|
+
|
|
62
|
+
async def on_call_tool(self, context, call_next):
|
|
63
|
+
host = self.host
|
|
64
|
+
async with host._action_lock:
|
|
65
|
+
# The frozen budget includes the final answer as its last action.
|
|
66
|
+
if host._sealed or len(host.actor_actions) >= host.max_actions - 1:
|
|
67
|
+
host.blocked_actor_tool_calls += 1
|
|
68
|
+
raise ToolError("reference action budget exhausted; return your final answer")
|
|
69
|
+
name, arguments = context.message.name, context.message.arguments or {}
|
|
70
|
+
started = time.monotonic()
|
|
71
|
+
entry = {"action": {"op": "tool", "name": name, "arguments": arguments}}
|
|
72
|
+
host.actor_actions.append(entry)
|
|
73
|
+
try:
|
|
74
|
+
deadline = OperationDeadline.start(NavigationLimits().elapsed_seconds)
|
|
75
|
+
result = await asyncio.wait_for(call_next(context), timeout=deadline.remaining())
|
|
76
|
+
payload = _mcp_json_payload(result, name)
|
|
77
|
+
entry["result"] = payload
|
|
78
|
+
if name == "source_read" and not result.is_error:
|
|
79
|
+
result_id, selections = host.delivered_pages.capture_page_selections(
|
|
80
|
+
packed_literal_evidence_pages(payload),
|
|
81
|
+
identities=literal_page_identities(payload), deadline=deadline.deadline)
|
|
82
|
+
if result_id is not None:
|
|
83
|
+
supporting = {"result_id": result_id,
|
|
84
|
+
"pages": [{k: v for k, v in row.items() if k != "selection"}
|
|
85
|
+
for row in selections],
|
|
86
|
+
"page_selections": selections}
|
|
87
|
+
entry["supporting_host_result"] = supporting
|
|
88
|
+
# Preserve the adapter's original packed payload verbatim.
|
|
89
|
+
# The small second block is supporting-host metadata, not
|
|
90
|
+
# an alternate source page or a changed product schema.
|
|
91
|
+
result = ToolResult(
|
|
92
|
+
content=[*result.content, TextContent(type="text", text=json.dumps(
|
|
93
|
+
{"supporting_host_result": supporting}, separators=(",", ":")))],
|
|
94
|
+
structured_content=result.structured_content, meta=result.meta,
|
|
95
|
+
is_error=result.is_error)
|
|
96
|
+
return result
|
|
97
|
+
except Exception as exc:
|
|
98
|
+
entry["error_type"] = type(exc).__name__
|
|
99
|
+
raise
|
|
100
|
+
finally:
|
|
101
|
+
entry["elapsed_seconds"] = time.monotonic() - started
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class NativeEvidenceHost:
|
|
105
|
+
"""One adapter instance and native MCP listener with a finite lifetime.
|
|
106
|
+
|
|
107
|
+
Construct a fresh host per question. ``prepare`` uses the existing collector
|
|
108
|
+
discovery path; only literal pages delivered by actor source_read calls get
|
|
109
|
+
numeric citation selections. ``seal`` checks those same live receipts.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(self, adapter, source_root, *, max_actions=8, allowed_tools=None,
|
|
113
|
+
include_reference_search=True, preserve_adapter_instructions=False):
|
|
114
|
+
if isinstance(max_actions, bool) or not isinstance(max_actions, int) or max_actions < 2:
|
|
115
|
+
raise ValueError("max_actions must include a tool action and final answer")
|
|
116
|
+
self.adapter = adapter
|
|
117
|
+
self.source_root = Path(source_root).resolve()
|
|
118
|
+
self.max_actions = max_actions
|
|
119
|
+
self.allowed_tools = frozenset(SOURCE_TOOLS if allowed_tools is None else allowed_tools)
|
|
120
|
+
if not self.allowed_tools or any(not isinstance(name, str) or not name for name in self.allowed_tools):
|
|
121
|
+
raise ValueError("native gateway requires explicit non-empty tool names")
|
|
122
|
+
self.include_reference_search = include_reference_search
|
|
123
|
+
self.preserve_adapter_instructions = preserve_adapter_instructions
|
|
124
|
+
self.delivered_pages = DeliveredEvidencePages()
|
|
125
|
+
self.actor_actions = []
|
|
126
|
+
self.blocked_actor_tool_calls = 0
|
|
127
|
+
self._action_lock = asyncio.Lock()
|
|
128
|
+
self._sealed = False
|
|
129
|
+
self._client = None
|
|
130
|
+
self._server = None
|
|
131
|
+
self._server_task = None
|
|
132
|
+
self._socket = None
|
|
133
|
+
self._prepared = None
|
|
134
|
+
|
|
135
|
+
async def __aenter__(self):
|
|
136
|
+
try:
|
|
137
|
+
self._client = Client(self.adapter)
|
|
138
|
+
await self._client.__aenter__()
|
|
139
|
+
gateway = FastMCP(
|
|
140
|
+
"dandelion-reference-native",
|
|
141
|
+
instructions=(getattr(self.adapter, "instructions", None)
|
|
142
|
+
if self.preserve_adapter_instructions else None),
|
|
143
|
+
)
|
|
144
|
+
for name in sorted(self.allowed_tools):
|
|
145
|
+
tool = await self.adapter.get_tool(name)
|
|
146
|
+
if tool is None:
|
|
147
|
+
raise ValueError(f"supporting adapter lacks {name}")
|
|
148
|
+
gateway.add_tool(tool)
|
|
149
|
+
|
|
150
|
+
if self.include_reference_search:
|
|
151
|
+
@gateway.tool(name="reference_search")
|
|
152
|
+
async def search(terms: list[str], scope: str | None = None) -> str:
|
|
153
|
+
"""Existing bounded reference discovery. Matches are hints; read literal pages before citing."""
|
|
154
|
+
if (not 1 <= len(terms) <= 16 or any(not term.strip() or len(term) > 200 for term in terms)
|
|
155
|
+
or scope is not None and len(scope) > 4096):
|
|
156
|
+
raise ToolError("search requires 1..16 bounded terms and an optional bounded scope")
|
|
157
|
+
found = await reference_search(self._client, terms, scope, source_root=self.source_root)
|
|
158
|
+
packed = reference_answer_prompt(self._prepared["question"] if self._prepared else "", found)
|
|
159
|
+
return json.dumps({"prompt_sha256": packed["prompt_sha256"],
|
|
160
|
+
"evidence": packed["evidence"], "coverage": packed["coverage"]},
|
|
161
|
+
ensure_ascii=False, separators=(",", ":"))
|
|
162
|
+
|
|
163
|
+
gateway.add_middleware(_ActorTools(self))
|
|
164
|
+
self.gateway = gateway
|
|
165
|
+
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
166
|
+
self._socket.bind(("127.0.0.1", 0))
|
|
167
|
+
port = self._socket.getsockname()[1]
|
|
168
|
+
path = "/mcp/" + secrets.token_urlsafe(24)
|
|
169
|
+
self.url = f"http://127.0.0.1:{port}{path}"
|
|
170
|
+
# Actor tools are request/response only: all evidence/action state
|
|
171
|
+
# lives in this host instance, and the gateway sends no server
|
|
172
|
+
# notifications. Stateless HTTP avoids an idle session SSE stream
|
|
173
|
+
# that native clients otherwise keep open for the host lifetime.
|
|
174
|
+
app = gateway.http_app(path=path, transport="streamable-http", json_response=True,
|
|
175
|
+
stateless_http=True, host_origin_protection=True,
|
|
176
|
+
allowed_hosts=["127.0.0.1"])
|
|
177
|
+
self._server = uvicorn.Server(uvicorn.Config(
|
|
178
|
+
app, host="127.0.0.1", port=port, log_level="error", access_log=False,
|
|
179
|
+
timeout_graceful_shutdown=2, lifespan="on"))
|
|
180
|
+
self._server_task = asyncio.create_task(self._server.serve(sockets=[self._socket]))
|
|
181
|
+
async with asyncio.timeout(10):
|
|
182
|
+
while not self._server.started:
|
|
183
|
+
if self._server_task.done():
|
|
184
|
+
await self._server_task
|
|
185
|
+
raise RuntimeError("native MCP listener failed to start")
|
|
186
|
+
await asyncio.sleep(0.01)
|
|
187
|
+
return self
|
|
188
|
+
except BaseException:
|
|
189
|
+
await self.__aexit__(None, None, None)
|
|
190
|
+
raise
|
|
191
|
+
|
|
192
|
+
async def __aexit__(self, exc_type, exc, traceback):
|
|
193
|
+
if self._server is not None:
|
|
194
|
+
self._server.should_exit = True
|
|
195
|
+
if self._server_task is not None:
|
|
196
|
+
try:
|
|
197
|
+
await asyncio.wait_for(self._server_task, timeout=5)
|
|
198
|
+
except (TimeoutError, asyncio.CancelledError):
|
|
199
|
+
self._server_task.cancel()
|
|
200
|
+
await asyncio.gather(self._server_task, return_exceptions=True)
|
|
201
|
+
if self._socket is not None:
|
|
202
|
+
self._socket.close()
|
|
203
|
+
if self._client is not None:
|
|
204
|
+
await self._client.__aexit__(exc_type, exc, traceback)
|
|
205
|
+
self._client = None
|
|
206
|
+
|
|
207
|
+
async def prepare(self, question, terms, *, arm="memory_assisted"):
|
|
208
|
+
if self._prepared is not None or self._client is None:
|
|
209
|
+
raise RuntimeError("prepare requires a new live host")
|
|
210
|
+
if arm not in {"source_reference", "memory_assisted"}:
|
|
211
|
+
raise ValueError("unknown reference arm")
|
|
212
|
+
initial = await reference_search(self._client, terms, source_root=self.source_root)
|
|
213
|
+
memory = await _mcp_recall(self._client, question, terms) if arm == "memory_assisted" else None
|
|
214
|
+
packed = reference_answer_prompt(question, initial, memory)
|
|
215
|
+
self._prepared = {"question": question, "arm": arm, "packed": packed,
|
|
216
|
+
"initial": initial, "memory": memory, "terms": terms}
|
|
217
|
+
schemas = {tool.name: tool.to_mcp_tool().model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
218
|
+
for tool in await self.gateway.list_tools()}
|
|
219
|
+
if "evidence_ref" not in schemas["source_read"]["inputSchema"].get("properties", {}):
|
|
220
|
+
raise ValueError("native citation hydration requires evidence_ref_v1")
|
|
221
|
+
return {"schema": "dandelion.public30.native-session-open.v1", "question": question,
|
|
222
|
+
"arm": arm, "prompt": packed["prompt"], "prompt_sha256": packed["prompt_sha256"],
|
|
223
|
+
"coverage": packed["coverage"], "memory_status": packed["memory_status"],
|
|
224
|
+
"memory_hint_count": packed["memory_hint_count"], "mcp_tools": schemas,
|
|
225
|
+
"max_actor_tool_calls": self.max_actions - 1,
|
|
226
|
+
"citation_guidance": "Use only the advertised native MCP tools. Search and memory are hints. "
|
|
227
|
+
"Read source_read literal pages before citing. Cite only integer selections from "
|
|
228
|
+
"supporting_host_result.page_selections. The host resolves those selections and rechecks "
|
|
229
|
+
"source bytes and authorization before sealing. Do not copy result_id or hashes into prose. "
|
|
230
|
+
"Unknown, evicted, expired, or withdrawn selections remain unresolved. "
|
|
231
|
+
"Provenance is not semantic truth. NO_MATCH or incomplete search cannot establish absence. "
|
|
232
|
+
"Return the required structured final answer; do not emit JSONL actions.",
|
|
233
|
+
"final_schema": FINAL_SCHEMA, "oracle_included": False}
|
|
234
|
+
|
|
235
|
+
async def seal(self, final, *, case_id, output_path, questions_sha256=QUESTION_SHA,
|
|
236
|
+
terms_sha256=TERMS_SHA, all_case_ids=(), capture_metadata=None):
|
|
237
|
+
if self._prepared is None or self._client is None or self._sealed:
|
|
238
|
+
raise RuntimeError("seal requires one prepared live host")
|
|
239
|
+
if (not isinstance(final, dict) or set(final) != {"answer", "citations", "abstained"}
|
|
240
|
+
or not isinstance(final["answer"], str) or len(final["answer"]) > 8192
|
|
241
|
+
or not isinstance(final["abstained"], bool)
|
|
242
|
+
or not isinstance(final["citations"], list) or len(final["citations"]) > 32
|
|
243
|
+
or any(isinstance(item, bool) or not isinstance(item, int) or item < 1
|
|
244
|
+
for item in final["citations"])):
|
|
245
|
+
raise ValueError("final answer violates the frozen native final schema")
|
|
246
|
+
async with self._action_lock:
|
|
247
|
+
self._sealed = True
|
|
248
|
+
timings = []
|
|
249
|
+
deadline = OperationDeadline.start(NavigationLimits().elapsed_seconds)
|
|
250
|
+
citations, hydration = await _hydrate_selected_evidence_citations(
|
|
251
|
+
self._client, final["citations"], self.delivered_pages,
|
|
252
|
+
deadline=deadline.deadline, timings=timings)
|
|
253
|
+
prepared, packed = self._prepared, self._prepared["packed"]
|
|
254
|
+
initial_action = {"action": {"op": "search", "terms": prepared["terms"]},
|
|
255
|
+
"result": {"prompt_sha256": packed["prompt_sha256"],
|
|
256
|
+
"evidence": packed["evidence"]},
|
|
257
|
+
"source_actions": prepared["initial"]["actions"],
|
|
258
|
+
"memory_recall": ({"tool": "recall_v2", "arguments": {
|
|
259
|
+
"question": prepared["question"], "terms": prepared["terms"],
|
|
260
|
+
"kind": "any", "limit": 8}, "result": prepared["memory"]}
|
|
261
|
+
if prepared["memory"] is not None else None)}
|
|
262
|
+
capture = {"schema": "dandelion.public30.reference-session-capture.v1",
|
|
263
|
+
"case_id": case_id, "arm": prepared["arm"], "question": prepared["question"],
|
|
264
|
+
"questions_sha256": questions_sha256, "terms_sha256": terms_sha256,
|
|
265
|
+
"all_case_ids": list(all_case_ids), "public30_complete": False,
|
|
266
|
+
"capture_metadata": capture_metadata or {}, "prompt_sha256": packed["prompt_sha256"],
|
|
267
|
+
"prompt": packed["prompt"], "initial_coverage": packed["coverage"],
|
|
268
|
+
"actions": [initial_action, *self.actor_actions],
|
|
269
|
+
"blocked_actor_tool_calls": self.blocked_actor_tool_calls,
|
|
270
|
+
"answer": final["answer"], "citations": citations, "abstained": final["abstained"],
|
|
271
|
+
"submitted_citations": final["citations"], "citation_hydration": hydration,
|
|
272
|
+
"citation_provenance": "UNRESOLVED" if any(
|
|
273
|
+
item["status"] != "VERIFIED" for item in hydration) else "VERIFIED",
|
|
274
|
+
"tool_timings": timings, "evidence_ref_v1": True, "host_page_selection": True,
|
|
275
|
+
"latency_scope": "host MCP action/hydration durations; model walltime separately in metadata",
|
|
276
|
+
"native_transport": "MCP_STREAMABLE_HTTP", "oracle_included": False}
|
|
277
|
+
write(Path(output_path), capture)
|
|
278
|
+
return capture
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def check_native_event(event, *, allowed_tools=None):
|
|
282
|
+
"""Fail closed on native output that reports any unapproved I/O capability.
|
|
283
|
+
|
|
284
|
+
This is an empirical event boundary, not an operating-system sandbox. Tool
|
|
285
|
+
feature switches are also set on the invocation, with a blank actor cwd.
|
|
286
|
+
"""
|
|
287
|
+
if not isinstance(event, dict):
|
|
288
|
+
raise ValueError("native event is not an object")
|
|
289
|
+
event_type = event.get("type")
|
|
290
|
+
if event_type in {"thread.started", "turn.started", "turn.completed"}:
|
|
291
|
+
return
|
|
292
|
+
if event_type not in {"item.started", "item.updated", "item.completed"}:
|
|
293
|
+
raise ValueError(f"native event rejected: {event_type}")
|
|
294
|
+
item = event.get("item")
|
|
295
|
+
if not isinstance(item, dict):
|
|
296
|
+
raise ValueError("native item is not an object")
|
|
297
|
+
item_type = item.get("type")
|
|
298
|
+
if item_type in {"agent_message", "reasoning", "plan", "todo_list"}:
|
|
299
|
+
return
|
|
300
|
+
expected_tools = NATIVE_SOURCE_TOOLS if allowed_tools is None else frozenset(allowed_tools)
|
|
301
|
+
if (item_type == "mcp_tool_call" and item.get("server") == NATIVE_SERVER_NAME
|
|
302
|
+
and item.get("tool") in expected_tools):
|
|
303
|
+
return
|
|
304
|
+
raise ValueError(f"native item rejected: {item_type}")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def codex_actor_command(codex_command, *, model, reasoning_effort, actor_cwd,
|
|
308
|
+
schema_path, final_path, mcp_url, allowed_tools=None):
|
|
309
|
+
"""Build one invocation without reading or changing global Codex config."""
|
|
310
|
+
if not isinstance(model, str) or not model.strip():
|
|
311
|
+
raise ValueError("actor model must be explicitly supplied")
|
|
312
|
+
if reasoning_effort not in {"low", "medium", "high", "xhigh", "max", "ultra"}:
|
|
313
|
+
raise ValueError("unsupported reasoning effort")
|
|
314
|
+
command = [str(part) for part in codex_command]
|
|
315
|
+
if not command:
|
|
316
|
+
raise ValueError("native Codex command required")
|
|
317
|
+
command += ["exec", "--ignore-user-config", "--ignore-rules", "--ephemeral",
|
|
318
|
+
"--skip-git-repo-check", "--json", "--model", model,
|
|
319
|
+
"--cd", str(actor_cwd), "--output-schema", str(schema_path),
|
|
320
|
+
"--output-last-message", str(final_path)]
|
|
321
|
+
for feature in DISABLED_FEATURES:
|
|
322
|
+
command += ["--disable", feature]
|
|
323
|
+
enabled_tools = NATIVE_SOURCE_TOOLS if allowed_tools is None else frozenset(allowed_tools)
|
|
324
|
+
if not enabled_tools or any(not isinstance(name, str) or not name for name in enabled_tools):
|
|
325
|
+
raise ValueError("native actor requires an explicit non-empty MCP tool allowlist")
|
|
326
|
+
command += ["-c", 'web_search="disabled"',
|
|
327
|
+
"-c", "tool_output_token_limit=12000",
|
|
328
|
+
"-c", f"model_reasoning_effort={json.dumps(reasoning_effort)}",
|
|
329
|
+
"-c", f"mcp_servers.{NATIVE_SERVER_NAME}.url={json.dumps(mcp_url)}",
|
|
330
|
+
"-c", f"mcp_servers.{NATIVE_SERVER_NAME}.enabled_tools=" + json.dumps(sorted(enabled_tools)),
|
|
331
|
+
"-c", f"mcp_servers.{NATIVE_SERVER_NAME}.required=true",
|
|
332
|
+
"-c", f'mcp_servers.{NATIVE_SERVER_NAME}.default_tools_approval_mode="approve"',
|
|
333
|
+
"-c", f"mcp_servers.{NATIVE_SERVER_NAME}.startup_timeout_sec=20",
|
|
334
|
+
"-c", f"mcp_servers.{NATIVE_SERVER_NAME}.tool_timeout_sec=60",
|
|
335
|
+
"-"]
|
|
336
|
+
return command
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
async def run_native_actor(host, opening, *, codex_command, model, actor_cwd,
|
|
340
|
+
artifact_dir, reasoning_effort="high", timeout_seconds=300,
|
|
341
|
+
allowed_tools=None, final_schema=None):
|
|
342
|
+
"""Run exactly one native actor; retain raw output, never repair a final answer.
|
|
343
|
+
|
|
344
|
+
Callers authorize model execution separately and must supply a new empty cwd
|
|
345
|
+
and fresh artifact directory. A transport, side-channel event, or malformed
|
|
346
|
+
final failure raises, preserving the raw attempt for an invalid-slot receipt.
|
|
347
|
+
"""
|
|
348
|
+
if (isinstance(timeout_seconds, bool) or not isinstance(timeout_seconds, (int, float))
|
|
349
|
+
or not math.isfinite(timeout_seconds) or timeout_seconds <= 0):
|
|
350
|
+
raise ValueError("native actor requires a finite positive deadline")
|
|
351
|
+
actor_cwd, artifact_dir = Path(actor_cwd).resolve(), Path(artifact_dir).resolve()
|
|
352
|
+
if not actor_cwd.is_dir() or any(actor_cwd.iterdir()):
|
|
353
|
+
raise ValueError("native actor cwd must be a pre-created empty directory")
|
|
354
|
+
if not artifact_dir.is_dir():
|
|
355
|
+
raise ValueError("native actor artifact directory must already exist")
|
|
356
|
+
schema_path, final_path = artifact_dir / "final-schema.json", artifact_dir / "native-final.json"
|
|
357
|
+
schema = FINAL_SCHEMA if final_schema is None else final_schema
|
|
358
|
+
write(schema_path, schema)
|
|
359
|
+
opening_path = artifact_dir / "session-open.json"
|
|
360
|
+
opening_sha = write(opening_path, opening)
|
|
361
|
+
command = codex_actor_command(codex_command, model=model, reasoning_effort=reasoning_effort,
|
|
362
|
+
actor_cwd=actor_cwd, schema_path=schema_path,
|
|
363
|
+
final_path=final_path, mcp_url=host.url,
|
|
364
|
+
allowed_tools=allowed_tools)
|
|
365
|
+
template_path = artifact_dir / "native-invocation-template.json"
|
|
366
|
+
template_sha = write(template_path, codex_actor_command(
|
|
367
|
+
codex_command, model=model, reasoning_effort=reasoning_effort,
|
|
368
|
+
actor_cwd="<ACTOR_CWD>", schema_path="<SCHEMA_PATH>", final_path="<FINAL_PATH>",
|
|
369
|
+
mcp_url="<MCP_URL>", allowed_tools=allowed_tools))
|
|
370
|
+
# Config paths stay host-owned. The prompt receives only the prepared public
|
|
371
|
+
# opening and the actual native server/tool names, never a source root/path.
|
|
372
|
+
prompt = json.dumps(opening, ensure_ascii=False, separators=(",", ":"))
|
|
373
|
+
stdout_path, stderr_path = artifact_dir / "native-events.jsonl", artifact_dir / "native-stderr.log"
|
|
374
|
+
started = time.monotonic()
|
|
375
|
+
process = await asyncio.create_subprocess_exec(
|
|
376
|
+
*command, cwd=actor_cwd, stdin=asyncio.subprocess.PIPE,
|
|
377
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
|
|
378
|
+
limit=8 * 1024 * 1024)
|
|
379
|
+
events = []
|
|
380
|
+
|
|
381
|
+
async def output():
|
|
382
|
+
with stdout_path.open("xb") as stream:
|
|
383
|
+
while raw := await process.stdout.readline():
|
|
384
|
+
stream.write(raw)
|
|
385
|
+
stream.flush()
|
|
386
|
+
event = json.loads(raw.decode("utf-8"))
|
|
387
|
+
events.append(event)
|
|
388
|
+
check_native_event(event, allowed_tools=allowed_tools)
|
|
389
|
+
|
|
390
|
+
async def errors():
|
|
391
|
+
with stderr_path.open("xb") as stream:
|
|
392
|
+
while raw := await process.stderr.read(65536):
|
|
393
|
+
stream.write(raw)
|
|
394
|
+
stream.flush()
|
|
395
|
+
|
|
396
|
+
readers = [asyncio.create_task(output()), asyncio.create_task(errors())]
|
|
397
|
+
try:
|
|
398
|
+
process.stdin.write(prompt.encode("utf-8"))
|
|
399
|
+
await process.stdin.drain()
|
|
400
|
+
process.stdin.close()
|
|
401
|
+
async with asyncio.timeout(timeout_seconds):
|
|
402
|
+
await asyncio.gather(*readers, process.wait())
|
|
403
|
+
if process.returncode != 0:
|
|
404
|
+
raise RuntimeError(f"native actor exited {process.returncode}")
|
|
405
|
+
if not events or events[-1].get("type") != "turn.completed":
|
|
406
|
+
raise ValueError("native actor did not emit a completed turn")
|
|
407
|
+
final = json.loads(final_path.read_text(encoding="utf-8"))
|
|
408
|
+
return final, {"model": model, "reasoning_effort": reasoning_effort,
|
|
409
|
+
"native_transport": "MCP_STREAMABLE_HTTP",
|
|
410
|
+
"session_open_artifact": {"path": str(opening_path), "sha256": opening_sha},
|
|
411
|
+
"native_events_artifact": {"path": str(stdout_path),
|
|
412
|
+
"sha256": sha(stdout_path.read_bytes())},
|
|
413
|
+
"native_stderr_artifact": {"path": str(stderr_path),
|
|
414
|
+
"sha256": sha(stderr_path.read_bytes())},
|
|
415
|
+
"native_final_artifact": {"path": str(final_path),
|
|
416
|
+
"sha256": sha(final_path.read_bytes())},
|
|
417
|
+
"actor_elapsed_seconds": time.monotonic() - started,
|
|
418
|
+
"command_sha256": sha(json.dumps(command, ensure_ascii=False,
|
|
419
|
+
separators=(",", ":")).encode("utf-8")),
|
|
420
|
+
"native_invocation_template": {"path": str(template_path), "sha256": template_sha},
|
|
421
|
+
"side_channel_event_policy": "fail_closed_native_event_allowlist",
|
|
422
|
+
"isolation_claim": "invocation_features_and_observed_events_not_OS_sandbox",
|
|
423
|
+
"native_events_count": len(events)}
|
|
424
|
+
finally:
|
|
425
|
+
if process.returncode is None:
|
|
426
|
+
process.kill()
|
|
427
|
+
await process.wait()
|
|
428
|
+
for reader in readers:
|
|
429
|
+
if not reader.done():
|
|
430
|
+
reader.cancel()
|
|
431
|
+
await asyncio.gather(*readers, return_exceptions=True)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
async def native_reference_session(adapter, *, question, terms, source_root, case_id,
|
|
435
|
+
output_path, codex_command, model, actor_cwd,
|
|
436
|
+
artifact_dir, arm="memory_assisted", max_actions=8,
|
|
437
|
+
session_timeout=300, reasoning_effort="high",
|
|
438
|
+
questions_sha256=QUESTION_SHA, terms_sha256=TERMS_SHA,
|
|
439
|
+
all_case_ids=(), capture_metadata=None):
|
|
440
|
+
"""Native model execution followed by same-instance evidence finalization."""
|
|
441
|
+
async with NativeEvidenceHost(adapter, source_root, max_actions=max_actions) as host:
|
|
442
|
+
opening = await host.prepare(question, terms, arm=arm)
|
|
443
|
+
final, metadata = await run_native_actor(
|
|
444
|
+
host, opening, codex_command=codex_command, model=model, actor_cwd=actor_cwd,
|
|
445
|
+
artifact_dir=artifact_dir, reasoning_effort=reasoning_effort,
|
|
446
|
+
timeout_seconds=session_timeout)
|
|
447
|
+
return await host.seal(final, case_id=case_id, output_path=output_path,
|
|
448
|
+
questions_sha256=questions_sha256, terms_sha256=terms_sha256,
|
|
449
|
+
all_case_ids=all_case_ids,
|
|
450
|
+
capture_metadata={**(capture_metadata or {}), **metadata})
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
async def run_native_host_worker(packet_path, *, stdout_path, stderr_path, timeout_seconds=420):
|
|
454
|
+
"""Run one host-owned packet in one fresh Python process, preserving its logs.
|
|
455
|
+
|
|
456
|
+
The lexical owner stays in the caller. Each child owns exactly one MCP
|
|
457
|
+
listener, native actor and finalization, so dependency shutdown globals
|
|
458
|
+
cannot affect the next question's transport.
|
|
459
|
+
"""
|
|
460
|
+
packet_path = Path(packet_path).resolve()
|
|
461
|
+
packet = json.loads(packet_path.read_text(encoding="utf-8"))
|
|
462
|
+
with Path(stdout_path).open("xb") as stdout, Path(stderr_path).open("xb") as stderr:
|
|
463
|
+
process = await asyncio.create_subprocess_exec(
|
|
464
|
+
sys.executable, "-m", "benchmarks.native_codex_host", "--packet", str(packet_path),
|
|
465
|
+
cwd=Path(__file__).resolve().parents[1], stdin=asyncio.subprocess.DEVNULL,
|
|
466
|
+
stdout=stdout, stderr=stderr)
|
|
467
|
+
try:
|
|
468
|
+
await asyncio.wait_for(process.wait(), timeout=timeout_seconds)
|
|
469
|
+
finally:
|
|
470
|
+
if process.returncode is None:
|
|
471
|
+
# The outer deadline is longer than the unchanged actor deadline.
|
|
472
|
+
# If the host itself hangs, terminate only its own process tree.
|
|
473
|
+
if os.name == "nt":
|
|
474
|
+
cleanup = await asyncio.create_subprocess_exec(
|
|
475
|
+
"taskkill", "/PID", str(process.pid), "/T", "/F",
|
|
476
|
+
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL)
|
|
477
|
+
await asyncio.wait_for(cleanup.wait(), timeout=10)
|
|
478
|
+
else:
|
|
479
|
+
process.kill()
|
|
480
|
+
await asyncio.wait_for(process.wait(), timeout=10)
|
|
481
|
+
if process.returncode != 0:
|
|
482
|
+
raise RuntimeError(f"native host worker exited {process.returncode}; see host stderr artifact")
|
|
483
|
+
capture = json.loads(Path(packet["session"]["output_path"]).read_text(encoding="utf-8"))
|
|
484
|
+
if capture.get("case_id") != packet["session"]["case_id"]:
|
|
485
|
+
raise ValueError("native host worker returned the wrong case identity")
|
|
486
|
+
return capture
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def host_worker_main():
|
|
490
|
+
"""Host-only process entrypoint; the native actor never receives this packet."""
|
|
491
|
+
parser = argparse.ArgumentParser(description="Run one isolated native MCP host session")
|
|
492
|
+
parser.add_argument("--packet", type=Path, required=True)
|
|
493
|
+
args = parser.parse_args()
|
|
494
|
+
packet = json.loads(args.packet.read_text(encoding="utf-8"))
|
|
495
|
+
if set(packet) != {"owner_workspace", "source_root", "session"}:
|
|
496
|
+
raise ValueError("host packet requires owner_workspace, source_root and session")
|
|
497
|
+
from dandelion.agent_adapter import bind_context, create_mcp
|
|
498
|
+
context = bind_context(memory_path=Path(packet["owner_workspace"]),
|
|
499
|
+
source_root=Path(packet["source_root"]),
|
|
500
|
+
lineage_root=Path(packet["source_root"]))
|
|
501
|
+
adapter = create_mcp(context, recall_v2_preview=True, evidence_ref_v1=True)
|
|
502
|
+
session = dict(packet["session"])
|
|
503
|
+
session["capture_metadata"] = {**session.get("capture_metadata", {}),
|
|
504
|
+
"host_execution": "one_python_process_per_case",
|
|
505
|
+
"host_worker_pid": os.getpid()}
|
|
506
|
+
capture = asyncio.run(native_reference_session(adapter, source_root=context.source_root, **session))
|
|
507
|
+
print(json.dumps({"status": "SEALED", "case_id": capture["case_id"],
|
|
508
|
+
"capture_sha256": sha(Path(session["output_path"]).read_bytes())},
|
|
509
|
+
separators=(",", ":")), flush=True)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
if __name__ == "__main__":
|
|
513
|
+
host_worker_main()
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Public subprocess acceptance for canonical scan -> owner-held dense recall."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main() -> int:
|
|
13
|
+
repository = Path(__file__).resolve().parents[1]
|
|
14
|
+
run_root = repository / "scratch" / "owner-dense-acceptance-final2-20260924"
|
|
15
|
+
workspace, source = run_root / "owner", run_root / "source"
|
|
16
|
+
workspace.mkdir(parents=True, exist_ok=True)
|
|
17
|
+
source.mkdir(parents=True, exist_ok=True)
|
|
18
|
+
(source / "package.json").write_text(
|
|
19
|
+
'{"name":"payments-agent","version":"1.0.0"}', encoding="utf-8"
|
|
20
|
+
)
|
|
21
|
+
(source / "README.md").write_text(
|
|
22
|
+
"# Payment worker\n\n## Retry decision\nThe payment worker uses a durable retry queue to survive restarts.\n",
|
|
23
|
+
encoding="utf-8",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
def call(operation: str, payload: dict | None = None) -> dict:
|
|
27
|
+
command = [sys.executable, "-m", "dandelion.cli", "memory", operation,
|
|
28
|
+
"--path", str(workspace), "--data", json.dumps(payload or {})]
|
|
29
|
+
completed = subprocess.run(command, cwd=repository, check=True, capture_output=True, text=True)
|
|
30
|
+
return json.loads(completed.stdout)
|
|
31
|
+
|
|
32
|
+
def start_owner() -> subprocess.Popen[str]:
|
|
33
|
+
process = subprocess.Popen(
|
|
34
|
+
[sys.executable, "-m", "dandelion.cli", "memory-owner", "start", "--path", str(workspace)],
|
|
35
|
+
cwd=repository, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
|
36
|
+
)
|
|
37
|
+
descriptor = workspace / ".dandelion" / "memory_owner.json"
|
|
38
|
+
for _ in range(240):
|
|
39
|
+
if descriptor.exists():
|
|
40
|
+
return process
|
|
41
|
+
if process.poll() is not None:
|
|
42
|
+
raise RuntimeError(process.stderr.read() if process.stderr else "owner exited")
|
|
43
|
+
time.sleep(0.25)
|
|
44
|
+
process.kill()
|
|
45
|
+
raise TimeoutError("owner did not publish its descriptor")
|
|
46
|
+
|
|
47
|
+
trace: dict = {"kind": "protocol_acceptance", "real_embedding": True, "steps": []}
|
|
48
|
+
owner = start_owner()
|
|
49
|
+
try:
|
|
50
|
+
preview = call("scan-bootstrap", {"source_workspace": str(source)})
|
|
51
|
+
applied = call("scan-bootstrap", {
|
|
52
|
+
"source_workspace": str(source), "apply": True, "confirm_apply": True,
|
|
53
|
+
})
|
|
54
|
+
pending = call("index-status")
|
|
55
|
+
consumed = call("consume-dense", {"limit": 1000})
|
|
56
|
+
recalled = call("dense-recall", {
|
|
57
|
+
"query": "How does the payment worker recover after a restart?", "limit": 3,
|
|
58
|
+
})
|
|
59
|
+
trace["steps"].extend([
|
|
60
|
+
{"preview": preview}, {"apply": applied}, {"pending": pending},
|
|
61
|
+
{"consume": consumed}, {"recall_before_restart": recalled},
|
|
62
|
+
])
|
|
63
|
+
if recalled.get("status") != "SUPPORTED" or not any(
|
|
64
|
+
"durable retry queue" in item.get("template", "") for item in recalled.get("results", [])
|
|
65
|
+
):
|
|
66
|
+
raise AssertionError("real dense recall did not return canonical memory")
|
|
67
|
+
call_result = call("rebuild-dense")
|
|
68
|
+
trace["steps"].append({"rebuild": call_result})
|
|
69
|
+
call("status")
|
|
70
|
+
call_stop = subprocess.run(
|
|
71
|
+
[sys.executable, "-m", "dandelion.cli", "memory-owner", "stop", "--path", str(workspace)],
|
|
72
|
+
cwd=repository, check=True, capture_output=True, text=True,
|
|
73
|
+
)
|
|
74
|
+
trace["steps"].append({"stop": json.loads(call_stop.stdout)})
|
|
75
|
+
owner.wait(timeout=20)
|
|
76
|
+
|
|
77
|
+
owner = start_owner()
|
|
78
|
+
after_restart = call("dense-recall", {
|
|
79
|
+
"query": "durable recovery queue", "limit": 3,
|
|
80
|
+
})
|
|
81
|
+
trace["steps"].append({"recall_after_restart": after_restart})
|
|
82
|
+
if after_restart.get("status") != "SUPPORTED" or not any(
|
|
83
|
+
"durable retry queue" in item.get("template", "") for item in after_restart.get("results", [])
|
|
84
|
+
):
|
|
85
|
+
raise AssertionError("dense recall failed after owner restart")
|
|
86
|
+
|
|
87
|
+
call("set-fact", {"key": "worker.retry_limit", "value": "3", "source": "acceptance"})
|
|
88
|
+
remembered = call("remember", {
|
|
89
|
+
"content": "worker live retry limit {{ref:worker.retry_limit}}",
|
|
90
|
+
"domain": "payments-agent.runtime", "source": "acceptance",
|
|
91
|
+
})
|
|
92
|
+
indexed = call("consume-dense", {"limit": 1000})
|
|
93
|
+
call("set-fact", {"key": "worker.retry_limit", "value": "5", "source": "acceptance-update"})
|
|
94
|
+
updated = call("dense-recall", {
|
|
95
|
+
"query": "worker retry limit", "domain": "payments-agent.runtime", "limit": 2,
|
|
96
|
+
})
|
|
97
|
+
if not any("retry limit 5" in item.get("text", "") for item in updated.get("results", [])):
|
|
98
|
+
raise AssertionError("dense hit did not hydrate updated canonical fact")
|
|
99
|
+
forgotten = call("forget", {"memory_id": remembered["memory_id"]})
|
|
100
|
+
deleted = call("consume-dense", {"limit": 1000})
|
|
101
|
+
after_forget = call("dense-recall", {
|
|
102
|
+
"query": "worker retry limit", "domain": "payments-agent.runtime", "limit": 2,
|
|
103
|
+
})
|
|
104
|
+
if after_forget.get("status") != "UNKNOWN":
|
|
105
|
+
raise AssertionError("forgotten canonical memory remained a dense result")
|
|
106
|
+
trace["steps"].extend([
|
|
107
|
+
{"remember_update_fixture": remembered}, {"index_update": indexed},
|
|
108
|
+
{"live_fact_update_recall": updated}, {"forget": forgotten},
|
|
109
|
+
{"index_delete": deleted}, {"recall_after_forget": after_forget},
|
|
110
|
+
])
|
|
111
|
+
finally:
|
|
112
|
+
if owner.poll() is None:
|
|
113
|
+
subprocess.run(
|
|
114
|
+
[sys.executable, "-m", "dandelion.cli", "memory-owner", "stop", "--path", str(workspace)],
|
|
115
|
+
cwd=repository, capture_output=True, text=True, timeout=10,
|
|
116
|
+
)
|
|
117
|
+
owner.wait(timeout=20)
|
|
118
|
+
|
|
119
|
+
output = repository / "scratch" / "MEMORY_OWNER_DENSE_ACCEPTANCE_20260924.json"
|
|
120
|
+
output.write_text(json.dumps(trace, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
121
|
+
print(output)
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
if __name__ == "__main__":
|
|
126
|
+
raise SystemExit(main())
|