The Atlas BigLaw / Big Michael — documentation bound to its code
7 documents

What a matter costs

See both ledgers a matter accrues: a CostEntry for every single model call (tokens, USD, cache buckets, local power) and a billable TimeEntry in 6-minute units for task runs, gate reviews, and AI agent work.

biglaw-go/internal/timekeeping/time.go380 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Discover Legal

package timekeeping

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"log/slog"
	"math"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/discover-legal/biglaw-go/internal/csvutil"
	"github.com/discover-legal/biglaw-go/internal/types"
)

// TimeFilter controls which entries List() / Export*() return.
type TimeFilter struct {
	ProfileID    string
	AgentID      string
	TaskID       string
	MatterNumber string
	ClientNumber string
	From         *time.Time
	To           *time.Time
	// nil = all, true = only agent_work events, false = exclude agent_work events
	AgentOnly *bool
}

// TimeStore holds all time entries in memory and persists them to a JSON file.
type TimeStore struct {
	mu        sync.Mutex
	persistMu sync.Mutex // serialises concurrent fire-and-forget persists
	entries   []types.TimeEntry
	path      string
}

// NewTimeStore creates an uninitialised TimeStore. Call Init before use.
func NewTimeStore() *TimeStore {
	return &TimeStore{}
}

// Init loads entries from the given JSON file path. Missing file is not an error.
func (s *TimeStore) Init(path string) error {
	s.path = path
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			s.entries = nil
			return nil
		}
		return err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	return json.Unmarshal(data, &s.entries)
}

// Open records the start of a new time entry. The caller should populate all
// relevant fields (TaskID, MatterNumber, etc.) before passing the entry.
// The ID and StartedAt fields are assigned here.
func (s *TimeStore) Open(entry types.TimeEntry) types.TimeEntry {
	entry.ID = generateID()
	if entry.StartedAt.IsZero() {
		entry.StartedAt = time.Now()
	}
	s.mu.Lock()
	s.entries = append(s.entries, entry)
	s.mu.Unlock()
	s.persist()
	return entry
}

// Close marks the entry with the given ID as finished and calculates billing
// fields. Returns nil if the ID is not found.
func (s *TimeStore) Close(id string) *types.TimeEntry {
	s.mu.Lock()
	defer s.mu.Unlock()
	for i := range s.entries {
		e := &s.entries[i]
		if e.ID != id {
			continue
		}
		now := time.Now()
		e.EndedAt = &now
		e.DurationMs = now.Sub(e.StartedAt).Milliseconds()
		// Billing units: ceil(durationMs / 360_000)  (1 unit = 0.1 h = 6 min)
		e.BillingUnits = int(math.Ceil(float64(e.DurationMs) / 360_000.0))
		if e.BillingRate != nil && *e.BillingRate > 0 {
			amount := float64(e.BillingUnits) * (*e.BillingRate) / 10.0
			e.BillingAmountUsd = &amount
		}
		cp := *e
		go s.persist()
		return &cp
	}
	return nil
}

// GetByID returns a pointer to a copy of the entry with the given ID, or nil.
func (s *TimeStore) GetByID(id string) *types.TimeEntry {
	s.mu.Lock()
	defer s.mu.Unlock()
	for i, e := range s.entries {
		if e.ID == id {
			cp := s.entries[i]
			return &cp
		}
	}
	return nil
}

// UpdateDescription sets the Description field on the entry with the given ID.
func (s *TimeStore) UpdateDescription(id, desc string) {
	s.mu.Lock()
	for i := range s.entries {
		if s.entries[i].ID == id {
			s.entries[i].Description = desc
			break
		}
	}
	s.mu.Unlock()
	s.persist()
}

// SetSuggestions replaces the OCG suggestions on an entry and stamps
// OcgCheckedAt. A missing ID is a no-op (mirrors the TS store).
func (s *TimeStore) SetSuggestions(entryID string, suggestions []types.OcgSuggestion) {
	s.mu.Lock()
	for i := range s.entries {
		if s.entries[i].ID == entryID {
			s.entries[i].OcgSuggestions = suggestions
			s.entries[i].OcgCheckedAt = time.Now().UTC().Format(time.RFC3339)
			break
		}
	}
	s.mu.Unlock()
	s.persist()
}

// AcceptSuggestion rewrites the entry description from the suggestion and
// marks it accepted. Returns the updated entry, or nil if entry or
// suggestion is not found.
func (s *TimeStore) AcceptSuggestion(entryID, ruleID string) *types.TimeEntry {
	s.mu.Lock()
	var updated *types.TimeEntry
	for i := range s.entries {
		if s.entries[i].ID != entryID {
			continue
		}
		for j := range s.entries[i].OcgSuggestions {
			if s.entries[i].OcgSuggestions[j].RuleID == ruleID {
				s.entries[i].Description = s.entries[i].OcgSuggestions[j].SuggestedDescription
				s.entries[i].OcgSuggestions[j].Status = "accepted"
				cp := s.entries[i]
				updated = &cp
				break
			}
		}
		break
	}
	s.mu.Unlock()
	if updated != nil {
		s.persist()
	}
	return updated
}

// DismissSuggestion marks a suggestion dismissed without changing the
// description. Returns the updated entry, or nil if not found.
func (s *TimeStore) DismissSuggestion(entryID, ruleID string) *types.TimeEntry {
	s.mu.Lock()
	var updated *types.TimeEntry
	for i := range s.entries {
		if s.entries[i].ID != entryID {
			continue
		}
		for j := range s.entries[i].OcgSuggestions {
			if s.entries[i].OcgSuggestions[j].RuleID == ruleID {
				s.entries[i].OcgSuggestions[j].Status = "dismissed"
				cp := s.entries[i]
				updated = &cp
				break
			}
		}
		break
	}
	s.mu.Unlock()
	if updated != nil {
		s.persist()
	}
	return updated
}

// List returns a filtered snapshot of entries. All filter fields are optional;
// a zero value means "no constraint on this field".
func (s *TimeStore) List(filter TimeFilter) []types.TimeEntry {
	s.mu.Lock()
	snapshot := make([]types.TimeEntry, len(s.entries))
	copy(snapshot, s.entries)
	s.mu.Unlock()

	var out []types.TimeEntry
	for _, e := range snapshot {
		if !matchesFilter(e, filter) {
			continue
		}
		out = append(out, e)
	}
	return out
}

// MarkClioSynced records the current UTC time as ClioSyncedAt on the given entry.
func (s *TimeStore) MarkClioSynced(id string) {
	s.mu.Lock()
	for i := range s.entries {
		if s.entries[i].ID == id {
			s.entries[i].ClioSyncedAt = time.Now().UTC().Format(time.RFC3339)
			break
		}
	}
	s.mu.Unlock()
	s.persist()
}

// SplitClioUnsynced partitions billable entries for a Clio sync run: entries
// with a positive duration that have never been synced go to toSync; already
// synced ones are counted as skipped. Open entries (durationMs <= 0) are
// excluded from both, mirroring the TS /time-entries/sync-to-clio filter.
func SplitClioUnsynced(entries []types.TimeEntry) (toSync []types.TimeEntry, skipped int) {
	for _, e := range entries {
		if e.DurationMs <= 0 {
			continue
		}
		if e.ClioSyncedAt != "" {
			skipped++
			continue
		}
		toSync = append(toSync, e)
	}
	return toSync, skipped
}

// ClioDurationHours converts an entry to decimal hours for a Clio activity:
// the larger of the 6-minute billing-unit total and the raw elapsed time,
// rounded to two decimal places (TS: max(billingUnits*0.1, durationMs/3.6e6)).
func ClioDurationHours(e types.TimeEntry) float64 {
	h := math.Max(float64(e.BillingUnits)*0.1, float64(e.DurationMs)/3_600_000.0)
	return math.Round(h*100) / 100
}

// ExportJSON returns filtered entries as a slice (suitable for JSON marshalling).
func (s *TimeStore) ExportJSON(filter TimeFilter) []types.TimeEntry {
	return s.List(filter)
}

// ExportCSV returns a CSV string of all filtered entries.
// Headers: id,event,profileId,profileName,agentId,agentName,taskId,
//
//	matterNumber,clientNumber,description,startedAt,endedAt,durationMs,
//	billingUnits,billingRate,billingAmountUsd,utbmsTaskCode,utbmsActivityCode,
//	clioSyncedAt
func (s *TimeStore) ExportCSV(filter TimeFilter) string {
	entries := s.List(filter)

	var sb strings.Builder
	sb.WriteString("id,event,profileId,profileName,agentId,agentName,taskId," +
		"matterNumber,clientNumber,description,startedAt,endedAt,durationMs," +
		"billingUnits,billingRate,billingAmountUsd,utbmsTaskCode,utbmsActivityCode," +
		"clioSyncedAt\n")

	for _, e := range entries {
		endedAt := ""
		if e.EndedAt != nil {
			endedAt = e.EndedAt.UTC().Format(time.RFC3339)
		}
		rate := ""
		if e.BillingRate != nil {
			rate = fmt.Sprintf("%.4f", *e.BillingRate)
		}
		amount := ""
		if e.BillingAmountUsd != nil {
			amount = fmt.Sprintf("%.4f", *e.BillingAmountUsd)
		}
		sb.WriteString(fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%d,%d,%s,%s,%s,%s,%s\n",
			csvEscape(e.ID),
			csvEscape(string(e.Event)),
			csvEscape(e.ProfileID),
			csvEscape(e.ProfileName),
			csvEscape(e.AgentID),
			csvEscape(e.AgentName),
			csvEscape(e.TaskID),
			csvEscape(e.MatterNumber),
			csvEscape(e.ClientNumber),
			csvEscape(e.Description),
			e.StartedAt.UTC().Format(time.RFC3339),
			endedAt,
			e.DurationMs,
			e.BillingUnits,
			rate,
			amount,
			csvEscape(e.UTBMSTaskCode),
			csvEscape(e.UTBMSActivityCode),
			csvEscape(e.ClioSyncedAt),
		))
	}
	return sb.String()
}

// ─── internal helpers ─────────────────────────────────────────────────────────

func matchesFilter(e types.TimeEntry, f TimeFilter) bool {
	if f.ProfileID != "" && e.ProfileID != f.ProfileID {
		return false
	}
	if f.AgentID != "" && e.AgentID != f.AgentID {
		return false
	}
	if f.TaskID != "" && e.TaskID != f.TaskID {
		return false
	}
	if f.MatterNumber != "" && e.MatterNumber != f.MatterNumber {
		return false
	}
	if f.ClientNumber != "" && e.ClientNumber != f.ClientNumber {
		return false
	}
	if f.From != nil && e.StartedAt.Before(*f.From) {
		return false
	}
	if f.To != nil && e.StartedAt.After(*f.To) {
		return false
	}
	if f.AgentOnly != nil {
		isAgentWork := e.Event == types.TimeEventAgentWork
		if *f.AgentOnly && !isAgentWork {
			return false
		}
		if !*f.AgentOnly && isAgentWork {
			return false
		}
	}
	return true
}

// persist writes the entry list atomically: write to <path>.tmp then rename.
// persist writes time entries atomically. 0600: billable time is client data.
func (s *TimeStore) persist() {
	s.persistMu.Lock()
	defer s.persistMu.Unlock()
	s.mu.Lock()
	data, _ := json.MarshalIndent(s.entries, "", "  ")
	s.mu.Unlock()
	tmp := s.path + ".tmp"
	if err := os.WriteFile(tmp, data, 0600); err != nil {
		slog.Error("timekeeping: persist write failed", "path", tmp, "err", err)
		return
	}
	if err := os.Rename(tmp, s.path); err != nil {
		slog.Error("timekeeping: persist rename failed", "path", s.path, "err", err)
	}
}

func generateID() string {
	b := make([]byte, 16)
	rand.Read(b)
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}

// csvEscape quotes a field (RFC 4180, embedded quotes doubled) and
// neutralizes spreadsheet formula injection via the shared helper — string
// fields like description and names carry LLM-/user-supplied content.
func csvEscape(s string) string {
	return csvutil.Escape(s)
}