kinescope 0.0.1__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 (86) hide show
  1. kinescope-0.0.1/.editorconfig +19 -0
  2. kinescope-0.0.1/.env.example +7 -0
  3. kinescope-0.0.1/.gitattributes +23 -0
  4. kinescope-0.0.1/.github/workflows/ci.yml +32 -0
  5. kinescope-0.0.1/.github/workflows/publish.yml +31 -0
  6. kinescope-0.0.1/.gitignore +47 -0
  7. kinescope-0.0.1/DESIGN.md +451 -0
  8. kinescope-0.0.1/LICENSE +21 -0
  9. kinescope-0.0.1/Makefile +21 -0
  10. kinescope-0.0.1/PKG-INFO +206 -0
  11. kinescope-0.0.1/PROGRESS.md +510 -0
  12. kinescope-0.0.1/README.md +169 -0
  13. kinescope-0.0.1/ROADMAP.md +152 -0
  14. kinescope-0.0.1/docs/Foundational-Doc.md +96 -0
  15. kinescope-0.0.1/docs/README.md +12 -0
  16. kinescope-0.0.1/docs/adr/0001-record-architecture-decisions.md +33 -0
  17. kinescope-0.0.1/docs/adr/0002-interception-and-storage.md +48 -0
  18. kinescope-0.0.1/docs/timeline.gif +0 -0
  19. kinescope-0.0.1/docs/timeline.svg +184 -0
  20. kinescope-0.0.1/examples/agent_script.py +31 -0
  21. kinescope-0.0.1/examples/fixtures/real_anthropic_run.zip +0 -0
  22. kinescope-0.0.1/examples/fixtures/real_gemini_run.zip +0 -0
  23. kinescope-0.0.1/examples/fixtures/real_ollama_run.zip +0 -0
  24. kinescope-0.0.1/examples/fork_demo.py +61 -0
  25. kinescope-0.0.1/examples/fork_demo_tui.py +50 -0
  26. kinescope-0.0.1/examples/live_agent.py +34 -0
  27. kinescope-0.0.1/examples/live_gemini_agent.py +38 -0
  28. kinescope-0.0.1/examples/live_gemini_record.py +67 -0
  29. kinescope-0.0.1/examples/live_ollama_agent.py +39 -0
  30. kinescope-0.0.1/examples/live_ollama_record.py +65 -0
  31. kinescope-0.0.1/examples/live_record.py +58 -0
  32. kinescope-0.0.1/examples/openai_demo.py +64 -0
  33. kinescope-0.0.1/examples/otel_export.py +53 -0
  34. kinescope-0.0.1/examples/record_demo.py +72 -0
  35. kinescope-0.0.1/examples/share_bundle.py +52 -0
  36. kinescope-0.0.1/examples/stateful_agent.py +52 -0
  37. kinescope-0.0.1/examples/tool_agent.py +81 -0
  38. kinescope-0.0.1/pyproject.toml +54 -0
  39. kinescope-0.0.1/src/kinescope/__init__.py +76 -0
  40. kinescope-0.0.1/src/kinescope/adapters/__init__.py +3 -0
  41. kinescope-0.0.1/src/kinescope/adapters/anthropic.py +25 -0
  42. kinescope-0.0.1/src/kinescope/adapters/base.py +47 -0
  43. kinescope-0.0.1/src/kinescope/adapters/gemini.py +37 -0
  44. kinescope-0.0.1/src/kinescope/adapters/ollama.py +20 -0
  45. kinescope-0.0.1/src/kinescope/adapters/openai.py +27 -0
  46. kinescope-0.0.1/src/kinescope/branch.py +98 -0
  47. kinescope-0.0.1/src/kinescope/cli.py +243 -0
  48. kinescope-0.0.1/src/kinescope/diff.py +65 -0
  49. kinescope-0.0.1/src/kinescope/engine.py +142 -0
  50. kinescope-0.0.1/src/kinescope/export/__init__.py +4 -0
  51. kinescope-0.0.1/src/kinescope/export/bundle.py +70 -0
  52. kinescope-0.0.1/src/kinescope/export/otel.py +74 -0
  53. kinescope-0.0.1/src/kinescope/intercept/__init__.py +12 -0
  54. kinescope-0.0.1/src/kinescope/intercept/http.py +160 -0
  55. kinescope-0.0.1/src/kinescope/intercept/stdlib.py +111 -0
  56. kinescope-0.0.1/src/kinescope/intercept/tools.py +100 -0
  57. kinescope-0.0.1/src/kinescope/model.py +84 -0
  58. kinescope-0.0.1/src/kinescope/runner.py +48 -0
  59. kinescope-0.0.1/src/kinescope/session.py +167 -0
  60. kinescope-0.0.1/src/kinescope/store/__init__.py +4 -0
  61. kinescope-0.0.1/src/kinescope/store/base.py +31 -0
  62. kinescope-0.0.1/src/kinescope/store/local.py +194 -0
  63. kinescope-0.0.1/src/kinescope/store/mongo.py +169 -0
  64. kinescope-0.0.1/src/kinescope/tui/__init__.py +3 -0
  65. kinescope-0.0.1/src/kinescope/tui/app.py +261 -0
  66. kinescope-0.0.1/tests/fixtures/gemini_generate.json +15 -0
  67. kinescope-0.0.1/tests/fixtures/openai_chat.json +15 -0
  68. kinescope-0.0.1/tests/test_adapters.py +73 -0
  69. kinescope-0.0.1/tests/test_async.py +48 -0
  70. kinescope-0.0.1/tests/test_branch.py +132 -0
  71. kinescope-0.0.1/tests/test_bundle.py +81 -0
  72. kinescope-0.0.1/tests/test_divergence.py +76 -0
  73. kinescope-0.0.1/tests/test_gemini.py +52 -0
  74. kinescope-0.0.1/tests/test_mongo.py +91 -0
  75. kinescope-0.0.1/tests/test_openai.py +58 -0
  76. kinescope-0.0.1/tests/test_otel.py +81 -0
  77. kinescope-0.0.1/tests/test_real_run.py +92 -0
  78. kinescope-0.0.1/tests/test_record_replay.py +69 -0
  79. kinescope-0.0.1/tests/test_runner.py +87 -0
  80. kinescope-0.0.1/tests/test_snapshots.py +111 -0
  81. kinescope-0.0.1/tests/test_stdlib.py +45 -0
  82. kinescope-0.0.1/tests/test_store.py +41 -0
  83. kinescope-0.0.1/tests/test_streaming.py +109 -0
  84. kinescope-0.0.1/tests/test_stress.py +211 -0
  85. kinescope-0.0.1/tests/test_tools.py +75 -0
  86. kinescope-0.0.1/tests/test_tui.py +101 -0
@@ -0,0 +1,19 @@
1
+ # EditorConfig — consistent formatting across editors. https://editorconfig.org
2
+ root = true
3
+
4
+ [*]
5
+ charset = utf-8
6
+ end_of_line = lf
7
+ insert_final_newline = true
8
+ trim_trailing_whitespace = true
9
+ indent_style = space
10
+ indent_size = 2
11
+
12
+ [*.{py,rs}]
13
+ indent_size = 4
14
+
15
+ [*.md]
16
+ trim_trailing_whitespace = false # trailing spaces are meaningful (hard line breaks)
17
+
18
+ [Makefile]
19
+ indent_style = tab
@@ -0,0 +1,7 @@
1
+ # Copy to `.env` and fill in real values. `.env` is gitignored; this file is not.
2
+ #
3
+ # Kinescope's core, tests, and the bundled demo need NO secrets — they run fully offline.
4
+ # An API key is only needed if you point an example at the real Anthropic API instead
5
+ # of a stub transport.
6
+
7
+ # ANTHROPIC_API_KEY=sk-ant-...
@@ -0,0 +1,23 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+
4
+ # Keep shell scripts LF even on Windows checkouts
5
+ *.sh text eol=lf
6
+
7
+ # Treat common binary assets as binary (no EOL munging, no bad diffs)
8
+ *.png binary
9
+ *.jpg binary
10
+ *.jpeg binary
11
+ *.gif binary
12
+ *.webp binary
13
+ *.ico binary
14
+ *.mp3 binary
15
+ *.wav binary
16
+ *.ogg binary
17
+ *.mp4 binary
18
+ *.glb binary
19
+ *.gltf binary
20
+ *.woff binary
21
+ *.woff2 binary
22
+ *.ttf binary
23
+ *.pdf binary
@@ -0,0 +1,32 @@
1
+ # CI — lint, typecheck, and test on every push / PR.
2
+ name: CI
3
+
4
+ on:
5
+ push:
6
+ branches: [main]
7
+ pull_request:
8
+
9
+ jobs:
10
+ check:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.11", "3.12", "3.13"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ cache: pip
22
+
23
+ - name: Install
24
+ run: pip install -e ".[dev]"
25
+
26
+ - name: Lint & typecheck
27
+ run: |
28
+ ruff check .
29
+ mypy src
30
+
31
+ - name: Test
32
+ run: pytest
@@ -0,0 +1,31 @@
1
+ name: Publish to PyPI
2
+
3
+ # Publishes to PyPI via Trusted Publishing (OIDC) — no API token required.
4
+ # Fires when you publish a GitHub Release, or manually from the Actions tab.
5
+ # The version published is whatever is in pyproject.toml at that commit; bump it
6
+ # before each release or PyPI will reject the upload as a duplicate.
7
+ on:
8
+ release:
9
+ types: [published]
10
+ workflow_dispatch:
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ publish:
17
+ runs-on: ubuntu-latest
18
+ permissions:
19
+ id-token: write # required: mints the OIDC token PyPI trusts
20
+ contents: read # required: for actions/checkout
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: "3.11"
26
+ - name: Build sdist + wheel
27
+ run: |
28
+ python -m pip install --upgrade build
29
+ python -m build
30
+ - name: Publish to PyPI
31
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,47 @@
1
+ # --- Base ignores (stack-agnostic) ---
2
+
3
+ # Secrets / local env — never commit real ones (see .env.example)
4
+ .env
5
+ .env.*
6
+ !.env.example
7
+ *.local
8
+
9
+ # AI assistant build instructions — kept local, never committed
10
+ CLAUDE.md
11
+ CLAUDE.local.md
12
+
13
+ # Editor / OS cruft
14
+ .vscode/*
15
+ !.vscode/extensions.json
16
+ !.vscode/launch.json
17
+ .idea/
18
+ .DS_Store
19
+ Thumbs.db
20
+ *.log
21
+
22
+ # Generic build / cache output
23
+ dist/
24
+ build/
25
+ out/
26
+ coverage/
27
+ .cache/
28
+ tmp/
29
+ *.tmp
30
+
31
+ # --- Stack-specific (Python) ---
32
+ .venv/
33
+ venv/
34
+ __pycache__/
35
+ *.py[cod]
36
+ *.egg-info/
37
+ .eggs/
38
+ .pytest_cache/
39
+ .mypy_cache/
40
+ .ruff_cache/
41
+ .coverage
42
+ htmlcov/
43
+
44
+ # Kinescope trace stores (recorded runs — local artifacts, not source).
45
+ # .eidetic/ is kept ignored for legacy traces recorded before the rename.
46
+ .kinescope/
47
+ .eidetic/
@@ -0,0 +1,451 @@
1
+ # Kinescope — Design
2
+
3
+ > `rr` for nondeterministic AI agents: capture every nondeterministic input so any run replays deterministically — and can be *branched*: "what if the model had picked the other tool here?"
4
+
5
+ **Status:** Design draft · **Language:** Python 3.11+ · **Stack target:** local-first library + CLI/TUI (cross-platform)
6
+
7
+ Name: **Kinescope** (kinescope memory = perfect total recall). Working codename — rename freely; the word is generic English and carries no usable trademark for dev tools, but do a quick PyPI/name check before publishing the package.
8
+
9
+ > **Privacy / secrets note (read first).** Kinescope records the full request/response of every LLM and tool call, which routinely contains API keys, auth headers, user PII, and proprietary prompts. Redaction is therefore a *core feature, not an afterthought*: Kinescope strips credential headers (`authorization`, `x-api-key`, `anthropic-*` auth) **by default** and exposes a scrubber hook for payload fields. Traces are local files by default; nothing leaves the machine unless the user exports it. See §6.6.
10
+
11
+ ---
12
+
13
+ ## 1. Concept
14
+
15
+ Debugging an agent today is archaeology through logs, made worse by nondeterminism: sampled model outputs, flaky tools, wall-clock and RNG drift. You cannot reliably reproduce the failure, so you cannot reliably fix it.
16
+
17
+ Kinescope is the systems answer. It sits at the **nondeterministic frontier** of an agent — the handful of places where the same code can produce different results: LLM calls, tool calls, the clock, the RNG/UUIDs, retrieval — and records the *output* of every crossing into an ordered event log plus periodic state snapshots. From that trace it can:
18
+
19
+ - **Replay** the run deterministically, feeding recorded outputs back instead of calling out, so the failure reproduces every time;
20
+ - **Branch** at any step *k*: override exactly one recorded event (swap a tool result, force a different completion), replay up to *k*, then **switch to live** execution for everything after — exploring the counterfactual path;
21
+ - **Scrub** the timeline in a terminal UI, inspecting each step's messages, tool I/O, and the JSON **diff** of agent state, with a one-key **fork**.
22
+
23
+ The thing a reader should "see": an agent fails a task; you `kinescope ui` the recorded run, scrub to step 7 where it called the wrong tool, hit **fork**, override that one tool result, and watch the branched run complete successfully — fully reproducible from the trace. That fork-and-fix is the entire pitch.
24
+
25
+ ### Engineering pillars (the 1–3 things that make or break this)
26
+
27
+ 1. **Transparent, total interception of the nondeterministic frontier.** Capture LLM (incl. **SSE streaming** and **async**), tools, clock, RNG/UUID — with a single global **sequence order** across all of them — *without the user rewriting their agent*. Get this wrong and replays drift. Approach: an **httpx transport shim** for HTTP boundaries (robust to SDK versions), a scoped **monkeypatch** for stdlib nondeterminism, and a **decorator/registry wrap** for tools — all funneling into one ordered log. (§4, §6.1)
28
+ 2. **Replay→live branching with honest divergence detection.** Replaying to *k* bit-for-bit, overriding one event, then *resuming live* while the recorder keeps capturing the new tail — and **detecting hidden nondeterminism** that escapes the shims instead of silently lying about determinism. (§6.3, §6.4)
29
+ 3. **State capture & diffing of document-shaped state at run length.** Content-addressed, deduplicated snapshots and lazy structural diffs so the timeline scrubs instantly even on long runs. (§6.5)
30
+
31
+ ---
32
+
33
+ ## 2. Goals / Non-goals
34
+
35
+ **Goals (v1 — each is testable):**
36
+
37
+ - Record a single-process agent's LLM + tool + clock + RNG/UUID boundaries to a local trace with **zero changes to agent logic** beyond wrapping it in a context manager and decorating tools.
38
+ - **Byte-stable deterministic replay**: a replayed run makes the identical sequence of boundary calls with identical inputs; any deviation is reported as a *divergence*, not hidden.
39
+ - Support both **sync and async**, and both **non-streaming and SSE-streaming** Anthropic Messages calls.
40
+ - **Branch** at step *k* with a single-event override and a clean replay→live handoff, producing a new child run linked to its parent.
41
+ - A **Textual TUI** to scrub steps and view message/tool I/O and state diffs, with fork.
42
+ - **Local-first, low-friction**: the recording core has a tiny dependency footprint (essentially `httpx`); storage is a `.kinescope/` dir (SQLite index + content-addressed blobs) with no external services.
43
+ - A provider-agnostic event schema (Anthropic adapter shipped) aligned with **OpenTelemetry GenAI** vocabulary so a second adapter and OTel export are cheap.
44
+
45
+ **Non-goals (v1) — deliberately out, with the "when":**
46
+
47
+ - **Reproducing provider-side sampling internals.** We record *outputs*; we never try to re-derive a completion from a seed/temperature. Determinism is at the *boundary*, by construction.
48
+ - **Distributed / multi-process / many-agent orchestration.** Single agent, single process first. Multi-process record-replay (shared clock/order across processes) is a hard future milestone.
49
+ - **Automatic root-cause analysis.** Kinescope gives you the deterministic substrate and the fork; it does not diagnose for you (an LLM-judge "explain this divergence" feature is a stretch).
50
+ - **A hosted SaaS / web dashboard.** CLI + TUI first; a web timeline is a stretch goal (§8 M5), not v1.
51
+ - **Framework-level instrumentation (LangGraph/CrewAI nodes).** We intercept at the SDK/HTTP boundary, which works *under* any framework. First-class framework adapters come later if demand appears.
52
+ - **Non-HTTP tool nondeterminism we can't see.** Tools that read files, hit databases via non-HTTP drivers, or spawn subprocesses are captured only via the `@kinescope.tool` wrapper; un-wrapped side effects are surfaced by the divergence detector, not magically captured.
53
+ - **Editing more than one event per fork in v1.** Single-event override keeps the counterfactual causal story clean; multi-edit forks are a later addition.
54
+
55
+ ---
56
+
57
+ ## 3. Tech stack
58
+
59
+ Verified **2026-06-28** against PyPI / official docs.
60
+
61
+ | Layer | Choice | Why |
62
+ |---|---|---|
63
+ | Language | **Python 3.11+** | The agent ecosystem is Python; 3.11 gives `tomllib`, `ExceptionGroup`, `Self`, and faster asyncio. The instrumentation lives where agents live. |
64
+ | LLM target | **`anthropic` 0.112.0** (Messages API) | First adapter; the user's ecosystem. Built on **httpx ≥0.25,<1**, which is exactly the seam we intercept. Made an *optional* extra — the engine itself only needs httpx. |
65
+ | Interception (HTTP) | **Custom `httpx` transport** | The SDK accepts `http_client=httpx.Client(transport=…)` (public, documented API) → we wrap the real transport. Robust to SDK version churn; captures raw request/response incl. SSE bodies; works sync **and** async. Far safer than monkeypatching SDK methods. |
66
+ | Interception (stdlib) | **Scoped monkeypatch** of `time`, `random`, `uuid` | Clock/RNG/UUID are stdlib; record each value drawn, replay in order. Patched only within the `record()`/`replay()` scope and restored on exit. |
67
+ | Trace index | **SQLite** (stdlib `sqlite3`, WAL mode) | Zero-dependency, embedded, transactional, great for the timeline's "events for run, ordered by seq" queries. The `TraceStore` interface keeps it swappable. |
68
+ | Trace payloads | **Content-addressed blob files** (BLAKE2b-256, gzip) | Large payloads (prompts, completions) live as deduplicated, compressed blobs outside SQLite; identical system prompts stored once. `hashlib.blake2b` + `gzip` are stdlib. |
69
+ | State diffs | **In-house canonical-JSON differ** (RFC 6902 / JSON-Patch shape) | Tiny, dependency-free; emits add/remove/replace ops over JSON pointers, rendered human-readably in the TUI. |
70
+ | CLI | **Typer** (`kinescope[cli]` extra) | Clean, typed, Click-based; behind an extra so the core stays minimal. |
71
+ | TUI | **Textual 8.2.7** (`kinescope[tui]` extra) | Modern, well-maintained terminal UI; gives the scrubbable timeline + fork demo without a web stack. |
72
+ | Pretty output | **Rich** (pulled by Typer/Textual) | Diff coloring, tables in `show`/`diff`. |
73
+ | Packaging | **`uv` + `hatchling`**, `pyproject.toml` | Fast, modern, lockfile-based; `kinescope` console entry point. |
74
+ | Test / lint | **pytest**, **ruff**, **mypy** | Standard. Replay determinism is itself the headline test target. |
75
+ | Storage adapter (later) | **`pymongo`** (`kinescope[mongo]` extra) | Document-shaped traces map cleanly to Mongo; ships post-v1 as a `MongoStore` implementing `TraceStore`. |
76
+
77
+ **Dependency story (the adoption lever):** the *core* engine depends on **`httpx` only**. `anthropic`, `typer`+`rich`, `textual`, and `pymongo` are all **extras**. `pip install kinescope` gives you record/replay; `pip install kinescope[anthropic,cli,tui]` gives the full experience. All licenses are permissive/commercial-friendly (anthropic MIT, httpx BSD, Textual MIT, Typer MIT, Rich MIT, pymongo Apache-2.0).
78
+
79
+ ---
80
+
81
+ ## 4. The trace model & interception contract — get this exactly right
82
+
83
+ Everything downstream (replay, branch, diff, divergence) is correct **iff** the trace and the interception contract are correct. This is the load-bearing core.
84
+
85
+ ### 4.1 The three invariants
86
+
87
+ 1. **Total order.** Every crossing of the nondeterministic frontier gets a single, process-global, monotonically increasing `seq`. Replay reconstructs exactly this order. (One `threading.Lock`-guarded counter in the active session; v1 is single-process.)
88
+ 2. **Output-authoritative replay.** On replay, a boundary *never* calls out; it returns the recorded `output` for the matching `seq`. The model is never re-sampled; tools never re-execute; `time.time()` returns the recorded float.
89
+ 3. **Input-verified matching.** Each boundary's *input* is canonicalized and hashed at record time. On replay, the live call's input hash is compared to the recorded one. Match → return recorded output. Mismatch (or wrong count) → **divergence** (policy-controlled, §6.4). This is what makes the determinism claim *honest*.
90
+
91
+ ### 4.2 Canonical input hashing
92
+
93
+ The hash must be **stable across runs** and ignore volatile-but-irrelevant fields, or every replay would false-positive a divergence.
94
+
95
+ ```python
96
+ # Canonicalize → BLAKE2b-256 hex. Used for matching, NOT for storage keys of output.
97
+ def canon_hash(kind: str, payload: dict) -> str:
98
+ norm = _strip_volatile(kind, payload) # see exclusions below
99
+ blob = json.dumps(norm, sort_keys=True, separators=(",", ":"),
100
+ ensure_ascii=False, default=_json_default).encode("utf-8")
101
+ return hashlib.blake2b(blob, digest_size=32).hexdigest()
102
+ ```
103
+
104
+ **Volatile fields excluded from the LLM input hash** (recorded in the raw blob, just not hashed): request `idempotency-key`, `x-request-id`, any `*-timestamp`/`date` header, retry counters, and SDK user-agent/version. **Kept (they change meaning):** model, messages, system, tools, tool_choice, temperature, top_p, max_tokens, stop sequences. For **tools**, the hash covers the tool name + canonicalized args. For **clock/RNG**, there is no meaningful input — they match purely by `(kind, seq)` position.
105
+
106
+ ### 4.3 Core types
107
+
108
+ ```python
109
+ from dataclasses import dataclass
110
+ from typing import Literal, Optional
111
+
112
+ BoundaryKind = Literal["llm", "tool", "clock", "rng", "retrieval"]
113
+
114
+ @dataclass(frozen=True, slots=True)
115
+ class Event:
116
+ run_id: str
117
+ seq: int # process-global order, 0-based
118
+ kind: BoundaryKind
119
+ name: str # "messages.create" | tool name | "time.time" | "uuid4" ...
120
+ input_hash: str # canon_hash(kind, input) — "" for clock/rng
121
+ input_ref: Optional[str] # blob id (BLAKE2b) of full input payload; None if trivial
122
+ output_ref: Optional[str] # blob id of full output payload
123
+ status: Literal["ok", "error"]
124
+ ts_wall: float # real wall time at record (informational; never used by replay)
125
+ dur_ms: float # informational
126
+ meta: dict # kind-specific, OTel-GenAI-aligned (see below)
127
+
128
+ @dataclass(frozen=True, slots=True)
129
+ class Snapshot:
130
+ run_id: str
131
+ after_seq: int # state as it was immediately after Event[after_seq]
132
+ state_ref: str # blob id of canonical-JSON state document
133
+ label: Optional[str] # e.g. "post-tool", user-supplied tag
134
+
135
+ @dataclass(frozen=True, slots=True)
136
+ class Run:
137
+ run_id: str # sortable: f"{base32(ts_ms)}-{rand4}"
138
+ label: str
139
+ created_at: float
140
+ status: Literal["recording", "complete", "error", "diverged"]
141
+ parent_run_id: Optional[str] # set for branched runs
142
+ forked_at_seq: Optional[int] # the k of the fork
143
+ overrides: list[dict] # the single-event override applied at the fork
144
+ sdk_versions: dict # {"kinescope": "...", "anthropic": "0.112.0", "python": "3.11.x"}
145
+ divergences: list[dict] # populated by replay/branch; [] when clean
146
+ ```
147
+
148
+ `meta` for an `llm` event mirrors **OpenTelemetry GenAI** semantic conventions so the data speaks the industry's language and can later export as `gen_ai.*` spans:
149
+
150
+ ```python
151
+ meta = {
152
+ "gen_ai.system": "anthropic",
153
+ "gen_ai.request.model": "claude-opus-4-8",
154
+ "gen_ai.usage.input_tokens": 1234,
155
+ "gen_ai.usage.output_tokens": 567,
156
+ "gen_ai.response.finish_reasons": ["tool_use"],
157
+ "stream": True,
158
+ "http.status": 200,
159
+ }
160
+ ```
161
+
162
+ ### 4.4 The interception/replay contract (why the httpx seam works for streaming)
163
+
164
+ The LLM boundary is intercepted at the **httpx transport**, so we capture the exact wire exchange — including the SSE event stream — and can **re-materialize it** on replay without the network. The Anthropic SDK's own SSE parser then re-parses identical bytes, yielding identical typed objects.
165
+
166
+ ```python
167
+ class KinescopeTransport(httpx.BaseTransport): # + async sibling
168
+ def __init__(self, inner: httpx.BaseTransport, session: "Session"):
169
+ self._inner, self._s = inner, session
170
+
171
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
172
+ seq = self._s.next_seq()
173
+ inp = _request_to_payload(request) # method,url,headers(redacted),body(json/sse)
174
+ if self._s.mode == "replay":
175
+ ev = self._s.expect(seq, kind="llm", input_hash=canon_hash("llm", inp))
176
+ body = self._s.store.get_blob(ev.output_ref) # recorded raw response bytes
177
+ return httpx.Response(ev.meta["http.status"], headers=ev.meta["resp_headers"],
178
+ stream=httpx.ByteStream(body), request=request)
179
+ # record (or live tail of a branch): call out, tee the body, log the event
180
+ resp = self._inner.handle_request(request)
181
+ raw = resp.read() # buffers SSE/non-SSE alike
182
+ self._s.record(Event(kind="llm", seq=seq, input_hash=canon_hash("llm", inp),
183
+ input_ref=self._s.store.put_blob(inp),
184
+ output_ref=self._s.store.put_blob(raw), ...))
185
+ return httpx.Response(resp.status_code, headers=resp.headers,
186
+ stream=httpx.ByteStream(raw), request=request)
187
+ ```
188
+
189
+ > **Streaming caveat, stated honestly:** buffering the SSE body means a replayed stream yields its chunks *all at once* rather than time-spaced. That is correct for content (identical tokens, identical tool_use blocks) and is the right tradeoff for deterministic debugging; we are reproducing *what*, not *the latency of*, the stream. If a user opts into the SDK's `aiohttp` transport extra instead of httpx, the shim doesn't see it — the divergence detector will flag the un-captured call. (Documented limitation.)
190
+
191
+ Clock/RNG/UUID and tools do **not** go through httpx; they are intercepted by monkeypatch and decorator respectively (§6.1), but obey the same `Event` contract and the same global `seq`.
192
+
193
+ ---
194
+
195
+ ## 5. Architecture
196
+
197
+ **Pattern: ports-and-adapters (hexagonal) around a deterministic core.** The core (`session`, `record`, `replay`, `branch`, event model) knows nothing about *how* boundaries are intercepted or *where* traces live — those are adapters. This is what makes "add OpenAI", "add MongoStore", "add OTel export" cheap, and keeps the determinism logic testable in isolation.
198
+
199
+ ```
200
+ ┌────────────────────── user's agent code ──────────────────────┐
201
+ │ with kinescope.record("run"): │
202
+ │ client = anthropic.Anthropic(http_client=ses.http_client())│
203
+ │ @kinescope.tool def search(q): ... │
204
+ │ kinescope.snapshot(state) │
205
+ └───────────────┬───────────────────────────────────────────────┘
206
+ INTERCEPTION ADAPTERS │ (every crossing → Event with global seq)
207
+ ┌───────────────┬──────────────────┼───────────────────┬───────────────────┐
208
+ │ httpx transport│ tool decorator/ │ clock/rng/uuid │ retrieval (HTTP │
209
+ │ shim (LLM) │ registry wrap │ monkeypatch │ via same shim) │
210
+ └───────┬────────┴────────┬─────────┴─────────┬─────────┴─────────┬─────────┘
211
+ └─────────────────┴──── Session (mode: record│replay│branch) ───────┘
212
+ • global seq counter • divergence detector
213
+ • redaction • snapshot capture
214
+ │
215
+ ┌─────────────────────┴─────────────────────┐
216
+ │ CORE ENGINE │
217
+ │ record.py · replay.py · branch.py · model │
218
+ └─────────────────────┬─────────────────────┘
219
+ │ TraceStore (port)
220
+ ┌─────────────────────┴─────────────────────┐
221
+ │ LocalStore (default): SQLite index + blobs/ │ ← MongoStore (later)
222
+ └─────────────────────┬─────────────────────┘
223
+ │
224
+ ┌──────────────────────────┴──────────────────────────┐
225
+ │ PRESENTATION │
226
+ │ cli.py (Typer) · tui/ (Textual) · diff renderer │
227
+ └───────────────────────────────────────────────────────┘
228
+ ```
229
+
230
+ Data flow per mode:
231
+
232
+ ```
233
+ record: agent → adapters → Event(seq,k) + Snapshot → TraceStore
234
+ replay: agent → adapters return recorded output by (seq, input_hash) → deterministic run + divergence report
235
+ branch: replay seq<k → override Event[k] → adapters go LIVE for seq>k → new child Run recorded
236
+ view: TraceStore → CLI/TUI: scrub seq · per-step I/O · JSON-Patch state diff · fork
237
+ ```
238
+
239
+ Repo layout:
240
+
241
+ ```
242
+ kinescope/
243
+ src/kinescope/
244
+ __init__.py # public API: record(), replay(), tool, snapshot, http_client()
245
+ session.py # Session: mode, global seq, divergence, redaction
246
+ model.py # Event, Snapshot, Run, BoundaryKind, canon_hash
247
+ record.py # record-mode logic
248
+ replay.py # replay-mode logic + divergence detector
249
+ branch.py # fork@k, single-event override, replay→live switch
250
+ intercept/
251
+ http.py # KinescopeTransport (sync+async) for LLM/retrieval
252
+ stdlib.py # clock/rng/uuid monkeypatch (scoped)
253
+ tools.py # @tool decorator + instrument_tools(registry)
254
+ adapters/
255
+ anthropic.py # raw exchange → OTel-aligned meta; output reconstruction
256
+ store/
257
+ base.py # TraceStore port
258
+ local.py # SQLite index + content-addressed blobs (default)
259
+ diff.py # canonical JSON + RFC6902-shape differ
260
+ cli.py # Typer: record/replay/ls/show/diff/fork/ui
261
+ tui/ # Textual timeline app
262
+ examples/
263
+ weather_agent.py # the demo agent (picks wrong tool → fork fixes it)
264
+ tests/
265
+ README.md ROADMAP.md DESIGN.md PROGRESS.md CLAUDE.md
266
+ ```
267
+
268
+ ---
269
+
270
+ ## 6. Core systems
271
+
272
+ ### 6.1 Interception layer
273
+
274
+ **What:** turn every boundary crossing into an `Event` with the global `seq`, transparently.
275
+
276
+ - **LLM / retrieval (HTTP):** `session.http_client()` returns an `httpx.Client`/`AsyncClient` whose transport is `KinescopeTransport` (§4.4). The user passes it to `anthropic.Anthropic(http_client=…)`. A convenience `kinescope.instrument(client)` swaps the transport on an already-built client for the zero-reconstruction path.
277
+ - **Tools:** `@kinescope.tool` wraps a callable; `kinescope.instrument_tools(mapping)` wraps a name→callable registry in place. Records `(name, canon args)` → return/raise.
278
+
279
+ ```python
280
+ def tool(fn=None, *, name=None):
281
+ def wrap(f):
282
+ @functools.wraps(f)
283
+ def inner(*a, **kw):
284
+ ses = active_session()
285
+ if ses is None: return f(*a, **kw) # no-op outside a session
286
+ seq = ses.next_seq(); inp = {"args": a, "kwargs": kw}
287
+ if ses.mode == "replay" and not ses.is_live_after_fork(seq):
288
+ ev = ses.expect(seq, "tool", canon_hash("tool", inp), name=name or f.__name__)
289
+ return ses.store.get_json(ev.output_ref) # tool does NOT execute
290
+ out = f(*a, **kw) # record / live-tail: execute
291
+ ses.record_tool(seq, name or f.__name__, inp, out)
292
+ return out
293
+ return inner
294
+ return wrap(fn) if fn else wrap
295
+ ```
296
+
297
+ - **Clock / RNG / UUID:** within a session, `time.time/monotonic/perf_counter`, `datetime.now/utcnow`, `random.random/randint/...`, and `uuid.uuid4` are patched to **record the value drawn** and, on replay, **return the recorded value by seq**. We record outputs (not seeds) — robust across Python versions, consistent with every other boundary. Patches are installed on `__enter__` and restored on `__exit__` (even on exception).
298
+
299
+ ### 6.2 Recorder
300
+
301
+ Opens a `Run`, sets `Session.mode="record"`, installs adapters, captures `Event`s and `Snapshot`s through the `TraceStore`, finalizes status on exit. Public surface:
302
+
303
+ ```python
304
+ with kinescope.record("nightly-repro", store=kinescope.LocalStore(".kinescope")) as ses:
305
+ run_my_agent() # boundaries auto-captured
306
+ print(ses.run_id) # e.g. "01JZ8…-a3f1"
307
+ ```
308
+
309
+ ### 6.3 Replay engine & branch engine
310
+
311
+ **Replay:** `Session.mode="replay"`; adapters consult the log instead of calling out. The engine walks user code again; `expect(seq, kind, input_hash)` returns the recorded output or raises/records a divergence. Output for `llm` is re-materialized as raw bytes through the transport so the SDK rebuilds identical objects.
312
+
313
+ **Branch (the novel hook):**
314
+
315
+ ```python
316
+ new_id = kinescope.fork(
317
+ run_id, at=7,
318
+ override={"kind": "tool", "output": {"temp_f": 71, "city": "Paris"}}, # OR llm completion
319
+ )
320
+ # semantics: replay events 0..6 deterministically; substitute the override AS event 7's output;
321
+ # from seq 8 onward, Session flips to LIVE — real LLM/tool calls — recording a NEW child Run
322
+ # whose parent_run_id=run_id, forked_at_seq=7, overrides=[...].
323
+ ```
324
+
325
+ The replay→live switch is a single boolean keyed on `seq > forked_at_seq`. The branched tail is recorded exactly like a fresh run, so branches are themselves replayable and forkable (a tree of runs).
326
+
327
+ ### 6.4 Divergence detector (the honesty mechanism)
328
+
329
+ During replay/branch-prefix, every boundary is checked:
330
+
331
+ - **Input mismatch:** live `input_hash` ≠ recorded → record a `divergence` `{seq, kind, expected, actual}`.
332
+ - **Order/count mismatch:** agent makes a call at a `seq` of a different `kind`, or runs off the end of the log, or finishes early.
333
+ - **Un-captured nondeterminism:** a boundary that *should* be in the log isn't (e.g., an un-wrapped tool, an aiohttp-transport call) shows up as an order mismatch — surfaced, not swallowed.
334
+
335
+ Policy via `record()/replay(policy=…)`: `strict` (raise on first), `warn` (default — log, continue using recorded-by-position), `off`. Divergences are written to `Run.divergences` and shown in `show`/TUI. **This is the feature that lets Kinescope claim determinism honestly:** it tells you precisely where the guarantee leaked.
336
+
337
+ ### 6.5 State snapshots & diffs
338
+
339
+ - **Capture:** `kinescope.snapshot(obj, label=None)` serializes a document-shaped state (the messages list, scratchpad, memory — user's choice) to canonical JSON and stores it content-addressed, tagged `after_seq = current seq`. Optionally `record(snapshot=lambda: agent.state)` auto-snapshots after each `llm` event.
340
+ - **Dedup:** identical states (common across adjacent steps) collapse to one blob via BLAKE2b id.
341
+ - **Diff:** `diff.py` computes an RFC 6902-shaped patch (`add`/`remove`/`replace` over JSON pointers) between any two snapshots, **lazily** (only when a step is viewed), rendered with Rich coloring. No diff is precomputed → scrubbing stays O(1).
342
+
343
+ ```python
344
+ # kinescope diff <run> 6 7 →
345
+ # replace /messages/8/content "I'll use convert_units" → "I'll use get_weather"
346
+ # add /scratchpad/last_tool "get_weather"
347
+ ```
348
+
349
+ ### 6.6 Storage (`TraceStore` port + `LocalStore`)
350
+
351
+ ```python
352
+ class TraceStore(Protocol):
353
+ def create_run(self, run: Run) -> None: ...
354
+ def update_run(self, run: Run) -> None: ...
355
+ def get_run(self, run_id: str) -> Run: ...
356
+ def list_runs(self) -> list[Run]: ...
357
+ def append_event(self, ev: Event) -> None: ...
358
+ def events(self, run_id: str) -> list[Event]: ... # ordered by seq
359
+ def put_snapshot(self, snap: Snapshot) -> None: ...
360
+ def snapshots(self, run_id: str) -> list[Snapshot]: ...
361
+ def put_blob(self, data: bytes | dict) -> str: ... # → BLAKE2b id, dedup, gzip
362
+ def get_blob(self, blob_id: str) -> bytes: ...
363
+ ```
364
+
365
+ `LocalStore` layout (everything under `.kinescope/`):
366
+
367
+ ```
368
+ .kinescope/
369
+ index.db # SQLite (WAL): runs, events, snapshots tables
370
+ blobs/<aa>/<blake2b-hex>.json.gz # content-addressed, gzipped, deduplicated
371
+ ```
372
+
373
+ **Redaction** runs *before* `put_blob` on any input payload: credential headers dropped, plus a user `scrubber(payload) -> payload` hook for body fields (e.g., redact `messages[*].content` matching a regex). On by default for auth headers; opt-in for body scrubbing.
374
+
375
+ ### 6.7 CLI & TUI surface
376
+
377
+ ```
378
+ kinescope record -- python weather_agent.py # run an agent under recording
379
+ kinescope ls # list runs (id, label, status, #events, divergences)
380
+ kinescope show <run-id> [--step k] # event detail: messages / tool I/O / meta
381
+ kinescope diff <run-id> <a> <b> # state diff between two steps
382
+ kinescope replay <run-id> [--policy strict] # deterministic replay + divergence report
383
+ kinescope fork <run-id> --at k --override-tool '{"temp_f":71}' # → new child run id
384
+ kinescope ui <run-id> # Textual timeline (scrub · inspect · fork)
385
+ ```
386
+
387
+ `record -- <cmd>` runs the user's program with an env flag that auto-activates a default session (for programs that call `kinescope.record()` themselves, it's a no-op wrapper). The first-class path is the in-code `with kinescope.record(...)`.
388
+
389
+ ---
390
+
391
+ ## 7. TUI — the timeline (where the demo lives)
392
+
393
+ A three-pane Textual app; the fork-and-fix gif is recorded here.
394
+
395
+ ```
396
+ ┌ Kinescope ── run 01JZ8…-a3f1 "weather repro" ⚠ 0 divergences ──────────────────────┐
397
+ │ STEPS │ STEP 7 · tool · get_weather │ STATE DIFF (6→7) │
398
+ │ 4 llm messages.crea │ input { "city": "Paris" } │ replace /messages/8│
399
+ │ 5 tool get_weather │ output { "temp_f": 71, "sky": "clear"} │ "use convert" → │
400
+ │ 6 llm messages.crea │ status ok · 142ms │ "use get_weather"│
401
+ │ ▸7 tool convert_units │ ───────────────────────────────────── │ add /scratchpad/… │
402
+ │ 8 llm messages.crea │ [ f ] fork here [ enter ] open │ │
403
+ └─ ↑/↓ scrub · f fork · d diff · / filter · q quit ──────────────────────────────────┘
404
+ ```
405
+
406
+ - **Steps pane:** the event log, color-coded by kind, fork points marked `⑂`, divergences marked `⚠`.
407
+ - **Detail pane:** selected step's normalized message / tool I/O / `meta`.
408
+ - **Diff pane:** lazy JSON-Patch diff vs. the previous snapshot.
409
+ - **`f` (fork):** prompts for the single-event override, calls `branch.fork`, and (stretch) drops you into the new child run live. The core feel-good loop: *scrub → spot the bad step → fork → watch it go right.*
410
+
411
+ ---
412
+
413
+ ## 8. Milestones
414
+
415
+ Top-down, each independently runnable. Scaffold turns these into `ROADMAP.md` (adding explicit Test steps).
416
+
417
+ - **M0 — Walking skeleton (record→replay one call).** `with kinescope.record()` + `KinescopeTransport` capture a single non-streaming Anthropic `messages.create` to `LocalStore`; `kinescope replay <id>` re-runs a one-call example agent returning the recorded completion; `kinescope ls`/`show`. **Proves** the end-to-end record→replay loop and the store on the simplest agent.
418
+ - **M1 — Full frontier + ordering + divergence.** Add `@kinescope.tool`, clock/RNG/UUID monkeypatch, the global `seq`, **async** + **SSE streaming** capture, and the divergence detector. Deterministically replay a multi-step, tool-using agent. **Proves** pillar 1 (total interception) and honest determinism.
419
+ - **M2 — State snapshots & diffs.** `kinescope.snapshot()`, content-addressed dedup, lazy RFC 6902 diffs; `show --step k`, `diff a b`. **Proves** pillar 3 (state diffing) and makes runs inspectable.
420
+ - **M3 — Branching (the novel hook).** `kinescope fork --at k --override …`, replay→live switch, child-run lineage, re-recorded tail. **Proves** pillar 2 — the counterfactual that makes Kinescope more than a tracer.
421
+ - **M4 — Timeline TUI + flagship demo.** Textual three-pane scrub/inspect/diff with `f`-to-fork; polish divergence display; record the fork-and-fix gif against `examples/weather_agent.py`. **Proves** the product — the pitch in one screen recording.
422
+ - **M5 — Reach (stretch, pick by signal).** OpenAI adapter (second provider validates the abstraction) · OTel `gen_ai.*` span export · `MongoStore` · shareable/exportable trace bundles · minimal web timeline.
423
+
424
+ **Ship publicly at M3–M4** (replay + branch + a demo is the story).
425
+
426
+ ---
427
+
428
+ ## 9. Risks / open questions
429
+
430
+ - **Hidden nondeterminism escapes the shims** (un-wrapped tools, file/DB reads, threads, dict/set ordering). → The **divergence detector** is the mitigation *and* the honest framing: we don't claim magic, we claim "deterministic at instrumented boundaries, and we'll tell you when something leaked." Document the wrap-your-tools contract clearly.
431
+ - **SSE replay loses streaming timing** (chunks arrive batched). → Accept it: debugging needs *what*, not *when*. Note in docs; a "paced replay" option is a possible later nicety.
432
+ - **Alternate SDK transports** (`anthropic[aiohttp]`) bypass the httpx seam. → Detect as an order mismatch and warn; httpx is the SDK default, so the common path is covered. An aiohttp adapter is a later add.
433
+ - **Replay→live branch divergence at the seam** (the live tail behaves unexpectedly because prefix state wasn't perfectly reconstructed). → Snapshots + divergence checks bracket the fork; the branch records a fresh trace so the result is itself inspectable. Open question: how aggressively to snapshot around fork points (every step near *k* vs. just at *k*).
434
+ - **Large traces / blob bloat** on long runs with big prompts. → Content-addressed dedup + gzip handles repetition; add a retention/prune command if needed.
435
+ - **Open question — auto-snapshot ergonomics.** Is a single `kinescope.snapshot(state)` call enough, or do we need framework-aware auto-capture of the messages list? Resolve in M2 against the real example agent.
436
+ - **Open question — multi-process / multi-agent.** Out for v1; the global-seq design is single-process. A future cross-process clock/order is a genuine research-grade extension (and a strong systems flex if pursued).
437
+
438
+ ---
439
+
440
+ ## 10. References
441
+
442
+ Prior art and standards the design leans on (verified **2026-06-28**):
443
+
444
+ - **rr** (Mozilla) & **Pernosco** — deterministic record-replay for native processes; the lineage and the bar for "replay any run." Kinescope is this idea, moved to the LLM-agent boundary.
445
+ - **VCR.py** (vcrpy 8.x) — HTTP record/replay via "cassettes." Kinescope generalizes the *technique* (transport-level record/replay) but adds agent state, global ordering across non-HTTP boundaries, and counterfactual branching — none of which VCR targets.
446
+ - **LangGraph time-travel / checkpointers** — fork/replay of agent runs, but **framework-locked** and rewinds *graph state* rather than replaying recorded *nondeterministic inputs*. Kinescope works *under* any framework at the SDK/HTTP seam.
447
+ - **Agent observability** (LangSmith, Langfuse, AgentOps, Arize Phoenix, W&B Weave, OpenLLMetry/Traceloop, Laminar) — strong *tracing/visualization*, but read-only: no deterministic replay, no single-event counterfactual fork. Kinescope's unoccupied niche.
448
+ - **OpenTelemetry GenAI semantic conventions** (`gen_ai.*` spans/events, Development status as of 2026) — the `Event.meta` vocabulary aligns to it for credibility and a future export path. <https://opentelemetry.io/docs/specs/semconv/gen-ai/>
449
+ - **Key libraries:** `anthropic` 0.112.0 (MIT; httpx-based) · `httpx` ≥0.25,<1 (BSD) · `textual` 8.2.7 (MIT) · `typer`/`rich` (MIT) · `pymongo` (Apache-2.0, later). Stdlib: `sqlite3`, `hashlib.blake2b`, `gzip`, `time`, `random`, `uuid`.
450
+ - **Stack reuse note:** the `MongoStore` adapter ties Kinescope to a document-DB stack if/when the author wants persistence beyond local files; the `TraceStore` port keeps that a drop-in, not a rewrite.
451
+ ```
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Satchel Hamilton
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.