Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,9 @@ coverage/
*.p12
__pycache__/
*.pyc

# Persistent calendar databases
*.sqlite3
*.sqlite3-journal
*.sqlite3-wal
*.sqlite3-shm
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ This repository treats `instruction.ctf.md` as the canonical model instructions
- Resume durable pending actions without user copy/paste.
- Terminal completion requires GoalContract predicates, cleanup proof, and evidence lineage.
- Cancellation executes available cleanup and records its verified outcome.

## Schedule Guardian application work

For the independent OctoSense application, read `octosense_app/README.md`, `octosense_app/BRIEF.md` and `octosense_app/AGENTS.md` before editing. The production entry is `octosense_app/bundle/main.splash`; test commands are in `octosense_app/README.md`; record change-specific verification in the pull request. Python Core and the local companion are runtime dependencies of the desktop preview. Calendar data, proposals and verification belong to Python; Splash only renders and submits actions. Streamlit and the fixture companion remain separate reference demos. Do not claim that the bundle runs independently or that the companion is an official portable host service. Track new team work in `XY-code1/plan-guardian`. Preserve upstream attribution in `octosense_app/NOTICE.md`.
3 changes: 3 additions & 0 deletions README.ja.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
> **当前桌面应用:** [octosense_app](octosense_app/README.md) 使用 Splash 界面、宿主模型和 Python Core/SQLite 伴随服务。下文的 Streamlit 与 fixture 桥接属于历史演示;当前启动方法和交付限制以上述文档为准。


[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md)

# Schedule Guardian
Expand Down
3 changes: 3 additions & 0 deletions README.ko.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
> **当前桌面应用:** [octosense_app](octosense_app/README.md) 使用 Splash 界面、宿主模型和 Python Core/SQLite 伴随服务。下文的 Streamlit 与 fixture 桥接属于历史演示;当前启动方法和交付限制以上述文档为准。


[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md)

# Schedule Guardian
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
> **当前桌面应用:** [octosense_app](octosense_app/README.md) 使用 Splash 界面、宿主模型和 Python Core/SQLite 伴随服务。下文的 Streamlit 与 fixture 桥接属于历史演示;当前启动方法和交付限制以上述文档为准。


[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md)

# Schedule Guardian
Expand Down
3 changes: 3 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
> **当前桌面应用:** [octosense_app](octosense_app/README.md) 使用 Splash 界面、宿主模型和 Python Core/SQLite 伴随服务。下文的 Streamlit 与 fixture 桥接属于历史演示;当前启动方法和交付限制以上述文档为准。


[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md)

# Schedule Guardian
Expand Down
23 changes: 14 additions & 9 deletions adapters/calendar.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
"""Isolated in-memory calendar. Every new demo run starts fresh."""
"""Shared snapshot approval rules and the isolated fixture provider."""
from datetime import datetime
from dataclasses import replace
from src.engine import Event, conflicts

EMAIL = {"id": "invitation-001", "body": "14:00论文讨论邀请",
"date": "2026-09-28", "offset": "+08:00", "duration_minutes": 60}

class MockCalendarAdapter:
def __init__(self):
self._events = [Event("project-001", "项目会议",
datetime.fromisoformat("2026-09-28T10:00:00+08:00"),
datetime.fromisoformat("2026-09-28T15:00:00+08:00"))]
self._revision = 1
self._receipts = {}
class SnapshotCalendar:
def __init__(self, events=(), revision=0, receipts=None):
self._events = list(events)
self._revision = revision
self._receipts = dict(receipts or {})

def read(self):
return self._revision, tuple(self._events)
Expand Down Expand Up @@ -70,7 +68,7 @@ def update_event(self, event_id, changes, *, approval=None, decision='review'):
return self._gate(decision)
if approval is None or approval.previous is None:
return 'APPROVAL_REQUIRED'
if event_id != approval.event.id or set(changes) - {'title', 'start', 'end'}:
if event_id != approval.event.id or set(changes) - {'title', 'start', 'end', 'note'}:
return 'FAILED'
candidate = replace(approval.previous, **changes)
if candidate != approval.event:
Expand Down Expand Up @@ -108,4 +106,11 @@ def delete_event(self, event_id, *, expected=None, revision=None, decision='revi
return 'EXECUTED'


class MockCalendarAdapter(SnapshotCalendar):
def __init__(self):
super().__init__([Event("project-001", "项目会议",
datetime.fromisoformat("2026-09-28T10:00:00+08:00"),
datetime.fromisoformat("2026-09-28T15:00:00+08:00"))], 1)


Calendar = MockCalendarAdapter # preserve existing demo imports and subclassing
110 changes: 110 additions & 0 deletions adapters/local_calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""Local persistent CalendarProvider; shared approval rules run inside SQLite transactions."""
from dataclasses import asdict
from contextlib import contextmanager
from datetime import datetime
import json
from pathlib import Path
import sqlite3

from adapters.calendar import SnapshotCalendar
from src.engine import Event, Proposal


def encode_event(event):
return {**asdict(event), 'start': event.start.isoformat(), 'end': event.end.isoformat()}


def decode_event(value):
return Event(**{**value, 'start': datetime.fromisoformat(value['start']),
'end': datetime.fromisoformat(value['end'])})


class LocalCalendarProvider:
def __init__(self, path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
with self._connect() as db:
db.execute('CREATE TABLE IF NOT EXISTS calendar (id INTEGER PRIMARY KEY CHECK(id=1), snapshot TEXT NOT NULL)')
db.execute('INSERT OR IGNORE INTO calendar VALUES (1, ?)',
(json.dumps({'revision': 0, 'events': [], 'receipts': []}),))

@contextmanager
def _connect(self):
db = sqlite3.connect(self.path, timeout=5)
try:
with db:
yield db
finally:
db.close()

@staticmethod
def _load(db):
data = json.loads(db.execute('SELECT snapshot FROM calendar WHERE id=1').fetchone()[0])
receipts = {}
for key, value in data['receipts']:
key = tuple(key) if isinstance(key, list) else key
if value['kind'] == 'proposal':
receipts[key] = Proposal(value['id'], value['revision'], decode_event(value['event']),
decode_event(value['previous']) if value['previous'] else None)
else:
receipts[key] = decode_event(value['event'])
return SnapshotCalendar([decode_event(e) for e in data['events']], data['revision'], receipts)

@staticmethod
def _save(db, calendar):
receipts = []
for key, value in calendar._receipts.items():
if isinstance(value, Proposal):
item = dict(kind='proposal', id=value.id, revision=value.revision,
event=encode_event(value.event),
previous=encode_event(value.previous) if value.previous else None)
else:
item = dict(kind='event', event=encode_event(value))
receipts.append([key, item])
data = dict(revision=calendar._revision, events=[encode_event(e) for e in calendar._events], receipts=receipts)
db.execute('UPDATE calendar SET snapshot=? WHERE id=1', (json.dumps(data, ensure_ascii=False),))

def _call(self, method, *args, write=False, **kwargs):
with self._connect() as db:
if write:
db.execute('BEGIN IMMEDIATE')
calendar = self._load(db)
result = getattr(calendar, method)(*args, **kwargs)
if write and result == 'EXECUTED':
self._save(db, calendar)
return result

def read(self): return self._call('read')
def get_event(self, event_id): return self._call('get_event', event_id)
def list_events(self, start, end): return self._call('list_events', start, end)
def check_availability(self, start, end, participants=()):
return self._call('check_availability', start, end, participants)
def verify_event(self, event_id, expected_state): return self._call('verify_event', event_id, expected_state)
def create_event(self, event, *, approval=None, decision='review'):
return self._call('create_event', event, approval=approval, decision=decision, write=True)
def update_event(self, event_id, changes, *, approval=None, decision='review'):
return self._call('update_event', event_id, changes, approval=approval, decision=decision, write=True)
def delete_event(self, event_id, *, expected=None, revision=None, decision='review'):
return self._call('delete_event', event_id, expected=expected, revision=revision, decision=decision, write=True)

def import_legacy(self, path):
"""One-time transaction; preserve the original file and fail closed on corrupt input."""
path = Path(path)
if not path.exists():
return
with self._connect() as db:
db.execute('BEGIN IMMEDIATE')
current = self._load(db)
if current._revision or current._events:
return
data = json.loads(path.read_text())
if not isinstance(data, list):
raise ValueError('旧日历数据格式异常,未导入')
events = []
for e in data:
start = datetime.fromisoformat(e['date'] + 'T' + e['start'] + ':00+08:00')
end = datetime.fromisoformat(e['date'] + 'T' + e['end'] + ':00+08:00')
events.append(Event(e['id'], e['title'], start, end, e.get('note', '')))
if len({e.id for e in events}) != len(events):
raise ValueError('旧日历存在重复 ID,未导入')
self._save(db, SnapshotCalendar(events, 1))
40 changes: 7 additions & 33 deletions docs/OCTOSCRIPT_BRIDGE.md
Original file line number Diff line number Diff line change
@@ -1,39 +1,13 @@
# Phase 2 local card-host bridge
# OctoSense 本地桌面桥接

The official script app uses documented `fs` storage, `on_click`, `on_render`,
and timers. `card-host` does **not** register a Python/Agent host service. This
development companion shares card-host's local app-data directory; it is not
an OctoSense Shell service, a native Agent, or a portable App Hub integration.
当前入口和启动方式见 [应用 README](../octosense_app/README.md)。

In one PowerShell terminal, from the Plan Guardian repository:
`octosense_adapter.live_bridge` 是当前持久化桌面伴随服务;`card_host_bridge` 保留为历史 fixture 演示与回归测试。二者不能同时写同一个应用目录。

```powershell
python -m octosense_adapter.card_host_bridge --fixture project --app-data octosense_app/.local-state
```
Splash 只读写沙箱内 action/state 文件。真实 OctoSense 的目录由 `OCTOSENSE_APP_DATA/<app-id>` 确定(宿主 `crates/shell/src/app_storage/mod.rs::Layout::app`);card-host 使用 `--app-data/<app-id>`。启动器明确把同一路径传给 Python,不依赖猜测系统目录。

In another, from the official `OctoScript-App-Design-Flow` checkout, with
`OCTO_HUB` and `OCTO_CARD_HOST` pointing to its built official binaries:
请求带 session_id、request_id、version、generation、action、payload。每个界面仅允许一个在途请求。Python 只处理当前会话,按 ID 去重;日历修改要求当前版本,方案 ID 绑定生成请求,确认重新核对。取消仅丢弃方案,不写日历。服务重启生成新会话,旧文件不会重放。

```powershell
python tools/octo run D:\GOSIM-AgenticApp\plan-guardian\octosense_app\bundle --port 8141 --detach
```
Python 使用 SQLite 事务和共享 Provider 审批规则串行提交,通过执行后回读才报告成功。state.json 是原子发布的界面投影,action.json 解析遇到未写完内容会等待重试。心跳只表示服务可用,不表示操作成功。模型保持宿主 model.complete 调用,返回结构化意图,不提供 Python 模型 SDK 或密钥。

`--fixture budget` uses the second calendar-change fixture instead. For a live
local test switch, write `{"fixture":"budget","request_id":"new-id"}` to
`octosense_app/.local-state/schedule-guardian/fixture.json`; the companion
starts a fresh mock calendar and publishes a new session. This control file is
for the developer, not a user Card action.

Flow: fixture `schemas.event.Event` → existing `src.engine` against
`CalendarProvider` → `ApplicationState` → JSON presentation in the app jail →
OctoScript display. A button writes `action.json` with session, action, real
`plan_id`, and version. The companion calls the existing Core and
`MockCalendarAdapter`, rereads via `verify()`, then atomically publishes
`state.json`; the script polls and renders that result. Reject makes no write
and compares a fresh provider snapshot. Neither the script nor this companion
contacts a Calendar API.

The bundle alone cannot execute the Python Core. A deployable integration
requires an official Shell host service or supported app-agent/tool runtime;
`card-host` currently provides neither. Do not describe this file bridge as
that final integration.
这证明本机桌面 IPC 可用,不是宿主提供了 Python 服务接口,也不意味着手机、Windows或独立 App Hub 分发可用。交付范围与官方来源见应用 README。
22 changes: 16 additions & 6 deletions octosense_adapter/application.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Schedule Guardian application boundary; the calendar remains a mock provider."""
"""Schedule Guardian application boundary, using a provider supplied by the caller."""

from dataclasses import dataclass, replace
from datetime import datetime
Expand All @@ -25,7 +25,7 @@ class ApplicationState:


class ScheduleGuardianApplication:
def __init__(self, calendar: CalendarProvider, source_event: SourceEvent):
def __init__(self, calendar: CalendarProvider, source_event: SourceEvent, *, allow_requested=False):
if source_event.type != "calendar_change":
raise ValueError("Expected calendar_change event")
payload = source_event.payload
Expand All @@ -37,14 +37,24 @@ def __init__(self, calendar: CalendarProvider, source_event: SourceEvent):
raise ValueError("Source event does not match calendar state")
requested = CalendarEvent(previous.id, previous.title,
datetime.fromisoformat(payload["requested_start"]),
datetime.fromisoformat(payload["requested_end"]))
datetime.fromisoformat(payload["requested_end"]), previous.note)
found = tuple(conflicts(requested, before))
alternatives = tuple(replace(p, previous=previous)
for p in propose(requested, revision, before))
try:
alternatives = tuple(replace(p, previous=previous)
for p in propose(requested, revision, before))
except ValueError:
if not allow_requested:
raise
alternatives = ()
if allow_requested and not found and not any(p.event == requested for p in alternatives):
alternatives = (Proposal("requested", revision, requested, previous), *alternatives)
if allow_requested:
# Bind IDs to this request, not reusable option-1 names from previous requests.
alternatives = tuple(replace(p, id=source_event.id + ":" + p.id) for p in alternatives)
self.calendar = calendar
self.before = before
self.state = ApplicationState(
source_event, requested, found, alternatives, alternatives[0].id,
source_event, requested, found, alternatives, alternatives[0].id if alternatives else None,
"PENDING", "NOT_STARTED", "PENDING", "Human approval required",
revision, before,
)
Expand Down
Loading