oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import "time"
4
5// Models is every model the schema generator manages. Keep it in step
6// with the structs below: `rastrillo migration generate` reads it to work
7// out what the database should look like, and `rastrillo migration check`
8// fails CI when it and the migrations disagree.
9var Models = []any{
10 &Member{},
11 &CardType{},
12 &FieldDef{},
13 &Card{},
14 &CardValue{},
15 &Entry{},
16 &EntryValue{},
17 &Ref{},
18 &Event{},
19}
20
21// The design is docs/superpowers/specs/2026-09-19-fichas-design.md. Two of
22// its rulings shape every struct in this file and are worth stating here,
23// because the next person will otherwise read the schema as timid.
24//
25// §4.3, ruled 2026-09-20: there are no user-defined tables. A card type is
26// rows in CardType and FieldDef, never DDL. sqlite_master holds table and
27// column names in plaintext in the file litestream replicates, so a
28// user-created type would write its own vocabulary — "Litigation",
29// "settlement_amount" — into the clear. That is the leak §4.1 closed by
30// sealing everything else.
31//
32// §4.1: sealed does not mean unqueryable. The search index lives in memory
33// and is rebuilt from these rows on wake, exactly as memoria's does and for
34// the same reason (FTS5 stores its postings in plaintext). So a column is
35// plaintext here ONLY where the durable file must answer without the key:
36// the suite contract's feed row, referential integrity, and the reach mark
37// a sibling evaluates for itself. Everything else is sealed.
38
39// Scopes for CardType.Scope.
40const (
41 ScopeCard = "card"
42 ScopeEntry = "entry"
43)
44
45// Member is a person this instance has seen. It exists so that "who owns
46// this card" and "who wrote this entry" are FOREIGN KEYS rather than
47// addresses repeated in the clear on every row.
48//
49// The first draft put the address string directly on Card.Owner and
50// Entry.Actor and cited Sheets as precedent. **That citation was wrong.**
51// Sheets' Event.ActorID and Cell.UpdatedBy are uint64 FKs to a Member row;
52// the address is plaintext exactly ONCE, in one table, and Sheets §2.2
53// publishes that as a stated leak. Repeating it per card, indexed, beside
54// an indexed updated_at, would have published per-person card counts and
55// activity cadence — the shape memoria seals its breaker tally for.
56//
57// So the address is stored memoria's way rather than Sheets': an
58// AddressPrint for lookup and a SealedAddress for display. A print is
59// admissible here although a roster is low-cardinality, because the print
60// is never compared across a field boundary — it answers exactly one
61// question, "which member is this", for a caller who already holds the
62// address.
63type Member struct {
64 ID int64
65 // AddressPrint is the keyed fingerprint used to find a member by
66 // address without holding one. Unique: two rows for one person would
67 // split their cards in half.
68 AddressPrint string `gorm:"uniqueIndex;size:64"`
69 // SealedAddress is the address itself, for display.
70 SealedAddress []byte
71 CreatedAt time.Time
72 UpdatedAt time.Time
73}
74
75// Tier is where a field's values live: the vocabulary of §4.2.
76//
77// TierPrint is a keyed one-way fingerprint and answers equality only — never
78// ranges, never ordering. It is for HIGH-CARDINALITY values. A print over a
79// five-value enum yields five visible equality classes that frequency
80// analysis puts in order, which is why `stage` is sealed and not printed.
81//
82// TierPlain is reserved for the structural fields this app ships. A
83// user-defined field may be TierSealed or TierPrint and nothing else
84// (§4.3), so that nobody marks a sensitive field plaintext without
85// understanding the trade.
86type Tier string
87
88const (
89 TierSealed Tier = "sealed"
90 TierPrint Tier = "print"
91 TierPlain Tier = "plain"
92)
93
94// CardType is one kind of card. Customer and Call Log ship as seeded rows
95// of this table (§4.4) — "ship a catalogue, not a builder".
96type CardType struct {
97 ID int64
98 // Key is opaque and ours, never the user's words: built-ins take
99 // stable constants (f_customer), anything added later takes a
100 // generated one. It is plaintext because code selects on it.
101 Key string `gorm:"uniqueIndex;size:64"`
102 // Scope is whether this type describes a CARD or an ENTRY.
103 //
104 // It exists because AddEntry used to look up the Call Log type by a
105 // constant regardless of what it was asked for, which bound every
106 // entry kind to one type's field definitions — and CreateCard would
107 // just as happily make a *card* of type Call Log. Entries are
108 // immutable (§3), so every row written that way is a row that cannot
109 // be corrected; there is no backfill for an entry whose type was an
110 // accident of a constant.
111 //
112 // Plaintext under §4.1 case 4: this app's own vocabulary.
113 Scope string `gorm:"size:8;not null;index"`
114 // SealedLabel is what a person reads. Sealed even for built-ins, so
115 // that one rule covers the catalogue and whatever is added to it —
116 // a label that is sometimes plaintext is a rule nobody can apply.
117 SealedLabel []byte
118 // SealedPlural is what a list of these is called — "Customers". Sealed
119 // for the same reason the label is: a user-added type's name is the
120 // user's own words. Empty means "derive it from the label".
121 SealedPlural []byte
122 // FaceKeys is the card face — which fields the Cards view shows, in
123 // order — as a JSON array of FieldDef keys, plus FaceLatestCall for
124 // the latest entry. Plaintext under §4.1 case 4: it is a list of this
125 // app's opaque keys, and never a value. Empty means the type's default.
126 FaceKeys string `gorm:"size:2048"`
127 CreatedAt time.Time
128 UpdatedAt time.Time
129 // RESTRICT, not CASCADE: deleting a type out from under live cards
130 // must fail rather than take the cards with it.
131 Fields []FieldDef `gorm:"constraint:OnDelete:RESTRICT"`
132}
133
134// FieldDef is one typed field on a card type. Adding a field is a row, not
135// a migration.
136type FieldDef struct {
137 ID int64
138 CardTypeID int64 `gorm:"index;not null"`
139 // Key is unique across the whole table, not merely within a type. A
140 // print is derived from the key (seal.Print), so two definitions
141 // sharing one would share an equality space — and the schema, not a
142 // test over a Go slice, is where that has to be refused.
143 Key string `gorm:"uniqueIndex;size:64"` // opaque, as CardType.Key
144 SealedLabel []byte
145 // SealedOptions is a KindEnum's permitted values, as a sealed JSON
146 // array. Sealed because "Lead", "Contract sent", "Won" are precisely
147 // the user vocabulary §4.3 exists to keep out of the durable file.
148 // Empty for every other kind.
149 SealedOptions []byte
150 // Kind is the value's shape — text, date, enum, number — and drives
151 // validation and how the in-memory index treats it. Plaintext: it is
152 // this app's vocabulary, not the team's content.
153 Kind string `gorm:"size:32"`
154 Tier Tier `gorm:"size:16"`
155 // Ordinal is display order within the type.
156 Ordinal int
157 CreatedAt time.Time
158 UpdatedAt time.Time
159}
160
161// Card is a mutable entity — the thing a person opens. Its field values are
162// CardValue rows; nothing about what it *says* is in this struct.
163type Card struct {
164 ID int64
165 CardTypeID int64 `gorm:"index;not null"`
166 // Revision, Gone and UpdatedAt are the suite contract's feed row
167 // (S1: item_id, revision, gone, touched_at) and are plaintext so the
168 // feed can be served without unsealing and passes the plaintext-grep
169 // gate unaided. memoria §3.2 already concedes update timestamps as a
170 // known leak; this is the same trade, made deliberately.
171 //
172 // A revision is a random positive int63 (store.go nextRevision), not a
173 // counter, so a database restored from an older backup hands one out
174 // again only with negligible probability, 2^-63 per draw (spec §6.2;
175 // it assumes whole-database restores). Only equality means anything: the order
176 // of a card's revisions is its event log's. Cards from before keep
177 // their small counted values until their next change.
178 Revision int64 `gorm:"not null;default:1"`
179 // Nonce is the card's half of its suite item id, "<id>.<nonce>": a
180 // random positive int63 written once at creation. After a restore a
181 // new card can be given an old card's id; its nonce matches only with
182 // probability 2^-63. Plaintext under §4.1 case 1. Write-once and positive,
183 // enforced by triggers (migrations/0005).
184 Nonce int64 `gorm:"not null;default:0"`
185 // not null with a default, because a nullable bool does not behave:
186 // with a NULL row, `gone = 0`, `gone != 1` and `NOT gone` all miss
187 // it — and suite/s1.go refuses a feed row whose gone is absent.
188 Gone bool `gorm:"index;not null;default:false"`
189 // Offered is the reach mark. Under the 2026-09-19 credential ruling
190 // the sibling evaluates its own mark, with no asker and no unsealing,
191 // so this must be answerable by SQL against the durable file.
192 Offered bool `gorm:"index;not null;default:false"`
193 // OwnerID is a Member row, never an address. See Member.
194 //
195 // A POINTER, and the difference is load-bearing: as a bare int64 the
196 // zero value is indistinguishable from "nobody set this", so a
197 // handler that forgot to resolve the session produced a card owned by
198 // member 0 and nothing complained. NULL means the app made it; a
199 // number means a person did, and the foreign key means that person
200 // exists.
201 //
202 // Ownership here is PROVENANCE, not authority. fichas is one instance
203 // per team and the team shares its cards (§9), so OwnerID answers
204 // "who put this here", never "who may read it". If that ever changes,
205 // every store function needs the owner threaded through it and
206 // scope.OwnedBy on the lookup — and this comment is what says it was
207 // a decision rather than an omission.
208 OwnerID *int64 `gorm:"index"`
209 Owner *Member `gorm:"constraint:OnDelete:RESTRICT"`
210 CreatedAt time.Time
211 UpdatedAt time.Time `gorm:"index"`
212
213 // Deleting a card takes its values, entries and references with it.
214 // Its EVENTS are deliberately absent from this list: the log must
215 // outlive the object, or "who deleted this" has no row to live on
216 // (§5).
217 Values []CardValue `gorm:"constraint:OnDelete:CASCADE"`
218 Entries []Entry `gorm:"constraint:OnDelete:CASCADE"`
219 Refs []Ref `gorm:"constraint:OnDelete:CASCADE"`
220}
221
222// CardValue is one field's value on one card. Sealed, with an optional
223// keyed print for the equality questions worth answering without the key —
224// "is this the same company", "do we already have this contact".
225type CardValue struct {
226 CardID int64 `gorm:"primaryKey"`
227 FieldDefID int64 `gorm:"primaryKey"`
228 SealedValue []byte
229 // Print is empty unless the FieldDef's Tier is TierPrint. Indexed
230 // because answering equality is the entire reason it exists.
231 Print string `gorm:"index;size:64"`
232}
233
234// Entry is an append-only event belonging to a card — a call log, a note.
235// Immutable once written (§3): a correction is a new entry that supersedes,
236// never an edit, because an entry is a fact about a past moment.
237type Entry struct {
238 ID int64
239 CardID int64 `gorm:"index;not null"`
240 Kind string `gorm:"index;size:32;not null"`
241 // Source is where it came from — "manual", "calls". Routing, not
242 // content.
243 Source string `gorm:"size:32"`
244 // ActorID names the real writer, per suite ruling 9 — a Member row,
245 // never an address. NULL means the app wrote it as itself, which a
246 // generated entry does; it is never attributed to whoever triggered
247 // it. See Actor in store.go: the app-as-itself case must be asked for
248 // explicitly and carries a reason, so that forgetting an argument
249 // cannot produce it.
250 ActorID *int64 `gorm:"index"`
251 Actor *Member `gorm:"constraint:OnDelete:RESTRICT"`
252 // TypeID is the entry's CardType, whose Scope is ScopeEntry. Kind is
253 // display and routing; this is what decides which FieldDefs apply.
254 TypeID int64 `gorm:"index;not null"`
255 // CreatedAt is when the row was written — the feed needs that.
256 // When the call actually happened is an EntryValue, sealed, because
257 // "when you called them" is content.
258 CreatedAt time.Time `gorm:"index"`
259
260 Values []EntryValue `gorm:"constraint:OnDelete:CASCADE"`
261 Refs []Ref `gorm:"constraint:OnDelete:CASCADE"`
262}
263
264// EntryValue is CardValue's twin for entries.
265type EntryValue struct {
266 EntryID int64 `gorm:"primaryKey"`
267 FieldDefID int64 `gorm:"primaryKey"`
268 SealedValue []byte
269 Print string `gorm:"index;size:64"`
270}
271
272// Ref points at an item in a sibling app — (app, instance, item) — and
273// holds no copy of it (§3, decision 5).
274//
275// SealedTarget is sealed rather than plaintext because of §9's open item: a
276// readable reference to a non-team item is at-rest knowledge, in a second
277// app, that a private item exists. That is the leak S1's visibility flag
278// was removed to prevent.
279type Ref struct {
280 ID int64
281 CardID int64 `gorm:"index;not null"`
282 // EntryID scopes a reference to one entry rather than to the card —
283 // the Calls meeting an entry came from. Nil for a card-level
284 // reference.
285 //
286 // This exists because the alternative was storing a sibling's item id
287 // as an ordinary field value, which would seal it under PurposeValue.
288 // memoria's seal keeps purposes separate "by who receives them": an
289 // id that goes back on the wire to another app is its own kind, and
290 // sealing it as a generic value loses that rule.
291 EntryID *int64 `gorm:"index"`
292 SealedTarget []byte
293 // Print dedupes on re-import. Unique per card so that
294 // check-then-insert cannot race a duplicate in.
295 Print string `gorm:"uniqueIndex:idx_refs_card_print;size:64"`
296 CreatedAt time.Time
297}
298
299// Event is the change log: what changed, who did it (§5, Paul 2026-09-19).
300//
301// Sheets' events table is the model, and an earlier comment here claimed
302// it was copied "field for field", which was false. What is copied is the
303// shape that matters: an append-only id that doubles as a cursor, a kind,
304// a payload sealed under "event.payload", and trigger_id. What differs:
305// tab_id becomes (object_kind, object_id) because fichas logs more than
306// one kind of object; derived_count is dropped as a spreadsheet's concern;
307// and Revision, ChangedFields and PayloadErasedAt are added for §5's
308// retention rule, which Sheets has no equivalent of.
309//
310// Retention is the load-bearing part and it is not tidiness. Kind,
311// ObjectKind, ObjectID, ActorID and CreatedAt are kept permanently and
312// survive the object's deletion — "who deleted this" is the question an
313// audit log most needs to answer. PayloadSealed holds the before/after
314// values and is tombstoned on a bounded window, because restore needs an
315// unbroken chain and erasure has to be able to break it.
316type Event struct {
317 ID int64
318 Kind string `gorm:"index;size:32;not null"`
319 ObjectKind string `gorm:"size:16;not null;index:idx_events_object"`
320 ObjectID int64 `gorm:"index:idx_events_object"`
321 // ActorID is a Member row, or NULL for the app acting as itself.
322 // Indexed because "who deleted this" is the one audit question the
323 // durable table has to answer without the key.
324 //
325 // No foreign key, deliberately, unlike Card.Owner and Entry.Actor:
326 // the log must outlive everything it describes, including a member
327 // row somebody removes.
328 ActorID *int64 `gorm:"index"`
329 // ActorReason is why the app acted, when ActorID is NULL —
330 // "summary regenerated", "intake form". Plaintext (§4.1 case 4) and
331 // required for an app actor, so that an honest machine write cannot
332 // be confused with a handler that forgot to resolve a session.
333 ActorReason string `gorm:"size:64"`
334 // ChildID names the object a card-scoped event is about when that is
335 // not the card itself — the entry that landed. Without it, an entry
336 // landing had to be logged under object_kind=entry while consuming a
337 // CARD revision, which left the card's own revision chain with gaps
338 // that a contiguity check reads as broken.
339 ChildID int64
340 // Revision is the object's revision AFTER this event. Card revisions
341 // are random (store.go nextRevision), so the chain is ordered by event
342 // id, not by revision value; it is unbroken when every card revision
343 // has its event, which every write path guarantees by logging in the
344 // same transaction. It is what lets the log answer "at what revision"
345 // for S1, and "was this ever this card's revision" for S2's STALE.
346 Revision int64
347 // Nonce is a random positive int63 written once with the event: the
348 // suite feed cursor is "<event id>.<nonce>", so a cursor names one
349 // event in one history even after a restore reissues the id.
350 // Plaintext under §4.1 case 1; write-once and never zero, enforced by
351 // triggers (migrations/0005).
352 Nonce int64 `gorm:"not null;default:0"`
353 // ChangedFields lists the FieldDef ids this event touched, as a JSON
354 // array of integers. **Plaintext, and it must be**: §5 keeps "which
355 // fields changed" permanently, and the only other place to put it is
356 // inside PayloadSealed — which is the thing erasure empties. Ids are
357 // opaque and structural, so this is §4.1 case 2.
358 ChangedFields string `gorm:"size:512"`
359 // PayloadSealed is sealed under its own purpose, as Sheets seals
360 // "event.payload". Emptied when the window passes; the row stays.
361 PayloadSealed []byte
362 // PayloadErasedAt records that the payload was deliberately removed.
363 //
364 // Without it an empty payload is ambiguous between "this event never
365 // carried values" and "these values were erased" — and a restore path
366 // that cannot tell them apart is §5's named failure: a silently broken
367 // chain that still offers a restore button and reconstructs a wrong
368 // object.
369 PayloadErasedAt *time.Time
370 // TriggerID is the event that caused this one. Sheets uses it for a
371 // recalc's input; fichas uses it for the derived summary, so that a
372 // machine-written change names the entry that provoked it and the
373 // actor stays honest (§5, §7).
374 TriggerID int64 `gorm:"index"`
375 CreatedAt time.Time `gorm:"index"`
376}
377