ReMe/reme/utils/proactive_record.py
jinliyl 524b1b6908
feat(studio): unify the workbench and proactive runtime (#764)
* fix(proactive): simplify round files and restore failed summaries

* fix(proactive): validate document-relative Markdown links

* feat(proactive_agent): implement v2 daily record workflow with single-file decision

- Add ProactiveAgentStepV2 class to support single daily note decision and reminder
- Introduce RoundOutputs for v2 round file tracking, and keep RoundArtifacts for v1 summary backup
- Refactor AgentOutbox to support both v1 standalone reminder files and v2 daily reminder records
- Add proactive_record utilities to parse and validate v2 daily record frontmatter and metadata
- Enhance proactive_agent to prepare, read, and manage artifacts for both v1 and v2 flows
- Add configuration profile proactive_v2 to enable new workflow with backward compatibility
- Update proactive.yaml and reactive proactive_agent_step configuration comment for easy switching
- Provide extensive schema validation for v2 reminders ensuring priority and message consistency
- Document v2 workflow and usage in English and Chinese runtime docs
- Add unit tests for v2 step verifying single file output and proper decision handling

* refactor(agent/runtime): replace ReminderRef with string keys and simplify reminder handling

- Remove ReminderRef model and switch to using workspace-relative string keys for reminders
- Simplify AgentOutbox to read, write, and manage reminders keyed by strings
- Change file locking and version checking to protect concurrent edits on daily record files
- Replace legacy and v2 reminder file handling with unified ReminderFiles storage
- Adjust ChatNotifications to operate with the new key scheme and update pending/read sets
- Refactor RoundOutputs to RoundRecord for safer round record tracking and rollback
- Remove unused ProactiveRunResult and related references from imports and exports
- Update InboxWakeRequest, AgentReminder, and related models for consistent ID and path validation
- Adjust proactive agent runtime and local runtime to check reminder versions before commit
- Correct language and docs to describe reminders as daily records instead of separate files
- Clean up roles of inbox and outbox for reminder ownership, delivery, and acknowledgments

* fix(proactive): serialize round commits and align desktop reminders

* refactor(proactive): unify task triggers in Proactive Runtime

* fix(proactive): bound reminder payloads and simplify receipts

* refactor(studio): share workbench and simplify proactive delivery

* fix(studio): update and centralize build dependencies

* fix(proactive): guard draft repair and verify Studio deployments

* chore(docs): update source-map-js

* feat(release): support publishing selected artifacts from a tag

* chore(studio): remove the public playground

* refactor: simplify reminders and release workflows

* fix: preserve proactive records and align release provenance

* test(proactive): remove brittle prompt and preset assertions

* fix(proactive): register reminders after input acknowledgement

* feat(notebook): list projects across todos and ideas

* feat(studio): connect mobile apps to configurable ReMe services

* fix(proactive): reserve registered reminder paths

* fix(studio): request Android local network access

* fix(proactive): reserve reminder paths referenced by receipts
2026-11-23 17:19:21 +08:00

98 lines
3.5 KiB
Python

"""Daily record paths, Markdown parsing, and version tracking for proactive tasks."""
from datetime import date
from pathlib import Path
import re
from stat import S_ISREG
import yaml
from .async_utils import complete_in_thread
from .files.path_lock import get_path_lock
from .files.workspace_files import WorkspaceFiles
_ROUND_SUFFIX = re.compile(r"[0-9]{6}(?:_[0-9]+)?\.md")
_FRONTMATTER = re.compile(r"\A---[ \t]*\r?\n(.*?)^---[ \t]*(?=\r?$)", re.MULTILINE | re.DOTALL)
def is_round_record(path, agent_name):
"""Check whether the filename matches this agent's round record format."""
prefix = f"{agent_name}_"
name = path.name
return name.startswith(prefix) and _ROUND_SUFFIX.fullmatch(name[len(prefix) :]) is not None
def is_date_directory(path):
"""Recognize the application's ISO date folder names."""
try:
return date.fromisoformat(path.name).isoformat() == path.name
except ValueError:
return False
def _split_frontmatter(text):
text = text.removeprefix("\ufeff")
if match := _FRONTMATTER.match(text):
return match[1], text[match.end() :]
return None, text
def split_record(text):
"""Read YAML metadata while keeping the exact Markdown suffix for state updates."""
header, body = _split_frontmatter(text)
if header is not None:
metadata = yaml.safe_load(header)
if isinstance(metadata, dict):
return metadata, body
return {}, text.removeprefix("\ufeff")
class RoundRecord:
"""Track the record's version until the input receipt is durable."""
def __init__(self, files: WorkspaceFiles):
self.files = files
self.path: Path | None = None
self.written = None
def _version(self, path):
try:
stat = self.files.checked(path).stat(follow_symlinks=False)
except FileNotFoundError:
return None
if not S_ISREG(stat.st_mode):
raise ValueError(f"Round record must be a regular file: {path}")
return stat.st_ino, stat.st_mtime_ns, stat.st_size
async def prepare(self, path: Path):
"""Ensure the model starts with an unused record path."""
async with await get_path_lock(path):
if await complete_in_thread(self._version, path) is not None:
raise FileExistsError(path)
self.path = path
def capture(self):
"""Capture the version visible after the model turn for validation."""
try:
self.written = self._version(self.path)
except (OSError, ValueError):
# Validation reports invalid or unreadable destinations.
self.written = None
def check_version(self, path: Path):
"""Reject edits made before commit, including a file created after a skip."""
if path != self.path or self._version(path) != self.written:
raise RuntimeError(f"Agent output changed outside this round: {path}")
def replace_frontmatter(self, metadata):
"""Replace the record's frontmatter only if its version still matches."""
self.check_version(self.path)
header, body = _split_frontmatter(self.files.read(self.path))
if header is None:
raise ValueError("The round record must have delimited YAML frontmatter")
def save_version(result):
_, self.written = result
content = f"---\n{yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False)}---{body}"
self.files.write(self.path, content, on_write=save_version)