ratifact 1.0.2__tar.gz → 1.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {ratifact-1.0.2 → ratifact-1.0.3}/LEEME.md +11 -6
  2. {ratifact-1.0.2 → ratifact-1.0.3}/PKG-INFO +11 -7
  3. {ratifact-1.0.2 → ratifact-1.0.3}/README.md +10 -6
  4. {ratifact-1.0.2 → ratifact-1.0.3}/pyproject.toml +1 -1
  5. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/__init__.py +1 -1
  6. ratifact-1.0.3/ratifact/informe_tokens.py +139 -0
  7. ratifact-1.0.3/ratifact/informe_tokens_atribucion.py +82 -0
  8. ratifact-1.0.3/ratifact/informe_tokens_lectura.py +117 -0
  9. ratifact-1.0.2/ratifact/informe_tokens.py +0 -246
  10. {ratifact-1.0.2 → ratifact-1.0.3}/.gitignore +0 -0
  11. {ratifact-1.0.2 → ratifact-1.0.3}/LICENSE +0 -0
  12. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/app.py +0 -0
  13. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/archivos.py +0 -0
  14. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/build.py +0 -0
  15. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/busqueda.py +0 -0
  16. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/catalogo.py +0 -0
  17. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/cli.py +0 -0
  18. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/clientes.py +0 -0
  19. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/clientes_toml.py +0 -0
  20. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/config.py +0 -0
  21. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/delegacion.py +0 -0
  22. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/doctor.py +0 -0
  23. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/doctor_plataforma.py +0 -0
  24. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/doctor_vivos.py +0 -0
  25. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/esquema.py +0 -0
  26. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/__init__.py +0 -0
  27. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/contexto_documentos.py +0 -0
  28. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/decisiones.py +0 -0
  29. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/pendientes_sesiones.py +0 -0
  30. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/proyectos.py +0 -0
  31. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/tareas.py +0 -0
  32. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/herramientas/tareas_brief.py +0 -0
  33. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/idioma.py +0 -0
  34. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/informe.py +0 -0
  35. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/informe_delegacion.py +0 -0
  36. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/informe_memoria.py +0 -0
  37. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/instalacion.py +0 -0
  38. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/instalar.py +0 -0
  39. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/instalar_extras.py +0 -0
  40. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/integraciones/__init__.py +0 -0
  41. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/integraciones/base.py +0 -0
  42. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/integraciones/codegraph.py +0 -0
  43. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/integraciones/engram.py +0 -0
  44. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/integraciones/gentle_ai.py +0 -0
  45. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/integraciones/registro.py +0 -0
  46. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/listado.py +0 -0
  47. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/migracion_v2.py +0 -0
  48. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/modelos.py +0 -0
  49. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/plantillas.py +0 -0
  50. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/plurales.py +0 -0
  51. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/procesos.py +0 -0
  52. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/prompts.py +0 -0
  53. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/registros.py +0 -0
  54. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/retirado.py +0 -0
  55. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/rutas.py +0 -0
  56. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/skills/run-task/SKILL.md +0 -0
  57. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/upgrade.py +0 -0
  58. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/upgrade_aplicar.py +0 -0
  59. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/vocabulario.py +0 -0
  60. {ratifact-1.0.2 → ratifact-1.0.3}/ratifact/workers.py +0 -0
@@ -146,16 +146,21 @@ reporta). Con la función apagada, `report` no abre ningún archivo de transcrip
146
146
  - Fuente: las transcripciones locales de Claude Code, `$CLAUDE_CONFIG_DIR/projects` o, si no, `~/.claude/projects`.
147
147
  Solo lee campos de metadatos de cada línea (fecha, carpeta de trabajo, rama, modelo, ids y los cuatro contadores de
148
148
  tokens de `usage`), nunca el contenido de ningún mensaje. No se guarda nada: se calcula en cada ejecución.
149
- - El consumo de una tarea cuenta las sesiones que trabajaron en la carpeta del proyecto (la carpeta `repo` de la
150
- tarea en proyectos multi-repo) y que tocaron la rama de la tarea. De esas sesiones cuentan los mensajes entre su
151
- `in_progress` y su siguiente `in_review` (una ventana por ejecución), estén en esa rama o en otra (por ejemplo
152
- main). Cada mensaje se cuenta una vez y nunca para dos tareas.
149
+ - El consumo de una tarea cuenta las sesiones del proyecto (cualquier línea cuya carpeta de trabajo sea la del
150
+ proyecto o esté dentro, también en proyectos multi-repo) que estaban activas en el momento en que la tarea pasó a
151
+ `in_progress` o a `in_review` (una línea a menos de dos minutos de ese momento). De esas sesiones cuentan los
152
+ mensajes entre su `in_progress` y su siguiente `in_review` (una ventana por ejecución), en cualquier rama. Si
153
+ varias sesiones estaban activas en el mismo momento, solo cuentan las que tienen una línea en la rama de la tarea
154
+ dentro de la ventana; si ninguna la tiene, la tarea se muestra como `ambiguous`. Cada mensaje se cuenta una vez y
155
+ nunca para dos tareas.
153
156
  - Por tarea con `routing:` del período: su política de delegación y, para la sesión principal y para los
154
157
  trabajadores (con su número), `in`, `out`, `cache write` y `cache read` por modelo. Por proyecto, el promedio por
155
- tarea de tokens de salida y de lectura de caché de las tareas delegadas y no delegadas, sobre las tareas con datos. Solo entran en
158
+ tarea de tokens de salida y de lectura de caché de las tareas delegadas y no delegadas, sobre las tareas con datos, con la mediana por tarea en una segunda línea.
159
+ Una tarea cuyas ventanas suman más de 8 horas lleva el aviso `long window` (puede incluir otro trabajo de la misma
160
+ sesión); se muestra y cuenta. Solo entran en
156
161
  los promedios las tareas con una línea `Workers` válida en su resultado; una tarea sin ella (por ejemplo, en curso)
157
162
  se muestra con sus cifras pero no cuenta en ningún grupo.
158
- Una tarea sin datos (otro cliente, o transcripciones ya borradas) muestra `no data`.
163
+ Una tarea sin datos (otro cliente, o transcripciones ya borradas) muestra `no data`; una tarea `ambiguous` queda fuera de los resúmenes.
159
164
  - Solo cubre Claude Code; Claude Code borra las transcripciones pasado su período de retención, así que las tareas
160
165
  viejas pierden sus datos. El desglose es por modelo, no por rol.
161
166
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ratifact
3
- Version: 1.0.2
3
+ Version: 1.0.3
4
4
  Summary: Local MCP server that turns each repository into the persistent memory of its project: decisions, open items, tasks and sessions in a git repository of their own.
5
5
  Project-URL: Homepage, https://github.com/EmaSleal/ratifact
6
6
  Project-URL: Repository, https://github.com/EmaSleal/ratifact
@@ -172,16 +172,20 @@ invalid value is treated as off and `ratifact doctor` reports it). With it off,
172
172
  - Source: the local Claude Code transcripts, `$CLAUDE_CONFIG_DIR/projects` or else `~/.claude/projects`. It reads only
173
173
  metadata fields of each line (timestamp, working folder, branch, model, ids and the four token counters of `usage`),
174
174
  never the content of any message. Nothing is stored: it is computed on each run.
175
- - A task's usage counts the sessions that worked in the project's folder (the task's `repo` folder in multi-repo
176
- projects) and that touched the task's branch. Of those sessions, the messages between the task's `in_progress` and
177
- its next `in_review` (one window per run) count, whether they are on that branch or on another one (for example
178
- main). A message is counted once, and never for two tasks.
175
+ - A task's usage counts the project's sessions (any line whose working folder is the project's folder or inside it,
176
+ also in multi-repo projects) that were active at the moment the task went to `in_progress` or to `in_review` (a
177
+ line within two minutes of that moment). Of those sessions, the messages between the task's `in_progress` and its
178
+ next `in_review` (one window per run) count, on whichever branch. If several sessions were active at the same
179
+ moment, only those with a line on the task's branch inside the window count; if none has it, the task shows as
180
+ `ambiguous`. A message is counted once, and never for two tasks.
179
181
  - Per task with `routing:` in the period: its delegation policy and, for the main session and for the workers (with
180
182
  their number), `in`, `out`, `cache write` and `cache read` per model. Per project, the average per task of output and
181
- cache-read tokens for delegated and not delegated tasks, over the tasks with data. Only tasks whose result has a
183
+ cache-read tokens for delegated and not delegated tasks, over the tasks with data, with the median per task on a
184
+ second line. A task whose windows add up to more than 8 hours carries a `long window` warning (it may include other
185
+ work of the same session); it is shown and counted. Only tasks whose result has a
182
186
  valid `Workers` line enter the averages; a task without one (for example, still in progress) is listed with its
183
187
  figures but counts in neither group. A task with no data (another
184
- client, or transcripts already deleted) shows `no data`.
188
+ client, or transcripts already deleted) shows `no data`; an `ambiguous` task is left out of the summaries.
185
189
  - It only covers Claude Code; transcripts are deleted by Claude Code after its retention period, so old tasks lose
186
190
  their data. The breakdown is per model, not per role.
187
191
 
@@ -142,16 +142,20 @@ invalid value is treated as off and `ratifact doctor` reports it). With it off,
142
142
  - Source: the local Claude Code transcripts, `$CLAUDE_CONFIG_DIR/projects` or else `~/.claude/projects`. It reads only
143
143
  metadata fields of each line (timestamp, working folder, branch, model, ids and the four token counters of `usage`),
144
144
  never the content of any message. Nothing is stored: it is computed on each run.
145
- - A task's usage counts the sessions that worked in the project's folder (the task's `repo` folder in multi-repo
146
- projects) and that touched the task's branch. Of those sessions, the messages between the task's `in_progress` and
147
- its next `in_review` (one window per run) count, whether they are on that branch or on another one (for example
148
- main). A message is counted once, and never for two tasks.
145
+ - A task's usage counts the project's sessions (any line whose working folder is the project's folder or inside it,
146
+ also in multi-repo projects) that were active at the moment the task went to `in_progress` or to `in_review` (a
147
+ line within two minutes of that moment). Of those sessions, the messages between the task's `in_progress` and its
148
+ next `in_review` (one window per run) count, on whichever branch. If several sessions were active at the same
149
+ moment, only those with a line on the task's branch inside the window count; if none has it, the task shows as
150
+ `ambiguous`. A message is counted once, and never for two tasks.
149
151
  - Per task with `routing:` in the period: its delegation policy and, for the main session and for the workers (with
150
152
  their number), `in`, `out`, `cache write` and `cache read` per model. Per project, the average per task of output and
151
- cache-read tokens for delegated and not delegated tasks, over the tasks with data. Only tasks whose result has a
153
+ cache-read tokens for delegated and not delegated tasks, over the tasks with data, with the median per task on a
154
+ second line. A task whose windows add up to more than 8 hours carries a `long window` warning (it may include other
155
+ work of the same session); it is shown and counted. Only tasks whose result has a
152
156
  valid `Workers` line enter the averages; a task without one (for example, still in progress) is listed with its
153
157
  figures but counts in neither group. A task with no data (another
154
- client, or transcripts already deleted) shows `no data`.
158
+ client, or transcripts already deleted) shows `no data`; an `ambiguous` task is left out of the summaries.
155
159
  - It only covers Claude Code; transcripts are deleted by Claude Code after its retention period, so old tasks lose
156
160
  their data. The breakdown is per model, not per role.
157
161
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ratifact"
3
- version = "1.0.2"
3
+ version = "1.0.3"
4
4
  description = "Local MCP server that turns each repository into the persistent memory of its project: decisions, open items, tasks and sessions in a git repository of their own."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -4,4 +4,4 @@
4
4
  No importa submódulos: cada uno se importa por separado (sin ciclos) y `ratifact.cli` / `servidor.py` los cargan en
5
5
  orden."""
6
6
 
7
- __version__ = "1.0.2" # igual que [project].version de pyproject.toml (tests/test_cli.py lo comprueba)
7
+ __version__ = "1.0.3" # igual que [project].version de pyproject.toml (tests/test_cli.py lo comprueba)
@@ -0,0 +1,139 @@
1
+ """Token usage section of `ratifact report` (opt-in: `"token_usage": "on"` in settings.json). Reads only metadata of the
2
+ Claude Code transcripts (`$CLAUDE_CONFIG_DIR/projects`, else `~/.claude/projects`): never message content. Computed
3
+ on demand, nothing is stored. Attribution (ADR-048, which corrects ADR-047 §4): the session of each in_progress →
4
+ in_review window is the project session (some line with `cwd` in the project path) with activity within 120 s of the
5
+ transition instants of the memory's git history; several sessions: the one with the task's `gitBranch` inside the
6
+ window, else the window is ambiguous and the task is shown as such, out of the summaries. Messages of the anchored
7
+ sessions and their subagent files inside the window count; a message goes to one task only (line's branch, else the
8
+ latest started window). Summaries show average and median; summed windows over 8 h get a warning. The format is not
9
+ a public contract of Claude Code: the reader is tolerant and never makes `report` fail."""
10
+ from __future__ import annotations
11
+
12
+ import datetime as dt
13
+ import json
14
+ import os
15
+ import re
16
+ import statistics
17
+ from pathlib import Path
18
+
19
+ from ratifact.config import _valor
20
+ from ratifact.informe_memoria import _memoria, _transiciones, ruta_config
21
+ from ratifact.informe_tokens_atribucion import VENTANA_LARGA, Tarea, atribuir
22
+ from ratifact.informe_tokens_lectura import CAMPOS, cargar_sesiones, directorio_base # noqa: F401 (re-exports)
23
+ from ratifact.plurales import contar
24
+ from ratifact.registros import _normalizar_id
25
+
26
+ ROTULOS = ("in", "out", "cache write", "cache read")
27
+ NOTA = ("Note: figures come from the local Claude Code transcripts, which are deleted after their retention "
28
+ "period; the breakdown is per model, not per role.")
29
+
30
+
31
+ def _ventanas(transiciones: list[tuple[dt.datetime, str]], ahora: dt.datetime):
32
+ """One window per in_progress: up to the first later in_review; else up to the next state change; else now.
33
+ The third item tells whether the end is an in_review commit (only then it anchors a session)."""
34
+ ventanas = []
35
+ for i, (inicio, estado) in enumerate(transiciones):
36
+ if estado != "in_progress":
37
+ continue
38
+ resto = transiciones[i + 1:]
39
+ revision = next((t for t, e in resto if e == "in_review"), None)
40
+ ventanas.append((inicio, revision or (resto[0][0] if resto else ahora), revision is not None))
41
+ return ventanas
42
+
43
+
44
+ def _desglose(t: Tarea, trabajador: bool) -> str:
45
+ partes = [f"{modelo}: " + " · ".join(f"{r} {v:,}" for r, v in zip(ROTULOS, c))
46
+ for (w, modelo), c in sorted(t.uso.items()) if w == trabajador]
47
+ return "; ".join(partes) or "none"
48
+
49
+
50
+ def _total(t: Tarea, trabajador: bool, i: int) -> int:
51
+ return sum(c[i] for (w, _), c in t.uso.items() if w == trabajador)
52
+
53
+
54
+ def _medias(con: list[Tarea], f) -> str:
55
+ return "; ".join(f"{lado}: " + " · ".join(f"{r} {f([_total(t, w, i) for t in con]):,.0f}"
56
+ for r, i in (("out", 1), ("cache read", 3)))
57
+ for lado, w in (("main session", False), ("workers", True)))
58
+
59
+
60
+ def _resumen(grupo: list[Tarea], nombre: str) -> list[str]:
61
+ con = [t for t in grupo if t.uso]
62
+ if not con:
63
+ return [f" {nombre}: —"]
64
+ return [f" {nombre}: {len(con)} of {contar(len(grupo), 'task')} with data · average per task — "
65
+ + _medias(con, lambda v: sum(v) / len(v)), f" median per task — " + _medias(con, statistics.median)]
66
+
67
+
68
+ def _aviso(t: Tarea) -> str:
69
+ if t.duracion() <= VENTANA_LARGA:
70
+ return ""
71
+ horas = f"{t.duracion().total_seconds() / 3600:.1f}".removesuffix(".0")
72
+ return f" ⚠ long window ({horas} h): may include other work of the same session"
73
+
74
+
75
+ def _tareas_proyecto(nombre: str, p: dict, desde: dt.datetime, ahora: dt.datetime) -> tuple[list[Tarea], list[Tarea]]:
76
+ """(tasks of the period, those of them with `routing:`), with their windows."""
77
+ from ratifact.delegacion import politica_de_routing, ultimo_workers_valido
78
+ from ratifact.informe_delegacion import _tareas_del_periodo
79
+ ruta = _valor(p, "ruta")
80
+ if not ruta:
81
+ return [], []
82
+ raiz = Path(ruta).expanduser()
83
+ mem = _memoria(nombre, p)
84
+ periodo = _tareas_del_periodo(mem, desde)
85
+ transiciones = _transiciones(mem) if periodo else {}
86
+ todas, con = [], []
87
+ for meta, cuerpo, archivo in periodo:
88
+ crudo = meta.get("id") or (re.match(r"T-\d+", archivo.name) or [None])[0]
89
+ if not crudo:
90
+ continue
91
+ id_ = _normalizar_id(crudo)
92
+ raices = list({os.path.normpath(raiz.resolve()), os.path.normpath(os.path.abspath(raiz))}) # project root, also with `repo`
93
+ trabajadores = ultimo_workers_valido(cuerpo.split("\n## Result", 1)[-1])
94
+ t = Tarea(id_, str(meta.get("branch") or ""), raices, _ventanas(transiciones.get(id_, []), ahora),
95
+ politica_de_routing(meta.get("routing", "")) or "unknown",
96
+ None if trabajadores is None else bool(trabajadores.total))
97
+ todas.append(t)
98
+ if meta.get("routing"):
99
+ con.append(t)
100
+ return todas, con
101
+
102
+
103
+ def seccion(desde: dt.datetime, proyecto: str | None) -> list[str]:
104
+ """Lines of the section (without its title). `desde` is naive local time, as in the rest of the report."""
105
+ base = directorio_base()
106
+ if not base.is_dir():
107
+ return [f" no transcripts found ({base})", NOTA]
108
+ try:
109
+ proyectos = json.loads(ruta_config().read_text(encoding="utf-8"))
110
+ except (OSError, ValueError):
111
+ return [" no configuration", NOTA]
112
+ desde = desde.astimezone()
113
+ ahora = dt.datetime.now(dt.timezone.utc)
114
+ sesiones = None
115
+ lineas = []
116
+ for nombre, p in proyectos.items():
117
+ if proyecto and nombre != proyecto or not isinstance(p, dict):
118
+ continue
119
+ todas, con = _tareas_proyecto(nombre, p, desde, ahora)
120
+ if not con:
121
+ continue
122
+ if sesiones is None:
123
+ sesiones = cargar_sesiones(base, desde)
124
+ atribuir(sesiones, todas)
125
+ lineas.append(f" {nombre}:")
126
+ for t in con:
127
+ if t.ambigua:
128
+ lineas.append(f" {t.id} · delegation={t.politica}: ambiguous "
129
+ f"({contar(t.ambigua, 'session')} active at the transition)")
130
+ continue
131
+ if not t.uso:
132
+ lineas.append(f" {t.id} · delegation={t.politica}: no data")
133
+ continue
134
+ lineas += [f" {t.id} · delegation={t.politica}{_aviso(t)}", f" main session: {_desglose(t, False)}",
135
+ f" workers: {contar(len(t.agentes), 'worker')} — {_desglose(t, True)}"]
136
+ sin_ambiguas = [t for t in con if not t.ambigua]
137
+ lineas += _resumen([t for t in sin_ambiguas if t.delegada is True], "delegated")
138
+ lineas += _resumen([t for t in sin_ambiguas if t.delegada is False], "not delegated")
139
+ return (lineas or [" no tasks in the period"]) + [NOTA]
@@ -0,0 +1,82 @@
1
+ """Attribution of transcript messages to tasks (ADR-048). A session is a candidate when one of its lines has a `cwd`
2
+ equal to the project path or inside it. The session of a run is the candidate with some line within TOLERANCIA of the
3
+ window start (memory in_progress commit) or end (in_review commit; a window closed by another state only anchors at
4
+ its start). Several anchored sessions: those with a line inside the window on the task branch; none and more than one
5
+ is an ambiguous window. Messages inside the window of the anchored sessions (and their subagents) count; a message
6
+ goes to one task only: the one whose branch matches the line's `gitBranch`, else the latest started window."""
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ import os
11
+ from dataclasses import dataclass, field
12
+
13
+ from ratifact.informe_tokens_lectura import Sesion, hay_linea
14
+
15
+ TOLERANCIA = dt.timedelta(seconds=120) # distance from a transition within which a line anchors a session
16
+ VENTANA_LARGA = dt.timedelta(hours=8) # summed windows above this get a warning
17
+
18
+
19
+ @dataclass
20
+ class Tarea:
21
+ id: str
22
+ rama: str
23
+ raices: list[str]
24
+ ventanas: list[tuple[dt.datetime, dt.datetime, bool]] # (start, end, whether the end is an in_review commit)
25
+ politica: str
26
+ delegada: bool | None # None: no valid `Workers:` line (excluded from the summaries)
27
+ uso: dict = field(default_factory=dict) # (worker?, model) -> [in, out, cache write, cache read]
28
+ agentes: set = field(default_factory=set)
29
+ ambigua: int = 0 # >0: sessions active at the transition of an ambiguous window
30
+
31
+ def duracion(self) -> dt.timedelta:
32
+ return sum((fin - ini for ini, fin, _ in self.ventanas), dt.timedelta())
33
+
34
+
35
+ def _dentro(cwds, raices: list[str]) -> bool:
36
+ for cwd in cwds:
37
+ p = os.path.normpath(cwd)
38
+ if any(p == r or p.startswith(r.rstrip(os.sep) + os.sep) for r in raices):
39
+ return True
40
+ return False
41
+
42
+
43
+ def _ancla(s: Sesion, ini: dt.datetime, fin: dt.datetime, con_fin: bool) -> bool:
44
+ return hay_linea(s.instantes, ini - TOLERANCIA, ini + TOLERANCIA) or \
45
+ (con_fin and hay_linea(s.instantes, fin - TOLERANCIA, fin + TOLERANCIA))
46
+
47
+
48
+ def _elegidas(sesiones: list[Sesion], t: Tarea, ventana) -> tuple[list[Sesion], int]:
49
+ """(sessions that own the window, number of anchored sessions if the window is ambiguous else 0)."""
50
+ ini, fin, con_fin = ventana
51
+ ancladas = [s for s in sesiones if _dentro(s.cwds, t.raices) and _ancla(s, ini, fin, con_fin)]
52
+ if len(ancladas) > 1:
53
+ con_rama = [s for s in ancladas if hay_linea(s.por_rama.get(t.rama, []), ini, fin)]
54
+ if con_rama:
55
+ return con_rama, 0
56
+ return [], len(ancladas)
57
+ return ancladas, 0
58
+
59
+
60
+ def atribuir(sesiones: list[Sesion], tareas: list[Tarea]) -> None:
61
+ propias: dict[int, list] = {id(s): [] for s in sesiones} # session -> [(start, end, task)]
62
+ for t in tareas:
63
+ elegidas = []
64
+ for v in t.ventanas:
65
+ sel, ambigua = _elegidas(sesiones, t, v)
66
+ t.ambigua = max(t.ambigua, ambigua)
67
+ elegidas += [(s, v[0], v[1], t) for s in sel]
68
+ if not t.ambigua: # an ambiguous task claims no message
69
+ for s, ini, fin, t in elegidas:
70
+ propias[id(s)].append((ini, fin, t))
71
+ for s in sesiones:
72
+ for m in s.mensajes.values():
73
+ opciones = [(ini, t) for ini, fin, t in propias[id(s)] if ini <= m.ts <= fin]
74
+ if not opciones:
75
+ continue
76
+ mias = [o for o in opciones if o[1].rama == m.rama] or opciones
77
+ t = max(mias, key=lambda o: o[0])[1]
78
+ acumulado = t.uso.setdefault((m.trabajador, m.modelo), [0, 0, 0, 0])
79
+ for i, v in enumerate(m.cifras):
80
+ acumulado[i] += v
81
+ if m.trabajador:
82
+ t.agentes.add(m.agente)
@@ -0,0 +1,117 @@
1
+ """Transcript reader of the token usage section: metadata only, never message content. Tolerant: unreadable or odd
2
+ lines and files are skipped. Per session it keeps the instants of ALL its lines (main file plus its subagent files:
3
+ a subagent's activity counts as the session's activity) so the attribution can ask "is there a line near t?"."""
4
+ from __future__ import annotations
5
+
6
+ import datetime as dt
7
+ import json
8
+ import os
9
+ import re
10
+ from bisect import bisect_left
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ CAMPOS = ("input_tokens", "output_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")
15
+
16
+
17
+ @dataclass
18
+ class Mensaje:
19
+ ts: dt.datetime
20
+ rama: str | None
21
+ modelo: str
22
+ trabajador: bool
23
+ agente: str | None
24
+ cifras: list[int]
25
+
26
+
27
+ @dataclass
28
+ class Sesion:
29
+ cwds: set = field(default_factory=set)
30
+ instantes: list = field(default_factory=list) # every line with a timestamp, sorted once loaded
31
+ por_rama: dict = field(default_factory=dict) # gitBranch -> sorted instants of the lines on that branch
32
+ mensajes: dict = field(default_factory=dict)
33
+
34
+
35
+ def directorio_base() -> Path:
36
+ base = os.environ.get("CLAUDE_CONFIG_DIR")
37
+ return (Path(base).expanduser() if base else Path.home() / ".claude") / "projects"
38
+
39
+
40
+ def _instante(texto) -> dt.datetime | None:
41
+ if not isinstance(texto, str):
42
+ return None
43
+ texto = re.sub(r"\.(\d+)", lambda m: "." + m.group(1)[:6].ljust(6, "0"), texto)
44
+ texto = texto[:-1] + "+00:00" if texto.endswith("Z") else texto # fromisoformat takes "Z" only from 3.11
45
+ try:
46
+ t = dt.datetime.fromisoformat(texto)
47
+ except ValueError:
48
+ return None
49
+ return t if t.tzinfo else t.replace(tzinfo=dt.timezone.utc)
50
+
51
+
52
+ def _texto(valor) -> str | None:
53
+ return valor if isinstance(valor, str) and valor else None
54
+
55
+
56
+ def _linea(d: dict, clave_defecto, es_sub: bool, ruta: Path, s: Sesion) -> None:
57
+ if _texto(d.get("cwd")):
58
+ s.cwds.add(d["cwd"])
59
+ ts = _instante(d.get("timestamp"))
60
+ if ts is not None:
61
+ s.instantes.append(ts)
62
+ if _texto(d.get("gitBranch")):
63
+ s.por_rama.setdefault(d["gitBranch"], []).append(ts)
64
+ msg = d.get("message")
65
+ uso = msg.get("usage") if isinstance(msg, dict) else None
66
+ if not isinstance(uso, dict):
67
+ return
68
+ cifras = [uso[c] if type(uso.get(c)) is int and uso[c] >= 0 else 0 for c in CAMPOS]
69
+ modelo = _texto(msg.get("model")) or "unknown"
70
+ if not any(type(uso.get(c)) is int for c in CAMPOS) or ts is None or modelo == "<synthetic>":
71
+ return
72
+ mid, rid = _texto(msg.get("id")), _texto(d.get("requestId"))
73
+ clave = (mid, rid) if mid or rid else clave_defecto
74
+ previo = s.mensajes.get(clave)
75
+ if previo: # repeated message: the maximum of each field
76
+ previo.cifras = [max(a, b) for a, b in zip(previo.cifras, cifras)]
77
+ return
78
+ trabajador = es_sub or d.get("isSidechain") is True
79
+ agente = str(ruta) if es_sub else _texto(d.get("agentId"))
80
+ s.mensajes[clave] = Mensaje(ts, _texto(d.get("gitBranch")), modelo, trabajador, agente if trabajador else None,
81
+ cifras)
82
+
83
+
84
+ def cargar_sesiones(base: Path, desde: dt.datetime) -> list[Sesion]:
85
+ """One Sesion per session (its file plus its `subagents/agent-*.jsonl`); files not modified since `desde` are
86
+ skipped; each file is read line by line."""
87
+ sesiones: dict[Path, Sesion] = {}
88
+ for ruta in sorted(base.glob("**/*.jsonl")):
89
+ try:
90
+ if ruta.stat().st_mtime < desde.timestamp():
91
+ continue
92
+ except OSError:
93
+ continue
94
+ es_sub = ruta.parent.name == "subagents" and ruta.name.startswith("agent-")
95
+ s = sesiones.setdefault(ruta.parent.parent if es_sub else ruta.with_suffix(""), Sesion())
96
+ try:
97
+ with ruta.open(encoding="utf-8", errors="replace") as f:
98
+ for n, linea in enumerate(f):
99
+ try:
100
+ d = json.loads(linea)
101
+ except (ValueError, RecursionError):
102
+ continue
103
+ if isinstance(d, dict):
104
+ _linea(d, (str(ruta), n), es_sub, ruta, s)
105
+ except OSError:
106
+ continue
107
+ for s in sesiones.values():
108
+ s.instantes.sort()
109
+ for v in s.por_rama.values():
110
+ v.sort()
111
+ return list(sesiones.values())
112
+
113
+
114
+ def hay_linea(instantes: list, a: dt.datetime, b: dt.datetime) -> bool:
115
+ """True when the sorted list has an instant in [a, b]."""
116
+ i = bisect_left(instantes, a)
117
+ return i < len(instantes) and instantes[i] <= b
@@ -1,246 +0,0 @@
1
- """Token usage section of `ratifact report` (opt-in: `"token_usage": "on"` in settings.json). Reads only metadata of the
2
- Claude Code transcripts (`$CLAUDE_CONFIG_DIR/projects`, else `~/.claude/projects`): never message content. Computed
3
- on demand, nothing is stored. Attribution to a task: a session qualifies when one of its lines has a `cwd` inside the
4
- task's code folder and another has the task's `gitBranch`; its messages (and those of its subagent files) count for
5
- the task when their `timestamp` falls in an in_progress → in_review window from the memory's git history. A message
6
- goes to one task only: the one whose branch matches the line's `gitBranch`, else the latest started window. The format
7
- is not a public contract of Claude Code: the reader is tolerant and never makes `report` fail."""
8
- from __future__ import annotations
9
-
10
- import datetime as dt
11
- import json
12
- import os
13
- import re
14
- from dataclasses import dataclass, field
15
- from pathlib import Path
16
-
17
- from ratifact.config import _valor
18
- from ratifact.informe_memoria import _memoria, _transiciones, ruta_config
19
- from ratifact.plurales import contar
20
- from ratifact.registros import _normalizar_id
21
-
22
- CAMPOS = ("input_tokens", "output_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")
23
- ROTULOS = ("in", "out", "cache write", "cache read")
24
- NOTA = ("Note: figures come from the local Claude Code transcripts, which are deleted after their retention "
25
- "period; the breakdown is per model, not per role.")
26
-
27
-
28
- @dataclass
29
- class Mensaje:
30
- ts: dt.datetime
31
- rama: str | None
32
- modelo: str
33
- trabajador: bool
34
- agente: str | None
35
- cifras: list[int]
36
-
37
-
38
- @dataclass
39
- class Sesion:
40
- cwds: set = field(default_factory=set)
41
- ramas: set = field(default_factory=set)
42
- mensajes: dict = field(default_factory=dict)
43
-
44
-
45
- @dataclass
46
- class Tarea:
47
- id: str
48
- rama: str
49
- raices: list[str]
50
- ventanas: list[tuple[dt.datetime, dt.datetime]]
51
- politica: str
52
- delegada: bool | None # None: no valid `Workers:` line (excluded from the averages)
53
- uso: dict = field(default_factory=dict) # (worker?, model) -> [in, out, cache write, cache read]
54
- agentes: set = field(default_factory=set)
55
-
56
-
57
- def directorio_base() -> Path:
58
- base = os.environ.get("CLAUDE_CONFIG_DIR")
59
- return (Path(base).expanduser() if base else Path.home() / ".claude") / "projects"
60
-
61
-
62
- def _instante(texto) -> dt.datetime | None:
63
- if not isinstance(texto, str):
64
- return None
65
- texto = re.sub(r"\.(\d+)", lambda m: "." + m.group(1)[:6].ljust(6, "0"), texto)
66
- texto = texto[:-1] + "+00:00" if texto.endswith("Z") else texto # fromisoformat takes "Z" only from 3.11
67
- try:
68
- t = dt.datetime.fromisoformat(texto)
69
- except ValueError:
70
- return None
71
- return t if t.tzinfo else t.replace(tzinfo=dt.timezone.utc)
72
-
73
-
74
- def _texto(valor) -> str | None:
75
- return valor if isinstance(valor, str) and valor else None
76
-
77
-
78
- def _linea(d: dict, clave_defecto, es_sub: bool, ruta: Path, s: Sesion) -> None:
79
- if _texto(d.get("cwd")):
80
- s.cwds.add(d["cwd"])
81
- if _texto(d.get("gitBranch")):
82
- s.ramas.add(d["gitBranch"])
83
- msg = d.get("message")
84
- uso = msg.get("usage") if isinstance(msg, dict) else None
85
- if not isinstance(uso, dict):
86
- return
87
- cifras = [uso[c] if type(uso.get(c)) is int and uso[c] >= 0 else 0 for c in CAMPOS]
88
- ts = _instante(d.get("timestamp"))
89
- modelo = _texto(msg.get("model")) or "unknown"
90
- if not any(type(uso.get(c)) is int for c in CAMPOS) or ts is None or modelo == "<synthetic>":
91
- return
92
- mid, rid = _texto(msg.get("id")), _texto(d.get("requestId"))
93
- clave = (mid, rid) if mid or rid else clave_defecto
94
- previo = s.mensajes.get(clave)
95
- if previo: # repeated message: the maximum of each field
96
- previo.cifras = [max(a, b) for a, b in zip(previo.cifras, cifras)]
97
- return
98
- trabajador = es_sub or d.get("isSidechain") is True
99
- agente = str(ruta) if es_sub else _texto(d.get("agentId"))
100
- s.mensajes[clave] = Mensaje(ts, _texto(d.get("gitBranch")), modelo, trabajador, agente if trabajador else None,
101
- cifras)
102
-
103
-
104
- def cargar_sesiones(base: Path, desde: dt.datetime) -> list[Sesion]:
105
- """One Sesion per session (its file plus its `subagents/agent-*.jsonl`); files not modified since `desde` are
106
- skipped; each file is read line by line."""
107
- sesiones: dict[Path, Sesion] = {}
108
- for ruta in sorted(base.glob("**/*.jsonl")):
109
- try:
110
- if ruta.stat().st_mtime < desde.timestamp():
111
- continue
112
- except OSError:
113
- continue
114
- es_sub = ruta.parent.name == "subagents" and ruta.name.startswith("agent-")
115
- s = sesiones.setdefault(ruta.parent.parent if es_sub else ruta.with_suffix(""), Sesion())
116
- try:
117
- with ruta.open(encoding="utf-8", errors="replace") as f:
118
- for n, linea in enumerate(f):
119
- try:
120
- d = json.loads(linea)
121
- except (ValueError, RecursionError):
122
- continue
123
- if isinstance(d, dict):
124
- _linea(d, (str(ruta), n), es_sub, ruta, s)
125
- except OSError:
126
- continue
127
- return list(sesiones.values())
128
-
129
-
130
- def _ventanas(transiciones: list[tuple[dt.datetime, str]], ahora: dt.datetime):
131
- """One window per in_progress: up to the first later in_review; else up to the next state change; else now."""
132
- ventanas = []
133
- for i, (inicio, estado) in enumerate(transiciones):
134
- if estado != "in_progress":
135
- continue
136
- resto = transiciones[i + 1:]
137
- fin = next((t for t, e in resto if e == "in_review"), resto[0][0] if resto else ahora)
138
- ventanas.append((inicio, fin))
139
- return ventanas
140
-
141
-
142
- def _dentro(cwds, raices: list[str]) -> bool:
143
- for cwd in cwds:
144
- p = os.path.normpath(cwd)
145
- if any(p == r or p.startswith(r.rstrip(os.sep) + os.sep) for r in raices):
146
- return True
147
- return False
148
-
149
-
150
- def atribuir(sesiones: list[Sesion], tareas: list[Tarea]) -> None:
151
- for s in sesiones:
152
- candidatas = [t for t in tareas if t.rama in s.ramas and _dentro(s.cwds, t.raices)]
153
- for m in s.mensajes.values():
154
- opciones = [(ini, t) for t in candidatas for ini, fin in t.ventanas if ini <= m.ts <= fin]
155
- if not opciones:
156
- continue
157
- propias = [o for o in opciones if o[1].rama == m.rama] or opciones
158
- t = max(propias, key=lambda o: o[0])[1]
159
- acumulado = t.uso.setdefault((m.trabajador, m.modelo), [0, 0, 0, 0])
160
- for i, v in enumerate(m.cifras):
161
- acumulado[i] += v
162
- if m.trabajador:
163
- t.agentes.add(m.agente)
164
-
165
-
166
- def _desglose(t: Tarea, trabajador: bool) -> str:
167
- partes = [f"{modelo}: " + " · ".join(f"{r} {v:,}" for r, v in zip(ROTULOS, c))
168
- for (w, modelo), c in sorted(t.uso.items()) if w == trabajador]
169
- return "; ".join(partes) or "none"
170
-
171
-
172
- def _total(t: Tarea, trabajador: bool, i: int) -> int:
173
- return sum(c[i] for (w, _), c in t.uso.items() if w == trabajador)
174
-
175
-
176
- def _promedio(grupo: list[Tarea], nombre: str) -> str:
177
- con = [t for t in grupo if t.uso]
178
- if not con:
179
- return f" {nombre}: —"
180
- medias = [f"{lado}: " + " · ".join(f"{r} {sum(_total(t, w, i) for t in con) / len(con):,.0f}"
181
- for r, i in (("out", 1), ("cache read", 3)))
182
- for lado, w in (("main session", False), ("workers", True))]
183
- return f" {nombre}: {len(con)} of {contar(len(grupo), 'task')} with data · average per task — " + "; ".join(medias)
184
-
185
-
186
- def _tareas_proyecto(nombre: str, p: dict, desde: dt.datetime, ahora: dt.datetime) -> tuple[list[Tarea], list[Tarea]]:
187
- """(tasks of the period, those of them with `routing:`), with their windows."""
188
- from ratifact.delegacion import politica_de_routing, ultimo_workers_valido
189
- from ratifact.informe_delegacion import _tareas_del_periodo
190
- ruta = _valor(p, "ruta")
191
- if not ruta:
192
- return [], []
193
- raiz = Path(ruta).expanduser()
194
- mem = _memoria(nombre, p)
195
- periodo = _tareas_del_periodo(mem, desde)
196
- transiciones = _transiciones(mem) if periodo else {}
197
- todas, con = [], []
198
- for meta, cuerpo, archivo in periodo:
199
- crudo = meta.get("id") or (re.match(r"T-\d+", archivo.name) or [None])[0]
200
- if not crudo:
201
- continue
202
- id_ = _normalizar_id(crudo)
203
- carpeta = raiz / meta["repo"] if meta.get("repo") else raiz
204
- raices = list({os.path.normpath(carpeta.resolve()), os.path.normpath(os.path.abspath(carpeta))})
205
- trabajadores = ultimo_workers_valido(cuerpo.split("\n## Result", 1)[-1])
206
- t = Tarea(id_, str(meta.get("branch") or ""), raices, _ventanas(transiciones.get(id_, []), ahora),
207
- politica_de_routing(meta.get("routing", "")) or "unknown",
208
- None if trabajadores is None else bool(trabajadores.total))
209
- todas.append(t)
210
- if meta.get("routing"):
211
- con.append(t)
212
- return todas, con
213
-
214
-
215
- def seccion(desde: dt.datetime, proyecto: str | None) -> list[str]:
216
- """Lines of the section (without its title). `desde` is naive local time, as in the rest of the report."""
217
- base = directorio_base()
218
- if not base.is_dir():
219
- return [f" no transcripts found ({base})", NOTA]
220
- try:
221
- proyectos = json.loads(ruta_config().read_text(encoding="utf-8"))
222
- except (OSError, ValueError):
223
- return [" no configuration", NOTA]
224
- desde = desde.astimezone()
225
- ahora = dt.datetime.now(dt.timezone.utc)
226
- sesiones = None
227
- lineas = []
228
- for nombre, p in proyectos.items():
229
- if proyecto and nombre != proyecto or not isinstance(p, dict):
230
- continue
231
- todas, con = _tareas_proyecto(nombre, p, desde, ahora)
232
- if not con:
233
- continue
234
- if sesiones is None:
235
- sesiones = cargar_sesiones(base, desde)
236
- atribuir(sesiones, todas)
237
- lineas.append(f" {nombre}:")
238
- for t in con:
239
- if not t.uso:
240
- lineas.append(f" {t.id} · delegation={t.politica}: no data")
241
- continue
242
- lineas += [f" {t.id} · delegation={t.politica}", f" main session: {_desglose(t, False)}",
243
- f" workers: {contar(len(t.agentes), 'worker')} — {_desglose(t, True)}"]
244
- lineas += [_promedio([t for t in con if t.delegada is True], "delegated"),
245
- _promedio([t for t in con if t.delegada is False], "not delegated")]
246
- return (lineas or [" no tasks in the period"]) + [NOTA]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes