Skip to content

← Praxis Today: time budgets and atomic PostgreSQL planning

Praxis Today: time budgets and atomic PostgreSQL planning

English ↔ Español

A different question from the goal graph

My earlier Praxis article described one goal tree powering a 2D map, list and 3D constellation. The new Today feature poses a different challenge: a goal tree can contain hundreds of tasks, but each day has only 24 hours. Dragging cards into a calendar does not solve capacity, competing edits or the need to preserve a plan when a change fails.

The implementation is documented in praxis-app, particularly src/lib/day.ts and migration 027_daily_blocks.sql. This is a code-based engineering analysis, not a claim about adoption or measured production performance.

Two budgets inside one day

The default preferences reserve eight hours for sleep, three for routine and up to six for tasks. These are configurable product defaults, not a prescription. Seven hours remain unallocated in that initial example.

text
24h = 8h sleep + 3h routine + 6h tasks + 7h unallocated

A completed task still occupies time; a released task does not. Completion changes progress, not the length of the day. That distinction is easy to miss when a user interface presents everything as a checklist.

A pure function for capacity

dailyCapacity calculates vital minutes, task minutes, the effective limit and percentage without depending on React. The essential rule is:

ts
const taskLimit = Math.max(0, Math.min(limit, 1440 - vitalMinutes))
const percent = taskLimit > 0 ? taskMinutes / taskLimit * 100 : 100

The UI labels up to 80% sustainable, above 80% attention and 100% full. assessAddition prompts pruning when the limit is reached; the database check rejects totals above the limit. A UX warning and a persistence invariant are different policies, and both deserve tests.

Drag-and-drop is a proposal

The task drawer prioritizes items due today, weekly commitments and if-then plans. Difficulty suggests durations of 30, 60 or 120 minutes. Before saving, assessAddition considers an existing edit and the planned blocks that could be moved out.

Sleep, routine and completed blocks are not candidates for pruning. The custom drag type application/x-praxis-day checks the shape of dropped data. It is a useful interface boundary, while the final decision about a schedule remains with the domain operation.

One budget across all maps

The migration separates daily_preferences, daily_days and daily_blocks. Preferences define the vital base; days contain limits and closure state; blocks contain durations, statuses, order and optional links to the goal tree. The day is keyed by user and local date. Opening another map cannot create another six-hour allowance.

A partial unique index prevents the same active goal-tree node from being allocated twice on the same day. The restored_from_id field connects a recovered block to its source. These database properties matter when two screens save near the same moment.

Why one database operation matters

A single 45-minute block may fit, while two simultaneous 45-minute additions do not fit the same remaining hour. Validating each row is insufficient; the sum must be checked after changes.

The database migration keeps reads scoped to the user and routes modifications through public.daily_plan, which also checks the caller's map-edit permission. The function groups related changes so that the budget is assessed as a whole. Its privileged execution context warrants dedicated review and access tests; see the Supabase documentation for the interaction between row policies and database privileges.

Two tabs, one remaining hour

The operation uses a transaction-scoped advisory lock keyed to the user. This lets one edit finish before the next recalculates the remaining capacity. The same approach covers moves between today and tomorrow, including tasks from different maps, without serializing unrelated users.

The PostgreSQL documentation distinguishes session-scoped from transaction-scoped locks. A lock is part of a consistent writing protocol, not a replacement for constraints or final capacity checks.

Pruning must be atomic

The critical workflow begins when today is full. The user selects planned blocks to move. The operation validates them, prepares tomorrow, checks tomorrow's capacity, releases the selected blocks from today, inserts the new task and verifies today's final capacity.

text
Validate -> Prepare tomorrow -> Check capacity
         -> Release today -> Add task -> Commit

If tomorrow is full, the migration signals DAILY_TOMORROW_CAPACITY and the transaction aborts. Today's previous plan remains intact. Splitting the move into two unrelated requests would allow a failure between them to leave a partial schedule. The same principle applies to inventory transfers and financial allocations.

Completion, shutdown and reopening

daily_plan handles save, complete, release, shutdown, settings and reopen. Completing a block linked to a goal-tree node updates the node. Shutdown records closed_at and resolves pending work, either returning it to the tree or moving it to tomorrow. Reopening makes adjustments possible again.

The operation receives an explicit local date. The server's midnight is not necessarily the user's midnight. Closure is therefore a recorded decision, not a side effect of the clock.

Testing without overstating evidence

The repository documents Vitest and PGlite for calculations and daily database flows. PGlite runs PostgreSQL in WebAssembly and is suitable for local testing. Still, pure functions, database operations and integration with multiple signed-in sessions are distinct test layers.

I inspected the implementation and documented commands; I did not run the suite or benchmark production. Important cases include two tabs competing for the last slot, a closed tomorrow, changes to vital preferences, completed blocks and repeated restoration.

Alternatives and the lesson

A single JSON document per day could simplify reads but complicate uniqueness and queries. Several independent client writes could reduce database code but increase partial-state risk. A dedicated backend transaction would also work; the chosen RPC keeps the aggregate rule near its data.

The trade-off is more PL/pgSQL and some waiting between edits from the same user. The benefit is that an unsuccessful replan does not erase the existing schedule. My checklist is to separate physical and plannable capacity, count completed time, enforce uniqueness, validate totals transactionally, test simultaneous edits and use explicit local dates.

Today looks like a calendar, but its core is resource allocation: the UI proposes, a pure function explains, and PostgreSQL decides whether the whole change can be committed. See the Praxis case study.

Una pregunta distinta al grafo de objetivos

En mi artículo anterior sobre Praxis expliqué cómo un árbol de objetivos alimenta mapa 2D, lista y constelación 3D sin duplicar el estado. La nueva función Hoy introduce otra restricción: un árbol puede contener cientos de tareas, pero cada día sigue teniendo 24 horas. Arrastrar tarjetas a una agenda no resuelve por sí solo la capacidad, las ediciones simultáneas ni la conservación del plan cuando algo falla.

La implementación está documentada en praxis-app, especialmente en src/lib/day.ts y la migración 027_daily_blocks.sql. Este texto analiza código y documentación, no métricas de adopción ni rendimiento medido en producción.

Dos presupuestos dentro de un día

Las preferencias iniciales reservan ocho horas de sueño, tres de rutina y hasta seis para tareas. Son valores configurables del producto, no una prescripción. Con ellos quedan siete horas sin asignar.

text
24h = 8h sueño + 3h rutina + 6h tareas + 7h sin asignar

Una tarea terminada sigue ocupando el tiempo que consumió; una tarea liberada deja de contar. Completar cambia el progreso, no la duración del día. Es una diferencia importante cuando la interfaz presenta todo como una lista de casillas.

Una función pura para la capacidad

dailyCapacity calcula minutos vitales, minutos de tareas, límite efectivo y porcentaje sin depender de React. La regla central es:

ts
const taskLimit = Math.max(0, Math.min(limit, 1440 - vitalMinutes))
const percent = taskLimit > 0 ? taskMinutes / taskLimit * 100 : 100

La interfaz considera sostenible hasta el 80%, advierte por encima y marca el 100% como lleno. assessAddition propone recortar cuando se alcanza el límite; la validación de base de datos rechaza un total que lo supere. Un aviso de experiencia de usuario y una invariante persistida son políticas diferentes y requieren pruebas separadas.

Arrastrar expresa una intención

El cajón prioriza tareas con plazo hoy, compromisos semanales y planes si-entonces. La dificultad sugiere duraciones de 30, 60 o 120 minutos. Antes de guardar, assessAddition considera una edición existente y los bloques planificados que podrían salir del día.

El sueño, la rutina y los bloques terminados no son candidatos al recorte. El tipo de arrastre application/x-praxis-day valida la estructura de los datos recibidos. Es una protección de interfaz; la decisión final sobre el plan corresponde a la operación del dominio.

Un presupuesto para todos los mapas

La migración separa daily_preferences, daily_days y daily_blocks. Las preferencias definen la base vital; los días contienen límites y cierre; los bloques contienen duraciones, estados, orden y vínculos opcionales al árbol. La clave del día combina usuario y fecha local. Abrir otro mapa no crea otras seis horas.

Un índice único parcial impide asignar dos veces el mismo nodo activo en el mismo día. restored_from_id conecta un bloque recuperado con su origen. Estas propiedades del banco siguen vigentes cuando dos pantallas intentan guardar casi a la vez.

Por qué importa una sola operación de base de datos

Un bloque de 45 minutos puede ser válido por separado, mientras que dos bloques simultáneos de 45 minutos no caben en la misma hora disponible. Validar cada fila no basta: también debe comprobarse la suma.

La migración limita la lectura a cada usuario y dirige las modificaciones a public.daily_plan, que comprueba el permiso de edición del mapa. La función agrupa los cambios para evaluar el presupuesto completo. Su contexto de ejecución privilegiado requiere revisión y pruebas de permisos; la documentación de Supabase explica la relación entre políticas por fila y privilegios del banco.

Dos pestañas, una hora libre

La operación utiliza un advisory lock de alcance transaccional asociado al usuario. Una edición termina antes de que la siguiente vuelva a calcular la capacidad. También cubre movimientos entre hoy y mañana, incluso desde mapas distintos, sin bloquear a otros usuarios.

La documentación de PostgreSQL diferencia bloqueos de sesión y de transacción. Un lock forma parte de un protocolo consistente de escritura; no sustituye restricciones ni comprobaciones finales.

Recortar hoy debe ser atómico

El flujo crítico empieza cuando hoy está lleno. El usuario elige bloques planificados para trasladar. La operación los valida, prepara mañana, comprueba su capacidad, libera los bloques de hoy, incorpora la nueva tarea y verifica el total final.

text
Validar -> Preparar mañana -> Comprobar capacidad
        -> Liberar hoy -> Añadir tarea -> Confirmar

Si mañana no tiene espacio, la migración emite DAILY_TOMORROW_CAPACITY y la transacción se cancela. El plan anterior permanece intacto. Dividir el traslado en dos solicitudes independientes permitiría que un error intermedio dejara un calendario incompleto. El mismo principio sirve para transferencias de inventario y presupuestos financieros.

Terminar, cerrar y reabrir

daily_plan admite save, complete, release, shutdown, settings y reopen. Terminar un bloque vinculado a un nodo también actualiza ese nodo. Cerrar registra closed_at y resuelve los pendientes: devolverlos al árbol o moverlos a mañana. Reabrir permite ajustes posteriores.

La operación recibe una fecha local explícita. La medianoche del servidor no coincide necesariamente con la del usuario. El cierre es una decisión registrada, no un efecto automático del reloj.

Pruebas sin exagerar la evidencia

El repositorio documenta Vitest y PGlite para cálculos y flujos diarios de base de datos. PGlite ejecuta PostgreSQL en WebAssembly y sirve para pruebas locales. Aun así, funciones puras, operaciones SQL e integración con varias sesiones autenticadas son niveles de evidencia diferentes.

Revisé la implementación y los comandos documentados; no ejecuté la suite ni medí producción. Los casos importantes incluyen dos pestañas disputando el último espacio, mañana cerrado, cambios de preferencias, bloques terminados y recuperaciones repetidas.

Alternativas y aprendizaje

Un JSON por día simplificaría lecturas, pero dificultaría unicidad y consultas. Varias escrituras independientes desde el cliente reducirían código SQL, pero aumentarían el riesgo de estado parcial. Un backend dedicado con transacciones también sería válido; la RPC elegida mantiene la regla agregada cerca de los datos.

El coste es más PL/pgSQL y cierta espera entre ediciones del mismo usuario. El beneficio es que un intento fallido de reorganización no borra el plan existente. Mi lista de comprobación: separar capacidad física y planificable, seguir contando tiempo completado, imponer unicidad, validar totales transaccionalmente, probar ediciones simultáneas y utilizar fechas locales explícitas.

Hoy parece un calendario, pero su núcleo es asignación de recursos: la interfaz propone, una función pura explica y PostgreSQL decide si todo el cambio puede confirmarse. Consulta el caso de estudio de Praxis.