nvs-runtime 1.0.0__py3-none-any.whl

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 (94) hide show
  1. nvs_runtime/__init__.py +29 -0
  2. nvs_runtime/__version__.py +3 -0
  3. nvs_runtime/config/__init__.py +3 -0
  4. nvs_runtime/config/settings.py +26 -0
  5. nvs_runtime/core/__init__.py +6 -0
  6. nvs_runtime/core/clock.py +32 -0
  7. nvs_runtime/core/composition.py +92 -0
  8. nvs_runtime/core/errors.py +69 -0
  9. nvs_runtime/core/hext.py +43 -0
  10. nvs_runtime/core/models.py +151 -0
  11. nvs_runtime/core/protocols.py +77 -0
  12. nvs_runtime/core/runtime.py +373 -0
  13. nvs_runtime/events/__init__.py +4 -0
  14. nvs_runtime/events/bus.py +50 -0
  15. nvs_runtime/events/types.py +35 -0
  16. nvs_runtime/executors/__init__.py +2 -0
  17. nvs_runtime/governance/__init__.py +4 -0
  18. nvs_runtime/governance/engine.py +58 -0
  19. nvs_runtime/governance/quota.py +48 -0
  20. nvs_runtime/graph/__init__.py +3 -0
  21. nvs_runtime/graph/capability_graph.py +100 -0
  22. nvs_runtime/hidden_trajectory/__init__.py +62 -0
  23. nvs_runtime/hidden_trajectory/_gate_child.py +375 -0
  24. nvs_runtime/hidden_trajectory/adapter_loader.py +70 -0
  25. nvs_runtime/hidden_trajectory/canonical.py +22 -0
  26. nvs_runtime/hidden_trajectory/capture_archive.py +204 -0
  27. nvs_runtime/hidden_trajectory/capture_chain.py +319 -0
  28. nvs_runtime/hidden_trajectory/cli.py +765 -0
  29. nvs_runtime/hidden_trajectory/envelope.py +303 -0
  30. nvs_runtime/hidden_trajectory/formal_save.py +499 -0
  31. nvs_runtime/hidden_trajectory/formal_writer.py +590 -0
  32. nvs_runtime/hidden_trajectory/gate_client.py +460 -0
  33. nvs_runtime/hidden_trajectory/item_set.py +317 -0
  34. nvs_runtime/hidden_trajectory/k_measure.py +145 -0
  35. nvs_runtime/hidden_trajectory/model_catalog.py +56 -0
  36. nvs_runtime/hidden_trajectory/payload.py +382 -0
  37. nvs_runtime/hidden_trajectory/phase2/__init__.py +3 -0
  38. nvs_runtime/hidden_trajectory/phase2/evaluate.py +319 -0
  39. nvs_runtime/hidden_trajectory/phase2/geometry.py +80 -0
  40. nvs_runtime/hidden_trajectory/phase2/labels.py +72 -0
  41. nvs_runtime/hidden_trajectory/phase4/__init__.py +3 -0
  42. nvs_runtime/hidden_trajectory/phase4/normalize.py +171 -0
  43. nvs_runtime/hidden_trajectory/phase4/summary.py +270 -0
  44. nvs_runtime/hidden_trajectory/phase4b/__init__.py +3 -0
  45. nvs_runtime/hidden_trajectory/phase4b/load.py +46 -0
  46. nvs_runtime/hidden_trajectory/phase4b/metrics.py +96 -0
  47. nvs_runtime/hidden_trajectory/phase4b/scan.py +33 -0
  48. nvs_runtime/hidden_trajectory/record.py +334 -0
  49. nvs_runtime/hidden_trajectory/record_schema.py +781 -0
  50. nvs_runtime/hidden_trajectory/replay/__init__.py +6 -0
  51. nvs_runtime/hidden_trajectory/replay/risk_control.py +196 -0
  52. nvs_runtime/hidden_trajectory/rerun.py +302 -0
  53. nvs_runtime/hidden_trajectory/rsa/__init__.py +6 -0
  54. nvs_runtime/hidden_trajectory/rsa/analysis.py +248 -0
  55. nvs_runtime/hidden_trajectory/rsa/calibration.py +659 -0
  56. nvs_runtime/hidden_trajectory/rsa/compare.py +714 -0
  57. nvs_runtime/hidden_trajectory/rsa/readout.py +192 -0
  58. nvs_runtime/hidden_trajectory/run.py +362 -0
  59. nvs_runtime/hidden_trajectory/token_temporal.py +368 -0
  60. nvs_runtime/hidden_trajectory/window.py +344 -0
  61. nvs_runtime/integrations/__init__.py +4 -0
  62. nvs_runtime/integrations/hekb_formal.py +169 -0
  63. nvs_runtime/integrations/hekb_vnext.py +302 -0
  64. nvs_runtime/metrics/__init__.py +3 -0
  65. nvs_runtime/metrics/collector.py +63 -0
  66. nvs_runtime/observability/__init__.py +3 -0
  67. nvs_runtime/observability/store.py +44 -0
  68. nvs_runtime/planner/__init__.py +3 -0
  69. nvs_runtime/planner/planner.py +158 -0
  70. nvs_runtime/providers/__init__.py +19 -0
  71. nvs_runtime/providers/base.py +43 -0
  72. nvs_runtime/providers/edge.py +165 -0
  73. nvs_runtime/providers/grpc.py +58 -0
  74. nvs_runtime/providers/hekb.py +77 -0
  75. nvs_runtime/providers/http.py +59 -0
  76. nvs_runtime/providers/kernel.py +67 -0
  77. nvs_runtime/providers/local.py +88 -0
  78. nvs_runtime/providers/mcp.py +84 -0
  79. nvs_runtime/providers/registry.py +56 -0
  80. nvs_runtime/providers/replay.py +138 -0
  81. nvs_runtime/py.typed +0 -0
  82. nvs_runtime/security/__init__.py +4 -0
  83. nvs_runtime/security/cbac.py +106 -0
  84. nvs_runtime/security/signer.py +20 -0
  85. nvs_runtime/session/__init__.py +4 -0
  86. nvs_runtime/session/checkpoint.py +108 -0
  87. nvs_runtime/session/manager.py +149 -0
  88. nvs_runtime/transport/__init__.py +3 -0
  89. nvs_runtime/transport/memory.py +36 -0
  90. nvs_runtime-1.0.0.dist-info/METADATA +234 -0
  91. nvs_runtime-1.0.0.dist-info/RECORD +94 -0
  92. nvs_runtime-1.0.0.dist-info/WHEEL +4 -0
  93. nvs_runtime-1.0.0.dist-info/entry_points.txt +2 -0
  94. nvs_runtime-1.0.0.dist-info/licenses/LICENSE +190 -0
@@ -0,0 +1,765 @@
1
+ """The observe CLI: model selection, capture, Formal Store, then log and verify.
2
+
3
+ ``python -m nvs_runtime.hidden_trajectory.cli observe|log|verify``. Src never imports
4
+ ``sensos_inference`` (by design, no cross-imports): the Adapter and ``CaptureRequest`` are
5
+ loaded by name. Nothing here
6
+ imports mlx.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import importlib
14
+ import json
15
+ import os
16
+ import shlex
17
+ import sys
18
+ import traceback
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from datetime import datetime
21
+ from functools import cached_property
22
+ from pathlib import Path
23
+ from typing import Any, TextIO, cast
24
+
25
+ from nvs_observation.adapter_session import AdapterSession
26
+
27
+ from nvs_runtime.hidden_trajectory.adapter_loader import (
28
+ _MISSING_MESSAGE,
29
+ AdapterLoadError,
30
+ load_adapter,
31
+ )
32
+ from nvs_runtime.hidden_trajectory.envelope import EnvelopeIds
33
+ from nvs_runtime.hidden_trajectory.formal_writer import FormalWriter
34
+ from nvs_runtime.hidden_trajectory.gate_client import GateClient, GateProcess, git_head
35
+ from nvs_runtime.hidden_trajectory.model_catalog import GREEDY, MAX_TOKENS, MODELS
36
+ from nvs_runtime.hidden_trajectory.rerun import rerun_from_store
37
+
38
+ EXIT_OK = 0
39
+ EXIT_FAIL = 1
40
+ EXIT_ERROR = 2
41
+
42
+
43
+ class ObserveDoor:
44
+ """The Gate and id operations the FormalWriter needs. Thin wrap of ``GateClient``."""
45
+
46
+ def __init__(self, gate_py: Path, sensos_tools: Path) -> None:
47
+ self.gate_py = Path(gate_py)
48
+ self.sensos_tools = Path(sensos_tools)
49
+
50
+ @classmethod
51
+ def from_paths(cls, gate_py: str | Path, sensos_tools: str | Path) -> ObserveDoor:
52
+ return cls(Path(gate_py), Path(sensos_tools))
53
+
54
+ @cached_property
55
+ def client(self) -> GateClient:
56
+ return GateClient(self.gate_py, self.sensos_tools)
57
+
58
+ def call(self, request: Mapping[str, Any]) -> dict[str, Any]:
59
+ return GateProcess(self.gate_py, self.sensos_tools).call(request)
60
+
61
+ def space_id_of(self, materials: Mapping[str, Any]) -> str:
62
+ return str(self.call({"op": "hid_space_id", "materials": dict(materials)})["space_id"])
63
+
64
+ def seal(self, envelope: dict[str, Any], lookup: Mapping[str, Any]) -> dict[str, Any]:
65
+ sealed = self.call({"op": "seal", "envelope": envelope, "lookup": dict(lookup)})["envelope"]
66
+ assert isinstance(sealed, dict)
67
+ return sealed
68
+
69
+ def session_id(
70
+ self, *, spec: str, item_id: str, condition: str, replicate: int, rng_seed: int
71
+ ) -> str:
72
+ request = {"op": "session_id", "spec": spec, "item_id": item_id, "condition": condition}
73
+ return str(self.call({**request, "replicate": replicate, "rng_seed": rng_seed})["id"])
74
+
75
+ def observation_id(self, session_id: str, ordinal: int = 0) -> str:
76
+ request = {"op": "observation_id", "session_id": session_id, "ordinal": ordinal}
77
+ return str(self.call(request)["id"])
78
+
79
+ def verdict(
80
+ self,
81
+ envelope: Mapping[str, Any],
82
+ *,
83
+ lookup: Mapping[str, Any] | None = None,
84
+ stored: Mapping[str, Any] | None = None,
85
+ blobs: Mapping[str, bytes] | None = None,
86
+ contract_facts: Mapping[str, Any] | None = None,
87
+ ) -> Mapping[str, Any]:
88
+ return self.client.verdict(
89
+ envelope, lookup=lookup, stored=stored, blobs=blobs, contract_facts=contract_facts
90
+ )
91
+
92
+
93
+ _DEFAULT_PROG = "python -m nvs_runtime.hidden_trajectory.cli"
94
+
95
+
96
+ def display_path(path: Path) -> str:
97
+ """Printable dest: home as ``~``, otherwise the absolute path. Copyable from any cwd."""
98
+ resolved = path.expanduser().resolve()
99
+ try:
100
+ relative = resolved.relative_to(Path.home().resolve())
101
+ except ValueError:
102
+ return resolved.as_posix()
103
+ posix = relative.as_posix()
104
+ return "~" if posix == "." else f"~/{posix}"
105
+
106
+
107
+ def _shell_display(shown: str) -> str:
108
+ """Quote a printable path so it pastes into a shell. Spaces only.
109
+
110
+ A leading ``~`` is left as-is when there is no space (the shell expands it).
111
+ Quoted ``~`` does not expand, so a tilde path with a space becomes ``"$HOME/..."``.
112
+ """
113
+ if shown.startswith("~"):
114
+ if " " not in shown and "\t" not in shown:
115
+ return shown
116
+ return '"$HOME' + shown[1:] + '"'
117
+ if " " in shown or "\t" in shown:
118
+ return shlex.quote(shown)
119
+ return shown
120
+
121
+
122
+ def _cli_prog() -> str:
123
+ raw = os.environ.get("SENSOS_PROG")
124
+ if not raw:
125
+ return _DEFAULT_PROG
126
+ return _shell_display(display_path(Path(raw)))
127
+
128
+
129
+ def _next_line(verb: str, data_dir: Path) -> str:
130
+ return f"next: {_cli_prog()} {verb} --data-dir {_shell_display(display_path(data_dir))}\n"
131
+
132
+
133
+ def _home_as_tilde(text: str) -> str:
134
+ home = str(Path.home().resolve())
135
+ if text == home:
136
+ return "~"
137
+ return text.replace(home + "/", "~/").replace(home, "~")
138
+
139
+
140
+ def _cli_error(error: BaseException) -> str:
141
+ """One line: the type and the message. Home as ``~``. No traceback."""
142
+ name = type(error).__name__
143
+ detail = str(error).strip()
144
+ if detail:
145
+ detail = _home_as_tilde(detail.splitlines()[0].strip())
146
+ if not detail or detail == name:
147
+ return f"error: {name}\n"
148
+ return f"error: {name}: {detail}\n"
149
+
150
+
151
+ def _emit_error(stream: TextIO, error: BaseException, ns: Any) -> None:
152
+ stream.write(_cli_error(error))
153
+ if getattr(ns, "debug", False):
154
+ traceback.print_exc(file=sys.stderr)
155
+
156
+
157
+ _HEKB_PACKAGES = ("graph", "vendor")
158
+
159
+
160
+ def _is_under(place: str, root: Path) -> bool:
161
+ try:
162
+ return Path(place).resolve().is_relative_to(root)
163
+ except (OSError, ValueError):
164
+ return False
165
+
166
+
167
+ def _drop_foreign_hekb_modules(root: Path) -> None:
168
+ """Forget ``graph`` / ``vendor`` loaded from somewhere other than ``root`` (cwd included)."""
169
+ for name in list(sys.modules):
170
+ if name.split(".")[0] not in _HEKB_PACKAGES:
171
+ continue
172
+ module = sys.modules[name]
173
+ file = getattr(module, "__file__", None) or ""
174
+ paths = [str(p) for p in getattr(module, "__path__", [])]
175
+ places = [p for p in (file, *paths) if p]
176
+ if not places or not any(_is_under(p, root) for p in places):
177
+ del sys.modules[name]
178
+
179
+
180
+ def _is_cwd_path_entry(entry: str, cwd: Path | None = None) -> bool:
181
+ if entry in ("", "."):
182
+ return True
183
+ here = cwd if cwd is not None else Path.cwd().resolve()
184
+ try:
185
+ return Path(entry).resolve() == here
186
+ except (OSError, ValueError):
187
+ return False
188
+
189
+
190
+ def _drop_cwd_from_sys_path() -> None:
191
+ """Same effect as ``python -P``: cwd is not searched for later imports."""
192
+ cwd = Path.cwd().resolve()
193
+ sys.path[:] = [p for p in sys.path if not _is_cwd_path_entry(p, cwd)]
194
+
195
+
196
+ def _has_namespace_hekb(entry: str) -> bool:
197
+ """True if this path holds ``graph`` or ``vendor`` as a namespace package (no
198
+ ``__init__.py``)."""
199
+ try:
200
+ base = Path(entry)
201
+ for name in _HEKB_PACKAGES:
202
+ folder = base / name
203
+ if folder.is_dir() and not (folder / "__init__.py").is_file():
204
+ return True
205
+ except OSError:
206
+ return False
207
+ return False
208
+
209
+
210
+ def _path_for_hekb_import(saved: list[str], root: Path) -> list[str]:
211
+ """``root`` first; drop cwd and namespace ``graph`` / ``vendor`` paths. Keep site-packages."""
212
+ root_text = str(root)
213
+ cwd = Path.cwd().resolve()
214
+ out = [root_text]
215
+ for entry in saved:
216
+ if entry == root_text:
217
+ continue
218
+ if _is_cwd_path_entry(entry, cwd):
219
+ continue
220
+ try:
221
+ if Path(entry).resolve() == root:
222
+ continue
223
+ except (OSError, ValueError):
224
+ pass
225
+ if _has_namespace_hekb(entry):
226
+ continue
227
+ out.append(entry)
228
+ return out
229
+
230
+
231
+ def _now() -> datetime:
232
+ return datetime.now().astimezone().replace(microsecond=0)
233
+
234
+
235
+ def _run_id(model: str, clock: datetime) -> str:
236
+ return f"{model}-{clock.strftime('%Y%m%d-%H%M%S')}"
237
+
238
+
239
+ def _item_id_for_prompt(prompt: str) -> str:
240
+ """First 16 hex digits of the prompt sha256. The prompt text is not kept."""
241
+ return hashlib.sha256(prompt.encode("utf-8")).hexdigest()[:16]
242
+
243
+
244
+ def _run_spec_hash(spec: Mapping[str, Any], max_tokens: int) -> str:
245
+ """sha256 of the run settings as sorted JSON with no spaces (64 hex digits)."""
246
+ payload = {
247
+ "build_id": spec["build_id"],
248
+ "max_tokens": max_tokens,
249
+ "points": list(spec["points"]),
250
+ "sampling": {"seed": GREEDY["seed"], "top_k": GREEDY["top_k"]},
251
+ }
252
+ text = json.dumps(payload, separators=(",", ":"), sort_keys=True)
253
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
254
+
255
+
256
+ def _replicate_value(raw: str) -> int:
257
+ try:
258
+ value = int(raw)
259
+ except ValueError as error:
260
+ raise argparse.ArgumentTypeError("replicate must be an integer >= 0") from error
261
+ if value < 0:
262
+ raise argparse.ArgumentTypeError("replicate must be an integer >= 0")
263
+ return value
264
+
265
+
266
+ def _read_prompt(text: str | None, path: str | None) -> str:
267
+ if text is not None and path is not None:
268
+ raise ValueError("give --prompt or --prompt-file, not both")
269
+ if path is not None:
270
+ return Path(path).read_text(encoding="utf-8")
271
+ if text is None:
272
+ raise ValueError("give --prompt or --prompt-file")
273
+ return text
274
+
275
+
276
+ def missing_observe(ns: argparse.Namespace) -> list[str]:
277
+ """What observe still needs, before any Adapter or model is loaded."""
278
+ missing: list[str] = []
279
+ if ns.model not in MODELS:
280
+ missing.append(f"--model {ns.model!r} is not llama31 or qwen35")
281
+ return missing
282
+ spec = MODELS[ns.model]
283
+ if not ns.prompt and not ns.prompt_file:
284
+ missing.append("--prompt or --prompt-file")
285
+ if ns.prompt and ns.prompt_file:
286
+ missing.append("give only one of --prompt and --prompt-file")
287
+ if ns.prompt_file and not Path(ns.prompt_file).is_file():
288
+ missing.append(f"--prompt-file is not a file ({display_path(Path(ns.prompt_file))})")
289
+ snapshot = ns.snapshot or os.environ.get(str(spec["snapshot_env"]))
290
+ if not snapshot:
291
+ missing.append(f"--snapshot or {spec['snapshot_env']}")
292
+ elif not Path(snapshot).is_dir():
293
+ missing.append("--snapshot is not a directory")
294
+ gate_py = ns.gate_python or os.environ.get("GATE_PY")
295
+ if not gate_py:
296
+ missing.append("--gate-python or GATE_PY")
297
+ elif not Path(gate_py).is_file():
298
+ missing.append("GATE_PY is not a file")
299
+ tools = ns.sensos_tools or os.environ.get("SENSOS_TOOLS")
300
+ if not tools:
301
+ missing.append("--sensos-tools or SENSOS_TOOLS")
302
+ elif not (Path(tools) / "contracts" / "gate_nvs.py").is_file():
303
+ missing.append("SENSOS_TOOLS has no contracts/gate_nvs.py")
304
+ hekb = ns.hekb_root or os.environ.get("HEKB_FORMAL_ROOT")
305
+ if not hekb:
306
+ missing.append("--hekb-root or HEKB_FORMAL_ROOT")
307
+ elif not (Path(hekb) / "graph" / "formal.py").is_file():
308
+ missing.append("HEKB_FORMAL_ROOT has no graph/formal.py")
309
+ return missing
310
+
311
+
312
+ def _capture_request(
313
+ spec: Mapping[str, Any],
314
+ max_tokens: int,
315
+ import_module: Callable[[str], Any] = importlib.import_module,
316
+ ) -> Any:
317
+ try:
318
+ observation = import_module("sensos_inference.observation")
319
+ except ModuleNotFoundError as error:
320
+ raise AdapterLoadError(_MISSING_MESSAGE) from error
321
+ return observation.CaptureRequest(
322
+ points=tuple(spec["points"]), max_tokens=max_tokens, sampling=dict(GREEDY)
323
+ )
324
+
325
+
326
+ def _declaration(door: Any, hekb_root: str, created_by: str = "sensos-observe") -> dict[str, Any]:
327
+ catalog = door.client.process.call({"op": "catalog"})
328
+ tools_parent = Path(getattr(door, "sensos_tools", hekb_root)).resolve().parent
329
+ version = git_head(tools_parent) or "unknown"
330
+ root = Path(hekb_root).resolve()
331
+ _drop_foreign_hekb_modules(root)
332
+ sys.path[:] = _path_for_hekb_import(list(sys.path), root)
333
+ formal = importlib.import_module("graph.formal")
334
+ declaration: dict[str, Any] = formal.formal_declaration(
335
+ catalog_rows=catalog["rows"], catalog_version=version, created_by=created_by
336
+ )
337
+ return declaration
338
+
339
+
340
+ _MEANING_SCHEMAS: tuple[dict[str, str], ...] = (
341
+ {"id": "nvs.token-temporal", "version": "0.1.0"},
342
+ {"id": "nvs.meaning-frame", "version": "0.1.0"},
343
+ {"id": "nvs.meaning-measurement", "version": "0.1.0"},
344
+ )
345
+ _FRAME_NOT_SUPPLIED: dict[str, str] = {
346
+ "check": "frame_binding",
347
+ "reason": "frame_not_supplied",
348
+ }
349
+
350
+
351
+ def meaning_declaration(
352
+ door: Any, hekb_root: str, created_by: str = "sensos-observe"
353
+ ) -> dict[str, Any]:
354
+ """A Formal Store declaration that accepts a meaning measurement and its frame.
355
+
356
+ ``catalog_rows`` are the live catalogue of the Gate child. ``catalog_version`` is the
357
+ full commit of the sensos checkout that child reads. ``_declaration`` is unchanged and
358
+ still uses the four default schemas.
359
+ """
360
+ catalog = door.client.process.call({"op": "catalog"})
361
+ tools = getattr(door, "sensos_tools", None)
362
+ if not isinstance(tools, str) or not tools:
363
+ raise RuntimeError("sensos tools path is missing; catalog_version cannot be read")
364
+ version = git_head(Path(tools).resolve().parent)
365
+ if version is None:
366
+ raise RuntimeError("sensos HEAD is not a full commit; catalog_version cannot be unknown")
367
+ root = Path(hekb_root).resolve()
368
+ _drop_foreign_hekb_modules(root)
369
+ sys.path[:] = _path_for_hekb_import(list(sys.path), root)
370
+ formal = importlib.import_module("graph.formal")
371
+ schemas = [dict(item) for item in formal.DEFAULT_PAYLOAD_SCHEMAS]
372
+ schemas.extend(dict(item) for item in _MEANING_SCHEMAS)
373
+ allow = [dict(item) for item in formal.DEFAULT_ALLOW_UNVERIFIED]
374
+ allow.append(dict(_FRAME_NOT_SUPPLIED))
375
+ declaration: dict[str, Any] = formal.formal_declaration(
376
+ catalog_rows=catalog["rows"],
377
+ catalog_version=version,
378
+ created_by=created_by,
379
+ accepted_payload_schemas=schemas,
380
+ allow_unverified=allow,
381
+ )
382
+ return declaration
383
+
384
+
385
+ def _gate_rows(record: Mapping[str, Any]) -> list[tuple[str, str, str]]:
386
+ rows: list[tuple[str, str, str]] = []
387
+ for point, entry in (record.get("positions") or {}).items():
388
+ gate = entry.get("gate") if isinstance(entry, dict) else None
389
+ status = str((gate or {}).get("status") or "not_called")
390
+ reason = ""
391
+ if isinstance(gate, dict):
392
+ violations = gate.get("violations") or []
393
+ if violations and isinstance(violations[0], dict):
394
+ reason = str(violations[0].get("message") or violations[0].get("code") or "")
395
+ rows.append((str(point), status, reason))
396
+ return rows
397
+
398
+
399
+ def _k_sha(record: Mapping[str, Any]) -> dict[str, str | None]:
400
+ out: dict[str, str | None] = {}
401
+ for point, entry in (record.get("positions") or {}).items():
402
+ k = entry.get("k_path") if isinstance(entry, dict) else None
403
+ if isinstance(k, dict):
404
+ out[str(point)] = k.get("causal_log_sha256")
405
+ else:
406
+ out[str(point)] = None
407
+ return out
408
+
409
+
410
+ _EMPTY_CAUSAL_LINE = "causal log: empty (this build records no causal log)\n"
411
+
412
+
413
+ def _causal_blob_is_empty(blob: bytes) -> bool:
414
+ """True when the stored causal log is ``[]`` or every entry is ``{}``."""
415
+ try:
416
+ entries = json.loads(blob)
417
+ except (json.JSONDecodeError, UnicodeError):
418
+ return False
419
+ if not isinstance(entries, list):
420
+ return False
421
+ return all(entry == {} for entry in entries)
422
+
423
+
424
+ def _observation_causal_blobs(got: Mapping[str, Any]) -> list[bytes]:
425
+ """The saved causal blobs of one observation (``FormalWriter.observation``)."""
426
+ blobs: list[bytes] = []
427
+ for item in (got.get("positions") or {}).values():
428
+ held = item.get("k") if isinstance(item, dict) else None
429
+ if not isinstance(held, dict):
430
+ continue
431
+ blob = held.get("causal_log")
432
+ if isinstance(blob, (bytes, bytearray)) and blob:
433
+ blobs.append(bytes(blob))
434
+ return blobs
435
+
436
+
437
+ def _empty_causal_line(blobs: Sequence[bytes]) -> str:
438
+ """One line when every saved causal log is empty; nothing otherwise."""
439
+ if blobs and all(_causal_blob_is_empty(blob) for blob in blobs):
440
+ return _EMPTY_CAUSAL_LINE
441
+ return ""
442
+
443
+
444
+ def cmd_observe(
445
+ ns: argparse.Namespace,
446
+ *,
447
+ adapter: Any = None,
448
+ door: Any = None,
449
+ declaration: Mapping[str, Any] | None = None,
450
+ writer_factory: Callable[..., FormalWriter] | None = None,
451
+ request: Any = None,
452
+ clock: Callable[[], datetime] | None = None,
453
+ import_module: Callable[[str], Any] = importlib.import_module,
454
+ out: TextIO | None = None,
455
+ ) -> int:
456
+ """Run one capture into a new Formal Store. 0 all Gate PASS, 1 a FAIL, 2 an error."""
457
+ stream = out or sys.stdout
458
+ missing = missing_observe(ns)
459
+ if missing:
460
+ stream.write("missing:\n")
461
+ for item in missing:
462
+ stream.write(f" {item}\n")
463
+ return EXIT_ERROR
464
+ spec = MODELS[ns.model]
465
+ try:
466
+ prompt = _read_prompt(ns.prompt, ns.prompt_file)
467
+ except (OSError, ValueError) as error:
468
+ stream.write(f"error: {error}\n")
469
+ return EXIT_ERROR
470
+ messages = [{"role": "user", "content": prompt}]
471
+ snapshot = Path(ns.snapshot or os.environ[str(spec["snapshot_env"])])
472
+ gate_py = ns.gate_python or os.environ["GATE_PY"]
473
+ tools = ns.sensos_tools or os.environ["SENSOS_TOOLS"]
474
+ hekb = ns.hekb_root or os.environ["HEKB_FORMAL_ROOT"]
475
+ tick = clock or _now
476
+ started = tick()
477
+ run_id = _run_id(ns.model, started)
478
+ data_dir = Path(ns.out) if ns.out else Path("sensos-runs") / run_id
479
+ empty_causal = ""
480
+ try:
481
+ data_dir.mkdir(parents=True, exist_ok=False)
482
+ except FileExistsError:
483
+ stream.write(f"error: output already exists ({display_path(data_dir)})\n")
484
+ return EXIT_ERROR
485
+ except OSError as error:
486
+ stream.write(f"error: cannot create output ({type(error).__name__}: {error})\n")
487
+ return EXIT_ERROR
488
+ try:
489
+ if adapter is None:
490
+ adapter = load_adapter(spec, snapshot, import_module=import_module)
491
+ if request is None:
492
+ request = _capture_request(spec, ns.max_tokens, import_module=import_module)
493
+ if door is None:
494
+ door = ObserveDoor.from_paths(gate_py, tools)
495
+ produced_at = started.strftime("%Y-%m-%dT%H:%M:%SZ")
496
+ session_id = door.session_id(
497
+ spec=_run_spec_hash(spec, ns.max_tokens),
498
+ item_id=_item_id_for_prompt(prompt),
499
+ condition="run",
500
+ replicate=int(getattr(ns, "replicate", 0)),
501
+ rng_seed=0,
502
+ )
503
+ observation_id = door.observation_id(session_id, 0)
504
+ sequence = iter(range(1, 10**6))
505
+ ids = EnvelopeIds(session_id, observation_id, produced_at, lambda: next(sequence))
506
+ captured = AdapterSession(adapter).capture_with_origin(
507
+ messages,
508
+ request,
509
+ model_build_id=str(spec["build_id"]),
510
+ compute_environment=str(spec["compute"]),
511
+ )
512
+ decl = declaration if declaration is not None else _declaration(door, hekb)
513
+ factory = writer_factory or FormalWriter.create
514
+ writer = factory(
515
+ data_dir,
516
+ decl,
517
+ hekb_vnext_root=hekb,
518
+ gate=door.verdict,
519
+ space_id_of=door.space_id_of,
520
+ seal=door.seal,
521
+ checker_bundle=door.client.checker_bundle,
522
+ clock=lambda: started,
523
+ k_path=True,
524
+ )
525
+ try:
526
+ saved = writer.save(
527
+ captured, contract_session_id=f"observe-{ns.model}", synthetic=False, ids=ids
528
+ )
529
+ empty_causal = _empty_causal_line(
530
+ _observation_causal_blobs(
531
+ writer.observation(str(saved.record.get("observation_id")))
532
+ )
533
+ )
534
+ finally:
535
+ writer.close()
536
+ except AdapterLoadError as error:
537
+ stream.write(f"error: {error}\n")
538
+ if getattr(ns, "debug", False):
539
+ traceback.print_exc(file=sys.stderr)
540
+ return EXIT_ERROR
541
+ except Exception as error: # noqa: BLE001 -- the CLI turns any failure into exit 2
542
+ _emit_error(stream, error, ns)
543
+ return EXIT_ERROR
544
+ record = saved.record
545
+ gates = _gate_rows(record)
546
+ k_sha = _k_sha(record)
547
+ failed = [point for point, status, _reason in gates if status == "FAIL"]
548
+ stream.write(f"run_id: {run_id}\n")
549
+ stream.write(f"out: {display_path(data_dir)}\n")
550
+ stream.write(f"observation_id: {record.get('observation_id')}\n")
551
+ for point, status, _reason in gates:
552
+ stream.write(f"gate {point}: {status}\n")
553
+ for point, digest in k_sha.items():
554
+ stream.write(f"k {point}: {digest or 'none'}\n")
555
+ if empty_causal:
556
+ stream.write(empty_causal)
557
+ stream.write(_next_line("log", data_dir))
558
+ stream.write(_next_line("verify", data_dir))
559
+ return EXIT_FAIL if failed else EXIT_OK
560
+
561
+
562
+ def _log_body(got: Mapping[str, Any], records: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
563
+ record = got.get("record") or {}
564
+ capture = record.get("capture") or {}
565
+ gates = _gate_rows(record) if record else []
566
+ k_sha = _k_sha(record) if record else {}
567
+ ports: dict[str, Any] = {}
568
+ for point, entry in (record.get("positions") or {}).items():
569
+ k = entry.get("k_path") if isinstance(entry, dict) else None
570
+ if isinstance(k, dict):
571
+ ports[str(point)] = {
572
+ "status": k.get("status"),
573
+ "n_records": k.get("n_records"),
574
+ "integrity": (k.get("integrity") or {}).get("chain_and_crc"),
575
+ }
576
+ return {
577
+ "observation_id": got.get("observation_id"),
578
+ "model_build_id": capture.get("model_build_id"),
579
+ "adapter": capture.get("adapter"),
580
+ "points": capture.get("points"),
581
+ "n_in": capture.get("n_in"),
582
+ "n_gen": capture.get("n_gen"),
583
+ "finish_reason": capture.get("finish_reason"),
584
+ "gate": [{"point": p, "status": s, "reason": r} for p, s, r in gates],
585
+ "k_sha256": k_sha,
586
+ "ports": ports,
587
+ "records": len(records),
588
+ "missing": list(got.get("missing") or []),
589
+ }
590
+
591
+
592
+ def cmd_log(
593
+ ns: argparse.Namespace,
594
+ *,
595
+ writer: FormalWriter | None = None,
596
+ out: TextIO | None = None,
597
+ ) -> int:
598
+ stream = out or sys.stdout
599
+ data_dir = Path(ns.data_dir)
600
+ if not data_dir.is_dir():
601
+ stream.write("error: --data-dir is not a directory\n")
602
+ return EXIT_ERROR
603
+ hekb = getattr(ns, "hekb_root", None) or os.environ.get("HEKB_FORMAL_ROOT")
604
+ if writer is None and not hekb:
605
+ stream.write("missing:\n --hekb-root or HEKB_FORMAL_ROOT\n")
606
+ return EXIT_ERROR
607
+ try:
608
+ opened = writer or FormalWriter.open(
609
+ data_dir, hekb_vnext_root=cast(str | os.PathLike[str], hekb)
610
+ )
611
+ try:
612
+ records = opened.records()
613
+ if not records:
614
+ stream.write("error: no capture records\n")
615
+ return EXIT_ERROR
616
+ observation_id = ns.observation or records[-1]["observation_id"]
617
+ got = opened.observation(observation_id)
618
+ finally:
619
+ if writer is None:
620
+ opened.close()
621
+ except Exception as error: # noqa: BLE001
622
+ _emit_error(stream, error, ns)
623
+ return EXIT_ERROR
624
+ body = _log_body(got, records)
625
+ if ns.json:
626
+ stream.write(json.dumps(body, indent=2, sort_keys=True) + "\n")
627
+ return EXIT_OK
628
+ stream.write(f"observation_id: {body['observation_id']}\n")
629
+ stream.write(f"model: {body['model_build_id']}\n")
630
+ stream.write(f"adapter: {body['adapter']}\n")
631
+ stream.write(f"points: {', '.join(body['points'] or [])}\n")
632
+ stream.write(
633
+ f"tokens: n_in={body['n_in']} n_gen={body['n_gen']} finish={body['finish_reason']}\n"
634
+ )
635
+ for row in body["gate"]:
636
+ extra = f" ({row['reason']})" if row["reason"] else ""
637
+ stream.write(f"gate {row['point']}: {row['status']}{extra}\n")
638
+ for point, digest in (body["k_sha256"] or {}).items():
639
+ stream.write(f"k {point}: {digest or 'none'}\n")
640
+ empty_causal = _empty_causal_line(_observation_causal_blobs(got))
641
+ if empty_causal:
642
+ stream.write(empty_causal)
643
+ for point, ports in (body["ports"] or {}).items():
644
+ stream.write(
645
+ f"ports {point}: status={ports['status']} n={ports['n_records']} "
646
+ f"chain={ports['integrity']}\n"
647
+ )
648
+ stream.write(f"records.jsonl: {body['records']} record(s)\n")
649
+ return EXIT_OK
650
+
651
+
652
+ def cmd_verify(
653
+ ns: argparse.Namespace,
654
+ *,
655
+ rerun: Callable[..., dict[str, Any]] = rerun_from_store,
656
+ writer: FormalWriter | None = None,
657
+ out: TextIO | None = None,
658
+ ) -> int:
659
+ stream = out or sys.stdout
660
+ data_dir = Path(ns.data_dir)
661
+ if not data_dir.is_dir():
662
+ stream.write("error: --data-dir is not a directory\n")
663
+ return EXIT_ERROR
664
+ try:
665
+ report = rerun(data_dir, rerun_k=bool(ns.rerun_k))
666
+ except Exception as error: # noqa: BLE001
667
+ _emit_error(stream, error, ns)
668
+ return EXIT_ERROR
669
+ items: list[tuple[str, str]] = []
670
+ items.append(("archive", "PASS" if report.get("ok") else "FAIL"))
671
+ hekb = getattr(ns, "hekb_root", None) or os.environ.get("HEKB_FORMAL_ROOT")
672
+ gate_fail = False
673
+ try:
674
+ if writer is not None or hekb:
675
+ opened = writer or FormalWriter.open(
676
+ data_dir, hekb_vnext_root=cast(str | os.PathLike[str], hekb)
677
+ )
678
+ try:
679
+ for record in opened.records():
680
+ for point, status, _reason in _gate_rows(record):
681
+ items.append((f"gate {point}", status))
682
+ if status == "FAIL":
683
+ gate_fail = True
684
+ for point, entry in (record.get("positions") or {}).items():
685
+ k = entry.get("k_path") if isinstance(entry, dict) else None
686
+ if isinstance(k, dict) and k.get("status") == "measured":
687
+ items.append((f"k {point}", "PASS"))
688
+ finally:
689
+ if writer is None:
690
+ opened.close()
691
+ except Exception as error: # noqa: BLE001
692
+ _emit_error(stream, error, ns)
693
+ return EXIT_ERROR
694
+ if ns.rerun_k:
695
+ for capture in report.get("captures") or []:
696
+ k_report = capture.get("k") or {}
697
+ for point, info in k_report.items():
698
+ if isinstance(info, dict) and "rerun_k" in info:
699
+ same = bool((info.get("rerun_k") or {}).get("same_as_stored"))
700
+ items.append((f"rerun_k {point}", "PASS" if same else "FAIL"))
701
+ for name, status in items:
702
+ stream.write(f"{name}: {status}\n")
703
+ unchecked = int(report.get("k_unchecked") or 0)
704
+ if unchecked >= 1:
705
+ stream.write(f"K: {unchecked} 位置は検査していません(Developer Tools が入っていません)\n")
706
+ failed = [name for name, status in items if status == "FAIL"]
707
+ if not report.get("ok") or gate_fail or failed:
708
+ return EXIT_FAIL
709
+ return EXIT_OK
710
+
711
+
712
+ def _parser() -> argparse.ArgumentParser:
713
+ parser = argparse.ArgumentParser(
714
+ prog="python -m nvs_runtime.hidden_trajectory.cli",
715
+ description="Observe a model, then read and verify the stored run.",
716
+ )
717
+ sub = parser.add_subparsers(dest="command", required=True)
718
+
719
+ observe = sub.add_parser("observe", help="capture, Gate, Formal Store, path K")
720
+ observe.add_argument("--model", required=True, choices=sorted(MODELS))
721
+ observe.add_argument("--snapshot", default=None)
722
+ observe.add_argument("--prompt", default=None)
723
+ observe.add_argument("--prompt-file", default=None)
724
+ observe.add_argument("--out", default=None)
725
+ observe.add_argument("--max-tokens", type=int, default=MAX_TOKENS)
726
+ observe.add_argument("--gate-python", default=None)
727
+ observe.add_argument("--sensos-tools", default=None)
728
+ observe.add_argument("--hekb-root", default=None)
729
+ observe.add_argument("--replicate", type=_replicate_value, default=0)
730
+ observe.add_argument("--debug", action="store_true")
731
+
732
+ log = sub.add_parser("log", help="read a stored observation")
733
+ log.add_argument("--data-dir", required=True)
734
+ log.add_argument("--observation", default=None)
735
+ log.add_argument("--json", action="store_true")
736
+ log.add_argument("--hekb-root", default=None)
737
+ log.add_argument("--debug", action="store_true")
738
+
739
+ verify = sub.add_parser("verify", help="check a stored run from its archive")
740
+ verify.add_argument("--data-dir", required=True)
741
+ verify.add_argument("--rerun-k", action="store_true")
742
+ verify.add_argument("--hekb-root", default=None)
743
+ verify.add_argument("--debug", action="store_true")
744
+ return parser
745
+
746
+
747
+ def main(argv: Sequence[str] | None = None) -> int:
748
+ _drop_cwd_from_sys_path()
749
+ parser = _parser()
750
+ ns = parser.parse_args(argv)
751
+ if ns.command == "observe":
752
+ return cmd_observe(ns)
753
+ if ns.command == "log":
754
+ return cmd_log(ns)
755
+ if ns.command == "verify":
756
+ return cmd_verify(ns)
757
+ return EXIT_ERROR
758
+
759
+
760
+ def entry() -> None:
761
+ raise SystemExit(main())
762
+
763
+
764
+ if __name__ == "__main__":
765
+ entry()