ratifact 1.0.2__tar.gz → 1.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. {ratifact-1.0.2 → ratifact-1.0.4}/LEEME.md +13 -7
  2. {ratifact-1.0.2 → ratifact-1.0.4}/PKG-INFO +11 -7
  3. {ratifact-1.0.2 → ratifact-1.0.4}/README.md +10 -6
  4. {ratifact-1.0.2 → ratifact-1.0.4}/pyproject.toml +1 -1
  5. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/__init__.py +1 -1
  6. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/contexto_documentos.py +8 -9
  7. ratifact-1.0.4/ratifact/herramientas/decisiones_visibilidad.py +81 -0
  8. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/tareas.py +7 -3
  9. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/tareas_brief.py +41 -6
  10. ratifact-1.0.4/ratifact/informe_tokens.py +139 -0
  11. ratifact-1.0.4/ratifact/informe_tokens_atribucion.py +82 -0
  12. ratifact-1.0.4/ratifact/informe_tokens_lectura.py +117 -0
  13. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/skills/run-task/SKILL.md +1 -1
  14. ratifact-1.0.2/ratifact/informe_tokens.py +0 -246
  15. {ratifact-1.0.2 → ratifact-1.0.4}/.gitignore +0 -0
  16. {ratifact-1.0.2 → ratifact-1.0.4}/LICENSE +0 -0
  17. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/app.py +0 -0
  18. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/archivos.py +0 -0
  19. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/build.py +0 -0
  20. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/busqueda.py +0 -0
  21. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/catalogo.py +0 -0
  22. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/cli.py +0 -0
  23. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/clientes.py +0 -0
  24. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/clientes_toml.py +0 -0
  25. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/config.py +0 -0
  26. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/delegacion.py +0 -0
  27. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/doctor.py +0 -0
  28. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/doctor_plataforma.py +0 -0
  29. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/doctor_vivos.py +0 -0
  30. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/esquema.py +0 -0
  31. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/__init__.py +0 -0
  32. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/decisiones.py +0 -0
  33. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/pendientes_sesiones.py +0 -0
  34. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/herramientas/proyectos.py +0 -0
  35. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/idioma.py +0 -0
  36. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/informe.py +0 -0
  37. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/informe_delegacion.py +0 -0
  38. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/informe_memoria.py +0 -0
  39. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/instalacion.py +0 -0
  40. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/instalar.py +0 -0
  41. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/instalar_extras.py +0 -0
  42. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/integraciones/__init__.py +0 -0
  43. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/integraciones/base.py +0 -0
  44. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/integraciones/codegraph.py +0 -0
  45. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/integraciones/engram.py +0 -0
  46. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/integraciones/gentle_ai.py +0 -0
  47. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/integraciones/registro.py +0 -0
  48. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/listado.py +0 -0
  49. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/migracion_v2.py +0 -0
  50. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/modelos.py +0 -0
  51. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/plantillas.py +0 -0
  52. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/plurales.py +0 -0
  53. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/procesos.py +0 -0
  54. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/prompts.py +0 -0
  55. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/registros.py +0 -0
  56. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/retirado.py +0 -0
  57. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/rutas.py +0 -0
  58. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/upgrade.py +0 -0
  59. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/upgrade_aplicar.py +0 -0
  60. {ratifact-1.0.2 → ratifact-1.0.4}/ratifact/vocabulario.py +0 -0
  61. {ratifact-1.0.2 → ratifact-1.0.4}/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
 
@@ -270,7 +275,8 @@ commit por enmienda; al menos uno de los dos campos; una enmienda idéntica dent
270
275
  no se escribe de nuevo.
271
276
 
272
277
  `read_task(project, id)`: brief de trabajo de una tarea en lugar del archivo completo: frontmatter, spec
273
- completa (con las enmiendas), el bloque relevante según el estado (`changes_requested` → la última Review;
278
+ completa (con las enmiendas), estado vigente de cada decisión aplicable al momento de leer (sin modificar la tarea),
279
+ el bloque relevante según el estado (`changes_requested` → la última Review;
274
280
  `in_review`/`failed` → el último resultado; `in_progress` → la última Review si es el último bloque) y un índice de una
275
281
  línea (título · rango de líneas · tamaño) de los demás bloques Result/Review, legibles con `read_document` y ese rango.
276
282
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ratifact
3
- Version: 1.0.2
3
+ Version: 1.0.4
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.4"
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.4" # igual que [project].version de pyproject.toml (tests/test_cli.py lo comprueba)
@@ -7,6 +7,7 @@ import subprocess
7
7
  from pathlib import Path
8
8
 
9
9
  from ratifact import build as _build
10
+ from ratifact import registros as _registros
10
11
  from ratifact.app import _ejecutar, herramienta
11
12
  from ratifact.busqueda import _resultados
12
13
  from ratifact.catalogo import _bloque_pendientes, _es_carpeta_de_registros, _linea, _registros_en, _resolver_id
@@ -14,11 +15,12 @@ from ratifact.config import (CARPETAS_IGNORADAS, EXT_TEXTO, LIMITE_INDICE, LIMIT
14
15
  _aviso_alias, _es_repo, _mem, _proyectos, _raiz, _repos, _ruta_segura, _traducir_alias,
15
16
  _valor)
16
17
  from ratifact.esquema import _bloqueo, _idioma_contenido, _version_esquema
18
+ from ratifact.herramientas.decisiones_visibilidad import _linea_propuestas
17
19
  from ratifact.idioma import linea_contenido
18
20
  from ratifact.integraciones import registro as _integraciones
19
21
  from ratifact.listado import _listado
20
- from ratifact.registros import _clave_id, _commit, _escribir_atomico, _leer_registro, _resumen_tareas
21
- from ratifact.vocabulario import DECISIONES, MODOS_V0
22
+ from ratifact.registros import _commit, _escribir_atomico, _leer_registro, _resumen_tareas
23
+ from ratifact.vocabulario import MODOS_V0
22
24
 
23
25
 
24
26
  # ───────────────────────── herramientas ─────────────────────────
@@ -43,8 +45,6 @@ def list_projects() -> str:
43
45
 
44
46
 
45
47
  UMBRAL_INDICE = 5 # cambios en la memoria tras los cuales INDEX.md se considera desactualizado
46
-
47
-
48
48
  def _aviso_indice(proyecto: str) -> str:
49
49
  """Si INDEX.md quedó atrás respecto de la memoria, lo dice explícitamente al cargar contexto."""
50
50
  mem = _mem(proyecto)
@@ -71,6 +71,7 @@ def get_context(project: str) -> str:
71
71
  The first line is `ratifact <build>` (version + content hash of the running server). Below it, a ⚠ line when
72
72
  this server process is older than the installation on disk (restart the client) or when the local source it was
73
73
  installed from is newer than the installation (reinstall).
74
+ Proposed decisions are listed with their age and oldest items are flagged for a small decision batch.
74
75
  At the end, if optional integrations are active (codegraph, gentle-ai, engram…), one line listing them and their
75
76
  planning guidance; that guidance is conditional: follow it only if you have their tools."""
76
77
  proyecto = project
@@ -89,11 +90,9 @@ def get_context(project: str) -> str:
89
90
  indice = mem / "INDEX.md"
90
91
  partes.append(indice.read_text(encoding="utf-8") if indice.exists() else "(INDEX.md does not exist)")
91
92
  partes.append(_bloque_pendientes(proyecto)) # ADR-026: del catálogo, no abiertas.md
92
- propuestas = ["-".join(p.stem.split("-", 2)[:2]) for p in (mem / DECISIONES).glob("ADR-*.md")
93
- if _leer_registro(p)[0].get("status") == "proposed"]
94
- if propuestas:
95
- partes.append("Proposed decisions awaiting the user's acceptance: "
96
- + ", ".join(sorted(propuestas, key=_clave_id)))
93
+ linea_propuestas = _linea_propuestas(mem)
94
+ if linea_propuestas:
95
+ partes.append(linea_propuestas)
97
96
  tareas = _resumen_tareas(proyecto)
98
97
  if tareas:
99
98
  partes.append("# Active code tasks\n" + "\n".join(tareas))
@@ -0,0 +1,81 @@
1
+ """Renderiza la edad y el estado actual de decisiones citadas por las herramientas."""
2
+ from __future__ import annotations
3
+
4
+ import datetime as _dt
5
+ from pathlib import Path
6
+
7
+ from ratifact import registros as _registros
8
+ from ratifact.config import ErrorMemoria, _mem
9
+ from ratifact.registros import _buscar_registro, _clave_id, _leer_registro, _normalizar_id
10
+ from ratifact.vocabulario import DECISIONES
11
+
12
+ UMBRAL_ANTIGUEDAD_PROPUESTA_DIAS = 14
13
+ MAX_PROPUESTAS_ANTIGUAS_A_DECIDIR = 3
14
+
15
+
16
+ def _propuestas_con_antiguedad(mem: Path) -> list[tuple[str, _dt.date | None]]:
17
+ """Devuelve propuestas de más antiguas a más nuevas; las fechas inválidas quedan al final."""
18
+ propuestas = []
19
+ for ruta in (mem / DECISIONES).glob("ADR-*.md"):
20
+ meta, _ = _leer_registro(ruta)
21
+ if meta.get("status") != "proposed":
22
+ continue
23
+ id_ = "-".join(ruta.stem.split("-", 2)[:2])
24
+ try:
25
+ fecha = _dt.date.fromisoformat(str(meta.get("date", "")))
26
+ except ValueError:
27
+ fecha = None
28
+ propuestas.append((id_, fecha))
29
+ return sorted(propuestas, key=lambda p: (p[1] is None, p[1] or _dt.date.max, _clave_id(p[0])))
30
+
31
+
32
+ def _linea_propuestas(mem: Path) -> str:
33
+ """Renderiza edad y sugerencia de decisión por lote sin alterar los ADR."""
34
+ propuestas = _propuestas_con_antiguedad(mem)
35
+ if not propuestas:
36
+ return ""
37
+ hoy = _registros._ahora().date()
38
+ elementos, antiguas = [], []
39
+ for id_, fecha in propuestas:
40
+ if fecha is None or fecha > hoy:
41
+ elementos.append(id_)
42
+ continue
43
+ dias = (hoy - fecha).days
44
+ elementos.append(f"{id_} ({'today' if dias == 0 else f'{dias} d'})")
45
+ if dias >= UMBRAL_ANTIGUEDAD_PROPUESTA_DIAS:
46
+ antiguas.append(id_)
47
+ linea = "Proposed decisions awaiting the user's acceptance: " + ", ".join(elementos)
48
+ if antiguas:
49
+ lote = ", ".join(antiguas[:MAX_PROPUESTAS_ANTIGUAS_A_DECIDIR])
50
+ cantidad = len(antiguas[:MAX_PROPUESTAS_ANTIGUAS_A_DECIDIR])
51
+ if cantidad == 1:
52
+ linea += f"\nOffer the user to decide the oldest proposal: {lote}"
53
+ else:
54
+ linea += f"\nOffer the user to decide the {cantidad} oldest proposals: {lote}"
55
+ return linea
56
+
57
+
58
+ def _avisos_decisiones(proyecto: str, decisiones: str) -> str:
59
+ """Informa estados no aceptados sin cambiar el formato guardado en la tarea."""
60
+ avisos = []
61
+ for id_ in decisiones.split(", ") if decisiones else ():
62
+ meta, _ = _leer_registro(_buscar_registro(_mem(proyecto) / DECISIONES, id_))
63
+ estado = meta.get("status", "unknown")
64
+ if estado == "accepted":
65
+ continue
66
+ if estado == "proposed":
67
+ avisos.append(f"⚠ {id_} is proposed; the coding agent will treat it as a reference, not as a rule. "
68
+ "Accept it before starting or clarify in the task notes how to treat it.")
69
+ elif estado == "superseded":
70
+ reemplazo = meta.get("superseded_by", "")
71
+ if reemplazo:
72
+ try:
73
+ reemplazo = _normalizar_id(reemplazo)
74
+ except ErrorMemoria:
75
+ pass
76
+ avisos.append(f"⚠ {id_} is superseded by {reemplazo}; do not treat it as current guidance.")
77
+ else:
78
+ avisos.append(f"⚠ {id_} is superseded; do not treat it as current guidance.")
79
+ else:
80
+ avisos.append(f"⚠ {id_} is {estado}; it is not applicable as current guidance and must not be treated as a rule.")
81
+ return "\n".join(avisos)
@@ -13,6 +13,7 @@ from ratifact.app import _ejecutar, herramienta
13
13
  from ratifact.catalogo import _registros_en
14
14
  from ratifact.config import ErrorMemoria, _mem, _proyectos, _repos, _valor
15
15
  from ratifact.esquema import _bloqueo, _idioma_contenido
16
+ from ratifact.herramientas.decisiones_visibilidad import _avisos_decisiones
16
17
  from ratifact.idioma import bloque_idioma
17
18
  from ratifact.integraciones import registro as _integraciones
18
19
  from ratifact.registros import (_buscar_registro, _commit, _duplicado_reciente, _escribir_registro, _hoy,
@@ -88,7 +89,8 @@ def create_task(project: str, title: str, goal: str, acceptance_criteria: str, d
88
89
  In multi-repo projects, `repo` (required) is the folder where the work happens; in single-repo projects it is
89
90
  ignored (the response says so).
90
91
  It must be self-contained: the coding agent runs it without this chat. `acceptance_criteria`: a verifiable list
91
- (tests that must pass, observable behavior). `decisions`: applicable ADR ids. `files`: paths likely to be
92
+ (tests that must pass, observable behavior). `decisions`: applicable ADR ids; non-accepted decisions are identified
93
+ in the response without preventing task creation. `files`: paths likely to be
92
94
  touched. The user runs it with /run-task T-NNN.
93
95
  `resolves`: pending items the task resolves, comma-separated, each optionally with "(partial)" (e.g.
94
96
  "P-036, P-037 (partial)"); they must exist and be open. Stored in the task ("Resolves" section); when the task is
@@ -151,8 +153,10 @@ def create_task(project: str, title: str, goal: str, acceptance_criteria: str, d
151
153
  _escribir_registro(ruta, meta, "\n\n".join(secciones))
152
154
  sha = _commit(proyecto, [ruta], f"{id_} {titulo} (todo)")
153
155
  linea = _integraciones._linea_integraciones(proyecto)
154
- return (f"{id_} created · suggested branch {meta['branch']} · commit {sha}\nRun it with: /run-task {id_}"
155
- + nota + (f"\n{linea}" if linea else ""))
156
+ respuesta = (f"{id_} created · suggested branch {meta['branch']} · commit {sha}\nRun it with: /run-task {id_}"
157
+ + nota + (f"\n{linea}" if linea else ""))
158
+ avisos = _avisos_decisiones(proyecto, decisiones_norm)
159
+ return respuesta + (f"\n{avisos}" if avisos else "")
156
160
  return _ejecutar(f)
157
161
 
158
162
 
@@ -17,8 +17,8 @@ from ratifact.config import MEM, ErrorMemoria, _mem
17
17
  from ratifact.esquema import _bloqueo, _idioma_contenido
18
18
  from ratifact.idioma import bloque_idioma
19
19
  from ratifact.registros import (MARCA_DUPLICADO, VENTANA_IDEMPOTENCIA_MINUTOS, _buscar_registro, _commit,
20
- _escribir_registro, _hoy, _leer_registro)
21
- from ratifact.vocabulario import TAREAS
20
+ _escribir_registro, _hoy, _leer_registro, _normalizar_id)
21
+ from ratifact.vocabulario import DECISIONES, TAREAS
22
22
 
23
23
  ESTADOS_AMPLIABLES = ("todo", "changes_requested")
24
24
  SECCION_ENMIENDAS = "## Amendments"
@@ -151,13 +151,47 @@ def _relevante(estado: str, bloques: list[tuple[str, int, int]]) -> tuple[str, i
151
151
  return None
152
152
 
153
153
 
154
+ def _decisiones_vigentes(mem, lineas: list[str]) -> list[str]:
155
+ """Renderiza estados actuales en el brief sin modificar las líneas persistidas."""
156
+ salida = lineas.copy()
157
+ inicio = next((i for i, linea in enumerate(salida) if linea.strip() == "## Applicable decisions"), None)
158
+ if inicio is None:
159
+ return salida
160
+ fin = next((i for i in range(inicio + 1, len(salida)) if salida[i].startswith("## ")), len(salida))
161
+ primera = next((i for i in range(inicio + 1, fin) if salida[i].strip()), None)
162
+ if primera is None:
163
+ return salida
164
+ ultima = next(i for i in range(fin - 1, primera - 1, -1) if salida[i].strip())
165
+ ids = [parte.strip() for parte in "\n".join(salida[primera:ultima + 1]).split(",")]
166
+ normalizados = []
167
+ for id_ in ids:
168
+ try:
169
+ normalizado = _normalizar_id(id_)
170
+ except ErrorMemoria:
171
+ return salida
172
+ if not re.fullmatch(r"ADR-\d+", normalizado):
173
+ return salida
174
+ normalizados.append(normalizado)
175
+ actuales = []
176
+ for id_ in normalizados:
177
+ try:
178
+ ruta = _buscar_registro(mem / DECISIONES, id_)
179
+ except ErrorMemoria:
180
+ actuales.append(f"{id_} (missing)")
181
+ continue
182
+ meta, _ = _leer_registro(ruta)
183
+ actuales.append(f"{id_} ({meta.get('status', 'unknown')})")
184
+ return salida[:primera] + [", ".join(actuales)] + salida[ultima + 1:]
185
+
186
+
154
187
  @herramienta
155
188
  def read_task(project: str, id: str) -> str:
156
189
  """Working brief of a task, instead of reading the whole file: the frontmatter, the full spec (Goal, Acceptance
157
190
  criteria, Resolves, Applicable decisions, Files involved, Out of scope, Notes, Amendments, How to verify), every
158
- Amendment block, the block relevant to the status in full (changes_requested → latest Review; in_review or
159
- failed → latest Result block; in_progress → the latest Review it answers) and a one-line index (heading · line
160
- range · size) of every other Result/Review block, readable with read_document and that range."""
191
+ Amendment block, and the block relevant to the status in full (changes_requested → latest Review; in_review or
192
+ failed → latest Result block; in_progress → the latest Review it answers). Applicable decisions show each
193
+ decision's current status at read time. The brief also indexes every other Result/Review block (heading · line
194
+ range · size), readable with read_document and that range."""
161
195
  def f():
162
196
  ruta = _buscar_registro(_mem(project) / TAREAS, id)
163
197
  relativa = f"{MEM}/{ruta.relative_to(_mem(project)).as_posix()}"
@@ -166,7 +200,8 @@ def read_task(project: str, id: str) -> str:
166
200
  cuerpo_desde = _fin_frontmatter(lineas)
167
201
  fin_spec = next((i for i in range(cuerpo_desde, len(lineas)) if lineas[i].strip() in SECCIONES_RESULTADO),
168
202
  len(lineas))
169
- partes = [f"(→ {relativa})\n" + "\n".join(lineas[:fin_spec]).rstrip(),
203
+ spec = _decisiones_vigentes(_mem(project), lineas[:fin_spec])
204
+ partes = [f"(→ {relativa})\n" + "\n".join(spec).rstrip(),
170
205
  bloque_idioma(_idioma_contenido(_mem(project)))]
171
206
  bloques = _bloques(lineas, fin_spec + 1)
172
207
  elegido = _relevante(meta.get("status", ""), bloques)
@@ -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
@@ -22,7 +22,7 @@ The project name in `ratifact` is in this repository's `CLAUDE.md` / `AGENTS.md`
22
22
 
23
23
  Amendments ("### Amendment N" blocks: **Additional criteria** and **Notes**) are part of the spec: they add to the original criteria.
24
24
  If the spec has a `repo` field (multi-repo projects), **everything that follows —git, branches, commands and tests— happens inside that folder**, not at the project root.
25
- 3. Read the decisions listed in "Applicable decisions" (`read_document("<project>", "ADR-NNN")`). Only `accepted` ones are rules.
25
+ 3. Read the decisions listed in "Applicable decisions" (`read_document("<project>", "ADR-NNN")`). `read_task` shows each decision's current status; only `accepted` ones are rules.
26
26
  4. Check with `git status` that the working tree is clean. If there are uncommitted changes, **stop** and ask me; do not move or discard them.
27
27
  5. Branch (the spec's `branch` field). Check whether it already exists with `git branch --list <branch>`:
28
28
  - **It exists** (always for `changes_requested`, often for `failed`): `git switch <branch>` and continue on it. Do not recreate it, rebase it or `--amend` earlier commits: corrections go in new commits.
@@ -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