ratifact 1.0.1__tar.gz → 1.0.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {ratifact-1.0.1 → ratifact-1.0.2}/LEEME.md +28 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/PKG-INFO +28 -1
- {ratifact-1.0.1 → ratifact-1.0.2}/README.md +27 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/pyproject.toml +1 -1
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/__init__.py +1 -1
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/doctor.py +12 -3
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/informe.py +10 -1
- ratifact-1.0.2/ratifact/informe_tokens.py +246 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/modelos.py +11 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/.gitignore +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/LICENSE +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/app.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/archivos.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/build.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/busqueda.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/catalogo.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/cli.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/clientes.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/clientes_toml.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/config.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/delegacion.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/doctor_plataforma.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/doctor_vivos.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/esquema.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/__init__.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/contexto_documentos.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/decisiones.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/pendientes_sesiones.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/proyectos.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/tareas.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/herramientas/tareas_brief.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/idioma.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/informe_delegacion.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/informe_memoria.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/instalacion.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/instalar.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/instalar_extras.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/integraciones/__init__.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/integraciones/base.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/integraciones/codegraph.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/integraciones/engram.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/integraciones/gentle_ai.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/integraciones/registro.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/listado.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/migracion_v2.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/plantillas.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/plurales.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/procesos.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/prompts.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/registros.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/retirado.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/rutas.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/skills/run-task/SKILL.md +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/upgrade.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/upgrade_aplicar.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/vocabulario.py +0 -0
- {ratifact-1.0.1 → ratifact-1.0.2}/ratifact/workers.py +0 -0
|
@@ -131,6 +131,34 @@ cada proyecto (o `models: session default`).
|
|
|
131
131
|
No cubre renombrar un proyecto ni mover la ubicación de su memoria (`.ratifact/<nombre>` o la clave `"memoria"`):
|
|
132
132
|
para eso edite `projects.json` a mano y mueva la carpeta con `git mv`/`mv` según corresponda.
|
|
133
133
|
|
|
134
|
+
### Consumo de tokens en `report`
|
|
135
|
+
|
|
136
|
+
`ratifact report` puede mostrar el consumo real de tokens de cada tarea ejecutada con Claude Code, separado entre la
|
|
137
|
+
sesión principal y los trabajadores y por modelo (para evaluar si delegar ahorra presupuesto del modelo principal).
|
|
138
|
+
Está desactivado por defecto: se activa con `"token_usage": "on"` en `settings.json`, junto a `"models"` y
|
|
139
|
+
`"delegation"` (`"off"` o ausente lo deja apagado; un valor inválido se trata como apagado y `ratifact doctor` lo
|
|
140
|
+
reporta). Con la función apagada, `report` no abre ningún archivo de transcripciones.
|
|
141
|
+
|
|
142
|
+
```json
|
|
143
|
+
{"token_usage": "on"}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
- Fuente: las transcripciones locales de Claude Code, `$CLAUDE_CONFIG_DIR/projects` o, si no, `~/.claude/projects`.
|
|
147
|
+
Solo lee campos de metadatos de cada línea (fecha, carpeta de trabajo, rama, modelo, ids y los cuatro contadores de
|
|
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.
|
|
153
|
+
- Por tarea con `routing:` del período: su política de delegación y, para la sesión principal y para los
|
|
154
|
+
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
|
|
156
|
+
los promedios las tareas con una línea `Workers` válida en su resultado; una tarea sin ella (por ejemplo, en curso)
|
|
157
|
+
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`.
|
|
159
|
+
- Solo cubre Claude Code; Claude Code borra las transcripciones pasado su período de retención, así que las tareas
|
|
160
|
+
viejas pierden sus datos. El desglose es por modelo, no por rol.
|
|
161
|
+
|
|
134
162
|
### Política de delegación
|
|
135
163
|
|
|
136
164
|
Si una tarea se delega lo decide ratifact al planificar, no el agente que la ejecuta. `"delegation": "required" |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: ratifact
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.2
|
|
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
|
|
@@ -158,6 +158,33 @@ session's model. With no configuration the response is unchanged. An invalid `se
|
|
|
158
158
|
(it is ignored with a warning in that block); `ratifact doctor` reports it without changing it and shows each
|
|
159
159
|
project's effective models (or `models: session default`).
|
|
160
160
|
|
|
161
|
+
## Token usage in `report`
|
|
162
|
+
|
|
163
|
+
`ratifact report` can show the real token usage of each task run with Claude Code, split between the main session and
|
|
164
|
+
the workers and by model (to judge whether delegating saves the main model's budget). It is off by default: turn it on
|
|
165
|
+
with `"token_usage": "on"` in `settings.json`, next to `"models"` and `"delegation"` (`"off"` or absent keeps it off; an
|
|
166
|
+
invalid value is treated as off and `ratifact doctor` reports it). With it off, `report` opens no transcript file.
|
|
167
|
+
|
|
168
|
+
```json
|
|
169
|
+
{"token_usage": "on"}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
- Source: the local Claude Code transcripts, `$CLAUDE_CONFIG_DIR/projects` or else `~/.claude/projects`. It reads only
|
|
173
|
+
metadata fields of each line (timestamp, working folder, branch, model, ids and the four token counters of `usage`),
|
|
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.
|
|
179
|
+
- Per task with `routing:` in the period: its delegation policy and, for the main session and for the workers (with
|
|
180
|
+
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
|
|
182
|
+
valid `Workers` line enter the averages; a task without one (for example, still in progress) is listed with its
|
|
183
|
+
figures but counts in neither group. A task with no data (another
|
|
184
|
+
client, or transcripts already deleted) shows `no data`.
|
|
185
|
+
- It only covers Claude Code; transcripts are deleted by Claude Code after its retention period, so old tasks lose
|
|
186
|
+
their data. The breakdown is per model, not per role.
|
|
187
|
+
|
|
161
188
|
## Delegation
|
|
162
189
|
|
|
163
190
|
Delegation policy: ratifact, not the executing agent, decides whether a task is delegated.
|
|
@@ -128,6 +128,33 @@ session's model. With no configuration the response is unchanged. An invalid `se
|
|
|
128
128
|
(it is ignored with a warning in that block); `ratifact doctor` reports it without changing it and shows each
|
|
129
129
|
project's effective models (or `models: session default`).
|
|
130
130
|
|
|
131
|
+
## Token usage in `report`
|
|
132
|
+
|
|
133
|
+
`ratifact report` can show the real token usage of each task run with Claude Code, split between the main session and
|
|
134
|
+
the workers and by model (to judge whether delegating saves the main model's budget). It is off by default: turn it on
|
|
135
|
+
with `"token_usage": "on"` in `settings.json`, next to `"models"` and `"delegation"` (`"off"` or absent keeps it off; an
|
|
136
|
+
invalid value is treated as off and `ratifact doctor` reports it). With it off, `report` opens no transcript file.
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{"token_usage": "on"}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
- Source: the local Claude Code transcripts, `$CLAUDE_CONFIG_DIR/projects` or else `~/.claude/projects`. It reads only
|
|
143
|
+
metadata fields of each line (timestamp, working folder, branch, model, ids and the four token counters of `usage`),
|
|
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.
|
|
149
|
+
- Per task with `routing:` in the period: its delegation policy and, for the main session and for the workers (with
|
|
150
|
+
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
|
|
152
|
+
valid `Workers` line enter the averages; a task without one (for example, still in progress) is listed with its
|
|
153
|
+
figures but counts in neither group. A task with no data (another
|
|
154
|
+
client, or transcripts already deleted) shows `no data`.
|
|
155
|
+
- It only covers Claude Code; transcripts are deleted by Claude Code after its retention period, so old tasks lose
|
|
156
|
+
their data. The breakdown is per model, not per role.
|
|
157
|
+
|
|
131
158
|
## Delegation
|
|
132
159
|
|
|
133
160
|
Delegation policy: ratifact, not the executing agent, decides whether a task is delegated.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "ratifact"
|
|
3
|
-
version = "1.0.
|
|
3
|
+
version = "1.0.2"
|
|
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.
|
|
7
|
+
__version__ = "1.0.2" # igual que [project].version de pyproject.toml (tests/test_cli.py lo comprueba)
|
|
@@ -130,20 +130,29 @@ def _settings(config: Path, acciones: list[str]) -> list[str]:
|
|
|
130
130
|
se modifica."""
|
|
131
131
|
ruta = modelos.ruta_settings(config)
|
|
132
132
|
if not ruta.is_file():
|
|
133
|
-
return [f"Settings: {ruta} (not created; models: session default)"]
|
|
133
|
+
return [f"Settings: {ruta} (not created; models: session default · token_usage: off (default))"]
|
|
134
134
|
try:
|
|
135
135
|
globales = modelos.leer_global(config)
|
|
136
136
|
except _cfg.ErrorMemoria as e:
|
|
137
137
|
acciones.append(f"settings.json: {e} Fix it by hand (ratifact never rewrites it)")
|
|
138
138
|
return [f"Settings: {ruta} (INVALID)"]
|
|
139
|
-
|
|
139
|
+
datos = modelos.leer_settings(config)
|
|
140
|
+
politica, tokens = datos.get(delegacion.CLAVE), datos.get(modelos.CLAVE_TOKENS)
|
|
141
|
+
invalido = False
|
|
140
142
|
if politica is not None and politica not in delegacion.POLITICAS:
|
|
141
143
|
acciones.append(f"settings.json: invalid `delegation` {politica!r} (valid: {', '.join(delegacion.POLITICAS)}). "
|
|
142
144
|
"Fix it by hand (ratifact never rewrites it)")
|
|
145
|
+
invalido = True
|
|
146
|
+
if tokens is not None and not (isinstance(tokens, str) and tokens in modelos.VALORES_TOKENS):
|
|
147
|
+
acciones.append(f"settings.json: invalid `token_usage` {tokens!r} (valid: {', '.join(modelos.VALORES_TOKENS)}; "
|
|
148
|
+
"treated as off). Fix it by hand (ratifact never rewrites it)")
|
|
149
|
+
invalido = True
|
|
150
|
+
if invalido:
|
|
143
151
|
return [f"Settings: {ruta} (INVALID)"]
|
|
144
152
|
return [f"Settings: {ruta} · global models: "
|
|
145
153
|
+ (", ".join(f"{r}={m}" for r, m in globales.items()) or "none")
|
|
146
|
-
+ f" · delegation: {politica or delegacion.DEFECTO + ' (default)'}"
|
|
154
|
+
+ f" · delegation: {politica or delegacion.DEFECTO + ' (default)'}"
|
|
155
|
+
+ f" · token_usage: {tokens or 'off (default)'}"]
|
|
147
156
|
|
|
148
157
|
|
|
149
158
|
def _clientes(acciones: list[str], paquete: Path | None = None) -> list[str]:
|
|
@@ -15,9 +15,10 @@ import sys
|
|
|
15
15
|
from collections import Counter, defaultdict
|
|
16
16
|
from pathlib import Path
|
|
17
17
|
|
|
18
|
+
from ratifact import informe_tokens, modelos
|
|
18
19
|
from ratifact.config import _entorno
|
|
19
20
|
from ratifact.informe_delegacion import indicador_delegacion
|
|
20
|
-
from ratifact.informe_memoria import higiene_pendientes, indicador_decisiones
|
|
21
|
+
from ratifact.informe_memoria import higiene_pendientes, indicador_decisiones, ruta_config
|
|
21
22
|
from ratifact.plurales import contar
|
|
22
23
|
from ratifact.rutas import log_por_defecto
|
|
23
24
|
from ratifact.vocabulario import HERRAMIENTAS_V0
|
|
@@ -175,6 +176,14 @@ def main(argv: list[str] | None = None, a: argparse.Namespace | None = None) ->
|
|
|
175
176
|
print("\nDelegation: tasks with `routing:` changed in the period")
|
|
176
177
|
for linea in indicador_delegacion(desde, a.proyecto):
|
|
177
178
|
print(linea)
|
|
179
|
+
if modelos.token_usage(ruta_config()) == "on":
|
|
180
|
+
print("\nToken usage (Claude Code transcripts)")
|
|
181
|
+
try:
|
|
182
|
+
lineas_tokens = informe_tokens.seccion(desde, a.proyecto)
|
|
183
|
+
except Exception as e: # the transcripts are not a public format: never make report fail
|
|
184
|
+
lineas_tokens = [f" token usage unavailable: {type(e).__name__}"]
|
|
185
|
+
for linea in lineas_tokens:
|
|
186
|
+
print(linea)
|
|
178
187
|
print("\nOpen pending items referenced by merged tasks")
|
|
179
188
|
for linea in higiene_pendientes(a.proyecto):
|
|
180
189
|
print(linea)
|
|
@@ -0,0 +1,246 @@
|
|
|
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]
|
|
@@ -17,6 +17,8 @@ ROLES = ("explore", "write", "verify")
|
|
|
17
17
|
ARCHIVO = "settings.json"
|
|
18
18
|
HEREDAR = "inherit"
|
|
19
19
|
CLAVE = "models"
|
|
20
|
+
CLAVE_TOKENS = "token_usage"
|
|
21
|
+
VALORES_TOKENS = ("on", "off")
|
|
20
22
|
|
|
21
23
|
|
|
22
24
|
def ruta_settings(config: Path | None = None) -> Path:
|
|
@@ -55,6 +57,15 @@ def leer_settings(config: Path | None = None) -> dict:
|
|
|
55
57
|
return datos
|
|
56
58
|
|
|
57
59
|
|
|
60
|
+
def token_usage(config: Path | None = None) -> str:
|
|
61
|
+
""""on" | "off" from settings.json: absent, unreadable or invalid is "off" (never raises)."""
|
|
62
|
+
try:
|
|
63
|
+
valor = leer_settings(config).get(CLAVE_TOKENS)
|
|
64
|
+
except (ErrorMemoria, OSError):
|
|
65
|
+
return "off"
|
|
66
|
+
return valor if isinstance(valor, str) and valor in VALORES_TOKENS else "off"
|
|
67
|
+
|
|
68
|
+
|
|
58
69
|
def leer_global(config: Path | None = None) -> dict[str, str]:
|
|
59
70
|
"""Modelos globales de settings.json. Sin archivo o sin `models`: {}. JSON inválido o roles desconocidos:
|
|
60
71
|
ErrorMemoria con un mensaje claro (nunca se modifica el archivo)."""
|
|
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
|
|
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
|