fd-open-data-protocol 0.3.2__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. fd_open_data_protocol-0.4.0/LICENSE +21 -0
  2. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/PKG-INFO +5 -1
  3. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/__init__.py +1 -1
  4. fd_open_data_protocol-0.4.0/fd_open_data_protocol/conformance_adapter.py +115 -0
  5. fd_open_data_protocol-0.4.0/fd_open_data_protocol/surface_report.py +167 -0
  6. fd_open_data_protocol-0.4.0/fd_open_data_protocol/vocabulary/alignment/foundation.yaml +65 -0
  7. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/concepts.yaml +135 -0
  8. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/entity_types.yaml +45 -0
  9. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary.py +145 -3
  10. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/PKG-INFO +5 -1
  11. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/SOURCES.txt +7 -1
  12. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/requires.txt +2 -0
  13. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/pyproject.toml +12 -2
  14. fd_open_data_protocol-0.4.0/tests/test_surface_report.py +209 -0
  15. fd_open_data_protocol-0.4.0/tests/test_vocabulary_additive.py +184 -0
  16. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/README.md +0 -0
  17. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/constants.py +0 -0
  18. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/loader.py +0 -0
  19. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/openalex_provider.py +0 -0
  20. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/provider.py +0 -0
  21. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/registry.py +0 -0
  22. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/registry_cli.py +0 -0
  23. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/registry_store.py +0 -0
  24. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/schema.py +0 -0
  25. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/crosswalks/datacommons-worldbank.yaml +0 -0
  26. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/event_types.yaml +0 -0
  27. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/qualifiers.yaml +0 -0
  28. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/relation_types.yaml +0 -0
  29. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol/vocabulary/units.yaml +0 -0
  30. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/dependency_links.txt +0 -0
  31. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/entry_points.txt +0 -0
  32. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/fd_open_data_protocol.egg-info/top_level.txt +0 -0
  33. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/setup.cfg +0 -0
  34. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/tests/test_loader.py +0 -0
  35. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/tests/test_openalex_provider.py +0 -0
  36. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/tests/test_registry_pipeline.py +0 -0
  37. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/tests/test_registry_schema.py +0 -0
  38. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/tests/test_schema_vocabulary.py +0 -0
  39. {fd_open_data_protocol-0.3.2 → fd_open_data_protocol-0.4.0}/tests/test_vocabulary.py +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FindData Technology
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.
@@ -1,17 +1,21 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fd-open-data-protocol
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
4
  Summary: The open-data datasource protocol: a manifest contract a datasource exposes to be ingested by fd-open-data-mcp (or any consumer).
5
5
  Author: FindDataOfficial
6
6
  License: MIT
7
7
  Requires-Python: >=3.10
8
8
  Description-Content-Type: text/markdown
9
+ License-File: LICENSE
9
10
  Requires-Dist: pydantic>=2.0
10
11
  Requires-Dist: pyyaml>=6.0
11
12
  Provides-Extra: dev
12
13
  Requires-Dist: pytest>=8.0; extra == "dev"
14
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
15
+ Requires-Dist: httpx>=0.27; extra == "dev"
13
16
  Provides-Extra: registry
14
17
  Requires-Dist: psycopg[binary]>=3.1; extra == "registry"
18
+ Dynamic: license-file
15
19
 
16
20
  # fd-open-data-protocol
17
21
 
@@ -5,4 +5,4 @@ concept hints + fetch reference) so that fd-open-data-mcp - or any consumer -
5
5
  can ingest it via ``register_datasource``. Ship one manifest file -> the
6
6
  datasource is added; no consumer-side wiring.
7
7
  """
8
- __version__ = "0.3.2"
8
+ __version__ = "0.4.0"
@@ -0,0 +1,115 @@
1
+ """Conformance adapter for the open-data vocabulary (task 7.3).
2
+
3
+ The protocol library has no storage of its own — its "ontology" is a versioned
4
+ YAML vocabulary — so the sandbox wires the kernel to an in-memory store whose
5
+ closed vocabulary *is* the shipped release. That is enough to run every check
6
+ that does not need a database, and it exercises the parts this library actually
7
+ owns: closed sets, additive releases and stable URIs.
8
+
9
+ The adapter lives here (not in the library's runtime path) because it needs the
10
+ kernel: the library itself keeps the kernel optional so it still installs in
11
+ environments that never see this workspace.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from fd_ontology_kernel.contracts import Unit
17
+ from fd_ontology_kernel.kernel import AdapterDeclaration, Kernel
18
+ from fd_ontology_kernel.memory import (
19
+ MemoryJournal,
20
+ MemoryProposalBox,
21
+ MemoryPublicationStore,
22
+ MemoryRegistry,
23
+ MemoryUnitStore,
24
+ )
25
+ from fd_ontology_kernel.vocab import Entry, Vocabulary, VocabularySet
26
+
27
+ from .vocabulary import load_vocabulary, to_kernel_vocabulary
28
+
29
+ DECLARATION = AdapterDeclaration(
30
+ system="fd-open-data-protocol",
31
+ kernel_contract="1.0",
32
+ manifest_shape=2,
33
+ )
34
+
35
+
36
+ def _contract_vocabulary() -> Vocabulary:
37
+ """The shipped release, renamed onto the kernel's two contract set names.
38
+
39
+ The kernel contract asks every surface for ``entity_types`` and
40
+ ``relationship_kinds``; this registry calls them ``entity-type`` and
41
+ ``relation-type``. Renaming here (rather than special-casing the kernel) keeps
42
+ one vocabulary and one closed-set rule.
43
+ """
44
+ registry = load_vocabulary()
45
+ base = to_kernel_vocabulary(registry)
46
+ sets = dict(base.sets)
47
+
48
+ def _renamed(source: str, target: str) -> VocabularySet | None:
49
+ hold = sets.get(source)
50
+ if hold is None:
51
+ return None
52
+ return VocabularySet(
53
+ name=target,
54
+ values=hold.values,
55
+ entries={
56
+ entry_id: Entry(
57
+ id=entry_id,
58
+ set_name=target,
59
+ label_en=entry.label_en,
60
+ label_zh=entry.label_zh,
61
+ description=entry.description,
62
+ superseded_by=entry.superseded_by,
63
+ )
64
+ for entry_id, entry in hold.entries.items()
65
+ },
66
+ )
67
+
68
+ entity_types = _renamed("entity-type", "entity_types")
69
+ relationship_kinds = _renamed("relation-type", "relationship_kinds")
70
+ if entity_types is not None:
71
+ sets["entity_types"] = entity_types
72
+ if relationship_kinds is not None:
73
+ sets["relationship_kinds"] = relationship_kinds
74
+
75
+ return Vocabulary(release=base.release, sets=sets)
76
+
77
+
78
+ class _VocabularySource:
79
+ def __init__(self, vocabulary: Vocabulary) -> None:
80
+ self._vocabulary = vocabulary
81
+
82
+ def load(self, *, scope_id: str) -> Vocabulary:
83
+ return self._vocabulary
84
+
85
+
86
+ def _sandbox() -> Kernel:
87
+ vocabulary = _contract_vocabulary()
88
+ relationship_hold = vocabulary.sets.get("relationship_kinds")
89
+ return Kernel(
90
+ units=MemoryUnitStore(),
91
+ events=MemoryJournal(),
92
+ vocabulary=_VocabularySource(vocabulary),
93
+ proposals=MemoryProposalBox(),
94
+ publications=MemoryPublicationStore(),
95
+ distribution=MemoryRegistry(),
96
+ relationship_kinds=tuple(relationship_hold.values) if relationship_hold else (),
97
+ # This vocabulary has no clause concept; the clause-parent rule is
98
+ # vacuous here and the suite reports it as skipped, not as passed.
99
+ clause_kinds=(),
100
+ manifest_shape=DECLARATION.manifest_shape,
101
+ declaration=DECLARATION,
102
+ )
103
+
104
+
105
+ def build():
106
+ """Factory named by ``adapters.json``."""
107
+ from fd_ontology_kernel.conformance.spec import AdapterSpec
108
+
109
+ return AdapterSpec(
110
+ name="fd-open-data-protocol",
111
+ system=DECLARATION.system,
112
+ declaration=DECLARATION,
113
+ sandbox=_sandbox,
114
+ notes="YAML vocabulary surface; sandbox is an in-memory store over the shipped release",
115
+ )
@@ -0,0 +1,167 @@
1
+ """启动时向 registry 自报工具面(共享实现,openspec: mcp-surface-self-report)。
2
+
3
+ 逐用户凭据服务的 HTTP 层匿名一律 401,registry 探针永远探不到——工具面变更后
4
+ 快照停旧值,发布门把合法新工具名判 unresolved。本模块在服务启动、工具注册完成
5
+ 后,把**运行时枚举**的工具名清单报给 registry 的内部自报路由(path 绑定 token)。
6
+
7
+ 从三份逐仓副本(wire-ops / wanxing-ops / fd-paper-trading,各 160 行近同)抽成单一
8
+ 共享实现(openspec: stabilize-mcp-lifecycle D1)——多份复制必然漂移,一处修复到不了
9
+ 另两处。
10
+
11
+ 纪律:
12
+ - 失败**不阻塞启动**——registry 不可达时服务照常提供能力;
13
+ - 有界重试 15s/1m/5m/30m ×4(`REGISTRY_SURFACE_BACKOFF` 可覆盖),成功即停——不是心跳;
14
+ - 未配置时**静默跳过**(本地开发/未上牌形态,零行为变化)。
15
+
16
+ env(按 `prefix` 派生,默认 `WIRE`;各服务用自己前缀,见 `ensure_started(prefix=...)`):
17
+ - `REGISTRY_INTERNAL_URL` registry 内网入口(全局,非按线)
18
+ - `<PREFIX>_SURFACE_TOKEN` 该服务 path 绑定的 srf_ token
19
+ - `<PREFIX>_SURFACE_ENTRY_PATH` 注册路径(如 `/wire-ops-mcp`)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import logging
26
+ import os
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ #: 退避序列(秒)。REGISTRY_SURFACE_BACKOFF 可整体覆盖(逗号分隔)。
31
+ _DEFAULT_BACKOFF = (15, 60, 300, 1800)
32
+
33
+
34
+ def _backoff_sequence() -> tuple[float, ...]:
35
+ raw = os.environ.get("REGISTRY_SURFACE_BACKOFF")
36
+ if not raw:
37
+ return _DEFAULT_BACKOFF
38
+ try:
39
+ values = tuple(float(x) for x in raw.split(",") if x.strip())
40
+ return values or _DEFAULT_BACKOFF
41
+ except ValueError:
42
+ logger.warning("REGISTRY_SURFACE_BACKOFF unparsable; using default")
43
+ return _DEFAULT_BACKOFF
44
+
45
+
46
+ def _configured(prefix: str) -> tuple[str, str, str] | None:
47
+ """(internal_url, entry_path, token) 或 None(未配置 → 静默跳过)。"""
48
+ base = os.environ.get("REGISTRY_INTERNAL_URL", "").rstrip("/")
49
+ token = os.environ.get(f"{prefix}_SURFACE_TOKEN", "")
50
+ path = os.environ.get(f"{prefix}_SURFACE_ENTRY_PATH", "").strip()
51
+ if not base or not token or not path:
52
+ return None
53
+ if not path.startswith("/"):
54
+ path = "/" + path
55
+ return base, path.rstrip("/"), token
56
+
57
+
58
+ async def _tool_names(mcp) -> list[str]:
59
+ """运行时枚举:真源是注册进 FastMCP 的工具,不是 tool-surface.json。
60
+
61
+ `fastmcp` 版本区间横跨两代枚举 API:4.x 只有 ``list_tools()``(Tool 对象/字典序列),
62
+ 更高版本另提供 ``get_tools()``({name: tool} 映射)。按可用性分派——只认其中一个
63
+ API 会在另一代的镜像里 AttributeError(2026-10-24 生产实证:启动自报因此一次都没
64
+ 发出去,fire-and-forget 边界吞成 failed)。
65
+ """
66
+ get_tools = getattr(mcp, "get_tools", None)
67
+ if get_tools is not None:
68
+ return sorted((await get_tools()).keys())
69
+ items = await mcp.list_tools()
70
+ return sorted(t["name"] if isinstance(t, dict) else t.name for t in items)
71
+
72
+
73
+ def _surface_version() -> str | None:
74
+ """tool-surface.json 的 sha 摘要(存在才带)——把自报与构建期清单对上版。
75
+
76
+ wheel 里它随包走(package-data);editable/源码树里它在仓库根,
77
+ importlib.resources 找不到——回落逐级父目录找。
78
+ """
79
+ try:
80
+ import hashlib
81
+ from pathlib import Path
82
+
83
+ here = Path(__file__).resolve().parent
84
+ for cand in (here, *here.parents[:5]):
85
+ if (cand / "tool-surface.json").is_file():
86
+ return hashlib.sha256((cand / "tool-surface.json").read_bytes()).hexdigest()[:12]
87
+ except Exception as exc: # noqa: BLE001 — 版本标注是可选元数据
88
+ logger.warning("surface_version unavailable: %s", exc)
89
+ return None
90
+
91
+
92
+ async def report_surface(mcp, *, prefix: str = "WIRE", httpx=None) -> bool:
93
+ """报一次;成功 True。所有失败都被吞掉并记日志——启动不受阻。"""
94
+ cfg = _configured(prefix)
95
+ if cfg is None:
96
+ logger.info("surface report: not configured (%s_SURFACE_*), skipping", prefix)
97
+ return False
98
+ base, path, token = cfg
99
+
100
+ if httpx is None:
101
+ import httpx as httpx_mod
102
+ httpx = httpx_mod
103
+
104
+ payload = {
105
+ "tools": [{"name": name} for name in await _tool_names(mcp)],
106
+ "surface_version": _surface_version(),
107
+ }
108
+ url = f"{base}/api/surface-report/servers{path}/tool-list"
109
+
110
+ for attempt, delay in enumerate((0.0,) + _backoff_sequence(), start=1):
111
+ if delay:
112
+ await asyncio.sleep(delay)
113
+ try:
114
+ async with httpx.AsyncClient(timeout=15) as client:
115
+ resp = await client.post(
116
+ url, json=payload,
117
+ headers={"Authorization": f"Bearer {token}"},
118
+ )
119
+ if resp.status_code == 200:
120
+ body = resp.json()
121
+ logger.info(
122
+ "surface report: ok (%s tool(s), updated=%s reason=%s)",
123
+ body.get("num_tools"), body.get("updated"), body.get("reason"),
124
+ )
125
+ return True
126
+ logger.warning(
127
+ "surface report: HTTP %s (attempt %s) — %s",
128
+ resp.status_code, attempt, resp.text[:160],
129
+ )
130
+ except Exception as exc: # noqa: BLE001 — 网络层任何异常都不上抛
131
+ logger.warning(
132
+ "surface report: %s: %s (attempt %s)",
133
+ type(exc).__name__, str(exc)[:120], attempt,
134
+ )
135
+ logger.error("surface report: giving up after %s attempts", len(_backoff_sequence()) + 1)
136
+ return False
137
+
138
+
139
+ def report_state(ok: bool, configured: bool) -> str:
140
+ """/health 的 last_surface_report 口径。"""
141
+ if not configured:
142
+ return "not_configured"
143
+ return "ok" if ok else "failed"
144
+
145
+
146
+ def start_background(mcp, *, prefix: str = "WIRE") -> asyncio.Task | None:
147
+ """fire-and-forget 自报任务;未配置时返回 None(零行为变化)。"""
148
+ if _configured(prefix) is None:
149
+ return None
150
+
151
+ async def _runner():
152
+ # 吞掉一切异常:网络层失败 report_surface 自己消化,但代码层缺陷
153
+ # (参数错、序列化炸)也不能把后台任务变成未处理异常——状态置 failed。
154
+ try:
155
+ ok = await report_surface(mcp, prefix=prefix)
156
+ mcp._surface_report = report_state(ok, configured=True)
157
+ except Exception: # noqa: BLE001 — fire-and-forget 边界
158
+ mcp._surface_report = report_state(False, configured=True)
159
+
160
+ return asyncio.create_task(_runner())
161
+
162
+
163
+ def ensure_started(mcp, *, prefix: str = "WIRE") -> None:
164
+ """首请求触发点:此时事件循环已在跑;只触发一次;未配置置 False 封口。"""
165
+ if getattr(mcp, "_surface_task", None) is not None:
166
+ return
167
+ mcp._surface_task = start_background(mcp, prefix=prefix) or False
@@ -0,0 +1,65 @@
1
+ # FindData vocabulary — cross-layer alignment with the ontology foundation.
2
+ #
3
+ # The observation layer (this package: country/stock/GDP/…) and the platform's
4
+ # business-ontology foundation (`organization`/`person`/`place`/…) describe the
5
+ # same referents from different lifecycles. `company` here is an *object being
6
+ # observed* — it has tickers and an identifiers table; `organization` there is a
7
+ # *party to transactions* — it has customers and contracts. They must NOT be
8
+ # merged: merging forces one side to accept the other's release cycle, and both
9
+ # sides can name a counterexample.
10
+ #
11
+ # So this file declares equivalence and nothing else. It is **not** consumed by
12
+ # the vocabulary loader (whose six YAML files are pinned by golden digests and
13
+ # must not change); it is read by the platform's template importer
14
+ # (`law-bench-internal/scripts/import_protocol_ontology.py`), which turns each
15
+ # entry into an `aligned_with` block on the observation-layer template.
16
+ #
17
+ # Adding an entry here never changes an entity type, a concept, or a digest. It
18
+ # only tells a reader "these two words point at one thing".
19
+ version: "2026.11"
20
+ kind: alignment
21
+ target:
22
+ template: foundation-v1
23
+ layer: foundation
24
+ alignments:
25
+ # --- organizations ---------------------------------------------------------
26
+ - from: company
27
+ to: organization
28
+ note: >-
29
+ A listed company is an organization that is also an observed object. The
30
+ observation layer keys it by exchange-suffixed ticker; the foundation keys
31
+ it by a business identity. Same referent, two lifecycles.
32
+ - from: organization
33
+ to: organization
34
+ note: Identical word both sides; declared so the mapping is explicit, not inferred.
35
+ - from: institution
36
+ to: organization
37
+ note: Universities, hospitals, agencies — an organization with a different role.
38
+
39
+ # --- places ----------------------------------------------------------------
40
+ - from: city
41
+ to: place
42
+ note: Keyed by DCID or GeoNames id here; by admin hierarchy there.
43
+ - from: port
44
+ to: place
45
+ note: >-
46
+ A port is a place with an operational role. It stays its own observation
47
+ type (trade statistics key on it) but lands on `place` in the foundation.
48
+ - from: venue
49
+ to: place
50
+ note: Exchange venues are places in the physical sense only when they have one.
51
+
52
+ # --- people ----------------------------------------------------------------
53
+ - from: person
54
+ to: person
55
+ note: Identical word both sides.
56
+ - from: author
57
+ to: person
58
+ note: An author is a person in a role; the role is the relationship, not a type.
59
+
60
+ # Deliberately NOT aligned (recorded so a later reader does not "fix" them):
61
+ # stock / fund / bond / index / future / commodity / currency_pair
62
+ # — these are *instruments*, not organizations. `instrument` is an industry-
63
+ # layer type; the alignment belongs there, not on the foundation.
64
+ # industry / topic / policy / approval
65
+ # — classification axes with no foundation counterpart.
@@ -249,6 +249,9 @@ entries:
249
249
  - {code: trade.export_flow.de, entity_type: hs_code, measure: export, unit: usd, frequency: yearly}
250
250
  - {code: trade.export_flow.jp, entity_type: hs_code, measure: export, unit: usd, frequency: yearly}
251
251
  - {code: trade.export_flow.uk, entity_type: hs_code, measure: export, unit: usd, frequency: yearly}
252
+ # 进口侧(add-flower-vertical 3.2):与出口同形,一字之差在 measure。
253
+ # 花卉三档(060311/060319/060120)先落 world 轴;伙伴国明细不展开。
254
+ - {code: trade.import_flow.world, entity_type: hs_code, measure: import, unit: usd, frequency: yearly}
252
255
 
253
256
  - id: FxRate
254
257
  label_en: FX reference rate
@@ -289,3 +292,135 @@ entries:
289
292
  dimensions: [daily_calls]
290
293
  variables:
291
294
  - {code: port.calls, entity_type: port, measure: daily_calls, unit: count, frequency: daily}
295
+
296
+ - id: PlantedArea
297
+ label_en: Planted area
298
+ label_zh: 种植面积
299
+ description: >-
300
+ Area under cultivation for an agricultural or horticultural product, in
301
+ hectares, as a per-country cross-section per product. Source: AIPH
302
+ international statistical yearbook (area chapter). Each row carries its
303
+ own reference year (2005-2024 mixed within one workbook), so the family is
304
+ a cross-section axis, never a time series: downstream MUST surface
305
+ ``ref_year`` and MUST NOT compute growth across differing ref_years.
306
+ Total = open (in-soil) + protected (greenhouse/tunnel) where both are
307
+ disclosed; a missing component stays NULL, never 0. The product axis is
308
+ encoded in the concept code (one series per code) and the country lands
309
+ on the entity, so two products of the same country never collide.
310
+ value_type: number
311
+ unit_type: hectare
312
+ dimensions: [rose, carnation, orchid, chrysanthemum, lily, christmas_tree,
313
+ cut_foliage, flowering_plant, green_foliage_plant]
314
+ variables:
315
+ # 品类编进 concept code、国家落在 entity(同 price.food.fao.<commodity> 先例)。
316
+ # 若把品类放在 entity 侧,同一国家的玫瑰与康乃馨会撞上 uq_sem_obs
317
+ # (concept, entity, date, granularity) 主键而互相覆盖——这是本族的最小不变量。
318
+ - {code: area.flower.rose.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
319
+ - {code: area.flower.carnation.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
320
+ - {code: area.flower.orchid.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
321
+ - {code: area.flower.chrysanthemum.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
322
+ - {code: area.flower.lily.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
323
+ - {code: area.flower.christmas_tree.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
324
+ - {code: area.flower.cut_foliage.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
325
+ - {code: area.flower.flowering_plant.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
326
+ - {code: area.flower.green_foliage_plant.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
327
+ # 欧盟花卉面积(add-flower-vertical 3.3):Eurostat apro_cpsh1 的 N0000
328
+ # 「Flowers and ornamental plants (excluding nurseries)」只有 MAR_THS_HA
329
+ # (主面积·千公顷)一种口径有值(产量/单产口径查询均 0 值),入库时 ×1000
330
+ # 折成公顷,与 AIPH 的面积序列同单位可直接比对(仍分源,不混图)。
331
+ - {code: area.flower.all.planted, entity_type: country, measure: area, unit: hectare, frequency: annual}
332
+
333
+ - id: ClinicalTrial
334
+ label_en: Clinical trial activity
335
+ label_zh: 临床试验活动
336
+ description: >-
337
+ Registration activity of clinical studies, sliced by study start month.
338
+ Sourced from ClinicalTrials.gov API v2 filtered to
339
+ ``AREA[LocationCountry]China`` (spiders/clinicaltrials-cn). Only studies
340
+ whose start date falls in the month are counted, so the series answers
341
+ "how many studies started", not "how many were registered" — the latter
342
+ would need StudyFirstPostDate and is deliberately not mixed in.
343
+ Status transitions (recruiting -> completed) are state facts appended per
344
+ fact-ledger, NOT variables of this family: a status is categorical and
345
+ has no unit to aggregate.
346
+ Upstream back-fills studies with past start dates, so historical month
347
+ counts grow slowly; consumers MUST treat the series as revisable and MUST
348
+ NOT pin an equality assertion on a past month (see the unit's golden).
349
+ value_type: count
350
+ unit_type: count
351
+ dimensions: [new_study, planned_enrollment, phase_mix]
352
+ variables:
353
+ - {code: trial.new, entity_type: country, measure: count_new, unit: count, frequency: monthly}
354
+ - {code: trial.enrollment.planned, entity_type: trial, measure: planned_enrollment, unit: persons, frequency: monthly}
355
+ # 阶段构成(expand-pharma-structure-concepts):实体=阶段,一条概念就能画出分布,
356
+ # 不必为每个阶段各开一条。取值忠实保留上游的复合形态(PHASE1,PHASE2 → PHASE1_PHASE2),
357
+ # 空值与 NA 分列(UNSPECIFIED / NOT_APPLICABLE);同月各阶段之和必须等于 trial.new。
358
+ - {code: trial.new.by_phase, entity_type: trial_phase, measure: count_new, unit: count, frequency: monthly}
359
+
360
+ # 聚合度量的实体粒度:count_new / catalog_entries / class_a_share 都是「范围内该期
361
+ # 总量」,实体 = 范围(country=CN)。挂到样本实体(trial/drug)上会让同一概念在每个
362
+ # 样本上各有一条同名值,读侧无法区分总量与个体值(add-pharma-observation-extraction D1)。
363
+ # 逐实体的度量(planned_enrollment)仍用该实体自身(trial=注册号)。
364
+ - id: InsuranceCatalogEntry
365
+ label_en: Insurance drug catalog entry
366
+ label_zh: 医保目录条目
367
+ description: >-
368
+ Membership of a drug in a national medical-insurance catalog edition,
369
+ sliced by catalog year (国家基本医疗保险、生育保险和工伤保险药品目录).
370
+ Sourced from the official PDF attachment of the publishing notice
371
+ (spiders/nrdl-national-catalog). A row identifies (catalog_year, section,
372
+ item_no) plus class A/B and the 限定支付范围 clause; catalog editions are
373
+ never overwritten, so two editions both replay (fact-ledger).
374
+ Hard boundary: this family carries classification only. Payment
375
+ standards / retail prices are out of scope by user ruling, and the unit
376
+ fails if any field matches an amount pattern.
377
+ value_type: count
378
+ unit_type: count
379
+ dimensions: [entry_count, class_a_share, section_mix]
380
+ variables:
381
+ - {code: catalog.drug.entries, entity_type: country, measure: catalog_entries, unit: count, frequency: yearly}
382
+ - {code: catalog.drug.class_a_share, entity_type: country, measure: class_a_share, unit: percent, frequency: yearly}
383
+ # 分部构成(expand-pharma-structure-concepts):实体=分部(western/patent_cn/
384
+ # negotiated/herbal_slice,中文只在 name_zh)。各分部可支付条目之和必须等于
385
+ # catalog.drug.entries —— 这是分类正确性的唯一算术判据。
386
+ - {code: catalog.drug.entries.by_section, entity_type: catalog_section, measure: catalog_entries, unit: count, frequency: yearly}
387
+
388
+ # 以下三族为**声明式**(无 variables: 种子)——对应源当前不可达,播种会造出
389
+ # 没有任何源能填的 concepts 行("声明≠挂载")。载具一旦落地,再补 variables 种子。
390
+ - id: DrugApproval
391
+ label_en: Drug marketing approval
392
+ label_zh: 药品批准文号
393
+ description: >-
394
+ Declarative only: authorisations granted to drugs, keyed by 国药准字
395
+ number. The authoritative surface (NMPA 数据查询) actively blocks
396
+ automated access (412 under a real browser too), so this family is
397
+ declared for downstream derivation links without a seeded variable; see
398
+ openspec/changes/establish-pharma-domain-stack/SOURCE-FEASIBILITY.md.
399
+ Seeding unlocks when an accessible authoritative surface exists.
400
+ value_type: count
401
+ unit_type: count
402
+
403
+ - id: ReviewProgress
404
+ label_en: Regulatory review progress
405
+ label_zh: 审评进度
406
+ description: >-
407
+ Declarative only: the ordered state machine of a marketing application
408
+ keyed by acceptance number (受理号). CDE's data surfaces return 202 to
409
+ both scripts and a real browser, so no variable is seeded yet. A review
410
+ stage is a state machine, not an aggregatable measure — when seeded, the
411
+ measure is a stage-duration or a stage-reached count, never the stage
412
+ label itself.
413
+ value_type: count
414
+ unit_type: count
415
+
416
+ - id: MedicalInstitution
417
+ label_en: Medical institution directory
418
+ label_zh: 医疗机构名录
419
+ description: >-
420
+ Declarative only: the national directory of licensed hospitals, keyed by
421
+ institution code with grade and region. NHC returns 412 to automated
422
+ access, so no variable is seeded yet. Whether the directory exposes
423
+ department level is unverified (#13 in EXPECTED-SURFACE.md) and the
424
+ department surface is explicitly out of this batch.
425
+ value_type: count
426
+ unit_type: count
@@ -174,3 +174,48 @@ entries:
174
174
  Individual policy/instrument entries (customs announcements, tax
175
175
  notices) keyed by issuing-body document id. Registered incrementally
176
176
  as policy patrol output lands.
177
+ - id: drug
178
+ label_en: Drug
179
+ label_zh: 药品
180
+ description: >-
181
+ Pharmaceutical products as licensed for use — keyed by the generic name
182
+ plus dosage form (通用名+剂型, e.g. 复方硼砂/外用液体剂). Distinct from
183
+ `company` (the licence holder) and from `industry` (a classification
184
+ node): a drug is an individual regulated product. Aligns with Wikidata
185
+ drug QIDs; the approval number that authorises it lives on `approval`.
186
+ - id: approval
187
+ label_en: Marketing approval
188
+ label_zh: 药品批件
189
+ description: >-
190
+ Regulatory authorisations for a drug — keyed by the approval number
191
+ (国药准字 H20123456) or, before approval, the acceptance number
192
+ (CXHS2400001). A licence is granted, varied and withdrawn over time, so
193
+ the same drug carries many approvals; status changes are appended as new
194
+ facts rather than overwriting (fact-ledger R1). Not `organization`: the
195
+ holder is an organization, the licence is not.
196
+ - id: trial
197
+ label_en: Clinical trial
198
+ label_zh: 临床试验
199
+ description: >-
200
+ Registered clinical studies — keyed by registry number (NCT06169930,
201
+ ChiCTR2400081234, CTR20240001). Carries phase, status and enrolment as
202
+ attributes; status transitions are appended as separate facts. Registry
203
+ number namespaces differ per registry, so the registry id is part of the
204
+ key, never assumed.
205
+ - id: hospital
206
+ label_en: Medical institution
207
+ label_zh: 医疗机构
208
+ description: >-
209
+ Licensed healthcare facilities — keyed by the official institution code
210
+ (医疗机构执业许可证登记号) with name, grade (三级甲等) and region as
211
+ attributes. Not `institution` (that value is scoped to scholarly
212
+ affiliation and keyed by OpenAlex id) and not `organization` (which would
213
+ group hospitals with agencies and associations in every group-by).
214
+ - id: indication
215
+ label_en: Indication
216
+ label_zh: 适应症
217
+ description: >-
218
+ The therapeutic use a regulatory document restricts a drug to — the
219
+ parsed target of a 限定支付范围 clause (限伴有出血的胃、十二指肠溃疡).
220
+ Keyed by a normalised indication string; kept distinct from `drug` so a
221
+ restriction can be compared across drugs and catalog editions.