diff --git a/docs/protocol.md b/docs/protocol.md index 0f8d0ce6..7740ec0f 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -171,6 +171,17 @@ Every node trusts exactly ONE association public key, persisted in `config.json` - Reply exception. Blocks are private (a block record is never shown to others), so the only public rule that stops a drive-by recado is the wall; under `'following'` a recado that answers one of the owner's own is still admitted, so a conversation does not need a mutual follow. A scrap of W with `replyTo = { author: O, seq: s }` is admitted when block `s` of O is a live `scrap` with `to === W` and `W`'s scrap is dated no earlier than that original (`reply.at >= original.at`). Only one reply per original is admitted: the lowest live block of W that answers it. A hidden reply keeps its slot (the owner hiding it does not let a second reply in); only W deleting that reply frees the slot for its next one. Under `'everyone'` and `'nobody'` the exception is moot. - Evidence of the follow. The seeder returns the seq of O's live `follow` record for W and the node reads that block with `diary.peek` and checks it is a live `follow` of `key === W` with `on: true`. One peek proves the block exists and is live, not that it is the latest operation for that key: a seeder can name a follow that O has since undone, or an older `scrap-wall` or an omitted `scrap-hide`, and the node cannot tell. That residual risk is the seeder's, accepted; see section 5 "Seeder recados index", Trust model. - Old readers: to apps, CLIs and seeders from before recados the three types are unknown, skipped as invalid (`malformed`) and never renumbered; the diary is never rejected for them. Such a reader shows no recados. +- Varandinha (`packages/core/lib/records.js`, rules in `packages/rpc/lib/garden.js`; seq >= 1, else `genesis-required`). Varandinha is the balcony of pots on a member's own diary: the member plants, waters and harvests under the reader's clock, and a neighbour who follows the owner may water that balcony once on a Brasília day. Three records, all public like a post. None of them carries text: nothing in them is ever shown as typed by a person. `garden` and `garden-state` are a self-asserted claim of the diary owner. The diary signature proves who appended them, not that the pots were grown by these rules, so anyone can append a valid balcony of their own. Because anyone can forge their own balcony, nothing may rank it or reward it (there is no score, and harvest only empties a pot). A `garden-help` is one watering signed by another certified member, in that member's own diary, addressed `to` the owner. `garden` and `garden-state` are latest-wins: the live record of that type with the highest block wins (a tombstone, section 2 "Deletion", takes one version away and the previous one shows again). A writer that publishes a new `garden` or `garden-state` therefore marks every earlier live version of that type as deleted, in the same write when they fit, older ones first otherwise, as `mood` does. Copies already fetched by others may remain. Leaving first marks the leaver's own game records as deleted: every live `garden-state` and every live `garden-help` the leaver wrote (the helps the leaver gave to other balconies), in as many appends as the writer needs. The `garden` with `on: false` is written last, latest-wins, so it also tombstones every earlier live `garden` and an older balcony does not come back. A leave that stops halfway still reads on. Leaving again re-reads the live records and finishes. Tombstoning a recent own help also takes away the boost it gave that neighbour's current planting. Helps other members wrote to the leaver's balcony live in their diaries. Only their writers can delete them. Retention: an honest writer also prunes its own `garden-help` records older than `GARDEN_HELP_WINDOW_MS` (72 h): a new help carries, in the same write, tombstones of own helps past the window. Only live records are folded. + - `{ "type": "garden", "on": , "at": }` (`GARDEN_KEYS`, builder `gardenRecord({ on, at })`). Exactly these 3 keys, and `on` a boolean, else `malformed`. A non-canonical `at` is `date-invalid` (shape is judged before the date). `on: true` shows the balcony, `on: false` hides it. A diary with no live `garden` is off. The builder's `at` defaults to now. + - `{ "type": "garden-state", "pots": , "n": , "at": }` (`GARDEN_STATE_KEYS`, builder `gardenStateRecord({ pots, n, at })`). Exactly these 4 keys, else `malformed`. `at` is judged before the pots and before `n`: a non-canonical `at` is `date-invalid`, and a bad `n` or a bad `pots` with a good date is `malformed`. `n` is the save ordinal of the Brasília day, an integer `1..GARDEN_SAVES_DAILY_MAX` (`isSaveOrdinal`, 6), else `malformed`. `pots` is a dense array of exactly `GARDEN_POTS` (6) pots (`isPots`). Each pot is `null` (empty) or exactly `{ "plant": , "at": , "water": , "w": }` (`POT_KEYS` in `packages/rpc/lib/garden.js`). `plant` is one id of `GARDEN_PLANTS` (`isPlantId`). Both pot dates are canonical, `pot.at <= pot.water`, and `pot.water` is not after the record's own `at` (a pot cannot be watered after the record that states it). `w` is an integer `0..GARDEN_WATER_MAX` (12). An extra key, a hole, a length other than 6, or a pot that fails those rules is `malformed`. The builder copies each plain pot one level down, so the record does not share objects with the caller. `saveOrdinal(prevState, now)` is the `n` an honest writer stores: `1` when there is no previous state or the previous `at` is before the start of the writer's Brasília day, `n + 1` while `n < 6`, and `null` past the daily max. A previous state dated after today counts as today, and an unreadable previous state, a clock that is not a finite time, or a clock whose Brasília day start is not a valid time answers `null`, never a fresh budget. + - `{ "type": "garden-help", "to": "", "pot": , "at": }` (`GARDEN_HELP_KEYS`, builder `gardenHelpRecord({ to, pot, at })`), in the HELPER's diary. Exactly these 4 keys, `to` lowercase hex64 and `pot` an integer `0..GARDEN_POTS - 1` (`isPotIndex`), else `malformed`. A non-canonical `at` is `date-invalid` (shape before the date). The record does not carry the writer's key, so a help addressed to the writer's own diary is still a valid record. The fold drops it. + - Play (`applyActs(state, acts, now, opts)`, pure, never throws, never mutates its inputs). One session produces the pots an honest writer then saves as `garden-state`. `state` null or undefined starts from six empty pots. Any other state whose `pots` do not copy against `now` (each planted pot's `water` at or before `now`) is reason `state`. `acts` is a dense list of 1..`GARDEN_ACTS_MAX` (24) acts (`isActs`), else `acts`. A plant act is exactly `{ "op": "plant", "pot": <0..5>, "plant": }`. A water, harvest or clear act is exactly `{ "op": "water" | "harvest" | "clear", "pot": <0..5> }`. One invalid act refuses the whole batch. In order: `plant` on an empty pot writes `{ plant, at, water, w: 0 }` with `at` and `water` the canonical ISO of `now`, and `occupied` when the pot is full. `water`, `harvest` and `clear` on an empty pot are `empty`. `water` is judged with zero received and zero given counts (`canWater` of that view): the pot must be dry and not ripe without any neighbour boost, else `not-dry`. A water that passes sets `water` to the ISO of `now` and `w` to `min(w + 1, GARDEN_WATER_MAX)`. The passed counts apply only to `harvest`: the pot must be ripe under `received[pot]` and `given[pot]`, else `not-ripe`, and a harvest that passes sets the pot to `null`. A bad counts array reads as six zeros, so the harvest sees no boost. `clear` sets the pot to `null` and does not wait for ripe. There is no score field and no reward. A clock that is not a finite time, or whose ISO form throws, is `invalid`. Success is `{ ok: true, state: { pots } }`. The writer adds `n` and `at`. + - Growth (`potView(pot, now, opts)`, `viewOf` inside `packages/rpc/lib/garden.js`), under the reader's clock, never the writer's. No death and no stall: an unwatered pot still ripens. Watering and neighbours only shorten the wait, never below half of it. For a pot already checked, `waters = min(w, floor((water - at) / GARDEN_WATER_GAP_MS))`, `boost = waters * GARDEN_WATER_BOOST_MS + min(received, GARDEN_HELP_PER_POT) * GARDEN_HELP_BOOST_MS + min(given, GARDEN_GIVEN_PER_POT) * GARDEN_GIVEN_BOOST_MS`, `need = max(ripeMs / 2, ripeMs - boost)`, `progress = 0` when `now <= at` and otherwise `min(1, (now - at) / need)`, `ripe` when `progress >= 1`, `ripeAt = at + need`. `stage` is 3 when ripe, 0 when progress is below 0.25, 1 from 0.25 up to but not including 0.6, and 2 from 0.6 until ripe. `dry` when `now - water >= GARDEN_WATER_GAP_MS`, and `canWater` when not ripe and dry. A bad count reads as 0. A bad pot or a clock that is not a finite time returns `null`. A pot whose `water` is more than `GARDEN_MAX_FUTURE_MS` ahead of `now` returns `null`, and so does a view whose computed `ripeAt` is not a valid time. `ripeMs` is the plant's value in `GARDEN_PLANTS` (frozen ids, Portuguese ASCII): `manjericao` 21600000 (6 h), `tomate` 36000000 (10 h), `pimenta` 57600000 (16 h), `alecrim` 86400000 (24 h), `samambaia` 129600000 (36 h), `espada` 172800000 (48 h). The other bounds: `GARDEN_WATER_GAP_MS` = 10800000 (3 h), `GARDEN_WATER_BOOST_MS` = 3600000 (1 h), `GARDEN_WATER_MAX` = 12, `GARDEN_HELP_BOOST_MS` = 7200000 (2 h), `GARDEN_HELP_PER_POT` = 3, `GARDEN_GIVEN_BOOST_MS` = 1800000 (30 min), `GARDEN_GIVEN_PER_POT` = 3, `GARDEN_SAVES_DAILY_MAX` = 6, `GARDEN_HELPS_DAILY_MAX` = 5, `GARDEN_ACTS_MAX` = 24, `GARDEN_HELP_WINDOW_MS` = 259200000 (72 h), `GARDEN_HELP_ROWS` = 24, `GARDEN_STREET_PAGE` = 20, `GARDEN_DAY_MS` = 86400000, `GARDEN_DAY_OFFSET_MS` = -10800000, `GARDEN_MAX_FUTURE_MS` = 86400000. The day is Brasília, fixed UTC-3, the same math as `packages/core/lib/activity.js` (`localDay`, `dayStart`), copied so this package keeps zero dependencies. A day starts at 03:00:00.000Z. `gardenDay(ms)` is that civil day as `YYYY-MM-DD`, or `null`. `dayStart(ms)` is the epoch ms of that start, or `NaN` when `ms` is not a finite time in the Date range, and also when the computed start falls outside the Date range. `GARDEN_MAX_FUTURE_MS` is the feed's future tolerance (`feed.MAX_FUTURE_MS`). + - Helps a reader counts (`foldHelps({ owner, pots, helps, now })`). Each row is `{ author, seq, record, follow }` (`record` the `garden-help`, `follow` the helper's `follow` record), `author` lowercase hex64, `seq` a safe integer >= 1, `to` equal to `owner`, author not the owner. The parsed `at` must fall in the window: not before `now - GARDEN_HELP_WINDOW_MS` and not after `now + GARDEN_MAX_FUTURE_MS` (both edges count). Outside that window, or more than 24 h ahead of the reader, the row is dropped. The helper follows the owner. The evidence is the helper's own live `follow` block, exact follow keys, `key` the owner, `on: true` and a canonical `at`, read with `diary.peek` (`isFollowOf`). One peek proves that block exists and is live, not that it is the latest operation for that key: a seeder can name a follow the helper has since undone, the same residual as Recados. One help per helper per owner per Brasília day: a row that fails the shape, the window or the follow never enters the dedupe. The fold then dedupes on (author, `dayStart(at)`), the start of the help's Brasília day, and the lowest `seq` wins. A help whose day start is `NaN` is dropped and never enters that dedupe, which happens before the planted-pot check. The winning help then counts only when its pot is planted and `help.at >= pot.at` (the current planting, equal counts, an earlier help or an empty pot is dropped). If the lowest seq of that day misses the pot, a higher seq the same day does not replace it. At most `GARDEN_HELP_PER_POT` (3) received helps count on one pot. The result is `{ perPot, helpers: [{ author, seq, pot, at }] }`, `perPot` six counts and `at` the record's ISO. The helper list keeps one row per author, that author's newest help that passed the pot check (largest `at`, on a tie the lowest seq), so a few accounts cannot fill the list. Order is newest `at` first, then author ascending, then seq ascending, cut at `GARDEN_HELP_ROWS` (24). A listed author's help may still be past the per-pot cap of 3. A list the fold cannot read as a dense array of at most 1024 rows counts nothing. + - Own helps (`foldGiven({ self, pots, given, now })`). Rows are `{ seq, record }` and the result is `{ perPot }`. It needs no follow evidence (the writer's own claim, like the rest of the balcony). The diary's own `garden-help` records to other balconies are a small boost on the writer's own pots. One per balcony per Brasília day (`dayStart`, lowest seq), then at most `GARDEN_HELPS_DAILY_MAX` (5) a day (the same `dayStart`, the lowest seqs), inside the same window, never to self. A help whose day start is `NaN` is dropped. Each counted help adds one to every own pot planted at or before that help, and each pot takes at most `GARDEN_GIVEN_PER_POT` (3). `foldBalcony({ owner, flag, state, helps, given, now })` is the balcony a reader shows: `{ on, pots, helpers, stale }`. The flag is the live `garden`. `on` is exactly `true`. A flag dated more than `GARDEN_MAX_FUTURE_MS` ahead of `now` is dropped and reads off, with six empty pots and `stale: true`. A state dated that far ahead is dropped too (`stale: true`, six empty pots) and a flag that is on stays on. An off flag, a missing flag, or a state the fold cannot copy shows six empty pots and no helpers (`stale` stays false when the dates themselves are not past the tolerance). When the flag is on and the state copies, each planted pot is a `potView` with that pot's received count and given count, and a pot whose `ripeAt` is not a valid time shows as an empty slot (`null`), as `potView` answers `null` for it. + - Three enforcement layers. Writer courtesy: before appending, the honest node asks `helpAllowed({ self, to, follows, own, now })` for a help, `applyActs` for the pots, and `saveOrdinal` for `n`, and does not append a refusal. `follows` is a Set of hex64 keys, and each own row is `{ to, at }` with `at` a canonical ISO or a safe integer of ms. `helpAllowed` answers `{ ok: false, reason }` with `self` (watering one's own balcony), `not-following` (`follows` is not a Set that contains `to`, a proxied Set included), `same-day` (an own row to that owner dated at or after the start of today's Brasília day, a row dated ahead of the clock included, so turning the clock back never frees the day), or `daily` (the writer already has `GARDEN_HELPS_DAILY_MAX` own rows dated at or after the start of today's Brasília day, to any balcony). Malformed input, a `self` or `to` that is not hex64, a clock that is not a finite time, a start of today's Brasília day that is not a valid time, or an own-row list the function cannot read, answers `invalid`, never ok. A non-canonical own row is ignored, not `invalid`. A row dated before today's Brasília start does not spend today's budget. Otherwise the answer is `{ ok: true }`. Reader fold: `foldHelps`, `foldGiven`, `foldBalcony` and `potView` decide what counts and what is shown, including a record the honest node would have refused. The received-help fold does not apply `GARDEN_HELPS_DAILY_MAX`. That cap is the writer check and `foldGiven`. The fold is written for a list of at most `GARDEN_HELP_ROWS` (24) rows, which is also the most helpers it returns, and a list of more than 1024 rows counts nothing, so a huge pointer list cannot raise a count. A reader reads every pointed block with `diary.peek`, checks it with `validateRecord`, and only then folds it. Seeder cap: a seeder that indexes Varandinha keeps pointers only (a diary key and a seq), never a pot or a plant, and hands a reader at most `GARDEN_HELP_ROWS` (24) help pointers per balcony, one per helper per Brasília day. Which seqs it names or omits are its claims. + - Residuals, accepted. A helper can backdate `at` to any canonical instant inside the days a planting spans, as long as `help.at >= pot.at` and the instant is inside the 72 h window and not more than 24 h ahead: `helpAllowed` looks at the writer's Brasília today, it does not pin the new record's `at` to now, and the fold believes `at`. A superseded follow looks live in one peek, the Recados residual above. A modified client can append what the honest node refuses, because `validateRecord` only checks the shape: a help `helpAllowed` would refuse, or pots `applyActs` would refuse, or an `n` that is not `saveOrdinal`. The fold still drops a received help that fails its own rules. It still shows a self-asserted balcony as written, inside the growth formula, and that balcony still ranks nothing and rewards nothing. + - Old readers: to apps, CLIs and seeders from before Varandinha the three types are unknown, skipped as invalid (`malformed`) and never renumbered; the diary is never rejected for them. Such a reader shows no balcony. `validateRecord` never throws. The builders throw `TypeError` with the reason `validateRecord` returned. Every function in `packages/rpc/lib/garden.js` never throws. `snapshot`, `snapshotArray` and `field` read each value once from its own data property, never through a get, and then the copy is judged, so a transparent proxy is read once and cannot answer differently after the check, while a getter or a throwing or revoked proxy is invalid. Records, pots, acts and the follow evidence must carry exactly their keys. Option bags, fold rows, the `state` of `applyActs` and the `prevState` of `saveOrdinal` are read field by field and may carry extra keys, which are ignored. - Perfil rico (`packages/core/lib/records.js`, rules in `packages/rpc/lib/profile-extra.js`; seq >= 1, else `genesis-required`). Two public records that add to the profile without touching it: the `profile` record (name, bio and photo) keeps its keys, so every older reader keeps showing name, bio and photo. Both are public like a post, optional, and the live record with the highest block wins (a tombstone, section 2 "Deletion", takes one version away and the previous one shows again). So a writer that withdraws one of them (docs/rpc.md 5.132, `profile.extra.delete`) tombstones EVERY live version of that type, never only the newest, and no older version comes back. A writer that publishes a new `profile-about` or `mood` also marks every earlier live version of that type as deleted (tombstones, docs/rpc.md 5.130 and 5.131): in the same write when they fit, older ones first otherwise. Copies already fetched by others may remain. - `{ "type": "profile-about", "about": , "city": , "work": , "studies": , "interests": , "birthday": <"MM-DD" | null>, "theme": , "at": }` (`PROFILE_ABOUT_KEYS`, builder `profileAboutRecord({ about, city, work, studies, interests, birthday, theme, at })`). Every key is present and an empty field is `null`, never `''` (the builder turns an absent or `''` argument into `null`; a validator refuses `''`). Limits in code points: `about` 1..`MAX_ABOUT` (600), `city` 1..`MAX_CITY` (60), `work` 1..`MAX_WORK` (80), `studies` 1..`MAX_STUDIES` (80), `interests` 1..`MAX_INTERESTS` (200). A line feed is allowed only in `about`; no other control character (a tab included), no lone surrogate, and a value made only of whitespace, zero-width characters (U+200B to U+200D, U+2060) or the soft hyphen is refused, because it would draw nothing. A bad text is `text-length`, a bad key set, `birthday` or `theme` is `malformed`, a bad `at` is `date-invalid`. `birthday` is `null` or `MM-DD` with a real month and a day that month can have, `02-29` included: a birthday has no year, and the record never carries one. `theme` is `null` or one of the frozen `THEME_IDS`: `varanda`, `floresta`, `mar`, `por-do-sol`, `ipe`, `flor`, `lavanda`, `terra`. The ids are a consensus rule: they are only ever appended in a protocol change, never renamed or reused. A reader that does not know an id ignores it and shows the usual band, with no theme (it does not fall back to `varanda`). There is no relationship field and no URL field, and no age-band rule applies to the fields. - `{ "type": "mood", "emoji": , "text": , "at": }` (`MOOD_KEYS`, builder `moodRecord({ emoji, text, at })`): `emoji` is `''` (none) or exactly one emoji (the `isReaction` rule of docs/rpc.md), `text` has 0..`MAX_MOOD_TEXT` (60) code points on one line (no line feed, no control character, no lone surrogate); a non-empty `text` made only of whitespace or invisible characters (zero-width, Hangul filler, braille blank, tag characters and the like) is invalid. A mood with both empty is still a valid record and clears the mood at the protocol level; the app does not publish an empty mood and removes a mood with `profile.extra.delete` (docs/rpc.md 5.132). A text-only mood is shown. A bad emoji is `malformed`, a bad text is `text-length`, a bad `at` is `date-invalid`. @@ -256,6 +267,9 @@ Example records: { "type": "scrap", "to": "", "text": "saudades!", "replyTo": null, "at": "2026-01-01T00:00:00.000Z" } { "type": "scrap-hide", "from": "", "seq": 4, "at": "2026-01-01T00:00:00.000Z" } { "type": "scrap-wall", "who": "following", "at": "2026-01-01T00:00:00.000Z" } +{ "type": "garden", "on": true, "at": "2026-01-01T00:00:00.000Z" } +{ "type": "garden-state", "pots": [{ "plant": "tomate", "at": "2026-01-01T00:00:00.000Z", "water": "2026-01-01T00:00:00.000Z", "w": 0 }, null, null, null, null, null], "n": 1, "at": "2026-01-01T00:00:00.000Z" } +{ "type": "garden-help", "to": "", "pot": 0, "at": "2026-01-01T00:00:00.000Z" } { "type": "profile-about", "about": "Moro em Recife.\nGosto de café.", "city": "Recife", "work": null, "studies": null, "interests": "música, caminhada", "birthday": "03-14", "theme": "mar", "at": "2026-01-01T00:00:00.000Z" } { "type": "mood", "emoji": "☕", "text": "começando o dia", "at": "2026-01-01T00:00:00.000Z" } { "type": "fan", "key": "", "on": true, "at": "2026-01-01T00:00:00.000Z" } diff --git a/docs/rpc.md b/docs/rpc.md index d5ebb957..61f121ed 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -1660,7 +1660,7 @@ This is the `isUnsafe` set of `packages/core/lib/safe.js` plus the three marks a ## 12. Module exports (`require('@varanda/rpc')`) -`index.js` re-exports: every constant of section 2 (including `FEED_INCOMPLETE_MAX`, `PEEK_LIMIT_DEFAULT`, `PEEK_LIMIT_MAX`, `PROFILE_LIMIT_MAX`, `ENGAGEMENT_LIMIT_MAX`, `PEEK_SEQS_MAX`, `PEEK_TIMEOUT_MS`, `NOTICES_LIMIT_DEFAULT`, `NOTICES_LIMIT_MAX`, `AVATAR_SIDE`, `MAX_AVATAR_BLOCKS`, `MAX_AVATAR_BYTES`, `AVATAR_MIMES`, `GROUP_LIMIT_DEFAULT`, `GROUP_LIMIT_MAX`, `GROUP_MEMBERS_LIMIT_MAX`, `GROUP_REACTIONS_MAX`, `GROUP_REACTORS_MAX`, `MAX_GROUP_NAME`, `MAX_GROUP_CUTS`, `MAX_GROUPS_PER_COMMUNITY`, `COMMUNITY_LIST_MAX`, `MAX_DM_MEDIA`, `DM_MEDIA_CHUNK_BYTES`, `DM_MEDIA_MAX_CHUNKS`, `DM_MEDIA_MAC_BYTES`, `DM_THREAD_LIMIT_DEFAULT` and `DM_THREAD_LIMIT_MAX`); the DM inner helpers of `lib/dm-budget.js` (5.75): `DM_INNER_KEYS`, `DM_INNER_KEYS_V2`, `DM_INNER_KEYS_V4`, `DM_INNER_KEYS_V7`, `DM_BLOB_KEYS`, `canonicalBlobDescriptor`, `DM_TARGET_KEYS`, `DM_MEDIA_KEYS`, `DM_CARD_KEYS`, `dmInnerVersion`, `canonicalDmInnerJson`, `dmTextBytes` and `dmTextBudget`; the signup invite card helpers of `lib/invite-card.js` (5.101): `INVITE_CARD_MAX_URL`, `FRAGMENT_MARK`, `NAME_MAX`, `MESSAGE_MAX_BYTES`, `DESIGNS`, `REGIONS`, `designIndex`, `designAt`, `canonicalInviteCardText`, `isInviteCode`, `isInviteCardExpires`, `buildInviteCardUrl`, `parseInviteCardUrl` and `messageRoom`; the link card rules of `lib/link-card.js` (protocol section 2, "Link cards"): `MAX_CARD_URL`, `MAX_CARD_TITLE`, `MAX_CARD_DESC`, `MAX_CARD_IMAGE_BYTES`, `isCardForbiddenChar`, `cardTextLength`, `cardText` and `cardUrlHost`; the momento music rules of `lib/music.js` (5.113): `MOMENT_MUSIC_KEYS`, `MOMENT_SNIPPET_S` and `isMomentMusic`; `feira` (`lib/feira.js`, the Feira rules of protocol sections 2 and 15: constants, shape checks, `unitAllowed`, `cityKey`, `priceLabel`, `statusLabel`, `dealPayload` and `parseOfferRef`); `mediaBounds`, `mediaSize`, `MAX_MEDIA_PIXELS`, `MAX_MEDIA_FRAMES` and `MAX_MEDIA_TOTAL_PIXELS` (`lib/media-bounds.js`, the image header bounds of protocol section 13; `mediaSize(bytes, mime)` reads the same headers and returns `{ width, height, frames }` without the dimension and pixel bounds, or `null` like `mediaBounds` (more than `MAX_MEDIA_FRAMES` frames is still `null`), for a caller with its own cap, such as the web photo encoder); `findMentions`, `mentionTokens`, `mentionSegments`, `activeMention` and `MENTION_MAX` (`lib/mentions.js`, the `@nome` grammar of protocol section 2; `NOTICE_KINDS` is not exported here, it lives in `@varanda/core` `lib/notices-v2.js`, and `NOTICE_V3_KINDS` (the v3 kinds, with `like` and `repost`) in `lib/notices-v3.js`); every export of section 7; `METHODS` (array, including `recovery.sign` and the IPC-only `identity.recoveryLookup`, `identity.recoveryOpen`, `identity.recoveryWrap` and `identity.recoveryBind`, 5.90 to 5.94; only `identity.recoveryBind` is in `MUTATING`), `MUTATING` (frozen array), `isMethod`, `isMutating`, `validateParams`, `isKey`, `isRef(str, minSeq = 1)`; `isReaction`, `REACTION_MAX_POINTS` (8) and `REACTION_MAX_BYTES` (40) (`lib/reaction.js`, the one-emoji rule of a `group-react` record, protocol section 10); `EVENTS` (`['sync.started', 'sync.event', 'sync.stopped', 'warning', 'follows.changed', 'groups.changed', 'dm.changed', 'dm.sending', 'seen.changed', 'dm.pageKeyMismatch', 'devices.changed', 'dm.copyProgress', 'dm.copyImported']`), `STOP_REASONS` (`['done', 'stopped', 'preempted', 'timeout', 'error', 'idle']`), `validateRequest`, `validateResponse`, `validateEvent`; `encodeFrame`, `createFrameDecoder`, `parseMessage`; `displayText`, `utf8ByteLength`, `utf8Encode`, `utf8Decode`, `clipText(str, max)`; `tokensEqual`; `capList`, `capSyncResult`; `createServerDispatcher`, `createClient`. Files: `lib/limits.js`, `lib/errors.js`, `lib/methods.js`, `lib/mentions.js`, `lib/dm-budget.js`, `lib/link-card.js`, `lib/invite-card.js`, `lib/reaction.js`, `lib/media-bounds.js`, `lib/envelope.js`, `lib/framing.js`, `lib/text.js`, `lib/token.js`, `lib/server.js`, `lib/client.js`. +`index.js` re-exports: every constant of section 2 (including `FEED_INCOMPLETE_MAX`, `PEEK_LIMIT_DEFAULT`, `PEEK_LIMIT_MAX`, `PROFILE_LIMIT_MAX`, `ENGAGEMENT_LIMIT_MAX`, `PEEK_SEQS_MAX`, `PEEK_TIMEOUT_MS`, `NOTICES_LIMIT_DEFAULT`, `NOTICES_LIMIT_MAX`, `AVATAR_SIDE`, `MAX_AVATAR_BLOCKS`, `MAX_AVATAR_BYTES`, `AVATAR_MIMES`, `GROUP_LIMIT_DEFAULT`, `GROUP_LIMIT_MAX`, `GROUP_MEMBERS_LIMIT_MAX`, `GROUP_REACTIONS_MAX`, `GROUP_REACTORS_MAX`, `MAX_GROUP_NAME`, `MAX_GROUP_CUTS`, `MAX_GROUPS_PER_COMMUNITY`, `COMMUNITY_LIST_MAX`, `MAX_DM_MEDIA`, `DM_MEDIA_CHUNK_BYTES`, `DM_MEDIA_MAX_CHUNKS`, `DM_MEDIA_MAC_BYTES`, `DM_THREAD_LIMIT_DEFAULT` and `DM_THREAD_LIMIT_MAX`); the DM inner helpers of `lib/dm-budget.js` (5.75): `DM_INNER_KEYS`, `DM_INNER_KEYS_V2`, `DM_INNER_KEYS_V4`, `DM_INNER_KEYS_V7`, `DM_BLOB_KEYS`, `canonicalBlobDescriptor`, `DM_TARGET_KEYS`, `DM_MEDIA_KEYS`, `DM_CARD_KEYS`, `dmInnerVersion`, `canonicalDmInnerJson`, `dmTextBytes` and `dmTextBudget`; the signup invite card helpers of `lib/invite-card.js` (5.101): `INVITE_CARD_MAX_URL`, `FRAGMENT_MARK`, `NAME_MAX`, `MESSAGE_MAX_BYTES`, `DESIGNS`, `REGIONS`, `designIndex`, `designAt`, `canonicalInviteCardText`, `isInviteCode`, `isInviteCardExpires`, `buildInviteCardUrl`, `parseInviteCardUrl` and `messageRoom`; the link card rules of `lib/link-card.js` (protocol section 2, "Link cards"): `MAX_CARD_URL`, `MAX_CARD_TITLE`, `MAX_CARD_DESC`, `MAX_CARD_IMAGE_BYTES`, `isCardForbiddenChar`, `cardTextLength`, `cardText` and `cardUrlHost`; the momento music rules of `lib/music.js` (5.113): `MOMENT_MUSIC_KEYS`, `MOMENT_SNIPPET_S` and `isMomentMusic`; `feira` (`lib/feira.js`, the Feira rules of protocol sections 2 and 15: constants, shape checks, `unitAllowed`, `cityKey`, `priceLabel`, `statusLabel`, `dealPayload` and `parseOfferRef`); `garden` (`lib/garden.js`, the Varandinha rules shared by core, the node and the app: the `GARDEN_*` constants (six pots, the six plants with their `ripeMs`, the water, help and daily caps, the help window, the Brasília day math and the 24 h future tolerance), the shape checks `isPlantId`, `isPotIndex`, `isPot(v, recordAtMs)`, `isPots`, `isSaveOrdinal`, `isAct`, `isActs` and `isFollowOf(record, owner)`, `gardenDay`, `dayStart`, growth under the reader clock `potView(pot, now, { received, given })`, the play reducer `applyActs(state, acts, now, { received, given })` (watering judged with no neighbour boosts, harvest under the passed per-pot counts, one invalid act refuses the batch), the folds `foldHelps`, `foldGiven` and `foldBalcony`, `helpAllowed` and `saveOrdinal`; nothing throws, no input is mutated, the clock is always a `now` argument in ms); `mediaBounds`, `mediaSize`, `MAX_MEDIA_PIXELS`, `MAX_MEDIA_FRAMES` and `MAX_MEDIA_TOTAL_PIXELS` (`lib/media-bounds.js`, the image header bounds of protocol section 13; `mediaSize(bytes, mime)` reads the same headers and returns `{ width, height, frames }` without the dimension and pixel bounds, or `null` like `mediaBounds` (more than `MAX_MEDIA_FRAMES` frames is still `null`), for a caller with its own cap, such as the web photo encoder); `findMentions`, `mentionTokens`, `mentionSegments`, `activeMention` and `MENTION_MAX` (`lib/mentions.js`, the `@nome` grammar of protocol section 2; `NOTICE_KINDS` is not exported here, it lives in `@varanda/core` `lib/notices-v2.js`, and `NOTICE_V3_KINDS` (the v3 kinds, with `like` and `repost`) in `lib/notices-v3.js`); every export of section 7; `METHODS` (array, including `recovery.sign` and the IPC-only `identity.recoveryLookup`, `identity.recoveryOpen`, `identity.recoveryWrap` and `identity.recoveryBind`, 5.90 to 5.94; only `identity.recoveryBind` is in `MUTATING`), `MUTATING` (frozen array), `isMethod`, `isMutating`, `validateParams`, `isKey`, `isRef(str, minSeq = 1)`; `isReaction`, `REACTION_MAX_POINTS` (8) and `REACTION_MAX_BYTES` (40) (`lib/reaction.js`, the one-emoji rule of a `group-react` record, protocol section 10); `EVENTS` (`['sync.started', 'sync.event', 'sync.stopped', 'warning', 'follows.changed', 'groups.changed', 'dm.changed', 'dm.sending', 'seen.changed', 'dm.pageKeyMismatch', 'devices.changed', 'dm.copyProgress', 'dm.copyImported']`), `STOP_REASONS` (`['done', 'stopped', 'preempted', 'timeout', 'error', 'idle']`), `validateRequest`, `validateResponse`, `validateEvent`; `encodeFrame`, `createFrameDecoder`, `parseMessage`; `displayText`, `utf8ByteLength`, `utf8Encode`, `utf8Decode`, `clipText(str, max)`; `tokensEqual`; `capList`, `capSyncResult`; `createServerDispatcher`, `createClient`. Files: `lib/limits.js`, `lib/errors.js`, `lib/methods.js`, `lib/mentions.js`, `lib/dm-budget.js`, `lib/link-card.js`, `lib/invite-card.js`, `lib/reaction.js`, `lib/media-bounds.js`, `lib/envelope.js`, `lib/framing.js`, `lib/text.js`, `lib/token.js`, `lib/server.js`, `lib/client.js`. ## 13. Known limits (v1) diff --git a/docs/verification/feat-varandinha-records.md b/docs/verification/feat-varandinha-records.md new file mode 100644 index 00000000..2877de94 --- /dev/null +++ b/docs/verification/feat-varandinha-records.md @@ -0,0 +1,17 @@ +# Varandinha, registros (PR feat/varandinha-records) + +Este PR acrescenta as regras puras de `packages/rpc/lib/garden.js` (exportadas como `garden` por `@varanda/rpc`), os três tipos de registro `garden`, `garden-state` e `garden-help` com os construtores em `packages/core/lib/records.js`, os testes `packages/rpc/test/garden.test.js` e `packages/core/test/garden.test.js`, o caso de leitor antigo em `packages/core/test/records.test.js`, o texto na seção 2 de `docs/protocol.md` e a menção na seção 12 de `docs/rpc.md`. Não há rota, método nem tela novos. + +Conferido à mão que cada constante, chave e função citada na seção 2 existe com o mesmo valor em garden.js e records.js. Os três exemplos JSON passam `validateRecord` na seq 1: rodado, com `` de `garden-help` trocado por um hex64 minúsculo. + +Rodado no Node 24.22.1, depois de `npm ci --ignore-scripts`, sobre a `main` em 34a4e34f: + +- `npm run lint` + resultado: passou. +- `npm test -- --affected=origin/main` + resultado: 800 arquivos, 798 passaram e 2 falharam por tempo, os dois fora deste PR. Detalhes, e os arquivos deste PR: + - `apps/cli/test/update.test.js` estourou o tempo na rodada paralela; sozinho (`node apps/cli/test/update.test.js`) passou, 73/73 testes e 1901/1901 asserções. + - `packages/core/test/private-member-3.test.js`: o teste "private: fake bans from an unadmitted writer never inflate a rotation" estourou os 30 s, na rodada paralela e duas vezes sozinho. Numa cópia limpa da mesma `main` (34a4e34f, sem este PR) falha igual, com o mesmo tempo esgotado. O teste grava 5000 banimentos de grupo e sincroniza; nenhum passa pelos tipos novos. A CI da `main` no GitHub passa com ele. + - `packages/rpc/test/garden.test.js`: 39/39 testes, 370/370 asserções. `packages/core/test/garden.test.js`: 12/12. `packages/core/test/records.test.js`: 70/70. +- `npm run demo` + resultado: passou, terminou com "DEMO OK". diff --git a/packages/core/lib/records.js b/packages/core/lib/records.js index 2f1500ec..d88960b5 100644 --- a/packages/core/lib/records.js +++ b/packages/core/lib/records.js @@ -14,7 +14,7 @@ const b4a = require('b4a') const { validLinkCard, validCardImageBytes, copyLinkCard, CARD_IMAGE_MIME } = require('./link-card') -const { feira, isMomentMusic, MOMENT_MUSIC_KEYS, MAX_TOP_FRIENDS, profileExtra: PX, isPoll, isPick, POLL_MIN, POLL_MAX, MAX_POLL_OPTION, isEvent, event: eventRules } = require('@varanda/rpc') +const { feira, isMomentMusic, MOMENT_MUSIC_KEYS, MAX_TOP_FRIENDS, profileExtra: PX, isPoll, isPick, POLL_MIN, POLL_MAX, MAX_POLL_OPTION, isEvent, event: eventRules, garden } = require('@varanda/rpc') const MAX_NAME = 80 const MAX_BIO = 280 @@ -162,6 +162,14 @@ const DEVICE_NONCE_BYTES = 24 const MIN_DEVICE_BOX = 17 // 32 writer pairs and a 40 code point name seal to about 5.2 KB. const MAX_DEVICE_BOX = 8192 +// Varandinha (docs/protocol.md): `garden` is the public flag that a diary +// shows its balcony, latest wins; `garden-state` is the whole balcony after +// a play session (the pot rules are packages/rpc lib/garden.js), latest +// wins; `garden-help` is one watering of another member's pot. No text: +// nothing in them is ever shown as typed by a person. +const GARDEN_KEYS = Object.freeze(['type', 'on', 'at']) +const GARDEN_STATE_KEYS = Object.freeze(['type', 'pots', 'n', 'at']) +const GARDEN_HELP_KEYS = Object.freeze(['type', 'to', 'pot', 'at']) const { THEME_IDS, MAX_ABOUT, MAX_CITY, MAX_WORK, MAX_STUDIES, MAX_INTERESTS, MAX_MOOD_TEXT } = PX // Momentos (docs/protocol.md): one photo or short video in the anonymous // blob pool, its key and nonce public in the record, shown by readers for 24 @@ -600,7 +608,7 @@ function validPageShape (r) { isHex64(r.owner) && r.actor === r.owner && validPageAdmins(r.admins, r.owner) } -const TYPES = Object.freeze(['member-cert', 'profile', 'post', 'username', 'media-core', 'follow', 'like', 'repost', 'group-join', 'delete', 'group-cut', 'group-confirm', 'dm-key', 'page-roster', 'page-accept', 'page-offer', 'page-close', 'page-moved', 'page-origin', 'page-delegate', 'page-link', 'listing', 'listing-edit', 'listing-status', 'listing-rate', 'testimonial', 'testimonial-show', 'moment', 'post-share', 'scrap', 'scrap-hide', 'scrap-wall', 'profile-about', 'mood', 'fan', 'top-friends', 'choice', 'visits', 'device']) +const TYPES = Object.freeze(['member-cert', 'profile', 'post', 'username', 'media-core', 'follow', 'like', 'repost', 'group-join', 'delete', 'group-cut', 'group-confirm', 'dm-key', 'page-roster', 'page-accept', 'page-offer', 'page-close', 'page-moved', 'page-origin', 'page-delegate', 'page-link', 'listing', 'listing-edit', 'listing-status', 'listing-rate', 'testimonial', 'testimonial-show', 'moment', 'post-share', 'scrap', 'scrap-hide', 'scrap-wall', 'profile-about', 'mood', 'fan', 'top-friends', 'choice', 'visits', 'device', 'garden', 'garden-state', 'garden-help']) // Required lazily: lib/group.js requires this module at load time. function weakBoxKey (hex) { @@ -714,6 +722,22 @@ function check (record, seq) { if (!isCanonicalBase64(record.box, MIN_DEVICE_BOX, MAX_DEVICE_BOX)) return 'malformed' return isCanonicalIso(record.at) ? null : 'date-invalid' } + if (type === 'garden') { + if (!hasExactKeys(record, GARDEN_KEYS) || typeof record.on !== 'boolean') return 'malformed' + return isCanonicalIso(record.at) ? null : 'date-invalid' + } + // A pot is judged against this record's own date (read once here): a pot + // watered after the record that states it was written is malformed. + if (type === 'garden-state') { + if (!hasExactKeys(record, GARDEN_STATE_KEYS)) return 'malformed' + const at = record.at + if (!isCanonicalIso(at)) return 'date-invalid' + return garden.isPots(record.pots, Date.parse(at)) && garden.isSaveOrdinal(record.n) ? null : 'malformed' + } + if (type === 'garden-help') { + if (!hasExactKeys(record, GARDEN_HELP_KEYS) || !isHex64(record.to) || !garden.isPotIndex(record.pot)) return 'malformed' + return isCanonicalIso(record.at) ? null : 'date-invalid' + } if (type === 'top-friends') { if (!hasExactKeys(record, TOP_FRIENDS_KEYS) || !validTopKeys(record.keys)) return 'malformed' return isCanonicalIso(record.at) ? null : 'date-invalid' @@ -964,6 +988,22 @@ function deviceRecord ({ nonce, box, at = nowIso() } = {}) { return build({ type: 'device', nonce, box, at }, 1) } +function gardenRecord ({ on, at = nowIso() } = {}) { + return build({ type: 'garden', on, at }, 1) +} + +// `pots` is copied one level down (a pot holds only primitives), so the +// record never shares an object with the caller; anything that is no array +// or no plain pot is passed through for validation to reject. +function gardenStateRecord ({ pots, n, at = nowIso() } = {}) { + const copy = Array.isArray(pots) ? pots.map((p) => (isPlainObject(p) ? { ...p } : p)) : pots + return build({ type: 'garden-state', pots: copy, n, at }, 1) +} + +function gardenHelpRecord ({ to, pot, at = nowIso() } = {}) { + return build({ type: 'garden-help', to, pot, at }, 1) +} + function topFriendsRecord ({ keys, at = nowIso() } = {}) { return build({ type: 'top-friends', keys: Array.isArray(keys) ? keys.slice() : keys, at }, 1) } @@ -1238,6 +1278,9 @@ module.exports = { MIN_DEVICE_BOX, MAX_DEVICE_BOX, isCanonicalBase64, + GARDEN_KEYS, + GARDEN_STATE_KEYS, + GARDEN_HELP_KEYS, TOP_FRIENDS_KEYS, MAX_TOP_FRIENDS, POST_POLL_KEYS, @@ -1312,6 +1355,9 @@ module.exports = { fanRecord, visitsRecord, deviceRecord, + gardenRecord, + gardenStateRecord, + gardenHelpRecord, topFriendsRecord, momentRecord, deleteRecord, diff --git a/packages/core/test/garden.test.js b/packages/core/test/garden.test.js new file mode 100644 index 00000000..eec5d3cc --- /dev/null +++ b/packages/core/test/garden.test.js @@ -0,0 +1,251 @@ +'use strict' + +const test = require('brittle') +const b4a = require('b4a') +const { garden } = require('@varanda/rpc') +const records = require('../lib/records') +const { applyDeletes } = require('../lib/deletion') +const feed = require('../lib/feed') +const activity = require('../lib/activity') + +const { + validateRecord, validRecordCopy, decodeBlock, deleteRecord, MAX_BLOCK_BYTES, + GARDEN_KEYS, GARDEN_STATE_KEYS, GARDEN_HELP_KEYS, + gardenRecord, gardenStateRecord, gardenHelpRecord +} = records + +const K2 = 'b'.repeat(64) +const AT = '2026-11-16T15:00:00.000Z' +const EARLIER = '2026-11-16T09:00:00.000Z' +const LATER = '2026-11-16T18:00:00.000Z' + +function pot (over = {}) { + return { plant: 'tomate', at: EARLIER, water: EARLIER, w: 0, ...over } +} + +function state (over = {}) { + return { type: 'garden-state', pots: [pot(), null, null, null, null, null], n: 1, at: AT, ...over } +} + +function without (record, key) { + const out = { ...record } + delete out[key] + return out +} + +test('garden key sets are frozen and exact', async (t) => { + t.alike([...GARDEN_KEYS], ['type', 'on', 'at']) + t.alike([...GARDEN_STATE_KEYS], ['type', 'pots', 'n', 'at']) + t.alike([...GARDEN_HELP_KEYS], ['type', 'to', 'pot', 'at']) + t.ok(Object.isFrozen(GARDEN_KEYS)) + t.ok(Object.isFrozen(GARDEN_STATE_KEYS)) + t.ok(Object.isFrozen(GARDEN_HELP_KEYS)) +}) + +test('garden record: rules, reasons and builder', async (t) => { + const rec = { type: 'garden', on: true, at: AT } + t.is(validateRecord(rec, 1), null) + t.is(validateRecord({ ...rec, on: false }, 7), null) + t.is(validateRecord(rec, 0), 'genesis-required') + for (const on of [1, 0, 'true', null, undefined, {}, []]) t.is(validateRecord({ ...rec, on }, 1), 'malformed', 'on ' + String(on)) + t.is(validateRecord({ ...rec, extra: 1 }, 1), 'malformed', 'extra key') + t.is(validateRecord({ ...rec, text: 'oi' }, 1), 'malformed', 'no text field') + t.is(validateRecord(without(rec, 'on'), 1), 'malformed', 'missing on') + t.is(validateRecord(without(rec, 'at'), 1), 'malformed', 'missing at') + for (const at of ['2026-11-16', 5, null, '2026-11-16T15:00:00Z']) t.is(validateRecord({ ...rec, at }, 1), 'date-invalid', 'at ' + at) + t.is(validateRecord({ ...rec, on: 'yes', at: 'x' }, 1), 'malformed', 'shape is judged before the date') + t.alike(gardenRecord({ on: true, at: AT }), rec) + t.alike(gardenRecord({ on: false, at: AT }), { ...rec, on: false }) + t.ok(records.isCanonicalIso(gardenRecord({ on: true }).at), 'at defaults to now') + await t.exception.all(async () => gardenRecord({ on: 'yes' }), /malformed/) + await t.exception.all(async () => gardenRecord({ on: true, at: 'ontem' }), /date-invalid/) +}) + +test('garden-state record: rules and reasons', async (t) => { + const rec = state() + t.is(validateRecord(rec, 1), null) + t.is(validateRecord(state({ pots: [null, null, null, null, null, null] }), 1), null, 'an empty balcony') + t.is(validateRecord(rec, 0), 'genesis-required') + t.is(validateRecord({ ...rec, extra: 1 }, 1), 'malformed', 'extra key') + t.is(validateRecord({ ...rec, text: 'oi' }, 1), 'malformed', 'no text field') + for (const k of ['pots', 'n', 'at']) t.is(validateRecord(without(rec, k), 1), 'malformed', 'missing ' + k) + for (const at of ['2026-11-16', 5, null, '2026-11-16T15:00:00Z']) t.is(validateRecord(state({ at }), 1), 'date-invalid', 'at ' + at) + t.is(validateRecord({ ...state({ at: 'x' }), extra: 1 }, 1), 'malformed', 'keys are judged before the date') + t.is(validateRecord(state({ at: 'x', n: 0 }), 1), 'date-invalid', 'the date is judged before pots and n') +}) + +test('garden-state record: n is the save ordinal of the day', async (t) => { + for (let n = 1; n <= garden.GARDEN_SAVES_DAILY_MAX; n++) t.is(validateRecord(state({ n }), 1), null, 'n ' + n) + for (const n of [0, -1, garden.GARDEN_SAVES_DAILY_MAX + 1, 1.5, '1', null, NaN, Infinity]) { + t.is(validateRecord(state({ n }), 1), 'malformed', 'n ' + String(n)) + } +}) + +test('garden-state record: pots shape and dates', async (t) => { + const empty = [null, null, null, null, null, null] + const withPot = (p, i = 0) => empty.map((x, j) => (j === i ? p : x)) + t.is(validateRecord(state({ pots: withPot(pot({ water: AT })) }), 1), null, 'watered at the record instant') + t.is(validateRecord(state({ pots: withPot(pot({ at: AT, water: AT })) }), 1), null, 'planted at the record instant') + t.is(validateRecord(state({ pots: withPot(pot(), 5) }), 1), null, 'the last pot') + t.is(validateRecord(state({ pots: withPot(pot({ water: LATER })) }), 1), 'malformed', 'watered after the record') + t.is(validateRecord(state({ pots: withPot(pot({ at: LATER, water: LATER })) }), 1), 'malformed', 'planted after the record') + t.is(validateRecord(state({ pots: withPot(pot({ at: AT, water: EARLIER })) }), 1), 'malformed', 'watered before it was planted') + t.is(validateRecord(state({ pots: withPot(pot({ at: '2026-11-16T09:00:00Z' })) }), 1), 'malformed', 'a pot date that is not canonical') + t.is(validateRecord(state({ pots: withPot(pot({ plant: 'rosa' })) }), 1), 'malformed', 'unknown plant') + t.is(validateRecord(state({ pots: withPot(pot({ w: -1 })) }), 1), 'malformed', 'negative waterings') + t.is(validateRecord(state({ pots: withPot(pot({ w: garden.GARDEN_WATER_MAX + 1 })) }), 1), 'malformed', 'too many waterings') + t.is(validateRecord(state({ pots: withPot({ ...pot(), extra: 1 }) }), 1), 'malformed', 'extra pot key') + t.is(validateRecord(state({ pots: withPot(without(pot(), 'w')) }), 1), 'malformed', 'missing pot key') + t.is(validateRecord(state({ pots: empty.slice(0, 5) }), 1), 'malformed', 'five pots') + t.is(validateRecord(state({ pots: [...empty, null] }), 1), 'malformed', 'seven pots') + t.is(validateRecord(state({ pots: new Array(6) }), 1), 'malformed', 'a sparse array') + for (const pots of [null, {}, 'pots', 6]) t.is(validateRecord(state({ pots }), 1), 'malformed', 'pots ' + String(pots)) + t.is(validateRecord(state({ pots: withPot(pot(), 0).map((p, i) => (i === 3 ? 0 : p)) }), 1), 'malformed', 'a pot that is no object') +}) + +test('garden-help record: rules, reasons and builder', async (t) => { + const rec = { type: 'garden-help', to: K2, pot: 0, at: AT } + t.is(validateRecord(rec, 1), null) + t.is(validateRecord({ ...rec, pot: 5 }, 1), null, 'the last pot') + t.is(validateRecord(rec, 0), 'genesis-required') + for (const p of [6, -1, 1.5, '0', null, NaN]) t.is(validateRecord({ ...rec, pot: p }, 1), 'malformed', 'pot ' + String(p)) + for (const to of ['B'.repeat(64), K2.slice(1), K2 + 'b', 7, null]) t.is(validateRecord({ ...rec, to }, 1), 'malformed', 'to ' + String(to)) + t.is(validateRecord({ ...rec, extra: 1 }, 1), 'malformed', 'extra key') + t.is(validateRecord({ ...rec, text: 'oi' }, 1), 'malformed', 'no text field') + for (const k of ['to', 'pot', 'at']) t.is(validateRecord(without(rec, k), 1), 'malformed', 'missing ' + k) + for (const at of ['2026-11-16', 5, null, '2026-11-16T15:00:00Z']) t.is(validateRecord({ ...rec, at }, 1), 'date-invalid', 'at ' + at) + t.is(validateRecord({ ...rec, to: 'B'.repeat(64), at: 'x' }, 1), 'malformed', 'shape is judged before the date') + t.alike(gardenHelpRecord({ to: K2, pot: 0, at: AT }), rec) + await t.exception.all(async () => gardenHelpRecord({ to: K2, pot: 6, at: AT }), /malformed/) + await t.exception.all(async () => gardenHelpRecord({ to: 'B'.repeat(64), pot: 0, at: AT }), /malformed/) +}) + +test('gardenStateRecord copies the pots', async (t) => { + const pots = [pot(), null, null, null, null, pot({ plant: 'alecrim' })] + const rec = gardenStateRecord({ pots, n: 2, at: AT }) + t.alike(rec, state({ pots: [pot(), null, null, null, null, pot({ plant: 'alecrim' })], n: 2 })) + t.not(rec.pots, pots) + t.not(rec.pots[0], pots[0]) + pots[0].w = 99 + pots[1] = pot() + t.is(rec.pots[0].w, 0, 'a later change to the caller pot does not reach the record') + t.is(rec.pots[1], null) + await t.exception.all(async () => gardenStateRecord({ pots: [pot({ water: LATER }), null, null, null, null, null], n: 1, at: AT }), /malformed/) + await t.exception.all(async () => gardenStateRecord({ pots: [null, null, null, null, null, null], n: 7, at: AT }), /malformed/) + await t.exception.all(async () => gardenStateRecord({ pots: 'x', n: 1, at: AT }), /malformed/) +}) + +test('hostile garden records are refused, never thrown', async (t) => { + const throwing = state() + Object.defineProperty(throwing, 'pots', { enumerable: true, get () { throw new Error('boom') } }) + t.is(validateRecord(throwing, 1), 'malformed') + t.is(validRecordCopy(throwing, 1), null) + + const getterPot = pot() + Object.defineProperty(getterPot, 'w', { enumerable: true, get () { return 0 } }) + t.is(validateRecord(state({ pots: [getterPot, null, null, null, null, null] }), 1), 'malformed', 'a pot field behind a getter') + + const proxied = new Proxy([pot(), null, null, null, null, null], { getOwnPropertyDescriptor () { throw new Error('boom') } }) + t.is(validateRecord(state({ pots: proxied }), 1), 'malformed', 'a proxy array whose descriptors throw') + const getTrap = new Proxy([pot(), null, null, null, null, null], { get () { throw new Error('boom') } }) + t.is(validRecordCopy(state({ pots: getTrap }), 1), null, 'a proxy array is never copied') + + const symbolPots = [null, null, null, null, null, null] + symbolPots[Symbol('x')] = 1 + t.is(validateRecord(state({ pots: symbolPots }), 1), 'malformed', 'an array with a symbol key') + + const extraPots = [null, null, null, null, null, null] + extraPots.extra = 1 + t.is(validateRecord(state({ pots: extraPots }), 1), 'malformed', 'an array with an extra key') + + const protoPot = Object.create({ evil: true }) + Object.assign(protoPot, pot()) + t.is(validateRecord(state({ pots: [protoPot, null, null, null, null, null] }), 1), 'malformed', 'a pot with a foreign prototype') + + const revocable = Proxy.revocable({}, {}) + revocable.revoke() + t.is(validateRecord(state({ pots: revocable.proxy }), 1), 'malformed', 'a revoked proxy') + t.is(validateRecord({ type: 'garden-help', to: K2, pot: { valueOf () { return 0 } }, at: AT }, 1), 'malformed') +}) + +test('garden constants match core: future tolerance and the Brasília day', async (t) => { + t.is(garden.GARDEN_MAX_FUTURE_MS, feed.MAX_FUTURE_MS) + t.is(garden.GARDEN_DAY_MS, activity.DAY_MS) + t.is(garden.GARDEN_DAY_OFFSET_MS, activity.DAY_OFFSET_MS) + let mismatches = 0 + let checked = 0 + const start = Date.parse('1969-12-25T00:00:00.000Z') + const end = Date.parse('1970-01-05T00:00:00.000Z') + // Every 7 minutes 13 seconds across the epoch, then across midnight + // Brasília (03:00 UTC) of a recent day to the millisecond edges. + for (let ms = start; ms < end; ms += 433000) { + checked++ + if (garden.gardenDay(ms) !== activity.localDay(ms)) mismatches++ + if (garden.dayStart(ms) !== activity.dayStart(ms)) mismatches++ + } + const midnight = Date.parse('2026-11-16T03:00:00.000Z') + for (const d of [-86400001, -1, 0, 1, 3599999, 86399999, 86400000]) { + checked++ + if (garden.gardenDay(midnight + d) !== activity.localDay(midnight + d)) mismatches++ + if (garden.dayStart(midnight + d) !== activity.dayStart(midnight + d)) mismatches++ + } + for (let ms = Date.parse('2026-01-01T00:00:00.000Z'); ms < Date.parse('2027-01-01T00:00:00.000Z'); ms += 3600000 + 17) { + checked++ + if (garden.gardenDay(ms) !== activity.localDay(ms)) mismatches++ + } + t.ok(checked > 10000, checked + ' instants') + t.is(mismatches, 0) + t.is(garden.gardenDay(midnight - 1), '2026-11-15') + t.is(garden.gardenDay(midnight), '2026-11-16') +}) + +test('deleting the newest garden-state makes the previous live one win', async (t) => { + const older = gardenStateRecord({ pots: [pot(), null, null, null, null, null], n: 1, at: EARLIER }) + const newer = gardenStateRecord({ pots: [null, pot({ plant: 'pimenta', at: AT, water: AT }), null, null, null, null], n: 2, at: AT }) + const latestState = (entries) => { + let best = null + for (const e of entries) { + const copy = e.record === null ? null : validRecordCopy(e.record, e.seq) + if (copy !== null && copy.type === 'garden-state' && (best === null || e.seq > best.seq)) best = { seq: e.seq, record: copy } + } + return best + } + const entries = [{ seq: 1, record: older }, { seq: 2, record: newer }] + t.is(latestState(applyDeletes(entries)).seq, 2, 'the newest wins while it lives') + const withDelete = [...entries, { seq: 3, record: deleteRecord({ seq: 2, at: LATER }) }] + const live = applyDeletes(withDelete) + t.ok(live[1].deleted, 'the newest state is deleted') + const best = latestState(live) + t.is(best.seq, 1, 'the previous state wins') + t.alike(best.record, older) +}) + +test('garden records survive validRecordCopy and the block codec', async (t) => { + const recs = [ + gardenRecord({ on: true, at: AT }), + gardenStateRecord({ pots: [pot(), null, pot({ plant: 'espada', w: 3 }), null, null, null], n: 3, at: AT }), + gardenHelpRecord({ to: K2, pot: 2, at: AT }) + ] + for (const r of recs) { + const copy = validRecordCopy(r, 4) + t.alike(copy, r, r.type + ' copy') + t.not(copy, r) + const decoded = decodeBlock(b4a.from(JSON.stringify(r))) + t.alike(decoded, r, r.type + ' block round trip') + t.is(validateRecord(decoded, 4), null) + t.is(validRecordCopy(r, 0), null, r.type + ' never at seq 0') + } + const copy = validRecordCopy(recs[1], 4) + t.not(copy.pots, recs[1].pots) + t.not(copy.pots[0], recs[1].pots[0]) +}) + +test('a full six-pot garden-state is far below MAX_BLOCK_BYTES', async (t) => { + const max = '2026-11-16T15:00:00.000Z' + const pots = garden.GARDEN_PLANTS.map((p) => ({ plant: p.id, at: '2026-11-16T09:00:00.000Z', water: max, w: garden.GARDEN_WATER_MAX })) + t.is(pots.length, garden.GARDEN_POTS) + const rec = gardenStateRecord({ pots, n: garden.GARDEN_SAVES_DAILY_MAX, at: max }) + const bytes = b4a.byteLength(JSON.stringify(rec)) + t.is(MAX_BLOCK_BYTES, 16384) + t.ok(bytes < MAX_BLOCK_BYTES / 16, bytes + ' bytes') +}) diff --git a/packages/core/test/records.test.js b/packages/core/test/records.test.js index ccdec456..2f063596 100644 --- a/packages/core/test/records.test.js +++ b/packages/core/test/records.test.js @@ -904,7 +904,7 @@ test('old readers: unknown types stay malformed', async (t) => { test('group-join records', async (t) => { await testnet(t) const { groupJoinRecord, TYPES, MAX_GROUP_WRITERS, MAX_GROUPS_PER_DIARY, MAX_GROUPS_PER_COMMUNITY, MAX_GROUP_CUTS, MAX_GROUP_NAME, MAX_GROUP_WRITERS_PER_DIARY } = records - t.alike([...TYPES], ['member-cert', 'profile', 'post', 'username', 'media-core', 'follow', 'like', 'repost', 'group-join', 'delete', 'group-cut', 'group-confirm', 'dm-key', 'page-roster', 'page-accept', 'page-offer', 'page-close', 'page-moved', 'page-origin', 'page-delegate', 'page-link', 'listing', 'listing-edit', 'listing-status', 'listing-rate', 'testimonial', 'testimonial-show', 'moment', 'post-share', 'scrap', 'scrap-hide', 'scrap-wall', 'profile-about', 'mood', 'fan', 'top-friends', 'choice', 'visits', 'device'], 'TYPES parity') + t.alike([...TYPES], ['member-cert', 'profile', 'post', 'username', 'media-core', 'follow', 'like', 'repost', 'group-join', 'delete', 'group-cut', 'group-confirm', 'dm-key', 'page-roster', 'page-accept', 'page-offer', 'page-close', 'page-moved', 'page-origin', 'page-delegate', 'page-link', 'listing', 'listing-edit', 'listing-status', 'listing-rate', 'testimonial', 'testimonial-show', 'moment', 'post-share', 'scrap', 'scrap-hide', 'scrap-wall', 'profile-about', 'mood', 'fan', 'top-friends', 'choice', 'visits', 'device', 'garden', 'garden-state', 'garden-help'], 'TYPES parity') t.ok(Object.isFrozen(TYPES)) t.alike([MAX_GROUP_WRITERS, MAX_GROUPS_PER_DIARY, MAX_GROUPS_PER_COMMUNITY, MAX_GROUP_CUTS, MAX_GROUP_NAME, MAX_GROUP_WRITERS_PER_DIARY], [512, 64, 32, 16, 80, 8]) const gj = { type: 'group-join', group: K1, writer: K2, on: true, at: AT } @@ -2022,6 +2022,27 @@ test('visits record: key set, rules and builder', async (t) => { await t.exception.all(async () => visitsRecord({ on: 'yes' }), /malformed/) }) +test('garden records: old readers skip all three as malformed', async (t) => { + // A copy of TYPES before the Varandinha: an old reader skips each record + // as any unknown type, and the diary that carries it is not rejected. + const OLD_TYPES = ['member-cert', 'profile', 'post', 'username', 'media-core', 'follow', 'like', 'repost', 'group-join', 'delete', 'group-cut', 'group-confirm', 'dm-key', 'page-roster', 'page-accept', 'page-offer', 'page-close', 'page-moved', 'page-origin', 'page-delegate', 'page-link', 'listing', 'listing-edit', 'listing-status', 'listing-rate', 'testimonial', 'testimonial-show', 'moment', 'post-share', 'scrap', 'scrap-hide', 'scrap-wall', 'profile-about', 'mood', 'fan', 'top-friends', 'choice', 'visits'] + const oldReader = (r) => (OLD_TYPES.includes(r.type) ? validateRecord(r, 1) : 'malformed') + const pot = { plant: 'tomate', at: AT, water: AT, w: 0 } + const recs = [ + { type: 'garden', on: true, at: AT }, + { type: 'garden-state', pots: [pot, null, null, null, null, null], n: 1, at: AT }, + { type: 'garden-help', to: K2, pot: 0, at: AT } + ] + for (const r of recs) { + t.is(validateRecord(r, 1), null, r.type + ' valid today') + t.is(oldReader(r), 'malformed', r.type + ' skipped by an old reader') + } + t.is(validateRecord({ ...recs[0], type: 'jardim' }, 1), 'malformed', 'unknown types stay malformed') + // None borrows another type's shape. + t.is(validateRecord({ type: 'garden', key: K2, on: true, at: AT }, 1), 'malformed') + t.is(validateRecord({ type: 'garden-help', key: K2, on: true, at: AT }, 1), 'malformed') +}) + test('fan and top-friends records: key sets, rules and builders', async (t) => { const { fanRecord, topFriendsRecord, FAN_KEYS, TOP_FRIENDS_KEYS, MAX_TOP_FRIENDS } = records t.alike([...FAN_KEYS], ['type', 'key', 'on', 'at']) diff --git a/packages/rpc/index.js b/packages/rpc/index.js index 28c0f652..198ad401 100644 --- a/packages/rpc/index.js +++ b/packages/rpc/index.js @@ -19,6 +19,7 @@ const music = require('./lib/music') const ogParse = require('./lib/og-parse') const musicCover = require('./lib/music-cover') const feira = require('./lib/feira') +const garden = require('./lib/garden') const inviteCard = require('./lib/invite-card') const reaction = require('./lib/reaction') const profileExtra = require('./lib/profile-extra') @@ -104,6 +105,7 @@ module.exports = { YOUTUBE_COVER_HOST: musicCover.YOUTUBE_COVER_HOST, youtubeCoverUrl: musicCover.youtubeCoverUrl, feira, + garden, profileExtra, THEME_IDS: profileExtra.THEME_IDS, isBirthday: profileExtra.isBirthday, diff --git a/packages/rpc/lib/garden.js b/packages/rpc/lib/garden.js new file mode 100644 index 00000000..5e039e73 --- /dev/null +++ b/packages/rpc/lib/garden.js @@ -0,0 +1,583 @@ +'use strict' + +// The pure rules of the Varandinha (the balcony garden): the pot and act +// shapes of the `garden-state` record, growth under the reader's clock, the +// reducer of one play session, and the folds of neighbours' `garden-help` +// records. Core validates records with them, the node judges plays and helps +// with them and the app draws the balcony with them, so every side agrees. +// Zero dependencies, no Node built-ins. Nothing here throws, no input is ever +// mutated and the clock is always a `now` argument in ms: peer records are +// read once into plain copies, and only the copies are judged and used. + +const GARDEN_POTS = 6 +// Portuguese ASCII ids, as THEME_IDS and the Feira KINDS; the pt-BR labels +// live in the app. +const GARDEN_PLANTS = Object.freeze([ + Object.freeze({ id: 'manjericao', ripeMs: 21600000 }), + Object.freeze({ id: 'tomate', ripeMs: 36000000 }), + Object.freeze({ id: 'pimenta', ripeMs: 57600000 }), + Object.freeze({ id: 'alecrim', ripeMs: 86400000 }), + Object.freeze({ id: 'samambaia', ripeMs: 129600000 }), + Object.freeze({ id: 'espada', ripeMs: 172800000 }) +]) +const GARDEN_WATER_GAP_MS = 10800000 +const GARDEN_WATER_BOOST_MS = 3600000 +const GARDEN_WATER_MAX = 12 +const GARDEN_HELP_BOOST_MS = 7200000 +const GARDEN_HELP_PER_POT = 3 +const GARDEN_GIVEN_BOOST_MS = 1800000 +const GARDEN_GIVEN_PER_POT = 3 +const GARDEN_SAVES_DAILY_MAX = 6 +const GARDEN_HELPS_DAILY_MAX = 5 +const GARDEN_ACTS_MAX = 24 +const GARDEN_HELP_WINDOW_MS = 259200000 +const GARDEN_HELP_ROWS = 24 +const GARDEN_STREET_PAGE = 20 +const GARDEN_DAY_MS = 86400000 +// Brasília time, fixed UTC-3 (no daylight saving time since 2019), the same +// day math as packages/core/lib/activity.js, copied so this package keeps +// zero dependencies. +const GARDEN_DAY_OFFSET_MS = -10800000 +// The feed's tolerance for a record dated ahead of the reader's clock +// (packages/core/lib/feed.js). +const GARDEN_MAX_FUTURE_MS = 86400000 + +const POT_KEYS = Object.freeze(['plant', 'at', 'water', 'w']) +const PLANT_ACT_KEYS = Object.freeze(['op', 'pot', 'plant']) +const POT_ACT_KEYS = Object.freeze(['op', 'pot']) +const POT_OPS = Object.freeze(['water', 'harvest', 'clear']) +const FOLLOW_KEYS = Object.freeze(['type', 'key', 'on', 'at']) +const FLAG_KEYS = Object.freeze(['type', 'on', 'at']) +const STATE_KEYS = Object.freeze(['type', 'pots', 'n', 'at']) +const HELP_KEYS = Object.freeze(['type', 'to', 'pot', 'at']) + +// Rows a fold reads at most: the index and the peeks hand over far fewer +// (GARDEN_HELP_ROWS), so a longer list is no honest input and counts nothing. +const FOLD_ROWS_MAX = 1024 +const MAX_TIME_MS = 8.64e15 +const HEX64 = /^[0-9a-f]{64}$/ + +const isHex64 = (v) => typeof v === 'string' && HEX64.test(v) + +function isTime (v) { + return typeof v === 'number' && Number.isFinite(v) && Math.abs(v) <= MAX_TIME_MS +} + +function isPlainObject (v) { + if (v === null || typeof v !== 'object' || Array.isArray(v)) return false + const proto = Object.getPrototypeOf(v) + return proto === Object.prototype || proto === null +} + +// One plain copy of v with exactly `keys`, each value read once from its own +// enumerable data property (never through a get, so a Proxy trap or an +// accessor cannot answer twice), or null when v is anything else. +function snapshot (v, keys) { + try { + if (!isPlainObject(v) || Object.getOwnPropertySymbols(v).length > 0) return null + const names = Object.getOwnPropertyNames(v) + if (names.length !== keys.length || !keys.every((k) => names.includes(k))) return null + const out = {} + for (const k of keys) { + const d = Object.getOwnPropertyDescriptor(v, k) + if (!d || !('value' in d) || !d.enumerable) return null + out[k] = d.value + } + return out + } catch { + return null + } +} + +// A plain copy of a dense array of at most `max` items with no other own +// property, each item read once from its data property, or null. +function snapshotArray (v, max) { + try { + if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype) return null + if (Object.getOwnPropertySymbols(v).length > 0) return null + const ld = Object.getOwnPropertyDescriptor(v, 'length') + const len = ld && ld.value + if (!Number.isSafeInteger(len) || len < 0 || len > max) return null + if (Object.getOwnPropertyNames(v).length !== len + 1) return null + const out = [] + for (let i = 0; i < len; i++) { + const d = Object.getOwnPropertyDescriptor(v, String(i)) + if (!d || !('value' in d) || !d.enumerable) return null + out.push(d.value) + } + return out + } catch { + return null + } +} + +// One own data property of a caller-built object (an options bag, a row), +// extra keys allowed, or undefined. Never runs a getter. +function field (o, k) { + try { + if (o === null || typeof o !== 'object') return undefined + const d = Object.getOwnPropertyDescriptor(o, k) + return d && 'value' in d ? d.value : undefined + } catch { + return undefined + } +} + +// The ms of a canonical instant (Date.parse finite and the toISOString form +// round trips), or NaN. +function isoMs (v) { + try { + if (typeof v !== 'string' || v.length > 32) return NaN + const ms = Date.parse(v) + if (!Number.isFinite(ms) || new Date(ms).toISOString() !== v) return NaN + return ms + } catch { + return NaN + } +} + +function plantOf (id) { + if (typeof id !== 'string') return null + for (const p of GARDEN_PLANTS) if (p.id === id) return p + return null +} + +function isPlantId (v) { + return plantOf(v) !== null +} + +function isPotIndex (v) { + return Number.isSafeInteger(v) && v >= 0 && v < GARDEN_POTS +} + +function isSaveOrdinal (v) { + return Number.isSafeInteger(v) && v >= 1 && v <= GARDEN_SAVES_DAILY_MAX +} + +// Epoch ms of 00:00 Brasília of the day containing ms, or NaN. The double +// modulo keeps the result right for instants before the epoch too. The +// earliest instants start their day below the Date range, which is NaN too. +function dayStart (ms) { + if (!isTime(ms)) return NaN + const start = ms - (((ms + GARDEN_DAY_OFFSET_MS) % GARDEN_DAY_MS) + GARDEN_DAY_MS) % GARDEN_DAY_MS + return isTime(start) ? start : NaN +} + +// The Brasília calendar day of ms as 'YYYY-MM-DD', or null. +function gardenDay (ms) { + try { + if (!isTime(ms)) return null + const day = new Date(ms + GARDEN_DAY_OFFSET_MS).toISOString().slice(0, 10) + return /^\d{4}-\d{2}-\d{2}$/.test(day) ? day : null + } catch { + return null + } +} + +// A pot: null (empty) or { plant, at, water, w }. Returns the copy, null for +// an empty pot, or undefined when v is no pot dated at or before recordAtMs. +function copyPot (v, recordAtMs) { + if (v === null) return null + const p = snapshot(v, POT_KEYS) + if (p === null || !isPlantId(p.plant)) return undefined + const at = isoMs(p.at) + const water = isoMs(p.water) + if (Number.isNaN(at) || Number.isNaN(water) || !(at <= water) || !(water <= recordAtMs)) return undefined + if (!Number.isSafeInteger(p.w) || p.w < 0 || p.w > GARDEN_WATER_MAX) return undefined + return p +} + +function copyPots (v, recordAtMs) { + const list = snapshotArray(v, GARDEN_POTS) + if (list === null || list.length !== GARDEN_POTS) return null + const out = [] + for (const item of list) { + const p = copyPot(item, recordAtMs) + if (p === undefined) return null + out.push(p) + } + return out +} + +// recordAtMs is the ms of the record that carries the pot: a pot cannot be +// watered after the record that states it was written. +function isPot (v, recordAtMs) { + return isTime(recordAtMs) && copyPot(v, recordAtMs) !== undefined +} + +function isPots (v, recordAtMs) { + return isTime(recordAtMs) && copyPots(v, recordAtMs) !== null +} + +function copyAct (v) { + const plant = snapshot(v, PLANT_ACT_KEYS) + if (plant !== null) return plant.op === 'plant' && isPotIndex(plant.pot) && isPlantId(plant.plant) ? plant : null + const act = snapshot(v, POT_ACT_KEYS) + if (act === null || typeof act.op !== 'string' || !POT_OPS.includes(act.op) || !isPotIndex(act.pot)) return null + return act +} + +function copyActs (v) { + const list = snapshotArray(v, GARDEN_ACTS_MAX) + if (list === null || list.length < 1) return null + const out = [] + for (const item of list) { + const a = copyAct(item) + if (a === null) return null + out.push(a) + } + return out +} + +function isAct (v) { + return copyAct(v) !== null +} + +function isActs (v) { + return copyActs(v) !== null +} + +// Whether record is a `follow` of owner that is on: the evidence a helper +// follows the balcony it waters. +function isFollowOf (record, owner) { + if (!isHex64(owner)) return false + const f = snapshot(record, FOLLOW_KEYS) + return f !== null && f.type === 'follow' && f.key === owner && f.on === true && !Number.isNaN(isoMs(f.at)) +} + +function count (v) { + return Number.isSafeInteger(v) && v >= 0 ? v : 0 +} + +// Six per-pot counts: an array of exactly six safe integers >= 0, or six +// zeros for anything else, so a bad argument never reads as NaN. +function counts (v) { + const list = snapshotArray(v, GARDEN_POTS) + if (list === null || list.length !== GARDEN_POTS || !list.every((n) => Number.isSafeInteger(n) && n >= 0)) { + return new Array(GARDEN_POTS).fill(0) + } + return list +} + +function zeros () { + return new Array(GARDEN_POTS).fill(0) +} + +// The view of a pot copy (already checked) at now. +function viewOf (p, now, received, given) { + const plant = plantOf(p.plant) + const at = Date.parse(p.at) + const water = Date.parse(p.water) + const waters = Math.min(p.w, Math.floor((water - at) / GARDEN_WATER_GAP_MS)) + const boost = waters * GARDEN_WATER_BOOST_MS + + Math.min(received, GARDEN_HELP_PER_POT) * GARDEN_HELP_BOOST_MS + + Math.min(given, GARDEN_GIVEN_PER_POT) * GARDEN_GIVEN_BOOST_MS + const need = Math.max(plant.ripeMs / 2, plant.ripeMs - boost) + const progress = now <= at ? 0 : Math.min(1, (now - at) / need) + const ripe = progress >= 1 + const stage = ripe ? 3 : progress < 0.25 ? 0 : progress < 0.6 ? 1 : 2 + const dry = now - water >= GARDEN_WATER_GAP_MS + return { plant: plant.id, progress, stage, ripe, ripeAt: at + need, dry, canWater: !ripe && dry } +} + +// A view whose ripeAt is no valid time is none, so a caller formatting ripeAt +// as a Date never throws. potView and foldBalcony both read pots through it, +// so they answer alike for the same pot and clock. +function shownView (p, now, received, given) { + const view = viewOf(p, now, received, given) + return isTime(view.ripeAt) ? view : null +} + +// Growth has no death and no stall: an unwatered pot still ripens, watering +// and neighbours only shorten the wait, never below half of it. A pot watered +// past the reader's future tolerance is no pot. +function potView (pot, now, opts) { + if (!isTime(now)) return null + const p = copyPot(pot, now + GARDEN_MAX_FUTURE_MS) + if (!p) return null + return shownView(p, now, count(field(opts, 'received')), count(field(opts, 'given'))) +} + +function emptyPots () { + return new Array(GARDEN_POTS).fill(null) +} + +// One play session: every act in order against a copy of the pots. One +// invalid act refuses the whole batch. Watering is judged with no +// neighbour boosts, so a session the node accepts never depends on helps it +// could not verify; only harvest reads the passed counts. +function applyActs (state, acts, now, opts) { + if (!isTime(now)) return { ok: false, reason: 'invalid' } + let pots + if (state === null || state === undefined) { + pots = emptyPots() + } else { + pots = copyPots(field(state, 'pots'), now) + if (pots === null) return { ok: false, reason: 'state' } + } + const list = copyActs(acts) + if (list === null) return { ok: false, reason: 'acts' } + const received = counts(field(opts, 'received')) + const given = counts(field(opts, 'given')) + let iso + try { + iso = new Date(now).toISOString() + } catch { + return { ok: false, reason: 'invalid' } + } + for (const act of list) { + const p = pots[act.pot] + if (act.op === 'plant') { + if (p !== null) return { ok: false, reason: 'occupied' } + pots[act.pot] = { plant: act.plant, at: iso, water: iso, w: 0 } + continue + } + if (p === null) return { ok: false, reason: 'empty' } + if (act.op === 'water') { + if (!viewOf(p, now, 0, 0).canWater) return { ok: false, reason: 'not-dry' } + pots[act.pot] = { plant: p.plant, at: p.at, water: iso, w: Math.min(p.w + 1, GARDEN_WATER_MAX) } + } else if (act.op === 'harvest') { + if (!viewOf(p, now, received[act.pot], given[act.pot]).ripe) return { ok: false, reason: 'not-ripe' } + pots[act.pot] = null + } else { + pots[act.pot] = null + } + } + return { ok: true, state: { pots } } +} + +function inWindow (atMs, now) { + return atMs <= now + GARDEN_MAX_FUTURE_MS && atMs >= now - GARDEN_HELP_WINDOW_MS +} + +function rows (v) { + return snapshotArray(v, FOLD_ROWS_MAX) || [] +} + +function seqOf (row) { + const seq = field(row, 'seq') + return Number.isSafeInteger(seq) && seq >= 1 ? seq : null +} + +// A garden-help record copy, or null. +function helpOf (record) { + const h = snapshot(record, HELP_KEYS) + if (h === null || h.type !== 'garden-help' || !isHex64(h.to) || !isPotIndex(h.pot)) return null + const atMs = isoMs(h.at) + return Number.isNaN(atMs) ? null : { to: h.to, pot: h.pot, at: h.at, atMs } +} + +function potsOrEmpty (pots) { + return copyPots(pots, Infinity) || emptyPots() +} + +// The neighbours' helps to owner's balcony. Each counted help is signed by +// a follower (its follow record is the evidence), dated inside the window, +// at most one per helper per Brasília day (the lowest seq of that day), and +// lands on a pot planted no later than the help. The day is dayStart, the +// same day the writer checks use. The window spans up to five days, so the +// helper list keeps one row per neighbour (the newest kept help): a few +// accounts cannot fill it and push real helpers off. +function foldHelps (args) { + const perPot = zeros() + const empty = { perPot, helpers: [] } + const owner = field(args, 'owner') + const now = field(args, 'now') + if (!isHex64(owner) || !isTime(now)) return empty + const pots = potsOrEmpty(field(args, 'pots')) + const byDay = new Map() + for (const row of rows(field(args, 'helps'))) { + const author = field(row, 'author') + const seq = seqOf(row) + if (!isHex64(author) || author === owner || seq === null) continue + const h = helpOf(field(row, 'record')) + if (h === null || h.to !== owner || !inWindow(h.atMs, now)) continue + if (!isFollowOf(field(row, 'follow'), owner)) continue + const day = dayStart(h.atMs) + if (Number.isNaN(day)) continue + const key = author + '/' + day + const prev = byDay.get(key) + if (prev === undefined || seq < prev.seq) byDay.set(key, { author, seq, pot: h.pot, at: h.at, atMs: h.atMs }) + } + const kept = [] + for (const h of byDay.values()) { + const p = pots[h.pot] + if (p !== null && h.atMs >= Date.parse(p.at)) kept.push(h) + } + kept.sort((a, b) => a.atMs - b.atMs || (a.author < b.author ? -1 : a.author > b.author ? 1 : 0) || a.seq - b.seq) + for (const h of kept) if (perPot[h.pot] < GARDEN_HELP_PER_POT) perPot[h.pot]++ + const newest = new Map() + for (const h of kept) { + const prev = newest.get(h.author) + if (prev === undefined || h.atMs > prev.atMs || (h.atMs === prev.atMs && h.seq < prev.seq)) newest.set(h.author, h) + } + const helpers = [...newest.values()] + .sort((a, b) => b.atMs - a.atMs || (a.author < b.author ? -1 : a.author > b.author ? 1 : 0) || a.seq - b.seq) + .slice(0, GARDEN_HELP_ROWS) + .map((h) => ({ author: h.author, seq: h.seq, pot: h.pot, at: h.at })) + return { perPot, helpers } +} + +// The own helps to other balconies, as a small boost to every own pot +// planted no later than the help: one per balcony per day, at most +// GARDEN_HELPS_DAILY_MAX a day (the lowest seqs), inside the window. +function foldGiven (args) { + const perPot = zeros() + const self = field(args, 'self') + const now = field(args, 'now') + if (!isHex64(self) || !isTime(now)) return { perPot } + const pots = potsOrEmpty(field(args, 'pots')) + const byTo = new Map() + for (const row of rows(field(args, 'given'))) { + const seq = seqOf(row) + if (seq === null) continue + const h = helpOf(field(row, 'record')) + if (h === null || h.to === self || !inWindow(h.atMs, now)) continue + const day = dayStart(h.atMs) + if (Number.isNaN(day)) continue + const key = h.to + '/' + day + const prev = byTo.get(key) + if (prev === undefined || seq < prev.seq) byTo.set(key, { seq, day, atMs: h.atMs }) + } + const byDay = new Map() + for (const h of byTo.values()) { + if (!byDay.has(h.day)) byDay.set(h.day, []) + byDay.get(h.day).push(h) + } + for (const list of byDay.values()) { + list.sort((a, b) => a.seq - b.seq) + for (const h of list.slice(0, GARDEN_HELPS_DAILY_MAX)) { + for (let i = 0; i < GARDEN_POTS; i++) { + const p = pots[i] + if (p !== null && Date.parse(p.at) <= h.atMs && perPot[i] < GARDEN_GIVEN_PER_POT) perPot[i]++ + } + } + } + return { perPot } +} + +// One balcony as a reader sees it. A flag or a state dated more than +// GARDEN_MAX_FUTURE_MS ahead of now is dropped (a dropped flag reads off) and +// the balcony reads as six empty pots with stale true; an off or missing +// flag shows no pots either. +function foldBalcony (args) { + const owner = field(args, 'owner') + const now = field(args, 'now') + const out = { on: false, pots: emptyPots(), helpers: [], stale: false } + if (!isHex64(owner) || !isTime(now)) return out + let stale = false + const flag = snapshot(field(args, 'flag'), FLAG_KEYS) + const flagMs = flag && flag.type === 'garden' && typeof flag.on === 'boolean' ? isoMs(flag.at) : NaN + let on = !Number.isNaN(flagMs) && flag.on === true + if (!Number.isNaN(flagMs) && flagMs > now + GARDEN_MAX_FUTURE_MS) { + on = false + stale = true + } + let pots = null + const state = snapshot(field(args, 'state'), STATE_KEYS) + const stateMs = state && state.type === 'garden-state' && isSaveOrdinal(state.n) ? isoMs(state.at) : NaN + if (!Number.isNaN(stateMs)) { + if (stateMs > now + GARDEN_MAX_FUTURE_MS) stale = true + else pots = copyPots(state.pots, stateMs) + } + if (!on || pots === null) return { on, pots: emptyPots(), helpers: [], stale } + const helps = foldHelps({ owner, pots, helps: field(args, 'helps'), now }) + const given = foldGiven({ self: owner, pots, given: field(args, 'given'), now }) + const views = pots.map((p, i) => p === null ? null : shownView(p, now, helps.perPot[i], given.perPot[i])) + return { on: true, pots: views, helpers: helps.helpers, stale: false } +} + +// The own helps rows as ms, or null when the list itself is unreadable. A +// row's at is a canonical instant or a safe integer of ms. +function ownRows (v) { + const list = snapshotArray(v, FOLD_ROWS_MAX) + if (list === null) return null + const out = [] + for (const row of list) { + const to = field(row, 'to') + const at = field(row, 'at') + const atMs = typeof at === 'number' ? (Number.isSafeInteger(at) ? at : NaN) : isoMs(at) + if (isHex64(to) && !Number.isNaN(atMs)) out.push({ to, atMs }) + } + return out +} + +// Whether self may water to's balcony now. A row dated after today (the +// clock moved back) counts as today, so turning the clock back never frees +// the daily budget. Unreadable input answers 'invalid', never ok. +function helpAllowed (args) { + const self = field(args, 'self') + const to = field(args, 'to') + const now = field(args, 'now') + if (!isHex64(self) || !isHex64(to) || !isTime(now)) return { ok: false, reason: 'invalid' } + if (to === self) return { ok: false, reason: 'self' } + let follows = false + try { + const set = field(args, 'follows') + follows = set instanceof Set && Set.prototype.has.call(set, to) === true + } catch { + follows = false + } + if (!follows) return { ok: false, reason: 'not-following' } + const own = ownRows(field(args, 'own')) + if (own === null) return { ok: false, reason: 'invalid' } + const today = dayStart(now) + if (Number.isNaN(today)) return { ok: false, reason: 'invalid' } + const todays = own.filter((r) => r.atMs >= today) + if (todays.some((r) => r.to === to)) return { ok: false, reason: 'same-day' } + if (todays.length >= GARDEN_HELPS_DAILY_MAX) return { ok: false, reason: 'daily' } + return { ok: true } +} + +// The ordinal n of the next saved state today: 1 on a fresh Brasília day, +// null past GARDEN_SAVES_DAILY_MAX. A previous state dated after today counts +// as today; an unreadable one, or a clock whose day start is no valid time +// (helpAllowed's 'invalid'), answers null, never a fresh budget. +function saveOrdinal (prevState, now) { + const today = dayStart(now) + if (Number.isNaN(today)) return null + if (prevState === null || prevState === undefined) return 1 + const n = field(prevState, 'n') + const atMs = isoMs(field(prevState, 'at')) + if (!isSaveOrdinal(n) || Number.isNaN(atMs)) return null + if (atMs < today) return 1 + return n < GARDEN_SAVES_DAILY_MAX ? n + 1 : null +} + +module.exports = Object.freeze({ + GARDEN_POTS, + GARDEN_PLANTS, + GARDEN_WATER_GAP_MS, + GARDEN_WATER_BOOST_MS, + GARDEN_WATER_MAX, + GARDEN_HELP_BOOST_MS, + GARDEN_HELP_PER_POT, + GARDEN_GIVEN_BOOST_MS, + GARDEN_GIVEN_PER_POT, + GARDEN_SAVES_DAILY_MAX, + GARDEN_HELPS_DAILY_MAX, + GARDEN_ACTS_MAX, + GARDEN_HELP_WINDOW_MS, + GARDEN_HELP_ROWS, + GARDEN_STREET_PAGE, + GARDEN_DAY_MS, + GARDEN_DAY_OFFSET_MS, + GARDEN_MAX_FUTURE_MS, + isPlantId, + isPotIndex, + isPot, + isPots, + isSaveOrdinal, + isAct, + isActs, + isFollowOf, + gardenDay, + dayStart, + potView, + applyActs, + foldHelps, + foldGiven, + foldBalcony, + helpAllowed, + saveOrdinal +}) diff --git a/packages/rpc/test/garden.test.js b/packages/rpc/test/garden.test.js new file mode 100644 index 00000000..cb22ee88 --- /dev/null +++ b/packages/rpc/test/garden.test.js @@ -0,0 +1,602 @@ +'use strict' + +const test = require('brittle') +const rpc = require('..') +const garden = require('../lib/garden') + +const H = 3600000 +// 09:00 Brasília. +const T0 = Date.parse('2026-11-16T12:00:00.000Z') +const iso = (ms) => new Date(ms).toISOString() +const OWNER = 'a'.repeat(64) +const B = 'b'.repeat(64) +const C = 'c'.repeat(64) +const D = 'd'.repeat(64) +const E = 'e'.repeat(64) + +const pot = (plant, atMs, waterMs = atMs, w = 0) => ({ plant, at: iso(atMs), water: iso(waterMs), w }) +const six = (...items) => [...items, null, null, null, null, null, null].slice(0, 6) +const follow = (key = OWNER, on = true) => ({ type: 'follow', key, on, at: iso(T0 - 100 * H) }) +const help = (to, p, atMs) => ({ type: 'garden-help', to, pot: p, at: iso(atMs) }) +const row = (author, seq, p, atMs, extra = {}) => ({ author, seq, record: help(OWNER, p, atMs), follow: follow(), ...extra }) + +test('garden is exported from the package index', (t) => { + t.is(rpc.garden, garden) + t.ok(Object.isFrozen(garden), 'the module object is frozen') + t.ok(Object.isFrozen(garden.GARDEN_PLANTS)) + t.ok(garden.GARDEN_PLANTS.every((p) => Object.isFrozen(p))) +}) + +test('constants are the agreed defaults', (t) => { + t.is(garden.GARDEN_POTS, 6) + t.alike(garden.GARDEN_PLANTS.map((p) => [p.id, p.ripeMs]), [ + ['manjericao', 21600000], ['tomate', 36000000], ['pimenta', 57600000], + ['alecrim', 86400000], ['samambaia', 129600000], ['espada', 172800000] + ]) + t.alike([ + garden.GARDEN_WATER_GAP_MS, garden.GARDEN_WATER_BOOST_MS, garden.GARDEN_WATER_MAX, + garden.GARDEN_HELP_BOOST_MS, garden.GARDEN_HELP_PER_POT, garden.GARDEN_GIVEN_BOOST_MS, + garden.GARDEN_GIVEN_PER_POT, garden.GARDEN_SAVES_DAILY_MAX, garden.GARDEN_HELPS_DAILY_MAX, + garden.GARDEN_ACTS_MAX, garden.GARDEN_HELP_WINDOW_MS, garden.GARDEN_HELP_ROWS, + garden.GARDEN_STREET_PAGE, garden.GARDEN_DAY_MS, garden.GARDEN_DAY_OFFSET_MS, garden.GARDEN_MAX_FUTURE_MS + ], [10800000, 3600000, 12, 7200000, 3, 1800000, 3, 6, 5, 24, 259200000, 24, 20, 86400000, -10800000, 86400000]) +}) + +test('invariants: the help window covers the slowest plant, the gap is shorter than the fastest', (t) => { + const ripes = garden.GARDEN_PLANTS.map((p) => p.ripeMs) + t.ok(garden.GARDEN_HELP_WINDOW_MS >= Math.max(...ripes) + garden.GARDEN_MAX_FUTURE_MS, 'a help to a ripening pot is still in the window') + t.ok(Math.min(...ripes) > garden.GARDEN_WATER_GAP_MS, 'every plant can be watered at least once') +}) + +test('isPlantId, isPotIndex, isSaveOrdinal', (t) => { + for (const p of garden.GARDEN_PLANTS) t.ok(garden.isPlantId(p.id), p.id) + for (const bad of ['Tomate', 'rosa', '', 'toString', '__proto__', null, 1, {}, ['tomate']]) t.absent(garden.isPlantId(bad), String(bad)) + for (let i = 0; i < 6; i++) t.ok(garden.isPotIndex(i)) + for (const bad of [-1, 6, 1.5, '1', NaN, null, true]) t.absent(garden.isPotIndex(bad), String(bad)) + for (let n = 1; n <= 6; n++) t.ok(garden.isSaveOrdinal(n)) + for (const bad of [0, 7, 2.5, '1', null]) t.absent(garden.isSaveOrdinal(bad), String(bad)) +}) + +test('isPot: exact shape, canonical dates, ordered at <= water <= record', (t) => { + const ok = pot('tomate', T0, T0 + 3 * H, 1) + t.ok(garden.isPot(ok, T0 + 3 * H), 'watered at the record instant') + t.ok(garden.isPot(null, T0), 'an empty pot') + t.absent(garden.isPot(ok, T0 + 3 * H - 1), 'watered after the record') + t.absent(garden.isPot(pot('tomate', T0 + H, T0), T0 + 2 * H), 'watered before planted') + t.absent(garden.isPot(ok), 'no record instant') + t.absent(garden.isPot(ok, NaN)) + t.absent(garden.isPot({ ...ok, extra: 1 }, T0 + 5 * H), 'an extra key') + const { w, ...missing } = ok + t.absent(garden.isPot(missing, T0 + 5 * H), 'a missing key') + for (const at of ['2026-11-16T12:00:00Z', '2026-11-16T12:00:00.000+00:00', '2026-11-16T09:00:00.000-03:00', '2026-02-30T12:00:00.000Z', '2026-11-16', ' 2026-11-16T12:00:00.000Z', 1763294400000]) { + t.absent(garden.isPot({ ...ok, at }, T0 + 5 * H), 'non-canonical at ' + JSON.stringify(at)) + } + for (const bad of [-1, 13, 1.5, '1', null, NaN]) t.absent(garden.isPot({ ...ok, w: bad }, T0 + 5 * H), 'w ' + String(bad)) + t.ok(garden.isPot({ ...ok, w: 12 }, T0 + 5 * H), 'w at the cap') + t.absent(garden.isPot({ ...ok, plant: 'rosa' }, T0 + 5 * H), 'unknown plant') + for (const bad of [undefined, 0, 'x', [], [ok]]) t.absent(garden.isPot(bad, T0 + 5 * H), String(bad)) +}) + +test('isPot: hostile objects never throw and never pass', (t) => { + const ok = pot('tomate', T0) + const getter = { ...ok } + Object.defineProperty(getter, 'w', { enumerable: true, get () { throw new Error('boom') } }) + t.absent(garden.isPot(getter, T0), 'a throwing getter') + const accessor = { ...ok } + Object.defineProperty(accessor, 'w', { enumerable: true, get () { return 0 } }) + t.absent(garden.isPot(accessor, T0), 'an accessor that returns a good value') + t.absent(garden.isPot(new Proxy({ ...ok }, { ownKeys () { throw new Error('boom') } }), T0), 'a throwing ownKeys trap') + t.absent(garden.isPot(new Proxy({ ...ok }, { getPrototypeOf () { throw new Error('boom') } }), T0), 'a throwing prototype trap') + const { proxy, revoke } = Proxy.revocable({ ...ok }, {}) + revoke() + t.absent(garden.isPot(proxy, T0), 'a revoked proxy') + t.absent(garden.isPot({ ...ok, [Symbol('x')]: 1 }, T0), 'a symbol key') + const hidden = { ...ok } + Object.defineProperty(hidden, 'extra', { enumerable: false, value: 1 }) + t.absent(garden.isPot(hidden, T0), 'a hidden extra key') + class Pot { constructor () { Object.assign(this, ok) } } + t.absent(garden.isPot(new Pot(), T0), 'a class instance') + t.ok(garden.isPot(Object.assign(Object.create(null), ok), T0), 'a null-prototype object is plain') +}) + +test('a Proxy cannot answer differently after the check', (t) => { + const target = pot('manjericao', T0) + const liar = new Proxy(target, { get (o, k) { return k === 'plant' ? 'espada' : k === 'w' ? 99 : o[k] } }) + t.ok(garden.isPot(liar, T0), 'the own data properties are a valid pot') + t.is(garden.potView(liar, T0 + H).plant, 'manjericao', 'the view reads the checked value, never the get trap') + const out = garden.applyActs({ pots: six(liar) }, [{ op: 'clear', pot: 0 }], T0 + H) + t.ok(out.ok) +}) + +test('isPots: a dense array of exactly six pots', (t) => { + t.ok(garden.isPots(six(), T0)) + t.ok(garden.isPots(six(pot('tomate', T0), null, pot('espada', T0 - H)), T0)) + t.absent(garden.isPots(six().slice(0, 5), T0), 'five') + t.absent(garden.isPots([...six(), null], T0), 'seven') + // eslint-disable-next-line no-sparse-arrays + t.absent(garden.isPots([null, , null, null, null, null], T0), 'sparse') + t.absent(garden.isPots(new Array(6), T0), 'all holes') + const extra = six() + extra.foo = 1 + t.absent(garden.isPots(extra, T0), 'an extra array property') + t.absent(garden.isPots({ 0: null, 1: null, 2: null, 3: null, 4: null, 5: null, length: 6 }, T0), 'array-like') + const getter = six() + Object.defineProperty(getter, 2, { enumerable: true, get () { throw new Error('boom') } }) + t.absent(garden.isPots(getter, T0), 'a throwing index getter') + t.absent(garden.isPots(new Proxy(six(), { ownKeys () { throw new Error('boom') } }), T0), 'a throwing proxy') + t.absent(garden.isPots(six(pot('tomate', T0 + 1)), T0), 'a pot dated after the record') + t.absent(garden.isPots(six({ plant: 'tomate' }), T0), 'one bad pot') + t.absent(garden.isPots(six(), 'x'), 'no record instant') +}) + +test('isAct and isActs: the four acts with exact keys', (t) => { + t.ok(garden.isAct({ op: 'plant', pot: 0, plant: 'tomate' })) + for (const op of ['water', 'harvest', 'clear']) t.ok(garden.isAct({ op, pot: 5 }), op) + t.absent(garden.isAct({ op: 'plant', pot: 0 }), 'plant without a plant') + t.absent(garden.isAct({ op: 'water', pot: 0, plant: 'tomate' }), 'water with a plant') + t.absent(garden.isAct({ op: 'plant', pot: 0, plant: 'tomate', at: 1 }), 'an extra key') + t.absent(garden.isAct({ op: 'water', pot: 6 }), 'pot 6') + t.absent(garden.isAct({ op: 'dig', pot: 0 }), 'unknown op') + t.absent(garden.isAct({ op: 'plant', pot: 0, plant: 'rosa' }), 'unknown plant') + const getter = { op: 'water' } + Object.defineProperty(getter, 'pot', { enumerable: true, get () { throw new Error('boom') } }) + t.absent(garden.isAct(getter), 'a throwing getter') + for (const bad of [null, undefined, 'water', ['water', 0]]) t.absent(garden.isAct(bad), String(bad)) + const act = { op: 'water', pot: 0 } + t.ok(garden.isActs([act])) + t.ok(garden.isActs(new Array(24).fill(act)), 'at the cap') + t.absent(garden.isActs([]), 'empty') + t.absent(garden.isActs(new Array(25).fill(act)), 'over the cap') + // eslint-disable-next-line no-sparse-arrays + t.absent(garden.isActs([act, , act]), 'sparse') + t.absent(garden.isActs([act, { op: 'water' }]), 'one bad act') + t.absent(garden.isActs({ 0: act, length: 1 }), 'array-like') +}) + +test('isFollowOf: an on follow of exactly that owner', (t) => { + t.ok(garden.isFollowOf(follow(), OWNER)) + t.absent(garden.isFollowOf(follow(OWNER, false), OWNER), 'an unfollow') + t.absent(garden.isFollowOf(follow(B), OWNER), 'a follow of someone else') + t.absent(garden.isFollowOf({ ...follow(), type: 'fan' }, OWNER), 'another type') + t.absent(garden.isFollowOf({ ...follow(), extra: 1 }, OWNER), 'an extra key') + t.absent(garden.isFollowOf({ ...follow(), on: 1 }, OWNER), 'on is not true') + t.absent(garden.isFollowOf({ ...follow(), at: '2026-11-16T12:00:00Z' }, OWNER), 'a non-canonical date') + t.absent(garden.isFollowOf(follow(), 'A'.repeat(64)), 'a bad owner') + t.absent(garden.isFollowOf(null, OWNER)) + t.absent(garden.isFollowOf(new Proxy(follow(), { ownKeys () { throw new Error('boom') } }), OWNER)) +}) + +test('gardenDay and dayStart: Brasília days start at 03:00Z', (t) => { + t.is(garden.gardenDay(Date.parse('2026-11-16T02:59:59.999Z')), '2026-11-15') + t.is(garden.gardenDay(Date.parse('2026-11-16T03:00:00.000Z')), '2026-11-16') + t.is(garden.dayStart(T0), Date.parse('2026-11-16T03:00:00.000Z')) + t.is(garden.dayStart(Date.parse('2026-11-16T02:00:00.000Z')), Date.parse('2026-11-15T03:00:00.000Z')) + t.is(garden.dayStart(-1), Date.parse('1969-12-31T03:00:00.000Z'), 'before the epoch') + for (const bad of [NaN, Infinity, '1', null, 9e15]) { + t.is(garden.gardenDay(bad), null, String(bad)) + t.ok(Number.isNaN(garden.dayStart(bad)), String(bad)) + } +}) + +test('dayStart: a start below the Date range is NaN', (t) => { + t.ok(Number.isNaN(garden.dayStart(-8.64e15)), 'the earliest instant starts its day out of range') + t.is(garden.dayStart(8.64e15), Date.parse('+275760-09-12T03:00:00.000Z'), 'the latest instant still has a day') + t.is(garden.dayStart(T0), Date.parse('2026-11-16T03:00:00.000Z'), 'a normal instant is unchanged') +}) + +test('potView: growth at zero, a quarter and ripe', (t) => { + const p = pot('manjericao', T0) + const v0 = garden.potView(p, T0) + t.alike(v0, { plant: 'manjericao', progress: 0, stage: 0, ripe: false, ripeAt: T0 + 6 * H, dry: false, canWater: false }) + t.is(garden.potView(p, T0 + 1.5 * H - 1).stage, 0, 'just below a quarter') + const q = garden.potView(p, T0 + 1.5 * H) + t.is(q.progress, 0.25) + t.is(q.stage, 1, 'a quarter') + t.is(garden.potView(p, T0 + 3.6 * H).stage, 2, 'from 0.6') + const almost = garden.potView(p, T0 + 6 * H - 1) + t.absent(almost.ripe) + t.is(almost.stage, 2) + const ripe = garden.potView(p, T0 + 6 * H) + t.ok(ripe.ripe) + t.is(ripe.stage, 3) + t.is(ripe.progress, 1) + t.absent(ripe.canWater, 'a ripe pot is never watered') + t.is(garden.potView(p, T0 + 100 * H).progress, 1, 'no death') + t.is(garden.potView(p, T0 + 3 * H).dry, true, 'dry after the gap') + t.is(garden.potView(p, T0 + 3 * H).canWater, true) + t.is(garden.potView(p, T0 + 3 * H - 1).dry, false) +}) + +test('potView: boosts, the half-time floor and waters clamped by the gaps', (t) => { + const watered = pot('manjericao', T0, T0 + 3 * H, 1) + t.is(garden.potView(watered, T0).ripeAt, T0 + 5 * H, 'one water takes an hour off') + t.is(garden.potView(pot('manjericao', T0, T0 + 4 * H, 12), T0).ripeAt, T0 + 5 * H, 'w is clamped by the gaps between at and water') + t.is(garden.potView(pot('manjericao', T0, T0 + 30 * H, 2), T0 + 30 * H).ripeAt, T0 + 4 * H, 'waters are clamped by w') + t.is(garden.potView(pot('manjericao', T0), T0, { received: 1 }).ripeAt, T0 + 4 * H, 'one help takes two hours off') + t.is(garden.potView(pot('manjericao', T0), T0, { received: 99 }).ripeAt, T0 + 3 * H, 'helps cap at three, floored at half time') + t.is(garden.potView(pot('espada', T0), T0, { received: 99 }).ripeAt, T0 + 48 * H - 6 * H, 'three helps on a slow plant') + t.is(garden.potView(pot('espada', T0), T0, { given: 99 }).ripeAt, T0 + 48 * H - 1.5 * H, 'given caps at three') + const max = pot('tomate', T0, T0 + 6 * H, 2) + t.is(garden.potView(max, T0, { received: 3, given: 3 }).ripeAt, T0 + 5 * H, 'waters, helps and given together never go below half of ripeMs') + t.ok(garden.potView(pot('manjericao', T0), T0 + 3 * H, { received: 3 }).ripe, 'ripe at the floor') + for (const bad of [-1, NaN, '3', 1.5, null, Infinity]) { + t.is(garden.potView(pot('manjericao', T0), T0, { received: bad, given: bad }).ripeAt, T0 + 6 * H, 'a bad count reads 0: ' + String(bad)) + } +}) + +test('potView: a pot dated ahead of now reads 0, bad input reads null', (t) => { + const v = garden.potView(pot('tomate', T0 + 2 * H), T0) + t.is(v.progress, 0) + t.is(v.stage, 0) + t.absent(v.dry) + t.is(garden.potView(null, T0), null) + t.is(garden.potView({ plant: 'tomate' }, T0), null) + t.is(garden.potView(pot('tomate', T0), NaN), null) + t.is(garden.potView(pot('tomate', T0), '1'), null) + const opts = {} + Object.defineProperty(opts, 'received', { enumerable: true, get () { throw new Error('boom') } }) + t.is(garden.potView(pot('manjericao', T0), T0, opts).ripeAt, T0 + 6 * H, 'a throwing options getter reads 0') +}) + +test('potView: a pot watered past the future tolerance, or ripe past the Date range, is null', (t) => { + const last = '+275760-09-13T00:00:00.000Z' + t.is(garden.potView({ plant: 'manjericao', at: last, water: last, w: 0 }, T0), null, 'dated at the largest instant') + t.is(garden.potView(pot('manjericao', T0, T0 + 23 * H), T0).plant, 'manjericao', 'watered 23 h ahead') + t.is(garden.potView(pot('manjericao', T0 + 24 * H), T0).progress, 0, 'at the tolerance') + t.is(garden.potView(pot('manjericao', T0, T0 + 25 * H), T0), null, 'watered 25 h ahead') + const late = 8.64e15 - H + t.is(garden.potView(pot('manjericao', late), late), null, 'a ripeAt past the Date range') +}) + +test('applyActs: plant, water, harvest, clear', (t) => { + let out = garden.applyActs(null, [{ op: 'plant', pot: 0, plant: 'manjericao' }, { op: 'plant', pot: 3, plant: 'tomate' }], T0) + t.ok(out.ok) + t.alike(out.state.pots, six(pot('manjericao', T0), null, null, pot('tomate', T0))) + t.ok(garden.isPots(out.state.pots, T0), 'the result is a valid state at now') + const s1 = out.state + t.is(garden.applyActs(s1, [{ op: 'water', pot: 0 }], T0 + 3 * H - 1).reason, 'not-dry') + out = garden.applyActs(s1, [{ op: 'water', pot: 0 }], T0 + 3 * H) + t.ok(out.ok) + t.alike(out.state.pots[0], pot('manjericao', T0, T0 + 3 * H, 1)) + t.is(garden.applyActs(out.state, [{ op: 'water', pot: 0 }], T0 + 3 * H).reason, 'not-dry', 'watered twice in one session') + t.is(garden.applyActs(out.state, [{ op: 'harvest', pot: 0 }], T0 + 5 * H - 1).reason, 'not-ripe') + const h = garden.applyActs(out.state, [{ op: 'harvest', pot: 0 }], T0 + 5 * H) + t.ok(h.ok, 'one water took an hour off') + t.is(h.state.pots[0], null) + t.is(garden.applyActs(s1, [{ op: 'plant', pot: 0, plant: 'tomate' }], T0).reason, 'occupied') + t.is(garden.applyActs(s1, [{ op: 'water', pot: 1 }], T0 + 3 * H).reason, 'empty') + t.is(garden.applyActs(s1, [{ op: 'clear', pot: 1 }], T0).reason, 'empty') + t.is(garden.applyActs(s1, [{ op: 'harvest', pot: 1 }], T0).reason, 'empty') + const c = garden.applyActs(s1, [{ op: 'clear', pot: 3 }], T0 + H) + t.ok(c.ok, 'clear needs no ripeness') + t.is(c.state.pots[3], null) + const replant = garden.applyActs(s1, [{ op: 'clear', pot: 3 }, { op: 'plant', pot: 3, plant: 'espada' }], T0 + H) + t.alike(replant.state.pots[3], pot('espada', T0 + H)) + t.is(garden.applyActs(null, [{ op: 'plant', pot: 0, plant: 'tomate' }, { op: 'water', pot: 0 }], T0).reason, 'not-dry', 'a fresh pot is not dry') +}) + +test('applyActs: w is capped at GARDEN_WATER_MAX', (t) => { + const state = { pots: six(pot('espada', T0, T0 + 30 * H, 12)) } + const out = garden.applyActs(state, [{ op: 'water', pot: 0 }], T0 + 33 * H) + t.ok(out.ok) + t.is(out.state.pots[0].w, 12) +}) + +test('applyActs: one bad act refuses the whole batch, inputs are never mutated', (t) => { + const state = { type: 'garden-state', pots: six(pot('manjericao', T0)), n: 1, at: iso(T0) } + const acts = [{ op: 'plant', pot: 1, plant: 'tomate' }, { op: 'water', pot: 0 }, { op: 'plant', pot: 2, plant: 'espada' }] + const before = JSON.stringify({ state, acts }) + const out = garden.applyActs(state, acts, T0 + H) + t.alike(out, { ok: false, reason: 'not-dry' }) + t.is(JSON.stringify({ state, acts }), before, 'a refusal changes nothing') + const good = garden.applyActs(state, [{ op: 'water', pot: 0 }, { op: 'plant', pot: 1, plant: 'tomate' }], T0 + 3 * H) + t.ok(good.ok) + t.is(JSON.stringify({ state, acts }), before, 'a success changes nothing either') + t.not(good.state.pots, state.pots) + good.state.pots[0].w = 9 + t.is(state.pots[0].w, 0, 'the result shares nothing with the input') + t.is(garden.applyActs(state, [{ op: 'clear', pot: 0 }, { op: 'dig', pot: 1 }], T0).reason, 'acts', 'one malformed act') + t.is(garden.applyActs(state, [], T0).reason, 'acts') + t.is(garden.applyActs(state, new Array(25).fill({ op: 'clear', pot: 0 }), T0).reason, 'acts') +}) + +test('applyActs: a bad state or clock refuses', (t) => { + const act = [{ op: 'plant', pot: 0, plant: 'tomate' }] + t.is(garden.applyActs({ pots: six(pot('tomate', T0 + H)) }, act, T0).reason, 'state', 'a state watered after now') + t.is(garden.applyActs({ pots: six().slice(0, 5) }, act, T0).reason, 'state') + t.is(garden.applyActs({}, act, T0).reason, 'state') + t.is(garden.applyActs('x', act, T0).reason, 'state') + const getter = {} + Object.defineProperty(getter, 'pots', { enumerable: true, get () { throw new Error('boom') } }) + t.is(garden.applyActs(getter, act, T0).reason, 'state', 'a throwing getter') + for (const bad of [NaN, '1', null, undefined, Infinity]) t.is(garden.applyActs(null, act, bad).reason, 'invalid', String(bad)) +}) + +test('applyActs: water ignores neighbour counts, harvest reads them (round 3)', (t) => { + const full = [3, 3, 3, 3, 3, 3] + const state = { pots: six(pot('manjericao', T0), pot('tomate', T0)) } + t.ok(garden.applyActs(state, [{ op: 'water', pot: 0 }], T0 + 3 * H, { received: full }).ok, 'manjericao watered at hour 3') + t.ok(garden.applyActs(state, [{ op: 'water', pot: 1 }], T0 + 6 * H, { received: full }).ok, 'tomate watered at hour 6') + t.ok(garden.applyActs(state, [{ op: 'water', pot: 1 }], T0 + 6 * H, { received: full, given: full }).ok, 'given does not block a water either') + t.ok(garden.applyActs(state, [{ op: 'harvest', pot: 0 }], T0 + 3 * H, { received: full }).ok, 'harvest under three helps at the floor') + t.is(garden.applyActs(state, [{ op: 'harvest', pot: 0 }], T0 + 3 * H).reason, 'not-ripe', 'not ripe with no helps') + const g = garden.applyActs(state, [{ op: 'harvest', pot: 0 }], T0 + 4.5 * H, { given: [3, 0, 0, 0, 0, 0] }) + t.ok(g.ok, 'given takes 1.5 h off') + for (const bad of [[3, 3], [3, 3, 3, 3, 3, 3, 3], 'x', 3, { 0: 3, length: 6 }, [3, 3, 3, 3, 3, -1], [3, 3, 3, 3, 3, 1.5], [NaN, 3, 3, 3, 3, 3], null]) { + t.is(garden.applyActs(state, [{ op: 'harvest', pot: 0 }], T0 + 3 * H, { received: bad }).reason, 'not-ripe', 'reads as zeros: ' + JSON.stringify(bad)) + } + const hostile = [3, 3, 3, 3, 3, 3] + Object.defineProperty(hostile, 0, { enumerable: true, get () { throw new Error('boom') } }) + t.is(garden.applyActs(state, [{ op: 'harvest', pot: 0 }], T0 + 3 * H, { received: hostile }).reason, 'not-ripe', 'a throwing count getter reads as zeros') +}) + +test('foldHelps: counted helps and the helper list', (t) => { + const pots = six(pot('espada', T0 - 10 * H), pot('tomate', T0 - 10 * H)) + const now = T0 + 2 * H + const out = garden.foldHelps({ owner: OWNER, pots, now, helps: [row(B, 5, 0, T0), row(C, 9, 1, T0 + H)] }) + t.alike(out.perPot, [1, 1, 0, 0, 0, 0]) + t.alike(out.helpers, [ + { author: C, seq: 9, pot: 1, at: iso(T0 + H) }, + { author: B, seq: 5, pot: 0, at: iso(T0) } + ], 'newest first') +}) + +test('foldHelps: one help per helper per Brasília day, across the 03:00Z boundary', (t) => { + const pots = six(pot('espada', T0 - 40 * H)) + const now = T0 + const before = Date.parse('2026-11-16T02:59:00.000Z') + const after = Date.parse('2026-11-16T03:01:00.000Z') + const late = Date.parse('2026-11-16T11:00:00.000Z') + let out = garden.foldHelps({ owner: OWNER, pots, now, helps: [row(B, 3, 0, before), row(B, 4, 0, after)] }) + t.is(out.perPot[0], 2, 'two Brasília days') + out = garden.foldHelps({ owner: OWNER, pots, now, helps: [row(B, 7, 0, late), row(B, 4, 0, after)] }) + t.is(out.perPot[0], 1, 'one Brasília day') + t.alike(out.helpers.map((h) => h.seq), [4], 'the lowest seq of the day wins') + out = garden.foldHelps({ owner: OWNER, pots, now, helps: [row(B, 4, 0, after), row(B, 4, 0, after)] }) + t.is(out.perPot[0], 1, 'a repeated row counts once') +}) + +test('foldHelps: a help without follow evidence, from the owner or to another balcony is dropped', (t) => { + const pots = six(pot('espada', T0 - 10 * H)) + const now = T0 + H + const count = (helps) => garden.foldHelps({ owner: OWNER, pots, now, helps }).perPot[0] + t.is(count([row(B, 1, 0, T0, { follow: null })]), 0, 'no follow record') + t.is(count([row(B, 1, 0, T0, { follow: follow(OWNER, false) })]), 0, 'an unfollow') + t.is(count([row(B, 1, 0, T0, { follow: follow(C) })]), 0, 'a follow of another member') + t.is(count([{ author: B, seq: 1, record: help(OWNER, 0, T0) }]), 0, 'a row without follow') + t.is(count([row(OWNER, 1, 0, T0)]), 0, 'the owner watering their own balcony') + t.is(count([{ ...row(B, 1, 0, T0), record: help(C, 0, T0) }]), 0, 'a help to another balcony') + t.is(count([{ ...row(B, 1, 0, T0), record: { ...help(OWNER, 0, T0), extra: 1 } }]), 0, 'an extra key') + t.is(count([{ ...row(B, 1, 0, T0), record: { ...help(OWNER, 0, T0), type: 'scrap' } }]), 0, 'another type') + t.is(count([{ ...row(B, 1, 0, T0), record: { ...help(OWNER, 0, T0), at: '2026-11-16T12:00:00Z' } }]), 0, 'a non-canonical date') + t.is(count([row(B, 0, 0, T0)]), 0, 'seq 0') + t.is(count([row('B'.repeat(64), 1, 0, T0)]), 0, 'a bad author') + const getter = row(C, 2, 0, T0) + Object.defineProperty(getter.record, 'pot', { enumerable: true, get () { throw new Error('boom') } }) + t.is(count([getter, row(B, 1, 0, T0)]), 1, 'a hostile record is skipped, the others count') + t.is(count([new Proxy(row(C, 2, 0, T0), { getOwnPropertyDescriptor () { throw new Error('boom') } }), row(B, 1, 0, T0)]), 1, 'a hostile row is skipped') + t.is(count([row(B, 1, 0, T0)]), 1, 'the control row counts') +}) + +test('foldHelps: the per-pot cap and the order of who counts', (t) => { + const pots = six(pot('espada', T0 - 10 * H)) + const now = T0 + 10 * H + const helps = [row(E, 1, 0, T0 + 3 * H), row(D, 1, 0, T0 + 2 * H), row(C, 1, 0, T0 + H), row(B, 1, 0, T0 + H)] + const out = garden.foldHelps({ owner: OWNER, pots, now, helps }) + t.is(out.perPot[0], 3, 'capped at GARDEN_HELP_PER_POT') + t.is(out.helpers.length, 4, 'every helper is still listed') + t.alike(out.helpers.map((h) => h.author), [E, D, B, C], 'newest first, then author') +}) + +test('foldHelps: one helper row per author, the newest kept help', (t) => { + const pots = six(pot('espada', T0 - 100 * H), pot('espada', T0 - 100 * H)) + const now = T0 + // Three Brasília days for B: 11-14, 11-15 and 11-16. + const helps = [row(B, 1, 0, T0 - 50 * H), row(B, 2, 1, T0 - 26 * H), row(B, 3, 0, T0 - 2 * H), row(C, 1, 1, T0 - H)] + const out = garden.foldHelps({ owner: OWNER, pots, now, helps }) + t.alike(out.perPot, [2, 2, 0, 0, 0, 0], 'every counted day still counts') + t.alike(out.helpers, [ + { author: C, seq: 1, pot: 1, at: iso(T0 - H) }, + { author: B, seq: 3, pot: 0, at: iso(T0 - 2 * H) } + ], 'B once, its newest help') +}) + +test('foldHelps: a few accounts cannot fill the helper list', (t) => { + const pots = six(pot('espada', T0 - 100 * H)) + const now = T0 + const authors = ['1', '2', '3', '4', '5'].map((c) => c.repeat(64)) + // Five Brasília days inside the window: 11-13 to 11-17. + const times = [T0 - 71 * H, T0 - 48 * H, T0 - 24 * H, T0, T0 + 23 * H] + const helps = [] + for (const a of authors) for (const [i, at] of times.entries()) helps.push(row(a, i + 1, 0, at)) + t.is(helps.length, 25) + let out = garden.foldHelps({ owner: OWNER, pots, now, helps }) + t.is(out.perPot[0], 3) + t.alike(out.helpers, authors.map((author) => ({ author, seq: 5, pot: 0, at: iso(T0 + 23 * H) })), 'five rows, one per author') + const honest = '6'.repeat(64) + out = garden.foldHelps({ owner: OWNER, pots, now, helps: [...helps, row(honest, 1, 0, now - 72 * H)] }) + t.is(out.helpers.length, 6) + t.is(out.helpers[5].author, honest, 'a real helper is still listed') +}) + +test('foldHelps: Brasília days past year 9999 are still separate days', (t) => { + const now = Date.parse('+010000-03-01T12:00:00.000Z') + const pots = six(pot('espada', now - 100 * H)) + const count = (helps) => garden.foldHelps({ owner: OWNER, pots, now, helps }).perPot[0] + t.is(count([row(B, 1, 0, now - 25 * H), row(B, 2, 0, now - H)]), 2, 'two consecutive days') + t.is(count([row(B, 1, 0, now - 2 * H), row(B, 2, 0, now - H)]), 1, 'the same day') +}) + +test('foldHelps: future, out-of-window and early helps are dropped', (t) => { + const pots = six(pot('espada', T0 - 100 * H), pot('tomate', T0)) + const now = T0 + const count = (helps) => garden.foldHelps({ owner: OWNER, pots, now, helps }).perPot + t.alike(count([row(B, 1, 0, now + 24 * H)]), [1, 0, 0, 0, 0, 0], 'at the future tolerance') + t.alike(count([row(B, 1, 0, now + 24 * H + 1)]), [0, 0, 0, 0, 0, 0], 'past the future tolerance') + t.alike(count([row(B, 1, 0, now - 72 * H)]), [1, 0, 0, 0, 0, 0], 'at the window edge') + t.alike(count([row(B, 1, 0, now - 72 * H - 1)]), [0, 0, 0, 0, 0, 0], 'older than the window') + t.alike(count([row(B, 1, 1, T0 - 1)]), [0, 0, 0, 0, 0, 0], 'before the pot was planted') + t.alike(count([row(B, 1, 1, T0)]), [0, 1, 0, 0, 0, 0], 'at the planting') + t.alike(count([row(B, 1, 2, T0)]), [0, 0, 0, 0, 0, 0], 'an empty pot') +}) + +test('foldHelps: the helper list is capped, bad input counts nothing', (t) => { + const pots = six(pot('espada', T0 - 100 * H)) + const helps = [] + for (let i = 0; i < 30; i++) helps.push(row(i.toString(16).padStart(64, '0'), 1, 0, T0 - i * H)) + const out = garden.foldHelps({ owner: OWNER, pots, now: T0, helps }) + t.is(out.helpers.length, 24) + t.is(out.helpers[0].at, iso(T0)) + t.is(out.perPot[0], 3) + const zero = { perPot: [0, 0, 0, 0, 0, 0], helpers: [] } + t.alike(garden.foldHelps({ owner: OWNER, pots, now: T0, helps: 'x' }), zero) + t.alike(garden.foldHelps({ owner: 'x', pots, now: T0, helps }), zero) + t.alike(garden.foldHelps({ owner: OWNER, pots, now: NaN, helps }), zero) + t.alike(garden.foldHelps({ owner: OWNER, pots: 'x', now: T0, helps }), zero, 'no planted pot') + t.alike(garden.foldHelps(null), zero) +}) + +test('foldGiven: own helps boost own pots planted before them', (t) => { + const pots = six(pot('espada', T0 - 10 * H), pot('tomate', T0 + H)) + const now = T0 + 2 * H + const g = (seq, to, atMs) => ({ seq, record: help(to, 0, atMs) }) + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: [g(1, B, T0)] }).perPot, [1, 0, 0, 0, 0, 0], 'the later pot gets nothing') + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: [g(1, B, T0 + H)] }).perPot, [1, 1, 0, 0, 0, 0], 'planted at the help') + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: [g(1, B, T0), g(2, B, T0 + 1000)] }).perPot, [1, 0, 0, 0, 0, 0], 'one per balcony per day') + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: [g(1, OWNER, T0)] }).perPot, [0, 0, 0, 0, 0, 0], 'a help to self') + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: [g(1, B, T0), g(2, C, T0), g(3, D, T0), g(4, E, T0)] }).perPot, [3, 0, 0, 0, 0, 0], 'capped per pot') + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: [g(1, B, now + 25 * H), g(2, C, now - 73 * H)] }).perPot, [0, 0, 0, 0, 0, 0], 'out of the window') + t.alike(garden.foldGiven({ self: OWNER, pots, now, given: 'x' }).perPot, [0, 0, 0, 0, 0, 0]) + t.alike(garden.foldGiven({ self: 'x', pots, now, given: [g(1, B, T0)] }).perPot, [0, 0, 0, 0, 0, 0]) +}) + +test('foldGiven: at most GARDEN_HELPS_DAILY_MAX a day, the lowest seqs', (t) => { + const now = T0 + 2 * H + const to = (i) => i.toString(16).padStart(64, '2') + const given = [] + for (let i = 0; i < 6; i++) given.push({ seq: 10 + i, record: help(to(i), 0, T0 + i * 1000) }) + // The pot is planted at the sixth help, so it sees that help alone. + const pots = six(pot('espada', T0 + 5000)) + t.is(garden.foldGiven({ self: OWNER, pots, now, given }).perPot[0], 0, 'the sixth help of the day does not count') + t.is(garden.foldGiven({ self: OWNER, pots, now, given: given.slice(1) }).perPot[0], 1, 'the same help as the fifth counts') + const nextDay = given.map((g, i) => i === 5 ? { seq: g.seq, record: help(to(5), 0, T0 + 24 * H) } : g) + t.is(garden.foldGiven({ self: OWNER, pots, now: T0 + 25 * H, given: nextDay }).perPot[0], 1, 'the next day has its own budget') +}) + +test('foldGiven: Brasília days past year 9999 are still separate days', (t) => { + const now = Date.parse('+010000-03-01T12:00:00.000Z') + const pots = six(pot('espada', now - 100 * H)) + const at = (seq, to, atMs) => ({ seq, record: help(to, 0, atMs) }) + t.is(garden.foldGiven({ self: OWNER, pots, now, given: [at(1, B, now - 25 * H), at(2, B, now - H)] }).perPot[0], 2, 'one balcony on two consecutive days') + t.is(garden.foldGiven({ self: OWNER, pots, now, given: [at(1, B, now - 2 * H), at(2, B, now - H)] }).perPot[0], 1, 'one balcony on the same day') + const to = (i) => i.toString(16).padStart(64, '2') + const given = [] + for (let i = 0; i < 5; i++) given.push(at(10 + i, to(i), now - 25 * H + i * 1000)) + given.push(at(20, to(5), now - H)) + // Planted at the last help, so the pot sees that help alone. + t.is(garden.foldGiven({ self: OWNER, pots: six(pot('espada', now - H)), now, given }).perPot[0], 1, 'the next day has its own budget') +}) + +test('foldBalcony: the reader view of a balcony', (t) => { + const flag = { type: 'garden', on: true, at: iso(T0 - 50 * H) } + const state = { type: 'garden-state', pots: six(pot('manjericao', T0 - 2 * H)), n: 1, at: iso(T0 - 2 * H) } + const helps = [row(B, 3, 0, T0 - H)] + const given = [{ seq: 2, record: help(C, 0, T0 - H) }] + const out = garden.foldBalcony({ owner: OWNER, flag, state, helps, given, now: T0 }) + t.is(out.on, true) + t.is(out.stale, false) + t.is(out.pots[0].ripeAt, T0 - 2 * H + 6 * H - 2 * H - 0.5 * H, 'one help and one given') + t.alike(out.pots.slice(1), [null, null, null, null, null]) + t.alike(out.helpers, [{ author: B, seq: 3, pot: 0, at: iso(T0 - H) }]) +}) + +test('foldBalcony: off, future and malformed records', (t) => { + const flag = { type: 'garden', on: true, at: iso(T0) } + const state = { type: 'garden-state', pots: six(pot('tomate', T0)), n: 1, at: iso(T0) } + const empty = [null, null, null, null, null, null] + let out = garden.foldBalcony({ owner: OWNER, flag: { ...flag, on: false }, state, now: T0 }) + t.alike([out.on, out.pots, out.stale], [false, empty, false], 'an off flag shows no pots') + out = garden.foldBalcony({ owner: OWNER, flag: null, state, now: T0 }) + t.alike([out.on, out.pots, out.stale], [false, empty, false], 'no flag') + out = garden.foldBalcony({ owner: OWNER, flag: { ...flag, at: iso(T0 + 24 * H + 1) }, state, now: T0 }) + t.alike([out.on, out.pots, out.stale], [false, empty, true], 'a future flag is dropped') + const future = iso(T0 + 24 * H + 1) + out = garden.foldBalcony({ owner: OWNER, flag, state: { ...state, pots: six(pot('tomate', T0 + 24 * H + 1)), at: future }, now: T0 }) + t.alike([out.on, out.pots, out.stale], [true, empty, true], 'a future state is dropped') + out = garden.foldBalcony({ owner: OWNER, flag, state: { ...state, pots: six(pot('tomate', T0 + 24 * H)), at: iso(T0 + 24 * H) }, now: T0 }) + t.is(out.pots[0].progress, 0, 'a state at the tolerance reads, its pot at zero') + out = garden.foldBalcony({ owner: OWNER, flag, state: { ...state, n: 7 }, now: T0 }) + t.alike([out.on, out.pots, out.stale], [true, empty, false], 'a malformed state') + out = garden.foldBalcony({ owner: OWNER, flag, state: { ...state, at: iso(T0 - 1) }, now: T0 }) + t.alike(out.pots, empty, 'a pot dated after its record') + out = garden.foldBalcony({ owner: OWNER, flag: { ...flag, on: 'true' }, state, now: T0 }) + t.is(out.on, false, 'on must be exactly true') + out = garden.foldBalcony({ owner: OWNER, flag: { ...flag, extra: 1 }, state, now: T0 }) + t.is(out.on, false, 'a flag with an extra key') + t.alike(garden.foldBalcony(null), { on: false, pots: empty, helpers: [], stale: false }) +}) + +test('foldBalcony: a pot ripe past the Date range is an empty slot, as potView answers', (t) => { + const now = 8.64e15 - 1000 + const planted = pot('manjericao', now - 1000) + const flag = { type: 'garden', on: true, at: iso(now - 50 * H) } + const state = { type: 'garden-state', pots: six(planted, pot('tomate', now)), n: 1, at: iso(now) } + t.is(garden.potView(planted, now), null, 'potView answers null') + t.is(garden.potView(pot('tomate', now), now), null, 'planted at now too') + const out = garden.foldBalcony({ owner: OWNER, flag, state, now }) + t.is(out.on, true) + t.is(out.stale, false) + t.alike(out.pots, [null, null, null, null, null, null], 'both slots read empty') + t.ok(out.pots.every((v) => v === null || Math.abs(v.ripeAt) <= 8.64e15), 'no view with an out-of-range ripeAt') +}) + +test('helpAllowed: reasons', (t) => { + const follows = new Set([B, C]) + const base = { self: OWNER, to: B, follows, own: [], now: T0 } + t.alike(garden.helpAllowed(base), { ok: true }) + t.alike(garden.helpAllowed({ ...base, to: OWNER }), { ok: false, reason: 'self' }) + t.alike(garden.helpAllowed({ ...base, to: D }), { ok: false, reason: 'not-following' }) + t.alike(garden.helpAllowed({ ...base, follows: [B] }), { ok: false, reason: 'not-following' }, 'follows must be a Set') + t.alike(garden.helpAllowed({ ...base, own: [{ to: B, at: iso(T0 - H) }] }), { ok: false, reason: 'same-day' }) + t.alike(garden.helpAllowed({ ...base, own: [{ to: B, at: iso(T0 - H).replace('.000Z', 'Z') }] }), { ok: true }, 'a non-canonical row is no row') + t.alike(garden.helpAllowed({ ...base, own: [{ to: B, at: T0 - H }] }), { ok: false, reason: 'same-day' }, 'a row in ms') + t.alike(garden.helpAllowed({ ...base, own: [{ to: B, at: Date.parse('2026-11-16T02:59:59.999Z') }] }), { ok: true }, 'yesterday in Brasília') + t.alike(garden.helpAllowed({ ...base, own: [{ to: B, at: iso(T0 + 48 * H) }] }), { ok: false, reason: 'same-day' }, 'a future row counts as today') + const five = [D, E, '1'.repeat(64), '2'.repeat(64), '3'.repeat(64)].map((to) => ({ to, at: iso(T0 - H) })) + t.alike(garden.helpAllowed({ ...base, own: five }), { ok: false, reason: 'daily' }) + t.alike(garden.helpAllowed({ ...base, own: five.slice(0, 4) }), { ok: true }) + t.alike(garden.helpAllowed({ ...base, own: five.map((r) => ({ ...r, at: iso(T0 - 24 * H) })) }), { ok: true }, 'yesterday frees the budget') + for (const bad of [{ ...base, now: NaN }, { ...base, now: -8.64e15 }, { ...base, self: 'x' }, { ...base, to: null }, { ...base, own: 'x' }, { ...base, own: undefined }, null]) { + t.alike(garden.helpAllowed(bad), { ok: false, reason: 'invalid' }) + } + const hostileSet = new Proxy(new Set([B]), {}) + t.alike(garden.helpAllowed({ ...base, follows: hostileSet }), { ok: false, reason: 'not-following' }, 'a proxied Set never throws') +}) + +test('saveOrdinal: rollover at the Brasília day', (t) => { + const prev = (n, atMs) => ({ type: 'garden-state', pots: six(), n, at: iso(atMs) }) + t.is(garden.saveOrdinal(null, T0), 1) + t.is(garden.saveOrdinal(undefined, T0), 1) + t.is(garden.saveOrdinal(prev(3, T0 - H), T0), 4) + t.is(garden.saveOrdinal(prev(5, T0 - H), T0), 6) + t.is(garden.saveOrdinal(prev(6, T0 - H), T0), null, 'past the daily max') + t.is(garden.saveOrdinal(prev(6, Date.parse('2026-11-16T02:59:59.999Z')), T0), 1, 'yesterday in Brasília') + t.is(garden.saveOrdinal(prev(6, Date.parse('2026-11-16T03:00:00.000Z')), T0), null, 'today from 03:00Z') + t.is(garden.saveOrdinal(prev(6, T0 + 48 * H), T0), null, 'a future state counts as today') + t.is(garden.saveOrdinal({ ...prev(2, T0 - H), seq: 9 }, T0), 3, 'extra wrapper keys are fine') + t.is(garden.saveOrdinal(prev(7, T0 - H), T0), null, 'a malformed ordinal') + t.is(garden.saveOrdinal({ n: 1, at: 'x' }, T0), null, 'a malformed date') + t.is(garden.saveOrdinal(prev(1, T0), NaN), null, 'no clock') +}) + +test('saveOrdinal: a clock whose Brasília day starts below the Date range answers null', (t) => { + const prev = (n, atMs) => ({ type: 'garden-state', pots: six(), n, at: iso(atMs) }) + const early = -8.64e15 + t.is(garden.saveOrdinal(null, early), null, 'no previous state') + t.is(garden.saveOrdinal(undefined, early), null) + t.is(garden.saveOrdinal(prev(2, early), early), null, 'a readable previous state') + t.is(garden.saveOrdinal(null, T0), 1, 'a normal clock is unchanged') + t.is(garden.saveOrdinal(prev(6, T0 - 24 * H), T0), 1, 'rollover') + t.is(garden.saveOrdinal(prev(2, T0 - H), T0), 3, 'n + 1') + t.is(garden.saveOrdinal(prev(6, T0 - H), T0), null, 'past the max') +})