chap-analytics 0.2.2__tar.gz → 0.2.4__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 (63) hide show
  1. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/CHANGELOG.md +26 -0
  2. {chap_analytics-0.2.2/chap_analytics.egg-info → chap_analytics-0.2.4}/PKG-INFO +1 -1
  3. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/__init__.py +1 -1
  4. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_patch.py +24 -1
  5. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/briefs.py +1 -1
  6. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/charts.py +2 -1
  7. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/load.py +56 -24
  8. {chap_analytics-0.2.2 → chap_analytics-0.2.4/chap_analytics.egg-info}/PKG-INFO +1 -1
  9. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/examples/chap_analytics_walkthrough.ipynb +1 -1
  10. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/pyproject.toml +1 -1
  11. chap_analytics-0.2.4/tests/test_typescript_store.py +135 -0
  12. chap_analytics-0.2.2/tests/test_typescript_store.py +0 -60
  13. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/LICENSE +0 -0
  14. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/MANIFEST.in +0 -0
  15. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/README.md +0 -0
  16. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_report/report.css +0 -0
  17. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_report/report.html +0 -0
  18. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_report/report.js +0 -0
  19. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_report/stats.js +0 -0
  20. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/LICENSE.vega +0 -0
  21. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/LICENSE.vega-embed +0 -0
  22. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/LICENSE.vega-lite +0 -0
  23. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/README.md +0 -0
  24. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/render.js +0 -0
  25. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/vega-embed.min.js +0 -0
  26. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/vega-lite.min.js +0 -0
  27. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/_vendor/vega.min.js +0 -0
  28. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/export.py +0 -0
  29. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/frames.py +0 -0
  30. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/graph.py +0 -0
  31. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/models.py +0 -0
  32. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/py.typed +0 -0
  33. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/report.py +0 -0
  34. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/sample.py +0 -0
  35. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/schema.py +0 -0
  36. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/stats.py +0 -0
  37. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics/watch.py +0 -0
  38. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics.egg-info/SOURCES.txt +0 -0
  39. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics.egg-info/dependency_links.txt +0 -0
  40. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics.egg-info/requires.txt +0 -0
  41. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/chap_analytics.egg-info/top_level.txt +0 -0
  42. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/examples/build_notebook.py +0 -0
  43. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/examples/support_desk.py +0 -0
  44. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/setup.cfg +0 -0
  45. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/conftest.py +0 -0
  46. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/js_stats_runner.js +0 -0
  47. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_charts_and_briefs.py +0 -0
  48. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_differential.py +0 -0
  49. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_example.py +0 -0
  50. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_from_url_scheme.py +0 -0
  51. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_graph.py +0 -0
  52. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_handoff_and_routing.py +0 -0
  53. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_identity.py +0 -0
  54. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_notebook.py +0 -0
  55. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_projection.py +0 -0
  56. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_redaction_and_malformed.py +0 -0
  57. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_refusals.py +0 -0
  58. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_report.py +0 -0
  59. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_review_passes.py +0 -0
  60. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_sample_and_export.py +0 -0
  61. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_stats.py +0 -0
  62. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_successors.py +0 -0
  63. {chap_analytics-0.2.2 → chap_analytics-0.2.4}/tests/test_watch_export_models.py +0 -0
@@ -4,6 +4,32 @@
4
4
  so a protocol release moves the coordinator packages together and leaves this
5
5
  one where it is until the tables or the analyses change.
6
6
 
7
+ ## 0.2.4
8
+
9
+ ### Fixed
10
+
11
+ - **A patch `test` that compares a boolean with a number.** `chap-analytics`
12
+ applies each override's patch to rebuild the corrected artefact, and the
13
+ patch's `test` operation counted `true` as equal to `1` and `false` as
14
+ equal to `0`, as Python does. It now tells a boolean from a number, as
15
+ RFC 6902 and both coordinators do.
16
+ - **What a lapse rate says.** The whispers chart and brief read a high lapse
17
+ rate as a reviewer who is away from the desk. A lapse records only that
18
+ no answer arrived before the lapse check ran. The chart now points at
19
+ questions the task input should have answered and at questions that reach
20
+ no one in time, and the brief suggests checking that the questions reach
21
+ the people asked.
22
+
23
+ ## 0.2.3
24
+
25
+ Reads the store of `chap-coordinator` 0.3.2 and later.
26
+
27
+ ### Fixed
28
+
29
+ - **The 0.3.2 store.** `from_sqlite` reads the tables `chap-coordinator`
30
+ 0.3.2 and later write, one row for each audit entry and each object. A
31
+ file an earlier release wrote reads as before.
32
+
7
33
  ## 0.2.2
8
34
 
9
35
  Reads the store of the TypeScript coordinator, which the Node templates of
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chap-analytics
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: The record of a collaboration between people and agents, measured and drawn: a CHAP audit chain as documented tables, statistics with their intervals, graphs, charts, briefs and a self-contained interactive report
5
5
  Author-email: Brightbeam AI <oss@brightbeam.com>
6
6
  License-Expression: Apache-2.0
@@ -41,7 +41,7 @@ The layers, bottom up:
41
41
  """
42
42
  from __future__ import annotations
43
43
 
44
- __version__ = "0.2.2"
44
+ __version__ = "0.2.4"
45
45
 
46
46
  from . import briefs, charts, export, graph, models, sample, stats, watch # noqa: E402
47
47
  from .frames import Frames, frames # noqa: E402
@@ -100,6 +100,29 @@ def _get(doc: Any, path: str) -> Any:
100
100
  return parent[key]
101
101
 
102
102
 
103
+ def _json_equal(a: Any, b: Any) -> bool:
104
+ """JSON-type-aware deep equality for the RFC 6902 ``test`` operation.
105
+
106
+ Python's ``==`` treats ``True == 1`` and ``False == 0`` as equal because
107
+ ``bool`` is a subclass of ``int``. JSON distinguishes them: ``true`` is a
108
+ boolean, ``1`` is a number. The TypeScript reference's ``deepEqual``
109
+ handles this via ``typeof``; this function is the Python equivalent.
110
+ """
111
+ if isinstance(a, bool) != isinstance(b, bool):
112
+ return False
113
+ if a is None or b is None:
114
+ return a is b
115
+ if isinstance(a, dict):
116
+ if not isinstance(b, dict) or len(a) != len(b):
117
+ return False
118
+ return all(k in b and _json_equal(a[k], b[k]) for k in a)
119
+ if isinstance(a, list):
120
+ if not isinstance(b, list) or len(a) != len(b):
121
+ return False
122
+ return all(_json_equal(x, y) for x, y in zip(a, b))
123
+ return a == b
124
+
125
+
103
126
  def _apply_one(doc: Any, op: dict) -> Any: # noqa: C901 - one branch per RFC 6902 operation
104
127
  kind = op.get("op")
105
128
  path = op.get("path", "")
@@ -180,7 +203,7 @@ def _apply_one(doc: Any, op: dict) -> Any: # noqa: C901 - one branch per RFC 69
180
203
  if kind == "test":
181
204
  if "value" not in op:
182
205
  raise PatchError("'test' requires 'value'")
183
- if _get(doc, path) != op["value"]:
206
+ if not _json_equal(_get(doc, path), op["value"]):
184
207
  raise PatchError(f"'test' failed at {path}")
185
208
  return doc
186
209
 
@@ -301,7 +301,7 @@ def whispers(f: Frames) -> Brief:
301
301
  if not r["sufficient"]:
302
302
  decision = "Too few resolved questions to judge; the lapse rate will settle as more are asked."
303
303
  elif r["lapse_rate"] > 0.25:
304
- decision = "More than a quarter lapse: the default answer is deciding those questions. Put the answer in the task input, or route whispers to whoever is at the desk."
304
+ decision = "More than a quarter lapse: the default answer is deciding those questions. Put the answer in the task input, check that the questions reach the people asked, or address them to someone who can answer in time."
305
305
  else:
306
306
  decision = "Questions are being answered in time."
307
307
  return Brief("whispers", "Whether agents get answers", head, text, decision, bool(r["sufficient"]), w)
@@ -629,7 +629,8 @@ def whispers(w: pd.DataFrame, by: str = "asker") -> Chart:
629
629
  """Lapse rate per asker with intervals. Takes :func:`stats.whispers` output."""
630
630
  name = "whispers"
631
631
  q = "How often do agents have to ask, and does anyone answer in time?"
632
- d = "A high lapse rate is a question the task input should have answered, or a reviewer who is never at the desk."
632
+ d = ("A high lapse rate points at questions the task input should have answered, or at questions that "
633
+ "reach no one in time. The chain records only that no answer arrived before the deadline.")
633
634
  if w.empty:
634
635
  return _empty(name, "Whispers that lapsed", q, d, "No whispers in this chain.")
635
636
  key = by if by in w.columns else None
@@ -271,41 +271,73 @@ def from_json(path: str, *, workspace: str | None = None, redact: Redactor | Non
271
271
  )
272
272
 
273
273
 
274
+ def _store_snapshot(con: sqlite3.Connection, workspace: str) -> dict:
275
+ """One workspace from the tables chap-coordinator 0.3.2 and later write.
276
+
277
+ The workspace's own fields, its log in seq order, and each collection as
278
+ objects keyed by id.
279
+ """
280
+ row = con.execute("SELECT data FROM chap_meta WHERE workspace = ?", (workspace,)).fetchone()
281
+ snap = json.loads(row[0])
282
+ for name in (*_KEYED_COLLECTIONS, "idempotency_keys"):
283
+ snap[name] = {}
284
+ snap["audit"] = [json.loads(d) for (d,) in con.execute(
285
+ "SELECT data FROM chap_entries WHERE workspace = ? ORDER BY seq", (workspace,))]
286
+ for collection, key, data in con.execute(
287
+ "SELECT collection, id, data FROM chap_objects WHERE workspace = ? ORDER BY rowid",
288
+ (workspace,)):
289
+ snap.setdefault(collection, {})[key] = json.loads(data)
290
+ return snap
291
+
292
+
274
293
  def from_sqlite(path: str, *, workspace: str | None = None, redact: Redactor | None = None) -> Chain:
275
294
  """
276
295
  Load from a SqliteStore file.
277
296
 
278
- The richest source: the store holds the whole workspace snapshot, so
279
- server-computed values are available alongside the envelopes. Opens the
297
+ The richest source: the store holds the whole workspace, so server-computed
298
+ values are available alongside the envelopes. Reads the tables
299
+ chap-coordinator 0.3.2 and later write, one row per audit entry and per
300
+ object, and the single snapshot table earlier releases wrote. Opens the
280
301
  file read-only, so it is safe against a database a coordinator is using.
281
302
  """
282
303
  uri = f"file:{path}?mode=ro"
283
304
  con = sqlite3.connect(uri, uri=True)
284
305
  try:
285
- rows = con.execute("SELECT id, data FROM chap_workspaces").fetchall()
286
- except sqlite3.OperationalError as exc: # pragma: no cover - depends on the file
287
- raise ValueError(
288
- f"{path} lacks the chap_workspaces table a CHAP SqliteStore has: {exc}"
289
- ) from exc
290
- finally:
291
- con.close()
292
-
293
- if not rows:
294
- raise ValueError(f"{path} holds an empty workspace table.")
295
- available = [r[0] for r in rows]
296
- if workspace is None:
297
- if len(rows) > 1:
306
+ # One read transaction, so a coordinator writing the file meanwhile
307
+ # cannot leave the log and the objects out of step.
308
+ con.execute("BEGIN")
309
+ tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}
310
+ if "chap_meta" in tables:
311
+ available = [r[0] for r in con.execute("SELECT workspace FROM chap_meta ORDER BY rowid")]
312
+ rows = None
313
+ elif "chap_workspaces" in tables:
314
+ rows = con.execute("SELECT id, data FROM chap_workspaces").fetchall()
315
+ available = [r[0] for r in rows]
316
+ else:
298
317
  raise ValueError(
299
- f"{path} holds {len(rows)} workspaces; name one with "
300
- f"workspace=. Available: {', '.join(available)}"
318
+ f"{path} lacks the tables a CHAP SqliteStore writes: chap_meta, or "
319
+ "chap_workspaces before chap-coordinator 0.3.2."
301
320
  )
302
- workspace = available[0]
303
- for ws_id, data in rows:
304
- if ws_id == workspace:
305
- snap = json.loads(data)
306
- return _chain(ws_id, snap.get("audit", []), snap, f"sqlite:{path}", redact)
307
- raise ValueError(f"{path} holds {', '.join(available)}. Pass one of those as workspace= "
308
- f"({workspace!r} was given).")
321
+
322
+ if not available:
323
+ raise ValueError(f"{path} holds an empty workspace table.")
324
+ if workspace is None:
325
+ if len(available) > 1:
326
+ raise ValueError(
327
+ f"{path} holds {len(available)} workspaces; name one with "
328
+ f"workspace=. Available: {', '.join(available)}"
329
+ )
330
+ workspace = available[0]
331
+ if workspace not in available:
332
+ raise ValueError(f"{path} holds {', '.join(available)}. Pass one of those as workspace= "
333
+ f"({workspace!r} was given).")
334
+ if rows is None:
335
+ snap = _store_snapshot(con, workspace)
336
+ else:
337
+ snap = json.loads(next(data for ws_id, data in rows if ws_id == workspace))
338
+ finally:
339
+ con.close()
340
+ return _chain(workspace, snap.get("audit", []), snap, f"sqlite:{path}", redact)
309
341
 
310
342
 
311
343
  def from_url(url: str, workspace: str, *, actor: str = "service:analytics",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chap-analytics
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: The record of a collaboration between people and agents, measured and drawn: a CHAP audit chain as documented tables, statistics with their intervals, graphs, charts, briefs and a self-contained interactive report
5
5
  Author-email: Brightbeam AI <oss@brightbeam.com>
6
6
  License-Expression: Apache-2.0
@@ -4149,7 +4149,7 @@
4149
4149
  " -> Reviewers agree on nearly every shared pass. Kappa is low only because almost all of those passes are acceptances, which leaves little disagreement to measure.\n",
4150
4150
  "\n",
4151
4151
  "64 questions asked, 20 lapsed (31%, 21% to 43%); answers took a median of 5 minutes.\n",
4152
- " -> More than a quarter lapse: the default answer is deciding those questions. Put the answer in the task input, or route whispers to whoever is at the desk.\n",
4152
+ " -> More than a quarter lapse: the default answer is deciding those questions. Put the answer in the task input, check that the questions reach the people asked, or address them to someone who can answer in time.\n",
4153
4153
  "\n",
4154
4154
  "10 handoffs proposed, 9 accepted (90%, 60% to 98%), 1 declined, 0 open; resolved in a median of 26 minutes.\n",
4155
4155
  " -> Work moves between people when it needs to.\n",
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "chap-analytics"
7
- version = "0.2.2"
7
+ version = "0.2.4"
8
8
  description = "The record of a collaboration between people and agents, measured and drawn: a CHAP audit chain as documented tables, statistics with their intervals, graphs, charts, briefs and a self-contained interactive report"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,135 @@
1
+ """A store the TypeScript coordinator wrote reads like one the Python coordinator wrote.
2
+
3
+ The TypeScript snapshot holds its collections as lists; the Python one holds
4
+ them as objects keyed by id. The same workspace, written both ways, has to
5
+ project to the same tables. So does a store from chap-coordinator 0.3.2 and
6
+ later, which writes a row per audit entry and per object.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sqlite3
12
+
13
+ import pandas as pd
14
+
15
+ from chap_analytics import frames, from_json, from_sqlite
16
+ from chap_analytics.sample import support_desk
17
+
18
+ KEYS = {"tasks": "id", "overrides": "id", "whispers": "id", "deliberations": "id",
19
+ "handoffs": "id", "snapshots": "id", "route_decisions": "id", "members": "uri"}
20
+
21
+
22
+ def as_typescript(state: dict) -> dict:
23
+ """The snapshot as the TypeScript coordinator writes it: collections as lists."""
24
+ out = dict(state)
25
+ for name in KEYS:
26
+ if isinstance(out.get(name), dict):
27
+ out[name] = list(out[name].values())
28
+ return out
29
+
30
+
31
+ def write_store(path, snapshot: dict) -> None:
32
+ """The single snapshot table chap-coordinator wrote before 0.3.2."""
33
+ con = sqlite3.connect(path)
34
+ con.execute("CREATE TABLE chap_workspaces (id TEXT PRIMARY KEY, version INTEGER NOT NULL, "
35
+ "data TEXT NOT NULL, updated_at TEXT NOT NULL)")
36
+ con.execute("INSERT INTO chap_workspaces VALUES (?, 1, ?, '2026-01-01T00:00:00Z')",
37
+ (snapshot["id"], json.dumps(snapshot)))
38
+ con.commit()
39
+ con.close()
40
+
41
+
42
+ def test_a_typescript_snapshot_projects_to_the_same_tables(tmp_path):
43
+ chain = support_desk()
44
+ snapshot = {**chain.state, "id": chain.workspace, "audit": chain.events}
45
+ python_store, ts_store = tmp_path / "py.db", tmp_path / "ts.db"
46
+ write_store(python_store, snapshot)
47
+ write_store(ts_store, as_typescript(snapshot))
48
+ assert isinstance(json.loads(sqlite3.connect(ts_store).execute("SELECT data FROM chap_workspaces").fetchone()[0])["tasks"], list)
49
+ a = frames(from_sqlite(str(python_store)))
50
+ b = frames(from_sqlite(str(ts_store)))
51
+ for name in ("tasks", "decisions", "overrides", "events"):
52
+ pd.testing.assert_frame_equal(getattr(a, name), getattr(b, name), check_like=True)
53
+ assert len(b.tasks) == len(a.tasks) > 0
54
+
55
+
56
+ def test_from_json_reads_a_typescript_snapshot(tmp_path):
57
+ chain = support_desk()
58
+ path = tmp_path / "ts.json"
59
+ path.write_text(json.dumps(as_typescript({**chain.state, "id": chain.workspace, "audit": chain.events})))
60
+ b = frames(from_json(str(path)))
61
+ a = frames(chain)
62
+ pd.testing.assert_frame_equal(a.tasks, b.tasks, check_like=True)
63
+
64
+
65
+ def write_rows(path, snapshot: dict) -> None:
66
+ """The tables chap-coordinator 0.3.2 and later write, one row per entry and object."""
67
+ con = sqlite3.connect(path)
68
+ con.executescript(
69
+ "CREATE TABLE chap_meta (workspace TEXT PRIMARY KEY, data TEXT NOT NULL, "
70
+ "version INTEGER NOT NULL, updated_at TEXT NOT NULL);"
71
+ "CREATE TABLE chap_entries (workspace TEXT NOT NULL, seq INTEGER NOT NULL, "
72
+ "data TEXT NOT NULL, PRIMARY KEY (workspace, seq));"
73
+ "CREATE TABLE chap_objects (workspace TEXT NOT NULL, collection TEXT NOT NULL, "
74
+ "id TEXT NOT NULL, data TEXT NOT NULL, PRIMARY KEY (workspace, collection, id));")
75
+ ws = snapshot["id"]
76
+ meta = {k: v for k, v in snapshot.items() if k not in KEYS and k not in ("audit", "idempotency_keys")}
77
+ con.execute("INSERT INTO chap_meta VALUES (?, ?, ?, '2026-01-01T00:00:00Z')",
78
+ (ws, json.dumps(meta), len(snapshot["audit"])))
79
+ # Out of order on purpose: the reader orders the log by seq.
80
+ for e in reversed(snapshot["audit"]):
81
+ con.execute("INSERT INTO chap_entries VALUES (?, ?, ?)", (ws, e["seq"], json.dumps(e)))
82
+ for name, key in KEYS.items():
83
+ items = snapshot.get(name) or {}
84
+ for item in (items.values() if isinstance(items, dict) else items):
85
+ con.execute("INSERT INTO chap_objects VALUES (?, ?, ?, ?)", (ws, name, item[key], json.dumps(item)))
86
+ con.commit()
87
+ con.close()
88
+
89
+
90
+ def test_a_store_with_a_row_per_entry_projects_to_the_same_tables(tmp_path):
91
+ chain = support_desk()
92
+ snapshot = {**chain.state, "id": chain.workspace, "audit": chain.events}
93
+ single, rows = tmp_path / "single.db", tmp_path / "rows.db"
94
+ write_store(single, snapshot)
95
+ write_rows(rows, snapshot)
96
+ a = frames(from_sqlite(str(single)))
97
+ b = frames(from_sqlite(str(rows)))
98
+ for name in ("tasks", "decisions", "overrides", "events"):
99
+ pd.testing.assert_frame_equal(getattr(a, name), getattr(b, name), check_like=True)
100
+ assert len(b.events) == len(chain.events) > 0
101
+
102
+
103
+ def test_the_coordinator_store_reads_back(tmp_path):
104
+ """A file the Python coordinator's own SqliteStore wrote, end to end."""
105
+ from chap_coordinator.storage.sqlite import SqliteStore
106
+ from chap_coordinator.storage.store import WorkspaceRecord
107
+
108
+ chain = support_desk()
109
+ snapshot = {**chain.state, "id": chain.workspace, "audit": chain.events}
110
+ path = tmp_path / "store.db"
111
+ store = SqliteStore(str(path))
112
+ store.save(WorkspaceRecord(id=chain.workspace, data=snapshot, version=1, updated_at="t"))
113
+ store.close()
114
+ a = frames(chain)
115
+ b = frames(from_sqlite(str(path)))
116
+ for name in ("tasks", "decisions", "overrides", "events"):
117
+ pd.testing.assert_frame_equal(getattr(a, name), getattr(b, name), check_like=True)
118
+
119
+
120
+ def test_naming_a_workspace_in_a_store_with_rows(tmp_path):
121
+ chain = support_desk()
122
+ snapshot = {**chain.state, "id": chain.workspace, "audit": chain.events}
123
+ path = tmp_path / "rows.db"
124
+ write_rows(path, snapshot)
125
+ con = sqlite3.connect(path)
126
+ con.execute("INSERT INTO chap_meta VALUES ('wsp_other', '{\"id\": \"wsp_other\"}', 0, 't')")
127
+ con.commit()
128
+ con.close()
129
+ try:
130
+ from_sqlite(str(path))
131
+ except ValueError as exc:
132
+ assert "2 workspaces" in str(exc) and chain.workspace in str(exc)
133
+ else:
134
+ raise AssertionError("two workspaces need a name")
135
+ assert from_sqlite(str(path), workspace="wsp_other").events == []
@@ -1,60 +0,0 @@
1
- """A store the TypeScript coordinator wrote reads like one the Python coordinator wrote.
2
-
3
- The TypeScript snapshot holds its collections as lists; the Python one holds
4
- them as objects keyed by id. The same workspace, written both ways, has to
5
- project to the same tables.
6
- """
7
- from __future__ import annotations
8
-
9
- import json
10
- import sqlite3
11
-
12
- import pandas as pd
13
-
14
- from chap_analytics import frames, from_json, from_sqlite
15
- from chap_analytics.sample import support_desk
16
-
17
- KEYS = {"tasks": "id", "overrides": "id", "whispers": "id", "deliberations": "id",
18
- "handoffs": "id", "snapshots": "id", "route_decisions": "id", "members": "uri"}
19
-
20
-
21
- def as_typescript(state: dict) -> dict:
22
- """The snapshot as the TypeScript coordinator writes it: collections as lists."""
23
- out = dict(state)
24
- for name in KEYS:
25
- if isinstance(out.get(name), dict):
26
- out[name] = list(out[name].values())
27
- return out
28
-
29
-
30
- def write_store(path, snapshot: dict) -> None:
31
- con = sqlite3.connect(path)
32
- con.execute("CREATE TABLE chap_workspaces (id TEXT PRIMARY KEY, version INTEGER NOT NULL, "
33
- "data TEXT NOT NULL, updated_at TEXT NOT NULL)")
34
- con.execute("INSERT INTO chap_workspaces VALUES (?, 1, ?, '2026-01-01T00:00:00Z')",
35
- (snapshot["id"], json.dumps(snapshot)))
36
- con.commit()
37
- con.close()
38
-
39
-
40
- def test_a_typescript_snapshot_projects_to_the_same_tables(tmp_path):
41
- chain = support_desk()
42
- snapshot = {**chain.state, "id": chain.workspace, "audit": chain.events}
43
- python_store, ts_store = tmp_path / "py.db", tmp_path / "ts.db"
44
- write_store(python_store, snapshot)
45
- write_store(ts_store, as_typescript(snapshot))
46
- assert isinstance(json.loads(sqlite3.connect(ts_store).execute("SELECT data FROM chap_workspaces").fetchone()[0])["tasks"], list)
47
- a = frames(from_sqlite(str(python_store)))
48
- b = frames(from_sqlite(str(ts_store)))
49
- for name in ("tasks", "decisions", "overrides", "events"):
50
- pd.testing.assert_frame_equal(getattr(a, name), getattr(b, name), check_like=True)
51
- assert len(b.tasks) == len(a.tasks) > 0
52
-
53
-
54
- def test_from_json_reads_a_typescript_snapshot(tmp_path):
55
- chain = support_desk()
56
- path = tmp_path / "ts.json"
57
- path.write_text(json.dumps(as_typescript({**chain.state, "id": chain.workspace, "audit": chain.events})))
58
- b = frames(from_json(str(path)))
59
- a = frames(chain)
60
- pd.testing.assert_frame_equal(a.tasks, b.tasks, check_like=True)
File without changes
File without changes
File without changes