langchain-agentx-python 2.5.1__py3-none-any.whl → 2.5.3__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.
- langchain_agentx/__init__.py +1 -1
- langchain_agentx/loop/context/query_source.py +2 -0
- langchain_agentx/loop/exit/query_source.py +2 -0
- langchain_agentx/memory/memdir/age.py +12 -3
- langchain_agentx/memory/memdir/consolidate.py +281 -0
- langchain_agentx/memory/memdir/memory_saved.py +6 -2
- langchain_agentx/memory/memdir/prompts/__init__.py +10 -4
- langchain_agentx/memory/memdir/prompts/consolidate.py +109 -0
- langchain_agentx/memory/memdir/tool_scope.py +11 -5
- langchain_agentx/memory/memdir/write_gate.py +257 -0
- langchain_agentx/tool_runtime/adapter.py +10 -0
- langchain_agentx/tool_runtime/models.py +2 -0
- langchain_agentx/tools/edit/tool.py +41 -4
- langchain_agentx/tools/workflow/backend.py +17 -3
- langchain_agentx/tools/workflow/observe/__init__.py +3 -1
- langchain_agentx/tools/workflow/observe/host_panel.py +12 -0
- langchain_agentx/tools/workflow/observe/nesting_link.py +61 -0
- langchain_agentx/tools/workflow/observe/task_bridge.py +80 -6
- langchain_agentx/tools/workflow/tool.py +46 -0
- langchain_agentx/tools/write/tool.py +29 -2
- langchain_agentx/workspace/config.py +3 -1
- langchain_agentx/workspace/project_memory_layout.py +26 -1
- langchain_agentx/workspace/resolver.py +4 -0
- {langchain_agentx_python-2.5.1.dist-info → langchain_agentx_python-2.5.3.dist-info}/METADATA +1 -1
- {langchain_agentx_python-2.5.1.dist-info → langchain_agentx_python-2.5.3.dist-info}/RECORD +28 -24
- {langchain_agentx_python-2.5.1.dist-info → langchain_agentx_python-2.5.3.dist-info}/LICENSE +0 -0
- {langchain_agentx_python-2.5.1.dist-info → langchain_agentx_python-2.5.3.dist-info}/WHEEL +0 -0
- {langchain_agentx_python-2.5.1.dist-info → langchain_agentx_python-2.5.3.dist-info}/top_level.txt +0 -0
langchain_agentx/__init__.py
CHANGED
|
@@ -33,6 +33,7 @@ EmitterRoute = Literal["main", "sidechain", "drop"]
|
|
|
33
33
|
_BACKGROUND_COMPACTION_SKIP: Final[FrozenSet[str]] = frozenset(
|
|
34
34
|
{
|
|
35
35
|
QuerySource.EXTRACT_MEMORIES,
|
|
36
|
+
QuerySource.CONSOLIDATE_MEMORIES,
|
|
36
37
|
QuerySource.SESSION_MEMORY,
|
|
37
38
|
QuerySource.COMPACT,
|
|
38
39
|
QuerySource.AGENT_SUMMARY,
|
|
@@ -43,6 +44,7 @@ _BACKGROUND_COMPACTION_SKIP: Final[FrozenSet[str]] = frozenset(
|
|
|
43
44
|
_TOKEN_BLOCKING_SKIP: Final[FrozenSet[str]] = frozenset(
|
|
44
45
|
{
|
|
45
46
|
QuerySource.EXTRACT_MEMORIES,
|
|
47
|
+
QuerySource.CONSOLIDATE_MEMORIES,
|
|
46
48
|
QuerySource.SESSION_MEMORY,
|
|
47
49
|
QuerySource.COMPACT,
|
|
48
50
|
}
|
|
@@ -21,6 +21,7 @@ class QuerySource:
|
|
|
21
21
|
|
|
22
22
|
MAIN_THREAD: Final[str] = "main_thread"
|
|
23
23
|
EXTRACT_MEMORIES: Final[str] = "extract_memories"
|
|
24
|
+
CONSOLIDATE_MEMORIES: Final[str] = "consolidate_memories"
|
|
24
25
|
SESSION_MEMORY: Final[str] = "session_memory"
|
|
25
26
|
COMPACT: Final[str] = "compact"
|
|
26
27
|
AGENT_SUMMARY: Final[str] = "agent_summary"
|
|
@@ -33,6 +34,7 @@ class QuerySource:
|
|
|
33
34
|
{
|
|
34
35
|
cls.MAIN_THREAD,
|
|
35
36
|
cls.EXTRACT_MEMORIES,
|
|
37
|
+
cls.CONSOLIDATE_MEMORIES,
|
|
36
38
|
cls.SESSION_MEMORY,
|
|
37
39
|
cls.COMPACT,
|
|
38
40
|
cls.AGENT_SUMMARY,
|
|
@@ -2,13 +2,15 @@
|
|
|
2
2
|
memory/memdir/age.py — Layer 2 记忆新鲜度文本。
|
|
3
3
|
|
|
4
4
|
职责:
|
|
5
|
-
基于文件更新时间计算 age 文本,为 memory manifest
|
|
5
|
+
基于文件更新时间计算 age 文本,为 memory manifest 提供可读提示;
|
|
6
|
+
d>1 时追加 CC memoryFreshnessText 后半句(point-in-time / verify)。
|
|
6
7
|
|
|
7
8
|
链路位置:
|
|
8
9
|
scan/build_memory_lines 在组装输出时读取本模块结果。
|
|
9
10
|
|
|
10
11
|
当前裁剪范围:
|
|
11
|
-
仅基于 mtime
|
|
12
|
+
仅基于 mtime;定案 A 保留 updated… 前缀(不抄 CC fresh 空串)。
|
|
13
|
+
对照:CC src/memdir/memoryAge.ts memoryFreshnessText。
|
|
12
14
|
"""
|
|
13
15
|
|
|
14
16
|
from __future__ import annotations
|
|
@@ -16,6 +18,13 @@ from __future__ import annotations
|
|
|
16
18
|
from datetime import datetime
|
|
17
19
|
from pathlib import Path
|
|
18
20
|
|
|
21
|
+
# 对齐 CC memoryAge.ts:37-40(定案 A:接在 updated… 之后,而非替换前缀)
|
|
22
|
+
_CC_STALENESS_CAVEAT = (
|
|
23
|
+
"Memories are point-in-time observations, not live state — "
|
|
24
|
+
"claims about code behavior or file:line citations may be outdated. "
|
|
25
|
+
"Verify against current code before asserting as fact."
|
|
26
|
+
)
|
|
27
|
+
|
|
19
28
|
|
|
20
29
|
def memory_age_days(path: Path, now: datetime | None = None) -> int:
|
|
21
30
|
snapshot = now or datetime.now()
|
|
@@ -30,7 +39,7 @@ def memory_freshness_text(path: Path, now: datetime | None = None) -> str:
|
|
|
30
39
|
return "updated today"
|
|
31
40
|
if days == 1:
|
|
32
41
|
return "updated yesterday"
|
|
33
|
-
return f"updated {days} days ago"
|
|
42
|
+
return f"updated {days} days ago. {_CC_STALENESS_CAVEAT}"
|
|
34
43
|
|
|
35
44
|
|
|
36
45
|
__all__ = ["memory_age_days", "memory_freshness_text"]
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""
|
|
2
|
+
memory/memdir/consolidate.py — 父生命周期 scratch→L2 单点归纳(SDK 独有)
|
|
3
|
+
|
|
4
|
+
职责:
|
|
5
|
+
ParentLifecycleMemoryConsolidate.run:读 scratch + L2 manifest,fork 合并写谱系 L2;
|
|
6
|
+
不经 ``_can_extract`` / 不套 hasMemoryWrites;正式路径禁止伪对齐 trigger_from_state。
|
|
7
|
+
|
|
8
|
+
链路位置:
|
|
9
|
+
宿主(new_agents / Graph 收口)显式 await run → ForkedAgentRunner
|
|
10
|
+
(query_source=CONSOLIDATE_MEMORIES)→ WriteGate(经 Write/Edit)→
|
|
11
|
+
MEMORY_SAVED → drain。
|
|
12
|
+
|
|
13
|
+
当前裁剪范围:
|
|
14
|
+
空 scratch → skipped_reason;无 forked_runner 且无 executor → skipped_reason;
|
|
15
|
+
drain 默认委托 drain_pending_extraction(清理同会话 in-flight extract);
|
|
16
|
+
``lineage_id`` 须与 ``workspace_cfg.memory_lineage_id``(若已设)sanitize 一致。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
from collections.abc import Awaitable, Callable
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from langchain_agentx.loop.exit.query_source import QuerySource
|
|
28
|
+
from langchain_agentx.workspace import ResolvedAgentStateConfig
|
|
29
|
+
from langchain_agentx.workspace.project_key import ProjectKeySanitizer
|
|
30
|
+
|
|
31
|
+
from .memory_saved import MemorySavedCallback, create_memory_saved_notification
|
|
32
|
+
from .prompts import build_consolidate_from_scratch_prompt
|
|
33
|
+
from .scan import format_memory_manifest, scan_memory_files
|
|
34
|
+
from .tool_scope import ToolPermissionScoper
|
|
35
|
+
from .written_paths import extract_topic_memory_paths
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
DrainFn = Callable[[], Awaitable[bool]]
|
|
40
|
+
ConsolidateExecutor = Callable[
|
|
41
|
+
...,
|
|
42
|
+
Awaitable["ConsolidateResult"],
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True, slots=True)
|
|
47
|
+
class ConsolidateResult:
|
|
48
|
+
"""父归纳一轮结果。"""
|
|
49
|
+
|
|
50
|
+
ok: bool
|
|
51
|
+
written_paths: tuple[str, ...] = ()
|
|
52
|
+
skipped_reason: str | None = None
|
|
53
|
+
error: str | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def list_scratch_files(scratch_dir: Path) -> list[Path]:
|
|
57
|
+
"""列出 scratch 下普通文件(稳定排序)。"""
|
|
58
|
+
root = Path(scratch_dir)
|
|
59
|
+
if not root.is_dir():
|
|
60
|
+
return []
|
|
61
|
+
files = [p for p in root.rglob("*") if p.is_file()]
|
|
62
|
+
return sorted(files, key=lambda p: str(p.relative_to(root)).lower())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def format_scratch_listing(scratch_dir: Path) -> str:
|
|
66
|
+
root = Path(scratch_dir)
|
|
67
|
+
files = list_scratch_files(root)
|
|
68
|
+
if not files:
|
|
69
|
+
return "(empty)"
|
|
70
|
+
lines: list[str] = []
|
|
71
|
+
for path in files:
|
|
72
|
+
rel = path.relative_to(root).as_posix()
|
|
73
|
+
try:
|
|
74
|
+
size = path.stat().st_size
|
|
75
|
+
except OSError:
|
|
76
|
+
size = -1
|
|
77
|
+
lines.append(f"- `{rel}` ({size} bytes)")
|
|
78
|
+
return "\n".join(lines)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _assert_lineage_matches_cfg(
|
|
82
|
+
workspace_cfg: ResolvedAgentStateConfig,
|
|
83
|
+
lineage_id: str,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""cfg 已绑 lineage 时,run 入参须 sanitize 一致(防 prompt/落盘谱系分叉)。"""
|
|
86
|
+
cfg_raw = getattr(workspace_cfg, "memory_lineage_id", None)
|
|
87
|
+
if cfg_raw is None or not str(cfg_raw).strip():
|
|
88
|
+
return
|
|
89
|
+
sanitizer = ProjectKeySanitizer()
|
|
90
|
+
expected = sanitizer.sanitize(str(cfg_raw).strip())
|
|
91
|
+
got = sanitizer.sanitize(str(lineage_id).strip())
|
|
92
|
+
if expected != got:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"lineage_id does not match workspace_cfg.memory_lineage_id "
|
|
95
|
+
f"(cfg={cfg_raw!r} → {expected!r}, arg={lineage_id!r} → {got!r})"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ParentLifecycleMemoryConsolidate:
|
|
100
|
+
"""父生命周期单点归纳:scratch → 谱系 L2(独立入口,非 extract)。"""
|
|
101
|
+
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
*,
|
|
105
|
+
forked_runner: Any | None = None,
|
|
106
|
+
tool_scoper: ToolPermissionScoper | None = None,
|
|
107
|
+
drain: DrainFn | None = None,
|
|
108
|
+
executor: ConsolidateExecutor | None = None,
|
|
109
|
+
on_memory_saved: MemorySavedCallback | None = None,
|
|
110
|
+
) -> None:
|
|
111
|
+
self._forked_runner = forked_runner
|
|
112
|
+
self._tool_scoper = tool_scoper or ToolPermissionScoper()
|
|
113
|
+
self._drain = drain
|
|
114
|
+
self._executor = executor
|
|
115
|
+
self._on_memory_saved = on_memory_saved
|
|
116
|
+
self._memory_saved_ui_pending: list[dict[str, Any]] = []
|
|
117
|
+
|
|
118
|
+
async def run(
|
|
119
|
+
self,
|
|
120
|
+
*,
|
|
121
|
+
workspace_cfg: ResolvedAgentStateConfig,
|
|
122
|
+
scratch_dir: Path,
|
|
123
|
+
run_id: str,
|
|
124
|
+
lineage_id: str,
|
|
125
|
+
optional_summary: str | None = None,
|
|
126
|
+
parent_state: dict[str, Any] | None = None,
|
|
127
|
+
session_id: str | None = None,
|
|
128
|
+
) -> ConsolidateResult:
|
|
129
|
+
"""
|
|
130
|
+
执行一轮 consolidate。
|
|
131
|
+
|
|
132
|
+
不调用 ``MemoryExtractionCoordinator.trigger_from_state``;
|
|
133
|
+
不经 ``_can_extract`` interactive 白名单;不套 has_memory_writes_since。
|
|
134
|
+
"""
|
|
135
|
+
_assert_lineage_matches_cfg(workspace_cfg, lineage_id)
|
|
136
|
+
scratch = Path(scratch_dir)
|
|
137
|
+
files = list_scratch_files(scratch)
|
|
138
|
+
if not files:
|
|
139
|
+
result = ConsolidateResult(ok=True, skipped_reason="empty_scratch")
|
|
140
|
+
await self._await_drain()
|
|
141
|
+
return result
|
|
142
|
+
|
|
143
|
+
if self._executor is not None:
|
|
144
|
+
result = await self._executor(
|
|
145
|
+
workspace_cfg=workspace_cfg,
|
|
146
|
+
scratch_dir=scratch,
|
|
147
|
+
run_id=run_id,
|
|
148
|
+
lineage_id=lineage_id,
|
|
149
|
+
optional_summary=optional_summary,
|
|
150
|
+
parent_state=parent_state,
|
|
151
|
+
)
|
|
152
|
+
self._notify_memory_saved(result.written_paths, session_id=session_id)
|
|
153
|
+
await self._await_drain()
|
|
154
|
+
return result
|
|
155
|
+
|
|
156
|
+
if self._forked_runner is None:
|
|
157
|
+
result = ConsolidateResult(ok=True, skipped_reason="no_forked_runner")
|
|
158
|
+
await self._await_drain()
|
|
159
|
+
return result
|
|
160
|
+
|
|
161
|
+
result = await self._run_forked(
|
|
162
|
+
workspace_cfg=workspace_cfg,
|
|
163
|
+
scratch_dir=scratch,
|
|
164
|
+
run_id=run_id,
|
|
165
|
+
lineage_id=lineage_id,
|
|
166
|
+
optional_summary=optional_summary,
|
|
167
|
+
parent_state=parent_state,
|
|
168
|
+
session_id=session_id,
|
|
169
|
+
)
|
|
170
|
+
await self._await_drain()
|
|
171
|
+
return result
|
|
172
|
+
|
|
173
|
+
def drain_memory_saved_ui_events(self) -> list[dict[str, Any]]:
|
|
174
|
+
"""宿主收口后取出 MEMORY_SAVED UI 事件(对齐 extract coordinator)。"""
|
|
175
|
+
pending = list(self._memory_saved_ui_pending)
|
|
176
|
+
self._memory_saved_ui_pending.clear()
|
|
177
|
+
return pending
|
|
178
|
+
|
|
179
|
+
def _notify_memory_saved(
|
|
180
|
+
self,
|
|
181
|
+
written_paths: tuple[str, ...] | list[str],
|
|
182
|
+
*,
|
|
183
|
+
session_id: str | None,
|
|
184
|
+
) -> None:
|
|
185
|
+
paths = [str(p) for p in written_paths if str(p).strip()]
|
|
186
|
+
if not paths:
|
|
187
|
+
return
|
|
188
|
+
notification = create_memory_saved_notification(
|
|
189
|
+
paths,
|
|
190
|
+
session_id=session_id,
|
|
191
|
+
query_source=QuerySource.CONSOLIDATE_MEMORIES,
|
|
192
|
+
)
|
|
193
|
+
if hasattr(notification, "to_ui_event_item"):
|
|
194
|
+
self._memory_saved_ui_pending.append(notification.to_ui_event_item())
|
|
195
|
+
if self._on_memory_saved is None:
|
|
196
|
+
logger.info(
|
|
197
|
+
"memory consolidate saved %s file(s) session=%s paths=%s",
|
|
198
|
+
notification.count,
|
|
199
|
+
session_id,
|
|
200
|
+
paths,
|
|
201
|
+
)
|
|
202
|
+
return
|
|
203
|
+
self._on_memory_saved(notification)
|
|
204
|
+
|
|
205
|
+
async def _await_drain(self) -> None:
|
|
206
|
+
if self._drain is not None:
|
|
207
|
+
await self._drain()
|
|
208
|
+
return
|
|
209
|
+
from .extractor import drain_pending_extraction
|
|
210
|
+
|
|
211
|
+
await drain_pending_extraction()
|
|
212
|
+
|
|
213
|
+
async def _run_forked(
|
|
214
|
+
self,
|
|
215
|
+
*,
|
|
216
|
+
workspace_cfg: ResolvedAgentStateConfig,
|
|
217
|
+
scratch_dir: Path,
|
|
218
|
+
run_id: str,
|
|
219
|
+
lineage_id: str,
|
|
220
|
+
optional_summary: str | None,
|
|
221
|
+
parent_state: dict[str, Any] | None,
|
|
222
|
+
session_id: str | None,
|
|
223
|
+
) -> ConsolidateResult:
|
|
224
|
+
from langchain_agentx.loop.subagent.forked_runner import ForkedRunParams
|
|
225
|
+
from langchain_core.messages import HumanMessage
|
|
226
|
+
|
|
227
|
+
memory_dir = workspace_cfg.memory_dir
|
|
228
|
+
headers = scan_memory_files(memory_dir)
|
|
229
|
+
manifest = format_memory_manifest(headers)
|
|
230
|
+
listing = format_scratch_listing(scratch_dir)
|
|
231
|
+
user_prompt = build_consolidate_from_scratch_prompt(
|
|
232
|
+
manifest,
|
|
233
|
+
listing,
|
|
234
|
+
scratch_dir=str(scratch_dir),
|
|
235
|
+
lineage_id=lineage_id,
|
|
236
|
+
run_id=run_id,
|
|
237
|
+
optional_summary=optional_summary,
|
|
238
|
+
)
|
|
239
|
+
can_use = self._tool_scoper.scope_for(
|
|
240
|
+
QuerySource.CONSOLIDATE_MEMORIES,
|
|
241
|
+
workspace_cfg=workspace_cfg,
|
|
242
|
+
)
|
|
243
|
+
state = dict(parent_state or {})
|
|
244
|
+
state.setdefault("messages", [])
|
|
245
|
+
params = ForkedRunParams(
|
|
246
|
+
prompt_messages=[HumanMessage(content=user_prompt)],
|
|
247
|
+
parent_state=state,
|
|
248
|
+
query_source=QuerySource.CONSOLIDATE_MEMORIES,
|
|
249
|
+
fork_label=QuerySource.CONSOLIDATE_MEMORIES,
|
|
250
|
+
can_use_tool=can_use,
|
|
251
|
+
skip_transcript=True,
|
|
252
|
+
max_turns=5,
|
|
253
|
+
)
|
|
254
|
+
fork_result = await self._forked_runner.run_forked(params)
|
|
255
|
+
if not fork_result.ok:
|
|
256
|
+
logger.warning(
|
|
257
|
+
"consolidate fork failed run_id=%s lineage=%s error=%s",
|
|
258
|
+
run_id,
|
|
259
|
+
lineage_id,
|
|
260
|
+
fork_result.error,
|
|
261
|
+
)
|
|
262
|
+
return ConsolidateResult(
|
|
263
|
+
ok=False,
|
|
264
|
+
error=str(fork_result.error or "fork_failed"),
|
|
265
|
+
)
|
|
266
|
+
topic_paths = extract_topic_memory_paths(
|
|
267
|
+
messages=list(fork_result.messages or []),
|
|
268
|
+
execution_trace=fork_result.execution_trace,
|
|
269
|
+
)
|
|
270
|
+
written = tuple(str(p) for p in topic_paths)
|
|
271
|
+
self._notify_memory_saved(written, session_id=session_id)
|
|
272
|
+
return ConsolidateResult(ok=True, written_paths=written)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
__all__ = [
|
|
276
|
+
"ConsolidateResult",
|
|
277
|
+
"ParentLifecycleMemoryConsolidate",
|
|
278
|
+
"build_consolidate_from_scratch_prompt",
|
|
279
|
+
"format_scratch_listing",
|
|
280
|
+
"list_scratch_files",
|
|
281
|
+
]
|
|
@@ -32,6 +32,7 @@ class MemorySavedNotification:
|
|
|
32
32
|
subtype: str = "memory_saved"
|
|
33
33
|
verb: str = "Saved"
|
|
34
34
|
session_id: str | None = None
|
|
35
|
+
query_source: str = QuerySource.EXTRACT_MEMORIES
|
|
35
36
|
|
|
36
37
|
@property
|
|
37
38
|
def count(self) -> int:
|
|
@@ -52,6 +53,7 @@ class MemorySavedNotification:
|
|
|
52
53
|
"count": self.count,
|
|
53
54
|
"display_hint": self.display_hint,
|
|
54
55
|
"session_id": self.session_id,
|
|
56
|
+
"query_source": self.query_source,
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
def to_agent_event_data(self) -> dict[str, Any]:
|
|
@@ -63,7 +65,7 @@ class MemorySavedNotification:
|
|
|
63
65
|
"count": self.count,
|
|
64
66
|
"display_hint": self.display_hint,
|
|
65
67
|
"session_id": self.session_id,
|
|
66
|
-
"query_source":
|
|
68
|
+
"query_source": self.query_source,
|
|
67
69
|
"skip_transcript": True,
|
|
68
70
|
}
|
|
69
71
|
|
|
@@ -75,14 +77,16 @@ class MemorySavedNotification:
|
|
|
75
77
|
|
|
76
78
|
|
|
77
79
|
def create_memory_saved_notification(
|
|
78
|
-
written_paths: list[str],
|
|
80
|
+
written_paths: list[str] | tuple[str, ...],
|
|
79
81
|
*,
|
|
80
82
|
session_id: str | None = None,
|
|
83
|
+
query_source: str | None = None,
|
|
81
84
|
) -> MemorySavedNotification:
|
|
82
85
|
"""构建 memory_saved 通知;路径应已过滤 MEMORY.md。"""
|
|
83
86
|
return MemorySavedNotification(
|
|
84
87
|
written_paths=tuple(written_paths),
|
|
85
88
|
session_id=session_id,
|
|
89
|
+
query_source=query_source or QuerySource.EXTRACT_MEMORIES,
|
|
86
90
|
)
|
|
87
91
|
|
|
88
92
|
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"""
|
|
2
|
-
prompts —
|
|
2
|
+
prompts — 后台记忆 fork 专用提示词(CC extract + SDK consolidate)。
|
|
3
3
|
|
|
4
4
|
职责:
|
|
5
|
-
build_extract_auto_only_prompt() 对齐 CC extractMemories/prompts.ts:buildExtractAutoOnlyPrompt
|
|
5
|
+
build_extract_auto_only_prompt() 对齐 CC extractMemories/prompts.ts:buildExtractAutoOnlyPrompt;
|
|
6
|
+
build_consolidate_from_scratch_prompt() 为 SDK 独有父生命周期归纳(非 messages opener)。
|
|
6
7
|
|
|
7
8
|
链路位置:
|
|
8
|
-
MemoryExtractionCoordinator._run_forked_extraction() → ForkedAgentRunner
|
|
9
|
+
MemoryExtractionCoordinator._run_forked_extraction() → ForkedAgentRunner;
|
|
10
|
+
ParentLifecycleMemoryConsolidate.run → ForkedAgentRunner。
|
|
9
11
|
|
|
10
12
|
CC 原文 → SDK 改动 → 原因:
|
|
11
13
|
- opener 工具名使用 SDK 常量(Read/Grep/Glob/Bash/Edit/Write),与 CC FILE_*_TOOL_NAME 等价。
|
|
@@ -22,6 +24,7 @@ from ._shared import (
|
|
|
22
24
|
WHAT_NOT_TO_SAVE_SECTION,
|
|
23
25
|
build_cc_fork_how_to_save_section,
|
|
24
26
|
)
|
|
27
|
+
from .consolidate import build_consolidate_from_scratch_prompt
|
|
25
28
|
|
|
26
29
|
# SDK 工具名(对齐 CC FILE_READ_TOOL_NAME 等)
|
|
27
30
|
_READ = "Read"
|
|
@@ -96,4 +99,7 @@ def build_extract_auto_only_prompt(
|
|
|
96
99
|
)
|
|
97
100
|
|
|
98
101
|
|
|
99
|
-
__all__ = [
|
|
102
|
+
__all__ = [
|
|
103
|
+
"build_consolidate_from_scratch_prompt",
|
|
104
|
+
"build_extract_auto_only_prompt",
|
|
105
|
+
]
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""
|
|
2
|
+
prompts/consolidate.py — 父生命周期 scratch→L2 归纳提示词(SDK 独有)
|
|
3
|
+
|
|
4
|
+
职责:
|
|
5
|
+
build_consolidate_from_scratch_prompt:合并工人 scratch 为谱系 L2 规则;
|
|
6
|
+
复用 CC how-to-save / 类型段语义,禁止复用 extract 的 messages-only opener。
|
|
7
|
+
|
|
8
|
+
链路位置:
|
|
9
|
+
ParentLifecycleMemoryConsolidate.run → ForkedAgentRunner。
|
|
10
|
+
|
|
11
|
+
当前裁剪范围:
|
|
12
|
+
允许 Read scratch + L2;Write/Edit 仅 L2;不依赖「最近 N 条 messages」。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from ._shared import (
|
|
18
|
+
TYPES_SECTION_INDIVIDUAL,
|
|
19
|
+
WHAT_NOT_TO_SAVE_SECTION,
|
|
20
|
+
build_cc_fork_how_to_save_section,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_READ = "Read"
|
|
24
|
+
_GREP = "Grep"
|
|
25
|
+
_GLOB = "Glob"
|
|
26
|
+
_BASH = "Bash"
|
|
27
|
+
_EDIT = "Edit"
|
|
28
|
+
_WRITE = "Write"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_consolidate_from_scratch_prompt(
|
|
32
|
+
existing_memories: str,
|
|
33
|
+
scratch_listing: str,
|
|
34
|
+
*,
|
|
35
|
+
scratch_dir: str,
|
|
36
|
+
lineage_id: str,
|
|
37
|
+
run_id: str,
|
|
38
|
+
optional_summary: str | None = None,
|
|
39
|
+
) -> str:
|
|
40
|
+
"""从 scratch 归纳进 L2;语义借鉴 CC 主题合并,入口非 messages extract。"""
|
|
41
|
+
manifest = ""
|
|
42
|
+
if existing_memories.strip():
|
|
43
|
+
manifest = (
|
|
44
|
+
f"\n\n## Existing memory files (lineage L2)\n\n{existing_memories}\n\n"
|
|
45
|
+
"Check this list before writing — update an existing file rather than creating a duplicate."
|
|
46
|
+
)
|
|
47
|
+
summary_block = ""
|
|
48
|
+
if optional_summary and optional_summary.strip():
|
|
49
|
+
summary_block = (
|
|
50
|
+
"\n\n## Optional run summary\n\n"
|
|
51
|
+
f"{optional_summary.strip()}\n"
|
|
52
|
+
)
|
|
53
|
+
listing = scratch_listing.strip() or "(empty)"
|
|
54
|
+
opener = "\n".join(
|
|
55
|
+
[
|
|
56
|
+
(
|
|
57
|
+
"You are now acting as the parent-lifecycle memory consolidate subagent. "
|
|
58
|
+
f"Lineage `{lineage_id}` run `{run_id}` has finished. "
|
|
59
|
+
"Your job is to merge worker scratch notes into durable lineage L2 memories "
|
|
60
|
+
"as concise rules (not per-run append-only logs)."
|
|
61
|
+
),
|
|
62
|
+
"",
|
|
63
|
+
(
|
|
64
|
+
f"Available tools: {_READ}, {_GREP}, {_GLOB}, read-only {_BASH} "
|
|
65
|
+
f"(ls/find/cat/stat/wc/head/tail and similar), and {_EDIT}/{_WRITE} for paths inside "
|
|
66
|
+
f"the memory directory only. {_BASH} rm is not permitted. All other tools — MCP, Agent, "
|
|
67
|
+
f"write-capable {_BASH}, etc — will be denied."
|
|
68
|
+
),
|
|
69
|
+
"",
|
|
70
|
+
(
|
|
71
|
+
f"You MAY {_READ} files under the scratch directory and under the L2 memory directory. "
|
|
72
|
+
f"You MUST NOT write outside the memory directory. Scratch path: `{scratch_dir}`."
|
|
73
|
+
),
|
|
74
|
+
"",
|
|
75
|
+
(
|
|
76
|
+
f"You have a limited turn budget. {_EDIT} requires a prior {_READ} of the same file, "
|
|
77
|
+
f"so the efficient strategy is: turn 1 — issue all {_READ} calls in parallel for every "
|
|
78
|
+
f"scratch note and every L2 topic you might update; turn 2 — issue all {_WRITE}/{_EDIT} "
|
|
79
|
+
"calls in parallel. Do not interleave reads and writes across multiple turns."
|
|
80
|
+
),
|
|
81
|
+
"",
|
|
82
|
+
(
|
|
83
|
+
"Merge by topic into durable rules: one rule + exceptions + id list when appropriate. "
|
|
84
|
+
"Do not create `Update (Nth…)` style chronological dumps. "
|
|
85
|
+
"If scratch content is already covered by an existing memory, update that file; "
|
|
86
|
+
"otherwise create a new topic file and index it."
|
|
87
|
+
)
|
|
88
|
+
+ manifest
|
|
89
|
+
+ summary_block,
|
|
90
|
+
"",
|
|
91
|
+
"## Scratch files for this run",
|
|
92
|
+
"",
|
|
93
|
+
listing,
|
|
94
|
+
]
|
|
95
|
+
)
|
|
96
|
+
how_to_save = build_cc_fork_how_to_save_section(skip_index=False)
|
|
97
|
+
return "\n".join(
|
|
98
|
+
[
|
|
99
|
+
opener,
|
|
100
|
+
"",
|
|
101
|
+
TYPES_SECTION_INDIVIDUAL,
|
|
102
|
+
WHAT_NOT_TO_SAVE_SECTION,
|
|
103
|
+
"",
|
|
104
|
+
how_to_save,
|
|
105
|
+
]
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
__all__ = ["build_consolidate_from_scratch_prompt"]
|
|
@@ -2,13 +2,16 @@
|
|
|
2
2
|
tool_scope.py — 后台 fork 任务工具权限收敛
|
|
3
3
|
|
|
4
4
|
职责:
|
|
5
|
-
按 query_source 提供 can_use_tool
|
|
5
|
+
按 query_source 提供 can_use_tool 白名单回调
|
|
6
|
+
(extract_memories / consolidate_memories 等)。
|
|
6
7
|
|
|
7
8
|
链路位置:
|
|
8
|
-
ForkedAgentRunner / MemoryExtractionCoordinator
|
|
9
|
+
ForkedAgentRunner / MemoryExtractionCoordinator /
|
|
10
|
+
ParentLifecycleMemoryConsolidate → ToolPermissionScoper.scope_for()。
|
|
9
11
|
|
|
10
12
|
当前裁剪范围:
|
|
11
|
-
|
|
13
|
+
extract_memories + consolidate_memories(写面同 L2;Read 放开);
|
|
14
|
+
session_memory / compact 在后续 Phase 接入。
|
|
12
15
|
"""
|
|
13
16
|
|
|
14
17
|
from __future__ import annotations
|
|
@@ -67,7 +70,10 @@ class ToolPermissionScoper:
|
|
|
67
70
|
memory_dir: Path | None = None,
|
|
68
71
|
) -> Callable[[str, dict[str, Any]], bool]:
|
|
69
72
|
normalized = QuerySource.normalize(query_source)
|
|
70
|
-
if normalized
|
|
73
|
+
if normalized in (
|
|
74
|
+
QuerySource.EXTRACT_MEMORIES,
|
|
75
|
+
QuerySource.CONSOLIDATE_MEMORIES,
|
|
76
|
+
):
|
|
71
77
|
if workspace_cfg is not None:
|
|
72
78
|
layout = workspace_cfg.project_memory_layout
|
|
73
79
|
return create_auto_mem_can_use_tool(
|
|
@@ -76,7 +82,7 @@ class ToolPermissionScoper:
|
|
|
76
82
|
)
|
|
77
83
|
if memory_dir is None:
|
|
78
84
|
raise ValueError(
|
|
79
|
-
"memory_dir or workspace_cfg required for
|
|
85
|
+
f"memory_dir or workspace_cfg required for {normalized} scope"
|
|
80
86
|
)
|
|
81
87
|
return create_auto_mem_can_use_tool(memory_dir)
|
|
82
88
|
raise ValueError(f"no tool scope defined for query_source={normalized!r}")
|