qiuql commited on
Commit
5a19855
·
verified ·
1 Parent(s): b6ed8ef

Add Harbor-format task: rental/renewal_negotiation_repair_rental

Browse files

Synced from https://github.com/evolvent-ai/VibeLifeBench/tree/cd21b2cb5d18a81b0fcdb4a948889a2148f48958/harbor/rental/renewal_negotiation_repair_rental (482 files, byte-identical to GitHub cd21b2cb).

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. harbor/rental/renewal_negotiation_repair_rental/environment/Dockerfile +57 -0
  2. harbor/rental/renewal_negotiation_repair_rental/environment/docker-compose.yaml +139 -0
  3. harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/collect +3 -0
  4. harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/collector.py +345 -0
  5. harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/harbor_env.py +179 -0
  6. harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/response_capture.py +392 -0
  7. harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/snapshot_capture.py +490 -0
  8. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/calendar/README.md +19 -0
  9. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/calendar/init.sql +0 -0
  10. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/email/README.md +19 -0
  11. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/email/init.sql +0 -0
  12. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/legal_search/README.md +19 -0
  13. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/legal_search/init.sql +0 -0
  14. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/listing_platform/README.md +19 -0
  15. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/listing_platform/init.sql +0 -0
  16. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/maps/README.md +19 -0
  17. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/maps/init.sql +0 -0
  18. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notification_hub/README.md +19 -0
  19. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notification_hub/init.sql +0 -0
  20. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notion/README.md +20 -0
  21. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notion/init.sql +0 -0
  22. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/review_platform/README.md +19 -0
  23. harbor/rental/renewal_negotiation_repair_rental/environment/seeds/review_platform/init.sql +0 -0
  24. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/.gitignore +13 -0
  25. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/Dockerfile +11 -0
  26. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/LICENSE +21 -0
  27. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/README.md +83 -0
  28. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/SPEC.md +196 -0
  29. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/pyproject.toml +26 -0
  30. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/__init__.py +1 -0
  31. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/__main__.py +4 -0
  32. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/backends/__init__.py +7 -0
  33. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/backends/db.py +118 -0
  34. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/models/__init__.py +9 -0
  35. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/models/calendar.py +14 -0
  36. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/models/event.py +39 -0
  37. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/server.py +99 -0
  38. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/__init__.py +7 -0
  39. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/_common.py +95 -0
  40. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/calendar_service.py +27 -0
  41. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/event_service.py +320 -0
  42. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/__init__.py +7 -0
  43. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/_common.py +39 -0
  44. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/calendar_tools.py +13 -0
  45. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/event_tools.py +119 -0
  46. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/__init__.py +0 -0
  47. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/dates.py +114 -0
  48. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/exceptions.py +41 -0
  49. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/ids.py +14 -0
  50. harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/world_clock.py +85 -0
harbor/rental/renewal_negotiation_repair_rental/environment/Dockerfile ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Must stay buildable from a public base alone: this bundle is built by whoever
2
+ # receives it, on a machine that has none of the author's local images. A
3
+ # `FROM <locally-built-image>` here fails with "pull access denied" there, and a
4
+ # structural delivery check cannot catch it — such checks inspect compose's
5
+ # `image:` keys, never a Dockerfile FROM.
6
+ #
7
+ # The default base is therefore public and the build needs nothing else. The ARG
8
+ # exists only so a caller who has pre-baked a heavier base (node + the agent CLI,
9
+ # to save time across repeated local runs) can opt in at build time:
10
+ #
11
+ # docker build --build-arg BASE_IMAGE=<your-prebaked-image> \
12
+ # -f environment/Dockerfile -t <tag> environment/
13
+ #
14
+ # Override the ARG; never edit FROM.
15
+ ARG BASE_IMAGE=python:3.12-slim
16
+ FROM ${BASE_IMAGE}
17
+
18
+ # Idempotent: a no-op when the pre-baked base already carries these.
19
+ RUN apt-get update \
20
+ && apt-get install -y --no-install-recommends \
21
+ bash ca-certificates coreutils curl jq procps sqlite3 \
22
+ && rm -rf /var/lib/apt/lists/*
23
+
24
+ # Core mcp only. The task's client code uses ClientSession and
25
+ # streamablehttp_client; the [cli] extra pulls a typer/rich chain that cannot be
26
+ # resolved against mcp 1.25.0's pydantic pin, so requesting it makes this image
27
+ # unbuildable while adding nothing the task uses.
28
+ RUN pip install --no-cache-dir \
29
+ "mcp==1.25.0" \
30
+ "PyYAML==6.0.3"
31
+
32
+ # Codex tuning, baked into Codex's Unix system layer so the package is
33
+ # self-contained. Harbor recreates /tmp/codex-home for each step, writes its
34
+ # base URL and MCP settings to that user layer, then removes $CODEX_HOME in the
35
+ # step cleanup. A config baked there therefore disappears before the first
36
+ # `codex exec resume --last`; /etc/codex/config.toml survives that lifecycle,
37
+ # and Codex merges it with Harbor's per-step user config.
38
+ #
39
+ # model_auto_compact_token_limit: every step resumes the same session, so the
40
+ # conversation grows monotonically. Measured on this task set it reaches the
41
+ # 196,608-token window around step 20; compacting at 150,000 keeps later steps
42
+ # from repeatedly processing a full window. Compaction replacement history is
43
+ # persisted in the session and is available to later resume processes.
44
+ #
45
+ # web_search: this task talks only to vendored mocks. Codex 0.146.0 expects the
46
+ # top-level enum `web_search = "disabled"`; the deprecated boolean form
47
+ # `[tools] web_search = false` is accepted but silently deserializes to no
48
+ # override, so do not replace this with that form.
49
+ RUN mkdir -p /etc/codex \
50
+ && printf 'model = "sub2api-gpt-5.6-sol"\nmodel_reasoning_effort = "xhigh"\nmodel_auto_compact_token_limit = 150000\nweb_search = "disabled"\n' \
51
+ > /etc/codex/config.toml
52
+
53
+ COPY evidence-collector /opt/evidence-collector
54
+ RUN chmod +x /opt/evidence-collector/collect
55
+
56
+ WORKDIR /workspace
57
+ USER root
harbor/rental/renewal_negotiation_repair_rental/environment/docker-compose.yaml ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ build:
4
+ context: .
5
+ dockerfile: Dockerfile
6
+ depends_on:
7
+ workspace-init: {condition: service_completed_successfully}
8
+ world-controller: {condition: service_healthy}
9
+ calendar: {condition: service_healthy}
10
+ email: {condition: service_healthy}
11
+ legal-search: {condition: service_healthy}
12
+ listing-platform: {condition: service_healthy}
13
+ maps: {condition: service_healthy}
14
+ notification-hub: {condition: service_healthy}
15
+ notion: {condition: service_healthy}
16
+ review-platform: {condition: service_healthy}
17
+ volumes:
18
+ - workspace-state:/workspace
19
+ - eval-evidence:/harbor/evidence:ro
20
+ - world-clock:/world-clock:ro
21
+ environment:
22
+ WORLD_CLOCK_FILE: /world-clock/current.json
23
+ NO_PROXY: localhost,127.0.0.1,::1,world-controller,calendar,email,legal-search,listing-platform,maps,notification-hub,notion,review-platform
24
+ no_proxy: localhost,127.0.0.1,::1,world-controller,calendar,email,legal-search,listing-platform,maps,notification-hub,notion,review-platform
25
+
26
+ workspace-init:
27
+ build:
28
+ context: .
29
+ dockerfile: workspace-init/Dockerfile
30
+ volumes: [workspace-state:/target]
31
+ restart: "no"
32
+
33
+ calendar:
34
+ build: {context: ./servers/calendar_mock}
35
+ volumes: [./seeds/calendar:/env-seed:ro, calendar-env:/env, world-clock:/world-clock:ro]
36
+ expose: ["8000"]
37
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
38
+ healthcheck: &health
39
+ test: [CMD, python, -c, "import socket; s=socket.create_connection(('127.0.0.1',8000),2); s.close()"]
40
+ interval: 2s
41
+ timeout: 5s
42
+ retries: 30
43
+ start_period: 3s
44
+ email:
45
+ build: {context: ./servers/email_mock}
46
+ volumes: [./seeds/email:/env-seed:ro, email-env:/env, world-clock:/world-clock:ro]
47
+ expose: ["8000"]
48
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
49
+ healthcheck: *health
50
+ legal-search:
51
+ build: {context: ./servers/legal_search_mock}
52
+ volumes: [./seeds/legal_search:/env-seed:ro, legal-search-env:/env, world-clock:/world-clock:ro]
53
+ expose: ["8000"]
54
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
55
+ healthcheck: *health
56
+ listing-platform:
57
+ build: {context: ./servers/listing_platform_mock}
58
+ volumes: [./seeds/listing_platform:/env-seed:ro, listing-platform-env:/env, world-clock:/world-clock:ro]
59
+ expose: ["8000"]
60
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
61
+ healthcheck: *health
62
+ maps:
63
+ build: {context: ./servers/maps_mock}
64
+ volumes: [./seeds/maps:/env-seed:ro, maps-env:/env, world-clock:/world-clock:ro]
65
+ expose: ["8000"]
66
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
67
+ healthcheck: *health
68
+ notification-hub:
69
+ build: {context: ./servers/notification_hub_mock}
70
+ volumes: [./seeds/notification_hub:/env-seed:ro, notification-hub-env:/env, world-clock:/world-clock:ro]
71
+ expose: ["8000"]
72
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
73
+ healthcheck: *health
74
+ notion:
75
+ build: {context: ./servers/notion_mock}
76
+ volumes: [./seeds/notion:/env-seed:ro, notion-env:/env, world-clock:/world-clock:ro]
77
+ expose: ["8000"]
78
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
79
+ healthcheck: *health
80
+ review-platform:
81
+ build: {context: ./servers/review_platform_mock}
82
+ volumes: [./seeds/review_platform:/env-seed:ro, review-platform-env:/env, world-clock:/world-clock:ro]
83
+ expose: ["8000"]
84
+ environment: {WORLD_CLOCK_FILE: /world-clock/current.json}
85
+ healthcheck: *health
86
+
87
+ world-controller:
88
+ build:
89
+ context: .
90
+ dockerfile: world-controller/Dockerfile
91
+ depends_on:
92
+ workspace-init: {condition: service_completed_successfully}
93
+ calendar: {condition: service_healthy}
94
+ email: {condition: service_healthy}
95
+ legal-search: {condition: service_healthy}
96
+ listing-platform: {condition: service_healthy}
97
+ maps: {condition: service_healthy}
98
+ notification-hub: {condition: service_healthy}
99
+ notion: {condition: service_healthy}
100
+ review-platform: {condition: service_healthy}
101
+ environment:
102
+ HEALTH_TOKEN: rental-health-6fd1289b
103
+ CLOCK_TOKEN: renewal-negotiation-repair-rental-clock-v1
104
+ WORLD_CLOCK_FILE: /world-clock/current.json
105
+ WORLD_CLOCK_REQUIRED: "1"
106
+ volumes:
107
+ - calendar-env:/calendar-env
108
+ - email-env:/email-env
109
+ - legal-search-env:/legal-search-env
110
+ - listing-platform-env:/listing-platform-env
111
+ - maps-env:/maps-env
112
+ - notification-hub-env:/notification-hub-env
113
+ - notion-env:/notion-env
114
+ - review-platform-env:/review-platform-env
115
+ - controller-state:/controller-state
116
+ - workspace-state:/workspace-source:ro
117
+ - eval-evidence:/evidence
118
+ - world-clock:/world-clock
119
+ expose: ["8090"]
120
+ healthcheck:
121
+ test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8090/health', timeout=2).read()"]
122
+ interval: 2s
123
+ timeout: 5s
124
+ retries: 30
125
+ start_period: 3s
126
+
127
+ volumes:
128
+ workspace-state:
129
+ eval-evidence:
130
+ world-clock:
131
+ controller-state:
132
+ calendar-env:
133
+ email-env:
134
+ legal-search-env:
135
+ listing-platform-env:
136
+ maps-env:
137
+ notification-hub-env:
138
+ notion-env:
139
+ review-platform-env:
harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/collect ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ exec python /opt/evidence-collector/collector.py "$@"
harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/collector.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted main-service collector for one Harbor turn.
2
+
3
+ This program runs only from Harbor's verifier collect phase, after Harbor has
4
+ uploaded the current agent logs and before the world-controller sidecar freezes
5
+ them. It replaces, rather than merges with, the agent-writable staging bundle.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import shutil
13
+ import sys
14
+ import tempfile
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ HERE = Path(__file__).resolve().parent
20
+ if str(HERE) not in sys.path:
21
+ sys.path.insert(0, str(HERE))
22
+
23
+ SCENARIO_CLOCK_PATH = Path(
24
+ os.environ.get("WORLD_CLOCK_FILE", "/world-clock/current.json")
25
+ )
26
+ SCENARIO_CLOCK_REQUIRED = os.environ.get("WORLD_CLOCK_REQUIRED", "0") == "1"
27
+
28
+ ORACLE_STDOUT_FILE = "oracle.txt"
29
+ ORACLE_EXIT_CODE_FILE = "exit-code.txt"
30
+
31
+ from response_capture import ( # noqa: E402
32
+ _codex_current_turn_rows,
33
+ _codex_session_items,
34
+ _jsonable,
35
+ _load_trajectory,
36
+ _tool_result_success,
37
+ atif_step_slice,
38
+ step_text_and_calls,
39
+ )
40
+
41
+ def scenario_clock() -> dict[str, Any]:
42
+ try:
43
+ payload = json.loads(SCENARIO_CLOCK_PATH.read_text(encoding="utf-8"))
44
+ if not isinstance(payload.get("step"), str) or not isinstance(payload.get("now"), str):
45
+ raise ValueError("invalid scenario clock payload")
46
+ parsed = datetime.fromisoformat(payload["now"].replace("Z", "+00:00"))
47
+ if parsed.tzinfo is None:
48
+ raise ValueError("scenario clock must include an offset")
49
+ return {
50
+ "schema_version": 1,
51
+ "step": payload["step"],
52
+ "now": parsed.isoformat(),
53
+ }
54
+ except Exception as exc:
55
+ if SCENARIO_CLOCK_REQUIRED:
56
+ raise RuntimeError(
57
+ f"required scenario clock unavailable at {SCENARIO_CLOCK_PATH}: {exc}"
58
+ ) from exc
59
+ now = datetime.now(timezone.utc).isoformat()
60
+ return {"schema_version": 1, "step": "unknown", "now": now}
61
+
62
+
63
+ def utc_now() -> str:
64
+ return scenario_clock()["now"]
65
+
66
+
67
+ def _write_json(path: Path, payload: Any) -> None:
68
+ path.write_text(
69
+ json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True, allow_nan=False)
70
+ + "\n",
71
+ encoding="utf-8",
72
+ )
73
+
74
+
75
+ def _latest_session(logs_root: Path) -> Path | None:
76
+ candidates = [
77
+ path
78
+ for pattern in ("sessions/**/rollout-*.jsonl", "sessions/**/*.jsonl")
79
+ for path in logs_root.glob(pattern)
80
+ if path.is_file() and not path.is_symlink()
81
+ ]
82
+ return max(candidates, key=lambda path: path.stat().st_mtime_ns) if candidates else None
83
+
84
+
85
+ def _oracle_run_marker(workspace_root: Path, logs_root: Path) -> bool:
86
+ """Legacy compatibility hook; workspace files never identify Oracle runs.
87
+
88
+ Evidence source selection is trajectory-first for both Oracle and real
89
+ agents. Harbor owns the lifecycle around ``oracle.txt``/``exit-code.txt``;
90
+ a file created by the agent in ``/workspace`` is never sufficient.
91
+ """
92
+ return False
93
+
94
+
95
+ def _oracle_exit_code(logs_root: Path) -> None:
96
+ """Fail closed when Harbor recorded a non-zero Oracle solution exit."""
97
+ path = logs_root / ORACLE_EXIT_CODE_FILE
98
+ if not path.is_file():
99
+ return
100
+ raw = path.read_text(encoding="utf-8").strip()
101
+ try:
102
+ code = int(raw)
103
+ except ValueError as exc:
104
+ raise RuntimeError(f"invalid Oracle exit code in {path}: {raw!r}") from exc
105
+ if code != 0:
106
+ raise RuntimeError(f"Oracle solution exited with code {code}")
107
+
108
+
109
+
110
+
111
+ def _empty_atif_bytes() -> bytes:
112
+ return (
113
+ json.dumps(
114
+ {"schema_version": "ATIF-v1.7", "steps": []},
115
+ ensure_ascii=False,
116
+ sort_keys=True,
117
+ allow_nan=False,
118
+ )
119
+ + "\n"
120
+ ).encode("utf-8")
121
+
122
+
123
+ def _trajectory_document_valid(trajectory: Any) -> bool:
124
+ """Accept the ATIF/legacy containers emitted by Harbor, not arbitrary JSON."""
125
+ if not isinstance(trajectory, dict):
126
+ return False
127
+ steps = trajectory.get("steps")
128
+ messages = trajectory.get("messages")
129
+ return isinstance(steps, list) or isinstance(messages, list)
130
+
131
+
132
+ def _validate_session_jsonl(path: Path) -> None:
133
+ """Fail closed when a discovered Codex session is empty or malformed."""
134
+ try:
135
+ lines = [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
136
+ except OSError as exc:
137
+ raise RuntimeError(f"unreadable Harbor session log: {path}") from exc
138
+ if not lines:
139
+ raise RuntimeError(f"empty Harbor session log: {path}")
140
+ for line_number, line in enumerate(lines, start=1):
141
+ try:
142
+ row = json.loads(line)
143
+ except json.JSONDecodeError as exc:
144
+ raise RuntimeError(
145
+ f"invalid Harbor session JSONL at {path}:{line_number}"
146
+ ) from exc
147
+ if not isinstance(row, dict):
148
+ raise RuntimeError(
149
+ f"invalid Harbor session record at {path}:{line_number}"
150
+ )
151
+
152
+
153
+ def _trajectory_and_items(
154
+ logs_root: Path, step_name: str, source_event_id: str, *, workspace_root: Path | None = None
155
+ ) -> tuple[bytes, str, list[dict[str, Any]], str, Path | None]:
156
+ workspace_root = Path(workspace_root) if workspace_root is not None else Path("/workspace")
157
+ # Oracle and real agents publish the same native trajectory contract. Do
158
+ # not inspect or trust any workspace call log when choosing the source.
159
+ _oracle_exit_code(logs_root)
160
+
161
+ if not logs_root.is_dir():
162
+ raise RuntimeError(f"Harbor agent log directory is unavailable: {logs_root}")
163
+ if not any(logs_root.iterdir()):
164
+ # Harbor's native NopAgent intentionally emits no files. Preserve that
165
+ # fact as an explicit empty turn instead of treating it as telemetry loss.
166
+ return _empty_atif_bytes(), "", [], "empty-agent-log", None
167
+
168
+ trajectory_path = logs_root / "trajectory.json"
169
+ trajectory_valid = False
170
+ if trajectory_path.exists():
171
+ if not trajectory_path.is_file() or trajectory_path.is_symlink():
172
+ raise RuntimeError(f"invalid Harbor trajectory path: {trajectory_path}")
173
+ raw = trajectory_path.read_bytes()
174
+ trajectory = _load_trajectory(trajectory_path)
175
+ trajectory_valid = _trajectory_document_valid(trajectory)
176
+ if not trajectory_valid:
177
+ raise RuntimeError(f"invalid Harbor trajectory: {trajectory_path}")
178
+ # Freeze only this step's turns; see atif_step_slice for why. Falls back
179
+ # to the raw bytes whenever the document is a valid legacy container.
180
+ sliced = atif_step_slice(trajectory)
181
+ if sliced is not None:
182
+ raw = (
183
+ json.dumps(sliced, ensure_ascii=False, sort_keys=True, allow_nan=False)
184
+ + "\n"
185
+ ).encode("utf-8")
186
+ text, calls = step_text_and_calls(trajectory, step_name, source_event_id)
187
+ if text.strip() or calls:
188
+ # codex rental detail unified_exec rental detail MCP callrental detail exec rental detail JS rental detail,ATIF onlyrental detail
189
+ # function_name="exec",rental detail trace rental detail MCP rental detailno,rental detail
190
+ # *_servers rental detail False。rental detailrecordonlyrental detail session jsonl rental detail
191
+ # event_msg/item_completed rental detail,rental detail。rental detail docstring。
192
+ session_path = _latest_session(logs_root)
193
+ if session_path is not None:
194
+ try:
195
+ calls = calls + _session_mcp_calls(session_path, source_event_id)
196
+ except (OSError, ValueError):
197
+ # rental detail:rental detail,rental detaildo notrental detailfailurerental detail
198
+ # "agent rental detailtool"rental detail。
199
+ pass
200
+ return raw, text, calls, "trajectory.json", None
201
+ else:
202
+ raw = _empty_atif_bytes()
203
+
204
+ session_path = _latest_session(logs_root)
205
+ if session_path is not None:
206
+ _validate_session_jsonl(session_path)
207
+ text, calls = _codex_session_items(session_path)
208
+ for call in calls:
209
+ call["event_id"] = source_event_id
210
+ calls.extend(_session_mcp_calls(session_path, source_event_id))
211
+ return raw, text, calls, "session.jsonl", session_path
212
+ if trajectory_valid:
213
+ # A valid empty ATIF document is legitimate for a no-op/empty response.
214
+ return raw, "", [], "trajectory.json", None
215
+ raise RuntimeError("Harbor produced neither a valid trajectory nor a session log")
216
+
217
+
218
+ def _replace_directory(tmp: Path, target: Path) -> None:
219
+ old: Path | None = None
220
+ if target.exists() or target.is_symlink():
221
+ old = target.parent / f".{target.name}.old-{os.getpid()}"
222
+ if old.exists() or old.is_symlink():
223
+ if old.is_dir() and not old.is_symlink():
224
+ shutil.rmtree(old)
225
+ else:
226
+ old.unlink()
227
+ os.replace(target, old)
228
+ try:
229
+ os.replace(tmp, target)
230
+ except Exception:
231
+ if old is not None and old.exists() and not target.exists():
232
+ os.replace(old, target)
233
+ raise
234
+ if old is not None:
235
+ if old.is_dir() and not old.is_symlink():
236
+ shutil.rmtree(old)
237
+ elif old.exists() or old.is_symlink():
238
+ old.unlink()
239
+
240
+
241
+ def collect_turn(
242
+ *,
243
+ workspace_root: Path,
244
+ logs_root: Path,
245
+ step_name: str,
246
+ virtual_stage: int,
247
+ source_event_id: str,
248
+ stage_boundary: bool,
249
+ ) -> Path:
250
+ """Replace the current staging bundle with evidence from this Harbor turn."""
251
+ workspace_root = Path(workspace_root)
252
+ logs_root = Path(logs_root)
253
+ stage_root = workspace_root / ".harbor-stage"
254
+ stage_root.mkdir(parents=True, exist_ok=True)
255
+ tmp = Path(tempfile.mkdtemp(prefix=".current.tmp-", dir=stage_root))
256
+ target = stage_root / "current"
257
+ try:
258
+ raw, text, calls, trajectory_source, session_path = _trajectory_and_items(
259
+ logs_root, step_name, source_event_id, workspace_root=workspace_root
260
+ )
261
+ (tmp / "trajectory.json").write_bytes(raw)
262
+ (tmp / "response.txt").write_text(text, encoding="utf-8")
263
+ _write_json(tmp / "trace.json", calls)
264
+ if session_path is not None:
265
+ shutil.copy2(session_path, tmp / "session.jsonl")
266
+
267
+
268
+ metadata = {
269
+ "schema_version": 1,
270
+ "step": step_name,
271
+ "virtual_stage": virtual_stage,
272
+ "source_event_id": source_event_id,
273
+ "stage_boundary": bool(stage_boundary),
274
+ "trajectory_source": trajectory_source,
275
+ "captured_at": utc_now(),
276
+ "scenario_clock": scenario_clock(),
277
+ }
278
+ _write_json(tmp / "metadata.json", metadata)
279
+ _replace_directory(tmp, target)
280
+ return target
281
+ finally:
282
+ if tmp.exists():
283
+ shutil.rmtree(tmp)
284
+
285
+
286
+ def _session_mcp_calls(path: Path, event_id: str | None) -> list[dict[str, Any]]:
287
+ """Extract completed MCP calls from the current Codex rollout turn."""
288
+ out: list[dict[str, Any]] = []
289
+ seen_ids: set[str] = set()
290
+ for row in _codex_current_turn_rows(path):
291
+ if row.get("type") != "event_msg":
292
+ continue
293
+ payload = row.get("payload") or {}
294
+ if payload.get("type") != "item_completed":
295
+ continue
296
+ item = payload.get("item") or {}
297
+ if item.get("type") != "McpToolCall":
298
+ continue
299
+ server = str(item.get("server") or "")
300
+ tool = str(item.get("tool") or "")
301
+ if not server or not tool or server == "codex":
302
+ continue
303
+ call_id = str(item.get("id") or ("mcp-%d" % len(out)))
304
+ if call_id in seen_ids:
305
+ continue
306
+ seen_ids.add(call_id)
307
+ arguments = item.get("arguments")
308
+ if isinstance(arguments, str):
309
+ try:
310
+ arguments = json.loads(arguments)
311
+ except json.JSONDecodeError:
312
+ arguments = {}
313
+ result = item.get("result")
314
+ out.append(
315
+ {
316
+ "event_id": event_id,
317
+ "id": call_id,
318
+ "name": f"{server}__{tool}",
319
+ "arguments": arguments if isinstance(arguments, dict) else {},
320
+ "success": item.get("status") == "completed"
321
+ and _tool_result_success({"content": result}),
322
+ "result": _jsonable(result),
323
+ }
324
+ )
325
+ return out
326
+
327
+
328
+ def main(argv: list[str] | None = None) -> int:
329
+ parser = argparse.ArgumentParser()
330
+ parser.add_argument("step_name")
331
+ parser.add_argument("virtual_stage", type=int)
332
+ parser.add_argument("source_event_id")
333
+ parser.add_argument("stage_boundary", choices=("0", "1"))
334
+ args = parser.parse_args(argv)
335
+ collect_turn(
336
+ workspace_root=Path("/workspace"),
337
+ logs_root=Path("/logs/agent"),
338
+ step_name=args.step_name,
339
+ virtual_stage=args.virtual_stage,
340
+ source_event_id=args.source_event_id,
341
+ stage_boundary=args.stage_boundary == "1",
342
+ )
343
+ return 0
344
+ if __name__ == "__main__":
345
+ raise SystemExit(main())
harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/harbor_env.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Live world access for the trusted evidence collector — capture side only.
2
+
3
+ This module belongs to the **collector**, which runs during Harbor's verifier
4
+ collect phase and freezes the world at each stage boundary. It is the one place
5
+ that is *supposed* to touch live state:
6
+
7
+ * ``getattr(env, f"{server}_mock").call_tool(tool, **kwargs)`` — real MCP reads
8
+ against the running services, used by ``snapshot_capture.py`` to build each
9
+ stage's ``snapshot.json``.
10
+ * ``env.workspace.fs`` — a read-only view of the live agent workspace at
11
+ ``/workspace``, captured into the same snapshot.
12
+
13
+ **Do not confuse this with the scoring side.** ``tests/`` has no adapter at all:
14
+ rubrics there read frozen evidence through ``tests/harbor_evidence.py``, which
15
+ has no MCP client by construction. Scoring a historical stage against live state
16
+ would silently re-score every earlier stage against the *final* world, rewarding
17
+ last-turn back-fill and punishing an agent that correctly superseded stale
18
+ values. Capture reads the live world; scoring never does.
19
+
20
+ Anything outside the slice is intentionally absent: a rubric reaching for it
21
+ should fail loudly rather than silently score zero.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import asyncio
26
+ import json
27
+ import os
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ # Ordered: the first existing root wins. /workspace is the live agent workspace
32
+ # (present when the verifier shares the main service); the evidence copy is the
33
+ # collected snapshot used for offline replay.
34
+ DEFAULT_WORKSPACE_ROOT = Path(os.environ.get("HARBOR_WORKSPACE_ROOT", "/workspace"))
35
+
36
+
37
+ def _service_host(server: str) -> str:
38
+ """docker-compose hostnames are the underscore-free capability name."""
39
+ return server.replace("_", "-")
40
+
41
+
42
+ def _unwrap_mcp(result: Any) -> Any:
43
+ """Decode a FastMCP CallToolResult into native Python.
44
+
45
+ Mirrors ``capabilities/base.py::_unwrap_mcp`` so the captured snapshot has
46
+ byte-identical shapes to the source capture — the rubrics match on nested
47
+ fields, so a different wrapper shape would fail every check.
48
+ """
49
+ if result is None:
50
+ return None
51
+ sc = getattr(result, "structuredContent", None) or getattr(result, "structured_content", None)
52
+ if isinstance(sc, dict) and "result" in sc:
53
+ value = sc["result"]
54
+ return json.loads(value) if isinstance(value, str) else value
55
+ for block in getattr(result, "content", None) or []:
56
+ text = getattr(block, "text", None)
57
+ if text:
58
+ try:
59
+ return json.loads(text)
60
+ except json.JSONDecodeError:
61
+ return text
62
+ return result
63
+
64
+
65
+ class _McpCapability:
66
+ """Read-side MCP capability used during trusted collection."""
67
+
68
+ def __init__(self, server: str) -> None:
69
+ self.server = server
70
+ host = os.environ.get(f"MCP_HOST_{server.upper()}", _service_host(server))
71
+ port = os.environ.get("MCP_PORT", "8000")
72
+ self.url = f"http://{host}:{port}/mcp"
73
+
74
+ async def _call_async(self, name: str, **kwargs: Any) -> Any:
75
+ from mcp import ClientSession
76
+ from mcp.client.streamable_http import streamablehttp_client
77
+
78
+ async with streamablehttp_client(self.url) as (read, write, _meta):
79
+ async with ClientSession(read, write) as session:
80
+ await session.initialize()
81
+ result = await session.call_tool(name, kwargs)
82
+ return _unwrap_mcp(result)
83
+
84
+ def call_tool(self, name: str, **kwargs: Any) -> Any:
85
+ return asyncio.run(self._call_async(name, **kwargs))
86
+
87
+ async def _call_sequence_async(self, requests: list[tuple[str, dict[str, Any]]]) -> list[Any]:
88
+ from mcp import ClientSession
89
+ from mcp.client.streamable_http import streamablehttp_client
90
+
91
+ results: list[Any] = []
92
+ async with streamablehttp_client(self.url) as (read, write, _meta):
93
+ async with ClientSession(read, write) as session:
94
+ await session.initialize()
95
+ for name, kwargs in requests:
96
+ try:
97
+ results.append(_unwrap_mcp(await session.call_tool(name, kwargs)))
98
+ except BaseException as exc: # noqa: BLE001 - parity with call_tool
99
+ results.append({"error": f"{type(exc).__name__}: {exc}"})
100
+ return results
101
+
102
+ def call_tool_sequence(self, requests: list[tuple[str, dict[str, Any]]]) -> list[Any]:
103
+ """Batched counterpart of :meth:`call_tool` for snapshot capture.
104
+
105
+ Every ``call_tool`` pays a full streamable-HTTP handshake plus
106
+ ``initialize`` for a single read. The stage snapshot issues hundreds of
107
+ such reads (per-message email details, per-page Notion children), and at
108
+ one-session-per-call that exceeds the collect hook budget. This method
109
+ reuses one session for the whole sequence while degrading each failed
110
+ call into the same ``{"error": ...}`` envelope ``call_tool`` produces,
111
+ so callers observe identical shapes.
112
+ """
113
+ if not requests:
114
+ return []
115
+ try:
116
+ return asyncio.run(self._call_sequence_async(requests))
117
+ except BaseException as exc: # noqa: BLE001 - parity with call_tool
118
+ return [{"error": f"{type(exc).__name__}: {exc}"} for _ in requests]
119
+
120
+
121
+ class _Fs:
122
+ """Live read-only workspace adapter used only during trusted collection."""
123
+
124
+ def __init__(self, workspace_root: Path | str = DEFAULT_WORKSPACE_ROOT) -> None:
125
+ self.workspace_root = Path(workspace_root)
126
+
127
+ def _candidate(self, path: str) -> Path:
128
+ raw = str(path).rstrip("/") or "/"
129
+ # Bare "/workspace" must resolve to the root itself. Falling through to
130
+ # the generic branch below would append "workspace/" and silently yield
131
+ # an empty listing — and because the rubrics only ask whether *any*
132
+ # workspace value is non-empty, that produces zero captured evidence
133
+ # instead of an error.
134
+ if raw == "/workspace":
135
+ return self.workspace_root
136
+ if raw.startswith("/workspace/"):
137
+ return self.workspace_root / raw[len("/workspace/") :]
138
+ return self.workspace_root / raw.lstrip("/")
139
+
140
+ def read_file(self, path: str) -> bytes:
141
+ candidate = self._candidate(path)
142
+ if not candidate.is_file() or candidate.is_symlink():
143
+ raise FileNotFoundError(path)
144
+ return candidate.read_bytes()
145
+
146
+ def exists(self, path: str) -> bool:
147
+ candidate = self._candidate(path)
148
+ return candidate.exists() and not candidate.is_symlink()
149
+
150
+ def list_dir(self, path: str) -> list[str]:
151
+ candidate = self._candidate(path)
152
+ if not candidate.is_dir() or candidate.is_symlink():
153
+ return []
154
+ return sorted(child.name for child in candidate.iterdir() if not child.is_symlink())
155
+
156
+ def write_file(self, path: str, data: bytes) -> None:
157
+ raise PermissionError("trusted collector workspace view is read-only")
158
+
159
+
160
+ class _Workspace:
161
+ def __init__(self, workspace_root: Path | str = DEFAULT_WORKSPACE_ROOT) -> None:
162
+ self.fs = _Fs(workspace_root)
163
+
164
+
165
+ class HarborEnv:
166
+ """Duck-typed ``env`` exposing ``<server>_mock`` and ``workspace``."""
167
+
168
+ def __init__(
169
+ self, servers: list[str], workspace_root: Path | str = DEFAULT_WORKSPACE_ROOT
170
+ ) -> None:
171
+ self.workspace = _Workspace(workspace_root)
172
+ self._caps: dict[str, _McpCapability] = {}
173
+ for server in servers:
174
+ cap = _McpCapability(server)
175
+ self._caps[server] = cap
176
+ setattr(self, f"{server}_mock", cap)
177
+
178
+ def capability(self, server: str) -> _McpCapability | None:
179
+ return self._caps.get(server)
harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/response_capture.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse the current Harbor trajectory into response and tool-call evidence.
2
+
3
+ This module is deliberately read-only: it never merges prior workspace files
4
+ and never writes historical evidence. The world-controller performs all
5
+ private event accumulation after this parser returns the current turn only.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Any, Iterable
12
+
13
+
14
+ def _field(obj: Any, name: str, default: Any = None) -> Any:
15
+ return obj.get(name, default) if isinstance(obj, dict) else getattr(obj, name, default)
16
+
17
+
18
+ def _jsonable(value: Any) -> Any:
19
+ try:
20
+ json.dumps(value, ensure_ascii=False)
21
+ except (TypeError, ValueError):
22
+ return str(value)
23
+ return value
24
+
25
+
26
+ def _errorish(value: Any) -> bool:
27
+ """True when a decoded payload has the mocks' error-response shape."""
28
+ if isinstance(value, str):
29
+ text = value.strip()
30
+ if not (text.startswith("{") or text.startswith("[")):
31
+ return False
32
+ try:
33
+ value = json.loads(text)
34
+ except json.JSONDecodeError:
35
+ return False
36
+ if isinstance(value, list):
37
+ return any(_errorish(item) for item in value)
38
+ if not isinstance(value, dict):
39
+ return False
40
+ if value.get("isError") is True or value.get("is_error") is True:
41
+ return True
42
+ if str(value.get("status", "")).lower() == "error":
43
+ return True
44
+ # ``error_response`` emits {"error": <message>, "code": <CODE>}. Require a
45
+ # non-empty error field so a row with error=None/"" is not counted.
46
+ return bool(value.get("error")) and "code" in value
47
+
48
+
49
+ def _tool_result_success(block: Any) -> bool:
50
+ """Whether a tool call succeeded, judged structurally.
51
+
52
+ A call is a failure only when the transport flags it, or when the payload
53
+ itself has the mocks' error shape. The previous implementation scanned the
54
+ serialized text for phrases like "not found", so a *successful* call whose
55
+ results merely contained that wording was recorded as failed.
56
+ """
57
+ if _field(block, "is_error", False) or _field(block, "isError", False):
58
+ return False
59
+ if _errorish(block):
60
+ return False
61
+ content = _field(block, "content", "")
62
+ return not _errorish(content)
63
+
64
+
65
+ def _content_blocks(message: Any) -> list[Any]:
66
+ content = _field(message, "content", "")
67
+ if isinstance(content, list):
68
+ return content
69
+ return []
70
+
71
+
72
+ def extract_assistant_text(messages: Iterable[Any]) -> str:
73
+ """Port of the source ``_extract_assistant_text`` (joins with ``\\n``)."""
74
+ chunks: list[str] = []
75
+ for message in messages or []:
76
+ if _field(message, "role") != "assistant":
77
+ continue
78
+ content = _field(message, "content", "")
79
+ if isinstance(content, str):
80
+ if content:
81
+ chunks.append(content)
82
+ continue
83
+ for block in content or []:
84
+ if _field(block, "type") == "text":
85
+ text = _field(block, "text", "") or ""
86
+ if text:
87
+ chunks.append(text)
88
+ return "\n".join(chunks)
89
+
90
+
91
+ def extract_tool_calls(messages: Iterable[Any], event_id: str | None = None) -> list[dict[str, Any]]:
92
+ """Port of the source ``_extract_tool_calls`` over ``role``/``content``."""
93
+ calls: list[dict[str, Any]] = []
94
+ by_id: dict[str, dict[str, Any]] = {}
95
+ for message in messages or []:
96
+ role = _field(message, "role")
97
+ if role == "assistant":
98
+ for block in _content_blocks(message):
99
+ if _field(block, "type", "") not in ("toolCall", "tool_call", "tool_use"):
100
+ continue
101
+ call = {
102
+ "event_id": event_id,
103
+ "id": _field(block, "id", _field(block, "tool_call_id", _field(block, "toolCallId"))),
104
+ "name": _field(block, "name"),
105
+ "arguments": _jsonable(_field(block, "arguments", _field(block, "input", {}))),
106
+ "success": None,
107
+ "result": None,
108
+ }
109
+ calls.append(call)
110
+ if call["id"] is not None:
111
+ by_id[str(call["id"])] = call
112
+ blocks = _content_blocks(message)
113
+ if role in ("user", "tool", "toolResult", "tool_result") and not blocks:
114
+ blocks = [message]
115
+ for block in blocks:
116
+ typ = _field(block, "type", "")
117
+ if typ not in ("toolResult", "tool_result") and role not in (
118
+ "tool",
119
+ "toolResult",
120
+ "tool_result",
121
+ ):
122
+ continue
123
+ tool_id = _field(
124
+ block,
125
+ "tool_use_id",
126
+ _field(block, "tool_call_id", _field(block, "toolCallId", _field(block, "id"))),
127
+ )
128
+ if tool_id is None:
129
+ continue
130
+ call = by_id.get(str(tool_id))
131
+ if call is not None:
132
+ call["success"] = _tool_result_success(block)
133
+ call["result"] = _jsonable(_field(block, "content", ""))
134
+ return calls
135
+
136
+
137
+ def _is_atif(trajectory: Any) -> bool:
138
+ steps = trajectory.get("steps") if isinstance(trajectory, dict) else None
139
+ return isinstance(steps, list) and any(
140
+ isinstance(step, dict) and "source" in step for step in steps
141
+ )
142
+
143
+
144
+ def _atif_window(trajectory: dict[str, Any]) -> list[dict[str, Any]]:
145
+ """Turns after the last user turn — the work belonging to this step.
146
+
147
+ Earlier turns belong to earlier steps; including them would replay every
148
+ previous step's prose and tool calls into each later stage.
149
+ """
150
+ steps = [step for step in trajectory.get("steps") or [] if isinstance(step, dict)]
151
+ last_user = -1
152
+ for index, step in enumerate(steps):
153
+ if str(step.get("source", "")).lower() == "user":
154
+ last_user = index
155
+ return steps[last_user + 1 :]
156
+
157
+
158
+ def atif_step_slice(trajectory: Any) -> dict[str, Any] | None:
159
+ """This step's own turns, in the ATIF envelope the verifier expects.
160
+
161
+ Harbor rewrites ``trajectory.json`` as the whole cumulative session on every
162
+ step, so step N carries steps 1..N-1 verbatim. Freezing that per stage costs
163
+ O(steps^2) on disk for no scoring value: the rubrics read only ``response``
164
+ and ``trace``, and the last step's copy already holds the full session.
165
+ Keep the envelope (``schema_version``/``session_id``/``agent``) so the file
166
+ stays a valid ATIF document. The prompt turn itself is deliberately excluded
167
+ because evidence records the agent's work after the prompt.
168
+
169
+ Returns None for non-ATIF input, leaving the caller on its raw-bytes path.
170
+ """
171
+ if not _is_atif(trajectory):
172
+ return None
173
+ steps = [step for step in trajectory.get("steps") or [] if isinstance(step, dict)]
174
+ last_user = -1
175
+ for index, step in enumerate(steps):
176
+ if str(step.get("source", "")).lower() == "user":
177
+ last_user = index
178
+ window = steps[last_user + 1 :] if last_user >= 0 else steps
179
+ sliced = {key: value for key, value in trajectory.items() if key != "steps"}
180
+ sliced["steps"] = window
181
+ return sliced
182
+
183
+
184
+ def _atif_text(trajectory: dict[str, Any]) -> str:
185
+ chunks: list[str] = []
186
+ for step in _atif_window(trajectory):
187
+ if str(step.get("source", "")).lower() != "agent":
188
+ continue
189
+ message = step.get("message")
190
+ if isinstance(message, str) and message.strip():
191
+ chunks.append(message)
192
+ elif isinstance(message, list):
193
+ for block in message:
194
+ if isinstance(block, dict) and block.get("type") == "text":
195
+ text = block.get("text") or ""
196
+ if text:
197
+ chunks.append(text)
198
+ return "\n".join(chunks)
199
+
200
+
201
+ def _atif_tool_calls(trajectory: dict[str, Any], event_id: str | None) -> list[dict[str, Any]]:
202
+ """Pair ATIF ``tool_calls`` with ``observation.results`` by ``source_call_id``."""
203
+ ordered: list[str] = []
204
+ calls: dict[str, dict[str, Any]] = {}
205
+ results: dict[str, Any] = {}
206
+ for step in _atif_window(trajectory):
207
+ if str(step.get("source", "")).lower() != "agent":
208
+ continue
209
+ for call in step.get("tool_calls") or []:
210
+ if not isinstance(call, dict):
211
+ continue
212
+ call_id = str(call.get("tool_call_id") or call.get("id") or "")
213
+ if not call_id or call_id in calls:
214
+ continue
215
+ name = call.get("function_name") or call.get("name")
216
+ function = call.get("function")
217
+ if isinstance(function, dict):
218
+ name = name or function.get("name")
219
+ arguments = function.get("arguments", call.get("arguments", {}))
220
+ else:
221
+ arguments = call.get("arguments", {})
222
+ if isinstance(arguments, str):
223
+ try:
224
+ arguments = json.loads(arguments)
225
+ except json.JSONDecodeError:
226
+ arguments = {}
227
+ calls[call_id] = {
228
+ "event_id": event_id,
229
+ "id": call_id,
230
+ "name": str(name or ""),
231
+ "arguments": arguments if isinstance(arguments, dict) else {},
232
+ "success": None,
233
+ "result": None,
234
+ }
235
+ ordered.append(call_id)
236
+ observation = step.get("observation")
237
+ rows = observation.get("results", []) if isinstance(observation, dict) else []
238
+ for row in rows:
239
+ if not isinstance(row, dict):
240
+ continue
241
+ call_id = str(row.get("source_call_id") or row.get("tool_call_id") or "")
242
+ if call_id:
243
+ results[call_id] = row.get("content")
244
+ out: list[dict[str, Any]] = []
245
+ for call_id in ordered:
246
+ call = calls[call_id]
247
+ if call_id in results:
248
+ content = results[call_id]
249
+ call["success"] = _tool_result_success({"content": content})
250
+ call["result"] = _jsonable(content)
251
+ out.append(call)
252
+ return out
253
+
254
+
255
+ def _messages_for_step(trajectory: Any, step_name: str) -> list[Any]:
256
+ """``role``/``content`` messages for this step, for non-ATIF dialects."""
257
+ if not isinstance(trajectory, dict):
258
+ return []
259
+ steps = trajectory.get("steps")
260
+ if isinstance(steps, list):
261
+ for step in steps:
262
+ if isinstance(step, dict) and step.get("name") == step_name:
263
+ messages = step.get("messages")
264
+ return messages if isinstance(messages, list) else []
265
+ return []
266
+ messages = trajectory.get("messages")
267
+ return messages if isinstance(messages, list) else []
268
+
269
+
270
+ def _codex_is_user_turn(row: Any) -> bool:
271
+ """Whether a Codex rollout record starts a new user turn."""
272
+ if not isinstance(row, dict):
273
+ return False
274
+ payload = row.get("payload") or {}
275
+ if row.get("type") == "event_msg":
276
+ return str(payload.get("type", "")).lower() in {
277
+ "user_message",
278
+ "user_turn",
279
+ "user",
280
+ }
281
+ if row.get("type") == "response_item":
282
+ return payload.get("type") == "message" and str(payload.get("role", "")).lower() == "user"
283
+ return False
284
+
285
+
286
+ def _codex_session_rows(path: Path) -> list[dict[str, Any]]:
287
+ """Read valid JSON objects from a Codex rollout JSONL file."""
288
+ try:
289
+ lines = path.read_text(encoding="utf-8").splitlines()
290
+ except OSError:
291
+ return []
292
+ rows: list[dict[str, Any]] = []
293
+ for line in lines:
294
+ line = line.strip()
295
+ if not line:
296
+ continue
297
+ try:
298
+ row = json.loads(line)
299
+ except json.JSONDecodeError:
300
+ continue
301
+ if isinstance(row, dict):
302
+ rows.append(row)
303
+ return rows
304
+
305
+
306
+ def _codex_current_turn_rows(path: Path) -> list[dict[str, Any]]:
307
+ """Return only records after the final user turn in a cumulative rollout."""
308
+ rows = _codex_session_rows(path)
309
+ last_user = -1
310
+ for index, row in enumerate(rows):
311
+ if _codex_is_user_turn(row):
312
+ last_user = index
313
+ return rows[last_user + 1 :]
314
+
315
+
316
+ def _codex_session_items(path: Path) -> tuple[str, list[dict[str, Any]]]:
317
+ """Read a Codex session JSONL into (prose, tool calls).
318
+
319
+ Harbor's codex agent converts sessions to ATIF *on the host*, so the
320
+ container only ever has ``/logs/agent/sessions/**/rollout-*.jsonl``. Reading
321
+ it directly is what keeps the Tool Call and Final buckets scorable — without
322
+ this the verifier sees an empty trajectory and those 20 points are
323
+ unreachable no matter what the agent did.
324
+ """
325
+ texts: list[str] = []
326
+ calls: dict[str, dict[str, Any]] = {}
327
+ order: list[str] = []
328
+ outputs: dict[str, Any] = {}
329
+ for row in _codex_current_turn_rows(path):
330
+ if row.get("type") != "response_item":
331
+ continue
332
+ payload = row.get("payload") or {}
333
+ kind = payload.get("type")
334
+ if kind == "message" and payload.get("role") == "assistant":
335
+ for block in payload.get("content") or []:
336
+ if isinstance(block, dict):
337
+ text = block.get("text") or ""
338
+ if text:
339
+ texts.append(text)
340
+ elif kind == "function_call":
341
+ call_id = str(payload.get("call_id") or "")
342
+ if not call_id:
343
+ continue
344
+ args = payload.get("arguments")
345
+ if isinstance(args, str):
346
+ try:
347
+ args = json.loads(args)
348
+ except json.JSONDecodeError:
349
+ args = {}
350
+ calls[call_id] = {
351
+ "event_id": None,
352
+ "id": call_id,
353
+ "name": str(payload.get("name") or ""),
354
+ "arguments": args if isinstance(args, dict) else {},
355
+ "success": None,
356
+ "result": None,
357
+ }
358
+ order.append(call_id)
359
+ elif kind == "function_call_output":
360
+ call_id = str(payload.get("call_id") or "")
361
+ if call_id:
362
+ outputs[call_id] = payload.get("output")
363
+ out: list[dict[str, Any]] = []
364
+ for call_id in order:
365
+ call = calls[call_id]
366
+ if call_id in outputs:
367
+ content = outputs[call_id]
368
+ call["success"] = _tool_result_success({"content": content})
369
+ call["result"] = _jsonable(content)
370
+ out.append(call)
371
+ return "\n".join(texts), out
372
+
373
+
374
+ def _load_trajectory(path: Path) -> Any:
375
+ if not path.is_file():
376
+ return None
377
+ try:
378
+ return json.loads(path.read_text(encoding="utf-8"))
379
+ except (OSError, json.JSONDecodeError):
380
+ return None
381
+
382
+
383
+ def step_text_and_calls(
384
+ trajectory: Any, step_name: str, event_id: str | None
385
+ ) -> tuple[str, list[dict[str, Any]]]:
386
+ """Prose and tool calls for one Harbor step, whichever dialect was written."""
387
+ if not isinstance(trajectory, dict):
388
+ return "", []
389
+ if _is_atif(trajectory):
390
+ return _atif_text(trajectory), _atif_tool_calls(trajectory, event_id)
391
+ messages = _messages_for_step(trajectory, step_name)
392
+ return extract_assistant_text(messages), extract_tool_calls(messages, event_id)
harbor/rental/renewal_negotiation_repair_rental/environment/evidence-collector/snapshot_capture.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture the authoritative stage-boundary world through MCP.
2
+
3
+ The world-controller invokes this module only in its sidecar phase. All world
4
+ mutations visible to the step were applied before the agent turn; no trailing
5
+ mutation is allowed between response collection and snapshot publication. The returned dictionary is written directly into the
6
+ private evidence volume; this module never materializes historical files in the
7
+ agent workspace.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ SCENARIO_CLOCK_PATH = Path(
17
+ os.environ.get("WORLD_CLOCK_FILE", "/world-clock/current.json")
18
+ )
19
+ SCENARIO_CLOCK_REQUIRED = os.environ.get("WORLD_CLOCK_REQUIRED", "0") == "1"
20
+
21
+ USER_ID = "usr_lin_che"
22
+ CALENDAR_ID = "cal_lin_primary"
23
+
24
+
25
+ def scenario_clock() -> dict[str, Any]:
26
+ try:
27
+ payload = json.loads(SCENARIO_CLOCK_PATH.read_text(encoding="utf-8"))
28
+ if not isinstance(payload.get("step"), str) or not isinstance(payload.get("now"), str):
29
+ raise ValueError("invalid scenario clock payload")
30
+ return {"schema_version": 1, "step": payload["step"], "now": payload["now"]}
31
+ except Exception as exc:
32
+ if SCENARIO_CLOCK_REQUIRED:
33
+ raise RuntimeError(
34
+ f"required scenario clock unavailable at {SCENARIO_CLOCK_PATH}: {exc}"
35
+ ) from exc
36
+ return {"schema_version": 1, "step": "unknown", "now": ""}
37
+
38
+
39
+ # Copied verbatim from the source task.py. The rubrics assert on these exact ids.
40
+ TRACKED_JOB_IDS = (
41
+ "job_mj_214",
42
+ "job_yr_098",
43
+ "job_qs_507",
44
+ "job_lh_332",
45
+ "job_jh_126",
46
+ "job_ba_773",
47
+ "job_eb2508",
48
+ "job_4437d4",
49
+ "job_08caa9",
50
+ "job_fbc2b6",
51
+ "job_86f824",
52
+ "job_361030",
53
+ "job_541371",
54
+ "job_adcf31",
55
+ )
56
+
57
+ TRACKED_APPLICATION_IDS = (
58
+ "app_mj_001",
59
+ "app_39f15c",
60
+ "app_9cfb94",
61
+ "app_a935d7",
62
+ "app_b323c6",
63
+ "app_ca54c7",
64
+ "app_308e6e",
65
+ "app_0a108f",
66
+ "app_6ebad5",
67
+ "app_bc0d7e",
68
+ )
69
+
70
+ TRACKED_LEGAL_IDS = {
71
+ "cases": (
72
+ "case_noncompete_comp",
73
+ "case_probation_salary",
74
+ "case_employee_work",
75
+ "case_customer_data",
76
+ "case_clause_scope",
77
+ "case_confidentiality",
78
+ "case_0b9fb5e5",
79
+ "case_91df21d0",
80
+ "case_32e71e2d",
81
+ "case_c202b143",
82
+ "case_9e37bba0",
83
+ ),
84
+ "statutes": (
85
+ "stat_labor_contract",
86
+ "stat_personal_info",
87
+ "stat_civil_code",
88
+ "stat_52e9ebd7",
89
+ "stat_b8e3b12b",
90
+ "stat_aa45041c",
91
+ "stat_53e861d3",
92
+ "stat_8f9c2ba0",
93
+ "stat_fdb02184",
94
+ "stat_fb08641d",
95
+ ),
96
+ "articles": (
97
+ "art_labor_19",
98
+ "art_labor_20",
99
+ "art_labor_23",
100
+ "art_labor_24",
101
+ "art_pipl_6",
102
+ "art_civil_privacy",
103
+ "art_87d7abfc",
104
+ "art_4cb3c589",
105
+ "art_314eb23c",
106
+ "art_41be0315",
107
+ "art_a67caa73",
108
+ "art_c6e4419e",
109
+ ),
110
+ }
111
+
112
+ # Workspace files shipped as baseline context. The source snapshot excludes them
113
+ # so that seeded prose can never be mistaken for the agent's own writing. The
114
+ # exclusion is content-aware: ARTIFACT_CONTRACT.md makes some of these files
115
+ # (BUDGET_LEDGER.md among them) agent-maintained deliverables, so a file that
116
+ # diverged from the shipped baseline is the agent's own writing and is captured.
117
+ BASELINE_WORKSPACE_NAMES = {
118
+ "AGENTS.md",
119
+ "ARTIFACT_CONTRACT.md",
120
+ "AUTHORIZATION.md",
121
+ "BUDGET_LEDGER.md",
122
+ "COMPENSATION.md",
123
+ "COMMUTE_POLICY.md",
124
+ "IDENTITY.md",
125
+ "INTERVIEW_PREP.md",
126
+ "LEASE_CHECKLIST_TEMPLATE.md",
127
+ "PERSONA.md",
128
+ "PRIVACY_POLICY.md",
129
+ "REFERENCES.md",
130
+ "RENTAL_REQUIREMENTS.md",
131
+ "RESUME_PROFILE.md",
132
+ "SOUL.md",
133
+ "TRACKER_TEMPLATE.md",
134
+ "TOOLS.md",
135
+ "USER.md",
136
+ }
137
+ # Pristine copies of the seeded workspace, baked into the world-controller
138
+ # image (see world-controller/Dockerfile). Content comparison against these
139
+ # decides whether a baseline-named file is still seed text or agent work.
140
+ BASELINE_WORKSPACE_ROOT = Path(
141
+ os.environ.get("WORLD_BASELINE_WORKSPACE", "/opt/workspace-baseline")
142
+ )
143
+ ALLOWED_WORKSPACE_SUFFIXES = (".md", ".txt", ".json", ".csv")
144
+
145
+
146
+ def _decode(value: Any) -> Any:
147
+ """Mirror of the source ``_decode_tool_value`` for JSON-in-string results."""
148
+ if isinstance(value, str):
149
+ try:
150
+ return json.loads(value)
151
+ except json.JSONDecodeError:
152
+ return value
153
+ return value
154
+
155
+
156
+ def _unwrap_envelope(value: Any, fetch_page: Any = None) -> Any:
157
+ """Normalize the canonical paginated MCP envelope into a complete list."""
158
+ if not isinstance(value, dict):
159
+ return value
160
+ rows = value.get("items")
161
+ if not isinstance(rows, list) or ("total" not in value and "has_more" not in value):
162
+ return value
163
+ merged = list(rows)
164
+ total = value.get("total")
165
+ page = int(value.get("page") or 1)
166
+ size = int(value.get("page_size") or len(rows) or 1)
167
+ while value.get("has_more") and fetch_page is not None:
168
+ page += 1
169
+ nxt = fetch_page(page)
170
+ if not isinstance(nxt, dict) or not isinstance(nxt.get("items"), list):
171
+ value["_pagination_incomplete"] = True
172
+ break
173
+ fresh = nxt["items"]
174
+ merged.extend(fresh)
175
+ value = nxt
176
+ if total is not None and len(merged) >= int(total):
177
+ break
178
+ if total is not None and len(merged) < int(total):
179
+ value["_pagination_incomplete"] = True
180
+ return merged
181
+
182
+
183
+ def _call(env: Any, server: str, tool: str, **kwargs: Any) -> Any:
184
+ """Mirror of the source ``_snapshot_call``: never raise, record the error.
185
+
186
+ A failed capability read must land in the snapshot as ``{"error": ...}``
187
+ exactly as the source recorded it, so a broken server produces failing checks
188
+ with a diagnosable cause instead of aborting the whole verifier.
189
+ """
190
+ cap = getattr(env, f"{server}_mock", None)
191
+ if cap is None:
192
+ return {"error": f"missing capability: {server}"}
193
+ try:
194
+ decoded = _decode(cap.call_tool(tool, **kwargs))
195
+ return _unwrap_envelope(decoded, lambda page: _decode(cap.call_tool(tool, **{**kwargs, "page": page})))
196
+ except BaseException as exc: # noqa: BLE001 - parity with source behaviour
197
+ return {"error": f"{type(exc).__name__}: {exc}"}
198
+
199
+
200
+ def _batch_call(env: Any, server: str, requests: list[tuple[str, dict[str, Any]]]) -> list[Any]:
201
+ """Run many reads against one server while paying for a single session.
202
+
203
+ Same never-raise contract as :func:`_call`: a missing capability or a dead
204
+ connection degrades into one ``{"error": ...}`` envelope per request instead
205
+ of aborting the capture. Results keep positional order.
206
+ """
207
+ cap = getattr(env, f"{server}_mock", None)
208
+ if cap is None:
209
+ return [{"error": f"missing capability: {server}"} for _ in requests]
210
+ batch = getattr(cap, "call_tool_sequence", None)
211
+ if batch is None:
212
+ return [_call(env, server, name, **kwargs) for name, kwargs in requests]
213
+ try:
214
+ results = batch([(name, dict(kwargs)) for name, kwargs in requests])
215
+ except BaseException as exc: # noqa: BLE001 - parity with _call behaviour
216
+ return [{"error": f"{type(exc).__name__}: {exc}"} for _ in requests]
217
+ return [
218
+ value
219
+ if isinstance(value, dict) and set(value) == {"error"}
220
+ else _unwrap_envelope(_decode(value))
221
+ for value in results
222
+ ]
223
+
224
+
225
+ def _paged_call(
226
+ env: Any, server: str, tool: str, *, rows_key: str, id_keys: tuple[str, ...], **kwargs: Any
227
+ ) -> Any:
228
+ """Walk every page of a paginated tool and merge the rows.
229
+
230
+ The email mock clamps ``page_size`` to 50 (``utils/validators.py``) and
231
+ signals the clamp only by echoing the applied value, so one large request
232
+ silently returns a prefix: the seeded INBOX holds 193 messages, of which a
233
+ single request captures 50. Evidence that never enters the snapshot can
234
+ never be scored, so the walk continues until the accumulated rows reach the
235
+ reported total. Rows are merged back into the first page's envelope, leaving
236
+ the stored shape unchanged for consumers.
237
+ """
238
+ first = _call(env, server, tool, page=1, page_size=200, **kwargs)
239
+ if not isinstance(first, dict):
240
+ return first
241
+
242
+ def _row_id(row: Any) -> str:
243
+ if not isinstance(row, dict):
244
+ return ""
245
+ for key in id_keys:
246
+ if row.get(key) is not None:
247
+ return str(row[key])
248
+ return ""
249
+
250
+ merged = [row for row in (first.get(rows_key) or []) if isinstance(row, dict)]
251
+ applied = int(first.get("page_size") or 0) or max(len(merged), 1)
252
+ raw_total = first.get("total_results", first.get("total"))
253
+ total = int(raw_total) if isinstance(raw_total, (int, float)) else None
254
+ seen = {_row_id(row) for row in merged}
255
+ page = 2
256
+ # The folder cannot need more pages than it has rows; +1 tolerates a total
257
+ # that grew between calls rather than silently stopping short.
258
+ max_pages = ((total + applied - 1) // applied + 1) if total else 1
259
+ while total is not None and len(merged) < total and page <= max_pages:
260
+ nxt = _call(env, server, tool, page=page, page_size=applied, **kwargs)
261
+ if not isinstance(nxt, dict):
262
+ break
263
+ # An out-of-range page is clamped to the last page rather than returning
264
+ # empty, so stop on the first page that yields nothing new.
265
+ fresh = [
266
+ row
267
+ for row in (nxt.get(rows_key) or [])
268
+ if isinstance(row, dict) and _row_id(row) not in seen
269
+ ]
270
+ if not fresh:
271
+ break
272
+ seen.update(_row_id(row) for row in fresh)
273
+ merged.extend(fresh)
274
+ page += 1
275
+ first[rows_key] = merged
276
+ first["captured_count"] = len(merged)
277
+ if total is not None:
278
+ first["captured_complete"] = len(merged) >= total
279
+ return first
280
+
281
+
282
+ def _email_listing(env: Any, folder: str) -> Any:
283
+ return _paged_call(
284
+ env, "email", "get_emails",
285
+ rows_key="emails", id_keys=("email_id", "id"), folder=folder,
286
+ )
287
+
288
+
289
+ def _email_snapshot(env: Any, folder: str, *, include_body: bool) -> dict[str, Any]:
290
+ """Capture a folder's listing plus per-message detail.
291
+
292
+ Detail merges ``read_email`` (body) with ``get_email_headers``
293
+ (``in_reply_to`` / ``references``). Both calls are required: the mock's
294
+ ``read_email`` projection deliberately omits threading headers, but
295
+ ``_helpers.sent_message_matches`` matches ``thread_message_id`` against
296
+ ``in_reply_to``/``references``. Capturing only ``read_email`` therefore makes
297
+ every threaded-reply check unreachable no matter what the agent does — the
298
+ reply is in Sent, correctly threaded in the database, and still scores zero.
299
+
300
+ The per-message calls are issued as one batched sequence over a single MCP
301
+ session (see ``_McpCapability.call_tool_sequence``). At one session per
302
+ call, the seeded INBOX alone costs roughly 2 x 193 full HTTP handshakes per
303
+ stage, which is what pushed the collect hook past its timeout budget.
304
+ """
305
+ listing = _email_listing(env, folder)
306
+ if not include_body or not isinstance(listing, dict):
307
+ return {"listing": listing, "details": []}
308
+ email_ids: list[str] = []
309
+ for item in listing.get("emails") or []:
310
+ if not isinstance(item, dict):
311
+ continue
312
+ email_id = item.get("email_id") or item.get("id")
313
+ if email_id is None:
314
+ continue
315
+ email_ids.append(str(email_id))
316
+ detail_results = _batch_call(
317
+ env, "email", [("read_email", {"email_id": email_id}) for email_id in email_ids]
318
+ )
319
+ header_results = _batch_call(
320
+ env, "email", [("get_email_headers", {"email_id": email_id}) for email_id in email_ids]
321
+ )
322
+ details: list[Any] = []
323
+ for detail, headers in zip(detail_results, header_results):
324
+ if isinstance(detail, dict) and isinstance(headers, dict):
325
+ for key in ("in_reply_to", "references", "references_header", "headers", "thread_id"):
326
+ if headers.get(key) is not None:
327
+ detail.setdefault(key, headers[key])
328
+ details.append(detail)
329
+ return {"listing": listing, "details": details}
330
+
331
+
332
+ def _baseline_unchanged(name: str, path: str, fs: Any) -> bool:
333
+ """True when a baseline-named workspace file still matches the shipped seed.
334
+
335
+ Unreadable entries stay excluded, matching the legacy behaviour for
336
+ anything that is not a readable file; a missing shipped baseline is also
337
+ treated as unchanged so the capture degrades to the legacy exclusion rather
338
+ than freezing unverifiable content.
339
+ """
340
+ try:
341
+ raw = fs.read_file(path)
342
+ except Exception: # noqa: BLE001 - directories and unreadable paths
343
+ return True
344
+ try:
345
+ seed = (BASELINE_WORKSPACE_ROOT / name).read_bytes()
346
+ except OSError:
347
+ return True
348
+ data = raw if isinstance(raw, bytes) else str(raw).encode("utf-8", errors="replace")
349
+ return data == seed
350
+
351
+
352
+ def _workspace_snapshot(env: Any) -> dict[str, str]:
353
+ """Agent-authored workspace files, unchanged baseline context excluded."""
354
+ fs = getattr(getattr(env, "workspace", None), "fs", None)
355
+ if fs is None:
356
+ return {}
357
+ out: dict[str, str] = {}
358
+ seen: set[str] = set()
359
+
360
+ def visit(path: str, depth: int) -> None:
361
+ if path in seen or len(out) >= 200:
362
+ return
363
+ seen.add(path)
364
+ name = path.rsplit("/", 1)[-1]
365
+ if name in BASELINE_WORKSPACE_NAMES and _baseline_unchanged(name, path, fs):
366
+ return
367
+ # Harness/verifier scratch is not agent output. Capturing it would let
368
+ # the reference oracle's own bookkeeping satisfy content checks that are
369
+ # supposed to be earned by the durable ledger.
370
+ if name.startswith("."):
371
+ return
372
+ if name.lower().endswith(ALLOWED_WORKSPACE_SUFFIXES):
373
+ try:
374
+ raw = fs.read_file(path)
375
+ except Exception: # noqa: BLE001
376
+ raw = None
377
+ if raw is not None:
378
+ text = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else str(raw)
379
+ if text.strip():
380
+ out[path] = text[:200000]
381
+ return
382
+ if depth <= 0:
383
+ return
384
+ try:
385
+ children = fs.list_dir(path)
386
+ except Exception: # noqa: BLE001
387
+ return
388
+ for child in children:
389
+ visit(f"{path.rstrip('/')}/{child}", depth - 1)
390
+
391
+ # Harbor mounts the agent workspace at /workspace; the captured keys are
392
+ # therefore Harbor-native paths. The rubrics treat this map opaquely (they
393
+ # only read its values), so the key spelling is free to be native.
394
+ visit("/workspace", 4)
395
+ return out
396
+
397
+
398
+ def _notion_snapshot(env: Any) -> dict[str, Any]:
399
+ """Pages plus database rows and their children.
400
+
401
+ ``API-post-search`` returns pages/databases but not database rows, so rows
402
+ are queried explicitly and their children captured separately — without this
403
+ the ledger checks read an empty Notion and fail for the wrong reason.
404
+
405
+ The per-object child reads go out as batched sequences over one session;
406
+ hundreds of single-session calls here were a second large contributor to
407
+ the stage collect timeout.
408
+ """
409
+ page_search = _call(
410
+ env,
411
+ "notion",
412
+ "API-post-search",
413
+ query="",
414
+ filter={"value": "page", "property": "object"},
415
+ page_size=100,
416
+ )
417
+ database_search = _call(
418
+ env,
419
+ "notion",
420
+ "API-post-search",
421
+ query="",
422
+ filter={"value": "database", "property": "object"},
423
+ page_size=100,
424
+ )
425
+
426
+ def _ids(payload: Any) -> list[str]:
427
+ if not isinstance(payload, dict):
428
+ return []
429
+ return [
430
+ str(item["id"])
431
+ for item in payload.get("results") or []
432
+ if isinstance(item, dict) and item.get("id")
433
+ ]
434
+
435
+ page_ids = _ids(page_search)
436
+ page_results = _batch_call(
437
+ env,
438
+ "notion",
439
+ [
440
+ ("API-get-block-children", {"block_id": page_id, "page_size": 100})
441
+ for page_id in page_ids
442
+ ],
443
+ )
444
+ page_blocks = dict(zip(page_ids, page_results))
445
+
446
+ database_rows: dict[str, Any] = {}
447
+ row_children: dict[str, Any] = {}
448
+ database_ids = _ids(database_search)
449
+ db_results = _batch_call(
450
+ env,
451
+ "notion",
452
+ [
453
+ ("API-post-database-query", {"database_id": database_id, "page_size": 100})
454
+ for database_id in database_ids
455
+ ],
456
+ )
457
+ row_ids: list[str] = []
458
+ row_requests: list[tuple[str, dict[str, Any]]] = []
459
+ for database_id, rows in zip(database_ids, db_results):
460
+ database_rows[database_id] = rows
461
+ for row_id in _ids(rows):
462
+ row_ids.append(row_id)
463
+ row_requests.append(("API-get-block-children", {"block_id": row_id, "page_size": 100}))
464
+ row_results = _batch_call(env, "notion", row_requests)
465
+ row_children = dict(zip(row_ids, row_results))
466
+ return {
467
+ "pages": page_search,
468
+ "databases": database_search,
469
+ "page_blocks": page_blocks,
470
+ "database_rows": database_rows,
471
+ "row_children": row_children,
472
+ }
473
+
474
+
475
+ def capture_stage_snapshot(env: Any, stage_idx: int) -> dict[str, Any]:
476
+ """Capture all task services at a stage boundary."""
477
+ listing_ids = ("bjr_4f2a9c1e", "bjr_8d71c4b0", "bjr_2c9e6a57", "bjr_9a5d0c73")
478
+ place_ids = ("bjp_61c4f20a", "bjp_7ad2e985", "bjp_3f8c1b76", "bjp_84e1c7d3")
479
+ merchant_ids = ("bjm_41d7a2c9", "bjm_72c4e8a1", "bjm_93a5d0f6")
480
+ return {
481
+ "stage": stage_idx, "scenario_clock": scenario_clock(),
482
+ "listing_platform": {"search": _call(env, "listing_platform", "search_listings", category="rent", city="Beijing", limit=200), "details": {i: _call(env, "listing_platform", "get_listing_detail", listing_id=i) for i in listing_ids}},
483
+ "maps": {"places": {i: _call(env, "maps", "get_place_details", place_id=i) for i in place_ids}},
484
+ "calendar": {"events": _call(env, "calendar", "list_events", calendar_id="cal_hanqi_main", max_results=500)},
485
+ "email": {"inbox": _email_snapshot(env, "INBOX", include_body=True), "sent": _email_snapshot(env, "Sent", include_body=True), "drafts": _paged_call(env, "email", "get_drafts", rows_key="drafts", id_keys=("draft_id", "id"))},
486
+ "notification_hub": {"subscriptions": _call(env, "notification_hub", "list_subscriptions", user_id="hanqi_rental"), "notifications": _call(env, "notification_hub", "list_notifications", user_id="hanqi_rental", limit=500)},
487
+ "review_platform": {"merchants": {i: _call(env, "review_platform", "get_merchant", merchant_id=i) for i in merchant_ids}, "reviews": {i: _call(env, "review_platform", "list_reviews", merchant_id=i, limit=100) for i in merchant_ids}},
488
+ "legal_search": {"cases": _call(env, "legal_search", "search_cases", keyword="lease", limit=100), "statutes": _call(env, "legal_search", "search_statutes", keyword="rental", limit=100)},
489
+ "workspace": _workspace_snapshot(env), "notion": _notion_snapshot(env),
490
+ }
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/calendar/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # calendar env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `events` | rental detail | 225 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/calendar/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/email/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # email env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `messages` | rental detail | 213 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/email/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/legal_search/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # legal_search env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `cases` | rental detail | 213 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/legal_search/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/listing_platform/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # listing_platform env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `listings` | rental detail | 240 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/listing_platform/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/maps/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # maps env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `places` | rental detail | 230 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/maps/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notification_hub/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # notification_hub env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `notifications` | rental detail | 220 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notification_hub/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notion/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # notion env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:rental detailrental housingworkspacerental detailnoise,agent rental detail tracker、budget、risk、auth、lease rental detail final rental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail task/rubric rental detail:Notion rental detaillistingrental detailentrance,rental detailstatusrental detail;seed rental detailonlyrental detailrental housingrental detailnoise,rental detail `rr007_current_home`、`rr007_backup_viable`、850000/858000 rental detailquoteconclusion。checker stillrental detail stage-local notion tool trace、workspace rental detail MCP rental detail agent rental detail。
6
+
7
+ statusrental detail:pages rental detail `reference/background/archive/noise` rental detailstatus;rental detail Notion seed。
8
+
9
+ rental detail:
10
+
11
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
12
+ |---|---|---:|---|---|---|
13
+ | `pages` | rental detail | 221 | Notion rental detailstatusrental detail、rental detailnoise / `s0_*`、`s2_tracker_persisted`、`s5_*`、`s20_*`、`s23_*` | 220 rental detailonlyrental detailrental housingrental detaildo not、statusrental detailcity,rental detaillisting ID、quoterental detailconclusion;agent rental detail last_edited_time updatedrental detail | rental detail |
14
+ | `users` | rental detail | 1 | rental detail | rental detail | rental detail |
15
+ | `workspaces` | rental detail | 1 | rental detail | rental detail | rental detail |
16
+ | `counters` | rental detail | 1 | rental detail | rental detail | rental detail |
17
+
18
+ rental detail smoke test:server rental detail init.sql;rental detail `API-post-search` searchrental detail,rental detail agent rental detailupdatedrental detail last_edited_time rental detailnoisebefore。
19
+
20
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/notion/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/review_platform/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # review_platform env for renewal_negotiation_repair_rental
2
+
3
+ rental detail:renewalrental detailrepair responsibilityrental detail。rental detail 2026-07-12 rental detail 2026-08-16,rental detail Asia/Shanghai。
4
+
5
+ rental detail:rr007_current_home、rr007_low_price_risk、rr007_backup_viable、pl_rr007_work、pl_rr007_current、pl_rr007_backup、rv_rr007_current、rv_rr007_backup。rental detaillistingrental detail、commute、repairrisk、rental detail、statusrefreshrental detailfinal archive。
6
+
7
+ rental detail task/rubric rental detail:rubric rental detailtool trace、rental detailstatusrental detail agent rental detailrefresh、rental detailchangerental detail。
8
+
9
+ statusrental detail:rental detail minor CNYrental detail;850000 rental detail 8500 CNY。statusrental detail active、delisted、pending、draft rental detail。
10
+
11
+ rental detail:
12
+
13
+ | rental detail | rental detail | rental detail | rental detail/check | rental detail | rental detail |
14
+ |---|---|---:|---|---|---|
15
+ | `reviews` | rental detail | 445 | renewalrental detail、repair responsibility、commute/rental detail/rental detail/notificationrental detail | rental detailretainrental detailprice、rental detail、ID、rental detailstatusrental detail,rental detailevidencestillrental detail | rental detail |
16
+
17
+ rental detail smoke test:server rental detail init.sql;rental detail MCP list/search/get toolreadrental detail。
18
+
19
+ rental detailsource:rental detail,rental detail。
harbor/rental/renewal_negotiation_repair_rental/environment/seeds/review_platform/init.sql ADDED
The diff for this file is too large to render. See raw diff
 
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ .uv/
6
+ *.db
7
+ *.db-wal
8
+ *.db-shm
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ build/
13
+ dist/
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY pyproject.toml README.md ./
6
+ COPY src ./src
7
+ RUN pip install --no-cache-dir .
8
+
9
+ EXPOSE 8000
10
+
11
+ ENTRYPOINT ["/bin/sh", "-c", "mkdir -p /env && cp -r /env-seed/. /env/ && exec calendar-mock --host 0.0.0.0 --port 8000 --env /env"]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mock-env contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/README.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # calendar-mock
2
+
3
+ A FastMCP-based, fully-offline mock of a Google-Calendar-style backend. Runs
4
+ over **streamable-HTTP** (no stdio) with a local SQLite database. Replaces
5
+ the legacy Node + PostgreSQL `Calendar-Autoauth-MCP-Server` with the same
6
+ agent-facing surface.
7
+
8
+ See [SPEC.md](./SPEC.md) for the full implementer-facing specification.
9
+
10
+ ## Tools (agent-facing)
11
+
12
+ - `list_calendars(user_id)` — calendars owned by a user.
13
+ - `list_events(time_min?, time_max?, calendar_id?, max_results=20, order_by="startTime")`
14
+ - `get_event(event_id, calendar_id?)` — full detail incl. attendees + reminders.
15
+ - `create_event(summary, start, end, description?, location?, calendar_id?, attendees?, reminders?)`
16
+ - `update_event(event_id, summary?, start?, end?, description?, location?, calendar_id?, status?)`
17
+ - `delete_event(event_id, calendar_id?)`
18
+ - `search_events(query, time_min?, time_max?, max_results=50)` — substring
19
+ match over summary / description / location / attendee email or name.
20
+
21
+ No admin tool / no clock. Recurring events store an `recurrence_rule` for
22
+ round-tripping but are not auto-materialized — env init.sql is responsible
23
+ for inserting whichever concrete child rows the task needs.
24
+
25
+ `start` / `end` are ISO 8601 datetimes (e.g. `2026-05-08T18:30:00+08:00`).
26
+
27
+ ## Quick start
28
+
29
+ ### Direct (Python)
30
+
31
+ ```bash
32
+ # From this directory
33
+ pip install -e .
34
+
35
+ # Run against the bundled env.
36
+ calendar-mock \
37
+ --port 8000 \
38
+ --env ../../envs/calendar/li_wei_may
39
+ ```
40
+
41
+ The server writes a fresh `runtime.db` inside the env directory on every
42
+ cold start, applies the bundled schema, then executes
43
+ `<env>/init.sql` if present.
44
+
45
+ ### Docker
46
+
47
+ ```bash
48
+ docker build -t calendar-mock .
49
+ docker run --rm -p 8000:8000 \
50
+ -v $PWD/../../envs/calendar/li_wei_may:/env-seed:ro \
51
+ calendar-mock
52
+ ```
53
+
54
+ The streamable-HTTP endpoint is at `http://<host>:<port>/mcp`.
55
+
56
+ ## CLI flags
57
+
58
+ - `--host` (default `0.0.0.0`)
59
+ - `--port` (pass `8000` for Docker/Terrarium parity)
60
+ - `--env PATH` — env directory (`runtime.db` lives inside; optional `init.sql` is applied)
61
+ - `--debug` — verbose logging
62
+
63
+ To boot stateless, point `--env` at `../../envs/calendar/empty`.
64
+
65
+ ## Smoke test
66
+
67
+ ```bash
68
+ python3 scripts/smoke_http.py
69
+ ```
70
+
71
+ Spins up the server in a subprocess on a free port, applies
72
+ `envs/calendar/li_wei_may/init.sql`, and round-trips
73
+ `list_calendars`, `list_events`, `get_event`, `search_events`,
74
+ `create_event`, `update_event`, `delete_event`, plus error paths. Prints
75
+ `PASS` or `FAIL`.
76
+
77
+ ## Errors
78
+
79
+ Every tool returns valid JSON. Errors come back as
80
+ `{"error": "<msg>", "code": "<CODE>"}` — never as exceptions. Stable codes:
81
+
82
+ `EVENT_NOT_FOUND`, `CALENDAR_NOT_FOUND`, `BAD_TIME_RANGE`, `BAD_DATE`,
83
+ `OVERLAPPING_EVENT`, `BAD_ARG`.
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/SPEC.md ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # calendar_mock — Specification
2
+
3
+ Status: v1 (implementer-facing)
4
+ Scope: implementation spec for the `calendar-mock` MCP server.
5
+
6
+ ## 1. Purpose
7
+
8
+ `calendar_mock` is a self-contained, fully-offline mock of a
9
+ Google-Calendar-style backend — calendars, events, attendees, reminders,
10
+ recurring rules. It replaces the legacy Node+PostgreSQL
11
+ `Calendar-Autoauth-MCP-Server` with the same agent surface so that
12
+ benchmark tasks can exercise an agent's ability to read schedule state,
13
+ create/update/delete events, search across events, and react to
14
+ deterministic state changes the task orchestrator injects via out-of-band
15
+ SQL mutations.
16
+
17
+ The server makes **no** network calls and ships **no** bundled seed data —
18
+ state enters only through `<env>/init.sql` (v3 contract).
19
+
20
+ Non-goals:
21
+
22
+ - No real Google Calendar API. Field names mirror the Google shape where
23
+ it's free, but the server is not API-compatible.
24
+ - No multi-user permissions or sharing. Identity is whatever the caller
25
+ passes as `user_id` on `list_calendars`.
26
+ - No timezone math beyond storing the string. ISO 8601 with an offset is
27
+ the input/output form.
28
+ - No i18n.
29
+
30
+ ## 2. Stack
31
+
32
+ - Python ≥ 3.12, stdlib `sqlite3`, `fastmcp ≥ 2.10.5`, `mcp[cli] ≥ 1.11.0`.
33
+ - No network libraries in the package.
34
+ - Transport: **streamable-HTTP only** at path `/mcp`. No stdio.
35
+
36
+ ## 3. Tools
37
+
38
+ All tools are `async def`, return `json.dumps(result, ensure_ascii=False)`,
39
+ and surface errors as `{"error": "...", "code": "..."}` rather than raising
40
+ across the MCP boundary. Datetimes are ISO 8601 strings; dates are
41
+ `YYYY-MM-DD`. IDs are domain-prefixed strings (`cal_…`, `evt_…`).
42
+
43
+ ### 3.1 `list_calendars(user_id) -> str`
44
+
45
+ ```json
46
+ [
47
+ {"calendar_id": "cal_000001", "user_id": "usr_li_wei",
48
+ "name": "Personal", "color": "#4285F4", "timezone": "Asia/Shanghai",
49
+ "is_primary": true, "created_at": "2024-01-01T00:00:00Z"},
50
+ ...
51
+ ]
52
+ ```
53
+
54
+ Order: `is_primary DESC, created_at ASC, calendar_id ASC`.
55
+
56
+ ### 3.2 `list_events(time_min?, time_max?, calendar_id?, max_results=20, order_by="startTime") -> str`
57
+
58
+ Returns events overlapping the half-open window `[time_min, time_max)`.
59
+ An event overlaps the window if `end_dt > time_min AND start_dt < time_max`.
60
+ Without `time_min`/`time_max` no bound is applied. `calendar_id`, if
61
+ present, scopes to a single calendar. `order_by` is one of `startTime`
62
+ (ASC) or `updated` (DESC). `max_results` defaults to 20, clamped to 500.
63
+
64
+ Each item has the same shape as `get_event` below.
65
+
66
+ ### 3.3 `get_event(event_id, calendar_id?) -> str`
67
+
68
+ Full event detail, attendees + reminders included.
69
+
70
+ ```json
71
+ {
72
+ "event_id": "evt_00000001",
73
+ "calendar_id": "cal_000001",
74
+ "summary": "Mom's birthday",
75
+ "description": "...",
76
+ "location": "...",
77
+ "start": {"dateTime": "2026-05-08T18:30:00+08:00"},
78
+ "end": {"dateTime": "2026-05-08T21:00:00+08:00"},
79
+ "all_day": false,
80
+ "status": "confirmed",
81
+ "created_at": "2026-04-01T09:00:00Z",
82
+ "updated_at": "2026-04-01T09:00:00Z",
83
+ "recurrence_rule": null,
84
+ "parent_event_id": null,
85
+ "attendees": [
86
+ {"email": "zhangfang@example.com", "name": "Mom", "response_status": "accepted"},
87
+ ...
88
+ ],
89
+ "reminders": [
90
+ {"method": "email", "minutes_before": 1440},
91
+ {"method": "popup", "minutes_before": 60}
92
+ ]
93
+ }
94
+ ```
95
+
96
+ If `calendar_id` is supplied and does not match, returns `EVENT_NOT_FOUND`.
97
+
98
+ ### 3.4 `create_event(summary, start, end, description?, location?, calendar_id?, attendees?, reminders?) -> str`
99
+
100
+ `start` and `end` are ISO 8601 datetime strings. `end` must be strictly
101
+ after `start` (`BAD_TIME_RANGE` otherwise). If `calendar_id` is omitted
102
+ the user's primary calendar is used; if no primary exists the oldest
103
+ calendar wins. If no calendars exist at all, `BAD_ARG`.
104
+
105
+ `attendees` is `[{email, name?, response_status?}]` where
106
+ `response_status` ∈ `{needsAction, accepted, declined, tentative}`
107
+ (default `needsAction`).
108
+
109
+ `reminders` is `[{minutes_before, method?}]` where `method` ∈
110
+ `{popup, email}` (default `popup`) and `minutes_before` is a non-negative
111
+ integer.
112
+
113
+ Returns the same shape as `get_event`.
114
+
115
+ ### 3.5 `update_event(event_id, summary?, start?, end?, description?, location?, calendar_id?, status?) -> str`
116
+
117
+ Only the supplied fields change. `description` and `location` accept the
118
+ empty string to clear the value (the field is overwritten only when the
119
+ argument is explicitly provided — `None` means "don't touch"). If both
120
+ `start` and `end` are touched they're validated together; if only one is
121
+ touched, validation uses the existing value of the other.
122
+
123
+ `status` ∈ `{confirmed, tentative, cancelled}`. To move an event between
124
+ calendars set `calendar_id`. Returns the updated event.
125
+
126
+ ### 3.6 `delete_event(event_id, calendar_id?) -> str`
127
+
128
+ Hard delete. Cascades to `attendees` and `reminders` via FK. If
129
+ `calendar_id` is supplied and does not match, returns `EVENT_NOT_FOUND`.
130
+
131
+ ```json
132
+ {"event_id": "evt_...", "deleted": true}
133
+ ```
134
+
135
+ ### 3.7 `search_events(query, time_min?, time_max?, max_results=50) -> str`
136
+
137
+ Case-insensitive substring match across `summary`, `description`,
138
+ `location`, and joined `attendees.email`/`attendees.name`. Optional
139
+ time-window restricts to overlap (same predicate as `list_events`). Same
140
+ return shape as `list_events`.
141
+
142
+ ## 4. Storage
143
+
144
+ SQLite, one file per server (`<env>/runtime.db`). `PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL`.
145
+
146
+ | table | purpose |
147
+ | ------------ | -------------------------------------------------------------------- |
148
+ | `calendars` | per-user calendars |
149
+ | `events` | event rows; `recurrence_rule` is stored verbatim (no materialization) |
150
+ | `attendees` | per-event invitee rows; cascade-deleted with the event |
151
+ | `reminders` | per-event reminders; cascade-deleted with the event |
152
+ | `_counters` | atomic seq counters used to mint stable IDs |
153
+
154
+ Indices: `(calendar_id, start_dt)` and `start_dt` on `events`,
155
+ `parent_event_id` on `events`, `event_id` on `attendees` / `reminders`.
156
+
157
+ The server carries no notion of "today"; date comparisons fall back to the
158
+ literal datetime strings the agent supplies.
159
+
160
+ ## 5. State injection
161
+
162
+ On cold start the server writes a fresh `<env>/runtime.db`, applies the
163
+ bundled schema, then executes `<env>/init.sql` if present. The package
164
+ ships no bundled seed data.
165
+
166
+ ## 6. Stage progression
167
+
168
+ No in-server clock walk. Date-keyed rows are pre-baked by `init.sql`.
169
+ Stage transitions arrive through the orchestrator's event-overlay
170
+ channel as raw SQL applied directly against `runtime.db`.
171
+
172
+ ## 7. Logging & ops
173
+
174
+ - `logging.getLogger(__name__)` everywhere; handler attached to stderr only.
175
+ - No `print()` in the package.
176
+
177
+ ## 8. Appendix — error codes
178
+
179
+ | code | meaning |
180
+ | ------------------- | -------------------------------------------------------------------- |
181
+ | `EVENT_NOT_FOUND` | `event_id` does not exist (or does not belong to `calendar_id`) |
182
+ | `CALENDAR_NOT_FOUND`| `calendar_id` does not exist |
183
+ | `BAD_TIME_RANGE` | `end` is not strictly after `start` |
184
+ | `BAD_DATE` | non-ISO date/datetime string |
185
+ | `OVERLAPPING_EVENT` | reserved (not raised in v1) |
186
+ | `BAD_ARG` | catch-all for malformed inputs |
187
+
188
+ ## 9. Out of scope
189
+
190
+ - No iCalendar import / export.
191
+ - No RRULE expansion. `recurrence_rule` is stored verbatim for round-tripping; the server does not materialize child instances.
192
+ - No pagination cursors (`max_results` only).
193
+ - No conflict detection between events (the `OVERLAPPING_EVENT` code is
194
+ reserved for a future version).
195
+ - No real auth, no permission enforcement beyond `user_id` scoping on
196
+ `list_calendars`.
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/pyproject.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "calendar-mock"
3
+ version = "0.1.0"
4
+ description = "FastMCP-based mock Google-Calendar-style server (SQLite, streamable-HTTP, offline)"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "fastmcp>=2.10.5",
9
+ "mcp[cli]>=1.11.0,<2.0.0",
10
+ "typing-extensions>=4.9.0",
11
+ ]
12
+
13
+ [project.scripts]
14
+ calendar-mock = "calendar_mock.server:main"
15
+
16
+ [build-system]
17
+ requires = ["hatchling"]
18
+ build-backend = "hatchling.build"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["src/calendar_mock"]
22
+
23
+ [tool.hatch.build]
24
+ include = [
25
+ "src/calendar_mock/**/*.py",
26
+ ]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.1.0"
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/backends/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .db import get_conn, init_schema, next_counter
2
+
3
+ __all__ = [
4
+ "get_conn",
5
+ "init_schema",
6
+ "next_counter",
7
+ ]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/backends/db.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite backend for calendar_mock.
2
+
3
+ Schema-only — no bundled seed data. State is injected by callers via
4
+ ``<env>/init.sql`` (INSERTs run after schema creation).
5
+
6
+ v3: dropped the simulated-clock singleton and the recurrence-materialized
7
+ log table. Recurring
8
+ events still carry an ``recurrence_rule`` column for round-tripping
9
+ through ``get_event``, but expansion is not performed by the server —
10
+ init.sql either pre-bakes the child rows directly or the agent treats
11
+ recurring rows as opaque single events.
12
+ """
13
+ import logging
14
+ import os
15
+ import sqlite3
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ SCHEMA_SQL = """
21
+ CREATE TABLE IF NOT EXISTS calendars (
22
+ calendar_id TEXT PRIMARY KEY,
23
+ user_id TEXT NOT NULL,
24
+ name TEXT NOT NULL,
25
+ color TEXT,
26
+ timezone TEXT NOT NULL DEFAULT 'UTC',
27
+ is_primary INTEGER NOT NULL DEFAULT 0,
28
+ created_at TEXT NOT NULL
29
+ );
30
+
31
+ CREATE INDEX IF NOT EXISTS idx_calendars_user ON calendars(user_id);
32
+
33
+ CREATE TABLE IF NOT EXISTS events (
34
+ event_id TEXT PRIMARY KEY,
35
+ calendar_id TEXT NOT NULL,
36
+ summary TEXT NOT NULL,
37
+ description TEXT,
38
+ location TEXT,
39
+ start_dt TEXT NOT NULL,
40
+ end_dt TEXT NOT NULL,
41
+ all_day INTEGER NOT NULL DEFAULT 0,
42
+ status TEXT NOT NULL CHECK(status IN ('confirmed','tentative','cancelled')) DEFAULT 'confirmed',
43
+ created_at TEXT NOT NULL,
44
+ updated_at TEXT NOT NULL,
45
+ recurrence_rule TEXT,
46
+ parent_event_id TEXT,
47
+ FOREIGN KEY (calendar_id) REFERENCES calendars(calendar_id)
48
+ );
49
+
50
+ CREATE INDEX IF NOT EXISTS idx_events_calendar_start ON events(calendar_id, start_dt);
51
+ CREATE INDEX IF NOT EXISTS idx_events_start ON events(start_dt);
52
+ CREATE INDEX IF NOT EXISTS idx_events_parent ON events(parent_event_id);
53
+
54
+ CREATE TABLE IF NOT EXISTS attendees (
55
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
56
+ event_id TEXT NOT NULL,
57
+ email TEXT NOT NULL,
58
+ name TEXT,
59
+ response_status TEXT NOT NULL CHECK(response_status IN
60
+ ('needsAction','accepted','declined','tentative')) DEFAULT 'needsAction',
61
+ FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE CASCADE
62
+ );
63
+
64
+ CREATE INDEX IF NOT EXISTS idx_attendees_event ON attendees(event_id);
65
+
66
+ CREATE TABLE IF NOT EXISTS reminders (
67
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
68
+ event_id TEXT NOT NULL,
69
+ method TEXT NOT NULL CHECK(method IN ('popup','email')) DEFAULT 'popup',
70
+ minutes_before INTEGER NOT NULL,
71
+ FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE CASCADE
72
+ );
73
+
74
+ CREATE INDEX IF NOT EXISTS idx_reminders_event ON reminders(event_id);
75
+
76
+ CREATE TABLE IF NOT EXISTS _counters (
77
+ key TEXT PRIMARY KEY,
78
+ value INTEGER NOT NULL DEFAULT 0
79
+ );
80
+ """
81
+
82
+
83
+ def get_conn(db_path: str) -> sqlite3.Connection:
84
+ """Open a SQLite connection with the project's PRAGMA defaults."""
85
+ parent = os.path.dirname(os.path.abspath(db_path))
86
+ if parent:
87
+ os.makedirs(parent, exist_ok=True)
88
+ conn = sqlite3.connect(db_path, isolation_level=None, check_same_thread=False)
89
+ conn.row_factory = sqlite3.Row
90
+ conn.execute("PRAGMA foreign_keys = ON;")
91
+ conn.execute("PRAGMA journal_mode = WAL;")
92
+ conn.execute("PRAGMA synchronous = NORMAL;")
93
+ # Out-wait an external writer (the task world-controller holds
94
+ # BEGIN IMMEDIATE across service databases with its own 10s busy_timeout).
95
+ # Without this the server inherits sqlite3's 5s default and loses the race,
96
+ # surfacing "database is locked" for a write that would have succeeded.
97
+ conn.execute("PRAGMA busy_timeout = 20000;")
98
+ return conn
99
+
100
+
101
+ def init_schema(conn: sqlite3.Connection) -> None:
102
+ """Create schema (idempotent)."""
103
+ conn.executescript(SCHEMA_SQL)
104
+
105
+
106
+ def next_counter(conn: sqlite3.Connection, key: str) -> int:
107
+ """Atomically bump and return a counter's new value."""
108
+ conn.execute(
109
+ "INSERT INTO _counters (key, value) VALUES (?, 0) ON CONFLICT(key) DO NOTHING",
110
+ (key,),
111
+ )
112
+ conn.execute(
113
+ "UPDATE _counters SET value = value + 1 WHERE key = ?", (key,)
114
+ )
115
+ row = conn.execute(
116
+ "SELECT value FROM _counters WHERE key = ?", (key,)
117
+ ).fetchone()
118
+ return int(row["value"])
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/models/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .calendar import Calendar
2
+ from .event import Event, Attendee, Reminder
3
+
4
+ __all__ = [
5
+ "Calendar",
6
+ "Event",
7
+ "Attendee",
8
+ "Reminder",
9
+ ]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/models/calendar.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+
5
+ @dataclass
6
+ class Calendar:
7
+ """A named calendar owned by a user (e.g. 'Personal', 'Work')."""
8
+ calendar_id: str
9
+ user_id: str
10
+ name: str
11
+ color: Optional[str]
12
+ timezone: str
13
+ is_primary: bool
14
+ created_at: str
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/models/event.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+
5
+ @dataclass
6
+ class Event:
7
+ """A calendar event. ``start_dt`` / ``end_dt`` are ISO 8601 strings."""
8
+ event_id: str
9
+ calendar_id: str
10
+ summary: str
11
+ description: Optional[str]
12
+ location: Optional[str]
13
+ start_dt: str
14
+ end_dt: str
15
+ all_day: bool
16
+ status: str # confirmed | tentative | cancelled
17
+ created_at: str
18
+ updated_at: str
19
+ recurrence_rule: Optional[str]
20
+ parent_event_id: Optional[str] = None
21
+
22
+
23
+ @dataclass
24
+ class Attendee:
25
+ """An invitee on an event."""
26
+ id: int
27
+ event_id: str
28
+ email: str
29
+ name: Optional[str]
30
+ response_status: str # needsAction | accepted | declined | tentative
31
+
32
+
33
+ @dataclass
34
+ class Reminder:
35
+ """A pre-event reminder for the calendar owner."""
36
+ id: int
37
+ event_id: str
38
+ method: str # popup | email
39
+ minutes_before: int
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/server.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """calendar_mock MCP server entry point (streamable-HTTP transport only)."""
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from mcp.server.fastmcp import FastMCP
9
+
10
+ from .backends import get_conn, init_schema
11
+ from .services import CalendarService, EventService
12
+ from .tools import register_calendar_tools, register_event_tools
13
+
14
+
15
+ def setup_logging(debug: bool = False) -> None:
16
+ level = logging.DEBUG if debug else logging.INFO
17
+ logging.basicConfig(
18
+ level=level,
19
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
20
+ handlers=[logging.StreamHandler(sys.stderr)],
21
+ force=True,
22
+ )
23
+
24
+
25
+ def build_server(env_dir: Path) -> FastMCP:
26
+ """Open a fresh runtime DB inside the env, apply schema + init.sql, return FastMCP."""
27
+ logger = logging.getLogger(__name__)
28
+
29
+ db_file = env_dir / "runtime.db"
30
+ for sidecar in (db_file, db_file.with_suffix(db_file.suffix + "-wal"),
31
+ db_file.with_suffix(db_file.suffix + "-shm")):
32
+ if sidecar.exists():
33
+ sidecar.unlink()
34
+
35
+ conn = get_conn(str(db_file))
36
+ init_schema(conn)
37
+
38
+ init_sql = env_dir / "init.sql"
39
+ if init_sql.exists():
40
+ logger.info("Applying init_sql from %s", init_sql)
41
+ conn.executescript(init_sql.read_text(encoding="utf-8"))
42
+
43
+ calendar_service = CalendarService(conn)
44
+ event_service = EventService(conn)
45
+
46
+ mcp = FastMCP("calendar-mock", host="0.0.0.0")
47
+ register_calendar_tools(mcp, calendar_service)
48
+ register_event_tools(mcp, event_service)
49
+ return mcp
50
+
51
+
52
+ def main() -> None:
53
+ parser = argparse.ArgumentParser(description="calendar_mock MCP server (streamable-HTTP)")
54
+ parser.add_argument("--host", default="0.0.0.0")
55
+ parser.add_argument("--port", type=int, default=8007)
56
+ parser.add_argument(
57
+ "--env", type=str, default=os.environ.get("XHS_ENV"),
58
+ help="Path to envs/<server>/<env_name>/ directory (falls back to $XHS_ENV)",
59
+ )
60
+ parser.add_argument("--transport", choices=["streamable-http", "stdio"],
61
+ default="streamable-http",
62
+ help="streamable-http for Terrarium/containers; stdio for local .mcp.json debugging")
63
+ parser.add_argument("--debug", action="store_true")
64
+ args = parser.parse_args()
65
+
66
+ setup_logging(args.debug)
67
+ logger = logging.getLogger(__name__)
68
+
69
+ if not args.env:
70
+ parser.error("--env is required (pass --env <dir> or set $XHS_ENV)")
71
+ env_dir = Path(args.env).resolve()
72
+ if not env_dir.is_dir():
73
+ logger.error("env path is not a directory: %s", env_dir)
74
+ sys.exit(2)
75
+
76
+ try:
77
+ mcp = build_server(env_dir)
78
+ if args.transport == "stdio":
79
+ logger.info("Starting calendar-mock on stdio (env=%s)", env_dir)
80
+ mcp.run(transport="stdio")
81
+ else:
82
+ mcp.settings.host = args.host
83
+ mcp.settings.port = args.port
84
+ logger.info(
85
+ "Starting calendar-mock on http://%s:%d/mcp (streamable-http, env=%s)",
86
+ args.host,
87
+ args.port,
88
+ env_dir,
89
+ )
90
+ mcp.run(transport="streamable-http")
91
+ except KeyboardInterrupt:
92
+ logger.info("Server shutdown requested")
93
+ except Exception as e:
94
+ logger.exception("Server startup failed: %s", e)
95
+ sys.exit(1)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .calendar_service import CalendarService
2
+ from .event_service import EventService
3
+
4
+ __all__ = [
5
+ "CalendarService",
6
+ "EventService",
7
+ ]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/_common.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared row-formatting helpers for calendar services."""
2
+ import sqlite3
3
+ from typing import List, Optional
4
+
5
+ from ..utils.exceptions import CalendarNotFoundError, EventNotFoundError
6
+
7
+
8
+ def fetch_calendar(conn: sqlite3.Connection, calendar_id: str) -> sqlite3.Row:
9
+ row = conn.execute(
10
+ "SELECT * FROM calendars WHERE calendar_id = ?", (calendar_id,)
11
+ ).fetchone()
12
+ if not row:
13
+ raise CalendarNotFoundError(f"calendar not found: {calendar_id}")
14
+ return row
15
+
16
+
17
+ def fetch_event_row(
18
+ conn: sqlite3.Connection,
19
+ event_id: str,
20
+ calendar_id: Optional[str] = None,
21
+ ) -> sqlite3.Row:
22
+ if calendar_id:
23
+ row = conn.execute(
24
+ "SELECT * FROM events WHERE event_id = ? AND calendar_id = ?",
25
+ (event_id, calendar_id),
26
+ ).fetchone()
27
+ else:
28
+ row = conn.execute(
29
+ "SELECT * FROM events WHERE event_id = ?", (event_id,)
30
+ ).fetchone()
31
+ if not row:
32
+ raise EventNotFoundError(f"event not found: {event_id}")
33
+ return row
34
+
35
+
36
+ def load_attendees(conn: sqlite3.Connection, event_id: str) -> List[dict]:
37
+ rows = conn.execute(
38
+ "SELECT email, name, response_status FROM attendees "
39
+ "WHERE event_id = ? ORDER BY id ASC",
40
+ (event_id,),
41
+ ).fetchall()
42
+ return [
43
+ {
44
+ "email": r["email"],
45
+ "name": r["name"],
46
+ "response_status": r["response_status"],
47
+ }
48
+ for r in rows
49
+ ]
50
+
51
+
52
+ def load_reminders(conn: sqlite3.Connection, event_id: str) -> List[dict]:
53
+ rows = conn.execute(
54
+ "SELECT method, minutes_before FROM reminders "
55
+ "WHERE event_id = ? ORDER BY minutes_before DESC, id ASC",
56
+ (event_id,),
57
+ ).fetchall()
58
+ return [
59
+ {"method": r["method"], "minutes_before": int(r["minutes_before"])}
60
+ for r in rows
61
+ ]
62
+
63
+
64
+ def format_event(conn: sqlite3.Connection, row: sqlite3.Row) -> dict:
65
+ """Format a DB event row + its attendees/reminders into the JSON shape."""
66
+ event_id = row["event_id"]
67
+ return {
68
+ "event_id": event_id,
69
+ "calendar_id": row["calendar_id"],
70
+ "summary": row["summary"],
71
+ "description": row["description"],
72
+ "location": row["location"],
73
+ "start": {"dateTime": row["start_dt"]},
74
+ "end": {"dateTime": row["end_dt"]},
75
+ "all_day": bool(int(row["all_day"])),
76
+ "status": row["status"],
77
+ "created_at": row["created_at"],
78
+ "updated_at": row["updated_at"],
79
+ "recurrence_rule": row["recurrence_rule"],
80
+ "parent_event_id": row["parent_event_id"],
81
+ "attendees": load_attendees(conn, event_id),
82
+ "reminders": load_reminders(conn, event_id),
83
+ }
84
+
85
+
86
+ def format_calendar(row: sqlite3.Row) -> dict:
87
+ return {
88
+ "calendar_id": row["calendar_id"],
89
+ "user_id": row["user_id"],
90
+ "name": row["name"],
91
+ "color": row["color"],
92
+ "timezone": row["timezone"],
93
+ "is_primary": bool(int(row["is_primary"])),
94
+ "created_at": row["created_at"],
95
+ }
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/calendar_service.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calendar listing service."""
2
+ import logging
3
+ import sqlite3
4
+ from typing import List
5
+
6
+ from ..utils.exceptions import BadArgError
7
+ from ._common import format_calendar
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class CalendarService:
13
+ def __init__(self, conn: sqlite3.Connection) -> None:
14
+ self.conn = conn
15
+
16
+ def list_calendars(self, user_id: str) -> List[dict]:
17
+ if not user_id:
18
+ raise BadArgError("user_id is required")
19
+ rows = self.conn.execute(
20
+ """
21
+ SELECT calendar_id, user_id, name, color, timezone, is_primary, created_at
22
+ FROM calendars WHERE user_id = ?
23
+ ORDER BY is_primary DESC, created_at ASC, calendar_id ASC
24
+ """,
25
+ (user_id,),
26
+ ).fetchall()
27
+ return [format_calendar(r) for r in rows]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/services/event_service.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event CRUD + listing/search service."""
2
+ import logging
3
+ import sqlite3
4
+ from typing import List, Optional
5
+
6
+ from ..backends.db import next_counter
7
+ from ..utils.dates import (
8
+ assert_time_range,
9
+ now_iso_z,
10
+ parse_datetime,
11
+ to_storage_offset,
12
+ )
13
+ from ..utils.exceptions import BadArgError
14
+ from ..utils.ids import event_id as make_event_id
15
+ from ._common import (
16
+ fetch_calendar,
17
+ fetch_event_row,
18
+ format_event,
19
+ )
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ VALID_STATUS = ("confirmed", "tentative", "cancelled")
24
+ VALID_ATTENDEE_RESPONSE = ("needsAction", "accepted", "declined", "tentative")
25
+ VALID_REMINDER_METHOD = ("popup", "email")
26
+ VALID_ORDER_BY = ("startTime", "updated")
27
+
28
+
29
+ class EventService:
30
+ def __init__(self, conn: sqlite3.Connection) -> None:
31
+ self.conn = conn
32
+
33
+ # ---- list / get / search --------------------------------------------
34
+ def list_events(
35
+ self,
36
+ time_min: Optional[str] = None,
37
+ time_max: Optional[str] = None,
38
+ calendar_id: Optional[str] = None,
39
+ max_results: int = 20,
40
+ order_by: str = "startTime",
41
+ page: int = 1,
42
+ ) -> dict:
43
+ if order_by not in VALID_ORDER_BY:
44
+ raise BadArgError(f"order_by must be one of {VALID_ORDER_BY}")
45
+ if max_results is None or int(max_results) < 1:
46
+ raise BadArgError("max_results must be >= 1")
47
+ max_results = min(int(max_results), 500)
48
+ if page is None or page < 1:
49
+ raise BadArgError("page must be >= 1")
50
+ # Validate, then rewrite each bound into the stored offset so the TEXT
51
+ # comparison below matches on the instant rather than on the spelling.
52
+ if time_min:
53
+ time_min = to_storage_offset(time_min)
54
+ if time_max:
55
+ time_max = to_storage_offset(time_max)
56
+ if calendar_id:
57
+ fetch_calendar(self.conn, calendar_id)
58
+
59
+ # `max_results` is a page size, not a data-loss cap: the matching set is
60
+ # materialised as a COUNT first, then sliced, and `has_more` signals
61
+ # whether a later page exists.
62
+ where = ["1=1"]
63
+ args: List = []
64
+ if calendar_id:
65
+ where.append("calendar_id = ?")
66
+ args.append(calendar_id)
67
+ if time_min:
68
+ # An event overlaps the window if its end is after time_min.
69
+ where.append("end_dt > ?")
70
+ args.append(time_min)
71
+ if time_max:
72
+ where.append("start_dt < ?")
73
+ args.append(time_max)
74
+
75
+ total = int(self.conn.execute(
76
+ f"SELECT COUNT(*) AS n FROM events WHERE {' AND '.join(where)}", args
77
+ ).fetchone()["n"])
78
+
79
+ if order_by == "updated":
80
+ order = "ORDER BY updated_at DESC, event_id DESC"
81
+ else:
82
+ order = "ORDER BY start_dt ASC, event_id ASC"
83
+
84
+ offset = (page - 1) * max_results
85
+ rows = self.conn.execute(
86
+ f"SELECT * FROM events WHERE {' AND '.join(where)} {order} LIMIT ? OFFSET ?",
87
+ args + [max_results, offset],
88
+ ).fetchall()
89
+ return {
90
+ "items": [format_event(self.conn, r) for r in rows],
91
+ "total": total,
92
+ "page": int(page),
93
+ "page_size": max_results,
94
+ "has_more": page * max_results < total,
95
+ }
96
+
97
+ def get_event(
98
+ self, event_id: str, calendar_id: Optional[str] = None
99
+ ) -> dict:
100
+ row = fetch_event_row(self.conn, event_id, calendar_id)
101
+ return format_event(self.conn, row)
102
+
103
+ def search_events(
104
+ self,
105
+ query: str,
106
+ time_min: Optional[str] = None,
107
+ time_max: Optional[str] = None,
108
+ max_results: int = 50,
109
+ page: int = 1,
110
+ ) -> dict:
111
+ if not query or not isinstance(query, str):
112
+ raise BadArgError("query is required")
113
+ # Validate, then rewrite each bound into the stored offset so the TEXT
114
+ # comparison below matches on the instant rather than on the spelling.
115
+ if time_min:
116
+ time_min = to_storage_offset(time_min)
117
+ if time_max:
118
+ time_max = to_storage_offset(time_max)
119
+ max_results = min(max(int(max_results or 50), 1), 500)
120
+ if page is None or page < 1:
121
+ raise BadArgError("page must be >= 1")
122
+ like = f"%{query.lower()}%"
123
+
124
+ where = (
125
+ "(LOWER(COALESCE(e.summary,'')) LIKE ? "
126
+ " OR LOWER(COALESCE(e.description,'')) LIKE ? "
127
+ " OR LOWER(COALESCE(e.location,'')) LIKE ? "
128
+ " OR LOWER(COALESCE(a.email,'')) LIKE ? "
129
+ " OR LOWER(COALESCE(a.name,'')) LIKE ?)"
130
+ )
131
+ args: List = [like, like, like, like, like]
132
+ if time_min:
133
+ where += " AND e.end_dt > ?"
134
+ args.append(time_min)
135
+ if time_max:
136
+ where += " AND e.start_dt < ?"
137
+ args.append(time_max)
138
+
139
+ # The search joins attendees, so a matching event can fan out to many
140
+ # rows; COUNT(DISTINCT event_id) is the true size of the result set.
141
+ total = int(self.conn.execute(
142
+ "SELECT COUNT(DISTINCT e.event_id) AS n FROM events e "
143
+ "LEFT JOIN attendees a ON a.event_id = e.event_id "
144
+ f"WHERE {where}", args
145
+ ).fetchone()["n"])
146
+
147
+ offset = (page - 1) * max_results
148
+ rows = self.conn.execute(
149
+ "SELECT DISTINCT e.* FROM events e "
150
+ "LEFT JOIN attendees a ON a.event_id = e.event_id "
151
+ f"WHERE {where} ORDER BY e.start_dt ASC, e.event_id ASC LIMIT ? OFFSET ?",
152
+ args + [max_results, offset],
153
+ ).fetchall()
154
+ return {
155
+ "items": [format_event(self.conn, r) for r in rows],
156
+ "total": total,
157
+ "page": int(page),
158
+ "page_size": max_results,
159
+ "has_more": page * max_results < total,
160
+ }
161
+
162
+ # ---- create / update / delete ---------------------------------------
163
+ def create_event(
164
+ self,
165
+ summary: str,
166
+ start: str,
167
+ end: str,
168
+ description: Optional[str] = None,
169
+ location: Optional[str] = None,
170
+ calendar_id: Optional[str] = None,
171
+ attendees: Optional[List[dict]] = None,
172
+ reminders: Optional[List[dict]] = None,
173
+ ) -> dict:
174
+ if not summary or not isinstance(summary, str):
175
+ raise BadArgError("summary is required")
176
+ assert_time_range(start, end)
177
+ cal_id = self._resolve_calendar(calendar_id)
178
+ attendees = attendees or []
179
+ reminders = reminders or []
180
+ self._validate_attendees(attendees)
181
+ self._validate_reminders(reminders)
182
+
183
+ seq = next_counter(self.conn, "event_seq")
184
+ new_id = make_event_id(seq)
185
+ now = now_iso_z()
186
+ self.conn.execute(
187
+ """
188
+ INSERT INTO events
189
+ (event_id, calendar_id, summary, description, location,
190
+ start_dt, end_dt, all_day, status,
191
+ created_at, updated_at, recurrence_rule, parent_event_id)
192
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'confirmed', ?, ?, NULL, NULL)
193
+ """,
194
+ (new_id, cal_id, summary, description, location,
195
+ start, end, now, now),
196
+ )
197
+ for att in attendees:
198
+ self.conn.execute(
199
+ """
200
+ INSERT INTO attendees (event_id, email, name, response_status)
201
+ VALUES (?, ?, ?, ?)
202
+ """,
203
+ (new_id, att["email"], att.get("name"),
204
+ att.get("response_status", "needsAction")),
205
+ )
206
+ for rem in reminders:
207
+ self.conn.execute(
208
+ """
209
+ INSERT INTO reminders (event_id, method, minutes_before)
210
+ VALUES (?, ?, ?)
211
+ """,
212
+ (new_id, rem.get("method", "popup"), int(rem["minutes_before"])),
213
+ )
214
+ row = fetch_event_row(self.conn, new_id)
215
+ return format_event(self.conn, row)
216
+
217
+ def update_event(
218
+ self,
219
+ event_id: str,
220
+ summary: Optional[str] = None,
221
+ start: Optional[str] = None,
222
+ end: Optional[str] = None,
223
+ description: Optional[str] = None,
224
+ location: Optional[str] = None,
225
+ calendar_id: Optional[str] = None,
226
+ status: Optional[str] = None,
227
+ ) -> dict:
228
+ existing = fetch_event_row(self.conn, event_id)
229
+ new_start = start if start is not None else existing["start_dt"]
230
+ new_end = end if end is not None else existing["end_dt"]
231
+ if start is not None or end is not None:
232
+ assert_time_range(new_start, new_end)
233
+ if status is not None and status not in VALID_STATUS:
234
+ raise BadArgError(f"status must be one of {VALID_STATUS}")
235
+ new_cal = (
236
+ self._resolve_calendar(calendar_id)
237
+ if calendar_id is not None
238
+ else existing["calendar_id"]
239
+ )
240
+
241
+ self.conn.execute(
242
+ """
243
+ UPDATE events
244
+ SET summary = COALESCE(?, summary),
245
+ description = CASE WHEN ? = 1 THEN ? ELSE description END,
246
+ location = CASE WHEN ? = 1 THEN ? ELSE location END,
247
+ start_dt = ?,
248
+ end_dt = ?,
249
+ calendar_id = ?,
250
+ status = COALESCE(?, status),
251
+ updated_at = ?
252
+ WHERE event_id = ?
253
+ """,
254
+ (
255
+ summary,
256
+ 1 if description is not None else 0, description,
257
+ 1 if location is not None else 0, location,
258
+ new_start, new_end, new_cal, status,
259
+ now_iso_z(), event_id,
260
+ ),
261
+ )
262
+ row = fetch_event_row(self.conn, event_id)
263
+ return format_event(self.conn, row)
264
+
265
+ def delete_event(
266
+ self, event_id: str, calendar_id: Optional[str] = None
267
+ ) -> dict:
268
+ fetch_event_row(self.conn, event_id, calendar_id)
269
+ self.conn.execute("DELETE FROM events WHERE event_id = ?", (event_id,))
270
+ return {"event_id": event_id, "deleted": True}
271
+
272
+ # ---- internals -------------------------------------------------------
273
+ def _resolve_calendar(self, calendar_id: Optional[str]) -> str:
274
+ if calendar_id:
275
+ fetch_calendar(self.conn, calendar_id)
276
+ return calendar_id
277
+ row = self.conn.execute(
278
+ "SELECT calendar_id FROM calendars WHERE is_primary = 1 "
279
+ "ORDER BY created_at ASC, calendar_id ASC LIMIT 1"
280
+ ).fetchone()
281
+ if row:
282
+ return row["calendar_id"]
283
+ row = self.conn.execute(
284
+ "SELECT calendar_id FROM calendars "
285
+ "ORDER BY created_at ASC, calendar_id ASC LIMIT 1"
286
+ ).fetchone()
287
+ if not row:
288
+ raise BadArgError(
289
+ "no calendars exist; pass calendar_id or seed one first"
290
+ )
291
+ return row["calendar_id"]
292
+
293
+ def _validate_attendees(self, attendees: List[dict]) -> None:
294
+ for att in attendees:
295
+ if not isinstance(att, dict) or "email" not in att:
296
+ raise BadArgError(
297
+ "each attendee must be {email, name?, response_status?}"
298
+ )
299
+ rs = att.get("response_status", "needsAction")
300
+ if rs not in VALID_ATTENDEE_RESPONSE:
301
+ raise BadArgError(
302
+ f"attendee response_status must be one of {VALID_ATTENDEE_RESPONSE}"
303
+ )
304
+
305
+ def _validate_reminders(self, reminders: List[dict]) -> None:
306
+ for rem in reminders:
307
+ if not isinstance(rem, dict) or "minutes_before" not in rem:
308
+ raise BadArgError(
309
+ "each reminder must be {minutes_before, method?}"
310
+ )
311
+ method = rem.get("method", "popup")
312
+ if method not in VALID_REMINDER_METHOD:
313
+ raise BadArgError(
314
+ f"reminder method must be one of {VALID_REMINDER_METHOD}"
315
+ )
316
+ try:
317
+ if int(rem["minutes_before"]) < 0:
318
+ raise ValueError
319
+ except (TypeError, ValueError):
320
+ raise BadArgError("reminder minutes_before must be a non-negative integer")
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .calendar_tools import register_calendar_tools
2
+ from .event_tools import register_event_tools
3
+
4
+ __all__ = [
5
+ "register_calendar_tools",
6
+ "register_event_tools",
7
+ ]
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/_common.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import json
3
+ import logging
4
+ from typing import Any
5
+
6
+ from ..utils.exceptions import CalendarMockError
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def dumps(value: Any) -> str:
12
+ return json.dumps(value, ensure_ascii=False)
13
+
14
+
15
+ def error_response(message: str, code: str) -> str:
16
+ return dumps({"error": message, "code": code})
17
+
18
+
19
+ def handle_errors(fn):
20
+ """Decorator: map CalendarMockError to structured JSON responses.
21
+
22
+ Uses functools.wraps so FastMCP introspects the wrapped function's
23
+ real parameter signature (not the wrapper's ``*args, **kwargs``).
24
+ """
25
+ @functools.wraps(fn)
26
+ async def wrapper(*args, **kwargs):
27
+ try:
28
+ return await fn(*args, **kwargs)
29
+ except CalendarMockError as e:
30
+ logger.info("tool error [%s]: %s", e.code, e.message)
31
+ return error_response(e.message, e.code)
32
+ except Exception as e: # pragma: no cover — defensive
33
+ # Not BAD_ARG: an unexpected exception here is a server-side fault
34
+ # (e.g. sqlite3.OperationalError "database is locked"), not a
35
+ # problem with the caller's arguments. Reporting it as BAD_ARG tells
36
+ # the agent to fix its input for a condition a retry would clear.
37
+ logger.exception("unexpected tool error")
38
+ return error_response(f"internal error: {e}", "INTERNAL")
39
+ return wrapper
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/calendar_tools.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mcp.server.fastmcp import FastMCP
2
+
3
+ from ..services.calendar_service import CalendarService
4
+ from ._common import dumps, handle_errors
5
+
6
+
7
+ def register_calendar_tools(mcp: FastMCP, calendar_service: CalendarService) -> None:
8
+
9
+ @mcp.tool()
10
+ @handle_errors
11
+ async def list_calendars(user_id: str) -> str:
12
+ """List a user's calendars (e.g. Personal, Work). Returns id, name, color, timezone, and whether it is the primary."""
13
+ return dumps(calendar_service.list_calendars(user_id))
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/tools/event_tools.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Optional
2
+
3
+ from mcp.server.fastmcp import FastMCP
4
+
5
+ from ..services.event_service import EventService
6
+ from ._common import dumps, handle_errors
7
+
8
+
9
+ def register_event_tools(mcp: FastMCP, event_service: EventService) -> None:
10
+
11
+ @mcp.tool()
12
+ @handle_errors
13
+ async def list_events(
14
+ time_min: Optional[str] = None,
15
+ time_max: Optional[str] = None,
16
+ calendar_id: Optional[str] = None,
17
+ max_results: int = 20,
18
+ order_by: str = "startTime",
19
+ page: int = 1,
20
+ ) -> str:
21
+ """List events overlapping a time window (ISO 8601). Optional `calendar_id` restricts to a single calendar; without it, all calendars are searched. `order_by` is `startTime` or `updated`. Paginated: `max_results` (1-500, default 20) is the page size, `page` (≥1) selects which page. Returns an envelope {items, total, page, page_size, has_more}; pass page=2,3,… while has_more is true to read the full result set."""
22
+ return dumps(
23
+ event_service.list_events(
24
+ time_min=time_min,
25
+ time_max=time_max,
26
+ calendar_id=calendar_id,
27
+ max_results=int(max_results),
28
+ order_by=order_by,
29
+ page=int(page),
30
+ )
31
+ )
32
+
33
+ @mcp.tool()
34
+ @handle_errors
35
+ async def get_event(
36
+ event_id: str, calendar_id: Optional[str] = None
37
+ ) -> str:
38
+ """Return full detail for a single event, including attendees and reminders. `calendar_id` is optional but, when supplied, scopes the lookup."""
39
+ return dumps(event_service.get_event(event_id, calendar_id))
40
+
41
+ @mcp.tool()
42
+ @handle_errors
43
+ async def create_event(
44
+ summary: str,
45
+ start: str,
46
+ end: str,
47
+ description: Optional[str] = None,
48
+ location: Optional[str] = None,
49
+ calendar_id: Optional[str] = None,
50
+ attendees: Optional[List[dict]] = None,
51
+ reminders: Optional[List[dict]] = None,
52
+ ) -> str:
53
+ """Create a new calendar event. `start`/`end` are ISO 8601 datetimes (e.g. `2026-05-10T09:00:00+08:00`). If `calendar_id` is omitted, the primary calendar is used. `attendees` is a list of `{email, name?, response_status?}` and `reminders` a list of `{minutes_before, method?}` where method is `popup` or `email`."""
54
+ return dumps(
55
+ event_service.create_event(
56
+ summary=summary,
57
+ start=start,
58
+ end=end,
59
+ description=description,
60
+ location=location,
61
+ calendar_id=calendar_id,
62
+ attendees=attendees,
63
+ reminders=reminders,
64
+ )
65
+ )
66
+
67
+ @mcp.tool()
68
+ @handle_errors
69
+ async def update_event(
70
+ event_id: str,
71
+ summary: Optional[str] = None,
72
+ start: Optional[str] = None,
73
+ end: Optional[str] = None,
74
+ description: Optional[str] = None,
75
+ location: Optional[str] = None,
76
+ calendar_id: Optional[str] = None,
77
+ status: Optional[str] = None,
78
+ ) -> str:
79
+ """Patch an event. Only the supplied fields change. `status` is one of `confirmed`, `tentative`, `cancelled`. To move between calendars set `calendar_id`."""
80
+ return dumps(
81
+ event_service.update_event(
82
+ event_id=event_id,
83
+ summary=summary,
84
+ start=start,
85
+ end=end,
86
+ description=description,
87
+ location=location,
88
+ calendar_id=calendar_id,
89
+ status=status,
90
+ )
91
+ )
92
+
93
+ @mcp.tool()
94
+ @handle_errors
95
+ async def delete_event(
96
+ event_id: str, calendar_id: Optional[str] = None
97
+ ) -> str:
98
+ """Delete an event. Returns EVENT_NOT_FOUND if the id is unknown (or does not belong to the supplied calendar_id, if given)."""
99
+ return dumps(event_service.delete_event(event_id, calendar_id))
100
+
101
+ @mcp.tool()
102
+ @handle_errors
103
+ async def search_events(
104
+ query: str,
105
+ time_min: Optional[str] = None,
106
+ time_max: Optional[str] = None,
107
+ max_results: int = 50,
108
+ page: int = 1,
109
+ ) -> str:
110
+ """Substring search over event summary, description, location, and attendee name/email. Case-insensitive. Optional `time_min`/`time_max` (ISO 8601) restrict the window. Paginated: `max_results` (1-500, default 50) is the page size, `page` (≥1) selects which page. Returns an envelope {items, total, page, page_size, has_more}; pass page=2,3,… while has_more is true to read the full result set."""
111
+ return dumps(
112
+ event_service.search_events(
113
+ query=query,
114
+ time_min=time_min,
115
+ time_max=time_max,
116
+ max_results=int(max_results),
117
+ page=int(page),
118
+ )
119
+ )
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/__init__.py ADDED
File without changes
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/dates.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Date / datetime parsing helpers.
2
+
3
+ Event start / end times are ISO 8601 datetimes (``YYYY-MM-DDTHH:MM:SS``
4
+ with optional ``Z`` or ``±HH:MM`` offset). Stored as text and compared
5
+ lexicographically thanks to the ISO ordering property.
6
+ """
7
+ from datetime import date, datetime, timedelta, timezone
8
+ from typing import Optional
9
+
10
+ from .exceptions import BadDateError
11
+ from .world_clock import now as _world_now, now_iso as _world_now_iso, now_iso_z as _world_now_iso_z, today_utc as _world_today_utc
12
+
13
+ DATE_FMT = "%Y-%m-%d"
14
+
15
+
16
+ def parse_date(s: str) -> date:
17
+ try:
18
+ return datetime.strptime(s, DATE_FMT).date()
19
+ except (TypeError, ValueError) as e:
20
+ raise BadDateError(f"invalid date '{s}': {e}")
21
+
22
+
23
+ def fmt(d: date) -> str:
24
+ return d.strftime(DATE_FMT)
25
+
26
+
27
+ def add_days(d: str, n: int) -> str:
28
+ return fmt(parse_date(d) + timedelta(days=n))
29
+
30
+
31
+ def parse_datetime(s: str) -> datetime:
32
+ """Parse an ISO 8601 datetime. Accepts trailing ``Z`` (treated as UTC)
33
+ and ``±HH:MM`` offsets. Naive datetimes are returned as-is."""
34
+ if not isinstance(s, str) or not s:
35
+ raise BadDateError(f"invalid datetime: {s!r}")
36
+ txt = s.strip()
37
+ if txt.endswith("Z"):
38
+ txt = txt[:-1] + "+00:00"
39
+ try:
40
+ return datetime.fromisoformat(txt)
41
+ except ValueError as e:
42
+ raise BadDateError(f"invalid datetime '{s}': {e}")
43
+
44
+
45
+ def datetime_to_iso(dt: datetime) -> str:
46
+ """Format ``dt`` as ISO 8601. Aware datetimes use ``+HH:MM``; naive
47
+ datetimes are written without an offset (caller's responsibility)."""
48
+ return dt.isoformat(timespec="seconds")
49
+
50
+
51
+ # Datetime columns are TEXT and every ordering/range filter compares them as
52
+ # strings, so a single stored offset form is required for those comparisons to
53
+ # agree with real time. All seed data and every world-controller mutation write
54
+ # +08:00; emitting Z here would sort every server-written row against the seed
55
+ # purely on the offset character ('+' 0x2B < digits < 'Z' 0x5A) rather than on
56
+ # the instant, silently inverting "newest first" and window filters.
57
+ WRITE_TZ = timezone(timedelta(hours=8))
58
+
59
+
60
+ def now_iso_z() -> str:
61
+ """Current time as an ISO 8601 string in the corpus offset (+08:00).
62
+
63
+ Named for the historical Z form it replaced; the name is kept so the
64
+ existing call sites stay untouched.
65
+ """
66
+ return _world_now_iso()
67
+
68
+
69
+ def to_storage_offset(s: str) -> str:
70
+ """Rewrite an ISO datetime into the stored offset, preserving the instant.
71
+
72
+ Window filters compare against TEXT columns, so the comparison is a byte
73
+ comparison: the same instant written ``...T16:00:00Z`` and
74
+ ``...T00:00:00+08:00`` compares differently even though both are legal
75
+ inputs per SPEC.md ("ISO 8601 with an offset is the input/output form").
76
+ Normalising the caller's bound to the offset the rows are stored in makes
77
+ the string comparison agree with chronological order.
78
+
79
+ A naive datetime carries no instant to convert, so it is passed through and
80
+ compared as written.
81
+ """
82
+ dt = parse_datetime(s)
83
+ if dt.tzinfo is None:
84
+ return s
85
+ return dt.astimezone(WRITE_TZ).isoformat(timespec="seconds")
86
+
87
+
88
+ def date_of(dt_str: str) -> str:
89
+ """Return the YYYY-MM-DD portion of an ISO datetime string."""
90
+ # The first 10 chars of any valid ISO 8601 form are the date.
91
+ parse_datetime(dt_str) # validates
92
+ return dt_str[:10]
93
+
94
+
95
+ def assert_time_range(start: str, end: str) -> None:
96
+ """Raise BadTimeRangeError if ``end`` is not strictly after ``start``."""
97
+ from .exceptions import BadTimeRangeError
98
+ s = parse_datetime(start)
99
+ e = parse_datetime(end)
100
+ # Both aware or both naive — normalise to comparable form.
101
+ if (s.tzinfo is None) != (e.tzinfo is None):
102
+ # Treat naive as UTC for the comparison only.
103
+ if s.tzinfo is None:
104
+ s = s.replace(tzinfo=timezone.utc)
105
+ if e.tzinfo is None:
106
+ e = e.replace(tzinfo=timezone.utc)
107
+ if e <= s:
108
+ raise BadTimeRangeError(
109
+ f"end ({end}) must be strictly after start ({start})"
110
+ )
111
+
112
+
113
+ def opt_parse_datetime(s: Optional[str]) -> Optional[datetime]:
114
+ return parse_datetime(s) if s else None
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/exceptions.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+
4
+ class CalendarMockError(Exception):
5
+ """Base exception for the calendar mock server.
6
+
7
+ Mapped to ``{"error": ..., "code": ...}`` JSON by the tool decorator;
8
+ never raised across the MCP boundary.
9
+ """
10
+
11
+ code: str = "BAD_ARG"
12
+
13
+ def __init__(self, message: str, code: Optional[str] = None) -> None:
14
+ super().__init__(message)
15
+ self.message = message
16
+ if code:
17
+ self.code = code
18
+
19
+
20
+ class BadArgError(CalendarMockError):
21
+ code = "BAD_ARG"
22
+
23
+
24
+ class BadDateError(CalendarMockError):
25
+ code = "BAD_DATE"
26
+
27
+
28
+ class BadTimeRangeError(CalendarMockError):
29
+ code = "BAD_TIME_RANGE"
30
+
31
+
32
+ class EventNotFoundError(CalendarMockError):
33
+ code = "EVENT_NOT_FOUND"
34
+
35
+
36
+ class CalendarNotFoundError(CalendarMockError):
37
+ code = "CALENDAR_NOT_FOUND"
38
+
39
+
40
+ class OverlappingEventError(CalendarMockError):
41
+ code = "OVERLAPPING_EVENT"
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/ids.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def event_id(seq: int) -> str:
2
+ return f"evt_{seq:08d}"
3
+
4
+
5
+ def calendar_id(seq: int) -> str:
6
+ return f"cal_{seq:06d}"
7
+
8
+
9
+ def attendee_id(seq: int) -> str:
10
+ return f"att_{seq:08d}"
11
+
12
+
13
+ def reminder_id(seq: int) -> str:
14
+ return f"rem_{seq:08d}"
harbor/rental/renewal_negotiation_repair_rental/environment/servers/calendar_mock/src/calendar_mock/utils/world_clock.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared virtual world-clock contract for mock server audit timestamps.
2
+
3
+ The Harbor world-controller owns ``WORLD_CLOCK_FILE`` and updates it at step
4
+ boundaries. ``WORLD_NOW`` is intentionally a secondary static override for
5
+ unit tests and local debugging. When neither is configured, reads fail closed.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from datetime import date, datetime, timedelta, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ WRITE_TZ = timezone(timedelta(hours=8))
16
+ WORLD_CLOCK_FILE_ENV = "WORLD_CLOCK_FILE"
17
+ WORLD_NOW_ENV = "WORLD_NOW"
18
+
19
+
20
+ class WorldClockError(RuntimeError):
21
+ """Raised when a configured virtual clock cannot be read safely."""
22
+
23
+
24
+ def _parse_timestamp(raw: Any, source: str) -> datetime:
25
+ if not isinstance(raw, str) or not raw.strip():
26
+ raise WorldClockError(f"{source} must contain a non-empty ISO timestamp")
27
+ try:
28
+ parsed = datetime.fromisoformat(raw.strip().replace("Z", "+00:00"))
29
+ except ValueError as exc:
30
+ raise WorldClockError(f"{source} is not a valid ISO timestamp: {raw!r}") from exc
31
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
32
+ raise WorldClockError(f"{source} must include an explicit timezone offset")
33
+ return parsed.astimezone(WRITE_TZ).replace(microsecond=0)
34
+
35
+
36
+ def _read_clock_file(path: Path) -> datetime:
37
+ try:
38
+ payload = json.loads(path.read_text(encoding="utf-8"))
39
+ except FileNotFoundError as exc:
40
+ raise WorldClockError(f"configured world clock file is missing: {path}") from exc
41
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
42
+ raise WorldClockError(f"configured world clock file is unreadable: {path}: {exc}") from exc
43
+ if not isinstance(payload, dict) or not ("world_now" in payload or "now" in payload):
44
+ raise WorldClockError(f"configured world clock file must contain a JSON object: {path}")
45
+ return _parse_timestamp(payload.get("world_now") or payload.get("now"), f"world_now in {path}")
46
+
47
+
48
+ def is_configured() -> bool:
49
+ """Whether Harbor or a caller supplied a virtual clock source."""
50
+ return bool(os.environ.get(WORLD_CLOCK_FILE_ENV) or os.environ.get(WORLD_NOW_ENV))
51
+
52
+
53
+ def now() -> datetime:
54
+ """Return the current world time as an aware datetime in ``+08:00``."""
55
+ clock_file = os.environ.get(WORLD_CLOCK_FILE_ENV)
56
+ if clock_file:
57
+ return _read_clock_file(Path(clock_file))
58
+
59
+ static_now = os.environ.get(WORLD_NOW_ENV)
60
+ if static_now:
61
+ return _parse_timestamp(static_now, WORLD_NOW_ENV)
62
+
63
+ raise WorldClockError(
64
+ "world clock not configured: set WORLD_CLOCK_FILE (world-controller) "
65
+ "or WORLD_NOW (tests); refusing to fall back to host wall clock")
66
+
67
+
68
+ def now_iso() -> str:
69
+ """Return the current world time in the corpus offset form."""
70
+ return now().isoformat()
71
+
72
+
73
+ def now_iso_z() -> str:
74
+ """Return the current world time as a UTC ``Z`` timestamp."""
75
+ return now().astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
76
+
77
+
78
+ def today_utc() -> str:
79
+ """Return the current world date in UTC as ``YYYY-MM-DD``."""
80
+ return now().astimezone(timezone.utc).date().isoformat()
81
+
82
+
83
+ def today_local() -> date:
84
+ """Return the current world date in the corpus offset."""
85
+ return now().date()