mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-09-12 23:01:15 +00:00
### 1. Agent Wrapper(统一 Agent 后端抽象) - **`base_agent_wrapper.py`**:`reply()` 返回值从 `tuple[str, Any]` 改为 `dict`(含 `session_id` / `last_message` / `result` / 可选 `structured_output`);`reply_stream()` 改为产出统一的 `StreamChunk`。废弃 `add_tools()`,改为 `add_job_tools(names: list[str])`(按名解析 BaseJob)与 `add_skills()`;新增 `_resolve_job_tools()`、`_merged_kwargs()`、`_chunk()` 辅助方法及 `project_path` / `project_skills_root` 属性。 - **`as_agent_wrapper.py`(AgentScope 后端)**: - 会话持久化重写:`session_path` 落地到 `<vault>/<session_dir>/agentscope/`,`_load_state` 支持 `resume` / `session_id` / `fork_session`,并做 UUID 校验(`_validate_session_id`);`_cleanup_expired_sessions` 按天数清理过期会话。 - 新增内置工具集(`BypassAnalysisBash` + Edit/Glob/Grep/Read/Write),`BypassAnalysisBash` 绕过 AgentScope 自带 Bash 静态分析以让 permission_mode 生效;`_resolve_skills()` 把配置的 skill 暴露给后端,`_load_tool_env()` 注入项目 `.env`。 - `_event_to_chunk()` 把 20+ 种 AgentScope 事件(Reply/Text/Thinking/Data/ToolCall/ToolResult/ModelCall/ExceedMaxIters)归一化为 `StreamChunk`。 - **`cc_agent_wrapper.py`(Claude Code SDK 后端,+551 行)**: - 新增 `_CcFileSessionStore`:基于 vault 的文件型会话存储,实现 append(按 uuid 去重)/ load / list / delete / list_subkeys,并对路径做 `_safe_parts` + `resolve()` 防越界校验。 - `_build_options()`:统一构建 `ClaudeAgentOptions`,处理 skills、disallowed_tools(默认禁 `WebSearch`)、`.env` 注入、Claude Code 的 API 凭据解析(`_claude_code_api_env`,多级 base_url/api_key 回退)、`CLAUDE_CONFIG_DIR` 设置、skill 目录软链接(`_ensure_claude_skill_dir`)。 - `_raw_event_to_chunk()` / `_message_content_to_chunks()`:把 Anthropic 流式事件(message_start/delta/stop、content_block_*)与 SDK 消息块(AssistantMessage/UserMessage/ResultMessage/RateLimitEvent)转换为统一 `StreamChunk`;跟踪 block_id/block_type/tool_call_name 做关联;处理尾部 `"success"` 误报异常的吞掉逻辑。 ### 2. 统一流式协议(StreamChunk / ChunkEnum) - **`stream_chunk.py`**:`StreamChunk` 扩展为承载 AS + CC 双后端完整信息的统一结构,新增 `session_id` / `block_id` / `tool_call_id` / `tool_call_name` / `media_type` / `input_tokens` / `output_tokens` 等字段,纯文本流仍保持轻量。 - **`chunk_enum.py`**:补全生命周期标记 `REPLY_START` / `REPLY_END`,并文档化两套后端事件 → ChunkEnum 的映射。 ### 3. Index 模块重构(变化批次化 + dispatch) - 新增 `_change_batch.py`:`coalesce_changes()` 把同路径多次事件折叠为最终状态(结合 path 存在性判定),`bucket_changes()` 按 watchfiles.Change 分桶。 - 新增 `init_changes.py`(`InitChangesStep`):一次性扫描,对比 file_store / file_catalog 已索引节点计算 added/modified/deleted,写入 `context["changes"]` 后 dispatch。 - 新增 `update_changes.py`:抽象基类 `ChangeApplyStep` 统一 added/modified/deleted 处理与错误收集;`UpdateCatalogStep`(写 file_catalog)、`UpdateIndexStep`(写 file_store,含按后缀解析 chunker)。 - **`watch_changes.py`**:改用 `dispatch_step_specs`(基类提供的 `dispatch_steps()`),每批先 `coalesce_changes` 再 dispatch;默认参数调整(debounce 5000ms / step 1000ms / poll 5000ms)并暴露常量。 - 删除旧步骤:`clear_and_scan` / `foreach_dispatch` / `scan_changes` / `update_catalog`(旧) / `update_index`(旧);`clear_store.py` 取代 clear_and_scan。 ### 4. Evolve / Dream 模块(拆分为多步 pipeline) - 删除旧的单体 `auto_dream.py` / `dream.py` / `dream.yaml`,新增 `dream/` 子包,按 5 个步骤组织: - **`extract.py`**:扫描当日 day-index + daily 笔记,对比 file_catalog 找出 changed/deleted,调用 LLM 全局抽取 `units`(procedure/personal/wiki 三桶)与 `topics`,路径与桶做清洗/路由。 - **`integrate.py`**:逐个 unit 调用 LLM 写入 digest,结构化输出 `IntegrateOutcome`(CREATE/CORROBORATE/REFINE/CORRECT),失败 unit/路径收集回写。 - **`topics.py`**:写 `daily/<date>/interests.yaml`,结合当天已有 + 近 N 天做去重(`normalize_topic`),可走 LLM 或纯规则去重两条路径。 - **`proactive.py`**:读取当日 `interests.yaml`,作为主动推荐话题的入口。 - **`finish.py`**:把变更路径落盘到 dream file_catalog(checkpoint),渲染最终汇总摘要。 - 新增 `schema.py`(`DreamState` 等跨步骤共享状态与结构化输出模型)与 `utils.py`(状态存取、扫描打包、YAML 读写、结构化回复解析等公共函数)。 - `evolve/__init__.py` 导出全部新 step。 ### 5. auto_memory / auto_resource(适配新 Agent API) - **`auto_memory.py`**:会话路径迁移到 `<session_dir>/dialog/<session_id>.jsonl`;改用 `job_tools`;新增 `source_conversation` frontmatter 反向链接(`_session_link`);执行后刷新 day 索引(`refresh_day_index`),并对 session_id 做合法性校验。 - **`auto_resource.py`**:资源改用「同名 daily note」方案(`_compute_note_stem` 取文件 stem);批量处理 `changes: list[dict]`(`_handle_change` 逐项处理,返回逐项结果摘要);agent 会话 id 用稳定的 `uuid5`;同样刷新 day 索引。 ### 6. BaseStep 基类增强 - 新增 `dispatch_steps` / `dispatch_step_specs` 机制:`_resolve_dispatch_step()` 支持字符串或 dict 形式的 step spec,`dispatch_steps()` 复用当前 context 调用下游 step。 - 新增 `config_value()`:按 key 取 app config,缺失时回退 `ApplicationConfig` 默认值。 - 小幅清理:`language` 初始化、`copy()`、`Ref.__init__` 签名精简。 ### 7. Components 改动 - **`file_store/local_file_store.py`**:持久化改用 zstd 压缩(`.jsonl.zst`,通过新 `utils/jsonl_zst.py`);upsert 时先删除旧 chunk 的 keyword 文档;embedding 复用改为 `(text, embedding)` 键控,要求文本一致才复用;新增 `_matches_search_filter()` 对 vector/keyword 搜索做 path/path_prefix/metadata 的统一后过滤。 - **`keyword_index/bm25_index.py`**:索引文件名加入组件名 + tokenizer 指纹(sha256 前 12 位),快照/恢复时校验指纹防配置漂移;空索引 dump 时删除文件,加载失败抛错而非静默。 - **`file_chunker/markdown_file_chunker.py`**:弃用 `python-frontmatter`,改用内置 YAML 解析(非法 YAML 不阻断正文索引),并修正因 frontmatter 占用行号导致的 AST 行号偏移(`line_offset`)。 - **`cron_job.py`**:大幅简化(-187 行),由原来「dispatch 外部 job/step + 多种调度模式」改为「在自身 steps 上跑 cron 表达式」;`Application` 启动顺序随之调整为 base > stream > background > cron。 - 其余小调整:service(base/http/mcp)、file_graph、file_catalog、as_llm、as_embedding、tokenizer、prompt_handler、base_component 的签名/接口微调。 ### 8. Application 生命周期 - `_start()` 启动顺序明确为 components → base → stream → background → cron,启动失败会触发 `_close()` 回滚并 re-raise(不再吞异常)。 - 启动时创建 `session_dir` 目录;新增 `update_component()`(按类型/名就地更新已存在组件,不存在则报错)。 ### 9. File IO / 路径安全 - **`_path.py`**:`resolve_path` 增加 vault 越界防护(`is_relative_to` 校验),禁止 `.` / `..` 路径分量,支持 `allow_empty`。 - **`read.py`**:大文件(超过 `MAX_FILE_READ_BYTES`)走按行读取 `read_file_lines_safe`,避免一次性载入内存。 - **`_file_io.py` / `_daily_index.py` / `_path.py`** 等支持函数补齐(如 `refresh_day_index`、`read_file_lines_safe`)。 - **`env_utils.py`**:新增 `parse_env_file()`,`load_env()` 返回加载到的键值、支持 `override`、对无路径调用做幂等缓存。 ### 10. Config - `ApplicationConfig` 新增 `session_dir`(默认 `reme_session`)。 - `config_parser.py`:环境变量展开后做类型转换(`_convert_value`)、dot-notation 与 key=value 参数校验更严格、配置文件路径支持相对 `_CONFIG_DIR` 查找、根非 dict 报错。 - `default.yaml`:作业编排改用 `init_changes_step` + `dispatch_steps`(index/resource/digest 三个 watch loop 与 reindex);新增 `auto_dream`(4 步)、`proactive` 作业,移除旧 `dream`;file_catalog 增配 `resource` / `digest` / `dream` 实例;LLM 默认值与 Claude Code 凭据配置调整(tool_result_limit 50000、thinking_enable=false 等)。 ### 11. 其它 - 新增 `steps/common/add.py`(`AddStep` 算术 demo)、`channel/__init__.py` 与 common `__init__` 导出整理。 - 新增 4 篇文档:`docs4/auto_dream_logic_and_step_refactor.md`、`docs4/watch_loop_step_refactor_plan.md`、`docs4/todo.md`,以及 `reme_design.md` 更新。 **
649 lines
25 KiB
Python
649 lines
25 KiB
Python
"""Tests for daily-aware steps: daily_create / daily_list / daily_reindex.
|
|
|
|
Sets up a small ``daily/`` tree with mixed dates and exercises note
|
|
provision / listing / index-rebuild operations. Body authoring and
|
|
frontmatter mutations are generic CRUD (covered in test_crud_steps
|
|
and test_property_steps).
|
|
|
|
A daily note is the single file ``daily/<YYYY-MM-DD>/<session_id>.md``
|
|
(no folder, no sibling materials). ``daily_create`` validates the
|
|
session_id, writes an empty-body note with default
|
|
``{name: session_id}`` frontmatter when the file is absent, and
|
|
refreshes the day index. When the file already exists it is a no-op
|
|
write (``created=False``) — the body is filled in afterwards via
|
|
``file_write`` / ``file_edit`` / ``frontmatter_update`` or a native
|
|
editor.
|
|
|
|
``daily_list`` is a **pure read** — it never refreshes the index.
|
|
Use ``daily_reindex`` explicitly when the index page needs to be
|
|
rebuilt (e.g. after batch flows or a ``frontmatter_update`` that
|
|
touched ``name`` / ``description``).
|
|
|
|
Note: status / lifecycle / scope / role / source are no longer
|
|
core-reserved fields — the reme schema reserves only name /
|
|
description (both optional). Opinionated state machines belong
|
|
to the plugin layer.
|
|
"""
|
|
|
|
# pylint: disable=protected-access
|
|
|
|
import asyncio
|
|
import os
|
|
import tempfile
|
|
from datetime import date as _date
|
|
from pathlib import Path
|
|
|
|
import warnings
|
|
|
|
from reme4.components.file_store import LocalFileStore
|
|
from reme4.steps.file_io import (
|
|
daily_create as daily_create_step,
|
|
daily_list as daily_list_step,
|
|
daily_reindex as daily_reindex_step,
|
|
)
|
|
|
|
warnings.filterwarnings("ignore", category=DeprecationWarning, module="jieba")
|
|
warnings.filterwarnings("ignore", category=DeprecationWarning, module="pkg_resources")
|
|
|
|
|
|
class temp_chdir:
|
|
"""Context manager: chdir into a path on enter, restore on exit."""
|
|
|
|
def __init__(self, path):
|
|
self.path = path
|
|
self.old = None
|
|
|
|
def __enter__(self):
|
|
self.old = os.getcwd()
|
|
os.chdir(self.path)
|
|
return self
|
|
|
|
def __exit__(self, *_):
|
|
os.chdir(self.old)
|
|
|
|
|
|
def _today() -> str:
|
|
return _date.today().isoformat()
|
|
|
|
|
|
async def _make_store_with_dailies(entries: list[tuple[str, str, str]]) -> LocalFileStore:
|
|
"""Seed the vault with daily notes.
|
|
|
|
entries: list of (date, session_id, body). Each tuple creates
|
|
``daily/<date>/<session_id>.md`` with a minimal ``name``-only
|
|
frontmatter — no opinionated status / lifecycle axes.
|
|
"""
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
for day, session_id, body in entries:
|
|
day_dir = Path.cwd() / "daily" / day
|
|
day_dir.mkdir(parents=True, exist_ok=True)
|
|
text = f"---\nname: {session_id}\n---\n{body}\n"
|
|
(day_dir / f"{session_id}.md").write_text(text, encoding="utf-8")
|
|
return store
|
|
|
|
|
|
def _metadata(step) -> dict:
|
|
return step.context.response.metadata
|
|
|
|
|
|
async def _seed_note(date: str, session_id: str, name: str = "", description: str = "") -> None:
|
|
"""Write ``daily/<date>/<session_id>.md`` with optional frontmatter."""
|
|
day_dir = Path.cwd() / "daily" / date
|
|
day_dir.mkdir(parents=True, exist_ok=True)
|
|
fm_lines = [f"name: {name or session_id}"]
|
|
if description:
|
|
fm_lines.append(f"description: {description}")
|
|
text = "---\n" + "\n".join(fm_lines) + "\n---\nbody\n"
|
|
(day_dir / f"{session_id}.md").write_text(text, encoding="utf-8")
|
|
|
|
|
|
# -- daily_list_step ----------------------------------------------------------
|
|
|
|
|
|
def test_daily_list_default_date_is_today():
|
|
"""No ``date`` arg ⇒ falls back to today; only today's notes returned."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
(_today(), "today-a", "today a"),
|
|
(_today(), "today-b", "today b"),
|
|
("2026-05-17", "yesterday", "y"),
|
|
],
|
|
)
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step()
|
|
payload = _metadata(step)
|
|
assert payload["date"] == _today()
|
|
assert payload["count"] == 2
|
|
answer = step.context.response.answer
|
|
assert f"daily/{_today()}/today-a.md" in answer
|
|
assert f"daily/{_today()}/today-b.md" in answer
|
|
await store.close()
|
|
print("✓ test_daily_list_default_date_is_today passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_list_filters_by_date():
|
|
"""Explicit ``date`` scopes to that day's folder."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
("2026-05-18", "a", "a"),
|
|
("2026-05-17", "b", "b"),
|
|
],
|
|
)
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
payload = _metadata(step)
|
|
assert payload["date"] == "2026-05-18"
|
|
assert payload["count"] == 1
|
|
answer = step.context.response.answer
|
|
assert "daily/2026-05-18/a.md" in answer
|
|
await store.close()
|
|
print("✓ test_daily_list_filters_by_date passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_list_returns_path_session_id_metadata():
|
|
"""Each note row exposes path / session_id / metadata (full frontmatter dict)."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
await _seed_note(
|
|
"2026-05-18",
|
|
"alpha",
|
|
name="Alpha Project",
|
|
description="JWT auth migration",
|
|
)
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
payload = _metadata(step)
|
|
assert payload["count"] == 1
|
|
answer = step.context.response.answer
|
|
assert "daily/2026-05-18/alpha.md" in answer
|
|
assert "Alpha Project" in answer
|
|
assert "JWT auth migration" in answer
|
|
await store.close()
|
|
print("✓ test_daily_list_returns_path_session_id_metadata passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_list_ignores_subdirectories():
|
|
"""Subdirectories under the day folder are skipped — only direct .md files count."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
("2026-05-18", "main", "main body"),
|
|
],
|
|
)
|
|
stray = Path(tmp) / "daily" / "2026-05-18" / "old-folder"
|
|
stray.mkdir(parents=True, exist_ok=True)
|
|
(stray / "old-folder.md").write_text(
|
|
"---\nname: old\n---\nstale\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
payload = _metadata(step)
|
|
assert payload["count"] == 1
|
|
answer = step.context.response.answer
|
|
assert "daily/2026-05-18/main.md" in answer
|
|
await store.close()
|
|
print("✓ test_daily_list_ignores_subdirectories passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_list_empty_when_no_daily_dir():
|
|
"""No daily/ folder ⇒ empty notes list, no crash."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
payload = _metadata(step)
|
|
assert payload == {"date": "2026-05-18", "count": 0}
|
|
await store.close()
|
|
print("✓ test_daily_list_empty_when_no_daily_dir passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_list_does_not_refresh_index():
|
|
"""daily_list is a pure read — it must NOT touch daily/<date>.md."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
("2026-05-18", "alpha", "a"),
|
|
("2026-05-18", "beta", "b"),
|
|
],
|
|
)
|
|
index_path = Path(tmp) / "daily" / "2026-05-18.md"
|
|
assert not index_path.exists()
|
|
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
|
|
assert not index_path.exists(), "daily_list must not refresh the day index — use daily_reindex"
|
|
await store.close()
|
|
print("✓ test_daily_list_does_not_refresh_index passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_list_response_shape():
|
|
"""daily_list returns only {date, count}."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
("2026-05-18", "alpha", "a"),
|
|
],
|
|
)
|
|
step = daily_list_step.DailyListStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
payload = _metadata(step)
|
|
assert set(payload.keys()) == {"date", "count"}
|
|
await store.close()
|
|
print("✓ test_daily_list_response_shape passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
# -- daily_create_step --------------------------------------------------------
|
|
|
|
|
|
def test_daily_create_provisions_note_and_refreshes_index():
|
|
"""Fresh session_id ⇒ empty-body note with ``{name: session_id}`` + day index refreshed."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies([])
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
await step(session_id="kickoff", date="2026-05-18")
|
|
payload = _metadata(step)
|
|
|
|
assert step.context.response.success is True
|
|
assert payload["created"] is True
|
|
assert payload["date"] == "2026-05-18"
|
|
assert payload["session_id"] == "kickoff"
|
|
assert payload["path"] == "daily/2026-05-18/kickoff.md"
|
|
|
|
note = Path(tmp) / "daily" / "2026-05-18" / "kickoff.md"
|
|
text = note.read_text(encoding="utf-8")
|
|
assert "name: kickoff" in text
|
|
# Body is empty — file is frontmatter + trailing newline.
|
|
assert text.rstrip().endswith("---")
|
|
|
|
index = Path(tmp) / "daily" / "2026-05-18.md"
|
|
assert index.is_file()
|
|
assert "[[daily/2026-05-18/kickoff.md]]" in index.read_text(encoding="utf-8")
|
|
await store.close()
|
|
print("✓ test_daily_create_provisions_note_and_refreshes_index passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_create_is_idempotent_on_existing():
|
|
"""File exists ⇒ ``created=False``; the file body is NOT touched; index still refreshes."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[("2026-05-18", "ongoing", "old body")],
|
|
)
|
|
file_path = Path(tmp) / "daily" / "2026-05-18" / "ongoing.md"
|
|
before = file_path.read_text(encoding="utf-8")
|
|
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
await step(session_id="ongoing", date="2026-05-18")
|
|
payload = _metadata(step)
|
|
|
|
assert step.context.response.success is True
|
|
assert payload["created"] is False
|
|
assert payload["path"] == "daily/2026-05-18/ongoing.md"
|
|
assert file_path.read_text(encoding="utf-8") == before
|
|
assert payload["index"]["path"] == "daily/2026-05-18.md"
|
|
await store.close()
|
|
print("✓ test_daily_create_is_idempotent_on_existing passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_create_default_date_is_today():
|
|
"""Omitted ``date`` ⇒ today's folder."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies([])
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
await step(session_id="today-task")
|
|
payload = _metadata(step)
|
|
assert payload["date"] == _today()
|
|
assert payload["path"] == f"daily/{_today()}/today-task.md"
|
|
assert payload["created"] is True
|
|
await store.close()
|
|
print("✓ test_daily_create_default_date_is_today passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_create_default_frontmatter_uses_session_id_as_name():
|
|
"""The provisioned note's frontmatter is ``{name: session_id, description: ''}`` (no body)."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies([])
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
await step(session_id="auth-refactor", date="2026-05-18")
|
|
|
|
note = Path(tmp) / "daily" / "2026-05-18" / "auth-refactor.md"
|
|
text = note.read_text(encoding="utf-8")
|
|
assert "name: auth-refactor" in text
|
|
assert "description:" in text
|
|
await store.close()
|
|
print("✓ test_daily_create_default_frontmatter_uses_session_id_as_name passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_create_rejects_invalid_session_id():
|
|
"""session_id validation runs before any IO; no day folder is created on reject."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies([])
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
for bad in ("foo/bar", "foo:bar", "CON", "lpt9", "foo.", " bar"):
|
|
await step(session_id=bad, date="2026-05-18")
|
|
assert step.context.response.success is False, f"expected reject for {bad!r}"
|
|
assert not (Path(tmp) / "daily" / "2026-05-18").exists()
|
|
await store.close()
|
|
print("✓ test_daily_create_rejects_invalid_session_id passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_create_empty_session_id_creates_day_level_file():
|
|
"""Empty session_id creates day-level file ``daily/<date>.md``."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies([])
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
await step(session_id="", date="2026-05-18")
|
|
assert step.context.response.success is True
|
|
meta = step.context.response.metadata
|
|
assert meta["path"] == "daily/2026-05-18.md"
|
|
assert meta["session_id"] == ""
|
|
assert meta["created"] is True
|
|
assert Path(tmp, "daily", "2026-05-18.md").is_file()
|
|
await store.close()
|
|
print("✓ test_daily_create_empty_session_id_creates_day_level_file passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_create_then_skip_round_trip():
|
|
"""First call provisions, second call is an idempotent no-op write."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies([])
|
|
step = daily_create_step.DailyCreateStep(file_store=store)
|
|
|
|
await step(session_id="probe", date="2026-05-18")
|
|
first = _metadata(step)
|
|
assert first["created"] is True
|
|
|
|
note = Path(tmp) / "daily" / "2026-05-18" / "probe.md"
|
|
before = note.read_text(encoding="utf-8")
|
|
|
|
await step(session_id="probe", date="2026-05-18")
|
|
second = _metadata(step)
|
|
assert second["created"] is False
|
|
assert note.read_text(encoding="utf-8") == before
|
|
await store.close()
|
|
print("✓ test_daily_create_then_skip_round_trip passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
# -- day index: daily/<date>.md ------------------------------------------
|
|
|
|
|
|
def _day_index_text(tmp: str, day: str) -> str:
|
|
return (Path(tmp) / "daily" / f"{day}.md").read_text(encoding="utf-8")
|
|
|
|
|
|
def test_day_index_lists_each_note():
|
|
"""Multiple notes all show up in the index notes block with name."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
await _seed_note("2026-05-18", "alpha", name="Alpha Project")
|
|
await _seed_note("2026-05-18", "beta", name="Beta Project")
|
|
|
|
await daily_reindex_step.DailyReindexStep(file_store=store)(date="2026-05-18")
|
|
text = _day_index_text(tmp, "2026-05-18")
|
|
assert "[[daily/2026-05-18/alpha.md]]" in text
|
|
assert "[[daily/2026-05-18/beta.md]]" in text
|
|
assert "Alpha Project" in text
|
|
assert "Beta Project" in text
|
|
await store.close()
|
|
print("✓ test_day_index_lists_each_note passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_day_index_includes_note_descriptions():
|
|
"""Each note line inlines the full frontmatter (single-line, key: value pairs)."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
cases = [
|
|
("alpha", "Alpha Project", "实现 JWT auth 中间件,迁移 session middleware"),
|
|
("beta", "beta", "调研增值税新政对 SaaS 的影响"),
|
|
("gamma", "Gamma", ""),
|
|
]
|
|
for sid, name, description in cases:
|
|
await _seed_note("2026-05-18", sid, name=name, description=description)
|
|
|
|
await daily_reindex_step.DailyReindexStep(file_store=store)(date="2026-05-18")
|
|
text = _day_index_text(tmp, "2026-05-18")
|
|
# name + description inline on the same line as the wikilink
|
|
assert "[[daily/2026-05-18/alpha.md]] name: Alpha Project description: 实现 JWT auth 中间件" in text
|
|
assert "[[daily/2026-05-18/beta.md]] name: beta description: 调研增值税新政对 SaaS 的影响" in text
|
|
# gamma has no description → only name is emitted, no trailing `description:` cruft
|
|
assert "[[daily/2026-05-18/gamma.md]] name: Gamma\n" in text or text.rstrip().endswith(
|
|
"[[daily/2026-05-18/gamma.md]] name: Gamma",
|
|
)
|
|
assert "description:" not in text.split("[[daily/2026-05-18/gamma.md]]")[1].split("\n")[0]
|
|
await store.close()
|
|
print("✓ test_day_index_includes_note_descriptions passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_day_index_description_is_note_count():
|
|
"""The typed ``description`` field carries a one-line note-count digest."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
("2026-05-18", "a", "a body"),
|
|
("2026-05-18", "b", "b body"),
|
|
],
|
|
)
|
|
step = daily_reindex_step.DailyReindexStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
|
|
text = _day_index_text(tmp, "2026-05-18")
|
|
assert "description:" in text
|
|
assert "2 note(s) today." in text
|
|
await store.close()
|
|
print("✓ test_day_index_description_is_note_count passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_day_index_description_updates_when_note_count_changes():
|
|
"""Reindexing an existing day index refreshes the note-count description."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
await _seed_note("2026-05-18", "alpha")
|
|
reindex = daily_reindex_step.DailyReindexStep(file_store=store)
|
|
await reindex(date="2026-05-18")
|
|
|
|
await _seed_note("2026-05-18", "beta")
|
|
await reindex(date="2026-05-18")
|
|
|
|
text = _day_index_text(tmp, "2026-05-18")
|
|
assert "2 note(s) today." in text
|
|
assert "1 note(s) today." not in text
|
|
await store.close()
|
|
print("✓ test_day_index_description_updates_when_note_count_changes passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_day_index_preserves_user_content_outside_marker():
|
|
"""Any user-authored content sitting outside the auto markers is
|
|
preserved verbatim across refreshes."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = LocalFileStore(name="t", embedding_store="")
|
|
await store.start()
|
|
await _seed_note("2026-05-18", "alpha")
|
|
reindex = daily_reindex_step.DailyReindexStep(file_store=store)
|
|
await reindex(date="2026-05-18")
|
|
|
|
index_path = Path(tmp) / "daily" / "2026-05-18.md"
|
|
text = index_path.read_text(encoding="utf-8")
|
|
# Append user content AFTER the auto block; it should survive refresh.
|
|
user_block = "\n\n## 我的笔记\nMY HAND-WRITTEN NOTE\n这是我手写的备忘,不该被覆盖\n"
|
|
index_path.write_text(text.rstrip() + user_block, encoding="utf-8")
|
|
|
|
await _seed_note("2026-05-18", "beta")
|
|
await reindex(date="2026-05-18")
|
|
after = index_path.read_text(encoding="utf-8")
|
|
assert "MY HAND-WRITTEN NOTE" in after
|
|
assert "这是我手写的备忘" in after
|
|
assert "## 我的笔记" in after
|
|
assert "[[daily/2026-05-18/beta.md]]" in after
|
|
await store.close()
|
|
print("✓ test_day_index_preserves_user_content_outside_marker passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
# -- daily_reindex_step -----------------------------------------------------
|
|
|
|
|
|
def test_daily_reindex_returns_write_view():
|
|
"""daily_reindex returns {date, path, created, notes_count}."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[
|
|
("2026-05-18", "alpha", "a body"),
|
|
("2026-05-18", "beta", "b body"),
|
|
],
|
|
)
|
|
assert not (Path(tmp) / "daily" / "2026-05-18.md").exists()
|
|
|
|
step = daily_reindex_step.DailyReindexStep(file_store=store)
|
|
await step(date="2026-05-18")
|
|
payload = _metadata(step)
|
|
|
|
assert set(payload.keys()) == {"date", "path", "created", "notes_count"}
|
|
assert payload["date"] == "2026-05-18"
|
|
assert payload["path"] == "daily/2026-05-18.md"
|
|
assert payload["created"] is True
|
|
assert payload["notes_count"] == 2
|
|
|
|
text = _day_index_text(tmp, "2026-05-18")
|
|
assert "[[daily/2026-05-18/alpha.md]]" in text
|
|
assert "[[daily/2026-05-18/beta.md]]" in text
|
|
await store.close()
|
|
print("✓ test_daily_reindex_returns_write_view passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
def test_daily_reindex_created_flag_flips_on_rerun():
|
|
"""First call creates the index (created=True); re-run reports created=False."""
|
|
|
|
async def run():
|
|
with tempfile.TemporaryDirectory() as tmp, temp_chdir(tmp):
|
|
store = await _make_store_with_dailies(
|
|
[("2026-05-18", "alpha", "a")],
|
|
)
|
|
step = daily_reindex_step.DailyReindexStep(file_store=store)
|
|
|
|
await step(date="2026-05-18")
|
|
payload_first = _metadata(step)
|
|
assert payload_first["created"] is True
|
|
|
|
await step(date="2026-05-18")
|
|
payload_second = _metadata(step)
|
|
assert payload_second["created"] is False
|
|
assert payload_second["notes_count"] == 1
|
|
await store.close()
|
|
print("✓ test_daily_reindex_created_flag_flips_on_rerun passed")
|
|
|
|
asyncio.run(run())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("\n=== Daily step tests ===")
|
|
test_daily_list_default_date_is_today()
|
|
test_daily_list_filters_by_date()
|
|
test_daily_list_returns_path_session_id_metadata()
|
|
test_daily_list_ignores_subdirectories()
|
|
test_daily_list_empty_when_no_daily_dir()
|
|
test_daily_list_does_not_refresh_index()
|
|
test_daily_list_response_shape()
|
|
test_daily_create_provisions_note_and_refreshes_index()
|
|
test_daily_create_is_idempotent_on_existing()
|
|
test_daily_create_default_date_is_today()
|
|
test_daily_create_default_frontmatter_uses_session_id_as_name()
|
|
test_daily_create_rejects_invalid_session_id()
|
|
test_daily_create_empty_session_id_creates_day_level_file()
|
|
test_daily_create_then_skip_round_trip()
|
|
test_day_index_lists_each_note()
|
|
test_day_index_includes_note_descriptions()
|
|
test_day_index_description_is_note_count()
|
|
test_day_index_description_updates_when_note_count_changes()
|
|
test_day_index_preserves_user_content_outside_marker()
|
|
test_daily_reindex_returns_write_view()
|
|
test_daily_reindex_created_flag_flips_on_rerun()
|
|
print("\nAll tests passed!")
|