chap-analytics 0.2.0__tar.gz → 0.2.2__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 (62) hide show
  1. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/CHANGELOG.md +68 -0
  2. {chap_analytics-0.2.0/chap_analytics.egg-info → chap_analytics-0.2.2}/PKG-INFO +7 -6
  3. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/README.md +4 -3
  4. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/__init__.py +2 -2
  5. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_report/report.js +15 -7
  6. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/briefs.py +6 -2
  7. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/charts.py +12 -4
  8. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/frames.py +85 -17
  9. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/graph.py +11 -12
  10. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/load.py +51 -5
  11. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/report.py +2 -0
  12. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/sample.py +6 -2
  13. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/schema.py +37 -6
  14. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/stats.py +11 -3
  15. {chap_analytics-0.2.0 → chap_analytics-0.2.2/chap_analytics.egg-info}/PKG-INFO +7 -6
  16. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics.egg-info/SOURCES.txt +3 -0
  17. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics.egg-info/requires.txt +2 -2
  18. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/examples/build_notebook.py +7 -4
  19. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/examples/chap_analytics_walkthrough.ipynb +882 -875
  20. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/pyproject.toml +3 -3
  21. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/js_stats_runner.js +1 -1
  22. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_charts_and_briefs.py +48 -0
  23. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_differential.py +9 -3
  24. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_graph.py +33 -11
  25. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_identity.py +2 -1
  26. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_projection.py +52 -0
  27. chap_analytics-0.2.2/tests/test_refusals.py +110 -0
  28. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_report.py +34 -0
  29. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_sample_and_export.py +2 -0
  30. chap_analytics-0.2.2/tests/test_successors.py +135 -0
  31. chap_analytics-0.2.2/tests/test_typescript_store.py +60 -0
  32. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/LICENSE +0 -0
  33. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/MANIFEST.in +0 -0
  34. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_patch.py +0 -0
  35. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_report/report.css +0 -0
  36. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_report/report.html +0 -0
  37. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_report/stats.js +0 -0
  38. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/LICENSE.vega +0 -0
  39. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/LICENSE.vega-embed +0 -0
  40. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/LICENSE.vega-lite +0 -0
  41. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/README.md +0 -0
  42. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/render.js +0 -0
  43. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/vega-embed.min.js +0 -0
  44. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/vega-lite.min.js +0 -0
  45. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/_vendor/vega.min.js +0 -0
  46. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/export.py +0 -0
  47. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/models.py +0 -0
  48. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/py.typed +0 -0
  49. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics/watch.py +0 -0
  50. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics.egg-info/dependency_links.txt +0 -0
  51. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/chap_analytics.egg-info/top_level.txt +0 -0
  52. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/examples/support_desk.py +0 -0
  53. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/setup.cfg +0 -0
  54. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/conftest.py +0 -0
  55. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_example.py +0 -0
  56. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_from_url_scheme.py +0 -0
  57. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_handoff_and_routing.py +0 -0
  58. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_notebook.py +0 -0
  59. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_redaction_and_malformed.py +0 -0
  60. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_review_passes.py +0 -0
  61. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_stats.py +0 -0
  62. {chap_analytics-0.2.0 → chap_analytics-0.2.2}/tests/test_watch_export_models.py +0 -0
@@ -4,6 +4,74 @@
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.2
8
+
9
+ Reads the store of the TypeScript coordinator, which the Node templates of
10
+ `create-chap-app` run. Install it with `chap-coordinator` 0.3.0 or later where
11
+ the `coordinator` extra drives a live coordinator.
12
+
13
+ ### Fixed
14
+
15
+ - **A TypeScript coordinator's store.** `from_sqlite` and `from_json` read a
16
+ workspace snapshot the TypeScript coordinator wrote, which holds its tasks,
17
+ members, overrides and the other collections as lists where the Python
18
+ coordinator holds them as objects keyed by id. Reading one stopped with an
19
+ `AttributeError`; the collections are now keyed on load, and both
20
+ coordinators' stores project to the same tables.
21
+
22
+ ## 0.2.1
23
+
24
+ Reads the logs a 0.3 coordinator writes. Install it with `chap-coordinator`
25
+ 0.3.0 or later where the `coordinator` extra drives a live coordinator.
26
+
27
+ ### Added
28
+
29
+ - **A `refusals` table.** A coordinator now records a member's refused call
30
+ when it was a governed attempt, such as a decision on a review addressed to
31
+ someone else or a pull on an emergency brake the workspace has switched off.
32
+ The entry holds the call under `request` with an `outcome` beside it. The
33
+ new table lists those attempts with the code each was refused with, and no
34
+ other table replays them, so a refused approval never counts as a decision.
35
+ `events` now holds the accepted entries, and the two tables together hold
36
+ the whole log. The assurance shares, in `stats`, the brief and the report,
37
+ count both, since a refusal is linked into the chain like any other entry.
38
+ A chain written before refusals were recorded reads exactly as before. The
39
+ redaction hook applies to a refused call's parameters as it does to an
40
+ accepted one's.
41
+
42
+ ### Changed
43
+
44
+ - **A successor keeps its original's review requirement.** From 0.3.0 the
45
+ coordinators give the successor that `escalate.raise` or
46
+ `control.supersede` makes the review requirement of the task it replaces,
47
+ and require review of a trial successor of `escalate.raise` under
48
+ `modes/1.0`. The replay follows, so completing such a successor opens a
49
+ review in the tables as it does on the coordinator. Read with server state,
50
+ `review_required` is the coordinator's own value, unset where the
51
+ coordinator left it unset, and a review pass the replay inferred on a task
52
+ the coordinator holds no review on is dropped. Read from envelopes alone, a
53
+ chain written by an earlier coordinator shows a successor that coordinator
54
+ completed directly, the successor of a reviewed task or a trial successor
55
+ of `escalate.raise` under `modes/1.0`, as requiring review, in state
56
+ `review_requested` with outcome `open`.
57
+ - **A log without a recorded submission says so.** A coordinator from 0.3.0
58
+ returns receipts from `audit.submit_to_scitt` and keeps no submission on the
59
+ log, so its logs mark no entry as submitted. Where the log holds no
60
+ submission, the assurance brief and the report say none is on record, and
61
+ the assurance chart leaves the submitted share out. The receipts the
62
+ coordinator returns are the record of what was submitted.
63
+
64
+ ### Fixed
65
+
66
+ - **The `fulfils` edge reads the field where the protocol puts it.**
67
+ SPECIFICATION 9.4 carries `fulfils` on the artefact, and the `tasks` table
68
+ reads it from the output a `task.complete` carried. `graph.build` read a
69
+ top-level field of the same name on the envelope instead, so the edge never
70
+ appeared on a chain a producer had actually written, including every chain
71
+ the wrap helper produces. The graph now reads the same field as the table.
72
+ The id is kept as the producer wrote it and lands on a decision node marked
73
+ `referenced`.
74
+
7
75
  ## 0.2.0
8
76
 
9
77
  The decision layer: every row of the roadmap's decision table, as a
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chap-analytics
3
- Version: 0.2.0
3
+ Version: 0.2.2
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
@@ -29,7 +29,7 @@ License-File: LICENSE
29
29
  Requires-Dist: pandas>=2.0
30
30
  Requires-Dist: numpy>=1.23
31
31
  Provides-Extra: coordinator
32
- Requires-Dist: chap-coordinator>=0.2.13; extra == "coordinator"
32
+ Requires-Dist: chap-coordinator>=0.3.0; extra == "coordinator"
33
33
  Provides-Extra: viz
34
34
  Requires-Dist: altair>=5; extra == "viz"
35
35
  Requires-Dist: vl-convert-python>=1.0; extra == "viz"
@@ -41,7 +41,7 @@ Requires-Dist: nbclient>=0.9; extra == "notebook"
41
41
  Requires-Dist: ipykernel>=6; extra == "notebook"
42
42
  Provides-Extra: dev
43
43
  Requires-Dist: pytest>=8; extra == "dev"
44
- Requires-Dist: chap-coordinator>=0.2.13; extra == "dev"
44
+ Requires-Dist: chap-coordinator>=0.3.0; extra == "dev"
45
45
  Requires-Dist: nbformat>=5; extra == "dev"
46
46
  Requires-Dist: altair>=5; extra == "dev"
47
47
  Requires-Dist: networkx>=3; extra == "dev"
@@ -308,12 +308,12 @@ states each method, what it assumes, and the minimum it asks for.
308
308
 
309
309
  ## The tables
310
310
 
311
- Underneath the statistics are eleven documented tables, projected from the
312
- chain by replaying the envelope stream.
311
+ Underneath the statistics are documented tables, projected from the chain by
312
+ replaying the envelope stream.
313
313
 
314
314
  | Table | Grain |
315
315
  |---|---|
316
- | `events` | one row per audit log entry |
316
+ | `events` | one row per accepted audit log entry |
317
317
  | `tasks` | one row per task |
318
318
  | `decisions` | one row per approve, reject, override or abstain |
319
319
  | `overrides` | one row per correction, with its diff summarised |
@@ -324,6 +324,7 @@ chain by replaying the envelope stream.
324
324
  | `whispers` | one row per deadline-bound question |
325
325
  | `handoffs` | one row per proposed handoff |
326
326
  | `routing` | one row per routing decision |
327
+ | `refusals` | one row per refused call the coordinator recorded |
327
328
 
328
329
  Every column is declared in
329
330
  [`schema.py`](https://github.com/BrightbeamAI/chap/blob/main/packages/chap-analytics/chap_analytics/schema.py)
@@ -259,12 +259,12 @@ states each method, what it assumes, and the minimum it asks for.
259
259
 
260
260
  ## The tables
261
261
 
262
- Underneath the statistics are eleven documented tables, projected from the
263
- chain by replaying the envelope stream.
262
+ Underneath the statistics are documented tables, projected from the chain by
263
+ replaying the envelope stream.
264
264
 
265
265
  | Table | Grain |
266
266
  |---|---|
267
- | `events` | one row per audit log entry |
267
+ | `events` | one row per accepted audit log entry |
268
268
  | `tasks` | one row per task |
269
269
  | `decisions` | one row per approve, reject, override or abstain |
270
270
  | `overrides` | one row per correction, with its diff summarised |
@@ -275,6 +275,7 @@ chain by replaying the envelope stream.
275
275
  | `whispers` | one row per deadline-bound question |
276
276
  | `handoffs` | one row per proposed handoff |
277
277
  | `routing` | one row per routing decision |
278
+ | `refusals` | one row per refused call the coordinator recorded |
278
279
 
279
280
  Every column is declared in
280
281
  [`schema.py`](https://github.com/BrightbeamAI/chap/blob/main/packages/chap-analytics/chap_analytics/schema.py)
@@ -21,7 +21,7 @@ lighter mode, whether reviewers agree, and who is deciding on whose work.
21
21
 
22
22
  The layers, bottom up:
23
23
 
24
- * ``frames``: eleven documented tables projected from the chain. Every column
24
+ * ``frames``: documented tables projected from the chain. Every column
25
25
  is declared in ``schema.py`` with its dtype and its provenance.
26
26
  * ``stats``: the estimates with their intervals, and a statement of what
27
27
  each one needs before it should be read.
@@ -41,7 +41,7 @@ The layers, bottom up:
41
41
  """
42
42
  from __future__ import annotations
43
43
 
44
- __version__ = "0.2.0"
44
+ __version__ = "0.2.2"
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
@@ -77,8 +77,10 @@
77
77
  const handoffs = D.handoffs.filter((h) => inRange(h.proposed_at) &&
78
78
  (!state.agent || h.proposer === state.agent || h.recipient === state.agent) &&
79
79
  (!state.reviewer || h.proposer === state.reviewer || h.recipient === state.reviewer));
80
- const events = D.events.filter((e) => inRange(e.ts) && (!e.task_id || !(state.kind || state.agent || state.mode || state.tag || state.reviewer) || ids.has(e.task_id)));
81
- return { tasks, decisions, overrides, patch_ops, passes, whispers, handoffs, events };
80
+ const onTask = (e) => inRange(e.ts) && (!e.task_id || !(state.kind || state.agent || state.mode || state.tag || state.reviewer) || ids.has(e.task_id));
81
+ const events = D.events.filter(onTask);
82
+ const refusals = (D.refusals || []).filter(onTask);
83
+ return { tasks, decisions, overrides, patch_ops, passes, whispers, handoffs, events, refusals };
82
84
  }
83
85
 
84
86
  // ------------------------------------------------------------ chart data builders
@@ -165,10 +167,15 @@
165
167
  },
166
168
  assurance(F) {
167
169
  const out = [];
168
- for (const r of S.assurance(F.events, "D")) {
170
+ // Accepted calls and recorded refusals are both entries on the chain.
171
+ // A coordinator from 0.3.0 keeps no submission on the log, so the
172
+ // submitted share is drawn only where the whole log holds one, as the
173
+ // library's chart does.
174
+ const onRecord = D.events.concat(D.refusals || []).some((e) => e.scitt_submitted === true);
175
+ for (const r of S.assurance(F.events.concat(F.refusals), "D")) {
169
176
  out.push({ period: r.period, n: r.n, share: r.chained_share, property: "hash-linked" });
170
177
  out.push({ period: r.period, n: r.n, share: r.signed_share, property: "signed" });
171
- out.push({ period: r.period, n: r.n, share: r.scitt_share, property: "SCITT submitted" });
178
+ if (onRecord) out.push({ period: r.period, n: r.n, share: r.scitt_share, property: "SCITT submitted" });
172
179
  }
173
180
  return out;
174
181
  },
@@ -264,10 +271,11 @@
264
271
  const h = S.handoffs(F.handoffs)[0];
265
272
  cards.push({ id: "handoffs", label: "Handoffs accepted", value: h ? pct(h.accept_rate) : "n/a",
266
273
  detail: h ? `${h.n} proposed; ${h.declined} declined; ${h.open} open` : "no handoffs", thin: !(h && h.sufficient) });
267
- const n = F.events.length;
268
- const chained = F.events.filter((e) => e.chained).length, signed = F.events.filter((e) => e.signed).length, sub = F.events.filter((e) => e.scitt_submitted).length;
274
+ const entries = F.events.concat(F.refusals);
275
+ const n = entries.length;
276
+ const chained = entries.filter((e) => e.chained).length, signed = entries.filter((e) => e.signed).length, sub = entries.filter((e) => e.scitt_submitted).length;
269
277
  cards.push({ id: "assurance", label: "Entries hash-linked", value: n ? pct(chained / n) : "n/a",
270
- detail: n ? `${n} entries; ${pct(signed / n)} signed; ${pct(sub / n)} SCITT submitted` : "no entries", thin: !n, tone: n && chained === n ? "ok" : "warn" });
278
+ detail: n ? `${n} entries; ${pct(signed / n)} signed; ${sub ? `${pct(sub / n)} SCITT submitted` : "no SCITT submission on record"}` : "no entries", thin: !n, tone: n && chained === n ? "ok" : "warn" });
271
279
  const cs = S.cusum(F.tasks, { shift: META.shift, threshold: thresholdFor });
272
280
  const alarms = cs.filter((x) => x.alarm).length;
273
281
  cards.push({ id: "drift", label: "Drift alarms", value: cs.length ? String(alarms) : "n/a",
@@ -333,7 +333,8 @@ def handoffs(f: Frames) -> Brief:
333
333
 
334
334
  def assurance(f: Frames) -> Brief:
335
335
  """How much of the chain is hash-linked, signed and submitted to a transparency log."""
336
- e = f.events
336
+ # Accepted calls and recorded refusals are both entries on the chain.
337
+ e = _stats._log_entries(f)
337
338
  if e.empty:
338
339
  return Brief("assurance", "Whether the record holds up", "No entries.", "The chain is empty.",
339
340
  "Nothing to verify.", False, e)
@@ -341,8 +342,11 @@ def assurance(f: Frames) -> Brief:
341
342
  chained = int(e["chained"].fillna(False).sum())
342
343
  signed = int(e["signed"].fillna(False).sum())
343
344
  sub = int(e["scitt_submitted"].fillna(False).sum())
345
+ # A coordinator from 0.3.0 keeps no submission on the log, so a share of
346
+ # zero would misstate a log whose submissions happened.
344
347
  head = (f"{_n(n, 'entry', 'entries')}: {_pct(chained / n)} hash-linked, {_pct(signed / n)} signed, "
345
- f"{_pct(sub / n)} submitted to a transparency log.")
348
+ + (f"{_pct(sub / n)} submitted to a transparency log." if sub
349
+ else "and no submission to a transparency log on record."))
346
350
  text = ("A hash-linked entry carries the hash of the one before it, so a change to an earlier entry shows up "
347
351
  "when the chain is checked against an independently held head. A signed entry carries its sender's "
348
352
  "signature, which a verifier can check against the sender's key. A submitted entry was sent to a "
@@ -690,13 +690,21 @@ def assurance(a: pd.DataFrame) -> Chart:
690
690
  d = "A line at 100% means every entry in the period carries that property. A dip is a period whose entries carry less than the rest."
691
691
  if a.empty:
692
692
  return _empty(name, "Chain assurance", q, d, "No entries in this chain.")
693
- long = pd.concat([
693
+ # A coordinator from 0.3.0 keeps no submission on the log, so the submitted
694
+ # share is drawn only where the log holds one.
695
+ on_record = int(a["scitt_submitted"].sum()) > 0
696
+ parts = [
694
697
  a[["period", "n", "chained_share"]].rename(columns={"chained_share": "share"}).assign(property="hash-linked"),
695
698
  a[["period", "n", "signed_share"]].rename(columns={"signed_share": "share"}).assign(property="signed"),
696
- a[["period", "n", "scitt_share"]].rename(columns={"scitt_share": "share"}).assign(property="SCITT submitted"),
697
- ])
699
+ ]
700
+ if on_record:
701
+ parts.append(a[["period", "n", "scitt_share"]].rename(columns={"scitt_share": "share"}).assign(property="SCITT submitted"))
702
+ long = pd.concat(parts)
698
703
  data = _records(long, ["period", "n", "share", "property"])
699
- spec = _base(name, "Chain assurance", "Share of entries per period that are hash-linked, signed, and submitted to a transparency log",
704
+ subtitle = ("Share of entries per period that are hash-linked, signed, and submitted to a transparency log"
705
+ if on_record else
706
+ "Share of entries per period that are hash-linked and signed. The log holds no submission to a transparency log.")
707
+ spec = _base(name, "Chain assurance", subtitle,
700
708
  data, width=620, height=240,
701
709
  mark={"type": "line", "point": True, "interpolate": "monotone"},
702
710
  encoding={"x": {"field": "period", "type": "temporal", "title": None,
@@ -32,7 +32,7 @@ import pandas as pd
32
32
 
33
33
  from . import schema
34
34
  from ._patch import PatchError, apply_json_patch
35
- from .load import Chain
35
+ from .load import Chain, is_refusal
36
36
 
37
37
  __all__ = ["frames", "Frames"]
38
38
 
@@ -307,6 +307,8 @@ class _Task:
307
307
  review_required: bool | None = None
308
308
  created_at: pd.Timestamp | None = None
309
309
  state: str = "created"
310
+ fulfils: str | None = None
311
+ paused_from: str | None = None
310
312
  settled_at: pd.Timestamp | None = None
311
313
  confidence: float | None = None
312
314
  criticality: str | None = None
@@ -422,6 +424,8 @@ class _Index:
422
424
  overrides: list[dict] = field(default_factory=list)
423
425
  routing: list[dict] = field(default_factory=list)
424
426
  events: list[dict] = field(default_factory=list)
427
+ #: Refused calls the coordinator recorded. Never replayed.
428
+ refusals: list[dict] = field(default_factory=list)
425
429
  #: Task ids in the order the replay first saw them, wherever they appeared.
426
430
  #: Derived from the events table instead, this missed every id that
427
431
  #: arrives nested, as handoff.propose's do.
@@ -437,6 +441,34 @@ class _Index:
437
441
  claimed_by: list[str | None] = field(default_factory=list)
438
442
 
439
443
 
444
+ def _refusal_row(entry: dict, workspace: str | None) -> dict:
445
+ """One row of the refusals table, from an entry that holds a refused call."""
446
+ req = entry.get("request")
447
+ req = req if isinstance(req, dict) else {}
448
+ p = req.get("params")
449
+ p = p if isinstance(p, dict) else {}
450
+ outcome = entry.get("outcome")
451
+ outcome = outcome if isinstance(outcome, dict) else {}
452
+ actor = p.get("from")
453
+ tid = p.get("task_id") or p.get("original_task_id")
454
+ arrived = _ts(entry.get("arrived"))
455
+ return {
456
+ "seq": entry.get("seq") if isinstance(entry.get("seq"), int) else None,
457
+ "workspace": p.get("workspace") or workspace,
458
+ "ts": _ts(p.get("ts")) or arrived,
459
+ "arrived": arrived,
460
+ "method": req.get("method"),
461
+ "actor": actor,
462
+ "actor_kind": _uri_kind(actor),
463
+ "task_id": tid if isinstance(tid, str) else None,
464
+ "code": outcome.get("code") if isinstance(outcome.get("code"), int) else None,
465
+ "prev_hash": entry.get("prev_hash"),
466
+ "chained": entry.get("prev_hash") is not None,
467
+ "signed": isinstance(req.get("sig"), str),
468
+ "scitt_submitted": False,
469
+ }
470
+
471
+
440
472
  def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per method
441
473
  ix = _Index()
442
474
  # Deliberation, whisper and handoff ids are minted by the coordinator and
@@ -468,7 +500,8 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
468
500
  Whether a task made from this spec requires review, as the coordinator
469
501
  decides it for task.create and control.supersede alike: a trial task
470
502
  under modes/1.0 does regardless, otherwise the spec's own flag, and
471
- otherwise the coordinator leaves it unset.
503
+ otherwise the coordinator leaves it unset. escalate.raise passes an
504
+ empty spec, since it reads no flag from its new_task.
472
505
  """
473
506
  if mode == "trial" and any(x == "modes" or x.startswith("modes/") for x in ws_profiles):
474
507
  return True
@@ -509,6 +542,11 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
509
542
  # A stray element in a hand-assembled export. Skipped, so the
510
543
  # entries after it still reach the analysis.
511
544
  continue
545
+ if is_refusal(entry):
546
+ # A refused call, recorded under `request`. It did not take effect,
547
+ # so it is listed and never replayed into any other table.
548
+ ix.refusals.append(_refusal_row(entry, chain.workspace))
549
+ continue
512
550
  env = entry.get("envelope")
513
551
  env = env if isinstance(env, dict) else {}
514
552
  p = env.get("params")
@@ -553,7 +591,7 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
553
591
  lo = rng.get("from_seq", 0)
554
592
  hi = rng.get("to_seq", pos)
555
593
  if isinstance(lo, int) and isinstance(hi, int):
556
- for row in ix.events:
594
+ for row in (*ix.events, *ix.refusals):
557
595
  s = row["seq"]
558
596
  if isinstance(s, int) and lo <= s < hi:
559
597
  row["scitt_submitted"] = True
@@ -601,6 +639,9 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
601
639
 
602
640
  elif method == "task.complete" and tid:
603
641
  t = task(tid)
642
+ out = p.get("output")
643
+ if isinstance(out, dict) and isinstance(out.get("fulfils"), str):
644
+ t.fulfils = out["fulfils"]
604
645
  conf = _decimal(p.get("confidence"))
605
646
  if conf is None:
606
647
  hints = p.get("routing_hints") if isinstance(p.get("routing_hints"), dict) else {}
@@ -702,13 +743,20 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
702
743
  old.state, old.settled_at = "escalated", ts
703
744
  spec = p.get("new_task") if isinstance(p.get("new_task"), dict) else {}
704
745
  # The successor inherits the original's kind where the spec names
705
- # none, and its mode always. The coordinator leaves review_required
706
- # at its default here.
707
- inherited = {"mode"} | ({"kind"} if not spec.get("kind") else set())
746
+ # none, and its mode where the spec names none. It requires review
747
+ # when the original did, and otherwise under the rule task.create
748
+ # applies to its mode. The coordinator reads no review_required
749
+ # from the spec.
750
+ mode = spec.get("mode") or (old.mode if old else None)
751
+ keeps_review = bool(old is not None and old.review_required)
752
+ inherited = ({"mode"} if not spec.get("mode") else set()) \
753
+ | ({"kind"} if not spec.get("kind") else set()) \
754
+ | ({"review_required"} if keeps_review else set())
708
755
  created(_Creation(
709
756
  pos=pos, kind=spec.get("kind") or (old.kind if old else None),
710
757
  delegator=actor, original_assignee=spec.get("assignee"),
711
- assignee=spec.get("assignee"), mode=old.mode if old else None,
758
+ assignee=spec.get("assignee"), mode=mode,
759
+ review_required=True if keeps_review else review_rule({}, mode),
712
760
  created_at=ts, supersedes=orig, inherited=frozenset(inherited)))
713
761
 
714
762
  elif method == "control.cancel" and tid:
@@ -720,23 +768,31 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
720
768
  old.state, old.settled_at = "superseded", ts
721
769
  spec = p.get("successor_task") if isinstance(p.get("successor_task"), dict) else {}
722
770
  # A successor is a created task and is bound as one: it takes the
723
- # original's assignee and mode where the spec names none, and the
724
- # same review rule task.create applies.
771
+ # original's assignee and mode where the spec names none, keeps
772
+ # the original's review requirement, and otherwise meets the same
773
+ # review rule task.create applies.
725
774
  assignee = spec.get("assignee") or old.assignee
726
775
  mode = spec.get("mode") or old.mode or ws_mode
776
+ keeps_review = bool(old.review_required)
727
777
  inherited = ({"assignee"} if not spec.get("assignee") else set()) \
728
- | ({"mode"} if not spec.get("mode") else set())
778
+ | ({"mode"} if not spec.get("mode") else set()) \
779
+ | ({"review_required"} if keeps_review else set())
729
780
  created(_Creation(
730
781
  pos=pos, kind=spec.get("kind"), delegator=actor,
731
782
  original_assignee=assignee, assignee=assignee, mode=mode,
732
- review_required=review_rule(spec, mode), created_at=ts, supersedes=tid,
733
- inherited=frozenset(inherited)))
783
+ review_required=True if keeps_review else review_rule(spec, mode),
784
+ created_at=ts, supersedes=tid, inherited=frozenset(inherited)))
734
785
 
735
786
  elif method == "control.pause" and tid and p.get("scope", "task") == "task":
736
- task(tid).state = "paused"
787
+ t = task(tid)
788
+ if t.state != "paused":
789
+ t.paused_from = t.state
790
+ t.state = "paused"
737
791
 
738
792
  elif method == "control.resume" and tid and p.get("scope", "task") == "task":
739
- task(tid).state = "in_progress"
793
+ t = task(tid)
794
+ t.state = t.paused_from or "in_progress"
795
+ t.paused_from = None
740
796
 
741
797
  elif method == "deliberate.open":
742
798
  d_open = _Delib(
@@ -1222,8 +1278,11 @@ def _merge_state(ix: _Index, chain: Chain) -> None: # noqa: C901 - one block pe
1222
1278
  t.delegator = stored.get("delegator", t.delegator)
1223
1279
  t.mode = stored.get("mode", t.mode)
1224
1280
  t.supersedes = stored.get("supersedes", t.supersedes)
1225
- if stored.get("review_required") is not None:
1226
- t.review_required = stored["review_required"]
1281
+ # A coordinator stores review_required only where it set it, so its
1282
+ # absence is the coordinator's own unset value. The replay infers an
1283
+ # escalated task's requirement from the task it replaces, and the
1284
+ # stored value settles it.
1285
+ t.review_required = stored.get("review_required")
1227
1286
  t.created_at = t.created_at or _ts(stored.get("created_at"))
1228
1287
  if t.confidence is None:
1229
1288
  t.confidence = _decimal(stored.get("confidence"))
@@ -1243,6 +1302,13 @@ def _merge_state(ix: _Index, chain: Chain) -> None: # noqa: C901 - one block pe
1243
1302
  r.requested_at = r.requested_at or _ts(review.get("requested_at"))
1244
1303
  r.rule = review.get("rule") or r.rule
1245
1304
  r.requested_to = list(review.get("requested_to") or r.requested_to)
1305
+ else:
1306
+ # A coordinator keeps a review once it opens one, so a task it
1307
+ # holds no review on never had one. A pass the replay opened with
1308
+ # no decision in it was inferred, such as the review an escalated
1309
+ # task's completion opens on a chain written before successors
1310
+ # kept the requirement, and is dropped.
1311
+ t.reviews = [r for r in t.reviews if r.decisions]
1246
1312
 
1247
1313
  # Overrides are matched to stored artefacts per task, in order: one
1248
1314
  # reviewer may correct the same task twice, so the pair (task, reviewer)
@@ -1450,6 +1516,7 @@ class Frames:
1450
1516
  whispers: pd.DataFrame
1451
1517
  handoffs: pd.DataFrame
1452
1518
  routing: pd.DataFrame
1519
+ refusals: pd.DataFrame
1453
1520
 
1454
1521
  def __getitem__(self, name: str) -> pd.DataFrame:
1455
1522
  if name not in schema.BY_NAME:
@@ -1589,7 +1656,7 @@ def frames(chain: Chain) -> Frames:
1589
1656
  "n_reviews": len(t.reviews),
1590
1657
  "n_decisions": len(t.decisions), "confidence": t.confidence,
1591
1658
  "criticality": t.criticality, "risk_tier": t.risk_tier,
1592
- "supersedes": t.supersedes,
1659
+ "supersedes": t.supersedes, "fulfils": t.fulfils,
1593
1660
  })
1594
1661
 
1595
1662
  # -- overrides and their operations -------------------------------------
@@ -1720,4 +1787,5 @@ def frames(chain: Chain) -> Frames:
1720
1787
  whispers=_enforce(schema.WHISPERS, whisper_rows),
1721
1788
  handoffs=_enforce(schema.HANDOFFS, handoff_rows),
1722
1789
  routing=_enforce(schema.ROUTING, ix.routing),
1790
+ refusals=_enforce(schema.REFUSALS, ix.refusals),
1723
1791
  )
@@ -68,7 +68,7 @@ EDGE_TYPES: dict[str, tuple[str, str, str]] = {
68
68
  "decision_on": ("decision", "review", "the pass the decision settled or contributed to"),
69
69
  "based_on": ("artefact", "artefact", "an override's corrected artefact and the draft it was derived from"),
70
70
  "overrode": ("decision", "artefact", "the corrected artefact an override decision produced"),
71
- "fulfils": ("artefact", "decision", "task.complete `fulfils`: the decision an execution's artefact says it carries out; the producer's claim, recorded without verification"),
71
+ "fulfils": ("artefact", "decision", "the `fulfils` field of the artefact a `task.complete` carried: the decision an execution says it carries out; the producer's claim, recorded without verification"),
72
72
  "supersedes": ("task", "task", "escalate.raise or control.supersede: the successor and the task it replaced"),
73
73
  "asked": ("participant", "whisper", "whisper.ask"),
74
74
  "whispered_to": ("whisper", "participant", "whisper.ask `to`"),
@@ -328,20 +328,19 @@ def build(f: Frames) -> Graph:
328
328
  if pass_idx is not None:
329
329
  g.add_edge(corrected, f"draft:{o.task_id}:{pass_idx}", "based_on")
330
330
 
331
- # Executions that name the decision they carry out: a task.complete whose
332
- # params carry `fulfils` (CEP-001). The value is the producer's reference
333
- # to a decision. A mapping with task_id and seq lands on that decision
334
- # node; any other value becomes a referenced decision node under its own
335
- # text, since the chain records the claim without resolving it.
331
+ # Executions that name the decision they carry out. SPECIFICATION 9.4 puts
332
+ # `fulfils` on the artefact, so it is read from the output a task.complete
333
+ # carried, the field the wrap helper writes and the `tasks` table reads.
334
+ # The value names the id of a decision the producer claims authorised the
335
+ # work. Node ids in this graph are built from the task and the sequence
336
+ # number, so a named id becomes a decision node of its own marked
337
+ # `referenced`: the chain holds the claim without resolving it.
336
338
  completes = ev[ev["method"] == "task.complete"].sort_values("seq")
337
339
  for r in completes.itertuples(index=False):
338
- ref = params_by_seq.get(_seq(r.seq), {}).get("fulfils")
339
- if ref is None or not _s(r.task_id):
340
+ out = params_by_seq.get(_seq(r.seq), {}).get("output")
341
+ target = out.get("fulfils") if isinstance(out, dict) else None
342
+ if not isinstance(target, str) or not target or not _s(r.task_id):
340
343
  continue
341
- if isinstance(ref, dict) and _s(ref.get("task_id")) and isinstance(ref.get("seq"), int):
342
- target = f"decision:{ref['task_id']}:{ref['seq']}"
343
- else:
344
- target = str(ref)
345
344
  art = f"output:{r.task_id}:{_seq(r.seq)}"
346
345
  g.add_node(art, "artefact", f"output of {r.task_id}", kind="output")
347
346
  a = participant(r.actor)
@@ -75,7 +75,10 @@ class Chain:
75
75
  def summary(self) -> str:
76
76
  methods: dict[str, int] = {}
77
77
  for e in self.events:
78
- m = (e.get("envelope") or {}).get("method", "?")
78
+ if is_refusal(e):
79
+ m = f"{(e.get('request') or {}).get('method', '?')} (refused)"
80
+ else:
81
+ m = (e.get("envelope") or {}).get("method", "?")
79
82
  methods[m] = methods.get(m, 0) + 1
80
83
  lines = [repr(self)]
81
84
  for m, n in sorted(methods.items(), key=lambda kv: (-kv[1], kv[0])):
@@ -126,14 +129,36 @@ def _redact_params(params: Any, redact: Redactor) -> None:
126
129
  spec[inner] = redact(spec[inner])
127
130
 
128
131
 
132
+ def is_refusal(entry: Any) -> bool:
133
+ """Whether a log entry records a refused call rather than an accepted one.
134
+
135
+ Read by value: a snapshot written by ``dataclasses.asdict`` carries every
136
+ field of an entry, with ``None`` in the ones that do not apply.
137
+ """
138
+ return (isinstance(entry, dict) and isinstance(entry.get("outcome"), dict)
139
+ and not isinstance(entry.get("envelope"), dict))
140
+
141
+
142
+ def _call(entry: dict[str, Any]) -> dict[str, Any]:
143
+ """The call a log entry records: the accepted envelope, or a refused request."""
144
+ call = entry.get("envelope")
145
+ if not isinstance(call, dict):
146
+ call = entry.get("request")
147
+ return call if isinstance(call, dict) else {}
148
+
149
+
129
150
  def _apply_redaction(events: list[dict[str, Any]], redact: Redactor | None) -> list[dict[str, Any]]:
130
- """Rewrite artefact-bearing params on a copy, before anything reads them."""
151
+ """Rewrite artefact-bearing params on a copy, before anything reads them.
152
+
153
+ A refused call carries content as much as an accepted one, so the
154
+ request of a refusal entry is redacted too.
155
+ """
131
156
  if redact is None:
132
157
  return events
133
158
  out: list[dict[str, Any]] = []
134
159
  for e in events:
135
160
  e = json.loads(json.dumps(e)) # deep copy; events may be shared
136
- _redact_params((e.get("envelope") or {}).get("params"), redact)
161
+ _redact_params(_call(e).get("params"), redact)
137
162
  out.append(e)
138
163
  return out
139
164
 
@@ -155,7 +180,7 @@ def _redact_state(state: dict | None, redact: Redactor | None) -> dict | None:
155
180
 
156
181
  for entry in state.get("audit") or []:
157
182
  if isinstance(entry, dict):
158
- _redact_params((entry.get("envelope") or {}).get("params"), redact)
183
+ _redact_params(_call(entry).get("params"), redact)
159
184
 
160
185
  for task in (state.get("tasks") or {}).values():
161
186
  if not isinstance(task, dict):
@@ -192,12 +217,33 @@ def _redact_state(state: dict | None, redact: Redactor | None) -> dict | None:
192
217
  return state
193
218
 
194
219
 
220
+ # The collections a workspace snapshot holds, and the field each is keyed by.
221
+ # The Python coordinator writes them as objects keyed by that field; the
222
+ # TypeScript coordinator writes them as lists. The projection reads objects.
223
+ _KEYED_COLLECTIONS = {
224
+ "tasks": "id", "overrides": "id", "whispers": "id", "deliberations": "id",
225
+ "handoffs": "id", "snapshots": "id", "route_decisions": "id", "members": "uri",
226
+ }
227
+
228
+
229
+ def _keyed_state(state: dict | None) -> dict | None:
230
+ """A snapshot with every collection keyed by id, whichever coordinator wrote it."""
231
+ if not isinstance(state, dict):
232
+ return state
233
+ out = dict(state)
234
+ for name, key in _KEYED_COLLECTIONS.items():
235
+ value = out.get(name)
236
+ if isinstance(value, list):
237
+ out[name] = {item[key]: item for item in value if isinstance(item, dict) and isinstance(item.get(key), str)}
238
+ return out
239
+
240
+
195
241
  def _chain(workspace: str, events: Iterable[dict], state: dict | None,
196
242
  source: str, redact: Redactor | None) -> Chain:
197
243
  evs = _apply_redaction(list(events), redact)
198
244
  evs.sort(key=lambda e: e.get("seq", 0) if isinstance(e, dict) else 0)
199
245
  return Chain(workspace=workspace, events=evs,
200
- state=_redact_state(state, redact), source=source)
246
+ state=_redact_state(_keyed_state(state), redact), source=source)
201
247
 
202
248
 
203
249
  def from_json(path: str, *, workspace: str | None = None, redact: Redactor | None = None) -> Chain:
@@ -130,6 +130,8 @@ def embedded_data(f: Frames, *, threshold: float = 0.10, freq: str = "W", ration
130
130
  "handoffs": _plain_records(f.handoffs, ["handoff_id", "proposer", "recipient", "resolution", "resolved_by",
131
131
  "response_s", "proposed_at", "n_tasks"]),
132
132
  "events": _plain_records(ev, ["seq", "ts", "method", "actor", "task_id", "chained", "signed", "scitt_submitted"]),
133
+ "refusals": _plain_records(f.refusals, ["seq", "ts", "method", "actor", "task_id", "code",
134
+ "chained", "signed", "scitt_submitted"]),
133
135
  "edges": _plain_records(edges, ["source", "target", "relation", "weight", "mean_latency_s"]),
134
136
  "positions": _plain_records(positions, ["node", "x", "y"]),
135
137
  "centrality": _plain_records(centrality, ["participant", "kind", "in_weight", "out_weight", "betweenness"]),