Replay your coding agent sessions as a map and a timeline
Python agent-observabilityai-agentsclaudeclaude-codecodexcoding-agentscursordeveloper-toolsdevtoolsgithub-copilotkirollmobservabilityopencodeprivacypythonsession-replaytypescriptvisualization
Initial public release of agentplay
Taradepan R7de8271bc9e4
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlnew file mode 100644index 0000000..f39ed30--- /dev/null+++ b/.github/dependabot.yml@@ -0,0 +1,14 @@+version: 2+updates:+ # Actions are pinned by commit SHA, so they only move when this opens a PR.+ - package-ecosystem: "github-actions"+ directory: "/"+ schedule:+ interval: "weekly"+ # Wait a week after a release before proposing it.+ cooldown:+ default-days: 7+ groups:+ actions:+ patterns:+ - "*"diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..f68babc--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,94 @@+name: ci++on:+ workflow_call:+ push:+ branches: [main]+ pull_request:++permissions:+ contents: read++jobs:+ python:+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ python: ["3.11", "3.12", "3.13", "3.14"]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: ${{ matrix.python }}+ - run: python -m pip install -e "python[dev]"+ - run: python -m pytest -q+ working-directory: python+ - run: python -m ruff check src tests+ working-directory: python+ if: matrix.os == 'ubuntu-latest'++ viewer:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ package_json_file: viewer/package.json+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 22+ cache: pnpm+ cache-dependency-path: viewer/pnpm-lock.yaml+ - run: pnpm install --frozen-lockfile+ working-directory: viewer+ - run: pnpm run typecheck+ working-directory: viewer+ - run: pnpm test+ working-directory: viewer+ - run: pnpm run build+ working-directory: viewer++ hygiene:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - run: python3 scripts/check_clean.py++ package:+ needs: [python, viewer]+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ package_json_file: viewer/package.json+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 22+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ - run: cd viewer && pnpm install --frozen-lockfile && pnpm run build+ - run: rm -rf python/src/agentplay/viewer && cp -r viewer/dist python/src/agentplay/viewer+ - run: python -m pip install build && python -m build python+ - name: smoke-test the wheel and the sdist+ run: |+ for dist in python/dist/*.whl python/dist/*.tar.gz; do+ rm -rf /tmp/w && python -m venv /tmp/w && /tmp/w/bin/pip install "$dist"+ /tmp/w/bin/agentplay --version+ /tmp/w/bin/python -c "import agentplay.server as s; assert s.viewer_root() is not None, 'viewer not bundled'; assert (s.viewer_root() / 'THIRD_PARTY_LICENSES.txt').is_file(), 'viewer licenses not bundled'"+ done+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: dist+ path: python/dist/diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..68190bd--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,60 @@+name: release++on:+ push:+ tags: ["v*"]++permissions:+ contents: read++jobs:+ # Fail early when the tag, pyproject.toml and __version__ disagree.+ version:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ - name: tag matches package versions+ run: |+ python - <<'EOF'+ import os, re, sys, tomllib+ tag = os.environ["GITHUB_REF_NAME"].removeprefix("v")+ with open("python/pyproject.toml", "rb") as f:+ pyproject = tomllib.load(f)["project"]["version"]+ with open("python/src/agentplay/__init__.py", encoding="utf-8") as f:+ init = re.search(r'^__version__\s*=\s*"([^"]+)"', f.read(), re.M).group(1)+ print(f"tag={tag} pyproject={pyproject} __init__={init}")+ if not (tag == pyproject == init):+ sys.exit("tag, python/pyproject.toml and agentplay.__version__ must all match")+ EOF++ # Same checks as every PR: tests on 3 OSes x 4 Pythons, viewer tests, and the+ # `package` job, which builds the wheel and sdist, smoke-tests the wheel and+ # uploads both as the `dist` artifact.+ ci:+ uses: ./.github/workflows/ci.yml+ permissions:+ contents: read++ # Publishes the `dist` artifact built by `ci`. Nothing is built here, so only+ # the download and the publish action run with the OIDC token.+ pypi:+ needs: [version, ci]+ runs-on: ubuntu-latest+ environment:+ name: pypi+ url: https://pypi.org/p/agentplay+ permissions:+ id-token: write # PyPI trusted publishing and attestations+ steps:+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: dist+ path: python/dist/+ - uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2+ with:+ packages-dir: python/dist/diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..d859794--- /dev/null+++ b/.gitignore@@ -0,0 +1,12 @@+node_modules/+dist/+build/+*.egg-info/+__pycache__/+.pytest_cache/+.ruff_cache/+.venv/+.DS_Store+# The built viewer is copied into the Python package by `make viewer`;+# release CI rebuilds it, so it is never committed.+python/src/agentplay/viewer/diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..e8fe6f7--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,7 @@+# Code of conduct++This project follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).++In short: be respectful, assume good faith, give and accept constructive feedback, and focus on what is best for the people using and building this tool. Harassment, personal attacks and discriminatory language are not acceptable in issues, pull requests, discussions or any other project space.++Report unacceptable behaviour privately to the maintainers at [[email protected]](mailto:[email protected]). If you would rather not use email, the repository's **Security → Report a vulnerability** form also reaches only the maintainers. All reports are reviewed and investigated promptly and fairly, and the reporter's privacy is respected. Maintainers who do not follow the code of conduct may be removed from the project.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..367b3df--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,68 @@+# Contributing to agentplay++Thanks for helping. This page covers the most useful kinds of contribution, the rules every change has to keep, and how to run everything locally.++## Before you build a feature++agentplay is maintained by Entelligence on a product roadmap. Parsers for new agents, bug fixes and documentation are always welcome as pull requests. For a new feature, please open an issue first so we can agree it fits before you spend time on it; we may decline a good feature that doesn't.++## Ground rules++1. **Privacy is the product.** A change must never cause a map, a log line, or the viewer to contain prompt text, model output, tool input or output, file contents, or command arguments. The full rules are in [docs/format.md](docs/format.md#redaction-contract). If you are not sure, ask in the PR.+2. **No new network calls.** The only one is the opt-in email signup in `account.py`, and the README promises that. Session data never goes over the network, and a feature that needs the network does not belong in the core tool. `tests/test_account.py` fails if `urllib.request` appears in any other file.+3. **No runtime dependencies** for the Python package. It runs on the standard library so that `uvx agentplay` starts instantly and installs cleanly everywhere. Dev and test dependencies are fine.+4. **Keep internal references out.** `make check` runs `scripts/check_clean.py`, which rejects ticket ids, private links and credential shapes.++## Setup++```bash+make setup # python/.venv (pytest, ruff, jsonschema) + viewer/node_modules+make test # everything+make check # lint + typecheck + tests + hygiene guard, what CI runs+```++**On Windows**, `make` works under Git Bash or MSYS2, or in WSL. Without `make`, follow the PowerShell steps under "Windows" in the [README](README.md#install). To run the Python tests directly:++```powershell+cd python+.venv\Scripts\python -m pytest -q+```++Python code lives in `python/src/agentplay`, and its tests are in `python/tests`, with parser tests in `python/tests/core`. The viewer lives in `viewer/`; see [viewer/README.md](viewer/README.md).++## Adding an agent++A parser turns one agent's transcript into the shared span shape: a root Session span, one Turn span per turn, and one tool span per tool call. Everything downstream (the builder, the viewer) then works without further changes.++1. **Get real transcripts.** Use two or three real sessions from the agent, and include one with a failed tool call if you can. Strip any personal content before committing them as fixtures. Keep them small.+2. **Write the parser** as `python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/<agent>.py`, exposing `parse_<agent>(data, trace_id, user_id=None, project_name=None) -> (TraceData, list[SpanData])`. [`codex.py`](python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/codex.py) is a good one to copy. Map the agent's tool names onto the canonical taxonomy in [`tool_taxonomy.py`](python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py) so that reads, edits and shell calls are classified correctly.+3. **Register it:**+ - add a value to `AgentType` and a sniffing rule to `detect_agent` in `parsers/base.py`;+ - export it from `parsers/__init__.py`;+ - add an indexer for the agent's home layout in `_sources/local/source.py`.+4. **If the agent stores sessions in a database** rather than files, add a decoder to [`materialize.py`](python/src/agentplay/materialize.py) that writes one NDJSON transcript per session into the cache, following the OpenCode one. Open databases read-only (`mode=ro&immutable=1`), or copy them first if they are WAL-mode and may be live.+5. **Tell discovery where it lives.** Add the default home, and a `AGENTPLAY_<AGENT>_HOMES` override, to `Homes` in [`discover.py`](python/src/agentplay/discover.py). Add the agent to `AGENTS`, and to the tables in the README.+6. **Test it.** Add parser tests in `python/tests/core/`. Also add one test that builds a map from your fixture and asserts that no text from it appears in the map (see `test_builder_never_leaks_free_text`).++## Changing the format++`agentplay/v1` only grows:++- add fields, never rename or repurpose one;+- update [docs/format.md](docs/format.md), [schema/agentplay-v1.schema.json](schema/agentplay-v1.schema.json) and the viewer's zod schema (`viewer/src/core/schema.ts`) in the same PR;+- keep new fields optional for readers, since older maps will not have them.++## Pull requests++- Keep each PR to one change, and include tests.+- Run `make check` before pushing.+- For UI changes, attach before and after screenshots in light and dark (`pnpm screenshots` in `viewer/`).+- By contributing, you agree that your contribution is licensed under the Apache License 2.0.++## Releasing++Maintainers: see [docs/RELEASING.md](docs/RELEASING.md) for the release steps.++## Code of conduct++Participation in this project is governed by the [Code of Conduct](CODE_OF_CONDUCT.md).diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/Makefile b/Makefilenew file mode 100644index 0000000..cd311cf--- /dev/null+++ b/Makefile@@ -0,0 +1,46 @@+VENV := python/.venv+# Windows venvs put the interpreter in Scripts/ (GNU make under Git Bash or MSYS2; `OS` is set by Windows).+ifeq ($(OS),Windows_NT)+PY ?= python+VPY := $(VENV)/Scripts/python.exe+else+PY ?= python3+VPY := $(VENV)/bin/python+endif++.PHONY: setup test test-python test-viewer check lint viewer run clean++setup:+ $(PY) -m venv $(VENV)+ $(VPY) -m pip install -q --upgrade pip+ $(VPY) -m pip install -q -e "python[dev]"+ cd viewer && pnpm install++test: test-python test-viewer++test-python:+ cd python && ../$(VPY) -m pytest -q++test-viewer:+ cd viewer && pnpm test++lint:+ cd python && ../$(VPY) -m ruff check src tests+ cd viewer && pnpm run typecheck++check: lint test+ $(PY) scripts/check_clean.py++# Build the web viewer (this also writes dist/THIRD_PARTY_LICENSES.txt) and copy it into the Python package+# so `agentplay view` serves it.+viewer:+ cd viewer && pnpm run build+ rm -rf python/src/agentplay/viewer+ cp -r viewer/dist python/src/agentplay/viewer++run:+ cd python && ../$(VPY) -m agentplay++clean:+ rm -rf python/.venv python/dist viewer/dist viewer/node_modules python/src/agentplay/viewer+ find . -name __pycache__ -prune -exec rm -rf {} +diff --git a/NOTICE b/NOTICEnew file mode 100644index 0000000..78da9dd--- /dev/null+++ b/NOTICE@@ -0,0 +1,13 @@+Agentplay+Copyright 2026 Entelligence AI, Inc.++This product is licensed under the Apache License, Version 2.0 (see LICENSE).++This product includes ideas and small, clearly scoped data tables from the+following open-source projects. No source file from either project is copied+or linked; see THIRD_PARTY_NOTICES.md for exactly what was used.++ * SuperBased Observer (https://github.com/superbasedapp/observer)+ Apache License 2.0, Copyright 2026 Gaja AI.+ * agentacct (https://github.com/mikehasa/agentacct)+ MIT License, Copyright (c) 2026 agentacct contributors.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..26789c4--- /dev/null+++ b/README.md@@ -0,0 +1,314 @@+# agentplay++**See what your coding agent actually did. Replay every session as a map and a timeline: what it read, what it edited, what failed, and what it shipped. Local, open source, works across Claude Code, Codex, Cursor, Copilot, OpenCode and Kiro.**++```bash+uvx agentplay+```++That one command finds the agent sessions already on your machine, builds a redacted replay of each one, and opens a local viewer. No account and no API key are required, and your session data never leaves your machine. The only network call is an optional email signup in the viewer, described under [Privacy](#privacy); set `AGENTPLAY_NO_NETWORK=1` to switch it off.++++<sub>Screenshot of the bundled demo session (synthetic data). Dark mode: [docs/images/explorer-dark.png](docs/images/explorer-dark.png).</sub>++---++## Contents++- [Why this exists](#why-this-exists)+- [Install](#install)+- [Using the viewer](#using-the-viewer)+- [Supported agents](#supported-agents)+- [Privacy](#privacy)+- [Command reference](#command-reference)+- [The session map format](#the-session-map-format)+- [How it works](#how-it-works)+- [Configuration](#configuration)+- [Development](#development)+- [Contributing](#contributing)+- [Known limitations](#known-limitations)+- [License and credits](#license-and-credits)++## Why this exists++Your agent's transcripts already record what it did: which files it read before editing, which commands it retried, which MCP servers failed, where the context window filled up, and which subagents came back empty. That data sits in `~/.claude`, `~/.codex`, `~/.cursor` and similar folders, and almost nobody looks at it.++agentplay makes that data readable. Every session becomes a map of everything it touched and a timeline you can play back, so you can answer questions like:++- What did the agent read before it edited this file, and what did it never open?+- Which commands failed, and how many times did it retry the same one?+- Where did the context window fill up, and what did the subagents bring back?+- Which PRs, commits and tickets did the session produce?++## Install++You need Python 3.11 or newer. agentplay has **no runtime dependencies** beyond the standard library.++```bash+uvx agentplay # run without installing (uv: https://docs.astral.sh/uv/)+pipx run agentplay # same, with pipx+pip install agentplay # or install it into an environment+```++**Setting up with a coding agent?** Point it at [`install.md`](install.md): step-by-step instructions written for an agent, covering every option above and how to check the viewer is up.++<details>+<summary>From source</summary>++```bash+git clone https://github.com/Entelligence-AI/agentplay+cd agentplay+make setup # python venv + viewer node_modules+make viewer # build the web viewer and copy it into the Python package+make run # agentplay view, from the checkout+```++</details>++<details>+<summary>Windows</summary>++The default session folders (`C:\Users\<you>\.claude`, `.codex`, and so on) are found automatically; no path configuration is needed.++`make` works under Git Bash or MSYS2 (it uses `python\.venv\Scripts\python.exe` on Windows) and in WSL. Without `make`, run the equivalent steps in PowerShell:++```powershell+git clone https://github.com/Entelligence-AI/agentplay+cd agentplay+uv venv python\.venv+uv pip install --python python\.venv\Scripts\python.exe -e "python[dev]" jsonschema+cd viewer+corepack pnpm install --frozen-lockfile+corepack pnpm run build+Remove-Item -Recurse -Force ..\python\src\agentplay\viewer -ErrorAction SilentlyContinue+Copy-Item -Recurse dist ..\python\src\agentplay\viewer+cd ..\python+.venv\Scripts\agentplay view+```++The viewer needs the pnpm version pinned in `viewer/package.json` (10.x). An older pnpm, such as 8, rejects the lockfile. `corepack pnpm ...` (as above) runs the pinned version without changing your global pnpm.++</details>++To try the viewer on its own, run `pnpm dev` in `viewer/`; it loads three synthetic demo sessions. You can also drag any `agentplay/v1` file onto the page.++## Using the viewer++```bash+agentplay # same as `agentplay view`+```++```+Found 412 sessions claude-code 301 · codex 88 · cursor 23+Built 412 new, 0 unchanged, 0 skipped in 9.4s. Nothing left this machine.+Viewer → http://127.0.0.1:7317/ (Ctrl+C to stop)+```++<sub>Illustrative counts. Builds are incremental, so later runs only rebuild sessions whose transcript changed.</sub>++In the viewer:++- **The map** is a radial tree of everything the session touched: repos, directories and files (seen, read or edited), shell verbs, MCP servers and tools, skills, subagents, web hosts, error classes, models, and the outputs it produced (commits, PRs, tickets).+- **The timeline** plays the session back at 1x, 4x or 16x. Scrub it, or switch between step axis and wall-clock time. Its lanes show prompts, errors, delays, outputs, edits, exploration, MCP, skills, tools, model, cost, tokens, subagents and context size, with compactions marked.+- **Keyboard:** Space plays and pauses. Arrow keys step, Shift steps by 10. `E`, `X`, `D`, `O` and `R` jump to the next edit, error, delay, output or retry.+- **Scopes:** pick a task, a model, or a single subagent ("agent lens"). The whole explorer re-scopes to it.+- **Tasks:** a session is split into tasks, usually one per prompt you gave it, each labelled with the start of that prompt. Labels live only in your local index, are added when the viewer loads a session, and are never written into a map (see [Privacy](#privacy)).+- **Errors:** the Errors tab lists every error in the session, grouped by class and ranked by the longest run of the same failing command. Click a row to seek the replay to it. The error, PR and subagent badges on the session header narrow the timeline the same way.++Every view is a URL, so a link to a moment in a session reopens it for anyone who runs the viewer on the same data.++## Supported agents++| Agent | Reads from (defaults) | Subagent lanes | Tokens | Notes |+|---|---|---|---|---|+| **Claude Code** | `~/.claude/projects/**/*.jsonl` and `…/subagents/agent-*.jsonl` | yes | per request | Highest fidelity: read straight from the JSONL, including hooks, compactions, stop reasons and latency |+| **Codex** (CLI, IDE) | `~/.codex/sessions/**/*.jsonl` | main lane only | per turn | |+| **Cursor** (agent CLI and IDE composer) | `~/.cursor` agent transcripts, `~/.cursor/chats/*/*/store.db`, IDE `state.vscdb` | main lane only | not recorded, see limitations | SQLite stores are copied and decoded locally, read-only |+| **GitHub Copilot CLI** | `~/.copilot/session-state/**` | main lane only | per turn | |+| **GitHub Copilot in VS Code** | VS Code `User/workspaceStorage/*/chatSessions` | main lane only | per turn, where recorded | Code, Code Insiders, VSCodium |+| **OpenCode** | `~/.local/share/opencode/opencode.db` | main lane only | per turn | SQLite, decoded locally |+| **Kiro** | `~/.kiro/sessions/*/*` | main lane only | per turn, where recorded | Sub-executions merged into the session |++"Main lane only" means the session's own tool calls are all there, but subagent work is not split out into separate lanes on the map.++Run `agentplay agents` to see which of these were found on your machine. Every location can be overridden (see [Configuration](#configuration)). A parser for another agent is the most useful contribution you can make; see [CONTRIBUTING.md](CONTRIBUTING.md).++## Privacy++agentplay was designed so that you can show a map to someone else without worrying about what is in it.++**Your session data never leaves your machine.** There is no usage telemetry, no update check and no upload of sessions or maps. The viewer is served from `127.0.0.1` and loads no remote fonts or scripts. It shows a few links to Entelligence (a banner, the welcome card, sample-review and "fix now" blocks); they open only when you click them, carry only a tag naming where you clicked (`?src=agentplay-viewer&from=banner`) and nothing from your sessions, and the viewer fetches nothing from them on its own. Cursor's billed-usage lookup, which would call Cursor's API with your stored token, is deliberately disabled.++**The one network call is your email, if you give it.** The first time the viewer opens, it offers to take your email so Entelligence can tell you about new features. If you type one in, agentplay sends Entelligence the event (signup, or later disconnect), that email, a random install id (generated once and kept in `~/.agentplay/account.json`, so it ties your signup and disconnect to the same install), its version number and the time, and nothing else: no session data, paths or repo names. "Continue without email" sends nothing. All of it is in one file, [`account.py`](python/src/agentplay/account.py); `grep -rn urllib.request python/src/` finds it and nothing else. You can disconnect from the top bar, which forgets the email locally and sends Entelligence one request to delete it; it is sent once and not retried, so if Entelligence can't be reached at that moment it may not arrive, and the email may stay on the list. `DO_NOT_TRACK=1` or `AGENTPLAY_NO_NETWORK=1` turns the offer off and blocks the request. Details: [docs/signup-endpoint.md](docs/signup-endpoint.md).++**A map document never contains:**++- prompt text, assistant text, or reasoning;+- tool inputs or outputs, or file contents;+- command arguments. A shell command is recorded as its verb only (`git log`, `pytest`), never `git log --author=...`;+- subagent prompts or descriptions. Only their type and model are recorded;+- user message text. Only its length and counts of images and links are recorded.++**A map does contain:** repo names and remotes, repo-relative file paths, tool, MCP server and skill names, model names, token counts, timings, error classes, and exit codes. Paths outside any repo collapse to coarse buckets such as `/tmp (scratch)`, `~/Downloads` or `outside-repo`.++**Path modes** control how file paths are stored. Pass them with `--path-mode` on `build` or `view`:++| mode | `src/billing/invoice.py` becomes |+|---|---|+| `relative` (default) | `src/billing/invoice.py` |+| `dirs_only` | `src/billing/•a1b2c3` |+| `hashed` | every segment HMAC-SHA256'd with the key in `AGENTPLAY_HMAC_KEY` (falls back to `dirs_only` without one) |++Repo names and remotes are kept in every path mode, so a reader can tell which project a map is about. Remove the `repos[].remote` field before sharing if that is sensitive.++**Local-only extras.** The session list shows a title for each session: Claude Code's own title, or else the first 90 characters of your first prompt. Task labels in the viewer are the start of each prompt. Both live only in `~/.agentplay/index.json`, are never written into a map, and are only served to a viewer on the same machine; turn them off with `--no-titles`, which also clears what is already stored for the sessions that run sees. The flag is per run, not a saved preference, so a later build without it puts them back. Images you pasted into Claude Code prompts are read from the original transcript on demand by the local server, for a viewer on this machine only, and are never stored in a map, the index or an export. The same goes for the message and command of a failed hook: the map keeps which hook failed and what it ran after, and the viewer reads the text from the transcript only on this machine.++**Sharing.** `agentplay export <session>` writes a single map file and tells you which repo names and how many paths it contains. For anything you post publicly, rebuild with `--path-mode dirs_only`.++The full contract, and the tests that enforce it, are described in [docs/format.md](docs/format.md#redaction-contract).++## Command reference++```+agentplay [view] build maps and open the viewer (default command)+agentplay build build maps for new or changed sessions+agentplay list list built sessions+agentplay export write one session's map to a .json or .json.gz file+agentplay import add map files (a teammate's, another machine's) to your local store+agentplay agents show which agents were found on this machine+```++| Flag | On | Meaning |+|---|---|---|+| `--since 30d` | build, view | only sessions changed in the window (`12h`, `2w`, `2026-09-01`) |+| `--agents claude-code,codex` | build, view | limit to these agents |+| `--rebuild` | build, view | rebuild even unchanged sessions |+| `--path-mode dirs_only` | build, view | see [Privacy](#privacy) |+| `--limit N` | build, view, list | newest N sessions |+| `--no-titles` | build, view | don't keep local titles, and clear any already stored |+| `--port 7317`, `--no-open`, `--no-build` | view | server options |+| `--json` | build, list | machine-readable output |++## The session map format++A session map (`agentplay/v1`) is one JSON document per session:++```jsonc+{+ "schema": "agentplay/v1",+ "session": { "id": "local:claude-code:5f2c…", "agentTool": "claude-code", "startedAt": "2026-09-24T14:05:00Z",+ "durationMs": 250000, "models": ["claude-sonnet-5"], "pathMode": "relative", "outcome": "pr_created" },+ "totals": { "calls": 26, "requests": 20, "errors": 2, "tokens": 1200000, "costUsd": 1.93, "compactions": 1, "…": 0 },+ "repos": [{ "id": "r0", "name": "api", "remote": "acme/api" }],+ "files": [{ "id": 0, "repo": "r0", "path": "src/orders.ts", "reads": 2, "edits": 2, "hits": 1 }],+ "agents": [{ "id": "main", "parent": null, "kind": "main" }, { "id": "sa-1", "parent": "main", "kind": "subagent", "subagentType": "Explore" }],+ "tasks": [{ "n": 1, "name": "Explore the request pipeline", "startSeq": 0, "endSeq": 12 }],+ "prs": [{ "provider": "github", "repo": "acme/api", "number": 142, "url": "https://github.com/acme/api/pull/142", "seq": 51 }],+ "events": [+ { "seq": 3, "t": 5210, "kind": "read", "agent": "main", "tool": "Read", "targets": [{ "file": 0, "touch": "read" }] },+ { "seq": 4, "t": 7730, "kind": "llm", "agent": "main", "model": "claude-sonnet-5", "in": 12, "cw": 3100, "cr": 41000, "out": 380, "latency": 2510 },+ { "seq": 9, "t": 19400, "kind": "verify", "agent": "main", "tool": "Bash", "verb": "pnpm test", "err": true, "errClass": "exit_code", "exitCode": 1 }+ ]+}+```++- **Spec:** [docs/format.md](docs/format.md). It covers every event kind and field, outcomes, tasks, and the redaction contract.+- **JSON Schema:** [schema/agentplay-v1.schema.json](schema/agentplay-v1.schema.json). CI validates every built map against it.+- **Compatibility:** readers accept both `agentplay/v1` and the earlier `entelligence.session-map/v1` name (same shape). Fields are added, never repurposed. Readers must ignore unknown fields.++The format is deliberately independent of this tool. If you build an agent, an observability product or a transcript tool, you can emit or read `agentplay/v1` and reuse the viewer.++## How it works++```+ ~/.claude ~/.codex ~/.cursor ~/.copilot VS Code opencode.db ~/.kiro+ │ │ │ │ │ │ │+ │ │ materialize.py (decode SQLite / dir stores → NDJSON cache, read-only)+ ▼ ▼ ▼ ▼ ▼ ▼ ▼+ _core parsers (one per agent) ──► spans ──► builder.py ──► agentplay/v1 documents+ (Claude Code is read straight from JSONL by builder.py for subagents + per-request tokens)+ │+ ▼+ ~/.agentplay/maps/*.json + index.json (store.py)+ │+ server.py + viewer (127.0.0.1 only)+```++| Path | What it is |+|---|---|+| `python/src/agentplay/_core/` | Transcript parsers and pure metrics: spans, tool taxonomy, pricing |+| `python/src/agentplay/builder.py` | Spans or JSONL → `agentplay/v1`, including redaction, path modes, outcomes, retries, delays, PR detection |+| `python/src/agentplay/materialize.py` | Decoders for database-backed agents (OpenCode, Cursor, Kiro) |+| `python/src/agentplay/discover.py` | Where each agent keeps its sessions; builds the parser over them |+| `python/src/agentplay/{store,pipeline}.py` | Incremental build into `~/.agentplay` |+| `python/src/agentplay/server.py` | Local read-only API and static viewer |+| `viewer/src/core/` | Pure TypeScript model: tree, radial layout, playback, signals, scopes, canvas painters. No React |+| `viewer/src/explorer/` | The React explorer |+| `viewer/src/data/` | `SessionMapSource` implementations: local server, dropped files, demo |+| `schema/` | JSON Schema for the format |++## Configuration++All configuration is through environment variables. The examples in this README use bash syntax; in PowerShell, set one with `$env:AGENTPLAY_NO_NETWORK = "1"` before running `agentplay` (it lasts for that session), and in cmd use `set AGENTPLAY_NO_NETWORK=1`.++| Variable | Default | Purpose |+|---|---|---|+| `AGENTPLAY_HOME` | `~/.agentplay` | where maps, the index and caches live |+| `AGENTPLAY_CLAUDE_HOMES` | `~/.claude` | comma-separated Claude Code homes. Useful on WSL: `~/.claude,/mnt/c/Users/you/.claude` |+| `AGENTPLAY_CODEX_HOMES` | `~/.codex` | Codex homes |+| `AGENTPLAY_CURSOR_HOMES` | `~/.cursor` | Cursor homes |+| `AGENTPLAY_COPILOT_HOMES` | `$COPILOT_HOME` or `~/.copilot` | Copilot CLI homes |+| `AGENTPLAY_COPILOT_VSCODE_HOMES` | VS Code `User` dirs | Copilot in VS Code |+| `AGENTPLAY_OPENCODE_HOMES` | `$XDG_DATA_HOME/opencode` | OpenCode data dirs |+| `AGENTPLAY_KIRO_HOMES` | `~/.kiro` | Kiro homes |+| `AGENTPLAY_HMAC_KEY` | unset | key for `--path-mode hashed` |+| `DO_NOT_TRACK`, `AGENTPLAY_NO_NETWORK` | unset | set either to turn off the email signup and its one network call |+| `AGENTPLAY_SIGNUP_URL` | built in | where the signup sends an email (for testing; see [docs/signup-endpoint.md](docs/signup-endpoint.md)) |+| `AGENTPLAY_DEV_ORIGINS` | unset | comma-separated extra origins allowed to post to the local server, for the viewer's dev server: `http://localhost:5173` |+| `NO_COLOR` | unset | disable terminal styling |++## Development++Requirements: Python 3.11+, and Node 22+ with pnpm for the viewer.++```bash+make setup # python/.venv with dev deps, viewer/node_modules+make test # python tests (pytest) + viewer tests (vitest)+make check # ruff, tsc, tests, and the hygiene guard+make viewer # build viewer/dist and copy it to python/src/agentplay/viewer+make run # run the CLI from the checkout+```++For the viewer's dev server, run `AGENTPLAY_DEV_ORIGINS=http://localhost:5173 agentplay view --no-open` in one terminal and `AGENTPLAY_SERVER=http://127.0.0.1:7317 pnpm dev` in `viewer/` in another. The local server only takes posts (the signup card) from its own origin, so the dev server's origin has to be listed.++Test suites:++- **Python** (`python/tests`): about 1,000 tests. They cover the parsers for every agent, the builder's redaction and shape, task labels, and the local tool end to end (build, store, server, export, import, schema validation).+- **Viewer** (`viewer/src`): over 250 tests covering the pure model, the schema, the data sources and the demo data.++## Contributing++Contributions are very welcome. The most valuable ones are:++1. **A parser for another agent**: Gemini CLI, Amp, Cline, Roo, Windsurf or Aider.+2. **Viewer improvements** that make a session easier to read.+3. **Fixture transcripts** for an agent version that broke parsing, with personal content removed.++[CONTRIBUTING.md](CONTRIBUTING.md) walks through each of these, the privacy rules every change must keep, and how to run the suites. Report security issues privately; see [SECURITY.md](SECURITY.md).++## Known limitations++- **Cursor sessions have no token or cost figures.** Cursor does not write billed usage to disk, and agentplay will not call Cursor's API to fetch it.+- **Whole-file writes and "created vs modified".** A map is built after the session, so the builder cannot always tell whether a `Write` created a file or overwrote one. The map records such a write as an edit only when the session had already seen the file.+- **Costs are estimates** from public list prices in `_core/pricing.py`. Plan, enterprise and batch pricing are not modelled.+- **Large sessions** are capped at 20,000 events per map (flagged `truncated`). Transcripts over 512 MB are skipped.+- **Windows** is supported by the parsers but less tested than macOS and Linux. CI runs the Python tests on Windows for every supported Python version. Building, the viewer, `list`, `export` and `import` have been run end to end from a source install on Windows 11 with Python 3.12 (see the Windows notes under [Install](#install)). Paths outside the user's home, such as `%APPDATA%` for Copilot in VS Code, are exercised less.++[Entelligence](https://entelligence.ai), which maintains agentplay, offers a hosted team edition. It adds review comments traced back to the session edit that caused them, cross-engineer views, team-level recommendations, and measured adoption. The open-source tool does not depend on it and will not be degraded to sell it.++## License and credits++Apache License 2.0; see [LICENSE](LICENSE) and [NOTICE](NOTICE). Copyright 2026 Entelligence AI, Inc.++Tool taxonomy rows and a parser design pattern were informed by [SuperBased Observer](https://github.com/superbasedapp/observer) (Apache-2.0). Some product ideas were informed by [agentacct](https://github.com/mikehasa/agentacct) (MIT); no agentacct code is used. Details are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..97582c2--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,23 @@+# Security policy++agentplay reads sensitive local data: your coding agents' transcripts. We treat three kinds of bug as security issues:++- **Redaction bugs:** any path by which a map, a log line, the local API or the viewer exposes prompt text, model output, tool input or output, file contents, command arguments or credentials.+- **Local server issues:** the viewer server is meant to bind only to `127.0.0.1` and serve read-only data. Anything that lets another origin or another machine read it, or lets a request write data, is a security issue. The one write, `POST /api/account`, must only be accepted from the local viewer.+- **Anything leaving the machine** beyond what the README's privacy section lists for the email signup.++## Reporting++Please **do not open a public issue** for these. Report privately through GitHub: on the repository page, open **Security → Report a vulnerability**. Include:++- what you found and how to reproduce it (a small synthetic transcript is ideal);+- the version (`agentplay --version`) and your OS;+- whether you would like to be credited.++If you cannot use GitHub, email the fallback contact: [[email protected]](mailto:[email protected])++We will acknowledge your report within 3 business days and aim to ship a fix within 30 days, sooner for anything that exposes content. We will tell you when it is fixed and credit you in the release notes if you want.++## Supported versions++Security fixes go into the latest release. The project is pre-1.0, so please upgrade rather than expect backports.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..66bc0c6--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,86 @@+# Third-party notices++This package ports ideas and small, clearly-scoped data tables from two+open-source projects, following one rule: "port ideas+and data tables, not code". No source file from either project is copied,+vendored, or linked at build or run time. This notice exists as a good-faith+attribution for the specific material listed below, independent of what+either license strictly requires for that material.++## SuperBased Observer (github.com/superbasedapp/observer)++Apache License, Version 2.0. Copyright 2026 Gaja AI. Full license text:+http://www.apache.org/licenses/LICENSE-2.0++What was ported:++- **Tool taxonomy rows** — `python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py`+ (`_COPILOT_VSCODE`), row values (raw tool name → canonical name) cross-checked+ against observer's `internal/tooltax/table.go` for the `copilot`/`copilot-vscode`+ agent rows, then re-verified independently against real local transcript data+ (see that module's own docstring) before being written down. No table.go+ source text is included verbatim.+- **Design pattern** — the copilot-vscode session parser+ (`python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot_vscode.py`)+ follows the same snapshot-plus-patch replay approach and per-request model+ resolution fallback order (resolvedModel → modelId → session-level+ selectedModel, skipping internal routing aliases at each tier) that+ observer's `internal/adapter/copilot/modern.go` uses, independently+ implemented in Python against this codebase's own `SpanData`/`TraceData`+ shapes and verified against real local data, not ported as code.++## agentacct (github.com/mikehasa/agentacct)++MIT License. Copyright (c) 2026 agentacct contributors. Full license text+included below.++What was used: no code. Three product ideas informed the design: cost-basis+labels distinguishing billed, estimated and unknown cost; a Reported-vs-Verified+task outcome; and a per-task estimate of subscription plan usage.++```+MIT License++Copyright (c) 2026 agentacct contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```++## Bundled viewer dependencies++The Python wheel ships the built web viewer (`agentplay/viewer/`), which is a+bundle of the viewer's production npm dependencies (React, React DOM, Base UI,+TanStack Query, cmdk, nuqs, zod, clsx, tailwind-merge, class-variance-authority,+Phosphor and Lucide icons, and their transitive dependencies) plus two font+families, Inter and JetBrains Mono, from `@fontsource-variable`.++License families found in that tree (`pnpm licenses list --prod`):++- **MIT**: the large majority of packages.+- **ISC** and **0BSD**: one package each.+- **Apache-2.0**: one package.+- **SIL Open Font License 1.1 (OFL-1.1)**: the Inter and JetBrains Mono font+ files. The OFL requires its license and copyright notice to travel with the+ fonts, which the generated THIRD_PARTY_LICENSES.txt does.++The exact package list, versions, and the full license text of each are+generated at build time by `scripts/collect_viewer_licenses.mjs` (run by+`pnpm run build` in `viewer/`) into `THIRD_PARTY_LICENSES.txt`, which is copied+into the wheel next to the viewer's `index.html` at `agentplay/viewer/THIRD_PARTY_LICENSES.txt`.+The file is generated, not committed, so it always matches the lockfile.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdnew file mode 100644index 0000000..34016fd--- /dev/null+++ b/docs/RELEASING.md@@ -0,0 +1,11 @@+# Releasing++## Cutting a release++1. Bump the version in both `python/pyproject.toml` and `python/src/agentplay/__init__.py`.+2. Merge to `main`, then tag: `git tag vX.Y.Z && git push origin vX.Y.Z`.+3. Pushing the tag starts `release.yml` (it triggers on tags matching `v*`). It first checks that the tag, `pyproject.toml` and `__version__` agree.+4. It then runs the full CI workflow, the same checks as every PR. Its `package` job builds the viewer (which also writes `THIRD_PARTY_LICENSES.txt`), builds the wheel and sdist, smoke-tests both, and uploads them as the `dist` artifact.+5. The `pypi` job waits for a maintainer to approve the `pypi` environment. Once approved, it downloads that `dist` artifact (nothing is rebuilt) and publishes it to PyPI with attestations through trusted publishing.++Push only the tag you are releasing (`git push origin vX.Y.Z`, never `git push --tags`).diff --git a/docs/format.md b/docs/format.mdnew file mode 100644index 0000000..789ebe8--- /dev/null+++ b/docs/format.md@@ -0,0 +1,229 @@+# The `agentplay/v1` format++A **session map** is a redacted, chronological replay of one coding-agent session. It records every tool call, file touch, MCP call, skill, subagent and model request, in order, with repo-relative paths. It does not contain the content of any of them.++One map is one JSON object. Its machine-readable definition is [`schema/agentplay-v1.schema.json`](../schema/agentplay-v1.schema.json) (JSON Schema 2020-12). This page explains the meaning of each part.++- **Media type:** `application/json`. It is commonly stored gzipped as `*.json.gz`.+- **Schema id:** `"schema": "agentplay/v1"`. Readers must also accept `"entelligence.session-map/v1"`, the format's earlier name. The shape is identical.+- **Evolution:** fields are only ever added inside v1, never removed or repurposed. Readers must ignore fields they do not know. A breaking change would be `agentplay/v2`.++## Contents++- [Redaction contract](#redaction-contract)+- [Top level](#top-level)+- [`session`](#session)+- [`totals`](#totals)+- [`repos`, `files`](#repos-files)+- [`agents`](#agents)+- [`tasks`](#tasks)+- [`prs`](#prs)+- [`events`](#events)+- [Outcomes](#outcomes)+- [Content hash](#content-hash)+- [Writing a producer](#writing-a-producer)++## Redaction contract++These rules are hard rules. A producer that breaks one of them is not producing a valid session map.++1. **No text content.** A map never carries prompt text, assistant or reasoning text, tool inputs, tool outputs, file contents, or command arguments.+2. **Shell commands contribute a verb only.** The verb is the program plus a subcommand for multi-verb tools such as `git log`, `npm run`, `pytest` or `gh pr view`. Never flags, paths or values.+3. **Subagents contribute only `subagentType` and `model`.** Never their description or prompt.+4. **User turns contribute only shape:** `chars` (the length), plus counts of `images` and `urls`. The `images` count is the only trace of an image; producers must never embed image data.+5. **Model responses contribute only metadata:** token counts, latency, stop reason, whether there was thinking, the number of tool calls requested, and the length of text blocks (`textChars`).+6. **Paths.** Inside a git repository, a path is repo-relative. Outside any repository, it collapses to a bucket label: `/tmp (scratch)`, `~/Documents`, `~/Downloads`, `~/Desktop`, `~/.claude/<area>`, `~ (home)` or `outside-repo`.+7. **Path modes** (`session.pathMode`):+ - `relative` (default): repo-relative paths as above.+ - `dirs_only`: each file name becomes `•<sha256(path)[:6]>` (the repo-relative path); directories are kept. The hash is short and unkeyed, so a common name in a known directory (`README.md`, `package.json`) can be guessed by hashing candidates; use `hashed` with a key for stronger protection.+ - `hashed`: every path segment becomes `HMAC-SHA256(key, segment)[:10]`. Without a key, this mode falls back to `dirs_only`.++Identifiers that may appear are repository names and remotes, MCP server and tool names, skill names, subagent types, model names, web host names, hook names, and PR or ticket numbers and URLs. These are needed to make a map useful. Producers should treat them as metadata the user can see and remove.++The reference producer ([`python/src/agentplay/builder.py`](../python/src/agentplay/builder.py)) is tested against this contract. [`tests/test_builder.py::test_builder_never_leaks_free_text`](../python/tests/test_builder.py) builds a map from a transcript seeded with secret prompt text, secret arguments and secret subagent descriptions, and asserts that none of it appears in the output.++## Top level++```jsonc+{+ "schema": "agentplay/v1",+ "session": { … },+ "totals": { … },+ "repos": [ … ],+ "files": [ … ],+ "agents": [ … ],+ "tasks": [ … ], // optional+ "prs": [ … ],+ "events": [ … ] // sorted by t; events[i].seq === i+}+```++## `session`++| field | type | meaning |+|---|---|---|+| `id` | string | Stable session id, conventionally `local:<agent>:<native id>` |+| `agentTool` | string | `claude-code`, `codex`, `cursor`, `copilot`, `copilot-vscode`, `opencode`, `kiro`, … |+| `cliVersion` | string | Version of the producer. Excluded from the content hash |+| `startedAt` | ISO-8601 UTC | Time of the first event |+| `durationMs` | number | Time from the first event to the last |+| `models` | string[] | Every model that served a request |+| `pathMode` | `relative` \| `dirs_only` \| `hashed` | See the redaction contract |+| `truncated` | bool | `true` when the producer stopped at its event cap (20,000 in the reference producer) |+| `outcome` | string | See [Outcomes](#outcomes) |+| `role` | `root` \| `subagent` \| `helper` \| `unknown` \| null | `subagent` and `helper` sessions are usually hidden from lists; their work already appears inside their parent |+| `parentSessionId` | string \| null | Set when `role` is `subagent` |++## `totals`++These are session-wide counters, so a list or dashboard never has to scan `events`.++| field | meaning |+|---|---|+| `calls` | tool calls. Excludes `llm`, `user`, `compaction`, `error` and `delay` events |+| `requests` | model requests |+| `userTurns` | user messages |+| `subagents` | subagent lanes |+| `errors` | events with `err: true` |+| `tokens` | all input, cache-write, cache-read and output tokens |+| `costUsd` | estimated cost at list prices. Advisory only |+| `filesTouched`, `filesCreated`, `filesDeleted` | distinct files |+| `errorsBySource` | `{tool, mcp, llm, hook, orchestration: n}` |+| `errorsByClass` | `{exit_code, timeout, rate_limit, …: n}` |+| `retries` | events with `retryOf` |+| `delays`, `delayMs` | delay events and their total duration |+| `maxContext` | largest main-agent context (`in + cw + cr`) seen |+| `compactions` | compaction events |+| `llmLatencyP50`, `llmLatencyP95` | model latency percentiles, in ms |+| `outputTokens` | output tokens only |+| `tasks` | number of task segments |+| `prsCreated`, `prsMerged`, `prsClosed`, `prComments`, `commits`, `ticketsCreated`, `ticketsUpdated`, `artifacts`, `skillsCreated`, `skillsUpdated`, `modelSwitches` | outputs the session produced (confirmed only) |+| `promptChars`, `promptImages`, `promptUrls` | the shape of what the user sent |++## `repos`, `files`++```jsonc+"repos": [{ "id": "r0", "name": "api", "remote": "acme/api" }],+"files": [{ "id": 0, "repo": "r0", "path": "src/orders.ts", "reads": 2, "edits": 2, "hits": 1, "first": 17, "op": "modify" }]+```++- **`files[].first`** is the `seq` of the event that first touched the file.+- **`files[].op`** is the last file operation seen for it: `create`, `modify`, `delete`, `rename-from` or `rename-to`.+- **Touch levels** (used by `targets[].touch`): `hit` means the file was named or listed, for example matched by a search. `read` means its contents were read. `edit` means it was changed.++## `agents`++```jsonc+"agents": [+ { "id": "main", "parent": null, "kind": "main", "start": 0, "end": 250000,+ "calls": 20, "requests": 16, "tokens": 900000, "cost": 1.61, "outcome": "pr_created" },+ { "id": "sa-ae824d54211f", "parent": "main", "kind": "subagent", "subagentType": "Explore",+ "model": "claude-haiku-4-5", "launchSeq": 14, "start": 31000, "end": 70000, "…": "same counters" }+]+```++Every event carries `agent`, which is `main` or one of these ids. `launchSeq` points at the `subagent` event that started the lane. A subagent has no further nesting.++## `tasks`++This field is optional. It records how the session divides into units of work:++```jsonc+"tasks": [{ "n": 1, "id": "t1", "name": "Explore the request pipeline", "source": "segments",+ "startSeq": 0, "endSeq": 12, "startT": 0, "endT": 70000, "firstTurn": 0, "lastTurn": 1 }]+```++- **`source`** is either `segments` or `turns`. `segments` means the tasks came from a task segmenter, which may use a model and produce names. `turns` means one task per user turn.+- **`startSeq` and `endSeq`** are inclusive.+- **`events[].task`** holds the task number `n`.+- **Fallback:** a malformed `tasks` block must never fail a reader. Drop it and fall back to one task per user turn.++## `prs`++```jsonc+"prs": [{ "provider": "github", "repo": "acme/api", "number": 142, "url": "https://github.com/acme/api/pull/142", "seq": 51, "state": "open" }]+```++A PR or MR is listed only once its URL is confirmed in a tool result. `seq` points at the event that created it.++## `events`++Every event has these fields:++| field | meaning |+|---|---|+| `seq` | index into `events` |+| `t` | ms since the first event |+| `kind` | see the table below |+| `agent` | `main` or a subagent id |+| `err` | the event failed |+| `task` | task number (when `tasks` is present) |+| `model` | the model driving the agent at this point |+| `cat` | tool category: `file`, `shell`, `vcs`, `test`, `cloud`, `http`, `fs`, `package`, `build`, `mcp`, `subagent`, `skill`, `web` or `tool` |++| kind | extra fields |+|---|---|+| `read`, `search`, `edit`, `exec`, `verify` | `tool`, `verb` (shell only), `targets[]`, `outBytes`, `dur`, `vcs?` |+| `mcp` | `server`, `tool`, `outBytes`, `dur` |+| `skill` | `skill` |+| `subagent` | `subagentType`, `model?`, `child` (agent id) |+| `web` | `host` (a hostname, or `search`) |+| `tool` | `tool`: any other tool (ToolSearch, AskUserQuestion, TodoWrite, …) |+| `llm` | `model`, `in` (fresh input), `cw` (cache write), `cr` (cache read), `out`, `cost?`, `latency`, `stop`, `thinking`, `toolCalls`, `textChars` |+| `user` | `chars`, `images`, `urls` |+| `error` | `source` (the builder writes `llm`, `hook` or `orchestration`; the schema also accepts `tool`, `mcp` and null, which a builder could use for a standalone error event, but a failed tool or MCP call is instead flagged on its own `tool`/`mcp` event and counted under that source in `totals.errorsBySource`), `errClass`, `hook?`, `hookEvent?`, `srcUuid?`, `ref?`, `retry?` |+| `delay` | `cause` (`tool`, `subagent`, `llm` or `stall`), `ms`, `ref?` (the causing event) |+| `compaction` | `trigger` (`auto` or `manual`), `preTokens`, `postTokens`, `ms` |+| `commit` | `repo`, `sha`, `files`, `ins`, `del` |+| `pr_merge`, `pr_close`, `pr_comment` | `repo`, `number`, `url?` |+| `ticket` | `tracker`, `action` (`create` or `update`), `id` |+| `artifact` | `url`, `title?`, `version?` |+| `skill_write` | `name`, `action` (`create` or `update`) |+| `model_switch` | `from`, `to` |++`verify` is a shell command recognised as a test, build, lint or type check (for example `pytest`, `pnpm test`, `tsc`, `cargo clippy`). Output kinds such as `commit` and `pr_merge` are emitted only when confirmed in a tool result.++### Targets++```jsonc+"targets": [{ "file": 0, "touch": "edit", "op": "modify" }, { "scope": "outside", "label": "/tmp (scratch)", "touch": "read" }]+```++### Signals++- **Failures.** A failed tool, MCP or subagent call can carry the following:+ - `errClass`: one of `exit_code`, `timeout`, `not_found`, `validation`, `permission_denied`, `blocked`, `stale_file`, `model_unavailable`, `rate_limit`, `api_error`, `interrupted`, `no_result`, `subagent_failed`, `subagent_killed` or `other`;+ - `exitCode`;+ - `retryOf`: the `seq` of the failed attempt it repeats (same agent, tool, verb or server, and first target, within the last 8 calls);+ - `attempt`: 2 or higher.+- **`error` events** record failures that are not tied to one tool call. Their `errClass` is one of `rate_limit`, `usage_limit`, `spend_limit`, `overloaded`, `server_error`, `auth`, `bad_request`, `api_error`, `refusal_fallback`, `hook_blocking`, `hook_error` or `interrupted`.+ - For a hook failure, `hook` is the hook's name (such as `PostToolUse:Bash`) and `hookEvent` the event it ran on (such as `PostToolUse`). `ref` is the `seq` of the tool call the hook ran after, when there is one. `srcUuid` is the id of the transcript record, an opaque random value that lets a viewer on the machine that recorded the session look the hook's message and command up; neither is ever stored.+- **`delay` events** are produced at these thresholds in the reference producer: a tool call of 30 s or more, model latency of 60 s or more, or a stall where the main agent was idle for 120 s or more while not waiting on the user.+- **`vcs`** is present on any VCS operation: `{provider: git|github|gitlab|bitbucket, action, repo?, number?}`.+ - For git, `action` is the subcommand. For gh or glab it is `<noun>_<verb>`.+ - `pr_create` is set only once the PR URL is confirmed. `pr_create_attempt` and `pr_create_failed` cover the rest.++## Outcomes++`session.outcome` and `agents[].outcome` take one of the values below. The first rule that matches wins.++1. `pr_created`: a confirmed PR or MR creation in the lane.+2. `interrupted`: an `interrupted` error in the last 12 events.+3. `blocked`: a `blocked` or `permission_denied` error in the last 12 events.+4. `verified`: the last `verify` event succeeded, with no edit after it.+5. `unresolved_errors`: 2 or more errors in the last 12 events.+6. `incomplete`: the lane ends on an edit or exec with no assistant text after it.+7. `completed`: none of the above.++## Content hash++`contentHash` is the SHA-256 of the canonical JSON of the map, with `session.cliVersion` removed. Canonical JSON means sorted keys, compact separators and UTF-8. Two producers that agree on a map produce the same hash, so independent builders can be checked against each other.++## Writing a producer++To make your agent's sessions work with the viewer:++1. Emit one map per session following this page. Start with the required fields: `schema`, `session.id`, `session.startedAt`, `totals` and `events[].t` and `kind`. Everything else is additive.+2. Validate your maps against the JSON Schema.+3. Keep to the redaction contract. If your agent's own logs contain text, drop it at the producer. Readers assume maps are safe to show.+4. Open a map by dragging the file onto the viewer, or add it to your local store with `agentplay import map.json.gz` so it shows in your session list. For a new agent, the better path is a parser in this repo; see [CONTRIBUTING.md](../CONTRIBUTING.md#adding-an-agent).diff --git a/docs/images/explorer-dark.png b/docs/images/explorer-dark.pngnew file mode 100644index 0000000..25ca62aBinary files /dev/null and b/docs/images/explorer-dark.png differdiff --git a/docs/images/explorer-light.png b/docs/images/explorer-light.pngnew file mode 100644index 0000000..9ae75adBinary files /dev/null and b/docs/images/explorer-light.png differdiff --git a/docs/signup-endpoint.md b/docs/signup-endpoint.mdnew file mode 100644index 0000000..50f4a7d--- /dev/null+++ b/docs/signup-endpoint.md@@ -0,0 +1,90 @@+# The signup endpoint++The viewer's welcome card asks for an email. When someone gives one, the local+server sends it to a signup endpoint with one `POST` (see+[`python/src/agentplay/account.py`](../python/src/agentplay/account.py)). The+built-in endpoint is `DEFAULT_SIGNUP_URL`, a Google Apps Script web app that+appends a row to Entelligence's signup Sheet.++## What is sent++```json+{"event": "signup", "email": "[email protected]", "installId": "3f9c…", "version": "0.1.0", "at": "2026-10-05T23:10:00Z"}+```++`event` is `signup` or `disconnect`. `installId` is a random id created on first+use and kept in `~/.agentplay/account.json`, so a disconnect can be matched to+its signup. Nothing about any session is ever sent.++## A Google Sheet as the endpoint++1. Create a Google Sheet, then open **Extensions → Apps Script** from inside+ it, so the script is attached to that Sheet. A script made from+ script.google.com is attached to a different file.+2. Replace the editor's contents with this. It creates a `signups` tab with+ headers the first time it runs:++ ```js+ function doPost(e) {+ const d = JSON.parse(e.postData.contents);+ const event = d.event === 'disconnect' ? 'disconnect' : 'signup';+ const email = String(d.email || '').trim().slice(0, 254);+ if (!/^[^@\s\ufeff]{1,64}@[^@\s\ufeff]+\.[^@\s\ufeff]{2,}$/.test(email)) { // the same check as account.py+ return reply({ ok: false });+ }+ // A cell starting with = + - @ (or tab, CR) would become a formula.+ const cell = (v, n) => String(v || '').slice(0, n).replace(/^[=+\-@\t\r]/, "'$&");+ const ss = SpreadsheetApp.getActive();+ const sheet = ss.getSheetByName('signups') ||+ ss.insertSheet('signups').appendRow(['received', 'event', 'email', 'installId', 'version', 'at']);+ sheet.appendRow([new Date(), event, cell(email, 254), cell(d.installId, 64), cell(d.version, 32), cell(d.at, 32)]);+ return reply({ ok: true });+ }++ function reply(body) {+ return ContentService.createTextOutput(JSON.stringify(body))+ .setMimeType(ContentService.MimeType.JSON);+ }+ ```++3. **Deploy → New deployment → Web app.** Execute as: *Me*. Who has access:+ *Anyone*. Copy the web app URL (it ends in `/exec`).+4. Try it locally:++ ```bash+ AGENTPLAY_SIGNUP_URL='https://script.google.com/macros/s/…/exec' agentplay view+ ```++5. To point released builds at it, set `DEFAULT_SIGNUP_URL` in `account.py`.++ To change the script later, keep the URL: **Deploy → Manage deployments →+ edit → Version: New version**. A *new deployment* gets a new URL, and+ released copies of agentplay would keep posting to the old one.++ The script checks the email and stops any cell from being read as a+ formula.++The URL must be `https` to a trusted host (`script.google.com`, its+`script.googleusercontent.com` redirect, or `entelligence.ai`), or `http` to this+machine for testing. Redirects are checked the same way. To send to another+host, add it to `TRUSTED_HOSTS` in `account.py`; any other URL turns the card off.++The endpoint must answer `{"ok": true}` once the row is written. Anything else,+including Apps Script's HTML error page (which it serves with status 200 when the+script throws, for example when the `signups` tab is missing), counts as a failed+signup: the viewer shows the retry message and nothing is stored locally.++A `disconnect` row is a deletion request: remove that email's `signup` rows+when you see one.++## Testing without a sheet++```bash+python3 scripts/fake_signup_endpoint.py # prints every event it receives+AGENTPLAY_SIGNUP_URL=http://127.0.0.1:8787/exec agentplay view+```++## Turning it off++`DO_NOT_TRACK=1` or `AGENTPLAY_NO_NETWORK=1` hides the card and blocks the+request, whatever endpoint is set.diff --git a/install.md b/install.mdnew file mode 100644index 0000000..408f539--- /dev/null+++ b/install.md@@ -0,0 +1,62 @@+# agentplay++> Replay coding-agent sessions (Claude Code, Codex, Cursor, Copilot, OpenCode, Kiro) as a map and a timeline. Local only: it reads transcripts already on disk and serves a viewer on 127.0.0.1.++I want you to set up agentplay on this machine and open it with my sessions mapped. Work through the steps yourself and stop to ask me only where a step says to, or if something fails.++OBJECTIVE: the agentplay viewer is running locally and shows the coding-agent sessions on this machine.++DONE WHEN: `/api/status` on the port the viewer printed (for example `http://127.0.0.1:7317/api/status`) returns JSON with `"available": true` and a `mapCount` above 0, and you have given me the URL.++## TODO++- [ ] Pick a way to run agentplay+- [ ] Confirm the version+- [ ] Find the agents with sessions on this machine+- [ ] Build the session maps+- [ ] Start the viewer+- [ ] Verify it and hand over++## Ground rules++- Ask me before installing anything system-wide (uv, pipx, a Python).+- Do not change any agent's settings or files. agentplay only reads them.+- Do not upload anything. agentplay makes no network calls with session data. The viewer may offer an optional email signup; leave that to me.++## Pick a way to run agentplay++Use the first that is already available. Each needs nothing else installed:++1. **uv:** run commands as `uvx agentplay@latest <command>`. uv brings its own Python. `@latest` stops uv reusing an older cached copy.+2. **pipx:** `pipx run agentplay <command>`.+3. **pip:** Python 3.11 or newer in a virtual environment, then `pip install -U agentplay` and run `agentplay <command>`.++If none of these is available, ask me before installing uv with its official installer: `curl -LsSf https://astral.sh/uv/install.sh | sh` on macOS and Linux, or `powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"` on Windows.++Below, `agentplay` means whichever form you picked.++## Confirm the version++Run `agentplay --version` and tell me the version.++## Find the agents with sessions on this machine++Run `agentplay agents`. A filled mark (`●`) means that agent's folder exists on this machine, not that it holds sessions; the build step below confirms that.++If no agent is marked, or the build finds no sessions, ask me where my sessions live and set the matching variable for the remaining commands: `AGENTPLAY_CLAUDE_HOMES`, `AGENTPLAY_CODEX_HOMES`, `AGENTPLAY_CURSOR_HOMES`, `AGENTPLAY_COPILOT_HOMES`, `AGENTPLAY_COPILOT_VSCODE_HOMES`, `AGENTPLAY_OPENCODE_HOMES` or `AGENTPLAY_KIRO_HOMES` (comma-separated paths). On WSL, Windows-side sessions are under `/mnt/c/Users/<name>/`.++## Build the session maps++Run `agentplay build` and summarise its output: how many sessions were found, built, unchanged and skipped. If it found none, go back to the previous step and ask me where my sessions live. Then run `agentplay list --limit 5` and show me the newest sessions.++## Start the viewer++Start it in the background, because it keeps running: `agentplay view --no-build`. It serves on `http://127.0.0.1:7317` and opens my browser. If port 7317 is busy, it picks a free port and says so; either way it prints the URL it is serving on (`Viewer → http://127.0.0.1:<port>/`). Use that URL from here on.++## Verify it and hand over++Check `/api/status` on the port the viewer printed, for example `http://127.0.0.1:7317/api/status` (with `curl -s` on macOS and Linux, `curl.exe -s` or `Invoke-RestMethod` on Windows). It should return `"available": true` with a `mapCount` above 0.++Then tell me the URL, how to stop the server, and that later runs of `agentplay` rebuild only the sessions that changed.++EXECUTE NOW: complete the TODO list above until the DONE WHEN condition holds.diff --git a/python/LICENSE b/python/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/python/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/python/NOTICE b/python/NOTICEnew file mode 100644index 0000000..78da9dd--- /dev/null+++ b/python/NOTICE@@ -0,0 +1,13 @@+Agentplay+Copyright 2026 Entelligence AI, Inc.++This product is licensed under the Apache License, Version 2.0 (see LICENSE).++This product includes ideas and small, clearly scoped data tables from the+following open-source projects. No source file from either project is copied+or linked; see THIRD_PARTY_NOTICES.md for exactly what was used.++ * SuperBased Observer (https://github.com/superbasedapp/observer)+ Apache License 2.0, Copyright 2026 Gaja AI.+ * agentacct (https://github.com/mikehasa/agentacct)+ MIT License, Copyright (c) 2026 agentacct contributors.diff --git a/python/README.md b/python/README.mdnew file mode 100644index 0000000..b2c4dd2--- /dev/null+++ b/python/README.md@@ -0,0 +1,13 @@+# agentplay++See what your coding agent actually did: replay every session as a map and a timeline. Local, open source, and it works across Claude Code, Codex, Cursor, Copilot, OpenCode and Kiro.++```bash+uvx agentplay # build redacted replays of your local sessions, open the viewer+agentplay list # list built sessions+agentplay export <id> # write one session's map to a file you can share+```++There are no runtime dependencies, and your session data never leaves your machine. No account is required. The only network call is the optional email signup in the viewer, which sends the email, a random install id kept in `~/.agentplay/account.json`, the version and a timestamp; set `AGENTPLAY_NO_NETWORK=1` or `DO_NOT_TRACK=1` to switch it off. See the repository README for details.++Full documentation: https://github.com/Entelligence-AI/agentplaydiff --git a/python/THIRD_PARTY_NOTICES.md b/python/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..66bc0c6--- /dev/null+++ b/python/THIRD_PARTY_NOTICES.md@@ -0,0 +1,86 @@+# Third-party notices++This package ports ideas and small, clearly-scoped data tables from two+open-source projects, following one rule: "port ideas+and data tables, not code". No source file from either project is copied,+vendored, or linked at build or run time. This notice exists as a good-faith+attribution for the specific material listed below, independent of what+either license strictly requires for that material.++## SuperBased Observer (github.com/superbasedapp/observer)++Apache License, Version 2.0. Copyright 2026 Gaja AI. Full license text:+http://www.apache.org/licenses/LICENSE-2.0++What was ported:++- **Tool taxonomy rows** — `python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py`+ (`_COPILOT_VSCODE`), row values (raw tool name → canonical name) cross-checked+ against observer's `internal/tooltax/table.go` for the `copilot`/`copilot-vscode`+ agent rows, then re-verified independently against real local transcript data+ (see that module's own docstring) before being written down. No table.go+ source text is included verbatim.+- **Design pattern** — the copilot-vscode session parser+ (`python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot_vscode.py`)+ follows the same snapshot-plus-patch replay approach and per-request model+ resolution fallback order (resolvedModel → modelId → session-level+ selectedModel, skipping internal routing aliases at each tier) that+ observer's `internal/adapter/copilot/modern.go` uses, independently+ implemented in Python against this codebase's own `SpanData`/`TraceData`+ shapes and verified against real local data, not ported as code.++## agentacct (github.com/mikehasa/agentacct)++MIT License. Copyright (c) 2026 agentacct contributors. Full license text+included below.++What was used: no code. Three product ideas informed the design: cost-basis+labels distinguishing billed, estimated and unknown cost; a Reported-vs-Verified+task outcome; and a per-task estimate of subscription plan usage.++```+MIT License++Copyright (c) 2026 agentacct contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```++## Bundled viewer dependencies++The Python wheel ships the built web viewer (`agentplay/viewer/`), which is a+bundle of the viewer's production npm dependencies (React, React DOM, Base UI,+TanStack Query, cmdk, nuqs, zod, clsx, tailwind-merge, class-variance-authority,+Phosphor and Lucide icons, and their transitive dependencies) plus two font+families, Inter and JetBrains Mono, from `@fontsource-variable`.++License families found in that tree (`pnpm licenses list --prod`):++- **MIT**: the large majority of packages.+- **ISC** and **0BSD**: one package each.+- **Apache-2.0**: one package.+- **SIL Open Font License 1.1 (OFL-1.1)**: the Inter and JetBrains Mono font+ files. The OFL requires its license and copyright notice to travel with the+ fonts, which the generated THIRD_PARTY_LICENSES.txt does.++The exact package list, versions, and the full license text of each are+generated at build time by `scripts/collect_viewer_licenses.mjs` (run by+`pnpm run build` in `viewer/`) into `THIRD_PARTY_LICENSES.txt`, which is copied+into the wheel next to the viewer's `index.html` at `agentplay/viewer/THIRD_PARTY_LICENSES.txt`.+The file is generated, not committed, so it always matches the lockfile.diff --git a/python/pyproject.toml b/python/pyproject.tomlnew file mode 100644index 0000000..33fa53f--- /dev/null+++ b/python/pyproject.toml@@ -0,0 +1,60 @@+[build-system]+requires = ["hatchling>=1.27"]+build-backend = "hatchling.build"++[project]+name = "agentplay"+version = "0.1.3"+description = "Replay your coding-agent sessions (Claude Code, Codex, Cursor, Copilot, OpenCode, Kiro) as a map and a timeline. Local only."+readme = "README.md"+license = "Apache-2.0"+license-files = ["LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md"]+requires-python = ">=3.11"+authors = [{ name = "Entelligence AI" }]+keywords = ["claude-code", "codex", "cursor", "copilot", "coding-agent", "observability", "developer-tools"]+classifiers = [+ "Development Status :: 3 - Alpha",+ "Environment :: Console",+ "Intended Audience :: Developers",+ "Operating System :: OS Independent",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Programming Language :: Python :: 3.14",+ "Topic :: Software Development :: Quality Assurance",+]+dependencies = []++[project.urls]+Homepage = "https://github.com/Entelligence-AI/agentplay"+Issues = "https://github.com/Entelligence-AI/agentplay/issues"+Source = "https://github.com/Entelligence-AI/agentplay"+Security = "https://github.com/Entelligence-AI/agentplay/security/policy"++[project.scripts]+agentplay = "agentplay.cli:main"++[project.optional-dependencies]+dev = ["pytest>=8", "ruff>=0.6", "jsonschema>=4"]++[tool.hatch.build.targets.wheel]+packages = ["src/agentplay"]+artifacts = ["src/agentplay/viewer/**"]++[tool.hatch.build.targets.sdist]+include = ["src/agentplay", "tests", "README.md", "LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md"]+artifacts = ["src/agentplay/viewer/**"]++[tool.pytest.ini_options]+testpaths = ["tests"]+pythonpath = ["src"]++[tool.ruff]+line-length = 120+target-version = "py311"+extend-exclude = ["src/agentplay/_core"]++[tool.ruff.lint]+select = ["E", "F", "W", "I", "B", "UP"]+ignore = ["E501"]diff --git a/python/src/agentplay/__init__.py b/python/src/agentplay/__init__.pynew file mode 100644index 0000000..b02068e--- /dev/null+++ b/python/src/agentplay/__init__.py@@ -0,0 +1,6 @@+"""Agentplay: replay coding-agent sessions as a map and a timeline.++Everything runs locally. See https://github.com/Entelligence-AI/agentplay.+"""++__version__ = "0.1.3"diff --git a/python/src/agentplay/__main__.py b/python/src/agentplay/__main__.pynew file mode 100644index 0000000..dd8a8c9--- /dev/null+++ b/python/src/agentplay/__main__.py@@ -0,0 +1,5 @@+import sys++from .cli import main++sys.exit(main())diff --git a/python/src/agentplay/_claude_role.py b/python/src/agentplay/_claude_role.pynew file mode 100644index 0000000..64c5b33--- /dev/null+++ b/python/src/agentplay/_claude_role.py@@ -0,0 +1,45 @@+"""Claude Code transcript role detection."""++from __future__ import annotations++import json+++def claude_subagent_transcript(data: bytes) -> bool:+ """Whether this transcript is a Claude Code subagent's, not a session of its own.++ Claude Code writes a subagent's turns to their own file and marks every+ conversation record ``isSidechain: true``. Newer builds front-load metadata+ records (``queue-operation``, ``last-prompt``, ``ai-title``) that carry no+ flag, so checking only the first line lets a subagent file pass as a+ standalone session.++ The test is ALL, not ANY: a real session that merely used subagents has its+ own unflagged turns. Only a transcript whose every conversation record is+ flagged is itself a subagent's.++ Args:+ data: raw transcript bytes.++ Returns:+ True only when at least one conversation record is a sidechain and none+ is not. False for an empty, unparseable, or ordinary transcript.+ """+ saw_sidechain = False+ for raw in data.split(b"\n"):+ raw = raw.strip()+ if not raw:+ continue+ try:+ record = json.loads(raw)+ except (ValueError, UnicodeDecodeError):+ continue+ if not isinstance(record, dict):+ continue+ if record.get("type") not in ("user", "assistant"):+ continue+ if record.get("isSidechain") is True:+ saw_sidechain = True+ continue+ return False+ return saw_sidechaindiff --git a/python/src/agentplay/_core/__init__.py b/python/src/agentplay/_core/__init__.pynew file mode 100644index 0000000..bdbf249--- /dev/null+++ b/python/src/agentplay/_core/__init__.py@@ -0,0 +1,3 @@+"""Agent-transcript compute: parsing, segmentation, metrics, pricing.++The single source for the coding-agent parse/segment-input/metrics compute."""diff --git a/python/src/agentplay/_core/claude_edit_evidence.py b/python/src/agentplay/_core/claude_edit_evidence.pynew file mode 100644index 0000000..ff84efe--- /dev/null+++ b/python/src/agentplay/_core/claude_edit_evidence.py@@ -0,0 +1,397 @@+"""Recover full-line edit evidence from Claude's recorded successful patch result."""++from difflib import SequenceMatcher+from typing import Any++from agentplay._core.code_authorship import (+ MAX_EDITS_PER_CALL,+ MAX_HASHES_PER_CALL,+ extract_edit_evidence,+ line_fingerprints,+)+++def result_patches(lines: list[dict]) -> dict[str, dict | None]:+ """Index native results; None fences invalid/conflicting IDs from legacy fallback."""+ results: dict[str, dict] = {}+ conflicting: set[str] = set()+ for line in lines:+ result = line.get("toolUseResult")+ message = line.get("message")+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, list):+ continue+ blocks = [b for b in content if isinstance(b, dict) and b.get("type") == "tool_result"]+ for block in blocks:+ key = block.get("tool_use_id")+ if not isinstance(key, str) or not key:+ continue+ if block.get("is_error"):+ conflicting.add(key)+ elif "toolUseResult" in line:+ if len(blocks) != 1 or not isinstance(result, dict):+ conflicting.add(key)+ elif key in results and results[key] != result:+ conflicting.add(key)+ else:+ results[key] = result+ return {**results, **dict.fromkeys(conflicting)}+++def call_edit_evidence(+ tool_name: Any, tool_input: Any, native: Any, *, has_native: bool, successful: bool+) -> dict:+ """Choose a Claude call's edit evidence: its native result when that is the truth.++ Edit always prefers its recorded patch: a present-but-unverifiable result+ yields ``invalid_edits`` rather than the weaker request-string capture. A+ Write whose result is an ``update`` (it overwrote an existing file) replays+ as that result's hunks, because a full-content ``write`` cannot be placed+ over a base; a fenced Write result (conflicting or invalid) yields+ ``invalid_edits`` like a fenced Edit. Every other call keeps request-based+ capture.++ Args:+ tool_name: The tool's name as recorded.+ tool_input: The tool_use input.+ native: This call's entry from ``result_patches`` (None when fenced).+ has_native: Whether ``result_patches`` has an entry for this call.+ successful: Whether the call produced a non-error result.++ Returns:+ A ``{"status", "edits"}`` evidence dict.+ """+ name = tool_name.lower() if isinstance(tool_name, str) else ""+ if (+ successful+ and has_native+ and (+ name == "edit"+ # None is result_patches' conflict fence: never fall back to the request.+ or (+ name == "write"+ and (native is None or isinstance(native, dict) and native.get("type") == "update")+ )+ )+ ):+ return extract_result_edit(tool_name, tool_input, native) or {+ "status": "invalid_edits",+ "edits": [],+ }+ return extract_edit_evidence(tool_name, tool_input, successful=successful)+++def extract_result_edit(tool_name: str, tool_input: Any, result: Any) -> dict | None:+ """Hash a verified native Edit/overwriting-Write result; mismatches yield no evidence.++ The patch records the actual complete lines changed by the tool, including+ boundary text omitted from an Edit substring. A Write over an existing file+ records an ``update`` patch of the same shape, verified against the written+ content (and the original file when recorded). No current working-tree read+ is used to reconstruct historical content. No source text leaves this helper.+ """+ if (+ not isinstance(tool_name, str)+ or tool_name.lower() not in {"edit", "write"}+ or not isinstance(tool_input, dict)+ or not isinstance(result, dict)+ ):+ return None+ write = tool_name.lower() == "write"+ path = tool_input.get("file_path")+ if (+ not isinstance(path, str)+ or not path+ or result.get("filePath") != path+ or result.get("userModified") is not False+ ):+ return None+ if write:+ written = tool_input.get("content")+ if (+ result.get("type") != "update"+ or not isinstance(written, str)+ or result.get("content") != written+ or len(written) > 1_000_000+ ):+ return None+ elif (+ result.get("oldString") != tool_input.get("old_string")+ or result.get("newString") != tool_input.get("new_string")+ or not isinstance(tool_input.get("old_string"), str)+ or not tool_input["old_string"]+ or not isinstance(tool_input.get("new_string"), str)+ or type(result.get("replaceAll")) is not bool+ or type(tool_input.get("replace_all", False)) is not bool+ or result["replaceAll"] != tool_input.get("replace_all", False)+ ):+ return None+ hunks = result.get("structuredPatch")+ if not isinstance(hunks, list) or not 0 < len(hunks) <= MAX_EDITS_PER_CALL:+ return None+ original = result.get("originalFile")+ reference = None+ if write:+ if isinstance(original, str):+ if len(original) > 1_000_000:+ return None+ reference = (original.splitlines(), written.splitlines())+ elif original is not None:+ return None+ elif isinstance(original, str):+ if len(original) > 1_000_000 or tool_input["old_string"] not in original:+ return None+ replacements = original.count(tool_input["old_string"]) if result["replaceAll"] else 1+ if (+ len(original)+ + replacements * (len(tool_input["new_string"]) - len(tool_input["old_string"]))+ > 1_000_000+ ):+ return None+ updated = original.replace(+ tool_input["old_string"],+ tool_input["new_string"],+ -1 if result["replaceAll"] else 1,+ )+ reference = (original.splitlines(), updated.splitlines())+ elif original is not None:+ return None+ reconstructed = []+ next_original_line = 0+ direct_match = len(hunks) == 1 or result.get("replaceAll") is True+ edits = []+ total = 0+ total_chars = 0+ last_old = last_new = 0+ for hunk in hunks:+ if not isinstance(hunk, dict):+ return None+ if any(+ type(hunk.get(k)) is not int or hunk[k] < 0+ for k in ("oldStart", "newStart", "oldLines", "newLines")+ ):+ return None+ if hunk["oldStart"] == 0:+ return None+ if hunk["oldStart"] < last_old or hunk["newStart"] < last_new:+ return None+ last_old = hunk["oldStart"] + hunk["oldLines"]+ last_new = hunk["newStart"] + hunk["newLines"]+ lines = hunk.get("lines")+ if not isinstance(lines, list):+ return None+ before, after = [], []+ for line in lines:+ if (+ not isinstance(line, str)+ or not line+ or line[0] not in " +-"+ or len(line.splitlines()) != 1+ or line.splitlines()[0] != line+ or any(0xD800 <= ord(c) <= 0xDFFF for c in line)+ ):+ return None+ total_chars += len(line)+ if total_chars > 1_000_000:+ return None+ if line[0] != "+":+ before.append(line[1:])+ if line[0] != "-":+ after.append(line[1:])+ if (+ len(before) != hunk["oldLines"]+ or len(after) != hunk["newLines"]+ or not before+ or before == after+ ):+ return None+ if reference is not None:+ old_start = hunk["oldStart"] - 1+ new_start = max(0, hunk["newStart"] - 1)+ if (+ old_start < 0+ or reference[0][old_start : old_start + len(before)] != before+ or reference[1][new_start : new_start + len(after)] != after+ ):+ return None+ reconstructed.extend(reference[0][next_original_line:old_start])+ reconstructed.extend(after)+ next_original_line = old_start + len(before)+ if reference is None and write:+ # No original recorded: the full written content still pins every+ # hunk's after side to its exact position.+ new_start = max(0, hunk["newStart"] - 1)+ if written.splitlines()[new_start : new_start + len(after)] != after:+ return None+ elif reference is None:+ before_text = "\n".join(before) + "\n"+ after_text = "\n".join(after) + "\n" if after else ""+ direct_match = direct_match and _matches_overlapping_replacement(+ before_text,+ after_text,+ tool_input["old_string"],+ tool_input["new_string"],+ result["replaceAll"],+ )+ total += len(before) + len(after)+ if total > MAX_HASHES_PER_CALL:+ return None+ edits.append(+ {+ "path": path,+ "operation": "replace",+ "before": line_fingerprints("\n".join(before) + "\n"),+ "after": line_fingerprints("\n".join(after) + "\n") if after else [],+ }+ )+ if reference is not None:+ reconstructed.extend(reference[0][next_original_line:])+ if reconstructed != reference[1]:+ return None+ if (+ reference is None+ and not write+ and not direct_match+ and not _matches_requested_changes(+ hunks, tool_input["old_string"], tool_input["new_string"], result["replaceAll"]+ )+ ):+ return None+ return {"status": "captured", "edits": edits}+++def _matches_overlapping_replacement(+ before: str, after: str, old: str, new: str, replace_all: bool+) -> bool:+ """Check a full replacement or a clipped patch with consistent shared context."""+ replacements = before.count(old) if replace_all else 1+ if len(before) + replacements * (len(new) - len(old)) > 1_000_000:+ return False+ if old in before and before.replace(old, new, -1 if replace_all else 1) == after:+ return True+ if replace_all or len(old) + len(new) > 1_000_000:+ return False+ prefix = 0+ while prefix < min(len(old), len(new)) and old[prefix] == new[prefix]:+ prefix += 1+ suffix = 0+ while suffix < min(len(old), len(new)) - prefix and old[-suffix - 1] == new[-suffix - 1]:+ suffix += 1+ old_core = old[prefix : len(old) - suffix]+ new_core = new[prefix : len(new) - suffix]+ needle, haystack = (old_core, before) if old_core else (new_core, after)+ if not needle:+ return False+ position = haystack.find(needle)+ for _ in range(64):+ if position < 0:+ return False+ start = position - prefix+ if before[:position] + new_core + before[position + len(old_core) :] == after:+ if all(+ observed[max(0, start) : min(len(observed), start + len(requested))]+ == requested[max(0, -start) : min(len(requested), len(observed) - start)]+ for observed, requested in ((before, old), (after, new))+ ):+ return True+ position = haystack.find(needle, position + 1)+ return False+++def _matches_requested_changes(hunks: list[dict], old: str, new: str, replace_all: bool) -> bool:+ """Validate clipped hunks against request changes, positions and overlapping context.++ Native patches can omit unchanged lines from a long replacement. Align each+ changed group with the request diff; only the request's boundary lines may+ have surrounding file text, and that surrounding text must remain unchanged.+ """+ old_lines, new_lines = old.splitlines(), new.splitlines()+ if len(old) + len(new) > 1_000_000 or len(old_lines) + len(new_lines) > MAX_HASHES_PER_CALL:+ return False+ expected = [+ op+ for op in SequenceMatcher(None, old_lines, new_lines, autojunk=False).get_opcodes()+ if op[0] != "equal"+ ]+ actual = []+ for hunk in hunks:+ old_pos, new_pos = hunk["oldStart"] - 1, max(0, hunk["newStart"] - 1)+ group = None+ for line in [*hunk["lines"], " "]:+ if line[0] == " ":+ if group is not None:+ actual.append(group)+ group = None+ old_pos += 1+ new_pos += 1+ else:+ if group is None:+ group = [old_pos, new_pos, [], []]+ if line[0] == "-":+ group[2].append(line[1:])+ old_pos += 1+ else:+ group[3].append(line[1:])+ new_pos += 1+ if (+ not expected+ or not actual+ or len(actual) % len(expected)+ or (not replace_all and len(actual) != len(expected))+ ):+ return False+ for occurrence in range(len(actual) // len(expected)):+ offsets = None+ for group, (_, i1, i2, j1, j2) in zip(actual[occurrence * len(expected) :], expected, strict=False):+ before, after = "\n".join(group[2]), "\n".join(group[3])+ wanted_before, wanted_after = "\n".join(old_lines[i1:i2]), "\n".join(new_lines[j1:j2])+ position = before.find(wanted_before)+ matched = False+ while position >= 0:+ prefix, suffix = before[:position], before[position + len(wanted_before) :]+ if (+ (not prefix or (i1 == j1 == 0 and "\n" not in prefix))+ and (+ not suffix+ or (+ i2 == len(old_lines)+ and j2 == len(new_lines)+ and not old.endswith("\n")+ and not new.endswith("\n")+ and "\n" not in suffix+ )+ )+ and after == prefix + wanted_after + suffix+ and (wanted_before or not before)+ ):+ matched = True+ break+ position = before.find(wanted_before, position + 1) if wanted_before else -1+ alignment = (group[0] - i1, group[1] - j1)+ if not matched or (offsets is not None and alignment != offsets):+ return False+ offsets = alignment+ if offsets[1] - offsets[0] != occurrence * (new.count("\n") - old.count("\n")):+ return False+ for hunk in hunks:+ for marker, start, offset, lines, text in (+ ("+", hunk["oldStart"] - 1, offsets[0], old_lines, old),+ ("-", max(0, hunk["newStart"] - 1), offsets[1], new_lines, new),+ ):+ visible = [line[1:] for line in hunk["lines"] if line[0] != marker]+ for index, line in enumerate(visible):+ relative = start + index - offset+ if not 0 <= relative < len(lines):+ continue+ expected_line = lines[relative]+ if relative == 0 and relative == len(lines) - 1 and not text.endswith("\n"):+ valid = expected_line in line+ elif relative == 0:+ valid = line.endswith(expected_line)+ elif relative == len(lines) - 1 and not text.endswith("\n"):+ valid = line.startswith(expected_line)+ else:+ valid = line == expected_line+ if not valid:+ return False+ return Truediff --git a/python/src/agentplay/_core/code_authorship.py b/python/src/agentplay/_core/code_authorship.pynew file mode 100644index 0000000..c581504--- /dev/null+++ b/python/src/agentplay/_core/code_authorship.py@@ -0,0 +1,401 @@+"""Content-free edit evidence and conservative surviving-line attribution.++PR creation, commit execution and billing are deliberately absent from this+module. Fingerprints describe observed edits, not an assertion that an LLM+invented the code. Unobserved or ambiguous transformations remain unknown.+"""++from __future__ import annotations++from collections import Counter+from difflib import SequenceMatcher+from hashlib import sha256+import json+import re+from typing import Any+from urllib.parse import urlsplit++ALGORITHM_VERSION = "edit-replay-v1"+MAX_HASHES_PER_CALL = 2048+MAX_EDITS_PER_CALL = 32+++def canonical_repository(remote: str) -> str | None:+ """Return host/owner/repository without credentials or transport aliases."""+ if not isinstance(remote, str):+ return None+ candidate = remote.strip()+ ssh = re.fullmatch(r"[^/@\s]+@([^/:\s]+):(.+)", candidate)+ if ssh:+ candidate = "ssh://" + ssh[1] + "/" + ssh[2]+ try:+ parsed = urlsplit(candidate)+ except ValueError:+ return None+ if parsed.scheme not in {"http", "https", "ssh"} or not parsed.hostname:+ return None+ path = parsed.path.strip("/").removesuffix(".git")+ if len(path.split("/")) < 2 or any(p in {"", ".", ".."} for p in path.split("/")):+ return None+ if not re.fullmatch(r"[A-Za-z0-9_.\-/]+", path):+ return None+ return (+ parsed.hostname.lower()+ + "/"+ + (path.lower() if parsed.hostname.lower() == "github.com" else path)+ )+++def line_fingerprints(content: str) -> list[str]:+ """Hash exact lines, normalizing only line-ending representation.++ Whitespace and empty lines remain significant. No raw content is returned.+ """+ return [sha256(line.encode("utf-8")).hexdigest() for line in content.splitlines()]+++def _patch_edits(patch: str) -> list[dict[str, Any]]:+ """Decode the explicit apply_patch format without evaluating shell or JS."""+ lines = patch.splitlines()+ if not lines or lines[0] != "*** Begin Patch" or lines[-1] != "*** End Patch":+ raise ValueError("unsupported_patch")+ edits: list[dict[str, Any]] = []+ path: str | None = None+ kind = ""+ moved = False+ before: list[str] = []+ after: list[str] = []++ def flush() -> None:+ if path and (before or after):+ edits.append({"path": path, "operation": kind, "before": before[:], "after": after[:]})+ before.clear()+ after.clear()++ for line in lines[1:-1]:+ if line.startswith(("*** Add File: ", "*** Update File: ", "*** Delete File: ")):+ flush()+ path = line.split(": ", 1)[1]+ kind = "create" if line.startswith("*** Add") else "replace"+ moved = False+ if line.startswith("*** Delete"):+ edits.append({"path": path, "operation": "delete", "before": [], "after": []})+ path = None+ elif line.startswith("@@"):+ flush()+ elif line == "*** End of File":+ continue+ elif line.startswith("*** Move to:"):+ if not path or kind != "replace" or moved or before or after:+ raise ValueError("unsupported_rename")+ destination = line.removeprefix("*** Move to:").strip()+ if not destination:+ raise ValueError("missing_path")+ # The provider's verified previous_filename supplies the old base;+ # captured changes belong to the post-move path, not a guessed alias.+ path = destination+ moved = True+ elif path and line.startswith((" ", "+", "-")):+ if line[0] != "+":+ before.append(line[1:])+ if line[0] != "-":+ after.append(line[1:])+ else:+ raise ValueError("unsupported_patch")+ flush()+ return edits+++def extract_edit_evidence(tool_name: str, tool_input: Any, *, successful: bool) -> dict[str, Any]:+ """Extract bounded line digests from successful, explicit edit operations.++ Paths are as recorded in the transcript here; callers must resolve each to an exact+ repository and relative path before shipping. Unsupported calls never emit+ partial evidence. Shell commands are not treated as edits by their name.+ """+ if not successful:+ return {"status": "not_successful", "edits": []}+ if not isinstance(tool_name, str):+ return {"status": "unsupported_tool", "edits": []}+ name = tool_name.lower().rsplit(".", 1)[-1]+ try:+ obj = json.loads(tool_input) if isinstance(tool_input, str) else tool_input+ except (TypeError, ValueError, RecursionError):+ obj = tool_input+ raw: list[dict[str, Any]] = []+ try:+ if name in {"edit", "str_replace", "str_replace_editor", "multiedit"} and isinstance(+ obj, dict+ ):+ if obj.get("command") not in {None, "str_replace"}:+ raise ValueError("unsupported_operation")+ path = obj.get("file_path") or obj.get("path")+ changes = obj.get("edits") if name == "multiedit" else [obj]+ if not isinstance(changes, list):+ raise ValueError("invalid_edits")+ for change in changes:+ old, new = (+ change.get("old_string", change.get("old_str", change.get("oldString"))),+ change.get("new_string", change.get("new_str", change.get("newString"))),+ )+ if (+ not isinstance(old, str)+ or not isinstance(new, str)+ or not old+ or change.get("replace_all", change.get("replaceAll"))+ ):+ raise ValueError("unsupported_replacement")+ old, new = (+ re.sub(r"\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]", "\n", value)+ for value in (old, new)+ )+ # Only newline-delimited interiors prove complete line boundaries.+ # A substring can also match an unrelated complete line in the PR.+ if not (+ old.startswith("\n")+ and old.endswith("\n")+ and new.startswith("\n")+ and new.endswith("\n")+ ):+ raise ValueError("unsupported_partial_line")+ raw.append(+ {+ "path": path,+ "operation": "replace",+ "before": old.split("\n")[1:-1],+ "after": new.split("\n")[1:-1],+ }+ )+ elif name in {"write", "write_file", "create_file"} and isinstance(obj, dict):+ content = obj.get("content", obj.get("file_text"))+ if not isinstance(content, str):+ raise ValueError("invalid_content")+ raw.append(+ {+ "path": obj.get("file_path") or obj.get("path"),+ "operation": "write",+ "before": [],+ "after": content.splitlines(),+ }+ )+ elif name == "apply_patch":+ patch = obj.get("patch", obj.get("input")) if isinstance(obj, dict) else obj+ if not isinstance(patch, str):+ raise ValueError("invalid_patch")+ raw = _patch_edits(patch)+ else:+ return {"status": "unsupported_tool", "edits": []}+ if (+ len(raw) > MAX_EDITS_PER_CALL+ or sum(len(e["before"]) + len(e["after"]) for e in raw) > MAX_HASHES_PER_CALL+ ):+ raise ValueError("capture_limit")+ if any(not isinstance(e["path"], str) or not e["path"] for e in raw):+ raise ValueError("missing_path")+ for edit in raw:+ for side in ("before", "after"):+ edit[side] = [sha256(line.encode("utf-8")).hexdigest() for line in edit[side]]+ return {"status": "captured" if raw else "no_edit", "edits": raw}+ except UnicodeError:+ return {"status": "invalid_input", "edits": []}+ except (ValueError, TypeError, AttributeError) as exc:+ return {"status": str(exc) if isinstance(exc, ValueError) else "invalid_input", "edits": []}+++def _unique_position(haystack: list[str], needle: list[str]) -> int | None:+ if not needle:+ return None+ positions = [+ i for i in range(len(haystack) - len(needle) + 1) if haystack[i : i + len(needle)] == needle+ ]+ return positions[0] if len(positions) == 1 else None+++def inserted_hashes(edits: list[dict[str, Any]], added_file: bool) -> dict[str, set[str]]:+ """Return, per session, the line digests its observed edits inserted into one path.++ A replace edit inserts the after-lines of its non-equal ``SequenceMatcher``+ opcodes; unchanged context lines are not insertions. Create/write edits count+ only for a file the PR adds, the same rule the replay applies, so a whole-file+ write over existing content never claims every line it happens to repeat.++ Args:+ edits: Observed edits for one repository path, each carrying ``session_id``.+ added_file: True when the PR adds the file (no base content).++ Returns:+ ``{session_id: {line_digest, ...}}``; a session with no insertions maps to+ an empty set.+ """+ inserted: dict[str, set[str]] = {}+ for edit in edits:+ hashes = inserted.setdefault(edit["session_id"], set())+ if edit["operation"] in {"create", "write"}:+ if added_file:+ hashes.update(edit["after"])+ elif edit["operation"] != "delete":+ opcodes = SequenceMatcher(None, edit["before"], edit["after"], autojunk=False)+ for tag, _a, _b, c, d in opcodes.get_opcodes():+ if tag != "equal":+ hashes.update(edit["after"][c:d])+ return inserted+++def attribute_file(+ base: str | None,+ head: str | None,+ edits: list[dict[str, Any]],+ *,+ exact_sessions: frozenset[str] = frozenset(),+) -> dict[str, Any]:+ """Replay ordered observed edits and count ownership surviving at the PR head.++ Each surviving added line is ``exclusive`` to its replay owner unless+ another session also inserted that line's digest on this path, which makes+ it ``shared`` (best-of-N attempts and parallel branches). When exactly one of+ the claiming sessions has an exact commit link to the PR and it is the owner,+ the line stays exclusive. A surviving deletion of a base line is credited to+ its owner in ``agent_deleted_lines``/``deletion_sessions`` and+ ``session_events`` but never counts as exclusive or shared: removing lines+ alone must not make a link strong.++ Args:+ base: Immutable PR-base file content, or None for an absent file.+ head: Immutable PR-head file content, or None for a deleted file.+ edits: Chronologically ordered digests for this exact repository/path,+ each carrying session_id and event_id (and ``completed_at`` when+ known). Callers enforce clocks and repository identity before+ passing evidence.+ exact_sessions: Sessions with an exact commit link to this PR; used only+ to break ties on shared lines.++ Returns:+ Added-line denominator, observed agent lines per session, unknown lines,+ matched event identities and unresolved-edit reasons, plus per session+ ``exclusive_lines``/``shared_lines`` counts and ``session_events``+ (``{session_id: {event_id: completed_at or None}}`` for every event that+ owns a credited line). No cost allocation or human-authored+ classification is inferred.+ """+ original = line_fingerprints(base or "")+ final = line_fingerprints(head or "")+ virtual = original[:]+ owners: list[tuple[str, str] | None] = [None] * len(virtual)+ base_indices: list[int | None] = list(range(len(original)))+ removed_owners: dict[int, tuple[str, str]] = {}+ unresolved: list[dict[str, str]] = []+ origins: dict[str, set[str]] = {}+ for edit in edits:+ signature = json.dumps([edit["operation"], edit["before"], edit["after"]])+ origins.setdefault(signature, set()).add(edit["session_id"])+ for edit in edits:+ before, after = edit["before"], edit["after"]+ owner = (edit["session_id"], edit["event_id"])+ signature = json.dumps([edit["operation"], before, after])+ assigned_owner = owner if len(origins[signature]) == 1 else None+ if assigned_owner is None:+ unresolved.append({"event_id": owner[1], "reason": "ambiguous_source_session"})+ operation = edit["operation"]+ if operation in {"create", "write"}:+ if virtual or base is not None:+ unresolved.append({"event_id": owner[1], "reason": "missing_before_snapshot"})+ continue+ virtual, owners = after[:], [assigned_owner] * len(after)+ base_indices = [None] * len(after)+ continue+ if operation == "delete":+ # A filename-only deletion provides no content evidence connecting+ # this checkout to the PR base. Keep that attribution unknown.+ unresolved.append({"event_id": owner[1], "reason": "missing_before_snapshot"})+ continue+ position = _unique_position(virtual, before)+ if position is None:+ unresolved.append({"event_id": owner[1], "reason": "before_not_unique_or_missing"})+ continue+ replacement: list[tuple[str, str] | None] = []+ replacement_indices: list[int | None] = []+ for tag, a, b, c, d in SequenceMatcher(None, before, after, autojunk=False).get_opcodes():+ if tag == "equal":+ replacement_indices.extend(base_indices[position + a : position + b])+ else:+ replacement_indices.extend([None] * (d - c))+ if assigned_owner is not None:+ for index in base_indices[position + a : position + b]:+ if index is not None:+ removed_owners[index] = assigned_owner+ replacement.extend(+ owners[position + a : position + b]+ if tag == "equal"+ else [assigned_owner] * (d - c)+ )+ virtual[position : position + len(before)] = after+ owners[position : position + len(before)] = replacement+ base_indices[position : position + len(before)] = replacement_indices++ surviving: dict[int, tuple[str, str]] = {}+ if virtual == final:+ surviving = {i: owner for i, owner in enumerate(owners) if owner is not None}+ else:+ # A later manual edit may move or replace lines. Only unique equal+ # sequences retain ownership; repeated boilerplate is not a tie-break.+ for block in SequenceMatcher(None, virtual, final, autojunk=False).get_matching_blocks():+ if not block.size:+ continue+ sequence = virtual[block.a : block.a + block.size]+ if (+ _unique_position(virtual, sequence) is None+ or _unique_position(final, sequence) is None+ ):+ continue+ for offset in range(block.size):+ owner = owners[block.a + offset]+ if owner is not None:+ surviving[block.b + offset] = owner+ added: set[int] = set()+ deleted_indices: set[int] = set()+ for tag, a, b, c, d in SequenceMatcher(None, original, final, autojunk=False).get_opcodes():+ if tag != "equal":+ added.update(range(c, d))+ deleted_indices.update(range(a, b))+ counts = Counter(surviving[i][0] for i in added if i in surviving)+ # Reappearing/moved base text is not evidence of a surviving deletion.+ final_hashes = set(final)+ surviving_deletions = {+ i: owner+ for i, owner in removed_owners.items()+ if i in deleted_indices and original[i] not in final_hashes+ }+ deletion_counts = Counter(owner[0] for owner in surviving_deletions.values())+ events = sorted({surviving[i][1] for i in added if i in surviving})+ credited = [(surviving[i], final[i]) for i in sorted(added) if i in surviving]+ inserted = inserted_hashes(edits, base is None)+ completed_at = {edit["event_id"]: edit.get("completed_at") for edit in edits}+ exclusive: Counter[str] = Counter()+ shared: Counter[str] = Counter()+ for (sid, _event_id), digest in credited:+ claimants = {sid} | {other for other, hashes in inserted.items() if digest in hashes}+ if len(claimants) == 1 or (claimants & exact_sessions) == {sid}:+ exclusive[sid] += 1+ else:+ shared[sid] += 1+ session_events: dict[str, dict[str, str | None]] = {}+ deletions = [owner for _, owner in sorted(surviving_deletions.items())]+ for sid, event_id in [owner for owner, _ in credited] + deletions:+ session_events.setdefault(sid, {})[event_id] = completed_at.get(event_id)+ return {+ "algorithm_version": ALGORITHM_VERSION,+ "added_lines": len(added),+ "deleted_lines": len(deleted_indices),+ "agent_deleted_lines": sum(deletion_counts.values()),+ "unknown_deleted_lines": len(deleted_indices) - sum(deletion_counts.values()),+ "deletion_sessions": dict(deletion_counts),+ "agent_added_lines": sum(counts.values()),+ "unknown_added_lines": len(added) - sum(counts.values()),+ "sessions": dict(counts),+ "event_ids": events,+ "deletion_event_ids": sorted({owner[1] for owner in surviving_deletions.values()}),+ "unresolved_edits": unresolved,+ "exclusive_lines": dict(exclusive),+ "shared_lines": dict(shared),+ "session_events": session_events,+ }diff --git a/python/src/agentplay/_core/ingestion/__init__.py b/python/src/agentplay/_core/ingestion/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/python/src/agentplay/_core/ingestion/coding_agent/__init__.py b/python/src/agentplay/_core/ingestion/coding_agent/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_paths.py b/python/src/agentplay/_core/ingestion/coding_agent/_paths.pynew file mode 100644index 0000000..8630c9c--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_paths.py@@ -0,0 +1,110 @@+"""Separator-agnostic handling of transcript paths.++Every path here arrives as a *string* recorded on someone else's machine, and on+Windows the two producers disagree:++* ``git rev-parse --show-toplevel`` — which the CLI stamps into the manifest's+ ``repo_roots`` — always emits forward slashes, even on Windows:+ ``C:/Users/Ada/repo``.+* tool-call file paths inside a transcript are whatever the agent saw, which on+ Windows is native and backslashed: ``C:\\Users\\Ada\\repo\\src\\main.py``.++The callers compare with ``"/"`` throughout (``startswith(root + "/")``,+``rstrip("/").rsplit("/", 1)``). Against a Windows pair those comparisons would+never match: file ops would stay unresolved, sessions would not be attributed to+a repo, and project names would be the whole path instead of its last segment.++Normalizing at the boundary keeps that POSIX-shaped code correct without+teaching every call site about backslashes. Deliberately string-only: these are+remote paths from another OS, so `pathlib` — which applies the *local*+platform's rules — would be wrong here.+"""++from __future__ import annotations++import re++# A Windows absolute path, in the two forms that exist: a drive letter+# (``C:/``, ``c:\``) and a UNC share (``\\server\share``, ``//server/share``).+# Both are case-insensitive on Windows. Matched against the already-normalized+# (forward-slash) form, so only ``/`` needs handling on the UNC branch. The+# drive letter also matches bare (``C:`` end-of-string): `to_posix` trims the+# trailing slash off a drive-root path, and requiring the slash here left a+# repo whose git toplevel is the drive root un-folded — and therefore+# unattributed against its case-folded file keys.+_WINDOWS_ABSOLUTE = re.compile(r"^([A-Za-z]:(/|$)|//[^/])")+++def to_posix(path: str) -> str:+ """Rewrite backslash separators as forward slashes, dropping trailing ones.++ Args:+ path: A path string produced on any platform.++ Returns:+ The path with ``/`` separators and no trailing separator; a bare root+ keeps its slash (``"/"`` stays ``"/"``).++ Example:+ >>> to_posix("C:\\\\Users\\\\Ada\\\\repo\\\\")+ 'C:/Users/Ada/repo'+ >>> to_posix("/home/ada/repo")+ '/home/ada/repo'+ """+ if not path:+ return path+ normalized = path.replace("\\", "/")+ stripped = normalized.rstrip("/")+ return stripped or normalized[:1]+++def basename(path: str) -> str:+ """Last segment of a path, whichever separator it uses.++ Replaces the POSIX-only ``path.rstrip("/").rsplit("/", 1)[-1]`` idiom, which+ hands back the *entire* string for a backslashed Windows path — surfacing+ ``C:\\Users\\Ada\\repo`` as a project name instead of ``repo``.++ Args:+ path: A path string produced on any platform.++ Returns:+ The final segment, or ``""`` when the input is empty.++ Example:+ >>> basename("C:\\\\Users\\\\Ada\\\\repo")+ 'repo'+ >>> basename("/home/ada/repo/")+ 'repo'+ """+ return to_posix(path).rsplit("/", 1)[-1] if path else ""+++def match_key(path: str) -> str:+ """Canonical form for comparing two paths that may differ in style.++ Beyond separators, Windows paths are case-insensitive and the case varies by+ producer (``C:/`` from git, ``c:\\`` from a shell), so a case-sensitive compare+ can still miss. Both Windows absolute forms count: drive letters *and* UNC+ shares — ``//Server/Share/repo`` from git against+ ``\\server\\share\\repo\\src\\main.py`` from a transcript is the same+ path on a network drive, and must also compare equal.++ Case folding applies **only** to those forms: POSIX filesystems are+ case-sensitive, and folding them would conflate genuinely distinct files.++ Args:+ path: A path string produced on any platform.++ Returns:+ A string safe to compare against — or prefix-match with — the+ `match_key` of another path.++ Example:+ >>> match_key("C:\\\\Users\\\\Ada\\\\Repo") == match_key("c:/users/ada/repo")+ True+ >>> match_key("/home/Ada") == match_key("/home/ada")+ False+ """+ normalized = to_posix(path)+ return normalized.casefold() if _WINDOWS_ABSOLUTE.match(normalized) else normalizeddiff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/__init__.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/_base.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/_base.pynew file mode 100644index 0000000..f68ad2a--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/_base.py@@ -0,0 +1,132 @@+"""TraceSource Protocol — what every coding-agent source implements.++Sources discover sessions and parse transcripts into the universal+`SpanData` shape. Anything that conforms to this Protocol can plug into+the ingestion pipeline without the rest of the code knowing where the+data came from.++# Why a Protocol and not an ABC++Sources are duck-typed across multiple parser implementations (local+Claude, local Codex, local Copilot, and so on). A `Protocol` needs no+inheritance chain and no metaclass gymnastics. `@runtime_checkable` makes+`isinstance(x, TraceSource)` work at the factory boundary.++# Identity convention — source-prefixed session IDs++Every source emits `session_id` strings prefixed by the source name+so collisions across sources are impossible:++- `local:{agent}:{file_stem}`++The prefix is also how the `source` value on a session is derived.+Sources MUST emit the same prefix consistently: it must match+`source.source_name`.+"""++from __future__ import annotations++from datetime import datetime+import json+from typing import Protocol, runtime_checkable++from agentplay._core.ingestion.coding_agent.metrics import session_tool_distribution+from agentplay._core.ingestion.coding_agent.spans import DiscoveredSession, SpanData++# Hard backstop only: a transcript larger than this is rejected rather than+# parsed. It exists to catch pathological multi-GB transcripts that would+# exhaust memory, and is set high so a normal-but-heavy session never trips it.+MAX_SESSION_BYTES = 1024 * 1024 * 1024 # 1 GB+++class OversizedSessionError(Exception):+ """A session's raw transcript exceeds ``MAX_SESSION_BYTES``.++ Raised by the local source while it reads a session (and any subagent+ transcripts merged into it) when the combined size passes the cap. The+ transcript is not parsed.+ """+++def build_sidecar_signals(spans: list[SpanData]) -> dict:+ """Session-payload signal blobs derived from a session's spans.++ Pulls the parser-stashed ``harness.session_signals`` (slash commands, skills used,+ captured skill definitions, interrupts) off the root span and adds the+ per-tool distribution computed from the spans. These are opaque count+ blobs kept in the session payload rather than on per-session fields.++ ``skill_definitions`` must stay in the key list below: omitting it+ silently drops captured SKILL.md bodies for every source relying on+ this shared helper.+ """+ out: dict = {}+ root = next((s for s in spans if s.parent_id is None), None)+ if root is not None:+ raw = root.attributes.get("harness.session_signals")+ if raw:+ try:+ sig = json.loads(raw) if isinstance(raw, str) else raw+ except json.JSONDecodeError:+ sig = None+ if isinstance(sig, dict):+ for key in (+ "slash_commands",+ "slash_invocations",+ "skills_used",+ "skill_definitions",+ "interrupts",+ ):+ if sig.get(key):+ out[key] = sig[key]+ tool_dist = session_tool_distribution(spans)+ if tool_dist:+ out["tool_distribution"] = tool_dist+ return out+++@runtime_checkable+class TraceSource(Protocol):+ """The contract every coding-agent source adapter satisfies.++ The built-in implementation lives under `local/`.+ """++ source_name: str+ """Currently 'local'. Used as the prefix for+ `session_id` values this source emits and as the `source` value on+ the resulting session."""++ def capabilities(self) -> frozenset[str]:+ """What this source can produce. Used by extractors to decide+ whether they have enough signal — e.g. token counts may be+ absent for some sources, in which case `total_cost_usd`+ is left null on the Session."""+ ...++ def discover_sessions(+ self,+ start_time: datetime | None = None,+ end_time: datetime | None = None,+ ) -> list[DiscoveredSession]:+ """Walk the source and list every session in `[start_time, end_time]`.++ Returns lightweight `DiscoveredSession` rows — span count + time+ bounds, enough for the pipeline to decide what to fetch. The+ actual transcript content arrives via `get_spans_by_session`.+ """+ ...++ def get_spans_by_session(self, session_id: str) -> list[SpanData]:+ """Parse the session's transcript into a span list.++ Returned spans MUST include a root `Session` span (with+ `parent_id is None`) carrying session-level attributes+ (`user.id`, `llm.model_name`, `session.id`, optional+ `project.name`, plus any source-specific harness signals+ under `harness.*` keys).+ """+ ...+++__all__ = ["TraceSource"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/_jsonl_utils.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/_jsonl_utils.pynew file mode 100644index 0000000..d2461ec--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/_jsonl_utils.py@@ -0,0 +1,808 @@+"""Shared parsing helpers for Claude Code JSONL transcripts.++The local ~/.claude file adapter and any other consumer of the Claude+Code JSONL format share these helpers: noise filtering, turn grouping,+session-signal extraction (slash commands / skill loads / interrupts).++The format is defined by Claude Code itself - keeping the helpers in one+place means a Claude Code format bump is a single edit.+"""++from __future__ import annotations++from collections import Counter, deque+from datetime import datetime, UTC+import hashlib+import json+import logging+import re++from agentplay._core.ingestion.coding_agent.skill_names import normalize_skill_name++logger = logging.getLogger(__name__)++# Line types that are housekeeping, not conversation.+SKIP_TYPES = {"progress", "system", "file-history-snapshot", "queue-operation", "summary"}++# Regex helpers for signal extraction.+_RE_COMMAND_NAME = re.compile(r"<command-name>([^<]+)</command-name>", re.IGNORECASE)+_RE_COMMAND_MESSAGE = re.compile(r"<command-message>([^<]+)</command-message>", re.IGNORECASE)+_RE_SKILL_DIR = re.compile(r"base directory for this skill:\s*(\S+)", re.IGNORECASE)+# Modern skill-invocation tool names (assistant `tool_use` blocks). Current+# Claude Code invokes a skill via the `Skill` tool (input `{"skill": "<name>"}`),+# NOT the legacy "base directory for this skill:" user-message injection matched+# by `_RE_SKILL_DIR` above — so on current versions skills went entirely+# uncounted. Lower-cased for case-insensitive matching.+_SKILL_TOOL_NAMES = {"skill", "activate_skill"}+# Bound on per-run slash-command entries a session reports.+_MAX_SLASH_INVOCATIONS = 200+++def parse_dt(value: str) -> datetime:+ """Parse an ISO-8601 timestamp (with `Z` shorthand) into an AWARE datetime.++ An offset-less value is read as UTC: every caller compares or maxes these+ against `Z`/offset timestamps from the same transcript, and Python refuses+ a naive/aware comparison — one bare timestamp would otherwise turn a+ whole session's capture into a TypeError.+ """+ value = value.replace("Z", "+00:00")+ parsed = datetime.fromisoformat(value)+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return parsed+++def safe_parse_dt(value: object) -> datetime | None:+ """:func:`parse_dt`, but never raises: None for a non-string or malformed value."""+ if not isinstance(value, str) or not value:+ return None+ try:+ return parse_dt(value)+ except ValueError:+ return None+++def drop_untyped(container: dict, keys: tuple[str, ...], kind: type | tuple) -> None:+ """Delete the ``keys`` whose value is not a ``kind``, so ``.get`` defaults apply.++ ``.get(key, default)`` only covers an ABSENT key; a retyped value (``null``, a+ number where an id string belongs) would raise deep inside a parser. Removing+ it at the boundary makes it read as absent instead.+ """+ for key in keys:+ if key in container and not isinstance(container[key], kind):+ del container[key]+++def as_count(value: object) -> int:+ """``value`` as a token count: 0 when absent, null, negative, or not numeric."""+ if isinstance(value, bool):+ return 0+ try:+ return max(int(value), 0) # type: ignore[call-overload]+ except (TypeError, ValueError, OverflowError):+ return 0+++def as_dict(value: object) -> dict:+ """``value`` when it is a dict, else ``{}`` -- for fields a newer schema may retype."""+ return value if isinstance(value, dict) else {}+++def extract_user_content(message: dict) -> str:+ """Pull the text out of a user message — handles str / list-of-blocks."""+ if not isinstance(message, dict):+ return ""+ content = message.get("content", "")+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ texts = []+ for block in content:+ if isinstance(block, dict):+ if block.get("type") == "text":+ texts.append(block.get("text", ""))+ elif isinstance(block, str):+ texts.append(block)+ return "\n".join(texts)+ return str(content)+++def extract_tool_results(message: dict) -> dict[str, dict]:+ """Pull `tool_use_id -> tool_result_block` from a user message."""+ if not isinstance(message, dict):+ return {}+ content = message.get("content", [])+ if not isinstance(content, list):+ return {}+ results = {}+ for block in content:+ if isinstance(block, dict) and block.get("type") == "tool_result":+ tool_use_id = block.get("tool_use_id", "")+ if tool_use_id:+ results[tool_use_id] = block+ return results+++# Reserved key stamped onto every parsed line dict by `parse_lines`: the byte+# offset of the line's START within the normalized stream. Leading+# underscore keeps it visually distinct from real transcript keys; nothing in+# any known agent transcript format uses this name. Consumers that+# hash or re-serialize a line dict must exclude it.+SOURCE_OFFSET_KEY = "_ent_offset"+# A content hash of the raw record, stamped beside the offset so every+# parser's spans carry the same anchor block.+SOURCE_HASH_KEY = "_ent_hash"+# The addressable row/document key of a record from a REWRITTEN source (a+# vscdb composer bubble id, an opencode message id) - the resume anchor where+# a byte offset cannot be one. Stamped by the producer that knows the key+# (the Cursor synthesizer, opencode's own record id), carried as+# `source.row_cursor`, and - like every stamp key - excluded from the content+# hash, so adding it never re-identifies a turn already stored under its hash.+SOURCE_ROW_CURSOR_KEY = "_ent_row_cursor"+_STAMP_KEYS = frozenset({SOURCE_OFFSET_KEY, SOURCE_HASH_KEY, SOURCE_ROW_CURSOR_KEY})++SOURCE_KIND_JSONL = "jsonl"+SOURCE_KIND_SQLITE = "sqlite"+SOURCE_KIND_JSON_DOC = "json_doc"+++def record_hash(record: object) -> str | None:+ """Content-anchored identity of one raw record.++ 16 hex chars of sha1 over the canonical JSON of the record with the+ parser's own stamps removed — identical regardless of where a rewrite+ placed the line. None when the record cannot be serialised.+ """+ if not isinstance(record, dict):+ return None+ try:+ body = {k: v for k, v in record.items() if k not in _STAMP_KEYS}+ canonical = json.dumps(body, sort_keys=True, default=str)+ except (TypeError, ValueError):+ return None+ return hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:16]+++def _has_usable_type(obj: object) -> bool:+ """A decoded line is a record only when it is a dict whose ``type`` (if any) is a string.++ Every parser keys on ``type`` (set membership, dict dispatch); a list or dict+ there is unhashable and would abort the whole session.+ """+ return isinstance(obj, dict) and isinstance(obj.get("type", ""), str)+++def _drop_bad_timestamp(obj: dict) -> None:+ """Remove a non-ISO ``timestamp`` so downstream time math treats it as absent.++ The rest of the record is still readable, so it is kept rather than skipped.+ """+ if "timestamp" in obj and safe_parse_dt(obj["timestamp"]) is None:+ del obj["timestamp"]+++def parse_jsonl_records(data: bytes) -> list[dict]:+ """Every dict line of a JSONL document, each stamped with its source anchors.++ The generic sibling of :func:`parse_lines` (which additionally applies+ claude-code's noise filter): no type is skipped, every kept dict carries+ :data:`SOURCE_OFFSET_KEY` (byte offset of its line's start in the+ normalized stream, stable across re-parses of an append-only file) and+ :data:`SOURCE_HASH_KEY` (see :func:`record_hash`). Used by the parsers of+ every append-only JSONL agent (codex, kiro, opencode, cursor-agent+ transcripts) so all of them carry the same anchor block.+ """+ if isinstance(data, bytes):+ data = data.decode("utf-8", errors="replace").encode("utf-8")+ records: list[dict] = []+ offset = 0+ skipped = 0+ for raw_line in data.split(b"\n"):+ line_start = offset+ offset += len(raw_line) + 1+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):+ skipped += 1+ continue+ if not _has_usable_type(obj):+ skipped += 1+ continue+ obj[SOURCE_HASH_KEY] = record_hash(obj)+ obj[SOURCE_OFFSET_KEY] = line_start+ _drop_bad_timestamp(obj)+ records.append(obj)+ if skipped:+ logger.debug("skipped %d unreadable JSONL line(s)", skipped)+ return records+++def source_attrs(+ record: object, *, kind: str = SOURCE_KIND_JSONL, row_cursor: str | None = None+) -> dict:+ """The span attributes of the source-cursor block for one originating record.++ ``source.kind`` always; ``source.byte_offset`` and ``source.content_hash``+ when the record carries the stamps (:func:`parse_jsonl_records`), the+ hash computed on the fly for an unstamped record so a parser that builds+ its own records still anchors them; ``source.row_cursor`` when the caller+ passes one or the record carries :data:`SOURCE_ROW_CURSOR_KEY`+ (rewritten sources whose records have an addressable key).+ Pure.+ """+ attrs: dict = {"source.kind": kind}+ if isinstance(row_cursor, str) and row_cursor:+ attrs["source.row_cursor"] = row_cursor+ if not isinstance(record, dict):+ return attrs+ offset = record.get(SOURCE_OFFSET_KEY)+ if offset is not None:+ attrs["source.byte_offset"] = offset+ content_hash = record.get(SOURCE_HASH_KEY) or record_hash(record)+ if content_hash is not None:+ attrs["source.content_hash"] = content_hash+ stamped = record.get(SOURCE_ROW_CURSOR_KEY)+ if "source.row_cursor" not in attrs and isinstance(stamped, str) and stamped:+ attrs["source.row_cursor"] = stamped+ return attrs+++def parse_lines(data: bytes) -> list[dict]:+ """Parse JSONL bytes into dicts, skipping non-conversation lines.++ Each kept dict is stamped with :data:`SOURCE_OFFSET_KEY` — the byte+ offset of its line's start (a transcript-anchored identity, stable+ across re-parses of an append-only file because earlier bytes never move). Offsets are measured over the+ NORMALIZED stream (post `errors="replace"` re-encode below), not the+ raw file bytes — the two differ only when the file held invalid UTF-8,+ and stability across re-parses (which all run the same normalization)+ is the property that matters, not agreement with `stat().st_size`.+ """+ if isinstance(data, bytes):+ data = data.decode("utf-8", errors="replace").encode("utf-8")+ lines = []+ offset = 0+ skipped = 0+ for raw_line in data.split(b"\n"):+ line_start = offset+ offset += len(raw_line) + 1 # +1 for the split-consumed "\n"+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, RecursionError):+ skipped += 1+ continue+ if not _has_usable_type(obj):+ skipped += 1+ continue+ line_type = obj.get("type", "")+ if line_type in SKIP_TYPES:+ continue+ if "snapshot" in obj and "messageId" in obj:+ continue+ obj[SOURCE_HASH_KEY] = record_hash(obj)+ obj[SOURCE_OFFSET_KEY] = line_start+ _drop_bad_timestamp(obj)+ lines.append(obj)+ if skipped:+ logger.debug("skipped %d unreadable JSONL line(s)", skipped)+ return lines+++def _is_image_source_line(msg: dict) -> bool:+ """Image-source reference lines aren't real user turns."""+ text = extract_user_content(msg)+ return text.startswith("[Image source:") or text.startswith("[Image: source:")+++def _is_meta_message(msg: dict) -> bool:+ """Claude Code's own system markers + slash-command wrappers.++ Signals from these lines (slash-command counts, skill loads,+ interrupt counts) should be extracted via `extract_session_signals`+ BEFORE this filter runs — otherwise the data is gone.+ """+ text = extract_user_content(msg).strip()+ if not text:+ return True+ head = text[:200]+ if head.startswith("[Request interrupted by user"):+ return True+ if head.startswith("<task-notification>"):+ return True+ if head.startswith("<local-command-caveat>") or head.startswith("<local-command-stdout>"):+ return True+ if "being continued from a previous conversation" in head:+ return True+ if head.lower().startswith("base directory for this skill:"):+ return True+ if head.startswith("<command-name>/compact"):+ return True+ if head.startswith("<command-name>") or head.startswith("<command-message>"):+ stripped = _RE_COMMAND_NAME.sub("", text)+ stripped = _RE_COMMAND_MESSAGE.sub("", stripped)+ stripped = re.sub(r"<command-args>[^<]*</command-args>", "", stripped)+ stripped = stripped.strip()+ if not stripped or len(stripped) < 30:+ return True+ return False+++# Cap a captured skill body so a pathological transcript (a skill that inlines a+# huge file) can't bloat the definition store. Sized so large+# but legitimate skill bodies stay intact while a runaway inline is bounded.+_SKILL_BODY_MAX_CHARS = 65_536+++def _skill_body_after_marker(text: str) -> str:+ """Return the SKILL.md body that follows the base-directory marker line.++ A skill load injects the marker line (``base directory for this skill:+ <dir>``) followed by the skill's SKILL.md content in the same message. This+ drops the marker line and returns the remaining body, stripped and+ size-capped (:data:`_SKILL_BODY_MAX_CHARS`).++ Args:+ text: the full injected skill-load message (marker line first).++ Returns:+ The body after the marker line, or ``""`` when there's nothing after it.+ """+ _marker, _, rest = text.lstrip().partition("\n")+ return rest.strip()[:_SKILL_BODY_MAX_CHARS]+++def _skill_tool_invocations(message: object) -> list[tuple[str, str | None]]:+ """`(skill name, tool_use id)` for each assistant `Skill`/`activate_skill` call.++ The modern Claude Code skill-invocation shape: an assistant `tool_use` block+ whose `name` is in `_SKILL_TOOL_NAMES` and whose `input` carries the skill+ under `"skill"` (or `"command"`). The `tool_use` id is returned alongside so+ the caller can dedupe blocks that a compacted session re-serialized — the+ same stable id reappears across replayed turns, and `extract_session_signals`+ runs on RAW lines, before any replay-dedup pass. Empty list for any+ non-conforming message (bare string content, no tool blocks) — never raises.+ """+ if not isinstance(message, dict):+ return []+ content = message.get("content")+ if not isinstance(content, list):+ return []+ out: list[tuple[str, str | None]] = []+ for block in content:+ if not isinstance(block, dict) or block.get("type") != "tool_use":+ continue+ if str(block.get("name", "")).strip().lower() not in _SKILL_TOOL_NAMES:+ continue+ inp = block.get("input")+ if isinstance(inp, dict):+ name = inp.get("skill") or inp.get("command")+ if isinstance(name, str) and name.strip():+ tool_id = block.get("id")+ out.append((name.strip(), tool_id if isinstance(tool_id, str) else None))+ return out+++def _typed_command_for_load(canonical: str, typed_unpaired: Counter[str]) -> str | None:+ """The unpaired typed command a Skill load belongs to, or None.++ A namespaced load pairs only with the same `plugin:command`, so `xlsx:docs`+ never pairs with a typed `myplugin:docs`. A bare load (older harnesses name+ only the leaf) pairs with a typed command of that leaf when exactly one+ plugin's command with that leaf is waiting; two candidates are ambiguous+ and the load counts on its own.++ Args:+ canonical: The load's normalized skill name.+ typed_unpaired: Unpaired typed commands of this turn, by full name.++ Returns:+ The typed command's full name, or None.+ """+ if typed_unpaired.get(canonical, 0) > 0:+ return canonical+ if ":" in canonical:+ return None+ same_leaf = [n for n, c in typed_unpaired.items() if c > 0 and n.rsplit(":", 1)[-1] == canonical]+ return same_leaf[0] if len(same_leaf) == 1 else None+++def extract_session_signals(+ lines: list[dict], seen_skill_tool_ids: set[str] | None = None+) -> dict:+ """Pull structured signals from raw JSONL lines BEFORE noise filtering.++ Returns a dict with:+ slash_commands: [{"name": str, "count": int}], one count per run+ slash_invocations: [{"name": str, "record_uuid": str|None, "ts": str|None}]+ skills_used: [{"path": str, "count": int}], one per skill activation+ interrupts: {"total": int, "during_tool_use": int}++ These are stashed on the session payload for later aggregation. This+ set is the deterministic, Claude-Code-only subset of session signals.++ Args:+ seen_skill_tool_ids: Shared, mutated in place, when a caller runs+ this over a session's `main_lines` and `sidechain_lines`+ separately (`parse_claude_code`): a+ subagent's own Skill call is echoed verbatim into BOTH the+ parent transcript (`isSidechain: false`) and its own file+ (`isSidechain: true`), sharing one tool_use id. Two independent+ fresh sets would each count it once, and `fold_subagent_skills`+ would then double it. None (the default) creates a fresh,+ call-local set.+ """+ slash_counts: Counter[str] = Counter()+ # Keyed by CANONICAL skill name (``normalize_skill_name``), never the raw+ # path/name. A single skill invocation surfaces under two shapes — the+ # assistant ``Skill`` tool_use (raw ``"my-skill"``) and the injected "base+ # directory for this skill: …/skills/my-skill" marker (raw ``"skills/my-skill"``)+ # — which normalize to the same name; keying on the canonical name collapses+ # them into one entry instead of two half-counts.+ skill_counts: Counter[str] = Counter()+ # canonical skill name -> its SKILL.md body (the longest seen this session).+ # Claude Code injects the full skill content in the same synthetic message as+ # the base-directory marker, so we capture it here rather than throwing it+ # away - it's what surfaces the skill's actual definition, not just a name.+ skill_bodies: dict[str, str] = {}+ # tool_use ids of Skill calls already counted — a compacted session replays+ # prior assistant turns verbatim, so the same block reappears in raw lines.+ if seen_skill_tool_ids is None:+ seen_skill_tool_ids = set()+ # canonical names already counted via a ``Skill`` tool_use this session. The+ # base-directory marker is emitted as a CONSEQUENCE of that same tool call, so+ # it must not re-count skills already seen here (that would double-count+ # each use); it still counts skills seen ONLY via the marker (legacy sessions).+ tool_counted_skills: set[str] = set()+ # A plugin skill's tool call names it `<plugin>:<skill>`, but its marker path+ # only yields `<skill>` (the plugin's folder name need not match the+ # namespace) — and two skills (two plugins, or a plugin skill and a plain+ # one) can share that same leaf. Two failure modes a naive mapping hits:+ # - a single bare-name -> namespace VALUE let a later invocation's marker+ # resolve to an earlier, unrelated skill's namespace once their leaves+ # collided (a queue fixes this — FIFO, one entry per invocation);+ # - overwriting that value with only the LATEST invocation instead+ # mishandled one assistant message with TWO same-leaf calls before+ # either marker arrives: the first call's entry was discarded before+ # its own marker ever got a chance to consume it.+ # A queue alone reintroduces the first failure mode once some invocation's marker+ # is simply missing (a truncated transcript): its entry sits in the queue+ # forever, so a later, unrelated same-leaf call's marker pops it instead+ # of its own. What distinguishes "missing marker, safe to discard" from+ # "same-message batch, must preserve order" is exactly whether the calls+ # share a CONVERSATION turn — not merely a raw line — so each leaf's+ # queue is reset (discarding whatever a PRIOR, now-closed turn left+ # unconsumed) the first time a new turn touches it, and only appended to+ # for the rest of that same turn. A raw line index is the wrong identity+ # for this: Claude Code can emit several SEPARATE+ # assistant records within one logical turn, with a plain tool-result+ # continuation line in between (a different tool's output, not this+ # skill's own marker) — counting that as a turn boundary would reset a+ # still-pending, still-unconsumed entry that belongs later in the SAME+ # turn. Track turn identity the same way group_into_turns does: bump it+ # only on a genuine new user message, never on a tool-result/image/meta+ # continuation.+ pending_by_bare: dict[str, deque[str]] = {}+ pending_turn_by_bare: dict[str, int] = {}+ interrupts_total = 0+ interrupts_during_tool = 0+ turn_index = 0+ # typed plugin commands of the CURRENT turn whose Skill load has+ # not been seen yet, by full `plugin:command` name. The load a typed command+ # triggers is the same use, so it pairs with the command instead of+ # counting again. Reset whenever a new turn types a command.+ typed_unpaired: Counter[str] = Counter()+ typed_turn = -1+ # message uuids of typed-command records already counted. Claude+ # Code re-writes a command record verbatim (same uuid) on resume/compaction.+ seen_command_uuids: set[str] = set()+ # one entry per typed run (metadata only: name, record uuid,+ # timestamp) so a consumer can drop a resume/fork copy that landed in+ # another session file with the same record uuid.+ slash_invocations: list[dict] = []++ for line in lines:+ line_type = line.get("type")+ # Modern skill invocation lives on the ASSISTANT side: a `Skill`/+ # `activate_skill` tool call. The legacy "base directory for this skill:"+ # marker below only ever appeared in synthetic USER messages on pre-+ # Skill-tool Claude Code, so current sessions had their skills go+ # entirely uncounted (empty skill_distribution). Count both shapes.+ if line_type == "assistant":+ for skill, tool_id in _skill_tool_invocations(line.get("message", {})):+ # Count each distinct tool_use block once, even when a compacted+ # session re-serializes it across replayed turns.+ is_replay = tool_id is not None and tool_id in seen_skill_tool_ids+ if tool_id is not None:+ seen_skill_tool_ids.add(tool_id)+ canonical = normalize_skill_name(skill)+ if canonical is None:+ continue+ # Queue the resolution even on a replay:+ # a compacted session replays a marker along with its+ # triggering tool_use, and skipping the queue entry here+ # left that replayed marker with nothing to consume,+ # falling back to the bare name and splitting one skill's+ # count/body across two keys.+ bare = canonical.rsplit(":", 1)[1] if ":" in canonical else canonical+ if pending_turn_by_bare.get(bare) != turn_index:+ pending_by_bare[bare] = deque()+ pending_turn_by_bare[bare] = turn_index+ pending_by_bare[bare].append(canonical)+ # Marked whether or not this occurrence is a replay: a caller+ # sharing `seen_skill_tool_ids` across a parent/sidechain pair+ # means THIS call's own first sight+ # of the tool_id can already be `is_replay` (claimed by the+ # other call) -- its own marker's tool-uncounted fallback below+ # must still recognize the skill as tool-counted, or it+ # double-counts via that path instead. Only the COUNT itself+ # stays gated on `is_replay`.+ tool_counted_skills.add(canonical)+ if is_replay:+ continue+ paired = _typed_command_for_load(canonical, typed_unpaired) if typed_turn == turn_index else None+ if paired is not None:+ # The load a typed `/<plugin>:<command>` triggered in this+ # turn: that command already counted this use.+ typed_unpaired[paired] -= 1+ else:+ skill_counts[canonical] += 1+ continue+ if line_type != "user":+ continue+ msg = line.get("message", {})+ # Same predicate group_into_turns uses to decide "still this turn":+ # a tool-result reply, an image-source line, or a meta message never+ # opens a new one.+ if (+ not extract_tool_results(msg)+ and not _is_image_source_line(msg)+ and not _is_meta_message(msg)+ ):+ turn_index += 1+ text = extract_user_content(msg)+ if not text:+ continue++ if text.startswith("[Request interrupted by user"):+ interrupts_total += 1+ if "for tool use" in text[:60]:+ interrupts_during_tool += 1+ continue++ # One slash-command run writes BOTH tags into one message with the same+ # name (`<command-name>/x</command-name>`, `<command-message>x+ # </command-message>`). Counting each tag doubled every command on every+ # CLI, so each distinct name counts once per message.+ # `/compact` keeps its historical single count.+ message_commands = {+ name+ for regex in (_RE_COMMAND_NAME, _RE_COMMAND_MESSAGE)+ for match in regex.finditer(text)+ if (name := match.group(1).strip().lstrip("/"))+ }+ if message_commands:+ # Resume and compaction re-write a command record verbatim, same+ # uuid; the copy is not a new run.+ record_uuid = line.get("uuid")+ if isinstance(record_uuid, str) and record_uuid:+ if record_uuid in seen_command_uuids:+ message_commands = set()+ seen_command_uuids.add(record_uuid)+ for name in sorted(message_commands):+ slash_counts[name] += 1+ if len(slash_invocations) < _MAX_SLASH_INVOCATIONS:+ record_uuid = line.get("uuid")+ ts = line.get("timestamp")+ slash_invocations.append(+ {+ "name": name[:128],+ "record_uuid": record_uuid[:64] if isinstance(record_uuid, str) else None,+ "ts": ts[:40] if isinstance(ts, str) else None,+ }+ )++ # A plugin command run as `/<plugin>:<command>` is a skill use too:+ # Claude Code writes it as a slash command, and the Skill+ # load it may trigger is the same use, so that load pairs+ # with the command instead of counting again. Queued like a Skill call+ # so a base-directory marker for the same command in this turn is not+ # counted again either.+ plugin_commands = {+ canonical+ for name in message_commands+ if ":" in name and (canonical := normalize_skill_name(name)) is not None+ }+ for canonical in plugin_commands:+ bare = canonical.rsplit(":", 1)[1]+ if pending_turn_by_bare.get(bare) != turn_index:+ pending_by_bare[bare] = deque()+ pending_turn_by_bare[bare] = turn_index+ pending_by_bare[bare].append(canonical)+ if typed_turn != turn_index:+ typed_unpaired = Counter()+ typed_turn = turn_index+ typed_unpaired[canonical] += 1+ tool_counted_skills.add(canonical)+ skill_counts[canonical] += 1++ # Skill loads: Claude Code injects "base directory for this skill: <dir>"+ # at the START of a synthetic user message. Match only when the message+ # begins with the phrase — the phrase quoted mid-text (in code, docs, or+ # a nested transcript, e.g. a Rust `Regex::new(r"base directory for this+ # skill:\s*(\S+)").unwrap()`) is NOT a real skill load and would leak+ # regex fragments in as garbage skill names. Validate the captured path+ # too, so a phrase-prefixed-but-junk token can't slip through either.+ stripped = text.lstrip()+ if stripped[:200].lower().startswith("base directory for this skill:"):+ match = _RE_SKILL_DIR.match(stripped)+ if match:+ path = match.group(1).strip().rstrip("/")+ short = path.split("/.claude/", 1)[-1] if "/.claude/" in path else path+ canonical = normalize_skill_name(short)+ if canonical is not None:+ # Only a pending call from THIS turn can own the marker: a+ # marker is a meta message, so it never opens a turn and+ # always shares its own tool call's turn. An entry left by+ # an earlier turn (its own marker never arrived) is stale;+ # consuming it would file a marker-only invocation under an+ # unrelated call's namespace and drop its count.+ if pending_turn_by_bare.get(canonical) != turn_index:+ pending_by_bare.pop(canonical, None)+ pending = pending_by_bare.get(canonical)+ if pending:+ canonical = pending.popleft()+ # A typed command whose body the harness injected+ # directly has now loaded; a later Skill call in this+ # turn is a separate activation, not its load.+ if typed_turn == turn_index and typed_unpaired.get(canonical, 0) > 0:+ typed_unpaired[canonical] -= 1+ # This marker is injected as a CONSEQUENCE of a `Skill` tool+ # call already counted above (same invocation) — counting it+ # again double-counts. Increment only for skills the+ # tool path never saw (legacy pre-Skill-tool sessions, where the+ # marker is the sole signal); capture the body either way.+ if canonical not in tool_counted_skills:+ skill_counts[canonical] += 1+ # The skill's SKILL.md body is the rest of this injected+ # message (everything after the base-directory marker line).+ # Keep the longest we've seen — a later re-load can be a+ # truncated re-inject, and the fullest copy is the useful one.+ body = _skill_body_after_marker(text)+ if body and len(body) > len(skill_bodies.get(canonical, "")):+ skill_bodies[canonical] = body++ return {+ "slash_commands": [{"name": n, "count": c} for n, c in slash_counts.most_common()],+ "slash_invocations": slash_invocations,+ # ``path`` carries the canonical skill name (already normalized), which+ # eliminates the raw ``skills/<name>`` vs ``<name>`` split.+ "skills_used": [{"path": p, "count": c} for p, c in skill_counts.most_common()],+ # One captured definition per skill loaded this session (name + body).+ "skill_definitions": [+ {"name": p, "body": skill_bodies[p]}+ for p, _ in skill_counts.most_common()+ if skill_bodies.get(p)+ ],+ "interrupts": {"total": interrupts_total, "during_tool_use": interrupts_during_tool},+ }+++def fold_subagent_skills(signals: dict, subagent_signals: dict) -> dict:+ """Add a subagent transcript's skill signals into the parent's.++ Claude Code callers run :func:`extract_session_signals` separately over a+ session's own lines and its spawned subagents' (``isSidechain``) lines,+ because ``slash_commands`` and ``interrupts`` describe what the DEVELOPER+ typed — a subagent's synthetic "user" turn is the parent's own tool call,+ not a developer action, so those two stay parent-only. A subagent+ invoking a skill is different: it is still work the developer's own+ dispatch caused, and excluding it is what made a skill like a plugin's+ orchestrator-dispatched command invisible to the "skills used" counts.+ Only ``skills_used`` and+ ``skill_definitions`` fold in here; the other two keys pass through from+ ``signals`` unchanged.++ Safe to call with ``subagent_signals`` from an entirely separate+ :func:`extract_session_signals` call: a subagent's own lines carry no+ duplicate copy in the parent's lines (sessions whose only skill+ invocations were subagent-scoped carried zero parent skill entries), so+ this cannot double an invocation the parent-only call already counted.++ Args:+ signals: The parent-only :func:`extract_session_signals` result.+ subagent_signals: The same function's result over the session's+ ``isSidechain`` lines.++ Returns:+ A new dict, ``signals`` with ``skills_used``/``skill_definitions``+ folded; ``signals`` and ``subagent_signals`` are not mutated.+ """+ counts: dict[str, int] = {e["path"]: e["count"] for e in signals["skills_used"]}+ for e in subagent_signals["skills_used"]:+ counts[e["path"]] = counts.get(e["path"], 0) + e["count"]+ # Longest body wins per name, matching the same rule+ # `extract_session_signals` already applies within one call.+ bodies: dict[str, str] = {d["name"]: d["body"] for d in signals["skill_definitions"]}+ for d in subagent_signals["skill_definitions"]:+ if len(d["body"]) > len(bodies.get(d["name"], "")):+ bodies[d["name"]] = d["body"]+ ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))+ return {+ **signals,+ "skills_used": [{"path": p, "count": c} for p, c in ranked],+ "skill_definitions": [{"name": p, "body": bodies[p]} for p, _ in ranked if bodies.get(p)],+ }+++def group_into_turns(lines: list[dict]) -> list[dict]:+ """Group conversation lines into turns (user → assistant exchanges).++ Each turn dict has:+ user — the user message line (or None)+ assistants — list of assistant message lines+ tool_results — {tool_use_id: tool_result_block}+ tool_result_timestamps — {tool_use_id: timestamp}+ """+ turns: list[dict] = []+ current_turn: dict | None = None++ for line in lines:+ line_type = line.get("type", "")++ if line_type == "user":+ msg = line.get("message", {})+ tool_results = extract_tool_results(msg)++ if tool_results and current_turn:+ current_turn["tool_results"].update(tool_results)+ ts = line.get("timestamp", "")+ for tid in tool_results:+ current_turn["tool_result_timestamps"][tid] = ts+ elif _is_image_source_line(msg) and current_turn:+ pass+ elif _is_meta_message(msg):+ pass+ else:+ if current_turn:+ turns.append(current_turn)+ current_turn = {+ "user": line,+ "assistants": [],+ "tool_results": {},+ "tool_result_timestamps": {},+ }++ elif line_type == "assistant":+ if current_turn is None:+ current_turn = {+ "user": None,+ "assistants": [],+ "tool_results": {},+ "tool_result_timestamps": {},+ }+ current_turn["assistants"].append(line)++ if current_turn:+ turns.append(current_turn)++ return turns+++__all__ = [+ "SOURCE_OFFSET_KEY",+ "extract_session_signals",+ "extract_tool_results",+ "extract_user_content",+ "fold_subagent_skills",+ "group_into_turns",+ "parse_dt",+ "parse_lines",+]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/__init__.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.pynew file mode 100644index 0000000..202a0d3--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/__init__.py@@ -0,0 +1,57 @@+"""Per-agent transcript parsers.++`detect_agent(data)` reads the head lines of a JSONL file and+returns the agent type by sniffing for marker lines:++- Claude Code: `type=user|assistant` + `sessionId` field.+- Codex: `session_meta` line with `originator` starting `codex`.+- Copilot: `session.start` line with `producer="copilot-agent"` (the CLI's own+ `~/.copilot/session-state/<id>/events.jsonl`, read in place).+- Copilot in VS Code (Chat/agent mode): a `.jsonl` file's first line is the+ `kind=0` snapshot envelope with a `requests` key. The sibling `.json`+ (single pretty-printed document, no self-contained line) isn't detected+ here at all -- `LocalSource._index_copilot_vscode_file` checks that shape+ directly.+- Cursor: synthesized header line with `type="cursor_store_session"`.+- Kiro: synthesized header line with `type="kiro_session"`.+- opencode: materialized records carrying a `message` object and a `parts` list.++Each parser exposes `parse_X(data, trace_id, user_id=None,+project_name=None) -> (TraceData, [SpanData])`. They all emit the+same span shape — a root Session span plus per-turn Turn spans plus+per-tool tool spans - so downstream code doesn't branch on agent.+"""++from __future__ import annotations++from agentplay._core.ingestion.coding_agent._sources.local.parsers.base import (+ AgentType,+ detect_agent,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.claude_code import parse_claude_code+from agentplay._core.ingestion.coding_agent._sources.local.parsers.codex import parse_codex+from agentplay._core.ingestion.coding_agent._sources.local.parsers.copilot import parse_copilot+from agentplay._core.ingestion.coding_agent._sources.local.parsers.copilot_vscode import (+ parse_copilot_vscode,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_agent_transcript import (+ parse_cursor_agent_transcript,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ parse_cursor_store,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.kiro import parse_kiro+from agentplay._core.ingestion.coding_agent._sources.local.parsers.opencode import parse_opencode++__all__ = [+ "AgentType",+ "detect_agent",+ "parse_claude_code",+ "parse_codex",+ "parse_copilot",+ "parse_copilot_vscode",+ "parse_cursor_agent_transcript",+ "parse_cursor_store",+ "parse_kiro",+ "parse_opencode",+]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.pynew file mode 100644index 0000000..b280d0d--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/base.py@@ -0,0 +1,153 @@+"""Agent detection from a JSONL file head.++Sniffs the head lines for marker shapes. Returns None when no+known agent matches — `LocalSource` skips those files rather than+guessing.+"""++from __future__ import annotations++from enum import StrEnum+import json+++class AgentType(StrEnum):+ """Agent enum used by the parsers + LocalSource dispatch.++ The string values are the agent names stamped on sessions.+ """++ CLAUDE_CODE = "claude-code"+ CODEX = "codex"+ COPILOT = "copilot"+ COPILOT_VSCODE = "copilot-vscode"+ OPENCODE = "opencode"+ CURSOR = "cursor"+ KIRO = "kiro"+++def detect_agent(data: bytes) -> AgentType | None:+ """Detect the agent that produced this transcript.++ Returns None when no marker matches — the caller treats that as+ "skip this file" rather than guessing.+ """+ # Every line the caller handed us, not a fixed count: see the note in+ # `_read_head`. It returns complete lines and already bounds the read.+ # Transcripts can open with many lines of `ai-title` / `agent-name` /+ # `permission-mode` metadata before the first `user` record, so a line cap+ # here would miss valid files.+ for raw_line in data.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ # UnicodeDecodeError: a fixed-size byte head can split a+ # multi-byte UTF-8 char at the boundary (unicode+ # in transcripts). Skip the unparseable line, don't crash+ # the whole index walk.+ continue++ # A bare JSON primitive/array is valid JSON but not an agent header+ # line; `.get()` on it would raise AttributeError and abort the whole+ # index walk and drop every session in the directory.+ if not isinstance(obj, dict):+ continue++ line_type = obj.get("type", "")++ # Cursor CLI/agent: synthesized header line, always first (see+ # agentplay.materialize.find_cursor_store_candidates).+ # Distinct enough (no other agent emits this `type`) that checking+ # it anywhere in the head, not just line 1, is safe.+ if line_type == "cursor_store_session":+ return AgentType.CURSOR++ # Kiro: synthesized header line, always first (see+ # agentplay.materialize.find_kiro_candidates). Same+ # rationale as Cursor's — no other agent emits this `type`.+ if line_type == "kiro_session":+ return AgentType.KIRO++ # Codex: session_meta with codex originator.+ if line_type == "session_meta":+ payload = obj.get("payload")+ # `.get("payload", {})` only defaults a MISSING key: an explicit null+ # (or a list) came through as-is and `.get` on it aborted detection,+ # and with it the whole index walk, on one malformed line.+ payload = payload if isinstance(payload, dict) else {}+ originator = payload.get("originator", "")+ originator = originator if isinstance(originator, str) else ""+ # Case-insensitive: the Codex CLI/TUI write `codex_cli_rs` / `codex-tui`,+ # but the Codex Desktop app writes `Codex Desktop` (capital C) — a+ # case-sensitive check would miss every Desktop session.+ if originator.lower().startswith("codex"):+ return AgentType.CODEX+ # A launcher wrapping the Codex CLI overwrites+ # `originator` with its own name, so the check above misses it.+ # `model_provider` is a field Codex's own session_meta schema+ # always carries (see codex.py's parse_codex, which relies on it+ # being present there and only there); no other agent's `type`+ # is `session_meta`, so its presence here is Codex-specific+ # without hardcoding a launcher name.+ if isinstance(payload.get("model_provider"), str) and payload["model_provider"]:+ return AgentType.CODEX++ # Copilot: session.start with producer=copilot-agent.+ if line_type == "session.start":+ data_field = obj.get("data")+ if isinstance(data_field, dict) and data_field.get("producer") == "copilot-agent":+ return AgentType.COPILOT++ # Copilot in VS Code (Chat/agent mode): the .jsonl snapshot-and-patch+ # log's FIRST line is always the kind=0 snapshot envelope, {"kind": 0,+ # "v": {<session doc with "requests">}}. No other agent uses a bare+ # top-level "kind" int (every branch above keys on "type", "role" or+ # "message"), so this is unambiguous without needing the nested check+ # -- the "requests" key is still required to reject an unrelated format+ # that happens to reuse "kind": 0 for something else entirely. The+ # sibling .json (single whole document, pretty-printed) format can't be+ # detected here at all -- this scanner parses per LINE, and a+ # pretty-printed document has no single self-contained JSON line -- so+ # `_index_copilot_vscode_file` checks that shape directly instead.+ if obj.get("kind") == 0:+ snapshot = obj.get("v")+ if isinstance(snapshot, dict) and "requests" in snapshot:+ return AgentType.COPILOT_VSCODE++ # Claude Code: type=user|assistant + sessionId field.+ if line_type in ("user", "assistant") and "sessionId" in obj:+ return AgentType.CLAUDE_CODE++ # opencode: materialized records carry a `message` object + `parts` list (and a+ # capital-ID `sessionID`); no top-level `type`, so this can't collide with Claude Code.+ message = obj.get("message")+ if (+ isinstance(message, dict)+ and message.get("role") in ("user", "assistant")+ and isinstance(obj.get("parts"), list)+ ):+ return AgentType.OPENCODE++ # Cursor agent-transcript (third Cursor format): a TOP-LEVEL `role` ++ # a `message.content` object, with NO `type`/`sessionId` (Claude Code /+ # Codex / cursor_store / kiro all carry `type`) and NO `parts` (opencode).+ # Files live at `~/.cursor/projects/<slug>/agent-transcripts/<uuid>/*.jsonl`.+ # Returns CURSOR so it shares the Cursor home/index; `_index_cursor_store_file`+ # re-sniffs the head to pick the agent-transcript vs store.db parser.+ if (+ obj.get("role") in ("user", "assistant")+ and "type" not in obj+ and "sessionId" not in obj+ and "parts" not in obj+ and isinstance(message, dict)+ and "content" in message+ ):+ return AgentType.CURSOR++ return None+++__all__ = ["AgentType", "detect_agent"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/claude_code.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/claude_code.pynew file mode 100644index 0000000..9bcb259--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/claude_code.py@@ -0,0 +1,995 @@+"""Parse a local Claude Code JSONL session into the universal SpanData shape.++Reads files written by Claude Code under `~/.claude/projects/<slug>/`.+Most of the work runs through the shared `_jsonl_utils` helpers. This parser additionally+de-duplicates turns that get replayed by session-continuation events+(Claude Code re-serialises earlier exchanges into a fresh session file+when you `/compact`, producing duplicate Turn timestamps).+"""++from __future__ import annotations++from datetime import UTC, datetime+import json+import logging+from typing import Any++from agentplay._core.claude_edit_evidence import call_edit_evidence, result_patches+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ SOURCE_HASH_KEY,+ SOURCE_OFFSET_KEY,+ drop_untyped,+ extract_session_signals,+ extract_user_content,+ fold_subagent_skills,+ group_into_turns,+ parse_dt,+ parse_lines,+ safe_parse_dt,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.claude_cost_summary import (+ extract_cost_summary,+)+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+)+from agentplay._core.ingestion.coding_agent.skill_names import skill_call_attributes+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData, model_id_or_none++logger = logging.getLogger(__name__)+++def _turn_index_for(at: datetime | None, turn_starts: list[datetime | None]) -> int:+ """1-based turn whose start is the latest at or before ``at``.++ A call before the first turn, or one whose turn has no clock, lands on+ turn 1; a call with no timestamp of its own lands on the last turn+ (subagent files are appended after the parent, so "latest" is the+ honest default). 0 when there are no turns at all.+ """+ if not turn_starts:+ return 0+ if at is None:+ return len(turn_starts)+ index = 1+ latest_start = None+ for i, started in enumerate(turn_starts, start=1):+ if (+ started is not None+ and started <= at+ and (latest_start is None or started > latest_start)+ ):+ index = i+ latest_start = started+ return index+++def _merge_replayed_turns(turns: list[dict]) -> list[dict]:+ """Keep each original turn anchor and merge its replayed observations."""+ unique: dict[tuple[str, str], dict] = {}+ for turn in turns:+ user = turn.get("user")+ anchor = user if user is not None else turn["assistants"][0]+ key = (+ "user" if user is not None else "assistant",+ anchor.get("uuid") or anchor[SOURCE_HASH_KEY],+ )+ if key not in unique:+ unique[key] = turn+ continue+ original = unique[key]+ seen = {line[SOURCE_HASH_KEY] for line in original["assistants"]}+ for line in turn["assistants"]:+ if line[SOURCE_HASH_KEY] not in seen:+ original["assistants"].append(line)+ seen.add(line[SOURCE_HASH_KEY])+ for tool_id, result in turn["tool_results"].items():+ timestamp = turn["tool_result_timestamps"].get(tool_id)+ old_timestamp = original["tool_result_timestamps"].get(tool_id)+ if tool_id not in original["tool_results"] or (+ timestamp and (not old_timestamp or parse_dt(timestamp) >= parse_dt(old_timestamp))+ ):+ original["tool_results"][tool_id] = result+ original["tool_result_timestamps"][tool_id] = timestamp+ return list(unique.values())+++def _message_key(line: dict) -> str:+ """Native message identity, with stable record identity for legacy records."""+ return line.get("message", {}).get("id") or line.get("uuid") or line[SOURCE_HASH_KEY]+++def _fallback_iterations(line: dict) -> list | None:+ """Validate iteration evidence before choosing its accounting contract.++ Evidence that cannot be trusted is ignored (None), so the response keeps its+ top-level usage rather than aborting the session.+ """+ message = line.get("message", {})+ iterations = (message.get("usage") or {}).get("iterations")+ if iterations is None or iterations == []:+ return None+ if not isinstance(iterations, list) or not all(+ isinstance(item, dict) and isinstance(item.get("type"), str) and item["type"]+ for item in iterations+ ):+ logger.debug("ignoring malformed Claude usage iterations")+ return None+ for item in iterations:+ for field in (+ "input_tokens",+ "output_tokens",+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+ ):+ value = (+ item.get(field)+ if field in {"input_tokens", "output_tokens"}+ else item.get(field, 0)+ )+ if type(value) is not int or value < 0:+ logger.debug("ignoring Claude usage iterations with a bad token count")+ return None+ if len(iterations) == 1 and iterations[0].get("model") in (None, message.get("model")):+ # Native ordinary responses carry one message iteration with model=null.+ # They retain the top-level streaming usage contract.+ return None+ # Any other shape means the response served more than one billed attempt —+ # a fallback after a refusal, or a side call such as an advisor iteration+ # whose tokens the top-level usage does not include. Per-attempt accounting+ # is the only contract that bills all of them. An iteration without a model+ # was served by the response's own model, so only a present one is checked.+ if not all(+ model_id_or_none(item["model"]) for item in iterations if item.get("model") is not None+ ):+ logger.debug("ignoring Claude usage iterations with a bad model")+ return None+ return iterations+++def _expand_fallback_requests(requests: dict) -> dict:+ """Use per-attempt usage when fallback makes top-level usage serving-only.++ Anthropic's refusals-and-fallback billing contract bills each attempt that+ produced output. An earlier refusal with no output is not billed. Retain+ the original response's source/clock, and distinguish attempts by position.+ Preliminary streaming fragments must not also become a top-level charge.+ """+ expanded = {}+ for key, (turn_num, fragments) in requests.items():+ snapshots = [line for line in fragments if _fallback_iterations(line) is not None]+ if not snapshots:+ expanded[key] = (turn_num, fragments)+ continue+ for line in snapshots:+ message = line["message"]+ usage = message["usage"]+ iterations = usage["iterations"]+ for index, item in enumerate(iterations):+ refused = index < len(iterations) - 1 or message.get("stop_reason") == "refusal"+ if refused and item["output_tokens"] == 0:+ continue+ attempt_key = f"{key}:iteration:{index}"+ attempt_usage = {**item}+ # Fallback messages never carry `server_tool_use` per iteration --+ # only the message-level `usage` has it. Same carry-forward as+ # speed/service_tier below, or a fallback response's web+ # search/fetch counts become 0 on the billed attempt.+ for field in ("speed", "service_tier", "server_tool_use"):+ if (+ field not in attempt_usage+ and field in usage+ and index == len(iterations) - 1+ ):+ attempt_usage[field] = usage[field]+ # Fallback configuration can override speed per attempt. The+ # serving model's mode cannot establish a prior attempt's price.+ if index < len(iterations) - 1 and "speed" not in attempt_usage:+ attempt_usage["speed"] = "unknown"+ attempt = {+ **line,+ "requestId": f"{line['requestId']}:iteration:{index}"+ if line.get("requestId")+ else None,+ "message": {+ **message,+ "id": attempt_key,+ "model": item.get("model") or message.get("model"),+ "usage": attempt_usage,+ },+ }+ expanded.setdefault(attempt_key, (turn_num, []))[1].append(attempt)+ return expanded+++def _fallback_tool_request_id(line: dict, request_id: str | None) -> str | None:+ """Point tools in a fallback response at the billed attempt they came from."""+ if not request_id:+ return None+ if ":iteration:" in request_id:+ return request_id+ iterations = _fallback_iterations(line)+ if not iterations:+ return request_id+ billed_indexes = []+ for index, item in enumerate(iterations):+ refused = (+ index < len(iterations) - 1 or line.get("message", {}).get("stop_reason") == "refusal"+ )+ if not (refused and item["output_tokens"] == 0):+ billed_indexes.append(index)+ if not billed_indexes:+ return request_id+ return f"{request_id}:iteration:{billed_indexes[-1]}"+++def _tool_request_id(line: dict, msg_meta: dict, fallback: str | None) -> str | None:+ """Resolve a tool to the highest billed fallback attempt for its message."""+ prefix = f"{_message_key(line)}:iteration:"+ candidates = [entry for entry in msg_meta.items() if entry[0].startswith(prefix)]+ if candidates:+ _key, metadata = max(+ candidates,+ key=lambda entry: int(entry[0].rsplit(":iteration:", 1)[1]),+ )+ return metadata.get("request_id") or fallback+ return fallback+++def _subagent_edit_calls(+ trace_id: str,+ turns: list[dict],+ main_lines: list[dict],+ sidechain_lines: list[dict],+ native_results: dict[str, dict | None],+) -> list[dict[str, Any]]:+ """Captured code edits made by Agent-tool subagents, in completion order.++ Deliberately NOT tool spans: every span-derived metric (tool counts, error+ rate, tool distribution) selects spans by ``tool.name`` and+ stays parent-only. These entries exist for code-authorship replay alone and+ are kept in a separate ``subagent_edit_calls`` array. Each keeps its+ own completion time, so it replays in its real order among the parent's+ edits even when the subagent ran in the background long after its spawning+ call returned.++ Args:+ trace_id: The session's trace id; turn ids derive from it.+ turns: The parent's turns, whose start times place each call.+ main_lines: Parent lines. A tool_use id recorded there with its+ successful result is already a parent tool span (Claude Code echoes+ some subagent lines into the parent), so it is skipped here rather+ than counted twice.+ sidechain_lines: Subagent lines (``isSidechain: true``).+ native_results: ``result_patches`` over the whole folded transcript.++ Returns:+ One dict per successful call with captured, non-empty evidence:+ ``turn_id``, ``tool_name``, ``subagent_id``, ``native_call_id``,+ ``started_at``/``completed_at`` (ISO, UTC), ``cwd``, ``input_value``+ (the same 2000-char input a tool span carries, for the input digest)+ and ``edit_evidence``. Ordered by completion time, then call id.+ """++ def blocks(line: dict, kind: str) -> list[dict]:+ message = line.get("message")+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, list):+ return []+ return [b for b in content if isinstance(b, dict) and b.get("type") == kind]++ # An echoed call is the parent's only when the parent also recorded its+ # successful result; otherwise its span is unsuccessful and only the+ # sidechain carries the edit.+ parent_used = {b.get("id") for line in main_lines for b in blocks(line, "tool_use")}+ parent_calls = {+ b.get("tool_use_id")+ for line in main_lines+ for b in blocks(line, "tool_result")+ if b.get("tool_use_id") in parent_used and not b.get("is_error")+ }+ results: dict[str, tuple[dict, Any]] = {}+ for line in sidechain_lines:+ for block in blocks(line, "tool_result"):+ results[block.get("tool_use_id")] = (block, line.get("timestamp"))+ starts = [safe_parse_dt((turn.get("user") or {}).get("timestamp")) for turn in turns]+ calls: dict[str, tuple[datetime, dict[str, Any]]] = {}+ for line in sidechain_lines:+ for block in blocks(line, "tool_use"):+ call_id = block.get("id")+ if not isinstance(call_id, str) or not call_id:+ continue+ if call_id in parent_calls or call_id in calls or call_id not in results:+ continue+ result, result_at = results[call_id]+ completed = safe_parse_dt(result_at)+ if result.get("is_error") or completed is None or not line.get("agentId"):+ continue+ tool_name, tool_input = block.get("name"), block.get("input", {})+ evidence = call_edit_evidence(+ tool_name,+ tool_input,+ native_results.get(call_id),+ has_native=call_id in native_results,+ successful=True,+ )+ started = safe_parse_dt(line.get("timestamp"))+ turn_num = _turn_index_for(started or completed, starts)+ if evidence["status"] != "captured" or not evidence["edits"] or not turn_num:+ continue+ input_str = json.dumps(tool_input) if isinstance(tool_input, dict) else str(tool_input)+ calls[call_id] = (+ completed,+ {+ "turn_id": f"{trace_id}:turn:{turn_num}",+ "tool_name": tool_name,+ "subagent_id": line["agentId"],+ "native_call_id": call_id,+ "started_at": started.astimezone(UTC).isoformat() if started else None,+ "completed_at": completed.astimezone(UTC).isoformat(),+ "cwd": line.get("cwd") or "",+ "input_value": input_str[:2000],+ "edit_evidence": evidence,+ },+ )+ ordered = sorted(calls.values(), key=lambda c: (c[0], c[1]["native_call_id"]))+ return [call for _, call in ordered]+++def _billed_lines_by_turn(turns: list[dict], sidechains: list[dict]) -> dict[int, list[dict]]:+ """Assign all fragments of a request once, before summing any turn's usage."""+ requests: dict[str, tuple[int, list[dict]]] = {}+ for turn_num, lines in [+ *((i, turn["assistants"]) for i, turn in enumerate(turns, 1)),+ (0, sidechains),+ ]:+ for line in lines:+ if line.get("type") == "assistant":+ message = line.get("message", {})+ usage = message.get("usage") or {}+ if (+ message.get("model") == "<synthetic>"+ and not any(+ usage.get(key, 0)+ for key in (+ "input_tokens",+ "output_tokens",+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+ )+ )+ and not any((usage.get("cache_creation") or {}).values())+ and not any((usage.get("server_tool_use") or {}).values())+ ):+ # Harness markers retain their turn/content, but are not API+ # requests. An unpriced marker would block the whole session's bill.+ continue+ requests.setdefault(_message_key(line), (turn_num, []))[1].append(line)+ requests = _expand_fallback_requests(requests)+ starts = [safe_parse_dt((turn.get("user") or {}).get("timestamp")) for turn in turns]+ billed: dict[int, list[dict]] = {}+ for message_id, (turn_num, fragments) in requests.items():+ # One message id legitimately reaches this loop from SEVERAL files, so+ # only genuinely irreconcilable facts about the call may raise.+ # `LocalSource` folds a session's `subagents/agent-<id>.jsonl` files into+ # the parent transcript, and Claude Code writes the same assistant line+ # into every file it belongs to:+ # * a subagent's own call lands in the parent (`isSidechain: false`,+ # no `agentId`) AND in that subagent's file (`isSidechain: true`,+ # its own `agentId`);+ # * a call that spawns N subagents in parallel lands in the parent and+ # in ALL N files, each stamping a DIFFERENT `agentId` — one billed+ # call, N+1 copies, N distinct subagent ids.+ # Both shapes are duplication, not corruption: the copies share one+ # `message.id` and one `requestId`, and the token merge in+ # `parse_claude_code` is a per-message-id `max()` per component, so they+ # collapse to a single billed call exactly like streamed fragments do.+ # Raising on them ("parent ownership" / "subagent id") would abort the+ # WHOLE session's parse and drop every day it touched from the bill.+ # Model and request id still raise: those cannot legitimately differ+ # for one message id.+ metadata = {+ "model": {model_id_or_none(line.get("message", {}).get("model")) for line in fragments},+ "request id": {line.get("requestId") for line in fragments},+ }+ for field, values in metadata.items():+ if len(values - {None, ""}) > 1:+ raise ValueError(f"Conflicting {field} for Claude message {message_id}")+ # The parent transcript is authoritative for ownership: a call recorded+ # there belongs to the turn it was found in, and the subagent-file copies+ # are echoes. Only a call that appears NOWHERE but in sidechain files is+ # re-dated onto the turn that spawned it. `all` (not `any`) preserves+ # exactly what the old `fragments[0]` test did — parent turns are grouped+ # before sidechains above, so fragment 0 was the parent copy whenever one+ # existed — without depending on that ordering.+ if fragments and all(line.get("isSidechain") is True for line in fragments):+ instants = [safe_parse_dt(line.get("timestamp")) for line in fragments]+ at = min((instant for instant in instants if instant is not None), default=None)+ turn_num = _turn_index_for(at, starts)+ billed.setdefault(turn_num, []).extend(fragments)+ return billed+++# Fields the parser indexes or hashes on, per record / per message / per content+# block / per usage dict. A newer or damaged transcript can retype any of them.+_LINE_STR_FIELDS = ("uuid", "requestId", "sessionId", "cwd", "version", "entrypoint")+_MESSAGE_STR_FIELDS = ("id", "model", "stop_reason")+_BLOCK_STR_FIELDS = ("type", "text", "id", "name", "tool_use_id")+_USAGE_COUNTS = (+ "input_tokens",+ "output_tokens",+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+)+++def _sanitize_usage(usage: dict) -> None:+ for key in _USAGE_COUNTS:+ if key in usage and type(usage[key]) is not int:+ del usage[key]+ for key in ("cache_creation", "server_tool_use"):+ nested = usage.get(key)+ if isinstance(nested, dict):+ for count in [k for k, v in nested.items() if type(v) is not int]:+ del nested[count]+ elif key in usage:+ del usage[key]+++def _sanitize_line(line: dict) -> bool:+ """Drop wrong-typed fields from one record; False when the record is unreadable.++ A retyped value would raise deep inside the span build and lose the whole+ session, so it is removed (read as absent) instead.+ """+ drop_untyped(line, _LINE_STR_FIELDS, str)+ if "message" not in line:+ return True+ message = line["message"]+ if not isinstance(message, dict):+ return False+ drop_untyped(message, _MESSAGE_STR_FIELDS, str)+ drop_untyped(message, ("content",), (str, list))+ drop_untyped(message, ("usage",), dict)+ if "usage" in message:+ _sanitize_usage(message["usage"])+ if isinstance(message.get("content"), list):+ message["content"] = [b for b in message["content"] if isinstance(b, (dict, str))]+ for block in message["content"]:+ if isinstance(block, dict):+ drop_untyped(block, _BLOCK_STR_FIELDS, str)+ return True+++def parse_claude_code(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a Claude Code JSONL file into a span tree.++ Args:+ data: raw JSONL bytes.+ trace_id: the source-prefixed session id (e.g. `local:claude-code:<uuid>`).+ user_id: identifier to stash on the root span's `user.id`.+ project_name: project slug resolved by `LocalSource`.++ Returns:+ `(trace, all_spans)` with the trace's `spans` matching the list.+ """+ transcript_bytes = len(data)+ lines = [line for line in parse_lines(data) if _sanitize_line(line)]+ native_edit_results = result_patches(lines)+ if not lines:+ now = datetime.now(UTC)+ trace = TraceData(trace_id=trace_id, start_time=now, end_time=now)+ return trace, []++ # Subagent (Agent tool) traffic. Claude Code writes each subagent's+ # conversation to `<session-id>/subagents/agent-<id>.jsonl` (older builds+ # inlined it), every line stamped `isSidechain: true`; `LocalSource`+ # appends those files to the parent transcript. Their user prompts are+ # the PARENT's tool calls, not developer turns, so they never open a+ # turn -- but their assistant lines are real, billed API calls and are+ # folded into the turn that spawned them (by time) below, so the session's+ # totals include subagent spend.+ sidechain_lines = [line for line in lines if line.get("isSidechain") is True]+ main_lines = [line for line in lines if line.get("isSidechain") is not True]+ turns = _merge_replayed_turns(group_into_turns(main_lines))+ billed_by_turn = _billed_lines_by_turn(turns, sidechain_lines)+ all_spans: list[SpanData] = []+ root_id = f"{trace_id}:root"++ # Best-effort harness metadata.+ model_name = ""+ agent_version = ""+ effort_level = ""+ adaptive_thinking_disabled = False+ # Parent lines only: a subagent's model must not seed the session model.+ for line in main_lines:+ if not agent_version and line.get("version"):+ agent_version = line["version"]+ thinking_meta = line.get("thinkingMetadata")+ if thinking_meta and not effort_level:+ effort_level = thinking_meta.get("level", "")+ adaptive_thinking_disabled = bool(thinking_meta.get("disabled", False))+ if line.get("type") == "assistant":+ model_id = model_id_or_none(line.get("message", {}).get("model"))+ if model_id:+ model_name = model_id+ if model_name and agent_version and effort_level:+ break++ # Native session metadata Claude Code stamps on (nearly) every line:+ # `sessionId` (the agent's own session UUID), `permissionMode`+ # (default | acceptEdits | bypassPermissions | plan), `entrypoint`+ # (cli | sdk-py | sdk-ts | ...), and the per-line `isSidechain` flag+ # marking subagent (Task tool) traffic. First non-empty value wins for+ # the scalars; `sidechain_count` needs the full pass, so this loop+ # never breaks early. All land on the root span as `harness.*` attrs.+ agent_session_id = ""+ permission_mode = ""+ entrypoint = ""+ sidechain_count = 0+ for line in lines:+ if not agent_session_id and line.get("sessionId"):+ agent_session_id = line["sessionId"]+ if not permission_mode and line.get("permissionMode"):+ permission_mode = line["permissionMode"]+ if not entrypoint and line.get("entrypoint"):+ entrypoint = line["entrypoint"]+ if line.get("isSidechain") is True:+ sidechain_count += 1++ all_timestamps = [parse_dt(line["timestamp"]) for line in lines if line.get("timestamp")]+ if all_timestamps:+ session_start = min(all_timestamps)+ session_end = max(all_timestamps)+ else:+ session_start = datetime.now(UTC)+ session_end = session_start++ for turn_num, turn in enumerate(turns, 1):+ turn_id = f"{trace_id}:turn:{turn_num}"+ user_line = turn.get("user")+ assistant_lines = turn.get("assistants", [])+ tool_results = turn.get("tool_results", {})++ turn_start = (+ parse_dt(user_line["timestamp"])+ if user_line and "timestamp" in user_line+ else session_start+ )+ turn_end = turn_start+ for aline in assistant_lines:+ if aline.get("timestamp"):+ turn_end = max(turn_end, parse_dt(aline["timestamp"]))++ # Streaming fragments share message IDs — take the max per ID.+ # Track each component (fresh input, cache write incl. its 5m/1h+ # TTL split, cache read, output) separately so the $-calc has the+ # breakdown it needs — 1h writes bill at 2x input vs 1.25x for 5m,+ # and real Claude Code transcripts are 1h-dominated.+ msg_tokens: dict[str, tuple[int, int, int, int, int, int]] = {}+ # server-side web search/fetch REQUEST counts (never a+ # fee -- unpriced, display/count only). Tracked separately from+ # msg_tokens rather than widening that tuple: this isn't a billed+ # token component and has no place in the $-calc it feeds. Real shape+ # verified against local Claude Code transcripts:+ # `usage.server_tool_use = {"web_search_requests": N, "web_fetch_requests": N}`.+ # Same max-per-fragment dedup as msg_tokens: a later streaming+ # fragment of the same message reports the same-or-larger cumulative+ # count, never a fresh one to add.+ msg_web: dict[str, tuple[int, int]] = {}+ # the per-call cost data, keyed the same way+ # as msg_tokens (dedupe on message.id) so the two stay in lockstep.+ # `timestamp`/`request_id`/`model`/`service_tier` come from the+ # EARLIEST line for a message (a streaming fragment's first line is+ # when the call actually started); `latest_timestamp` retains a+ # distinct later fragment as directly-observed completion evidence.+ # Token totals above still take the MAX per component across+ # fragments, an unrelated dedupe axis.+ msg_meta: dict[str, dict[str, Any]] = {}+ # Parent calls first, then this turn's subagent calls. These are NOT+ # always distinct message ids: one subagent call is written to both the+ # parent transcript and the subagent's own file, so the same id arrives+ # twice once `LocalSource` folds them together. Merging the pair is the+ # point — the per-id `max()` below bills it once.+ billed_lines = billed_by_turn.get(turn_num, [])+ for aline in billed_lines:+ is_subagent = aline.get("isSidechain") is True+ msg = aline.get("message", {})+ usage = msg.get("usage", {})+ input_fresh = usage.get("input_tokens", 0)+ cache_w = usage.get("cache_creation_input_tokens", 0)+ # Nested TTL split (`usage.cache_creation.ephemeral_{5m,1h}_...`).+ # Older transcripts carry only the top-level total: the split+ # stays 0/0 and the $-calc bills every write at the 5m rate —+ # a deliberate lower bound, since the TTL is unknowable there.+ nested = usage.get("cache_creation") or {}+ cache_w_5m = nested.get("ephemeral_5m_input_tokens", 0)+ cache_w_1h = nested.get("ephemeral_1h_input_tokens", 0)+ if not cache_w and (cache_w_5m or cache_w_1h):+ cache_w = cache_w_5m + cache_w_1h+ cache_r = usage.get("cache_read_input_tokens", 0)+ completion_t = usage.get("output_tokens", 0)+ key = _message_key(aline)+ existing = msg_tokens.get(key, (0, 0, 0, 0, 0, 0))+ msg_tokens[key] = (+ max(existing[0], input_fresh),+ max(existing[1], cache_w),+ max(existing[2], cache_w_5m),+ max(existing[3], cache_w_1h),+ max(existing[4], cache_r),+ max(existing[5], completion_t),+ )+ server_tool_use = usage.get("server_tool_use") or {}+ existing_web = msg_web.get(key, (0, 0))+ msg_web[key] = (+ max(existing_web[0], server_tool_use.get("web_search_requests", 0) or 0),+ max(existing_web[1], server_tool_use.get("web_fetch_requests", 0) or 0),+ )++ model_id = model_id_or_none(msg.get("model"))+ if model_id and not is_subagent:+ model_name = model_id++ aline_ts = aline.get("timestamp")+ prior_meta = msg_meta.get(key)+ # Compared as parsed instants, never raw strings: a bare string+ # compare both crashes when the FIRST fragment for a message has+ # no timestamp at all (comparing a+ # str to prior_meta's stored None raises TypeError) and, even+ # when both are present, can pick the wrong "earliest" fragment+ # across differing UTC offsets.+ prior_instant = safe_parse_dt(prior_meta.get("timestamp")) if prior_meta else None+ prior_latest = (+ safe_parse_dt(prior_meta.get("latest_timestamp")) if prior_meta else None+ )+ seen_instant = safe_parse_dt(aline_ts)+ if prior_meta is None or (+ seen_instant is not None and (prior_instant is None or seen_instant < prior_instant)+ ):+ latest_timestamp = (+ prior_meta.get("latest_timestamp")+ if prior_meta is not None and prior_latest is not None+ else aline_ts+ )+ msg_meta[key] = {+ "timestamp": aline_ts,+ "latest_timestamp": latest_timestamp,+ # Keep a request identity observed on any fragment while+ # still allowing an earlier fragment to win the clock.+ "request_id": aline.get("requestId") or (prior_meta or {}).get("request_id"),+ # The earliest fragment wins the clock and request id; the+ # model is whichever fragment named one -- a first fragment+ # with no model must not price the call as unknown when a+ # later fragment carries it.+ "model": model_id or (prior_meta or {}).get("model"),+ "service_tier": usage.get("service_tier"),+ "speed": (prior_meta or {}).get("speed"),+ "subagent_id": (aline.get("agentId") if is_subagent else None)+ or (prior_meta or {}).get("subagent_id"),+ }+ else:+ if seen_instant is not None and (+ prior_latest is None or seen_instant > prior_latest+ ):+ prior_meta["latest_timestamp"] = aline_ts+ if model_id and not prior_meta.get("model"):+ prior_meta["model"] = model_id+ if aline.get("requestId") and not prior_meta.get("request_id"):+ prior_meta["request_id"] = aline["requestId"]+ if is_subagent and aline.get("agentId") and not prior_meta.get("subagent_id"):+ # LocalSource appends child files after the parent. A+ # duplicate parent message can therefore be materialized+ # before its sidechain copy; preserve that later evidence.+ prior_meta["subagent_id"] = aline["agentId"]+ speed = usage.get("speed")+ if speed is not None:+ prior_speed = msg_meta[key].get("speed")+ if prior_speed is not None and prior_speed != speed:+ raise ValueError("Conflicting response speed for Claude request")+ msg_meta[key]["speed"] = speed++ # Context window size = max across message IDs (what the model+ # "sees" at any one time). Total billed = sum (what you pay for).+ # `prompt` is everything sent: fresh input + cache write + cache read.+ per_msg_prompt = [t[0] + t[1] + t[4] for t in msg_tokens.values()]+ context_window_prompt = max(per_msg_prompt, default=0)+ total_billed_prompt = sum(per_msg_prompt)+ total_input_fresh = sum(t[0] for t in msg_tokens.values())+ total_cache_write = sum(t[1] for t in msg_tokens.values())+ total_cache_write_5m = sum(t[2] for t in msg_tokens.values())+ total_cache_write_1h = sum(t[3] for t in msg_tokens.values())+ total_cache_read = sum(t[4] for t in msg_tokens.values())+ total_completion = sum(t[5] for t in msg_tokens.values())+ total_web_searches = sum(t[0] for t in msg_web.values())+ total_web_fetches = sum(t[1] for t in msg_web.values())++ # one row per API call (message.id), the request grain - kept+ # alongside the turn sums above, which stay unchanged by construction (same+ # msg_tokens, just not discarded after summing). A call with no+ # timestamp at all can't be placed and is skipped (never guessed).+ cost_events = []+ for key, tokens in msg_tokens.items():+ meta = msg_meta.get(key, {})+ if not meta.get("timestamp"):+ continue+ event: dict[str, Any] = {+ "timestamp": meta["timestamp"],+ "started_at": meta["timestamp"],+ "completed_at": None,+ "duration_ms": None,+ "message_id": key or None,+ "request_id": meta.get("request_id"),+ "model": meta.get("model"),+ "service_tier": meta.get("service_tier"),+ **({"speed": meta["speed"]} if meta.get("speed") is not None else {}),+ "cache_ttl_known": tokens[1] == tokens[2] + tokens[3],+ "input_tokens": tokens[0],+ # Preserve unsplit writes at the same 5m lower-bound rate+ # used by the turn-level cost calculator. Apply after the+ # streaming max merge, so a later TTL split isn't added twice.+ "cache_write_5m_tokens": tokens[2] + max(0, tokens[1] - tokens[2] - tokens[3]),+ "cache_write_1h_tokens": tokens[3],+ "cache_read_tokens": tokens[4],+ "output_tokens": tokens[5],+ }+ started = safe_parse_dt(meta.get("timestamp"))+ completed = safe_parse_dt(meta.get("latest_timestamp"))+ if started is not None and completed is not None and completed > started:+ event["completed_at"] = meta["latest_timestamp"]+ event["duration_ms"] = int((completed - started).total_seconds() * 1000)+ # Only stamped on subagent calls, so the shape of a parent call's+ # event (and every existing consumer of it) is unchanged.+ if meta.get("subagent_id"):+ event["subagent_id"] = meta["subagent_id"]+ cost_events.append(event)++ # Per-turn cwd — Claude Code stamps `cwd` on (nearly) every+ # user/assistant entry. One session can span multiple repos+ # (the dev `cd`s mid-session), so we record THIS turn's cwd on+ # the turn span so each turn can resolve to its own repo. Prefer the+ # user line's cwd, fall back to the first assistant line that carries one.+ turn_cwd = user_line.get("cwd") if user_line else None+ if not turn_cwd:+ for aline in assistant_lines:+ if aline.get("cwd"):+ turn_cwd = aline["cwd"]+ break++ user_query = ""+ if user_line:+ user_query = extract_user_content(user_line.get("message", {}))++ assistant_text_parts = []+ for aline in assistant_lines:+ msg = aline.get("message", {})+ for block in msg.get("content", []):+ if isinstance(block, dict) and block.get("type") == "text":+ assistant_text_parts.append(block.get("text", ""))+ assistant_text = "\n".join(assistant_text_parts)++ turn_span = SpanData(+ span_id=turn_id,+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=turn_start,+ end_time=turn_end,+ attributes={+ "input.value": user_query[:2000] if user_query else "",+ "output.value": assistant_text[:2000] if assistant_text else "",+ "cwd": turn_cwd or "",+ "llm.token_count.prompt": context_window_prompt,+ "llm.token_count.completion": total_completion,+ "llm.token_count.total_billed_prompt": total_billed_prompt,+ "llm.token_count.input_fresh": total_input_fresh,+ "llm.token_count.cache_write": total_cache_write,+ "llm.token_count.cache_write_5m": total_cache_write_5m,+ "llm.token_count.cache_write_1h": total_cache_write_1h,+ "llm.token_count.cache_read": total_cache_read,+ "llm.model_name": model_name,+ # request counts, never a fee -- see msg_web above.+ "llm.web_searches": total_web_searches,+ "llm.web_fetches": total_web_fetches,++ "llm.cost_events": cost_events,+ },+ )+ # transcript-anchored turn identity — the byte offset of+ # the line that OPENED the original turn. Replay merging preserves+ # this anchor instead of identifying a turn by its mutable token totals.+ _anchor_line = (+ user_line+ if user_line is not None+ else (assistant_lines[0] if assistant_lines else None)+ )+ _anchor_offset = _anchor_line.get(SOURCE_OFFSET_KEY) if _anchor_line is not None else None+ if _anchor_offset is not None:+ turn_span.attributes["source.byte_offset"] = _anchor_offset+ # the source anchor block - kind + content hash on every span.+ turn_span.attributes.update(+ {k: v for k, v in source_attrs(_anchor_line).items() if k != "source.byte_offset"}+ )+ all_spans.append(turn_span)++ for aline in assistant_lines:+ msg = aline.get("message", {})+ content_blocks = msg.get("content", [])+ if not isinstance(content_blocks, list):+ continue+ aline_ts = aline.get("timestamp")+ tool_start = parse_dt(aline_ts) if aline_ts else turn_start++ for block in content_blocks:+ if not isinstance(block, dict) or block.get("type") != "tool_use":+ continue++ tool_use_id = block.get("id", "")+ tool_name = block.get("name", "unknown")+ if not isinstance(tool_name, str) or not tool_name:+ tool_name = "unknown"+ tool_input = block.get("input", {})++ result_block = tool_results.get(tool_use_id, {})+ tool_output = result_block.get("content", "")+ is_error = result_block.get("is_error", False)++ tool_end = tool_start+ result_ts = turn.get("tool_result_timestamps", {}).get(tool_use_id)+ if result_ts:+ tool_end = parse_dt(result_ts)++ input_str = (+ json.dumps(tool_input) if isinstance(tool_input, dict) else str(tool_input)+ )+ command_attrs = creation_command_attributes(input_str, tool_name)+ output_str = str(tool_output) if tool_output else ""++ tool_span = SpanData(+ span_id=f"{trace_id}:tool:{tool_use_id}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=tool_name,+ span_kind="CHAIN",+ status_code="ERROR" if is_error else "OK" if tool_use_id in tool_results else "UNSET",+ start_time=tool_start,+ end_time=tool_end,+ attributes={+ "tool.name": tool_name,+ "cwd": aline.get("cwd") or turn_cwd or "",+ "tool.description": (+ tool_input.get("description", "")+ if isinstance(tool_input, dict)+ else ""+ ),+ "input.value": input_str[:2000],+ # the Skill name survives a long `args` that+ # truncates `input.value` into unparseable JSON.+ **skill_call_attributes(tool_name, tool_input),+ **command_attrs,+ **creation_output_attributes(+ tool_output, command_attrs.get("pr.create.provider"),+ command_attrs.get("pr.create.repository")+ ),+ "code.edit_evidence": call_edit_evidence(+ tool_name,+ tool_input,+ native_edit_results.get(tool_use_id),+ has_native=tool_use_id in native_edit_results,+ successful=tool_use_id in tool_results and not is_error,+ ),+ "output.value": output_str[:2000],+ # content-anchored identity. tool_use_id is+ # Anthropic's own `toolu_…` id — stable across+ # re-parses by construction (it also seeds span_id+ # above; carried explicitly so consumers never parse+ # it back out of the span_id string).+ "source.tool_use_id": tool_use_id,+ # The assistant message that produced this tool call is+ # Claude's direct request-to-tool association. Match+ # the cost-event identity exactly.+ "llm.request_fact_id": _fallback_tool_request_id(+ aline,+ _tool_request_id(+ aline,+ msg_meta,+ msg_meta.get(_message_key(aline), {}).get("request_id")+ or msg.get("id"),+ ),+ ),+ },+ )+ _aline_offset = aline.get(SOURCE_OFFSET_KEY)+ if _aline_offset is not None:+ tool_span.attributes["source.byte_offset"] = _aline_offset+ tool_span.attributes.update(+ {k: v for k, v in source_attrs(aline).items() if k != "source.byte_offset"}+ )+ all_spans.append(tool_span)++ # Parent lines drive slash_commands/interrupts: those describe what the+ # DEVELOPER typed, and a subagent's synthetic "user" turn is the+ # parent's own tool call, not a developer action. Skills are different —+ # a subagent invoking one is still work the developer's own dispatch+ # caused, so those fold in from the sidechain lines too+ # (`fold_subagent_skills`): otherwise a skill an orchestrator-style+ # plugin dispatched to a subagent (rather than calling directly) would+ # never appear in "skills used" at all.+ #+ # One shared `seen_skill_tool_ids` set across both calls: a subagent's own Skill call is echoed verbatim into BOTH the+ # parent transcript (isSidechain: false) and its own file (isSidechain:+ # true), sharing one tool_use id — two independent fresh sets would each+ # count it once, and the fold below would then double it.+ seen_skill_tool_ids: set[str] = set()+ session_signals = extract_session_signals(main_lines, seen_skill_tool_ids)+ if sidechain_lines:+ session_signals = fold_subagent_skills(+ session_signals,+ extract_session_signals(sidechain_lines, seen_skill_tool_ids),+ )+ # Inline sidechain requests preceding a checkpoint are billing evidence.+ # Appended child files remain after the parent's checkpoints: their order+ # cannot establish which cumulative snapshot included those requests.+ cost_summary = extract_cost_summary(+ [+ line+ for line in lines+ if line.get("isSidechain") is not True or line.get("type") == "assistant"+ ],+ request_expander=_expand_fallback_requests,+ )++ subagent_edits = _subagent_edit_calls(+ trace_id, turns, main_lines, sidechain_lines, native_edit_results+ )+ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "user.id": user_id or "",+ "llm.model_name": model_name,+ "session.id": trace_id,+ "project.name": project_name or "",+ "harness.agent_session_id": agent_session_id,+ "harness.agent_version": agent_version,+ "harness.effort_level": effort_level,+ "harness.adaptive_thinking_disabled": adaptive_thinking_disabled,+ "harness.permission_mode": permission_mode,+ "harness.entrypoint": entrypoint,+ "harness.sidechain_count": sidechain_count,+ "harness.subagent_count": len(+ {line.get("agentId") for line in sidechain_lines if line.get("agentId")}+ ),+ "harness.session_signals": json.dumps(session_signals),+ **({"llm.cost_summary": cost_summary} if cost_summary is not None else {}),+ **({"code.subagent_edit_calls": subagent_edits} if subagent_edits else {}),+ # raw transcript length as read (pre-normalization).+ "source.transcript_bytes": transcript_bytes,+ },+ )+ all_spans.insert(0, root_span)++ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ return trace, all_spans+++__all__ = ["parse_claude_code"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/claude_cost_summary.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/claude_cost_summary.pynew file mode 100644index 0000000..f273258--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/claude_cost_summary.py@@ -0,0 +1,148 @@+"""Retain Claude's cumulative cost checkpoints without inventing requests.++The process start clock is an identity, not a billing-window boundary: resumed+processes can carry costs from before it. Compare each checkpoint only with the+request observations preceding that checkpoint in this transcript.+"""++from collections.abc import Callable+import hashlib+import json+import math++from agentplay._core.ingestion.coding_agent.spans import model_id_or_none+from agentplay._core.pricing import normalize_model_key++TOKEN_FIELDS = ("inputTokens", "outputTokens", "cacheReadInputTokens", "cacheCreationInputTokens")+USAGE_FIELDS = (+ "input_tokens",+ "output_tokens",+ "cache_read_input_tokens",+ "cache_creation_input_tokens",+)+++def extract_cost_summary(+ lines: list[dict], *, request_expander: Callable[[dict], dict] | None = None+) -> dict | None:+ """Return bounded numeric evidence; flag malformed/oversized checkpoints.++ Snapshots are observations, never additive invoices. Keep the first copy of+ each checkpoint so replayed records cannot compare it with later activity.+ """+ if not any(line.get("type") == "cost-state" for line in lines):+ return None+ observations: dict[str, tuple[int, list[dict]]] = {}+ checkpoints: dict[str, dict] = {}+ invalid = 0+ for line in lines:+ message = line.get("message") or {}+ usage = message.get("usage") or {}+ if line.get("type") == "assistant" and message.get("id") and usage:+ observations.setdefault(message["id"], (0, []))[1].append(line)+ if line.get("type") != "cost-state":+ continue+ # Only evidence already visible at this checkpoint may participate.+ # A final fallback snapshot replaces earlier serving-only fragments;+ # expanding the whole transcript here would leak future evidence back.+ try:+ expanded = request_expander(observations) if request_expander else observations+ requests: dict[str, tuple[str, tuple[int, ...]]] = {}+ for _, fragments in expanded.values():+ for fragment in fragments:+ message = fragment["message"]+ usage = message["usage"]+ model = normalize_model_key(model_id_or_none(message.get("model")) or "")+ values = tuple(usage.get(field, 0) for field in USAGE_FIELDS)+ if any(type(v) is not int or v < 0 for v in values):+ continue # The request parser owns malformed request handling.+ old = requests.get(message["id"])+ if old and old[0] and model and old[0] != model:+ # A model-id rename, or a new id `normalize_model_key` folds+ # differently, must discard this checkpoint, not the session.+ raise ValueError("Conflicting model in Claude cost checkpoint")+ model = model or (old[0] if old else "")+ requests[message["id"]] = (+ model,+ tuple(max(a, b) for a, b in zip(old[1], values, strict=True))+ if old+ else values,+ )+ models = line.get("modelUsage")+ start = line.get("startTime")+ total = line.get("totalCostUSD")+ unknown = line.get("hasUnknownModelCost")+ if (+ type(start) is not int+ or start < 0+ or type(unknown) is not bool+ or type(total) not in (float, int)+ or not math.isfinite(total)+ or total < 0+ or not isinstance(models, dict)+ or len(models) > 128+ ):+ raise ValueError("Invalid Claude cost-state checkpoint")+ identity = hashlib.sha256(+ json.dumps(+ [start, total, unknown, models], sort_keys=True, separators=(",", ":")+ ).encode()+ ).hexdigest()+ if identity in checkpoints:+ continue+ if len(checkpoints) >= 128:+ raise ValueError("Claude cost-state checkpoint limit exceeded")+ rows = []+ reported_models = set()+ for name, data in sorted(models.items()):+ if (+ not isinstance(name, str)+ or not name+ or len(name) > 128+ or not isinstance(data, dict)+ ):+ raise ValueError("Invalid Claude cost-state model")+ values = [data.get(field) for field in TOKEN_FIELDS]+ cost = data.get("costUSD")+ if (+ any(type(v) is not int or v < 0 for v in values)+ or type(cost) not in (int, float)+ or not math.isfinite(cost)+ or cost < 0+ ):+ raise ValueError("Invalid Claude cost-state usage")+ model = normalize_model_key(name)+ if model in reported_models:+ raise ValueError("Duplicate normalized Claude checkpoint model")+ reported_models.add(model)+ visible = [sum(v[i] for m, v in requests.values() if m == model) for i in range(4)]+ rows.append(+ {+ "model": name,+ "reported_cost_usd": cost,+ "reported_tokens": values,+ "visible_tokens": visible,+ }+ )+ if not unknown and not math.isclose(+ sum(r["reported_cost_usd"] for r in rows), total, rel_tol=1e-9, abs_tol=1e-6+ ):+ raise ValueError("Claude checkpoint total disagrees with its models")+ checkpoints[identity] = {+ "source_hash": identity,+ "process_start_ms": start,+ "reported_total_usd": total,+ "has_unknown_model_cost": unknown,+ "models": rows,+ "visible_unreported_tokens": [+ sum(v[i] for m, v in requests.values() if m not in reported_models)+ for i in range(4)+ ],+ }+ except (ValueError, TypeError, OverflowError):+ invalid += 1+ return (+ {"checkpoints": list(checkpoints.values()), "invalid_checkpoints": invalid}+ if checkpoints or invalid+ else None+ )diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/codex.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/codex.pynew file mode 100644index 0000000..c873c0d--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/codex.py@@ -0,0 +1,1082 @@+"""Parse OpenAI Codex JSONL sessions into the universal SpanData shape.++Codex's format differs from Claude Code's: lines are typed `session_meta`,+`response_item`, `event_msg`, and turns are bracketed by user+`response_item` messages with `input_text` content blocks. Token counts+arrive as native `token_usage_record` records or legacy `event_msg` lines+(`type=token_count`). Native response IDs survive display-counter resets.+"""++from __future__ import annotations++from datetime import UTC, datetime+import json+import logging+import re++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._paths import basename as path_basename+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ drop_untyped,+ parse_dt,+ parse_jsonl_records,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent.edit_lines import count_patch_lines+from agentplay._core.ingestion.coding_agent.native_operations import (+ ProcessEvidence,+ literal_operations,+ literal_results,+ shell_result,+)+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData, model_id_or_none+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++# Raw -> canonical tool names live in the shared table (tool_taxonomy.py).+_TOOL_ALIASES: dict[str, str] = aliases_for("codex")++# Codex tool calls arrive as two `response_item` payload types: regular+# `function_call` (JSON `arguments`) and `custom_tool_call` (freeform+# `input` — this is how `apply_patch` ships its patch text). Both pair with+# a `*_output` line via `call_id`, so both types must be matched or+# apply_patch spans are lost.+_TOOL_CALL_TYPES = ("function_call", "custom_tool_call")+_TOOL_OUTPUT_TYPES = ("function_call_output", "custom_tool_call_output")++# First `Process exited with code N` line in an exec-style output — the+# unified-exec header Codex prepends before the command's own `Output:`+# section. Full-line MULTILINE match so a stray substring inside the+# command's stdout can't trigger it, and `search` (first match) so the+# header verdict wins even when the output body echoes a similar line.+_RE_EXEC_EXIT_CODE = re.compile(r"^Process exited with code (\d+)$", re.MULTILINE)++# File headers inside an `apply_patch` body. The codex patch format brackets+# hunks with `*** Begin Patch` / `*** End Patch` and names each touched file+# on a `*** <Verb> File: <path>` header; renames add a `*** Move to: <dest>`+# line under the Update header. `Update File` and `Add File` are the forms+# seen in transcripts; `Delete File` / `Move to` are documented parts of the+# same grammar and matched for completeness. Full-line MULTILINE match so+# patch BODY lines that merely quote a header (e.g. an added doc line+# `+*** Update File: x`) can't inject phantom paths.+_RE_PATCH_FILE_HEADER = re.compile(+ r"^\*\*\* (?:(?:Update|Add|Delete) File|Move to): (.+?)\s*$", re.MULTILINE+)+++def _apply_patch_input(patch_text: str) -> str:+ """Rewrite an apply_patch body into a `file_path`-keyed input string.++ Files-touched consumers (`file_paths.extract_file_path`, ...) regex-scan a tool span's+ `input.value` for `"file_path": "..."` pairs — they never see the+ patch grammar, so a raw apply_patch body yields zero files touched+ for every Codex session. This prefixes one `"file_path"` pair per+ file named in the patch headers, then appends the original patch+ text under `"patch"`. Paths go FIRST so they survive the parser's+ 2000-char `input.value` truncation even for long patches (same+ lesson as opencode's `_normalize_file_path_arg`: the key must be in+ the retained prefix, not the truncated tail).++ Multi-file patches produce REPEATED `"file_path"` keys — legal JSON+ text, and the regex consumers match every occurrence; a `json.loads`+ consumer would keep only the last path, which no current consumer+ does (all are regex-based, per `file_paths.py`'s module contract).++ Args:+ patch_text: The raw `custom_tool_call.input` payload — an+ `*** Begin Patch` body, untruncated.++ Also stamps `lines_added` / `lines_removed`, computed from the untruncated+ body — see the comment at the append below for why it has to happen here.++ Returns:+ `{"lines_added": <n>, "lines_removed": <n>, "file_path": "<p1>"[,+ "file_path": "<p2>"...], "patch": "<body>"}` as a string, or `patch_text`+ unchanged when no file header is found (nothing to extract — keep the+ raw evidence).+ """+ paths = list(dict.fromkeys(_RE_PATCH_FILE_HEADER.findall(patch_text)))+ if not paths:+ return patch_text+ # AI lines of code, counted HERE because this is the last place the+ # untruncated body exists: `input.value` is capped at 2,000 characters just+ # below, which cuts most apply_patch spans+ # mid-string. `edit_lines.edit_line_counts` reads the stamp by regex, so a+ # truncated tail does not cost the session its counts.+ #+ # FIRST, ahead of the paths. The path list is unbounded — a multi-file patch+ # emits one pair per file — so a patch touching enough files, or files with+ # long enough paths, would push a trailing stamp past the cap and report+ # no counts for a session that was measured perfectly well. These two integers+ # cost ~45 characters of a 2,000-character budget; the paths can afford it,+ # and file-path extraction is regex-based (`file_paths.py`) so a partially+ # truncated path list still yields every path it retained.+ added, removed = count_patch_lines(patch_text)+ pairs = [f'"lines_added": {added}, "lines_removed": {removed}']+ pairs.extend(f'"file_path": {json.dumps(p)}' for p in paths)+ pairs.append(f'"patch": {json.dumps(patch_text)}')+ return "{" + ", ".join(pairs) + "}"+++def parse_codex(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a Codex JSONL file into a span tree."""+ lines = _parse_jsonl(data)+ if not lines:+ now = datetime.now(UTC)+ trace = TraceData(trace_id=trace_id, start_time=now, end_time=now)+ return trace, []++ # Session-level metadata. cwd, the native session id, and the CLI+ # version come from session_meta; the model name lives on+ # `turn_context` (session_meta only carries model_provider) —+ # reading only session_meta would leave `model_name` empty. Take the+ # first of each we see.+ model_name = ""+ cwd = ""+ agent_session_id = ""+ agent_version = ""+ for line in lines:+ payload = line.get("payload", {})+ ltype = line.get("type")+ if ltype == "session_meta":+ if not cwd:+ cwd = payload.get("cwd", "")+ if not agent_session_id:+ agent_session_id = payload.get("id", "") or ""+ if not agent_version:+ agent_version = payload.get("cli_version", "") or ""+ elif ltype == "turn_context" and not model_name:+ model_name = model_id_or_none(payload.get("model")) or ""+ if cwd and model_name and agent_session_id and agent_version:+ break++ if not project_name and cwd:+ project_name = path_basename(cwd)++ turns, native_ledger_rejected = _group_into_turns(lines)++ all_spans: list[SpanData] = []+ root_id = f"{trace_id}:root"++ all_timestamps = [parse_dt(line["timestamp"]) for line in lines if line.get("timestamp")]+ if all_timestamps:+ session_start = min(all_timestamps)+ session_end = max(all_timestamps)+ else:+ session_start = datetime.now(UTC)+ session_end = session_start++ for turn_num, turn in enumerate(turns, 1):+ turn_id = f"{trace_id}:turn:{turn_num}"++ turn_start = parse_dt(turn["start_ts"]) if turn.get("start_ts") else session_start+ turn_end = parse_dt(turn["end_ts"]) if turn.get("end_ts") else turn_start++ total_prompt = turn.get("input_tokens", 0)+ total_completion = turn.get("output_tokens", 0)+ total_reasoning = turn.get("reasoning_tokens", 0)+ cache_read = turn.get("cache_read", 0)++ # Match the attribute shape Claude parsers use so consumers+ # read every agent consistently. Codex doesn't expose+ # cache_write - leave it zero.+ turn_span = SpanData(+ span_id=turn_id,+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=turn_start,+ end_time=turn_end,+ attributes={+ "input.value": turn.get("user_query", "")[:2000],+ # Session metadata is a fallback; individual calls retain+ # the working directory observed in their turn_context.+ "cwd": cwd or "",+ "llm.token_count.prompt": total_prompt,+ "llm.token_count.completion": total_completion,+ # Subset of total_completion, not additive -- see+ # `_reasoning_tokens`. Display-only; no consumer bills off it.+ "llm.token_count.reasoning": total_reasoning,+ "llm.token_count.cache_read": cache_read,+ "llm.token_count.cache_write": 0,+ "llm.token_count.input_fresh": max(0, total_prompt - cache_read),+ "llm.cost_events": turn["cost_events"],+ # Per-turn model — Codex can switch models mid-session; fall+ # back to the session model when a turn carries none.+ "llm.model_name": turn.get("model") or model_name,+ },+ )+ turn_span.attributes.update(source_attrs(turn.get("_src")))+ all_spans.append(turn_span)++ for tool in turn.get("tools", []):+ tool_start = parse_dt(tool["start_ts"]) if tool.get("start_ts") else turn_start+ tool_end = parse_dt(tool["end_ts"]) if tool.get("end_ts") else tool_start++ # Canonical name on both span name and `tool.name` — matching+ # cursor_store.py, which also doesn't keep the raw name; the+ # the tool distribution reads `tool.name`, so it shows the same+ # canonical vocabulary for every agent.+ tool_name = _TOOL_ALIASES.get(tool["name"], tool["name"])+ tool_span = SpanData(+ span_id=f"{trace_id}:tool:{tool['call_id']}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=tool_name,+ span_kind="CHAIN",+ # `is_error` is decided from the untruncated output payload+ # when the matching `*_output` line lands (see+ # `_tool_output_is_error`); dangling calls carry no verdict+ # and remain UNSET.+ status_code=(+ "UNSET"+ if "is_error" not in tool or tool.get("provenance.capture") == "pending_process"+ else "ERROR"+ if tool.get("is_error")+ else "OK"+ ),+ start_time=tool_start,+ end_time=tool_end,+ attributes={+ "tool.name": tool_name,+ "cwd": tool.get("cwd", ""),+ "input.value": tool.get("input", "")[:2000],+ **{+ key: tool[key]+ for key in (+ "pr.create.provider",+ "pr.create.repository",+ "pr.create.requested_repository",+ "pr.create.command_sha256",+ "pr.create.output_url",+ "pr.create.capture",+ "provenance.capture",+ )+ if key in tool+ },+ "code.edit_evidence": (+ tool.get("edit_evidence", {"status": "unsupported_tool", "edits": []})+ if "is_error" in tool and not tool["is_error"]+ else {"status": "not_successful", "edits": []}+ ),+ "output.value": tool.get("output", "")[:2000],+ },+ )+ tool_span.attributes.update(source_attrs(tool.get("_src")))+ all_spans.append(tool_span)++ # Session-level model: the last model actually used in a turn (handles+ # mid-session switches), falling back to the first turn_context model.+ session_model = next((t["model"] for t in reversed(turns) if t.get("model")), model_name)++ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "user.id": user_id or "",+ "llm.model_name": session_model,+ "session.id": trace_id,+ "project.name": project_name or "",+ "harness.agent_session_id": agent_session_id,+ "harness.agent_version": agent_version,+ },+ )+ all_spans.insert(0, root_span)+ incomplete_turns = [turn for turn in turns if turn.get("usage_incomplete")]+ # native_ledger_rejected covers the case a rejected native ledger leaves no+ # turn to mark: e.g. token_usage_record lines with no matching legacy+ # event_msg usage, so the session-wide loss would otherwise go unrecorded.+ if incomplete_turns or native_ledger_rejected:+ root_span.attributes["llm.usage_complete"] = False+ root_span.attributes["llm.usage_state"] = "unknown_components"+ totals = [+ turn["reported_total_tokens"]+ for turn in incomplete_turns+ if "reported_total_tokens" in turn+ ]+ if totals:+ root_span.attributes["llm.reported_total_tokens"] = max(totals)++ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ return trace, all_spans+++# Payload fields read as strings; any other type reads as absent.+_PAYLOAD_STR_FIELDS = (+ "type",+ "role",+ "model",+ "turn_id",+ "cwd",+ "call_id",+ "name",+ "id",+ "message",+)+++def _parse_jsonl(data: bytes) -> list[dict]:+ """Lighter JSONL parser — Codex doesn't have noise types to skip.++ every line carries the shared source anchors (offset + hash). A retyped+ payload field reads as absent (see :func:`drop_untyped`) instead of raising+ later and losing the whole session.+ """+ records = parse_jsonl_records(data)+ for record in records:+ drop_untyped(record, ("payload",), dict)+ payload = record.get("payload")+ if payload is None:+ continue+ drop_untyped(payload, _PAYLOAD_STR_FIELDS, str)+ drop_untyped(payload, ("info",), dict)+ drop_untyped(payload, ("content",), list)+ info = payload.get("info")+ if isinstance(info, dict):+ drop_untyped(info, ("last_token_usage", "total_token_usage"), dict)+ if "content" in payload:+ payload["content"] = [b for b in payload["content"] if isinstance(b, dict)]+ for block in payload["content"]:+ drop_untyped(block, ("type", "text"), str)+ return records+++def _total_only_usage(usage: dict) -> bool:+ """Recognize legacy exports whose component counters are absent/zero.++ The reported total is evidence of usage, never evidence of an input/output+ split. Nonzero conflicting components and native request ledgers still fail+ validation; this exception only preserves activity from total-only exports.+ """+ total = usage.get("total_tokens")+ return (+ type(total) is int+ and total > 0+ and all(+ key not in usage or (type(usage[key]) is int and usage[key] == 0)+ for key in (+ "input_tokens",+ "output_tokens",+ "cached_input_tokens",+ "cache_write_input_tokens",+ "reasoning_output_tokens",+ )+ )+ )+++def _token_components(usage: dict) -> tuple[int, int, int]:+ """The three billed components, validated for internal consistency.++ Codex output already includes reasoning; cached input is an input subset.++ Split out of :func:`_token_usage` because the two kinds of failure below it+ mean opposite things for the running cumulative baseline. A figure that+ fails HERE is malformed: the snapshot contradicts itself and nothing in it+ can be trusted, the baseline included. A figure that passes here but is+ refused for an unpriceable extra component is well formed and its total is+ still good, so the baseline must move with it. Keeping both in one function+ is what made every cache-write record hold the baseline back.+ """+ values = []+ for key in ("input_tokens", "cached_input_tokens", "output_tokens"):+ value = usage.get(key, 0 if key == "cached_input_tokens" else None)+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ raise ValueError(f"Invalid Codex usage component: {key}")+ values.append(value)+ if values[1] > values[0]:+ raise ValueError("Codex cached input exceeds total input")+ if "total_tokens" in usage:+ total = usage["total_tokens"]+ if type(total) is not int or total != values[0] + values[2]:+ raise ValueError("Codex token total must equal input plus output")+ return tuple(values)+++def _reasoning_tokens(usage: dict, output_tokens: int) -> int:+ """Display-only reasoning-token count from a single usage snapshot.++ Never affects billing: `_token_components` already docstrings that Codex+ `output_tokens` includes reasoning, so this is purely a breakdown for+ display, not a fourth billed component. Absent or malformed values fall+ back to 0 rather than raising — this field is optional metadata, unlike+ the billed components `_token_components` enforces. Clamped to+ `output_tokens` (the caller's already-validated billed component) so a+ malformed vendor payload can't report reasoning larger than the+ completion it is supposed to be a subset of.+ """+ value = usage.get("reasoning_output_tokens", 0)+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return 0+ return min(value, output_tokens)+++def _reject_unpriceable_components(usage: dict) -> None:+ """Refuse a well-formed snapshot this parser cannot price.++ The current OpenAI source reports zero writes. A nonzero value from a+ different provider lacks the TTL needed to price the write.+ Codex can run models from several providers, so a nonzero write stays a+ refusal, not an assumption.+ """+ if usage.get("cache_write_input_tokens"):+ raise ValueError("Codex cache-write pricing requires provider/TTL evidence")+++def _token_usage(usage: dict) -> tuple[int, int, int]:+ """Billed components, refusing anything this parser cannot price."""+ values = _token_components(usage)+ _reject_unpriceable_components(usage)+ return values+++def _native_usage_events(lines: list[dict]) -> dict[str, dict] | None:+ """Return provider-owned usage records after validating their ledger."""+ if not any(line.get("type") == "token_usage_record" for line in lines):+ return None+ owner = next(+ (line.get("payload", {}).get("id") for line in lines if line.get("type") == "session_meta"),+ None,+ )+ if not isinstance(owner, str) or not owner:+ raise ValueError("Codex native usage lacks its session owner")+ models_by_turn: dict[str, set[str]] = {}+ for line in lines:+ if line.get("type") == "turn_context":+ context = line.get("payload", {})+ model = model_id_or_none(context.get("model"))+ if context.get("turn_id") and model:+ models_by_turn.setdefault(context["turn_id"], set()).add(model)++ events: dict[str, dict] = {}+ seen_native: dict[str, tuple[dict, str]] = {}+ native_total = (0, 0, 0)+ for line in lines:+ kind = line.get("type")+ payload = line.get("payload", {})+ if kind == "token_usage_record":+ for key in ("thread_id", "turn_id", "response_id"):+ if not isinstance(payload.get(key), str) or not payload[key]:+ raise ValueError(f"Codex native usage lacks {key}")+ if payload["thread_id"] != owner:+ raise ValueError("Codex inherited native usage requires owner reconciliation")+ usage_record = payload.get("usage")+ cumulative_record = payload.get("thread_token_usage")+ if not isinstance(usage_record, dict) or not isinstance(cumulative_record, dict):+ raise ValueError("Codex native usage lacks billed components")+ usage = _token_usage(usage_record)+ cumulative = _token_usage(cumulative_record)+ timestamp = line.get("timestamp")+ if not isinstance(timestamp, str) or not timestamp:+ raise ValueError("Codex native usage lacks a timestamp")+ parse_dt(timestamp)+ response_id = payload["response_id"]+ identity = (payload, timestamp)+ if response_id in seen_native:+ if seen_native[response_id] != identity:+ raise ValueError("Codex native response has conflicting usage")+ continue+ if cumulative != tuple(a + b for a, b in zip(native_total, usage, strict=True)):+ raise ValueError("Codex native cumulative usage has a gap or legacy prefix")+ seen_native[response_id] = identity+ native_total = cumulative+ models = models_by_turn.get(payload["turn_id"], set())+ model = next(iter(models)) if len(models) == 1 else ""+ anchor = source_attrs(line)+ events[anchor["source.content_hash"]] = {+ "timestamp": timestamp,+ "request_id": None,+ "message_id": f"codex-response:{response_id}",+ "turn_id": payload["turn_id"],+ "model": model,+ "input_tokens": usage[0] - usage[1],+ "cache_read_tokens": usage[1],+ "cache_write_5m_tokens": 0,+ "cache_write_1h_tokens": 0,+ "output_tokens": usage[2],+ "reasoning_tokens": _reasoning_tokens(usage_record, usage[2]),+ "usage_basis": "token_usage_record",+ **anchor,+ }+ return events+++def _group_into_turns(lines: list[dict]) -> tuple[list[dict], bool]:+ """Group Codex lines into turns keyed on user `response_item` messages.++ Codex turn boundary = a `response_item` with `role=user` carrying+ text that isn't a system context injection (lines starting with+ `<` or `#`). Tokens land on `event_msg` `token_count` lines and+ accumulate into the current turn.+ """+ turns: list[dict] = []+ current_turn: dict | None = None+ session_id = (+ next(+ (+ line.get("payload", {}).get("id")+ for line in lines+ if line.get("type") == "session_meta"+ ),+ "",+ )+ or ""+ )+ native_ledger_rejected = False+ try:+ native_events = _native_usage_events(lines)+ except ValueError as exc:+ # A vendor change to the native usage ledger must degrade the whole+ # session to the legacy token_count accounting path below, never abort+ # the transcript. Every turn and tool span still parses; only the more+ # precise native basis is lost for this session.+ native_ledger_rejected = True+ logger.debug(+ "session %s: native Codex usage ledger rejected (%s); falling back to legacy token_count accounting",+ session_id,+ exc,+ )+ native_events = None+ pending_native_events: dict[str, list[dict]] = {}+ emitted_native: set[str] = set()+ native_source_records = {+ source_attrs(line)["source.content_hash"]: line+ for line in lines+ if line.get("type") == "token_usage_record"+ }++ pending_calls: dict[str, dict] = {} # call_id → pending function call+ processes = ProcessEvidence()++ # Session-wide counter minting synthetic call_ids for unpaired+ # `web_search_call` lines (they carry no call_id of their own).+ websearch_seq = 0++ prev_total_tokens: int | None = None+ prev_usage: tuple[int, int, int] | None = None+ seen_usage_records: set[str] = set()++ # Model active for the current turn. Codex emits a `turn_context` line+ # (with the model) before each turn and can switch models mid-session,+ # so we track the latest and stamp it on each turn.+ current_model = ""+ current_cwd = ""+ active_native_turn_id = ""++ for line in lines:+ line_type = line.get("type", "")+ payload = line.get("payload", {})+ ts = line.get("timestamp", "")++ if line_type in {"session_meta", "turn_context"}:+ observed_cwd = payload.get("cwd")+ if isinstance(observed_cwd, str) and observed_cwd:+ current_cwd = observed_cwd++ if line_type == "turn_context":+ model_id = model_id_or_none(payload.get("model"))+ active_native_turn_id = payload.get("turn_id") or ""+ if model_id:+ current_model = model_id+ # A context can precede the NEXT user message. Never relabel+ # already observed usage on the preceding turn with that model.+ if (+ native_events is None+ and current_turn is not None+ and not current_turn["cost_events"]+ ):+ current_turn["model"] = model_id+ continue++ if line_type == "response_item" and payload.get("role") == "user":+ content = payload.get("content", [])+ user_text = ""+ for block in content if isinstance(content, list) else []:+ if isinstance(block, dict) and block.get("type") == "input_text":+ text = block.get("text", "")+ if not text.startswith("<") and not text.startswith("#"):+ user_text = text+ break++ if user_text:+ if current_turn:+ turns.append(current_turn)+ current_turn = {+ "_src": line, # the line that opened the turn+ "user_query": user_text,+ "start_ts": ts,+ "end_ts": ts,+ "input_tokens": 0,+ "output_tokens": 0,+ "reasoning_tokens": 0,+ "cache_read": 0,+ "tools": [],+ "cost_events": [],+ "model": current_model,+ "_native_turn_id": active_native_turn_id,+ }++ elif line_type == "token_usage_record" and native_events is not None:+ event = native_events.get(source_attrs(line)["source.content_hash"])+ if event is not None and event["message_id"] not in emitted_native:+ emitted_native.add(event["message_id"])+ pending_native_events.setdefault(event["turn_id"], []).append(event)++ elif line_type == "event_msg":+ evt_type = payload.get("type", "")+ if evt_type == "user_message" and not current_turn:+ current_turn = {+ "_src": line,+ "user_query": payload.get("message", ""),+ "start_ts": ts,+ "end_ts": ts,+ "input_tokens": 0,+ "output_tokens": 0,+ "reasoning_tokens": 0,+ "cache_read": 0,+ "tools": [],+ "cost_events": [],+ "model": current_model,+ "_native_turn_id": active_native_turn_id,+ }+ elif evt_type == "token_count" and current_turn:+ if native_events is not None:+ continue+ info = payload.get("info") or {}+ cum = info.get("total_token_usage") or {}+ last = info.get("last_token_usage") or {}+ if not cum and not last:+ continue # Rate-limit-only observation; no usage was reported.+ anchor = source_attrs(line)+ record_id = anchor["source.content_hash"]+ if record_id in seen_usage_records:+ continue+ seen_usage_records.add(record_id)+ # Set only once this record's own cumulative figures have passed+ # every check that judges THEM, so the except below can move the+ # baseline forward without trusting a number that was itself the+ # problem. Leaving the baseline behind on an otherwise sound+ # record would make the next record's delta include the rejected+ # tokens and bill them twice; adopting the figures from a record+ # rejected BECAUSE its counter moved backwards or contradicted+ # itself would corrupt every turn after it. Neither is acceptable,+ # hence the narrow window.+ rejected_total: int | None = None+ rejected_cumulative: tuple[int, int, int] | None = None+ try:+ cur_total = cum.get("total_tokens")+ if cur_total is not None and (+ isinstance(cur_total, bool)+ or not isinstance(cur_total, int)+ or cur_total < 0+ ):+ raise ValueError("Invalid Codex cumulative token count")+ # Components only. The priceability refusal is deferred to+ # just after the baseline is recorded below: a cache-write+ # figure is well formed and its total is trustworthy, so+ # raising here would hold the baseline at the previous+ # record and make every later delta span two records.+ cumulative = (+ _token_components(cum)+ if "input_tokens" in cum and not _total_only_usage(cum)+ else None+ )+ if cur_total is not None and prev_total_tokens is not None:+ if cur_total < prev_total_tokens:+ # No inferred counter epochs. A decrease may be+ # a reset or stale snapshot; hold capture for reconciliation.+ raise ValueError("Codex cumulative usage moved backwards")+ if cur_total == prev_total_tokens:+ if (+ cumulative is not None+ and prev_usage is not None+ and cumulative != prev_usage+ ):+ raise ValueError(+ "Codex repeated total has conflicting token components"+ )+ # Nothing to bill, but still something to say: a+ # repeated total that carries an unpriceable+ # component has shown us a cost we did not account+ # for, and continuing quietly would let the session+ # report a complete picture that is not complete.+ # The baseline is untouched either way, the total+ # has not moved.+ _reject_unpriceable_components(cum)+ continue+ # Past this point the cumulative figures are trustworthy:+ # well formed, not moving backwards, not contradicting a+ # repeated total. Anything rejected from here on is a fault+ # in `last`, in the delta, or in a component this parser+ # cannot price, none of which impugns the running total.+ rejected_total = cur_total+ rejected_cumulative = cumulative+ # Safe to refuse now: whatever happens next, the baseline+ # moves to this record's own figures rather than staying on+ # the one before it.+ _reject_unpriceable_components(cum)+ if _total_only_usage(cum) or _total_only_usage(last):+ current_turn["usage_incomplete"] = True+ if cur_total is not None:+ current_turn["reported_total_tokens"] = cur_total+ if not last or _total_only_usage(last):+ if cur_total is not None:+ prev_total_tokens = cur_total+ prev_usage = cumulative+ if ts:+ current_turn["end_ts"] = ts+ continue+ basis = "last_token_usage"+ if last:+ usage = _token_usage(last)+ reasoning = _reasoning_tokens(last, usage[2])+ if cur_total is not None and prev_total_tokens is not None:+ # The snapshot says the counter moved by exactly this+ # much; the per-call components must add up to it or+ # the billed figure disagrees with the vendor's own+ # total. Same total definition as+ # `_token_usage` (input incl. cached + output).+ delta = cur_total - prev_total_tokens+ if usage[0] + usage[2] != delta:+ raise ValueError(+ "Codex last_token_usage disagrees with the cumulative delta"+ )+ elif cumulative is not None:+ basis = "cumulative_delta"+ # No per-call snapshot to read reasoning_output_tokens+ # from here, only a running total with no matching+ # prev-reasoning baseline tracked alongside prev_usage+ # -- report 0 rather than fabricate a delta.+ reasoning = 0+ if prev_total_tokens is not None and prev_usage is None:+ # A total-only prefix cannot provide a component delta.+ # Establish this baseline for later observed increments.+ current_turn["usage_incomplete"] = True+ prev_total_tokens, prev_usage = cur_total, cumulative+ continue+ usage = tuple(+ a - b for a, b in zip(cumulative, prev_usage or (0, 0, 0), strict=True)+ )+ if min(usage) < 0 or usage[1] > usage[0]:+ # The total climbed, so `rejected_total` stays: that+ # figure passed its own guards above. These components+ # did not, and adopting them would measure every later+ # delta against numbers this parser has just refused,+ # rejecting the rest of the session off one bad record.+ rejected_cumulative = None+ raise ValueError("Codex cumulative components moved backwards")+ else:+ raise ValueError("Codex usage has no billed token components")+ if cur_total is not None:+ prev_total_tokens = cur_total+ prev_usage = cumulative+ in_t, cache_r, out_t = usage+ if in_t or out_t:+ if not ts:+ raise ValueError("Codex billed usage has no timestamp")+ current_turn["input_tokens"] += in_t+ current_turn["output_tokens"] += out_t+ current_turn["reasoning_tokens"] += reasoning+ current_turn["cache_read"] += cache_r+ current_turn["model"] = current_model+ current_turn["cost_events"].append(+ {+ "timestamp": ts,+ "request_id": None,+ "message_id": f"codex-usage:{record_id}",+ "model": current_model,+ "input_tokens": in_t - cache_r,+ "cache_read_tokens": cache_r,+ "cache_write_5m_tokens": 0,+ "cache_write_1h_tokens": 0,+ "output_tokens": out_t,+ "reasoning_tokens": reasoning,+ "usage_basis": basis,+ **anchor,+ }+ )+ except ValueError as exc:+ # A vendor change to this one usage snapshot must not cost the+ # whole transcript: lose this record's token accounting only,+ # mark the turn's usage incomplete (same signal as a total-only+ # export), and keep every other turn and tool span intact.+ logger.debug(+ "session %s record %s: Codex token_count usage rejected (%s); "+ "marking turn usage incomplete and continuing",+ session_id,+ record_id,+ exc,+ )+ current_turn["usage_incomplete"] = True+ # Resync to whatever the vendor reported for THIS record, so+ # the next record's delta starts from the right place. Only+ # values that passed their own validation above are used; if+ # the totals themselves were the unreadable part, the+ # baseline stays put and the next record is judged against+ # the last figure we could trust.+ if rejected_total is not None:+ prev_total_tokens = rejected_total+ if rejected_cumulative is not None:+ prev_usage = rejected_cumulative+ continue++ if current_turn and ts:+ current_turn["end_ts"] = ts++ elif line_type == "response_item" and payload.get("type") in _TOOL_CALL_TYPES:+ call_id = payload.get("call_id", "")+ name = payload.get("name", "unknown")+ if not isinstance(name, str) or not name:+ name = "unknown"+ # function_call carries JSON `arguments`; custom_tool_call+ # (apply_patch) carries the raw patch text under `input`.+ arguments = str(payload.get("arguments") or payload.get("input") or "")+ evidence = extract_edit_evidence(name, arguments, successful=True)+ if name == "apply_patch":+ # Rewrite BEFORE truncation — paths must land in the+ # retained 2000-char prefix (see `_apply_patch_input`).+ arguments = _apply_patch_input(arguments)+ pending_calls[call_id] = {+ "_src": line, # the line that requested the call+ "call_id": call_id,+ "name": name,+ "input": arguments[:2000],+ "_operations": literal_operations(arguments) if name == "exec" else [],+ "provenance.capture": "unsupported_orchestration"+ if name == "exec"+ else "native_operation",+ "_arguments": arguments if name in {"exec_command", "write_stdin"} else "",+ **creation_command_attributes(arguments, name),+ "edit_evidence": evidence,+ "cwd": current_cwd,+ "output": "",+ "start_ts": ts,+ "end_ts": ts,+ }+ if current_turn and ts:+ current_turn["end_ts"] = ts++ elif line_type == "response_item" and payload.get("type") == "web_search_call":+ # Codex built-in browsing: a single completed line per action —+ # no call_id, no paired `*_output`. Emit a point-in-time tool+ # (start == end, empty output) parented to the current turn,+ # mirroring how the other parsers surface single-event tools+ # (Cursor's `web_search` rows also carry no separate result+ # event). The `action` dict is the whole input: `search`+ # carries `query`/`queries`, `open_page` a `url`,+ # `find_in_page` a `url` + `pattern`.+ if current_turn is not None:+ websearch_seq += 1+ current_turn["tools"].append(+ {+ "_src": line, # the line that carried the search+ "call_id": f"websearch:{websearch_seq}",+ "name": "web_search_call",+ "input": json.dumps(payload.get("action") or {})[:2000],+ "output": "",+ "start_ts": ts,+ "end_ts": ts,+ # Only an explicit `failed` status is failure+ # evidence; completed calls report `completed`.+ "is_error": payload.get("status") == "failed",+ }+ )+ if ts:+ current_turn["end_ts"] = ts++ elif line_type == "response_item" and payload.get("type") in _TOOL_OUTPUT_TYPES:+ call_id = payload.get("call_id", "")+ output = payload.get("output", "")+ pending = pending_calls.get(call_id)+ operations = pending.get("_operations", []) if pending else []+ results = literal_results(output, len(operations)) if operations else []+ if pending and results and current_turn:+ for index, ((name, args), result) in enumerate(+ zip(operations, results, strict=False)+ ):+ arguments = args if isinstance(args, str) else json.dumps(args)+ failed = _tool_output_is_error(json.dumps(result))+ native = {+ "_src": pending["_src"],+ "call_id": f"{call_id}:op:{index}",+ "name": name,+ "provenance.capture": "literal_operation",+ "input": arguments[:2000],+ "cwd": args.get("workdir", pending["cwd"])+ if isinstance(args, dict)+ else pending["cwd"],+ "start_ts": pending["start_ts"],+ "end_ts": ts,+ "output": json.dumps(result)[:2000],+ "is_error": failed,+ "edit_evidence": extract_edit_evidence(+ name, arguments, successful=not failed+ ),+ **creation_command_attributes(arguments, name),+ }+ native.update(+ creation_output_attributes(+ result,+ native.get("pr.create.provider"),+ native.get("pr.create.repository"),+ )+ )+ processes.observe(native, args, result)+ current_turn["tools"].append(native)+ pending_calls.pop(call_id)+ current_turn["end_ts"] = ts+ continue+ if isinstance(output, list):+ output = "\n".join(+ block["text"]+ for block in output+ if isinstance(block, dict)+ and block.get("type") in {"text", "input_text", "output_text"}+ and isinstance(block.get("text"), str)+ )+ if call_id in pending_calls:+ pending_calls[call_id].update(+ creation_output_attributes(+ output,+ pending_calls[call_id].get("pr.create.provider"),+ pending_calls[call_id].get("pr.create.repository"),+ )+ )+ pending_calls[call_id]["output"] = str(output)[:2000]+ # Decide failure on the FULL payload, before truncation —+ # apply_patch's JSON output carries `metadata.exit_code`+ # after a potentially long `output` text, so a truncated+ # string would no longer parse.+ pending_calls[call_id]["is_error"] = _tool_output_is_error(output)+ pending_calls[call_id]["end_ts"] = ts+ try:+ args = json.loads(pending_calls[call_id].get("_arguments") or "null")+ result = shell_result(output)+ except (ValueError, TypeError, RecursionError):+ pass+ else:+ if isinstance(result, dict):+ processes.observe(pending_calls[call_id], args, result)+ if current_turn:+ current_turn["tools"].append(pending_calls.pop(call_id))+ current_turn["end_ts"] = ts++ elif current_turn and ts:+ current_turn["end_ts"] = ts++ if current_turn:+ for call in pending_calls.values():+ current_turn["tools"].append(call)+ turns.append(current_turn)++ turns_by_native_id = {+ turn["_native_turn_id"]: turn for turn in turns if turn.get("_native_turn_id")+ }+ for native_turn_id, events in pending_native_events.items():+ target = turns_by_native_id.get(native_turn_id)+ if target is None:+ target = {+ "_src": native_source_records[events[0]["source.content_hash"]],+ "user_query": "",+ "start_ts": events[0]["timestamp"],+ "end_ts": events[-1]["timestamp"],+ "input_tokens": 0,+ "output_tokens": 0,+ "reasoning_tokens": 0,+ "cache_read": 0,+ "tools": [],+ "cost_events": [],+ "model": events[0]["model"],+ "_native_turn_id": native_turn_id,+ }+ turns.append(target)+ turns_by_native_id[native_turn_id] = target+ for event in events:+ target["input_tokens"] += event["input_tokens"] + event["cache_read_tokens"]+ target["cache_read"] += event["cache_read_tokens"]+ target["output_tokens"] += event["output_tokens"]+ target["reasoning_tokens"] += event["reasoning_tokens"]+ target["model"] = event["model"] or target["model"]+ target["cost_events"].append(event)+ target["start_ts"] = min(target["start_ts"], event["timestamp"])+ target["end_ts"] = max(target["end_ts"], event["timestamp"])++ return turns, native_ledger_rejected+++def _tool_output_is_error(output: object) -> bool:+ """Best-effort failure detection on a Codex tool-call output payload.++ Same conservative semantics as `cursor_store._tool_result_is_error` /+ Claude Code's `is_error` flag: only clear failure evidence flips a tool+ span to ERROR; anything ambiguous stays OK. Codex never sets a failure+ status on the call line itself (`custom_tool_call.status` is+ `"completed"` even for rejected patches), so the output payload is the+ only signal. Recognized shapes:++ - exec-style plain text (`exec_command`/`write_stdin`): a+ `Process exited with code N` header line — nonzero N is a failure.+ Backgrounded processes (`Process running with session ID ...`) carry+ no header and stay OK.+ - `apply_patch` JSON (`{"output": ..., "metadata": {"exit_code": N}}`):+ nonzero `metadata.exit_code` is a failure; a truthy top-level+ `"error"` key too (mirrors cursor's `result.get("error")` check).+ - `apply_patch` plain text: the verifier's+ `apply_patch verification failed: ...` message is a failure.+ - MCP JSON dicts / image-block lists: no failure evidence — OK.++ Args:+ output: The `*_output` payload's `output` field, UNtruncated —+ usually a string, occasionally a list of content blocks.++ Returns:+ True only when the payload carries one of the failure shapes above.+ """+ if not isinstance(output, str) or not output:+ return False+ if output.startswith("apply_patch verification failed"):+ return True+ try:+ parsed = json.loads(output)+ except (json.JSONDecodeError, UnicodeDecodeError):+ parsed = None+ if isinstance(parsed, dict):+ if parsed.get("isError") is True:+ return True+ exit_code = parsed.get("exit_code")+ if type(exit_code) is int and exit_code != 0:+ return True+ metadata = parsed.get("metadata")+ if isinstance(metadata, dict):+ exit_code = metadata.get("exit_code")+ if isinstance(exit_code, int) and not isinstance(exit_code, bool) and exit_code != 0:+ return True+ return bool(parsed.get("error"))+ m = _RE_EXEC_EXIT_CODE.search(output)+ return bool(m and m.group(1) != "0")+++__all__ = ["parse_codex"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot.pynew file mode 100644index 0000000..a1e5557--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot.py@@ -0,0 +1,905 @@+"""Parse GitHub Copilot CLI ``events.jsonl`` sessions into the universal SpanData shape.++Copilot CLI (the ``copilot`` binary from the ``@github/copilot`` npm package)+writes one append-only event log per session:++ ~/.copilot/session-state/<session-id>/events.jsonl (CLI >= 1.0.11)+ ~/.copilot/session-state/<session-id>.jsonl (legacy flat layout)++Every line is an envelope ``{"type", "data", "id", "timestamp", "parentId"}``+with a dotted ``type``. The events this parser reads, verified against the+Copilot CLI 1.0.82 bundle and real local transcripts:++ session.start sessionId, copilotVersion, selectedModel,+ context{cwd, gitRoot, branch, repository, hostType}+ session.resume context{cwd, ...} (a resumed session may move dirs)+ session.model_change newModel, previousModel, reasoningEffort+ session.mode_changed newMode (interactive | autopilot | plan ...)+ user.message content; delivery="steering" is a mid-turn+ injection; parentToolCallId / parentAgentTaskId+ mark a sub-agent's prompt, not the developer's+ assistant.turn_end closes the turn (turnId)+ assistant.message content, model, outputTokens,+ toolRequests[{toolCallId, name, arguments}],+ parentToolCallId on sub-agent traffic+ tool.execution_start toolCallId, toolName, arguments (request fallback)+ tool.execution_complete toolCallId, success, result{content} | error{message},+ model, toolTelemetry{metrics{linesAdded, linesRemoved},+ properties{filePaths: JSON-encoded string array}}+ abort the developer cancelled the running turn+ session.truncation Copilot dropped context (its compaction analogue)+ session.usage_checkpoint totalPremiumRequests (Copilot's billing unit)+ session.shutdown modelMetrics{<model>: {requests{count}, usage{+ inputTokens, outputTokens, cacheReadTokens,+ cacheWriteTokens}}}: the only session-wide token source++# Tokens++Copilot never persists per-request input tokens. The ``assistant.usage`` event+that carries them is emitted ephemerally (streamed to attached clients and+filtered out of ``events.jsonl``). What survives on disk is ``outputTokens``+per ``assistant.message`` and the per-model ``session.shutdown.modelMetrics``+aggregate written when the session ends. So turn spans carry real completion+tokens and zero prompt / cache tokens, and when ``session.shutdown`` is present+the root span carries the billed session totals as ``session.token_count.*``,+which ``session_pure.aggregate_session_spans`` prefers over the turn sums+(the same override Cursor's billed-usage path uses). A session that has not+shut down yet is priced from completion tokens only until its next re-index.+``inputTokens`` is the TOTAL input count, inclusive of cache reads and writes.+This is unlike Anthropic's ``input_tokens`` field despite the similar name:+fresh input = max(input - cache_read - cache_write, 0). The prompt total must+therefore use ``inputTokens`` directly or cached input is counted twice.++# Turns, tools, sub-agents++``user.message`` opens a turn; ``assistant.turn_end`` closes it. A steering+message is appended to the open turn's input rather than starting a new one.+Sub-agent traffic (any event carrying ``parentToolCallId``) stays inside the+turn that spawned it, since its tool calls and tokens are that turn's spend,+and is counted on the root as ``harness.sidechain_count``, the Claude Code+``isSidechain`` analogue. Tool calls pair the request (``toolRequests[]`` or+``tool.execution_start``) with ``tool.execution_complete`` by ``toolCallId``;+a call that never completes becomes a zero-length UNSET span. Raw tool names are+aliased to the canonical vocabulary (``_TOOL_ALIASES``) so the read / edit /+shell counters, the blind-edit ordering and the sub-agent and skill capability+detectors see Copilot sessions the way they see Claude Code ones.++It reads far more than ``user.message`` / ``assistant.message`` /+``tool.execution_complete``: it also emits harness metadata, cwd, session+totals and transcript anchors.+"""++from __future__ import annotations++from collections import Counter+from datetime import UTC, datetime+import json+import logging++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._paths import basename as path_basename+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ SOURCE_HASH_KEY,+ SOURCE_KIND_JSONL,+ SOURCE_OFFSET_KEY,+ parse_dt,+ parse_lines,+)+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+)+from agentplay._core.ingestion.coding_agent.skill_names import normalize_skill_name+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData, model_id_or_none+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++# input.value / output.value truncation, matching every other local parser.+_TRUNCATE = 2000++# Raw -> canonical tool names live in the shared table (tool_taxonomy.py).+_TOOL_ALIASES: dict[str, str] = aliases_for("copilot")++# Raw Copilot name of the skill-invocation tool (``arguments.skill`` names the+# skill). Compared lower-cased.+_SKILL_TOOL_RAW = "skill"++# Canonical names for which a tool-telemetry ``filePaths`` entry may stand in+# for a missing ``file_path`` argument. Deliberately excludes Bash: a shell+# command that happened to touch files must not start carrying a file_path,+# exactly as Claude's ``Bash`` never does (see ``file_paths.py``).+_FILE_TOOLS: frozenset[str] = frozenset({"Read", "Edit", "Write", "MultiEdit", "NotebookEdit"})++# Event types whose sub-agent variants count toward ``harness.sidechain_count``.+_SIDECHAIN_TYPES: frozenset[str] = frozenset(+ {"user.message", "assistant.message", "tool.execution_start", "tool.execution_complete"}+)+++def parse_copilot(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a Copilot CLI ``events.jsonl`` into a span tree.++ Args:+ data: raw JSONL bytes (one Copilot event envelope per line).+ trace_id: the source-prefixed session id (e.g. ``local:copilot:<uuid>``).+ user_id: identifier to stash on the root span's ``user.id``.+ project_name: project name resolved by ``LocalSource`` (from the+ ``session.start`` context cwd); derived from that cwd here when+ not given.++ Returns:+ ``(trace, all_spans)`` with the trace's ``spans`` matching the list.+ Empty when the file holds no parseable lines. A file with metadata+ but no conversation still yields a root span and no turns; the+ indexer (``LocalSource._index_copilot_file``) skips such files before+ they get here.+ """+ transcript_bytes = len(data)+ lines = parse_lines(data)+ if not lines:+ now = datetime.now(UTC)+ return TraceData(trace_id=trace_id, start_time=now, end_time=now), []++ root_id = f"{trace_id}:root"+ all_spans: list[SpanData] = []++ # Session metadata. Identity fields take the first value seen; state+ # fields (model, mode, cwd) take the last, since they change mid-session.+ agent_session_id = ""+ agent_version = ""+ entrypoint = ""+ repository = ""+ branch = ""+ cwd = ""+ model_name = ""+ effort_level = ""+ mode = ""+ sidechain_count = 0+ truncation_count = 0+ premium_requests: float | None = None+ shutdown_metrics: dict | None = None+ shutdown_model = ""+ interrupts_total = 0+ interrupts_during_tool = 0+ slash_counts: Counter[str] = Counter()+ skill_counts: Counter[str] = Counter()+ seen_ignored_etypes: set[str] = set()++ all_timestamps = [t for t in (_event_time(line) for line in lines) if t is not None]+ if all_timestamps:+ session_start = min(all_timestamps)+ session_end = max(all_timestamps)+ else:+ session_start = datetime.now(UTC)+ session_end = session_start++ # Turn assembly state.+ turn_num = 0+ turn: SpanData | None = None+ turn_output_parts: list[str] = []+ turn_completion = 0+ # The model in force for the OPEN turn: seeded from the session-level model+ # when the turn opens, then overwritten by the `model` each of its own+ # assistant.message / tool.execution_complete lines carries. Kept apart+ # from `model_name` because a `session.model_change` between two turns+ # lands BEFORE the next user.message closes the previous turn, and stamping+ # the session-level value at close would credit the earlier turn's work to+ # the later model.+ turn_model = ""+ # toolCallId -> request record (see _new_tool_record); popped on completion.+ pending_tools: dict[str, dict] = {}++ def _close_turn() -> None:+ nonlocal turn, turn_output_parts, turn_completion+ if turn is None:+ return+ turn.attributes["output.value"] = "\n".join(turn_output_parts)[:_TRUNCATE]+ turn.attributes["llm.token_count.completion"] = turn_completion+ # The model a turn ran on is only known once its assistant messages+ # have been read, so it is stamped at close, not at open.+ turn.attributes["llm.model_name"] = turn_model+ # Requests that never completed (session or turn ended mid-call) become+ # zero-length spans; flushing per turn keeps the abort during-tool-use+ # check honest for later turns.+ for rec in pending_tools.values():+ all_spans.append(_build_tool_span(trace_id, rec, None, rec["start"]))+ pending_tools.clear()+ turn = None+ turn_output_parts = []+ turn_completion = 0++ def _open_turn(+ ts: datetime, input_value: str, offset: object, source_hash: object = None+ ) -> SpanData:+ nonlocal turn_num, turn, turn_model+ turn_num += 1+ turn_model = model_name+ turn = SpanData(+ span_id=f"{trace_id}:turn:{turn_num}",+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=ts,+ end_time=ts,+ attributes={+ "input.value": input_value[:_TRUNCATE],+ "output.value": "",+ # The cwd in force when the turn opened (session.start, updated+ # by session.resume). Used to resolve the turn's repo, as for every agent.+ "cwd": cwd,+ # Per-request input tokens are not on disk (see module docstring):+ # prompt / cache attrs stay 0 and the session total rides on the+ # root span instead.+ "llm.token_count.prompt": 0,+ "llm.token_count.completion": 0,+ "llm.token_count.total_billed_prompt": 0,+ "llm.token_count.input_fresh": 0,+ "llm.token_count.cache_read": 0,+ "llm.token_count.cache_write": 0,+ "llm.model_name": model_name,+ },+ )+ # transcript-anchored turn identity, the byte offset of the+ # line that opened the turn.+ if offset is not None:+ turn.attributes["source.byte_offset"] = offset+ # the universal anchor block.+ turn.attributes["source.kind"] = SOURCE_KIND_JSONL+ if source_hash is not None:+ turn.attributes["source.content_hash"] = source_hash+ all_spans.append(turn)+ return turn++ def _record_request(+ call_id: str, name: object, args: object, ts: datetime, offset: object+ ) -> None:+ """Remember a tool request so its completion can be paired later."""+ assert turn is not None # callers open a turn first+ rec = pending_tools.get(call_id)+ if rec is None:+ rec = _new_tool_record(call_id, name, args, ts, offset, turn.span_id, source_hash)+ pending_tools[call_id] = rec+ _note_skill(rec, skill_counts)+ return+ # A request seen twice (toolRequests then execution_start): fill gaps+ # only, never overwrite the first sighting.+ if not rec["name"] and isinstance(name, str) and name:+ rec["name"] = name+ _note_skill(rec, skill_counts)+ if rec["args"] is None and args is not None:+ rec["args"] = args++ prev_ts = session_start+ for line in lines:+ etype = line.get("type")+ if not isinstance(etype, str):+ continue+ payload = line.get("data")+ payload = payload if isinstance(payload, dict) else {}+ ts = _event_time(line) or prev_ts+ prev_ts = ts+ offset = line.get(SOURCE_OFFSET_KEY)+ source_hash = line.get(SOURCE_HASH_KEY)++ parent_call = payload.get("parentToolCallId") or payload.get("parentAgentTaskId")+ is_sidechain = isinstance(parent_call, str) and bool(parent_call)+ if is_sidechain and etype in _SIDECHAIN_TYPES:+ sidechain_count += 1++ if etype == "session.start":+ sid = payload.get("sessionId")+ if not agent_session_id and isinstance(sid, str):+ agent_session_id = sid+ ver = payload.get("copilotVersion")+ if not agent_version and isinstance(ver, str):+ agent_version = ver+ selected = model_id_or_none(payload.get("selectedModel"))+ if selected:+ model_name = selected+ ctx = payload.get("context")+ if isinstance(ctx, dict):+ cwd = _str_field(ctx, "cwd") or cwd+ branch = _str_field(ctx, "branch") or branch+ repository = _str_field(ctx, "repository") or repository+ entrypoint = entrypoint or _str_field(ctx, "hostType")+ continue++ if etype == "session.resume":+ ctx = payload.get("context")+ if isinstance(ctx, dict):+ cwd = _str_field(ctx, "cwd") or cwd+ branch = _str_field(ctx, "branch") or branch+ repository = _str_field(ctx, "repository") or repository+ selected = model_id_or_none(payload.get("selectedModel"))+ if selected:+ model_name = selected+ continue++ if etype == "session.model_change":+ new_model = model_id_or_none(payload.get("newModel"))+ if new_model:+ model_name = new_model+ effort = payload.get("reasoningEffort")+ if isinstance(effort, str) and effort:+ effort_level = effort+ continue++ if etype == "session.mode_changed":+ new_mode = payload.get("newMode")+ if isinstance(new_mode, str) and new_mode:+ mode = new_mode+ continue++ if etype == "session.info":+ # Legacy builds carried no session.start context; the folder-trust+ # notice ("Folder /x/y has been added to trusted folders.") is the+ # only cwd hint they wrote.+ if not cwd and payload.get("infoType") == "folder_trust":+ cwd = _folder_trust_path(payload.get("message")) or cwd+ continue++ if etype == "session.truncation":+ truncation_count += 1+ continue++ if etype == "session.usage_checkpoint":+ requests = _as_float(payload.get("totalPremiumRequests"))+ if requests is not None:+ premium_requests = requests+ continue++ if etype == "session.shutdown":+ metrics = payload.get("modelMetrics")+ if isinstance(metrics, dict) and metrics:+ shutdown_metrics = metrics+ current = model_id_or_none(payload.get("currentModel"))+ if current:+ shutdown_model = current+ requests = _as_float(payload.get("totalPremiumRequests"))+ if requests is not None:+ premium_requests = requests+ continue++ if etype == "abort":+ interrupts_total += 1+ # A cancel with tool calls still awaiting results is an interrupt+ # DURING tool use, the distinction the Claude Code signals draw.+ if pending_tools:+ interrupts_during_tool += 1+ if turn is not None:+ turn.end_time = ts+ continue++ if etype == "user.message":+ if is_sidechain:+ continue # a sub-agent's prompt is not the developer's+ content = payload.get("content")+ text = content if isinstance(content, str) else ""+ stripped = text.lstrip()+ if stripped.startswith("/"):+ command = stripped.split(None, 1)[0].lstrip("/")+ if command:+ slash_counts[command] += 1+ if payload.get("delivery") == "steering" and turn is not None:+ # Steering is delivered INTO the running turn, so it extends the+ # turn's input rather than opening a new one.+ joined = f"{turn.attributes['input.value']}\n{text}".strip()+ turn.attributes["input.value"] = joined[:_TRUNCATE]+ turn.end_time = ts+ continue+ _close_turn()+ _open_turn(ts, text, offset, source_hash)+ continue++ if etype == "assistant.turn_end":+ if turn is not None:+ turn.end_time = ts+ continue++ if etype not in ("assistant.message", "tool.execution_start", "tool.execution_complete"):+ # Reasoning, hooks, subagent lifecycle and system notices are dropped+ # on purpose. A genuinely NEW vendor etype would drop just as+ # silently, which is the failure this warning exists to catch, so+ # only an etype outside the known-intentional set is worth a warning:+ # warning on every skip would add many lines per session of ordinary+ # traffic, and a warning people always see is a warning people mute. Once per distinct value per session either way.+ if etype not in seen_ignored_etypes:+ seen_ignored_etypes.add(etype)+ if _is_intentionally_ignored(etype):+ logger.debug(+ "session %s: copilot event type %r skipped by design",+ trace_id,+ etype,+ )+ else:+ logger.debug(+ "session %s: copilot event type %r is not handled; record "+ "dropped. If Copilot added this type, the parser needs it.",+ trace_id,+ etype,+ )+ continue++ if turn is None:+ # Agent-initiated activity before any user message still needs a+ # turn to live under (same fallback as cursor_store / kiro).+ _open_turn(ts, "", offset, source_hash)+ assert turn is not None # for type checkers; _open_turn always sets it+ turn.end_time = ts++ line_model = model_id_or_none(payload.get("model"))+ if line_model:+ model_name = line_model+ turn_model = line_model++ if etype == "assistant.message":+ out_tokens = payload.get("outputTokens")+ if isinstance(out_tokens, int | float) and not isinstance(out_tokens, bool):+ turn_completion += max(0, int(out_tokens))+ content = payload.get("content")+ if isinstance(content, str) and content.strip():+ turn_output_parts.append(content)+ requests_list = payload.get("toolRequests")+ if isinstance(requests_list, list):+ for req in requests_list:+ if not isinstance(req, dict):+ continue+ call_id = req.get("toolCallId")+ if isinstance(call_id, str) and call_id:+ _record_request(call_id, req.get("name"), req.get("arguments"), ts, offset)+ continue++ call_id = payload.get("toolCallId")+ if not (isinstance(call_id, str) and call_id):+ continue++ if etype == "tool.execution_start":+ _record_request(call_id, payload.get("toolName"), payload.get("arguments"), ts, offset)+ continue++ # tool.execution_complete+ rec = pending_tools.pop(call_id, None)+ if rec is None:+ # A result whose request line was lost (truncated head, hand-edited+ # file): still a tool call that ran, just without its arguments.+ rec = _new_tool_record(call_id, None, None, ts, offset, turn.span_id, source_hash)+ all_spans.append(_build_tool_span(trace_id, rec, payload, ts))++ # Closes the final turn and flushes any tool calls still open at session+ # end (dangling spans), see _close_turn.+ _close_turn()++ if not project_name and cwd:+ project_name = path_basename(cwd) or None++ session_signals = {+ "slash_commands": [{"name": n, "count": c} for n, c in slash_counts.most_common()],+ # ``path`` carries the canonical skill name, the same contract the+ # Claude Code signals use (see _jsonl_utils.extract_session_signals).+ "skills_used": [{"path": p, "count": c} for p, c in skill_counts.most_common()],+ # Copilot never injects a SKILL.md body into the transcript.+ "skill_definitions": [],+ "interrupts": {"total": interrupts_total, "during_tool_use": interrupts_during_tool},+ }++ root_attrs: dict = {+ "user.id": user_id or "",+ "llm.model_name": model_name or shutdown_model,+ "session.id": trace_id,+ "project.name": project_name or "",+ "harness.agent_session_id": agent_session_id,+ "harness.agent_version": agent_version,+ "harness.effort_level": effort_level,+ # Copilot's session mode (interactive | autopilot | plan) is the closest+ # analogue to Claude Code's permission mode: it decides how much the+ # agent may do without asking.+ "harness.permission_mode": mode,+ # The surface the session ran on: "cli", "github" (cloud), ...+ "harness.entrypoint": entrypoint,+ "harness.sidechain_count": sidechain_count,+ "harness.session_signals": json.dumps(session_signals),+ # raw transcript length as read.+ "source.transcript_bytes": transcript_bytes,+ # Copilot-native session facts. Carried so repo attribution and a+ # premium-request -> USD conversion can use them without a re-parse.+ "session.copilot.repository": repository,+ "session.copilot.branch": branch,+ "session.copilot.truncation_count": truncation_count,+ }+ if premium_requests is not None:+ root_attrs["session.copilot.premium_requests"] = premium_requests++ totals = _shutdown_totals(shutdown_metrics, trace_id)+ if totals is not None:+ # Session-wide billed totals: consumers should prefer these over the+ # (prompt-less) turn sums when ``session.token_count.prompt`` is+ # present. ``session.cost_usd`` is deliberately NOT stamped: Copilot+ # bills premium requests, and the dollar value is the pricing layer's+ # call, not the parser's.+ root_attrs["session.token_count.prompt"] = totals["prompt"]+ root_attrs["session.token_count.completion"] = totals["completion"]+ root_attrs["session.token_count.cache_read"] = totals["cache_read"]+ root_attrs["session.token_count.cache_write"] = totals["cache_write"]+ root_attrs["session.copilot.request_count"] = totals["requests"]+ root_attrs["session.copilot.model_metrics"] = json.dumps(+ totals["per_model"], sort_keys=True+ )++ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes=root_attrs,+ )+ all_spans.insert(0, root_span)++ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ return trace, all_spans+++def _new_tool_record(+ call_id: str,+ name: object,+ args: object,+ ts: datetime,+ offset: object,+ turn_id: str,+ source_hash: object = None,+) -> dict:+ """The pending-request record a completion is later paired with."""+ return {+ "call_id": call_id,+ "name": name if isinstance(name, str) and name else "",+ "args": args,+ "start": ts,+ "offset": offset,+ "source_hash": source_hash,+ "turn_id": turn_id,+ }+++def _note_skill(rec: dict, skill_counts: Counter[str]) -> None:+ """Count a ``skill`` tool request under its canonical skill name."""+ if rec["name"].lower() != _SKILL_TOOL_RAW:+ return+ args = _coerce_args(rec["args"])+ if not isinstance(args, dict):+ return+ raw = args.get("skill") or args.get("name")+ if isinstance(raw, str) and raw.strip():+ canonical = normalize_skill_name(raw.strip())+ if canonical is not None:+ skill_counts[canonical] += 1+++def _build_tool_span(+ trace_id: str,+ rec: dict,+ result: dict | None,+ end: datetime,+) -> SpanData:+ """One request / completion pair -> a tool span.++ Tool names are aliased to the canonical vocabulary via ``_TOOL_ALIASES``+ (unknown names pass through). Args are normalized so the shared+ ``file_paths.py`` extractor, which only matches a ``file_path`` key, finds+ the touched file: Copilot's ``view`` / ``edit`` / ``create`` key it as+ ``path``. A call is an ERROR when the completion reported+ ``success: false``; a request with no completion (``result`` is None) is a+ zero-length UNSET span.+ """+ raw_name = rec["name"] or "unknown"+ if not isinstance(raw_name, str):+ raw_name = "unknown"+ tool_name = _TOOL_ALIASES.get(raw_name, raw_name)++ telemetry = result.get("toolTelemetry") if isinstance(result, dict) else None+ telemetry = telemetry if isinstance(telemetry, dict) else {}+ telemetry_paths = _telemetry_file_paths(telemetry) if tool_name in _FILE_TOOLS else []++ args = _coerce_args(rec["args"])+ description = ""+ if isinstance(args, dict):+ args = _normalize_file_path_arg(args, telemetry_paths)+ desc = args.get("description")+ description = desc if isinstance(desc, str) else ""+ input_value = json.dumps(args)+ elif args is None:+ input_value = ""+ else:+ input_value = str(args)++ output_value = ""+ is_error = False+ if result is not None:+ if result.get("success") is False:+ is_error = True+ body = result.get("result")+ if isinstance(body, dict):+ content = body.get("content")+ if isinstance(content, str):+ output_value = content+ elif content is not None:+ output_value = json.dumps(content)+ elif isinstance(body, str):+ output_value = body+ error = result.get("error")+ if not output_value and isinstance(error, dict):+ message = error.get("message")+ if isinstance(message, str):+ output_value = message++ successful = isinstance(result, dict) and result.get("success") is True and not is_error+ command_attrs = creation_command_attributes(input_value, tool_name)+ creation_result = (+ (result.get("result") if command_attrs.get("pr.create.repository") else output_value)+ if successful+ else ""+ )+ attrs: dict = {+ "tool.name": tool_name,+ "code.edit_evidence": extract_edit_evidence(+ raw_name if raw_name == "apply_patch" else tool_name,+ input_value,+ successful=successful,+ ),+ "tool.description": description,+ "input.value": input_value[:_TRUNCATE],+ **command_attrs,+ **creation_output_attributes(+ creation_result,+ command_attrs.get("pr.create.provider"),+ command_attrs.get("pr.create.repository"),+ ),+ "output.value": output_value[:_TRUNCATE],+ # content-anchored identity. ``toolCallId`` is Copilot's own+ # id for the call, stable across re-parses by construction.+ "source.tool_use_id": rec["call_id"],+ }+ if rec["offset"] is not None:+ attrs["source.byte_offset"] = rec["offset"]+ attrs["source.kind"] = SOURCE_KIND_JSONL+ if rec.get("source_hash") is not None:+ attrs["source.content_hash"] = rec["source_hash"]+ metrics = telemetry.get("metrics")+ if isinstance(metrics, dict):+ for key, attr in (+ ("linesAdded", "tool.lines_added"),+ ("linesRemoved", "tool.lines_removed"),+ ):+ value = metrics.get(key)+ if isinstance(value, int | float) and not isinstance(value, bool):+ attrs[attr] = int(value)++ start = rec["start"]+ return SpanData(+ span_id=f"{trace_id}:tool:{rec['call_id']}",+ trace_id=trace_id,+ parent_id=rec["turn_id"],+ name=tool_name,+ span_kind="CHAIN",+ status_code="ERROR" if is_error else "OK" if successful else "UNSET",+ start_time=start,+ end_time=end if end >= start else start,+ attributes=attrs,+ )+++def _coerce_args(args: object) -> object:+ """Tool arguments as recorded, decoding a JSON-encoded string form.++ Copilot writes ``arguments`` as an object; relayed sessions have been seen+ carrying the same payload as a JSON string. Anything else is returned as-is+ so the caller can still stringify it into ``input.value``.+ """+ if isinstance(args, str):+ stripped = args.strip()+ if stripped.startswith("{"):+ try:+ decoded = json.loads(stripped)+ except (json.JSONDecodeError, ValueError):+ return args+ return decoded if isinstance(decoded, dict) else args+ return args+++def _normalize_file_path_arg(args: dict, telemetry_paths: list[str]) -> dict:+ """Alias Copilot's ``path`` arg key to ``file_path``.++ Copilot's file tools (``view``, ``edit``, ``create``, ``str_replace_editor``)+ key the touched file as ``path``; ``file_paths.py``'s shared extractor only+ matches ``file_path``, so the translation happens here, as the Cursor and+ Kiro parsers do for their own key names. When the args carry no path at+ all, the first ``toolTelemetry.properties.filePaths`` entry stands in (the+ caller only passes those for file-oriented tools).++ Purely additive: only fills ``file_path`` when absent, never mutates or+ removes the original key. The synthesized key is PREPENDED: ``input.value``+ is truncated to 2,000 characters and an ``edit`` carrying a large+ ``new_str`` would otherwise push ``file_path`` past the cut, and the file+ would silently vanish from blind-edit / files-touched attribution.+ """+ if "file_path" in args:+ return args+ for key in ("path", "filePath"):+ value = args.get(key)+ if isinstance(value, str) and value:+ return {"file_path": value, **args}+ if telemetry_paths:+ return {"file_path": telemetry_paths[0], **args}+ return args+++def _telemetry_file_paths(telemetry: dict) -> list[str]:+ """Decode ``toolTelemetry.properties.filePaths``, a JSON-encoded string array."""+ props = telemetry.get("properties")+ if not isinstance(props, dict):+ return []+ raw = props.get("filePaths")+ if isinstance(raw, list):+ return [p for p in raw if isinstance(p, str) and p]+ if not isinstance(raw, str) or not raw:+ return []+ try:+ decoded = json.loads(raw)+ except (json.JSONDecodeError, ValueError):+ return []+ if not isinstance(decoded, list):+ return []+ return [p for p in decoded if isinstance(p, str) and p]+++# Copilot event types this parser drops ON PURPOSE: session.*, model.*, hook.*, permission.*,+# subagent.*, skill.invoked, assistant.turn_start. Prefixes rather than an exact+# list because Copilot versions these families independently, and a new member+# of a known-inert family is not the event we are trying to catch.+_IGNORED_ETYPE_PREFIXES = (+ "session.",+ "model.",+ "hook.",+ "permission.",+ "subagent.",+ "skill.",+ "assistant.turn_",+ # `system.message` is the CLI's own system prompt and `system.notification`+ # is a shell/subagent completion notice. Both carry only role/content/+ # kind, no tokens and no tool calls. They are the "system notices dropped on+ # purpose" the skip branch's comment names, so they belong here rather than+ # producing warnings about records nothing wants.+ "system.",+)+++def _is_intentionally_ignored(etype: str) -> bool:+ """True when this event type is a known-inert family, not a new vendor type."""+ return etype.startswith(_IGNORED_ETYPE_PREFIXES)+++def _shutdown_totals(metrics: dict | None, trace_id: str = "<unknown>") -> dict | None:+ """Sum ``session.shutdown.modelMetrics`` across models.++ Returns ``{prompt, completion, cache_read, cache_write, requests,+ per_model}`` or None when there are no metrics or every count is zero+ (a zero aggregate must not override real per-turn completion tokens).+ Copilot's ``inputTokens`` is already the total input count, including cache+ reads and writes. ``input`` in the normalized per-model detail remains the+ fresh component that pricing code expects.+ """+ if not metrics:+ return None+ prompt = completion = cache_read = cache_write = requests = 0+ per_model: dict[str, dict[str, int]] = {}+ for model, entry in metrics.items():+ if not isinstance(model, str) or not isinstance(entry, dict):+ # A malformed modelMetrics key/entry drops that model's whole+ # token total silently otherwise; each bad key is unique per+ # dict, so this can't flood the log.+ logger.debug(+ "session %s: copilot shutdown.modelMetrics entry %r is malformed "+ "(key or value has the wrong shape); its token total is dropped",+ trace_id,+ model,+ )+ continue+ usage = entry.get("usage")+ usage = usage if isinstance(usage, dict) else {}+ req = entry.get("requests")+ req = req if isinstance(req, dict) else {}+ total_input = _as_int(usage.get("inputTokens"))+ out = _as_int(usage.get("outputTokens"))+ read = _as_int(usage.get("cacheReadTokens"))+ write = _as_int(usage.get("cacheWriteTokens"))+ fresh = max(total_input - read - write, 0)+ count = _as_int(req.get("count"))+ per_model[model] = {+ "input": fresh,+ "output": out,+ "cache_read": read,+ "cache_write": write,+ "requests": count,+ }+ prompt += total_input+ completion += out+ cache_read += read+ cache_write += write+ requests += count+ if prompt == 0 and completion == 0:+ return None+ return {+ "prompt": prompt,+ "completion": completion,+ "cache_read": cache_read,+ "cache_write": cache_write,+ "requests": requests,+ "per_model": per_model,+ }+++def _folder_trust_path(message: object) -> str:+ """cwd from a folder-trust notice: "Folder <path> has been added to trusted folders."."""+ if not isinstance(message, str):+ return ""+ marker = "Folder "+ start = message.find(marker)+ if start == -1:+ return ""+ rest = message[start + len(marker) :]+ end = rest.find(" has been")+ path = rest if end == -1 else rest[:end]+ return path.strip()+++def _event_time(line: dict) -> datetime | None:+ """The envelope's ISO-8601 ``timestamp`` as an aware datetime, None when junk."""+ raw = line.get("timestamp")+ if not isinstance(raw, str) or not raw:+ return None+ try:+ dt = parse_dt(raw)+ except ValueError:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return dt+++def _str_field(obj: dict, key: str) -> str:+ value = obj.get(key)+ return value.rstrip("/") if isinstance(value, str) and value else ""+++def _as_int(value: object) -> int:+ if isinstance(value, bool):+ return 0+ if isinstance(value, int | float):+ return max(0, int(value))+ return 0+++def _as_float(value: object) -> float | None:+ if isinstance(value, bool):+ return None+ if isinstance(value, int | float):+ return max(0.0, float(value))+ return None+++__all__ = ["parse_copilot"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot_vscode.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot_vscode.pynew file mode 100644index 0000000..a891c64--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/copilot_vscode.py@@ -0,0 +1,499 @@+"""Parse GitHub Copilot in VS Code (Chat / agent mode) sessions into the universal+SpanData shape.++This is a DIFFERENT product from the ``copilot`` CLI (``copilot.py`` in this+package): VS Code's built-in Copilot Chat extension, in Ask/Edit/Agent mode. It+writes one JSON document per chat session under the workspace's or the empty+window's storage:++ <appUserDir>/workspaceStorage/<ws>/chatSessions/<id>.jsonl+ <appUserDir>/globalStorage/emptyWindowChatSessions/<id>.jsonl+ <appUserDir>/globalStorage/emptyWindowChatSessions/<id>.json (older, rarer)++``<appUserDir>`` is VS Code's (or a fork's) per-OS ``User`` directory; discovery+of the app + OS + home combinations lives in discovery, not here.++# Two on-disk shapes, one final state++A ``.json`` file is the session's final state as one document: ``{version,+sessionId, creationDate, requests: [...], inputState, ...}``.++A ``.jsonl`` file is a snapshot-plus-patches LOG of that same document, one+line per envelope ``{"kind": N, ...}``:++ kind 0 {"kind": 0, "v": <full state dict>} -- initial snapshot+ kind 1 {"kind": 1, "k": [path...], "v": <value>} -- set state[path] = v+ kind 2 {"kind": 2, "k": [path...], "v": [items], "i": idx?}+ -- splice state[path] (a list): "i" omitted means append "v";+ "i" present means truncate the list to "i" items then extend+ with "v" (this is also how a streamed response's text array+ grows token-by-token: repeated kind-2 patches on+ ``requests[N].response`` with a rising "i").++A later patch can rewrite an EARLIER request (e.g. a retried tool call), so+the whole file must be replayed in order every time -- there is no safe+incremental read. The replay below reproduces+the same request count, tool names, and token fields a `.json` (already-final)+sibling file shows directly.++# Per-request fields (verified against real data, not the VS Code source)++ requestId, timestamp (epoch ms), elapsedMs, isComplete, modelId (the+ router alias, e.g. "copilot/auto"), agent{extensionId, id, ...},+ result{usage{promptTokens, completionTokens}, metadata{resolvedModel,+ toolCallRounds, toolCallResults, promptTokens, outputTokens,+ renderedUserMessage, renderedGlobalContext}, errorDetails{code, message,+ isQuotaExceeded}, details (a free-text model/pricing line, e.g.+ "Claude Haiku 4.5 - 13.8 credits" -- premium-request evidence, not yet+ structured)}.++``result.usage.promptTokens`` is the primary token source (present on 14/50+real requests); ``result.metadata.{promptTokens,outputTokens}`` is checked+next (4/50) when ``usage`` is absent. Most requests carry neither -- Copilot+in VS Code will always be activity-complete but token-sparse. Every dollar+computed from what tokens ARE present must carry an "estimated" cost basis,+never treated as authoritative the way Claude's per-request usage+block is.++Model resolution fallback order:+``result.metadata.resolvedModel``, skipped if it is a routing alias -> top-level+``modelId`` (also skipped if a routing alias) -> the session-level+``inputState.selectedModel.identifier`` (last resort; not per-request, also+skipped if a routing alias). "Routing alias" means either a ``"capi-"``-prefixed+internal id, or the literal string ``"copilot/auto"`` -- present on+``modelId`` of real requests, so without also treating it+as an alias the session-level tier could never be reached.++``result.metadata.toolCallRounds[].toolCalls[]`` holds ``{id, name,+arguments}`` with ``arguments`` a JSON-ENCODED STRING (not a pre-parsed+dict). Outputs come from the per-REQUEST (not+per-round) ``result.metadata.toolCallResults[callId]``, itself a VS Code+document-model object: ``{"$mid": N, "content": [{"$mid": M, "value":+"..."}]}``. That shape carries no error flag,+so a tool call is OK when its result is present, UNSET when it never+resolved (killed, interrupted, or the map cuts off mid-round).++A per-request ``errorDetails`` (verified: e.g. ``{"code": "quotaExceeded",+"message": "..."}``) marks the whole request's Turn span as ERROR and is+NOT swallowed into a tool span.++# What is dropped, and where++``renderedUserMessage``, ``renderedGlobalContext``, ``result.details``'+free text, and every tool call/result's own content are read here to run the+same extractors every other parser runs over its transcript text+(commit/PR/ticket detection via ``produced.py``, edit evidence via+``code_authorship.py``) -- exactly like Claude Code, Codex, Cursor and+opencode transcripts, which also carry real prompt/tool text into+``SpanData.attributes`` internally. NONE of that text is unique to this+parser's output.++# Known gap: no cwd / repo resolution++VS Code does not store the workspace path inside the chat session document+itself -- it lives in a sibling ``workspaceStorage/<ws>/workspace.json``+this parser does not read. Sessions from this parser therefore carry no+``cwd`` and resolve no repo/PR-repo context until that sibling file is read+and threaded through.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+import json+import logging++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ SOURCE_KIND_JSON_DOC,+ as_count,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData, model_id_or_none+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++_TOOL_ALIASES: dict[str, str] = aliases_for("copilot-vscode")++# Internal routing aliases VS Code stamps on `modelId`/`resolvedModel` instead+# of a model a person would recognise -- never a real billable model.+_ROUTING_MODEL_PREFIX = "capi-"+# The router alias `modelId` appears on real requests -- also never a real model, but not `capi-`-prefixed, so+# it needs its own check wherever a routing alias is filtered.+_ROUTING_MODEL_ALIAS = "copilot/auto"+++def _is_routing_alias(model: str | None) -> bool:+ return bool(model) and (+ model.startswith(_ROUTING_MODEL_PREFIX) or model == _ROUTING_MODEL_ALIAS+ )+++def parse_copilot_vscode(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse one VS Code Copilot chat session (``.json`` or replayed ``.jsonl``)."""+ state = _load_state(data)+ session_model = _session_level_model(state)+ requests = (state or {}).get("requests")+ if not isinstance(requests, list):+ requests = []+ session_id = (state or {}).get("sessionId") or trace_id+ session_created = _epoch_ms((state or {}).get("creationDate"))++ if not requests:+ now = session_created or datetime.now(UTC)+ trace = TraceData(trace_id=trace_id, start_time=now, end_time=now, spans=[])+ return trace, []++ all_spans: list[SpanData] = []+ root_id = f"{trace_id}:root"+ turn_starts: list[datetime] = []+ turn_ends: list[datetime] = []++ for turn_num, req in enumerate(requests, 1):+ if not isinstance(req, dict):+ continue+ turn_start = _epoch_ms(req.get("timestamp")) or session_created or datetime.now(UTC)+ elapsed = req.get("elapsedMs")+ turn_end = (+ turn_start + _ms_delta(elapsed) if isinstance(elapsed, int | float) else turn_start+ )+ turn_starts.append(turn_start)+ turn_ends.append(turn_end)++ result = req.get("result") if isinstance(req.get("result"), dict) else {}+ usage = result.get("usage") if isinstance(result.get("usage"), dict) else {}+ metadata = result.get("metadata") if isinstance(result.get("metadata"), dict) else {}+ error = result.get("errorDetails") if isinstance(result.get("errorDetails"), dict) else {}++ model = _resolved_model(metadata, req, session_model)+ turn_input = _rendered_user_message_text(metadata.get("renderedUserMessage"))+ turn_output = _response_text(req.get("response"))+ prompt_tokens = usage.get("promptTokens")+ completion_tokens = usage.get("completionTokens")+ if prompt_tokens is None:+ prompt_tokens = metadata.get("promptTokens")+ if completion_tokens is None:+ completion_tokens = metadata.get("outputTokens") or metadata.get("completionTokens")++ request_id = req.get("requestId") or f"{session_id}:{turn_num}"+ turn_id = f"{trace_id}:turn:{turn_num}"+ turn_span = SpanData(+ span_id=turn_id,+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="ERROR" if error else "OK",+ start_time=turn_start,+ end_time=turn_end,+ attributes={+ "llm.model_name": model or "",+ "input.value": turn_input[:2000],+ "output.value": turn_output[:2000],+ "llm.token_count.prompt": as_count(prompt_tokens),+ "llm.token_count.completion": as_count(completion_tokens),+ # No cache/cache-write signal exists for this agent (see module+ # docstring): tokens above are approximate, never authoritative.+ "harness.request_id": str(request_id),+ "harness.is_complete": bool(req.get("isComplete")),+ # Free-text pricing/model line (e.g. "Claude Haiku 4.5 - 13.8+ # credits"): premium-request evidence, not yet structured.+ "copilot.request_detail": str(result.get("details") or "")[:200],+ **(+ {+ "error.code": str(error.get("code") or "")[:80],+ "error.message": str(error.get("message") or "")[:300],+ }+ if error+ else {}+ ),+ },+ )+ turn_span.attributes.update(+ source_attrs({}, kind=SOURCE_KIND_JSON_DOC, row_cursor=str(request_id))+ )+ all_spans.append(turn_span)++ tool_call_results = metadata.get("toolCallResults")+ tool_call_results = tool_call_results if isinstance(tool_call_results, dict) else {}+ rounds = metadata.get("toolCallRounds")+ for round_ in rounds if isinstance(rounds, list) else []:+ for tc in _tool_calls_of(round_):+ span = _tool_span(tc, tool_call_results, trace_id, turn_id, turn_start, turn_end)+ if span is not None:+ all_spans.append(span)++ session_start = min(turn_starts) if turn_starts else session_created or datetime.now(UTC)+ session_end = max(turn_ends) if turn_ends else session_start+ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="AGENT",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "session.id": session_id,+ "session.agent_tool": "copilot-vscode",+ "project.name": project_name or "",+ "user.id": user_id or "",+ },+ )+ all_spans.insert(0, root_span)++ trace = TraceData(+ trace_id=trace_id, start_time=session_start, end_time=session_end, spans=all_spans+ )+ return trace, all_spans+++def _tool_calls_of(round_: object) -> list[dict]:+ calls = (round_ or {}).get("toolCalls") if isinstance(round_, dict) else None+ return [c for c in calls if isinstance(c, dict)] if isinstance(calls, list) else []+++def _tool_span(+ tc: dict,+ tool_call_results: dict,+ trace_id: str,+ turn_id: str,+ turn_start: datetime,+ turn_end: datetime,+) -> SpanData | None:+ call_id = tc.get("id") if isinstance(tc.get("id"), str) else None+ raw_name = tc.get("name")+ if not isinstance(raw_name, str) or not raw_name:+ return None+ name = _TOOL_ALIASES.get(raw_name, raw_name)++ args = tc.get("arguments")+ if isinstance(args, str):+ try:+ args = json.loads(args)+ except (ValueError, RecursionError):+ args = {}+ if not isinstance(args, dict):+ args = {}+ args = _normalize_file_path_arg(args)+ tool_input = json.dumps(args) if args else ""++ result_obj = tool_call_results.get(call_id) if isinstance(call_id, str) else None+ has_result = call_id is not None and call_id in tool_call_results+ output_text = _tool_result_text(result_obj)++ command_attrs = creation_command_attributes(tool_input, name)+ output_attrs = creation_output_attributes(+ output_text,+ command_attrs.get("pr.create.provider"),+ command_attrs.get("pr.create.repository"),+ )+ edit_evidence = extract_edit_evidence(name, tool_input, successful=has_result)++ return SpanData(+ span_id=f"{trace_id}:tool:{call_id or name}:{id(tc)}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=name,+ span_kind="TOOL",+ status_code="OK" if has_result else "UNSET",+ start_time=turn_start,+ end_time=turn_end,+ attributes={+ "tool.name": name,+ "input.value": tool_input[:2000],+ "output.value": output_text[:2000],+ "code.edit_evidence": edit_evidence,+ **command_attrs,+ **output_attrs,+ },+ )+++def _tool_result_text(result_obj: object) -> str:+ """Flatten a VS Code tool-result document (``{"content": [{"value": ...}]}``)+ or a plain string into the text other extractors expect."""+ if isinstance(result_obj, str):+ return result_obj+ if isinstance(result_obj, dict):+ content = result_obj.get("content")+ if isinstance(content, list):+ parts = [c.get("value") for c in content if isinstance(c, dict)]+ return "\n".join(p for p in parts if isinstance(p, str))+ return ""+++def _rendered_user_message_text(parts: object) -> str:+ """The user's typed prompt, as ``result.metadata.renderedUserMessage`` carries+ it: a list of parts, only the plain-text ones (``type == 1``) carrying a string ``text`` field. Image/other reference parts+ (``type`` 2 and 3) never have one and are skipped, not stringified.++ Without this, every Copilot VS Code turn read as an empty prompt to every+ text-based extractor.+ """+ if not isinstance(parts, list):+ return ""+ texts = [p.get("text") for p in parts if isinstance(p, dict) and isinstance(p.get("text"), str)]+ return "\n".join(texts)+++def _response_text(parts: object) -> str:+ """The assistant's final response text, as ``request.response`` carries it: a+ list of heterogeneous parts (thinking, tool-invocation markers, markdown,+ ...). Only the markdown/text parts -- verified real shape: no ``kind`` key at+ all, plus a string ``value`` -- are joined; ``thinking`` parts (the model's+ own chain-of-thought, NOT the answer) are deliberately excluded, same as+ every other kind (tool markers, edit groups, confirmations, ...)."""+ if not isinstance(parts, list):+ return ""+ texts = [+ p.get("value")+ for p in parts+ if isinstance(p, dict) and p.get("kind") is None and isinstance(p.get("value"), str)+ ]+ return "\n".join(texts)+++def _normalize_file_path_arg(args: dict) -> dict:+ """VS Code tool args carry ``filePath`` (camelCase); the shared+ ``file_paths.py`` extractors, and ``code_authorship.extract_edit_evidence``'s+ ``path = obj.get("file_path")``, only ever match snake_case. `file_path`+ key goes FIRST so it survives `input.value`'s 2000-char truncation on a+ large edit -- same reasoning as opencode's `_normalize_file_path_arg`.+ """+ if "file_path" in args:+ return args+ file_path = args.get("filePath")+ if isinstance(file_path, str) and file_path:+ return {"file_path": file_path, **args}+ return args+++def _resolved_model(metadata: dict, req: dict, session_model: str | None) -> str | None:+ resolved = model_id_or_none(metadata.get("resolvedModel"))+ if resolved and not _is_routing_alias(resolved):+ return resolved+ top = model_id_or_none(req.get("modelId"))+ if top and not _is_routing_alias(top):+ return top+ # Last resort: the session-level model the user had selected, not per-request+ # (verified real shape: state.inputState.selectedModel.identifier) -- still+ # better than a bare routing alias when neither per-request field resolved+ # to one. `top` is "copilot/auto" on every real request (verified), so+ # without this tier the session-level signal could never be reached.+ if session_model and not _is_routing_alias(session_model):+ return session_model+ # Every tier was an alias: prefer `top` ("copilot/auto", a recognisable+ # label) over `resolved` (a capi-* internal pool id, meaningless to a+ # person) over session_model, rather than the tier order above -- that+ # order exists to prefer a REAL model where one exists, not to rank+ # unhelpful aliases against each other.+ return top or resolved or session_model+++def _session_level_model(state: dict | None) -> str | None:+ input_state = (state or {}).get("inputState")+ selected = (input_state or {}).get("selectedModel") if isinstance(input_state, dict) else None+ if not isinstance(selected, dict):+ return None+ return model_id_or_none(selected.get("identifier"))+++def _epoch_ms(value: object) -> datetime | None:+ try:+ return datetime.fromtimestamp(int(value) / 1000, tz=UTC)+ except (TypeError, ValueError, OSError, OverflowError):+ return None+++def _ms_delta(ms: float) -> timedelta:+ return timedelta(milliseconds=ms)+++def _load_state(data: bytes) -> dict | None:+ """Return the session's final ``{requests: [...], ...}`` document.++ A ``.json`` file IS that document. A ``.jsonl`` file is a snapshot (kind 0)+ plus patches (kind 1 set / kind 2 list-splice); replay every line in order,+ since a later patch can rewrite an earlier request. Malformed lines and+ patches that reference a path no longer present are skipped, not fatal --+ partial reconstruction beats losing the whole session.+ """+ try:+ doc = json.loads(data)+ except (ValueError, RecursionError):+ doc = None+ if isinstance(doc, dict) and "requests" in doc:+ return doc++ state: dict | None = None+ for raw_line in data.split(b"\n"):+ line = raw_line.strip()+ if not line:+ continue+ try:+ obj = json.loads(line)+ except (ValueError, RecursionError):+ continue+ if not isinstance(obj, dict):+ continue+ kind = obj.get("kind")+ if kind == 0:+ v = obj.get("v")+ state = v if isinstance(v, dict) else {}+ continue+ if state is None or kind not in (1, 2):+ continue+ path = obj.get("k") or []+ if not isinstance(path, list) or not path:+ continue+ cur = state+ ok = True+ for key in path[:-1]:+ try:+ cur = cur[key]+ except (KeyError, IndexError, TypeError):+ ok = False+ break+ if not ok:+ continue+ last = path[-1]+ if kind == 1:+ try:+ cur[last] = obj.get("v")+ except (TypeError, IndexError):+ pass+ continue+ # kind == 2: splice a list. No "i" means append; "i" present means+ # truncate to that length, then extend (how streamed response text+ # arrays grow -- verified against real ["requests", N, "response"]+ # patches with a monotonically rising "i").+ try:+ target = cur[last]+ except (KeyError, IndexError, TypeError):+ continue+ if not isinstance(target, list):+ continue+ values = obj.get("v")+ values = values if isinstance(values, list) else []+ idx = obj.get("i")+ if idx is None:+ target.extend(values)+ elif isinstance(idx, int):+ del target[idx:]+ target.extend(values)+ return state+++__all__ = ["parse_copilot_vscode"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/cursor_agent_transcript.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/cursor_agent_transcript.pynew file mode 100644index 0000000..5277593--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/cursor_agent_transcript.py@@ -0,0 +1,309 @@+"""Parse a Cursor **agent-transcript** JSONL session into the universal SpanData shape.++This is Cursor's third local format, distinct from the two the ``cursor_store``+parser handles (the CLI/agent ``store.db`` NDJSON and the IDE composer ``vscdb``).+Cursor's agent/CLI also writes a lightweight narrative transcript per session at+``~/.cursor/projects/<project-slug>/agent-transcripts/<uuid>/<uuid>.jsonl`` (plus+``subagents/*.jsonl`` children). Each line is an Anthropic-message-shaped record::++ {"role": "user"|"assistant", "message": {"content": [<block>, ...]}}++where each ``<block>`` is ``{"type": "text", "text": ...}`` or+``{"type": "tool_use", "name": ..., "input": {...}, "id": ...}``. Unlike Claude+Code's JSONL this format carries **no** top-level ``type``/``sessionId``, **no**+per-message ``usage`` (billed tokens), and **no** timestamps — so:++* token counts are emitted as 0 (like ``cursor_store`` before its usage-API+ enrichment; there is no local billed-usage source for these files yet), and+* per-turn / per-tool timestamps are **synthesized** monotonically from a single+ base time so the spans keep a stable order and non-zero durations. The absolute+ time is not meaningful (the source has none); ordering, turn/tool+ counts, and the transcript text are.++What it DOES recover : the session+itself, its user/assistant turns, the ``tool_use`` calls (→ ``tool.name`` on TOOL+spans, so ``tool_distribution`` populates), and ``Skill`` / ``activate_skill``+tool calls (→ ``session_signals.skills_used``, so ``skill_distribution`` populates+for Cursor too). It deliberately does not fabricate cost/efficiency numbers the+source can't support.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+import json++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._paths import basename as path_basename+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ _SKILL_TOOL_NAMES,+ parse_jsonl_records,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.base import AgentType++# Reuse the Cursor tool-name aliases + file-path arg normalization from the+# sibling store.db parser: both Cursor surfaces emit the same non-canonical+# vocabulary (`StrReplace`/`Shell`/`ReadLints`/`read_file_v2` …), and the+# read/edit/shell/search counters + the shared `file_paths.py` extractor+# only match the canonical Claude/Codex names + a `file_path` key. Without+# this the agent-transcript sessions would count tools but show 0 on the+# read/edit/shell buckets.+from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ _TOOL_ALIASES,+ _normalize_file_path_arg,+ _skill_name_from_skill_md_path,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData++# Synthetic clock: the source has no timestamps, so space turns/tools by a fixed+# step to keep a stable order + non-zero span durations. Absolute time is not+# meaningful for this format (see module docstring).+_STEP = timedelta(seconds=1)+++def _text_of(content: object) -> str:+ """Concatenate the ``text`` blocks of a message ``content`` (str or list)."""+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ return ""+ parts = [+ block.get("text", "")+ for block in content+ if isinstance(block, dict) and block.get("type") == "text"+ ]+ return "\n".join(p for p in parts if p and isinstance(p, str))+++def _tool_uses(content: object) -> list[dict]:+ """The ``tool_use`` blocks of a message ``content`` (empty if none)."""+ if not isinstance(content, list):+ return []+ return [+ block for block in content if isinstance(block, dict) and block.get("type") == "tool_use"+ ]+++def parse_cursor_agent_transcript(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a Cursor agent-transcript JSONL file into a span tree.++ Args:+ data: raw JSONL bytes.+ trace_id: the source-prefixed session id (``local:cursor:<uuid>``).+ user_id: identifier to stash on the root span's ``user.id``.+ project_name: project slug resolved by ``LocalSource`` (from the path).++ Returns:+ ``(trace, all_spans)`` — a root Session (AGENT) span, one CHAIN span per+ turn, and one TOOL span per ``tool_use``. Empty span list for a file with+ no parseable turns (the caller skips it rather than storing an empty+ session).+ """+ # every record carries the shared source anchors (offset + hash).+ records = [obj for obj in parse_jsonl_records(data) if obj.get("role") in ("user", "assistant")]+ # Ordering only: this format records no activity timestamps. Never re-date+ # identical bytes to the time this parser happens to run.+ base = datetime(1970, 1, 1, tzinfo=UTC)+ if not records:+ return TraceData(trace_id=trace_id, start_time=base, end_time=base), []++ root_id = f"{trace_id}:root"+ all_spans: list[SpanData] = []++ # Group records into turns: a turn opens on a user message and absorbs the+ # assistant messages that follow it (until the next user message). Leading+ # assistant messages (no preceding user) attach to an implicit turn 0.+ turns: list[dict] = []+ current: dict | None = None+ for rec in records:+ if rec.get("role") == "user":+ current = {"user": rec, "assistants": []}+ turns.append(current)+ else:+ if current is None:+ current = {"user": None, "assistants": []}+ turns.append(current)+ current["assistants"].append(rec)++ # Collect skill invocations across the whole session (Skill/activate_skill+ # tool calls) → session_signals.skills_used, so skill_distribution populates.+ skills_used: list[dict] = []+ clock = base++ for turn_num, turn in enumerate(turns, 1):+ turn_id = f"{trace_id}:turn:{turn_num}"+ turn_start = clock+ user_msg = turn["user"].get("message", {}) if turn["user"] else {}+ user_query = _text_of(user_msg.get("content")) if isinstance(user_msg, dict) else ""+ assistant_text_parts: list[str] = []++ # Advance the synthetic clock once per assistant message so tools/turns+ # keep a stable monotonic order.+ tool_spans_this_turn: list[SpanData] = []+ for aline in turn["assistants"]:+ msg = aline.get("message", {})+ if not isinstance(msg, dict):+ continue+ assistant_text_parts.append(_text_of(msg.get("content")))+ for block in _tool_uses(msg.get("content")):+ clock += _STEP+ raw_name = block.get("name", "unknown") or "unknown"+ # A malformed tool block can carry a non-string (unhashable) name+ # — e.g. a list/dict — which would make `_TOOL_ALIASES.get(name)`+ # raise TypeError and, since get_spans_by_session doesn't catch+ # parser errors, drop the WHOLE session. Coerce to str first.+ if not isinstance(raw_name, str):+ raw_name = str(raw_name)+ tool_input = block.get("input", {})+ tool_use_id = block.get("id", "") or f"{turn_num}:{len(tool_spans_this_turn)}"+ # Skill detection uses the RAW name (skill/activate_skill aren't+ # aliased); the span uses the canonical alias so the read/edit/+ # shell/search counters match.+ if str(raw_name).strip().lower() in _SKILL_TOOL_NAMES:+ skill_arg = ""+ if isinstance(tool_input, dict):+ skill_arg = (+ tool_input.get("skill")+ or tool_input.get("name")+ or tool_input.get("command")+ or ""+ )+ if skill_arg:+ skills_used.append({"path": str(skill_arg), "count": 1})+ tool_name = _TOOL_ALIASES.get(raw_name, raw_name)+ if isinstance(tool_input, dict):+ tool_input = _normalize_file_path_arg(tool_input)+ # the _SKILL_TOOL_NAMES check above only ever+ # matches Claude Code's own tool vocabulary ("skill"/+ # "activate_skill") — genuine Cursor skill usage instead+ # shows up as a plain Read call on the skill's SKILL.md+ # path (confirmed against real local Cursor IDE history;+ # see cursor_store.py's _skill_read_from_tool for the+ # full rationale). Match on basename, not a fixed root.+ if tool_name == "Read":+ skill_path = tool_input.get("file_path")+ if (+ isinstance(skill_path, str)+ and skill_path+ and path_basename(skill_path).lower() == "skill.md"+ ):+ canonical = _skill_name_from_skill_md_path(skill_path)+ if canonical:+ skills_used.append({"path": canonical, "count": 1})+ # Serialize file_path FIRST so it survives the input.value+ # truncation below: a large StrReplace / multi-path arg would+ # otherwise push the appended key past the 2000-char cap, and+ # the shared file_paths.py extractor (which keys on file_path)+ # would find nothing — losing edit/read file attribution.+ if "file_path" in tool_input:+ tool_input = {+ "file_path": tool_input["file_path"],+ **{k: v for k, v in tool_input.items() if k != "file_path"},+ }+ input_str = (+ json.dumps(tool_input) if isinstance(tool_input, dict) else str(tool_input)+ )+ tool_spans_this_turn.append(+ SpanData(+ span_id=f"{trace_id}:tool:{tool_use_id}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=str(tool_name),+ span_kind="CHAIN",+ status_code="OK",+ start_time=clock,+ end_time=clock,+ attributes={+ "tool.name": str(tool_name),+ "input.value": input_str[:2000],+ # Narrative calls have neither completion evidence nor+ # observed clocks. The legacy OK span is not a verdict.+ "code.edit_evidence": extract_edit_evidence(+ str(tool_name), tool_input, successful=False+ ),+ "output.value": "",+ **source_attrs(aline),+ },+ )+ )+ clock += _STEP+ turn_end = clock+ assistant_text = "\n".join(p for p in assistant_text_parts if p)++ all_spans.append(+ SpanData(+ span_id=turn_id,+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=turn_start,+ end_time=turn_end,+ attributes={+ "input.value": user_query[:2000] if user_query else "",+ "output.value": assistant_text[:2000] if assistant_text else "",+ "cwd": "",+ # No billed usage in this format — emit explicit zeros so the+ # aggregator treats them as "known 0", not missing.+ "llm.token_count.prompt": 0,+ "llm.token_count.completion": 0,+ "llm.token_count.cache_read": 0,+ "llm.token_count.cache_write": 0,+ "llm.model_name": "",+ # anchored to the record that opened the turn.+ **source_attrs(+ turn["user"] or (turn["assistants"][0] if turn["assistants"] else None)+ ),+ },+ )+ )+ all_spans.extend(tool_spans_this_turn)++ session_start = base+ session_end = clock++ # No "interrupts": {"total": 0} placeholder — `build_sidecar_signals` treats+ # any non-empty dict as a real signal, so a hardcoded zero would make every+ # signal-less session look like it has interrupt data and create a sidecar+ # for nothing (same reasoning as cursor_store.py). This format+ # has no interrupt signal source at all, so omitting the key is what "no+ # signal source" actually means.+ signals = {"slash_commands": [], "skills_used": skills_used}+ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="AGENT",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ # session.id is required on every root span by the TraceSource+ # contract (all sibling parsers set it to trace_id).+ "session.id": trace_id,+ "harness.agent": str(AgentType.CURSOR),+ "harness.session_signals": json.dumps(signals),+ "user.id": user_id or "",+ "project.name": project_name or "",+ "llm.model_name": "",+ },+ )+ all_spans.insert(0, root_span)++ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ for span in all_spans:+ span.attributes["session.timestamps_observed"] = False+ return trace, all_spansdiff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/cursor_store.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/cursor_store.pynew file mode 100644index 0000000..657db1f--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/cursor_store.py@@ -0,0 +1,1062 @@+"""Parse a synthesized Cursor CLI/agent NDJSON transcript into the universal SpanData shape.++Cursor's CLI/agent surfaces persist each session as its own ``store.db`` SQLite+file (no per-session JSONL like Claude Code/Codex). Materialization decodes it+into an NDJSON transcript per session - a header line, then one+line per message verbatim (see ``agentplay.materialize.+find_cursor_store_candidates``):++ {"type": "cursor_store_session", "agentId": ..., "name": ..., "createdAt":+ <ms>, "updatedAt": <ms>, "surface": "cli", "timezone": ..., "cwd": ...,+ "contextUsed": ..., "contextWindow": ...}+ {"role": "user"|"assistant"|"tool", "content": <str|parts>, "id": ...,+ "providerOptions": ...}+ ...++``content`` is a plain string or a list of parts (``text`` /+``redacted-reasoning``/``reasoning`` / ``tool-call`` / ``tool-result`` /+``image``). The model lives at ``providerOptions.cursor.modelName`` (message-+or part-level). Unlike every other local format, Cursor carries no native+per-turn billed token usage, so turn attrs default to 0 (see ``_open_turn``).+When the header carries billed usage for the session, it+also carries a SESSION-WIDE billed total (``prompt_tokens``/+``completion_tokens``/``cache_read_tokens``/``cache_write_tokens``/+``cost_cents``) — this parser stamps those onto the root span (see+``_session_billed_usage_attrs``), where session aggregation reads them.++Per-event billed usage (newer materializations): right after the header,+one line is appended per CHARGED usage event of the matched+conversation, sorted ascending by timestamp:++ {"type": "cursor_usage_event", "ts": <epoch millis int>,+ "input_tokens": int, "output_tokens": int, "cache_read_tokens": int,+ "cache_write_tokens": int, "cost_cents": float, "model": str}++This parser maps those events onto turns and stamps the per-turn sums as+``llm.token_count.prompt`` (input + both cache buckets, matching the+header's prompt convention), ``.completion``, ``.cache_read``,+``.cache_write``, ``.input_fresh`` (codex formula: prompt − cache_read) and+``llm.cost.billed_cents`` (exact billed cents for the turn, preferred over+any pricing-catalog estimate).++Event→turn mapping strategy (in preference order):+ 1. TIMESTAMP CONTAINMENT — used when every turn-opening message carries a+ parseable ``createdAt`` (ISO-8601 string; forwarded from IDE+ composer bubbles — exactly the transcripts where the usage join lands)+ and those times are non-decreasing. An event belongs to the last turn+ whose opening time <= the event's ``ts`` (events bill when a generation+ finishes, i.e. after the user message that started the turn); events+ stamped before the first turn clamp to turn 1.+ 2. ORDER-PROPORTIONAL fallback — when message timestamps are absent+ (store.db CLI/ACP transcripts, older materializations). Event ``j`` of ``n``+ (0-based, ts-ascending) goes to turn ``min(k-1, j*k // n)`` of ``k``:+ exact 1:1 when ``n == k``, everything to the single turn when+ ``k == 1``, an even order-based spread otherwise. FAILURE MODE: when+ one turn fired multiple billed calls and a neighbour fired none, this+ smears usage across adjacent turns — per-turn numbers are then an+ approximation, though session totals stay exact (the header sums are+ authoritative and land on the root span regardless).++Turn/tool span times use a message's real ``createdAt`` when available, so+request attribution uses the same clock as the parser's usage mapping.+Undated messages retain the synthetic spread across the header window; their+turn attribution remains approximate.++Returns the same span shape/contract as ``opencode.py``/``codex.py``.+"""++from __future__ import annotations++from bisect import bisect_right+from collections import Counter+from datetime import UTC, datetime+import hashlib+import json+import logging++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._paths import basename as path_basename+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ _SKILL_BODY_MAX_CHARS,+ SOURCE_KIND_SQLITE,+ SOURCE_ROW_CURSOR_KEY,+)+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+)+from agentplay._core.ingestion.coding_agent.skill_names import skill_name_from_skill_md_path+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++# input.value / output.value truncation, matching every other local parser.+_TRUNCATE = 2000++# Raw -> canonical tool names live in the shared table (tool_taxonomy.py).+_TOOL_ALIASES: dict[str, str] = aliases_for("cursor")+++def _skill_body_from_result(result: dict | None) -> str:+ """Best-effort SKILL.md body from a Read tool-result part; "" if unavailable.++ The part's own+ ``"result"`` value is a JSON-encoded string wrapping ``{"contents": "..."}``.+ Handle a plain dict too (some materializations may skip the string-encoding+ step) since either shape is plausible.++ A THIRD shape also occurs: ``"result"`` as a plain+ string that is the file's literal content, not JSON at all (e.g. the file+ starts with ``---`` frontmatter, which is invalid JSON). The caller only+ reaches this function after confirming the read targeted a SKILL.md file,+ so a string that fails to parse as JSON is the body itself, not garbage —+ treating it as empty would drop that whole shape. Never raises -+ a body is a nice-to-have; a parse failure here must not break the span.+ """+ if not isinstance(result, dict):+ return ""+ raw = result.get("result", "")+ if isinstance(raw, dict):+ contents = raw.get("contents")+ return contents if isinstance(contents, str) else ""+ if isinstance(raw, str) and raw:+ try:+ parsed = json.loads(raw)+ except (json.JSONDecodeError, UnicodeDecodeError):+ return raw+ if isinstance(parsed, dict):+ contents = parsed.get("contents")+ return contents if isinstance(contents, str) else ""+ return ""+ return ""+++# Lives in `skill_names` so every caller derives names through the SAME+# function - two copies of this rule is exactly how two names for one skill+# come to differ. Kept as a module-local alias: this parser and its tests+# reference it by the private name, and the indirection costs nothing.+_skill_name_from_skill_md_path = skill_name_from_skill_md_path+++def _skill_read_from_tool(+ tool_name: str, args: dict, result: dict | None+) -> tuple[str, str] | None:+ """Detect a Cursor skill invocation from an already-resolved Read call.++ Cursor has no dedicated ``Skill``/``activate_skill`` tool — that vocabulary+ is Claude Code's. Cursor's own skills system is invoked by the model+ reading the skill's SKILL.md file with a plain Read call, per Cursor's own+ injected instructions ("read the skill file at the provided absolute path+ using the Read tool"). Confirmed against this machine's real local Cursor+ IDE history — the tool name in that capture was+ ``read_file_v2``, already aliased to ``"Read"`` by ``_TOOL_ALIASES`` above.++ Matches on the file's basename only (case-insensitive) via+ `_skill_name_from_skill_md_path` — see that function for why a fixed root+ directory doesn't work here.++ Args:+ tool_name: the tool name AFTER `_TOOL_ALIASES` resolution (e.g. "Read",+ not "read_file_v2").+ args: the tool call's args, already passed through+ `_normalize_file_path_arg` (so `"file_path"` is present when+ resolvable).+ result: the matching tool-result part, or None if the call never+ completed.++ Returns:+ `(canonical_skill_name, body)` when this call read a SKILL.md file+ with a resolvable canonical name (`body` is `""` when the result+ carried no usable content, INCLUDING a failed read — see below);+ `None` when this isn't a skill read.+ """+ if tool_name != "Read":+ return None+ file_path = args.get("file_path")+ if not isinstance(file_path, str) or not file_path:+ return None+ if path_basename(file_path).lower() != "skill.md":+ return None+ canonical = _skill_name_from_skill_md_path(file_path)+ if canonical is None:+ return None+ # A failed read (file missing, permission denied, ...) still names the+ # attempted skill, but its "result" is an error string/blob, not file+ # content — post-, a non-JSON string is otherwise treated as the+ # literal body, so an unguarded call here would store the error message+ # as the skill's body. Same empty-body contract as a dangling call with+ # no result at all.+ if result is not None and _tool_result_is_error(result):+ return canonical, ""+ return canonical, _skill_body_from_result(result)+++def _event_hash(event: dict | None) -> str | None:+ """Content-anchored identity for one raw NDJSON event.++ Cursor's cache file is REGENERATED on every materialization (the whole+ NDJSON is rewritten), so byte offsets are not stable between reads —+ unlike claude-code's append-only JSONL. A canonical-JSON hash of the+ event dict is the stable identity instead: the same message content+ hashes the same regardless of where the rewrite placed it. 16 hex chars+ of sha1 — collision space is per-session (tens to hundreds of events).+ """+ if not isinstance(event, dict):+ return None+ # The parser's own `_ent_*` stamps (the bubble id the synthesizer adds+ # as the row cursor) are not content - stripping them keeps every hash+ # identical to what the same message hashed to before the stamp existed.+ body = {k: v for k, v in event.items() if not (isinstance(k, str) and k.startswith("_ent_"))}+ try:+ canonical = json.dumps(body, sort_keys=True, default=str)+ except (TypeError, ValueError):+ return None+ return hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:16]+++def _row_cursor(event: dict | None) -> str | None:+ """The record's addressable key — the composer bubble id.++ The synthesizer has always written the bubble id as the message's+ ``id`` (user and assistant messages), so existing files already carry+ it and it is already inside the content hash. The ``_ent_row_cursor``+ stamp is the generic fallback for a producer that keeps the key out of+ the record body. None when neither is present.+ """+ if not isinstance(event, dict):+ return None+ for key in ("id", SOURCE_ROW_CURSOR_KEY):+ cursor = event.get(key)+ if isinstance(cursor, str) and cursor:+ return cursor+ return None+++def parse_cursor_store(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a synthesized Cursor CLI/agent NDJSON transcript into a span tree.++ Args:+ data: raw NDJSON bytes — header line + one message line each.+ trace_id: the source-prefixed session id (e.g. `local:cursor:<uuid>`).+ user_id: identifier to stash on the root span's `user.id`.+ project_name: project name resolved by `LocalSource` (from the+ header's `cwd`); used as-is when the caller already knows it.++ Returns:+ `(trace, all_spans)` with the trace's `spans` matching the list.+ Empty when the header is missing/malformed or there are zero+ messages — `LocalSource` already skips indexing such a file (see+ `_index_cursor_store_file`), so this is a defensive fallback for+ direct callers, not a path normal indexing hits.+ """+ transcript_bytes = len(data)+ header, usage_events, messages = _parse_ndjson(data, trace_id)+ if header is None or not messages:+ now = datetime.now(UTC)+ return TraceData(trace_id=trace_id, start_time=now, end_time=now), []++ cwd = header.get("cwd") if isinstance(header.get("cwd"), str) else ""+ if not project_name and cwd:+ project_name = path_basename(cwd) or None++ session_start = _ms_to_dt(header.get("createdAt"))+ session_end = _ms_to_dt(header.get("updatedAt"))+ if session_start is None and session_end is None:+ session_start = session_end = datetime.now(UTC)+ elif session_start is None:+ session_start = session_end+ elif session_end is None or session_end < session_start:+ session_end = session_start++ n_messages = len(messages)++ def _clock(i: int) -> datetime:+ real = _iso_to_dt(messages[i].get("createdAt"))+ if real is not None:+ return real+ if n_messages <= 1:+ return session_start+ return session_start + (session_end - session_start) * (i / (n_messages - 1))++ root_id = f"{trace_id}:root"+ all_spans: list[SpanData] = []+ # toolCallId -> (tool-call part, owning turn's span_id, call timestamp,+ # the requesting message's row cursor or None).+ pending_calls: dict[str, tuple[dict, str, datetime, str | None]] = {}+ # skill invocations detected via `_skill_read_from_tool`, keyed by+ # canonical name — same contract shape claude_code.py's capture produces.+ skill_counts: Counter[str] = Counter()+ skill_bodies: dict[str, str] = {}++ turn_num = 0+ turn: SpanData | None = None+ turn_output_parts: list[str] = []+ turn_model = ""+ # Parallel per-turn records for usage-event mapping: the turn spans in+ # order, and the REAL wall-clock time of each turn's opening message+ # (None when that message carried no createdAt) — see module docstring.+ turns: list[SpanData] = []+ turn_open_real_ts: list[datetime | None] = []+ seen_unknown_roles: set[str] = set()++ def _close_turn() -> None:+ nonlocal turn, turn_output_parts, turn_model+ if turn is not None:+ turn.attributes["output.value"] = "\n".join(turn_output_parts)[:_TRUNCATE]+ if turn_model:+ turn.attributes["llm.model_name"] = turn_model+ turn = None+ turn_output_parts = []+ turn_model = ""++ def _open_turn(+ ts: datetime,+ input_value: str = "",+ real_ts: datetime | None = None,+ source_hash: str | None = None,+ row_cursor: str | None = None,+ ) -> None:+ nonlocal turn_num, turn+ turn_num += 1+ turn = SpanData(+ span_id=f"{trace_id}:turn:{turn_num}",+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=ts,+ end_time=ts,+ attributes={+ "input.value": input_value[:_TRUNCATE],+ **creation_command_attributes(input_value),+ "output.value": "",+ # Cursor records cwd once on the header, not per message, so+ # every turn gets the same value — mirrors Codex's uniform+ # per-turn cwd (see codex.py), so the whole session resolves+ # to one repo.+ "cwd": cwd,+ # Token attrs default to 0 (no NATIVE per-turn usage in this+ # format). Newer materializations carry cursor_usage_event+ # lines; when present, the+ # mapped turns get these overwritten by+ # _stamp_turn_billed_usage after the message loop. (A+ # session-WIDE total may also land on the root span — see+ # _session_billed_usage_attrs.)+ "llm.token_count.prompt": 0,+ "llm.token_count.completion": 0,+ "llm.token_count.total_billed_prompt": 0,+ "llm.token_count.input_fresh": 0,+ "llm.token_count.cache_read": 0,+ "llm.token_count.cache_write": 0,+ "llm.model_name": "",+ },+ )+ if source_hash is not None:+ # content-anchored turn identity (offsets are unstable+ # here — see _event_hash's docstring).+ turn.attributes["source.content_hash"] = source_hash+ # the store file is rewritten on each materialization, so the anchor kind is+ # the content hash, never an offset; `source.kind` says so explicitly.+ turn.attributes["source.kind"] = SOURCE_KIND_SQLITE+ if row_cursor:+ # the bubble id — the seekable key in a rewritten store.+ turn.attributes["source.row_cursor"] = row_cursor+ all_spans.append(turn)+ turns.append(turn)+ turn_open_real_ts.append(real_ts)++ for i, msg in enumerate(messages):+ role = msg.get("role")+ if role == "system":+ continue+ ts = _clock(i)++ if role == "user":+ _close_turn()+ _open_turn(+ ts,+ _text_from_content(msg.get("content")),+ _iso_to_dt(msg.get("createdAt")),+ source_hash=_event_hash(msg),+ row_cursor=_row_cursor(msg),+ )+ continue++ if turn is None:+ # Assistant/tool activity before any user message (e.g. an+ # agent-initiated step) still needs a turn to live under.+ _open_turn(+ ts,+ real_ts=_iso_to_dt(msg.get("createdAt")),+ source_hash=_event_hash(msg),+ row_cursor=_row_cursor(msg),+ )+ turn.end_time = max(turn.end_time, ts)++ if role == "assistant":+ parts = msg.get("content") if isinstance(msg.get("content"), list) else []+ text_bits = [+ p["text"]+ for p in parts+ if isinstance(p, dict) and p.get("type") == "text" and isinstance(p.get("text"), str)+ ]+ if text_bits:+ turn_output_parts.append("\n".join(text_bits))+ model = _model_from_message(msg)+ if model:+ turn_model = model+ for part in parts:+ if isinstance(part, dict) and part.get("type") == "tool-call":+ call_id = part.get("toolCallId")+ if call_id and isinstance(call_id, str):+ previous = pending_calls.get(call_id)+ if previous is not None:+ old_call, old_turn, old_ts, old_cursor = previous+ # Cursor reuses call IDs in distinct bubbles. Keep+ # the unfinished attempt before the newer call takes+ # ownership of any subsequent result.+ all_spans.append(+ _build_tool_span(+ trace_id,+ old_turn,+ old_call,+ None,+ old_ts,+ old_ts,+ skill_counts,+ skill_bodies,+ row_cursor=old_cursor,+ )+ )+ pending_calls[call_id] = (part, turn.span_id, ts, _row_cursor(msg))+ elif role == "tool":+ parts = msg.get("content") if isinstance(msg.get("content"), list) else []+ for part in parts:+ if not (isinstance(part, dict) and part.get("type") == "tool-result"):+ continue+ call_id = part.get("toolCallId")+ call_part, tool_turn_id, call_ts, call_cursor = pending_calls.pop(+ call_id if isinstance(call_id, str) else None, (None, turn.span_id, ts, None)+ )+ all_spans.append(+ _build_tool_span(+ trace_id,+ tool_turn_id,+ call_part,+ part,+ call_ts,+ ts,+ skill_counts,+ skill_bodies,+ # The request's message anchors the call; the result's+ # message is the fallback for an orphaned result.+ row_cursor=call_cursor or _row_cursor(msg),+ )+ )+ else:+ # A role outside user/assistant/tool/system drops the whole+ # message's content with nothing else to show for it.+ # `role` is whatever the vendor put there, so the dedup key is+ # built from its type name and repr rather than the value: repr is+ # defined for every object (a list or dict is unhashable and using+ # the value itself as a set key would raise TypeError and abort the+ # whole transcript, the exact failure this warning exists to+ # prevent), and the type name keeps values Python calls equal but a+ # reader would not -- integer 0 and boolean false -- each named once.+ role_key = (type(role).__name__, repr(role))+ if role_key not in seen_unknown_roles:+ seen_unknown_roles.add(role_key)+ logger.debug(+ "session %s: cursor_store message has unrecognised role %r; "+ "message content dropped",+ trace_id,+ role,+ )++ _close_turn()++ if usage_events and turns:+ _stamp_turn_billed_usage(turns, turn_open_real_ts, usage_events)++ # Tool calls that never saw a matching result (session ended mid-call) —+ # still worth a span; the absence of a result does not establish success.+ for call_part, tool_turn_id, call_ts, call_cursor in pending_calls.values():+ all_spans.append(+ _build_tool_span(+ trace_id,+ tool_turn_id,+ call_part,+ None,+ call_ts,+ call_ts,+ skill_counts,+ skill_bodies,+ row_cursor=call_cursor,+ )+ )++ # Session model = LAST model used, matching opencode/codex/claude_code —+ # consumers read root llm.model_name for provider/cost attribution, and+ # the last model is what siblings report after a mid-session switch.+ # Fallback: the file HEADER also records the picker's model (e.g.+ # "cursor-grok-4.6-high-fast"), and some sessions carry NO message-level+ # providerOptions at all - those+ # sessions would otherwise come out model-less and unpriced despite the+ # header naming the model. "default" (Cursor Auto) passes through as-is: it is+ # honest, and pricing already treats it as unpriceable either way.+ session_model = _last_model(messages) or str(header.get("model") or "")++ # same session_signals contract claude_code.py populates, so+ # skill_distribution reads Cursor sessions the same way it reads+ # Claude Code ones. No "interrupts" key: build_sidecar_signals treats any+ # non-empty dict as a real signal (`if sig.get(key)`), so a hardcoded zero+ # would make every signal-less Cursor session look like it has interrupt+ # data, creating a sidecar for nothing. This format can't detect interrupts at all - omitting the key,+ # not zeroing it, is what "no signal source" actually means.+ signals = {+ "slash_commands": [],+ "skills_used": [{"path": p, "count": c} for p, c in skill_counts.most_common()],+ "skill_definitions": [+ {"name": p, "body": skill_bodies[p]}+ for p, _ in skill_counts.most_common()+ if skill_bodies.get(p)+ ],+ }++ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "user.id": user_id or "",+ "llm.model_name": session_model,+ "session.id": trace_id,+ "project.name": project_name or "",+ # Cursor's native session id — the header's `agentId`. The+ # header carries no agent/CLI version, so that attr is absent.+ "harness.agent_session_id": str(header.get("agentId") or ""),+ "harness.session_signals": json.dumps(signals),+ **_session_billed_usage_attrs(header),+ **_session_context_path_attrs(header),+ # length of the synthesized NDJSON as parsed. Weaker+ # than claude-code's (the file is rewritten per materialization)+ # but still an honest observed-size claim.+ "source.transcript_bytes": transcript_bytes,+ },+ )+ all_spans.insert(0, root_span)+ if messages and not any(_iso_to_dt(m.get("createdAt")) is not None for m in messages):+ # Every turn clock above came from `_clock`'s even spread between the+ # header's createdAt/updatedAt — synthetic ordering, not observed+ # activity time. Same flag cursor_agent_transcript raises for its+ # clock-less source, so consumers omit the fabricated dates. A composer with SOME real+ # createdAt stays observed: those anchor the spread.+ for span in all_spans:+ span.attributes["session.timestamps_observed"] = False++ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ return trace, all_spans+++def _build_tool_span(+ trace_id: str,+ turn_id: str,+ call: dict | None,+ result: dict | None,+ start: datetime,+ end: datetime,+ skill_counts: Counter[str],+ skill_bodies: dict[str, str],+ row_cursor: str | None = None,+) -> SpanData:+ """One tool-call/tool-result pair -> a tool span.++ Tool names are aliased to the canonical Claude/Codex vocabulary via+ `_TOOL_ALIASES`. Every other local parser here passes tool names+ through unaliased because their native names ARE canonical; Cursor's+ aren't, so this is the one parser that needs the table. Unknown names+ pass through unchanged.++ Args are also normalized here (see `_normalize_file_path_arg`) so the+ shared `file_paths.py` extractor — which only ever matches a+ `"file_path"` key, on purpose, to stay byte-identical for Claude/+ Codex/opencode — finds Cursor's file too. This keeps the Cursor-only+ quirk (its args key the touched file as `"path"`/`"paths"`) confined+ to this parser instead of widening the shared extractor.++ `skill_counts`/`skill_bodies` are mutated in place when this call turns+ out to be a Cursor skill invocation (see `_skill_read_from_tool`)+ — done here rather than at the call sites so the tool-name-alias + arg-+ normalization logic this needs stays in one place.+ """+ raw_name = (call or {}).get("toolName")+ raw_name = raw_name if isinstance(raw_name, str) and raw_name else "unknown"+ tool_name = _TOOL_ALIASES.get(raw_name, raw_name)+ args = (call or {}).get("args", {})+ if isinstance(args, dict):+ args = _normalize_file_path_arg(args)+ skill = _skill_read_from_tool(tool_name, args, result)+ if skill is not None:+ canonical, body = skill+ skill_counts[canonical] += 1+ # Capped the same as the Claude Code path (`_skill_body_after_marker`)+ # — a Read result can embed arbitrarily large file content otherwise.+ body = body[:_SKILL_BODY_MAX_CHARS] if body else body+ if body and len(body) > len(skill_bodies.get(canonical, "")):+ skill_bodies[canonical] = body+ input_value = args if isinstance(args, str) else json.dumps(args)++ output_value = ""+ is_error = False+ if result is not None:+ raw_result = result.get("result", "")+ output_value = raw_result if isinstance(raw_result, str) else json.dumps(raw_result)+ is_error = _tool_result_is_error(result)++ call_id = (call or {}).get("toolCallId") or f"{turn_id}:{start.isoformat()}"+ source_attrs: dict = {}+ native_call_id = (call or {}).get("toolCallId")+ if native_call_id:+ # Cursor's own toolCallId — content-anchored, survives the+ # cache rewrite (carried explicitly, same reasoning as claude-code's+ # source.tool_use_id).+ source_attrs["source.tool_call_id"] = str(native_call_id)+ content_hash = _event_hash(call) or _event_hash(result)+ if content_hash is not None:+ source_attrs["source.content_hash"] = content_hash+ source_attrs["source.kind"] = SOURCE_KIND_SQLITE+ if row_cursor:+ source_attrs["source.row_cursor"] = row_cursor+ # Native tool-call IDs repeat across IDE bubbles. The bubble identifies+ # the occurrence while the vendor ID above remains useful for correlation.+ occurrence_id = f"{call_id}:{row_cursor}" if row_cursor else call_id+ command_attrs = creation_command_attributes(input_value, tool_name)+ return SpanData(+ span_id=f"{trace_id}:tool:{occurrence_id}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=tool_name,+ span_kind="CHAIN",+ status_code="UNSET" if result is None else ("ERROR" if is_error else "OK"),+ start_time=start,+ end_time=end,+ attributes={+ "tool.name": tool_name,+ "code.edit_evidence": extract_edit_evidence(+ "apply_patch" if raw_name == "ApplyPatch" else tool_name,+ input_value,+ successful=result is not None and not is_error,+ ),+ "input.value": input_value[:_TRUNCATE],+ **command_attrs,+ **creation_output_attributes(+ output_value,+ command_attrs.get("pr.create.provider"),+ command_attrs.get("pr.create.repository"),+ ),+ "output.value": output_value[:_TRUNCATE],+ **source_attrs,+ },+ )+++def _normalize_file_path_arg(args: dict) -> dict:+ """Alias Cursor's `path`/`paths`/`targetFile`/`relativeWorkspacePath` arg+ keys to `file_path`.++ Cursor's Read/Edit/+ Grep/StrReplace key the touched file as `"path"`; ReadLints keys it as+ a `"paths"` list. IDE composer's `*_v2` tools use different keys entirely+ (`read_file_v2`/`edit_file_v2` calls never carry `"path"`/`"paths"`):+ `read_file_v2` (aliased to `"Read"`) carries `"targetFile"`+ (`"effectiveUri"` is also present but duplicates `"targetFile"`, so it is+ redundant to check separately) and `edit_file_v2` (aliased to `"Edit"`)+ carries `"relativeWorkspacePath"`. Without these, a+ `_TOOL_ALIASES`-resolved `"Read"`/`"Edit"` call never gets a `file_path`,+ which would break Cursor skill-name resolution AND every other+ `file_paths.py` consumer (read/edit/search counters, blind-edit-rate,+ file attribution) for the entire IDE composer surface. Every other local+ parser's native tool args already carry `"file_path"`, which is the only+ key `file_paths.py`'s shared extractor matches — so this is where+ Cursor's shape gets translated, not the shared module.++ Only fills `file_path` when it's absent, and never mutates/removes the+ original key — purely additive. Glob's `target_directory`/+ `targetDirectory` names a directory, not one file, so it's deliberately+ left unmapped rather than fabricating a `file_path` for it. Shell/`Bash`-+ style `"command"` strings are left untouched too — Cursor's shell calls+ get no `file_path`, matching how Claude's `Bash` calls are handled.++ `file_path` is PREPENDED, not appended: `_build_tool_span` serializes+ these args to JSON and truncates to `_TRUNCATE` chars for the span's+ `input.value`, which `file_paths.py`'s regex then scans — a key added at+ the end can be sheared off by that truncation before it's ever read.+ This matters in practice for `edit_file_v2`, whose args carry the whole+ edit diff under `streamingContent`, easily past `_TRUNCATE` on its own.++ Args:+ args: The tool-call's raw `args` dict (already confirmed a dict+ by the caller).++ Returns:+ `args` unchanged, or a shallow copy with `file_path` added.+ """+ if "file_path" in args:+ return args+ path = args.get("path")+ if isinstance(path, str) and path:+ return {"file_path": path, **args}+ paths = args.get("paths")+ if isinstance(paths, list) and paths and isinstance(paths[0], str) and paths[0]:+ return {"file_path": paths[0], **args}+ target_file = args.get("targetFile")+ if isinstance(target_file, str) and target_file:+ return {"file_path": target_file, **args}+ relative_workspace_path = args.get("relativeWorkspacePath")+ if isinstance(relative_workspace_path, str) and relative_workspace_path:+ return {"file_path": relative_workspace_path, **args}+ return args+++def _tool_result_is_error(result: dict) -> bool:+ """Best-effort error detection on a tool-result part."""+ status = result.get("status") or result.get("state")+ if isinstance(status, str) and ("error" in status.lower() or "fail" in status.lower()):+ return True+ return result.get("success") is False or bool(result.get("error") or result.get("isError"))+++def _text_from_content(content: object) -> str:+ """Join every ``text``-type part; ``content`` may also be a plain string."""+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "\n".join(+ p["text"]+ for p in content+ if isinstance(p, dict) and p.get("type") == "text" and isinstance(p.get("text"), str)+ )+ return ""+++def _model_from_message(msg: dict) -> str | None:+ """First ``providerOptions.cursor.modelName`` on a message or its parts."""+ candidates = [msg.get("providerOptions")]+ content = msg.get("content")+ if isinstance(content, list):+ candidates.extend(p.get("providerOptions") for p in content if isinstance(p, dict))+ for po in candidates:+ if isinstance(po, dict):+ cursor = po.get("cursor")+ if isinstance(cursor, dict) and isinstance(cursor.get("modelName"), str):+ return cursor["modelName"]+ return None+++def _last_model(messages: list[dict]) -> str | None:+ """Last model name used in the session, or None if unknown."""+ for msg in reversed(messages):+ model = _model_from_message(msg)+ if model:+ return model+ return None+++# header key -> root-span attribute key, for the token fields (cost_cents is+# handled separately below since it converts units and lands under a+# different name).+_USAGE_TOKEN_FIELDS = (+ ("prompt_tokens", "session.token_count.prompt"),+ ("completion_tokens", "session.token_count.completion"),+ ("cache_read_tokens", "session.token_count.cache_read"),+ ("cache_write_tokens", "session.token_count.cache_write"),+)+++def _session_billed_usage_attrs(header: dict) -> dict:+ """Session-wide billed-token/cost root-span attrs, when the header has them.++ The header may carry ``prompt_tokens``/``completion_tokens``/+ ``cache_read_tokens``/``cache_write_tokens``/``cost_cents`` - they're+ ABSENT, not zero, when no billed usage is known. Every value is validated numeric+ before use so a malformed/missing header can't crash the parse or+ smuggle in a false "session billed zero" reading. ``cost_cents``+ is checked independently of the token fields - it may lag behind+ (present tokens, absent cost) on older files.++ Returns:+ A dict to merge into the root span's ``attributes`` — empty when the+ header carries none of these fields. Keys are only present for+ fields that were actually found, so+ session aggregation can tell "no+ data" (key absent) from "session billed zero" (key present, 0).+ """+ attrs: dict = {}+ for header_key, attr_key in _USAGE_TOKEN_FIELDS:+ value = header.get(header_key)+ # Accept int OR float here (never bool, never NaN/inf, same guard the+ # cost_cents check below already uses) - the usage source can hand back+ # a float, and rejecting it drops the session's whole billed total.+ if (+ isinstance(value, int | float)+ and not isinstance(value, bool)+ and 0 <= value < float("inf")+ ):+ attrs[attr_key] = value+ cost_cents = header.get("cost_cents")+ if (+ isinstance(cost_cents, int | float)+ and not isinstance(cost_cents, bool)+ and 0 <= cost_cents < float("inf")+ ):+ attrs["session.cost_usd"] = cost_cents / 100.0+ return attrs+++def _session_context_path_attrs(header: dict) -> dict:+ """Root-span attr carrying the composer's structured file paths, when present.++ Cursor's IDE composer records reference real files — ``newlyCreatedFiles``,+ ``context.selections``, the ``originalFileStates`` keys, and the git worktree+ / tracked-repo roots — but none of that is a tool call, so none of it reaches+ the tool spans that repo attribution normally reads. Materialization collects+ those paths into the header's ``contextFiles``+ (``agentplay.materialize._cursor_composer_context_paths``); this+ forwards them so they can be leaf-matched against known repos.++ Absent, not empty, when nothing was found - an older materialization omits+ the field entirely, and a reader must be able to tell "this build never collected+ paths" from "this session referenced no files".++ Encoded as a JSON string for the same reason ``harness.session_signals`` is:+ span attributes travel as scalars, and every reader of that attribute already+ accepts either a JSON string or a decoded value.++ Args:+ header: The ``cursor_store_session`` header dict (line 1 of the NDJSON).++ Returns:+ ``{"harness.context_files": "<json array>"}``, or ``{}`` when the header+ carries no usable paths.+ """+ raw = header.get("contextFiles")+ if not isinstance(raw, list):+ return {}+ paths = [p for p in raw if isinstance(p, str) and p]+ if not paths:+ return {}+ return {"harness.context_files": json.dumps(paths, separators=(",", ":"))}+++def _parse_ndjson(+ data: bytes, trace_id: str = "<unknown>"+) -> tuple[dict | None, list[dict], list[dict]]:+ """Split the transcript into `(header, usage_events, messages)`.++ Line 1 must be the `cursor_store_session` header; every subsequent+ valid `{role: ...}` dict is a message, and every+ `{"type": "cursor_usage_event", "ts": <epoch ms int>, ...}` dict is a+ per-event billed-usage line (newer materializations - see module docstring).+ An event line without a positive-int `ts` is dropped: it can't be+ ordered or mapped, and the header's summed totals still carry its+ tokens. Malformed/absent header -> `(None, [], [])`.+ """+ lines: list[dict] = []+ for raw in data.split(b"\n"):+ raw = raw.strip()+ if not raw:+ continue+ try:+ obj = json.loads(raw)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if isinstance(obj, dict):+ lines.append(obj)++ if not lines or lines[0].get("type") != "cursor_store_session":+ return None, [], []++ header, rest = lines[0], lines[1:]+ messages = [m for m in rest if "role" in m]+ usage_events: list[dict] = []+ seen_bad_ts_types: set[str] = set()+ for e in rest:+ if e.get("type") != "cursor_usage_event" or "role" in e:+ continue+ ts = e.get("ts")+ if isinstance(ts, int) and not isinstance(ts, bool) and ts > 0:+ usage_events.append(e)+ continue+ # A `ts` that stops being a positive int (e.g. an ISO string) drops+ # this event's per-event billed tokens and cost_cents with nothing+ # to show for it. Dedup by the value's type, not per event.+ ts_type = type(ts).__name__+ if ts_type not in seen_bad_ts_types:+ seen_bad_ts_types.add(ts_type)+ logger.debug(+ "session %s: cursor_usage_event has non-positive-int ts (type=%s); "+ "event's billed tokens/cost dropped",+ trace_id,+ ts_type,+ )+ # Contract says ts-ascending already; don't trust it — mapping relies on order.+ usage_events.sort(key=lambda e: e["ts"])+ return header, usage_events, messages+++def _ms_to_dt(ms: object) -> datetime | None:+ """Epoch-ms -> aware UTC datetime, or None if missing/not an int."""+ if not isinstance(ms, int) or isinstance(ms, bool):+ return None+ try:+ return datetime.fromtimestamp(ms / 1000, tz=UTC)+ except (OverflowError, OSError, ValueError):+ return None+++def _iso_to_dt(value: object) -> datetime | None:+ """ISO-8601 string (e.g. ``"2025-10-02T06:43:45.379Z"``) -> aware UTC+ datetime, or None when missing/unparsable.++ IDE composer bubbles are the only Cursor messages that carry a+ timestamp, and they carry it in this shape; a naive result (no offset)+ is assumed UTC, matching how Cursor writes them.+ """+ if not isinstance(value, str) or not value:+ return None+ try:+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return dt.astimezone(UTC)+++def _as_count(value: object) -> int:+ """Coerce a usage-event token field to a non-negative int (0 on junk)."""+ if isinstance(value, bool):+ return 0+ if isinstance(value, int | float):+ return max(0, int(value))+ return 0+++def _assign_events_to_turns(+ events: list[dict],+ turn_open_real_ts: list[datetime | None],+) -> list[int]:+ """Per-event turn index (0-based) for ts-ascending ``events``.++ Timestamp containment when every turn-opening time is known and+ non-decreasing; order-proportional spread otherwise — strategy and+ failure mode documented in the module docstring.++ Args:+ events: usage-event dicts, each with a positive-int ``ts``+ (epoch ms), already sorted ascending.+ turn_open_real_ts: real opening time per turn, aligned with the+ parse's turn order; any ``None`` disables containment.++ Returns:+ A list the length of ``events``; each value in+ ``[0, len(turn_open_real_ts))``.+ """+ k = len(turn_open_real_ts)+ if all(t is not None for t in turn_open_real_ts):+ starts_ms = [int(t.timestamp() * 1000) for t in turn_open_real_ts] # type: ignore[union-attr]+ if starts_ms == sorted(starts_ms):+ indexes: list[int] = []+ for event in events:+ idx = bisect_right(starts_ms, event["ts"]) - 1+ indexes.append(max(0, idx))+ return indexes+ n = len(events)+ return [min(k - 1, j * k // n) for j in range(n)]+++def _stamp_turn_billed_usage(+ turns: list[SpanData],+ turn_open_real_ts: list[datetime | None],+ events: list[dict],+) -> None:+ """Map usage events onto turns and stamp per-turn billed token/cost attrs.++ Mutates the mapped Turn spans in place: ``llm.token_count.prompt``+ (input + cache_read + cache_write, the same prompt convention the+ session header uses), ``.completion``, ``.cache_read``,+ ``.cache_write``, ``.input_fresh`` (codex formula: prompt − cache_read)+ and ``llm.cost.billed_cents`` (float; exact billed cents - preferred+ over a pricing-catalog estimate).+ Turns that received no event keep their zeroed attrs and get NO+ ``llm.cost.billed_cents`` key, so "no billing data" stays+ distinguishable from "billed zero cents".+ """+ per_turn: dict[int, dict[str, float]] = {}+ for event, idx in zip(events, _assign_events_to_turns(events, turn_open_real_ts), strict=True):+ bucket = per_turn.setdefault(+ idx,+ {+ "input": 0,+ "output": 0,+ "cache_read": 0,+ "cache_write": 0,+ "cents": 0.0,+ "has_cents": True,+ },+ )+ bucket["input"] += _as_count(event.get("input_tokens"))+ bucket["output"] += _as_count(event.get("output_tokens"))+ bucket["cache_read"] += _as_count(event.get("cache_read_tokens"))+ bucket["cache_write"] += _as_count(event.get("cache_write_tokens"))+ cents = event.get("charged_cents")+ if cents is None:+ cents = event.get("cost_cents")+ if (+ isinstance(cents, int | float)+ and not isinstance(cents, bool)+ and 0 <= cents < float("inf")+ ):+ bucket["cents"] += float(cents)+ else:+ bucket["has_cents"] = False++ for idx, bucket in per_turn.items():+ turn = turns[idx]+ prompt = int(bucket["input"] + bucket["cache_read"] + bucket["cache_write"])+ turn.attributes["llm.token_count.prompt"] = prompt+ turn.attributes["llm.token_count.completion"] = int(bucket["output"])+ turn.attributes["llm.token_count.cache_read"] = int(bucket["cache_read"])+ turn.attributes["llm.token_count.cache_write"] = int(bucket["cache_write"])+ turn.attributes["llm.token_count.input_fresh"] = max(0, prompt - int(bucket["cache_read"]))+ # total_billed_prompt mirrors prompt: Cursor usage events report the+ # actual billed prompt (not context-window max), so it is the same+ # value. Without this, waste computation falls back to prompt_tokens+ # (which is also correct for Cursor, but the explicit key keeps the+ # `or` fallback working).+ turn.attributes["llm.token_count.total_billed_prompt"] = prompt+ # Contract: absent key = "no billing data" (pricing falls back to+ # the catalog); 0.0 = "genuinely billed zero". Stamping 0.0 for events+ # that carried no cost_cents would kill the catalog fallback.+ if bucket["has_cents"]:+ turn.attributes["llm.cost.billed_cents"] = bucket["cents"]+++__all__ = ["parse_cursor_store"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/kiro.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/kiro.pynew file mode 100644index 0000000..010bee5--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/kiro.py@@ -0,0 +1,516 @@+"""Parse a synthesized Kiro NDJSON transcript into the universal SpanData shape.++Kiro persists a session as a DIRECTORY, not a file:+``~/.kiro/sessions/<ws-hash>/<session-id>/`` holds ``session.json`` ++``messages.jsonl``, with sub-agent runs in ``sub-executions/<exec-id>.jsonl``.+Materialization merges those into one NDJSON transcript per session - a header+line, then every event verbatim in timestamp order (see+``agentplay.materialize.find_kiro_candidates``):++ {"type": "kiro_session", "id": ..., "title": ..., "agentMode": "spec"|"vibe",+ "workspacePaths": [...], "createdAt": <ISO>, "lastModifiedAt": <ISO>,+ "autopilot": bool, "specWorkflow": ..., "status": ...}+ {"id": ..., "timestamp": <ISO>, "payload": {"type": "user", "content": ...}}+ {"id": ..., "timestamp": <ISO>, "payload": {"type": "assistant", "content": ...}}+ {"id": ..., "timestamp": <ISO>, "payload": {"type": "tool_call", "toolCallId": ...,+ "toolName": ..., "args": {...}, "status": ..., "kind": ...}}+ {"id": ..., "timestamp": <ISO>, "payload": {"type": "tool_result", "toolCallId": ...,+ "content": ..., "success": bool}}+ ...++Unlike Cursor's synthesized format, every Kiro event carries a real ISO+timestamp, so span times are the true wall clock — no synthetic spread needed.++# Turn boundaries++``user`` events open a turn; ``turn_end`` closes the execution and carries+``stopReason``. Sub-execution files contain only ``assistant``/``tool_call``/+``tool_result`` (never ``user``), so merging them inline can't fabricate turns —+their tool calls land in the enclosing turn, which is what we want: a sub-agent's+work belongs to the turn that spawned it.++# Tokens and cost++Kiro bills in CREDITS, not tokens: ``usage_summary`` events carry+``promptTurnSummaries[].usage`` with ``unit: "credit"``, and no prompt/completion+counts exist anywhere in the transcript. So per-turn token attrs stay 0 (same as+Cursor's no-native-usage default) and the session token/cost attrs are+deliberately NOT stamped - an absent key means "no data" when spans are+aggregated, whereas a 0 would assert the session genuinely billed nothing.+The credit total lands on the root span as ``session.kiro.total_credits``+for a future credit→USD conversion; nothing consumes it yet.++Kiro records no model name either, so ``llm.model_name`` is "" throughout.+"""++from __future__ import annotations++from datetime import UTC, datetime+import json+import logging++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._paths import basename as path_basename+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ parse_jsonl_records,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++# input.value / output.value truncation, matching every other local parser.+_TRUNCATE = 2000++# Raw -> canonical tool names live in the shared table (tool_taxonomy.py).+_TOOL_ALIASES: dict[str, str] = aliases_for("kiro")+++def parse_kiro(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a synthesized Kiro NDJSON transcript into a span tree.++ Args:+ data: raw NDJSON bytes — `kiro_session` header line, then event lines.+ trace_id: the source-prefixed session id (e.g. `local:kiro:<session-id>`).+ user_id: identifier to stash on the root span's `user.id`.+ project_name: project name resolved by `LocalSource` (from the header's+ `workspacePaths[0]`); derived from that path here when not given.++ Returns:+ `(trace, all_spans)` with the trace's `spans` matching the list. Empty+ when the header is missing/malformed or there are no events —+ `LocalSource` already skips indexing such a file (see+ `_index_kiro_file`), so this is a defensive fallback for direct callers.+ """+ header, events = _parse_ndjson(data)+ if header is None or not events:+ now = datetime.now(UTC)+ return TraceData(trace_id=trace_id, start_time=now, end_time=now), []++ cwd = _header_cwd(header)+ if not project_name and cwd:+ project_name = path_basename(cwd) or None++ session_start = _iso_to_dt(header.get("createdAt"))+ session_end = _iso_to_dt(header.get("lastModifiedAt"))+ # Fall back to the event stream when the header's stamps are absent/junk —+ # the events are the source of truth for when work actually happened.+ event_times = [t for t in (_iso_to_dt(e.get("timestamp")) for e in events) if t is not None]+ if session_start is None:+ session_start = event_times[0] if event_times else datetime.now(UTC)+ if session_end is None or session_end < session_start:+ session_end = event_times[-1] if event_times else session_start+ if session_end < session_start:+ session_end = session_start++ root_id = f"{trace_id}:root"+ all_spans: list[SpanData] = []+ # toolCallId -> (tool_call payload, owning turn's span_id, call time).+ pending_calls: dict[str, tuple[dict, str, datetime, dict | None]] = {}++ turn_num = 0+ turn: SpanData | None = None+ turn_output_parts: list[str] = []+ interrupts_total = 0+ interrupts_during_tool = 0+ total_credits = 0.0+ seen_unrecognised: set[tuple[str, str]] = set()++ def _close_turn() -> None:+ nonlocal turn, turn_output_parts+ if turn is not None:+ turn.attributes["output.value"] = "\n".join(turn_output_parts)[:_TRUNCATE]+ # Flush this turn's still-open tool calls as dangling spans (no result —+ # session/turn ended mid-call; the call's own status decides OK vs ERROR)+ # and clear the map. Clearing per-turn is what keeps the `turn_end`+ # during-tool-use interrupt check accurate: a dangling call from an+ # earlier turn must not make a later cancelled turn look mid-tool.+ for call_payload, tool_turn_id, call_ts, call_event in pending_calls.values():+ dangling = _build_tool_span(+ trace_id, tool_turn_id, call_payload, None, call_ts, call_ts+ )+ dangling.attributes.update(source_attrs(call_event))+ all_spans.append(dangling)+ pending_calls.clear()+ turn = None+ turn_output_parts = []++ def _open_turn(ts: datetime, input_value: str = "", src: dict | None = None) -> SpanData:+ nonlocal turn_num, turn+ turn_num += 1+ turn = SpanData(+ span_id=f"{trace_id}:turn:{turn_num}",+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=ts,+ end_time=ts,+ attributes={+ "input.value": input_value[:_TRUNCATE],+ "output.value": "",+ # Kiro records the workspace once on the header, not per event,+ # so every turn carries the same cwd - mirrors Codex/Cursor.+ "cwd": cwd,+ # Kiro bills credits and reports no token counts — these stay 0,+ # matching Cursor's no-native-usage default (see module docstring).+ "llm.token_count.prompt": 0,+ "llm.token_count.completion": 0,+ "llm.token_count.total_billed_prompt": 0,+ "llm.token_count.input_fresh": 0,+ "llm.token_count.cache_read": 0,+ "llm.token_count.cache_write": 0,+ # Kiro's transcript never names the model.+ "llm.model_name": "",+ },+ )+ turn.attributes.update(source_attrs(src))+ all_spans.append(turn)+ return turn++ prev_ts = session_start+ for event in events:+ payload = event.get("payload")+ if not isinstance(payload, dict):+ continue+ ptype = payload.get("type")+ ts = _iso_to_dt(event.get("timestamp")) or prev_ts+ prev_ts = ts++ if ptype == "user":+ _close_turn()+ content = payload.get("content")+ _open_turn(ts, content if isinstance(content, str) else "", event)+ continue++ if ptype == "turn_end":+ if payload.get("stopReason") == "cancelled":+ interrupts_total += 1+ # A cancel with tool calls still awaiting results is an+ # interrupt DURING tool use, counted separately.+ if pending_calls:+ interrupts_during_tool += 1+ if turn is not None:+ turn.end_time = ts+ continue++ if ptype == "usage_summary":+ summaries = payload.get("promptTurnSummaries")+ if isinstance(summaries, list):+ for summary in summaries:+ if isinstance(summary, dict):+ usage = summary.get("usage")+ # `bool` is an int subclass, so it passes a plain+ # numeric check while `_as_float` deliberately returns+ # 0.0 for it. Treat it as non-numeric here or a+ # malformed `usage: true` is counted as zero silently.+ if usage is not None and (+ isinstance(usage, bool) or not isinstance(usage, int | float)+ ):+ # A non-numeric usage value is coerced to 0.0 by+ # _as_float below, under-counting credits with+ # nothing to show for it.+ key = ("usage_summary", type(usage).__name__)+ if key not in seen_unrecognised:+ seen_unrecognised.add(key)+ logger.debug(+ "session %s: usage_summary usage value has "+ "non-numeric type %s; counted as 0 credits",+ trace_id,+ type(usage).__name__,+ )+ total_credits += _as_float(usage)+ continue++ if ptype not in ("assistant", "tool_call", "tool_result"):+ # pending_interaction / session_metadata / session_event / sub_agent_*+ # are dropped on purpose and appear in ordinary sessions, so warning+ # on them means every session logs a warning nobody should act on.+ # A genuinely NEW vendor ptype is the one worth naming.+ if _is_intentionally_ignored_ptype(ptype):+ continue+ key = ("ptype", str(ptype))+ if key not in seen_unrecognised:+ seen_unrecognised.add(key)+ logger.debug(+ "session %s: kiro event has unrecognised payload type %r; record dropped",+ trace_id,+ ptype,+ )+ continue++ if turn is None:+ # Agent-initiated activity before any user message still needs a+ # turn to live under (same fallback as cursor_store.py).+ _open_turn(ts, "", event)+ assert turn is not None # for type checkers; _open_turn always sets it+ turn.end_time = ts++ if ptype == "assistant":+ content = payload.get("content")+ if isinstance(content, str) and content:+ turn_output_parts.append(content)+ elif ptype == "tool_call":+ call_id = payload.get("toolCallId")+ if isinstance(call_id, str) and call_id:+ pending_calls[call_id] = (payload, turn.span_id, ts, event)+ elif ptype == "tool_result":+ call_id = payload.get("toolCallId")+ call_payload, tool_turn_id, call_ts, call_event = pending_calls.pop(+ call_id if isinstance(call_id, str) else "",+ (None, turn.span_id, ts, None),+ )+ tool_span = _build_tool_span(trace_id, tool_turn_id, call_payload, payload, call_ts, ts)+ # anchored to the line that requested the call (the+ # result line when the call was never seen).+ tool_span.attributes.update(source_attrs(call_event or event))+ all_spans.append(tool_span)+ _close_turn()++ session_signals = {+ # Kiro has no slash commands or skills; the keys stay present so+ # readers see "none used", not "unknown".+ "slash_commands": [],+ "skills_used": [],+ "interrupts": {"total": interrupts_total, "during_tool_use": interrupts_during_tool},+ }++ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "user.id": user_id or "",+ # Kiro's transcript never names the model, so provider/cost+ # attribution in session.py finds "" and skips — deliberate.+ "llm.model_name": "",+ "session.id": trace_id,+ "project.name": project_name or "",+ "harness.agent_session_id": str(header.get("id") or ""),+ "harness.session_signals": json.dumps(session_signals),+ # Kiro's billing unit. Carried so a future credit->USD rate can use+ # it; no consumer reads this yet, and session.cost_usd is+ # deliberately NOT stamped (we don't know the dollar value).+ "session.kiro.total_credits": total_credits,+ "session.kiro.agent_mode": str(header.get("agentMode") or ""),+ "session.kiro.autopilot": bool(header.get("autopilot")),+ "session.kiro.spec_workflow": str(header.get("specWorkflow") or ""),+ },+ )+ all_spans.insert(0, root_span)++ trace = TraceData(+ trace_id=trace_id,+ start_time=session_start,+ end_time=session_end,+ spans=all_spans,+ )+ return trace, all_spans+++def _build_tool_span(+ trace_id: str,+ turn_id: str,+ call: dict | None,+ result: dict | None,+ start: datetime,+ end: datetime,+) -> SpanData:+ """One tool_call/tool_result pair -> a tool span.++ Tool names are aliased to the canonical vocabulary via `_TOOL_ALIASES`+ (unknown names pass through). Args are normalized so the shared+ `file_paths.py` extractor — which only matches a `file_path` key — finds+ Kiro's touched file, same approach `cursor_store.py` takes for its+ `path`/`paths` keys.++ A call is an ERROR when Kiro marked the call `status: "failed"` or the+ result reported `success: false`.+ """+ raw_name = (call or {}).get("toolName")+ raw_name = raw_name if isinstance(raw_name, str) and raw_name else "unknown"+ tool_name = _TOOL_ALIASES.get(raw_name, raw_name)++ args = (call or {}).get("args", {})+ if isinstance(args, dict):+ args = _normalize_file_path_arg(args)+ if raw_name in {"fs_write", "fsWrite"} and "content" not in args and "text" in args:+ args = {**args, "content": args["text"]}+ input_value = args if isinstance(args, str) else json.dumps(args)++ output_value = ""+ is_error = (call or {}).get("status") == "failed"+ if result is not None:+ raw_result = result.get("content", "")+ output_value = raw_result if isinstance(raw_result, str) else json.dumps(raw_result)+ if result.get("success") is False:+ is_error = True++ call_id = (call or {}).get("toolCallId") or f"{turn_id}:{start.isoformat()}"+ return SpanData(+ span_id=f"{trace_id}:tool:{call_id}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=tool_name,+ span_kind="CHAIN",+ status_code=(+ "ERROR"+ if is_error+ else "OK"+ if isinstance(result, dict) and result.get("success") is True+ else "UNSET"+ ),+ start_time=start,+ end_time=end,+ attributes={+ "tool.name": tool_name,+ "code.edit_evidence": extract_edit_evidence(+ tool_name,+ input_value,+ successful=isinstance(result, dict)+ and result.get("success") is True+ and not is_error,+ ),+ "input.value": input_value[:_TRUNCATE],+ "output.value": output_value[:_TRUNCATE],+ },+ )+++def _normalize_file_path_arg(args: dict) -> dict:+ """Alias Kiro's `path`/`paths` arg keys to `file_path`.++ Kiro's read/edit/write tools+ (`read_file`, `fs_write`, `fs_append`, `str_replace`, `list_directory`) key+ the touched file as `"path"`; `read_files` keys it as a `"paths"` list.+ `file_paths.py`'s shared extractor only matches `"file_path"`, so the+ translation happens here rather than widening the shared module — the same+ call `cursor_store.py::_normalize_file_path_arg` makes.++ Purely additive: only fills `file_path` when absent, never mutates or+ removes the original key. `execute_bash`'s `command` is left untouched,+ matching how Claude's `Bash` calls get no `file_path`.++ Args:+ args: The tool call's raw `args` dict (already confirmed a dict).++ Returns:+ `args` unchanged, or a shallow copy with `file_path` added.+ """+ if "file_path" in args:+ return args+ path = args.get("path")+ if isinstance(path, str) and path:+ return {**args, "file_path": path}+ paths = args.get("paths")+ if isinstance(paths, list) and paths and isinstance(paths[0], str) and paths[0]:+ return {**args, "file_path": paths[0]}+ return args+++def _header_cwd(header: dict) -> str:+ """The session's workspace root — `workspacePaths[0]`, or "" when absent.++ Machine-independent (Kiro records the real workspace path the developer had+ open), so it survives copying and drives project_name + the repo resolver,+ same as every other agent's cwd.+ """+ paths = header.get("workspacePaths")+ if isinstance(paths, list) and paths:+ first = paths[0]+ if isinstance(first, str) and first:+ return first.rstrip("/")+ return ""+++def _parse_ndjson(data: bytes) -> tuple[dict | None, list[dict]]:+ """Split the transcript into `(header, events)`.++ Line 1 must be the `kiro_session` header; every subsequent dict with a+ `payload` is an event. Malformed/absent header -> `(None, [])`.+ """+ lines = parse_jsonl_records(data) # source anchors on every event+ if not lines or lines[0].get("type") != "kiro_session":+ return None, []++ header, rest = lines[0], lines[1:]+ events = [e for e in rest if isinstance(e.get("payload"), dict)]+ # The materializer writes these timestamp-sorted; don't trust it - turn assembly+ # depends on order, and a hand-edited or re-merged file could drift.+ events.sort(key=lambda e: str(e.get("timestamp") or ""))+ return header, events+++def _iso_to_dt(value: object) -> datetime | None:+ """ISO-8601 string (e.g. `"2026-07-17T07:38:01.179Z"`) -> aware UTC datetime.++ Returns None when missing/unparsable. A naive result is assumed UTC,+ matching how Kiro writes them.+ """+ if not isinstance(value, str) or not value:+ return None+ try:+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return dt.astimezone(UTC)+++# Kiro payload types this parser drops ON PURPOSE. Prefix matching because Kiro+# versions the sub_agent_* family independently, and a new member of a known+# inert family is not the vendor change this warning is looking for.+_IGNORED_PTYPE_PREFIXES = (+ "pending_interaction",+ "session_metadata",+ "session_event",+ "sub_agent_",+)++# Exact types, not families. Everything in the tuple above names a prefix Kiro+# really does expand (`sub_agent_started`, `session_event_*`), but a type that is+# a whole name on its own has to match exactly: as a prefix, `turn_start` would+# also swallow a future `turn_start_v2`, and silently dropping a vendor addition+# is the failure these warnings exist to catch.+_IGNORED_PTYPES = frozenset(+ {+ # The opening marker of every turn, carrying only an executionId;+ # `turn_end` above is the one that has something to say. It appears in+ # ordinary well-formed sessions, so warning about it means warning+ # once per session about ordinary traffic, and a warning people+ # always see is a warning people mute.+ "turn_start",+ }+)+++def _is_intentionally_ignored_ptype(ptype: object) -> bool:+ """True when this payload type is a known inert family, not a new one."""+ if not isinstance(ptype, str):+ return False+ return ptype in _IGNORED_PTYPES or ptype.startswith(_IGNORED_PTYPE_PREFIXES)+++def _as_float(value: object) -> float:+ """Coerce a credit-usage field to a non-negative float (0.0 on junk)."""+ if isinstance(value, bool):+ return 0.0+ if isinstance(value, int | float):+ return max(0.0, float(value))+ return 0.0+++__all__ = ["parse_kiro"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/opencode.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/opencode.pynew file mode 100644index 0000000..8b7234d--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/parsers/opencode.py@@ -0,0 +1,461 @@+"""Parse an opencode session (materialized NDJSON) into the universal SpanData shape.++opencode (sst/opencode) has no per-session file - it stores sessions in a SQLite db. Discovery+materializes each session into NDJSON, one record per message:++ {"id": <msgId>, "sessionID": <sid>, "message": {...}, "parts": [{...}, ...]}++``message`` carries ``role`` and, on assistants, ``modelID`` / ``tokens`` / ``path.cwd``. ``parts``+are the content units (``type``: ``text`` | ``reasoning`` | ``tool`` | ``step-start`` |+``step-finish`` | ...). We bracket user→assistant into turns and emit a root Session span plus+per-turn Turn spans plus per-tool tool spans — the same shape the Claude Code / Codex parsers+emit, so downstream code never branches on agent.+"""++from __future__ import annotations++from datetime import UTC, datetime+import json+import logging++from agentplay._core.code_authorship import extract_edit_evidence+from agentplay._core.ingestion.coding_agent._paths import basename as path_basename+from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ SOURCE_KIND_SQLITE,+ as_count,+ as_dict,+ drop_untyped,+ parse_jsonl_records,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData, TraceData+from agentplay._core.ingestion.coding_agent.tool_taxonomy import aliases_for++logger = logging.getLogger(__name__)++# Raw -> canonical tool names live in the shared table (tool_taxonomy.py).+_TOOL_ALIASES: dict[str, str] = aliases_for("opencode")+++def _source_attrs(record: dict | None) -> dict:+ """``source_attrs(record, kind="sqlite")`` minus the offset.++ opencode sessions are re-materialized from SQLite into NDJSON fresh on+ every parse (see the module docstring) — the NDJSON byte offset+ ``parse_jsonl_records`` stamps on a record is a position in that+ throwaway intermediate, not a stable transcript location, and would+ drift across re-parses if kept. ``kind="sqlite"`` (content hash+ only) matches ``cursor_store.py``'s own rewritten-store anchor.+ """+ # the message id IS the addressable key in the re-materialized+ # store — the row cursor a seek can find again, unlike the throwaway+ # NDJSON offset. It is part of the record already, so the hash is unchanged.+ msg_id = record.get("id") if isinstance(record, dict) else None+ return {+ k: v+ for k, v in source_attrs(+ record,+ kind=SOURCE_KIND_SQLITE,+ row_cursor=msg_id if isinstance(msg_id, str) and msg_id else None,+ ).items()+ if k != "source.byte_offset"+ }+++def parse_opencode(+ data: bytes,+ trace_id: str,+ user_id: str | None = None,+ project_name: str | None = None,+) -> tuple[TraceData, list[SpanData]]:+ """Parse a materialized opencode NDJSON transcript into a span tree."""+ records = _parse_jsonl(data)+ if not records:+ now = datetime.now(UTC)+ return TraceData(trace_id=trace_id, start_time=now, end_time=now), []++ turns = _group_into_turns(records)++ # Session-level cwd/model: first assistant path.cwd / modelID we see.+ # opencode's native session id rides on every record as `sessionID`+ # (capital ID); no version field exists anywhere in the format.+ cwd = ""+ model_name = ""+ agent_session_id = ""+ for rec in records:+ msg = rec.get("message") or {}+ if not cwd:+ cwd = (msg.get("path") or {}).get("cwd") or ""+ if not model_name and msg.get("modelID"):+ model_name = msg["modelID"]+ if not agent_session_id and rec.get("sessionID"):+ agent_session_id = rec["sessionID"]+ if cwd and model_name and agent_session_id:+ break++ if not project_name and cwd:+ project_name = path_basename(cwd)++ all_ts = [ts for rec in records if (ts := _created(rec.get("message") or {}))]+ if all_ts:+ session_start, session_end = min(all_ts), max(all_ts)+ else:+ session_start = session_end = datetime.now(UTC)++ all_spans: list[SpanData] = []+ root_id = f"{trace_id}:root"++ for turn_num, turn in enumerate(turns, 1):+ turn_id = f"{trace_id}:turn:{turn_num}"+ turn_start = turn.get("start") or session_start+ turn_end = turn.get("end") or turn_start++ turn_span = SpanData(+ span_id=turn_id,+ trace_id=trace_id,+ parent_id=root_id,+ name=f"Turn {turn_num}",+ span_kind="CHAIN",+ status_code="OK",+ start_time=turn_start,+ end_time=turn_end,+ attributes={+ "input.value": turn.get("user_query", "")[:2000],+ "output.value": turn.get("assistant_text", "")[:2000],+ "cwd": turn.get("cwd") or cwd or "",+ # opencode reports fresh input, output, reasoning, and cache read/write+ # separately (input + output + reasoning + cache == total). Normalize to the+ # same attribute shape the Claude/Codex parsers use.+ "llm.token_count.prompt": turn.get("prompt", 0),+ "llm.token_count.completion": turn.get("completion", 0),+ "llm.token_count.input_fresh": turn.get("input_fresh", 0),+ "llm.token_count.cache_read": turn.get("cache_read", 0),+ "llm.token_count.cache_write": turn.get("cache_write", 0),+ "llm.model_name": turn.get("model") or model_name,+ },+ )+ turn_span.attributes.update(_source_attrs(turn.get("_src")))+ all_spans.append(turn_span)++ for tool in turn.get("tools", []):+ all_spans.append(+ SpanData(+ span_id=f"{trace_id}:tool:{tool['call_id']}",+ trace_id=trace_id,+ parent_id=turn_id,+ name=tool["name"],+ span_kind="CHAIN",+ status_code=(+ "ERROR"+ if tool.get("is_error")+ else "OK"+ if tool.get("completed")+ else "UNSET"+ ),+ start_time=tool.get("start") or turn_start,+ end_time=tool.get("end") or turn_end,+ attributes={+ "tool.name": tool["name"],+ "code.edit_evidence": tool["edit_evidence"],+ "input.value": tool.get("input", "")[:2000],+ **{+ key: tool[key]+ for key in (+ "pr.create.provider",+ "pr.create.capture",+ "pr.create.repository",+ "pr.create.requested_repository",+ "pr.create.command_sha256",+ "pr.create.output_url",+ )+ if key in tool+ },+ "output.value": tool.get("output", "")[:2000],+ **_source_attrs(tool.get("_src")),+ },+ )+ )++ # Session model = last model actually used (handles mid-session switches).+ session_model = next((t["model"] for t in reversed(turns) if t.get("model")), model_name)++ root_span = SpanData(+ span_id=root_id,+ trace_id=trace_id,+ parent_id=None,+ name="Session",+ span_kind="CHAIN",+ status_code="OK",+ start_time=session_start,+ end_time=session_end,+ attributes={+ "user.id": user_id or "",+ "llm.model_name": session_model,+ "session.id": trace_id,+ "project.name": project_name or "",+ "harness.agent_session_id": agent_session_id,+ },+ )+ all_spans.insert(0, root_span)++ trace = TraceData(+ trace_id=trace_id, start_time=session_start, end_time=session_end, spans=all_spans+ )+ return trace, all_spans+++def _parse_jsonl(data: bytes) -> list[dict]:+ """every record carries the shared source anchors (offset + hash).++ A retyped field reads as absent (see :func:`drop_untyped`) instead of raising+ later and losing the whole session.+ """+ records = parse_jsonl_records(data)+ for rec in records:+ drop_untyped(rec, ("message",), dict)+ drop_untyped(rec, ("parts",), list)+ msg = rec.get("message")+ if msg is not None:+ drop_untyped(msg, ("time", "path", "tokens", "model"), dict)+ drop_untyped(msg, ("modelID",), str)+ drop_untyped(as_dict(msg.get("path")), ("cwd",), str)+ drop_untyped(as_dict(msg.get("tokens")), ("cache",), dict)+ for part in rec.get("parts", ()):+ if isinstance(part, dict):+ drop_untyped(part, ("state", "tokens"), dict)+ drop_untyped(part, ("text",), str)+ state = part.get("state")+ if state is not None:+ drop_untyped(state, ("time",), dict)+ drop_untyped(as_dict(part.get("tokens")), ("cache",), dict)+ return records+++def _created(message: dict) -> datetime | None:+ return _epoch_ms((message.get("time") or {}).get("created"))+++def _epoch_ms(ms) -> datetime | None:+ try:+ return datetime.fromtimestamp(int(ms) / 1000, tz=UTC)+ except (TypeError, ValueError, OSError, OverflowError):+ return None+++def _text_of(parts: list, kinds: tuple[str, ...]) -> str:+ return "\n".join(+ p["text"] for p in parts if isinstance(p, dict) and p.get("type") in kinds and p.get("text")+ )+++def _new_turn(msg: dict, parts: list, created: datetime | None, src: dict | None = None) -> dict:+ model = msg.get("modelID")+ if not model and isinstance(msg.get("model"), dict):+ model = msg["model"].get("modelID")+ return {+ "_src": src, # the record that opened the turn+ "user_query": _text_of(parts, ("text",)),+ "assistant_text": "",+ "start": created,+ "end": created,+ "prompt": 0,+ "completion": 0,+ "input_fresh": 0,+ "cache_read": 0,+ "cache_write": 0,+ "tools": [],+ "model": model,+ "cwd": (msg.get("path") or {}).get("cwd") or "",+ }+++def _group_into_turns(records: list[dict]) -> list[dict]:+ """Bracket messages into turns: a user message opens a turn; assistant messages fold in."""+ turns: list[dict] = []+ current: dict | None = None+ # Dedup so a vendor rename doesn't flood the log: one warning per distinct+ # (session, bad value) pair, not one per record.+ seen_unknown_roles: set[tuple[str, str]] = set()+ seen_finish_shapes: set[tuple[str, str]] = set()++ for rec in records:+ msg = rec.get("message") or {}+ role = msg.get("role")+ parts = rec.get("parts") or []+ created = _created(msg)+ session_id = rec.get("sessionID") or "<unknown>"++ if role == "user":+ if current:+ turns.append(current)+ current = _new_turn(msg, parts, created, rec)+ elif role == "assistant":+ if current is None:+ current = _new_turn({}, [], created, rec)+ text = _text_of(parts, ("text",))+ if text:+ current["assistant_text"] = (+ f"{current['assistant_text']}\n{text}" if current["assistant_text"] else text+ )+ if msg.get("modelID"):+ current["model"] = msg["modelID"]+ if not current.get("cwd"):+ current["cwd"] = (msg.get("path") or {}).get("cwd") or ""+ _fold_tokens(+ current,+ msg.get("tokens") or _step_finish_tokens(parts, session_id, seen_finish_shapes),+ )+ for part in parts:+ if isinstance(part, dict) and part.get("type") == "tool":+ tool = _tool_from_part(part, created)+ tool["_src"] = rec # the record that carried the call+ current["tools"].append(tool)+ if created:+ current["end"] = created+ else:+ # A role opencode never documented (user/assistant only) drops the+ # whole record, tokens included, with nothing else to show for it.+ # str() collapses values a reader would not: 1 and "1" stringify+ # alike, so the second malformed role would drop with no warning.+ key = (session_id, type(role).__name__, repr(role))+ if key not in seen_unknown_roles:+ seen_unknown_roles.add(key)+ logger.debug(+ "session %s: opencode message has unrecognised role %r; record dropped",+ session_id,+ role,+ )++ if current:+ turns.append(current)+ return turns+++def _step_finish_tokens(+ parts: list, session_id: str = "<unknown>", seen: set[tuple[str, str]] | None = None+) -> dict | None:+ for part in parts:+ if isinstance(part, dict) and part.get("type") == "step-finish" and part.get("tokens"):+ return part["tokens"]+ # The `step-finish` part is opencode's ONLY source of per-turn tokens when+ # the assistant message itself carries no `tokens` field. If the vendor+ # renames the part's `type` (or restructures it) while still shipping a+ # `tokens` payload under some other type, this loop would otherwise+ # silently zero the turn's tokens with no trace at all.+ for part in parts:+ if isinstance(part, dict) and part.get("tokens") and part.get("type") != "step-finish":+ ptype = part.get("type")+ # Same collision as the unknown-role key above: type plus repr, so+ # 1 and "1" are each named once.+ key = (session_id, type(ptype).__name__, repr(ptype))+ if seen is not None and key not in seen:+ seen.add(key)+ logger.debug(+ "session %s: opencode part type %r carries tokens but is not "+ "'step-finish'; turn tokens from this part are dropped",+ session_id,+ ptype,+ )+ return None+++def _fold_tokens(turn: dict, tokens: dict | None) -> None:+ if not tokens:+ return+ cache = as_dict(tokens.get("cache"))+ fresh = as_count(tokens.get("input"))+ cache_read = as_count(cache.get("read"))+ cache_write = as_count(cache.get("write"))+ turn["input_fresh"] += fresh+ turn["cache_read"] += cache_read+ turn["cache_write"] += cache_write+ turn["prompt"] += fresh + cache_read + cache_write+ turn["completion"] += as_count(tokens.get("output")) + as_count(tokens.get("reasoning"))+++def _tool_from_part(part: dict, created: datetime | None) -> dict:+ """One `tool`-type part -> the parser's intermediate tool dict.++ Tool names are canonicalized to the Claude-cased vocabulary via+ `_TOOL_ALIASES` here — the span builder stamps `name` on both the span+ name and `tool.name`, matching cursor_store.py (which also doesn't keep+ the raw name). Dict args are normalized (see `_normalize_file_path_arg`)+ so the shared `file_paths.py` extractors - which only ever match+ a snake_case `"file_path"` key, on purpose — find opencode's camelCase+ `filePath` too. Both quirks stay confined to this parser instead of+ widening the shared modules.+ """+ state = part.get("state") or {}+ raw_name = part.get("tool") or part.get("name") or "tool"+ if not isinstance(raw_name, str):+ raw_name = "unknown"+ name = _TOOL_ALIASES.get(raw_name, raw_name)+ tool_input = state.get("input", part.get("input"))+ if isinstance(tool_input, dict):+ tool_input = _normalize_file_path_arg(tool_input)+ if isinstance(tool_input, dict | list):+ tool_input = json.dumps(tool_input)+ command_attrs = creation_command_attributes(tool_input, name)+ return {+ "call_id": part.get("callID") or part.get("id") or name,+ "name": name,+ "input": str(tool_input or "")[:2000],+ **command_attrs,+ **creation_output_attributes(+ (state.get("output") or "") if state.get("status") == "completed" else "",+ command_attrs.get("pr.create.provider"),+ command_attrs.get("pr.create.repository"),+ ),+ "edit_evidence": extract_edit_evidence(+ "apply_patch" if raw_name == "patch" else name,+ tool_input,+ successful=state.get("status") == "completed",+ ),+ "output": str(state.get("output") or "")[:2000],+ "is_error": state.get("status") == "error",+ "completed": state.get("status") == "completed",+ "start": _epoch_ms((state.get("time") or {}).get("start")) or created,+ "end": _epoch_ms((state.get("time") or {}).get("end")) or created,+ }+++def _normalize_file_path_arg(args: dict) -> dict:+ """Alias opencode's camelCase `filePath` arg key to `file_path`.++ opencode's read/edit/write args key+ the touched file as `"filePath"`, but the shared files-touched+ extractors (file_paths.py) match only the snake_case+ `"file_path"`/`"notebook_path"` keys — deliberately narrow so every+ parser translates its own quirk at the boundary (same contract+ `cursor_store._normalize_file_path_arg` honors for Cursor's+ `path`/`paths`).++ Only fills `file_path` when it's absent, and never mutates/removes the+ original key — purely additive. Unlike the Cursor version, the added+ key goes FIRST, not last: opencode edit args carry large+ `oldString`/`newString` blobs and `input.value` truncates at 2000+ chars, so a trailing `file_path` would routinely be cut off. `grep`/+ `glob`'s `"path"` arg names a search DIRECTORY here, not a file, so —+ unlike Cursor, where `path` is the touched file — it is deliberately+ left unmapped rather than fabricating a `file_path` from it.++ Args:+ args: The tool part's raw input dict (already confirmed a dict by+ the caller).++ Returns:+ `args` unchanged, or a shallow copy with `file_path` prepended.+ """+ if "file_path" in args:+ return args+ file_path = args.get("filePath")+ if isinstance(file_path, str) and file_path:+ return {"file_path": file_path, **args}+ return args+++__all__ = ["parse_opencode"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.py b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.pynew file mode 100644index 0000000..045bff5--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/_sources/local/source.py@@ -0,0 +1,2397 @@+"""Local filesystem source — walks ~/.claude / ~/.codex / Copilot dirs.++Indexes JSONL session files under per-agent homes, detects the agent+from the file head, and emits the universal `SpanData` shape via the+matching parser. Multi-agent by design — drop a Codex session next to+a Claude Code session in the same home and the index picks both up.+"""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass+from datetime import UTC, datetime+import hashlib+import json+import logging+import os+from pathlib import Path+import re+from typing import Any++from agentplay._core.ingestion.coding_agent._paths import to_posix+from agentplay._core.ingestion.coding_agent._sources._base import (+ MAX_SESSION_BYTES,+ OversizedSessionError,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers import (+ AgentType,+ detect_agent,+ parse_claude_code,+ parse_codex,+ parse_copilot,+ parse_copilot_vscode,+ parse_cursor_agent_transcript,+ parse_cursor_store,+ parse_kiro,+ parse_opencode,+)+from agentplay._core.ingestion.coding_agent.spans import DiscoveredSession, SpanData++logger = logging.getLogger(__name__)+++@dataclass(slots=True, frozen=True)+class ManifestIdentity:+ """The identity block from an optional identity stamp file under+ `<home>/_manifest/`. Used to detect transcripts that belong to more+ than one owner.++ Every field is optional because the stamp may carry only partial+ data; consumers degrade gracefully when a field is absent.+ """++ user_uuid: str | None+ org_uuid: str | None+ org_name: str | None+ email: str | None+ display_name: str | None+ github_username: str | None++ @classmethod+ def from_manifest_block(cls, block: dict | None) -> ManifestIdentity | None:+ """Parse the identity block. Empty / shape-wrong → None."""+ if not isinstance(block, dict):+ return None+ identity = cls(+ user_uuid=_str_or_none(block.get("user_uuid")),+ org_uuid=_str_or_none(block.get("org_uuid")),+ org_name=_str_or_none(block.get("org_name")),+ email=_str_or_none(block.get("email")),+ display_name=_str_or_none(block.get("name")),+ github_username=_str_or_none(block.get("github_username")),+ )+ # All-None means nothing to attribute to — treat as absent.+ if not any(+ (+ identity.user_uuid,+ identity.email,+ identity.github_username,+ identity.display_name,+ )+ ):+ return None+ return identity+++def _index_put(+ index: dict[str, _FileRef],+ session_id: str,+ ref: _FileRef,+ newest: dict[str, datetime],+) -> None:+ """Insert ``ref`` under ``session_id``, keeping the richer file on a collision.++ One session legitimately appears under two copy prefixes. A copied transcript tree+ may include a hostname directory, and macOS renames a machine whenever+ the network changes (``Foo.local`` -> ``Foo.lan``, or a lowercase+ ``mac`` fallback), so the same transcript uuid lands under two hostnames and+ both get walked into this index.++ A plain ``index[session_id] = ref`` would let the home visited LAST win,+ and since the walker is fed ``sorted(...)``, the winner would be decided by+ hostname spelling. A stale copy could then beat a fresher, larger one, and+ because the stale copy's content hash never changes, every later scan would+ skip the session as "unchanged".++ Transcripts are append-only, so byte SIZE is the honest "more complete"+ signal; ``mtime`` only breaks a size tie, because a re-copy (redaction, a+ new hostname prefix) rewrites mtime without adding content.++ Args:+ index: The ``session_id -> _FileRef`` map being built; mutated in place.+ session_id: Namespaced id, e.g. ``local:claude-code:<uuid>``.+ ref: Candidate pointer for this session.+ newest: ``session_id -> newest mtime seen`` across ALL candidates.+ Recorded here, applied to the winner only after the whole walk by+ :func:`_carry_collision_mtimes`. It must NOT be folded into the+ winner during selection: with three copies, a smaller-but-newer+ loser would raise the incumbent's mtime, and the next equal-sized+ candidate would then be compared against that synthetic timestamp+ and could lose despite being genuinely fresher.++ Side effects:+ Logs a warning naming both paths whenever a collision is resolved, so a+ duplicated copy prefix is visible rather than silent.+ """+ incumbent = index.get(session_id)++ def _is_narrative(candidate: _FileRef) -> bool:+ return candidate.subformat == "agent_transcript"++ # Recency bookkeeping, decided BEFORE the winner is picked because the two+ # answers differ.+ #+ # `_carry_collision_mtimes` gives each winner the newest mtime seen across+ # its duplicates, which is right when the files are two copies of one thing+ # (a re-copy really is fresher). It is wrong for a Cursor narrative/store+ # pair: only the store cache is stamped with the session's real activity+ # time, so folding in a narrative's filesystem clock re-dates an old session+ # as current and drags the newest-seen timestamp forward.+ #+ # So a narrative contributes nothing once a store is present, and the first+ # store DISPLACES whatever narratives contributed. Between two stores the+ # normal max applies, which is what keeps the newer of two duplicate store+ # copies.+ previous = newest.get(session_id)+ if incumbent is not None and _is_narrative(ref) and not _is_narrative(incumbent):+ pass # narrative alongside a store: contributes no recency+ elif previous is None or (+ not _is_narrative(ref) and incumbent is not None and _is_narrative(incumbent)+ ):+ # First ref, or the first store to arrive after narratives — displace.+ newest[session_id] = ref.mtime+ else:+ newest[session_id] = max(previous, ref.mtime)++ if incumbent is None:+ index[session_id] = ref+ return++ def _size(candidate: _FileRef) -> int:+ try:+ return candidate.path.stat().st_size+ except OSError:+ return -1++ new_size, old_size = _size(ref), _size(incumbent)++ # Format DOMINANCE outranks size, for the one case where the two files are+ # not two copies of the same thing.+ #+ # cursor-agent persists each session twice: the `agent-transcripts` narrative+ # (subformat "agent_transcript") and the store.db NDJSON (subformat None).+ # They share a session id, so they collide here. The store shape strictly+ # contains the narrative one — it adds tool RESULTS, billed tokens, the model+ # and real timestamps, all of which the narrative omits entirely. Size cannot+ # express that: a chatty narrative log is often the LARGER file, so the+ # size rule would keep the copy with no tool output and silently undo the+ # whole point of materializing the store (no commit SHAs, no produced edges,+ # no tokens). Prefer the store whenever both exist; the narrative still wins+ # uncontested when no store cache was materialized for that session.+ if _is_narrative(ref) != _is_narrative(incumbent):+ richer, poorer = (incumbent, ref) if _is_narrative(ref) else (ref, incumbent)+ index[session_id] = richer+ # Recency was already settled above, where a narrative contributes+ # nothing and the max between two stores is preserved. Re-pinning it here+ # would discard the newer of two duplicate store copies.+ logger.info(+ "session %s found as both a Cursor narrative and a store transcript; "+ "keeping the store copy (%s) over the narrative (%s) — the narrative "+ "carries no tool results, tokens or model",+ session_id,+ richer.path,+ poorer.path,+ )+ return++ if (new_size, ref.mtime) > (old_size, incumbent.mtime):+ winner, loser, winner_size, loser_size = ref, incumbent, new_size, old_size+ index[session_id] = ref+ else:+ winner, loser, winner_size, loser_size = incumbent, ref, old_size, new_size++ # Severity follows whether anything was actually at risk. A duplicate+ # prefix is overwhelmingly benign: nearly all overlaps are byte-identical+ # re-copies under a renamed host. Warning on every one of those, every run,+ # is noise that trains readers to skim past the ones that matter.+ # Diverging sizes mean a real shadow (a fresher copy was+ # being hidden), which is the only case worth a warning.+ if winner_size != loser_size:+ logger.warning(+ "session %s found under more than one path with DIFFERING sizes; "+ "keeping the larger copy (%d bytes at %s) over %d bytes at %s",+ session_id,+ winner_size,+ winner.path,+ loser_size,+ loser.path,+ )+ else:+ logger.debug(+ "session %s found under more than one path, identical size (%d bytes); keeping %s",+ session_id,+ winner_size,+ winner.path,+ )+++def _carry_collision_mtimes(index: dict[str, _FileRef], newest: dict[str, datetime]) -> None:+ """Give each collided winner the newest mtime seen across its duplicates.++ Time-window filtering compares the ref's mtime, so a larger-but-older copy+ would be selected and then filtered out before parsing, discarding the+ richer bytes. Size decides WHICH FILE to read; recency decides WHETHER+ the session is inside the requested window, and the session was+ demonstrably touched at the latest of its copies' times.++ Applied after the walk rather than during it, so a loser's timestamp can+ never contaminate the comparison key a later candidate is judged against.++ Args:+ index: Finished ``session_id -> _FileRef`` map; winners mutated in place.+ newest: ``session_id -> newest mtime``, as recorded by :func:`_index_put`.+ """+ for session_id, ts in newest.items():+ ref = index.get(session_id)+ if ref is not None and ts > ref.mtime:+ ref.mtime = ts+++def _read_head(+ path: Path,+ *,+ min_lines: int = 20,+ max_bytes: int = 5_000_000,+ stop_when: Callable[[bytes], bool] | None = None,+) -> bytes:+ """Return the head of a JSONL file for cheap metadata sniffing — agent+ detection, cwd, branch.++ Reads whole lines, not a fixed byte slab, so a giant opening record can't+ hide the identifying keys behind a mid-JSON truncation. Newer Claude Code+ builds front-load a multi-MB ``queue-operation`` line (the user's pasted+ context); a fixed 32KB read would cut it mid-object, ``json.loads`` would+ fail on every line, and ``detect_agent`` would return None for a valid+ session. Complete-line reads avoid that.++ ``min_lines`` alone is not a safe stopping rule for agent detection. A line+ budget assumes the identifying record sits near the top, and transcripts+ can open with dozens of metadata records (``queue-operation`` /+ ``file-history-snapshot`` / ``attachment``) before the first ``user`` line,+ so a 64KB chunk can satisfy a line budget well before the marker appears.+ Detection would then see no marker and skip the session. Callers that are+ looking for something specific should say so with ``stop_when`` rather+ than trusting a line count to be generous enough.++ Cost: with ``stop_when`` the read continues past ``min_lines`` until the+ predicate is satisfied or ``max_bytes`` is reached, so a file that never+ satisfies it costs one ``max_bytes`` read instead of one chunk. That is the+ deliberate trade: the alternative is silently discarding a valid session.++ Args:+ path: the JSONL transcript.+ min_lines: keep reading until the buffer holds this many complete lines.+ max_bytes: hard ceiling so a pathological single line can't run away.+ stop_when: optional predicate over the buffer so far. When supplied,+ reading continues past ``min_lines`` until it returns True. Checked+ only after ``min_lines`` is met, so the common case still stops at+ the first chunk.++ Returns:+ The head bytes (may hold fewer than ``min_lines`` lines for short files).+ """+ buf = bytearray()+ newline_count = 0+ # Bytes already offered to ``stop_when``, always on a line boundary. The+ # predicate sees each complete line exactly once: handing it the whole+ # accumulated buffer every chunk is O(n²) on a multi-MB JSONL, the same+ # quadratic trap the newline counter below avoids, one level up.+ scanned_to = 0+ # Absolute offset just past the newest complete line. Derived from each+ # chunk as it arrives: ``buf.rfind`` would rescan the whole accumulated+ # buffer whenever it holds no newline, which is exactly the multi-MB+ # single-line opener this function was written for — O(n²) again, by a+ # different route.+ line_end = 0+ satisfied = stop_when is None+ with open(path, "rb") as fh:+ # Count newlines incrementally per chunk — rescanning the whole buffer+ # each iteration (buf.count) is O(n²) on a multi-MB+ # single-line opener.+ while len(buf) < max_bytes:+ if newline_count >= min_lines and satisfied:+ break+ chunk = fh.read(65536)+ if not chunk:+ break+ newline_count += chunk.count(b"\n")+ chunk_start = len(buf)+ buf += chunk+ last_nl = chunk.rfind(b"\n")+ if last_nl != -1:+ line_end = chunk_start + last_nl + 1+ if not satisfied and line_end > scanned_to:+ # Only whole lines: a record split across the chunk boundary is+ # left for the next pass rather than parsed half-formed.+ if stop_when(bytes(buf[scanned_to:line_end])):+ satisfied = True+ scanned_to = line_end+ return bytes(buf)+++def _agent_detected(buf: bytes) -> bool:+ """``_read_head`` stop predicate for callers that need an agent marker.++ Detection is the reason the head is being read at all, so it is also the+ only honest place to stop reading. A line count cannot know whether the+ identifying record has been seen yet.+ """+ return detect_agent(buf) is not None+++# Record types that carry no conversation: Claude Code session metadata and the+# Cursor end-of-turn marker. A file made only of these has nothing to map.+_NON_CONVERSATION_TYPES = frozenset(+ {+ "agent-name",+ "ai-title",+ "attachment",+ "cost-state",+ "file-history-snapshot",+ "last-prompt",+ "mode",+ "permission-mode",+ "queue-operation",+ "summary",+ "system",+ "turn_ended",+ }+)+++def _is_metadata_only(head: bytes) -> bool:+ """True when every record in ``head`` is a known non-conversation type.++ Deliberately narrow: an unknown ``type``, or a head with no parseable+ record at all, is not metadata-only, so real format drift still reaches the+ "agent detection failed" warning instead of being filed as empty.+ """+ parsed = False+ for line in head.split(b"\n"):+ try:+ rec = json.loads(line)+ except ValueError: # blank, truncated, or split mid-character+ continue+ if not isinstance(rec, dict):+ continue+ kind = rec.get("type")+ if not isinstance(kind, str) or kind not in _NON_CONVERSATION_TYPES:+ return False+ parsed = True+ return parsed+++def _str_or_none(v: object) -> str | None:+ if isinstance(v, str):+ s = v.strip()+ return s or None+ return None+++def _manifest_files(home: Path) -> list[Path]:+ """`<home>/_manifest/*.json`, oldest → newest.++ Ordered by filename - manifests are named with a UTC timestamp+ (`20260702T101500Z.json`), so lexicographic order IS chronological+ order and survives mtime-mangling copies.+ """+ manifest_dir = home / "_manifest"+ if not manifest_dir.is_dir():+ return []+ try:+ return sorted(p for p in manifest_dir.iterdir() if p.is_file() and p.suffix == ".json")+ except OSError:+ return []+++def _all_manifest_bodies(home: Path) -> list[dict]:+ """Every parseable manifest body in the home, oldest → newest.++ Each manifest describes only one batch's sessions - so a fact stamped+ for an old session (its cwd→repo, its repo roots) exists only in an old+ manifest. Readers that need such facts (the repo loaders) must merge+ across all of them, newest-wins per key; reading only the newest+ manifest forgets every prior batch's stamps. Unreadable files+ are skipped (logged), not fatal.+ """+ bodies: list[dict] = []+ for path in _manifest_files(home):+ try:+ body = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ logger.warning("manifest at %s unreadable; skipping it", path)+ continue+ if isinstance(body, dict):+ bodies.append(body)+ return bodies+++def _newest_manifest_body(home: Path) -> dict | None:+ """Parse the newest `<home>/_manifest/*.json`; None if absent/unreadable.++ For stamps where only the LATEST value is meaningful (the identity+ stamp). Facts that accumulate across manifests (cwd_repos,+ repo_roots) go through `_all_manifest_bodies` instead.+ """+ files = _manifest_files(home)+ if not files:+ return None+ newest = files[-1]+ try:+ body = json.loads(newest.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ logger.warning("manifest at %s unreadable; scan falls back to other signals", newest)+ return None+ return body if isinstance(body, dict) else None+++def _load_manifest_identity(home: Path) -> ManifestIdentity | None:+ """Verified user/org identity from the newest manifest's identity block.++ Missing dir / unreadable JSON / absent block → None (callers treat the+ home as having no identity).+ """+ body = _newest_manifest_body(home)+ if body is None:+ return None+ return ManifestIdentity.from_manifest_block(body.get("entelligence"))+++def _load_manifest_repos(home: Path) -> dict[str, str]:+ """Read the manifest's `cwd_repos` map → `{cwd: 'owner/repo'}`.++ Stamped into the manifest, which resolves `git remote` per cwd+ where the repo is live — the only place the owner is knowable for+ copied transcripts. Accepts both the flat `{cwd: 'owner/repo'}` and+ the richer `{cwd: {'repo': ..., 'base': ...}}` shapes. Empty dict+ when no manifest carries the stamp — the repo resolver then falls+ through to its other tiers.++ Merged across ALL the home's manifests (newest wins per cwd): each+ manifest stamps only its own batch's cwds, so an old session's mapping+ lives only in an old manifest - newest-only reading would lose it.+ """+ out: dict[str, str] = {}+ for body in _all_manifest_bodies(home):+ raw = body.get("cwd_repos")+ if not isinstance(raw, dict):+ continue+ for cwd, val in raw.items():+ if isinstance(val, str):+ out[cwd] = val+ elif isinstance(val, dict) and isinstance(val.get("repo"), str):+ out[cwd] = val["repo"]+ return out+++def _load_manifest_repo_roots(home: Path) -> dict[str, str]:+ """`{git_toplevel: 'owner/repo'}` for every repo the home's sessions touched.++ Primary source is the manifest's `repo_roots` map - the git toplevel+ of each repo the sessions' TOOL CALLS touched+ (not just their cwds), so cross-repo edits resolve too. For manifests+ predating that stamp, roots are derived from `cwd_repos`: the rich+ shape's `base` IS a git toplevel, and a flat entry's cwd approximates+ one — partial coverage beats none, and `repo_roots` entries overwrite+ the derived ones when both exist.++ Trailing slashes are stripped so prefix matching is uniform.++ Merged across ALL the home's manifests (newest wins per root, and a+ `repo_roots` stamp beats a cwd-derived fallback within each body):+ each manifest stamps only its own batch's roots, so older sessions'+ roots survive later partial batches.+ """+ out: dict[str, str] = {}+ for body in _all_manifest_bodies(home):+ raw_cwds = body.get("cwd_repos")+ if isinstance(raw_cwds, dict):+ for cwd, val in raw_cwds.items():+ if not isinstance(cwd, str):+ continue+ if isinstance(val, str):+ out[cwd.rstrip("/")] = val+ elif isinstance(val, dict) and isinstance(val.get("repo"), str):+ base = val.get("base")+ root = base if isinstance(base, str) and base else cwd+ out[root.rstrip("/")] = val["repo"]+ raw_roots = body.get("repo_roots")+ if isinstance(raw_roots, dict):+ for root, repo in raw_roots.items():+ if isinstance(root, str) and isinstance(repo, str) and root and repo:+ out[root.rstrip("/")] = repo+ return out+++def _project_from_cc_slug(slug: str) -> str | None:+ """Reconstruct the project name from a Claude Code project slug.++ Claude Code names its project directories `-<path-with-slashes-as-dashes>`.+ Directory names can themselves contain dashes (`my-cool-app`) so a+ straight split loses information; we walk the real filesystem to+ find the actual split points.++ Worktree sub-paths (`--claude-worktrees-*`) are stripped first.+ """+ base = slug.split("--")[0] if "--" in slug else slug++ resolved = _resolve_slug_path(base)+ if resolved:+ return resolved.name++ # Fallback: the last dash-separated component of the slug.+ parts = base.strip("-").split("-")+ last = parts[-1] if parts else None+ return last or None+++def _resolve_slug_path(slug: str) -> Path | None:+ """Walk the filesystem to reconstruct the real path from a slug.++ Claude Code slugs replace both `/` and `.` with `-`. At each level+ we try the longest matching directory name first, testing both+ dash-literal and dot-substituted variants so `my-site-io` resolves+ to `my-site.io` when that's what exists on disk.+ """+ remaining = slug.lstrip("-")+ current = Path("/")++ while remaining:+ parts = remaining.split("-")+ matched = False+ for length in range(len(parts), 0, -1):+ candidate_name = "-".join(parts[:length])+ for name in _slug_name_variants(candidate_name):+ candidate_path = current / name+ if candidate_path.is_dir():+ current = candidate_path+ remaining = "-".join(parts[length:])+ matched = True+ break+ if matched:+ break+ if not matched:+ break++ return current if str(current) != "/" else None+++def _slug_name_variants(name: str) -> list[str]:+ """Candidate directory names from a slug segment.++ Returns the literal name first, then the fully-dotted variant.+ Only the two extremes — generating every intermediate combination+ would blow up the search space.+ """+ variants = [name]+ dotted = name.replace("-", ".")+ if dotted != name:+ variants.append(dotted)+ return variants+++#: Where a Codex home keeps rollouts. Codex MOVES a rollout, unchanged, from+#: `sessions/YYYY/MM/DD/` to a flat `archived_sessions/` when the developer+#: archives the thread. The file stem -- and so the session id -- is the same in+#: both, so reading the second folder cannot mint a second session.+CODEX_ROLLOUT_DIRS = ("sessions", "archived_sessions")+++def codex_rollout_dirs(home: Path) -> list[Path]:+ """Return the rollout directories that exist under a Codex home.++ The single answer to "where are this home's Codex sessions", shared by+ every reader so none of them can overlook archived threads.++ Args:+ home: a candidate Codex home.++ Returns:+ The existing directories, `sessions/` first. EMPTY means this is not a+ Codex home: a home whose every thread is archived has no `sessions/`+ directory and is still a home.+ """+ return [home / name for name in CODEX_ROLLOUT_DIRS if (home / name).is_dir()]+++#: Where Codex records the sessions it imported from another agent, one record+#: per import, each naming the Codex thread it created (`imported_thread_id`).+_CODEX_IMPORT_LEDGER = "external_agent_session_imports.json"+_UUID_LEN = 36+++def _codex_imported_thread_ids(home: Path) -> frozenset[str]:+ """Return the thread ids Codex says it imported from another agent.++ Reads Codex's own ledger, so an import is identified by what Codex+ recorded, never guessed from a transcript's shape.++ Args:+ home: a Codex home (the directory holding `sessions/`).++ Returns:+ The imported thread ids. EMPTY when the ledger is absent, unreadable+ or not the expected shape, and malformed records are passed over: an+ empty set skips nothing, so every failure here fails open to+ capturing the rollout, never to dropping a session.+ """+ try:+ ledger = json.loads((home / _CODEX_IMPORT_LEDGER).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return frozenset()+ records = ledger.get("records") if isinstance(ledger, dict) else None+ if not isinstance(records, list):+ return frozenset()+ return frozenset(+ record["imported_thread_id"]+ for record in records+ if isinstance(record, dict) and isinstance(record.get("imported_thread_id"), str)+ )+++def _codex_ran_a_turn(jsonl_file: Path) -> bool:+ """Return whether Codex ran a model turn of its own in this rollout.++ Codex writes a `turn_context` record for every turn it runs. A transcript+ it only imported has none; one the developer then continued in Codex does,+ and carries real Codex spend.++ Returns:+ True when a `turn_context` record is present -- and also when the file+ cannot be read, so an I/O fault can never be what drops a session.+ """+ # An import that was never continued is re-read in full on every index+ # build. Cache by (path, mtime, size) if a home ever holds enough imports+ # for that to matter.+ try:+ with jsonl_file.open("rb") as fh:+ for line in fh:+ if b'"turn_context"' not in line:+ continue+ try:+ record = json.loads(line)+ except ValueError:+ continue+ if isinstance(record, dict) and record.get("type") == "turn_context":+ return True+ except OSError:+ return True+ return False+++def _codex_is_uncontinued_import(jsonl_file: Path, imported_thread_ids: frozenset[str]) -> bool:+ """Return whether a rollout is another agent's session that Codex only imported.++ The single statement of the rule, shared by every Codex discovery path+ so they cannot disagree about which rollouts are Codex sessions.++ Args:+ jsonl_file: the rollout; its stem ends in its thread id.+ imported_thread_ids: `_codex_imported_thread_ids` of the rollout's home.++ Returns:+ True only when BOTH hold: Codex's ledger names the thread, and Codex+ never ran a turn of its own in it. The ledger alone would drop an+ import the developer went on to continue in Codex, which carries+ real Codex spend.+ """+ return jsonl_file.stem[-_UUID_LEN:] in imported_thread_ids and not _codex_ran_a_turn(jsonl_file)+++def _cwd_from_codex_head(head: bytes) -> str | None:+ """The absolute `cwd` Codex records in its `session_meta` line.++ Codex stamps the working directory once, in the opening `session_meta`+ payload (unlike Claude Code, which repeats it on every record). This is+ machine-independent, so it stays correct for transcripts copied from+ another machine - and it's the key mapped to `owner/repo` via the+ manifest's `cwd_repos`, so without capturing it a Codex session can't+ resolve a repo.+ """+ # Scan every line `_read_head` returned, not a fixed count. `_read_head`+ # already bounds the work (it stops at ~64KB / 5MB), so a second cap here+ # would drop valid sessions: transcripts can open with many lines of+ # metadata (`ai-title`, `agent-name`, `permission-mode`,+ # `file-history-snapshot`, `cursor_usage_event`) before the first real+ # record, and a `cursor_usage_event` stream can be the only place billed+ # tokens live.+ for raw_line in head.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ # A byte-truncated head can split a multi-byte UTF-8 char.+ continue+ if obj.get("type") == "session_meta":+ cwd = obj.get("payload", {}).get("cwd", "").rstrip("/")+ return cwd or None+ return None+++def _first_field_in_cc_head(head: bytes, key: str) -> str | None:+ """First non-empty string value for `key` among the head's session lines.++ Claude Code stamps `cwd` and `gitBranch` on (nearly) every record, so the+ first record carrying them is normally line 1 and this returns immediately.++ Scans every line the head holds rather than a fixed count. The head is+ already bounded by ``_read_head``'s ``max_bytes``, and a session whose first+ real record sits deep in the file has its ``cwd`` and ``gitBranch`` on that+ same record, so a line cap would return None for both and the session would+ have no repo attribution. A record carrying the field is the only thing+ worth stopping on; a line number never is.+ """+ for raw_line in head.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, ValueError):+ continue+ val = obj.get(key)+ if isinstance(val, str) and val:+ return val+ return None+++def _cwd_from_cc_head(head: bytes) -> str | None:+ """The `cwd` Claude Code stamps on its session lines.++ Unlike the on-disk project slug, cwd is **machine-independent** — it+ stays correct when the transcript was copied from another+ developer's machine, where the slug's real path doesn't exist to walk.+ """+ return _first_field_in_cc_head(head, "cwd")+++def _branch_metadata(data: bytes, agent: AgentType) -> tuple[str | None, list[str]]:+ """Read observed branch fields in transcript order, excluding subagents.++ No local git lookup: sessions may have run on another machine.+ Claude Code records changes per event, Codex in session_meta.git, and+ Copilot in its session context. Other formats without a branch stay empty.+ """+ latest = None+ branches: list[str] = []+ for line in data.splitlines():+ try:+ obj = json.loads(line)+ except (ValueError, UnicodeDecodeError):+ continue+ if not isinstance(obj, dict) or obj.get("isSidechain") is True:+ continue+ branch = None+ if agent == AgentType.CLAUDE_CODE:+ branch = obj.get("gitBranch")+ elif agent == AgentType.CODEX and obj.get("type") == "session_meta":+ payload = obj.get("payload")+ git = payload.get("git") if isinstance(payload, dict) else None+ branch = git.get("branch") if isinstance(git, dict) else None+ elif agent == AgentType.COPILOT and obj.get("type") in {"session.start", "session.resume"}:+ payload = obj.get("data")+ context = payload.get("context") if isinstance(payload, dict) else None+ branch = context.get("branch") if isinstance(context, dict) else None+ if isinstance(branch, str) and branch.strip():+ latest = branch.strip()+ if latest != "HEAD" and latest not in branches:+ branches.append(latest)+ return latest, branches+++def _branch_from_cc_head(head: bytes) -> str | None:+ """Latest branch observed in the supplied head (full history loads on parse)."""+ return _branch_metadata(head, AgentType.CLAUDE_CODE)[0]+++def _cwd_from_opencode_head(head: bytes) -> str | None:+ """The `cwd` opencode records on its assistant messages (`message.path.cwd`).++ Machine-independent (the session's working directory, not an on-disk slug),+ so it stays correct for transcripts copied from another machine - and it's what the repo+ resolver's manifest tier and Conductor-workspace detection key off. The+ opening record is a user message with no `path`, so scan a few lines to+ reach the first assistant message.+ """+ for raw_line in head.split(b"\n")[:30]:+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ message = obj.get("message")+ if isinstance(message, dict):+ cwd = (message.get("path") or {}).get("cwd")+ if isinstance(cwd, str) and cwd:+ return cwd.rstrip("/")+ return None+++def _cwd_from_cursor_store_head(head: bytes) -> str | None:+ """The `cwd` Cursor's synthesized header line carries (line 1, `cursor_store_session`).++ Machine-independent (resolved from the store.db's workspace URI or the+ acp-sessions `meta.json` sidecar before materializing the header), same+ rationale as every other agent's cwd getter - it stays correct for+ transcripts copied from another machine.+ """+ for raw_line in head.split(b"\n")[:5]:+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if obj.get("type") != "cursor_store_session":+ return None # first real line isn't the header — nothing to find+ cwd = obj.get("cwd")+ return cwd.rstrip("/") if isinstance(cwd, str) and cwd else None+ return None+++def _cursor_store_message_count(head: bytes) -> int:+ """Count real (non-header) message lines in a Cursor NDJSON head.++ The header (line 1) carries no conversation; `find_cursor_store_candidates`+ already refuses to materialize a session with zero messages, but a+ hand-edited file could still produce one - and `parse_cursor_store` would+ then yield an empty span list, which the pipeline treats as a+ FAILED session rather than a benign skip. Index time is where "nothing to+ index" can be told apart from "indexing broke", so callers use this to skip indexing such a file outright.+ """+ count = 0+ # Scan every line `_read_head` returned, not a fixed count. `_read_head`+ # already bounds the work (it stops at ~64KB / 5MB), so a second cap here+ # would drop valid sessions: transcripts can open with many lines of+ # metadata (`ai-title`, `agent-name`, `permission-mode`,+ # `file-history-snapshot`, `cursor_usage_event`) before the first real+ # record, and a `cursor_usage_event` stream can be the only place billed+ # tokens live.+ for i, raw_line in enumerate(head.split(b"\n")):+ if i == 0:+ continue # header line+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if isinstance(obj, dict) and "role" in obj:+ count += 1+ return count+++def _cwd_from_kiro_head(head: bytes) -> str | None:+ """The workspace root Kiro's synthesized header carries (`workspacePaths[0]`).++ Machine-independent (Kiro records the real path the developer had open in+ the IDE), so it survives copying - same rationale as every other agent's+ cwd getter.+ """+ for raw_line in head.split(b"\n")[:5]:+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if obj.get("type") != "kiro_session":+ return None # first real line isn't the header — nothing to find+ paths = obj.get("workspacePaths")+ if isinstance(paths, list) and paths and isinstance(paths[0], str) and paths[0]:+ return paths[0].rstrip("/")+ return None+ return None+++def _kiro_event_count(head: bytes) -> int:+ """Count real (non-header) event lines in a Kiro NDJSON head.++ The header (line 1) carries no conversation. `find_kiro_candidates`+ already refuses to materialize a session with no `turn_end`, but a+ hand-edited file could still produce an event-less one — and `parse_kiro`+ would then yield an empty span list, which the pipeline+ treats as a FAILED session rather than a benign skip. Same guard, and same+ reasoning, as `_cursor_store_message_count`.+ """+ count = 0+ # Scan every line `_read_head` returned, not a fixed count. `_read_head`+ # already bounds the work (it stops at ~64KB / 5MB), so a second cap here+ # would drop valid sessions: transcripts can open with many lines of+ # metadata (`ai-title`, `agent-name`, `permission-mode`,+ # `file-history-snapshot`, `cursor_usage_event`) before the first real+ # record, and a `cursor_usage_event` stream can be the only place billed+ # tokens live.+ for i, raw_line in enumerate(head.split(b"\n")):+ if i == 0:+ continue # header line+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if isinstance(obj, dict) and isinstance(obj.get("payload"), dict):+ count += 1+ return count+++def _copilot_session_start(head: bytes) -> dict | None:+ """The ``data`` payload of the head's ``session.start`` event, if any."""+ for raw_line in head.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if not isinstance(obj, dict):+ continue+ if obj.get("type") == "session.start":+ payload = obj.get("data")+ return payload if isinstance(payload, dict) else None+ return None+++def _copilot_session_key(start: dict | None, jsonl_file: Path) -> str:+ """The session id segment for a Copilot transcript.++ Every current-layout file is literally named ``events.jsonl``, so the stem+ would collide every session onto one id. Prefer the header's own+ ``sessionId`` (the UUID ``copilot --resume`` takes); fall back to the+ per-session directory name for the current layout and to the stem for the+ legacy flat layout.+ """+ if start is not None:+ sid = start.get("sessionId")+ if isinstance(sid, str) and sid.strip():+ return sid.strip()+ if jsonl_file.stem == "events":+ return jsonl_file.parent.name+ return jsonl_file.stem+++def _cwd_from_copilot_head(head: bytes, start: dict | None) -> str | None:+ """cwd from the ``session.start`` context, else the folder-trust notice.++ Legacy builds wrote no ``context`` on ``session.start``; their only cwd hint+ is the ``session.info`` line "Folder <path> has been added to trusted+ folders." (the same fallback the parser uses).+ """+ if start is not None:+ ctx = start.get("context")+ if isinstance(ctx, dict):+ cwd = ctx.get("cwd")+ if isinstance(cwd, str) and cwd:+ return cwd.rstrip("/")+ for raw_line in head.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if not isinstance(obj, dict) or obj.get("type") != "session.info":+ continue+ payload = obj.get("data")+ if not isinstance(payload, dict) or payload.get("infoType") != "folder_trust":+ continue+ message = payload.get("message")+ if not isinstance(message, str):+ continue+ marker = "Folder "+ at = message.find(marker)+ if at == -1:+ continue+ rest = message[at + len(marker) :]+ end = rest.find(" has been")+ path = (rest if end == -1 else rest[:end]).strip()+ if path:+ return path.rstrip("/")+ return None+++def _branch_from_copilot_head(start: dict | None) -> str | None:+ """Git branch from the ``session.start`` context, when Copilot recorded one."""+ if start is None:+ return None+ ctx = start.get("context")+ if not isinstance(ctx, dict):+ return None+ branch = ctx.get("branch")+ return branch if isinstance(branch, str) and branch else None+++# Bound for the second, cwd-hunting head read on a Copilot log whose first head+# carried no cwd. Legacy builds wrote the folder-trust notice as a separate+# `session.info` record, so it can sit past the detection-sized head; 1 MiB+# covers any realistic preamble while keeping a cwd-less legacy file (a folder+# already trusted earlier emits no notice at all) from costing a 5 MB read.+_COPILOT_CWD_SCAN_MAX_BYTES = 1_000_000+++def _copilot_cwd_present(buf: bytes) -> bool:+ """`_read_head` stop predicate: a cwd-bearing Copilot RECORD has been read.++ Record-aware on purpose: a bare substring test on ``"cwd"`` would also fire+ on a tool call whose arguments happen to carry a ``cwd`` key and stop the+ scan before the later folder-trust notice. `_read_head` hands the predicate+ complete lines, so parsing them here is exact, and the same two getters+ the indexer uses decide what counts.+ """+ return _cwd_from_copilot_head(buf, _copilot_session_start(buf)) is not None+++def _copilot_has_conversation(head: bytes) -> bool:+ """True when the head holds a prompt or an assistant reply.++ Same guard, same reasoning as ``_cursor_store_message_count`` /+ ``_kiro_event_count``: a metadata-only file would yield an+ empty span list, which the pipeline treats as a FAILED session+ rather than a benign skip. Scans every line ``_read_head`` returned.+ """+ for raw_line in head.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if isinstance(obj, dict) and obj.get("type") in ("user.message", "assistant.message"):+ return True+ return False+++def _copilot_vscode_jsonl_session_id(head: bytes) -> str | None:+ """``sessionId`` from a Copilot-VS-Code ``.jsonl``'s first line (the+ kind=0 snapshot). Cheap and stable: a replay may later rewrite+ which requests exist, never the id the session was created under."""+ first_line = head.split(b"\n", 1)[0].strip()+ try:+ obj = json.loads(first_line)+ except (json.JSONDecodeError, UnicodeDecodeError):+ return None+ if not isinstance(obj, dict) or obj.get("kind") != 0:+ return None+ snapshot = obj.get("v")+ session_id = snapshot.get("sessionId") if isinstance(snapshot, dict) else None+ return session_id if isinstance(session_id, str) and session_id else None+++def _copilot_vscode_json_session_id(head: bytes) -> tuple[str | None, bool]:+ """``(sessionId, has_requests)`` from a Copilot-VS-Code ``.json`` single+ document.++ Confirms the shape directly (``requests`` present) rather than through+ ``detect_agent`` -- a pretty-printed document has no single+ self-contained JSON line for that line-oriented scanner to match. A+ byte-capped ``head`` on a huge file fails ``json.loads`` cleanly (the+ document is no longer valid JSON once truncated mid-object), which reads+ as "not this format" here rather than a crash -- same safe-failure shape+ ``detect_agent`` itself relies on for a malformed line.++ ``has_requests`` lets the caller skip a genuinely empty "empty window"+ document (``requests: []``) without a second full-document parse.+ """+ try:+ obj = json.loads(head)+ except (json.JSONDecodeError, UnicodeDecodeError):+ return None, False+ if not isinstance(obj, dict) or "requests" not in obj:+ return None, False+ session_id = obj.get("sessionId")+ session_id = session_id if isinstance(session_id, str) and session_id else None+ requests = obj.get("requests")+ return session_id, isinstance(requests, list) and len(requests) > 0+++def _project_from_cwd(cwd: str) -> str | None:+ """Project name from the transcript's cwd.++ Normally the cwd's final path component (`…/api` → `api`).++ Claude Code git worktrees live at `<repo>/.claude/worktrees/<name>`,+ where the final component is a generated worktree name+ (`joyful-shimmying-crane`) — useless as a project label and a+ cost-attribution leak: every worktree session would become its own+ phantom project, splitting one repo's spend across many buckets. For+ those, the real project is the repo dir holding `.claude`, so we take+ the component just before `/.claude/worktrees/`.++ Normalized through `_paths.to_posix` first: this runs ahead of every+ parser (the parsers' own basename fallback only fires when this+ returns None), so a backslashed Windows cwd handled here as a raw+ string would surface the whole path as the project name — and the+ worktree marker would never match its backslashed form either.+ """+ path = to_posix(cwd)+ marker = "/.claude/worktrees/"+ if marker in path:+ path = path.split(marker, 1)[0]+ name = path.rsplit("/", 1)[-1]+ return name or None+++def _has_cursor_store_header(head: bytes) -> bool:+ """True if the head carries a ``cursor_store_session`` line (the store.db shape).++ Distinguishes Cursor's two local JSONL shapes — both detect as+ ``AgentType.CURSOR`` — so the index can route the store.db NDJSON to+ ``parse_cursor_store`` and the header-less ``agent-transcripts`` narrative to+ ``parse_cursor_agent_transcript``.+ """+ for raw in head.split(b"\n"):+ raw = raw.strip()+ if not raw:+ continue+ try:+ obj = json.loads(raw)+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ if isinstance(obj, dict) and obj.get("type") == "cursor_store_session":+ return True+ return False+++def _claude_code_subagent_files(transcript: Path) -> list[Path]:+ """List child transcripts; missing directory is normal, read errors are not."""+ directory = transcript.with_suffix("") / "subagents"+ try:+ with os.scandir(directory) as entries:+ return sorted(Path(e.path) for e in entries if Path(e.name).match("agent-*.jsonl"))+ except FileNotFoundError:+ return []+++def _with_claude_code_subagents(+ data: bytes, transcript: Path, *, related_parents: tuple[Path, ...] = ()+) -> bytes:+ """Read child files beside every duplicate parent, without losing unique calls.++ Any unreadable/oversized child fails this session, leaving the caller's replay+ pending. Exact lines repeated in another file are ignored; streaming fragments+ within a file retain their parser semantics. Parent offsets remain unchanged.+ """+ files = sorted(+ {+ child+ for parent in (transcript, *related_parents)+ for child in _claude_code_subagent_files(parent)+ }+ )+ parts = [data]+ seen: set[bytes] = set()+ total = len(data)+ for path in files:+ size = path.stat().st_size+ if total + size > MAX_SESSION_BYTES:+ raise OversizedSessionError(f"Subagent {path.name} exceeds the session byte cap")+ extra = path.read_bytes()+ if len(extra) > MAX_SESSION_BYTES:+ raise OversizedSessionError(f"Subagent {path.name} grew past the session byte cap")+ lines = extra.splitlines(keepends=True)+ unseen = [line for line in lines if line not in seen]+ seen.update(lines)+ extra = b"".join(unseen)+ if not extra:+ continue+ sep = b"" if parts[-1].endswith(b"\n") else b"\n"+ if total + len(extra) + len(sep) > MAX_SESSION_BYTES:+ raise OversizedSessionError(+ f"{transcript.name}: parent and children exceed the session byte cap"+ )+ parts.extend((sep, extra))+ total += len(extra) + len(sep)+ return b"".join(parts)+++class LocalSource:+ """Read JSONL session files from local Claude Code / Codex homes.++ Per-home index pattern:+ Claude Code: `<home>/projects/<slug>/**/*.jsonl`+ Codex: `<home>/sessions/**/*.jsonl`++ Copilot: `<home>/session-state/<session-id>/events.jsonl`+ (legacy `<home>/session-state/<session-id>.jsonl`)++ Sub-agent sessions (Claude Code's `isSidechain=true` files —+ prompt suggestions, compactions, etc.) are skipped to avoid+ polluting the index with non-conversation traces.+ """++ source_name = "local"++ def __init__(+ self,+ claude_code_homes: list[Path],+ codex_homes: list[Path],+ opencode_homes: list[Path] | None = None,+ cursor_store_homes: list[Path] | None = None,+ kiro_homes: list[Path] | None = None,+ copilot_homes: list[Path] | None = None,+ copilot_vscode_homes: list[Path] | None = None,+ ) -> None:+ self.claude_code_homes = claude_code_homes+ self.codex_homes = codex_homes+ # opencode has no per-session file - each SQLite+ # session is materialized to NDJSON under a home labelled `opencode`, laid out+ # `<home>/<project_id>/<session_id>.jsonl` (no `projects/`/`sessions/`+ # wrapper), so it gets its own rglob walk + indexer below.+ self.opencode_homes = opencode_homes or []+ # Cursor CLI/agent sessions have no per-session JSONL either — the+ # materializer decodes each `store.db` into an NDJSON+ # transcript per session, laid out flat as `<home>/<session_id>.jsonl`+ # (no `projects/`/`sessions/` wrapper, no per-project subdir like+ # opencode). Same rglob-the-whole-home treatment.+ self.cursor_store_homes = cursor_store_homes or []+ # Kiro sessions are a DIRECTORY per session, so the materializer merges+ # each one (session.json + messages.jsonl + sub-executions/*.jsonl) into+ # a single NDJSON transcript, laid out `<home>/<ws_hash>/<session_id>+ # .jsonl` — one subdir level, like opencode. Same rglob walk.+ self.kiro_homes = kiro_homes or []+ # Copilot CLI writes a real per-session JSONL itself, so no+ # materialization step: `<home>/session-state/<session-id>/events.jsonl`+ # (older builds: `<home>/session-state/<session-id>.jsonl`). Every file+ # is named `events.jsonl`, so the session id comes from the header's+ # `sessionId` (else the parent directory), never the file stem.+ self.copilot_homes = copilot_homes or []+ # Copilot in VS Code (Chat/agent mode) writes a `User` dir that+ # `_copilot_vscode_homes()` resolves per app/OS; chat sessions live+ # one or two levels under it (`workspaceStorage/*/chatSessions/` or+ # `globalStorage/emptyWindowChatSessions/`), so this also gets the+ # whole-home rglob treatment, over both `.jsonl` and `.json`.+ self.copilot_vscode_homes = copilot_vscode_homes or []+ # Per-home identity stamp (`<home>/_manifest/*.json`). It carries a+ # user_uuid/email/github_username used to detect duplicated sessions+ # that belong to different owners. Missing manifest → empty dict.+ self._home_identities: dict[Path, ManifestIdentity] = {}+ # Per-home `cwd → owner/repo` map from the manifest's `cwd_repos`+ # (a git-remote stamp). Feeds the repo resolver's top `manifest`+ # tier - the only reliable repo signal for copied transcripts.+ # Empty for manifests predating the stamp.+ self._home_repos: dict[Path, dict[str, str]] = {}+ # Per-home `git_toplevel → owner/repo` map from the manifest's+ # `repo_roots` (a stamp of every repo the sessions' tool calls+ # touched - not just the cwds). Feeds multi-repo attribution:+ # files are prefix-matched against these roots, where no git is+ # on disk.+ self._home_roots: dict[Path, dict[str, str]] = {}+ for home in (+ *claude_code_homes,+ *codex_homes,+ *self.opencode_homes,+ *self.cursor_store_homes,+ *self.kiro_homes,+ *self.copilot_homes,+ *self.copilot_vscode_homes,+ ):+ identity = _load_manifest_identity(home)+ if identity is not None:+ self._home_identities[home] = identity+ logger.info(+ "manifest identity loaded home=%s user_uuid=%s email=%s github=%s",+ home,+ identity.user_uuid,+ identity.email,+ identity.github_username,+ )+ repos = _load_manifest_repos(home)+ if repos:+ self._home_repos[home] = repos+ roots = _load_manifest_repo_roots(home)+ if roots:+ self._home_roots[home] = roots+ self._file_index: dict[str, _FileRef] | None = None+ self._branch_history: dict[str, tuple[str | None, list[str]]] = {}+ self._claude_code_families: dict[str, set[Path]] = {}+ self._slug_cache: dict[str, str | None] = {}+ # Per-agent file-discovery tally, filled in by+ # `_record_discovery` as `_build_index()` walks each home. Pure+ # aggregate integers, keyed by the home list being walked (e.g.+ # "claude-code"), not necessarily the file's own detected agent —+ # see `_record_discovery`'s docstring for why that distinction matters.+ self._discovery_stats: dict[str, dict[str, Any]] = {}++ def _record_discovery(self, walk_agent: str, outcome: str) -> None:+ """Tally one file's discovery outcome. Aggregate counts ONLY.++ `walk_agent` is the home list this file was found under (e.g.+ "claude-code"), not necessarily what `detect_agent` returned for+ it — a `"different_agent"` outcome means detection succeeded but+ for a different type sharing the same home directory, which is+ expected and not a capture problem.++ `outcome` is either `"indexed"` (became a real session) or a skip+ reason (`"different_agent"`, `"detection_failed"`, ...) — see each+ `_index_*_file` method for its own reasons.++ Never pass a file path, name, byte size, or any other per-file+ detail here or downstream of here: the whole point of this tally is+ that nothing more specific than an integer count ever leaves this+ method.+ """+ bucket = self._discovery_stats.setdefault(+ walk_agent, {"seen": 0, "indexed": 0, "skipped": {}}+ )+ bucket["seen"] += 1+ if outcome == "indexed":+ bucket["indexed"] += 1+ else:+ bucket["skipped"][outcome] = bucket["skipped"].get(outcome, 0) + 1++ def discovery_stats(self) -> dict[str, dict[str, Any]]:+ """Per-agent file-discovery counts from the last `_build_index()` call.++ ``{agent: {"seen": int, "indexed": int, "skipped": {reason: int}}}``+ — pure aggregate integers, never a file path, name, or byte size.+ Empty until `discover_sessions()` (which calls `_build_index()`) has+ run at least once.+ """+ return self._discovery_stats++ def capabilities(self) -> frozenset[str]:+ """Local files expose tokens + project_name + tool calls, but+ no user identity beyond the file owner."""+ return frozenset(+ {+ "tokens",+ "tool_calls",+ "project_name",+ "user_id_from_filesystem",+ "multi_agent",+ }+ )++ def _build_index(self) -> dict[str, _FileRef]:+ if self._file_index is not None:+ return self._file_index++ index: dict[str, _FileRef] = {}+ # Newest mtime per session across duplicate prefixes; applied to the+ # winners after the walk (see `_carry_collision_mtimes`).+ newest: dict[str, datetime] = {}++ for home in self.claude_code_homes:+ projects_dir = home / "projects"+ if not projects_dir.is_dir():+ logger.debug("Skipping non-existent path: %s", projects_dir)+ continue+ for jsonl_file in projects_dir.rglob("*.jsonl"):+ ref = self._index_cc_file(jsonl_file, projects_dir, home=home)+ if ref:+ incumbent = index.get(ref[0])+ if incumbent:+ old_identity = self._home_identities.get(incumbent.home)+ new_identity = self._home_identities.get(home)++ def owner(identity):+ return (+ (identity.org_uuid, identity.user_uuid or identity.email)+ if identity+ else None+ )++ if owner(old_identity) != owner(new_identity):+ raise ValueError(f"Conflicting owners for duplicated session {ref[0]}")+ self._claude_code_families.setdefault(ref[0], set()).add(jsonl_file)+ _index_put(index, ref[0], ref[1], newest)++ for home in self.codex_homes:+ rollout_dirs = codex_rollout_dirs(home)+ if not rollout_dirs:+ logger.debug("Skipping non-existent path: %s", home / "sessions")+ continue+ imported_thread_ids = _codex_imported_thread_ids(home)+ for rollout_dir in rollout_dirs:+ for jsonl_file in rollout_dir.rglob("*.jsonl"):+ ref = self._index_codex_file(+ jsonl_file, home=home, imported_thread_ids=imported_thread_ids+ )+ if ref:+ _index_put(index, ref[0], ref[1], newest)++ # opencode: materialized NDJSON lives at `<home>/<project_id>/*.jsonl`+ # (no fixed sub-dir like Claude's `projects/` or Codex's `sessions/`),+ # so walk the whole home. `detect_agent` content-sniffs each file, so a+ # stray non-opencode `.jsonl` here is skipped rather than mis-parsed.+ for home in self.opencode_homes:+ if not home.is_dir():+ logger.debug("Skipping non-existent path: %s", home)+ continue+ for jsonl_file in home.rglob("*.jsonl"):+ ref = self._index_opencode_file(jsonl_file, home=home)+ if ref:+ _index_put(index, ref[0], ref[1], newest)++ # Cursor: materialized NDJSON lives flat at `<home>/<session_id>.jsonl`+ # (no per-project subdir even), so walk the whole home too.+ # `detect_agent` content-sniffs each file for the `cursor_store_session`+ # header, so a stray non-Cursor `.jsonl` here is skipped, not mis-parsed.+ for home in self.cursor_store_homes:+ if not home.is_dir():+ logger.debug("Skipping non-existent path: %s", home)+ continue+ for jsonl_file in home.rglob("*.jsonl"):+ ref = self._index_cursor_store_file(jsonl_file, home=home)+ if ref:+ _index_put(index, ref[0], ref[1], newest)++ # Kiro: materialized NDJSON lives at `<home>/<ws_hash>/<session_id>.jsonl`.+ # `detect_agent` content-sniffs for the `kiro_session` header, so a stray+ # non-Kiro `.jsonl` here is skipped, not mis-parsed.+ for home in self.kiro_homes:+ if not home.is_dir():+ logger.debug("Skipping non-existent path: %s", home)+ continue+ for jsonl_file in home.rglob("*.jsonl"):+ ref = self._index_kiro_file(jsonl_file, home=home)+ if ref:+ _index_put(index, ref[0], ref[1], newest)++ # Copilot: `<home>/session-state/<session-id>/events.jsonl` (legacy flat+ # `<session-id>.jsonl`). Walk the whole home so a copied tree that+ # kept only the `session-state/` subtree still indexes. `detect_agent`+ # sniffs for the `session.start` / `producer=copilot-agent` header, so+ # a stray non-Copilot `.jsonl` is skipped, not mis-parsed.+ for home in self.copilot_homes:+ if not home.is_dir():+ logger.debug("Skipping non-existent path: %s", home)+ continue+ for jsonl_file in home.rglob("*.jsonl"):+ ref = self._index_copilot_file(jsonl_file, home=home)+ if ref:+ _index_put(index, ref[0], ref[1], newest)++ # Copilot in VS Code (Chat/agent mode): `<home>/workspaceStorage/<ws>/+ # chatSessions/<id>.jsonl` (snapshot+patch log) and `<home>/+ # globalStorage/emptyWindowChatSessions/<id>.json|.jsonl` (a `.json`+ # is the session's final state as one document; a `.jsonl` is the+ # same snapshot+patch shape as chatSessions'). Walk both extensions —+ # `_index_copilot_vscode_file` tells them apart and confirms the+ # match itself, so a stray non-matching file here is skipped, not+ # mis-parsed. When both a `.json` and a `.jsonl` exist for the same+ # session, they collide on the same `session_id` key and resolve+ # through the SAME size-first, mtime-only-as-tiebreak rule every+ # other agent's multi-file case already uses (`_index_put` -- byte+ # size is the "more complete" signal since transcripts are+ # append-only; mtime only breaks an exact size tie) -- no bespoke+ # "prefer jsonl" rule. In practice a `.jsonl` with any real+ # conversation is larger than an abandoned empty `.json`, so this+ # already resolves the common case correctly; it is not a+ # format-aware rule, just the existing one applied here too.+ for home in self.copilot_vscode_homes:+ if not home.is_dir():+ logger.debug("Skipping non-existent path: %s", home)+ continue+ for session_file in (*home.rglob("*.jsonl"), *home.rglob("*.json")):+ ref = self._index_copilot_vscode_file(session_file, home=home)+ if ref:+ _index_put(index, ref[0], ref[1], newest)++ _carry_collision_mtimes(index, newest)+ self._file_index = index+ logger.info(+ "Indexed %d local JSONL files from %d homes",+ len(index),+ len(self.claude_code_homes)+ + len(self.codex_homes)+ + len(self.opencode_homes)+ + len(self.cursor_store_homes)+ + len(self.kiro_homes)+ + len(self.copilot_homes)+ + len(self.copilot_vscode_homes),+ )+ return index++ def _index_cc_file(+ self,+ jsonl_file: Path,+ projects_dir: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one Claude Code JSONL file (or skip if sub-agent / wrong agent)."""+ if not jsonl_file.is_file():+ # A directory or broken symlink `rglob` matched by pattern —+ # never a real transcript, so never tallied at all (counting it as+ # "empty_or_unreadable" would report a phantom file).+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("claude-code", "empty_or_unreadable")+ return None+ # `<slug>/<session>/subagents/agent-*.jsonl` are component pieces of+ # the parent session, not sessions of their own — `get_spans_by_session`+ # folds them into the parent (`_with_claude_code_subagents`), so+ # indexing one here would also stand it up as a standalone session and+ # count its turns, tools and spend twice.+ #+ # Checked before the head is read, so a subagent file never reaches+ # detection (and its warning). It is a PATH check because the content+ # check below is not sufficient on its own: it reads the first parseable line, and newer+ # Claude Code builds front-load `queue-operation` / `last-prompt` /+ # `ai-title` records that carry no `isSidechain` flag at all, so the+ # loop breaks on one of those and admits the file. Observed in real+ # transcript sets: ids shaped `local:claude-code:agent-<hex>`,+ # every one of them a subagent transcript admitted this way. The Cursor+ # indexer makes exactly this exclusion already. Check the parts BELOW+ # `projects_dir` only: a configured home (or any ancestor of it) could itself be named+ # `subagents`, which must not drop real sessions.+ try:+ relative_parts = jsonl_file.relative_to(projects_dir).parts+ except ValueError:+ relative_parts = ()+ if "subagents" in relative_parts:+ self._record_discovery("claude-code", "subagent_component")+ return None++ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("claude-code", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ # Only a head that is the whole file can prove there is no conversation;+ # a capped head may stop before the first message.+ if len(head) >= size and _is_metadata_only(head):+ logger.debug("no conversation in %s (%d bytes); session skipped", jsonl_file, size)+ self._record_discovery("claude-code", "no_conversation")+ return None+ # A .jsonl no agent shape claims is skipped, but loudly, so format+ # drift surfaces in logs instead of as quietly-missing data.+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("claude-code", "detection_failed")+ return None+ if agent != AgentType.CLAUDE_CODE:+ # A *different* agent's file in this home is fine (multi-agent+ # homes are by design) — the matching indexer picks it up.+ self._record_discovery("claude-code", "different_agent")+ return None++ # Sub-agent sessions also carry isSidechain=true; skip them — they're+ # not developer-initiated work. Retained for the older layout, which+ # wrote a sidechain as a sibling transcript with no `subagents/` parent.+ for line in head.split(b"\n"):+ line = line.strip()+ if not line:+ continue+ try:+ rec = json.loads(line)+ if rec.get("isSidechain") is True:+ self._record_discovery("claude-code", "subagent_component")+ return None+ break+ except (json.JSONDecodeError, ValueError):+ continue++ stem = jsonl_file.stem+ session_id = f"local:{agent}:{stem}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)+ # Time-window filtering reads this clock, and a subagent file can+ # be newer than the parent (parent killed mid-subagent, so no+ # tool_result line ever advanced it) -- the session's activity clock+ # is the newest write across the whole family.+ for sub in _claude_code_subagent_files(jsonl_file):+ try:+ mtime = max(mtime, datetime.fromtimestamp(sub.stat().st_mtime, tz=UTC))+ except OSError:+ continue++ # Project name: prefer the transcript's own `cwd` — it's+ # machine-independent, so it stays correct for transcripts+ # copied from another machine. Fall back to reconstructing the on-disk slug only+ # when cwd is absent; that walk needs the real path to exist+ # locally, so it's unreliable for someone else's transcripts+ # (e.g. `-Users-ada-work-my-cool-app` → `Users`).+ cwd = _cwd_from_cc_head(head)+ project_name = _project_from_cwd(cwd) if cwd else None+ if project_name is None:+ try:+ rel = jsonl_file.relative_to(projects_dir)+ slug = rel.parts[0]+ except (ValueError, IndexError):+ slug = jsonl_file.parent.name+ if slug not in self._slug_cache:+ self._slug_cache[slug] = _project_from_cc_slug(slug)+ project_name = self._slug_cache[slug]++ self._record_discovery("claude-code", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ branch=_branch_from_cc_head(head),+ home=home,+ )++ def _index_codex_file(+ self,+ jsonl_file: Path,+ *,+ home: Path,+ imported_thread_ids: frozenset[str] = frozenset(),+ ) -> tuple[str, _FileRef] | None:+ """Index one Codex JSONL file.++ Args:+ jsonl_file: the rollout to index.+ home: the Codex home it was found under.+ imported_thread_ids: `_codex_imported_thread_ids(home)`, read once+ per home by the caller. A rollout named for one of these that+ Codex never ran a turn in is another agent's session, already+ captured under that agent, and is skipped.+ """+ if not jsonl_file.is_file():+ # See _index_cc_file's identical guard: a directory/broken symlink+ # is never tallied, only a genuinely empty real file is.+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("codex", "empty_or_unreadable")+ return None+ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("codex", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("codex", "detection_failed")+ return None+ if agent != AgentType.CODEX:+ self._record_discovery("codex", "different_agent")+ return None++ if _codex_is_uncontinued_import(jsonl_file, imported_thread_ids):+ self._record_discovery("codex", "imported_not_continued")+ return None+ stem = jsonl_file.stem+ session_id = f"local:{agent}:{stem}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)++ cwd = _cwd_from_codex_head(head)+ project_name = _project_from_cwd(cwd) if cwd else None++ self._record_discovery("codex", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ home=home,+ )++ def _index_opencode_file(+ self,+ jsonl_file: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one materialized opencode NDJSON transcript."""+ if not jsonl_file.is_file():+ # See _index_cc_file's identical guard: a directory/broken symlink+ # is never tallied, only a genuinely empty real file is.+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("opencode", "empty_or_unreadable")+ return None+ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("opencode", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("opencode", "detection_failed")+ return None+ if agent != AgentType.OPENCODE:+ # A different agent's file under an opencode home (or a stray+ # `.jsonl`) — skip; the matching indexer, if any, owns it.+ self._record_discovery("opencode", "different_agent")+ return None++ stem = jsonl_file.stem+ session_id = f"local:{agent}:{stem}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)++ # cwd (from the assistant message's `path.cwd`) is machine-independent,+ # so it survives copying - it drives project_name, the repo resolver's+ # manifest tier, and Conductor-workspace detection.+ cwd = _cwd_from_opencode_head(head)+ project_name = _project_from_cwd(cwd) if cwd else None++ self._record_discovery("opencode", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ home=home,+ )++ def _index_kiro_file(+ self,+ jsonl_file: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one materialized Kiro NDJSON transcript."""+ if not jsonl_file.is_file():+ # See _index_cc_file's identical guard: a directory/broken symlink+ # is never tallied, only a genuinely empty real file is.+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("kiro", "empty_or_unreadable")+ return None+ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("kiro", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("kiro", "detection_failed")+ return None+ if agent != AgentType.KIRO:+ # A different agent's file under a Kiro home (or a stray `.jsonl`)+ # — skip; the matching indexer, if any, owns it.+ self._record_discovery("kiro", "different_agent")+ return None++ if _kiro_event_count(head) == 0:+ logger.debug("kiro: %s has zero events; session skipped", jsonl_file)+ self._record_discovery("kiro", "empty_events")+ return None++ stem = jsonl_file.stem+ session_id = f"local:{agent}:{stem}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)++ # cwd comes from the header's `workspacePaths[0]` — machine-independent,+ # so it survives copying and drives project_name + the repo resolver's+ # manifest tier, same as every other agent.+ cwd = _cwd_from_kiro_head(head)+ project_name = _project_from_cwd(cwd) if cwd else None++ self._record_discovery("kiro", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ home=home,+ )++ def _index_copilot_file(+ self,+ jsonl_file: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one Copilot CLI ``events.jsonl`` (or legacy flat) transcript."""+ if not jsonl_file.is_file():+ # See _index_cc_file's identical guard: a directory/broken symlink+ # is never tallied, only a genuinely empty real file is.+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("copilot", "empty_or_unreadable")+ return None+ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("copilot", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("copilot", "detection_failed")+ return None+ if agent != AgentType.COPILOT:+ # A different agent's file under a Copilot home (or a stray `.jsonl`)+ # is skipped; the matching indexer, if any, owns it.+ self._record_discovery("copilot", "different_agent")+ return None++ start = _copilot_session_start(head)+ # Copilot creates the session directory (and often the event log with+ # just `session.start` + a model-change line) the moment the binary+ # starts, so a large share of on-disk sessions never held a prompt.+ # Skip those when the head IS the whole file; a file longer than the+ # head is indexed regardless, since its conversation sits further down.+ if not _copilot_has_conversation(head) and len(head) >= jsonl_file.stat().st_size:+ logger.debug("copilot: %s has no conversation events; session skipped", jsonl_file)+ self._record_discovery("copilot", "no_conversation")+ return None++ session_id = f"local:{agent}:{_copilot_session_key(start, jsonl_file)}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)++ # cwd / branch come from the `session.start` context (machine-independent:+ # Copilot records the real directory the developer ran it in), with the+ # legacy folder-trust notice as the fallback for builds that wrote no+ # context. Drives project_name + the repo resolver, as for every agent.+ cwd = _cwd_from_copilot_head(head, start)+ if cwd is None:+ # The detection-sized head stops as soon as `session.start` is seen,+ # and a legacy log records its cwd on a LATER `session.info`+ # folder-trust line. Re-read, bounded, until a cwd-bearing record+ # shows up so long legacy transcripts keep their repo attribution.+ try:+ longer = _read_head(+ jsonl_file,+ max_bytes=_COPILOT_CWD_SCAN_MAX_BYTES,+ stop_when=_copilot_cwd_present,+ )+ except OSError:+ longer = head+ cwd = _cwd_from_copilot_head(longer, start)+ project_name = _project_from_cwd(cwd) if cwd else None++ self._record_discovery("copilot", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ branch=_branch_from_copilot_head(start),+ home=home,+ )++ def _index_copilot_vscode_file(+ self,+ session_file: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one Copilot-in-VS-Code chat session (``.jsonl`` snapshot+patch+ log, or a ``.json`` single document).++ Cheap head-only peek for the stable ``sessionId`` — the full+ snapshot+patch replay (``parse_copilot_vscode``) is deferred+ to actual parse time, same division of labour as every other indexer+ here. ``detect_agent`` only covers the ``.jsonl`` shape (see its+ docstring); the ``.json`` shape is confirmed directly, since a+ pretty-printed document has no single self-contained JSON line for+ that line-oriented scanner to match.+ """+ if not session_file.is_file():+ return None+ if session_file.stat().st_size == 0:+ self._record_discovery("copilot-vscode", "empty_or_unreadable")+ return None+ try:+ if session_file.suffix == ".jsonl":+ # Only the FIRST line matters (the kind=0 snapshot); the+ # default head is always enough for that regardless of the+ # rest of the file's length.+ head = _read_head(session_file)+ else:+ # .json is one whole document -- `_read_head`'s DEFAULT+ # behaviour (no `stop_when`) stops as soon as 20 lines have+ # accumulated, which truncates a pretty-printed document mid-+ # object for any session past a few requests. Forcing+ # `stop_when` false disables that early stop, so this reads to+ # EOF (the common case) or the same 5MB cap every other+ # agent's head-read already uses, not a silently truncated+ # blob `json.loads` would then always fail on.+ head = _read_head(session_file, stop_when=lambda _buf: False)+ except OSError:+ self._record_discovery("copilot-vscode", "empty_or_unreadable")+ return None++ if session_file.suffix == ".jsonl":+ agent = detect_agent(head)+ if agent is None:+ self._record_discovery("copilot-vscode", "detection_failed")+ return None+ if agent != AgentType.COPILOT_VSCODE:+ # A different agent's `.jsonl` under a shared VS Code home+ # (or a stray file) is skipped; the matching indexer, if+ # any, owns it.+ self._record_discovery("copilot-vscode", "different_agent")+ return None+ raw_session_id = _copilot_vscode_jsonl_session_id(head)+ else:+ # .json: not JSONL at all -- read and confirm the whole document+ # shape directly rather than forcing it through detect_agent. A+ # `requests: []` document is a genuinely empty "empty window"+ # session that was abandoned before any real message -- unlike an+ # empty `.jsonl` (which may just be mid-conversation, patches+ # still to come), this is FINAL state, so skip it here rather+ # than indexing something the parser will always emit zero spans+ # for and the pipeline then records as a failed session.+ raw_session_id, has_requests = _copilot_vscode_json_session_id(head)+ if raw_session_id is None:+ self._record_discovery("copilot-vscode", "different_agent")+ return None+ if not has_requests:+ self._record_discovery("copilot-vscode", "no_conversation")+ return None+ agent = AgentType.COPILOT_VSCODE++ if not raw_session_id:+ self._record_discovery("copilot-vscode", "detection_failed")+ return None+ # Namespaced like every other local indexer (`local:<agent>:<id>`) --+ # a bare sessionId would collide across agents and break the+ # session-id contract.+ session_id = f"local:{agent}:{raw_session_id}"++ mtime = datetime.fromtimestamp(session_file.stat().st_mtime, tz=UTC)+ self._record_discovery("copilot-vscode", "indexed")+ return session_id, _FileRef(+ path=session_file,+ agent=agent,+ mtime=mtime,+ # No cwd/repo resolution yet (the documented known gap: VS+ # Code stores the workspace path in a sibling workspace.json this+ # indexer doesn't read) -- project_name/cwd/branch stay None,+ # same as any other agent's session with no resolvable repo.+ home=home,+ )++ def _index_cursor_store_file(+ self,+ jsonl_file: Path,+ *,+ home: Path,+ ) -> tuple[str, _FileRef] | None:+ """Index one materialized Cursor CLI/agent NDJSON transcript."""+ if not jsonl_file.is_file():+ # See _index_cc_file's identical guard: a directory/broken symlink+ # is never tallied, only a genuinely empty real file is.+ return None+ size = jsonl_file.stat().st_size+ if size == 0:+ self._record_discovery("cursor", "empty_or_unreadable")+ return None+ # `agent-transcripts/<uuid>/subagents/*.jsonl` are component pieces of+ # the parent session, not standalone sessions — indexing them as their+ # own session would inflate session/turn/tool metrics. Skip them; the parent+ # `<uuid>/<uuid>.jsonl` transcript still indexes normally. Check the+ # HOME-RELATIVE parts only: a configured Cursor home (or any ancestor)+ # could itself be named `subagents`, which must not drop real sessions.+ if "subagents" in jsonl_file.relative_to(home).parts:+ self._record_discovery("cursor", "subagent_component")+ return None+ try:+ head = _read_head(jsonl_file, stop_when=_agent_detected)+ except OSError:+ self._record_discovery("cursor", "empty_or_unreadable")+ return None++ agent = detect_agent(head)+ if agent is None:+ # Only a head that is the whole file can prove there is no conversation;+ # a capped head may stop before the first message.+ if len(head) >= size and _is_metadata_only(head):+ logger.debug("no conversation in %s (%d bytes); session skipped", jsonl_file, size)+ self._record_discovery("cursor", "no_conversation")+ return None+ logger.warning(+ "agent detection failed for %s (%d bytes); session skipped",+ jsonl_file,+ size,+ )+ self._record_discovery("cursor", "detection_failed")+ return None+ if agent != AgentType.CURSOR:+ # A different agent's file under a Cursor home (or a stray+ # `.jsonl`) — skip; the matching indexer, if any, owns it.+ self._record_discovery("cursor", "different_agent")+ return None++ stem = jsonl_file.stem+ session_id = f"local:{agent}:{stem}"+ mtime = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=UTC)++ # Cursor has two local JSONL shapes under the same home + `cursor` label.+ # The store.db-derived NDJSON opens with a `cursor_store_session` header;+ # the `agent-transcripts/*.jsonl` narrative has none. Route each to its+ # parser via the `subformat` discriminator (both stay `AgentType.CURSOR`).+ if not _has_cursor_store_header(head):+ # Agent-transcript: no header, no cwd/tokens/timestamps in the source.+ # Derive project_name from the `projects/<slug>/agent-transcripts/…`+ # path slug (same decoder Claude Code uses for its `projects/<slug>`).+ slug: str | None = None+ parts = jsonl_file.parts+ if "agent-transcripts" in parts:+ # Use the INNERMOST `agent-transcripts` component — a configured+ # Cursor home path could itself contain an earlier one, and+ # `parts.index` would then pick the wrong (outer) slug.+ idx = len(parts) - 1 - parts[::-1].index("agent-transcripts")+ if idx >= 1:+ slug = parts[idx - 1]+ project_name = None+ if slug:+ if slug not in self._slug_cache:+ self._slug_cache[slug] = _project_from_cc_slug(slug)+ project_name = self._slug_cache[slug]+ self._record_discovery("cursor", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ home=home,+ subformat="agent_transcript",+ )++ # A store.db session with zero messages after the header has nothing to+ # index - `find_cursor_store_candidates` already refuses to+ # materialize these, but skip defensively rather than let+ # `parse_cursor_store` yield an empty span list (which the pipeline+ # would count as a FAILED session, not a skip).+ if _cursor_store_message_count(head) == 0:+ logger.debug("cursor_store: %s has zero messages; session skipped", jsonl_file)+ self._record_discovery("cursor", "empty_store_session")+ return None++ # cwd (from the header's `cwd` field) is machine-independent, so it+ # survives copying - it drives project_name and the repo resolver's+ # manifest tier, same as every other agent's cwd.+ cwd = _cwd_from_cursor_store_head(head)+ project_name = _project_from_cwd(cwd) if cwd else None++ self._record_discovery("cursor", "indexed")+ return session_id, _FileRef(+ path=jsonl_file,+ agent=agent,+ mtime=mtime,+ project_name=project_name,+ cwd=cwd,+ home=home,+ )++ def discover_sessions(+ self,+ start_time: datetime | None = None,+ end_time: datetime | None = None,+ ) -> list[DiscoveredSession]:+ index = self._build_index()+ results = []++ for session_id, ref in index.items():+ # Metadata can arrive after a completed transcript checkpoint.+ # Snapshot validation still happens against the exact parsed bytes.+ try:+ sidecar_time = datetime.fromtimestamp(+ ref.path.with_suffix(".metadata.json").stat().st_mtime, tz=UTC+ )+ except OSError:+ # One inaccessible optional sidecar must not block discovery+ # of the other sessions. Reading selected sessions still+ # validates metadata and reports access failures for retry.+ pass+ else:+ ref.mtime = max(ref.mtime, sidecar_time)+ if start_time and ref.mtime < start_time:+ continue+ if end_time and ref.mtime > end_time:+ continue++ # Rough span-count estimate: ~500 bytes per line.+ file_size = ref.path.stat().st_size+ estimated_spans = max(file_size // 500, 1)++ results.append(+ DiscoveredSession(+ session_id=session_id,+ span_count=estimated_spans,+ last_span_time=ref.mtime,+ start_time=ref.mtime,+ end_time=ref.mtime,+ )+ )++ results.sort(key=lambda s: s.start_time, reverse=True)+ return results++ def get_spans_by_session(self, session_id: str) -> list[SpanData]:+ index = self._build_index()+ ref = index.get(session_id)+ if not ref:+ logger.debug("Session not found in index: %s", session_id)+ return []++ try:+ data = ref.path.read_bytes()+ except FileNotFoundError:+ # The file moved after the index was built -- typically a Codex+ # rollout archived from sessions/YYYY/MM/DD/ to archived_sessions/+ # mid-run. Both locations are indexed, so rebuild the index once+ # and re-resolve the session. Still missing = moved or deleted: an+ # expected race, not an error (no traceback, nothing captured).+ self._file_index = None+ # Report the rebuilt walk only, not both walks added together.+ self._discovery_stats = {}+ ref = self._build_index().get(session_id)+ try:+ if ref is None:+ raise FileNotFoundError(session_id)+ data = ref.path.read_bytes()+ except FileNotFoundError:+ logger.info("Session file moved or deleted: %s", session_id)+ return []+ except OSError as exc:+ logger.warning(+ "Failed to read session file: %s", exc, exc_info=logger.isEnabledFor(logging.DEBUG)+ )+ return []+ except OSError as exc:+ logger.warning("Failed to read session file: %s", exc, exc_info=logger.isEnabledFor(logging.DEBUG))+ return []++ # Verify against the exact parent bytes being parsed, before appending+ # subagents. A partially written transcript/metadata pair must remain retryable rather+ # than applying a new repository to an older transcript (or vice versa).+ try:+ metadata = json.loads(ref.path.with_suffix(".metadata.json").read_bytes())+ except FileNotFoundError:+ metadata = None+ else:+ if not isinstance(metadata, dict) or (+ metadata.get("repo_name") is not None and not isinstance(metadata["repo_name"], str)+ ):+ raise ValueError("Invalid repository metadata sidecar; retry")+ if isinstance(metadata, dict) and "transcript_sha256" in metadata:+ if metadata["transcript_sha256"] != hashlib.sha256(data).hexdigest():+ raise ValueError("Transcript and repository metadata snapshot mismatch; retry")++ self._branch_history[session_id] = _branch_metadata(data, ref.agent)++ if ref.agent == AgentType.CLAUDE_CODE:+ data = _with_claude_code_subagents(+ data,+ ref.path,+ related_parents=tuple(self._claude_code_families.get(session_id, ())),+ )++ # Bail before parsing a pathologically large transcript: parsing it+ # can exhaust memory. Callers get OversizedSessionError instead.+ if len(data) > MAX_SESSION_BYTES:+ raise OversizedSessionError(+ f"{ref.path.name}: {len(data) // (1024 * 1024)} MB "+ f"exceeds {MAX_SESSION_BYTES // (1024 * 1024)} MB cap"+ )++ # The OS user running the scan: the operator is the developer.+ user_id = os.environ.get("USER") or Path.home().name++ parsers = {+ AgentType.CLAUDE_CODE: parse_claude_code,+ AgentType.CODEX: parse_codex,+ AgentType.COPILOT: parse_copilot,+ AgentType.COPILOT_VSCODE: parse_copilot_vscode,+ AgentType.OPENCODE: parse_opencode,+ AgentType.CURSOR: parse_cursor_store,+ AgentType.KIRO: parse_kiro,+ }++ # Cursor's `agent-transcripts` narrative shares the `cursor` agent label+ # but needs its own parser (no header/tokens/timestamps).+ if ref.subformat == "agent_transcript":+ parser = parse_cursor_agent_transcript+ else:+ parser = parsers.get(ref.agent)+ if not parser:+ logger.debug("No parser for agent type: %s", ref.agent)+ return []++ _, spans = parser(+ data=data,+ trace_id=session_id,+ user_id=user_id,+ project_name=ref.project_name,+ )+ branch, branches = self._branch_history[session_id]+ root = next((span for span in spans if span.parent_id is None), None)+ if root is not None:+ root.attributes.update({"git.branch": branch, "git.branches": branches})+ # A cloud-run session stores selected-repository metadata in a sidecar+ # beside the unmodified transcript, whose remote cwd may be absent.+ repo = metadata.get("repo_name") if isinstance(metadata, dict) else None+ if isinstance(repo, str):+ root.attributes["harness.repo_name"] = repo+ if isinstance(metadata, dict) and "transcript_sha256" in metadata:+ cloud_ids = metadata.get("claude_cloud_session_ids")+ if (+ ref.agent == AgentType.CLAUDE_CODE+ and isinstance(cloud_ids, list)+ and len(cloud_ids) <= 100+ and all(isinstance(value, str) and re.fullmatch(r"session_[A-Za-z0-9]{1,128}", value) for value in cloud_ids)+ ):+ root.attributes["harness.claude_cloud_session_ids"] = sorted(set(cloud_ids))+ return spans++ def get_agent_type(self, session_id: str) -> str | None:+ """Return the agent that produced this session ('claude-code', 'codex', ...)."""+ index = self._build_index()+ ref = index.get(session_id)+ return ref.agent if ref else None++ def get_project_name(self, session_id: str) -> str | None:+ """Return the project name derived during indexing."""+ index = self._build_index()+ ref = index.get(session_id)+ return ref.project_name if ref else None++ def get_cwd(self, session_id: str) -> str | None:+ """Return the transcript's working directory, if captured at indexing.++ The machine-independent project anchor (Claude Code). Used by the+ repo resolver to tie a session to its own repo. None for sources+ that don't record a cwd in the head (e.g. Codex today).+ """+ index = self._build_index()+ ref = index.get(session_id)+ return ref.cwd if ref else None++ def get_branch(self, session_id: str) -> str | None:+ """Latest recorded branch; HEAD explicitly records a detached checkout."""+ self.get_branches(session_id)+ return self._branch_history.get(session_id, (None, []))[0]++ def get_branches(self, session_id: str) -> list[str]:+ """Distinct named branches from the selected original transcript copy."""+ if session_id not in self._branch_history:+ ref = self._build_index().get(session_id)+ if ref:+ self._branch_history[session_id] = _branch_metadata(+ ref.path.read_bytes(), ref.agent+ )+ return list(self._branch_history.get(session_id, (None, []))[1])++ def get_manifest_repo(self, session_id: str) -> str | None:+ """Canonical `owner/repo` for this session from the manifest stamp.++ Resolution: session → its home → that home's `cwd_repos` map →+ the session's cwd. Returns None when the manifest carries no repo+ for this cwd - the resolver then falls through to its produced-PR /+ git-remote / local-git tiers.+ """+ index = self._build_index()+ ref = index.get(session_id)+ if not ref or not ref.home or not ref.cwd:+ return None+ return self._home_repos.get(ref.home, {}).get(ref.cwd)++ def get_cwd_repos(self, session_id: str) -> dict[str, str]:+ """The full `cwd -> 'owner/repo'` map for this session's home.++ The per-task repo resolver needs every cwd→repo entry (not just+ the session's own cwd) because one session can span several repos+ and each task resolves against its own dominant cwd. Resolution:+ session → its home → that home's `cwd_repos` map. Empty dict when+ the home had no manifest stamp.+ """+ index = self._build_index()+ ref = index.get(session_id)+ if not ref or not ref.home:+ return {}+ return self._home_repos.get(ref.home, {})++ def get_repo_roots(self, session_id: str) -> dict[str, str]:+ """The `git_toplevel -> 'owner/repo'` map for this session's home.++ Per-task multi-repo attribution prefix-matches each task's touched+ files against these roots (the only git-truth file→repo signal+ available at scan time). Empty dict when the home's manifest carries+ neither `repo_roots` nor a derivable `cwd_repos`.+ """+ index = self._build_index()+ ref = index.get(session_id)+ if not ref or not ref.home:+ return {}+ return self._home_roots.get(ref.home, {})+++class _FileRef:+ """Internal pointer: session_id → file path + index-time metadata."""++ __slots__ = ("agent", "branch", "cwd", "home", "mtime", "path", "project_name", "subformat")++ def __init__(+ self,+ path: Path,+ agent: AgentType,+ mtime: datetime,+ project_name: str | None = None,+ cwd: str | None = None,+ branch: str | None = None,+ home: Path | None = None,+ subformat: str | None = None,+ ):+ self.path = path+ self.agent = agent+ self.mtime = mtime+ self.project_name = project_name+ # Sub-format discriminator within an agent that has more than one local+ # shape. Currently only Cursor: None = store.db NDJSON (`parse_cursor_store`),+ # "agent_transcript" = the `agent-transcripts/*.jsonl` narrative+ # (`parse_cursor_agent_transcript`). Lets the parse step pick the right+ # parser while both keep `agent == AgentType.CURSOR` (one agent label).+ self.subformat = subformat+ # Full working directory from the transcript (Claude Code). The+ # machine-independent ground truth for project_name, and the+ # anchor the repo resolver uses to tie a session to its own repo.+ self.cwd = cwd+ # Git branch the session ran on (Claude Code `gitBranch`).+ self.branch = branch+ # The home dir under which this file was discovered — used to+ # look up the manifest identity for that home.+ self.home = home+++__all__ = ["LocalSource", "ManifestIdentity"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/edit_lines.py b/python/src/agentplay/_core/ingestion/coding_agent/edit_lines.pynew file mode 100644index 0000000..d54ea66--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/edit_lines.py@@ -0,0 +1,236 @@+"""Added / removed line counts from an edit tool span's `input.value`.++The AI-lines-of-code signal. Counted locally, for two reasons.++First, lines added is a plain count. Ratios built on top of it, such as an+AI-code percentage, need totals this module cannot see and are derived by the+consumer, in line with `metrics.py`'s "Counts only; ratios are derived by the+consumer".++Second, and load-bearing: the raw material never leaves the machine. A tool+span's `input.value` holds the actual edit payload, and the session payload+deliberately excludes tool arguments and results because "those are+content". Counting locally and emitting two integers keeps that property. Any+downstream derivation would mean shipping diffs.++Deliberately narrow, in the same spirit as `file_paths.py`: only the four tools+whose input genuinely carries the changed text, and a strict `json.loads` rather+than a regex. A payload that does not parse yields None (unknown), never 0 —+persisting a fabricated 0 would launder an unmeasured session into a real-looking+measurement, the same distinction `session_pure.interrupt_count_measured`+documents.++Per-agent coverage is NOT uniform, and the gap is deliberate rather than hidden.+The local parsers do normalize every agent's edits into this tool taxonomy, so+this module never branches per agent — but what reaches `input.value` differs:++- Claude Code: full `old_string` / `new_string` / `content`. Measured; the diff+ discounts unchanged context lines that a naive payload-line count would include.+- Codex: `apply_patch` arrives as `{"file_path": ..., "patch": <body>}`, and+ `parsers/codex.py` truncates `input.value` at 2,000 characters with the patch+ key LAST — so any non-trivial patch is cut mid-string and fails `json.loads`,+ yielding None. Counting only the patches small enough to survive would report+ a confident number biased low by exactly the large edits that matter most, so+ unmeasured is the honest answer until the parser stamps counts at parse time+ (where it still holds the untruncated body).+- Cursor / opencode / kiro: same 2,000-character truncation applies.++Note for future edits: `parsers/codex.py::_rewrite_apply_patch_input` documents+that its repeated `"file_path"` keys are safe because "no current consumer" uses+`json.loads`. This module is the first one that does. Duplicate keys resolve+last-wins, which is harmless here (the path is not read), but a consumer added+later that needs every path must stay regex-based per `file_paths.py`.+"""++from __future__ import annotations++import difflib+import json+import re++# Tools whose `input.value` carries the changed text. `Edit` and `MultiEdit`+# carry BOTH sides, so they diff exactly. `Write` and `NotebookEdit` carry only+# the new content — the prior text is not in the payload — so every line reads+# as added; see `_full_content_counts`.+_DIFF_TOOLS: frozenset[str] = frozenset({"Edit"})+_MULTI_EDIT_TOOLS: frozenset[str] = frozenset({"MultiEdit"})+_FULL_CONTENT_TOOLS: frozenset[str] = frozenset({"Write", "NotebookEdit"})++EDIT_LINE_TOOLS: frozenset[str] = _DIFF_TOOLS | _MULTI_EDIT_TOOLS | _FULL_CONTENT_TOOLS++# Above this combined line count a real diff stops being worth its runtime, so+# both sides are charged whole. Generated files and vendored blobs are the only+# realistic way to reach it; a hand-written edit never does.+_DIFF_LINE_CAP = 20_000++# Keys holding the post-edit text, in the order the tools use them.+_CONTENT_KEYS = ("content", "new_source", "new_string")++# Counts stamped by a parser that held the untruncated body (codex apply_patch).+# Matched positionally so a truncated tail cannot break the read.+_RE_STAMPED_COUNTS = re.compile(r'"lines_added":\s*(\d+),\s*"lines_removed":\s*(\d+)')+++def _lines(text: object) -> list[str]:+ """Line list for a payload field, tolerant of a missing / non-string value.++ Uses `splitlines()` so a trailing newline does not invent an empty final+ line — `"a\\n"` is one line, not two.+ """+ return text.splitlines() if isinstance(text, str) and text else []+++def _diff_counts(old: object, new: object) -> tuple[int, int]:+ """`(added, removed)` between two versions of a file's text.++ A real line diff rather than `len(new), len(old)`: an `Edit` that rewrites+ one line inside a ten-line block changed one line, and charging it ten each+ way would inflate every session that edits in context.+ """+ old_lines, new_lines = _lines(old), _lines(new)+ if len(old_lines) + len(new_lines) > _DIFF_LINE_CAP:+ return len(new_lines), len(old_lines)+ added = removed = 0+ # autojunk=False: its "popular element" heuristic treats lines recurring in+ # >1% of a long sequence as junk, which in source files means blank lines and+ # closing braces — exactly the lines that anchor a correct diff.+ matcher = difflib.SequenceMatcher(None, old_lines, new_lines, autojunk=False)+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():+ if tag in ("replace", "insert"):+ added += j2 - j1+ if tag in ("replace", "delete"):+ removed += i2 - i1+ return added, removed+++def _full_content_counts(payload: dict) -> tuple[int, int] | None:+ """`(added, 0)` for a tool that carries only the post-edit text.++ `Write` overwriting an existing file is a full rewrite whose prior content+ the payload does not carry, so its whole body counts as added and nothing as+ removed. That over-counts a rewrite relative to a diff — accepted, because+ the alternative is reading the file from disk at parse time, which the+ parsers deliberately never do.+ """+ for key in _CONTENT_KEYS:+ if isinstance(payload.get(key), str):+ return len(_lines(payload[key])), 0+ return None+++def count_patch_lines(patch_text: object) -> tuple[int, int]:+ """`(added, removed)` for a codex `apply_patch` body.++ Called by `_sources/local/parsers/codex.py` at PARSE time, on the+ untruncated body. It has to happen there: the parser caps `input.value` at+ 2,000 characters, so by the time a consumer sees the span the patch tail is+ gone: a typical apply_patch span is cut mid-string.++ Counts hunk content only. `+`/`-` lines are additions/removals; `***`+ headers, `@@` markers and context lines are not content. A body line that+ merely quotes a header (`+*** Update File: x`) is an added line and counts+ as one, which the prefix test gets right for free.++ Assumes the apply_patch grammar specifically, NOT unified diff: there are no+ `+++` / `---` file markers to skip, and treating them as markers would drop+ real content (a source line starting `++` arrives as `+++`).++ A `*** Delete File:` header carries no body, so the removed lines of the+ file it drops are invisible here and counted as 0 — the same limit `Write`+ has when it overwrites a file whose prior content the payload never carried.++ Args:+ patch_text: The raw `*** Begin Patch` body.++ Returns:+ `(added, removed)`; `(0, 0)` when the input is not a usable string.+ """+ if not isinstance(patch_text, str) or not patch_text:+ return 0, 0+ added = removed = 0+ for line in patch_text.splitlines():+ # No `+++` / `---` skip here. Those are UNIFIED-diff file markers, and+ # this grammar has none — apply_patch names files on `*** <Verb> File:`+ # headers. Skipping them would instead drop real content: a source line+ # beginning `++` is encoded `+++`, so such a guard would undercount+ # every added line that starts with two plus signs.+ if line.startswith("+"):+ added += 1+ elif line.startswith("-"):+ removed += 1+ return added, removed+++def _stamped_counts(input_value: str) -> tuple[int, int] | None:+ """Counts a parser already stamped into `input.value`, if present.++ Regex rather than `json.loads` deliberately: a stamped payload whose tail+ was truncated is no longer parseable JSON, and the stamp exists precisely so+ those sessions stay measurable. This also keeps the module aligned with+ `file_paths.py`'s contract that `input.value` consumers are regex-based.+ """+ match = _RE_STAMPED_COUNTS.search(input_value)+ if match is None:+ return None+ return int(match.group(1)), int(match.group(2))+++def edit_line_counts(tool_name: object, input_value: object) -> tuple[int, int] | None:+ """Lines added and removed by one tool call.++ Args:+ tool_name: The span's `tool.name`. Anything outside `EDIT_LINE_TOOLS`+ returns None — a `Bash` `sed` call edits files too, but its payload+ carries a command rather than the text, so it is not countable here.+ input_value: The span's `input.value` attribute, expected to be a JSON+ object string.++ Returns:+ `(added, removed)`, or None when the tool is not a counted edit tool or+ the payload cannot be parsed into the fields this needs.+ """+ # `str` check before set membership: `tool.name` is a span attribute, so a+ # malformed transcript can put a list or dict there, and `in` on an+ # unhashable raises TypeError. `edit_line_totals` has no per-call guard, so+ # one malformed tool would abort the whole session's counts instead of the+ # documented None.+ if not isinstance(tool_name, str) or tool_name not in EDIT_LINE_TOOLS:+ return None+ if not isinstance(input_value, str) or not input_value:+ return None+ # A parser-stamped count wins: it was computed before truncation, so it is+ # both more accurate and readable on payloads json.loads would reject.+ stamped = _stamped_counts(input_value)+ if stamped is not None:+ return stamped+ try:+ payload = json.loads(input_value)+ except (TypeError, ValueError):+ return None+ if not isinstance(payload, dict):+ return None++ if tool_name in _MULTI_EDIT_TOOLS:+ edits = payload.get("edits")+ if not isinstance(edits, list):+ return None+ added = removed = 0+ counted = False+ for edit in edits:+ if not isinstance(edit, dict):+ continue+ one_added, one_removed = _diff_counts(edit.get("old_string"), edit.get("new_string"))+ added += one_added+ removed += one_removed+ counted = True+ return (added, removed) if counted else None++ if tool_name in _DIFF_TOOLS:+ if "old_string" not in payload and "new_string" not in payload:+ return None+ return _diff_counts(payload.get("old_string"), payload.get("new_string"))++ return _full_content_counts(payload)+++__all__ = ["EDIT_LINE_TOOLS", "count_patch_lines", "edit_line_counts"]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/file_paths.py b/python/src/agentplay/_core/ingestion/coding_agent/file_paths.pynew file mode 100644index 0000000..2b08a0f--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/file_paths.py@@ -0,0 +1,86 @@+"""Shared file-path extraction from a tool span's `input.value`.++`metrics.py` classifies tool calls by the file they touched (blind-edit,+duplicate-read, repeated-edit, single-file-focus, ...). Every local parser+JSON-serializes the touched file under a `"file_path":"..."` key by the+time its spans reach that consumer — Claude Code, Codex, and opencode use `file_path` natively;+Cursor's raw `"path"`/`"paths"` args are normalized to `file_path` by the+Cursor parser itself (`_sources/local/parsers/cursor_store.py::+_build_tool_span`) before the span is built. So this module stays a+single, narrow `file_path`-key regex match for every source — widening it+here (e.g. matching a bare `"path"` key or falling back to a whitespace+heuristic) would leak paths out of non-file spans too, like a Claude+`Bash` `{"command": "cat /a/b.py"}` or a `Grep` `{"path": "/a"}`, which+never carried a file path pre-Cursor-support and must not start now.+"""++from __future__ import annotations++from pathlib import PureWindowsPath+import re++from agentplay._core.ingestion.coding_agent._paths import to_posix++_RE_FILE_PATH = re.compile(r'"file_path":\s*"([^"]+)"')+++def extract_file_path(input_value: object) -> str | None:+ """Pull the `file_path` value out of a tool span's `input.value`.++ Args:+ input_value: The span's `input.value` attribute — expected to be+ a JSON-ish string; any other type (None, dict, ...) returns+ None.++ Returns:+ The first `"file_path":"..."` match, or None when `input_value`+ isn't a non-empty string or contains no match.+ """+ if not isinstance(input_value, str) or not input_value:+ return None+ m = _RE_FILE_PATH.search(input_value)+ return m.group(1) if m else None+++def extract_all_file_paths(input_value: object) -> set[str]:+ """Every `"file_path":"..."` match in a tool span's `input.value`.++ Args:+ input_value: The span's `input.value` attribute.++ Returns:+ The set of all `file_path` matches, or an empty set when none+ are found (or `input_value` isn't a non-empty string).+ """+ if not isinstance(input_value, str) or not input_value:+ return set()+ return {m.group(1) for m in _RE_FILE_PATH.finditer(input_value)}+++__all__ = ["extract_all_file_paths", "extract_file_path"]+++def repo_relative_path(path: object, repo_name: str) -> str | None:+ """Normalize a recorded file against its already-attributed repository.++ Absolute paths need the repository's own leaf in their ancestry. Reject+ traversal and repeated leaf segments: neither identifies an exact root.+ Relative paths stay relative; this never searches other repositories.+ """+ if not isinstance(path, str) or not path or not repo_name:+ return None+ path = to_posix(path)+ parts = path.split("/")+ if ".." in parts or "\x00" in path:+ return None+ parts = [part for part in parts if part and part != "."]+ if path.startswith("/") or re.match(r"^[A-Za-z]:/", path):+ leaf = repo_name.rsplit("/", 1)[-1]+ # Use the recorded platform, not the host running a replay. Preserve+ # the original relative-path casing and POSIX case sensitivity.+ key = str.casefold if PureWindowsPath(path).is_absolute() else str+ matches = [i for i, part in enumerate(parts) if key(part) == key(leaf)]+ if len(matches) != 1:+ return None+ parts = parts[matches[0] + 1 :]+ return "/".join(parts) or Nonediff --git a/python/src/agentplay/_core/ingestion/coding_agent/metrics.py b/python/src/agentplay/_core/ingestion/coding_agent/metrics.pynew file mode 100644index 0000000..be81274--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/metrics.py@@ -0,0 +1,308 @@+"""Cost-efficiency counters for `CodingAgentTask` — pure, no LLM.++Walks the spans that belong to a task once and returns the deterministic+counter set stored for a task. Ratios+(`tokens_per_edit`, `cache_hit_ratio`, `compaction_waste_ratio`,+`context_pressure_score`) are intentionally *not* stored: they are+derived from these counters plus the token aggregates, so slicers+(by-language, by-project, by-cohort) can compute ratios over filtered+subsets without re-walking spans.++# Why one module, one function++Every caller recomputes these counters from spans. Centralizing the+formula here means any future tuning (e.g. adding "TodoWrite" as a+non-edit) lands in exactly one place.++# Why counters, not ratios++A ratio is a function of (numerator, denominator). The denominator+wanted changes by slice - "tokens per edit across this+project" vs "across this user" vs "across this week" — so we keep the+inputs and let the consumer compose.+"""++from __future__ import annotations++from dataclasses import dataclass++from agentplay._core.ingestion.coding_agent.file_paths import extract_file_path as _file_path+from agentplay._core.ingestion.coding_agent.spans import SpanData++# Tool taxonomy used by the counter walk.+#+# SEARCH_TOOLS: "Search" and "ListDir" are+# the canonical names Cursor's SemanticSearch and Kiro's list_directory+# alias to -- tool_taxonomy.TOOL_ALIASES also produces them for Copilot,+# Copilot-in-VS-Code and OpenCode. Missing them here meant search_count+# undercounted every non-Claude, non-Codex agent's exploration activity;+# those tool spans still hit tool_count, just no bucket.+EDIT_TOOLS: frozenset[str] = frozenset({"Edit", "MultiEdit", "Write"})+READ_TOOLS: frozenset[str] = frozenset({"Read", "NotebookRead"})+SEARCH_TOOLS: frozenset[str] = frozenset({"Grep", "Glob", "Search", "ListDir"})+SHELL_TOOLS: frozenset[str] = frozenset({"Bash", "BashOutput"})++# Taxonomy for the ordering-dependent metrics (read-before-edit and+# full-rewrite). Deliberately distinct from the bucket sets above: read-first+# folds search / web tools into "reads", and the edit set excludes `Write`+# (a full rewrite, counted on its own) and `MultiEdit`.+RF_READ_TOOLS: frozenset[str] = frozenset(+ {"Read", "Glob", "Grep", "Search", "ListDir", "WebFetch", "WebSearch"}+)+RF_EDIT_TOOLS: frozenset[str] = frozenset({"Edit", "NotebookEdit"})+RF_WRITE_TOOLS: frozenset[str] = frozenset({"Write"})+++@dataclass(frozen=True, slots=True)+class TaskCounters:+ """Per-task counter snapshot."""++ tool_count: int+ edit_count: int+ read_count: int+ search_count: int+ shell_count: int+ error_count: int+ max_turn_prompt_tokens: int+ cache_read_total: int+ cache_write_total: int+ # Ordering-dependent (read-before-edit, full-rewrite).+ edit_op_count: int # Edit / NotebookEdit calls — read-first denominator+ blind_edit_count: int # edits to a file not read earlier in the task+ full_rewrite_count: int # Write calls — full-file rewrites+ mutation_count: int # Edit / NotebookEdit / Write — full-rewrite denominator+ # Context-health signals (duplicate reads, repeated edits, context+ # resets, context pressure, useful edits). Counts only; ratios are+ # derived by the consumer.+ duplicate_read_count: int # reads of an already-read file+ repeated_edit_count: int # consecutive Edit/NotebookEdit to the same file+ useful_edit_count: int # successful mutations (for tokens-per-useful-edit)+ context_reset_count: int # turns where prompt dropped >40%+ context_steep_count: int # turns where prompt grew >50% (pressure numerator)+ context_comparison_count: int # turn-to-turn comparisons (pressure denominator)+++def compute_task_counters(+ spans: list[SpanData],+ *,+ start_turn: int,+ end_turn: int,+) -> TaskCounters:+ """Walk a session's spans → counters for the named turn range.++ Args:+ spans: full session span list. Filtered to `[start_turn,+ end_turn]` internally — callers don't pre-filter.+ start_turn: 1-indexed first turn of the task (inclusive).+ end_turn: 1-indexed last turn of the task (inclusive).++ Returns:+ `TaskCounters`. Counts that don't apply (no edits at all) are+ zero, never None.+ """+ tool_count = edit = read = search = shell = errors = 0+ max_prompt = 0+ cache_read = cache_write = 0+ # (start_time, tool, file_path, success) for the task's tool spans, walked+ # in chronological order for the order-dependent metrics.+ ordered: list[tuple[object, str, str | None, bool]] = []+ # (turn_num, prompt_tokens) for context resets / pressure.+ turn_prompts: list[tuple[int, int]] = []++ def in_range(n: int) -> bool:+ return start_turn <= n <= end_turn++ for s in spans:+ # Turn span — picks up peak prompt + per-turn cache numbers.+ if s.name.startswith("Turn "):+ n = _parse_turn_num(s.name)+ if n is None or not in_range(n):+ continue+ prompt = int(s.attributes.get("llm.token_count.prompt", 0))+ if prompt > max_prompt:+ max_prompt = prompt+ cache_read += int(s.attributes.get("llm.token_count.cache_read", 0))+ cache_write += int(s.attributes.get("llm.token_count.cache_write", 0))+ turn_prompts.append((n, prompt))+ continue++ # Tool span — counts, attributed to the parent turn.+ tool = s.attributes.get("tool.name")+ if not tool or not s.parent_id:+ continue+ n = _turn_num_from_parent(s.parent_id)+ if n is None or not in_range(n):+ continue+ tool_count += 1+ if tool in EDIT_TOOLS:+ edit += 1+ elif tool in READ_TOOLS:+ read += 1+ elif tool in SEARCH_TOOLS:+ search += 1+ elif tool in SHELL_TOOLS:+ shell += 1+ if s.status_code == "ERROR":+ errors += 1+ ordered.append(+ (s.start_time, tool, _file_path(s.attributes.get("input.value")), s.status_code == "OK")+ )++ ow = _ordered_walk_metrics(ordered)+ tm = _turn_series_metrics(turn_prompts)++ return TaskCounters(+ tool_count=tool_count,+ edit_count=edit,+ read_count=read,+ search_count=search,+ shell_count=shell,+ error_count=errors,+ max_turn_prompt_tokens=max_prompt,+ cache_read_total=cache_read,+ cache_write_total=cache_write,+ edit_op_count=ow["edit_op_count"],+ blind_edit_count=ow["blind_edit_count"],+ full_rewrite_count=ow["full_rewrite_count"],+ mutation_count=ow["mutation_count"],+ duplicate_read_count=ow["duplicate_read_count"],+ repeated_edit_count=ow["repeated_edit_count"],+ useful_edit_count=ow["useful_edit_count"],+ context_reset_count=tm["context_reset_count"],+ context_steep_count=tm["context_steep_count"],+ context_comparison_count=tm["context_comparison_count"],+ )+++def _ordered_walk_metrics(+ ordered: list[tuple[object, str, str | None, bool]],+) -> dict[str, int]:+ """Order-dependent tool metrics from time-ordered (tool, file, success) calls.++ Computes the read-first and full-rewrite counts, duplicate reads,+ repeated edits to the same file, and the `useful` count for+ tokens-per-useful-edit, all in one pass:++ - a file Read (incl. search/web) seeds the read-set; an `Edit`/`NotebookEdit`+ on a file not yet in it is a "blind edit"; `Write` is a full rewrite.+ - re-reading an already-read file is a duplicate read.+ - a consecutive `Edit`/`NotebookEdit` to the same file is a repeated edit.+ - a successful mutation (`Edit`/`NotebookEdit`/`Write`) is a useful edit.+ """+ read_files: set[str] = set()+ seen_reads: set[str] = set()+ blind = edit_ops = writes = mutations = 0+ duplicate_reads = repeated_edits = useful_edits = 0+ last_edit_file: str | None = None++ for _, tool, fp, ok in sorted(ordered, key=lambda x: x[0]):+ is_edit = tool in RF_EDIT_TOOLS+ is_write = tool in RF_WRITE_TOOLS+ if is_edit:+ edit_ops += 1+ mutations += 1+ if fp and fp == last_edit_file:+ repeated_edits += 1+ last_edit_file = fp+ else:+ if is_write:+ writes += 1+ mutations += 1+ last_edit_file = None+ if (is_edit or is_write) and ok:+ useful_edits += 1++ if not fp:+ continue+ if tool in RF_READ_TOOLS:+ if fp in seen_reads:+ duplicate_reads += 1+ seen_reads.add(fp)+ read_files.add(fp)+ elif is_edit and fp not in read_files:+ blind += 1++ return {+ "edit_op_count": edit_ops,+ "blind_edit_count": blind,+ "full_rewrite_count": writes,+ "mutation_count": mutations,+ "duplicate_read_count": duplicate_reads,+ "repeated_edit_count": repeated_edits,+ "useful_edit_count": useful_edits,+ }+++def _turn_series_metrics(turn_prompts: list[tuple[int, int]]) -> dict[str, int]:+ """Context resets + pressure counters from the task's per-turn prompt series.++ A >40% prompt drop between consecutive turns is a reset; a >50% jump is+ a steep increase. The pressure ratio (steep / comparisons) is derived+ by the consumer.+ """+ prompts = [p for _, p in sorted(turn_prompts, key=lambda x: x[0])]+ resets = steep = comparisons = 0+ for i in range(1, len(prompts)):+ prev, curr = prompts[i - 1], prompts[i]+ if prev > 1000 and curr < prev * 0.6:+ resets += 1+ if prev > 0:+ comparisons += 1+ if curr > prev * 1.5:+ steep += 1+ return {+ "context_reset_count": resets,+ "context_steep_count": steep,+ "context_comparison_count": comparisons,+ }+++def session_tool_distribution(spans: list[SpanData]) -> dict[str, int]:+ """Per-named-tool span counts across the whole session.++ The session-level sibling of `slash_commands` / `skills_used`: an opaque+ count distribution kept in the session payload rather than as a+ scalar counter, since a JSON map can't be summed like one.++ Counts every tool span (any `tool.name`), session-wide — no turn-range+ filter, unlike `compute_task_counters` which is scoped to one task.+ """+ tools: dict[str, int] = {}+ for s in spans:+ tool = s.attributes.get("tool.name")+ if tool:+ tools[tool] = tools.get(tool, 0) + 1+ return tools+++def _parse_turn_num(name: str) -> int | None:+ """`Turn N` → N. Returns None when the suffix isn't an int."""+ parts = name.split()+ if len(parts) < 2:+ return None+ try:+ return int(parts[1])+ except ValueError:+ return None+++def _turn_num_from_parent(parent_id: str) -> int | None:+ """Extract N from `{trace_id}:turn:{N}` — the convention every parser emits."""+ head, _, tail = parent_id.rpartition(":turn:")+ if not head or not tail:+ return None+ try:+ return int(tail)+ except ValueError:+ return None+++__all__ = [+ "EDIT_TOOLS",+ "READ_TOOLS",+ "SEARCH_TOOLS",+ "SHELL_TOOLS",+ "TaskCounters",+ "compute_task_counters",+ "session_tool_distribution",+]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/native_operations.py b/python/src/agentplay/_core/ingestion/coding_agent/native_operations.pynew file mode 100644index 0000000..6a92304--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/native_operations.py@@ -0,0 +1,271 @@+"""Decode literal, serial Codex tool bundles without evaluating JavaScript.++Only statements that emit their own awaited tool result are supported. Branches,+loops, concurrency, computed arguments and extra output remain unsupported: their+textual call order cannot prove which result belongs to which operation.+"""++from __future__ import annotations++import json+import re+from typing import Any++from agentplay._core.ingestion.coding_agent.produced import is_pr_creation_tool++_TOKEN = re.compile(+ r'\s*("(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[A-Za-z_$][\w$]*|[^\s])'+)+_NAME = re.compile(r"[A-Za-z_$][\w$]*")+_TOOLS = {"exec_command", "write_stdin", "apply_patch"}+# `text(typeof R === "string" ? R : JSON.stringify(R))` for a binding R emits+# exactly what `text(R)` emits, once, so it proves no more than the plain form.+_STRINGIFIED = [m[1] for m in _TOKEN.finditer('typeof R === "string" ? R : JSON.stringify(R)')]+++def literal_operations(code: str) -> list[tuple[str, Any]]:+ """Return ordered literal calls only when the entire emitted script is safe.++ Supports ``text(await tools.NAME(JSON))`` and an immediately emitted local+ binding. A ``const NAME = <literal>;`` binding may stand in for a literal+ argument (Codex binds a patch before ``tools.apply_patch(NAME)``); it emits+ nothing, so it cannot shift the result order. Unquoted object keys are+ accepted; expressions are not. Unsupported input returns an empty list and+ must retain its original native tool record.+ """+ if not isinstance(code, str) or len(code) > 2_000_000:+ return []+ code = re.sub(r"\A\s*// @exec:[^\n]*\n", "", code)+ tokens = [match[1] for match in _TOKEN.finditer(code)]+ pos = 0+ literals: dict[str, Any] = {}++ def take(expected: str | None = None) -> str:+ nonlocal pos+ token = tokens[pos]+ pos += 1+ if expected is not None and token != expected:+ raise ValueError("unsupported expression")+ return token++ def value(depth: int = 0) -> Any:+ if depth > 20:+ raise ValueError("nested literal limit")+ token = take()+ if token in literals:+ return literals[token]+ if token == "{":+ result = {}+ while tokens[pos] != "}":+ key = take()+ key = json.loads(key) if key.startswith('"') else key+ if not isinstance(key, str) or not _NAME.fullmatch(key):+ raise ValueError("unsupported key")+ if key in result or key in {"__proto__", "constructor", "prototype"}:+ raise ValueError("ambiguous object")+ take(":")+ result[key] = value(depth + 1)+ if tokens[pos] != "}":+ take(",")+ take("}")+ return result+ if token == "[":+ result = []+ while tokens[pos] != "]":+ result.append(value(depth + 1))+ if tokens[pos] != "]":+ take(",")+ take("]")+ return result+ return json.loads(token)++ operations = []+ try:+ while pos < len(tokens):+ binding = None+ if tokens[pos] in {"const", "let"}:+ take()+ binding = take()+ if (+ not _NAME.fullmatch(binding)+ or binding in {"tools", "text", "true", "false", "null"}+ or binding in literals+ ):+ return []+ take("=")+ if tokens[pos] != "await":+ literals[binding] = value()+ if pos < len(tokens) and tokens[pos] == ";":+ take()+ continue+ else:+ take("text")+ take("(")+ take("await")+ take("tools")+ take(".")+ tool = take()+ if tool not in _TOOLS and not is_pr_creation_tool(tool):+ return []+ take("(")+ args = value()+ take(")")+ if binding is None:+ take(")")+ else:+ if pos < len(tokens) and tokens[pos] == ";":+ take()+ take("text")+ take("(")+ stringified = [binding if t == "R" else t for t in _STRINGIFIED]+ if tokens[pos : pos + len(stringified)] == stringified:+ pos += len(stringified)+ else:+ take(binding)+ take(")")+ if pos < len(tokens) and tokens[pos] == ";":+ take()+ if tool == "apply_patch":+ if not isinstance(args, str):+ return []+ elif not isinstance(args, dict):+ return []+ operations.append((tool, args))+ if len(operations) > 100:+ return []+ except (ValueError, IndexError, RecursionError):+ return []+ return operations+++def literal_results(output: object, count: int) -> list[dict[str, Any]]:+ """Validate one structured host result per emitted operation, in order."""+ if not isinstance(output, list):+ return []+ if (+ output+ and isinstance(output[0], dict)+ and re.fullmatch(+ r"Script completed\nWall time [\d.]+ seconds\nOutput:\n?",+ str(output[0].get("text", "")),+ )+ ):+ output = output[1:]+ if len(output) != count:+ return []+ results = []+ for block in output:+ if not isinstance(block, dict) or block.get("type") not in {+ "text",+ "input_text",+ "output_text",+ }:+ return []+ try:+ result = json.loads(block["text"])+ except (KeyError, TypeError, ValueError):+ return []+ if not isinstance(result, dict):+ return []+ results.append(result)+ return results+++def shell_result(output: str) -> dict[str, Any] | None:+ """Decode structured or native textual host metadata before the output body."""+ try:+ result = json.loads(output)+ except (ValueError, TypeError):+ result = None+ if isinstance(result, dict):+ return result+ if not isinstance(output, str):+ return None+ parts = re.split(r"\n(?:Final output|Output):\n", output, maxsplit=1)+ if len(parts) != 2:+ return None+ header, body = parts+ exited = re.search(r"^Process exited with code (\d+)$", header, re.MULTILINE)+ running = re.search(r"^Process running with session ID (\d+)$", header, re.MULTILINE)+ if bool(exited) == bool(running):+ return None+ return {+ "output": body,+ "wall_time_seconds": 0,+ "exit_code": int(exited[1]) if exited else None,+ "session_id": int(running[1]) if running else None,+ }+++class ProcessEvidence:+ """Correlate native shell completion with its launching tool within a session.++ Retains references to original tool records so later polls update the launch+ evidence without attributing creation to a poll or duplicating tool events.+ Interactive input invalidates the pending command; process reuse replaces it.+ The map is private to a single transcript parse, never shared across sessions.+ """++ def __init__(self) -> None:+ self.pending: dict[int, dict] = {}++ def observe(self, tool: dict, args: Any, result: dict) -> None:+ """Attach complete successful output to its original launch record."""+ from agentplay._core.ingestion.coding_agent.produced import creation_output_attributes++ name = tool["name"]+ if name not in {"exec_command", "write_stdin"} or not isinstance(args, dict):+ return+ process_id = result.get("session_id") if name == "exec_command" else args.get("session_id")+ origin = tool+ if name == "write_stdin":+ if type(process_id) is not int:+ return+ origin = self.pending.get(process_id)+ if origin is None:+ return+ if args.get("chars", "") or args.get("terminate"):+ self.pending.pop(process_id, None)+ return+ elif type(process_id) is int:+ self.pending.pop(process_id, None)+ if result.get("isError") is True:+ if type(process_id) is int:+ self.pending.pop(process_id, None)+ origin["pr.create.output_url"] = ""+ origin["is_error"] = True+ origin["provenance.capture"] = "failed_process"+ return+ exit_code = result.get("exit_code")+ output = result.get("output")+ if not isinstance(output, str) or "wall_time_seconds" not in result:+ return+ output = origin.get("_process_output", "") + output+ if len(output) > 2_000_000:+ if type(process_id) is int:+ self.pending.pop(process_id, None)+ origin["pr.create.output_url"] = ""+ origin["is_error"] = True+ return+ origin["_process_output"] = output+ # A running chunk is never a completed create, even if it prints a URL.+ origin["pr.create.output_url"] = ""+ origin["is_error"] = True+ if exit_code is None and type(process_id) is int:+ origin["provenance.capture"] = "pending_process"+ if len(self.pending) < 1000:+ self.pending[process_id] = origin+ return+ if type(process_id) is int:+ self.pending.pop(process_id, None)+ if type(exit_code) is int:+ origin["provenance.capture"] = "completed_process"+ if type(exit_code) is int and exit_code == 0:+ origin.update(+ creation_output_attributes(+ output, origin.get("pr.create.provider"), origin.get("pr.create.repository")+ )+ )+ origin["output"] = output[:2000]+ origin["end_ts"] = tool["end_ts"]+ origin["is_error"] = Falsediff --git a/python/src/agentplay/_core/ingestion/coding_agent/produced.py b/python/src/agentplay/_core/ingestion/coding_agent/produced.pynew file mode 100644index 0000000..9b67a93--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/produced.py@@ -0,0 +1,570 @@+"""PR creation evidence shared by raw transcript parsing and structured tool records."""++from __future__ import annotations++import ast+from dataclasses import dataclass, field+from hashlib import sha256+import json+import re+import shlex++from agentplay._core.ingestion.coding_agent.spans import SpanData++_GH_PR = re.compile(r"https?://github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pull/(\d+)")+_GL_MR = re.compile(+ r"https?://(gitlab[A-Za-z0-9_.-]*\.[a-z]+)/([A-Za-z0-9_./-]+)/-/merge_requests/(\d+)"+)+_SHELL_TOOLS = {"bash", "shell"}+++@dataclass(frozen=True, slots=True)+class CreatedPR:+ """A successful create invocation's single output URL and observed turn."""++ provider: str+ repo_name: str+ number: int+ url: str+ source_event_id: str | None = field(default=None, compare=False)+ command_sha256: str | None = field(default=None, compare=False)+ created_in_turn: int | None = None+++def _command_value(value: object) -> str:+ """Unwrap native shell args or a single literal Codex Desktop tool call."""+ if isinstance(value, str):+ try:+ parsed = json.loads(value)+ except (ValueError, RecursionError):+ pass+ else:+ value = parsed if isinstance(parsed, dict) else None+ if isinstance(value, dict):+ value = value.get("command") or value.get("cmd")+ if not isinstance(value, str):+ return ""+ # Desktop wrappers can also arrive inside native shell args. Parse only+ # one exact invocation after unwrapping; never search arbitrary JavaScript.+ match = re.fullmatch(+ r"\s*(?:(?:const|let)\s+[A-Za-z_$][\w$]*\s*=\s*)?await\s+tools\.exec_command\((\{.*\})\)\s*;?\s*",+ value,+ re.DOTALL,+ )+ if not match:+ return value+ try:+ args = json.loads(match.group(1))+ except (ValueError, RecursionError):+ return ""+ command = args.get("command") or args.get("cmd")+ return command if isinstance(command, str) else ""+++def command_text(span: SpanData) -> str:+ """Read the recorded command without coercing arbitrary structured input."""+ return _command_value(span.input_value)+++def _ordinary_body_path(value: str) -> bool:+ """Accept literal file paths while excluding stream/device namespaces."""+ normalized = value.replace("\\", "/")+ parts = [part for part in normalized.split("/") if part not in {"", "."}]+ if not parts or ".." in parts or normalized.startswith(("//./", "//?/")):+ return False+ if normalized.startswith("/") and parts[0] in {"dev", "proc", "sys"}:+ return False+ return parts[-1].split(".")[0].upper() not in {"CON", "CONIN$", "CONOUT$", "PRN", "AUX", "NUL"}+++def _silent_body_file(match: re.Match[str]) -> str:+ """Mask only a literal pathlib write, never arbitrary Python stdout."""+ try:+ nodes = ast.parse(match.group(2)).body+ except (SyntaxError, ValueError, RecursionError):+ return match.group(0)+ if len(nodes) != 2:+ return match.group(0)+ imported, expression = nodes+ if not (+ isinstance(imported, ast.ImportFrom)+ and imported.level == 0+ and imported.module == "pathlib"+ and len(imported.names) == 1+ and imported.names[0].name == "Path"+ and imported.names[0].asname is None+ and isinstance(expression, ast.Expr)+ and isinstance(expression.value, ast.Call)+ ):+ return match.group(0)+ call = expression.value+ if not (isinstance(call.func, ast.Attribute) and call.func.attr == "write_text"):+ return match.group(0)+ path = call.func.value+ if not (+ isinstance(path, ast.Call)+ and isinstance(path.func, ast.Name)+ and path.func.id == "Path"+ and len(path.args) == 1+ and isinstance(path.args[0], ast.Constant)+ and isinstance(path.args[0].value, str)+ and _ordinary_body_path(path.args[0].value)+ and not path.keywords+ and len(call.args) == 1+ and isinstance(call.args[0], ast.Constant)+ and isinstance(call.args[0].value, str)+ and all(+ k.arg == "encoding"+ and isinstance(k.value, ast.Constant)+ and k.value.value in {"utf-8", "utf8"}+ for k in call.keywords+ )+ ):+ return match.group(0)+ return ""+++def _literal_shell(command: str) -> str:+ """Mask only quoted literal here-documents in known body-file idioms.++ Arbitrary command substitutions, unquoted heredocs and shell evaluation+ remain unsupported. The original command, not this analysis copy, is hashed.+ """+ command = command.replace("\\\n", "")+ command = re.sub(+ r"""\$\(gh auth token --user [A-Za-z0-9_-]+\)""",+ "credential-from-provider",+ command,+ )+ command = re.sub(+ r'''"\$\(cat\s+<<'([A-Za-z_][A-Za-z_0-9]*)'\n.*?\n\1\n\)"''',+ '"literal-body"',+ command,+ flags=re.DOTALL,+ )+ command = re.sub(+ r"(?m)^cat\s+>\s+(?P<body_file>[/A-Za-z0-9_.-]+)\s+<<'(?P<eof>[A-Za-z_][A-Za-z_0-9]*)'\n.*?\n(?P=eof)(?:\n|$)",+ lambda match: "" if _ordinary_body_path(match.group("body_file")) else match.group(0),+ command,+ flags=re.DOTALL,+ )+ command = re.sub(+ r"(?m)^python(?:3(?:\.\d+)?)? - <<'([A-Za-z_][A-Za-z_0-9]*)'\n(.*?)\n\1\n(?=\S)",+ _silent_body_file,+ command,+ flags=re.DOTALL,+ )+ return command if "$(" not in command and "`" not in command else ""+++def _create_invocation(command: str) -> tuple[str, list[str], dict[str, str]] | None:+ """Accept a direct create, optionally after cd or git add/commit/push; never execute.++ A head/tail filter requires guarded pipefail; other pipelines and multiple+ output-producing commands are ambiguous. Quoted arguments may contain substitutions.+ Quoted mentions in Python, echo, --body and comments are not invocations.+ """+ try:+ lexer = shlex.shlex(+ _literal_shell(command).strip(), posix=True, punctuation_chars=";&|()<>\n"+ )+ lexer.whitespace = " \t\r"+ lexer.whitespace_split = True+ tokens = list(lexer)+ except ValueError:+ return None+ pipefail = False+ if len(tokens) >= 4 and tokens[:1] == ["set"] and tokens[2] == "pipefail" and tokens[3] == "&&":+ pipefail = tokens[1] in {"-o", "-eo", "-euo", "-uo"}+ if not pipefail:+ return None+ tokens = tokens[4:]+ # Only non-PR preparatory commands may surround a single create. No echo,+ # view, branch, loop, function, OR fallback or arbitrary executable can+ # manufacture the URL subsequently used as creation evidence.+ parts = []+ current = []+ for token in tokens:+ if token in {"&&", ";"} or token.strip("\n") == "":+ if current:+ parts.append((current, token))+ current = []+ else:+ current.append(token)+ if current:+ parts.append((current, None))+ creates = []+ for part, separator in parts:+ if part[:1] == ["set"] and len(part) == 2 and re.fullmatch(r"-[eu]+", part[1]):+ continue+ if (+ len(part) == 3+ and part[0] == "set"+ and part[1] in {"-o", "-eo", "-euo", "-uo"}+ and part[2] == "pipefail"+ ):+ pipefail = True+ continue+ if part[:1] == ["cd"] and len(part) == 2:+ continue+ if len(part) == 1 and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=[^;&|()<>]*", part[0]):+ continue+ # `git add/commit/push && gh pr create`: git prefixes remote text with+ # `remote:` and prints no PR URL of its own, so the single-URL line rule+ # below still attributes only the create's output. `&&` makes the create+ # conditional on them; no redirect, pipe or fallback may ride along.+ if (+ not creates+ and separator == "&&"+ and part[:1] == ["git"]+ and part[1:2] in (["add"], ["commit"], ["push"])+ and not any(re.fullmatch(r"[;&|()<>]+", token) for token in part)+ ):+ continue+ creates.append(part)+ if len(creates) != 1:+ return None+ tokens = creates[0]+ if tokens[:1] == ["env"]:+ tokens = tokens[1:]+ environment = {}+ while tokens and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", tokens[0], re.DOTALL):+ key, value = tokens[0].split("=", 1)+ environment[key] = value+ tokens = tokens[1:]+ if "|" in tokens:+ if not pipefail or tokens.count("|") != 1:+ return None+ split = tokens.index("|")+ suffix = tokens[split + 1 :]+ if (+ not suffix+ or suffix[0] not in {"tail", "head"}+ or not all(re.fullmatch(r"-?\d+|-n\d*", flag) for flag in suffix[1:])+ ):+ return None+ tokens = tokens[:split]+ if tokens[-3:] == ["2", ">&", "1"]:+ tokens = tokens[:-3]+ if any(+ token+ in {+ "\n",+ "--web",+ "--dry-run",+ ";",+ "&&",+ "||",+ "|",+ "&",+ "(",+ ")",+ ">",+ ">>",+ "<",+ "<<",+ ">&",+ }+ for token in tokens+ ):+ return None+ if tokens[:3] == ["gh", "pr", "create"]:+ return "github", tokens, environment+ if tokens[:3] == ["glab", "mr", "create"]:+ return "gitlab", tokens, environment+ return None+++def _create_provider(command: str) -> str | None:+ invocation = _create_invocation(command)+ return invocation[0] if invocation else None+++def _requested_github_repository(tokens: list[str], environment: dict[str, str]) -> str | None:+ """Read explicit repository selectors without mistaking body text for flags.++ None means cwd determines the repository; an empty value means an explicit+ selector was malformed or ambiguous and cannot support creation evidence.+ """+ repos = []+ value_flags = {+ "-a",+ "--assignee",+ "-B",+ "--base",+ "-b",+ "--body",+ "-F",+ "--body-file",+ "-H",+ "--head",+ "-l",+ "--label",+ "-m",+ "--milestone",+ "-p",+ "--project",+ "--recover",+ "-r",+ "--reviewer",+ "-T",+ "--template",+ "-t",+ "--title",+ }+ i = 3+ while i < len(tokens):+ arg = tokens[i]+ if arg in {"-R", "--repo"}:+ if i + 1 >= len(tokens):+ return ""+ repos.append(tokens[i + 1])+ i += 2+ elif arg.startswith("--repo="):+ repos.append(arg.split("=", 1)[1])+ i += 1+ elif arg.startswith("-R") and len(arg) > 2:+ repos.append(arg[2:])+ i += 1+ elif arg in value_flags:+ i += 2+ else:+ i += 1+ # The explicit CLI flag overrides GH_REPO. Multiple flags are deliberately+ # not resolved by guessing the command-line parser's precedence.+ if len(repos) > 1:+ return ""+ selected = repos[0] if repos else environment.get("GH_REPO")+ if environment.get("GH_HOST", "github.com").lower() != "github.com":+ return ""+ if selected is None:+ return None+ selected = selected.removeprefix("github.com/")+ return selected if re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", selected) else ""+++def _command_sha256(command: str) -> str | None:+ try:+ return sha256(command.encode()).hexdigest()+ except UnicodeEncodeError:+ # JSON can contain unpaired surrogates. Preserve the observation while+ # leaving its byte digest unknown instead of hashing replacement bytes.+ return None+++def is_pr_creation_tool(tool_name: str) -> bool:+ """Recognize the explicit GitHub MCP creation operation, not read tools."""+ return bool(+ re.fullmatch(+ r"(?:(?:functions|tools)\.)?(?:mcp__github__|github[._])create_pull_request", tool_name+ )+ )+++def _github_api_creation_repo(command: str) -> str | None:+ """Recognize an explicit, single GitHub REST POST via gh api."""+ try:+ lexer = shlex.shlex(_literal_shell(command), posix=True, punctuation_chars=";&|()<>\n")+ lexer.whitespace = " \t\r"+ lexer.whitespace_split = True+ tokens = list(lexer)+ except ValueError:+ return None+ if tokens[:2] != ["gh", "api"]:+ return None+ method = None+ endpoint = None+ i = 2+ while i < len(tokens):+ token = tokens[i]+ if token in {+ "--method",+ "-X",+ "-f",+ "-F",+ "--field",+ "--raw-field",+ "--input",+ "-H",+ "--header",+ }:+ if i + 1 >= len(tokens):+ return None+ if token in {"--method", "-X"}:+ if method is not None:+ return None+ method = tokens[i + 1]+ i += 2+ elif endpoint is None:+ endpoint = token+ i += 1+ else:+ return None+ match = re.fullmatch(+ r"(?:https://api\.github\.com/|/)?repos/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pulls",+ endpoint or "",+ )+ return match[1] if method == "POST" and match else None+++def creation_command_attributes(value: object, tool_name: str = "") -> dict[str, str]:+ """Compute invocation evidence before parsers truncate long tool input.++ Retain the provider and full command digest, never another command/body copy.+ """+ if is_pr_creation_tool(tool_name):+ try:+ args = json.loads(value) if isinstance(value, str) else value+ except (ValueError, RecursionError):+ args = None+ if isinstance(args, dict):+ repo = f"{args.get('owner', '')}/{args.get('repo', '')}"+ if re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo):+ return {"pr.create.provider": "github", "pr.create.repository": repo}+ return {"pr.create.capture": "unrecognized_creation_text"}+ command = _command_value(value)+ api_repo = _github_api_creation_repo(command)+ if api_repo:+ digest = _command_sha256(command)+ return {+ "pr.create.provider": "github",+ "pr.create.repository": api_repo,+ **({"pr.create.command_sha256": digest} if digest else {}),+ }+ invocation = _create_invocation(command)+ provider = invocation[0] if invocation else None+ if not provider:+ return (+ {"pr.create.capture": "unrecognized_creation_text"}+ if re.search(r"\b(?:gh\s+pr|glab\s+mr)\s+create\b", command)+ else {}+ )+ requested = (+ _requested_github_repository(invocation[1], invocation[2]) if provider == "github" else None+ )+ digest = _command_sha256(command)+ return {+ "pr.create.provider": provider,+ **({"pr.create.requested_repository": requested} if requested is not None else {}),+ **({"pr.create.capture": "unrecognized_creation_text"} if requested == "" else {}),+ **({"pr.create.command_sha256": digest} if digest else {}),+ }+++def _creation_match(output: object, provider: str) -> re.Match | None:+ if not isinstance(output, str):+ return None+ # A failed create often prints an existing PR URL. Inspect the full result,+ # including any error or second URL beyond a parser's display limit.+ if re.search(r"^Process exited with code [1-9]\d*$", output, re.MULTILINE):+ return None+ if re.search(r"already exists|failed|error:", output, re.IGNORECASE):+ return None+ matches = list((_GH_PR if provider == "github" else _GL_MR).finditer(output))+ if len(matches) != 1:+ return None+ match = matches[0]+ return match if match.group(0) in [line.strip() for line in output.splitlines()] else None+++def creation_output_attributes(+ output: object, provider: str | None, repository: str | None = None+) -> dict[str, str]:+ """Retain validated URL evidence before display truncation, not the raw output."""+ if provider not in {"github", "gitlab"}:+ return {}+ if repository is not None:+ return {"pr.create.output_url": _structured_creation_url(output, repository)}+ match = _creation_match(output, provider)+ # An explicit empty result prevents falling back to a truncated prefix that+ # may hide a later error or another URL. Missing metadata remains legacy.+ return {"pr.create.output_url": match.group(0) if match else ""}+++def _structured_creation_url(output: object, repository: str) -> str:+ """Validate one successful MCP creation response against its request repo."""+ try:+ value = json.loads(output) if isinstance(output, str) else output+ if isinstance(value, dict) and "content" in value:+ if value.get("isError") is not None and value.get("isError") is not False:+ return ""+ value = value["content"]+ if isinstance(value, str):+ value = json.loads(value)+ if isinstance(value, list):+ if len(value) != 1 or not isinstance(value[0], dict) or value[0].get("type") != "text":+ return ""+ value = json.loads(value[0]["text"])+ if not isinstance(value, dict) or value.get("error") or value.get("isError"):+ return ""+ url = value.get("html_url") or value.get("url")+ match = _GH_PR.fullmatch(url) if isinstance(url, str) else None+ if not match or match[1].lower() != repository.lower() or int(match[2]) <= 0:+ return ""+ number = value.get("number")+ if number is not None and (type(number) is not int or number != int(match[2])):+ return ""+ return url+ except (ValueError, TypeError, KeyError, RecursionError):+ return ""+++def extract_created_prs(spans: list[SpanData]) -> list[CreatedPR]:+ """Return only successful direct creates with one unambiguous output URL."""+ turns = {}+ for span in spans:+ match = re.fullmatch(r"Turn (\d+)", span.name)+ if match:+ turns[span.span_id] = int(match[1])+ seen: set[str] = set()+ result = []+ for span in spans:+ if span.status_code != "OK":+ continue+ structured = span.attributes.get("pr.create.repository")+ if (span.tool_name or "").lower() not in _SHELL_TOOLS and not (+ structured and is_pr_creation_tool(span.tool_name or "")+ ):+ continue+ command = command_text(span)+ provider = span.attributes.get("pr.create.provider") or _create_provider(command)+ if provider not in {"github", "gitlab"}:+ continue+ output = span.attributes.get("pr.create.output_url", span.output_value)+ match = _creation_match(output, provider)+ if match is None:+ continue+ if provider == "github":+ repo, number = match.groups()+ url = f"https://github.com/{repo}/pull/{number}"+ else:+ host, repo, number = match.groups()+ url = f"https://{host}/{repo}/-/merge_requests/{number}"+ requested = span.attributes.get("pr.create.requested_repository")+ if requested is None and provider == "github":+ invocation = _create_invocation(command)+ requested = (+ _requested_github_repository(invocation[1], invocation[2]) if invocation else None+ )+ if requested is not None and (not requested or requested.lower() != repo.lower()):+ continue+ if url in seen or int(number) <= 0:+ continue+ seen.add(url)+ digest = span.attributes.get("pr.create.command_sha256")+ if not isinstance(digest, str) or re.fullmatch(r"[0-9a-f]{64}", digest) is None:+ # Only the parser saw the complete source command. An unmarked+ # historical span may contain a valid-looking truncated prefix.+ digest = None+ result.append(+ CreatedPR(+ provider=provider,+ repo_name=repo,+ number=int(number),+ url=url,+ source_event_id=span.span_id,+ command_sha256=digest,+ created_in_turn=turns.get(span.parent_id),+ )+ )+ return resultdiff --git a/python/src/agentplay/_core/ingestion/coding_agent/session_pure.py b/python/src/agentplay/_core/ingestion/coding_agent/session_pure.pynew file mode 100644index 0000000..fbbd94f--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/session_pure.py@@ -0,0 +1,1143 @@+"""Session-level compute - pure, no LLM.++Rolls a parsed span list up into session metrics: token+aggregation (fresh / cache-read / cache-write split), the three whole-session+waste components (interrupt / repeat / retry) + floor drift, model resolution,+automation detection, and the **derived behaviour metrics** a session+summary exposes (efficiency score, the read/edit+behaviour ratios, error rate, tool-calls-per-turn, and the tool / skill+distributions).++The public entry for callers is :func:`build_session_metrics`, which returns+the session metrics dict.++SESSION cost is NOT computed here: a consumer may recompute ``total_cost_usd``+from tokens + model, so only token components are emitted. The one+dollar-denominated exception is the marginal-waste trio+(``*_marginal_usd``, :func:`_marginal_waste_usd`): it must price per-turn+token components that never leave this layer, so it is computed here off the+shared rate card (``agentplay._core.pricing``).+"""++from __future__ import annotations++import json+from typing import Any, NamedTuple++from agentplay._core.ingestion.coding_agent.edit_lines import edit_line_counts+from agentplay._core.ingestion.coding_agent.file_paths import extract_file_path as _file_path+from agentplay._core.ingestion.coding_agent.metrics import (+ RF_EDIT_TOOLS,+ RF_READ_TOOLS,+ RF_WRITE_TOOLS,+ session_tool_distribution,+)+from agentplay._core.ingestion.coding_agent.skill_names import normalize_skill_name+from agentplay._core.ingestion.coding_agent.spans import (+ SpanData,+ last_genuine_model_id,+ model_id_or_none,+)+from agentplay._core.pricing import MODEL_RATES, normalize_model_key++# ── automation detection ───────────────────────────────────────────+_AUTOMATION_MARKERS = (+ "sandbox reminder",+ "you are inside a remote e2b",+ "/workspace/repo",+)+_AUTOMATION_SCAN_SPANS = 40 # markers live in early system/setup content+++def detect_automated(spans: list[SpanData]) -> bool:+ """True when early span content carries an automation marker.++ Bounded prefix scan (first ``_AUTOMATION_SCAN_SPANS`` spans, string+ attribute values only) so it stays flat-cost even for huge sessions.+ """+ for span in spans[:_AUTOMATION_SCAN_SPANS]:+ for value in span.attributes.values():+ if isinstance(value, str):+ low = value.lower()+ if any(m in low for m in _AUTOMATION_MARKERS):+ return True+ return False+++# ── waste components ────────────────────────+_EDIT_TOOLS: frozenset[str] = frozenset({"Edit", "MultiEdit", "Write"})+_COMPACTION_DROP_RATIO = 0.6+_COMPACTION_MIN_TOKENS = 1000+_RETRY_INPUT_PREFIX = 60+++class _ToolCall(NamedTuple):+ tool_name: str+ input_value: str+ # True = OK, False = ERROR, None = UNSET (the call's result was never+ # observed -- a dangling Cursor call). Unknown is neither a success nor a+ # failure: it must not seed a retry pair, count against the error rate,+ # or contribute edit lines.+ success: bool | None+ # Turn number the call belongs to (via the tool span's parent turn span),+ # or None when the parent isn't a turn. Lets waste land in BILLED tokens+ # of the specific turns involved instead of avg context windows.+ turn: int | None = None+++def _context_growth(spans: list[SpanData]) -> list[dict]:+ """Per-turn prompt-token series, ascending by turn — for floor drift."""+ rows: list[dict] = []+ for s in spans:+ if not s.name.startswith("Turn "):+ continue+ try:+ n = int(s.name.split()[1])+ except (ValueError, IndexError):+ continue+ rows.append(+ {"turn": n, "prompt_tokens": int(s.attributes.get("llm.token_count.prompt") or 0)}+ )+ rows.sort(key=lambda r: r["turn"])+ return rows+++def _turn_number(name: str) -> int | None:+ """Parse ``"Turn N"`` → N, else None."""+ if not name.startswith("Turn "):+ return None+ try:+ return int(name.split()[1])+ except (ValueError, IndexError):+ return None+++def _tool_calls(spans: list[SpanData]) -> list[_ToolCall]:+ """Chronologically ordered tool calls — for repeat / retry detection."""+ turn_by_id = {s.span_id: n for s in spans if (n := _turn_number(s.name)) is not None}+ tool_spans = [s for s in spans if s.attributes.get("tool.name")]+ tool_spans.sort(key=lambda s: s.start_time)+ return [+ _ToolCall(+ tool_name=s.attributes["tool.name"],+ input_value=s.attributes.get("input.value", "") or "",+ success=(None if s.status_code == "UNSET" else s.status_code != "ERROR"),+ turn=turn_by_id.get(s.parent_id or ""),+ )+ for s in tool_spans+ ]+++def interrupt_count_measured(spans: list[SpanData]) -> int | None:+ """User-interrupt total, or ``None`` when the harness never reported it.++ The distinction is load-bearing for the emitted field. A harness that emits no+ ``harness.session_signals`` is "not instrumented", which is NOT the same as+ "zero interrupts": persisting 0 for it launders an unmeasured session into a+ real-looking measurement, and a consumer needs to be able to tell those+ apart. Waste accounting wants a number, so+ :func:`_interrupt_count` keeps coercing to 0 for that use only.+ """+ root = next((s for s in spans if s.parent_id is None), None)+ if root is None:+ return None+ raw = root.attributes.get("harness.session_signals")+ if not raw:+ return None+ try:+ sig = json.loads(raw) if isinstance(raw, str) else raw+ except json.JSONDecodeError:+ return None+ if not isinstance(sig, dict):+ return None+ interrupts = sig.get("interrupts")+ if not isinstance(interrupts, dict):+ return None+ try:+ return int(interrupts.get("total", 0))+ except (TypeError, ValueError):+ return None+++def _interrupt_count(spans: list[SpanData]) -> int:+ """Interrupt total coerced to 0 — for waste maths, which needs a number."""+ return interrupt_count_measured(spans) or 0+++def repeated_edits_to_same_file(tool_calls: list[_ToolCall]) -> int:+ """Count of consecutive Edit calls to the same file (thrashing)."""+ count = 0+ last_edit_file: str | None = None+ for tc in tool_calls:+ if tc.tool_name in _EDIT_TOOLS:+ file_path = _file_path(tc.input_value)+ if file_path and file_path == last_edit_file:+ count += 1+ last_edit_file = file_path+ else:+ last_edit_file = None+ return count+++def _same_operation(a: _ToolCall, b: _ToolCall) -> bool:+ if a.tool_name != b.tool_name:+ return False+ ia, ib = (a.input_value or "").strip(), (b.input_value or "").strip()+ if not ia or not ib:+ return False+ return ia[:_RETRY_INPUT_PREFIX] == ib[:_RETRY_INPUT_PREFIX]+++def error_retry_sequences(tool_calls: list[_ToolCall]) -> int:+ """Count error→retry patterns: a failed call re-attempted (within 3 calls)+ with the same tool AND the same input prefix — the same operation."""+ count = 0+ for i in range(len(tool_calls) - 1):+ if tool_calls[i].success is False: # an UNSET call is not a failed one+ for j in range(i + 1, min(i + 4, len(tool_calls))):+ if _same_operation(tool_calls[i], tool_calls[j]):+ count += 1+ break+ return count+++def _find_compaction_events(context_growth: list[dict]) -> list[tuple[int, int, int]]:+ events: list[tuple[int, int, int]] = []+ for i in range(1, len(context_growth)):+ prev = context_growth[i - 1].get("prompt_tokens", 0)+ curr = context_growth[i].get("prompt_tokens", 0)+ if prev > _COMPACTION_MIN_TOKENS and curr < prev * _COMPACTION_DROP_RATIO:+ events.append((i, prev, curr))+ return events+++def floor_drift_score(context_growth: list[dict]) -> float | None:+ """0-1: fraction of consecutive post-compaction floors that grew. None when+ fewer than 2 compaction events (nothing to compare)."""+ if len(context_growth) < 2:+ return None+ events = _find_compaction_events(context_growth)+ if len(events) < 2:+ return None+ floors = [post for _, _, post in events]+ increases = sum(1 for i in range(1, len(floors)) if floors[i] > floors[i - 1])+ return round(increases / (len(floors) - 1), 2)+++def _repeat_edit_turns(tool_calls: list[_ToolCall]) -> set[int]:+ """Turns containing consecutive same-file Edit calls (thrashing).++ Same detection as :func:`repeated_edits_to_same_file`, but collects the+ TURNS involved instead of counting events — the unit the billed-waste+ computation charges.+ """+ turns: set[int] = set()+ last_edit_file: str | None = None+ for tc in tool_calls:+ if tc.tool_name in _EDIT_TOOLS:+ file_path = _file_path(tc.input_value)+ if file_path and file_path == last_edit_file and tc.turn is not None:+ turns.add(tc.turn)+ last_edit_file = file_path+ else:+ last_edit_file = None+ return turns+++def _retry_turns(tool_calls: list[_ToolCall]) -> set[int]:+ """Turns containing an error→retry pair (same detection as+ :func:`error_retry_sequences`; collects both calls' turns)."""+ turns: set[int] = set()+ for i in range(len(tool_calls) - 1):+ if tool_calls[i].success is False: # an UNSET call is not a failed one+ for j in range(i + 1, min(i + 4, len(tool_calls))):+ if _same_operation(tool_calls[i], tool_calls[j]):+ if tool_calls[i].turn is not None:+ turns.add(tool_calls[i].turn)+ if tool_calls[j].turn is not None:+ turns.add(tool_calls[j].turn)+ break+ return turns+++# ── marginal waste in dollars ──────────────────────────────────────+# Per-component cache multipliers when the rate card carries no explicit+# override: read 0.1x input, 5-minute write 1.25x, 1-hour write 2x. These are+# the same defaults `agentplay._core.pricing` applies, so a marginal dollar+# here is a subset of the same bill computed for the whole session.+_CACHE_READ_MULTIPLIER = 0.1+_CACHE_WRITE_5M_MULTIPLIER = 1.25+_CACHE_WRITE_1H_MULTIPLIER = 2.0+++def _component_rates(model_id: str | None) -> tuple[float, float, float, float, float] | None:+ """Per-Mtok USD rates ``(fresh_input, cache_read, cache_write_5m,+ cache_write_1h, output)`` for a model, or None when unpriceable.++ Resolves through the ONE rate card (``agentplay._core.pricing.MODEL_RATES``+ via ``normalize_model_key``) — no local price table. Missing cache keys+ fall back to the standard multipliers above, which reproduce the+ published cache prices for every Anthropic entry on the card. Models+ the card lacks are unpriceable here (None).+ """+ if not model_id:+ return None+ entry = MODEL_RATES.get(normalize_model_key(model_id))+ if not entry:+ return None+ input_rate = float(entry["input"])+ return (+ input_rate,+ float(entry.get("cache_read", input_rate * _CACHE_READ_MULTIPLIER)),+ float(entry.get("cache_write", input_rate * _CACHE_WRITE_5M_MULTIPLIER)),+ input_rate * _CACHE_WRITE_1H_MULTIPLIER,+ float(entry["output"]),+ )+++def _turn_token_components(spans: list[SpanData]) -> dict[int, tuple[int, int, int, int, int]]:+ """Per-turn billed token split ``{turn: (fresh, cache_read,+ cache_write_5m, cache_write_1h, output)}`` from the turn spans.++ Reads the same attributes ``aggregate_session_spans`` sums session-wide,+ so both grains price off identical inputs. ``fresh`` prefers the+ the DERIVED ``total_billed_prompt − cache_read − cache_write`` (clamped+ ≥ 0), so a marginal dollar is priced off the same split as the+ session's own bill. The parser-stamped+ ``llm.token_count.input_fresh`` is only the FALLBACK, for parsers that+ never stamp a billed prompt (codex, opencode), because its meaning is+ not uniform across parsers: Claude Code stamps genuine+ fresh input (identical to the derived value by construction — see+ ``claude_code.py``'s ``per_msg_prompt = fresh + write + read``), but+ Cursor stamps ``prompt − cache_read``, which still CONTAINS the cache+ writes. Preferring it there billed those tokens twice (once at the+ input rate inside "fresh", again at the 1.25x write rate).++ A turn stamping NEITHER key falls back to plain ``prompt`` minus the+ cache components — mirroring ``aggregate_session_spans``' own+ no-``input_fresh`` fallback (``input_fresh = input_tokens``), so a+ parser that only stamps ``prompt`` prices its waste off the same+ number its session bill uses instead of silently pricing fresh=0.+ (Every current parser stamps one of the two keys or all-zeros — the+ all-zero shape is caught by the no-billed-tokens None guard — so this+ tail is for parser shapes we haven't met yet.)+ Duplicate ``Turn N`` spans resolve last-wins, matching+ ``compute_session_waste``'s ``billed_by_turn``.+ """+ comps: dict[int, tuple[int, int, int, int, int]] = {}+ for s in spans:+ n = _turn_number(s.name)+ if n is None:+ continue+ attrs = s.attributes+ cache_read = int(attrs.get("llm.token_count.cache_read") or 0)+ cache_write = int(attrs.get("llm.token_count.cache_write") or 0)+ # The 1h subset can never exceed the write total (defensive clamp).+ w1h = min(int(attrs.get("llm.token_count.cache_write_1h") or 0), cache_write)+ w5m = cache_write - w1h+ if "llm.token_count.total_billed_prompt" in attrs:+ billed_prompt = int(attrs.get("llm.token_count.total_billed_prompt") or 0)+ fresh = max(billed_prompt - cache_read - cache_write, 0)+ elif "llm.token_count.input_fresh" in attrs:+ fresh = int(attrs.get("llm.token_count.input_fresh") or 0)+ else:+ # Neither key: plain `prompt` IS fresh — deliberately NOT minus+ # the cache components, because that is exactly how the session+ # BILL prices this shape (`aggregate_session_spans` falls back to+ # `input_fresh = input_tokens`, and total input is rebuilt as+ # fresh + read + write on top of it). A+ # "better" cache-subtracted guess here would make a retry turn's+ # marginal dollars disagree with the same turn's share of the+ # bill — consistency with the bill outranks a better estimate.+ fresh = int(attrs.get("llm.token_count.prompt") or 0)+ output = int(attrs.get("llm.token_count.completion") or 0)+ comps[n] = (fresh, cache_read, w5m, w1h, output)+ return comps+++def _turn_cost_usd(+ comp: tuple[int, int, int, int, int], rates: tuple[float, float, float, float, float]+) -> float:+ """One turn's full billed dollars: each token component at its own rate."""+ fresh, cache_read, w5m, w1h, output = comp+ in_r, read_r, w5m_r, w1h_r, out_r = rates+ return (+ fresh * in_r + cache_read * read_r + w5m * w5m_r + w1h * w1h_r + output * out_r+ ) / 1_000_000.0+++def _repeat_edit_call_counts(tool_calls: list[_ToolCall]) -> dict[int, int]:+ """``{turn: redundant edit-call count}`` — same detection as+ :func:`_repeat_edit_turns`, but counting the redundant calls per turn+ (the numerator of the repeat-edit marginal share)."""+ counts: dict[int, int] = {}+ last_edit_file: str | None = None+ for tc in tool_calls:+ if tc.tool_name in _EDIT_TOOLS:+ file_path = _file_path(tc.input_value)+ if file_path and file_path == last_edit_file and tc.turn is not None:+ counts[tc.turn] = counts.get(tc.turn, 0) + 1+ last_edit_file = file_path+ else:+ last_edit_file = None+ return counts+++def _resolve_pricing_model(spans: list[SpanData], model_id: str | None) -> str | None:+ """The model id the marginal dollars price against.++ Mirrors session pricing's fallback chain: an explicit caller-supplied id+ (typically the model the session's ``total_cost_usd`` is priced with)+ wins, else the root span's model, else the last genuine model+ observed in the spans — exactly ``aggregate_session_spans``' resolution.+ """+ resolved = model_id_or_none(model_id) if model_id is not None else None+ if resolved:+ return resolved+ root = next((s for s in spans if s.parent_id is None), None)+ resolved = model_id_or_none(root.model_name) if root else None+ return resolved or last_genuine_model_id(spans)+++def _marginal_waste_usd(+ spans: list[SpanData],+ calls: list[_ToolCall],+ retry_turns: set[int],+ repeat_turns: set[int],+ model_id: str | None,+) -> dict[str, float | None]:+ """The three MARGINAL waste components, in dollars.++ Marginal = what would not have been billed absent the waste event —+ unlike the billed trio (whole billed tokens of every involved turn, an+ upper bound), each component charges+ only the spend the event actually caused:++ - ``retry_waste_marginal_usd`` — each retry turn's FULL billed cost+ (fresh input at the input rate, cache reads at the read rate, 5m/1h+ cache writes at their write rates, output at the output rate): the+ dead attempt's whole bill bought nothing. Charges every turn in the+ same disjoint retry set the billed trio uses.+ - ``interrupt_waste_marginal_usd`` — only the discarded GENERATION:+ interrupts carry no turn ids, so it charges the session-average+ output cost per turn × interrupt count (capped at turn count).+ The interrupted prompt/context is NOT counted — it+ re-bills as cheap cache reads on the next attempt.+ - ``repeat_edit_waste_marginal_usd`` — for each repeat-edit turn, the+ redundant share of its OUTPUT cost: output cost × (redundant edit calls+ in the turn / total tool calls in the turn); the+ whole turn's output when the turn shows no attributable tool calls.+ The turn's prompt side is NOT counted.++ Approximations (per-turn splits come straight from parser-stamped span+ attributes — see :func:`_turn_token_components` — so only the+ attribution itself is approximate): interrupt attribution uses the+ session-average output per turn (no turn ids); the repeat-edit share+ treats a turn's output as evenly spread across its tool calls.++ All values are ≥ 0, and their sum is clamped to the session's own+ billed total (each request's model rate when complete request evidence+ exists, otherwise the session model rate, and Cursor's stamped+ ``session.cost_usd`` when present).++ Returns all three as None — unknown, never a fabricated $0 — when+ EITHER the model can't be priced off the rate card, OR the session+ carries no per-turn billed tokens to price (see the guard below).+ """+ _none = {+ "retry_waste_marginal_usd": None,+ "interrupt_waste_marginal_usd": None,+ "repeat_edit_waste_marginal_usd": None,+ }+ comps = _turn_token_components(spans)+ # An unpriceable MODEL is not the only way to be unknown. A session whose+ # parser stamps no per-turn billed tokens at all — a Cursor transcript+ # with no `cursor_usage_event` lines, cursor_agent_transcript, kiro; all+ # zero every turn token attr and leave any real total on the ROOT span —+ # would price all three components at exactly $0.00 even though its+ # retry/interrupt EVENTS are detected normally (those come from the tool+ # spans, which ARE stamped). A confident $0.00 reads as "measured, no+ # waste here"; the truth is "never measured". Root-level totals cannot be+ # attributed to individual retry turns without inventing an allocation+ # rule, so unknown is the only honest answer.+ if not any(sum(c) for c in comps.values()):+ return _none+ n_turns = len(comps)+ # Validate request coverage before using it: partial evidence must not+ # price a complete turn, and a display model cannot price other models.+ has_events = session_model_usage(spans) is not None+ fallback_rates = _component_rates(_resolve_pricing_model(spans, model_id))+ turn_costs: dict[int, float] = {}+ output_costs: dict[int, float] = {}+ for span in spans:+ n = _turn_number(span.name)+ if n is None:+ continue+ if has_events:+ full, output = 0.0, 0.0+ for event in span.attributes["llm.cost_events"]:+ component = tuple(+ event.get(k, 0)+ for k in (+ "input_tokens",+ "cache_read_tokens",+ "cache_write_5m_tokens",+ "cache_write_1h_tokens",+ "output_tokens",+ )+ )+ if not any(component):+ # Zero-token evidence (a rate-limit-only or model-less+ # call) prices to $0 under any card; needing its rate+ # would make every waste figure unknown for nothing+ # Positive usage still must price.+ continue+ rates = _component_rates(event.get("model"))+ if rates is None:+ return _none+ full += _turn_cost_usd(component, rates)+ output += component[4] * rates[4] / 1_000_000.0+ else:+ if fallback_rates is None:+ return _none+ full = _turn_cost_usd(comps[n], fallback_rates)+ output = comps[n][4] * fallback_rates[4] / 1_000_000.0+ turn_costs[n], output_costs[n] = full, output++ retry_usd = sum(turn_costs.get(t, 0.0) for t in retry_turns)+ avg_output_cost = sum(output_costs.values()) / n_turns if n_turns else 0.0+ interrupts = min(_interrupt_count(spans), n_turns)+ interrupt_usd = interrupts * avg_output_cost++ redundant_by_turn = _repeat_edit_call_counts(calls)+ calls_by_turn: dict[int, int] = {}+ for tc in calls:+ if tc.turn is not None:+ calls_by_turn[tc.turn] = calls_by_turn.get(tc.turn, 0) + 1+ repeat_usd = 0.0+ for t in repeat_turns:+ denom = calls_by_turn.get(t, 0)+ share = min(redundant_by_turn.get(t, 0) / denom, 1.0) if denom else 1.0+ repeat_usd += output_costs.get(t, 0.0) * share++ # Guardrail invariant, not the estimator: each component is ≥ 0 by+ # construction, but the three can jointly exceed the session's billed+ # total in pathological shapes (interrupts have no turn ids, so their+ # average-output charge can land on turns retry already billed in full).+ # Clamp the SUM to the session's own billed cost — the same rates over+ # all turns, further capped by Cursor's stamped invoice total when the+ # source provided one — scaling the components proportionally so their+ # relative attribution survives.+ session_total = sum(turn_costs.values())+ root = next((s for s in spans if s.parent_id is None), None)+ stamped = root.attributes.get("session.cost_usd") if root is not None else None+ if stamped is not None:+ session_total = min(session_total, float(stamped))+ marginal_sum = retry_usd + interrupt_usd + repeat_usd+ if marginal_sum > session_total:+ scale = (session_total / marginal_sum) if marginal_sum > 0 else 0.0+ retry_usd *= scale+ interrupt_usd *= scale+ repeat_usd *= scale++ return {+ "retry_waste_marginal_usd": round(max(0.0, retry_usd), 6),+ "interrupt_waste_marginal_usd": round(max(0.0, interrupt_usd), 6),+ "repeat_edit_waste_marginal_usd": round(max(0.0, repeat_usd), 6),+ }+++def compute_session_waste(spans: list[SpanData], model_id: str | None = None) -> dict:+ """Session-level waste components, in two unit systems.++ Legacy fields (``*_waste_tokens``) charge ``event_count × avg context+ window`` - a SCORE-space heuristic. They are fine+ for the clamped efficiency score but must never be priced: the unit is+ the cache-inflated context window, so their sum can exceed the session's+ billed tokens many times over.++ Billed fields (``*_waste_billed_tokens``) are the priceable variants:+ the BILLED tokens (total_billed_prompt + completion) of the specific+ turns involved, categories disjoint by construction (retry wins over+ repeat when a turn shows both; interrupts — a session-level count with+ no turn ids — charge ``min(count, turn_count)`` average billed turns).+ Bounded by the session's own billed total, so any dollar figure derived+ from them is a true subset of spend. Still an UPPER bound though: a turn+ involved in waste isn't wholly waste, so billed fields+ over-attribute and are not meant for display.++ Marginal fields (``*_marginal_usd``) are the display numbers: what would+ not have been paid absent each waste event, priced per component off the+ unified rate card. See :func:`_marginal_waste_usd` for the exact+ semantics and approximations. ``model_id`` (optional) is the pricing+ model (typically the one ``total_cost_usd`` is priced with); when absent the root-span → last-genuine-model chain applies+ (identical to :func:`aggregate_session_spans`). All three are None when+ the model can't be priced, or when the session's parser stamped no+ per-turn billed tokens to price.++ ``retry_turn_count`` is the size of the engine's retry TURN set (the same+ disjoint set the billed/marginal retry figures charge — both calls of an+ error→retry pair land their turns in it). It is the span-derived+ instrumentation for "how much retrying happened here": always an int, and+ 0 is a real measurement (the engine scanned the tool calls and found no+ retry pair) - unlike the ``error_retry_sequences`` field,+ which is None when never measured.++ Returns ``{interrupt_waste_tokens, repeat_waste_tokens,+ retry_waste_tokens, interrupt_waste_billed_tokens,+ repeat_waste_billed_tokens, retry_waste_billed_tokens,+ retry_waste_marginal_usd, interrupt_waste_marginal_usd,+ repeat_edit_waste_marginal_usd, retry_turn_count, floor_drift}``.+ Deterministic; safe on empty input.+ """+ growth = _context_growth(spans)+ calls = _tool_calls(spans)+ avg_prompt = sum(t["prompt_tokens"] for t in growth) / len(growth) if growth else 0.0++ # Billed tokens per turn, from the turn spans themselves.+ billed_by_turn: dict[int, int] = {}+ for s in spans:+ n = _turn_number(s.name)+ if n is None:+ continue+ billed_by_turn[n] = int(s.attributes.get("llm.token_count.total_billed_prompt") or 0) + int(+ s.attributes.get("llm.token_count.completion") or 0+ )++ retry_t = _retry_turns(calls)+ repeat_t = _repeat_edit_turns(calls) - retry_t # disjoint: retry wins+ n_turns = len(billed_by_turn)+ avg_billed = (sum(billed_by_turn.values()) / n_turns) if n_turns else 0.0+ interrupts = min(_interrupt_count(spans), n_turns)++ return {+ "interrupt_waste_tokens": int(_interrupt_count(spans) * avg_prompt),+ "repeat_waste_tokens": int(repeated_edits_to_same_file(calls) * avg_prompt),+ "retry_waste_tokens": int(error_retry_sequences(calls) * avg_prompt),+ "interrupt_waste_billed_tokens": int(interrupts * avg_billed),+ "repeat_waste_billed_tokens": sum(billed_by_turn.get(t, 0) for t in repeat_t),+ "retry_waste_billed_tokens": sum(billed_by_turn.get(t, 0) for t in retry_t),+ **_marginal_waste_usd(spans, calls, retry_t, repeat_t, model_id),+ "retry_turn_count": len(retry_t),+ "floor_drift": floor_drift_score(growth),+ }+++# ── token aggregation ────+def aggregate_session_spans(spans: list[SpanData]) -> dict:+ """Roll spans up into session token components + model + bounds.++ Returns ``{start_time, end_time, model_name, turn_count, input_tokens,+ input_fresh, cache_read_tokens, cache_write_tokens, cache_write_1h_tokens,+ output_tokens, session_cost_usd}``. Per-source quirks (Cursor session-wide+ override, cache split, etc.) are handled below.+ """+ if not spans:+ return {+ "start_time": None,+ "end_time": None,+ "model_name": None,+ "turn_count": 0,+ "input_tokens": 0,+ "input_fresh": 0,+ "cache_read_tokens": 0,+ "cache_write_tokens": 0,+ "cache_write_1h_tokens": 0,+ "output_tokens": 0,+ "session_cost_usd": None,+ }++ root = next((s for s in spans if s.parent_id is None), None)+ start_time = root.start_time if root else min(s.start_time for s in spans)+ end_time = root.end_time if root else max(s.end_time for s in spans)+ timestamps_observed = not any(+ s.attributes.get("session.timestamps_observed") is False for s in spans+ )+ if not timestamps_observed:+ start_time = end_time = None++ model_name = model_id_or_none(root.model_name) if root else None+ if not model_name:+ model_name = last_genuine_model_id(spans)++ turn_spans = [s for s in spans if s.name.startswith("Turn ")]+ turn_count = len(turn_spans)+ input_tokens = sum(s.prompt_tokens for s in turn_spans)+ output_tokens = sum(s.completion_tokens for s in turn_spans)+ cache_read_tokens = sum(+ int(s.attributes.get("llm.token_count.cache_read") or 0) for s in turn_spans+ )+ cache_write_tokens = sum(+ int(s.attributes.get("llm.token_count.cache_write") or 0) for s in turn_spans+ )+ cache_write_1h_tokens = sum(+ int(s.attributes.get("llm.token_count.cache_write_1h") or 0) for s in turn_spans+ )+ # Prefer the summed genuine fresh-input attribute. Fall back to input_tokens+ # ONLY when NO turn span carried the attribute at all (a parser that never+ # stamps it) — never when it is present but legitimately sums to 0 (a+ # cache-only session). Forcing input_tokens there would let a consumer that+ # rebuilds the billed total as `input_fresh + cache_read + cache_write` add+ # the cached tokens a second time and overstate cost.+ _has_fresh_attr = any("llm.token_count.input_fresh" in s.attributes for s in turn_spans)+ input_fresh = sum(int(s.attributes.get("llm.token_count.input_fresh") or 0) for s in turn_spans)+ if not _has_fresh_attr:+ input_fresh = input_tokens++ session_cost_usd: float | None = None+ if root is not None:+ session_prompt = root.attributes.get("session.token_count.prompt")+ if session_prompt is not None:+ input_tokens = int(session_prompt)+ output_tokens = int(root.attributes.get("session.token_count.completion") or 0)+ cache_read_tokens = int(root.attributes.get("session.token_count.cache_read") or 0)+ cache_write_tokens = int(root.attributes.get("session.token_count.cache_write") or 0)+ cache_write_1h_tokens = 0+ input_fresh = max(input_tokens - cache_read_tokens - cache_write_tokens, 0)+ session_cost = root.attributes.get("session.cost_usd")+ if session_cost is not None:+ session_cost_usd = float(session_cost)++ return {+ "start_time": start_time,+ "end_time": end_time,+ "model_name": model_name,+ "turn_count": turn_count,+ "input_tokens": input_tokens,+ "input_fresh": input_fresh,+ "cache_read_tokens": cache_read_tokens,+ "cache_write_tokens": cache_write_tokens,+ "cache_write_1h_tokens": cache_write_1h_tokens,+ "output_tokens": output_tokens,+ "session_cost_usd": session_cost_usd,+ **({"timestamps_observed": False} if not timestamps_observed else {}),+ }+++# ── derived behaviour metrics ────+# The read/edit ratios use the read-first taxonomy (``RF_*`` in+# ``metrics.py``). A denominator of zero returns ``None``, never a+# fabricated 0.+_RF_MUTATION_TOOLS: frozenset[str] = RF_EDIT_TOOLS | RF_WRITE_TOOLS+_EFFICIENCY_MIN_TOKENS = 500 # below this a session is too small to score+_FLOOR_DRIFT_PENALTY = 0.3+++def read_edit_ratio(tool_calls: list[_ToolCall]) -> float | None:+ """Reads / Edits — higher = more research before modifying. None if no edits."""+ reads = sum(1 for tc in tool_calls if tc.tool_name in RF_READ_TOOLS)+ edits = sum(1 for tc in tool_calls if tc.tool_name in RF_EDIT_TOOLS)+ return round(reads / edits, 2) if edits else None+++def edits_without_read_pct(tool_calls: list[_ToolCall]) -> float | None:+ """Percent of Edit calls on a file not Read earlier in the session. None if no edits."""+ edits = sum(1 for tc in tool_calls if tc.tool_name in RF_EDIT_TOOLS)+ if not edits:+ return None+ read_files: set[str] = set()+ blind = 0+ for tc in tool_calls:+ fp = _file_path(tc.input_value)+ if not fp:+ continue+ if tc.tool_name in RF_READ_TOOLS:+ read_files.add(fp)+ elif tc.tool_name in RF_EDIT_TOOLS and fp not in read_files:+ blind += 1+ return round(blind / edits * 100, 1)+++def research_mutation_ratio(tool_calls: list[_ToolCall]) -> float | None:+ """Reads / mutations (Edit+Write). None if no mutations."""+ research = sum(1 for tc in tool_calls if tc.tool_name in RF_READ_TOOLS)+ mutations = sum(1 for tc in tool_calls if tc.tool_name in _RF_MUTATION_TOOLS)+ return round(research / mutations, 2) if mutations else None+++def write_vs_edit_pct(tool_calls: list[_ToolCall]) -> float | None:+ """Write (full-file rewrite) as percent of all mutations. None if no mutations."""+ writes = sum(1 for tc in tool_calls if tc.tool_name in RF_WRITE_TOOLS)+ mutations = sum(1 for tc in tool_calls if tc.tool_name in _RF_MUTATION_TOOLS)+ return round(writes / mutations * 100, 1) if mutations else None+++def error_rate(tool_calls: list[_ToolCall]) -> float | None:+ """Percent of tool calls that failed. None when the session ran no tools."""+ known = [tc for tc in tool_calls if tc.success is not None]+ if not known:+ return None # nothing ran, or nothing whose outcome was observed+ failed = sum(1 for tc in known if tc.success is False)+ return round(failed / len(known) * 100, 1)+++def edit_line_totals(tool_calls: list[_ToolCall]) -> tuple[int | None, int | None]:+ """Session-wide ``(lines_added, lines_removed)`` from the edit tool payloads.++ The AI-lines-of-code signal, counted locally - see+ :mod:`agentplay._core.ingestion.coding_agent.edit_lines` for why.++ Only SUCCESSFUL calls count: a failed ``Edit`` changed no lines, the same+ reason ``metrics.py`` gates ``useful_edit_count`` on success.++ Args:+ tool_calls: The session's chronological tool calls.++ Returns:+ ``(added, removed)``, or ``(None, None)`` when not one call carried a+ countable payload - an unmeasured session, which must stay None rather+ than land as a real-looking 0 (the contract+ :func:`session_derived_metrics` documents).+ """+ added = removed = 0+ measured = False+ for call in tool_calls:+ if call.success is not True: # failed OR never observed: no lines landed+ continue+ counts = edit_line_counts(call.tool_name, call.input_value)+ if counts is None:+ continue+ added += counts[0]+ removed += counts[1]+ measured = True+ return (added, removed) if measured else (None, None)+++def efficiency_score(+ total_tokens: int,+ compaction_waste: int,+ interrupt_waste: int,+ repeat_waste: int,+ retry_waste: int,+ floor_drift: float | None,+) -> float | None:+ """Composite 0-100 token-efficiency score (higher = less waste).++ ``100 * (1 - waste/tokens) * (1 - 0.3 * floor_drift)`` where+ ``waste = compaction + interrupt + repeat + retry``, clamped so waste never+ exceeds tokens (score floors at 0).++ The caller supplies ``total_tokens`` and ``compaction_waste`` from the+ **per-task** rollup (``Σ prompt+completion`` and ``Σ estimated_waste_tokens``+ over the session's segmented tasks), NOT the cache-inflated session token+ sum or a whole-session compaction estimate.+ That is why this lives one layer up from :func:`session_derived_metrics`+ (which has no task data). ``None`` for sessions under 500 tokens.+ """+ if total_tokens < _EFFICIENCY_MIN_TOKENS:+ return None+ total_waste = compaction_waste + interrupt_waste + repeat_waste + retry_waste+ waste_ratio = min(total_waste / total_tokens, 1.0) # clamp: waste ≤ tokens+ score = 100 * (1 - waste_ratio)+ if floor_drift is not None:+ score *= 1 - _FLOOR_DRIFT_PENALTY * floor_drift+ return round(max(0.0, score), 1)+++def skill_distribution(spans: list[SpanData]) -> dict[str, int]:+ """``{skill_name: count}`` from the session's ``skills_used`` signal, garbage dropped.++ Normalize each recorded skill path, drop entries that fail validation or carry a+ non-positive count, and sum by normalized name. Empty for parsers that emit+ no session signals (Codex / Copilot) or a session that loaded no skills.+ """+ root = next((s for s in spans if s.parent_id is None), None)+ if root is None:+ return {}+ raw = root.attributes.get("harness.session_signals")+ if not raw:+ return {}+ try:+ sig = json.loads(raw) if isinstance(raw, str) else raw+ except json.JSONDecodeError:+ return {}+ if not isinstance(sig, dict):+ return {}+ entries = sig.get("skills_used") or []+ if not isinstance(entries, list):+ return {}+ out: dict[str, int] = {}+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ try:+ count = int(entry.get("count", 0) or 0)+ except (ValueError, TypeError):+ continue+ if count <= 0:+ continue+ path = entry.get("path")+ name = normalize_skill_name(str(path or ""))+ if not path or name is None:+ continue+ out[name] = out.get(name, 0) + count+ return out+++def session_derived_metrics(spans: list[SpanData]) -> dict[str, Any]:+ """Span-only derived session metrics.++ The read/edit behaviour ratios, error rate, tool-calls-per-turn, the+ tool / skill distributions, and the added/removed line counts of a session+ summary (behaviour, tool errors, tool and skill usage, lines changed).+ Computed straight from the spans.++ ``efficiency_score`` is deliberately NOT here: it is scored from the+ **per-task** token + waste rollup (see :func:`efficiency_score`), which only+ exists after segmentation - the caller computes it.+ Only non-null / non-empty entries are returned: a missing signal (no+ edits, no skills) is omitted rather than a fabricated 0.+ """+ calls = _tool_calls(spans)+ turn_count = len(_context_growth(spans)) # one row per "Turn N" span == turns++ out: dict[str, Any] = {}++ def _put(key: str, value: Any) -> None:+ if value is not None:+ out[key] = value++ _put("read_edit_ratio", read_edit_ratio(calls))+ _put("edits_without_read_pct", edits_without_read_pct(calls))+ _put("research_mutation_ratio", research_mutation_ratio(calls))+ _put("write_vs_edit_pct", write_vs_edit_pct(calls))+ _put("error_rate", error_rate(calls))+ # These two are computed right here in this module and feed the waste+ # rollup, so they are emitted here too; leaving them off+ # made retry rate and interrupts per session read as missing while token+ # waste, fed by the same numbers, was present.+ #+ # Both keep the null-vs-zero contract this function documents: retries only+ # when there were tool calls to retry, interrupts only when the harness+ # actually reported signals. A fabricated 0 would read as a healthy green+ # score, which is strictly worse than an honest dash.+ if calls:+ _put("error_retry_sequences", error_retry_sequences(calls))+ _put("interrupt_count", interrupt_count_measured(spans))+ # AI lines of code. Same null-vs-zero contract: a session whose edit payloads+ # never parsed leaves both fields None, so a reader shows a dash rather+ # than claiming the agent wrote nothing.+ lines_added, lines_removed = edit_line_totals(calls)+ _put("lines_added", lines_added)+ _put("lines_removed", lines_removed)+ if turn_count and calls:+ out["tool_calls_per_turn"] = round(len(calls) / turn_count, 1)+ tool_dist = session_tool_distribution(spans)+ if tool_dist:+ out["tool_distribution"] = tool_dist+ skill_dist = skill_distribution(spans)+ if skill_dist:+ out["skill_distribution"] = skill_dist+ return out+++# ── public entry ─────────────────────────────────────────+def session_model_usage(spans: list[SpanData]) -> list[dict[str, Any]] | None:+ """Per-model billed token totals when the parser supplies request evidence.++ Match every billed component against the independent turn aggregates before+ publishing a complete summary. Never turn a partial request list into a+ session price. Other parsers retain their existing estimate path.+ """+ turns = [s for s in spans if s.name.startswith("Turn ")]+ if not turns or not any("llm.cost_events" in s.attributes for s in turns):+ return None+ if not all("llm.cost_events" in s.attributes for s in turns):+ raise ValueError("Request evidence is missing for part of the session")+ if not any(s.attributes.get("llm.cost_events") for s in turns):+ # Every turn carries the key but not one request row. Two cases:+ # the turns billed NOTHING (rate-limit-only / valid zero usage) --+ # observed zero, reconciled to [] below -- or the parser saw usage+ # it could not place (no timestamp) and kept only the turn totals:+ # absent evidence, so callers keep the aggregate estimate instead+ # of a mismatch error.+ seen = aggregate_session_spans(spans)+ if any(+ seen[k]+ for k in (+ "input_fresh",+ "cache_read_tokens",+ "cache_write_tokens",+ "cache_write_1h_tokens",+ "output_tokens",+ )+ ):+ return None+ grouped: dict[tuple[str, str], dict[str, Any]] = {}+ fields = (+ "input_tokens",+ "cache_read_tokens",+ "cache_write_5m_tokens",+ "cache_write_1h_tokens",+ "output_tokens",+ )+ for turn in turns:+ for event in turn.attributes["llm.cost_events"]:+ model = str(event.get("model") or "")+ raw_speed = event.get("speed")+ speed = "" if raw_speed is None else str(raw_speed)+ row = grouped.setdefault(+ (model, speed),+ {+ "model": model,+ "requests": 0,+ **dict.fromkeys(fields, 0),+ **({"speed": speed} if speed else {}),+ },+ )+ if "cache_ttl_known" in event:+ row["cache_ttl_known"] = (+ row.get("cache_ttl_known", True) and event["cache_ttl_known"]+ )+ row["requests"] += 1+ for field in fields:+ value = event.get(field, 0)+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ raise ValueError(f"Invalid request token component: {field}")+ row[field] += value+ agg = aggregate_session_spans(spans)+ totals = {field: sum(row[field] for row in grouped.values()) for field in fields}+ if (+ totals["input_tokens"] != agg["input_fresh"]+ or totals["cache_read_tokens"] != agg["cache_read_tokens"]+ or totals["cache_write_5m_tokens"] + totals["cache_write_1h_tokens"]+ != agg["cache_write_tokens"]+ or totals["cache_write_1h_tokens"] != agg["cache_write_1h_tokens"]+ or totals["output_tokens"] != agg["output_tokens"]+ ):+ raise ValueError("Request evidence does not cover the session's billed tokens")+ return [grouped[model] for model in sorted(grouped)]+++def build_session_metrics(spans: list[SpanData]) -> dict[str, Any]:+ """Session-level metrics dict.++ Combines :func:`aggregate_session_spans`, :func:`compute_session_waste`,+ :func:`detect_automated`, and :func:`session_derived_metrics` (the behaviour+ ratios + error rate + tool-calls-per-turn + tool & skill distributions). Omits+ ``total_cost_usd`` (a consumer can recompute cost from tokens ++ model) — but DOES emit ``billed_cost_usd``: the vendor's own stamped invoice+ figure (Cursor's analytics API → root-span ``session.cost_usd``), a+ different provenance a consumer may prefer. OMITTED - not null - when no+ stamp exists: a present null could be read as an explicit clear, and+ omission is this function's convention for signal-less keys anyway.++ ``efficiency_score`` is NOT emitted here. It needs the per-task token+waste+ rollup that only exists after segmentation, so the caller scores it with+ :func:`efficiency_score` and adds it to this dict. See :func:`session_derived_metrics`.++ Returns:+ A dict of ``{model, billed_cost_usd, input_tokens, input_fresh, output_tokens,+ cache_read_tokens, cache_write_tokens, cache_write_1h_tokens, cached_tokens,+ interrupt_waste_tokens,+ repeat_waste_tokens, retry_waste_tokens, interrupt_waste_billed_tokens,+ repeat_waste_billed_tokens, retry_waste_billed_tokens, retry_turn_count,+ floor_drift, is_automated}``+ plus, when computable, ``{read_edit_ratio, edits_without_read_pct,+ research_mutation_ratio, write_vs_edit_pct, error_rate,+ tool_calls_per_turn, tool_distribution, skill_distribution,+ lines_added, lines_removed}`` — the+ derived keys are omitted (not NULL-valued) when a session lacks the+ signal to compute them. ``efficiency_score`` is added by the caller, not+ this function.+ """+ agg = aggregate_session_spans(spans)+ model_usage = session_model_usage(spans)+ # Same pricing model the session's own cost uses (root → last genuine).+ waste = compute_session_waste(spans, model_id=agg["model_name"])+ out: dict[str, Any] = {+ "timestamps_observed": agg.get("timestamps_observed") is not False,+ "model": agg["model_name"],+ "input_tokens": agg["input_tokens"],+ # The genuinely-fresh (non-cached) input, SUM-flavoured across turns.+ # A session is priced off ``input_fresh + cache_read + cache_write``+ # (the billed sum), so this is emitted to let a consumer price off the+ # SAME cache-inclusive total instead of+ # ``input_tokens`` (the per-turn context-window MAX summed), which on+ # multi-turn sessions falls below the cumulative cache totals and clamps+ # the priced fresh input to 0.+ "input_fresh": agg["input_fresh"],+ "output_tokens": agg["output_tokens"],+ "cache_read_tokens": agg["cache_read_tokens"],+ "cache_write_tokens": agg["cache_write_tokens"],+ # The 1h-TTL write subset — always emitted (0 when none) so a consumer+ # can price 1h cache writes at 2x and any re-computed value stays+ # cache-write-1h-aware for every session.+ "cache_write_1h_tokens": agg["cache_write_1h_tokens"],+ "cached_tokens": agg["cache_read_tokens"] + agg["cache_write_tokens"],+ "interrupt_waste_tokens": waste["interrupt_waste_tokens"],+ "repeat_waste_tokens": waste["repeat_waste_tokens"],+ "retry_waste_tokens": waste["retry_waste_tokens"],+ # Billed-unit waste — the PRICEABLE fields (see compute_session_waste).+ # Emitted so no consumer has to do dollar math on the score-space trio+ # above, which inflates reclaimable spend.+ "interrupt_waste_billed_tokens": waste["interrupt_waste_billed_tokens"],+ "repeat_waste_billed_tokens": waste["repeat_waste_billed_tokens"],+ "retry_waste_billed_tokens": waste["retry_waste_billed_tokens"],+ # Span-derived retry instrumentation — always emitted: unlike the+ # pricing-gated marginal trio below, a 0 here is a real measurement+ # (the engine scanned the calls and found no error→retry pair), the+ # honest replacement for `error_retry_sequences`, which is None+ # when never measured.+ "retry_turn_count": waste["retry_turn_count"],+ "is_automated": detect_automated(spans),+ }+ if model_usage is not None:+ out["model_usage"] = model_usage+ root = next((s for s in spans if s.parent_id is None), None)+ if root and "llm.cost_summary" in root.attributes:+ out["claude_cost_summary"] = root.attributes["llm.cost_summary"]+ checkpoints = out["claude_cost_summary"]["checkpoints"]+ if out["claude_cost_summary"].get("invalid_checkpoints") or any(c["has_unknown_model_cost"] or any(c["visible_unreported_tokens"]) or any(r["reported_tokens"] != r["visible_tokens"] for r in c["models"]) for c in checkpoints):+ for row in out.get("model_usage", []):+ row["session_coverage_complete"] = False+ # Vendor-stamped invoice figure (see docstring): present only when a stamp+ # exists, so a session without a stamp never reports a billed cost of its own.+ if agg["session_cost_usd"] is not None:+ out["billed_cost_usd"] = agg["session_cost_usd"]+ # Marginal-dollar waste — the DISPLAY numbers (the billed trio is an+ # upper bound; see _marginal_waste_usd). Emitted whenever the session's+ # model prices off the rate card (0.0 = genuinely no waste); omitted —+ # like floor_drift — when the model is unpriceable, so an unknown rate+ # never lands as a fabricated $0.+ for key in (+ "retry_waste_marginal_usd",+ "interrupt_waste_marginal_usd",+ "repeat_edit_waste_marginal_usd",+ ):+ if waste[key] is not None:+ out[key] = waste[key]+ if waste["floor_drift"] is not None:+ out["floor_drift"] = waste["floor_drift"]+ out.update(session_derived_metrics(spans))+ if root and root.attributes.get("llm.usage_complete") is False:+ out["usage_complete"] = False+ out["usage_state"] = root.attributes["llm.usage_state"]+ if "llm.reported_total_tokens" in root.attributes:+ out["reported_total_tokens"] = root.attributes["llm.reported_total_tokens"]+ # Known request components remain lower bounds. Neither the session+ # nor counterfactual savings can be priced as a complete observation.+ for key in ("retry_waste_marginal_usd", "interrupt_waste_marginal_usd",+ "repeat_edit_waste_marginal_usd", "floor_drift"):+ out.pop(key, None)+ return out+++__all__ = [+ "aggregate_session_spans",+ "build_session_metrics",+ "compute_session_waste",+ "detect_automated",+ "edits_without_read_pct",+ "efficiency_score",+ "error_rate",+ "error_retry_sequences",+ "floor_drift_score",+ "interrupt_count_measured",+ "read_edit_ratio",+ "repeated_edits_to_same_file",+ "research_mutation_ratio",+ "session_derived_metrics",+ "skill_distribution",+ "write_vs_edit_pct",+]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/skill_names.py b/python/src/agentplay/_core/ingestion/coding_agent/skill_names.pynew file mode 100644index 0000000..adf1e66--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/skill_names.py@@ -0,0 +1,351 @@+"""Skill-name extraction and validation.++A "skill" is a Claude Code skill directory (``skills/<name>/SKILL.md``); the+``<name>`` segment is a kebab-case identifier. Two layers must agree on what a+valid skill name is:++* extraction - ``extract_session_signals`` records ``skills_used`` from+ transcript signals (``_sources/_jsonl_utils.py``);+* display - anything that lists those skills.++Keeping the rule in one place stops garbage captured at extraction (e.g. a regex+literal that quotes the skill-load phrase) from leaking into output, and keeps+the display-side filter from disagreeing with the parser about what counts as+a skill.+"""++from __future__ import annotations++import re++from agentplay._core.ingestion.coding_agent._paths import to_posix++# Skill dir names are kebab-case identifiers: first char alnum, then alnum / dot+# / underscore / hyphen, bounded length. Deliberately rejects quotes, parens,+# backticks, backslashes, and whitespace — the shapes that garbage captures+# (code / regex fragments quoting "base directory for this skill:") take.+# Directory names that hold skills rather than being one. Matched as whole+# path segments — see `skill_name_from_path`.+_SKILL_ROOT_SEGMENTS = frozenset({"skills", "skills-cursor"})+_PLUGIN_COMMANDS_SEGMENT = "commands"+_PLUGINS_SEGMENT = "plugins"++# Names that are never skills: the first segment of an absolute path+# (`/Users/…` → `Users`, `/private/var/…` → `private`), a plugin's folder names+# (`plugins`, `common`), and Claude Code's own tools (`ExitPlanMode`). Rejected+# on read as well as on write, so stored values with these names do not show+# as skills.+_NOT_SKILL_NAMES = frozenset(+ {+ # OS / home-directory path segments+ "Users",+ "home",+ "private",+ "tmp",+ "var",+ "opt",+ "Volumes",+ "Library",+ "Applications",+ "Desktop",+ "Documents",+ "Downloads",+ # plugin layout folders+ "plugins",+ "common",+ "synced",+ # Claude Code tools+ "Agent",+ "Bash",+ "Edit",+ "EnterPlanMode",+ "ExitPlanMode",+ "Glob",+ "Grep",+ "MultiEdit",+ "NotebookEdit",+ "Read",+ "Skill",+ "Task",+ "TodoWrite",+ "WebFetch",+ "WebSearch",+ "Write",+ }+)++# An optional `<plugin>:` namespace is kept so a plugin skill stays+# attributable to its plugin. 128 caps the whole name length.+_VALID_SKILL_NAME = re.compile(+ r"(?=.{1,128}\Z)[A-Za-z0-9][A-Za-z0-9._-]{0,79}(?::[A-Za-z0-9][A-Za-z0-9._-]{0,79})?"+)+++def skill_name_from_path(raw: str) -> str:+ """Reduce a skill path to its display name; best-effort, never empty.++ ``skills/dark-mode-ui/SKILL.md`` -> ``dark-mode-ui``. Strips a leading store+ prefix (``.../.claude/...`` or ``.../.cursor/...``), isolates the segment+ after the last ``skills/``, and drops any trailing ``/SKILL.md`` or+ sub-path. Does NOT validate the result — pair with+ :func:`is_valid_skill_name`.++ Both stores are stripped so a Cursor skill path resolves identically to a+ Claude one. It matters when an EARLIER path segment is itself named+ ``skills`` (``/home/skills/.cursor/skills/a11y/SKILL.md``): without the+ store strip the split below latches onto that first segment and yields+ ``.cursor`` instead of ``a11y``.++ Plugin skills: a namespaced invocation ``myplugin:deploy``+ is kept whole, so the plugin stays visible; a namespaced invocation whose+ command is itself nested (``myplugin:common/engine/myplugin-run``) keeps the+ namespace and the command's LEAF segment (``myplugin:myplugin-run``); a+ plugin command path ``plugins/cache/m/myplugin/1.0/commands/+ deploy.md`` resolves to ``deploy``; a path under ``plugins/``+ with neither a skills nor a commands segment resolves to ``"unknown"``+ rather than to ``plugins``.++ An absolute path (``/Users/…``, ``~/…``) with no skills or commands+ segment also resolves to ``"unknown"``: its first segment is a root+ folder such as ``Users`` or ``tmp``, not a skill. A relative+ ``my-skill/SKILL.md`` still resolves to ``my-skill``.++ Args:+ raw: A skill path or bare name as recorded in ``skills_used``.++ Returns:+ The skill name segment, or ``"unknown"`` when ``raw`` is empty or names+ no skill.+ """+ stripped = (raw or "").strip()+ # An absolute path (`/Users/…`, `~/…`) whose skill can't be located below+ # resolves to no name rather than to its first segment.+ is_absolute = stripped.startswith(("/", "~"))+ cleaned = stripped.strip("/")+ if not cleaned:+ return "unknown"+ # A plugin's own command can itself be nested (`myplugin:common/engine/+ # myplugin-run`): checked BEFORE the general slash+ # split below, which otherwise treats the whole string as a plain path+ # and returns just its first segment (`myplugin:common`), dropping the+ # actual command. The leaf after the last `/` is the+ # command; the namespace is kept as sent, unsplit.+ ns, sep, rest = cleaned.partition(":")+ if sep and ns and "/" not in ns and rest:+ leaf = rest.rstrip("/").rsplit("/", 1)[-1]+ if leaf:+ return f"{ns}:{leaf}"+ for store_prefix in ("/.claude/", "/.cursor/"):+ if store_prefix in cleaned:+ cleaned = cleaned.split(store_prefix, 1)[1]+ break+ # Both skills ROOTS: Cursor ships its bundled skills under+ # `~/.cursor/skills-cursor/<name>/`, which contains no `skills/` segment at+ # all. Without handling it the FIRST path segment is returned as the name —+ # `skills-cursor` for a `.cursor` path, `Users` for one whose store prefix+ # was not stripped.+ #+ # Matched as a WHOLE SEGMENT, not a substring. A+ # bare `"skills-cursor/" in cleaned` also fires on+ # `skills/skills-cursor/SKILL.md` — a skill genuinely NAMED `skills-cursor`+ # — and hands back `SKILL.md`, which `is_valid_skill_name` happily accepts,+ # so the skill list shows a skill called `SKILL.md`. It would equally fire+ # inside an unrelated segment such as `my-skills-cursor/`.+ segments = [seg for seg in cleaned.split("/") if seg]+ for i, seg in enumerate(segments):+ if seg in _SKILL_ROOT_SEGMENTS and i + 1 < len(segments):+ return segments[i + 1]+ if not segments:+ return "unknown"+ # Plugin slash commands live at `<plugin>/commands/<name>.md` and are invoked+ # through the same Skill tool, so they resolve like a skill directory.+ for i, seg in enumerate(segments[:-1]):+ if seg == _PLUGIN_COMMANDS_SEGMENT:+ name = segments[i + 1]+ return name[: -len(".md")] if name.endswith(".md") else name+ # A plugin's own root (`plugins/cache/<marketplace>/<plugin>/…`) names no skill;+ # falling through would report the folder `plugins` as one.+ if len(segments) > 1 and _PLUGINS_SEGMENT in segments:+ return "unknown"+ # A relative `my-skill/SKILL.md` names its skill first; an absolute path's+ # first segment is a root folder (`Users`, `tmp`, `private`), never a skill.+ if is_absolute and len(segments) > 1:+ return "unknown"+ return segments[0]+++def is_valid_skill_name(name: str) -> bool:+ """True when ``name`` is a plausible skill identifier (kebab-case, bounded).++ Rejects the garbage shapes seen in real transcripts (backticks, quotes, parens, regex+ fragments) while accepting real skills like ``ui-ux-pro-max`` or+ ``web-design-guidelines``. Requires at least one letter, so version-like+ tokens (``2.1.159``, ``1.0.0``) that leak from transcripts are dropped —+ real skill names always have letters. Also rejects the known non-skill+ names in ``_NOT_SKILL_NAMES`` (path segments, plugin folders, tool names).+ """+ return (+ bool(name)+ and _VALID_SKILL_NAME.fullmatch(name) is not None+ and any(c.isalpha() for c in name)+ and name not in _NOT_SKILL_NAMES+ )+++def normalize_skill_name(raw: str) -> str | None:+ """Extract and validate a skill name from a raw path/name.++ Args:+ raw: A skill path or bare name (e.g. ``skills/frontend-design``).++ Returns:+ The clean skill name, or ``None`` when ``raw`` doesn't resolve to a+ plausible skill (garbage captured from quoted code, regex literals, …).+ Blank/empty input resolves to the ``"unknown"`` sentinel, which is+ treated as no skill (``None``) rather than a real name.+ """+ name = skill_name_from_path(raw)+ if name == "unknown": # sentinel for empty/unresolvable input, not a real skill+ return None+ return name if is_valid_skill_name(name) else None+++def skill_name_from_skill_md_path(file_path: str) -> str | None:+ """Canonical skill name from a ``.../<name>/SKILL.md`` path, or None.++ The name is the SKILL.md file's immediate PARENT DIRECTORY, not (as+ :func:`skill_name_from_path` assumes) the segment after a literal+ ``"skills/"`` anchor. There is no single fixed skills root in the wild:+ real captured examples include ``~/.cursor/skills-cursor/<name>/``+ (no ``"skills/"`` substring at all), ``~/.codex/skills/.system/<name>/``+ (the anchor rule grabs ``".system"``), project-local+ ``<repo>/.claude/skills/<name>/`` and marketplace-plugin caches nested+ arbitrarily deep. Reuses only the shared kebab-case validation.++ This is the ONE derivation every SKILL.md-read detector (`cursor_store`+ and the others) calls, so a name can never differ between detectors for+ the same path string.++ Args:+ file_path: An absolute or relative path to a SKILL.md file. The caller+ is responsible for confirming the basename is ``SKILL.md``; this+ function does not re-check it.++ Returns:+ The parent directory name when it is a plausible skill identifier,+ else ``None`` (too short a path, or a garbage/invalid name).++ Example:+ >>> skill_name_from_skill_md_path("/Users/x/.cursor/skills-cursor/autopilot/SKILL.md")+ 'autopilot'+ """+ segments = [s for s in to_posix(file_path).split("/") if s]+ if len(segments) < 2:+ return None+ name = segments[-2]+ return name if is_valid_skill_name(name) else None+++def skill_summary(text: str, *, limit: int = 160) -> str:+ """One-line description of an authored skill, from its SKILL.md body.++ Prefers the frontmatter ``description:`` field; otherwise the first prose+ line (skipping YAML frontmatter, Markdown headings, and blanks). Returns ""+ when nothing usable is found. Truncated to ``limit`` chars.++ Lives here beside the name rules so every consumer gets the same+ answer. The ``limit`` default keeps the text short enough to compare+ by token overlap: an untruncated body dilutes the score.++ Args:+ text: The full SKILL.md body, or "" when no definition was captured.+ limit: Max characters of the extracted description.++ Returns:+ The description line, truncated, or "" when nothing usable is found.+ """+ if not text:+ return ""+ in_frontmatter = False+ for i, raw in enumerate(text.splitlines()):+ line = raw.strip()+ if i == 0 and line == "---":+ in_frontmatter = True+ continue+ if in_frontmatter:+ if line == "---":+ in_frontmatter = False+ continue+ if line.lower().startswith("description:"):+ desc = line.split(":", 1)[1].strip().strip("'\"")+ if desc:+ return desc[:limit].rstrip()+ continue+ if not line or line.startswith("#") or line.startswith("---"):+ continue+ return line[:limit].rstrip()+ return ""+++# tool names that load a skill, and the span attribute carrying the+# invoked name so a consumer never has to re-parse a truncated ``input.value``.+SKILL_TOOL_NAMES = frozenset({"skill", "activate_skill"})+SKILL_CALL_NAME_ATTR = "skill.name"+++def skill_call_attributes(tool_name: str, tool_input: object) -> dict[str, str]:+ """Span attributes for a skill-loading tool call: its raw invoked name.++ Args:+ tool_name: The tool_use block's ``name`` (``Skill``, ``activate_skill``, …).+ tool_input: The tool_use block's ``input`` (a dict for Claude Code).++ Returns:+ ``{"skill.name": <raw name>}`` for a Skill call that names a skill,+ else ``{}``. The name is raw (normalize with :func:`skill_call_name`).+ """+ if str(tool_name).strip().lower() not in SKILL_TOOL_NAMES or not isinstance(tool_input, dict):+ return {}+ raw = tool_input.get("skill") or tool_input.get("command")+ if not isinstance(raw, str) or not raw.strip():+ return {}+ return {SKILL_CALL_NAME_ATTR: raw.strip()[:256]}+++def skill_call_name(tool_name: str, attributes: dict | None, input_value: object = None) -> str | None:+ """Canonical skill name of a skill-loading tool call, or None.++ Prefers the ``skill.name`` span attribute, then the+ JSON ``input.value``. A leading ``/`` is dropped, and the name goes+ through :func:`normalize_skill_name`, so junk (``common``) stays None.++ Args:+ tool_name: The tool's name; only ``Skill``/``activate_skill`` qualify.+ attributes: The span's attributes (may be None).+ input_value: The span's ``input.value`` JSON string, if any.++ Returns:+ ``plugin:skill`` or ``skill``, or None when the call names no real skill.++ Example:+ >>> skill_call_name("Skill", {"skill.name": "myplugin:deploy"})+ 'myplugin:deploy'+ """+ if str(tool_name).strip().lower() not in SKILL_TOOL_NAMES:+ return None+ raw = (attributes or {}).get(SKILL_CALL_NAME_ATTR)+ if not isinstance(raw, str) or not raw.strip():+ raw = None+ if isinstance(input_value, str) and input_value:+ import json++ try:+ payload = json.loads(input_value)+ except (json.JSONDecodeError, TypeError):+ payload = None+ if isinstance(payload, dict):+ cand = payload.get("skill") or payload.get("command")+ raw = cand if isinstance(cand, str) else None+ if not raw:+ return None+ return normalize_skill_name(raw.strip().lstrip("/"))diff --git a/python/src/agentplay/_core/ingestion/coding_agent/spans.py b/python/src/agentplay/_core/ingestion/coding_agent/spans.pynew file mode 100644index 0000000..ac3ed6e--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/spans.py@@ -0,0 +1,315 @@+"""Universal transcript payload shapes.++Every coding-agent source (local ~/.claude file walks,+and so on) normalizes its raw transcript into this single+shape. Extractors only ever see `SpanData` lists — they don't know+which source produced them.++This module does NOT carry the `TraceSource` Protocol. The Protocol lives in+`_sources/_base.py` so it stays alongside the per-source adapters and+out of the extractor import path. Splitting them keeps the dependency+direction clean — extractors import `spans`, sources import `spans`,+sources additionally import `_sources/_base`.++# Why dataclasses, not Pydantic++These shapes flow inside a single extractor call. They're not+persisted, not validated at API boundaries, and not exposed through+JSON. `@dataclass` is lighter and keeps the parsers simple.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime+import re++_SENTINEL_MODEL_IDS: frozenset[str] = frozenset(+ {"default", "default_routing", "unknown", "none", "n/a"}+)+_STRIP_SENTINEL_SUFFIX_RE = re.compile(+ r"\s*\((?:default|default_routing|unknown|none|n/a)\)$", re.IGNORECASE+)+++def model_id_or_none(raw: object) -> str | None:+ """Return a trustworthy model identifier, or ``None`` for a sentinel.++ Transcript formats occasionally emit internal placeholders such as+ ``<synthetic>`` instead of the model that generated a user-visible turn.+ They are not model identifiers and must not become model buckets in+ per-model views or pricing. This deliberately does not+ guess aliases: a real provider model id is preserved exactly.+ """+ if not isinstance(raw, str):+ return None+ model_id = raw.strip()+ if not model_id:+ return None+ if model_id.startswith("<") and model_id.endswith(">"):+ return None+ if model_id.startswith("(") and model_id.endswith(")"):+ return None+ # Strip trailing parenthetical sentinels so composite strings like+ # "claude-sonnet-4-6 (default_routing)" resolve to the real model.+ model_id = _STRIP_SENTINEL_SUFFIX_RE.sub("", model_id).strip()+ if not model_id:+ return None+ if model_id.lower() in _SENTINEL_MODEL_IDS:+ return None+ return model_id+++def last_genuine_model_id(spans: list[SpanData]) -> str | None:+ """The most recent real model id in a span list, ignoring placeholders.++ Claude Code stamps ``<synthetic>`` on assistant entries the CLI wrote+ itself rather than the model — API-error notices, rate-limit lines,+ "Not logged in", "No response requested" — all carrying zero usage. A+ session that ends on one of those reads as ``<synthetic>`` even though+ its real turns burned real tokens, and a placeholder cannot be priced.++ Two different kinds of transcript land on that same label:++ * Some hold real turns alongside the error lines and carry essentially+ all of the prompt tokens. A genuine model ran; this helper finds it+ and the cost becomes knowable.+ * Others carry **zero** prompt tokens: the session opened, hit an error+ or a login prompt, and nothing ever ran. There is no genuine model to+ find, so the cost stays unknown, which is correct: they cost nothing.++ Walks backwards because the model a session ended on is the best single+ label for it.++ Args:+ spans: the session's parsed spans, in transcript order.++ Returns:+ The last span-level model id that survives :func:`model_id_or_none`,+ or ``None`` when the session carries no genuine model at all (which+ is honest: the cost stays null rather than being priced at a guess).++ Example:+ >>> last_genuine_model_id([turn_on_opus, api_error_span])+ 'claude-opus-4-8'+ """+ for span in reversed(spans):+ model_id = model_id_or_none(span.model_name)+ if model_id:+ return model_id+ return None+++# Ordered most-specific-first: "API Error: 402 Router balance depleted" must+# resolve to the balance reason, not the generic api_error catch-all below it.+# Strings are verbatim from Claude-Code-written ``<synthetic>`` entries.+_FAILED_START_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (+ ("model_unavailable", re.compile(r"issue with the selected model", re.I)),+ ("router_balance_depleted", re.compile(r"router balance depleted|top up credits", re.I)),+ ("credentials_missing", re.compile(r"could not load credentials", re.I)),+ ("org_policy_block", re.compile(r"organization has disabled claude", re.I)),+ ("prompt_too_long", re.compile(r"prompt is too long", re.I)),+ (+ "not_logged_in",+ re.compile(r"not logged in|please run /login|invalid api key", re.I),+ ),+ (+ "rate_limited",+ re.compile(r"rate limit|usage limit reached|hit your usage limit", re.I),+ ),+ ("api_error", re.compile(r"api error", re.I)),+)+++def failed_start_reason(spans: list[SpanData]) -> str:+ """Name the startup failure recorded in an error-only session's spans.++ A "failed start" is a session where no model ever ran: every assistant+ entry is a CLI-written ``<synthetic>`` notice and token usage is zero.+ The caller owns that guard (it already has the aggregated+ totals); this function only names the reason from the error text the+ CLI wrote, which the parser preserves in each turn span's+ ``output.value`` attribute.++ Typical reasons are ``model_unavailable`` (a harness pinned to an+ inaccessible router model), router balance, credentials, org-policy and+ prompt-length failures.++ Args:+ spans: the session's parsed spans, in transcript order.++ Returns:+ A stable snake_case reason slug (``model_unavailable``,+ ``router_balance_depleted``, ``credentials_missing``,+ ``org_policy_block``, ``prompt_too_long``, ``not_logged_in``,+ ``rate_limited``, ``api_error``), or ``"unknown"`` when the spans+ carry no recognizable error text. Never ``None``: by the caller's+ guard the session IS a failed start, so an unmatched text is still+ a failed start — just one we cannot name yet.+ """+ texts: list[str] = []+ for span in spans:+ out = span.attributes.get("output.value")+ if isinstance(out, str) and out.strip():+ texts.append(out)+ return failed_start_reason_from_text("\n".join(texts))+++def failed_start_reason_from_text(text: str) -> str:+ """Classify a failed start straight from error text.++ The transcript-level entry point, for callers that scan+ raw ``.jsonl`` files without building spans. Same pattern table and same+ contract as :func:`failed_start_reason`: always returns a slug, with+ ``"unknown"`` for unrecognized (or absent) text.+ """+ if text and text.strip():+ for reason, pattern in _FAILED_START_PATTERNS:+ if pattern.search(text):+ return reason+ return "unknown"+++@dataclass+class DiscoveredSession:+ """Lightweight session info — what a source returns from discovery.++ Carries just enough to decide whether to fetch the full transcript+ (size estimate, time bounds). The actual spans live behind a second+ call (`get_spans_by_session(session_id)`).+ """++ session_id: str+ span_count: int+ last_span_time: datetime+ start_time: datetime+ end_time: datetime+++@dataclass+class SpanData:+ """One span from a parsed transcript.++ The unit every parser emits and every analyzer consumes. Shape is+ loosely inspired by OpenTelemetry's Span (parent_id, span_kind,+ status_code, attributes) while+ Claude Code / Codex / Copilot transcripts get synthesized into that+ shape by their respective parsers.++ `attributes` is the bag where every parser stashes source-specific+ fields. The convenience properties below name the ones we read+ everywhere so call sites don't sprinkle string keys.+ """++ span_id: str+ trace_id: str+ parent_id: str | None+ name: str+ span_kind: str # AGENT | TOOL | LLM | CHAIN | ... (OpenInference-style taxonomy)+ status_code: str # OK | ERROR | UNSET+ start_time: datetime+ end_time: datetime+ attributes: dict = field(default_factory=dict)++ @property+ def duration_ms(self) -> float:+ return (self.end_time - self.start_time).total_seconds() * 1000++ @property+ def tool_name(self) -> str | None:+ return self.attributes.get("tool.name") or self.attributes.get("name")++ @property+ def input_value(self) -> str | None:+ return self.attributes.get("input.value")++ @property+ def output_value(self) -> str | None:+ return self.attributes.get("output.value")++ @property+ def is_success(self) -> bool:+ return self.status_code == "OK"++ @property+ def user_id(self) -> str | None:+ return self.attributes.get("user.id")++ @property+ def project_name(self) -> str | None:+ # Both flat ("project.name") and nested ({"project": {"name": ...}})+ # shapes: our synthesized spans emit flat, nested is also accepted.+ if "project.name" in self.attributes:+ return self.attributes["project.name"]+ project = self.attributes.get("project")+ if isinstance(project, dict):+ return project.get("name")+ return None++ @property+ def model_name(self) -> str | None:+ return self.attributes.get("llm.model_name")++ @property+ def total_tokens(self) -> int:+ return int(self.attributes.get("llm.token_count.total", 0))++ @property+ def prompt_tokens(self) -> int:+ return int(self.attributes.get("llm.token_count.prompt", 0))++ @property+ def completion_tokens(self) -> int:+ return int(self.attributes.get("llm.token_count.completion", 0))+++@dataclass+class TraceData:+ """One trace — typically one agent session or one conversation turn.++ `root_span` is the synthesized `Session` span every parser emits as+ `span_id = "<trace_id>:root"`. Turn spans and tool spans hang off it.+ """++ trace_id: str+ start_time: datetime+ end_time: datetime+ spans: list[SpanData] = field(default_factory=list)++ @property+ def root_span(self) -> SpanData | None:+ for span in self.spans:+ if span.parent_id is None:+ return span+ return None++ @property+ def tool_spans(self) -> list[SpanData]:+ return [s for s in self.spans if s.span_kind == "TOOL"]+++@dataclass+class SessionData:+ """A session container — one or more traces grouped by session id.++ Most sources emit one trace per session, but a session can span+ multiple traces to a single session (sub-agents, retries). Tasks+ and Themes are computed over the union of all spans across all+ traces in the SessionData.+ """++ session_id: str+ traces: list[TraceData]+ start_time: datetime+ end_time: datetime+++__all__ = [+ "DiscoveredSession",+ "SessionData",+ "SpanData",+ "TraceData",+ "failed_start_reason",+ "failed_start_reason_from_text",+ "model_id_or_none",+]diff --git a/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py b/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.pynew file mode 100644index 0000000..fa029aa--- /dev/null+++ b/python/src/agentplay/_core/ingestion/coding_agent/tool_taxonomy.py@@ -0,0 +1,239 @@+"""The one table that maps each coding agent's raw tool names to our canonical names.++Every parser reads its aliases from here, so a new agent (or a renamed vendor tool)+is one row in one file, and every consumer -- metrics, segmentation -- sees the same+answer. Canonical names are Claude Code's own tool names (``Bash``, ``Read``,+``Edit``, ``Grep``, ``Task``...), so Claude transcripts need no aliasing and every+downstream name set keeps its meaning.+"""++from __future__ import annotations++# Codex emits raw agent-internal tool names that differ from the canonical+# Claude vocabulary every downstream consumer keys off by `tool.name`+# (read/edit/search/shell counters in metrics.py, blind-edit/full-rewrite+# ordering, tool_distribution, produced-output extraction). Without this+# alias table those buckets never match, so a Codex session shows tools/turn+# but zero read/edit/shell counts. Mirrors `cursor_store.py::_TOOL_ALIASES`+# (the same fix for Cursor's raw names). Names surveyed across 19 real Codex+# transcripts: `exec_command`/`write_stdin` (unified exec) and `apply_patch`+# dominate; `shell`/`read_file` are older Codex releases' names for the same+# operations. Desktop's wrapper exposes the same host command capability as+# `exec`, so it must share the shell alias to preserve PR-create provenance.+# Meta/MCP tools (`update_plan`, `list_mcp_resources`,+# `mcp__<server>__<tool>`, ...) intentionally pass through unaliased — they+# don't belong to a read/edit/shell bucket and tool_distribution should show+# their real names.+_CODEX: dict[str, str] = {+ "exec_command": "Bash",+ "exec": "Bash",+ "shell": "Bash",+ # stdin writes into a running exec session — shell interaction, same+ # bucket as Cursor's `AwaitShell`.+ "write_stdin": "Bash",+ "apply_patch": "Edit",+ "read_file": "Read",+ # Not a tool name but a `response_item` payload TYPE — Codex's built-in+ # browsing runs as unpaired `web_search_call` lines (no call_id, no+ # output line). `_group_into_turns` emits them as point-in-time tools+ # under this raw name; canonicalized here like Cursor's `web_search`.+ "web_search_call": "WebSearch",+}++# Cursor emits raw agent-internal tool names that differ from the canonical+# Claude/Codex vocabulary every downstream consumer keys off by+# `tool.name` (read/edit/search/shell counters in metrics.py, blind-edit/+# full-rewrite ordering, tool_distribution, subagent adoption). Without this+# alias table those buckets never match, so a Cursor session would show+# tools/turn but zero read/edit/search/shell counts. Includes the IDE+# `*_v2` names from live composers. Meta tools (TodoWrite, AskQuestion, CreatePlan,+# update_current_step, ...) intentionally pass through unaliased — they+# don't belong to a read/edit/write bucket.+_CURSOR: dict[str, str] = {+ # edits (Claude-ish + Cursor ACP)+ "StrReplace": "Edit",+ "StrConfReplace": "Edit",+ "ApplyPatch": "Edit",+ # reads / search (Claude-ish + Cursor ACP)+ "ReadFile": "Read",+ "ReadLints": "Read",+ "rg": "Grep",+ "SemanticSearch": "Search",+ # shell / execute (Claude-ish + Cursor ACP)+ "Shell": "Bash",+ "AwaitShell": "Bash",+ # subagent+ "Subagent": "Task",+ # IDE composer `*_v2` names (live state.vscdb / NDJSON) — without these,+ # tools/turn still counts but read/edit/search/shell buckets stay 0.+ "read_file_v2": "Read",+ "read_file": "Read",+ "read_lints": "Read",+ "edit_file_v2": "Edit",+ "edit_file": "Edit",+ "write_file_v2": "Write",+ "write_file": "Write",+ "run_terminal_command_v2": "Bash",+ "run_terminal_cmd": "Bash",+ "await": "Bash",+ "ripgrep_raw_search": "Grep",+ "glob_file_search": "Glob",+ "list_dir": "ListDir",+ "web_fetch": "WebFetch",+ "web_search": "WebSearch",+ "task_v2": "Task",+}++# Copilot's built-in tool vocabulary -> the canonical Claude names every+# consumer keys off (read/edit/search/shell counters in metrics.py, blind-edit+# and full-rewrite ordering, tool_distribution, sub-agent + skill capability+# detection). Names come from the Copilot CLI bundle's own tool classifier+# (bash/local_shell/stop_bash = execute; view/glob/grep/read_bash = read;+# edit/create/str_replace_editor/str_replace/write_bash = edit; web_search =+# search; web_fetch = fetch; update_todo = think; task/skill = other) plus the+# names seen in real transcripts. MCP tools (``github-mcp-server-*``) and+# meta tools (``report_intent``, ``ask_user``, ``sql``) pass through unaliased:+# they belong to no bucket and tool_distribution should show their real names.+_COPILOT: dict[str, str] = {+ # shell+ "bash": "Bash",+ "shell": "Bash",+ "local_shell": "Bash",+ "powershell": "Bash",+ # interaction with a still-running shell command: same bucket as Cursor's+ # ``AwaitShell`` and Codex's ``write_stdin``.+ "read_bash": "Bash",+ "write_bash": "Bash",+ "stop_bash": "Bash",+ # reads / search+ "view": "Read",+ "grep": "Grep",+ "glob": "Glob",+ # edits / writes. ``create`` writes a whole new file, so it is the+ # full-rewrite bucket; the str_replace family is an in-place edit.+ "edit": "Edit",+ "str_replace_editor": "Edit",+ "str_replace": "Edit",+ "apply_patch": "Edit",+ "create": "Write",+ # web+ "web_fetch": "WebFetch",+ "fetch_copilot_cli_documentation": "WebFetch",+ "web_search": "WebSearch",+ "github-mcp-server-web_search": "WebSearch",+ # semantic code search: same mapping Cursor's SemanticSearch gets.+ "search_code_subagent": "Search",+ # planning+ "update_todo": "TodoWrite",+ # sub-agents: drives the ``subagents`` capability and sub-agent adoption+ # metrics, which look for the canonical ``Task`` name.+ "task": "Task",+ # skills: ``_jsonl_utils._SKILL_TOOL_NAMES`` matches case-insensitively,+ # so the canonical casing keeps Copilot skill loads counted the same way.+ "skill": "Skill",+}++# Kiro emits its own tool vocabulary, which the consumers (read/edit/+# search/shell counters in metrics.py, tool_distribution, subagent adoption)+# don't recognise — they key off the canonical Claude/Codex names. Without this+# table a Kiro session would show tools-per-turn but zero read/edit/search+# buckets, exactly the failure `cursor_store.py::_TOOL_ALIASES` exists to+# prevent. Names verified against real ~/.kiro transcripts. Meta tools+# (`kiro_powers`, `subagent_response`) intentionally pass through unaliased —+# they belong to no bucket.+_KIRO: dict[str, str] = {+ # reads+ "read_file": "Read",+ "read_files": "Read",+ "readFile": "Read",+ # edits / writes+ "fs_write": "Write",+ "fsWrite": "Write",+ "fs_append": "Edit",+ "str_replace": "Edit",+ # search+ "grep_search": "Grep",+ "file_search": "Glob",+ "list_directory": "ListDir",+ # shell+ "execute_bash": "Bash",+ # subagent — drives the `subagents` capability + sub-agent adoption metrics,+ # which look for the canonical `Task`/`Agent` names.+ "invoke_sub_agent": "Task",+}++# opencode names its built-in tools in lowercase (`read`, `edit`, `bash`,+# ...) while every downstream consumer keys off the canonical+# Claude-cased vocabulary by `tool.name` (read/edit/search/shell counters in+# metrics.py, blind-edit/full-rewrite ordering, tool_distribution). Without+# this casing table those buckets never match, so an opencode session shows+# tools/turn but zero read/edit/shell counts. Mirrors+# `cursor_store.py::_TOOL_ALIASES` (same fix for Cursor's raw names). Names+# surveyed across two real multi-MB opencode transcripts (read/edit/grep/+# bash/webfetch/write/todowrite/glob/websearch/codesearch/task) plus the+# rest of opencode's core toolset (`patch`, `list`, `todoread`). Unknown+# names (MCP tools, future built-ins) pass through unchanged.+_OPENCODE: dict[str, str] = {+ "bash": "Bash",+ "edit": "Edit",+ # opencode's `patch` is its apply-a-diff mutation tool — same Edit+ # bucket as Codex's `apply_patch` / Cursor's `ApplyPatch`.+ "patch": "Edit",+ "write": "Write",+ "read": "Read",+ "grep": "Grep",+ "glob": "Glob",+ "list": "ListDir",+ "webfetch": "WebFetch",+ "websearch": "WebSearch",+ # semantic code search — same mapping cursor_store gives SemanticSearch.+ "codesearch": "Search",+ "todowrite": "TodoWrite",+ "todoread": "TodoRead",+ "task": "Task",+}++# Copilot IN VS CODE (Chat / agent mode), NOT the `copilot` CLI above -- a+# different product with its own tool schema. Rows are VS Code's own built-in+# tool identifiers, taken from `workspaceStorage/*/chatSessions/*.jsonl`+# request `toolCallRounds[].toolCalls[].name` values.+#+# Deliberately unmapped (pass through as their real name, same convention as+# an unrecognised or MCP tool): `get_errors`, `open_browser_page`,+# `read_page`, `run_playwright_code` (browser/diagnostic tools with no Claude+# equivalent) and `memory` (ambiguous -- an MCP server or a VS Code built-in,+# not yet confirmed).+_COPILOT_VSCODE: dict[str, str] = {+ # shell+ "run_in_terminal": "Bash",+ "get_terminal_output": "BashOutput",+ # reads / search+ "read_file": "Read",+ "read_notebook_cell_output": "NotebookRead",+ "grep_search": "Grep",+ "file_search": "Glob",+ "list_dir": "ListDir",+ # edits / writes. `create_file` writes a whole new file (full-rewrite+ # bucket); the replace family is an in-place edit, same split as Copilot+ # CLI's `create` vs `edit`/`str_replace_editor` above.+ "replace_string_in_file": "Edit",+ "multi_replace_string_in_file": "MultiEdit",+ "create_file": "Write",+ # planning / sub-agents+ "manage_todo_list": "TodoWrite",+ "runSubagent": "Task",+}++TOOL_ALIASES: dict[str, dict[str, str]] = {+ "codex": _CODEX,+ "cursor": _CURSOR,+ "copilot": _COPILOT,+ "copilot-vscode": _COPILOT_VSCODE,+ "kiro": _KIRO,+ "opencode": _OPENCODE,+}+++def aliases_for(agent: str) -> dict[str, str]:+ """The raw-name -> canonical-name table for one agent (empty for Claude Code)."""+ return TOOL_ALIASES.get(agent, {})diff --git a/python/src/agentplay/_core/pricing.py b/python/src/agentplay/_core/pricing.pynew file mode 100644index 0000000..d8c633d--- /dev/null+++ b/python/src/agentplay/_core/pricing.py@@ -0,0 +1,569 @@+"""The rate card: model pricing data and model-name normalization.++What lives here (data and pure string functions only):++- ``MODEL_RATES`` - the rate card. USD per **million** tokens.+ ``{"input": .., "output": ..}`` with optional per-million ``cache_read``+ / ``cache_write`` overrides; absent cache keys mean the standard+ multipliers apply (read 0.1x input, 5-minute write 1.25x, 1-hour write 2x).+ An entry pinned to ``None`` means "listed but price unfindable": lookups+ hit the unknown-model path, which must stay LOUD (warning), never a+ silent $0.+- ``strip_variant_suffix`` / ``canonicalize_family_order`` - the+ sampling-mode normalizer: agents decorate model names with effort/speed+ tokens ("claude-opus-4-8-thinking-medium", "composer-2-fast") and Cursor+ reverses family/version ("claude-4.6-sonnet"). Those select a sampling+ mode, not a different SKU (the provider bills the base model), so names+ are normalized before lookup instead of hand-adding every spelling.++House rule for edits: rates change HERE and nowhere else. When adding an+entry, cite the price-card URL in a comment like the existing rows do.+"""++from __future__ import annotations++import re++# ── the rate card ────────────────────────────────────────────────+MODEL_RATES: dict[str, dict[str, float] | None] = {+ # Base input/output rates from https://claude.com/pricing (Model pricing).+ # Prompt-cache rates aren't stored per model: cache reads/writes are derived+ # from `input` via the default multipliers+ # (read 0.1x, 5-min write 1.25x), which reproduce the published cache prices+ # exactly for every model below. Opus 4.7+ uses a new tokenizer (up to ~35%+ # more tokens for the same text) — that affects token COUNTS, already+ # captured per session, not the per-token rate here.+ # ── Anthropic (via Bedrock, us.* regional prefix) ──+ "us.anthropic.claude-opus-5": {"input": 5.0, "output": 25.0},+ "us.anthropic.claude-opus-4-8": {"input": 5.0, "output": 25.0},+ "us.anthropic.claude-opus-4-7": {"input": 5.0, "output": 25.0},+ "us.anthropic.claude-opus-4-6": {"input": 5.0, "output": 25.0},+ "us.anthropic.claude-opus-4-5": {"input": 5.0, "output": 25.0},+ "us.anthropic.claude-sonnet-4-6": {"input": 3.0, "output": 15.0},+ # Haiku 4.5 is $1.00/$5.00 per https://claude.com/pricing — the previous+ # $0.8/$4.0 here was Haiku 3.5's rate and underpriced every 4.5 session 20%.+ "us.anthropic.claude-haiku-4-5-20251001-v1:0": {"input": 1.0, "output": 5.0},+ "us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"input": 3.0, "output": 15.0},+ # Anthropic (via Bedrock — global.* cross-region prefix)+ "global.anthropic.claude-opus-5": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-opus-4-8": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-opus-4-7": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-opus-4-6": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-opus-4-5": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-sonnet-4-6": {"input": 3.0, "output": 15.0},+ "global.anthropic.claude-haiku-4-5-20251001-v1:0": {"input": 1.0, "output": 5.0},+ "global.anthropic.claude-sonnet-4-5-20250929-v1:0": {"input": 3.0, "output": 15.0},+ # Anthropic direct / Vercel AI Gateway aliases+ "anthropic/claude-opus-4.8": {"input": 5.0, "output": 25.0},+ "anthropic/claude-opus-4.7": {"input": 5.0, "output": 25.0},+ "anthropic/claude-opus-4.6": {"input": 5.0, "output": 25.0},+ "anthropic/claude-opus-4.5": {"input": 5.0, "output": 25.0},+ "anthropic/claude-sonnet-4.6": {"input": 3.0, "output": 15.0},+ "anthropic/claude-sonnet-4.5": {"input": 3.0, "output": 15.0},+ "anthropic/claude-haiku-4.5": {"input": 1.0, "output": 5.0},+ "anthropic/claude-opus-5": {"input": 5.0, "output": 25.0},+ "anthropic/claude-fable-5": {"input": 10.0, "output": 50.0},+ "anthropic/claude-mythos-5": {"input": 10.0, "output": 50.0},+ # Short names (stripped prefixes)+ "claude-opus-5": {"input": 5.0, "output": 25.0},+ # Verified 2026-09-28: https://platform.claude.com/docs/en/about-claude/pricing+ # $4/$20, 5m write $5 (default 1.25x), 1h write $8 (default 2x). Cache+ # reads are 0.05x input ($0.20), NOT the default 0.1x.+ "claude-opus-5-5": {+ "input": 4.0,+ "output": 20.0,+ "cache_read": 0.20,+ "cache_write": 5.0,+ },+ "claude-fable-5": {"input": 10.0, "output": 50.0},+ # Verified 2026-09-08: https://platform.claude.com/docs/en/models/fable-5-1/overview+ # Cache reads are 0.025x input, NOT Fable 5's default 0.1x.+ "claude-fable-5-1": {+ "input": 10.0,+ "output": 50.0,+ "cache_read": 0.25,+ "cache_write": 12.5,+ },+ "claude-mythos-5": {"input": 10.0, "output": 50.0},+ "claude-opus-4-8": {"input": 5.0, "output": 25.0},+ "claude-opus-4-7": {"input": 5.0, "output": 25.0},+ "claude-opus-4-6": {"input": 5.0, "output": 25.0},+ "claude-opus-4-5": {"input": 5.0, "output": 25.0},+ # Verified 2026-09-28: https://platform.claude.com/docs/en/about-claude/pricing+ # Opus 4.1 and Opus 4 never took the 4.5-generation cut: $15/$75, 5m+ # write $18.75, read $1.50 (default multipliers). Both are retired on+ # the Claude API but can still appear in agent transcripts.+ "claude-opus-4-1": {"input": 15.0, "output": 75.0},+ "claude-opus-4": {"input": 15.0, "output": 75.0},+ # Verified 2026-09-11: the planned September increase was cancelled.+ # https://platform.claude.com/docs/en/about-claude/pricing+ "claude-sonnet-5": {"input": 2.0, "output": 10.0},+ "claude-sonnet-4-6": {"input": 3.0, "output": 15.0},+ "claude-sonnet-4-5": {"input": 3.0, "output": 15.0},+ "claude-sonnet-4-5-20250929": {"input": 3.0, "output": 15.0},+ "claude-sonnet-4-5-20250514": {"input": 3.0, "output": 15.0},+ "claude-sonnet-4-20250514": {"input": 3.0, "output": 15.0},+ # Verified 2026-09-28: https://platform.claude.com/docs/en/about-claude/pricing+ # Sonnet 4 undated router id; same $3/$15 card as the dated SKU above.+ "claude-sonnet-4": {"input": 3.0, "output": 15.0},+ "claude-haiku-4-5": {"input": 1.0, "output": 5.0},+ "claude-haiku-4-5-20251001": {"input": 1.0, "output": 5.0},+ "claude-3-7-sonnet-latest": {"input": 3.0, "output": 15.0},+ "claude-3-5-sonnet-20241022": {"input": 3.0, "output": 15.0},+ # Haiku 3.5 (not 4.5) really is $0.80/$4.00 — do not "fix" to match 4.5.+ "claude-3-5-haiku-20241022": {"input": 0.8, "output": 4.0},+ # Haiku 3 (router ``claude-3-haiku``; canonical order ``claude-haiku-3``).+ # Retired 2026-04-20 and dropped from the live pricing page; verified+ # 2026-09-28 against Anthropic's own page as archived 2025-09-16:+ # https://web.archive.org/web/20250916142058/https://docs.anthropic.com/en/docs/about-claude/pricing+ # $0.25/$1.25, 5m write $0.30 (1.2x, not 1.25x), read $0.03 (not 0.1x).+ "claude-haiku-3": {+ "input": 0.25,+ "output": 1.25,+ "cache_read": 0.03,+ "cache_write": 0.30,+ },+ # Cursor-style "-thinking" aliases: thinking is a mode, not a rate card —+ # billed at the base model's prices (https://claude.com/pricing; thinking+ # tokens are ordinary output tokens).+ "claude-4.5-sonnet-thinking": {"input": 3.0, "output": 15.0},+ "claude-4.5-haiku-thinking": {"input": 1.0, "output": 5.0},+ "claude-4.5-opus-thinking": {"input": 5.0, "output": 25.0},+ # ── OpenAI ───────────────────────────────────────────────────────────────+ # Standard-tier input/output from the OpenAI pricing page. (The cached-input+ # column isn't stored — the agent-cost cache split is Anthropic-shaped and+ # OpenAI sessions here carry no cache breakdown.) Codex variants are priced+ # at their base model's rate, matching the existing gpt-5.2-codex entry.+ # GPT-5.5 cached input is $0.50/M on OpenAI DIRECT (90% off, per the OpenAI+ # pricing page and every tracker; verified 2026-08-07). The previous $5-flat+ # cache_read here over-generalized a gateway-specific rate (that+ # gateway charges cached = uncached) to the model itself, over-billing every cache-heavy+ # direct Codex session ~10x on cache reads. If gateway traffic ever needs+ # pricing, give its model ref its own no-discount entry instead of+ # re-widening this one. cache_write stays at the input rate: OpenAI bills+ # cache writes as ordinary input, so this keeps the write term neutral.+ "gpt-5.5": {"input": 5.0, "output": 30.0, "cache_read": 0.50, "cache_write": 5.0},+ # GPT-5.6 Sol — $5/$30 per the OpenAI list price mirrored at+ # https://openrouter.ai/openai/gpt-5.6-sol and+ # https://www.aipricing.guru/openai-pricing/ (July 2026).+ "gpt-5.6-sol": {"input": 5.0, "output": 30.0},+ # Verified 2026-09-08: https://developers.openai.com/api/docs/models/gpt-6-astra+ # STANDARD base rates. >272K input PER REQUEST costs 2x input/cache and+ # 1.5x output. Session aggregates cannot determine that request tier;+ # this card's session estimate is not an exact long-context invoice.+ "gpt-6-astra": {+ "input": 10.0,+ "output": 50.0,+ "cache_read": 1.0,+ "cache_write": 12.5,+ "long_context_threshold": 272_000,+ "long_context_input_multiplier": 2.0,+ "long_context_output_multiplier": 1.5,+ },+ # GPT-5.6 Terra / Luna — OpenAI LIST price per the 2026-07-30 price cut+ # (Luna -80%, Terra to $2/$12; https://www.aipricing.guru/openai-pricing/,+ # openai.com "Advancing the price-performance frontier with GPT-5.6").+ # Sessions priced here run on the user's own account (Codex reports+ # terra), so list is the right card.+ # Cached input is 90% off and cache writes 1.25x for the whole 5.6 family,+ # which the default multipliers already reproduce — no overrides needed.+ "gpt-5.6-terra": {"input": 2.0, "output": 12.0},+ "gpt-5.6-luna": {"input": 0.20, "output": 1.20},+ # Verified 2026-09-23: https://developers.openai.com/api/docs/models/gpt-6-luna+ # Standard rates; requests above 272K input tokens use 2x input/cache+ # and 1.5x output for the full request.+ "gpt-6-luna": {+ "input": 0.10,+ "output": 0.50,+ "cache_read": 0.01,+ "cache_write": 0.125,+ "long_context_threshold": 272_000,+ "long_context_input_multiplier": 2.0,+ "long_context_output_multiplier": 1.5,+ },+ # GPT-5.3-Codex-Spark is a RESEARCH PREVIEW with no OpenAI-published rate+ # card as of 2026-07. ESTIMATE: priced at the base gpt-5.3-codex API card+ # ($1.75/$14) — the assumption third-party estimators also make — because a+ # plausible estimate beats a silent $0. Revisit when OpenAI finalizes rates.+ # "-high" is a reasoning-effort tag, not a separate rate card.+ "gpt-5.3-codex-spark": {"input": 1.75, "output": 14.0},+ "gpt-5.3-codex-spark-high": {"input": 1.75, "output": 14.0},+ "gpt-5.4": {"input": 2.5, "output": 15.0},+ "gpt-5.4-mini": {"input": 0.75, "output": 4.5},+ "gpt-5.4-nano": {"input": 0.2, "output": 1.25},+ "gpt-5.2": {"input": 1.75, "output": 14.0},+ "gpt-5": {"input": 1.25, "output": 10.0},+ "gpt-5-mini": {"input": 0.25, "output": 2.0},+ "gpt-5-nano": {"input": 0.05, "output": 0.4},+ "gpt-5-codex": {"input": 1.25, "output": 10.0},+ "gpt-5.3-codex": {"input": 1.75, "output": 14.0},+ "openai/gpt-5.3-codex": {"input": 1.75, "output": 14.0},+ # codex-max/-mini have no separately published rate; priced at the closest+ # base tier (gpt-5.1 / gpt-5-mini) per the codex=base convention above.+ "gpt-5.1-codex-max": {"input": 1.25, "output": 10.0},+ "gpt-5.1-codex-mini": {"input": 0.25, "output": 2.0},+ "openai/gpt-5.2-codex": {"input": 1.75, "output": 14.0},+ "gpt-5.2-codex": {"input": 1.75, "output": 14.0},+ "openai/gpt-4.1": {"input": 2.0, "output": 8.0},+ "openai/gpt-4o-mini": {"input": 0.15, "output": 0.60},+ "openai/gpt-4o": {"input": 2.5, "output": 10.0},+ "gpt-5.1": {"input": 1.25, "output": 10.0},+ "gpt-5.3-chat-latest": {"input": 2.0, "output": 8.0},+ "gpt-4.1": {"input": 2.0, "output": 8.0},+ "gpt-4o": {"input": 2.5, "output": 10.0},+ "gpt-4o-mini": {"input": 0.15, "output": 0.60},+ "gpt-4-turbo": {"input": 10.0, "output": 30.0},+ # ── Google ───────────────────────────────────────────────────────────────+ "google/gemini-3-flash": {"input": 0.5, "output": 3.0},+ "gemini/gemini-2.5-flash-preview-05-20": {"input": 0.5, "output": 3.0},+ "google/gemini-2.5-flash": {"input": 0.5, "output": 3.0},+ "gemini-3-flash": {"input": 0.5, "output": 3.0},+ "gemini-2.0-flash": {"input": 0.1, "output": 0.4},+ "gemini-1.5-pro": {"input": 1.25, "output": 5.0},+ "gemini-1.5-flash": {"input": 0.075, "output": 0.3},+ # ── Zhipu (Z.ai) ────────────────────────────────────────────────────────+ # GLM-5.2 — $1.40/$4.40 on the official Z.ai API, per+ # https://www.requesty.ai/models/zai/glm-5.2 (mirrors the official rate;+ # resellers like OpenRouter discount below it — we pin the official rate).+ "glm-5.2": {"input": 1.4, "output": 4.4},+ # Fireworks' router alias for the same SKU.+ "FW-GLM-5.2": {"input": 1.4, "output": 4.4},+ # ── Cursor Composer ─────────────────────────────────────────────────────+ # Rates from https://cursor.com/docs/models-and-pricing.md (composer-1,+ # composer-2.5 incl. cache-read) and https://www.vantage.sh/blog/cursor-composer-2+ # + https://www.digitalapplied.com/blog/cursor-composer-1-5-ai-coding-model-guide+ # (composer-2 / composer-1.5). Cache keys are explicit per-1M overrides+ # where Cursor publishes them (Cursor's read rate is 0.1x input; no+ # published write surcharge for composer-1/2.5).+ "composer-1": {"input": 1.25, "output": 10.0, "cache_read": 0.125},+ "composer-1.5": {+ "input": 3.5,+ "output": 17.5,+ "cache_read": 0.35,+ "cache_write": 3.5,+ },+ "composer-2": {"input": 0.5, "output": 2.5},+ "composer-2.5": {"input": 0.5, "output": 2.5, "cache_read": 0.2},+ # ── Morph ───────────────────────────────────────────────────────────────+ # Morph API pricing unknown — None (not 0/0) so lookups hit the LOUD+ # unknown-model path instead of silently recording $0, per the module+ # contract above.+ "morph-v3-large": None,+ # ── Fireworks / deployed models ─────────────────────────────────────────+ # Full serverless deepseek-r1 (671B MoE), as logged for+ # model="accounts/fireworks/models/deepseek-r1".+ "deepseek-r1": {"input": 0.56, "output": 1.68},+ # ── MiniMax / Moonshot ────────────────+ # MiniMax M3 standard tier (≤512K input): $0.30/$1.20, cache read $0.06+ # per https://openrouter.ai/minimax/minimax-m3 (mirrors the official+ # billed rate; the >512K tier is 2x, not modeled; typical sessions are+ # far below it).+ "minimax-m3": {"input": 0.30, "output": 1.20, "cache_read": 0.06},+ # Kimi K3: $3/$15 flat across the 1M window, cache-hit input $0.30 —+ # exactly the default 0.1x read multiplier, so no override needed.+ # https://openrouter.ai/moonshotai/kimi-k3+ "kimi-k3": {"input": 3.0, "output": 15.0},+ # ── xAI Grok. Base tier (<200K prompts):+ # grok-4.5 $2/$6 (cached input $0.50 = 0.25x, override), grok-code-fast-1+ # $1/$2 per https://benchlm.ai/xai/api-pricing + layer3labs guides.+ # The >=200K high-context 2x surcharge is not modeled (tier data absent+ # per session); grok-4.6 mirrors 4.5's published base rate.+ "grok-4.5": {"input": 2.0, "output": 6.0, "cache_read": 0.50},+ "grok-4.6": {"input": 2.0, "output": 6.0, "cache_read": 0.50},+ "grok-code-fast-1": {"input": 1.0, "output": 2.0},+ # ── OpenAI gpt-5.1 base tier (codex=base convention above) ──────────────+ "gpt-5.1": {"input": 1.25, "output": 10.0},+ "gpt-5.1-codex": {"input": 1.25, "output": 10.0},+ # ── Cursor display-name aliases (UI labels, not catalog ids) ────────────+ # "Opus 5 (Auto Balanced)" slugs to opus-5 after the paren-strip ++ # space-slug candidates in normalize_model_key.+ "opus-5": {"input": 5.0, "output": 25.0},+ # ── Local inference — DELIBERATELY $0, not unpriced ─────────────────────+ # Ollama/MLX/gguf models run on the user's own hardware: a $0 rate is the+ # honest price, and an explicit entry keeps them out of the unpriced+ # warning.+ #+ # `"free": True` marks the zero as the real price. Without it these entries+ # are indistinguishable from an all-zero PLACEHOLDER whose rate is unknown.+ "gemma4": {"input": 0.0, "output": 0.0, "free": True},+ "qwen3.8:27b-mlx-32k": {"input": 0.0, "output": 0.0, "free": True},+ "canned-1b.gguf": {"input": 0.0, "output": 0.0, "free": True},+ # Ollama tags carry an explicit `:<size>` suffix and always run locally.+ # Same reasoning - genuinely free, not unknown.+ "qwen3-coder:30b": {"input": 0.0, "output": 0.0, "free": True},+ "qwen2.5-coder:7b": {"input": 0.0, "output": 0.0, "free": True},+ "qwen2.5-coder:1.5b": {"input": 0.0, "output": 0.0, "free": True},+ "gpt-oss:20b": {"input": 0.0, "output": 0.0, "free": True},+ # ── Moonshot Kimi K2.x ──────────────────────+ # K2.7 Code: Moonshot's standard rate is $0.95/$4.00 with cache-hit input $0.19+ # (openrouter.ai/moonshotai/kimi-k2.7-code, benchlm.ai/moonshot/api-pricing,+ # Aug 2026). Third-party resellers quote $0.67-$0.95 in; the official rate+ # is used here, consistent with kimi-k3 above. Cache read is an explicit+ # override because 0.19/0.95 = 0.2x, not the default 0.1x.+ "kimi-k2.7-code": {"input": 0.95, "output": 4.0, "cache_read": 0.19},+ # K2.5: Moonshot's own rate is $0.60/$3.00 (OpenRouter resells at+ # $0.375/$2.025). Official rate, same convention as above. Cache read+ # $0.07 is published, an explicit override at ~0.12x.+ "kimi-k2.5": {"input": 0.60, "output": 3.0, "cache_read": 0.07},+ # ── Google Gemini 3.1 Pro ───────────────────+ # $2/$12 base tier (<=200K prompts), cache read $0.20. The >200K tier is+ # $4/$18 and is NOT modeled — per-session prompt tier is not recorded,+ # the same simplification the Grok entries above make.+ "gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.20},+ # DeepSeek V4 Pro — $0.44/$0.88 official base rate (¥3/¥6 per 1M),+ # verified 2026-08-18 (openrouter.ai/deepseek/deepseek-v4-pro and+ # orcarouter.ai list the same figures). CAVEAT: DeepSeek introduced+ # peak/off-peak OUTPUT tiers on 2026-08-17 (¥13.5/¥27 per 1M); this entry+ # keeps the flat base rate.+ "deepseek-v4-pro": {"input": 0.44, "output": 0.88},+ "gpt-3.5-turbo-16k": {"input": 3.00, "output": 4.00},+ "gpt-4o-2024-08-06": {"input": 2.50, "output": 10.00},+ "gpt-4o-2024-11-20": {"input": 2.50, "output": 10.00},+ # ── NVIDIA ──────────────────────────────────────────────────────────────+ "nvidia.nemotron-super-3-120b": {"input": 0.20, "output": 0.20},+ # ── Bedrock catalog spellings + Haiku 4.6 ──────────────────────────────+ # Cache rates for all of them are the standard Anthropic multipliers, so+ # input/output suffices.+ "global.anthropic.claude-opus-4-8-v1:0": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-opus-5-v1:0": {"input": 5.0, "output": 25.0},+ "global.anthropic.claude-fable-5-v1:0": {"input": 10.0, "output": 50.0},+ "global.anthropic.claude-mythos-5-v1:0": {"input": 10.0, "output": 50.0},+ # AWS public pricing, 2026-09-12: global $2/$10, commercial geo $2.20/$11.+ "global.anthropic.claude-sonnet-5-v1:0": {"input": 2.0, "output": 10.0},+ "us.anthropic.claude-sonnet-5-v1:0": {"input": 2.2, "output": 11.0},+ "eu.anthropic.claude-sonnet-5-v1:0": {"input": 2.2, "output": 11.0},+ "ap.anthropic.claude-sonnet-5-v1:0": {"input": 2.2, "output": 11.0},+ "global.anthropic.claude-haiku-4-6-v1:0": {"input": 1.0, "output": 5.0},+ "claude-haiku-4-6": {"input": 1.0, "output": 5.0},+}++# Rate-card keys are matched case-INSENSITIVELY: every lookup resolves through+# `normalize_model_key`, which lower-cases the id. Fold any as-authored mixed-case+# key to lowercase so it stays reachable. Folded in place so the literal above+# keeps its human-readable spelling.+MODEL_RATES = {k.lower(): v for k, v in MODEL_RATES.items()}++# Provider spellings share the exact card entry, so cache-rate corrections+# cannot drift between the short id, gateway and Bedrock spellings.+for _alias in (+ "anthropic/claude-fable-5-1",+ "anthropic.claude-fable-5-1",+ "anthropic.claude-fable-5-1-v1:0",+ "global.anthropic.claude-fable-5-1",+ "global.anthropic.claude-fable-5-1-v1:0",+):+ MODEL_RATES[_alias] = MODEL_RATES["claude-fable-5-1"]+# Opus 5.5 under every spelling its Opus 5 sibling carries: dotted gateway+# id (OpenRouter's anthropic/claude-opus-5.5), Bedrock global + regional+# profiles (regional collapses to global — same card, as for Opus 5), the+# Bedrock catalog ``-v1:0`` form, and Cursor's "Opus 5.5 (...)" display slug.+for _alias in (+ "anthropic/claude-opus-5.5",+ "anthropic/claude-opus-5-5",+ "us.anthropic.claude-opus-5-5",+ "global.anthropic.claude-opus-5-5",+ "global.anthropic.claude-opus-5-5-v1:0",+ "opus-5.5",+):+ MODEL_RATES[_alias] = MODEL_RATES["claude-opus-5-5"]+MODEL_RATES["openai/gpt-6-astra"] = MODEL_RATES["gpt-6-astra"]+MODEL_RATES["openai/gpt-6-luna"] = MODEL_RATES["gpt-6-luna"]++# ── sampling-mode normalization ─────────────────────────────────────────+# Effort / speed / reasoning tokens agents append to a model name. They+# select a SAMPLING MODE, not a different priced model — the provider bills+# the base model's rates — but they made catalog lookups miss and price the+# session at $0 while their base names priced correctly.+VARIANT_TOKENS: frozenset[str] = frozenset(+ {"thinking", "high", "medium", "low", "fast", "xhigh", "minimal", "max"}+)++# Cursor emits the Claude family and version in the opposite order+# ("claude-4.6-sonnet" for "claude-sonnet-4-6"), which no catalog knows.+_CURSOR_FAMILY_RE = re.compile(+ r"^claude-(?P<ver>\d+(?:[.\-]\d+)?)-(?P<family>opus|sonnet|haiku|fable|mythos)$"+)++# Gateway / router ids keep the family first but write the version dotted+# ("claude-opus-4.6", the LiteLLM router and OpenRouter spelling), while the+# card keys the dashed first-party id ("claude-opus-4-6"). Same SKU, same+# bill - fold the dot so both spellings reach the one entry.+_DOTTED_VERSION_RE = re.compile(+ r"^claude-(?P<family>opus|sonnet|haiku|fable|mythos)-(?P<major>\d+)\.(?P<minor>\d+)$"+)+++def strip_variant_suffix(s: str) -> str:+ """Drop trailing effort/reasoning-mode tokens (see ``VARIANT_TOKENS``).++ Only whole hyphen-delimited tokens are removed, and only from the tail,+ so dated ids (``claude-haiku-4-5-20251001``) and names that merely+ contain a variant word are untouched.+ """+ parts = s.split("-")+ while len(parts) > 1 and parts[-1] in VARIANT_TOKENS:+ parts.pop()+ return "-".join(parts)+++def canonicalize_family_order(s: str) -> str:+ """``claude-4.6-sonnet`` / ``claude-sonnet-4.6`` → ``claude-sonnet-4-6``.++ Cursor reverses family and version; gateways keep the order but dot the+ version. Both are spellings of the dashed first-party id.+ """+ m = _CURSOR_FAMILY_RE.match(s)+ if m:+ return f"claude-{m.group('family')}-{m.group('ver').replace('.', '-')}"+ m = _DOTTED_VERSION_RE.match(s)+ if m:+ return f"claude-{m.group('family')}-{m.group('major')}-{m.group('minor')}"+ return s+++# Bedrock regional inference-profile prefixes. The card stores one entry per+# model under the ``global.`` catalog form unless an explicit regional rate+# exists. Preserve known regional premiums before the legacy global fallback.+_BEDROCK_REGIONAL_PREFIXES = ("us.anthropic.", "eu.anthropic.", "ap.anthropic.")+++_BEDROCK_GLOBAL_PREFIX = "global.anthropic."+++def canonicalize_bedrock_region(s: str) -> str:+ """Preserve explicit regional premiums; otherwise use the global catalog key.++ The model part is family-canonicalized too: ``canonicalize_family_order``+ only matches bare ``claude-…`` strings, so a reversed family INSIDE a+ prefixed id (``us.anthropic.claude-4.6-sonnet``) would otherwise survive+ the region rewrite un-fixed and miss the card.+ """+ for prefix in (*_BEDROCK_REGIONAL_PREFIXES, _BEDROCK_GLOBAL_PREFIX):+ if s.startswith(prefix):+ tail = canonicalize_family_order(s[len(prefix) :])+ regional = prefix + tail+ global_key = _BEDROCK_GLOBAL_PREFIX + tail+ if regional in MODEL_RATES and MODEL_RATES[regional] != MODEL_RATES.get(global_key):+ return regional+ return global_key+ return s+++# Fireworks catalog ids encode version dots as ``p`` (``glm-5p2`` is GLM-5.2,+# ``llama-v3p1`` is Llama 3.1) and arrive as full paths+# (``accounts/fireworks/models/glm-5p2``); neither the path nor the ``p``+# spelling would otherwise reach the card's ``glm-5.2`` entry.+_FIREWORKS_DOT_RE = re.compile(r"(?<=\d)p(?=\d)")++# Trailing release-date stamp (``z-ai/glm-5.2-20260616``). Candidate-only:+# a dated SKU with its own card entry (``claude-haiku-4-5-20251001``) hits+# the card exactly BEFORE this strip is ever tried, so it never rewrites a+# genuinely dated price.+_DATE_SUFFIX_RE = re.compile(r"-20\d{6}$")++# Cursor UI display labels: a parenthetical mode suffix ("Cursor Grok 4.5+# (Auto Balanced)") and spaces instead of hyphens. Both are candidates only —+# adopted solely on an exact card hit, same contract as the path/dot rules.+_PAREN_SUFFIX_RE = re.compile(r"\s*\([^)]*\)\s*$")+++def _display_slugged(s: str) -> str:+ """``cursor grok 4.5 (auto balanced)`` → ``cursor-grok-4.5``."""+ return _PAREN_SUFFIX_RE.sub("", s).strip().replace(" ", "-")+++def _cursor_prefix_stripped(s: str) -> str:+ """``cursor-grok-4.5`` → ``grok-4.5`` — Cursor prefixes third-party SKUs."""+ return s[len("cursor-") :] if s.startswith("cursor-") else s+++def _dot_folded(s: str) -> str:+ """``glm-5p2`` → ``glm-5.2`` (Fireworks' dot encoding, digits-only guard)."""+ return _FIREWORKS_DOT_RE.sub(".", s)+++def _date_stripped(s: str) -> str:+ """``glm-5.2-20260616`` → ``glm-5.2`` (trailing release-date stamp)."""+ return _DATE_SUFFIX_RE.sub("", s)+++def normalize_model_key(model_id: str) -> str:+ """Lower-case + variant-strip + family-order + region/path/dot fix — the shared key.++ A real SKU whose tail merely LOOKS like a sampling-mode token — e.g. the+ priced ``gpt-5.1-codex-max`` (the card carries the ``-max`` SKU, not a bare+ ``gpt-5.1-codex``) — is returned WITHOUT variant-stripping so it keeps+ matching the card. Generic effort/speed tails (``-high``, ``-thinking``, …)+ still strip, because for those the base name IS the priced model. In short:+ prefer an exact rate-card hit before applying generic suffix stripping+.++ Provider catalog paths (``accounts/<owner>/models/<name>``) and Fireworks'+ dot-encoding are handled as CANDIDATES only: a transform is adopted solely+ on an exact rate-card hit, so any id these rules don't recognize returns+ exactly what it did before this change (no fallback-behavior drift).+ """+ lowered = (model_id or "").lower()+ if "claude" in lowered:+ lowered = re.sub(r"(?:\[1m\]|-1m)$", "", lowered)+ unstripped = canonicalize_bedrock_region(canonicalize_family_order(lowered))+ if unstripped in MODEL_RATES:+ return unstripped+ base = lowered.rsplit("/", 1)[-1] if "/" in lowered else lowered+ slugged = _display_slugged(base)+ for cand in (+ canonicalize_family_order(base),+ _dot_folded(canonicalize_family_order(base)),+ _date_stripped(canonicalize_family_order(base)),+ canonicalize_family_order(strip_variant_suffix(base)),+ _dot_folded(canonicalize_family_order(strip_variant_suffix(base))),+ _date_stripped(_dot_folded(canonicalize_family_order(strip_variant_suffix(base)))),+ # Cursor display labels and cursor- prefixed SKUs:+ # each is candidate-only — adopted solely on an exact card hit.+ slugged,+ strip_variant_suffix(slugged),+ _cursor_prefix_stripped(strip_variant_suffix(slugged)),+ ):+ if cand in MODEL_RATES:+ return cand+ return canonicalize_bedrock_region(canonicalize_family_order(strip_variant_suffix(lowered)))+++__all__ = [+ "canonicalize_bedrock_region",+ "MODEL_RATES",+ "VARIANT_TOKENS",+ "canonicalize_family_order",+ "normalize_model_key",+ "response_speed_multiplier",+ "strip_variant_suffix",+]+++def response_speed_multiplier(model: str, speed: str | None) -> float | None:+ """Price observed response speed; unsupported premium evidence stays unknown.++ Anthropic fast-mode rates verified 2026-09-11: Opus 5/4.8 use $10/$50+ versus $5/$25, with the same multiplier on cache rates. Do not infer this+ from a requested mode: fallback responses explicitly report standard.+ https://platform.claude.com/docs/en/build-with-claude/fast-mode+ Opus 5.5 fast mode verified 2026-09-28: $8/$40 versus $4/$20 (also 2x),+ https://platform.claude.com/docs/en/about-claude/pricing+ """+ if speed in (None, "", "standard"):+ return 1.0+ key = normalize_model_key(model)+ for prefix in ("anthropic/", "us.anthropic.", "global.anthropic."):+ key = key.removeprefix(prefix)+ key = re.sub(r"-v\d+:\d+$", "", key)+ key = key.replace("opus-4.8", "opus-4-8").replace("opus-5.5", "opus-5-5")+ if speed == "fast" and key in {+ "claude-opus-5-5",+ "claude-opus-5",+ "claude-opus-4-8",+ "opus-5-5",+ "opus-5",+ "opus-4-8",+ }:+ return 2.0+ return Nonediff --git a/python/src/agentplay/_util.py b/python/src/agentplay/_util.pynew file mode 100644index 0000000..d2ce6f9--- /dev/null+++ b/python/src/agentplay/_util.py@@ -0,0 +1,25 @@+"""Small shared helpers."""++from __future__ import annotations++import contextlib+import logging++logger = logging.getLogger("agentplay")+++class captured(contextlib.AbstractContextManager): # noqa: N801 - reads like suppress()+ """Suppress and log any exception raised inside the block.++ Used on best-effort paths (metadata, enrichment) where one odd record must+ never fail a whole map build. The exception is logged at debug level so+ ``--verbose`` surfaces it.+ """++ def __exit__(self, exc_type, exc, tb) -> bool:+ if exc_type is None:+ return False+ if issubclass(exc_type, (KeyboardInterrupt, SystemExit)):+ return False+ logger.debug("suppressed %s: %s", exc_type.__name__, exc)+ return Truediff --git a/python/src/agentplay/account.py b/python/src/agentplay/account.pynew file mode 100644index 0000000..aaa86a5--- /dev/null+++ b/python/src/agentplay/account.py@@ -0,0 +1,220 @@+"""The optional email signup: local state, and the package's only network call.++When someone types their email into the viewer's welcome card, the local server+sends it to the signup endpoint with :func:`send`. That is the one place the+package talks to the network, and this is the one file that imports a network+client. ``grep -rn urllib.request python/src/`` finds it and nothing else.++What is sent is the event (``signup`` or ``disconnect``), the email, a random+install id and the package version. No session data, no paths, no repo names.++Nothing is sent when ``DO_NOT_TRACK`` or ``AGENTPLAY_NO_NETWORK`` is set, or when+no endpoint is configured; the viewer then skips the card entirely.++State lives in ``~/.agentplay/account.json``::++ {"status": "signed_up" | "skipped", "email": "...", "installId": "...", "at": "..."}+"""++from __future__ import annotations++import contextlib+import http.client+import ipaddress+import json+import os+import re+import urllib.error+import urllib.request+import uuid+from datetime import UTC, datetime+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit++from . import __version__+from .store import _atomic_write, root++# The endpoint the welcome card posts to: a Google Apps Script web app that+# appends a row to a Sheet. AGENTPLAY_SIGNUP_URL overrides it (for testing).+# To change the script, edit this deployment rather than making a new one, or+# released copies keep posting here. See docs/signup-endpoint.md.+DEFAULT_SIGNUP_URL = (+ "https://script.google.com/macros/s/"+ "AKfycbzmLDzEVW3e25b2Zc96sd7uLoKLGGCTv1h52S7IXLOZV64tmm4AV_85c7U92eCDGM5o/exec"+)+TIMEOUT_S = 8+# The only hosts an email may go to over https: a Google Apps Script web app+# (which answers from googleusercontent after a redirect) or Entelligence.+TRUSTED_HOSTS = ("script.google.com", "script.googleusercontent.com", "entelligence.ai")+# \ufeff too: JavaScript's \s matches it and Python's does not, and the signup+# endpoint (docs/signup-endpoint.md) checks with this same pattern in JavaScript.+_EMAIL = re.compile(r"^[^@\s\ufeff]{1,64}@[^@\s\ufeff]+\.[^@\s\ufeff]{2,}$")+_OFF = {"", "0", "false", "no", "off"}+++def path() -> Path:+ return root() / "account.json"+++def signup_url() -> str:+ return (os.environ.get("AGENTPLAY_SIGNUP_URL") or DEFAULT_SIGNUP_URL).strip()+++def _trusted_https(parts: Any, host: str) -> bool:+ return parts.scheme == "https" and any(host == h or host.endswith("." + h) for h in TRUSTED_HOSTS)+++def _local_http(parts: Any, host: str) -> bool:+ if parts.scheme != "http":+ return False+ if host == "localhost":+ return True+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return False+++def allowed_url(url: str, *, local: bool = True) -> bool:+ """``https`` to a trusted host, or ``http`` to this machine (the local stand-in).++ The URL comes from ``DEFAULT_SIGNUP_URL`` or the user's own environment, never+ from a request. Even so, nothing else is reachable: urllib also speaks+ ``file://`` and ``ftp://``, and an arbitrary https host could be an internal+ service. Checked again on every redirect. ``local=False`` refuses the http+ stand-in too.+ """+ try:+ parts = urlsplit(url)+ host = (parts.hostname or "").lower()+ except ValueError:+ return False+ if not host or parts.username or parts.password:+ return False+ return _trusted_https(parts, host) or (local and _local_http(parts, host))+++class _CheckedRedirects(urllib.request.HTTPRedirectHandler):+ """Follow a redirect only to a URL :func:`allowed_url` accepts.++ A redirect may land on this machine only from a URL that was already there+ (a local test endpoint): the real endpoint answering with a redirect to+ ``http://127.0.0.1`` must not turn into a request to a local service.+ """++ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ANN201 - urllib's signature+ came_from_local = allowed_url(req.full_url) and not allowed_url(req.full_url, local=False)+ if not allowed_url(newurl, local=came_from_local):+ raise urllib.error.HTTPError(newurl, code, "redirect to an untrusted host", headers, fp)+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++_opener = urllib.request.build_opener(_CheckedRedirects)+++def network_disabled() -> bool:+ """True when the user has asked for no network at all, by either convention."""+ return any(+ (os.environ.get(var) or "").strip().lower() not in _OFF for var in ("DO_NOT_TRACK", "AGENTPLAY_NO_NETWORK")+ )+++def valid_email(email: str) -> bool:+ return len(email) <= 254 and bool(_EMAIL.match(email))+++def load() -> dict[str, Any]:+ try:+ data = json.loads(path().read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ return data if isinstance(data, dict) else {}+++def _save(data: dict[str, Any]) -> None:+ _atomic_write(path(), json.dumps(data, indent=2).encode("utf-8"))+++def _install_id(state: dict[str, Any]) -> str:+ iid = state.get("installId")+ return iid if isinstance(iid, str) and iid else uuid.uuid4().hex+++def _now() -> str:+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def public_state() -> dict[str, Any]:+ """What the viewer needs to decide whether to show the card."""+ state = load()+ status = state.get("status") if state.get("status") in ("signed_up", "skipped") else "none"+ return {+ "status": status,+ "email": state.get("email") if status == "signed_up" else None,+ # The card is only offered when an email could actually be delivered.+ "enabled": allowed_url(signup_url()) and not network_disabled(),+ }+++def send(event: str, email: str, install_id: str) -> None:+ """POST one event to the signup endpoint. Raises ``OSError`` if it can't be delivered."""+ url = signup_url()+ if not url or network_disabled():+ raise OSError("signup is turned off")+ if not allowed_url(url):+ raise OSError("signup URL must be https (or http to this machine)")+ body = json.dumps({"event": event, "email": email, "installId": install_id,+ "version": __version__, "at": _now()}).encode("utf-8")+ req = urllib.request.Request(url, data=body, method="POST",+ headers={"Content-Type": "application/json", "User-Agent": f"agentplay/{__version__}"})+ # A Google Apps Script web app answers a POST with a redirect to its output;+ # urllib follows it as a GET, the same as `curl -L`. The row is written by+ # the POST either way.+ try:+ with _opener.open(req, timeout=TIMEOUT_S) as resp:+ if resp.status >= 400:+ raise OSError(f"signup endpoint answered {resp.status}")+ answer = resp.read(4096)+ except http.client.HTTPException as exc: # a malformed answer is a failed delivery too+ raise OSError(f"signup endpoint answered badly: {exc}") from exc+ # Apps Script reports a crashed script as a 200 HTML error page, so the+ # status alone proves nothing. Only an explicit {"ok": true} counts.+ try:+ ok = json.loads(answer).get("ok") is True+ except (ValueError, AttributeError, RecursionError):+ ok = False+ if not ok:+ raise OSError("signup endpoint did not confirm the row was written")+++def sign_up(email: str) -> dict[str, Any]:+ """Deliver the email, then remember it. Nothing is stored if delivery fails."""+ state = load()+ iid = _install_id(state)+ send("signup", email, iid)+ _save({"status": "signed_up", "email": email, "installId": iid, "at": _now()})+ return public_state()+++def skip() -> dict[str, Any]:+ state = load()+ _save({"status": "skipped", "installId": _install_id(state), "at": _now()})+ return public_state()+++def disconnect() -> dict[str, Any]:+ """Forget the email locally and ask the endpoint to drop it.++ The local copy goes even when the endpoint can't be reached: disconnecting+ must never fail on this machine. The card is not shown again.+ """+ state = load()+ iid = _install_id(state)+ email = state.get("email")+ if state.get("status") == "signed_up" and isinstance(email, str):+ # Anything the endpoint does must not keep the email on this machine.+ with contextlib.suppress(Exception):+ send("disconnect", email, iid)+ _save({"status": "skipped", "installId": iid, "at": _now()})+ return public_state()diff --git a/python/src/agentplay/builder.py b/python/src/agentplay/builder.pynew file mode 100644index 0000000..09ecd1a--- /dev/null+++ b/python/src/agentplay/builder.py@@ -0,0 +1,2820 @@+"""Session maps: a redacted, chronological replay of one coding-agent session.++A session map (schema ``agentplay/v1``) is what the Agentplay viewer+renders: every tool call, file touch, MCP call, skill, subagent+and LLM request of a session, in order, with repo-relative paths.++This module is **pure**: it reads local transcripts and returns a dict. It never+touches the network or the CLI's state files. Anything that goes wrong raises;+callers decide how soft to be.++Redaction contract (raw transcripts never leave the machine):++* no prompt / assistant text, no tool inputs or outputs, no file contents;+* shell commands contribute only their verb (``git log``, ``pytest``), never args;+* subagents contribute their type and model, never their prompt/description;+* file paths inside a git repo are repo-relative; paths outside any repo collapse+ to coarse buckets (``/tmp (scratch)``, ``~/Documents``, ``~/.claude/…``);+* ``path_mode`` = ``dirs_only`` drops file names, ``hashed`` HMACs every segment.++Claude Code is read directly from its JSONL (main transcript plus+``<session>/subagents/agent-*.jsonl``) because the shared span parser does not+emit subagent tool calls and only keeps per-turn token totals. Every other agent+goes through the shared ``LocalSource`` spans (``build_map_from_spans``).+"""++from __future__ import annotations++import configparser+import hashlib+import hmac+import json+import os+import re+from collections.abc import Iterable+from contextlib import suppress+from datetime import UTC, datetime+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit++from ._util import captured++SCHEMA = "agentplay/v1"+LEGACY_SCHEMA = "entelligence.session-map/v1" # accepted by readers; same document shape+SCHEMA_VERSION = 1+MAX_EVENTS = 20_000 # hard cap per map; beyond it the map is truncated and flagged+ROLE_READ_MAX_BYTES = 64 * 1024 * 1024+PATH_MODES = ("relative", "dirs_only", "hashed")++EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit", "apply_patch"}+SEARCH_TOOLS = {"Grep", "Glob", "LS", "view_image"}+SHELL_TOOLS = {"Bash", "exec_command", "shell", "local_shell", "run_terminal_cmd"}+SUBAGENT_TOOLS = {"Agent", "Task", "spawn_agent"}+WEB_TOOLS = {"WebFetch", "WebSearch", "web_search"}++_VERIFY_RE = re.compile(+ r"\b(pytest|go test|go vet|npm (?:run )?(?:test|build|lint)|pnpm (?:run )?(?:test|check|lint)"+ r"|yarn (?:test|build)|tsc\b|ruff|mypy|make (?:test|check)|cargo (?:test|clippy|check)"+ r"|vitest|jest|just test)"+)+_SEARCH_VERBS = {"grep", "rg", "find", "ls", "tree", "fd", "ag"}+_READ_VERBS = {"cat", "sed", "head", "tail", "less", "wc", "jq", "nl", "bat"}+_MULTI_VERBS = {+ "git",+ "gh",+ "aws",+ "npm",+ "pnpm",+ "yarn",+ "make",+ "cargo",+ "go",+ "uv",+ "just",+ "docker",+ "kubectl",+}+_ABS_PATH_RE = re.compile(r"(?<![\w.-])(/(?:[\w.@+-]+/)*[\w.@+-]+)")+_TOKEN_RE = re.compile(r"[A-Za-z0-9_./@+-]+")+# A bare commit sha (`git show <sha>`, a conflict marker) is never a file path.+_HEX_RE = re.compile(r"[0-9a-f]{7,}")+_CD_RE = re.compile(r"^\s*cd\s+(['\"]?)([^'\";&|]+)\1")+_GIT_C_RE = re.compile(r"\bgit\s+-C\s+(['\"]?)([^'\"\s;&|]+)\1")+_TOUCH_RANK = {"hit": 1, "read": 2, "edit": 3}+++# ---------------------------------------------------------------- helpers+def _parse_ts(value: Any) -> float | None:+ if not value or not isinstance(value, str):+ return None+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()+ except ValueError:+ return None+++def _iso(ts: float) -> str:+ return datetime.fromtimestamp(ts, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def estimate_cost_usd(+ model: str | None,+ fresh: int,+ cache_write: int,+ cache_read: int,+ output: int,+ *,+ single_request: bool = True,+) -> float | None:+ """Advisory per-request cost from the bundled rate card; ``None`` when unpriced.++ Standard multipliers when a card has no cache keys:+ read 0.1x input, write 1.25x input.++ Args:+ single_request: False when the token counts sum several requests (a+ turn aggregate). The long-context tier is a per-request property,+ so an aggregate is priced at base rates.+ """+ if not model:+ return None+ try:+ from agentplay._core.pricing import MODEL_RATES, normalize_model_key+ except Exception: # pragma: no cover - module always present in a build+ return None+ rates = MODEL_RATES.get(normalize_model_key(model))+ if not rates:+ return None+ inp, out = float(rates["input"]), float(rates["output"])+ cr = float(rates.get("cache_read", inp * 0.1))+ cw = float(rates.get("cache_write", inp * 1.25))+ # Per-request rule: a request+ # whose cache-inclusive input crosses the card's threshold is billed at the+ # long-context tier for the WHOLE request (gpt-6-astra, gpt-6-luna).+ threshold = rates.get("long_context_threshold")+ if single_request and threshold is not None and fresh + cache_write + cache_read > threshold:+ in_mult = float(rates["long_context_input_multiplier"])+ inp, cr, cw = inp * in_mult, cr * in_mult, cw * in_mult+ out *= float(rates["long_context_output_multiplier"])+ return round((fresh * inp + cache_write * cw + cache_read * cr + output * out) / 1e6, 6)+++def _cost_from_events(model: str | None, events: list[dict[str, Any]]) -> float | None:+ """Sum of per-request advisory costs from a turn's ``llm.cost_events``.++ ``None`` when any request is unpriced or malformed, so the caller falls+ back to the aggregate estimate instead of reporting a partial sum.+ """+ total = 0.0+ for e in events:+ if not isinstance(e, dict):+ return None+ cost = estimate_cost_usd(+ e.get("model") or model,+ int(e.get("input_tokens") or 0),+ int(e.get("cache_write_5m_tokens") or 0) + int(e.get("cache_write_1h_tokens") or 0),+ int(e.get("cache_read_tokens") or 0),+ int(e.get("output_tokens") or 0),+ )+ if cost is None:+ return None+ total += cost+ return round(total, 6)+++class RepoResolver:+ """Maps absolute paths to ``(repo_root, repo_name, remote_slug)`` without spawning git.++ Reads ``.git`` (directory or worktree pointer file) and the ``origin`` url+ from the git config directly; results are cached per directory.+ """++ def __init__(self) -> None:+ self._cache: dict[str, tuple[str, str, str] | None] = {}++ def resolve(self, path: str) -> tuple[str, str, str] | None:+ p = Path(path)+ d = p if p.is_dir() else p.parent+ seen: list[str] = []+ result: tuple[str, str, str] | None = None+ while True:+ key = str(d)+ if key in self._cache:+ result = self._cache[key]+ break+ seen.append(key)+ git = d / ".git"+ if git.exists():+ result = (key, *self._remote(d, git))+ break+ if d.parent == d:+ break+ d = d.parent+ for k in seen:+ self._cache[k] = result+ return result++ @staticmethod+ def _remote(root: Path, git: Path) -> tuple[str, str]:+ config_path = None+ try:+ if git.is_dir():+ config_path = git / "config"+ else: # worktree / submodule: "gitdir: <path>"+ text = git.read_text(encoding="utf-8", errors="replace").strip()+ if text.startswith("gitdir:"):+ gitdir = Path(text.split(":", 1)[1].strip())+ if not gitdir.is_absolute():+ gitdir = (root / gitdir).resolve()+ common = gitdir / "commondir"+ base = (+ (gitdir / common.read_text(encoding="utf-8", errors="replace").strip()).resolve()+ if common.exists()+ else gitdir+ )+ config_path = base / "config"+ url = ""+ if config_path and config_path.exists():+ cp = configparser.ConfigParser(strict=False, interpolation=None)+ cp.read(config_path, encoding="utf-8")+ url = cp.get('remote "origin"', "url", fallback="") or ""+ except Exception:+ url = ""+ url = url.strip()+ if _is_local_remote(url):+ # A clone of a local path: the url is the owner's filesystem layout (and+ # username), not a repository identity. Recorded with no remote.+ return root.name, ""+ if url:+ slug = re.sub(+ r"\.git$",+ "",+ re.sub(r"^.*?(?:github\.com|gitlab\.com|bitbucket\.org)[:/]", "", url),+ )+ slug = re.sub(r"^[a-z]+://[^/]+/", "", slug) # other hosts: drop scheme+host+ name = slug.rstrip("/").rsplit("/", 1)[-1] or root.name+ return name, slug+ return root.name, root.name+++def _is_local_remote(url: str) -> bool:+ """True for a remote url that is a filesystem path, not a hosted repository."""+ return url.startswith(("/", "~", ".", "\\", "file:")) or bool(re.match(r"[A-Za-z]:[\\/]", url))+++def _isabs(path: str) -> bool:+ """`os.path.isabs`, but a rooted path like `/tmp/x` counts on every OS.++ Transcripts recorded on macOS, Linux or WSL carry POSIX paths. Windows+ stopped treating those as absolute in Python 3.13 (it now wants a drive or+ UNC root), which sent them down the relative-path branches.+ """+ return os.path.isabs(path) or path.startswith(("/", "\\"))+++def _outside_bucket(path: str) -> str:+ home = str(Path.home())+ if (+ path.startswith("/tmp")+ or path.startswith("/private/tmp")+ or path.startswith("/var/folders")+ ):+ return "/tmp (scratch)"+ if "/.claude/" in path or path.endswith("/.claude"):+ m = re.search(r"/\.claude/(skills/[^/]+|projects|plans|agents|commands|memory)", path)+ return "~/.claude/" + (+ m.group(1).split("/")[0] + ("/" + m.group(1).split("/")[1] if "/" in m.group(1) else "")+ if m+ else "…"+ )+ for folder in ("Documents", "Downloads", "Desktop"):+ if path.startswith(f"{home}/{folder}"):+ return f"~/{folder}"+ if path.startswith(home):+ return "~ (home)"+ return "outside-repo"+++# Commands that only prepare the shell. When one leads a sequence the verb belongs to+# what follows, or `cd x && make test` is filed under `cd` and `export A=1; pytest`+# under `export` — and a long-running tail gets attributed to the setup that preceded it.+_PREFIX_VERBS = {"cd", "export", "set", "unset", "source", "pushd", "popd"}++# `&&`, `||`, `;` and a newline sequence commands; a pipe does not+# (`cat x | grep y` is a grep).+_SEQUENCE_RE = re.compile(r"&&|\|\||;|\n")++# `for i in ...; do CMD; done` and `if ...; then CMD; fi` — the verb is the body's,+# not the shell keyword. `do`/`then` may follow a `;` or a newline. Opener and body+# keyword are separate so the keyword can be required to sit outside quoting.+_BLOCK_FORMS = (+ (re.compile(r"^(?:for|while|until)\b", re.S), re.compile(r"[;\n]\s*do\s+", re.S)),+ (re.compile(r"^if\b", re.S), re.compile(r"[;\n]\s*then\s+", re.S)),+)++# `$(...)` and backticks run their own commands; their words are never this line's verb.+# `P=$(uv tool dir)/x; find .` must be a `find`, not a `tool`.+_SUBSTITUTION_RE = re.compile(r"\$\([^()]*\)|`[^`]*`")+++def _unquoted(line: str) -> list[bool]:+ """Per-character mask of where quoting is *not* in effect.++ A separator inside an argument is not a command boundary. Splitting on it+ hands the verb to a fragment of that argument, so ``cd "/private;token" &&+ pytest`` would be filed as ``token`` — a piece of a path written into the+ map, which the redaction contract forbids.++ Args:+ line: one shell command line.++ Returns:+ A list as long as ``line``: ``True`` for a character outside any+ quoting, ``False`` for a quote character, everything inside a matching+ pair, a backslash, and the character it escapes.+ """+ mask = [True] * len(line)+ quote = ""+ i = 0+ while i < len(line):+ ch = line[i]+ if quote:+ mask[i] = False+ if ch == "\\" and quote == '"' and i + 1 < len(line):+ mask[i + 1] = False+ i += 2+ continue+ if ch == quote:+ quote = ""+ elif ch in "'\"":+ quote = ch+ mask[i] = False+ elif ch == "\\" and i + 1 < len(line):+ mask[i] = mask[i + 1] = False+ i += 2+ continue+ i += 1+ return mask+++def _search_unquoted(pattern: re.Pattern[str], line: str) -> re.Match[str] | None:+ """First match of ``pattern`` in ``line`` lying wholly outside quoting, else None."""+ mask = _unquoted(line)+ for m in pattern.finditer(line):+ if all(mask[i] for i in range(m.start(), m.end())):+ return m+ return None+++def _block_body(line: str) -> str | None:+ """Body of a ``for``/``while``/``until ... do`` or ``if ... then`` line, else None."""+ for opener, keyword in _BLOCK_FORMS:+ if opener.match(line) is None:+ continue+ m = _search_unquoted(keyword, line)+ if m is not None:+ return line[m.end() :].strip()+ return None+++# A recorded verb is a command name, optionally with one subcommand word. Anything+# else is an argument fragment and is never written; it is filed under `sh` instead.+_VERB_SHAPE = re.compile(r"[A-Za-z0-9_.+-]{1,32}(?: [a-z][a-z0-9-]{0,24})?")+_ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=")+_SEQUENCE_SEPS = {";", "&&", "||", "\n"}+# Launcher options whose next word is the option's value, not the command.+_LAUNCHER_OPT_ARGS = {"-u", "-g", "-h", "-p", "-C", "-D", "-U", "-r", "-t", "-s", "-k"}+++class _Unbalanced(ValueError):+ """An open quote or substitution that never closes."""+++def _skip_quoted(line: str, i: int) -> int:+ """Index just past the quoted span or substitution that opens at ``line[i]``.++ Handles ``'...'``, ``$'...'``, ``"..."``, ``$(...)``, ``${...}`` and backticks,+ nested as the shell nests them. Raises ``_Unbalanced`` when one never closes.+ """+ n = len(line)+ if line.startswith("$'", i): # ANSI-C string: backslash escapes the next char+ j = i + 2+ while j < n and line[j] != "'":+ j += 2 if line[j] == "\\" else 1+ if j >= n:+ raise _Unbalanced+ return j + 1+ ch = line[i]+ if ch == "'":+ j = line.find("'", i + 1)+ if j < 0:+ raise _Unbalanced+ return j + 1+ if ch == "`":+ j = i + 1+ while j < n and line[j] != "`":+ j += 2 if line[j] == "\\" else 1+ if j >= n:+ raise _Unbalanced+ return j + 1+ if ch == '"':+ j = i + 1+ while j < n and line[j] != '"':+ if line[j] == "\\":+ j += 2+ elif line.startswith(("$(", "${"), j) or line[j] == "`":+ j = _skip_quoted(line, j)+ else:+ j += 1+ if j >= n:+ raise _Unbalanced+ return j + 1+ # `$(` or `${`: balanced up to the matching close, quotes inside respected.+ opener = line[i + 1]+ close = ")" if opener == "(" else "}"+ depth, j = 0, i + 1+ while j < n:+ c = line[j]+ if c == "\\":+ j += 2+ continue+ if c in "'\"`" or line.startswith(("$(", "${", "$'"), j):+ j = _skip_quoted(line, j)+ continue+ if c == opener:+ depth += 1+ elif c == close:+ depth -= 1+ if depth == 0:+ return j + 1+ j += 1+ raise _Unbalanced+++def _next_command(line: str, pos: int) -> tuple[list[tuple[str, str]], int, str]:+ """Words of the simple command starting at ``line[pos]``, honouring shell quoting.++ Returns ``(words, end, sep)``: each word as ``(raw, text)`` — ``raw`` exactly as+ written, ``text`` with quotes removed and every substitution replaced by ``$_``+ (its contents are never kept) — the index just past the separator that ended+ the command, and that separator (``""`` at end of line). A quote that never+ closes (a heredoc body, a truncated line) makes the rest one opaque word.+ """+ words: list[tuple[str, str]] = []+ raw: list[str] = []+ text: list[str] = []++ def flush() -> None:+ if raw:+ words.append(("".join(raw), "".join(text)))+ raw.clear()+ text.clear()++ n, i = len(line), pos+ while i < n:+ ch = line[i]+ if ch in " \t\r":+ flush()+ i += 1+ elif ch in ";|\n" or (+ ch == "&" and not (i and line[i - 1] in "<>") and not line.startswith("&>", i)+ ):+ flush()+ sep = line[i : i + 2] if line.startswith(("&&", "||"), i) else ch+ return words, i + len(sep), sep+ elif ch == "\\":+ raw.append(line[i : i + 2])+ text.append(line[i + 1 : i + 2])+ i += 2+ elif ch in "'\"`" or line.startswith(("$(", "${", "$'"), i):+ try:+ j = _skip_quoted(line, i)+ except _Unbalanced: # never closes: the rest of the line is one opaque word+ raw.append(line[i:])+ text.append("$_")+ break+ raw.append(line[i:j])+ if ch in "'\"" or line.startswith("$'", i):+ inner = line[i + 2 if ch == "$" else i + 1 : j - 1]+ text.append(_SUBSTITUTION_RE.sub("$_", inner) if ch == '"' else inner)+ else:+ text.append("$_")+ i = j+ else:+ raw.append(ch)+ text.append(ch)+ i += 1+ flush()+ return words, n, ""+++def _shell_verb(cmd: str) -> str:+ """First meaningful command word(s) of a shell line; never arguments or env values.++ The line is tokenized with shell quoting, so a quoted value — ``A="x y" cmd`` —+ is one word and is dropped whole with its assignment, never split into a+ fragment that could pose as the command. Whatever survives must still look+ like a command name (``_VERB_SHAPE``); anything else is filed as ``sh``.+ """+ line = cmd.strip()+ for _ in range(4): # innermost-out; bounded so nesting can't spin+ collapsed = _SUBSTITUTION_RE.sub("$_", line)+ if collapsed == line:+ break+ line = collapsed+ line = line.strip()+ try:+ # `for ...; do if ...; then CMD` nests, and a block may follow setup segments+ # (`A=1; for ...`). Both loops are bounded so a pathological line can't spin.+ pos = 0+ for _ in range(4):+ body = _block_body(line)+ if body is not None:+ line, pos = body, 0+ continue+ # Walk past `cd`/`export`/`A=1`... segments.+ pos = 0+ for _ in range(8):+ words, end, sep = _next_command(line, pos)+ names = [t for r, t in words if not _ASSIGN_RE.match(r)]+ if (+ sep in _SEQUENCE_SEPS+ and line[end:].strip()+ and (not names or os.path.basename(names[0].strip("()")) in _PREFIX_VERBS)+ ):+ pos = end+ continue+ break+ if pos == 0 or _block_body(line[pos:].strip()) is None:+ break+ line, pos = line[pos:].strip(), 0+ # Either loop can run out (deep nesting, many setup segments): tokenize the+ # command where the walk stopped rather than reuse a stale or unset `words`.+ words, _, _ = _next_command(line, pos)+ except (RecursionError, IndexError):+ return "sh"+ words = [t for r, t in words if not _ASSIGN_RE.match(r) and ("=" not in t or t.startswith("-"))]+ if not words or words[0].endswith("()") or words[1:2] == ["()"]:+ return "sh" # nothing to run, or a function definition: its name is the author's+ first = os.path.basename(words[0].strip("()")) or "sh"+ if first in {"sudo", "time", "timeout", "nohup", "env"} and len(words) > 1:+ rest: list[str] = []+ skip = False+ for w in words[1:]:+ if skip:+ skip = False+ elif w in _LAUNCHER_OPT_ARGS and first in {"sudo", "timeout"}:+ skip = True+ elif rest or not re.fullmatch(r"-?\d+[smh]?|-\w+", w):+ rest.append(w)+ if rest:+ words = rest+ first = os.path.basename(rest[0]) or first+ verb = first[:32]+ if first in _MULTI_VERBS and len(words) > 1:+ sub = next((w for w in words[1:] if not w.startswith("-") and "/" not in w), "")+ if sub and re.fullmatch(r"[a-z][a-z0-9-]{0,24}", sub):+ verb = f"{first} {sub}"+ return verb if _VERB_SHAPE.fullmatch(verb) else "sh"+++_QUOTED_RE = re.compile(r"'[^']*'|\"(?:\\.|[^\"\\])*\"")+_SEGMENT_RE = re.compile(r"&&|\|\||[;|&\n]")+_ENV_ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=\S*")+_LAUNCHER_ARG_RE = re.compile(r"-\S*|\d+(?:\.\d+)?[smhd]?")+_LAUNCHERS_1 = {"sudo", "nohup", "time", "timeout", "env", "command", "exec", "uvx", "npx", "bunx"}+_LAUNCHERS_2 = {+ ("uv", "run"),+ ("poetry", "run"),+ ("pipenv", "run"),+ ("hatch", "run"),+ ("pdm", "run"),+ ("pnpm", "exec"),+ ("pnpm", "dlx"),+ ("yarn", "dlx"),+}+_PYTHON_RE = re.compile(r"python(?:\d+(?:\.\d+)?)?")+++def _url_host(url: str) -> str:+ """Hostname only — never userinfo (credentials), port, path, query or fragment."""+ if not re.match(r"^https?://", url, re.I):+ return ""+ try:+ host = urlsplit(url).hostname or ""+ except ValueError:+ return ""+ return host[:80]+++def _is_verify(cmd: str) -> bool:+ """True when some command in the line *runs* a test/lint/build tool.++ Matches the command word (after launchers such as ``uv run`` / ``python -m`` /+ ``npx`` and env assignments) of each ``&&``/``;``/``|`` segment — never an+ argument, so ``echo pytest`` or ``git commit -m "pytest"`` stay ``exec``.+ """+ for seg in _SEGMENT_RE.split(_QUOTED_RE.sub(" ", cmd)):+ words = seg.split()+ while words:+ head = os.path.basename(words[0])+ if _ENV_ASSIGN_RE.fullmatch(words[0]):+ words = words[1:]+ elif head in _LAUNCHERS_1:+ words = words[1:]+ while words and _LAUNCHER_ARG_RE.fullmatch(words[0]):+ words = words[1:]+ elif len(words) > 1 and (head, words[1]) in _LAUNCHERS_2:+ words = words[2:]+ while words and words[0].startswith("-"):+ words = words[1:]+ elif len(words) > 1 and _PYTHON_RE.fullmatch(head) and words[1] == "-m":+ words = words[2:]+ else:+ break+ if words and _VERIFY_RE.match(" ".join([os.path.basename(words[0]), *words[1:]])):+ return True+ return False+++def _shell_paths(cmd: str, cwd: str | None) -> list[str]:+ base = cwd+ m = _CD_RE.match(cmd) or _GIT_C_RE.search(cmd)+ if m:+ base = os.path.expanduser(m.group(2).strip())+ out = [p for p in _ABS_PATH_RE.findall(cmd) if p.count("/") >= 2]+ if base and _isabs(base) and os.path.isdir(base):+ for tok in _TOKEN_RE.findall(cmd):+ if (+ tok.startswith(("/", "-"))+ or len(tok) < 3+ or _HEX_RE.fullmatch(tok)+ or ("/" not in tok and "." not in tok[1:])+ ):+ continue+ cand = os.path.normpath(os.path.join(base, tok))+ if cand != os.path.normpath(base) and os.path.exists(cand):+ out.append(cand)+ seen: set[str] = set()+ return [p for p in out if not (p in seen or seen.add(p))][:8]+++def classify(+ tool: str, inp: dict[str, Any], cwd: str | None+) -> tuple[str, list[str], str | None, str | None]:+ """``(kind, abs_paths, touch, verb)`` for one tool call."""++ def _abs(p: str) -> str:+ return p if _isabs(p) or not cwd else os.path.join(cwd, p)++ if tool == "Read":+ p = inp.get("file_path") or inp.get("path") or ""+ return "read", [_abs(p)] if p else [], "read", None+ if tool in EDIT_TOOLS:+ p = inp.get("file_path") or inp.get("notebook_path") or ""+ if tool == "apply_patch" and not p:+ patch = inp.get("input") or inp.get("patch") or ""+ paths = re.findall(r"^\*\*\* (?:Update|Add|Delete) File: (.+)$", str(patch), re.M)+ return "edit", [_abs(x.strip()) for x in paths][:8], "edit", None+ return "edit", [_abs(p)] if p else [], "edit", None+ if tool in SEARCH_TOOLS:+ p = inp.get("path") or ""+ return "search", [_abs(p)] if p else [], "hit", None+ if tool in SHELL_TOOLS:+ cmd = inp.get("command") or inp.get("cmd") or ""+ if isinstance(cmd, list):+ cmd = " ".join(str(c) for c in cmd)+ cmd = str(cmd)+ verb = _shell_verb(cmd)+ paths = _shell_paths(cmd, inp.get("workdir") or cwd)+ if _is_verify(cmd):+ return "verify", paths, "hit", verb+ head = verb.split()[0]+ if head in _READ_VERBS:+ return "read", paths, "read", verb+ if head in _SEARCH_VERBS or verb == "git grep":+ return "search", paths, "hit", verb+ return "exec", paths, "hit", verb+ if tool.startswith("mcp__") or (tool.startswith("mcp-") and tool.count("-") >= 2):+ return "mcp", [], None, None+ if tool == "Skill":+ return "skill", [], None, None+ if tool in SUBAGENT_TOOLS:+ return "subagent", [], None, None+ if tool in WEB_TOOLS:+ return "web", [], None, None+ return "tool", [], None, None+++# ---------------------------------------------------------------- error signals+# Closed vocabularies: only these class names (and an exit code) ever leave the+# machine; the error text itself is read locally to classify and then dropped.+_TOOL_ERROR_PATTERNS: tuple[tuple[str, tuple[str, ...]], ...] = (+ (+ "permission_denied",+ (+ "doesn't want to proceed",+ "user rejected",+ "Permission denied",+ "permission to use",+ "not allowed",+ ),+ ),+ ("blocked", ("<tool_use_error>Blocked", "blocked by", "Blocked:")),+ ("validation", ("InputValidationError", "invalid input", "Invalid tool parameters")),+ ("timeout", ("timed out", "Timeout", "timeout")),+ ("model_unavailable", ("temporarily unavailable", "model is unavailable")),+ ("rate_limit", ("rate limit", "Rate limit", " 429")),+ ("api_error", ("API Error",)),+ ("stale_file", ("has been modified since", "File has not been read yet")),+ ("not_found", ("not found", "No such file", "does not exist", "ENOENT")),+ ("interrupted", ("interrupted", "Interrupted")),+)+_EXIT_RE = re.compile(r"^\s*Exit code (\d+)")+_API_ERROR_FIELD = {+ "rate_limit": "rate_limit",+ "server_error": "server_error",+ "overloaded_error": "overloaded",+ "authentication_failed": "auth",+ "oauth_org_not_allowed": "auth",+ "permission_error": "auth",+ "invalid_request": "bad_request",+ "invalid_request_error": "bad_request",+}+ERROR_SOURCES = ("tool", "mcp", "llm", "hook", "orchestration")+TOOL_DELAY_MS = 30_000+LLM_DELAY_MS = 60_000+STALL_MS = 120_000+RETRY_WINDOW = 8+++def _flat_text(content: Any, limit: int = 600) -> str:+ """Local-only text used to classify an error; never stored in the map."""+ if isinstance(content, str):+ return content[:limit]+ if isinstance(content, list):+ parts = [x.get("text", "") for x in content if isinstance(x, dict)]+ return " ".join(p for p in parts if isinstance(p, str))[:limit]+ return str(content or "")[:limit]+++def classify_tool_error(text: str) -> tuple[str, int | None]:+ m = _EXIT_RE.match(text)+ if m:+ return "exit_code", int(m.group(1))+ for cls, pats in _TOOL_ERROR_PATTERNS:+ if any(p in text for p in pats):+ return cls, None+ return "other", None+++def classify_api_error(field: Any, text: str) -> str:+ if isinstance(field, str) and field in _API_ERROR_FIELD:+ return _API_ERROR_FIELD[field]+ low = text.lower()+ if "spend limit" in low:+ return "spend_limit"+ if "limit" in low and ("hit your" in low or "reached your" in low):+ return "usage_limit"+ if "overloaded" in low or " 529" in low:+ return "overloaded"+ if "api error: 400" in low:+ return "bad_request"+ if "rate limit" in low or " 429" in low:+ return "rate_limit"+ if "api error: 5" in low:+ return "server_error"+ return "api_error"+++_NON_CALL_KINDS = frozenset(+ {+ "llm",+ "user",+ "compaction",+ "error",+ "delay",+ "model_switch",+ *("commit", "pr_merge", "pr_close", "pr_comment", "ticket", "artifact", "skill_write"),+ }+)++# ---------------------------------------------------------------- tool categories, VCS, file ops, PRs+_PKG = {+ "pip",+ "pip3",+ "npm",+ "pnpm",+ "yarn",+ "uv",+ "poetry",+ "brew",+ "apt",+ "apt-get",+ "gem",+ "bundle",+}+_BUILD = {"make", "tsc", "webpack", "vite", "gradle", "mvn", "bazel", "just"}+_CLOUD = {+ "aws",+ "gcloud",+ "az",+ "kubectl",+ "terraform",+ "docker",+ "helm",+ "sam",+ "eb",+ "flyctl",+ "vercel",+}+_HTTP = {"curl", "wget", "http", "httpie", "xh"}+_FS = {"rm", "mv", "cp", "mkdir", "touch", "chmod", "ln", "rmdir", "tee", "rsync", "unzip", "tar"}+_VCS_CLI = {"git": "git", "gh": "github", "hub": "github", "glab": "gitlab", "bb": "bitbucket"}+_PR_URL = re.compile(+ r"https?://(?:github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pull/(\d+)"+ r"|[A-Za-z0-9.-]*gitlab[A-Za-z0-9.-]*/((?:[A-Za-z0-9_.-]+/)+[A-Za-z0-9_.-]+)/-/merge_requests/(\d+)"+ r"|bitbucket\.org/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pull-requests/(\d+))"+)+++def _cmd_words(cmd: str) -> list[str]:+ line = cmd.strip()+ if line.startswith("cd ") and "&&" in line:+ line = line.split("&&", 1)[1].strip()+ return [w.strip("'\"") for w in line.split() if "=" not in w or w.startswith("-")]+++def tool_category(ev: dict[str, Any]) -> str:+ """Closed vocabulary for the tool-call breakdown; never args."""+ kind = ev["kind"]+ if kind == "mcp":+ srv = str(ev.get("server") or "").lower()+ return "vcs" if any(h in srv for h in ("github", "gitlab", "bitbucket")) else "mcp"+ if kind in ("skill", "subagent", "web", "tool"):+ return kind+ verb = str(ev.get("verb") or "")+ if not verb:+ return "file"+ head = verb.split()[0]+ if head in _VCS_CLI:+ return "vcs"+ if kind == "verify":+ return "test"+ if head in _READ_VERBS or head in _SEARCH_VERBS:+ return "file"+ if head in _FS:+ return "fs"+ if head in _PKG and any(+ w in verb for w in ("install", "add", "ci", "sync", "update", "remove")+ ):+ return "package"+ if head in _BUILD or verb in ("cargo build", "go build", "npm run", "pnpm run", "yarn build"):+ return "build"+ if head in _CLOUD:+ return "cloud"+ if head in _HTTP:+ return "http"+ return "shell"+++def vcs_action(tool: str, inp: dict[str, Any], server: str | None) -> dict[str, Any] | None:+ """``{provider, action[, number]}`` for git/gh/glab/bb commands and VCS MCP tools. Never args."""+ if server is not None:+ srv = server.lower()+ prov = next((p for p in ("github", "gitlab", "bitbucket") if p in srv), None)+ if prov:+ return {"provider": prov, "action": tool[:48]}+ return None+ cmd = inp.get("command") or inp.get("cmd") or ""+ if isinstance(cmd, list):+ cmd = " ".join(str(c) for c in cmd)+ words = _cmd_words(str(cmd))+ if not words:+ return None+ head = os.path.basename(words[0])+ prov = _VCS_CLI.get(head)+ if not prov:+ return None+ rest = [w for w in words[1:] if not w.startswith("-")]+ if head == "git":+ if words[1:2] == ["-C"]:+ rest = [w for w in words[3:] if not w.startswith("-")]+ sub = rest[0] if rest else ""+ return {+ "provider": "git",+ "action": sub if re.fullmatch(r"[a-z-]{2,20}", sub or "") else "git",+ }+ noun = rest[0] if rest else ""+ verb = rest[1] if len(rest) > 1 else ""+ action = f"{noun}_{verb}".strip("_") if re.fullmatch(r"[a-z-]{0,20}", noun + verb) else noun+ if noun in ("pr", "mr") and verb == "create":+ # A command shape, not an outcome: tool_event may overwrite this with the+ # resolved "pr_create" action once (and only once) a real PR/MR URL is seen+ # in the result. Kept distinct from that sentinel so an unresolved command+ # never reads as a confirmed PR (see pr_create_intent's shape fallback).+ return {"provider": prov, "action": "pr_create_cmd"}+ out: dict[str, Any] = {"provider": prov, "action": action[:40] or head}+ # Only the token immediately after the noun/verb (`gh pr view 123`): scanning the+ # whole tail picks up stray digits from free-text titles/bodies.+ num = rest[2] if len(rest) > 2 and rest[2].isdigit() and len(rest[2]) <= 8 else None+ if noun in ("pr", "mr") and num:+ out["number"] = int(num)+ return out+++def _pr_from_url(text: str) -> dict[str, Any] | None:+ m = _PR_URL.search(text or "")+ if not m:+ return None+ if m.group(1):+ return {+ "provider": "github",+ "repo": m.group(1),+ "number": int(m.group(2)),+ "url": m.group(0),+ }+ if m.group(3):+ return {+ "provider": "gitlab",+ "repo": m.group(3),+ "number": int(m.group(4)),+ "url": m.group(0),+ }+ return {+ "provider": "bitbucket",+ "repo": m.group(5),+ "number": int(m.group(6)),+ "url": m.group(0),+ }+++def pr_create_intent(tool: str, inp: dict[str, Any]) -> dict[str, Any] | None:+ """PR/MR creation intent via the bundled detectors (gh/glab/GitHub API/MCP) + Bitbucket."""+ try:+ from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ )++ value = inp if tool.startswith("mcp__") else (inp.get("command") or inp.get("cmd") or "")+ attrs = creation_command_attributes(+ json.dumps(value) if isinstance(value, dict) else value, tool+ )+ except Exception: # noqa: BLE001 — detection is best-effort+ attrs = {}+ if attrs.get("pr.create.provider"):+ return {+ "provider": attrs["pr.create.provider"],+ "repo": attrs.get("pr.create.repository")+ or attrs.get("pr.create.requested_repository"),+ }+ cmd = str(inp.get("command") or "")+ if tool in SHELL_TOOLS:+ # Tier 2: the bundled detector marks a long, free-text-bearing command (a+ # real PR title/body) as "unrecognized_creation_text" rather than confirming+ # a provider — a cheap shape check on the first tokens still tells us this IS+ # a create call, so it still gets resolved by URL below.+ words = _cmd_words(cmd)+ head = os.path.basename(words[0]) if words else ""+ rest = [w for w in words[1:] if not w.startswith("-")]+ if head in ("gh", "hub") and rest[:2] == ["pr", "create"]:+ return {"provider": "github", "repo": None}+ if head == "glab" and rest[:2] == ["mr", "create"]:+ return {"provider": "gitlab", "repo": None}+ low = (tool + " " + cmd).lower()+ if re.search(r"\b(?:bb|bitbucket)\b.*\bpr\b.*\bcreate\b", low) or (+ "bitbucket" in low and "pull" in low and "create" in low+ ):+ return {"provider": "bitbucket", "repo": None}+ return None+++def file_ops(tool: str, inp: dict[str, Any], cwd: str | None) -> dict[str, str]:+ """abs path -> create | modify | delete | rename-from | rename-to for file-changing calls."""++ def _abs(p: str) -> str:+ return os.path.normpath(p if _isabs(p) or not cwd else os.path.join(cwd, p))++ ops: dict[str, str] = {}+ if tool == "apply_patch":+ patch = str(inp.get("input") or inp.get("patch") or "")+ for kind, path in re.findall(r"^\*\*\* (Add|Delete|Update) File: (.+)$", patch, re.M):+ ops[_abs(path.strip())] = {"Add": "create", "Delete": "delete", "Update": "modify"}[+ kind+ ]+ for path in re.findall(r"^\*\*\* Move to: (.+)$", patch, re.M):+ ops[_abs(path.strip())] = "rename-to"+ return ops+ if tool in SHELL_TOOLS:+ cmd = inp.get("command") or inp.get("cmd") or ""+ if isinstance(cmd, list):+ cmd = " ".join(str(c) for c in cmd)+ base = inp.get("workdir") or cwd+ m = _CD_RE.match(str(cmd))+ if m:+ base = os.path.expanduser(m.group(2).strip())+ for seg in re.split(r"&&|;|\|\||\n", str(cmd)):+ w = _cmd_words(seg)+ if not w:+ continue+ h = os.path.basename(w[0])+ args = [a for a in w[1:] if not a.startswith("-")]+ if h == "git" and args[:1] in (["rm"], ["mv"]):+ h, args = args[0], args[1:]+ ab = [+ os.path.normpath(a if _isabs(a) or not base else os.path.join(base, a))+ for a in args+ ]+ if h in ("rm", "rmdir", "unlink"):+ for a in ab:+ ops[a] = "delete"+ elif h == "mv" and len(ab) >= 2:+ for a in ab[:-1]:+ ops[a] = "rename-from"+ ops[ab[-1]] = "rename-to"+ elif h == "cp" and len(ab) >= 2:+ ops[ab[-1]] = "create"+ elif h == "touch":+ for a in ab:+ ops.setdefault(a, "create")+ # Path-safe characters only: a permissive class also matches Python f-string+ # alignment specs (`{x:>7.0f}`) as a false "redirect target"; this excludes+ # {}, (), quotes, $ outright. `:` is excluded from the lookbehind too, since+ # a real shell redirect is never preceded by one, but an f-string spec always is.+ # Nor by another `>`: a merge-conflict marker (`>>>>>>> <sha>`) in a heredoc+ # is not a write.+ for red in re.findall(r"(?<![0-9&:>])>{1,2}\s*([\w./@+-]+)", seg):+ # Excludes bare numbers, incl. decimals/durations: `[ "$rc" > 1 ]`, and+ # `echo "$val > $threshold" | bc -l` (a common bash float-comparison+ # idiom) are numeric comparisons, not redirects — a real redirect+ # target is never a bare number in practice, so this is a safe, cheap+ # guard against exactly that ambiguity (regex alone can't tell `>`+ # apart from a comparison operator).+ if (+ red in ("/dev/null", "&1", "&2")+ or re.fullmatch(r"[\d.]+(s|ms|h|m|x|%)?", red)+ ):+ continue+ ops.setdefault(+ _abs(red if _isabs(red) or not base else os.path.join(base, red)),+ "modify" if ">>" in seg else "create",+ )+ return ops+++# ---------------------------------------------------------------- outputs+# Every output is confirmed-only: the call's *input* says what was attempted+# (an "intent"), and an output event is emitted only when the call's *result*+# carries positive evidence it happened (git's own "[branch sha]" line, gh's+# "Merged pull request", a ticket identifier, an artifact URL). Tool status alone+# is not enough — Codex reports status OK for calls that failed ("is not+# mergeable", "Error: Could not find team"). Result text is read locally and+# dropped; only closed-vocabulary fields, ids, counts and repo names are stored.+OUTPUT_KINDS = (+ "commit",+ "pr_merge",+ "pr_close",+ "pr_comment",+ "ticket",+ "artifact",+ "skill_write",+)+_COMMIT_OK = re.compile(r"\[([^\]\n]{1,120}?) ([0-9a-f]{7,40})\]")+_COMMIT_STAT = re.compile(+ r"(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?"+)+_MERGE_OK = re.compile(+ r"(?:squashed and merged|rebased and merged|\bmerged) pull request"+ r"|merge request !?\d+ (?:was |has been )?merged"+ r'|"merged"\s*:\s*true|successfully merged',+ re.I,+)+_CLOSE_OK = re.compile(r"\bclosed pull request|merge request !?\d+ (?:was )?closed", re.I)+_REVIEW_OK = re.compile(+ r"(?:approved|reviewed|requested changes (?:to|for)) pull request"+ r"|#issuecomment-\d+|#pullrequestreview-\d+|#discussion_r\d+",+ re.I,+)+# gh/glab print their success line only to a TTY: a non-interactive `gh pr merge` that+# worked prints nothing (or just the local fast-forward). So a CLI PR action is+# confirmed by a clean exit with nothing in the output saying it was refused.+_PR_REFUSED = re.compile(+ r"not mergeable|already (?:merged|closed)|is (?:still )?a draft|cannot be merged"+ r"|merge conflict|no pull requests? found|could not resolve|graphql:|http 4\d\d"+ r"|(?m:^\W*(?:x\s|error\b|failed\b))",+ re.I,+)+# gh merges on GitHub first, then switches/deletes the local branch; that local step+# failing (exit 1) happens *after* the merge.+_PR_LOCAL_AFTERMATH = re.compile(+ r"failed to run git: fatal: '[^']+' is already used by worktree|failed to delete local branch",+ re.I,+)+_TICKET_ID = re.compile(r"\b([A-Z][A-Z0-9]{1,9}-\d{1,7})\b")+_GH_ISSUE_URL = re.compile(r"github\.com/[\w.-]+/[\w.-]+/issues/(\d+)")+_ARTIFACT_OK = re.compile(r"claude\.ai/(?:code/)?artifact/[A-Za-z0-9-]+")+_ARTIFACT_VERSION = re.compile(r"\(Version (\d+)\)")+_PR_REF = re.compile(r"([\w.-]+/[\w.-]+)#(\d+)|pull request #(\d+)|/pull/(\d+)", re.I)+_SKILL_FILE = re.compile(r"(?:^|/)skills/([^/]{1,80})/SKILL\.md$")+_FAILED_TEXT = re.compile(+ r"^\W*(?:error\b|x\b|failed\b|fatal:|gh: |graphql: )|is not mergeable|could not|"+ r"not found|permission denied|unauthorized|forbidden|\"isError\"\s*:\s*true",+ re.I,+)+_LINEAR_LEAVES = {+ "save_issue",+ "create_issue",+ "update_issue",+ "save_comment",+ "create_comment",+ "linear_create_issue",+ "linear_update_issue",+ "linear_create_comment",+}+_JIRA_LEAVES = {+ "createjiraissue",+ "editjiraissue",+ "addcommenttojiraissue",+ "transitionjiraissue",+ "jira_create_issue",+ "jira_update_issue",+ "jira_add_comment",+ "jira_transition_issue",+}+_GH_PR_COMMENT_LEAVES = {+ "add_issue_comment",+ "add_pull_request_review_comment",+ "add_pull_request_review_comment_to_pending_review",+ "add_comment_to_pending_review",+ "create_pull_request_review",+ "create_and_submit_pull_request_review",+ "submit_pending_pull_request_review",+ "pull_request_review_write",+}+++def unwrap_command(cmd: str) -> tuple[str, str | None]:+ """``(command, workdir)`` with Codex code-mode unwrapped.++ Codex's code mode wraps shell calls in JS — ``const r = await+ tools.exec_command({"cmd": "gh pr merge 1 …", "workdir": "…"}); …`` — so the+ raw input is not the command. Returns the input unchanged when it isn't one.+ """+ i = cmd.find("exec_command(")+ j = cmd.find("{", i) if i >= 0 else -1+ if j < 0:+ return cmd, None+ try:+ d, _ = json.JSONDecoder().raw_decode(cmd[j:])+ except ValueError:+ # A JS object literal with bare keys (`{cmd:"…", workdir:"…"}`) is not JSON.+ inner = _js_string_field(cmd[j:], ("cmd", "command"))+ return (inner, _js_string_field(cmd[j:], ("workdir",))) if inner else (cmd, None)+ if not isinstance(d, dict):+ return cmd, None+ inner = d.get("cmd") or d.get("command")+ if isinstance(inner, list):+ inner = " ".join(str(x) for x in inner)+ if not isinstance(inner, str) or not inner.strip():+ return cmd, None+ wd = d.get("workdir")+ return inner, wd if isinstance(wd, str) else None+++def _js_string_field(src: str, keys: tuple[str, ...]) -> str | None:+ """A double-quoted string value for one of ``keys`` in a JS/JSON object; tolerates a+ truncated value (Cursor clips long inputs) by taking what is there."""+ for key in keys:+ m = re.search(r'["\']?\b' + key + r'["\']?\s*:\s*"((?:\\.|[^"\\])*)("?)', src)+ if not m:+ continue+ try:+ return json.loads('"' + m.group(1) + '"')+ except ValueError:+ return m.group(1).replace('\\"', '"')+ return None+++def loose_command(raw: str) -> str:+ """The shell command from a tool input that is not valid JSON (truncated JSON, or a+ Codex code-mode snippet); falls back to the raw text."""+ if raw.lstrip().startswith("{"):+ found = _js_string_field(raw, ("command", "cmd"))+ if found:+ return found+ return raw+++def _segments_words(cmd: str) -> list[list[str]]:+ out = []+ for seg in re.split(r"&&|\|\||;|\n", cmd):+ w = _cmd_words(seg)+ if w:+ out.append(w)+ return out+++def _gh_number(args: list[str]) -> int | None:+ for a in args:+ m = re.fullmatch(r"#?(\d{1,8})", a) or re.search(r"/pull/(\d{1,8})", a)+ if m:+ return int(m.group(1))+ return None+++def _gh_repo_arg(words: list[str]) -> str | None:+ for i, w in enumerate(words):+ if w in ("--repo", "-R") and i + 1 < len(words):+ v = words[i + 1].strip("'\"")+ if re.fullmatch(r"[\w.-]+/[\w.-]+", v):+ return v+ if w.startswith("--repo="):+ v = w.split("=", 1)[1].strip("'\"")+ if re.fullmatch(r"[\w.-]+/[\w.-]+", v):+ return v+ return None+++_BARE_MCP_LEAVES = (+ _LINEAR_LEAVES+ | _JIRA_LEAVES+ | _GH_PR_COMMENT_LEAVES+ | {"merge_pull_request", "update_pull_request"}+)+++def output_intents(+ tool: str, inp: dict[str, Any], server: str | None, leaf: str | None+) -> list[dict[str, Any]]:+ """What a call *attempts* to produce (commit, PR merge/close/comment, ticket, …).++ Never an outcome: :meth:`MapBuilder.resolve_outputs` confirms each intent+ against the call's result before any output event exists.+ """+ intents: list[dict[str, Any]] = []+ if tool in SHELL_TOOLS:+ cmd = inp.get("command") or inp.get("cmd") or ""+ if isinstance(cmd, list):+ cmd = " ".join(str(c) for c in cmd)+ for words in _segments_words(str(cmd)):+ head = os.path.basename(words[0])+ args = [w for w in words[1:] if not w.startswith("-")]+ if head == "git":+ sub = [w for w in words[1:] if not w.startswith("-")]+ if words[1:2] == ["-C"]:+ sub = [w for w in words[3:] if not w.startswith("-")]+ if sub[:1] == ["commit"]:+ intents.append({"type": "commit"})+ elif head in ("gh", "hub", "glab") and len(args) >= 2:+ noun, verb = args[0], args[1]+ repo = _gh_repo_arg(words)+ num = _gh_number(args[2:3])+ if noun in ("pr", "mr") and verb == "merge":+ intents.append(+ {+ "type": "pr_merge",+ "repo": repo,+ "number": num,+ "cli": True,+ "auto": "--auto" in words,+ }+ )+ elif noun in ("pr", "mr") and verb == "close":+ intents.append({"type": "pr_close", "repo": repo, "number": num, "cli": True})+ elif noun in ("pr", "mr") and verb in ("comment", "review", "note"):+ intents.append({"type": "pr_comment", "repo": repo, "number": num, "cli": True})+ elif noun == "issue" and verb in ("create", "edit", "comment", "close"):+ intents.append(+ {+ "type": "ticket",+ "tracker": "github",+ "action": "create" if verb == "create" else "update",+ "id": f"#{num}" if num else None,+ "tool": f"{head} issue {verb}",+ }+ )+ return intents+ if server is not None or leaf is not None:+ srv = (server or "").lower()+ name = (leaf or tool).lower()+ if "github" in srv or (not srv and (name == "merge_pull_request" or _mcp_repo(inp))):+ if name == "merge_pull_request":+ intents.append(+ {+ "type": "pr_merge",+ "repo": _mcp_repo(inp),+ "number": _int_or_none(inp.get("pullNumber") or inp.get("pull_number")),+ }+ )+ elif name == "update_pull_request" and str(inp.get("state") or "") == "closed":+ intents.append(+ {+ "type": "pr_close",+ "repo": _mcp_repo(inp),+ "number": _int_or_none(inp.get("pullNumber") or inp.get("pull_number")),+ }+ )+ elif name in _GH_PR_COMMENT_LEAVES:+ intents.append(+ {+ "type": "pr_comment",+ "repo": _mcp_repo(inp),+ "number": _int_or_none(+ inp.get("pullNumber")+ or inp.get("pull_number")+ or inp.get("issue_number")+ ),+ }+ )+ elif name in ("create_issue", "update_issue"):+ intents.append(+ {+ "type": "ticket",+ "tracker": "github",+ "action": "create" if name == "create_issue" else "update",+ "id": None,+ "tool": name[:60],+ }+ )+ return intents+ tracker = None+ if "linear" in srv or name.startswith("linear") or (not srv and name in _LINEAR_LEAVES):+ tracker = "linear"+ elif "jira" in srv or "atlassian" in srv or "jira" in name:+ tracker = "jira"+ if tracker and (name in _LINEAR_LEAVES or name in _JIRA_LEAVES or "issue" in name):+ if any(k in name for k in ("get", "list", "search", "fetch", "read")):+ return intents+ has_id = any(inp.get(k) for k in ("id", "issueId", "issue_id", "issueIdOrKey"))+ create = ("create" in name and "comment" not in name) or (+ name == "save_issue" and not has_id+ )+ ref = next(+ (+ str(inp.get(k))+ for k in ("id", "issueId", "issue_id", "issueIdOrKey")+ if isinstance(inp.get(k), str) and _TICKET_ID.fullmatch(str(inp.get(k)))+ ),+ None,+ )+ intents.append(+ {+ "type": "ticket",+ "tracker": tracker,+ "action": "create" if create else "update",+ "id": ref,+ "tool": name[:60],+ }+ )+ return intents+ if tool == "Artifact":+ action = str(inp.get("action") or "publish")+ if action == "publish" and not inp.get("asset"):+ fp = inp.get("file_path")+ size = None+ if isinstance(fp, str) and fp:+ with suppress(OSError):+ size = os.path.getsize(fp)+ intents.append({"type": "artifact", "bytes": size, "tool": "Artifact"})+ return intents+++def _mcp_repo(inp: dict[str, Any]) -> str | None:+ owner, repo = inp.get("owner"), inp.get("repo")+ if isinstance(owner, str) and isinstance(repo, str) and owner and repo:+ return f"{owner}/{repo}"[:120]+ return None+++def _int_or_none(v: Any) -> int | None:+ try:+ return int(v)+ except (TypeError, ValueError):+ return None+++def _result_core(text: str) -> str:+ """Drop harness framing (Codex: ``Script completed Wall time … Output:``)."""+ i = text.find("Output:")+ return text[i + len("Output:") :] if 0 <= i < 120 else text+++def confirm_output(+ intent: dict[str, Any], text: str, err: bool, *, repo_name: str | None = None+) -> dict[str, Any] | None:+ """The output event fields for a confirmed intent, else ``None`` (never a guess)."""+ core = _result_core(text or "")+ # The one error that follows a real merge: gh's *local* branch cleanup.+ after_merge = (+ intent["type"] == "pr_merge"+ and intent.get("cli")+ and _PR_LOCAL_AFTERMATH.search(core)+ and not _PR_REFUSED.search(_PR_LOCAL_AFTERMATH.sub("", core))+ )+ if err and not after_merge:+ return None+ failed = bool(_FAILED_TEXT.search(core[:400]))+ typ = intent["type"]+ if typ == "commit":+ m = _COMMIT_OK.search(core)+ if not m:+ return None+ out: dict[str, Any] = {"kind": "commit", "sha": m.group(2)[:12]}+ if repo_name:+ out["repo"] = repo_name+ st = _COMMIT_STAT.search(core, m.end())+ if st:+ out["files"] = int(st.group(1))+ out["ins"] = int(st.group(2) or 0)+ out["del"] = int(st.group(3) or 0)+ return out+ if typ in ("pr_merge", "pr_close", "pr_comment"):+ ok = {"pr_merge": _MERGE_OK, "pr_close": _CLOSE_OK, "pr_comment": _REVIEW_OK}[typ]+ if intent.get("auto"):+ return None # `--auto` only queues the merge for when checks pass+ confirmed = bool(ok.search(core)) or (+ typ == "pr_comment" and not failed and "html_url" in core+ )+ if not confirmed and intent.get("cli"):+ confirmed = not _PR_REFUSED.search(_PR_LOCAL_AFTERMATH.sub("", core))+ if not confirmed:+ return None+ out = {"kind": typ}+ repo, num = intent.get("repo"), intent.get("number")+ m = _PR_REF.search(core)+ if m:+ repo = repo or m.group(1)+ num = num or _int_or_none(m.group(2) or m.group(3) or m.group(4))+ if repo:+ out["repo"] = str(repo)[:120]+ if num:+ out["number"] = num+ return out+ if typ == "ticket":+ if failed:+ return None+ tid = intent.get("id")+ if intent.get("tracker") == "github":+ m = _GH_ISSUE_URL.search(core)+ tid = tid or (f"#{m.group(1)}" if m else None)+ else:+ m = _TICKET_ID.search(core)+ tid = tid or (m.group(1) if m else None)+ if intent.get("action") == "create" and not tid:+ return None # a create with no identifier in its result never demonstrably happened+ if not tid and not core.strip():+ return None+ out = {+ "kind": "ticket",+ "tracker": intent["tracker"],+ "action": intent["action"],+ "tool": intent.get("tool"),+ }+ if tid:+ out["id"] = tid+ return out+ if typ == "artifact":+ if failed or not _ARTIFACT_OK.search(core):+ return None+ out = {"kind": "artifact", "tool": intent.get("tool") or "Artifact"}+ if intent.get("bytes") is not None:+ out["bytes"] = int(intent["bytes"])+ v = _ARTIFACT_VERSION.search(core)+ if v:+ out["version"] = int(v.group(1))+ return out+ return None+++OUTCOME_KIND = (+ "pr_created",+ "verified",+ "blocked",+ "interrupted",+ "unresolved_errors",+ "completed",+ "incomplete",+)+++def classify_outcome(events: list[dict[str, Any]], last_text: str) -> str:+ """A single closed-vocabulary label for how a session/agent ended.++ Reads local signals only (error/verify/PR events, and the *length* of the+ final assistant reply as a tie-breaker heuristic — never its content) and+ returns one of ``OUTCOME_KIND``. Priority: an actual PR/MR created beats+ everything; then whether the run ends mid-work vs cleanly.+ """+ if not events:+ return "incomplete"+ if any((e.get("vcs") or {}).get("action") == "pr_create" for e in events):+ return "pr_created"+ tail = events[-12:]+ if any(e.get("kind") == "error" and e.get("errClass") == "interrupted" for e in tail):+ return "interrupted"+ if any(e.get("errClass") in ("blocked", "permission_denied") for e in tail if e.get("err")):+ return "blocked"+ verifies = [e for e in events if e.get("kind") == "verify"]+ if verifies and not verifies[-1].get("err"):+ # `seq` is the event's position in the whole session, and `events` may be one+ # agent's slice of it, so compare seqs rather than slicing by one.+ last_verify = verifies[-1]["seq"]+ if not any(e.get("kind") == "edit" and e["seq"] > last_verify for e in events):+ return "verified"+ trailing_errors = sum(1 for e in tail if e.get("err") and e.get("kind") != "error") or sum(+ 1 for e in tail if e.get("kind") == "error"+ )+ if trailing_errors >= 2:+ return "unresolved_errors"+ last = events[-1]+ if last.get("kind") in ("edit", "exec") and not last_text.strip():+ return "incomplete"+ return "completed"+++def _error_source(e: dict[str, Any]) -> str:+ if e["kind"] == "error":+ return str(e.get("source") or "tool")+ if e["kind"] == "mcp":+ return "mcp"+ if e["kind"] == "subagent":+ return "orchestration"+ return "tool"+++def _signal_totals(evs: list[dict[str, Any]]) -> dict[str, Any]:+ by_src: dict[str, int] = {}+ by_cls: dict[str, int] = {}+ for e in evs:+ if not e.get("err"):+ continue+ src = _error_source(e)+ by_src[src] = by_src.get(src, 0) + 1+ cls = str(e.get("errClass") or "other")+ by_cls[cls] = by_cls.get(cls, 0) + 1+ llm = [e for e in evs if e["kind"] == "llm"]+ lats = sorted(int(e["latency"]) for e in llm if e.get("latency"))+ ctx = [e["in"] + e["cw"] + e["cr"] for e in llm if e["agent"] == "main"]+ delays = [e for e in evs if e["kind"] == "delay"]+ return {+ "errorsBySource": by_src,+ "errorsByClass": by_cls,+ "retries": sum(1 for e in evs if e.get("retryOf") is not None),+ "delays": len(delays),+ "delayMs": sum(int(e.get("ms") or 0) for e in delays),+ "maxContext": max(ctx, default=0),+ "compactions": sum(1 for e in evs if e["kind"] == "compaction"),+ "llmLatencyP50": lats[len(lats) // 2] if lats else 0,+ "llmLatencyP95": lats[min(len(lats) - 1, int(len(lats) * 0.95))] if lats else 0,+ "outputTokens": sum(e["out"] for e in llm),+ }+++# ---------------------------------------------------------------- builder+class MapBuilder:+ """Accumulates events for one session (main agent plus subagents) and emits the map."""++ def __init__(+ self,+ *,+ path_mode: str = "relative",+ hmac_key: bytes | None = None,+ resolver: RepoResolver | None = None,+ ) -> None:+ if path_mode not in PATH_MODES:+ path_mode = "relative"+ if path_mode == "hashed" and not hmac_key:+ path_mode = "dirs_only" # never emit plain names when a hash was asked for+ self.path_mode = path_mode+ self.hmac_key = hmac_key or b""+ self.resolver = resolver or RepoResolver()+ self.repos: dict[str, dict[str, Any]] = {}+ self.files: dict[str, dict[str, Any]] = {}+ self.events: list[dict[str, Any]] = []+ self.agents: list[dict[str, Any]] = [{"id": "main", "parent": None, "kind": "main"}]+ self.t0: float | None = None+ self.truncated = False+ self._touched_keys: set[str] = set()+ self.prs_created: list[dict[str, Any]] = []+ self.last_agent_text: dict[str, str] = {}+ # Model used when a harness reports none per request (Cursor: "default"),+ # and the CLI's own task segmentation for this session, when it has any.+ self.default_model: str = ""+ self.task_specs: list[dict[str, Any]] | None = None++ # -- paths+ def _seg(self, s: str) -> str:+ return hmac.new(self.hmac_key, s.encode(), hashlib.sha256).hexdigest()[:10]++ def _redact_rel(self, rel: str) -> str:+ if self.path_mode == "relative":+ return rel+ parts = rel.split("/")+ if self.path_mode == "dirs_only":+ return "/".join(parts[:-1] + ["•" + hashlib.sha256(rel.encode()).hexdigest()[:6]])+ return "/".join(self._seg(p) for p in parts)++ def target(self, abspath: str, touch: str) -> dict[str, Any] | None:+ abspath = abspath.rstrip(".,:;)'\"")+ if not abspath or not _isabs(abspath):+ return None+ found = None+ # Only the user's own ~/.claude (config, transcripts, skills) is bucketed without+ # repo lookup; a repo's checked-in .claude/ files stay repo-relative.+ home_claude = os.path.join(str(Path.home()), ".claude")+ if not (abspath == home_claude or abspath.startswith(home_claude + os.sep)):+ try:+ found = self.resolver.resolve(abspath)+ except Exception:+ found = None+ if not found:+ return {"scope": "outside", "label": _outside_bucket(abspath), "touch": touch}+ root, name, slug = found+ rel = os.path.relpath(abspath, root)+ if rel in (".", "") or rel.startswith("..") or rel.split(os.sep)[0] == ".git":+ return None+ rel = rel.replace(os.sep, "/")+ repo_key = slug or f"local:{root}" # a local-path remote has no slug; key by checkout+ repo = self.repos.get(repo_key)+ if repo is None:+ repo = {"id": f"r{len(self.repos)}", "name": name, "remote": slug or None}+ self.repos[repo_key] = repo+ key = f"{repo['id']}:{rel}"+ f = self.files.get(key)+ if f is None:+ f = {+ "id": len(self.files),+ "repo": repo["id"],+ "path": self._redact_rel(rel),+ "reads": 0,+ "edits": 0,+ "hits": 0,+ "first": None,+ }+ self.files[key] = f+ return {"file": f["id"], "touch": touch, "_key": key}++ # -- events+ def rel_ms(self, ts: float | None) -> int:+ if ts is None:+ return self.events[-1]["t"] if self.events else 0+ if self.t0 is None or ts < self.t0:+ self.t0 = ts if self.t0 is None else self.t0+ return int((ts - (self.t0 or ts)) * 1000)++ def add(self, ev: dict[str, Any], ts: float | None) -> dict[str, Any]:+ ev["_ts"] = ts+ ev.setdefault("err", False)+ if len(self.events) >= MAX_EVENTS:+ self.truncated = True+ return ev+ self.events.append(ev)+ return ev++ def tool_event(+ self, *, tool: str, inp: dict[str, Any], cwd: str | None, agent: str, ts: float | None+ ) -> dict[str, Any]:+ inp = inp if isinstance(inp, dict) else {}+ if tool in SHELL_TOOLS or tool == "js":+ raw = inp.get("command") or inp.get("cmd") or ""+ if isinstance(raw, str) and "exec_command(" in raw:+ unwrapped, wd = unwrap_command(raw)+ if unwrapped is not raw:+ inp = {**inp, "command": unwrapped}+ if wd:+ inp["workdir"] = wd+ tool = "Bash" if tool == "js" else tool+ kind, paths, touch, verb = classify(tool, inp, cwd)+ ev: dict[str, Any] = {"kind": kind, "tool": tool, "agent": agent}+ if verb:+ ev["verb"] = verb+ if kind == "mcp":+ if tool.startswith("mcp__"):+ parts = tool.split("__")+ ev["server"] = parts[1] if len(parts) > 2 else "mcp"+ ev["tool"] = parts[-1]+ else: # Cursor: "mcp-<server>-<tool>"; tool names use underscores, servers dashes+ server, _, leaf = tool[len("mcp-") :].rpartition("-")+ ev["server"] = (server or "mcp")[:80]+ ev["tool"] = (leaf or tool)[:80]+ elif kind == "skill":+ skill = str((inp or {}).get("skill") or (inp or {}).get("name") or "")+ ev["skill"] = skill[:80]+ elif kind == "subagent":+ ev["subagentType"] = str(+ (inp or {}).get("subagent_type") or (inp or {}).get("agent_type") or "general"+ )[:40]+ if (inp or {}).get("model"):+ ev["model"] = str(inp["model"])[:60]+ elif kind == "web":+ url = str((inp or {}).get("url") or "")+ ev["host"] = _url_host(url) or "search"+ ops = file_ops(tool, inp if isinstance(inp, dict) else {}, cwd)+ if tool == "Write" and paths:+ ops.setdefault(os.path.normpath(paths[0]), "write")+ elif tool in EDIT_TOOLS and paths:+ ops.setdefault(os.path.normpath(paths[0]), "modify")+ targets = []+ intents: list[dict[str, Any]] = []+ seen_paths: set[str] = set()+ for p in list(paths) + [q for q in ops if q not in {os.path.normpath(x) for x in paths}]:+ np_ = os.path.normpath(p) if _isabs(p) else p+ if np_ in seen_paths:+ continue+ seen_paths.add(np_)+ op = ops.get(np_)+ t = self.target(p, "edit" if op else (touch or "hit"))+ if t:+ if op:+ key = t.get("_key")+ if op == "write":+ if key in self._touched_keys:+ op = "modify"+ else:+ # First Write to this path in the session: only "create" when+ # the path didn't already exist on disk before this Write (a+ # local stat, same trust level as the shell-path existence+ # check above) — not merely unseen so far in-session.+ with suppress(OSError):+ op = "modify" if os.path.exists(np_) else "create"+ if op == "write":+ op = "create"+ t["op"] = op+ sk = (+ _SKILL_FILE.search(np_.replace(os.sep, "/")) if tool in EDIT_TOOLS else None+ )+ if sk:+ intents.append(+ {+ "type": "skill_write",+ "name": sk.group(1)[:80],+ "action": "create" if op == "create" else "update",+ }+ )+ if t.get("_key"):+ self._touched_keys.add(t["_key"])+ targets.append(t)+ if targets:+ ev["targets"] = targets+ server = ev.get("server") if kind == "mcp" else None+ vcs = vcs_action(+ ev.get("tool", tool) if kind == "mcp" else tool,+ inp if isinstance(inp, dict) else {},+ server,+ )+ intent = pr_create_intent(tool, inp if isinstance(inp, dict) else {})+ if intent:+ vcs = {**(vcs or {}), "provider": intent["provider"], "action": "pr_create"}+ ev["_prIntent"] = intent+ if vcs:+ ev["vcs"] = vcs+ ev["cat"] = tool_category(ev)+ leaf = ev.get("tool") if kind == "mcp" else None+ if leaf is None and tool.lower() in _BARE_MCP_LEAVES:+ leaf = tool # Codex reports MCP tools without their server+ intents.extend(+ output_intents(+ leaf if kind == "mcp" else tool,+ inp,+ ev.get("server") if kind == "mcp" else None,+ leaf,+ )+ )+ if intents:+ ev["_intents"] = intents+ base = inp.get("workdir") or cwd+ cmd = inp.get("command") or inp.get("cmd") or ""+ m = _CD_RE.match(cmd) if isinstance(cmd, str) else None+ if m:+ base = os.path.expanduser(m.group(2).strip())+ ev["_cwd"] = base+ return self.add(ev, ts)++ def resolve_outputs(self, ev: dict[str, Any], text: str, err: bool, ts: float | None) -> None:+ """Confirm a call's output intents against its result; emit output events."""+ intents = ev.pop("_intents", None)+ cwd = ev.pop("_cwd", None)+ if not intents:+ return+ found = None+ if cwd and _isabs(cwd):+ with captured():+ found = self.resolver.resolve(cwd)+ for it in intents:+ if it["type"] == "skill_write":+ # Status alone is not proof (Codex/Cursor report OK for a failed edit):+ # the result must not say the write failed either.+ core = _result_core(text or "")+ failed = err or "tool_use_error" in core or _FAILED_TEXT.search(core[:400])+ out = (+ None+ if failed+ else {"kind": "skill_write", "name": it["name"], "action": it["action"]}+ )+ else:+ out = confirm_output(it, text, err, repo_name=found[1] if found else None)+ if (+ out+ and out["kind"] in ("pr_merge", "pr_close", "pr_comment")+ and not out.get("repo")+ and found+ and "/" in found[2]+ ):+ out["repo"] = found[2][:120] # the checkout's own origin (owner/repo)+ if out:+ out.update(agent=ev["agent"], err=False, _ref=ev)+ self.add(out, ts)++ def llm_event(+ self,+ *,+ agent: str,+ model: str | None,+ usage: dict[str, Any],+ ts: float | None,+ meta: dict[str, Any] | None = None,+ aggregate: bool = False,+ cost_events: list[dict[str, Any]] | None = None,+ ) -> None:+ """One LLM request. ``meta`` carries response metadata only (never text):+ ``stop``, ``thinking``, ``toolCalls``, ``textChars``, ``latency``.++ ``aggregate`` marks ``usage`` as a turn's summed requests; ``cost_events``+ (the turn span's ``llm.cost_events``) then prices each request on its own,+ so the per-request long-context tier applies only where one request+ actually crossed it.+ """+ fresh = int(usage.get("input_tokens") or 0)+ cw = int(usage.get("cache_creation_input_tokens") or 0)+ cr = int(usage.get("cache_read_input_tokens") or 0)+ out = int(usage.get("output_tokens") or 0)+ ev: dict[str, Any] = {+ "kind": "llm",+ "agent": agent,+ "model": model or "",+ "in": fresh,+ "cw": cw,+ "cr": cr,+ "out": out,+ }+ cost = _cost_from_events(model, cost_events) if cost_events else None+ if cost is None:+ cost = estimate_cost_usd(model, fresh, cw, cr, out, single_request=not aggregate)+ if cost is not None:+ ev["cost"] = cost+ for k, v in (meta or {}).items():+ if v not in (None, "", 0, False) or k == "toolCalls":+ ev[k] = v+ self.add(ev, ts)++ def signal(+ self, *, agent: str, source: str, err_class: str, ts: float | None, **extra: Any+ ) -> dict[str, Any]:+ """An error signal that is not the result of one of our tool events."""+ ev: dict[str, Any] = {+ "kind": "error",+ "agent": agent,+ "source": source,+ "errClass": err_class,+ "err": True,+ }+ ev.update({k: v for k, v in extra.items() if v is not None})+ return self.add(ev, ts)++ def _derive(self, evs: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Add delay events (slow tools, slow LLM responses, stalls). Returns new events."""+ extra: list[dict[str, Any]] = []+ for e in evs:+ ts = e.get("_ts")+ if ts is None:+ continue+ if e["kind"] not in ("llm", "user", "compaction", "error", "delay"):+ dur = e.get("dur") or 0+ if dur >= TOOL_DELAY_MS:+ extra.append(+ {+ "kind": "delay",+ "agent": e["agent"],+ "err": False,+ "cause": "subagent" if e["kind"] == "subagent" else "tool",+ "ms": int(dur),+ "_ref": e,+ "_ts": ts + 0.0005,+ }+ )+ elif e["kind"] == "llm" and (e.get("latency") or 0) >= LLM_DELAY_MS:+ extra.append(+ {+ "kind": "delay",+ "agent": e["agent"],+ "err": False,+ "cause": "llm",+ "ms": int(e["latency"]),+ "_ref": e,+ "_ts": ts - e["latency"] / 1000.0,+ }+ )+ main = [e for e in evs if e["agent"] == "main" and e.get("_ts") is not None]+ for prev, nxt in zip(main, main[1:], strict=False):+ gap = (nxt["_ts"] - prev["_ts"]) * 1000+ if gap >= STALL_MS and nxt["kind"] not in ("user",) and prev["kind"] != "user":+ covered = (prev.get("dur") or 0) >= gap * 0.8 or (+ nxt.get("latency") or 0+ ) >= gap * 0.8+ if not covered:+ extra.append(+ {+ "kind": "delay",+ "agent": "main",+ "err": False,+ "cause": "stall",+ "ms": int(gap),+ "_ts": prev["_ts"] + 0.0005,+ }+ )+ return extra++ @staticmethod+ def _retry_key(e: dict[str, Any]) -> tuple[Any, ...] | None:+ if e["kind"] in _NON_CALL_KINDS:+ return None+ tg = (e.get("targets") or [{}])[0]+ return (+ e["agent"],+ e.get("tool"),+ e.get("server"),+ e.get("verb"),+ e.get("skill"),+ tg.get("file"),+ tg.get("label"),+ )++ def _mark_retries(self, evs: list[dict[str, Any]]) -> None:+ recent: dict[str, list[dict[str, Any]]] = {}+ for e in evs:+ key = self._retry_key(e)+ if key is None:+ continue+ window = recent.setdefault(e["agent"], [])+ prev = next((p for p in reversed(window) if self._retry_key(p) == key), None)+ if prev is not None and prev.get("err"):+ e["retryOf"] = prev["seq"]+ e["attempt"] = int(prev.get("attempt") or 1) + 1+ window.append(e)+ del window[:-RETRY_WINDOW]++ # -- finalize+ def finish(self, *, session: dict[str, Any]) -> dict[str, Any]:+ evs = [e for e in self.events if e.get("_ts") is not None] + [+ e for e in self.events if e.get("_ts") is None+ ]+ evs.sort(key=lambda e: e["_ts"] if e["_ts"] is not None else float("inf"))+ derived = self._derive(evs)+ room = max(MAX_EVENTS - len(evs), 0) # raw events are already capped in add()+ if len(derived) > room:+ derived = derived[:room]+ self.truncated = True+ evs.extend(derived)+ evs.sort(key=lambda e: e["_ts"] if e["_ts"] is not None else float("inf"))+ switches = self._assign_models(evs)+ room = max(MAX_EVENTS - len(evs), 0)+ if len(switches) > room:+ switches = switches[:room]+ self.truncated = True+ if switches:+ evs.extend(switches)+ evs.sort(key=lambda e: e["_ts"] if e["_ts"] is not None else float("inf"))+ t0 = next((e["_ts"] for e in evs if e["_ts"] is not None), None)+ last_t = 0+ for i, e in enumerate(evs):+ for private in ("_intents", "_cwd", "_prIntent"):+ e.pop(private, None)+ ts = e.pop("_ts")+ e["t"] = int((ts - t0) * 1000) if (ts is not None and t0 is not None) else last_t+ last_t = e["t"]+ e["seq"] = i+ for tg in e.get("targets", []):+ key = tg.pop("_key", None)+ if key:+ f = self.files[key]+ f[{"read": "reads", "edit": "edits", "hit": "hits"}[tg["touch"]]] += 1+ if f["first"] is None:+ f["first"] = i+ if tg.get("op"):+ f["op"] = tg["op"]+ for e in evs:+ ref = e.pop("_ref", None)+ if ref is not None and "seq" in ref:+ e["ref"] = ref["seq"]+ self._mark_retries(evs)+ tasks = self._assign_tasks(evs, t0)+ # A PR-creating call past MAX_EVENTS never got a home (add() drops it without a+ # seq once truncated) — the PR still happened, but there's no event to link it+ # to, so it's dropped from the list rather than crashing the whole build.+ kept: list[dict[str, Any]] = []+ for pr in self.prs_created:+ ev_ref = pr.pop("_ev")+ if "seq" in ev_ref:+ pr["seq"] = ev_ref["seq"]+ kept.append(pr)+ self.prs_created = kept+ for a in self.agents:+ mine = [e for e in evs if e["agent"] == a["id"]]+ if not mine:+ continue+ a.update(+ start=mine[0]["t"],+ end=mine[-1]["t"],+ calls=sum(1 for e in mine if e["kind"] not in _NON_CALL_KINDS),+ requests=sum(1 for e in mine if e["kind"] == "llm"),+ tokens=sum(+ e.get("in", 0) + e.get("cw", 0) + e.get("cr", 0) + e.get("out", 0) for e in mine+ ),+ cost=round(sum(e.get("cost", 0.0) for e in mine), 4),+ outcome=classify_outcome(mine, self.last_agent_text.get(a["id"], "")),+ )+ agents = [a for a in self.agents if "start" in a]+ llm = [e for e in evs if e["kind"] == "llm"]+ prs = [dict(pr) for pr in self.prs_created]+ created_numbers = [pr["number"] for pr in prs]+ for pr in prs:+ pr["state"] = "open"+ for e in evs:+ if e["kind"] not in ("pr_merge", "pr_close") or e.get("number") != pr["number"]:+ continue+ if e.get("repo"):+ if str(e["repo"]).lower() != str(pr["repo"]).lower():+ continue # same number in another repo: not this PR+ elif created_numbers.count(pr["number"]) != 1:+ continue # a repo-less outcome is only attributable when unambiguous+ pr["state"] = "merged" if e["kind"] == "pr_merge" else "closed"+ users = [e for e in evs if e["kind"] == "user" and e["agent"] == "main"]++ def _n(kind: str, **match: Any) -> int:+ return sum(+ 1 for e in evs if e["kind"] == kind and all(e.get(k) == v for k, v in match.items())+ )++ doc = {+ "schema": SCHEMA,+ "session": {+ **session,+ "startedAt": _iso(t0) if t0 else session.get("startedAt"),+ "durationMs": evs[-1]["t"] if evs else 0,+ "models": sorted({e["model"] for e in llm if e.get("model")}),+ "pathMode": self.path_mode,+ "truncated": self.truncated,+ "outcome": classify_outcome(evs, self.last_agent_text.get("main", "")),+ },+ "totals": {+ "calls": sum(1 for e in evs if e["kind"] not in _NON_CALL_KINDS),+ "requests": len(llm),+ "userTurns": sum(1 for e in evs if e["kind"] == "user"),+ "subagents": len(agents) - 1 if agents else 0,+ "errors": sum(1 for e in evs if e.get("err")),+ "tokens": sum(e["in"] + e["cw"] + e["cr"] + e["out"] for e in llm),+ "costUsd": round(sum(e.get("cost", 0.0) for e in llm), 4),+ "filesTouched": len(self.files),+ "prsCreated": len(prs),+ "filesCreated": sum(1 for f in self.files.values() if f.get("op") == "create"),+ "filesDeleted": sum(1 for f in self.files.values() if f.get("op") == "delete"),+ **_signal_totals(evs),+ "tasks": len(tasks),+ "commits": _n("commit"),+ "prsMerged": _n("pr_merge"),+ "prsClosed": _n("pr_close"),+ "prComments": _n("pr_comment"),+ "ticketsCreated": _n("ticket", action="create"),+ "ticketsUpdated": _n("ticket", action="update"),+ "artifacts": _n("artifact"),+ "skillsCreated": _n("skill_write", action="create"),+ "skillsUpdated": _n("skill_write", action="update"),+ "modelSwitches": _n("model_switch"),+ "promptChars": sum(int(e.get("chars") or 0) for e in users),+ "promptImages": sum(int(e.get("images") or 0) for e in users),+ "promptUrls": sum(int(e.get("urls") or 0) for e in users),+ },+ "repos": list(self.repos.values()),+ "files": sorted(self.files.values(), key=lambda f: f["id"]),+ "agents": agents,+ "prs": prs,+ "tasks": tasks,+ "events": evs,+ }+ return doc++ def _assign_models(self, evs: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Stamp each event with the model driving its agent; return model_switch events.++ An agent's model is its latest LLM request's model (its first one for events+ before any request; the harness default — Cursor's ``"default"`` — when the+ harness never names one). A ``subagent`` launch keeps its own ``model``: that+ is the *requested child* model.+ """+ first: dict[str, str] = {}+ for e in evs:+ if e["kind"] == "llm" and e.get("model"):+ first.setdefault(e["agent"], e["model"])+ last: dict[str, str] = {}+ switches: list[dict[str, Any]] = []+ for e in evs:+ agent = e["agent"]+ if e["kind"] == "llm":+ if not e.get("model"):+ e["model"] = last.get(agent) or first.get(agent) or self.default_model+ prev = last.get(agent)+ if e.get("model") and prev and prev != e["model"] and e.get("_ts") is not None:+ switches.append(+ {+ "kind": "model_switch",+ "agent": agent,+ "err": False,+ "from": prev,+ "to": e["model"],+ "model": e["model"],+ "_ts": e["_ts"] - 1e-6,+ }+ )+ if e.get("model"):+ last[agent] = e["model"]+ elif not (e["kind"] == "subagent" and e.get("model")):+ m = last.get(agent) or first.get(agent) or self.default_model+ if m:+ e["model"] = m+ return switches++ def _assign_tasks(self, evs: list[dict[str, Any]], t0: float | None) -> list[dict[str, Any]]:+ """Split the session into tasks (time windows); stamp each event's ``task``.++ Source ``segments``: the CLI's own segmentation of this session, cached on+ disk. Source ``turns`` (fallback): one task per user prompt, since a+ task starts at a prompt and runs until the next one. Events before the first+ boundary belong to task 1.+ """+ if not evs:+ return []+ specs: list[dict[str, Any]] = []+ if self.task_specs and t0 is not None:+ seen: set[int] = set()+ for sp in self.task_specs:+ st = _parse_ts(sp.get("startAt"))+ if st is None:+ continue+ start = max(0, int((st - t0) * 1000))+ if start in seen:+ continue+ seen.add(start)+ specs.append(+ {+ "id": f"task:{sp.get('n')}",+ "name": (str(sp["name"])[:120] if sp.get("name") else None),+ "source": "segments",+ "startT": start,+ "firstTurn": sp.get("firstTurn"),+ "lastTurn": sp.get("lastTurn"),+ }+ )+ specs.sort(key=lambda x: x["startT"])+ if not specs:+ users = [e for e in evs if e["kind"] == "user" and e["agent"] == "main"]+ specs = [+ {"id": f"turn:{i + 1}", "name": None, "source": "turns", "startT": u["t"]}+ for i, u in enumerate(users)+ ] or [{"id": "turn:1", "name": None, "source": "turns", "startT": 0}]+ specs[0]["startT"] = 0+ k = 0+ turn = 0+ for e in evs:+ while k + 1 < len(specs) and e["t"] >= specs[k + 1]["startT"]:+ k += 1+ e["task"] = k + 1+ if e["kind"] == "user" and e["agent"] == "main":+ turn += 1+ spec = specs[k]+ if spec["source"] == "turns":+ spec.setdefault("firstTurn", turn)+ spec["lastTurn"] = turn+ by_task: dict[int, list[dict[str, Any]]] = {}+ for e in evs:+ by_task.setdefault(e["task"], []).append(e)+ out = []+ for i, spec in enumerate(specs):+ mine = by_task.get(i + 1)+ if not mine:+ continue # a boundary with no events of its own (e.g. two prompts, no work)+ n = len(out) + 1+ for e in mine:+ e["task"] = n+ llm = [e for e in mine if e["kind"] == "llm"]+ out.append(+ {+ "n": n,+ "id": spec["id"],+ "name": spec["name"],+ "source": spec["source"],+ "startSeq": mine[0]["seq"],+ "endSeq": mine[-1]["seq"],+ "startT": mine[0]["t"],+ "endT": mine[-1]["t"],+ "firstTurn": spec.get("firstTurn"),+ "lastTurn": spec.get("lastTurn"),+ "requests": len(llm),+ "calls": sum(1 for e in mine if e["kind"] not in _NON_CALL_KINDS),+ "costUsd": round(sum(e.get("cost", 0.0) for e in llm), 4),+ }+ )+ return out+++# ---------------------------------------------------------------- Claude Code+_URL_RE = re.compile(r"https?://[^\s<>\"')\]]+")+++def _count_images(content: Any) -> int:+ """Image blocks in a prompt — a count only, never the image."""+ if not isinstance(content, list):+ return 0+ return sum(1 for x in content if isinstance(x, dict) and x.get("type") == "image")+++def _user_text(content: Any) -> str | None:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ if any(isinstance(x, dict) and x.get("type") == "tool_result" for x in content):+ return None+ texts = [+ x["text"] for x in content+ if isinstance(x, dict) and x.get("type") == "text" and isinstance(x.get("text"), str)+ ]+ return " ".join(texts) if texts else None+ return None+++def user_turn_text(rec: Any, agent_id: str = "main") -> str | None:+ """Prompt text of a Claude Code record that becomes a ``user`` event, else None.++ The single rule for "is this a user turn". Anything that answers None here+ contributes no ``user`` event, so it must not take a slot in anything+ indexed by turn either: task titles are looked up by ``firstTurn``, which+ counts *emitted* user events, and one extra entry shifts every later label.++ Args:+ rec: one decoded transcript record.+ agent_id: the agent the record is being read into; only ``main`` turns+ are emitted, subagent prompts never are.++ Returns:+ The prompt text (unstripped, as the event's ``chars`` counts it), or+ None for tool results, meta and compact-summary records, interruptions,+ harness-only turns, and records with no usable timestamp.+ """+ if not isinstance(rec, dict) or rec.get("type") != "user":+ return None+ if rec.get("isCompactSummary") or rec.get("isMeta") or agent_id != "main":+ return None+ if _parse_ts(rec.get("timestamp")) is None:+ return None+ msg = rec.get("message") if isinstance(rec.get("message"), dict) else {}+ text = _user_text(msg.get("content"))+ if text is None:+ return None+ stripped = text.lstrip()+ if not stripped or stripped.startswith("[Request interrupted") or stripped.startswith("<"):+ return None+ if "[SYSTEM NOTIFICATION" in stripped:+ return None+ return text+++def user_turns(lines: Iterable[str]) -> list[tuple[int, dict[str, Any], str]]:+ """Every record of a Claude Code transcript that becomes a ``user`` event, in turn order.++ Turn ``k`` (1-based, as ``firstTurn`` counts it) is element ``k - 1``. The+ builder numbers turns after a stable sort of its events by timestamp, not in+ file order: a resumed session replays earlier prompts with their original+ timestamps, so file order would point every later turn at the wrong prompt.+ Anything indexed by turn (task titles, prompt images) must order the same way.++ Args:+ lines: raw transcript lines; ones that are not JSON are skipped.++ Returns:+ ``(line_no, record, text)`` per emitted turn, ``line_no`` being the+ 0-based position of the record's line within ``lines``.+ """+ # Holds every user record (pasted images included) until the sort; keeping only+ # (timestamp, line_no) and re-reading records would cut memory on huge transcripts.+ turns: list[tuple[int, dict[str, Any], str]] = []+ for line_no, line in enumerate(lines):+ try:+ rec = json.loads(line)+ except ValueError:+ continue+ text = user_turn_text(rec)+ if text is not None:+ turns.append((line_no, rec, text))+ # `user_turn_text` only accepts records with a parseable timestamp.+ turns.sort(key=lambda t: _parse_ts(t[1]["timestamp"]) or 0.0)+ return turns+++def _read_claude_transcript(+ b: MapBuilder, path: Path, agent_id: str, child_links: dict[str, str]+) -> None:+ """One Claude Code JSONL (main or subagent) into events.++ LLM requests are keyed by message id: a streamed response spans several+ lines, so usage/stop reason come from the last line and content-derived+ metadata (thinking, tool-call count, text length) is summed across lines.+ Error text is read only to classify it (``classify_*``); it is never stored.+ """+ msgs: dict[str, dict[str, Any]] = {}+ pending: dict[str, dict[str, Any]] = {}+ tool_events: dict[str, dict[str, Any]] = {} # tool_use id -> event; hook errors link back to it+ ready_ts: float | None = None # when the agent last had new input (user turn / tool result)+ last_text = "" # last assistant text block; only its length feeds classify_outcome, never stored+ with path.open(encoding="utf-8", errors="replace") as fh:+ for line in fh:+ try:+ d = json.loads(line)+ except (ValueError, TypeError):+ continue+ if not isinstance(d, dict):+ continue+ ts = _parse_ts(d.get("timestamp"))+ if ts is None:+ continue+ msg = d.get("message") if isinstance(d.get("message"), dict) else {}+ typ = d.get("type")+ if typ == "system":+ sub = d.get("subtype")+ if sub == "compact_boundary":+ cm = (+ d.get("compactMetadata")+ if isinstance(d.get("compactMetadata"), dict)+ else {}+ )+ ev = {"kind": "compaction", "agent": agent_id}+ for src, dst in (+ ("trigger", "trigger"),+ ("preTokens", "preTokens"),+ ("postTokens", "postTokens"),+ ("durationMs", "ms"),+ ):+ v = cm.get(src)+ if isinstance(v, (int, float)) or (src == "trigger" and isinstance(v, str)):+ ev[dst] = v if src == "trigger" else int(v)+ b.add(ev, ts)+ elif sub == "model_refusal_fallback":+ b.signal(+ agent=agent_id,+ source="llm",+ err_class="refusal_fallback",+ ts=ts,+ retry=d.get("direction") == "retry",+ )+ elif sub == "api_error" or (sub and "error" in str(sub)):+ b.signal(+ agent=agent_id,+ source="llm",+ err_class=classify_api_error(d.get("error"), _flat_text(d.get("content"))),+ ts=ts,+ )+ continue+ if typ == "attachment":+ att = d.get("attachment") if isinstance(d.get("attachment"), dict) else {}+ at = att.get("type")+ if at in ("hook_blocking_error", "hook_non_blocking_error"):+ b.signal(+ agent=agent_id,+ source="hook",+ err_class="hook_blocking" if at == "hook_blocking_error" else "hook_error",+ ts=ts,+ hook=str(att.get("hookName") or att.get("hookEvent") or "")[:60] or None,+ hookEvent=str(att.get("hookEvent") or "")[:60] or None,+ # The record's random id, so a local viewer can look the message up.+ srcUuid=d["uuid"][:64] if isinstance(d.get("uuid"), str) else None,+ _ref=tool_events.get(str(att.get("toolUseID"))),+ )+ continue+ if typ == "user":+ if d.get("isCompactSummary"):+ continue+ content = msg.get("content")+ text = _user_text(content)+ if (+ text is not None+ and not d.get("isMeta")+ and text.lstrip().startswith("[Request interrupted")+ ):+ b.signal(+ agent=agent_id, source="orchestration", err_class="interrupted", ts=ts+ )+ else:+ turn = user_turn_text(d, agent_id)+ if turn is not None:+ b.add(+ {+ "kind": "user",+ "agent": agent_id,+ "chars": len(turn),+ "images": _count_images(content),+ "urls": len(_URL_RE.findall(turn)),+ },+ ts,+ )+ ready_ts = ts+ if isinstance(content, list):+ for x in content:+ if not isinstance(x, dict) or x.get("type") != "tool_result":+ continue+ ready_ts = ts+ ev = pending.pop(x.get("tool_use_id"), None)+ if ev is None:+ continue+ body = x.get("content")+ ev["err"] = bool(x.get("is_error"))+ if ev["err"]:+ cls, code = classify_tool_error(_flat_text(body))+ ev["errClass"] = cls+ if code is not None:+ ev["exitCode"] = code+ ev["outBytes"] = (+ len(json.dumps(body, ensure_ascii=False)) if body is not None else 0+ )+ if ev.get("_ts") is not None:+ ev["dur"] = max(0, int((ts - ev["_ts"]) * 1000))+ intent = ev.pop("_prIntent", None)+ if intent:+ hit = None if ev["err"] else _pr_from_url(_flat_text(body, 4000))+ if hit and (+ not intent.get("repo")+ or hit["repo"].endswith(intent["repo"].split("/")[-1])+ ):+ ev["vcs"] = {+ "provider": hit["provider"],+ "action": "pr_create",+ "repo": hit["repo"],+ "number": hit["number"],+ }+ b.prs_created.append(+ {+ "provider": hit["provider"],+ "repo": hit["repo"],+ "number": hit["number"],+ "url": hit["url"],+ "_ev": ev,+ }+ )+ else:+ # Optimistic action set at tool_event time didn't resolve to a+ # real PR/MR URL: the command errored, or its output didn't+ # contain one (e.g. `gh pr create --web`, a dry run).+ ev["vcs"]["action"] = (+ "pr_create_failed" if ev["err"] else "pr_create_attempt"+ )+ b.resolve_outputs(ev, _flat_text(body, 20_000), ev["err"], ts)+ res = d.get("toolUseResult")+ if ev.get("kind") == "subagent" and isinstance(res, dict):+ if res.get("agentId"):+ child = "sa-" + str(res["agentId"])[:12]+ ev["child"] = child+ child_links[str(res["agentId"])] = child+ status = str(res.get("status") or "")+ if status in ("failed", "error", "killed", "cancelled"):+ ev["err"] = True+ ev.setdefault("errClass", "subagent_" + status)+ continue+ if typ == "assistant":+ if d.get("isApiErrorMessage"):+ b.signal(+ agent=agent_id,+ source="llm",+ err_class=classify_api_error(+ d.get("error"), _flat_text(msg.get("content"))+ ),+ ts=ts,+ )+ continue+ mid = msg.get("id")+ if mid and msg.get("model") != "<synthetic>":+ m = msgs.get(mid)+ if m is None:+ latency = (+ int((ts - ready_ts) * 1000)+ if ready_ts is not None and ts >= ready_ts+ else None+ )+ m = msgs[mid] = {+ "ts": ts,+ "model": msg.get("model"),+ "usage": {},+ "thinking": False,+ "toolCalls": 0,+ "textChars": 0,+ "stop": None,+ "latency": latency,+ }+ if isinstance(msg.get("usage"), dict):+ m["usage"] = msg["usage"]+ if msg.get("stop_reason"):+ m["stop"] = str(msg["stop_reason"])[:32]+ for c in msg.get("content") or []:+ if not isinstance(c, dict):+ continue+ if c.get("type") in ("thinking", "redacted_thinking"):+ m["thinking"] = True+ elif c.get("type") == "text":+ text = str(c.get("text") or "")+ m["textChars"] += len(text)+ if text.strip():+ last_text = text+ elif c.get("type") == "tool_use":+ m["toolCalls"] += 1+ for c in msg.get("content") or []:+ if not isinstance(c, dict) or c.get("type") != "tool_use":+ continue+ ev = b.tool_event(+ tool=str(c.get("name") or "tool"),+ inp=c.get("input") or {},+ cwd=d.get("cwd"),+ agent=agent_id,+ ts=ts,+ )+ if c.get("id"):+ pending[c["id"]] = ev+ tool_events[c["id"]] = ev+ for m in msgs.values():+ if not m["usage"]:+ continue+ b.llm_event(+ agent=agent_id,+ model=m["model"],+ usage=m["usage"],+ ts=m["ts"],+ meta={+ "stop": m["stop"],+ "thinking": m["thinking"],+ "toolCalls": m["toolCalls"],+ "textChars": m["textChars"],+ "latency": m["latency"],+ },+ )+ b.last_agent_text[agent_id] = last_text+ for ev in pending.values(): # tool calls that never got a result (killed, interrupted, crash)+ ev["err"] = True+ ev.setdefault("errClass", "no_result")+ ev.pop("_prIntent", None)+ if (ev.get("vcs") or {}).get("action") == "pr_create":+ ev["vcs"]["action"] = "pr_create_failed"+++def build_claude_code_map(+ transcript: Path,+ *,+ path_mode: str = "relative",+ hmac_key: bytes | None = None,+ cli_version: str = "",+ resolver: RepoResolver | None = None,+ tasks: list[dict[str, Any]] | None = None,+) -> dict[str, Any]:+ """Build a map for one Claude Code session file (plus its subagent transcripts)."""+ transcript = Path(transcript)+ b = MapBuilder(path_mode=path_mode, hmac_key=hmac_key, resolver=resolver)+ b.task_specs = tasks+ links: dict[str, str] = {}+ _read_claude_transcript(b, transcript, "main", links)+ sub_dir = transcript.with_suffix("") / "subagents"+ if sub_dir.is_dir():+ for f in sorted(sub_dir.glob("agent-*.jsonl")):+ raw_id = f.stem[len("agent-") :]+ if raw_id.startswith("acompact-"):+ # Auto-compaction snapshots re-record parent API messages, not an agent's+ # work: a subagent would be fake and its llm events would double-count them.+ # The compaction call itself stays billed on the parent.+ continue+ aid = links.get(raw_id) or ("sa-" + raw_id[:12])+ sub_type, model = "general", ""+ meta = f.with_suffix(".meta.json")+ if meta.exists():+ try:+ m = json.loads(meta.read_text(encoding="utf-8"))+ sub_type = str(m.get("agentType") or m.get("subagent_type") or sub_type)[:40]+ model = str(m.get("model") or "")[:60]+ except (ValueError, OSError):+ pass+ launch = next((e for e in b.events if e.get("child") == aid), None)+ if launch is not None:+ sub_type = launch.get("subagentType", sub_type)+ b.agents.append(+ {+ "id": aid,+ "parent": "main",+ "kind": "subagent",+ "subagentType": sub_type,+ **({"model": model} if model else {}),+ }+ )+ _read_claude_transcript(b, f, aid, {})+ doc = b.finish(+ session={+ "id": f"local:claude-code:{transcript.stem}",+ "agentTool": "claude-code",+ "cliVersion": cli_version,+ "role": _claude_role(transcript),+ "parentSessionId": None,+ }+ )+ for a in doc["agents"]:+ launch = next((e for e in doc["events"] if e.get("child") == a["id"]), None)+ if launch is not None:+ a["launchSeq"] = launch["seq"]+ return doc+++def _claude_role(transcript: Path) -> str | None:+ """root / subagent / helper - the transcript's own classification, reused so the+ sidebar and the recorded facts can never disagree. ``None`` when it can't be read."""+ try:+ if transcript.stat().st_size > ROLE_READ_MAX_BYTES:+ return "root" # classifying needs the whole file; a transcript this big is real work+ from ._claude_role import claude_subagent_transcript as _claude_subagent_transcript++ data = transcript.read_bytes()+ if _claude_subagent_transcript(data):+ return "subagent"+ return "root"+ except Exception: # noqa: BLE001 — a role is metadata; never fail the map over it+ return None+++# ---------------------------------------------------------------- generic spans+def _span_ts(v: Any) -> float | None:+ """Epoch seconds from a span time (ISO string or datetime); ``None`` if unusable."""+ try:+ if isinstance(v, str):+ return _parse_ts(v)+ if hasattr(v, "timestamp"):+ return float(v.timestamp())+ except (TypeError, ValueError, OverflowError, OSError):+ return None+ return None+++def build_map_from_spans(+ spans: Iterable[Any],+ *,+ session_id: str,+ agent_tool: str,+ path_mode: str = "relative",+ hmac_key: bytes | None = None,+ cli_version: str = "",+ resolver: RepoResolver | None = None,+ tasks: list[dict[str, Any]] | None = None,+ role: str | None = None,+ parent_session_id: str | None = None,+ started_at_hint: float | None = None,+) -> dict[str, Any]:+ """Build a map from the shared ``LocalSource`` span tree (Codex, Cursor, Kiro, …).++ Turn spans become one ``llm`` event (turn-level tokens) plus a ``user`` event;+ tool spans (children of turns) become tool events. Subagent traffic is not in+ the span tree, so these maps have only the main agent.++ ``started_at_hint`` (epoch seconds, typically the source file's own mtime) is+ the session's ``startedAt`` when no span carries a timestamp — a real gap seen+ on tiny Cursor sessions (a handful of untimestamped events). Without it+ ``finish()``'s own fallback (``session.get("startedAt")``) has nothing to fall+ back to, since this dict never set that key, so the map ships with no+ ``startedAt`` at all and readers cannot place it on the timeline, so the+ map is invalid rather than merely incomplete.+ """+ b = MapBuilder(path_mode=path_mode, hmac_key=hmac_key, resolver=resolver)+ b.task_specs = tasks+ spans = list(spans)+ turn_ids = {s.span_id for s in spans if str(getattr(s, "name", "")).startswith("Turn ")}+ root = next((s for s in spans if getattr(s, "parent_id", None) is None), None)+ if root is not None:+ # Cursor stamps its model ("default", unresolved) on the session root only.+ b.default_model = str((getattr(root, "attributes", {}) or {}).get("llm.model_name") or "")[+ :60+ ]+ for s in spans:+ attrs = getattr(s, "attributes", {}) or {}+ ts = _span_ts(getattr(s, "start_time", None))+ if s.span_id in turn_ids:+ prompt = attrs.get("input.value")+ if prompt:+ b.add(+ {+ "kind": "user",+ "agent": "main",+ "chars": len(str(prompt)),+ "images": 0,+ "urls": len(_URL_RE.findall(str(prompt))),+ },+ ts,+ )+ usage = {+ "input_tokens": attrs.get("llm.token_count.input_fresh") or 0,+ "cache_creation_input_tokens": attrs.get("llm.token_count.cache_write") or 0,+ "cache_read_input_tokens": attrs.get("llm.token_count.cache_read") or 0,+ "output_tokens": attrs.get("llm.token_count.completion") or 0,+ }+ # One request per turn even when the parser has no usage (Cursor stamps zeros).+ events = attrs.get("llm.cost_events")+ b.llm_event(+ agent="main",+ model=attrs.get("llm.model_name"),+ usage=usage,+ ts=ts,+ aggregate=True,+ cost_events=events if isinstance(events, list) else None,+ )+ continue+ if getattr(s, "parent_id", None) not in turn_ids:+ continue+ raw = attrs.get("input.value")+ tool_name = str(attrs.get("tool.name") or s.name)+ try:+ inp = json.loads(raw) if isinstance(raw, str) else (raw or {})+ except ValueError:+ # Codex code mode: the input is a JS snippet wrapping the shell command.+ inp = (+ {"command": loose_command(raw)}+ if tool_name in SHELL_TOOLS or tool_name == "js"+ else {}+ )+ ev = b.tool_event(+ tool=tool_name,+ inp=inp if isinstance(inp, dict) else {},+ cwd=attrs.get("cwd"),+ agent="main",+ ts=ts,+ )+ ev["err"] = getattr(s, "status_code", "") == "ERROR"+ end_ts = _span_ts(getattr(s, "end_time", None))+ if ts is not None and end_ts is not None and end_ts >= ts:+ ev["dur"] = int((end_ts - ts) * 1000)+ out = attrs.get("output.value")+ if out is not None:+ ev["outBytes"] = len(str(out))+ b.resolve_outputs(+ ev, str(out or "")[:20_000], ev["err"], end_ts if end_ts is not None else ts+ )+ return b.finish(+ session={+ "id": session_id,+ "agentTool": agent_tool,+ "cliVersion": cli_version,+ "role": role,+ "parentSessionId": parent_session_id,+ "startedAt": _iso(started_at_hint) if started_at_hint else None,+ }+ )+++# ---------------------------------------------------------------- serialization+def canonical_bytes(doc: dict[str, Any]) -> bytes:+ """Deterministic JSON bytes (sorted keys, compact) — the content hash input."""+ return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(+ "utf-8"+ )+++def content_hash(doc: dict[str, Any]) -> str:+ """sha256 over the map minus volatile fields, so rebuilding an unchanged session is a no-op."""+ stable = {+ **doc,+ "session": {k: v for k, v in doc.get("session", {}).items() if k != "cliVersion"},+ }+ return hashlib.sha256(canonical_bytes(stable)).hexdigest()+++def summary(doc: dict[str, Any]) -> dict[str, Any]:+ """The small index-row summary stored alongside each map in the local index."""+ s, t = doc["session"], doc["totals"]+ return {+ "startedAt": s.get("startedAt"),+ "durationMs": s.get("durationMs"),+ "agentTool": s.get("agentTool"),+ "models": s.get("models", []),+ "repos": [r["name"] for r in doc.get("repos", [])],+ "calls": t["calls"],+ "requests": t["requests"],+ "subagents": t["subagents"],+ "errors": t["errors"],+ "filesTouched": t["filesTouched"],+ "costUsd": t["costUsd"],+ "tokens": t["tokens"],+ "userTurns": t["userTurns"],+ "truncated": bool(s.get("truncated")),+ "errorsBySource": t.get("errorsBySource", {}),+ "retries": t.get("retries", 0),+ "delays": t.get("delays", 0),+ "maxContext": t.get("maxContext", 0),+ "compactions": t.get("compactions", 0),+ # The sidebar filters on role (main sessions only) and shows+ # outputs/PR state without opening the map.+ "role": s.get("role"),+ "parentSessionId": s.get("parentSessionId"),+ "tasks": t.get("tasks", 0),+ "outputs": {+ "commits": t.get("commits", 0),+ "prsCreated": t.get("prsCreated", 0),+ "prsMerged": t.get("prsMerged", 0),+ "prsClosed": t.get("prsClosed", 0),+ "prComments": t.get("prComments", 0),+ "ticketsCreated": t.get("ticketsCreated", 0),+ "ticketsUpdated": t.get("ticketsUpdated", 0),+ "artifacts": t.get("artifacts", 0),+ "skillsCreated": t.get("skillsCreated", 0),+ "skillsUpdated": t.get("skillsUpdated", 0),+ },+ "prs": [+ {k: pr.get(k) for k in ("repo", "number", "url", "state")}+ for pr in doc.get("prs", [])[:20]+ ],+ }diff --git a/python/src/agentplay/cli.py b/python/src/agentplay/cli.pynew file mode 100644index 0000000..20880a1--- /dev/null+++ b/python/src/agentplay/cli.py@@ -0,0 +1,411 @@+"""Command line: ``agentplay [view|build|list|export|import|agents]``.++Run with no arguments to build maps for your sessions and open the viewer.+"""++from __future__ import annotations++import argparse+import gzip+import json+import logging+import os+import re+import sys+import threading+import warnings+import webbrowser+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import TextIO++from . import __version__, discover, pipeline+from .store import Store++_TTY = sys.stdout.isatty() and not os.environ.get("NO_COLOR")+++def _b(s: str) -> str:+ return f"\033[1m{s}\033[0m" if _TTY else s+++def _dim(s: str) -> str:+ return f"\033[2m{s}\033[0m" if _TTY else s++++def _since(value: str | None) -> datetime | None:+ """Parse ``30d`` / ``12h`` / ``2026-09-01``."""+ if not value:+ return None+ m = re.fullmatch(r"(\d+)([dhw])", value.strip())+ if m:+ n, unit = int(m.group(1)), m.group(2)+ delta = {"d": timedelta(days=n), "h": timedelta(hours=n), "w": timedelta(weeks=n)}[unit]+ return datetime.now(UTC) - delta+ try:+ dt = datetime.fromisoformat(value)+ return dt if dt.tzinfo else dt.replace(tzinfo=UTC)+ except ValueError:+ raise SystemExit(f"agentplay: can't read --since {value!r}; use 30d, 12h, 2w or YYYY-MM-DD") from None+++def _agents(value: str | None) -> set[str] | None:+ if not value:+ return None+ wanted = {a.strip() for a in value.split(",") if a.strip()}+ unknown = wanted - set(discover.AGENTS)+ if unknown:+ raise SystemExit(f"agentplay: unknown agent(s) {sorted(unknown)}; choose from {', '.join(discover.AGENTS)}")+ return wanted+++# --------------------------------------------------------------------------- build+# True while a progress bar is on screen, so log lines know to wipe it first.+_progress_live = False+++def _progress(done: int, total: int, _sid: str) -> None:+ global _progress_live+ if not sys.stderr.isatty() or total == 0:+ return+ width = 24+ fill = int(width * done / total)+ sys.stderr.write(f"\r building maps [{'█' * fill}{' ' * (width - fill)}] {done}/{total}")+ _progress_live = done < total+ if not _progress_live:+ sys.stderr.write("\r" + " " * 60 + "\r")+ sys.stderr.flush()+++class _LogHandler(logging.StreamHandler):+ """Writes log records to the terminal without tearing the progress bar."""++ def emit(self, record: logging.LogRecord) -> None:+ if _progress_live:+ self.stream.write("\r\x1b[2K") # the next progress tick redraws the bar+ super().emit(record)+++class _LogFormatter(logging.Formatter):+ """``agentplay: warning: message``; ``-v`` adds the logger name."""++ def formatMessage(self, record: logging.LogRecord) -> str: # noqa: N802 - logging API+ record.level = record.levelname.lower()+ return super().formatMessage(record)+++def _log_handler(stream: TextIO, *, verbose: bool) -> logging.Handler:+ handler = _LogHandler(stream)+ fmt = "agentplay: %(level)s: %(name)s: %(message)s" if verbose else "agentplay: %(level)s: %(message)s"+ handler.setFormatter(_LogFormatter(fmt))+ return handler+++def _configure_logging(verbose: bool) -> None:+ """Route every log record through one stderr handler owned by the CLI."""+ root = logging.getLogger()+ root.handlers[:] = [h for h in root.handlers if not isinstance(h, _LogHandler)]+ root.addHandler(_log_handler(sys.stderr, verbose=verbose))+ root.setLevel(logging.DEBUG if verbose else logging.WARNING)+++_SKIP_LABELS = {+ "no_conversation": "no conversation",+ "empty_or_unreadable": "empty or unreadable",+ "detection_failed": "unrecognized format",+ "empty_events": "no events",+ "empty_store_session": "no messages",+ "no_spans": "no messages",+ "too_large": "too large",+ "imported_not_continued": "imported",+}+++def _skip_breakdown(rep: pipeline.BuildReport) -> str:+ """`` (4 no conversation, 2 subagent)``, or nothing when no session was skipped."""+ if not rep.skip_reasons:+ return ""+ parts = ", ".join(+ f"{n} {_SKIP_LABELS.get(reason, reason.replace('_', ' '))}" for reason, n in rep.skip_reasons.most_common()+ )+ return f" ({parts})"+++def _agent_breakdown(rep: pipeline.BuildReport) -> str:+ """``claude-code 44 · codex 5 · 3 not built``: per-agent counts that add up to ``found``.++ ``by_agent`` counts only the sessions that were built or already fresh, so+ the sessions skipped or failed this run are shown as one remainder.+ """+ parts = [f"{a or 'unknown'} {n}" for a, n in rep.by_agent.most_common()]+ rest = rep.found - sum(rep.by_agent.values())+ if rest > 0:+ parts.append(f"{rest} not built")+ return " · ".join(parts) or "none"+++def cmd_build(args: argparse.Namespace, *, quiet: bool = False) -> pipeline.BuildReport:+ if getattr(args, "path_mode", None) == "hashed" and not os.environ.get("AGENTPLAY_HMAC_KEY"):+ print("agentplay: --path-mode hashed needs AGENTPLAY_HMAC_KEY; building with dirs_only instead.",+ file=sys.stderr)+ rep = pipeline.build_all(+ agents=_agents(args.agents),+ since=_since(args.since),+ rebuild=args.rebuild,+ path_mode=args.path_mode,+ limit=args.limit,+ titles=not args.no_titles,+ progress=_progress,+ )+ if getattr(args, "json", False) and not quiet:+ print(json.dumps({**rep.__dict__, "by_agent": dict(rep.by_agent)}, indent=2))+ return rep+ if quiet:+ # The caller owns the output: the viewer prints a one-liner when the+ # background scan lands.+ return rep+ print(f"Found {_b(str(rep.found))} sessions {_dim(_agent_breakdown(rep))}")+ failed = f", {rep.failed} failed" if rep.failed else ""+ print(f"Built {rep.built} new, {rep.unchanged} unchanged, {rep.skipped} skipped{_skip_breakdown(rep)}{failed} "+ f"in {rep.seconds}s. Nothing left this machine.")+ if rep.failed and args.verbose:+ for e in rep.errors[:20]:+ print(" " + _dim(e))+ if rep.found == 0:+ print("\nNo sessions found. Looked in: " + ", ".join(+ str(p) for ps in discover.Homes.default().__dict__.values() for p in ps))+ print("Set AGENTPLAY_CLAUDE_HOMES (or _CODEX_, _CURSOR_, ...) if your agent keeps them elsewhere.")+ return rep+++# --------------------------------------------------------------------------- view+def _background_scan(args: argparse.Namespace) -> None:+ """Scan for new sessions beside a running viewer.++ Failures are reported and dropped: a bad transcript must not take the viewer+ down with it, and everything already built stays servable.+ """+ try:+ rep = cmd_build(args, quiet=True)+ except Exception as exc: # noqa: BLE001 - the viewer outlives a failed scan+ print(_dim(f"Scan failed: {type(exc).__name__}: {exc}"), file=sys.stderr, flush=True)+ return+ built = f"{rep.built} new" if rep.built else "nothing new"+ skipped = f", {rep.skipped} skipped{_skip_breakdown(rep)}" if rep.skipped else ""+ print(_dim(f"Scan done: {built} of {rep.found} sessions{skipped} in {rep.seconds}s. Reload to see them."), flush=True)+++def cmd_view(args: argparse.Namespace) -> int:+ from .server import serve, viewer_root++ # Serve first, then scan in the background. A scan can take a long time+ # (decoding database-backed agents such as Cursor dominates it), and+ # everything already built is servable immediately; the index is re-read+ # as new maps land.+ httpd = serve(args.port)+ port = httpd.server_address[1]+ if args.port and port != args.port:+ print(f"Port {args.port} is busy; using {port} instead.", file=sys.stderr, flush=True)+ url = f"http://127.0.0.1:{port}/"+ if viewer_root() is None:+ print(_dim("The web viewer is not bundled in this install (source checkout?). The API is still up; "+ "run `make viewer` to build it."))+ # Flushed: stdout is block-buffered when it is not a tty, and "the viewer is+ # ready" is worthless to anything wrapping or piping us if it arrives at exit.+ print(f"Viewer → {_b(url)} {_dim('(Ctrl+C to stop)')}", flush=True)+ if not args.no_build:+ print(_dim("Scanning for new sessions in the background…"), flush=True)+ threading.Thread(target=_background_scan, args=(args,), daemon=True).start()+ if not args.no_open:+ threading.Timer(0.3, lambda: webbrowser.open(url)).start()+ try:+ httpd.serve_forever()+ except KeyboardInterrupt:+ print()+ finally:+ httpd.server_close()+ return 0+++# --------------------------------------------------------------------------- list+def cmd_list(args: argparse.Namespace) -> int:+ st = Store()+ rows = [r for r in st.rows() if r.get("role") not in ("subagent", "helper")][: args.limit or 30]+ if args.json:+ print(json.dumps(rows, indent=2))+ return 0+ if not rows:+ print("No maps yet. Run `agentplay build`.")+ return 0+ for r in rows:+ cost = f"${r.get('costUsd') or 0:.2f}"+ mins = (r.get("durationMs") or 0) / 60000+ title = (r.get("sessionTitle") or "")[:60]+ print(f"{(r.get('startedAt') or '')[:16].replace('T', ' ')} {r.get('agentTool', ''):<14} "+ f"{cost:>8} {mins:6.0f}m {r.get('calls', 0):5} calls {r.get('errors', 0):3} err {title}")+ print(" " + _dim(r["sessionId"]))+ return 0+++# --------------------------------------------------------------------------- export / agents+def cmd_export(args: argparse.Namespace) -> int:+ st = Store()+ sid = args.session+ if sid not in st.index:+ matches = [k for k in st.index if k.endswith(sid) or sid in k]+ if len(matches) != 1:+ print(f"agentplay: {'no' if not matches else 'several'} sessions match {sid!r}.", file=sys.stderr)+ return 2+ sid = matches[0]+ doc = st.get(sid)+ if doc is None:+ print("agentplay: map file missing; run `agentplay build --rebuild`.", file=sys.stderr)+ return 1+ body = json.dumps(doc, sort_keys=True, separators=(",", ":")).encode("utf-8")+ out = Path(args.output or f"{re.sub(r'[^A-Za-z0-9._-]+', '_', sid)}.json.gz")+ out.write_bytes(gzip.compress(body) if out.suffix == ".gz" else body)+ labels = (r.get("remote") or r.get("name") for r in doc.get("repos", []))+ repos = ", ".join(label for label in labels if label) or "none"+ mode = doc["session"].get("pathMode")+ hint = "" if mode in ("dirs_only", "hashed") else " Rebuild with --path-mode dirs_only to hide file names."+ print(f"Wrote {out} ({out.stat().st_size // 1024} KB). It contains no prompt or output text, but it does "+ f"contain repo names ({repos}) and {len(doc.get('files', []))} file paths "+ f"(path mode: {mode}).{hint}")+ return 0+++def cmd_import(args: argparse.Namespace) -> int:+ from . import builder++ st = Store()+ n = 0+ for raw in args.files:+ path = Path(raw)+ try:+ data = path.read_bytes()+ doc = json.loads(gzip.decompress(data) if data[:2] == b"\x1f\x8b" else data)+ except (OSError, ValueError) as exc:+ print(f"agentplay: can't read {path}: {exc}", file=sys.stderr)+ return 1+ if not isinstance(doc, dict) or doc.get("schema") not in (builder.SCHEMA, builder.LEGACY_SCHEMA):+ print(f"agentplay: {path} is not a agentplay/v1 document", file=sys.stderr)+ return 1+ sid = str(doc.get("session", {}).get("id") or "")+ if not sid or not doc.get("session", {}).get("startedAt"):+ print(f"agentplay: {path} has no session.id / session.startedAt", file=sys.stderr)+ return 1+ started = doc["session"]["startedAt"]+ st.put(doc, {**builder.summary(doc), "sessionId": sid, "sessionDate": started[:10],+ "sessionTitle": args.title or None, "contentHash": builder.content_hash(doc),+ "imported": str(path)})+ n += 1+ st.save_index()+ print(f"Imported {n} map(s).")+ return 0+++def cmd_agents(_args: argparse.Namespace) -> int:+ homes = discover.Homes.default()+ present = homes.present()+ for agent in discover.AGENTS:+ paths = present.get(agent)+ mark = "●" if paths else "○"+ print(f" {mark} {agent:<15} {', '.join(map(str, paths)) if paths else _dim('not found')}")+ return 0+++# --------------------------------------------------------------------------- parser+def _build_flags(p: argparse.ArgumentParser) -> None:+ p.add_argument("--since", help="only sessions changed since (30d, 12h, 2w, YYYY-MM-DD)")+ p.add_argument("--agents", help=f"comma-separated subset of: {', '.join(discover.AGENTS)}")+ p.add_argument("--rebuild", action="store_true", help="rebuild every selected map")+ p.add_argument("--path-mode", default="relative", choices=["relative", "dirs_only", "hashed"],+ help="how file paths are recorded in maps (default: relative)")+ p.add_argument("--limit", type=int, help="newest N sessions only")+ p.add_argument("--no-titles", action="store_true", help="don't keep local session titles in the index")+++def parser() -> argparse.ArgumentParser:+ ap = argparse.ArgumentParser(+ prog="agentplay",+ description="Replay your coding-agent sessions as a map and a timeline. Local only.",+ )+ ap.add_argument("--version", action="version", version=f"agentplay {__version__}")+ ap.add_argument("-v", "--verbose", action="store_true")+ # Also accepted after the subcommand. SUPPRESS leaves the top-level value alone+ # when it isn't repeated there.+ common = argparse.ArgumentParser(add_help=False)+ common.add_argument("-v", "--verbose", action="store_true", default=argparse.SUPPRESS)+ sub = ap.add_subparsers(dest="cmd")++ v = sub.add_parser("view", parents=[common], help="build maps and open the viewer (default)")+ _build_flags(v)+ v.add_argument("--port", type=int, default=7317)+ v.add_argument("--no-open", action="store_true", help="don't open a browser")+ v.add_argument("--no-build", action="store_true", help="serve what's already built")+ v.set_defaults(fn=cmd_view)++ b = sub.add_parser("build", parents=[common], help="build maps for new or changed sessions")+ _build_flags(b)+ b.add_argument("--json", action="store_true")+ b.set_defaults(fn=cmd_build)++ ls = sub.add_parser("list", parents=[common], help="list built sessions")+ ls.add_argument("--limit", type=int)+ ls.add_argument("--json", action="store_true")+ ls.set_defaults(fn=cmd_list)++ e = sub.add_parser("export", parents=[common], help="write one session's map to a file you can share or open elsewhere")+ e.add_argument("session", help="session id (or a unique suffix of one)")+ e.add_argument("-o", "--output", help="output path (.json or .json.gz)")+ e.set_defaults(fn=cmd_export)++ im = sub.add_parser("import", parents=[common], help="add map files (someone else's, or another machine's) to your local store")+ im.add_argument("files", nargs="+", help=".json or .json.gz map files")+ im.add_argument("--title", help="title to show in the session list")+ im.set_defaults(fn=cmd_import)++ a = sub.add_parser("agents", parents=[common], help="show which agents were found on this machine")+ a.set_defaults(fn=cmd_agents)+ return ap+++def _utf8_stdio() -> None:+ """Write UTF-8 to a pipe or file, whatever the locale says.++ On Windows a redirected stream falls back to the ANSI code page (cp1252),+ which cannot encode the marks we print (`●`, `→`) or a session title in most+ scripts, so `agentplay agents | ...` and any agent running us crashed. A+ console is left alone: it already takes Unicode.+ """+ for stream in (sys.stdout, sys.stderr):+ encoding = (getattr(stream, "encoding", None) or "").lower().replace("-", "")+ if encoding != "utf8" and hasattr(stream, "reconfigure"):+ try:+ stream.reconfigure(encoding="utf-8", errors="replace")+ except (ValueError, OSError):+ pass+++def main(argv: list[str] | None = None) -> int:+ ap = parser()+ args = ap.parse_args(argv)+ _utf8_stdio()+ _configure_logging(args.verbose)+ if not sys.warnoptions:+ # Python's advice for applications: warnings (from dependencies, or from+ # parsing a transcript's own code) are not the user's to act on.+ # `-W` or PYTHONWARNINGS still opts back in.+ warnings.simplefilter("ignore")+ if not getattr(args, "fn", None):+ args = ap.parse_args(["view", *(argv or sys.argv[1:])])+ try:+ rv = args.fn(args)+ except KeyboardInterrupt:+ return 130+ return 0 if rv is None or isinstance(rv, pipeline.BuildReport) else int(rv)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/python/src/agentplay/discover.py b/python/src/agentplay/discover.pynew file mode 100644index 0000000..d7cf7b3--- /dev/null+++ b/python/src/agentplay/discover.py@@ -0,0 +1,398 @@+"""Find coding-agent sessions on this machine and build maps for them.++Supported agents and where each keeps its sessions by default:++================= ===================================================== ===========+agent default location read as+================= ===================================================== ===========+Claude Code ``~/.claude/projects/**/*.jsonl`` (+ ``subagents/``) file+Codex ``~/.codex/sessions/**/*.jsonl`` file+Copilot CLI ``~/.copilot/session-state/**`` file+Copilot VS Code VS Code ``User/workspaceStorage/*/chatSessions`` file+Cursor ``~/.cursor`` agent transcripts, ``chats/*/store.db``, decoded+ IDE ``state.vscdb``+OpenCode ``~/.local/share/opencode/opencode.db`` decoded+Kiro ``~/.kiro/sessions`` decoded+================= ===================================================== ===========++"Decoded" agents keep sessions in a database; :mod:`agentplay.materialize`+turns each one into an NDJSON transcript under ``~/.agentplay/cache`` first.++Every location can be overridden with a comma-separated environment variable,+``AGENTPLAY_<AGENT>_HOMES`` (for example ``AGENTPLAY_CLAUDE_HOMES`` for a WSL+``/mnt/c/Users/<you>/.claude``).+"""++from __future__ import annotations++import json+import logging+import os+import re+import sys+from collections.abc import Iterable+from dataclasses import dataclass+from datetime import UTC, datetime+from itertools import islice+from pathlib import Path+from typing import Any++from . import builder, materialize+from ._util import captured++logger = logging.getLogger("agentplay.discover")++AGENTS = ("claude-code", "codex", "cursor", "copilot", "copilot-vscode", "opencode", "kiro")++# Transcripts above this size are skipped rather than parsed (a 20k-event map cap+# applies anyway; this keeps one pathological file from stalling a run).+MAX_SOURCE_BYTES = 512 * 1024 * 1024+++def _homes_from_env(var: str, defaults: Iterable[str | Path]) -> list[Path]:+ raw = os.environ.get(var, "").strip()+ if raw:+ return [Path(os.path.expanduser(p.strip())) for p in raw.split(",") if p.strip()]+ return [Path(os.path.expanduser(str(d))) for d in defaults]+++def _vscode_user_dirs() -> list[Path]:+ home = Path.home()+ if sys.platform == "darwin":+ base = home / "Library" / "Application Support"+ elif sys.platform == "win32":+ base = Path(os.environ.get("APPDATA") or home / "AppData" / "Roaming")+ else:+ base = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")+ return [base / app / "User" for app in ("Code", "Code - Insiders", "VSCodium")]+++def _opencode_data_dirs() -> list[Path]:+ xdg = os.environ.get("XDG_DATA_HOME")+ base = Path(xdg) if xdg else Path.home() / ".local" / "share"+ return [base / "opencode"]+++@dataclass(frozen=True)+class Homes:+ """Resolved agent home directories (the raw agent stores, before decoding)."""++ claude_code: list[Path]+ codex: list[Path]+ cursor: list[Path]+ copilot: list[Path]+ copilot_vscode: list[Path]+ opencode: list[Path]+ kiro: list[Path]++ @classmethod+ def default(cls) -> Homes:+ copilot_default = os.environ.get("COPILOT_HOME", "").strip() or "~/.copilot"+ return cls(+ claude_code=_homes_from_env("AGENTPLAY_CLAUDE_HOMES", ["~/.claude"]),+ codex=_homes_from_env("AGENTPLAY_CODEX_HOMES", ["~/.codex"]),+ cursor=_homes_from_env("AGENTPLAY_CURSOR_HOMES", ["~/.cursor"]),+ copilot=_homes_from_env("AGENTPLAY_COPILOT_HOMES", [copilot_default]),+ copilot_vscode=_homes_from_env("AGENTPLAY_COPILOT_VSCODE_HOMES", _vscode_user_dirs()),+ opencode=_homes_from_env("AGENTPLAY_OPENCODE_HOMES", _opencode_data_dirs()),+ kiro=_homes_from_env("AGENTPLAY_KIRO_HOMES", ["~/.kiro"]),+ )++ def present(self) -> dict[str, list[Path]]:+ """Only the homes that exist on this machine, by agent name."""+ out: dict[str, list[Path]] = {}+ for agent, paths in (+ ("claude-code", self.claude_code),+ ("codex", self.codex),+ ("cursor", self.cursor),+ ("copilot", self.copilot),+ ("copilot-vscode", self.copilot_vscode),+ ("opencode", self.opencode),+ ("kiro", self.kiro),+ ):+ found = [p for p in paths if p.is_dir()]+ if found:+ out[agent] = found+ return out+++def materialize_all(homes: Homes, agents: set[str]) -> dict[str, int]:+ """Decode database-backed agents into the local NDJSON cache.++ Args:+ homes: resolved agent homes.+ agents: agent names to include.++ Returns:+ Sessions decoded per agent. Failures are logged and counted as zero:+ one unreadable store never stops the run.+ """+ counts: dict[str, int] = {}+ kinds = materialize.AgentKind+ jobs: list[tuple[str, Any]] = []+ if "opencode" in agents:+ for h in homes.opencode:+ if h.is_dir():+ jobs.append(("opencode", lambda h=h: materialize.find_opencode_candidates(+ materialize.HomeSpec(kind=kinds.OPENCODE, path=h))))+ if "kiro" in agents:+ for h in homes.kiro:+ if h.is_dir():+ jobs.append(("kiro", lambda h=h: materialize.find_kiro_candidates(+ materialize.HomeSpec(kind=kinds.KIRO, path=h))))+ if "cursor" in agents:+ for h in homes.cursor:+ if h.is_dir():+ jobs.append(("cursor", lambda h=h: materialize.find_cursor_store_candidates(+ materialize.HomeSpec(kind=kinds.CURSOR, path=h))))+ if materialize._default_state_db_path().is_file(): # noqa: SLF001+ jobs.append(("cursor", materialize.find_cursor_composer_candidates))+ for agent, job in jobs:+ n = 0+ try:+ for _ in job():+ n += 1+ except Exception as exc: # noqa: BLE001 - decoding is best-effort per store+ logger.warning("could not decode %s sessions: %s", agent, exc)+ counts[agent] = counts.get(agent, 0) + n+ return counts+++def _cache_dirs(agent: str) -> list[Path]:+ root = materialize.cache_root()+ if agent == "opencode":+ return [p for p in (root / "opencode").glob("*") if p.is_dir()]+ if agent == "kiro":+ return [p for p in (root / "kiro").glob("*") if p.is_dir()]+ if agent == "cursor":+ return [p for p in (root / "cursor-store").glob("*") if p.is_dir()] + [+ p for p in (root / "cursor-composer").glob("*") if p.is_dir()+ ]+ return []+++def local_source(homes: Homes, agents: set[str]) -> Any:+ """The shared multi-agent parser over every present home plus the decoded cache."""+ from ._core.ingestion.coding_agent._sources.local.source import LocalSource++ def pick(agent: str, raw: list[Path]) -> list[Path]:+ if agent not in agents:+ return []+ return [p for p in raw if p.is_dir()]++ return LocalSource(+ claude_code_homes=pick("claude-code", homes.claude_code),+ codex_homes=pick("codex", homes.codex),+ opencode_homes=pick("opencode", _cache_dirs("opencode")),+ cursor_store_homes=pick("cursor", homes.cursor + _cache_dirs("cursor")),+ kiro_homes=pick("kiro", _cache_dirs("kiro")),+ copilot_homes=pick("copilot", homes.copilot),+ copilot_vscode_homes=pick("copilot-vscode", homes.copilot_vscode),+ )+++@dataclass+class Candidate:+ """One session found on disk."""++ session_id: str+ agent: str+ path: str+ mtime: float+++def _agent_name(raw: Any) -> str:+ name = str(getattr(raw, "value", raw) or "")+ return {"claude_code": "claude-code", "copilot_vscode": "copilot-vscode"}.get(name, name)+++def candidates(source: Any, *, since: datetime | None = None) -> list[Candidate]:+ """Every session the parser can see, newest first.++ Args:+ source: a ``LocalSource`` from :func:`local_source`.+ since: only sessions whose transcript changed at or after this time.+ """+ index = source._build_index() # noqa: SLF001 - the only path -> session id map+ out: list[Candidate] = []+ floor = since.timestamp() if since else None+ for sid, ref in index.items():+ with captured():+ mtime = ref.mtime.timestamp() if isinstance(ref.mtime, datetime) else float(ref.mtime or 0)+ if floor is not None and mtime < floor:+ continue+ out.append(Candidate(sid, _agent_name(ref.agent), str(ref.path), mtime))+ out.sort(key=lambda c: c.mtime, reverse=True)+ return out+++def source_bytes(c: Candidate) -> int:+ """On-disk size of a session's transcript plus Claude Code subagent files."""+ total = 0+ with captured():+ p = Path(c.path)+ if p.is_file():+ total += p.stat().st_size+ sub = p.with_suffix("") / "subagents"+ if sub.is_dir():+ total += sum(f.stat().st_size for f in sub.glob("agent-*.jsonl"))+ return total+++class SkipSession(Exception):+ """A session that cannot or should not be mapped (too large, empty)."""+++def build_map(c: Candidate, source: Any, *, path_mode: str = "relative",+ hmac_key: bytes | None = None, version: str = "") -> dict[str, Any]:+ """Build the ``agentplay/v1`` document for one candidate.++ Claude Code is read straight from its JSONL (the only way to see subagent+ tool calls and per-request tokens). Every other agent goes through the+ shared parser's spans.++ Raises:+ SkipSession: the transcript is too large or has no parseable spans.+ """+ if source_bytes(c) > MAX_SOURCE_BYTES:+ raise SkipSession("too_large")+ if c.agent == "claude-code" and c.path.endswith(".jsonl"):+ return builder.build_claude_code_map(+ Path(c.path), path_mode=path_mode, hmac_key=hmac_key, cli_version=version+ )+ spans = source.get_spans_by_session(c.session_id)+ if not spans:+ raise SkipSession("no_spans")+ return builder.build_map_from_spans(+ spans,+ session_id=c.session_id,+ agent_tool=c.agent or "unknown",+ path_mode=path_mode,+ hmac_key=hmac_key,+ cli_version=version,+ started_at_hint=c.mtime or None,+ )+++# --------------------------------------------------------------------- titles+_TITLE_MAX = 90+# Task labels sit in a narrow sidebar column, so they get less room than a title.+_TASK_TITLE_MAX = 60++# Blocks the harness wraps around a turn. They often *prefix* a real prompt, so+# dropping the whole turn on sight of a leading "<" throws the prompt away with+# them: a worktree `<system-reminder>` would hide "set up the staging deploy+# script" entirely.+_HARNESS_TAGS = (+ "system-reminder", "task-notification", "ci-monitor-event",+ "local-command-caveat", "local-command-stdout", "local-command-stderr",+ "command-name", "command-message", "command-args",+ "user-prompt-submit-hook",+)+_HARNESS_BLOCK_RE = re.compile(+ r"<(" + "|".join(_HARNESS_TAGS) + r")\b[^>]*>.*?</\1>|<(" + "|".join(_HARNESS_TAGS) + r")\b[^>]*/?>",+ re.S | re.I,+)+# A whole turn the harness wrote on the user's behalf: no prompt in it at all.+_HARNESS_MARKER_RE = re.compile(r"^\[Request interrupted by user[^\]]*\]$", re.I)+# Attachment placeholders sit in front of real prose ("[Image #1] yesterday is ...").+_ATTACHMENT_RE = re.compile(r"^(?:\[(?:Image|Pasted text|Attachment)[^\]]*\]\s*)+", re.I)+++def _clean_title(text: str, limit: int = _TITLE_MAX) -> str | None:+ text = _HARNESS_BLOCK_RE.sub(" ", str(text))+ text = " ".join(text.split())+ text = _ATTACHMENT_RE.sub("", text).strip()+ if not text or _HARNESS_MARKER_RE.match(text) or text.startswith("<") or text.startswith("Caveat:"):+ return None+ return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"+++def local_title(c: Candidate, source: Any | None = None) -> str | None:+ """A human title for the local session list: Claude Code's own ``ai-title`` /+ ``summary`` record when present, else the first real user prompt.++ Titles live only in the local index on this machine. They are never written+ into a map document, which stays free of prompt text by contract.+ """+ with captured():+ if c.agent == "claude-code" and c.path.endswith(".jsonl"):+ first_prompt = None+ with open(c.path, encoding="utf-8", errors="replace") as fh:+ for i, line in enumerate(fh):+ if i > 4000:+ break+ try:+ rec = json.loads(line)+ except ValueError:+ continue+ if not isinstance(rec, dict):+ continue+ kind = rec.get("type")+ if kind in ("ai-title", "summary"):+ t = _clean_title(rec.get("title") or rec.get("summary") or "")+ if t:+ return t+ if first_prompt is None and kind == "user" and not rec.get("isMeta"):+ msg = rec.get("message") or {}+ content = msg.get("content")+ if isinstance(content, list):+ content = " ".join(+ b["text"] for b in content+ if isinstance(b, dict) and b.get("type") == "text"+ and isinstance(b.get("text"), str)+ )+ if isinstance(content, str):+ first_prompt = _clean_title(content)+ return first_prompt+ if source is not None:+ for s in source.get_spans_by_session(c.session_id):+ if s.name.startswith("Turn "):+ t = _clean_title(s.attributes.get("input.value") or "")+ if t:+ return t+ return None+++def local_task_titles(c: Candidate, source: Any | None = None) -> list[str | None] | None:+ """One short label per user turn, for the task list, in turn order.++ A task window starts at a user turn, so the turn's own prompt is the only+ thing on the machine that says what the task was. Without this every task+ renders as "Task 3", which is why the task list cannot be used to pick what+ to review.++ Same contract as :func:`local_title`, and the same ``--no-titles`` switch:+ these live only in the local index on this machine and are merged into a map+ when it is *served*, never when it is built or exported. A map document on+ disk stays free of prompt text, so ``agentplay export`` is unaffected.++ The list is positional: a task is labelled by its ``firstTurn``, which counts+ the ``user`` events the builder emitted. So this walks records with the+ builder's own predicate (:func:`builder.user_turn_text`) and appends one+ entry per *emitted* turn — never for an interruption or a harness-only+ record, each of which would otherwise shift every later label by one. An+ entry may still be ``None`` when the prompt cleans down to nothing; that+ leaves the task unlabelled without moving its neighbours.+ """+ with captured():+ if c.agent == "claude-code" and c.path.endswith(".jsonl"):+ with open(c.path, encoding="utf-8", errors="replace") as fh:+ turns = builder.user_turns(islice(fh, 4001))+ return [_clean_title(text, _TASK_TITLE_MAX) for _, _, text in turns] or None+ if source is not None:+ # `build_map_from_spans` emits a user event only for a turn that carries+ # a prompt, so a turn without one takes no slot here either.+ prompts = [+ s.attributes.get("input.value")+ for s in source.get_spans_by_session(c.session_id)+ if s.name.startswith("Turn ")+ ]+ prompts = [p for p in prompts if p]+ if prompts:+ return [_clean_title(str(p), _TASK_TITLE_MAX) for p in prompts]+ return None+++def now_utc() -> datetime:+ return datetime.now(UTC)diff --git a/python/src/agentplay/hook_detail.py b/python/src/agentplay/hook_detail.pynew file mode 100644index 0000000..78c0645--- /dev/null+++ b/python/src/agentplay/hook_detail.py@@ -0,0 +1,115 @@+"""Hook failure details, read on demand and never persisted.++A map records that a hook failed (which hook, whether it blocked, the tool call+that triggered it) but never what it said or ran: both are free text. To show+them the local server opens the original transcript when the viewer asks and+returns the message and command of that one record. Nothing here writes to a+map, the index, an export or disk: the scan below caches *line numbers* (never+text), and a read re-parses that single line.++A record is addressed by the opaque ``srcUuid`` the builder stored on the error+event; the session's subagent transcripts are searched too, as the builder reads them. Callers (the server) decide who may ask. This module trusts the path it+is given.+"""++from __future__ import annotations++import functools+import itertools+import json+import os+from pathlib import Path+from typing import Any++from .prompt_images import Unavailable++MAX_CHARS = 4000+"""Longest message or command returned, in characters."""++_HOOK_ERRORS = ("hook_blocking_error", "hook_non_blocking_error")++def _not_found() -> Unavailable:+ return Unavailable(404, "not_found", "We couldn't find that hook failure.")++def _gone() -> Unavailable:+ return Unavailable(410, "gone", "The transcript for this session is no longer on this machine.")++def _stat(path: str) -> os.stat_result:+ try:+ return os.stat(path)+ except FileNotFoundError:+ raise _gone() from None++def _hook_attachment(rec: Any) -> dict[str, Any] | None:+ att = rec.get("attachment") if isinstance(rec, dict) else None+ if isinstance(att, dict) and att.get("type") in _HOOK_ERRORS:+ return att+ return None+[email protected]_cache(maxsize=64)+def _scan(path: str, mtime_ns: int, size: int) -> dict[str, int]:+ """Line number of every hook error record, by uuid. Holds no text.++ ``mtime_ns`` and ``size`` are only the cache key: a transcript that grows+ gets a fresh scan.+ """+ lines: dict[str, int] = {}+ with open(path, encoding="utf-8", errors="replace") as fh:+ for n, line in enumerate(fh):+ if "hook_" not in line: # cheap filter before parsing+ continue+ try:+ rec = json.loads(line)+ except ValueError:+ continue+ if _hook_attachment(rec) is not None and isinstance(rec.get("uuid"), str):+ lines.setdefault(rec["uuid"], n)+ return lines++def _text(value: Any) -> str | None:+ return value[:MAX_CHARS] if isinstance(value, str) and value else None++def _transcripts(path: str) -> list[str]:+ """The session transcript, then its subagents' (``<session>/subagents/agent-*.jsonl``)."""+ return [path, *sorted(str(f) for f in (Path(path).with_suffix("") / "subagents").glob("agent-*.jsonl"))]++def _load(path: str, line_no: int, uuid: str) -> dict[str, Any] | None:+ """The hook attachment on one line, or None if the file changed under us."""+ try:+ with open(path, encoding="utf-8", errors="replace") as fh:+ rec = json.loads(next(itertools.islice(fh, line_no, None), ""))+ except (OSError, ValueError):+ return None+ # The file may have changed since the scan; trust nothing the cached line says.+ return _hook_attachment(rec) if isinstance(rec, dict) and rec.get("uuid") == uuid else None++def read_hook_detail(path: str, uuid: str) -> tuple[str | None, str | None]:+ """The message and command of one hook failure in the transcript.++ Args:+ path: the transcript ``.jsonl``.+ uuid: the ``srcUuid`` of the map's error event.++ Returns:+ ``(message, command)``, each capped at ``MAX_CHARS`` and ``None`` when the+ record has none. A blocking hook's message is its ``blockingError``; a+ non-blocking one's is its stderr, or stdout when stderr is empty.++ Raises:+ Unavailable: 410 if the transcript is gone; 404 if no hook error record+ has that uuid.+ """+ _stat(path)+ for f in _transcripts(path):+ try:+ st = os.stat(f)+ line_no = _scan(f, st.st_mtime_ns, st.st_size).get(uuid)+ except OSError:+ continue+ att = None if line_no is None else _load(f, line_no, uuid)+ if att is not None:+ be = att.get("blockingError")+ if isinstance(be, dict):+ return _text(be.get("blockingError")), _text(be.get("command"))+ return _text(att.get("stderr")) or _text(att.get("stdout")), _text(att.get("command"))+ raise _not_found()diff --git a/python/src/agentplay/materialize.py b/python/src/agentplay/materialize.pynew file mode 100644index 0000000..13cd9a4--- /dev/null+++ b/python/src/agentplay/materialize.py@@ -0,0 +1,1525 @@+"""Decode agents that keep sessions in a database into NDJSON transcripts.++OpenCode (``opencode.db``), Cursor CLI/agent (``store.db``), Cursor IDE composer+chats (``state.vscdb``) and Kiro (session directories) do not write one plain+file per session. Each ``find_*_candidates`` generator below decodes those stores+and writes one NDJSON transcript per session into a local cache under+``~/.agentplay/cache/<agent>/``, which the parsers in ``agentplay._core`` then+read like any other transcript. Consuming the generator performs the writes.++Everything here is read-only against the agent's own files: SQLite stores are+opened ``mode=ro&immutable=1`` or copied to a temp dir first. Nothing here makes+a network call.+"""++from __future__ import annotations++import contextlib+import hashlib+import json+import logging+import os+import shutil+import sqlite3+import sys+import tempfile+import time+from collections.abc import Iterator+from dataclasses import dataclass, field+from datetime import UTC, datetime+from enum import StrEnum+from pathlib import Path++from . import store++logger = logging.getLogger("agentplay.materialize")++_warned: set[str] = set()+++def _warn_once(key: str, message: str, *args: object) -> None:+ """Log ``message`` at WARNING the first time ``key`` is seen in this process.++ A transcript source that cannot be read hides every session in it, so the user+ should hear about it once, not once per session or per rescan.+ """+ if key not in _warned:+ _warned.add(key)+ logger.warning(message, *args)+++def _warn_unreadable_db(agent: str, db_path: Path, exc: Exception) -> None:+ """One WARNING per broken ``agent`` database; the path is shown home-relative."""+ try:+ shown = "~/" + db_path.relative_to(Path.home()).as_posix()+ except ValueError:+ shown = db_path.name+ reason = exc.strerror if isinstance(exc, OSError) and exc.strerror else exc+ _warn_once(+ f"{agent}:{db_path}",+ "%s: cannot read %s (%s); its sessions are skipped",+ agent,+ shown,+ reason,+ )+++def cache_root() -> Path:+ """Where decoded transcripts are cached, resolved at call time.++ Resolved per call rather than at import, so ``AGENTPLAY_HOME`` set after this+ module is imported (a test fixture, an embedding process) is still honoured.+ """+ return store.root() / "cache"+++class AgentKind(StrEnum):+ CLAUDE_CODE = "claude-code"+ CODEX = "codex"+ OPENCODE = "opencode"+ CURSOR = "cursor"+ KIRO = "kiro"+ COPILOT = "copilot"+++@dataclass(frozen=True)+class HomeSpec:+ """One agent home directory to read from."""++ kind: AgentKind+ path: Path++ @property+ def label(self) -> str:+ """Cache sub-directory for this home: its name, plus a short digest when+ the home is not directly under ``$HOME`` so two homes never collide."""+ name = self.path.name or self.path.anchor.strip("/") or "root"+ parent = self.path.parent+ try:+ home = Path.home()+ if parent == home or parent == home.resolve():+ return name+ except (OSError, RuntimeError):+ pass+ digest = hashlib.blake2s(str(parent).encode("utf-8"), digest_size=3).hexdigest()+ return f"{name}-{digest}"+++@dataclass+class Session:+ """A materialized session file."""++ agent: AgentKind+ home_label: str+ abs_path: Path+ rel_path: Path+ size_bytes: int+ mtime: datetime+ turns: int = 0+ cwd: Path | None = None+ secret_findings: list = field(default_factory=list)+++def _default_state_db_path() -> Path:+ """Cursor's global ``state.vscdb`` for the current OS."""+ home = Path.home()+ if sys.platform == "darwin":+ base = home / "Library" / "Application Support"+ elif sys.platform == "win32":+ base = Path(os.environ.get("APPDATA") or home / "AppData" / "Roaming")+ else:+ base = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")+ return base / "Cursor" / "User" / "globalStorage" / "state.vscdb"+++#+# opencode (sst/opencode, v1.17+) stores everything in a single SQLite db at+# ``<data-dir>/opencode.db`` — no per-session file. A session is one ``session`` row (which+# carries ``directory`` = cwd) plus rows in ``message`` / ``part``. To ride the same file-based+# pipeline as Claude Code / Codex, we synthesize one NDJSON transcript per session (one line per+# message, its parts merged in) and materialize it under this cache root; the rest of the pipeline+# (secret + PII scrub, manifest, dedup) then treats it like any other transcript file.++def opencode_cache_root() -> Path:+ return cache_root() / "opencode"+++def _opencode_db(home: Path) -> Path | None:+ """The opencode SQLite db under ``home`` (``opencode.db``, or an ``opencode-<channel>.db``)."""+ db = home / "opencode.db"+ if db.is_file():+ return db+ others = sorted(home.glob("opencode*.db"))+ return others[0] if others else None+++def _sqlite_ro_uri(db: Path) -> str:+ """Read-only, immutable SQLite URI. Percent-encode the path so a home dir containing+ ``?`` or ``#`` (URI delimiters) doesn't make SQLite open the wrong file."""+ from urllib.parse import quote++ return f"file:{quote(str(db))}?mode=ro&immutable=1"+++def _safe_component(value: object, fallback: str) -> str:+ """A single, filesystem-safe path component: no separators or ``.``/``..`` traversal, so an+ absolute or dotted opencode id can't escape the cache root when joined with ``/``."""+ text = str(value or fallback)+ for sep in ("/", "\\", "\x00"):+ text = text.replace(sep, "_")+ return text.strip(". ") or fallback+++def _opencode_json(raw: str) -> dict:+ # TypeError guards a SQL NULL data column (json.loads(None) raises TypeError, not ValueError).+ try:+ obj = json.loads(raw)+ return obj if isinstance(obj, dict) else {"value": obj}+ except (json.JSONDecodeError, TypeError, ValueError):+ return {}+++def _opencode_synthesize(con: sqlite3.Connection, session_id: str) -> bytes:+ """One NDJSON line per message (parts merged), ordered by creation time. b'' if empty."""+ lines: list[str] = []+ messages = con.execute(+ "SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id",+ (session_id,),+ ).fetchall()+ for msg_id, msg_data in messages:+ parts = con.execute(+ "SELECT data FROM part WHERE message_id = ? ORDER BY time_created, id",+ (msg_id,),+ ).fetchall()+ record = {+ "id": msg_id,+ "sessionID": session_id,+ "message": _opencode_json(msg_data),+ "parts": [_opencode_json(p[0]) for p in parts],+ }+ lines.append(json.dumps(record, separators=(",", ":")))+ return ("\n".join(lines) + "\n").encode() if lines else b""+++def _pin_cache_mtime(path: Path, epoch_ms: float) -> bool:+ """Set a materialized cache file's mtime, and CONFIRM it took.++ Other readers use this file's filesystem mtime as the session's timestamp, so a+ failed pin is not cosmetic: the file keeps the moment it was written, the+ session re-qualifies for the look-back window, and the unchanged-content guard+ then prevents any later run from correcting it.++ The result is checked rather than assumed because some filesystems accept+ `utime` and quietly ignore it — a silent no-op would look identical to+ success and reintroduce the bug it exists to prevent.++ Args:+ path: The materialized cache file.+ epoch_ms: Target modification time, epoch milliseconds.++ Returns:+ True when the file's mtime now matches the target within a second.+ False on any failure, so the caller can report it instead of skipping+ the next write for a file whose timestamp is wrong.+ """+ try:+ when = float(epoch_ms) / 1000+ # `< 0`, not `<= 0`. Epoch zero is a real — if bizarre — modification+ # time, and the RESTORE path can legitimately carry it; rejecting it+ # would leave that file with its write time, which is the one outcome+ # this helper exists to prevent. "No timestamp at all" is the caller's+ # question, and every caller already tests it before calling.+ if when < 0:+ return False+ # Upper bound too: the timestamps come from a hand-rolled protobuf walk+ # of a possibly hot/corrupt db, and `os.utime` happily ACCEPTS an+ # insane value (year 316-million). Once pinned, the file's real mtime+ # is insane as well, and the discovery loop's `st.st_mtime` fallback,+ # the guard for exactly this corruption, would raise instead of+ # saving the session. A year of clock skew is the generous ceiling;+ # beyond it the value is corruption, not a date, and the caller's+ # warning path is the right outcome.+ if when > time.time() + 365 * 86400:+ return False+ os.utime(path, (when, when))+ return abs(path.stat().st_mtime - when) <= 1+ except (OSError, OverflowError, TypeError, ValueError):+ return False+++def find_opencode_candidates(+ home: HomeSpec, *, cache_root: Path | None = None+) -> Iterator[Session]:+ """Yield a Session per opencode session, materializing each into an NDJSON transcript.++ ``home.path`` is the opencode data dir (holds ``opencode.db``). Each session is synthesized+ to ``<cache_root>/<home_label>/<project_id>/<session_id>.jsonl`` and that file becomes the+ Session's ``abs_path`` - so scanning, redaction, and dedup are all unchanged.+ """+ db = _opencode_db(home.path)+ if db is None:+ logger.debug("Skipping %s (no opencode db)", home.path)+ return+ root = (cache_root or opencode_cache_root()) / home.label+ try:+ con = sqlite3.connect(_sqlite_ro_uri(db), uri=True)+ except sqlite3.Error as exc:+ _warn_unreadable_db("opencode", db, exc)+ return+ try:+ con.row_factory = sqlite3.Row+ try:+ rows = con.execute(+ "SELECT id, project_id, directory, time_updated FROM session"+ ).fetchall()+ except sqlite3.Error as exc:+ _warn_unreadable_db("opencode", db, exc)+ return+ for s in rows:+ # A schema mismatch (missing message/part table) raises sqlite3.Error mid-generator;+ # contain it per-session so one bad db doesn't abort the whole run.+ try:+ data = _opencode_synthesize(con, s["id"])+ except sqlite3.Error as exc:+ logger.debug("opencode synthesize failed for session %s: %s", s["id"], exc)+ continue+ if not data:+ continue+ # Sanitize both components: an absolute or ``..``-laden project_id/session id would+ # otherwise let ``root / rel`` write outside the cache (Path drops the left side on an+ # absolute right side).+ rel = Path(_safe_component(s["project_id"], "unknown")) / (+ f"{_safe_component(s['id'], 'session')}.jsonl"+ )+ abs_path = root / rel+ # Same contract as the Cursor composer cache: other readers use+ # these files' mtimes as the session's timestamp, so a file is only+ # rewritten when its bytes change. An unconditional rewrite would+ # stamp every OpenCode session "now" and re-qualify all of them for+ # the look-back window on every run.+ updated_ms = s["time_updated"] or 0+ # Same contract as the composer materializer: an undatable session+ # must keep the timestamp it already had rather than gaining the+ # write time, which would re-qualify it for the look-back window.+ try:+ prior_mtime = abs_path.stat().st_mtime if abs_path.is_file() else None+ except OSError:+ prior_mtime = None+ try:+ unchanged = (+ abs_path.is_file()+ and abs_path.stat().st_size == len(data)+ and abs_path.read_bytes() == data+ )+ except OSError:+ unchanged = False+ try:+ if not unchanged:+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = abs_path.with_name(abs_path.name + ".tmp")+ tmp_path.write_bytes(data)+ os.replace(tmp_path, abs_path)+ except OSError as exc:+ logger.debug("opencode materialize failed %s: %s", abs_path, exc)+ with contextlib.suppress(OSError, UnboundLocalError):+ tmp_path.unlink()+ continue+ if not updated_ms:+ if prior_mtime is not None and not _pin_cache_mtime(abs_path, prior_mtime * 1000):+ logger.debug(+ "opencode: could not restore the previous cache mtime "+ "for %s; this undated session will be re-read on the "+ "next run until it can",+ abs_path,+ )+ elif not _pin_cache_mtime(abs_path, updated_ms):+ logger.debug(+ "opencode: could not pin cache mtime for %s; this session "+ "will be re-read on the next run until it can",+ abs_path,+ )+ directory = s["directory"]+ try:+ mtime = datetime.fromtimestamp(updated_ms / 1000, tz=UTC)+ except (OverflowError, OSError, TypeError, ValueError):+ # A corrupt time_updated skips the timestamp, not the session or the run.+ try:+ mtime = datetime.fromtimestamp(abs_path.stat().st_mtime, tz=UTC)+ except OSError:+ continue+ yield Session(+ agent=AgentKind.OPENCODE,+ home_label=home.label,+ abs_path=abs_path,+ rel_path=rel,+ size_bytes=len(data),+ mtime=mtime,+ cwd=Path(directory) if directory else None,+ secret_findings=[],+ )+ finally:+ con.close()+++# ----- Discovery: Cursor store.db -------------------------------------------+#+# Cursor's CLI/agent surfaces persist each session as its own SQLite file, under one of+# two routes in the Cursor home: ``chats/<workspace-hash>/<session-uuid>/store.db`` or+# ``acp-sessions/<session-uuid>/store.db`` (+ sibling ``meta.json``). Format+# (reverse-engineered):+#+# meta table key '0' -> HEX-encoded JSON {agentId, latestRootBlobId, name, mode, createdAt(ms)}+# blobs table content-addressed (id = sha256): root blob = protobuf; repeated field 1 =+# 32-byte child blob ids IN CONVERSATION ORDER; field 9 = workspace file://+# URI; field 22 = surface ("cli"); field 26 = updatedAt ms; field 27 = IANA+# timezone. Child blobs = JSON messages {role, content, providerOptions, id}.+#+# The dbs are WAL-mode and often hot: recent data lives in store.db-wal, and an+# immutable=1 read of the bare file can see EMPTY tables. So each read copies+# db(+wal/+shm) to a temp dir first — never the live files. As with opencode, each+# session is synthesized into an NDJSON transcript (header line + one line per message)+# and materialized under a cache root so the rest of the pipeline treats it like any+# other transcript file.++def cursor_store_cache_root() -> Path:+ return cache_root() / "cursor-store"++# Root-blob protobuf field numbers (see module docstring above).+_CURSOR_F_CHILD_ID = 1+_CURSOR_F_CONTEXT = 5+_CURSOR_F_WORKSPACE_URI = 9+_CURSOR_F_SURFACE = 22+_CURSOR_F_UPDATED_AT = 26+_CURSOR_F_TIMEZONE = 27+# Context-stats sub-fields (nested in field 5).+_CURSOR_F_CTX_USED = 1+_CURSOR_F_CTX_WINDOW = 2+++def _cursor_read_varint(data: bytes, i: int) -> tuple[int, int]:+ value = shift = 0+ while True:+ byte = data[i]+ i += 1+ value |= (byte & 0x7F) << shift+ shift += 7+ if not byte & 0x80:+ return value, i+++def _cursor_parse_protobuf(data: bytes) -> list[tuple[int, int, object]]:+ """Minimal protobuf wire decode: [(field, wire_type, value), ...].++ Only wire types 0/1/2/5 (all the root blob uses). Stops at the first malformed+ byte and returns what parsed so far — never raises.+ """+ out: list[tuple[int, int, object]] = []+ i, n = 0, len(data)+ try:+ while i < n:+ tag, i = _cursor_read_varint(data, i)+ fnum, wire = tag >> 3, tag & 7+ if wire == 0:+ value, i = _cursor_read_varint(data, i)+ elif wire == 1:+ value, i = data[i : i + 8], i + 8+ elif wire == 2:+ length, i = _cursor_read_varint(data, i)+ if i + length > n:+ break+ value, i = data[i : i + length], i + length+ elif wire == 5:+ value, i = data[i : i + 4], i + 4+ else: # groups (3/4) / invalid — can't know the length, stop here+ break+ out.append((fnum, wire, value))+ except IndexError:+ pass # truncated varint at end of buffer+ return out+++def _cursor_decode_meta(raw: object) -> dict | None:+ """meta.value is hex-encoded JSON (text or bytes). None if undecodable."""+ if isinstance(raw, bytes):+ raw = raw.decode("ascii", errors="replace")+ if not isinstance(raw, str):+ return None+ try:+ decoded = json.loads(bytes.fromhex(raw.strip()))+ except ValueError:+ return None+ return decoded if isinstance(decoded, dict) else None+++def _cursor_utf8(value: bytes) -> str | None:+ try:+ return value.decode("utf-8")+ except UnicodeDecodeError:+ return None+++def _cursor_uri_to_path(uri: str) -> str | None:+ """``file:///Users/x/proj`` -> ``/Users/x/proj``; None for a non-``file`` URI."""+ from urllib.parse import unquote, urlparse++ parsed = urlparse(uri)+ if parsed.scheme != "file" or not parsed.path:+ return None+ return unquote(parsed.path)+++def _cursor_read_copied(db: Path) -> tuple[dict, list[dict]] | None:+ """Decode a (temp-copied) store.db -> (header, ordered messages). Raises sqlite3.Error."""+ con = sqlite3.connect(f"{db.resolve().as_uri()}?mode=ro", uri=True)+ try:+ row = con.execute("SELECT value FROM meta WHERE key='0'").fetchone()+ if row is None:+ return None+ meta = _cursor_decode_meta(row[0])+ if meta is None:+ return None++ header: dict = {+ "agentId": meta.get("agentId"),+ "name": meta.get("name") if isinstance(meta.get("name"), str) else None,+ "createdAt": meta.get("createdAt") if isinstance(meta.get("createdAt"), int) else None,+ "updatedAt": None,+ "surface": None,+ "timezone": None,+ "cwd": None,+ "contextUsed": None,+ "contextWindow": None,+ }++ root_id = meta.get("latestRootBlobId")+ root = None+ if isinstance(root_id, str):+ hit = con.execute("SELECT data FROM blobs WHERE id=?", (root_id,)).fetchone()+ root = hit[0] if hit else None+ if not isinstance(root, bytes):+ return header, [] # meta-only session; caller skips it (zero messages)++ child_ids: list[str] = []+ for fnum, wire, value in _cursor_parse_protobuf(root):+ if fnum == _CURSOR_F_CHILD_ID and wire == 2 and len(value) == 32:+ child_ids.append(value.hex())+ elif fnum == _CURSOR_F_CONTEXT and wire == 2:+ for sub_f, sub_w, sub_v in _cursor_parse_protobuf(value):+ if sub_w != 0:+ continue+ if sub_f == _CURSOR_F_CTX_USED:+ header["contextUsed"] = sub_v+ elif sub_f == _CURSOR_F_CTX_WINDOW:+ header["contextWindow"] = sub_v+ elif fnum == _CURSOR_F_WORKSPACE_URI and wire == 2:+ path = _cursor_uri_to_path(_cursor_utf8(value) or "")+ if path:+ header["cwd"] = path+ elif fnum == _CURSOR_F_SURFACE and wire == 2:+ header["surface"] = _cursor_utf8(value)+ elif fnum == _CURSOR_F_UPDATED_AT and wire == 0:+ header["updatedAt"] = value+ elif fnum == _CURSOR_F_TIMEZONE and wire == 2:+ header["timezone"] = _cursor_utf8(value)++ messages: list[dict] = []+ for cid in child_ids:+ hit = con.execute("SELECT data FROM blobs WHERE id=?", (cid,)).fetchone()+ if hit is None:+ continue # child blob missing — skip it, keep the rest of the conversation+ try:+ msg = json.loads(hit[0])+ except (TypeError, ValueError):+ continue+ if isinstance(msg, dict) and "role" in msg:+ messages.append(msg)+ return header, messages+ finally:+ con.close()+++def _cursor_read_store_db(db_path: Path) -> tuple[dict, list[dict]] | None:+ """WAL-safe decode of one store.db: copies db(+wal/+shm) to a temp dir first.++ Never raises — returns None on any I/O or decode failure. ``header["cwd"]`` is+ overridden from the sibling ``meta.json`` (acp-sessions route) when present.+ """+ if not db_path.exists():+ return None+ try:+ with tempfile.TemporaryDirectory(prefix="cursor_store_") as tmp:+ copy = Path(tmp) / "store.db"+ shutil.copy2(db_path, copy)+ for suffix in ("-wal", "-shm"):+ side = db_path.with_name(db_path.name + suffix)+ if side.exists():+ shutil.copy2(side, copy.with_name(copy.name + suffix))+ result = _cursor_read_copied(copy)+ except (OSError, sqlite3.Error) as exc:+ _warn_unreadable_db("cursor_store", db_path, exc)+ return None+ if result is None:+ return None+ header, messages = result++ # Root-blob field 26 (updatedAt) goes stale mid-session — Cursor bumps it on+ # meta events, not per message (seen live: field frozen ~3h behind a WAL that+ # kept appending messages). The db/-wal mtimes track the last real write, so+ # session end = newest of the three; flows into the NDJSON header and the+ # Session.mtime recency guard.+ disk_ms = 0+ for f in (db_path, db_path.with_name(db_path.name + "-wal")):+ with contextlib.suppress(OSError):+ disk_ms = max(disk_ms, f.stat().st_mtime_ns // 1_000_000)+ header["updatedAt"] = max(header.get("updatedAt") or 0, disk_ms) or None++ # acp-sessions keeps cwd in a sibling meta.json (no trailing newline); it wins over+ # the field-9 workspace URI when present.+ meta_json = db_path.parent / "meta.json"+ if meta_json.exists():+ try:+ sidecar = json.loads(meta_json.read_bytes())+ if isinstance(sidecar, dict) and isinstance(sidecar.get("cwd"), str):+ header["cwd"] = sidecar["cwd"]+ except (OSError, ValueError):+ logger.debug("cursor_store: bad meta.json next to %s", db_path)+ return header, messages+++def _find_cursor_store_dbs(home: Path) -> list[Path]:+ """All ``store.db`` files under a Cursor home's ``chats/`` + ``acp-sessions/``."""+ return sorted([*home.glob("chats/*/*/store.db"), *home.glob("acp-sessions/*/store.db")])+++def _cursor_last_message_model(messages: list[dict]) -> str | None:+ """Last ``providerOptions.cursor.modelName`` in conversation order (message or part).++ Stamped on the header when the store records no model of its own; the session's+ model is the last one it used.+ """+ last: str | None = None+ for msg in messages:+ if not isinstance(msg, dict):+ continue+ po = msg.get("providerOptions")+ if isinstance(po, dict):+ cur = po.get("cursor")+ if isinstance(cur, dict) and isinstance(cur.get("modelName"), str) and cur["modelName"]:+ last = cur["modelName"]+ content = msg.get("content")+ if isinstance(content, list):+ for part in content:+ if not isinstance(part, dict):+ continue+ ppo = part.get("providerOptions")+ if isinstance(ppo, dict):+ cur = ppo.get("cursor")+ if (+ isinstance(cur, dict)+ and isinstance(cur.get("modelName"), str)+ and cur["modelName"]+ ):+ last = cur["modelName"]+ return last+++def find_cursor_store_candidates(+ home: HomeSpec, *, cache_root: Path | None = None+) -> Iterator[Session]:+ """Yield a Session per Cursor CLI/agent store.db, synthesizing an NDJSON transcript.++ ``home.path`` is the Cursor home (holds ``chats/`` and/or ``acp-sessions/``). Each+ session is materialized to ``<cache_root>/<home_label>/<session-uuid>.jsonl`` — a+ ``cursor_store_session`` header line, then one line per message verbatim — and that+ file becomes the Session's ``abs_path``, mirroring ``find_opencode_candidates``.+ Sessions with zero messages are skipped (nothing useful to replay).+ """+ root = (cache_root or cursor_store_cache_root()) / home.label+ for db_path in _find_cursor_store_dbs(home.path):+ result = _cursor_read_store_db(db_path)+ if result is None:+ continue+ header, messages = result+ if not messages:+ continue+ session_id = header.get("agentId") or db_path.parent.name+ if not header.get("model"):+ msg_model = _cursor_last_message_model(messages)+ if msg_model:+ header = {**header, "model": msg_model}+ # Path-traversal-safe cache naming, same guard as opencode's project_id/session id.+ rel = Path(f"{_safe_component(session_id, 'session')}.jsonl")+ abs_path = root / rel+ record = {"type": "cursor_store_session", **header}+ lines = [json.dumps(record, separators=(",", ":"))]+ lines.extend(json.dumps(m, separators=(",", ":")) for m in messages)+ data = ("\n".join(lines) + "\n").encode()+ try:+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ # Only write when the bytes actually differ. Other readers use+ # each file's MTIME as the session's timestamp, so an unconditional+ # rewrite would make every materialized Cursor session look newer+ # than it is and re-process the entire cache on every run.+ # Prior mtime captured before any write, for the undated case+ # below — same contract as the composer and OpenCode materializers.+ try:+ prior_mtime = abs_path.stat().st_mtime if abs_path.is_file() else None+ except OSError:+ prior_mtime = None+ if not (abs_path.is_file() and abs_path.read_bytes() == data):+ # Atomic, like its siblings: with the unchanged-content skip+ # above, a .jsonl truncated by a crash mid-write would never be+ # rewritten.+ tmp_path = abs_path.with_name(abs_path.name + ".tmp")+ tmp_path.write_bytes(data)+ os.replace(tmp_path, abs_path)+ # Stamp with the STORE's own activity time, not "now" — and do it+ # whether or not we just wrote.+ #+ # Readers take st_mtime as the session's timestamp and apply a+ # `--hours` look-back against it. A+ # file left at the filesystem clock makes a months-old Cursor session+ # look like it happened this minute: it slips through the look-back+ # and drags the high-water mark forward, which then hides everything+ # genuinely older.+ #+ # Applied OUTSIDE the fresh-write branch on purpose: a cache file+ # whose bytes are unchanged but whose mtime is wrong is corrected+ # too, since the unchanged-content guard would otherwise never+ # revisit it. `os.utime` on an already-correct file is a no-op for+ # mtime, so this stays idempotent.+ stamp_ms = header.get("updatedAt") or header.get("createdAt") or 0+ # Through the verifying helper, like the other two materializers:+ # a bare `os.utime` that silently no-ops would leave the write time+ # in place. Both fields here are raw record ints, where 0 means+ # unset, so the composer path's epoch-zero distinction does not+ # apply to this materializer.+ if not stamp_ms:+ # Undatable: keep the timestamp the file already carried rather+ # than letting a rewrite advance it to "now".+ if prior_mtime is not None and not _pin_cache_mtime(abs_path, prior_mtime * 1000):+ logger.debug(+ "cursor_store: could not restore the previous cache "+ "mtime for %s; this undated session will be re-read "+ "on the next run until it can",+ abs_path,+ )+ elif not _pin_cache_mtime(abs_path, stamp_ms):+ logger.debug(+ "cursor_store: could not pin cache mtime for %s; this "+ "session will be re-read on the next run until it can",+ abs_path,+ )+ except OSError as exc:+ logger.debug("cursor_store materialize failed %s: %s", abs_path, exc)+ continue+ try:+ st = abs_path.stat()+ except OSError:+ continue++ cwd = header.get("cwd")+ mtime_ms = header.get("updatedAt") or header.get("createdAt") or 0+ try:+ mtime = datetime.fromtimestamp(mtime_ms / 1000, tz=UTC)+ except (OverflowError, OSError, ValueError):+ # updatedAt comes from a hand-rolled protobuf walk of a possibly+ # hot/corrupt db — an insane value must not abort ALL discovery.+ mtime = datetime.fromtimestamp(st.st_mtime, tz=UTC)+ yield Session(+ agent=AgentKind.CURSOR,+ home_label=home.label,+ abs_path=abs_path,+ rel_path=rel,+ size_bytes=st.st_size,+ mtime=mtime,+ cwd=Path(cwd) if cwd else None,+ secret_findings=[],+ )+++# ----- Discovery: Cursor IDE composers (state.vscdb) -------------------------+#+# The IDE keeps composer chats in its global ``state.vscdb`` rather than in a+# per-session store.db. They are synthesized into the same NDJSON shape as+# store.db (``cursor_store_session`` header + messages) so one parser handles both.++def cursor_composer_cache_root() -> Path:+ return cache_root() / "cursor-composer"+_CURSOR_COMPOSER_HOME_LABEL = "cursor-ide"+++def _default_cursor_state_db() -> Path:+ """Cursor's global ``state.vscdb``."""+ return _default_state_db_path()+++def _cursor_composer_cwd(composer: dict) -> str | None:+ """Workspace path from ``workspaceIdentifier.uri``, if present."""+ ws = composer.get("workspaceIdentifier")+ if not isinstance(ws, dict):+ return None+ uri = ws.get("uri")+ if isinstance(uri, dict):+ for key in ("fsPath", "path"):+ val = uri.get(key)+ if isinstance(val, str) and val:+ return val+ external = uri.get("external")+ if isinstance(external, str) and external:+ return _cursor_uri_to_path(external)+ elif isinstance(uri, str) and uri:+ return _cursor_uri_to_path(uri)+ return None+++_CURSOR_CONTEXT_PATH_CAP = 200+++def _cursor_composer_context_paths(composer: dict) -> list[str]:+ """Structured file paths an IDE composer record references, for repo attribution.++ Composer chats rarely run ``git remote`` and rarely open a PR, and their+ transcripts carry few tool-call file paths - so all three git-free resolver tiers+ miss and the session ends up unattributed. Cursor does record real paths, just+ never anywhere the parser looks, and far more composer records carry one of+ these than carry a ``workspaceIdentifier`` cwd.++ Collected here, most-trustworthy first:++ * ``trackedGitRepos[].repoPath`` and ``gitWorktree`` roots — literal repo+ roots, so a leaf match is as good as a git remote;+ * ``newlyCreatedFiles[].uri`` — the dominant carrier in practice;+ * ``context.selections[].uri`` — files the user explicitly attached;+ * ``originalFileStates`` — whose dict KEYS are ``file://`` URIs of every+ file the session edited;+ * ``workspaceIdentifier.uri``, the same value ``_cursor_composer_cwd``+ returns, included because repo attribution reads file paths, not ``cwd``.++ For the same reason these travel as their own header field rather than being+ folded into ``cwd``.++ Ordering is preserved and duplicates dropped, so the strongest signal leads+ and the downstream tally sees each path once. Capped at+ ``_CURSOR_CONTEXT_PATH_CAP`` because ``originalFileStates`` grows with the+ session and the header must stay a single NDJSON line.++ Args:+ composer: One decoded ``composerData:`` record.++ Returns:+ Absolute path strings (``file://`` scheme stripped, percent-decoded), or+ ``[]`` when the record references none. A Windows URI decodes with a+ leading slash before the drive (``/C:/Users/...``); harmless here because+ the consuming tier matches path SEGMENTS, not prefixes.+ """+ out: list[str] = []+ seen: set[str] = set()++ def each(node: object) -> list:+ """Iterate only a genuine list.++ ``x or []`` still hands a truthy SCALAR straight to ``for``, and the+ resulting TypeError escapes ``_cursor_read_composers`` — which catches+ only OSError/sqlite3.Error — so one malformed record would abort composer+ discovery for the whole machine, not just skip itself.+ """+ return node if isinstance(node, list) else []++ def add(value: object) -> None:+ if not isinstance(value, str) or not value:+ return+ path = _cursor_uri_to_path(value) if value.startswith("file://") else value+ if not path or path in seen:+ return+ seen.add(path)+ out.append(path)++ def add_uri(node: object) -> None:+ """A vscode URI, stored either as an object or a bare string."""+ if isinstance(node, dict):+ for key in ("fsPath", "path", "external"):+ if isinstance(node.get(key), str) and node[key]:+ add(node[key])+ return+ elif isinstance(node, str):+ add(node)++ for repo in each(composer.get("trackedGitRepos")):+ if isinstance(repo, dict):+ add(repo.get("repoPath"))+ worktree = composer.get("gitWorktree")+ if isinstance(worktree, dict):+ add(worktree.get("worktreePath"))+ add(worktree.get("mainWorktreePath"))+ for created in each(composer.get("newlyCreatedFiles")):+ if isinstance(created, dict):+ add_uri(created.get("uri"))+ context = composer.get("context")+ if isinstance(context, dict):+ for selection in each(context.get("selections")):+ if isinstance(selection, dict):+ add_uri(selection.get("uri"))+ states = composer.get("originalFileStates")+ if isinstance(states, dict):+ for key in states:+ add(key)+ workspace = composer.get("workspaceIdentifier")+ if isinstance(workspace, dict):+ add_uri(workspace.get("uri"))++ return out[:_CURSOR_CONTEXT_PATH_CAP]+++def _cursor_bubble_to_messages(bubble: dict) -> list[dict]:+ """One IDE bubble → zero-or-more NDJSON messages the store parser understands.++ The bubble's ``createdAt`` (an ISO-8601 UTC string in real state.vscdb data,+ e.g. ``"2025-10-02T06:43:45.379Z"``) is forwarded onto every emitted message+ because it is the only per-message timestamp Cursor persists, and the parser+ times each turn from it. Store.db (CLI/ACP) messages carry no equivalent.+ """+ btype = bubble.get("type")+ text = bubble.get("text") if isinstance(bubble.get("text"), str) else ""+ bubble_id = bubble.get("bubbleId")+ created_at = bubble.get("createdAt") if isinstance(bubble.get("createdAt"), str) else None+ model = None+ mi = bubble.get("modelInfo")+ if isinstance(mi, dict) and isinstance(mi.get("modelName"), str):+ model = mi["modelName"]+ provider = {"cursor": {"modelName": model}} if model else None++ out: list[dict] = []+ if btype == 1: # user+ msg: dict = {"role": "user", "content": text}+ if bubble_id:+ msg["id"] = bubble_id+ if created_at:+ msg["createdAt"] = created_at+ if provider:+ msg["providerOptions"] = provider+ out.append(msg)+ return out++ # assistant (type 2) and anything else with signal+ tfd = bubble.get("toolFormerData")+ parts: list[dict] = []+ if text:+ parts.append({"type": "text", "text": text})+ tool_name = None+ tool_call_id = None+ tool_args: dict | str = {}+ tool_result = None+ tool_error = False+ if isinstance(tfd, dict) and tfd:+ name = tfd.get("name") or tfd.get("toolName")+ if isinstance(name, str) and name:+ tool_name = name+ tool_call_id = tfd.get("toolCallId") or f"call-{bubble_id or 'x'}"+ raw_args = tfd.get("params") if tfd.get("params") is not None else tfd.get("rawArgs")+ if isinstance(raw_args, dict):+ tool_args = raw_args+ elif isinstance(raw_args, str) and raw_args:+ try:+ parsed = json.loads(raw_args)+ tool_args = parsed if isinstance(parsed, dict) else {"raw": raw_args}+ except (TypeError, ValueError):+ tool_args = {"raw": raw_args}+ parts.append(+ {+ "type": "tool-call",+ "toolCallId": tool_call_id,+ "toolName": tool_name,+ "args": tool_args,+ }+ )+ result = tfd.get("result")+ if result is not None:+ tool_result = result if isinstance(result, str) else json.dumps(result)+ status = tfd.get("status") or tfd.get("state")+ if (+ (+ isinstance(status, str)+ and ("error" in status.lower() or "fail" in status.lower())+ )+ or tfd.get("error")+ or tfd.get("isError")+ ):+ tool_error = True++ if not parts and not tool_name:+ return out++ asst: dict = {"role": "assistant", "content": parts}+ if bubble_id:+ asst["id"] = bubble_id+ if created_at:+ asst["createdAt"] = created_at+ if provider:+ asst["providerOptions"] = provider+ out.append(asst)++ if tool_name and tool_call_id is not None and tool_result is not None:+ tool_msg: dict = {+ "role": "tool",+ "content": [+ {+ "type": "tool-result",+ "toolCallId": tool_call_id,+ "result": tool_result,+ "isError": tool_error,+ }+ ],+ }+ if created_at:+ tool_msg["createdAt"] = created_at+ out.append(tool_msg)+ return out+++def _cursor_like_escape(value: str) -> str:+ r"""Escape LIKE wildcards (% _ \) so a composer id is matched literally.++ Extracted (not inlined in an f-string) — Python 3.11 forbids backslash+ escapes inside f-string expressions.+ """+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+++def _cursor_read_composers(+ db_path: Path,+) -> list[tuple[dict, list[dict]]]:+ """Read every composer with ≥1 bubble from ``state.vscdb``. Never raises."""+ if not db_path.is_file():+ return []+ try:+ with contextlib.ExitStack() as stack:+ # Read the LIVE store, read-only, rather than copying it: the file+ # can be gigabytes, and copying the db and its WAL seconds apart can+ # produce a torn pair on a busy Cursor. A deferred read transaction+ # on WAL is a genuine snapshot and never blocks Cursor's own writers.+ try:+ con = sqlite3.connect(f"{db_path.resolve().as_uri()}?mode=ro", uri=True)+ con.execute("BEGIN DEFERRED")+ except sqlite3.Error:+ # Some filesystems and older SQLite builds refuse a read-only+ # URI open of a WAL database. Snapshot it the old way rather+ # than losing the whole Cursor surface.+ tmp = stack.enter_context(tempfile.TemporaryDirectory(prefix="cursor_composer_"))+ copy = Path(tmp) / "state.vscdb"+ shutil.copy2(db_path, copy)+ for suffix in ("-wal", "-shm"):+ side = Path(str(db_path) + suffix)+ if side.is_file():+ shutil.copy2(side, Path(str(copy) + suffix))+ con = sqlite3.connect(f"{copy.resolve().as_uri()}?mode=ro", uri=True)+ try:+ try:+ rows = con.execute(+ "SELECT key, value FROM cursorDiskKV WHERE key LIKE 'composerData:%'"+ ).fetchall()+ except sqlite3.Error:+ return []+ results: list[tuple[dict, list[dict]]] = []+ for key, value in rows:+ if not isinstance(key, str) or not key.startswith("composerData:"):+ continue+ composer_id = key.split(":", 1)[1]+ if not composer_id or composer_id == "empty-state-draft":+ continue+ try:+ raw = value.decode() if isinstance(value, bytes) else value+ composer = json.loads(raw)+ except (TypeError, ValueError, UnicodeDecodeError):+ continue+ if not isinstance(composer, dict):+ continue+ try:+ # Range, not LIKE. `ESCAPE` disables SQLite's LIKE+ # optimisation outright, and the default+ # case_sensitive_like=off disqualifies the BINARY+ # autoindex anyway — so every one of these planned as a+ # full table SCAN, 239 of them, ~9.9s per run. The+ # prefix ends in ':' (0x3A), so ';' (0x3B) is exactly+ # the next possible key: identical rows, via SEARCH.+ prefix = f"bubbleId:{composer_id}:"+ bubble_rows = con.execute(+ "SELECT value FROM cursorDiskKV WHERE key >= ? AND key < ?",+ (prefix, prefix[:-1] + ";"),+ ).fetchall()+ except sqlite3.Error:+ continue+ bubbles: list[dict] = []+ for (bval,) in bubble_rows:+ try:+ braw = bval.decode() if isinstance(bval, bytes) else bval+ bubble = json.loads(braw)+ except (TypeError, ValueError, UnicodeDecodeError):+ continue+ if isinstance(bubble, dict):+ bubbles.append(bubble)+ if not bubbles:+ continue+ bubbles.sort(key=lambda b: b.get("createdAt") or "")++ model = None+ mc = composer.get("modelConfig")+ if isinstance(mc, dict) and isinstance(mc.get("modelName"), str):+ model = mc["modelName"]+ created = composer.get("createdAt")+ updated = _cursor_composer_last_activity_ms(composer, bubbles)+ header: dict = {+ "agentId": composer_id,+ "name": composer.get("name")+ if isinstance(composer.get("name"), str)+ else None,+ "createdAt": created if isinstance(created, int) else None,+ "updatedAt": updated if isinstance(updated, int) else None,+ "surface": "ide",+ "timezone": None,+ "cwd": _cursor_composer_cwd(composer),+ # Absent (not empty) when this composer referenced no+ # files, so a reader can tell "no paths" from "old CLI".+ **(+ {"contextFiles": _ctx_paths}+ if (_ctx_paths := _cursor_composer_context_paths(composer))+ else {}+ ),+ "contextUsed": composer.get("contextTokensUsed")+ if isinstance(composer.get("contextTokensUsed"), int)+ else None,+ "contextWindow": composer.get("contextTokenLimit")+ if isinstance(composer.get("contextTokenLimit"), int)+ else None,+ }+ if model:+ header["model"] = model++ messages: list[dict] = []+ for bubble in bubbles:+ messages.extend(_cursor_bubble_to_messages(bubble))+ if not messages:+ continue+ results.append((header, messages))+ return results+ finally:+ con.close()+ except (OSError, sqlite3.Error) as exc:+ _warn_unreadable_db("cursor_composer", db_path, exc)+ return []+++def _cursor_composer_last_activity_ms(composer: dict, bubbles: list[dict]) -> int | None:+ """Epoch-ms of a composer's newest real MESSAGE.++ The record-level ``lastUpdatedAt`` is not per-message truth. It is absent+ on most composer records, and it drifts in BOTH directions against the+ conversation's own messages: bumped without any message changing, and+ observed running days behind bubbles that kept arriving. Either direction+ makes it useless as a freshness signal.++ Bubble ``createdAt`` is the only per-message timestamp Cursor persists, so+ it is what "when did this session last do work" has to mean. Note the type+ split: bubbles carry an ISO-8601 STRING while the composer record carries+ epoch MILLISECONDS, which is why this returns ms and parses accordingly.++ Args:+ composer: The decoded ``composerData:`` record.+ bubbles: Its decoded ``bubbleId:`` records, in any order.++ Returns:+ Epoch milliseconds of the newest datable bubble; failing that the+ record's own fields, so a conversation whose bubbles carry no parseable+ timestamp still resolves to something real. None when nothing is+ datable at all — the caller must not substitute "now".+ """+ # None-sentinel, not 0: a bubble parsed as exactly epoch+ # zero is a real — if bizarre — timestamp, and a zero sentinel would+ # conflate it with "no datable bubble at all" and skip this branch.+ newest: int | None = None+ for bubble in bubbles:+ value = bubble.get("createdAt")+ if not isinstance(value, str) or not value:+ continue+ try:+ when = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ continue+ if when.tzinfo is None:+ when = when.replace(tzinfo=UTC)+ ts = int(when.timestamp() * 1000)+ newest = ts if newest is None else max(newest, ts)+ if newest is not None:+ return newest+ for key in ("lastUpdatedAt", "conversationCheckpointLastUpdatedAt", "createdAt"):+ value = composer.get(key)+ if isinstance(value, int) and value > 0:+ return value+ return None+++def find_cursor_composer_candidates(+ *,+ state_db: Path | None = None,+ cache_root: Path | None = None,+) -> Iterator[Session]:+ """Yield Sessions for IDE composer chats in ``state.vscdb``.++ Materializes the same ``cursor_store_session`` NDJSON shape as+ :func:`find_cursor_store_candidates`.+ """+ db_path = state_db or _default_cursor_state_db()+ composers = _cursor_read_composers(db_path)+ if not composers:+ return++ root = (cache_root or cursor_composer_cache_root()) / _CURSOR_COMPOSER_HOME_LABEL+ for header, messages in composers:+ session_id = header.get("agentId") or "session"+ if not header.get("model"):+ msg_model = _cursor_last_message_model(messages)+ if msg_model:+ header = {**header, "model": msg_model}++ rel = Path(f"{_safe_component(session_id, 'session')}.jsonl")+ abs_path = root / rel+ record = {"type": "cursor_store_session", **header}+ lines = [json.dumps(record, separators=(",", ":"))]+ lines.extend(json.dumps(m, separators=(",", ":")) for m in messages)+ data = ("\n".join(lines) + "\n").encode()+ cwd = header.get("cwd")+ # Split semantics: `updatedAt` is derived by+ # `_cursor_composer_last_activity_ms`, which already distinguishes+ # "no datable bubble" (None) from a genuine epoch-zero bubble (0) — so+ # it is read None-aware and a 0 is pinned as a real timestamp. Raw+ # record ints are different: a `createdAt: 0` means the field was+ # unset, exactly the way the derivation's own `> 0` gates read record+ # fields, so the fallback keeps the truthy gate.+ mtime_ms = header.get("updatedAt")+ if mtime_ms is None:+ mtime_ms = header.get("createdAt") or None++ # Readers take this file's FILESYSTEM mtime as the session's+ # timestamp, so rewriting every composer on every run would stamp all+ # of them "now" and re-qualify year-old conversations for the+ # look-back window. Skip the write when the bytes are identical, then+ # pin the mtime to the conversation's newest message.+ #+ # `prior_mtime` covers a conversation with no datable bubble AND no+ # record timestamp: there is nothing to pin to, so a later content+ # change would otherwise stamp it "now" and pull an undated+ # conversation into the look-back window. Keeping the timestamp the+ # file already had is the only honest choice.+ try:+ prior_mtime = abs_path.stat().st_mtime if abs_path.is_file() else None+ except OSError:+ prior_mtime = None+ try:+ unchanged = (+ abs_path.is_file()+ and abs_path.stat().st_size == len(data)+ and abs_path.read_bytes() == data+ )+ except OSError:+ unchanged = False+ if not unchanged:+ try:+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ # Atomic: unchanged files are never rewritten, so a .jsonl+ # truncated by a crash mid-write would otherwise be permanent.+ tmp_path = abs_path.with_name(abs_path.name + ".tmp")+ tmp_path.write_bytes(data)+ os.replace(tmp_path, abs_path)+ except OSError as exc:+ logger.debug("cursor_composer materialize failed %s: %s", abs_path, exc)+ with contextlib.suppress(OSError):+ tmp_path.unlink()+ continue+ if mtime_ms is None:+ # Undatable. Restore the timestamp the file already carried rather+ # than letting a rewrite advance it; a brand-new undated cache has+ # no prior evidence, so it keeps the write time and ages out of the+ # window normally instead of returning on every build.+ if prior_mtime is not None:+ # Through the verifying helper, not a bare suppressed utime.+ # An unverified restore has the same failure mode as an+ # unverified pin: the file silently keeps its write time and+ # the session re-qualifies on every build.+ if not _pin_cache_mtime(abs_path, prior_mtime * 1000):+ logger.debug(+ "cursor_composer: could not restore the previous cache "+ "mtime for %s; this undated session will be re-read "+ "on the next run until it can",+ abs_path,+ )+ else:+ logger.debug(+ "cursor_composer: %s carries no datable message or record "+ "timestamp; its cache keeps the write time",+ abs_path,+ )+ elif not _pin_cache_mtime(abs_path, mtime_ms):+ # Do not skip the next write for a file whose timestamp we could+ # not pin. Silently continuing leaves the just-written mtime, which+ # is "now", and the unchanged-content guard would then make sure+ # this file is never revisited to correct it. Yield the session (the data is fine) but say so,+ # so a machine that cannot pin timestamps is diagnosable instead of+ # quietly leaving every session looking changed on each run.+ logger.debug(+ "cursor_composer: could not pin cache mtime for %s; this "+ "session will be re-read on the next run until it can",+ abs_path,+ )+ try:+ st = abs_path.stat()+ except OSError:+ continue+ try:+ # None = undated: the file's own (kept/restored) mtime is the only+ # evidence there is — and it is truer than the old `0 → 1970`+ # collapse this replaces.+ mtime = (+ datetime.fromtimestamp(mtime_ms / 1000, tz=UTC)+ if mtime_ms is not None+ else datetime.fromtimestamp(st.st_mtime, tz=UTC)+ )+ except (OverflowError, OSError, ValueError):+ mtime = datetime.fromtimestamp(st.st_mtime, tz=UTC)+ yield Session(+ agent=AgentKind.CURSOR,+ home_label=_CURSOR_COMPOSER_HOME_LABEL,+ abs_path=abs_path,+ rel_path=rel,+ size_bytes=st.st_size,+ mtime=mtime,+ cwd=Path(cwd) if cwd else None,+ secret_findings=[],+ )+++#+# A Kiro session is a DIRECTORY, not a file: sessions/<ws-hash>/<session-id>/ holds+# session.json (metadata) + messages.jsonl (event log), and sub-agent runs land in+# sub-executions/<execution-id>.jsonl. We synthesize one NDJSON per session — a+# `kiro_session` header line then the raw events, merged by timestamp — mirroring+# the cursor_store/opencode pattern so scan, redaction, and dedup are all+# unchanged downstream. Agent detection sniffs the header type.++def kiro_cache_root() -> Path:+ return cache_root() / "kiro"+++def _count_kiro_sessions(home: Path) -> int:+ """Count session dirs under <home>/sessions/<ws-hash>/<session-id>/ (0 if none)."""+ sessions_root = home / "sessions"+ if not sessions_root.is_dir():+ return 0+ n = 0+ try:+ for ws_hash_dir in sessions_root.iterdir():+ if not ws_hash_dir.is_dir():+ continue+ for session_dir in ws_hash_dir.iterdir():+ if session_dir.is_dir() and (session_dir / "session.json").is_file():+ n += 1+ except OSError:+ return n+ return n+++def _kiro_cwd(session_meta: dict) -> Path | None:+ """The session's primary workspace root (``workspacePaths[0]``), else None.++ None means the session records no workspace, so it carries no cwd.+ """+ paths = session_meta.get("workspacePaths")+ if isinstance(paths, list) and paths:+ first = paths[0]+ if isinstance(first, str) and first.strip():+ return Path(first)+ return None+++def _kiro_read_events(path: Path) -> list[dict]:+ """Parse one Kiro JSONL event log; unparseable/non-dict lines are dropped."""+ events: list[dict] = []+ try:+ data = path.read_bytes()+ except OSError:+ return events+ for raw_line in data.split(b"\n"):+ raw_line = raw_line.strip()+ if not raw_line:+ continue+ try:+ obj = json.loads(raw_line)+ except (json.JSONDecodeError, UnicodeDecodeError, ValueError):+ continue+ if isinstance(obj, dict):+ events.append(obj)+ return events+++def _kiro_source_mtime(messages_mtime: float, session_dir: Path) -> float:+ """Latest mtime across every file `_kiro_synthesize` reads for this session.++ That is ``messages.jsonl`` plus any ``sub-executions/*.jsonl``. The cache+ freshness guard compares against this so a sub-agent file updated after+ ``messages.jsonl`` still triggers re-synthesis — comparing against+ ``messages.jsonl`` alone would serve a cache missing those sub-agent events.+ A missing/unreadable ``sub-executions/`` dir falls back to ``messages_mtime``.+ """+ latest = messages_mtime+ sub_exec_dir = session_dir / "sub-executions"+ if sub_exec_dir.is_dir():+ try:+ for sub_file in sub_exec_dir.iterdir():+ if sub_file.suffix != ".jsonl":+ continue+ with contextlib.suppress(OSError):+ latest = max(latest, sub_file.stat().st_mtime)+ except OSError:+ pass+ return latest+++def _kiro_synthesize(session_meta: dict, messages_path: Path, session_dir: Path) -> bytes | None:+ """Build one session's NDJSON: `kiro_session` header + events, merged by timestamp.++ Sub-execution (sub-agent) events are merged inline so the whole conversation —+ including sub-agent tool calls - travels as a single file.++ Returns None when the session has no ``turn_end`` event: an empty or+ metadata-only session has nothing worth replaying.+ """+ events = _kiro_read_events(messages_path)+ sub_exec_dir = session_dir / "sub-executions"+ if sub_exec_dir.is_dir():+ try:+ sub_files = sorted(p for p in sub_exec_dir.iterdir() if p.suffix == ".jsonl")+ except OSError:+ sub_files = []+ for sub_file in sub_files:+ events.extend(_kiro_read_events(sub_file))++ # Stable sort on timestamp: equal/absent timestamps keep file order (main+ # stream first, then each sub-execution in name order).+ events.sort(key=lambda e: str(e.get("timestamp") or ""))++ has_turns = any(+ isinstance(e.get("payload"), dict) and e["payload"].get("type") == "turn_end"+ for e in events+ )+ if not has_turns:+ return None++ # Marker key LAST so it always wins: if a future session.json carries its own+ # `type`, spreading it after would clobber the `kiro_session` marker and the+ # agent detection would fail to recognise the transcript (dropping it).+ header = {**session_meta, "type": "kiro_session"}+ lines = [json.dumps(header, separators=(",", ":"))]+ lines.extend(json.dumps(e, separators=(",", ":")) for e in events)+ return ("\n".join(lines) + "\n").encode()+++def find_kiro_candidates(home: HomeSpec, *, cache_root: Path | None = None) -> Iterator[Session]:+ """Yield a Session per Kiro session, synthesizing an NDJSON transcript.++ ``home.path`` is the Kiro home (holds ``sessions/``). Each session is materialized+ to ``<cache_root>/<ws-hash>/<session-id>.jsonl`` and that file becomes the Session's+ ``abs_path``, mirroring ``find_cursor_store_candidates``.++ The cache is only rewritten when ``messages.jsonl`` is newer than it, so a re-run+ over unchanged sessions costs a stat() rather than a full re-synthesis.+ """+ sessions_root = home.path / "sessions"+ if not sessions_root.is_dir():+ logger.debug("kiro: no sessions dir under %s", home.path)+ return+ root = cache_root or kiro_cache_root()+ try:+ ws_hash_dirs = sorted(p for p in sessions_root.iterdir() if p.is_dir())+ except OSError as exc:+ logger.debug("kiro: cannot list %s: %s", sessions_root, exc)+ return++ for ws_hash_dir in ws_hash_dirs:+ ws_hash = _safe_component(ws_hash_dir.name, "unknown")+ try:+ session_dirs = sorted(p for p in ws_hash_dir.iterdir() if p.is_dir())+ except OSError:+ continue+ for session_dir in session_dirs:+ session_json_path = session_dir / "session.json"+ messages_path = session_dir / "messages.jsonl"+ if not session_json_path.is_file() or not messages_path.is_file():+ continue+ try:+ session_meta = json.loads(session_json_path.read_bytes())+ except (OSError, json.JSONDecodeError, ValueError):+ logger.debug("kiro: bad session.json in %s", session_dir)+ continue+ if not isinstance(session_meta, dict):+ continue+ try:+ messages_mtime = messages_path.stat().st_mtime+ except OSError:+ continue+ # Freshness is judged against every file the synthesis reads — not+ # just messages.jsonl. Sub-executions are merged in too, and a+ # sub-agent file updated after messages.jsonl would otherwise leave+ # the cache "fresh" while missing those events.+ source_mtime = _kiro_source_mtime(messages_mtime, session_dir)++ session_id = _safe_component(session_meta.get("id") or session_dir.name, "session")+ rel = Path(ws_hash) / f"{session_id}.jsonl"+ abs_path = root / rel+ cwd = _kiro_cwd(session_meta)++ fresh = False+ with contextlib.suppress(OSError):+ fresh = abs_path.stat().st_mtime >= source_mtime+ if not fresh:+ data = _kiro_synthesize(session_meta, messages_path, session_dir)+ if data is None:+ continue+ # Atomic: freshness is judged by mtime, so a torn write would+ # otherwise look fresh and never be rewritten.+ tmp_path = abs_path.with_name(abs_path.name + ".tmp")+ try:+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path.write_bytes(data)+ os.replace(tmp_path, abs_path)+ except OSError as exc:+ logger.debug("kiro materialize failed %s: %s", abs_path, exc)+ with contextlib.suppress(OSError):+ tmp_path.unlink()+ continue+ try:+ st = abs_path.stat()+ except OSError:+ continue+ yield Session(+ agent=AgentKind.KIRO,+ home_label=home.label,+ abs_path=abs_path,+ rel_path=rel,+ size_bytes=st.st_size,+ # messages.jsonl mtime, not the cache file's: the cache is rewritten+ # on re-synthesis and would otherwise report every session as "just now".+ mtime=datetime.fromtimestamp(messages_mtime, tz=UTC),+ cwd=cwd,+ secret_findings=[],+ )+++# ----- Discovery: GitHub Copilot CLI -----------------------------------------+# Copilot CLI writes one JSONL event log per session, so unlike Cursor / Kiro /+# opencode nothing is synthesized: the on-disk file IS the transcript the parser's+# `parse_copilot` reads.+# <home>/session-state/<session-id>/events.jsonl Copilot CLI >= 1.0.11+# <home>/session-state/<session-id>.jsonl legacy flat layout+# Copilot creates the session directory (and an events.jsonl holding only+# `session.start` + a model-change line) the moment the binary starts, so most+# session folders on a machine never held a prompt; those are skipped.+diff --git a/python/src/agentplay/pipeline.py b/python/src/agentplay/pipeline.pynew file mode 100644index 0000000..8ad377a--- /dev/null+++ b/python/src/agentplay/pipeline.py@@ -0,0 +1,211 @@+"""Build maps for every session on this machine into the local store."""++from __future__ import annotations++import logging+import os+import time+from collections import Counter+from collections.abc import Callable+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any++from . import __version__, builder, discover+from .store import Store++logger = logging.getLogger("agentplay.pipeline")+++@dataclass+class BuildReport:+ found: int = 0+ built: int = 0+ unchanged: int = 0+ skipped: int = 0+ skip_reasons: Counter = field(default_factory=Counter)+ failed: int = 0+ decoded: dict[str, int] = field(default_factory=dict)+ by_agent: Counter = field(default_factory=Counter)+ seconds: float = 0.0+ errors: list[str] = field(default_factory=list)++ def skip(self, reason: str, n: int = 1) -> None:+ """Count ``n`` sessions or files left out of the run, and why."""+ self.skipped += n+ self.skip_reasons[reason] += n+++def _row(+ doc: dict[str, Any],+ cand: discover.Candidate,+ title: str | None,+ task_titles: list[str | None] | None = None,+) -> dict[str, Any]:+ s = builder.summary(doc)+ started = s.get("startedAt") or ""+ ended = None+ try:+ t0 = datetime.fromisoformat(started.replace("Z", "+00:00"))+ ended = datetime.fromtimestamp(t0.timestamp() + (s.get("durationMs") or 0) / 1000, tz=UTC).strftime(+ "%Y-%m-%dT%H:%M:%SZ")+ except ValueError:+ pass+ return {+ **s,+ "sessionId": doc["session"]["id"],+ "sessionDate": started[:10] or None,+ "endedAt": ended,+ "sessionTitle": title,+ "taskTitles": task_titles,+ "contentHash": builder.content_hash(doc),+ "bytesGz": None,+ "updatedAt": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),+ "sourceMtime": cand.mtime,+ "sourcePath": cand.path,+ "builtWith": __version__,+ "pathMode": (doc.get("session") or {}).get("pathMode") or "relative",+ }+++def _sync_titles(store: Store, cand: discover.Candidate, source: Any, *, titles: bool) -> bool:+ """Bring an unchanged session's stored titles in line with this run's ``titles``.++ ``--no-titles`` is a per-run switch, not a stored preference, so it has to+ work in both directions on a session the build path never reaches:++ * **off clears** what earlier runs stored. The first prompt and every task+ label are prompt text sitting in the index, and an opt-out that only+ covers sessions built from here on leaves all of it there, still served+ with every local map. The switch has to reach data already on disk or it+ is not a privacy switch.+ * **on fills** a row that has none: the shape of a row written before task+ titles existed, and the shape a ``--no-titles`` run leaves behind.+ Without this such a row keeps rendering "Task 2" until its transcript+ changes or the user runs ``--rebuild``.++ Only the unchanged path needs this. A rebuilt session gets a whole new row+ from :func:`_row`, which already honours ``titles``. Titles live only in+ the index, so neither direction touches a map document.++ "Unfilled" means ``None`` as well as absent, and that is what lets the two+ directions compose: a cleared row has to be indistinguishable from one+ written before titles existed, or the next default run would read its own+ clearing as "already done" and never put the labels back. The cost is that+ a session whose prompts clean down to nothing is re-read once per run; the+ alternative is a stored ``None`` no later run can tell apart from an+ opt-out, which is the bug this replaces.++ Args:+ store: the store holding the row (mutated in place; the caller saves).+ cand: the discovered session whose row is being synced.+ source: the shared span source, for agents read through it.+ titles: whether this run keeps local titles at all.++ Returns:+ True when the row was changed, False when it already matched this run's+ ``titles`` or there is no row for this session.+ """+ row = store.index.get(cand.session_id)+ if row is None:+ return False+ if not titles:+ if row.get("sessionTitle") is None and row.get("taskTitles") is None:+ return False+ row["sessionTitle"] = None+ row["taskTitles"] = None+ return True+ changed = False+ if row.get("sessionTitle") is None:+ row["sessionTitle"] = discover.local_title(cand, source)+ changed = True+ if row.get("taskTitles") is None:+ row["taskTitles"] = discover.local_task_titles(cand, source)+ changed = True+ return changed+++def build_all(+ *,+ agents: set[str] | None = None,+ since: datetime | None = None,+ rebuild: bool = False,+ path_mode: str = "relative",+ limit: int | None = None,+ titles: bool = True,+ progress: Callable[[int, int, str], None] | None = None,+ store: Store | None = None,+) -> BuildReport:+ """Discover sessions and (re)build their maps into the local store.++ Args:+ agents: agent names to include (default: all supported).+ since: only sessions whose transcript changed at or after this time.+ rebuild: ignore the incremental check and rebuild everything selected.+ path_mode: ``relative`` | ``dirs_only`` | ``hashed`` (see the format spec).+ limit: newest N sessions only.+ titles: keep a local title (Claude Code's own title, else the first prompt,+ truncated) and one label per task in the index for the session list.+ Never written into maps. Per run, not a stored preference: off also+ clears what earlier runs stored for the sessions this run sees, and+ on puts it back.+ progress: ``callback(done, total, session_id)``.+ store: target store (default ``~/.agentplay``).+ """+ t0 = time.monotonic()+ store = store or Store()+ agents = set(agents or discover.AGENTS)+ homes = discover.Homes.default()+ report = BuildReport()+ key = os.environ.get("AGENTPLAY_HMAC_KEY", "")+ hmac_key = key.encode("utf-8") if key else None+ # What the builder will actually emit: `hashed` without a key falls back.+ effective_mode = "dirs_only" if path_mode == "hashed" and not hmac_key else path_mode+ report.decoded = discover.materialize_all(homes, agents)+ source = discover.local_source(homes, agents)+ cands = [c for c in discover.candidates(source, since=since) if c.agent in agents or not c.agent]+ if limit:+ cands = cands[:limit]+ report.found = len(cands)+ # Files the walk set aside before they became candidates. Another agent's+ # file (picked up by that agent's own walk) and a subagent transcript (folded+ # into its parent session) are not sessions, so they are not skips. The walk+ # covers the whole disk, so a --since/--limit run has no skips of this kind+ # to report: they belong to sessions outside its scope.+ if since is None and not limit:+ for walk in source.discovery_stats().values():+ for reason, n in walk["skipped"].items():+ if reason not in ("different_agent", "subagent_component"):+ report.skip(reason, n)+ for i, c in enumerate(cands):+ if progress:+ progress(i, len(cands), c.session_id)+ if not rebuild and store.is_fresh(c.session_id, c.mtime, built_with=__version__, path_mode=effective_mode):+ report.unchanged += 1+ report.by_agent[c.agent] += 1+ _sync_titles(store, c, source, titles=titles)+ continue+ try:+ doc = discover.build_map(c, source, path_mode=path_mode, hmac_key=hmac_key, version=__version__)+ except discover.SkipSession as exc:+ report.skip(str(exc))+ continue+ except Exception as exc: # noqa: BLE001 - one bad transcript must not stop the run+ report.failed += 1+ report.errors.append(f"{c.session_id}: {type(exc).__name__}: {exc}")+ logger.debug("build failed for %s", c.session_id, exc_info=True)+ continue+ if not doc.get("events"):+ report.skip("empty_events")+ continue+ doc["session"]["id"] = c.session_id if not doc["session"].get("id") else doc["session"]["id"]+ title = discover.local_title(c, source) if titles else None+ task_titles = discover.local_task_titles(c, source) if titles else None+ store.put(doc, _row(doc, c, title, task_titles))+ report.built += 1+ report.by_agent[c.agent] += 1+ store.save_index()+ if progress:+ progress(len(cands), len(cands), "")+ report.seconds = round(time.monotonic() - t0, 2)+ return reportdiff --git a/python/src/agentplay/prompt_images.py b/python/src/agentplay/prompt_images.pynew file mode 100644index 0000000..3f79705--- /dev/null+++ b/python/src/agentplay/prompt_images.py@@ -0,0 +1,242 @@+"""Images pasted into Claude Code prompts, read on demand and never persisted.++A map carries only an ``images`` count per user turn. To show the pictures+themselves the local server opens the original transcript when the viewer asks+and returns the bytes for that one image. Nothing here writes to a map, the+index, an export or disk: the scan below caches *metadata and a line number*+(never image data), and a read re-parses that single line.++Turns are numbered by :func:`agentplay.builder.user_turns`, exactly as the+builder numbers its ``user`` events and :func:`agentplay.discover.local_task_titles`+labels them, so turn ``k`` here is the task whose ``firstTurn`` is ``k`` and a+viewer can pair an image with a task without any index of its own.++Callers (the server) decide who may ask. This module trusts the path it is given.+"""++from __future__ import annotations++import base64+import binascii+import functools+import itertools+import json+import os+from typing import Any, NamedTuple++from .builder import user_turn_text, user_turns++MEDIA_TYPES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"})+MAX_IMAGE_BYTES = 10 * 1024 * 1024+"""Largest decoded image served. Checked on the base64 length, before decoding."""++_PREFIX_CHARS = 16 # a multiple of 4: 12 decoded bytes, enough for every magic number below+++class Unavailable(Exception):+ """An image that cannot be served, with the HTTP status and error code to report.++ The message is a fixed string: it never names a path or echoes transcript data.+ """++ def __init__(self, status: int, code: str, message: str) -> None:+ super().__init__(message)+ self.status = status+ self.code = code+ self.message = message+++def _not_found() -> Unavailable:+ return Unavailable(404, "not_found", "We couldn't find that image.")+++def _gone() -> Unavailable:+ return Unavailable(410, "gone", "The transcript for this session is no longer on this machine.")+++def _invalid() -> Unavailable:+ return Unavailable(422, "invalid_image", "That image can't be shown.")+++class _Image(NamedTuple):+ i: int+ paste_id: int | None+ media_type: str | None+ available: bool+++class _Turn(NamedTuple):+ turn: int+ line: int # 0-based line index in the transcript+ images: tuple[_Image, ...]+++def _sniff(data: bytes) -> str | None:+ """Media type implied by the leading bytes of an image, or None if unrecognised."""+ if data.startswith(b"\x89PNG\r\n\x1a\n"):+ return "image/png"+ if data.startswith(b"\xff\xd8\xff"):+ return "image/jpeg"+ if data.startswith((b"GIF87a", b"GIF89a")):+ return "image/gif"+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":+ return "image/webp"+ return None+++def _image_blocks(rec: dict[str, Any]) -> list[dict[str, Any]]:+ message = rec.get("message")+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, list):+ return []+ return [x for x in content if isinstance(x, dict) and x.get("type") == "image"]+++def _source(block: dict[str, Any]) -> dict[str, Any] | None:+ """The block's ``base64`` source, or None for a URL/file source or a malformed block."""+ source = block.get("source")+ if isinstance(source, dict) and source.get("type") == "base64":+ return source+ return None+++def _matches_media_type(source: dict[str, Any]) -> bool:+ """Whether the declared media type is allowed and the first bytes agree with it."""+ media_type, data = source.get("media_type"), source.get("data")+ if not isinstance(media_type, str) or media_type not in MEDIA_TYPES or not isinstance(data, str):+ return False+ try:+ head = base64.b64decode(data[:_PREFIX_CHARS], validate=True)+ except (binascii.Error, ValueError):+ return False+ return _sniff(head) == media_type+++def _paste_ids(rec: dict[str, Any], count: int) -> list[int | None]:+ ids = rec.get("imagePasteIds")+ if (+ isinstance(ids, list)+ and len(ids) == count+ and all(isinstance(x, int) and not isinstance(x, bool) for x in ids)+ ):+ return list(ids)+ return [None] * count+++def _stat(path: str) -> os.stat_result:+ try:+ return os.stat(path)+ except FileNotFoundError:+ raise _gone() from None++[email protected]_cache(maxsize=16)+def _scan(path: str, mtime_ns: int, size: int) -> tuple[_Turn, ...]:+ """Metadata for every turn with an image block. Holds no image data.++ ``mtime_ns`` and ``size`` are only the cache key: a transcript that grows+ gets a fresh scan.+ """+ turns: list[_Turn] = []+ with open(path, encoding="utf-8", errors="replace") as fh:+ records = user_turns(fh)+ for n, (line_no, rec, _) in enumerate(records, start=1):+ blocks = _image_blocks(rec)+ if not blocks:+ continue+ ids = _paste_ids(rec, len(blocks))+ images = []+ for i, block in enumerate(blocks):+ source = _source(block)+ images.append(+ _Image(+ i=i,+ paste_id=ids[i],+ media_type=source.get("media_type") if source else None,+ available=source is not None and _matches_media_type(source),+ )+ )+ turns.append(_Turn(turn=n, line=line_no, images=tuple(images)))+ return tuple(turns)+++def _scan_file(path: str) -> tuple[_Turn, ...]:+ st = _stat(path)+ try:+ return _scan(path, st.st_mtime_ns, st.st_size)+ except FileNotFoundError:+ raise _gone() from None+ except OSError:+ raise _not_found() from None+++def list_images(path: str) -> list[dict[str, Any]]:+ """Per-turn image metadata for a transcript, only for turns that have images.++ Raises:+ Unavailable: 410 if the transcript is gone.+ """+ return [+ {+ "turn": t.turn,+ "images": [+ {"i": im.i, "pasteId": im.paste_id, "mediaType": im.media_type, "available": im.available}+ for im in t.images+ ],+ }+ for t in _scan_file(path)+ ]+++def read_image(path: str, turn: int, index: int) -> tuple[str, bytes]:+ """Decode one pasted image from the transcript.++ Args:+ path: the transcript ``.jsonl``.+ turn: 1-based user-turn number, as in :func:`list_images`.+ index: 0-based position among that turn's image blocks.++ Returns:+ ``(media_type, bytes)``, the type being the sniffed one.++ Raises:+ Unavailable: 410 if the transcript is gone; 404 for an unknown turn or+ index or a block whose source is not inline base64; 422 for a+ disallowed media type, invalid base64, bytes that are not the declared+ type, or an image over ``MAX_IMAGE_BYTES``.+ """+ entry = next((t for t in _scan_file(path) if t.turn == turn), None)+ if entry is None or not 0 <= index < len(entry.images):+ raise _not_found()+ try:+ with open(path, encoding="utf-8", errors="replace") as fh:+ line = next(itertools.islice(fh, entry.line, None), "")+ except FileNotFoundError:+ raise _gone() from None+ except OSError:+ raise _not_found() from None+ try:+ rec = json.loads(line)+ except ValueError:+ raise _not_found() from None+ # The file may have changed since the scan; trust nothing the cached line says.+ if user_turn_text(rec) is None:+ raise _not_found()+ blocks = _image_blocks(rec)+ if index >= len(blocks):+ raise _not_found()+ source = _source(blocks[index])+ if source is None:+ raise _not_found()+ media_type, data = source.get("media_type"), source.get("data")+ if not isinstance(media_type, str) or media_type not in MEDIA_TYPES or not isinstance(data, str):+ raise _invalid()+ if len(data) * 3 // 4 - data[-2:].count("=") > MAX_IMAGE_BYTES:+ raise _invalid()+ try:+ raw = base64.b64decode(data, validate=True)+ except (binascii.Error, ValueError):+ raise _invalid() from None+ if _sniff(raw) != media_type:+ raise _invalid()+ return media_type, rawdiff --git a/python/src/agentplay/server.py b/python/src/agentplay/server.pynew file mode 100644index 0000000..564047a--- /dev/null+++ b/python/src/agentplay/server.py@@ -0,0 +1,515 @@+"""Local viewer server: the bundled web viewer plus a small read-only JSON API.++Binds to 127.0.0.1 only. Serves the static viewer from the package's+``viewer/`` directory and these endpoints over the local store:++``GET /api/status`` ``{available, mapCount, latestSessionDate}``+``GET /api/sessions`` paged session rows (``from``, ``to``, ``search``, ``pageSize``, ``cursor``)+``GET /api/map`` one entry per ``session_id`` param, each with a ``url``+``GET /api/map-doc?id=...`` the map document itself+``GET /api/account`` whether to offer the email signup card (see ``account.py``)+``GET /api/prompt-images?id=...`` per-turn metadata for images pasted into Claude Code prompts (this machine only)+``GET /api/prompt-image?id=...&turn=...&i=...`` one such image, read from the transcript on demand (this machine only)+``GET /api/hook-detail?id=...&uuid=...`` the message and command of one hook failure, read from the transcript on demand (this machine only)+``POST /api/account`` ``{"action": "signup", "email": ...}``, ``{"action": "skip"}``, ``{"action": "disconnect"}``++Pasted images are read from the original transcript when asked for and never+stored in a map, the index or an export; see ``prompt_images.py``. Hook failure+messages and commands are read the same way; see ``hook_detail.py``.++The only write is ``~/.agentplay/account.json``, and the only thing that can leave+the machine is an email the user typed into the signup card.+"""++from __future__ import annotations++import base64+import hashlib+import ipaddress+import json+import mimetypes+import os+import re+import threading+from http import HTTPStatus+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from importlib import resources+from pathlib import Path+from typing import Any+from urllib.parse import parse_qs, quote, urlsplit++from . import account, hook_detail, prompt_images+from .store import Store++MAX_PAGE = 200+DEFAULT_PAGE = 50+MAX_BODY = 4096+_LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"}+# Extra origins allowed to post (comma-separated), e.g. the viewer's Vite dev+# server at http://localhost:5173. Nothing else but this server's own origin.+DEV_ORIGINS_ENV = "AGENTPLAY_DEV_ORIGINS"+_FETCH_SITES = {"same-origin", "none"}+_INLINE_SCRIPT_RE = re.compile(rb"<script>(.*?)</script>", re.S)+++def viewer_root() -> Path | None:+ """Directory holding the built viewer (``index.html``), or None if not bundled."""+ try:+ root = Path(str(resources.files("agentplay") / "viewer"))+ except (ModuleNotFoundError, TypeError):+ return None+ return root if (root / "index.html").is_file() else None+++def _cursor_encode(offset: int) -> str:+ return base64.urlsafe_b64encode(json.dumps({"o": offset}).encode()).decode().rstrip("=")+++def _cursor_decode(raw: str | None) -> int | None:+ """The offset in a cursor from ``_cursor_encode``, 0 for none, None if it is not one."""+ if not raw:+ return 0+ try:+ pad = "=" * (-len(raw) % 4)+ return max(0, int(json.loads(base64.urlsafe_b64decode(raw + pad))["o"]))+ except (ValueError, KeyError, TypeError, OverflowError): # OverflowError: {"o": 1e999}+ return None+++_UUID_RE = re.compile(r"[A-Za-z0-9-]{1,64}")+++def _non_negative_int(raw: str) -> int | None:+ """``raw`` as an int if it is 1-9 plain ASCII digits, else None (no sign, space or underscore)."""+ return int(raw) if 0 < len(raw) <= 9 and raw.isascii() and raw.isdigit() else None+++def _public_row(row: dict[str, Any]) -> dict[str, Any]:+ return {+ k: v+ for k, v in row.items()+ if k not in ("key", "sourcePath", "sourceMtime", "signals", "imported", "taskTitles")+ }+++def _is_loopback(address: Any) -> bool:+ """Whether a peer address belongs to this machine's loopback interface.++ Fails closed: anything unparseable is treated as remote.++ Args:+ address: a ``(host, port, ...)`` tuple as ``client_address`` gives it,+ or a bare host string.++ Returns:+ True for ``127.0.0.0/8``, ``::1`` and IPv4-mapped forms of them.+ """+ host = address[0] if isinstance(address, tuple) and address else address+ try:+ ip = ipaddress.ip_address(str(host).split("%", 1)[0])+ except ValueError:+ return False+ return (getattr(ip, "ipv4_mapped", None) or ip).is_loopback+++def _local_origin(value: str | None) -> bool:+ """Whether a ``Host`` value names this machine (any port).++ Any port, because the viewer's dev server proxies to this one with its own+ Host. ``Origin`` is held to a stricter rule: see ``_Handler._allowed_origin``.+ """+ if not value:+ return False+ try:+ parts = urlsplit(value if "//" in value else f"//{value}")+ host, _ = parts.hostname or "", parts.port # `.port` raises on a bad or out-of-range port+ except ValueError:+ return False+ return (f"[{host}]" if ":" in host else host) in _LOCAL_HOSTS+++def _with_task_titles(doc: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]:+ """Label a served map's tasks from the local index.++ Task labels are prompt text, so they live in the index and are merged here, at+ serve time, rather than being built into the map. `store.get` keeps returning a+ map with no prompt text in it, which is what `agentplay export` writes and what+ the format contract promises — see `discover.local_task_titles`.++ Callers must merge only for a loopback peer (`_is_loopback`): the API is+ unauthenticated, so on a server bound to a non-loopback host this would hand+ the user's prompt text to anyone who can reach the port.++ Only fills a task whose name is empty, so a name the builder derived from a+ named span still wins.+ """+ titles = row.get("taskTitles")+ tasks = doc.get("tasks")+ if not titles or not tasks:+ return doc+ out = []+ for t in tasks:+ turn = t.get("firstTurn")+ if not t.get("name") and isinstance(turn, int) and 1 <= turn <= len(titles):+ label = titles[turn - 1]+ if label:+ t = {**t, "name": label}+ out.append(t)+ return {**doc, "tasks": out}+++def _page_csp(html: bytes) -> str:+ """The viewer's Content-Security-Policy, allowing exactly the inline scripts ``html`` carries.++ The only inline script is the theme-before-first-paint snippet in+ ``index.html``; hashing it at serve time keeps the policy right when it changes.+ Styles stay ``'unsafe-inline'``: the UI libraries set ``style`` attributes and+ inject positioning styles. Fonts are bundled, some as ``data:`` URLs in the CSS.+ """+ hashes = " ".join(+ "'sha256-" + base64.b64encode(hashlib.sha256(m).digest()).decode() + "'"+ for m in _INLINE_SCRIPT_RE.findall(html)+ )+ return (+ f"default-src 'self'; script-src 'self' {hashes}".rstrip() + "; "+ "style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; "+ "connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"+ )+++class _Server(ThreadingHTTPServer):+ # The default backlog of 5 resets connections when the viewer fires a burst+ # of requests (about ten at once on a cold load).+ request_queue_size = 128+++class _Handler(BaseHTTPRequestHandler):+ server_version = "agentplay"+ # A client that stalls mid-request gives up its thread instead of holding it forever.+ timeout = 15+ store: Store+ static: Path | None+ lock = threading.Lock()++ def log_message(self, fmt: str, *args: Any) -> None: # quiet by default+ return++ # ------------------------------------------------------------------ io+ def end_headers(self) -> None:+ # On every response, http.server's own error pages included.+ self.send_header("X-Content-Type-Options", "nosniff")+ self.send_header("X-Frame-Options", "DENY")+ self.send_header("Referrer-Policy", "no-referrer")+ super().end_headers()++ def _json(self, body: Any, status: int = 200) -> None:+ data = json.dumps(body, separators=(",", ":")).encode("utf-8")+ self.send_response(status)+ self.send_header("Content-Type", "application/json; charset=utf-8")+ self.send_header("Content-Length", str(len(data)))+ self.send_header("Cache-Control", "no-store")+ self.send_header("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")+ self.send_header("Cross-Origin-Resource-Policy", "same-origin")+ self.end_headers()+ self.wfile.write(data)++ def _bytes(self, content_type: str, data: bytes) -> None:+ """Send a user's image: private, and inert if a browser is steered into rendering it as a page."""+ self.send_response(200)+ self.send_header("Content-Type", content_type)+ self.send_header("Content-Length", str(len(data)))+ self.send_header("Content-Security-Policy", "default-src 'none'; sandbox")+ self.send_header("Cross-Origin-Resource-Policy", "same-origin")+ self.send_header("Cache-Control", "private, max-age=3600")+ self.end_headers()+ self.wfile.write(data)++ def _error(self, status: int, code: str, message: str) -> None:+ self._json({"success": False, "code": code, "error": message}, status)++ def _static(self, path: str) -> None:+ if self.static is None:+ self._error(404, "not_found", "The viewer is not bundled in this install. Build it with `make viewer`.")+ return+ rel = path.lstrip("/") or "index.html"+ root = self.static.resolve()+ try:+ target = (root / rel).resolve()+ found = target.is_relative_to(root) and target.is_file()+ except (OSError, ValueError): # e.g. a name too long for the filesystem+ found = False+ if not found:+ target = root / "index.html" # SPA fallback+ data = target.read_bytes()+ ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream"+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(len(data)))+ # Only an HTML page runs anything, so only it needs the script hashes.+ html = data if target.suffix == ".html" else b""+ self.send_header("Content-Security-Policy", _page_csp(html))+ self.end_headers()+ self.wfile.write(data)++ def _from_this_machine(self) -> bool:+ """Whether a read may include the user's own data (task labels, the email).++ A loopback peer is not enough: a DNS-rebinding page reaches 127.0.0.1 under+ its own hostname and reads the answer as same-origin. So the Host must name+ this machine, and so must the Origin whenever a browser sends one.+ """+ origin = self.headers.get("Origin")+ return (_is_loopback(self.client_address) and _local_origin(self.headers.get("Host"))+ and (origin is None or self._allowed_origin(origin)))++ def _allowed_origin(self, origin: str | None) -> bool:+ """Whether ``origin`` is this server's own, or one listed in ``AGENTPLAY_DEV_ORIGINS``.++ Not any local port: another local web app (or anything a page can make+ listen on localhost) would otherwise be trusted too.+ """+ if not origin:+ return False+ port = self.server.server_address[1]+ allowed = {f"http://{h}:{port}" for h in _LOCAL_HOSTS}+ allowed.update(o.strip().rstrip("/").lower() for o in os.environ.get(DEV_ORIGINS_ENV, "").split(","))+ allowed.discard("")+ return origin.strip().lower() in allowed++ # ------------------------------------------------------------------ routes+ def do_GET(self) -> None: # noqa: N802 - http.server naming+ # Every read is the user's own data (session titles are prompt text, maps+ # name private repos and files), so a DNS-rebinding page gets nothing.+ if not self._from_this_machine():+ return self._error(403, "forbidden", "Only the local viewer can read this.")+ url = urlsplit(self.path)+ q = parse_qs(url.query)+ # A browser labels every fetch with where it came from. The viewer's own+ # calls are same-origin; anything else (an <img> or <script> on another+ # site) gets nothing. Pages stay open to a typed URL or a link.+ site = self.headers.get("Sec-Fetch-Site")+ if url.path.startswith("/api/") and site is not None and site.lower() not in _FETCH_SITES:+ return self._error(403, "forbidden", "Only the local viewer can read this.")+ if url.path.startswith("/api/"):+ # `agentplay view` scans in the background, so the index can change+ # while we are serving. Cheap: one stat unless it actually moved.+ with self.lock:+ self.store.reload_if_changed()+ try:+ if url.path == "/api/status":+ return self._status()+ if url.path == "/api/sessions":+ return self._sessions(q)+ if url.path == "/api/map":+ return self._maps(q)+ if url.path == "/api/map-doc":+ return self._map_doc(q)+ if url.path == "/api/prompt-images":+ return self._prompt_images(q)+ if url.path == "/api/prompt-image":+ return self._prompt_image(q)+ if url.path == "/api/hook-detail":+ return self._hook_detail(q)+ if url.path == "/api/account":+ # The email is the user's: only the viewer on this machine sees it,+ # and only it is ever offered the card.+ if not self._from_this_machine():+ return self._json({"success": True, "status": "none", "email": None, "enabled": False})+ return self._json({"success": True, **account.public_state()})+ if url.path.startswith("/api/"):+ return self._error(404, "not_found", "Unknown endpoint.")+ return self._static(url.path)+ except BrokenPipeError:+ return None+ except Exception: # noqa: BLE001 - never leak a traceback to the page+ return self._error(500, "internal_error", "Something went wrong reading your local sessions.")++ def do_POST(self) -> None: # noqa: N802 - http.server naming+ url = urlsplit(self.path)+ if url.path != "/api/account":+ return self._error(404, "not_found", "Unknown endpoint.")+ # The only write this server takes. A browser on another site can reach+ # 127.0.0.1, so: same machine, a local Origin and Host (no DNS rebinding),+ # and a JSON body, which a cross-site form can't send without a preflight+ # this server never answers.+ if not (_is_loopback(self.client_address) and self._allowed_origin(self.headers.get("Origin"))+ and _local_origin(self.headers.get("Host"))):+ return self._error(403, "forbidden", "Only the local viewer can do this.")+ if (self.headers.get("Content-Type") or "").split(";")[0].strip().lower() != "application/json":+ return self._error(415, "unsupported_media_type", "Send JSON.")+ try:+ size = int(self.headers.get("Content-Length") or 0)+ except ValueError:+ size = -1+ if not 0 < size <= MAX_BODY:+ return self._error(400, "invalid_input", "Bad request body.")+ try:+ body = json.loads(self.rfile.read(size))+ except ValueError:+ return self._error(400, "invalid_input", "Bad request body.")+ action = body.get("action") if isinstance(body, dict) else None+ try:+ if action == "skip":+ return self._json({"success": True, **account.skip()})+ if action == "disconnect":+ return self._json({"success": True, **account.disconnect()})+ if action == "signup":+ email = str(body.get("email") or "").strip()+ if not account.valid_email(email):+ return self._error(400, "invalid_email", "That doesn't look like an email address.")+ try:+ return self._json({"success": True, **account.sign_up(email)})+ except (OSError, ValueError):+ return self._error(502, "unreachable", "We couldn't reach Entelligence. Check your connection and try again.")+ return self._error(400, "invalid_input", "Unknown action.")+ except BrokenPipeError:+ return None+ except Exception: # noqa: BLE001 - never leak a traceback to the page+ return self._error(500, "internal_error", "Something went wrong saving that.")++ def _rows(self) -> list[dict[str, Any]]:+ with self.lock:+ return [r for r in self.store.rows() if r.get("role") not in ("subagent", "helper")]++ def _status(self) -> None:+ rows = self._rows()+ latest = max((r.get("sessionDate") or "" for r in rows), default="") or None+ self._json({"success": True, "available": bool(rows), "mapCount": len(rows), "latestSessionDate": latest})++ def _sessions(self, q: dict[str, list[str]]) -> None:+ rows = self._rows()+ lo = (q.get("from") or [""])[0]+ hi = (q.get("to") or [""])[0]+ search = (q.get("search") or [""])[0].strip().lower()+ try:+ size = min(MAX_PAGE, max(1, int((q.get("pageSize") or [DEFAULT_PAGE])[0])))+ except ValueError:+ size = DEFAULT_PAGE+ out = []+ for r in rows:+ day = r.get("sessionDate") or ""+ if lo and day and day < lo:+ continue+ if hi and day and day > hi:+ continue+ if search:+ hay = " ".join(+ [str(r.get("sessionTitle") or ""), str(r.get("sessionId") or ""), str(r.get("agentTool") or ""),+ " ".join(map(str, r.get("repos") or [])), " ".join(map(str, r.get("models") or []))]+ ).lower()+ if search not in hay:+ continue+ out.append(r)+ start = _cursor_decode((q.get("cursor") or [None])[0])+ if start is None:+ return self._error(400, "invalid_input", "That page cursor is not valid.")+ page = out[start:start + size]+ more = start + size < len(out)+ self._json({+ "success": True,+ "sessions": [_public_row(r) for r in page],+ "nextCursor": _cursor_encode(start + size) if more else None,+ "hasMore": more,+ })++ def _maps(self, q: dict[str, list[str]]) -> None:+ ids = (q.get("session_id") or [])[:20]+ if not ids:+ return self._error(400, "invalid_input", "Pass at least one session_id.")+ index = self.store.index+ maps = []+ for sid in ids:+ row = index.get(sid)+ if row is None:+ maps.append({"sessionId": sid, "status": "not_found"})+ continue+ maps.append({+ "sessionId": sid,+ "url": f"/api/map-doc?id={quote(sid, safe='')}",+ "schemaVersion": 1,+ "contentHash": row.get("contentHash") or sid,+ "bytesGz": None,+ })+ self._json({"success": True, "expiresIn": 3600, "maps": maps})++ def _map_doc(self, q: dict[str, list[str]]) -> None:+ sid = (q.get("id") or [""])[0]+ doc = self.store.get(sid)+ if doc is None:+ return self._error(404, "not_found", "We couldn't find that session.")+ # Task labels are prompt text and the API is unauthenticated: a network+ # client gets the stored map, which carries none.+ if self._from_this_machine():+ doc = _with_task_titles(doc, self.store.index.get(sid) or {})+ self._json(doc)++ def _image_source(self, sid: str) -> str | None:+ """Transcript path for a session whose transcript extras may be read, else None after replying.++ Pasted images and hook failure details are the user's own data, so only+ the viewer on this machine gets them. Only a Claude Code session built from a local transcript has any:+ the path comes from the index row alone, never from the request.+ """+ if not self._from_this_machine():+ self._error(403, "forbidden", "Only the local viewer can read this.")+ return None+ if not sid:+ self._error(400, "invalid_input", "Missing session id.")+ return None+ row = self.store.index.get(sid) or {}+ path = row.get("sourcePath")+ if (row.get("imported") or row.get("agentTool") != "claude-code"+ or not isinstance(path, str) or not path.endswith(".jsonl")):+ self._error(404, "not_found", "We couldn't find that session.")+ return None+ return path++ def _prompt_images(self, q: dict[str, list[str]]) -> None:+ path = self._image_source((q.get("id") or [""])[0])+ if path is None:+ return+ try:+ turns = prompt_images.list_images(path)+ except prompt_images.Unavailable as e:+ return self._error(e.status, e.code, e.message)+ self._json({"success": True, "turns": turns})++ def _prompt_image(self, q: dict[str, list[str]]) -> None:+ path = self._image_source((q.get("id") or [""])[0])+ if path is None:+ return+ turn, index = (_non_negative_int((q.get(k) or [""])[0]) for k in ("turn", "i"))+ if turn is None or index is None:+ return self._error(400, "invalid_input", "turn and i must be non-negative integers.")+ try:+ content_type, data = prompt_images.read_image(path, turn, index)+ except prompt_images.Unavailable as e:+ return self._error(e.status, e.code, e.message)+ self._bytes(content_type, data)++ def _hook_detail(self, q: dict[str, list[str]]) -> None:+ path = self._image_source((q.get("id") or [""])[0])+ if path is None:+ return+ uuid = (q.get("uuid") or [""])[0]+ if not _UUID_RE.fullmatch(uuid):+ return self._error(400, "invalid_input", "uuid must be a transcript record id.")+ try:+ message, command = hook_detail.read_hook_detail(path, uuid)+ except prompt_images.Unavailable as e:+ return self._error(e.status, e.code, e.message)+ self._json({"success": True, "message": message, "command": command})+++def serve(port: int = 7317, *, store: Store | None = None, host: str = "127.0.0.1") -> ThreadingHTTPServer:+ """Create (but do not start) the local server. Call ``serve_forever()`` on the result."""+ handler = type("Handler", (_Handler,), {"store": store or Store(), "static": viewer_root()})+ try:+ return _Server((host, port), handler)+ except OSError:+ if port == 0:+ raise+ return _Server((host, 0), handler) # port taken: pick a free one+++__all__ = ["serve", "viewer_root", "HTTPStatus"]diff --git a/python/src/agentplay/store.py b/python/src/agentplay/store.pynew file mode 100644index 0000000..f3064e4--- /dev/null+++ b/python/src/agentplay/store.py@@ -0,0 +1,181 @@+"""The local map store: ``~/.agentplay/maps`` plus a JSON index.++Layout (override the root with ``AGENTPLAY_HOME``)::++ ~/.agentplay/+ index.json session_id -> index row (summary, hash, source mtime)+ maps/<key>.json one agentplay/v1 document per session+ cache/<agent>/... decoded transcripts for database-backed agents++Builds are incremental: a session is rebuilt only when its transcript's mtime+changed since the stored build (or ``--rebuild`` is passed).+"""++from __future__ import annotations++import hashlib+import json+import os+import re+import tempfile+from collections.abc import Iterator+from pathlib import Path+from typing import Any++INDEX_VERSION = 1+++def root() -> Path:+ return Path(os.environ.get("AGENTPLAY_HOME") or Path.home() / ".agentplay")+++def _atomic_write(path: Path, data: bytes) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")+ try:+ with os.fdopen(fd, "wb") as fh:+ fh.write(data)+ os.replace(tmp, path)+ except BaseException:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+++# What `map_key` produces. A key read back from the index is checked against it,+# so a hand-edited or planted index can't point a read outside `maps/`.+_KEY_RE = re.compile(r"[A-Za-z0-9._-]{1,80}-[0-9a-f]{10}")+++def map_key(session_id: str) -> str:+ """Filesystem-safe, collision-free file stem for a session id."""+ safe = re.sub(r"[^A-Za-z0-9._-]+", "_", session_id)[:80]+ digest = hashlib.sha256(session_id.encode("utf-8")).hexdigest()[:10]+ return f"{safe}-{digest}"+++class Store:+ """Read/write access to the local index and map files."""++ def __init__(self, base: Path | None = None) -> None:+ self.base = base or root()+ self.maps_dir = self.base / "maps"+ self.index_path = self.base / "index.json"+ self._index: dict[str, dict[str, Any]] | None = None+ self._index_stamp: tuple[int, int] | None = None++ # ------------------------------------------------------------------ index+ @property+ def index(self) -> dict[str, dict[str, Any]]:+ index = self._index+ if index is None:+ try:+ raw = json.loads(self.index_path.read_text(encoding="utf-8"))+ index = raw.get("sessions", {}) if raw.get("version") == INDEX_VERSION else {}+ except (OSError, ValueError, AttributeError):+ index = {}+ self._index = index+ self._index_stamp = self._disk_stamp()+ return index++ def _disk_stamp(self) -> tuple[int, int] | None:+ # Size as well as mtime: Windows file times tick about every 15 ms, so two+ # writes in a row can share an mtime.+ try:+ st = self.index_path.stat()+ except OSError:+ return None+ return st.st_mtime_ns, st.st_size++ def reload_if_changed(self) -> bool:+ """Drop the cached index when index.json changed underneath us.++ The server holds one Store for its lifetime, and `agentplay view` now scans+ in a background thread, so the index it serves would otherwise be whatever+ existed at startup.++ Explicit rather than a check inside `index`: `build_all` does many `put`s+ before a single `save_index`, and reloading between them would discard+ every pending row.+ """+ if self._index is None:+ return False+ stamp = self._disk_stamp()+ if stamp is None or stamp == self._index_stamp:+ return False+ self._index = None+ return True++ def save_index(self) -> None:+ body = json.dumps({"version": INDEX_VERSION, "sessions": self.index}, separators=(",", ":"))+ _atomic_write(self.index_path, body.encode("utf-8"))+ self._index_stamp = self._disk_stamp()++ def is_fresh(+ self, session_id: str, source_mtime: float, built_with: str | None = None, path_mode: str | None = None+ ) -> bool:+ row = self.index.get(session_id)+ if not row:+ return False+ if row.get("imported"):+ return True # an imported map has no local transcript to rebuild from+ if abs(float(row.get("sourceMtime") or 0) - source_mtime) > 0.5:+ return False+ # A map built by another version is rebuilt once: redaction fixes (and any+ # other change to what a map holds) must reach maps already on disk.+ if built_with is not None and row.get("builtWith") != built_with:+ return False+ # Asking for another path mode (say dirs_only after a relative build) must+ # re-redact maps already on disk, not only new sessions.+ if path_mode is not None and (row.get("pathMode") or "relative") != path_mode:+ return False+ return (self.maps_dir / f"{row['key']}.json").is_file()++ # ------------------------------------------------------------------ maps+ def put(self, doc: dict[str, Any], row: dict[str, Any]) -> None:+ """Store one map document and its index row."""+ sid = doc["session"]["id"]+ key = map_key(sid)+ _atomic_write(self.maps_dir / f"{key}.json", _canonical(doc))+ self.index[sid] = {**row, "key": key}++ def get(self, session_id: str) -> dict[str, Any] | None:+ row = self.index.get(session_id)+ key = row.get("key") if row else None+ if not isinstance(key, str) or not _KEY_RE.fullmatch(key):+ return None+ try:+ maps = self.maps_dir.resolve()+ target = (maps / f"{key}.json").resolve()+ if not target.is_relative_to(maps): # e.g. a symlink planted in maps/+ return None+ return json.loads(target.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None++ def rows(self) -> list[dict[str, Any]]:+ """Index rows, newest first."""+ return sorted(self.index.values(), key=lambda r: r.get("startedAt") or "", reverse=True)++ def docs(self, *, since: str | None = None, main_only: bool = True) -> Iterator[dict[str, Any]]:+ """Stored map documents, newest first.++ Args:+ since: ISO date (YYYY-MM-DD); skip sessions that started earlier.+ main_only: skip subagent and helper sessions (their work is already+ inside the parent map).+ """+ for row in self.rows():+ if since and (row.get("startedAt") or "")[:10] < since:+ continue+ if main_only and row.get("role") in ("subagent", "helper"):+ continue+ doc = self.get(row["sessionId"])+ if doc is not None:+ yield doc+++def _canonical(doc: dict[str, Any]) -> bytes:+ return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")diff --git a/python/tests/core/__init__.py b/python/tests/core/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/python/tests/core/test_claude_code_subagent_edits.py b/python/tests/core/test_claude_code_subagent_edits.pynew file mode 100644index 0000000..d0d64e5--- /dev/null+++ b/python/tests/core/test_claude_code_subagent_edits.py@@ -0,0 +1,173 @@+"""Claude Code subagent edits reach code-authorship replay without becoming tool calls.++Subagent (Agent/Workflow tool) traffic is folded into the parent transcript as+``isSidechain: true`` lines. Its edits ship on the root span's+``code.subagent_edit_calls`` (the envelope's separate ``subagent_edit_calls``+array), never as tool spans, so every span-derived tool metric stays+parent-only. Fixtures mirror real transcript shapes with synthetic content.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources.local.parsers.claude_code import (+ parse_claude_code,+)+from agentplay._core.ingestion.coding_agent.metrics import session_tool_distribution+++def _line(kind: str, at: str, content: list | str, **extra) -> dict:+ return {+ "type": kind,+ "timestamp": f"2026-09-20T10:00:{at}Z",+ "sessionId": "sid",+ "cwd": "/repo",+ "message": {"role": kind, "content": content},+ **extra,+ }+++def _use(call_id: str, name: str, tool_input: dict) -> list[dict]:+ return [{"type": "tool_use", "id": call_id, "name": name, "input": tool_input}]+++def _result(call_id: str, *, error: bool = False) -> list[dict]:+ return [{"type": "tool_result", "tool_use_id": call_id, "content": "ok", "is_error": error}]+++def _edit(path: str) -> tuple[dict, dict]:+ args = {"file_path": path, "old_string": "old", "new_string": "new"}+ native = {+ "filePath": path,+ "oldString": "old",+ "newString": "new",+ "userModified": False,+ "replaceAll": False,+ "structuredPatch": [+ {+ "oldStart": 1,+ "oldLines": 2,+ "newStart": 1,+ "newLines": 2,+ "lines": ["-return old", "+return new", " context"],+ }+ ],+ }+ return args, native+++def _parent() -> list[dict]:+ edit_args, edit_native = _edit("/repo/app.py")+ return [+ _line("user", "00", "ship it"),+ _line(+ "assistant",+ "01",+ _use("toolu_agent", "Agent", {"prompt": "p", "run_in_background": True}),+ ),+ _line(+ "user",+ "02",+ _result("toolu_agent"),+ toolUseResult={"status": "async_launched", "agentId": "a1", "isAsync": True},+ ),+ _line("assistant", "10", _use("toolu_parent_edit", "Edit", edit_args)),+ _line("user", "11", _result("toolu_parent_edit"), toolUseResult=edit_native),+ ]+++def _subagent(agent_id: str = "a1") -> list[dict]:+ edit_args, edit_native = _edit("/repo/lib.py")+ side = {"isSidechain": True, "agentId": agent_id}+ parent_edit_args, _ = _edit("/repo/app.py")+ return [+ _line("user", "02", "subagent prompt", **side),+ _line("assistant", "05", _use("toolu_sub_edit", "Edit", edit_args), **side),+ _line("user", "06", _result("toolu_sub_edit"), toolUseResult=edit_native, **side),+ _line(+ "assistant",+ "20",+ _use("toolu_sub_write", "Write", {"file_path": "/repo/new.py", "content": "x\n"}),+ **side,+ ),+ _line(+ "user",+ "21",+ _result("toolu_sub_write"),+ toolUseResult={"type": "create", "filePath": "/repo/new.py"},+ **side,+ ),+ _line("assistant", "22", _use("toolu_sub_failed", "Edit", edit_args), **side),+ _line("user", "23", _result("toolu_sub_failed", error=True), **side),+ # Claude Code copies a spawning parent message into subagent files: a+ # parent-recorded call id is the parent's, never a subagent edit.+ _line("assistant", "24", _use("toolu_parent_edit", "Edit", parent_edit_args), **side),+ ]+++def _parse(lines: list[dict]):+ data = "\n".join(json.dumps(line) for line in lines).encode()+ return parse_claude_code(data, "t")[1]+++def _tool_spans(spans) -> list[tuple]:+ return [+ (s.span_id, s.attributes["tool.name"], s.status_code)+ for s in spans+ if s.attributes.get("tool.name")+ ]+++def test_subagent_edits_ship_for_replay_without_changing_tool_spans():+ parent_only = _parse(_parent())+ folded = _parse(_parent() + _subagent())++ # Every span-derived tool metric reads `tool.name` spans: unchanged.+ assert _tool_spans(folded) == _tool_spans(parent_only)+ assert session_tool_distribution(folded) == {"Agent": 1, "Edit": 1}+ assert "code.subagent_edit_calls" not in parent_only[0].attributes++ calls = folded[0].attributes["code.subagent_edit_calls"]+ assert [c["native_call_id"] for c in calls] == ["toolu_sub_edit", "toolu_sub_write"]+ assert {c["subagent_id"] for c in calls} == {"a1"}+ assert {c["turn_id"] for c in calls} == {"t:turn:1"}+ assert [[e["operation"] for e in c["edit_evidence"]["edits"]] for c in calls] == [+ ["replace"],+ ["write"],+ ]+ assert all(c["edit_evidence"]["status"] == "captured" for c in calls)+ assert all(json.loads(c["input_value"])["file_path"] for c in calls)+++def test_subagent_edits_keep_their_real_completion_order_around_parent_edits():+ folded = _parse(_parent() + _subagent())+ parent_edit = next(s for s in folded if s.attributes.get("tool.name") == "Edit")+ events = sorted(+ [(parent_edit.end_time.isoformat(), "parent")]+ + [+ (c["completed_at"], c["native_call_id"])+ for c in folded[0].attributes["code.subagent_edit_calls"]+ ]+ )+ # The background subagent's first edit finished before the parent's edit+ # and its second after it; its spawning call had returned at :02.+ assert [name for _, name in events] == ["toolu_sub_edit", "parent", "toolu_sub_write"]+++def test_echoed_call_whose_result_is_only_in_the_sidechain_still_ships():+ edit_args, edit_native = _edit("/repo/echo.py")+ side = {"isSidechain": True, "agentId": "a1"}+ folded = _parse(+ _parent()+ + _subagent()+ + [+ # The call is echoed into the parent, its result is not.+ _line("assistant", "30", _use("toolu_echoed", "Edit", edit_args)),+ _line("assistant", "30", _use("toolu_echoed", "Edit", edit_args), **side),+ _line("user", "31", _result("toolu_echoed"), toolUseResult=edit_native, **side),+ ]+ )+ calls = folded[0].attributes["code.subagent_edit_calls"]+ (echoed,) = (c for c in calls if c["native_call_id"] == "toolu_echoed")+ assert echoed["edit_evidence"]["status"] == "captured"diff --git a/python/tests/core/test_claude_edit_results.py b/python/tests/core/test_claude_edit_results.pynew file mode 100644index 0000000..1f78a10--- /dev/null+++ b/python/tests/core/test_claude_edit_results.py@@ -0,0 +1,416 @@+"""Successful native patches attribute substring edits without inventing line boundaries."""++import json+from copy import deepcopy++import pytest++from agentplay._core.claude_edit_evidence import (+ call_edit_evidence,+ extract_result_edit,+ result_patches,+)+from agentplay._core.code_authorship import attribute_file+from agentplay._core.ingestion.coding_agent._sources.local.parsers.claude_code import parse_claude_code+++def fixture():+ args = {"file_path": "/repo/app.py", "old_string": "old", "new_string": "new"}+ result = {+ "filePath": "/repo/app.py",+ "oldString": "old",+ "newString": "new",+ "userModified": False,+ "replaceAll": False,+ "structuredPatch": [+ {+ "oldStart": 1,+ "oldLines": 2,+ "newStart": 1,+ "newLines": 2,+ "lines": ["-return old", "+return new", " context"],+ }+ ],+ }+ return args, result+++def test_partial_line_native_result_survives_manual_git_and_other_session():+ args, result = fixture()+ evidence = extract_result_edit("Edit", args, result)+ assert evidence["status"] == "captured"+ assert "return new" not in json.dumps(evidence)+ edits = [{**evidence["edits"][0], "session_id": "agent-a", "event_id": "call-a"}]+ args2 = {**args, "old_string": "context", "new_string": "other"}+ result2 = {+ **result,+ "oldString": "context",+ "newString": "other",+ "structuredPatch": [+ {+ "oldStart": 1,+ "oldLines": 2,+ "newStart": 1,+ "newLines": 2,+ "lines": [" return new", "-context", "+other"],+ }+ ],+ }+ edits += [+ {+ **extract_result_edit("Edit", args2, result2)["edits"][0],+ "session_id": "agent-b",+ "event_id": "call-b",+ }+ ]+ assert attribute_file("return old\ncontext\n", "return new\nother\n", edits)["sessions"] == {+ "agent-a": 1,+ "agent-b": 1,+ }+ assert attribute_file("return old\ncontext\n", "manual\nother\n", edits)["sessions"] == {+ "agent-b": 1+ }+ assert (+ attribute_file("unrelated old\ncontext\n", "return new\nother\n", edits)["sessions"] == {}+ )+++ "field,value",+ [+ ("filePath", "/foreign/app.py"),+ ("oldString", "wrong"),+ ("newString", "wrong"),+ ("userModified", True),+ ("userModified", None),+ ("structuredPatch", []),+ ],+)+def test_mismatch_never_yields_evidence(field, value):+ args, result = fixture()+ result[field] = value+ assert extract_result_edit("Edit", args, result) is None+++ "mutation", ["counts", "prefix", "multiline", "overlap", "unicode", "surrogate"]+)+def test_invalid_native_patch_rejected(mutation):+ args, result = fixture()+ h = result["structuredPatch"][0]+ if mutation == "counts":+ h["oldLines"] = 99+ if mutation == "prefix":+ h["lines"][0] = "?old"+ if mutation == "multiline":+ h["lines"][0] = "-old\nspoof"+ if mutation == "overlap":+ result["structuredPatch"].append(deepcopy(h))+ if mutation == "unicode":+ h["lines"][0] = "-old\u2028spoof"+ if mutation == "surrogate":+ h["lines"][0] = "-old\ud800"+ assert extract_result_edit("Edit", args, result) is None+++def transcript(failed=False, pending=False):+ args, result = fixture()+ rows = [+ {"type": "user", "message": {"role": "user", "content": "fix"}},+ {+ "type": "assistant",+ "message": {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "call-a", "name": "Edit", "input": args}],+ },+ },+ ]+ if not pending:+ rows.append(+ {+ "type": "user",+ "toolUseResult": result,+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call-a",+ "content": "done",+ "is_error": failed,+ }+ ],+ },+ }+ )+ return [{**r, "timestamp": "2026-09-14T10:00:00Z"} for r in rows]++[email protected]("failed,pending", [(False, False), (True, False), (False, True)])+def test_real_parser_uses_only_successful_result(failed, pending):+ rows = transcript(failed, pending)+ _, spans = parse_claude_code("\n".join(map(json.dumps, rows)).encode(), "agent-a")+ edit = next(s for s in spans if s.tool_name == "Edit").attributes["code.edit_evidence"]+ assert edit["status"] == ("not_successful" if failed or pending else "captured")+++def test_conflicting_replay_does_not_select_arbitrary_patch():+ rows = transcript()+ other = deepcopy(rows[-1])+ other["toolUseResult"]["filePath"] = "/foreign.py"+ assert result_patches([*rows, other]) == {"call-a": None}+ assert result_patches([*rows, deepcopy(rows[-1])]) == {"call-a": rows[-1]["toolUseResult"]}++[email protected]("first", [True, False])[email protected]("mutation", ["failed", "null", "conflicting", "ambiguous"])+def test_invalid_replay_blocks_native_and_legacy_capture(first, mutation):+ rows = transcript()+ args = rows[1]["message"]["content"][0]["input"]+ args.update(old_string="\nold\n", new_string="\nnew\n")+ rows[-1]["toolUseResult"].update(oldString="\nold\n", newString="\nnew\n")+ other = deepcopy(rows[-1])+ if mutation == "failed":+ other["message"]["content"][0]["is_error"] = True+ other.pop("toolUseResult")+ elif mutation == "null":+ other["toolUseResult"] = None+ elif mutation == "conflicting":+ other["toolUseResult"]["filePath"] = "/foreign.py"+ else:+ other["message"]["content"].append({"type": "tool_result", "tool_use_id": "other"})+ rows.insert(2 if first else len(rows), other)+ assert result_patches(rows)["call-a"] is None+ _, spans = parse_claude_code("\n".join(map(json.dumps, rows)).encode(), "agent-a")+ evidence = next(s for s in spans if s.tool_name == "Edit").attributes["code.edit_evidence"]+ assert evidence["edits"] == []+ assert evidence["status"] in {"invalid_edits", "not_successful"}++[email protected]("mutation", ["modified", "invalid_patch", "absent"])+def test_legacy_fallback_only_when_native_result_absent(mutation):+ rows = transcript()+ args = rows[1]["message"]["content"][0]["input"]+ args.update(old_string="\nold\n", new_string="\nnew\n")+ rows[-1]["toolUseResult"].update(oldString="\nold\n", newString="\nnew\n")+ if mutation == "modified":+ rows[-1]["toolUseResult"]["userModified"] = True+ elif mutation == "invalid_patch":+ rows[-1]["toolUseResult"]["structuredPatch"] = []+ else:+ rows[-1].pop("toolUseResult")+ _, spans = parse_claude_code("\n".join(map(json.dumps, rows)).encode(), "agent-a")+ evidence = next(s for s in spans if s.tool_name == "Edit").attributes["code.edit_evidence"]+ assert evidence["status"] == ("captured" if mutation == "absent" else "invalid_edits")+++def test_native_write_keeps_legacy_full_file_capture():+ rows = transcript()+ rows[1]["message"]["content"][0].update(+ name="Write", input={"file_path": "/repo/app.py", "content": "new\n"}+ )+ rows[-1]["toolUseResult"] = {"type": "create", "filePath": "/repo/app.py"}+ _, spans = parse_claude_code("\n".join(map(json.dumps, rows)).encode(), "agent-a")+ evidence = next(s for s in spans if s.tool_name == "Write").attributes["code.edit_evidence"]+ assert evidence["status"] == "captured"++[email protected]("value", [None, 0, 1, "", "false", [], {}])[email protected]("field", ["replaceAll", "replace_all"])+def test_nonboolean_replacement_mode_is_not_verified(field, value):+ args, result = fixture()+ (result if field == "replaceAll" else args)[field] = value+ assert extract_result_edit("Edit", args, result) is None+++def test_native_replacement_mode_required_but_optional_invocation_defaults_false():+ args, result = fixture()+ assert extract_result_edit("Edit", args, result)["status"] == "captured"+ args["replace_all"] = True+ assert extract_result_edit("Edit", args, result) is None+ result["replaceAll"] = True+ assert extract_result_edit("Edit", args, result)["status"] == "captured"+ del result["replaceAll"]+ assert extract_result_edit("Edit", args, result) is None+++ "lines", [["-invented", "+credited", " context"], ["-return old", "+unrequested", " context"]]+)+def test_matching_metadata_cannot_validate_fabricated_patch_contents(lines):+ args, result = fixture()+ result["structuredPatch"][0]["lines"] = lines+ assert extract_result_edit("Edit", args, result) is None+++def test_original_file_validates_split_patch_for_one_long_replacement():+ args, result = fixture()+ before = "old\n" + "unchanged\n" * 10 + "last\n"+ after = "new\n" + "unchanged\n" * 10 + "changed\n"+ args.update(old_string=before, new_string=after)+ result.update(+ oldString=before,+ newString=after,+ originalFile=before,+ structuredPatch=[+ {"oldStart": 1, "newStart": 1, "oldLines": 1, "newLines": 1, "lines": ["-old", "+new"]},+ {+ "oldStart": 12,+ "newStart": 12,+ "oldLines": 1,+ "newLines": 1,+ "lines": ["-last", "+changed"],+ },+ ],+ )+ assert extract_result_edit("Edit", args, result)["status"] == "captured"+ incomplete = deepcopy(result)+ incomplete["structuredPatch"].pop()+ assert extract_result_edit("Edit", args, incomplete) is None+ without_original = deepcopy(result)+ del without_original["originalFile"]+ assert extract_result_edit("Edit", args, without_original)["status"] == "captured"+ result["structuredPatch"][1]["lines"][-1] = "+fabricated"+ assert extract_result_edit("Edit", args, result) is None+ result["structuredPatch"][1]["lines"][-1] = "+changed"+ result["structuredPatch"][1]["newStart"] = 11+ assert extract_result_edit("Edit", args, result) is None+ del result["originalFile"]+ assert extract_result_edit("Edit", args, result) is None+++def test_clipped_patch_checks_replacement_and_all_overlapping_context():+ args, result = fixture()+ args.update(+ old_string="omitted\nreturn old\ncontext\nomitted tail",+ new_string="omitted\nreturn new\ncontext\nomitted tail",+ )+ result.update(oldString=args["old_string"], newString=args["new_string"])+ assert extract_result_edit("Edit", args, result)["status"] == "captured"+ result["structuredPatch"][0]["lines"][-1] = " fabricated context"+ assert extract_result_edit("Edit", args, result) is None+++def test_clipped_replace_all_preserves_offsets_across_occurrences():+ args, result = fixture()+ args.update(old_string="start\nold\nend", new_string="start\nnew\nend", replace_all=True)+ result.update(+ oldString=args["old_string"],+ newString=args["new_string"],+ replaceAll=True,+ structuredPatch=[+ {"oldStart": 2, "newStart": 2, "oldLines": 1, "newLines": 1, "lines": ["-old", "+new"]},+ {+ "oldStart": 12,+ "newStart": 12,+ "oldLines": 1,+ "newLines": 1,+ "lines": ["-old", "+new"],+ },+ ],+ )+ assert extract_result_edit("Edit", args, result)["status"] == "captured"+ result["structuredPatch"][1]["newStart"] = 13+ assert extract_result_edit("Edit", args, result) is None++[email protected]("no_op", [False, True])+def test_original_snapshot_does_not_make_context_only_hunks_edit_evidence(no_op):+ args, result = fixture()+ result["originalFile"] = "return old\ncontext\n"+ if no_op:+ args["new_string"] = args["old_string"]+ result["newString"] = result["oldString"]+ result["structuredPatch"] = [+ {"oldStart": 2, "newStart": 2, "oldLines": 1, "newLines": 1, "lines": [" context"]}+ ]+ assert extract_result_edit("Edit", args, result) is None+++def test_zero_old_start_without_original_file_is_rejected():+ args, result = fixture()+ result["structuredPatch"][0]["oldStart"] = 0+ assert extract_result_edit("Edit", args, result) is None+++def write_update(original="a\nold\nz\n", written="a\nnew\nz\n"):+ """A Write that overwrote an existing file, shaped like Claude Code's record."""+ args = {"file_path": "/repo/app.py", "content": written}+ result = {+ "type": "update",+ "filePath": "/repo/app.py",+ "content": written,+ "userModified": False,+ "originalFile": original,+ "structuredPatch": [+ {+ "oldStart": 1,+ "oldLines": 3,+ "newStart": 1,+ "newLines": 3,+ "lines": [" a", "-old", "+new", " z"],+ }+ ],+ }+ return args, result++[email protected]("original", ["a\nold\nz\n", None])+def test_write_over_existing_file_replays_as_its_patch(original):+ args, result = write_update(original)+ evidence = call_edit_evidence("Write", args, result, has_native=True, successful=True)+ assert evidence["status"] == "captured"+ assert [e["operation"] for e in evidence["edits"]] == ["replace"]+ edits = [{**evidence["edits"][0], "session_id": "agent-a", "event_id": "call-a"}]+ attributed = attribute_file("a\nold\nz\n", "a\nnew\nz\n", edits)+ assert attributed["sessions"] == {"agent-a": 1}+ assert attributed["unresolved_edits"] == []+ # The full-content capture it replaces cannot be placed over a base.+ legacy = call_edit_evidence("Write", args, None, has_native=False, successful=True)+ legacy_edits = [{**legacy["edits"][0], "session_id": "agent-a", "event_id": "call-a"}]+ assert attribute_file("a\nold\nz\n", "a\nnew\nz\n", legacy_edits)["unresolved_edits"] == [+ {"event_id": "call-a", "reason": "missing_before_snapshot"}+ ]+++ "mutate",+ [+ lambda a, r: r.update(content="a\nnew\nz\nextra\n"), # recorded != requested+ lambda a, r: r.update(filePath="/repo/other.py"),+ lambda a, r: r.update(userModified=True),+ lambda a, r: r.update(originalFile="a\ndifferent\nz\n"), # patch misplaced+ lambda a, r: r["structuredPatch"][0].update(newStart=2), # after side misplaced+ lambda a, r: r.update(originalFile=None, content="x\nnew\nz\n")+ or a.update(content="x\nnew\nz\n"),+ ],+)+def test_unverifiable_write_update_yields_no_evidence(mutate):+ args, result = write_update()+ mutate(args, result)+ evidence = call_edit_evidence("Write", args, result, has_native=True, successful=True)+ assert evidence == {"status": "invalid_edits", "edits": []}+++def test_write_create_and_absent_result_keep_full_file_capture():+ args, result = write_update()+ for native, has_native in (({**result, "type": "create"}, True), (None, False)):+ evidence = call_edit_evidence("Write", args, native, has_native=has_native, successful=True)+ assert [e["operation"] for e in evidence["edits"]] == ["write"]+++def test_fenced_write_result_never_falls_back_to_the_request():+ args, _ = write_update()+ evidence = call_edit_evidence("Write", args, None, has_native=True, successful=True)+ assert evidence == {"status": "invalid_edits", "edits": []}+++def test_real_parser_turns_overwriting_write_into_replace():+ rows = transcript()+ args, result = write_update()+ rows[1]["message"]["content"][0].update(name="Write", input=args)+ rows[-1]["toolUseResult"] = result+ _, spans = parse_claude_code("\n".join(map(json.dumps, rows)).encode(), "agent-a")+ evidence = next(s for s in spans if s.tool_name == "Write").attributes["code.edit_evidence"]+ assert evidence["status"] == "captured"+ assert [e["operation"] for e in evidence["edits"]] == ["replace"]diff --git a/python/tests/core/test_code_authorship.py b/python/tests/core/test_code_authorship.pynew file mode 100644index 0000000..e342574--- /dev/null+++ b/python/tests/core/test_code_authorship.py@@ -0,0 +1,382 @@+"""Observed edits survive external commits without confusing creation or usage."""++import json++from agentplay._core.code_authorship import (+ attribute_file,+ extract_edit_evidence,+ inserted_hashes,+ line_fingerprints,+)+++def edit(old, new, *, session="agent-a", event="edit-1"):+ captured = extract_edit_evidence(+ "Edit",+ {"file_path": "app.py", "old_string": "\n" + old + "\n", "new_string": "\n" + new + "\n"},+ successful=True,+ )+ return {**captured["edits"][0], "session_id": session, "event_id": event}+++def test_manual_commit_and_pr_need_no_agent_shell_commands():+ result = attribute_file(+ "return old\n", "return improved\n", [edit("return old", "return improved")]+ )+ assert result["agent_added_lines"] == 1+ assert result["unknown_added_lines"] == 0+ assert result["sessions"] == {"agent-a": 1}+++def test_pr_creation_is_not_code_evidence():+ evidence = extract_edit_evidence("Bash", '{"command":"gh pr create"}', successful=True)+ assert evidence["edits"] == []+ result = attribute_file("", "human implementation\n", [])+ assert result["agent_added_lines"] == 0+ assert result["unknown_added_lines"] == 1+++def test_human_replacement_removes_prior_agent_ownership():+ result = attribute_file("old\n", "human replacement\n", [edit("old", "agent replacement")])+ assert result["agent_added_lines"] == 0+ assert result["unknown_added_lines"] == 1+++def test_human_addition_preserves_surviving_agent_lines():+ result = attribute_file(+ "old\n", "agent replacement\nhuman addition\n", [edit("old", "agent replacement")]+ )+ assert result["sessions"] == {"agent-a": 1}+ assert result["added_lines"] == 2+ assert result["unknown_added_lines"] == 1+++def test_sequential_agents_do_not_double_count_the_same_line():+ result = attribute_file(+ "old\n",+ "final\n",+ [edit("old", "interim"), edit("interim", "final", session="agent-b", event="edit-2")],+ )+ assert result["sessions"] == {"agent-b": 1}+ assert result["event_ids"] == ["edit-2"]+++def test_multiple_agents_keep_their_distinct_contributions():+ result = attribute_file(+ "one\ntwo\n",+ "first\nsecond\n",+ [edit("one", "first"), edit("two", "second", session="agent-b", event="edit-2")],+ )+ assert result["sessions"] == {"agent-a": 1, "agent-b": 1}+ assert result["added_lines"] == 2+++def test_ambiguous_before_does_not_choose_a_duplicate():+ result = attribute_file("same\nsame\n", "replacement\nsame\n", [edit("same", "replacement")])+ assert result["agent_added_lines"] == 0+ assert result["unresolved_edits"][0]["reason"] == "before_not_unique_or_missing"+++def test_failed_edit_never_emits_evidence():+ result = extract_edit_evidence(+ "Edit", {"file_path": "app.py", "old_string": "old", "new_string": "new"}, successful=False+ )+ assert result == {"status": "not_successful", "edits": []}+++def test_patch_fingerprints_never_contain_source_content():+ captured = extract_edit_evidence(+ "apply_patch",+ "*** Begin Patch\n*** Update File: app.py\n@@\n-old unique secret text\n+new unique secret text\n*** End Patch",+ successful=True,+ )+ assert captured["status"] == "captured"+ assert "unique secret text" not in json.dumps(captured)+ evidence = {**captured["edits"][0], "session_id": "agent-a", "event_id": "patch-1"}+ assert (+ attribute_file("old unique secret text\n", "new unique secret text\n", [evidence])[+ "agent_added_lines"+ ]+ == 1+ )+++def test_new_file_write_matches_without_commit_identity():+ captured = extract_edit_evidence(+ "Write", {"file_path": "app.py", "content": "first\nsecond\n"}, successful=True+ )+ evidence = {**captured["edits"][0], "session_id": "agent-a", "event_id": "write-1"}+ assert attribute_file(None, "first\nsecond\n", [evidence])["agent_added_lines"] == 2+++def test_existing_file_write_without_before_stays_unknown():+ captured = extract_edit_evidence(+ "Write", {"file_path": "app.py", "content": "human and agent changes\n"}, successful=True+ )+ evidence = {**captured["edits"][0], "session_id": "agent-a", "event_id": "write-1"}+ assert (+ attribute_file("old\n", "human and agent changes\n", [evidence])["agent_added_lines"] == 0+ )+++def test_capture_limit_does_not_emit_a_partial_success():+ evidence = extract_edit_evidence(+ "Write", {"file_path": "app.py", "content": "line\n" * 2049}, successful=True+ )+ assert evidence == {"status": "capture_limit", "edits": []}+++def test_identical_edits_from_distinct_sessions_remain_ambiguous():+ result = attribute_file(+ "old\n", "new\n", [edit("old", "new"), edit("old", "new", session="agent-b", event="other")]+ )+ assert result["sessions"] == {}+ assert result["deletion_sessions"] == {}+ assert result["unknown_added_lines"] == 1+++def test_deletion_only_has_independent_session_evidence():+ result = attribute_file("keep\nremove\n", "keep\n", [edit("keep\nremove", "keep")])+ assert result["added_lines"] == 0+ assert result["agent_deleted_lines"] == 1+ assert result["deletion_sessions"] == {"agent-a": 1}+ assert result["deletion_event_ids"] == ["edit-1"]+ assert result["event_ids"] == []+++def test_reintroduced_deleted_text_is_not_agent_deletion():+ result = attribute_file("keep\nremove\n", "remove\nkeep\n", [edit("keep\nremove", "keep")])+ assert result["agent_deleted_lines"] == 0+++def test_filename_only_delete_is_not_content_evidence():+ captured = extract_edit_evidence(+ "apply_patch", "*** Begin Patch\n*** Delete File: app.py\n*** End Patch", successful=True+ )+ result = attribute_file(+ "old\n", None, [{**captured["edits"][0], "session_id": "agent-a", "event_id": "delete"}]+ )+ assert result["agent_deleted_lines"] == 0+ assert result["unknown_deleted_lines"] == 1+++def test_replacement_preserves_trailing_blank_lines():+ from hashlib import sha256++ evidence = extract_edit_evidence(+ "Edit",+ {"path": "app.py", "old_string": "\nold\n\n", "new_string": "\nnew\n\n"},+ successful=True,+ )+ empty = sha256(b"").hexdigest()+ assert evidence["edits"][0]["before"][-1] == empty+ assert evidence["edits"][0]["after"][-1] == empty+ assert len(evidence["edits"][0]["after"]) == 2+ result = attribute_file(+ "old\n\n",+ "new\n\n",+ [{**evidence["edits"][0], "session_id": "agent-a", "event_id": "blank-lines"}],+ )+ assert result["agent_added_lines"] == 1+++def test_replacing_a_blank_line_preserves_its_fingerprint():+ from hashlib import sha256++ evidence = extract_edit_evidence(+ "Edit", {"path": "app.py", "old_string": "\n\n", "new_string": "\nnew\n"}, successful=True+ )+ assert evidence["edits"][0]["before"] == [sha256(b"").hexdigest()]+++def test_kiro_requires_boolean_success_and_supports_fswrite_alias():+ from datetime import UTC, datetime++ from agentplay._core.ingestion.coding_agent._sources.local.parsers.kiro import _build_tool_span++ now = datetime.now(UTC)+ call = {+ "toolName": "fsWrite",+ "args": {"path": "app.py", "text": "new\n"},+ "toolCallId": "call-a",+ }+ for result in (+ None,+ {},+ {"success": None},+ {"success": False},+ {"success": "true"},+ {"success": 1},+ ):+ span = _build_tool_span("session-a", "turn-a", call, result, now, now)+ assert span.attributes["code.edit_evidence"] == {"status": "not_successful", "edits": []}+ span = _build_tool_span("session-a", "turn-a", call, {"success": True}, now, now)+ assert span.name == "Write"+ assert span.attributes["code.edit_evidence"]["status"] == "captured"+++def test_notebook_and_streaming_snippets_do_not_fabricate_before_snapshots():+ for name, args in (+ ("NotebookEdit", {"notebook_path": "example.ipynb", "new_source": "new"}),+ ("Edit", {"path": "app.py", "streamingContent": "// ... existing code ...\nnew"}),+ ):+ assert extract_edit_evidence(name, args, successful=True)["edits"] == []+++++def test_replacement_line_endings_match_file_fingerprints_without_losing_blanks():+ from agentplay._core.code_authorship import line_fingerprints++ for ending in (+ "\n",+ "\r\n",+ "\r",+ "\v",+ "\f",+ "\x1c",+ "\x1d",+ "\x1e",+ "\x85",+ "\u2028",+ "\u2029",+ ):+ old = ending + "old" + ending + ending+ new = ending + "new" + ending + ending+ captured = extract_edit_evidence(+ "Edit", {"path": "app.py", "old_string": old, "new_string": new}, successful=True+ )+ assert captured["status"] == "captured", repr(ending)+ evidence = captured["edits"][0]+ assert evidence["before"] == line_fingerprints("old" + ending + ending)+ assert evidence["after"] == line_fingerprints("new" + ending + ending)+ result = attribute_file(+ "old" + ending + ending,+ "new" + ending + ending,+ [{**evidence, "session_id": "agent-a", "event_id": "endings"}],+ )+ assert result["agent_added_lines"] == 1, repr(ending)+++def test_native_rename_retains_verified_edit_at_destination():+ captured = extract_edit_evidence(+ "apply_patch",+ "*** Begin Patch\n*** Update File: old.py\n*** Move to: new.py\n@@\n-old unique implementation\n+new unique implementation\n*** End Patch",+ successful=True,+ )+ assert captured["status"] == "captured"+ assert captured["edits"][0]["path"] == "new.py"+ evidence = {**captured["edits"][0], "session_id": "agent-a", "event_id": "move-edit"}+ result = attribute_file(+ "old unique implementation\n", "new unique implementation\n", [evidence]+ )+ assert result["sessions"] == {"agent-a": 1}+++def test_rename_without_content_does_not_claim_authorship():+ captured = extract_edit_evidence(+ "apply_patch",+ "*** Begin Patch\n*** Update File: old.py\n*** Move to: new.py\n*** End Patch",+ successful=True,+ )+ assert captured == {"status": "no_edit", "edits": []}+++def test_uncaptured_formatting_does_not_claim_semantic_equivalence():+ result = attribute_file(+ "return old\n",+ "return improved\n",+ [edit("return old", "return improved")],+ )+ assert result["sessions"] == {}+ assert result["unknown_added_lines"] == 1+++def test_captured_formatting_preserves_traceable_session_contributions():+ result = attribute_file(+ "return old\n",+ "return improved\n",+ [+ edit("return old", "return improved"),+ edit("return improved", "return improved", session="formatter", event="format"),+ ],+ )+ assert result["sessions"] == {"formatter": 1}+++def _replace(before, after, session, event, completed_at=None):+ return {+ "path": "app.py",+ "operation": "replace",+ "before": line_fingerprints(before),+ "after": line_fingerprints(after),+ "session_id": session,+ "event_id": event,+ "completed_at": completed_at,+ }+++def test_inserted_hashes_ignore_context_and_whole_file_writes_over_content():+ replace = _replace("keep\nold\n", "keep\nnew\n", "a", "e1")+ write = {**_replace("", "keep\nwritten\n", "b", "e2"), "operation": "write"}+ assert inserted_hashes([replace, write], added_file=False) == {+ "a": set(line_fingerprints("new\n")),+ "b": set(),+ }+ assert inserted_hashes([write], added_file=True) == {+ "b": set(line_fingerprints("keep\nwritten\n"))+ }+++def test_same_insertion_by_two_sessions_is_shared_and_unique_lines_stay_exclusive():+ # Best-of-N: both sessions insert "shared"; only session a also wrote "only_a".+ edits = [+ _replace("x\n", "x\nshared\nonly_a\n", "a", "a1", "2026-09-20T10:00:00+00:00"),+ _replace("y\n", "y\nshared\n", "b", "b1", "2026-09-20T11:00:00+00:00"),+ ]+ result = attribute_file("x\ny\n", "x\nshared\nonly_a\ny\nshared\n", edits)+ assert result["sessions"] == {"a": 2, "b": 1}+ assert result["exclusive_lines"] == {"a": 1}+ assert result["shared_lines"] == {"a": 1, "b": 1}+ assert result["session_events"] == {+ "a": {"a1": "2026-09-20T10:00:00+00:00"},+ "b": {"b1": "2026-09-20T11:00:00+00:00"},+ }+++def test_exact_linked_owner_wins_a_shared_line_tie():+ edits = [+ _replace("x\n", "x\nshared\nonly_a\n", "a", "a1"),+ _replace("y\n", "y\nshared\n", "b", "b1"),+ ]+ result = attribute_file(+ "x\ny\n", "x\nshared\nonly_a\ny\nshared\n", edits, exact_sessions=frozenset({"a"})+ )+ assert result["exclusive_lines"] == {"a": 2}+ assert result["shared_lines"] == {"b": 1}+++def test_deletions_never_count_toward_link_strength():+ # Session a deletes five base lines and adds one; b only deletes.+ base = "keep\n" + "".join(f"gone{i}\n" for i in range(5)) + "drop\n"+ edits = [+ _replace("keep\n" + "".join(f"gone{i}\n" for i in range(5)), "keep\nnew\n", "a", "a1"),+ _replace("keep\nnew\ndrop\n", "keep\nnew\n", "b", "b1"),+ ]+ result = attribute_file(base, "keep\nnew\n", edits)+ assert result["deletion_sessions"] == {"a": 5, "b": 1}+ assert result["sessions"] == {"a": 1}+ assert result["exclusive_lines"] == {"a": 1}+ assert result["shared_lines"] == {}+ # Deletion events stay evidence for the session even without line credit.+ assert result["session_events"] == {"a": {"a1": None}, "b": {"b1": None}}+++def test_line_replay_handles_a_twenty_two_thousand_line_file():+ changed = range(0, 22_000, 1_000)+ base = "".join(f"line {n}\n" for n in range(22_000))+ head = "".join(f"agent {n}\n" if n in changed else f"line {n}\n" for n in range(22_000))+ chain = [_replace(f"line {n}\n", f"agent {n}\n", "a", f"e{n}") for n in changed]+ result = attribute_file(base, head, chain)+ assert result["sessions"] == {"a": 22}+ assert result["unresolved_edits"] == []diff --git a/python/tests/core/test_codex_cost_events.py b/python/tests/core/test_codex_cost_events.pynew file mode 100644index 0000000..43d9e6d--- /dev/null+++ b/python/tests/core/test_codex_cost_events.py@@ -0,0 +1,658 @@+"""Real JSONL → billed components, with no network or provider calls."""++import json++import pytest++from agentplay._core.ingestion.coding_agent._sources.local.parsers.codex import parse_codex+from agentplay._core.ingestion.coding_agent.session_pure import build_session_metrics+++def _line(kind, payload, second=0):+ return {"type": kind, "timestamp": f"2026-09-08T10:00:{second:02}Z", "payload": payload}+++def _user(text="Fix the bug"):+ return _line(+ "response_item",+ {"role": "user", "content": [{"type": "input_text", "text": text}]},+ )+++def _model(name):+ return _line("turn_context", {"model": name})+++def _usage(inp=1000, cached=400, out=200, reasoning=50):+ return dict(+ input_tokens=inp,+ cached_input_tokens=cached,+ output_tokens=out,+ reasoning_output_tokens=reasoning,+ total_tokens=inp + out,+ )+++def _event(last, cumulative, second=1):+ return _line(+ "event_msg",+ {+ "type": "token_count",+ "info": {"last_token_usage": last, "total_token_usage": cumulative},+ },+ second,+ )+++def _native_context(turn_id, model="gpt-5", second=0):+ return _line("turn_context", {"turn_id": turn_id, "model": model}, second)+++def _native_record(+ response_id,+ turn_id,+ usage,+ cumulative,+ thread_id="native-thread",+ second=1,+ reasoning=0,+):+ def payload_values(values, reasoning_output_tokens=0):+ inp, cached, out = values+ return {+ "input_tokens": inp,+ "cached_input_tokens": cached,+ "cache_write_input_tokens": 0,+ "output_tokens": out,+ "reasoning_output_tokens": reasoning_output_tokens,+ "total_tokens": inp + out,+ }++ return _line(+ "token_usage_record",+ {+ "thread_id": thread_id,+ "turn_id": turn_id,+ "response_id": response_id,+ "usage": payload_values(usage, reasoning),+ "thread_token_usage": payload_values(cumulative),+ },+ second,+ )+++def _parse(*records):+ data = b"\n".join(json.dumps(row).encode() for row in records) + b"\n"+ _, spans = parse_codex(data, trace_id="local:codex:billing-fixture")+ turns = [s for s in spans if s.name.startswith("Turn ")]+ return spans, turns+++def test_reasoning_is_subset_and_cache_components_are_conserved():+ spans, (turn,) = _parse(_user(), _model("gpt-5"), _event(_usage(), _usage()))+ (event,) = turn.attributes["llm.cost_events"]+ assert turn.completion_tokens == event["output_tokens"] == 200+ assert event["input_tokens"] == 600+ assert event["cache_read_tokens"] == 400+ assert event["cache_write_5m_tokens"] == event["cache_write_1h_tokens"] == 0+ # reasoning_output_tokens=50 is folded into the 200 output_tokens above+ # (not billed on top), but is still surfaced separately for display.+ assert event["reasoning_tokens"] == 50+ assert turn.attributes["llm.token_count.reasoning"] == 50+ assert event["usage_basis"] == "last_token_usage"+ assert event["request_id"] is None+ assert event["message_id"].startswith("codex-usage:")+ assert event["source.kind"] == "jsonl"+ assert event["source.byte_offset"] > 0+ assert event["source.content_hash"]+ assert build_session_metrics(spans)["model_usage"] == [+ dict(+ model="gpt-5",+ requests=1,+ input_tokens=600,+ cache_read_tokens=400,+ cache_write_5m_tokens=0,+ cache_write_1h_tokens=0,+ output_tokens=200,+ )+ ]+++def test_reasoning_tokens_are_clamped_to_the_output_they_are_a_subset_of():+ # Review-caught: a malformed vendor payload could report reasoning above+ # the snapshot's own output_tokens, contradicting the subset invariant+ # the whole field exists to display. Clamp rather than trust the vendor.+ _spans, (turn,) = _parse(+ _user(), _model("gpt-5"), _event(_usage(out=200, reasoning=9999), _usage())+ )+ (event,) = turn.attributes["llm.cost_events"]+ assert event["output_tokens"] == 200+ assert event["reasoning_tokens"] == 200+ assert turn.attributes["llm.token_count.reasoning"] == 200++[email protected]("context_before_user", [True, False])+def test_model_switch_preserves_both_turn_and_request_models(context_before_user):+ first = [_user("first"), _model("gpt-5"), _event(_usage(), _usage())]+ boundary = [_model("gpt-5-mini"), _user("second")]+ if not context_before_user:+ boundary.reverse()+ spans, turns = _parse(*first, *boundary, _event(_usage(), _usage(2000, 800, 400), 2))+ assert [t.model_name for t in turns] == ["gpt-5", "gpt-5-mini"]+ assert [t.attributes["llm.cost_events"][0]["model"] for t in turns] == ["gpt-5", "gpt-5-mini"]+ assert [row["model"] for row in build_session_metrics(spans)["model_usage"]] == [+ "gpt-5",+ "gpt-5-mini",+ ]+++def test_model_switch_inside_one_turn_keeps_each_usage_model():+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(_usage(), _usage()),+ _model("gpt-5-mini"),+ _event(_usage(), _usage(2000, 800, 400), 2),+ )+ assert [event["model"] for event in turn.attributes["llm.cost_events"]] == [+ "gpt-5",+ "gpt-5-mini",+ ]+ assert len(build_session_metrics(spans)["model_usage"]) == 2+++def test_repeated_snapshots_and_old_records_do_not_repeat_usage():+ first = _event(_usage(), _usage())+ _, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ first,+ _event(_usage(), _usage(), 2), # Same cumulative snapshot, later clock.+ _event(_usage(), _usage(2000, 800, 400), 3),+ first, # Exact older record replayed after a newer snapshot.+ )+ assert turn.prompt_tokens == 2000+ assert turn.completion_tokens == 400+ assert len(turn.attributes["llm.cost_events"]) == 2+++def test_observation_ids_survive_appends_and_prepended_nonusage_records():+ prefix = [_user(), _model("gpt-5"), _event(_usage(), _usage())]+ _, (before,) = _parse(*prefix)+ _, after = _parse(+ _line("session_meta", {"id": "native-id"}),+ *prefix,+ _user("another"),+ _event(_usage(), _usage(2000, 800, 400), 2),+ )+ expected = before.attributes["llm.cost_events"][0]+ actual = after[0].attributes["llm.cost_events"][0]+ assert actual["message_id"] == expected["message_id"]+ assert actual["source.content_hash"] == expected["source.content_hash"]+ assert actual["source.byte_offset"] != expected["source.byte_offset"]+++def test_cumulative_only_usage_subtracts_each_component():+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(None, _usage()),+ _event(None, _usage(2500, 1000, 500, 100), 2),+ )+ first, second = turn.attributes["llm.cost_events"]+ assert first["usage_basis"] == second["usage_basis"] == "cumulative_delta"+ assert second["input_tokens"] == 900+ assert second["cache_read_tokens"] == 600+ assert second["output_tokens"] == 300+ # No per-call snapshot to read reasoning_output_tokens from on this+ # basis, and no baseline to delta it against either -- reported as 0+ # rather than a fabricated figure. See `_reasoning_tokens` callers.+ assert first["reasoning_tokens"] == second["reasoning_tokens"] == 0+ assert turn.attributes["llm.token_count.reasoning"] == 0+ metrics = build_session_metrics(spans)+ assert (metrics["input_fresh"], metrics["cache_read_tokens"], metrics["output_tokens"]) == (+ 1500,+ 1000,+ 500,+ )+++ "bad",+ [+ _usage(900, 1000), # Cache cannot exceed input.+ _usage(inp=True),+ _usage(out=-1),+ {**_usage(), "cache_write_input_tokens": 100}, # No TTL evidence.+ ],+)+def test_bad_or_unpriceable_usage_rejects_capture(bad):+ # A vendor-drift or malformed record degrades this one usage snapshot --+ # not the whole transcript. Nothing gets captured or billed for it, and+ # the loss is surfaced via usage_complete rather than an aborted parse.+ spans, (turn,) = _parse(_user(), _model("gpt-5"), _event(None, bad))+ assert turn.attributes["llm.cost_events"] == []+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_cache_write_token_usage_costs_only_its_own_turn():+ """A nonzero cache_write_input_tokens (no TTL evidence) used to raise and+ lose every turn in the transcript. It must now cost only the turn that+ carried it -- every other turn's usage stays bit-identical."""+ good = _usage(1000, 400, 200)+ bad_cache_write = {**_usage(500, 100, 50), "cache_write_input_tokens": 64}+ spans, (turn_one, turn_two) = _parse(+ _user("first"), _model("gpt-5"), _event(good, good, second=1),+ _user("second"), _event(bad_cache_write, bad_cache_write, second=2),+ )+ # First turn's billing is untouched -- bit-identical to a session with no+ # cache-write component at all.+ assert (turn_one.prompt_tokens, turn_one.completion_tokens) == (1000, 200)+ assert len(turn_one.attributes["llm.cost_events"]) == 1+ # Second turn's cache-write record is rejected and dropped, never billed+ # and never allowed to abort the rest of the transcript.+ assert turn_two.attributes["llm.cost_events"] == []+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_a_rejected_record_does_not_poison_the_next_turn_billing():+ """Rejecting one snapshot must not double-bill or reject the turns after it.++ The baseline must advance along with the rejected record; otherwise the NEXT+ valid record would measure its delta from a total that still included the+ rejected record's tokens. The third turn below is the one that matters: it+ must neither bill the rejected 150 tokens a second time nor trip the+ backwards guard and take the rest of the session with it.+ """+ # Cumulative totals climb 1200, 1750, 2130 across the three records, so the+ # third record's delta is 380 and its own last_token_usage totals 380 too.+ # That only reconciles if the baseline moved to 1750 when the second record+ # was rejected; left at 1200 the delta reads 930 and the third turn is+ # rejected as well.+ spans, turns = _parse(+ _user("first"), _model("gpt-5"),+ _event(_usage(1000, 400, 200), _usage(1000, 400, 200), second=1),+ _user("second"),+ _event(+ {**_usage(500, 100, 50), "cache_write_input_tokens": 64},+ _usage(1500, 500, 250),+ second=2,+ ),+ _user("third"),+ _event(_usage(300, 100, 80), _usage(1800, 600, 330), second=3),+ )+ turn_one, turn_two, turn_three = turns+ assert (turn_one.prompt_tokens, turn_one.completion_tokens) == (1000, 200)+ assert turn_two.attributes["llm.cost_events"] == []+ # Recovering later billing is not the same as billing the session correctly:+ # the rejected turn's own usage is still missing, so the session has to say+ # so rather than report a total that looks whole.+ assert build_session_metrics(spans)["usage_complete"] is False+ # The third turn bills its own usage and nothing else.+ assert (turn_three.prompt_tokens, turn_three.completion_tokens) == (300, 80)+ assert len(turn_three.attributes["llm.cost_events"]) == 1+++def test_a_backwards_snapshot_does_not_become_the_new_baseline():+ """The mirror of the test above: some records are rejected BECAUSE their own+ cumulative figures cannot be trusted, and those must never be adopted as the+ baseline. Here the counter drops to 800 and is rejected; the third record+ reports 1500, whose delta only reconciles against the trusted 1200. Adopting+ 800 would make the delta 700 against a reported 300 and reject turn three+ too, one bad record silently ending billing for the rest of the session.+ """+ spans, turns = _parse(+ _user("first"), _model("gpt-5"),+ _event(_usage(1000, 400, 200), _usage(1000, 400, 200), second=1),+ _user("second"),+ _event(_usage(600, 200, 200), _usage(600, 200, 200), second=2),+ _user("third"),+ _event(_usage(220, 0, 80), _usage(1200, 400, 300), second=3),+ )+ turn_one, turn_two, turn_three = turns+ assert (turn_one.prompt_tokens, turn_one.completion_tokens) == (1000, 200)+ assert turn_two.attributes["llm.cost_events"] == []+ # Rejecting the record is only half the contract: the session must also say+ # its usage is incomplete. Without this, a parser that drops the record and+ # keeps billing would still pass, and the session would be reported as a+ # complete cost picture that is quietly missing a turn.+ assert build_session_metrics(spans)["usage_complete"] is False+ assert (turn_three.prompt_tokens, turn_three.completion_tokens) == (220, 80)+++def test_backwards_components_do_not_become_the_new_baseline():+ """A record rejected for backwards COMPONENTS must not be adopted either.++ The total-level guards run before the baseline is remembered, but the+ component guard runs after, so a snapshot whose total climbs while its own+ components move backwards was recorded as the fallback baseline and then+ adopted by the handler that rejected it. Every later delta was then measured+ against figures the parser had already refused, which rejected the rest of+ the session: the exact one-bad-record-ends-billing failure the total-level+ guards exist to prevent.+ """+ spans, turns = _parse(+ _user("first"), _model("gpt-5"),+ _event(None, _usage(1000, 400, 200), second=1),+ _user("second"),+ # Total climbs 1200 -> 1600, but input drops 1000 -> 900: rejected.+ _event(None, _usage(900, 300, 700), second=2),+ _user("third"),+ # Reconciles against the trusted (1000, 400, 200), not the rejected one.+ _event(None, _usage(1400, 500, 600), second=3),+ )+ turn_one, turn_two, turn_three = turns+ assert (turn_one.prompt_tokens, turn_one.completion_tokens) == (1000, 200)+ assert turn_two.attributes["llm.cost_events"] == []+ assert (turn_three.prompt_tokens, turn_three.completion_tokens) == (400, 400)+ assert len(turn_three.attributes["llm.cost_events"]) == 1+ # The rejected turn's own usage is still missing, so the session says so.+ assert build_session_metrics(spans)["usage_complete"] is False+++# Every `raise` in the token_count containment block, and what it means for the+# running cumulative baseline. Three separate MAJOR review findings were each one+# row of this table derived by hand, so the table itself is the test now: a+# rejection either leaves the baseline on the PREVIOUS record (correct only when+# this record's own total cannot be trusted) or moves it to THIS record (correct+# whenever the total is sound and the fault lies elsewhere). Getting it wrong in+# the "advances" direction is not one mis-billed turn: every later delta then+# spans two records, disagrees with its own `last`, and is rejected in turn, so+# one bad record silently ends billing for the rest of the session.+_BASELINE = _usage(1000, 400, 200) # total 1200, the trusted baseline+_SOUND_SECOND = _usage(1500, 500, 250) # total 1750, a well-formed successor++# (id, second record's cumulative, second record's last, baseline advances)+_REJECTION_TABLE = [+ # Sound total, unpriceable extra component: the figures are internally+ # consistent and the counter really did reach 1750.+ (+ "cache_write_is_unpriceable_not_malformed",+ {**_SOUND_SECOND, "cache_write_input_tokens": 64},+ _usage(500, 100, 50),+ True,+ ),+ # Sound total, the fault is in `last`, which the baseline does not depend on.+ ("last_disagrees_with_delta", _SOUND_SECOND, _usage(1, 0, 1), True),+ # The total itself is unreadable, so nothing downstream of it can be trusted.+ ("cumulative_total_is_not_an_int", {**_SOUND_SECOND, "total_tokens": "x"}, _usage(500, 100, 50), False),+ ("cumulative_total_is_negative", {**_SOUND_SECOND, "total_tokens": -5}, _usage(500, 100, 50), False),+ # The snapshot contradicts itself: components malformed, or not adding up.+ ("component_is_not_an_int", {**_SOUND_SECOND, "input_tokens": "x"}, _usage(500, 100, 50), False),+ ("cached_exceeds_input", {**_SOUND_SECOND, "cached_input_tokens": 9999}, _usage(500, 100, 50), False),+ ("total_is_not_input_plus_output", {**_SOUND_SECOND, "total_tokens": 99999}, _usage(500, 100, 50), False),+ # A counter that went down is a reset or a stale read; adopting it would+ # reject every later record for moving backwards against it.+ ("cumulative_moved_backwards", _usage(800, 300, 100), _usage(500, 100, 50), False),+]+++ ("cumulative", "last", "baseline_advances"),+ [pytest.param(cum, lst, adv, id=name) for name, cum, lst, adv in _REJECTION_TABLE],+)+def test_a_rejected_record_advances_the_baseline_only_when_its_total_is_sound(+ cumulative, last, baseline_advances+):+ """One fixture, one mutation per rejection reason, one assertion: turn three.++ The third record's `last` reports 380 and its cumulative reads 2130. That+ reconciles against a baseline of 1750 (2130 - 1750 = 380) and against+ nothing else, so turn three billing its real 300/80 is a direct readout of+ whether the rejected second record advanced the baseline.+ """+ spans, turns = _parse(+ _user("first"), _model("gpt-5"),+ _event(_usage(1000, 400, 200), _BASELINE, second=1),+ _user("second"),+ _event(last, cumulative, second=2),+ _user("third"),+ _event(_usage(300, 100, 80), _usage(1800, 600, 330), second=3),+ )+ turn_one, turn_two, turn_three = turns+ # Turn one is untouched and turn two loses its own usage either way.+ assert (turn_one.prompt_tokens, turn_one.completion_tokens) == (1000, 200)+ assert turn_two.attributes["llm.cost_events"] == []+ expected = (300, 80) if baseline_advances else (0, 0)+ assert (turn_three.prompt_tokens, turn_three.completion_tokens) == expected+ # Whichever way it went, the session never claims a complete cost picture.+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_a_repeated_total_carrying_an_unpriceable_component_is_still_refused():+ """The repeated-total short circuit must not skip the priceability check.++ A snapshot whose total simply has not moved is normally nothing to do:+ the block `continue`s without billing and without touching the baseline.+ But "nothing to bill" is not the same as "nothing to say". If that same+ record carries a cache write this parser cannot price, the session has+ seen a component it did not account for, and continuing silently makes it+ report a complete cost picture that is not complete.+ """+ repeated = _usage(1000, 400, 200)+ spans, turns = _parse(+ _user("first"), _model("gpt-5"),+ _event(repeated, repeated, second=1),+ _user("second"),+ _event(repeated, {**repeated, "cache_write_input_tokens": 64}, second=2),+ )+ turn_one, turn_two = turns+ # The first record still bills normally; the repeated one adds nothing.+ assert (turn_one.prompt_tokens, turn_one.completion_tokens) == (1000, 200)+ assert (turn_two.prompt_tokens, turn_two.completion_tokens) == (0, 0)+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_decreasing_cumulative_snapshot_is_not_guessed_as_new_cost():+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(_usage(), _usage(2000, 800, 400)),+ _event(_usage(), _usage(), 2),+ )+ # The first snapshot still bills; the backwards-moving second one is+ # rejected and dropped rather than guessed at or aborting the transcript.+ assert len(turn.attributes["llm.cost_events"]) == 1+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_cumulative_only_delta_requires_known_previous_components():+ spans, (turn,) = _parse(+ _user(), _model("gpt-5"),+ _event(_usage(), {"total_tokens": 1200}),+ _event(None, _usage(2000, 800, 400), 2),+ )+ assert len(turn.attributes["llm.cost_events"]) == 1+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_valid_zero_usage_and_rate_limit_only_turns_have_empty_evidence():+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(None, None),+ _event(_usage(0, 0, 0, 0), _usage(0, 0, 0, 0), 2),+ )+ assert turn.attributes["llm.cost_events"] == []+ assert build_session_metrics(spans)["model_usage"] == []++[email protected]("usage_kind", ["last", "cumulative"])[email protected]("total", [True, None, "0", 0.0, -1])+def test_supplied_total_must_match_consumed_components(usage_kind, total):+ bad = {**_usage(0, 0, 0, 0), "total_tokens": total}+ last, cumulative = (bad, None) if usage_kind == "last" else (None, bad)+ spans, (turn,) = _parse(_user(), _model("gpt-5"), _event(last, cumulative))+ assert turn.attributes["llm.cost_events"] == []+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_last_usage_can_omit_redundant_total():+ last = _usage()+ del last["total_tokens"]+ _, (turn,) = _parse(_user(), _model("gpt-5"), _event(last, None))+ assert (turn.prompt_tokens, turn.completion_tokens) == (1000, 200)+ assert len(turn.attributes["llm.cost_events"]) == 1+++def test_unchanged_cumulative_ignores_unconsumed_last_usage_placeholder():+ placeholder = {**_usage(0, 0, 0, 0), "total_tokens": 76776}+ _, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(_usage(), _usage()),+ _event(placeholder, _usage(), 2),+ _event(_usage(), _usage(2000, 800, 400), 3),+ )+ assert (turn.prompt_tokens, turn.completion_tokens) == (2000, 400)+ assert len(turn.attributes["llm.cost_events"]) == 2+++def test_native_ledger_survives_legacy_reset_and_attaches_delayed_turn():+ rows = [+ _line("session_meta", {"id": "native-thread"}),+ _native_context("turn-1", second=0),+ _user(+ "first",+ ),+ _native_record("response-1", "turn-1", (1000, 400, 200), (1000, 400, 200), second=1),+ _line("compacted", {}, 2),+ # Codex can flush this native record before its context and user line.+ _native_record("response-2", "turn-2", (500, 100, 50), (1500, 500, 250), second=3),+ _native_context("turn-2", model="gpt-5-mini", second=4),+ _user(+ "second",+ ),+ # Legacy display counters are advisory once native records exist.+ _event({"input_tokens": 1}, {}, 5),+ ]+ _, spans = _parse(*rows)+ turns = [span for span in spans if span.name.startswith("Turn ")]+ events = [event for turn in turns for event in turn.attributes["llm.cost_events"]]+ assert [(event["message_id"], event["model"]) for event in events] == [+ ("codex-response:response-1", "gpt-5"),+ ("codex-response:response-2", "gpt-5-mini"),+ ]+ assert [+ turn.attributes["llm.cost_events"][0]["turn_id"]+ for turn in turns+ if turn.attributes["llm.cost_events"]+ ] == [+ "turn-1",+ "turn-2",+ ]+ assert build_session_metrics(spans)["model_usage"] == [+ dict(+ model="gpt-5",+ requests=1,+ input_tokens=600,+ cache_read_tokens=400,+ cache_write_5m_tokens=0,+ cache_write_1h_tokens=0,+ output_tokens=200,+ ),+ dict(+ model="gpt-5-mini",+ requests=1,+ input_tokens=400,+ cache_read_tokens=100,+ cache_write_5m_tokens=0,+ cache_write_1h_tokens=0,+ output_tokens=50,+ ),+ ]+++def test_native_duplicate_response_is_emitted_once():+ record = _native_record("response-1", "turn-1", (1000, 400, 200), (1000, 400, 200))+ _, (turn,) = _parse(+ _line("session_meta", {"id": "native-thread"}),+ _native_context("turn-1"),+ _user(),+ record,+ record,+ )+ assert [event["message_id"] for event in turn.attributes["llm.cost_events"]] == [+ "codex-response:response-1"+ ]+++def test_native_ledger_reasoning_tokens_are_read_per_response():+ record = _native_record(+ "response-1", "turn-1", (1000, 400, 200), (1000, 400, 200), reasoning=75+ )+ _, (turn,) = _parse(+ _line("session_meta", {"id": "native-thread"}),+ _native_context("turn-1"),+ _user(),+ record,+ )+ (event,) = turn.attributes["llm.cost_events"]+ assert event["reasoning_tokens"] == 75+ assert turn.attributes["llm.token_count.reasoning"] == 75+++ "mutate, message",+ [+ (lambda row: row["payload"].update(thread_id="other"), "owner"),+ (lambda row: row["payload"].update(response_id=""), "response_id"),+ (+ lambda row: row["payload"].update(+ thread_token_usage={+ "input_tokens": 2000,+ "cached_input_tokens": 400,+ "output_tokens": 200,+ "total_tokens": 2200,+ }+ ),+ "gap",+ ),+ ],+)+def test_native_ledger_rejects_unowned_or_incomplete_records(mutate, message):+ record = _native_record("response-1", "turn-1", (1000, 400, 200), (1000, 400, 200))+ mutate(record)+ # The whole native ledger is untrustworthy once one record fails+ # validation, so the session degrades to no native usage instead of+ # aborting the transcript with a raise.+ spans, turns = _parse(_line("session_meta", {"id": "native-thread"}), record)+ assert turns == []+ assert spans[0].attributes["llm.usage_complete"] is False+++def test_native_conflicting_replay_is_rejected():+ first = _native_record("response-1", "turn-1", (1000, 400, 200), (1000, 400, 200))+ second = _native_record("response-1", "turn-1", (1001, 400, 200), (1001, 400, 200), second=2)+ spans, turns = _parse(_line("session_meta", {"id": "native-thread"}), first, second)+ assert turns == []+ assert spans[0].attributes["llm.usage_complete"] is False+++def test_last_usage_that_disagrees_with_the_cumulative_delta_rejects_capture():+ """The snapshot says the counter moved by 1,200 but the+ per-call components add up to 600 -- billing would disagree with the+ vendor's own total, so the capture is rejected rather than trusted."""+ first = _usage(1000, 400, 200)+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(first, first, second=1),+ _event(_usage(500, 0, 100), _usage(2000, 400, 400), second=2),+ )+ # The first snapshot still bills; the disagreeing second one is rejected+ # and dropped rather than trusted or aborting the transcript.+ assert len(turn.attributes["llm.cost_events"]) == 1+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_last_usage_that_matches_the_cumulative_delta_is_accepted():+ first = _usage(1000, 400, 200)+ spans, _turns = _parse(+ _user(),+ _model("gpt-5"),+ _event(first, first, second=1),+ _event(_usage(1000, 0, 200), _usage(2000, 400, 400), second=2),+ )+ events = [e for s in spans for e in s.attributes.get("llm.cost_events", [])]+ assert len(events) == 2diff --git a/python/tests/core/test_codex_total_only.py b/python/tests/core/test_codex_total_only.pynew file mode 100644index 0000000..15f9fa5--- /dev/null+++ b/python/tests/core/test_codex_total_only.py@@ -0,0 +1,112 @@+"""Legacy totals preserve activity; a missing billing split is never a price."""++import json++import pytest++from agentplay._core.ingestion.coding_agent._sources.local.parsers.codex import parse_codex+from agentplay._core.ingestion.coding_agent.session_pure import build_session_metrics+++def _line(kind, payload, second=0):+ return {"type": kind, "timestamp": f"2026-09-13T00:00:{second:02}Z", "payload": payload}+++def _user():+ return _line("event_msg", {"type": "user_message", "message": "inspect"})+++def _model(model):+ return _line("turn_context", {"model": model})+++def _usage(inp=1000, cached=400, out=200, reasoning=50):+ return dict(+ input_tokens=inp,+ cached_input_tokens=cached,+ output_tokens=out,+ reasoning_output_tokens=reasoning,+ total_tokens=inp + out,+ )+++def _event(last, cumulative, second=1):+ return _line(+ "event_msg",+ {+ "type": "token_count",+ "info": {"last_token_usage": last, "total_token_usage": cumulative},+ },+ second,+ )+++def _parse(*rows):+ _, spans = parse_codex(+ "\n".join(map(json.dumps, rows)).encode(), trace_id="local:codex:total-only"+ )+ return spans, [s for s in spans if s.name.startswith("Turn ")]++[email protected]("zeros", [False, True])+def test_total_only_preserves_turn_and_tool_without_minting_requests(zeros):+ total = {**(_usage(0, 0, 0, 0) if zeros else {}), "total_tokens": 15585}+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _line(+ "response_item",+ {+ "type": "function_call",+ "name": "exec_command",+ "call_id": "call-1",+ "arguments": '{"cmd":"pwd"}',+ },+ ),+ _line(+ "response_item",+ {+ "type": "function_call_output",+ "call_id": "call-1",+ "output": "Process exited with code 0",+ },+ ),+ _event(total, total),+ )+ assert turn.attributes["llm.cost_events"] == []+ assert len([s for s in spans if s.attributes.get("tool.name")]) == 1+ metrics = build_session_metrics(spans)+ assert metrics["usage_complete"] is False+ assert metrics["usage_state"] == "unknown_components"+ assert metrics["reported_total_tokens"] == 15585+ assert metrics["model_usage"] == []+ assert "retry_waste_marginal_usd" not in metrics+++def test_total_only_gap_preserves_known_requests_without_claiming_complete_coverage():+ total = {"total_tokens": 1500}+ spans, (turn,) = _parse(+ _user(),+ _model("gpt-5"),+ _event(_usage(), _usage()),+ _event(total, total, 2),+ _event(_usage(), _usage(2200, 800, 500), 3),+ )+ assert len(turn.attributes["llm.cost_events"]) == 2+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_nonzero_conflicting_components_still_fail():+ # A conflicting total is still never trusted -- it just costs this one+ # snapshot instead of the whole transcript.+ spans, (turn,) = _parse(_user(), _event(None, {**_usage(), "total_tokens": 9000}))+ assert turn.attributes["llm.cost_events"] == []+ assert build_session_metrics(spans)["usage_complete"] is False+++def test_repaired_source_becomes_complete_without_sticky_unknown_state():+ before, _ = _parse(_user(), _model("gpt-5"), _event(None, {"total_tokens": 1200}))+ after, _ = _parse(_user(), _model("gpt-5"), _event(_usage(), _usage()))+ assert build_session_metrics(before)["usage_complete"] is False+ assert "usage_complete" not in build_session_metrics(after)+ assert len(build_session_metrics(after)["model_usage"]) == 1diff --git a/python/tests/core/test_copilot_vscode_parser.py b/python/tests/core/test_copilot_vscode_parser.pynew file mode 100644index 0000000..50e1175--- /dev/null+++ b/python/tests/core/test_copilot_vscode_parser.py@@ -0,0 +1,344 @@+"""Copilot in VS Code (Chat / agent mode) parser.++Fixtures below are SYNTHETIC, shaped to match what real local+`workspaceStorage/*/chatSessions/*.jsonl` and `.json` files carry (see the parser's+module docstring). No real prompt/response text+appears in this file; fixture strings are placeholders only.++Each test pins one gap this parser exists to close (see the module+docstring's "Two on-disk shapes" / "Known gap" sections):++1. A `.json` snapshot (already-final state) parses directly.+2. A `.jsonl` file (kind-0 snapshot + kind-1/2 patches) replays to the SAME+ result a `.json` sibling with equivalent content would give -- including a+ kind-2 splice WITH an explicit `i` (streamed response growth) and WITHOUT+ one (plain append), both seen in real files.+3. Tool names alias through `copilot-vscode`'s table; `arguments` (a+ JSON-encoded STRING in real files, not a dict) is decoded before use.+4. Model resolution skips a `capi-*` routing id and the `copilot/auto` router+ alias from `modelId`, in that fallback order.+5. `result.usage.promptTokens` is preferred over `result.metadata`'s sparser+ fields.+6. A request-level `errorDetails` marks the turn ERROR; no error signal+ fabricated when tool results are merely absent.+7. `filePath` (camelCase) survives into the `file_path` key the shared+ extractors match.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources.local.parsers.copilot_vscode import (+ parse_copilot_vscode,+)+++def _tool_call(call_id: str, name: str, **args) -> dict:+ return {"id": call_id, "name": name, "arguments": json.dumps(args)}+++def _request(+ request_id: str,+ *,+ ts_ms: int,+ model_id: str = "copilot/auto",+ resolved_model: str | None = None,+ usage: dict | None = None,+ metadata_tokens: dict | None = None,+ tool_rounds: list[dict] | None = None,+ tool_results: dict | None = None,+ error: dict | None = None,+ elapsed_ms: int = 1000,+) -> dict:+ metadata = {+ "toolCallRounds": tool_rounds or [],+ "toolCallResults": tool_results or {},+ **(metadata_tokens or {}),+ }+ if resolved_model is not None:+ metadata["resolvedModel"] = resolved_model+ result = {"metadata": metadata}+ if usage is not None:+ result["usage"] = usage+ if error is not None:+ result["errorDetails"] = error+ return {+ "requestId": request_id,+ "timestamp": ts_ms,+ "elapsedMs": elapsed_ms,+ "isComplete": True,+ "modelId": model_id,+ "result": result,+ }+++def _snapshot_line(state: dict) -> bytes:+ return (json.dumps({"kind": 0, "v": state}) + "\n").encode()+++def _set_line(path: list, value) -> bytes:+ return (json.dumps({"kind": 1, "k": path, "v": value}) + "\n").encode()+++def _splice_line(path: list, value: list, index: int | None = None) -> bytes:+ obj: dict = {"kind": 2, "k": path, "v": value}+ if index is not None:+ obj["i"] = index+ return (json.dumps(obj) + "\n").encode()+++def test_a_json_snapshot_parses_directly():+ state = {+ "sessionId": "s1",+ "creationDate": 1_780_000_000_000,+ "requests": [_request("r1", ts_ms=1_780_000_001_000, resolved_model="gpt-5.4")],+ }+ trace, spans = parse_copilot_vscode(json.dumps(state).encode(), trace_id="local:x:s1")+ turns = [s for s in spans if s.name == "Turn 1"]+ assert len(turns) == 1+ assert turns[0].attributes["llm.model_name"] == "gpt-5.4"+ root = next(s for s in spans if s.parent_id is None)+ assert root.attributes["session.id"] == "s1"+++def test_jsonl_replay_matches_the_equivalent_json_document():+ final = {+ "sessionId": "s2",+ "creationDate": 1_780_000_000_000,+ "requests": [_request("r1", ts_ms=1_780_000_001_000, resolved_model="grok-code-fast-1")],+ }+ lines = [+ _snapshot_line({"sessionId": "s2", "creationDate": 1_780_000_000_000, "requests": []}),+ _splice_line(["requests"], [final["requests"][0]]), # kind 2, no "i": append+ ]+ json_trace, json_spans = parse_copilot_vscode(json.dumps(final).encode(), trace_id="j")+ jsonl_trace, jsonl_spans = parse_copilot_vscode(b"".join(lines), trace_id="j")+ assert len(jsonl_spans) == len(json_spans)+ assert [s.attributes.get("llm.model_name") for s in jsonl_spans if s.name == "Turn 1"] == [+ s.attributes.get("llm.model_name") for s in json_spans if s.name == "Turn 1"+ ]+++def test_a_streamed_response_growth_patch_with_explicit_index_is_applied():+ # Real shape: kind-2 patches on requests[N].response with a rising "i" --+ # each one truncates to "i" items then appends, simulating token-by-token+ # streaming. This must not raise or silently drop the request.+ lines = [+ _snapshot_line(+ {"sessionId": "s3", "requests": [_request("r1", ts_ms=1, elapsed_ms=1)]}+ ),+ _set_line(["requests", 0, "response"], []),+ _splice_line(["requests", 0, "response"], [{"value": "a"}]),+ _splice_line(["requests", 0, "response"], [{"value": "a"}, {"value": "b"}], index=0),+ ]+ trace, spans = parse_copilot_vscode(b"".join(lines), trace_id="j3")+ turn = next(s for s in spans if s.name == "Turn 1")+ # Strong assertion (not merely that the request survived; that the indexed+ # splice actually reconstructed correctly): "b" replaced the SECOND item at i=0 rather than appending a+ # third, and both are real response text now that output.value is wired.+ assert turn.attributes["output.value"] == "a\nb"+++def test_malformed_patches_are_skipped_not_fatal():+ lines = [+ _snapshot_line({"sessionId": "s4", "requests": [_request("r1", ts_ms=1)]}),+ b"not json at all\n",+ _set_line(["requests", 99, "nope"], "x"), # out-of-range index+ _splice_line(["missing", "path"], ["x"]), # path doesn't exist+ ]+ trace, spans = parse_copilot_vscode(b"".join(lines), trace_id="j4")+ assert any(s.name == "Turn 1" for s in spans)+++def test_tool_names_alias_and_arguments_string_is_decoded():+ rounds = [+ {+ "toolCalls": [+ _tool_call("c1", "run_in_terminal", command="git log -1"),+ _tool_call("c2", "replace_string_in_file", filePath="/repo/a.py", oldString="\nx\n", newString="\ny\n"),+ ]+ }+ ]+ results = {"c1": {"content": [{"value": "abc123"}]}, "c2": {"content": [{"value": "ok"}]}}+ req = _request("r1", ts_ms=1, resolved_model="gpt-5.4", tool_rounds=rounds, tool_results=results)+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s5", "requests": [req]}).encode(), trace_id="j5"+ )+ tools = {s.attributes["tool.name"]: s for s in spans if s.span_kind == "TOOL"}+ assert set(tools) == {"Bash", "Edit"}+ assert tools["Bash"].attributes["input.value"] == '{"command": "git log -1"}'+ assert tools["Bash"].status_code == "OK"+ # file_path (snake_case) was inserted ahead of the camelCase filePath.+ assert '"file_path": "/repo/a.py"' in tools["Edit"].attributes["input.value"]+++def test_a_tool_call_with_no_result_is_unset_not_an_error():+ rounds = [{"toolCalls": [_tool_call("c1", "read_file", filePath="/a.py")]}]+ req = _request("r1", ts_ms=1, tool_rounds=rounds, tool_results={}) # never resolved+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s6", "requests": [req]}).encode(), trace_id="j6"+ )+ tool = next(s for s in spans if s.span_kind == "TOOL")+ assert tool.status_code == "UNSET"+++def test_model_resolution_skips_capi_and_the_router_alias_in_order():+ real = _request("r1", ts_ms=1, model_id="copilot/auto", resolved_model="grok-code-fast-1")+ capi = _request("r2", ts_ms=2, model_id="copilot/auto", resolved_model="capi-noe-ptuc-h200")+ neither = _request("r3", ts_ms=3, model_id="copilot/auto", resolved_model=None)+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s7", "requests": [real, capi, neither]}).encode(),+ trace_id="j7",+ )+ turns = [s for s in spans if s.name.startswith("Turn")]+ assert [t.attributes["llm.model_name"] for t in turns] == [+ "grok-code-fast-1",+ "copilot/auto", # capi-* skipped -> falls back to the router alias+ "copilot/auto", # no resolvedModel at all -> same fallback+ ]+++def test_usage_promptTokens_is_preferred_over_metadata():+ req = _request(+ "r1",+ ts_ms=1,+ usage={"promptTokens": 41236, "completionTokens": 2027},+ metadata_tokens={"promptTokens": 999, "outputTokens": 999},+ )+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s8", "requests": [req]}).encode(), trace_id="j8"+ )+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.attributes["llm.token_count.prompt"] == 41236+ assert turn.attributes["llm.token_count.completion"] == 2027+++def test_metadata_tokens_used_when_usage_is_absent():+ req = _request("r1", ts_ms=1, metadata_tokens={"promptTokens": 52214, "outputTokens": 1220})+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s9", "requests": [req]}).encode(), trace_id="j9"+ )+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.attributes["llm.token_count.prompt"] == 52214+ assert turn.attributes["llm.token_count.completion"] == 1220+++def test_a_request_level_error_marks_the_turn_error_and_carries_the_code():+ req = _request(+ "r1",+ ts_ms=1,+ error={"code": "quotaExceeded", "message": "You've reached your monthly quota."},+ )+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s10", "requests": [req]}).encode(), trace_id="j10"+ )+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.status_code == "ERROR"+ assert turn.attributes["error.code"] == "quotaExceeded"+++def test_no_error_is_fabricated_when_a_request_has_no_errorDetails():+ req = _request("r1", ts_ms=1)+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s11", "requests": [req]}).encode(), trace_id="j11"+ )+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.status_code == "OK"+ assert "error.code" not in turn.attributes+++def test_an_empty_session_produces_no_spans_but_does_not_raise():+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s12", "requests": []}).encode(), trace_id="j12"+ )+ assert spans == []+++def test_root_span_carries_the_session_id_and_agent_tool():+ req = _request("r1", ts_ms=1_780_000_000_000)+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s13", "requests": [req]}).encode(),+ trace_id="j13",+ user_id="u-42",+ project_name="my-repo",+ )+ root = next(s for s in spans if s.parent_id is None)+ assert root.attributes["session.id"] == "s13"+ assert root.attributes["session.agent_tool"] == "copilot-vscode"+ assert root.attributes["project.name"] == "my-repo"+ # Review-caught: user_id was accepted but never attached to the root span,+ # breaking the TraceSource contract every sibling parser follows.+ assert root.attributes["user.id"] == "u-42"+++def test_root_span_user_id_defaults_to_empty_string():+ req = _request("r1", ts_ms=1)+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s14", "requests": [req]}).encode(), trace_id="j14"+ )+ root = next(s for s in spans if s.parent_id is None)+ assert root.attributes["user.id"] == ""+++def test_turn_input_value_comes_from_rendered_user_message_text_parts_only():+ # Real shape: a list of parts; only type==1 parts carry a string "text".+ # type 2/3 (image / other reference) never do and must be skipped, not+ # stringified into noise.+ req = _request("r1", ts_ms=1)+ req["result"]["metadata"]["renderedUserMessage"] = [+ {"type": 1, "text": "fix the bug"},+ {"type": 3, "imageUrl": "data:..."},+ {"type": 1, "text": "in auth.py"},+ ]+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s15", "requests": [req]}).encode(), trace_id="j15"+ )+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.attributes["input.value"] == "fix the bug\nin auth.py"+++def test_turn_output_value_excludes_thinking_and_tool_marker_parts():+ # Real shape: response is heterogeneous (thinking, toolInvocationSerialized,+ # mcpServersStarting, ...); only the markdown/text parts -- no "kind" key at+ # all, a string "value" -- are the actual answer.+ req = _request("r1", ts_ms=1)+ req["response"] = [+ {"kind": "thinking", "value": "let me consider..."},+ {"kind": "mcpServersStarting", "didStartServerIds": ["s1"]},+ {"value": "Here is the fix."},+ ]+ trace, spans = parse_copilot_vscode(+ json.dumps({"sessionId": "s16", "requests": [req]}).encode(), trace_id="j16"+ )+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.attributes["output.value"] == "Here is the fix."+++def test_model_falls_through_to_the_session_level_selected_model():+ # Real shape: state.inputState.selectedModel.identifier, session-scoped not+ # per-request -- the third tier the module docstring already promised but+ # the code never implemented.+ req = _request("r1", ts_ms=1, model_id="copilot/auto", resolved_model=None)+ state = {+ "sessionId": "s17",+ "requests": [req],+ "inputState": {"selectedModel": {"identifier": "claude-sonnet-5"}},+ }+ trace, spans = parse_copilot_vscode(json.dumps(state).encode(), trace_id="j17")+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.attributes["llm.model_name"] == "claude-sonnet-5"+++def test_session_level_model_is_skipped_when_itself_a_routing_alias():+ req = _request("r1", ts_ms=1, model_id="copilot/auto", resolved_model=None)+ state = {+ "sessionId": "s18",+ "requests": [req],+ "inputState": {"selectedModel": {"identifier": "capi-noe-ptuc-h200"}},+ }+ trace, spans = parse_copilot_vscode(json.dumps(state).encode(), trace_id="j18")+ turn = next(s for s in spans if s.name == "Turn 1")+ # Falls back further to the per-request modelId (still "copilot/auto"),+ # never a bare capi-* id.+ assert turn.attributes["llm.model_name"] == "copilot/auto"diff --git a/python/tests/core/test_cursor_context_files.py b/python/tests/core/test_cursor_context_files.pynew file mode 100644index 0000000..e36fdd2--- /dev/null+++ b/python/tests/core/test_cursor_context_files.py@@ -0,0 +1,79 @@+"""Cursor composer sessions forward their referenced file paths.++Composer chats rarely run ``git remote``, rarely open a PR, and carry few+tool-call file paths, so every git-free repo-attribution tier missed them and+they ended up with no repo attribution. Cursor does record the+files, in ``newlyCreatedFiles``, ``context.selections``, the+``originalFileStates`` keys, and the git worktree / tracked-repo roots, but the+materializer dropped all of it, so nothing reached the parser.++Measured on a real ``state.vscdb``: 6 of 189 composer records carried a+``workspaceIdentifier`` cwd; 66 carried one of the above. The materializer now collects+them into the header's ``contextFiles`` and this parser forwards them as+``harness.context_files`` for repo attribution.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ parse_cursor_store,+)+++def _transcript(**header_extra) -> bytes:+ header = {+ "type": "cursor_store_session",+ "agentId": "abc-123",+ "cwd": "/w/repo",+ "createdAt": "2026-08-19T10:00:00.000Z",+ **header_extra,+ }+ msg_user = {+ "role": "user",+ "content": "do the thing",+ "createdAt": "2026-08-19T10:00:01.000Z",+ }+ msg_asst = {+ "role": "assistant",+ "content": [{"type": "text", "text": "done"}],+ "createdAt": "2026-08-19T10:00:05.000Z",+ }+ return "\n".join(json.dumps(o) for o in (header, msg_user, msg_asst)).encode()+++def _context_files(data: bytes):+ _trace, spans = parse_cursor_store(data, "local:cursor:abc-123")+ root = next(s for s in spans if s.parent_id is None)+ return root.attributes.get("harness.context_files")+++def test_context_files_reach_the_root_span():+ paths = ["/w/repo/a.py", "/w/repo/b.py"]+ assert json.loads(_context_files(_transcript(contextFiles=paths))) == paths+++def test_attribute_is_absent_when_the_cli_sent_none():+ """Absent, not empty: a reader must tell "no paths" from "old CLI build"."""+ assert _context_files(_transcript()) is None+ assert _context_files(_transcript(contextFiles=[])) is None+++def test_non_string_entries_are_dropped():+ data = _transcript(contextFiles=["/w/repo/a.py", 42, None, ""])+ assert json.loads(_context_files(data)) == ["/w/repo/a.py"]+++def test_a_malformed_field_does_not_break_the_parse():+ """A bad header field must never cost us the whole session."""+ data = _transcript(contextFiles="not-a-list")+ _trace, spans = parse_cursor_store(data, "local:cursor:abc-123")+ assert spans, "session must still parse"+ assert _context_files(data) is None+++def test_windows_paths_survive_verbatim():+ """Normalisation belongs to the consumer (`_paths.match_key`), not here."""+ paths = [r"C:\Users\Ada\repo\main.py"]+ assert json.loads(_context_files(_transcript(contextFiles=paths))) == pathsdiff --git a/python/tests/core/test_cursor_header_model_fallback.py b/python/tests/core/test_cursor_header_model_fallback.pynew file mode 100644index 0000000..1ac2eb1--- /dev/null+++ b/python/tests/core/test_cursor_header_model_fallback.py@@ -0,0 +1,63 @@+"""Cursor sessions whose messages carry no model still get the header's.++Cursor writes the model+twice — per-message at ``providerOptions.cursor.modelName`` and once in the+file header's ``model`` field — but some sessions carry NO message-level+providerOptions at all. The model must come from the header in that case, or the session+would be model-less and priced $0.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ parse_cursor_store,+)+++def _transcript(header_model: str, message_model: str | None) -> bytes:+ header = {+ "type": "cursor_store_session",+ "agentId": "abc-123",+ "model": header_model,+ "cwd": "/w/repo",+ "createdAt": "2026-08-19T10:00:00.000Z",+ }+ msg_user: dict = {+ "role": "user",+ "content": "do the thing",+ "createdAt": "2026-08-19T10:00:01.000Z",+ }+ if message_model:+ msg_user["providerOptions"] = {"cursor": {"modelName": message_model}}+ msg_asst = {+ "role": "assistant",+ "content": [{"type": "text", "text": "done"}],+ "createdAt": "2026-08-19T10:00:05.000Z",+ }+ return "\n".join(json.dumps(o) for o in (header, msg_user, msg_asst)).encode()+++def _root_model(data: bytes) -> str:+ _trace, spans = parse_cursor_store(data, "local:cursor:abc-123")+ root = next(s for s in spans if s.parent_id is None)+ return root.attributes.get("llm.model_name")+++def test_message_model_still_wins_when_present():+ assert _root_model(_transcript("cursor-grok-4.6-high-fast", "grok-4.6")) == "grok-4.6"+++def test_header_model_fills_in_when_messages_carry_none():+ assert (+ _root_model(_transcript("cursor-grok-4.6-high-fast", None))+ == "cursor-grok-4.6-high-fast"+ )+++def test_auto_default_passes_through_honestly():+ # "default" (Cursor Auto) is not a priceable model, but it is the truth —+ # pricing treats it as unpriceable either way, and the billed-cost stamp+ # is what prices those sessions.+ assert _root_model(_transcript("default", None)) == "default"diff --git a/python/tests/core/test_cursor_reused_tool_ids.py b/python/tests/core/test_cursor_reused_tool_ids.pynew file mode 100644index 0000000..ef8dfae--- /dev/null+++ b/python/tests/core/test_cursor_reused_tool_ids.py@@ -0,0 +1,97 @@+"""Retained Cursor bubbles can reuse a native tool ID for distinct attempts."""++import json++from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ parse_cursor_store,+)+++def _spans(records):+ data = ("\n".join(json.dumps(row) for row in records) + "\n").encode()+ _, spans = parse_cursor_store(data, trace_id="cursor-reused", user_id="offline")+ return spans+++def _records(first_result=False):+ records = [+ {"type": "cursor_store_session", "agentId": "cursor-reused", "createdAt": 1000},+ {"role": "user", "id": "user-one", "content": "First", "createdAt": "2026-09-01T00:00:00Z"},+ {+ "role": "assistant",+ "id": "bubble-one",+ "createdAt": "2026-09-01T00:00:01Z",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "reused",+ "toolName": "ReadFile",+ "args": {"path": "one.py"},+ },+ ],+ },+ ]+ if first_result:+ records.append(+ {+ "role": "tool",+ "content": [+ {"type": "tool-result", "toolCallId": "reused", "result": "first result"}+ ],+ }+ )+ records.extend(+ [+ {+ "role": "user",+ "id": "user-two",+ "content": "Second",+ "createdAt": "2026-09-01T00:00:02Z",+ },+ {+ "role": "assistant",+ "id": "bubble-two",+ "createdAt": "2026-09-01T00:00:03Z",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "reused",+ "toolName": "ReadFile",+ "args": {"path": "two.py"},+ },+ ],+ },+ {+ "role": "tool",+ "createdAt": "2026-09-01T00:00:04Z",+ "content": [+ {"type": "tool-result", "toolCallId": "reused", "result": "second result"}+ ],+ },+ ]+ )+ return records+++def test_reused_id_preserves_unfinished_attempt_and_pairs_latest_result():+ spans = _spans(_records())+ tools = [s for s in spans if s.attributes.get("tool.name")]+ assert len(tools) == 2+ first, second = tools+ assert first.span_id != second.span_id+ assert first.parent_id != second.parent_id+ assert first.attributes["source.row_cursor"] == "bubble-one"+ assert second.attributes["source.row_cursor"] == "bubble-two"+ assert first.attributes["input.value"] != second.attributes["input.value"]+ assert first.attributes["output.value"] == ""+ assert first.status_code == "UNSET"+ assert second.attributes["output.value"] == "second result"+ assert second.status_code == "OK"+ assert [s.span_id for s in spans] == [s.span_id for s in _spans(_records())]+++def test_sequential_reuse_retains_each_completed_occurrence():+ tools = [s for s in _spans(_records(first_result=True)) if s.attributes.get("tool.name")]+ assert len(tools) == len({s.span_id for s in tools}) == 2+ assert [s.attributes["output.value"] for s in tools] == ["first result", "second result"]+ assert all(s.status_code == "OK" for s in tools)diff --git a/python/tests/core/test_cursor_skill_detection.py b/python/tests/core/test_cursor_skill_detection.pynew file mode 100644index 0000000..8476596--- /dev/null+++ b/python/tests/core/test_cursor_skill_detection.py@@ -0,0 +1,368 @@+"""Cursor skill invocation detection.++Cursor has no dedicated ``Skill``/``activate_skill`` tool — that vocabulary is+Claude Code's own, and checking for it (as ``cursor_agent_transcript.py``+already did) essentially never fires for genuine Cursor usage. Cursor's own+skills system (``~/.cursor/skills-cursor/<name>/SKILL.md``,+``~/.codex/skills/**/SKILL.md``, or a marketplace-plugin cache path) is+invoked by the model reading the skill's SKILL.md file with a plain Read call,+per Cursor's own injected instructions. Confirmed against a real local Cursor+IDE history capture — a ``read_file_v2`` Read call whose result carried the+skill's frontmatter'd body. ``cursor_store.py`` (the dominant format — CLI+``store.db`` + IDE composer ``vscdb``) detects skills from file reads;+``cursor_agent_transcript.py`` does the same instead of relying on the tool name.++These tests lock in: name detection is basename-based (not tied to one root+directory), counts aggregate per canonical skill, a Read of an unrelated file+(including one merely containing "skills/" in its path) is never a false+positive, and the captured body reaches ``skill_definitions``.++IDE composer ``read_file_v2`` calls carry the touched path under+``"targetFile"``, not ``"path"``. `_skill_read_messages` below uses+`targetFile` to match; `test_cursor_store_detects_a_real_skill_read_via_target_file_key`+pins it.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources._base import build_sidecar_signals+from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_agent_transcript import (+ parse_cursor_agent_transcript,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ parse_cursor_store,+)++# --- cursor_store.py (dominant format) --------------------------------------+++def _cursor_transcript(*lines: dict) -> bytes:+ header = {+ "type": "cursor_store_session",+ "agentId": "agent-1",+ "createdAt": 1_000_000,+ "updatedAt": 1_010_000,+ "cwd": "/w/repo",+ }+ return ("\n".join(json.dumps(x) for x in (header, *lines))).encode()+++def _signals(data: bytes) -> dict:+ _trace, spans = parse_cursor_store(data, "local:cursor:agent-1")+ root = next(s for s in spans if s.parent_id is None)+ raw = root.attributes.get("harness.session_signals")+ return json.loads(raw) if raw else {}+++# Real capture: a marketplace-plugin skill cached under a+# hash-named directory, `read_file_v2` (already aliased to "Read"), result a+# JSON-encoded string wrapping {"contents": "..."}.+_SKILL_PATH = (+ "/home/user/.cursor/plugins/cache/cursor-public/deploy-on-aws/"+ "437f4bed0bfd7367df7613ca932fe900f7e08d89/skills/deploy/SKILL.md"+)+_SKILL_BODY = '---\nname: deploy\ndescription: "Deploy applications to AWS."\n---\n\nBody text.'+++def _skill_read_messages(+ path: str = _SKILL_PATH, body: str = _SKILL_BODY, arg_key: str = "path"+) -> tuple[dict, dict]:+ call = {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "tc1",+ "toolName": "read_file_v2",+ "args": {arg_key: path},+ }+ ],+ }+ result = {+ "role": "tool",+ "content": [+ {+ "type": "tool-result",+ "toolCallId": "tc1",+ "result": json.dumps({"contents": body}),+ }+ ],+ }+ return call, result+++def test_cursor_store_detects_a_real_skill_read():+ call, result = _skill_read_messages()+ data = _cursor_transcript({"role": "user", "content": "deploy this"}, call, result)+ signals = _signals(data)+ assert signals["skills_used"] == [{"path": "deploy", "count": 1}]+ assert signals["skill_definitions"] == [{"name": "deploy", "body": _SKILL_BODY}]+++def test_cursor_store_matches_any_root_by_basename():+ """Not tied to skills-cursor/ — a .codex/skills/ path counts the same."""+ call, result = _skill_read_messages(path="/home/user/.codex/skills/.system/skill-creator/SKILL.md")+ data = _cursor_transcript({"role": "user", "content": "hi"}, call, result)+ assert _signals(data)["skills_used"] == [{"path": "skill-creator", "count": 1}]+++def test_cursor_store_counts_repeat_reads_of_the_same_skill():+ call1, result1 = _skill_read_messages()+ call2 = json.loads(json.dumps(call1))+ call2["content"][0]["toolCallId"] = "tc2"+ result2 = json.loads(json.dumps(result1))+ result2["content"][0]["toolCallId"] = "tc2"+ data = _cursor_transcript(+ {"role": "user", "content": "go"}, call1, result1, call2, result2+ )+ assert _signals(data)["skills_used"] == [{"path": "deploy", "count": 2}]+++def test_cursor_store_ignores_a_read_of_an_unrelated_file():+ call, result = _skill_read_messages(path="/w/repo/main.py", body="print('hi')")+ data = _cursor_transcript({"role": "user", "content": "read main"}, call, result)+ assert _signals(data)["skills_used"] == []+++def test_cursor_store_requires_the_basename_not_just_a_skills_substring():+ """A path containing 'skills/' that isn't actually a SKILL.md read must+ not false-positive (e.g. reading a project's own src/skills/utils.py)."""+ call, result = _skill_read_messages(path="/w/repo/src/skills/utils.py", body="def f(): ...")+ data = _cursor_transcript({"role": "user", "content": "read utils"}, call, result)+ assert _signals(data)["skills_used"] == []+++def test_cursor_store_skill_detection_is_case_insensitive_on_basename():+ call, result = _skill_read_messages(path="/w/repo/skills/loop/Skill.MD")+ data = _cursor_transcript({"role": "user", "content": "go"}, call, result)+ assert _signals(data)["skills_used"] == [{"path": "loop", "count": 1}]+++def test_cursor_store_a_non_read_tool_never_counts_as_a_skill():+ call = {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "tc1",+ "toolName": "run_terminal_cmd",+ "args": {"command": "cat /w/repo/skills/deploy/SKILL.md"},+ }+ ],+ }+ result = {+ "role": "tool",+ "content": [{"type": "tool-result", "toolCallId": "tc1", "result": "ok"}],+ }+ data = _cursor_transcript({"role": "user", "content": "cat it"}, call, result)+ assert _signals(data)["skills_used"] == []+++def test_cursor_store_dangling_skill_call_with_no_result_still_counts_the_name():+ """A skill Read with no matching result (session ended mid-call) still+ gets a best-effort name capture, just with an empty body."""+ call, _result = _skill_read_messages()+ data = _cursor_transcript({"role": "user", "content": "go"}, call)+ signals = _signals(data)+ assert signals["skills_used"] == [{"path": "deploy", "count": 1}]+ assert signals["skill_definitions"] == []+++# --- IDE composer's real `*_v2` arg keys, not `"path"`/`"paths"` --+++def test_cursor_store_detects_a_real_skill_read_via_target_file_key():+ """IDE composer `read_file_v2` calls carry the path under `"targetFile"`,+ never under `"path"` (the key the fixture above assumes). This is the+ shape that must be detected."""+ call, result = _skill_read_messages(arg_key="targetFile")+ data = _cursor_transcript({"role": "user", "content": "deploy this"}, call, result)+ signals = _signals(data)+ assert signals["skills_used"] == [{"path": "deploy", "count": 1}]+ assert signals["skill_definitions"] == [{"name": "deploy", "body": _SKILL_BODY}]+++def test_cursor_store_normalizes_edit_file_v2_relative_workspace_path():+ """Same gap on the sibling `edit_file_v2` tool (aliased to+ `"Edit"`): calls carry the path under+ `"relativeWorkspacePath"`, never `"path"`/`"paths"`/`"file_path"`. Not a+ skill read, but exercises the same `_normalize_file_path_arg` path that+ also feeds `file_paths.py`'s read/edit/search counters."""+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ _normalize_file_path_arg,+ )++ args = _normalize_file_path_arg({"relativeWorkspacePath": "/w/repo/main.py"})+ assert args["file_path"] == "/w/repo/main.py"+++def test_cursor_store_file_path_survives_truncation_of_a_large_edit():+ """`_build_tool_span` truncates the JSON-serialized args to `_TRUNCATE` (2000) chars for `input.value`, which+ `file_paths.py`'s regex then scans. `edit_file_v2`'s real args carry the+ whole diff under `streamingContent` — easily past that limit on its own+ — so a `file_path` appended AFTER it would be sheared off by truncation+ before anything ever reads it. `_normalize_file_path_arg` must PREPEND+ the key so it survives regardless of how large the rest of args is."""+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ _normalize_file_path_arg,+ )++ args = _normalize_file_path_arg(+ {+ "relativeWorkspacePath": "/w/repo/main.py",+ "streamingContent": "x" * 5000,+ }+ )+ serialized = json.dumps(args)+ assert '"file_path": "/w/repo/main.py"' in serialized[:2000]+++# --- a real Read result can be a plain (non-JSON) string body ----+++def test_cursor_store_captures_a_plain_string_result_as_the_literal_body():+ """A result may carry `"result"` as the raw file content directly (not JSON,+ not wrapped in `{"contents": ...}`) - e.g. frontmatter starting with `---`,+ which fails `json.loads`. The raw string is kept as the literal body."""+ plain_body = "---\nname: deploy\ndescription: Deploy to AWS.\n---\n\nBody text."+ call = {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "tc1",+ "toolName": "read_file_v2",+ "args": {"targetFile": _SKILL_PATH},+ }+ ],+ }+ result = {+ "role": "tool",+ "content": [{"type": "tool-result", "toolCallId": "tc1", "result": plain_body}],+ }+ data = _cursor_transcript({"role": "user", "content": "deploy this"}, call, result)+ assert _signals(data)["skill_definitions"] == [{"name": "deploy", "body": plain_body}]+++def test_cursor_store_a_failed_skill_read_never_stores_the_error_as_a_body():+ """A failed read (file missing, permission+ denied, ...) still names the attempted skill, but its `"result"` is an+ error string, not file content. ANY non-JSON string is treated+ as a literal body — without an error check, this would store the error+ message itself as the skill's body. Must fall back to the same empty-+ body contract as a dangling call with no result at all."""+ call = {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "tc1",+ "toolName": "read_file_v2",+ "args": {"targetFile": _SKILL_PATH},+ }+ ],+ }+ result = {+ "role": "tool",+ "content": [+ {+ "type": "tool-result",+ "toolCallId": "tc1",+ "result": "Error: ENOENT: no such file or directory",+ "isError": True,+ }+ ],+ }+ data = _cursor_transcript({"role": "user", "content": "deploy this"}, call, result)+ signals = _signals(data)+ assert signals["skills_used"] == [{"path": "deploy", "count": 1}]+ assert signals["skill_definitions"] == []+++# --- build_sidecar_signals forwarding (pre-existing gap, fixed alongside) --+++def test_sidecar_forwards_captured_skill_definitions():+ """skill_definitions was missing from build_sidecar_signals'+ key allowlist from the day the field was added -- this affects EVERY+ source using the shared helper, not just Cursor. A captured body must+ actually reach the sidecar dict, not just harness.session_signals."""+ call, result = _skill_read_messages()+ data = _cursor_transcript({"role": "user", "content": "deploy this"}, call, result)+ _trace, spans = parse_cursor_store(data, "local:cursor:agent-1")+ sidecar = build_sidecar_signals(spans)+ assert sidecar["skill_definitions"] == [{"name": "deploy", "body": _SKILL_BODY}]+ assert sidecar["skills_used"] == [{"path": "deploy", "count": 1}]+++def test_sidecar_omits_skill_definitions_key_when_none_were_captured():+ """Absent, not an empty list -- matches the other signal keys' contract+ (build_sidecar_signals only ever sets a key when `sig.get(key)` is truthy)."""+ data = _cursor_transcript({"role": "user", "content": "hi"})+ _trace, spans = parse_cursor_store(data, "local:cursor:agent-1")+ assert "skill_definitions" not in build_sidecar_signals(spans)+++# --- cursor_agent_transcript.py (secondary fix) -----------------------------+++def _line(role: str, blocks: list[dict]) -> dict:+ return {"role": role, "message": {"content": blocks}}+++def _agent_transcript(*lines: dict) -> bytes:+ return "\n".join(json.dumps(line) for line in lines).encode()+++def _agent_transcript_signals(data: bytes) -> dict:+ _trace, spans = parse_cursor_agent_transcript(data, "local:cursor:agent-2")+ root = next(s for s in spans if s.parent_id is None)+ raw = root.attributes.get("harness.session_signals")+ return json.loads(raw) if raw else {}+++def test_agent_transcript_detects_a_skill_read_via_path_not_tool_name():+ """The pre-existing _SKILL_TOOL_NAMES check only matches Claude Code's own+ tool name ('skill'/'activate_skill') and never fires for Cursor's real+ 'Read' call — this is the actual signal that needs to work."""+ data = _agent_transcript(+ _line("user", [{"type": "text", "text": "<user_query>deploy</user_query>"}]),+ _line(+ "assistant",+ [+ {+ "type": "tool_use",+ "name": "ReadFile",+ "input": {"path": "/home/user/.cursor/skills-cursor/loop/SKILL.md"},+ "id": "t1",+ }+ ],+ ),+ )+ assert _agent_transcript_signals(data)["skills_used"] == [{"path": "loop", "count": 1}]+++def test_agent_transcript_read_of_unrelated_file_is_not_a_skill():+ data = _agent_transcript(+ _line("user", [{"type": "text", "text": "<user_query>read it</user_query>"}]),+ _line(+ "assistant",+ [{"type": "tool_use", "name": "Read", "input": {"path": "/a.py"}, "id": "t1"}],+ ),+ )+ assert _agent_transcript_signals(data)["skills_used"] == []+++def test_agent_transcript_legacy_tool_name_check_still_works():+ """Regression guard: the original skill/activate_skill tool-name path+ (kept as a defensive fallback) must keep working unchanged."""+ data = _agent_transcript(+ _line("user", [{"type": "text", "text": "<user_query>go</user_query>"}]),+ _line(+ "assistant",+ [{"type": "tool_use", "name": "skill", "input": {"skill": "entloop"}, "id": "t1"}],+ ),+ )+ assert _agent_transcript_signals(data)["skills_used"] == [{"path": "entloop", "count": 1}]diff --git a/python/tests/core/test_edit_lines.py b/python/tests/core/test_edit_lines.pynew file mode 100644index 0000000..220e7ba--- /dev/null+++ b/python/tests/core/test_edit_lines.py@@ -0,0 +1,221 @@+"""Unit tests for `ingestion/coding_agent/edit_lines.py` — AI lines of code.++Two properties matter and are pinned here: an `Edit` in context charges only+the lines it actually changed (not the whole surrounding block), and a session+that never produced a countable payload stays unmeasured (None) rather than+reporting 0.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta++import pytest++from agentplay._core.ingestion.coding_agent.edit_lines import (+ count_patch_lines,+ edit_line_counts,+)+from agentplay._core.ingestion.coding_agent.session_pure import (+ edit_line_totals,+ session_derived_metrics,+)+from agentplay._core.ingestion.coding_agent.spans import SpanData+++def _ts(offset_min: int = 0) -> datetime:+ return datetime(2026, 5, 30, 10, 0, 0, tzinfo=UTC) + timedelta(minutes=offset_min)+++def _tool(name: str, payload: dict, *, ok: bool = True, at: int = 0) -> SpanData:+ return SpanData(+ span_id=f"trace:tool:{name}:{at}",+ trace_id="trace",+ parent_id="trace:turn:1",+ name=name,+ span_kind="TOOL",+ status_code="OK" if ok else "ERROR",+ start_time=_ts(at),+ end_time=_ts(at),+ attributes={"tool.name": name, "input.value": json.dumps(payload)},+ )+++# ── per-call counting ───────────────────────────────────────────────+++def test_edit_charges_only_the_changed_line() -> None:+ """A one-line change inside a block is 1 added / 1 removed, not 3 each.++ This is the whole reason the module runs a real diff instead of measuring+ both strings — charging the surrounding context would inflate every session+ that edits in place.+ """+ counts = edit_line_counts(+ "Edit",+ json.dumps(+ {+ "file_path": "/a/b.py",+ "old_string": "def f():\n return 1\n",+ "new_string": "def f():\n return 2\n",+ }+ ),+ )+ assert counts == (1, 1)+++def test_pure_insertion_removes_nothing() -> None:+ counts = edit_line_counts(+ "Edit",+ json.dumps({"old_string": "a\nb\n", "new_string": "a\nNEW\nb\n"}),+ )+ assert counts == (1, 0)+++def test_write_counts_whole_body_as_added() -> None:+ """`Write` carries no prior text, so its body is all additions."""+ counts = edit_line_counts("Write", json.dumps({"content": "one\ntwo\nthree"}))+ assert counts == (3, 0)+++def test_trailing_newline_does_not_invent_a_line() -> None:+ assert edit_line_counts("Write", json.dumps({"content": "only\n"})) == (1, 0)+++def test_multiedit_sums_its_edits() -> None:+ counts = edit_line_counts(+ "MultiEdit",+ json.dumps(+ {+ "file_path": "/a/b.py",+ "edits": [+ {"old_string": "x\n", "new_string": "y\n"},+ {"old_string": "", "new_string": "added\n"},+ ],+ }+ ),+ )+ assert counts == (2, 1)+++def test_unhashable_tool_name_returns_none_not_typeerror() -> None:+ """`tool.name` is a span attribute, so a malformed transcript can put a list+ or dict there. `in` on an unhashable raises, and `edit_line_totals` has no+ per-call guard — one malformed tool would abort the whole session's counts.+ """+ assert edit_line_counts(["Edit"], '{"new_string": "x"}') is None+ assert edit_line_counts({"tool": "Edit"}, '{"new_string": "x"}') is None+ assert edit_line_counts(None, '{"new_string": "x"}') is None+++def test_uncountable_inputs_are_none_not_zero() -> None:+ """Unknown must never collapse to a confident 0."""+ assert edit_line_counts("Bash", json.dumps({"command": "sed -i s/a/b/ f.py"})) is None+ assert edit_line_counts("Read", json.dumps({"file_path": "/a/b.py"})) is None+ assert edit_line_counts("Edit", "not json at all") is None+ assert edit_line_counts("Edit", json.dumps({"file_path": "/a/b.py"})) is None+ assert edit_line_counts("Edit", "") is None+ assert edit_line_counts("Edit", None) is None+++# ── codex apply_patch ───────────────────────────────────────────────+++def test_count_patch_lines_counts_hunk_content_only() -> None:+ body = (+ "*** Begin Patch\n"+ "*** Update File: a.py\n"+ "@@ -1,3 +1,3 @@\n"+ " context\n"+ "-old line\n"+ "+new line\n"+ "+extra line\n"+ "*** End Patch\n"+ )+ assert count_patch_lines(body) == (2, 1)+++def test_count_patch_lines_counts_double_prefixed_content() -> None:+ """apply_patch has no `+++` / `---` file markers to skip.++ A source line beginning `++` is encoded `+++`, so treating those as unified-+ diff markers silently undercounted every such added line.+ """+ body = "*** Update File: a.cpp\n+++i;\n+plain\n---j;\n"+ assert count_patch_lines(body) == (2, 1)+++def test_stamped_counts_survive_truncation() -> None:+ """The whole point of stamping at parse time.++ Codex apply_patch spans are often cut+ mid-string by the parser's 2,000-char cap, so `json.loads` fails. The stamp+ sits in the retained prefix and is read by regex instead.+ """+ truncated = (+ '{"file_path": "a.py", "lines_added": 42, "lines_removed": 7, '+ '"patch": "*** Begin Patch\\n+one\\n+tw'+ )+ with pytest.raises(json.JSONDecodeError):+ json.loads(truncated)+ assert edit_line_counts("Edit", truncated) == (42, 7)+++def test_stamped_counts_win_over_the_payload_body() -> None:+ """A stamp was computed before truncation, so it is the better source."""+ stamped = (+ '{"file_path": "a.py", "lines_added": 99, "lines_removed": 1, '+ '"patch": "*** Begin Patch\\n+only-one-line\\n*** End Patch\\n"}'+ )+ assert edit_line_counts("Edit", stamped) == (99, 1)+++def test_unstamped_patch_payload_is_still_unmeasured() -> None:+ """An older parser emitted no stamp and no old_string / new_string."""+ complete = json.dumps({"file_path": "a.py", "patch": "*** Begin Patch\n+x\n"})+ assert edit_line_counts("Edit", complete) is None+++# ── session fold ────────────────────────────────────────────────────+++def test_session_totals_sum_successful_edits() -> None:+ calls = [+ _tool("Write", {"content": "a\nb\n"}, at=0),+ _tool("Edit", {"old_string": "a\n", "new_string": "z\n"}, at=1),+ ]+ from agentplay._core.ingestion.coding_agent.session_pure import _tool_calls++ assert edit_line_totals(_tool_calls(calls)) == (3, 1)+++def test_failed_edit_changed_no_lines() -> None:+ from agentplay._core.ingestion.coding_agent.session_pure import _tool_calls++ calls = _tool_calls([_tool("Edit", {"old_string": "a\n", "new_string": "z\n"}, ok=False)])+ assert edit_line_totals(calls) == (None, None)+++def test_session_with_no_edits_is_unmeasured() -> None:+ from agentplay._core.ingestion.coding_agent.session_pure import _tool_calls++ calls = _tool_calls([_tool("Read", {"file_path": "/a/b.py"})])+ assert edit_line_totals(calls) == (None, None)+++# ── output keys ──────────────────────────────────────────────────────+++def test_keys_reach_the_wire_when_measured() -> None:+ spans = [_tool("Write", {"content": "a\nb\nc\n"})]+ out = session_derived_metrics(spans)+ assert out["lines_added"] == 3+ assert out["lines_removed"] == 0+++def test_keys_omitted_when_unmeasured() -> None:+ """Omitted, not null-valued, so a consumer can show "unmeasured" instead of 0."""+ out = session_derived_metrics([_tool("Read", {"file_path": "/a/b.py"})])+ assert "lines_added" not in out+ assert "lines_removed" not in outdiff --git a/python/tests/core/test_head_scan_window.py b/python/tests/core/test_head_scan_window.pynew file mode 100644index 0000000..45855d4--- /dev/null+++ b/python/tests/core/test_head_scan_window.py@@ -0,0 +1,315 @@+"""Head-scanning must read every line `_read_head` returned, not the first 20.++# Why this exists++`_read_head` returns complete lines rather than a byte slab, so a giant opening+record is never cut mid-JSON. It returns *at least* 20 complete lines and+usually more (it reads 64KB chunks), so callers must scan all of them rather+than slicing `head.split(b"\n")[:20]` and dropping the remainder.++Some transcripts open with 23-67 lines of+metadata (`ai-title`, `agent-name`, `mode`, `permission-mode`,+`file-history-snapshot`, `cursor_usage_event`) before the first real record.+Discarding the head above the cap would drop those sessions, including a+`cursor-ide` transcript whose `cursor_usage_event` stream is the only place its+billed tokens live.++A transcript is not malformed because it front-loads metadata.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources.local.parsers.base import detect_agent+++def _claude_transcript(metadata_lines: int) -> bytes:+ """A valid Claude Code transcript preceded by `metadata_lines` of preamble."""+ kinds = ["ai-title", "agent-name", "mode", "permission-mode", "file-history-snapshot"]+ head = [json.dumps({"type": kinds[i % len(kinds)]}) for i in range(metadata_lines)]+ head.append(+ json.dumps(+ {+ "type": "user",+ "message": {"role": "user", "content": "hi"},+ "sessionId": "s",+ "uuid": "u",+ "timestamp": "2026-07-31T00:00:00Z",+ }+ )+ )+ return "\n".join(head).encode()+++def test_detects_when_the_first_record_is_within_the_old_window() -> None:+ """The case that always worked — must keep working."""+ assert detect_agent(_claude_transcript(5)) is not None+++def test_detects_when_the_first_record_sits_just_past_line_20() -> None:+ """23-28 metadata lines push the first `user` record past line 20; a valid+ transcript must still be detected rather than skipped."""+ assert detect_agent(_claude_transcript(23)) is not None+ assert detect_agent(_claude_transcript(28)) is not None+++def test_detects_a_deeply_front_loaded_transcript() -> None:+ """The worst observed opener ran to 67 metadata lines (a cursor-ide file)."""+ assert detect_agent(_claude_transcript(67)) is not None+++def test_still_returns_none_for_a_file_with_no_agent_marker() -> None:+ """Widening the scan must not make detection credulous — an unrecognised+ file still has to be skipped rather than guessed at."""+ junk = b"\n".join(json.dumps({"type": "ai-title"}).encode() for _ in range(40))+ assert detect_agent(junk) is None+++def test_empty_input_is_none() -> None:+ assert detect_agent(b"") is None+++# --- The READ axis -----------------------------------------------------------+# A third failure mode. The byte axis was fixed (complete lines, not a+# 32KB slab) and the line axis was fixed (scan every line the head returned).+# What stayed broken is how much `_read_head` *reads*: it stopped as soon as it+# held `min_lines` complete lines, so a transcript whose identifying record sits+# past that point never had it in the buffer at all — the scan above cannot find+# what was never read.+#+# Observed: a large real transcript opens with 39 metadata records, its first+# `user` line is #40, and a single 64KB chunk already satisfied 20 lines at line+# 25. `detect_agent` returned None and that session was skipped on EVERY scan,+# permanently. Detection is why the head is read, so detection is what has to+# decide when to stop.+++def _write(tmp_path, name: str, payload: bytes):+ p = tmp_path / name+ p.write_bytes(payload)+ return p+++def test_reads_past_min_lines_until_the_agent_marker_is_found(tmp_path) -> None:+ """The regression: 39 metadata records, identifying record at line 40."""+ from agentplay._core.ingestion.coding_agent._sources.local.source import (+ _agent_detected,+ _read_head,+ )++ # Pad each metadata line so 20 lines comfortably exceed one 64KB chunk,+ # reproducing "chunk satisfied min_lines before the marker was reached".+ filler = "x" * 4000+ lines = [json.dumps({"type": "queue-operation", "pad": filler}) for _ in range(39)]+ lines.append(+ json.dumps(+ {+ "type": "assistant",+ "message": {"role": "assistant", "content": "hi"},+ "sessionId": "s",+ "uuid": "u",+ "timestamp": "2026-08-13T00:00:00Z",+ }+ )+ )+ f = _write(tmp_path, "long_preamble.jsonl", "\n".join(lines).encode())++ assert detect_agent(_read_head(f)) is None, "precondition: the old stop rule misses it"+ assert detect_agent(_read_head(f, stop_when=_agent_detected)) is not None+++def test_common_case_still_stops_at_the_first_chunk(tmp_path) -> None:+ """The predicate must not turn every scan into a full-file read."""+ from agentplay._core.ingestion.coding_agent._sources.local.source import (+ _agent_detected,+ _read_head,+ )++ body = [+ json.dumps(+ {+ "type": "user",+ "message": {"role": "user", "content": "hi"},+ "sessionId": "s",+ "uuid": f"u{i}",+ "timestamp": "2026-08-13T00:00:00Z",+ }+ )+ for i in range(4000)+ ]+ f = _write(tmp_path, "normal.jsonl", "\n".join(body).encode())++ head = _read_head(f, stop_when=_agent_detected)+ assert detect_agent(head) is not None+ assert len(head) <= 65536, "a normal transcript must still cost one chunk"+++def test_unrecognisable_file_is_bounded_by_max_bytes(tmp_path) -> None:+ """No marker ever appears — the read must stop, not run to EOF unbounded."""+ from agentplay._core.ingestion.coding_agent._sources.local.source import (+ _agent_detected,+ _read_head,+ )++ junk = "\n".join(json.dumps({"type": "nope", "i": i}) for i in range(50_000))+ f = _write(tmp_path, "junk.jsonl", junk.encode())++ head = _read_head(f, stop_when=_agent_detected, max_bytes=200_000)+ assert detect_agent(head) is None+ assert len(head) <= 200_000 + 65536+++def test_predicate_sees_each_line_once_not_the_whole_buffer(tmp_path) -> None:+ """Guards the O(n^2) trap.++ Handing `stop_when` the whole accumulated buffer every chunk made an+ unrecognised 5.9MB JSONL cost 1.3s instead of 0.1ms. Asserting on total+ bytes handed to the predicate rather than wall-clock keeps this+ deterministic: linear means ~one pass over the file, quadratic means+ hundreds.+ """+ from agentplay._core.ingestion.coding_agent._sources.local.source import _read_head++ junk = "\n".join(json.dumps({"type": "nope", "i": i, "pad": "x" * 80}) for i in range(20_000))+ f = _write(tmp_path, "junk.jsonl", junk.encode())+ size = f.stat().st_size++ seen = []++ def _never(buf: bytes) -> bool:+ seen.append(len(buf))+ return False++ _read_head(f, stop_when=_never, max_bytes=size + 1)++ # Every complete line offered exactly once => total <= file size.+ assert sum(seen) <= size, f"predicate re-read the buffer: {sum(seen):,} > {size:,}"+++def test_predicate_segments_do_not_overlap(tmp_path) -> None:+ """Each segment must start where the previous ended, on a line boundary."""+ from agentplay._core.ingestion.coding_agent._sources.local.source import _read_head++ body = "\n".join(json.dumps({"type": "meta", "i": i, "pad": "z" * 500}) for i in range(2_000))+ f = _write(tmp_path, "segments.jsonl", body.encode())++ chunks = []++ def _collect(buf: bytes) -> bool:+ chunks.append(buf)+ return False++ _read_head(f, stop_when=_collect, max_bytes=f.stat().st_size + 1)++ rejoined = b"".join(chunks)+ assert rejoined == f.read_bytes()[: len(rejoined)], "segments must tile the file in order"+ for c in chunks:+ assert c.endswith(b"\n"), "every segment must end on a line boundary"+++def test_metadata_is_found_on_a_late_first_record(tmp_path) -> None:+ """Fourth cap, same failure.++ Rescuing a long-preamble session from the drop is only half the job: `cwd`+ and `gitBranch` live on the SAME late record that detection was looking for,+ so a 30-line cap in `_first_field_in_cc_head` returned None for both and the+ session landed with no repo attribution — silently degraded, which is worse+ than the drop it replaced.+ """+ from agentplay._core.ingestion.coding_agent._sources.local.source import (+ _branch_from_cc_head,+ _cwd_from_cc_head,+ )++ lines = [json.dumps({"type": "queue-operation", "i": i}) for i in range(39)]+ lines.append(+ json.dumps(+ {+ "type": "user",+ "message": {"role": "user", "content": "hi"},+ "sessionId": "s",+ "uuid": "u",+ "timestamp": "2026-08-13T00:00:00Z",+ "cwd": "/Users/dev/repo",+ "gitBranch": "feat/x",+ }+ )+ )+ head = "\n".join(lines).encode()++ assert _cwd_from_cc_head(head) == "/Users/dev/repo"+ assert _branch_from_cc_head(head) == "feat/x"+++def test_metadata_on_the_first_record_still_returns_immediately(tmp_path) -> None:+ """The common case must not pay for the uncapped scan."""+ from agentplay._core.ingestion.coding_agent._sources.local.source import _cwd_from_cc_head++ first = json.dumps(+ {"type": "user", "sessionId": "s", "uuid": "u", "cwd": "/repo", "gitBranch": "main"}+ )+ tail = "\n".join(json.dumps({"type": "user", "i": i}) for i in range(5_000))+ assert _cwd_from_cc_head(f"{first}\n{tail}".encode()) == "/repo"+++def test_no_complete_line_means_the_predicate_is_never_called(tmp_path) -> None:+ """A buffer holding no complete line must not be handed to `stop_when`.++ Scope note, because the obvious stronger claim does not hold: this does NOT+ prove the line-boundary search is O(chunk). The earlier whole-buffer `rfind`+ also returned -1 here and also skipped the call, so this assertion passes on+ both implementations. The O(chunk) property comes from searching the chunk+ rather than the buffer (`chunk.rfind` + the chunk's start offset) and is+ structural, not asserted here — a pure cost property needs either timing,+ which is flaky, or instrumentation the function does not expose.++ What this does pin: partial records are never parsed.+ """+ from agentplay._core.ingestion.coding_agent._sources.local.source import _read_head++ f = _write(tmp_path, "single.jsonl", (json.dumps({"type": "x", "pad": "y" * 900_000})).encode())++ calls = []++ def _never(buf: bytes) -> bool:+ calls.append(len(buf))+ return False++ _read_head(f, stop_when=_never, max_bytes=f.stat().st_size + 1)++ assert calls == [], "a buffer with no complete line must not be scanned"+++def test_line_boundary_is_tracked_across_a_giant_opener(tmp_path) -> None:+ """A giant first line followed by real records still finds the marker.++ The fixture ends with a trailing newline on purpose: without it the marker+ record is not a COMPLETE line, so `stop_when` never receives it and+ `detect_agent` would only see it in the EOF buffer `_read_head` returns+ anyway — the test would pass even if predicate-based stopping were broken.+ """+ from agentplay._core.ingestion.coding_agent._sources.local.source import (+ _agent_detected,+ _cwd_from_cc_head,+ _read_head,+ )++ lines = [json.dumps({"type": "queue-operation", "pad": "y" * 300_000})]+ lines += [json.dumps({"type": "meta", "i": i}) for i in range(30)]+ lines.append(+ json.dumps({"type": "user", "sessionId": "s", "uuid": "u", "cwd": "/repo"})+ )+ f = _write(tmp_path, "mixed.jsonl", ("\n".join(lines) + "\n").encode())++ # The predicate itself must be satisfied, not just the returned buffer.+ seen = []++ def _spy(buf: bytes) -> bool:+ seen.append(buf)+ return _agent_detected(buf)++ head = _read_head(f, stop_when=_spy)+ assert any(_agent_detected(b) for b in seen), "the marker must reach stop_when"+ assert detect_agent(head) is not None+ assert _cwd_from_cc_head(head) == "/repo"diff --git a/python/tests/core/test_local_source_codex_archived.py b/python/tests/core/test_local_source_codex_archived.pynew file mode 100644index 0000000..c8ed28e--- /dev/null+++ b/python/tests/core/test_local_source_codex_archived.py@@ -0,0 +1,170 @@+"""An archived Codex thread is still a Codex session.++Codex MOVES a rollout, unchanged, from `sessions/YYYY/MM/DD/` to a flat+`archived_sessions/` when the developer archives the thread .+`LocalSource` walked `sessions/` only, so an archived session could never be+found again on a later scan, and one archived before its first scan was+never captured at all.++The session id is built from the file stem, which the move does not change, so+reading the second folder cannot mint a second session for the same thread.+"""++from __future__ import annotations++import json+from pathlib import Path++from agentplay._core.ingestion.coding_agent._sources.local.source import (+ LocalSource,+ codex_rollout_dirs,+)++LIVE = "01a0a028-0000-7000-8000-0000000000a1"+ARCHIVED = "01a0a028-0000-7000-8000-0000000000a2"+ARCHIVED_IMPORT = "01a0a028-0000-7000-8000-0000000000a3"++_META = {"type": "session_meta", "payload": {"originator": "codex_cli_rs", "cwd": "/repo"}}+_TURN = {"type": "turn_context", "payload": {"model": "gpt-6-astra"}}+++def _name(thread_id: str) -> str:+ return f"rollout-2026-09-08T22-45-23-{thread_id}.jsonl"+++def _write(path: Path, records: list[dict]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"\n".join(json.dumps(r).encode() for r in records) + b"\n")+++def _session_id(thread_id: str) -> str:+ return f"local:codex:rollout-2026-09-08T22-45-23-{thread_id}"+++def _discovered(home: Path) -> set[str]:+ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ return {d.session_id for d in source.discover_sessions()}+++def test_an_archived_rollout_is_discovered_under_the_same_session_id(tmp_path: Path) -> None:+ home = tmp_path / ".codex"+ _write(home / "sessions" / "2026" / "09" / "08" / _name(LIVE), [_META, _TURN])+ _write(home / "archived_sessions" / _name(ARCHIVED), [_META, _TURN])++ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ found = {d.session_id for d in source.discover_sessions()}++ assert found == {_session_id(LIVE), _session_id(ARCHIVED)}+ assert source.discovery_stats()["codex"] == {"seen": 2, "indexed": 2, "skipped": {}}+++def test_a_home_holding_only_archived_rollouts_is_still_walked(tmp_path: Path) -> None:+ home = tmp_path / ".codex"+ _write(home / "archived_sessions" / _name(ARCHIVED), [_META, _TURN])++ assert _discovered(home) == {_session_id(ARCHIVED)}+ assert codex_rollout_dirs(home) == [home / "archived_sessions"]+++def test_the_import_skip_applies_to_an_archived_rollout_too(tmp_path: Path) -> None:+ home = tmp_path / ".codex"+ _write(home / "archived_sessions" / _name(ARCHIVED), [_META, _TURN])+ _write(home / "archived_sessions" / _name(ARCHIVED_IMPORT), [_META])+ (home / "external_agent_session_imports.json").write_text(+ json.dumps({"records": [{"imported_thread_id": ARCHIVED_IMPORT}]})+ )++ assert _discovered(home) == {_session_id(ARCHIVED)}+++def test_one_thread_in_both_folders_is_one_session_and_the_fuller_copy_wins(tmp_path: Path) -> None:+ # Codex moves rather than copies, so this should not happen; if a tool ever+ # leaves both behind, the index must not pick the truncated one.+ home = tmp_path / ".codex"+ stale = home / "sessions" / "2026" / "09" / "08" / _name(LIVE)+ full = home / "archived_sessions" / _name(LIVE)+ _write(stale, [_META])+ _write(full, [_META, _TURN, _TURN])++ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ found = [d.session_id for d in source.discover_sessions()]++ assert found == [_session_id(LIVE)]+ assert source._build_index()[_session_id(LIVE)].path == full+++def test_a_directory_with_neither_folder_is_not_a_codex_home(tmp_path: Path) -> None:+ (tmp_path / ".codex" / "log").mkdir(parents=True)++ assert codex_rollout_dirs(tmp_path / ".codex") == []+ assert _discovered(tmp_path / ".codex") == set()+++_SPAN_RECORDS = [+ {+ "timestamp": "2026-09-08T22:45:23.000Z",+ "type": "session_meta",+ "payload": {"originator": "codex_cli_rs", "cwd": "/repo"},+ },+ {+ "timestamp": "2026-09-08T22:45:24.000Z",+ "type": "turn_context",+ "payload": {"model": "gpt-6-astra", "cwd": "/repo"},+ },+ {+ "timestamp": "2026-09-08T22:45:25.000Z",+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "hello"}],+ },+ },+ {+ "timestamp": "2026-09-08T22:45:26.000Z",+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "hi"}],+ },+ },+]+++def test_a_rollout_archived_after_indexing_is_re_resolved_and_read(tmp_path: Path, caplog) -> None:+ """A rollout that moved (was archived) between discovery and read is found again."""+ home = tmp_path / ".codex"+ live = home / "sessions" / "2026" / "09" / "08" / _name(LIVE)+ _write(live, _SPAN_RECORDS)+ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ assert {d.session_id for d in source.discover_sessions()} == {_session_id(LIVE)}++ (home / "archived_sessions").mkdir()+ live.rename(home / "archived_sessions" / _name(LIVE))++ with caplog.at_level("INFO"):+ spans = source.get_spans_by_session(_session_id(LIVE))++ assert len(spans) == 2+ assert not [r for r in caplog.records if r.levelname == "ERROR"]+ # Counts describe the rebuilt walk, not both walks added together.+ assert source.discovery_stats()["codex"] == {"seen": 1, "indexed": 1, "skipped": {}}+++def test_a_rollout_deleted_after_indexing_returns_nothing_without_an_error(+ tmp_path: Path, caplog+) -> None:+ home = tmp_path / ".codex"+ live = home / "sessions" / "2026" / "09" / "08" / _name(LIVE)+ _write(live, _SPAN_RECORDS)+ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ list(source.discover_sessions())+ live.unlink()++ with caplog.at_level("INFO"):+ spans = source.get_spans_by_session(_session_id(LIVE))++ assert spans == []+ assert not [r for r in caplog.records if r.levelname == "ERROR"]+ assert any("moved or deleted" in r.getMessage() for r in caplog.records)diff --git a/python/tests/core/test_local_source_codex_imports.py b/python/tests/core/test_local_source_codex_imports.pynew file mode 100644index 0000000..4314d10--- /dev/null+++ b/python/tests/core/test_local_source_codex_imports.py@@ -0,0 +1,163 @@+"""A transcript Codex imported from another agent is not a Codex session.++Codex can import another agent's sessions. It writes each one as an ordinary `sessions/**/rollout-*.jsonl` and+records the import in `<codex home>/external_agent_session_imports.json`. The+original session is already captured under its own agent, so indexing the copy+counted it a second time -- as a Codex session with no model, $0 and a+total-only token count the parser rightly refuses to price.++The skip needs BOTH halves, and these tests pin each one:++* the thread is in Codex's own import ledger -- never a guess from the file's+ shape, so a real session that merely looks empty is still captured; and+* Codex never ran a turn of its own in it (no `turn_context` record) -- an+ import the developer then CONTINUED in Codex carries real Codex spend and+ must still be captured.++Anything wrong with the ledger fails open: every rollout is indexed, exactly as+before the ledger was consulted.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from agentplay._core.ingestion.coding_agent._sources.local.source import (+ LocalSource,+ _codex_ran_a_turn,+)++IMPORTED = "01a0a028-0000-7000-8000-00000000000a"+CONTINUED = "01a0a028-0000-7000-8000-00000000000b"+REAL = "01a0a028-0000-7000-8000-00000000000c"+REAL_BUT_EMPTY = "01a0a028-0000-7000-8000-00000000000d"++_META = {"type": "session_meta", "payload": {"originator": "codex_cli_rs", "cwd": "/repo"}}+_TURN = {"type": "turn_context", "payload": {"model": "gpt-5.6-sol"}}+# What an import carries: the ORIGINAL session's size as a total-only count.+_TOTAL_ONLY_USAGE = {+ "type": "event_msg",+ "payload": {+ "type": "token_count",+ "info": {+ "total_token_usage": {"input_tokens": 0, "output_tokens": 0, "total_tokens": 493481}+ },+ },+}+_REAL_USAGE = {+ "type": "event_msg",+ "payload": {+ "type": "token_count",+ "info": {+ "total_token_usage": {"input_tokens": 900, "output_tokens": 100, "total_tokens": 1000}+ },+ },+}+++def _session_id(thread_id: str) -> str:+ return f"local:codex:rollout-2026-09-08T07-23-37-{thread_id}"+++def _write_rollout(home: Path, thread_id: str, records: list[dict]) -> None:+ day = home / "sessions" / "2026" / "09" / "08"+ day.mkdir(parents=True, exist_ok=True)+ body = b"\n".join(json.dumps(r).encode() for r in records) + b"\n"+ (day / f"rollout-2026-09-08T07-23-37-{thread_id}.jsonl").write_bytes(body)+++def _codex_home(tmp_path: Path) -> Path:+ home = tmp_path / ".codex"+ _write_rollout(home, IMPORTED, [_META, _TOTAL_ONLY_USAGE])+ _write_rollout(home, CONTINUED, [_META, _TOTAL_ONLY_USAGE, _TURN, _REAL_USAGE])+ _write_rollout(home, REAL, [_META, _TURN, _REAL_USAGE])+ _write_rollout(home, REAL_BUT_EMPTY, [_META])+ return home+++def _ledger(*thread_ids: str) -> str:+ return json.dumps(+ {+ "records": [+ {"imported_thread_id": t, "source_path": "/home/dev/.claude/projects/-repo/x.jsonl"}+ for t in thread_ids+ ],+ "detected_connector_records": [],+ }+ )+++def _discovered(home: Path) -> set[str]:+ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ return {d.session_id for d in source.discover_sessions()}+++def test_only_the_imported_and_never_continued_rollout_is_skipped(tmp_path: Path) -> None:+ home = _codex_home(tmp_path)+ (home / "external_agent_session_imports.json").write_text(_ledger(IMPORTED, CONTINUED))++ source = LocalSource(claude_code_homes=[], codex_homes=[home])+ found = {d.session_id for d in source.discover_sessions()}++ assert found == {_session_id(CONTINUED), _session_id(REAL), _session_id(REAL_BUT_EMPTY)}+ assert source.discovery_stats()["codex"] == {+ "seen": 4,+ "indexed": 3,+ "skipped": {"imported_not_continued": 1},+ }+++ "ledger",+ [+ None, # no ledger at all: Codex never imported anything+ "{not json",+ "[]",+ '{"records": "nope"}',+ '{"records": [null, 7, {"imported_thread_id": null}, {"title": "no id"}]}',+ ],+)+def test_a_missing_or_malformed_ledger_skips_nothing(tmp_path: Path, ledger: str | None) -> None:+ home = _codex_home(tmp_path)+ if ledger is not None:+ (home / "external_agent_session_imports.json").write_text(ledger)++ assert _discovered(home) == {+ _session_id(IMPORTED),+ _session_id(CONTINUED),+ _session_id(REAL),+ _session_id(REAL_BUT_EMPTY),+ }+++def test_valid_records_still_count_beside_malformed_ones(tmp_path: Path) -> None:+ home = _codex_home(tmp_path)+ (home / "external_agent_session_imports.json").write_text(+ json.dumps({"records": [None, {"imported_thread_id": 7}, {"imported_thread_id": IMPORTED}]})+ )++ assert _session_id(IMPORTED) not in _discovered(home)+++def test_a_rollout_that_cannot_be_read_is_never_the_reason_to_skip(tmp_path: Path) -> None:+ # Gone between the head read and the scan: "ran a turn" keeps it captured.+ assert _codex_ran_a_turn(tmp_path / "vanished.jsonl") is True+++def test_a_transcript_that_only_mentions_turn_context_is_still_an_import(tmp_path: Path) -> None:+ # Only a record whose OWN type is `turn_context` is a Codex turn. An imported+ # conversation about Codex rollouts quotes the name in its text, and another+ # record can carry it as a value.+ home = tmp_path / ".codex"+ quoted_in_text = {+ "type": "response_item",+ "payload": {"type": "message", "role": "user", "content": 'grep "turn_context" x.jsonl'},+ }+ carried_as_a_value = {"type": "event_msg", "payload": {"type": "turn_context"}}+ _write_rollout(home, IMPORTED, [_META, quoted_in_text, carried_as_a_value, _TOTAL_ONLY_USAGE])+ (home / "external_agent_session_imports.json").write_text(_ledger(IMPORTED))++ assert _discovered(home) == set()diff --git a/python/tests/core/test_local_source_copilot_vscode.py b/python/tests/core/test_local_source_copilot_vscode.pynew file mode 100644index 0000000..0b33be8--- /dev/null+++ b/python/tests/core/test_local_source_copilot_vscode.py@@ -0,0 +1,263 @@+"""LocalSource wiring for Copilot in VS Code (Chat/agent mode) --+agentplay._core half. The parser (`parse_copilot_vscode`) and+its `detect_agent` branch are tested elsewhere (test_copilot_vscode_parser.py,+test_parser_invariants.py); this file pins that a real file on disk actually+gets discovered, classified, deduped and dispatched end to end.++# Why this exists++The .json branch has a real gap other agents don't: `_read_head`'s DEFAULT+behaviour (no `stop_when`) stops as soon as 20 lines accumulate, which is the+right trade for the .jsonl branch (only the first line matters) but wrong for+a pretty-printed whole document -- a real 1.6KB local Copilot .json session+with ZERO requests was already 66 lines. Reading a large one with the default+would truncate it, and `json.loads` on the truncated blob would then always+fail, silently dropping the session from discovery forever (the exact class+of bug `_read_head`'s own docstring already describes fixing twice for other+agents). `test_a_large_json_document_past_the_default_line_cap_is_not_truncated`+pins the fix.+"""++from __future__ import annotations++import json+import os+from pathlib import Path++from agentplay._core.ingestion.coding_agent._sources.local.source import LocalSource+++def _snapshot_line(session_id: str, requests: list[dict]) -> bytes:+ return (+ json.dumps({"kind": 0, "v": {"sessionId": session_id, "requests": requests}}) + "\n"+ ).encode()+++def _snapshot_line_padded(session_id: str, requests: list[dict], target_len: int) -> bytes:+ """Like `_snapshot_line`, but padded with an extra `_pad` field so the+ encoded line is exactly `target_len` bytes -- for fixtures that must+ differ in content while being byte-identical in size."""+ unpadded = (+ json.dumps({"kind": 0, "v": {"sessionId": session_id, "requests": requests, "_pad": ""}})+ + "\n"+ ).encode()+ needed = target_len - len(unpadded)+ assert needed >= 0, f"target_len {target_len} smaller than the unpadded fixture ({len(unpadded)}B)"+ padded = (+ json.dumps(+ {+ "kind": 0,+ "v": {"sessionId": session_id, "requests": requests, "_pad": "x" * needed},+ }+ )+ + "\n"+ ).encode()+ assert len(padded) == target_len+ return padded+++def _splice_line(request: dict) -> bytes:+ return (json.dumps({"kind": 2, "k": ["requests"], "v": [request]}) + "\n").encode()+++def _request(request_id: str, ts_ms: int = 1) -> dict:+ return {"requestId": request_id, "timestamp": ts_ms, "elapsedMs": 1, "result": {}}+++class TestDiscoveryAndDispatch:+ def test_a_real_jsonl_snapshot_session_is_discovered_and_parses(self, tmp_path: Path):+ home = tmp_path / "Code" / "User"+ ws = home / "workspaceStorage" / "abc123" / "chatSessions"+ ws.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000001"+ session_id = f"local:copilot-vscode:{sid}"+ (ws / f"{sid}.jsonl").write_bytes(_snapshot_line(sid, [_request("r1")]))++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert len(found) == 1+ assert source.get_agent_type(session_id) == "copilot-vscode"+ assert source.discovery_stats()["copilot-vscode"] == {+ "seen": 1,+ "indexed": 1,+ "skipped": {},+ }+ spans = source.get_spans_by_session(session_id)+ assert any(s.name == "Turn 1" for s in spans), "parser was never dispatched"++ def test_a_real_json_document_session_is_discovered_and_parses(self, tmp_path: Path):+ home = tmp_path / "Code" / "User"+ ews = home / "globalStorage" / "emptyWindowChatSessions"+ ews.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000002"+ session_id = f"local:copilot-vscode:{sid}"+ doc = json.dumps(+ {"sessionId": sid, "requests": [_request("r1")]}, indent=2+ ).encode()+ (ews / f"{sid}.json").write_bytes(doc)++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert len(found) == 1+ assert source.get_agent_type(session_id) == "copilot-vscode"+ spans = source.get_spans_by_session(session_id)+ assert any(s.name == "Turn 1" for s in spans)++ def test_a_large_json_document_past_the_default_line_cap_is_not_truncated(+ self, tmp_path: Path+ ):+ # Regression: `_read_head` without `stop_when` stops at 20 LINES, but+ # only takes effect past the first 65536-byte chunk (the first chunk+ # is always read whole, so a small fixture hides the bug entirely --+ # caught in review of this very test: an earlier ~4KB/40-request+ # version of this fixture passed identically with and without the+ # fix, proving nothing). This fixture is deliberately padded well+ # past 65536 bytes so it spans multiple chunk reads, which is where+ # the early stop actually bites.+ home = tmp_path / "Code" / "User"+ ews = home / "globalStorage" / "emptyWindowChatSessions"+ ews.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000003"+ session_id = f"local:copilot-vscode:{sid}"+ n = 400+ requests = [+ {**_request(f"r{i}", ts_ms=i), "padding": "x" * 150} for i in range(n)+ ]+ doc = json.dumps({"sessionId": sid, "requests": requests}, indent=2).encode()+ assert len(doc) > 100_000, f"fixture must span multiple 65536B chunks, got {len(doc)}B"+ assert doc.count(b"\n") > 20, "fixture must exceed the 20-line default cap too"+ (ews / f"{sid}.json").write_bytes(doc)++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert len(found) == 1, "a truncated document fails json.loads and drops the session"+ spans = source.get_spans_by_session(session_id)+ turns = [s for s in spans if s.name.startswith("Turn")]+ assert len(turns) == n, f"expected all {n} requests parsed, got {len(turns)}"++ def test_the_larger_jsonl_sibling_wins_over_a_smaller_json_even_when_older(+ self, tmp_path: Path+ ):+ # No bespoke "prefer jsonl" rule -- this relies on the SAME+ # size-first collision resolution every other agent's multi-file+ # case already uses (`_index_put`: byte size is the "more complete"+ # signal since transcripts are append-only; mtime only breaks an+ # EXACT size tie, per that function's own docstring).+ #+ # To prove SIZE, not recency, decides: the smaller .json is written+ # SECOND (so it has the newer mtime) and must still lose.+ home = tmp_path / "Code" / "User"+ ews = home / "globalStorage" / "emptyWindowChatSessions"+ ws = home / "workspaceStorage" / "abc123" / "chatSessions"+ ews.mkdir(parents=True)+ ws.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000004"+ session_id = f"local:copilot-vscode:{sid}"+ jsonl_bytes = _snapshot_line(sid, [_request("r1")])+ json_bytes = json.dumps({"sessionId": sid, "requests": []}, indent=2).encode()+ assert len(jsonl_bytes) > len(json_bytes), "fixture must genuinely differ in size"++ (ws / f"{sid}.jsonl").write_bytes(jsonl_bytes) # larger, written (and so aged) first+ (ews / f"{sid}.json").write_bytes(json_bytes) # smaller, written second -> newer mtime++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert len(found) == 1, "same sessionId from two files must collapse to one session"+ spans = source.get_spans_by_session(session_id)+ # The larger .jsonl (with a real request) won despite being older.+ assert any(s.name == "Turn 1" for s in spans)++ def test_the_newer_file_wins_a_collision_only_when_sizes_are_exactly_equal(+ self, tmp_path: Path+ ):+ # Complement to the size-wins test above: `_index_put` compares+ # `(size, mtime)` as a tuple, so mtime is only ever consulted once+ # size is tied. Equal-size, distinct-content candidates isolate that+ # branch -- unequal sizes (as above) would pass even with a broken+ # mtime tie-break.+ home = tmp_path / "Code" / "User"+ ws = home / "workspaceStorage" / "abc123" / "chatSessions"+ ws.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000006"+ newer = _snapshot_line(sid, [_request("r1"), _request("r2")])+ older = _snapshot_line_padded(sid, [_request("r1")], target_len=len(newer))+ assert len(older) == len(newer), "fixture must be an exact size tie"++ older_path = ws / f"{sid}-a.jsonl"+ newer_path = ws / f"{sid}-b.jsonl"+ older_path.write_bytes(older)+ newer_path.write_bytes(newer)+ now = older_path.stat().st_mtime+ os.utime(older_path, (now - 60, now - 60))+ os.utime(newer_path, (now, now))++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert len(found) == 1, "same sessionId from two files must collapse to one session"+ session_id = f"local:copilot-vscode:{sid}"+ spans = source.get_spans_by_session(session_id)+ turns = [s for s in spans if s.name.startswith("Turn")]+ assert len(turns) == 2, "the newer, equal-sized file (2 requests) must win the tie"++ def test_a_stray_non_matching_file_is_skipped_not_misindexed(self, tmp_path: Path):+ home = tmp_path / "Code" / "User"+ ws = home / "workspaceStorage" / "abc123" / "chatSessions"+ ws.mkdir(parents=True)+ (ws / "not-a-session.jsonl").write_bytes(b'{"unrelated": "shape"}\n')++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert found == []+ assert source.discovery_stats()["copilot-vscode"]["skipped"].get("detection_failed") == 1++ def test_an_empty_file_is_skipped_and_labelled(self, tmp_path: Path):+ home = tmp_path / "Code" / "User"+ ews = home / "globalStorage" / "emptyWindowChatSessions"+ ews.mkdir(parents=True)+ (ews / "empty.json").touch()++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ source.discover_sessions()++ assert (+ source.discovery_stats()["copilot-vscode"]["skipped"].get("empty_or_unreadable") == 1+ )++ def test_a_final_state_json_document_with_zero_requests_is_skipped(self, tmp_path: Path):+ # Review-caught: distinct from the zero-byte case above. This is a+ # VALID, well-formed document (a real VS Code "empty window" session+ # abandoned before any message) -- the parser always emits zero spans+ # for it, which would otherwise be recorded as a+ # FAILED session on every repeated scan, not a benign empty one.+ home = tmp_path / "Code" / "User"+ ews = home / "globalStorage" / "emptyWindowChatSessions"+ ews.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000005"+ (ews / f"{sid}.json").write_bytes(+ json.dumps({"sessionId": sid, "requests": []}, indent=2).encode()+ )++ source = LocalSource(claude_code_homes=[], codex_homes=[], copilot_vscode_homes=[home])+ found = source.discover_sessions()++ assert found == []+ assert source.discovery_stats()["copilot-vscode"]["skipped"].get("no_conversation") == 1++ def test_no_homes_configured_is_a_no_op_not_an_error(self, tmp_path: Path):+ source = LocalSource(claude_code_homes=[], codex_homes=[])+ assert source.discover_sessions() == []+ assert source.copilot_vscode_homes == []++ def test_a_missing_home_directory_is_skipped_gracefully(self, tmp_path: Path):+ source = LocalSource(+ claude_code_homes=[],+ codex_homes=[],+ copilot_vscode_homes=[tmp_path / "does-not-exist"],+ )+ assert source.discover_sessions() == []diff --git a/python/tests/core/test_local_source_detection_noise.py b/python/tests/core/test_local_source_detection_noise.pynew file mode 100644index 0000000..2e7cead--- /dev/null+++ b/python/tests/core/test_local_source_detection_noise.py@@ -0,0 +1,209 @@+"""Files that hold no conversation are not detection failures.++`_build_index()` used to log a WARNING ("agent detection failed") for every+`.jsonl` no agent claimed, which buried real format drift under Claude+metadata-only files and Cursor subagent stubs. These tests pin the split: a+file whose records are all known non-conversation metadata is a quiet+`no_conversation` skip, subagent files are dropped by path before any+detection runs, and only a file that looks conversational yet matches no+agent still warns.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path++import pytest++from agentplay._core.ingestion.coding_agent._sources.local import source as source_mod+from agentplay._core.ingestion.coding_agent._sources.local.source import LocalSource++DETECTION_WARNING = "agent detection failed"+++def _jsonl(records: list[dict]) -> bytes:+ return b"\n".join(json.dumps(r).encode() for r in records) + b"\n"+++def _warnings(caplog: pytest.LogCaptureFixture) -> list[str]:+ return [r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING]+++def _claude_home(tmp_path: Path) -> tuple[Path, Path]:+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ slug.mkdir(parents=True)+ return home, slug+++def _cursor_home(tmp_path: Path) -> tuple[Path, Path]:+ home = tmp_path / ".cursor"+ conv = home / "projects" / "-repo" / "agent-transcripts" / "conv1"+ (conv / "subagents").mkdir(parents=True)+ return home, conv+++def test_claude_metadata_only_file_is_quietly_skipped(tmp_path: Path, caplog) -> None:+ home, slug = _claude_home(tmp_path)+ (slug / "meta.jsonl").write_bytes(+ _jsonl([{"type": "ai-title", "aiTitle": "x"}, {"type": "agent-name", "agentName": "y"}])+ )+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert _warnings(caplog) == []+ assert source.discovery_stats()["claude-code"]["skipped"] == {"no_conversation": 1}+++def test_conversational_file_no_agent_claims_still_warns(tmp_path: Path, caplog) -> None:+ home, slug = _claude_home(tmp_path)+ # A user turn without the `sessionId` every known shape carries: format drift.+ (slug / "drift.jsonl").write_bytes(_jsonl([{"type": "user", "message": {"content": "hi"}}]))+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert any(DETECTION_WARNING in m for m in _warnings(caplog))+ assert source.discovery_stats()["claude-code"]["skipped"] == {"detection_failed": 1}+++def test_unknown_record_type_still_warns(tmp_path: Path, caplog) -> None:+ home, slug = _claude_home(tmp_path)+ (slug / "mystery.jsonl").write_bytes(_jsonl([{"type": "workflow_journal", "note": "x"}]))+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert any(DETECTION_WARNING in m for m in _warnings(caplog))+++def test_claude_subagent_file_is_dropped_before_detection(tmp_path: Path, caplog, monkeypatch) -> None:+ home, slug = _claude_home(tmp_path)+ sub = slug / "sid" / "subagents"+ sub.mkdir(parents=True)+ (sub / "agent-a1.jsonl").write_bytes(_jsonl([{"type": "ai-title", "aiTitle": "x"}]))++ def no_read(*_a, **_k):+ raise AssertionError("a subagent file must not be read")++ monkeypatch.setattr(source_mod, "_read_head", no_read)+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert _warnings(caplog) == []+ assert source.discovery_stats()["claude-code"]["skipped"] == {"subagent_component": 1}+++def test_cursor_subagent_stub_is_dropped_before_detection(tmp_path: Path, caplog) -> None:+ home, conv = _cursor_home(tmp_path)+ (conv / "subagents" / "a1.jsonl").write_bytes(_jsonl([{"type": "turn_ended", "reason": "done"}]))+ source = LocalSource(claude_code_homes=[], codex_homes=[], cursor_store_homes=[home])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert _warnings(caplog) == []+ assert source.discovery_stats()["cursor"]["skipped"] == {"subagent_component": 1}+++def test_cursor_file_with_only_a_turn_marker_is_no_conversation(tmp_path: Path, caplog) -> None:+ home, conv = _cursor_home(tmp_path)+ (conv / "conv1.jsonl").write_bytes(_jsonl([{"type": "turn_ended"}]))+ source = LocalSource(claude_code_homes=[], codex_homes=[], cursor_store_homes=[home])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert _warnings(caplog) == []+ assert source.discovery_stats()["cursor"]["skipped"] == {"no_conversation": 1}+++def test_file_deleted_before_the_warning_does_not_crash(tmp_path: Path, caplog, monkeypatch) -> None:+ home, slug = _claude_home(tmp_path)+ doomed = slug / "mystery.jsonl"+ doomed.write_bytes(_jsonl([{"type": "workflow_journal", "note": "x"}]))+ real_read_head = source_mod._read_head++ def read_then_vanish(path, **kwargs):+ head = real_read_head(path, **kwargs)+ path.unlink()+ return head++ monkeypatch.setattr(source_mod, "_read_head", read_then_vanish)+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert any(DETECTION_WARNING in m for m in _warnings(caplog))+ assert source.discovery_stats()["claude-code"]["skipped"] == {"detection_failed": 1}+++def _unreadable_session(tmp_path: Path, monkeypatch) -> tuple[LocalSource, str]:+ home, slug = _claude_home(tmp_path)+ turn = {"type": "user", "sessionId": "s1", "timestamp": "2026-09-01T00:00:00Z", "cwd": "/repo"}+ (slug / "s1.jsonl").write_bytes(_jsonl([{**turn, "message": {"role": "user", "content": "hi"}}]))+ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ (session_id,) = source._build_index()++ def denied(_self):+ raise PermissionError(13, "Permission denied")++ monkeypatch.setattr(Path, "read_bytes", denied)+ return source, session_id+++def test_unreadable_session_file_warns_without_a_traceback(tmp_path: Path, caplog, monkeypatch) -> None:+ source, session_id = _unreadable_session(tmp_path, monkeypatch)++ with caplog.at_level(logging.INFO):+ assert source.get_spans_by_session(session_id) == []++ (record,) = [r for r in caplog.records if r.levelno >= logging.WARNING]+ assert "Permission denied" in record.getMessage()+ assert not record.exc_info+++def test_unreadable_session_file_keeps_its_traceback_at_debug(tmp_path: Path, caplog, monkeypatch) -> None:+ source, session_id = _unreadable_session(tmp_path, monkeypatch)++ with caplog.at_level(logging.DEBUG):+ source.get_spans_by_session(session_id)++ (record,) = [r for r in caplog.records if r.levelno >= logging.WARNING]+ assert record.exc_info+++def test_metadata_head_cut_short_by_the_read_cap_still_warns(tmp_path: Path, caplog, monkeypatch) -> None:+ """A capped head can stop before the first message, so it proves nothing about the rest."""+ home, slug = _claude_home(tmp_path)+ records = [{"type": "ai-title", "aiTitle": "x" * 5000}] * 40 # past one 64KB read+ (slug / "big.jsonl").write_bytes(_jsonl(records))+ capped = source_mod._read_head+ monkeypatch.setattr(source_mod, "_read_head", lambda p, **k: capped(p, **{**k, "max_bytes": 512}))+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert any(DETECTION_WARNING in m for m in _warnings(caplog))+ assert "no_conversation" not in source.discovery_stats()["claude-code"]["skipped"]+++def test_unhashable_record_type_does_not_break_discovery(tmp_path: Path, caplog) -> None:+ home, slug = _claude_home(tmp_path)+ (slug / "odd.jsonl").write_bytes(_jsonl([{"type": ["x"]}, {"type": "ai-title"}]))+ source = LocalSource(claude_code_homes=[home], codex_homes=[])++ with caplog.at_level(logging.DEBUG):+ source.discover_sessions()++ assert source.discovery_stats()["claude-code"]["skipped"] == {"detection_failed": 1}diff --git a/python/tests/core/test_local_source_discovery_stats.py b/python/tests/core/test_local_source_discovery_stats.pynew file mode 100644index 0000000..0523b8e--- /dev/null+++ b/python/tests/core/test_local_source_discovery_stats.py@@ -0,0 +1,239 @@+"""Per-agent file-discovery counts (seen / indexed / skipped).++`LocalSource._build_index()` already visits every `.jsonl` under every+configured home once; these tests pin that walk now also tallies, per agent+type, how many files it saw, how many became a real session, and — when it+skipped one — *why*. `discovery_stats()` must never expose more than an+integer count: no file path, name, or byte size is ever attached to the+tally, matching this codebase's identity-stripping discipline for anything+that could reach a diagnostic event or the heartbeat.+"""++from __future__ import annotations++import json+from pathlib import Path++from agentplay._core.ingestion.coding_agent._sources.local.source import (+ LocalSource,+)+++def _jsonl(records: list[dict]) -> bytes:+ return b"\n".join(json.dumps(r).encode() for r in records) + b"\n"+++def _cc_user(session_id: str, ts: str = "2026-09-01T00:00:00Z") -> dict:+ return {+ "type": "user",+ "timestamp": ts,+ "sessionId": session_id,+ "cwd": "/repo",+ "message": {"role": "user", "content": "hi"},+ }+++def _cc_assistant(session_id: str, message_id: str, ts: str = "2026-09-01T00:00:01Z") -> dict:+ return {+ "type": "assistant",+ "timestamp": ts,+ "sessionId": session_id,+ "cwd": "/repo",+ "message": {+ "id": message_id,+ "model": "claude-opus-5",+ "role": "assistant",+ "content": [{"type": "text", "text": "hi back"}],+ "usage": {"input_tokens": 1, "output_tokens": 1},+ },+ }+++class TestClaudeCodeDiscoveryStats:+ def test_a_real_session_counts_as_seen_and_indexed(self, tmp_path: Path):+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ slug.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000001"+ (slug / f"{sid}.jsonl").write_bytes(_jsonl([_cc_user(sid), _cc_assistant(sid, "m1")]))++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ found = source.discover_sessions()++ assert len(found) == 1+ assert source.discovery_stats() == {"claude-code": {"seen": 1, "indexed": 1, "skipped": {}}}++ def test_a_subagent_component_file_is_skipped_and_labelled_as_such(self, tmp_path: Path):+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ sid = "9f1c3c2a-0000-4000-8000-000000000002"+ (slug / sid / "subagents").mkdir(parents=True)+ (slug / f"{sid}.jsonl").write_bytes(_jsonl([_cc_user(sid), _cc_assistant(sid, "m1")]))+ # A subagent's own file: every line isSidechain=true.+ side = {**_cc_assistant(sid, "m-side"), "isSidechain": True}+ (slug / sid / "subagents" / "agent-a1.jsonl").write_bytes(_jsonl([side]))++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ source.discover_sessions()++ stats = source.discovery_stats()["claude-code"]+ assert stats["seen"] == 2+ assert stats["indexed"] == 1+ assert stats["skipped"] == {"subagent_component": 1}++ def test_undetectable_shape_is_a_detection_failure_not_silently_ignored(self, tmp_path: Path):+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ slug.mkdir(parents=True)+ # Valid JSON, but no agent claims this shape.+ (slug / "mystery.jsonl").write_bytes(_jsonl([{"type": "workflow_journal", "note": "x"}]))++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ source.discover_sessions()++ assert source.discovery_stats()["claude-code"] == {+ "seen": 1,+ "indexed": 0,+ "skipped": {"detection_failed": 1},+ }++ def test_a_different_agents_file_in_the_same_home_is_not_a_failure(self, tmp_path: Path):+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ slug.mkdir(parents=True)+ # A Codex file that happens to live under a Claude Code home.+ (slug / "codex.jsonl").write_bytes(+ _jsonl([{"type": "session_meta", "payload": {"originator": "codex_cli_rs"}}])+ )++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ source.discover_sessions()++ assert source.discovery_stats()["claude-code"] == {+ "seen": 1,+ "indexed": 0,+ "skipped": {"different_agent": 1},+ }++ def test_empty_file_is_a_distinct_reason_from_detection_failure(self, tmp_path: Path):+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ slug.mkdir(parents=True)+ (slug / "empty.jsonl").write_bytes(b"")++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ source.discover_sessions()++ assert source.discovery_stats()["claude-code"] == {+ "seen": 1,+ "indexed": 0,+ "skipped": {"empty_or_unreadable": 1},+ }++ def test_a_directory_matching_the_glob_is_never_tallied_as_a_phantom_file(self, tmp_path: Path):+ """`rglob("*.jsonl")` can yield a directory (or a+ broken symlink) with that suffix; it must be silently skipped,+ never counted as a seen/empty file -+ that would report a phantom transcript on the heartbeat."""+ home = tmp_path / ".claude"+ slug = home / "projects" / "-repo"+ slug.mkdir(parents=True)+ (slug / "not-a-file.jsonl").mkdir() # a directory, not a transcript+ sid = "9f1c3c2a-0000-4000-8000-000000000004"+ (slug / f"{sid}.jsonl").write_bytes(_jsonl([_cc_user(sid), _cc_assistant(sid, "m1")]))++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ source.discover_sessions()++ # Only the real transcript is tallied; the directory is invisible to+ # the tally entirely, not counted as "seen" or as any skip reason.+ assert source.discovery_stats()["claude-code"] == {+ "seen": 1,+ "indexed": 1,+ "skipped": {},+ }++ def test_stats_never_carry_a_file_path_name_or_size(self, tmp_path: Path):+ """The whole point of the tally: aggregate counts only, nothing per-file."""+ home = tmp_path / ".claude"+ slug = home / "projects" / "-a-very-identifying-project-name"+ slug.mkdir(parents=True)+ (slug / "some-session-id.jsonl").write_bytes(_jsonl([{"type": "unknown"}]))++ source = LocalSource(claude_code_homes=[home], codex_homes=[])+ source.discover_sessions()++ dumped = json.dumps(source.discovery_stats())+ assert "a-very-identifying-project-name" not in dumped+ assert "some-session-id" not in dumped+ assert str(home) not in dumped+++class TestCrossAgentAggregation:+ def test_counts_land_under_separate_top_level_keys_per_agent(self, tmp_path: Path):+ cc_home = tmp_path / ".claude"+ cc_slug = cc_home / "projects" / "-repo"+ cc_slug.mkdir(parents=True)+ sid = "9f1c3c2a-0000-4000-8000-000000000003"+ (cc_slug / f"{sid}.jsonl").write_bytes(_jsonl([_cc_user(sid), _cc_assistant(sid, "m1")]))++ cursor_home = tmp_path / ".cursor-store"+ cursor_home.mkdir(parents=True)+ (cursor_home / "sess.jsonl").write_bytes(+ _jsonl(+ [+ {"type": "cursor_store_session", "cwd": "/repo"},+ {"role": "user", "content": "hi"},+ ]+ )+ )++ source = LocalSource(+ claude_code_homes=[cc_home], codex_homes=[], cursor_store_homes=[cursor_home]+ )+ source.discover_sessions()++ stats = source.discovery_stats()+ assert stats["claude-code"]["indexed"] == 1+ assert stats["cursor"]["indexed"] == 1+ # Each agent's tally is independent — one agent's file never inflates+ # or shrinks another agent's counts just because they share a run.+ assert stats["claude-code"]["seen"] == 1+ assert stats["cursor"]["seen"] == 1+++class TestCursorDiscoveryStats:+ def test_a_subagent_file_under_a_cursor_home_is_skipped_and_labelled(self, tmp_path: Path):+ home = tmp_path / ".cursor"+ parent_dir = home / "projects" / "-repo" / "agent-transcripts" / "conv1"+ (parent_dir / "subagents").mkdir(parents=True)+ (parent_dir / "conv1.jsonl").write_bytes(+ _jsonl([{"role": "user", "message": {"content": "hi"}}])+ )+ (parent_dir / "subagents" / "agent-a1.jsonl").write_bytes(+ _jsonl([{"role": "assistant", "message": {"content": "sub"}}])+ )++ source = LocalSource(claude_code_homes=[], codex_homes=[], cursor_store_homes=[home])+ source.discover_sessions()++ stats = source.discovery_stats()["cursor"]+ assert stats["seen"] == 2+ assert stats["indexed"] == 1+ assert stats["skipped"] == {"subagent_component": 1}++ def test_a_store_session_with_no_messages_is_its_own_reason(self, tmp_path: Path):+ home = tmp_path / ".cursor-store"+ home.mkdir(parents=True)+ (home / "empty-sess.jsonl").write_bytes(+ _jsonl([{"type": "cursor_store_session", "cwd": "/repo"}])+ )++ source = LocalSource(claude_code_homes=[], codex_homes=[], cursor_store_homes=[home])+ source.discover_sessions()++ assert source.discovery_stats()["cursor"] == {+ "seen": 1,+ "indexed": 0,+ "skipped": {"empty_store_session": 1},+ }diff --git a/python/tests/core/test_native_operations.py b/python/tests/core/test_native_operations.pynew file mode 100644index 0000000..67a143d--- /dev/null+++ b/python/tests/core/test_native_operations.py@@ -0,0 +1,337 @@+"""Cohort regressions: literal wrappers, process completion and shell bodies."""++import json++import pytest++from agentplay._core.ingestion.coding_agent._sources.local.parsers.codex import parse_codex+from agentplay._core.ingestion.coding_agent.native_operations import literal_operations+from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ extract_created_prs,+)+++ "code",+ [+ 'text(await tools.exec_command({cmd:"gh pr create --fill"}));',+ 'const r = await tools.exec_command({"cmd":"gh pr create --fill"}); text(r);',+ ],+)+def test_literal_wrapper(code):+ assert literal_operations(code) == [("exec_command", {"cmd": "gh pr create --fill"})]+++ "code",+ [+ 'if (false) { text(await tools.exec_command({cmd:"gh pr create"})); }',+ "text(await tools.exec_command({cmd:command}));",+ 'text(await Promise.all([tools.exec_command({cmd:"gh pr create"})]));',+ 'text(await tools.exec_command({cmd:"gh pr create"})); text("fake");',+ 'text(await tools.exec_command({cmd:"gh pr create", cmd:"echo fake"}));',+ 'const tools = await tools.exec_command({cmd:"gh pr create"}); text(tools);',+ ],+)+def test_unsupported_scripts_cannot_claim_operations(code):+ assert literal_operations(code) == []+++ "command",+ [+ "cd /repo\ngh pr create --body \"$(cat <<'EOF'\nbody `not code`\nEOF\n)\" 2>&1",+ "cat > /tmp/body.md <<'EOF'\nbody\nEOF\ngh pr create --body-file /tmp/body.md",+ "git push -u origin feature && gh pr create --fill",+ "cd /repo && git add -A && git commit -m \"$(cat <<'EOF'\nfix: x\n\nbody\nEOF\n)\" "+ "&& git push -u origin HEAD && gh pr create --title t --body b",+ ],+)+def test_supported_cohort_shell_shapes(command):+ assert creation_command_attributes(command)["pr.create.provider"] == "github"+++ "command",+ [+ "gh auth switch --user user1 2>&1 | tail -1\ngh pr create --fill\ngh auth switch --user user2 2>&1",+ # git preparation is accepted only as `&&`-joined add/commit/push+ # BEFORE the one create, with no redirect, pipe or fallback of its own.+ "git push; gh pr create --fill",+ "git push\ngh pr create --fill",+ "git push || true && gh pr create --fill",+ "git push 2>&1 | tail -1 && gh pr create --fill",+ "git push > /tmp/out && gh pr create --fill",+ "gh pr create --fill && git push",+ "git log && gh pr create --fill",+ "git push && gh pr create --web",+ "git push && gh pr create --fill | cat",+ "git push && gh pr create --fill && gh pr create --fill",+ "git diff && gh pr create --fill | head -n0",+ "echo 'gh pr create'",+ "false || gh pr create",+ "gh pr create; echo https://github.com/acme/repo/pull/1",+ 'gh pr create --body "$(arbitrary-command)"',+ "cat <<EOF\ngh pr create\nEOF",+ "gh pr create && gh pr view 2",+ ],+)+def test_noncausal_shell_shapes(command):+ assert "pr.create.provider" not in creation_command_attributes(command)+++def _parse(exit_code=0, chars="", launch_output="", final_output=None, host_error=False):+ url = "https://github.com/acme/repo/pull/7"+ rows = [+ {"type": "session_meta", "payload": {"id": "native", "cwd": "/repo"}},+ {+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "make a change"}],+ },+ },+ ]+ for call_id, code, result in [+ (+ "launch",+ 'text(await tools.exec_command({cmd:"gh pr create --fill"}));',+ {"output": launch_output, "session_id": 42, "wall_time_seconds": 1},+ ),+ (+ "poll",+ "text(await tools.write_stdin("+ + json.dumps({"session_id": 42, "chars": chars})+ + "));",+ {+ "output": final_output if final_output is not None else url,+ "exit_code": exit_code,+ "isError": host_error,+ "wall_time_seconds": 1,+ },+ ),+ ]:+ rows.extend(+ [+ {+ "type": "response_item",+ "payload": {+ "type": "custom_tool_call",+ "name": "exec",+ "call_id": call_id,+ "input": code,+ },+ },+ {+ "type": "response_item",+ "payload": {+ "type": "custom_tool_call_output",+ "call_id": call_id,+ "output": [{"type": "text", "text": json.dumps(result)}],+ },+ },+ ]+ )+ for index, row in enumerate(rows):+ row["timestamp"] = f"2026-09-21T01:00:{index:02d}Z"+ _, spans = parse_codex(+ data="\n".join(json.dumps(r) for r in rows).encode(), trace_id="local:codex:native"+ )+ return extract_created_prs(spans)+++def test_async_completion_keeps_launch_identity():+ result = _parse()+ assert len(result) == 1+ assert result[0].source_event_id.endswith(":tool:launch:op:0")+ assert result[0].number == 7+ assert result[0].command_sha256+++ "kwargs",+ [+ {"exit_code": 1},+ {"host_error": True},+ {"chars": "echo fake\n"},+ {"exit_code": None},+ {"launch_output": "error: creation failed\n"},+ {"launch_output": "https://github.com/acme/repo/pull/8\n"},+ ],+)+def test_async_failure_or_ambiguity_never_creates_link(kwargs):+ assert _parse(**kwargs) == []+++def test_output_printed_before_exit_requires_successful_completion():+ assert len(_parse(launch_output="https://github.com/acme/repo/pull/7\n", final_output="")) == 1+++def test_native_text_process_headers_are_not_read_from_stdout():+ from agentplay._core.ingestion.coding_agent.native_operations import shell_result++ result = shell_result("Chunk ID: abc\nProcess running with session ID 17\nOutput:\nwaiting")+ assert result["session_id"] == 17+ assert result["exit_code"] is None+ assert shell_result("Chunk ID: abc\nOutput:\nProcess exited with code 0") is None+++def test_serial_native_input_text_result_header():+ from agentplay._core.ingestion.coding_agent.native_operations import literal_results++ blocks = [+ {"type": "input_text", "text": "Script completed\nWall time 0.1 seconds\nOutput:\n"},+ {"type": "input_text", "text": '{"exit_code":0,"wall_time_seconds":0.1,"output":"done"}'},+ ]+ assert literal_results(blocks, 1)[0]["exit_code"] == 0+ assert literal_results([*blocks, {"type": "input_text", "text": "extra"}], 1) == []+++def test_json_exponent_literal_preserves_operation():+ assert literal_operations(+ 'text(await tools.exec_command({"cmd":"pwd","yield_time_ms":1e3}));'+ ) == [("exec_command", {"cmd": "pwd", "yield_time_ms": 1000})]+++ "result",+ [+ {"exit_code": 1, "output": "failed"},+ {"isError": True, "output": "failed"},+ {"metadata": {"exit_code": 1}, "output": "failed"},+ ],+)+def test_failed_literal_patch_never_captures_edits(result):+ patch = "*** Begin Patch\n*** Update File: /repo/app.py\n@@\n-old\n+new\n*** End Patch"+ records = [+ {"type": "session_meta", "payload": {"id": "native", "cwd": "/repo"}},+ {+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "edit"}],+ },+ },+ {+ "type": "response_item",+ "payload": {+ "type": "custom_tool_call",+ "name": "exec",+ "call_id": "patch",+ "input": "text(await tools.apply_patch(" + json.dumps(patch) + "));",+ },+ },+ {+ "type": "response_item",+ "payload": {+ "type": "custom_tool_call_output",+ "call_id": "patch",+ "output": [{"type": "text", "text": json.dumps(result)}],+ },+ },+ ]+ for index, row in enumerate(records):+ row["timestamp"] = f"2026-09-21T01:00:{index:02d}Z"+ _, spans = parse_codex(+ data="\n".join(json.dumps(row) for row in records).encode(), trace_id="native"+ )+ operation = next(span for span in spans if span.span_id.endswith(":op:0"))+ assert operation.status_code == "ERROR"+ assert operation.attributes["code.edit_evidence"]["edits"] == []+++def test_nested_arguments_do_not_abort_codex_transcript():+ rows = [+ {"type": "session_meta", "payload": {"id": "native", "cwd": "/repo"}},+ {"type": "response_item", "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "work"}]}},+ {"type": "response_item", "payload": {"type": "function_call", "name": "exec_command", "call_id": "nested", "arguments": "[" * 2000 + "0" + "]" * 2000}},+ {"type": "response_item", "payload": {"type": "function_call_output", "call_id": "nested", "output": '{"output":"done","exit_code":0}'}},+ ]+ _, spans = parse_codex("\n".join(json.dumps(row) for row in rows).encode(), trace_id="native")+ assert any(span.span_id.endswith(":tool:nested") for span in spans)+ assert extract_created_prs(spans) == []+++_PATCH = "*** Begin Patch\n*** Update File: /repo/app.py\n@@\n-old\n+new\n*** End Patch"+++ "code",+ [+ "const patch = PATCH; text(await tools.apply_patch(patch));",+ "const patch=PATCH;text(await tools.apply_patch(patch))",+ "const patch = PATCH; const r = await tools.apply_patch(patch); "+ 'text(typeof r === "string" ? r : JSON.stringify(r));',+ "const p=PATCH;const r=await tools.apply_patch(p);"+ 'text(typeof r==="string"?r:JSON.stringify(r))',+ ],+)+def test_codex_bound_patch_is_a_literal_operation(code):+ assert literal_operations(code.replace("PATCH", json.dumps(_PATCH))) == [+ ("apply_patch", _PATCH)+ ]+++ "code",+ [+ "let patch = PATCH; patch = PATCH; text(await tools.apply_patch(patch));",+ "const patch = PATCH + PATCH; text(await tools.apply_patch(patch));",+ "text(await tools.apply_patch(patch)); const patch = PATCH;",+ "const patch = PATCH; const patch = PATCH; text(await tools.apply_patch(patch));",+ "const true = PATCH; text(await tools.apply_patch(true));",+ "const p = PATCH; for (const x of [1]) { text(await tools.apply_patch(p)); }",+ # Emits something other than the awaited result: order proves nothing.+ "const p = PATCH; const r = await tools.apply_patch(p); "+ 'text(typeof r === "string" ? p : JSON.stringify(r));',+ "const p = PATCH; const r = await tools.apply_patch(p);",+ ],+)+def test_codex_bound_literal_shapes_that_prove_nothing(code):+ assert literal_operations(code.replace("PATCH", json.dumps(_PATCH))) == []+++def test_codex_bound_patch_captures_edit_evidence():+ code = "const patch = " + json.dumps(_PATCH) + "; text(await tools.apply_patch(patch));"+ records = [+ {"type": "session_meta", "payload": {"id": "native", "cwd": "/repo"}},+ {+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "edit"}],+ },+ },+ {+ "type": "response_item",+ "payload": {"type": "custom_tool_call", "name": "exec", "call_id": "c", "input": code},+ },+ {+ "type": "response_item",+ "payload": {+ "type": "custom_tool_call_output",+ "call_id": "c",+ "output": [+ {+ "type": "input_text",+ "text": "Script completed\nWall time 0.1 seconds\nOutput:\n",+ },+ {"type": "input_text", "text": "{}"},+ ],+ },+ },+ ]+ for index, row in enumerate(records):+ row["timestamp"] = f"2026-09-21T01:00:{index:02d}Z"+ _, spans = parse_codex(+ data="\n".join(json.dumps(row) for row in records).encode(), trace_id="native"+ )+ operation = next(span for span in spans if span.span_id.endswith(":op:0"))+ assert operation.attributes["provenance.capture"] == "literal_operation"+ evidence = operation.attributes["code.edit_evidence"]+ assert evidence["status"] == "captured"+ assert [(e["path"], e["operation"]) for e in evidence["edits"]] == [("/repo/app.py", "replace")]diff --git a/python/tests/core/test_null_safe_token_coercion.py b/python/tests/core/test_null_safe_token_coercion.pynew file mode 100644index 0000000..663b1f2--- /dev/null+++ b/python/tests/core/test_null_safe_token_coercion.py@@ -0,0 +1,41 @@+"""token-count coercion must survive an explicit JSON null.++Some parsers (e.g. OpenCode) preserve `null` for a token attribute rather than+omitting the key, so `dict.get(key, 0)` returns None and a bare `int(None)` used+to raise, aborting the whole session's aggregation. The coercion sites now read+`int(x.attributes.get(key) or 0)`, so an explicit null degrades to 0.+"""++from __future__ import annotations++from datetime import UTC, datetime++from agentplay._core.ingestion.coding_agent.session_pure import _context_growth+from agentplay._core.ingestion.coding_agent.spans import SpanData+++def _turn_span(turn: int, prompt_tokens) -> SpanData:+ now = datetime.now(UTC)+ return SpanData(+ span_id=f"s{turn}",+ trace_id="t",+ parent_id="root",+ name=f"Turn {turn}",+ span_kind="LLM",+ status_code="OK",+ start_time=now,+ end_time=now,+ attributes={"llm.token_count.prompt": prompt_tokens},+ )+++def test_explicit_null_prompt_tokens_coerces_to_zero():+ # The key is PRESENT with value None (an explicit JSON null), the case that+ # used to raise TypeError on int(None).+ rows = _context_growth([_turn_span(1, None)])+ assert rows == [{"turn": 1, "prompt_tokens": 0}]+++def test_real_token_value_passes_through():+ rows = _context_growth([_turn_span(1, 1234), _turn_span(2, 0)])+ assert rows == [{"turn": 1, "prompt_tokens": 1234}, {"turn": 2, "prompt_tokens": 0}]diff --git a/python/tests/core/test_parser_robustness.py b/python/tests/core/test_parser_robustness.pynew file mode 100644index 0000000..e4e29ff--- /dev/null+++ b/python/tests/core/test_parser_robustness.py@@ -0,0 +1,416 @@+"""One malformed or unexpected record never drops a session or crashes a scan.++Real transcripts change schema often (new record types, partial usage blocks,+wrong-typed fields). Every parser must skip what it cannot read and still+produce the rest of the session. Fixtures are minimal and synthetic.++Two sweeps per parser:++* structural damage (truncated tail, bad JSON, non-dict JSON, BOM, non-UTF-8+ bytes, unknown record type) must leave the turn count unchanged;+* every field of every record replaced, one at a time, with a wrong-typed+ value must not raise.+"""++from __future__ import annotations++import copy+import json+import logging++import pytest++from agentplay._core.ingestion.coding_agent._sources.local.parsers import (+ parse_claude_code,+ parse_codex,+ parse_copilot,+ parse_copilot_vscode,+ parse_cursor_agent_transcript,+ parse_cursor_store,+ parse_kiro,+ parse_opencode,+)++TS = "2026-09-14T10:00:0{}Z"+WRONG_TYPES = (None, 123, "str", [], {}, True)+++def _claude() -> list[dict]:+ args = {"file_path": "/repo/app.py", "old_string": "old", "new_string": "new"}+ usage = {"input_tokens": 10, "output_tokens": 5, "cache_read_input_tokens": 2}+ return [+ {+ "type": "user",+ "sessionId": "s1",+ "cwd": "/repo",+ "version": "2.1.0",+ "entrypoint": "cli",+ "timestamp": TS.format(0),+ "message": {"role": "user", "content": "fix it"},+ },+ {+ "type": "assistant",+ "requestId": "r1",+ "timestamp": TS.format(1),+ "message": {+ "id": "m1",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "usage": usage,+ "content": [+ {"type": "text", "text": "ok"},+ {"type": "tool_use", "id": "c1", "name": "Edit", "input": args},+ ],+ },+ },+ {+ "type": "user",+ "timestamp": TS.format(2),+ "toolUseResult": {"filePath": "/repo/app.py"},+ "message": {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "c1", "content": "done"}],+ },+ },+ ]+++def _codex() -> list[dict]:+ usage = {"input_tokens": 10, "cached_input_tokens": 2, "output_tokens": 5, "total_tokens": 15}++ def line(i: int, kind: str, payload: dict) -> dict:+ return {"timestamp": TS.format(i), "type": kind, "payload": payload}++ return [+ line(0, "session_meta", {"id": "s1", "cwd": "/repo", "originator": "codex-tui"}),+ line(1, "turn_context", {"model": "gpt-5", "cwd": "/repo"}),+ line(1, "event_msg", {"type": "user_message", "message": "fix it"}),+ line(+ 2,+ "response_item",+ {"type": "function_call", "name": "exec_command", "arguments": "{}", "call_id": "c1"},+ ),+ line(3, "response_item", {"type": "function_call_output", "call_id": "c1", "output": "ok"}),+ line(+ 4,+ "response_item",+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "done"}],+ },+ ),+ line(+ 4,+ "event_msg",+ {+ "type": "token_count",+ "info": {"last_token_usage": usage, "total_token_usage": usage},+ },+ ),+ ]+++def _copilot() -> list[dict]:+ def ev(i: int, kind: str, data: dict) -> dict:+ return {"type": kind, "data": data, "id": f"e{i}", "timestamp": TS.format(i)}++ return [+ ev(+ 0,+ "session.start",+ {+ "sessionId": "s1",+ "producer": "copilot-agent",+ "startTime": TS.format(0),+ "context": {"cwd": "/repo"},+ },+ ),+ ev(1, "user.message", {"content": "fix it"}),+ ev(2, "assistant.turn_start", {"turnId": "0"}),+ ev(3, "assistant.message", {"messageId": "m1", "content": "ok", "outputTokens": 5}),+ ev(+ 4,+ "tool.execution_start",+ {"toolCallId": "c1", "toolName": "bash", "arguments": {"command": "ls"}},+ ),+ ev(+ 5,+ "tool.execution_complete",+ {+ "toolCallId": "c1",+ "model": "gpt-5",+ "success": True,+ "result": {"content": "ok"},+ },+ ),+ ev(6, "assistant.turn_end", {"turnId": "0"}),+ ]+++def _copilot_vscode() -> list[dict]:+ request = {+ "requestId": "r1",+ "timestamp": 1_780_000_000_000,+ "elapsedMs": 1000,+ "isComplete": True,+ "modelId": "copilot/auto",+ "message": {"text": "fix it"},+ "response": [{"value": "ok"}],+ "result": {+ "usage": {"promptTokens": 10, "completionTokens": 5},+ "metadata": {+ "toolCallRounds": [+ {"toolCalls": [{"id": "c1", "name": "run_in_terminal", "arguments": "{}"}]}+ ],+ "toolCallResults": {"c1": {"content": "ok"}},+ },+ },+ }+ return [{"kind": 0, "v": {"sessionId": "s1", "requests": [request]}}]+++def _cursor_store() -> list[dict]:+ return [+ {+ "type": "cursor_store_session",+ "agentId": "a1",+ "name": "t",+ "createdAt": 1_780_000_000_000,+ "updatedAt": 1_780_000_060_000,+ "cwd": "/repo",+ },+ {"role": "user", "content": [{"type": "text", "text": "<user_query>fix it</user_query>"}]},+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "ok"},+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "Read",+ "args": {"path": "/repo/app.py"},+ },+ ],+ },+ {+ "role": "tool",+ "content": [+ {"type": "tool-result", "toolCallId": "c1", "toolName": "Read", "result": "x"}+ ],+ },+ {"role": "assistant", "content": [{"type": "text", "text": "done"}]},+ ]+++def _cursor_agent() -> list[dict]:+ return [+ {"role": "user", "message": {"content": [{"type": "text", "text": "fix it"}]}},+ {+ "role": "assistant",+ "message": {+ "content": [+ {"type": "text", "text": "ok"},+ {"type": "tool_use", "name": "Read", "input": {"path": "/repo/app.py"}},+ ]+ },+ },+ {"role": "assistant", "message": {"content": [{"type": "text", "text": "done"}]}},+ ]+++def _kiro() -> list[dict]:+ def ev(i: int, payload: dict) -> dict:+ return {"id": f"e{i}", "timestamp": TS.format(i), "payload": payload}++ return [+ {+ "type": "kiro_session",+ "id": "s1",+ "title": "t",+ "workspacePaths": ["/repo"],+ "createdAt": TS.format(0),+ "lastModifiedAt": TS.format(5),+ },+ ev(1, {"type": "user", "content": "fix it"}),+ ev(2, {"type": "assistant", "content": "ok"}),+ ev(+ 3,+ {+ "type": "tool_call",+ "toolCallId": "c1",+ "toolName": "readFile",+ "args": {"path": "/repo/app.py"},+ },+ ),+ ev(4, {"type": "tool_result", "toolCallId": "c1", "content": "x", "success": True}),+ ev(5, {"type": "turn_end", "stopReason": "end_turn"}),+ ev(5, {"type": "usage_summary", "promptTurnSummaries": [{"usage": 1.5}]}),+ ]+++def _opencode() -> list[dict]:+ created = 1_780_000_000_000+ return [+ {+ "id": "msg_1",+ "sessionID": "ses_1",+ "message": {"role": "user", "time": {"created": created}},+ "parts": [{"type": "text", "text": "fix it"}],+ },+ {+ "id": "msg_2",+ "sessionID": "ses_1",+ "message": {+ "role": "assistant",+ "modelID": "m",+ "path": {"cwd": "/repo"},+ "time": {"created": created + 1000},+ "tokens": {"input": 10, "output": 5, "reasoning": 0, "cache": {"read": 1, "write": 2}},+ },+ "parts": [+ {"type": "text", "text": "ok"},+ {+ "type": "tool",+ "tool": "read",+ "callID": "c1",+ "state": {+ "status": "completed",+ "input": {"filePath": "/repo/app.py"},+ "output": "x",+ "time": {"start": created + 1000, "end": created + 1500},+ },+ },+ ],+ },+ ]+++PARSERS = {+ "claude_code": (parse_claude_code, _claude),+ "codex": (parse_codex, _codex),+ "copilot": (parse_copilot, _copilot),+ "copilot_vscode": (parse_copilot_vscode, _copilot_vscode),+ "cursor_store": (parse_cursor_store, _cursor_store),+ "cursor_agent": (parse_cursor_agent_transcript, _cursor_agent),+ "kiro": (parse_kiro, _kiro),+ "opencode": (parse_opencode, _opencode),+}+UNKNOWN_RECORD = {"type": "agentplay-future-record", "payload": {"x": 1}}+++def _encode(records: list[dict]) -> bytes:+ return b"".join(json.dumps(r).encode() + b"\n" for r in records)+++def _turns(parse, data: bytes) -> int:+ _, spans = parse(data, "t")+ return sum(1 for s in spans if s.name.startswith("Turn"))+++def _paths(obj, prefix=()):+ """Every dict key / list index path inside ``obj`` (depth-first)."""+ if isinstance(obj, dict):+ for key, value in obj.items():+ yield (*prefix, key)+ yield from _paths(value, (*prefix, key))+ elif isinstance(obj, list):+ for i, value in enumerate(obj):+ yield (*prefix, i)+ yield from _paths(value, (*prefix, i))+++def _assign(obj, path, value):+ for key in path[:-1]:+ obj = obj[key]+ obj[path[-1]] = value++[email protected](autouse=True)+def _quiet(caplog):+ caplog.set_level(logging.CRITICAL)++[email protected]("name", PARSERS)+def test_clean_fixture_yields_a_turn(name):+ parse, build = PARSERS[name]+ assert _turns(parse, _encode(build())) >= 1+++def _damage_cases(clean: bytes) -> dict[str, bytes]:+ return {+ "truncated_last_line": clean + b'{"type": "user", "message": {"role": "us',+ "invalid_json_line": b"{not json}\n" + clean + b"{also not\n",+ "non_dict_json": b'[1, 2]\n42\n"str"\nnull\n' + clean,+ "unknown_record_type": clean + _encode([UNKNOWN_RECORD]),+ "bom_prefix": b"\xef\xbb\xbf" + clean,+ "non_utf8_bytes": clean + b'{"type": "x", "text": "\xff\xfe\xfa"}\n\xc3\x28\n',+ "blank_lines": b"\n\n" + clean.replace(b"\n", b"\n\n"),+ }++[email protected]("name", PARSERS)+ "case",+ [+ "truncated_last_line",+ "invalid_json_line",+ "non_dict_json",+ "unknown_record_type",+ "bom_prefix",+ "non_utf8_bytes",+ "blank_lines",+ ],+)+def test_structural_damage_keeps_the_session(name, case):+ parse, build = PARSERS[name]+ clean = _encode(build())+ expected = _turns(parse, clean)+ assert _turns(parse, _damage_cases(clean)[case]) == expected++[email protected]("name", PARSERS)+def test_wrong_typed_fields_never_raise(name):+ parse, build = PARSERS[name]+ base = build()+ failures = []+ for index, record in enumerate(base):+ for path in _paths(record):+ for bad in WRONG_TYPES:+ records = copy.deepcopy(base)+ _assign(records[index], path, bad)+ try:+ parse(_encode(records), "t")+ except Exception as exc:+ failures.append(f"record {index} {path} = {bad!r}: {type(exc).__name__}: {exc}")+ assert not failures, "\n".join(failures[:25])++[email protected]("name", PARSERS)+def test_wrong_typed_record_keeps_other_records(name):+ """A record whose every field is junk costs only itself."""+ parse, build = PARSERS[name]+ base = build()+ expected = _turns(parse, _encode(base))+ junk = {"type": 123, "timestamp": 123, "message": "str", "payload": None, "usage": [], "content": None}+ assert _turns(parse, _encode([*base, junk])) == expected+++ "iterations",+ [+ "x",+ [None],+ [{"input_tokens": 1}],+ [{"type": "message", "input_tokens": "1", "output_tokens": 1}],+ [{"type": "message", "input_tokens": 1, "output_tokens": -1}],+ [{"type": "message", "input_tokens": 1, "output_tokens": 1, "model": ["x"]}],+ ],+)+def test_claude_malformed_usage_iterations_fall_back_to_top_level_usage(iterations):+ """Unusable per-attempt evidence must not abort a session whose top-level usage is fine."""+ records = _claude()+ records[1]["message"]["usage"]["iterations"] = iterations+ _, spans = parse_claude_code(_encode(records), "t")+ turn = next(s for s in spans if s.name == "Turn 1")+ assert turn.attributes["llm.token_count.completion"] >= 5diff --git a/python/tests/core/test_skill_call_name.py b/python/tests/core/test_skill_call_name.pynew file mode 100644index 0000000..9b76128--- /dev/null+++ b/python/tests/core/test_skill_call_name.py@@ -0,0 +1,35 @@+"""a Skill call's name is always recoverable (span attribute first)."""++from agentplay._core.ingestion.coding_agent.skill_names import (+ SKILL_CALL_NAME_ATTR,+ skill_call_attributes,+ skill_call_name,+)+++def test_attribute_is_set_only_for_skill_calls():+ assert skill_call_attributes("Skill", {"skill": "myplugin:deploy", "args": "x"}) == {+ SKILL_CALL_NAME_ATTR: "myplugin:deploy"+ }+ assert skill_call_attributes("activate_skill", {"command": "entloop"}) == {+ SKILL_CALL_NAME_ATTR: "entloop"+ }+ assert skill_call_attributes("Bash", {"command": "ls"}) == {}+ assert skill_call_attributes("Skill", "not-a-dict") == {}+++def test_name_survives_a_truncated_input_value():+ truncated = '{"skill": "myplugin:deploy", "args": "' + "x" * 3000+ assert skill_call_name("Skill", {SKILL_CALL_NAME_ATTR: "myplugin:deploy"}, truncated[:2000]) == (+ "myplugin:deploy"+ )+++def test_falls_back_to_input_json_and_strips_a_slash():+ assert skill_call_name("Skill", {}, '{"skill": "/security-review"}') == "security-review"+++def test_junk_and_non_skill_calls_are_none():+ assert skill_call_name("Skill", {SKILL_CALL_NAME_ATTR: "common"}) is None+ assert skill_call_name("Read", {SKILL_CALL_NAME_ATTR: "entloop"}) is None+ assert skill_call_name("Skill", None, "{not json") is Nonediff --git a/python/tests/core/test_source_cursor_universal.py b/python/tests/core/test_source_cursor_universal.pynew file mode 100644index 0000000..6b3b136--- /dev/null+++ b/python/tests/core/test_source_cursor_universal.py@@ -0,0 +1,420 @@+"""— one source-cursor contract, every agent parser.++Every turn and tool span carries ``source.kind`` and ``source.content_hash``;+append-only JSONL parsers also carry ``source.byte_offset``. The hash is the+universal verifier (stable across a rewrite of the same content), the offset+the seek point (stable when the file grows). The contract is pinned here once+for every parser.+"""++from __future__ import annotations++import json++from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import (+ SOURCE_HASH_KEY,+ SOURCE_OFFSET_KEY,+ parse_jsonl_records,+ record_hash,+ source_attrs,+)+from agentplay._core.ingestion.coding_agent._sources.local.parsers import (+ claude_code,+ codex,+ copilot,+ cursor_agent_transcript,+ cursor_store,+ kiro,+ opencode,+)+++def _jl(*objs: dict) -> bytes:+ return ("\n".join(json.dumps(o) for o in objs)).encode()+++def _claude(n: int = 1) -> list[dict]:+ return [+ {+ "type": "user",+ "uuid": f"u{n}",+ "timestamp": "2026-09-01T00:00:01Z",+ "message": {"role": "user", "content": "hi"},+ "cwd": "/w",+ "sessionId": "s",+ },+ {+ "type": "assistant",+ "uuid": f"a{n}",+ "timestamp": "2026-09-01T00:00:02Z",+ "message": {+ "role": "assistant",+ "model": "claude-sonnet-5",+ "content": [{"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {}}],+ "usage": {"input_tokens": 1, "output_tokens": 1},+ },+ },+ ]+++def _codex() -> list[dict]:+ return [+ {+ "type": "session_meta",+ "timestamp": "2026-09-01T00:00:00Z",+ "payload": {"cwd": "/w", "id": "s1"},+ },+ {+ "type": "response_item",+ "timestamp": "2026-09-01T00:00:01Z",+ "payload": {"role": "user", "content": [{"type": "input_text", "text": "hi"}]},+ },+ {+ "type": "response_item",+ "timestamp": "2026-09-01T00:00:02Z",+ "payload": {+ "type": "function_call",+ "call_id": "c1",+ "name": "shell",+ "arguments": "{}",+ },+ },+ {+ "type": "response_item",+ "timestamp": "2026-09-01T00:00:03Z",+ "payload": {"type": "function_call_output", "call_id": "c1", "output": "ok"},+ },+ ]+++def _kiro() -> list[dict]:+ return [+ {"type": "kiro_session", "cwd": "/w"},+ {"timestamp": "2026-09-01T00:00:01Z", "payload": {"type": "user", "content": "hi"}},+ {+ "timestamp": "2026-09-01T00:00:02Z",+ "payload": {"type": "tool_call", "toolCallId": "t1", "toolName": "read", "args": {}},+ },+ {+ "timestamp": "2026-09-01T00:00:03Z",+ "payload": {+ "type": "tool_result",+ "toolCallId": "t1",+ "content": "ok",+ "success": True,+ },+ },+ ]+++def _opencode() -> list[dict]:+ return [+ {+ "message": {"role": "user", "time": {"created": 1756684800000}, "path": {"cwd": "/w"}},+ "parts": [{"type": "text", "text": "hi"}],+ },+ {+ "message": {"role": "assistant", "time": {"created": 1756684801000}, "modelID": "m"},+ "parts": [+ {+ "type": "tool",+ "callID": "t1",+ "tool": "read",+ "state": {"input": {}, "output": "ok", "status": "completed"},+ }+ ],+ },+ ]+++def _cursor_transcript() -> list[dict]:+ return [+ {"role": "user", "message": {"content": "hi"}},+ {+ "role": "assistant",+ "message": {"content": [{"type": "tool_use", "id": "t1", "name": "read", "input": {}}]},+ },+ ]+++def _cursor_store() -> list[dict]:+ return [+ {+ "type": "cursor_store_session",+ "agentId": "a1",+ "name": "n",+ "createdAt": 1756684800000,+ "updatedAt": 1756684900000,+ },+ {+ "role": "user",+ "createdAt": "2026-09-01T00:00:01Z",+ "content": [{"type": "text", "text": "hi"}],+ },+ {+ "role": "assistant",+ "createdAt": "2026-09-01T00:00:02Z",+ "content": [{"type": "tool_call", "toolCallId": "t1", "name": "read", "args": {}}],+ },+ {"role": "tool", "createdAt": "2026-09-01T00:00:03Z", "toolCallId": "t1", "result": "ok"},+ ]+++def _copilot() -> list[dict]:+ # Minimal Copilot CLI shape: session.start, a user message, a tool request + completion.+ return [+ {+ "type": "session.start",+ "timestamp": "2026-09-01T00:00:00Z",+ "data": {"sessionId": "s", "cwd": "/w", "context": {"cwd": "/w"}},+ },+ {"type": "user.message", "timestamp": "2026-09-01T00:00:01Z", "data": {"content": "hi"}},+ {"type": "assistant.turn_start", "timestamp": "2026-09-01T00:00:02Z", "data": {}},+ {+ "type": "tool.execution_start",+ "timestamp": "2026-09-01T00:00:03Z",+ "data": {"toolCallId": "t1", "toolName": "read", "arguments": {}},+ },+ {+ "type": "tool.execution_complete",+ "timestamp": "2026-09-01T00:00:04Z",+ "data": {"toolCallId": "t1", "result": {"content": "ok"}, "success": True},+ },+ ]+++_PARSERS = {+ # name: (parser, fixture, expected kind, (turn line index, tool line index))+ # — the fixture line each anchor MUST come from: the line that opened the+ # turn, and the line that requested the tool call ("some+ # parsed line" is not the contract). None ⇒ a rewritten store: hash only.+ "claude_code": (claude_code.parse_claude_code, _claude, "jsonl", (0, 1)),+ "codex": (codex.parse_codex, _codex, "jsonl", (1, 2)),+ "kiro": (kiro.parse_kiro, _kiro, "jsonl", (1, 2)),+ # Review-caught: opencode has no per-session file — it's+ # re-materialized from a SQLite db into NDJSON fresh on every parse, so+ # the NDJSON byte offset is a position in a throwaway intermediate, not+ # a stable transcript location. Rewritten store ⇒ hash only, like+ # cursor_store.+ "opencode": (opencode.parse_opencode, _opencode, "sqlite", None),+ "cursor_agent_transcript": (+ cursor_agent_transcript.parse_cursor_agent_transcript,+ _cursor_transcript,+ "jsonl",+ (0, 1),+ ),+ "cursor_store": (cursor_store.parse_cursor_store, _cursor_store, "sqlite", None),+ "copilot": (copilot.parse_copilot, _copilot, "jsonl", (1, 3)),+}+++def _anchored(spans):+ return [s for s in spans if s.name.startswith("Turn ") or s.attributes.get("tool.name")]+++def _parse(name):+ parser, fixture, _kind, _lines = _PARSERS[name]+ return parser(_jl(*fixture()), "trace-1")[1]+++def test_every_parser_stamps_its_own_kind_and_a_hash_on_every_turn_and_tool_span():+ for name, (_parser, _fixture, kind, lines) in _PARSERS.items():+ spans = _anchored(_parse(name))+ assert spans, name+ for span in spans:+ attrs = span.attributes+ # The parser-specific kind, not "some kind".+ assert attrs.get("source.kind") == kind, (name, span.name, attrs)+ assert (+ isinstance(attrs.get("source.content_hash"), str)+ and len(attrs["source.content_hash"]) == 16+ ), (name, span.name)+ if lines is not None:+ assert isinstance(attrs.get("source.byte_offset"), int), (name, span.name, attrs)+ else:+ assert "source.byte_offset" not in attrs, (name, span.name)+++def test_jsonl_parsers_anchor_the_turn_to_its_opening_line_and_the_tool_to_the_request_line():+ for name, (_parser, fixture, _kind, lines) in _PARSERS.items():+ if lines is None:+ continue+ records = parse_jsonl_records(_jl(*fixture()))+ turn_line, tool_line = lines+ expected_turn = (+ records[turn_line][SOURCE_OFFSET_KEY],+ records[turn_line][SOURCE_HASH_KEY],+ )+ expected_tool = (+ records[tool_line][SOURCE_OFFSET_KEY],+ records[tool_line][SOURCE_HASH_KEY],+ )+ spans = _anchored(_parse(name))+ turn = next(s for s in spans if s.name.startswith("Turn "))+ tool = next(s for s in spans if s.attributes.get("tool.name"))+ # Exactly the fixture line that opened the turn / requested the call+ # (not merely "one of the parsed lines").+ assert (+ turn.attributes["source.byte_offset"],+ turn.attributes["source.content_hash"],+ ) == expected_turn, (name, "turn")+ assert (+ tool.attributes["source.byte_offset"],+ tool.attributes["source.content_hash"],+ ) == expected_tool, (name, "tool")+++def test_hashes_survive_a_rewrite_and_offsets_survive_growth():+ for name, (parser, fixture, _kind, lines) in _PARSERS.items():+ before = {s.name: s.attributes for s in _anchored(_parse(name))}+ # Rewrite: same content, different serialization (key order + spacing).+ rewritten = (+ "\n".join(json.dumps(o, sort_keys=True, separators=(", ", ": ")) for o in fixture())+ ).encode()+ after = {s.name: s.attributes for s in _anchored(parser(rewritten, "trace-1")[1])}+ for span_name, attrs in before.items():+ assert after[span_name]["source.content_hash"] == attrs["source.content_hash"], (+ name,+ span_name,+ )+ if lines is not None:+ grown = _jl(*fixture(), {"type": "trailing", "noise": True})+ grown_attrs = {s.name: s.attributes for s in _anchored(parser(grown, "trace-1")[1])}+ for span_name, attrs in before.items():+ assert (+ grown_attrs[span_name]["source.byte_offset"] == attrs["source.byte_offset"]+ ), (+ name,+ span_name,+ )+++def test_codex_web_search_calls_are_anchored_too():+ # Review-caught: a synthetic web_search tool record must carry its line.+ lines = [+ {+ "type": "session_meta",+ "timestamp": "2026-09-01T00:00:00Z",+ "payload": {"cwd": "/w", "id": "s1"},+ },+ {+ "type": "response_item",+ "timestamp": "2026-09-01T00:00:01Z",+ "payload": {"role": "user", "content": [{"type": "input_text", "text": "hi"}]},+ },+ {+ "type": "response_item",+ "timestamp": "2026-09-01T00:00:02Z",+ "payload": {"type": "web_search_call", "action": {"query": "x"}, "status": "completed"},+ },+ ]+ records = parse_jsonl_records(_jl(*lines))+ spans = codex.parse_codex(_jl(*lines), "trace-1")[1]+ tools = [s for s in spans if s.attributes.get("tool.name")]+ assert tools, "web_search should produce a tool span"+ assert tools[0].attributes["source.byte_offset"] == records[2][SOURCE_OFFSET_KEY]+ assert tools[0].attributes["source.content_hash"] == records[2][SOURCE_HASH_KEY]+++def test_record_hash_ignores_the_parsers_own_stamps():+ rec = {"a": 1, "b": [1, 2]}+ stamped = {**rec, SOURCE_OFFSET_KEY: 42, SOURCE_HASH_KEY: "x"}+ assert record_hash(rec) == record_hash(stamped)+ assert record_hash("not a dict") is None+ assert source_attrs(None) == {"source.kind": "jsonl"}+ assert source_attrs(stamped)["source.byte_offset"] == 42+++def test_parse_jsonl_records_keeps_every_dict_line_with_anchors():+ data = b'{"a": 1}\n\nnot json\n[1, 2]\n{"b": 2}\n'+ records = parse_jsonl_records(data)+ assert [r["a"] if "a" in r else r["b"] for r in records] == [1, 2]+ assert records[0][SOURCE_OFFSET_KEY] == 0+ assert records[1][SOURCE_OFFSET_KEY] == data.index(b'{"b": 2}')+ assert all(len(r[SOURCE_HASH_KEY]) == 16 for r in records)+++# ── row cursors for rewritten sources ────────────────────+++def test_rewritten_store_parsers_carry_a_row_cursor_when_the_record_names_one():+ from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import SOURCE_ROW_CURSOR_KEY++ # cursor_store: the CLI synthesizer stamps each message with its bubble id.+ # Messages in the parser's real wire shape (`tool-call` / `tool-result`+ # parts) so the tool span is actually built.+ msgs = [+ _cursor_store()[0],+ {+ "role": "user",+ "createdAt": "2026-09-01T00:00:01Z",+ "content": [{"type": "text", "text": "hi"}],+ SOURCE_ROW_CURSOR_KEY: "bubble-u1",+ },+ {+ "role": "assistant",+ "createdAt": "2026-09-01T00:00:02Z",+ "content": [{"type": "tool-call", "toolCallId": "t1", "toolName": "read", "args": {}}],+ SOURCE_ROW_CURSOR_KEY: "bubble-a1",+ },+ {+ "role": "tool",+ "createdAt": "2026-09-01T00:00:03Z",+ "content": [{"type": "tool-result", "toolCallId": "t1", "result": "ok"}],+ SOURCE_ROW_CURSOR_KEY: "bubble-t1",+ },+ ]+ spans = _anchored(cursor_store.parse_cursor_store(_jl(*msgs), "trace-1")[1])+ assert any(s.attributes.get("tool.name") for s in spans), [s.name for s in spans]+ turn = next(s for s in spans if s.name.startswith("Turn "))+ tool = next(s for s in spans if s.attributes.get("tool.name"))+ assert turn.attributes["source.row_cursor"] == "bubble-u1"+ # The requesting message anchors the call, not the result's message.+ assert tool.attributes["source.row_cursor"] == "bubble-a1"+ assert "source.byte_offset" not in turn.attributes+ assert turn.attributes["source.kind"] == "sqlite"++ # opencode: the message id is the key.+ recs = _opencode()+ recs[0]["id"] = "msg-1"+ recs[1]["id"] = "msg-2"+ spans = _anchored(opencode.parse_opencode(_jl(*recs), "trace-1")[1])+ turn = next(s for s in spans if s.name.startswith("Turn "))+ tool = next(s for s in spans if s.attributes.get("tool.name"))+ assert turn.attributes["source.row_cursor"] == "msg-1"+ assert tool.attributes["source.row_cursor"] == "msg-2"+++def test_cursor_store_reads_the_bubble_id_the_synthesizer_already_writes():+ # The materializer writes each bubble's id as the message `id`, so the+ # cursor is available with no new stamp and no hash churn.+ msgs = _cursor_store()+ msgs[1]["id"] = "bubble-u1"+ before = cursor_store._event_hash({k: v for k, v in msgs[1].items()})+ spans = _anchored(cursor_store.parse_cursor_store(_jl(*msgs), "trace-1")[1])+ turn = next(s for s in spans if s.name.startswith("Turn "))+ assert turn.attributes["source.row_cursor"] == "bubble-u1"+ assert turn.attributes["source.content_hash"] == before+++def test_older_uploads_without_a_row_cursor_are_unchanged():+ for name in ("cursor_store", "opencode"):+ for span in _anchored(_parse(name)):+ assert "source.row_cursor" not in span.attributes, (name, span.name)+++def test_the_row_cursor_stamp_never_changes_the_content_hash():+ from agentplay._core.ingestion.coding_agent._sources._jsonl_utils import SOURCE_ROW_CURSOR_KEY++ msg = {"role": "user", "content": "hi"}+ assert cursor_store._event_hash(msg) == cursor_store._event_hash(+ {**msg, SOURCE_ROW_CURSOR_KEY: "bubble-1"}+ )+ rec = {"a": 1}+ assert record_hash(rec) == record_hash({**rec, SOURCE_ROW_CURSOR_KEY: "x"})+ assert (+ source_attrs({"a": 1, SOURCE_ROW_CURSOR_KEY: "r"}, kind="sqlite")["source.row_cursor"]+ == "r"+ )+ assert source_attrs(None, row_cursor="r") == {"source.kind": "jsonl", "source.row_cursor": "r"}+ assert "source.row_cursor" not in source_attrs({"a": 1, SOURCE_ROW_CURSOR_KEY: ""})diff --git a/python/tests/core/test_structured_pr_creation.py b/python/tests/core/test_structured_pr_creation.pynew file mode 100644index 0000000..459a5f7--- /dev/null+++ b/python/tests/core/test_structured_pr_creation.py@@ -0,0 +1,545 @@+"""Structured creation requests must match successful native tool results."""++import json++import pytest++from agentplay._core.ingestion.coding_agent._sources.local.parsers.claude_code import parse_claude_code+from agentplay._core.ingestion.coding_agent._sources.local.parsers.codex import parse_codex+from agentplay._core.ingestion.coding_agent.produced import extract_created_prs+++def parse(+ agent,+ output,+ *,+ name="mcp__github__create_pull_request",+ failed=False,+ completed=True,+ tool_args=None,+ return_spans=False,+):+ args = {"owner": "Owner", "repo": "Repo", "head": "feature", "base": "main", "body": "x" * 3000}+ if tool_args is not None:+ args = tool_args+ if agent == "claude":+ rows = [+ {"type": "user", "message": {"role": "user", "content": "open PR"}},+ {+ "type": "assistant",+ "message": {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "create", "name": name, "input": args},+ ],+ },+ },+ ]+ if completed:+ rows.append(+ {+ "type": "user",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "create",+ "content": output,+ "is_error": failed,+ },+ ],+ },+ }+ )+ parser = parse_claude_code+ elif agent == "cursor":+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.cursor_store import (+ parse_cursor_store,+ )++ rows = [+ {"type": "cursor_store_session", "cwd": "/repo", "createdAt": 1790006400000},+ {"role": "user", "content": "open PR"},+ {+ "role": "assistant",+ "content": [+ {"type": "tool-call", "toolCallId": "create", "toolName": name, "args": args}+ ],+ },+ ]+ if completed:+ rows.append(+ {+ "role": "tool",+ "content": [+ {+ "type": "tool-result",+ "toolCallId": "create",+ "result": output,+ "isError": failed,+ }+ ],+ }+ )+ parser = parse_cursor_store+ elif agent == "copilot":+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.copilot import parse_copilot++ rows = [+ {"type": "user.message", "data": {"content": "open PR"}},+ {+ "type": "tool.execution_start",+ "data": {"toolCallId": "create", "toolName": name, "arguments": args},+ },+ ]+ if completed:+ rows.append(+ {+ "type": "tool.execution_complete",+ "data": {+ "toolCallId": "create",+ "success": not failed,+ "result": {"content": output},+ },+ }+ )+ parser = parse_copilot+ elif agent == "kiro":+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.kiro import parse_kiro++ rows = [+ {"type": "kiro_session", "id": "session"},+ {"payload": {"type": "user", "content": "edit"}},+ {+ "payload": {+ "type": "tool_call",+ "toolCallId": "edit",+ "toolName": name,+ "args": args,+ }+ },+ ]+ if completed:+ rows.append(+ {+ "payload": {+ "type": "tool_result",+ "toolCallId": "edit",+ "success": not failed,+ "content": output,+ }+ }+ )+ parser = parse_kiro+ elif agent == "opencode":+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.opencode import (+ parse_opencode,+ )++ rows = [+ {+ "id": "u",+ "message": {"role": "user", "time": {"created": 1000}},+ "parts": [{"type": "text", "text": "open PR"}],+ },+ {+ "id": "a",+ "message": {"role": "assistant", "time": {"created": 2000}},+ "parts": [+ {+ "type": "tool",+ "tool": name,+ "callID": "create",+ "state": {+ "input": args,+ "output": output,+ "status": "error"+ if failed+ else "completed"+ if completed+ else "running",+ },+ }+ ],+ },+ ]+ parser = parse_opencode+ else:+ rows = [+ {"type": "session_meta", "payload": {"id": "session", "cwd": "/repo"}},+ {+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "open PR"}],+ },+ },+ {+ "type": "response_item",+ "payload": {+ "type": "function_call",+ "call_id": "create",+ "name": name,+ "arguments": json.dumps(args),+ },+ },+ ]+ if agent == "codex-wrapper":+ rows[-1]["payload"].update(+ name="exec", arguments="text(await tools." + name + "(" + json.dumps(args) + "));"+ )+ result = {"content": output} if isinstance(output, list) else json.loads(output)+ output = [{"type": "text", "text": json.dumps(result)}]+ if completed:+ rows.append(+ {+ "type": "response_item",+ "payload": {+ "type": "function_call_output",+ "call_id": "create",+ "output": output,+ },+ }+ )+ parser = parse_codex+ raw = b"\n".join(json.dumps({**r, "timestamp": "2026-09-21T00:00:00Z"}).encode() for r in rows)+ _, spans = parser(raw, "session")+ return spans if return_spans else extract_created_prs(spans)+++ "agent", ["claude", "codex", "codex-wrapper", "cursor", "copilot", "opencode"]+)[email protected]("wrapped", [False, True])+def test_successful_structured_creation_survives_display_truncation(agent, wrapped):+ result = json.dumps(+ {"body": "x" * 4000, "html_url": "https://github.com/owner/repo/pull/9", "number": 9}+ )+ if wrapped:+ result = [{"type": "text", "text": result}]+ [created] = parse(agent, result)+ assert created.number == 9+ assert created.repo_name == "owner/repo"+ assert created.source_event_id+++ "agent", ["claude", "codex", "codex-wrapper", "cursor", "copilot", "opencode"]+)+ "result",+ [+ {"html_url": "https://github.com/other/repo/pull/9", "number": 9},+ {"html_url": "https://github.com/owner/repo/pull/9", "number": 8},+ {"html_url": "https://github.com/owner/repo/pull/9", "error": "already exists"},+ {"html_url": "https://github.com/owner/repo/pull/9", "isError": True},+ {"html_url": "https://github.com/owner/repo/pull/9", "number": True},+ ],+)+def test_conflicting_or_failed_structured_result_never_links(agent, result):+ assert parse(agent, json.dumps(result)) == []+++ "agent", ["claude", "codex", "codex-wrapper", "cursor", "copilot", "opencode"]+)+def test_reads_and_unfinished_creates_never_link(agent):+ result = json.dumps({"html_url": "https://github.com/owner/repo/pull/9", "number": 9})+ assert parse(agent, result, name="mcp__github__pull_request_read") == []+ assert parse(agent, result, completed=False) == []++[email protected]("agent", ["claude", "cursor", "copilot", "opencode"])+def test_failed_tool_result_never_links(agent):+ assert (+ parse(agent, json.dumps({"html_url": "https://github.com/owner/repo/pull/9"}), failed=True)+ == []+ )+++ ("command", "expected"),+ [+ (+ "gh api repos/owner/repo/pulls -X POST -f title=change -f head=feature -f base=main",+ True,+ ),+ ("gh api /repos/owner/repo/pulls --method POST --input body.json", True),+ ("gh api repos/owner/repo/pulls -X GET", False),+ ("gh api repos/owner/repo/pulls -X POST; echo fake", False),+ ("gh api repos/owner/repo/pulls -X POST -f title=x;echo fake", False),+ ("gh api repos/owner/repo/pulls -X POST\necho fake", False),+ ("gh api repos/owner/repo/pulls -X POST --hostname github.example", False),+ ],+)+def test_explicit_rest_creation_requires_single_successful_request(command, expected):+ from datetime import UTC, datetime++ from agentplay._core.ingestion.coding_agent.produced import (+ creation_command_attributes,+ creation_output_attributes,+ )+ from agentplay._core.ingestion.coding_agent.spans import SpanData++ request = creation_command_attributes({"command": command}, "Bash")+ output = json.dumps({"html_url": "https://github.com/owner/repo/pull/9", "number": 9})+ response = creation_output_attributes(+ output, request.get("pr.create.provider"), request.get("pr.create.repository")+ )+ now = datetime.now(UTC)+ span = SpanData(+ "event",+ "session",+ None,+ "Bash",+ "TOOL",+ "OK",+ now,+ now,+ {+ "tool.name": "Bash",+ "input.value": json.dumps({"command": command}),+ "output.value": output,+ **request,+ **response,+ },+ )+ assert bool(extract_created_prs([span])) is expected+ if expected:+ span.attributes["tool.name"] = "Read"+ assert extract_created_prs([span]) == []+ span.attributes["tool.name"] = "Bash"+ span.status_code = "ERROR"+ assert extract_created_prs([span]) == []+++def test_codex_shell_rest_creation_uses_completed_process_body():+ args = {"cmd": "gh api repos/owner/repo/pulls -X POST -f head=feature -f base=main"}+ response = json.dumps(+ {"body": "x" * 4000, "html_url": "https://github.com/owner/repo/pull/9", "number": 9}+ )+ records = [+ {"type": "session_meta", "payload": {"id": "session", "cwd": "/repo"}},+ {+ "type": "response_item",+ "payload": {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "create"}],+ },+ },+ {+ "type": "response_item",+ "payload": {+ "type": "function_call",+ "name": "exec_command",+ "call_id": "create",+ "arguments": json.dumps(args),+ },+ },+ {+ "type": "response_item",+ "payload": {+ "type": "function_call_output",+ "call_id": "create",+ "output": json.dumps({"output": response, "exit_code": 0, "wall_time_seconds": 1}),+ },+ },+ ]+ raw = b"\n".join(+ json.dumps({**row, "timestamp": "2026-09-21T00:00:00Z"}).encode() for row in records+ )+ _, spans = parse_codex(raw, "session")+ tool = next(s for s in spans if s.tool_name == "Bash")+ assert tool.attributes["pr.create.output_url"] == "https://github.com/owner/repo/pull/9"+ assert "https://github.com/owner/repo/pull/9" not in tool.attributes["output.value"]+ assert [created.number for created in extract_created_prs(spans)] == [9]+++ "name",+ [+ "mcp__evil__create_pull_request",+ "mcp__gitlab__create_pull_request",+ "create_pull_request",+ "githubish.create_pull_request",+ ],+)+def test_unknown_provider_never_becomes_github_creation(name):+ assert (+ parse(+ "claude",+ json.dumps({"html_url": "https://github.com/owner/repo/pull/9", "number": 9}),+ name=name,+ )+ == []+ )++[email protected]("tool_name", ["Edit", "Write"])[email protected]("status", ["OK", "ERROR", "UNSET"])+def test_only_completed_mutations_count_as_useful_edits(tool_name, status):+ from datetime import UTC, datetime++ from agentplay._core.ingestion.coding_agent.metrics import compute_task_counters+ from agentplay._core.ingestion.coding_agent.spans import SpanData++ now = datetime.now(UTC)+ span = SpanData(+ "event",+ "session",+ "session:turn:1",+ tool_name,+ "TOOL",+ status,+ now,+ now,+ {"tool.name": tool_name, "input.value": json.dumps({"file_path": "src.py"})},+ )+ counters = compute_task_counters([span], start_turn=1, end_turn=1)+ assert counters.useful_edit_count == int(status == "OK")+ assert counters.error_count == int(status == "ERROR")++[email protected]("failed", [False, True])+def test_copilot_preserves_mcp_error_envelope(failed):+ from agentplay._core.ingestion.coding_agent._sources.local.parsers.copilot import parse_copilot++ body = {+ "isError": failed,+ "content": [+ {+ "type": "text",+ "text": json.dumps(+ {"html_url": "https://github.com/owner/repo/pull/9", "number": 9}+ ),+ }+ ],+ }+ rows = [+ {+ "type": "tool.execution_start",+ "data": {+ "toolCallId": "create",+ "toolName": "mcp__github__create_pull_request",+ "arguments": {"owner": "owner", "repo": "repo"},+ },+ },+ {+ "type": "tool.execution_complete",+ "data": {"toolCallId": "create", "success": True, "result": body},+ },+ ]+ _, spans = parse_copilot(+ b"\n".join(json.dumps({**r, "timestamp": "2026-09-21T00:00:00Z"}).encode() for r in rows),+ "session",+ )+ assert bool(extract_created_prs(spans)) is not failed+++ "agent", ["claude", "codex", "cursor", "copilot", "opencode", "kiro"]+)[email protected]("name", ["Edit", "Write"])[email protected]("completed", [True, False])+def test_native_mutation_completion_controls_useful_edit_metrics(agent, name, completed):+ from agentplay._core.ingestion.coding_agent.metrics import compute_task_counters++ spans = parse(+ agent,+ "done",+ name=name,+ completed=completed,+ tool_args={+ "file_path": "src.py",+ "old_string": "before",+ "new_string": "after",+ "content": "after",+ },+ return_spans=True,+ )+ [tool] = [s for s in spans if s.tool_name == name]+ assert tool.status_code == ("OK" if completed else "UNSET")+ counters = compute_task_counters(spans, start_turn=1, end_turn=1)+ assert counters.useful_edit_count == int(completed)++[email protected]("agent", ["claude", "codex", "cursor", "copilot", "opencode"])+ "selector",+ ["-R owner/repo", "--repo=owner/repo", "-Rowner/repo", "--repo github.com/owner/repo"],+)+def test_explicit_shell_repository_must_match_created_url(agent, selector):+ command = "gh pr create --body '" + "x" * 2500 + "' " + selector+ args = {"command": command} if agent != "codex" else {"cmd": command}+ name = "exec_command" if agent == "codex" else "bash"+ good = "https://github.com/owner/repo/pull/9"+ bad = "https://github.com/other/repo/pull/9"+ assert len(parse(agent, good, name=name, tool_args=args)) == 1+ assert parse(agent, bad, name=name, tool_args=args) == []+++ "command,accepted",+ [+ ("GH_REPO=owner/repo gh pr create", True),+ ("GH_REPO=other/repo gh pr create", False),+ ("GH_REPO=other/repo gh pr create -R owner/repo", True),+ ("GH_HOST=enterprise.example gh pr create -R owner/repo", False),+ ("gh pr create -R owner/repo --repo other/repo", False),+ ("gh pr create --body '-R other/repo' -R owner/repo", True),+ ],+)+def test_shell_repository_selectors_and_body_text(command, accepted):+ assert (+ bool(+ parse(+ "claude",+ "https://github.com/owner/repo/pull/9",+ name="bash",+ tool_args={"command": command},+ )+ )+ is accepted+ )+++def test_opencode_retains_unsupported_creation_capture():+ spans = parse(+ "opencode",+ "https://github.com/owner/repo/pull/9",+ name="bash",+ tool_args={"command": "python create_pr.py && gh pr create"},+ return_spans=True,+ )+ assert any(s.attributes.get("pr.create.capture") == "unrecognized_creation_text" for s in spans)++[email protected]("poll", [False, True])+def test_host_error_overrides_zero_exit_code(poll):+ from agentplay._core.ingestion.coding_agent.native_operations import ProcessEvidence++ evidence = ProcessEvidence()+ origin = {"name": "exec_command", "pr.create.provider": "github", "end_ts": "now"}+ if poll:+ evidence.observe(+ origin,+ {"cmd": "gh pr create"},+ {"session_id": 7, "exit_code": None, "wall_time_seconds": 0, "output": ""},+ )+ tool = {"name": "write_stdin", "end_ts": "later"} if poll else origin+ evidence.observe(+ tool,+ {"session_id": 7} if poll else {"cmd": "gh pr create"},+ {+ "isError": True,+ "exit_code": 0,+ "wall_time_seconds": 0,+ "output": "https://github.com/owner/repo/pull/9",+ },+ )+ assert origin["is_error"] is True+ assert origin["pr.create.output_url"] == ""+ assert evidence.pending == {}diff --git a/python/tests/core/test_tool_taxonomy.py b/python/tests/core/test_tool_taxonomy.pynew file mode 100644index 0000000..5596410--- /dev/null+++ b/python/tests/core/test_tool_taxonomy.py@@ -0,0 +1,74 @@+"""The shared raw -> canonical tool table.++Every parser reads ``tool_taxonomy``. These tests pin that the rows resolve+the way each parser expects.+"""++from __future__ import annotations++import pytest++from agentplay._core.ingestion.coding_agent import tool_taxonomy as tt+from agentplay._core.ingestion.coding_agent._sources.local.parsers import (+ codex,+ copilot,+ cursor_agent_transcript,+ cursor_store,+ kiro,+ opencode,+)+++ ("module", "agent"),+ [+ (codex, "codex"),+ (cursor_store, "cursor"),+ (cursor_agent_transcript, "cursor"),+ (copilot, "copilot"),+ (kiro, "kiro"),+ (opencode, "opencode"),+ ],+)+def test_every_parser_reads_the_shared_table(module, agent) -> None:+ # Same object, not a copy: a new row in tool_taxonomy reaches the parser.+ assert module._TOOL_ALIASES is tt.aliases_for(agent)+++ ("agent", "raw", "canonical"),+ [+ ("codex", "exec_command", "Bash"),+ ("codex", "apply_patch", "Edit"),+ ("cursor", "run_terminal_cmd", "Bash"),+ ("cursor", "SemanticSearch", "Search"),+ ("cursor", "Subagent", "Task"),+ ("copilot", "str_replace_editor", "Edit"),+ ("copilot", "view", "Read"),+ ("kiro", "execute_bash", "Bash"),+ ("opencode", "todowrite", "TodoWrite"),+ ],+)+def test_known_raw_names_resolve(agent, raw, canonical) -> None:+ assert tt.aliases_for(agent)[raw] == canonical+++def test_unknown_and_claude_names_pass_through() -> None:+ # Claude Code names are already canonical; MCP and unknown names are not rows,+ # so the parsers' ``.get(raw, raw)`` passes them through.+ assert tt.aliases_for("claude-code") == {}+ assert "brand_new_tool" not in tt.aliases_for("codex")+ assert not any(k.startswith("mcp__") for t in tt.TOOL_ALIASES.values() for k in t)+++def test_table_sizes_are_pinned() -> None:+ # These counts are pinned; a changed count means a row was added or dropped on purpose -- update here.+ # copilot-vscode's 12 rows are pinned against real tool names.+ assert {a: len(t) for a, t in tt.TOOL_ALIASES.items()} == {+ "codex": 7,+ "cursor": 26,+ "copilot": 23,+ "copilot-vscode": 12,+ "kiro": 12,+ "opencode": 14,+ }diff --git a/python/tests/test_account.py b/python/tests/test_account.pynew file mode 100644index 0000000..144a151--- /dev/null+++ b/python/tests/test_account.py@@ -0,0 +1,409 @@+"""The email signup: what is sent, when nothing is sent, and who may post."""++from __future__ import annotations++import http.client+import json+import re+import socket+import subprocess+import sys+import threading+import urllib.error+import urllib.request+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any++import pytest++from agentplay import account+from agentplay import server as server_mod+from agentplay.server import serve+from agentplay.store import Store+++class _Endpoint:+ """A stand-in for the signup endpoint that records what it was sent."""++ def __init__(self, status: int = 200, answer: bytes = b'{"ok": true}') -> None:+ received: list[dict[str, Any]] = []++ class H(BaseHTTPRequestHandler):+ def log_message(self, *a: Any) -> None:+ return++ def do_POST(self) -> None: # noqa: N802+ received.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(answer)))+ self.end_headers()+ self.wfile.write(answer)++ self.received = received+ self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)+ self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}/exec"+ threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()++ def close(self) -> None:+ self.httpd.shutdown()+ self.httpd.server_close()++[email protected](autouse=True)+def no_real_endpoint(monkeypatch):+ """Tests never reach the real Sheet: the built-in URL is blanked for all of them."""+ monkeypatch.setattr(account, "DEFAULT_SIGNUP_URL", "")+++def home(tmp_path, monkeypatch):+ monkeypatch.setenv("AGENTPLAY_HOME", str(tmp_path / "sm"))+ for var in ("AGENTPLAY_SIGNUP_URL", "DO_NOT_TRACK", "AGENTPLAY_NO_NETWORK"):+ monkeypatch.delenv(var, raising=False)+ return tmp_path / "sm"+++def endpoint(home, monkeypatch):+ ep = _Endpoint()+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", ep.url)+ yield ep+ ep.close()+++def viewer(home):+ httpd = serve(0, store=Store(home))+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ port = httpd.server_address[1]+ yield f"http://127.0.0.1:{port}"+ httpd.shutdown()+ httpd.server_close()+++def _post(base: str, body: Any, *, origin: str | None = "same", ctype: str = "application/json") -> tuple[int, dict]:+ data = json.dumps(body).encode()+ headers = {"Content-Type": ctype}+ if origin == "same":+ headers["Origin"] = base+ elif origin:+ headers["Origin"] = origin+ req = urllib.request.Request(base + "/api/account", data=data, method="POST", headers=headers)+ try:+ with urllib.request.urlopen(req) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read())+++def _get(base: str) -> dict:+ with urllib.request.urlopen(base + "/api/account") as r:+ return json.loads(r.read())+++def test_card_is_off_without_an_endpoint(home, viewer):+ assert _get(viewer) == {"success": True, "status": "none", "email": None, "enabled": False}++[email protected]("var", ["DO_NOT_TRACK", "AGENTPLAY_NO_NETWORK"])+def test_opt_out_turns_the_card_off_and_sends_nothing(endpoint, viewer, monkeypatch, var):+ monkeypatch.setenv(var, "1")+ assert _get(viewer)["enabled"] is False+ status, body = _post(viewer, {"action": "signup", "email": "[email protected]"})+ assert status == 502 and endpoint.received == []+ assert not account.path().exists()+++def test_signup_sends_only_the_email_and_an_install_id(endpoint, viewer):+ assert _get(viewer)["enabled"] is True+ status, body = _post(viewer, {"action": "signup", "email": "[email protected]"})+ assert status == 200 and body["status"] == "signed_up" and body["email"] == "[email protected]"+ (sent,) = endpoint.received+ assert set(sent) == {"event", "email", "installId", "version", "at"}+ assert sent["event"] == "signup" and sent["email"] == "[email protected]"+ assert _get(viewer)["status"] == "signed_up"+++def test_failed_delivery_stores_nothing(home, viewer, monkeypatch):+ down = _Endpoint(status=500)+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", down.url)+ try:+ status, body = _post(viewer, {"action": "signup", "email": "[email protected]"})+ finally:+ down.close()+ assert status == 502 and body["code"] == "unreachable"+ assert _get(viewer)["status"] == "none"+++def test_skip_sends_nothing_and_is_remembered(endpoint, viewer):+ status, body = _post(viewer, {"action": "skip"})+ assert status == 200 and body["status"] == "skipped"+ assert endpoint.received == []+++def test_disconnect_forgets_locally_and_tells_the_endpoint(endpoint, viewer):+ _post(viewer, {"action": "signup", "email": "[email protected]"})+ iid = account.load()["installId"]+ status, body = _post(viewer, {"action": "disconnect"})+ assert status == 200 and body["status"] == "skipped" and body["email"] is None+ assert [e["event"] for e in endpoint.received] == ["signup", "disconnect"]+ assert endpoint.received[1]["installId"] == iid+ assert "email" not in account.load()+++def test_disconnect_still_forgets_when_the_endpoint_is_down(home, viewer, monkeypatch):+ ep = _Endpoint()+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", ep.url)+ _post(viewer, {"action": "signup", "email": "[email protected]"})+ ep.close()+ status, body = _post(viewer, {"action": "disconnect"})+ assert status == 200 and body["email"] is None++[email protected]("email", ["", "not-an-email", "a@b", "a [email protected]", "x" * 250 + "@a.co"])+def test_rejects_bad_emails_without_sending(endpoint, viewer, email):+ status, body = _post(viewer, {"action": "signup", "email": email})+ assert status == 400 and body["code"] == "invalid_email"+ assert endpoint.received == []++[email protected]("origin", [None, "https://evil.example", "http://127.0.0.1.evil.example:7317"])+def test_rejects_posts_from_other_sites(endpoint, viewer, origin):+ status, _ = _post(viewer, {"action": "signup", "email": "[email protected]"}, origin=origin)+ assert status == 403 and endpoint.received == []+++def test_accepts_the_dev_server_origin_only_when_configured(endpoint, viewer, monkeypatch):+ status, _ = _post(viewer, {"action": "skip"}, origin="http://localhost:5173")+ assert status == 403+ monkeypatch.setenv("AGENTPLAY_DEV_ORIGINS", "http://localhost:4000, http://localhost:5173/")+ status, _ = _post(viewer, {"action": "skip"}, origin="http://localhost:5173")+ assert status == 200+++def test_accepts_its_own_origin_under_any_local_name(endpoint, viewer):+ port = viewer.rsplit(":", 1)[1]+ for host in ("127.0.0.1", "localhost", "LOCALHOST"):+ status, _ = _post(viewer, {"action": "skip"}, origin=f"http://{host}:{port}")+ assert status == 200, host++[email protected]("origin", ["http://localhost:1", "http://127.0.0.1:8080", "https://localhost:{port}"])+def test_rejects_other_local_ports(endpoint, viewer, origin):+ origin = origin.format(port=viewer.rsplit(":", 1)[1])+ status, _ = _post(viewer, {"action": "signup", "email": "[email protected]"}, origin=origin)+ assert status == 403 and endpoint.received == []+++def test_rejects_form_posts(endpoint, viewer):+ status, _ = _post(viewer, {"action": "skip"}, ctype="text/plain")+ assert status == 415+++def test_network_code_lives_in_one_file():+ src = Path(account.__file__).parent+ hits = sorted(p.name for p in src.rglob("*.py") if "urllib.request" in p.read_text(encoding="utf-8"))+ assert hits == ["account.py"]+++def test_importing_the_package_makes_no_network_call():+ code = ("import socket\n"+ "def no(*a, **k): raise AssertionError('network')\n"+ "socket.socket.connect = no\n"+ "import agentplay.cli, agentplay.server, agentplay.account\n")+ subprocess.run([sys.executable, "-c", code], check=True)++[email protected](("url", "ok"), [+ ("https://script.google.com/macros/s/x/exec", True),+ ("https://script.googleusercontent.com/macros/echo?x=1", True),+ ("https://api.entelligence.ai/signup", True),+ ("https://example.com/exec", False),+ ("https://script.google.com.evil.example/exec", False),+ ("https://user:[email protected]/exec", False),+ ("https://10.0.0.5/exec", False),+ ("http://script.google.com/exec", False),+ ("http://127.0.0.1:8787/exec", True),+ ("http://localhost:8787/exec", True),+ ("http://[::1]:8787/exec", True),+ ("http://example.com/exec", False),+ ("file:///etc/passwd", False),+ ("ftp://example.com/x", False),+ ("https:///nohost", False),+ ("", False),+])+def test_only_https_or_this_machine_is_allowed(url, ok):+ assert account.allowed_url(url) is ok+++def test_a_disallowed_url_turns_the_card_off_and_sends_nothing(home, viewer, monkeypatch):+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", "file:///etc/passwd")+ assert _get(viewer)["enabled"] is False+ status, _ = _post(viewer, {"action": "signup", "email": "[email protected]"})+ assert status == 502 and not account.path().exists()+++def _garbage_endpoint() -> tuple[str, socket.socket]:+ """Answers every connection with a malformed status line."""+ srv = socket.socket()+ srv.bind(("127.0.0.1", 0))+ srv.listen()++ def loop() -> None:+ while True:+ try:+ conn, _ = srv.accept()+ except OSError:+ return+ with conn:+ conn.recv(65536)+ conn.sendall(b"NOT-HTTP garbage\r\n\r\n")++ threading.Thread(target=loop, daemon=True).start()+ return f"http://127.0.0.1:{srv.getsockname()[1]}/exec", srv+++def test_a_malformed_answer_is_a_failed_signup_and_never_blocks_disconnect(endpoint, viewer, monkeypatch):+ _post(viewer, {"action": "signup", "email": "[email protected]"})+ url, srv = _garbage_endpoint()+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", url)+ try:+ status, body = _post(viewer, {"action": "disconnect"})+ assert status == 200 and body["email"] is None+ assert "email" not in account.load()+ account.skip()+ status, body = _post(viewer, {"action": "signup", "email": "[email protected]"})+ assert status == 502 and body["code"] == "unreachable"+ finally:+ srv.close()+++def test_a_remote_client_never_sees_the_email(endpoint, viewer, monkeypatch):+ _post(viewer, {"action": "signup", "email": "[email protected]"})+ monkeypatch.setattr(server_mod, "_is_loopback", lambda _addr: False)+ assert _get_as(viewer, {}) == (403, FORBIDDEN)+++def test_a_redirect_to_an_untrusted_host_is_a_failed_signup(home, viewer, monkeypatch):+ class R(BaseHTTPRequestHandler):+ def log_message(self, *a: Any) -> None:+ return++ def do_POST(self) -> None: # noqa: N802+ self.rfile.read(int(self.headers["Content-Length"]))+ self.send_response(302)+ self.send_header("Location", "http://example.com/steal")+ self.send_header("Content-Length", "0")+ self.end_headers()++ httpd = ThreadingHTTPServer(("127.0.0.1", 0), R)+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", f"http://127.0.0.1:{httpd.server_address[1]}/exec")+ # Record every host a connection is opened to, and never actually reach the+ # outside: the guard must stop the redirect before any connection is made.+ contacted: list[str] = []+ real_connect = http.client.HTTPConnection.connect++ def spy(conn: http.client.HTTPConnection) -> None:+ contacted.append(conn.host)+ if conn.host not in ("127.0.0.1", "localhost"):+ raise AssertionError(f"contacted {conn.host}")+ real_connect(conn)++ monkeypatch.setattr(http.client.HTTPConnection, "connect", spy)+ try:+ status, body = _post(viewer, {"action": "signup", "email": "[email protected]"})+ finally:+ httpd.shutdown()+ httpd.server_close()+ assert "example.com" not in contacted+ assert status == 502 and not account.path().exists()++[email protected](("start", "target", "ok"), [+ ("https://script.google.com/macros/s/x/exec", "https://script.googleusercontent.com/echo", True),+ ("https://script.google.com/macros/s/x/exec", "http://127.0.0.1:8080/admin", False),+ ("https://script.google.com/macros/s/x/exec", "http://localhost/admin", False),+ ("https://script.google.com/macros/s/x/exec", "https://evil.example/", False),+ ("http://127.0.0.1:9/exec", "http://localhost:9/echo", True), # a local test endpoint+ ("http://127.0.0.1:9/exec", "https://script.googleusercontent.com/echo", True),+ ("http://127.0.0.1:9/exec", "https://evil.example/", False),+])+def test_a_redirect_lands_on_this_machine_only_from_a_local_url(start, target, ok):+ """Checked on the handler directly: nothing is opened, so nothing can leak."""+ handler = account._CheckedRedirects()+ req = urllib.request.Request(start, data=b"{}", method="POST")+ if ok:+ assert handler.redirect_request(req, None, 302, "Found", {}, target).full_url == target+ return+ with pytest.raises(urllib.error.HTTPError):+ handler.redirect_request(req, None, 302, "Found", {}, target)+++FORBIDDEN = {"success": False, "code": "forbidden", "error": "Only the local viewer can read this."}+++def _get_as(base: str, headers: dict[str, str]) -> tuple[int, dict]:+ req = urllib.request.Request(base + "/api/account", headers=headers)+ try:+ with urllib.request.urlopen(req) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read())++[email protected]("headers", [+ {"Host": "evil.example:7317"},+ {"Host": "127.0.0.1.evil.example"},+ {"Origin": "https://evil.example"},+])+def test_a_rebinding_page_never_reads_the_email(endpoint, viewer, headers):+ _post(viewer, {"action": "signup", "email": "[email protected]"})+ assert _get_as(viewer, headers) == (403, FORBIDDEN)+ assert _get(viewer)["email"] == "[email protected]"++[email protected]("answer", [+ b"<!DOCTYPE html><title>Error</title>TypeError: Cannot read properties of null", # a crashed Apps Script+ b"",+ b'{"ok": false}',+ b"[]",+ b"[" * 1000 + b"]" * 1000, # nested deep enough to make json.loads raise RecursionError+])+def test_a_200_without_ok_true_is_a_failed_signup(home, viewer, monkeypatch, answer):+ ep = _Endpoint(answer=answer)+ monkeypatch.setenv("AGENTPLAY_SIGNUP_URL", ep.url)+ try:+ status, body = _post(viewer, {"action": "signup", "email": "[email protected]"})+ finally:+ ep.close()+ assert status == 502 and body["code"] == "unreachable"+ assert _get(viewer)["status"] == "none"+++def test_the_built_in_endpoint_is_a_trusted_https_url():+ import importlib++ fresh = importlib.reload(account) # the module constant, before the autouse blanking+ try:+ assert fresh.DEFAULT_SIGNUP_URL.startswith("https://script.google.com/macros/s/")+ assert fresh.allowed_url(fresh.DEFAULT_SIGNUP_URL)+ finally:+ importlib.reload(account)+++def test_signup_script_accepts_exactly_what_the_client_sends():+ """docs/signup-endpoint.md's Apps Script must not reject an address the CLI posts."""+ doc = Path(__file__).resolve().parents[2] / "docs" / "signup-endpoint.md"+ if not doc.exists():+ pytest.skip("docs/ is not in an unpacked sdist")+ m = re.search(r"if \(!/(.+?)/\.test\(email\)\)", doc.read_text(encoding="utf-8"))+ assert m, "email check not found in the reference script"+ assert m.group(1) == account._EMAIL.pattern+ assert account.valid_email("[email protected]")+ # Where Python's and JavaScript's \s differ, the client must be the stricter side+ # so it never posts an address the endpoint refuses.+ assert not account.valid_email("a\[email protected]")+ assert not account.valid_email("a\[email protected]")diff --git a/python/tests/test_builder.py b/python/tests/test_builder.pynew file mode 100644index 0000000..3090604--- /dev/null+++ b/python/tests/test_builder.py@@ -0,0 +1,743 @@+"""Builder: redaction and document shape."""++from __future__ import annotations++import json+import os+import re+from pathlib import Path+from types import SimpleNamespace++import pytest++from agentplay import builder as sm++SECRET_PROMPT = "please fix the SECRET-PROMPT-TEXT in billing"+SECRET_ARG = "--token=hunter2-SECRET-ARG"+# Shell lines whose quoted or substituted values once leaked into `verb`: a naive+# whitespace split handed a fragment of the value to the verb. Values are fake.+LEAKY_COMMANDS = (+ ('AUTH="Bearer sk-ant-FAKE123456" curl https://x', "curl"),+ ('F="/Users/me/Application Support/secret-plan.pdf"; open "$F"', "open"),+ ('MSG="fix secret stuff" git commit', "git commit"),+ ('x=$(gh api repos/acme/LEAKREPO --jq ".a | select(.b == \\"c d\\")") && echo "$x"', "echo"),+ ("A=$'line one\\nANSI-SECRET two' make build", "make build"),+ ("env TOKEN='abc ENV-SECRET' FOO=1 npm test", "npm test"),+ ("sudo -u sudo-secret-user systemctl restart x", "systemctl"),+ ('cd "/x y/CD-SECRET" && A="p QUOTED-SECRET" pytest -q', "pytest"),+ ('"$SECRET_BIN" --flag', "sh"),+ ("$(which SUBST-SECRET) run.py", "sh"),+ ("leak(){ echo FN-SECRET; }; leak", "sh"),+ ('echo "never closes SECRET-OPEN', "echo"),+)+++def _line(**d):+ return json.dumps(d) + "\n"+++def fake_home(tmp_path, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HOME", str(home))+ # Windows expands ~ from USERPROFILE, and VS Code paths from APPDATA.+ monkeypatch.setenv("USERPROFILE", str(home))+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ return home+++def transcript(tmp_path):+ repo = tmp_path / "work" / "backend"+ (repo / ".git").mkdir(parents=True)+ (repo / ".git" / "config").write_text(+ '[remote "origin"]\n\turl = [email protected]:acme/backend.git\n'+ )+ (repo / "billing_core").mkdir()+ (repo / "billing_core" / "controller.py").write_text("x = 1\n")+ (repo / "README.md").write_text("hi\n")+ cwd = str(repo)+ ts = "2026-09-10T01:00:0{}Z"+ lines = [+ _line(+ type="user",+ timestamp=ts.format(0),+ cwd=cwd,+ message={"role": "user", "content": SECRET_PROMPT},+ ),+ _line(+ type="assistant",+ timestamp=ts.format(1),+ cwd=cwd,+ message={+ "id": "m1",+ "model": "claude-sonnet-5",+ "usage": {+ "input_tokens": 10,+ "cache_creation_input_tokens": 100,+ "cache_read_input_tokens": 1000,+ "output_tokens": 50,+ },+ "content": [+ {+ "type": "tool_use",+ "id": "t1",+ "name": "Read",+ "input": {"file_path": f"{cwd}/billing_core/controller.py"},+ },+ {+ "type": "tool_use",+ "id": "t2",+ "name": "Bash",+ "input": {"command": f"cd {cwd} && git log -5 {SECRET_ARG} README.md"},+ },+ *(+ {"type": "tool_use", "id": f"tl{i}", "name": "Bash", "input": {"command": c}}+ for i, (c, _) in enumerate(LEAKY_COMMANDS)+ ),+ {+ "type": "tool_use",+ "id": "t3",+ "name": "mcp__claude-in-chrome__navigate",+ "input": {"url": "https://secret.example/x?token=abc"},+ },+ {+ "type": "tool_use",+ "id": "t4",+ "name": "Skill",+ "input": {"skill": "entloop", "args": SECRET_ARG},+ },+ {+ "type": "tool_use",+ "id": "t5",+ "name": "Agent",+ "input": {+ "description": "SECRET-SUBAGENT-DESC",+ "prompt": SECRET_PROMPT,+ "subagent_type": "Explore",+ },+ },+ ],+ },+ ),+ _line(+ type="user",+ timestamp=ts.format(2),+ cwd=cwd,+ message={+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "t1",+ "content": "file body SECRET-OUTPUT",+ },+ {+ "type": "tool_result",+ "tool_use_id": "t2",+ "content": "log",+ "is_error": True,+ },+ {"type": "tool_result", "tool_use_id": "t3", "content": "ok"},+ {"type": "tool_result", "tool_use_id": "t4", "content": "ok"},+ {"type": "tool_result", "tool_use_id": "t5", "content": "done"},+ ],+ },+ toolUseResult={"agentId": "abc123def456789"},+ ),+ _line(+ type="assistant",+ timestamp=ts.format(3),+ cwd=cwd,+ message={+ "id": "m2",+ "model": "claude-sonnet-5",+ "usage": {"input_tokens": 5, "output_tokens": 5},+ "content": [+ {+ "type": "tool_use",+ "id": "t6",+ "name": "Edit",+ "input": {+ "file_path": f"{cwd}/billing_core/controller.py",+ "old_string": "x",+ "new_string": "SECRET-EDIT",+ },+ }+ ],+ },+ ),+ _line(+ type="user",+ timestamp=ts.format(4),+ cwd=cwd,+ message={+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "t6", "content": "ok"}],+ },+ ),+ ]+ path = tmp_path / "proj" / "11111111-2222-3333-4444-555555555555.jsonl"+ path.parent.mkdir(parents=True)+ path.write_text("".join(lines))+ sub = path.with_suffix("") / "subagents"+ sub.mkdir(parents=True)+ (sub / "agent-abc123def456789.jsonl").write_text(+ _line(+ type="assistant",+ timestamp=ts.format(2),+ cwd=cwd,+ isSidechain=True,+ message={+ "id": "s1",+ "model": "claude-haiku-4-5-20251001",+ "usage": {"input_tokens": 7, "output_tokens": 3},+ "content": [+ {+ "type": "tool_use",+ "id": "u1",+ "name": "Grep",+ "input": {"pattern": "SECRET-PATTERN", "path": f"{cwd}/billing_core"},+ }+ ],+ },+ )+ )+ return path+++# ---------------------------------------------------------------- builder+++def test_acompact_snapshot_is_not_a_subagent_lane(transcript):+ before = sm.build_claude_code_map(transcript)+ parent_llm = next(+ json.loads(line)+ for line in transcript.read_text().splitlines()+ if json.loads(line).get("type") == "assistant"+ )+ (transcript.with_suffix("") / "subagents" / "agent-acompact-0a1b2c3d.jsonl").write_text(+ _line(**{**parent_llm, "isSidechain": True})+ )+ doc = sm.build_claude_code_map(transcript)+ assert [a["id"] for a in doc["agents"]] == [a["id"] for a in before["agents"]]+ assert not any("acompact" in a["id"] for a in doc["agents"])+ assert doc["totals"]["subagents"] == 1+ assert doc["totals"]["tokens"] == before["totals"]["tokens"]+++def test_builder_never_leaks_free_text(transcript):+ raw = json.dumps(sm.build_claude_code_map(transcript))+ for secret in (+ "SECRET-PROMPT-TEXT",+ "hunter2",+ "SECRET-ARG",+ "SECRET-OUTPUT",+ "SECRET-SUBAGENT-DESC",+ "SECRET-EDIT",+ "SECRET-PATTERN",+ "token=abc",+ "secret.example/x",+ "sk-ant-FAKE123456",+ "secret-plan",+ "Application Support",+ "fix secret stuff",+ "LEAKREPO",+ "ANSI-SECRET",+ "ENV-SECRET",+ "sudo-secret-user",+ "CD-SECRET",+ "QUOTED-SECRET",+ "SECRET_BIN",+ "SUBST-SECRET",+ "FN-SECRET",+ "SECRET-OPEN",+ ):+ assert secret not in raw, secret+ verbs = [e.get("verb") for e in json.loads(raw)["events"] if e.get("tool") == "Bash"]+ for _, verb in LEAKY_COMMANDS:+ assert verb in verbs, verb+++_TRICKY_COMMANDS = (+ *(c for c, _ in LEAKY_COMMANDS),+ "TOKEN=\"$(cat ~/.creds | jq -r '.a b')\" ./deploy.sh --env prod",+ "X='a;b && c' Y=\"d|e\" git push origin HEAD",+ "for f in $(ls 'my dir'); do B=\"x y\" python3 \"$f\"; done",+ "if [ \"$(git status --porcelain)\" ]; then MSG='wip stuff' git stash; fi",+ "OUT=`date +%s`; A=\"`whoami` here\" ls -la",+ "P=${HOME}/a\\ b/c; cat \"$P\"",+ "K=\"unterminated value with words",+ "sudo -u deploy env A='b c' timeout 30 pytest -q",+ "(cd 'some where' && N=\"q r\" make test)",+ "git commit -m \"$(cat <<'EOF'\nDon't leak this body\nEOF\n)\"",+)+++_QUOTED = r"'[^']*'|\"(?:\\.|[^\"\\])*\"|\$\((?:[^()]|\([^()]*\))*\)|`[^`]*`"+_VALUE_RE = re.compile(rf"\w+=(?:{_QUOTED}|[^\s;&|])*|{_QUOTED}")++[email protected]("cmd", _TRICKY_COMMANDS)+def test_shell_verb_never_contains_an_argument_value(cmd):+ verb = sm._shell_verb(cmd)+ assert sm._VERB_SHAPE.fullmatch(verb), verb+ if verb == "sh":+ return+ # Every verb word is a word written outside any quoted value, substitution or+ # assignment — never a piece of one.+ outside = {w.rsplit("/", 1)[-1].strip("();") for w in _VALUE_RE.sub(" ", cmd).split()}+ assert set(verb.split()) <= outside, (cmd, verb)+ for m in _VALUE_RE.finditer(cmd):+ for piece in re.split(r"[\s'\"`$()=;|&{}\\/]+", m.group(0)):+ if len(piece) >= 3 and piece not in outside:+ assert piece not in verb, (cmd, verb, piece)+++def test_commit_shas_are_never_file_paths(tmp_path):+ sha = "0123456789abcdef0123456789abcdef01234567"+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "app.py").write_text("x = 1\n")+ cwd = str(tmp_path)+ for cmd in (+ f"git show {sha}",+ f"git show {sha[:7]} -- src",+ # A merge-conflict marker inside a heredoc is not a redirect to a file.+ f"python3 - <<'EOF'\ns = s.index('>>>>>>> {sha}')\nEOF",+ ):+ _, paths, _, _ = sm.classify("Bash", {"command": cmd}, cwd)+ ops = sm.file_ops("Bash", {"command": cmd}, cwd)+ for p in [*paths, *ops]:+ assert sha[:7] not in p, (cmd, p)+ # Real paths still come through.+ _, paths, _, _ = sm.classify("Bash", {"command": f"git show {sha} -- src/app.py"}, cwd)+ assert paths == [str(tmp_path / "src" / "app.py")]+ assert sm.file_ops("Bash", {"command": "echo x > out.txt"}, cwd) == {str(tmp_path / "out.txt"): "create"}+ # `git rm` only takes file names, so a hex-named file is a real delete.+ assert sm.file_ops("Bash", {"command": f"git rm {sha[:12]}"}, cwd) == {str(tmp_path / sha[:12]): "delete"}+++def test_content_hash_ignores_cli_version(transcript):+ a = sm.build_claude_code_map(transcript, cli_version="1")+ b = sm.build_claude_code_map(transcript, cli_version="2")+ assert sm.content_hash(a) == sm.content_hash(b)+++def test_outside_repo_buckets():+ b = sm.MapBuilder()+ t = b.target("/tmp/claude-1000/x/y.html", "read")+ assert t == {"scope": "outside", "label": "/tmp (scratch)", "touch": "read"}+++def test_posix_paths_stay_absolute_where_the_os_disagrees(monkeypatch):+ # Python 3.13 on Windows: a path with no drive or UNC root is not absolute.+ monkeypatch.setattr(sm.os.path, "isabs", lambda p: p[1:3] == ":\\" or p.startswith("\\\\"))+ b = sm.MapBuilder()+ t = b.target("/tmp/claude-1000/x/y.html", "read")+ assert t == {"scope": "outside", "label": "/tmp (scratch)", "touch": "read"}+++# ---------------------------------------------------------------- heartbeat plan+def _gen(v):+ return lambda which, org, user: v+++++++++++++++# ---------------------------------------------------------------- signals (scope extension)+def _jsonl(path, rows):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("".join(json.dumps(r) + "\n" for r in rows))+ return path+++def test_error_taxonomy_retries_delays_and_compaction(tmp_path):+ ts = lambda s: f"2026-09-10T01:{s // 60:02d}:{s % 60:02d}Z" # noqa: E731++ def u(s, c, **k):+ return {"type": "user", "timestamp": ts(s), "message": {"role": "user", "content": c}, **k}++ def a(s, mid, content, **k):+ return {+ "type": "assistant",+ "timestamp": ts(s),+ "message": {+ "id": mid,+ "model": "claude-sonnet-5",+ "stop_reason": k.pop("stop", "tool_use"),+ "usage": {"input_tokens": 1, "cache_read_input_tokens": 1000, "output_tokens": 9},+ "content": content,+ },+ **k,+ }++ bash = lambda i: { # noqa: E731+ "type": "tool_use",+ "id": i,+ "name": "Bash",+ "input": {"command": "pytest -x"},+ } # noqa: E731+ rows = [+ u(0, "go"),+ a(+ 2,+ "m1",+ [+ {"type": "thinking", "thinking": "SECRET-THOUGHT"},+ {"type": "text", "text": "SECRET-REPLY"},+ bash("b1"),+ ],+ ),+ u(+ 40,+ [+ {+ "type": "tool_result",+ "tool_use_id": "b1",+ "content": "Exit code 2\nSECRET-TRACE",+ "is_error": True,+ }+ ],+ ),+ a(41, "m2", [bash("b2")]),+ u(45, [{"type": "tool_result", "tool_use_id": "b2", "content": "ok"}]),+ {+ "type": "assistant",+ "timestamp": ts(50),+ "isApiErrorMessage": True,+ "error": "rate_limit",+ "message": {+ "model": "<synthetic>",+ "content": [{"type": "text", "text": "SECRET-API"}],+ },+ },+ {+ "type": "attachment",+ "timestamp": ts(51),+ "uuid": "11111111-aaaa-bbbb-cccc-000000000001",+ "attachment": {+ "type": "hook_non_blocking_error",+ "hookName": "PostToolUse:Bash",+ "hookEvent": "PostToolUse",+ "toolUseID": "b1",+ "command": "SECRET-HOOK-CMD",+ "stderr": "SECRET-HOOK",+ },+ },+ {+ "type": "attachment",+ "timestamp": ts(51),+ "uuid": "11111111-aaaa-bbbb-cccc-000000000002",+ "attachment": {+ "type": "hook_blocking_error",+ "hookName": "Stop",+ "hookEvent": "Stop",+ "toolUseID": "turn-1",+ "blockingError": {"blockingError": "SECRET-BLOCK", "command": "SECRET-BLOCK-CMD"},+ },+ },+ {+ "type": "system",+ "subtype": "compact_boundary",+ "timestamp": ts(52),+ "compactMetadata": {+ "trigger": "auto",+ "preTokens": 900000,+ "postTokens": 20000,+ "durationMs": 9000,+ },+ },+ {+ "type": "system",+ "subtype": "model_refusal_fallback",+ "timestamp": ts(53),+ "direction": "retry",+ },+ u(54, "[Request interrupted by user]"),+ a(300, "m3", [{"type": "text", "text": "done"}], stop="end_turn"),+ ]+ doc = sm.build_claude_code_map(_jsonl(tmp_path / "p" / "s.jsonl", rows))+ evs = doc["events"]+ first, retry = [e for e in evs if e.get("tool") == "Bash"]+ assert first["err"] and first["errClass"] == "exit_code" and first["exitCode"] == 2+ assert retry["retryOf"] == first["seq"] and retry["attempt"] == 2 and not retry["err"]+ sig = {(e["source"], e["errClass"]) for e in evs if e["kind"] == "error"}+ assert sig == {+ ("llm", "rate_limit"),+ ("hook", "hook_error"),+ ("hook", "hook_blocking"),+ ("llm", "refusal_fallback"),+ ("orchestration", "interrupted"),+ }+ comp = next(e for e in evs if e["kind"] == "compaction")+ assert (comp["trigger"], comp["preTokens"], comp["postTokens"], comp["ms"]) == (+ "auto",+ 900000,+ 20000,+ 9000,+ )+ llm1 = next(e for e in evs if e["kind"] == "llm")+ assert (+ llm1["thinking"] is True+ and llm1["toolCalls"] == 1+ and llm1["textChars"] == len("SECRET-REPLY")+ )+ assert llm1["latency"] == 2000 and llm1["stop"] == "tool_use"+ delays = [e for e in evs if e["kind"] == "delay"]+ assert {d["cause"] for d in delays} >= {"tool", "llm"} # 38 s pytest, 246 s to the last reply+ t = doc["totals"]+ assert t["retries"] == 1 and t["compactions"] == 1 and t["errorsBySource"]["llm"] == 2+ assert t["errors"] == sum(t["errorsBySource"].values())+ hooks = {e["hook"]: e for e in evs if e.get("source") == "hook"}+ post, stop = hooks["PostToolUse:Bash"], hooks["Stop"]+ assert (post["hookEvent"], post["srcUuid"]) == ("PostToolUse", "11111111-aaaa-bbbb-cccc-000000000001")+ assert post["ref"] == first["seq"] # the failed Bash call that triggered it+ assert (stop["hookEvent"], stop["srcUuid"]) == ("Stop", "11111111-aaaa-bbbb-cccc-000000000002")+ assert "ref" not in stop # a turn id, not one of our tool events+ raw = json.dumps(doc)+ for secret in (+ "SECRET-THOUGHT",+ "SECRET-REPLY",+ "SECRET-TRACE",+ "SECRET-API",+ "SECRET-HOOK",+ "SECRET-BLOCK",+ ):+ assert secret not in raw, secret+++def test_tool_without_result_is_flagged(tmp_path):+ rows = [+ {+ "type": "assistant",+ "timestamp": "2026-09-10T01:00:00Z",+ "message": {+ "id": "m",+ "model": "claude-sonnet-5",+ "usage": {"output_tokens": 1},+ "content": [+ {+ "type": "tool_use",+ "id": "t",+ "name": "Bash",+ "input": {"command": "sleep 999"},+ }+ ],+ },+ }+ ]+ doc = sm.build_claude_code_map(_jsonl(tmp_path / "q" / "s.jsonl", rows))+ ev = next(e for e in doc["events"] if e.get("tool") == "Bash")+ assert ev["err"] and ev["errClass"] == "no_result"+++ ("text", "cls", "code"),+ [+ ("Exit code 137", "exit_code", 137),+ ("<tool_use_error>InputValidationError: x", "validation", None),+ ("The user doesn't want to proceed", "permission_denied", None),+ ("Command timed out", "timeout", None),+ ("claude-opus-5 is temporarily unavailable", "model_unavailable", None),+ ("weird", "other", None),+ ],+)+def test_classify_tool_error(text, cls, code):+ assert sm.classify_tool_error(text) == (cls, code)+++# ---------------------------------------------------------------- misc detection+ ("cmd", "kind"),+ [+ ("pytest -q", "verify"),+ ("uv run pytest tests/", "verify"),+ ("python -m pytest -x", "verify"),+ (".venv/bin/pytest", "verify"),+ ("cd /x && FOO=1 npm test", "verify"),+ ("timeout 300 cargo test", "verify"),+ ("uvx ruff check src", "verify"),+ ("echo pytest", "exec"),+ ('git commit -m "run pytest; ruff"', "exec"),+ ("git commit -m 'fix pytest'", "exec"),+ ("grep -r pytest .", "search"),+ ],+)+def test_verify_only_matches_the_command_word(cmd, kind):+ assert sm.classify("Bash", {"command": cmd}, None)[0] == kind+++def test_repo_dot_claude_stays_repo_relative(tmp_path, fake_home):+ repo = tmp_path / "work" / "svc"+ (repo / ".git").mkdir(parents=True)+ (repo / ".claude").mkdir()+ (repo / ".claude" / "rules.md").write_text("x")+ b = sm.MapBuilder()+ t = b.target(str(repo / ".claude" / "rules.md"), "read")+ assert "file" in t and b.files[t["_key"]]["path"] == ".claude/rules.md"+ home_t = b.target(str(fake_home / ".claude" / "skills" / "x" / "SKILL.md"), "read")+ assert home_t["scope"] == "outside" and "file" not in home_t+++ ("url", "host"),+ [+ ("https://SECRET:[email protected]:8443/x?q=1#f", "api.example.com"),+ ("https://[email protected]/x", "api.example.com"),+ ("http://docs.python.org/3/", "docs.python.org"),+ ("how to parse urls", "search"),+ ("https://[::1", "search"),+ ],+)+def test_web_host_never_carries_credentials(url, host):+ b = sm.MapBuilder()+ ev = b.tool_event(tool="WebFetch", inp={"url": url}, cwd=None, agent="main", ts=1.0)+ assert ev["host"] == host and "SECRET" not in json.dumps(ev)+++def test_derived_delays_respect_max_events(monkeypatch):+ monkeypatch.setattr(sm, "MAX_EVENTS", 10)+ b = sm.MapBuilder()+ for i in range(10):+ ev = b.tool_event(+ tool="Bash", inp={"command": "make"}, cwd=None, agent="main", ts=100.0 * i+ )+ ev["dur"] = sm.TOOL_DELAY_MS * 2+ doc = b.finish(session={"id": "s", "agentTool": "claude-code"})+ assert len(doc["events"]) == 10+ assert doc["session"]["truncated"] is True+ assert all(e["kind"] != "delay" or isinstance(e.get("ref"), int) for e in doc["events"])+++def _span(span_id, name, start, end=None, parent=None, **attrs):+ return SimpleNamespace(+ span_id=span_id,+ name=name,+ start_time=start,+ end_time=end,+ parent_id=parent,+ status_code="OK",+ attributes=attrs,+ )+++def test_spans_zero_usage_turn_counts_and_tool_duration():+ from datetime import UTC, datetime, timedelta++ t0 = datetime(2026, 9, 10, 1, 0, tzinfo=UTC)+ spans = [+ _span("t1", "Turn 1", t0, **{"llm.model_name": "cursor-fast"}),+ _span(+ "c1",+ "Shell",+ t0 + timedelta(seconds=1),+ t0 + timedelta(seconds=1 + sm.TOOL_DELAY_MS / 1000 * 2),+ parent="t1",+ **{"tool.name": "Bash", "input.value": json.dumps({"command": "make"})},+ ),+ ]+ doc = sm.build_map_from_spans(spans, session_id="local:cursor:x", agent_tool="cursor")+ assert doc["totals"]["requests"] == 1+ llm = next(e for e in doc["events"] if e["kind"] == "llm")+ assert (llm["in"], llm["out"], llm["model"]) == (0, 0, "cursor-fast")+ tool = next(e for e in doc["events"] if e.get("tool") == "Bash")+ assert tool["dur"] == sm.TOOL_DELAY_MS * 2+ assert any(e["kind"] == "delay" and e.get("cause") == "tool" for e in doc["events"])+++def test_spans_all_untimestamped_falls_back_to_started_at_hint():+ """A tiny Cursor/Codex session where no span carries a timestamp (for example a+ 3-event Cursor session) must still get a real+ ``startedAt``. Without one the map has no start time, even though the+ build itself "succeeded"."""+ spans = [+ _span("t1", "Turn 1", None, **{"llm.model_name": "default"}),+ _span("c1", "Shell", None, None, parent="t1", **{"tool.name": "Bash", "input.value": "{}"}),+ ]+ hint = 1_757_000_000.0 # arbitrary fixed epoch seconds, stands in for the source file's mtime+ doc = sm.build_map_from_spans(+ spans, session_id="local:cursor:x", agent_tool="cursor", started_at_hint=hint+ )+ assert doc["session"]["startedAt"] == sm._iso(hint)+ # Without the hint the old (broken) behaviour is preserved — never silently+ # invent a timestamp when nothing at all is known about when this happened.+ doc_no_hint = sm.build_map_from_spans(spans, session_id="local:cursor:y", agent_tool="cursor")+ assert doc_no_hint["session"]["startedAt"] is None+++++++++++++++def test_estimate_cost_applies_the_long_context_tier_per_request():+ # gpt-6-luna: $0.10 in / $0.50 out / $0.01 read / $0.125 write per 1M;+ # >272K cache-inclusive input bills the WHOLE request at 2x in, 1.5x out.+ at_threshold = sm.estimate_cost_usd("gpt-6-luna", 272_000, 0, 0, 1_000_000)+ assert at_threshold == pytest.approx(0.0272 + 0.5)++ long = sm.estimate_cost_usd("gpt-6-luna", 200_000, 50_000, 30_000, 1_000_000)+ # input 200K*0.20 + write 50K*0.25 + read 30K*0.02 + out 1M*0.75, per 1M+ assert long == pytest.approx(0.04 + 0.0125 + 0.0006 + 0.75)++ # A card without a long-context tier keeps its base rates at any size.+ assert sm.estimate_cost_usd("gpt-5.6-luna", 400_000, 0, 0, 0) == pytest.approx(0.08)+++def test_a_turn_aggregate_is_not_billed_at_the_long_context_tier():+ # Two 200K gpt-6-luna requests in one turn: each is below 272K, so neither+ # is long-context -- the 400K turn sum must not trip the tier (review finding).+ events = [+ {"model": "gpt-6-luna", "input_tokens": 200_000, "output_tokens": 0},+ {"model": "gpt-6-luna", "input_tokens": 200_000, "output_tokens": 0},+ ]+ assert sm._cost_from_events("gpt-6-luna", events) == pytest.approx(0.04)+ # Without per-request events, an aggregate is priced at base rates.+ assert sm.estimate_cost_usd(+ "gpt-6-luna", 400_000, 0, 0, 0, single_request=False+ ) == pytest.approx(0.04)+ # One genuinely long request inside the turn still gets the tier.+ events.append({"model": "gpt-6-luna", "input_tokens": 300_000, "output_tokens": 0})+ assert sm._cost_from_events("gpt-6-luna", events) == pytest.approx(0.04 + 0.06)+++++++++ ("cmd", "verb"),+ [+ ("for a in 1; do " * 5 + "pytest; " + "done; " * 5, "for"), # deeper than the walk: no crash+ ("cd a; " * 8 + "pytest -q", "pytest"), # the walk's last step still reaches the command+ ("A=1; " * 3 + "cd x && make test", "make test"),+ ],+)+def test_shell_verb_survives_deep_nesting_and_long_setup(cmd, verb):+ assert sm._shell_verb(cmd) == verb+++def test_hex_named_files_are_still_file_operations():+ ops = sm.file_ops("Bash", {"command": "rm deadbeef1 && echo x > cafe1234"}, "/repo")+ assert ops.get(os.path.normpath("/repo/deadbeef1")) == "delete"+ assert ops.get(os.path.normpath("/repo/cafe1234")) == "create"diff --git a/python/tests/test_builder_pr_outcome.py b/python/tests/test_builder_pr_outcome.pynew file mode 100644index 0000000..eee43b8--- /dev/null+++ b/python/tests/test_builder_pr_outcome.py@@ -0,0 +1,536 @@+"""Tests for PR-creation / outcome / tool-category / file-op detection in builder.py.++Scope: gh/glab/GitHub-API/MCP PR creation detection (URL-+confirmed only), a closed-vocabulary tool-call category per event, file create/modify/+delete/rename detection, and a per-agent/session outcome label.+"""++from __future__ import annotations++import json++import pytest++from agentplay import builder as sm+++def _line(**d):+ return json.dumps(d) + "\n"+++def _repo(tmp_path, name="backend", remote="acme/backend"):+ repo = tmp_path / "work" / name+ (repo / ".git").mkdir(parents=True)+ (repo / ".git" / "config").write_text(+ f'[remote "origin"]\n\turl = [email protected]:{remote}.git\n'+ )+ return repo+++def _bash(seq_id, ts, cwd, command, result, *, is_error=False):+ return [+ _line(+ type="assistant",+ timestamp=ts[0],+ cwd=cwd,+ message={+ "id": "m" + seq_id,+ "model": "claude-sonnet-5",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ "content": [+ {+ "type": "tool_use",+ "id": "t" + seq_id,+ "name": "Bash",+ "input": {"command": command},+ }+ ],+ },+ ),+ _line(+ type="user",+ timestamp=ts[1],+ cwd=cwd,+ message={+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "t" + seq_id,+ "content": result,+ "is_error": is_error,+ }+ ],+ },+ ),+ ]+++def _write_session(tmp_path, lines, name="s"):+ path = tmp_path / "proj" / f"{name}.jsonl"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("".join(line for group in lines for line in group))+ return path+++# ---------------------------------------------------------------- PR creation+def test_successful_pr_create_resolves_from_url(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = [+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:02Z"),+ cwd,+ "gh pr create --repo acme/backend --base main --head feat/x "+ '--title "feat: add the thing" --body "## Why\\n\\nBecause it helps.\\n\\n- point one\\n- point two"',+ "https://github.com/acme/backend/pull/101",+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ ev = next(e for e in doc["events"] if e.get("vcs", {}).get("action") == "pr_create")+ assert ev["vcs"] == {+ "provider": "github",+ "action": "pr_create",+ "repo": "acme/backend",+ "number": 101,+ }+ assert doc["prs"] == [+ {+ "provider": "github",+ "repo": "acme/backend",+ "number": 101,+ "url": "https://github.com/acme/backend/pull/101",+ "seq": ev["seq"],+ "state": "open",+ }+ ]+ assert doc["totals"]["prsCreated"] == 1+ assert doc["session"]["outcome"] == "pr_created"+++def test_failed_pr_create_is_not_counted_as_created(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = [+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:02Z"),+ cwd,+ 'gh pr create --repo acme/backend --title "x" --body "some free text with a 1 in it"',+ "pull request create failed: GraphQL: already exists",+ is_error=True,+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ ev = next(e for e in doc["events"] if e.get("vcs"))+ assert ev["vcs"]["action"] == "pr_create_failed"+ assert doc["prs"] == [] and doc["totals"]["prsCreated"] == 0+ assert doc["session"]["outcome"] != "pr_created"+++def test_pr_create_with_no_url_in_output_is_an_attempt_not_a_success(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = [+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:02Z"),+ cwd,+ 'gh pr create --repo acme/backend --title "x" --body "free text mentioning 5 things"',+ "Opening in your browser.",+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ ev = next(e for e in doc["events"] if e.get("vcs"))+ assert ev["vcs"]["action"] == "pr_create_attempt"+ assert doc["prs"] == []+++def test_ordinary_gh_pr_commands_never_read_as_create(tmp_path):+ """A generic noun/verb pair like ('pr','create') from vcs_action must not leak the+ literal sentinel 'pr_create' when pr_create_intent finds no create shape at all —+ regression for the collision between the generic label and the resolved-PR marker."""+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = (+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:02Z"),+ cwd,+ "gh pr view 101",+ '{"state":"OPEN"}',+ )+ + _bash(+ "2",+ ("2026-09-10T01:00:03Z", "2026-09-10T01:00:04Z"),+ cwd,+ "gh pr checks 101",+ "all pass",+ )+ + _bash(+ "3",+ ("2026-09-10T01:00:05Z", "2026-09-10T01:00:06Z"),+ cwd,+ "gh pr merge 101 --merge",+ "Merged",+ )+ )+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ actions = [e["vcs"]["action"] for e in doc["events"] if e.get("vcs")]+ assert actions == ["pr_view", "pr_checks", "pr_merge"]+ assert all(e["vcs"].get("number") == 101 for e in doc["events"] if e.get("vcs"))+ assert "pr_create" not in actions+++def test_interrupted_pr_create_never_got_a_result(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = [+ _line(+ type="assistant",+ timestamp="2026-09-10T01:00:00Z",+ cwd=cwd,+ message={+ "id": "m1",+ "model": "claude-sonnet-5",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ "content": [+ {+ "type": "tool_use",+ "id": "t1",+ "name": "Bash",+ "input": {+ "command": 'gh pr create --repo acme/backend --title "x" --body "y"'+ },+ }+ ],+ },+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ ev = next(e for e in doc["events"] if e.get("tool") == "Bash")+ assert ev["err"] is True and ev["errClass"] == "no_result"+ assert ev["vcs"]["action"] == "pr_create_failed"+ assert doc["prs"] == []+++def test_bitbucket_and_gitlab_create_detected_by_shape(tmp_path):+ repo = _repo(tmp_path, "svc", "myorg/svc")+ cwd = str(repo)+ lines = _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:02Z"),+ cwd,+ "glab mr create --title x --description y",+ "https://gitlab.com/myorg/svc/-/merge_requests/12",+ ) + _bash(+ "2",+ ("2026-09-10T01:00:03Z", "2026-09-10T01:00:04Z"),+ cwd,+ "bb pr create --title x",+ "https://bitbucket.org/myorg/svc/pull-requests/7",+ )+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ assert {(p["provider"], p["number"]) for p in doc["prs"]} == {("gitlab", 12), ("bitbucket", 7)}+++def test_mcp_pr_tool_sets_vcs_category(tmp_path):+ cwd = str(_repo(tmp_path))+ lines = [+ _line(+ type="assistant",+ timestamp="2026-09-10T01:00:00Z",+ cwd=cwd,+ message={+ "id": "m1",+ "model": "claude-sonnet-5",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ "content": [+ {+ "type": "tool_use",+ "id": "t1",+ "name": "mcp__github__create_pull_request",+ "input": {"owner": "acme", "repo": "backend", "title": "x"},+ }+ ],+ },+ ),+ _line(+ type="user",+ timestamp="2026-09-10T01:00:02Z",+ cwd=cwd,+ message={+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "t1",+ "content": "https://github.com/acme/backend/pull/102",+ }+ ],+ },+ ),+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ ev = next(e for e in doc["events"] if e["kind"] == "mcp")+ assert ev["cat"] == "vcs" and ev["vcs"]["action"] == "pr_create" and ev["vcs"]["number"] == 102+++# ---------------------------------------------------------------- shell verbs+ ("command", "verb"),+ [+ # Setup prefixes hand the verb to what follows, through any sequence operator.+ ("cd /x && make setup", "make setup"),+ ("cd /x; make setup", "make setup"),+ ("export AGENTPLAY_HOME=/x && python -m agentplay build", "python"),+ ("export FOO=1; pytest -q", "pytest"),+ ("cd /x && export Y=1 && pnpm dev", "pnpm dev"),+ # A newline sequences commands just as `;` does.+ ("cd /x\nmake setup", "make setup"),+ ("cd /x\nexport Y=1\npnpm dev", "pnpm dev"),+ # Shell keywords are not commands; the body's verb is. `do`/`then` may follow+ # a `;` or a newline, and blocks nest.+ ("for i in $(seq 1 60); do curl -s x; done", "curl"),+ ("if [ -f x ]; then rm x; fi", "rm"),+ ("for i in 1 2 3\ndo\n curl x\ndone", "curl"),+ ("for i in 1 2; do if [ -f x ]; then echo up; fi; done", "echo"),+ # `$(...)` and backticks run their own commands; their words aren't this verb.+ ('P=$(uv tool dir)/agentplay; find $P -name "*.py"', "find"),+ ("M=$(ls /x | head -1)\npython3 -c 'import json'", "python3"),+ ("D=`date`; echo $D", "echo"),+ # A pipe is not a sequence: the head still owns the verb.+ ("cat x | grep y", "cat"),+ # A separator inside quotes belongs to an argument, not to the shell. Splitting+ # on it hands the verb to a fragment of that argument — here, of a path.+ ('cd "/private;token" && pytest', "pytest"),+ ("cd '/private;token' && pytest", "pytest"),+ ("cd /x; echo 'a&&b'", "echo"),+ ("cd /x\\;token && pytest", "pytest"), # a backslash quotes the next character+ # Same rule for the `do`/`then` that opens a block body.+ ('if [ -f "a;then token" ]; then pytest -q; fi', "pytest"),+ ("for i in 'a;do token'; do curl -s x; done", "curl"),+ # Unchanged behaviour.+ ("pytest -q", "pytest"),+ ("AGENTPLAY_HOME=/x pytest -q", "pytest"),+ ("git status", "git status"),+ ("cd /x", "cd"),+ ("export FOO=1", "export"),+ ],+)+def test_shell_verb_skips_setup_prefixes_and_block_keywords(command, verb):+ assert sm._shell_verb(command) == verb+++# ---------------------------------------------------------------- tool categories+ ("command", "cat"),+ [+ ("pytest -x tests/", "test"),+ # `_VERIFY_RE` (the base classifier, unchanged) buckets test/build/lint together as+ # kind="verify" — CAT labels that bucket "Test / verify", so a build lands there too.+ ("npm run build", "test"),+ ("npm install", "package"),+ ("aws s3 ls", "cloud"),+ ("curl -s https://x", "http"),+ ("rm -rf build/", "fs"),+ ("cat README.md", "file"),+ ("echo hi", "shell"),+ ("git status", "vcs"),+ ],+)+def test_tool_category_from_shell_verb(command, cat):+ kind, paths, touch, verb = sm.classify("Bash", {"command": command}, "/tmp")+ ev = {"kind": kind, "tool": "Bash", "verb": verb}+ assert sm.tool_category(ev) == cat+++def test_tool_category_mcp_vcs_vs_other():+ assert sm.tool_category({"kind": "mcp", "server": "github"}) == "vcs"+ assert sm.tool_category({"kind": "mcp", "server": "claude-in-chrome"}) == "mcp"+++# ---------------------------------------------------------------- file ops+def test_write_to_new_path_is_create_existing_path_is_modify(tmp_path):+ repo = _repo(tmp_path)+ existing = repo / "README.md"+ existing.write_text("hi\n")+ cwd = str(repo)+ lines = [+ _line(+ type="assistant",+ timestamp="2026-09-10T01:00:00Z",+ cwd=cwd,+ message={+ "id": "m1",+ "model": "claude-sonnet-5",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ "content": [+ {+ "type": "tool_use",+ "id": "t1",+ "name": "Write",+ "input": {"file_path": str(repo / "new_file.py"), "content": "x"},+ },+ {+ "type": "tool_use",+ "id": "t2",+ "name": "Write",+ "input": {"file_path": str(existing), "content": "y"},+ },+ ],+ },+ ),+ _line(+ type="user",+ timestamp="2026-09-10T01:00:01Z",+ cwd=cwd,+ message={+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "t1", "content": "ok"},+ {"type": "tool_result", "tool_use_id": "t2", "content": "ok"},+ ],+ },+ ),+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ by_path = {f["path"]: f["op"] for f in doc["files"]}+ assert by_path["new_file.py"] == "create" and by_path["README.md"] == "modify"+ assert doc["totals"]["filesCreated"] == 1 and doc["totals"]["filesDeleted"] == 0+++def test_shell_rm_mv_touch_detected(tmp_path):+ repo = _repo(tmp_path)+ (repo / "old.py").write_text("x\n")+ cwd = str(repo)+ lines = [+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:01Z"),+ cwd,+ "mv old.py new.py && touch fresh.py && rm stale.py",+ "",+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ by_path = {f["path"]: f["op"] for f in doc["files"]}+ assert by_path["old.py"] == "rename-from" and by_path["new.py"] == "rename-to"+ assert by_path["fresh.py"] == "create" and by_path["stale.py"] == "delete"+++def test_apply_patch_add_delete_update(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ patch = (+ f"*** Add File: {repo}/a.py\n+x\n"+ f"*** Delete File: {repo}/b.py\n"+ f"*** Update File: {repo}/c.py\n-x\n+y\n"+ )+ lines = [+ _line(+ type="assistant",+ timestamp="2026-09-10T01:00:00Z",+ cwd=cwd,+ message={+ "id": "m1",+ "model": "claude-sonnet-5",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ "content": [+ {+ "type": "tool_use",+ "id": "t1",+ "name": "apply_patch",+ "input": {"input": patch},+ }+ ],+ },+ ),+ _line(+ type="user",+ timestamp="2026-09-10T01:00:01Z",+ cwd=cwd,+ message={+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "applied"}],+ },+ ),+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ by_path = {f["path"]: f["op"] for f in doc["files"]}+ assert by_path == {"a.py": "create", "b.py": "delete", "c.py": "modify"}+++def test_shell_redirect_creates_file_but_numeric_comparison_does_not(tmp_path):+ """`> 1` inside a numeric/string test (`[ "$rc" > 1 ]`) must never be read as a+ redirect to a file literally named '1' — the two are only distinguishable by this+ kind of conservative guard, not by the redirect grammar alone."""+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = [+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:01Z"),+ cwd,+ 'echo hi > out.log\nrc=$?\nif [ "$rc" > 1 ]; then\n echo bad\nfi',+ "",+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ paths = {f["path"] for f in doc["files"]}+ assert "out.log" in paths+ assert "1" not in paths+++def test_fstring_alignment_spec_not_read_as_redirect(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = [+ _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:01Z"),+ cwd,+ "python3 -c \"print(f'{x:>7.0f} rows')\"",+ " 12 rows",+ )+ ]+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ assert doc["files"] == []+++# ---------------------------------------------------------------- outcome+def test_outcome_verified_when_last_verify_has_no_later_edit(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = _bash(+ "1", ("2026-09-10T01:00:00Z", "2026-09-10T01:00:01Z"), cwd, "pytest -q", "12 passed"+ )+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ assert doc["session"]["outcome"] == "verified"+++def test_outcome_unresolved_errors_when_session_ends_on_failures(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ lines = _bash(+ "1",+ ("2026-09-10T01:00:00Z", "2026-09-10T01:00:01Z"),+ cwd,+ "pytest -q",+ "3 failed",+ is_error=True,+ ) + _bash(+ "2",+ ("2026-09-10T01:00:02Z", "2026-09-10T01:00:03Z"),+ cwd,+ "pytest -q -k thing",+ "1 failed",+ is_error=True,+ )+ doc = sm.build_claude_code_map(_write_session(tmp_path, lines))+ assert doc["session"]["outcome"] == "unresolved_errors"+++def test_outcome_incomplete_on_empty_session():+ assert sm.classify_outcome([], "") == "incomplete"diff --git a/python/tests/test_builder_stage2.py b/python/tests/test_builder_stage2.pynew file mode 100644index 0000000..d632d35--- /dev/null+++ b/python/tests/test_builder_stage2.py@@ -0,0 +1,768 @@+"""Builder: outputs, models, tasks, roles,+Cursor/Codex coverage and worker hardening.++Golden fixtures per harness (Claude Code JSONL + subagent file, Codex spans incl. code+mode and a spawned child, Cursor spans) carry every one of these signals plus the negative+cases that must NOT produce an output (failed commit, un-mergeable PR, errored ticket+call, errored artifact publish).+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta+from pathlib import Path+from types import SimpleNamespace++import pytest++from agentplay import builder as sm+++# ---------------------------------------------------------------- helpers+def _line(**d):+ return json.dumps(d) + "\n"+++def fake_home(tmp_path, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HOME", str(home))+ # Windows expands ~ from USERPROFILE, and VS Code paths from APPDATA.+ monkeypatch.setenv("USERPROFILE", str(home))+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ return home+++def _repo(tmp_path, name="dashboard", remote="acme/dashboard"):+ repo = tmp_path / "work" / name+ (repo / ".git").mkdir(parents=True)+ (repo / ".git" / "config").write_text(+ f'[remote "origin"]\n\turl = [email protected]:{remote}.git\n'+ )+ return repo+++def _ts(sec: float) -> str:+ return (datetime(2026, 9, 23, 15, 44, tzinfo=UTC) + timedelta(seconds=sec)).strftime(+ "%Y-%m-%dT%H:%M:%S.%f"+ )[:-3] + "Z"+++def _call(i, sec, cwd, name, inp, result, *, is_error=False, model="claude-opus-5-5"):+ return [+ _line(+ type="assistant",+ timestamp=_ts(sec),+ cwd=cwd,+ message={+ "id": f"m{i}",+ "model": model,+ "usage": {"input_tokens": 10, "output_tokens": 5},+ "content": [{"type": "tool_use", "id": f"t{i}", "name": name, "input": inp}],+ },+ ),+ _line(+ type="user",+ timestamp=_ts(sec + 1),+ cwd=cwd,+ message={+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": f"t{i}",+ "content": result,+ "is_error": is_error,+ }+ ],+ },+ ),+ ]+++def _prompt(sec, cwd, text, images=0):+ content = [{"type": "text", "text": text}] + [+ {"type": "image", "source": {"type": "base64", "data": "x"}} for _ in range(images)+ ]+ return [+ _line(+ type="user",+ timestamp=_ts(sec),+ cwd=cwd,+ message={"role": "user", "content": content},+ )+ ]+++def _write(tmp_path, groups, name="s"):+ path = tmp_path / "proj" / f"{name}.jsonl"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("".join(line for g in groups for line in g))+ return path+++def _kinds(doc, kind):+ return [e for e in doc["events"] if e["kind"] == kind]+++# ---------------------------------------------------------------- Claude Code golden+def claude_doc(tmp_path, fake_home):+ repo = _repo(tmp_path)+ cwd = str(repo)+ skills = fake_home / ".claude" / "skills"+ (skills / "old-skill").mkdir(parents=True)+ (skills / "old-skill" / "SKILL.md").write_text("x")+ page = tmp_path / "page.html"+ page.write_text("<html>" + "x" * 994 + "</html>") # 1007 bytes+ groups = [+ _prompt(0, cwd, "look at https://app.example.com/x and https://github.com/a/b", images=1),+ # commit: confirmed, then failed (nothing to commit), then errored+ _call(+ 1,+ 5,+ cwd,+ "Bash",+ {"command": f"cd {cwd} && git add -A && git commit -m 'fix csp'"},+ "[main 75f3d6d9a] fix csp\n 2 files changed, 10 insertions(+), 3 deletions(-)",+ ),+ _call(+ 2,+ 10,+ cwd,+ "Bash",+ {"command": "git commit -m x"},+ "nothing to commit, working tree clean",+ ),+ _call(+ 3,+ 15,+ cwd,+ "Bash",+ {"command": "git commit -m y"},+ "Exit code 1\nhook failed",+ is_error=True,+ ),+ # PR create → merge (confirmed) + a refused merge + a comment+ _call(+ 4,+ 20,+ cwd,+ "Bash",+ {"command": "gh pr create --title t --body b"},+ "https://github.com/acme/dashboard/pull/102",+ ),+ _prompt(30, cwd, "merge it"),+ _call(+ 5,+ 35,+ cwd,+ "Bash",+ {"command": "gh pr merge 3890 --squash"},+ "X Pull request acme/dashboard#3890 is not mergeable: the base branch policy prohibits the merge.",+ ),+ _call(+ 6,+ 40,+ cwd,+ "Bash",+ {"command": "gh pr merge 102 --squash --delete-branch --admin"},+ "✓ Squashed and merged pull request acme/dashboard#102 (fix csp)",+ ),+ _call(+ 7,+ 45,+ cwd,+ "Bash",+ {"command": "gh pr comment 102 --body 'thanks'"},+ "https://github.com/acme/dashboard/pull/102#issuecomment-1234",+ ),+ _call(+ 8,+ 47,+ cwd,+ "Bash",+ {"command": "gh pr merge 102 --auto --squash"},+ "! Pull request acme/dashboard#102 will be automatically merged via squash when all requirements are met",+ ),+ # tickets: create (confirmed), update (confirmed), create that errored in its result+ _call(+ 9,+ 50,+ cwd,+ "mcp__claude_ai_Linear__save_issue",+ {"team": "ENT", "title": "t"},+ json.dumps({"id": "ACME-4787", "title": "t"}),+ ),+ _call(+ 10,+ 55,+ cwd,+ "mcp__claude_ai_Linear__save_issue",+ {"id": "ACME-4787", "state": "Done"},+ json.dumps({"id": "ACME-4787", "state": "Done"}),+ ),+ _call(+ 11,+ 60,+ cwd,+ "mcp__claude_ai_Linear__save_issue",+ {"team": "Nope", "title": "t"},+ 'Error: Could not find team "Nope"',+ ),+ _call(+ 12,+ 62,+ cwd,+ "mcp__claude_ai_Linear__get_issue",+ {"id": "ACME-1"},+ json.dumps({"id": "ACME-1"}),+ ),+ # artifact publish: confirmed, and an errored one+ _call(+ 13,+ 65,+ cwd,+ "Artifact",+ {"file_path": str(page)},+ "Published page.html at https://claude.ai/artifact/AbCdEf0123456789xyz (Version 3)",+ ),+ _call(14, 70, cwd, "Artifact", {"file_path": str(page)}, "publish failed", is_error=True),+ _call(+ 15,+ 72,+ cwd,+ "Artifact",+ {"action": "read", "url": "https://claude.ai/artifact/x"},+ "https://claude.ai/artifact/x",+ ),+ # skills: create a new one, update an existing one+ _call(+ 16,+ 75,+ cwd,+ "Write",+ {"file_path": str(skills / "new-skill" / "SKILL.md"), "content": "x"},+ "File created",+ ),+ _call(+ 17,+ 80,+ cwd,+ "Edit",+ {+ "file_path": str(skills / "old-skill" / "SKILL.md"),+ "old_string": "x",+ "new_string": "y",+ },+ "ok",+ ),+ # model switch on the main agent+ _call(18, 90, cwd, "Bash", {"command": "ls"}, "a", model="claude-sonnet-5"),+ ]+ path = _write(tmp_path, groups)+ return sm.build_claude_code_map(path)+++def test_claude_commit_confirmed_only(claude_doc):+ commits = _kinds(claude_doc, "commit")+ assert len(commits) == 1+ c = commits[0]+ assert (c["sha"], c["files"], c["ins"], c["del"], c["repo"]) == (+ "75f3d6d9a",+ 2,+ 10,+ 3,+ "dashboard",+ )+ assert claude_doc["events"][c["ref"]]["tool"] == "Bash"+ assert claude_doc["totals"]["commits"] == 1+++def test_claude_pr_merge_state_and_comment(claude_doc):+ merges = _kinds(claude_doc, "pr_merge")+ assert [(m.get("repo"), m.get("number")) for m in merges] == [("acme/dashboard", 102)]+ assert claude_doc["prs"][0]["state"] == "merged"+ assert [c.get("number") for c in _kinds(claude_doc, "pr_comment")] == [102]+ t = claude_doc["totals"]+ assert (t["prsCreated"], t["prsMerged"], t["prsClosed"], t["prComments"]) == (1, 1, 0, 1)+++def test_claude_tickets_create_update_and_errors_dropped(claude_doc):+ tickets = _kinds(claude_doc, "ticket")+ assert [(t["tracker"], t["action"], t.get("id")) for t in tickets] == [+ ("linear", "create", "ACME-4787"),+ ("linear", "update", "ACME-4787"),+ ]+ assert claude_doc["totals"]["ticketsCreated"] == 1+ assert claude_doc["totals"]["ticketsUpdated"] == 1+++def test_claude_artifact_publish_confirmed_with_size_and_version(claude_doc):+ arts = _kinds(claude_doc, "artifact")+ assert len(arts) == 1+ assert (arts[0]["bytes"], arts[0]["version"]) == (1007, 3)+++def test_claude_skill_writes(claude_doc):+ got = [(s["name"], s["action"]) for s in _kinds(claude_doc, "skill_write")]+ assert got == [("new-skill", "create"), ("old-skill", "update")]+ t = claude_doc["totals"]+ assert (t["skillsCreated"], t["skillsUpdated"]) == (1, 1)+++def test_claude_models_on_every_event_and_switch(claude_doc):+ assert all(e.get("model") for e in claude_doc["events"])+ sw = _kinds(claude_doc, "model_switch")+ assert [(s["from"], s["to"]) for s in sw] == [("claude-opus-5-5", "claude-sonnet-5")]+ assert claude_doc["totals"]["modelSwitches"] == 1+++def test_claude_prompt_counts_never_text(claude_doc):+ u = _kinds(claude_doc, "user")[0]+ assert (u["images"], u["urls"]) == (1, 2)+ raw = json.dumps(claude_doc)+ assert "app.example.com" not in raw and "fix csp" not in raw and "thanks" not in raw+ assert claude_doc["totals"]["promptImages"] == 1+++def test_claude_tasks_fallback_one_per_prompt(claude_doc):+ tasks = claude_doc["tasks"]+ assert [t["n"] for t in tasks] == [1, 2]+ assert all(t["source"] == "turns" for t in tasks)+ assert tasks[0]["startSeq"] == 0 and tasks[-1]["endSeq"] == len(claude_doc["events"]) - 1+ assert {e["task"] for e in claude_doc["events"]} == {1, 2}+ merge = _kinds(claude_doc, "pr_merge")[0]+ assert merge["task"] == 2+ assert claude_doc["totals"]["tasks"] == 2+++def test_claude_role_and_summary(claude_doc):+ assert claude_doc["session"]["role"] == "root"+ s = sm.summary(claude_doc)+ assert s["role"] == "root" and s["tasks"] == 2+ assert s["outputs"]["prsMerged"] == 1 and s["outputs"]["commits"] == 1+ assert s["prs"] == [+ {+ "repo": "acme/dashboard",+ "number": 102,+ "url": "https://github.com/acme/dashboard/pull/102",+ "state": "merged",+ }+ ]+ assert json.dumps(s) # serializable+++def test_no_private_keys_leak(claude_doc):+ for e in claude_doc["events"]:+ assert not [k for k in e if k.startswith("_")], e+++def test_claude_tasks_from_segmentation_cache(tmp_path, fake_home):+ repo = _repo(tmp_path)+ cwd = str(repo)+ groups = [+ _prompt(0, cwd, "a"),+ _call(1, 5, cwd, "Bash", {"command": "ls"}, "x"),+ _prompt(10, cwd, "b"),+ _call(2, 15, cwd, "Bash", {"command": "ls"}, "x"),+ _prompt(20, cwd, "c"),+ _call(3, 25, cwd, "Bash", {"command": "ls"}, "x"),+ ]+ path = _write(tmp_path, groups)+ tasks = [+ {"n": 1, "name": "Diagnose", "startAt": _ts(0), "firstTurn": 1, "lastTurn": 2},+ {"n": 2, "name": "Fix", "startAt": _ts(20), "firstTurn": 3, "lastTurn": 3},+ ]+ doc = sm.build_claude_code_map(path, tasks=tasks)+ got = [(t["n"], t["name"], t["source"], t["firstTurn"], t["lastTurn"]) for t in doc["tasks"]]+ assert got == [(1, "Diagnose", "segments", 1, 2), (2, "Fix", "segments", 3, 3)]+ last_ls = [e for e in doc["events"] if e.get("tool") == "Bash"][-1]+ assert last_ls["task"] == 2+++def test_claude_subagent_launch_keeps_child_model(tmp_path):+ repo = _repo(tmp_path)+ cwd = str(repo)+ groups = [+ _prompt(0, cwd, "go"),+ _call(1, 5, cwd, "Agent", {"subagent_type": "Explore", "model": "haiku"}, "done"),+ ]+ path = _write(tmp_path, groups)+ sub = path.with_suffix("") / "subagents"+ sub.mkdir(parents=True)+ (sub / "agent-abc.jsonl").write_text(+ "".join(+ _call(+ 9, 6, cwd, "Read", {"file_path": str(repo / "a.py")}, "x", model="claude-haiku-4-5"+ )+ )+ )+ doc = sm.build_claude_code_map(path)+ launch = next(e for e in doc["events"] if e["kind"] == "subagent")+ assert launch["model"] == "haiku" # the requested child model the viewer shows+ read = next(e for e in doc["events"] if e.get("tool") == "Read")+ assert read["model"] == "claude-haiku-4-5" and read["agent"] != "main"+++# ---------------------------------------------------------------- spans (Codex / Cursor)+def _span(span_id, name, start, end=None, parent=None, status="OK", **attrs):+ return SimpleNamespace(+ span_id=span_id,+ name=name,+ start_time=start,+ end_time=end,+ parent_id=parent,+ status_code=status,+ attributes=attrs,+ )+++T0 = datetime(2026, 9, 23, 15, 44, tzinfo=UTC)+++def _at(sec):+ return T0 + timedelta(seconds=sec)+++def test_codex_code_mode_outputs_status_ok_is_not_trusted(tmp_path):+ repo = _repo(tmp_path, "backend", "acme/backend")+ wrap = lambda cmd: ( # noqa: E731+ "const r = await tools.exec_command("+ + json.dumps({"cmd": cmd, "workdir": str(repo)})+ + "); text(r.output);"+ )+ spans = [+ _span("root", "Session", _at(0), **{"harness.agent_session_id": "c1"}),+ _span(+ "t1",+ "Turn 1",+ _at(0),+ _at(60),+ parent="root",+ **{"input.value": "ship it", "llm.model_name": "gpt-6-astra"},+ ),+ _span(+ "a",+ "Bash",+ _at(1),+ _at(2),+ parent="t1",+ **{+ "tool.name": "Bash",+ "input.value": wrap("git commit -m x"),+ "output.value": "Script completed Wall time 0.3 seconds Output: [feat deadbee] x\n 1 file changed, 2 insertions(+)",+ },+ ),+ _span(+ "b",+ "Bash",+ _at(3),+ _at(4),+ parent="t1",+ **{+ "tool.name": "Bash",+ "input.value": wrap("gh pr merge 103 --squash"),+ "output.value": "Script completed Output: X Pull request acme/app#103 is not mergeable",+ },+ ),+ _span(+ "c",+ "save_issue",+ _at(5),+ _at(6),+ parent="t1",+ **{+ "tool.name": "save_issue",+ "input.value": json.dumps({"team": "X", "title": "t"}),+ "output.value": 'Wall time: 0.7 seconds Output: Error: Could not find team "X"',+ },+ ),+ _span(+ "d",+ "save_issue",+ _at(7),+ _at(8),+ parent="t1",+ **{+ "tool.name": "save_issue",+ "input.value": json.dumps({"team": "ENT", "title": "t"}),+ "output.value": 'Output: {"id":"ACME-4800"}',+ },+ ),+ _span(+ "t2",+ "Turn 2",+ _at(60),+ _at(90),+ parent="root",+ **{"input.value": "next", "llm.model_name": "gpt-5.6-terra"},+ ),+ _span(+ "e",+ "js",+ _at(61),+ _at(62),+ parent="t2",+ **{+ "tool.name": "js",+ "input.value": 'text(await tools.exec_command({cmd:"gh pr comment 5 --body hi", workdir:"/w"}));',+ "output.value": "https://github.com/acme/backend/pull/5#issuecomment-9",+ },+ ),+ ]+ doc = sm.build_map_from_spans(+ spans,+ session_id="local:codex:x",+ agent_tool="codex",+ role="subagent",+ parent_session_id="p1",+ )+ assert [(c["sha"], c["repo"]) for c in _kinds(doc, "commit")] == [("deadbee", "backend")]+ assert _kinds(doc, "pr_merge") == []+ assert [(t["tracker"], t["action"], t["id"]) for t in _kinds(doc, "ticket")] == [+ ("linear", "create", "ACME-4800")+ ]+ assert [c.get("number") for c in _kinds(doc, "pr_comment")] == [5]+ commit_call = next(e for e in doc["events"] if e.get("verb") == "git commit")+ assert commit_call["kind"] == "exec"+ assert [(s["from"], s["to"]) for s in _kinds(doc, "model_switch")] == [+ ("gpt-6-astra", "gpt-5.6-terra")+ ]+ assert (doc["session"]["role"], doc["session"]["parentSessionId"]) == ("subagent", "p1")+ assert [t["n"] for t in doc["tasks"]] == [1, 2]+++def test_cursor_default_model_mcp_names_and_truncated_input(tmp_path):+ repo = _repo(tmp_path)+ spans = [+ _span("root", "Session", _at(0), **{"llm.model_name": "default"}),+ _span(+ "t1",+ "Turn 1",+ _at(0),+ _at(30),+ parent="root",+ **{"input.value": "see https://x.io", "llm.model_name": ""},+ ),+ _span(+ "a",+ "Bash",+ _at(1),+ _at(2),+ parent="t1",+ **{+ "tool.name": "Bash",+ "cwd": str(repo),+ "input.value": '{"command": "cd ' + str(repo) + ' && git commit -m \\"x',+ "output.value": '{"output":"[fix/a c0ffee1] x\\n 3 files changed, 913 insertions(+)"}',+ },+ ),+ _span(+ "b",+ "mcp",+ _at(3),+ _at(4),+ parent="t1",+ **{+ "tool.name": "mcp-linear-create_issue",+ "input.value": json.dumps({"title": "t"}),+ "output.value": '{"identifier":"ACME-9"}',+ },+ ),+ ]+ doc = sm.build_map_from_spans(spans, session_id="local:cursor:x", agent_tool="cursor")+ assert {e["model"] for e in doc["events"]} == {"default"}+ assert [c["sha"] for c in _kinds(doc, "commit")] == ["c0ffee1"]+ mcp = next(e for e in doc["events"] if e["kind"] == "mcp")+ assert (mcp["server"], mcp["tool"]) == ("linear", "create_issue")+ assert [(t["tracker"], t["id"]) for t in _kinds(doc, "ticket")] == [("linear", "ACME-9")]+ assert _kinds(doc, "user")[0]["urls"] == 1+++ ("text", "ok"),+ [+ ("✓ Merged pull request #12 (x)", True),+ ('{"sha":"a","merged":true,"message":"Pull Request successfully merged"}', True),+ (+ "! Pull request #12 will be automatically merged via squash when all requirements are met",+ False,+ ),+ ("X Pull request #12 is not mergeable", False),+ ("! Pull request #12 was already merged", False),+ ],+)+def test_merge_confirmation(text, ok):+ got = sm.confirm_output({"type": "pr_merge", "repo": None, "number": 12}, text, False)+ assert bool(got) is ok+++def test_unwrap_command_variants():+ assert sm.unwrap_command('x = tools.exec_command({"cmd":"ls -l","workdir":"/w"})') == (+ "ls -l",+ "/w",+ )+ assert sm.unwrap_command('tools.exec_command({cmd:"git commit -m \\"a\\"", workdir:"/w"})') == (+ 'git commit -m "a"',+ "/w",+ )+ assert sm.unwrap_command("git status") == ("git status", None)+++# ---------------------------------------------------------------- task cache+++++++def _cand(sid, agent, path, source=None):+ return {"session_id": sid, "agent": agent, "path": str(path), "mtime": 1.0, "_source": source}+++++++++++++++++ ("text", "err", "extra", "ok"),+ [+ # gh prints its success line only to a TTY: a clean, silent exit IS the merge+ ("(Bash completed with no output)", False, {}, True),+ ("From https://github.com/a/b\n * branch main\nFast-forward\n x.py | 3 +", False, {}, True),+ # merged on GitHub, then gh's local branch switch failed (exit 1): still a merge+ (+ "Exit code 1\nfailed to run git: fatal: 'main' is already used by worktree at '/w'",+ True,+ {},+ True,+ ),+ (+ "X Pull request #5 is not mergeable: the base branch policy prohibits the merge.",+ False,+ {},+ False,+ ),+ ("Exit code 1\nGraphQL: Pull Request is not mergeable", True, {}, False),+ ("! Pull request #5 was already merged", False, {}, False),+ ("", False, {"auto": True}, False), # --auto only queues it+ ],+)+def test_cli_merge_confirmation_non_tty(text, err, extra, ok):+ intent = {"type": "pr_merge", "repo": None, "number": 5, "cli": True, **extra}+ assert bool(sm.confirm_output(intent, text, err)) is ok+++def test_cli_merge_intent_flags_auto():+ [it] = sm.output_intents("Bash", {"command": "gh pr merge 5 --auto --squash"}, None, None)+ assert it["auto"] is True and it["cli"] is True and it["number"] == 5+++def test_pr_merge_without_repo_flag_takes_the_checkouts_origin(tmp_path):+ repo = _repo(tmp_path, "backend", "acme/backend")+ cwd = str(repo)+ path = _write(+ tmp_path,+ [+ _prompt(0, cwd, "merge"),+ _call(+ 1,+ 5,+ cwd,+ "Bash",+ {"command": f"cd {cwd} && gh pr merge 42 --squash"},+ "(Bash completed with no output)",+ ),+ ],+ )+ [m] = _kinds(sm.build_claude_code_map(path), "pr_merge")+ assert (m["repo"], m["number"]) == ("acme/backend", 42)+++++def test_skill_write_with_ok_status_but_failed_result_is_dropped(tmp_path):+ spans = [+ _span("t1", "Turn 1", _at(0), _at(30), **{"input.value": "x", "llm.model_name": "m"}),+ _span(+ "a",+ "Edit",+ _at(1),+ _at(2),+ parent="t1",+ **{+ "tool.name": "Edit",+ "input.value": json.dumps(+ {+ "file_path": "/h/.claude/skills/s1/SKILL.md",+ "old_string": "a",+ "new_string": "b",+ }+ ),+ "output.value": "<tool_use_error>String to replace not found in file.</tool_use_error>",+ },+ ),+ _span(+ "b",+ "Edit",+ _at(3),+ _at(4),+ parent="t1",+ **{+ "tool.name": "Edit",+ "input.value": json.dumps(+ {+ "file_path": "/h/.claude/skills/s2/SKILL.md",+ "old_string": "a",+ "new_string": "b",+ }+ ),+ "output.value": "The file /h/.claude/skills/s2/SKILL.md has been updated successfully.",+ },+ ),+ ]+ doc = sm.build_map_from_spans(spans, session_id="local:codex:x", agent_tool="codex")+ assert [s["name"] for s in _kinds(doc, "skill_write")] == ["s2"]+++def test_pr_state_requires_the_exact_repo(tmp_path):+ repo = _repo(tmp_path, "service", "org-a/service")+ cwd = str(repo)+ path = _write(+ tmp_path,+ [+ _prompt(0, cwd, "x"),+ _call(+ 1,+ 5,+ cwd,+ "Bash",+ {"command": "gh pr create -t t -b b"},+ "https://github.com/org-a/service/pull/7",+ ),+ _call(+ 2,+ 9,+ cwd,+ "Bash",+ {"command": "gh pr merge 7 --repo org-b/service --squash"},+ "(Bash completed with no output)",+ ),+ ],+ )+ doc = sm.build_claude_code_map(path)+ assert _kinds(doc, "pr_merge")[0]["repo"] == "org-b/service"+ assert doc["prs"][0]["state"] == "open"diff --git a/python/tests/test_check_clean.py b/python/tests/test_check_clean.pynew file mode 100644index 0000000..c18e05d--- /dev/null+++ b/python/tests/test_check_clean.py@@ -0,0 +1,30 @@+"""The publish-time leak scanner flags leak shapes and passes placeholders."""++import importlib.util+from pathlib import Path++import pytest++_script = Path(__file__).resolve().parents[2] / "scripts" / "check_clean.py"+if not _script.is_file():+ pytest.skip("scripts/ is only in a repo checkout, not the sdist", allow_module_level=True)+_spec = importlib.util.spec_from_file_location("check_clean", _script)+check_clean = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(check_clean) # type: ignore[union-attr]+++def test_flags_leak_shapes() -> None:+ assert "ticket id" in check_clean.scan_line("fixes ZZ" + "-123")+ assert "cross-repo PR ref" in check_clean.scan_line("see widgets" + "#1234")+ assert "personal home path" in check_clean.scan_line("/Users" + "/bob/project")+ assert "personal home path" in check_clean.scan_line("~/.claude/projects/-Users" + "-bob-app")+ assert "personal home path" in check_clean.scan_line("bobs" + "-MacBook-Pro.local")+ assert "real-looking email" in check_clean.scan_line("mail bob" + "@corp.io")+++def test_placeholders_pass() -> None:+ for line in (+ "UTF-8 and SHA-256", "acme/app#1234", "ACME-42", "/Users/you/x", "[email protected]",+ "-Users-ada-work-app", "adas-MacBook-Pro.local",+ ):+ assert check_clean.scan_line(line) == [], linediff --git a/python/tests/test_cli_output.py b/python/tests/test_cli_output.pynew file mode 100644index 0000000..c272971--- /dev/null+++ b/python/tests/test_cli_output.py@@ -0,0 +1,167 @@+"""Terminal output: log lines, the progress bar, and the end-of-run summary."""++from __future__ import annotations++import io+import logging+from collections import Counter+from datetime import UTC, datetime++import pytest++from agentplay import cli, pipeline+++class _TTY(io.StringIO):+ def isatty(self) -> bool:+ return True++[email protected](autouse=True)+def _restore_logging(monkeypatch):+ root = logging.getLogger()+ handlers, level = list(root.handlers), root.level+ monkeypatch.setattr(cli, "_progress_live", False)+ yield+ root.handlers[:] = handlers+ root.setLevel(level)+++def _emit(handler: logging.Handler, msg: str = "session skipped", name: str = "agentplay.x.source",+ level: int = logging.WARNING) -> None:+ handler.handle(logging.LogRecord(name, level, __file__, 1, msg, None, None))+++def test_default_format_is_user_facing_with_no_module_path() -> None:+ out = io.StringIO()+ _emit(cli._log_handler(out, verbose=False))+ assert out.getvalue() == "agentplay: warning: session skipped\n"+++def test_verbose_format_names_the_logger_and_level() -> None:+ out = io.StringIO()+ _emit(cli._log_handler(out, verbose=True), name="agentplay.x.source", level=logging.DEBUG)+ assert out.getvalue() == "agentplay: debug: agentplay.x.source: session skipped\n"+++def test_live_progress_line_is_cleared_before_the_message() -> None:+ out = _TTY()+ cli._progress_live = True+ _emit(cli._log_handler(out, verbose=False))+ assert out.getvalue() == "\r\x1b[2Kagentplay: warning: session skipped\n"+++def test_no_clear_sequence_when_no_progress_is_live() -> None:+ out = _TTY()+ _emit(cli._log_handler(out, verbose=False))+ assert "\x1b" not in out.getvalue()+++def test_progress_tracks_whether_a_bar_is_on_screen(monkeypatch) -> None:+ monkeypatch.setattr(cli.sys, "stderr", _TTY())+ cli._progress(1, 10, "")+ assert cli._progress_live+ cli._progress(10, 10, "")+ assert not cli._progress_live+++def test_progress_is_not_live_when_stderr_is_not_a_tty(monkeypatch) -> None:+ monkeypatch.setattr(cli.sys, "stderr", io.StringIO())+ cli._progress(1, 10, "")+ assert not cli._progress_live+++def _report(**kw) -> pipeline.BuildReport:+ return pipeline.BuildReport(found=563, built=557, **kw)+++def test_summary_lists_skip_reasons_by_count(monkeypatch, capsys) -> None:+ rep = _report(skipped=7, skip_reasons=Counter(no_conversation=4, too_large=2, empty_or_unreadable=1))+ monkeypatch.setattr(cli.pipeline, "build_all", lambda **_kw: rep)+ assert cli.main(["build"]) == 0+ assert "7 skipped (4 no conversation, 2 too large, 1 empty or unreadable)" in capsys.readouterr().out+++def test_summary_has_no_breakdown_when_nothing_was_skipped(monkeypatch, capsys) -> None:+ monkeypatch.setattr(cli.pipeline, "build_all", lambda **_kw: _report())+ assert cli.main(["build"]) == 0+ assert "0 skipped in" in capsys.readouterr().out+++def test_main_ignores_python_warnings_unless_the_user_opted_in(monkeypatch) -> None:+ calls: list[tuple] = []+ monkeypatch.setattr(cli.warnings, "simplefilter", lambda *a, **k: calls.append(a))+ monkeypatch.setattr(cli.pipeline, "build_all", lambda **_kw: _report())+ monkeypatch.setattr(cli.sys, "warnoptions", [])+ cli.main(["build"])+ assert calls == [("ignore",)]+ calls.clear()+ monkeypatch.setattr(cli.sys, "warnoptions", ["error"])+ cli.main(["build"])+ assert calls == []+++def test_build_all_tallies_discovery_skips_but_not_subagents_or_other_agents(monkeypatch, tmp_path) -> None:+ class _Source:+ def discovery_stats(self):+ skipped = {"no_conversation": 2, "subagent_component": 9, "different_agent": 5}+ return {"claude-code": {"seen": 16, "indexed": 0, "skipped": skipped}}++ monkeypatch.setattr(pipeline.discover, "materialize_all", lambda *_a: {})+ monkeypatch.setattr(pipeline.discover, "local_source", lambda *_a: _Source())+ monkeypatch.setattr(pipeline.discover, "candidates", lambda *_a, **_k: [])+ rep = pipeline.build_all(store=pipeline.Store(tmp_path))+ assert rep.skipped == 2+ assert rep.skip_reasons == {"no_conversation": 2}++[email protected]("scope", [{"since": datetime(2026, 1, 1, tzinfo=UTC)}, {"limit": 5}])+def test_scoped_build_does_not_count_skips_from_the_whole_disk(monkeypatch, tmp_path, scope) -> None:+ """The walk sees every file on disk; a --since/--limit run must not report those as its skips."""+ class _Source:+ def discovery_stats(self):+ return {"claude-code": {"seen": 3, "indexed": 0, "skipped": {"no_conversation": 3}}}++ monkeypatch.setattr(pipeline.discover, "materialize_all", lambda *_a: {})+ monkeypatch.setattr(pipeline.discover, "local_source", lambda *_a: _Source())+ monkeypatch.setattr(pipeline.discover, "candidates", lambda *_a, **_k: [])+ rep = pipeline.build_all(store=pipeline.Store(tmp_path), **scope)+ assert rep.skipped == 0+ assert not rep.skip_reasons+++def test_agent_breakdown_adds_up_to_found(monkeypatch, capsys) -> None:+ rep = pipeline.BuildReport(found=52, built=49, skipped=3, by_agent=Counter({"claude-code": 44, "codex": 5}))+ monkeypatch.setattr(cli.pipeline, "build_all", lambda **_kw: rep)+ assert cli.main(["build"]) == 0+ assert "claude-code 44 · codex 5 · 3 not built" in capsys.readouterr().out+++def test_agent_breakdown_has_no_remainder_when_everything_was_built() -> None:+ rep = pipeline.BuildReport(found=5, built=5, by_agent=Counter({"codex": 5}))+ assert cli._agent_breakdown(rep) == "codex 5"+ assert cli._agent_breakdown(pipeline.BuildReport()) == "none"+++class _FakeServer:+ """What ``serve`` returns, bound to ``port``, without opening a socket."""++ def __init__(self, port: int) -> None:+ self.server_address = ("127.0.0.1", port)++ def serve_forever(self) -> None:+ pass++ def server_close(self) -> None:+ pass++[email protected](("requested", "bound", "notice"), [(7317, 62505, True), (7317, 7317, False), (0, 50123, False)])+def test_view_says_when_the_requested_port_is_busy(monkeypatch, capsys, requested, bound, notice) -> None:+ from agentplay import server++ monkeypatch.setattr(server, "serve", lambda _port: _FakeServer(bound))+ assert cli.main(["view", "--port", str(requested), "--no-open", "--no-build"]) == 0+ out, err = capsys.readouterr()+ assert (f"Port {requested} is busy; using {bound} instead." in err) is notice+ assert f"127.0.0.1:{bound}/" in outdiff --git a/python/tests/test_launch_regressions.py b/python/tests/test_launch_regressions.pynew file mode 100644index 0000000..3679e19--- /dev/null+++ b/python/tests/test_launch_regressions.py@@ -0,0 +1,98 @@+"""Regression tests for discovery, outcome classification and export edge cases."""++from __future__ import annotations++import argparse+import json+import os+import pathlib+import sqlite3++from agentplay import builder as sm+from agentplay import cli, materialize+from agentplay.materialize import AgentKind, HomeSpec+from agentplay.store import Store+++def test_classify_outcome_uses_seq_on_a_filtered_event_list():+ # A subagent's events are a filtered slice of the session, so their `seq`+ # values are global positions, not indexes into the slice.+ events = [+ {"kind": "verify", "seq": 10},+ {"kind": "edit", "seq": 11},+ ]+ assert sm.classify_outcome(events, "done") != "verified"+++def test_classify_outcome_still_verifies_when_no_edit_follows():+ events = [+ {"kind": "edit", "seq": 10},+ {"kind": "verify", "seq": 11},+ ]+ assert sm.classify_outcome(events, "done") == "verified"+++def test_opencode_session_with_out_of_range_time_does_not_abort_discovery(tmp_path, monkeypatch):+ home = tmp_path / "opencode"+ home.mkdir()+ con = sqlite3.connect(home / "opencode.db")+ con.execute("CREATE TABLE session (id TEXT, project_id TEXT, directory TEXT, time_updated INTEGER)")+ con.executemany(+ "INSERT INTO session VALUES (?, ?, ?, ?)",+ [("bad", "p", "/w", 10**18), ("good", "p", "/w", 1_700_000_000_000)],+ )+ con.commit()+ con.close()+ monkeypatch.setattr(materialize, "_opencode_synthesize", lambda _con, _sid: b"x\n")++ spec = HomeSpec(AgentKind.OPENCODE, home)+ sessions = list(materialize.find_opencode_candidates(spec, cache_root=tmp_path / "c"))++ assert sorted(s.rel_path.name for s in sessions) == ["bad.jsonl", "good.jsonl"]+++def test_kiro_cache_survives_a_failed_rewrite(tmp_path, monkeypatch):+ home = tmp_path / "kiro"+ session_dir = home / "sessions" / "ws" / "s1"+ session_dir.mkdir(parents=True)+ (session_dir / "session.json").write_text(json.dumps({"id": "s1"}))+ messages = session_dir / "messages.jsonl"+ messages.write_text("{}\n")+ cache = tmp_path / "c"+ cached = cache / "ws" / "s1.jsonl"+ cached.parent.mkdir(parents=True)+ cached.write_bytes(b"OLD\n")+ os.utime(cached, (1_000_000, 1_000_000)) # older than messages.jsonl: forces a rewrite++ monkeypatch.setattr(materialize, "_kiro_synthesize", lambda *_a: b"NEW CONTENT\n")+ real_write_bytes = pathlib.Path.write_bytes++ def torn_write(self, data):+ if self.parent == cached.parent:+ real_write_bytes(self, data[:3])+ raise OSError("disk full")+ return real_write_bytes(self, data)++ monkeypatch.setattr(pathlib.Path, "write_bytes", torn_write)+ list(materialize.find_kiro_candidates(HomeSpec(AgentKind.KIRO, home), cache_root=cache))++ assert cached.read_bytes() == b"OLD\n"+ assert [p.name for p in cached.parent.iterdir()] == ["s1.jsonl"]+++def test_export_with_an_unnamed_repo(tmp_path, monkeypatch, capsys):+ monkeypatch.setenv("AGENTPLAY_HOME", str(tmp_path / "home"))+ st = Store()+ doc = {+ "schema": sm.SCHEMA,+ "session": {"id": "sess-1", "pathMode": "relative"},+ "repos": [{"id": "r0", "name": None, "remote": None}, {"id": "r1", "name": "app", "remote": None}],+ "files": [],+ }+ st.put(doc, {"sessionId": "sess-1"})+ st.save_index()++ out = tmp_path / "out.json"+ assert cli.cmd_export(argparse.Namespace(session="sess-1", output=str(out))) == 0+ assert out.is_file()+ assert "repo names (app)" in capsys.readouterr().outdiff --git a/python/tests/test_license_copies.py b/python/tests/test_license_copies.pynew file mode 100644index 0000000..d3815e2--- /dev/null+++ b/python/tests/test_license_copies.py@@ -0,0 +1,15 @@+"""python/ ships copies of the repo's license files; they must match the originals."""++from pathlib import Path++import pytest++PYTHON = Path(__file__).resolve().parents[1]+REPO = PYTHON.parent++[email protected]("name", ["LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md"])+def test_copy_matches_repo_root(name: str) -> None:+ if not (REPO / name).is_file():+ pytest.skip("not in a repo checkout (e.g. an unpacked sdist)")+ assert (PYTHON / name).read_bytes() == (REPO / name).read_bytes(), f"copy {name} to python/{name}"diff --git a/python/tests/test_local_tool.py b/python/tests/test_local_tool.pynew file mode 100644index 0000000..019b922--- /dev/null+++ b/python/tests/test_local_tool.py@@ -0,0 +1,1075 @@+"""End-to-end tests for the local tool: build, store, server, export, import."""++from __future__ import annotations++import base64+import contextlib+import gzip+import io+import json+import os+import struct+import subprocess+import sys+import threading+import urllib.error+import urllib.request+import zlib+from pathlib import Path+from typing import Any++import pytest++from agentplay import cli, discover, materialize, pipeline+from agentplay import server as server_mod+from agentplay import store as store_mod+from agentplay.server import serve+from agentplay.store import Store+++def _line(**d: Any) -> str:+ return json.dumps(d) + "\n"+++def _write_claude_session(home: Path, stem: str, cwd: Path, *, ts_day: str = "2026-09-10", edits_without_read: bool = False) -> Path:+ proj = home / ".claude" / "projects" / "-work-app"+ proj.mkdir(parents=True, exist_ok=True)+ f = proj / f"{stem}.jsonl"+ target = f"{cwd}/src/app.py"+ lines = [+ _line(type="user", timestamp=f"{ts_day}T01:00:00Z", cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": "please fix the SECRET-PROMPT bug"}),+ ]+ seq = 1+ if not edits_without_read:+ lines.append(_line(type="assistant", timestamp=f"{ts_day}T01:00:01Z", cwd=str(cwd), sessionId=stem,+ message={"id": f"m{seq}", "model": "claude-sonnet-5", "role": "assistant",+ "usage": {"input_tokens": 10, "output_tokens": 5, "cache_read_input_tokens": 100},+ "content": [{"type": "tool_use", "id": "r1", "name": "Read",+ "input": {"file_path": target}}]}))+ lines.append(_line(type="user", timestamp=f"{ts_day}T01:00:02Z", cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": "r1",+ "content": "x = 1"}]}))+ for i in range(4):+ tid = f"e{i}"+ lines.append(_line(type="assistant", timestamp=f"{ts_day}T01:00:{10 + 2 * i:02d}Z", cwd=str(cwd), sessionId=stem,+ message={"id": f"m{10 + i}", "model": "claude-sonnet-5", "role": "assistant",+ "usage": {"input_tokens": 10, "output_tokens": 5},+ "content": [{"type": "tool_use", "id": tid, "name": "Edit",+ "input": {"file_path": target, "old_string": "a", "new_string": "b"}}]}))+ lines.append(_line(type="user", timestamp=f"{ts_day}T01:00:{11 + 2 * i:02d}Z", cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": tid,+ "content": "ok"}]}))+ f.write_text("".join(lines))+ return f+++def env(tmp_path, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HOME", str(home))+ # Windows expands ~ from USERPROFILE, and VS Code paths from APPDATA.+ monkeypatch.setenv("USERPROFILE", str(home))+ monkeypatch.setenv("APPDATA", str(home / "AppData" / "Roaming"))+ monkeypatch.setenv("LOCALAPPDATA", str(home / "AppData" / "Local"))+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ monkeypatch.setenv("AGENTPLAY_HOME", str(tmp_path / "sm"))+ for var in ("AGENTPLAY_CLAUDE_HOMES", "AGENTPLAY_CODEX_HOMES", "AGENTPLAY_CURSOR_HOMES"):+ monkeypatch.delenv(var, raising=False)+ repo = tmp_path / "work" / "app"+ (repo / ".git").mkdir(parents=True)+ (repo / ".git" / "config").write_text('[remote "origin"]\n\turl = [email protected]:acme/app.git\n')+ (repo / "src").mkdir()+ (repo / "src" / "app.py").write_text("x = 1\n")+ return {"home": home, "repo": repo, "sm": tmp_path / "sm"}+++def test_cache_root_follows_agentplay_home_set_after_import(tmp_path, monkeypatch):+ """Cache roots resolve per call, not at import.++ Binding these at import time made every cache read fall back to the developer's+ real ``~/.agentplay/cache``, so a test that set ``AGENTPLAY_HOME`` in a fixture+ still ingested their whole session history.+ """+ monkeypatch.setenv("AGENTPLAY_HOME", str(tmp_path / "elsewhere"))+ assert materialize.cache_root() == tmp_path / "elsewhere" / "cache"+ assert store_mod.root() == tmp_path / "elsewhere"+ for derived in (+ materialize.opencode_cache_root(),+ materialize.cursor_store_cache_root(),+ materialize.cursor_composer_cache_root(),+ materialize.kiro_cache_root(),+ ):+ assert derived.parent == tmp_path / "elsewhere" / "cache"+++def test_build_is_incremental_and_redacted(env):+ _write_claude_session(env["home"], "11111111-0000-0000-0000-000000000001", env["repo"])+ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert (rep.found, rep.built, rep.unchanged) == (1, 1, 0)+ again = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert (again.built, again.unchanged) == (0, 1)+ st = Store(env["sm"])+ (row,) = st.rows()+ assert row["sessionId"] == "local:claude-code:11111111-0000-0000-0000-000000000001"+ assert row["sessionTitle"] == "please fix the SECRET-PROMPT bug" # local index only+ raw = (env["sm"] / "maps" / f"{row['key']}.json").read_text()+ assert "SECRET-PROMPT" not in raw # the map itself never carries prompt text+ doc = st.get(row["sessionId"])+ assert doc["schema"] == "agentplay/v1"+ assert [f["path"] for f in doc["files"]] == ["src/app.py"]+ assert doc["repos"][0]["remote"] == "acme/app"+++ ("raw", "want"),+ [+ # A harness block usually *prefixes* a real prompt. Dropping the turn on+ # sight of a leading "<" threw the prompt away with it.+ ("<system-reminder>\nWorktree: /x\n</system-reminder>\n\nset up the staging deploy script",+ "set up the staging deploy script"),+ ("[Image #1] [Image #2] yesterday is image 1", "yesterday is image 1"),+ # Whole turns the harness wrote: no prompt in them at all.+ ("[Request interrupted by user]", None),+ ("[Request interrupted by user for tool use]", None),+ ("<task-notification>\n<task-id>abc</task-id>\n</task-notification>", None),+ ("<command-name>/setup</command-name>\n<command-args>--x</command-args>", None),+ ("Caveat: The messages below were generated", None),+ ("please fix the SECRET-PROMPT bug", "please fix the SECRET-PROMPT bug"),+ ],+)+def test_clean_title_keeps_the_prompt_and_drops_the_harness(raw, want):+ assert discover._clean_title(raw, 60) == want+++def test_task_titles_are_served_but_never_written_to_the_map(env):+ """Task labels are prompt text: index and served map yes, map on disk no."""+ _write_claude_session(env["home"], "44444444-0000-0000-0000-000000000004", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()++ assert row["taskTitles"] == ["please fix the SECRET-PROMPT bug"]+ raw = (env["sm"] / "maps" / f"{row['key']}.json").read_text()+ assert "SECRET-PROMPT" not in raw # what `export` writes+ assert st.get(row["sessionId"])["tasks"][0]["name"] is None++ httpd = serve(0, store=st)+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ try:+ with urllib.request.urlopen(+ f"{base}/api/map-doc?id={urllib.request.quote(row['sessionId'], safe='')}"+ ) as r:+ served = json.loads(r.read())+ assert served["tasks"][0]["name"] == "please fix the SECRET-PROMPT bug"+ with urllib.request.urlopen(f"{base}/api/sessions?pageSize=5") as r:+ page = json.loads(r.read())+ assert "taskTitles" not in page["sessions"][0] # the list has no use for them+ finally:+ httpd.shutdown()+ httpd.server_close()+++def test_no_titles_also_drops_task_titles(env):+ _write_claude_session(env["home"], "55555555-0000-0000-0000-000000000005", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]), titles=False)+ (row,) = Store(env["sm"]).rows()+ assert row["sessionTitle"] is None and row["taskTitles"] is None+++def _write_multi_turn_session(home: Path, stem: str, cwd: Path) -> Path:+ """Three real prompts, separated by records that emit no user turn.++ The interruption, the harness-only turn and the system notification each+ look like a "user" record and each produce no ``user`` event, so none of+ them may take a slot in the task-title list.+ """+ proj = home / ".claude" / "projects" / "-work-app"+ proj.mkdir(parents=True, exist_ok=True)+ f = proj / f"{stem}.jsonl"+ target = f"{cwd}/src/app.py"+ lines: list[str] = []++ def user(ts: str, content: Any, **extra: Any) -> None:+ lines.append(_line(type="user", timestamp=ts, cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": content}, **extra))++ def tool_call(ts: str, mid: str, tid: str) -> None:+ lines.append(_line(type="assistant", timestamp=ts, cwd=str(cwd), sessionId=stem,+ message={"id": mid, "model": "claude-sonnet-5", "role": "assistant",+ "usage": {"input_tokens": 10, "output_tokens": 5},+ "content": [{"type": "tool_use", "id": tid, "name": "Read",+ "input": {"file_path": target}}]}))+ lines.append(_line(type="user", timestamp=ts, cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": [{"type": "tool_result",+ "tool_use_id": tid, "content": "x = 1"}]}))++ user("2026-09-10T01:00:00Z", "first prompt about parsing")+ tool_call("2026-09-10T01:00:01Z", "m1", "t1")+ user("2026-09-10T01:00:03Z", "[Request interrupted by user]")+ user("2026-09-10T01:00:04Z", "<task-notification>\n<task-id>abc</task-id>\n</task-notification>")+ user("2026-09-10T01:00:05Z", "meta chatter", isMeta=True)+ user("2026-09-10T01:00:06Z", "second prompt about caching")+ tool_call("2026-09-10T01:00:07Z", "m2", "t2")+ user("2026-09-10T01:00:09Z", "[SYSTEM NOTIFICATION - NOT USER INPUT] a task finished")+ user("2026-09-10T01:00:10Z", "third prompt about the viewer")+ tool_call("2026-09-10T01:00:11Z", "m3", "t3")+ f.write_text("".join(lines))+ return f+++def test_task_titles_line_up_with_the_user_turns_the_builder_emits(env):+ """One title per emitted user turn, so `firstTurn` indexes the right label.++ Interruptions, harness-only turns and meta records are "user" records that+ emit no `user` event. Counting them here put six entries against three+ turns, which blanked task 2 and gave task 3 task 2's prompt.+ """+ _write_multi_turn_session(env["home"], "77777777-0000-0000-0000-000000000007", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()+ doc = st.get(row["sessionId"])++ assert sum(1 for e in doc["events"] if e["kind"] == "user") == 3+ assert row["taskTitles"] == [+ "first prompt about parsing",+ "second prompt about caching",+ "third prompt about the viewer",+ ]+ assert [t["firstTurn"] for t in doc["tasks"]] == [1, 2, 3]+ named = server_mod._with_task_titles(doc, row)+ assert [t["name"] for t in named["tasks"]] == [+ "first prompt about parsing",+ "second prompt about caching",+ "third prompt about the viewer",+ ]+++_MULTI_TURN_TITLES = [+ "first prompt about parsing",+ "second prompt about caching",+ "third prompt about the viewer",+]++[email protected]("unfilled", ["absent", "null"])+def test_unchanged_session_gains_task_titles_without_a_rebuild(env, unfilled):+ """A row with no task titles gets them on the next incremental run.++ Two shapes mean "not filled in" and both have to be refilled: a row written+ before task titles existed carries no key at all, and a `--no-titles` run+ leaves the key set to None. Reading `None` as "already done" left every+ session a `--no-titles` run had touched generically labelled until its+ transcript changed or the user forced a `--rebuild`.+ """+ _write_multi_turn_session(env["home"], "88888888-0000-0000-0000-000000000008", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))++ old = Store(env["sm"])+ (row,) = old.rows()+ sid, content_hash = row["sessionId"], row["contentHash"]+ if unfilled == "absent":+ del old.index[sid]["taskTitles"] # the shape an older version wrote+ else:+ old.index[sid]["taskTitles"] = None # the shape a `--no-titles` run writes+ old.save_index()++ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert (rep.built, rep.unchanged) == (0, 1) # the map itself was not rebuilt++ (row,) = Store(env["sm"]).rows()+ assert row["contentHash"] == content_hash+ assert row["taskTitles"] == _MULTI_TURN_TITLES+++def test_a_row_that_already_has_titles_is_not_re_read(env, monkeypatch):+ """Filled is filled: a default run neither re-extracts nor overwrites.++ Only `None`-or-absent counts as unfilled, so a row carrying real labels is+ left exactly as it is rather than being rebuilt from the transcript on+ every incremental run.+ """+ _write_multi_turn_session(env["home"], "99999999-0000-0000-0000-000000000009", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()+ st.index[row["sessionId"]]["taskTitles"] = ["kept"]+ st.index[row["sessionId"]]["sessionTitle"] = "kept too"+ st.save_index()++ def _boom(*_a, **_k):+ raise AssertionError("a filled row must not be read from the transcript again")++ monkeypatch.setattr(discover, "local_title", _boom)+ monkeypatch.setattr(discover, "local_task_titles", _boom)++ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ (row,) = Store(env["sm"]).rows()+ assert row["taskTitles"] == ["kept"]+ assert row["sessionTitle"] == "kept too"+++def test_no_titles_clears_the_prompt_text_an_earlier_run_stored(env):+ """The opt-out reaches data already on disk, not only future sessions.++ `--no-titles` is a per-run switch. A default build writes the first prompt+ and every task label into `index.json`; a later `--no-titles` run has to+ take them back out again, or the switch never touches the prompt text it+ exists for and local map responses keep serving the labels.+ """+ _write_multi_turn_session(env["home"], "bbbbbbbb-0000-0000-0000-00000000000b", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ index_path = env["sm"] / "index.json"+ stored = index_path.read_text(encoding="utf-8")+ assert all(t in stored for t in _MULTI_TURN_TITLES) # the state being opted out of++ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]), titles=False)+ assert (rep.built, rep.unchanged) == (0, 1) # cleared in place, nothing rebuilt++ # On disk, not just in what the API chooses to serve: the finding is that+ # the prompt text is still in the index.+ stored = index_path.read_text(encoding="utf-8")+ for fragment in (*_MULTI_TURN_TITLES, "prompt about", "parsing", "caching", "viewer"):+ assert fragment not in stored++ st = Store(env["sm"])+ (row,) = st.rows()+ assert row["sessionTitle"] is None and row["taskTitles"] is None+ doc = st.get(row["sessionId"])+ assert [t["name"] for t in server_mod._with_task_titles(doc, row)["tasks"]] == [None, None, None]+++def test_titles_come_back_on_the_next_default_run(env):+ """Clearing is this run's doing, not a preference the next run inherits."""+ _write_multi_turn_session(env["home"], "cccccccc-0000-0000-0000-00000000000c", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]), titles=False)+ (row,) = Store(env["sm"]).rows()+ assert row["sessionTitle"] is None and row["taskTitles"] is None++ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert (rep.built, rep.unchanged) == (0, 1)+ (row,) = Store(env["sm"]).rows()+ assert row["sessionTitle"] == "first prompt about parsing"+ assert row["taskTitles"] == _MULTI_TURN_TITLES+++ ("peer", "loopback"),+ [+ ("127.0.0.1", True),+ ("127.0.1.1", True),+ ("::1", True),+ ("::ffff:127.0.0.1", True), # an IPv6 socket serving an IPv4 local client+ ("fe80::1%eth0", False),+ ("192.168.1.20", False),+ ("10.0.0.7", False),+ ("", False), # unparseable fails closed+ ],+)+def test_is_loopback_peer(peer, loopback):+ assert server_mod._is_loopback((peer, 51000)) is loopback+++def test_task_titles_are_withheld_from_a_non_loopback_client(env):+ """Titles are prompt text and the API is unauthenticated: local peers only.++ `serve(host=...)` accepts a non-loopback bind, and the stored map carries no+ prompt text, so the merge is what a network client must not get.+ """+ _write_claude_session(env["home"], "aaaaaaaa-0000-0000-0000-00000000000a", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()+ assert row["taskTitles"] == ["please fix the SECRET-PROMPT bug"]++ httpd = serve(0, store=st)+ base_handler = httpd.RequestHandlerClass++ class RemoteHandler(base_handler): # type: ignore[valid-type, misc]+ def setup(self) -> None:+ super().setup()+ self.client_address = ("192.168.1.20", 51000)++ httpd.RequestHandlerClass = RemoteHandler+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ try:+ with pytest.raises(urllib.error.HTTPError) as e:+ urllib.request.urlopen(f"{base}/api/map-doc?id={urllib.request.quote(row['sessionId'], safe='')}")+ assert e.value.code == 403+ assert "SECRET-PROMPT" not in e.value.read().decode()+ finally:+ httpd.shutdown()+ httpd.server_close()++[email protected]("headers", [{"Host": "evil.example:7317"}, {"Origin": "https://evil.example"}])+def test_task_titles_are_withheld_from_a_rebinding_page(env, headers):+ """A DNS-rebinding page reaches 127.0.0.1 from a loopback peer under its own+ Host. Prompt text must still only go to this machine's viewer."""+ _write_claude_session(env["home"], "bbbbbbbb-0000-0000-0000-00000000000b", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()+ httpd = serve(0, store=st)+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ url = f"http://127.0.0.1:{httpd.server_address[1]}/api/map-doc?id={urllib.request.quote(row['sessionId'], safe='')}"+ try:+ with pytest.raises(urllib.error.HTTPError) as e:+ urllib.request.urlopen(urllib.request.Request(url, headers=headers))+ assert e.value.code == 403+ assert "SECRET-PROMPT" not in e.value.read().decode()+ with urllib.request.urlopen(url) as r:+ assert "SECRET-PROMPT" in r.read().decode() # the real viewer still gets them+ finally:+ httpd.shutdown()+ httpd.server_close()+[email protected]("path", ["/api/status", "/api/sessions", "/"])+def test_a_rebinding_page_reads_nothing(env, path):+ """Session titles are prompt text and maps name private repos, so a rebinding+ Host gets 403 on every read, not just the routes that merge prompt labels."""+ _write_claude_session(env["home"], "cccccccc-0000-0000-0000-00000000000c", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ httpd = serve(0, store=Store(env["sm"]))+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ url = f"http://127.0.0.1:{httpd.server_address[1]}{path}"+ try:+ with pytest.raises(urllib.error.HTTPError) as e:+ urllib.request.urlopen(urllib.request.Request(url, headers={"Host": "evil.example:7317"}))+ assert e.value.code == 403+ assert "SECRET-PROMPT" not in e.value.read().decode()+ if path != "/": # no built viewer in the test tree, so only the API is checked locally+ with urllib.request.urlopen(url) as r:+ assert r.status == 200+ finally:+ httpd.shutdown()+ httpd.server_close()+++def test_server_picks_up_sessions_built_while_it_runs(env):+ """`view` serves first and scans in a background thread, so a Store held for+ the server's lifetime has to notice an index written underneath it."""+ _write_claude_session(env["home"], "66666666-0000-0000-0000-000000000006", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))++ served = Store(env["sm"])+ httpd = serve(0, store=served)+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"++ def count() -> int:+ with urllib.request.urlopen(f"{base}/api/status") as r:+ return json.loads(r.read())["mapCount"]++ try:+ assert count() == 1+ # A second session appears while the server is up, via its own Store —+ # exactly what the background scan does.+ _write_claude_session(env["home"], "77777777-0000-0000-0000-000000000007", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert count() == 2+ finally:+ httpd.shutdown()+ httpd.server_close()+++def test_reload_if_changed_is_opt_in_because_it_discards_pending_writes(env):+ """Why the reload is an explicit call and not a check inside `index`.++ `build_all` does many `put`s before a single `save_index`. A reload between+ them drops every pending row, so only the server — which never writes — may+ ask for one.+ """+ _write_claude_session(env["home"], "88888888-0000-0000-0000-000000000008", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))++ st = Store(env["sm"])+ st.index["pending"] = {"key": "k", "sessionId": "pending"}+ # Nothing moved on disk: the pending row survives.+ assert st.reload_if_changed() is False+ assert "pending" in st.index++ # Someone else writes the index. Asking to reload now is what would cost us+ # the pending row -- correct for the server, which is why a writer must not.+ other = Store(env["sm"])+ other.index["elsewhere"] = {"key": "k2", "sessionId": "elsewhere"}+ other.save_index()+ assert st.reload_if_changed() is True+ assert "pending" not in st.index+ assert "elsewhere" in st.index+++def test_server_endpoints(env):+ _write_claude_session(env["home"], "22222222-0000-0000-0000-000000000002", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ httpd = serve(0, store=Store(env["sm"]))+ t = threading.Thread(target=httpd.serve_forever, daemon=True)+ t.start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"++ def get(path: str) -> Any:+ with urllib.request.urlopen(base + path) as r:+ return json.loads(r.read())++ try:+ status = get("/api/status")+ assert status == {"success": True, "available": True, "mapCount": 1, "latestSessionDate": "2026-09-10"}+ page = get("/api/sessions?pageSize=10")+ assert page["hasMore"] is False and len(page["sessions"]) == 1+ row = page["sessions"][0]+ assert "sourcePath" not in row and row["agentTool"] == "claude-code"+ assert get("/api/sessions?search=nomatch")["sessions"] == []+ sid = row["sessionId"]+ batch = get("/api/map?session_id=" + urllib.request.quote(sid, safe="") + "&session_id=missing")+ assert batch["maps"][1] == {"sessionId": "missing", "status": "not_found"}+ doc = get(batch["maps"][0]["url"])+ assert doc["session"]["id"] == sid+ for gone in ("/api/nope",):+ with pytest.raises(urllib.error.HTTPError) as err:+ get(gone)+ assert err.value.code == 404+ finally:+ httpd.shutdown()+ httpd.server_close()+++def test_cli_build_json_and_export(env, capsys, monkeypatch):+ _write_claude_session(env["home"], "33333333-0000-0000-0000-000000000003", env["repo"])+ assert cli.main(["build", "--json"]) == 0+ rep = json.loads(capsys.readouterr().out)+ assert (rep["found"], rep["built"]) == (1, 1)+ monkeypatch.chdir(env["repo"])+ assert cli.main(["export", "000000000003", "-o", "s.json.gz"]) == 0+ assert (env["repo"] / "s.json.gz").stat().st_size > 100+++def test_hashed_without_key_warns_and_export_drops_the_dirs_only_hint(env, capsys, monkeypatch):+ _write_claude_session(env["home"], "33333333-0000-0000-0000-000000000003", env["repo"])+ monkeypatch.delenv("AGENTPLAY_HMAC_KEY", raising=False)+ monkeypatch.chdir(env["repo"])+ assert cli.main(["build", "--path-mode", "hashed"]) == 0+ err = capsys.readouterr().err+ assert "needs AGENTPLAY_HMAC_KEY" in err and "dirs_only" in err+ assert cli.main(["export", "000000000003", "-o", "s.json"]) == 0+ out = capsys.readouterr().out+ assert "path mode: dirs_only" in out and "Rebuild with" not in out+ assert "contains no prompt or output text" in out+ # A relative map still gets the hint, and a keyed hashed build no warning.+ assert cli.main(["build", "--rebuild"]) == 0+ capsys.readouterr()+ assert cli.main(["export", "000000000003", "-o", "s.json"]) == 0+ assert "Rebuild with --path-mode dirs_only" in capsys.readouterr().out+ monkeypatch.setenv("AGENTPLAY_HMAC_KEY", "test-key")+ assert cli.main(["build", "--rebuild", "--path-mode", "hashed"]) == 0+ assert "AGENTPLAY_HMAC_KEY" not in capsys.readouterr().err+++def test_local_path_remote_is_recorded_without_a_remote(env, capsys, monkeypatch):+ for url in (+ "/Users/ada/someone/app.git",+ "~/someone/app",+ "file:///Users/ada/someone/app",+ "C:\\Users\\someone\\app",+ "../someone/app",+ ):+ (env["repo"] / ".git" / "config").write_text(f'[remote "origin"]\n\turl = {url}\n')+ _write_claude_session(env["home"], "33333333-0000-0000-0000-000000000003", env["repo"])+ for mode in ("relative", "dirs_only"):+ pipeline.build_all(agents={"claude-code"}, rebuild=True, path_mode=mode, store=Store(env["sm"]))+ (doc,) = list(Store(env["sm"]).docs())+ assert [(r["name"], r["remote"]) for r in doc["repos"]] == [("app", None)], (url, mode)+ assert "someone" not in json.dumps(doc)+ monkeypatch.chdir(env["repo"])+ assert cli.main(["export", "000000000003", "-o", "s.json"]) == 0+ out = capsys.readouterr().out+ assert "repo names (app)" in out and "someone" not in out+++def test_built_maps_validate_against_published_schema(env):+ jsonschema = pytest.importorskip("jsonschema")+ schema_path = Path(__file__).resolve().parents[2] / "schema" / "agentplay-v1.schema.json"+ if not schema_path.is_file():+ pytest.skip("schema/ is only in a repo checkout, not the sdist")+ schema = json.loads(schema_path.read_text())+ _write_claude_session(env["home"], "44444444-0000-0000-0000-000000000004", env["repo"])+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ (doc,) = list(Store(env["sm"]).docs())+ jsonschema.validate(doc, schema)+++def test_cli_import_roundtrip(env, capsys, monkeypatch, tmp_path):+ _write_claude_session(env["home"], "55555555-0000-0000-0000-000000000005", env["repo"])+ monkeypatch.chdir(tmp_path)+ assert cli.main(["build"]) == 0+ assert cli.main(["export", "000000000005", "-o", "m.json.gz"]) == 0+ other = tmp_path / "other"+ monkeypatch.setenv("AGENTPLAY_HOME", str(other))+ assert cli.main(["import", "m.json.gz", "--title", "from a teammate"]) == 0+ (row,) = Store(other).rows()+ assert row["sessionTitle"] == "from a teammate" and row["imported"] == "m.json.gz"+ (tmp_path / "bad.json").write_text('{"schema": "other/v9"}')+ assert cli.main(["import", "bad.json"]) == 1+++# ---------------------------------------------------------------- pasted images+def _png(rgb: tuple[int, int, int]) -> bytes:+ def chunk(kind: bytes, body: bytes) -> bytes:+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))++ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(b"\x00" + bytes(rgb))) + chunk(b"IEND", b""))+++_PNG_A, _PNG_B, _PNG_C, _PNG_D = (_png(c) for c in ((255, 0, 0), (0, 255, 0), (0, 0, 255), (9, 9, 9)))+_JPEG = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xd9"+++def _img(data: bytes, media_type: str = "image/png", *, extra: str = "") -> dict[str, Any]:+ return {"type": "image", "source": {"type": "base64", "media_type": media_type,+ "data": base64.b64encode(data).decode() + extra}}+++def _write_image_session(home: Path, stem: str, cwd: Path, *, sentinel: str = "") -> Path:+ """A transcript whose prompts carry pasted images, plus every record that must not take a turn.++ The builder numbers a user turn from `user_turn_text` alone, so the+ `isSidechain` record and the resumed-session duplicate each take a slot+ (the builder neither dedupes nor looks at `isSidechain`); the meta,+ interruption and harness records do not.+ """+ proj = home / ".claude" / "projects" / "-work-app"+ proj.mkdir(parents=True, exist_ok=True)+ f = proj / f"{stem}.jsonl"++ def user(sec: int, content: Any, **extra: Any) -> str:+ return _line(type="user", timestamp=f"2026-09-10T01:00:{sec:02d}Z", cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": content}, **extra)++ prompt = [{"type": "text", "text": "[Image #2] [Image #3] look at the red and green"},+ _img(_PNG_A, extra=sentinel), _img(_PNG_B)]+ f.write_text("".join([+ user(0, prompt, imagePasteIds=[2, 3]),+ user(1, [{"type": "text", "text": "[Image: source: /private/tmp/x/2.png]"}], isMeta=True),+ _line(type="assistant", timestamp="2026-09-10T01:00:02Z", cwd=str(cwd), sessionId=stem,+ message={"id": "m1", "model": "claude-sonnet-5", "role": "assistant",+ "usage": {"input_tokens": 10, "output_tokens": 5}, "content": [{"type": "text", "text": "ok"}]}),+ user(3, [{"type": "text", "text": "sidechain note"}, _img(_PNG_C)], isSidechain=True),+ user(4, [{"type": "text", "text": "[Request interrupted by user]"}]),+ user(5, [{"type": "text", "text": "compare the jpeg screenshot"}, _img(_JPEG, "image/jpeg")], imagePasteIds=[4]),+ # A resumed session replays the earlier prompt with its original timestamp. The builder+ # numbers turns in timestamp order, so the replay is turn 2 even though it sits later in+ # the file; numbering in file order would point every turn after it at the wrong prompt.+ user(0, prompt, imagePasteIds=[2, 3]),+ user(7, "<task-notification>\n<task-id>abc</task-id>\n</task-notification>"),+ user(8, "a closing prompt with no image"),+ ]))+ return f+++_IMAGE_TURNS = {1: [_PNG_A, _PNG_B], 2: [_PNG_A, _PNG_B], 3: [_PNG_C], 4: [_JPEG]}+++class _Served:+ def __init__(self, httpd: Any, store: Store, row: dict[str, Any], transcript: Path) -> None:+ self.httpd, self.store, self.row, self.transcript = httpd, store, row, transcript+ self.base = f"http://127.0.0.1:{httpd.server_address[1]}"+ self.sid = row["sessionId"]++ def get(self, path: str, headers: dict[str, str] | None = None) -> tuple[int, Any, bytes]:+ req = urllib.request.Request(self.base + path, headers=headers or {})+ try:+ with urllib.request.urlopen(req) as r:+ return r.status, r.headers, r.read()+ except urllib.error.HTTPError as e:+ return e.code, e.headers, e.read()++ def images(self, headers: dict[str, str] | None = None) -> tuple[int, Any, bytes]:+ return self.get(f"/api/prompt-images?id={urllib.request.quote(self.sid, safe='')}", headers)++ def hook(self, uuid: Any, headers: dict[str, str] | None = None) -> tuple[int, Any, bytes]:+ return self.get(f"/api/hook-detail?id={urllib.request.quote(self.sid, safe='')}&uuid={uuid}", headers)++ def image(self, turn: Any, i: Any, headers: dict[str, str] | None = None) -> tuple[int, Any, bytes]:+ return self.get(f"/api/prompt-image?id={urllib.request.quote(self.sid, safe='')}&turn={turn}&i={i}", headers)+++def _serve_image_session(env, *, remote: bool = False, sentinel: str = ""):+ stem = "cccccccc-0000-0000-0000-00000000000c"+ transcript = _write_image_session(env["home"], stem, env["repo"], sentinel=sentinel)+ with _serve_built(env, transcript, remote=remote) as served:+ yield served++def _serve_built(env, transcript: Path, *, remote: bool = False):+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()+ httpd = serve(0, store=st)+ if remote:+ base_handler = httpd.RequestHandlerClass++ class RemoteHandler(base_handler): # type: ignore[valid-type, misc]+ def setup(self) -> None:+ super().setup()+ self.client_address = ("192.168.1.20", 51000)++ httpd.RequestHandlerClass = RemoteHandler+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ try:+ yield _Served(httpd, st, row, transcript)+ finally:+ httpd.shutdown()+ httpd.server_close()+++def pasted(env):+ with _serve_image_session(env) as served:+ yield served+++def test_prompt_image_turns_line_up_with_the_builder_and_task_titles(pasted):+ """Turn k here is `taskTitles[k - 1]` and the k-th `user` event, whatever else is in the file."""+ doc = pasted.store.get(pasted.sid)+ user_events = [e for e in doc["events"] if e["kind"] == "user"]+ titles = pasted.row["taskTitles"]+ assert len(user_events) == len(titles) == 5 # sidechain and replayed prompts count; meta/interrupt/harness do not+ assert titles[2] == "sidechain note" and titles[3] == "compare the jpeg screenshot"++ status, headers, body = pasted.images()+ assert status == 200 and headers["Cache-Control"] == "no-store"+ turns = json.loads(body)["turns"]+ assert json.loads(body)["success"] is True+ assert [t["turn"] for t in turns] == [1, 2, 3, 4]+ for t in turns: # the builder's own per-turn image count agrees+ assert len(t["images"]) == user_events[t["turn"] - 1]["images"]+ assert [im["pasteId"] for im in turns[0]["images"]] == [2, 3]+ assert [im["pasteId"] for im in turns[1]["images"]] == [2, 3] # the replay, numbered by timestamp+ assert [im["pasteId"] for im in turns[2]["images"]] == [None] # no imagePasteIds on that record+ assert turns[3]["images"] == [{"i": 0, "pasteId": 4, "mediaType": "image/jpeg", "available": True}]+ assert all(im["available"] for t in turns for im in t["images"])+ named = server_mod._with_task_titles(doc, pasted.row)+ assert all(t["name"] == titles[t["firstTurn"] - 1] for t in named["tasks"])+ assert {t["firstTurn"] for t in doc["tasks"]} <= {t["turn"] for t in turns} | {5}+++def test_prompt_image_bytes_and_headers(pasted):+ for turn, images in _IMAGE_TURNS.items():+ for i, want in enumerate(images):+ status, headers, body = pasted.image(turn, i)+ assert status == 200 and body == want+ assert headers["Content-Type"] == ("image/jpeg" if want == _JPEG else "image/png")+ assert headers["Content-Length"] == str(len(want))+ assert headers["X-Content-Type-Options"] == "nosniff"+ assert headers["Content-Security-Policy"] == "default-src 'none'; sandbox"+ assert headers["Cross-Origin-Resource-Policy"] == "same-origin"+ assert headers["Cache-Control"] == "private, max-age=3600"++[email protected]("via", ["remote", "host", "origin"])+def test_prompt_images_are_withheld_from_anyone_but_this_machine(env, via):+ """Images are the user's data: a network peer or a DNS-rebinding page gets 403 and nothing else."""+ headers = {"host": {"Host": "evil.example:7317"}, "origin": {"Origin": "https://evil.example"}}.get(via)+ with _serve_image_session(env, remote=via == "remote") as s:+ for status, _, body in (s.images(headers), s.image(1, 0, headers)):+ assert status == 403+ assert json.loads(body) == {"success": False, "code": "forbidden",+ "error": "Only the local viewer can read this."}+ assert s.image(1, 0)[0] == (403 if via == "remote" else 200) # a local viewer is unaffected+++ "query",+ [+ "", "id=", "turn=1&i=0", # missing id+ ],+)+def test_prompt_images_need_a_session_id(pasted, query):+ for path in ("/api/prompt-images", "/api/prompt-image"):+ status, _, body = pasted.get(f"{path}?{query}")+ assert status == 400 and json.loads(body)["code"] == "invalid_input"+++ ("turn", "i"),+ [("", "0"), ("1", ""), ("abc", "0"), ("1", "x"), ("-1", "0"), ("1", "-1"), ("1.5", "0"), ("+1", "0"), ("1", " 0"),+ ("\u0663", "0"), ("9" * 5000, "0")],+)+def test_prompt_image_rejects_malformed_turn_or_index(pasted, turn, i):+ status, _, body = pasted.get(+ f"/api/prompt-image?id={urllib.request.quote(pasted.sid, safe='')}&turn={urllib.request.quote(turn)}&i={urllib.request.quote(i)}"+ )+ assert status == 400 and json.loads(body)["code"] == "invalid_input"+ assert pasted.get(f"/api/prompt-image?id={urllib.request.quote(pasted.sid, safe='')}")[0] == 400++[email protected](("turn", "i"), [(0, 0), (5, 0), (6, 0), (1, 2), (3, 1), (99, 99)])+def test_prompt_image_unknown_turn_or_index_is_404(pasted, turn, i):+ status, _, body = pasted.image(turn, i)+ assert status == 404 and json.loads(body)["code"] == "not_found"+ assert str(pasted.transcript) not in body.decode()+++def test_prompt_images_unknown_session_is_404(pasted):+ for path in ("/api/prompt-images?id=nope", "/api/prompt-image?id=nope&turn=1&i=0"):+ status, _, body = pasted.get(path)+ assert status == 404 and json.loads(body)["code"] == "not_found"+++ "change",+ [{"imported": "m.json.gz"}, {"agentTool": "codex"}, {"agentTool": None}, {"sourcePath": None},+ {"sourcePath": "/etc/passwd"}, {"sourcePath": 7}],+)+def test_prompt_images_only_serve_a_local_claude_code_transcript(pasted, change):+ pasted.store.index[pasted.sid].update(change)+ for status, _, body in (pasted.images(), pasted.image(1, 0)):+ assert status == 404 and json.loads(body)["code"] == "not_found"+ assert str(pasted.transcript) not in body.decode()+++def test_prompt_images_deleted_transcript_is_410(pasted):+ pasted.transcript.unlink()+ for status, _, body in (pasted.images(), pasted.image(1, 0)):+ assert status == 410 and json.loads(body)["code"] == "gone"+ assert str(pasted.transcript) not in body.decode() and str(pasted.transcript.parent) not in body.decode()+++def test_prompt_image_422_for_a_bad_block_never_leaks_the_path(env):+ stem = "dddddddd-0000-0000-0000-00000000000d"+ f = _write_image_session(env["home"], stem, env["repo"])+ f.write_text(f.read_text().replace('"image/jpeg"', '"image/svg+xml"'))+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ st = Store(env["sm"])+ (row,) = st.rows()+ httpd = serve(0, store=st)+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ try:+ s = _Served(httpd, st, row, f)+ assert json.loads(s.images()[2])["turns"][3]["images"][0]["available"] is False+ status, _, body = s.image(4, 0)+ assert status == 422 and json.loads(body)["code"] == "invalid_image"+ assert str(f) not in body.decode()+ finally:+ httpd.shutdown()+ httpd.server_close()+++def test_pasted_image_data_never_reaches_a_map_the_index_or_an_export(env, monkeypatch, tmp_path):+ """Only the `images` count survives a build; the bytes are read from the transcript on demand."""+ sentinel = "SENTINELIMAGEBYTES"+ with _serve_image_session(env, sentinel=sentinel) as s:+ assert sentinel in s.transcript.read_text()+ map_raw = (env["sm"] / "maps" / f"{s.row['key']}.json").read_text()+ index_raw = (env["sm"] / "index.json").read_text()+ monkeypatch.chdir(tmp_path)+ assert cli.main(["export", s.sid[-12:], "-o", "m.json.gz"]) == 0+ export_raw = gzip.decompress((tmp_path / "m.json.gz").read_bytes()).decode()+ for raw in (map_raw, index_raw, export_raw):+ assert sentinel not in raw+ assert base64.b64encode(_PNG_B).decode() not in raw+ assert [e["images"] for e in json.loads(map_raw)["events"] if e["kind"] == "user"] == [2, 2, 1, 1, 0]+++def test_piped_output_in_a_legacy_code_page_does_not_crash(env):+ """Windows pipes fall back to cp1252, which has no `●` or `→`.++ `PYTHONIOENCODING=cp1252` reproduces that on any OS: `agents` crashed+ before, and so did `view` before it ever served.+ """+ proc = subprocess.run(+ [sys.executable, "-m", "agentplay", "agents"],+ env={**os.environ, "PYTHONIOENCODING": "cp1252"},+ capture_output=True,+ timeout=60,+ )+ assert proc.returncode == 0, proc.stderr.decode("utf-8", "replace")+ assert "●".encode() in proc.stdout or "○".encode() in proc.stdout+++def test_utf8_stdio_reencodes_only_a_non_utf8_stream(monkeypatch):+ stream = io.TextIOWrapper(io.BytesIO(), encoding="cp1252")+ monkeypatch.setattr(sys, "stdout", stream)+ cli._utf8_stdio()+ assert sys.stdout.encoding == "utf-8"+ print("● → 日本語")+ sys.stdout.flush()+ assert stream.buffer.getvalue().decode("utf-8").startswith("● → 日本語")++ utf8 = io.TextIOWrapper(io.BytesIO(), encoding="utf-8", errors="strict")+ monkeypatch.setattr(sys, "stdout", utf8)+ cli._utf8_stdio()+ assert utf8.errors == "strict"+++# ---------------------------------------------------------------- hook failure details++_HOOK_BLOCK, _HOOK_WARN, _HOOK_STOP = (f"22222222-0000-0000-0000-00000000000{n}" for n in (1, 2, 3))+_HOOK_TEXT = ("SECRET-HOOK-MSG", "SECRET-HOOK-CMD", "SECRET-HOOK-STDERR", "SECRET-HOOK-WARN-CMD")++def _write_hook_session(home: Path, stem: str, cwd: Path) -> Path:+ proj = home / ".claude" / "projects" / "-work-app"+ proj.mkdir(parents=True, exist_ok=True)+ f = proj / f"{stem}.jsonl"+ day = "2026-09-10"+ hook = {"type": "attachment", "cwd": str(cwd), "sessionId": stem}+ f.write_text("".join([+ _line(type="user", timestamp=f"{day}T01:00:00Z", cwd=str(cwd), sessionId=stem, uuid="33333333-0000-0000-0000-000000000001",+ message={"role": "user", "content": "go"}),+ _line(type="assistant", timestamp=f"{day}T01:00:01Z", cwd=str(cwd), sessionId=stem,+ message={"id": "m1", "model": "claude-sonnet-5", "role": "assistant",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ "content": [{"type": "tool_use", "id": "r1", "name": "Read",+ "input": {"file_path": f"{cwd}/src/app.py"}}]}),+ _line(type="user", timestamp=f"{day}T01:00:02Z", cwd=str(cwd), sessionId=stem,+ message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": "r1", "content": "x = 1"}]}),+ _line(**hook, timestamp=f"{day}T01:00:03Z", uuid=_HOOK_BLOCK, attachment={+ "type": "hook_blocking_error", "hookName": "PostToolUse:Read", "hookEvent": "PostToolUse", "toolUseID": "r1",+ "blockingError": {"blockingError": "SECRET-HOOK-MSG" + "x" * 5000, "command": "SECRET-HOOK-CMD"}}),+ _line(**hook, timestamp=f"{day}T01:00:04Z", uuid=_HOOK_WARN, attachment={+ "type": "hook_non_blocking_error", "hookName": "PostToolUse:Read", "hookEvent": "PostToolUse", "toolUseID": "r1",+ "command": "SECRET-HOOK-WARN-CMD", "stderr": "SECRET-HOOK-STDERR", "stdout": "", "exitCode": 1}),+ _line(**hook, timestamp=f"{day}T01:00:05Z", uuid=_HOOK_STOP, attachment={+ "type": "hook_blocking_error", "hookName": "Stop", "hookEvent": "Stop", "toolUseID": "turn-1",+ "blockingError": {"blockingError": "stop msg", "command": "stop cmd"}}),+ ]))+ return f++def _serve_hook_session(env, *, remote: bool = False):+ transcript = _write_hook_session(env["home"], "eeeeeeee-0000-0000-0000-00000000000e", env["repo"])+ with _serve_built(env, transcript, remote=remote) as served:+ yield served++def hooked(env):+ with _serve_hook_session(env) as served:+ yield served++def test_hook_detail_reads_message_and_command_from_the_transcript(hooked):+ status, _, body = hooked.hook(_HOOK_BLOCK)+ got = json.loads(body)+ assert status == 200 and got["success"] is True and set(got) == {"success", "message", "command"}+ assert got["message"].startswith("SECRET-HOOK-MSG") and len(got["message"]) == 4000 # capped+ assert got["command"] == "SECRET-HOOK-CMD"+ # A non-blocking failure's message is its stderr.+ assert json.loads(hooked.hook(_HOOK_WARN)[2]) == {+ "success": True, "message": "SECRET-HOOK-STDERR", "command": "SECRET-HOOK-WARN-CMD"}++def test_hook_detail_matches_the_map_events(hooked):+ evs = [e for e in hooked.store.get(hooked.sid)["events"] if e.get("source") == "hook"]+ assert {e["srcUuid"] for e in evs} == {_HOOK_BLOCK, _HOOK_WARN, _HOOK_STOP}+ read = next(e for e in hooked.store.get(hooked.sid)["events"] if e["kind"] == "read")+ assert {e["srcUuid"]: e.get("ref") for e in evs} == {+ _HOOK_BLOCK: read["seq"], _HOOK_WARN: read["seq"], _HOOK_STOP: None}+ assert all(hooked.hook(e["srcUuid"])[0] == 200 for e in evs)+[email protected]("via", ["remote", "host", "origin"])+def test_hook_detail_is_withheld_from_anyone_but_this_machine(env, via):+ headers = {"host": {"Host": "evil.example:7317"}, "origin": {"Origin": "https://evil.example"}}.get(via)+ with _serve_hook_session(env, remote=via == "remote") as s:+ status, _, body = s.hook(_HOOK_BLOCK, headers)+ assert status == 403+ assert json.loads(body) == {"success": False, "code": "forbidden",+ "error": "Only the local viewer can read this."}+ assert not any(t in body.decode() for t in _HOOK_TEXT)+ assert s.hook(_HOOK_BLOCK)[0] == (403 if via == "remote" else 200)+[email protected]("uuid", ["", "a%20b", "..%2Fx", "x" * 65, "%00"])+def test_hook_detail_rejects_a_malformed_uuid(hooked, uuid):+ status, _, body = hooked.hook(uuid)+ assert status == 400 and json.loads(body)["code"] == "invalid_input"++def test_hook_detail_needs_a_session_id(hooked):+ assert hooked.get(f"/api/hook-detail?uuid={_HOOK_BLOCK}")[0] == 400+[email protected]("uuid", ["33333333-0000-0000-0000-000000000001", "44444444-0000-0000-0000-000000000009"])+def test_hook_detail_unknown_uuid_or_a_non_hook_record_is_404(hooked, uuid):+ status, _, body = hooked.hook(uuid) # the first is a real record, but a user turn+ assert status == 404 and json.loads(body)["code"] == "not_found"+ assert str(hooked.transcript) not in body.decode()+[email protected]("change", [{"imported": "m.json.gz"}, {"agentTool": "codex"}, {"sourcePath": None},+ {"sourcePath": "/etc/passwd"}])+def test_hook_detail_only_serves_a_local_claude_code_transcript(hooked, change):+ hooked.store.index[hooked.sid].update(change)+ status, _, body = hooked.hook(_HOOK_BLOCK)+ assert status == 404 and json.loads(body)["code"] == "not_found"++def test_hook_detail_deleted_transcript_is_410_without_a_path(hooked):+ hooked.transcript.unlink()+ status, _, body = hooked.hook(_HOOK_BLOCK)+ assert status == 410 and json.loads(body)["code"] == "gone"+ assert str(hooked.transcript.parent) not in body.decode()++def test_hook_detail_follows_a_transcript_that_changes(hooked):+ assert hooked.hook(_HOOK_STOP)[0] == 200+ lines = hooked.transcript.read_text().splitlines(keepends=True)+ hooked.transcript.write_text("".join(lines[:-1])) # drop the Stop record: the cached scan must not serve it+ assert hooked.hook(_HOOK_STOP)[0] == 404++def test_hook_text_never_reaches_a_map_the_index_or_an_export(env, monkeypatch, tmp_path):+ """Only the hook name, its event and the opaque record id survive a build."""+ with _serve_hook_session(env) as s:+ assert all(t in s.transcript.read_text() for t in _HOOK_TEXT)+ map_raw = (env["sm"] / "maps" / f"{s.row['key']}.json").read_text()+ index_raw = (env["sm"] / "index.json").read_text()+ monkeypatch.chdir(tmp_path)+ assert cli.main(["export", s.sid[-12:], "-o", "m.json.gz"]) == 0+ export_raw = gzip.decompress((tmp_path / "m.json.gz").read_bytes()).decode()+ for raw in (map_raw, index_raw, export_raw):+ assert not any(t in raw for t in _HOOK_TEXT)+ assert "stop msg" not in raw and "stop cmd" not in raw+ assert _HOOK_BLOCK in map_raw and _HOOK_BLOCK not in index_raw++def test_hook_detail_finds_a_subagent_hook_in_its_own_transcript(hooked):+ sub = hooked.transcript.with_suffix("") / "subagents"+ sub.mkdir(parents=True)+ uuid = "55555555-0000-0000-0000-000000000005"+ (sub / "agent-abc.jsonl").write_text(_line(type="attachment", uuid=uuid, attachment={+ "type": "hook_blocking_error", "hookName": "Stop", "hookEvent": "Stop",+ "blockingError": {"blockingError": "sub msg", "command": "sub cmd"}}))+ assert json.loads(hooked.hook(uuid)[2]) == {"success": True, "message": "sub msg", "command": "sub cmd"}+++def test_maps_built_by_another_version_are_rebuilt_once(env, monkeypatch):+ """A redaction fix must reach maps already on disk, not only new sessions."""+ _write_claude_session(env["home"], "12121212-0000-0000-0000-000000000012", env["repo"])+ assert pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"])).built == 1+ assert pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"])).unchanged == 1++ # An index written by an older agentplay (no builtWith, or a different one).+ st = Store(env["sm"])+ for row in st.index.values():+ row.pop("builtWith", None)+ st.save_index()+ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert (rep.built, rep.unchanged) == (1, 0)++ monkeypatch.setattr(pipeline, "__version__", "9.9.9")+ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert (rep.built, rep.unchanged) == (1, 0)+ assert all(r["builtWith"] == "9.9.9" for r in Store(env["sm"]).index.values())+ assert pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"])).unchanged == 1+++def test_a_new_path_mode_re_redacts_fresh_maps(env, monkeypatch):+ """Asking for dirs_only (or hashed without a key) must reach maps already built."""+ monkeypatch.delenv("AGENTPLAY_HMAC_KEY", raising=False)+ _write_claude_session(env["home"], "13131313-0000-0000-0000-000000000013", env["repo"])+ assert pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"])).built == 1+ for mode in ("dirs_only", "hashed"):+ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]), path_mode=mode)+ st = Store(env["sm"])+ doc = st.get(next(iter(st.index)))+ assert doc["session"]["pathMode"] == "dirs_only"+ assert doc["files"] and all("•" in f["path"] for f in doc["files"]), mode+ assert rep.built == (1 if mode == "dirs_only" else 0) # hashed w/o key == dirs_only: fresh+ rep = pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))+ assert rep.built == 1 # back to relativediff --git a/python/tests/test_materialize_warnings.py b/python/tests/test_materialize_warnings.pynew file mode 100644index 0000000..fbd0897--- /dev/null+++ b/python/tests/test_materialize_warnings.py@@ -0,0 +1,50 @@+"""A broken transcript database is reported once per run, not silently and not per session."""++from __future__ import annotations++import logging++import pytest++from agentplay import materialize+from agentplay.materialize import AgentKind, HomeSpec++[email protected](autouse=True)+def _fresh_warnings(monkeypatch):+ monkeypatch.setattr(materialize, "_warned", set())+++def _warnings(caplog) -> list[str]:+ return [r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING]+++def test_unreadable_opencode_db_warns_once_without_the_full_path(tmp_path, caplog):+ home = tmp_path / "opencode"+ home.mkdir()+ (home / "opencode.db").write_bytes(b"this is not a sqlite database" * 20)+ spec = HomeSpec(AgentKind.OPENCODE, home)+ caplog.set_level(logging.DEBUG, logger="agentplay.materialize")++ for _ in range(2): # a rescan in the same process stays quiet+ assert list(materialize.find_opencode_candidates(spec, cache_root=tmp_path / "c")) == []++ (message,) = _warnings(caplog)+ assert "opencode" in message and "opencode.db" in message+ assert str(tmp_path) not in message+++def test_unreadable_cursor_store_db_warns_once(tmp_path, caplog):+ home = tmp_path / ".cursor"+ store = home / "chats" / "h" / "agent-1" / "store.db"+ store.parent.mkdir(parents=True)+ store.write_bytes(b"this is not a sqlite database" * 20)+ spec = HomeSpec(AgentKind.CURSOR, home)+ caplog.set_level(logging.DEBUG, logger="agentplay.materialize")++ for _ in range(2):+ list(materialize.find_cursor_store_candidates(spec, cache_root=tmp_path / "c"))++ (message,) = _warnings(caplog)+ assert "cursor_store" in message and "store.db" in message+ assert str(tmp_path) not in messagediff --git a/python/tests/test_prompt_images.py b/python/tests/test_prompt_images.pynew file mode 100644index 0000000..2191a0f--- /dev/null+++ b/python/tests/test_prompt_images.py@@ -0,0 +1,241 @@+"""Reading pasted images out of a Claude Code transcript: validation, caching, staleness."""++from __future__ import annotations++import base64+import json+import os+import struct+import zlib+from pathlib import Path+from typing import Any++import pytest++from agentplay import prompt_images as pi+++def _png(rgb: tuple[int, int, int] = (255, 0, 0)) -> bytes:+ def chunk(kind: bytes, body: bytes) -> bytes:+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))++ ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)+ idat = zlib.compress(b"\x00" + bytes(rgb))+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")+++JPEG = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xd9"+GIF = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"+WEBP = b"RIFF\x1a\x00\x00\x00WEBPVP8L\x0d\x00\x00\x00/\x00\x00\x00\x10\x07\x10\x11\x11\x88\x88\xfe\x07\x00"+++def _b64(data: bytes) -> str:+ return base64.b64encode(data).decode()+++def _block(data: bytes | str, media_type: str = "image/png", source_type: str = "base64") -> dict[str, Any]:+ return {"type": "image", "source": {"type": source_type, "media_type": media_type,+ "data": data if isinstance(data, str) else _b64(data)}}+++def _prompt(n: int, *blocks: dict[str, Any], text: str = "look", **extra: Any) -> str:+ rec = {"type": "user", "timestamp": f"2026-09-10T01:00:{n:02d}Z", "sessionId": "s",+ "message": {"role": "user", "content": [{"type": "text", "text": text}, *blocks]}, **extra}+ return json.dumps(rec) + "\n"+++def _write(tmp_path: Path, *lines: str) -> str:+ f = tmp_path / "t.jsonl"+ f.write_text("".join(lines))+ return str(f)+++ ("data", "want"),+ [+ (_png(), "image/png"),+ (JPEG, "image/jpeg"),+ (GIF, "image/gif"),+ (b"GIF87a" + b"\x00" * 8, "image/gif"),+ (WEBP, "image/webp"),+ (b"RIFF\x00\x00\x00\x00WAVEfmt ", None),+ (b"RIFF\x00\x00\x00", None),+ (b"\x89PNG\r\n", None),+ (b"<svg xmlns=", None),+ (b"", None),+ ],+)+def test_sniff(data, want):+ assert pi._sniff(data) == want+++def test_list_and_read_round_trip(tmp_path):+ a, b = _png((1, 2, 3)), _png((4, 5, 6))+ path = _write(tmp_path, _prompt(0, _block(a), _block(JPEG, "image/jpeg"), imagePasteIds=[7, 8]),+ _prompt(1, text="no images", **{}), _prompt(2, _block(b), imagePasteIds=[9]))+ assert pi.list_images(path) == [+ {"turn": 1, "images": [{"i": 0, "pasteId": 7, "mediaType": "image/png", "available": True},+ {"i": 1, "pasteId": 8, "mediaType": "image/jpeg", "available": True}]},+ {"turn": 3, "images": [{"i": 0, "pasteId": 9, "mediaType": "image/png", "available": True}]},+ ]+ assert pi.read_image(path, 1, 0) == ("image/png", a)+ assert pi.read_image(path, 1, 1) == ("image/jpeg", JPEG)+ assert pi.read_image(path, 3, 0) == ("image/png", b)+++ ("ids", "want"),+ [([1], [None, None]), (["1", "2"], [None, None]), ([True, False], [None, None]), (None, [None, None]),+ ([4, 5], [4, 5])],+)+def test_paste_ids_only_when_they_pair_up(tmp_path, ids, want):+ extra = {} if ids is None else {"imagePasteIds": ids}+ path = _write(tmp_path, _prompt(0, _block(_png()), _block(_png()), **extra))+ (turn,) = pi.list_images(path)+ assert [im["pasteId"] for im in turn["images"]] == want+++ "block",+ [+ _block(JPEG, "image/png"), # declared png, bytes are jpeg+ _block("!!!not base64!!!"),+ _block(_png(), "image/svg+xml"),+ _block(_png(), "text/html"),+ ],+)+def test_invalid_images_are_listed_unavailable_and_refused_with_422(tmp_path, block):+ path = _write(tmp_path, _prompt(0, block))+ (turn,) = pi.list_images(path)+ assert turn["images"][0]["available"] is False+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(path, 1, 0)+ assert (err.value.status, err.value.code) == (422, "invalid_image")+ assert path not in err.value.message+++def test_invalid_base64_is_refused_even_when_the_prefix_looks_right(tmp_path):+ data = _b64(_png()) + "!!!!"+ path = _write(tmp_path, _prompt(0, _block(data)))+ assert pi.list_images(path)[0]["images"][0]["available"] is True # only a prefix is sniffed+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(path, 1, 0)+ assert err.value.status == 422+++def test_non_base64_source_is_unavailable_and_404(tmp_path):+ path = _write(tmp_path, _prompt(0, {"type": "image", "source": {"type": "url", "url": "https://x/y.png"}}))+ assert pi.list_images(path) == [+ {"turn": 1, "images": [{"i": 0, "pasteId": None, "mediaType": None, "available": False}]}+ ]+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(path, 1, 0)+ assert (err.value.status, err.value.code) == (404, "not_found")+++def test_oversize_is_refused_before_decoding(tmp_path, monkeypatch):+ path = _write(tmp_path, _prompt(0, _block(_png())))+ pi.list_images(path) # scan first: it sniffs a prefix with b64decode, which is fine+ monkeypatch.setattr(pi, "MAX_IMAGE_BYTES", 8)++ def boom(*_a: Any, **_k: Any) -> bytes:+ raise AssertionError("decoded an oversize image")++ monkeypatch.setattr(pi.base64, "b64decode", boom)+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(path, 1, 0)+ assert (err.value.status, err.value.code) == (422, "invalid_image")++[email protected](("turn", "index"), [(0, 0), (2, 0), (1, 1), (1, 99)])+def test_unknown_turn_or_index_is_404(tmp_path, turn, index):+ path = _write(tmp_path, _prompt(0, _block(_png())))+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(path, turn, index)+ assert err.value.status == 404+++def test_missing_transcript_is_410(tmp_path):+ path = str(tmp_path / "gone.jsonl")+ for call in (lambda: pi.list_images(path), lambda: pi.read_image(path, 1, 0)):+ with pytest.raises(pi.Unavailable) as err:+ call()+ assert (err.value.status, err.value.code) == (410, "gone")+++def test_a_transcript_that_grows_is_rescanned(tmp_path):+ f = tmp_path / "t.jsonl"+ f.write_text(_prompt(0, _block(_png())))+ assert [t["turn"] for t in pi.list_images(str(f))] == [1]+ misses = pi._scan.cache_info().misses+ pi.list_images(str(f))+ assert pi._scan.cache_info().misses == misses # unchanged file: served from cache+ with f.open("a") as fh:+ fh.write(_prompt(1, _block(JPEG, "image/jpeg")))+ assert [t["turn"] for t in pi.list_images(str(f))] == [1, 2]+ assert pi.read_image(str(f), 2, 0) == ("image/jpeg", JPEG)+++def test_a_stale_cached_line_is_rechecked_not_trusted(tmp_path):+ """The file changes under an unchanged (mtime, size) key: the read re-parses and refuses."""+ f = tmp_path / "t.jsonl"+ f.write_bytes(_prompt(0, _block(_png())).encode())+ st = f.stat()+ assert pi.list_images(str(f))[0]["turn"] == 1+ replacement = json.dumps({"type": "user", "timestamp": "2026-09-10T01:00:00Z",+ "message": {"role": "user", "content": [{"type": "text", "text": "x"}]}})+ f.write_bytes((replacement.ljust(st.st_size - 1) + "\n").encode())+ os.utime(f, ns=(st.st_atime_ns, st.st_mtime_ns))+ assert f.stat().st_size == st.st_size+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(str(f), 1, 0)+ assert err.value.status == 404+++def test_only_user_turns_count(tmp_path):+ """Meta, interruption and tool-result records take no turn number, as in the builder."""+ meta = {"type": "user", "isMeta": True, "timestamp": "2026-09-10T01:00:01Z",+ "message": {"role": "user", "content": [{"type": "text", "text": "[Image: source: /tmp/2.png]"}]}}+ interrupted = {"type": "user", "timestamp": "2026-09-10T01:00:02Z",+ "message": {"role": "user", "content": [{"type": "text", "text": "[Request interrupted by user]"}]}}+ path = _write(tmp_path, _prompt(0, _block(_png())), json.dumps(meta) + "\n", "not json\n",+ json.dumps(interrupted) + "\n", _prompt(3, _block(JPEG, "image/jpeg")))+ assert [t["turn"] for t in pi.list_images(path)] == [1, 2]++[email protected]("media_type", [["image/png"], {"t": "image/png"}, None, 7])+def test_a_non_string_media_type_is_unavailable_not_a_crash(tmp_path, media_type):+ block = _block(_png())+ block["source"]["media_type"] = media_type+ path = _write(tmp_path, _prompt(0, block))+ assert pi.list_images(path)[0]["images"][0]["available"] is False+ with pytest.raises(pi.Unavailable) as err:+ pi.read_image(path, 1, 0)+ assert (err.value.status, err.value.code) == (422, "invalid_image")+++def test_an_image_exactly_at_the_size_cap_is_served(tmp_path, monkeypatch):+ png = _png() + b"\0" # trailing byte: the base64 now ends in padding+ assert base64.b64encode(png).endswith(b"=") # padding must not count toward the size+ path = _write(tmp_path, _prompt(0, _block(png)))+ monkeypatch.setattr(pi, "MAX_IMAGE_BYTES", len(png))+ assert pi.read_image(path, 1, 0) == ("image/png", png)+++def test_hook_detail_record_replaced_by_non_object_json_is_not_found(tmp_path):+ """The line changes under an unchanged (mtime, size) key: a JSON `null` is a miss, not a 500."""+ from agentplay import hook_detail++ rec = {"type": "attachment", "uuid": "u-1", "timestamp": "2026-09-10T01:00:00Z",+ "attachment": {"type": "hook_blocking_error", "hookName": "Stop", "hookEvent": "Stop",+ "blockingError": {"blockingError": "msg", "command": "cmd"}}}+ f = tmp_path / "t.jsonl"+ f.write_bytes((json.dumps(rec) + "\n").encode())+ st = f.stat()+ assert hook_detail.read_hook_detail(str(f), "u-1") == ("msg", "cmd")+ f.write_bytes(("null".ljust(st.st_size - 1) + "\n").encode())+ os.utime(f, ns=(st.st_atime_ns, st.st_mtime_ns))+ assert f.stat().st_size == st.st_size+ with pytest.raises(pi.Unavailable) as err:+ hook_detail.read_hook_detail(str(f), "u-1")+ assert err.value.status == 404diff --git a/python/tests/test_robustness.py b/python/tests/test_robustness.pynew file mode 100644index 0000000..6134bc6--- /dev/null+++ b/python/tests/test_robustness.py@@ -0,0 +1,325 @@+"""Malformed input and races that must degrade to a clean answer, never a crash."""++from __future__ import annotations++import base64+import hashlib+import http.client+import json+import socket+import threading+import time+from pathlib import Path+from typing import Any++import pytest++from agentplay import builder, cli, discover, hook_detail, pipeline+from agentplay import prompt_images as pi+from agentplay import server as server_mod+from agentplay.server import serve+from agentplay.store import Store++# ---------------------------------------------------------------- prompt text+++def _user(n: int, content: Any) -> str:+ rec = {"type": "user", "timestamp": f"2026-09-10T01:00:{n:02d}Z", "sessionId": "s",+ "message": {"role": "user", "content": content}}+ return json.dumps(rec) + "\n"+++BAD_TEXT = [{"type": "text", "text": None}, {"type": "text", "text": 7}, {"type": "text"}]+++def _transcript(tmp_path: Path) -> Path:+ f = tmp_path / "s.jsonl"+ f.write_text(+ _user(1, [{"type": "text", "text": "first"}, *BAD_TEXT])+ + _user(2, BAD_TEXT)+ + _user(3, "third")+ )+ return f+++def test_user_turns_skip_non_string_text_blocks(tmp_path) -> None:+ with open(_transcript(tmp_path), encoding="utf-8") as fh:+ turns = builder.user_turns(fh)+ assert [text for _, _, text in turns] == ["first", "third"]+++def test_claude_code_map_survives_non_string_text_blocks(tmp_path) -> None:+ doc = builder.build_claude_code_map(_transcript(tmp_path))+ assert sum(1 for e in doc["events"] if e["kind"] == "user") == 2+++def test_local_task_titles_survive_non_string_text_blocks(tmp_path) -> None:+ c = discover.Candidate("s", "claude-code", str(_transcript(tmp_path)), 0.0)+ assert discover.local_task_titles(c) == ["first", "third"]+++def test_first_prompt_title_ignores_non_string_text_blocks(tmp_path) -> None:+ f = tmp_path / "t.jsonl"+ f.write_text(_user(1, [*BAD_TEXT, {"type": "text", "text": "real prompt"}]))+ c = discover.Candidate("s", "claude-code", str(f), 0.0)+ assert discover.local_title(c) == "real prompt"+++# ---------------------------------------------------------------- store.index+++def test_index_is_never_none_when_another_thread_invalidates_it(tmp_path, monkeypatch) -> None:+ st = Store(tmp_path)+ real = st._disk_stamp++ def invalidating() -> tuple[int, int] | None:+ st._index = None # what `reload_if_changed` does from another thread+ return real()++ monkeypatch.setattr(st, "_disk_stamp", invalidating)+ for _ in range(50):+ st._index = None+ assert st.index == {}+++# ---------------------------------------------------------------- server+++def httpd(tmp_path):+ server = serve(0, store=Store(tmp_path))+ threading.Thread(target=server.serve_forever, daemon=True).start()+ try:+ yield server+ finally:+ server.shutdown()+ server.server_close()+++def _request(server, method: str, headers: dict[str, str]) -> tuple[int, Any]:+ conn = http.client.HTTPConnection("127.0.0.1", server.server_address[1], timeout=5)+ conn.putrequest(method, "/api/account" if method == "POST" else "/api/status", skip_host=True)+ for k, v in headers.items():+ conn.putheader(k, v)+ conn.putheader("Content-Length", "2")+ conn.endheaders(b"{}")+ resp = conn.getresponse()+ body = json.loads(resp.read())+ conn.close()+ return resp.status, body++[email protected]("host", ["[::1", "[::1:80", "a]b", "localhost:99999", "localhost:abc"])+def test_malformed_host_is_403_json(httpd, host) -> None:+ for method in ("GET", "POST"):+ status, body = _request(httpd, method, {"Host": host})+ assert status == 403+ assert body["code"] == "forbidden"++[email protected]("origin", ["http://[::1", "http://a]b", "http://localhost:99999"])+def test_malformed_origin_is_403_json(httpd, origin) -> None:+ for method in ("GET", "POST"):+ status, body = _request(httpd, method, {"Host": "localhost", "Origin": origin})+ assert status == 403+ assert body["code"] == "forbidden"+++def test_local_host_with_a_valid_port_still_passes(httpd) -> None:+ status, _ = _request(httpd, "GET", {"Host": "localhost:7317"})+ assert status == 200+++_THEME = b"document.documentElement.dataset.theme = 'dark';"+++def site(tmp_path, monkeypatch):+ """A server over a stand-in viewer bundle with one inline script, like the real index.html."""+ static = tmp_path / "viewer"+ (static / "assets").mkdir(parents=True)+ (static / "index.html").write_bytes(b"<!doctype html><script>" + _THEME + b"</script><div id=root></div>")+ (static / "assets" / "app.js").write_text("console.log(1)")+ sibling = tmp_path / "viewer-private" # shares the bundle dir's name as a prefix+ sibling.mkdir()+ (sibling / "secret.txt").write_text("SECRET")+ monkeypatch.setattr(server_mod, "viewer_root", lambda: static)+ server = serve(0, store=Store(tmp_path / "sm"))+ threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ try:+ yield server+ finally:+ server.shutdown()+ server.server_close()+++def _get(server, path: str, headers: dict[str, str] | None = None, method: str = "GET"):+ conn = http.client.HTTPConnection("127.0.0.1", server.server_address[1], timeout=5)+ conn.request(method, path, headers=headers or {})+ resp = conn.getresponse()+ body = resp.read()+ conn.close()+ return resp.status, resp.headers, body++[email protected](("path", "method"), [+ ("/", "GET"), ("/assets/app.js", "GET"), ("/api/status", "GET"), ("/api/nope", "GET"),+ ("/api/status", "PUT"), # http.server's own 501 page+])+def test_every_response_carries_the_security_headers(site, path, method) -> None:+ _, headers, _ = _get(site, path, method=method)+ assert headers["X-Content-Type-Options"] == "nosniff"+ assert headers["X-Frame-Options"] == "DENY"+ assert headers["Referrer-Policy"] == "no-referrer"+++def test_the_page_csp_allows_only_its_own_inline_script(site) -> None:+ status, headers, body = _get(site, "/")+ assert status == 200 and _THEME in body+ csp = headers["Content-Security-Policy"]+ for directive in ("default-src 'self'", "frame-ancestors 'none'", "base-uri 'none'", "object-src 'none'"):+ assert directive in csp+ digest = base64.b64encode(hashlib.sha256(_THEME).digest()).decode()+ assert f"script-src 'self' 'sha256-{digest}';" in csp+ assert "unsafe-eval" not in csp and "script-src 'self' 'unsafe-inline'" not in csp+++def test_json_is_same_origin_only(site) -> None:+ _, headers, _ = _get(site, "/api/status")+ assert headers["Cross-Origin-Resource-Policy"] == "same-origin"+ assert "frame-ancestors 'none'" in headers["Content-Security-Policy"]++[email protected](("site_header", "status"), [+ (None, 200), ("same-origin", 200), ("none", 200), ("same-site", 403), ("cross-site", 403),+])+def test_only_same_origin_fetches_read_the_api(site, site_header, status) -> None:+ headers = {"Sec-Fetch-Site": site_header} if site_header else {}+ assert _get(site, "/api/status", headers)[0] == status+ # A link from anywhere still opens the page itself.+ assert _get(site, "/", headers)[0] == 200++[email protected]("payload", [b'{"o":1e999}', b'{"o":"x"}', b"[]", b"not json"])+def test_a_bad_cursor_is_400(site, payload) -> None:+ cursor = base64.urlsafe_b64encode(payload).decode().rstrip("=")+ status, _, body = _get(site, f"/api/sessions?cursor={cursor}")+ assert status == 400 and json.loads(body)["code"] == "invalid_input"+++def test_a_path_too_long_for_the_filesystem_gets_the_page(site) -> None:+ status, _, body = _get(site, "/" + "a" * 5000)+ assert status == 200 and _THEME in body+++def test_static_files_stay_inside_the_bundle(site) -> None:+ status, _, body = _get(site, "/../viewer-private/secret.txt")+ assert status == 200 and b"SECRET" not in body and _THEME in body+++def test_server_takes_a_burst_and_drops_a_stalled_client(site) -> None:+ assert site.request_queue_size == 128+ assert server_mod._Handler.timeout == 15+ site.RequestHandlerClass.timeout = 0.2+ stalled = socket.create_connection(("127.0.0.1", site.server_address[1]))+ stalled.sendall(b"GET /api/status HTTP/1.1\r\n") # and never finishes+ stalled.settimeout(5)+ started = time.monotonic()+ assert stalled.recv(1024) == b"" # the server hung up+ assert time.monotonic() - started < 4+ stalled.close()+++def test_store_never_reads_outside_maps(tmp_path) -> None:+ st = Store(tmp_path)+ st.put({"session": {"id": "s1"}}, {"sessionId": "s1"})+ (tmp_path / "outside.json").write_text('{"leaked": true}')+ assert st.get("s1") == {"session": {"id": "s1"}}+ for key in ("../outside", "/etc/passwd", "a/../../outside-0123456789", None, 7):+ st.index["bad"] = {"sessionId": "bad", "key": key}+ assert st.get("bad") is None+ # A well-formed key that is a symlink out of maps/ is refused too.+ link = st.maps_dir / "evil-0123456789.json"+ link.symlink_to(tmp_path / "outside.json")+ st.index["bad"] = {"sessionId": "bad", "key": "evil-0123456789"}+ assert st.get("bad") is None+++# ---------------------------------------------------------------- transcript races+++def _png_turn(tmp_path: Path) -> str:+ block = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo="}}+ f = tmp_path / "t.jsonl"+ f.write_text(_user(1, [{"type": "text", "text": "look"}, block]))+ return str(f)+++ ("exc", "status"), [(FileNotFoundError(), 410), (PermissionError(), 404)]+)+def test_prompt_images_scan_open_failure_after_stat(tmp_path, monkeypatch, exc, status) -> None:+ path = _png_turn(tmp_path)+ pi._scan.cache_clear()++ def boom(*_a, **_k):+ raise exc++ monkeypatch.setattr("builtins.open", boom)+ with pytest.raises(pi.Unavailable) as e:+ pi.list_images(path)+ assert e.value.status == status+++ ("exc", "status"), [(FileNotFoundError(), 410), (PermissionError(), 404)]+)+def test_prompt_image_read_open_failure_after_scan(tmp_path, monkeypatch, exc, status) -> None:+ path = _png_turn(tmp_path)+ pi.list_images(path) # warm the scan cache++ def boom(*_a, **_k):+ raise exc++ monkeypatch.setattr("builtins.open", boom)+ with pytest.raises(pi.Unavailable) as e:+ pi.read_image(path, 1, 0)+ assert e.value.status == status+++def test_hook_detail_unreadable_transcript_is_404(tmp_path, monkeypatch) -> None:+ f = tmp_path / "t.jsonl"+ f.write_text("{}\n")+ hook_detail._scan.cache_clear()++ def boom(*_a, **_k):+ raise PermissionError++ monkeypatch.setattr("builtins.open", boom)+ with pytest.raises(hook_detail.Unavailable) as e:+ hook_detail.read_hook_detail(str(f), "u")+ assert e.value.status == 404+++# ---------------------------------------------------------------- cli -v+++def _report(**kw: Any) -> pipeline.BuildReport:+ base = {"found": 1, "built": 0, "unchanged": 0, "skipped": 0, "failed": 1, "seconds": 0.0,+ "errors": ["s1: boom"]}+ return pipeline.BuildReport(**{**base, **kw})++[email protected]("argv", [["-v", "build"], ["build", "-v"], ["build", "--verbose"]])+def test_verbose_is_accepted_before_or_after_the_subcommand(monkeypatch, capsys, argv) -> None:+ monkeypatch.setattr(cli.pipeline, "build_all", lambda **_kw: _report())+ monkeypatch.setattr(cli, "_configure_logging", lambda verbose: None)+ assert cli.main(argv) == 0+ assert "s1: boom" in capsys.readouterr().out+++def test_failures_are_hidden_without_verbose(monkeypatch, capsys) -> None:+ monkeypatch.setattr(cli.pipeline, "build_all", lambda **_kw: _report())+ monkeypatch.setattr(cli, "_configure_logging", lambda verbose: None)+ assert cli.main(["build"]) == 0+ assert "s1: boom" not in capsys.readouterr().outdiff --git a/schema/agentplay-v1.schema.json b/schema/agentplay-v1.schema.jsonnew file mode 100644index 0000000..44fa818--- /dev/null+++ b/schema/agentplay-v1.schema.json@@ -0,0 +1,1067 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/Entelligence-AI/agentplay/schema/agentplay-v1.schema.json",+ "title": "agentplay/v1",+ "description": "A redacted, chronological replay of one coding-agent session. Contains no prompt text, model output, tool inputs or outputs, file contents or command arguments. See docs/format.md.",+ "type": "object",+ "required": [+ "schema",+ "session",+ "totals",+ "events"+ ],+ "properties": {+ "schema": {+ "enum": [+ "agentplay/v1",+ "entelligence.session-map/v1"+ ]+ },+ "session": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "agentTool": {+ "type": [+ "string",+ "null"+ ],+ "description": "claude-code | codex | cursor | copilot | copilot-vscode | opencode | kiro | ..."+ },+ "cliVersion": {+ "type": [+ "string",+ "null"+ ]+ },+ "startedAt": {+ "type": "string",+ "format": "date-time"+ },+ "durationMs": {+ "type": [+ "number",+ "null"+ ]+ },+ "models": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "pathMode": {+ "enum": [+ "relative",+ "dirs_only",+ "hashed",+ null+ ]+ },+ "truncated": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "outcome": {+ "type": [+ "string",+ "null"+ ],+ "description": "pr_created | verified | blocked | interrupted | unresolved_errors | completed | incomplete"+ },+ "role": {+ "type": [+ "string",+ "null"+ ],+ "description": "root | subagent | helper | unknown"+ },+ "parentSessionId": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "id",+ "startedAt"+ ]+ },+ "totals": {+ "type": "object",+ "properties": {+ "calls": {+ "type": [+ "number",+ "null"+ ]+ },+ "requests": {+ "type": [+ "number",+ "null"+ ]+ },+ "userTurns": {+ "type": [+ "number",+ "null"+ ]+ },+ "subagents": {+ "type": [+ "number",+ "null"+ ]+ },+ "errors": {+ "type": [+ "number",+ "null"+ ]+ },+ "tokens": {+ "type": [+ "number",+ "null"+ ]+ },+ "costUsd": {+ "type": [+ "number",+ "null"+ ]+ },+ "filesTouched": {+ "type": [+ "number",+ "null"+ ]+ },+ "retries": {+ "type": [+ "number",+ "null"+ ]+ },+ "delays": {+ "type": [+ "number",+ "null"+ ]+ },+ "delayMs": {+ "type": [+ "number",+ "null"+ ]+ },+ "maxContext": {+ "type": [+ "number",+ "null"+ ]+ },+ "compactions": {+ "type": [+ "number",+ "null"+ ]+ },+ "llmLatencyP50": {+ "type": [+ "number",+ "null"+ ]+ },+ "llmLatencyP95": {+ "type": [+ "number",+ "null"+ ]+ },+ "outputTokens": {+ "type": [+ "number",+ "null"+ ]+ },+ "prsCreated": {+ "type": [+ "number",+ "null"+ ]+ },+ "filesCreated": {+ "type": [+ "number",+ "null"+ ]+ },+ "filesDeleted": {+ "type": [+ "number",+ "null"+ ]+ },+ "tasks": {+ "type": [+ "number",+ "null"+ ]+ },+ "commits": {+ "type": [+ "number",+ "null"+ ]+ },+ "prsMerged": {+ "type": [+ "number",+ "null"+ ]+ },+ "prsClosed": {+ "type": [+ "number",+ "null"+ ]+ },+ "prComments": {+ "type": [+ "number",+ "null"+ ]+ },+ "ticketsCreated": {+ "type": [+ "number",+ "null"+ ]+ },+ "ticketsUpdated": {+ "type": [+ "number",+ "null"+ ]+ },+ "artifacts": {+ "type": [+ "number",+ "null"+ ]+ },+ "skillsCreated": {+ "type": [+ "number",+ "null"+ ]+ },+ "skillsUpdated": {+ "type": [+ "number",+ "null"+ ]+ },+ "modelSwitches": {+ "type": [+ "number",+ "null"+ ]+ },+ "promptChars": {+ "type": [+ "number",+ "null"+ ]+ },+ "promptImages": {+ "type": [+ "number",+ "null"+ ]+ },+ "promptUrls": {+ "type": [+ "number",+ "null"+ ]+ },+ "errorsBySource": {+ "type": "object",+ "additionalProperties": {+ "type": "number"+ }+ },+ "errorsByClass": {+ "type": "object",+ "additionalProperties": {+ "type": "number"+ }+ }+ },+ "additionalProperties": true+ },+ "repos": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "remote": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "id",+ "name"+ ]+ }+ },+ "files": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "integer"+ },+ "repo": {+ "type": "string"+ },+ "path": {+ "type": "string"+ },+ "reads": {+ "type": [+ "number",+ "null"+ ]+ },+ "edits": {+ "type": [+ "number",+ "null"+ ]+ },+ "hits": {+ "type": [+ "number",+ "null"+ ]+ },+ "first": {+ "type": [+ "number",+ "null"+ ]+ },+ "op": {+ "enum": [+ "create",+ "modify",+ "delete",+ "rename-from",+ "rename-to",+ null+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "id",+ "repo",+ "path"+ ]+ }+ },+ "prs": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string"+ },+ "repo": {+ "type": [+ "string",+ "null"+ ]+ },+ "number": {+ "type": "number"+ },+ "url": {+ "type": "string"+ },+ "seq": {+ "type": "integer"+ },+ "state": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "provider",+ "number",+ "url",+ "seq"+ ]+ }+ },+ "agents": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "parent": {+ "type": [+ "string",+ "null"+ ]+ },+ "kind": {+ "enum": [+ "main",+ "subagent",+ null+ ]+ },+ "subagentType": {+ "type": [+ "string",+ "null"+ ]+ },+ "launchSeq": {+ "type": [+ "integer",+ "null"+ ]+ },+ "start": {+ "type": [+ "number",+ "null"+ ]+ },+ "end": {+ "type": [+ "number",+ "null"+ ]+ },+ "calls": {+ "type": [+ "number",+ "null"+ ]+ },+ "requests": {+ "type": [+ "number",+ "null"+ ]+ },+ "tokens": {+ "type": [+ "number",+ "null"+ ]+ },+ "cost": {+ "type": [+ "number",+ "null"+ ]+ },+ "outcome": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "id"+ ]+ }+ },+ "tasks": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "n": {+ "type": "integer"+ },+ "id": {+ "type": [+ "string",+ "null"+ ]+ },+ "name": {+ "type": [+ "string",+ "null"+ ]+ },+ "source": {+ "enum": [+ "segments",+ "turns",+ null+ ]+ },+ "startSeq": {+ "type": [+ "integer",+ "null"+ ]+ },+ "endSeq": {+ "type": [+ "integer",+ "null"+ ]+ },+ "startT": {+ "type": [+ "number",+ "null"+ ]+ },+ "endT": {+ "type": [+ "number",+ "null"+ ]+ },+ "firstTurn": {+ "type": [+ "number",+ "null"+ ]+ },+ "lastTurn": {+ "type": [+ "number",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "n"+ ]+ }+ },+ "events": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/event"+ }+ }+ },+ "additionalProperties": true,+ "$defs": {+ "target": {+ "type": "object",+ "properties": {+ "file": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 0+ },+ "scope": {+ "const": "outside"+ },+ "label": {+ "type": [+ "string",+ "null"+ ]+ },+ "touch": {+ "enum": [+ "hit",+ "read",+ "edit"+ ]+ },+ "op": {+ "enum": [+ "create",+ "modify",+ "delete",+ "rename-from",+ "rename-to",+ null+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "touch"+ ]+ },+ "event": {+ "type": "object",+ "properties": {+ "seq": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 0+ },+ "t": {+ "type": "number",+ "minimum": 0,+ "description": "ms since the first event"+ },+ "kind": {+ "type": "string",+ "description": "read|search|edit|exec|verify|mcp|skill|subagent|web|tool|llm|error|delay|user|compaction|commit|pr_merge|pr_close|pr_comment|ticket|artifact|skill_write|model_switch"+ },+ "agent": {+ "type": [+ "string",+ "null"+ ],+ "description": "'main' or a subagent id from agents[]"+ },+ "err": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "tool": {+ "type": [+ "string",+ "null"+ ]+ },+ "verb": {+ "type": [+ "string",+ "null"+ ],+ "description": "shell verb only, e.g. 'git log'; never arguments"+ },+ "targets": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/target"+ }+ },+ "vcs": {+ "type": "object",+ "properties": {+ "provider": {+ "type": "string"+ },+ "action": {+ "type": "string"+ },+ "repo": {+ "type": [+ "string",+ "null"+ ]+ },+ "number": {+ "type": [+ "number",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "provider",+ "action"+ ]+ },+ "cat": {+ "enum": [+ "file",+ "shell",+ "vcs",+ "test",+ "cloud",+ "http",+ "fs",+ "package",+ "build",+ "mcp",+ "subagent",+ "skill",+ "web",+ "tool",+ null+ ]+ },+ "outBytes": {+ "type": [+ "number",+ "null"+ ]+ },+ "dur": {+ "type": [+ "number",+ "null"+ ]+ },+ "server": {+ "type": [+ "string",+ "null"+ ]+ },+ "skill": {+ "type": [+ "string",+ "null"+ ]+ },+ "subagentType": {+ "type": [+ "string",+ "null"+ ]+ },+ "model": {+ "type": [+ "string",+ "null"+ ]+ },+ "child": {+ "type": [+ "string",+ "null"+ ]+ },+ "host": {+ "type": [+ "string",+ "null"+ ]+ },+ "in": {+ "type": [+ "number",+ "null"+ ]+ },+ "cw": {+ "type": [+ "number",+ "null"+ ]+ },+ "cr": {+ "type": [+ "number",+ "null"+ ]+ },+ "out": {+ "type": [+ "number",+ "null"+ ]+ },+ "cost": {+ "type": [+ "number",+ "null"+ ]+ },+ "chars": {+ "type": [+ "number",+ "null"+ ]+ },+ "errClass": {+ "type": [+ "string",+ "null"+ ]+ },+ "exitCode": {+ "type": [+ "number",+ "null"+ ]+ },+ "retryOf": {+ "type": [+ "integer",+ "null"+ ]+ },+ "attempt": {+ "type": [+ "integer",+ "null"+ ]+ },+ "latency": {+ "type": [+ "number",+ "null"+ ]+ },+ "stop": {+ "type": [+ "string",+ "null"+ ]+ },+ "thinking": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "toolCalls": {+ "type": [+ "number",+ "null"+ ]+ },+ "textChars": {+ "type": [+ "number",+ "null"+ ]+ },+ "source": {+ "enum": [+ "llm",+ "hook",+ "orchestration",+ "tool",+ "mcp",+ null+ ]+ },+ "hook": {+ "type": [+ "string",+ "null"+ ]+ },+ "hookEvent": {+ "type": [+ "string",+ "null"+ ]+ },+ "srcUuid": {+ "type": [+ "string",+ "null"+ ]+ },+ "retry": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "cause": {+ "enum": [+ "tool",+ "subagent",+ "llm",+ "stall",+ null+ ]+ },+ "ms": {+ "type": [+ "number",+ "null"+ ]+ },+ "ref": {+ "type": [+ "integer",+ "null"+ ]+ },+ "trigger": {+ "type": [+ "string",+ "null"+ ]+ },+ "preTokens": {+ "type": [+ "number",+ "null"+ ]+ },+ "postTokens": {+ "type": [+ "number",+ "null"+ ]+ },+ "task": {+ "type": [+ "integer",+ "null"+ ]+ },+ "images": {+ "type": [+ "number",+ "null"+ ]+ },+ "urls": {+ "type": [+ "number",+ "null"+ ]+ },+ "repo": {+ "type": [+ "string",+ "null"+ ]+ },+ "sha": {+ "type": [+ "string",+ "null"+ ]+ },+ "files": {+ "type": [+ "number",+ "null"+ ]+ },+ "ins": {+ "type": [+ "number",+ "null"+ ]+ },+ "del": {+ "type": [+ "number",+ "null"+ ]+ },+ "number": {+ "type": [+ "number",+ "null"+ ]+ },+ "url": {+ "type": [+ "string",+ "null"+ ]+ },+ "tracker": {+ "type": [+ "string",+ "null"+ ]+ },+ "action": {+ "type": [+ "string",+ "null"+ ]+ },+ "id": {+ "type": [+ "string",+ "null"+ ]+ },+ "title": {+ "type": [+ "string",+ "null"+ ]+ },+ "bytes": {+ "type": [+ "number",+ "null"+ ]+ },+ "version": {+ "type": [+ "number",+ "null"+ ]+ },+ "name": {+ "type": [+ "string",+ "null"+ ]+ },+ "from": {+ "type": [+ "string",+ "null"+ ]+ },+ "to": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "additionalProperties": true,+ "required": [+ "t",+ "kind"+ ]+ }+ }+}\ No newline at end of filediff --git a/scripts/check_clean.py b/scripts/check_clean.pynew file mode 100644index 0000000..4c95df0--- /dev/null+++ b/scripts/check_clean.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""CI guard: fail if private references or credentials appear in tracked files.++Flags patterns that are wrong whatever the file: credential formats, ticket+ids, private document links, cross-repo PR references, personal home paths+and real-looking email addresses.+"""++import re+import subprocess+import sys++# Prefixes that look like ticket ids but are standard names (UTF-8, SHA-256...).+TICKET_ALLOW = {+ "UTF", "SHA", "GPT", "ISO", "CVE", "PEP", "RFC", "AES", "RSA", "TLS", "SSL", "MD", "HTTP",+ "ASCII", "BASE", "TCP", "UDP", "CRC", "EC", "ED", "GB", "KB", "MB", "TB", "PNG", "JPEG",+ "WEBP", "UTC", "GMT", "IEEE", "ECMA", "WCAG", "NFC", "NFD", "NFKC", "NFKD", "HS", "RS",+ "ES", "PS", "SM", "ARM", "X", "TS", "JS", "CP", "IBM", "SJIS", "EUC", "GBK", "BIG", "KOI",+ "AMD", "MP", "H", "VP", "AV", "OP", "OS", "P", "T", "E", "HTML", "CSS", "ICO", "AWS",+ "ACME", # placeholder tracker prefix used in fixtures+}+OK_EMAIL = re.compile(+ r"(?:^info@entelligence\.ai$)" # the project's published contact+ r"|@(?:example\.(?:com|org|net)|[\w.-]*acme[\w.-]*|[a-z]\.co|company\.com|github\.com"+ r"|users\.noreply\.github\.com|noreply\.github\.com|anthropic\.com)$",+ re.I,+)+EMAIL = re.compile(r"(?<![:/\w.+-])[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[A-Za-z]{2,}\b")+HOME_OK = {"dev", "you", "ada", "me", "runner", "user", "name", "x", "username", "yourname"}+HOME = re.compile(r"/Users/([A-Za-z0-9._-]+)/")+# The same home as a Claude Code project folder name (-Users-<name>-repo) and+# a default macOS hostname (<name>s-MacBook-Pro.local).+SLUG = re.compile(r"(?<![\w-])-Users-([A-Za-z0-9._]+)-")+MAC_HOST = re.compile(r"\b([A-Za-z0-9]+)s-(?:MacBook|MBP|iMac|Mac-mini)", re.I)+TICKET = re.compile(r"\b([A-Z]{2,5})-\d{2,5}\b")++PATTERNS = {+ "private document link": re.compile(r"claude\.ai/(?:code/)?artifact/(?!AbCdEf)[A-Za-z0-9-]{8,}"),+ "cross-repo PR ref": re.compile(r"(?<!acme/)\b\w+#\d{3,5}\b"),+ "issue tracker link": re.compile(r"linear\.app"),+ "aws key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),+ "private key": re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),+ "github token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{30,}\b"),+ "slack token": re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b"),+ "api key": re.compile(r"\bsk-(?:ant-)?[A-Za-z0-9_-]{24,}\b"),+}+SKIP = ("scripts/check_clean.py", "pnpm-lock.yaml", "package-lock.json", "uv.lock")+BINARY = (".png", ".jpg", ".gif", ".woff", ".woff2", ".ico", ".gz")++def scan_line(line: str) -> list[str]:+ """Return a label for every problem found in one line."""+ found = []+ for label, pat in PATTERNS.items():+ if pat.search(line):+ found.append(label)+ if any(m.group(1) not in TICKET_ALLOW for m in TICKET.finditer(line)):+ found.append("ticket id")+ homes = [m.group(1) for pat in (HOME, SLUG, MAC_HOST) for m in pat.finditer(line)]+ if any(h.lower() not in HOME_OK for h in homes):+ found.append("personal home path")+ if any(not OK_EMAIL.search(m.group(0)) for m in EMAIL.finditer(line)):+ found.append("real-looking email")+ return found+++def main() -> int:+ files = subprocess.run(+ ["git", "ls-files", "-co", "--exclude-standard"], capture_output=True, text=True, check=True+ ).stdout.split("\n")+ bad = 0+ for f in filter(None, files):+ if f.endswith(SKIP) or f.endswith(BINARY):+ continue+ try:+ with open(f, encoding="utf-8") as fh:+ text = fh.read()+ except (UnicodeDecodeError, FileNotFoundError, IsADirectoryError):+ continue+ for n, line in enumerate(text.splitlines(), 1):+ for label in scan_line(line):+ print(f"{f}:{n}: {label}")+ bad += 1+ if bad:+ print(f"\n{bad} problem(s). Remove them before committing.")+ return 1+ print("clean")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/collect_viewer_licenses.mjs b/scripts/collect_viewer_licenses.mjsnew file mode 100644index 0000000..d5b2abc--- /dev/null+++ b/scripts/collect_viewer_licenses.mjs@@ -0,0 +1,87 @@+#!/usr/bin/env node+// Collect license texts for the viewer's production dependency tree and write+// viewer/dist/THIRD_PARTY_LICENSES.txt, so the wheel (which bundles viewer/dist)+// carries the notices its dependencies and fonts require. No extra dependencies:+// it reads `pnpm licenses list --prod --json` and the LICENSE files on disk.+//+// Run after `vite build` (the viewer `build` script does this). Usage:+// node scripts/collect_viewer_licenses.mjs [viewerDir]++import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const viewerDir = resolve(process.argv[2] ?? join(root, "viewer"));+const outFile = join(viewerDir, "dist", "THIRD_PARTY_LICENSES.txt");++// Call the pnpm that is running this build (`corepack pnpm run build` sets+// npm_execpath to its own entry script), not whichever pnpm is first on PATH:+// an older global pnpm rejects the lockfile.+const pnpmArgs = ["licenses", "list", "--prod", "--json"];+const execPath = process.env.npm_execpath ?? "";+const [cmd, args, shell] = /pnpm[^/\\]*\.[cm]?js$/i.test(execPath)+ ? [process.execPath, [execPath, ...pnpmArgs], false]+ : ["pnpm", pnpmArgs, process.platform === "win32"]; // pnpm is pnpm.cmd on Windows+const raw = execFileSync(cmd, args, {+ cwd: viewerDir,+ encoding: "utf8",+ maxBuffer: 64 * 1024 * 1024,+ shell,+});+const byLicense = JSON.parse(raw.slice(raw.indexOf("{")));++const LICENSE_FILE = /^(licen[cs]e|copying|notice)(\.|-|$)/i;+const licenseText = (dir) => {+ if (!existsSync(dir)) return null;+ const names = readdirSync(dir).filter((n) => LICENSE_FILE.test(n)).sort();+ return names.length ? names.map((n) => readFileSync(join(dir, n), "utf8").trim()).join("\n\n") : null;+};++const seen = new Set();+const entries = [];+const counts = {};+for (const [license, pkgs] of Object.entries(byLicense)) {+ for (const pkg of pkgs) {+ pkg.versions.forEach((version, i) => {+ const key = `${pkg.name}@${version}`;+ if (seen.has(key)) return;+ seen.add(key);+ counts[license] = (counts[license] ?? 0) + 1;+ entries.push({+ key,+ license,+ homepage: pkg.homepage,+ author: pkg.author,+ text: licenseText(pkg.paths[i] ?? pkg.paths[0]),+ });+ });+ }+}+entries.sort((a, b) => a.key.localeCompare(b.key));++const missing = entries.filter((e) => !e.text).map((e) => e.key);+const bar = "=".repeat(78);+const parts = [+ "agentplay viewer: third-party licenses",+ "",+ "The bundled web viewer includes the open-source packages below (production",+ "dependencies, including transitive ones, and bundled fonts). Each entry gives",+ "the declared SPDX license and the license text shipped by the package.",+ "",+ "Summary: " + Object.entries(counts).sort().map(([l, n]) => `${l} (${n})`).join(", "),+ "",+];+for (const e of entries) {+ parts.push(bar, `${e.key} [${e.license}]`);+ if (e.author) parts.push(`Author: ${e.author}`);+ if (e.homepage) parts.push(`Homepage: ${e.homepage}`);+ parts.push("", e.text ?? `(no license file shipped; declared license: ${e.license})`, "");+}++mkdirSync(dirname(outFile), { recursive: true });+writeFileSync(outFile, parts.join("\n"));+console.log(`wrote ${outFile}: ${entries.length} packages`);+for (const [l, n] of Object.entries(counts).sort()) console.log(` ${l}: ${n}`);+if (missing.length) console.log(` no license file on disk (declared license only): ${missing.join(", ")}`);diff --git a/scripts/fake_signup_endpoint.py b/scripts/fake_signup_endpoint.pynew file mode 100644index 0000000..016d20d--- /dev/null+++ b/scripts/fake_signup_endpoint.py@@ -0,0 +1,41 @@+#!/usr/bin/env python3+"""A stand-in signup endpoint for trying the welcome card locally.++ python3 scripts/fake_signup_endpoint.py [--port 8787] [--fail]+ AGENTPLAY_SIGNUP_URL=http://127.0.0.1:8787/exec agentplay view++Prints each event it receives. ``--fail`` answers 500, to see the card's error.+"""++import argparse+import json+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("--port", type=int, default=8787)+ ap.add_argument("--fail", action="store_true", help="answer 500 to every request")+ args = ap.parse_args()++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *a: object) -> None:+ return++ def do_POST(self) -> None: # noqa: N802+ body = self.rfile.read(int(self.headers.get("Content-Length") or 0))+ try:+ print(json.dumps(json.loads(body)), flush=True)+ except ValueError:+ print(f"(not JSON) {body[:200]!r}", flush=True)+ self.send_response(500 if args.fail else 200)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(b'{"ok": true}')++ print(f"Listening on http://127.0.0.1:{args.port}/exec", flush=True)+ ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever()+++if __name__ == "__main__":+ main()diff --git a/viewer/.gitignore b/viewer/.gitignorenew file mode 100644index 0000000..f4e2c6d--- /dev/null+++ b/viewer/.gitignore@@ -0,0 +1,3 @@+node_modules/+dist/+*.tsbuildinfodiff --git a/viewer/README.md b/viewer/README.mdnew file mode 100644index 0000000..5762f66--- /dev/null+++ b/viewer/README.md@@ -0,0 +1,105 @@+# agentplay viewer++The Session Explorer as a standalone single-page app: a radial map of every+file, tool, MCP server, subagent, model and output a coding-agent session+touched, a replayable timeline, and the details panels beside them. It reads+`agentplay/v1` map documents (the older `entelligence.session-map/v1` name+is the same shape and is accepted too).+++++Vite + React 19 + TypeScript + Tailwind 3. Data through TanStack Query, URL+state (selected session, scope, tabs, timeline chips) through nuqs, so every+view is a shareable link.++## Develop++```bash+pnpm install+pnpm dev # http://localhost:5173, demo sessions+AGENTPLAY_SERVER=http://127.0.0.1:7317 pnpm dev # proxy /api to `agentplay view --no-open`+ # (start that with AGENTPLAY_DEV_ORIGINS=http://localhost:5173 so the signup card can post)+pnpm test # vitest: model and data-layer tests+pnpm typecheck+pnpm build # tsc -b && vite build -> dist/+node scripts/make-demo.mjs # regenerate public/demo (deterministic)+node scripts/screenshots.mjs # after a build: ../docs/images/explorer-{light,dark}.png+```++`dist/` uses relative asset paths (`base: './'`), so it can be served from any+path. The Python package ships it and serves it next to its API.++## Data sources++Every component reads through one injected `SessionMapSource`+(`src/data/source.ts`):++```ts+interface SessionMapSource {+ id: string; label: string;+ status(): Promise<Status>;+ sessions(p: { from?, to?, search?, pageSize?, cursor? }): Promise<SessionsPage>;+ maps(ids: string[]): Promise<MapBatch>;+ fetchMap(meta: MapMeta): Promise<SessionMap>;+}+```++`App.tsx` picks one at load:++| Source | When | What it reads |+| --- | --- | --- |+| `httpSource(base)` | `GET /api/status` answers JSON | the local CLI server (contract below) |+| `demoSource()` | no server, or `?demo` in the URL | `demo/index.json` + `demo/<file>` static files |+| `fileSource()` | you drop or pick files | `.json` / `.json.gz` maps, parsed in the tab, never uploaded |++Drag-and-drop works anywhere on the page in every mode; opened files replace+the list until you click "Back". `?server=http://host:port` points the viewer+at a server on another origin.++### Local server contract++All answers are camelCase JSON, validated by the zod schemas in+`src/core/schema.ts`:++- `GET /api/status` -> `{success, available, mapCount, latestSessionDate}`+- `GET /api/sessions?from=&to=&search=&pageSize=50&cursor=` ->+ `{success, sessions: [row], nextCursor, hasMore}`+- `GET /api/map?session_id=A&session_id=B` -> `{success, expiresIn, maps:+ [{sessionId, url, schemaVersion, contentHash, bytesGz} | {sessionId, status:+ "not_found"}]}`+- `GET <url>` -> the map document (plain or gzipped JSON)++## Embedding++The explorer is a plain component tree. To embed it in another React app:++```tsx+<QueryClientProvider client={queryClient}>+ <NuqsAdapter> {/* any nuqs adapter */}+ <SessionMapSourceProvider source={httpSource('https://maps.example')}>+ <div className="flex h-screen flex-col">+ <SessionExplorer windowKey="all" onWindowChange={setWindowKey} />+ </div>+ </SessionMapSourceProvider>+ </NuqsAdapter>+</QueryClientProvider>+```++Implement `SessionMapSource` for any other backend. The explorer fills the+height of its flex parent. It needs the `ds-*` tokens in+`src/styles/index.css` and the Tailwind theme in `tailwind.config.ts`; the+tokens are trimmed to what the explorer uses, light and dark (`.dark` on+`<html>`, set from `prefers-color-scheme` or `?theme=light|dark`).++## Layout++- `src/core/` pure TypeScript: map model, layout, scoping, signals, playback,+ timeline drawing, colours, schema and map-loading policy, with their tests.+- `src/explorer/` the React components and hooks.+- `src/data/` the source interface, the three sources, and the TanStack+ Query hooks the components call.+- `src/components/`, `src/lib/`, `src/hooks/` the small UI kit (shadcn-style+ on Base UI), `cn`, the chart palette and helpers.+- `public/demo/` synthetic demo sessions from `scripts/make-demo.mjs`+ (invented `acme/*` repos; every title starts with "Demo:").diff --git a/viewer/index.html b/viewer/index.htmlnew file mode 100644index 0000000..081116a--- /dev/null+++ b/viewer/index.html@@ -0,0 +1,39 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="color-scheme" content="light dark" />+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ccircle cx='16' cy='16' r='14' fill='%2356653e'/%3E%3Ccircle cx='16' cy='16' r='4' fill='%23e7f2d4'/%3E%3C/svg%3E" />+ <title>Agentplay Viewer</title>+ <script>+ // Theme before first paint: ?theme=light|dark, then a remembered choice,+ // then the OS preference (followed live while no choice is pinned).+ (function () {+ var root = document.documentElement;+ var mq = window.matchMedia('(prefers-color-scheme: dark)');+ function pinned() {+ var q = new URLSearchParams(location.search).get('theme');+ if (q === 'light' || q === 'dark') return q;+ try {+ var s = localStorage.getItem('agentplay.theme');+ if (s === 'light' || s === 'dark') return s;+ } catch (e) {}+ return null;+ }+ function apply() {+ var t = pinned() || (mq.matches ? 'dark' : 'light');+ root.classList.toggle('dark', t === 'dark');+ root.dataset.theme = t;+ }+ apply();+ mq.addEventListener('change', apply);+ window.__agentplayApplyTheme = apply;+ })();+ </script>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/viewer/package.json b/viewer/package.jsonnew file mode 100644index 0000000..0c75492--- /dev/null+++ b/viewer/package.json@@ -0,0 +1,57 @@+{+ "name": "agentplay-viewer",+ "version": "0.1.0",+ "private": true,+ "license": "Apache-2.0",+ "type": "module",+ "description": "Standalone Session Explorer viewer for agentplay documents.",+ "scripts": {+ "dev": "vite",+ "build": "tsc -b && vite build && node ../scripts/collect_viewer_licenses.mjs",+ "preview": "vite preview",+ "typecheck": "tsc -b --noEmit",+ "test": "vitest run",+ "demo": "node scripts/make-demo.mjs",+ "screenshots": "node scripts/screenshots.mjs"+ },+ "dependencies": {+ "@base-ui/react": "^1.6.0",+ "@fontsource-variable/inter": "^5.3.0",+ "@fontsource-variable/jetbrains-mono": "^5.3.0",+ "@phosphor-icons/react": "^2.1.10",+ "@tanstack/react-query": "^5.101.4",+ "class-variance-authority": "^0.7.1",+ "clsx": "^2.1.1",+ "cmdk": "^1.1.1",+ "lucide-react": "^0.569.0",+ "nuqs": "^2.9.4",+ "react": "^19.2.8",+ "react-dom": "^19.2.8",+ "tailwind-merge": "^2.6.0",+ "zod": "^3.25.76"+ },+ "devDependencies": {+ "@types/node": "22.20.1",+ "@types/react": "^19.2.18",+ "@types/react-dom": "^19.2.4",+ "@vitejs/plugin-react": "^5.0.0",+ "autoprefixer": "10.4.15",+ "jsdom": "^27.0.1",+ "playwright-core": "^1.56.0",+ "postcss": "^8.5.6",+ "tailwindcss": "^3.4.18",+ "tailwindcss-animate": "^1.0.7",+ "typescript": "6.0.3",+ "vite": "^7.1.0",+ "vitest": "^4.1.10"+ },+ "packageManager": "[email protected]",+ "engines": {+ "node": ">=22"+ },+ "pnpm": {+ "onlyBuiltDependencies": [+ "esbuild"+ ]+ }+}diff --git a/viewer/pnpm-lock.yaml b/viewer/pnpm-lock.yamlnew file mode 100644index 0000000..25dda66--- /dev/null+++ b/viewer/pnpm-lock.yaml@@ -0,0 +1,2988 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ '@base-ui/react':+ specifier: ^1.6.0+ '@fontsource-variable/inter':+ specifier: ^5.3.0+ version: 5.3.0+ '@fontsource-variable/jetbrains-mono':+ specifier: ^5.3.0+ version: 5.3.0+ '@phosphor-icons/react':+ specifier: ^2.1.10+ '@tanstack/react-query':+ specifier: ^5.101.4+ version: 5.104.0([email protected])+ class-variance-authority:+ specifier: ^0.7.1+ version: 0.7.1+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ cmdk:+ specifier: ^1.1.1+ version: 1.1.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ lucide-react:+ specifier: ^0.569.0+ version: 0.569.0([email protected])+ nuqs:+ specifier: ^2.9.4+ version: 2.10.1([email protected])+ react:+ specifier: ^19.2.8+ version: 19.3.0+ react-dom:+ specifier: ^19.2.8+ version: 19.3.0([email protected])+ tailwind-merge:+ specifier: ^2.6.0+ version: 2.6.1+ zod:+ specifier: ^3.25.76+ version: 3.25.76+ devDependencies:+ '@types/node':+ specifier: 22.20.1+ version: 22.20.1+ '@types/react':+ specifier: ^19.2.18+ version: 19.3.0+ '@types/react-dom':+ specifier: ^19.2.4+ version: 19.3.0(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^5.0.0+ autoprefixer:+ specifier: 10.4.15+ version: 10.4.15([email protected])+ jsdom:+ specifier: ^27.0.1+ version: 27.4.0+ playwright-core:+ specifier: ^1.56.0+ version: 1.63.0+ postcss:+ specifier: ^8.5.6+ version: 8.5.28+ tailwindcss:+ specifier: ^3.4.18+ version: 3.4.19+ tailwindcss-animate:+ specifier: ^1.0.7+ version: 1.0.7([email protected])+ typescript:+ specifier: 6.0.3+ version: 6.0.3+ vite:+ specifier: ^7.1.0+ version: 7.3.6(@types/[email protected])([email protected])+ vitest:+ specifier: ^4.1.10+ version: 4.1.11(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))++packages:++ '@acemir/[email protected]':+ resolution: {integrity: sha512-ZnR3GSaH+/vJ0YlHau21FjfLYjMpYVIzTD8M8vIEQvIGxeOXyXdzCI140rrCY862p/C/BbzWsjc1dgnM9mkoTA==}++ '@alloc/[email protected]':+ resolution: {integrity: sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==}+ engines: {node: '>=10'}++ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-NfBUvBaYgKIuq6E/RBLY1m0IohzNHAYyaJGuTK79Z23uNwmz2jl1mPsC5ZxCCxylinKhT1Amn5oNTlx1wN8cQg==}++ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-MvRz1nCqW0fsy8Qz4dnLIvhOlMzqDVBabZx6lH+YywFDdjXhMY37SmpV1XFX3JzG5GWHn63j6HX6QPr3lZXHvQ==}++ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0++ '@babel/[email protected]':+ resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ '@babel/[email protected]':+ resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}+ engines: {node: '>=6.9.0'}++ '@base-ui/[email protected]':+ resolution: {integrity: sha512-P0/1sxo6SBVZOklKMIedvTWqw2s2IQzi9x5bIVsXu980cuSOD4NeuRSs+/L7LZQfDkZP/uRZyGPyfFl/B1oH+Q==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ '@date-fns/tz': ^1.2.0+ '@types/react': ^17 || ^18 || ^19+ date-fns: ^4.0.0+ react: ^17 || ^18 || ^19+ react-dom: ^17 || ^18 || ^19+ peerDependenciesMeta:+ '@date-fns/tz':+ optional: true+ '@types/react':+ optional: true+ date-fns:+ optional: true++ '@base-ui/[email protected]':+ resolution: {integrity: sha512-bO9fz25kKtPf+aZVyfQrC0PDmJdmVni31W2hCS5/Owb+inwdIL3XU26pCPRPlt4LSxZrBgLwubXQXQlKaFEZzw==}+ peerDependencies:+ '@types/react': ^17 || ^18 || ^19+ react: ^17 || ^18 || ^19+ react-dom: ^17 || ^18 || ^19+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@csstools/[email protected]':+ resolution: {integrity: sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==}+ engines: {node: '>=20.19.0'}++ '@csstools/[email protected]':+ resolution: {integrity: sha512-EtC7SoN1j6J4E4DCwg5QgbO5TGxgxIA1RXqe+W+qUM+BUcezx9wT+/tiQ/WO2yCX4i5X+Cuf9ciJ22aP4UEwWw==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ '@csstools/css-parser-algorithms': ^4.0.1+ '@csstools/css-tokenizer': ^4.0.2++ '@csstools/[email protected]':+ resolution: {integrity: sha512-DyefytAZ735mX4Dq/WcDAXFtXhaEFvme0ZS9tVEBAc2whxUthXr0R0L2rmEPm59SrMBkGrFzQviBXMs/UtnABQ==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ '@csstools/css-parser-algorithms': ^4.0.1+ '@csstools/css-tokenizer': ^4.0.2++ '@csstools/[email protected]':+ resolution: {integrity: sha512-ShL8BqPfbKJrJiKFH0xBbN0i7Nrh9HXYRuF+pzyj93R/BL2YAsUxJeqANErzqM+0JGl7vjHp+3OIgd/DL69YIA==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ '@csstools/css-tokenizer': ^4.0.2++ '@csstools/[email protected]':+ resolution: {integrity: sha512-HpbVXyrofRXpHpgkNIjU/3EWR4WJvOkO3emNK/L6X/mTJU7bGUI3AkkpoTNXznQLp0KRjLHELTGeKI5dIkI9JQ==}+ peerDependencies:+ css-tree: ^3.2.1+ peerDependenciesMeta:+ css-tree:+ optional: true++ '@csstools/[email protected]':+ resolution: {integrity: sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==}+ engines: {node: '>=20.19.0'}++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@exodus/[email protected]':+ resolution: {integrity: sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+ peerDependencies:+ '@noble/hashes': ^1.8.0 || ^2.0.0+ peerDependenciesMeta:+ '@noble/hashes':+ optional: true++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==}++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==}++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}++ '@fontsource-variable/[email protected]':+ resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==}++ '@fontsource-variable/[email protected]':+ resolution: {integrity: sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}+ engines: {node: ^22.20 || ^24.12 || >=25}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@nodelib/[email protected]':+ resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}+ engines: {node: '>= 8'}++ '@nodelib/[email protected]':+ resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==}+ engines: {node: '>= 8'}++ '@nodelib/[email protected]':+ resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}+ engines: {node: '>= 8'}++ '@phosphor-icons/[email protected]':+ resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==}+ engines: {node: '>=10'}+ peerDependencies:+ react: '>= 16.8'+ react-dom: '>= 16.8'++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q==}++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@radix-ui/[email protected]':+ resolution: {integrity: sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==}++ '@rollup/[email protected]':+ resolution: {integrity: sha512-J25QJU+B78T4FhhBsNpLJyVWOi31mwtpcMwywHmOKH65Q9IWGA81gPj+dnwlhU8wktVriYE+tFAaQgrnJRzAZg==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-LDopB3zuZM5Ux9TT2luNEBJW/tYbGU2g1d+VpKk6I+gSKDb+/7sYE6M225gRQt4RbMX6MSwMsVR/phdjVUgRLg==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-wlJEERGfeuHeBavCL2qVnNacOK43NDoZM4sjkeRPymd04OAE9T1zBqDJgmZ+CIsPTYKwdzpUC8vmOw84dwY4Tg==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-4nJJGg5jbo2wwPP4JP+LfEBA3bvP8rU9CLuhp7jWvq9sxEyhjQFTFdrqi+/dHEin/pd8jpT0vcehIpnZtmEdcQ==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-DrZbyCDF1hneuO6jRbvZ2D7+PIBM6yIwYnJpg2vIk58T+wuFpiaGZrfUr59lDWw45bg+IrpTGLPiNi/Fk4w3Cg==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-gqfUVMJMB3mehqywxp6hTBFfgtMQykZY19+cfiaYP0toIJLb/1DZRJHVkQQGP13W4TAwfZDWeg1qBcheTRioXQ==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-CFmhpvAwzSaWMlN3VN7UtmoTihlZNzoP0juQib5TQRnYUyDV8dXeWOp29sobWAT6gXl/hQgAClLlEiYozQG3OQ==}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Uc9H8eXCOayV6JLTH5bXKMId6qbhNHa818/BgYjm4jrlq3vZquC9cqyvHBw17xy5Mnj5f+I3gFK5JcEf3hSqrw==}+ cpu: [arm]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-VcPr/szv/1BFw112Kt//fxulXt/JPqzzidU84iW68L2DdjnOO8QFUv2zTSYBEPHD6movBD4z+bbr5y60GYM7Jw==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BnxtJ5/91BrIHYIkGrmjz/lbMhqEHt1dPFqIxIFR+jPn0xVc/oUSCtIT089zfp5ufwGDlYz2UC+Fe1SRBpYFbQ==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-LrYcHZwF+fAMNKHYTOQ5osWM4AZF7YF6D+XtsjDyEvljtt11twc+zHVXBLNEjxVSUnKYsOhvVz4Z213eW02COQ==}+ cpu: [loong64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-nj7QKQePAAUpCpJHtg0pR0W/b92A9NO17JS3BAQmHDn/yhmkir2p8llrKY9TOhleKIaSzy1JhxS3T9FVld6coA==}+ cpu: [loong64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-5ylkX6dWMeBKge9nTU+Rxfb+ZfaCIJ9lRqIFaK0eAMcWp7OJbYnLveLgXmm0VrvuLKb8qIK+mHyH0qu88RM+iA==}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-oHK4ZHYFDKjZviK34I+NwgfbGxgI7ztrNxj2hPTSSNFgeq1a/lEd7dHV2fdGAuTH4Iym3RHJg+vAbWaWG4B7Zg==}+ cpu: [ppc64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-UcetmHZ6XOXuUByiKZyQmb55ZPr0LABr3Ec/HB9wKZn6CEAFWZkE+hsJErJ9hbPBC7nI0dKuELx7CoV6IM7TMg==}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-C5CmDPQBtvjVo8cgQsBs+w6WB0JLkiixhgi6hVLV11hERWdn/p0XcPU2OUcZzac9BPOFq7SbaHFa8r3SWEysCQ==}+ cpu: [riscv64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-lHVQHJFKsuuxLMi3MQO9XVL8Tje3JR82CzB+QDKC5NWBcsIWuwsn9uIM5e3lBhI+fF1/s63qnyYqsg65+8rV/w==}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-3W9bTFcQNJn71cSJVM9RKIiZOy8DO/XLDii8Uv/Pm6WKqDRj7JV3ZfuXIEfyuy5LXpIzAbB/1M4Ukp9GKNa7nA==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-VDC7rRJlee/scpki96GZ27Omf6yU87s1YXwVTpjE5841faVlDYYT565rgfmoR1U0sqL7z5ivQSDjcsF6VRXyBA==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-z86Ok2p4pTdv5xqCKZsTooO7yBEiaJR/HzU3Wx8RmWsPoLppnMKROhJusQob8B3IE1ghC343kUW9rC2r+Wf3ig==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-IzQmj+xXwQFGhMAMKMQVXkMwMZN3TqkJgAE0nSsqvVwWWciP4AIPMmWRqOQ2GfX7TUDZr+xqGFcBS36CRPGw0g==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-F6qpTaPc9bwBH85kjy0/BLmLSW1uv7AoOXCoRIkg2arlgCYlWYcAbiMkvZuAcaWk9TpCRG//okznLAqLGshkMw==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-igoDsTFhhwECBeGbUuLeIk7t8Y1apa+cs6mDWpx2EZ0ch7oEQgzHbFUXN9euoHekCAQzXdXApAGkV6jznS7tWw==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-U3teMeMbXFmaM5D+OTJpsOXd+wV/qftIeYF9kBKL4v73641qyJmoXFtA28DQLsnmlyayEsTe72xpLHrArq6vHw==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-ypfC34F3RKXvCXBglGqGMsUSMKlgwd1HX9AOAlx9RoZZ6GaI42YHVeKpzg3JG+wpBUJYTG+NNZhqbDWL8tBZkw==}+ cpu: [x64]+ os: [win32]++ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-JrC2r/JQlXt7khBSdUpsgxNvybzOg+aITa+ARRMlP2AFo93Y8vIqz077rp+e61mJetSZ0T6AJbwW1JHer1vrPQ==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-e1TZmDCQnWIfiDVryIHeA6Idj+Lfx1hORLOhXS/l5wcgvtVD4yYqbTDl378sGQKIi2cSgb0TEMC9cKK8GGoJEw==}+ peerDependencies:+ react: ^18 || ^19++ '@types/[email protected]':+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}++ '@types/[email protected]':+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}+ peerDependencies:+ '@types/react': ^19.3.0++ '@types/[email protected]':+ resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}++ '@vitejs/[email protected]':+ resolution: {integrity: sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ peerDependencies:+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0++ '@vitest/[email protected]':+ resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}+ peerDependencies:+ msw: ^2.4.9+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true++ '@vitest/[email protected]':+ resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}++ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==}++ resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==}++ resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-KCuPB8ZCIqFdA4HwKXsvz7j6gvSDNhDP7WnUjBleRkKjPdvCmHFuQ77ocavI8FT6NdvlBnE2UFr2H4Mycn8Vew==}+ engines: {node: ^10 || ^12 || >=14}+ hasBin: true+ peerDependencies:+ postcss: ^8.1.0++ resolution: {integrity: sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==}++ resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==}+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}+ hasBin: true++ resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-zfjJo4rM0+fUomGDBW/xcDjhIwz/210DGvip2MAMDZ8KHcRPnOHmEgHPZP0UHlZoxr8fYKVJOqcORhYQcG4FKQ==}++ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}+ engines: {node: '>= 8.10.0'}++ resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}++ resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}+ peerDependencies:+ react: ^18 || ^19 || ^19.0.0-rc+ react-dom: ^18 || ^19 || ^19.0.0-rc++ resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}++ resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}+ engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}++ resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}+ engines: {node: '>=4'}+ hasBin: true++ resolution: {integrity: sha512-7D2EPVltRrsTkhpQmksIu+LxeWAIEk6wRDMJ1qljlv+CKHJM+cJLlfhWIzNA44eAsHXSNe3+vO6DW1yCYx8SuQ==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}++ resolution: {integrity: sha512-euIQENZg6x8mj3fO6o9+fOW8MimUI4PpD/fZBhJfeioZVy9TUpM4UY7KjQNVZFlqwJ0UdzRDzkycB997HEq1BQ==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}++ resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}++ resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}++ resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}++ resolution: {integrity: sha512-SghDzqdJokdz8zP8YNlvS74+CwLRoUPDGvP/gFA+HrKVw+pOshUAgx8pXR37xl/u16zGae746rFNWvZ/22kU2Q==}++ resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==}+ engines: {node: '>=20.19.0'}++ resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}++ resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}++ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}+ engines: {node: '>=8.6.0'}++ resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==}++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}++ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}+ engines: {node: '>=6.9.0'}++ resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}+ engines: {node: '>=10.13.0'}++ resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}++ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}+ engines: {node: '>=0.12.0'}++ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}++ resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==}+ hasBin: true++ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}++ resolution: {integrity: sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+ peerDependencies:+ canvas: ^3.0.0+ peerDependenciesMeta:+ canvas:+ optional: true++ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}++ resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==}+ engines: {node: 20 || >=22}++ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}++ resolution: {integrity: sha512-70SOx2wHI+fcSzAN6dA4GRvkZSFKapppiAbE+/ktpkeYCo1ULlD5wSMGHRlBsWSsVn4Uwzoo/4i+5o0pIWnwTQ==}+ peerDependencies:+ react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0++ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}++ resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}++ resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}+ engines: {node: '>=8.6'}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}++ resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-7lPZrPJVOsD0VvfQSKtodYBBPGPLsLzkFU8ueYIap9yMMJvSw6UC12p8luA5NW7aKe7AbPHKxcxb3OluH6iAJA==}+ peerDependencies:+ '@remix-run/react': '>=2'+ '@tanstack/react-router': ^1+ next: '>=14.2.0'+ react: '>=18.2.0 || ^19.0.0-0'+ react-router: ^5 || ^6 || ^7 || ^8+ react-router-dom: ^5 || ^6 || ^7+ peerDependenciesMeta:+ '@remix-run/react':+ optional: true+ '@tanstack/react-router':+ optional: true+ next:+ optional: true+ react-router:+ optional: true+ react-router-dom:+ optional: true++ resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==}+ engines: {node: '>=12.20.0'}++ resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}++ resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}++ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==}+ engines: {node: '>=8.6'}++ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==}+ engines: {node: '>=20'}+ hasBin: true++ resolution: {integrity: sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ postcss: ^8.0.0++ resolution: {integrity: sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==}+ engines: {node: ^12 || ^14 || >= 16}+ peerDependencies:+ postcss: ^8.4.21++ resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}+ engines: {node: '>= 18'}+ peerDependencies:+ jiti: '>=1.21.0'+ postcss: '>=8.0.9'+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ jiti:+ optional: true+ postcss:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==}+ engines: {node: '>=12.0'}+ peerDependencies:+ postcss: ^8.2.14++ resolution: {integrity: sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==}+ engines: {node: '>=4'}++ resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}++ resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}++ resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==}+ peerDependencies:+ react: ^19.3.0++ resolution: {integrity: sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==}+ engines: {node: '>=10'}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ '@types/react':+ optional: true++ resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==}+ engines: {node: '>=10'}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}+ engines: {node: '>=10'}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-/peqiBB/n07gQGLsWaHho3WfvUyRscw0gYTsEFMhrIe/nWLkYaf5SbKYjGYqtRV3aPwykJgF2VEMo1ac4bnsGA==}++ resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}+ engines: {node: '>=8.10.0'}++ resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}++ resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==}+ engines: {node: '>= 0.4'}+ hasBin: true++ resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}+ engines: {iojs: '>=1.0.0', node: '>=0.10.0'}++ resolution: {integrity: sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}++ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}+ engines: {node: '>=v12.22.7'}++ resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}++ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}+ hasBin: true++ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}++ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}++ resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}++ resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}+ engines: {node: '>=16 || 14 >=14.17'}+ hasBin: true++ resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}++ resolution: {integrity: sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==}++ resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}+ peerDependencies:+ tailwindcss: '>=3.0.0 || insiders'++ resolution: {integrity: sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==}+ engines: {node: '>=14.0.0'}+ hasBin: true++ resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}+ engines: {node: '>=0.8'}++ resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}++ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}++ resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==}++ resolution: {integrity: sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==}+ hasBin: true++ resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}+ engines: {node: '>=8.0'}++ resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==}+ engines: {node: '>=16'}++ resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}++ resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==}+ hasBin: true+ peerDependencies:+ browserslist: '>= 4.21.0'++ resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==}+ engines: {node: '>=10'}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==}+ engines: {node: '>=10'}+ peerDependencies:+ '@types/react': '*'+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc+ peerDependenciesMeta:+ '@types/react':+ optional: true++ resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0++ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}++ resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^20.19.0 || >=22.12.0+ jiti: '>=1.21.0'+ less: ^4.0.0+ lightningcss: ^1.21.0+ sass: ^1.70.0+ sass-embedded: ^1.70.0+ stylus: '>=0.54.8'+ sugarss: ^5.0.0+ terser: ^5.16.0+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ '@types/node':+ optional: true+ jiti:+ optional: true+ less:+ optional: true+ lightningcss:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==}+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}+ hasBin: true+ peerDependencies:+ '@edge-runtime/vm': '*'+ '@opentelemetry/api': ^1.9.0+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0+ '@vitest/browser-playwright': 4.1.11+ '@vitest/browser-preview': 4.1.11+ '@vitest/browser-webdriverio': 4.1.11+ '@vitest/coverage-istanbul': 4.1.11+ '@vitest/coverage-v8': 4.1.11+ '@vitest/ui': 4.1.11+ happy-dom: '*'+ jsdom: '*'+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0+ peerDependenciesMeta:+ '@edge-runtime/vm':+ optional: true+ '@opentelemetry/api':+ optional: true+ '@types/node':+ optional: true+ '@vitest/browser-playwright':+ optional: true+ '@vitest/browser-preview':+ optional: true+ '@vitest/browser-webdriverio':+ optional: true+ '@vitest/coverage-istanbul':+ optional: true+ '@vitest/coverage-v8':+ optional: true+ '@vitest/ui':+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true++ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}+ engines: {node: '>=8'}+ hasBin: true++ resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}++ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}++ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}++snapshots:++ '@acemir/[email protected]': {}++ '@alloc/[email protected]': {}++ '@asamuzakjp/[email protected]':+ dependencies:+ '@csstools/css-calc': 3.4.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-color-parser': 4.2.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-parser-algorithms': 4.0.1(@csstools/[email protected])+ '@csstools/css-tokenizer': 4.0.2+ lru-cache: 11.5.3++ '@asamuzakjp/[email protected]':+ dependencies:+ '@asamuzakjp/nwsapi': 2.3.9+ bidi-js: 1.1.0+ css-tree: 3.2.1+ is-potential-custom-element-name: 1.0.1+ lru-cache: 11.5.3++ '@asamuzakjp/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-validator-identifier': 7.29.7+ js-tokens: 4.0.0+ picocolors: 1.1.1++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.8+ '@babel/helper-compilation-targets': 7.29.7+ '@babel/helper-module-transforms': 7.29.7(@babel/[email protected])+ '@babel/helpers': 7.29.7+ '@babel/parser': 7.29.9+ '@babel/template': 7.29.7+ '@babel/traverse': 7.29.8+ '@babel/types': 7.29.8+ '@jridgewell/remapping': 2.3.5+ convert-source-map: 2.0.0+ debug: 4.4.3+ gensync: 1.0.0-beta.2+ json5: 2.2.3+ semver: 6.3.1+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31+ jsesc: 3.1.0++ '@babel/[email protected]':+ dependencies:+ '@babel/compat-data': 7.29.7+ '@babel/helper-validator-option': 7.29.7+ browserslist: 4.29.3+ lru-cache: 5.1.1+ semver: 6.3.1++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/traverse': 7.29.8+ '@babel/types': 7.29.8+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.7+ '@babel/helper-module-imports': 7.29.7+ '@babel/helper-validator-identifier': 7.29.7+ '@babel/traverse': 7.29.8+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/template': 7.29.7+ '@babel/types': 7.29.8++ '@babel/[email protected]':+ dependencies:+ '@babel/types': 7.29.8++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.7+ '@babel/helper-plugin-utils': 7.29.7++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.7+ '@babel/helper-plugin-utils': 7.29.7++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.8+ '@babel/helper-globals': 7.29.7+ '@babel/parser': 7.29.9+ '@babel/template': 7.29.7+ '@babel/types': 7.29.8+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-string-parser': 7.29.7+ '@babel/helper-validator-identifier': 7.29.7++ '@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.29.7+ '@base-ui/utils': 0.4.0(@types/[email protected])([email protected]([email protected]))([email protected])+ '@floating-ui/utils': 0.2.12+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ use-sync-external-store: 1.7.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0++ '@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.29.7+ '@floating-ui/utils': 0.2.12+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ reselect: 5.3.0+ use-sync-external-store: 1.7.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0++ '@csstools/[email protected]': {}++ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':+ dependencies:+ '@csstools/css-parser-algorithms': 4.0.1(@csstools/[email protected])+ '@csstools/css-tokenizer': 4.0.2++ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':+ dependencies:+ '@csstools/color-helpers': 6.1.2+ '@csstools/css-calc': 3.4.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-parser-algorithms': 4.0.1(@csstools/[email protected])+ '@csstools/css-tokenizer': 4.0.2++ '@csstools/[email protected](@csstools/[email protected])':+ dependencies:+ '@csstools/css-tokenizer': 4.0.2++ '@csstools/[email protected]([email protected])':+ optionalDependencies:+ css-tree: 3.2.1++ '@csstools/[email protected]': {}++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@exodus/[email protected]': {}++ '@floating-ui/[email protected]':+ dependencies:+ '@floating-ui/utils': 0.2.12++ '@floating-ui/[email protected]':+ dependencies:+ '@floating-ui/core': 1.8.0+ '@floating-ui/utils': 0.2.12++ dependencies:+ '@floating-ui/dom': 1.8.0+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ '@floating-ui/[email protected]': {}++ '@fontsource-variable/[email protected]': {}++ '@fontsource-variable/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.6.0++ '@napi-rs/[email protected]':+ optional: true++ '@nodelib/[email protected]':+ dependencies:+ '@nodelib/fs.stat': 2.0.5+ run-parallel: 1.2.0++ '@nodelib/[email protected]': {}++ '@nodelib/[email protected]':+ dependencies:+ '@nodelib/fs.scandir': 2.1.5+ fastq: 1.20.3++ dependencies:+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ '@radix-ui/[email protected]': {}++ dependencies:+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/primitive': 1.1.7+ '@radix-ui/react-compose-refs': 1.1.5(@types/[email protected])([email protected])+ '@radix-ui/react-context': 1.2.2(@types/[email protected])([email protected])+ '@radix-ui/react-dismissable-layer': 1.1.19(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-focus-guards': 1.1.6(@types/[email protected])([email protected])+ '@radix-ui/react-focus-scope': 1.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-id': 1.1.4(@types/[email protected])([email protected])+ '@radix-ui/react-portal': 1.1.17(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-presence': 1.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-primitive': 2.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-slot': 1.3.3(@types/[email protected])([email protected])+ '@radix-ui/react-use-controllable-state': 1.2.6(@types/[email protected])([email protected])+ '@radix-ui/react-use-layout-effect': 1.1.4(@types/[email protected])([email protected])+ aria-hidden: 1.2.6+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ react-remove-scroll: 2.7.2(@types/[email protected])([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])++ '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/primitive': 1.1.7+ '@radix-ui/react-compose-refs': 1.1.5(@types/[email protected])([email protected])+ '@radix-ui/react-primitive': 2.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-use-callback-ref': 1.1.4(@types/[email protected])([email protected])+ '@radix-ui/react-use-effect-event': 0.0.5(@types/[email protected])([email protected])+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])++ dependencies:+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/react-compose-refs': 1.1.5(@types/[email protected])([email protected])+ '@radix-ui/react-primitive': 2.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-use-callback-ref': 1.1.4(@types/[email protected])([email protected])+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])++ dependencies:+ '@radix-ui/react-use-layout-effect': 1.1.4(@types/[email protected])([email protected])+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/react-primitive': 2.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-use-layout-effect': 1.1.4(@types/[email protected])([email protected])+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])++ '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/react-use-layout-effect': 1.1.4(@types/[email protected])([email protected])+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])++ '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@radix-ui/react-slot': 1.3.3(@types/[email protected])([email protected])+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])++ dependencies:+ '@radix-ui/react-compose-refs': 1.1.5(@types/[email protected])([email protected])+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ '@radix-ui/primitive': 1.1.7+ '@radix-ui/react-use-effect-event': 0.0.5(@types/[email protected])([email protected])+ '@radix-ui/react-use-layout-effect': 1.1.4(@types/[email protected])([email protected])+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ '@radix-ui/react-use-layout-effect': 1.1.4(@types/[email protected])([email protected])+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0++ '@rolldown/[email protected]': {}++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@standard-schema/[email protected]': {}++ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]([email protected])':+ dependencies:+ '@tanstack/query-core': 5.104.0+ react: 19.3.0++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8+ '@types/babel__generator': 7.27.0+ '@types/babel__template': 7.4.4+ '@types/babel__traverse': 7.28.0++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.8++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.8++ '@types/[email protected]':+ dependencies:+ '@types/deep-eql': 4.0.2+ assertion-error: 2.0.1++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ undici-types: 6.21.0++ '@types/[email protected](@types/[email protected])':+ dependencies:+ '@types/react': 19.3.0++ '@types/[email protected]':+ dependencies:+ csstype: 3.2.3++ dependencies:+ '@babel/core': 7.29.7+ '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])+ '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/[email protected])+ '@rolldown/pluginutils': 1.0.0-rc.3+ '@types/babel__core': 7.20.5+ react-refresh: 0.18.0+ vite: 7.3.6(@types/[email protected])([email protected])+ transitivePeerDependencies:+ - supports-color++ '@vitest/[email protected]':+ dependencies:+ '@standard-schema/spec': 1.1.0+ '@types/chai': 5.2.3+ '@vitest/spy': 4.1.11+ '@vitest/utils': 4.1.11+ chai: 6.2.2+ tinyrainbow: 3.1.1++ dependencies:+ '@vitest/spy': 4.1.11+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:+ vite: 7.3.6(@types/[email protected])([email protected])++ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 3.1.1++ '@vitest/[email protected]':+ dependencies:+ '@vitest/utils': 4.1.11+ pathe: 2.0.3++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 4.1.11+ '@vitest/utils': 4.1.11+ magic-string: 0.30.21+ pathe: 2.0.3++ '@vitest/[email protected]': {}++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 4.1.11+ convert-source-map: 2.0.0+ tinyrainbow: 3.1.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ normalize-path: 3.0.0+ picomatch: 2.3.2++ [email protected]: {}++ dependencies:+ tslib: 2.8.1++ [email protected]: {}++ dependencies:+ browserslist: 4.29.3+ caniuse-lite: 1.0.30001813+ fraction.js: 4.3.7+ normalize-range: 0.1.2+ picocolors: 1.1.1+ postcss: 8.5.28+ postcss-value-parser: 4.2.0++ [email protected]: {}++ dependencies:+ require-from-string: 2.0.2++ [email protected]: {}++ dependencies:+ fill-range: 7.1.1++ dependencies:+ baseline-browser-mapping: 2.11.26+ caniuse-lite: 1.0.30001813+ electron-to-chromium: 1.5.440+ node-releases: 2.0.57+ update-browserslist-db: 1.3.3([email protected])++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ anymatch: 3.1.3+ braces: 3.0.3+ glob-parent: 5.1.2+ is-binary-path: 2.1.0+ is-glob: 4.0.3+ normalize-path: 3.0.0+ readdirp: 3.6.0+ optionalDependencies:+ fsevents: 2.3.3++ dependencies:+ clsx: 2.1.1++ [email protected]: {}++ [email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]):+ dependencies:+ '@radix-ui/react-compose-refs': 1.1.5(@types/[email protected])([email protected])+ '@radix-ui/react-dialog': 1.1.23(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@radix-ui/react-id': 1.1.4(@types/[email protected])([email protected])+ '@radix-ui/react-primitive': 2.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ transitivePeerDependencies:+ - '@types/react'+ - '@types/react-dom'++ [email protected]: {}++ [email protected]: {}++ dependencies:+ mdn-data: 2.27.1+ source-map-js: 1.2.1++ [email protected]: {}++ dependencies:+ '@asamuzakjp/css-color': 4.1.2+ '@csstools/css-syntax-patches-for-csstree': 1.1.14([email protected])+ css-tree: 3.2.1+ lru-cache: 11.5.3++ [email protected]: {}++ dependencies:+ whatwg-mimetype: 5.0.0+ whatwg-url: 15.1.0++ dependencies:+ ms: 2.1.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.28.2+ '@esbuild/android-arm': 0.28.2+ '@esbuild/android-arm64': 0.28.2+ '@esbuild/android-x64': 0.28.2+ '@esbuild/darwin-arm64': 0.28.2+ '@esbuild/darwin-x64': 0.28.2+ '@esbuild/freebsd-arm64': 0.28.2+ '@esbuild/freebsd-x64': 0.28.2+ '@esbuild/linux-arm': 0.28.2+ '@esbuild/linux-arm64': 0.28.2+ '@esbuild/linux-ia32': 0.28.2+ '@esbuild/linux-loong64': 0.28.2+ '@esbuild/linux-mips64el': 0.28.2+ '@esbuild/linux-ppc64': 0.28.2+ '@esbuild/linux-riscv64': 0.28.2+ '@esbuild/linux-s390x': 0.28.2+ '@esbuild/linux-x64': 0.28.2+ '@esbuild/netbsd-arm64': 0.28.2+ '@esbuild/netbsd-x64': 0.28.2+ '@esbuild/openbsd-arm64': 0.28.2+ '@esbuild/openbsd-x64': 0.28.2+ '@esbuild/openharmony-arm64': 0.28.2+ '@esbuild/sunos-x64': 0.28.2+ '@esbuild/win32-arm64': 0.28.2+ '@esbuild/win32-ia32': 0.28.2+ '@esbuild/win32-x64': 0.28.2++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.9++ [email protected]: {}++ dependencies:+ '@nodelib/fs.stat': 2.0.5+ '@nodelib/fs.walk': 1.2.8+ glob-parent: 5.1.2+ merge2: 1.4.1+ micromatch: 4.0.8++ dependencies:+ reusify: 1.1.0++ optionalDependencies:+ picomatch: 4.0.7++ dependencies:+ to-regex-range: 5.0.1++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ is-glob: 4.0.3++ dependencies:+ is-glob: 4.0.3++ dependencies:+ function-bind: 1.1.2++ dependencies:+ '@exodus/bytes': 1.16.0+ transitivePeerDependencies:+ - '@noble/hashes'++ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ binary-extensions: 2.3.0++ dependencies:+ hasown: 2.0.4++ [email protected]: {}++ dependencies:+ is-extglob: 2.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@acemir/cssom': 0.9.31+ '@asamuzakjp/dom-selector': 6.8.1+ '@exodus/bytes': 1.16.0+ cssstyle: 5.3.7+ data-urls: 6.0.1+ decimal.js: 10.6.0+ html-encoding-sniffer: 6.0.0+ http-proxy-agent: 7.0.2+ https-proxy-agent: 7.0.6+ is-potential-custom-element-name: 1.0.1+ parse5: 8.0.1+ saxes: 6.0.0+ symbol-tree: 3.2.4+ tough-cookie: 6.0.2+ w3c-xmlserializer: 5.0.0+ webidl-conversions: 8.0.1+ whatwg-mimetype: 4.0.0+ whatwg-url: 15.1.0+ ws: 8.22.0+ xml-name-validator: 5.0.0+ transitivePeerDependencies:+ - '@noble/hashes'+ - bufferutil+ - supports-color+ - utf-8-validate++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ yallist: 3.1.1++ dependencies:+ react: 19.3.0++ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ braces: 3.0.3+ picomatch: 2.3.2++ [email protected]: {}++ dependencies:+ any-promise: 1.3.0+ object-assign: 4.1.1+ thenify-all: 1.6.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@standard-schema/spec': 1.1.0+ react: 19.3.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ entities: 8.1.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ postcss: 8.5.28+ postcss-value-parser: 4.2.0+ read-cache: 1.0.2+ resolve: 1.22.12++ dependencies:+ camelcase-css: 2.0.1+ postcss: 8.5.28++ dependencies:+ lilconfig: 3.1.3+ optionalDependencies:+ jiti: 1.21.7+ postcss: 8.5.28++ dependencies:+ postcss: 8.5.28+ postcss-selector-parser: 6.1.4++ dependencies:+ cssesc: 3.0.0+ util-deprecate: 1.0.2++ [email protected]: {}++ dependencies:+ nanoid: 3.3.19+ picocolors: 1.1.1+ source-map-js: 1.2.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ react: 19.3.0+ scheduler: 0.28.0++ [email protected]: {}++ dependencies:+ react: 19.3.0+ react-style-singleton: 2.2.3(@types/[email protected])([email protected])+ tslib: 2.8.1+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ react: 19.3.0+ react-remove-scroll-bar: 2.3.8(@types/[email protected])([email protected])+ react-style-singleton: 2.2.3(@types/[email protected])([email protected])+ tslib: 2.8.1+ use-callback-ref: 1.3.3(@types/[email protected])([email protected])+ use-sidecar: 1.1.3(@types/[email protected])([email protected])+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ get-nonce: 1.0.1+ react: 19.3.0+ tslib: 2.8.1+ optionalDependencies:+ '@types/react': 19.3.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ picomatch: 2.3.2++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0+ is-core-module: 2.17.0+ path-parse: 1.0.7+ supports-preserve-symlinks-flag: 1.0.0++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.9+ optionalDependencies:+ '@napi-rs/lzma-linux-x64-gnu': 1.5.1+ '@rollup/rollup-android-arm-eabi': 4.63.5+ '@rollup/rollup-android-arm64': 4.63.5+ '@rollup/rollup-darwin-arm64': 4.63.5+ '@rollup/rollup-darwin-x64': 4.63.5+ '@rollup/rollup-freebsd-arm64': 4.63.5+ '@rollup/rollup-freebsd-x64': 4.63.5+ '@rollup/rollup-linux-arm-gnueabihf': 4.63.5+ '@rollup/rollup-linux-arm-musleabihf': 4.63.5+ '@rollup/rollup-linux-arm64-gnu': 4.63.5+ '@rollup/rollup-linux-arm64-musl': 4.63.5+ '@rollup/rollup-linux-loong64-gnu': 4.63.5+ '@rollup/rollup-linux-loong64-musl': 4.63.5+ '@rollup/rollup-linux-ppc64-gnu': 4.63.5+ '@rollup/rollup-linux-ppc64-musl': 4.63.5+ '@rollup/rollup-linux-riscv64-gnu': 4.63.5+ '@rollup/rollup-linux-riscv64-musl': 4.63.5+ '@rollup/rollup-linux-s390x-gnu': 4.63.5+ '@rollup/rollup-linux-x64-gnu': 4.63.5+ '@rollup/rollup-linux-x64-musl': 4.63.5+ '@rollup/rollup-openbsd-x64': 4.63.5+ '@rollup/rollup-openharmony-arm64': 4.63.5+ '@rollup/rollup-win32-arm64-msvc': 4.63.5+ '@rollup/rollup-win32-ia32-msvc': 4.63.5+ '@rollup/rollup-win32-x64-gnu': 4.63.5+ '@rollup/rollup-win32-x64-msvc': 4.63.5+ fsevents: 2.3.3++ dependencies:+ queue-microtask: 1.2.3++ dependencies:+ xmlchars: 2.2.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ commander: 4.1.1+ lines-and-columns: 1.2.4+ mz: 2.7.0+ pirates: 4.0.7+ tinyglobby: 0.2.17+ ts-interface-checker: 0.1.13++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tailwindcss: 3.4.19++ dependencies:+ '@alloc/quick-lru': 5.3.0+ arg: 5.0.2+ chokidar: 3.6.0+ didyoumean: 1.2.2+ dlv: 1.1.3+ fast-glob: 3.3.3+ glob-parent: 6.0.2+ is-glob: 4.0.3+ jiti: 1.21.7+ lilconfig: 3.1.3+ micromatch: 4.0.8+ normalize-path: 3.0.0+ object-hash: 3.0.0+ picocolors: 1.1.1+ postcss: 8.5.28+ postcss-import: 15.1.0([email protected])+ postcss-js: 4.1.0([email protected])+ postcss-load-config: 6.0.1([email protected])([email protected])+ postcss-nested: 6.2.0([email protected])+ postcss-selector-parser: 6.1.4+ resolve: 1.22.12+ sucrase: 3.35.1+ transitivePeerDependencies:+ - tsx+ - yaml++ dependencies:+ thenify: 3.3.1++ dependencies:+ any-promise: 1.3.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tldts-core: 7.4.16++ dependencies:+ is-number: 7.0.0++ dependencies:+ tldts: 7.4.16++ dependencies:+ punycode: 2.3.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ browserslist: 4.29.3+ escalade: 3.2.0+ picocolors: 1.1.1++ dependencies:+ react: 19.3.0+ tslib: 2.8.1+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ detect-node-es: 1.1.0+ react: 19.3.0+ tslib: 2.8.1+ optionalDependencies:+ '@types/react': 19.3.0++ dependencies:+ react: 19.3.0++ [email protected]: {}++ dependencies:+ esbuild: 0.28.2+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7+ postcss: 8.5.28+ rollup: 4.63.5+ tinyglobby: 0.2.17+ optionalDependencies:+ '@types/node': 22.20.1+ fsevents: 2.3.3+ jiti: 1.21.7++ [email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])):+ dependencies:+ '@vitest/expect': 4.1.11+ '@vitest/pretty-format': 4.1.11+ '@vitest/runner': 4.1.11+ '@vitest/snapshot': 4.1.11+ '@vitest/spy': 4.1.11+ '@vitest/utils': 4.1.11+ es-module-lexer: 2.3.2+ expect-type: 1.4.0+ magic-string: 0.30.21+ obug: 2.2.1+ pathe: 2.0.3+ picomatch: 4.0.7+ std-env: 4.3.0+ tinybench: 2.9.0+ tinyexec: 1.3.1+ tinyglobby: 0.2.17+ tinyrainbow: 3.1.1+ vite: 7.3.6(@types/[email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/node': 22.20.1+ jsdom: 27.4.0+ transitivePeerDependencies:+ - msw++ dependencies:+ xml-name-validator: 5.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tr46: 6.0.0+ webidl-conversions: 8.0.1++ dependencies:+ siginfo: 2.0.0+ stackback: 0.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}diff --git a/viewer/postcss.config.js b/viewer/postcss.config.jsnew file mode 100644index 0000000..2aa7205--- /dev/null+++ b/viewer/postcss.config.js@@ -0,0 +1,6 @@+export default {+ plugins: {+ tailwindcss: {},+ autoprefixer: {},+ },+};diff --git a/viewer/public/demo/claude-code-rate-limit.json b/viewer/public/demo/claude-code-rate-limit.jsonnew file mode 100644index 0000000..6297a7c--- /dev/null+++ b/viewer/public/demo/claude-code-rate-limit.json@@ -0,0 +1,1166 @@+{+ "schema": "agentplay/v1",+ "session": {+ "id": "local:claude-code:5f2c9a1e-7b44-4d0e-9c1a-demo00000001",+ "agentTool": "claude-code",+ "cliVersion": "2.1.4",+ "startedAt": "2026-09-24T14:05:12.000Z",+ "durationMs": 249685,+ "models": [+ "claude-haiku-4-5",+ "claude-opus-4-5",+ "claude-sonnet-4-5"+ ],+ "pathMode": "relative",+ "truncated": false,+ "outcome": "pr_created",+ "role": "root",+ "parentSessionId": null+ },+ "totals": {+ "calls": 26,+ "requests": 20,+ "userTurns": 3,+ "subagents": 1,+ "errors": 2,+ "tokens": 1239680,+ "costUsd": 1.9251,+ "filesTouched": 10,+ "prsCreated": 1,+ "filesCreated": 3,+ "filesDeleted": 0,+ "errorsBySource": {+ "tool": 1,+ "llm": 1+ },+ "errorsByClass": {+ "exit_code": 1,+ "overloaded": 1+ },+ "retries": 1,+ "delays": 2,+ "delayMs": 33800,+ "maxContext": 161000,+ "compactions": 1,+ "llmLatencyP50": 6151,+ "llmLatencyP95": 21000,+ "outputTokens": 10680,+ "tasks": 3,+ "commits": 1+ },+ "repos": [+ {+ "id": "r0",+ "name": "acme/api",+ "remote": "[email protected]:acme/api.git"+ }+ ],+ "files": [+ {+ "id": 0,+ "repo": "r0",+ "path": "README.md",+ "reads": 1,+ "edits": 0,+ "hits": 0,+ "first": 2+ },+ {+ "id": 1,+ "repo": "r0",+ "path": "src/middleware/index.ts",+ "reads": 1,+ "edits": 1,+ "hits": 1,+ "first": 6,+ "op": "modify"+ },+ {+ "id": 2,+ "repo": "r0",+ "path": "src/middleware/auth.ts",+ "reads": 1,+ "edits": 0,+ "hits": 1,+ "first": 6+ },+ {+ "id": 3,+ "repo": "r0",+ "path": "src/server.ts",+ "reads": 1,+ "edits": 0,+ "hits": 1,+ "first": 6+ },+ {+ "id": 4,+ "repo": "r0",+ "path": "src/config/env.ts",+ "reads": 1,+ "edits": 1,+ "hits": 0,+ "first": 12,+ "op": "modify"+ },+ {+ "id": 5,+ "repo": "r0",+ "path": "src/routes/orders.ts",+ "reads": 1,+ "edits": 1,+ "hits": 0,+ "first": 15,+ "op": "modify"+ },+ {+ "id": 6,+ "repo": "r0",+ "path": "package.json",+ "reads": 1,+ "edits": 0,+ "hits": 0,+ "first": 16+ },+ {+ "id": 7,+ "repo": "r0",+ "path": "src/middleware/rateLimit.ts",+ "reads": 1,+ "edits": 2,+ "hits": 0,+ "first": 21,+ "op": "create"+ },+ {+ "id": 8,+ "repo": "r0",+ "path": "test/rateLimit.test.ts",+ "reads": 0,+ "edits": 1,+ "hits": 0,+ "first": 26,+ "op": "create"+ },+ {+ "id": 9,+ "repo": "r0",+ "path": "docs/rate-limits.md",+ "reads": 0,+ "edits": 1,+ "hits": 0,+ "first": 41,+ "op": "create"+ }+ ],+ "prs": [+ {+ "provider": "github",+ "repo": "acme/api",+ "number": 142,+ "url": "https://github.com/acme/api/pull/142",+ "seq": 53,+ "state": "open"+ }+ ],+ "agents": [+ {+ "id": "main",+ "parent": null,+ "kind": "main",+ "start": 12185,+ "end": 249685,+ "calls": 21,+ "requests": 16,+ "tokens": 1179940,+ "cost": 1.8984,+ "outcome": "pr_created"+ },+ {+ "id": "sub-explore",+ "parent": "main",+ "kind": "subagent",+ "subagentType": "Explore",+ "launchSeq": 4,+ "start": 33323,+ "end": 59447,+ "calls": 5,+ "requests": 4,+ "tokens": 59740,+ "cost": 0.0267,+ "outcome": "completed"+ }+ ],+ "tasks": [+ {+ "n": 1,+ "id": "task:1",+ "name": "Explore the request pipeline",+ "source": "segments",+ "startSeq": 0,+ "endSeq": 18,+ "startT": 12185,+ "endT": 81985+ },+ {+ "n": 2,+ "id": "task:2",+ "name": "Add a token-bucket rate limiter",+ "source": "segments",+ "startSeq": 19,+ "endSeq": 41,+ "startT": 99110,+ "endT": 196333+ },+ {+ "n": 3,+ "id": "task:3",+ "name": "Commit and open a PR",+ "source": "segments",+ "startSeq": 42,+ "endSeq": 55,+ "startT": 206863,+ "endT": 249685+ }+ ],+ "events": [+ {+ "seq": 0,+ "t": 12185,+ "agent": "main",+ "err": false,+ "kind": "user",+ "chars": 1180,+ "urls": 1,+ "task": 1+ },+ {+ "seq": 1,+ "t": 18967,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 626,+ "cw": 2506,+ "cr": 14868,+ "out": 420,+ "cost": 0.03673,+ "latency": 6642,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 756,+ "task": 1+ },+ {+ "seq": 2,+ "t": 20551,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 0,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 1+ },+ {+ "seq": 3,+ "t": 26610,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 1109,+ "cw": 4435,+ "cr": 15456,+ "out": 380,+ "cost": 0.05049,+ "latency": 6079,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 684,+ "task": 1+ },+ {+ "seq": 4,+ "t": 28066,+ "agent": "main",+ "err": false,+ "kind": "subagent",+ "tool": "Task",+ "subagentType": "Explore",+ "child": "sub-explore",+ "model": "claude-haiku-4-5",+ "cat": "subagent",+ "task": 1+ },+ {+ "seq": 5,+ "t": 33323,+ "agent": "sub-explore",+ "err": false,+ "kind": "llm",+ "model": "claude-haiku-4-5",+ "in": 200,+ "cw": 802,+ "cr": 7998,+ "out": 300,+ "cost": 0.0035,+ "latency": 5184,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 540,+ "task": 1+ },+ {+ "seq": 6,+ "t": 34077,+ "agent": "sub-explore",+ "err": false,+ "kind": "search",+ "tool": "Grep",+ "verb": "rg",+ "targets": [+ {+ "file": 1,+ "touch": "hit"+ },+ {+ "file": 2,+ "touch": "hit"+ },+ {+ "file": 3,+ "touch": "hit"+ }+ ],+ "cat": "file",+ "model": "claude-haiku-4-5",+ "task": 1+ },+ {+ "seq": 7,+ "t": 38304,+ "agent": "sub-explore",+ "err": false,+ "kind": "llm",+ "model": "claude-haiku-4-5",+ "in": 586,+ "cw": 2346,+ "cr": 9068,+ "out": 260,+ "cost": 0.00573,+ "latency": 4276,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 468,+ "task": 1+ },+ {+ "seq": 8,+ "t": 39986,+ "agent": "sub-explore",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 1,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-haiku-4-5",+ "task": 1+ },+ {+ "seq": 9,+ "t": 40666,+ "agent": "sub-explore",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 2,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-haiku-4-5",+ "task": 1+ },+ {+ "seq": 10,+ "t": 46722,+ "agent": "sub-explore",+ "err": false,+ "kind": "llm",+ "model": "claude-haiku-4-5",+ "in": 514,+ "cw": 2055,+ "cr": 13431,+ "out": 280,+ "cost": 0.00583,+ "latency": 5918,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 504,+ "task": 1+ },+ {+ "seq": 11,+ "t": 48894,+ "agent": "sub-explore",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 3,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-haiku-4-5",+ "task": 1+ },+ {+ "seq": 12,+ "t": 50985,+ "agent": "sub-explore",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 4,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-haiku-4-5",+ "task": 1+ },+ {+ "seq": 13,+ "t": 59447,+ "agent": "sub-explore",+ "err": false,+ "kind": "llm",+ "model": "claude-haiku-4-5",+ "in": 909,+ "cw": 3637,+ "cr": 16454,+ "out": 900,+ "cost": 0.0116,+ "latency": 8640,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 1620,+ "task": 1+ },+ {+ "seq": 14,+ "t": 68270,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 685,+ "cw": 2742,+ "cr": 22573,+ "out": 520,+ "cost": 0.04485,+ "latency": 8964,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 936,+ "task": 1+ },+ {+ "seq": 15,+ "t": 70306,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 5,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 1+ },+ {+ "seq": 16,+ "t": 71470,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 6,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 1+ },+ {+ "seq": 17,+ "t": 73088,+ "agent": "main",+ "err": false,+ "kind": "mcp",+ "server": "docs",+ "tool": "search_docs",+ "outBytes": 4200,+ "dur": 820,+ "cat": "mcp",+ "model": "claude-opus-4-5",+ "task": 1+ },+ {+ "seq": 18,+ "t": 81985,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 1021,+ "cw": 4084,+ "cr": 25895,+ "out": 640,+ "cost": 0.05958,+ "latency": 8757,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 1152,+ "task": 1+ },+ {+ "seq": 19,+ "t": 99110,+ "agent": "main",+ "err": false,+ "kind": "user",+ "chars": 420,+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 20,+ "t": 106779,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 2924,+ "cw": 11696,+ "cr": 57380,+ "out": 1400,+ "cost": 0.15141,+ "latency": 7532,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 2520,+ "task": 2+ },+ {+ "seq": 21,+ "t": 108273,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Write",+ "targets": [+ {+ "file": 7,+ "touch": "edit",+ "op": "create"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 22,+ "t": 114373,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 3076,+ "cw": 12304,+ "cr": 72620,+ "out": 700,+ "cost": 0.14609,+ "latency": 6006,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 1260,+ "task": 2+ },+ {+ "seq": 23,+ "t": 114969,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Edit",+ "targets": [+ {+ "file": 1,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 24,+ "t": 116786,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Edit",+ "targets": [+ {+ "file": 4,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 25,+ "t": 125492,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 5636,+ "cw": 22546,+ "cr": 75818,+ "out": 1100,+ "cost": 0.2345,+ "latency": 8512,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 1980,+ "task": 2+ },+ {+ "seq": 26,+ "t": 126834,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Write",+ "targets": [+ {+ "file": 8,+ "touch": "edit",+ "op": "create"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 27,+ "t": 131762,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 4370,+ "cw": 17482,+ "cr": 95148,+ "out": 300,+ "cost": 0.18619,+ "latency": 4835,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 540,+ "task": 2+ },+ {+ "seq": 28,+ "t": 140215,+ "agent": "main",+ "err": true,+ "kind": "verify",+ "tool": "Bash",+ "verb": "npm test",+ "cat": "test",+ "errClass": "exit_code",+ "exitCode": 1,+ "dur": 14200,+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 29,+ "t": 145596,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 3305,+ "cw": 13221,+ "cr": 112474,+ "out": 520,+ "cost": 0.16839,+ "latency": 5442,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 936,+ "task": 2+ },+ {+ "seq": 30,+ "t": 147849,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "Read",+ "targets": [+ {+ "file": 7,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 31,+ "t": 148601,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Edit",+ "targets": [+ {+ "file": 7,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 32,+ "t": 154568,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 7073,+ "cw": 28294,+ "cr": 102633,+ "out": 260,+ "cost": 0.27002,+ "latency": 6117,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 468,+ "task": 2+ },+ {+ "seq": 33,+ "t": 162367,+ "agent": "main",+ "err": false,+ "kind": "verify",+ "tool": "Bash",+ "verb": "npm test",+ "cat": "test",+ "retryOf": 28,+ "attempt": 2,+ "dur": 12800,+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 34,+ "t": 162436,+ "agent": "main",+ "err": false,+ "kind": "delay",+ "cause": "tool",+ "ms": 12800,+ "ref": 33,+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 35,+ "t": 163892,+ "agent": "main",+ "err": true,+ "kind": "error",+ "source": "llm",+ "errClass": "overloaded",+ "retry": true,+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 36,+ "t": 184856,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 3261,+ "cw": 13042,+ "cr": 132697,+ "out": 480,+ "cost": 0.17617,+ "latency": 21000,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 864,+ "task": 2+ },+ {+ "seq": 37,+ "t": 184952,+ "agent": "main",+ "err": false,+ "kind": "delay",+ "cause": "llm",+ "ms": 21000,+ "ref": 36,+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 38,+ "t": 188847,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "tsc",+ "dur": 6100,+ "cat": "shell",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 39,+ "t": 192931,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-opus-4-5",+ "in": 6216,+ "cw": 24862,+ "cr": 129922,+ "out": 220,+ "cost": 0.25693,+ "latency": 4281,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 396,+ "task": 2+ },+ {+ "seq": 40,+ "t": 195269,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Edit",+ "targets": [+ {+ "file": 5,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 41,+ "t": 196333,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "Write",+ "targets": [+ {+ "file": 9,+ "touch": "edit",+ "op": "create"+ }+ ],+ "cat": "file",+ "model": "claude-opus-4-5",+ "task": 2+ },+ {+ "seq": 42,+ "t": 206863,+ "agent": "main",+ "err": false,+ "kind": "user",+ "chars": 160,+ "model": "claude-opus-4-5",+ "task": 3+ },+ {+ "seq": 43,+ "t": 208162,+ "agent": "main",+ "err": false,+ "kind": "compaction",+ "trigger": "auto",+ "preTokens": 168400,+ "postTokens": 23100,+ "model": "claude-opus-4-5",+ "task": 3+ },+ {+ "seq": 44,+ "t": 208162,+ "agent": "main",+ "err": false,+ "kind": "model_switch",+ "from": "claude-opus-4-5",+ "to": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 45,+ "t": 214154,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-sonnet-4-5",+ "in": 629,+ "cw": 2515,+ "cr": 20856,+ "out": 380,+ "cost": 0.02328,+ "latency": 6151,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 684,+ "task": 3+ },+ {+ "seq": 46,+ "t": 217908,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "git",+ "vcs": {+ "provider": "git",+ "action": "status",+ "repo": "acme/api"+ },+ "cat": "vcs",+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 47,+ "t": 221980,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "git",+ "vcs": {+ "provider": "git",+ "action": "diff",+ "repo": "acme/api"+ },+ "cat": "vcs",+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 48,+ "t": 230980,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-sonnet-4-5",+ "in": 598,+ "cw": 2392,+ "cr": 26010,+ "out": 540,+ "cost": 0.02667,+ "latency": 8959,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 972,+ "task": 3+ },+ {+ "seq": 49,+ "t": 234803,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "git",+ "vcs": {+ "provider": "git",+ "action": "commit",+ "repo": "acme/api"+ },+ "cat": "vcs",+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 50,+ "t": 234926,+ "agent": "main",+ "err": false,+ "kind": "commit",+ "repo": "acme/api",+ "sha": "9d41c07be2a1",+ "files": 6,+ "ins": 214,+ "del": 12,+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 51,+ "t": 236308,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "git",+ "vcs": {+ "provider": "git",+ "action": "push",+ "repo": "acme/api"+ },+ "cat": "vcs",+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 52,+ "t": 244856,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-sonnet-4-5",+ "in": 928,+ "cw": 3711,+ "cr": 26361,+ "out": 820,+ "cost": 0.03691,+ "latency": 8464,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 1476,+ "task": 3+ },+ {+ "seq": 53,+ "t": 246445,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "gh",+ "vcs": {+ "provider": "github",+ "action": "pr_create",+ "repo": "acme/api",+ "number": 142+ },+ "cat": "vcs",+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 54,+ "t": 247148,+ "agent": "main",+ "err": false,+ "kind": "pr_comment",+ "repo": "acme/api",+ "number": 142,+ "url": "https://github.com/acme/api/pull/142",+ "model": "claude-sonnet-4-5",+ "task": 3+ },+ {+ "seq": 55,+ "t": 249685,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "claude-sonnet-4-5",+ "in": 994,+ "cw": 3976,+ "cr": 28030,+ "out": 260,+ "cost": 0.0302,+ "latency": 2600,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": true,+ "textChars": 468,+ "task": 3+ }+ ]+}diff --git a/viewer/public/demo/codex-flaky-test.json b/viewer/public/demo/codex-flaky-test.jsonnew file mode 100644index 0000000..ddc5c78--- /dev/null+++ b/viewer/public/demo/codex-flaky-test.json@@ -0,0 +1,579 @@+{+ "schema": "agentplay/v1",+ "session": {+ "id": "local:codex:0199a3b2-demo-4f0c-8e55-000000000002",+ "agentTool": "codex",+ "cliVersion": "0.44.0",+ "startedAt": "2026-09-23T09:41:03.000Z",+ "durationMs": 132039,+ "models": [+ "gpt-5-codex"+ ],+ "pathMode": "relative",+ "truncated": false,+ "outcome": "verified",+ "role": "root",+ "parentSessionId": null+ },+ "totals": {+ "calls": 12,+ "requests": 11,+ "userTurns": 2,+ "subagents": 0,+ "errors": 2,+ "tokens": 314060,+ "costUsd": 0.0851,+ "filesTouched": 4,+ "prsCreated": 0,+ "filesCreated": 0,+ "filesDeleted": 0,+ "errorsBySource": {+ "tool": 2+ },+ "errorsByClass": {+ "exit_code": 2+ },+ "retries": 1,+ "delays": 0,+ "delayMs": 0,+ "maxContext": 38000,+ "compactions": 0,+ "llmLatencyP50": 5776,+ "llmLatencyP95": 8190,+ "outputTokens": 4060,+ "tasks": 2,+ "commits": 1+ },+ "repos": [+ {+ "id": "r0",+ "name": "acme/web",+ "remote": "[email protected]:acme/web.git"+ },+ {+ "id": "r1",+ "name": "acme/ui-kit",+ "remote": "[email protected]:acme/ui-kit.git"+ }+ ],+ "files": [+ {+ "id": 0,+ "repo": "r0",+ "path": "src/lib/formatDate.ts",+ "reads": 1,+ "edits": 1,+ "hits": 1,+ "first": 2,+ "op": "modify"+ },+ {+ "id": 1,+ "repo": "r0",+ "path": "src/lib/formatDate.test.ts",+ "reads": 1,+ "edits": 1,+ "hits": 1,+ "first": 2,+ "op": "modify"+ },+ {+ "id": 2,+ "repo": "r0",+ "path": "src/components/OrderRow.tsx",+ "reads": 0,+ "edits": 0,+ "hits": 1,+ "first": 2+ },+ {+ "id": 3,+ "repo": "r1",+ "path": "src/date/index.ts",+ "reads": 1,+ "edits": 0,+ "hits": 0,+ "first": 11+ }+ ],+ "prs": [],+ "agents": [+ {+ "id": "main",+ "parent": null,+ "kind": "main",+ "start": 5484,+ "end": 132039,+ "calls": 12,+ "requests": 11,+ "tokens": 314060,+ "cost": 0.0851,+ "outcome": "verified"+ }+ ],+ "tasks": [+ {+ "n": 1,+ "id": "task:1",+ "name": "Reproduce the flaky date test",+ "source": "segments",+ "startSeq": 0,+ "endSeq": 13,+ "startT": 5484,+ "endT": 64307+ },+ {+ "n": 2,+ "id": "task:2",+ "name": "Fix the timezone handling",+ "source": "segments",+ "startSeq": 14,+ "endSeq": 25,+ "startT": 70822,+ "endT": 132039+ }+ ],+ "events": [+ {+ "seq": 0,+ "t": 5484,+ "agent": "main",+ "err": false,+ "kind": "user",+ "chars": 640,+ "task": 1+ },+ {+ "seq": 1,+ "t": 11693,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 746,+ "cw": 2983,+ "cr": 10271,+ "out": 300,+ "cost": 0.00522,+ "latency": 6287,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 540,+ "task": 1+ },+ {+ "seq": 2,+ "t": 14245,+ "agent": "main",+ "err": false,+ "kind": "search",+ "tool": "shell",+ "verb": "rg",+ "targets": [+ {+ "file": 0,+ "touch": "hit"+ },+ {+ "file": 1,+ "touch": "hit"+ },+ {+ "file": 2,+ "touch": "hit"+ }+ ],+ "cat": "file",+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 3,+ "t": 19929,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 806,+ "cw": 3225,+ "cr": 12969,+ "out": 260,+ "cost": 0.00523,+ "latency": 5503,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 468,+ "task": 1+ },+ {+ "seq": 4,+ "t": 22146,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "shell",+ "targets": [+ {+ "file": 0,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 5,+ "t": 22566,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "shell",+ "targets": [+ {+ "file": 1,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 6,+ "t": 26245,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 581,+ "cw": 2323,+ "cr": 18096,+ "out": 240,+ "cost": 0.00539,+ "latency": 3845,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 432,+ "task": 1+ },+ {+ "seq": 7,+ "t": 42056,+ "agent": "main",+ "err": true,+ "kind": "verify",+ "tool": "shell",+ "verb": "pnpm vitest",+ "cat": "test",+ "errClass": "exit_code",+ "exitCode": 1,+ "dur": 9100,+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 8,+ "t": 47929,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 538,+ "cw": 2153,+ "cr": 21309,+ "out": 380,+ "cost": 0.00714,+ "latency": 5776,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 684,+ "task": 1+ },+ {+ "seq": 9,+ "t": 49111,+ "agent": "main",+ "err": true,+ "kind": "exec",+ "tool": "shell",+ "verb": "pnpm",+ "errClass": "exit_code",+ "exitCode": 1,+ "cat": "shell",+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 10,+ "t": 56192,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 986,+ "cw": 3942,+ "cr": 21072,+ "out": 420,+ "cost": 0.00807,+ "latency": 6887,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 756,+ "task": 1+ },+ {+ "seq": 11,+ "t": 57061,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "shell",+ "targets": [+ {+ "file": 3,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 12,+ "t": 59322,+ "agent": "main",+ "err": false,+ "kind": "web",+ "tool": "web_search",+ "host": "developer.mozilla.org",+ "cat": "web",+ "model": "gpt-5-codex",+ "task": 1+ },+ {+ "seq": 13,+ "t": 64307,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 1404,+ "cw": 5615,+ "cr": 22981,+ "out": 520,+ "cost": 0.00983,+ "latency": 4872,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 936,+ "task": 1+ },+ {+ "seq": 14,+ "t": 70822,+ "agent": "main",+ "err": false,+ "kind": "user",+ "chars": 210,+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 15,+ "t": 78156,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 876,+ "cw": 3506,+ "cr": 27618,+ "out": 900,+ "cost": 0.01355,+ "latency": 7331,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 1620,+ "task": 2+ },+ {+ "seq": 16,+ "t": 80637,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "apply_patch",+ "targets": [+ {+ "file": 0,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 17,+ "t": 82720,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "apply_patch",+ "targets": [+ {+ "file": 1,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 18,+ "t": 90526,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 707,+ "cw": 2829,+ "cr": 31464,+ "out": 300,+ "cost": 0.00782,+ "latency": 7748,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 540,+ "task": 2+ },+ {+ "seq": 19,+ "t": 104077,+ "agent": "main",+ "err": false,+ "kind": "verify",+ "tool": "shell",+ "verb": "pnpm vitest",+ "cat": "test",+ "retryOf": 7,+ "attempt": 2,+ "dur": 8800,+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 20,+ "t": 107731,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 996,+ "cw": 3982,+ "cr": 31022,+ "out": 200,+ "cost": 0.00712,+ "latency": 3730,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 360,+ "task": 2+ },+ {+ "seq": 21,+ "t": 117455,+ "agent": "main",+ "err": false,+ "kind": "verify",+ "tool": "shell",+ "verb": "pnpm lint",+ "cat": "build",+ "dur": 7400,+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 22,+ "t": 125769,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 747,+ "cw": 2986,+ "cr": 33267,+ "out": 360,+ "cost": 0.00869,+ "latency": 8190,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 648,+ "task": 2+ },+ {+ "seq": 23,+ "t": 129960,+ "agent": "main",+ "err": false,+ "kind": "exec",+ "tool": "Bash",+ "verb": "git",+ "vcs": {+ "provider": "git",+ "action": "commit",+ "repo": "acme/web"+ },+ "cat": "vcs",+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 24,+ "t": 130058,+ "agent": "main",+ "err": false,+ "kind": "commit",+ "repo": "acme/web",+ "sha": "3be07f19ac44",+ "files": 2,+ "ins": 18,+ "del": 7,+ "model": "gpt-5-codex",+ "task": 2+ },+ {+ "seq": 25,+ "t": 132039,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "gpt-5-codex",+ "in": 749,+ "cw": 2996,+ "cr": 34255,+ "out": 180,+ "cost": 0.00702,+ "latency": 2100,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 324,+ "task": 2+ }+ ]+}diff --git a/viewer/public/demo/cursor-copy-tweak.json b/viewer/public/demo/cursor-copy-tweak.jsonnew file mode 100644index 0000000..23a3d94--- /dev/null+++ b/viewer/public/demo/cursor-copy-tweak.json@@ -0,0 +1,242 @@+{+ "schema": "agentplay/v1",+ "session": {+ "id": "local:cursor:c1d2e3f4-demo-4a5b-9c8d-000000000003",+ "agentTool": "cursor",+ "cliVersion": "1.7",+ "startedAt": "2026-09-22T17:20:44.000Z",+ "durationMs": 30584,+ "models": [+ "cursor-auto"+ ],+ "pathMode": "relative",+ "truncated": false,+ "outcome": "completed",+ "role": "root",+ "parentSessionId": null+ },+ "totals": {+ "calls": 4,+ "requests": 3,+ "userTurns": 1,+ "subagents": 0,+ "errors": 0,+ "tokens": 0,+ "costUsd": 0,+ "filesTouched": 2,+ "prsCreated": 0,+ "filesCreated": 0,+ "filesDeleted": 0,+ "errorsBySource": {},+ "errorsByClass": {},+ "retries": 0,+ "delays": 0,+ "delayMs": 0,+ "maxContext": 0,+ "compactions": 0,+ "llmLatencyP50": 2817,+ "llmLatencyP95": 7824,+ "outputTokens": 0,+ "tasks": 1,+ "commits": 0+ },+ "repos": [+ {+ "id": "r0",+ "name": "acme/web",+ "remote": "[email protected]:acme/web.git"+ }+ ],+ "files": [+ {+ "id": 0,+ "repo": "r0",+ "path": "src/pages/cart.tsx",+ "reads": 0,+ "edits": 1,+ "hits": 1,+ "first": 2,+ "op": "modify"+ },+ {+ "id": 1,+ "repo": "r0",+ "path": "src/i18n/en.json",+ "reads": 1,+ "edits": 1,+ "hits": 1,+ "first": 2,+ "op": "modify"+ }+ ],+ "prs": [],+ "agents": [+ {+ "id": "main",+ "parent": null,+ "kind": "main",+ "start": 12261,+ "end": 30584,+ "calls": 4,+ "requests": 3,+ "tokens": 0,+ "cost": 0,+ "outcome": "completed"+ }+ ],+ "tasks": [+ {+ "n": 1,+ "id": "task:1",+ "name": "Update the empty-cart copy",+ "source": "segments",+ "startSeq": 0,+ "endSeq": 7,+ "startT": 12261,+ "endT": 30584+ }+ ],+ "events": [+ {+ "seq": 0,+ "t": 12261,+ "agent": "main",+ "err": false,+ "kind": "user",+ "chars": 180,+ "task": 1+ },+ {+ "seq": 1,+ "t": 15174,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "cursor-auto",+ "in": 0,+ "cw": 0,+ "cr": 0,+ "out": 0,+ "cost": 0,+ "latency": 2817,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 396,+ "task": 1+ },+ {+ "seq": 2,+ "t": 16010,+ "agent": "main",+ "err": false,+ "kind": "search",+ "tool": "Grep",+ "verb": "grep",+ "targets": [+ {+ "file": 0,+ "touch": "hit"+ },+ {+ "file": 1,+ "touch": "hit"+ }+ ],+ "cat": "file",+ "model": "cursor-auto",+ "task": 1+ },+ {+ "seq": 3,+ "t": 17704,+ "agent": "main",+ "err": false,+ "kind": "read",+ "tool": "read_file",+ "targets": [+ {+ "file": 1,+ "touch": "read"+ }+ ],+ "cat": "file",+ "model": "cursor-auto",+ "task": 1+ },+ {+ "seq": 4,+ "t": 25584,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "cursor-auto",+ "in": 0,+ "cw": 0,+ "cr": 0,+ "out": 0,+ "cost": 0,+ "latency": 7824,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 468,+ "task": 1+ },+ {+ "seq": 5,+ "t": 27076,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "edit_file",+ "targets": [+ {+ "file": 1,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "cursor-auto",+ "task": 1+ },+ {+ "seq": 6,+ "t": 28795,+ "agent": "main",+ "err": false,+ "kind": "edit",+ "tool": "edit_file",+ "targets": [+ {+ "file": 0,+ "touch": "edit",+ "op": "modify"+ }+ ],+ "cat": "file",+ "model": "cursor-auto",+ "task": 1+ },+ {+ "seq": 7,+ "t": 30584,+ "agent": "main",+ "err": false,+ "kind": "llm",+ "model": "cursor-auto",+ "in": 0,+ "cw": 0,+ "cr": 0,+ "out": 0,+ "cost": 0,+ "latency": 1900,+ "stop": "tool_use",+ "toolCalls": 1,+ "thinking": false,+ "textChars": 252,+ "task": 1+ }+ ]+}diff --git a/viewer/public/demo/index.json b/viewer/public/demo/index.jsonnew file mode 100644index 0000000..f2abd6f--- /dev/null+++ b/viewer/public/demo/index.json@@ -0,0 +1,136 @@+{+ "note": "Synthetic demo sessions generated by scripts/make-demo.mjs. Not real transcripts.",+ "sessions": [+ {+ "sessionId": "local:claude-code:5f2c9a1e-7b44-4d0e-9c1a-demo00000001",+ "sessionDate": "2026-09-24",+ "startedAt": "2026-09-24T14:05:12.000Z",+ "endedAt": "2026-09-24T14:09:21.685Z",+ "durationMs": 249685,+ "agentTool": "claude-code",+ "models": [+ "claude-haiku-4-5",+ "claude-opus-4-5",+ "claude-sonnet-4-5"+ ],+ "repos": [+ "acme/api"+ ],+ "calls": 26,+ "requests": 20,+ "subagents": 1,+ "errors": 2,+ "filesTouched": 10,+ "costUsd": 1.9251,+ "tokens": 1239680,+ "userTurns": 3,+ "sessionTitle": "Demo: Add rate limiting to the orders API",+ "contentHash": "36537ba819a74723",+ "bytesGz": null,+ "updatedAt": null,+ "errorsBySource": {+ "tool": 1,+ "llm": 1+ },+ "retries": 1,+ "delays": 2,+ "maxContext": 161000,+ "compactions": 1,+ "role": "root",+ "parentSessionId": null,+ "tasks": 3,+ "outputs": {+ "commit": 1,+ "pr_comment": 1+ },+ "prs": [+ {+ "repo": "acme/api",+ "number": 142,+ "url": "https://github.com/acme/api/pull/142",+ "state": "open"+ }+ ],+ "file": "claude-code-rate-limit.json"+ },+ {+ "sessionId": "local:codex:0199a3b2-demo-4f0c-8e55-000000000002",+ "sessionDate": "2026-09-23",+ "startedAt": "2026-09-23T09:41:03.000Z",+ "endedAt": "2026-09-23T09:43:15.039Z",+ "durationMs": 132039,+ "agentTool": "codex",+ "models": [+ "gpt-5-codex"+ ],+ "repos": [+ "acme/web",+ "acme/ui-kit"+ ],+ "calls": 12,+ "requests": 11,+ "subagents": 0,+ "errors": 2,+ "filesTouched": 4,+ "costUsd": 0.0851,+ "tokens": 314060,+ "userTurns": 2,+ "sessionTitle": "Demo: Fix a flaky timezone test",+ "contentHash": "ccc87449f7aec04f",+ "bytesGz": null,+ "updatedAt": null,+ "errorsBySource": {+ "tool": 2+ },+ "retries": 1,+ "delays": 0,+ "maxContext": 38000,+ "compactions": 0,+ "role": "root",+ "parentSessionId": null,+ "tasks": 2,+ "outputs": {+ "commit": 1+ },+ "prs": [],+ "file": "codex-flaky-test.json"+ },+ {+ "sessionId": "local:cursor:c1d2e3f4-demo-4a5b-9c8d-000000000003",+ "sessionDate": "2026-09-22",+ "startedAt": "2026-09-22T17:20:44.000Z",+ "endedAt": "2026-09-22T17:21:14.584Z",+ "durationMs": 30584,+ "agentTool": "cursor",+ "models": [+ "cursor-auto"+ ],+ "repos": [+ "acme/web"+ ],+ "calls": 4,+ "requests": 3,+ "subagents": 0,+ "errors": 0,+ "filesTouched": 2,+ "costUsd": 0,+ "tokens": 0,+ "userTurns": 1,+ "sessionTitle": "Demo: Update empty-cart copy",+ "contentHash": "abf82441087c6dfc",+ "bytesGz": null,+ "updatedAt": null,+ "errorsBySource": {},+ "retries": 0,+ "delays": 0,+ "maxContext": 0,+ "compactions": 0,+ "role": "root",+ "parentSessionId": null,+ "tasks": 1,+ "outputs": {},+ "prs": [],+ "file": "cursor-copy-tweak.json"+ }+ ]+}diff --git a/viewer/scripts/make-demo.mjs b/viewer/scripts/make-demo.mjsnew file mode 100644index 0000000..c10f949--- /dev/null+++ b/viewer/scripts/make-demo.mjs@@ -0,0 +1,514 @@+#!/usr/bin/env node+/**+ * Generate the bundled demo sessions: `public/demo/index.json` plus one+ * `agentplay/v1` map document per session.+ *+ * Everything here is SYNTHETIC: invented repos (acme/*), invented PR numbers+ * and hashes, no real transcript behind any of it. The output is fully+ * deterministic (seeded PRNG, fixed dates), so re-running the script produces+ * byte-identical files.+ *+ * node scripts/make-demo.mjs+ */+import fs from 'node:fs';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';++const OUT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../public/demo');+const SCHEMA = 'agentplay/v1';++// --- deterministic PRNG (mulberry32) ----------------------------------------+function rng(seed) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** $ per million tokens: fresh input, cache write, cache read, output. */+const PRICE = {+ 'claude-opus-4-5': [5, 6.25, 0.5, 25],+ 'claude-sonnet-4-5': [3, 3.75, 0.3, 15],+ 'claude-haiku-4-5': [1, 1.25, 0.1, 5],+ 'gpt-5-codex': [1.25, 0, 0.125, 10],+ 'cursor-auto': [1.25, 0, 0.125, 6],+};++const NON_CALL = new Set([+ 'llm', 'user', 'compaction', 'error', 'delay', 'model_switch',+ 'commit', 'pr_merge', 'pr_close', 'pr_comment', 'ticket', 'artifact', 'skill_write',+]);++const CAT = {+ read: 'file', edit: 'file', search: 'file', exec: 'shell', verify: 'test',+ mcp: 'mcp', web: 'web', skill: 'skill', subagent: 'subagent', tool: 'tool',+};++class Session {+ constructor({ id, agentTool, startedAt, cliVersion, seed, repos }) {+ this.id = id;+ this.agentTool = agentTool;+ this.startedAt = startedAt;+ this.cliVersion = cliVersion;+ this.rand = rng(seed);+ this.t = 0;+ this.events = [];+ this.repos = repos.map((r, i) => ({ id: `r${i}`, name: r, remote: `[email protected]:${r}.git` }));+ this.files = [];+ this.agents = [{ id: 'main', parent: null, kind: 'main' }];+ this.prs = [];+ this.segments = [];+ this.model = { main: null };+ }++ /** advance the clock by `lo..hi` ms (deterministic) */+ tick(lo, hi) {+ this.t += Math.round(lo + this.rand() * (hi - lo));+ return this.t;+ }++ file(repo, p) {+ const r = this.repos.find((x) => x.name === repo);+ let f = this.files.find((x) => x.repo === r.id && x.path === p);+ if (!f) {+ f = { id: this.files.length, repo: r.id, path: p, reads: 0, edits: 0, hits: 0 };+ this.files.push(f);+ }+ return f.id;+ }++ push(ev, gap = [400, 2600]) {+ const e = { seq: this.events.length, t: this.tick(...gap), agent: 'main', err: false, ...ev };+ if (!NON_CALL.has(e.kind) && !e.cat) e.cat = e.vcs ? 'vcs' : CAT[e.kind] ?? 'tool';+ this.events.push(e);+ return e;+ }++ task(name) {+ this.segments.push({ name, start: this.events.length });+ }++ user(chars, extra = {}) {+ return this.push({ kind: 'user', chars, ...extra }, [4000, 20000]);+ }++ llm(model, { agent = 'main', ctx = 30000, out = 600, latency } = {}) {+ const prev = this.model[agent];+ if (prev && prev !== model && agent === 'main') {+ this.push({ kind: 'model_switch', agent, from: prev, to: model }, [0, 5]);+ }+ this.model[agent] = model;+ // Cursor does not write billed usage to disk, so its events carry zeros.+ const noUsage = this.agentTool === 'cursor';+ const cached = Math.round(ctx * (0.72 + this.rand() * 0.2));+ const cw = Math.round((ctx - cached) * 0.8);+ const fresh = ctx - cached - cw;+ const [pi, pw, pr, po] = PRICE[model];+ const cost = (fresh * pi + cw * pw + cached * pr + out * po) / 1e6;+ const lat = latency ?? Math.round(1800 + this.rand() * 5200 + out * 4);+ return this.push(+ {+ kind: 'llm',+ agent,+ model,+ in: noUsage ? 0 : fresh,+ cw: noUsage ? 0 : cw,+ cr: noUsage ? 0 : cached,+ out: noUsage ? 0 : out,+ cost: noUsage ? 0 : Math.round(cost * 1e5) / 1e5,+ latency: lat,+ stop: 'tool_use',+ toolCalls: 1,+ thinking: model.startsWith('claude') && this.rand() > 0.5,+ textChars: Math.round(out * 1.8),+ },+ [lat - 200, lat + 200]+ );+ }++ read(repo, p, agent = 'main', tool = 'Read') {+ return this.push({ kind: 'read', agent, tool, targets: [{ file: this.file(repo, p), touch: 'read' }] });+ }++ search(repo, paths, agent = 'main', verb = 'rg') {+ return this.push({+ kind: 'search',+ agent,+ tool: 'Grep',+ verb,+ targets: paths.map((p) => ({ file: this.file(repo, p), touch: 'hit' })),+ });+ }++ edit(repo, p, op = 'modify', agent = 'main', tool = 'Edit') {+ return this.push({+ kind: 'edit',+ agent,+ tool: op === 'create' ? 'Write' : tool,+ targets: [{ file: this.file(repo, p), touch: 'edit', op }],+ });+ }++ exec(verb, extra = {}) {+ return this.push({ kind: 'exec', tool: 'Bash', verb, ...extra }, [900, 6000]);+ }++ verify(verb, extra = {}) {+ return this.push({ kind: 'verify', tool: 'Bash', verb, cat: 'test', ...extra }, [3000, 16000]);+ }++ subagent(child, subagentType, model) {+ this.agents.push({ id: child, parent: 'main', kind: 'subagent', subagentType, launchSeq: this.events.length });+ return this.push({ kind: 'subagent', tool: 'Task', subagentType, child, model });+ }++ commit(repo, sha, files, ins, del) {+ this.exec('git', { vcs: { provider: 'git', action: 'commit', repo } });+ return this.push({ kind: 'commit', repo, sha, files, ins, del }, [50, 200]);+ }++ prCreate(repo, number) {+ const e = this.exec('gh', { vcs: { provider: 'github', action: 'pr_create', repo, number } });+ this.prs.push({ provider: 'github', repo, number, url: `https://github.com/${repo}/pull/${number}`, seq: e.seq, state: 'open' });+ return e;+ }++ finish({ outcome }) {+ const evs = this.events;+ // per-file touch counts and last op+ for (const e of evs) {+ for (const t of e.targets ?? []) {+ if (t.file == null) continue;+ const f = this.files[t.file];+ if (t.touch === 'edit') f.edits++;+ else if (t.touch === 'read') f.reads++;+ else f.hits++;+ if (f.first == null) f.first = e.seq;+ if (t.op) f.op = f.op === 'create' ? 'create' : t.op;+ }+ }+ // stamp the driving model on every event+ let cur = {};+ for (const e of evs) {+ if (e.kind === 'llm') cur[e.agent] = e.model;+ if (e.kind !== 'llm' && e.kind !== 'model_switch' && cur[e.agent] && !e.model) e.model = cur[e.agent];+ }+ // tasks from the named segments+ const tasks = this.segments.map((s, i) => {+ const end = (this.segments[i + 1]?.start ?? evs.length) - 1;+ return {+ n: i + 1,+ id: `task:${i + 1}`,+ name: s.name,+ source: 'segments',+ startSeq: s.start,+ endSeq: end,+ startT: evs[s.start].t,+ endT: evs[end].t,+ };+ });+ for (const task of tasks) for (let i = task.startSeq; i <= task.endSeq; i++) evs[i].task = task.n;++ const llm = evs.filter((e) => e.kind === 'llm');+ const agents = this.agents.map((a) => {+ const mine = evs.filter((e) => e.agent === a.id);+ return {+ ...a,+ start: mine[0].t,+ end: mine[mine.length - 1].t,+ calls: mine.filter((e) => !NON_CALL.has(e.kind)).length,+ requests: mine.filter((e) => e.kind === 'llm').length,+ tokens: mine.reduce((s, e) => s + (e.in ?? 0) + (e.cw ?? 0) + (e.cr ?? 0) + (e.out ?? 0), 0),+ cost: round4(mine.reduce((s, e) => s + (e.kind === 'llm' ? e.cost : 0), 0)),+ outcome: a.id === 'main' ? outcome : 'completed',+ };+ });+ const bySrc = {};+ const byCls = {};+ for (const e of evs) {+ if (!e.err) continue;+ const src = e.kind === 'error' ? e.source ?? 'tool' : e.kind === 'mcp' ? 'mcp' : e.kind === 'subagent' ? 'orchestration' : 'tool';+ bySrc[src] = (bySrc[src] ?? 0) + 1;+ const cls = e.errClass ?? 'other';+ byCls[cls] = (byCls[cls] ?? 0) + 1;+ }+ const lats = llm.map((e) => e.latency).sort((a, b) => a - b);+ const delays = evs.filter((e) => e.kind === 'delay');+ const ctx = llm.filter((e) => e.agent === 'main').map((e) => e.in + e.cw + e.cr);+ const models = [...new Set(llm.map((e) => e.model))].sort();+ const totals = {+ calls: evs.filter((e) => !NON_CALL.has(e.kind)).length,+ requests: llm.length,+ userTurns: evs.filter((e) => e.kind === 'user').length,+ subagents: agents.length - 1,+ errors: evs.filter((e) => e.err).length,+ tokens: llm.reduce((s, e) => s + e.in + e.cw + e.cr + e.out, 0),+ costUsd: round4(llm.reduce((s, e) => s + e.cost, 0)),+ filesTouched: this.files.length,+ prsCreated: this.prs.length,+ filesCreated: this.files.filter((f) => f.op === 'create').length,+ filesDeleted: this.files.filter((f) => f.op === 'delete').length,+ errorsBySource: bySrc,+ errorsByClass: byCls,+ retries: evs.filter((e) => e.retryOf != null).length,+ delays: delays.length,+ delayMs: delays.reduce((s, e) => s + e.ms, 0),+ maxContext: Math.max(0, ...ctx),+ compactions: evs.filter((e) => e.kind === 'compaction').length,+ llmLatencyP50: lats[Math.floor(lats.length / 2)] ?? 0,+ llmLatencyP95: lats[Math.min(lats.length - 1, Math.floor(lats.length * 0.95))] ?? 0,+ outputTokens: llm.reduce((s, e) => s + e.out, 0),+ tasks: tasks.length,+ commits: evs.filter((e) => e.kind === 'commit').length,+ };+ for (const pr of this.prs) {+ if (evs.some((e) => e.kind === 'pr_merge' && e.number === pr.number)) pr.state = 'merged';+ }+ return {+ schema: SCHEMA,+ session: {+ id: this.id,+ agentTool: this.agentTool,+ cliVersion: this.cliVersion,+ startedAt: this.startedAt,+ durationMs: evs[evs.length - 1].t,+ models,+ pathMode: 'relative',+ truncated: false,+ outcome,+ role: 'root',+ parentSessionId: null,+ },+ totals,+ repos: this.repos,+ files: this.files,+ prs: this.prs,+ agents,+ tasks,+ events: evs,+ };+ }+}++const round4 = (n) => Math.round(n * 1e4) / 1e4;++// --- session 1: Claude Code, rate limiting in acme/api ----------------------+function claudeSession() {+ const s = new Session({+ id: 'local:claude-code:5f2c9a1e-7b44-4d0e-9c1a-demo00000001',+ agentTool: 'claude-code',+ startedAt: '2026-09-24T14:05:12.000Z',+ cliVersion: '2.1.4',+ seed: 11,+ repos: ['acme/api'],+ });+ const R = 'acme/api';+ const O = 'claude-opus-4-5';+ const H = 'claude-haiku-4-5';+ const S = 'claude-sonnet-4-5';++ s.task('Explore the request pipeline');+ s.user(1180, { urls: 1 });+ s.llm(O, { ctx: 18000, out: 420 });+ s.read(R, 'README.md');+ s.llm(O, { ctx: 21000, out: 380 });+ s.subagent('sub-explore', 'Explore', H);+ s.llm(H, { agent: 'sub-explore', ctx: 9000, out: 300 });+ s.search(R, ['src/middleware/index.ts', 'src/middleware/auth.ts', 'src/server.ts'], 'sub-explore');+ s.llm(H, { agent: 'sub-explore', ctx: 12000, out: 260 });+ s.read(R, 'src/middleware/index.ts', 'sub-explore');+ s.read(R, 'src/middleware/auth.ts', 'sub-explore');+ s.llm(H, { agent: 'sub-explore', ctx: 16000, out: 280 });+ s.read(R, 'src/server.ts', 'sub-explore');+ s.read(R, 'src/config/env.ts', 'sub-explore');+ s.llm(H, { agent: 'sub-explore', ctx: 21000, out: 900 });+ s.llm(O, { ctx: 26000, out: 520 });+ s.read(R, 'src/routes/orders.ts');+ s.read(R, 'package.json');+ s.push({ kind: 'mcp', server: 'docs', tool: 'search_docs', outBytes: 4200, dur: 820 });+ s.llm(O, { ctx: 31000, out: 640 });++ s.task('Add a token-bucket rate limiter');+ s.user(420);+ s.llm(O, { ctx: 72000, out: 1400 });+ s.edit(R, 'src/middleware/rateLimit.ts', 'create');+ s.llm(O, { ctx: 88000, out: 700 });+ s.edit(R, 'src/middleware/index.ts');+ s.edit(R, 'src/config/env.ts');+ s.llm(O, { ctx: 104000, out: 1100 });+ s.edit(R, 'test/rateLimit.test.ts', 'create');+ s.llm(O, { ctx: 117000, out: 300 });+ const failed = s.verify('npm test', { err: true, errClass: 'exit_code', exitCode: 1, dur: 14200 });+ s.llm(O, { ctx: 129000, out: 520 });+ s.read(R, 'src/middleware/rateLimit.ts');+ s.edit(R, 'src/middleware/rateLimit.ts');+ s.llm(O, { ctx: 138000, out: 260 });+ const pass = s.verify('npm test', { retryOf: failed.seq, attempt: 2, dur: 12800 });+ s.push({ kind: 'delay', cause: 'tool', ms: 12800, ref: pass.seq }, [50, 100]);+ s.push({ kind: 'error', source: 'llm', errClass: 'overloaded', err: true, retry: true }, [800, 1500]);+ s.llm(O, { ctx: 149000, out: 480, latency: 21000 });+ s.push({ kind: 'delay', cause: 'llm', ms: 21000, ref: s.events.length - 1 }, [50, 100]);+ s.exec('npx', { verb: 'tsc', dur: 6100 });+ s.llm(O, { ctx: 161000, out: 220 });+ s.edit(R, 'src/routes/orders.ts');+ s.edit(R, 'docs/rate-limits.md', 'create');++ s.task('Commit and open a PR');+ s.user(160);+ s.push({ kind: 'compaction', trigger: 'auto', preTokens: 168400, postTokens: 23100 }, [1200, 2000]);+ s.model.main = O;+ s.llm(S, { ctx: 24000, out: 380 });+ s.exec('git', { vcs: { provider: 'git', action: 'status', repo: R } });+ s.exec('git', { vcs: { provider: 'git', action: 'diff', repo: R } });+ s.llm(S, { ctx: 29000, out: 540 });+ s.commit(R, '9d41c07be2a1', 6, 214, 12);+ s.exec('git', { vcs: { provider: 'git', action: 'push', repo: R } });+ s.llm(S, { ctx: 31000, out: 820 });+ s.prCreate(R, 142);+ s.push({ kind: 'pr_comment', repo: R, number: 142, url: 'https://github.com/acme/api/pull/142' });+ s.llm(S, { ctx: 33000, out: 260, latency: 2600 });+ return {+ doc: s.finish({ outcome: 'pr_created' }),+ title: 'Demo: Add rate limiting to the orders API',+ file: 'claude-code-rate-limit.json',+ };+}++// --- session 2: Codex, flaky date test in acme/web --------------------------+function codexSession() {+ const s = new Session({+ id: 'local:codex:0199a3b2-demo-4f0c-8e55-000000000002',+ agentTool: 'codex',+ startedAt: '2026-09-23T09:41:03.000Z',+ cliVersion: '0.44.0',+ seed: 23,+ repos: ['acme/web', 'acme/ui-kit'],+ });+ const W = 'acme/web';+ const U = 'acme/ui-kit';+ const M = 'gpt-5-codex';+ s.task('Reproduce the flaky date test');+ s.user(640);+ s.llm(M, { ctx: 14000, out: 300 });+ s.exec('rg', { kind: 'search', tool: 'shell', targets: [+ { file: s.file(W, 'src/lib/formatDate.ts'), touch: 'hit' },+ { file: s.file(W, 'src/lib/formatDate.test.ts'), touch: 'hit' },+ { file: s.file(W, 'src/components/OrderRow.tsx'), touch: 'hit' },+ ] });+ s.llm(M, { ctx: 17000, out: 260 });+ s.read(W, 'src/lib/formatDate.ts', 'main', 'shell');+ s.read(W, 'src/lib/formatDate.test.ts', 'main', 'shell');+ s.llm(M, { ctx: 21000, out: 240 });+ const f1 = s.verify('pnpm vitest', { tool: 'shell', err: true, errClass: 'exit_code', exitCode: 1, dur: 9100 });+ s.llm(M, { ctx: 24000, out: 380 });+ s.exec('TZ=Pacific/Auckland pnpm', { tool: 'shell', verb: 'pnpm', err: true, errClass: 'exit_code', exitCode: 1 });+ s.llm(M, { ctx: 26000, out: 420 });+ s.read(U, 'src/date/index.ts', 'main', 'shell');+ s.push({ kind: 'web', tool: 'web_search', host: 'developer.mozilla.org' });+ s.llm(M, { ctx: 30000, out: 520 });++ s.task('Fix the timezone handling');+ s.user(210);+ s.llm(M, { ctx: 32000, out: 900 });+ s.edit(W, 'src/lib/formatDate.ts', 'modify', 'main', 'apply_patch');+ s.edit(W, 'src/lib/formatDate.test.ts', 'modify', 'main', 'apply_patch');+ s.llm(M, { ctx: 35000, out: 300 });+ s.verify('pnpm vitest', { tool: 'shell', retryOf: f1.seq, attempt: 2, dur: 8800 });+ s.llm(M, { ctx: 36000, out: 200 });+ s.verify('pnpm lint', { tool: 'shell', cat: 'build', dur: 7400 });+ s.llm(M, { ctx: 37000, out: 360 });+ s.commit(W, '3be07f19ac44', 2, 18, 7);+ s.llm(M, { ctx: 38000, out: 180, latency: 2100 });+ return {+ doc: s.finish({ outcome: 'verified' }),+ title: 'Demo: Fix a flaky timezone test',+ file: 'codex-flaky-test.json',+ };+}++// --- session 3: Cursor, short copy change -----------------------------------+function cursorSession() {+ const s = new Session({+ id: 'local:cursor:c1d2e3f4-demo-4a5b-9c8d-000000000003',+ agentTool: 'cursor',+ startedAt: '2026-09-22T17:20:44.000Z',+ cliVersion: '1.7',+ seed: 37,+ repos: ['acme/web'],+ });+ const W = 'acme/web';+ const M = 'cursor-auto';+ s.task('Update the empty-cart copy');+ s.user(180);+ s.llm(M, { ctx: 9000, out: 220 });+ s.search(W, ['src/pages/cart.tsx', 'src/i18n/en.json'], 'main', 'grep');+ s.read(W, 'src/i18n/en.json', 'main', 'read_file');+ s.llm(M, { ctx: 11000, out: 260 });+ s.edit(W, 'src/i18n/en.json', 'modify', 'main', 'edit_file');+ s.edit(W, 'src/pages/cart.tsx', 'modify', 'main', 'edit_file');+ s.llm(M, { ctx: 12500, out: 140, latency: 1900 });+ return {+ doc: s.finish({ outcome: 'completed' }),+ title: 'Demo: Update empty-cart copy',+ file: 'cursor-copy-tweak.json',+ };+}++// --- write -----------------------------------------------------------------+fs.mkdirSync(OUT, { recursive: true });+const rows = [];+for (const make of [claudeSession, codexSession, cursorSession]) {+ const { doc, title, file } = make();+ const text = `${JSON.stringify(doc, null, 1)}\n`;+ fs.writeFileSync(path.join(OUT, file), text);+ const t = doc.totals;+ const outputs = {};+ for (const e of doc.events) {+ if (['commit', 'pr_merge', 'pr_close', 'pr_comment', 'ticket', 'artifact', 'skill_write'].includes(e.kind)) {+ outputs[e.kind] = (outputs[e.kind] ?? 0) + 1;+ }+ }+ rows.push({+ sessionId: doc.session.id,+ sessionDate: doc.session.startedAt.slice(0, 10),+ startedAt: doc.session.startedAt,+ endedAt: new Date(Date.parse(doc.session.startedAt) + doc.session.durationMs).toISOString(),+ durationMs: doc.session.durationMs,+ agentTool: doc.session.agentTool,+ models: doc.session.models,+ repos: doc.repos.map((r) => r.name),+ calls: t.calls,+ requests: t.requests,+ subagents: t.subagents,+ errors: t.errors,+ filesTouched: t.filesTouched,+ costUsd: t.costUsd,+ tokens: t.tokens,+ userTurns: t.userTurns,+ sessionTitle: title,+ contentHash: createHash('sha256').update(text).digest('hex').slice(0, 16),+ bytesGz: null,+ updatedAt: null,+ errorsBySource: t.errorsBySource,+ retries: t.retries,+ delays: t.delays,+ maxContext: t.maxContext,+ compactions: t.compactions,+ role: 'root',+ parentSessionId: null,+ tasks: doc.tasks.length,+ outputs,+ prs: doc.prs.map(({ repo, number, url, state }) => ({ repo, number, url, state })),+ file,+ });+}+fs.writeFileSync(+ path.join(OUT, 'index.json'),+ `${JSON.stringify({ note: 'Synthetic demo sessions generated by scripts/make-demo.mjs. Not real transcripts.', sessions: rows }, null, 1)}\n`+);+console.log(`wrote ${rows.length} demo sessions to ${path.relative(process.cwd(), OUT)}`);diff --git a/viewer/scripts/screenshots.mjs b/viewer/scripts/screenshots.mjsnew file mode 100644index 0000000..0324a6c--- /dev/null+++ b/viewer/scripts/screenshots.mjs@@ -0,0 +1,76 @@+#!/usr/bin/env node+/**+ * Serve `dist/` in demo mode and capture the explorer in light and dark+ * (prefers-color-scheme) into ../docs/images/explorer-{light,dark}.png. Fails on console errors.+ *+ * pnpm build && node scripts/screenshots.mjs+ *+ * Needs a Chromium: set CHROMIUM_PATH, or it looks under+ * $PLAYWRIGHT_BROWSERS_PATH for a playwright-managed build.+ */+import fs from 'node:fs';+import http from 'node:http';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { chromium } from 'playwright-core';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const DIST = path.join(ROOT, 'dist');+const OUT = path.join(ROOT, '../docs/images');+const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.woff2': 'font/woff2' };++function findChromium() {+ if (process.env.CHROMIUM_PATH) return process.env.CHROMIUM_PATH;+ const base = process.env.PLAYWRIGHT_BROWSERS_PATH ?? '/opt/pw-browsers';+ for (const d of fs.existsSync(base) ? fs.readdirSync(base).sort().reverse() : []) {+ if (!d.startsWith('chromium-')) continue;+ for (const rel of ['chrome-linux/chrome', 'chrome-mac/Chromium.app/Contents/MacOS/Chromium', 'chrome-win/chrome.exe']) {+ const p = path.join(base, d, rel);+ if (fs.existsSync(p)) return p;+ }+ }+ return undefined;+}++// A static server that, like a plain file host, has no /api (so the viewer+// falls back to demo mode on its own).+const server = http.createServer((req, res) => {+ const url = new URL(req.url, 'http://x');+ let file = path.join(DIST, decodeURIComponent(url.pathname));+ if (file.endsWith('/')) file = path.join(file, 'index.html');+ if (!file.startsWith(DIST) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {+ res.writeHead(404).end('not found');+ return;+ }+ res.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream' });+ fs.createReadStream(file).pipe(res);+});+await new Promise((r) => server.listen(0, '127.0.0.1', r));+const port = server.address().port;+const sessionId = process.env.SESSION ?? 'local:claude-code:5f2c9a1e-7b44-4d0e-9c1a-demo00000001';++fs.mkdirSync(OUT, { recursive: true });+const browser = await chromium.launch({ executablePath: findChromium() });+const problems = [];+for (const scheme of ['light', 'dark']) {+ const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 }, colorScheme: scheme, deviceScaleFactor: 1 });+ const page = await ctx.newPage();+ page.on('console', (m) => {+ if (m.type() === 'error' || m.type() === 'warning') problems.push(`[${scheme}] console.${m.type()}: ${m.text()}`);+ });+ page.on('pageerror', (e) => problems.push(`[${scheme}] pageerror: ${e.message}`));+ await page.goto(`http://127.0.0.1:${port}/?demo&session=${encodeURIComponent(sessionId)}${process.env.QUERY ?? ''}`);+ await page.waitForSelector('svg circle', { timeout: 15000 });+ await page.waitForSelector('canvas', { timeout: 15000 });+ await page.waitForTimeout(800);+ const file = path.join(OUT, `${process.env.PREFIX ?? 'explorer-'}${scheme}.png`);+ await page.screenshot({ path: file });+ console.log(`saved ${path.relative(ROOT, file)}`);+ await ctx.close();+}+await browser.close();+server.close();+if (problems.length) {+ console.error(problems.join('\n'));+ process.exit(1);+}diff --git a/viewer/src/App.tsx b/viewer/src/App.tsxnew file mode 100644index 0000000..ebb447d--- /dev/null+++ b/viewer/src/App.tsx@@ -0,0 +1,306 @@+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';+import { parseAsStringEnum, useQueryState, useQueryStates, parseAsString } from 'nuqs';+import {+ FileArrowUp,+ MapTrifold,+ Moon,+ Sun,+ X,+} from '@phosphor-icons/react';+import { Button } from '@/components/ui/button';+import { Badge } from '@/components/ui/badge';+import { SessionExplorer } from '@/explorer/SessionExplorer';+import { SessionExplorerSkeleton } from '@/explorer/SessionExplorerStates';+import { WINDOW_KEYS, type WindowKey } from '@/core/windowOptions';+import { SessionMapSourceProvider } from '@/data/SourceContext';+import { demoSource } from '@/data/demoSource';+import { fileSource, type OpenResult } from '@/data/fileSource';+import { httpSource, probeServer } from '@/data/httpSource';+import type { SessionMapSource } from '@/data/source';+import { useSessionExplorerStatus } from '@/data/hooks';+import { AccountChip, useAccount, WelcomeGate } from '@/app/AccountGate';+import { PlatformBanner } from '@/app/PlatformBanner';+import { useTheme } from '@/app/theme';+import { useFileDrop } from '@/app/useFileDrop';+import {+ SAMPLE_QUERY,+ SampleModeProvider,+ showsOpenedFiles,+ type SampleMode,+} from '@/app/sampleMode';++type Mode = 'probing' | 'server' | 'demo';++/** `?server=http://host:port` points the viewer at a server on another+ * origin (e.g. `vite dev` against a running CLI); default is same-origin. */+function serverBase(): string {+ const p = new URLSearchParams(window.location.search).get('server');+ return p && /^https?:\/\//.test(p) ? p : '';+}++/** Local server if `/api/status` answers, else the bundled demo sessions.+ *+ * `?demo` still forces the demo, but it is read as a query param rather than+ * latched at mount, so "See sample" can switch into the demo and Back can+ * switch out of it -- both are just the URL changing. The probe runs either+ * way, because the answer is what tells us whether there are real sessions to+ * go back to. */+function useProbedMode(base: string): Mode {+ const [mode, setMode] = useState<Mode>('probing');+ useEffect(() => {+ let live = true;+ void probeServer(base).then((ok) => {+ if (live) setMode(ok ? 'server' : 'demo');+ });+ return () => {+ live = false;+ };+ }, [base]);+ return mode;+}++export function App() {+ const base = useMemo(serverBase, []);+ const probed = useProbedMode(base);+ const server = useMemo(() => httpSource(base), [base]);+ // Only the CLI's own server knows about the signup; demo and files never ask.+ const account = useAccount(base, probed === 'server');+ const demo = useMemo(() => demoSource(), []);+ const files = useMemo(() => fileSource(), []);+ // Opened files take over the view; "Back" returns to the base source.+ const [showFiles, setShowFiles] = useState(false);+ // bumped when files are added: `files.id` changes, this re-renders onto it+ const [, setFilesGen] = useState(0);+ const [notice, setNotice] = useState<OpenResult | null>(null);+ // `demo` doubles as the sample switch: present means show the bundled+ // sessions, absent means the user's own. `sample` is the reveal state of+ // the locked block, kept in the URL so it survives the source swap.+ // `sq` (the sessions search) and `win` (the time window) are here because+ // they decide which sessions the explorer can select at all.+ const [sampleQuery, setSampleQuery] = useQueryStates({+ demo: parseAsString,+ sample: parseAsString,+ session: parseAsString,+ view: parseAsString,+ sq: parseAsString,+ win: parseAsString,+ });+ const sampleActive = sampleQuery.demo !== null;+ const mode: Mode = sampleActive ? 'demo' : probed;+ const [windowKey, setWindowKey] = useQueryState(+ 'win',+ parseAsStringEnum<WindowKey>([...WINDOW_KEYS]).withDefault('all')+ );+ const inputRef = useRef<HTMLInputElement>(null);++ const openFiles = useCallback(+ async (list: File[]) => {+ const result = await files.addFiles(list);+ setNotice(result.failed.length || !result.added.length ? result : null);+ if (result.added.length) {+ setFilesGen((g) => g + 1);+ setShowFiles(true);+ // Opening a file leaves the sample: it is the user replacing the+ // view, and the sample now bypasses the file source rather than+ // closing it, so leaving it in place would hide what they opened.+ void setSampleQuery({+ demo: null,+ sample: null,+ session: result.added[0],+ view: null,+ });+ }+ },+ [files, setSampleQuery]+ );+ const dragging = useFileDrop((f) => void openFiles(f));++ const sampleMode = useMemo<SampleMode>(+ () => ({+ active: sampleActive,+ canExit: probed === 'server',+ // Pushed, not replaced: swapping the view out from under someone is+ // only acceptable if the browser's own Back button undoes it. What the+ // query clears, and why, is `SAMPLE_QUERY`. `showFiles` is deliberately+ // left alone -- the sample bypasses an opened file (see `source` below)+ // instead of closing it, so Back returns to the file-backed session.+ show: () => void setSampleQuery(SAMPLE_QUERY, { history: 'push' }),+ exit: () =>+ void setSampleQuery({+ demo: null,+ sample: null,+ session: null,+ view: null,+ }),+ }),+ [sampleActive, probed, setSampleQuery]+ );++ const baseSource = mode === 'server' ? server : demo;+ const openedFiles = showsOpenedFiles({+ showFiles,+ fileCount: files.size,+ sampleActive,+ });+ const source: SessionMapSource = openedFiles ? files : baseSource;+ const picker = (+ <>+ <input+ ref={inputRef}+ type="file"+ accept=".json,.gz,application/json,application/gzip"+ multiple+ hidden+ onChange={(e) => {+ const list = Array.from(e.target.files ?? []);+ e.target.value = '';+ if (list.length) void openFiles(list);+ }}+ />+ <Button variant="outline" size="sm" className="gap-1.5" onClick={() => inputRef.current?.click()}>+ <FileArrowUp size={14} aria-hidden />+ Open map file+ </Button>+ </>+ );++ return (+ <div className="flex h-screen min-h-[700px] w-full flex-col gap-3 px-6 py-3">+ <SessionMapSourceProvider source={source}>+ <SampleModeProvider value={sampleMode}>+ <AppBar+ mode={mode}+ source={source}+ picker={picker}+ onBack={openedFiles ? () => setShowFiles(false) : undefined}+ baseLabel={baseSource.label}+ account={mode === 'server' ? <AccountChip base={base} state={account.data} /> : null}+ />+ {mode !== 'probing' ? <PlatformBanner /> : null}+ {mode === 'demo' && source === demo ? (+ <Banner>+ Demo sessions. Run <code className="font-mono">uvx agentplay</code> (or{' '}+ <code className="font-mono">pipx run agentplay</code>) to see your own, or drop a map+ file anywhere on this page.+ </Banner>+ ) : null}+ {notice ? <OpenNotice result={notice} onClose={() => setNotice(null)} /> : null}+ {mode === 'probing' ? (+ <SessionExplorerSkeleton />+ ) : (+ <SessionExplorer+ key={`explorer:${source.id}`}+ windowKey={windowKey}+ onWindowChange={(k) => void setWindowKey(k === 'all' ? null : k)}+ emptyAction={picker}+ />+ )}+ {mode === 'server' && source === server ? <WelcomeGate base={base} state={account.data} /> : null}+ </SampleModeProvider>+ </SessionMapSourceProvider>+ {dragging ? <DropOverlay /> : null}+ </div>+ );+}++function AppBar({+ mode,+ source,+ picker,+ onBack,+ baseLabel,+ account,+}: {+ mode: Mode;+ source: SessionMapSource;+ picker: ReactNode;+ onBack?: () => void;+ baseLabel: string;+ account: ReactNode;+}) {+ const { theme, toggle } = useTheme();+ const status = useSessionExplorerStatus();+ const count = mode === 'probing' ? null : (status.data?.mapCount ?? null);+ return (+ <header className="flex shrink-0 items-center gap-3">+ <div className="flex items-center gap-2">+ <span className="flex size-7 items-center justify-center rounded-lg border border-ds-brand-subtlest bg-ds-brand-lightest">+ <MapTrifold size={16} weight="duotone" className="text-ds-brand-subtle" aria-hidden />+ </span>+ <span className="ds-text-body-sm-semibold text-ds-text-darker">agentplay</span>+ </div>+ {mode !== 'probing' ? (+ <Badge variant="keyline">+ {source.label}+ {count != null ? ` · ${count} ${count === 1 ? 'map' : 'maps'}` : ''}+ </Badge>+ ) : null}+ {onBack ? (+ <Button variant="ghost" size="sm" className="h-7 px-2 text-ds-text-subtle" onClick={onBack}>+ Back to {baseLabel.toLowerCase()}+ </Button>+ ) : null}+ <div className="ml-auto flex items-center gap-2">+ {account}+ {picker}+ <Button+ variant="ghost"+ size="iconSm"+ aria-label={theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'}+ onClick={toggle}+ >+ {theme === 'dark' ? <Sun size={16} aria-hidden /> : <Moon size={16} aria-hidden />}+ </Button>+ </div>+ </header>+ );+}++function Banner({ children }: { children: ReactNode }) {+ return (+ <div+ role="note"+ className="shrink-0 rounded-lg border border-ds-brand-subtlest bg-ds-brand-lightest px-3 py-2 ds-text-body-xs-medium text-ds-text-default"+ >+ {children}+ </div>+ );+}++function OpenNotice({ result, onClose }: { result: OpenResult; onClose: () => void }) {+ const failed = result.failed;+ return (+ <div+ role="alert"+ className="flex shrink-0 items-start gap-2 rounded-lg border border-ds-danger-subtler bg-ds-danger-subtlest px-3 py-2 ds-text-body-xs-medium text-ds-danger-darkest"+ >+ <div className="flex-1">+ {failed.length+ ? `${failed.length === 1 ? 'One file' : `${failed.length} files`} could not be opened: ${failed+ .map((f) => `${f.name} (${f.reason})`)+ .join(', ')}.`+ : 'No session maps found in those files.'}+ </div>+ <button type="button" aria-label="Dismiss" onClick={onClose} className="shrink-0">+ <X size={14} aria-hidden />+ </button>+ </div>+ );+}++function DropOverlay() {+ return (+ <div+ aria-hidden+ className="pointer-events-none fixed inset-3 z-50 flex items-center justify-center rounded-2xl border-2 border-dashed border-ds-brand-subtler bg-ds-surface-white/80 backdrop-blur-sm"+ >+ <div className="flex flex-col items-center gap-2">+ <FileArrowUp size={28} className="text-ds-brand-subtle" aria-hidden />+ <p className="ds-text-body-sm-semibold text-ds-text-darker">Drop session maps to open them</p>+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ .json or .json.gz, read in this tab only+ </p>+ </div>+ </div>+ );+}diff --git a/viewer/src/app/AccountGate.tsx b/viewer/src/app/AccountGate.tsxnew file mode 100644index 0000000..ec277ab--- /dev/null+++ b/viewer/src/app/AccountGate.tsx@@ -0,0 +1,189 @@+import { useState, type FormEvent } from 'react';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { EnvelopeSimple, LockSimple, MapTrifold } from '@phosphor-icons/react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import {+ AccountError,+ fetchAccount,+ isLocalBase,+ postAccount,+ showsWelcome,+ type AccountAction,+ type AccountState,+} from '@/data/account';+import { useSessionExplorerStatus } from '@/data/hooks';+import { researchUrl } from '@/core/entelligence';++const key = (base: string) => ['account', base] as const;++/** The signup state from the local server; off unless `enabled` and the+ * server is on this machine (see `isLocalBase`). */+export function useAccount(base: string, enabled: boolean) {+ return useQuery({+ queryKey: key(base),+ queryFn: () => fetchAccount(base),+ enabled: enabled && isLocalBase(base),+ staleTime: Infinity,+ retry: false,+ });+}++function useAccountAction(base: string) {+ const qc = useQueryClient();+ return useMutation<AccountState, AccountError, AccountAction>({+ mutationFn: (body) => postAccount(base, body),+ onSuccess: (state) => qc.setQueryData(key(base), state),+ });+}++/**+ * First-run card over the viewer. The user's sessions keep loading behind it,+ * so the first thing they see when it closes is their own data.+ */+export function WelcomeGate({ base, state }: { base: string; state: AccountState | undefined }) {+ const [email, setEmail] = useState('');+ const act = useAccountAction(base);+ const status = useSessionExplorerStatus();+ if (!showsWelcome(state)) return null;++ const count = status.data?.mapCount ?? 0;+ const submit = (e: FormEvent) => {+ e.preventDefault();+ act.mutate({ action: 'signup', email: email.trim() });+ };+ const busy = act.isPending;++ return (+ <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-ds-surface-white/70 p-4 pt-[15vh] backdrop-blur-sm">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="welcome-title"+ className="w-full max-w-md rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-6 shadow-lg"+ >+ <span className="mb-4 flex size-9 items-center justify-center rounded-lg border border-ds-brand-subtlest bg-ds-brand-lightest">+ <MapTrifold size={20} weight="duotone" className="text-ds-brand-subtle" aria-hidden />+ </span>+ <h1 id="welcome-title" className="ds-text-title-md-semibold text-ds-text-darker">+ {count > 0 ? `Your ${count} ${count === 1 ? 'session is' : 'sessions are'} ready` : 'Welcome to agentplay'}+ </h1>+ <p className="mt-1.5 ds-text-body-sm-medium text-ds-text-default">+ agentplay is the first step toward coding agents that learn from their own mistakes.{' '}+ <a+ href={researchUrl('welcome')}+ target="_blank"+ rel="noopener noreferrer"+ className="text-ds-brand-subtle underline underline-offset-2 hover:text-ds-text-darker"+ >+ Read how+ </a>+ , and get updates on Entelligence for you and your team.+ </p>+ <form onSubmit={submit} className="mt-4 flex flex-col gap-2">+ <label htmlFor="welcome-email" className="sr-only">+ </label>+ <div className="flex gap-2">+ <Input+ id="welcome-email"+ type="email"+ autoComplete="email"+ autoFocus+ required+ placeholder="[email protected]"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ aria-invalid={act.isError || undefined}+ aria-describedby={act.isError ? 'welcome-error' : 'welcome-privacy'}+ disabled={busy}+ />+ <Button type="submit" disabled={busy || !email.trim()} className="shrink-0">+ {busy ? 'Saving…' : 'Get updates'}+ </Button>+ </div>+ {act.isError ? (+ <p id="welcome-error" role="alert" className="ds-text-body-xs-medium text-ds-danger-default">+ {act.error.message}+ </p>+ ) : null}+ </form>+ <details id="welcome-privacy" className="mt-3 ds-text-body-xs-medium text-ds-text-subtle">+ <summary className="flex cursor-pointer list-none items-center gap-1.5 [&::-webkit-details-marker]:hidden">+ <LockSimple size={12} className="shrink-0" aria-hidden />+ <span>+ Nothing from your sessions leaves this machine.{' '}+ <span className="underline underline-offset-2">What’s sent?</span>+ </span>+ </summary>+ <p className="mt-1.5 pl-[18px]">+ Signing up sends your email, a random install id, the agentplay version and the time. Your sessions,+ prompts and code never leave this machine. Disconnect any time from the top bar.+ </p>+ </details>+ <div className="mt-5 flex justify-end">+ <Button+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-ds-text-subtle"+ disabled={busy}+ onClick={() => act.mutate({ action: 'skip' })}+ >+ Continue without email+ </Button>+ </div>+ </div>+ </div>+ );+}++/** Top-bar entry: who you are and the way back out, or, after a skip, the way+ * back in. Reopening only changes the cached state; nothing is stored until+ * the card is answered again. */+export function AccountChip({ base, state }: { base: string; state: AccountState | undefined }) {+ const act = useAccountAction(base);+ const qc = useQueryClient();+ if (state?.enabled && state.status === 'skipped') {+ return (+ <Button+ variant="ghost"+ size="sm"+ className="h-7 gap-1.5 px-2 text-ds-text-subtle"+ onClick={() => qc.setQueryData(key(base), { ...state, status: 'none' })}+ >+ <EnvelopeSimple size={14} aria-hidden />+ Get updates+ </Button>+ );+ }+ if (state?.status !== 'signed_up' || !state.email) return null;+ return (+ <Popover>+ <PopoverTrigger+ render={+ <Button variant="ghost" size="sm" className="h-7 gap-1.5 px-2 text-ds-text-subtle">+ <EnvelopeSimple size={14} aria-hidden />+ <span className="max-w-48 truncate">{state.email}</span>+ </Button>+ }+ />+ <PopoverContent align="end" className="w-72 p-3">+ <p className="ds-text-body-xs-medium text-ds-text-default">+ Signed up as <span className="ds-text-body-xs-semibold">{state.email}</span>. Disconnecting removes it+ from this machine and sends Entelligence one request to delete it, with the same details. It is sent once and+ not retried, so if we can't be reached right then, it may not arrive and the email may stay on our list.+ </p>+ <Button+ variant="outline"+ size="sm"+ className="mt-3 w-full"+ disabled={act.isPending}+ onClick={() => act.mutate({ action: 'disconnect' })}+ >+ {act.isPending ? 'Disconnecting…' : 'Disconnect'}+ </Button>+ </PopoverContent>+ </Popover>+ );+}diff --git a/viewer/src/app/PlatformBanner.tsx b/viewer/src/app/PlatformBanner.tsxnew file mode 100644index 0000000..9696c2c--- /dev/null+++ b/viewer/src/app/PlatformBanner.tsx@@ -0,0 +1,61 @@+import { parseAsString, useQueryState } from 'nuqs';+import { ArrowRight } from '@phosphor-icons/react';+import { connectUrl, researchUrl } from '@/core/entelligence';+import { useSampleMode } from '@/app/sampleMode';++const link =+ 'whitespace-nowrap text-ds-brand-default underline underline-offset-2 hover:text-ds-text-darker';++/**+ * A standing line above the explorer: why agentplay exists, and the three ways+ * further in. It stays put on purpose -- it is the one place every view links+ * the write-up, the review demo and the product, without interrupting anyone.+ *+ * The demo link swaps onto the bundled sample (as "See sample" does) and opens+ * the right column's Review tab, where that sample's review comments are.+ * Both are URL params set in one update, so Back undoes the whole jump.+ */+export function PlatformBanner() {+ const sample = useSampleMode();+ const [, setPanel] = useQueryState('panel', parseAsString);+ const openDemo = () => {+ sample.show();+ void setPanel('review');+ };+ return (+ <div+ role="note"+ aria-label="About agentplay"+ className="flex shrink-0 flex-wrap items-center justify-center gap-x-3 gap-y-1 rounded-lg border border-ds-brand-subtlest bg-ds-brand-lightest px-3 py-1.5 text-center ds-text-body-xs-medium text-ds-text-default"+ >+ <span>agentplay is the first step toward coding agents that learn from their own mistakes.</span>+ <a href={researchUrl('banner')} target="_blank" rel="noopener noreferrer" className={link}>+ Read the whitepaper+ </a>+ <span aria-hidden className="text-ds-text-subtler">+ ·+ </span>+ {sample.active && sample.canExit ? (+ <button type="button" onClick={sample.exit} className={link}>+ Back to your sessions+ </button>+ ) : (+ <button type="button" onClick={openDemo} disabled={sample.active} className={link}>+ See it on a sample PR+ </button>+ )}+ <span aria-hidden className="text-ds-text-subtler">+ ·+ </span>+ <a+ href={connectUrl('banner')}+ target="_blank"+ rel="noopener noreferrer"+ className={`${link} inline-flex items-center gap-1`}+ >+ Entelligence for teams+ <ArrowRight size={12} aria-hidden />+ </a>+ </div>+ );+}diff --git a/viewer/src/app/sampleMode.test.ts b/viewer/src/app/sampleMode.test.tsnew file mode 100644index 0000000..696c200--- /dev/null+++ b/viewer/src/app/sampleMode.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest';+import {+ LIST_FILTER_PARAMS,+ SAMPLE_QUERY,+ SAMPLE_SESSION_ID,+ showsOpenedFiles,+} from './sampleMode';++/**+ * "See sample" swaps the whole viewer onto the bundled session the review+ * comments are about. Two things went wrong with that, and both of them are+ * about state the swap did not own: the filters that decide whether the+ * sample is reachable at all, and the file the reader had opened.+ */+describe('the query "See sample" pushes', () => {+ it('asks for the sample session, in the bundled sessions', () => {+ expect(SAMPLE_QUERY.session).toBe(SAMPLE_SESSION_ID);+ expect(SAMPLE_QUERY.demo).toBe('1');+ // ...with the locked block revealed, which is the point of going there.+ expect(SAMPLE_QUERY.sample).toBe('1');+ });++ it('clears every filter the sessions list applies', () => {+ // The explorer selects the first row of the FILTERED list when the+ // session it is asked for is not in it. A search or a time window that+ // excludes the sample therefore landed the reader on a different+ // session, with the preview still blurred. A new list+ // filter has to be cleared here too, which is what this asserts.+ for (const key of LIST_FILTER_PARAMS)+ expect(SAMPLE_QUERY[key], `${key} is cleared`).toBeNull();+ expect([...LIST_FILTER_PARAMS]).toEqual(['sq', 'win']);+ });++ it('does not clear them by leaving them out of the query', () => {+ // nuqs leaves an omitted key alone, so an absent key is not a cleared+ // one: each has to be present and null.+ for (const key of LIST_FILTER_PARAMS)+ expect(Object.hasOwn(SAMPLE_QUERY, key), `${key} is written`).toBe(true);+ });+});++describe('the sample over an opened file', () => {+ const opened = { showFiles: true, fileCount: 1 };++ it('bypasses the opened file rather than closing it', () => {+ expect(showsOpenedFiles({ ...opened, sampleActive: true })).toBe(false);+ // Leaving the sample is only the URL changing -- the browser's Back+ // button restores nothing else -- so the opened file has to come back+ // from state the swap never touched.+ expect(showsOpenedFiles({ ...opened, sampleActive: false })).toBe(true);+ });++ it('shows the base source when no file is open', () => {+ expect(+ showsOpenedFiles({ showFiles: false, fileCount: 1, sampleActive: false })+ ).toBe(false);+ // Nothing opened yet: `showFiles` can be true before a file lands.+ expect(+ showsOpenedFiles({ showFiles: true, fileCount: 0, sampleActive: false })+ ).toBe(false);+ });+});diff --git a/viewer/src/app/sampleMode.tsx b/viewer/src/app/sampleMode.tsxnew file mode 100644index 0000000..eded547--- /dev/null+++ b/viewer/src/app/sampleMode.tsx@@ -0,0 +1,102 @@+import { createContext, useContext, type ReactNode } from 'react';++/**+ * The bundled demo session that opened a PR (`scripts/make-demo.mjs`, first+ * entry). It is the only demo session with a PR in it, so it is the one worth+ * swapping to when someone asks what the review loop looks like.+ *+ * A wrong id here is not fatal: the explorer falls back to the first session+ * in the list, which is this one.+ */+export const SAMPLE_SESSION_ID =+ 'local:claude-code:5f2c9a1e-7b44-4d0e-9c1a-demo00000001';++/**+ * The URL params that decide which sessions the explorer's list can offer:+ * the sessions search box and the time window. Anything else that filters+ * that list belongs here too.+ */+export const LIST_FILTER_PARAMS = ['sq', 'win'] as const;++/** The query "See sample" pushes. Null clears a param. */+export interface SampleQuery {+ demo: string | null;+ sample: string | null;+ session: string | null;+ view: string | null;+ /** the sessions search (`LIST_FILTER_PARAMS`) */+ sq: string | null;+ /** the time window (`LIST_FILTER_PARAMS`) */+ win: string | null;+}++/**+ * Showing the sample swaps the view onto `SAMPLE_SESSION_ID` *and* clears+ * every list filter, because the explorer falls back to the first row of the+ * **filtered** list when the session it is asked for is not in it: a search+ * or a time window that excludes the sample would otherwise leave the reader+ * on some other session with the preview still blurred.+ *+ * It is a pushed history entry, so the browser's own Back button restores the+ * filters the reader had -- which is why they are cleared through the URL+ * rather than as local state.+ */+export const SAMPLE_QUERY: SampleQuery = {+ demo: '1',+ sample: '1',+ session: SAMPLE_SESSION_ID,+ view: null,+ sq: null,+ win: null,+};++/**+ * Whether the viewer renders the files the reader opened rather than its base+ * source. The sample outranks them while it is on, but only bypasses them:+ * "See sample" leaves the opened-file selection alone so that leaving the+ * sample -- including by a Back that restores the URL and nothing else --+ * returns to the file-backed session instead of losing it.+ */+export const showsOpenedFiles = (s: {+ showFiles: boolean;+ fileCount: number;+ sampleActive: boolean;+}): boolean => s.showFiles && s.fileCount > 0 && !s.sampleActive;++export interface SampleMode {+ /** the viewer is showing the bundled sample instead of the user's own */+ active: boolean;+ /** a local server answered, so there is something to go back to */+ canExit: boolean;+ /** swap the list, the map and the panels onto the sample session */+ show: () => void;+ /** back to the user's own sessions */+ exit: () => void;+}++const NO_SAMPLE: SampleMode = {+ active: false,+ canExit: false,+ show: () => {},+ exit: () => {},+};++const SampleModeContext = createContext<SampleMode>(NO_SAMPLE);++/** Lets a panel deep in the explorer swap the whole view onto the sample+ * session without threading four callbacks through every layer between. */+export function SampleModeProvider({+ value,+ children,+}: {+ value: SampleMode;+ children: ReactNode;+}) {+ return (+ <SampleModeContext.Provider value={value}>+ {children}+ </SampleModeContext.Provider>+ );+}++export const useSampleMode = (): SampleMode => useContext(SampleModeContext);diff --git a/viewer/src/app/theme.ts b/viewer/src/app/theme.tsnew file mode 100644index 0000000..aaf7bc8--- /dev/null+++ b/viewer/src/app/theme.ts@@ -0,0 +1,40 @@+import { useCallback, useEffect, useState } from 'react';++type Theme = 'light' | 'dark';++declare global {+ interface Window {+ __agentplayApplyTheme?: () => void;+ }+}++const KEY = 'agentplay.theme';+const current = (): Theme =>+ document.documentElement.classList.contains('dark') ? 'dark' : 'light';++/** The resolved theme plus a toggle that pins the other one. The pin lives+ * in localStorage (a per-viewer convenience; every access is guarded). */+export function useTheme() {+ const [theme, setTheme] = useState<Theme>(current);+ useEffect(() => {+ const obs = new MutationObserver(() => setTheme(current()));+ obs.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });+ return () => obs.disconnect();+ }, []);+ const toggle = useCallback(() => {+ const next: Theme = current() === 'dark' ? 'light' : 'dark';+ try {+ localStorage.setItem(KEY, next);+ } catch {+ // storage blocked: the toggle still applies for this page view+ }+ const url = new URL(window.location.href);+ if (url.searchParams.has('theme')) {+ url.searchParams.delete('theme');+ window.history.replaceState(window.history.state, '', url);+ }+ if (window.__agentplayApplyTheme) window.__agentplayApplyTheme();+ document.documentElement.classList.toggle('dark', next === 'dark');+ }, []);+ return { theme, toggle };+}diff --git a/viewer/src/app/useFileDrop.ts b/viewer/src/app/useFileDrop.tsnew file mode 100644index 0000000..a9615ef--- /dev/null+++ b/viewer/src/app/useFileDrop.ts@@ -0,0 +1,49 @@+import { useEffect, useRef, useState } from 'react';++const isFileDrag = (e: DragEvent) =>+ Array.from(e.dataTransfer?.types ?? []).includes('Files');++/** Page-wide drag-and-drop of files. `dragging` drives the overlay. */+export function useFileDrop(onFiles: (files: File[]) => void) {+ const [dragging, setDragging] = useState(false);+ const depth = useRef(0);+ const cb = useRef(onFiles);+ cb.current = onFiles;+ useEffect(() => {+ const enter = (e: DragEvent) => {+ if (!isFileDrag(e)) return;+ e.preventDefault();+ depth.current++;+ setDragging(true);+ };+ const over = (e: DragEvent) => {+ if (!isFileDrag(e)) return;+ e.preventDefault();+ if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';+ };+ const leave = (e: DragEvent) => {+ if (!isFileDrag(e)) return;+ depth.current = Math.max(0, depth.current - 1);+ if (depth.current === 0) setDragging(false);+ };+ const drop = (e: DragEvent) => {+ if (!isFileDrag(e)) return;+ e.preventDefault();+ depth.current = 0;+ setDragging(false);+ const files = Array.from(e.dataTransfer?.files ?? []);+ if (files.length) cb.current(files);+ };+ window.addEventListener('dragenter', enter);+ window.addEventListener('dragover', over);+ window.addEventListener('dragleave', leave);+ window.addEventListener('drop', drop);+ return () => {+ window.removeEventListener('dragenter', enter);+ window.removeEventListener('dragover', over);+ window.removeEventListener('dragleave', leave);+ window.removeEventListener('drop', drop);+ };+ }, []);+ return dragging;+}diff --git a/viewer/src/assets/GitHubMark.tsx b/viewer/src/assets/GitHubMark.tsxnew file mode 100644index 0000000..b036f12--- /dev/null+++ b/viewer/src/assets/GitHubMark.tsx@@ -0,0 +1,16 @@+export function GitHubMark({ className }: { className?: string }) {+ return (+ <svg+ className={className}+ viewBox="0 0 24 24"+ fill="currentColor"+ aria-hidden+ >+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.17 6.839 9.49.5.092.682-.217.682-.482 0-.237-.008-.866-.013-1.7-2.782.603-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.463-1.11-1.463-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.578 9.578 0 0112 6.836c.85.004 1.705.114 2.504.336 1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.203 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.578.688.48C19.138 20.167 22 16.418 22 12c0-5.523-4.477-10-10-10z"+ />+ </svg>+ );+}diff --git a/viewer/src/components/EmptyState.tsx b/viewer/src/components/EmptyState.tsxnew file mode 100644index 0000000..509a709--- /dev/null+++ b/viewer/src/components/EmptyState.tsx@@ -0,0 +1,85 @@+import { type ReactNode } from 'react';+import { Tray } from '@phosphor-icons/react';++import { cn } from '@/lib/utils';++/**+ * In-card empty state: icon in brand box, title, subtext.+ * Use for "No data", "No patterns yet", "No repositories match", etc.+ */+interface EmptyStateProps {+ /** Main heading (e.g. "No activity in this period") */+ title: string;+ /** Supporting line (e.g. "Try adjusting the date range...") */+ description: string;+ /** Optional icon; default is Tray for generic empty */+ icon?: ReactNode;+ /** Optional CTA (e.g. a Button) rendered under the description */+ action?: ReactNode;+ /**+ * Vertical footprint. `md` (default, ~230px) is the standalone/section form+ * used when the empty state IS the widget body. `sm` (~130px) is for a card+ * sitting in a grid beside siblings that carry data -- e.g.+ * sidebar cards, where the full form would out-tall the real content it+ * replaces. Same anatomy either way, so a row of mixed states still reads as+ * one system.+ */+ size?: 'sm' | 'md';+ /** Layout-only overrides (e.g. a min-height matched to the widget body). */+ className?: string;+}++export function EmptyState({+ title,+ description,+ icon,+ action,+ size = 'md',+ className,+}: EmptyStateProps) {+ const sm = size === 'sm';+ return (+ <div+ className={cn(+ 'flex w-full flex-col items-center justify-center text-center',+ sm ? 'min-h-[130px] gap-3 p-4' : 'min-h-[180px] gap-6 p-6',+ className+ )}+ role="status"+ aria-label={title}+ >+ <div+ className={cn(+ 'flex shrink-0 items-center justify-center rounded-lg border border-ds-brand-subtlest bg-ds-brand-lightest/20',+ sm ? 'size-8' : 'size-10'+ )}+ aria-hidden+ >+ {icon ?? (+ <Tray+ size={sm ? 18 : 24}+ className="text-ds-brand-subtler"+ weight="regular"+ aria-hidden+ />+ )}+ </div>+ <div className="flex w-full flex-col items-center gap-2 text-center">+ <p className="ds-text-body-sm-semibold text-ds-text-default w-full">+ {title}+ </p>+ <p+ className={cn(+ 'ds-text-body-xs-medium text-ds-text-subtle w-full',+ sm ? 'max-w-[320px]' : 'max-w-[280px]'+ )}+ >+ {description}+ </p>+ {action && (+ <div className="mt-2 flex items-center justify-center">{action}</div>+ )}+ </div>+ </div>+ );+}diff --git a/viewer/src/components/ErrorBoundary.tsx b/viewer/src/components/ErrorBoundary.tsxnew file mode 100644index 0000000..bdbeaae--- /dev/null+++ b/viewer/src/components/ErrorBoundary.tsx@@ -0,0 +1,25 @@+import { Component, type ErrorInfo, type ReactNode } from 'react';++/**+ * Catches a render-time throw in `children` and shows `fallback` instead of+ * unmounting the whole app. Give it a `key` that changes with the thing it+ * guards (e.g. the session id) so moving on resets it.+ */+export class ErrorBoundary extends Component<+ { children: ReactNode; fallback: ReactNode },+ { failed: boolean }+> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ componentDidCatch(error: Error, info: ErrorInfo) {+ console.error('render failed', error, info.componentStack);+ }++ render() {+ return this.state.failed ? this.props.fallback : this.props.children;+ }+}diff --git a/viewer/src/components/LockedBlock.tsx b/viewer/src/components/LockedBlock.tsxnew file mode 100644index 0000000..f800d6e--- /dev/null+++ b/viewer/src/components/LockedBlock.tsx@@ -0,0 +1,118 @@+import type { ReactNode } from 'react';+import { ArrowSquareOut } from '@phosphor-icons/react';+import { buttonVariants } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import { connectUrl, type LinkSource } from '@/core/entelligence';++interface Props {+ title: string;+ blurb: string;+ /**+ * The sample rendering behind the glass. Always invented data -- the point+ * of the block is a capability the local map cannot have, so there is+ * nothing real to put here.+ */+ preview: ReactNode;+ ctaLabel: string;+ src: LinkSource;+ /** whether the sample is un-blurred; owned by the caller, because showing+ * it also swaps the session and the map underneath */+ shown: boolean;+ onToggle: () => void;+ /** rendered beside the buttons when the whole view is on the sample */+ exit?: ReactNode;+}++/**+ * A capability the viewer cannot do locally, shown rather than described: a+ * sample behind frosted glass, a sentence saying what it is, and a link out.+ *+ * Deliberately not a gate on anything that works offline. It appears where+ * the local answer is genuinely empty, it never interrupts playback, and+ * "See sample" un-blurs the sample so nobody has to hand over an email to+ * find out what is being offered. The link is the only thing that leaves+ * the page, and only when clicked.+ */+export function LockedBlock({+ title,+ blurb,+ preview,+ ctaLabel,+ src,+ shown,+ onToggle,+ exit,+}: Props) {+ return (+ // A 2px brand keyline, not the hairline every other card wears: this is+ // the one block in the panel offering something, and at a hairline it+ // read as another quiet row rather than a thing to act on.+ <section className="relative mt-3 shrink-0 overflow-hidden rounded-lg border-2 border-ds-brand-subtler bg-ds-surface-white">+ {/* Collapsed, the sample is wallpaper: it fills the card the text+ * below sizes, so the block is never taller than what it has to say,+ * and it is hidden from assistive tech and inert so nobody tabs into+ * a blurred card. Revealed, it joins the flow, takes its own height,+ * and anything interactive in it has to work. */}+ <div+ aria-hidden={shown ? undefined : true}+ className={cn(+ 'p-3 transition-[filter,opacity]',+ shown+ ? 'opacity-100'+ : 'pointer-events-none absolute inset-0 select-none opacity-40 blur-[4px]'+ )}+ >+ {preview}+ </div>+ <div+ className={cn(+ 'relative flex flex-col gap-2 p-3',+ shown+ ? 'border-t border-ds-border-subtlest'+ : // Nearly opaque, not a tint. The sample only has to read as+ // texture; the sentence over it has to be readable, and at+ // /70 the sample's own words showed through the blurb.+ 'bg-ds-surface-white/92 backdrop-blur-[6px]'+ )}+ >+ <div className="flex flex-col gap-0.5">+ <p className="ds-text-body-xs-semibold text-ds-text-default">+ {title}+ </p>+ <p className="ds-text-body-xs-medium text-ds-text-default">{blurb}</p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {/* The link is the primary action and is dressed as one: brand+ * fill, and a soft brand halo so it carries across the panel's+ * quiet greys in both themes. "See sample" stays ghost -- two+ * loud buttons is no emphasis at all. */}+ <a+ href={connectUrl(src)}+ target="_blank"+ rel="noopener noreferrer"+ className={cn(+ buttonVariants({ variant: 'default', size: 'sm' }),+ // The solid brand weight (the `brandSolid` badge's tokens), so+ // the button is a filled colour rather than a tint, and the+ // same colour again as a halo. Holds up on both themes: the+ // fill carries light mode, the halo carries dark.+ 'border-transparent bg-ds-brand-fill font-semibold text-ds-brand-on-fill hover:bg-ds-brand-subtler active:bg-ds-brand-subtler',+ 'shadow-[0_0_0_1px_var(--primitive-brand-green-500),0_3px_16px_-2px_var(--primitive-brand-green-400)] transition-shadow hover:shadow-[0_0_0_1px_var(--primitive-brand-green-400),0_5px_24px_-2px_var(--primitive-brand-green-400)]'+ )}+ >+ {ctaLabel}+ <ArrowSquareOut size={12} aria-hidden />+ </a>+ <button+ type="button"+ onClick={onToggle}+ className={cn(buttonVariants({ variant: 'ghost', size: 'sm' }))}+ >+ {shown ? 'Hide sample' : 'See sample'}+ </button>+ {exit}+ </div>+ </div>+ </section>+ );+}diff --git a/viewer/src/components/dataviz/index.ts b/viewer/src/components/dataviz/index.tsnew file mode 100644index 0000000..6ffb993--- /dev/null+++ b/viewer/src/components/dataviz/index.ts@@ -0,0 +1,12 @@+export {+ SERIES,+ SERIES_OTHER,+ seriesColor,+ PRIMARY,+ PRIMARY_ACCENT,+ SEQUENTIAL,+ INTENSITY,+ DIVERGING,+ STATUS,+ CHROME,+} from './palette';diff --git a/viewer/src/components/dataviz/palette.ts b/viewer/src/components/dataviz/palette.tsnew file mode 100644index 0000000..f40b9db--- /dev/null+++ b/viewer/src/components/dataviz/palette.ts@@ -0,0 +1,86 @@+/**+ * Chart palette — the single source of colour for every chart in the app.+ *+ * Four jobs, four rules:+ * - identity (which series) -> SERIES, in fixed slot order, never cycled+ * - magnitude (how much) -> SEQUENTIAL, one hue, light to dark+ * - polarity (which side) -> DIVERGING, two hues + neutral midpoint+ * - state (good..bad) -> STATUS, reserved meaning, always icon + label+ *+ * Every value is a CSS variable, so light and dark flip without a `dark:`+ * prefix and without JS theme state.+ */++/** Categorical identity slots. Fixed order — assign in sequence, never cycle. */+export const SERIES = [+ 'var(--ds-series-1)',+ 'var(--ds-series-2)',+ 'var(--ds-series-3)',+ 'var(--ds-series-4)',+ 'var(--ds-series-5)',+ 'var(--ds-series-6)',+ 'var(--ds-series-7)',+ 'var(--ds-series-8)',+] as const;++/** Everything past slot 8, and the de-emphasised rest in an emphasis chart. */+export const SERIES_OTHER = 'var(--ds-series-other)';++/**+ * Colour for series `index`. Past slot 8 you get the neutral "other" grey,+ * because a generated 9th hue is indistinguishable under colour blindness.+ * Fold the tail into an explicit "Other" bucket instead of leaning on this.+ */+export function seriesColor(index: number): string {+ return SERIES[index] ?? SERIES_OTHER;+}++/** Single series, and the "one hue + grey" emphasis chart. */+export const PRIMARY = 'var(--ds-brand-subtler)';+/** Active dot ring and other accents that sit on top of PRIMARY. */+export const PRIMARY_ACCENT = 'var(--ds-brand-subtle)';++/** Magnitude ramp, low to high. One hue, monotone lightness. */+export const SEQUENTIAL = [+ 'var(--primitive-brand-green-200)',+ 'var(--primitive-brand-green-300)',+ 'var(--primitive-brand-green-400)',+ 'var(--primitive-brand-green-500)',+ 'var(--primitive-brand-green-600)',+] as const;++/** Intensity ramp with no hue at all (activity heatmap). */+export const INTENSITY = [+ 'var(--ds-heatmap-1)',+ 'var(--ds-heatmap-2)',+ 'var(--ds-heatmap-3)',+ 'var(--ds-heatmap-4)',+ 'var(--ds-heatmap-5)',+] as const;++/** Polarity: two poles and a neutral midpoint. Never a hue in the middle. */+export const DIVERGING = {+ negative: 'var(--ds-danger-default)',+ neutral: 'var(--primitive-gray-300)',+ positive: 'var(--ds-success-default)',+} as const;++/**+ * Reserved state colours. Never reuse one of these as "series 4" — a status+ * colour must only ever mean its state, and always ships with an icon or label.+ */+export const STATUS = {+ good: 'var(--ds-success-default)',+ info: 'var(--ds-blue-default)',+ warning: 'var(--ds-warning-default)',+ critical: 'var(--ds-danger-default)',+} as const;++/** Chart chrome. */+export const CHROME = {+ grid: 'var(--ds-chart-grid)',+ axis: 'var(--ds-chart-axis)',+ cursor: 'var(--ds-chart-cursor)',+ /** Donut / meter track ring. */+ track: 'var(--primitive-gray-100)',+} as const;diff --git a/viewer/src/components/ui/badge.tsx b/viewer/src/components/ui/badge.tsxnew file mode 100644index 0000000..eec39c6--- /dev/null+++ b/viewer/src/components/ui/badge.tsx@@ -0,0 +1,72 @@+import * as React from 'react';+import { cva, type VariantProps } from 'class-variance-authority';++import { cn } from '@/lib/utils';++/**+ * Every fill/ink pair below clears 4.5:1 in BOTH themes, checked by+ * a contrast audit. Five of the nine variants did not+ * when that check was first written: `secondary` 3.86:1, `destructive` 3.61:1,+ * `keyline` 3.95:1, `success` 3.18:1 and `warning` 3.27:1, all in LIGHT mode,+ * all shipped. Every one had been eyeballed and passed, because a 3.2:1 chip+ * looks fine next to a 9:1 one until you compute it.+ *+ * If you add or retune a variant, re-check contrast in both themes.+ */+const badgeVariants = cva(+ 'inline-flex items-center gap-1 rounded-lg border border-transparent px-2 py-0.5 ds-text-body-xs-medium shadow-none transition-colors focus:outline-none focus:ring-2 focus:ring-ds-brand-subtle focus:ring-offset-2',+ {+ variants: {+ variant: {+ // Ink is `subtle`, not `default`: every consumer was already+ // overriding it to `text-ds-brand-subtle`. Still AA on the subtlest+ // fill: 5.4:1 light, 9.0:1 dark.+ default: 'bg-ds-brand-subtlest text-ds-brand-subtle',+ secondary: 'bg-ds-gray-subtlest text-ds-text-default',+ destructive: 'bg-ds-danger-subtlest text-ds-danger-darkest',+ outline: 'border-ds-border-subtlest text-ds-text-default',+ info: 'bg-ds-purple-subtlest text-ds-purple-default',+ // Defines the variant; it does not choose it. Product code wanting a+ // positive metric wants `default` (brand color), not this.+ // Uses `-subtlest` like its siblings, so it never reads as a solid+ // button-like fill in dark mode.+ success: 'bg-ds-success-subtlest text-ds-success-darker',+ warning: 'bg-ds-warning-subtlest text-ds-warning-darker',+ // The two brand weights above a tint, so a surface that needs to rank+ // three states (filled > ringed > tinted > neutral) can do it through+ // the design system instead of a private class map. Weight carries the+ // hierarchy; the hue never changes.+ brandSolid: 'bg-ds-brand-fill text-ds-brand-on-fill',+ // The quiet annotation chip: "12 engineers", "spend-weighted", "Low+ // sample", "approx". Lower emphasis than `secondary`, and bordered so it+ // reads as a qualifier on the number beside it rather than a status of+ // its own. Six files had hand-rolled this exact look before it was a+ // variant.+ keyline:+ 'border-ds-border-subtlest bg-ds-gray-lightest text-ds-text-default',+ brandOutline:+ 'border-ds-brand-subtler bg-ds-brand-subtlest text-ds-brand-subtle',+ // Alias of `destructive`, kept because call sites reach for whichever+ // word fits the sentence ("closed" is an error, "delete" is+ // destructive). Same tokens on purpose -- do not let them drift, and do+ // not add a third.+ error: 'bg-ds-danger-subtlest text-ds-danger-darkest',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ }+);++export interface BadgeProps+ extends React.HTMLAttributes<HTMLDivElement>,+ VariantProps<typeof badgeVariants> {}++function Badge({ className, variant, ...props }: BadgeProps) {+ return (+ <div className={cn(badgeVariants({ variant }), className)} {...props} />+ );+}++export { Badge, badgeVariants };diff --git a/viewer/src/components/ui/button.tsx b/viewer/src/components/ui/button.tsxnew file mode 100644index 0000000..02fb387--- /dev/null+++ b/viewer/src/components/ui/button.tsx@@ -0,0 +1,77 @@+import * as React from 'react';+import { Button as ButtonPrimitive } from '@base-ui/react/button';+import { cva, type VariantProps } from 'class-variance-authority';++import { cn } from '@/lib/utils';++const buttonVariants = cva(+ 'motion-tap inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[10px] text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ds-brand-subtler disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',+ {+ variants: {+ variant: {+ // Primary: brand/default bg, brand/subtler border, brand/subtlest text+ default:+ 'bg-ds-brand-default border-[1.5px] border-ds-brand-subtler text-ds-brand-subtlest hover:bg-ds-brand-subtle active:bg-ds-brand-darker',+ // Danger: danger/darker bg, danger/default border, white text+ destructive:+ 'bg-ds-danger-darker border-[1px] border-ds-danger-default text-ds-surface-white hover:bg-ds-danger-default active:bg-ds-danger-darkest',+ // Destructive outline: quiet danger — transparent bg, danger text + subtle danger border, danger-tint hover. For guarded actions where the loud solid-red belongs on the confirm step.+ destructiveOutline:+ 'bg-transparent border-[1px] border-ds-danger-subtler text-ds-danger-default hover:bg-ds-danger-subtlest hover:border-ds-danger-default',+ // Outline: transparent bg, border/subtlest border, text/default+ outline:+ 'border-[1px] border-ds-border-subtlest bg-transparent text-ds-text-default hover:bg-ds-gray-subtlest',+ // Secondary: surface/white bg, border/subtlest border, text/default+ secondary:+ 'bg-ds-surface-white border-[1px] border-ds-border-subtlest text-ds-text-default hover:bg-ds-gray-subtlest',+ // Ghost: no bg, no border, text/default+ ghost: 'bg-transparent text-ds-text-default hover:bg-ds-gray-subtlest',+ // Link: text/default with underline on hover+ link: 'bg-transparent text-ds-text-default underline-offset-4 hover:underline',+ },+ size: {+ default: 'h-9 px-4 py-2',+ sm: 'h-8 px-3 py-1.5 rounded-md text-xs',+ lg: 'h-11 px-4 py-3',+ icon: 'h-9 w-9',+ // Square icon button matched to `sm`, for icon controls that sit beside+ // a small button (h-9 `icon` next to an h-8 `sm` reads as misaligned).+ iconSm: 'h-8 w-8 rounded-md',+ },+ },+ defaultVariants: {+ variant: 'default',+ size: 'default',+ },+ }+);++export interface ButtonProps+ extends ButtonPrimitive.Props,+ VariantProps<typeof buttonVariants> {}++const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(+ ({ className, variant, size, nativeButton, render, ...props }, ref) => {+ // Base UI's Button defaults `nativeButton` to true and warns when `render`+ // supplies a non-<button> element (links, spans, divs). Disable native button+ // semantics for non-button renders unless the caller set it explicitly.+ const resolvedNativeButton =+ nativeButton ??+ (render != null &&+ !(React.isValidElement(render) && render.type === 'button')+ ? false+ : undefined);+ return (+ <ButtonPrimitive+ className={cn(buttonVariants({ variant, size, className }))}+ ref={ref}+ nativeButton={resolvedNativeButton}+ render={render}+ {...props}+ />+ );+ }+);+Button.displayName = 'Button';++export { Button, buttonVariants };diff --git a/viewer/src/components/ui/command.tsx b/viewer/src/components/ui/command.tsxnew file mode 100644index 0000000..c4a78a8--- /dev/null+++ b/viewer/src/components/ui/command.tsx@@ -0,0 +1,138 @@+import * as React from 'react';+import { Command as CommandPrimitive } from 'cmdk';+import { Search } from 'lucide-react';++import { cn } from '@/lib/utils';++const Command = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive>+>(({ className, ...props }, ref) => (+ <CommandPrimitive+ ref={ref}+ className={cn(+ 'flex h-full w-full flex-col overflow-hidden rounded-md bg-ds-surface-white text-ds-text-default',+ className+ )}+ {...props}+ />+));+Command.displayName = CommandPrimitive.displayName;++const CommandInput = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.Input>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>+>(({ className, ...props }, ref) => (+ <div+ className="flex items-center border-b border-ds-border-subtler px-3"+ data-cmdk-input-wrapper=""+ >+ <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />+ <CommandPrimitive.Input+ ref={ref}+ className={cn(+ 'flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-ds-text-subtle disabled:cursor-not-allowed disabled:opacity-50',+ className+ )}+ {...props}+ />+ </div>+));++CommandInput.displayName = CommandPrimitive.Input.displayName;++const CommandList = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.List>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>+>(({ className, ...props }, ref) => (+ <CommandPrimitive.List+ ref={ref}+ className={cn('max-h-[300px] overflow-y-auto overflow-x-hidden', className)}+ {...props}+ />+));++CommandList.displayName = CommandPrimitive.List.displayName;++const CommandEmpty = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.Empty>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>+>((props, ref) => (+ <CommandPrimitive.Empty+ ref={ref}+ className="py-6 text-center text-sm"+ {...props}+ />+));++CommandEmpty.displayName = CommandPrimitive.Empty.displayName;++const CommandGroup = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.Group>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>+>(({ className, ...props }, ref) => (+ <CommandPrimitive.Group+ ref={ref}+ className={cn(+ 'overflow-hidden p-1 text-ds-text-default [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-ds-text-subtle',+ className+ )}+ {...props}+ />+));++CommandGroup.displayName = CommandPrimitive.Group.displayName;++const CommandSeparator = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.Separator>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>+>(({ className, ...props }, ref) => (+ <CommandPrimitive.Separator+ ref={ref}+ className={cn('-mx-1 h-px bg-border', className)}+ {...props}+ />+));+CommandSeparator.displayName = CommandPrimitive.Separator.displayName;++const CommandItem = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>+>(({ className, ...props }, ref) => (+ <CommandPrimitive.Item+ ref={ref}+ className={cn(+ 'relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-ds-gray-subtlest data-[selected=true]:text-ds-text-default data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',+ className+ )}+ {...props}+ />+));++CommandItem.displayName = CommandPrimitive.Item.displayName;++const CommandShortcut = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLSpanElement>) => {+ return (+ <span+ className={cn(+ 'ml-auto text-xs tracking-widest text-ds-text-subtle',+ className+ )}+ {...props}+ />+ );+};+CommandShortcut.displayName = 'CommandShortcut';++export {+ Command,+ CommandInput,+ CommandList,+ CommandEmpty,+ CommandGroup,+ CommandItem,+ CommandSeparator,+};diff --git a/viewer/src/components/ui/dialog.tsx b/viewer/src/components/ui/dialog.tsxnew file mode 100644index 0000000..241d5c4--- /dev/null+++ b/viewer/src/components/ui/dialog.tsx@@ -0,0 +1,41 @@+import * as React from 'react';+import { Dialog as DialogPrimitive } from '@base-ui/react/dialog';++import { cn } from '@/lib/utils';++const Dialog = DialogPrimitive.Root;++const DialogTrigger = DialogPrimitive.Trigger;++const DialogClose = DialogPrimitive.Close;++const DialogTitle = DialogPrimitive.Title;++const DialogDescription = DialogPrimitive.Description;++const DialogContent = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Popup>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Popup>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Portal>+ <DialogPrimitive.Backdrop className="fixed inset-0 z-[1000] bg-ds-gray-darkest/40 transition-opacity data-ending-style:opacity-0 data-starting-style:opacity-0" />+ <DialogPrimitive.Popup+ ref={ref}+ className={cn(+ 'fixed left-1/2 top-1/2 z-[1001] flex max-h-[min(40rem,calc(100vh-3rem))] w-[min(30rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col gap-3 overflow-y-auto rounded-xl border border-ds-border-subtler bg-ds-surface-white p-4 text-ds-text-default shadow-lg outline-none transition-[opacity,transform] data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',+ className+ )}+ {...props}+ />+ </DialogPrimitive.Portal>+));+DialogContent.displayName = DialogPrimitive.Popup.displayName;++export {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+ DialogTrigger,+};diff --git a/viewer/src/components/ui/input.tsx b/viewer/src/components/ui/input.tsxnew file mode 100644index 0000000..9b55289--- /dev/null+++ b/viewer/src/components/ui/input.tsx@@ -0,0 +1,22 @@+import * as React from 'react';++import { cn } from '@/lib/utils';++const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(+ ({ className, type, ...props }, ref) => {+ return (+ <input+ type={type}+ className={cn(+ 'flex h-9 w-full rounded-md border border-ds-border-subtlest bg-ds-surface-white px-3 py-1 text-base text-ds-text-darker shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-ds-text-default placeholder:text-ds-text-subtle focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ds-brand-subtler focus-visible:ring-offset-1 focus-visible:ring-offset-ds-surface-white disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',+ className+ )}+ ref={ref}+ {...props}+ />+ );+ }+);+Input.displayName = 'Input';++export { Input };diff --git a/viewer/src/components/ui/popover.tsx b/viewer/src/components/ui/popover.tsxnew file mode 100644index 0000000..64404a6--- /dev/null+++ b/viewer/src/components/ui/popover.tsx@@ -0,0 +1,53 @@+import * as React from 'react';+import { Popover as PopoverPrimitive } from '@base-ui/react/popover';++import { cn } from '@/lib/utils';++const Popover = PopoverPrimitive.Root;++const PopoverTrigger = PopoverPrimitive.Trigger;++const PopoverClose = PopoverPrimitive.Close;++const PopoverContent = React.forwardRef<+ React.ElementRef<typeof PopoverPrimitive.Popup>,+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Popup> &+ Pick<+ PopoverPrimitive.Positioner.Props,+ 'align' | 'alignOffset' | 'side' | 'sideOffset'+ >+>(+ (+ {+ className,+ align = 'center',+ alignOffset,+ side,+ sideOffset = 4,+ ...props+ },+ ref+ ) => (+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Positioner+ className="isolate z-[1000]"+ align={align}+ alignOffset={alignOffset}+ side={side}+ sideOffset={sideOffset}+ >+ <PopoverPrimitive.Popup+ ref={ref}+ className={cn(+ 'z-50 w-96 rounded-md border border-ds-border-subtler bg-ds-surface-white p-4 text-ds-text-default shadow-md outline-none transition-[opacity,transform] data-starting-style:opacity-0 data-ending-style:opacity-0 data-starting-style:scale-95 data-ending-style:scale-95 data-[side=bottom]:data-starting-style:-translate-y-2 data-[side=left]:data-starting-style:translate-x-2 data-[side=right]:data-starting-style:-translate-x-2 data-[side=top]:data-starting-style:translate-y-2',+ className+ )}+ {...props}+ />+ </PopoverPrimitive.Positioner>+ </PopoverPrimitive.Portal>+ )+);+PopoverContent.displayName = PopoverPrimitive.Popup.displayName;++export { Popover, PopoverTrigger, PopoverClose, PopoverContent };diff --git a/viewer/src/components/ui/select.tsx b/viewer/src/components/ui/select.tsxnew file mode 100644index 0000000..4287e6b--- /dev/null+++ b/viewer/src/components/ui/select.tsx@@ -0,0 +1,179 @@+import * as React from 'react';+import { Select as SelectPrimitive } from '@base-ui/react/select';+import { Check, ChevronDown, ChevronUp } from 'lucide-react';++import { cn } from '@/lib/utils';++const Select = SelectPrimitive.Root;++const SelectGroup = SelectPrimitive.Group;++const SelectValue = SelectPrimitive.Value;++const SelectTrigger = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Trigger>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>+>(({ className, children, ...props }, ref) => (+ <SelectPrimitive.Trigger+ ref={ref}+ className={cn(+ 'flex h-9 w-full items-center justify-between whitespace-nowrap overflow-hidden rounded-lg border border-ds-border-subtlest bg-ds-surface-white px-3 py-2 text-sm text-ds-text-default data-[placeholder]:text-ds-text-subtle shadow-sm focus:outline-none focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 [&>span]:truncate',+ className+ )}+ {...props}+ >+ {children}+ <SelectPrimitive.Icon+ render={<ChevronDown className="h-4 w-4 text-ds-text-subtle" />}+ />+ </SelectPrimitive.Trigger>+));+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;++const SelectScrollUpButton = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.ScrollUpArrow>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpArrow>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.ScrollUpArrow+ ref={ref}+ className={cn(+ 'top-0 w-full flex cursor-default items-center justify-center py-1',+ className+ )}+ {...props}+ >+ <ChevronUp className="h-4 w-4" />+ </SelectPrimitive.ScrollUpArrow>+));+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpArrow.displayName;++const SelectScrollDownButton = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.ScrollDownArrow>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownArrow>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.ScrollDownArrow+ ref={ref}+ className={cn(+ 'bottom-0 w-full flex cursor-default items-center justify-center py-1',+ className+ )}+ {...props}+ >+ <ChevronDown className="h-4 w-4" />+ </SelectPrimitive.ScrollDownArrow>+));+SelectScrollDownButton.displayName =+ SelectPrimitive.ScrollDownArrow.displayName;++const SelectContent = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Popup>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Popup> &+ Pick<+ SelectPrimitive.Positioner.Props,+ 'alignItemWithTrigger' | 'sideOffset' | 'align' | 'alignOffset' | 'side'+ > & {+ container?: HTMLElement | null;+ }+>(+ (+ {+ className,+ children,+ container,+ alignItemWithTrigger = false,+ sideOffset = 4,+ align,+ alignOffset,+ side,+ ...props+ },+ ref+ ) => (+ <SelectPrimitive.Portal container={container ?? undefined}>+ <SelectPrimitive.Positioner+ className="isolate z-[1000]"+ alignItemWithTrigger={alignItemWithTrigger}+ sideOffset={sideOffset}+ align={align}+ alignOffset={alignOffset}+ side={side}+ >+ <SelectPrimitive.Popup+ ref={ref}+ className={cn(+ 'relative isolate z-50 max-h-[var(--available-height,20rem)] w-[var(--anchor-width)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border border-ds-border-subtlest bg-ds-surface-white p-1 text-ds-text-default shadow-md origin-[var(--transform-origin)] transition-[opacity,transform] data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:scale-95 data-[side=bottom]:data-[starting-style]:-translate-y-2 data-[side=top]:data-[starting-style]:translate-y-2 data-[side=left]:data-[starting-style]:translate-x-2 data-[side=right]:data-[starting-style]:-translate-x-2',+ className+ )}+ {...props}+ >+ <SelectScrollUpButton />+ <SelectPrimitive.List>{children}</SelectPrimitive.List>+ <SelectScrollDownButton />+ </SelectPrimitive.Popup>+ </SelectPrimitive.Positioner>+ </SelectPrimitive.Portal>+ )+);+SelectContent.displayName = SelectPrimitive.Popup.displayName;++const SelectLabel = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.GroupLabel>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.GroupLabel>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.GroupLabel+ ref={ref}+ className={cn(+ 'px-2 py-1.5 text-sm font-semibold text-ds-text-default',+ className+ )}+ {...props}+ />+));+SelectLabel.displayName = SelectPrimitive.GroupLabel.displayName;++const SelectItem = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>+>(({ className, children, ...props }, ref) => (+ <SelectPrimitive.Item+ ref={ref}+ className={cn(+ 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none text-ds-text-default data-[highlighted]:bg-ds-gray-subtlest data-[highlighted]:text-ds-text-default data-[disabled]:pointer-events-none data-[disabled]:opacity-50',+ className+ )}+ {...props}+ >+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>+ <SelectPrimitive.ItemIndicator+ render={+ <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center" />+ }+ >+ <Check className="h-4 w-4 text-ds-brand-subtle" />+ </SelectPrimitive.ItemIndicator>+ </SelectPrimitive.Item>+));+SelectItem.displayName = SelectPrimitive.Item.displayName;++const SelectSeparator = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Separator>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.Separator+ ref={ref}+ className={cn('-mx-1 my-1 h-px bg-border', className)}+ {...props}+ />+));+SelectSeparator.displayName = SelectPrimitive.Separator.displayName;++export {+ Select,+ SelectGroup,+ SelectValue,+ SelectTrigger,+ SelectContent,+ SelectLabel,+ SelectItem,+ SelectSeparator,+};diff --git a/viewer/src/components/ui/skeleton.tsx b/viewer/src/components/ui/skeleton.tsxnew file mode 100644index 0000000..eb9ee05--- /dev/null+++ b/viewer/src/components/ui/skeleton.tsx@@ -0,0 +1,27 @@+import type React from 'react';+import { cn } from '@/lib/utils';++interface SkeletonProps extends React.HTMLAttributes<HTMLDivElement> {+ shimmer?: boolean;+}++export function Skeleton({+ className,+ shimmer = true,+ ...props+}: SkeletonProps) {+ return (+ <div+ className={cn(+ 'rounded-md bg-muted',+ // Travelling sheen rather than an opacity pulse: a pulse reads as+ // "something is blinking", a sheen reads as "data is arriving". Shared+ // with the widget placeholders (index.css `widget-skeleton-*`) so+ // every loading surface in the product moves the same way.+ shimmer && 'widget-skeleton-sheen',+ className+ )}+ {...props}+ />+ );+}diff --git a/viewer/src/components/ui/toggle-group.tsx b/viewer/src/components/ui/toggle-group.tsxnew file mode 100644index 0000000..b6d4926--- /dev/null+++ b/viewer/src/components/ui/toggle-group.tsx@@ -0,0 +1,39 @@+import * as React from 'react';+import { ToggleGroup as ToggleGroupPrimitive } from '@base-ui/react/toggle-group';+import { Toggle as TogglePrimitive } from '@base-ui/react/toggle';++import { cn } from '@/lib/utils';++const ToggleGroup = React.forwardRef<+ HTMLDivElement,+ React.ComponentProps<typeof ToggleGroupPrimitive>+>(({ className, ...props }, ref) => (+ <ToggleGroupPrimitive+ ref={ref}+ className={cn(+ 'inline-flex items-center gap-1 rounded-md border border-ds-border-subtlest bg-ds-surface-white p-0.5',+ className+ )}+ {...props}+ />+));+ToggleGroup.displayName = 'ToggleGroup';++const ToggleGroupItem = React.forwardRef<+ HTMLButtonElement,+ React.ComponentProps<typeof TogglePrimitive>+>(({ className, children, ...props }, ref) => (+ <TogglePrimitive+ ref={ref}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded px-3 py-1 ds-text-body-xs-medium text-ds-text-subtle transition-colors hover:text-ds-text-darker data-[pressed]:bg-ds-gray-subtlest data-[pressed]:text-ds-text-darker',+ className+ )}+ {...props}+ >+ {children}+ </TogglePrimitive>+));+ToggleGroupItem.displayName = 'ToggleGroupItem';++export { ToggleGroup, ToggleGroupItem };diff --git a/viewer/src/core/entelligence.test.ts b/viewer/src/core/entelligence.test.tsnew file mode 100644index 0000000..88f9405--- /dev/null+++ b/viewer/src/core/entelligence.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest';+import {+ researchUrl,+ ENTELLIGENCE_HOME,+ prLabel,+ reviewLoopCopy,+ connectUrl,+} from './entelligence';+import type { SessionMapPr } from './schema';++const pr = (over: Partial<SessionMapPr> = {}): SessionMapPr =>+ ({+ number: 133,+ url: 'https://github.com/owner/repo/pull/133',+ seq: 1046,+ state: 'open',+ repo: 'owner/repo',+ provider: 'github',+ ...over,+ }) as SessionMapPr;++describe('connectUrl', () => {+ it('points at the public site and nowhere else', () => {+ expect(connectUrl('outcomes')).toBe(+ 'https://entelligence.ai/?src=agentplay-viewer&from=outcomes'+ );+ expect(connectUrl('pr-menu').startsWith(ENTELLIGENCE_HOME)).toBe(true);+ });++ it('carries nothing but the source tag', () => {+ const q = new URL(connectUrl('outcomes')).searchParams;+ expect([...q.keys()].sort()).toEqual(['from', 'src']);+ });+});++describe('prLabel', () => {+ it('uses the repo when the map recorded one', () => {+ expect(prLabel(pr())).toBe('owner/repo #133');+ });++ it('falls back to the bare number', () => {+ expect(prLabel(pr({ repo: null }))).toBe('#133');+ });+});++describe('reviewLoopCopy', () => {+ it('names the PR and the step it was opened at', () => {+ const copy = reviewLoopCopy([pr()]);+ expect(copy.blurb).toContain('owner/repo #133');+ expect(copy.blurb).toContain('step 1046');+ expect(copy.pr?.number).toBe(133);+ });++ it('takes the first PR when a session opened several', () => {+ expect(reviewLoopCopy([pr(), pr({ number: 134 })]).pr?.number).toBe(133);+ });++ it('falls back to the generic line with no PR', () => {+ const copy = reviewLoopCopy([]);+ expect(copy.pr).toBeNull();+ expect(copy.blurb).not.toContain('step');+ });++ it('never puts session data in the link', () => {+ expect(connectUrl('outcomes')).not.toContain('owner/repo');+ });+});++describe('researchUrl', () => {+ it('points at the write-up and says only which surface opened it', () => {+ expect(researchUrl('welcome')).toBe(+ 'https://entelligence.ai/research/self-improving-coding-agents?src=agentplay-viewer&from=welcome'+ );+ });+});diff --git a/viewer/src/core/entelligence.ts b/viewer/src/core/entelligence.tsnew file mode 100644index 0000000..747f513--- /dev/null+++ b/viewer/src/core/entelligence.ts@@ -0,0 +1,78 @@+/**+ * The one file in the viewer that knows an Entelligence URL.+ *+ * The README promises the viewer "loads no remote fonts or scripts" and that+ * the package makes no network calls except the optional email signup and+ * disconnect. Both stay true here: nothing in this file fetches anything. It+ * builds a string for an `<a href>` the user has to click, and `grep -rn "entelligence.ai" src/` returns this file and its test,+ * so the claim stays checkable in under a minute.+ *+ * Nothing from the session goes into a link. The source tag is a constant per+ * call site -- no repo name, no path, no identifier.+ */++import type { SessionMapPr } from './schema';++export const ENTELLIGENCE_HOME = 'https://entelligence.ai/';++/** The research write-up the welcome card links to: why agentplay exists. */+export const SELF_IMPROVING_AGENTS = `${ENTELLIGENCE_HOME}research/self-improving-coding-agents`;++/** The surface a locked block was clicked from. A fixed vocabulary, so a+ * reviewer can see the whole set of things a link can say about the user. */+export type LinkSource =+ | 'outcomes'+ | 'pr-menu'+ | 'review-tab'+ | 'fix-dialog'+ | 'welcome'+ | 'banner';++/** Where a locked block's call to action points: the public site's home+ * page. There is no waitlist to send anyone to yet, so every call to action+ * lands in the same place and says the same thing. */+export function connectUrl(src: LinkSource): string {+ return `${ENTELLIGENCE_HOME}?src=agentplay-viewer&from=${src}`;+}++/** The write-up, tagged with the surface it was opened from. */+export function researchUrl(src: LinkSource): string {+ return `${SELF_IMPROVING_AGENTS}?src=agentplay-viewer&from=${src}`;+}++export interface ReviewLoopCopy {+ title: string;+ blurb: string;+ /** The PR the blurb names, for the row under the call to action. */+ pr: SessionMapPr | null;+}++/** "#133" on its own, or "owner/repo #133" when the map recorded the repo. */+export const prLabel = (pr: SessionMapPr): string =>+ pr.repo ? `${pr.repo} #${pr.number}` : `#${pr.number}`;++/**+ * What the outcomes block says. With a PR in the map it names that PR and the+ * step it was opened at, because the map already carries both -- few sessions+ * open one, and the specific sentence is the whole reason to show this rather+ * than a standing banner.+ *+ * The first PR wins. A session that opens several is rarer still, and naming+ * one is better than a list nobody reads.+ */+export function reviewLoopCopy(prs: readonly SessionMapPr[]): ReviewLoopCopy {+ const pr = prs[0] ?? null;+ if (!pr) {+ return {+ title: 'Review comments, traced to the edit behind them',+ blurb:+ 'When a session opens a pull request, Entelligence links each review comment back to the edit that caused it, and clusters the repeats into a rule your agent gets next time.',+ pr: null,+ };+ }+ return {+ title: 'Review comments on this PR',+ blurb: `This session opened ${prLabel(pr)} at step ${pr.seq}. Entelligence traces each review comment on it back to the edit that caused it.`,+ pr,+ };+}diff --git a/viewer/src/core/eventColors.ts b/viewer/src/core/eventColors.tsnew file mode 100644index 0000000..bdafe93--- /dev/null+++ b/viewer/src/core/eventColors.ts@@ -0,0 +1,193 @@+/**+ * Event-kind colours for the Session Explorer, all from the dataviz palette.+ * Kinds are identity, so they take SERIES slots in a fixed order; the two low-salience kinds (generic tool, web) fold into+ * SERIES_OTHER rather than a generated 9th hue. Errors and compaction are+ * state, so they wear STATUS. The LLM cost row is a single series: PRIMARY.+ *+ * Every value is a `var(--…)` string: SVG uses it directly, Canvas resolves it+ * through `resolveCssColor` so light and dark both follow the theme.+ */+import {+ CHROME,+ PRIMARY,+ PRIMARY_ACCENT,+ SERIES,+ SERIES_OTHER,+ STATUS,+} from '@/components/dataviz';+import type { SessionMapEvent } from './schema';+import {+ ERROR_SOURCE_LABEL,+ type ErrorSource,+ type NodeType,+ type ToolCategory,+ type TouchLevel,+} from './sessionMapModel';+import type { Category } from './sessionLayout';++export interface KindMeta {+ label: string;+ color: string;+}++export const KIND_META: Record<string, KindMeta> = {+ verify: { label: 'Verify', color: SERIES[0] },+ read: { label: 'Read', color: SERIES[1] },+ mcp: { label: 'MCP', color: SERIES[2] },+ exec: { label: 'Exec', color: SERIES[3] },+ edit: { label: 'Edit', color: SERIES[4] },+ search: { label: 'Search', color: SERIES[5] },+ subagent: { label: 'Subagent', color: SERIES[6] },+ skill: { label: 'Skill', color: SERIES[7] },+ web: { label: 'Web', color: SERIES_OTHER },+ tool: { label: 'Tool', color: SERIES_OTHER },+ llm: { label: 'LLM request', color: PRIMARY },+ user: { label: 'User turn', color: 'var(--ds-text-subtle)' },+ compaction: { label: 'Compaction', color: STATUS.critical },+ error: { label: 'Error signal', color: STATUS.critical },+ delay: { label: 'Delay', color: STATUS.warning },+ // Outputs + model switches: no new hues, each reuses the+ // identity colour of the kind it is closest to.+ commit: { label: 'Commit', color: SERIES[0] },+ pr_create: { label: 'PR opened', color: PRIMARY_ACCENT },+ pr_merge: { label: 'PR merged', color: PRIMARY_ACCENT },+ pr_close: { label: 'PR closed', color: 'var(--ds-text-subtle)' },+ pr_comment: { label: 'PR comment', color: SERIES_OTHER },+ ticket: { label: 'Ticket', color: SERIES[2] },+ artifact: { label: 'Artifact', color: SERIES[5] },+ skill_write: { label: 'Skill written', color: SERIES[7] },+ model_switch: { label: 'Model switch', color: PRIMARY },+};++export const kindMeta = (kind: string): KindMeta =>+ KIND_META[kind] ?? KIND_META.tool;++/** `events[].cat` colour for the tool-category breakdown: reuses the+ * KIND_META colour of the closest-matching kind rather than a new hue.+ * `test` and `build` share `verify`'s colour, matching their shared label. */+export const CAT_COLOR: Record<ToolCategory, string> = {+ file: KIND_META.read.color,+ shell: KIND_META.exec.color,+ vcs: KIND_META.mcp.color,+ test: KIND_META.verify.color,+ build: KIND_META.verify.color,+ cloud: KIND_META.subagent.color,+ http: KIND_META.web.color,+ fs: SERIES_OTHER,+ package: KIND_META.skill.color,+ mcp: KIND_META.mcp.color,+ subagent: KIND_META.subagent.color,+ skill: KIND_META.skill.color,+ web: KIND_META.web.color,+ tool: SERIES_OTHER,+};+export const catColor = (cat: string): string =>+ CAT_COLOR[cat as ToolCategory] ?? SERIES_OTHER;++/** Map colour by touch level: seen / read / edited. */+export const TOUCH_COLOR: Record<TouchLevel, string> = {+ 1: KIND_META.search.color,+ 2: KIND_META.read.color,+ 3: KIND_META.edit.color,+};++export const NODE_COLOR: Partial<Record<NodeType, string>> = {+ repo: 'var(--ds-text-default)',+ group: 'var(--ds-text-subtle)',+ dir: 'var(--ds-text-subtle)',+ place: SERIES_OTHER,+ server: KIND_META.mcp.color,+ mcptool: KIND_META.mcp.color,+ skill: KIND_META.skill.color,+ agent: KIND_META.subagent.color,+ web: KIND_META.web.color,+ model: PRIMARY,+ outgroup: 'var(--ds-text-subtle)',+ output: SERIES[0],+};++export const nodeColor = (n: {+ type: NodeType;+ src?: ErrorSource;+ kind?: string;+}): string =>+ (n.type === 'errsrc' || n.type === 'errclass') && n.src+ ? ERROR_SOURCE_COLOR[n.src]+ : n.type === 'output' && n.kind+ ? kindMeta(n.kind).color+ : (NODE_COLOR[n.type] ?? 'var(--ds-border-subtler)');++export const ERROR_COLOR = STATUS.critical;++/** Error sources are state first (tool failures critical, LLM/API trouble+ * warning); MCP, hook and orchestration keep the identity of the thing that+ * failed so the error lane reads against the map. */+export const ERROR_SOURCE_COLOR: Record<ErrorSource, string> = {+ tool: STATUS.critical,+ mcp: KIND_META.mcp.color,+ llm: STATUS.warning,+ hook: KIND_META.skill.color,+ orchestration: KIND_META.subagent.color,+};++/** Kind style for an event: an `error` event takes its source's colour. */+export function kindStyle(e: SessionMapEvent): KindMeta {+ if (e.kind === 'error') {+ const src = (Object.keys(ERROR_SOURCE_COLOR) as ErrorSource[]).find(+ (k) => k === e.source+ );+ const s: ErrorSource = src ?? 'tool';+ return {+ label: `Error · ${ERROR_SOURCE_LABEL[s]}`,+ color: ERROR_SOURCE_COLOR[s],+ };+ }+ return kindMeta(e.kind);+}++/** Main-agent context line on the timeline. */+export const CONTEXT_COLOR = KIND_META.read.color;+/** Prompt marks on the timeline: lime (light #65a30d, dark #a3e635). */+export const PROMPT_COLOR = 'var(--ds-session-prompt)';+/** Swatch of each dock category (chips, Events bar, events list). No new+ * hues: problems wear STATUS, activity reuses the kind it names; model+ * requests and their tokens are PRIMARY, cost PRIMARY_ACCENT (SERIES[5]+ * stays the map's "seen" file colour). */+export const CATEGORY_COLOR: Record<Category, string> = {+ prompt: PROMPT_COLOR,+ error: STATUS.critical,+ delay: STATUS.warning,+ out: SERIES[0],+ edit: KIND_META.edit.color,+ explore: KIND_META.read.color,+ mcp: KIND_META.mcp.color,+ skill: KIND_META.skill.color,+ tool: KIND_META.exec.color,+ model: KIND_META.llm.color,+ cost: PRIMARY_ACCENT,+ tokens: PRIMARY,+};+export const TRAIL_COLOR = PRIMARY_ACCENT;+/** Single-series meter fill (agents cost share). */+export const PANEL_BAR_COLOR = PRIMARY;+export const GRID_COLOR = CHROME.grid;+export const AXIS_COLOR = CHROME.axis;++/** Faint fill for nodes touched before the active window. */+export const FAINT_FILL = 'var(--ds-gray-subtler)';+/** Untouched (hollow) node fill + ring. */+export const HOLLOW_FILL = 'var(--ds-surface-white)';+export const HOLLOW_RING = 'var(--ds-border-subtler)';++/**+ * Resolve `var(--x)` (or a bare `--x`) to the computed colour on `el`, so a+ * Canvas can paint with the current theme. Falls back to the input for a+ * literal colour.+ */+export function resolveCssColor(el: Element, value: string): string {+ const m = /^var\((--[^),\s]+)/.exec(value.trim());+ const name = m ? m[1] : value.startsWith('--') ? value : null;+ if (!name) return value;+ const v = getComputedStyle(el).getPropertyValue(name).trim();+ return v || 'currentColor';+}diff --git a/viewer/src/core/mapGeometry.test.ts b/viewer/src/core/mapGeometry.test.tsnew file mode 100644index 0000000..dcd1b17--- /dev/null+++ b/viewer/src/core/mapGeometry.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from 'vitest';+import {+ LABEL_MAX_CHARS,+ MAP_RADIUS,+ PAD_X,+ PAD_Y_MAX,+ PAD_Y_MIN,+ labelChars,+ labelExtentY,+ mapPadY,+ mapViewBox,+ truncateLabel,+ type LabelSpot,+} from './mapGeometry';++const R = MAP_RADIUS;+/** A leaf label spot at angle `a` (radians from +x, y down). */+const leaf = (a: number, len: number): LabelSpot => ({+ r0: R + 8,+ a,+ font: 13.5,+ len,+});+const TOP = -Math.PI / 2;++describe('map geometry', () => {+ it('is a plain circle: the viewBox is R + padding on each side', () => {+ expect(mapViewBox(60)).toBe(+ `${-R - PAD_X} ${-R - 60} ${2 * (R + PAD_X)} ${2 * (R + 60)}`+ );+ });++ it('never lets a label run past the viewBox horizontally, at any angle', () => {+ // Largest leaf font; the SVG clips at its own box, so side labels need+ // the same guarantee as the top / bottom ones.+ for (let k = 0; k < 72; k++) {+ const a = (k / 72) * 2 * Math.PI;+ const s: LabelSpot = { r0: R + 8, a, font: 14, len: 60 };+ const n = labelChars(s, PAD_Y_MAX);+ const xEnd =+ (s.r0 + n * s.font * 0.62) * Math.abs(Math.cos(a)) ++ (s.font / 2) * Math.abs(Math.sin(a));+ expect(xEnd).toBeLessThanOrEqual(R + PAD_X + 1e-9);+ }+ // ...and PAD_X is wide enough that a straight side label keeps its full length.+ expect(labelChars({ r0: R + 8, a: 0, font: 14, len: 60 }, PAD_Y_MAX)).toBe(+ LABEL_MAX_CHARS+ );+ });++ it('pads only as much as the top / bottom labels need, within bounds', () => {+ // side labels need no vertical room at all+ expect(mapPadY([leaf(0, 24), leaf(Math.PI, 24)])).toBe(PAD_Y_MIN);+ // a short label straight up needs a little+ const short = mapPadY([leaf(TOP, 4)]);+ expect(short).toBeGreaterThan(PAD_Y_MIN);+ expect(short).toBeLessThan(PAD_Y_MAX);+ // a long one is capped (it gets shortened instead)+ expect(mapPadY([leaf(TOP, 24)])).toBe(PAD_Y_MAX);+ expect(mapPadY([])).toBe(PAD_Y_MIN);+ });++ it('never lets a shown label run past the viewBox edge', () => {+ for (const len of [3, 12, 24, 60]) {+ const spots = Array.from({ length: 72 }, (_, k) =>+ leaf((k / 72) * 2 * Math.PI, len)+ );+ const padY = mapPadY(spots);+ for (const s of spots) {+ const n = Math.min(s.len, labelChars(s, padY));+ expect(labelExtentY(s, n)).toBeLessThanOrEqual(R + padY + 1e-9);+ }+ }+ });++ it('keeps full labels on the sides and shortens only near the top', () => {+ expect(labelChars(leaf(0, 40), PAD_Y_MAX)).toBe(LABEL_MAX_CHARS);+ expect(labelChars(leaf(Math.PI / 5, 40), PAD_Y_MAX)).toBe(LABEL_MAX_CHARS);+ const top = labelChars(leaf(TOP, 40), PAD_Y_MAX);+ expect(top).toBeGreaterThanOrEqual(3);+ expect(top).toBeLessThan(LABEL_MAX_CHARS);+ });++ it('truncates with an ellipsis within the budget', () => {+ expect(truncateLabel('proxy.ts', 24)).toBe('proxy.ts');+ expect(truncateLabel('SessionMapSvg.tsx', 8)).toBe('Session…');+ expect(truncateLabel('SessionMapSvg.tsx', 8)).toHaveLength(8);+ });+});diff --git a/viewer/src/core/mapGeometry.ts b/viewer/src/core/mapGeometry.tsnew file mode 100644index 0000000..2337b0d--- /dev/null+++ b/viewer/src/core/mapGeometry.ts@@ -0,0 +1,91 @@+/**+ * Radial map geometry: a plain circle (leaves on the ring R), a viewBox+ * whose vertical padding is only as tall as the labels need, and per-label+ * truncation so a label near the top or bottom never runs past it. Pure;+ * tested in `mapGeometry.test.ts`.+ *+ * Why the vertical padding matters: the map's pane is wider than tall, so+ * the SVG scales to fit its height (`xMidYMid meet`). Horizontal room is+ * cheap (PAD_X is sized so a full-length side label fits), but anything above or+ * below the viewBox is clipped -- and every point of vertical padding is+ * circle radius lost. Labels are rotated along their spokes, so a label at+ * angle `a` rises `len * |sin a|`; only labels near the top and bottom need+ * the padding, and those are shortened to fit it.+ */++export const MAP_RADIUS = 250;+/** Horizontal room for the leaf labels on the left / right: enough for a+ * full LABEL_MAX_CHARS label at the largest leaf font (14px) starting just+ * outside the ring, so side labels are never cut by the SVG's own box. The+ * pane is landscape and the map height-bound, so this extra width does not+ * shrink the circle. That holds while the pane is at least ~1.55x as wide as+ * tall (the typical desktop layout); a narrower pane scales to its width and+ * gives up some radius -- a deliberate trade for side labels that are never+ * clipped. */+export const PAD_X = 220;+/** Vertical padding bounds: the floor covers the pulse ring and ×N badges+ * around a leaf at the very top; the cap is what the circle gives up at+ * most (labels longer than that near the top are shortened). */+export const PAD_Y_MIN = 24;+export const PAD_Y_MAX = 80;+/** Longest label, in characters (the rest is in the tooltip). */+export const LABEL_MAX_CHARS = 24;+/** Monospace advance, in em (a conservative upper bound). */+const CHAR_EM = 0.62;+/** Clearance kept between a label's end and the viewBox edge (text halo). */+const EDGE = 3;++/** Where one rotated label sits: it starts at radius `r0` on angle `a`, in a+ * `font`-px monospace, and is `len` characters long untruncated. */+export interface LabelSpot {+ r0: number;+ a: number;+ font: number;+ len: number;+}++/** How far (|y|) a label of `chars` characters reaches from the centre. */+export function labelExtentY(s: LabelSpot, chars: number): number {+ const along = s.r0 + chars * s.font * CHAR_EM;+ return (+ along * Math.abs(Math.sin(s.a)) ++ (s.font / 2) * Math.abs(Math.cos(s.a)) ++ EDGE+ );+}++/** The vertical padding the labels need, clamped to [PAD_Y_MIN, PAD_Y_MAX]. */+export function mapPadY(spots: readonly LabelSpot[], R = MAP_RADIUS): number {+ let need = PAD_Y_MIN;+ for (const s of spots)+ need = Math.max(+ need,+ labelExtentY(s, Math.min(s.len, LABEL_MAX_CHARS)) - R+ );+ return Math.ceil(Math.min(PAD_Y_MAX, need));+}++/** The most characters a label may show and still end inside the viewBox,+ * both vertically (R + padY) and horizontally (R + PAD_X) -- the SVG clips+ * at its own box, so a side label is not free to run past the viewBox+ * either (at least 3, at most LABEL_MAX_CHARS). */+export function labelChars(s: LabelSpot, padY: number, R = MAP_RADIUS): number {+ const sin = Math.abs(Math.sin(s.a));+ const cos = Math.abs(Math.cos(s.a));+ let room = Infinity;+ if (sin > 1e-6)+ room = Math.min(room, (R + padY - EDGE - (s.font / 2) * cos) / sin - s.r0);+ if (cos > 1e-6)+ room = Math.min(room, (R + PAD_X - EDGE - (s.font / 2) * sin) / cos - s.r0);+ if (!Number.isFinite(room)) return LABEL_MAX_CHARS;+ const n = Math.floor(room / (s.font * CHAR_EM));+ return Math.max(3, Math.min(LABEL_MAX_CHARS, n));+}++/** The SVG viewBox of a circle of radius R with the given vertical padding. */+export const mapViewBox = (padY: number, R = MAP_RADIUS): string =>+ `${-R - PAD_X} ${-R - padY} ${2 * (R + PAD_X)} ${2 * (R + padY)}`;++/** `s` cut to at most `n` characters, the last one an ellipsis. */+export const truncateLabel = (s: string, n: number): string =>+ s.length > n ? `${s.slice(0, Math.max(1, n - 1))}…` : s;diff --git a/viewer/src/core/maps.test.ts b/viewer/src/core/maps.test.tsnew file mode 100644index 0000000..24f77e7--- /dev/null+++ b/viewer/src/core/maps.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it, vi } from 'vitest';+import {+ fetchMapWithRetry,+ isUrlFailure,+ mapRequestIds,+} from './maps';+import {+ SESSION_MAP_SCHEMA_V1,+ sessionExplorerMapBatchSchema,+ sessionMapSchema,+ isMapFound,+} from './schema';++const LIST = ['a', 'b', 'c', 'd', 'e'];++describe('mapRequestIds', () => {+ it('asks for the selected session plus the next two', () => {+ expect(mapRequestIds(LIST, 'b')).toEqual(['b', 'c', 'd']);+ });++ it('stops at the end of the list', () => {+ expect(mapRequestIds(LIST, 'd')).toEqual(['d', 'e']);+ expect(mapRequestIds(LIST, 'e')).toEqual(['e']);+ });++ it('skips sessions already known to have no map', () => {+ expect(mapRequestIds(LIST, 'a', new Set(['b']))).toEqual(['a', 'c', 'd']);+ });++ it('requests a selected id that is not in the list on its own', () => {+ expect(mapRequestIds(LIST, 'zz')).toEqual(['zz']);+ });+});++const doc = sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: { id: 'local:claude-code:x', startedAt: '2026-09-10T00:00:00Z' },+ totals: {},+});++class ExpiredError extends Error {+ code = 'expired';+}++describe('fetchMapWithRetry', () => {+ it('uses the first URL when it works', async () => {+ const fresh = vi.fn(async () => 'u2');+ const fetchDoc = vi.fn(async () => doc);+ await expect(fetchMapWithRetry('u1', fresh, fetchDoc)).resolves.toBe(doc);+ expect(fresh).not.toHaveBeenCalled();+ expect(fetchDoc).toHaveBeenCalledWith('u1');+ });++ it('re-resolves once after an expired URL', async () => {+ const fresh = vi.fn(async () => 'u2');+ const fetchDoc = vi+ .fn<(url: string) => Promise<typeof doc>>()+ .mockRejectedValueOnce(new ExpiredError('403'))+ .mockResolvedValueOnce(doc);+ await expect(fetchMapWithRetry('u1', fresh, fetchDoc)).resolves.toBe(doc);+ expect(fresh).toHaveBeenCalledTimes(1);+ expect(fetchDoc.mock.calls.map((c) => c[0])).toEqual(['u1', 'u2']);+ });++ it('re-resolves once after a network failure, then gives up', async () => {+ const fresh = vi.fn(async () => 'u2');+ const fetchDoc = vi.fn(async () => {+ throw new TypeError('Failed to fetch');+ });+ await expect(fetchMapWithRetry('u1', fresh, fetchDoc)).rejects.toThrow(+ TypeError+ );+ expect(fresh).toHaveBeenCalledTimes(1);+ expect(fetchDoc).toHaveBeenCalledTimes(2);+ });++ it('does not re-resolve for other failures (e.g. an unsupported schema)', async () => {+ const fresh = vi.fn(async () => 'u2');+ const err = Object.assign(new Error('bad'), { code: 'unsupported_schema' });+ const fetchDoc = vi.fn(async () => {+ throw err;+ });+ await expect(fetchMapWithRetry('u1', fresh, fetchDoc)).rejects.toBe(err);+ expect(fresh).not.toHaveBeenCalled();+ expect(isUrlFailure(err)).toBe(false);+ });+});++describe('sessionExplorerMapBatchSchema', () => {+ it('parses signed and not_found items', () => {+ const b = sessionExplorerMapBatchSchema.parse({+ success: true,+ expiresIn: 300,+ maps: [+ {+ sessionId: 'a',+ url: 'https://s3/x',+ schemaVersion: 1,+ contentHash: 'h',+ bytesGz: 10,+ },+ { sessionId: 'b', status: 'not_found' },+ ],+ });+ expect(b.maps.map((m) => isMapFound(m))).toEqual([true, false]);+ });+});diff --git a/viewer/src/core/maps.ts b/viewer/src/core/maps.tsnew file mode 100644index 0000000..9ee0d14--- /dev/null+++ b/viewer/src/core/maps.ts@@ -0,0 +1,63 @@+/**+ * Session map loading policy, kept pure so it is unit-tested in+ * `maps.test.ts`:+ * - which ids to ask the batch `map/` endpoint for (selected + next 2),+ * - fetching a map URL with one fresh-URL retry on expiry / network+ * failure (a defensive retry for sources whose URLs can expire;+ * a local server's relative URLs never do).+ */+import type { SessionMap } from './schema';++/** How many sessions after the selected one to resolve and prefetch. */+export const MAP_PREFETCH_AHEAD = 2;++/**+ * Ids for one batch `map/` call: the selected session first, then the next+ * `ahead` sessions in list order, skipping ids already known to have no map.+ * A selected id that is not in the (filtered) list is still requested alone.+ */+export function mapRequestIds(+ listIds: readonly string[],+ selectedId: string,+ unavailable: ReadonlySet<string> = new Set(),+ ahead = MAP_PREFETCH_AHEAD+): string[] {+ const out = [selectedId];+ const start = listIds.indexOf(selectedId);+ if (start < 0) return out;+ for (let i = start + 1; i < listIds.length && out.length <= ahead; i++) {+ const id = listIds[i];+ if (!unavailable.has(id) && !out.includes(id)) out.push(id);+ }+ return out;+}++/** True for failures a fresh URL can fix: a 403 (URL+ * expired, for sources that issue expiring URLs) or a network-level fetch failure. */+export function isUrlFailure(err: unknown): boolean {+ if (err instanceof TypeError) return true;+ return (+ !!err &&+ typeof err === 'object' &&+ 'code' in err &&+ (err as { code: unknown }).code === 'expired'+ );+}++/**+ * Fetch a map document from `url`; if that fails because the URL expired or+ * the network dropped, ask the source for a fresh URL once and try again. Any other+ * failure, or a second failure, is thrown to the caller (inline error card).+ */+export async function fetchMapWithRetry(+ url: string,+ freshUrl: () => Promise<string>,+ fetchDoc: (url: string) => Promise<SessionMap>+): Promise<SessionMap> {+ try {+ return await fetchDoc(url);+ } catch (err) {+ if (!isUrlFailure(err)) throw err;+ return fetchDoc(await freshUrl());+ }+}diff --git a/viewer/src/core/playback.test.ts b/viewer/src/core/playback.test.tsnew file mode 100644index 0000000..cfef6a5--- /dev/null+++ b/viewer/src/core/playback.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from 'vitest';+import {+ MS_PER_EVENT,+ SPEEDS,+ initialPlayback,+ playbackReducer,+ replayKeyAction,+ type PlaybackAction,+ type PlaybackState,+} from './playback';++const run = (s: PlaybackState, ...actions: PlaybackAction[]) =>+ actions.reduce(playbackReducer, s);++const loaded = (n = 100, start = 10) =>+ playbackReducer(initialPlayback, { type: 'load', n, start });++describe('playbackReducer', () => {+ it('loads paused and clamps the start', () => {+ expect(loaded(5, 99).p).toBe(4);+ expect(loaded(5, -3).p).toBe(0);+ expect(loaded(0, 3).p).toBe(0);+ expect(loaded().playing).toBe(false);+ });++ it('seek and step clamp and pause', () => {+ const playing = run(loaded(), { type: 'play' });+ expect(playing.playing).toBe(true);+ const sought = playbackReducer(playing, { type: 'seek', index: 500 });+ expect(sought.p).toBe(99);+ expect(sought.playing).toBe(false);+ expect(run(loaded(), { type: 'step', delta: -50 }).p).toBe(0);+ expect(run(loaded(), { type: 'step', delta: 10 }).p).toBe(20);+ });++ it('play at the end restarts from the top', () => {+ const s = run(loaded(), { type: 'seek', index: 99 }, { type: 'play' });+ expect(s.p).toBe(0);+ expect(s.playing).toBe(true);+ });++ it('does not play a single-event session', () => {+ expect(run(loaded(1, 0), { type: 'play' }).playing).toBe(false);+ });++ it('toggle flips play and pause', () => {+ const s = run(loaded(), { type: 'toggle' });+ expect(s.playing).toBe(true);+ expect(playbackReducer(s, { type: 'toggle' }).playing).toBe(false);+ });++ it('cycles speeds 1x, 4x, 16x', () => {+ const s0 = loaded();+ expect(SPEEDS[s0.speedIdx]).toBe(4);+ const s1 = playbackReducer(s0, { type: 'cycleSpeed' });+ expect(SPEEDS[s1.speedIdx]).toBe(16);+ const s2 = playbackReducer(s1, { type: 'cycleSpeed' });+ expect(SPEEDS[s2.speedIdx]).toBe(1);+ });++ it('ticks advance by elapsed time times speed', () => {+ let s = run(loaded(), { type: 'play' }); // 4x+ s = playbackReducer(s, { type: 'tick', dtMs: MS_PER_EVENT / 8 });+ expect(s.p).toBe(10); // 0.5 event accumulated+ s = playbackReducer(s, { type: 'tick', dtMs: MS_PER_EVENT / 8 });+ expect(s.p).toBe(11);+ s = playbackReducer(s, { type: 'tick', dtMs: MS_PER_EVENT });+ expect(s.p).toBe(15);+ });++ it('stops at the last event', () => {+ let s = run(loaded(20, 18), { type: 'play' });+ s = playbackReducer(s, { type: 'tick', dtMs: MS_PER_EVENT * 10 });+ expect(s.p).toBe(19);+ expect(s.playing).toBe(false);+ expect(playbackReducer(s, { type: 'tick', dtMs: 1000 })).toBe(s);+ });++ it('ignores ticks while paused', () => {+ const s = loaded();+ expect(playbackReducer(s, { type: 'tick', dtMs: 1000 })).toBe(s);+ });+});++describe('replayKeyAction', () => {+ const key = (k: string, mods: Partial<Record<string, boolean>> = {}) =>+ replayKeyAction({+ key: k,+ shiftKey: false,+ metaKey: false,+ ctrlKey: false,+ altKey: false,+ ...mods,+ });++ it('space toggles, arrows step (Shift steps 10)', () => {+ expect(key(' ')).toEqual({ type: 'toggle' });+ expect(key('ArrowRight')).toEqual({ type: 'step', delta: 1 });+ expect(key('ArrowLeft')).toEqual({ type: 'step', delta: -1 });+ expect(key('ArrowLeft', { shiftKey: true })).toEqual({+ type: 'step',+ delta: -10,+ });+ });++ it('E / X / D / O / R jump, either case', () => {+ expect(key('e')).toEqual({ type: 'jump', kind: 'edit' });+ expect(key('X')).toEqual({ type: 'jump', kind: 'err' });+ expect(key('d')).toEqual({ type: 'jump', kind: 'delay' });+ expect(key('O')).toEqual({ type: 'jump', kind: 'out' });+ expect(key('r')).toEqual({ type: 'jump', kind: 'retry' });+ });++ it('other keys and browser shortcuts map to nothing', () => {+ expect(key('q')).toBeNull();+ expect(key('Enter')).toBeNull();+ expect(key('constructor')).toBeNull();+ expect(key('e', { metaKey: true })).toBeNull();+ expect(key(' ', { ctrlKey: true })).toBeNull();+ expect(key('ArrowRight', { altKey: true })).toBeNull();+ });+});diff --git a/viewer/src/core/playback.ts b/viewer/src/core/playback.tsnew file mode 100644index 0000000..d0b849d--- /dev/null+++ b/viewer/src/core/playback.ts@@ -0,0 +1,124 @@+/**+ * Playback state machine for the Session Explorer. Pure: the rAF loop in+ * SessionExplorer feeds `tick` with elapsed milliseconds, everything else is a+ * user action. Unit-tested in `playback.test.ts`.+ */++export const SPEEDS = [1, 4, 16] as const;+/** ms of wall clock per event at 1x (the default pacing). */+export const MS_PER_EVENT = 220;++export interface PlaybackState {+ /** playhead: index of the current event */+ p: number;+ /** number of events in the loaded session */+ n: number;+ playing: boolean;+ speedIdx: number;+ /** fractional events accumulated between ticks */+ acc: number;+}++export type PlaybackAction =+ | { type: 'load'; n: number; start: number }+ | { type: 'seek'; index: number }+ | { type: 'step'; delta: number }+ | { type: 'play' }+ | { type: 'pause' }+ | { type: 'toggle' }+ | { type: 'cycleSpeed' }+ | { type: 'tick'; dtMs: number };++export const initialPlayback: PlaybackState = {+ p: 0,+ n: 0,+ playing: false,+ speedIdx: 1,+ acc: 0,+};++const clamp = (i: number, n: number) => Math.max(0, Math.min(n - 1, i));++export function playbackReducer(+ s: PlaybackState,+ a: PlaybackAction+): PlaybackState {+ switch (a.type) {+ case 'load':+ return {+ ...s,+ n: a.n,+ p: a.n ? clamp(a.start, a.n) : 0,+ playing: false,+ acc: 0,+ };+ case 'seek':+ if (!s.n) return s;+ return { ...s, p: clamp(a.index, s.n), playing: false, acc: 0 };+ case 'step':+ if (!s.n) return s;+ return { ...s, p: clamp(s.p + a.delta, s.n), playing: false, acc: 0 };+ case 'play':+ if (s.n < 2) return s;+ // At the end, play restarts from the top.+ return { ...s, playing: true, acc: 0, p: s.p >= s.n - 1 ? 0 : s.p };+ case 'pause':+ return s.playing ? { ...s, playing: false, acc: 0 } : s;+ case 'toggle':+ return playbackReducer(s, { type: s.playing ? 'pause' : 'play' });+ case 'cycleSpeed':+ return { ...s, speedIdx: (s.speedIdx + 1) % SPEEDS.length };+ case 'tick': {+ if (!s.playing) return s;+ const acc = s.acc + (a.dtMs * SPEEDS[s.speedIdx]) / MS_PER_EVENT;+ if (acc < 1) return { ...s, acc };+ const adv = Math.floor(acc);+ if (s.p >= s.n - 1) return { ...s, playing: false, acc: 0 };+ const p = clamp(s.p + adv, s.n);+ return { ...s, p, acc: acc - adv, playing: p < s.n - 1 };+ }+ default:+ return s;+ }+}++/** What a key press in the replay region does (see its aria-label). */+export type ReplayKeyAction =+ | { type: 'toggle' }+ | { type: 'step'; delta: number }+ | { type: 'jump'; kind: JumpKey };++type JumpKey = 'edit' | 'err' | 'delay' | 'out' | 'retry';++const JUMP_KEYS: Record<string, JumpKey> = {+ e: 'edit',+ x: 'err',+ d: 'delay',+ o: 'out',+ // Retries have no category chip; R keeps the jump the old Next… menu had.+ r: 'retry',+};++/**+ * Space plays or pauses, the arrow keys step (Shift steps 10), and E / X / D /+ * O / R jump to the next edit / error / delay / output / retry. Any modifier+ * other than Shift means the key belongs to the browser, so it maps to nothing.+ */+export function replayKeyAction(e: {+ key: string;+ shiftKey: boolean;+ metaKey: boolean;+ ctrlKey: boolean;+ altKey: boolean;+}): ReplayKeyAction | null {+ if (e.metaKey || e.ctrlKey || e.altKey) return null;+ if (e.key === ' ') return { type: 'toggle' };+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {+ const d = (e.shiftKey ? 10 : 1) * (e.key === 'ArrowRight' ? 1 : -1);+ return { type: 'step', delta: d };+ }+ const k = e.key.toLowerCase();+ return Object.hasOwn(JUMP_KEYS, k)+ ? { type: 'jump', kind: JUMP_KEYS[k] }+ : null;+}diff --git a/viewer/src/core/promptImages.test.ts b/viewer/src/core/promptImages.test.tsnew file mode 100644index 0000000..bb26c93--- /dev/null+++ b/viewer/src/core/promptImages.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';+import {+ imageLabel,+ mediaTypeLabel,+ pasteTag,+ promptImageTurns,+} from './promptImages';+import { SESSION_MAP_SCHEMA_V1, sessionMapSchema } from './schema';++type RawEvent = Record<string, unknown> & { kind: string };++function makeMap(events: RawEvent[]) {+ return sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: {+ id: 'local:claude-code:s1',+ startedAt: '2026-09-23T15:44:00Z',+ },+ totals: { calls: 0, requests: 0 },+ agents: [+ { id: 'main', parent: null, kind: 'main' },+ { id: 'sub1', parent: 'main', kind: 'subagent' },+ ],+ events: events.map((e, i) => ({ seq: i, t: i * 1000, agent: 'main', ...e })),+ });+}++describe('promptImageTurns', () => {+ it('numbers turns over main-agent user events only, across mixed events', () => {+ const map = makeMap([+ { kind: 'user', task: 1, images: 1 }, // turn 1+ { kind: 'llm', task: 1 },+ { kind: 'user', task: 1, agent: 'sub1', images: 5 }, // subagent: no turn+ { kind: 'exec', task: 1 },+ { kind: 'user', task: 2 }, // turn 2, no images+ { kind: 'llm', task: 2 },+ { kind: 'user', task: 2, images: 2 }, // turn 3+ { kind: 'user', task: 3, images: 4 }, // turn 4+ ]);+ expect(promptImageTurns(map, 1)).toEqual([{ turn: 1, count: 1 }]);+ expect(promptImageTurns(map, 2)).toEqual([{ turn: 3, count: 2 }]);+ expect(promptImageTurns(map, 3)).toEqual([{ turn: 4, count: 4 }]);+ });++ it('keeps global numbering and excludes events outside the task window', () => {+ const map = makeMap([+ { kind: 'user', task: 1, images: 3 },+ { kind: 'user', task: 2, images: 1 },+ { kind: 'user', task: 2, images: 2 },+ ]);+ expect(promptImageTurns(map, 2)).toEqual([+ { turn: 2, count: 1 },+ { turn: 3, count: 2 },+ ]);+ expect(promptImageTurns(map, 9)).toEqual([]);+ });++ it('returns nothing when no turn carried images', () => {+ const map = makeMap([+ { kind: 'user', task: 1 },+ { kind: 'user', task: 1, images: 0 },+ { kind: 'llm', task: 1 },+ ]);+ expect(promptImageTurns(map, 1)).toEqual([]);+ });+});++describe('labels', () => {+ it('uses the paste id, falling back to the 1-based position', () => {+ expect(pasteTag(2, 0)).toBe('#2');+ expect(pasteTag(null, 0)).toBe('#1');+ expect(imageLabel(null, 2, 'image/png')).toBe('#3 · PNG');+ });++ it('labels media types', () => {+ expect(mediaTypeLabel('image/png')).toBe('PNG');+ expect(mediaTypeLabel('image/jpeg')).toBe('JPEG');+ expect(mediaTypeLabel('image/svg+xml')).toBe('SVG');+ expect(mediaTypeLabel('')).toBe('');+ expect(imageLabel(2, 0, '')).toBe('#2');+ expect(imageLabel(2, 0, 'image/webp')).toBe('#2 · WEBP');+ });+});diff --git a/viewer/src/core/promptImages.ts b/viewer/src/core/promptImages.tsnew file mode 100644index 0000000..c867ad1--- /dev/null+++ b/viewer/src/core/promptImages.ts@@ -0,0 +1,54 @@+import type { SessionMap } from './schema';++/** One user turn that carried pasted images. */+export interface PromptImageTurn {+ /** 1-based, counted over the whole session's main-agent user events */+ turn: number;+ /** images the map recorded on that turn */+ count: number;+}++/**+ * The turns of one task that carried images, numbered the way the server+ * numbers them: the builder counts every `user` event of the `main` agent in+ * array order, so the k-th such event is turn k for the whole session, not+ * for the task. `map` must therefore be the full map (never a scoped or lens+ * view, which drops events and shifts the count). A task's window is the+ * events stamped with its number, the same windowing `taskSummaries` uses.+ */+export function promptImageTurns(+ map: Pick<SessionMap, 'events'>,+ task: number+): PromptImageTurn[] {+ const out: PromptImageTurn[] = [];+ let turn = 0;+ for (const e of map.events) {+ if (e.kind !== 'user' || e.agent !== 'main') continue;+ turn += 1;+ const count = e.images ?? 0;+ if (e.task === task && count > 0) out.push({ turn, count });+ }+ return out;+}++/** "#2" for a paste id, else the image's 1-based position in its task. */+export function pasteTag(pasteId: number | null, i: number): string {+ return `#${pasteId ?? i + 1}`;+}++/** "PNG" from "image/png"; "SVG" from "image/svg+xml"; '' when unknown. */+export function mediaTypeLabel(mediaType: string): string {+ const sub = mediaType.split('/')[1]?.split('+')[0]?.trim();+ return sub ? sub.toUpperCase() : '';+}++/** Thumbnail overlay text: "#2 · PNG". */+export function imageLabel(+ pasteId: number | null,+ i: number,+ mediaType: string+): string {+ const type = mediaTypeLabel(mediaType);+ const tag = pasteTag(pasteId, i);+ return type ? `${tag} · ${type}` : tag;+}diff --git a/viewer/src/core/schema.test.ts b/viewer/src/core/schema.test.tsnew file mode 100644index 0000000..d781b9f--- /dev/null+++ b/viewer/src/core/schema.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest';+import { sessionExplorerSessionSchema, sessionMapSchema } from './schema';++const BASE = { sessionId: 's1', startedAt: '2026-09-10T00:00:00Z' };++// The CLI writes JSON, so an absent optional is `null`, not a missing key. The+// schema's optionals rejected null, and `tasks` is wrapped in `.catch(undefined)`+// — so a single `"name": null` silently dropped every task in the map and the+// sidebar fell back to "Task 1", "Task 2", ... for every turn-derived session.+describe('sessionMapSchema null handling', () => {+ const map = (tasks: unknown) => ({+ schema: 'agentplay/v1',+ session: { id: 's1', startedAt: '2026-09-10T00:00:00Z' },+ totals: {},+ events: [],+ tasks,+ });++ it('keeps a tasks block whose optional fields are null', () => {+ const parsed = sessionMapSchema.parse(+ map([+ { n: 1, id: 'turn:1', name: null, source: 'turns', startSeq: 0, endSeq: 3 },+ { n: 2, id: 'turn:2', name: 'fix the flaky test', source: 'turns' },+ ])+ );+ expect(parsed.tasks).toHaveLength(2);+ expect(parsed.tasks?.[0]?.name ?? null).toBeNull();+ expect(parsed.tasks?.[1]?.name).toBe('fix the flaky test');+ });++ it('still drops a genuinely malformed tasks block rather than failing the map', () => {+ const parsed = sessionMapSchema.parse(map([{ n: 'not-a-number' }]));+ expect(parsed.tasks).toBeUndefined();+ expect(parsed.schema).toBe('agentplay/v1');+ });+});++describe('sessionExplorerSessionSchema repos', () => {+ it('keeps plain string repos as-is', () => {+ const s = sessionExplorerSessionSchema.parse({+ ...BASE,+ repos: ['api', 'web'],+ });+ expect(s.repos).toEqual(['api', 'web']);+ });++ // A server may reduce a commit-summary repo to `{name, remote}` when it is+ // not a plain string. Parsing it with `z.array(z.string())`+ // would throw and put the whole sessions list into its error state.+ it('normalizes {name, remote} objects to their display name', () => {+ const s = sessionExplorerSessionSchema.parse({+ ...BASE,+ repos: [+ { name: 'api', remote: '[email protected]:acme/api.git' },+ 'web',+ ],+ });+ expect(s.repos).toEqual(['api', 'web']);+ });++ it('falls back to remote when name is missing', () => {+ const s = sessionExplorerSessionSchema.parse({+ ...BASE,+ repos: [{ remote: '[email protected]:acme/api.git' }],+ });+ expect(s.repos).toEqual(['[email protected]:acme/api.git']);+ });++ it('drops entries with neither a usable name nor remote', () => {+ const s = sessionExplorerSessionSchema.parse({+ ...BASE,+ repos: [{}, '', ' '],+ });+ expect(s.repos).toEqual([]);+ });+});diff --git a/viewer/src/core/schema.ts b/viewer/src/core/schema.tsnew file mode 100644index 0000000..a7c3693--- /dev/null+++ b/viewer/src/core/schema.ts@@ -0,0 +1,462 @@+import { z } from 'zod';++/**+ * Session Explorer API boundary.+ *+ * The three data endpoints (`status`, `sessions`, `map`) answer in camelCase,+ * and the map document itself is `agentplay/v1` (the older+ * `entelligence.session-map/v1` name is the same document shape and is+ * accepted too), fetched from whatever URL the data source's `map` batch hands back.+ *+ * The map schema is validated loosely: every object is `passthrough` and+ * optional fields default, so a CLI that adds a field never breaks the page.+ * Only the `schema` discriminator is strict, because a v2 map is not something+ * this renderer can draw.+ */++export const SESSION_MAP_SCHEMA_V1 = 'agentplay/v1';+/** The same v1 document under its original name; readers accept both. */+export const SESSION_MAP_SCHEMA_V1_LEGACY = 'entelligence.session-map/v1';++export const sessionExplorerStatusSchema = z+ .object({+ success: z.boolean().optional(),+ available: z.boolean().catch(false).default(false),+ mapCount: z.number().catch(0).default(0),+ latestSessionDate: z.string().nullable().catch(null).default(null),+ })+ .passthrough();+export type SessionExplorerStatus = z.infer<typeof sessionExplorerStatusSchema>;++/** Session-list `repos`: a server sends either plain names or+ * `{name, remote}` objects reduced from the commit summary. Normalize both+ * to the display name `SessionList` renders. */+const sessionRepoNameSchema = z+ .union([+ z.string(),+ z+ .object({ name: z.string().optional(), remote: z.string().optional() })+ .passthrough(),+ ])+ .transform((repo) =>+ (typeof repo === 'string' ? repo : (repo.name ?? repo.remote ?? '')).trim()+ )+ .catch('');++export const sessionExplorerSessionSchema = z+ .object({+ sessionId: z.string(),+ sessionDate: z.string().nullable().default(null),+ startedAt: z.string(),+ endedAt: z.string().nullable().default(null),+ durationMs: z.number().default(0),+ agentTool: z.string().default('claude-code'),+ models: z.array(z.string()).default([]),+ repos: z+ .array(sessionRepoNameSchema)+ .default([])+ .transform((repos) => repos.filter((r) => r.length > 0)),+ calls: z.number().default(0),+ requests: z.number().default(0),+ subagents: z.number().default(0),+ errors: z.number().default(0),+ filesTouched: z.number().default(0),+ costUsd: z.number().default(0),+ tokens: z.number().default(0),+ userTurns: z.number().default(0),+ sessionTitle: z.string().nullable().default(null),+ contentHash: z.string().nullable().default(null),+ bytesGz: z.number().nullable().default(null),+ updatedAt: z.string().nullable().default(null),+ // optional signal summary (render when present)+ errorsBySource: z+ .record(z.string(), z.number())+ .optional()+ .catch(undefined),+ retries: z.number().optional().catch(undefined),+ delays: z.number().optional().catch(undefined),+ maxContext: z.number().optional().catch(undefined),+ compactions: z.number().optional().catch(undefined),+ // All optional: an older server omits them.+ role: z.string().nullable().optional().catch(undefined),+ parentSessionId: z.string().nullable().optional().catch(undefined),+ tasks: z.number().optional().catch(undefined),+ outputs: z.record(z.string(), z.number()).optional().catch(undefined),+ prs: z+ .array(+ z+ .object({+ repo: z.string().optional(),+ number: z.number().optional(),+ url: z.string().optional(),+ state: z.string().optional(),+ })+ .passthrough()+ )+ .optional()+ .catch(undefined),+ })+ .passthrough();+export type SessionExplorerSession = z.infer<+ typeof sessionExplorerSessionSchema+>;++export const sessionExplorerSessionsSchema = z+ .object({+ success: z.boolean().optional(),+ sessions: z.array(sessionExplorerSessionSchema).default([]),+ nextCursor: z.string().nullable().default(null),+ hasMore: z.boolean().default(false),+ })+ .passthrough();+export type SessionExplorerSessionsPage = z.infer<+ typeof sessionExplorerSessionsSchema+>;++/** One map entry in the batch answer: where to fetch it and its hash. */+export const sessionExplorerMapMetaSchema = z+ .object({+ sessionId: z.string(),+ url: z.string().min(1),+ schemaVersion: z.number().default(1),+ contentHash: z.string().min(1),+ bytesGz: z.number().nullable().default(null),+ })+ .passthrough();+export type SessionExplorerMapMeta = z.infer<+ typeof sessionExplorerMapMetaSchema+>;++/** An id the server has no map for (unknown or removed row). */+export const sessionExplorerMapMissingSchema = z+ .object({ sessionId: z.string(), status: z.literal('not_found') })+ .passthrough();++/** `map/?session_id=A&session_id=B…` (1-20 ids). */+export const sessionExplorerMapBatchSchema = z+ .object({+ success: z.boolean().optional(),+ expiresIn: z.number().default(300),+ maps: z+ .array(+ z.union([sessionExplorerMapMetaSchema, sessionExplorerMapMissingSchema])+ )+ .default([]),+ })+ .passthrough();+export type SessionExplorerMapBatch = z.infer<+ typeof sessionExplorerMapBatchSchema+>;+export type SessionExplorerMapItem = SessionExplorerMapBatch['maps'][number];++/** `GET /api/prompt-images`: the images pasted into each user turn. `turn` is+ * 1-based over the session's main-agent user events (see `promptImageTurns`). */+export const promptImagesResponseSchema = z+ .object({+ success: z.boolean().optional(),+ turns: z+ .array(+ z+ .object({+ turn: z.number().int(),+ images: z+ .array(+ z+ .object({+ i: z.number().int(),+ pasteId: z.number().nullable().catch(null).default(null),+ mediaType: z.string().catch('').default(''),+ available: z.boolean().catch(false).default(false),+ })+ .passthrough()+ )+ .default([]),+ })+ .passthrough()+ )+ .default([]),+ })+ .passthrough();+export type PromptImagesResponse = z.infer<typeof promptImagesResponseSchema>;++/** `GET /api/hook-detail`: what one failed hook said and ran. Free text that+ * a map never carries; the server reads it from the transcript on demand. */+export const hookDetailResponseSchema = z+ .object({+ success: z.boolean().optional(),+ message: z.string().nullable().catch(null).default(null),+ command: z.string().nullable().catch(null).default(null),+ })+ .passthrough();+export type HookDetailResponse = z.infer<typeof hookDetailResponseSchema>;++export const isMapFound = (+ item: SessionExplorerMapItem+): item is SessionExplorerMapMeta =>+ 'url' in item && typeof item.url === 'string';++// --- map document ---------------------------------------------------------++const touchSchema = z.enum(['hit', 'read', 'edit']).catch('hit');++/** `targets[].op` / `files[].op`: closed vocabulary, but optional and+ * `.catch(undefined)` since most tool events touch no file at all. */+const fileOpSchema = z+ .enum(['create', 'modify', 'delete', 'rename-from', 'rename-to'])+ .optional()+ .catch(undefined);++const targetSchema = z+ .object({+ file: z.number().optional(),+ scope: z.string().optional(),+ label: z.string().optional(),+ touch: touchSchema,+ op: fileOpSchema,+ })+ .passthrough();++// The CLI writes JSON, where an absent value is `null` (`"name": null`), not a+// missing key. `.optional()` alone rejects null, which took whole blocks down:+// `tasks` is wrapped in `.catch(undefined)`, so one null name silently discarded+// every task in the map and the viewer fell back to "Task 1", "Task 2", ...+const optNum = z.number().nullish();+const optStr = z.string().nullish();++/** `events[].vcs`: a VCS/PR-hosting operation. `action` is an open+ * vocabulary (git subcommands, `<noun>_<verb>` for gh/glab) except the three+ * closed PR-creation states (`pr_create`, `pr_create_attempt`,+ * `pr_create_failed`), so it stays `z.string()` rather than an enum. */+const vcsSchema = z+ .object({+ provider: z.string(),+ action: z.string(),+ repo: optStr,+ number: optNum,+ })+ .passthrough()+ .optional();++export const sessionMapEventSchema = z+ .object({+ seq: optNum,+ t: z.number().default(0),+ kind: z.string(),+ agent: z.string().default('main'),+ err: z.boolean().default(false),+ tool: optStr,+ verb: optStr,+ targets: z.array(targetSchema).optional(),+ // PR creation, tool categories+ vcs: vcsSchema,+ cat: optStr,+ outBytes: optNum,+ dur: optNum,+ server: optStr,+ skill: optStr,+ subagentType: optStr,+ model: optStr,+ child: optStr,+ host: optStr,+ in: optNum,+ cw: optNum,+ cr: optNum,+ out: optNum,+ cost: optNum,+ chars: optNum,+ // signals: tool/MCP/subagent failures and retries+ errClass: optStr,+ exitCode: optNum,+ retryOf: optNum,+ attempt: optNum,+ // llm response metadata (never text)+ latency: optNum,+ stop: optStr,+ thinking: z.boolean().optional(),+ toolCalls: optNum,+ textChars: optNum,+ // error events+ source: optStr,+ hook: optStr,+ hookEvent: optStr,+ srcUuid: optStr,+ retry: z.boolean().optional(),+ // delay events+ cause: optStr,+ ms: optNum,+ ref: optNum,+ // compaction events+ trigger: optStr,+ preTokens: optNum,+ postTokens: optNum,+ // Additive in v1: task number + driving model on+ // every event, prompt shape on user turns (counts only, never content),+ // and the fields of the output kinds (commit / pr_merge / pr_close /+ // pr_comment / ticket / artifact / skill_write / model_switch).+ task: optNum,+ images: optNum,+ urls: optNum,+ repo: optStr,+ sha: optStr,+ files: optNum,+ ins: optNum,+ del: optNum,+ number: optNum,+ url: optStr,+ tracker: optStr,+ action: optStr,+ id: optStr,+ title: optStr,+ bytes: optNum,+ version: optNum,+ name: optStr,+ from: optStr,+ to: optStr,+ })+ .passthrough();++/** `tasks[]`: the CLI's own segmentation (`source: "segments"`) or+ * one task per user-turn window (`"turns"`). `startSeq`/`endSeq` are+ * inclusive event sequence numbers (seq === index). */+export const sessionMapTaskSchema = z+ .object({+ n: z.number(),+ id: optStr,+ name: optStr,+ source: optStr,+ startSeq: optNum,+ endSeq: optNum,+ startT: optNum,+ endT: optNum,+ firstTurn: optNum,+ lastTurn: optNum,+ })+ .passthrough();++export const sessionMapSchema = z+ .object({+ schema: z.union([+ z.literal(SESSION_MAP_SCHEMA_V1),+ z.literal(SESSION_MAP_SCHEMA_V1_LEGACY),+ ]),+ session: z+ .object({+ id: z.string(),+ agentTool: z.string().default('claude-code'),+ cliVersion: optStr,+ startedAt: z.string(),+ durationMs: z.number().default(0),+ models: z.array(z.string()).default([]),+ pathMode: optStr,+ truncated: z.boolean().default(false),+ // one of pr_created | verified | blocked | interrupted |+ // unresolved_errors | completed | incomplete; open string so an+ // unrecognized value degrades to its own label instead of failing.+ outcome: optStr,+ role: z.string().nullable().optional(),+ parentSessionId: z.string().nullable().optional(),+ })+ .passthrough(),+ totals: z+ .object({+ calls: z.number().default(0),+ requests: z.number().default(0),+ userTurns: z.number().default(0),+ subagents: z.number().default(0),+ errors: z.number().default(0),+ tokens: z.number().default(0),+ costUsd: z.number().default(0),+ filesTouched: z.number().default(0),+ errorsBySource: z.record(z.string(), z.number()).default({}),+ errorsByClass: z.record(z.string(), z.number()).default({}),+ retries: optNum,+ delays: optNum,+ delayMs: optNum,+ maxContext: optNum,+ compactions: optNum,+ llmLatencyP50: optNum,+ llmLatencyP95: optNum,+ outputTokens: optNum,+ // PR creation, file ops+ prsCreated: optNum,+ filesCreated: optNum,+ filesDeleted: optNum,+ })+ .passthrough(),+ repos: z+ .array(+ z+ .object({ id: z.string(), name: z.string(), remote: optStr })+ .passthrough()+ )+ .default([]),+ files: z+ .array(+ z+ .object({+ id: z.number(),+ repo: z.string(),+ path: z.string(),+ reads: z.number().default(0),+ edits: z.number().default(0),+ hits: z.number().default(0),+ first: optNum,+ // last op seen for this file across the whole doc; a lens must+ // not read this for its own scope (see fileCoverage/recomputeTotals)+ op: fileOpSchema,+ })+ .passthrough()+ )+ .default([]),+ // Confirmed PR/MRs; `seq` points at the creating event.+ // `totals.prsCreated` = length, kept separately since the producer+ // writes both.+ prs: z+ .array(+ z+ .object({+ provider: z.string(),+ repo: optStr,+ number: z.number(),+ url: z.string(),+ seq: z.number(),+ state: optStr,+ })+ .passthrough()+ )+ .default([]),+ agents: z+ .array(+ z+ .object({+ id: z.string(),+ parent: z.string().nullable().default(null),+ kind: z.string().default('main'),+ subagentType: optStr,+ launchSeq: optNum,+ start: z.number().default(0),+ end: z.number().default(0),+ calls: z.number().default(0),+ requests: z.number().default(0),+ tokens: z.number().default(0),+ cost: z.number().default(0),+ outcome: optStr,+ })+ .passthrough()+ )+ .default([]),+ events: z.array(sessionMapEventSchema).default([]),+ // A malformed tasks block must never fail the whole map: drop it and+ // fall back to per-user-turn windows.+ tasks: z.array(sessionMapTaskSchema).optional().catch(undefined),+ })+ .passthrough();++export type SessionMap = z.infer<typeof sessionMapSchema>;+export type SessionMapEvent = SessionMap['events'][number];+export type SessionMapTarget = NonNullable<SessionMapEvent['targets']>[number];+export type SessionMapFile = SessionMap['files'][number];+export type SessionMapAgent = SessionMap['agents'][number];+export type SessionMapPr = SessionMap['prs'][number];+export type SessionMapTask = z.infer<typeof sessionMapTaskSchema>;+export type FileOp = NonNullable<SessionMapFile['op']>;diff --git a/viewer/src/core/sessionLayout.test.ts b/viewer/src/core/sessionLayout.test.tsnew file mode 100644index 0000000..eee0ea6--- /dev/null+++ b/viewer/src/core/sessionLayout.test.ts@@ -0,0 +1,1438 @@+import { describe, expect, it, vi } from 'vitest';+import {+ SESSION_MAP_SCHEMA_V1,+ sessionMapSchema,+ type SessionExplorerSession,+ type SessionMap,+ type SessionMapEvent,+ type SessionMapPr,+} from './schema';+import {+ buildTree,+ deriveLensDoc,+ eventNodeRefs,+ outputTotals,+ srcSeqOf,+ subagentOrdinal,+ activeSet,+ type NodeRef,+} from './sessionMapModel';+import { deriveScopeDoc, sessionTasks, stampTasks, withoutSrcSeq } from './sessionScope';+import { optionalLanesHeight } from './timelineDraw';+import {+ SIDEBAR_COLLAPSED_KEY,+ adjacentSubagent,+ adjacentTask,+ agentWindow,+ costLabel,+ lensSourceIndex,+ nearestLensIndex,+ orderedSubagents,+ outputsLine,+ readSidebarCollapsed,+ resolveSidebarTab,+ errorClickAction,+ sessionErrors,+ taskErrors,+ wholeSessionErrors,+ sidebarTabs,+ stripState,+ taskAt,+ taskIndexWindow,+ taskSummaries,+ touchedGroups,+ windowProgress,+ writeSidebarCollapsed,+ getSidebarCollapsed,+ setSidebarCollapsed,+ spanBarGeometry,+ subscribeSidebarCollapsed,+ agentOptions,+ agentOptionsInScope,+ emptyScopeDescription,+ detailsTitle,+ groupSessionsByDay,+ hasScopeFilter,+ outcomeParts,+ prCountLabel,+ prMenuItems,+ safeLinkUrl,+ promptLine,+ sidebarRailLabel,+ taskFilterLabel,+ CATEGORIES,+ DEFAULT_CATEGORIES,+ activeRefs,+ DOCK_HEIGHT_KEY,+ DOCK_MIN_HEIGHT,+ clampDockHeight,+ dockOverflow,+ categoryIndices,+ categoryMatches,+ categoryOf,+ displayCategory,+ isDefaultCategories,+ lastPicked,+ mapChipSelection,+ magnitude,+ matchesAnyCategory,+ mapFocus,+ pathFocus,+ narrowsView,+ parseCategories,+ pickHistory,+ serializeCategories,+ sizeMetric,+ toggleCategory,+ type Category,+ getDockHeight,+ readDockHeight,+ setDockHeight,+ stepEvent,+ stepPosition,+ subagentLanes,+ subscribeDockHeight,+ writeDockHeight,+} from './sessionLayout';++type RawEvent = Record<string, unknown> & { kind: string };++function makeMap(events: RawEvent[]): SessionMap {+ return sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: {+ id: 'local:claude-code:s1',+ agentTool: 'claude-code',+ startedAt: '2026-09-23T15:44:00Z',+ durationMs: 60_000,+ models: ['opus-5.5'],+ },+ totals: { calls: 0, requests: 0 },+ repos: [{ id: 'r0', name: 'dashboard' }],+ files: [+ { id: 0, repo: 'r0', path: 'src/proxy.ts' },+ { id: 1, repo: 'r0', path: 'src/app.ts' },+ ],+ agents: [+ { id: 'main', parent: null, kind: 'main' },+ { id: 'subA', parent: 'main', kind: 'subagent', subagentType: 'Explore' },+ { id: 'subB', parent: 'main', kind: 'subagent', subagentType: 'fork' },+ { id: 'ghost', parent: 'main', kind: 'subagent' },+ ],+ prs: [],+ events: events.map((e, i) => ({+ seq: i,+ t: i * 1000,+ agent: 'main',+ ...e,+ })),+ });+}++/** Two tasks: subA is spawned and runs in task 1, subB in task 2; the+ * `ghost` agent is listed but never runs. */+const EVENTS: RawEvent[] = [+ { kind: 'user', chars: 10 }, // 0 task 1+ { kind: 'llm', model: 'opus-5.5', cost: 0.5 }, // 1+ { kind: 'subagent', child: 'subA', subagentType: 'Explore' }, // 2+ { kind: 'llm', agent: 'subA', model: 'haiku-4.5', cost: 0 }, // 3+ { kind: 'read', agent: 'subA', targets: [{ file: 0, touch: 'read' }] }, // 4+ { kind: 'read', agent: 'subA', targets: [{ file: 0, touch: 'read' }] }, // 5+ { kind: 'edit', agent: 'subA', targets: [{ file: 1, touch: 'edit' }] }, // 6+ { kind: 'user', chars: 20 }, // 7 task 2+ { kind: 'subagent', child: 'subB', subagentType: 'fork' }, // 8+ { kind: 'exec', agent: 'subB' }, // 9+ { kind: 'llm', model: 'opus-5.5', cost: 1.25 }, // 10+ { kind: 'commit', repo: 'dashboard', sha: 'abc', files: 1 }, // 11+];++const map = stampTasks(makeMap(EVENTS));++describe('windows', () => {+ it('agentWindow spans first..last event of the agent', () => {+ expect(agentWindow(map.events, 'subA')).toEqual({ start: 3, end: 6 });+ expect(agentWindow(map.events, 'subB')).toEqual({ start: 9, end: 9 });+ expect(agentWindow(map.events, 'ghost')).toBeNull();+ });++ it('taskIndexWindow uses the task stamps', () => {+ expect(taskIndexWindow(map.events, 1)).toEqual({ start: 0, end: 6 });+ expect(taskIndexWindow(map.events, 2)).toEqual({ start: 7, end: 11 });+ expect(taskIndexWindow(map.events, 9)).toBeNull();+ });++ it('lensSourceIndex maps a lensed replay back onto the session', () => {+ const src = lensSourceIndex(map.events, 'subA');+ expect(src).toEqual([3, 4, 5, 6]);+ // the lens doc has exactly those events, in that order+ expect(deriveLensDoc(map, 'subA').events).toHaveLength(src.length);+ });++ it('nearestLensIndex snaps a session index to the closest lens event', () => {+ const src = [3, 4, 5, 9];+ expect(nearestLensIndex(src, 0)).toBe(0);+ expect(nearestLensIndex(src, 4)).toBe(1);+ expect(nearestLensIndex(src, 7)).toBe(2); // 5 and 9 tie -> earlier+ expect(nearestLensIndex(src, 8)).toBe(3);+ expect(nearestLensIndex(src, 100)).toBe(3);+ expect(nearestLensIndex([], 4)).toBe(0);+ });++ it('windowProgress clamps to the window', () => {+ expect(windowProgress({ start: 10, end: 20 }, 5)).toBe(0);+ expect(windowProgress({ start: 10, end: 20 }, 15)).toBe(0.5);+ expect(windowProgress({ start: 10, end: 20 }, 25)).toBe(1);+ expect(windowProgress({ start: 4, end: 4 }, 4)).toBe(1);+ expect(windowProgress(null, 4)).toBe(0);+ });+});++describe('tasks', () => {+ const { tasks } = sessionTasks(map);++ it('taskAt reads the task under the playhead', () => {+ expect(taskAt(map.events, 0)).toBe(1);+ expect(taskAt(map.events, 9)).toBe(2);+ expect(taskAt(map.events, 99)).toBeNull();+ });++ it('adjacentTask steps and clamps', () => {+ expect(adjacentTask(tasks, 1, 1)).toBe(2);+ expect(adjacentTask(tasks, 2, 1)).toBe(2);+ expect(adjacentTask(tasks, 1, -1)).toBe(1);+ expect(adjacentTask(tasks, null, 1)).toBe(1);+ expect(adjacentTask(tasks, null, -1)).toBe(2);+ expect(adjacentTask([], 1, 1)).toBeNull();+ });++ it('taskSummaries sums each task once', () => {+ const s = taskSummaries(map);+ expect(s.get(1)?.cost).toBeCloseTo(0.5);+ expect(s.get(2)?.cost).toBeCloseTo(1.25);+ expect(s.get(2)?.outputs.commits).toBe(1);+ expect(s.get(1)?.requests).toBe(2);+ });++ it('costLabel says n/a instead of $0.00', () => {+ expect(costLabel(0)).toBe('cost n/a');+ expect(costLabel(1.5)).toBe('$1.50');+ });++ it('outputsLine lists only non-zero outputs', () => {+ expect(outputsLine(outputTotals(map.events))).toBe('1 commit');+ expect(outputsLine(outputTotals([]))).toBe('');+ expect(outputsLine(outputTotals([]), 2)).toBe('2 PRs created');+ });+});++describe('subagents', () => {+ const ordinals = subagentOrdinal(map);++ it('orders by first event, skips agents with no events, finds the parent task', () => {+ const subs = orderedSubagents(map, ordinals);+ expect(subs.map((s) => s.id)).toEqual(['subA', 'subB']);+ expect(subs.map((s) => s.index)).toEqual([1, 2]);+ expect(subs[0]).toMatchObject({+ label: 'Sub 1: Explore',+ type: 'Explore',+ window: { start: 3, end: 6 },+ startT: 3000,+ endT: 6000,+ parentTask: 1,+ requests: 1,+ cost: 0,+ });+ expect(subs[1].parentTask).toBe(2);+ });++ it('orders by start even when the agents list says otherwise', () => {+ const late = stampTasks(+ makeMap([+ { kind: 'user' },+ { kind: 'exec', agent: 'subB' },+ { kind: 'exec', agent: 'subA' },+ ])+ );+ expect(+ orderedSubagents(late, subagentOrdinal(late)).map((s) => s.id)+ ).toEqual(['subB', 'subA']);+ });++ it('falls back to the first event task without a spawn event', () => {+ const noSpawn = stampTasks(+ makeMap([{ kind: 'user' }, { kind: 'exec', agent: 'subA' }])+ );+ expect(+ orderedSubagents(noSpawn, subagentOrdinal(noSpawn))[0].parentTask+ ).toBe(1);+ });++ it('adjacentSubagent steps without wrapping', () => {+ const subs = orderedSubagents(map, ordinals);+ expect(adjacentSubagent(subs, 'subA', 1)).toBe('subB');+ expect(adjacentSubagent(subs, 'subB', 1)).toBeNull();+ expect(adjacentSubagent(subs, 'subA', -1)).toBeNull();+ expect(adjacentSubagent(subs, 'nope', 1)).toBeNull();+ });++ it('touchedGroups groups the helper leaves by top-level group', () => {+ const lens = deriveLensDoc(map, 'subA');+ const tree = buildTree(lens);+ const groups = touchedGroups(tree, eventNodeRefs(lens, tree));+ const repo = groups.find((g) => g.name === 'dashboard');+ expect(repo).toBeDefined();+ const names = repo!.items.map((i) => i.name);+ expect(names.some((n) => n.includes('proxy.ts'))).toBe(true);+ // most-touched first: proxy.ts was read twice, app.ts edited once+ expect(repo!.items[0].count).toBeGreaterThanOrEqual(+ repo!.items[repo!.items.length - 1].count+ );+ expect(groups.every((g) => g.items.every((i) => i.type !== 'model'))).toBe(+ true+ );+ });+});++describe('stripState', () => {+ const base = {+ task: null,+ sub: null,+ collapsed: false,+ playing: false,+ playheadTask: 1,+ taskCount: 3,+ };++ it('hides with nothing active', () => {+ expect(stripState(base)).toBeNull();+ expect(stripState({ ...base, collapsed: true })).toBeNull();+ });++ it('shows a selected task only when collapsed or playing', () => {+ expect(stripState({ ...base, task: 2 })).toBeNull();+ expect(stripState({ ...base, task: 2, collapsed: true })).toEqual({+ kind: 'task',+ n: 2,+ playing: false,+ followsPlayhead: false,+ });+ expect(stripState({ ...base, task: 2, playing: true })).toMatchObject({+ n: 2,+ playing: true,+ followsPlayhead: false,+ });+ });++ it('follows the playhead task while playing with no task', () => {+ expect(stripState({ ...base, playing: true, playheadTask: 3 })).toEqual({+ kind: 'task',+ n: 3,+ playing: true,+ followsPlayhead: true,+ });+ expect(stripState({ ...base, playing: true, taskCount: 1 })).toBeNull();+ expect(+ stripState({ ...base, playing: true, playheadTask: null })+ ).toBeNull();+ });++ it('an open subagent wins over the task', () => {+ expect(+ stripState({ ...base, task: 2, sub: 'subA', playing: true })+ ).toEqual({ kind: 'sub', id: 'subA', playing: true });+ expect(stripState({ ...base, sub: 'subA' })).toBeNull();+ });+});++describe('wholeSessionErrors', () => {+ const err = (seq: number, task: number, verb: string): RawEvent => ({+ kind: 'exec', seq, t: seq * 10, tool: 'Bash', verb, err: true, errClass: 'exit_code', task,+ });+ const full = () =>+ makeMap([err(0, 1, 'ls'), err(1, 1, 'pytest'), err(2, 2, 'curl'), err(3, 3, 'ls')]);++ it('keeps the whole-session count and rows under any scope', () => {+ const m = full();+ const whole = wholeSessionErrors(m);+ expect(whole.total).toBe(4);+ // The scoped map is what the old tab read: it narrows.+ expect(sessionErrors(deriveScopeDoc(m, { task: 2, model: null })).total).toBe(1);+ // The whole-session list is built from the unscoped map, so it does not.+ expect(wholeSessionErrors(m).total).toBe(whole.total);+ });++ it('carries the whole-session seq and the task on each row', () => {+ const rows = wholeSessionErrors(full()).groups.flatMap((g) => g.errors);+ expect(rows.map((r) => [r.seq, r.task]).sort()).toEqual([+ [0, 1],+ [1, 1],+ [2, 2],+ [3, 3],+ ]);+ });+});++describe('errorClickAction', () => {+ const ev = (seq: number, task: number): RawEvent => ({+ kind: 'exec', seq, t: seq * 10, tool: 'Bash', verb: 'ls', err: true, errClass: 'exit_code', task,+ });+ const m = makeMap([ev(0, 1), ev(1, 1), ev(2, 2), ev(3, 3)]);+ const rowFor = (seq: number) =>+ wholeSessionErrors(m).groups.flatMap((g) => g.errors).find((r) => r.seq === seq)!;++ it('seeks in place by whole-session seq when nothing is filtered', () => {+ expect(errorClickAction(rowFor(2), m)).toEqual({ kind: 'seek', index: 2 });+ });++ it('seeks within a task scope by seq, not by the row index', () => {+ const scoped = deriveScopeDoc(m, { task: 2, model: null });+ expect(errorClickAction(rowFor(2), scoped)).toEqual({ kind: 'seek', index: 0 });+ });++ it('jumps to the error\'s task when the scope hides it', () => {+ const scoped = deriveScopeDoc(m, { task: 2, model: null });+ expect(errorClickAction(rowFor(3), scoped)).toEqual({ kind: 'jump', task: 3, seq: 3 });+ });++ it('clears the task filter for a hidden error that has none', () => {+ const scoped = deriveScopeDoc(m, { task: 2, model: null });+ expect(+ errorClickAction({ seq: 3, task: undefined }, scoped)+ ).toEqual({ kind: 'jump', task: null, seq: 3 });+ });+});++describe('taskErrors', () => {+ const err = (seq: number, task: number, verb: string, errClass = 'exit_code'): RawEvent => ({+ kind: 'exec', seq, t: seq * 10, tool: 'Bash', verb, err: true, errClass, task,+ });++ it('counts each task\'s errors and skips tasks with none', () => {+ const m = makeMap([+ err(0, 1, 'pytest'),+ { kind: 'exec', seq: 1, t: 10, tool: 'Bash', verb: 'ls', err: false, task: 1 },+ err(2, 1, 'pytest'),+ { kind: 'exec', seq: 3, t: 30, tool: 'Bash', verb: 'ls', err: false, task: 2 },+ err(4, 3, 'curl'),+ ]);+ const byTask = taskErrors(m);+ expect(byTask.get(1)?.count).toBe(2);+ expect(byTask.has(2)).toBe(false);+ expect(byTask.get(3)).toEqual({ count: 1, firstSeq: 4 });+ });++ it('lands on the row the scoped Errors tab lists first, not the earliest error', () => {+ // A provider-side failure comes first in time, but the Errors tab ranks it+ // last; the tag must land on what the user then sees at the top. Task 2+ // starts later, so scoping to it renumbers `seq` and the tag must still+ // resolve to the same event.+ const m = makeMap([+ err(0, 1, 'ls'),+ { kind: 'user', seq: 1, t: 10, task: 2 },+ err(2, 2, 'claude', 'rate_limit'),+ err(3, 2, 'pytest'),+ err(4, 2, 'pytest'),+ ]);+ const first = taskErrors(m).get(2);+ expect(first?.firstSeq).toBe(3);+ const scopedMap = deriveScopeDoc(m, { task: 2, model: null });+ const top = sessionErrors(scopedMap).groups[0].errors[0];+ expect(top.seq).not.toBe(3); // renumbered by the scope+ expect(srcSeqOf(scopedMap.events[top.index])).toBe(first?.firstSeq);+ });++ it('keeps the whole-session position for an event without a seq', () => {+ const m = makeMap([+ { kind: 'exec', seq: 0, t: 0, tool: 'Bash', verb: 'ls', err: false, task: 1 },+ { kind: 'exec', t: 10, tool: 'Bash', verb: 'pytest', err: true, errClass: 'exit_code', task: 1 },+ ]);+ // makeMap fills `seq` in; take it back out so the fallback is what runs.+ const noSeq = {+ ...m,+ events: m.events.map((e, i) => (i === 1 ? { ...e, seq: undefined } : e)),+ };+ expect(noSeq.events[1].seq).toBeUndefined();+ expect(taskErrors(noSeq).get(1)?.firstSeq).toBe(1);+ });++ it('never trusts a srcSeq the document arrived with', () => {+ const m = makeMap([err(0, 1, 'ls'), err(1, 1, 'pytest')]);+ // A document claiming its pytest failure is event 0: trusted, the tag+ // would land on the `ls` failure instead.+ const raw = {+ ...m,+ events: m.events.map((e, i) => (i === 1 ? { ...e, srcSeq: 0 } : e)),+ };+ const full = stampTasks(withoutSrcSeq(raw));+ expect(full.events.some((e) => e.srcSeq !== undefined)).toBe(false);+ expect(taskErrors(full).get(1)?.count).toBe(2);+ });++ it('a derivation stamps the document\'s own seq, not its position', () => {+ // seq !== index: a document whose numbering starts at 100.+ const m = makeMap([err(0, 1, 'ls'), { kind: 'user', seq: 1, t: 10, task: 2 }, err(2, 2, 'pytest')]);+ const shifted = { ...m, events: m.events.map((e, i) => ({ ...e, seq: 100 + i })) };+ const first = taskErrors(shifted).get(2);+ expect(first?.firstSeq).toBe(102);+ const scoped = deriveScopeDoc(shifted, { task: 2, model: null });+ const i = scoped.events.findIndex((e) => srcSeqOf(e) === first?.firstSeq);+ expect(scoped.events[i]?.verb).toBe('pytest');+ });+});++describe('sessionErrors', () => {+ const errMap = (events: RawEvent[]) => makeMap(events);++ it('groups failures by class and carries the detail a row needs', () => {+ const { groups, total } = sessionErrors(+ errMap([+ { kind: 'exec', seq: 0, t: 0, tool: 'Bash', verb: 'pytest', err: true, errClass: 'exit_code', exitCode: 1,+ targets: [{ label: 'src/app.py' }] },+ { kind: 'mcp', seq: 1, t: 10, server: 'linear', tool: 'search', err: true, errClass: 'timeout' },+ { kind: 'exec', seq: 2, t: 20, tool: 'Bash', verb: 'curl', err: false },+ ])+ );+ expect(total).toBe(2);+ expect(groups.map((g) => g.errClass).sort()).toEqual(['exit_code', 'timeout']);+ const exit = groups.find((g) => g.errClass === 'exit_code');+ expect(exit?.label).toBe('non-zero exit');+ expect(exit?.errors[0]).toMatchObject({+ index: 0,+ label: 'pytest',+ exitCode: 1,+ target: 'src/app.py',+ });+ expect(groups.find((g) => g.errClass === 'timeout')?.errors[0].label).toBe(+ 'linear.search'+ );+ });++ // One failure is noise; the same command failing four times running is the+ // signal worth acting on, so it has to outrank a bigger pile of one-offs.+ it('ranks a retry run above a larger pile of unrelated failures', () => {+ const run = [0, 1, 2, 3].map((i) => ({+ kind: 'exec', seq: i, t: i, tool: 'Bash', verb: 'tsc',+ err: true, errClass: 'exit_code',+ }));+ const spread = [4, 5, 6, 7, 8].map((i) => ({+ kind: 'exec', seq: i, t: i, tool: 'Bash', verb: `cmd${i}`,+ err: true, errClass: 'timeout',+ }));+ const { groups } = sessionErrors(errMap([...run, ...spread]));+ expect(groups[0].errClass).toBe('exit_code');+ expect(groups[0].worstRun).toBe(4);+ expect(groups[0].worstRunLabel).toBe('tsc');+ expect(groups[1].worstRun).toBe(1);+ });++ it('is empty for a clean session', () => {+ expect(sessionErrors(errMap([{ kind: 'exec', seq: 0, t: 0, verb: 'ls' }]))).toEqual({+ groups: [],+ total: 0,+ });+ });++ // "other error" was a fifth of real errors and says nothing. Those events+ // still carry a tool category, so use it.+ it('names an unclassified failure after its tool category', () => {+ const { groups } = sessionErrors(+ errMap([+ { kind: 'exec', seq: 0, t: 0, verb: 'aws s3', err: true, errClass: 'other', cat: 'cloud' },+ { kind: 'mcp', seq: 1, t: 1, server: 'linear', tool: 'save', err: true, cat: 'mcp' },+ ])+ );+ expect(groups.map((g) => g.label).sort()).toEqual([+ 'Cloud / infra failed',+ 'MCP (other) failed',+ ]);+ });++ // Provider failures can outnumber tool failures, so left unranked they+ // bury everything the harness can actually fix.+ it('ranks provider-side failures last however many there are', () => {+ const many = Array.from({ length: 9 }, (_, i) => ({+ kind: 'llm', seq: i, t: i, err: true, errClass: 'api_error',+ }));+ const { groups } = sessionErrors(+ errMap([+ ...many,+ { kind: 'exec', seq: 9, t: 9, verb: 'pytest', err: true, errClass: 'exit_code' },+ ])+ );+ expect(groups.map((g) => [g.errClass, g.provider])).toEqual([+ ['exit_code', false],+ ['api_error', true],+ ]);+ });++ // Every target on a real error event was a bucket ("outside-repo"), so showing+ // it put the same word on every row.+ it('keeps a target that names something and drops a privacy bucket', () => {+ const { groups } = sessionErrors(+ errMap([+ { kind: 'edit', seq: 0, t: 0, tool: 'Edit', err: true, errClass: 'stale_file',+ targets: [{ label: 'src/app.ts', scope: 'repo' }] },+ { kind: 'exec', seq: 1, t: 1, verb: 'cat', err: true, errClass: 'stale_file', dur: 1200,+ targets: [{ label: 'outside-repo', scope: 'outside' }] },+ ])+ );+ const errs = groups[0].errors;+ expect(errs[0].target).toBe('src/app.ts');+ expect(errs[1].target).toBeUndefined();+ expect(errs[1].durMs).toBe(1200);+ });+});++describe('sidebar', () => {+ it('shows Tasks only with >1 task and Subagents only with any', () => {+ expect(sidebarTabs(1, 0)).toEqual(['insights']);+ expect(sidebarTabs(2, 0)).toEqual(['tasks', 'insights']);+ expect(sidebarTabs(1, 3)).toEqual(['subagents', 'insights']);+ expect(sidebarTabs(4, 3)).toEqual(['tasks', 'subagents', 'insights']);+ });++ it('shows Errors only when the session has any', () => {+ expect(sidebarTabs(1, 0, 0)).toEqual(['insights']);+ expect(sidebarTabs(1, 0, 2)).toEqual(['errors', 'insights']);+ expect(sidebarTabs(4, 3, 2)).toEqual([+ 'tasks',+ 'errors',+ 'subagents',+ 'insights',+ ]);+ });++ it('resolves an unavailable tab to the first available', () => {+ expect(resolveSidebarTab('tasks', ['subagents', 'insights'])).toBe(+ 'subagents'+ );+ expect(resolveSidebarTab(null, ['tasks', 'insights'])).toBe('tasks');+ expect(resolveSidebarTab('insights', ['tasks', 'insights'])).toBe(+ 'insights'+ );+ });++ it('persists the collapsed state and survives broken storage', () => {+ const mem = new Map<string, string>();+ const storage = {+ getItem: (k: string) => mem.get(k) ?? null,+ setItem: (k: string, v: string) => void mem.set(k, v),+ };+ expect(readSidebarCollapsed(storage)).toBe(false);+ writeSidebarCollapsed(true, storage);+ expect(mem.get(SIDEBAR_COLLAPSED_KEY)).toBe('1');+ expect(readSidebarCollapsed(storage)).toBe(true);+ const broken = {+ getItem: () => {+ throw new Error('blocked');+ },+ setItem: () => {+ throw new Error('blocked');+ },+ };+ expect(readSidebarCollapsed(broken)).toBe(false);+ expect(() => writeSidebarCollapsed(true, broken)).not.toThrow();+ expect(readSidebarCollapsed(null)).toBe(false);+ });+});++describe('spanBarGeometry', () => {+ it('keeps a one-event helper at the session end inside the track', () => {+ const { left, width } = spanBarGeometry(10_000, 10_000, 10_000);+ expect(width).toBeCloseTo(0.015);+ expect(left + width).toBeLessThanOrEqual(1);+ expect(left).toBeCloseTo(0.985);+ });++ it('places a normal span proportionally', () => {+ expect(spanBarGeometry(2_000, 5_000, 10_000)).toEqual({+ left: 0.2,+ width: 0.3,+ });+ });++ it('survives a zero-length session', () => {+ const g = spanBarGeometry(0, 0, 0);+ expect(g.left).toBe(0);+ expect(g.width).toBeCloseTo(0.015);+ expect(g.left + g.width).toBeLessThanOrEqual(1);+ });+});++describe('sidebar collapsed store', () => {+ it('notifies subscribers and reads back the value', () => {+ let calls = 0;+ const unsub = subscribeSidebarCollapsed(() => {+ calls += 1;+ });+ setSidebarCollapsed(true);+ expect(getSidebarCollapsed()).toBe(true);+ setSidebarCollapsed(false);+ expect(getSidebarCollapsed()).toBe(false);+ expect(calls).toBe(2);+ unsub();+ setSidebarCollapsed(true);+ expect(calls).toBe(2);+ setSidebarCollapsed(false);+ });+});++describe('fit-viewport header', () => {+ const pr = (number: number, repo?: string, state?: string): SessionMapPr => ({+ provider: 'github',+ repo,+ number,+ url: `https://github.com/o/${repo ?? 'r'}/pull/${number}`,+ seq: number,+ state,+ });++ it('prMenuItems lists each PR once, in map order', () => {+ const items = prMenuItems([+ pr(12, 'dashboard', 'merged'),+ pr(7),+ pr(12, 'dashboard', 'open'),+ pr(12, 'backend'),+ ]);+ expect(items.map((i) => i.label)).toEqual([+ 'dashboard #12',+ '#7',+ 'backend #12',+ ]);+ expect(items[0]).toMatchObject({+ provider: 'github',+ state: 'merged',+ url: 'https://github.com/o/dashboard/pull/12',+ });+ expect(items[1].state).toBeNull();+ expect(prMenuItems([])).toEqual([]);+ });++ it('prMenuItems drops a PR url that is not http(s)', () => {+ const bad = (url: string) => ({ ...pr(1), url });+ expect(prMenuItems([bad('javascript:alert(1)')])[0].url).toBeNull();+ expect(prMenuItems([bad('data:text/html,<script>x</script>')])[0].url).toBeNull();+ expect(prMenuItems([bad('not a url')])[0].url).toBeNull();+ expect(safeLinkUrl('http://git.example/pr/1')).toBe('http://git.example/pr/1');+ expect(safeLinkUrl(' JavaScript:alert(1)')).toBeNull();+ });++ it('prCountLabel pluralises', () => {+ expect(prCountLabel(1)).toBe('1 PR');+ expect(prCountLabel(9)).toBe('9 PRs');+ });++ it('outcomeParts: the non-zero outputs, never the task count', () => {+ expect(outcomeParts(map)).toEqual(['1 commit']);+ // A session that produced nothing gets no callout, rather than one+ // restating the `Tasks` row above it.+ expect(outcomeParts(makeMap([{ kind: 'user' }]))).toEqual([]);+ });+});++describe('fit-viewport toolbar labels', () => {+ const tasks = sessionTasks(map).tasks;++ it('taskFilterLabel names the picked prompt', () => {+ expect(taskFilterLabel(tasks, null)).toBe('All prompts');+ expect(taskFilterLabel(tasks, 2)).toBe(`2 · ${tasks[1].name}`);+ expect(taskFilterLabel(tasks, 99)).toBe('All prompts');+ // A real segmenter's windows are tasks.+ expect(+ taskFilterLabel(+ tasks.map((t) => ({ ...t, source: 'segments' as const })),+ null+ )+ ).toBe('All tasks');+ });++ it('hasScopeFilter: any filter or an open subagent', () => {+ const none = { task: null, model: null };+ expect(hasScopeFilter(none, null)).toBe(false);+ expect(hasScopeFilter({ ...none, task: 1 }, null)).toBe(true);+ expect(hasScopeFilter({ ...none, model: 'opus' }, null)).toBe(true);+ expect(hasScopeFilter(none, 'subA')).toBe(true);+ });++ it('agentOptions: the whole session, then each subagent', () => {+ const opts = agentOptions(map, subagentOrdinal(map));+ expect(opts.map((o) => o.id)).toEqual(['main', 'subA', 'subB', 'ghost']);+ expect(opts[0].label).toBe('All agents');+ expect(opts[1].label).toMatch(/Explore/);+ const solo = makeMap([{ kind: 'user' }]);+ expect(+ agentOptions({ ...solo, agents: solo.agents.slice(0, 1) }, new Map())+ ).toEqual([]);+ });++ it('agentOptionsInScope: counts inside the prompt/model scope, empty rows flagged', () => {+ const all = agentOptions(map, subagentOrdinal(map));+ const inTask = (task: number | null, model: string | null = null) =>+ agentOptionsInScope(all, deriveScopeDoc(map, { task, model }));+ const emptyIds = (o: ReturnType<typeof inTask>) =>+ o.filter((a) => a.empty).map((a) => a.id);+ expect(emptyIds(inTask(null))).toEqual(['ghost']);+ expect(emptyIds(inTask(1))).toEqual(['subB', 'ghost']);+ expect(emptyIds(inTask(2))).toEqual(['subA', 'ghost']);+ expect(inTask(1)[1].calls).toBeGreaterThan(0);+ expect(inTask(2)[1].calls).toBe(0);+ expect(inTask(2)[1].cost).toBe(0);+ // a prompt x model pair with nothing in it empties every row+ expect(emptyIds(inTask(1, 'nope'))).toEqual(['main', 'subA', 'subB', 'ghost']);+ });++ it('emptyScopeDescription: names only the active filters', () => {+ const noun = { one: 'Prompt' };+ const d = (task: number | null, model: string | null, sub: string | null) =>+ emptyScopeDescription({ task, model }, sub, noun);+ expect(d(1, null, null)).toBe(+ 'No events match the selected prompt. Clear a filter above.'+ );+ expect(d(null, 'm', 'a')).toBe(+ 'No events match the selected model and agent. Clear a filter above.'+ );+ expect(d(1, 'm', 'a')).toBe(+ 'No events match the selected prompt, model and agent. Clear a filter above.'+ );+ expect(emptyScopeDescription({ task: 1, model: null }, null, { one: 'Task' })).toBe(+ 'No events match the selected task. Clear a filter above.'+ );+ });+});++describe('fit-viewport side column', () => {+ const tasks = sessionTasks(map).tasks;++ it('detailsTitle', () => {+ const base = {+ inspector: false,+ selected: undefined,+ taskCount: 2,+ noun: { one: 'Prompt' },+ };+ expect(detailsTitle({ ...base, scoped: false })).toBe('Whole session');+ expect(detailsTitle({ ...base, scoped: true })).toBe('Filtered session');+ expect(detailsTitle({ ...base, selected: tasks[1], scoped: true })).toBe(+ 'Prompt 2 of 2'+ );+ expect(+ detailsTitle({+ ...base,+ noun: { one: 'Task' },+ selected: tasks[1],+ scoped: true,+ })+ ).toBe('Task 2 of 2');+ expect(+ detailsTitle({+ ...base,+ inspector: true,+ selected: tasks[1],+ scoped: true,+ })+ ).toBe('Subagent');+ });++ it('promptLine', () => {+ const z = { promptChars: 30, promptImages: 0, promptUrls: 0 };+ expect(promptLine(z)).toBe('30 chars');+ expect(promptLine({ ...z, promptImages: 1, promptUrls: 2 })).toBe(+ '30 chars · 1 image · 2 URLs'+ );+ });++ it('sidebarRailLabel', () => {+ const base = {+ subLabel: null,+ mode: 'session' as const,+ sessionId: 'local:claude-code:abcd1234-5678',+ taskCount: 1,+ noun: { one: 'Prompt', many: 'Prompts' },+ };+ expect(sidebarRailLabel(base)).toBe('abcd1234 · 1 prompt');+ expect(sidebarRailLabel({ ...base, taskCount: 17 })).toBe(+ 'abcd1234 · 17 prompts'+ );+ expect(+ sidebarRailLabel({+ ...base,+ taskCount: 17,+ noun: { one: 'Task', many: 'Tasks' },+ })+ ).toBe('abcd1234 · 17 tasks');+ expect(sidebarRailLabel({ ...base, mode: 'list' })).toBe('Sessions');+ expect(sidebarRailLabel({ ...base, subLabel: 'Sub 2: Explore' })).toBe(+ '↳ Sub 2: Explore'+ );+ });++ it('groupSessionsByDay keeps list order and runs', () => {+ const s = (id: string, startedAt: string, sessionDate?: string) =>+ ({ sessionId: id, startedAt, sessionDate }) as SessionExplorerSession;+ const groups = groupSessionsByDay([+ s('a', '2026-09-23T10:00:00Z'),+ s('b', '2026-09-23T08:00:00Z'),+ s('c', '2026-09-22T23:00:00Z', '2026-09-23'),+ s('d', '2026-09-21T09:00:00Z'),+ ]);+ expect(groups.map((g) => [g.day, g.items.map((i) => i.sessionId)])).toEqual(+ [+ ['2026-09-23', ['a', 'b', 'c']],+ ['2026-09-21', ['d']],+ ]+ );+ });+});++describe('event categories', () => {+ const m = makeMap([+ { kind: 'user', chars: 40 }, // 0 prompt+ { kind: 'read', targets: [{ file: 0, touch: 'read' }] }, // 1 explore+ { kind: 'exec', err: true }, // 2 tool + error+ { kind: 'delay', ms: 90_000 }, // 3 delay+ { kind: 'commit', sha: 'abc1234' }, // 4 out+ { kind: 'compaction', preTokens: 9, postTokens: 1 }, // 5 delay+ { kind: 'error', source: 'llm', err: true }, // 6 error+ { kind: 'edit', vcs: { provider: 'github', action: 'pr_create' } }, // 7 out + edit+ { kind: 'user', chars: 5 }, // 8 prompt+ { kind: 'mcp', server: 'linear', tool: 'get_issue', err: true }, // 9 mcp + error+ { kind: 'skill', name: 'deploy' }, // 10 skill+ { kind: 'llm', model: 'opus-5.5', cost: 0.4, in: 900, out: 100 }, // 11 model, cost, tokens+ { kind: 'llm', model: 'opus-5.5', cost: 0 }, // 12 model only+ { kind: 'model_switch', from: 'opus-5.5', to: 'sonnet-5' }, // 13 model+ { kind: 'search' }, // 14 explore+ { kind: 'web' }, // 15 tool+ { kind: 'subagent', child: 'subA', subagentType: 'Explore' }, // 16 tool+ { kind: 'edit', targets: [{ file: 1, touch: 'edit' }] }, // 17 edit+ { kind: 'exec', cat: 'mcp' }, // 18 mcp by category+ ]);+ const ev = m.events;++ it('gives every event one primary category', () => {+ expect(ev.map(categoryOf)).toEqual([+ 'prompt',+ 'explore',+ 'tool',+ 'delay',+ 'out',+ 'delay',+ 'error',+ 'out',+ 'prompt',+ 'mcp',+ 'skill',+ 'model',+ 'model',+ 'model',+ 'explore',+ 'tool',+ 'tool',+ 'edit',+ 'mcp',+ ]);+ });++ it('lets one event belong to several categories', () => {+ const cats = (i: number) =>+ CATEGORIES.filter((c) => categoryMatches(ev[i], c));+ expect(cats(2)).toEqual(['error', 'tool']);+ expect(cats(7)).toEqual(['out', 'edit']);+ expect(cats(9)).toEqual(['error', 'mcp']);+ expect(cats(11)).toEqual(['model', 'cost', 'tokens']);+ expect(cats(12)).toEqual(['model']);+ expect(cats(18)).toEqual(['mcp']);+ expect(cats(16)).toEqual(['tool']);+ });++ it('colours by the first selected category an event is in', () => {+ const errors = new Set<Category>(['error']);+ expect(displayCategory(ev[9], errors)).toBe('error');+ expect(displayCategory(ev[9], new Set(['mcp']))).toBe('mcp');+ expect(displayCategory(ev[9], new Set(['prompt']))).toBe('mcp');+ expect(displayCategory(ev[11], new Set(['cost']))).toBe('cost');+ });++ it('counts a PR-opening exec as an Output, not also as Tools', () => {+ const [prOpen, plainExec] = makeMap([+ { kind: 'exec', vcs: { provider: 'github', action: 'pr_create' } },+ { kind: 'exec' },+ ]).events;+ expect(categoryMatches(prOpen, 'out')).toBe(true);+ expect(categoryMatches(prOpen, 'tool')).toBe(false);+ expect(categoryMatches(plainExec, 'tool')).toBe(true);+ });++ it('starts on Prompts + Errors, and knows when a selection narrows', () => {+ expect([...DEFAULT_CATEGORIES]).toEqual(['prompt', 'error']);+ expect(isDefaultCategories(new Set(DEFAULT_CATEGORIES))).toBe(true);+ expect(narrowsView(new Set(DEFAULT_CATEGORIES))).toBe(false);+ expect(narrowsView(new Set(CATEGORIES))).toBe(false);+ expect(narrowsView(new Set(['edit']))).toBe(true);+ // An empty selection is "no filter active" (every chip deselected),+ // the same as picking every chip -- not "filter to nothing". ev=none+ // round-trips it through the URL as exactly that.+ expect(narrowsView(new Set())).toBe(false);+ });++ it('lists indices by category in time order, optionally lens-limited', () => {+ expect(categoryIndices(ev, 'prompt')).toEqual([0, 8]);+ expect(categoryIndices(ev, 'delay')).toEqual([3, 5]);+ expect(categoryIndices(ev, 'out')).toEqual([4, 7]);+ expect(categoryIndices(ev, 'error')).toEqual([2, 6, 9]);+ expect(categoryIndices(ev, 'edit', (i) => i > 10)).toEqual([17]);+ });++ it('toggles a category without mutating the set, allowing an empty set', () => {+ const on = new Set<Category>(['prompt']);+ const off = toggleCategory(on, 'prompt');+ expect([...off]).toEqual([]);+ expect([...on]).toEqual(['prompt']);+ expect([...toggleCategory(off, 'delay')]).toEqual(['delay']);+ });++ it('knows the last chip clicked, not the last in CATEGORIES order', () => {+ const base = new Set<Category>(['prompt', 'error']);+ // click MCP, then Errors off and on again: Errors is the latest pick,+ // though the URL rebuilds the Set as prompt, error, mcp+ let h = pickHistory(+ [],+ base,+ new Set<Category>(['prompt', 'error', 'mcp'])+ );+ h = pickHistory(+ h,+ new Set<Category>(['prompt', 'error', 'mcp']),+ new Set<Category>(['prompt', 'mcp'])+ );+ const now = new Set<Category>(['prompt', 'error', 'mcp']);+ h = pickHistory(h, new Set<Category>(['prompt', 'mcp']), now);+ expect(h).toEqual(['mcp', 'error']);+ expect(lastPicked(h, now)).toBe('error');+ // Tools clicked last: an eligible-only lookup keeps the previous pick+ const withTools = new Set<Category>([...now, 'tool']);+ const h2 = pickHistory(h, now, withTools);+ expect(lastPicked(h2, withTools)).toBe('tool');+ expect(lastPicked(h2, withTools, ['error', 'mcp', 'skill', 'model'])).toBe(+ 'error'+ );+ // nothing clicked yet (URL / default): CATEGORIES order stands in+ expect(lastPicked([], base, ['error', 'mcp'])).toBe('error');+ expect(lastPicked([], new Set(), ['error'])).toBeNull();+ });++ it('sizes marks by Cost, else Tokens (Cost wins when both are on)', () => {+ expect(sizeMetric(new Set(['cost', 'tokens']))).toBe('cost');+ expect(sizeMetric(new Set(['tokens', 'model']))).toBe('tokens');+ expect(sizeMetric(new Set(['model']))).toBeNull();+ // square-root scaled, floored for anything above zero, capped at 1+ expect(magnitude(1, 1)).toBe(1);+ expect(magnitude(0.25, 1)).toBeCloseTo(0.5);+ expect(magnitude(0.0001, 1)).toBe(0.12);+ expect(magnitude(0, 1)).toBe(0);+ expect(magnitude(5, 1)).toBe(1);+ expect(magnitude(1, 0)).toBe(0);+ expect(magnitude(Number.NaN, 1)).toBe(0);+ });+});++describe('event categories: URL', () => {+ it('parses ev=, drops junk, and round-trips', () => {+ expect([...parseCategories(null)]).toEqual(DEFAULT_CATEGORIES);+ expect([...parseCategories('edit,bogus,mcp')]).toEqual(['edit', 'mcp']);+ expect([...parseCategories('none')]).toEqual([]);+ expect([...parseCategories('toString')]).toEqual(DEFAULT_CATEGORIES);+ const s = new Set<Category>(['cost', 'edit']);+ expect(serializeCategories(s)).toBe('edit,cost');+ expect(parseCategories(serializeCategories(s))).toEqual(s);+ expect(serializeCategories(new Set(DEFAULT_CATEGORIES))).toBeNull();+ expect(serializeCategories(new Set())).toBe('none');+ });+});++describe('event categories: map focus', () => {+ const m = makeMap([+ { kind: 'user' }, // 0+ { kind: 'read', targets: [{ file: 0, touch: 'read' }] }, // 1+ { kind: 'edit', targets: [{ file: 1, touch: 'edit' }] }, // 2+ { kind: 'delay', ms: 5000 }, // 3+ ]);+ const tree = buildTree(m);+ const refs = eventNodeRefs(m, tree);+ const fileNode = (f: number) =>+ [...tree.byId.values()].find((n) => n.id === `file:${f}`);++ it('is off for the default and the full selection', () => {+ expect(+ mapFocus(tree, refs, m.events, new Set(DEFAULT_CATEGORIES))+ ).toBeNull();+ expect(mapFocus(tree, refs, m.events, new Set(CATEGORIES))).toBeNull();+ });++ it('lights the touched nodes and their branch only', () => {+ const f = mapFocus(tree, refs, m.events, new Set(['edit']));+ expect(f).not.toBeNull();+ expect(f?.has(fileNode(1)?.id ?? '')).toBe(true);+ expect(f?.has(fileNode(0)?.id ?? '')).toBe(false);+ expect(f?.has('root')).toBe(true);+ const x = mapFocus(tree, refs, m.events, new Set(['explore']));+ expect(x?.has(fileNode(0)?.id ?? '')).toBe(true);+ expect(x?.has(fileNode(1)?.id ?? '')).toBe(false);+ });++ it('stays off when nothing selected touches the map', () => {+ expect(mapFocus(tree, refs, m.events, new Set(['delay']))).toBeNull();+ });++ it('pathFocus lights only the cited steps and their branch', () => {+ const f = pathFocus(tree, refs, m.events, [2]);+ expect(f?.has(fileNode(1)?.id ?? '')).toBe(true);+ expect(f?.has(fileNode(0)?.id ?? '')).toBe(false);+ expect(f?.has('root')).toBe(true);+ });++ it('pathFocus reads seq, not the index into events', () => {+ // Events dropped by a scope shift every index; `seq` survives that, and+ // a comment cites `seq`.+ const scoped = { ...m, events: m.events.slice(2) };+ const scopedRefs = eventNodeRefs(scoped, tree);+ const f = pathFocus(tree, scopedRefs, scoped.events, [2]);+ expect(f?.has(fileNode(1)?.id ?? '')).toBe(true);+ });++ it('pathFocus is null when no cited step is in this scope', () => {+ expect(pathFocus(tree, refs, m.events, [99])).toBeNull();+ expect(pathFocus(tree, refs, m.events, [])).toBeNull();+ // A step with no map node of its own (a delay) dims nothing.+ expect(pathFocus(tree, refs, m.events, [3])).toBeNull();+ });++ // The chips narrow the map twice. `pathFocus` winning the+ // focus set is not enough, because `activeRefs` blanks the refs of every+ // event outside the selection, and that is what the active dots and the+ // labels are built from. A path step in an unchecked category went dark.+ it('a lit path survives a chip selection that excludes its steps', () => {+ const chips = new Set<Category>(['edit']); // Exploration unchecked+ const step = 1; // ...and step #1 is a Read+ expect(categoryOf(m.events[step])).toBe('explore');++ // The focus set lights it either way.+ expect(+ pathFocus(tree, refs, m.events, [step])?.has(fileNode(0)?.id ?? '')+ ).toBe(true);++ // But the refs the map draws from do not, while the chips still narrow.+ expect(activeRefs(refs, m.events, chips)[step]).toEqual([]);++ // With a path lit, the chips are suspended and the whole path is drawn.+ const lit = activeRefs(refs, m.events, mapChipSelection(chips, true));+ expect(lit[step]).toEqual(refs[step]);+ expect(lit[2]).toEqual(refs[2]); // the Edit the chips did select, still on++ // With no path lit, the chips narrow exactly as before.+ expect(activeRefs(refs, m.events, mapChipSelection(chips, false))).toEqual(+ activeRefs(refs, m.events, chips)+ );+ });+});++/**+ * A scope reindexes `seq` over the events it kept, so a+ * causal path cited against the full session either found nothing or -- worse+ * -- found whatever event had landed on that number and lit unrelated nodes.+ */+describe('map focus: a causal path under a scope', () => {+ // file 0 is src/proxy.ts, file 1 is src/app.ts.+ const full = makeMap([+ { kind: 'user' }, // 0, task 1+ { kind: 'edit', targets: [{ file: 1, touch: 'edit' }] }, // 1, task 1+ { kind: 'user' }, // 2, task 2+ { kind: 'edit', targets: [{ file: 0, touch: 'edit' }] }, // 3, task 2+ { kind: 'edit', targets: [{ file: 1, touch: 'edit' }] }, // 4, task 2+ ]);+ const scoped = deriveScopeDoc(full, { task: 2, model: null });+ const tree = buildTree(scoped);+ const refs = eventNodeRefs(scoped, tree);+ const node = (f: number) =>+ [...tree.byId.values()].find((n) => n.id === `file:${f}`)?.id ?? '';++ it('renumbers seq but keeps the full session\'s number on srcSeq', () => {+ expect(scoped.events.map((e) => e.seq)).toEqual([0, 1, 2]);+ expect(scoped.events.map(srcSeqOf)).toEqual([2, 3, 4]);+ });++ it('lights the cited step, not the one now sitting on that number', () => {+ // #4 edits src/app.ts. It is the scoped map's event 2, whose renumbered+ // `seq` is 2 -- and the event that now holds seq 1 edits src/proxy.ts.+ const f = pathFocus(tree, refs, scoped.events, [4]);+ expect(f?.has(node(1))).toBe(true);+ expect(f?.has(node(0))).toBe(false);+ });++ it('lights nothing for a step the scope dropped', () => {+ // #1 edits src/app.ts but belongs to task 1. Read against the renumbered+ // `seq` it would have lit src/proxy.ts, which it never touched.+ expect(pathFocus(tree, refs, scoped.events, [1])).toBeNull();+ });++ it('is unchanged on the unscoped map', () => {+ const fullTree = buildTree(full);+ const fullRefs = eventNodeRefs(full, fullTree);+ const f = pathFocus(fullTree, fullRefs, full.events, [4]);+ expect(f?.has(node(1))).toBe(true);+ expect(f?.has(node(0))).toBe(false);+ });+});++describe('event categories: activeRefs', () => {+ it('is a no-op (same reference) when the selection does not narrow', () => {+ const refs: NodeRef[][] = [[{ id: 'a' }], [{ id: 'b' }]];+ const events = [{ kind: 'edit' }, { kind: 'mcp' }] as SessionMapEvent[];+ expect(activeRefs(refs, events, new Set(DEFAULT_CATEGORIES))).toBe(refs);+ expect(activeRefs(refs, events, new Set(CATEGORIES))).toBe(refs);+ });++ it('blanks refs for events outside the selection', () => {+ const refs: NodeRef[][] = [[{ id: 'a' }], [{ id: 'b' }], [{ id: 'c' }]];+ const events = [+ { kind: 'edit' },+ { kind: 'mcp' },+ { kind: 'read' },+ ] as SessionMapEvent[];+ const scoped = activeRefs(refs, events, new Set(['edit', 'explore']));+ expect(scoped).toEqual([[{ id: 'a' }], [], [{ id: 'c' }]]);+ });++ it("makes a kept event's passive refs active (the model under Model / Cost / Tokens)", () => {+ const model = { id: 'model:opus', passive: true };+ const refs: NodeRef[][] = [[model], [{ id: 'file:0' }]];+ const events = [+ { kind: 'llm', model: 'opus', in: 10, out: 5, cost: 0.2 },+ { kind: 'edit' },+ ] as SessionMapEvent[];+ const scoped = activeRefs(refs, events, new Set(['tokens']));+ expect(scoped).toEqual([[{ id: 'model:opus', passive: false }], []]);+ // the caller's refs are not mutated+ expect(refs[0][0].passive).toBe(true);+ expect(activeSet(scoped, 1, 20).has('model:opus')).toBe(true);+ });++ it("keeps a matched event's passive model ref passive outside Model / Cost / Tokens", () => {+ // An errored LLM, selected only through Errors: it wasn't the model the+ // user asked to see, just incidental to the error that was.+ const model = { id: 'model:opus', passive: true };+ const errClass = { id: 'errc:llm/timeout' };+ const refs: NodeRef[][] = [[model, errClass]];+ const events = [+ { kind: 'llm', model: 'opus', err: true, cost: 0.2 },+ ] as SessionMapEvent[];+ // a fresh literal, not `model` itself: an `activeRefs` regressed to+ // mutating its input would make `model` and the expected value the+ // same already-mutated object, and this assertion would pass either way+ expect(activeRefs(refs, events, new Set(['error']))).toEqual([+ [{ id: 'model:opus', passive: true }, errClass],+ ]);+ expect(model.passive).toBe(true);+ // the same event, with Model also selected: now it activates+ expect(activeRefs(refs, events, new Set(['error', 'model']))).toEqual([+ [{ id: 'model:opus', passive: false }, errClass],+ ]);+ });++ it("a burst of unselected activity doesn't crowd a selected touch out of the recent-N window", () => {+ // The bug: with Edits selected, 25 unrelated+ // MCP calls right before the playhead pushed the one edited file out+ // of activeSet's recent-20 budget, so its label never showed and+ // stopped tracking the playhead. Scoping refs by the selection first+ // means only matching touches consume that budget.+ const events: SessionMapEvent[] = [+ {+ kind: 'edit',+ targets: [{ file: 0, touch: 'edit' }],+ } as SessionMapEvent,+ // 25 DISTINCT mcp targets -- identical calls collapse to one node in+ // activeSet's distinct-id budget, so only distinct ones can crowd it.+ ...Array.from(+ { length: 25 },+ (_, i) =>+ ({ kind: 'mcp', server: 's', tool: `t${i}` }) as SessionMapEvent+ ),+ ];+ const m = makeMap(events);+ const tree = buildTree(m);+ const refs = eventNodeRefs(m, tree);+ const p = refs.length - 1;+ const selected = new Set<Category>(['edit']);++ const editedId = [...tree.byId.values()].find((n) => n.id === 'file:0')?.id;+ expect(editedId).toBeDefined();++ expect(activeSet(refs, p, 20).has(editedId!)).toBe(false); // the bug+ const scoped = activeRefs(refs, m.events, selected);+ expect(activeSet(scoped, p, 20).has(editedId!)).toBe(true); // the fix+ });+});++describe('timeline dock: stepping', () => {+ const list = [2, 5, 9];++ it('steps from the pinned event, clamped at both ends', () => {+ expect(stepEvent(list, 5, 0, 1)).toBe(9);+ expect(stepEvent(list, 5, 0, -1)).toBe(2);+ expect(stepEvent(list, 9, 0, 1)).toBe(9);+ expect(stepEvent(list, 2, 0, -1)).toBe(2);+ });++ it('with nothing pinned, steps from the playhead and wraps', () => {+ expect(stepEvent(list, null, 5, 1)).toBe(9);+ expect(stepEvent(list, null, 5, -1)).toBe(2);+ expect(stepEvent(list, null, 9, 1)).toBe(2); // past the last: wrap+ expect(stepEvent(list, null, 2, -1)).toBe(9); // before the first: wrap+ // a pin of another type counts as nothing pinned in this list+ expect(stepEvent(list, 4, 4, 1)).toBe(5);+ });++ it('returns null for an empty list', () => {+ expect(stepEvent([], null, 3, 1)).toBeNull();+ expect(stepEvent([], 3, 3, -1)).toBeNull();+ });++ it('reports k/N only while the pinned event is in the list', () => {+ expect(stepPosition(list, 5)).toBe('2/3');+ expect(stepPosition(list, 4)).toBeNull();+ expect(stepPosition(list, null)).toBeNull();+ });+});++describe('timeline dock: subagent rows', () => {+ it('keeps the start order and labels rows "n · type"', () => {+ const m = makeMap(EVENTS);+ const subs = orderedSubagents(m, subagentOrdinal(m));+ const rows = subagentLanes(subs, m.events);+ expect(rows.map((r) => r.id)).toEqual(subs.map((s) => s.id));+ expect(rows[0].label).toBe(`1 · ${subs[0].type}`);+ // a subagent with no events in the timeline's map gets no row+ const onlyMain = m.events.filter((e) => e.agent === 'main');+ expect(subagentLanes(subs, onlyMain)).toEqual([]);+ });+});++describe('timeline dock: height', () => {+ it('clamps a dragged height to [min, 72% of the explorer]', () => {+ expect(clampDockHeight(50, 900)).toBe(DOCK_MIN_HEIGHT);+ expect(clampDockHeight(300.4, 900)).toBe(300);+ expect(clampDockHeight(2000, 900)).toBe(648);+ // a tiny explorer never clamps below the minimum+ expect(clampDockHeight(300, 100)).toBe(DOCK_MIN_HEIGHT);+ });++ it("measures the optional lanes' height over the always-on ones", () => {+ const all = new Set(['tasks', 'events', 'ctx', 'main', 'subs'] as const);+ const subs = [+ { id: 'a', label: '1 · fork' },+ { id: 'b', label: '2 · fork' },+ ];+ // Context 32+4, Subagents 16+4, and each expanded row 12+2+ expect(optionalLanesHeight(all, subs, true)).toBe(84);+ expect(optionalLanesHeight(all, subs, false)).toBe(56);+ expect(+ optionalLanesHeight(+ new Set(['tasks', 'events', 'main'] as const),+ subs,+ true+ )+ ).toBe(0);+ });++ it('extends the page by what the optional lanes add past any dragged floor', () => {+ // no floor: all of it (so the map keeps its size)+ expect(dockOverflow(300, 84, null)).toBe(84);+ // a floor under the base height reserves nothing+ expect(dockOverflow(300, 84, 176)).toBe(84);+ // a floor that already covers part of the lanes+ expect(dockOverflow(300, 84, 280)).toBe(20);+ // a floor taller than every lane: the dock never grows+ expect(dockOverflow(320, 84, 320)).toBe(0);+ expect(dockOverflow(216, 0, null)).toBe(0);+ });++ it('persists through guarded storage; junk and resets read as null', () => {+ const mem = new Map<string, string>();+ const storage = {+ getItem: (k: string) => mem.get(k) ?? null,+ setItem: (k: string, v: string) => void mem.set(k, v),+ };+ expect(readDockHeight(storage)).toBeNull();+ writeDockHeight(260, storage);+ expect(mem.get(DOCK_HEIGHT_KEY)).toBe('260');+ expect(readDockHeight(storage)).toBe(260);+ writeDockHeight(null, storage);+ expect(readDockHeight(storage)).toBeNull();+ mem.set(DOCK_HEIGHT_KEY, 'tall');+ expect(readDockHeight(storage)).toBeNull();+ mem.set(DOCK_HEIGHT_KEY, '12');+ expect(readDockHeight(storage)).toBeNull(); // under the minimum+ const broken = {+ getItem: () => {+ throw new Error('blocked');+ },+ setItem: () => {+ throw new Error('blocked');+ },+ };+ expect(readDockHeight(broken)).toBeNull();+ expect(() => writeDockHeight(300, broken)).not.toThrow();+ expect(readDockHeight(null)).toBeNull();+ });++ it('notifies subscribers; a mid-drag set is not persisted', () => {+ let calls = 0;+ const unsub = subscribeDockHeight(() => {+ calls += 1;+ });+ // An in-memory storage (this env's jsdom localStorage isn't usable).+ const store = new Map<string, string>([[DOCK_HEIGHT_KEY, '240']]);+ vi.stubGlobal('localStorage', {+ getItem: (k: string) => store.get(k) ?? null,+ setItem: (k: string, v: string) => void store.set(k, v),+ removeItem: (k: string) => void store.delete(k),+ });+ setDockHeight(300, false);+ expect(getDockHeight()).toBe(300);+ // mid-drag: memory moves, storage keeps the last persisted height+ expect(store.get(DOCK_HEIGHT_KEY)).toBe('240');+ vi.unstubAllGlobals();+ setDockHeight(null);+ expect(getDockHeight()).toBeNull();+ expect(calls).toBe(2);+ unsub();+ setDockHeight(320);+ expect(calls).toBe(2);+ setDockHeight(null);+ });+});++describe('sessionErrors for failed hooks', () => {+ const hook = (seq: number, name: string, errClass = 'hook_error'): RawEvent => ({+ kind: 'error', seq, t: seq, err: true, source: 'hook', errClass, hook: name,+ });++ it('names each hook in its group and in the burst label', () => {+ const { groups } = sessionErrors(+ makeMap([+ hook(0, 'PostToolUse:Bash'),+ hook(1, 'PostToolUse:Bash'),+ hook(2, 'PostToolUse:Bash'),+ hook(3, 'Stop', 'hook_blocking'),+ ])+ );+ expect(groups.map((g) => g.label).sort()).toEqual([+ 'PostToolUse:Bash hook error',+ 'Stop hook blocked',+ ]);+ const post = groups.find((g) => g.label === 'PostToolUse:Bash hook error');+ expect(post?.errors).toHaveLength(3);+ expect(post?.errors[0].label).toBe('PostToolUse:Bash hook error');+ expect(post?.worstRun).toBe(3);+ expect(post?.worstRunLabel).toBe('PostToolUse:Bash hook error');+ });+});diff --git a/viewer/src/core/sessionLayout.ts b/viewer/src/core/sessionLayout.tsnew file mode 100644index 0000000..fc3ca5c--- /dev/null+++ b/viewer/src/core/sessionLayout.ts@@ -0,0 +1,1488 @@+/**+ * Pure helpers behind the Session Explorer layout: the one sidebar+ * (tasks / subagents / insights), the subagent view, and the one-line+ * task/subagent strip above the timeline. Kept free of React so every rule+ * here is unit-tested (sessionLayout.test.ts).+ */+import type {+ SessionExplorerSession,+ SessionMap,+ SessionMapEvent,+ SessionMapPr,+} from './schema';+import {+ NON_CALL,+ agentLabel,+ ancestorsOf,+ catLabel,+ clockAt,+ errClassLabel,+ errClassOf,+ fmtDur,+ fmtTok,+ fmtUsd,+ hookErrorTitle,+ isOutputEvent,+ llmTokens,+ outputTotals,+ srcSeqOf,+ stateAt,+ type NodeRef,+ type NodeType,+ type OutputTotals,+ type SessionTree,+} from './sessionMapModel';+import {+ hasReplayEvents,+ summarizeEvents,+ taskNoun,+ type Scope,+ type TaskSummary,+ type TaskWindow,+} from './sessionScope';++// --- windows -----------------------------------------------------------------++/** An inclusive event-index window. */+export interface IndexWindow {+ start: number;+ end: number;+}++/** First and last index of the events that pass `test`, or null. */+export function indexWindow(+ events: readonly SessionMapEvent[],+ test: (e: SessionMapEvent) => boolean+): IndexWindow | null {+ let start = -1;+ let end = -1;+ events.forEach((e, i) => {+ if (!test(e)) return;+ if (start < 0) start = i;+ end = i;+ });+ return start < 0 ? null : { start, end };+}++/** The [first, last] event window a subagent ran in. */+export const agentWindow = (+ events: readonly SessionMapEvent[],+ agentId: string+): IndexWindow | null => indexWindow(events, (e) => e.agent === agentId);++/** The [first, last] event window of task `n` (events must be task-stamped). */+export const taskIndexWindow = (+ events: readonly SessionMapEvent[],+ n: number+): IndexWindow | null => indexWindow(events, (e) => e.task === n);++/** For every event of `agentId` (in order), its index in `events`: the map+ * from a lensed (subagent-only) replay back onto the whole session. */+export function lensSourceIndex(+ events: readonly SessionMapEvent[],+ agentId: string+): number[] {+ const out: number[] = [];+ events.forEach((e, i) => {+ if (e.agent === agentId) out.push(i);+ });+ return out;+}++/** The lens index whose source index is nearest `fullIndex` (ties go to the+ * earlier one). `src` is ascending; returns 0 for an empty map. */+export function nearestLensIndex(src: readonly number[], fullIndex: number) {+ if (!src.length) return 0;+ let lo = 0;+ let hi = src.length - 1;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (src[mid] < fullIndex) lo = mid + 1;+ else hi = mid;+ }+ if (lo > 0 && fullIndex - src[lo - 1] <= src[lo] - fullIndex) return lo - 1;+ return lo;+}++/** 0..1 position of the playhead inside a window (clamped). */+export function windowProgress(w: IndexWindow | null, p: number): number {+ if (!w) return 0;+ if (w.end <= w.start) return p >= w.end ? 1 : 0;+ return Math.max(0, Math.min(1, (p - w.start) / (w.end - w.start)));+}++// --- tasks -------------------------------------------------------------------++/** The task under the playhead, from the event's task stamp. */+export function taskAt(+ events: readonly SessionMapEvent[],+ p: number+): number | null {+ const t = events[p]?.task;+ return typeof t === 'number' && t > 0 ? t : null;+}++/** The task `delta` steps from `n` (clamped to the list); with no current+ * task, stepping forward starts at the first and back at the last. */+export function adjacentTask(+ tasks: readonly TaskWindow[],+ n: number | null,+ delta: number+): number | null {+ if (!tasks.length) return null;+ const i = n == null ? -1 : tasks.findIndex((t) => t.n === n);+ if (i < 0) return (delta >= 0 ? tasks[0] : tasks[tasks.length - 1]).n;+ const j = Math.max(0, Math.min(tasks.length - 1, i + delta));+ return tasks[j].n;+}++/** Per-task summaries in one pass (events must be task-stamped). */+export function taskSummaries(map: SessionMap): Map<number, TaskSummary> {+ const byTask = new Map<number, SessionMapEvent[]>();+ for (const e of map.events) {+ if (typeof e.task !== 'number') continue;+ const list = byTask.get(e.task);+ if (list) list.push(e);+ else byTask.set(e.task, [e]);+ }+ const out = new Map<number, TaskSummary>();+ for (const [n, events] of byTask)+ out.set(+ n,+ summarizeEvents(+ events,+ events.map((e) => e.model ?? '')+ )+ );+ return out;+}++/** "HH:MM–HH:MM" of a span that starts `startT` ms into the session. */+export const spanLabel = (+ sessionStart: string,+ startT: number,+ endT: number+): string =>+ `${clockAt(sessionStart, startT).slice(0, 5)}–${clockAt(sessionStart, endT).slice(0, 5)}`;++/** "$1.23", or "cost n/a" when nothing in the span was priced. */+export const costLabel = (cost: number): string =>+ cost > 0 ? fmtUsd(cost) : 'cost n/a';++const plural = (n: number, one: string, many = `${one}s`) =>+ `${n} ${n === 1 ? one : many}`;++/** Short "2 commits · 1 PR merged" line of the non-zero outputs. */+export function outputsLine(o: OutputTotals, prsCreated = 0): string {+ const parts: string[] = [];+ if (prsCreated) parts.push(plural(prsCreated, 'PR created', 'PRs created'));+ if (o.prsMerged) parts.push(plural(o.prsMerged, 'PR merged', 'PRs merged'));+ if (o.prsClosed) parts.push(`${o.prsClosed} closed unmerged`);+ if (o.prComments) parts.push(plural(o.prComments, 'PR comment'));+ if (o.commits) parts.push(plural(o.commits, 'commit'));+ if (o.ticketsCreated) parts.push(plural(o.ticketsCreated, 'ticket'));+ if (o.ticketsUpdated) parts.push(`${o.ticketsUpdated} ticket updates`);+ if (o.artifacts) parts.push(plural(o.artifacts, 'artifact'));+ if (o.skillsCreated + o.skillsUpdated)+ parts.push(plural(o.skillsCreated + o.skillsUpdated, 'skill write'));+ return parts.join(' · ');+}++// --- subagents ---------------------------------------------------------------++export interface SubagentInfo {+ id: string;+ /** 1-based position in the ordered list */+ index: number;+ label: string;+ type: string;+ window: IndexWindow;+ /** ms since session start */+ startT: number;+ endT: number;+ calls: number;+ requests: number;+ cost: number;+ tokens: number;+ /** the task the subagent was spawned in (spawn event, else first event) */+ parentTask: number | null;+}++/**+ * Every subagent that ran in the session, in the order it started, with its+ * window, totals and parent task. `map` is the whole (task-stamped) session+ * map; subagents with no events in it are skipped.+ */+export function orderedSubagents(+ map: SessionMap,+ ordinals: Map<string, number>+): SubagentInfo[] {+ const byAgent = new Map<string, number[]>();+ map.events.forEach((e, i) => {+ if (!e.agent || e.agent === 'main') return;+ const list = byAgent.get(e.agent);+ if (list) list.push(i);+ else byAgent.set(e.agent, [i]);+ });+ const spawnTask = new Map<string, number>();+ for (const e of map.events)+ if (e.kind === 'subagent' && e.child && typeof e.task === 'number')+ if (!spawnTask.has(e.child)) spawnTask.set(e.child, e.task);+ const rows: Omit<SubagentInfo, 'index'>[] = [];+ for (const a of map.agents) {+ if (a.id === 'main') continue;+ const idx = byAgent.get(a.id);+ if (!idx?.length) continue;+ const events = idx.map((i) => map.events[i]);+ const s = summarizeEvents(+ events,+ events.map((e) => e.model ?? '')+ );+ const first = events[0];+ const last = events[events.length - 1];+ rows.push({+ id: a.id,+ label: agentLabel(map, a.id, ordinals),+ type: a.subagentType || 'subagent',+ window: { start: idx[0], end: idx[idx.length - 1] },+ startT: first.t,+ endT: last.t,+ calls: s.calls,+ requests: s.requests,+ cost: s.cost,+ tokens: s.tokens,+ parentTask:+ spawnTask.get(a.id) ??+ (typeof first.task === 'number' ? first.task : null),+ });+ }+ rows.sort(+ (x, y) =>+ x.window.start - y.window.start ||+ (ordinals.get(x.id) ?? 0) - (ordinals.get(y.id) ?? 0)+ );+ return rows.map((r, i) => ({ ...r, index: i + 1 }));+}++/** The subagent `delta` steps from `id` in the ordered list, or null at+ * either end. */+export function adjacentSubagent(+ subs: readonly SubagentInfo[],+ id: string,+ delta: number+): string | null {+ const i = subs.findIndex((s) => s.id === id);+ if (i < 0) return null;+ return subs[i + delta]?.id ?? null;+}++// --- touched-by-helper list -----------------------------------------------------++export interface TouchedItem {+ id: string;+ name: string;+ type: NodeType;+ count: number;+}++export interface TouchedGroup {+ id: string;+ name: string;+ items: TouchedItem[];+}++/**+ * Leaves the replay touched, grouped under their top-level map group (a repo,+ * "Outside repo", "Subagents", ...), each group and its items sorted by+ * touch count. Model nodes are left out: every request lights one.+ */+export function touchedGroups(+ tree: SessionTree,+ refs: NodeRef[][]+): TouchedGroup[] {+ const st = stateAt(refs, refs.length - 1);+ const groups = new Map<string, TouchedGroup & { total: number }>();+ for (const leaf of tree.leaves) {+ if (leaf.type === 'model' || leaf.type === 'root') continue;+ const cnt = st.get(leaf.id)?.cnt ?? 0;+ if (!cnt) continue;+ let top = leaf;+ while (top.parent && top.parent.type !== 'root') top = top.parent;+ let g = groups.get(top.id);+ if (!g) {+ g = { id: top.id, name: top.name, items: [], total: 0 };+ groups.set(top.id, g);+ }+ g.items.push({ id: leaf.id, name: leaf.name, type: leaf.type, count: cnt });+ g.total += cnt;+ }+ return [...groups.values()]+ .sort((a, b) => b.total - a.total)+ .map(({ id, name, items }) => ({+ id,+ name,+ items: items.sort((a, b) => b.count - a.count),+ }));+}++// --- the one-line strip ----------------------------------------------------------++export type StripState =+ | { kind: 'sub'; id: string; playing: boolean }+ | {+ kind: 'task';+ n: number;+ playing: boolean;+ /** no task is selected: the strip follows the task under the playhead */+ followsPlayhead: boolean;+ }+ | null;++/**+ * When the strip above the timeline shows, and what: an open subagent or a+ * selected task shows while the sidebar is collapsed or playback runs; while+ * playing with no task selected it follows the task under the playhead (only+ * when the session has more than one task).+ */+export function stripState(s: {+ task: number | null;+ sub: string | null;+ collapsed: boolean;+ playing: boolean;+ playheadTask: number | null;+ taskCount: number;+}): StripState {+ const visible = s.collapsed || s.playing;+ if (s.sub != null)+ return visible ? { kind: 'sub', id: s.sub, playing: s.playing } : null;+ if (s.task != null)+ return visible+ ? { kind: 'task', n: s.task, playing: s.playing, followsPlayhead: false }+ : null;+ if (s.playing && s.playheadTask != null && s.taskCount > 1)+ return {+ kind: 'task',+ n: s.playheadTask,+ playing: true,+ followsPlayhead: true,+ };+ return null;+}++// --- sidebar -------------------------------------------------------------------++export type SidebarTab = 'tasks' | 'errors' | 'subagents' | 'insights';+export const SIDEBAR_TABS: readonly SidebarTab[] = [+ 'tasks',+ 'errors',+ 'subagents',+ 'insights',+];++/** Tabs a session's sidebar shows: Tasks only with more than one task,+ * Errors and Subagents only when it has any; Insights always. */+export function sidebarTabs(+ taskCount: number,+ subCount: number,+ errorCount = 0+): SidebarTab[] {+ const out: SidebarTab[] = [];+ if (taskCount > 1) out.push('tasks');+ if (errorCount > 0) out.push('errors');+ if (subCount > 0) out.push('subagents');+ out.push('insights');+ return out;+}++/** The tab to show: the requested one when it is available, else the first. */+export const resolveSidebarTab = (+ want: SidebarTab | null,+ available: readonly SidebarTab[]+): SidebarTab =>+ want && available.includes(want) ? want : (available[0] ?? 'insights');++export const SIDEBAR_COLLAPSED_KEY = 'session-explorer:sidebar-collapsed';++type MaybeStorage = Pick<Storage, 'getItem' | 'setItem'> | null | undefined;++const defaultStorage = (): MaybeStorage => {+ try {+ return typeof window === 'undefined' ? null : window.localStorage;+ } catch {+ return null;+ }+};++/** Persisted collapsed state; false whenever storage is missing or throws. */+export function readSidebarCollapsed(+ storage: MaybeStorage = defaultStorage()+): boolean {+ try {+ return storage?.getItem(SIDEBAR_COLLAPSED_KEY) === '1';+ } catch {+ return false;+ }+}++export function writeSidebarCollapsed(+ collapsed: boolean,+ storage: MaybeStorage = defaultStorage()+): void {+ try {+ storage?.setItem(SIDEBAR_COLLAPSED_KEY, collapsed ? '1' : '0');+ } catch {+ // private mode / blocked storage: the state just is not remembered+ }+}++/*+ * `useSyncExternalStore` source for the collapsed state, so the first client+ * render reads it directly instead of flashing the expanded sidebar from a+ * mount-time effect. The in-memory value is this tab's source of truth (so+ * collapsing still works with storage blocked); storage seeds and persists+ * it, and `storage` events keep other tabs in step.+ */+let collapsedMem: boolean | null = null;+const collapsedListeners = new Set<() => void>();++export function getSidebarCollapsed(): boolean {+ if (collapsedMem === null) collapsedMem = readSidebarCollapsed();+ return collapsedMem;+}++/** SSR has no storage: render expanded, React swaps in the client value. */+export function getSidebarCollapsedServer(): boolean {+ return false;+}++export function setSidebarCollapsed(next: boolean): void {+ collapsedMem = next;+ writeSidebarCollapsed(next);+ collapsedListeners.forEach((l) => l());+}++export function subscribeSidebarCollapsed(listener: () => void): () => void {+ collapsedListeners.add(listener);+ const onStorage = (e: StorageEvent) => {+ if (e.key !== SIDEBAR_COLLAPSED_KEY) return;+ collapsedMem = e.newValue === '1';+ listener();+ };+ if (typeof window !== 'undefined')+ window.addEventListener('storage', onStorage);+ return () => {+ collapsedListeners.delete(listener);+ if (typeof window !== 'undefined')+ window.removeEventListener('storage', onStorage);+ };+}++/** "12:00–12:30 · 30m · $1.23 · 4 calls · 1 commit" for a task in the strip. */+export function taskStripMeta(+ startedAt: string,+ t: TaskWindow,+ s: TaskSummary | undefined+): string {+ const parts = [+ spanLabel(startedAt, t.startT, t.endT),+ fmtDur(t.endT - t.startT),+ costLabel(s?.cost ?? 0),+ `${s?.calls ?? 0} calls`,+ ];+ const outs = s ? outputsLine(s.outputs, s.prsCreated) : '';+ if (outs) parts.push(outs);+ return parts.join(' · ');+}++export function subStripMeta(startedAt: string, s: SubagentInfo): string {+ return [+ spanLabel(startedAt, s.startT, s.endT),+ `${s.calls} calls`,+ costLabel(s.cost),+ `${fmtTok(s.tokens)} tokens`,+ ].join(' · ');+}++/**+ * Left/width (0..1) of a subagent's position bar in a clipped 100%-wide+ * track. The minimum width keeps a one-event helper visible; the offset is+ * clamped so that minimum still fits when the helper ran at the very end.+ */+export function spanBarGeometry(+ startT: number,+ endT: number,+ durationMs: number+): { left: number; width: number } {+ const MIN = 0.015;+ const d = Math.max(1, durationMs);+ const width = Math.min(1, Math.max(MIN, (endT - startT) / d));+ const left = Math.max(0, Math.min(1 - width, startT / d));+ return { left, width };+}++// --- fit-viewport layout: compact header, toolbar, side column ---------------++/** One PR in the header's "N PRs" popover. */+export interface PrMenuItem {+ key: string;+ /** `repo #12`, or `#12` when the PR carries no repo */+ label: string;+ provider: string;+ /** null when the map's URL is not http(s): shown as text, never a link */+ url: string | null;+ state: string | null;+}++/** `url` if it is an http(s) URL, else null. A map is untrusted input (any+ * file can be dropped on the page), and a `javascript:` href runs on click. */+export function safeLinkUrl(url: string | null | undefined): string | null {+ if (!url) return null;+ try {+ const { protocol } = new URL(url);+ return protocol === 'https:' || protocol === 'http:' ? url : null;+ } catch {+ return null;+ }+}++/** The session's PRs for the header popover, one row per PR (the first+ * occurrence wins when the map lists a PR twice), in map order. */+export function prMenuItems(prs: readonly SessionMapPr[]): PrMenuItem[] {+ const out = new Map<string, PrMenuItem>();+ for (const pr of prs) {+ const key = `${pr.provider}:${pr.repo ?? ''}:${pr.number}`;+ if (out.has(key)) continue;+ out.set(key, {+ key,+ label: pr.repo ? `${pr.repo} #${pr.number}` : `#${pr.number}`,+ provider: pr.provider,+ url: safeLinkUrl(pr.url),+ state: pr.state ?? null,+ });+ }+ return [...out.values()];+}++/** "1 PR" / "9 PRs": the header's PR popover trigger. */+export const prCountLabel = (n: number): string =>+ n === 1 ? '1 PR' : `${n} PRs`;++/** The one-line outcome: every non-zero output, in the order the old chip row+ * used.+ *+ * The task count is deliberately not here. It was, and on a session that+ * produced nothing it made the callout read "13 tasks" directly under the+ * `Tasks 13` row three lines above -- a brand-tinted box restating its+ * neighbour. With no outputs there is now no callout, which is the honest+ * answer: the session produced nothing. */+export function outcomeParts(map: SessionMap): string[] {+ const o = outputTotals(map.events);+ const items: [number, string, string?][] = [+ [map.totals.prsCreated ?? 0, 'PR created', 'PRs created'],+ [o.prsMerged, 'PR merged', 'PRs merged'],+ [o.prsClosed, 'closed unmerged', 'closed unmerged'],+ [o.prComments, 'PR comment'],+ [o.commits, 'commit'],+ [o.ticketsCreated, 'ticket created', 'tickets created'],+ [o.ticketsUpdated, 'ticket updated', 'tickets updated'],+ [o.artifacts, 'artifact'],+ [o.skillsCreated, 'skill created', 'skills created'],+ [o.skillsUpdated, 'skill updated', 'skills updated'],+ [o.modelSwitches, 'model switch', 'model switches'],+ ];+ return items+ .filter(([n]) => n > 0)+ .map(([n, one, many]) => plural(n, one, many));+}++/** Toolbar trigger text for the task / prompt filter. */+export function taskFilterLabel(+ tasks: readonly TaskWindow[],+ task: number | null+): string {+ const t = task != null ? tasks.find((x) => x.n === task) : undefined;+ return t ? `${t.n} · ${t.name}` : `All ${taskNoun(tasks).many.toLowerCase()}`;+}++/** A task, model or subagent filter is narrowing the replay. */+export const hasScopeFilter = (scope: Scope, sub: string | null): boolean =>+ scope.task != null || scope.model != null || !!sub;++/** Title of the right column's Details card. */+export function detailsTitle(s: {+ inspector: boolean;+ selected: TaskWindow | undefined;+ taskCount: number;+ /** what the windows are called (`taskNoun`) */+ noun: { one: string };+ scoped: boolean;+}): string {+ if (s.inspector) return 'Subagent';+ if (s.selected) return `${s.noun.one} ${s.selected.n} of ${s.taskCount}`;+ return s.scoped ? 'Filtered session' : 'Whole session';+}++/** "1,204 chars · 2 images · 1 URL" for a task's prompt row. */+export function promptLine(+ s: Pick<TaskSummary, 'promptChars' | 'promptImages' | 'promptUrls'>+): string {+ const plural = (n: number, one: string) => `${n} ${one}${n > 1 ? 's' : ''}`;+ const parts = [`${s.promptChars} chars`];+ if (s.promptImages) parts.push(plural(s.promptImages, 'image'));+ if (s.promptUrls) parts.push(plural(s.promptUrls, 'URL'));+ return parts.join(' · ');+}++/** The sessions list's day groups (list order kept; a day that reappears+ * later in the list starts a new group, as before). */+export function groupSessionsByDay(+ sessions: readonly SessionExplorerSession[]+): { day: string; items: SessionExplorerSession[] }[] {+ const groups: { day: string; items: SessionExplorerSession[] }[] = [];+ for (const s of sessions) {+ const day = (s.sessionDate ?? s.startedAt).slice(0, 10);+ const last = groups[groups.length - 1];+ if (last && last.day === day) last.items.push(s);+ else groups.push({ day, items: [s] });+ }+ return groups;+}++/** One row of the toolbar's Agent picker. */+export interface AgentOption {+ /** agent id; `main` is the whole session (every agent) */+ id: string;+ label: string;+ calls: number;+ cost: number;+ /** set by `agentOptionsInScope`: no events in the prompt/model scope */+ empty?: boolean;+}++/** The Agent picker's rows: the whole session, then every subagent (as+ * `Sub n: type`). Empty when the session ran no subagents. */+export function agentOptions(+ map: SessionMap,+ ordinals: Map<string, number>+): AgentOption[] {+ const subs = map.agents.filter((a) => a.id !== 'main');+ if (!subs.length) return [];+ return [+ {+ id: 'main',+ label: 'All agents',+ calls: map.totals.calls,+ cost: map.totals.costUsd,+ },+ ...subs.map((a) => ({+ id: a.id,+ label: agentLabel(map, a.id, ordinals),+ calls: a.calls,+ cost: a.cost,+ })),+ ];+}++/**+ * The Agent picker's rows counted inside the prompt/model scope (`scoped` is+ * `deriveScopeDoc`'s output, before the lens): the same rows, with the calls+ * and cost the scope holds, `empty` where the agent has no event in it.+ */+export function agentOptionsInScope(+ options: readonly AgentOption[],+ scoped: SessionMap+): AgentOption[] {+ const active = new Set(scoped.events.map((e) => e.agent));+ return options.map((o) => {+ if (o.id === 'main')+ return {+ ...o,+ calls: scoped.totals.calls,+ cost: scoped.totals.costUsd,+ empty: !hasReplayEvents(scoped),+ };+ const a = scoped.agents.find((x) => x.id === o.id);+ return {+ ...o,+ calls: a?.calls ?? 0,+ cost: a?.cost ?? 0,+ empty: !active.has(o.id),+ };+ });+}++/** The empty-replay sentence, naming only the filters that are set. */+export function emptyScopeDescription(+ scope: Scope,+ sub: string | null,+ noun: { one: string }+): string {+ const names = [+ scope.task != null ? noun.one.toLowerCase() : null,+ scope.model != null ? 'model' : null,+ sub ? 'agent' : null,+ ].filter((n): n is string => n != null);+ const list =+ names.length > 1+ ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`+ : names.join('');+ return `No events match the selected ${list}. Clear a filter above.`;+}++/** The collapsed sidebar rail's vertical label. */+export function sidebarRailLabel(s: {+ /** the open subagent's label, if any */+ subLabel: string | null;+ mode: 'list' | 'session';+ sessionId: string;+ taskCount: number;+ /** what the windows are called (`taskNoun`) */+ noun: { one: string; many: string };+}): string {+ if (s.subLabel) return `↳ ${s.subLabel}`;+ if (s.mode !== 'session') return 'Sessions';+ const shortId = (s.sessionId.split(':').pop() ?? s.sessionId).slice(0, 8);+ return `${shortId} · ${s.taskCount} ${(s.taskCount === 1 ? s.noun.one : s.noun.many).toLowerCase()}`;+}++// --- event categories: the dock's one chip row (timeline, map, Activity) -----++/**+ * The event categories behind the dock's chip row. One selection drives the+ * timeline's Events bar (matching marks bright, the rest dim), the map+ * (matching nodes bright) and the Activity feed.+ *+ * Mapping (event kind -> category; `categoryMatches` is the membership test,+ * `categoryOf` the one primary category an event is coloured by):+ * - prompt: `user` turns+ * - error: any failed event (`err`) and `error` signals -- also counted in+ * the category of what failed (an errored MCP call is MCP too)+ * - delay: `delay` and `compaction`+ * - out: commits, PR merge / close / comment, tickets, artifacts, skill+ * writes, and a tool call that opened a PR (`vcs.action`)+ * - edit: `edit`+ * - explore: `read` and `search` (the read / view / find calls)+ * - mcp: `mcp` calls (and any call categorised `cat: 'mcp'`)+ * - skill: `skill` invocations (and `cat: 'skill'`)+ * - tool: every other tool call: `exec`, `verify`, `web`, `tool`, and the+ * `subagent` spawn call+ * - model: `llm` requests and `model_switch`+ * - cost: `llm` requests that cost something+ * - tokens: `llm` requests that carry tokens+ */+export type Category =+ | 'prompt'+ | 'error'+ | 'delay'+ | 'out'+ | 'edit'+ | 'explore'+ | 'mcp'+ | 'skill'+ | 'tool'+ | 'model'+ | 'cost'+ | 'tokens';++export const CATEGORIES: readonly Category[] = [+ 'prompt',+ 'error',+ 'delay',+ 'out',+ 'edit',+ 'explore',+ 'mcp',+ 'skill',+ 'tool',+ 'model',+ 'cost',+ 'tokens',+];++export const CATEGORY_LABEL: Record<Category, string> = {+ prompt: 'Prompts',+ error: 'Errors',+ delay: 'Delays',+ out: 'Outputs',+ edit: 'Edits',+ explore: 'Exploration',+ mcp: 'MCP',+ skill: 'Skill',+ tool: 'Tools',+ model: 'Model',+ cost: 'Cost',+ tokens: 'Tokens',+};++/** Delays, Outputs and the activity categories are the noisiest, so the+ * dock starts on Prompts + Errors. */+export const DEFAULT_CATEGORIES: readonly Category[] = ['prompt', 'error'];++const EXPLORE_KINDS = new Set(['read', 'search']);+const MODEL_KINDS = new Set(['llm', 'model_switch']);+const isMcp = (e: SessionMapEvent) => e.kind === 'mcp' || e.cat === 'mcp';+const isSkill = (e: SessionMapEvent) => e.kind === 'skill' || e.cat === 'skill';+/** A tool call that no more specific call category claims -- including+ * Outputs: an `exec` that opened a PR is an output, not "another tool". */+const isOtherTool = (e: SessionMapEvent) =>+ !NON_CALL.has(e.kind) &&+ e.kind !== 'edit' &&+ !EXPLORE_KINDS.has(e.kind) &&+ !isMcp(e) &&+ !isSkill(e) &&+ !isOutputEvent(e);++const CATEGORY_TEST: Record<Category, (e: SessionMapEvent) => boolean> = {+ prompt: (e) => e.kind === 'user',+ error: (e) => !!e.err || e.kind === 'error',+ delay: (e) => e.kind === 'delay' || e.kind === 'compaction',+ out: isOutputEvent,+ edit: (e) => e.kind === 'edit',+ explore: (e) => EXPLORE_KINDS.has(e.kind),+ mcp: (e) => !NON_CALL.has(e.kind) && isMcp(e),+ skill: (e) => !NON_CALL.has(e.kind) && isSkill(e),+ tool: isOtherTool,+ model: (e) => MODEL_KINDS.has(e.kind),+ cost: (e) => e.kind === 'llm' && (e.cost ?? 0) > 0,+ tokens: (e) => e.kind === 'llm' && llmTokens(e) > 0,+};++/** Whether `e` belongs to `cat` (an event can be in several). */+export const categoryMatches = (e: SessionMapEvent, cat: Category): boolean =>+ CATEGORY_TEST[cat](e);++/** Whether `e` belongs to any category in `cats`. */+export const matchesAnyCategory = (+ e: SessionMapEvent,+ cats: Iterable<Category>+): boolean => {+ for (const c of cats) if (CATEGORY_TEST[c](e)) return true;+ return false;+};++/** Primary categories, most specific first: the one an event is coloured by+ * when none of its selected categories applies. `cost` / `tokens` are+ * measures of a model request, never primary. */+const PRIMARY_ORDER: readonly Category[] = [+ 'prompt',+ 'delay',+ 'out',+ 'edit',+ 'explore',+ 'mcp',+ 'skill',+ 'model',+ 'tool',+];++/** The one category an event is drawn as. A standalone `error` signal is an+ * error; a failed call keeps the category of the call (its error shows+ * through `categoryMatches`). Every event has one (`tool` catches the rest). */+export function categoryOf(e: SessionMapEvent): Category {+ if (e.kind === 'error') return 'error';+ return PRIMARY_ORDER.find((c) => CATEGORY_TEST[c](e)) ?? 'tool';+}++/** The category to colour `e` by under a selection: the first selected one+ * it matches (so an errored edit reads red while Errors is on), else its+ * primary category. */+export function displayCategory(+ e: SessionMapEvent,+ selected: ReadonlySet<Category>+): Category {+ for (const c of CATEGORIES)+ if (selected.has(c) && CATEGORY_TEST[c](e)) return c;+ return categoryOf(e);+}++/** Indices (in time order) of the events in `cat`, optionally only those+ * `allow` accepts (the open subagent's events in the lensed timeline). */+export function categoryIndices(+ events: readonly SessionMapEvent[],+ cat: Category,+ allow?: (i: number) => boolean+): number[] {+ const out: number[] = [];+ events.forEach((e, i) => {+ if (CATEGORY_TEST[cat](e) && (!allow || allow(i))) out.push(i);+ });+ return out;+}++/** Toggle one category (the selection may become empty). */+export function toggleCategory(+ selected: ReadonlySet<Category>,+ c: Category+): Set<Category> {+ const next = new Set(selected);+ if (next.has(c)) next.delete(c);+ else next.add(c);+ return next;+}++/** The chips' click order across a selection change `prev` -> `next`:+ * newly selected chips are appended, deselected ones dropped. (The URL+ * rebuilds a selection in CATEGORIES order, so the Set's own order can't+ * say which chip was clicked last.) */+export function pickHistory(+ history: readonly Category[],+ prev: ReadonlySet<Category>,+ next: ReadonlySet<Category>+): Category[] {+ const out = history.filter((c) => next.has(c));+ for (const c of CATEGORIES)+ if (next.has(c) && !prev.has(c) && !out.includes(c)) out.push(c);+ return out;+}++/** The most recently picked selected chip, optionally among `eligible`.+ * Chips selected without a click this visit (the URL or default) count as+ * picked first, in CATEGORIES order. */+export function lastPicked(+ history: readonly Category[],+ selected: ReadonlySet<Category>,+ eligible?: readonly Category[]+): Category | null {+ const pickedSet = new Set(history);+ const order = [+ ...CATEGORIES.filter((c) => selected.has(c) && !pickedSet.has(c)),+ ...history.filter((c) => selected.has(c)),+ ];+ const eligibleSet = eligible && new Set(eligible);+ for (let i = order.length - 1; i >= 0; i--)+ if (!eligibleSet || eligibleSet.has(order[i])) return order[i];+ return null;+}++/** Every category: a selection that narrows nothing. */+export const ALL_CATEGORIES: ReadonlySet<Category> = new Set(CATEGORIES);++/** The selection is exactly the default one. */+export const isDefaultCategories = (s: ReadonlySet<Category>): boolean =>+ s.size === DEFAULT_CATEGORIES.length &&+ DEFAULT_CATEGORIES.every((c) => s.has(c));++/** The selection narrows the map / Activity feed: anything but the default,+ * every category, or none of them (all three render unfiltered -- an empty+ * selection is "no filter active", the same as picking every chip, not "hide+ * everything"; `ev=none` round-trips it through the URL as exactly that). */+export const narrowsView = (s: ReadonlySet<Category>): boolean =>+ s.size > 0 && !isDefaultCategories(s) && s.size < CATEGORIES.length;++/** Which measure sizes the LLM marks on the Events bar: Cost wins when both+ * Cost and Tokens are selected. */+export function sizeMetric(s: ReadonlySet<Category>): 'cost' | 'tokens' | null {+ if (s.has('cost')) return 'cost';+ if (s.has('tokens')) return 'tokens';+ return null;+}++/** A mark's size fraction in [0, 1] for `v` against the largest `max`:+ * square-root scaled so one outlier does not flatten the rest; 0 for+ * nothing, and never below `floor` for anything above zero. */+export function magnitude(v: number, max: number, floor = 0.12): number {+ if (!(v > 0) || !(max > 0)) return 0;+ return Math.max(floor, Math.min(1, Math.sqrt(v / max)));+}++const isCategory = (v: string): v is Category =>+ (CATEGORIES as readonly string[]).includes(v);++/**+ * The chip selection from the URL: `ev` (a comma list of categories, `none`+ * for an explicitly empty one); else the default. Unknown values are ignored,+ * never thrown on.+ */+export function parseCategories(ev: string | null | undefined): Set<Category> {+ if (ev === 'none') return new Set();+ const keys = (ev ?? '')+ .split(',')+ .map((k) => k.trim())+ .filter(isCategory);+ if (keys.length) return new Set(CATEGORIES.filter((c) => keys.includes(c)));+ return new Set(DEFAULT_CATEGORIES);+}++/** The `ev` URL value for a selection: null (no param) for the default. */+export function serializeCategories(s: ReadonlySet<Category>): string | null {+ if (isDefaultCategories(s)) return null;+ if (!s.size) return 'none';+ return CATEGORIES.filter((c) => s.has(c)).join(',');+}++/**+ * The map nodes a non-default selection highlights: every node an event in+ * the selection touches (`refs`), plus its ancestors so the branch to it+ * stays lit. Null (the map renders as today) for the default or full+ * selection, or when nothing selected touches the map (prompts / delays+ * alone have no nodes: dimming everything would read as an empty map).+ */+export function mapFocus(+ tree: SessionTree,+ refs: readonly NodeRef[][],+ events: readonly SessionMapEvent[],+ selected: ReadonlySet<Category>+): Set<string> | null {+ if (!narrowsView(selected)) return null;+ const ids: string[] = [];+ events.forEach((e, i) => {+ if (!matchesAnyCategory(e, selected)) return;+ for (const r of refs[i] ?? []) ids.push(r.id);+ });+ if (!ids.length) return null;+ return ancestorsOf(tree, ids);+}++/**+ * The map nodes on one review comment's causal path: the nodes its steps+ * touch, plus their ancestors so the branch to each stays lit. Same shape as+ * `mapFocus`, so the map dims everything else exactly as it does for a+ * category selection -- a path is just a different reason to narrow.+ *+ * `seqs` are event `seq` values, which is what a comment cites, rather than+ * indices into `events`: a scoped map drops events, so the two differ.+ * Returns null when none of them are in this scope, so the caller shows an+ * unchanged map instead of dimming everything to nothing.+ *+ * Matched through `srcSeqOf`, not `e.seq`: a scoped or lensed map renumbers+ * `seq` over the events it kept, so a cited number read against `seq` there+ * resolves to whatever event now sits at that position -- lighting unrelated+ * nodes while the cited ones stay dark.+ */+export function pathFocus(+ tree: SessionTree,+ refs: readonly NodeRef[][],+ events: readonly SessionMapEvent[],+ seqs: readonly number[]+): Set<string> | null {+ const want = new Set(seqs);+ const ids: string[] = [];+ events.forEach((e, i) => {+ const seq = srcSeqOf(e);+ if (seq == null || !want.has(seq)) return;+ for (const r of refs[i] ?? []) ids.push(r.id);+ });+ if (!ids.length) return null;+ return ancestorsOf(tree, ids);+}++/**+ * What the map filters its event refs by, given the dock's chip selection and+ * whether a review comment's causal path is currently lit.+ *+ * A picked path already wins the *focus* set (`pathFocus` over `mapFocus`),+ * but the map narrows twice: it also blanks the refs of every event outside+ * the selection (`activeRefs`), which decides the active dots and the labels.+ * Left narrowed, a path step whose own category is unchecked would be blanked+ * out of both, so picking a comment lit only the steps the chips happened to+ * include. While a path is lit the chips are suspended; with+ * no path they are returned untouched, so ordinary filtering is unchanged.+ */+export const mapChipSelection = (+ selected: ReadonlySet<Category>,+ pathLit: boolean+): ReadonlySet<Category> => (pathLit ? ALL_CATEGORIES : selected);++/** `refs`, with every event that doesn't match the selection blanked out.+ * Feeds the map's "what's currently touched" pipeline (`stateAt`,+ * `activeSet`, `recentTargets`) so that a narrowed selection's recent-N+ * window, dot prominence and labels are scoped to the selection too --+ * otherwise a burst of unselected activity (e.g. many MCP calls while only+ * Edits is selected) fills the recent-touch budget and an edited file's+ * label never appears, or stops updating as the playhead advances past it.+ * Identity (same reference) when the selection doesn't narrow the view, so+ * it costs nothing there. Deliberately NOT applied to `nextTouchOf`'s seek+ * target, which stays on the raw event stream regardless of the selection.+ *+ * A kept event's passive refs (an LLM request's model) turn active only+ * when the selection itself includes Model / Cost / Tokens -- the model+ * *is* what was selected there, and left passive its leaf would never+ * light or get its label. Selected through some other category (e.g. an+ * errored LLM matched via Errors), the model stays passive: it wasn't+ * what the user asked to see, just incidental to the event that was. */+const MODEL_CATEGORIES: ReadonlySet<Category> = new Set([+ 'model',+ 'cost',+ 'tokens',+]);+export function activeRefs(+ refs: NodeRef[][],+ events: readonly SessionMapEvent[],+ selected: ReadonlySet<Category>+): NodeRef[][] {+ if (!narrowsView(selected)) return refs;+ const promotePassive = [...MODEL_CATEGORIES].some((c) => selected.has(c));+ return refs.map((r, i) => {+ if (!matchesAnyCategory(events[i], selected)) return [];+ if (!promotePassive || !r.some((x) => x.passive)) return r;+ return r.map((x) => (x.passive ? { ...x, passive: false } : x));+ });+}++// --- timeline dock: stepping, pinned height ----------------------------------++/**+ * The event `dir` steps from the pinned one in `list` (clamped at the ends).+ * With nothing pinned in the list, forward goes to the first event after the+ * playhead (wrapping to the first) and back to the last one before it+ * (wrapping to the last). Null for an empty list.+ */+export function stepEvent(+ list: readonly number[],+ pinned: number | null,+ p: number,+ dir: 1 | -1+): number | null {+ if (!list.length) return null;+ const k = pinned == null ? -1 : list.indexOf(pinned);+ if (k >= 0) return list[Math.max(0, Math.min(list.length - 1, k + dir))];+ if (dir > 0) return list.find((i) => i > p) ?? list[0];+ for (let j = list.length - 1; j >= 0; j--) if (list[j] < p) return list[j];+ return list[list.length - 1];+}++/** "k/N" when the pinned event is in `list`, else null. */+export function stepPosition(+ list: readonly number[],+ pinned: number | null+): string | null {+ const k = pinned == null ? -1 : list.indexOf(pinned);+ return k >= 0 ? `${k + 1}/${list.length}` : null;+}++/** One row per subagent that has events in the timeline's map, in the+ * order they started, labelled "n · type". */+export function subagentLanes(+ subs: readonly SubagentInfo[],+ events: readonly SessionMapEvent[]+): { id: string; label: string }[] {+ const present = new Set(events.map((e) => e.agent));+ return subs+ .filter((s) => present.has(s.id))+ .map((s) => ({ id: s.id, label: `${s.index} · ${s.type}` }));+}++export const DOCK_HEIGHT_KEY = 'session-explorer:timeline-height';+/** The dock never gets shorter than this (header + a few lanes)... */+export const DOCK_MIN_HEIGHT = 140;+/** ...nor, when dragged, taller than this share of the explorer. */+export const DOCK_MAX_FRACTION = 0.72;++/** A dragged dock height clamped to [min, 72% of the explorer]. */+export function clampDockHeight(h: number, containerH: number): number {+ const max = Math.max(DOCK_MIN_HEIGHT, containerH * DOCK_MAX_FRACTION);+ return Math.round(Math.max(DOCK_MIN_HEIGHT, Math.min(h, max)));+}++/** How far the dock (rendered `dockH` tall) grows past the height the+ * explorer budgets for it: its optional lanes' height (`optionalH`), less+ * whatever a dragged `floor` had already reserved. The explorer extends by+ * exactly this below the fold, so turning on Subagents / Context scrolls the+ * page instead of shrinking the map. */+export function dockOverflow(+ dockH: number,+ optionalH: number,+ floor: number | null+): number {+ return Math.max(+ 0,+ Math.round(dockH - Math.max(floor ?? 0, dockH - optionalH))+ );+}++/** The persisted dock height, or null (content height) when it is unset,+ * unparseable, or storage is missing or throws. */+export function readDockHeight(+ storage: MaybeStorage = defaultStorage()+): number | null {+ try {+ const v = Number(storage?.getItem(DOCK_HEIGHT_KEY) ?? '');+ return Number.isFinite(v) && v >= DOCK_MIN_HEIGHT ? Math.round(v) : null;+ } catch {+ return null;+ }+}++export function writeDockHeight(+ h: number | null,+ storage: MaybeStorage = defaultStorage()+): void {+ try {+ // '' (reset) reads back as null: content height+ storage?.setItem(DOCK_HEIGHT_KEY, h == null ? '' : String(Math.round(h)));+ } catch {+ // private mode / blocked storage: the height just is not remembered+ }+}++/* `useSyncExternalStore` source for the dock height, like the sidebar's+ * collapsed state: memory is this tab's truth, storage seeds and persists+ * it, and `storage` events keep other tabs in step. */+let dockMem: number | null | undefined;+const dockListeners = new Set<() => void>();++export function getDockHeight(): number | null {+ if (dockMem === undefined) dockMem = readDockHeight();+ return dockMem;+}++/** SSR has no storage: render at content height. */+export function getDockHeightServer(): number | null {+ return null;+}++/** Set (and persist, unless `persist` is false: mid-drag) the height. */+export function setDockHeight(next: number | null, persist = true): void {+ dockMem = next;+ if (persist) writeDockHeight(next);+ dockListeners.forEach((l) => l());+}++export function subscribeDockHeight(listener: () => void): () => void {+ dockListeners.add(listener);+ const onStorage = (e: StorageEvent) => {+ if (e.key !== DOCK_HEIGHT_KEY) return;+ dockMem = readDockHeight();+ listener();+ };+ if (typeof window !== 'undefined')+ window.addEventListener('storage', onStorage);+ return () => {+ dockListeners.delete(listener);+ if (typeof window !== 'undefined')+ window.removeEventListener('storage', onStorage);+ };+}++// --- errors ------------------------------------------------------------------++/** One failed call, with the detail needed to decide what to do about it. */+export interface SessionError {+ /** Index into the map's events, for seeking. */+ index: number;+ seq: number;+ t: number;+ /** Shell verb, MCP server/tool, or tool name. */+ label: string;+ errClass: string;+ exitCode?: number;+ /** How long the call ran before failing. A 72s failure and an 0.8s one are+ * different problems, and this is the only cost an error row can show. */+ durMs?: number;+ /** Only when it names something real. Every target on an error event is a+ * coarse privacy bucket ("outside-repo", "/tmp (scratch)") unless the call+ * touched a file inside a repo, and a bucket on every row is noise. */+ target?: string;+ /** The task it happened in, for jumping back to what was being asked. */+ task?: number;+ agent: string;+}++/** Failures of one class, newest run first. */+export interface ErrorGroup {+ errClass: string;+ label: string;+ /** Provider-side (rate limit, overload, auth) rather than something this+ * harness can fix per call. Ranked last so it cannot bury the rest. */+ provider: boolean;+ errors: SessionError[];+ /** Longest run of consecutive failures of the same label in this class.+ * One failure is noise; four of the same command in a row is a harness+ * problem, and that is what makes the list actionable rather than a log. */+ worstRun: number;+ worstRunLabel?: string;+}++const errorLabelOf = (e: SessionMapEvent): string => {+ const hookTitle = hookErrorTitle(e);+ if (hookTitle) return hookTitle;+ if (e.kind === 'mcp') return [e.server, e.tool].filter(Boolean).join('.') || 'mcp';+ return e.verb || e.tool || e.kind;+};++/** Only a target that names something. The path mode collapses anything+ * outside a repo into a coarse bucket ("outside-repo", "/tmp (scratch)");+ * repeating that on every row crowds out the detail that does vary. */+const errorTargetOf = (e: SessionMapEvent): string | undefined => {+ const t = e.targets?.find((x) => x.label && x.scope !== 'outside');+ return t?.label ?? undefined;+};++/** Provider-side failures: rate limits, overloads, auth. Real, but not something+ * a per-call fix addresses, and they can outnumber tool failures, so they+ * must not bury the ones the harness can act on. */+const PROVIDER_CLASSES = new Set([+ 'api_error',+ 'rate_limit',+ 'model_unavailable',+ 'server_error',+ 'overloaded',+ 'spend_limit',+ 'usage_limit',+ 'auth',+]);++/** How a failure is grouped and named.+ *+ * `errClass` is sometimes missing or "other", and+ * "other error" is not something anyone can act on. Those events still carry a+ * tool category, so fall back to it: "Shell failed" beats "other error". */+function errorGroupOf(e: SessionMapEvent): { key: string; label: string } {+ const cls = errClassOf(e);+ // A hook failure is named for its hook: "Stop hook blocked" is a different+ // problem from "PostToolUse:Bash hook error".+ const hookTitle = hookErrorTitle(e);+ if (hookTitle) return { key: `${cls}/${e.hook ?? ''}`, label: hookTitle };+ if (cls && cls !== 'other') return { key: cls, label: errClassLabel(cls) };+ const cat = typeof e.cat === 'string' ? e.cat : e.kind;+ return { key: `cat:${cat}`, label: `${catLabel(cat)} failed` };+}++/**+ * Every failure in the map, grouped by class and ordered by weight.+ *+ * Over whichever map it is given: a scoped map lists that scope, and an index+ * can be handed straight to `seek` on that map. See `wholeSessionErrors` for+ * the list that ignores the scope.+ */+export function sessionErrors(map: SessionMap): {+ groups: ErrorGroup[];+ total: number;+} {+ const all: SessionError[] = [];+ const labelOfKey = new Map<string, string>();+ map.events.forEach((e, index) => {+ if (!e.err && e.kind !== 'error') return;+ const group = errorGroupOf(e);+ labelOfKey.set(group.key, group.label);+ all.push({+ index,+ seq: e.seq ?? index,+ t: e.t ?? 0,+ label: errorLabelOf(e),+ errClass: group.key,+ exitCode: typeof e.exitCode === 'number' ? e.exitCode : undefined,+ durMs: typeof e.dur === 'number' ? e.dur : undefined,+ target: errorTargetOf(e),+ task: typeof e.task === 'number' ? e.task : undefined,+ agent: e.agent ?? 'main',+ });+ });++ const byClass = new Map<string, SessionError[]>();+ for (const err of all) {+ const list = byClass.get(err.errClass);+ if (list) list.push(err);+ else byClass.set(err.errClass, [err]);+ }++ const groups: ErrorGroup[] = [];+ for (const [errClass, errors] of byClass) {+ // Longest consecutive run of the same label, over the whole session: a+ // retry loop is the same command failing again, not merely failing twice.+ let worstRun = 1;+ let worstRunLabel: string | undefined;+ let run = 0;+ let runLabel = '';+ for (const err of all) {+ if (err.errClass === errClass && err.label === runLabel) run += 1;+ else {+ run = err.errClass === errClass ? 1 : 0;+ runLabel = err.errClass === errClass ? err.label : '';+ }+ if (run > worstRun) {+ worstRun = run;+ worstRunLabel = runLabel;+ }+ }+ groups.push({+ errClass,+ label: labelOfKey.get(errClass) ?? errClass,+ provider: PROVIDER_CLASSES.has(errClass),+ errors,+ worstRun,+ worstRunLabel,+ });+ }+ // What the harness can fix first, then the biggest problem: a retry run+ // outranks a larger pile of one-offs.+ groups.sort(+ (a, b) =>+ Number(a.provider) - Number(b.provider) ||+ b.worstRun - a.worstRun ||+ b.errors.length - a.errors.length+ );+ return { groups, total: all.length };+}++/** Errors per task, for the task list's error tags. */+export interface TaskErrors {+ count: number;+ /** Whole-session `seq` (`srcSeqOf`) of the row the Errors tab lists first+ * once scoped to this task, so the tag lands on what the user then sees at+ * the top. Not an index, and not the scoped `seq`: deriving a scope renumbers+ * both, and the jump re-scopes. */+ firstSeq: number;+}++/** The map's failures, each carrying its whole-session number as `seq` so a+ * list built from them reports it rather than its own index. */+function errorEventsBySessionSeq(map: SessionMap): SessionMapEvent[] {+ const out: SessionMapEvent[] = [];+ map.events.forEach((e, index) => {+ if (!e.err && e.kind !== 'error') return;+ out.push({ ...e, seq: srcSeqOf(e) ?? index });+ });+ return out;+}++/** The Errors tab's list: every failure of the whole session, however the+ * player is scoped. Pass the unscoped map. Rows carry the whole-session `seq`+ * (not an index into a scoped map), so use `errorClickAction` to act on one. */+export function wholeSessionErrors(map: SessionMap): {+ groups: ErrorGroup[];+ total: number;+} {+ return sessionErrors({ ...map, events: errorEventsBySessionSeq(map) });+}++/** What clicking an Errors row does: seek the player, or re-scope first. */+export type ErrorClickAction =+ | { kind: 'seek'; index: number }+ | { kind: 'jump'; task: number | null; seq: number };++/**+ * The list covers the whole session, the player may not. An error the current+ * map still holds is sought in place, by whole-session `seq` (a scope renumbers+ * `seq` and the index). One the scope hides re-scopes to its task, or clears the+ * task when it has none, and lands on it there.+ */+export function errorClickAction(+ err: Pick<SessionError, 'seq' | 'task'>,+ scopedMap: SessionMap+): ErrorClickAction {+ const index = scopedMap.events.findIndex((e, i) => (srcSeqOf(e) ?? i) === err.seq);+ if (index >= 0) return { kind: 'seek', index };+ return { kind: 'jump', task: err.task ?? null, seq: err.seq };+}++/** Per task, how many errors it had and where its Errors list starts. Over the+ * whole session (tasks are stamped on `fullMap`), like the rest of the task+ * list, so the tags don't change with the current scope. */+export function taskErrors(map: SessionMap): Map<number, TaskErrors> {+ const byTask = new Map<number, SessionMapEvent[]>();+ for (const ev of errorEventsBySessionSeq(map)) {+ if (typeof ev.task !== 'number') continue;+ const list = byTask.get(ev.task);+ if (list) list.push(ev);+ else byTask.set(ev.task, [ev]);+ }+ const out = new Map<number, TaskErrors>();+ for (const [task, events] of byTask) {+ // The same grouping and ranking the Errors tab applies to this task alone.+ const { groups, total } = sessionErrors({ ...map, events });+ const first = groups[0]?.errors[0];+ if (first) out.set(task, { count: total, firstSeq: first.seq });+ }+ return out;+}diff --git a/viewer/src/core/sessionMapModel.test.ts b/viewer/src/core/sessionMapModel.test.tsnew file mode 100644index 0000000..76f8430--- /dev/null+++ b/viewer/src/core/sessionMapModel.test.ts@@ -0,0 +1,625 @@+import { describe, expect, it } from 'vitest';+import {+ SESSION_MAP_SCHEMA_V1,+ sessionMapSchema,+ type SessionMap,+} from './schema';+import {+ INNER_MAX,+ INNER_MIN,+ activeSet,+ agentLabel,+ buildTree,+ countersAt,+ cumulativeCost,+ deriveLensDoc,+ describeEvent,+ eventNodeRefs,+ fileCoverage,+ findNext,+ initialPlayhead,+ lastTouch,+ layoutTree,+ nextTouchOf,+ recentTargets,+ recomputeTotals,+ reviewMetrics,+ shiftStartedAt,+ stateAt,+} from './sessionMapModel';++type RawEvent = Record<string, unknown> & { kind: string };++function makeMap(events: RawEvent[], overrides: Record<string, unknown> = {}) {+ return sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: {+ id: 'local:claude-code:abc12345-0000',+ agentTool: 'claude-code',+ startedAt: '2026-09-10T01:00:00Z',+ durationMs: 60_000,+ models: ['claude-opus-5'],+ },+ totals: { calls: 0, requests: 0 },+ repos: [+ { id: 'r0', name: 'backend', remote: 'org/backend' },+ { id: 'r1', name: 'cli' },+ ],+ files: [+ {+ id: 0,+ repo: 'r0',+ path: 'billing_core/deep/nested/controller.py',+ reads: 1,+ edits: 3,+ },+ {+ id: 1,+ repo: 'r0',+ path: 'billing_core/views.py',+ reads: 2,+ edits: 0,+ },+ { id: 2, repo: 'r1', path: 'README.md', reads: 0, edits: 1 },+ {+ id: 3,+ repo: 'r0',+ path: 'billing_core/new_file.py',+ reads: 0,+ edits: 1,+ },+ ],+ agents: [+ { id: 'main', parent: null, kind: 'main', cost: 3, calls: 5 },+ {+ id: 'sa-ae824d54211f',+ parent: 'main',+ kind: 'subagent',+ subagentType: 'general-purpose',+ cost: 1,+ calls: 2,+ },+ ],+ events: events.map((e, i) => ({+ seq: i,+ t: i * 1000,+ agent: 'main',+ err: false,+ ...e,+ })),+ ...overrides,+ });+}++const EVENTS: RawEvent[] = [+ { kind: 'user', chars: 120 }, // 0+ {+ kind: 'llm',+ model: 'claude-opus-5',+ in: 10,+ cw: 100,+ cr: 1000,+ out: 50,+ cost: 0.5,+ }, // 1+ { kind: 'read', tool: 'Read', targets: [{ file: 1, touch: 'read' }] }, // 2+ { kind: 'edit', tool: 'Edit', targets: [{ file: 0, touch: 'edit' }] }, // 3 blind+ { kind: 'read', tool: 'Read', targets: [{ file: 0, touch: 'read' }] }, // 4+ { kind: 'edit', tool: 'Write', targets: [{ file: 3, touch: 'edit' }] }, // 5 creates, not blind+ { kind: 'mcp', server: 'acme-context', tool: 'find_expert' }, // 6+ { kind: 'skill', skill: 'artifact-design' }, // 7+ { kind: 'web', tool: 'WebFetch', host: 'docs.example.com' }, // 8+ {+ kind: 'subagent',+ tool: 'Agent',+ subagentType: 'general-purpose',+ child: 'sa-ae824d54211f',+ }, // 9+ {+ kind: 'read',+ tool: 'Read',+ agent: 'sa-ae824d54211f',+ targets: [{ file: 1, touch: 'read' }],+ }, // 10 re-read+ {+ kind: 'exec',+ tool: 'Bash',+ verb: 'git log',+ err: true,+ targets: [{ scope: 'outside', label: '/tmp (scratch)', touch: 'read' }],+ }, // 11+ { kind: 'verify', tool: 'Bash', verb: 'pytest' }, // 12+ { kind: 'edit', tool: 'Edit', targets: [{ file: 0, touch: 'edit' }] }, // 13 after verify+ {+ kind: 'llm',+ model: 'claude-sonnet-5',+ in: 5,+ cw: 0,+ cr: 500,+ out: 20,+ cost: 0.25,+ }, // 14+ { kind: 'edit', tool: 'Edit', targets: [{ file: 2, touch: 'edit' }] }, // 15 blind (never read)+];++describe('sessionMapSchema', () => {+ it('rejects a map that is not v1', () => {+ const r = sessionMapSchema.safeParse({+ schema: 'agentplay/v2',+ session: { id: 'x', startedAt: '2026-01-01T00:00:00Z' },+ totals: {},+ });+ expect(r.success).toBe(false);+ });++ it('keeps unknown fields and defaults optional ones', () => {+ const m = makeMap([{ kind: 'read', futureField: 7 }], { extra: true });+ expect(m.events[0].agent).toBe('main');+ expect((m.events[0] as Record<string, unknown>).futureField).toBe(7);+ expect((m as Record<string, unknown>).extra).toBe(true);+ expect(m.session.truncated).toBe(false);+ });+});++describe('buildTree', () => {+ const map = makeMap(EVENTS);+ const tree = buildTree(map);++ it('puts repos first, then the named groups', () => {+ const names = tree.root.children.map((c) => `${c.type}:${c.name}`);+ expect(names.slice(0, 2)).toEqual(['repo:backend', 'repo:cli']);+ expect(names).toEqual(+ expect.arrayContaining([+ 'group:outside repos',+ 'group:MCP',+ 'group:skills',+ 'group:web',+ 'group:subagents',+ ])+ );+ });++ it('collapses single-child directory chains and keeps folded ids resolvable', () => {+ const collapsed = tree.byId.get('dir:r0/billing_core/deep');+ expect(collapsed?.name).toBe('deep/nested');+ expect(tree.byId.get('dir:r0/billing_core/deep/nested')).toBe(collapsed);+ // billing_core has 3 children (deep/nested, views.py, new_file.py): not collapsed+ expect(tree.byId.get('dir:r0/billing_core')?.name).toBe('billing_core');+ });++ it('nests MCP tools under their server and labels subagents by type', () => {+ const tool = tree.byId.get('mcp:acme-context/find_expert');+ expect(tool?.parent?.id).toBe('srv:acme-context');+ expect(tool?.parent?.parent?.id).toBe('g:mcp');+ expect(tree.byId.get('agent:sa-ae824d54211f')?.name).toBe(+ 'Sub 1: general-purpose'+ );+ });+});++describe('layoutTree', () => {+ it('puts leaves on the outer ring and internals between 0.32R and 0.78R', () => {+ const R = 200;+ const tree = buildTree(makeMap(EVENTS));+ const nodes = layoutTree(tree, R);+ for (const n of nodes) {+ if (n === tree.root) {+ expect(n.r).toBe(0);+ } else if (!n.children.length) {+ expect(n.r).toBeCloseTo(R);+ expect(Math.hypot(n.x, n.y)).toBeCloseTo(R);+ } else {+ expect(n.r).toBeGreaterThanOrEqual(R * INNER_MIN - 1e-9);+ expect(n.r).toBeLessThanOrEqual(R * INNER_MAX + 1e-9);+ }+ }+ });+});++describe('playhead state', () => {+ const map = makeMap(EVENTS);+ const tree = buildTree(map);+ const refs = eventNodeRefs(map, tree);++ it('counts touches and keeps the highest touch level', () => {+ const st = stateAt(refs, 4);+ const f0 = st.get('file:0');+ expect(f0?.cnt).toBe(2);+ expect(f0?.lvl).toBe(3);+ expect(f0?.first).toBe(3);+ expect(st.get('file:1')?.lvl).toBe(2);+ expect(st.has('file:2')).toBe(false);+ });++ it('keeps only the most recent distinct nodes active', () => {+ const active = activeSet(refs, 11, 3);+ // #11 failed: its place and the error-class node are both active+ expect([...active]).toEqual([+ 'place:/tmp (scratch)',+ 'errc:tool/other',+ 'file:1',+ ]);+ });++ it('builds the trail oldest first', () => {+ const trail = recentTargets(refs, 5, 9);+ expect(trail.map((t) => t.i)).toEqual([2, 3, 4, 5]);+ });++ it('finds the one step the playhead lights: the last real touch', () => {+ expect(lastTouch(refs, 5)).toEqual({ i: 5, ids: ['file:3'] });+ // #12 (a verify) touches nothing: the failed #11 stays lit, with its+ // error class+ expect(lastTouch(refs, 12)).toEqual({+ i: 11,+ ids: ['place:/tmp (scratch)', 'errc:tool/other'],+ });+ // #1's model ref is passive, and #0 touches nothing+ expect(lastTouch(refs, 1)).toBeNull();+ });++ it('jumps to the next touch of a node or anything under it, wrapping', () => {+ expect(nextTouchOf(tree, refs, 3, 'file:0')).toBe(4);+ expect(nextTouchOf(tree, refs, 13, 'file:0')).toBe(3);+ expect(nextTouchOf(tree, refs, 0, 'dir:r0/billing_core')).toBe(2);+ expect(nextTouchOf(tree, refs, 0, 'nope')).toBeNull();+ });+});++describe('navigation helpers', () => {+ const map = makeMap(EVENTS);++ it('findNext wraps around and handles errors', () => {+ expect(findNext(map.events, 3, 'edit')).toBe(5);+ expect(findNext(map.events, 15, 'edit')).toBe(3);+ expect(findNext(map.events, 0, 'err')).toBe(11);+ expect(findNext(map.events, 0, 'subagent')).toBe(9);+ expect(findNext(makeMap([{ kind: 'read' }]).events, 0, 'user')).toBeNull();+ });++ it('opens just past the first edit, or 40% in without edits', () => {+ expect(initialPlayhead(map.events)).toBe(15);+ const noEdits = makeMap(+ Array.from({ length: 10 }, () => ({ kind: 'read' }))+ );+ expect(initialPlayhead(noEdits.events)).toBe(4);+ expect(initialPlayhead([])).toBe(0);+ });+});++describe('counters and costs', () => {+ const map = makeMap(EVENTS);++ it('counts calls, requests and files at the playhead', () => {+ const c = countersAt(map.events, 11);+ expect(c.requests).toBe(1);+ expect(c.tokens).toBe(1160);+ expect(c.cost).toBeCloseTo(0.5);+ expect(c.calls).toBe(10);+ expect(c.errors).toBe(1);+ expect(c.mcp).toBe(1);+ expect(c.skills).toBe(1);+ expect(c.subagents).toBe(1);+ expect(c.filesRead).toBe(2);+ expect(c.filesEdited).toBe(2);+ });++ it('accumulates cost as a prefix sum', () => {+ const cum = cumulativeCost(map.events);+ expect(cum[0]).toBe(0);+ expect(cum[1]).toBeCloseTo(0.5);+ expect(cum[cum.length - 1]).toBeCloseTo(0.75);+ });+});++describe('reviewMetrics', () => {+ it('flags blind edits but not a Write that creates a file', () => {+ const r = reviewMetrics(makeMap(EVENTS));+ expect(r.blindEdits).toBe(2); // #3 file 0, #15 file 2+ expect(r.errors).toBe(1);+ expect(r.churnFiles).toBe(1);+ // 3 file reads; #10 re-reads file 1 unchanged since #2+ expect(r.reReadPct).toBe(33);+ expect(r.verification).toBe('edits_after_verify');+ });++ it('reports verification after the final edit, and never', () => {+ const after = makeMap([+ { kind: 'edit', tool: 'Write', targets: [{ file: 3, touch: 'edit' }] },+ { kind: 'verify', tool: 'Bash', verb: 'pytest' },+ ]);+ expect(reviewMetrics(after).verification).toBe('after_final_edit');+ expect(reviewMetrics(after).blindEdits).toBe(0);+ expect(reviewMetrics(makeMap([{ kind: 'read' }])).verification).toBe(+ 'never'+ );+ });++ it('does not count a read after an edit as a re-read', () => {+ const m = makeMap([+ { kind: 'read', tool: 'Read', targets: [{ file: 1, touch: 'read' }] },+ { kind: 'edit', tool: 'Edit', targets: [{ file: 1, touch: 'edit' }] },+ { kind: 'read', tool: 'Read', targets: [{ file: 1, touch: 'read' }] },+ ]);+ expect(reviewMetrics(m).reReadPct).toBe(0);+ });+});++describe('describeEvent and labels', () => {+ const map: SessionMap = makeMap(EVENTS);++ it('describes LLM, user and file events without leaking content', () => {+ expect(describeEvent(map, map.events[1]).title).toBe(+ 'claude-opus-5 · $0.50'+ );+ expect(describeEvent(map, map.events[0]).detail).toBe(+ '120 chars (text not stored)'+ );+ const edit = describeEvent(map, map.events[3]);+ expect(edit.title).toBe('controller.py');+ expect(edit.detail).toBe(+ 'backend/billing_core/deep/nested/controller.py'+ );+ expect(describeEvent(map, map.events[11]).title).toBe('/tmp (scratch)');+ expect(describeEvent(map, map.events[9]).detail).toBe(+ 'spawned Sub 1: general-purpose'+ );+ });++ it('labels agents', () => {+ expect(agentLabel(map, 'main')).toBe('Main agent');+ expect(agentLabel(map, 'sa-ae824d54211f')).toBe('Sub 1: general-purpose');+ });++ it('summarises file coverage', () => {+ expect(fileCoverage(map)).toEqual({ edited: 3, read: 1, seen: 0 });+ });+});++describe('agent lens (deriveLensDoc / recomputeTotals)', () => {+ // `main` touches file 0 and file 2; `sa-1` (spawned by main at #2) has its+ // own lane: a failed exec, a retry of it, a tool delay caused by+ // it, a file it creates (file 1), and a confirmed PR create.+ const LENS_EVENTS: RawEvent[] = [+ { kind: 'user', chars: 10 }, // 0 main+ {+ kind: 'edit',+ tool: 'Write',+ targets: [{ file: 0, touch: 'edit', op: 'modify' }],+ }, // 1 main touches file 0+ {+ kind: 'subagent',+ tool: 'Agent',+ subagentType: 'general-purpose',+ child: 'sa-1',+ }, // 2 main spawns sa-1+ {+ kind: 'exec',+ tool: 'Bash',+ verb: 'pytest',+ agent: 'sa-1',+ err: true,+ errClass: 'exit_code',+ }, // 3 sa-1 fails+ { kind: 'exec', tool: 'Bash', verb: 'pytest', agent: 'sa-1', retryOf: 3 }, // 4 sa-1 retries #3+ { kind: 'delay', agent: 'sa-1', cause: 'tool', ms: 45_000, ref: 3 }, // 5 sa-1 delay caused by #3+ {+ kind: 'edit',+ tool: 'Write',+ agent: 'sa-1',+ targets: [{ file: 1, touch: 'edit', op: 'create' }],+ }, // 6 sa-1 creates file 1+ {+ kind: 'exec',+ tool: 'gh',+ verb: 'pr create',+ agent: 'sa-1',+ vcs: {+ provider: 'github',+ action: 'pr_create',+ repo: 'org/backend',+ number: 42,+ },+ }, // 7 sa-1 opens a PR+ {+ kind: 'edit',+ tool: 'Write',+ targets: [{ file: 2, touch: 'edit', op: 'modify' }],+ }, // 8 main touches file 2 (sa-1 never touches this file)+ ];+ const lensMap = makeMap(LENS_EVENTS, {+ prs: [+ {+ provider: 'github',+ repo: 'org/backend',+ number: 42,+ url: 'https://github.com/org/backend/pull/42',+ seq: 7,+ },+ ],+ files: [+ { id: 0, repo: 'r0', path: 'a.py' },+ { id: 1, repo: 'r0', path: 'b.py' },+ { id: 2, repo: 'r0', path: 'c.py' },+ ],+ agents: [+ { id: 'main', parent: null, kind: 'main', cost: 3, calls: 5 },+ {+ id: 'sa-1',+ parent: 'main',+ kind: 'subagent',+ subagentType: 'general-purpose',+ cost: 2,+ calls: 4,+ },+ ],+ });++ it('returns the full doc unchanged for "main"', () => {+ expect(deriveLensDoc(lensMap, 'main')).toBe(lensMap);+ });++ it('returns the full doc unchanged for an agent with no events of its own', () => {+ expect(deriveLensDoc(lensMap, 'nope')).toBe(lensMap);+ });++ it('reindexes events to a local 0-based sequence rebased at t=0', () => {+ const lens = deriveLensDoc(lensMap, 'sa-1');+ expect(lens.events.map((e) => e.seq)).toEqual([0, 1, 2, 3, 4]);+ expect(lens.events[0]?.t).toBe(0);+ expect(lens.events.map((e) => e.t)).toEqual([0, 1000, 2000, 3000, 4000]);+ expect(lens.events.every((e) => e.agent === 'main')).toBe(true);+ });++ it('remaps retryOf/ref to the new local sequence numbers', () => {+ const lens = deriveLensDoc(lensMap, 'sa-1');+ // event #4 (retryOf: 3) is local index 1; its retryOf must point at+ // local index 0 (the original #3), not the stale original seq.+ expect(lens.events[1]?.retryOf).toBe(0);+ // event #5 (ref: 3) is local index 2; same remap for `ref`.+ expect(lens.events[2]?.ref).toBe(0);+ });++ it('remaps retryOf/ref by original position even when events omit seq', () => {+ // `seq` is schema-optional; the remap must key off each event's own+ // position in `full.events`, not a `seq` field that may be absent.+ const noSeqMap = makeMap(+ LENS_EVENTS.map((e) => ({ ...e, seq: undefined })),+ {+ prs: lensMap.prs,+ files: lensMap.files,+ agents: lensMap.agents,+ }+ );+ expect(noSeqMap.events.every((e) => e.seq === undefined)).toBe(true);+ const lens = deriveLensDoc(noSeqMap, 'sa-1');+ expect(lens.events[1]?.retryOf).toBe(0);+ expect(lens.events[2]?.ref).toBe(0);+ });++ it("scopes totals to the lens's own events, not the full session", () => {+ const lens = deriveLensDoc(lensMap, 'sa-1');+ expect(lens.totals).toEqual(recomputeTotals(lens.events));+ expect(lens.totals.errors).toBe(1);+ expect(lens.totals.retries).toBe(1);+ expect(lens.totals.delays).toBe(1);+ expect(lens.totals.delayMs).toBe(45_000);+ expect(lens.totals.prsCreated).toBe(1);+ expect(lens.totals.filesCreated).toBe(1);+ expect(lens.totals.filesTouched).toBe(1);+ expect(lens.totals.subagents).toBe(0);+ });++ it('carries only PRs created within the lens, and derives its outcome', () => {+ const lens = deriveLensDoc(lensMap, 'sa-1');+ expect(lens.prs).toEqual(lensMap.prs);+ expect(lens.session.outcome).toBe('pr_created');+ });++ it('exposes itself as the sole "main" agent, with no further nesting', () => {+ const lens = deriveLensDoc(lensMap, 'sa-1');+ expect(lens.agents).toHaveLength(1);+ expect(lens.agents[0]?.id).toBe('main');+ expect(lens.agents[0]?.subagentType).toBe('general-purpose');+ });++ it(+ "does not leak the shared files[] aggregate into the lens's coverage " ++ "(file-touch counts must come from the lens's own " ++ 'events, not the full-document file records)',+ () => {+ const lens = deriveLensDoc(lensMap, 'sa-1');+ // main's touches (file 0, file 2) must not appear; only file 1, which+ // sa-1 itself created.+ expect(fileCoverage(lens)).toEqual({ edited: 1, read: 0, seen: 0 });+ }+ );+});++describe('recomputeTotals', () => {+ it('computes calls/requests/errors/PRs/file-ops from a bare event list', () => {+ const events = sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: { id: 'x', startedAt: '2026-01-01T00:00:00Z' },+ totals: {},+ files: [{ id: 0, repo: 'r0', path: 'a.py' }],+ events: [+ { seq: 0, t: 0, kind: 'user', agent: 'main', err: false, chars: 5 },+ {+ seq: 1,+ t: 100,+ kind: 'llm',+ agent: 'main',+ err: false,+ model: 'claude-opus-5',+ in: 10,+ out: 5,+ cost: 0.1,+ latency: 500,+ },+ {+ seq: 2,+ t: 200,+ kind: 'edit',+ agent: 'main',+ err: false,+ targets: [{ file: 0, touch: 'edit', op: 'create' }],+ },+ {+ seq: 3,+ t: 300,+ kind: 'error',+ agent: 'main',+ err: true,+ source: 'tool',+ errClass: 'timeout',+ },+ {+ seq: 4,+ t: 400,+ kind: 'exec',+ agent: 'main',+ err: false,+ tool: 'gh',+ vcs: { provider: 'github', action: 'pr_create', number: 1 },+ },+ ],+ }).events;+ const totals = recomputeTotals(events);+ expect(totals.calls).toBe(2); // edit + exec, not llm/user/error+ expect(totals.requests).toBe(1);+ expect(totals.errors).toBe(1);+ expect(totals.errorsBySource).toEqual({ tool: 1 });+ expect(totals.errorsByClass).toEqual({ timeout: 1 });+ expect(totals.prsCreated).toBe(1);+ expect(totals.filesCreated).toBe(1);+ expect(totals.filesTouched).toBe(1);+ expect(totals.subagents).toBe(0);+ });+});++describe('describeEvent for failed hooks', () => {+ const title = (e: Record<string, unknown>) => {+ const m = makeMap([{ ...e, kind: 'error', err: true, source: 'hook' }]);+ return describeEvent(m, m.events[0]).title;+ };++ it('names the hook and whether it blocked', () => {+ expect(title({ errClass: 'hook_error', hook: 'PostToolUse:Bash' })).toBe('PostToolUse:Bash hook error');+ expect(title({ errClass: 'hook_blocking', hook: 'Stop' })).toBe('Stop hook blocked');+ expect(title({ errClass: 'hook_error' })).toBe('Hook error');+ });+});++describe('shiftStartedAt', () => {+ it('moves a valid timestamp forward as ISO', () => {+ expect(shiftStartedAt('2026-09-10T01:00:00Z', 6000)).toBe(+ '2026-09-10T01:00:06.000Z'+ );+ });++ it('returns an unparseable timestamp unchanged instead of throwing', () => {+ expect(shiftStartedAt('not a date', 6000)).toBe('not a date');+ expect(shiftStartedAt('', 0)).toBe('');+ });+});diff --git a/viewer/src/core/sessionMapModel.ts b/viewer/src/core/sessionMapModel.tsnew file mode 100644index 0000000..25f3c7c--- /dev/null+++ b/viewer/src/core/sessionMapModel.ts@@ -0,0 +1,1469 @@+/**+ * Pure model for the Session Explorer: tree building, radial layout, playhead+ * state, review metrics and event descriptions. No React, no DOM, so every+ * rule here is unit-tested in `sessionMapModel.test.ts`.+ */+import type {+ FileOp,+ SessionMap,+ SessionMapAgent,+ SessionMapEvent,+} from './schema';++export type NodeType =+ | 'root'+ | 'repo'+ | 'dir'+ | 'file'+ | 'group'+ | 'place'+ | 'server'+ | 'mcptool'+ | 'skill'+ | 'agent'+ | 'web'+ | 'errsrc'+ | 'errclass'+ // The model that drove each request, and what the session produced+ | 'model'+ | 'outgroup'+ | 'output';++export interface TreeNode {+ id: string;+ name: string;+ type: NodeType;+ children: TreeNode[];+ parent: TreeNode | null;+ depth: number;+ /** repo-relative path, files only */+ path?: string;+ repoName?: string;+ /** error source, errsrc/errclass nodes only */+ src?: ErrorSource;+ /** output event kind, output nodes only (drives the node colour) */+ kind?: string;+ /** angle (radians) and radius from layoutTree */+ a: number;+ r: number;+ x: number;+ y: number;+}++export interface SessionTree {+ root: TreeNode;+ /** every id, including ids folded away by chain collapsing, -> canonical node */+ byId: Map<string, TreeNode>;+ leaves: TreeNode[];+ maxDepth: number;+}++/** 1 = seen (hit), 2 = read, 3 = edit. Non-file nodes carry no level. */+export type TouchLevel = 1 | 2 | 3;+export const TOUCH_LEVEL: Record<'hit' | 'read' | 'edit', TouchLevel> = {+ hit: 1,+ read: 2,+ edit: 3,+};++export interface NodeRef {+ id: string;+ lvl?: TouchLevel;+ /** the error-class node an errored event lights */+ errNode?: boolean;+ /** this event failed while touching this node */+ failed?: boolean;+ /** counted and coloured, but not part of the playback trail or the active+ * label set (model nodes: every request lights one) */+ passive?: boolean;+}++const GROUP_ORDER: Partial<Record<NodeType, number>> = { repo: 0, group: 1 };++// --- signal vocabulary ---------------------------------++export type ErrorSource = 'tool' | 'mcp' | 'llm' | 'hook' | 'orchestration';+export const ERROR_SOURCES: ErrorSource[] = [+ 'tool',+ 'mcp',+ 'llm',+ 'hook',+ 'orchestration',+];+export const ERROR_SOURCE_LABEL: Record<ErrorSource, string> = {+ tool: 'Tool call',+ mcp: 'MCP',+ llm: 'LLM / API',+ hook: 'Hook',+ orchestration: 'Agent orchestration',+};+export const ERROR_CLASS_LABEL: Record<string, string> = {+ exit_code: 'non-zero exit',+ timeout: 'timeout',+ not_found: 'not found',+ validation: 'invalid input',+ permission_denied: 'permission denied',+ blocked: 'blocked',+ stale_file: 'stale file',+ model_unavailable: 'model unavailable',+ rate_limit: 'rate limited',+ api_error: 'API error',+ interrupted: 'interrupted by user',+ no_result: 'no result (killed)',+ spend_limit: 'spend limit hit',+ usage_limit: 'usage limit hit',+ server_error: 'server error',+ overloaded: 'overloaded',+ auth: 'auth failed',+ bad_request: 'bad request',+ refusal_fallback: 'refusal, model fallback',+ hook_blocking: 'hook blocked',+ hook_error: 'hook failed',+ subagent_failed: 'subagent failed',+ subagent_killed: 'subagent killed',+ other: 'other error',+};+export const DELAY_CAUSE_LABEL: Record<string, string> = {+ tool: 'slow tool call',+ subagent: 'slow subagent',+ llm: 'slow LLM response',+ stall: 'stall (no activity)',+};+/** Output kinds. Each is a confirmed annotation the CLI+ * emits next to the tool call that produced it, so none counts as a call. */+export const OUTPUT_KINDS = new Set([+ 'commit',+ 'pr_merge',+ 'pr_close',+ 'pr_comment',+ 'ticket',+ 'artifact',+ 'skill_write',+]);++/** Kinds that are not tool calls (contract: `calls` excludes these). */+export const NON_CALL = new Set([+ 'llm',+ 'user',+ 'compaction',+ 'error',+ 'delay',+ 'model_switch',+ ...OUTPUT_KINDS,+]);++/** An output of the session: an output kind, or a confirmed PR+ * creation (recorded on the creating tool call's `vcs`). */+export const isOutputEvent = (e: SessionMapEvent): boolean =>+ OUTPUT_KINDS.has(e.kind) || e.vcs?.action === 'pr_create';++type OutputBucket = 'github' | 'tickets' | 'artifacts' | 'skills';+const OUTPUT_BUCKET_LABEL: Record<OutputBucket, string> = {+ github: 'GitHub',+ tickets: 'tickets',+ artifacts: 'artifacts',+ skills: 'skills written',+};++/** Where an output event sits on the map: bucket, stable node id and label.+ * Every event on the same PR (opened, commented, merged, closed) lands on+ * one `pr:` node so the PR reads as one thing that happened to it. */+export function outputNodeOf(+ e: SessionMapEvent,+ i: number+): { bucket: OutputBucket; id: string; name: string } | null {+ const prNum = e.number ?? e.vcs?.number;+ const prRepo = e.repo ?? e.vcs?.repo ?? '';+ if (+ e.kind === 'pr_merge' ||+ e.kind === 'pr_close' ||+ e.kind === 'pr_comment' ||+ e.vcs?.action === 'pr_create'+ ) {+ const key = prNum != null ? `${prRepo}#${prNum}` : `seq${i}`;+ return {+ bucket: 'github',+ id: `pr:${key}`,+ name: prNum != null ? `PR #${prNum}` : 'pull request',+ };+ }+ switch (e.kind) {+ case 'commit':+ return {+ bucket: 'github',+ id: `commit:${e.sha ?? `seq${i}`}`,+ name: e.sha ? `commit ${e.sha.slice(0, 7)}` : 'commit',+ };+ case 'ticket':+ return {+ bucket: 'tickets',+ id: `ticket:${e.id ?? `seq${i}`}`,+ name: e.id ?? `${e.tracker ?? 'ticket'} ${e.action ?? ''}`.trim(),+ };+ case 'artifact':+ return {+ bucket: 'artifacts',+ id: `artifact:${e.title ?? `seq${i}`}`,+ name: e.title ?? 'artifact',+ };+ case 'skill_write':+ return {+ bucket: 'skills',+ id: `skillw:${e.name ?? `seq${i}`}`,+ name: e.name ?? 'skill',+ };+ default:+ return null;+ }+}++const isErrorSource = (v: unknown): v is ErrorSource =>+ typeof v === 'string' && (ERROR_SOURCES as string[]).includes(v);++/** Error source per contract: `error.source`; else `mcp` for MCP events,+ * `orchestration` for subagent events, `tool` otherwise. */+export function errSource(e: SessionMapEvent): ErrorSource {+ if (e.kind === 'error') return isErrorSource(e.source) ? e.source : 'tool';+ if (e.kind === 'mcp') return 'mcp';+ if (e.kind === 'subagent') return 'orchestration';+ return 'tool';+}++export const errClassOf = (e: SessionMapEvent): string => e.errClass || 'other';+export const errClassLabel = (cls: string): string =>+ ERROR_CLASS_LABEL[cls] ?? cls;++/** "PostToolUse:Bash hook error" or "Stop hook blocked" for a failed hook, so a+ * row names the hook instead of "error". Undefined for any other event. */+export const hookErrorTitle = (e: SessionMapEvent): string | undefined => {+ if (e.source !== 'hook') return undefined;+ const verdict = e.errClass === 'hook_blocking' ? 'blocked' : 'error';+ return `${e.hook ? `${e.hook} hook` : 'Hook'} ${verdict}`;+};++/** Context sent with one LLM request: fresh + cache write + cache read. */+export const ctxOf = (e: SessionMapEvent): number =>+ (e.in ?? 0) + (e.cw ?? 0) + (e.cr ?? 0);++// --- PR creation, tool categories, file ops, outcome, agent lens+// ----------------------------------------------------------------------------++/** `events[].cat`: closed vocabulary for the tool-category breakdown.+ * `test` and `build` share the base `verify` kind and land in the same+ * label/colour bucket (contract). */+export type ToolCategory =+ | 'file'+ | 'shell'+ | 'vcs'+ | 'test'+ | 'build'+ | 'cloud'+ | 'http'+ | 'fs'+ | 'package'+ | 'mcp'+ | 'subagent'+ | 'skill'+ | 'web'+ | 'tool';++export const CAT_LABEL: Record<ToolCategory, string> = {+ file: 'File',+ shell: 'Shell',+ vcs: 'Git / VCS',+ test: 'Test / verify',+ build: 'Test / verify',+ cloud: 'Cloud / infra',+ http: 'HTTP',+ fs: 'Filesystem',+ package: 'Package manager',+ mcp: 'MCP (other)',+ subagent: 'Subagent',+ skill: 'Skill',+ web: 'Web',+ tool: 'Other tool',+};+const isToolCategory = (v: unknown): v is ToolCategory =>+ typeof v === 'string' && v in CAT_LABEL;+export const catLabel = (cat: string): string =>+ isToolCategory(cat) ? CAT_LABEL[cat] : cat;++/** `targets[].op` / `files[].op` glyph and past-tense label. */+export const OP_GLYPH: Record<FileOp, string> = {+ create: '+',+ modify: '~',+ delete: '−',+ 'rename-from': '→',+ 'rename-to': '→',+};+export const OP_LABEL: Record<FileOp, string> = {+ create: 'created',+ modify: 'modified',+ delete: 'deleted',+ 'rename-from': 'renamed from',+ 'rename-to': 'renamed to',+};++/** `session.outcome` / `agents[].outcome`: closed 7-way vocabulary. */+export type SessionOutcome =+ | 'pr_created'+ | 'verified'+ | 'completed'+ | 'blocked'+ | 'unresolved_errors'+ | 'interrupted'+ | 'incomplete';++export interface OutcomeMeta {+ label: string;+ /** shadcn Badge variant. `success` is a genuine terminal status (PR+ * opened / verified), not a positive metric, so it is the documented+ * exception to the rule that positive metrics use the brand badge. */+ variant: 'success' | 'secondary' | 'error' | 'warning' | 'outline';+}+export const OUTCOME_META: Record<SessionOutcome, OutcomeMeta> = {+ pr_created: { label: 'PR opened', variant: 'success' },+ verified: { label: 'Verified', variant: 'success' },+ completed: { label: 'Completed', variant: 'secondary' },+ blocked: { label: 'Blocked', variant: 'error' },+ unresolved_errors: { label: 'Unresolved errors', variant: 'error' },+ interrupted: { label: 'Interrupted', variant: 'warning' },+ incomplete: { label: 'Incomplete', variant: 'outline' },+};+const isSessionOutcome = (v: unknown): v is SessionOutcome =>+ typeof v === 'string' && v in OUTCOME_META;+export const outcomeMeta = (outcome: string | undefined | null): OutcomeMeta =>+ isSessionOutcome(outcome)+ ? OUTCOME_META[outcome]+ : { label: outcome ?? 'Unknown', variant: 'outline' };++/** `events[].vcs.action`: open vocabulary (git subcommand, or+ * `<noun>_<verb>` for gh/glab); the three PR-creation states are closed. */+const VCS_ACTION_LABEL: Record<string, string> = {+ pr_create: 'opened a pull request',+ pr_create_attempt: 'tried to open a pull request',+ pr_create_failed: 'failed to open a pull request',+ pr_merge: 'merged',+ pr_view: 'viewed',+ pr_checks: 'checked CI status',+ commit: 'committed',+ push: 'pushed',+ pull: 'pulled',+ fetch: 'fetched',+ checkout: 'checked out a branch',+ branch: 'branched',+ merge: 'merged',+ rebase: 'rebased',+ status: 'checked status',+ diff: 'diffed',+ log: 'read the log',+ add: 'staged files',+ reset: 'reset',+ tag: 'tagged',+ clone: 'cloned',+ worktree: 'used a worktree',+ api: 'called the API',+ api_graphql: 'called the GraphQL API',+};+export const vcsActionLabel = (action: string): string =>+ VCS_ACTION_LABEL[action] ?? action.replace(/_/g, ' ');++export function subagentOrdinal(map: SessionMap): Map<string, number> {+ const out = new Map<string, number>();+ let k = 0;+ for (const a of map.agents) if (a.id !== 'main') out.set(a.id, ++k);+ return out;+}++export function agentLabel(+ map: SessionMap,+ agentId: string,+ ordinals: Map<string, number> = subagentOrdinal(map)+): string {+ if (agentId === 'main') return 'Main agent';+ const a = map.agents.find((x) => x.id === agentId);+ const k = ordinals.get(agentId);+ const type = a?.subagentType || 'subagent';+ return k ? `Sub ${k}: ${type}` : type;+}++export function buildTree(map: SessionMap): SessionTree {+ const root: TreeNode = mkNode('root', 'session', 'root', null);+ const byId = new Map<string, TreeNode>([['root', root]]);+ const add = (+ parent: TreeNode,+ id: string,+ name: string,+ type: NodeType,+ extra: Partial<TreeNode> = {}+ ): TreeNode => {+ const existing = byId.get(id);+ if (existing) return existing;+ const n = { ...mkNode(id, name, type, parent), ...extra };+ parent.children.push(n);+ byId.set(id, n);+ return n;+ };+ const repoName = new Map(map.repos.map((r) => [r.id, r.name]));+ for (const r of map.repos) add(root, `repo:${r.id}`, r.name, 'repo');+ for (const f of map.files) {+ let p = byId.get(`repo:${f.repo}`);+ if (!p) p = add(root, `repo:${f.repo}`, f.repo, 'repo');+ const parts = f.path.split('/').filter(Boolean);+ let acc = f.repo;+ for (let i = 0; i < parts.length - 1; i++) {+ acc += `/${parts[i]}`;+ p = add(p, `dir:${acc}`, parts[i], 'dir');+ }+ add(p, `file:${f.id}`, parts[parts.length - 1] ?? f.path, 'file', {+ path: f.path,+ repoName: repoName.get(f.repo) ?? f.repo,+ });+ }+ const group = (id: string, name: string) => add(root, id, name, 'group');+ for (const e of map.events) {+ for (const t of e.targets ?? []) {+ if (t.scope && t.label) {+ add(+ group('g:outside', 'outside repos'),+ `place:${t.label}`,+ t.label,+ 'place'+ );+ }+ }+ if (e.kind === 'mcp' && e.server) {+ const s = add(+ group('g:mcp', 'MCP'),+ `srv:${e.server}`,+ e.server,+ 'server'+ );+ add(s, `mcp:${e.server}/${e.tool ?? ''}`, e.tool ?? 'tool', 'mcptool');+ }+ if (e.kind === 'skill' && e.skill) {+ add(group('g:skill', 'skills'), `skill:${e.skill}`, e.skill, 'skill');+ }+ if (e.kind === 'web' && e.host) {+ add(group('g:web', 'web'), `web:${e.host}`, e.host, 'web');+ }+ if (e.err) {+ const src = errSource(e);+ const cls = errClassOf(e);+ const sn = add(+ group('g:errors', 'errors'),+ `errsrc:${src}`,+ ERROR_SOURCE_LABEL[src],+ 'errsrc',+ { src }+ );+ add(sn, `errc:${src}/${cls}`, errClassLabel(cls), 'errclass', { src });+ }+ }+ map.events.forEach((e, i) => {+ if ((e.kind === 'llm' || e.kind === 'model_switch') && (e.model || e.to)) {+ const m = (e.kind === 'model_switch' ? e.to : e.model) as string;+ add(group('g:models', 'models'), `model:${m}`, m, 'model');+ }+ const out = isOutputEvent(e) ? outputNodeOf(e, i) : null;+ if (out) {+ const b = add(+ group('g:outputs', 'outputs'),+ `outg:${out.bucket}`,+ OUTPUT_BUCKET_LABEL[out.bucket],+ 'outgroup'+ );+ add(b, out.id, out.name, 'output', {+ kind: e.vcs?.action === 'pr_create' ? 'pr_create' : e.kind,+ });+ }+ });+ const ordinals = subagentOrdinal(map);+ for (const a of map.agents) {+ if (a.id === 'main') continue;+ add(+ group('g:agents', 'subagents'),+ `agent:${a.id}`,+ agentLabel(map, a.id, ordinals),+ 'agent'+ );+ }++ // Collapse single-child dir chains (a/b/c with nothing beside b) into one+ // node so deep monorepo paths do not eat the radius. Folded ids keep+ // resolving to the surviving node.+ const aliasOf = new Map<TreeNode, string[]>();+ const compress = (n: TreeNode) => {+ for (const c of n.children) compress(c);+ if (+ n.type === 'dir' &&+ n.children.length === 1 &&+ n.children[0].type === 'dir'+ ) {+ const c = n.children[0];+ n.name = `${n.name}/${c.name}`;+ n.children = c.children;+ for (const k of n.children) k.parent = n;+ const folded = [c.id, ...(aliasOf.get(c) ?? [])];+ for (const id of folded) byId.set(id, n);+ aliasOf.set(n, [...(aliasOf.get(n) ?? []), ...folded]);+ }+ };+ compress(root);++ // repos, then groups; the errors group always last+ root.children.sort(+ (a, b) =>+ (GROUP_ORDER[a.type] ?? 2) - (GROUP_ORDER[b.type] ?? 2) ||+ Number(a.id === 'g:errors') - Number(b.id === 'g:errors')+ );++ let maxDepth = 0;+ const leaves: TreeNode[] = [];+ const walk = (n: TreeNode, d: number) => {+ n.depth = d;+ maxDepth = Math.max(maxDepth, d);+ if (!n.children.length && n !== root) leaves.push(n);+ for (const c of n.children) walk(c, d + 1);+ };+ walk(root, 0);+ return { root, byId, leaves, maxDepth };+}++function mkNode(+ id: string,+ name: string,+ type: NodeType,+ parent: TreeNode | null+): TreeNode {+ return {+ id,+ name,+ type,+ children: [],+ parent,+ depth: 0,+ a: 0,+ r: 0,+ x: 0,+ y: 0,+ };+}++/** Internal nodes start on this fraction of R so group labels do not pile up+ * at the centre, and end at INNER_MAX; leaves sit on the outer ring R. */+export const INNER_MIN = 0.32;+export const INNER_MAX = 0.78;++/**+ * Radial cluster layout. Every leaf sits on the outer ring (where there is+ * circumference for labels); internal nodes spread from 0.32R to 0.78R by+ * depth. A small angular gap separates top-level branches. Mutates the nodes+ * and returns them in pre-order.+ */+export function layoutTree(tree: SessionTree, R: number): TreeNode[] {+ const { root } = tree;+ const top = root.children;+ const leafCount = (n: TreeNode): number =>+ n.children.length ? n.children.reduce((s, c) => s + leafCount(c), 0) : 1;+ let slots = 0;+ for (const c of top) slots += leafCount(c) + 1.2;+ const unit = (2 * Math.PI) / Math.max(slots, 1);+ let a = -Math.PI / 2 + unit * 0.6;+ const place = (n: TreeNode) => {+ if (!n.children.length) {+ n.a = a;+ a += unit;+ return;+ }+ for (const c of n.children) place(c);+ n.a = (n.children[0].a + n.children[n.children.length - 1].a) / 2;+ };+ for (const c of top) {+ place(c);+ a += unit * 1.2;+ }+ let maxInternal = 1;+ const md = (n: TreeNode) => {+ if (n.children.length && n !== root)+ maxInternal = Math.max(maxInternal, n.depth);+ for (const c of n.children) md(c);+ };+ md(root);+ const step = (R * (INNER_MAX - INNER_MIN)) / Math.max(maxInternal - 1, 1);+ const all: TreeNode[] = [];+ const walk = (n: TreeNode) => {+ n.r =+ n === root+ ? 0+ : n.children.length+ ? R * INNER_MIN + (n.depth - 1) * step+ : R;+ n.x = Math.cos(n.a) * n.r;+ n.y = Math.sin(n.a) * n.r;+ all.push(n);+ for (const c of n.children) walk(c);+ };+ walk(root);+ return all;+}++/** Canonical map nodes each event touches (files, places, MCP tool, skill,+ * web host, spawned subagent, and the error class when the event failed). */+export function nodeRefsFor(+ e: SessionMapEvent,+ tree: SessionTree,+ i = -1+): NodeRef[] {+ const out: NodeRef[] = [];+ const get = (id: string) => tree.byId.get(id)?.id ?? null;+ for (const t of e.targets ?? []) {+ const id = t.scope+ ? t.label+ ? get(`place:${t.label}`)+ : null+ : t.file != null+ ? get(`file:${t.file}`)+ : null;+ if (id) out.push({ id, lvl: TOUCH_LEVEL[t.touch] });+ }+ let extra: string | null = null;+ if (e.kind === 'mcp') extra = get(`mcp:${e.server}/${e.tool ?? ''}`);+ else if (e.kind === 'skill') extra = get(`skill:${e.skill}`);+ else if (e.kind === 'web') extra = get(`web:${e.host}`);+ else if (e.kind === 'subagent' && e.child) extra = get(`agent:${e.child}`);+ if (extra) out.push({ id: extra });+ const modelId =+ e.kind === 'llm' && e.model+ ? get(`model:${e.model}`)+ : e.kind === 'model_switch' && e.to+ ? get(`model:${e.to}`)+ : null;+ if (modelId) out.push({ id: modelId, passive: e.kind === 'llm' });+ if (isOutputEvent(e)) {+ const o = outputNodeOf(e, i);+ const id = o ? get(o.id) : null;+ if (id) out.push({ id });+ }+ if (e.err) {+ for (const r of out) r.failed = true;+ const id = get(`errc:${errSource(e)}/${errClassOf(e)}`);+ if (id) out.push({ id, errNode: true });+ }+ return out;+}++export function eventNodeRefs(map: SessionMap, tree: SessionTree): NodeRef[][] {+ return map.events.map((e, i) => nodeRefsFor(e, tree, i));+}++export interface NodeState {+ /** highest touch level so far (2 when the node has no levels, e.g. MCP) */+ lvl: TouchLevel;+ cnt: number;+ first: number;+ last: number;+ /** events that failed at this node */+ err: number;+}++/** Per-node touch state for events [0..p]. */+export function stateAt(refs: NodeRef[][], p: number): Map<string, NodeState> {+ const st = new Map<string, NodeState>();+ for (let i = 0; i <= p && i < refs.length; i++) {+ for (const x of refs[i]) {+ let s = st.get(x.id);+ if (!s) {+ s = { lvl: 1, cnt: 0, first: i, last: i, err: 0 };+ st.set(x.id, s);+ }+ s.cnt++;+ s.last = i;+ if (x.failed) s.err++;+ const lvl = x.lvl ?? 2;+ if (lvl > s.lvl) s.lvl = lvl;+ }+ }+ return st;+}++/** The ~`limit` most recently touched distinct nodes at the playhead. These+ * get full colour and labels; everything touched earlier renders gray. */+export function activeSet(+ refs: NodeRef[][],+ p: number,+ limit = 10+): Set<string> {+ const active = new Set<string>();+ for (+ let i = Math.min(p, refs.length - 1);+ i >= 0 && active.size < limit;+ i--+ ) {+ for (const x of refs[i]) {+ if (x.passive) continue;+ active.add(x.id);+ if (active.size >= limit) break;+ }+ }+ return active;+}++/** The latest event at or before `p` that touches a node (passive refs,+ * e.g. an LLM request's model, don't count): its index and node ids. The+ * map lights this one step, so across the LLM requests and prompts between+ * two touches it stays on the last real one instead of going blank. */+export function lastTouch(+ refs: NodeRef[][],+ p: number+): { i: number; ids: string[] } | null {+ for (let i = Math.min(p, refs.length - 1); i >= 0; i--) {+ const ids = refs[i].filter((x) => !x.passive).map((x) => x.id);+ if (ids.length) return { i, ids };+ }+ return null;+}++/** Nodes (and their ancestors) touched up to the playhead. */+export function litSet(+ tree: SessionTree,+ st: Map<string, NodeState>+): Set<string> {+ const lit = new Set<string>();+ for (const id of st.keys()) {+ let q: TreeNode | null | undefined = tree.byId.get(id);+ while (q && !lit.has(q.id)) {+ lit.add(q.id);+ q = q.parent;+ }+ }+ return lit;+}++export function ancestorsOf(+ tree: SessionTree,+ ids: Iterable<string>+): Set<string> {+ const out = new Set<string>();+ for (const id of ids) {+ let q: TreeNode | null | undefined = tree.byId.get(id);+ while (q) {+ out.add(q.id);+ q = q.parent;+ }+ }+ return out;+}++/** Up to `limit` recent events that touched a node, oldest first, for the+ * trail. Each item is the event index and its first node id. */+export function recentTargets(+ refs: NodeRef[][],+ p: number,+ limit = 9+): { i: number; id: string }[] {+ const out: { i: number; id: string }[] = [];+ for (+ let i = Math.min(p, refs.length - 1);+ i >= 0 && out.length < limit;+ i--+ ) {+ const x = refs[i].find((r) => !r.errNode && !r.passive);+ if (x) out.push({ i, id: x.id });+ }+ return out.reverse();+}++function isUnder(tree: SessionTree, id: string, ancestor: TreeNode): boolean {+ let q: TreeNode | null | undefined = tree.byId.get(id);+ while (q) {+ if (q === ancestor) return true;+ q = q.parent;+ }+ return false;+}++/** Next event after `p` (wrapping) that touches `nodeId` or anything under it. */+export function nextTouchOf(+ tree: SessionTree,+ refs: NodeRef[][],+ p: number,+ nodeId: string+): number | null {+ const node = tree.byId.get(nodeId);+ if (!node) return null;+ const hit = (i: number) => refs[i].some((x) => isUnder(tree, x.id, node));+ for (let i = p + 1; i < refs.length; i++) if (hit(i)) return i;+ for (let i = 0; i <= p && i < refs.length; i++) if (hit(i)) return i;+ return null;+}++export type JumpKind =+ | 'edit'+ | 'err'+ | 'user'+ | 'subagent'+ | 'delay'+ | 'retry'+ | 'compaction'+ | 'out';++const JUMP_TEST: Record<JumpKind, (e: SessionMapEvent) => boolean> = {+ edit: (e) => e.kind === 'edit',+ err: (e) => e.err,+ user: (e) => e.kind === 'user',+ subagent: (e) => e.kind === 'subagent',+ delay: (e) => e.kind === 'delay',+ retry: (e) => e.retryOf != null,+ compaction: (e) => e.kind === 'compaction',+ out: isOutputEvent,+};++/** Next event after `p` (wrapping) matching the jump kind, or null. */+export function findNext(+ events: SessionMapEvent[],+ p: number,+ kind: JumpKind+): number | null {+ return findNextWhere(events, p, JUMP_TEST[kind]);+}++/** Next event after `p` (wrapping) passing `test`, or null. */+export function findNextWhere(+ events: SessionMapEvent[],+ p: number,+ test: (e: SessionMapEvent) => boolean+): number | null {+ for (let i = p + 1; i < events.length; i++) if (test(events[i])) return i;+ for (let i = 0; i <= p && i < events.length; i++)+ if (test(events[i])) return i;+ return null;+}++/** A meaningful first frame: just past the first error (else the first+ * edit), else 40% in. */+export function initialPlayhead(events: SessionMapEvent[]): number {+ if (!events.length) return 0;+ const firstErr = events.findIndex((e) => e.err);+ const firstEdit = events.findIndex((e) => e.kind === 'edit');+ const anchor = firstErr > 0 ? firstErr : firstEdit;+ return anchor > 0+ ? Math.min(events.length - 1, anchor + 12)+ : Math.floor(events.length * 0.4);+}++// --- counters / costs ------------------------------------------------------++export const llmTokens = (e: SessionMapEvent): number =>+ (e.in ?? 0) + (e.cw ?? 0) + (e.cr ?? 0) + (e.out ?? 0);++/** Prefix sums of advisory LLM cost: cum[i] = cost of events [0..i]. */+export function cumulativeCost(events: SessionMapEvent[]): Float64Array {+ const cum = new Float64Array(events.length);+ let s = 0;+ events.forEach((e, i) => {+ s += e.cost ?? 0;+ cum[i] = s;+ });+ return cum;+}++export interface PlayheadCounters {+ calls: number;+ requests: number;+ tokens: number;+ cost: number;+ errors: number;+ mcp: number;+ skills: number;+ subagents: number;+ filesRead: number;+ filesEdited: number;+}++export function countersAt(+ events: SessionMapEvent[],+ p: number+): PlayheadCounters {+ const c: PlayheadCounters = {+ calls: 0,+ requests: 0,+ tokens: 0,+ cost: 0,+ errors: 0,+ mcp: 0,+ skills: 0,+ subagents: 0,+ filesRead: 0,+ filesEdited: 0,+ };+ const reads = new Set<number>();+ const edits = new Set<number>();+ for (let i = 0; i <= p && i < events.length; i++) {+ const e = events[i];+ if (e.err) c.errors++;+ if (e.kind === 'llm') {+ c.requests++;+ c.tokens += llmTokens(e);+ c.cost += e.cost ?? 0;+ continue;+ }+ if (NON_CALL.has(e.kind)) continue;+ c.calls++;+ if (e.kind === 'mcp') c.mcp++;+ if (e.kind === 'skill') c.skills++;+ if (e.kind === 'subagent') c.subagents++;+ for (const t of e.targets ?? []) {+ if (t.scope || t.file == null) continue;+ if (t.touch === 'edit') edits.add(t.file);+ else if (t.touch === 'read') reads.add(t.file);+ }+ }+ c.filesRead = reads.size;+ c.filesEdited = edits.size;+ return c;+}++// --- review (whole session) -------------------------------------------------++export type VerificationState =+ 'never' | 'after_final_edit' | 'edits_after_verify';++export interface ReviewMetrics {+ errors: number;+ /** edits to a file that was never read first; a first Write that creates+ * the file is not blind */+ blindEdits: number;+ /** files edited 3+ times */+ churnFiles: number;+ /** % of reads that re-read a file unchanged since its last read */+ reReadPct: number;+ verification: VerificationState;+}++const CREATE_TOOLS = new Set(['Write', 'write', 'create_file', 'CreateFile']);++export function reviewMetrics(map: SessionMap): ReviewMetrics {+ const readSoFar = new Set<number>();+ const lastEditAt = new Map<number, number>();+ const lastReadAt = new Map<number, number>();+ let blind = 0;+ let reReads = 0;+ let readsN = 0;+ let errors = 0;+ let lastVerify = -1;+ let lastEdit = -1;+ map.events.forEach((e, i) => {+ if (e.err) errors++;+ if (e.kind === 'verify') lastVerify = i;+ if (e.kind === 'edit') lastEdit = i;+ for (const t of e.targets ?? []) {+ if (t.scope || t.file == null) continue;+ const f = t.file;+ if (t.touch === 'read') {+ readsN++;+ const lr = lastReadAt.get(f);+ const le = lastEditAt.get(f);+ if (lr != null && !(le != null && le > lr)) reReads++;+ lastReadAt.set(f, i);+ readSoFar.add(f);+ } else if (t.touch === 'edit') {+ const creates =+ CREATE_TOOLS.has(e.tool ?? '') &&+ !lastEditAt.has(f) &&+ !readSoFar.has(f);+ if (!readSoFar.has(f) && !creates) blind++;+ readSoFar.add(f);+ lastEditAt.set(f, i);+ }+ }+ });+ return {+ errors,+ blindEdits: blind,+ churnFiles: map.files.filter((f) => f.edits >= 3).length,+ reReadPct: readsN ? Math.round((100 * reReads) / readsN) : 0,+ verification:+ lastVerify < 0+ ? 'never'+ : lastVerify > lastEdit+ ? 'after_final_edit'+ : 'edits_after_verify',+ };+}++export interface FileCoverage {+ edited: number;+ read: number;+ seen: number;+}++/**+ * Derived from `map.events`, not `map.files[].reads/edits/hits`: those are+ * a document-level aggregate across every agent, so once an agent lens+ * (`deriveLensDoc`) scopes `events` to one lane while leaving the shared+ * `files` array untouched, reading the file records would leak the OTHER+ * agents' touches into this lens's coverage.+ * `seen` counts a file touched only as a dependency (`hit`), never read or+ * edited; a file never touched at all is not counted here at all.+ */+export function fileCoverage(map: SessionMap): FileCoverage {+ const touch = new Map<number, { read: number; edit: number; hit: number }>();+ for (const e of map.events) {+ for (const t of e.targets ?? []) {+ if (t.scope || t.file == null) continue;+ const c = touch.get(t.file) ?? { read: 0, edit: 0, hit: 0 };+ c[t.touch]++;+ touch.set(t.file, c);+ }+ }+ let edited = 0;+ let read = 0;+ for (const c of touch.values()) {+ if (c.edit > 0) edited++;+ else if (c.read > 0) read++;+ }+ return { edited, read, seen: touch.size - edited - read };+}++export function touchesOfFile(+ map: SessionMap,+ fileId: number+): { read: number; edit: number; hit: number } {+ const c = { read: 0, edit: 0, hit: 0 };+ for (const e of map.events) {+ for (const t of e.targets ?? [])+ if (!t.scope && t.file === fileId) c[t.touch]++;+ }+ return c;+}++// --- derived documents ------------------------------------------------------++/**+ * `startedAt` moved forward by `offsetMs`, as ISO. The schema only requires a+ * string, so an unparseable stamp (an imported map can carry anything) is+ * returned as-is: `new Date(NaN).toISOString()` throws a RangeError mid-render.+ */+export function shiftStartedAt(startedAt: string, offsetMs: number): string {+ const ms = Date.parse(startedAt);+ return Number.isNaN(ms) ? startedAt : new Date(ms + offsetMs).toISOString();+}++/**+ * The event's sequence number in the document it was derived from, which is+ * the one every reference taken outside the viewer is in terms of.+ *+ * `deriveScopeDoc` and `deriveLensDoc` keep a subset of the events and+ * renumber `seq` so that `seq === index` still holds in the copy. That is+ * what keeps every other index in the copy (`ref`, `retryOf`, `prs[].seq`)+ * consistent, but it also means a reference taken against the full document+ * -- a review comment's causal path, say -- no longer resolves against+ * `seq`: it finds whatever event now sits at that position, or none.+ * Those derivations stamp the original number on `srcSeq` instead.+ *+ * `srcSeq` rides the event schema's `passthrough` rather than being a field+ * of it, because it is the viewer's own and never on the wire; a document+ * that happens to carry one is not trusted to have put a number there. An+ * underived event has none, and its own `seq` is already the answer.+ */+export function srcSeqOf(e: SessionMapEvent): number | null | undefined {+ const src = e.srcSeq;+ return typeof src === 'number' ? src : e.seq;+}++// --- agent lens -------------------------------------++/**+ * Recompute `totals` from an event subset. Used by `deriveLensDoc` so a+ * lens's totals reflect only its own events, never the full document's+ * cross-agent aggregate (the same hazard `fileCoverage` guards against).+ */+export function recomputeTotals(+ events: SessionMapEvent[]+): SessionMap['totals'] {+ const llm = events.filter((e) => e.kind === 'llm');+ const errorsBySource: Record<string, number> = {};+ const errorsByClass: Record<string, number> = {};+ for (const e of events) {+ if (!e.err) continue;+ const src = errSource(e);+ errorsBySource[src] = (errorsBySource[src] ?? 0) + 1;+ const cls = errClassOf(e);+ errorsByClass[cls] = (errorsByClass[cls] ?? 0) + 1;+ }+ const files = new Set<number>();+ const created = new Set<number>();+ const deleted = new Set<number>();+ for (const e of events) {+ for (const t of e.targets ?? []) {+ if (t.scope || t.file == null) continue;+ files.add(t.file);+ if (t.op === 'create') created.add(t.file);+ if (t.op === 'delete') deleted.add(t.file);+ }+ }+ const latencies = events+ .filter((e) => e.kind === 'llm' && e.latency != null)+ .map((e) => e.latency ?? 0)+ .sort((a, b) => a - b);+ const delays = events.filter((e) => e.kind === 'delay');+ const contexts = llm.map((e) => ctxOf(e));+ return {+ calls: events.filter((e) => !NON_CALL.has(e.kind)).length,+ requests: llm.length,+ userTurns: events.filter((e) => e.kind === 'user').length,+ // a lens has no further nesting (contract), so it never has its own+ // subagents even when the full session did+ subagents: 0,+ errors: events.filter((e) => e.err).length,+ tokens: llm.reduce((s, e) => s + ctxOf(e) + (e.out ?? 0), 0),+ costUsd:+ Math.round(llm.reduce((s, e) => s + (e.cost ?? 0), 0) * 10000) / 10000,+ filesTouched: files.size,+ errorsBySource,+ errorsByClass,+ retries: events.filter((e) => e.retryOf != null).length,+ delays: delays.length,+ delayMs: delays.reduce((s, e) => s + (e.ms ?? 0), 0),+ maxContext: Math.max(0, ...contexts),+ compactions: events.filter((e) => e.kind === 'compaction').length,+ llmLatencyP50: latencies.length+ ? latencies[Math.floor(latencies.length / 2)]+ : 0,+ llmLatencyP95: latencies.length+ ? latencies[+ Math.min(latencies.length - 1, Math.floor(latencies.length * 0.95))+ ]+ : 0,+ outputTokens: llm.reduce((s, e) => s + (e.out ?? 0), 0),+ prsCreated: events.filter((e) => e.vcs?.action === 'pr_create').length,+ filesCreated: created.size,+ filesDeleted: deleted.size,+ ...outputTotals(events),+ };+}++export interface OutputTotals {+ commits: number;+ prsMerged: number;+ prsClosed: number;+ prComments: number;+ ticketsCreated: number;+ ticketsUpdated: number;+ artifacts: number;+ skillsCreated: number;+ skillsUpdated: number;+ modelSwitches: number;+}++/** Output counts over an event subset (a task, a model, a lens). */+export function outputTotals(events: SessionMapEvent[]): OutputTotals {+ const n = (test: (e: SessionMapEvent) => boolean) =>+ events.filter(test).length;+ return {+ commits: n((e) => e.kind === 'commit'),+ prsMerged: n((e) => e.kind === 'pr_merge'),+ prsClosed: n((e) => e.kind === 'pr_close'),+ prComments: n((e) => e.kind === 'pr_comment'),+ ticketsCreated: n((e) => e.kind === 'ticket' && e.action === 'create'),+ ticketsUpdated: n((e) => e.kind === 'ticket' && e.action !== 'create'),+ artifacts: n((e) => e.kind === 'artifact'),+ skillsCreated: n((e) => e.kind === 'skill_write' && e.action === 'create'),+ skillsUpdated: n((e) => e.kind === 'skill_write' && e.action !== 'create'),+ modelSwitches: n((e) => e.kind === 'model_switch'),+ };+}++/**+ * Agent lens (viewer-only, no change to the map): scope the whole explorer to one+ * agent's own events, as if it were the primary session — same map/timeline+ * code, a filtered + reindexed event list. `retryOf`/`ref` are remapped to+ * the new local sequence numbers (both always resolve within one agent's+ * own lane by construction). A subagent has no further nesting in this data+ * model, so a lens's own `agents` list is always just itself.+ *+ * `'main'` (or an agent id with no events of its own) returns `full`+ * unchanged, so callers can pass the lens id straight through without a+ * branch.+ */+export function deriveLensDoc(full: SessionMap, agentId: string): SessionMap {+ if (agentId === 'main') return full;+ const src: { e: SessionMapEvent; oldIndex: number }[] = [];+ full.events.forEach((e, oldIndex) => {+ if (e.agent === agentId) src.push({ e, oldIndex });+ });+ if (!src.length) return full;++ // Keyed by each event's position in `full.events`, not its wire `seq`+ // (schema: optional - a map may omit it). The contract guarantees+ // seq === index, and `retryOf`/`ref` are seq references, so position is+ // the same identifier without depending on `seq` actually being present.+ const oldToNew = new Map<number, number>();+ src.forEach(({ oldIndex }, i) => oldToNew.set(oldIndex, i));+ const t0 = src[0].e.t;+ const events = src.map(({ e, oldIndex }, i) => {+ const ev: SessionMapEvent = {+ ...e,+ seq: i,+ // Set once, by the first derivation: a lens over an already-scoped+ // document must still name the full document's sequence number.+ srcSeq: typeof e.srcSeq === 'number' ? e.srcSeq : (e.seq ?? oldIndex),+ t: e.t - t0,+ agent: 'main',+ };+ if (ev.retryOf != null) ev.retryOf = oldToNew.get(ev.retryOf);+ if (ev.ref != null) ev.ref = oldToNew.get(ev.ref);+ return ev;+ });+ const lastEvent = events[events.length - 1];+ const durationMs = lastEvent ? lastEvent.t : 0;+ const meta = full.agents.find((a) => a.id === agentId);+ const prs = full.prs.filter((pr) =>+ src.some(({ oldIndex }) => oldIndex === pr.seq)+ );++ // Reduced approximation of the map's outcome heuristic, used only when+ // deriving an agent-lens view; it does not attempt `verified`,+ // `blocked` or `incomplete`, which need signal only the producer has.+ const tail = events.slice(-12);+ const outcome: SessionOutcome = events.some(+ (e) => e.vcs?.action === 'pr_create'+ )+ ? 'pr_created'+ : tail.some((e) => e.err && e.errClass === 'interrupted')+ ? 'interrupted'+ : tail.filter((e) => e.err).length >= 2+ ? 'unresolved_errors'+ : 'completed';++ return {+ ...full,+ session: {+ ...full.session,+ id: `${full.session.id}:${agentId}`,+ startedAt: shiftStartedAt(full.session.startedAt, t0),+ durationMs,+ outcome,+ },+ totals: recomputeTotals(events),+ prs,+ agents: [+ {+ id: 'main',+ parent: null,+ kind: meta?.kind ?? 'subagent',+ subagentType: meta?.subagentType,+ launchSeq: meta?.launchSeq,+ start: 0,+ end: durationMs,+ calls: events.filter((e) => !NON_CALL.has(e.kind)).length,+ requests: events.filter((e) => e.kind === 'llm').length,+ tokens: events.reduce(+ (s, e) => (e.kind === 'llm' ? s + ctxOf(e) + (e.out ?? 0) : s),+ 0+ ),+ cost: meta?.cost ?? 0,+ outcome,+ },+ ],+ events,+ };+}++export function leafCount(n: TreeNode): number {+ return n.children.length+ ? n.children.reduce((s, c) => s + leafCount(c), 0)+ : 1;+}++// --- formatting -------------------------------------------------------------++export const fmtTok = (n: number): string =>+ n >= 1e9+ ? `${(n / 1e9).toFixed(1)}B`+ : n >= 1e6+ ? `${(n / 1e6).toFixed(1)}M`+ : n >= 1e3+ ? `${(n / 1e3).toFixed(1)}K`+ : String(Math.round(n));++export const fmtUsd = (n: number): string =>+ `$${n >= 100 ? n.toFixed(0) : n.toFixed(2)}`;++export const fmtBytes = (n: number): string =>+ n >= 1e6+ ? `${(n / 1e6).toFixed(1)} MB`+ : n >= 1e3+ ? `${(n / 1e3).toFixed(1)} KB`+ : `${Math.round(n)} B`;++export const fmtDur = (ms: number): string => {+ const s = Math.max(0, Math.round(ms / 1000));+ const h = Math.floor(s / 3600);+ const m = Math.floor((s % 3600) / 60);+ const x = s % 60;+ if (h) return `${h}h ${String(m).padStart(2, '0')}m`;+ if (m) return `${m}m ${String(x).padStart(2, '0')}s`;+ return `${(Math.max(0, ms) / 1000).toFixed(1)}s`;+};++/** HH:MM:SS UTC at `ms` after `iso`. */+export const clockAt = (iso: string, ms: number): string => {+ const base = Date.parse(iso);+ if (Number.isNaN(base)) return '--:--:--';+ return new Date(base + ms).toISOString().slice(11, 19);+};++export const dayLabel = (iso: string): string => {+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return iso;+ return d.toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ weekday: 'short',+ timeZone: 'UTC',+ });+};++// --- event descriptions -----------------------------------------------------++export interface EventDescription {+ title: string;+ detail: string;+}++export function describeEvent(+ map: SessionMap,+ e: SessionMapEvent,+ ordinals?: Map<string, number>+): EventDescription {+ const f = e.targets?.find((t) => !t.scope && t.file != null);+ const fo = f ? map.files.find((x) => x.id === f.file) : undefined;+ const repo = fo+ ? (map.repos.find((r) => r.id === fo.repo)?.name ?? fo.repo)+ : '';+ const place = e.targets?.find((t) => t.scope);+ switch (e.kind) {+ case 'llm':+ return {+ title: `${e.model || 'model'} · ${fmtUsd(e.cost ?? 0)}`,+ detail: `${fmtTok(ctxOf(e))} context in · ${fmtTok(e.out ?? 0)} out${e.latency ? ` · ${fmtDur(e.latency)} latency` : ''}`,+ };+ case 'error':+ return {+ title: hookErrorTitle(e) ?? errClassLabel(errClassOf(e)),+ detail: `${isErrorSource(e.source) ? ERROR_SOURCE_LABEL[e.source] : (e.source ?? 'error')}${e.hook ? ` · ${e.hook}` : ''}${e.retry ? ' · retried' : ''}`,+ };+ case 'delay':+ return {+ title: `${DELAY_CAUSE_LABEL[e.cause ?? ''] ?? 'delay'} · ${fmtDur(e.ms ?? 0)}`,+ detail:+ e.ref != null+ ? `caused by event #${e.ref}`+ : 'no activity on the main agent',+ };+ case 'user': {+ const extras = [+ e.images ? `${e.images} image${e.images > 1 ? 's' : ''}` : '',+ e.urls ? `${e.urls} URL${e.urls > 1 ? 's' : ''}` : '',+ ].filter(Boolean);+ return {+ title: e.task != null ? `User turn · task ${e.task}` : 'User turn',+ detail: `${e.chars ?? 0} chars${extras.length ? ` · ${extras.join(' · ')}` : ''} (text not stored)`,+ };+ }+ case 'model_switch':+ return {+ title: `Model switched to ${e.to ?? 'another model'}`,+ detail: e.from ? `from ${e.from}` : 'model switch',+ };+ case 'commit':+ return {+ title: `Commit ${e.sha ? e.sha.slice(0, 7) : ''}`.trim(),+ detail: `${e.repo ?? ''}${e.files != null ? ` · ${e.files} file${e.files === 1 ? '' : 's'}` : ''}${e.ins != null || e.del != null ? ` · +${e.ins ?? 0} −${e.del ?? 0}` : ''}`,+ };+ case 'pr_merge':+ case 'pr_close':+ case 'pr_comment': {+ const verb =+ e.kind === 'pr_merge'+ ? 'merged'+ : e.kind === 'pr_close'+ ? 'closed without merging'+ : 'commented on';+ return {+ title: `PR ${e.number != null ? `#${e.number} ` : ''}${verb}`,+ detail: e.repo ?? e.url ?? 'pull request',+ };+ }+ case 'ticket':+ return {+ title: `Ticket ${e.action === 'create' ? 'created' : 'updated'}${e.id ? ` · ${e.id}` : ''}`,+ detail: `${e.tracker ?? 'tracker'}${e.tool ? ` · ${e.tool}` : ''}`,+ };+ case 'artifact':+ return {+ title: `Artifact published${e.title ? ` · ${e.title}` : ''}`,+ detail: `${e.bytes != null ? fmtBytes(e.bytes) : 'size unknown'}${e.version != null ? ` · version ${e.version}` : ''}`,+ };+ case 'skill_write':+ return {+ title: `Skill ${e.action === 'create' ? 'created' : 'updated'}${e.name ? ` · ${e.name}` : ''}`,+ detail: 'skill file written',+ };+ case 'compaction':+ return {+ title: `Context compacted${e.trigger ? ` (${e.trigger})` : ''}`,+ detail: `${fmtTok(e.preTokens ?? 0)} → ${fmtTok(e.postTokens ?? 0)} tokens`,+ };+ case 'mcp':+ return {+ title: `${e.server ?? 'MCP'} · ${e.tool ?? ''}`,+ detail: 'MCP call',+ };+ case 'skill':+ return { title: `/${e.skill ?? 'skill'}`, detail: 'Skill invoked' };+ case 'subagent':+ return {+ title: `Subagent · ${e.subagentType || 'general'}`,+ detail: e.child+ ? `spawned ${agentLabel(map, e.child, ordinals)}${e.model ? ` · ${e.model}` : ''}`+ : 'spawned a subagent',+ };+ case 'web':+ return { title: e.host ?? 'web', detail: e.tool ?? 'Web' };+ default: {+ const tool = e.tool ?? e.kind;+ const verb = e.verb ? ` · ${e.verb}` : '';+ if (e.vcs) {+ const prTail =+ e.vcs.action === 'pr_create' && e.vcs.number != null+ ? ` · ${e.vcs.provider} #${e.vcs.number}`+ : '';+ return {+ title: `${vcsActionLabel(e.vcs.action)}${e.vcs.repo ? ` · ${e.vcs.repo}` : ''}${e.vcs.number != null ? ` #${e.vcs.number}` : ''}`,+ detail: `${tool}${verb}${prTail}`,+ };+ }+ if (fo) {+ const op = f?.op;+ return {+ title: `${op ? `${OP_GLYPH[op]} ` : ''}${fo.path.split('/').pop() || fo.path}`,+ detail: `${repo}/${fo.path}${op ? ` · ${OP_LABEL[op]}` : ''}`,+ };+ }+ return {+ title: place?.label ?? e.verb ?? tool,+ detail: `${tool}${verb}`,+ };+ }+ }+}++export function agentById(+ map: SessionMap,+ id: string+): SessionMapAgent | undefined {+ return map.agents.find((a) => a.id === id);+}diff --git a/viewer/src/core/sessionScope.test.ts b/viewer/src/core/sessionScope.test.tsnew file mode 100644index 0000000..b72aab2--- /dev/null+++ b/viewer/src/core/sessionScope.test.ts@@ -0,0 +1,621 @@+import { describe, expect, it } from 'vitest';+import {+ SESSION_MAP_SCHEMA_V1,+ sessionMapSchema,+ type SessionMap,+} from './schema';+import {+ buildTree,+ deriveLensDoc,+ describeEvent,+ eventNodeRefs,+ findNext,+ outputTotals,+ recomputeTotals,+} from './sessionMapModel';+import {+ EMPTY_SCOPE,+ LANE_KEYS,+ deriveScopeDoc,+ eventModels,+ hasReplayEvents,+ modelUsage,+ normalizeScope,+ scopeForSession,+ scopedModelUsage,+ sessionTasks,+ stampTasks,+ summarizeEvents,+ taskNoun,+ timelineLanes,+} from './sessionScope';++type RawEvent = Record<string, unknown> & { kind: string };++function makeMap(+ events: RawEvent[],+ overrides: Record<string, unknown> = {}+): SessionMap {+ return sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: {+ id: 'local:claude-code:s1',+ agentTool: 'claude-code',+ startedAt: '2026-09-23T15:44:00Z',+ durationMs: 1_080_000,+ models: ['opus-5.5'],+ },+ totals: { calls: 0, requests: 0 },+ repos: [{ id: 'r0', name: 'dashboard' }],+ files: [{ id: 0, repo: 'r0', path: 'src/proxy.ts' }],+ agents: [+ { id: 'main', parent: null, kind: 'main' },+ { id: 'sub1', parent: 'main', kind: 'subagent', subagentType: 'Explore' },+ ],+ prs: [],+ events: events.map((e, i) => ({+ seq: i,+ t: i * 1000,+ agent: 'main',+ ...e,+ })),+ ...overrides,+ });+}++/** A 3-task CSP-fix session: diagnose, fix + open PR, verify + merge. */+const CSP_EVENTS: RawEvent[] = [+ { kind: 'user', chars: 1240, urls: 1 }, // 0 task 1+ { kind: 'llm', model: 'opus-5.5', cost: 0.05, in: 100, out: 20 }, // 1+ { kind: 'read', targets: [{ file: 0, touch: 'read' }] }, // 2+ { kind: 'subagent', child: 'sub1', subagentType: 'Explore' }, // 3+ { kind: 'llm', agent: 'sub1', model: 'haiku-4.5', cost: 0.01 }, // 4+ { kind: 'search', agent: 'sub1' }, // 5+ { kind: 'user', chars: 310, images: 1 }, // 6 task 2+ { kind: 'llm', model: 'opus-5.5', cost: 0.1 }, // 7+ { kind: 'edit', targets: [{ file: 0, touch: 'edit' }] }, // 8+ { kind: 'exec', err: true, errClass: 'exit_code' }, // 9+ { kind: 'exec', retryOf: 9 }, // 10+ {+ kind: 'commit',+ repo: 'dashboard',+ sha: 'a1b2c3d4',+ files: 1,+ ins: 2,+ del: 0,+ }, // 11+ {+ kind: 'exec',+ vcs: {+ provider: 'github',+ action: 'pr_create',+ repo: 'dashboard',+ number: 42,+ },+ }, // 12+ { kind: 'pr_comment', repo: 'dashboard', number: 42 }, // 13+ { kind: 'user', chars: 95 }, // 14 task 3+ { kind: 'model_switch', from: 'opus-5.5', to: 'sonnet-5' }, // 15+ { kind: 'llm', model: 'sonnet-5', cost: 0.02 }, // 16+ { kind: 'pr_merge', repo: 'dashboard', number: 42 }, // 17+ { kind: 'ticket', tracker: 'linear', action: 'update', id: 'ACME-4767' }, // 18+ { kind: 'artifact', title: 'proposal', bytes: 840_000, version: 3 }, // 19+ { kind: 'skill_write', name: 'session-map-directive', action: 'create' }, // 20+];++describe('sessionTasks', () => {+ it('falls back to one task per user turn when the map has no tasks', () => {+ const { taskOf, tasks } = sessionTasks(makeMap(CSP_EVENTS));+ expect(tasks.map((t) => [t.n, t.start, t.end, t.source])).toEqual([+ [1, 0, 5, 'turns'],+ [2, 6, 13, 'turns'],+ [3, 14, 20, 'turns'],+ ]);+ expect(tasks[0].name).toBe('Prompt 1');+ expect(taskOf[9]).toBe(2);+ });++ it('marks a turn task named only when the map titled it', () => {+ const map = makeMap(CSP_EVENTS, {+ tasks: [{ n: 2, name: 'fix the flaky test', source: 'turns' }],+ });+ const { tasks } = sessionTasks(map);+ expect(tasks.map((t) => [t.n, t.name, t.named])).toEqual([+ [1, 'Prompt 1', false],+ [2, 'fix the flaky test', true],+ [3, 'Prompt 3', false],+ ]);+ });++ it('events before the first user turn join task 1; no turns = one task', () => {+ const { taskOf } = sessionTasks(+ makeMap([{ kind: 'read' }, { kind: 'user' }, { kind: 'read' }])+ );+ expect(taskOf).toEqual([1, 1, 1]);+ const one = sessionTasks(makeMap([{ kind: 'read' }, { kind: 'llm' }]));+ expect(one.tasks).toHaveLength(1);+ });++ it('prefers the CLI segmentation (tasks[] start/end seq) and its names', () => {+ const map = makeMap(CSP_EVENTS, {+ tasks: [+ { n: 1, name: 'Diagnose', source: 'segments', startSeq: 0, endSeq: 8 },+ { n: 2, name: 'Ship', source: 'segments', startSeq: 11, endSeq: 20 },+ ],+ });+ const { taskOf, tasks } = sessionTasks(map);+ expect(tasks.map((t) => t.name)).toEqual(['Diagnose', 'Ship']);+ // 9 and 10 fall between windows: carried forward into task 1+ expect(taskOf.slice(8, 12)).toEqual([1, 1, 1, 2]);+ expect(tasks[0].source).toBe('segments');+ });++ it('prefers per-event task stamps over everything else', () => {+ const map = makeMap(+ CSP_EVENTS.map((e, i) => ({ ...e, task: i < 10 ? 1 : 2 })),+ {+ tasks: [+ { n: 1, name: 'A' },+ { n: 2, name: 'B' },+ ],+ }+ );+ const { tasks } = sessionTasks(map);+ expect(tasks.map((t) => [t.n, t.name, t.start, t.end])).toEqual([+ [1, 'A', 0, 9],+ [2, 'B', 10, 20],+ ]);+ });++ it('survives a malformed tasks block (schema drops it)', () => {+ const map = makeMap(CSP_EVENTS, { tasks: 'garbage' });+ expect(map.tasks).toBeUndefined();+ expect(sessionTasks(map).tasks).toHaveLength(3);+ });++ it('stampTasks keeps turn-derived names through reindexing', () => {+ const stamped = stampTasks(makeMap(CSP_EVENTS));+ expect(stamped.events.every((e) => typeof e.task === 'number')).toBe(true);+ const lens = deriveLensDoc(stamped, 'sub1');+ const { tasks } = sessionTasks(lens);+ expect(tasks).toHaveLength(1);+ expect(tasks[0].name).toBe('Prompt 1');+ // the placeholder is regenerated, never persisted as if it were a title+ expect(tasks[0].named).toBe(false);+ expect(tasks[0].source).toBe('turns');+ // already stamped: returned as-is+ expect(stampTasks(stamped)).toBe(stamped);+ });+});++describe('taskNoun', () => {+ it('calls user-turn windows prompts', () => {+ expect(taskNoun([{ source: 'turns' }, { source: 'turns' }])).toEqual({+ one: 'Prompt',+ many: 'Prompts',+ });+ expect(taskNoun([])).toEqual({ one: 'Prompt', many: 'Prompts' });+ });++ it('keeps tasks when any window comes from a segmenter', () => {+ expect(taskNoun([{ source: 'turns' }, { source: 'segments' }])).toEqual({+ one: 'Task',+ many: 'Tasks',+ });+ });+});++describe('models', () => {+ it('attributes every event to the model driving its agent', () => {+ const models = eventModels(makeMap(CSP_EVENTS));+ expect(models[0]).toBe('opus-5.5'); // before the first request: back-filled+ expect(models[2]).toBe('opus-5.5');+ expect(models[5]).toBe('haiku-4.5'); // subagent keeps its own model+ expect(models[15]).toBe('sonnet-5'); // model switch+ expect(models[17]).toBe('sonnet-5'); // after the switch+ });++ it('falls back to the session model when no request names one', () => {+ const models = eventModels(makeMap([{ kind: 'read' }, { kind: 'llm' }]));+ expect(models).toEqual(['opus-5.5', 'opus-5.5']);+ });++ it('modelUsage rolls up requests and cost, most expensive first', () => {+ const u = modelUsage(makeMap(CSP_EVENTS));+ expect(u.map((m) => [m.model, m.requests])).toEqual([+ ['opus-5.5', 2],+ ['sonnet-5', 1],+ ['haiku-4.5', 1],+ ]);+ expect(u[0].cost).toBeCloseTo(0.15);+ });+});++describe('deriveScopeDoc', () => {+ const map = makeMap(CSP_EVENTS);++ it('returns the map itself when nothing is scoped', () => {+ expect(deriveScopeDoc(map, EMPTY_SCOPE)).toBe(map);+ });++ it('scopes to a task window, rebased, with retries remapped', () => {+ const d = deriveScopeDoc(map, { ...EMPTY_SCOPE, task: 2 });+ expect(d.events).toHaveLength(8);+ expect(d.events[0].kind).toBe('user');+ expect(d.events[0].t).toBe(0);+ expect(d.events.every((e, i) => e.seq === i)).toBe(true);+ expect(d.events.every((e) => e.task === 2)).toBe(true);+ // exec retry (old 10 -> old 9) is now 4 -> 3+ expect(d.events[4].retryOf).toBe(3);+ expect(d.session.startedAt).toBe('2026-09-23T15:44:06.000Z');+ expect(d.totals.commits).toBe(1);+ expect(d.totals.prComments).toBe(1);+ expect(d.totals.requests).toBe(1);+ });++ it('keeps an unparseable startedAt instead of throwing', () => {+ const bad = makeMap(+ [{ kind: 'user' }, { kind: 'user', t: 5000 }],+ { session: { ...makeMap([{ kind: 'user' }]).session, startedAt: 'garbage' } }+ );+ const d = deriveScopeDoc(bad, { ...EMPTY_SCOPE, task: 2 });+ expect(d.session.startedAt).toBe('garbage');+ });++ it('drops a retry link whose failed attempt fell out of scope', () => {+ const onlyRetry = deriveScopeDoc(+ makeMap([+ { kind: 'user' },+ { kind: 'exec', err: true },+ { kind: 'user' },+ { kind: 'read', retryOf: 1 },+ ]),+ { ...EMPTY_SCOPE, task: 2 }+ );+ expect(onlyRetry.events.map((e) => e.kind)).toEqual(['user', 'read']);+ expect(onlyRetry.events[1].retryOf).toBeUndefined();+ });++ it('scopes to one model and keeps the task structure', () => {+ const d = deriveScopeDoc(map, { ...EMPTY_SCOPE, model: 'sonnet-5' });+ // user turns stay, sonnet-driven events from the switch on+ expect(d.events.map((e) => e.kind)).toEqual([+ 'user',+ 'user',+ 'user',+ 'model_switch',+ 'llm',+ 'pr_merge',+ 'ticket',+ 'artifact',+ 'skill_write',+ ]);+ expect(d.events[0].task).toBe(1);+ expect(d.agents.map((a) => a.id)).toEqual(['main']);+ expect(d.totals.subagents).toBe(0);+ });++ it('recomputes per-agent rollups inside the scope', () => {+ const d = deriveScopeDoc(map, { ...EMPTY_SCOPE, task: 1 });+ const sub = d.agents.find((a) => a.id === 'sub1');+ expect(sub?.requests).toBe(1);+ expect(sub?.cost).toBeCloseTo(0.01);+ expect(d.totals.subagents).toBe(1);+ });++ it('keeps and reindexes PRs whose creating event is in scope', () => {+ const withPr = makeMap(CSP_EVENTS, {+ prs: [+ {+ provider: 'github',+ repo: 'dashboard',+ number: 42,+ url: 'u',+ seq: 12,+ },+ ],+ });+ expect(deriveScopeDoc(withPr, { ...EMPTY_SCOPE, task: 2 }).prs[0].seq).toBe(+ 6+ );+ expect(deriveScopeDoc(withPr, { ...EMPTY_SCOPE, task: 3 }).prs).toEqual([]);+ });++ it('an empty scope yields an empty document, not the whole session', () => {+ const d = deriveScopeDoc(map, { ...EMPTY_SCOPE, model: 'no-such-model' });+ // only user turns match a model filter they are exempt from+ expect(d.events.every((e) => e.kind === 'user')).toBe(true);+ const none = deriveScopeDoc(makeMap([{ kind: 'read' }]), {+ ...EMPTY_SCOPE,+ model: 'no-such-model',+ });+ expect(none.events).toEqual([]);+ });+});++describe('outputs on the map, jumps and descriptions', () => {+ const map = makeMap(CSP_EVENTS);++ it('builds a models branch and an outputs branch with one node per PR', () => {+ const tree = buildTree(map);+ const models = tree.byId.get('g:models');+ expect(models?.children.map((c) => c.name).sort()).toEqual([+ 'haiku-4.5',+ 'opus-5.5',+ 'sonnet-5',+ ]);+ const outs = tree.byId.get('g:outputs');+ expect(outs?.children.map((c) => c.id).sort()).toEqual([+ 'outg:artifacts',+ 'outg:github',+ 'outg:skills',+ 'outg:tickets',+ ]);+ const gh = tree.byId.get('outg:github');+ // commit + a single PR node for create, comment and merge+ expect(gh?.children.map((c) => c.id).sort()).toEqual([+ 'commit:a1b2c3d4',+ 'pr:dashboard#42',+ ]);+ expect(tree.byId.get('pr:dashboard#42')?.type).toBe('output');+ });++ it('lights model nodes from requests and output nodes from outputs', () => {+ const tree = buildTree(map);+ const refs = eventNodeRefs(map, tree);+ expect(refs[1].map((r) => r.id)).toContain('model:opus-5.5');+ expect(refs[15].map((r) => r.id)).toContain('model:sonnet-5');+ expect(refs[17].map((r) => r.id)).toContain('pr:dashboard#42');+ expect(refs[12].map((r) => r.id)).toContain('pr:dashboard#42');+ });++ it('jumps to the next output, wrapping', () => {+ expect(findNext(map.events, 0, 'out')).toBe(11);+ expect(findNext(map.events, 11, 'out')).toBe(12);+ expect(findNext(map.events, 20, 'out')).toBe(11);+ });++ it('outputs are not tool calls and are counted per kind', () => {+ const t = recomputeTotals(map.events);+ expect(t.calls).toBe(7); // read, subagent, search, edit, 3x exec+ expect(outputTotals(map.events)).toEqual({+ commits: 1,+ prsMerged: 1,+ prsClosed: 0,+ prComments: 1,+ ticketsCreated: 0,+ ticketsUpdated: 1,+ artifacts: 1,+ skillsCreated: 1,+ skillsUpdated: 0,+ modelSwitches: 1,+ });+ });++ it('describes the new kinds without content', () => {+ const d = (i: number) => describeEvent(map, map.events[i]);+ expect(d(0).detail).toBe('1240 chars · 1 URL (text not stored)');+ expect(d(11).title).toBe('Commit a1b2c3d');+ expect(d(11).detail).toContain('+2 −0');+ expect(d(17).title).toBe('PR #42 merged');+ expect(d(18).title).toBe('Ticket updated · ACME-4767');+ expect(d(19).detail).toBe('840.0 KB · version 3');+ expect(d(15).title).toBe('Model switched to sonnet-5');+ });++ it('summarizes a task window', () => {+ const d = deriveScopeDoc(map, { ...EMPTY_SCOPE, task: 2 });+ const s = summarizeEvents(+ d.events,+ d.events.map((e) => e.model ?? '')+ );+ expect(s.promptChars).toBe(310);+ expect(s.promptImages).toBe(1);+ expect(s.prsCreated).toBe(1);+ expect(s.outputs.commits).toBe(1);+ expect(s.models).toEqual(['opus-5.5']);+ });+});++describe('lanes', () => {+ it('draws tasks, the Events bar and the main agent; Context and Subagents on their toggles', () => {+ expect([...timelineLanes({ context: false, subagents: false })]).toEqual([+ 'tasks',+ 'events',+ 'main',+ ]);+ expect([...timelineLanes({ context: true, subagents: true })]).toEqual(+ LANE_KEYS+ );+ expect([...timelineLanes({ context: true, subagents: false })]).toEqual([+ 'tasks',+ 'events',+ 'ctx',+ 'main',+ ]);+ });+});++describe('scope totals', () => {+ it('a scope with no matching events has zero totals, not the session ones', () => {+ const d = deriveScopeDoc(+ makeMap([{ kind: 'read' }, { kind: 'llm', cost: 1 }]),+ {+ ...EMPTY_SCOPE,+ model: 'no-such-model',+ }+ );+ expect(d.events).toEqual([]);+ expect(d.totals.requests).toBe(0);+ expect(d.totals.costUsd).toBe(0);+ expect(d.session.durationMs).toBe(0);+ });++ it('modelUsage buckets match the model filter attribution', () => {+ // a request with no model of its own, after a switch on the same agent+ const map = makeMap(+ [+ { kind: 'llm', model: 'opus-5.5', cost: 1 },+ { kind: 'model_switch', from: 'opus-5.5', to: 'sonnet-5' },+ { kind: 'llm', cost: 2 },+ ],+ { session: { id: 's', startedAt: '2026-09-23T15:44:00Z', models: [] } }+ );+ const usage = modelUsage(map);+ expect(usage.map((u) => [u.model, u.requests])).toEqual([+ ['sonnet-5', 1],+ ['opus-5.5', 1],+ ]);+ const scoped = deriveScopeDoc(map, { ...EMPTY_SCOPE, model: 'sonnet-5' });+ expect(scoped.events.filter((e) => e.kind === 'llm')).toHaveLength(1);+ // no model anywhere: no bucket, rather than an "unknown" chip that+ // would scope to nothing+ expect(+ modelUsage(+ makeMap([{ kind: 'llm' }], {+ session: { id: 's', startedAt: '2026-09-23T15:44:00Z', models: [] },+ })+ )+ ).toEqual([]);+ });++ it('task windows keep full-session offsets under a scope that drops the prefix', () => {+ const map = stampTasks(makeMap(CSP_EVENTS));+ const full = sessionTasks(map).tasks;+ // a task scope drops everything before task 3 (a model scope keeps the+ // user turns, so it would not): the scoped doc starts at task 3+ const scoped = deriveScopeDoc(map, { ...EMPTY_SCOPE, task: 3 });+ // compare instants: '…Z' and '….000Z' are the same time as strings differ+ expect(Date.parse(scoped.session.startedAt)).toBe(+ Date.parse(map.session.startedAt) + 14_000+ );+ // full-map windows are measured from the full session start: adding their+ // offset to the scoped start would put task 3 at +28s instead of +14s,+ // which is why TaskCard is given the full session start+ expect(full[2].startT).toBe(14_000);+ expect(Date.parse(map.session.startedAt) + full[2].startT).toBe(+ Date.parse(scoped.session.startedAt)+ );+ });+});++describe('scope binding and repos', () => {+ it('a scope set on one session does not apply to another', () => {+ const p = { task: 2, model: null, ss: 'A' };+ expect(scopeForSession(p, 'A')).toEqual({+ scope: { task: 2, model: null },+ sub: null,+ stale: false,+ unowned: false,+ });+ expect(scopeForSession(p, 'B')).toEqual({+ scope: EMPTY_SCOPE,+ sub: null,+ stale: true,+ unowned: false,+ });+ // unowned deep link: applies to the session it is shown with, flagged so+ // the caller binds it to that session+ const u = scopeForSession({ ...p, ss: null }, 'B');+ expect(u.scope.task).toBe(2);+ expect(u.unowned).toBe(true);+ expect(+ scopeForSession({ task: null, model: null, ss: null }, 'B').unowned+ ).toBe(false);+ // nothing scoped on another session: not stale, nothing to clear+ expect(+ scopeForSession({ task: null, model: null, ss: 'A' }, 'B').stale+ ).toBe(false);+ });++ it('an open subagent (?sub=) is bound to its session like the scope', () => {+ const p = { task: null, model: null, sub: 'sub1', ss: 'A' };+ expect(scopeForSession(p, 'A').sub).toBe('sub1');+ const other = scopeForSession(p, 'B');+ expect(other.sub).toBeNull();+ expect(other.stale).toBe(true);+ // a hand-written ?sub= link is claimed by the session it is shown with+ expect(scopeForSession({ ...p, ss: null }, 'B')).toMatchObject({+ sub: 'sub1',+ unowned: true,+ });+ });++ it('a scoped map keeps only the repos and files its events touch', () => {+ const map = makeMap(+ [+ { kind: 'user' },+ { kind: 'read', targets: [{ file: 0, touch: 'read' }] },+ { kind: 'user' },+ { kind: 'edit', targets: [{ file: 1, touch: 'edit' }] },+ ],+ {+ repos: [+ { id: 'r0', name: 'dashboard' },+ { id: 'r1', name: 'backend' },+ ],+ files: [+ { id: 0, repo: 'r0', path: 'src/proxy.ts' },+ { id: 1, repo: 'r1', path: 'views.py' },+ ],+ }+ );+ const d = deriveScopeDoc(map, { ...EMPTY_SCOPE, task: 2 });+ expect(d.files.map((f) => f.id)).toEqual([1]);+ expect(d.repos.map((r) => r.name)).toEqual(['backend']);+ const tree = buildTree(d);+ expect(tree.byId.has('file:0')).toBe(false);+ expect(tree.byId.has('repo:r0')).toBe(false);+ // unscoped: untouched+ expect(deriveScopeDoc(map, EMPTY_SCOPE).files).toHaveLength(2);+ });+});++describe('scope filter helpers', () => {+ // task 1 ran opus only, task 2 ran sonnet only+ const map = stampTasks(+ makeMap([+ { kind: 'user' },+ { kind: 'llm', model: 'opus-5.5', cost: 1 },+ { kind: 'user' },+ { kind: 'llm', model: 'sonnet-5', cost: 2 },+ { kind: 'llm', model: 'sonnet-5', cost: 3 },+ ])+ );+ const tasks = sessionTasks(map).tasks;+ const models = modelUsage(map);++ it('hasReplayEvents: a prompt with no event of the model is not a replay', () => {+ const miss = deriveScopeDoc(map, { task: 1, model: 'sonnet-5' });+ // the model filter keeps the prompt's own `user` event+ expect(miss.events.map((e) => e.kind)).toEqual(['user']);+ expect(hasReplayEvents(miss)).toBe(false);+ expect(hasReplayEvents(deriveScopeDoc(map, { task: 2, model: 'sonnet-5' }))).toBe(true);+ expect(hasReplayEvents(map)).toBe(true);+ expect(hasReplayEvents({ ...map, events: [] })).toBe(false);+ });++ it('scopedModelUsage: per-model requests inside one prompt, zero kept', () => {+ const inTask = (n: number) =>+ scopedModelUsage(models, deriveScopeDoc(map, { task: n, model: null }));+ const reqs = (u: { model: string; requests: number }[]) =>+ Object.fromEntries(u.map((m) => [m.model, m.requests]));+ expect(reqs(inTask(1))).toEqual({ 'opus-5.5': 1, 'sonnet-5': 0 });+ expect(reqs(inTask(2))).toEqual({ 'opus-5.5': 0, 'sonnet-5': 2 });+ expect(inTask(2).map((m) => m.model)).toEqual(models.map((m) => m.model));+ expect(reqs(scopedModelUsage(models, map))).toEqual({+ 'opus-5.5': 1,+ 'sonnet-5': 2,+ });+ });++ it('normalizeScope: an out-of-range task or unknown model reads as unset', () => {+ const n = (task: number | null, model: string | null) =>+ normalizeScope({ task, model }, tasks, models);+ expect(n(2, 'sonnet-5')).toEqual({ task: 2, model: 'sonnet-5' });+ expect(n(999, 'sonnet-5')).toEqual({ task: null, model: 'sonnet-5' });+ expect(n(0, null)).toEqual(EMPTY_SCOPE);+ expect(n(1, 'nope')).toEqual({ task: 1, model: null });+ expect(n(null, null)).toEqual(EMPTY_SCOPE);+ });+});diff --git a/viewer/src/core/sessionScope.ts b/viewer/src/core/sessionScope.tsnew file mode 100644index 0000000..7e7944b--- /dev/null+++ b/viewer/src/core/sessionScope.ts@@ -0,0 +1,516 @@+/**+ * Scoping: tasks, per-event model, and the scoped+ * document every view renders from. Pure, no React: tested in+ * `sessionScope.test.ts`.+ *+ * Scoping works the same way the agent lens does (`deriveLensDoc`): the+ * explorer is re-rendered from a filtered, reindexed copy of the map, so the+ * radial map, the timeline and every side card agree on what is in scope+ * without each one learning about filters.+ */+import { parseAsInteger, parseAsString } from 'nuqs';+import type {+ SessionMap,+ SessionMapAgent,+ SessionMapEvent,+} from './schema';+import {+ NON_CALL,+ ctxOf,+ outputTotals,+ recomputeTotals,+ shiftStartedAt,+ type OutputTotals,+} from './sessionMapModel';++// --- tasks -------------------------------------------------------------------++export interface TaskWindow {+ n: number;+ name: string;+ /** whether `name` came from the map (a segment or a prompt title) rather+ * than the "Task 3" / "Prompt 3" placeholder */+ named: boolean;+ /** `segments`: the CLI's own task segmentation; `turns`: one task per user+ * turn, derived here when the map carries no tasks */+ source: 'segments' | 'turns';+ /** first and last event index (inclusive) */+ start: number;+ end: number;+ /** ms since session start */+ startT: number;+ endT: number;+}++/** What the UI calls these windows. Locally every window is one user prompt+ * (`turns`); only a map with a real segmenter carries `segments` windows,+ * which are genuine tasks. */+export function taskNoun(tasks: readonly Pick<TaskWindow, 'source'>[]): {+ one: string;+ many: string;+} {+ return tasks.some((t) => t.source === 'segments')+ ? { one: 'Task', many: 'Tasks' }+ : { one: 'Prompt', many: 'Prompts' };+}++/**+ * Task number per event, and the task windows. Preference order:+ * 1. every event's own `task` (the CLI stamps it from `tasks[]`);+ * 2. `map.tasks[]` start/end sequence numbers (seq === index);+ * 3. user-turn windows: a task starts at each user turn and runs until the+ * next one; events before the first turn belong to task 1.+ * A map with no user turns at all is one task. Never throws on a malformed+ * tasks block: it falls through to the next source.+ */+export function sessionTasks(map: SessionMap): {+ taskOf: number[];+ tasks: TaskWindow[];+} {+ const events = map.events;+ const N = events.length;+ const named = new Map<number, string>();+ const turnsTask = new Set<number>();+ for (const t of map.tasks ?? []) {+ if (typeof t.n !== 'number') continue;+ if (t.name) named.set(t.n, t.name);+ if (t.source === 'turns') turnsTask.add(t.n);+ }+ let taskOf: number[] | null = null;+ let source: TaskWindow['source'] = 'segments';++ if (N && events.every((e) => typeof e.task === 'number' && e.task > 0)) {+ taskOf = events.map((e) => e.task as number);+ } else if (map.tasks?.length) {+ const arr = new Array<number>(N).fill(0);+ for (const t of map.tasks) {+ if (t.startSeq == null || t.endSeq == null) continue;+ for (let i = Math.max(0, t.startSeq); i <= Math.min(N - 1, t.endSeq); i++)+ arr[i] = t.n;+ }+ // carry forward so events between declared windows join the prior task+ let last = 0;+ for (let i = 0; i < N; i++) {+ if (arr[i]) last = arr[i];+ else arr[i] = last;+ }+ const first = arr.find((v) => v > 0) ?? 0;+ if (first) {+ for (let i = 0; i < N && !arr[i]; i++) arr[i] = first;+ taskOf = arr;+ }+ }+ if (!taskOf) {+ source = 'turns';+ let k = 0;+ taskOf = events.map((e) => {+ if (e.kind === 'user') k++;+ return Math.max(1, k);+ });+ }++ const tasks: TaskWindow[] = [];+ taskOf.forEach((n, i) => {+ const last = tasks[tasks.length - 1];+ if (last && last.n === n) {+ last.end = i;+ last.endT = events[i].t;+ } else {+ const src = turnsTask.has(n) ? 'turns' : source;+ tasks.push({+ n,+ name: named.get(n) ?? (src === 'turns' ? `Prompt ${n}` : `Task ${n}`),+ named: named.has(n),+ source: src,+ start: i,+ end: i,+ startT: events[i].t,+ endT: events[i].t,+ });+ }+ });+ return { taskOf, tasks };+}++/**+ * Stamp every event with its task (and give the map a `tasks` block) so the+ * task survives later reindexing by an agent lens or a scope. A no-op when+ * the CLI already stamped every event.+ */+/**+ * Drop any `srcSeq` a document arrived with. It is the viewer's own field,+ * stamped by `deriveScopeDoc` / `deriveLensDoc` (see `srcSeqOf`), and rides the+ * schema's passthrough, so a map loaded from disk could carry one: trusted, it+ * would point a `?at=` link or a task's error tag at some other event. Applied+ * once, where the explorer takes in a raw map.+ */+export function withoutSrcSeq(map: SessionMap): SessionMap {+ if (!map.events.some((e) => e.srcSeq !== undefined)) return map;+ return {+ ...map,+ events: map.events.map((e) => {+ if (e.srcSeq === undefined) return e;+ const { srcSeq: _drop, ...rest } = e;+ return rest as SessionMapEvent;+ }),+ };+}++export function stampTasks(map: SessionMap): SessionMap {+ if (map.events.every((e) => typeof e.task === 'number' && e.task > 0))+ return map;+ const { taskOf, tasks } = sessionTasks(map);+ return {+ ...map,+ // Only a real name is carried: a "Prompt 3" placeholder written back here+ // would read as a title (`named`) on the next `sessionTasks` pass.+ tasks: tasks.map((t) => ({ n: t.n, name: t.named ? t.name : null, source: t.source })),+ events: map.events.map((e, i) => ({ ...e, task: taskOf[i] })),+ };+}++/** Summary of one task window for the side card. */+export interface TaskSummary {+ requests: number;+ calls: number;+ cost: number;+ tokens: number;+ outputs: OutputTotals;+ prsCreated: number;+ promptChars: number;+ promptImages: number;+ promptUrls: number;+ agents: string[];+ models: string[];+}++export function summarizeEvents(+ events: SessionMapEvent[],+ models: string[]+): TaskSummary {+ const llm = events.filter((e) => e.kind === 'llm');+ const users = events.filter((e) => e.kind === 'user');+ return {+ requests: llm.length,+ calls: events.filter((e) => !NON_CALL.has(e.kind)).length,+ cost: llm.reduce((s, e) => s + (e.cost ?? 0), 0),+ tokens: llm.reduce((s, e) => s + ctxOf(e) + (e.out ?? 0), 0),+ outputs: outputTotals(events),+ prsCreated: events.filter((e) => e.vcs?.action === 'pr_create').length,+ promptChars: users.reduce((s, e) => s + (e.chars ?? 0), 0),+ promptImages: users.reduce((s, e) => s + (e.images ?? 0), 0),+ promptUrls: users.reduce((s, e) => s + (e.urls ?? 0), 0),+ agents: [...new Set(events.map((e) => e.agent))],+ models: [...new Set(models.filter(Boolean))],+ };+}++// --- models ------------------------------------------------------------------++/**+ * The model that drove each event: the event's own `model` (newer CLIs stamp+ * every event), else the most recent LLM request's model on the same agent+ * (carried forward, then backward to cover events before the first request),+ * else the session's first model. '' when the map names no model at all.+ */+export function eventModels(map: SessionMap): string[] {+ const events = map.events;+ const out = new Array<string>(events.length).fill('');+ const lastByAgent = new Map<string, string>();+ events.forEach((e, i) => {+ const own = e.kind === 'model_switch' ? e.to : e.model;+ if (own) lastByAgent.set(e.agent, own);+ out[i] = own || lastByAgent.get(e.agent) || '';+ });+ const nextByAgent = new Map<string, string>();+ for (let i = events.length - 1; i >= 0; i--) {+ const e = events[i];+ if (out[i]) nextByAgent.set(e.agent, out[i]);+ else out[i] = nextByAgent.get(e.agent) || map.session.models[0] || '';+ }+ return out;+}++export interface ModelUsage {+ model: string;+ requests: number;+ cost: number;+ tokens: number;+}++/** Per-model request/cost/token rollup, most expensive first. */+export function modelUsage(map: SessionMap): ModelUsage[] {+ const by = new Map<string, ModelUsage>();+ // Same attribution as the model filter: a request with no+ // model of its own must land in the bucket the filter would put it in.+ const resolved = eventModels(map);+ for (const [i, e] of map.events.entries()) {+ if (e.kind !== 'llm') continue;+ const m = resolved[i];+ if (!m) continue;+ const u = by.get(m) ?? { model: m, requests: 0, cost: 0, tokens: 0 };+ u.requests++;+ u.cost += e.cost ?? 0;+ u.tokens += ctxOf(e) + (e.out ?? 0);+ by.set(m, u);+ }+ return [...by.values()].sort(+ (a, b) => b.cost - a.cost || b.requests - a.requests+ );+}++// --- scope -------------------------------------------------------------------++export interface Scope {+ /** task number, or null for the whole session */+ task: number | null;+ /** model name, or null for every model */+ model: string | null;+}++export const EMPTY_SCOPE: Scope = { task: null, model: null };++/**+ * URL params for the scope (`?task=2&model=sonnet-5`): filters live in the+ * URL so reload, share and Back restore them. Shared by the explorer and the+ * session list (which clears them on a session switch, since task numbers+ * and models belong to one session).+ */+export const SCOPE_PARAMS = {+ task: parseAsInteger,+ model: parseAsString,+ /** an open subagent (agent id): the replay is lensed onto that helper's+ * events (`?sub=<agentId>`), so a subagent view is linkable */+ sub: parseAsString,+ /** the session the scope was set on: a scope never carries over to+ * another session, however the selection changed (click, search, window) */+ ss: parseAsString,+};++export const CLEAR_SCOPE_PARAMS = {+ task: null,+ model: null,+ sub: null,+ ss: null,+};++/**+ * The scope that applies to `sessionId`, from the URL params. A scope set on+ * another session reads as empty. A scope with no owner (a hand-written+ * link) is taken to belong to the session it is first shown with.+ */+export function scopeForSession(+ p: {+ task: number | null;+ model: string | null;+ sub?: string | null;+ ss: string | null;+ },+ sessionId: string+): { scope: Scope; sub: string | null; stale: boolean; unowned: boolean } {+ const sub = p.sub ?? null;+ const any = p.task != null || p.model != null || sub != null;+ if (p.ss != null && p.ss !== sessionId)+ return { scope: EMPTY_SCOPE, sub: null, stale: any, unowned: false };+ return {+ scope: { task: p.task, model: p.model },+ sub,+ stale: false,+ // the caller stamps it with this session so it cannot carry over later+ unowned: any && p.ss == null,+ };+}++/**+ * Keep only the repos and files the kept events touch, so a scoped map does+ * not draw unrelated files as hollow nodes. Files keep their ids (event+ * targets point at them), repos stay those of the kept files.+ */+export function scopeFiles(+ map: SessionMap,+ events: SessionMapEvent[]+): Pick<SessionMap, 'repos' | 'files'> {+ const fileIds = new Set<number>();+ for (const e of events)+ for (const t of e.targets ?? [])+ if (!t.scope && t.file != null) fileIds.add(t.file);+ const files = map.files.filter((f) => fileIds.has(f.id));+ const repoIds = new Set(files.map((f) => f.repo));+ return { repos: map.repos.filter((r) => repoIds.has(r.id)), files };+}++export const isScoped = (s: Scope): boolean =>+ s.task != null || s.model != null;++/**+ * Scope a map (the full map, before any agent lens) to a task window, a+ * model, or both. Returns `map` itself when nothing is scoped.+ *+ * Kept events are reindexed; `retryOf`/`ref` are remapped to the new+ * positions or dropped when their target fell out of scope (a retry arc to+ * an event that is not drawn would point at the wrong mark). Times are+ * rebased to the first kept event so the timeline spans the scope, and+ * `session.startedAt` moves with them so clock labels stay true. Each event+ * keeps its `task` and gets its resolved `model`, so the task lane and model+ * branch still read correctly inside a scope.+ */+export function deriveScopeDoc(map: SessionMap, scope: Scope): SessionMap {+ if (!isScoped(scope) || !map.events.length) return map;+ const { taskOf } = sessionTasks(map);+ const models = eventModels(map);+ const keep: number[] = [];+ map.events.forEach((e, i) => {+ if (scope.task != null && taskOf[i] !== scope.task) return;+ if (scope.model != null && e.kind !== 'user' && models[i] !== scope.model)+ return;+ keep.push(i);+ });+ if (!keep.length)+ // Nothing matches: zero totals and duration, never the full session's.+ return {+ ...map,+ session: { ...map.session, durationMs: 0 },+ totals: recomputeTotals([]),+ repos: [],+ files: [],+ events: [],+ agents: [],+ prs: [],+ };++ const oldToNew = new Map<number, number>();+ keep.forEach((oldIndex, i) => oldToNew.set(oldIndex, i));+ const t0 = map.events[keep[0]].t;+ const events = keep.map((oldIndex, i) => {+ const e = map.events[oldIndex];+ const ev: SessionMapEvent = {+ ...e,+ seq: i,+ // `seq` is renumbered to stay `seq === index` here; `srcSeq` keeps the+ // full document's number so a reference held across the derivation+ // still resolves (`srcSeqOf`). Set once, by the first derivation.+ srcSeq: typeof e.srcSeq === 'number' ? e.srcSeq : (e.seq ?? oldIndex),+ t: e.t - t0,+ task: taskOf[oldIndex],+ model: e.kind === 'model_switch' ? e.model : models[oldIndex] || e.model,+ };+ if (ev.retryOf != null) ev.retryOf = oldToNew.get(ev.retryOf);+ if (ev.ref != null) ev.ref = oldToNew.get(ev.ref);+ return ev;+ });+ const durationMs = events[events.length - 1].t;+ const kept = new Set(keep);++ const agents: SessionMapAgent[] = map.agents+ .map((a) => {+ const own = events.filter((e) => e.agent === a.id);+ if (!own.length) return null;+ const llm = own.filter((e) => e.kind === 'llm');+ return {+ ...a,+ start: own[0].t,+ end: own[own.length - 1].t,+ calls: own.filter((e) => !NON_CALL.has(e.kind)).length,+ requests: llm.length,+ tokens: llm.reduce((s, e) => s + ctxOf(e) + (e.out ?? 0), 0),+ cost: llm.reduce((s, e) => s + (e.cost ?? 0), 0),+ };+ })+ .filter((a): a is SessionMapAgent => a != null);++ const totals = recomputeTotals(events);+ return {+ ...map,+ ...scopeFiles(map, events),+ session: {+ ...map.session,+ startedAt: shiftStartedAt(map.session.startedAt, t0),+ durationMs,+ },+ totals: {+ ...totals,+ subagents: agents.filter((a) => a.id !== 'main').length,+ },+ prs: map.prs+ .filter((pr) => kept.has(pr.seq))+ .map((pr) => ({ ...pr, seq: oldToNew.get(pr.seq) ?? pr.seq })),+ agents,+ events,+ };+}++/**+ * Whether a (scoped) map has anything to replay. A model filter keeps every+ * `user` event, so a prompt that used none of the model survives as its bare+ * prompt node: that is an empty scope, not a replay.+ */+export const hasReplayEvents = (map: SessionMap): boolean =>+ map.events.some((e) => e.kind !== 'user');++/**+ * The model picker's rows as counted inside a task scope (`map` is the+ * task-scoped doc, no model filter): every model stays listed, with zero+ * requests where the prompt did not use it.+ */+export function scopedModelUsage(+ models: readonly ModelUsage[],+ map: SessionMap+): ModelUsage[] {+ const inScope = new Map(modelUsage(map).map((u) => [u.model, u]));+ return models.map(+ (m) => inScope.get(m.model) ?? { ...m, requests: 0, cost: 0, tokens: 0 }+ );+}++/**+ * A scope from the URL, with a task this session does not have or a model it+ * never used read as unset, so a stale link cannot leave a filter looking+ * active over an empty replay.+ */+export function normalizeScope(+ scope: Scope,+ tasks: readonly Pick<TaskWindow, 'n'>[],+ models: readonly Pick<ModelUsage, 'model'>[]+): Scope {+ const task =+ scope.task != null && tasks.some((t) => t.n === scope.task)+ ? scope.task+ : null;+ const model =+ scope.model != null && models.some((m) => m.model === scope.model)+ ? scope.model+ : null;+ return task === scope.task && model === scope.model+ ? scope+ : { task, model };+}++// --- timeline lanes -----------------------------------------------------------++/** Timeline lanes, in drawing order. Every point event draws on the one+ * `events` bar (the dock's category chips pick what is bright); Context and+ * Subagents are optional lanes switched by their own dock toggles. */+export type LaneKey = 'tasks' | 'events' | 'ctx' | 'main' | 'subs';++export const LANE_LABEL: Record<LaneKey, string> = {+ tasks: 'Tasks',+ events: 'Events',+ ctx: 'Context',+ main: 'Main agent',+ subs: 'Subagents',+};++export const LANE_KEYS = Object.keys(LANE_LABEL) as LaneKey[];++/** The lanes to draw: tasks, the Events bar and the main agent always; the+ * Context and Subagents lanes when their toggles are on. */+export function timelineLanes(opts: {+ context: boolean;+ subagents: boolean;+}): Set<LaneKey> {+ return new Set(+ LANE_KEYS.filter(+ (k) => (k !== 'ctx' || opts.context) && (k !== 'subs' || opts.subagents)+ )+ );+}diff --git a/viewer/src/core/sessionSignals.test.ts b/viewer/src/core/sessionSignals.test.tsnew file mode 100644index 0000000..8ca2157--- /dev/null+++ b/viewer/src/core/sessionSignals.test.ts@@ -0,0 +1,362 @@+import { describe, expect, it } from 'vitest';+import {+ SESSION_MAP_SCHEMA_V1,+ sessionMapSchema,+} from './schema';+import {+ buildTree,+ errSource,+ eventNodeRefs,+ stateAt,+} from './sessionMapModel';+import {+ IDLE_CAP_MS,+ contextSeries,+ detailRows,+ indexAtFraction,+ sessionSignals,+ signalsAt,+ timePositions,+} from './sessionSignals';+import { cumulativeCost } from './sessionMapModel';+import { sessionWindowRange } from './sessionWindow';++type RawEvent = Record<string, unknown> & { kind: string; t: number };++function makeMap(events: RawEvent[], totals: Record<string, unknown> = {}) {+ return sessionMapSchema.parse({+ schema: SESSION_MAP_SCHEMA_V1,+ session: { id: 'local:claude-code:s1', startedAt: '2026-09-10T00:00:00Z' },+ totals,+ repos: [{ id: 'r0', name: 'backend' }],+ files: [{ id: 0, repo: 'r0', path: 'a.py' }],+ agents: [{ id: 'main', parent: null, kind: 'main' }],+ events: events.map((e, i) => ({ seq: i, agent: 'main', err: false, ...e })),+ });+}++const MIN = 60_000;+const EVENTS: RawEvent[] = [+ { kind: 'user', t: 0, chars: 10 }, // 0+ {+ kind: 'llm',+ t: 1000,+ in: 10,+ cw: 1000,+ cr: 9000,+ out: 50,+ cost: 0.1,+ latency: 2000,+ }, // 1 ctx 10010+ {+ kind: 'exec',+ t: 2000,+ tool: 'Bash',+ verb: 'pytest',+ err: true,+ errClass: 'exit_code',+ exitCode: 1,+ targets: [{ file: 0, touch: 'read' }],+ }, // 2+ {+ kind: 'exec',+ t: 3000,+ tool: 'Bash',+ verb: 'pytest',+ retryOf: 2,+ attempt: 2,+ targets: [{ file: 0, touch: 'read' }],+ }, // 3+ {+ kind: 'mcp',+ t: 4000,+ server: 'linear',+ tool: 'list_issues',+ err: true,+ errClass: 'not_found',+ }, // 4+ {+ kind: 'error',+ t: 5000,+ source: 'llm',+ errClass: 'rate_limit',+ err: true,+ retry: true,+ }, // 5+ { kind: 'delay', t: 5000 + 3 * MIN, cause: 'tool', ms: 3 * MIN, ref: 4 }, // 6+ {+ kind: 'llm',+ t: 5000 + 3 * MIN + 1000,+ in: 5,+ cw: 0,+ cr: 40000,+ out: 20,+ cost: 0.2,+ latency: 90_000,+ stop: 'max_tokens',+ thinking: true,+ toolCalls: 2,+ textChars: 300,+ }, // 7 ctx 40005+ {+ kind: 'compaction',+ t: 5000 + 4 * MIN,+ trigger: 'auto',+ preTokens: 50000,+ postTokens: 8000,+ ms: 4000,+ }, // 8+ { kind: 'user', t: 5000 + 64 * MIN, chars: 5 }, // 9: 60 min idle gap+ {+ kind: 'subagent',+ t: 5000 + 65 * MIN,+ subagentType: 'fork',+ err: true,+ errClass: 'subagent_failed',+ }, // 10+];++describe('errSource', () => {+ it('derives the source from the event kind or the error event', () => {+ const m = makeMap(EVENTS);+ expect(m.events.filter((e) => e.err).map(errSource)).toEqual([+ 'tool',+ 'mcp',+ 'llm',+ 'orchestration',+ ]);+ const hookErr = makeMap([+ { kind: 'error', t: 0, source: 'hook', err: true },+ ]);+ expect(errSource(hookErr.events[0])).toBe('hook');+ const unknown = makeMap([+ { kind: 'error', t: 0, source: 'mystery', err: true },+ ]);+ expect(errSource(unknown.events[0])).toBe('tool');+ });+});++describe('contextSeries', () => {+ it('carries the main context forward and drops at a compaction', () => {+ const c = contextSeries(makeMap(EVENTS));+ expect(c.values[0]).toBe(0);+ expect(c.values[1]).toBe(10010);+ expect(c.values[5]).toBe(10010); // carried+ expect(c.values[7]).toBe(40005);+ expect(c.before.get(8)).toBe(50000);+ expect(c.values[8]).toBe(8000);+ expect(c.values[10]).toBe(8000);+ expect(c.max).toBe(50000);+ });++ it('uses totals.maxContext when it is larger', () => {+ expect(contextSeries(makeMap(EVENTS, { maxContext: 90000 })).max).toBe(+ 90000+ );+ });+});++describe('timePositions', () => {+ const m = makeMap(EVENTS);++ it('spaces events evenly on the steps axis', () => {+ const pos = timePositions(m.events, 'steps');+ expect(pos[0]).toBe(0);+ expect(pos[5]).toBeCloseTo(0.5);+ expect(pos[10]).toBe(1);+ });++ it('caps idle gaps (user turns, gaps over 20 min) to 5 min on the time axis', () => {+ const pos = timePositions(m.events, 'time');+ // raw gaps: 1000 x5 (0..5), 3min, 1000, 1min-1000, 60min (user) -> 5min, 1min+ const total = 5000 + 3 * MIN + 1000 + (MIN - 1000) + IDLE_CAP_MS + MIN;+ expect(pos[9]).toBeCloseTo((total - MIN) / total);+ expect(pos[10]).toBe(1);+ for (let i = 1; i < pos.length; i++)+ expect(pos[i]).toBeGreaterThanOrEqual(pos[i - 1]);+ });++ it('maps a fraction back to the nearest event', () => {+ const pos = timePositions(m.events, 'steps');+ expect(indexAtFraction(pos, 0)).toBe(0);+ expect(indexAtFraction(pos, 0.52)).toBe(5);+ expect(indexAtFraction(pos, 1)).toBe(10);+ });+});++describe('signalsAt / sessionSignals', () => {+ const m = makeMap(EVENTS);++ it('counts signals up to the playhead', () => {+ const at = signalsAt(m.events, 6);+ expect(at.errors).toBe(3);+ expect(at.bySource).toEqual({+ tool: 1,+ mcp: 1,+ llm: 1,+ hook: 0,+ orchestration: 0,+ });+ expect(at.byClass).toEqual({ exit_code: 1, not_found: 1, rate_limit: 1 });+ expect(at.retries).toBe(1);+ expect(at.delays).toBe(1);+ expect(at.delayMs).toBe(3 * MIN);+ expect(at.compactions).toBe(0);+ expect(at.ctxNow).toBe(10010);+ expect(signalsAt(m.events, 8).ctxNow).toBe(8000);+ });++ it('computes session signals from events when totals are absent', () => {+ const s = sessionSignals(m);+ expect(s.errors).toBe(4);+ expect(s.bySource.orchestration).toBe(1);+ expect(s.compactions).toBe(1);+ expect(s.maxContext).toBe(50000);+ expect(s.latencyP50).toBe(2000);+ expect(s.latencyP95).toBe(90_000);+ });++ it('prefers the CLI totals when present', () => {+ const s = sessionSignals(+ makeMap(EVENTS, {+ errors: 1,+ errorsBySource: { tool: 7 },+ retries: 9,+ llmLatencyP50: 5,+ })+ );+ // The event-derived count for EVENTS is 4 (see the test above); the CLI+ // total of 1 must win, not lose to it.+ expect(s.errors).toBe(1);+ expect(s.bySource.tool).toBe(7);+ expect(s.bySource.mcp).toBe(0);+ expect(s.retries).toBe(9);+ expect(s.latencyP50).toBe(5);+ });+});++describe('error nodes on the map', () => {+ it('lights error-class nodes and rings the node that failed', () => {+ const m = makeMap(EVENTS);+ const tree = buildTree(m);+ expect(tree.byId.get('errsrc:tool')?.parent?.id).toBe('g:errors');+ expect(tree.root.children[tree.root.children.length - 1].id).toBe(+ 'g:errors'+ );+ const st = stateAt(eventNodeRefs(m, tree), 3);+ expect(st.get('errc:tool/exit_code')?.cnt).toBe(1);+ expect(st.get('file:0')?.err).toBe(1);+ expect(st.get('file:0')?.cnt).toBe(2);+ });+});++describe('detailRows', () => {+ const m = makeMap(EVENTS);+ const cum = cumulativeCost(m.events);+ const ord = new Map<string, number>();+ const asObj = (i: number, compact = false) =>+ Object.fromEntries(+ detailRows(m, i, cum, ord, compact).map((r) => [r.k, r.v])+ );++ it('shows LLM metadata without any response text', () => {+ const r = asObj(7);+ expect(r['context in']).toBe('40.0K');+ expect(r['session so far']).toBe('$0.30');+ expect(r['stop reason']).toBe('max_tokens');+ expect(r['thinking']).toBe('yes');+ expect(r['tool calls asked']).toBe('2');+ expect(r['response text']).toBe('300 chars (not stored)');+ expect(r['agent']).toBe('Main agent');+ expect(asObj(7, true)['agent']).toBeUndefined();+ });++ it('shows failures, retries, delays and compactions', () => {+ expect(asObj(2)['exit code']).toBe('1');+ expect(asObj(3)['retry']).toBe('attempt 2 · after #2');+ expect(asObj(6)['duration']).toBe('3m 00s');+ expect(asObj(8)['dropped']).toBe('42.0K');+ });+});++describe('sessionWindowRange', () => {+ const now = new Date('2026-09-22T10:00:00Z');+ it('derives inclusive UTC from/to from the page window', () => {+ expect(sessionWindowRange('30d', now)).toEqual({+ from: '2026-08-24',+ to: '2026-09-22',+ });+ expect(sessionWindowRange('90d', now).from).toBe('2026-06-25');+ expect(sessionWindowRange('all', now)).toEqual({});+ });++ describe('mtd', () => {++ // A window length computed once at import time would return the SAME+ // `from` for both months below instead of tracking `now`.+ it("derives MTD from `now`'s own month, not an import-time snapshot", () => {+ expect(+ sessionWindowRange('mtd', new Date('2026-08-31T12:00:00Z'))+ ).toEqual({+ from: '2026-08-01',+ to: '2026-08-31',+ });+ expect(+ sessionWindowRange('mtd', new Date('2026-09-05T12:00:00Z'))+ ).toEqual({+ from: '2026-09-01',+ to: '2026-09-05',+ });+ });++ // An elapsed-ms calculation undercounts at exact local midnight: zero+ // ms have passed since 00:00 on day N, so a naive `Math.ceil` gives+ // N - 1 instead of including day N itself.+ // Server `sessionDate` is UTC, so the month boundary is UTC too. The suite+ // runs under TZ=America/Los_Angeles (vite.config.ts), where this instant+ // is still Sep 30 locally.+ it('uses the UTC month, not the local one, near a month boundary', () => {+ expect(+ sessionWindowRange('mtd', new Date('2026-10-01T03:00:00Z'))+ ).toEqual({ from: '2026-10-01', to: '2026-10-01' });+ expect(+ sessionWindowRange('mtd', new Date('2026-09-30T23:59:59Z'))+ ).toEqual({ from: '2026-09-01', to: '2026-09-30' });+ });++ it('counts today even at exact local midnight', () => {+ expect(+ sessionWindowRange('mtd', new Date('2026-09-02T00:00:00Z'))+ ).toEqual({+ from: '2026-09-01',+ to: '2026-09-02',+ });+ });+ });+});++describe('detailRows for a failed hook', () => {+ const m = makeMap([+ { kind: 'exec', t: 0, tool: 'Bash', verb: 'pytest' },+ { kind: 'error', t: 1, err: true, source: 'hook', errClass: 'hook_blocking', hook: 'PostToolUse:Bash', hookEvent: 'PostToolUse', ref: 0, srcUuid: 'u1' },+ { kind: 'error', t: 2, err: true, source: 'hook', errClass: 'hook_error', hook: 'Stop', ref: 99 },+ ]);+ const rows = (i: number) => detailRows(m, i, cumulativeCost(m.events), new Map(), false);++ it('says whether it blocked and points at the call that triggered it', () => {+ expect(rows(1).map((r) => [r.k, r.v, r.seek])).toEqual([+ ['source', 'Hook', undefined],+ ['class', 'hook_blocking', undefined],+ ['hook', 'PostToolUse:Bash', undefined],+ ['blocking', 'yes', undefined],+ ['triggered by', '#0 pytest', 0],+ ['agent', 'Main agent', undefined],+ ]);+ });++ it('shows no link when the cause is not in the map', () => {+ const r = rows(2);+ expect(r.find((x) => x.k === 'blocking')?.v).toBe('no');+ expect(r.some((x) => x.k === 'triggered by')).toBe(false);+ });+});diff --git a/viewer/src/core/sessionSignals.ts b/viewer/src/core/sessionSignals.tsnew file mode 100644index 0000000..fc28e23--- /dev/null+++ b/viewer/src/core/sessionSignals.ts@@ -0,0 +1,321 @@+/**+ * Signals for the Session Explorer (errors, retries,+ * delays, context, LLM output): context series with compaction drops, the+ * idle-compressed time axis, retry pairs, per-playhead signal counts, session+ * signal totals and the per-kind detail rows the inspector and tooltips show.+ * Pure, unit-tested in `sessionSignals.test.ts`.+ */+import type { SessionMap, SessionMapEvent } from './schema';+import {+ DELAY_CAUSE_LABEL,+ ERROR_SOURCES,+ ERROR_SOURCE_LABEL,+ agentLabel,+ ctxOf,+ describeEvent,+ errClassLabel,+ errClassOf,+ errSource,+ fmtDur,+ fmtTok,+ fmtUsd,+ type ErrorSource,+} from './sessionMapModel';++// --- context ----------------------------------------------------------------++export interface ContextSeries {+ /** main-agent context after event i (carried forward between requests) */+ values: Float64Array;+ /** for a compaction at i: the context just before it dropped */+ before: Map<number, number>;+ /** y-scale max: totals.maxContext, any compaction's preTokens, or the peak */+ max: number;+}++/**+ * Main-agent context over the session: each main `llm` sets it to+ * in + cw + cr; a main compaction first climbs to `preTokens` (or the+ * carried value) then drops to `postTokens`.+ */+export function contextSeries(map: SessionMap): ContextSeries {+ const events = map.events;+ const values = new Float64Array(events.length);+ const before = new Map<number, number>();+ let cur = 0;+ let peak = 0;+ events.forEach((e, i) => {+ if (e.agent === 'main' && e.kind === 'llm') cur = ctxOf(e);+ if (e.kind === 'compaction' && e.agent === 'main') {+ const pre = e.preTokens ?? cur;+ before.set(i, pre);+ peak = Math.max(peak, pre);+ cur = e.postTokens ?? 0;+ }+ peak = Math.max(peak, cur);+ values[i] = cur;+ });+ return {+ values,+ before,+ max: Math.max(map.totals.maxContext ?? 0, peak, 1),+ };+}++// --- time axis ----------------------------------------------------------------++export const TIMELINE_AXES = ['steps', 'time'] as const;+export type TimelineAxis = (typeof TIMELINE_AXES)[number];+export const isTimelineAxis = (a: unknown): a is TimelineAxis =>+ typeof a === 'string' && (TIMELINE_AXES as readonly string[]).includes(a);++/** Idle gaps (a user turn, or any gap over 20 min) are capped to 5 min on+ * the time axis so one lunch break does not flatten the session. */+export const IDLE_GAP_MS = 20 * 60 * 1000;+export const IDLE_CAP_MS = 5 * 60 * 1000;++/** x position in [0, 1] of every event, by step or by compressed time. */+export function timePositions(+ events: SessionMapEvent[],+ axis: TimelineAxis+): Float64Array {+ const N = events.length;+ const pos = new Float64Array(N);+ if (N < 2) return pos;+ if (axis === 'steps') {+ for (let i = 0; i < N; i++) pos[i] = i / (N - 1);+ return pos;+ }+ let acc = 0;+ for (let i = 1; i < N; i++) {+ let g = Math.max(0, events[i].t - events[i - 1].t);+ if (events[i].kind === 'user' || g > IDLE_GAP_MS)+ g = Math.min(g, IDLE_CAP_MS);+ acc += g;+ pos[i] = acc;+ }+ if (acc) for (let i = 0; i < N; i++) pos[i] /= acc;+ return pos;+}++/** Nearest event index to the fraction `f` (positions are non-decreasing). */+export function indexAtFraction(pos: Float64Array, f: number): number {+ const N = pos.length;+ if (!N) return 0;+ let lo = 0;+ let hi = N - 1;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (pos[mid] < f) lo = mid + 1;+ else hi = mid;+ }+ return lo > 0 && Math.abs(pos[lo - 1] - f) < Math.abs(pos[lo] - f)+ ? lo - 1+ : lo;+}++// --- signals at the playhead / whole session -------------------------------++export interface SignalCounts {+ errors: number;+ bySource: Record<ErrorSource, number>;+ byClass: Record<string, number>;+ retries: number;+ delays: number;+ delayMs: number;+ compactions: number;+ /** main-agent context at the playhead */+ ctxNow: number;+}++const zeroSources = (): Record<ErrorSource, number> => ({+ tool: 0,+ mcp: 0,+ llm: 0,+ hook: 0,+ orchestration: 0,+});++export function signalsAt(events: SessionMapEvent[], p: number): SignalCounts {+ const c: SignalCounts = {+ errors: 0,+ bySource: zeroSources(),+ byClass: {},+ retries: 0,+ delays: 0,+ delayMs: 0,+ compactions: 0,+ ctxNow: 0,+ };+ for (let i = 0; i <= p && i < events.length; i++) {+ const e = events[i];+ if (e.err) {+ c.errors++;+ c.bySource[errSource(e)]++;+ const k = errClassOf(e);+ c.byClass[k] = (c.byClass[k] ?? 0) + 1;+ }+ if (e.retryOf != null) c.retries++;+ if (e.kind === 'delay') {+ c.delays++;+ c.delayMs += e.ms ?? 0;+ }+ if (e.kind === 'compaction') {+ c.compactions++;+ if (e.agent === 'main') c.ctxNow = e.postTokens ?? 0;+ }+ if (e.kind === 'llm' && e.agent === 'main') c.ctxNow = ctxOf(e);+ }+ return c;+}++export interface SessionSignals {+ errors: number;+ bySource: Record<ErrorSource, number>;+ retries: number;+ delays: number;+ delayMs: number;+ compactions: number;+ maxContext: number;+ latencyP50: number | null;+ latencyP95: number | null;+}++function percentile(sorted: number[], q: number): number | null {+ if (!sorted.length) return null;+ const idx = Math.min(+ sorted.length - 1,+ Math.max(0, Math.ceil(q * sorted.length) - 1)+ );+ return sorted[idx];+}++/** Whole-session signals: the map's totals when the CLI sent them, computed+ * from events otherwise (older maps). */+export function sessionSignals(map: SessionMap): SessionSignals {+ const all = signalsAt(map.events, map.events.length - 1);+ const t = map.totals;+ const bySource = zeroSources();+ const src = Object.keys(t.errorsBySource).length+ ? t.errorsBySource+ : all.bySource;+ for (const k of ERROR_SOURCES) bySource[k] = src[k] ?? 0;+ const latencies = map.events+ .filter((e) => e.kind === 'llm' && e.latency != null)+ .map((e) => e.latency ?? 0)+ .sort((a, b) => a - b);+ return {+ errors: t.errors || all.errors,+ bySource,+ retries: t.retries ?? all.retries,+ delays: t.delays ?? all.delays,+ delayMs: t.delayMs ?? all.delayMs,+ compactions: t.compactions ?? all.compactions,+ maxContext: t.maxContext ?? contextSeries(map).max,+ latencyP50: t.llmLatencyP50 ?? percentile(latencies, 0.5),+ latencyP95: t.llmLatencyP95 ?? percentile(latencies, 0.95),+ };+}++// --- detail rows ------------------------------------------------------------++export type RowTone = 'bad' | 'warn';+export interface DetailRow {+ k: string;+ v: string;+ tone?: RowTone;+ /** Index of an event the row points at; the card renders it as a seek button. */+ seek?: number;+}++const SLOW_TOOL_MS = 30_000;+const SLOW_LLM_MS = 60_000;+export const LONG_DELAY_MS = 120_000;++/**+ * Per-kind detail rows for the event inspector (`compact` = the timeline+ * tooltip: agent only for subagents, response text only when present).+ */+export function detailRows(+ map: SessionMap,+ i: number,+ cumCost: Float64Array,+ ordinals: Map<string, number>,+ compact: boolean+): DetailRow[] {+ const e = map.events[i];+ const rows: DetailRow[] = [];+ const add = (k: string, v: string, tone?: RowTone) =>+ rows.push({ k, v, tone });+ if (e.kind === 'llm') {+ add('context in', fmtTok(ctxOf(e)));+ add('fresh input', fmtTok(e.in ?? 0));+ add('cache write', fmtTok(e.cw ?? 0));+ add('cache read', fmtTok(e.cr ?? 0));+ add('output', fmtTok(e.out ?? 0));+ add('cost', fmtUsd(e.cost ?? 0));+ add('session so far', fmtUsd(cumCost[i] ?? 0));+ if (e.latency != null)+ add(+ 'latency',+ fmtDur(e.latency),+ e.latency >= SLOW_LLM_MS ? 'warn' : undefined+ );+ if (e.stop)+ add('stop reason', e.stop, e.stop === 'max_tokens' ? 'warn' : undefined);+ add('thinking', e.thinking ? 'yes' : 'no');+ add('tool calls asked', String(e.toolCalls ?? 0));+ if (!compact || e.textChars)+ add('response text', `${fmtTok(e.textChars ?? 0)} chars (not stored)`);+ } else if (e.kind === 'compaction') {+ add('trigger', e.trigger || 'auto');+ add('before', fmtTok(e.preTokens ?? 0));+ add('after', fmtTok(e.postTokens ?? 0));+ add('dropped', fmtTok((e.preTokens ?? 0) - (e.postTokens ?? 0)));+ if (e.ms) add('took', fmtDur(e.ms));+ } else if (e.kind === 'error') {+ const src = errSource(e);+ add('source', ERROR_SOURCE_LABEL[src]);+ add('class', errClassOf(e), 'bad');+ if (e.hook) add('hook', e.hook);+ if (e.source === 'hook')+ add('blocking', e.errClass === 'hook_blocking' ? 'yes' : 'no');+ // `ref` is a seq; a scoped map may not hold the event it names.+ const cause = map.events.findIndex((x, j) => (x.seq ?? j) === e.ref);+ if (e.ref != null && cause >= 0)+ rows.push({+ k: 'triggered by',+ v: `#${cause} ${describeEvent(map, map.events[cause]).title}`,+ seek: cause,+ });+ if (e.retry) add('retried', 'yes');+ } else if (e.kind === 'delay') {+ add('cause', DELAY_CAUSE_LABEL[e.cause ?? ''] ?? e.cause ?? 'delay');+ add(+ 'duration',+ fmtDur(e.ms ?? 0),+ (e.ms ?? 0) >= LONG_DELAY_MS ? 'bad' : 'warn'+ );+ if (e.ref != null) add('event', `#${e.ref}`);+ } else if (e.kind === 'user') {+ add('length', `${e.chars ?? 0} chars`);+ } else {+ if (e.verb && e.tool === 'Bash') add('command', e.verb);+ if (e.dur != null)+ add(+ 'duration',+ fmtDur(e.dur),+ e.dur >= SLOW_TOOL_MS ? 'warn' : undefined+ );+ if (e.outBytes != null) add('output', `${fmtTok(e.outBytes)}B`);+ if (e.err) {+ add('error', e.errClass ? errClassLabel(e.errClass) : 'failed', 'bad');+ if (e.exitCode != null) add('exit code', String(e.exitCode), 'bad');+ }+ if (e.retryOf != null)+ add('retry', `attempt ${e.attempt ?? 2} · after #${e.retryOf}`, 'warn');+ }+ if (!compact || e.agent !== 'main')+ add('agent', agentLabel(map, e.agent, ordinals));+ return rows;+}diff --git a/viewer/src/core/sessionWindow.ts b/viewer/src/core/sessionWindow.tsnew file mode 100644index 0000000..a034237--- /dev/null+++ b/viewer/src/core/sessionWindow.ts@@ -0,0 +1,35 @@+import { windowDays, type WindowKey } from './windowOptions';++/** Days from the 1st of `now`'s UTC month through `now`, inclusive of today.+ * UTC, not local, to match `from`/`to` below and the server's UTC `sessionDate`.+ * A calendar "days this month" count, but keyed off the caller's clock+ * instead of a fresh `new Date()` baked into a module-level constant at+ * import time: such a constant freezes at whenever the module first loaded+ * and goes stale for any session still open past a month boundary.+ *+ * The day-of-month number IS the inclusive count on purpose, not an+ * elapsed-time calculation: `now.getTime() - anchor.getTime()` undercounts+ * at exact midnight (an integer number of days has elapsed, so+ * `Math.ceil` returns it unchanged instead of adding the partial day that+ * is "today") and is sensitive to DST shifting the ms-per-day. `getUTCDate()`+ * has neither problem. */+function daysThisMonth(now: Date): number {+ return now.getUTCDate();+}++/**+ * `from` / `to` (UTC YYYY-MM-DD, inclusive) for the sessions list, from the+ * window selector. "All time" sends neither.+ */+export function sessionWindowRange(+ windowKey: WindowKey,+ now: Date+): { from?: string; to?: string } {+ const days =+ windowKey === 'mtd' ? daysThisMonth(now) : windowDays(windowKey);+ if (days == null) return {};+ const iso = (d: Date) => d.toISOString().slice(0, 10);+ const from = new Date(now.getTime());+ from.setUTCDate(from.getUTCDate() - Math.max(days - 1, 0));+ return { from: iso(from), to: iso(now) };+}diff --git a/viewer/src/core/timelineDraw.ts b/viewer/src/core/timelineDraw.tsnew file mode 100644index 0000000..2bab69c--- /dev/null+++ b/viewer/src/core/timelineDraw.ts@@ -0,0 +1,499 @@+/**+ * Canvas painters for the Session Explorer timeline (`SessionTimeline`).+ * Each takes the shared draw environment and one lane; none keeps state.+ */+import type { SessionMapEvent } from './schema';+import {+ CATEGORY_COLOR,+ CONTEXT_COLOR,+ KIND_META,+ kindMeta,+ kindStyle,+} from './eventColors';+import {+ categoryOf,+ displayCategory,+ magnitude,+ matchesAnyCategory,+ sizeMetric,+ type Category,+} from './sessionLayout';+import { clockAt, fmtTok, llmTokens } from './sessionMapModel';+import { LANE_LABEL, type LaneKey, type TaskWindow } from './sessionScope';++/** Row geometry (CSS px). */+export const TL = {+ labelW: 112,+ top: 6,+ right: 8,+ gap: 4,+ subGap: 2,+ axisH: 14,+};++const ROW_H: Record<LaneKey | 'sub', number> = {+ tasks: 30,+ events: 30,+ ctx: 32,+ main: 14,+ subs: 16,+ sub: 12,+};++export interface Lane {+ /** the lane key, or the agent id of one expanded subagent row */+ id: string;+ key: LaneKey | 'sub';+ label: string;+ h: number;+ y: number;+}++/** Lane geometry: the visible lanes in fixed order, then (when the+ * Subagents row is expanded) one row per subagent.+ *+ * `subRows` is the session's full subagent list, always -- the collapsed+ * row's "(N)" count reads its length regardless of `expanded`, so it never+ * shows a stale "(0)" before the row has ever been opened.+ * `expanded` alone decides whether the individual rows are also drawn.+ * `tasksLabel` names the first lane (`taskNoun`). */+export function buildLanes(+ visible: ReadonlySet<LaneKey>,+ subRows: readonly { id: string; label: string }[] | null,+ expanded: boolean,+ tasksLabel = LANE_LABEL.tasks+): { lanes: Lane[]; bottom: number } {+ const rows: Omit<Lane, 'y'>[] = [];+ for (const key of Object.keys(LANE_LABEL) as LaneKey[]) {+ if (!visible.has(key)) continue;+ const label =+ key === 'subs'+ ? `Subagents (${subRows?.length ?? 0})`+ : key === 'tasks'+ ? tasksLabel+ : LANE_LABEL[key];+ rows.push({ id: key, key, label, h: ROW_H[key] });+ if (key === 'subs' && expanded && subRows)+ for (const s of subRows)+ rows.push({ id: s.id, key: 'sub', label: s.label, h: ROW_H.sub });+ }+ let y = TL.top;+ const lanes = rows.map((l) => {+ const lane = { ...l, y };+ y += l.h + (l.key === 'sub' ? TL.subGap : TL.gap);+ return lane;+ });+ return { lanes, bottom: y };+}++/** The height the optional lanes (Context, Subagents and its expanded rows)+ * add over the always-on ones. */+export function optionalLanesHeight(+ visible: ReadonlySet<LaneKey>,+ subRows: readonly { id: string; label: string }[] | null,+ expanded: boolean+): number {+ const base = new Set([...visible].filter((k) => k !== 'ctx' && k !== 'subs'));+ return (+ buildLanes(visible, subRows, expanded).bottom -+ buildLanes(base, subRows, false).bottom+ );+}++/** Events drawn on the agent rows (the tool-ish work of that agent). */+const onAgentRow = (e: SessionMapEvent) =>+ e.kind !== 'user' &&+ e.kind !== 'compaction' &&+ e.kind !== 'error' &&+ e.kind !== 'llm' &&+ e.kind !== 'delay';++/** Which events the hover snaps to on a lane (none: the raw index). On the+ * Events bar that is the selected categories' events, if any are selected. */+export function laneSnap(+ lane: Lane,+ selected: ReadonlySet<Category> = new Set()+): ((e: SessionMapEvent) => boolean) | undefined {+ switch (lane.key) {+ case 'events':+ return selected.size ? (e) => matchesAnyCategory(e, selected) : undefined;+ case 'ctx':+ return (e) => e.kind === 'llm' || e.kind === 'compaction';+ case 'main':+ return (e) => e.agent === 'main' && onAgentRow(e);+ case 'subs':+ return (e) => e.agent !== 'main' && onAgentRow(e);+ case 'sub':+ return (e) => e.agent === lane.id && onAgentRow(e);+ default:+ return undefined;+ }+}++/** Everything a painter needs: the context, colour resolver and x scale. */+export interface DrawEnv {+ ctx: CanvasRenderingContext2D;+ col: (v: string) => string;+ /** event index -> x (CSS px) */+ x: (i: number) => number;+ /** width of one event column on the steps axis */+ cw: number;+ width: number;+ plotW: number;+ bottom: number;+ sans: string;+ mono: string;+ events: readonly SessionMapEvent[];+}++/** Lane backgrounds and labels (lanes in `htmlLabels` get HTML buttons). */+export function drawLaneFrames(+ g: DrawEnv,+ lanes: readonly Lane[],+ htmlLabels: (l: Lane) => boolean+) {+ const { ctx, col } = g;+ for (const ln of lanes) {+ const chart = ln.key === 'ctx';+ if (!chart) {+ ctx.fillStyle = col('var(--ds-gray-subtlest)');+ ctx.fillRect(TL.labelW, ln.y, g.plotW, ln.h);+ }+ if (htmlLabels(ln)) continue;+ ctx.fillStyle = col('var(--ds-text-subtle)');+ ctx.fillText(ln.label, 4, ln.y + (chart ? ln.h / 2 - 6 : ln.h / 2));+ }+}++/** Task brackets: one labelled segment per task window. */+export function drawTasks(+ g: DrawEnv,+ TK: Lane,+ windows: readonly TaskWindow[],+ task: number | null,+ startedAt: string+) {+ const { ctx, col, x, cw } = g;+ for (const w of windows) {+ const x0 = x(w.start) - cw / 2;+ const x1 = x(w.end) + cw / 2;+ const sel = task === w.n;+ ctx.globalAlpha = 1;+ // Was --ds-surface-white for an unselected bracket: on the timeline's+ // own dark-mode canvas that's a near-black fill under --ds-text-default+ // (a mid gray meant for the page's body text, not this specific+ // backdrop) -- low contrast, hard to read. Same+ // gray the lane rows themselves already use (proven legible here) as+ // the fill, with the higher-emphasis text token as the label colour.+ ctx.fillStyle = col(+ sel ? 'var(--ds-brand-lightest)' : 'var(--ds-gray-subtlest)'+ );+ ctx.fillRect(x0 + 1, TK.y, Math.max(2, x1 - x0 - 2), TK.h);+ ctx.strokeStyle = col(+ sel ? 'var(--ds-brand-default)' : 'var(--ds-border-darker)'+ );+ ctx.lineWidth = 1;+ ctx.strokeRect(x0 + 1.5, TK.y + 0.5, Math.max(2, x1 - x0 - 3), TK.h - 1);+ ctx.fillStyle = col('var(--ds-brand-default)');+ ctx.fillRect(x0 + 1, TK.y, Math.max(2, x1 - x0 - 2), 2.5);+ ctx.globalAlpha = 1;+ // Always `n · name`, clipped to the bracket: no width threshold that+ // drops the label (the full name is on the canvas title on hover).+ const room = x1 - x0 - 10;+ if (room <= 0) continue;+ ctx.save();+ ctx.beginPath();+ ctx.rect(x0 + 4, TK.y, room, TK.h);+ ctx.clip();+ ctx.fillStyle = col(+ sel ? 'var(--ds-brand-default)' : 'var(--ds-text-darker)'+ );+ ctx.fillText(`${w.n} · ${w.name}`, x0 + 6, TK.y + 11);+ ctx.fillStyle = col(+ sel ? 'var(--ds-brand-default)' : 'var(--ds-text-subtle)'+ );+ ctx.font = g.mono;+ ctx.fillText(+ `${clockAt(startedAt, w.startT).slice(0, 5)}–${clockAt(startedAt, w.endT).slice(0, 5)}`,+ x0 + 6,+ TK.y + 22+ );+ ctx.font = g.sans;+ ctx.restore();+ }+}++/** Main-agent context, carried forward; compactions drop pre -> post. */+export function drawContext(+ g: DrawEnv,+ C: Lane,+ series: {+ max: number;+ values: ArrayLike<number>;+ before: Map<number, number>;+ }+) {+ const { ctx, col, x, events } = g;+ const N = events.length;+ const cy = (v: number) => C.y + C.h - (v / series.max) * (C.h - 4);+ const tracePath = () => {+ ctx.moveTo(x(0), cy(0));+ for (let i = 0; i < N; i++) {+ const pre = series.before.get(i);+ if (pre != null) ctx.lineTo(x(i), cy(pre));+ ctx.lineTo(x(i), cy(series.values[i]));+ }+ };+ ctx.beginPath();+ tracePath();+ ctx.lineTo(x(N - 1), cy(0));+ ctx.closePath();+ ctx.globalAlpha = 0.16;+ ctx.fillStyle = col(CONTEXT_COLOR);+ ctx.fill();+ ctx.globalAlpha = 1;+ ctx.beginPath();+ tracePath();+ ctx.strokeStyle = col(CONTEXT_COLOR);+ ctx.lineWidth = 1.4;+ ctx.stroke();+ ctx.fillStyle = col('var(--ds-text-subtle)');+ ctx.fillText(`${fmtTok(series.max)} max`, 4, C.y + C.h / 2 + 8);+ ctx.font = g.mono;+ ctx.fillStyle = col(KIND_META.compaction.color);+ events.forEach((e, i) => {+ if (e.kind !== 'compaction') return;+ const cx = x(i);+ ctx.fillRect(cx - 0.75, C.y, 1.5, C.h);+ ctx.fillText(+ `${fmtTok(e.preTokens ?? 0)}→${fmtTok(e.postTokens ?? 0)}`,+ Math.min(cx + 5, g.width - 70),+ C.y + 8+ );+ });+ ctx.font = g.sans;+}++const line = (g: DrawEnv, xc: number, y: number, h: number, w: number) =>+ g.ctx.fillRect(xc - w / 2, y, w, h);++function diamond(g: DrawEnv, xc: number, yc: number, r: number) {+ const { ctx } = g;+ ctx.beginPath();+ ctx.moveTo(xc, yc - r);+ ctx.lineTo(xc + r, yc);+ ctx.lineTo(xc, yc + r);+ ctx.lineTo(xc - r, yc);+ ctx.closePath();+}++/** What the Events bar sizes its marks against (the scope's largest). */+export interface EventScales {+ maxChars: number;+ maxDelayMs: number;+ maxCost: number;+ maxTok: number;+}++/** Opacity of a mark outside the selected categories. */+const DIM_ALPHA = 0.15;+/** A dim mark's height, as a share of the bar. */+const DIM_H = 0.45;++/** Height share and width of a selected mark: prompts by their size,+ * delays by their length, LLM requests by cost / tokens while Cost or Tokens+ * is selected (`sizeMetric`), everything else full height. */+function markSize(+ e: SessionMapEvent,+ metric: 'cost' | 'tokens' | null,+ s: EventScales+): { f: number; w: number } {+ if (metric && e.kind === 'llm') {+ const m =+ metric === 'cost'+ ? magnitude(e.cost ?? 0, s.maxCost)+ : magnitude(llmTokens(e), s.maxTok);+ return { f: Math.max(0.12, m), w: 2 + 3.5 * m };+ }+ if (e.kind === 'user')+ return { f: 0.45 + 0.55 * Math.sqrt((e.chars ?? 0) / s.maxChars), w: 2 };+ if (e.kind === 'delay') {+ const logMax = Math.log(1 + s.maxDelayMs / 1000) || 1;+ const f = Math.log(1 + (e.ms ?? 0) / 1000) / logMax;+ return { f: 0.35 + 0.65 * Math.min(1, f), w: 2 };+ }+ return { f: 1, w: 2 };+}++/** One selected mark: an output is a diamond in its kind's colour, anything+ * else a bottom-anchored line in its category colour. */+function drawSelectedMark(+ g: DrawEnv,+ E: Lane,+ i: number,+ cat: Category,+ size: { f: number; w: number },+ emph: boolean+) {+ const { ctx, col, x, events } = g;+ const e = events[i];+ const xc = x(i);+ if (cat === 'out') {+ const kind = e.vcs?.action === 'pr_create' ? 'pr_create' : e.kind;+ ctx.fillStyle = col(kindMeta(kind).color);+ diamond(g, xc, E.y + E.h / 2, 5);+ ctx.fill();+ if (emph) {+ diamond(g, xc, E.y + E.h / 2, 8);+ ctx.strokeStyle = col('var(--ds-text-darker)');+ ctx.lineWidth = 1.5;+ ctx.stroke();+ }+ return;+ }+ const hh = (E.h - 4) * size.f;+ ctx.fillStyle = col(CATEGORY_COLOR[cat]);+ line(g, xc, E.y + E.h - 2 - hh, hh, emph ? size.w + 2 : size.w);+}++/**+ * The Events bar: every event, in its category colour. Events in a selected+ * category draw at full strength (and on top); the rest dim to a short,+ * faint tick so the selection lights up on the same bar. `emph` marks+ * (pinned / hovered) draw wider.+ */+export function drawEvents(+ g: DrawEnv,+ E: Lane,+ selected: ReadonlySet<Category>,+ scale: EventScales,+ emph: ReadonlySet<number>+) {+ const { ctx, col, x, events } = g;+ const on: number[] = [];+ const dimH = (E.h - 4) * DIM_H;+ ctx.globalAlpha = DIM_ALPHA;+ events.forEach((e, i) => {+ if (matchesAnyCategory(e, selected)) {+ on.push(i);+ return;+ }+ ctx.fillStyle = col(CATEGORY_COLOR[categoryOf(e)]);+ line(g, x(i), E.y + E.h - 2 - dimH, dimH, emph.has(i) ? 3 : 1.5);+ });+ ctx.globalAlpha = 1;+ const metric = sizeMetric(selected);+ for (const i of on) {+ const e = events[i];+ drawSelectedMark(+ g,+ E,+ i,+ displayCategory(e, selected),+ markSize(e, metric, scale),+ emph.has(i)+ );+ }+}++/** Agent rows: main, all subagents combined, and each expanded subagent. */+export function drawAgentRows(g: DrawEnv, lanes: readonly Lane[]) {+ const { ctx, col, x, cw, events } = g;+ const main = lanes.find((l) => l.key === 'main');+ const subs = lanes.find((l) => l.key === 'subs');+ const rows = new Map(+ lanes.filter((l) => l.key === 'sub').map((l) => [l.id, l])+ );+ if (!main && !subs && !rows.size) return;+ events.forEach((e, i) => {+ if (!onAgentRow(e)) return;+ ctx.fillStyle = col(kindStyle(e).color);+ const bx = x(i) - cw / 2;+ const targets =+ e.agent === 'main' ? [main] : [subs, rows.get(e.agent ?? '')];+ for (const ln of targets) if (ln) ctx.fillRect(bx, ln.y + 1, cw, ln.h - 2);+ });+}++/** Outside an open subagent's window: shaded, the window outlined. */+export function drawShade(g: DrawEnv, shade: { start: number; end: number }) {+ const { ctx, col, x, cw, width, bottom } = g;+ const sx0 = x(shade.start) - cw / 2;+ const sx1 = x(shade.end) + cw / 2;+ ctx.fillStyle = col('var(--ds-gray-subtlest)');+ ctx.globalAlpha = 0.8;+ if (sx0 > TL.labelW)+ ctx.fillRect(TL.labelW, TL.top, sx0 - TL.labelW, bottom - TL.top);+ if (sx1 < width - TL.right)+ ctx.fillRect(sx1, TL.top, width - TL.right - sx1, bottom - TL.top);+ ctx.globalAlpha = 1;+ ctx.strokeStyle = col('var(--ds-brand-default)');+ ctx.lineWidth = 1;+ ctx.strokeRect(+ sx0 + 0.5,+ TL.top + 0.5,+ Math.max(1, sx1 - sx0 - 1),+ bottom - TL.top - 1+ );+}++/** The pinned event: a dashed rule across every lane. */+export function drawPin(g: DrawEnv, i: number) {+ const { ctx, col, x, bottom } = g;+ ctx.save();+ ctx.strokeStyle = col('var(--ds-text-darker)');+ ctx.globalAlpha = 0.6;+ ctx.lineWidth = 2;+ ctx.setLineDash([4, 3]);+ ctx.beginPath();+ ctx.moveTo(x(i), 0);+ ctx.lineTo(x(i), bottom);+ ctx.stroke();+ ctx.restore();+}++/** The future dimmed, and the playhead. */+export function drawPlayhead(g: DrawEnv, p: number) {+ const { ctx, col, x, cw, width, bottom } = g;+ const px = x(p);+ ctx.fillStyle = col('var(--ds-surface-white)');+ ctx.globalAlpha = 0.55;+ ctx.fillRect(+ px + cw / 2,+ TL.top,+ width - TL.right - px - cw / 2,+ bottom - TL.top+ );+ ctx.globalAlpha = 1;+ ctx.strokeStyle = col('var(--ds-text-darker)');+ ctx.lineWidth = 1.5;+ ctx.beginPath();+ ctx.moveTo(px, 0);+ ctx.lineTo(px, bottom);+ ctx.stroke();+}++/** Five clock ticks along the bottom. */+export function drawAxis(+ g: DrawEnv,+ pos: Float64Array,+ startedAt: string,+ height: number+) {+ const { ctx, col, x, events } = g;+ const N = events.length;+ ctx.fillStyle = col('var(--ds-text-subtler)');+ ctx.font = g.mono;+ for (let q = 0; q <= 4; q++) {+ let i = pos.findIndex((v) => v >= q / 4);+ if (i < 0) i = N - 1;+ ctx.textAlign = q === 0 ? 'left' : q === 4 ? 'right' : 'center';+ ctx.fillText(+ clockAt(startedAt, events[i]?.t ?? 0).slice(0, 5),+ x(i),+ height - 6+ );+ }+ ctx.textAlign = 'left';+ ctx.font = g.sans;+}diff --git a/viewer/src/core/windowOptions.ts b/viewer/src/core/windowOptions.tsnew file mode 100644index 0000000..b4b5040--- /dev/null+++ b/viewer/src/core/windowOptions.ts@@ -0,0 +1,27 @@+/**+ * Date-range window for the sessions list: the option list the selector+ * renders and the day count each key maps to. No React, no fetchers.+ */+export type WindowKey = 'mtd' | '30d' | '90d' | 'all';++export interface WindowOption {+ key: WindowKey;+ /** inclusive day count; `null` = all time. `mtd` is computed per call. */+ days: number | null;+ label: string;+}++export const WINDOW_OPTIONS: WindowOption[] = [+ { key: 'mtd', days: null, label: 'MTD' },+ { key: '30d', days: 30, label: 'Last 30d' },+ { key: '90d', days: 90, label: 'Last 90d' },+ { key: 'all', days: null, label: 'All time' },+];++export const WINDOW_KEYS = WINDOW_OPTIONS.map((o) => o.key);++/** Day count for a fixed window; `null` for all time. `mtd` depends on the+ * caller's clock, so `sessionWindowRange` computes it itself. */+export function windowDays(key: WindowKey): number | null {+ return WINDOW_OPTIONS.find((o) => o.key === key)?.days ?? null;+}diff --git a/viewer/src/data/SourceContext.tsx b/viewer/src/data/SourceContext.tsxnew file mode 100644index 0000000..ed6817c--- /dev/null+++ b/viewer/src/data/SourceContext.tsx@@ -0,0 +1,25 @@+import { createContext, useContext, type ReactNode } from 'react';+import type { SessionMapSource } from './source';++const SourceContext = createContext<SessionMapSource | null>(null);++/** Inject the data source every Session Explorer hook reads from. */+export function SessionMapSourceProvider({+ source,+ children,+}: {+ source: SessionMapSource;+ children: ReactNode;+}) {+ return (+ <SourceContext.Provider value={source}>{children}</SourceContext.Provider>+ );+}++export function useSessionMapSource(): SessionMapSource {+ const source = useContext(SourceContext);+ if (!source) {+ throw new Error('useSessionMapSource needs a SessionMapSourceProvider');+ }+ return source;+}diff --git a/viewer/src/data/account.test.ts b/viewer/src/data/account.test.tsnew file mode 100644index 0000000..3bf8441--- /dev/null+++ b/viewer/src/data/account.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';+import { fetchAccount, isLocalBase, parseAccount, postAccount, showsWelcome } from './account';++describe('parseAccount', () => {+ it('reads a well-formed answer', () => {+ expect(parseAccount({ success: true, status: 'signed_up', email: '[email protected]', enabled: true })).toEqual({+ status: 'signed_up',+ email: '[email protected]',+ enabled: true,+ });+ });++ it('treats anything malformed as nothing to offer', () => {+ for (const body of [null, 'x', {}, { status: 'weird', enabled: 'yes' }]) {+ expect(parseAccount(body)).toEqual({ status: 'none', email: null, enabled: false });+ }+ });+});++describe('showsWelcome', () => {+ it('shows only when signup is on and nothing was chosen yet', () => {+ expect(showsWelcome({ status: 'none', email: null, enabled: true })).toBe(true);+ expect(showsWelcome({ status: 'none', email: null, enabled: false })).toBe(false);+ expect(showsWelcome({ status: 'skipped', email: null, enabled: true })).toBe(false);+ expect(showsWelcome({ status: 'signed_up', email: '[email protected]', enabled: true })).toBe(false);+ expect(showsWelcome(undefined)).toBe(false);+ });+});++describe('isLocalBase', () => {+ it('allows same-origin and this machine only', () => {+ for (const ok of ['', 'http://127.0.0.1:7317', 'http://localhost:5173/', 'http://[::1]:7317']) {+ expect(isLocalBase(ok)).toBe(true);+ }+ for (const no of ['https://evil.example', 'http://127.0.0.1.evil.example', 'javascript:alert(1)', 'not a url']) {+ expect(isLocalBase(no)).toBe(false);+ }+ });++ it('never sends an email to a remote ?server base', async () => {+ let called = false;+ const real = globalThis.fetch;+ globalThis.fetch = (async () => {+ called = true;+ return new Response('{}');+ }) as typeof fetch;+ try {+ await expect(postAccount('https://evil.example', { action: 'signup', email: '[email protected]' })).rejects.toThrow();+ expect(await fetchAccount('https://evil.example')).toEqual({ status: 'none', email: null, enabled: false });+ } finally {+ globalThis.fetch = real;+ }+ expect(called).toBe(false);+ });+});diff --git a/viewer/src/data/account.ts b/viewer/src/data/account.tsnew file mode 100644index 0000000..0346ced--- /dev/null+++ b/viewer/src/data/account.ts@@ -0,0 +1,100 @@+/**+ * The optional email signup, through the local server (`GET`/`POST+ * /api/account`). The viewer itself still talks only to the local server: it+ * is the server that forwards an email, and only one the user typed in.+ */++export type AccountStatus = 'none' | 'signed_up' | 'skipped';++export interface AccountState {+ status: AccountStatus;+ email: string | null;+ /** False when no endpoint is set or the user opted out (DO_NOT_TRACK). */+ enabled: boolean;+}++export type AccountAction =+ | { action: 'signup'; email: string }+ | { action: 'skip' }+ | { action: 'disconnect' };++export class AccountError extends Error {+ constructor(+ message: string,+ readonly code: string+ ) {+ super(message);+ }+}++const STATUSES: readonly AccountStatus[] = ['none', 'signed_up', 'skipped'];++/** Anything unexpected reads as "nothing to offer": the card must never+ * block the viewer because of a malformed answer. */+export function parseAccount(body: unknown): AccountState {+ const b = (body && typeof body === 'object' ? body : {}) as Record<string, unknown>;+ const status = STATUSES.includes(b.status as AccountStatus) ? (b.status as AccountStatus) : 'none';+ return {+ status,+ email: typeof b.email === 'string' ? b.email : null,+ enabled: b.enabled === true,+ };+}++const LOCAL_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);++/**+ * Whether account calls may go to `base`: same-origin (`''`, the CLI serving+ * this page) or a server on this machine. `?server=` can name any host, and+ * this is the one call that carries something the user typed, so it never+ * leaves the machine from the browser.+ */+export function isLocalBase(base: string): boolean {+ if (base === '') return true;+ try {+ const u = new URL(base);+ return (u.protocol === 'http:' || u.protocol === 'https:') && LOCAL_HOSTS.has(u.hostname);+ } catch {+ return false;+ }+}++function url(base: string): string {+ if (!isLocalBase(base)) throw new AccountError('Signup only talks to the agentplay server on this machine.', 'not_local');+ return `${base.replace(/\/+$/, '')}/api/account`;+}++export async function fetchAccount(base: string): Promise<AccountState> {+ if (!isLocalBase(base)) return { status: 'none', email: null, enabled: false };+ const r = await fetch(url(base), { headers: { Accept: 'application/json' } });+ if (!r.ok || !(r.headers.get('content-type') ?? '').includes('json')) {+ return { status: 'none', email: null, enabled: false };+ }+ return parseAccount(await r.json());+}++export async function postAccount(base: string, body: AccountAction): Promise<AccountState> {+ const r = await fetch(url(base), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },+ body: JSON.stringify(body),+ });+ let answer: Record<string, unknown> = {};+ try {+ answer = (await r.json()) as Record<string, unknown>;+ } catch {+ // keep the status-derived error below+ }+ if (!r.ok) {+ throw new AccountError(+ typeof answer.error === 'string' ? answer.error : 'Something went wrong. Try again.',+ typeof answer.code === 'string' ? answer.code : 'internal_error'+ );+ }+ return parseAccount(answer);+}++/** Whether the welcome card should cover the viewer. */+export function showsWelcome(state: AccountState | undefined): boolean {+ return !!state && state.enabled && state.status === 'none';+}diff --git a/viewer/src/data/data.test.ts b/viewer/src/data/data.test.tsnew file mode 100644index 0000000..de51083--- /dev/null+++ b/viewer/src/data/data.test.ts@@ -0,0 +1,127 @@+// @vitest-environment node+import fs from 'node:fs';+import path from 'node:path';+import { gzipSync } from 'node:zlib';+import { describe, expect, it } from 'vitest';+import { SESSION_MAP_SCHEMA_V1_LEGACY, sessionMapSchema } from '@/core/schema';+import { listRows } from './memoryListing';+import { dedupeSessions, fnv1a, parseMapBytes, rowFromMap } from './parse';+import { fileSource } from './fileSource';++const DEMO = path.resolve(__dirname, '../../public/demo');+const demoFiles = fs.readdirSync(DEMO).filter((f) => f !== 'index.json');+const read = (f: string) => JSON.parse(fs.readFileSync(path.join(DEMO, f), 'utf8'));++describe('demo data', () => {+ it('ships at least three valid map documents', () => {+ expect(demoFiles.length).toBeGreaterThanOrEqual(3);+ for (const f of demoFiles) {+ expect(sessionMapSchema.safeParse(read(f)).success).toBe(true);+ }+ });++ it('indexes every map file, with titles marked as demo', () => {+ const index = read('index.json') as { sessions: { file: string; sessionTitle: string }[] };+ expect(index.sessions.map((s) => s.file).sort()).toEqual([...demoFiles].sort());+ for (const s of index.sessions) expect(s.sessionTitle.startsWith('Demo: ')).toBe(true);+ });+});++describe('parseMapBytes', () => {+ const doc = read(demoFiles[0]);+ const bytes = new TextEncoder().encode(JSON.stringify(doc));++ it('reads plain JSON', async () => {+ const map = await parseMapBytes(bytes);+ expect(map.session.id).toBe(doc.session.id);+ });++ it('reads gzipped JSON', async () => {+ const map = await parseMapBytes(new Uint8Array(gzipSync(bytes)));+ expect(map.events.length).toBe(doc.events.length);+ });++ it('accepts the legacy schema name', async () => {+ const legacy = { ...doc, schema: SESSION_MAP_SCHEMA_V1_LEGACY };+ const map = await parseMapBytes(new TextEncoder().encode(JSON.stringify(legacy)));+ expect(map.schema).toBe('entelligence.session-map/v1');+ });++ it('rejects another schema with a typed code', async () => {+ const v2 = new TextEncoder().encode(JSON.stringify({ ...doc, schema: 'agentplay/v2' }));+ await expect(parseMapBytes(v2)).rejects.toMatchObject({ code: 'unsupported_schema' });+ await expect(parseMapBytes(new TextEncoder().encode('{'))).rejects.toMatchObject({+ code: 'invalid_file',+ });+ });++ it('hashes deterministically', () => {+ expect(fnv1a(new TextEncoder().encode('abc'))).toBe('1a47e90b');+ });+});++describe('rowFromMap + listRows', () => {+ const rows = demoFiles.map((f) =>+ rowFromMap(sessionMapSchema.parse(read(f)), { contentHash: f })+ );++ it('derives a list row from the document totals', () => {+ const doc = sessionMapSchema.parse(read(demoFiles[0]));+ const row = rowFromMap(doc, { contentHash: 'h' });+ expect(row.calls).toBe(doc.totals.calls);+ expect(row.repos).toEqual(doc.repos.map((r) => r.name));+ expect(row.sessionDate).toBe(doc.session.startedAt.slice(0, 10));+ });++ it('sorts newest first and pages with an opaque cursor', () => {+ const p1 = listRows(rows, { pageSize: 2 });+ expect(p1.sessions).toHaveLength(2);+ expect(p1.hasMore).toBe(true);+ expect(p1.sessions[0].startedAt >= p1.sessions[1].startedAt).toBe(true);+ const p2 = listRows(rows, { pageSize: 2, cursor: p1.nextCursor });+ expect(p2.hasMore).toBe(false);+ expect(p2.sessions.map((s) => s.sessionId)).not.toContain(p1.sessions[0].sessionId);+ });++ it('filters by inclusive date window and search', () => {+ const day = rows[0].sessionDate as string;+ expect(listRows(rows, { from: day, to: day }).sessions.every((s) => s.sessionDate === day)).toBe(true);+ expect(listRows(rows, { search: 'codex' }).sessions.map((s) => s.agentTool)).toEqual(['codex']);+ });+});++describe('fileSource', () => {+ it('holds opened files in memory and reports bad ones', async () => {+ const src = fileSource();+ const good = new File([fs.readFileSync(path.join(DEMO, demoFiles[0]))], demoFiles[0]);+ const bad = new File(['nope'], 'bad.json');+ const res = await src.addFiles([good, bad]);+ expect(res.added).toHaveLength(1);+ expect(res.failed).toEqual([{ name: 'bad.json', reason: 'not valid JSON' }]);+ const batch = await src.maps([res.added[0], 'missing']);+ expect(batch.maps[1]).toEqual({ sessionId: 'missing', status: 'not_found' });+ const status = await src.status();+ expect(status.mapCount).toBe(1);+ });+});++describe('dedupeSessions', () => {+ it('keeps the first occurrence of a repeated sessionId, in order', () => {+ const rows = [+ { sessionId: 'a', n: 1 },+ { sessionId: 'b', n: 2 },+ { sessionId: 'a', n: 3 },+ { sessionId: 'c', n: 4 },+ { sessionId: 'b', n: 5 },+ ];+ expect(dedupeSessions(rows)).toEqual([+ { sessionId: 'a', n: 1 },+ { sessionId: 'b', n: 2 },+ { sessionId: 'c', n: 4 },+ ]);+ });++ it('returns an empty list for no rows', () => {+ expect(dedupeSessions([])).toEqual([]);+ });+});diff --git a/viewer/src/data/demoSource.ts b/viewer/src/data/demoSource.tsnew file mode 100644index 0000000..e7c3c81--- /dev/null+++ b/viewer/src/data/demoSource.ts@@ -0,0 +1,67 @@+import {+ sessionExplorerSessionSchema,+ type SessionExplorerSession,+} from '@/core/schema';+import { SessionExplorerError } from './errors';+import { listRows } from './memoryListing';+import { parseMapBytes } from './parse';+import type { SessionMapSource } from './source';++type DemoRow = SessionExplorerSession & { file?: string };++/**+ * The bundled synthetic sessions: `demo/index.json` (`{sessions: [row ++ * file]}`) and one `demo/<file>` map document per row, as static files next+ * to the page. `root` is resolved against the page, so the build works from+ * any path.+ */+export function demoSource(root = 'demo/'): SessionMapSource {+ const base = new URL(root, document.baseURI);+ let index: Promise<DemoRow[]> | null = null;+ const load = () =>+ (index ??= fetch(new URL('index.json', base))+ .then((r) => {+ if (!r.ok) throw new SessionExplorerError('demo index missing', 'not_found');+ return r.json() as Promise<{ sessions?: unknown[] }>;+ })+ .then((body) =>+ (body.sessions ?? []).map((raw) => {+ const row = sessionExplorerSessionSchema.parse(raw) as DemoRow;+ return row;+ })+ )+ .catch((err) => {+ index = null;+ throw err;+ }));+ return {+ id: 'demo',+ label: 'Demo sessions',+ async status() {+ const rows = await load();+ const latest = rows.map((r) => r.sessionDate ?? '').sort().pop() || null;+ return { success: true, available: rows.length > 0, mapCount: rows.length, latestSessionDate: latest };+ },+ async sessions(params) {+ return listRows(await load(), params);+ },+ async maps(ids) {+ const rows = await load();+ return {+ success: true,+ expiresIn: 3600,+ maps: ids.map((id) => {+ const row = rows.find((r) => r.sessionId === id);+ return row?.file+ ? { sessionId: id, url: new URL(row.file, base).href, schemaVersion: 1, contentHash: row.contentHash ?? id, bytesGz: row.bytesGz }+ : { sessionId: id, status: 'not_found' as const };+ }),+ };+ },+ async fetchMap(meta) {+ const r = await fetch(meta.url);+ if (!r.ok) throw new SessionExplorerError(`demo map ${r.status}`, 'not_found');+ return parseMapBytes(new Uint8Array(await r.arrayBuffer()));+ },+ };+}diff --git a/viewer/src/data/errors.ts b/viewer/src/data/errors.tsnew file mode 100644index 0000000..563a6e0--- /dev/null+++ b/viewer/src/data/errors.ts@@ -0,0 +1,11 @@+/** Error carrying a stable `code` (e.g. `not_found`, `expired`,+ * `unsupported_schema`) so the UI can pick human copy without ever showing a+ * status code or URL. */+export class SessionExplorerError extends Error {+ code: string;+ constructor(message: string, code: string) {+ super(message);+ this.name = 'SessionExplorerError';+ this.code = code;+ }+}diff --git a/viewer/src/data/fileSource.ts b/viewer/src/data/fileSource.tsnew file mode 100644index 0000000..67bf758--- /dev/null+++ b/viewer/src/data/fileSource.ts@@ -0,0 +1,90 @@+import type {+ SessionExplorerSession,+ SessionMap,+} from '@/core/schema';+import { SessionExplorerError } from './errors';+import { listRows } from './memoryListing';+import { fnv1a, parseMapBytes, rowFromMap } from './parse';+import type { SessionMapSource } from './source';++export interface OpenResult {+ added: string[];+ failed: { name: string; reason: string }[];+}++export interface FileSource extends SessionMapSource {+ /** parse and hold `.json` / `.json.gz` map files; re-opening a session+ * replaces its earlier copy */+ addFiles(files: Iterable<File>): Promise<OpenResult>;+ readonly size: number;+}++const REASON: Record<string, string> = {+ unsupported_schema: 'not an agentplay v1 document',+ invalid_file: 'not valid JSON',+ unsupported_file: 'gzip is not supported by this browser',+};++/**+ * Maps the user opened (drag-and-drop or file picker), held in memory only.+ * Nothing is uploaded anywhere: parsing happens in this tab.+ */+export function fileSource(): FileSource {+ const docs = new Map<string, { map: SessionMap; row: SessionExplorerSession }>();+ let generation = 0;+ const src: FileSource = {+ get id() {+ return `files:${generation}`;+ },+ label: 'Opened files',+ get size() {+ return docs.size;+ },+ async addFiles(files) {+ const out: OpenResult = { added: [], failed: [] };+ for (const f of files) {+ try {+ const bytes = new Uint8Array(await f.arrayBuffer());+ const map = await parseMapBytes(bytes);+ const row = rowFromMap(map, {+ contentHash: fnv1a(bytes),+ bytesGz: f.name.endsWith('.gz') ? bytes.length : null,+ });+ docs.set(row.sessionId, { map, row });+ out.added.push(row.sessionId);+ } catch (err) {+ const code = err instanceof SessionExplorerError ? err.code : '';+ out.failed.push({ name: f.name, reason: REASON[code] ?? 'could not be read' });+ }+ }+ if (out.added.length) generation++;+ return out;+ },+ async status() {+ const rows = [...docs.values()].map((d) => d.row);+ const latest = rows.map((r) => r.sessionDate ?? '').sort().pop() || null;+ return { success: true, available: rows.length > 0, mapCount: rows.length, latestSessionDate: latest };+ },+ async sessions(params) {+ return listRows([...docs.values()].map((d) => d.row), params);+ },+ async maps(ids) {+ return {+ success: true,+ expiresIn: 3600,+ maps: ids.map((id) => {+ const d = docs.get(id);+ return d+ ? { sessionId: id, url: `memory:${encodeURIComponent(id)}`, schemaVersion: 1, contentHash: d.row.contentHash ?? id, bytesGz: d.row.bytesGz }+ : { sessionId: id, status: 'not_found' as const };+ }),+ };+ },+ async fetchMap(meta) {+ const d = docs.get(meta.sessionId);+ if (!d) throw new SessionExplorerError('map not open', 'not_found');+ return d.map;+ },+ };+ return src;+}diff --git a/viewer/src/data/hooks.ts b/viewer/src/data/hooks.tsnew file mode 100644index 0000000..bad0687--- /dev/null+++ b/viewer/src/data/hooks.ts@@ -0,0 +1,216 @@+import { useCallback, useEffect } from 'react';+import {+ keepPreviousData,+ useInfiniteQuery,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query';+import {+ isMapFound,+ type SessionExplorerMapBatch,+ type SessionExplorerMapMeta,+} from '@/core/schema';+import { fetchMapWithRetry, mapRequestIds } from '@/core/maps';+import { SessionExplorerError } from './errors';+import { useSessionMapSource } from './SourceContext';++export const sessionExplorerStatusKey = (sourceId: string) =>+ ['sessionExplorerStatus', sourceId] as const;++/** Whether the injected source has any maps. Fails closed: any error reads+ * as "not available" in the caller. */+export function useSessionExplorerStatus() {+ const source = useSessionMapSource();+ return useQuery({+ queryKey: sessionExplorerStatusKey(source.id),+ queryFn: () => source.status(),+ staleTime: 3 * 60 * 1000,+ retry: false,+ });+}++const SESSION_EXPLORER_PAGE_SIZE = 50;++export function useSessionExplorerSessions(+ search: string,+ range: { from?: string; to?: string } = {},+ enabled = true+) {+ const source = useSessionMapSource();+ return useInfiniteQuery({+ queryKey: [+ 'sessionExplorerSessions',+ source.id,+ search,+ range.from ?? null,+ range.to ?? null,+ ],+ queryFn: ({ pageParam }) =>+ source.sessions({+ search: search || undefined,+ from: range.from,+ to: range.to,+ pageSize: SESSION_EXPLORER_PAGE_SIZE,+ cursor: pageParam,+ }),+ initialPageParam: null as string | null,+ getNextPageParam: (last) => (last.hasMore ? last.nextCursor : null),+ enabled,+ staleTime: 60 * 1000,+ // Search is in the key: keep the old list up while a new term loads so+ // the filter input is never unmounted mid-typing.+ placeholderData: keepPreviousData,+ });+}++export const sessionExplorerMapBatchKey = (+ sourceId: string,+ ids: readonly string[]+) => ['sessionExplorerMapBatch', sourceId, ids.join(',')] as const;++export const sessionExplorerMapDocKey = (+ sourceId: string,+ contentHash: string | null+) => ['sessionExplorerMap', sourceId, contentHash] as const;++/** Map URLs come from the data source (relative server URLs, or demo/file+ * sources). Some sources may issue URLs that expire, so re-resolve often. */+const MAP_URL_STALE_MS = 60 * 1000;++/**+ * Batch-resolve the selected session plus the next two in the list, load the+ * selected map now and prefetch the other two into the contentHash-keyed+ * cache (documents are immutable per hash, so they never go stale). A map+ * whose URL expired or whose download failed on the network is re-resolved+ * once before the caller shows its inline error.+ */+export function useSessionExplorerMap(+ sessionId: string | null,+ listIds: readonly string[]+) {+ const source = useSessionMapSource();+ const queryClient = useQueryClient();+ const batchRoot = ['sessionExplorerMapBatch', source.id] as const;+ const unavailable = new Set<string>();+ for (const [, data] of queryClient.getQueriesData<SessionExplorerMapBatch>({+ queryKey: batchRoot,+ })) {+ for (const m of data?.maps ?? []) if (!isMapFound(m)) unavailable.add(m.sessionId);+ }+ const ids = sessionId ? mapRequestIds(listIds, sessionId, unavailable) : [];+ const batchKey = sessionExplorerMapBatchKey(source.id, ids);+ const batch = useQuery({+ queryKey: batchKey,+ queryFn: () => source.maps(ids),+ enabled: ids.length > 0,+ staleTime: MAP_URL_STALE_MS,+ retry: 1,+ // Learning a neighbour has no map changes the id set; keep the answer+ // we have so the selected map does not flash back to a skeleton.+ placeholderData: keepPreviousData,+ });+ for (const m of batch.data?.maps ?? []) if (!isMapFound(m)) unavailable.add(m.sessionId);++ const items = batch.data?.maps ?? [];+ const selected = items.find((m) => m.sessionId === sessionId);+ const found = selected && isMapFound(selected) ? selected : null;++ const loadDoc = useCallback(+ (item: SessionExplorerMapMeta) =>+ fetchMapWithRetry(+ item.url,+ async () => {+ const fresh = await source.maps([item.sessionId]);+ const m = fresh.maps.find((x) => x.sessionId === item.sessionId);+ if (!m || !isMapFound(m)) {+ throw new SessionExplorerError('Session map not found', 'not_found');+ }+ return m.url;+ },+ (url) => source.fetchMap({ ...item, url })+ ),+ [source]+ );++ const doc = useQuery({+ queryKey: sessionExplorerMapDocKey(source.id, found?.contentHash ?? null),+ queryFn: () => loadDoc(found as SessionExplorerMapMeta),+ enabled: !!found,+ staleTime: Infinity,+ gcTime: 10 * 60 * 1000,+ retry: false,+ });++ // Prefetch the neighbours without blocking the selected map.+ useEffect(() => {+ for (const m of batch.data?.maps ?? []) {+ if (m.sessionId === sessionId || !isMapFound(m)) continue;+ void queryClient.prefetchQuery({+ queryKey: sessionExplorerMapDocKey(source.id, m.contentHash),+ queryFn: () => loadDoc(m),+ staleTime: Infinity,+ gcTime: 10 * 60 * 1000,+ });+ }+ }, [batch.data, sessionId, queryClient, loadDoc, source.id]);++ const notFound = !!selected && !found;+ const retry = async () => {+ await queryClient.invalidateQueries({ queryKey: batchKey });+ if (found) await doc.refetch();+ };+ return {+ data: doc.data ?? null,+ isLoading: batch.isLoading || (!!found && doc.isLoading),+ isError: batch.isError || doc.isError || notFound,+ error: notFound+ ? new SessionExplorerError('sessionMap not found', 'not_found')+ : (batch.error ?? doc.error ?? null),+ unavailable: unavailable as ReadonlySet<string>,+ retry,+ };+}++export const promptImagesKey = (sourceId: string, sessionId: string, throughTurn: number) =>+ ['promptImages', sourceId, sessionId, throughTurn] as const;++/**+ * Which images were pasted into each turn of a session. Idle unless the+ * source can serve them and the caller has images to show. No retry: a+ * refusal (other machine, imported, transcript gone) is a settled answer.+ *+ * Keyed by the last image turn the caller needs: a live session only appends+ * turns, so an answer that covers `throughTurn` never goes stale, and a newly+ * pasted image (a higher turn) asks again instead of reading as unavailable.+ */+export function usePromptImages(sessionId: string, throughTurn: number, enabled: boolean) {+ const source = useSessionMapSource();+ const promptImages = source.promptImages?.bind(source);+ return useQuery({+ queryKey: promptImagesKey(source.id, sessionId, throughTurn),+ queryFn: () => promptImages!(sessionId),+ enabled: enabled && !!promptImages,+ retry: false,+ staleTime: Infinity,+ });+}++export const hookDetailKey = (sourceId: string, sessionId: string, uuid: string) =>+ ['hookDetail', sourceId, sessionId, uuid] as const;++/**+ * What one failed hook said and ran. Idle unless the source can serve it and+ * the event carries a `srcUuid`. No retry: a refusal (other machine, imported,+ * transcript gone) is a settled answer, and a transcript record never changes.+ */+export function useHookDetail(sessionId: string, uuid: string | undefined) {+ const source = useSessionMapSource();+ const hookDetail = source.hookDetail?.bind(source);+ return useQuery({+ queryKey: hookDetailKey(source.id, sessionId, uuid ?? ''),+ queryFn: () => hookDetail!(sessionId, uuid!),+ enabled: !!uuid && !!hookDetail,+ retry: false,+ staleTime: Infinity,+ });+}diff --git a/viewer/src/data/httpSource.ts b/viewer/src/data/httpSource.tsnew file mode 100644index 0000000..cd057a7--- /dev/null+++ b/viewer/src/data/httpSource.ts@@ -0,0 +1,131 @@+import {+ hookDetailResponseSchema,+ promptImagesResponseSchema,+ sessionExplorerMapBatchSchema,+ sessionExplorerSessionsSchema,+ sessionExplorerStatusSchema,+ type SessionMap,+} from '@/core/schema';+import { SessionExplorerError } from './errors';+import { parseMapBytes } from './parse';+import { SESSION_MAP_BATCH_MAX, type SessionMapSource } from './source';++async function failure(r: Response, what: string): Promise<SessionExplorerError> {+ let code = r.status === 404 ? 'not_found' : 'internal_error';+ try {+ const body: unknown = await r.json();+ if (+ body &&+ typeof body === 'object' &&+ 'code' in body &&+ typeof body.code === 'string'+ ) {+ code = body.code;+ }+ } catch {+ // non-JSON error body: keep the status-derived code+ }+ return new SessionExplorerError(`${what} failed: ${r.status}`, code);+}++/** Parse a JSON API answer, refusing an HTML fallback page (a static host+ * that answers every path with index.html is not an agentplay server). */+async function json(r: Response, what: string): Promise<unknown> {+ const type = r.headers.get('content-type') ?? '';+ if (!type.includes('json')) {+ throw new SessionExplorerError(`${what}: not a JSON answer`, 'no_server');+ }+ return r.json();+}++/**+ * The local `agentplay` CLI server: `GET {base}/api/status`,+ * `/api/sessions`, `/api/map`, then each map's own `url`. `baseUrl` is ''+ * for same-origin (the CLI serves this viewer), or e.g.+ * `http://127.0.0.1:8765` when the viewer runs from `vite dev`.+ */+export function httpSource(baseUrl: string): SessionMapSource {+ const base = baseUrl.replace(/\/+$/, '');+ const get = (path: string) =>+ fetch(`${base}${path}`, { headers: { Accept: 'application/json' } });+ return {+ id: `http:${base}`,+ label: 'Local sessions',+ async status() {+ const r = await get('/api/status');+ if (!r.ok) throw await failure(r, 'status');+ return sessionExplorerStatusSchema.parse(await json(r, 'status'));+ },+ async sessions(params) {+ const qs = new URLSearchParams();+ if (params.from) qs.set('from', params.from);+ if (params.to) qs.set('to', params.to);+ if (params.search) qs.set('search', params.search);+ if (params.pageSize) qs.set('pageSize', String(params.pageSize));+ if (params.cursor) qs.set('cursor', params.cursor);+ const r = await get(`/api/sessions?${qs.toString()}`);+ if (!r.ok) throw await failure(r, 'sessions');+ return sessionExplorerSessionsSchema.parse(await json(r, 'sessions'));+ },+ async maps(ids) {+ const qs = new URLSearchParams();+ for (const id of ids.slice(0, SESSION_MAP_BATCH_MAX)) {+ qs.append('session_id', id);+ }+ const r = await get(`/api/map?${qs.toString()}`);+ if (!r.ok) throw await failure(r, 'map');+ return sessionExplorerMapBatchSchema.parse(await json(r, 'map'));+ },+ async fetchMap(meta): Promise<SessionMap> {+ // A relative url is the server's own map-doc route; an absolute one+ // is supplied by the source (not this server), so it must not carry credentials.+ const absolute = /^[a-z]+:\/\//i.test(meta.url);+ const r = await fetch(absolute ? meta.url : `${base}${meta.url}`, {+ credentials: absolute ? 'omit' : 'same-origin',+ });+ if (!r.ok) {+ throw new SessionExplorerError(+ `Could not load the session map (HTTP ${r.status})`,+ r.status === 403 ? 'expired' : r.status === 404 ? 'not_found' : 'internal_error'+ );+ }+ return parseMapBytes(new Uint8Array(await r.arrayBuffer()));+ },+ async promptImages(sessionId) {+ const qs = new URLSearchParams({ id: sessionId });+ const r = await get(`/api/prompt-images?${qs.toString()}`);+ if (!r.ok) throw await failure(r, 'promptImages');+ return promptImagesResponseSchema.parse(await json(r, 'promptImages'));+ },+ async hookDetail(sessionId, uuid) {+ const qs = new URLSearchParams({ id: sessionId, uuid });+ const r = await get(`/api/hook-detail?${qs.toString()}`);+ if (!r.ok) throw await failure(r, 'hookDetail');+ return hookDetailResponseSchema.parse(await json(r, 'hookDetail'));+ },+ promptImageUrl(sessionId, turn, i) {+ const qs = new URLSearchParams({+ id: sessionId,+ turn: String(turn),+ i: String(i),+ });+ return `${base}/api/prompt-image?${qs.toString()}`;+ },+ };+}++/** True when `{base}/api/status` answers like an agentplay server. */+export async function probeServer(baseUrl: string): Promise<boolean> {+ try {+ const r = await fetch(`${baseUrl.replace(/\/+$/, '')}/api/status`, {+ headers: { Accept: 'application/json' },+ });+ if (!r.ok || !(r.headers.get('content-type') ?? '').includes('json')) {+ return false;+ }+ const body: unknown = await r.json();+ return !!body && typeof body === 'object' && 'available' in body;+ } catch {+ return false;+ }+}diff --git a/viewer/src/data/memoryListing.ts b/viewer/src/data/memoryListing.tsnew file mode 100644index 0000000..30c49ad--- /dev/null+++ b/viewer/src/data/memoryListing.ts@@ -0,0 +1,46 @@+import type {+ SessionExplorerSession,+ SessionExplorerSessionsPage,+} from '@/core/schema';+import type { SessionsParams } from './source';++/**+ * Server-equivalent listing over rows held in memory: date window and search+ * filter, newest first, and an opaque offset cursor, so in-memory sources+ * page exactly like the local server does.+ */+export function listRows(+ rows: readonly SessionExplorerSession[],+ params: SessionsParams+): SessionExplorerSessionsPage {+ const q = (params.search ?? '').trim().toLowerCase();+ const day = (r: SessionExplorerSession) =>+ r.sessionDate ?? r.startedAt.slice(0, 10);+ const matching = rows+ .filter((r) => !params.from || day(r) >= params.from)+ .filter((r) => !params.to || day(r) <= params.to)+ .filter(+ (r) =>+ !q ||+ [r.sessionId, r.sessionTitle ?? '', r.agentTool, ...r.repos, ...r.models]+ .join(' ')+ .toLowerCase()+ .includes(q)+ )+ .sort(+ (a, b) =>+ b.startedAt.localeCompare(a.startedAt) ||+ a.sessionId.localeCompare(b.sessionId)+ );+ const size = Math.min(Math.max(params.pageSize ?? 50, 1), 200);+ const offset = params.cursor ? Number(atob(params.cursor)) || 0 : 0;+ const page = matching.slice(offset, offset + size);+ const next = offset + size;+ const hasMore = next < matching.length;+ return {+ success: true,+ sessions: page,+ nextCursor: hasMore ? btoa(String(next)) : null,+ hasMore,+ };+}diff --git a/viewer/src/data/parse.ts b/viewer/src/data/parse.tsnew file mode 100644index 0000000..5a2e41c--- /dev/null+++ b/viewer/src/data/parse.ts@@ -0,0 +1,141 @@+import {+ sessionExplorerSessionSchema,+ sessionMapSchema,+ type SessionExplorerSession,+ type SessionMap,+} from '@/core/schema';+import { SessionExplorerError } from './errors';++/**+ * Rows with a repeated `sessionId` dropped, first occurrence kept. Pages use+ * an offset cursor, so a scan inserting newer rows between fetches shifts+ * later rows into the next page and repeats them.+ */+export function dedupeSessions<T extends { sessionId: string }>(+ rows: readonly T[]+): T[] {+ const seen = new Set<string>();+ return rows.filter((r) => !seen.has(r.sessionId) && !!seen.add(r.sessionId));+}++const isGzip = (b: Uint8Array) => b.length > 2 && b[0] === 0x1f && b[1] === 0x8b;++/** Inflate gzip bytes with the browser's own `DecompressionStream`. */+export async function gunzip(bytes: Uint8Array): Promise<Uint8Array> {+ if (typeof DecompressionStream === 'undefined') {+ throw new SessionExplorerError(+ 'gzip is not supported by this browser',+ 'unsupported_file'+ );+ }+ const stream = new Response(bytes as BodyInit).body!.pipeThrough(+ new DecompressionStream('gzip')+ );+ return new Uint8Array(await new Response(stream).arrayBuffer());+}++/** Bytes (plain or gzipped JSON) to a validated map document. */+export async function parseMapBytes(bytes: Uint8Array): Promise<SessionMap> {+ const raw = isGzip(bytes) ? await gunzip(bytes) : bytes;+ let json: unknown;+ try {+ json = JSON.parse(new TextDecoder().decode(raw));+ } catch {+ throw new SessionExplorerError('map is not JSON', 'invalid_file');+ }+ return parseMapJson(json);+}++export function parseMapJson(json: unknown): SessionMap {+ const parsed = sessionMapSchema.safeParse(json);+ if (!parsed.success) {+ throw new SessionExplorerError(+ 'This file is not a valid agentplay session map',+ 'unsupported_schema'+ );+ }+ return parsed.data;+}++/** A cheap, stable content hash (FNV-1a, 32 bit) for cache keys. */+export function fnv1a(bytes: Uint8Array): string {+ let h = 0x811c9dc5;+ for (let i = 0; i < bytes.length; i++) {+ h ^= bytes[i];+ h = Math.imul(h, 0x01000193);+ }+ return (h >>> 0).toString(16).padStart(8, '0');+}++/**+ * The session-list row for a map document, for sources that only have the+ * documents themselves (dropped files). Mirrors what a server reports.+ */+export function rowFromMap(+ map: SessionMap,+ extra: { contentHash: string; bytesGz?: number | null; title?: string | null }+): SessionExplorerSession {+ const s = map.session;+ const t = map.totals;+ const started = Date.parse(s.startedAt);+ const ended = Number.isFinite(started)+ ? new Date(started + (s.durationMs || 0)).toISOString()+ : null;+ const sessionTitle =+ extra.title ??+ (typeof (s as Record<string, unknown>).title === 'string'+ ? ((s as Record<string, unknown>).title as string)+ : null);+ const outputs: Record<string, number> = {};+ for (const e of map.events) {+ if (+ [+ 'commit',+ 'pr_merge',+ 'pr_close',+ 'pr_comment',+ 'ticket',+ 'artifact',+ 'skill_write',+ ].includes(e.kind)+ )+ outputs[e.kind] = (outputs[e.kind] ?? 0) + 1;+ }+ return sessionExplorerSessionSchema.parse({+ sessionId: s.id,+ sessionDate: s.startedAt.slice(0, 10),+ startedAt: s.startedAt,+ endedAt: ended,+ durationMs: s.durationMs,+ agentTool: s.agentTool,+ models: s.models,+ repos: map.repos.map((r) => r.name),+ calls: t.calls,+ requests: t.requests,+ subagents: t.subagents,+ errors: t.errors,+ filesTouched: t.filesTouched,+ costUsd: t.costUsd,+ tokens: t.tokens,+ userTurns: t.userTurns,+ sessionTitle,+ contentHash: extra.contentHash,+ bytesGz: extra.bytesGz ?? null,+ updatedAt: null,+ errorsBySource: t.errorsBySource,+ retries: t.retries,+ delays: t.delays,+ maxContext: t.maxContext,+ compactions: t.compactions,+ role: s.role ?? null,+ parentSessionId: s.parentSessionId ?? null,+ tasks: map.tasks?.length,+ outputs,+ prs: map.prs.map((p) => ({+ repo: p.repo,+ number: p.number,+ url: p.url,+ state: p.state,+ })),+ });+}diff --git a/viewer/src/data/source.ts b/viewer/src/data/source.tsnew file mode 100644index 0000000..d63e892--- /dev/null+++ b/viewer/src/data/source.ts@@ -0,0 +1,56 @@+import type {+ HookDetailResponse,+ PromptImagesResponse,+ SessionExplorerMapBatch,+ SessionExplorerMapMeta,+ SessionExplorerSessionsPage,+ SessionExplorerStatus,+ SessionMap,+} from '@/core/schema';++export interface SessionsParams {+ /** inclusive UTC `YYYY-MM-DD` */+ from?: string;+ to?: string;+ search?: string;+ pageSize?: number;+ cursor?: string | null;+}++/**+ * Where the explorer gets its data. Every method answers with the same+ * camelCase shapes the zod schemas in `core/schema.ts` parse, so a source is+ * swappable without touching a component.+ */+export interface SessionMapSource {+ /** stable id, folded into every query key so switching sources never+ * serves one source's cached answer for another */+ readonly id: string;+ /** short human label for the app bar ("Local server", "Demo", ...) */+ readonly label: string;+ status(): Promise<SessionExplorerStatus>;+ sessions(params: SessionsParams): Promise<SessionExplorerSessionsPage>;+ /** 1-20 ids; unknown ids come back as `{sessionId, status: 'not_found'}` */+ maps(ids: string[]): Promise<SessionExplorerMapBatch>;+ /** load one map document from its batch entry */+ fetchMap(meta: SessionExplorerMapMeta): Promise<SessionMap>;+ /**+ * Optional. Which images were pasted into each user turn of a session.+ * Only a source that sits next to the recording machine can serve them;+ * rejects when they are unavailable (another machine, imported, gone).+ * Absent on sources that never have the bytes (file, demo).+ */+ promptImages?(sessionId: string): Promise<PromptImagesResponse>;+ /** Optional. Same-origin URL of one pasted image's bytes (`turn` is+ * 1-based, `i` is the image's index within that turn). */+ promptImageUrl?(sessionId: string, turn: number, i: number): string;+ /**+ * Optional. The message and command of one failed hook, by the `srcUuid`+ * its error event carries. Same rules as `promptImages`: only a source next+ * to the recording machine can answer, and it rejects otherwise.+ */+ hookDetail?(sessionId: string, uuid: string): Promise<HookDetailResponse>;+}++/** Max ids per `maps()` call. */+export const SESSION_MAP_BATCH_MAX = 20;diff --git a/viewer/src/explorer/ExplorerToolbar.tsx b/viewer/src/explorer/ExplorerToolbar.tsxnew file mode 100644index 0000000..3237b2d--- /dev/null+++ b/viewer/src/explorer/ExplorerToolbar.tsx@@ -0,0 +1,289 @@+import { useState, type ReactNode } from 'react';+import { CaretDown, Check } from '@phosphor-icons/react';+import { Button } from '@/components/ui/button';+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from '@/components/ui/command';+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover';+import { cn } from '@/lib/utils';+import { taskFilterLabel, type AgentOption } from '@/core/sessionLayout';+import { fmtUsd } from '@/core/sessionMapModel';+import {+ taskNoun,+ type ModelUsage,+ type TaskWindow,+} from '@/core/sessionScope';++interface Props {+ tasks: TaskWindow[];+ task: number | null;+ onTask: (n: number | null) => void;+ /** the Agent picker's rows (`agentOptions`); empty hides the picker */+ agents: AgentOption[];+ /** the agent lens: `main` or a subagent id */+ lens: string;+ lensLabel: string | null;+ onLens: (id: string) => void;+ models: ModelUsage[];+ model: string | null;+ onModel: (model: string | null) => void;+ /** a filter or subagent is narrowing the replay */+ filtered: boolean;+ onClear: () => void;+}++/**+ * The Task / Agent / Model filters, rendered inline at the right of the+ * session header's one line (fit-viewport layout). Each filter opens a+ * popover; the URL params and what each choice does are unchanged. What the+ * timeline, map and Activity highlight is the dock's category chips.+ */+export function ExplorerToolbar(props: Props) {+ return (+ <div+ role="group"+ aria-label="Filter the map, timeline and side panel"+ className="flex shrink-0 flex-wrap items-center gap-1.5"+ >+ {props.tasks.length > 1 ? <TaskPicker {...props} /> : null}+ {props.agents.length ? <AgentPicker {...props} /> : null}+ {props.models.length > 1 ? <ModelPicker {...props} /> : null}+ {props.filtered ? (+ <Button+ variant="link"+ size="sm"+ onClick={props.onClear}+ className="h-7 px-1.5 text-ds-text-subtle"+ >+ Clear filters+ </Button>+ ) : null}+ </div>+ );+}++/** The trigger's "Label: value ▾" contents. */+function TriggerLabel({+ label,+ value,+ active,+}: {+ label: string;+ value: string;+ active: boolean;+}) {+ return (+ <>+ <span className="text-ds-text-subtle">{label}:</span>+ <span+ className={cn(+ 'min-w-0 truncate',+ active ? 'text-ds-brand-default' : 'text-ds-text-darker'+ )}+ >+ {value}+ </span>+ <CaretDown size={10} aria-hidden className="shrink-0" />+ </>+ );+}++/** A filter popover: trigger button + content, closed on a pick. */+function Picker({+ label,+ value,+ active,+ width = 'w-80',+ children,+}: {+ label: string;+ value: string;+ active: boolean;+ width?: string;+ children: (close: () => void) => ReactNode;+}) {+ const [open, setOpen] = useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ aria-label={`${label}: ${value}`}+ className={cn(+ 'h-7 max-w-[260px] gap-1 px-2.5 font-normal',+ active && 'border-ds-brand-subtler bg-ds-brand-lightest'+ )}+ >+ <TriggerLabel label={label} value={value} active={active} />+ </Button>+ }+ />+ <PopoverContent align="start" className={cn(width, 'p-0')}>+ {children(() => setOpen(false))}+ </PopoverContent>+ </Popover>+ );+}++const Tick = ({ on }: { on: boolean }) => (+ <Check+ size={12}+ aria-hidden+ className={cn('shrink-0', on ? 'opacity-100' : 'opacity-0')}+ />+);++const Meta = ({ children }: { children: ReactNode }) => (+ <span className="ml-auto shrink-0 font-mono ds-text-body-xs-medium text-ds-text-subtler tabular-nums">+ {children}+ </span>+);++function TaskPicker({ tasks, task, onTask }: Props) {+ const noun = taskNoun(tasks);+ const many = noun.many.toLowerCase();+ return (+ <Picker+ label={noun.one}+ value={taskFilterLabel(tasks, task)}+ active={task != null}+ >+ {(close) => (+ <Command>+ <CommandInput placeholder={`Search ${many}…`} className="h-9" />+ <CommandList className="max-h-[320px]">+ <CommandEmpty>No {noun.one.toLowerCase()} matches.</CommandEmpty>+ <CommandGroup>+ <CommandItem+ value={`all ${many}`}+ onSelect={() => {+ onTask(null);+ close();+ }}+ >+ <Tick on={task == null} />+ All {many}+ <Meta>{tasks.length}</Meta>+ </CommandItem>+ {tasks.map((t) => (+ <CommandItem+ key={t.n}+ value={`${t.n} ${t.name}`}+ onSelect={() => {+ onTask(task === t.n ? null : t.n);+ close();+ }}+ >+ <Tick on={task === t.n} />+ <span className="shrink-0 font-mono tabular-nums">{t.n}</span>+ <span className="min-w-0 truncate" title={t.name}>+ {t.named ? t.name : ''}+ </span>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ )}+ </Picker>+ );+}++function AgentPicker({ agents, lens, lensLabel, onLens }: Props) {+ const subCount = agents.length - 1;+ const subNoun = `${subCount} subagent${subCount === 1 ? '' : 's'}`;+ return (+ <Picker+ label="Agent"+ value={lensLabel ?? `All agents (${subNoun})`}+ active={lens !== 'main'}+ >+ {(close) => (+ <Command>+ <CommandInput placeholder="Search subagents…" className="h-9" />+ <CommandList className="max-h-[320px]">+ <CommandEmpty>No subagent matches.</CommandEmpty>+ <CommandGroup>+ {agents.map((a) => (+ <CommandItem+ key={a.id}+ value={`${a.label} ${a.id}`}+ className={cn(a.empty && 'opacity-50')}+ onSelect={() => {+ onLens(a.id);+ close();+ }}+ >+ <Tick on={lens === a.id} />+ <span className="min-w-0 truncate">{a.label}</span>+ <Meta>+ {a.calls} calls · {fmtUsd(a.cost)}+ </Meta>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ <p className="border-t border-ds-border-subtlest px-3 py-1.5 ds-text-body-xs-medium text-ds-text-subtler">+ A subagent has no further nesting.+ </p>+ </Command>+ )}+ </Picker>+ );+}++function ModelPicker({ models, model, onModel }: Props) {+ return (+ <Picker+ label="Model"+ value={model ?? 'All models'}+ active={model != null}+ width="w-72"+ >+ {(close) => (+ <Command>+ <CommandList className="max-h-[320px]">+ <CommandGroup>+ <CommandItem+ value="all models"+ onSelect={() => {+ onModel(null);+ close();+ }}+ >+ <Tick on={model == null} />+ All models+ </CommandItem>+ {models.map((m) => (+ <CommandItem+ key={m.model}+ value={m.model}+ className={cn(m.requests === 0 && 'opacity-50')}+ onSelect={() => {+ onModel(model === m.model ? null : m.model);+ close();+ }}+ >+ <Tick on={model === m.model} />+ <span className="min-w-0 truncate">{m.model}</span>+ <Meta>{m.requests} req</Meta>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ )}+ </Picker>+ );+}diff --git a/viewer/src/explorer/FixNowDialog.tsx b/viewer/src/explorer/FixNowDialog.tsxnew file mode 100644index 0000000..26749c5--- /dev/null+++ b/viewer/src/explorer/FixNowDialog.tsx@@ -0,0 +1,137 @@+import { useState } from 'react';+import { ArrowSquareOut } from '@phosphor-icons/react';+import { buttonVariants } from '@/components/ui/button';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog';+import { connectUrl } from '@/core/entelligence';+import { cn } from '@/lib/utils';+import { DELIVERIES, type DeliveryId, type SampleComment } from './reviewSample';++/**+ * What "Fix now" on a review comment opens: the rule the comment turns into,+ * and the four build-time routes it can reach the agent by.+ *+ * The viewer installs nothing. Every route here happens when a session is+ * built, on a machine with the repo and an account, which is exactly why the+ * block around it is locked -- so the dialog says so rather than offering a+ * button that would quietly do nothing.+ */+export function FixNowDialog({ c }: { c: SampleComment }) {+ const [delivery, setDelivery] = useState<DeliveryId>(c.fix.delivery);+ return (+ <Dialog>+ <DialogTrigger+ render={+ <button+ type="button"+ className={cn(+ buttonVariants({ variant: 'secondary', size: 'sm' }),+ 'cursor-pointer'+ )}+ >+ Fix now+ </button>+ }+ />+ <DialogContent aria-describedby={undefined}>+ <div className="flex flex-col gap-1">+ <DialogTitle className="ds-text-body-sm-semibold text-ds-text-darker">+ Fix {c.flagged.toLowerCase()}+ </DialogTitle>+ <DialogDescription className="font-mono ds-text-body-xs-medium text-ds-text-subtle">+ {c.file} {c.line} · edit #{c.editSeq} · {c.learning}+ </DialogDescription>+ </div>++ <section className="flex flex-col gap-1 rounded-lg border border-ds-border-subtlest bg-ds-gray-subtlest p-3">+ <h3 className="ds-text-body-xs-semibold text-ds-text-subtle">+ The rule+ </h3>+ <p className="ds-text-body-xs-medium text-ds-text-default">+ {c.fix.rule}+ </p>+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Fires: {c.fix.trigger}+ </p>+ </section>++ <section className="flex flex-col gap-2">+ <h3 className="ds-text-body-xs-semibold text-ds-text-subtle">+ Delivery at build time+ </h3>+ <div role="radiogroup" aria-label="Delivery at build time" className="flex flex-col gap-1.5">+ {DELIVERIES.map((d) => (+ <button+ key={d.id}+ type="button"+ role="radio"+ aria-checked={delivery === d.id}+ onClick={() => setDelivery(d.id)}+ className={cn(+ 'flex cursor-pointer flex-col gap-0.5 rounded-lg border p-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ds-brand-subtler',+ delivery === d.id+ ? 'border-ds-brand-subtler bg-ds-brand-lightest'+ : 'border-ds-border-subtlest hover:bg-ds-gray-subtlest'+ )}+ >+ <span className="ds-text-body-xs-semibold text-ds-text-darker">+ {d.label}+ {d.id === c.fix.delivery ? (+ <span className="ml-1.5 ds-text-body-xs-medium text-ds-brand-default">+ suggested+ </span>+ ) : null}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {d.detail}+ </span>+ </button>+ ))}+ </div>+ </section>++ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Nothing is written from here. Entelligence compiles the rule in when+ this repo’s next session is built, records which sessions got+ it, and holds a share back so the before/after is measured against a+ control rather than against memory.+ </p>++ <div className="flex flex-wrap items-center gap-2">+ <a+ href={connectUrl('fix-dialog')}+ target="_blank"+ rel="noopener noreferrer"+ className={cn(+ buttonVariants({ variant: 'default', size: 'sm' }),+ 'border-transparent bg-ds-brand-fill font-semibold text-ds-brand-on-fill hover:bg-ds-brand-subtler active:bg-ds-brand-subtler',+ 'shadow-[0_0_0_1px_var(--primitive-brand-green-500),0_3px_16px_-2px_var(--primitive-brand-green-400)] transition-shadow hover:shadow-[0_0_0_1px_var(--primitive-brand-green-400),0_5px_24px_-2px_var(--primitive-brand-green-400)]'+ )}+ >+ Connect your PRs+ <ArrowSquareOut size={12} aria-hidden />+ </a>+ <DialogClose+ render={+ <button+ type="button"+ className={cn(+ buttonVariants({ variant: 'ghost', size: 'sm' }),+ 'cursor-pointer'+ )}+ >+ Close+ </button>+ }+ />+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/viewer/src/explorer/HookDetail.tsx b/viewer/src/explorer/HookDetail.tsxnew file mode 100644index 0000000..5638e73--- /dev/null+++ b/viewer/src/explorer/HookDetail.tsx@@ -0,0 +1,48 @@+import { Skeleton } from '@/components/ui/skeleton';+import { useHookDetail } from '@/data/hooks';++/** What a failed hook said and ran. A map never carries this text, so it is+ * read from the transcript on demand and only on the recording machine. */+export function HookDetail({+ sessionId,+ uuid,+}: {+ sessionId: string;+ uuid: string;+}) {+ const query = useHookDetail(sessionId, uuid);+ if (query.isPending && query.fetchStatus !== 'idle')+ return (+ <div className="mt-2 flex flex-col gap-1" aria-hidden>+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-2/3" />+ </div>+ );+ const { message, command } = query.data ?? {};+ if (!message && !command)+ return (+ <p className="mt-2 ds-text-body-xs-medium text-ds-text-subtler">+ Details stay on the machine that recorded the session.+ </p>+ );+ return (+ <div className="mt-2 flex flex-col gap-1.5 ds-text-body-xs-medium">+ {message ? (+ <div>+ <div className="text-ds-text-subtle">message</div>+ <p className="max-h-24 overflow-y-auto whitespace-pre-wrap break-words text-ds-text-darker">+ {message}+ </p>+ </div>+ ) : null}+ {command ? (+ <div>+ <div className="text-ds-text-subtle">command</div>+ <code className="block break-all font-mono text-ds-text-darker">+ {command}+ </code>+ </div>+ ) : null}+ </div>+ );+}diff --git a/viewer/src/explorer/MapPlayerParts.tsx b/viewer/src/explorer/MapPlayerParts.tsxnew file mode 100644index 0000000..9a05835--- /dev/null+++ b/viewer/src/explorer/MapPlayerParts.tsx@@ -0,0 +1,367 @@+import { useMemo, type ReactNode } from 'react';+import type {+ SessionExplorerSession,+ SessionMap,+} from '@/core/schema';+import { EmptyState } from '@/components/EmptyState';+import { agentToolLabel, sessionTitle } from './SessionList';+import { SessionMapSvg } from './SessionMapSvg';+import {+ ScopeStrip,+ SessionSidebar,+ SidebarRail,+ SubagentSidebar,+} from './SessionSidebar';+import {+ adjacentSubagent,+ adjacentTask,+ mapChipSelection,+ mapFocus,+ pathFocus,+ resolveSidebarTab,+ sidebarRailLabel,+ errorClickAction,+ wholeSessionErrors,+ taskErrors,+ sidebarTabs,+ stripState,+ subStripMeta,+ taskAt,+ taskIndexWindow,+ taskStripMeta,+ touchedGroups,+ windowProgress,+ type Category,+ type SidebarTab,+ type SubagentInfo,+} from '@/core/sessionLayout';+import { srcSeqOf, type TreeNode } from '@/core/sessionMapModel';+import { hasReplayEvents, taskNoun } from '@/core/sessionScope';+import type { ExplorerScope } from './useExplorerScope';+import type { MapModel } from './usePlaybackWindow';++/** Sidebar state owned by `SessionExplorer`, rendered by the map player+ * (session mode needs the loaded map) or by the explorer itself. */+export interface SidebarCtl {+ /** `list`: the sessions list; `session`: only the selected session */+ mode: 'list' | 'session';+ collapsed: boolean;+ setCollapsed: (collapsed: boolean) => void;+ showList: () => void;+ showSession: () => void;+ /** the sessions list element (list mode) */+ list: ReactNode;+}++/** Open the subagent `delta` places before/after the open one, if any. */+function stepSubagent(x: ExplorerScope, delta: number) {+ const next = x.sub ? adjacentSubagent(x.subs, x.sub, delta) : null;+ if (next) x.setLens(next);+}++/** The one sidebar: rail (collapsed), the open subagent, the sessions list,+ * or the selected session with its Tasks / Subagents / Insights tabs. */+export function ExplorerSidebar({+ x,+ model,+ row,+ sidebar,+ subInfo,+ tabParam,+ onTab,+ insights,+ onFocusCategory,+ p,+ onSeek,+ onJumpToTaskErrors,+}: {+ x: ExplorerScope;+ model: MapModel;+ row: SessionExplorerSession | null;+ sidebar: SidebarCtl;+ subInfo: SubagentInfo | null;+ tabParam: SidebarTab | null;+ onTab: (tab: SidebarTab) => void;+ insights: ReactNode;+ onFocusCategory?: (c: Category) => void;+ p: number;+ onSeek: (index: number) => void;+ /** Scope to a task, open its errors and land on the first one. */+ onJumpToTaskErrors?: (task: number | null, seq: number) => void;+}) {+ const { fullMap, tasks, subs } = x;+ if (sidebar.collapsed) {+ return (+ <SidebarRail+ label={sidebarRailLabel({+ subLabel: subInfo?.label ?? null,+ mode: sidebar.mode,+ sessionId: x.map.session.id,+ taskCount: tasks.length,+ noun: taskNoun(tasks),+ })}+ onExpand={() => sidebar.setCollapsed(false)}+ />+ );+ }+ if (subInfo)+ return <SubagentPane x={x} sub={subInfo} model={model} sidebar={sidebar} />;+ if (sidebar.mode === 'list') return <>{sidebar.list}</>;+ // Over the whole session, whatever the prompt or model scope, so the Errors+ // count and list never narrow. A row is addressed by its whole-session `seq`;+ // `onSelectError` seeks in place or re-scopes first when the scope hides it.+ const errs = wholeSessionErrors(fullMap);+ const playhead = x.map.events[p];+ const playheadSeq = playhead ? (srcSeqOf(playhead) ?? p) : null;+ // Over the whole session, like the rest of the task list.+ const errsByTask = taskErrors(fullMap);+ const tabs = sidebarTabs(tasks.length, subs.length, errs.total);+ const s = x.map.session;+ return (+ <SessionSidebar+ row={row}+ title={row ? sessionTitle(row) : `${agentToolLabel(s.agentTool)} session`}+ startedAt={fullMap.session.startedAt}+ durationMs={fullMap.session.durationMs}+ costUsd={fullMap.totals.costUsd}+ prCount={fullMap.prs.length}+ errors={errs.total}+ tasks={tasks}+ taskSums={x.taskSums}+ task={x.scope.task}+ onSelectTask={(n) => x.setScope((s0) => ({ ...s0, task: n }))}+ subs={subs}+ onOpenSub={x.setLens}+ tabs={tabs}+ tab={resolveSidebarTab(tabParam, tabs)}+ onTab={onTab}+ onShowList={sidebar.showList}+ onCollapse={() => sidebar.setCollapsed(true)}+ insights={insights}+ onFocusCategory={onFocusCategory}+ errorGroups={errs.groups}+ playheadSeq={playheadSeq}+ onSelectError={(err) => {+ const act = errorClickAction(err, x.map);+ if (act.kind === 'seek') onSeek(act.index);+ else onJumpToTaskErrors?.(act.task, act.seq);+ }}+ taskErrors={errsByTask}+ onJumpToTaskErrors={onJumpToTaskErrors}+ />+ );+}++/** The subagent view's sidebar: the helper and what it touched (from the+ * lensed map's tree). */+function SubagentPane({+ x,+ sub,+ model,+ sidebar,+}: {+ x: ExplorerScope;+ sub: SubagentInfo;+ model: MapModel;+ sidebar: SidebarCtl;+}) {+ const groups = useMemo(+ () => touchedGroups(model.tree, model.refs),+ [model.tree, model.refs]+ );+ return (+ <SubagentSidebar+ sub={sub}+ total={x.subs.length}+ tasks={x.tasks}+ startedAt={x.fullMap.session.startedAt}+ groups={groups}+ onBack={() => x.setLens('main')}+ onStep={(d) => stepSubagent(x, d)}+ canPrev={!!adjacentSubagent(x.subs, sub.id, -1)}+ canNext={!!adjacentSubagent(x.subs, sub.id, 1)}+ onCollapse={() => sidebar.setCollapsed(true)}+ />+ );+}++/** The radial map, filling the middle row. */+export function MapPane({+ map,+ model,+ p,+ onSeek,+ onNodeAction,+ filtered,+ filteredCopy,+ playing,+ selected,+ path = null,+}: {+ map: SessionMap;+ model: MapModel;+ p: number;+ onSeek: (i: number) => void;+ onNodeAction: (node: TreeNode) => boolean;+ /** a task / model / agent filter is set (for the empty-state copy) */+ filtered: boolean;+ /** the empty-state sentence naming the active filters */+ filteredCopy: string;+ /** caps the map to the recently-touched window while playback runs */+ playing: boolean;+ /** the dock's category chips: a narrowing selection lights its nodes */+ selected: ReadonlySet<Category>;+ /** event `seq`s of a picked review comment's causal path, lit over+ * everything else; null when no comment is picked */+ path?: readonly number[] | null;+}) {+ const chipFocus = useMemo(+ () => mapFocus(model.tree, model.refs, map.events, selected),+ [model.tree, model.refs, map.events, selected]+ );+ const onPath = useMemo(+ () =>+ path?.length+ ? pathFocus(model.tree, model.refs, map.events, path)+ : null,+ [model.tree, model.refs, map.events, path]+ );+ // A picked path wins over the chips: it is the more specific thing the+ // user just asked to see, and intersecting the two can empty the map.+ const focus = onPath ?? chipFocus;+ // ...and winning has to mean the chips stop narrowing the map at all, not+ // just that `focus` is overridden: the map filters its event refs by the+ // selection too (`mapChipSelection`).+ const chips = mapChipSelection(selected, onPath != null);+ return (+ <section className="flex h-full min-h-0 min-w-0 flex-col rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-3">+ {hasReplayEvents(map) ? (+ <SessionMapSvg+ onNodeAction={onNodeAction}+ map={map}+ tree={model.tree}+ nodes={model.nodes}+ refs={model.refs}+ p={p}+ onSeek={onSeek}+ playing={playing}+ focus={focus}+ selected={chips}+ />+ ) : (+ <EmptyState+ title={+ filtered+ ? 'Nothing in this scope'+ : 'Nothing recorded in this session'+ }+ description={+ filtered+ ? filteredCopy+ : 'The map has no events to replay.'+ }+ size="sm"+ />+ )}+ </section>+ );+}++/** The one-line task / subagent strip, floating above the timeline dock. */+export function TimelineStrip({+ x,+ subInfo,+ playing,+ p,+ collapsed,+}: {+ x: ExplorerScope;+ subInfo: SubagentInfo | null;+ playing: boolean;+ p: number;+ collapsed: boolean;+}) {+ const strip = stripState({+ task: x.scope.task,+ sub: x.sub,+ collapsed,+ playing,+ playheadTask: taskAt(x.map.events, p),+ taskCount: x.tasks.length,+ });+ const lastIdx = Math.max(0, x.map.events.length - 1);+ if (strip?.kind === 'sub' && subInfo) {+ return (+ <ScopeStrip+ lead={`${strip.playing ? '▶ Playing' : 'Subagent'} ${subInfo.index}/${x.subs.length}`}+ name={subInfo.label}+ meta={subStripMeta(x.fullMap.session.startedAt, subInfo)}+ progress={+ strip.playing ? windowProgress({ start: 0, end: lastIdx }, p) : null+ }+ onPrev={() => stepSubagent(x, -1)}+ onNext={() => stepSubagent(x, 1)}+ canPrev={!!adjacentSubagent(x.subs, subInfo.id, -1)}+ canNext={!!adjacentSubagent(x.subs, subInfo.id, 1)}+ onClear={() => x.setLens('main')}+ prevLabel="Previous subagent"+ nextLabel="Next subagent"+ clearLabel="Back to the main session"+ />+ );+ }+ if (strip?.kind !== 'task') return null;+ return (+ <TaskStrip+ x={x}+ n={strip.n}+ playing={strip.playing}+ followsPlayhead={strip.followsPlayhead}+ p={p}+ lastIdx={lastIdx}+ />+ );+}++function TaskStrip({+ x,+ n,+ playing,+ followsPlayhead,+ p,+ lastIdx,+}: {+ x: ExplorerScope;+ n: number;+ playing: boolean;+ followsPlayhead: boolean;+ p: number;+ lastIdx: number;+}) {+ const { tasks } = x;+ const t = tasks.find((w) => w.n === n);+ if (!t) return null;+ const select = (task: number | null) => x.setScope((s0) => ({ ...s0, task }));+ const { one } = taskNoun(tasks);+ const prev = adjacentTask(tasks, t.n, -1);+ const next = adjacentTask(tasks, t.n, 1);+ const win = followsPlayhead+ ? taskIndexWindow(x.map.events, t.n)+ : { start: 0, end: lastIdx };+ return (+ <ScopeStrip+ lead={`${playing ? '▶ Playing' : one} ${t.n}/${tasks.length}`}+ name={t.name}+ meta={taskStripMeta(x.fullMap.session.startedAt, t, x.taskSums.get(t.n))}+ progress={playing ? windowProgress(win, p) : null}+ onPrev={() => select(prev)}+ onNext={() => select(next)}+ canPrev={prev != null && prev !== t.n}+ canNext={next != null && next !== t.n}+ onClear={followsPlayhead ? null : () => select(null)}+ prevLabel={`Previous ${one.toLowerCase()}`}+ nextLabel={`Next ${one.toLowerCase()}`}+ clearLabel={`Clear the ${one.toLowerCase()} filter`}+ />+ );+}diff --git a/viewer/src/explorer/PlaybackControls.tsx b/viewer/src/explorer/PlaybackControls.tsxnew file mode 100644index 0000000..d4d1307--- /dev/null+++ b/viewer/src/explorer/PlaybackControls.tsx@@ -0,0 +1,74 @@+import { Pause, Play, SkipBack } from '@phosphor-icons/react';+import { Button } from '@/components/ui/button';+import { SPEEDS, type PlaybackState } from '@/core/playback';+import { fmtDur } from '@/core/sessionMapModel';++interface Props {+ state: PlaybackState;+ /** wall clock at the playhead ("HH:MM") */+ clock: string;+ /** ms since session start at the playhead */+ elapsedMs: number;+ durationMs: number;+ onStart: () => void;+ onToggle: () => void;+ onCycleSpeed: () => void;+}++/** The dock's playback group: start, play / pause, speed and the readout.+ * Stepping and the jumps stay on the keyboard (see the replay region). */+export function PlaybackControls({+ state,+ clock,+ elapsedMs,+ durationMs,+ onStart,+ onToggle,+ onCycleSpeed,+}: Props) {+ return (+ <div className="flex shrink-0 items-center gap-1.5">+ <Button+ variant="outline"+ size="iconSm"+ onClick={onStart}+ disabled={state.n < 1}+ aria-label="Jump to start"+ >+ <SkipBack size={14} weight="fill" />+ </Button>+ <Button+ size="sm"+ onClick={onToggle}+ disabled={state.n < 2}+ aria-label={state.playing ? 'Pause (Space)' : 'Play (Space)'}+ className="min-w-[76px]"+ >+ {state.playing ? (+ <Pause size={14} weight="fill" />+ ) : (+ <Play size={14} weight="fill" />+ )}+ {state.playing ? 'Pause' : 'Play'}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={onCycleSpeed}+ aria-label="Playback speed"+ className="font-mono"+ >+ {SPEEDS[state.speedIdx]}×+ </Button>+ <span+ className="font-mono ds-text-body-xs-medium text-ds-text-subtle tabular-nums"+ title={`${fmtDur(elapsedMs)} of ${fmtDur(durationMs)}`}+ >+ {state.n+ ? `${(state.p + 1).toLocaleString()}/${state.n.toLocaleString()}`+ : '0/0'}{' '}+ · {clock}+ </span>+ </div>+ );+}diff --git a/viewer/src/explorer/PromptImages.tsx b/viewer/src/explorer/PromptImages.tsxnew file mode 100644index 0000000..b35dced--- /dev/null+++ b/viewer/src/explorer/PromptImages.tsx@@ -0,0 +1,285 @@+/**+ * The images pasted into one task's prompts: a thumbnail grid, and a lightbox+ * to read one at full size. The bytes live on the machine that recorded the+ * session, so every way they can be missing (a source that never has them, a+ * refused request, an entry the server marks unavailable, an image that fails+ * to load) lands on the same honest "unavailable" state instead of an error.+ */+import { useMemo, useState } from 'react';+import { ImageSquare, WarningCircle, X } from '@phosphor-icons/react';+import { buttonVariants } from '@/components/ui/button';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogTitle,+} from '@/components/ui/dialog';+import { Skeleton } from '@/components/ui/skeleton';+import {+ imageLabel,+ pasteTag,+ type PromptImageTurn,+} from '@/core/promptImages';+import { usePromptImages } from '@/data/hooks';+import { useSessionMapSource } from '@/data/SourceContext';+import { cn } from '@/lib/utils';++const TILE =+ 'relative aspect-[4/3] overflow-hidden rounded-lg border border-ds-border-subtlest bg-ds-gray-subtlest';++interface Slot {+ key: string;+ turn: number;+ /** index within its turn, what the image endpoint takes */+ i: number;+ pasteId: number | null;+ mediaType: string;+ available: boolean;+}++const imagesLabel = (n: number) => `${n} ${n === 1 ? 'image' : 'images'}`;++function Unavailable({ count }: { count: number }) {+ return (+ <div+ role="note"+ className="flex items-start gap-2 rounded-lg border border-dashed border-ds-border-subtler p-3 ds-text-body-xs-medium text-ds-text-subtle"+ >+ <WarningCircle size={14} aria-hidden className="mt-px shrink-0" />+ <span>+ {imagesLabel(count)} attached. Images stay on the machine that recorded+ the session.+ </span>+ </div>+ );+}++export function PromptImages({+ sessionId,+ turns,+}: {+ sessionId: string;+ /** this task's image turns, from `promptImageTurns` over the full map */+ turns: PromptImageTurn[];+}) {+ const source = useSessionMapSource();+ const total = turns.reduce((s, t) => s + t.count, 0);+ const canServe = !!source.promptImages && !!source.promptImageUrl;+ const throughTurn = turns.reduce((m, t) => Math.max(m, t.turn), 0);+ const query = usePromptImages(sessionId, throughTurn, canServe && total > 0);+ const [failed, setFailed] = useState<ReadonlySet<string>>(new Set());+ const [openKey, setOpenKey] = useState<string | null>(null);++ // Join the map's turns with what the server listed; an image the server+ // did not list is unavailable, so a short answer pads rather than hides.+ const slots = useMemo<Slot[]>(() => {+ const byTurn = new Map(query.data?.turns.map((t) => [t.turn, t.images]));+ return turns.flatMap(({ turn, count }) =>+ Array.from({ length: count }, (_, i) => {+ const img = byTurn.get(turn)?.find((x) => x.i === i);+ return {+ key: `${turn}:${i}`,+ turn,+ i,+ pasteId: img?.pasteId ?? null,+ mediaType: img?.mediaType ?? '',+ available: !!img?.available,+ };+ })+ );+ }, [turns, query.data]);++ if (total === 0) return null;+ if (!canServe || query.isError) return <Unavailable count={total} />;+ if (query.isPending) {+ return (+ <div+ className="grid grid-cols-2 gap-2"+ role="status"+ aria-label="Loading images"+ >+ {Array.from({ length: total }, (_, i) => (+ <Skeleton key={i} className="aspect-[4/3] rounded-lg" />+ ))}+ </div>+ );+ }++ const urlOf = (s: Slot) => source.promptImageUrl!(sessionId, s.turn, s.i);+ const markFailed = (key: string) =>+ setFailed((prev) => new Set(prev).add(key));+ const openable = slots.filter((s) => s.available && !failed.has(s.key));+ const current = openable.findIndex((s) => s.key === openKey);+ const step = (delta: number) => {+ const next = openable[current + delta];+ if (next) setOpenKey(next.key);+ };+ const position = (s: Slot) => slots.indexOf(s) + 1;++ return (+ <>+ <ul className="grid grid-cols-2 gap-2" aria-label="Pasted images">+ {slots.map((s) => (+ <li key={s.key}>+ {s.available && !failed.has(s.key) ? (+ <button+ type="button"+ aria-label={`Open image ${position(s)} of ${total}`}+ onClick={() => setOpenKey(s.key)}+ className={cn(+ TILE,+ 'block w-full cursor-pointer outline-none transition-colors hover:border-ds-border-subtler focus-visible:ring-2 focus-visible:ring-ds-border-focus'+ )}+ >+ <img+ src={urlOf(s)}+ alt=""+ loading="lazy"+ decoding="async"+ onError={() => markFailed(s.key)}+ className="size-full object-contain"+ />+ <span className="absolute bottom-1 left-1 rounded bg-ds-surface-white/80 px-1 ds-text-body-xs-medium text-ds-text-darker">+ {imageLabel(s.pasteId, position(s) - 1, s.mediaType)}+ </span>+ </button>+ ) : (+ <div+ className={cn(+ TILE,+ 'flex items-center justify-center gap-1 border-dashed text-ds-text-subtler'+ )}+ title="Images stay on the machine that recorded the session."+ >+ <ImageSquare size={14} aria-hidden />+ <span className="ds-text-body-xs-medium">Unavailable</span>+ </div>+ )}+ </li>+ ))}+ </ul>+ <Lightbox+ // a lightbox with no openable image has nothing to show+ slot={current >= 0 ? openable[current] : null}+ url={current >= 0 ? urlOf(openable[current]) : ''}+ position={current >= 0 ? position(openable[current]) : 0}+ total={total}+ hasPrev={current > 0}+ hasNext={current >= 0 && current < openable.length - 1}+ onStep={step}+ onClose={() => setOpenKey(null)}+ onError={markFailed}+ />+ </>+ );+}++function Lightbox({+ slot,+ url,+ position,+ total,+ hasPrev,+ hasNext,+ onStep,+ onClose,+ onError,+}: {+ slot: Slot | null;+ url: string;+ position: number;+ total: number;+ hasPrev: boolean;+ hasNext: boolean;+ onStep: (delta: number) => void;+ onClose: () => void;+ onError: (key: string) => void;+}) {+ // Natural size is only known once the bytes decode; keyed by slot so a+ // neighbour never shows the previous image's dimensions.+ const [size, setSize] = useState<{ key: string; w: number; h: number } | null>(+ null+ );+ const dims = slot && size?.key === slot.key ? ` · ${size.w}×${size.h}` : '';+ return (+ <Dialog open={!!slot} onOpenChange={(open) => !open && onClose()}>+ <DialogContent+ aria-describedby={undefined}+ className="w-[min(64rem,calc(100vw-2rem))] max-h-[calc(100vh-2rem)]"+ onKeyDown={(e) => {+ if (e.key === 'ArrowLeft') onStep(-1);+ else if (e.key === 'ArrowRight') onStep(1);+ else return;+ e.preventDefault();+ }}+ >+ {slot ? (+ <>+ <div className="flex items-center justify-between gap-2">+ <DialogTitle className="ds-text-body-sm-semibold text-ds-text-darker">+ Image {position} of {total} · {pasteTag(slot.pasteId, position - 1)}+ {dims}+ </DialogTitle>+ <DialogClose+ render={+ <button+ type="button"+ aria-label="Close"+ className={cn(+ buttonVariants({ variant: 'ghost', size: 'sm' }),+ 'cursor-pointer'+ )}+ >+ <X size={14} aria-hidden />+ </button>+ }+ />+ </div>+ <div className="flex items-center justify-center rounded-lg bg-ds-gray-subtlest">+ <img+ src={url}+ alt={`Pasted ${position} of ${total}`}+ decoding="async"+ onLoad={(e) =>+ setSize({+ key: slot.key,+ w: e.currentTarget.naturalWidth,+ h: e.currentTarget.naturalHeight,+ })+ }+ onError={() => onError(slot.key)}+ className="max-h-[80vh] max-w-full object-contain"+ />+ </div>+ <div className="flex justify-between gap-2">+ <button+ type="button"+ aria-label="Previous image"+ disabled={!hasPrev}+ onClick={() => onStep(-1)}+ className={cn(+ buttonVariants({ variant: 'outline', size: 'sm' }),+ 'cursor-pointer'+ )}+ >+ Previous+ </button>+ <button+ type="button"+ aria-label="Next image"+ disabled={!hasNext}+ onClick={() => onStep(1)}+ className={cn(+ buttonVariants({ variant: 'outline', size: 'sm' }),+ 'cursor-pointer'+ )}+ >+ Next+ </button>+ </div>+ </>+ ) : null}+ </DialogContent>+ </Dialog>+ );+}diff --git a/viewer/src/explorer/ReviewLoopBlock.tsx b/viewer/src/explorer/ReviewLoopBlock.tsxnew file mode 100644index 0000000..bff07bb--- /dev/null+++ b/viewer/src/explorer/ReviewLoopBlock.tsx@@ -0,0 +1,244 @@+import { ArrowRight } from '@phosphor-icons/react';+import { parseAsString, useQueryState } from 'nuqs';+import { Badge } from '@/components/ui/badge';+import { buttonVariants } from '@/components/ui/button';+import { LockedBlock } from '@/components/LockedBlock';+import { FixNowDialog } from './FixNowDialog';+import { SAMPLE_SESSION_ID, useSampleMode } from '@/app/sampleMode';+import { reviewLoopCopy, type LinkSource } from '@/core/entelligence';+import {+ SAMPLE_COMMENTS,+ type SampleComment as SampleCommentData,+} from './reviewSample';+import type { SessionMap } from '@/core/schema';+import { srcSeqOf } from '@/core/sessionMapModel';+import { cn } from '@/lib/utils';++/**+ * The review loop, in the outcomes panel: a review comment on a PR, the edit+ * that caused it, and the rule the repeats cluster into.+ *+ * It gates a capability the map cannot have rather than a feature that works+ * offline. Review comment text needs the host's API and an authenticated+ * account; attributing one to an edit needs the comment plus the session; the+ * cluster needs every other session too. None of that can be computed from a+ * local document, so nothing here is being withheld.+ */+export function ReviewLoopBlock({+ map,+ src = 'outcomes',+ path = null,+ onPath,+ onSeek,+}: {+ map: SessionMap;+ src?: LinkSource;+ /** the picked comment's causal path, lit on the map */+ path?: readonly number[] | null;+ onPath?: (seqs: readonly number[] | null) => void;+ /** move the playhead to the flagged edit when a comment is picked */+ onSeek?: (index: number) => void;+}) {+ const copy = reviewLoopCopy(map.prs);+ const [sample, setSample] = useQueryState('sample', parseAsString);+ const mode = useSampleMode();+ // Revealed only on the session the comments are about. `sample` survives+ // picking another session out of the sidebar, and the steps they cite+ // exist in that map too -- they would light the wrong nodes in it.+ const shown = sample !== null && map.session.id === SAMPLE_SESSION_ID;+ return (+ <LockedBlock+ title={copy.title}+ blurb={copy.blurb}+ ctaLabel="Connect your PRs"+ src={src}+ preview={+ <ReviewLoopSample+ path={path}+ onPath={onPath}+ onSeek={+ onSeek+ ? (seq) => {+ // `srcSeqOf`, not `e.seq`: under a task or model scope the+ // map is a renumbered copy, so the cited number read+ // against `seq` parks the playhead on an unrelated event.+ const i = map.events.findIndex((e) => srcSeqOf(e) === seq);+ if (i >= 0) onSeek(i);+ }+ : undefined+ }+ />+ }+ shown={shown}+ // Showing the sample swaps the whole view onto the bundled session+ // that opened a PR, so the map, the timeline and the panels are all+ // the same session the comment below belongs to. Hiding it only+ // re-blurs: leaving the sample is a separate, named action, because+ // doing it silently would throw away a session the user had open.+ onToggle={() => (shown ? void setSample(null) : mode.show())}+ exit={+ mode.active && mode.canExit ? (+ <button+ type="button"+ onClick={mode.exit}+ className={cn(buttonVariants({ variant: 'link', size: 'sm' }))}+ >+ Back to your sessions+ </button>+ ) : null+ }+ />+ );+}++/**+ * Invented, and labelled as such by `LockedBlock` -- but every step number,+ * file and task below is a real one from the demo session the "See sample"+ * button switches to, so a reader can scrub the timeline and find each one.+ * Shaped like the real panel: comment, cause, causal path, cluster.+ */+function ReviewLoopSample({+ path,+ onPath,+ onSeek,+}: {+ path?: readonly number[] | null;+ onPath?: (seqs: readonly number[] | null) => void;+ onSeek?: (seq: number) => void;+}) {+ const sameAs = (c: SampleCommentData) =>+ !!path && path.length === c.path.length && path.every((s, i) => s === c.path[i].seq);+ return (+ <div className="flex flex-col gap-3">+ <p className="ds-text-body-xs-semibold text-ds-text-subtle">+ {SAMPLE_COMMENTS.length} review comments on acme/api #142+ {onPath ? ' \u00b7 pick one to light its path on the map' : null}+ </p>+ {SAMPLE_COMMENTS.map((c) => (+ <SampleComment+ key={c.editSeq}+ c={c}+ picked={sameAs(c)}+ onPick={+ onPath+ ? () => {+ const clearing = sameAs(c);+ onPath(clearing ? null : c.path.map((s) => s.seq));+ // Park the playhead on the flagged edit, so the timeline+ // and the Event panel agree with the lit map.+ if (!clearing) onSeek?.(c.editSeq);+ }+ : undefined+ }+ />+ ))}+ </div>+ );+}++/**+ * One comment. Picking it lights its causal path on the map and dims the+ * rest -- the same focus mechanism the dock's category chips use, so the+ * path is drawn by the map rather than painted over it. Picking it again+ * clears the focus.+ */+function SampleComment({+ c,+ picked,+ onPick,+}: {+ c: SampleCommentData;+ picked: boolean;+ onPick?: () => void;+}) {+ const body = (+ <>+ <div className="flex items-baseline justify-between gap-2">+ <span className="truncate font-mono ds-text-body-xs-medium text-ds-danger-default">+ {c.file} {c.line}+ </span>+ <span className="shrink-0 ds-text-body-xs-medium text-ds-text-subtle">+ @{c.author}+ </span>+ </div>+ <p className="ds-text-body-xs-medium text-ds-text-default">“{c.text}”</p>+ <div className="flex flex-wrap items-center gap-1.5">+ <Badge variant="error">{c.flagged}</Badge>+ <span className="font-mono ds-text-body-xs-medium text-ds-text-subtle">+ edit #{c.editSeq}+ </span>+ </div>+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Task: {c.task}+ </p>+ <div className="flex flex-col gap-0.5">+ <span className="ds-text-body-xs-semibold text-ds-text-subtle">+ Cause · {c.cause}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-default">+ {c.why}+ </span>+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="ds-text-body-xs-semibold text-ds-text-subtle">+ Causal path+ </span>+ {c.path.map((s) => (+ <div key={s.seq} className="flex items-baseline gap-2">+ <span className="w-8 shrink-0 font-mono ds-text-body-xs-medium text-ds-text-subtle">+ #{s.seq}+ </span>+ <span className="w-8 shrink-0 ds-text-body-xs-medium text-ds-text-subtle">+ {s.who}+ </span>+ <span className="min-w-0 flex-1 font-mono ds-text-body-xs-medium text-ds-text-default">+ {s.what}+ </span>+ </div>+ ))}+ </div>+ {c.ghost ? (+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Ghost: {c.ghost}+ </p>+ ) : null}+ <div className="flex items-center gap-1 ds-text-body-xs-medium text-ds-brand-default">+ <span>+ Clustered into {c.learning} with {c.alsoIn}{' '}+ {c.alsoIn === 1 ? 'other session' : 'other sessions'}+ </span>+ <ArrowRight size={12} aria-hidden className="shrink-0" />+ </div>+ </>+ );+ // The card is a div, not a button: "Fix now" lives inside it, and a+ // button inside a button is invalid and unreachable by keyboard. The+ // comment itself is the pick target; the footer is its own row.+ return (+ <div+ className={cn(+ 'flex w-full flex-col gap-1.5 rounded-md border p-2 text-left transition-colors',+ picked+ ? 'border-ds-brand-subtler bg-ds-brand-lightest'+ : 'border-ds-border-subtlest'+ )}+ >+ {onPick ? (+ <button+ type="button"+ aria-pressed={picked}+ aria-label={`Light the path to ${c.file} ${c.line} on the map`}+ onClick={onPick}+ className="-m-1 flex cursor-pointer flex-col gap-1.5 rounded p-1 text-left transition-colors hover:bg-ds-gray-subtlest focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ds-brand-subtler"+ >+ {body}+ </button>+ ) : (+ <div className="flex flex-col gap-1.5">{body}</div>+ )}+ <div className="flex items-center gap-2 border-t border-ds-border-subtlest pt-1.5">+ <FixNowDialog c={c} />+ </div>+ </div>+ );+}diff --git a/viewer/src/explorer/SessionExplorer.tsx b/viewer/src/explorer/SessionExplorer.tsxnew file mode 100644index 0000000..163ebef--- /dev/null+++ b/viewer/src/explorer/SessionExplorer.tsx@@ -0,0 +1,768 @@+import { srcSeqOf } from '@/core/sessionMapModel';+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ useSyncExternalStore,+ type ReactNode,+} from 'react';+import { CalendarBlankIcon, MapTrifold } from '@phosphor-icons/react';+import {+ parseAsInteger,+ parseAsString,+ parseAsStringEnum,+ useQueryState,+ useQueryStates,+} from 'nuqs';+import type {+ SessionExplorerSession,+ SessionMap,+} from '@/core/schema';+import { SessionExplorerError } from '@/data/errors';+import { dedupeSessions } from '@/data/parse';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { EmptyState } from '@/components/EmptyState';+import { ErrorBoundary } from '@/components/ErrorBoundary';+import { cn } from '@/lib/utils';+import { useDebounce } from '@/hooks/useDebounce';+import {+ useSessionExplorerMap,+ useSessionExplorerSessions,+} from '@/data/hooks';+import { WINDOW_OPTIONS, type WindowKey } from '@/core/windowOptions';+import { ExplorerToolbar } from './ExplorerToolbar';+import { ExplorerSidebar, MapPane, type SidebarCtl } from './MapPlayerParts';+import { SessionHeader } from './SessionHeader';+import { SessionList } from './SessionList';+import {+ InlineError,+ MapSkeleton,+ SessionExplorerSkeleton,+ SidePanelsSkeleton,+} from './SessionExplorerStates';+import {+ SessionListHeader,+ SidebarRail,+ SubagentInspector,+} from './SessionSidebar';+import { InsightsPanel, SidePanels } from './SidePanels';+import { TimelineDock } from './TimelineDock';+import {+ SIDEBAR_TABS,+ agentOptions,+ agentOptionsInScope,+ emptyScopeDescription,+ getSidebarCollapsed,+ getSidebarCollapsedServer,+ hasScopeFilter,+ setSidebarCollapsed,+ subscribeSidebarCollapsed,+ type SidebarTab,+} from '@/core/sessionLayout';+import type { TreeNode } from '@/core/sessionMapModel';+import {+ CLEAR_SCOPE_PARAMS,+ SCOPE_PARAMS,+ deriveScopeDoc,+ hasReplayEvents,+ modelUsage,+ scopedModelUsage,+ taskNoun,+} from '@/core/sessionScope';+import { sessionWindowRange } from '@/core/sessionWindow';+import { useEventCategories } from './useEventCategories';+import { useExplorerScope, type ExplorerScope } from './useExplorerScope';+import { useMapModel, usePlaybackWindow } from './usePlaybackWindow';++interface Props {+ /** the window selector's value; the list follows it */+ windowKey: WindowKey;+ /** the window select lives in the sessions sidebar */+ onWindowChange?: (key: WindowKey) => void;+ /** optional control under the "No session maps yet" empty state (e.g. an+ * "Open a map file" button) */+ emptyAction?: ReactNode;+}++/** A cache-busting key that changes at EITHER the viewer's local midnight+ * or UTC midnight, whichever comes first (not a real ISO date). Two+ * different fields of `sessionWindowRange`'s result roll over on two+ * different clocks: `daysThisMonth` derives MTD's `from` from local+ * `getDate()`, but `to` (every window) is `toISOString().slice(0, 10)`,+ * a UTC date. A key on only one clock stays stale across the other+ * boundary for up to the viewer's UTC offset. */+const dateBoundaryKey = (d: Date) =>+ `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${d.toISOString().slice(0, 10)}`;++/** The list's date range for `windowKey`, kept fresh across midnight. */+function useWindowRange(windowKey: WindowKey) {+ // `sessionWindowRange` is keyed off `new Date()` at call time, but a memo+ // keyed only on `windowKey` never re-runs that call once the tab has been+ // open a while - the range (mtd's start, and every window's `to`) goes+ // stale after a real calendar day rolls over while the page stays mounted+ //. A cheap poll refreshes it within a minute of that,+ // keyed by both clocks it can roll over on (see `dateBoundaryKey`).+ const [today, setToday] = useState(() => dateBoundaryKey(new Date()));+ useEffect(() => {+ const id = setInterval(() => {+ const next = dateBoundaryKey(new Date());+ setToday((prev) => (prev === next ? prev : next));+ }, 60_000);+ return () => clearInterval(id);+ }, []);+ return useMemo(+ // `today` is not read in the body; it exists purely to invalidate this+ // memo once the poll above notices the calendar date has moved on.+ () => sessionWindowRange(windowKey, new Date()),+ [windowKey, today]+ );+}++/** The sessions in the window (search-filtered), the effective selection,+ * and its map. */+function useExplorerSessions(windowKey: WindowKey) {+ const [search, setSearch] = useQueryState(+ 'sq',+ parseAsString.withDefault('')+ );+ const [selected, setSelected] = useQueryState('session', parseAsString);+ const debouncedSearch = useDebounce(search.trim(), 300);+ const range = useWindowRange(windowKey);+ const list = useSessionExplorerSessions(debouncedSearch, range);+ const sessions = useMemo<SessionExplorerSession[]>(+ () =>+ dedupeSessions(list.data?.pages.flatMap((pg) => pg.sessions) ?? []).filter(+ (s) => s.calls > 0+ ),+ [list.data]+ );+ const listIds = useMemo(() => sessions.map((s) => s.sessionId), [sessions]);+ const selectedId = sessions.some((s) => s.sessionId === selected)+ ? selected+ : (sessions[0]?.sessionId ?? null);+ const selectedRow = sessions.find((s) => s.sessionId === selectedId) ?? null;+ const mapQuery = useSessionExplorerMap(selectedId, listIds);+ return {+ search,+ setSearch,+ selected,+ setSelected,+ debouncedSearch,+ list,+ sessions,+ selectedId,+ selectedRow,+ mapQuery,+ };+}++type MapQuery = ReturnType<typeof useSessionExplorerMap>;++function WindowSelect({+ windowKey,+ onChange,+}: {+ windowKey: WindowKey;+ onChange: (key: WindowKey) => void;+}) {+ return (+ <Select+ value={windowKey}+ // label lookup for SelectValue (otherwise it renders the raw key)+ items={WINDOW_OPTIONS.map((o) => ({ value: o.key, label: o.label }))}+ onValueChange={(v: string | null) => {+ if (v) onChange(v as WindowKey);+ }}+ >+ <SelectTrigger+ aria-label="Select time window"+ className="h-8 w-full gap-2"+ >+ <CalendarBlankIcon+ size={14}+ className="shrink-0 text-ds-text-subtle"+ weight="duotone"+ />+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="start">+ {WINDOW_OPTIONS.map((opt) => (+ <SelectItem key={opt.key} value={opt.key}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++/**+ * The Session Explorer: sessions sidebar + the selected session's replay+ * (header, filter toolbar, map + details, timeline dock). It fills the+ * height it is given (a flex parent): the map row takes what the docked+ * timeline leaves, and only the inner regions scroll.+ */+export function SessionExplorer({+ windowKey,+ onWindowChange,+ emptyAction,+}: Props) {+ const data = useExplorerSessions(windowKey);+ const { list, sessions, selectedId } = data;+ const [, setScopeParams] = useQueryStates(SCOPE_PARAMS);+ // One sidebar: the list until a session is picked (or one is linked), then+ // only that session; "All sessions" flips back without touching the URL.+ const [sidebarMode, setSidebarMode] = useState<'list' | 'session'>(() =>+ data.selected ? 'session' : 'list'+ );+ // An external store (localStorage-backed, every access guarded) so the+ // first client render already has the persisted value; SSR renders+ // expanded via the server snapshot.+ const collapsed = useSyncExternalStore(+ subscribeSidebarCollapsed,+ getSidebarCollapsed,+ getSidebarCollapsedServer+ );+ const setCollapsed = setSidebarCollapsed;++ if (list.isLoading && !list.data)+ return (+ <div className="flex flex-col gap-3">+ <SessionExplorerSkeleton />+ </div>+ );+ if (list.isError && !list.data) {+ console.error('session explorer: session list failed', list.error);+ return (+ <div className="flex flex-col gap-3">+ <InlineError+ title="Could not load sessions"+ description="The list of recorded sessions did not load. Try again in a moment."+ onRetry={() => void list.refetch()}+ />+ </div>+ );+ }+ const windowSelect = onWindowChange ? (+ <WindowSelect windowKey={windowKey} onChange={onWindowChange} />+ ) : null;++ if (!sessions.length && !data.debouncedSearch && !list.hasNextPage) {+ // The window select lives in the sidebar, which this state replaces, so+ // it is rendered here too -- otherwise "try a longer window" would have+ // no control to act on.+ return (+ <div className="flex flex-col gap-3">+ {windowSelect ? <div className="w-48">{windowSelect}</div> : null}+ <EmptyState+ icon={<MapTrifold size={24} weight="duotone" />}+ title="No session maps yet"+ description="Session maps appear here once a coding-agent session has been indexed. Try a longer window if you expected one."+ action={emptyAction}+ />+ </div>+ );+ }++ const listNode = (+ <SessionList+ sessions={sessions}+ selectedId={selectedId}+ // Picking a session shows its map and Details; the list stays, so+ // the next one is one click away rather than one back-out away.+ onSelect={(id) => {+ if (id !== selectedId) void setScopeParams(CLEAR_SCOPE_PARAMS);+ void data.setSelected(id);+ }}+ // Open descends into it, on every task: any task/model narrowing from+ // the previous session would otherwise follow you in.+ onOpen={(id) => {+ void setScopeParams(CLEAR_SCOPE_PARAMS);+ void data.setSelected(id);+ setSidebarMode('session');+ }}+ search={data.search}+ onSearch={(v) => void data.setSearch(v || null)}+ hasMore={!!list.hasNextPage}+ loadingMore={list.isFetchingNextPage}+ onLoadMore={() => void list.fetchNextPage()}+ unavailable={data.mapQuery.unavailable}+ header={+ <SessionListHeader+ count={sessions.length}+ onCollapse={() => setCollapsed(true)}+ />+ }+ toolbar={windowSelect}+ />+ );+ const sidebar: SidebarCtl = {+ mode: sidebarMode,+ collapsed,+ setCollapsed,+ showList: () => setSidebarMode('list'),+ showSession: () => setSidebarMode('session'),+ list: listNode,+ };++ return (+ <div+ className={cn(+ 'grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)] gap-4',+ collapsed+ ? 'grid-cols-[40px_minmax(0,1fr)]'+ : 'grid-cols-[300px_minmax(0,1fr)]'+ )}+ >+ <ExplorerBody+ selectedId={selectedId}+ mapQuery={data.mapQuery}+ row={data.selectedRow}+ sidebar={sidebar}+ />+ </div>+ );+}++/** The sidebar column's slot: the explorer's full height, scrolling inside. */+function SidebarSlot({ children }: { children: ReactNode }) {+ return (+ <aside+ aria-label="Session explorer sidebar"+ className="h-full min-h-0 min-w-0"+ >+ {children}+ </aside>+ );+}++/** Everything right of (and including) the sidebar, by map state. */+function ExplorerBody({+ selectedId,+ mapQuery,+ row,+ sidebar,+}: {+ selectedId: string | null;+ mapQuery: MapQuery;+ row: SessionExplorerSession | null;+ sidebar: SidebarCtl;+}) {+ // Without a loaded map there is no session to show: the list (or rail).+ const listSidebar = (+ <SidebarSlot>+ {sidebar.collapsed ? (+ <SidebarRail+ label="Sessions"+ onExpand={() => sidebar.setCollapsed(false)}+ />+ ) : (+ sidebar.list+ )}+ </SidebarSlot>+ );+ // Until a map loads (and on errors) the right column is one stacked cell.+ const column = (content: ReactNode) => (+ <div className="flex min-h-0 min-w-0 flex-col gap-3">{content}</div>+ );+ if (!selectedId) {+ return (+ <>+ {listSidebar}+ {column(+ <EmptyState+ title="Pick a session"+ description="Choose a session on the left to replay its map."+ />+ )}+ </>+ );+ }+ if (mapQuery.isError) {+ console.error('session explorer: map failed', mapQuery.error);+ const copy = mapErrorCopy(mapQuery.error);+ return (+ <>+ {listSidebar}+ {column(+ <InlineError+ title={copy.title}+ description={copy.description}+ onRetry={copy.retry ? () => void mapQuery.retry() : undefined}+ />+ )}+ </>+ );+ }+ if (mapQuery.isLoading || !mapQuery.data) {+ return (+ <>+ {listSidebar}+ {column(+ <div className="grid min-h-0 min-w-0 grid-cols-[minmax(0,1fr)_300px] items-start gap-4 overflow-hidden">+ <MapSkeleton />+ <SidePanelsSkeleton />+ </div>+ )}+ </>+ );+ }+ return (+ <ErrorBoundary+ key={selectedId}+ fallback={+ <>+ {listSidebar}+ {column(+ <InlineError+ title="This session could not be displayed."+ description="Pick another session from the list."+ />+ )}+ </>+ }+ >+ <MapPlayer+ sessionId={selectedId}+ map={mapQuery.data}+ row={row}+ sidebar={sidebar}+ />+ </ErrorBoundary>+ );+}++function mapErrorCopy(error: unknown): {+ title: string;+ description: string;+ retry: boolean;+} {+ const code = error instanceof SessionExplorerError ? error.code : '';+ if (code === 'not_found') {+ return {+ title: 'Map not available',+ description:+ 'This session has no stored map. Pick another session from the list.',+ retry: false,+ };+ }+ if (code === 'unsupported_schema') {+ return {+ title: 'This session map needs a newer page',+ description:+ 'It was recorded in a format this page cannot draw yet. Refresh the page to pick up the latest version.',+ retry: false,+ };+ }+ return {+ title: 'Could not load this session map',+ description: 'Something went wrong fetching the map. Try again.',+ retry: true,+ };+}++/**+ * Binds the URL scope + agent lens to this session (`useExplorerScope`) and+ * remounts `MapPlayerBody` on any change (`key`), since `useReducer`'s lazy+ * playback init only runs once per mount and must re-run against the new+ * event count.+ */+function MapPlayer({+ sessionId,+ map,+ row,+ sidebar,+}: {+ sessionId: string;+ map: SessionMap;+ row: SessionExplorerSession | null;+ sidebar: SidebarCtl;+}) {+ const x = useExplorerScope(sessionId, map);+ return (+ <MapPlayerBody+ key={x.key}+ x={x}+ row={row}+ sidebar={sidebar}+ />+ );+}++/** `?at=<seq>`: a deep link to one event (e.g. from an error row or a badge).+ * Seeks the replay to the event carrying that `seq` (or that index when no+ * event carries it), then drops the param so a later seek is not undone. */+function useSeekParam(map: SessionMap, seek: (index: number) => void) {+ const [at, setAt] = useQueryState('at', parseAsInteger);+ useEffect(() => {+ if (at == null) return;+ const n = map.events.length;+ if (n) {+ // `srcSeqOf`, not `e.seq`: a task or model scope renumbers `seq`, and a+ // link (or a task's error tag) names the whole-session event.+ const bySeq = map.events.findIndex((e) => srcSeqOf(e) === at);+ seek(bySeq >= 0 ? bySeq : Math.max(0, Math.min(n - 1, at)));+ }+ void setAt(null);+ }, [at, map.events, seek, setAt]);+}++/** URL-backed sidebar tab. */+function useSideTab() {+ const [sideTab, setSideTab] = useQueryState(+ 'stab',+ parseAsStringEnum<SidebarTab>([...SIDEBAR_TABS])+ );+ return { sideTab, setSideTab };+}++/** Task / model toggles, and what a click on a map node does. */+function useScopeActions(x: ExplorerScope) {+ const { setScope, lens, fullMap, setLens } = x;+ const selectTask = useCallback(+ (n: number) =>+ setScope((s0) => ({ ...s0, task: s0.task === n ? null : n })),+ [setScope]+ );+ const selectModel = useCallback(+ (m: string) =>+ setScope((s0) => ({ ...s0, model: s0.model === m ? null : m })),+ [setScope]+ );+ const onNodeAction = useCallback(+ (node: TreeNode): boolean => {+ if (node.type === 'model') {+ selectModel(node.name);+ return true;+ }+ if (node.type !== 'agent' || lens !== 'main') return false;+ const id = node.id.slice('agent:'.length);+ if (!fullMap.agents.some((a) => a.id === id)) return false;+ setLens(id);+ return true;+ },+ [selectModel, lens, fullMap.agents, setLens]+ );+ return { selectTask, selectModel, onNodeAction };+}++const REPLAY_LABEL =+ 'Session replay. Space plays or pauses, arrow keys step, Shift steps 10, E jumps to the next edit, X to the next error, D to the next delay, O to the next output, R to the next retry.';++/**+ * The fit-viewport replay: sidebar | (header with the filters on its line,+ * map + details row that takes the remaining height, timeline pinned at the+ * bottom).+ */+function MapPlayerBody({+ x,+ row,+ sidebar,+}: {+ x: ExplorerScope;+ row: SessionExplorerSession | null;+ sidebar: SidebarCtl;+}) {+ const { map, scope, sub } = x;+ const url = useSideTab();+ const cats = useEventCategories();+ const { selectTask, selectModel, onNodeAction } = useScopeActions(x);+ const scopedModels = useMemo(() => modelUsage(map), [map]);+ // Both pickers count inside the other filters: the Agent rows inside the+ // prompt/model scope, the Model rows inside the prompt.+ const agents = useMemo(+ () =>+ agentOptionsInScope(agentOptions(x.fullMap, x.ordinals), x.scopedMap),+ [x.fullMap, x.ordinals, x.scopedMap]+ );+ const pickerModels = useMemo(+ () =>+ scopedModelUsage(+ x.models,+ deriveScopeDoc(x.fullMap, { task: scope.task, model: null })+ ),+ [x.models, x.fullMap, scope.task]+ );+ const model = useMapModel(map);+ const playback = usePlaybackWindow(map);+ const { pb } = playback;+ useSeekParam(map, playback.seek);+ // A task row's error tag, or an Errors row the scope hides (`task` null when+ // that error has none: the task filter is cleared). Scope, tab and `at` change in one URL update, so the+ // replay re-scoped to the task is the one that seeks: `at` is a `seq`, which+ // survives the re-scope where an index would not. The model filter and the+ // agent lens are cleared so they can't hide the error being jumped to (the+ // Errors tab lists every agent's errors).+ const [, setAt] = useQueryState('at', parseAsInteger);+ const jumpToTaskErrors = useCallback(+ (task: number | null, seq: number) => {+ x.setScope((s0) => ({ ...s0, task, model: null }), { clearLens: true });+ void url.setSideTab('errors');+ void setAt(seq);+ },+ [x, url, setAt]+ );+ const subInfo = sub ? (x.subs.find((s) => s.id === sub) ?? null) : null;+ const hasEvents = hasReplayEvents(map);+ // The review comment whose causal path the map is lighting, as the event+ // `seq`s on that path. Owned here because the comment is clicked in the+ // right-hand column and drawn on the map beside it.+ const [reviewPath, setReviewPath] = useState<readonly number[] | null>(null);+ // How far the dock's optional lanes (Subagents / Context) grow it past+ // its budget (TimelineDock's onOverflow). The column grows by that much+ // below the fold, so the map's flex row keeps its size and the page+ // scrolls instead of shrinking it. Null until the dock first measures.+ const [dockExtra, setDockExtra] = useState<number | null>(null);+ const columnRef = useRef<HTMLDivElement>(null);+ const prevExtra = useRef<number | null>(null);+ useEffect(() => {+ if (dockExtra == null) return;+ const prev = prevExtra.current;+ prevExtra.current = dockExtra;+ // A lane was just turned on or expanded: scroll it into view. Not on+ // the first measurement, so opening a session never jumps the page.+ if (prev != null && dockExtra > prev)+ columnRef.current?.scrollIntoView({ block: 'end', behavior: 'smooth' });+ }, [dockExtra]);++ const insights = hasEvents ? (+ <InsightsPanel+ map={map}+ p={pb.p}+ ordinals={model.ordinals}+ review={model.review}+ signals={model.signals}+ onJumpSource={playback.jumpSource}+ models={scopedModels}+ model={scope.model}+ onSelectModel={selectModel}+ />+ ) : (+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Nothing in this scope.+ </p>+ );++ return (+ <>+ <SidebarSlot>+ <ExplorerSidebar+ x={x}+ model={model}+ row={row}+ sidebar={sidebar}+ subInfo={subInfo}+ tabParam={url.sideTab}+ onTab={(t) => void url.setSideTab(t)}+ insights={insights}+ onFocusCategory={(c) => cats.setSelected(new Set([c]))}+ p={pb.p}+ onSeek={playback.seek}+ onJumpToTaskErrors={jumpToTaskErrors}+ />+ </SidebarSlot>+ <div+ ref={columnRef}+ className="flex min-h-0 min-w-0 flex-col gap-3 outline-none"+ style={+ dockExtra ? { height: `calc(100% + ${dockExtra}px)` } : undefined+ }+ onKeyDown={playback.onKeyDown}+ role="region"+ tabIndex={-1}+ aria-label={REPLAY_LABEL}+ >+ <SessionHeader+ map={map}+ row={row}+ lensLabel={x.lensLabel}+ onExitLens={() => x.setLens('main')}+ filters={+ <ExplorerToolbar+ tasks={x.tasks}+ task={scope.task}+ onTask={(task) => x.setScope((s0) => ({ ...s0, task }))}+ agents={agents}+ lens={x.lens}+ lensLabel={x.lensLabel}+ onLens={x.setLens}+ models={pickerModels}+ model={scope.model}+ onModel={(m) => x.setScope((s0) => ({ ...s0, model: m }))}+ filtered={hasScopeFilter(scope, sub)}+ onClear={x.clearAll}+ />+ }+ />+ {/* The middle row takes whatever height the docked timeline+ leaves; the map scales into it and the details column scrolls+ inside itself. */}+ <div className="grid min-h-0 min-w-0 flex-1 grid-cols-[minmax(0,1fr)_300px] grid-rows-[minmax(0,1fr)] gap-4">+ <MapPane+ map={map}+ model={model}+ p={pb.p}+ onSeek={playback.seek}+ onNodeAction={onNodeAction}+ filtered={hasScopeFilter(scope, sub)}+ filteredCopy={emptyScopeDescription(scope, sub, taskNoun(x.tasks))}+ playing={pb.playing}+ selected={cats.selected}+ path={reviewPath}+ />+ {hasEvents ? (+ <SidePanels+ map={map}+ fullMap={x.fullMap}+ p={pb.p}+ ordinals={model.ordinals}+ cumCost={model.cumCost}+ onSeek={playback.seek}+ tasks={x.tasks}+ sessionStart={x.fullMap.session.startedAt}+ task={scope.task}+ onSelectTask={selectTask}+ scoped={scope.model != null}+ selected={cats.selected}+ picks={cats.picks}+ reviewPath={reviewPath}+ onReviewPath={setReviewPath}+ inspector={+ subInfo ? (+ <SubagentInspector+ sub={subInfo}+ tasks={x.tasks}+ startedAt={x.fullMap.session.startedAt}+ />+ ) : undefined+ }+ />+ ) : (+ <div />+ )}+ </div>+ {hasEvents ? (+ <TimelineDock+ x={x}+ playback={playback}+ model={model}+ cats={cats}+ onSelectTask={selectTask}+ subInfo={subInfo}+ collapsed={sidebar.collapsed}+ onOverflow={setDockExtra}+ columnExtra={dockExtra}+ />+ ) : null}+ </div>+ </>+ );+}diff --git a/viewer/src/explorer/SessionExplorerStates.tsx b/viewer/src/explorer/SessionExplorerStates.tsxnew file mode 100644index 0000000..f576cdc--- /dev/null+++ b/viewer/src/explorer/SessionExplorerStates.tsx@@ -0,0 +1,110 @@+import { ArrowClockwise, WarningCircle } from '@phosphor-icons/react';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';++const CARD = 'rounded-xl border border-ds-border-subtlest bg-ds-surface-white';+const FILL = 'bg-ds-gray-subtlest';++/** Main column placeholder: header, map card, timeline card. */+export function MapSkeleton() {+ return (+ <div className="flex min-w-0 flex-col gap-4" aria-hidden>+ <div className="flex flex-col gap-2">+ <Skeleton className={`h-5 w-2/3 ${FILL}`} />+ <Skeleton className={`h-3.5 w-1/2 ${FILL}`} />+ </div>+ <div className={`${CARD} flex items-center justify-center p-4`}>+ <Skeleton className={`size-[440px] rounded-full ${FILL}`} />+ </div>+ <div className={`${CARD} flex flex-col gap-2 p-4`}>+ <Skeleton className={`h-14 w-full ${FILL}`} />+ <Skeleton className={`h-9 w-full ${FILL}`} />+ <Skeleton className={`h-7 w-full ${FILL}`} />+ <Skeleton className={`h-8 w-1/2 ${FILL}`} />+ </div>+ </div>+ );+}++export function SidePanelsSkeleton() {+ return (+ <div className="flex flex-col gap-3" aria-hidden>+ {[88, 120, 260, 96, 150].map((h) => (+ <div key={h} className={`${CARD} p-3`}>+ <Skeleton className={`mb-2 h-3.5 w-1/3 ${FILL}`} />+ <Skeleton className={`w-full ${FILL}`} style={{ height: h - 40 }} />+ </div>+ ))}+ </div>+ );+}++function ListSkeleton() {+ return (+ <div className={`${CARD} flex flex-col gap-2 p-3`} aria-hidden>+ <Skeleton className={`h-8 w-full ${FILL}`} />+ <Skeleton className={`h-3 w-1/2 ${FILL}`} />+ {Array.from({ length: 6 }, (_, i) => (+ <div key={i} className="flex flex-col gap-1.5 py-1.5">+ <Skeleton className={`h-4 w-5/6 ${FILL}`} />+ <Skeleton className={`h-3 w-2/3 ${FILL}`} />+ <Skeleton className={`h-4 w-1/2 ${FILL}`} />+ </div>+ ))}+ </div>+ );+}++/** Whole-explorer placeholder shaped like list | main | side. */+export function SessionExplorerSkeleton() {+ return (+ <div+ className="grid grid-cols-[280px_minmax(0,1fr)_320px] gap-4"+ role="status"+ aria-label="Loading Session Explorer"+ >+ <ListSkeleton />+ <MapSkeleton />+ <SidePanelsSkeleton />+ </div>+ );+}++export function InlineError({+ title,+ description,+ onRetry,+}: {+ title: string;+ description: string;+ onRetry?: () => void;+}) {+ return (+ <div+ role="alert"+ className={`${CARD} flex min-h-[220px] flex-col items-center justify-center gap-3 p-6 text-center`}+ >+ <div className="flex size-10 items-center justify-center rounded-lg bg-ds-danger-subtlest">+ <WarningCircle+ size={22}+ weight="duotone"+ className="text-ds-danger-default"+ />+ </div>+ <div className="flex max-w-[360px] flex-col gap-1">+ <span className="ds-text-body-xs-semibold text-ds-text-darker">+ {title}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {description}+ </span>+ </div>+ {onRetry ? (+ <Button variant="outline" size="sm" onClick={onRetry}>+ <ArrowClockwise size={14} />+ Try again+ </Button>+ ) : null}+ </div>+ );+}diff --git a/viewer/src/explorer/SessionHeader.tsx b/viewer/src/explorer/SessionHeader.tsxnew file mode 100644index 0000000..b033b93--- /dev/null+++ b/viewer/src/explorer/SessionHeader.tsx@@ -0,0 +1,188 @@+import type { ReactNode } from 'react';+import {+ ArrowSquareOut,+ CaretDown,+ GitPullRequest,+} from '@phosphor-icons/react';+import type {+ SessionExplorerSession,+ SessionMap,+} from '@/core/schema';+import { GitHubMark } from '@/assets/GitHubMark';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover';+import { agentToolLabel, sessionTitle } from './SessionList';+import { prCountLabel, prMenuItems } from '@/core/sessionLayout';+import { connectUrl } from '@/core/entelligence';+import { clockAt, dayLabel, outcomeMeta } from '@/core/sessionMapModel';++interface Props {+ /** the replayed (scoped + lensed) map */+ map: SessionMap;+ row: SessionExplorerSession | null;+ /** the open subagent's label (agent lens), or null on the main session */+ lensLabel: string | null;+ onExitLens: () => void;+ /** the Task / Agent / Model filters, on the same line at the right */+ filters?: ReactNode;+}++/**+ * The compact session header (fit-viewport layout): the title, tool, outcome+ * pill and PR menu, with the Task / Agent / Model filters at the right of+ * the same line (the separate toolbar row is gone, so the map gets its+ * height); the session id and start time live in the title's tooltip. Cost/tokens/duration and coverage+ * already live in Details (`SessionSummary`/`TaskDetail`, below Outcome);+ * models, errors/retries/delays/compactions and coverage already live in+ * the sidebar's Insights tab -- keeping them here too was pure duplication+ * that cost the map its vertical space, so this header carries only what+ * isn't shown anywhere else.+ */+export function SessionHeader(props: Props) {+ const { map, row, lensLabel } = props;+ const s = map.session;+ const title =+ lensLabel ??+ (row ? sessionTitle(row) : `${agentToolLabel(s.agentTool)} session`);+ const stamp = `${(s.id.split(':').pop() ?? s.id).slice(0, 8)} · ${dayLabel(s.startedAt)} ${clockAt(s.startedAt, 0).slice(0, 5)} UTC`;+ return (+ <header className="flex min-w-0 shrink-0 flex-wrap items-center gap-x-3 gap-y-1">+ <div className="flex min-w-[240px] flex-1 items-center gap-2">+ {lensLabel ? <LensCrumb onExit={props.onExitLens} /> : null}+ <h2+ className="min-w-0 truncate ds-text-body-sm-semibold text-ds-text-darker"+ title={`${title}\n${stamp}`}+ >+ {title}+ </h2>+ <Badge variant="secondary" className="shrink-0">+ {agentToolLabel(s.agentTool)}+ </Badge>+ {s.outcome ? <OutcomePill outcome={s.outcome} /> : null}+ <PrMenu prs={map.prs} />+ </div>+ {props.filters}+ {/* The id / start time is also in the title's tooltip; shown inline+ only where the row has room for it next to the filters. */}+ <span className="hidden shrink-0 font-mono ds-text-body-xs-medium text-ds-text-subtle 2xl:inline">+ {stamp}+ </span>+ </header>+ );+}++function LensCrumb({ onExit }: { onExit: () => void }) {+ return (+ <nav+ aria-label="Breadcrumb"+ className="flex shrink-0 items-center gap-1.5 ds-text-body-xs-medium text-ds-text-subtle"+ >+ <Button variant="outline" size="sm" onClick={onExit} className="h-6 px-2">+ ← Session+ </Button>+ <span aria-hidden>›</span>+ </nav>+ );+}++function OutcomePill({ outcome }: { outcome: string }) {+ const meta = outcomeMeta(outcome);+ if (meta.variant === 'success') {+ return (+ <Badge variant="success">{meta.label}</Badge>+ );+ }+ return <Badge variant={meta.variant}>{meta.label}</Badge>;+}++/** One "N PRs" button; the PRs themselves are listed in its popover. */+function PrMenu({ prs }: { prs: SessionMap['prs'] }) {+ const items = prMenuItems(prs);+ if (!items.length) return null;+ const label = prCountLabel(items.length);+ return (+ <Popover>+ <PopoverTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-6 gap-1 px-2 font-mono"+ aria-label={`${label} in this session`}+ >+ <GitPullRequest size={12} aria-hidden />+ {label}+ <CaretDown size={10} aria-hidden />+ </Button>+ }+ />+ <PopoverContent align="start" className="w-72 p-1.5">+ <ul+ aria-label="Pull requests"+ className="flex max-h-72 flex-col overflow-y-auto"+ >+ {items.map((pr) => {+ const body = (+ <>+ {pr.provider === 'github' ? (+ <GitHubMark className="size-3 shrink-0 text-ds-text-subtle" />+ ) : null}+ <span+ className="min-w-0 flex-1 truncate font-mono"+ title={pr.label}+ >+ {pr.provider === 'github'+ ? pr.label+ : `${pr.provider} ${pr.label}`}+ </span>+ </>+ );+ const row =+ 'flex items-center gap-2 rounded-md px-3 py-1.5 ds-text-body-xs-medium text-ds-text-default';+ return (+ <li key={pr.key}>+ {/* `url` is null unless it is http(s), so a crafted map can't+ * plant a javascript: link. */}+ {pr.url ? (+ <a+ href={pr.url}+ target="_blank"+ rel="noopener noreferrer"+ className={`${row} hover:bg-ds-gray-subtlest focus-visible:bg-ds-gray-subtlest focus-visible:outline-none`}+ >+ {body}+ <ArrowSquareOut+ size={12}+ aria-hidden+ className="shrink-0 text-ds-text-subtle"+ />+ </a>+ ) : (+ <div className={row}>{body}</div>+ )}+ </li>+ );+ })}+ </ul>+ {/* One row under the PRs, not a block over them: every link above+ * works offline, and this is the one thing that needs an account. */}+ <a+ href={connectUrl('pr-menu')}+ target="_blank"+ rel="noopener noreferrer"+ className="mt-1 flex items-center gap-2 rounded-md border-t border-ds-border-subtlest px-3 pb-1.5 pt-2 ds-text-body-xs-medium text-ds-text-subtle hover:bg-ds-gray-subtlest focus-visible:bg-ds-gray-subtlest focus-visible:outline-none"+ >+ <span className="min-w-0 flex-1 truncate">+ Trace review comments to the edits behind them+ </span>+ <ArrowSquareOut size={12} aria-hidden className="shrink-0" />+ </a>+ </PopoverContent>+ </Popover>+ );+}diff --git a/viewer/src/explorer/SessionList.tsx b/viewer/src/explorer/SessionList.tsxnew file mode 100644index 0000000..4266ab0--- /dev/null+++ b/viewer/src/explorer/SessionList.tsx@@ -0,0 +1,343 @@+import {+ useLayoutEffect,+ useRef,+ useState,+ type ReactNode,+} from 'react';+import { MagnifyingGlass } from '@phosphor-icons/react';+import type { SessionExplorerSession } from '@/core/schema';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { cn } from '@/lib/utils';+import { clockAt, dayLabel, fmtDur, fmtUsd } from '@/core/sessionMapModel';+import { groupSessionsByDay } from '@/core/sessionLayout';++const AGENT_TOOL_LABEL: Record<string, string> = {+ 'claude-code': 'Claude Code',+ codex: 'Codex',+ cursor: 'Cursor',+ kiro: 'Kiro',+ opencode: 'OpenCode',+ copilot: 'Copilot',+};++export const agentToolLabel = (tool: string): string =>+ AGENT_TOOL_LABEL[tool] ?? tool;++/** Subagent and helper runs are reached from inside their parent session;+ * the server already drops them from the list, this guards an older+ * server. A missing role is a main session (older CLIs). */+export const isMainSession = (s: SessionExplorerSession): boolean =>+ s.role !== 'subagent' && s.role !== 'helper';++export const sessionTitle = (s: SessionExplorerSession): string =>+ s.sessionTitle?.trim() ||+ `${agentToolLabel(s.agentTool)} session${s.repos[0] ? ` in ${s.repos[0]}` : ''}`;++interface Props {+ sessions: SessionExplorerSession[];+ selectedId: string | null;+ onSelect: (sessionId: string) => void;+ /** open the session in the sidebar: its tasks, errors and subagents */+ onOpen: (sessionId: string) => void;+ search: string;+ onSearch: (value: string) => void;+ hasMore: boolean;+ loadingMore: boolean;+ onLoadMore: () => void;+ /** sessions whose map the server reported as not_found */+ unavailable?: ReadonlySet<string>;+ /** sidebar header row (title + collapse button), above the search */+ header?: ReactNode;+ /** extra controls under the search (the window range select) */+ toolbar?: ReactNode;+}++/**+ * The list's scroll offset, kept outside React on purpose.+ *+ * The sidebar renders inside `MapPlayerBody`, which `MapPlayer` keys on the+ * scope so playback re-initialises for the new session -- so picking a+ * session unmounts this list and mounts a fresh one, scrolled to the top,+ * taking the row that was just clicked off screen with it. Component state+ * cannot survive that; a module-level value can.+ *+ * Tagged with the filter it was taken under, so an offset from one list is+ * never restored onto a different one.+ */+let savedScroll: { top: number; tag: string } | null = null;++export function SessionList({+ sessions,+ selectedId,+ onSelect,+ onOpen,+ search,+ onSearch,+ hasMore,+ loadingMore,+ onLoadMore,+ unavailable,+ header,+ toolbar,+}: Props) {+ const [tool, setTool] = useState<string>('all');+ const main = sessions.filter(isMainSession);+ const present = [...new Set(main.map((s) => s.agentTool))];+ // Keep a selected tool's chip even when a search leaves it no sessions, so+ // the filter stays visible and effective rather than silently+ // widening to every session.+ const tools =+ tool !== 'all' && !present.includes(tool) ? [...present, tool] : present;+ const visible =+ tool === 'all' ? main : main.filter((s) => s.agentTool === tool);+ const groups = groupSessionsByDay(visible);++ const scrollRef = useRef<HTMLDivElement>(null);+ const selectedRef = useRef<HTMLDivElement>(null);+ // What the saved offset belongs to. A search or a tool filter builds a+ // different list, and an offset from the old one would land anywhere.+ const tag = `${search}\u0000${tool}`;+ useLayoutEffect(() => {+ const box = scrollRef.current;+ if (!box) return;+ if (savedScroll && savedScroll.tag === tag) box.scrollTop = savedScroll.top;+ // The offset is restored first so the list looks untouched; this only+ // moves anything when it could not do its job -- a deep link, a+ // filter change, or a row that has shifted out of view since.+ const row = selectedRef.current;+ if (!row) return;+ const r = row.getBoundingClientRect();+ const b = box.getBoundingClientRect();+ if (r.top < b.top || r.bottom > b.bottom) {+ row.scrollIntoView({ block: 'nearest' });+ }+ // Mount only: this restores a position across the remount that picking a+ // session causes, and must not fight the user's own scrolling after.+ }, []);++ return (+ <nav+ aria-label="Sessions with maps"+ className="flex h-full min-h-0 flex-col gap-2 rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-3"+ >+ {header}+ <div className="relative">+ <MagnifyingGlass+ size={14}+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-ds-text-subtle"+ />+ <Input+ value={search}+ onChange={(e) => onSearch(e.target.value)}+ placeholder="Filter by title or repo"+ aria-label="Filter sessions"+ className="h-8 pl-8"+ />+ </div>+ {toolbar}+ {tools.length > 1 ? (+ <ToolFilter tools={tools} tool={tool} onTool={setTool} />+ ) : null}+ <div className="ds-text-body-xs-medium text-ds-text-subtle">+ {visible.length} session{visible.length === 1 ? '' : 's'} with maps+ {hasMore ? ' loaded' : ''} · main sessions only+ </div>+ <div+ ref={scrollRef}+ onScroll={(e) => {+ savedScroll = { top: e.currentTarget.scrollTop, tag };+ }}+ className="-mx-1 flex min-h-0 flex-1 flex-col overflow-y-auto px-1"+ >+ {groups.length === 0 ? (+ <div className="py-6 text-center ds-text-body-xs-medium text-ds-text-subtle">+ No sessions match this filter+ </div>+ ) : null}+ {groups.map((g) => (+ <div key={g.day} className="flex flex-col gap-1 pb-2">+ <div className="sticky top-0 z-10 bg-ds-surface-white py-1 ds-text-body-xs-semibold text-ds-text-subtle">+ {dayLabel(`${g.day}T00:00:00Z`)}+ </div>+ {g.items.map((s) => (+ <SessionRow+ key={s.sessionId}+ s={s}+ selected={s.sessionId === selectedId}+ unavailable={!!unavailable?.has(s.sessionId)}+ rowRef={s.sessionId === selectedId ? selectedRef : undefined}+ onSelect={() => onSelect(s.sessionId)}+ onOpen={() => onOpen(s.sessionId)}+ />+ ))}+ </div>+ ))}+ {hasMore ? (+ <Button+ variant="outline"+ size="sm"+ onClick={onLoadMore}+ disabled={loadingMore}+ className="mt-1"+ >+ {loadingMore ? 'Loading…' : 'Load more sessions'}+ </Button>+ ) : null}+ </div>+ </nav>+ );+}++function ToolFilter({+ tools,+ tool,+ onTool,+}: {+ tools: string[];+ tool: string;+ onTool: (tool: string) => void;+}) {+ return (+ <div+ role="group"+ aria-label="Filter sessions by coding agent"+ className="flex flex-wrap gap-1"+ >+ {['all', ...tools].map((t) => (+ <button+ key={t}+ type="button"+ aria-pressed={tool === t}+ onClick={() => onTool(t)}+ className={cn(+ 'rounded-full border px-2 py-0.5 ds-text-body-xs-medium transition-colors',+ tool === t+ ? 'border-transparent bg-ds-brand-lightest text-ds-text-darker'+ : 'border-ds-border-subtlest text-ds-text-subtle hover:border-ds-border-default'+ )}+ >+ {t === 'all' ? 'All' : agentToolLabel(t)}+ </button>+ ))}+ </div>+ );+}++/**+ * A row picks a session; "Open" is what descends into it. Picking does not+ * replace the list with one session's tasks, so two sessions can be compared+ * without going back out each time: the map and Details follow the selection+ * while the list stays put, and Open is the deliberate step.+ *+ * A div, not a button: Open sits inside the card, and a button inside a+ * button is invalid and unreachable by keyboard.+ */+function SessionRow({+ s,+ selected,+ unavailable,+ onSelect,+ onOpen,+ rowRef,+}: {+ s: SessionExplorerSession;+ selected: boolean;+ unavailable: boolean;+ onSelect: () => void;+ onOpen: () => void;+ rowRef?: React.Ref<HTMLDivElement>;+}) {+ return (+ <div+ ref={rowRef}+ className={cn(+ 'group flex flex-col rounded-lg border transition-colors',+ selected+ ? 'border-ds-brand-subtler bg-ds-brand-lightest'+ : 'border-transparent hover:bg-ds-gray-subtlest'+ )}+ >+ <button+ type="button"+ aria-current={selected ? 'true' : undefined}+ onClick={onSelect}+ onDoubleClick={onOpen}+ className="flex cursor-pointer flex-col gap-1 rounded-lg p-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ds-brand-subtler"+ >+ <span className="line-clamp-2 ds-text-body-xs-medium text-ds-text-darker">+ {sessionTitle(s)}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {clockAt(s.startedAt, 0).slice(0, 5)} UTC · {fmtDur(s.durationMs)} ·{' '}+ {s.calls} calls · {fmtUsd(s.costUsd)}+ </span>+ <SessionRowBadges s={s} unavailable={unavailable} />+ </button>+ {/* Always there for the selected row -- you just clicked it, so that+ * is where the next step belongs. Quiet on the rest until pointed at+ * or tabbed to, so a long list does not grow a button per row. */}+ <div+ className={cn(+ 'px-2 pb-2 transition-opacity',+ selected+ ? 'opacity-100'+ : 'opacity-0 focus-within:opacity-100 group-hover:opacity-100'+ )}+ >+ <Button+ variant="secondary"+ size="sm"+ onClick={onOpen}+ className="h-6 w-full cursor-pointer px-2"+ aria-label={`Open ${sessionTitle(s)}: its prompts, errors and subagents`}+ >+ Open+ </Button>+ </div>+ </div>+ );+}++const plural = (n: number, one: string) => `${n} ${one}${n > 1 ? 's' : ''}`;++function SessionRowBadges({+ s,+ unavailable,+}: {+ s: SessionExplorerSession;+ unavailable: boolean;+}) {+ const merged = !!s.prs?.some((pr) => pr.state === 'merged');+ // The row carries no task source, so count user prompts (every local task+ // window is one). A segmented session with no user turns shows no count+ // rather than its task count under the prompt label.+ const prompts = s.userTurns;+ return (+ <span className="flex flex-wrap gap-1">+ <Badge variant="secondary">{agentToolLabel(s.agentTool)}</Badge>+ {s.repos.map((r) => (+ <Badge key={r} variant="outline">+ {r}+ </Badge>+ ))}+ {prompts > 1 ? (+ <Badge variant="outline">{plural(prompts, 'prompt')}</Badge>+ ) : null}+ {merged ? <Badge variant="outline">PR merged</Badge> : null}+ {s.subagents ? (+ <Badge variant="outline">{plural(s.subagents, 'subagent')}</Badge>+ ) : null}+ {s.errors ? (+ <Badge variant="error">{plural(s.errors, 'error')}</Badge>+ ) : null}+ {s.compactions ? (+ <Badge variant="warning">{plural(s.compactions, 'compaction')}</Badge>+ ) : null}+ {unavailable ? (+ <Badge variant="secondary">map not available</Badge>+ ) : null}+ </span>+ );+}diff --git a/viewer/src/explorer/SessionMapSvg.tsx b/viewer/src/explorer/SessionMapSvg.tsxnew file mode 100644index 0000000..de49ea9--- /dev/null+++ b/viewer/src/explorer/SessionMapSvg.tsx@@ -0,0 +1,669 @@+import { useMemo, useState, type KeyboardEvent, type MouseEvent } from 'react';+import type { SessionMap } from '@/core/schema';+import {+ OP_GLYPH,+ activeSet,+ ancestorsOf,+ lastTouch,+ leafCount,+ litSet,+ nextTouchOf,+ stateAt,+ touchesOfFile,+ type NodeRef,+ type NodeState,+ type SessionTree,+ type TreeNode,+} from '@/core/sessionMapModel';+import {+ ERROR_COLOR,+ FAINT_FILL,+ HOLLOW_FILL,+ HOLLOW_RING,+ KIND_META,+ TOUCH_COLOR,+ TRAIL_COLOR,+ kindStyle,+ nodeColor,+} from '@/core/eventColors';+import {+ labelChars,+ mapPadY,+ mapViewBox,+ truncateLabel,+ type LabelSpot,+} from '@/core/mapGeometry';+import {+ ALL_CATEGORIES,+ activeRefs,+ narrowsView,+ type Category,+} from '@/core/sessionLayout';++/** Leaf / branch label sizes (px in viewBox units). */+const LEAF_FONT = 13.5;+const BRANCH_FONT = 14;+const ACTIVE_LEN = 20;+const MONO = 'var(--font-mono, ui-monospace, monospace)';+/** Opacity multiplier for everything off the pinned leaf's ancestor chain,+ * while a leaf is pinned: noticeably faded but still legible. */+const PIN_DIM = 0.38;+/** Nodes coloured by their own touch state (everything else lights by path). */+const LEAFISH = new Set([+ 'file',+ 'place',+ 'mcptool',+ 'skill',+ 'agent',+ 'web',+ 'errclass',+ 'model',+ 'output',+]);+/** Nodes whose label carries a trailing ×N -- entities called/touched more+ * than once that a chip selection can narrow down to, so the count reads+ * as "how many times", e.g. an MCP tool invoked repeatedly with different+ * args. */+const COUNTED = new Set([+ 'file',+ 'place',+ 'errclass',+ 'mcptool',+ 'server',+ 'skill',+ 'model',+]);+const TYPE_LABEL: Record<string, string> = {+ model: 'model',+ outgroup: 'outputs',+ output: 'output',+ mcptool: 'MCP tool',+ server: 'MCP server',+ place: 'outside repo',+ agent: 'subagent',+ errclass: 'error class',+ errsrc: 'error source',+};++interface Props {+ map: SessionMap;+ tree: SessionTree;+ nodes: TreeNode[];+ refs: NodeRef[][];+ p: number;+ onSeek: (index: number) => void;+ /** true while playback is actively advancing: only the step at the+ * playhead is lit and labelled. False (paused) lights the recent+ * ACTIVE_LEN window. */+ playing: boolean;+ /** A node click that means "scope to this" instead of "jump to+ * its next touch" (model nodes scope to that model, subagent nodes open+ * that subagent's own map). Return true when handled. */+ onNodeAction?: (node: TreeNode) => boolean;+ /** the nodes the dock's category selection lights (`mapFocus`); the rest+ * fade. Null: no category focus, the map renders as usual. */+ focus?: ReadonlySet<string> | null;+ /** the dock's category chips: also scopes the recent-touch window (dot+ * prominence + labels) to the selection, via `activeRefs` -- so it's the+ * selection's own last ACTIVE_LEN, not whatever else happened to be+ * touched most recently. Same set `focus` was built from. */+ selected?: ReadonlySet<Category>;+}++interface Tip {+ id: string;+ x: number;+ y: number;+}++function edgePath(n: TreeNode, root: TreeNode): string {+ const p = n.parent;+ if (!p) return '';+ if (p === root) return `M0 0 L${n.x} ${n.y}`;+ const rm = (p.r + n.r) / 2;+ const c1x = Math.cos(p.a) * rm;+ const c1y = Math.sin(p.a) * rm;+ const c2x = Math.cos(n.a) * rm;+ const c2y = Math.sin(n.a) * rm;+ return `M${p.x} ${p.y} C${c1x} ${c1y} ${c2x} ${c2y} ${n.x} ${n.y}`;+}++const isBig = (n: TreeNode) => n.type === 'repo' || n.type === 'group';+/** Nodes whose label runs along their spoke whenever it is shown. */+const hasSpokeLabel = (n: TreeNode) =>+ !n.children.length ||+ (n.type === 'dir' && n.depth <= 2) ||+ n.type === 'server' ||+ n.type === 'errsrc';+/** Where a node's spoke label starts, and how long it wants to be. */+const labelSpot = (n: TreeNode): LabelSpot => ({+ r0: n.r + (n.children.length ? 7 : 8),+ a: n.a,+ font: n.children.length ? BRANCH_FONT : LEAF_FONT,+ len: n.name.length,+});+/** Opacity multiplier for nodes outside the chip selection's focus. */+const FOCUS_DIM = 0.22;++interface DotStyle {+ fill: string;+ stroke: string;+ strokeWidth: number;+ r: number;+ opacity: number;+}++function dotStyle(+ n: TreeNode,+ s: NodeState | undefined,+ on: boolean,+ lit: boolean+): DotStyle {+ const big = isBig(n);+ if (LEAFISH.has(n.type)) {+ if (!s) {+ return {+ fill: HOLLOW_FILL,+ stroke: HOLLOW_RING,+ strokeWidth: 1.2,+ r: 2.6,+ opacity: 0.9,+ };+ }+ const color = n.type === 'file' ? TOUCH_COLOR[s.lvl] : nodeColor(n);+ return {+ fill: on ? color : FAINT_FILL,+ // a node that failed at the playhead wears a critical ring+ stroke: s.err ? ERROR_COLOR : on ? 'none' : color,+ strokeWidth: s.err ? 1.8 : 1,+ r: Math.min(3 + Math.sqrt(s.cnt) * 1.3, 9),+ opacity: on ? 1 : 0.7,+ };+ }+ return {+ fill: lit ? nodeColor(n) : HOLLOW_FILL,+ stroke: lit ? 'none' : HOLLOW_RING,+ strokeWidth: 1.2,+ r: big ? 5.5 : 3,+ opacity: lit ? 1 : 0.9,+ };+}++export function SessionMapSvg({+ map,+ tree,+ nodes,+ refs,+ p,+ onSeek,+ playing,+ onNodeAction,+ focus = null,+ // An omitted `selected` means "no narrowing", same as focus's own null+ // default.+ selected = ALL_CATEGORIES,+}: Props) {+ const [tip, setTip] = useState<Tip | null>(null);+ const hover = tip?.id ?? null;+ // Local, map-only "pinned leaf": clicking a visible leaf's label+ // toggles it. Does not touch ExplorerScope/URL/timeline/event chips.+ const [pinned, setPinned] = useState<string | null>(null);++ // Vertical room for the spoke labels near the top / bottom, per map.+ const padY = useMemo(+ () =>+ mapPadY(+ nodes+ .filter((n) => n.parent && !isBig(n) && hasSpokeLabel(n))+ .map(labelSpot)+ ),+ [nodes]+ );+ const fade = (id: string) => (focus && !focus.has(id) ? FOCUS_DIM : 1);+ // A narrowing chip selection also scopes what counts as "recently+ // touched": otherwise unselected activity (e.g. MCP calls while only+ // Edits is selected) fills the recent-N budget and an edited file's+ // label never appears, or stops tracking the playhead. `nextTouchOf`'s+ // seek target stays on the raw `refs` below -- scoping it would stop a+ // click from finding a real touch just because it's outside the current+ // selection.+ const focusRefs = useMemo(+ () => activeRefs(refs, map.events, selected),+ [refs, map.events, selected]+ );+ // `p` defaults to a "meaningful first frame" partway into the session+ // (initialPlayhead), not the end -- fine for the default view, but a+ // narrowing chip selection means "show me every match", not "only the+ // matches seen by wherever the scrubber happens to be sitting". So+ // while paused, a narrowed selection reads state as of the session's+ // last event instead of the live playhead; playing still animates the+ // reveal from `p` as before.+ const stP = !playing && narrowsView(selected) ? focusRefs.length - 1 : p;+ const st = useMemo(() => stateAt(focusRefs, stP), [focusRefs, stP]);+ // Also on stP, not the live p: `active` gates label visibility below+ // (line ~464) regardless of playing state, so a paused, narrowed view+ // needs it walking back from the full session too, or the dots light up+ // (via st, above) while their labels stay hidden -- still capped at+ // ACTIVE_LEN, same as ever, just anchored at the selection's own last+ // touch instead of wherever the scrubber happens to be.+ // The step at the playhead: the latest event at or before p that touches+ // a node in the selection. It pulses, its centre-to-leaf curve is drawn in+ // its colour, and -- for a subagent's step -- so is the path to that+ // subagent (in place of the old straight dashed link across the map).+ const touch = useMemo(() => lastTouch(focusRefs, p), [focusRefs, p]);+ const touchEvent = touch ? map.events[touch.i] : undefined;+ const agentId =+ touchEvent && touchEvent.agent && touchEvent.agent !== 'main'+ ? (tree.byId.get(`agent:${touchEvent.agent}`)?.id ?? null)+ : null;+ const touchPath = useMemo(+ () => (touch ? ancestorsOf(tree, new Set(touch.ids)) : null),+ [tree, touch]+ );+ const agentPath = useMemo(+ () => (agentId ? ancestorsOf(tree, new Set([agentId])) : null),+ [tree, agentId]+ );+ // What's lit and labelled. Playing: only that one step (and its+ // subagent) -- one leaf path at a time as the timeline moves, not a+ // recent-N window of leaves lighting up together. Paused: the recent+ // ACTIVE_LEN window from stP, plus the step itself so its pulse is never+ // an unlabelled dot.+ const active = useMemo(() => {+ const out = playing+ ? new Set<string>()+ : activeSet(focusRefs, stP, ACTIVE_LEN);+ for (const id of touch?.ids ?? []) out.add(id);+ if (agentId) out.add(agentId);+ return out;+ }, [playing, focusRefs, stP, touch, agentId]);+ const activeAnc = useMemo(() => ancestorsOf(tree, active), [tree, active]);+ const lit = useMemo(() => litSet(tree, st), [tree, st]);+ // Only active nodes render coloured (and their paths lit), paused or+ // playing: a node touched earlier but outside the window would keep a+ // coloured ring with no label. Coloured <=> labelled; everything else+ // reads as untouched.+ const windowedSt = useMemo(+ () => new Map([...st].filter(([id]) => active.has(id))),+ [st, active]+ );+ // activeAnc is already active's own ids plus their ancestors+ // (ancestorsOf includes the starting id), so it doubles as the windowed+ // lit set without a separate union.+ const windowedLit = activeAnc;+ // #4: pinning overrides the window -- the pinned leaf and its ancestor+ // chain always render at full prominence, even mid-playback and even out+ // of the recent window.+ const pinnedAnc = useMemo(+ () => (pinned ? ancestorsOf(tree, new Set([pinned])) : null),+ [tree, pinned]+ );+ const effectiveLit = useMemo(+ () => (pinnedAnc ? new Set([...windowedLit, ...pinnedAnc]) : windowedLit),+ [windowedLit, pinnedAnc]+ );++ const jumpTo = (id: string) => {+ const node = tree.byId.get(id);+ if (node && onNodeAction?.(node)) return;+ const i = nextTouchOf(tree, refs, p, id);+ if (i != null) onSeek(i);+ };++ const onMove = (ev: MouseEvent<SVGSVGElement>) => {+ const id = (ev.target as Element).getAttribute?.('data-id');+ if (!id) {+ if (tip) setTip(null);+ return;+ }+ const box = ev.currentTarget.getBoundingClientRect();+ setTip({ id, x: ev.clientX - box.left, y: ev.clientY - box.top });+ };++ const onClick = (ev: MouseEvent<SVGSVGElement>) => {+ const id = (ev.target as Element).getAttribute?.('data-id');+ if (id) jumpTo(id);+ };++ const onKey = (ev: KeyboardEvent<SVGCircleElement>, id: string) => {+ if (ev.key === 'Enter') {+ ev.preventDefault();+ ev.stopPropagation();+ jumpTo(id);+ }+ };++ // A leaf's label click/Enter/Space toggles the pin (a second, independent+ // interactive target from its dot, which keeps seeking to next touch).+ const togglePin = (id: string) =>+ setPinned((cur) => (cur === id ? null : id));+ const onLabelKey = (ev: KeyboardEvent<SVGTextElement>, id: string) => {+ if (ev.key === 'Enter' || ev.key === ' ') {+ ev.preventDefault();+ ev.stopPropagation();+ togglePin(id);+ }+ };++ const pulseColor = touchEvent+ ? touchEvent.err+ ? ERROR_COLOR+ : kindStyle(touchEvent).color+ : TRAIL_COLOR;++ const tipNode = hover ? tree.byId.get(hover) : undefined;++ return (+ // Fills its pane (fit-viewport layout): the SVG takes the pane's full+ // height and scales the radial map into it (xMidYMid meet keeps it round+ // and centred; the dock's category chips carry the colour key). No CSS+ // transitions or animations here: playback re-renders it every tick.+ <div className="relative flex h-full min-h-0 flex-col">+ <svg+ viewBox={mapViewBox(padY)}+ preserveAspectRatio="xMidYMid meet"+ width="100%"+ height="100%"+ className="block min-h-0 w-full flex-1 select-none"+ role="img"+ aria-label="Session map: repositories, files, MCP tools, skills, subagents and errors touched in this session"+ onMouseMove={onMove}+ onMouseLeave={() => setTip(null)}+ onClick={onClick}+ >+ <g>+ {nodes.map((n) => {+ if (!n.parent) return null;+ const onPath = pinnedAnc?.has(n.id) ?? false;+ const dim = pinned != null && !onPath;+ // The current step's centre-to-leaf curve in its own colour, and+ // the acting subagent's path in the subagent colour.+ const stepColor = touchPath?.has(n.id)+ ? pulseColor+ : agentPath?.has(n.id)+ ? KIND_META.subagent.color+ : null;+ if (stepColor) {+ return (+ <path+ key={`e-${n.id}`}+ d={edgePath(n, tree.root)}+ fill="none"+ strokeWidth={2.2}+ strokeLinecap="round"+ stroke={stepColor}+ opacity={(dim ? PIN_DIM : 1) * fade(n.id)}+ />+ );+ }+ return (+ <path+ key={`e-${n.id}`}+ d={edgePath(n, tree.root)}+ fill="none"+ strokeWidth={n.parent === tree.root ? 1.4 : 1}+ stroke={+ effectiveLit.has(n.id)+ ? 'var(--ds-border-default)'+ : 'var(--ds-border-subtler)'+ }+ opacity={+ (effectiveLit.has(n.id) ? 0.9 : 0.55) *+ (dim ? PIN_DIM : 1) *+ fade(n.id)+ }+ />+ );+ })}+ </g>+ <g>+ {nodes.map((n) => {+ if (n === tree.root) {+ return (+ <g key="root">+ <circle r={9} fill="var(--ds-brand-subtlest)" />+ <circle r={3.5} fill="var(--ds-brand-subtle)" />+ </g>+ );+ }+ const onPath = pinnedAnc?.has(n.id) ?? false;+ const d = dotStyle(+ n,+ onPath ? st.get(n.id) : windowedSt.get(n.id),+ active.has(n.id) || onPath,+ effectiveLit.has(n.id)+ );+ const leaf = !n.children.length;+ const dim = pinned != null && !onPath;+ return (+ <circle+ key={n.id}+ data-id={n.id}+ cx={n.x}+ cy={n.y}+ r={d.r}+ fill={d.fill}+ stroke={d.stroke}+ strokeWidth={d.strokeWidth}+ opacity={d.opacity * (dim ? PIN_DIM : 1) * fade(n.id)}+ tabIndex={leaf ? 0 : -1}+ aria-label={leaf ? `${n.name}, jump to next touch` : undefined}+ className="cursor-pointer outline-none focus-visible:stroke-ds-brand-subtle"+ onKeyDown={leaf ? (ev) => onKey(ev, n.id) : undefined}+ />+ );+ })}+ </g>+ <g pointerEvents="none">+ {nodes.map((n) => {+ if (n === tree.root) return null;+ const big = isBig(n);+ const show =+ big ||+ n.id === hover ||+ (pinnedAnc?.has(n.id) ?? false) ||+ (n.children.length ? activeAnc.has(n.id) : active.has(n.id)) ||+ (n.type === 'errsrc' && lit.has(n.id));+ if (!show) return null;+ const flip = Math.cos(n.a) < 0;+ if (big) {+ const lx = Math.cos(n.a) * (n.r + 14);+ const ly = Math.sin(n.a) * (n.r + 14);+ return (+ <text+ key={`l-${n.id}`}+ x={lx}+ y={ly}+ textAnchor={+ Math.abs(Math.cos(n.a)) < 0.3+ ? 'middle'+ : flip+ ? 'end'+ : 'start'+ }+ dominantBaseline="middle"+ fontSize={16}+ fontWeight={600}+ fill="var(--ds-text-darker)"+ paintOrder="stroke"+ stroke="var(--ds-surface-white)"+ strokeWidth={4}+ opacity={(lit.has(n.id) ? 1 : 0.45) * fade(n.id)}+ >+ {n.name}+ </text>+ );+ }+ if (!hasSpokeLabel(n) && n.id !== hover) return null;+ const isLeaf = !n.children.length;+ const off = n.children.length ? 7 : 8;+ const lx = n.x + Math.cos(n.a) * off;+ const ly = n.y + Math.sin(n.a) * off;+ // The label runs along the node's own radial spoke, cut to what+ // fits above / below the circle (`labelChars`).+ const deg = (n.a * 180) / Math.PI;+ const rot = flip ? deg + 180 : deg;+ // A ×N suffix, not the old separate badge floating off to one+ // side of the dot (read as a prefix at some angles): it now+ // trails the name inside the same text run, so it always reads+ // after it, in the node's own colour to set it apart.+ const s = st.get(n.id);+ const showCount = COUNTED.has(n.type) && !!s && s.cnt > 1;+ const countTxt = s ? (s.cnt > 99 ? '99+' : String(s.cnt)) : '';+ const countColor = s+ ? n.type === 'file'+ ? TOUCH_COLOR[s.lvl]+ : nodeColor(n)+ : undefined;+ const budget = labelChars(labelSpot(n), padY);+ const nameBudget = showCount+ ? Math.max(3, budget - countTxt.length - 2)+ : budget;+ return (+ <text+ key={`l-${n.id}`}+ x={lx}+ y={ly}+ transform={`rotate(${rot} ${lx} ${ly})`}+ textAnchor={flip ? 'end' : 'start'}+ dominantBaseline="middle"+ fontSize={n.children.length ? BRANCH_FONT : LEAF_FONT}+ opacity={fade(n.id)}+ fill={+ n.children.length+ ? 'var(--ds-text-subtle)'+ : 'var(--ds-text-default)'+ }+ fontFamily={MONO}+ paintOrder="stroke"+ stroke="var(--ds-surface-white)"+ strokeWidth={3}+ role={isLeaf ? 'button' : undefined}+ tabIndex={isLeaf ? 0 : undefined}+ aria-pressed={isLeaf ? n.id === pinned : undefined}+ style={+ isLeaf+ ? { cursor: 'pointer', pointerEvents: 'auto' }+ : undefined+ }+ onClick={+ isLeaf+ ? (ev) => {+ ev.stopPropagation();+ togglePin(n.id);+ }+ : undefined+ }+ onKeyDown={isLeaf ? (ev) => onLabelKey(ev, n.id) : undefined}+ >+ {truncateLabel(n.name, nameBudget)}+ {showCount ? (+ <tspan fill={countColor} fontWeight={700}>+ {' '}+ ×{countTxt}+ </tspan>+ ) : null}+ </text>+ );+ })}+ </g>+ <g pointerEvents="none">+ {(touch?.ids ?? []).map((id) => {+ const n = tree.byId.get(id);+ if (!n) return null;+ return (+ <g key={`p-${id}`}>+ {/* One steady ring, no animation: during playback the+ current node changes every tick, and a re-started+ pulse read as the whole map flashing. */}+ <circle+ cx={n.x}+ cy={n.y}+ r={8}+ fill="none"+ stroke={pulseColor}+ strokeWidth={2}+ opacity={0.55}+ />+ <circle cx={n.x} cy={n.y} r={4.5} fill={pulseColor} />+ </g>+ );+ })}+ </g>+ </svg>+ {tip && tipNode ? (+ <MapTooltip+ map={map}+ node={tipNode}+ state={st.get(tipNode.id)}+ x={tip.x}+ y={tip.y}+ />+ ) : null}+ </div>+ );+}++function MapTooltip({+ map,+ node,+ state,+ x,+ y,+}: {+ map: SessionMap;+ node: TreeNode;+ state: NodeState | undefined;+ x: number;+ y: number;+}) {+ const kids = node.children.length ? `${leafCount(node)} items below` : '';+ const fileId =+ node.type === 'file' ? Number(node.id.slice('file:'.length)) : null;+ // Last op seen for this file, a document-level+ // record so it stays correct even under an agent lens (the file itself+ // did not change scope, only which events are being replayed).+ const fileOp =+ fileId != null ? map.files.find((f) => f.id === fileId)?.op : undefined;+ const title =+ node.type === 'file'+ ? `${fileOp ? `${OP_GLYPH[fileOp]} ` : ''}${node.repoName}/${node.path}`+ : node.name;+ const touches = fileId != null ? touchesOfFile(map, fileId) : null;+ return (+ <div+ className="pointer-events-none absolute z-20 w-max max-w-[320px] rounded-lg border border-ds-border-subtlest bg-ds-surface-white p-2.5 shadow-md"+ style={{ left: Math.max(8, x + 12), top: y + 12 }}+ role="tooltip"+ >+ <div className="break-all ds-text-body-xs-semibold text-ds-text-darker">+ {title}+ </div>+ <div className="mt-0.5 ds-text-body-xs-medium text-ds-text-subtle">+ {TYPE_LABEL[node.type] ?? node.type}+ {kids ? ` · ${kids}` : ''}+ </div>+ {touches ? (+ <div className="mt-0.5 ds-text-body-xs-medium text-ds-text-default">+ session: {touches.read} reads · {touches.edit} edits · {touches.hit}{' '}+ hits+ </div>+ ) : null}+ <div className="mt-0.5 ds-text-body-xs-medium text-ds-text-subtle">+ {state+ ? `touched ${state.cnt}× by playhead · first at #${state.first}`+ : 'not yet touched at playhead'}+ {state?.err ? (+ <span className="text-ds-danger-default"> · {state.err} failed</span>+ ) : null}+ {node.children.length+ ? ''+ : node.type === 'model'+ ? ' · click to show only this model'+ : node.type === 'agent'+ ? " · click to open this subagent's map"+ : ' · click to jump to next touch'}+ </div>+ </div>+ );+}diff --git a/viewer/src/explorer/SessionSidebar.tsx b/viewer/src/explorer/SessionSidebar.tsxnew file mode 100644index 0000000..593cfca--- /dev/null+++ b/viewer/src/explorer/SessionSidebar.tsx@@ -0,0 +1,970 @@+/**+ * The one left sidebar: the sessions list, or (once a session is+ * open) that session's card with Tasks / Subagents / Insights tabs, or (once+ * a subagent is open) the helper's card and what it touched. Collapses to a+ * 40px rail. Also the one-line task/subagent strip above the timeline.+ */+import type { ReactNode } from 'react';+import {+ ArrowLeft,+ CaretDoubleLeft,+ CaretDoubleRight,+ CaretLeft,+ CaretRight,+ ImageSquare,+ X,+} from '@phosphor-icons/react';+import type { SessionExplorerSession } from '@/core/schema';+import { Badge } from '@/components/ui/badge';+import { cn } from '@/lib/utils';+import { agentToolLabel } from './SessionList';+import { clockAt, dayLabel, fmtDur, fmtTok } from '@/core/sessionMapModel';+import {+ taskNoun,+ type TaskSummary,+ type TaskWindow,+} from '@/core/sessionScope';+import {+ costLabel,+ outputsLine,+ spanBarGeometry,+ spanLabel,+ type Category,+ type ErrorGroup,+ type SessionError,+ type SidebarTab,+ type SubagentInfo,+ type TaskErrors,+ type TouchedGroup,+} from '@/core/sessionLayout';+import { TOUCH_COLOR } from '@/core/eventColors';++const SIDEBAR_TAB_LABEL: Record<SidebarTab, string> = {+ errors: 'Errors',+ tasks: 'Tasks',+ subagents: 'Subagents',+ insights: 'Insights',+};++const iconBtn =+ 'inline-flex size-7 shrink-0 items-center justify-center rounded-md text-ds-text-subtle transition-colors hover:bg-ds-gray-subtlest hover:text-ds-text-default';++/** The frame every sidebar mode renders in: the explorer's full height, with+ * one region inside it scrolling (never the page). */+export function SidebarFrame({ children }: { children: ReactNode }) {+ return (+ <div className="flex h-full min-h-0 min-w-0 flex-col gap-3">{children}</div>+ );+}++export function CollapseButton({ onCollapse }: { onCollapse: () => void }) {+ return (+ <button+ type="button"+ onClick={onCollapse}+ aria-label="Collapse sidebar"+ title="Collapse sidebar"+ className={iconBtn}+ >+ <CaretDoubleLeft size={14} />+ </button>+ );+}++/** The collapsed sidebar: a 40px rail with vertical text; click expands. */+export function SidebarRail({+ label,+ onExpand,+}: {+ label: string;+ onExpand: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onExpand}+ aria-label={`Show sidebar (${label})`}+ title="Show sidebar"+ className="flex h-full min-h-[240px] w-10 flex-col items-center gap-3 rounded-xl border border-ds-border-subtlest bg-ds-surface-white py-3 text-ds-text-subtle transition-colors hover:border-ds-border-default hover:text-ds-text-default"+ >+ <CaretDoubleRight size={14} className="shrink-0" />+ <span className="max-h-full overflow-hidden whitespace-nowrap font-mono ds-text-body-xs-medium [writing-mode:vertical-rl]">+ {label}+ </span>+ </button>+ );+}++/** Header row of the sessions list (list mode). */+export function SessionListHeader({+ count,+ onCollapse,+}: {+ count: number;+ onCollapse: () => void;+}) {+ return (+ <div className="flex items-center gap-2">+ <span className="ds-text-body-sm-semibold text-ds-text-darker">+ Sessions+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle tabular-nums">+ {count}+ </span>+ <span className="flex-1" />+ <CollapseButton onCollapse={onCollapse} />+ </div>+ );+}++function BackRow({+ label,+ onBack,+ onCollapse,+}: {+ label: string;+ onBack: () => void;+ onCollapse: () => void;+}) {+ return (+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={onBack}+ className="inline-flex items-center gap-1.5 rounded-md py-1 pr-2 ds-text-body-xs-semibold text-ds-text-default hover:text-ds-text-darker"+ >+ <ArrowLeft size={14} />+ {label}+ </button>+ <span className="flex-1" />+ <CollapseButton onCollapse={onCollapse} />+ </div>+ );+}++/** A chip that narrows the timeline when clicked. Falls back to a plain chip+ * when no handler is given, so the chips still render outside the explorer. */+function ActionChip({+ onClick,+ title,+ variant,+ children,+}: {+ onClick?: () => void;+ title: string;+ variant: 'outline' | 'error';+ children: ReactNode;+}) {+ const chip = <Badge variant={variant}>{children}</Badge>;+ if (!onClick) return chip;+ return (+ <button+ type="button"+ onClick={onClick}+ title={title}+ aria-label={title}+ className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ds-border-focus"+ >+ {chip}+ </button>+ );+}++/** Chips of a session row: tool, tasks, PRs, subagents, errors.+ *+ * The counts are the quickest read in the sidebar, so the ones that correspond+ * to something on the timeline act as filters for it rather than sitting inert. */+function SessionChips({+ row,+ taskCount,+ noun,+ prCount,+ subCount,+ errors,+ onFocusCategory,+ onShowSubagents,+}: {+ row: SessionExplorerSession | null;+ taskCount: number;+ /** what the task windows are called (`taskNoun`) */+ noun: { many: string };+ prCount: number;+ subCount: number;+ errors: number;+ onFocusCategory?: (c: Category) => void;+ onShowSubagents?: () => void;+}) {+ return (+ <span className="flex flex-wrap gap-1">+ {row ? (+ <Badge variant="secondary">{agentToolLabel(row.agentTool)}</Badge>+ ) : null}+ {taskCount > 1 ? (+ <Badge variant="outline">+ {taskCount} {noun.many.toLowerCase()}+ </Badge>+ ) : null}+ {prCount ? (+ <ActionChip+ variant="outline"+ title="Show outputs on the timeline"+ onClick={onFocusCategory && (() => onFocusCategory('out'))}+ >+ {prCount} PR{prCount > 1 ? 's' : ''}+ </ActionChip>+ ) : null}+ {subCount ? (+ <ActionChip+ variant="outline"+ title="Show the subagents"+ onClick={onShowSubagents}+ >+ {subCount} subagent{subCount > 1 ? 's' : ''}+ </ActionChip>+ ) : null}+ {errors ? (+ <ActionChip+ variant="error"+ title="Show errors on the timeline"+ onClick={onFocusCategory && (() => onFocusCategory('error'))}+ >+ {errors} error{errors > 1 ? 's' : ''}+ </ActionChip>+ ) : null}+ </span>+ );+}++const card =+ 'flex flex-col gap-1 rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-3';++export interface SessionSidebarProps {+ row: SessionExplorerSession | null;+ title: string;+ startedAt: string;+ durationMs: number;+ costUsd: number;+ prCount: number;+ errors: number;+ tasks: TaskWindow[];+ taskSums: Map<number, TaskSummary>;+ task: number | null;+ onSelectTask: (n: number | null) => void;+ subs: SubagentInfo[];+ onOpenSub: (id: string) => void;+ tabs: SidebarTab[];+ tab: SidebarTab;+ onTab: (t: SidebarTab) => void;+ insights: ReactNode;+ onShowList: () => void;+ onCollapse: () => void;+ /** Narrow the timeline to one category, for the clickable count chips. */+ onFocusCategory?: (c: Category) => void;+ /** Every failure in the whole session, worst group first. */+ errorGroups?: ErrorGroup[];+ /** Whole-session `seq` under the playhead, to mark the error being replayed. */+ playheadSeq?: number | null;+ /** A row was clicked: the caller seeks, or re-scopes to reach it. */+ onSelectError?: (err: SessionError) => void;+ /** Errors per task, for the tag on each task row. */+ taskErrors?: Map<number, TaskErrors>;+ /** A task's error tag: scope to it, open Errors, land on its first error. */+ onJumpToTaskErrors?: (task: number, seq: number) => void;+}++/** Session mode: "← All sessions", the session card, then the tabs. */+export function SessionSidebar(props: SessionSidebarProps) {+ const {+ row,+ title,+ startedAt,+ durationMs,+ costUsd,+ tasks,+ task,+ onSelectTask,+ subs,+ tabs,+ tab,+ onTab,+ } = props;+ const noun = taskNoun(tasks);+ return (+ <SidebarFrame>+ <BackRow+ label="All sessions"+ onBack={props.onShowList}+ onCollapse={props.onCollapse}+ />+ <div className={card}>+ <span className="line-clamp-3 ds-text-body-sm-semibold text-ds-text-darker">+ {title}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {dayLabel(startedAt)} · {clockAt(startedAt, 0).slice(0, 5)} UTC ·{' '}+ {fmtDur(durationMs)} · {costLabel(costUsd)}+ </span>+ <SessionChips+ row={row}+ taskCount={tasks.length}+ noun={noun}+ prCount={props.prCount}+ subCount={subs.length}+ errors={props.errors}+ onFocusCategory={props.onFocusCategory}+ onShowSubagents={+ tabs.includes('subagents') ? () => onTab('subagents') : undefined+ }+ />+ </div>+ <div+ role="tablist"+ aria-label="Session sidebar"+ className="flex min-w-0 gap-0.5 rounded-lg border border-ds-border-subtlest bg-ds-surface-white p-[3px]"+ >+ {tabs.map((t) => (+ <button+ key={t}+ id={`se-sidebar-tab-${t}`}+ type="button"+ role="tab"+ aria-selected={tab === t}+ aria-controls="se-sidebar-panel"+ onClick={() => onTab(t)}+ className={cn(+ // Sized to its label (then sharing the slack), not a fixed quarter:+ // "Subagents 13" is wider than "Insights". `min-w-0` lets a label+ // truncate instead of widening the bar past the sidebar.+ 'flex min-w-0 flex-auto items-center justify-center gap-1 whitespace-nowrap rounded-md px-1 py-1 ds-text-body-xs-medium transition-colors',+ tab === t+ ? 'bg-ds-brand-lightest text-ds-brand-default'+ : 'text-ds-text-subtle hover:text-ds-text-default'+ )}+ >+ <span className="truncate">+ {t === 'tasks' ? noun.many : SIDEBAR_TAB_LABEL[t]}+ </span>+ {t === 'tasks' || t === 'subagents' || t === 'errors' ? (+ <span className="shrink-0 font-mono tabular-nums text-ds-text-subtler">+ {t === 'tasks'+ ? tasks.length+ : t === 'errors'+ ? props.errors+ : subs.length}+ </span>+ ) : null}+ </button>+ ))}+ </div>+ <div+ id="se-sidebar-panel"+ role="tabpanel"+ aria-labelledby={`se-sidebar-tab-${tab}`}+ className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto"+ >+ {tab === 'tasks' ? (+ <TaskList+ tasks={tasks}+ sums={props.taskSums}+ task={task}+ startedAt={startedAt}+ durationMs={durationMs}+ onSelect={onSelectTask}+ errors={props.taskErrors}+ onJumpToErrors={props.onJumpToTaskErrors}+ />+ ) : null}+ {tab === 'errors' ? (+ <ErrorList+ groups={props.errorGroups ?? []}+ noun={noun}+ startedAt={startedAt}+ playheadSeq={props.playheadSeq ?? null}+ onSelectError={props.onSelectError}+ />+ ) : null}+ {tab === 'subagents' ? (+ <SubagentList+ subs={subs}+ tasks={tasks}+ startedAt={startedAt}+ durationMs={durationMs}+ onOpen={props.onOpenSub}+ />+ ) : null}+ {tab === 'insights' ? props.insights : null}+ </div>+ </SidebarFrame>+ );+}++const rowBtn = (active: boolean) =>+ cn(+ 'flex w-full items-start gap-2 rounded-lg border p-2 text-left transition-colors',+ active+ ? 'border-ds-brand-subtler bg-ds-brand-lightest'+ : 'border-transparent hover:bg-ds-gray-subtlest'+ );++/** Every failure in the session, grouped by class, worst group first.+ *+ * The dock could already step between errors and the Activity feed listed the+ * ones behind the playhead, but nothing showed them all, and a row that reads+ * "outside-repo failed" is not enough to decide anything. These rows carry the+ * command, the class and the exit code the event already recorded, and a run+ * marker where the same command failed repeatedly — one failure is noise, four+ * in a row is a harness problem. */+function ErrorList({+ groups,+ noun,+ startedAt,+ playheadSeq,+ onSelectError,+}: {+ groups: ErrorGroup[];+ noun: { one: string };+ startedAt: string;+ playheadSeq: number | null;+ onSelectError?: (err: SessionError) => void;+}) {+ if (!groups.length)+ return (+ <p className="p-2 ds-text-body-xs-medium text-ds-text-subtle">+ No errors in this session.+ </p>+ );+ return (+ <>+ {groups.map((g) => (+ <section key={g.errClass} className="flex flex-col gap-1">+ <header className="flex items-baseline gap-1.5 px-2 pt-1.5">+ <span className="ds-text-body-xs-semibold text-ds-text-darker">+ {g.label}+ </span>+ <span className="font-mono tabular-nums ds-text-body-xs-medium text-ds-text-subtler">+ {g.errors.length}+ </span>+ {g.provider ? (+ <span className="ds-text-body-xs-medium text-ds-text-subtler">+ provider-side+ </span>+ ) : null}+ {g.worstRun > 2 && g.worstRunLabel ? (+ <Badge variant="error">+ {g.worstRun}× {g.worstRunLabel} in a row+ </Badge>+ ) : null}+ </header>+ {g.errors.map((e) => (+ <button+ key={`${e.index}`}+ type="button"+ aria-label={`${g.label}: ${e.label} at event ${e.seq}`}+ title={`${e.label} · ${g.label}${e.exitCode != null ? ` · exit ${e.exitCode}` : ''}`}+ onClick={() => onSelectError?.(e)}+ disabled={!onSelectError}+ className={rowBtn(playheadSeq === e.seq)}+ >+ <span className="w-10 shrink-0 text-right font-mono ds-text-body-xs-medium text-ds-text-subtler">+ {clockAt(startedAt, e.t).slice(0, 5)}+ </span>+ <span className="flex min-w-0 flex-col gap-0.5">+ <span className="truncate font-mono ds-text-body-xs-semibold text-ds-text-darker">+ {e.label}+ {e.exitCode != null ? (+ <span className="text-ds-text-subtler"> · exit {e.exitCode}</span>+ ) : null}+ </span>+ <span className="truncate ds-text-body-xs-medium text-ds-text-subtler">+ {[+ e.durMs ? `took ${fmtDur(e.durMs)}` : null,+ e.task != null+ ? `${noun.one.toLowerCase()} ${e.task}`+ : null,+ e.target,+ ]+ .filter(Boolean)+ .join(' · ')}+ </span>+ </span>+ </button>+ ))}+ </section>+ ))}+ </>+ );+}++function TaskList({+ tasks,+ sums,+ task,+ startedAt,+ durationMs,+ onSelect,+ errors,+ onJumpToErrors,+}: {+ tasks: TaskWindow[];+ sums: Map<number, TaskSummary>;+ task: number | null;+ startedAt: string;+ durationMs: number;+ onSelect: (n: number | null) => void;+ errors?: Map<number, TaskErrors>;+ onJumpToErrors?: (task: number, seq: number) => void;+}) {+ const noun = taskNoun(tasks);+ return (+ <ul+ className="flex flex-col gap-0.5"+ aria-label={`${noun.many} in this session`}+ >+ <li>+ <button+ type="button"+ aria-pressed={task == null}+ onClick={() => onSelect(null)}+ className={rowBtn(task == null)}+ >+ <span className="w-5 shrink-0 text-right font-mono ds-text-body-xs-medium text-ds-text-subtler">+ ∗+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="ds-text-body-xs-semibold text-ds-text-darker">+ All {noun.many.toLowerCase()}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {tasks.length} {noun.many.toLowerCase()} · {fmtDur(durationMs)}+ </span>+ </span>+ </button>+ </li>+ {tasks.map((t) => {+ const s = sums.get(t.n);+ const outs = s ? outputsLine(s.outputs, s.prsCreated) : '';+ const errs = errors?.get(t.n);+ const imgs = s?.promptImages ?? 0;+ const imgsText = `${imgs} ${imgs === 1 ? 'image' : 'images'}`;+ return (+ <li key={t.n} className="relative">+ <button+ type="button"+ aria-pressed={task === t.n}+ aria-label={`${noun.one} ${t.n}: ${t.name}${imgs ? `, ${imgsText}` : ''}`}+ title={`${t.n} · ${t.name}`}+ onClick={() => onSelect(task === t.n ? null : t.n)}+ className={rowBtn(task === t.n)}+ >+ <span className="w-5 shrink-0 text-right font-mono ds-text-body-xs-medium text-ds-text-subtler">+ {t.n}+ </span>+ <span className="flex min-w-0 flex-col gap-0.5">+ <span className="line-clamp-2 ds-text-body-xs-semibold text-ds-text-darker">+ {t.name}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {spanLabel(startedAt, t.startT, t.endT)} ·{' '}+ {fmtDur(t.endT - t.startT)} · {costLabel(s?.cost ?? 0)} ·{' '}+ {s?.calls ?? 0} calls+ </span>+ {outs ? (+ <span className="ds-text-body-xs-medium text-ds-text-subtler">+ {outs}+ </span>+ ) : null}+ {/* Room for the tags, which sit over this corner: a button+ can't hold another button. */}+ {errs || imgs ? <span aria-hidden className="h-5" /> : null}+ </span>+ </button>+ {errs || imgs ? (+ // Clicks fall through to the row, except on the error tag.+ <div className="pointer-events-none absolute bottom-2 left-9 flex items-center gap-1.5">+ {errs ? (+ <button+ type="button"+ onClick={() => onJumpToErrors?.(t.n, errs.firstSeq)}+ disabled={!onJumpToErrors}+ aria-label={`${noun.one} ${t.n}: ${errs.count} ${errs.count === 1 ? 'error' : 'errors'}. Show them`}+ title={`Show this ${noun.one.toLowerCase()}'s errors`}+ className="pointer-events-auto rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ds-border-focus"+ >+ <Badge variant="error">+ {errs.count} {errs.count === 1 ? 'error' : 'errors'}+ </Badge>+ </button>+ ) : null}+ {imgs ? (+ <Badge variant="secondary" aria-hidden>+ <ImageSquare size={12} aria-hidden />+ {imgsText}+ </Badge>+ ) : null}+ </div>+ ) : null}+ </li>+ );+ })}+ </ul>+ );+}++/** Thin bar: where in the session [startT, endT] ran. */+function SpanBar({+ startT,+ endT,+ durationMs,+}: {+ startT: number;+ endT: number;+ durationMs: number;+}) {+ const { left, width } = spanBarGeometry(startT, endT, durationMs);+ return (+ <span+ aria-hidden+ className="relative mt-1 block h-1 w-full overflow-hidden rounded-full bg-ds-gray-subtlest"+ >+ <span+ className="absolute inset-y-0 rounded-full bg-ds-brand-default"+ style={{ left: `${left * 100}%`, width: `${width * 100}%` }}+ />+ </span>+ );+}++const taskName = (tasks: TaskWindow[], n: number | null) =>+ n == null ? null : (tasks.find((t) => t.n === n)?.name ?? null);++function SubagentList({+ subs,+ tasks,+ startedAt,+ durationMs,+ onOpen,+}: {+ subs: SubagentInfo[];+ tasks: TaskWindow[];+ startedAt: string;+ durationMs: number;+ onOpen: (id: string) => void;+}) {+ const noun = taskNoun(tasks);+ return (+ <ul+ className="flex flex-col gap-0.5"+ aria-label="Subagents in this session"+ >+ {subs.map((s) => {+ const parent = taskName(tasks, s.parentTask);+ return (+ <li key={s.id}>+ <button+ type="button"+ onClick={() => onOpen(s.id)}+ aria-label={`Open ${s.label}`}+ className={rowBtn(false)}+ >+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate ds-text-body-xs-semibold text-ds-text-darker">+ {s.label}+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ {spanLabel(startedAt, s.startT, s.endT)} · {s.calls} calls ·{' '}+ {costLabel(s.cost)}+ </span>+ {s.parentTask != null && tasks.length > 1 ? (+ <span className="truncate ds-text-body-xs-medium text-ds-text-subtler">+ in {noun.one.toLowerCase()} {s.parentTask}+ {parent ? ` · ${parent}` : ''}+ </span>+ ) : null}+ <SpanBar+ startT={s.startT}+ endT={s.endT}+ durationMs={durationMs}+ />+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ );+}++/** The open subagent's facts, shared by the sidebar card and the inspector. */+export function SubagentFacts({+ sub,+ tasks,+ startedAt,+}: {+ sub: SubagentInfo;+ tasks: TaskWindow[];+ startedAt: string;+}) {+ const parent = taskName(tasks, sub.parentTask);+ const rows: [string, string][] = [+ ['When', spanLabel(startedAt, sub.startT, sub.endT)],+ ['Steps', `${sub.window.start + 1}–${sub.window.end + 1}`],+ ['Calls', `${sub.calls} · ${sub.requests} requests`],+ ['Cost', costLabel(sub.cost)],+ ['Tokens', fmtTok(sub.tokens)],+ ];+ if (sub.parentTask != null)+ rows.push([+ 'Spawned in',+ `${taskNoun(tasks).one.toLowerCase()} ${sub.parentTask}${parent ? ` · ${parent}` : ''}`,+ ]);+ return (+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 ds-text-body-xs-medium">+ {rows.map(([k, v]) => (+ <div key={k} className="contents">+ <dt className="text-ds-text-subtle">{k}</dt>+ <dd className="text-right font-mono text-ds-text-darker">{v}</dd>+ </div>+ ))}+ </dl>+ );+}++/** Inspector (right column) body for an open subagent. */+export function SubagentInspector({+ sub,+ tasks,+ startedAt,+}: {+ sub: SubagentInfo;+ tasks: TaskWindow[];+ startedAt: string;+}) {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-col">+ <span className="font-mono ds-text-body-xs-medium uppercase tracking-wide text-ds-text-subtler">+ {sub.type}+ </span>+ <span className="ds-text-body-sm-semibold text-ds-text-darker">+ {sub.label}+ </span>+ </div>+ <SubagentFacts sub={sub} tasks={tasks} startedAt={startedAt} />+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Map and timeline show only this helper's work. Play replays its+ window; ‹ › in the strip step through helpers.+ </p>+ </div>+ );+}++/** Subagent mode: "← Main session", the helper card, what it touched. */+export function SubagentSidebar({+ sub,+ total,+ tasks,+ startedAt,+ groups,+ onBack,+ onStep,+ canPrev,+ canNext,+ onCollapse,+}: {+ sub: SubagentInfo;+ total: number;+ tasks: TaskWindow[];+ startedAt: string;+ groups: TouchedGroup[];+ onBack: () => void;+ onStep: (delta: number) => void;+ canPrev: boolean;+ canNext: boolean;+ onCollapse: () => void;+}) {+ const leaves = groups.reduce((n, g) => n + g.items.length, 0);+ return (+ <SidebarFrame>+ <BackRow label="Main session" onBack={onBack} onCollapse={onCollapse} />+ <div className={cn(card, 'border-ds-brand-subtler bg-ds-brand-lightest')}>+ <span className="font-mono ds-text-body-xs-medium text-ds-text-subtle">+ Subagent {sub.index} of {total} · {sub.type}+ </span>+ <span className="ds-text-body-sm-semibold text-ds-text-darker">+ {sub.label}+ </span>+ <SubagentFacts sub={sub} tasks={tasks} startedAt={startedAt} />+ <div className="mt-1 flex gap-1.5">+ <button+ type="button"+ onClick={() => onStep(-1)}+ disabled={!canPrev}+ aria-label="Previous subagent"+ className="inline-flex items-center gap-1 rounded-md border border-ds-border-subtlest bg-ds-surface-white px-3 py-1 ds-text-body-xs-medium text-ds-text-default hover:border-ds-border-default disabled:opacity-40"+ >+ <CaretLeft size={12} /> Prev+ </button>+ <button+ type="button"+ onClick={() => onStep(1)}+ disabled={!canNext}+ aria-label="Next subagent"+ className="inline-flex items-center gap-1 rounded-md border border-ds-border-subtlest bg-ds-surface-white px-3 py-1 ds-text-body-xs-medium text-ds-text-default hover:border-ds-border-default disabled:opacity-40"+ >+ Next <CaretRight size={12} />+ </button>+ </div>+ </div>+ <div className="font-mono ds-text-body-xs-medium uppercase tracking-wide text-ds-text-subtler">+ Touched by this helper · {leaves}+ </div>+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">+ {groups.length ? (+ groups.map((g) => (+ <section key={g.id} aria-label={g.name}>+ <div className="mb-1 ds-text-body-xs-semibold text-ds-text-default">+ {g.name}{' '}+ <span className="text-ds-text-subtler">{g.items.length}</span>+ </div>+ <ul className="flex flex-col gap-0.5">+ {g.items.map((it) => (+ <li+ key={it.id}+ className="flex items-center gap-2 ds-text-body-xs-medium"+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{+ background:+ it.type === 'file' || it.type === 'dir'+ ? TOUCH_COLOR[2]+ : TOUCH_COLOR[1],+ }}+ />+ <span+ className="min-w-0 flex-1 truncate text-ds-text-default"+ title={it.name}+ >+ {it.name}+ </span>+ <span className="shrink-0 font-mono tabular-nums text-ds-text-subtle">+ {it.count}+ </span>+ </li>+ ))}+ </ul>+ </section>+ ))+ ) : (+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ This helper touched no files or tools in this scope.+ </p>+ )}+ </div>+ </SidebarFrame>+ );+}++/**+ * The one-line strip directly above the timeline tracks: the active task+ * (or the task under the playhead while playing) or the open subagent, with+ * ‹ › to step and × to clear.+ */+export function ScopeStrip({+ lead,+ name,+ meta,+ progress,+ onPrev,+ onNext,+ onClear,+ prevLabel,+ nextLabel,+ clearLabel,+ canPrev,+ canNext,+}: {+ lead: string;+ name: string;+ meta: string;+ /** 0..1 while playing, null otherwise */+ progress: number | null;+ onPrev: () => void;+ onNext: () => void;+ onClear: (() => void) | null;+ prevLabel: string;+ nextLabel: string;+ clearLabel: string;+ canPrev: boolean;+ canNext: boolean;+}) {+ return (+ <div+ role="status"+ aria-live="off"+ className="flex min-w-0 items-center gap-3 rounded-lg border border-ds-brand-subtler bg-ds-brand-lightest px-3 py-1.5"+ >+ <span className="shrink-0 font-mono ds-text-body-xs-medium text-ds-brand-default">+ {lead}+ </span>+ <span+ className="min-w-0 shrink truncate ds-text-body-xs-semibold text-ds-text-darker"+ title={name}+ >+ {name}+ </span>+ <span className="min-w-0 flex-1 truncate ds-text-body-xs-medium text-ds-text-subtle">+ {meta}+ </span>+ {progress != null ? (+ <span+ role="progressbar"+ aria-label="Progress through this window"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(progress * 100)}+ className="relative h-1 w-24 shrink-0 overflow-hidden rounded-full bg-ds-surface-white"+ >+ <span+ className="absolute inset-y-0 left-0 rounded-full bg-ds-brand-default"+ style={{ width: `${progress * 100}%` }}+ />+ </span>+ ) : null}+ <span className="flex shrink-0 items-center gap-0.5">+ <button+ type="button"+ onClick={onPrev}+ disabled={!canPrev}+ aria-label={prevLabel}+ title={prevLabel}+ className={cn(iconBtn, 'size-6 disabled:opacity-40')}+ >+ <CaretLeft size={12} />+ </button>+ <button+ type="button"+ onClick={onNext}+ disabled={!canNext}+ aria-label={nextLabel}+ title={nextLabel}+ className={cn(iconBtn, 'size-6 disabled:opacity-40')}+ >+ <CaretRight size={12} />+ </button>+ {onClear ? (+ <button+ type="button"+ onClick={onClear}+ aria-label={clearLabel}+ title={clearLabel}+ className={cn(iconBtn, 'size-6')}+ >+ <X size={12} />+ </button>+ ) : null}+ </span>+ </div>+ );+}diff --git a/viewer/src/explorer/SessionTimeline.tsx b/viewer/src/explorer/SessionTimeline.tsxnew file mode 100644index 0000000..c0521ca--- /dev/null+++ b/viewer/src/explorer/SessionTimeline.tsx@@ -0,0 +1,458 @@+import {+ useEffect,+ useMemo,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+} from 'react';+import { parseAsStringEnum, useQueryState } from 'nuqs';+import type { SessionMap } from '@/core/schema';+import { cn } from '@/lib/utils';+import { resolveCssColor } from '@/core/eventColors';+import type { Category } from '@/core/sessionLayout';+import { llmTokens } from '@/core/sessionMapModel';+import {+ sessionTasks,+ taskNoun,+ type LaneKey,+ type TaskWindow,+} from '@/core/sessionScope';+import {+ TIMELINE_AXES,+ contextSeries,+ indexAtFraction,+ timePositions,+ type TimelineAxis,+} from '@/core/sessionSignals';+import {+ TL,+ buildLanes,+ drawAgentRows,+ drawAxis,+ drawContext,+ drawEvents,+ drawLaneFrames,+ drawPin,+ drawPlayhead,+ drawShade,+ drawTasks,+ laneSnap,+ type DrawEnv,+ type Lane,+} from '@/core/timelineDraw';+import { TimelineTooltip } from './TimelineTooltip';++/** The timeline's x axis (`axis` URL param): steps or wall-clock time. */+export function useTimelineAxis() {+ return useQueryState(+ 'axis',+ parseAsStringEnum<TimelineAxis>([...TIMELINE_AXES]).withDefault('steps')+ );+}++interface Props {+ map: SessionMap;+ p: number;+ cumCost: Float64Array;+ ordinals: Map<string, number>;+ onSeek: (index: number) => void;+ /** the lanes to draw (`timelineLanes`) */+ lanes: ReadonlySet<LaneKey>;+ /** the dock's selected categories: bright on the Events bar */+ selected: ReadonlySet<Category>;+ /** selected task, highlighted on the task lane */+ task?: number | null;+ /** clicking a task bracket selects that task (click again to clear) */+ onSelectTask?: (n: number) => void;+ /** inclusive event window to keep bright; everything outside it is shaded+ * (an open subagent's [first, last] window on the whole-session timeline) */+ shade?: { start: number; end: number } | null;+ /** one row per subagent, in start order ("n · type") */+ subRows: readonly { id: string; label: string }[];+ /** the Subagents row is expanded into `subRows` */+ subsOpen: boolean;+ onToggleSubs: () => void;+ /** a subagent row's label opens that subagent's view */+ onOpenSubagent?: (id: string) => void;+ /** the open subagent (its row label is highlighted) */+ activeAgent?: string | null;+ /** the pinned event: a dashed rule and an emphasised mark */+ pinned?: number | null;+ /** an event to emphasise (hovered in the events list) */+ highlight?: number | null;+}++interface Hover {+ i: number;+ x: number;+ /** y in the non-scrolling wrapper's coordinates, where the tooltip is+ * drawn so the lane scrollport cannot clip it */+ vy: number;+}++/** Bumps whenever the theme class / attribute on <html> changes, so the+ * canvas re-resolves its CSS variables. */+function useThemeVersion(): number {+ const [v, setV] = useState(0);+ useEffect(() => {+ const mo = new MutationObserver(() => setV((x) => x + 1));+ mo.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class', 'data-theme', 'style'],+ });+ return () => mo.disconnect();+ }, []);+ return v;+}++/** Width of an element, tracked with a ResizeObserver. */+function useWidth(ref: React.RefObject<HTMLElement | null>): number {+ const [width, setWidth] = useState(0);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const ro = new ResizeObserver((entries) => {+ setWidth(Math.floor(entries[0]?.contentRect.width ?? 0));+ });+ ro.observe(el);+ return () => ro.disconnect();+ }, [ref]);+ return width;+}++/** Scales the timeline draws against (largest prompt, delay, request). */+function useScales(map: SessionMap) {+ return useMemo(() => {+ let maxCost = 1e-9;+ let maxTok = 1;+ let maxChars = 1;+ let maxDelayMs = 1000;+ for (const e of map.events) {+ if (e.kind === 'user') maxChars = Math.max(maxChars, e.chars ?? 0);+ if (e.kind === 'delay') maxDelayMs = Math.max(maxDelayMs, e.ms ?? 0);+ if (e.kind !== 'llm') continue;+ maxCost = Math.max(maxCost, e.cost ?? 0);+ maxTok = Math.max(maxTok, llmTokens(e));+ }+ return { maxCost, maxTok, maxChars, maxDelayMs, ctx: contextSeries(map) };+ }, [map]);+}++const hasHtmlLabel = (l: Lane) => l.key === 'subs' || l.key === 'sub';++/**+ * The canvas timeline: task brackets, the Events bar (every event, the+ * selected categories bright), the optional context lane, agent rows and the+ * playhead. Drag to scrub,+ * hover for details. It grows to its content; the dock scrolls it.+ */+export function SessionTimeline({+ map,+ p,+ cumCost,+ ordinals,+ onSeek,+ lanes: visible,+ selected,+ task = null,+ onSelectTask,+ shade = null,+ subRows,+ subsOpen,+ onToggleSubs,+ onOpenSubagent,+ activeAgent = null,+ pinned = null,+ highlight = null,+}: Props) {+ /** full "n · name" of the task bracket under the pointer (canvas title) */+ const [taskTip, setTaskTip] = useState<string | null>(null);+ const taskWindows = useMemo<TaskWindow[]>(+ () => sessionTasks(map).tasks,+ [map]+ );+ const wrapRef = useRef<HTMLDivElement>(null);+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const outerRef = useRef<HTMLDivElement>(null);+ const dragging = useRef(false);+ const width = useWidth(wrapRef);+ const [hover, setHover] = useState<Hover | null>(null);+ const themeVersion = useThemeVersion();+ const [axis] = useTimelineAxis();++ const events = map.events;+ const N = events.length;+ const noun = taskNoun(taskWindows);+ const { lanes, bottom } = useMemo(+ () => buildLanes(visible, subRows, subsOpen, noun.many),+ [visible, subsOpen, subRows, noun.many]+ );+ const height = bottom + TL.axisH;+ const pos = useMemo(() => timePositions(events, axis), [events, axis]);+ const scales = useScales(map);+ const plotW = Math.max(1, width - TL.labelW - TL.right);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || !width || !N) return;+ const dpr = window.devicePixelRatio || 1;+ canvas.width = Math.round(width * dpr);+ canvas.height = Math.round(height * dpr);+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ const cache = new Map<string, string>();+ const family = getComputedStyle(canvas).fontFamily || 'sans-serif';+ const g: DrawEnv = {+ ctx,+ col: (v) => {+ let c = cache.get(v);+ if (c == null) {+ c = resolveCssColor(canvas, v);+ cache.set(v, c);+ }+ return c;+ },+ x: (i) => TL.labelW + plotW * (pos[i] ?? 0),+ cw: Math.max(1.2, axis === 'steps' ? plotW / N : 2),+ width,+ plotW,+ bottom,+ sans: `10.5px ${family}`,+ mono: '9.5px ui-monospace, SFMono-Regular, Menlo, monospace',+ events,+ };+ const L = new Map(lanes.map((l) => [l.key, l]));++ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, width, height);+ ctx.font = g.sans;+ ctx.textBaseline = 'middle';++ drawLaneFrames(g, lanes, hasHtmlLabel);+ const TK = L.get('tasks');+ if (TK) drawTasks(g, TK, taskWindows, task, map.session.startedAt);+ const C = L.get('ctx');+ if (C) drawContext(g, C, scales.ctx);+ const emph = new Set<number>();+ if (pinned != null) emph.add(pinned);+ if (highlight != null) emph.add(highlight);+ const E = L.get('events');+ if (E) drawEvents(g, E, selected, scales, emph);+ drawAgentRows(g, lanes);+ if (shade) drawShade(g, shade);+ drawPlayhead(g, p);+ if (pinned != null && pinned < N) drawPin(g, pinned);+ drawAxis(g, pos, map.session.startedAt, height);+ }, [+ width,+ height,+ plotW,+ N,+ p,+ pos,+ axis,+ lanes,+ bottom,+ events,+ scales,+ selected,+ map.session.startedAt,+ taskWindows,+ task,+ themeVersion,+ shade,+ pinned,+ highlight,+ ]);++ const idxFromX = (clientX: number) => {+ const r = canvasRef.current?.getBoundingClientRect();+ if (!r || N <= 1) return 0;+ const f = Math.max(0, Math.min(1, (clientX - r.left - TL.labelW) / plotW));+ return indexAtFraction(pos, f);+ };++ const taskUnder = (yy: number, i: number) => {+ const TK = lanes.find((l) => l.key === 'tasks');+ return TK && yy >= TK.y && yy <= TK.y + TK.h+ ? taskWindows.find((t) => i >= t.start && i <= t.end)+ : undefined;+ };++ const onPointerDown = (e: ReactPointerEvent<HTMLCanvasElement>) => {+ if (!N) return;+ const yy = e.clientY - e.currentTarget.getBoundingClientRect().top;+ const w = onSelectTask ? taskUnder(yy, idxFromX(e.clientX)) : undefined;+ if (w && onSelectTask) {+ onSelectTask(w.n);+ return;+ }+ dragging.current = true;+ e.currentTarget.setPointerCapture(e.pointerId);+ setHover(null);+ onSeek(idxFromX(e.clientX));+ };++ const onPointerMove = (e: ReactPointerEvent<HTMLCanvasElement>) => {+ if (!N) return;+ if (dragging.current) {+ onSeek(idxFromX(e.clientX));+ return;+ }+ const r = e.currentTarget.getBoundingClientRect();+ const yy = e.clientY - r.top;+ const raw = idxFromX(e.clientX);+ const overTask = taskUnder(yy, raw);+ setTaskTip(+ overTask ? `${noun.one} ${overTask.n} · ${overTask.name}` : null+ );+ const ln = lanes.find((l) => yy >= l.y - 2 && yy <= l.y + l.h + 2);+ // The Events bar prefers a selected event near the pointer, else the+ // (dimmed) event right under it, so every mark has a tooltip.+ const i =+ snapIndex(events, raw, ln ? laneSnap(ln, selected) : undefined) ??+ (ln?.key === 'events' ? raw : null);+ if (i == null) {+ setHover(null);+ return;+ }+ const outerTop = outerRef.current?.getBoundingClientRect().top ?? r.top;+ setHover({ i, x: e.clientX - r.left, vy: yy + r.top - outerTop });+ };++ const endDrag = () => {+ dragging.current = false;+ };++ return (+ // The tooltip is drawn in this relative wrapper, outside the lanes'+ // scrollport, so it is never clipped by it.+ <div ref={outerRef} className="relative flex min-h-0 flex-col">+ <div className="min-h-0 overflow-y-auto overscroll-contain">+ <div ref={wrapRef} className="relative w-full">+ <canvas+ ref={canvasRef}+ className="block w-full cursor-ew-resize touch-none"+ style={{ height }}+ aria-label="Timeline: drag to scrub, hover for details"+ title={taskTip ?? undefined}+ role="img"+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={endDrag}+ onPointerCancel={endDrag}+ onPointerLeave={() => {+ setHover(null);+ setTaskTip(null);+ }}+ />+ <AgentLaneLabels+ lanes={lanes}+ subsOpen={subsOpen}+ onToggleSubs={onToggleSubs}+ onOpenSubagent={onOpenSubagent}+ activeAgent={activeAgent}+ />+ {taskWindows.length > 1 ? (+ <ul className="sr-only" aria-label={`${noun.many} on the timeline`}>+ {taskWindows.map((w) => (+ <li key={w.n}>+ {noun.one} {w.n}: {w.name}+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ </div>+ {hover && events[hover.i] ? (+ <TimelineTooltip+ map={map}+ i={hover.i}+ cumCost={cumCost}+ ordinals={ordinals}+ left={Math.max(4, Math.min(hover.x + 12, width - 264))}+ top={hover.vy}+ />+ ) : null}+ </div>+ );+}++/** Nearest event to `i` (within a small window) that `want` accepts; the+ * raw index when the lane has no snap rule, null when nothing is near. */+function snapIndex(+ events: SessionMap['events'],+ i: number,+ want: ((e: SessionMap['events'][number]) => boolean) | undefined+): number | null {+ if (!want) return i;+ const N = events.length;+ const span = Math.max(3, Math.ceil(N / 120));+ let best = -1;+ let bd = Infinity;+ for (let j = Math.max(0, i - span); j <= Math.min(N - 1, i + span); j++) {+ if (want(events[j]) && Math.abs(j - i) < bd) {+ bd = Math.abs(j - i);+ best = j;+ }+ }+ return best < 0 ? null : best;+}++/** HTML labels over the canvas for the agent rows that act on click: the+ * Subagents row expands / collapses, a subagent row opens its view. */+function AgentLaneLabels({+ lanes,+ subsOpen,+ onToggleSubs,+ onOpenSubagent,+ activeAgent,+}: {+ lanes: readonly Lane[];+ subsOpen: boolean;+ onToggleSubs: () => void;+ onOpenSubagent?: (id: string) => void;+ activeAgent: string | null;+}) {+ return (+ <>+ {lanes.filter(hasHtmlLabel).map((l) =>+ l.key === 'subs' ? (+ <button+ key={l.id}+ type="button"+ aria-expanded={subsOpen}+ onClick={onToggleSubs}+ title={+ subsOpen+ ? 'Collapse to one combined row'+ : 'Expand: one row per subagent'+ }+ className="absolute left-0 flex items-center gap-1 truncate rounded px-1 text-left text-[10.5px] font-semibold leading-none text-ds-text-default hover:bg-ds-gray-subtlest"+ style={{ top: l.y, height: l.h, width: TL.labelW - 6 }}+ >+ <span aria-hidden>{subsOpen ? '▾' : '▸'}</span>+ {l.label}+ </button>+ ) : (+ <button+ key={l.id}+ type="button"+ onClick={() => onOpenSubagent?.(l.id)}+ disabled={!onOpenSubagent}+ title={`Open subagent ${l.label}`}+ className={cn(+ 'absolute left-0 truncate rounded pl-3 pr-1 text-left text-[10px] leading-none hover:bg-ds-gray-subtlest disabled:cursor-default',+ activeAgent === l.id+ ? 'font-semibold text-ds-brand-default'+ : 'text-ds-text-subtle'+ )}+ style={{ top: l.y, height: l.h, width: TL.labelW - 6 }}+ >+ {l.label}+ </button>+ )+ )}+ </>+ );+}diff --git a/viewer/src/explorer/SidePanels.tsx b/viewer/src/explorer/SidePanels.tsxnew file mode 100644index 0000000..8052460--- /dev/null+++ b/viewer/src/explorer/SidePanels.tsx@@ -0,0 +1,1419 @@+import { useMemo, type ReactNode } from 'react';+import { parseAsStringEnum, useQueryState } from 'nuqs';+import type { SessionMap, SessionMapEvent } from '@/core/schema';+import { X } from '@phosphor-icons/react';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import {+ CAT_LABEL,+ ERROR_SOURCES,+ ERROR_SOURCE_LABEL,+ agentLabel,+ catLabel,+ clockAt,+ countersAt,+ describeEvent,+ errClassLabel,+ errClassOf,+ errSource,+ fileCoverage,+ fmtDur,+ fmtTok,+ fmtUsd,+ isOutputEvent,+ type ErrorSource,+ type ReviewMetrics,+ type ToolCategory,+} from '@/core/sessionMapModel';+import {+ detailRows,+ signalsAt,+ type DetailRow,+ type SessionSignals,+} from '@/core/sessionSignals';+import {+ CATEGORY_COLOR,+ ERROR_COLOR,+ ERROR_SOURCE_COLOR,+ PANEL_BAR_COLOR,+ catColor,+ kindMeta,+ kindStyle,+} from '@/core/eventColors';+import {+ summarizeEvents,+ taskNoun,+ type ModelUsage,+ type TaskSummary,+ type TaskWindow,+} from '@/core/sessionScope';+import { promptImageTurns, type PromptImageTurn } from '@/core/promptImages';+import { HookDetail } from './HookDetail';+import { PromptImages } from './PromptImages';+import { ReviewLoopBlock } from './ReviewLoopBlock';+import {+ CATEGORIES,+ CATEGORY_LABEL,+ DEFAULT_CATEGORIES,+ categoryMatches,+ costLabel,+ detailsTitle,+ lastPicked,+ matchesAnyCategory,+ narrowsView,+ outcomeParts,+ promptLine,+ type Category,+} from '@/core/sessionLayout';++// Signals live in the sidebar's Insights tab (`InsightsPanel`);+// the right column keeps the inspector (Details), Event and Activity.+const PANEL_TABS = ['task', 'event', 'activity', 'review'] as const;+type PanelTab = (typeof PANEL_TABS)[number];+const PANEL_TAB_LABEL: Record<PanelTab, string> = {+ task: 'Details',+ event: 'Event',+ activity: 'Activity',+ review: 'Review',+};+/** Review has a tab of its own because the block in Details sits under the+ * Produced list, and a session with a long list pushes it past the fold. */+const ACCENT_TAB: PanelTab = 'review';++const FEED_LEN = 14;+/** `cat:<ToolCategory>`, one filter value per category:+ * clicking a row in the CategoriesCard sets it. */+const CAT_KEYS = Object.keys(CAT_LABEL) as ToolCategory[];+const CAT_FILTER_VALUES = CAT_KEYS.map((c) => `cat:${c}` as const);+const FEED_FILTER_VALUES = ['all', ...CAT_FILTER_VALUES] as const;+type FeedFilter = (typeof FEED_FILTER_VALUES)[number];+const isCatFilter = (f: FeedFilter): f is `cat:${ToolCategory}` =>+ f.startsWith('cat:');+/** What Recent activity lists: the dock chips' categories when they narrow+ * the view (the default Prompts + Errors, or every chip, lists everything),+ * further narrowed to a picked tool category. */+const feedWant =+ (filter: FeedFilter, selected: ReadonlySet<Category>) =>+ (e: SessionMapEvent): boolean =>+ (!narrowsView(selected) || matchesAnyCategory(e, selected)) &&+ (!isCatFilter(filter) || e.cat === filter.slice(4));++interface Props {+ map: SessionMap;+ /** the unfiltered map: pasted-image turns are numbered over the whole+ * session, which a scoped `map` no longer has */+ fullMap?: SessionMap;+ p: number;+ ordinals: Map<string, number>;+ cumCost: Float64Array;+ review: ReviewMetrics;+ signals: SessionSignals;+ onSeek: (index: number) => void;+ onJumpSource: (source: ErrorSource) => void;+ /** Task windows of the session, and the selected one. Their+ * offsets are from `sessionStart` (the full session), not from the scoped+ * map's rebased start. */+ tasks?: TaskWindow[];+ sessionStart?: string;+ task?: number | null;+ onSelectTask?: (n: number) => void;+ /** Per-model usage of the current scope, and the selected model */+ models?: ModelUsage[];+ model?: string | null;+ onSelectModel?: (model: string) => void;+ /** replaces the task/session detail at the top of Details (the open+ * subagent's card) */+ inspector?: ReactNode;+ /** a model filter is narrowing the map (no task picked) */+ scoped?: boolean;+ /** the dock's category chips (Recent activity follows them) */+ selected?: ReadonlySet<Category>;+ /** the chips' click order (`useEventCategories`), for "the last chip" */+ picks?: readonly Category[];+ /** the review comment whose causal path the map is lighting */+ reviewPath?: readonly number[] | null;+ onReviewPath?: (seqs: readonly number[] | null) => void;+}++/** No chip selection passed: Recent activity lists everything. */+const DEFAULT_SELECTION: ReadonlySet<Category> = new Set(DEFAULT_CATEGORIES);+const NO_PICKS: readonly Category[] = [];++/**+ * The right-hand column next to the map: Details (the inspector for the+ * selected task / open subagent / whole session, and what the scope+ * produced), Event (the event at the playhead) and Activity (recent events).+ * The Signals cards live in the sidebar's Insights tab (`InsightsPanel`).+ */+export function SidePanels({+ map,+ p,+ ordinals,+ cumCost,+ onSeek,+ fullMap,+ tasks = [],+ sessionStart,+ task = null,+ onSelectTask,+ inspector,+ scoped,+ selected = DEFAULT_SELECTION,+ picks = NO_PICKS,+ reviewPath = null,+ onReviewPath,+}: Omit<+ Props,+ 'review' | 'signals' | 'onJumpSource' | 'models' | 'model' | 'onSelectModel'+>) {+ const [tab, setTab] = useQueryState(+ 'panel',+ parseAsStringEnum<PanelTab>([...PANEL_TABS]).withDefault('task')+ );+ return (+ <aside className="flex h-full min-h-0 min-w-0 flex-col gap-3">+ <div+ role="tablist"+ aria-label="Session details"+ className="flex shrink-0 gap-0.5 rounded-lg border border-ds-border-subtlest bg-ds-surface-white p-[3px]"+ >+ {PANEL_TABS.map((t) => (+ <button+ key={t}+ type="button"+ role="tab"+ aria-selected={tab === t}+ onClick={() => void setTab(t)}+ className={cn(+ 'flex-1 rounded-md px-2 py-1 ds-text-body-xs-medium transition-colors',+ tab === t+ ? 'bg-ds-brand-lightest text-ds-brand-default'+ : t === ACCENT_TAB+ ? // Unselected but not quiet: the one tab here that is an+ // offer rather than a view of the session. `motion-safe`+ // because a loop that never ends is exactly what someone+ // who asked for less motion was asking to be spared.+ 'text-ds-brand-default ring-1 ring-inset ring-ds-brand-subtler hover:bg-ds-brand-lightest motion-safe:animate-pulse-glow'+ : 'text-ds-text-subtle hover:text-ds-text-default'+ )}+ >+ {PANEL_TAB_LABEL[t]}+ </button>+ ))}+ </div>+ {tab === 'task' ? (+ <div className="flex min-h-0 flex-1 flex-col gap-3">+ <TaskCard+ map={map}+ fullMap={fullMap}+ sessionStart={sessionStart ?? map.session.startedAt}+ tasks={tasks}+ task={task}+ onSelectTask={onSelectTask}+ onSeek={onSeek}+ inspector={inspector}+ scoped={scoped}+ reviewPath={reviewPath}+ onReviewPath={onReviewPath}+ />+ <UniqueEntitiesCard map={map} selected={selected} picks={picks} />+ </div>+ ) : tab === 'review' ? (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <ReviewLoopBlock+ map={map}+ src="review-tab"+ path={reviewPath}+ onPath={onReviewPath}+ onSeek={onSeek}+ />+ </div>+ ) : (+ // Event / Activity scroll inside the column, never the page.+ <div className="min-h-0 flex-1 overflow-y-auto">+ {tab === 'event' ? (+ <EventCard+ map={map}+ p={p}+ ordinals={ordinals}+ cumCost={cumCost}+ sessionId={(fullMap ?? map).session.id}+ onSeek={onSeek}+ />+ ) : (+ <FeedCard+ map={map}+ p={p}+ ordinals={ordinals}+ onSeek={onSeek}+ selected={selected}+ />+ )}+ </div>+ )}+ </aside>+ );+}++/**+ * The sidebar's Insights tab: counters at the playhead, signals, tool+ * categories, agents, models and review (the old Signals tab, moved).+ */+export function InsightsPanel({+ map,+ p,+ ordinals,+ review,+ signals,+ onJumpSource,+ models = [],+ model = null,+ onSelectModel,+}: Pick<+ Props,+ | 'map'+ | 'p'+ | 'ordinals'+ | 'review'+ | 'signals'+ | 'onJumpSource'+ | 'models'+ | 'model'+ | 'onSelectModel'+>) {+ const at = useMemo(() => signalsAt(map.events, p), [map.events, p]);+ return (+ <div className="flex min-w-0 flex-col gap-3">+ <CountersCard map={map} p={p} ctxNow={at.ctxNow} />+ <SignalsCard at={at} session={signals} onJumpSource={onJumpSource} />+ <CategoriesCard map={map} />+ <AgentsCard map={map} ordinals={ordinals} />+ <ModelsCard models={models} model={model} onSelect={onSelectModel} />+ <ReviewCard review={review} signals={signals} />+ </div>+ );+}++function SideCard({+ title,+ aside,+ children,+ collapsible = false,+ defaultOpen = true,+ className,+}: {+ title: string;+ aside?: ReactNode;+ children: ReactNode;+ /** render as a <details> section that can be folded away */+ collapsible?: boolean;+ defaultOpen?: boolean;+ className?: string;+}) {+ if (collapsible) {+ return (+ <details+ open={defaultOpen}+ className="group rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-3"+ >+ <summary className="flex cursor-pointer list-none items-center justify-between gap-2 ds-text-body-xs-semibold text-ds-text-subtle group-open:mb-2 [&::-webkit-details-marker]:hidden">+ <span>+ <span+ aria-hidden+ className="mr-1 inline-block group-open:rotate-90"+ >+ ▸+ </span>+ {title}+ </span>+ {aside}+ </summary>+ {children}+ </details>+ );+ }+ return (+ <section+ className={cn(+ 'rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-3',+ className+ )}+ >+ <div className="mb-2 flex shrink-0 items-center justify-between gap-2 ds-text-body-xs-semibold text-ds-text-subtle">+ <span>{title}</span>+ {aside}+ </div>+ {children}+ </section>+ );+}++/** Details tab: the inspector (the selected task's detail, an open+ * subagent's card, or the whole session) and what the current scope+ * produced. The task list itself lives in the sidebar's Tasks tab. Fills+ * the right column; the Produced list scrolls inside the card. */+function TaskCard({+ map,+ fullMap,+ sessionStart,+ tasks,+ task,+ onSelectTask,+ onSeek,+ inspector,+ scoped,+ reviewPath,+ onReviewPath,+}: {+ map: SessionMap;+ fullMap?: SessionMap;+ sessionStart: string;+ tasks: TaskWindow[];+ task: number | null;+ onSelectTask?: (n: number) => void;+ onSeek: (i: number) => void;+ inspector?: ReactNode;+ scoped?: boolean;+ reviewPath?: readonly number[] | null;+ onReviewPath?: (seqs: readonly number[] | null) => void;+}) {+ const summary = useMemo(+ () =>+ summarizeEvents(+ map.events,+ map.events.map((e) => e.model ?? '')+ ),+ [map.events]+ );+ const selected = task != null ? tasks.find((t) => t.n === task) : undefined;+ const noun = taskNoun(tasks);+ const imageTurns = useMemo(+ () => (selected ? promptImageTurns(fullMap ?? map, selected.n) : []),+ [fullMap, map, selected]+ );+ let detail: ReactNode;+ if (inspector) detail = inspector;+ else if (selected)+ detail = (+ <TaskDetail+ task={selected}+ summary={summary}+ sessionStart={sessionStart}+ onSelectTask={onSelectTask}+ sessionId={(fullMap ?? map).session.id}+ imageTurns={imageTurns}+ noun={noun}+ />+ );+ else+ detail = (+ <SessionSummary+ map={map}+ summary={summary}+ sessionStart={sessionStart}+ taskCount={tasks.length}+ noun={noun}+ />+ );+ return (+ <SideCard+ title={detailsTitle({+ inspector: !!inspector,+ selected,+ taskCount: tasks.length,+ noun,+ scoped: !!scoped,+ })}+ aside={selected && !inspector ? <span>{selected.source}</span> : null}+ className="flex min-h-0 flex-1 flex-col"+ >+ {/* One scroll region, not several sections competing for a fixed+ * height, which on a short window would clip every one of them. */}+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ {detail}+ <OutcomeLine map={map} />+ <ProducedList+ map={map}+ onSeek={onSeek}+ reviewPath={reviewPath}+ onReviewPath={onReviewPath}+ />+ </div>+ </SideCard>+ );+}++/** Categories with a natural per-name identity worth deduplicating here.+ * Edits/Exploration/Tools are left out on purpose: they're one row per+ * file or per raw call, so a unique list would run to hundreds of rows+ * instead of the small, scannable set this card is for. */+const UNIQUE_CATEGORIES: readonly Category[] = [+ 'error',+ 'mcp',+ 'skill',+ 'model',+];++/** The one thing an event in `cat` is named after, for grouping -- null+ * when the event doesn't actually carry that identity (e.g. an MCP-category+ * event with no tool name). */+function entityOf(+ e: SessionMapEvent,+ cat: Category+): { key: string; label: string } | null {+ switch (cat) {+ case 'error': {+ const cls = errClassOf(e);+ return { key: `${errSource(e)}/${cls}`, label: errClassLabel(cls) };+ }+ case 'mcp':+ return e.tool+ ? { key: `${e.server ?? ''}/${e.tool}`, label: e.tool }+ : null;+ case 'skill':+ return e.skill ? { key: e.skill, label: e.skill } : null;+ case 'model':+ return e.model ? { key: e.model, label: e.model } : null;+ default:+ return null;+ }+}++/** Details tab, below the task/session card: the most recently clicked+ * chip's unique names, each with how many times it occurred -- the same+ * identities the round map's leaves dedupe to, as a scannable list instead+ * of a graph. Only one chip, not every chip on at once: the most recently+ * clicked of the eligible ones (`picks` is the click order), so turning on+ * e.g. Tools after MCP keeps showing MCP. */+function UniqueEntitiesCard({+ map,+ selected,+ picks,+}: {+ map: SessionMap;+ selected: ReadonlySet<Category>;+ picks: readonly Category[];+}) {+ const cat = lastPicked(picks, selected, UNIQUE_CATEGORIES);+ const rows = useMemo(() => {+ if (!cat) return [];+ const counts = new Map<string, { label: string; n: number }>();+ for (const e of map.events) {+ if (!categoryMatches(e, cat)) continue;+ const entity = entityOf(e, cat);+ if (!entity) continue;+ const cur = counts.get(entity.key);+ if (cur) cur.n++;+ else counts.set(entity.key, { label: entity.label, n: 1 });+ }+ return [...counts.values()].sort((a, b) => b.n - a.n);+ }, [map.events, cat]);+ if (!cat || !rows.length) return null;+ return (+ <SideCard+ title="Unique activity"+ className="shrink-0"+ aside={+ <span className="flex items-center gap-1.5 normal-case text-ds-text-subtle">+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{ background: CATEGORY_COLOR[cat] }}+ />+ {CATEGORY_LABEL[cat]} · {rows.length} unique+ </span>+ }+ >+ <ul className="flex flex-col gap-0.5">+ {rows.map((r) => (+ <li+ key={r.label}+ className="flex items-center justify-between gap-2 ds-text-body-xs-medium text-ds-text-default"+ >+ <span className="min-w-0 truncate font-mono">{r.label}</span>+ {r.n > 1 ? (+ <span+ className="shrink-0 font-mono text-[10.5px] tabular-nums"+ style={{ color: CATEGORY_COLOR[cat] }}+ >+ ×{r.n}+ </span>+ ) : null}+ </li>+ ))}+ </ul>+ </SideCard>+ );+}++/** What the scope produced, on one line. Was on the header (moved into+ * Details so the header stays one line and the map gets the vertical+ * space back). */+function OutcomeLine({ map }: { map: SessionMap }) {+ const parts = outcomeParts(map);+ const truncated = map.session.truncated;+ if (!parts.length && !truncated) return null;+ const text = parts.join(' · ');+ // A brand-tinted callout, not a muted footnote: the outcome is the one+ // line a reader scans Details for. It wraps rather than truncating, so+ // every part (tasks, PRs, tickets...) stays readable.+ return (+ <div className="mt-1 shrink-0 rounded-lg border border-ds-brand-subtler bg-ds-brand-lightest px-2.5 py-2">+ {parts.length ? (+ <>+ <p className="font-mono text-[10.5px] font-semibold uppercase tracking-wide text-ds-brand-default">+ Outcome+ </p>+ <p className="mt-0.5 ds-text-body-sm-semibold text-ds-text-darker">+ {text}+ </p>+ </>+ ) : null}+ {truncated ? (+ <p className="mt-1 ds-text-body-xs-medium text-ds-warning-default">+ This session was long, so the map stops at its first 20,000 events.+ </p>+ ) : null}+ </div>+ );+}++function DetailRows({ rows }: { rows: [string, string][] }) {+ return (+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 ds-text-body-xs-medium">+ {rows.map(([k, v]) => (+ <div key={k} className="contents">+ <dt className="text-ds-text-subtle">{k}</dt>+ <dd className="text-right font-mono text-ds-text-darker">{v}</dd>+ </div>+ ))}+ </dl>+ );+}++/** The selected task: its name, span and what it cost. */+function TaskDetail({+ task,+ summary,+ sessionStart,+ onSelectTask,+ sessionId,+ imageTurns,+ noun,+}: {+ task: TaskWindow;+ summary: TaskSummary;+ sessionStart: string;+ onSelectTask?: (n: number) => void;+ sessionId: string;+ imageTurns: PromptImageTurn[];+ noun: { many: string };+}) {+ return (+ <div className="flex flex-col gap-2">+ <div className="ds-text-body-xs-semibold text-ds-text-darker">+ {task.name}+ </div>+ <DetailRows+ rows={[+ [+ 'Span',+ `${clockAt(sessionStart, task.startT).slice(0, 5)}–${clockAt(sessionStart, task.endT).slice(0, 5)} · ${fmtDur(task.endT - task.startT)}`,+ ],+ ['Prompt', promptLine(summary)],+ ['Requests', String(summary.requests)],+ ['Tool calls', String(summary.calls)],+ ['Cost', fmtUsd(summary.cost)],+ ['Tokens', fmtTok(summary.tokens)],+ ['Agents', String(summary.agents.length)],+ ['Models', summary.models.join(', ') || '-'],+ ]}+ />+ <PromptImages sessionId={sessionId} turns={imageTurns} />+ {onSelectTask ? (+ <button+ type="button"+ onClick={() => onSelectTask(task.n)}+ className="self-start ds-text-body-xs-medium text-ds-text-subtle underline-offset-2 hover:underline"+ >+ Show all {noun.many.toLowerCase()}+ </button>+ ) : null}+ </div>+ );+}++/** No task picked: the whole (possibly filtered) session. */+function SessionSummary({+ map,+ summary,+ sessionStart,+ taskCount,+ noun,+}: {+ map: SessionMap;+ summary: TaskSummary;+ sessionStart: string;+ taskCount: number;+ noun: { one: string; many: string };+}) {+ // Distinct files by their strongest touch (the old header coverage row).+ const files = useMemo(() => fileCoverage(map), [map]);+ return (+ <div className="flex flex-col gap-2">+ <DetailRows+ rows={[+ [+ 'Span',+ `${clockAt(sessionStart, 0).slice(0, 5)}–${clockAt(sessionStart, map.session.durationMs).slice(0, 5)} · ${fmtDur(map.session.durationMs)}`,+ ],+ [noun.many, String(taskCount)],+ ['Requests', String(summary.requests)],+ ['Tool calls', String(summary.calls)],+ ['Cost', costLabel(summary.cost)],+ ['Tokens', fmtTok(summary.tokens)],+ ['Agents', String(summary.agents.length)],+ [+ 'Files',+ `${files.edited} edited · ${files.read} read · ${files.seen} seen`,+ ],+ ]}+ />+ {taskCount > 1 ? (+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Pick a {noun.one.toLowerCase()} in the sidebar or on the timeline to+ narrow the map and timeline. Hover any node or mark for details.+ </p>+ ) : null}+ </div>+ );+}++/** What the current scope produced, in the Details card's scroll region. */+function ProducedList({+ map,+ onSeek,+ reviewPath = null,+ onReviewPath,+}: {+ map: SessionMap;+ onSeek: (i: number) => void;+ reviewPath?: readonly number[] | null;+ onReviewPath?: (seqs: readonly number[] | null) => void;+}) {+ const produced = useMemo(+ () =>+ map.events.map((e, i) => ({ e, i })).filter(({ e }) => isOutputEvent(e)),+ [map.events]+ );+ return (+ <>+ <div className="mb-1 mt-3 flex shrink-0 items-center justify-between ds-text-body-xs-semibold text-ds-text-subtle">+ <span>Produced</span>+ <span>{produced.length}</span>+ </div>+ {produced.length ? (+ <ul className="flex shrink-0 flex-col gap-0.5">+ {produced.map(({ e, i }) => (+ <ProducedRow key={i} map={map} e={e} onSeek={() => onSeek(i)} />+ ))}+ </ul>+ ) : (+ <p className="ds-text-body-xs-medium text-ds-text-subtle">+ Nothing produced in this scope.+ </p>+ )}+ {/* Below the list, never over it: what the session produced is a local+ * answer and stays one, whether or not it found anything. */}+ <ReviewLoopBlock+ map={map}+ path={reviewPath}+ onPath={onReviewPath}+ onSeek={onSeek}+ />+ </>+ );+}++function ProducedRow({+ map,+ e,+ onSeek,+}: {+ map: SessionMap;+ e: SessionMapEvent;+ onSeek: () => void;+}) {+ const K = kindMeta(e.vcs?.action === 'pr_create' ? 'pr_create' : e.kind);+ const D = describeEvent(map, e);+ return (+ <li>+ <button+ type="button"+ onClick={onSeek}+ className="flex w-full items-center gap-2 rounded px-1 py-0.5 text-left ds-text-body-xs-medium hover:bg-ds-gray-subtlest"+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rotate-45 rounded-[1px]"+ style={{ background: K.color }}+ />+ <span className="min-w-0 flex-1 truncate text-ds-text-default">+ {D.title}+ </span>+ <span className="shrink-0 font-mono text-ds-text-subtle">+ {clockAt(map.session.startedAt, e.t).slice(0, 5)}+ </span>+ </button>+ </li>+ );+}++/** Per-model cost share; clicking a model scopes the explorer to it. */+function ModelsCard({+ models,+ model,+ onSelect,+}: {+ models: ModelUsage[];+ model: string | null;+ onSelect?: (model: string) => void;+}) {+ if (!models.length) return null;+ const total = models.reduce((s, m) => s + m.cost, 0) || 1;+ return (+ <SideCard+ title="Models"+ aside={<span>cost share</span>}+ collapsible+ defaultOpen={false}+ >+ <div className="flex flex-col gap-2">+ {models.map((m) => {+ const share = Math.max(0, Math.min(1, m.cost / total));+ return (+ <button+ key={m.model}+ type="button"+ aria-pressed={model === m.model}+ onClick={() => onSelect?.(m.model)}+ className={cn(+ 'flex flex-col gap-1 rounded px-1 py-0.5 text-left',+ model === m.model && 'bg-ds-brand-lightest'+ )}+ >+ <span className="flex w-full items-baseline justify-between gap-2 ds-text-body-xs-medium">+ <span className="min-w-0 truncate text-ds-text-darker">+ {m.model}+ </span>+ <span className="shrink-0 font-mono text-ds-text-subtle tabular-nums">+ {fmtUsd(m.cost)} · {m.requests} req+ </span>+ </span>+ <span className="block h-1.5 w-full overflow-hidden rounded-full bg-ds-gray-subtlest">+ <span+ className="block h-full rounded-full"+ style={{+ width: `${share * 100}%`,+ background: PANEL_BAR_COLOR,+ }}+ />+ </span>+ </button>+ );+ })}+ </div>+ </SideCard>+ );+}++const toneClass = (tone?: 'bad' | 'warn') =>+ tone === 'bad'+ ? 'text-ds-danger-default'+ : tone === 'warn'+ ? 'text-ds-warning-default'+ : 'text-ds-text-darker';++function CountersCard({+ map,+ p,+ ctxNow,+}: {+ map: SessionMap;+ p: number;+ ctxNow: number;+}) {+ const c = useMemo(() => countersAt(map.events, p), [map.events, p]);+ const pct = map.events.length+ ? Math.round((100 * (p + 1)) / map.events.length)+ : 0;+ const items: { v: string | number; l: string; tone?: 'bad' }[] = [+ { v: c.calls, l: 'tool calls' },+ { v: c.requests, l: 'LLM requests' },+ { v: fmtTok(c.tokens), l: 'tokens' },+ { v: fmtUsd(c.cost), l: 'est. cost' },+ { v: c.filesRead, l: 'files read' },+ { v: c.filesEdited, l: 'files edited' },+ { v: c.errors, l: 'error signals', tone: c.errors ? 'bad' : undefined },+ { v: fmtTok(ctxNow), l: 'context now' },+ ];+ return (+ <SideCard+ title="At playhead"+ aside={<span className="font-mono tabular-nums">{pct}%</span>}+ collapsible+ >+ <div className="grid grid-cols-4 gap-x-2 gap-y-2.5">+ {items.map((it) => (+ <div key={it.l} className="flex min-w-0 flex-col">+ <b+ className={cn(+ 'truncate font-mono ds-text-body-xs-semibold tabular-nums',+ toneClass(it.tone)+ )}+ >+ {it.v}+ </b>+ <span className="truncate ds-text-body-xs-medium text-ds-text-subtle">+ {it.l}+ </span>+ </div>+ ))}+ </div>+ </SideCard>+ );+}++function SignalsCard({+ at,+ session,+ onJumpSource,+}: {+ at: ReturnType<typeof signalsAt>;+ session: SessionSignals;+ onJumpSource: (source: ErrorSource) => void;+}) {+ const classes = Object.entries(at.byClass)+ .sort((a, b) => b[1] - a[1])+ .slice(0, 6);+ const peak = Math.max(session.maxContext, 1);+ const ctxPct = Math.min(100, (100 * at.ctxNow) / peak);+ return (+ <SideCard+ title="Signals"+ aside={<span>at playhead / session</span>}+ collapsible+ >+ <div className="flex flex-col">+ {ERROR_SOURCES.map((src) => (+ <button+ key={src}+ type="button"+ onClick={() => onJumpSource(src)}+ disabled={!session.bySource[src]}+ aria-label={`Jump to the next ${ERROR_SOURCE_LABEL[src]} error`}+ className="flex items-center gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-ds-gray-subtlest disabled:cursor-default disabled:hover:bg-transparent"+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{ background: ERROR_SOURCE_COLOR[src] }}+ />+ <span className="min-w-0 flex-1 truncate ds-text-body-xs-medium text-ds-text-default">+ {ERROR_SOURCE_LABEL[src]}+ </span>+ <span className="shrink-0 font-mono ds-text-body-xs-medium tabular-nums">+ <b+ className={+ at.bySource[src]+ ? 'text-ds-danger-default'+ : 'text-ds-text-darker'+ }+ >+ {at.bySource[src]}+ </b>+ <span className="text-ds-text-subtle">+ {' '}+ / {session.bySource[src]}+ </span>+ </span>+ </button>+ ))}+ </div>+ <div className="mt-2 flex flex-wrap gap-1">+ {classes.length ? (+ classes.map(([k, v]) => (+ <Badge key={k} variant="error">+ {errClassLabel(k)} ×{v}+ </Badge>+ ))+ ) : (+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ No errors yet at the playhead+ </span>+ )}+ </div>+ <dl className="mt-2 grid grid-cols-[1fr_auto] gap-x-3 gap-y-0.5 ds-text-body-xs-medium">+ <dt className="text-ds-text-subtle">Retries</dt>+ <dd className="text-right font-mono text-ds-text-darker">+ {at.retries}+ </dd>+ <dt className="text-ds-text-subtle">Delays</dt>+ <dd className="text-right font-mono text-ds-text-darker">+ {at.delays} · {fmtDur(at.delayMs)}+ </dd>+ <dt className="text-ds-text-subtle">Compactions</dt>+ <dd className="text-right font-mono text-ds-text-darker">+ {at.compactions}+ </dd>+ </dl>+ <div className="mt-2 flex items-center justify-between ds-text-body-xs-medium text-ds-text-subtle">+ <span>Context window</span>+ <span className="font-mono">+ {fmtTok(at.ctxNow)} / peak {fmtTok(session.maxContext)}+ </span>+ </div>+ <div+ className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-ds-gray-subtlest"+ role="meter"+ aria-label="Context now against the session peak"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(ctxPct)}+ >+ <div+ className="h-full rounded-full"+ style={{ width: `${ctxPct}%`, background: PANEL_BAR_COLOR }}+ />+ </div>+ </SideCard>+ );+}++function Rows({+ rows,+ onSeek,+}: {+ rows: DetailRow[];+ onSeek?: (index: number) => void;+}) {+ return (+ <dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 ds-text-body-xs-medium">+ {rows.map((r) => (+ <div key={r.k} className="contents">+ <dt className="text-ds-text-subtle">{r.k}</dt>+ <dd+ className={cn('truncate text-right font-mono', toneClass(r.tone))}+ >+ {r.seek != null && onSeek ? (+ <button+ type="button"+ onClick={() => onSeek(r.seek!)}+ className="max-w-full cursor-pointer truncate rounded text-right underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ds-border-focus"+ >+ {r.v}+ </button>+ ) : (+ r.v+ )}+ </dd>+ </div>+ ))}+ </dl>+ );+}++function EventCard({+ map,+ p,+ ordinals,+ cumCost,+ sessionId,+ onSeek,+}: {+ map: SessionMap;+ p: number;+ ordinals: Map<string, number>;+ cumCost: Float64Array;+ sessionId: string;+ onSeek: (index: number) => void;+}) {+ const e = map.events[p];+ if (!e) return null;+ const K = kindStyle(e);+ const D = describeEvent(map, e, ordinals);+ const failedCall = e.err && e.kind !== 'error';+ return (+ <SideCard+ title={`Event #${p}`}+ aside={+ <span className="font-mono">+ {clockAt(map.session.startedAt, e.t)} UTC+ </span>+ }+ // One height for every event, sized to fit an LLM request (the longest+ // common kind), so stepping through events never resizes the card.+ // Anything longer scrolls inside it.+ className="flex h-[22rem] flex-col"+ >+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div+ className={cn(+ 'flex items-center gap-1.5 ds-text-body-xs-semibold',+ failedCall ? 'text-ds-danger-default' : 'text-ds-text-default'+ )}+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{ background: K.color }}+ />+ {K.label}+ {failedCall ? ' · failed' : ''}+ </div>+ <div className="mt-1 break-all ds-text-body-xs-semibold text-ds-text-darker">+ {D.title}+ </div>+ {D.detail ? (+ <div className="mt-0.5 break-all ds-text-body-xs-medium text-ds-text-subtle">+ {D.detail}+ </div>+ ) : null}+ <Rows+ rows={detailRows(map, p, cumCost, ordinals, false)}+ onSeek={onSeek}+ />+ {e.source === 'hook' && e.srcUuid ? (+ <HookDetail sessionId={sessionId} uuid={e.srcUuid} />+ ) : null}+ </div>+ </SideCard>+ );+}++function FeedCard({+ map,+ p,+ ordinals,+ onSeek,+ selected,+}: {+ map: SessionMap;+ p: number;+ ordinals: Map<string, number>;+ onSeek: (i: number) => void;+ selected: ReadonlySet<Category>;+}) {+ // `feed` now only carries a tool category picked in the Insights tab's+ // Categories card; older `feed=tools|llm|…` values read as no filter.+ const [filter, setFilter] = useQueryState(+ 'feed',+ parseAsStringEnum<FeedFilter>([...FEED_FILTER_VALUES]).withDefault('all')+ );+ const rows = useMemo(() => {+ const want = feedWant(filter, selected);+ const out: number[] = [];+ for (let i = p; i >= 0 && out.length < FEED_LEN; i--) {+ if (want(map.events[i])) out.push(i);+ }+ return out;+ }, [map.events, p, filter, selected]);+ return (+ <SideCard+ title="Recent activity"+ aside={+ isCatFilter(filter) ? (+ <Button+ variant="outline"+ size="sm"+ onClick={() => void setFilter('all')}+ title="Clear the tool-category filter"+ className="h-6 gap-1 px-2"+ >+ {catLabel(filter.slice(4))}+ <X size={10} aria-hidden />+ </Button>+ ) : null+ }+ >+ <p className="mb-2 ds-text-body-xs-medium text-ds-text-subtle">+ {narrowsView(selected)+ ? `${CATEGORIES.filter((c) => selected.has(c))+ .map((c) => CATEGORY_LABEL[c])+ .join(', ')} · from the timeline chips`+ : 'Everything · pick timeline chips to narrow'}+ </p>+ {rows.length ? (+ <ul className="flex flex-col">+ {rows.map((i) => {+ const e = map.events[i];+ const K = kindStyle(e);+ const D = describeEvent(map, e, ordinals);+ return (+ <li key={i}>+ <button+ type="button"+ onClick={() => onSeek(i)}+ className={cn(+ 'flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-ds-gray-subtlest',+ i === p && 'bg-ds-brand-lightest'+ )}+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{ background: e.err ? ERROR_COLOR : K.color }}+ />+ <span className="min-w-0 flex-1 truncate ds-text-body-xs-medium text-ds-text-default">+ {D.title}+ {e.err && e.kind !== 'error' ? (+ <span className="ml-1 text-ds-danger-default">+ failed+ </span>+ ) : null}+ {e.retryOf != null ? (+ <span className="ml-1 text-ds-warning-default">+ retry+ </span>+ ) : null}+ </span>+ <span className="shrink-0 font-mono ds-text-body-xs-medium text-ds-text-subtler">+ {clockAt(map.session.startedAt, e.t).slice(0, 5)}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ ) : (+ <div className="px-1 ds-text-body-xs-medium text-ds-text-subtle">+ Nothing of this kind yet+ </div>+ )}+ </SideCard>+ );+}++/** Tool-category breakdown: counts per+ * `events[].cat`, click a row to filter Recent activity to that category+ * (the `feed` query state FeedCard narrows by). Renders+ * nothing for a map with no categorized events (older maps, pre-contract). */+function CategoriesCard({ map }: { map: SessionMap }) {+ const [filter, setFilter] = useQueryState(+ 'feed',+ parseAsStringEnum<FeedFilter>([...FEED_FILTER_VALUES]).withDefault('all')+ );+ const entries = useMemo(() => {+ const counts = new Map<string, number>();+ for (const e of map.events) {+ if (!e.cat) continue;+ counts.set(e.cat, (counts.get(e.cat) ?? 0) + 1);+ }+ return [...counts.entries()].sort((a, b) => b[1] - a[1]);+ }, [map.events]);+ if (!entries.length) return null;+ const max = entries[0][1];+ return (+ <SideCard title="Tool categories" collapsible defaultOpen={false}>+ <ul className="flex flex-col gap-0.5">+ {entries.map(([cat, n]) => {+ const value = `cat:${cat}` as FeedFilter;+ const active = filter === value;+ const color = catColor(cat);+ return (+ <li key={cat}>+ <button+ type="button"+ aria-pressed={active}+ onClick={() => void setFilter(active ? 'all' : value)}+ className={cn(+ 'grid w-full grid-cols-[104px_1fr_auto] items-center gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-ds-gray-subtlest',+ active && 'bg-ds-brand-lightest'+ )}+ >+ <span className="flex min-w-0 items-center gap-1.5 truncate ds-text-body-xs-medium text-ds-text-default">+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{ background: color }}+ />+ {catLabel(cat)}+ </span>+ <span className="h-1.5 overflow-hidden rounded-full bg-ds-gray-subtlest">+ <span+ className="block h-full rounded-full"+ style={{ width: `${(100 * n) / max}%`, background: color }}+ />+ </span>+ <span className="ds-text-body-xs-medium tabular-nums text-ds-text-subtle">+ {n}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </SideCard>+ );+}++function AgentsCard({+ map,+ ordinals,+}: {+ map: SessionMap;+ ordinals: Map<string, number>;+}) {+ const total = map.agents.reduce((s, a) => s + a.cost, 0) || 1;+ if (!map.agents.length) return null;+ return (+ <SideCard+ title="Agents"+ aside={<span>cost share</span>}+ collapsible+ defaultOpen={false}+ >+ <div className="flex flex-col gap-2">+ {map.agents.map((a) => {+ const share = Math.max(0, Math.min(1, a.cost / total));+ const label = agentLabel(map, a.id, ordinals);+ return (+ <div key={a.id} className="flex flex-col gap-1">+ <div className="flex items-baseline justify-between gap-2 ds-text-body-xs-medium">+ <span+ className={cn(+ 'min-w-0 truncate',+ a.id === 'main'+ ? 'text-ds-text-darker'+ : 'text-ds-text-default'+ )}+ title={label}+ >+ {label}+ </span>+ <span className="shrink-0 font-mono text-ds-text-subtle tabular-nums">+ {fmtUsd(a.cost)} · {a.calls} calls+ </span>+ </div>+ <div+ className="h-1.5 w-full overflow-hidden rounded-full bg-ds-gray-subtlest"+ role="meter"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(share * 100)}+ aria-label={`${label} cost share`}+ >+ <div+ className="h-full rounded-full"+ style={{+ width: `${share * 100}%`,+ background: PANEL_BAR_COLOR,+ }}+ />+ </div>+ </div>+ );+ })}+ </div>+ </SideCard>+ );+}++const VERIFICATION_COPY: Record<ReviewMetrics['verification'], string> = {+ never: 'never verified',+ after_final_edit: 'after final edit',+ edits_after_verify: 'edits after last verify',+};++function ReviewCard({+ review,+ signals,+}: {+ review: ReviewMetrics;+ signals: SessionSignals;+}) {+ const bySource =+ ERROR_SOURCES.filter((s) => signals.bySource[s])+ .map((s) => `${ERROR_SOURCE_LABEL[s]} ${signals.bySource[s]}`)+ .join(' · ') || 'none';+ const latency =+ signals.latencyP50 != null && signals.latencyP95 != null+ ? `${fmtDur(signals.latencyP50)} / ${fmtDur(signals.latencyP95)}`+ : 'n/a';+ const rows: {+ label: string;+ value: string;+ tone?: 'bad' | 'warn';+ sub?: string;+ }[] = [+ {+ label: 'Error signals',+ value: String(signals.errors),+ tone: signals.errors ? 'bad' : undefined,+ sub: bySource,+ },+ {+ label: 'Retries after a failure',+ value: String(signals.retries),+ tone: signals.retries ? 'warn' : undefined,+ },+ {+ label: 'Delays (total)',+ value: `${signals.delays} · ${fmtDur(signals.delayMs)}`,+ tone: signals.delays ? 'warn' : undefined,+ },+ { label: 'LLM latency p50 / p95', value: latency },+ {+ label: 'Compactions · peak context',+ value: `${signals.compactions} · ${fmtTok(signals.maxContext)}`,+ },+ {+ label: 'Edits to files never read first',+ value: String(review.blindEdits),+ tone: review.blindEdits ? 'warn' : undefined,+ },+ {+ label: 'Files edited 3+ times',+ value: String(review.churnFiles),+ tone: review.churnFiles ? 'warn' : undefined,+ },+ { label: 'Re-reads of unchanged files', value: `${review.reReadPct}%` },+ {+ label: 'Verification',+ value: VERIFICATION_COPY[review.verification],+ tone: review.verification === 'after_final_edit' ? undefined : 'warn',+ },+ ];+ return (+ <SideCard+ title="Review"+ aside={<span>whole session</span>}+ collapsible+ defaultOpen={false}+ >+ <div className="flex flex-col divide-y divide-ds-border-subtlest">+ {rows.map((r) => (+ <div key={r.label} className="flex flex-col gap-0.5 py-1.5">+ <div className="flex items-center justify-between gap-3 ds-text-body-xs-medium">+ <span className="text-ds-text-subtle">{r.label}</span>+ <b+ className={cn(+ 'shrink-0 font-mono ds-text-body-xs-semibold',+ toneClass(r.tone)+ )}+ >+ {r.value}+ </b>+ </div>+ {r.sub ? (+ <span className="ds-text-body-xs-medium text-ds-text-subtler">+ {r.sub}+ </span>+ ) : null}+ </div>+ ))}+ </div>+ </SideCard>+ );+}diff --git a/viewer/src/explorer/TimelineDock.tsx b/viewer/src/explorer/TimelineDock.tsxnew file mode 100644index 0000000..a864df2--- /dev/null+++ b/viewer/src/explorer/TimelineDock.tsx@@ -0,0 +1,454 @@+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ useSyncExternalStore,+ type KeyboardEvent,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+} from 'react';+import { parseAsString, useQueryState } from 'nuqs';+import type { SessionMap } from '@/core/schema';+import { Button } from '@/components/ui/button';+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';+import { CONTEXT_COLOR, KIND_META } from '@/core/eventColors';+import { TimelineStrip } from './MapPlayerParts';+import { PlaybackControls } from './PlaybackControls';+import {+ CATEGORIES,+ DEFAULT_CATEGORIES,+ DOCK_MIN_HEIGHT,+ categoryIndices,+ clampDockHeight,+ dockOverflow,+ getDockHeight,+ getDockHeightServer,+ lensSourceIndex,+ matchesAnyCategory,+ nearestLensIndex,+ setDockHeight,+ stepEvent,+ subagentLanes,+ subscribeDockHeight,+ toggleCategory,+ type Category,+ type SubagentInfo,+} from '@/core/sessionLayout';+import { clockAt, cumulativeCost, subagentOrdinal } from '@/core/sessionMapModel';+import { timelineLanes } from '@/core/sessionScope';+import { SessionTimeline, useTimelineAxis } from './SessionTimeline';+import { isTimelineAxis } from '@/core/sessionSignals';+import { CategoryChips, EventsPanel, LaneToggle } from './TimelineEvents';+import { optionalLanesHeight } from '@/core/timelineDraw';+import type { EventCategories } from './useEventCategories';+import type { ExplorerScope } from './useExplorerScope';+import type { MapModel, PlaybackWindow } from './usePlaybackWindow';++/**+ * What the timeline replays: the playback map itself, or (in a subagent+ * view) the whole session with the subagent's replay mapped onto it.+ * `allow` limits the event chips / list to the subagent's own events.+ */+function useTimelineSource(+ x: ExplorerScope,+ playback: PlaybackWindow,+ model: MapModel+) {+ const { map, scopedMap, sub } = x;+ const { pb, seek } = playback;+ const lens = useMemo(() => {+ if (!sub) return null;+ const src = lensSourceIndex(scopedMap.events, sub);+ const set = new Set(src);+ return {+ src,+ allow: (i: number) => set.has(i),+ cumCost: cumulativeCost(scopedMap.events),+ ordinals: subagentOrdinal(scopedMap),+ };+ }, [sub, scopedMap]);+ if (!lens)+ return {+ map,+ p: pb.p,+ seek,+ cumCost: model.cumCost,+ ordinals: model.ordinals,+ shade: null,+ allow: undefined,+ };+ const { src } = lens;+ return {+ map: scopedMap,+ p: src[pb.p] ?? 0,+ seek: (i: number) => seek(nearestLensIndex(src, i)),+ cumCost: lens.cumCost,+ ordinals: lens.ordinals,+ shade: src.length ? { start: src[0], end: src[src.length - 1] } : null,+ allow: lens.allow,+ };+}++/** The persisted dock height floor (null: just its content height). */+function useDockHeight() {+ return useSyncExternalStore(+ subscribeDockHeight,+ getDockHeight,+ getDockHeightServer+ );+}++/**+ * The timeline dock at the bottom of the explorer: a resize grip, one+ * header row (playback, the category chips with steppers, the Subagents /+ * Context lane toggles, axis, the events list)+ * and the lanes. It is as tall as its lanes, so they never scroll inside+ * it; optional lanes extend the page below the fold instead. A+ * dragged height is remembered as a floor.+ */+export function TimelineDock({+ x,+ playback,+ model,+ cats,+ onSelectTask,+ subInfo,+ collapsed,+ onOverflow,+ columnExtra,+}: {+ x: ExplorerScope;+ playback: PlaybackWindow;+ model: MapModel;+ /** the category chips' selection and the Context lane toggle */+ cats: EventCategories;+ onSelectTask: (n: number) => void;+ subInfo: SubagentInfo | null;+ collapsed: boolean;+ /** how many px the optional lanes grow the dock past its budget+ * (`dockOverflow`), for the explorer to grow the column by so the map+ * doesn't shrink to make room */+ onOverflow?: (px: number) => void;+ /** what the explorer actually applied from the last `onOverflow` call,+ * echoed back so the measurement effect reruns once the column's own+ * height has caught up (see the effect's comment) */+ columnExtra?: number | null;+}) {+ const tl = useTimelineSource(x, playback, model);+ const { pb, dispatch } = playback;+ const dockRef = useRef<HTMLElement>(null);+ const height = useDockHeight();+ const { selected } = cats;+ const [subsOpen, setSubsOpen] = useState(false);+ // Off by default: a whole agent-rows lane, not a point-event category,+ // so it is gated independently of the category chips.+ const [subsOn, setSubsOn] = useState(false);+ const [listOpen, setListOpen] = useState(false);+ const [hoverRow, setHoverRow] = useState<number | null>(null);+ // Local pin, tied to the map it indexes (a new scope drops it).+ const [pin, setPin] = useState<{ map: SessionMap; i: number } | null>(null);+ const pinned = pin && pin.map === tl.map ? pin.i : null;+ const [, setPanel] = useQueryState('panel', parseAsString);++ const events = tl.map.events;+ const { allow } = tl;+ const lists = useMemo(+ () =>+ Object.fromEntries(+ CATEGORIES.map((c) => [c, categoryIndices(events, c, allow)])+ ) as Record<Category, number[]>,+ [events, allow]+ );+ const rows = useMemo(() => {+ const out: number[] = [];+ events.forEach((e, i) => {+ if ((!allow || allow(i)) && matchesAnyCategory(e, selected)) out.push(i);+ });+ return out;+ }, [events, allow, selected]);+ const visibleLanes = useMemo(+ () => timelineLanes({ context: cats.context, subagents: subsOn }),+ [cats.context, subsOn]+ );+ const subRows = useMemo(+ () => subagentLanes(x.subs, events),+ [x.subs, events]+ );+ const optionalH = useMemo(+ () => optionalLanesHeight(visibleLanes, subRows, subsOpen),+ [visibleLanes, subRows, subsOpen]+ );+ // Measured, not computed: the dock's own chrome (header rows, padding)+ // decides its rendered height (a narrower window can wrap the header),+ // and the explorer column's height bounds the saved floor.+ const [box, setBox] = useState<{ dockH: number; columnH: number } | null>(+ null+ );+ // Synchronous (useLayoutEffect, before paint), not a ResizeObserver: every+ // state below already re-renders the dock at its new height on its own,+ // so re-measuring on the same triggers is exactly as timely and never+ // depends on a notification the observer might coalesce, throttle or (in+ // at least one real browser instance, confirmed by hand) never deliver at+ // all. A plain `resize` listener catches the one case none of this state+ // can: the window narrowing enough to wrap the header row.+ //+ // `columnExtra` (what the explorer actually applied last, echoed back as+ // a prop) closes the other case: shrinking the optional lanes measures+ // before `onOverflow` has told the explorer to shrink the column back,+ // so this first pass still sees its old, larger height and `floor` can+ // exceed the true cap. Once the explorer applies the smaller height and+ // that change comes back down as `columnExtra`, this reruns and the+ // second measurement is correct -- converges in at most one extra pass,+ // since a converged `overflow` reported back is a no-op for the explorer.+ useLayoutEffect(() => {+ const measure = () => {+ const el = dockRef.current;+ const column = el?.parentElement;+ if (!el || !column) return;+ setBox({+ dockH: el.getBoundingClientRect().height,+ columnH: column.clientHeight,+ });+ };+ measure();+ window.addEventListener('resize', measure);+ return () => window.removeEventListener('resize', measure);+ }, [+ subsOpen,+ subsOn,+ cats.context,+ collapsed,+ height,+ optionalH,+ columnExtra,+ ]);+ // A floor saved in a taller window is re-clamped to this one, so it can+ // never outgrow the explorer and squeeze the map.+ const floor =+ height != null && box ? clampDockHeight(height, box.columnH) : height;+ // How far the optional lanes grow the dock past its budget. Reported to+ // the explorer (onOverflow), which grows the column by the same amount+ // instead of letting the map's flex row shrink to make room.+ const overflow = box ? dockOverflow(box.dockH, optionalH, floor) : 0;+ // Scrolling a newly-grown lane into view is the explorer's job+ // (onOverflow drives it there, once the column has actually grown).+ useEffect(() => onOverflow?.(overflow), [overflow, onOverflow]);++ const pinEvent = (i: number) => {+ setPin({ map: tl.map, i });+ tl.seek(i);+ void setPanel('event');+ };+ // A pinned event the new selection no longer covers is unpinned.+ const select = (next: ReadonlySet<Category>) => {+ cats.setSelected(next);+ if (pinned != null && !matchesAnyCategory(events[pinned], next))+ setPin(null);+ };+ const onToggleSubsOn = () => {+ // Turning it off also collapses it, so re-enabling always starts+ // collapsed. Both updates are queued from the handler (not from inside+ // an updater, which React may replay).+ if (subsOn) setSubsOpen(false);+ setSubsOn(!subsOn);+ };+ const onStep = (c: Category, dir: 1 | -1) => {+ const i = stepEvent(lists[c], pinned, tl.p, dir);+ if (i != null) pinEvent(i);+ };+ const closeList = useCallback(() => {+ setListOpen(false);+ setHoverRow(null);+ }, []);++ return (+ <section+ ref={dockRef}+ aria-label="Timeline"+ // Sized by its lanes, never clipped: turning on Subagents / Context+ // grows the dock, and `onOverflow` tells the explorer column to grow+ // by the same amount, so the map keeps its size and the page scrolls+ // -- no scrollbar inside the dock. A dragged height is a floor.+ className="relative flex min-h-0 flex-none flex-col rounded-xl border border-ds-border-subtlest bg-ds-surface-white px-2.5 pb-1.5 pt-3"+ style={{ minHeight: floor ?? undefined }}+ >+ <DockGrip dockRef={dockRef} height={height} />+ <div className="pointer-events-none absolute bottom-full left-0 z-20 mb-1.5 max-w-[60%] [&>*]:pointer-events-auto [&>*]:shadow-md">+ <TimelineStrip+ x={x}+ subInfo={subInfo}+ playing={pb.playing}+ p={pb.p}+ collapsed={collapsed}+ />+ </div>+ {listOpen ? (+ <EventsPanel+ map={tl.map}+ rows={rows}+ selected={selected}+ ordinals={tl.ordinals}+ pinned={pinned}+ onPin={pinEvent}+ onHover={setHoverRow}+ onClose={closeList}+ />+ ) : null}+ <div className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1.5 pb-1.5">+ <PlaybackControls+ state={pb}+ clock={clockAt(+ x.map.session.startedAt,+ x.map.events[pb.p]?.t ?? 0+ ).slice(0, 5)}+ elapsedMs={x.map.events[pb.p]?.t ?? 0}+ durationMs={x.map.session.durationMs}+ onStart={() => playback.seek(0)}+ onToggle={() => dispatch({ type: 'toggle' })}+ onCycleSpeed={() => dispatch({ type: 'cycleSpeed' })}+ />+ <CategoryChips+ lists={lists}+ selected={selected}+ pinned={pinned}+ onToggle={(c) => select(toggleCategory(selected, c))}+ onStep={onStep}+ onReset={() => select(new Set(DEFAULT_CATEGORIES))}+ />+ <span aria-hidden className="h-4 w-px shrink-0 bg-ds-border-subtler" />+ <LaneToggle+ label="Subagents"+ color={KIND_META.subagent.color}+ count={subRows.length}+ on={subsOn}+ onToggle={onToggleSubsOn}+ />+ <LaneToggle+ label="Context"+ color={CONTEXT_COLOR}+ on={cats.context}+ onToggle={() => cats.setContext(!cats.context)}+ />+ <span className="flex-1" />+ <AxisToggle />+ <Button+ variant="outline"+ size="sm"+ aria-expanded={listOpen}+ aria-haspopup="listbox"+ onClick={() => (listOpen ? closeList() : setListOpen(true))}+ >+ List {listOpen ? '▾' : '▴'}+ </Button>+ </div>+ <SessionTimeline+ map={tl.map}+ p={tl.p}+ cumCost={tl.cumCost}+ ordinals={tl.ordinals}+ onSeek={tl.seek}+ shade={tl.shade}+ lanes={visibleLanes}+ selected={selected}+ task={x.scope.task}+ onSelectTask={onSelectTask}+ subRows={subRows}+ subsOpen={subsOpen}+ onToggleSubs={() => setSubsOpen((o) => !o)}+ onOpenSubagent={x.lens === 'main' ? x.setLens : undefined}+ activeAgent={x.sub}+ pinned={pinned}+ highlight={listOpen ? hoverRow : null}+ />+ </section>+ );+}++/** Steps / Time: what the timeline's x axis spaces events by. */+function AxisToggle() {+ const [axis, setAxis] = useTimelineAxis();+ return (+ <ToggleGroup+ value={[axis]}+ onValueChange={(v: unknown[]) => {+ const next = v.find(isTimelineAxis);+ if (next) void setAxis(next);+ }}+ aria-label="Timeline axis"+ className="shrink-0"+ >+ <ToggleGroupItem value="steps" className="px-2">+ Steps+ </ToggleGroupItem>+ <ToggleGroupItem value="time" className="px-2">+ Time+ </ToggleGroupItem>+ </ToggleGroup>+ );+}++const KEY_STEP = 24;++/** The dock's top-edge grip: drag to resize, double-click to reset to the+ * content height, ↑ / ↓ to resize from the keyboard. */+function DockGrip({+ dockRef,+ height,+}: {+ dockRef: RefObject<HTMLElement | null>;+ height: number | null;+}) {+ const drag = useRef<{ y0: number; h0: number; box: number } | null>(null);+ const container = () => dockRef.current?.parentElement?.clientHeight ?? 0;+ // The rendered height, not the saved one: the saved height is only a+ // floor, so the dock can be taller than it when its lanes need the room.+ const current = () =>+ dockRef.current?.getBoundingClientRect().height ?? height ?? 0;++ const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {+ drag.current = { y0: e.clientY, h0: current(), box: container() };+ e.currentTarget.setPointerCapture(e.pointerId);+ e.preventDefault();+ };+ const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {+ const d = drag.current;+ if (!d) return;+ setDockHeight(clampDockHeight(d.h0 - (e.clientY - d.y0), d.box), false);+ };+ const onPointerUp = () => {+ if (!drag.current) return;+ drag.current = null;+ setDockHeight(getDockHeight());+ };+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {+ const d =+ e.key === 'ArrowUp' ? KEY_STEP : e.key === 'ArrowDown' ? -KEY_STEP : 0;+ if (!d) return;+ e.preventDefault();+ e.stopPropagation();+ setDockHeight(clampDockHeight(current() + d, container()));+ };+ return (+ <div+ role="separator"+ aria-orientation="horizontal"+ aria-label="Resize the timeline: drag, or use the up and down arrow keys; double-click to reset"+ aria-valuemin={DOCK_MIN_HEIGHT}+ aria-valuenow={height ?? undefined}+ tabIndex={0}+ title="Drag to resize · double-click to reset"+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ onDoubleClick={() => setDockHeight(null)}+ onKeyDown={onKeyDown}+ className="group absolute inset-x-0 top-0 flex h-3 cursor-ns-resize touch-none justify-center pt-1 outline-none"+ >+ <span className="h-[5px] w-14 rounded-full bg-ds-border-default transition-colors group-hover:bg-ds-brand-default group-focus-visible:bg-ds-brand-default motion-reduce:transition-none" />+ </div>+ );+}diff --git a/viewer/src/explorer/TimelineEvents.tsx b/viewer/src/explorer/TimelineEvents.tsxnew file mode 100644index 0000000..ef7d1f1--- /dev/null+++ b/viewer/src/explorer/TimelineEvents.tsx@@ -0,0 +1,371 @@+import { useEffect, useRef } from 'react';+import { CaretLeft, CaretRight, X } from '@phosphor-icons/react';+import type { SessionMap, SessionMapEvent } from '@/core/schema';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import { CATEGORY_COLOR, kindMeta, kindStyle } from '@/core/eventColors';+import {+ CATEGORIES,+ CATEGORY_LABEL,+ displayCategory,+ isDefaultCategories,+ stepPosition,+ type Category,+} from '@/core/sessionLayout';+import { clockAt, describeEvent } from '@/core/sessionMapModel';++const SINGULAR: Record<Category, string> = {+ prompt: 'prompt',+ error: 'error',+ delay: 'delay',+ out: 'output',+ edit: 'edit',+ explore: 'exploration call',+ mcp: 'MCP call',+ skill: 'skill call',+ tool: 'tool call',+ model: 'model request',+ cost: 'costed request',+ tokens: 'request',+};++const CHIP = 'inline-flex items-center rounded-full border py-px pl-px pr-0.5';+const chipTone = (on: boolean) =>+ on+ ? 'border-ds-border-default bg-ds-gray-subtlest'+ : 'border-ds-border-subtlest bg-ds-surface-white';+const CHIP_BUTTON =+ 'inline-flex items-center gap-1.5 rounded-full py-0.5 pl-2 pr-1.5 text-xs font-medium';+const COUNT = 'font-mono text-[10.5px] text-ds-text-subtle tabular-nums';++/**+ * The dock's category chips: one per category with its count in the current+ * scope. A chip toggles the category in the selection (several may be on),+ * which lights its events on the timeline's Events bar, its nodes on the map+ * and its rows in Activity. A selected chip gets ‹ › to step to the previous+ * / next event of the category (pinning it), with "k/N" while one is pinned.+ * Reset returns to the default selection.+ */+export function CategoryChips({+ lists,+ selected,+ pinned,+ onToggle,+ onStep,+ onReset,+}: {+ lists: Record<Category, number[]>;+ selected: ReadonlySet<Category>;+ pinned: number | null;+ onToggle: (c: Category) => void;+ onStep: (c: Category, dir: 1 | -1) => void;+ onReset: () => void;+}) {+ return (+ // `contents`, not its own flex row: as a normal flex item this whole+ // group either fits next to PlaybackControls or, being wider than the+ // remaining space, wraps as one block -- stranding Playback alone on+ // its own line even when a few chips would have fit beside it. As+ // `contents` the chips become direct items of the dock's own row, so+ // they flow onto whichever line has room, same as everything else in+ // it. `role`/`aria-label` still apply: contents keeps element+ // semantics, it only removes the box.+ <div+ role="group"+ aria-label="Event categories: highlight on the timeline, map and activity"+ className="contents"+ >+ {CATEGORIES.map((c) => (+ <CategoryChip+ key={c}+ c={c}+ on={selected.has(c)}+ list={lists[c]}+ pinned={pinned}+ onToggle={onToggle}+ onStep={onStep}+ />+ ))}+ {isDefaultCategories(selected) ? null : (+ <Button+ variant="link"+ size="sm"+ onClick={onReset}+ title="Back to the default selection (Prompts and Errors)"+ className="h-6 px-1 text-ds-text-subtle"+ >+ Reset+ </Button>+ )}+ </div>+ );+}++function CategoryChip({+ c,+ on,+ list,+ pinned,+ onToggle,+ onStep,+}: {+ c: Category;+ on: boolean;+ list: readonly number[];+ pinned: number | null;+ onToggle: (c: Category) => void;+ onStep: (c: Category, dir: 1 | -1) => void;+}) {+ const at = on ? stepPosition(list, pinned) : null;+ return (+ <span className={cn(CHIP, chipTone(on), !on && 'pr-px')}>+ <button+ type="button"+ aria-pressed={on}+ onClick={() => onToggle(c)}+ title={`Highlight ${CATEGORY_LABEL[c]} on the timeline, map and activity`}+ className={cn(+ CHIP_BUTTON,+ on ? 'text-ds-text-darker' : 'text-ds-text-subtle'+ )}+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-sm"+ style={{ background: CATEGORY_COLOR[c] }}+ />+ {CATEGORY_LABEL[c]}+ <span className={COUNT}>{list.length.toLocaleString()}</span>+ </button>+ {on ? (+ <>+ <StepButton+ dir={-1}+ label={`Previous ${SINGULAR[c]}`}+ disabled={!list.length}+ onClick={() => onStep(c, -1)}+ />+ {at ? (+ <span className="font-mono text-[10.5px] text-ds-text-darker tabular-nums">+ {at}+ </span>+ ) : null}+ <StepButton+ dir={1}+ label={`Next ${SINGULAR[c]}`}+ disabled={!list.length}+ onClick={() => onStep(c, 1)}+ />+ </>+ ) : null}+ </span>+ );+}++/** An optional timeline lane's on/off chip (Context, Subagents): kept apart+ * from the category chips, since it adds a lane rather than lighting events. */+export function LaneToggle({+ label,+ color,+ count,+ on,+ onToggle,+}: {+ label: string;+ color: string;+ count?: number;+ on: boolean;+ onToggle: () => void;+}) {+ return (+ <button+ type="button"+ aria-pressed={on}+ onClick={onToggle}+ title={`Show or hide the ${label} lane`}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-full border py-0.5 pl-2 pr-2.5 text-xs font-medium',+ chipTone(on),+ on ? 'text-ds-text-darker' : 'text-ds-text-subtle'+ )}+ >+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-sm"+ style={{ background: color }}+ />+ {label}+ {count != null ? (+ <span className={COUNT}>{count.toLocaleString()}</span>+ ) : null}+ </button>+ );+}++function StepButton({+ dir,+ label,+ disabled,+ onClick,+}: {+ dir: 1 | -1;+ label: string;+ disabled: boolean;+ onClick: () => void;+}) {+ const Icon = dir < 0 ? CaretLeft : CaretRight;+ return (+ <button+ type="button"+ aria-label={label}+ title={label}+ disabled={disabled}+ onClick={onClick}+ className="inline-flex size-5 items-center justify-center rounded text-ds-text-subtle hover:bg-ds-surface-white hover:text-ds-text-darker disabled:opacity-35"+ >+ <Icon size={11} weight="bold" />+ </button>+ );+}++/** One line of the events list: what happened, in a few words. */+function eventRowLabel(+ map: SessionMap,+ e: SessionMapEvent,+ ordinals: Map<string, number>+): string {+ if (e.kind === 'user') return `Prompt · ${e.chars ?? 0} chars`;+ const d = describeEvent(map, e, ordinals).title;+ if (!e.err) return d;+ const k = kindStyle(e).label;+ return e.kind === 'error'+ ? `${k} · ${d}`+ : `Failed ${k.toLowerCase()} · ${d}`;+}++const markColor = (e: SessionMapEvent, c: Category) =>+ c === 'out'+ ? kindMeta(e.vcs?.action === 'pr_create' ? 'pr_create' : e.kind).color+ : CATEGORY_COLOR[c];++/**+ * The events list, opened from the dock's "List" button: every event in the+ * selected categories, in time order. It floats above the dock (over the map)+ * rather than pushing the layout; Escape or × closes it. Clicking a row pins+ * the event; hovering one highlights its mark on the timeline.+ */+export function EventsPanel({+ map,+ rows,+ selected,+ ordinals,+ pinned,+ onPin,+ onHover,+ onClose,+}: {+ map: SessionMap;+ rows: readonly number[];+ /** the dock's selected categories (each row's swatch follows them) */+ selected: ReadonlySet<Category>;+ ordinals: Map<string, number>;+ pinned: number | null;+ onPin: (i: number) => void;+ onHover: (i: number | null) => void;+ onClose: () => void;+}) {+ const boxRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const onKey = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape') onClose();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [onClose]);+ // Bring the pinned row into view when the list opens or the pin moves.+ useEffect(() => {+ const box = boxRef.current;+ const row = box?.querySelector<HTMLElement>('[aria-selected="true"]');+ if (box && row) box.scrollTop = Math.max(0, row.offsetTop - 60);+ }, [pinned]);+ const startedAt = map.session.startedAt;+ return (+ <div className="absolute bottom-full right-3 z-30 mb-1.5 flex max-h-[340px] w-[min(560px,90%)] flex-col rounded-lg border border-ds-border-default bg-ds-surface-white shadow-lg">+ <div className="flex items-center gap-2 border-b border-ds-border-subtlest px-3 py-2">+ <span className="ds-text-body-xs-semibold text-ds-text-darker">+ {rows.length.toLocaleString()} events+ </span>+ <span className="ds-text-body-xs-medium text-ds-text-subtle">+ categories follow the chips · click to pin on the timeline+ </span>+ <span className="flex-1" />+ <button+ type="button"+ onClick={onClose}+ aria-label="Close the events list (Escape)"+ className="inline-flex size-6 items-center justify-center rounded text-ds-text-subtle hover:bg-ds-gray-subtlest hover:text-ds-text-darker"+ >+ <X size={14} />+ </button>+ </div>+ <div+ ref={boxRef}+ role="listbox"+ aria-label="Session events"+ className="relative min-h-0 flex-1 overflow-y-auto overscroll-contain"+ onMouseLeave={() => onHover(null)}+ >+ {rows.length ? (+ rows.map((i) => {+ const e = map.events[i];+ const c = displayCategory(e, selected);+ const sel = pinned === i;+ return (+ <button+ key={i}+ type="button"+ role="option"+ aria-selected={sel}+ onClick={() => onPin(i)}+ onMouseEnter={() => onHover(i)}+ onFocus={() => onHover(i)}+ className={cn(+ 'grid w-full grid-cols-[44px_10px_minmax(0,1fr)_40px_64px] items-center gap-2 border-b border-ds-border-subtlest px-3 py-1 text-left text-xs hover:bg-ds-gray-subtlest',+ sel && 'bg-ds-brand-lightest'+ )}+ >+ <span className="font-mono text-[11px] text-ds-text-subtle">+ {clockAt(startedAt, e.t).slice(0, 5)}+ </span>+ <span+ aria-hidden+ className={cn(+ 'size-2 rounded-sm',+ c === 'out' && 'rotate-45 scale-90'+ )}+ style={{ background: markColor(e, c) }}+ />+ <span className="truncate text-ds-text-default">+ {eventRowLabel(map, e, ordinals)}+ </span>+ <span className="truncate text-[11px] text-ds-text-subtle">+ {typeof e.task === 'number' ? `T${e.task}` : ''}+ </span>+ <span className="truncate text-[11px] text-ds-text-subtle">+ {e.agent === 'main'+ ? 'main'+ : `Sub ${ordinals.get(e.agent ?? '') ?? ''}`}+ </span>+ </button>+ );+ })+ ) : (+ <p className="px-3 py-4 ds-text-body-xs-medium text-ds-text-subtle">+ No events in the selected categories in this scope. Switch a chip+ on.+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/viewer/src/explorer/TimelineTooltip.tsx b/viewer/src/explorer/TimelineTooltip.tsxnew file mode 100644index 0000000..812b50e--- /dev/null+++ b/viewer/src/explorer/TimelineTooltip.tsx@@ -0,0 +1,72 @@+import type { SessionMap } from '@/core/schema';+import { cn } from '@/lib/utils';+import { kindStyle } from '@/core/eventColors';+import { clockAt, describeEvent } from '@/core/sessionMapModel';+import { detailRows } from '@/core/sessionSignals';++/** The hover card of a timeline mark (drawn outside the lane scrollport). */+export function TimelineTooltip({+ map,+ i,+ cumCost,+ ordinals,+ left,+ top,+}: {+ map: SessionMap;+ i: number;+ cumCost: Float64Array;+ ordinals: Map<string, number>;+ left: number;+ top: number;+}) {+ const ev = map.events[i];+ const K = kindStyle(ev);+ const D = describeEvent(map, ev, ordinals);+ const rows = detailRows(map, i, cumCost, ordinals, true);+ return (+ <div+ role="tooltip"+ className="pointer-events-none absolute z-20 w-[252px] rounded-lg border border-ds-border-subtlest bg-ds-surface-white p-2.5 shadow-md"+ style={{ left, top, transform: 'translateY(calc(-100% - 10px))' }}+ >+ <div className="flex items-center gap-1.5 ds-text-body-xs-semibold text-ds-text-darker">+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{ background: K.color }}+ />+ <span className="truncate">{D.title}</span>+ <span className="ml-auto shrink-0 font-mono ds-text-body-xs-medium text-ds-text-subtle">+ #{i} · {clockAt(map.session.startedAt, ev.t)}+ </span>+ </div>+ {ev.kind !== 'llm' && D.detail ? (+ <div className="mt-1 break-all ds-text-body-xs-medium text-ds-text-subtle">+ {D.detail}+ </div>+ ) : null}+ {rows.length ? (+ <dl className="mt-1.5 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 ds-text-body-xs-medium">+ {rows.map((r) => (+ <div key={r.k} className="contents">+ <dt className="text-ds-text-subtle">{r.k}</dt>+ <dd+ className={cn(+ 'text-right font-mono',+ r.tone === 'bad'+ ? 'text-ds-danger-default'+ : r.tone === 'warn'+ ? 'text-ds-warning-default'+ : 'text-ds-text-darker'+ )}+ >+ {r.v}+ </dd>+ </div>+ ))}+ </dl>+ ) : null}+ </div>+ );+}diff --git a/viewer/src/explorer/reviewSample.test.ts b/viewer/src/explorer/reviewSample.test.tsnew file mode 100644index 0000000..376930e--- /dev/null+++ b/viewer/src/explorer/reviewSample.test.ts@@ -0,0 +1,66 @@+import { readFileSync } from 'node:fs';+import { describe, expect, it } from 'vitest';+import { SAMPLE_COMMENTS } from './reviewSample';++/**+ * The sample comments cite step numbers and files from the bundled demo+ * session, and "See sample" puts the reader on that very session. If the+ * demo is regenerated and a step moves, a citation here becomes a lie that+ * anyone can check by scrubbing the timeline. These tests are what stop+ * that happening quietly.+ */+interface DemoMap {+ files: { id: number; path: string }[];+ tasks: { name: string; startSeq: number; endSeq: number }[];+ events: {+ seq: number;+ kind: string;+ tool?: string;+ targets?: { file?: number; touch?: string }[];+ }[];+}++const demo = JSON.parse(+ readFileSync('public/demo/claude-code-rate-limit.json', 'utf8')+) as DemoMap;++const bySeq = new Map(demo.events.map((e) => [e.seq, e]));+const pathOf = (id: number | undefined) =>+ demo.files.find((f) => f.id === id)?.path;+const taskAt = (seq: number) =>+ demo.tasks.find((t) => seq >= t.startSeq && seq <= t.endSeq)?.name;++describe('the sample comments are anchored in the demo session', () => {+ it.each(SAMPLE_COMMENTS)('$file $line', (c) => {+ const edit = bySeq.get(c.editSeq);+ expect(edit, `step #${c.editSeq} is in the demo map`).toBeDefined();+ expect(edit?.kind, `step #${c.editSeq} is an edit`).toBe('edit');+ // The comment is on the file that edit actually touched.+ expect(edit?.targets?.map((t) => pathOf(t.file))).toContain(c.file);+ // And it is filed under the task that edit falls in.+ expect(taskAt(c.editSeq)).toBe(c.task);+ });++ it('cites only steps the demo session has, in order', () => {+ for (const c of SAMPLE_COMMENTS) {+ const seqs = c.path.map((s) => s.seq);+ expect(seqs).toEqual([...seqs].sort((a, b) => a - b));+ for (const s of seqs) expect(bySeq.has(s)).toBe(true);+ // The path ends at the edit the comment is attributed to.+ expect(seqs).toContain(c.editSeq);+ }+ });++ it('calls a ghost only on a file the session never touched', () => {+ const touched = new Set(demo.files.map((f) => f.path));+ for (const c of SAMPLE_COMMENTS) {+ if (!c.ghost) continue;+ const named = c.ghost.split(' ')[0];+ expect(touched.has(named), `${named} is absent from the map`).toBe(false);+ }+ });++ it('shows more than one issue', () => {+ expect(SAMPLE_COMMENTS.length).toBeGreaterThan(1);+ });+});diff --git a/viewer/src/explorer/reviewSample.ts b/viewer/src/explorer/reviewSample.tsnew file mode 100644index 0000000..890c2c6--- /dev/null+++ b/viewer/src/explorer/reviewSample.ts@@ -0,0 +1,158 @@+/**+ * The invented review comments shown behind the locked block's glass.+ *+ * Invented, but not arbitrary: every step number, file and task here is a+ * real one from the bundled demo session (`scripts/make-demo.mjs`, the+ * `acme/api` rate-limit session, PR #142), because "See sample" swaps the+ * viewer onto exactly that session. A reader who opens the map can find+ * every step cited below. `reviewSample.test.ts` checks that against the+ * demo document, so the two cannot drift apart silently.+ *+ * Nothing here is a claim about the user's own sessions.+ */++/**+ * How a fix reaches the agent. All four are build-time routes: the rule is+ * compiled in before the session starts rather than injected into a running+ * one, which is why an audit can say what each session was given and the+ * holdout can be a real control.+ */+export const DELIVERIES = [+ {+ id: 'rules',+ label: 'Rules file',+ detail: 'Compiled into CLAUDE.md when the session is built',+ },+ {+ id: 'skill',+ label: 'Skill',+ detail: 'Bundled as a skill; loads when the task type matches',+ },+ {+ id: 'mcp',+ label: 'MCP server',+ detail: 'Registered at build; retrieved when trigger paths match',+ },+ {+ id: 'hook',+ label: 'Pre-edit hook',+ detail: 'Installed at build; runs before edits to trigger paths',+ },+] as const;++export type DeliveryId = (typeof DELIVERIES)[number]['id'];++export interface SampleFix {+ /** the route this one is best delivered by, pre-selected in the dialog */+ delivery: DeliveryId;+ /** the rule itself, in the words the agent would receive */+ rule: string;+ /** where it fires */+ trigger: string;+}++export interface SampleStep {+ /** the event index in the demo map */+ seq: number;+ who: string;+ what: string;+}++export interface SampleComment {+ file: string;+ line: string;+ author: string;+ /** the reviewer's words */+ text: string;+ /** the edit the comment is attributed to */+ editSeq: number;+ /** the demo session's task that edit falls in */+ task: string;+ /** what the detector called it */+ flagged: string;+ cause: string;+ /** why the agent did it, in one sentence */+ why: string;+ /** the steps from the first cause to the flagged edit */+ path: SampleStep[];+ /** a file the work needed and never opened */+ ghost?: string;+ learning: string;+ /** how many other sessions landed in the same cluster */+ alsoIn: number;+ /** what "Fix now" would ship, and how */+ fix: SampleFix;+}++export const SAMPLE_COMMENTS: readonly SampleComment[] = [+ {+ file: 'src/middleware/rateLimit.ts',+ line: 'L64',+ author: 'sample-reviewer-1',+ text: 'This keeps the bucket in process memory. Behind three pods a client gets three times the limit.',+ editSeq: 31,+ task: 'Add a token-bucket rate limiter',+ flagged: 'In-memory state behind a load balancer',+ cause: 'Convention never read',+ why: 'src/config/env.ts was read at #12 and edited at #24, both times without reaching for a shared store.',+ path: [+ { seq: 12, who: 'Main', what: 'Read src/config/env.ts' },+ { seq: 21, who: 'Main', what: 'Write src/middleware/rateLimit.ts' },+ { seq: 31, who: 'Main', what: 'Edit src/middleware/rateLimit.ts L64' },+ ],+ ghost: 'CONVENTIONS.md states the shared-store rule and was never opened.',+ learning: 'L-14',+ alsoIn: 4,+ fix: {+ delivery: 'rules',+ rule: 'Rate limiters and counters keep their state in the shared store named by REDIS_URL in src/config/env.ts, never in process memory.',+ trigger: 'Every session in this repo',+ },+ },+ {+ file: 'src/routes/orders.ts',+ line: 'L38',+ author: 'sample-reviewer-2',+ text: 'The 429 here skips the Retry-After header our clients back off on.',+ editSeq: 40,+ task: 'Add a token-bucket rate limiter',+ flagged: '429 without Retry-After',+ cause: 'Spec read, never applied',+ why: 'The docs lookup at #17 returned the rate-limit spec; the handler was edited 23 steps later without it.',+ path: [+ { seq: 15, who: 'Main', what: 'Read src/routes/orders.ts' },+ { seq: 17, who: 'Main', what: 'search_docs rate-limit spec' },+ { seq: 40, who: 'Main', what: 'Edit src/routes/orders.ts L38' },+ ],+ learning: 'L-9',+ alsoIn: 2,+ fix: {+ delivery: 'skill',+ rule: 'A 429 response carries Retry-After. Check the rate-limit spec before editing a route handler that can reject.',+ trigger: 'Tasks that touch src/routes/**',+ },+ },+ {+ file: 'test/rateLimit.test.ts',+ line: 'L12',+ author: 'sample-reviewer-1',+ text: 'This asserts the window the limiter had before you changed it, so it passes either way.',+ editSeq: 26,+ task: 'Add a token-bucket rate limiter',+ flagged: 'Test asserts the pre-edit behaviour',+ cause: 'Verified before the last edit',+ why: 'The limiter changed at #31, after the test was written at #26; npm test at #33 passed on the old assertion.',+ path: [+ { seq: 26, who: 'Main', what: 'Write test/rateLimit.test.ts L12' },+ { seq: 31, who: 'Main', what: 'Edit src/middleware/rateLimit.ts L64' },+ { seq: 33, who: 'Main', what: 'npm test' },+ ],+ learning: 'L-22',+ alsoIn: 1,+ fix: {+ delivery: 'hook',+ rule: 'After editing a module, re-run the tests that cover it before reporting it verified -- a test written earlier may still assert the old behaviour.',+ trigger: 'Before edits to src/middleware/**',+ },+ },+];diff --git a/viewer/src/explorer/useEventCategories.ts b/viewer/src/explorer/useEventCategories.tsnew file mode 100644index 0000000..be8f857--- /dev/null+++ b/viewer/src/explorer/useEventCategories.ts@@ -0,0 +1,52 @@+import { useCallback, useMemo, useState } from 'react';+import {+ parseAsBoolean,+ parseAsString,+ useQueryStates,+} from 'nuqs';+import {+ parseCategories,+ pickHistory,+ serializeCategories,+ type Category,+} from '@/core/sessionLayout';++/** `ev`: the chip selection; `ctx`: the Context lane. */+const CATEGORY_PARAMS = {+ ev: parseAsString,+ ctx: parseAsBoolean,+};++/**+ * The dock's category selection and the Context lane toggle, in the URL so+ * reload / share keep them. Not part of the replay scope: changing them+ * never remounts the replay (playback keeps its place).+ */+export function useEventCategories() {+ const [q, setQ] = useQueryStates(CATEGORY_PARAMS);+ const selected = useMemo(() => parseCategories(q.ev), [q.ev]);+ const context = q.ctx ?? false;+ // Click order this visit (see pickHistory): what "the last chip" means.+ const [picks, setPicks] = useState<Category[]>([]);+ const setSelected = useCallback(+ (next: ReadonlySet<Category>) => {+ setPicks((h) => pickHistory(h, selected, next));+ void setQ({+ ev: serializeCategories(next),+ ctx: context || null,+ });+ },+ [setQ, context, selected]+ );+ const setContext = useCallback(+ (on: boolean) =>+ void setQ({+ ctx: on || null,+ ev: serializeCategories(selected),+ }),+ [setQ, selected]+ );+ return { selected, setSelected, picks, context, setContext };+}++export type EventCategories = ReturnType<typeof useEventCategories>;diff --git a/viewer/src/explorer/useExplorerScope.ts b/viewer/src/explorer/useExplorerScope.tsnew file mode 100644index 0000000..63a4da5--- /dev/null+++ b/viewer/src/explorer/useExplorerScope.ts@@ -0,0 +1,153 @@+import { useCallback, useEffect, useMemo } from 'react';+import { useQueryStates } from 'nuqs';+import type { SessionMap } from '@/core/schema';+import { agentLabel, deriveLensDoc, subagentOrdinal } from '@/core/sessionMapModel';+import { orderedSubagents, taskSummaries } from '@/core/sessionLayout';+import {+ CLEAR_SCOPE_PARAMS,+ SCOPE_PARAMS,+ deriveScopeDoc,+ modelUsage,+ normalizeScope,+ scopeForSession,+ sessionTasks,+ stampTasks,+ withoutSrcSeq,+ type Scope,+} from '@/core/sessionScope';++export type SetScope = (+ next: Scope | ((prev: Scope) => Scope),+ /** also close the agent lens (an error jump may target another agent) */+ opts?: { clearLens?: boolean }+) => void;++const isEmptyScope = (s: Scope, sub: string | null) =>+ s.task == null && s.model == null && sub == null;++/** The agent lens (`?sub=<agentId>`): an id this session does not have reads+ * as the main agent. */+function resolveLens(map: SessionMap, subParam: string | null): string {+ if (!subParam || subParam === 'main') return 'main';+ return map.agents.some((a) => a.id === subParam) ? subParam : 'main';+}++/**+ * The agent lens and the scope (task window,+ * model), all in the URL: the full map is task-stamped, scoped+ * via `deriveScopeDoc`, then lensed via `deriveLensDoc`. `key` changes with+ * any of them so the replay body remounts (its lazy playback init must+ * re-run against the new event count).+ */+export function useExplorerScope(sessionId: string, rawMap: SessionMap) {+ // `srcSeq` is the viewer's own; one carried in by the document is dropped+ // here, before any derivation could pass it on (`withoutSrcSeq`).+ const fullMap = useMemo(() => stampTasks(withoutSrcSeq(rawMap)), [rawMap]);+ // Scope lives in the URL so reload, share and Back keep it.+ const [params, setParams] = useQueryStates(SCOPE_PARAMS);+ // Scope is bound to the session it was set on, so a search or window+ // change that swaps the effective session does not carry the old scope+ // over; a stale scope reads empty here and is cleared from the URL.+ const {+ scope: urlScope,+ sub: subParam,+ stale,+ unowned,+ } = useMemo(() => scopeForSession(params, sessionId), [params, sessionId]);+ const ordinals = useMemo(() => subagentOrdinal(fullMap), [fullMap]);+ const tasks = useMemo(() => sessionTasks(fullMap).tasks, [fullMap]);+ const models = useMemo(() => modelUsage(fullMap), [fullMap]);+ // A task or model this session does not have reads as unset (like `?sub=`).+ const scope = useMemo(+ () => normalizeScope(urlScope, tasks, models),+ [urlScope, tasks, models]+ );+ const lens = resolveLens(fullMap, subParam);+ const sub = lens === 'main' ? null : lens;+ useEffect(() => {+ if (stale) void setParams(CLEAR_SCOPE_PARAMS);+ // an unowned deep link belongs to the first session it is shown with+ else if (unowned) void setParams({ ss: sessionId });+ // a stale task / model is dropped from the URL (replace, no history entry)+ else if (scope !== urlScope)+ void setParams({+ task: scope.task,+ model: scope.model,+ ss: isEmptyScope(scope, sub) ? null : sessionId,+ });+ }, [stale, unowned, scope, urlScope, sub, sessionId, setParams]);++ const setScope = useCallback<SetScope>(+ (next, opts) => {+ const s1 = typeof next === 'function' ? next(scope) : next;+ // An agent with nothing in the new scope would land on an empty replay:+ // close its lens (the filter that was just changed wins).+ const dropLens =+ sub != null &&+ (opts?.clearLens ||+ !deriveScopeDoc(fullMap, s1).events.some((e) => e.agent === sub));+ void setParams({+ task: s1.task,+ model: s1.model,+ ...(dropLens ? { sub: null } : {}),+ ss: isEmptyScope(s1, dropLens ? null : sub) ? null : sessionId,+ });+ },+ [scope, setParams, sessionId, sub, fullMap]+ );+ const setLens = useCallback(+ (id: string) => {+ const nextSub = id === 'main' ? null : id;+ void setParams({+ sub: nextSub,+ ss: isEmptyScope(scope, nextSub) ? null : sessionId,+ });+ },+ [scope, setParams, sessionId]+ );++ const clearAll = useCallback(+ () => void setParams(CLEAR_SCOPE_PARAMS),+ [setParams]+ );++ const subs = useMemo(+ () => orderedSubagents(fullMap, ordinals),+ [fullMap, ordinals]+ );+ const taskSums = useMemo(() => taskSummaries(fullMap), [fullMap]);+ const scoped = useMemo(+ () => deriveScopeDoc(fullMap, scope),+ [fullMap, scope]+ );+ const map = useMemo(() => {+ // A lens on an agent with nothing in this scope shows an empty replay,+ // not the whole scope (deriveLensDoc falls back to its input).+ if (lens !== 'main' && !scoped.events.some((e) => e.agent === lens))+ return { ...scoped, events: [], agents: [], prs: [] };+ return deriveLensDoc(scoped, lens);+ }, [scoped, lens]);+ const lensLabel =+ lens === 'main' ? null : agentLabel(fullMap, lens, ordinals);+ const key = `${lens}|${scope.task ?? ''}|${scope.model ?? ''}`;+ return {+ key,+ fullMap,+ scopedMap: scoped,+ map,+ scope,+ setScope,+ lens,+ sub,+ setLens,+ clearAll,+ lensLabel,+ ordinals,+ tasks,+ models,+ subs,+ taskSums,+ };+}++export type ExplorerScope = ReturnType<typeof useExplorerScope>;diff --git a/viewer/src/explorer/usePlaybackWindow.ts b/viewer/src/explorer/usePlaybackWindow.tsnew file mode 100644index 0000000..8a7ee5d--- /dev/null+++ b/viewer/src/explorer/usePlaybackWindow.ts@@ -0,0 +1,116 @@+import {+ useCallback,+ useEffect,+ useMemo,+ useReducer,+ type KeyboardEvent,+} from 'react';+import type { SessionMap, SessionMapEvent } from '@/core/schema';+import { initialPlayback, playbackReducer, replayKeyAction } from '@/core/playback';+import { MAP_RADIUS } from '@/core/mapGeometry';+import {+ buildTree,+ cumulativeCost,+ errSource,+ eventNodeRefs,+ fileCoverage,+ findNext,+ findNextWhere,+ initialPlayhead,+ layoutTree,+ reviewMetrics,+ subagentOrdinal,+ type ErrorSource,+ type JumpKind,+} from '@/core/sessionMapModel';+import { sessionSignals } from '@/core/sessionSignals';++/** Everything the map, timeline and panels derive from the replayed map. */+export function useMapModel(map: SessionMap) {+ return useMemo(() => {+ const tree = buildTree(map);+ const nodes = layoutTree(tree, MAP_RADIUS);+ return {+ tree,+ nodes,+ refs: eventNodeRefs(map, tree),+ cumCost: cumulativeCost(map.events),+ ordinals: subagentOrdinal(map),+ review: reviewMetrics(map),+ coverage: fileCoverage(map),+ signals: sessionSignals(map),+ };+ }, [map]);+}++export type MapModel = ReturnType<typeof useMapModel>;++/**+ * The replay's playback window: the reducer (lazily loaded once per mount+ * against `map`'s event count), the rAF loop while playing, seeking/jumping,+ * and the replay region's keyboard shortcuts.+ */+export function usePlaybackWindow(map: SessionMap) {+ const [pb, dispatch] = useReducer(playbackReducer, map, (m) =>+ playbackReducer(initialPlayback, {+ type: 'load',+ n: m.events.length,+ start: initialPlayhead(m.events),+ })+ );++ // rAF loop while playing; the reducer turns elapsed ms into events.+ useEffect(() => {+ if (!pb.playing) return;+ let raf = 0;+ let last = 0;+ const frame = (t: number) => {+ const dt = last ? t - last : 0;+ last = t;+ if (dt) dispatch({ type: 'tick', dtMs: dt });+ raf = requestAnimationFrame(frame);+ };+ raf = requestAnimationFrame(frame);+ return () => cancelAnimationFrame(raf);+ }, [pb.playing]);++ const seek = useCallback(+ (index: number) => dispatch({ type: 'seek', index }),+ []+ );+ const jumpWhere = useCallback(+ (test: (e: SessionMapEvent) => boolean) => {+ const i = findNextWhere(map.events, pb.p, test);+ if (i != null) dispatch({ type: 'seek', index: i });+ },+ [map.events, pb.p]+ );+ const jump = useCallback(+ (kind: JumpKind) => {+ const i = findNext(map.events, pb.p, kind);+ if (i != null) dispatch({ type: 'seek', index: i });+ },+ [map.events, pb.p]+ );+ const jumpSource = useCallback(+ (src: ErrorSource) => jumpWhere((e) => e.err && errSource(e) === src),+ [jumpWhere]+ );++ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {+ const t = e.target as HTMLElement;+ if (t.closest('input, textarea, [contenteditable="true"]')) return;+ const action = replayKeyAction(e);+ if (!action) return;+ if (action.type === 'jump') {+ jump(action.kind);+ return;+ }+ e.preventDefault();+ dispatch(action);+ };++ return { pb, dispatch, seek, jump, jumpSource, onKeyDown };+}++export type PlaybackWindow = ReturnType<typeof usePlaybackWindow>;diff --git a/viewer/src/hooks/useDebounce.ts b/viewer/src/hooks/useDebounce.tsnew file mode 100644index 0000000..632445d--- /dev/null+++ b/viewer/src/hooks/useDebounce.ts@@ -0,0 +1,12 @@+import { useEffect, useState } from 'react';++export function useDebounce<T>(value: T, delay = 300): T {+ const [debounced, setDebounced] = useState(value);++ useEffect(() => {+ const id = setTimeout(() => setDebounced(value), delay);+ return () => clearTimeout(id);+ }, [value, delay]);++ return debounced;+}diff --git a/viewer/src/lib/utils.ts b/viewer/src/lib/utils.tsnew file mode 100644index 0000000..3382242--- /dev/null+++ b/viewer/src/lib/utils.ts@@ -0,0 +1,41 @@+import { clsx, type ClassValue } from 'clsx';+import { extendTailwindMerge } from 'tailwind-merge';++const NAMESPACES = [+ 'gray',+ 'border',+ 'warning',+ 'brand',+ 'text',+ 'success',+ 'danger',+] as const;+const SCALE = [+ 'lightest',+ 'subtlest',+ 'subtler',+ 'subtle',+ 'default',+ 'darker',+ 'darkest',+];+const SURFACES = ['white', 'off-white', 'dark'];++const dsClasses = (prefix: 'text' | 'bg' | 'border' | 'divide') => [+ ...NAMESPACES.flatMap((ns) => SCALE.map((s) => `${prefix}-ds-${ns}-${s}`)),+ ...SURFACES.map((s) => `${prefix}-ds-surface-${s}`),+];++const customTwMerge = extendTailwindMerge({+ extend: {+ classGroups: {+ 'text-color': dsClasses('text'),+ 'bg-color': dsClasses('bg'),+ 'border-color': dsClasses('border'),+ },+ },+});++export function cn(...inputs: ClassValue[]) {+ return customTwMerge(clsx(inputs));+}diff --git a/viewer/src/main.tsx b/viewer/src/main.tsxnew file mode 100644index 0000000..7d0b554--- /dev/null+++ b/viewer/src/main.tsx@@ -0,0 +1,20 @@+import { StrictMode } from 'react';+import { createRoot } from 'react-dom/client';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { NuqsAdapter } from 'nuqs/adapters/react';+import { App } from './App';+import './styles/index.css';++const queryClient = new QueryClient({+ defaultOptions: { queries: { refetchOnWindowFocus: false } },+});++createRoot(document.getElementById('root')!).render(+ <StrictMode>+ <QueryClientProvider client={queryClient}>+ <NuqsAdapter>+ <App />+ </NuqsAdapter>+ </QueryClientProvider>+ </StrictMode>+);diff --git a/viewer/src/styles/index.css b/viewer/src/styles/index.cssnew file mode 100644index 0000000..fe45cff--- /dev/null+++ b/viewer/src/styles/index.css@@ -0,0 +1,342 @@+/* Design tokens (ds-*) for the Session Explorer, light + dark. Theme is the+ `.dark` class on <html>, set from prefers-color-scheme (or ?theme=) by the+ inline script in index.html. */+@import '@fontsource-variable/inter';+@import '@fontsource-variable/jetbrains-mono';++:root {+ color-scheme: light;+ --font-inter: 'Inter Variable', 'Inter', ui-sans-serif, system-ui, sans-serif;+ --font-jetbrains-mono: 'JetBrains Mono Variable', 'JetBrains Mono';+ --font-mono: 'JetBrains Mono Variable', ui-monospace, monospace;+}++.dark {+ color-scheme: dark;+}++@tailwind base;+@tailwind components;+@tailwind utilities;++@layer base {+ :root {+ /* Easing - stronger than browser built-ins; purposeful curves */+ --motion-ease-out: cubic-bezier(0.23, 1, 0.32, 1); /* entries, reveals */++ /* Duration scale - UI animations MUST stay ≤300ms */+ --motion-dur-instant: 80ms; /* press feedback, immediate toggle */++ --muted: 210 40% 96.1%;++ --border: 214.3 31.8% 91.4%;++ --radius: 0.5rem;++ /* Primitives */+ --primitive-brand-green-100: #f6fbed;+ --primitive-brand-green-200: #e7f2d4;+ --primitive-brand-green-300: #d6e7bb;+ --primitive-brand-green-400: #bdd29b;+ --primitive-brand-green-500: #9ab175;+ --primitive-brand-green-600: #72884e;+ --primitive-brand-green-700: #56653e;+ --primitive-brand-green-800: #3a422c;+ --primitive-brand-green-900: #262a1f;+ --primitive-brand-green-950: #13150f;+ --primitive-white-off-white: #faf9f5;+ --primitive-white-solid: #ffffff;+ --primitive-gray-50: #f7f7f7;+ --primitive-gray-100: #f5f4f5;+ --primitive-gray-200: #dbdbdb;+ --primitive-gray-300: #bdbdbd;+ --primitive-gray-400: #989898;+ --primitive-gray-500: #7b7b7b;+ --primitive-gray-800: #404040;+ --primitive-gray-900: #2c2c2c;+ --primitive-purple-100: #ece8ff;+ --primitive-purple-700: #6a1be0;+ --primitive-red-100: #ffe5e1;+ --primitive-red-300: #ffaea2;+ --primitive-red-600: #e23a20;+ --primitive-red-700: #cc3018;+ --primitive-red-900: #82281a;+ --primitive-orange-50: #fffdf7;+ --primitive-orange-100: #fffaeb;+ --primitive-orange-700: #e06800;+ --primitive-orange-800: #a34b09;+ --primitive-green-50: #f2fcf1;+ --primitive-green-100: #defbdd;+ --primitive-green-600: #1c9e1b;+ --primitive-green-900: #19621a;+ --primitive-blue-700: #194ad2;++ /* Design system semantic color tokens - aliases over primitives.+ Primitives flip in `.dark`, so these auto-flip too. Mirrors the+ `ds.*` mapping in tailwind.config.ts so `var(--ds-text-subtle)` works+ in JS / inline styles / SVG fill the same as the `text-ds-text-subtle`+ Tailwind utility. */+ --ds-gray-subtlest: var(--primitive-gray-100);+ --ds-gray-subtler: var(--primitive-gray-300);++ --ds-border-subtler: var(--primitive-gray-200);+ --ds-border-default: var(--primitive-gray-800);+ --ds-border-darker: var(--primitive-gray-900);++ --ds-text-subtler: var(--primitive-gray-300);+ --ds-text-subtle: var(--primitive-gray-500);+ --ds-text-default: var(--primitive-gray-800);+ --ds-text-darker: var(--primitive-gray-900);++ --ds-surface-white: var(--primitive-white-solid);++ /* The subtly brand-tinted RAISED surface (a nested card, a hover fill, a+ tinted callout). SELECTED per mode, because the brand ramp inverts: in+ dark, brand-green-100 is darker than the card it sits on, so dark mode+ takes its own value one clear step above the card. */+ --ds-brand-lightest: var(--primitive-brand-green-100);+ --ds-brand-subtlest: var(--primitive-brand-green-200);+ --ds-brand-subtler: var(--primitive-brand-green-500);+ --ds-brand-subtle: var(--primitive-brand-green-700);+ --ds-brand-default: var(--primitive-brand-green-800);++ /* SELECTED per mode, same reasoning as --ds-success-subtlest below: in+ dark, orange-100 is a saturated warm brown that made the warning chip+ the loudest thing on a card; orange-50 recedes and keeps AA contrast. */+ --ds-warning-subtlest: var(--primitive-orange-100);+ --ds-warning-default: var(--primitive-orange-700);++ /* Success was the only semantic family missing its first rung, so anything+ wanting a subtle success tint had to reach for `-subtler` and rendered a+ rung heavier than every sibling variant. Most visible on Badge in dark+ mode, where `-subtler` resolves to a solid #19621a and the chip was the+ loudest thing in the row.++ SELECTED per mode, not inverted -- same reasoning as the chart series+ block in `.dark`. The green primitive ramp inverts across a different+ lightness band than red and purple do, so one primitive cannot serve both+ modes here: green-50 is #f2fcf1 in light, which is the page background+ and leaves the chip with no container at all. Light takes green-100 for a+ readable tint, dark takes green-50 for a properly recessed one. */+ --ds-success-subtlest: var(--primitive-green-100);+ --ds-success-default: var(--primitive-green-600);++ --ds-danger-default: var(--primitive-red-600);++ --ds-purple-subtlest: var(--primitive-purple-100);+ --ds-purple-default: var(--primitive-purple-700);++ --ds-blue-default: var(--primitive-blue-700);++ /* Chart series palette (`--ds-series-1..8`, categorical identity only).+ Fixed slot order, assigned in sequence, never cycled and never+ re-ordered. The slots sit in one mid-chroma band around the brand sage+ so any subset agrees with the rest of the page. Hue ORDER is identical+ across themes so a series keeps its identity when the theme flips; only+ the lightness step is re-picked per theme. */+ --ds-series-1: #6f8a4b;+ --ds-series-2: #3d6e92;+ --ds-series-3: #8b4e99;+ --ds-series-4: #8a6b21;+ --ds-series-5: #a35638;+ --ds-series-6: #2f7f76;+ --ds-series-7: #5b569e;+ --ds-series-8: #9e4560;+ --ds-series-other: var(--primitive-gray-400);+ /* Session Explorer prompt marks (lime): identity-free, so not a series. */+ --ds-session-prompt: #65a30d;++ /* Chart chrome - one place for grid, axis ink and hover cursor. */+ --ds-chart-grid: var(--primitive-gray-100);+ --ds-chart-axis: var(--primitive-gray-500);+ --ds-chart-cursor: var(--ds-brand-subtler);++ /* Neutral warm-stone intensity ramp (few -> many): darkness only, no hue,+ so it never reads as a status colour. Tuned per theme. */+ --ds-heatmap-1: #e2e0dd;+ --ds-heatmap-2: #c2bfba;+ --ds-heatmap-3: #9b9791;+ --ds-heatmap-4: #6e6a64;+ --ds-heatmap-5: #45423d;++ /* Design system typography tokens (text/body, text/title, text/code) */+ --ds-font-body: 'Inter Variable', 'Inter', ui-sans-serif, system-ui, sans-serif;+ --ds-font-code: var(--font-jetbrains-mono), ui-monospace, monospace;+ --ds-text-body-xs-medium: 12px;+ --ds-text-body-xs-medium-lh: 16px;+ --ds-text-body-xs-semibold: 12px;+ --ds-text-body-xs-semibold-lh: 16px;+ --ds-text-body-sm-semibold: 14px;+ --ds-text-body-sm-semibold-lh: 1.45;+ }++ .dark {+ /* See the light-mode note: the subtlest success rung is picked per mode.+ In dark, green-100 is #19621a -- a solid mid-green that made the Badge+ read as a filled button rather than a chip. */+ --ds-success-subtlest: var(--primitive-green-50);+ --ds-warning-subtlest: var(--primitive-orange-50);+ --ds-brand-lightest: #1f221b;++ /* Chart series palette - dark mode is SELECTED, not an inversion of the+ light steps: each slot is re-picked inside the dark lightness band and+ re-validated against the dark chart surface (#1B1B1B). Worst adjacent+ pair deuteranopia dE 18.2, normal-vision dE 25.9. Slot order is+ identical to light so a series keeps its identity across themes. */+ --ds-series-1: #a9c084;+ --ds-series-2: #8fb8d8;+ --ds-series-3: #c79bd4;+ --ds-series-4: #dcc48a;+ --ds-series-5: #d89478;+ --ds-series-6: #7fc7be;+ --ds-series-7: #a8a4dc;+ --ds-series-8: #d98fa6;+ --ds-session-prompt: #a3e635;++ /* Activity heatmap - dark-mode neutral stone ramp (dim → bright stone on+ near-black); see the :root block for the light values and rationale. */+ --ds-heatmap-1: #3a3a38;+ --ds-heatmap-2: #55534f;+ --ds-heatmap-3: #78756f;+ --ds-heatmap-4: #9e9b94;+ --ds-heatmap-5: #cac7c0;++ --muted: 0 0% 17%;++ --border: 0 0% 17%;++ /* Primitives, dark mode */+ --primitive-brand-green-100: #13150f;+ --primitive-brand-green-200: #262a1f;+ --primitive-brand-green-300: #3a422c;+ --primitive-brand-green-400: #56653e;+ --primitive-brand-green-500: #72884e;+ --primitive-brand-green-600: #9ab175;+ --primitive-brand-green-700: #bdd29b;+ --primitive-brand-green-800: #d6e7bb;+ --primitive-brand-green-900: #e7f2d4;+ --primitive-brand-green-950: #f6fbed;+ --primitive-white-off-white: #161616;+ --primitive-white-solid: #1b1b1b;+ --primitive-gray-50: #191919;+ --primitive-gray-100: #2a2a2a;+ --primitive-gray-200: #404040;+ --primitive-gray-300: #525252;+ --primitive-gray-400: #656565;+ --primitive-gray-500: #7b7b7b;+ --primitive-gray-800: #dbdbdb;+ --primitive-gray-900: #efeef0;+ /* Purple: dark-mode values of the semantic purple ramp. */+ --primitive-purple-100: #3b2165;+ --primitive-purple-700: #c2b1ff;+ --primitive-red-100: #211412;+ --primitive-red-300: #933f32;+ --primitive-red-600: #e08a7d;+ --primitive-red-700: #e29387;+ --primitive-red-900: #f4d7d3;+ /* Orange + green primitives fully invert in dark mode. */+ --primitive-orange-50: #2a1704;+ --primitive-orange-100: #471e03;+ --primitive-orange-700: #ffc966;+ --primitive-orange-800: #ffe4a3;+ --primitive-green-50: #072c08;+ --primitive-green-100: #19621a;+ --primitive-green-600: #51d850;+ --primitive-green-900: #defbdd;+ /* Blue: brighter in dark so accent text passes AA on dark surfaces. */+ --primitive-blue-700: #b3c6f9;+ }+}++body {+ --ds-font-code: var(--font-jetbrains-mono), ui-monospace, monospace;+ margin: 0;+ font-family: var(--ds-font-body);+ background: var(--primitive-white-off-white);+ color: var(--ds-text-default);+ -webkit-font-smoothing: antialiased;+}++:root {+ /* Drop shadow for tooltips / hover cards. Light: soft, low-opacity+ black so the surface lifts gently off white. Dark: heavier opacity+ so the drop still reads against the near-black surface. */+ --ds-shadow-tooltip:+ 0 8px 16px -4px rgba(15, 15, 15, 0.08),+ 0 4px 8px -4px rgba(15, 15, 15, 0.04);+}++.dark {+ --ds-shadow-tooltip:+ 0 8px 16px -4px rgba(0, 0, 0, 0.55), 0 4px 8px -4px rgba(0, 0, 0, 0.35);+}++/* Global: every native button + role="button" presses on :active, app-wide.+ Opt out with `data-no-tap` on the element. Disabled never presses. */+button:not(:disabled):not([data-no-tap]),+[role='button']:not([aria-disabled='true']):not([data-no-tap]) {+ transition: scale var(--motion-dur-instant) var(--motion-ease-out);+}+button:not(:disabled):not([data-no-tap]):active,+[role='button']:not([aria-disabled='true']):not([data-no-tap]):active {+ scale: 0.97;+}++/* motion-tap - explicit press feedback for clickable non-button elements+ (divs/rows/cards with onClick). Adds color/bg transitions too so hover and+ press feel unified. Uses the same `scale:` property as the global rule. */+.motion-tap {+ transition:+ scale var(--motion-dur-instant) var(--motion-ease-out),+ color 150ms ease,+ background-color 150ms ease,+ border-color 150ms ease,+ opacity 150ms ease;+}+.motion-tap:active:not(:disabled):not([aria-disabled='true']) {+ scale: 0.97;+}++@keyframes widget-skeleton-sheen {+ from {+ background-position: 160% 0;+ }+ to {+ background-position: -60% 0;+ }+}+/* The sheen sits on top of the skeleton's own `bg-muted`, so a gray-500/60%+ band read as a second, much darker bar travelling through every placeholder -+ the "too bright" in a page full of them. Softened to a hint above the base+ fill; the movement still says "data is arriving" without competing with real+ content elsewhere on the screen. */+.widget-skeleton-sheen {+ background-image: linear-gradient(+ 100deg,+ transparent 22%,+ color-mix(in srgb, var(--primitive-gray-400) 26%, transparent) 47%,+ color-mix(in srgb, var(--primitive-gray-400) 26%, transparent) 53%,+ transparent 78%+ );+ background-size: 220% 100%;+ background-repeat: no-repeat;+ animation: widget-skeleton-sheen 1.9s linear infinite;+ animation-delay: calc(var(--skeleton-i, 0) * 0.14s);+}++@media (prefers-reduced-motion: reduce) {+ .motion-tap,+ button,+ [role='button'] {+ transition: none;+ }+ button:active,+ [role='button']:active,+ .motion-tap:active {+ scale: 1;+ }+ .widget-skeleton-sheen {+ animation: none;+ background-position: 50% 0;+ }+}diff --git a/viewer/tailwind.config.ts b/viewer/tailwind.config.tsnew file mode 100644index 0000000..be0de7b--- /dev/null+++ b/viewer/tailwind.config.ts@@ -0,0 +1,465 @@+import tailwindcssAnimate from 'tailwindcss-animate';+import tailwindPlugin from 'tailwindcss/plugin';+import type { Config } from 'tailwindcss';++/** Design token colors mapped to primitive CSS vars. */+const ds = {+ gray: {+ lightest: 'var(--primitive-gray-50)',+ subtlest: 'var(--primitive-gray-100)',+ subtler: 'var(--primitive-gray-300)',+ subtle: 'var(--primitive-gray-500)',+ default: 'var(--primitive-gray-800)',+ darker: 'var(--primitive-gray-900)',+ },+ border: {+ subtlest: 'var(--primitive-gray-100)',+ subtler: 'var(--primitive-gray-200)',+ subtle: 'var(--primitive-gray-500)',+ default: 'var(--primitive-gray-800)',+ darker: 'var(--primitive-gray-900)',+ },+ warning: {+ // Semantic var, not a primitive: this rung is picked per mode. See the+ // note in src/styles/index.css.+ subtlest: 'var(--ds-warning-subtlest)',+ subtler: 'var(--primitive-orange-300)',+ subtle: 'var(--primitive-orange-500)',+ default: 'var(--primitive-orange-700)',+ darker: 'var(--primitive-orange-800)',+ },+ // Chart series palette — categorical identity slots, fixed order.+ // Use for legend swatches / inline series dots; charts read the CSS var+ // directly.+ series: {+ 1: 'var(--ds-series-1)',+ 2: 'var(--ds-series-2)',+ 3: 'var(--ds-series-3)',+ 4: 'var(--ds-series-4)',+ 5: 'var(--ds-series-5)',+ 6: 'var(--ds-series-6)',+ 7: 'var(--ds-series-7)',+ 8: 'var(--ds-series-8)',+ other: 'var(--ds-series-other)',+ },+ brand: {+ // Semantic var, not a primitive: picked per mode so a tinted surface stays+ // ABOVE the card it sits on in both themes. See the note in src/styles/index.css.+ lightest: 'var(--ds-brand-lightest)',+ subtlest: 'var(--primitive-brand-green-200)',+ // The filled chip and its ink. See the note in src/styles/index.css: the pair is+ // chosen for AA in BOTH modes.+ fill: 'var(--primitive-brand-green-400)',+ 'on-fill': 'var(--primitive-brand-green-950)',+ subtler: 'var(--primitive-brand-green-500)',+ subtle: 'var(--primitive-brand-green-700)',+ default: 'var(--primitive-brand-green-800)',+ darker: 'var(--primitive-brand-green-900)',+ },+ text: {+ subtlest: 'var(--primitive-gray-100)',+ subtler: 'var(--primitive-gray-300)',+ subtle: 'var(--primitive-gray-500)',+ default: 'var(--primitive-gray-800)',+ darker: 'var(--primitive-gray-900)',+ },+ success: {+ // Points at the SEMANTIC var, not a primitive, because this rung is picked+ // per mode -- see the note on --ds-success-subtlest in src/styles/index.css. Same+ // shape as the `series` slots below.+ subtlest: 'var(--ds-success-subtlest)',+ subtler: 'var(--primitive-green-100)',+ subtle: 'var(--primitive-green-400)',+ default: 'var(--primitive-green-600)',+ darker: 'var(--primitive-green-900)',+ },+ danger: {+ subtlest: 'var(--primitive-red-100)',+ subtler: 'var(--primitive-red-300)',+ subtle: 'var(--primitive-red-500)',+ default: 'var(--primitive-red-600)',+ darker: 'var(--primitive-red-700)',+ darkest: 'var(--primitive-red-900)',+ },+ surface: {+ // Neutral nested-card surface, picked per mode. See src/styles/index.css.+ raised: 'var(--ds-surface-raised)',+ white: 'var(--primitive-white-solid)',+ 'off-white': 'var(--primitive-white-off-white)',+ // Fixed dark surface (does NOT auto-flip). For toggled-mode surfaces, pair+ // bg-ds-surface-white with dark:bg-ds-surface-dark.+ dark: 'var(--ds-surface-dark)',+ },+ purple: {+ subtlest: 'var(--ds-purple-subtlest)',+ subtler: 'var(--ds-purple-subtler)',+ subtle: 'var(--ds-purple-subtle)',+ default: 'var(--ds-purple-default)',+ darker: 'var(--ds-purple-darker)',+ darkest: 'var(--ds-purple-darkest)',+ },+ blue: {+ subtlest: 'var(--ds-blue-subtlest)',+ subtler: 'var(--ds-blue-subtler)',+ subtle: 'var(--ds-blue-subtle)',+ default: 'var(--ds-blue-default)',+ darker: 'var(--ds-blue-darker)',+ darkest: 'var(--ds-blue-darkest)',+ },+};++const primitive = {+ 'brand-green': {+ 100: 'var(--primitive-brand-green-100)',+ 200: 'var(--primitive-brand-green-200)',+ 300: 'var(--primitive-brand-green-300)',+ 400: 'var(--primitive-brand-green-400)',+ 500: 'var(--primitive-brand-green-500)',+ 600: 'var(--primitive-brand-green-600)',+ 700: 'var(--primitive-brand-green-700)',+ 800: 'var(--primitive-brand-green-800)',+ 900: 'var(--primitive-brand-green-900)',+ 950: 'var(--primitive-brand-green-950)',+ },+ white: {+ 'off-white': 'var(--primitive-white-off-white)',+ solid: 'var(--primitive-white-solid)',+ },+ gray: {+ 50: 'var(--primitive-gray-50)',+ 100: 'var(--primitive-gray-100)',+ 200: 'var(--primitive-gray-200)',+ 300: 'var(--primitive-gray-300)',+ 400: 'var(--primitive-gray-400)',+ 500: 'var(--primitive-gray-500)',+ 600: 'var(--primitive-gray-600)',+ 700: 'var(--primitive-gray-700)',+ 800: 'var(--primitive-gray-800)',+ 900: 'var(--primitive-gray-900)',+ 950: 'var(--primitive-gray-950)',+ },+ purple: {+ 50: 'var(--primitive-purple-50)',+ 100: 'var(--primitive-purple-100)',+ 200: 'var(--primitive-purple-200)',+ 300: 'var(--primitive-purple-300)',+ 400: 'var(--primitive-purple-400)',+ 500: 'var(--primitive-purple-500)',+ 600: 'var(--primitive-purple-600)',+ 700: 'var(--primitive-purple-700)',+ 800: 'var(--primitive-purple-800)',+ 900: 'var(--primitive-purple-900)',+ 950: 'var(--primitive-purple-950)',+ },+ 'soft-purple': {+ 50: 'var(--primitive-soft-purple-50)',+ 100: 'var(--primitive-soft-purple-100)',+ 200: 'var(--primitive-soft-purple-200)',+ 300: 'var(--primitive-soft-purple-300)',+ 400: 'var(--primitive-soft-purple-400)',+ 500: 'var(--primitive-soft-purple-500)',+ 600: 'var(--primitive-soft-purple-600)',+ 700: 'var(--primitive-soft-purple-700)',+ 800: 'var(--primitive-soft-purple-800)',+ 900: 'var(--primitive-soft-purple-900)',+ 950: 'var(--primitive-soft-purple-950)',+ },+ red: {+ 100: 'var(--primitive-red-100)',+ 200: 'var(--primitive-red-200)',+ 300: 'var(--primitive-red-300)',+ 400: 'var(--primitive-red-400)',+ 500: 'var(--primitive-red-500)',+ 600: 'var(--primitive-red-600)',+ 700: 'var(--primitive-red-700)',+ 800: 'var(--primitive-red-800)',+ 900: 'var(--primitive-red-900)',+ 950: 'var(--primitive-red-950)',+ },+ orange: {+ 100: 'var(--primitive-orange-100)',+ 200: 'var(--primitive-orange-200)',+ 300: 'var(--primitive-orange-300)',+ 400: 'var(--primitive-orange-400)',+ 500: 'var(--primitive-orange-500)',+ 600: 'var(--primitive-orange-600)',+ 700: 'var(--primitive-orange-700)',+ 800: 'var(--primitive-orange-800)',+ 900: 'var(--primitive-orange-900)',+ 950: 'var(--primitive-orange-950)',+ },+ green: {+ 50: 'var(--primitive-green-50)',+ 100: 'var(--primitive-green-100)',+ 200: 'var(--primitive-green-200)',+ 300: 'var(--primitive-green-300)',+ 400: 'var(--primitive-green-400)',+ 500: 'var(--primitive-green-500)',+ 600: 'var(--primitive-green-600)',+ 700: 'var(--primitive-green-700)',+ 800: 'var(--primitive-green-800)',+ 900: 'var(--primitive-green-900)',+ 950: 'var(--primitive-green-950)',+ },+ violet: {+ 57: 'var(--primitive-violet-57)',+ 67: 'var(--primitive-violet-67)',+ 70: 'var(--primitive-violet-70)',+ },+ azure: {+ 46: 'var(--primitive-azure-46)',+ 50: 'var(--primitive-azure-50)',+ 53: 'var(--primitive-azure-53)',+ 59: 'var(--primitive-azure-59)',+ 78: 'var(--primitive-azure-78)',+ 87: 'var(--primitive-azure-87)',+ 89: 'var(--primitive-azure-89)',+ },+ blue: {+ 8: 'var(--primitive-blue-8)',+ 12: 'var(--primitive-blue-12)',+ 85: 'var(--primitive-blue-85)',+ 100: 'var(--primitive-blue-100)',+ 200: 'var(--primitive-blue-200)',+ 300: 'var(--primitive-blue-300)',+ 400: 'var(--primitive-blue-400)',+ 500: 'var(--primitive-blue-500)',+ 600: 'var(--primitive-blue-600)',+ 700: 'var(--primitive-blue-700)',+ 800: 'var(--primitive-blue-800)',+ 900: 'var(--primitive-blue-900)',+ 950: 'var(--primitive-blue-950)',+ },+ magenta: {+ 37: 'var(--primitive-magenta-37)',+ },+ cyan: {+ 29: 'var(--primitive-cyan-29)',+ 36: 'var(--primitive-cyan-36)',+ 43: 'var(--primitive-cyan-43)',+ 68: 'var(--primitive-cyan-68)',+ 82: 'var(--primitive-cyan-82)',+ },+ teal: {+ 29: 'var(--primitive-teal-29)',+ 36: 'var(--primitive-teal-36)',+ 43: 'var(--primitive-teal-43)',+ 68: 'var(--primitive-teal-68)',+ 82: 'var(--primitive-teal-82)',+ },+};++/** Design system typography: one utility per token (e.g. ds-text-body-xs-medium). */+const dsTypographyPlugin = function ({+ addUtilities,+}: {+ addUtilities: (utilities: Record<string, Record<string, string>>) => void;+}) {+ const bodyFont = 'var(--ds-font-body)';+ const codeFont = 'var(--ds-font-code)';+ addUtilities({+ '.ds-text-body-xs-medium': {+ fontSize: 'var(--ds-text-body-xs-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-body-xs-medium-lh)',+ },+ '.ds-text-body-xs-semibold': {+ fontSize: 'var(--ds-text-body-xs-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-body-xs-semibold-lh)',+ },+ '.ds-text-body-sm-medium': {+ fontSize: 'var(--ds-text-body-sm-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-body-sm-medium-lh)',+ },+ '.ds-text-body-sm-semibold': {+ fontSize: 'var(--ds-text-body-sm-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-body-sm-semibold-lh)',+ },+ '.ds-text-body-md-medium': {+ fontSize: 'var(--ds-text-body-md-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-body-md-medium-lh)',+ },+ '.ds-text-body-md-semibold': {+ fontSize: 'var(--ds-text-body-md-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-body-md-semibold-lh)',+ },+ '.ds-text-title-sm-medium': {+ fontSize: 'var(--ds-text-title-sm-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-title-sm-medium-lh)',+ },+ '.ds-text-title-sm-semibold': {+ fontSize: 'var(--ds-text-title-sm-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-title-sm-semibold-lh)',+ },+ '.ds-text-title-md-medium': {+ fontSize: 'var(--ds-text-title-md-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-title-md-medium-lh)',+ },+ '.ds-text-title-md-semibold': {+ fontSize: 'var(--ds-text-title-md-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-title-md-semibold-lh)',+ },+ '.ds-text-title-lg-medium': {+ fontSize: 'var(--ds-text-title-lg-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-title-lg-medium-lh)',+ },+ '.ds-text-title-lg-semibold': {+ fontSize: 'var(--ds-text-title-lg-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-title-lg-semibold-lh)',+ },+ '.ds-text-title-xl-medium': {+ fontSize: 'var(--ds-text-title-xl-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-title-xl-medium-lh)',+ },+ '.ds-text-title-xl-semibold': {+ fontSize: 'var(--ds-text-title-xl-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-title-xl-semibold-lh)',+ },+ '.ds-text-title-2xl-medium': {+ fontSize: 'var(--ds-text-title-2xl-medium)',+ fontFamily: bodyFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-title-2xl-medium-lh)',+ },+ '.ds-text-title-2xl-semibold': {+ fontSize: 'var(--ds-text-title-2xl-semibold)',+ fontFamily: bodyFont,+ fontWeight: '600',+ lineHeight: 'var(--ds-text-title-2xl-semibold-lh)',+ },+ '.ds-text-code-sm': {+ fontSize: 'var(--ds-text-code-sm)',+ fontFamily: codeFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-code-sm-lh)',+ },+ '.ds-text-code-md': {+ fontSize: 'var(--ds-text-code-md)',+ fontFamily: codeFont,+ fontWeight: '500',+ lineHeight: 'var(--ds-text-code-md-lh)',+ },+ '.ds-text-code-md-regular': {+ fontSize: 'var(--ds-text-code-md-regular)',+ fontFamily: codeFont,+ fontWeight: '400',+ lineHeight: 'var(--ds-text-code-md-regular-lh)',+ },+ '.ds-text-code-lg': {+ fontSize: 'var(--ds-text-code-lg)',+ fontFamily: codeFont,+ fontWeight: '700',+ lineHeight: 'var(--ds-text-code-lg-lh)',+ },+ });+};++const config: Config = {+ darkMode: 'class',+ content: ['./index.html', './src/**/*.{ts,tsx}'],+ theme: {+ extend: {+ fontFamily: {+ code: ['var(--font-jetbrains-mono)', 'ui-monospace', 'monospace'],+ },+ transitionTimingFunction: {+ 'motion-out': 'var(--motion-ease-out)',+ },+ colors: {+ background: 'hsl(var(--background))',+ foreground: 'hsl(var(--foreground))',+ muted: {+ DEFAULT: 'hsl(var(--muted))',+ foreground: 'hsl(var(--muted-foreground))',+ },+ border: 'hsl(var(--border))',+ input: 'hsl(var(--input))',+ ring: 'hsl(var(--ring))',+ ds,+ primitive,+ },+ borderRadius: {+ lg: 'var(--radius)',+ md: 'calc(var(--radius) - 2px)',+ sm: 'calc(var(--radius) - 4px)',+ },+ keyframes: {+ // The Review tab: the one control here that is an offer rather than+ // a view of the session, so it breathes instead of sitting still.+ // Slow and small on purpose -- it shares a 300px column with a map+ // and a timeline, and anything faster reads as an alert.+ // Both ends are lit: it travels between a visible glow and a+ // brighter one, never through transparent. A pulse that fades out+ // spends half its cycle looking like a control nobody styled.+ 'pulse-glow': {+ '0%, 100%': {+ boxShadow:+ '0 0 0 1px var(--primitive-brand-green-500), 0 1px 6px -1px var(--primitive-brand-green-500)',+ transform: 'translateY(0)',+ },+ '50%': {+ boxShadow:+ '0 0 0 1.5px var(--primitive-brand-green-400), 0 5px 18px -3px var(--primitive-brand-green-400)',+ transform: 'translateY(-1.5px)',+ },+ },+ },+ animation: {+ // A literal curve, not a var(): an unresolved var() invalidates the+ // whole shorthand, which silently leaves `animation: none`.+ 'pulse-glow': 'pulse-glow 2.8s cubic-bezier(0.4, 0, 0.6, 1) infinite',+ },+ },+ },+ plugins: [+ tailwindcssAnimate,+ dsTypographyPlugin,+ // Base UI (@base-ui/react) exposes state as boolean-presence data-attributes+ // (data-open, data-checked, data-starting-style, ...). Register them as+ // shorthand Tailwind variants so `data-open:`, `group-data-active:`, etc.+ // resolve. Parameterized attrs (data-[side=top], data-[state=...]) use the+ // native bracket form and need no registration.+ tailwindPlugin(({ addVariant }: { addVariant: (name: string, selector: string) => void }) => {+ const states = [+ 'open', 'closed', 'checked', 'unchecked', 'indeterminate',+ 'disabled', 'readonly', 'required', 'valid', 'invalid', 'dirty',+ 'touched', 'filled', 'focused', 'active', 'inactive', 'selected',+ 'unselected', 'highlighted', 'pressed', 'current', 'popup-open',+ 'starting-style', 'ending-style', 'scrolling', 'nested',+ ];+ for (const s of states) {+ addVariant(`data-${s}`, `&[data-${s}]`);+ addVariant(`group-data-${s}`, `:merge(.group)[data-${s}] &`);+ addVariant(`peer-data-${s}`, `:merge(.peer)[data-${s}] ~ &`);+ }+ }),+ ],+};+export default config;diff --git a/viewer/tsconfig.app.json b/viewer/tsconfig.app.jsonnew file mode 100644index 0000000..ae75bb0--- /dev/null+++ b/viewer/tsconfig.app.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",+ "target": "ES2022",+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "react-jsx",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "isolatedModules": true,+ "moduleDetection": "force",+ "allowImportingTsExtensions": true,+ "noFallthroughCasesInSwitch": true,+ "types": ["vite/client", "vitest/globals", "node"],+ "paths": { "@/*": ["./src/*"] }+ },+ "include": ["src"]+}diff --git a/viewer/tsconfig.json b/viewer/tsconfig.jsonnew file mode 100644index 0000000..1ffef60--- /dev/null+++ b/viewer/tsconfig.json@@ -0,0 +1,7 @@+{+ "files": [],+ "references": [+ { "path": "./tsconfig.app.json" },+ { "path": "./tsconfig.node.json" }+ ]+}diff --git a/viewer/tsconfig.node.json b/viewer/tsconfig.node.jsonnew file mode 100644index 0000000..622d91a--- /dev/null+++ b/viewer/tsconfig.node.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",+ "target": "ES2023",+ "lib": ["ES2023"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "isolatedModules": true,+ "moduleDetection": "force",+ "types": ["node"]+ },+ "include": ["vite.config.ts", "tailwind.config.ts"]+}diff --git a/viewer/vite.config.ts b/viewer/vite.config.tsnew file mode 100644index 0000000..1aa0307--- /dev/null+++ b/viewer/vite.config.ts@@ -0,0 +1,29 @@+import path from 'node:path';+import { defineConfig } from 'vitest/config';+import react from '@vitejs/plugin-react';++// `base: './'` keeps every asset URL relative, so the built `dist/` can be+// served from any path (the Python CLI mounts it wherever it likes).+// `AGENTPLAY_SERVER` proxies `/api` to a running `agentplay` server in dev.+const server = process.env.AGENTPLAY_SERVER;++export default defineConfig({+ base: './',+ plugins: [react()],+ resolve: {+ alias: { '@': path.resolve(__dirname, './src') },+ },+ server: server ? { proxy: { '/api': server } } : undefined,+ build: {+ outDir: 'dist',+ emptyOutDir: true,+ chunkSizeWarningLimit: 1000,+ },+ test: {+ environment: 'jsdom',+ // Non-UTC on purpose: the server speaks UTC dates, so local-time bugs show.+ env: { TZ: 'America/Los_Angeles' },+ globals: true,+ include: ['src/**/*.test.{ts,tsx}'],+ },+});