qiuql commited on
Commit
a6bc6be
·
verified ·
1 Parent(s): 4fc924b

Add Harbor-format task: shopping/apple_watch_tradein_30d

Browse files

Synced from https://github.com/evolvent-ai/VibeLifeBench/tree/cd21b2cb5d18a81b0fcdb4a948889a2148f48958/harbor/shopping/apple_watch_tradein_30d (536 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/shopping/apple_watch_tradein_30d/environment/Dockerfile +57 -0
  2. harbor/shopping/apple_watch_tradein_30d/environment/docker-compose.yaml +120 -0
  3. harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/collect +3 -0
  4. harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/collector.py +355 -0
  5. harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/harbor_env.py +146 -0
  6. harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/response_capture.py +357 -0
  7. harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/snapshot_capture.py +314 -0
  8. harbor/shopping/apple_watch_tradein_30d/environment/seeds/calendar/README.md +13 -0
  9. harbor/shopping/apple_watch_tradein_30d/environment/seeds/calendar/init.sql +34 -0
  10. harbor/shopping/apple_watch_tradein_30d/environment/seeds/credit_card/README.md +13 -0
  11. harbor/shopping/apple_watch_tradein_30d/environment/seeds/credit_card/init.sql +40 -0
  12. harbor/shopping/apple_watch_tradein_30d/environment/seeds/delivery_logistics/README.md +13 -0
  13. harbor/shopping/apple_watch_tradein_30d/environment/seeds/delivery_logistics/init.sql +51 -0
  14. harbor/shopping/apple_watch_tradein_30d/environment/seeds/ecommerce/README.md +13 -0
  15. harbor/shopping/apple_watch_tradein_30d/environment/seeds/ecommerce/init.sql +152 -0
  16. harbor/shopping/apple_watch_tradein_30d/environment/seeds/email/README.md +13 -0
  17. harbor/shopping/apple_watch_tradein_30d/environment/seeds/email/init.sql +40 -0
  18. harbor/shopping/apple_watch_tradein_30d/environment/seeds/listing_platform/README.md +13 -0
  19. harbor/shopping/apple_watch_tradein_30d/environment/seeds/listing_platform/init.sql +48 -0
  20. harbor/shopping/apple_watch_tradein_30d/environment/seeds/notification_hub/README.md +13 -0
  21. harbor/shopping/apple_watch_tradein_30d/environment/seeds/notification_hub/init.sql +61 -0
  22. harbor/shopping/apple_watch_tradein_30d/environment/seeds/weather/README.md +13 -0
  23. harbor/shopping/apple_watch_tradein_30d/environment/seeds/weather/init.sql +52 -0
  24. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/.gitignore +13 -0
  25. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/Dockerfile +11 -0
  26. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/LICENSE +21 -0
  27. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/README.md +83 -0
  28. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/SPEC.md +196 -0
  29. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/pyproject.toml +26 -0
  30. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/__init__.py +1 -0
  31. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/__main__.py +4 -0
  32. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/backends/__init__.py +7 -0
  33. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/backends/db.py +118 -0
  34. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/models/__init__.py +9 -0
  35. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/models/calendar.py +14 -0
  36. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/models/event.py +39 -0
  37. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/server.py +99 -0
  38. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/services/__init__.py +7 -0
  39. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/services/_common.py +95 -0
  40. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/services/calendar_service.py +27 -0
  41. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/services/event_service.py +320 -0
  42. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/tools/__init__.py +7 -0
  43. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/tools/_common.py +39 -0
  44. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/tools/calendar_tools.py +13 -0
  45. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/tools/event_tools.py +119 -0
  46. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/__init__.py +0 -0
  47. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/dates.py +114 -0
  48. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/exceptions.py +41 -0
  49. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/ids.py +14 -0
  50. harbor/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/world_clock.py +87 -0
harbor/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/environment/docker-compose.yaml ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ build: {context: ., dockerfile: Dockerfile}
4
+ depends_on:
5
+ workspace-init: {condition: service_completed_successfully}
6
+ world-controller: {condition: service_healthy}
7
+ calendar: {condition: service_healthy}
8
+ credit-card: {condition: service_healthy}
9
+ delivery-logistics: {condition: service_healthy}
10
+ ecommerce: {condition: service_healthy}
11
+ email: {condition: service_healthy}
12
+ listing-platform: {condition: service_healthy}
13
+ notification-hub: {condition: service_healthy}
14
+ weather: {condition: service_healthy}
15
+ environment:
16
+ WORLD_CLOCK_FILE: /world-clock/current.json
17
+ SCENARIO_CLOCK_REQUIRED: '1'
18
+ NO_PROXY: localhost,127.0.0.1,::1,world-controller,calendar,credit-card,delivery-logistics,ecommerce,email,listing-platform,notification-hub,weather
19
+ no_proxy: localhost,127.0.0.1,::1,world-controller,calendar,credit-card,delivery-logistics,ecommerce,email,listing-platform,notification-hub,weather
20
+ volumes:
21
+ - workspace-state:/workspace
22
+ - eval-evidence:/harbor/evidence:ro
23
+ - world-clock:/world-clock:ro
24
+ workspace-init:
25
+ build: {context: ., dockerfile: workspace-init/Dockerfile}
26
+ volumes: [workspace-state:/target]
27
+ restart: 'no'
28
+ calendar: &mock_calendar
29
+ build: {context: ./servers/calendar_mock}
30
+ volumes: [./seeds/calendar:/env-seed:ro, calendar-env:/env, world-clock:/world-clock:ro]
31
+ expose: ['8000']
32
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
33
+ healthcheck: &hc {test: [CMD, python, -c, "import socket; s=socket.create_connection(('127.0.0.1',8000),2); s.close()"], interval: 2s, timeout: 5s, retries: 30, start_period: 3s}
34
+ credit-card:
35
+ build: {context: ./servers/credit_card_mock}
36
+ volumes: [./seeds/credit_card:/env-seed:ro, credit-card-env:/env, world-clock:/world-clock:ro]
37
+ expose: ['8000']
38
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
39
+ healthcheck: *hc
40
+ delivery-logistics:
41
+ build: {context: ./servers/delivery_logistics_mock}
42
+ volumes: [./seeds/delivery_logistics:/env-seed:ro, delivery-logistics-env:/env, world-clock:/world-clock:ro]
43
+ expose: ['8000']
44
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
45
+ healthcheck: *hc
46
+ ecommerce:
47
+ build: {context: ./servers/ecommerce_mock}
48
+ volumes: [./seeds/ecommerce:/env-seed:ro, ecommerce-env:/env, world-clock:/world-clock:ro]
49
+ expose: ['8000']
50
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
51
+ healthcheck: *hc
52
+ email:
53
+ build: {context: ./servers/email_mock}
54
+ volumes: [./seeds/email:/env-seed:ro, email-env:/env, world-clock:/world-clock:ro]
55
+ expose: ['8000']
56
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
57
+ healthcheck: *hc
58
+ listing-platform:
59
+ build: {context: ./servers/listing_platform_mock}
60
+ volumes: [./seeds/listing_platform:/env-seed:ro, listing-platform-env:/env, world-clock:/world-clock:ro]
61
+ expose: ['8000']
62
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
63
+ healthcheck: *hc
64
+ notification-hub:
65
+ build: {context: ./servers/notification_hub_mock}
66
+ volumes: [./seeds/notification_hub:/env-seed:ro, notification-hub-env:/env, world-clock:/world-clock:ro]
67
+ expose: ['8000']
68
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
69
+ healthcheck: *hc
70
+ weather:
71
+ build: {context: ./servers/weather_mock}
72
+ volumes: [./seeds/weather:/env-seed:ro, weather-env:/env, world-clock:/world-clock:ro]
73
+ expose: ['8000']
74
+ environment: {XHS_ENV: /env, WORLD_CLOCK_FILE: /world-clock/current.json, SCENARIO_CLOCK_REQUIRED: '1'}
75
+ healthcheck: *hc
76
+ world-controller:
77
+ build: {context: ., dockerfile: world-controller/Dockerfile}
78
+ environment:
79
+ HEALTH_TOKEN: awch-health-2026
80
+ CLOCK_TOKEN: apple_watch_tradein_30d-clock-token
81
+ WORLD_CLOCK_FILE: /world-clock/current.json
82
+ SCENARIO_CLOCK_REQUIRED: '1'
83
+ depends_on:
84
+ workspace-init: {condition: service_completed_successfully}
85
+ calendar: {condition: service_healthy}
86
+ credit-card: {condition: service_healthy}
87
+ delivery-logistics: {condition: service_healthy}
88
+ ecommerce: {condition: service_healthy}
89
+ email: {condition: service_healthy}
90
+ listing-platform: {condition: service_healthy}
91
+ notification-hub: {condition: service_healthy}
92
+ weather: {condition: service_healthy}
93
+ volumes:
94
+ - calendar-env:/calendar-env
95
+ - credit-card-env:/credit-card-env
96
+ - delivery-logistics-env:/delivery-logistics-env
97
+ - ecommerce-env:/ecommerce-env
98
+ - email-env:/email-env
99
+ - listing-platform-env:/listing-platform-env
100
+ - notification-hub-env:/notification-hub-env
101
+ - weather-env:/weather-env
102
+ - workspace-state:/workspace-source:ro
103
+ - eval-evidence:/evidence
104
+ - controller-state:/controller-state
105
+ - world-clock:/world-clock
106
+ expose: ['8090']
107
+ healthcheck: {test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8090/health',timeout=2).read()"], interval: 2s, timeout: 5s, retries: 30, start_period: 3s}
108
+ volumes:
109
+ workspace-state: {}
110
+ eval-evidence: {}
111
+ world-clock: {}
112
+ controller-state: {}
113
+ calendar-env: {}
114
+ credit-card-env: {}
115
+ delivery-logistics-env: {}
116
+ ecommerce-env: {}
117
+ email-env: {}
118
+ listing-platform-env: {}
119
+ notification-hub-env: {}
120
+ weather-env: {}
harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/collect ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ exec python /opt/evidence-collector/collector.py "$@"
harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/collector.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ WORLD_CLOCK_FILE = Path(
24
+ os.environ.get("WORLD_CLOCK_FILE", "/world-clock/current.json")
25
+ )
26
+ SCENARIO_CLOCK_REQUIRED = os.environ.get("SCENARIO_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_session_items,
33
+ _jsonable,
34
+ _load_trajectory,
35
+ _tool_result_success,
36
+ atif_step_slice,
37
+ step_text_and_calls,
38
+ )
39
+
40
+ def scenario_clock() -> dict[str, Any]:
41
+ try:
42
+ payload = json.loads(WORLD_CLOCK_FILE.read_text(encoding="utf-8"))
43
+ if not isinstance(payload.get("step"), str) or not isinstance(payload.get("now"), str):
44
+ raise ValueError("invalid scenario clock payload")
45
+ parsed = datetime.fromisoformat(payload["now"].replace("Z", "+00:00"))
46
+ if parsed.tzinfo is None:
47
+ raise ValueError("scenario clock must include an offset")
48
+ return {
49
+ "schema_version": 1,
50
+ "step": payload["step"],
51
+ "now": parsed.isoformat(),
52
+ }
53
+ except Exception as exc:
54
+ if SCENARIO_CLOCK_REQUIRED:
55
+ raise RuntimeError(
56
+ f"required world clock unavailable at {WORLD_CLOCK_FILE}: {exc}"
57
+ ) from exc
58
+ now = datetime.now(timezone.utc).isoformat()
59
+ return {"schema_version": 1, "step": "unknown", "now": now}
60
+
61
+
62
+ def utc_now() -> str:
63
+ return scenario_clock()["now"]
64
+
65
+
66
+ def _write_json(path: Path, payload: Any) -> None:
67
+ path.write_text(
68
+ json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True, allow_nan=False)
69
+ + "\n",
70
+ encoding="utf-8",
71
+ )
72
+
73
+
74
+ def _latest_session(logs_root: Path) -> Path | None:
75
+ candidates = [
76
+ path
77
+ for pattern in ("sessions/**/rollout-*.jsonl", "sessions/**/*.jsonl")
78
+ for path in logs_root.glob(pattern)
79
+ if path.is_file() and not path.is_symlink()
80
+ ]
81
+ return max(candidates, key=lambda path: path.stat().st_mtime_ns) if candidates else None
82
+
83
+
84
+ def _oracle_run_marker(workspace_root: Path, logs_root: Path) -> bool:
85
+ """Legacy compatibility hook; workspace files never identify Oracle runs.
86
+
87
+ Evidence source selection is trajectory-first for both Oracle and real
88
+ agents. Harbor owns the lifecycle around ``oracle.txt``/``exit-code.txt``;
89
+ a file created by the agent in ``/workspace`` is never sufficient.
90
+ """
91
+ return False
92
+
93
+
94
+ def _oracle_exit_code(logs_root: Path) -> None:
95
+ """Fail closed when Harbor recorded a non-zero Oracle solution exit."""
96
+ path = logs_root / ORACLE_EXIT_CODE_FILE
97
+ if not path.is_file():
98
+ return
99
+ raw = path.read_text(encoding="utf-8").strip()
100
+ try:
101
+ code = int(raw)
102
+ except ValueError as exc:
103
+ raise RuntimeError(f"invalid Oracle exit code in {path}: {raw!r}") from exc
104
+ if code != 0:
105
+ raise RuntimeError(f"Oracle solution exited with code {code}")
106
+
107
+
108
+
109
+
110
+ def _empty_atif_bytes() -> bytes:
111
+ return (
112
+ json.dumps(
113
+ {"schema_version": "ATIF-v1.7", "steps": []},
114
+ ensure_ascii=False,
115
+ sort_keys=True,
116
+ allow_nan=False,
117
+ )
118
+ + "\n"
119
+ ).encode("utf-8")
120
+
121
+
122
+ def _trajectory_document_valid(trajectory: Any) -> bool:
123
+ """Accept the ATIF/legacy containers emitted by Harbor, not arbitrary JSON."""
124
+ if not isinstance(trajectory, dict):
125
+ return False
126
+ steps = trajectory.get("steps")
127
+ messages = trajectory.get("messages")
128
+ return isinstance(steps, list) or isinstance(messages, list)
129
+
130
+
131
+ def _validate_session_jsonl(path: Path) -> None:
132
+ """Fail closed when a discovered Codex session is empty or malformed."""
133
+ try:
134
+ lines = [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
135
+ except OSError as exc:
136
+ raise RuntimeError(f"unreadable Harbor session log: {path}") from exc
137
+ if not lines:
138
+ raise RuntimeError(f"empty Harbor session log: {path}")
139
+ for line_number, line in enumerate(lines, start=1):
140
+ try:
141
+ row = json.loads(line)
142
+ except json.JSONDecodeError as exc:
143
+ raise RuntimeError(
144
+ f"invalid Harbor session JSONL at {path}:{line_number}"
145
+ ) from exc
146
+ if not isinstance(row, dict):
147
+ raise RuntimeError(
148
+ f"invalid Harbor session record at {path}:{line_number}"
149
+ )
150
+
151
+
152
+ def _trajectory_and_items(
153
+ logs_root: Path, step_name: str, source_event_id: str, *, workspace_root: Path | None = None
154
+ ) -> tuple[bytes, str, list[dict[str, Any]], str, Path | None]:
155
+ workspace_root = Path(workspace_root) if workspace_root is not None else Path("/workspace")
156
+ # Oracle and real agents publish the same native trajectory contract. Do
157
+ # not inspect or trust any workspace call log when choosing the source.
158
+ _oracle_exit_code(logs_root)
159
+
160
+ if not logs_root.is_dir():
161
+ raise RuntimeError(f"Harbor agent log directory is unavailable: {logs_root}")
162
+ if not any(logs_root.iterdir()):
163
+ # Harbor's native NopAgent intentionally emits no files. Preserve that
164
+ # fact as an explicit empty turn instead of treating it as telemetry loss.
165
+ return _empty_atif_bytes(), "", [], "empty-agent-log", None
166
+
167
+ trajectory_path = logs_root / "trajectory.json"
168
+ trajectory_valid = False
169
+ if trajectory_path.exists():
170
+ if not trajectory_path.is_file() or trajectory_path.is_symlink():
171
+ raise RuntimeError(f"invalid Harbor trajectory path: {trajectory_path}")
172
+ raw = trajectory_path.read_bytes()
173
+ trajectory = _load_trajectory(trajectory_path)
174
+ trajectory_valid = _trajectory_document_valid(trajectory)
175
+ if not trajectory_valid:
176
+ raise RuntimeError(f"invalid Harbor trajectory: {trajectory_path}")
177
+ # Freeze only this step's turns; see atif_step_slice for why. Falls back
178
+ # to the raw bytes whenever the document is a valid legacy container.
179
+ sliced = atif_step_slice(trajectory)
180
+ if sliced is not None:
181
+ raw = (
182
+ json.dumps(sliced, ensure_ascii=False, sort_keys=True, allow_nan=False)
183
+ + "\n"
184
+ ).encode("utf-8")
185
+ text, calls = step_text_and_calls(trajectory, step_name, source_event_id)
186
+ if text.strip() or calls:
187
+ # codex translated text unified_exec translated text MCP translated text exec translated text JS translated text ,ATIF translated text
188
+ # function_name="exec", translated text trace translated text MCP translated text , translated text
189
+ # *_servers translated text False。 translated text record translated text session jsonl translated text
190
+ # event_msg/item_completed translated text , translated text 。 translated text item translated text docstring。
191
+ session_path = _latest_session(logs_root)
192
+ if session_path is not None:
193
+ try:
194
+ calls = calls + _session_mcp_calls(session_path, source_event_id)
195
+ except (OSError, ValueError):
196
+ # translated text : translated text , translated text do not translated text
197
+ # "agent translated text " translated text 。
198
+ pass
199
+ return raw, text, calls, "trajectory.json", None
200
+ else:
201
+ raw = _empty_atif_bytes()
202
+
203
+ session_path = _latest_session(logs_root)
204
+ if session_path is not None:
205
+ _validate_session_jsonl(session_path)
206
+ text, calls = _codex_session_items(session_path)
207
+ # Codex records MCP calls as event_msg/item_completed entries in the
208
+ # rollout JSONL (alongside response_item function calls). Include them
209
+ # when no trajectory envelope is available so MCP evidence is retained.
210
+ calls.extend(_session_mcp_calls(session_path, source_event_id))
211
+ for call in calls:
212
+ call["event_id"] = source_event_id
213
+ return raw, text, calls, "session.jsonl", session_path
214
+ if trajectory_valid:
215
+ # A valid empty ATIF document is legitimate for a no-op/empty response.
216
+ return raw, "", [], "trajectory.json", None
217
+ raise RuntimeError("Harbor produced neither a valid trajectory nor a session log")
218
+
219
+
220
+ def _replace_directory(tmp: Path, target: Path) -> None:
221
+ old: Path | None = None
222
+ if target.exists() or target.is_symlink():
223
+ old = target.parent / f".{target.name}.old-{os.getpid()}"
224
+ if old.exists() or old.is_symlink():
225
+ if old.is_dir() and not old.is_symlink():
226
+ shutil.rmtree(old)
227
+ else:
228
+ old.unlink()
229
+ os.replace(target, old)
230
+ try:
231
+ os.replace(tmp, target)
232
+ except Exception:
233
+ if old is not None and old.exists() and not target.exists():
234
+ os.replace(old, target)
235
+ raise
236
+ if old is not None:
237
+ if old.is_dir() and not old.is_symlink():
238
+ shutil.rmtree(old)
239
+ elif old.exists() or old.is_symlink():
240
+ old.unlink()
241
+
242
+
243
+ def collect_turn(
244
+ *,
245
+ workspace_root: Path,
246
+ logs_root: Path,
247
+ step_name: str,
248
+ virtual_stage: int,
249
+ source_event_id: str,
250
+ stage_boundary: bool,
251
+ ) -> Path:
252
+ """Replace the current staging bundle with evidence from this Harbor turn."""
253
+ workspace_root = Path(workspace_root)
254
+ logs_root = Path(logs_root)
255
+ stage_root = workspace_root / ".harbor-stage"
256
+ stage_root.mkdir(parents=True, exist_ok=True)
257
+ tmp = Path(tempfile.mkdtemp(prefix=".current.tmp-", dir=stage_root))
258
+ target = stage_root / "current"
259
+ try:
260
+ raw, text, calls, trajectory_source, session_path = _trajectory_and_items(
261
+ logs_root, step_name, source_event_id, workspace_root=workspace_root
262
+ )
263
+ (tmp / "trajectory.json").write_bytes(raw)
264
+ (tmp / "response.txt").write_text(text, encoding="utf-8")
265
+ _write_json(tmp / "trace.json", calls)
266
+ if session_path is not None:
267
+ shutil.copy2(session_path, tmp / "session.jsonl")
268
+
269
+
270
+ metadata = {
271
+ "schema_version": 1,
272
+ "step": step_name,
273
+ "virtual_stage": virtual_stage,
274
+ "source_event_id": source_event_id,
275
+ "stage_boundary": bool(stage_boundary),
276
+ "trajectory_source": trajectory_source,
277
+ "captured_at": utc_now(),
278
+ "scenario_clock": scenario_clock(),
279
+ }
280
+ _write_json(tmp / "metadata.json", metadata)
281
+ _replace_directory(tmp, target)
282
+ return target
283
+ finally:
284
+ if tmp.exists():
285
+ shutil.rmtree(tmp)
286
+
287
+
288
+ def _session_mcp_calls(path, event_id):
289
+ """ translated text codex session jsonl translated text MCP translated text , translated text trace translated text 。
290
+
291
+ codex translated text MCP translated text ** translated text ** translated text ``event_msg`` translated text ``item_completed`` translated text
292
+ (``item.type == "McpToolCall"``);``response_item`` translated text exec
293
+ (``custom_tool_call``)。 translated text ``<server>__<tool>``——rubric translated text
294
+ ``_server()`` translated text 。
295
+ """
296
+ import json as _json
297
+
298
+ out = []
299
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
300
+ line = line.strip()
301
+ if not line:
302
+ continue
303
+ try:
304
+ row = _json.loads(line)
305
+ except ValueError:
306
+ continue
307
+ if row.get("type") != "event_msg":
308
+ continue
309
+ payload = row.get("payload") or {}
310
+ if payload.get("type") != "item_completed":
311
+ continue
312
+ item = payload.get("item") or {}
313
+ item_type = str(item.get("type") or "").replace("_", "").lower()
314
+ if item_type != "mcptoolcall":
315
+ continue
316
+ server = str(item.get("server") or item.get("server_name") or "")
317
+ tool = str(item.get("tool") or item.get("tool_name") or "")
318
+ # server == "codex" translated text CLI translated text (list_mcp_resources translated text ), translated text task
319
+ # translated text ; translated text _stage_servers_correct translated text allow_extra=False translated text 。
320
+ if not server or not tool or server == "codex":
321
+ continue
322
+ result = item.get("result", item.get("output"))
323
+ args = item.get("arguments", item.get("input", {}))
324
+ out.append({
325
+ "event_id": event_id,
326
+ "id": str(item.get("id") or ("mcp-%d" % len(out))),
327
+ "name": "%s__%s" % (server, tool),
328
+ "arguments": args if isinstance(args, dict) else {},
329
+ "success": str(item.get("status") or "").lower() == "completed"
330
+ and _tool_result_success({"content": result}),
331
+ "result": _jsonable(result),
332
+ })
333
+ return out
334
+
335
+
336
+ def main(argv: list[str] | None = None) -> int:
337
+ parser = argparse.ArgumentParser()
338
+ parser.add_argument("step_name")
339
+ parser.add_argument("virtual_stage", type=int)
340
+ parser.add_argument("source_event_id")
341
+ parser.add_argument("stage_boundary", choices=("0", "1"))
342
+ args = parser.parse_args(argv)
343
+ collect_turn(
344
+ workspace_root=Path("/workspace"),
345
+ logs_root=Path("/logs/agent"),
346
+ step_name=args.step_name,
347
+ virtual_stage=args.virtual_stage,
348
+ source_event_id=args.source_event_id,
349
+ stage_boundary=args.stage_boundary == "1",
350
+ )
351
+ return 0
352
+
353
+
354
+ if __name__ == "__main__":
355
+ raise SystemExit(main())
harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/harbor_env.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
88
+ class _Fs:
89
+ """Live read-only workspace adapter used only during trusted collection."""
90
+
91
+ def __init__(self, workspace_root: Path | str = DEFAULT_WORKSPACE_ROOT) -> None:
92
+ self.workspace_root = Path(workspace_root)
93
+
94
+ def _candidate(self, path: str) -> Path:
95
+ raw = str(path).rstrip("/") or "/"
96
+ # Bare "/workspace" must resolve to the root itself. Falling through to
97
+ # the generic branch below would append "workspace/" and silently yield
98
+ # an empty listing — and because the rubrics only ask whether *any*
99
+ # workspace value is non-empty, that produces zero captured evidence
100
+ # instead of an error.
101
+ if raw == "/workspace":
102
+ return self.workspace_root
103
+ if raw.startswith("/workspace/"):
104
+ return self.workspace_root / raw[len("/workspace/") :]
105
+ return self.workspace_root / raw.lstrip("/")
106
+
107
+ def read_file(self, path: str) -> bytes:
108
+ candidate = self._candidate(path)
109
+ if not candidate.is_file() or candidate.is_symlink():
110
+ raise FileNotFoundError(path)
111
+ return candidate.read_bytes()
112
+
113
+ def exists(self, path: str) -> bool:
114
+ candidate = self._candidate(path)
115
+ return candidate.exists() and not candidate.is_symlink()
116
+
117
+ def list_dir(self, path: str) -> list[str]:
118
+ candidate = self._candidate(path)
119
+ if not candidate.is_dir() or candidate.is_symlink():
120
+ return []
121
+ return sorted(child.name for child in candidate.iterdir() if not child.is_symlink())
122
+
123
+ def write_file(self, path: str, data: bytes) -> None:
124
+ raise PermissionError("trusted collector workspace view is read-only")
125
+
126
+
127
+ class _Workspace:
128
+ def __init__(self, workspace_root: Path | str = DEFAULT_WORKSPACE_ROOT) -> None:
129
+ self.fs = _Fs(workspace_root)
130
+
131
+
132
+ class HarborEnv:
133
+ """Duck-typed ``env`` exposing ``<server>_mock`` and ``workspace``."""
134
+
135
+ def __init__(
136
+ self, servers: list[str], workspace_root: Path | str = DEFAULT_WORKSPACE_ROOT
137
+ ) -> None:
138
+ self.workspace = _Workspace(workspace_root)
139
+ self._caps: dict[str, _McpCapability] = {}
140
+ for server in servers:
141
+ cap = _McpCapability(server)
142
+ self._caps[server] = cap
143
+ setattr(self, f"{server}_mock", cap)
144
+
145
+ def capability(self, server: str) -> _McpCapability | None:
146
+ return self._caps.get(server)
harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/response_capture.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ content = _field(block, "content", "")
60
+ return not _errorish(content)
61
+
62
+
63
+ def _content_blocks(message: Any) -> list[Any]:
64
+ content = _field(message, "content", "")
65
+ if isinstance(content, list):
66
+ return content
67
+ return []
68
+
69
+
70
+ def extract_assistant_text(messages: Iterable[Any]) -> str:
71
+ """Port of the source ``_extract_assistant_text`` (joins with ``\\n``)."""
72
+ chunks: list[str] = []
73
+ for message in messages or []:
74
+ if _field(message, "role") != "assistant":
75
+ continue
76
+ content = _field(message, "content", "")
77
+ if isinstance(content, str):
78
+ if content:
79
+ chunks.append(content)
80
+ continue
81
+ for block in content or []:
82
+ if _field(block, "type") == "text":
83
+ text = _field(block, "text", "") or ""
84
+ if text:
85
+ chunks.append(text)
86
+ return "\n".join(chunks)
87
+
88
+
89
+ def extract_tool_calls(messages: Iterable[Any], event_id: str | None = None) -> list[dict[str, Any]]:
90
+ """Port of the source ``_extract_tool_calls`` over ``role``/``content``."""
91
+ calls: list[dict[str, Any]] = []
92
+ by_id: dict[str, dict[str, Any]] = {}
93
+ for message in messages or []:
94
+ role = _field(message, "role")
95
+ if role == "assistant":
96
+ for block in _content_blocks(message):
97
+ if _field(block, "type", "") not in ("toolCall", "tool_call", "tool_use"):
98
+ continue
99
+ call = {
100
+ "event_id": event_id,
101
+ "id": _field(block, "id", _field(block, "tool_call_id", _field(block, "toolCallId"))),
102
+ "name": _field(block, "name"),
103
+ "arguments": _jsonable(_field(block, "arguments", _field(block, "input", {}))),
104
+ "success": None,
105
+ "result": None,
106
+ }
107
+ calls.append(call)
108
+ if call["id"] is not None:
109
+ by_id[str(call["id"])] = call
110
+ blocks = _content_blocks(message)
111
+ if role in ("user", "tool", "toolResult", "tool_result") and not blocks:
112
+ blocks = [message]
113
+ for block in blocks:
114
+ typ = _field(block, "type", "")
115
+ if typ not in ("toolResult", "tool_result") and role not in (
116
+ "tool",
117
+ "toolResult",
118
+ "tool_result",
119
+ ):
120
+ continue
121
+ tool_id = _field(
122
+ block,
123
+ "tool_use_id",
124
+ _field(block, "tool_call_id", _field(block, "toolCallId", _field(block, "id"))),
125
+ )
126
+ if tool_id is None:
127
+ continue
128
+ call = by_id.get(str(tool_id))
129
+ if call is not None:
130
+ call["success"] = _tool_result_success(block)
131
+ call["result"] = _jsonable(_field(block, "content", ""))
132
+ return calls
133
+
134
+
135
+ def _is_atif(trajectory: Any) -> bool:
136
+ steps = trajectory.get("steps") if isinstance(trajectory, dict) else None
137
+ return isinstance(steps, list) and any(
138
+ isinstance(step, dict) and "source" in step for step in steps
139
+ )
140
+
141
+
142
+ def _atif_window(trajectory: dict[str, Any]) -> list[dict[str, Any]]:
143
+ """Turns after the last user turn — the work belonging to this step.
144
+
145
+ Earlier turns belong to earlier steps; including them would replay every
146
+ previous step's prose and tool calls into each later stage.
147
+ """
148
+ steps = [step for step in trajectory.get("steps") or [] if isinstance(step, dict)]
149
+ last_user = -1
150
+ for index, step in enumerate(steps):
151
+ if str(step.get("source", "")).lower() == "user":
152
+ last_user = index
153
+ return steps[last_user + 1 :]
154
+
155
+
156
+ def atif_step_slice(trajectory: Any) -> dict[str, Any] | None:
157
+ """This step's own turns, in the ATIF envelope the verifier expects.
158
+
159
+ Harbor rewrites ``trajectory.json`` as the whole cumulative session on every
160
+ step, so step N carries steps 1..N-1 verbatim. Freezing that per stage costs
161
+ O(steps^2) on disk for no scoring value: the rubrics read only ``response``
162
+ and ``trace``, and the last step's copy already holds the full session.
163
+ Keep the envelope (``schema_version``/``session_id``/``agent``) so the file
164
+ stays a valid ATIF document, and carry the trailing user turn so the frozen
165
+ evidence still shows what this step was asked to do.
166
+
167
+ Returns None for non-ATIF input, leaving the caller on its raw-bytes path.
168
+ """
169
+ if not _is_atif(trajectory):
170
+ return None
171
+ steps = [step for step in trajectory.get("steps") or [] if isinstance(step, dict)]
172
+ last_user = -1
173
+ for index, step in enumerate(steps):
174
+ if str(step.get("source", "")).lower() == "user":
175
+ last_user = index
176
+ # Keep only turns after the trailing user prompt; the prompt itself is
177
+ # metadata for the step and is not evidence of agent work.
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_session_items(path: Path) -> tuple[str, list[dict[str, Any]]]:
271
+ """Read a Codex session JSONL into (prose, tool calls).
272
+
273
+ Harbor's codex agent converts sessions to ATIF *on the host*, so the
274
+ container only ever has ``/logs/agent/sessions/**/rollout-*.jsonl``. Reading
275
+ it directly is what keeps the Tool Call and Final buckets scorable — without
276
+ this the verifier sees an empty trajectory and those 20 points are
277
+ unreachable no matter what the agent did.
278
+ """
279
+ texts: list[str] = []
280
+ calls: dict[str, dict[str, Any]] = {}
281
+ order: list[str] = []
282
+ outputs: dict[str, Any] = {}
283
+ try:
284
+ lines = path.read_text(encoding="utf-8").splitlines()
285
+ except OSError:
286
+ return "", []
287
+ for line in lines:
288
+ line = line.strip()
289
+ if not line:
290
+ continue
291
+ try:
292
+ row = json.loads(line)
293
+ except json.JSONDecodeError:
294
+ continue
295
+ if row.get("type") != "response_item":
296
+ continue
297
+ payload = row.get("payload") or {}
298
+ kind = payload.get("type")
299
+ if kind == "message" and payload.get("role") == "assistant":
300
+ for block in payload.get("content") or []:
301
+ if isinstance(block, dict):
302
+ text = block.get("text") or ""
303
+ if text:
304
+ texts.append(text)
305
+ elif kind == "function_call":
306
+ call_id = str(payload.get("call_id") or "")
307
+ if not call_id:
308
+ continue
309
+ args = payload.get("arguments")
310
+ if isinstance(args, str):
311
+ try:
312
+ args = json.loads(args)
313
+ except json.JSONDecodeError:
314
+ args = {}
315
+ calls[call_id] = {
316
+ "event_id": None,
317
+ "id": call_id,
318
+ "name": str(payload.get("name") or ""),
319
+ "arguments": args if isinstance(args, dict) else {},
320
+ "success": None,
321
+ "result": None,
322
+ }
323
+ order.append(call_id)
324
+ elif kind == "function_call_output":
325
+ call_id = str(payload.get("call_id") or "")
326
+ if call_id:
327
+ outputs[call_id] = payload.get("output")
328
+ out: list[dict[str, Any]] = []
329
+ for call_id in order:
330
+ call = calls[call_id]
331
+ if call_id in outputs:
332
+ content = outputs[call_id]
333
+ call["success"] = _tool_result_success({"content": content})
334
+ call["result"] = _jsonable(content)
335
+ out.append(call)
336
+ return "\n".join(texts), out
337
+
338
+
339
+ def _load_trajectory(path: Path) -> Any:
340
+ if not path.is_file():
341
+ return None
342
+ try:
343
+ return json.loads(path.read_text(encoding="utf-8"))
344
+ except (OSError, json.JSONDecodeError):
345
+ return None
346
+
347
+
348
+ def step_text_and_calls(
349
+ trajectory: Any, step_name: str, event_id: str | None
350
+ ) -> tuple[str, list[dict[str, Any]]]:
351
+ """Prose and tool calls for one Harbor step, whichever dialect was written."""
352
+ if not isinstance(trajectory, dict):
353
+ return "", []
354
+ if _is_atif(trajectory):
355
+ return _atif_text(trajectory), _atif_tool_calls(trajectory, event_id)
356
+ messages = _messages_for_step(trajectory, step_name)
357
+ return extract_assistant_text(messages), extract_tool_calls(messages, event_id)
harbor/shopping/apple_watch_tradein_30d/environment/evidence-collector/snapshot_capture.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture the authoritative stage-boundary world through MCP — apple_watch_tradein_30d.
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
6
+ returned dictionary is written directly into the private evidence volume; this
7
+ module never materializes historical files in the agent workspace.
8
+
9
+ translated text task translated text status translated text rubric translated text ( translated text tests/rubrics/checks.py):
10
+ - workspace translated text item( translated text ledger/ translated text / translated text /risk/ translated text )—— translated text check translated text ;
11
+ - ecommerce:cart(s8_optimal translated text )、order(two transactions translated text / translated text order translated text )、 translated text /SKU translated text ( translated text token:sn SONAR-A7C2-6320/batch/vcode VRF-PSCN-6320G);
12
+ - credit_card:statement translated text (foreign currency tx_pscn_fx / duplicate charge tx_pscn_dup / reversal tx_pscn_rev / translated text tx_pscn_pp / dispute disp_pscn_01);
13
+ - notification_hub:notification translated text (mutation translated text translated text /dispute/ translated text /credited translated text item);
14
+ - email:INBOX/Sent( translated text phishing、off-platformdeposit translated text );
15
+ - listing_platform / calendar / delivery_logistics / weather: translated text 、 translated text 、 translated text 、 translated text item translated text ( translated text rainstormalert)。
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ EXPECTED_WORLD_CLOCK_FILE = "/world-clock/current.json"
26
+ WORLD_CLOCK_FILE = Path(EXPECTED_WORLD_CLOCK_FILE)
27
+ CLOCK_KEYS = frozenset({"schema_version", "step", "now"})
28
+ SCENARIO_TIMES = {
29
+ "event-000": "2026-06-15T09:00:00+08:00", "event-001": "2026-06-15T09:30:00+08:00",
30
+ "event-002": "2026-06-16T10:00:00+08:00", "event-003": "2026-06-16T10:20:00+08:00",
31
+ "event-004": "2026-06-16T10:40:00+08:00", "event-005": "2026-06-17T14:30:00+08:00",
32
+ "event-006": "2026-06-18T18:20:00+08:00", "event-007": "2026-06-19T09:10:00+08:00",
33
+ "event-008": "2026-06-19T09:30:00+08:00", "event-009": "2026-06-20T11:20:00+08:00",
34
+ "event-010": "2026-06-21T15:10:00+08:00", "event-011": "2026-06-22T10:00:00+08:00",
35
+ "event-012": "2026-06-22T15:00:00+08:00", "event-013": "2026-06-23T13:30:00+08:00",
36
+ "event-014": "2026-06-24T09:20:00+08:00", "event-015": "2026-06-25T10:00:00+08:00",
37
+ "event-016": "2026-06-25T10:20:00+08:00", "event-017": "2026-06-26T16:20:00+08:00",
38
+ "event-018": "2026-06-28T09:00:00+08:00", "event-019": "2026-06-28T09:20:00+08:00",
39
+ "event-020": "2026-06-30T10:30:00+08:00", "event-021": "2026-07-02T09:00:00+08:00",
40
+ "event-022": "2026-07-02T09:30:00+08:00", "event-023": "2026-07-02T09:40:00+08:00",
41
+ "event-024": "2026-07-04T10:00:00+08:00", "event-025": "2026-07-06T14:00:00+08:00",
42
+ "event-026": "2026-07-08T18:30:00+08:00", "event-027": "2026-07-10T11:30:00+08:00",
43
+ "event-028": "2026-07-11T16:30:00+08:00", "event-029": "2026-07-12T10:00:00+08:00",
44
+ "event-030": "2026-07-13T10:00:00+08:00", "event-031": "2026-07-14T10:00:00+08:00",
45
+ }
46
+
47
+ USER_ID = "usr_mo_fan"
48
+ CARD_ID = "card_awch_01"
49
+ CALENDAR_ID = "cal_awch_task"
50
+
51
+ # translated text /SKU/order/ translated text rubric translated text id( translated text details, translated text token translated text )。
52
+ TRACKED_PRODUCT_IDS = ("prod_awch_main",)
53
+ # translated text (s8_optimal translated text cart translated text SKU)。
54
+ BUNDLE_PRODUCT_IDS = (
55
+ "prod_awch_001", "prod_awch_002", "prod_awch_003", "prod_awch_004",
56
+ "prod_awch_005", "prod_awch_006", "prod_awch_007",
57
+ )
58
+ TRACKED_ORDER_IDS = ("ord_awch_0001", "ord_awch_0002")
59
+ TRACKED_LISTING_IDS = ("lst_awch_0001", "lst_awch_0002", "lst_awch_0003")
60
+
61
+ BASELINE_WORKSPACE_NAMES = {
62
+ "AGENTS.md", "IDENTITY.md", "PERSONA.md", "SOUL.md", "TOOLS.md", "USER.md",
63
+ }
64
+ ALLOWED_WORKSPACE_SUFFIXES = (".md", ".txt", ".json", ".csv")
65
+
66
+
67
+ def _validate_clock_environment() -> None:
68
+ if os.environ.get("WORLD_CLOCK_FILE") != EXPECTED_WORLD_CLOCK_FILE:
69
+ raise RuntimeError(
70
+ f"WORLD_CLOCK_FILE must equal {EXPECTED_WORLD_CLOCK_FILE!r}"
71
+ )
72
+ if os.environ.get("SCENARIO_CLOCK_REQUIRED") != "1":
73
+ raise RuntimeError("SCENARIO_CLOCK_REQUIRED must equal '1'")
74
+ def scenario_clock(expected_step: str) -> dict[str, Any]:
75
+ _validate_clock_environment()
76
+ try:
77
+ payload = json.loads(WORLD_CLOCK_FILE.read_text(encoding="utf-8"))
78
+ if not isinstance(payload, dict) or set(payload) != CLOCK_KEYS:
79
+ raise ValueError(f"clock keys must be exactly {sorted(CLOCK_KEYS)}")
80
+ if not isinstance(expected_step, str) or not expected_step:
81
+ raise ValueError("expected Harbor step must be non-empty")
82
+ if payload["step"] != expected_step:
83
+ raise ValueError(
84
+ f"clock step {payload['step']!r} does not match expected {expected_step!r}"
85
+ )
86
+ if not isinstance(payload["now"], str) or not payload["now"].strip():
87
+ raise ValueError("clock now must be a non-empty string")
88
+ parsed = datetime.fromisoformat(payload["now"].replace("Z", "+00:00"))
89
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
90
+ raise ValueError("scenario clock must include an offset")
91
+ here = Path(__file__).resolve().parent.parent
92
+ map_candidates = []
93
+ env_map = os.environ.get("STEP_RELEASE_MAP")
94
+ if env_map:
95
+ map_candidates.append(Path(env_map))
96
+ map_candidates.extend(
97
+ [
98
+ # image layout: /opt/world-controller/{capture,snapshot_capture -> step-release-map.json}
99
+ here / "step-release-map.json",
100
+ # source-tree layout: environment/evidence-collector -> environment/world-controller
101
+ here / "world-controller" / "step-release-map.json",
102
+ Path("/opt/world-controller/step-release-map.json"),
103
+ ]
104
+ )
105
+ expected_now = SCENARIO_TIMES.get(expected_step)
106
+ mapped = next((c for c in map_candidates if c.is_file()), None)
107
+ if mapped is not None:
108
+ try:
109
+ expected_now = json.loads(mapped.read_text(encoding="utf-8"))["steps"][expected_step]["scenario_time"]
110
+ except Exception:
111
+ pass
112
+ if payload["now"] != expected_now:
113
+ raise ValueError(f"scenario clock mismatch for {expected_step}")
114
+ return dict(payload)
115
+ except Exception as exc:
116
+ raise RuntimeError(
117
+ f"required scenario clock unavailable at {WORLD_CLOCK_FILE}: {exc}"
118
+ ) from exc
119
+
120
+
121
+ def _decode(value: Any) -> Any:
122
+ if isinstance(value, str):
123
+ try:
124
+ return json.loads(value)
125
+ except json.JSONDecodeError:
126
+ return value
127
+ return value
128
+
129
+
130
+ def _unwrap_envelope(value: Any, fetch_page: Any = None) -> Any:
131
+ """Flatten the shared ``items`` pagination envelope without touching business objects."""
132
+ if not isinstance(value, dict):
133
+ return value
134
+ rows = value.get("items")
135
+ if not isinstance(rows, list) or ("total" not in value and "has_more" not in value):
136
+ return value
137
+ merged = list(rows)
138
+ total = value.get("total")
139
+ page = int(value.get("page") or 1) + 1
140
+ while fetch_page is not None and value.get("has_more") and page <= 100:
141
+ nxt = fetch_page(page)
142
+ if not isinstance(nxt, dict) or not isinstance(nxt.get("items"), list):
143
+ value["_pagination_incomplete"] = True
144
+ break
145
+ merged.extend(nxt["items"])
146
+ value = nxt
147
+ page += 1
148
+ if isinstance(total, int) and len(merged) >= total:
149
+ break
150
+ if value.get("has_more"):
151
+ merged_marker = list(merged)
152
+ result = dict(value)
153
+ result["items"] = merged_marker
154
+ result["_pagination_incomplete"] = True
155
+ return result
156
+ return merged
157
+
158
+
159
+ def _call(env: Any, server: str, tool: str, **kwargs: Any) -> Any:
160
+ """Mirror of the source ``_snapshot_call``: never raise, record the error."""
161
+ cap = getattr(env, f"{server}_mock", None)
162
+ if cap is None:
163
+ return {"error": f"missing capability: {server}"}
164
+ try:
165
+ value = _decode(cap.call_tool(tool, **kwargs))
166
+ return _unwrap_envelope(
167
+ value,
168
+ lambda page: _decode(cap.call_tool(tool, **{**kwargs, "page": page})),
169
+ )
170
+ except BaseException as exc: # noqa: BLE001 - parity with source behaviour
171
+ return {"error": f"{type(exc).__name__}: {exc}"}
172
+
173
+
174
+ def _paged_call(env: Any, server: str, tool: str, *, rows_key: str, id_keys: tuple[str, ...], **kwargs: Any) -> Any:
175
+ """Walk email-style pages whose rows live under a service-specific key."""
176
+ first = _call(env, server, tool, page=1, page_size=50, **kwargs)
177
+ if not isinstance(first, dict):
178
+ return first
179
+ rows = [row for row in (first.get(rows_key) or []) if isinstance(row, dict)]
180
+ total = first.get("total_results", first.get("total"))
181
+ seen = {str(next((row.get(k) for k in id_keys if row.get(k) is not None), "")) for row in rows}
182
+ page = 2
183
+ while isinstance(total, (int, float)) and len(rows) < int(total) and page <= 100:
184
+ nxt = _call(env, server, tool, page=page, page_size=50, **kwargs)
185
+ if not isinstance(nxt, dict):
186
+ break
187
+ fresh = []
188
+ for row in (nxt.get(rows_key) or []):
189
+ if not isinstance(row, dict):
190
+ continue
191
+ rid = str(next((row.get(k) for k in id_keys if row.get(k) is not None), ""))
192
+ if rid not in seen:
193
+ seen.add(rid); fresh.append(row)
194
+ if not fresh:
195
+ break
196
+ rows.extend(fresh); page += 1
197
+ result = dict(first); result[rows_key] = rows; result["captured_count"] = len(rows)
198
+ if isinstance(total, (int, float)): result["captured_complete"] = len(rows) >= int(total)
199
+ return result
200
+
201
+
202
+ def _workspace_snapshot(env: Any) -> dict[str, str]:
203
+ """Agent-authored workspace files, baseline context excluded."""
204
+ fs = getattr(getattr(env, "workspace", None), "fs", None)
205
+ if fs is None:
206
+ return {}
207
+ out: dict[str, str] = {}
208
+ seen: set[str] = set()
209
+
210
+ def visit(path: str, depth: int) -> None:
211
+ if path in seen or len(out) >= 200:
212
+ return
213
+ seen.add(path)
214
+ name = path.rsplit("/", 1)[-1]
215
+ if name in BASELINE_WORKSPACE_NAMES:
216
+ return
217
+ if name.startswith("."):
218
+ return
219
+ if name.lower().endswith(ALLOWED_WORKSPACE_SUFFIXES):
220
+ try:
221
+ raw = fs.read_file(path)
222
+ except Exception: # noqa: BLE001
223
+ raw = None
224
+ if raw is not None:
225
+ text = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else str(raw)
226
+ if text.strip():
227
+ out[path] = text[:200000]
228
+ return
229
+ if depth <= 0:
230
+ return
231
+ try:
232
+ children = fs.list_dir(path)
233
+ except Exception: # noqa: BLE001
234
+ return
235
+ for child in children:
236
+ visit(f"{path.rstrip('/')}/{child}", depth - 1)
237
+
238
+ visit("/workspace", 4)
239
+ return out
240
+
241
+
242
+ def _ecommerce_snapshot(env: Any) -> dict[str, Any]:
243
+ return {
244
+ "cart": _call(env, "ecommerce", "get_cart", user_id=USER_ID),
245
+ "orders": {
246
+ "list": _call(env, "ecommerce", "list_orders", user_id=USER_ID, limit=50),
247
+ "details": {
248
+ oid: _call(env, "ecommerce", "get_order", order_id=oid)
249
+ for oid in TRACKED_ORDER_IDS
250
+ },
251
+ },
252
+ "products": {
253
+ pid: _call(env, "ecommerce", "get_product", product_id=pid)
254
+ for pid in (TRACKED_PRODUCT_IDS + BUNDLE_PRODUCT_IDS)
255
+ },
256
+ }
257
+
258
+
259
+ def _credit_card_snapshot(env: Any) -> dict[str, Any]:
260
+ return {
261
+ "statements": _call(env, "credit_card", "list_statements", card_id=CARD_ID, limit=12),
262
+ "unbilled": _call(env, "credit_card", "list_unbilled", card_id=CARD_ID),
263
+ "disputes": _call(env, "credit_card", "list_disputes", card_id=CARD_ID),
264
+ }
265
+
266
+
267
+ def _delivery_snapshot(env: Any) -> dict[str, Any]:
268
+ return {
269
+ "shipments": _call(env, "delivery_logistics", "list_shipments", user_id=USER_ID),
270
+ "tracking": {
271
+ "line1": _call(env, "delivery_logistics", "track_package", tracking_no="SF8259520001CN"),
272
+ "line2": _call(env, "delivery_logistics", "track_package", tracking_no="YTOAWCH5520002CN"),
273
+ },
274
+ }
275
+
276
+
277
+ def _listing_snapshot(env: Any) -> dict[str, Any]:
278
+ return {
279
+ lid: _call(env, "listing_platform", "get_listing_detail", listing_id=lid)
280
+ for lid in TRACKED_LISTING_IDS
281
+ }
282
+
283
+
284
+ def capture_stage_snapshot(
285
+ env: Any, stage_idx: int, expected_step: str
286
+ ) -> dict[str, Any]:
287
+ """Freeze the stage-boundary world for apple_watch_tradein_30d."""
288
+ return {
289
+ "stage": stage_idx,
290
+ "scenario_clock": scenario_clock(expected_step),
291
+ "workspace": _workspace_snapshot(env),
292
+ "ecommerce": _ecommerce_snapshot(env),
293
+ "credit_card": _credit_card_snapshot(env),
294
+ "notification_hub": {
295
+ "notifications": _call(
296
+ env, "notification_hub", "list_notifications", user_id=USER_ID, limit=500
297
+ ),
298
+ "subscriptions": _call(
299
+ env, "notification_hub", "list_subscriptions", user_id=USER_ID
300
+ ),
301
+ },
302
+ "email": {
303
+ "inbox": _paged_call(env, "email", "get_emails", rows_key="emails", id_keys=("email_id", "id"), folder="INBOX"),
304
+ "sent": _paged_call(env, "email", "get_emails", rows_key="emails", id_keys=("email_id", "id"), folder="Sent"),
305
+ },
306
+ "listing_platform": _listing_snapshot(env),
307
+ "calendar": {
308
+ "events": _call(env, "calendar", "list_events", calendar_id=CALENDAR_ID, max_results=500),
309
+ },
310
+ "delivery_logistics": _delivery_snapshot(env),
311
+ "weather": {
312
+ "alerts": _call(env, "weather", "get_alerts", geo="Shanghai"),
313
+ },
314
+ }
harbor/shopping/apple_watch_tradein_30d/environment/seeds/calendar/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Calendar Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text , translated text table translated text evidence submission、 translated text 、 translated text close case translated text , translated text 、 translated text 、 translated text 。Stage 0 translated text record translated text descriptionuser translated text handling translated text ,cannot translated text 、 translated text ruling translated text credited。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai)。 translated text seed translated text ; translated text conditionreview、 translated text dispute translated text 、 translated text 、 translated text credited translated text Stage translated text 。future translated text , translated text cannot translated text 。
8
+
9
+ ## translated text
10
+ translated text includesuser `usr_mo_fan`、order `ord_awch_0001` / `ord_awch_0002`、evidence submission translated text 、payment due date translated text close case translated text 。 translated text confirmed、tentative、cancelled status, translated text attendees、reminders translated text events translated text linked, translated text item、 translated text 。
11
+
12
+ ## translated text description
13
+ translated text 、 translated text userconfirm。 translated text 、 translated text 、appraisal translated text status translated text verify,cannot translated text itemtitle translated text 。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/calendar/init.sql ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Stage 0 calendar state for translated text on 2026-06-15; review and settlement results are event-gated.
2
+ BEGIN;
3
+ INSERT INTO calendars (calendar_id,user_id,name,color,timezone,is_primary,created_at) VALUES
4
+ ('cal_awch_main','usr_mo_fan','Personal calendar','#4285F4','Asia/Shanghai',1,'2024-01-01T00:00:00Z'),
5
+ ('cal_awch_task','usr_mo_fan','Apple Watch trade-in','#0B8043','Asia/Shanghai',0,'2026-05-22T00:00:00Z'),
6
+ ('cal_awch_work','usr_mo_fan','Fitness studio schedule','#8E24AA','Asia/Shanghai',0,'2025-10-01T00:00:00Z');
7
+ INSERT INTO events (event_id,calendar_id,summary,description,location,start_dt,end_dt,all_day,status,created_at,updated_at,recurrence_rule,parent_event_id) VALUES
8
+ ('0d7a4c92-b561-48ef-93a2-6c18e5b7d4fa','cal_awch_task',' translated text table translated text review','verifymodel、serial number、batch、inspection reference translated text battery healthrecord。','online','2026-06-16T19:30:00+08:00','2026-06-16T20:20:00+08:00',0,'confirmed','2026-06-09T00:00:00Z','2026-06-09T00:00:00Z',NULL,NULL),
9
+ ('83e1b6d5-2c94-47a0-bf38-5d7a21e96c4f','cal_awch_task','recycler translated text ',' translated text appraisalreview translated text formalstatus translated text 。','online','2026-06-20T12:00:00+08:00','2026-06-20T12:20:00+08:00',0,'tentative','2026-06-14T00:00:00Z','2026-06-14T00:00:00Z',NULL,NULL),
10
+ ('f4a29c81-6d35-42be-8c71-1b9e50d64af3','cal_awch_task',' translated text ',' translated text battery health translated text 、appearancephotos、 translated text video、 translated text record。','Home translated text ','2026-06-24T20:00:00+08:00','2026-06-24T21:00:00+08:00',0,'confirmed','2026-06-12T00:00:00Z','2026-06-12T00:00:00Z',NULL,NULL),
11
+ ('2b97d5e3-c816-49a4-a1f3-7e52c08d64bf','cal_awch_task',' translated text ledgerreview',' translated text table translated text 、 translated text discount translated text 、dispute translated text credited。','online','2026-06-30T09:00:00+08:00','2026-06-30T09:30:00+08:00',0,'confirmed','2026-06-12T00:00:00Z','2026-06-12T00:00:00Z',NULL,NULL),
12
+ ('d61c4a09-3e58-43fb-97d2-8a20b5e16c7f','cal_awch_task','platform reviewevidence submission translated text ',' translated text 7 translated text 9 translated text ;confirm translated text 。','online','2026-07-09T18:00:00+08:00','2026-07-09T18:30:00+08:00',0,'confirmed','2026-06-11T00:00:00Z','2026-06-11T00:00:00Z',NULL,NULL),
13
+ ('75e8b3d2-f104-46ac-9b71-2c5d80a63ef4','cal_awch_main',' translated text payment due date','normalamount due translated text disputeamountrespectivelyverify。',' translated text ','2026-07-10T09:00:00+08:00','2026-07-10T09:20:00+08:00',0,'confirmed','2026-06-06T00:00:00Z','2026-06-06T00:00:00Z',NULL,NULL),
14
+ ('a3d52f86-7c19-45e0-b4a8-9f20d76c315e','cal_awch_task','closing deadline',' translated text tableverify、appraisalreview、top-up payment translated text archive。','online','2026-07-15T10:30:00+08:00','2026-07-15T11:30:00+08:00',0,'confirmed','2026-06-01T00:00:00Z','2026-06-01T00:00:00Z',NULL,NULL),
15
+ ('6c18e5b4-92d3-4fa7-81c0-5e26b9d74a3f','cal_awch_work',' translated text ','verify translated text 、 translated text rules translated text 。',' translated text 2F','2026-06-18T15:00:00+08:00','2026-06-18T16:00:00+08:00',0,'confirmed','2026-06-05T00:00:00Z','2026-06-05T00:00:00Z',NULL,NULL),
16
+ ('e802b7a1-4d73-48cf-a519-6b9e25d63f0c','cal_awch_main',' translated text ',' translated text 。',' translated text ','2026-06-28T10:00:00+08:00','2026-06-28T11:00:00+08:00',0,'confirmed','2026-06-10T00:00:00Z','2026-06-10T00:00:00Z',NULL,NULL),
17
+ ('5f63a8d9-b210-46e4-97c5-1d8a42b73e6f','cal_awch_main','Home translated text ',' translated text ,retain translated text 。','ShanghaiXuhui translated text ','2026-06-14T09:00:00+08:00','2026-06-14T11:00:00+08:00',0,'cancelled','2026-06-11T00:00:00Z','2026-06-13T00:00:00Z',NULL,NULL),
18
+ ('b4d91c36-2a75-49ef-83b0-7c86e15d4a2f','cal_awch_work',' translated text ',' translated text 。','online translated text ','2026-07-03T16:00:00+08:00','2026-07-03T17:00:00+08:00',0,'confirmed','2026-06-08T00:00:00Z','2026-06-08T00:00:00Z',NULL,NULL),
19
+ ('38a7e5c4-d961-43b8-a2f0-6e25c97d14ba','cal_awch_main',' translated text ',' translated text , translated text 。',' translated text ','2026-05-31T13:30:00+08:00','2026-05-31T17:10:00+08:00',0,'confirmed','2026-05-16T08:20:00Z','2026-05-31T09:25:00Z',NULL,NULL),
20
+ ('c7f42b93-8e15-46ad-90d3-2a6b51e78cf4','cal_awch_main',' translated text item',' translated text , translated text 。',' translated text ','2026-06-12T18:20:00+08:00','2026-06-12T18:45:00+08:00',0,'confirmed','2026-06-09T05:10:00Z','2026-06-12T11:05:00Z',NULL,NULL),
21
+ ('90d3a7f8-2c65-4be1-b940-5e37d82a6c1f','cal_awch_main',' translated text ',' translated text photos,active translated text 86 translated text 。',' translated text ','2026-06-06T18:10:00+08:00','2026-06-06T21:30:00+08:00',0,'confirmed','2026-05-28T09:35:00Z','2026-06-06T14:15:00Z',NULL,NULL),
22
+ ('4a82e1d7-f356-40bc-8d59-3c70a96e25bf','cal_awch_main',' translated text ',' translated text table translated text , translated text item translated text 。',' translated text ','2026-06-09T14:00:00+08:00','2026-06-09T16:05:00+08:00',0,'confirmed','2026-06-01T06:50:00Z','2026-06-09T08:20:00Z',NULL,NULL);
23
+ INSERT INTO attendees (event_id,email,name,response_status) VALUES
24
+ ('6c18e5b4-92d3-4fa7-81c0-5e26b9d74a3f','ops-review@studio.example',' translated text group','accepted'),
25
+ ('e802b7a1-4d73-48cf-a519-6b9e25d63f0c','booking@jingan-sports.example',' translated text ','accepted'),
26
+ ('b4d91c36-2a75-49ef-83b0-7c86e15d4a2f','coaches@studio.example',' translated text ','accepted');
27
+ INSERT INTO reminders (event_id,method,minutes_before) VALUES
28
+ ('0d7a4c92-b561-48ef-93a2-6c18e5b7d4fa','popup',120),('83e1b6d5-2c94-47a0-bf38-5d7a21e96c4f','email',1440),('f4a29c81-6d35-42be-8c71-1b9e50d64af3','popup',180),('2b97d5e3-c816-49a4-a1f3-7e52c08d64bf','popup',60),
29
+ ('d61c4a09-3e58-43fb-97d2-8a20b5e16c7f','email',2880),('d61c4a09-3e58-43fb-97d2-8a20b5e16c7f','popup',360),('75e8b3d2-f104-46ac-9b71-2c5d80a63ef4','popup',1440),('a3d52f86-7c19-45e0-b4a8-9f20d76c315e','email',2880),
30
+ ('6c18e5b4-92d3-4fa7-81c0-5e26b9d74a3f','popup',30),('e802b7a1-4d73-48cf-a519-6b9e25d63f0c','popup',1440),('b4d91c36-2a75-49ef-83b0-7c86e15d4a2f','popup',60),
31
+ ('38a7e5c4-d961-43b8-a2f0-6e25c97d14ba','popup',45),('c7f42b93-8e15-46ad-90d3-2a6b51e78cf4','email',360),
32
+ ('90d3a7f8-2c65-4be1-b940-5e37d82a6c1f','popup',90),('4a82e1d7-f356-40bc-8d59-3c70a96e25bf','email',720);
33
+ INSERT INTO _counters (key,value) VALUES ('event_seq',15);
34
+ COMMIT;
harbor/shopping/apple_watch_tradein_30d/environment/seeds/credit_card/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Credit Card Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text statement、details、 translated text 、 translated text 、 translated text a transaction translated text dispute, translated text verifysmartwatch translated text 、overseas originalwatch bandforeign currency translated text 。Stage 0 translated text status, translated text 、 translated text 、pay translated text separate。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai)。 translated text foreign currencyduplicate charge、 translated text dispute、 translated text approved translated text reversal translated text ,respectively translated text 。 translated text disputelinked translated text , translated text table translated text duplicate charge translated text 。
8
+
9
+ ## translated text
10
+ translated text includes `card_awch_01`、statementduration、 translated text merchant。 translated text 、 translated text 、 translated text item translated text 、 translated text , translated text merchant、MCC、category translated text kind;statement_lines、unbilled_transactions、payments、rewards_balances translated text rewards_ledger translated text consistent。
11
+
12
+ ## translated text description
13
+ translated text 、 translated text 、dispute translated text 、 translated text reversal translated text normal translated text respectivelyrecord。notification translated text email translated text ,amount translated text status translated text 。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/credit_card/init.sql ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Stage 0 card state for translated text on 2026-06-15; future duplicate charge, dispute approval and credits are absent.
2
+ BEGIN;
3
+ INSERT INTO cards (card_id,user_id,issuer,product_name,masked_no,type,credit_limit_minor,available_credit_minor,statement_balance_minor,unbilled_balance_minor,min_payment_due_minor,due_date,cycle_start_day,cycle_end_day,grace_period_days,status,interest_apr_bp) VALUES
4
+ ('card_awch_01','usr_mo_fan','China Merchants Bank','Classic White Visa','**** **** **** 8634','Visa',4000000,3120000,459900,113600,45990,'2026-07-10',8,7,25,'active',1800),
5
+ ('card_awch_02','usr_mo_fan','SPDB Shanghai Life UnionPay',' translated text ','**** **** **** 2751','UnionPay',3000000,2586600,266800,42600,266800,'2026-06-29',18,17,12,'active',1700);
6
+ INSERT INTO statements (statement_id,card_id,period_start,period_end,opening_balance_minor,new_charges_minor,payments_minor,closing_balance_minor,min_payment_due_minor,due_date,status) VALUES
7
+ ('stmt_awch','card_awch_01','2026-06-08','2026-07-07',0,459900,0,459900,45990,'2026-07-10','open'),
8
+ ('SPDB-2751-20260617-L5C8','card_awch_02','2026-05-18','2026-06-17',95400,266800,95400,266800,266800,'2026-06-29','open');
9
+ INSERT INTO statement_lines (line_id,statement_id,posted_at,amount_minor,merchant_name,mcc,category,kind) VALUES
10
+ ('line_awch_1','stmt_awch','2026-06-15T19:20:05+08:00',459900,'Apple official translated text ','5732','wearable electronics','purchase'),
11
+ ('SPDB-METRO-0519-H2Q7','SPDB-2751-20260617-L5C8','2026-05-19T08:25:00+08:00',4200,' translated text ','4111',' translated text ','purchase'),
12
+ ('SPDB-LUNCH-0522-C8M4','SPDB-2751-20260617-L5C8','2026-05-22T12:40:00+08:00',7280,' translated text ','5812',' translated text ','purchase'),
13
+ ('SPDB-CLOUD-0526-P5R9','SPDB-2751-20260617-L5C8','2026-05-26T20:10:00+08:00',11800,' translated text ','4899',' translated text ','purchase'),
14
+ ('SPDB-ALDI-0530-W3K6','SPDB-2751-20260617-L5C8','2026-05-30T18:20:00+08:00',19800,' translated text ','5411',' translated text ','purchase'),
15
+ ('SPDB-IKEA-0603-N7V2','SPDB-2751-20260617-L5C8','2026-06-03T21:30:00+08:00',25900,' translated text Home translated text ','5712','Home translated text ','purchase'),
16
+ ('SPDB-SPORTS-0609-F4L8','SPDB-2751-20260617-L5C8','2026-06-09T18:30:00+08:00',26800,' translated text ','7997',' translated text ','purchase'),
17
+ ('SPDB-TELECOM-0613-J6T1','SPDB-2751-20260617-L5C8','2026-06-13T09:10:00+08:00',62620,' translated text ','4814',' translated text ','purchase'),
18
+ ('SPDB-ARTPASS-0521-B9D5','SPDB-2751-20260617-L5C8','2026-05-21T14:20:00+08:00',16800,' translated text ','7991',' translated text ','purchase'),
19
+ ('SPDB-OPTICAL-0605-X2S7','SPDB-2751-20260617-L5C8','2026-06-05T18:40:00+08:00',68000,' translated text ','8043',' translated text ','purchase'),
20
+ ('SPDB-PETCLINIC-0612-M8C3','SPDB-2751-20260617-L5C8','2026-06-12T09:35:00+08:00',23600,' translated text ','0742',' translated text ','purchase');
21
+ INSERT INTO unbilled_transactions (tx_id,card_id,posted_at,amount_minor,merchant_name,mcc,category,kind) VALUES
22
+ ('tx_awch_1','card_awch_01','2026-06-15T10:05:08+08:00',92000,'Apple Store','5732','wearable electronics','purchase'),
23
+ ('tx_awch_fx','card_awch_01','2026-06-15T11:30:00+08:00',14800,'GAZELLE US','4814','wearable electronics','purchase'),
24
+ ('CMB-LAWSON-0614-Q4N8','card_awch_01','2026-06-14T12:20:00+08:00',3460,' translated text ','5499',' translated text ','purchase'),
25
+ ('SPDB-TAXI-0613-V7H2','card_awch_02','2026-06-13T19:00:00+08:00',17600,' translated text ','4121',' translated text ','purchase'),
26
+ ('SPDB-GROCERY-0615-K3P9','card_awch_02','2026-06-15T08:10:00+08:00',25000,' translated text ','5411',' translated text ','purchase');
27
+ INSERT INTO payments (payment_id,card_id,posted_at,amount_minor,source_hint,applied_to_statement_minor,applied_to_unbilled_minor) VALUES
28
+ ('pay_awch_01','card_awch_02','2026-05-29T08:30:00+08:00',95400,' translated text account',95400,0),
29
+ ('pay_awch_02','card_awch_01','2026-05-10T09:00:00+08:00',268500,'China Merchants Bank translated text ',268500,0);
30
+ INSERT INTO disputes (dispute_id,card_id,tx_id,reason,status,opened_at,expected_resolution_date,resolved_at) VALUES
31
+ ('DSP-2751-20260613-P3H6','card_awch_02','SPDB-TAXI-0613-V7H2',' translated text ','approved','2026-06-13T20:00:00+08:00','2026-06-20','2026-06-14T15:20:00+08:00');
32
+ INSERT INTO rewards_balances (card_id,points_balance,ytd_earned,lifetime_earned,updated_at) VALUES
33
+ ('card_awch_01',20480,10800,65200,'2026-06-15T00:00:00Z'),('card_awch_02',7350,3980,30100,'2026-06-15T00:00:00Z');
34
+ INSERT INTO rewards_ledger (ledger_id,card_id,posted_at,kind,delta,balance_after,note) VALUES
35
+ ('rl_awch_1','card_awch_01','2026-06-15T19:20:05+08:00','earn',9198,20480,' translated text tableorder translated text confirm'),
36
+ ('rl_awch_2','card_awch_02','2026-06-13T09:10:00+08:00','earn',626,7350,' translated text statement translated text '),
37
+ ('rl_awch_3','card_awch_02','2026-06-01T09:00:00+08:00','redeem',-1000,6724,' translated text coupon'),
38
+ ('rl_awch_4','card_awch_01','2026-05-31T09:00:00+08:00','earn',480,11282,' translated text active translated text ');
39
+ INSERT INTO _counters (key,value) VALUES ('payment_seq',2),('line_seq',11),('dispute_seq',1),('ledger_seq',4);
40
+ COMMIT;
harbor/shopping/apple_watch_tradein_30d/environment/seeds/delivery_logistics/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Delivery Logistics Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text record translated text 、 translated text table translated text 、 translated text 、 translated text item translated text 、 translated text 、status translated text record。`SF8259520001CN` translated text `YTOAWCH5520002CN` translated text , translated text record translated text delivered、 translated text 、 translated text item、 translated text status。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai)。 translated text 、 translated text 、delivery receipt translated text ; translated text 、 translated text appearance translated text 、 translated text 、 translated text final translated text 。Stage 15 translated text rainstorm translated text 。
8
+
9
+ ## translated text
10
+ translated text order translated text 、 translated text 、 translated text current translated text 。 translated text approved shipments、shipment_events、pickups、issue_tickets、status_subscriptions translated text notifications_outbox translated text , translated text fact, translated text appraisal translated text 。
11
+
12
+ ## translated text description
13
+ translated text record translated text , translated text tablecondition、trade-in appraisal、disputereversal translated text platform review translated text 。 translated text verify。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/delivery_logistics/init.sql ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Stage 0 logistics state for translated text ; later review and settlement outcomes are not present.
2
+ BEGIN;
3
+ INSERT INTO address_book (address_id,user_id,label,recipient,phone,province,city,district,detail,postal_code,is_default) VALUES
4
+ ('abk_awch_1','usr_mo_fan',' translated text ',' translated text ( translated text SY2099)','4001234567','Guangdong','Guangzhou','Baiyun',' translated text A translated text 217 translated text SY2099 translated text ','510410',0),
5
+ ('abk_awch_2','usr_mo_fan','Home',' translated text ','13900000000','Shanghai','Shanghai','Pudong',' translated text 88 translated text 1203','201203',1),
6
+ ('abk_awch_3','usr_mo_fan','Office reception',' translated text ','02188886666','Shanghai','Shanghai','Xuhui',' translated text 88 translated text 6 translated text ','200030',0);
7
+ INSERT INTO shipments (shipment_id,user_id,tracking_no,carrier,service_level,status,sender_json,recipient_json,weight_kg,dimensions_json,declared_value_minor,fee_minor,created_at,eta_date,scheduled_pickup_at,updated_at,cancel_reason) VALUES
8
+ ('shp_awch_0001','usr_mo_fan','SF8259520001CN',' translated text ','express','delivered','{"recipient":"Apple translated text ","city":"Suzhou","district":"Industrial Park"}','{"recipient":" translated text ","city":"Shanghai","district":"Pudong"}',1.0,'{"length_cm":30,"width_cm":22,"height_cm":6}',380000,0,'2026-06-13T09:00:00+08:00','2026-06-15',NULL,'2026-06-15T16:40:00+08:00',NULL),
9
+ ('shp_awch_0002','usr_mo_fan','YTOAWCH5520002CN',' translated text ','standard','in_transit','{"recipient":" translated text ","city":"Shanghai","district":"Pudong"}','{"recipient":"Apple translated text ","city":"Suzhou","district":"Industrial Park"}',0.8,'{"length_cm":20,"width_cm":15,"height_cm":8}',380000,800,'2026-06-15T08:30:00+08:00','2026-06-17','2026-06-15T08:30:00+08:00','2026-06-15T20:10:00+08:00',NULL),
10
+ ('ship-JDVA55268831','usr_mo_fan','JDVA55268831',' translated text ','same_day','delivered','{"recipient":" translated text "}','{"recipient":" translated text ","district":"Pudong"}',0.6,'{"length_cm":28,"width_cm":20,"height_cm":12}',29900,0,'2026-05-20T08:00:00+08:00','2026-05-20',NULL,'2026-05-20T18:12:00+08:00',NULL),
11
+ ('ship-ZTO6821457712','usr_mo_fan','ZTO6821457712',' translated text ','standard','delivered','{"recipient":" translated text "}','{"recipient":" translated text ","district":"Pudong"}',0.9,'{"length_cm":35,"width_cm":25,"height_cm":8}',48900,600,'2026-05-27T10:00:00+08:00','2026-05-30',NULL,'2026-05-29T14:30:00+08:00',NULL),
12
+ ('ship-SFRA82590031','usr_mo_fan','SFRA82590031',' translated text ','express','returned','{"recipient":" translated text ","district":"Pudong"}','{"recipient":" translated text table translated text ","district":" translated text "}',0.3,'{"length_cm":18,"width_cm":12,"height_cm":8}',90000,1800,'2026-04-18T11:00:00+08:00','2026-04-19','2026-04-18T10:30:00+08:00','2026-04-20T09:20:00+08:00',' translated text item translated text '),
13
+ ('ship-EMS552093957CN','usr_mo_fan','EMS552093957CN',' translated text EMS','standard','cancelled','{"recipient":" translated text ","district":"Pudong"}','{"recipient":" translated text ","city":" translated text "}',1.4,'{"length_cm":38,"width_cm":28,"height_cm":16}',28000,1600,'2026-05-06T09:00:00+08:00','2026-05-09','2026-05-06T14:00:00+08:00','2026-05-06T10:10:00+08:00','shipment translated text '),
14
+ ('ship-ZTOAWCH39174620CN','usr_mo_fan','ZTOAWCH39174620CN',' translated text ','standard','delivered','{"recipient":" translated text ","district":" translated text "}','{"recipient":" translated text ","district":"Pudong"}',0.5,'{"length_cm":24,"width_cm":18,"height_cm":8}',42800,600,'2026-05-14T10:20:00+08:00','2026-05-17',NULL,'2026-05-16T16:32:00+08:00',NULL),
15
+ ('ship-SFAWCH71820455CN','usr_mo_fan','SFAWCH71820455CN',' translated text ','express','returned','{"recipient":" translated text ","district":"Pudong"}','{"recipient":" translated text item translated text ","district":" translated text "}',0.7,'{"length_cm":26,"width_cm":19,"height_cm":10}',65900,1500,'2026-06-01T08:50:00+08:00','2026-06-02','2026-06-01T08:30:00+08:00','2026-06-02T18:25:00+08:00',' translated text ');
16
+ INSERT INTO shipment_events (event_id,shipment_id,at,location,status_code,description) VALUES
17
+ ('SF8259520001CN-0613T0910-K7QA','shp_awch_0001','2026-06-13T09:10:00+08:00',' translated text Industrial Park','picked_up',' translated text Home translated text '),
18
+ ('SF8259520001CN-0614T0320-S4XM','shp_awch_0001','2026-06-14T03:20:00+08:00',' translated text ','in_transit',' translated text '),
19
+ ('SF8259520001CN-0615T1640-W9KD','shp_awch_0001','2026-06-15T16:40:00+08:00','ShanghaiPudong','delivered',' translated text delivery receipt'),
20
+ ('YTOAWCH5520002CN-0615T0845-C5LW','shp_awch_0002','2026-06-15T08:45:00+08:00','ShanghaiPudong','picked_up',' translated text old device translated text '),
21
+ ('YTOAWCH5520002CN-0615T2010-P7FC','shp_awch_0002','2026-06-15T20:10:00+08:00',' translated text ','in_transit',' translated text official recycling translated text '),
22
+ ('JDVA55268831-0520T0900-J4PR','ship-JDVA55268831','2026-05-20T09:00:00+08:00',' translated text ','out_for_delivery',' translated text '),
23
+ ('JDVA55268831-0520T1812-D9VT','ship-JDVA55268831','2026-05-20T18:12:00+08:00','ShanghaiPudong','delivered',' translated text delivery receipt'),
24
+ ('ZTO6821457712-0527T1200-N2GX','ship-ZTO6821457712','2026-05-27T12:00:00+08:00','SuzhouIndustrial Park','picked_up',' translated text Home translated text '),
25
+ ('ZTO6821457712-0529T1430-R6NB','ship-ZTO6821457712','2026-05-29T14:30:00+08:00','ShanghaiPudong','delivered',' translated text delivery receipt'),
26
+ ('SFRA82590031-0418T1110-B8SY','ship-SFRA82590031','2026-04-18T11:10:00+08:00','ShanghaiPudong','picked_up',' translated text item'),
27
+ ('SFRA82590031-0419T1500-G5UE','ship-SFRA82590031','2026-04-19T15:00:00+08:00','Shanghai translated text ','delivery_failed',' translated text '),
28
+ ('SFRA82590031-0420T0920-L3HZ','ship-SFRA82590031','2026-04-20T09:20:00+08:00','ShanghaiPudong','returned',' translated text item translated text '),
29
+ ('EMS552093957CN-0506T0920-Q7BJ','ship-EMS552093957CN','2026-05-06T09:20:00+08:00','ShanghaiPudong','pickup_scheduled',' translated text item'),
30
+ ('EMS552093957CN-0506T1010-E4CW','ship-EMS552093957CN','2026-05-06T10:10:00+08:00','ShanghaiPudong','cancelled','shipment translated text '),
31
+ ('YTOAWCH5520002CN-0615T2100-V9ZK','shp_awch_0002','2026-06-15T21:00:00+08:00',' translated text ','eta_updated',' translated text 6 translated text 17 translated text official recycling translated text '),
32
+ ('ZTOAWCH39174620CN-0514T1205-Y5MR','ship-ZTOAWCH39174620CN','2026-05-14T12:05:00+08:00',' translated text ','picked_up',' translated text '),
33
+ ('ZTOAWCH39174620CN-0516T1632-H2KL','ship-ZTOAWCH39174620CN','2026-05-16T16:32:00+08:00','ShanghaiPudong','delivered',' translated text delivery receipt'),
34
+ ('SFAWCH71820455CN-0601T0842-X8PV','ship-SFAWCH71820455CN','2026-06-01T08:42:00+08:00','ShanghaiPudong','picked_up',' translated text '),
35
+ ('SFAWCH71820455CN-0602T1825-M6DT','ship-SFAWCH71820455CN','2026-06-02T18:25:00+08:00','ShanghaiPudong','returned',' translated text shipment translated text delivery receipt');
36
+ INSERT INTO pickups (pickup_id,shipment_id,scheduled_at,completed_at,status) VALUES
37
+ ('pk_awch_1','ship-SFRA82590031','2026-04-18T10:30:00+08:00','2026-04-18T11:10:00+08:00','completed'),
38
+ ('pk_awch_2','ship-EMS552093957CN','2026-05-06T14:00:00+08:00',NULL,'cancelled'),
39
+ ('pk_awch_3','ship-SFAWCH71820455CN','2026-06-01T08:30:00+08:00','2026-06-01T08:42:00+08:00','completed');
40
+ INSERT INTO issue_tickets (ticket_id,shipment_id,issue_type,description,status,opened_at,expected_response_date,resolved_at) VALUES
41
+ ('case-SFRA82590031-MV8D','ship-SFRA82590031','wrong_address',' translated text ,request translated text ','resolved','2026-04-19T15:10:00+08:00','2026-04-20','2026-04-20T09:20:00+08:00'),
42
+ ('case-ZTO6821457712-SMS6','ship-ZTO6821457712','delivery_failed',' translated text , translated text ','resolved','2026-05-29T16:00:00+08:00','2026-05-30','2026-05-29T18:00:00+08:00'),
43
+ ('case-SFAWCH71820455-DMG3','ship-SFAWCH71820455CN','damaged',' translated text , translated text ','closed','2026-06-02T09:15:00+08:00','2026-06-03','2026-06-02T18:25:00+08:00');
44
+ INSERT INTO status_subscriptions (subscription_id,shipment_id,channel,target,active,created_at) VALUES
45
+ ('sublog_awch_1','shp_awch_0002','email','mo.fan.tradein@gmail.com',1,'2026-06-15T09:00:00+08:00'),
46
+ ('sublog_awch_2','shp_awch_0001','sms','13900000000',0,'2026-06-13T09:00:00+08:00');
47
+ INSERT INTO notifications_outbox (subscription_id,payload_json,queued_at,sent_at) VALUES
48
+ ('sublog_awch_1','{"tracking_no":"YTOAWCH5520002CN","status":"in_transit"}','2026-06-15T20:11:00+08:00','2026-06-15T20:12:00+08:00'),
49
+ ('sublog_awch_2','{"tracking_no":"SF8259520001CN","status":"delivered"}','2026-06-15T16:41:00+08:00','2026-06-15T16:42:00+08:00');
50
+ INSERT INTO _counters (key,value) VALUES ('shipment_seq',8),('event_seq',19),('pickup_seq',3),('ticket_seq',3),('subscription_seq',2),('outbox_seq',2),('address_seq',3);
51
+ COMMIT;
harbor/shopping/apple_watch_tradein_30d/environment/seeds/ecommerce/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ecommerce Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text smartwatchtrade-in translated text store translated text , translated text old Apple Watch Ultra first generation、official translated text 、in-store credit translated text option, translated text 、SKU、 translated text 、 translated text 、cart、 translated text coupon、order translated text 。Stage 0 translated text verify `ord_awch_0001`、`ord_awch_0002`、`sku_awch_main` translated text serial number、batch、inspection reference translated text battery health translated text 。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai)。 translated text reviewrecord `ref_awch_b`、rejected、additional materials、platform review translated text credited translated text seed translated text , translated text item translated text 。 translated text refund translated text , translated text differentorder translated text refund translated text 。
8
+
9
+ ## translated text
10
+ translated text order translated text ; translated text 、 translated text item、 translated text 、 translated text 、 translated text 、 translated text 、Home translated text 、 translated text Home、 translated text 、 translated text 、 translated text , translated text different translated text 、 translated text 、 translated text 、 translated text item。 translated text 、SKU、order translated text 、 translated text coupon、status translated text refund translated text complete translated text 。
11
+
12
+ ## translated text description
13
+ translated text battery health、 translated text appraisal、final translated text amount translated text table translated text different translated text 。confirmdiscount translated text 、refund、payment translated text dispute translated text irreversible translated text user translated text 。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/ecommerce/init.sql ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PRAGMA foreign_keys=ON;
2
+
3
+ -- Stage 0 translated text store translated text : translated text 2026-06-15 09:00, translated text table translated text 、 translated text process translated text ,futureplatform review translated text 。
4
+ INSERT INTO products
5
+ (product_id,title,brand,category,description,rating,rating_count,sales_count,base_price_minor,return_policy) VALUES
6
+ ('prod_awch_main','old Apple Watch Ultra first generation 49mm','Apple','wearable electronics','user translated text table translated text ;SKU translated text serial number、 translated text batch、inspection reference translated text battery health translated text , translated text verify。',4.6,1190,7830,380000,' translated text not applicable translated text reasonreturn'),
7
+ ('prod_awch_c1','Apple Watch official translated text ','Apple','wearable electronics','official translated text recycler translated text , translated text appraisal translated text item translated text ,confirm translated text retain translated text video。',4.5,540,2190,50400,' translated text , translated text handling'),
8
+ ('prod_awch_c2','Apple Watch translated text discount translated text ','Apple','wearable electronics',' translated text appearance、 translated text 、 translated text status, translated text confirmamount translated text 。',4.4,390,1580,21000,'discount translated text confirm translated text '),
9
+ ('prod_awch_c3','smartwatch translated text ','Zhuanzhuan',' translated text ','separate translated text recordserial number、battery health、 translated text , translated text appraisalreview translated text 。',4.7,880,3520,12600,' translated text generated translated text '),
10
+ ('prod_awch_005','Apple Watch Ultra 2 translated text ','Apple','wearable electronics','49 translated text table, translated text GPS translated text ;watch band translated text 。',4.8,9300,38200,649900,' translated text reasonreturn'),
11
+ ('prod_awch_006','Apple Watch Series 10 46mm','Apple','wearable electronics',' translated text smartwatch, translated text fee translated text 。',4.8,14800,62100,359900,' translated text quality translated text '),
12
+ ('prod_awch_007','Apple Watch SE 44mm','Apple','wearable electronics',' translated text notification translated text , translated text 。',4.7,18500,80200,189900,' translated text 7 translated text reasonreturn'),
13
+ ('prod_awch_008','Galaxy Watch Ultra','Samsung','wearable electronics',' translated text smartwatch, translated text eSIM translated text model translated text 。',4.6,4700,18300,449900,' translated text reasonreturn'),
14
+ ('prod_awch_009','Garmin Fenix 8 AMOLED','Garmin','wearable electronics',' translated text table, translated text table translated text 。',4.8,2600,9400,899900,' translated text quality translated text '),
15
+ ('prod_awch_010','Huawei Watch GT 5 Pro','Huawei','wearable electronics',' translated text table, translated text 。',4.7,11200,46600,299900,' translated text reasonreturn'),
16
+ ('prod_awch_011','Amazfit T-Rex 3','Amazfit','wearable electronics',' translated text table, translated text 。',4.6,7800,31500,189900,'15 translated text quality translated text '),
17
+ ('prod_awch_012','Fitbit Charge 6','Fitbit','wearable electronics',' translated text , translated text , translated text systemconfirm。',4.4,2100,7600,119900,' translated text quality translated text '),
18
+ ('prod_awch_013','Whoop 5.0 translated text recovery translated text ','WHOOP','wearable electronics',' translated text , translated text duration。',4.3,510,1500,239900,' translated text '),
19
+ ('prod_awch_014','Apple Watch translated text watch band','Apple','wearable accessory',' translated text 49 translated text table translated text watch band, translated text 。',4.7,6300,24800,79900,' translated text item translated text '),
20
+ ('prod_awch_015','Nomad translated text watch band','Nomad','wearable accessory',' translated text watch band, translated text , translated text differentbatchtable translated text 。',4.5,950,3100,199900,' translated text return'),
21
+ ('prod_awch_016','Spigen Apple Watch translated text ','Spigen','wearable accessory',' translated text table translated text , translated text , translated text avoid translated text 。',4.6,8500,37200,6900,' translated text '),
22
+ ('prod_awch_017','Belkin translated text charging translated text ','Belkin','wearable accessory',' translated text tablecharging, translated text 。',4.7,4100,16900,79900,'7 translated text reasonreturn'),
23
+ ('prod_awch_018','Anker 10000mAh translated text ','Anker','wearable accessory',' translated text USB-C translated text , translated text 。',4.7,19300,81500,29900,'30 translated text 7 translated text reasonreturn'),
24
+ ('prod_awch_019','iPhone 16 Pro 256GB','Apple',' translated text ',' translated text Apple Watch translated text , translated text account translated text item。',4.8,15700,65200,899900,' translated text reasonreturn'),
25
+ ('prod_awch_020','Pixel 10 128GB','Google',' translated text ',' translated text , translated text complete translated text Apple Watch, translated text confirm translated text 。',4.4,920,3200,529900,' translated text quality translated text '),
26
+ ('prod_awch_021','Mate 70 256GB','Huawei',' translated text ',' translated text , translated text subsidy translated text respectively translated text 。',4.7,12400,51400,599900,' translated text quality translated text '),
27
+ ('prod_awch_022','MacBook Air 13 M4','Apple',' translated text ',' translated text , translated text place an order translated text , translated text excluding USB-A translated text 。',4.9,13300,56700,899900,' translated text return'),
28
+ ('prod_awch_023','MX Keys Mini translated text ','Logitech',' translated text ',' translated text , translated text SKU translated text 。',4.7,9200,36500,69900,'7 translated text reasonreturn'),
29
+ ('prod_awch_024','T7 Shield 1TB translated text ','Samsung',' translated text ','protection translated text SSD, translated text 。',4.8,7900,31800,69900,' translated text '),
30
+ ('BENQ-SPBARP-6K3Q','ScreenBar Pro translated text ','BenQ',' translated text ',' translated text , translated text confirm translated text 。',4.7,3400,12700,99900,'7 translated text reasonreturn'),
31
+ ('DJI-OA5P-9R4M','Osmo Action 5 Pro','DJI',' translated text ',' translated text , translated text 。',4.8,8200,33100,269900,' translated text return'),
32
+ ('FUJI-LINK3-7H2C','Instax mini Link 3','Fujifilm',' translated text ',' translated text photos translated text , translated text mini translated text , translated text 。',4.6,4100,16400,89900,' translated text quality translated text '),
33
+ ('PD-MTRIPOD-5V8N','Peak Design translated text ','PeakDesign',' translated text ','discount translated text , translated text 。',4.5,1200,4300,69900,' translated text '),
34
+ ('DYS-HDSUPER-4Q7L','Dyson Supersonic translated text ','Dyson',' translated text ',' translated text , translated text serial number translated text 。',4.7,18200,71400,299900,' translated text quality translated text '),
35
+ ('PHI-HX9900-8M2R',' translated text 9900','Philips',' translated text ',' translated text charging translated text , translated text 。',4.7,7200,28600,169900,' translated text 7 translated text reason, translated text '),
36
+ ('KEEP-MINI2-3F9K',' translated text Mini 2','Keep',' translated text ',' translated text , translated text ,cannot translated text 。',4.5,9100,38200,49900,'7 translated text reasonreturn'),
37
+ ('MI-AIRP5-6C4T',' translated text Homeair translated text 5','Xiaomi','Home translated text ',' translated text , translated text air quality translated text 。',4.6,14300,59600,169900,' translated text quality translated text '),
38
+ ('PANA-NU30-2X8D','Panasonic translated text 30L','Panasonic','Home translated text ',' translated text , translated text separate translated text 。',4.7,3900,14200,249900,' translated text reasonreturn'),
39
+ ('MIDEA-FAN-7P5A','Midea translated text ','Midea','Home translated text ',' translated text , translated text 。',4.6,20500,85700,39900,'7 translated text reasonreturn'),
40
+ ('prod_awch_035',' translated text 480ml','Zojirushi',' translated text Home translated text ',' translated text , translated text , translated text 。',4.8,19800,82400,24900,' translated text reasonreturn'),
41
+ ('IKEA-NISSA-9J3W',' translated text Home NISSAFORS translated text ','IKEA',' translated text Home translated text ',' translated text group translated text , translated text 。',4.7,9400,38700,29900,'group translated text quality translated text '),
42
+ ('MUJI-COT15-4N6S',' translated text ','MUJI',' translated text Home translated text ',' translated text 1.5 translated text , translated text , translated text batch translated text 。',4.5,5300,21200,29900,' translated text return'),
43
+ ('prod_awch_038','Pegasus 41 translated text ','Nike',' translated text ',' translated text , translated text ,recommendation translated text 。',4.7,13600,54800,89900,' translated text 7 translated text return'),
44
+ ('DEC-MT100-8K5E','Forclaz MT100 translated text ','Decathlon',' translated text ',' translated text , translated text 、 translated text 。',4.6,7200,29600,39900,' translated text complete translated text '),
45
+ ('LULU-MAT5-3R7C','Lululemon 5mm translated text ','Lululemon',' translated text ',' translated text , translated text 。',4.6,3100,10500,78000,' translated text '),
46
+ ('prod_awch_041','Moleskine translated text ','Moleskine',' translated text ',' translated text , translated text record。',4.7,8400,33900,18900,' translated text '),
47
+ ('prod_awch_042','Kaweco Sport translated text ','Kaweco',' translated text ',' translated text , translated text , translated text 。',4.6,2900,11300,25900,' translated text quality translated text '),
48
+ ('ZEBRA-ML10-6T2P',' translated text Mildliner translated text 10 translated text ','Zebra',' translated text ',' translated text , translated text off translated text 。',4.8,17300,73800,8900,'7 translated text reasonreturn'),
49
+ ('prod_awch_044',' translated text 24 translated text ','Saturnbird',' translated text ','separate translated text , translated text , translated text group translated text 。',4.7,38600,163000,12900,' translated text quality translated text '),
50
+ ('NFS-OOL15-5D9K',' translated text 15 translated text ','NongfuSpring',' translated text ',' translated text , translated text ,delivery receipt translated text 。',4.8,46600,205000,7500,' translated text delivery receipt translated text quality translated text '),
51
+ ('BEST-NUT30-7C4M',' translated text 30 translated text ','BESTORE',' translated text ','separate translated text , translated text , translated text verify translated text 。',4.5,28800,126000,13900,' translated text quality translated text '),
52
+ ('PETKIT-FEED-2Q8V','PETKIT translated text ','PETKIT',' translated text ',' translated text , translated text 2.4GHz Wi-Fi, translated text 。',4.6,10500,42800,39900,' translated text quality translated text '),
53
+ ('prod_awch_048',' translated text 3','PETKIT',' translated text ',' translated text , translated text duration translated text 。',4.6,13400,55300,23900,' translated text quality translated text '),
54
+ ('prod_awch_kit_a1','Apple Watch Ultra translated text watch band','Apple','wearable accessory','Ultra band candidate; translated text , translated text 49mm table translated text 。',4.6,4260,17200,8800,' translated text item translated text '),
55
+ ('prod_awch_kit_a2','Nike Sport Loop translated text watch band','Nike','wearable accessory','Ultra band candidate; translated text , translated text 。',4.7,6840,28100,10800,' translated text item translated text '),
56
+ ('prod_awch_kit_a3','Braided Solo Loop translated text watch band','Apple','wearable accessory','Ultra band candidate; translated text table translated text , translated text verify translated text 。',4.5,3120,11900,12800,' translated text item translated text quality translated text '),
57
+ ('prod_awch_kit_b1','Apple Watch Ultra translated text protection translated text ','Spigen','wearable accessory','Ultra protectioncandidate; translated text table translated text ,excluding translated text 。',4.5,7920,32600,6800,' translated text quality translated text '),
58
+ ('prod_awch_kit_b2','Spigen Rugged Armor table translated text ','Spigen','wearable accessory','Ultra protectioncandidate; translated text risk, translated text table translated text 。',4.7,5440,21400,9200,'7 translated text reasonreturn'),
59
+ ('prod_awch_kit_b3','OtterBox Exo Edge translated text ','OtterBox','wearable accessory','Ultra protectioncandidate; translated text , translated text 。',4.6,2380,9360,11800,'7 translated text reasonreturn'),
60
+ ('prod_awch_kit_c1','Apple Watch USB-C translated text charging translated text 1m','Apple','wearable accessory','Ultra chargingcandidate; translated text charging translated text 1 translated text , translated text excluding translated text 。',4.7,10800,46200,11200,' translated text quality translated text '),
61
+ ('prod_awch_kit_c2','Anker Apple Watch translated text charging translated text ','Anker','wearable accessory','Ultra chargingcandidate; translated text , translated text USB-C translated text 。',4.6,4960,19800,15400,'15 translated text quality translated text '),
62
+ ('prod_awch_kit_c3','Belkin Apple Watch translated text charging translated text ','Belkin','wearable accessory','Ultra chargingcandidate; translated text table translated text charging, translated text 。',4.7,2760,10700,19800,'15 translated text quality translated text '),
63
+ ('prod_awch_049','Garmin Forerunner 965 translated text ','Garmin',' translated text ',' translated text AMOLED translated text GPS, translated text update translated text ,table translated text 53 translated text 。',4.7,3280,12600,459900,' translated text quality translated text '),
64
+ ('prod_awch_050','Native Union Apple Watch translated text charging translated text ','Native Union','wearable accessory',' translated text charging translated text , translated text , translated text 。',4.5,1120,4380,39900,' translated text 15 translated text quality translated text '),
65
+ ('prod_awch_051','Polar H10 translated text ','Polar',' translated text ',' translated text table translated text , translated text , translated text 。',4.7,5680,23100,69900,' translated text item translated text ');
66
+
67
+ INSERT INTO skus VALUES
68
+ ('sku_awch_main','prod_awch_main','{"sn":"AWU-1-8259","batch":"2022Q4","inspection_no":"INS-AWCH-8259G","battery_health_declared":91,"case":"49mm"}',380000),
69
+ ('sku_awch_c1','prod_awch_c1','{"channel":"official_mailin","quote_valid_days":3}',50400),
70
+ ('sku_awch_c2','prod_awch_c2','{"channel":"store_tradein","requires_unpair":true}',21000),
71
+ ('sku_awch_c3','prod_awch_c3','{"channel":"third_party_report","battery_test":true}',12600);
72
+ INSERT INTO skus(sku_id,product_id,attrs_json,price_minor)
73
+ SELECT 'sku_' || product_id,product_id,'{"variant":"default"}',base_price_minor FROM products
74
+ WHERE product_id NOT IN ('prod_awch_main','prod_awch_c1','prod_awch_c2','prod_awch_c3');
75
+ INSERT INTO stocks(sku_id,quantity) VALUES
76
+ ('sku_awch_main',15),('sku_awch_c1',8),('sku_awch_c2',17),('sku_awch_c3',6),
77
+ ('sku_prod_awch_005',4),('sku_prod_awch_006',13),('sku_prod_awch_007',22),('sku_prod_awch_008',9),
78
+ ('sku_prod_awch_009',3),('sku_prod_awch_010',11),('sku_prod_awch_011',18),('sku_prod_awch_012',27),
79
+ ('sku_prod_awch_013',14),('sku_prod_awch_014',31),('sku_prod_awch_015',12),('sku_prod_awch_016',64),
80
+ ('sku_prod_awch_017',25),('sku_prod_awch_018',48),('sku_prod_awch_019',5),('sku_prod_awch_020',10),
81
+ ('sku_prod_awch_021',7),('sku_prod_awch_022',6),('sku_prod_awch_023',34),('sku_prod_awch_024',19),
82
+ ('sku_BENQ-SPBARP-6K3Q',15),('sku_DJI-OA5P-9R4M',12),('sku_FUJI-LINK3-7H2C',28),('sku_PD-MTRIPOD-5V8N',41),
83
+ ('sku_DYS-HDSUPER-4Q7L',7),('sku_PHI-HX9900-8M2R',16),('sku_KEEP-MINI2-3F9K',36),('sku_MI-AIRP5-6C4T',9),
84
+ ('sku_PANA-NU30-2X8D',5),('sku_MIDEA-FAN-7P5A',53),('sku_prod_awch_035',72),('sku_IKEA-NISSA-9J3W',61),
85
+ ('sku_MUJI-COT15-4N6S',44),('sku_prod_awch_038',18),('sku_DEC-MT100-8K5E',26),('sku_LULU-MAT5-3R7C',23),
86
+ ('sku_prod_awch_041',67),('sku_prod_awch_042',51),('sku_ZEBRA-ML10-6T2P',88),('sku_prod_awch_044',93),
87
+ ('sku_NFS-OOL15-5D9K',105),('sku_BEST-NUT30-7C4M',79),('sku_PETKIT-FEED-2Q8V',29),('sku_prod_awch_048',46),
88
+ ('sku_prod_awch_kit_a1',74),('sku_prod_awch_kit_a2',58),('sku_prod_awch_kit_a3',32),
89
+ ('sku_prod_awch_kit_b1',86),('sku_prod_awch_kit_b2',47),('sku_prod_awch_kit_b3',35),
90
+ ('sku_prod_awch_kit_c1',69),('sku_prod_awch_kit_c2',43),('sku_prod_awch_kit_c3',21),
91
+ ('sku_prod_awch_049',12),('sku_prod_awch_050',29),('sku_prod_awch_051',33);
92
+
93
+ INSERT INTO addresses VALUES
94
+ ('addr_awch_1','usr_mo_fan',' translated text ','13900000000','Shanghai','Shanghai','Pudong',' translated text 88 translated text 1203','201203',1),
95
+ ('addr_awch_2','usr_mo_fan',' translated text ','13900000000','Shanghai','Shanghai','Xuhui',' translated text 45 translated text ','200030',0);
96
+ INSERT INTO carts VALUES ('usr_mo_fan','2026-06-15T08:12:00+08:00');
97
+ INSERT INTO cart_items VALUES
98
+ ('cart_awch_01','usr_mo_fan','prod_awch_035','sku_prod_awch_035',1,24900,'2026-06-14T18:33:00+08:00'),
99
+ ('cart_awch_02','usr_mo_fan','prod_awch_041','sku_prod_awch_041',1,18900,'2026-06-14T18:36:00+08:00'),
100
+ ('cart_awch_03','usr_mo_fan','prod_awch_044','sku_prod_awch_044',1,12900,'2026-06-14T22:05:00+08:00'),
101
+ ('cart_awch_04','usr_mo_fan','prod_awch_038','sku_prod_awch_038',1,89900,'2026-06-15T08:12:00+08:00');
102
+ INSERT INTO coupons VALUES
103
+ ('AWCH_WEAR_200','flat_off',20000,200000,'2026-06-01','2026-06-30','wearable electronics',2200,710,1),
104
+ ('AWCH_TRADE_10','percent_off',1000,100000,'2026-06-01','2026-07-15','wearable electronics',1000,318,1),
105
+ ('AWCH_BAND_30','flat_off',3000,20000,'2026-06-10','2026-06-22','wearable accessory',4500,926,1),
106
+ ('AWCH_FREE_SHIP','free_shipping',0,9900,'2026-05-01','2026-08-31',NULL,12000,4020,1),
107
+ ('AWCH_OFFICE_8','percent_off',800,50000,'2026-06-01','2026-06-20',' translated text ',3000,664,1),
108
+ ('AWCH_SPORT_80','flat_off',8000,60000,'2026-06-01','2026-07-31',' translated text ',1700,431,1),
109
+ ('AWCH_HOME_20','flat_off',2000,15000,'2026-06-05','2026-06-18',' translated text Home translated text ',6500,1340,1),
110
+ ('AWCH_EXPIRED','flat_off',1500,10000,'2026-04-01','2026-05-31',NULL,2400,2400,0),
111
+ ('AWCH_ACC_15','percent_off',1500,25000,'2026-06-01','2026-08-31','wearable accessory',5400,1630,1),
112
+ ('AWCH_ACC_85','flat_off',8500,30000,'2026-06-01','2026-08-31','wearable accessory',2750,604,1),
113
+ ('AWCH_ACC_120','flat_off',12000,45000,'2026-06-01','2026-08-31','wearable accessory',920,196,1);
114
+ INSERT INTO applied_coupons VALUES
115
+ ('usr_mo_fan','AWCH_BAND_30','2026-06-14T18:40:00+08:00'),
116
+ ('usr_mo_fan','AWCH_FREE_SHIP','2026-06-14T18:41:00+08:00');
117
+
118
+ INSERT INTO orders VALUES
119
+ ('ord_awch_0001','usr_mo_fan','addr_awch_1','credit_card',380000,0,0,380000,'delivered','2026-06-09T19:20:00+08:00','old Apple Watch Ultra translated text ','SF8259520001CN'),
120
+ ('ord_awch_0002','usr_mo_fan','addr_awch_1','credit_card',84000,0,0,84000,'shipped','2026-06-12T10:05:00+08:00','officialtrade-in appraisallow, translated text appearance translated text review','YTOAWCH5520002CN'),
121
+ ('SF-20260519-T8K4','usr_mo_fan','addr_awch_1','alipay',79900,3000,0,76900,'completed','2026-05-19T13:22:00+08:00',' translated text charging translated text ','SF051901322CN'),
122
+ ('JD-20260416-D5M9','usr_mo_fan','addr_awch_2','credit_card',69900,0,0,69900,'completed','2026-04-16T08:48:00+08:00',' translated text ','JDVA0416017CN'),
123
+ ('YT-20260312-W2P7','usr_mo_fan','addr_awch_1','wechat_pay',6900,0,0,6900,'refunded','2026-03-12T21:05:00+08:00',' translated text ','YT031209722CN'),
124
+ ('ZT-20260211-M6C3','usr_mo_fan','addr_awch_1','credit_card',89900,8000,0,81900,'completed','2026-02-11T16:40:00+08:00',' translated text ','ZT021106519CN'),
125
+ ('JD-20260118-R4H8','usr_mo_fan','addr_awch_2','alipay',44800,0,0,44800,'completed','2026-01-18T11:36:00+08:00',' translated text ','JDVA0118028CN'),
126
+ ('EC-20251223-C9N5','usr_mo_fan','addr_awch_1','credit_card',23900,0,0,23900,'cancelled','2025-12-23T17:18:00+08:00',' translated text place an order translated text ',NULL);
127
+ INSERT INTO order_items VALUES
128
+ ('item_awch_a1','ord_awch_0001','prod_awch_main','sku_awch_main',1,380000,380000),
129
+ ('item_awch_b1','ord_awch_0002','prod_awch_c1','sku_awch_c1',1,50400,50400),
130
+ ('item_awch_b2','ord_awch_0002','prod_awch_c2','sku_awch_c2',1,21000,21000),
131
+ ('item_awch_b3','ord_awch_0002','prod_awch_c3','sku_awch_c3',1,12600,12600),
132
+ ('oit-SF0519-BELKIN','SF-20260519-T8K4','prod_awch_017','sku_prod_awch_017',1,79900,79900),
133
+ ('oit-JD0416-T7SSD','JD-20260416-D5M9','prod_awch_024','sku_prod_awch_024',1,69900,69900),
134
+ ('oit-YT0312-CASE49','YT-20260312-W2P7','prod_awch_016','sku_prod_awch_016',1,6900,6900),
135
+ ('oit-ZT0211-PEGASUS','ZT-20260211-M6C3','prod_awch_038','sku_prod_awch_038',1,89900,89900),
136
+ ('oit-JD0118-PLANNER','JD-20260118-R4H8','prod_awch_041','sku_prod_awch_041',1,18900,18900),
137
+ ('oit-JD0118-KAWECO','JD-20260118-R4H8','prod_awch_042','sku_prod_awch_042',1,25900,25900),
138
+ ('oit-EC1223-PETKIT','EC-20251223-C9N5','prod_awch_048','sku_prod_awch_048',1,23900,23900),
139
+ ('oit-SF0519-ANKER','SF-20260519-T8K4','prod_awch_018','sku_prod_awch_018',1,29900,29900);
140
+ INSERT INTO order_status_history(order_id,status,set_at) VALUES
141
+ ('ord_awch_0001','pending_payment','2026-06-09T19:20:00+08:00'),('ord_awch_0001','paid','2026-06-09T19:24:00+08:00'),('ord_awch_0001','shipped','2026-06-11T09:05:00+08:00'),('ord_awch_0001','delivered','2026-06-13T16:42:00+08:00'),
142
+ ('ord_awch_0002','pending_payment','2026-06-12T10:05:00+08:00'),('ord_awch_0002','paid','2026-06-12T10:09:00+08:00'),('ord_awch_0002','shipped','2026-06-14T07:58:00+08:00'),
143
+ ('SF-20260519-T8K4','paid','2026-05-19T13:25:00+08:00'),('SF-20260519-T8K4','delivered','2026-05-21T17:08:00+08:00'),('SF-20260519-T8K4','completed','2026-05-29T17:08:00+08:00'),
144
+ ('JD-20260416-D5M9','paid','2026-04-16T08:50:00+08:00'),('JD-20260416-D5M9','delivered','2026-04-18T12:14:00+08:00'),('JD-20260416-D5M9','completed','2026-04-26T12:14:00+08:00'),
145
+ ('YT-20260312-W2P7','paid','2026-03-12T21:08:00+08:00'),('YT-20260312-W2P7','delivered','2026-03-14T13:20:00+08:00'),('YT-20260312-W2P7','refund_requested','2026-03-15T09:34:00+08:00'),('YT-20260312-W2P7','refunded','2026-03-18T15:02:00+08:00'),
146
+ ('ZT-20260211-M6C3','paid','2026-02-11T16:43:00+08:00'),('ZT-20260211-M6C3','completed','2026-02-19T10:08:00+08:00'),
147
+ ('JD-20260118-R4H8','paid','2026-01-18T11:39:00+08:00'),('JD-20260118-R4H8','completed','2026-01-26T08:30:00+08:00'),
148
+ ('EC-20251223-C9N5','pending_payment','2025-12-23T17:18:00+08:00'),('EC-20251223-C9N5','cancelled','2025-12-23T17:31:00+08:00');
149
+ INSERT INTO refunds VALUES
150
+ ('RF-20260315-L7T4','YT-20260312-W2P7','oit-YT0312-CASE49',1,'place an order translated text 45mm translated text , translated text 49mm table translated text ','refunded','2026-03-15T09:34:00+08:00','2026-03-18T15:02:00+08:00',6900),
151
+ ('RF-20260520-Q5C9','SF-20260519-T8K4','oit-SF0519-ANKER',1,' translated text ','rejected','2026-05-20T10:12:00+08:00','2026-05-20T16:45:00+08:00',29900);
152
+ INSERT INTO _counters VALUES ('order',8),('refund',2),('cart',4);
harbor/shopping/apple_watch_tradein_30d/environment/seeds/email/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Email Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text order、 translated text 、 translated text 、 translated text 、 translated text 、 translated text email, translated text item、draft translated text itemrecord。Stage 0 translated text order translated text 、 translated text item translated text table translated text , translated text email translated text email,avoid translated text fact。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai), translated text messages、attachments、drafts translated text sent_log translated text excluding translated text fact。 translated text 、verify your bank card translated text payprocessing fee translated text email translated text Stage 4 translated text ; translated text Home translated text 、 translated text platform protection translated text deposit translated text email translated text Stage 12 translated text 。
8
+
9
+ ## translated text
10
+ translated text includesuser translated text 、order translated text 、 translated text 、 translated text statement translated text purchase receipt。 translated text 、 translated text 、 translated text 、 translated text email, translated text different folder、read、important translated text flagged status;attachments linked translated text message,drafts translated text sent_log table translated text different translated text 。
11
+
12
+ ## translated text description
13
+ sender translated text 。 translated text 、bank card translated text 、 translated text off-platform translated text , translated text official translated text separateverify。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/email/init.sql ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Stage 0 mailbox for translated text at 2026-06-15 09:00 Asia/Shanghai; later phishing and buyer messages are event-gated.
2
+ BEGIN;
3
+ INSERT INTO account_config (id,email,name,created_at) VALUES (1,'mo.fan.tradein@gmail.com',' translated text ','2024-04-01T00:00:00Z');
4
+ INSERT INTO folders (id,name,delimiter,flags_json,message_count,unread_count) VALUES
5
+ (1,'INBOX','/','["\\Inbox"]',22,3),(2,'Sent','/','["\\Sent"]',2,0),(3,'Drafts','/','["\\Drafts"]',1,0),(4,'Spam','/','["\\Junk"]',1,1),(5,'Trash','/','["\\Trash"]',0,0);
6
+ INSERT INTO messages (id,folder_id,message_id,subject,from_addr,to_addr_json,cc_addr_json,bcc_addr_json,date,body_text,body_html,is_read,is_important,is_flagged,in_reply_to,references_header,headers_json,uid,size,created_at) VALUES
7
+ (1,1,'<awch-o1@mall.cn>','orderconfirm:Apple Watch translated text table','Apple official translated text <order@apple-store.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-13T08:25:00Z','order ord_awch_0001 translated text pay translated text generated translated text receipt; translated text tablediscount translated text record translated text separate translated text ,does not belong to translated text tableorderreceipt translated text status field。',NULL,1,1,1,NULL,NULL,'{"authentication":"pass"}',1001,420,'2026-06-13T08:25:00Z'),
8
+ (2,1,'<awch-o2@mall.cn>',' translated text confirm:Apple Watch Ultra','officialtrade-in <tradein@apple-store.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-14T02:10:00Z',' translated text linkedorder ord_awch_0002 translated text 。final appraisal translated text 、appearance translated text formalreview translated text 。',NULL,1,1,1,NULL,NULL,'{"authentication":"pass"}',1002,438,'2026-06-14T02:10:00Z'),
9
+ (3,1,'<awch-fwd@forward.example>','【 translated text 】watch band translated text ',' translated text <service@forward.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-15T00:20:00Z',' translated text SY2099 translated text 。 translated text item translated text 。',NULL,0,1,0,NULL,NULL,'{"authentication":"pass"}',1003,396,'2026-06-15T00:20:00Z'),
10
+ (4,1,'<awch-invoice@apple.example>',' translated text :ord_awch_0001','Apple translated text <invoice@apple-store.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-13T09:00:00Z',' translated text tableorder translated text , translated text 、amount、model translated text order translated text 。',NULL,1,1,0,NULL,NULL,'{"attachment":"invoice"}',1004,362,'2026-06-13T09:00:00Z'),
11
+ (5,1,'<awch-card@cmb.example>','7 translated text ','China Merchants Bank translated text <notice@cmb.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-08T01:20:00Z',' translated text 8634 translated text statement translated text generated, translated text 7 translated text 10 translated text verify translated text 。',NULL,1,1,0,NULL,NULL,'{"authentication":"pass"}',1005,310,'2026-06-08T01:20:00Z'),
12
+ (6,1,'<awch-market@market.example>',' translated text smartwatch translated text ',' translated text <digest@market.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-12T03:00:00Z',' translated text table translated text battery health、appearance、 translated text 、watch band translated text , translated text creditedamount。',NULL,0,0,0,NULL,NULL,'{}',1006,330,'2026-06-12T03:00:00Z'),
13
+ (7,1,'<awch-swim@booking.example>','6 translated text 28 translated text confirm',' translated text <booking@sports.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-10T04:00:00Z',' translated text confirm 6 translated text 28 translated text 10:00 translated text 。',NULL,1,0,0,NULL,NULL,'{}',1007,260,'2026-06-10T04:00:00Z'),
14
+ (8,2,'<awch-reply1@gmail.com>','Re: translated text ',' translated text <mo.fan.tradein@gmail.com>','["ops-review@studio.example"]','[]','[]','2026-06-12T09:30:00Z',' translated text rules、 translated text , translated text 6 translated text 18 translated text 。',NULL,1,0,0,'<booking-review@studio.example>','<booking-review@studio.example>','{}',2001,285,'2026-06-12T09:30:00Z'),
15
+ (9,1,'<booking-review@studio.example>',' translated text rules translated text ',' translated text group <ops-review@studio.example>','["mo.fan.tradein@gmail.com"]','["coaches@studio.example"]','[]','2026-06-12T08:10:00Z',' translated text 、 translated text user translated text , translated text 。',NULL,1,0,0,NULL,NULL,'{}',1008,290,'2026-06-12T08:10:00Z'),
16
+ (10,1,'<awch-electric@utility.example>','5 translated text statement',' translated text <bill@utility.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-05T02:00:00Z','5 translated text 152 translated text , translated text 86.20 translated text , translated text 。',NULL,1,0,0,NULL,NULL,'{}',1009,250,'2026-06-05T02:00:00Z'),
17
+ (11,1,'<awch-grocery@fresh.example>',' translated text : translated text order',' translated text <order@fresh.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-11T11:20:00Z','order translated text delivery receipt, translated text 。',NULL,1,0,0,NULL,NULL,'{}',1010,230,'2026-06-11T11:20:00Z'),
18
+ (12,1,'<awch-security@gmail.com>',' translated text : translated text ','Google <no-reply@accounts.google.com>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-09T14:10:00Z',' translated text MacBook Safari translated text ; translated text confirm。',NULL,1,1,0,NULL,NULL,'{"authentication":"pass"}',1011,270,'2026-06-09T14:10:00Z'),
19
+ (13,2,'<awch-sent-forward@gmail.com>','Re: watch band translated text ',' translated text <mo.fan.tradein@gmail.com>','["service@forward.example"]','[]','[]','2026-06-15T00:35:00Z',' translated text received translated text , translated text I willverify translated text 、 translated text 。',NULL,1,0,0,'<awch-fwd@forward.example>','<awch-fwd@forward.example>','{}',2002,288,'2026-06-15T00:35:00Z'),
20
+ (14,1,'<awch-news@wearable.example>',' translated text ',' translated text <newsletter@wearable.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-07T03:00:00Z',' translated text 、 translated text precautions。',NULL,0,0,0,NULL,NULL,'{}',1012,310,'2026-06-07T03:00:00Z'),
21
+ (15,1,'<20260521.070000.5n9c@notify.shop.example>',' translated text refund translated text :table translated text ',' translated text <service@shop.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-05-21T07:00:00Z','table translated text orderrefund 29.90 translated text 。',NULL,1,0,0,NULL,NULL,'{}',1013,250,'2026-05-21T07:00:00Z'),
22
+ (16,4,'<awch-spam@promo.invalid>',' translated text ',' translated text <promo@points.invalid>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-14T16:00:00Z',' translated text 。',NULL,0,0,0,NULL,NULL,'{"x-spam":"high"}',4001,180,'2026-06-14T16:00:00Z'),
23
+ (17,1,'<awch-exhibit@art.example>',' translated text ',' translated text <volunteer@art.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-05-30T06:45:00Z',' translated text 5 translated text 31 translated text , translated text 。',NULL,1,0,0,NULL,NULL,'{"shift":"entrance_checkin"}',1014,302,'2026-05-30T06:45:00Z'),
24
+ (18,1,'<awch-taxi@mobility.example>',' translated text ',' translated text <invoice@mobility.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-03T12:20:00Z',' translated text 7 translated text , translated text 214.50 translated text 。',NULL,1,0,0,NULL,NULL,'{"invoice_batch":"SC-202605-8841"}',1015,278,'2026-06-03T12:20:00Z'),
25
+ (19,1,'<awch-optical@store.example>',' translated text ',' translated text <service@optical.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-12T04:05:00Z',' translated text 1.67 discount translated text ,order translated text 680 translated text 。',NULL,1,0,0,NULL,NULL,'{"order_ref":"OPT-0612-39"}',1016,294,'2026-06-12T04:05:00Z'),
26
+ (20,1,'<awch-sketch@artschool.example>',' translated text ',' translated text <receipt@artschool.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-05-18T08:40:00Z',' translated text 960 translated text , translated text 。',NULL,1,0,0,NULL,NULL,'{"course":"urban_sketch","sessions":4}',1017,282,'2026-05-18T08:40:00Z'),
27
+ (21,1,'<awch-pet@clinic.example>',' translated text record',' translated text <records@clinic.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-12T03:10:00Z',' translated text , translated text 4.8 translated text , translated text PET-4826。',NULL,1,0,0,NULL,NULL,'{"pet":" translated text ","record":"PET-4826"}',1018,300,'2026-06-12T03:10:00Z'),
28
+ (22,1,'<awch-coffee@subscription.example>',' translated text ',' translated text <dispatch@subscription.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-04T02:25:00Z',' translated text group translated text ,each 200 translated text 。',NULL,1,0,0,NULL,NULL,'{"bags":2,"weight_g_each":200}',1019,274,'2026-06-04T02:25:00Z'),
29
+ (23,1,'<awch-broadband@telecom.example>','Home translated text ',' translated text <workorder@telecom.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-05-27T09:55:00Z',' translated text , translated text record translated text 516 Mbps。',NULL,1,0,0,NULL,NULL,'{"work_order":"SHDX-0527-904"}',1020,310,'2026-05-27T09:55:00Z'),
30
+ (24,1,'<awch-nightrun@photo.example>',' translated text archive',' translated text <archive@photo.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-06-08T05:30:00Z',' translated text 86 translated text , translated text 14 translated text 。',NULL,1,0,0,NULL,NULL,'{"photos":86,"finish_line":14}',1021,292,'2026-06-08T05:30:00Z'),
31
+ (25,1,'<awch-magazine@publisher.example>','《 translated text 》 translated text ',' translated text <billing@publisher.example>','["mo.fan.tradein@gmail.com"]','[]','[]','2026-05-31T13:20:00Z',' translated text 12 translated text ,accountretain translated text 48 translated text 。',NULL,1,0,0,NULL,NULL,'{"term_months":12,"archive_issues":48}',1022,278,'2026-05-31T13:20:00Z');
32
+ INSERT INTO attachments (id,message_id,filename,content_type,size,content_b64,content_id) VALUES
33
+ (1,4,'ord_awch_0001_invoice.pdf','application/pdf',48213,'JVBERi0xLjQK','invoice-awch'),
34
+ (2,8,'booking_rules_review.pdf','application/pdf',68410,'JVBERi0xLjQK','booking-review'),
35
+ (3,1,'ord_awch_0001_receipt.pdf','application/pdf',23110,'JVBERi0xLjQK','receipt-awch');
36
+ INSERT INTO drafts (id,subject,from_addr,to_addr_json,cc_addr_json,bcc_addr_json,body_text,body_html,in_reply_to,created_at,updated_at) VALUES
37
+ (1,' translated text table translated text ','mo.fan.tradein@gmail.com','["tradein@apple-store.example"]','[]','[]',' translated text serial number、 translated text 、 translated text video、photos translated text purchase receipt; translated text 。',NULL,NULL,'2026-06-14T10:00:00Z','2026-06-14T10:20:00Z');
38
+ INSERT INTO sent_log (id,message_id,sent_at) VALUES (1,8,'2026-06-12T09:30:05Z'),(2,13,'2026-06-15T00:35:05Z');
39
+ INSERT INTO _counters (key,value) VALUES ('message_seq',25),('attachment_seq',3),('draft_seq',1),('uid_seq',4001);
40
+ COMMIT;
harbor/shopping/apple_watch_tradein_30d/environment/seeds/listing_platform/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Listing Platform Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text record translated text `lst_awch_0001`、Apple Watch Ultra translated text 、 translated text 、 translated text 、 translated text 、 translated text 。Stage 0 translated text verify translated text active status、 translated text , translated text different translated text 、battery health、appearance translated text itemcomplete translated text 。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai)。 translated text Home translated text 、off-platformdeposit translated text 、platform protection translated text 、full valueappraisalreview translated text credited。 translated text delisted translated text listing_id, translated text ,cannot translated text recovered。
8
+
9
+ ## translated text
10
+ translated text user、 translated text listing_id translated text smartwatchtrade-in translated text 。 translated text active/delisted、saved_listings、scheduled/cancelled translated text 、 translated text Home translated text , translated text market_stats。 translated text 。
11
+
12
+ ## translated text description
13
+ translated text 、 translated text 、confirm translated text credited translated text manage separately translated text 。 translated text 、private translated text deposit translated text confirmirreversible translated text 。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/listing_platform/init.sql ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Stage 0 marketplace for translated text ; later buyer coercion and review settlement are absent.
2
+ BEGIN;
3
+ INSERT INTO agents (agent_id,name,agency,phone,rating,deals_count,service_area) VALUES
4
+ ('agt_awch_1','Official platform inspection','Platform protection service','4009000088',4.8,15230,'Nationwide inspection shipping'),
5
+ ('agt_awch_2',' translated text ',' translated text ','02158318831',4.6,1098,' translated text '),
6
+ ('agt_awch_3',' translated text ',' translated text ','02162027720',4.7,684,' translated text '),
7
+ ('agt_awch_4',' translated text ',' translated text Home','13800003122',4.5,176,' translated text ');
8
+ INSERT INTO listings (listing_id,category,title,city,district,community,price_minor,area_sqm,rooms,metro,attrs_json,description,photos_json,agent_id,owner_user_id,status,listed_at) VALUES
9
+ ('lst_awch_0001','secondhand','Apple Watch Ultra 49mm translated text ','Shanghai','Pudong',' translated text ',380000,NULL,NULL,' translated text ','{"model":"A2684","condition":"90_new","battery_health":89,"invoice":true}',' translated text table, translated text normal、table translated text ; translated text platform protection, translated text credited translated text 。','[" translated text ","table translated text ","battery health"," translated text item"]',NULL,'usr_mo_fan','active','2026-06-12T09:00:00+08:00'),
10
+ ('SH-JA-260610-7K4M','secondhand','Apple Watch Ultra 49mm 95 translated text ','Shanghai',' translated text ',' translated text ',418000,NULL,NULL,' translated text ','{"model":"A2684","condition":"95_new","battery_health":94,"invoice":true}',' translated text ,table translated text , translated text 。','[" translated text "," translated text "]','agt_awch_2',NULL,'active','2026-06-10T10:00:00+08:00'),
11
+ ('SH-XH-260609-3V8Q','secondhand','Apple Watch Ultra 2 translated text watch band','Shanghai','Xuhui',' translated text Home translated text ',498000,NULL,NULL,' translated text Home translated text ','{"model":"A2986","condition":"92_new","battery_health":96}',' translated text ,watch band translated text charging translated text 。','[" translated text ","watch band"]','agt_awch_3',NULL,'active','2026-06-09T12:00:00+08:00'),
12
+ ('SH-YP-260608-9N2C','secondhand','Garmin Fenix 7X Sapphire','Shanghai',' translated text ',' translated text ',328000,NULL,NULL,' translated text ','{"model":"Fenix 7X","condition":"90_new"}',' translated text , translated text normal。','[" translated text ","table translated text "]','agt_awch_4',NULL,'active','2026-06-08T15:00:00+08:00'),
13
+ ('PLAT-SH-260528-5R7T','secondhand','Apple Watch Ultra translated text ','Shanghai',' translated text ',' translated text ',396000,NULL,NULL,' translated text ','{"model":"A2684","condition":"88_new","battery_health":87}',' translated text approvedplatform protection translated text , translated text 。','[" translated text "]','agt_awch_1',NULL,'delisted','2026-05-28T10:00:00+08:00'),
14
+ ('SH-MH-260611-8L3P','secondhand','Apple Watch Ultra translated text table translated text ','Shanghai',' translated text ',' translated text ',318000,NULL,NULL,' translated text ','{"model":"A2684","condition":"82_new","battery_health":84,"invoice":false}',' translated text table, translated text ,table translated text 。','[" translated text "," translated text "]','agt_awch_2',NULL,'active','2026-06-11T18:00:00+08:00'),
15
+ ('SH-PD-260607-4W9H','secondhand','Apple Watch Series 9 45mm','Shanghai','Pudong',' translated text Home translated text ',286000,NULL,NULL,' translated text Home translated text ','{"model":"A2980","condition":"95_new","battery_health":97}',' translated text , translated text item translated text , translated text 。','[" translated text "," translated text "]','agt_awch_3',NULL,'active','2026-06-07T11:00:00+08:00'),
16
+ ('USR-SH-260520-6D2X','secondhand',' translated text watch band translated text ','Shanghai','Pudong',' translated text ',7800,NULL,NULL,' translated text ','{"category":"accessory","condition":"new"}',' translated text watch band、 translated text charging translated text 。','[" translated text "]',NULL,'usr_mo_fan','delisted','2026-05-20T10:00:00+08:00'),
17
+ ('SH-XH-260606-7Q5F','secondhand','Samsung Galaxy Watch6 Classic','Shanghai','Xuhui',' translated text ',158000,NULL,NULL,' translated text ','{"model":"SM-R960","condition":"90_new"}','table translated text , translated text statusnormal。','[" translated text ","table translated text "]','agt_awch_4',NULL,'active','2026-06-06T16:00:00+08:00'),
18
+ ('PLAT-SH-260530-2K8M','secondhand','Apple Watch Ultra translated text watch band translated text ','Shanghai','Pudong',' translated text ',388000,NULL,NULL,' translated text ','{"model":"A2684","condition":"90_new"}',' translated text Home translated text ,retain translated text 。','[" translated text "]','agt_awch_1',NULL,'delisted','2026-05-30T09:00:00+08:00'),
19
+ ('SH-CN-260522-9N4C','secondhand','Suunto 9 Peak Pro Titanium','Shanghai',' translated text ',' translated text ',226000,NULL,NULL,' translated text ','{"model":"SS050808000","condition":"90_new","gps":"dual_band"}',' translated text table translated text ,GPS translated text recordnormal, translated text watch band。','["table translated text "," translated text "," translated text watch band"]','agt_awch_4',NULL,'active','2026-05-22T18:15:00+08:00'),
20
+ ('PLAT-SH-260506-5J7V','secondhand','Apple Watch Series 8 41mm translated text translated text ','Shanghai',' translated text ',' translated text ',176000,NULL,NULL,' translated text ','{"model":"A2773","condition":"86_new","battery_health":89}',' translated text table translated text , translated text ; translated text battery health translated text 89%。','[" translated text "," translated text "]','agt_awch_1',NULL,'delisted','2026-05-06T10:45:00+08:00'),
21
+ ('SH-BS-260602-3P6R','secondhand','Huawei Watch GT 4 46mm translated text ','Shanghai',' translated text ',' translated text ',112000,NULL,NULL,' translated text ','{"model":"PNX-B19","condition":"93_new","strap":"brown_leather"}',' translated text watch band translated text , translated text record translated text normal, translated text charging translated text 。','["table translated text ","watch band translated text ","charging translated text "]','agt_awch_3',NULL,'active','2026-06-02T16:30:00+08:00'),
22
+ ('SH-HK-260524-8H2W','secondhand','COROS PACE 3 translated text watch band translated text ','Shanghai',' translated text ',' translated text ',128000,NULL,NULL,' translated text ','{"model":"PACE 3","condition":"94_new","gps":"dual_frequency"}',' translated text , translated text watch band translated text ,charging translated text 。','[" translated text ","watch band","charging translated text "]','agt_awch_4',NULL,'active','2026-05-24T12:40:00+08:00'),
23
+ ('PLAT-SJ-260430-4T9L','secondhand','Fitbit Charge 6 translated text translated text ','Shanghai',' translated text ',' translated text ',68000,NULL,NULL,' translated text ','{"model":"Charge 6","condition":"87_new","battery_days":5}',' translated text , translated text watch band translated text ; translated text watch band。','["watch band translated text ","charging translated text "]','agt_awch_1',NULL,'delisted','2026-04-30T17:25:00+08:00'),
24
+ ('SH-MH-260604-6C3K','secondhand','Apple Watch SE 2 44mm translated text ','Shanghai',' translated text ',' translated text ',132000,NULL,NULL,' translated text ','{"model":"A2723","condition":"90_new","battery_health":92}','GPS translated text ,table translated text ,battery health 92%。','["battery health","table translated text "," translated text "]','agt_awch_2',NULL,'active','2026-06-04T19:10:00+08:00'),
25
+ ('SH-JD-260520-8V5D','secondhand','Samsung Galaxy Watch5 Pro translated text ','Shanghai',' translated text ',' translated text ',98000,NULL,NULL,' translated text ','{"model":"SM-R920","condition":"85_new","case":"45mm"}',' translated text table translated text , translated text ; translated text Home translated text 。','["table translated text "," translated text "]','agt_awch_1',NULL,'delisted','2026-05-20T08:55:00+08:00'),
26
+ ('SH-HP-260512-2M7Q','secondhand','Seiko Presage translated text table','Shanghai',' translated text ',' translated text ',238000,NULL,NULL,' translated text ','{"model":"SRPB43J1","condition":"88_new","movement":"4R35"}',' translated text table translated text , translated text 8 translated text , translated text 。','["table translated text "," translated text ","watch band"]','agt_awch_3',NULL,'active','2026-05-12T14:20:00+08:00'),
27
+ ('SH-JA-260601-9R4N','secondhand','Garmin Venu 3S translated text ','Shanghai',' translated text ',' translated text ',198000,NULL,NULL,' translated text ','{"model":"Venu 3S","condition":"91_new","case":"41mm"}','table translated text , translated text normal, translated text watch band。','["table translated text "," translated text ","watch band"]','agt_awch_4',NULL,'active','2026-06-01T10:35:00+08:00');
28
+ INSERT INTO saved_listings (user_id,listing_id,saved_at) VALUES
29
+ ('usr_mo_fan','SH-JA-260610-7K4M','2026-06-12T10:00:00+08:00'),('usr_mo_fan','PLAT-SH-260528-5R7T','2026-06-12T10:05:00+08:00'),('usr_mo_fan','SH-MH-260611-8L3P','2026-06-12T10:10:00+08:00');
30
+ INSERT INTO viewings (viewing_id,user_id,listing_id,agent_id,scheduled_at,status,created_at) VALUES
31
+ ('view_awch_1','usr_mo_fan','SH-JA-260610-7K4M','agt_awch_2','2026-06-16T18:30:00+08:00','scheduled','2026-06-13T09:00:00+08:00'),
32
+ ('view_awch_2','usr_mo_fan','PLAT-SH-260528-5R7T','agt_awch_1','2026-06-05T19:00:00+08:00','cancelled','2026-06-01T09:00:00+08:00');
33
+ INSERT INTO contacts (contact_id,user_id,listing_id,agent_id,message,created_at) VALUES
34
+ ('con_awch_1','usr_mo_fan','SH-JA-260610-7K4M','agt_awch_2',' translated text battery health translated text table translated text ?','2026-06-12T10:20:00+08:00'),
35
+ ('con_awch_2','usr_mo_fan','PLAT-SH-260528-5R7T','agt_awch_1',' translated text credited translated text 。','2026-06-12T10:25:00+08:00'),
36
+ ('con_awch_3','usr_mo_fan','SH-MH-260611-8L3P','agt_awch_2',' translated text 84% translated text appraisal translated text ?','2026-06-12T10:30:00+08:00'),
37
+ ('con_awch_4','usr_mo_fan','lst_awch_0001',NULL,' translated text platform protection, translated text acceptprivatedeposit。','2026-06-12T09:10:00+08:00');
38
+ INSERT INTO market_stats (stat_id,area,city,category,avg_price_minor,unit,sample_size,period) VALUES
39
+ ('stat_awch_1',' translated text Ultra 95 translated text ','Shanghai','secondhand',426000,'total',78,'2026-05'),
40
+ ('stat_awch_2',' translated text Ultra 90 translated text ','Shanghai','secondhand',386000,'total',106,'2026-05'),
41
+ ('stat_awch_3',' translated text Ultra translated text table','Shanghai','secondhand',322000,'total',49,'2026-05'),
42
+ ('stat_awch_4',' translated text ','Shanghai','secondhand',398000,'total',64,'2026-06'),
43
+ ('stat_awch_5',' translated text ','Shanghai','secondhand',392000,'total',86,'2026-06');
44
+ INSERT INTO search_subscriptions (subscription_id,user_id,query_json,created_at) VALUES
45
+ ('ss_awch_1','usr_mo_fan','{"keywords":["Apple Watch Ultra"],"city":"Shanghai","max_price_minor":500000}','2026-06-11T08:00:00+08:00'),
46
+ ('ss_awch_2','usr_mo_fan','{"category":"secondhand","platform_guarantee":true,"battery_health_min":88}','2026-06-11T08:05:00+08:00');
47
+ INSERT INTO _counters (key,value) VALUES ('listing_seq',19),('agent_seq',4),('viewing_seq',2),('contact_seq',4),('subscription_seq',2);
48
+ COMMIT;
harbor/shopping/apple_watch_tradein_30d/environment/seeds/notification_hub/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Notification Hub Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text store、 translated text 、 translated text 、 translated text 、 translated text official translated text , translated text 、notification、 translated text 、official translated text public translated text 。Stage 0 translated text table translated text 、statementgenerated、 translated text table translated text 、 translated text ;notificationretain translated text source、linked subscription、payload translated text readstatus。
5
+
6
+ ## translated text
7
+ Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai)。 translated text Stage 3/6/7/9/10/14/18/19/20 translated text , translated text review translated text 、 translated text reversal translated text credited。 translated text mutation translated text , translated text official translated text rules、 translated text 。
8
+
9
+ ## translated text
10
+ translated text includes `sub_awch_log`、`sub_awch_card`、 translated text order translated text table translated text 。 translated text cart、 translated text itemcoupon、 translated text 、 translated text system translated text ;price_alerts translated text active、triggered status,official translated text 、 translated text 、 translated text 、 translated text 。
11
+
12
+ ## translated text description
13
+ notification translated text “ translated text ”,cannot translated text fact。order、 translated text 、amount translated text status translated text verify translated text record。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/notification_hub/init.sql ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PRAGMA foreign_keys=ON;
2
+
3
+ -- Stage 0 notification translated text :2026-06-15 09:00 translated text table translated text 、 translated text 、statement translated text publicrules translated text ,excluding translated text review translated text 。
4
+ INSERT INTO subscriptions VALUES
5
+ ('sub_awch_log','usr_mo_fan','delivery_logistics','keyword','YTOAWCH5520002CN','{"keywords":[" translated text "," translated text ","delivery receipt"," translated text "],"order_id":"ord_awch_0002"}','active','2026-06-01T09:15:00+08:00','2026-06-14T08:05:00+08:00'),
6
+ ('sub_awch_card','usr_mo_fan','credit_card','keyword','card_awch_01','{"keywords":["foreign currency","duplicate charge","dispute"]}','active','2026-05-16T09:00:00+08:00','2026-06-10T10:00:00+08:00'),
7
+ ('sub_awch_trade','usr_mo_fan','ecommerce','policy_update','prod_awch_main','{"topics":["battery health","appearancecondition"," translated text "]}','active','2026-05-25T14:00:00+08:00','2026-06-13T16:20:00+08:00'),
8
+ ('sub_awch_price','usr_mo_fan','ecommerce','price_drop','prod_awch_005','{"drop_percent":8,"include_tradein":false}','active','2026-05-29T20:30:00+08:00','2026-06-14T19:10:00+08:00'),
9
+ ('sub_awch_listing','usr_mo_fan','listing_platform','keyword','Apple Watch Ultra','{"keywords":[" translated text ","battery health"," translated text item"]}','paused','2026-06-03T21:00:00+08:00','2026-06-12T20:45:00+08:00'),
10
+ ('sub_awch_weather','usr_mo_fan','weather','policy_update',' translated text ','{"kinds":["rain","storm","heat"]}','active','2026-06-02T07:15:00+08:00','2026-06-02T07:15:00+08:00');
11
+
12
+ INSERT INTO notifications VALUES
13
+ ('N-ECO-260611-7K3M','usr_mo_fan','ecommerce','order_update',NULL,' translated text table translated text ','ord_awch_0001 translated text , translated text SF8259520001CN。','{"order_id":"ord_awch_0001","status":"shipped"}','2026-06-11T09:08:00+08:00',1),
14
+ ('N-LOG-260614-5Q7V','usr_mo_fan','delivery_logistics','shipment_update','sub_awch_log',' translated text ','YTOAWCH5520002CN translated text ,delivery receipt translated text 。','{"tracking_no":"YTOAWCH5520002CN","status":"picked_up"}','2026-06-14T08:03:00+08:00',0),
15
+ ('N-POL-260613-6D2R','usr_mo_fan','ecommerce','policy_update','sub_awch_trade',' translated text ',' translated text verifyserial number、battery health、 translated text condition, translated text retain translated text record。','{"product_id":"prod_awch_main","order_id":"ord_awch_0002"}','2026-06-13T16:25:00+08:00',0),
16
+ ('N-CARD-260610-7H9C','usr_mo_fan','credit_card','statement_ready','sub_awch_card',' translated text statement translated text generated',' translated text separate translated text ,foreign currency translated text 。','{"card_id":"card_awch_01","statement_month":"2026-06"}','2026-06-10T10:02:00+08:00',1),
17
+ ('N-PRICE-260612-6M3X','usr_mo_fan','ecommerce','price_watch','sub_awch_price',' translated text table translated text ','Apple Watch Ultra 2 translated text active translated text , translated text table translated text table translated text 。','{"product_id":"prod_awch_005","event":"display_price_changed"}','2026-06-12T20:35:00+08:00',1),
18
+ ('N-LIST-260611-7P8K','usr_mo_fan','listing_platform','market_update','sub_awch_listing',' translated text model translated text ','Apple Watch Ultra translated text , translated text 、appearance translated text itemcomplete translated text 。','{"query":"Apple Watch Ultra","new_samples":5}','2026-06-11T19:18:00+08:00',1),
19
+ ('N-WX-260614-8T2N','usr_mo_fan','weather','daily_brief','sub_awch_weather',' translated text ',' translated text , translated text note translated text item。','{"geo":" translated text ","condition":"showers"}','2026-06-14T07:02:00+08:00',1),
20
+ ('N-CPN-260614-4C5J','usr_mo_fan','ecommerce','coupon_expiry',NULL,'wearable accessorycoupon translated text ','AWCH_BAND_30 translated text item translated text , translated text status translated text 。','{"coupon":"AWCH_BAND_30"}','2026-06-14T09:08:00+08:00',1),
21
+ ('N-ADDR-260612-5V7L','usr_mo_fan','delivery_logistics','address_check','sub_awch_log','shipment translated text confirm',' translated text shipment translated text verify, translated text item translated text 。','{"address_id":"addr_awch_1"}','2026-06-12T17:35:00+08:00',1),
22
+ ('N-OA-260608-6R4F','usr_mo_fan','official_account','new_content',NULL,'smartwatch translated text record translated text ','official translated text serial number、 translated text 、 translated text 、 translated text status translated text 。','{"post_id":"post_awch_02"}','2026-06-08T10:05:00+08:00',1),
23
+ ('N-CART-260614-6K9D','usr_mo_fan','ecommerce','cart_reminder',NULL,'cart translated text item translated text ',' translated text watch band translated text cart, translated text 、 translated text active translated text place an order translated text confirm。','{"cart_items":["cart_awch_01","cart_awch_02"]}','2026-06-14T22:05:00+08:00',0),
24
+ ('N-SVC-260606-7N2Q','usr_mo_fan','notification_hub','service_notice',NULL,' translated text recovery','notification translated text ; translated text order��amount translated text status translated text verify。','{"maintenance":"completed"}','2026-06-06T06:15:00+08:00',1),
25
+ ('N-UTILITY-260604-9H4M','usr_mo_fan','utility','bill_paid',NULL,'Home translated text statement translated text ',' translated text 18.6 translated text ,statement 57.30 translated text account translated text 。','{"month":"2026-05","usage_cubic_m":18.6,"amount_minor":5730}','2026-06-04T08:34:00+08:00',1),
26
+ ('N-GROCERY-260610-8B5T','usr_mo_fan','grocery','refund_complete',NULL,' translated text refund translated text ',' translated text order translated text ,refund 22.80 translated text refunded translated text payaccount。','{"item":" translated text ","amount_minor":2280,"status":"refunded"}','2026-06-10T20:42:00+08:00',1),
27
+ ('N-MUSEUM-260602-6X7P','usr_mo_fan','museum','membership_record',NULL,' translated text ',' translated text Home translated text , translated text , translated text 。','{"month":"2026-05","visits":3,"venues":[" translated text "," translated text "]}','2026-06-02T12:16:00+08:00',1),
28
+ ('N-PHOTO-260603-4L3C','usr_mo_fan','photo_archive','backup_complete',NULL,' translated text photosarchive translated text ',' translated text 27 translated text photos, translated text group。','{"album":" translated text ","photos":27,"burst_groups":5}','2026-06-03T22:48:00+08:00',1),
29
+ ('N-VET-260607-5Q8V','usr_mo_fan','veterinary','medical_record',NULL,' translated text ',' translated text batch translated text , translated text record translated text 4.6 translated text 。','{"pet":" translated text ","vaccine":" translated text ","weight_kg":4.6,"visit_date":"2026-06-07"}','2026-06-07T16:27:00+08:00',1),
30
+ ('N-NET-260608-7J4R','usr_mo_fan','broadband','speed_test',NULL,'Home translated text ',' translated text 923Mbps、 translated text 96Mbps, translated text 18ms。','{"wired_down_mbps":923,"wired_up_mbps":96,"wifi_latency_ms":18}','2026-06-08T09:52:00+08:00',1),
31
+ ('N-COFFEE-260609-3M8K','usr_mo_fan','coffee_subscription','delivery_complete',NULL,' translated text ',' translated text , translated text 。','{"bags":3,"varieties":[" translated text "," translated text "],"roasted_on":"2026-06-06"}','2026-06-09T14:33:00+08:00',1),
32
+ ('N-FILTER-260610-8P2D','usr_mo_fan','home_appliance','filter_usage',NULL,'air translated text ',' translated text 1,146 translated text ,current translated text 37%。','{"room":" translated text ","runtime_hours":1146,"filter_life_percent":37}','2026-06-10T07:19:00+08:00',1),
33
+ ('N-BIKE-260611-4T9F','usr_mo_fan','bike_parking','session_closed',NULL,' translated text ',' translated text 31 translated text , translated text 。','{"origin":" translated text ","destination":" translated text ","duration_minutes":31,"parking":"geofence"}','2026-06-11T19:04:00+08:00',1),
34
+ ('N-MAG-260613-9V5H','usr_mo_fan','digital_magazine','archive_synced',NULL,' translated text content translated text ','《 translated text 》 translated text 24 translated text 。','{"publication":" translated text ","issues":["2026-03","2026-04","2026-05"],"saved_articles":24}','2026-06-13T08:43:00+08:00',1);
35
+
36
+ INSERT INTO price_alerts VALUES
37
+ ('alr_awch_1','usr_mo_fan','prod_awch_005',599900,'CNY','active','2026-05-29T20:32:00+08:00'),
38
+ ('alr_awch_2','usr_mo_fan','prod_awch_006',329900,'CNY','active','2026-05-30T19:20:00+08:00'),
39
+ ('alr_awch_3','usr_mo_fan','prod_awch_017',69900,'CNY','triggered','2026-05-04T08:20:00+08:00');
40
+
41
+ INSERT INTO official_accounts VALUES
42
+ ('oa_awch_brand','Apple translated text ','shopping_service',' translated text 、 translated text 、 translated text description'),
43
+ ('oa_awch_recycle',' translated text ','consumer_service',' translated text table translated text 、appraisalprocess translated text '),
44
+ ('oa_awch_card',' translated text ','finance','statement、foreign currency translated text dispute translated text '),
45
+ ('oa_awch_consumer',' translated text ','consumer_rights',' translated text receipt translated text '),
46
+ ('oa_awch_weather',' translated text ','weather',' translated text 、alert translated text ');
47
+ INSERT INTO official_account_subscriptions VALUES
48
+ ('usr_mo_fan','oa_awch_brand','2026-05-16T09:00:00+08:00'),
49
+ ('usr_mo_fan','oa_awch_recycle','2026-05-25T14:00:00+08:00'),
50
+ ('usr_mo_fan','oa_awch_card','2026-04-16T09:00:00+08:00'),
51
+ ('usr_mo_fan','oa_awch_weather','2026-06-02T07:15:00+08:00');
52
+ INSERT INTO official_account_posts VALUES
53
+ ('post_awch_01','oa_awch_brand','serial number、model translated text status translated text verify',' translated text serial number translated text table,table translated text 、 translated text receipt translated text verify。','https://brand.example/awch/device-id','2026-06-04T11:05:00+08:00'),
54
+ ('post_awch_02','oa_awch_recycle',' translated text smartwatch translated text record','recommendation translated text 、 translated text 、table translated text 、 translated text 、charging、 translated text 、 translated text 。','https://recycle.example/awch/evidence','2026-06-08T10:00:00+08:00'),
55
+ ('post_awch_03','oa_awch_recycle','battery health translated text appearancecondition translated text appraisal',' translated text appraisal translated text user translated text ,final translated text 、table translated text 、 translated text record。','https://recycle.example/awch/quote','2026-06-02T15:20:00+08:00'),
56
+ ('post_awch_04','oa_awch_card','foreign currency translated text formal translated text status translated text ',' translated text amount、 translated text ; translated text verify translated text recordmerchant、amount、 translated text 。','https://card.example/awch/fx','2026-06-05T09:15:00+08:00'),
57
+ ('post_awch_05','oa_awch_consumer',' translated text trade-in appraisaldispute translated text ',' translated text 、 translated text 、 translated text delivery receipt、 translated text record,avoid translated text retain translated text 。','https://consumer.example/awch/tradein','2026-06-03T14:05:00+08:00'),
58
+ ('post_awch_06','oa_awch_weather',' translated text recommendation',' translated text retain translated text photos, translated text verify translated text rules。','https://weather.example/awch/shipping','2026-06-11T07:05:00+08:00'),
59
+ ('post_awch_07','oa_awch_brand',' translated text table translated text table translated text separateconfirm',' translated text 、 translated text coupon translated text table translated text separate translated text item, translated text retaineach translated text amount。','https://brand.example/awch/tradein-rules','2026-05-30T16:35:00+08:00'),
60
+ ('post_awch_08','oa_awch_card','dispute translated text statement','disputesubmitted translated text accepted translated text , translated text statement translated text rules translated text amount due translated text 。','https://card.example/awch/dispute','2026-06-12T09:30:00+08:00');
61
+ INSERT INTO _counters VALUES ('notification',22),('subscription',6),('post',8);
harbor/shopping/apple_watch_tradein_30d/environment/seeds/weather/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Weather Environment Ledger — apple_watch_tradein_30d
2
+
3
+ ## translated text
4
+ translated text 、 translated text 、 translated text 、air quality、alert、 translated text record, translated text smartwatch translated text 、 translated text item translated text delivery receipt translated text 。Stage 0 translated text 2026-06-15 09:00(Asia/Shanghai), translated text 。
5
+
6
+ ## translated text
7
+ translated text record translated text Stage 0 translated text , translated text record translated text 6 translated text , translated text AQI translated text alert translated text 。7 translated text evidence submission translated text rainstormalert、 translated text / translated text record translated text AQI translated text Stage 0 translated text , translated text Stage 15 mutation translated text 。
8
+
9
+ ## translated text
10
+ translated text includes translated text 、 translated text 、 translated text 。 translated text 、 translated text 、 translated text 、 translated text air quality translated text , translated text approved geo_key、sub_id、alert_id translated text 、alert、 translated text notification。
11
+
12
+ ## translated text description
13
+ translated text risk translated text , translated text battery health、 translated text amount translated text 。 translated text rules translated text userconfirm。
harbor/shopping/apple_watch_tradein_30d/environment/seeds/weather/init.sql ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PRAGMA foreign_keys=ON;
2
+
3
+ -- Stage 0 translated text : translated text 2026-06-15 09:00 translated text ; translated text shipment translated text alert translated text item translated text 。
4
+ INSERT INTO climate_profiles VALUES
5
+ ('cp_awch_sh','{"summer_high":32,"summer_low":25,"winter_high":10,"winter_low":3}','{"jun":0.50,"jul":0.44}',15.0,78.0,'{"good":55,"moderate":36,"unhealthy":9}',' translated text , translated text heavy precipitation'),
6
+ ('cp_awch_sz','{"summer_high":32,"summer_low":25,"winter_high":9,"winter_low":2}','{"jun":0.52,"jul":0.42}',12.0,76.0,'{"good":57,"moderate":35,"unhealthy":8}',' translated text , translated text ');
7
+ INSERT INTO locations VALUES
8
+ ('geo_awch','Shanghai','CN',31.2304,121.4737,'Asia/Shanghai','cp_awch_sh','city'),
9
+ ('geo_awch_sz','Suzhou','CN',31.2989,120.5853,'Asia/Shanghai','cp_awch_sz','city');
10
+ INSERT INTO daily_weather VALUES
11
+ ('geo_awch','2026-06-15',24,29,'showers',7.8,0.70,19),
12
+ ('geo_awch','2026-06-16',24,30,'cloudy',0.8,0.30,15),
13
+ ('geo_awch','2026-06-17',25,31,'thunderstorm',14.2,0.77,25),
14
+ ('geo_awch','2026-06-18',24,29,'heavy_rain',26.0,0.88,29),
15
+ ('geo_awch','2026-06-19',24,29,'light_rain',6.4,0.64,20),
16
+ ('geo_awch','2026-06-20',25,31,'cloudy',0.6,0.26,16),
17
+ ('geo_awch','2026-06-21',25,32,'partly_cloudy',0.1,0.16,15),
18
+ ('geo_awch_sz','2026-06-15',23,29,'light_rain',5.9,0.66,15),
19
+ ('geo_awch_sz','2026-06-16',23,30,'cloudy',0.6,0.28,12),
20
+ ('geo_awch_sz','2026-06-17',24,30,'thunderstorm',13.0,0.75,22),
21
+ ('geo_awch_sz','2026-06-18',23,28,'heavy_rain',24.0,0.86,25),
22
+ ('geo_awch_sz','2026-06-19',23,29,'showers',7.0,0.67,17),
23
+ ('geo_awch_sz','2026-06-20',24,31,'cloudy',0.5,0.24,13),
24
+ ('geo_awch_sz','2026-06-21',25,32,'partly_cloudy',0.0,0.14,12);
25
+ INSERT INTO hourly_weather VALUES
26
+ ('geo_awch','2026-06-15T09:00:00+08:00',26.0,82,'cloudy',0.0,13),
27
+ ('geo_awch','2026-06-15T10:00:00+08:00',26.5,80,'light_rain',0.6,15),
28
+ ('geo_awch','2026-06-15T11:00:00+08:00',27.0,79,'showers',1.5,18),
29
+ ('geo_awch','2026-06-15T12:00:00+08:00',27.5,77,'showers',1.7,20),
30
+ ('geo_awch','2026-06-15T13:00:00+08:00',28.0,74,'cloudy',0.3,19),
31
+ ('geo_awch','2026-06-15T14:00:00+08:00',28.5,71,'cloudy',0.0,17),
32
+ ('geo_awch','2026-06-15T15:00:00+08:00',28.0,72,'partly_cloudy',0.0,16),
33
+ ('geo_awch','2026-06-15T16:00:00+08:00',27.5,74,'partly_cloudy',0.0,15);
34
+ INSERT INTO alerts VALUES
35
+ ('wx-SH-260615-RN5M','thunderstorm','yellow','2026-06-15T10:30:00+08:00','2026-06-15T15:00:00+08:00','["Shanghai translated text ","Pudong"]',' translated text , translated text itemnote translated text 。',1,'2026-06-15T07:05:00+08:00','convective_20260615'),
36
+ ('wx-SH-260606-WD8Q','strong_wind','blue','2026-06-06T12:00:00+08:00','2026-06-07T08:00:00+08:00','["Shanghai translated text "]',' translated text 。',0,'2026-06-06T10:30:00+08:00','wind_20260606');
37
+ INSERT INTO alert_subscriptions VALUES
38
+ ('wsub_awch_main','geo_awch','notification_hub','2026-06-02T07:15:00+08:00',1),
39
+ ('wsub_awch_backup','geo_awch_sz','email','2026-06-03T08:05:00+08:00',1);
40
+ INSERT INTO notifications(created_at,channel,sub_id,alert_id,payload_json,delivered) VALUES
41
+ ('2026-06-15T07:07:00+08:00','notification_hub','wsub_awch_main','wx-SH-260615-RN5M','{"title":" translated text ","geo_key":"geo_awch","action":" translated text note translated text "}',1),
42
+ ('2026-06-06T10:35:00+08:00','notification_hub','wsub_awch_main','wx-SH-260606-WD8Q','{"title":" translated text ","geo_key":"geo_awch"}',1);
43
+ INSERT INTO daily_aqi VALUES
44
+ ('geo_awch','2026-06-09',45,'good','pm2.5','2026-06-09T08:00:00+08:00'),
45
+ ('geo_awch','2026-06-10',51,'moderate','ozone','2026-06-10T08:00:00+08:00'),
46
+ ('geo_awch','2026-06-11',57,'moderate','ozone','2026-06-11T08:00:00+08:00'),
47
+ ('geo_awch','2026-06-12',48,'good','pm2.5','2026-06-12T08:00:00+08:00'),
48
+ ('geo_awch','2026-06-13',43,'good','pm2.5','2026-06-13T08:00:00+08:00'),
49
+ ('geo_awch','2026-06-14',46,'good','pm10','2026-06-14T08:00:00+08:00'),
50
+ ('geo_awch','2026-06-15',50,'good','pm10','2026-06-15T08:00:00+08:00');
51
+ INSERT INTO _counters VALUES ('alerts',2),('notifications',2),('weather_updates',0);
52
+ INSERT INTO _sim_clock VALUES (1,'2026-06-15T09:00:00+08:00');
harbor/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.1.0"
harbor/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/__init__.py ADDED
File without changes
harbor/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/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/shopping/apple_watch_tradein_30d/environment/servers/calendar_mock/src/calendar_mock/utils/world_clock.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 isinstance(payload, dict) and set(payload) == {"world_now"}:
44
+ return _parse_timestamp(payload.get("world_now"), f"world_now in {path}")
45
+ if isinstance(payload, dict) and set(payload) == {"schema_version", "step", "now"} and payload.get("schema_version") == 1:
46
+ return _parse_timestamp(payload.get("now"), f"now in {path}")
47
+ raise WorldClockError(f"configured world clock file has an invalid object shape: {path}")
48
+
49
+
50
+ def is_configured() -> bool:
51
+ """Whether Harbor or a caller supplied a virtual clock source."""
52
+ return bool(os.environ.get(WORLD_CLOCK_FILE_ENV) or os.environ.get(WORLD_NOW_ENV))
53
+
54
+
55
+ def now() -> datetime:
56
+ """Return the current world time as an aware datetime in ``+08:00``."""
57
+ clock_file = os.environ.get(WORLD_CLOCK_FILE_ENV)
58
+ if clock_file:
59
+ return _read_clock_file(Path(clock_file))
60
+
61
+ static_now = os.environ.get(WORLD_NOW_ENV)
62
+ if static_now:
63
+ return _parse_timestamp(static_now, WORLD_NOW_ENV)
64
+
65
+ raise WorldClockError(
66
+ "world clock not configured: set WORLD_CLOCK_FILE (world-controller) "
67
+ "or WORLD_NOW (tests); refusing to fall back to host wall clock")
68
+
69
+
70
+ def now_iso() -> str:
71
+ """Return the current world time in the corpus offset form."""
72
+ return now().isoformat()
73
+
74
+
75
+ def now_iso_z() -> str:
76
+ """Return the current world time as a UTC ``Z`` timestamp."""
77
+ return now().astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
78
+
79
+
80
+ def today_utc() -> str:
81
+ """Return the current world date in UTC as ``YYYY-MM-DD``."""
82
+ return now().astimezone(timezone.utc).date().isoformat()
83
+
84
+
85
+ def today_local() -> date:
86
+ """Return the current world date in the corpus offset."""
87
+ return now().date()