4047a2bae95ed3faf7efa3f9e6e0bb0106c95a9a
600 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
4047a2bae9 |
refactor: say what an event is in one place, not on one screen
`FrostSigningScreen` turned an event into words -- "New chapter", "Genesis 1 · 797 words · 31 chunks" -- inside a private composable, which was the right place for it while one screen was the only place a proposal was ever seen. The room's list of proposals is about to need the same words, and two copies of this mapping is two names for one thing. They would not drift immediately; they would drift the first time a kind is added and only one of them learns about it, and the reader would meet an artifact on one screen and "Event of kind 30300" on the other. `ProposedEvent.summarize` is the same `when`, moved whole, returning a label and a detail instead of a `Pair` so the two halves are named where they are read. Not a composable and deliberately: nothing about naming a thing needs a composition, and a plain function can be called from a view model, which is where the list does it -- once per emission rather than once per recomposition of a scrolling row. The reasoning moved with it, because it is reasoning about the words rather than about the screen: a member deciding whether to sign is deciding about a dialect or an artifact, "kind 30304" answers a question nobody asked, and the raw kind stays for anything unrecognised since refusing to describe an event is better than describing it wrongly. What stays on the screen is what is true only there: a batch is all-or-nothing, so an event that cannot be read is a reason to refuse the whole proposal rather than a gap to render around. No behaviour change. Same strings, same order, same fallback. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
4de87edf12 |
fix: tell one proposal's transcript lines from another's
A room with two proposals open showed "Review" on both, and then dropped it from both the moment either one was decided. The second proposal was still waiting on the reader, still had a decision in it, and had nowhere left to be reached from. Two proposals at once is not a corner case any more: a chapter and the translation scaffolding beside it are proposed as separate sessions, on purpose, and they run at the same time. Both write the same line types into the same stretch of transcript. `answeredRequests` matched a request against any later line of the fulfilling type, and `settledRequests` against any later ending. That reads a room signing one thing at a time exactly right -- the nonce after the request is the answer to it, because there is nothing else it could be an answer to -- and a room signing two things at once exactly wrong. Nothing else on the row could separate them: same type, same room, same minute, and `ChatMessage` carried no session. So the session goes on the row. `ChatMessage.frostSigningSessionId` is nullable, added as schema v11 through `AutoMigration(10, 11)`, and stamped by `FrostSigningManager.announce` -- the one place every FROST line is written, so there is no line that can be forgotten. Both rules read it when both rows have one and fall back to the clock when either does not. The fallback is not a compromise, it is the right reading of the rows it applies to. A line written before this column has no session and never will, and the rooms that wrote those lines could not run two sessions at once, so the clock is the whole truth there. A ceremony line falls back too and always will: a room runs one ritual at a time, and a DKG step is either taken or still waited on. **This reverses a call `FrostSigningRoute` argued for.** Its note said a chat row carrying a session id was "a poor trade for a lookup the screen can do". That was right when the lookup could only be wrong about which of one session it meant. The batch work made two sessions ordinary, and the lookup and the rules both became guesses at the same moment. A column on the table every message uses is the cost; two proposals, one of them unreachable, was the alternative. **Tests.** Three in TranscriptRequestStateTest for what the column buys: a nonce answers its own session's request and not the other's, one session completing settles nothing in the other, and a line naming no session is still read by the clock. TranslationBatchProposalJvmTest proves the other half against a real two-session proposal -- every FROST line the manager writes names its own session, and neither session's lines are attributed to the other. The rule is tested on rows and the stamping is tested on a database, because a rule that is right about rows nothing writes correctly is worth nothing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
3fade6c849 |
feat: propose a long artifact's translation in more sessions, not none at all
An artifact of more than MAX_CHAPTERS_PER_TRANSLATION chapters could not be translated. The form refused, said so in red, and left nothing to be done about it -- the chapters are already signed, and unlike a chapter's paragraphs there is nothing the person reading that message can split. It was a cap on how long a book may be, wearing a cap on a batch as a disguise. The same answer the chapter side already gives: propose more than once. The translation and as many chapters as fit go in the first session, and the rest follow in sessions of their own, naming the translation the first is about to sign. The admins answer once per session, and the form counts them before the tap rather than colouring a refusal. MAX_CHAPTERS_PER_TRANSLATION stays, meaning what it now measures -- how many chapters ride in the translation's own session, the batch minus the place the translation itself takes. It is a cap on a session rather than on the work. The cost is the one every second session in this design carries, and is documented where it is paid: if the translation fails to reach a quorum while these succeed, they are valid signatures over rows naming a translation nobody has, which fail a foreign key on the way in and are logged rather than applied. The catch-up on the translation is what fills that in afterwards. **Tests.** TranslationBatchProposalJvmTest now covers the split: an artifact three chapters past the cap proposes a full first session and a second of three, every chapter of the work covered exactly once across both, in order, each naming the translation as the group will author it. The refusal test stays and keeps its point -- one session is still refused a chapter too many, because a batch that quietly dropped its last chapters would sign a translation the group believes covers the whole work while the end of it can never be translated. What changed is who prevents it: the screen splits rather than checks, and the manager still refuses independently. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
df058dc61c |
feat: let a translation ask for the chapters it is missing
A translation is scaffolded from both ends now -- the chapters that existed when it was proposed, and each chapter signed afterwards putting itself in. Neither end closes the gap on its own, and no snapshot taken at proposal time can. Two ways they miss each other. A chapter and a translation proposed at the same moment each read what exists when they are proposed, so neither sees the other and nothing retries. And a scaffolding session that fails to reach a quorum leaves nothing behind to try again with -- the chapter's id is spent, since a re-proposed chapter is a different one. So the translation's own screen says what it is missing and offers to ask for it. Above the chapter list rather than below, because a chapter that is not in a translation is invisible from a list of the ones that are: the whole failure is that nothing looks wrong. **Matched on the chapter named, not counted.** `chaptersMissingFrom` compares which source chapter each translation chapter stands for. A count would read a translation that is missing its second chapter but picked up its third as one missing its last, and would then scaffold the wrong chapter -- leaving the real gap open and a duplicate beside it. It also means running a catch-up on a translation that is already complete proposes nothing at all, rather than a second copy of every chapter under fresh ids. **More sessions rather than a cap.** The missing chapters are chunked at MAX_BATCH_SIZE, one session each. A translation far enough behind to need more than a batch holds is not one to refuse; it is one the group answers for more than once. They share a timestamp, so a catch-up reads as the one act it is. The screen lands on the first session -- the rest are beside it in the room's list -- and the card stays until a quorum arrives, which is honest: the chapters are still missing until then. **Tests.** Two more in TranslationScaffoldTest, both about the matching rather than the counting: a gap in the middle, and a complete translation being missing nothing. Checked against a broken implementation -- taking the missing chapters as the tail after a count passes on a translation that fell behind at the end, which is the easy case, and is caught by the gap. Not covered: `catchUpMissingChapters` itself, which is plumbing over the templates those tests pin and the batch API the jvm tests pin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
66119f34df |
feat: put a new chapter into the artifact's translations, in a session of its own
A translation covered the chapters that existed when it was proposed, and nothing put a later one into it. The chapter was signed, every device applied it, and in every translation of that artifact it simply was not there -- no translation chapter to hang translated chunks off, so the text could not be worked on at all. Invisible from the translation, which lists what it has. Adding a chapter now proposes twice: the chapter and its chunks as before, then a second session carrying one translation chapter per translation of that version. **Why a second session rather than more items on the first.** Because the two would compete for one batch. A session signs at most MAX_BATCH_SIZE events, a chapter is capped at MAX_CHUNKS_PER_CHAPTER paragraphs against it, and every dialect the group works in would have taken one of those places away. How long a chapter may be and how many languages it is read in have nothing to do with each other, and sharing the cap would have moved the first under whoever was typing whenever somebody else did the second. Nothing had to be built for a room to run two at once. Every FROST message carries the session it belongs to and everything is looked up by that id, so there is no "current" session on a room -- `liveSessionForChatRoom` is a fallback for a screen opened without one, not state the protocol keeps. And `itemsOver` mints an independent nonce seed per item per session, so two sessions running together can no more share an `R` than two items of one batch can. The cost is one more approval for the admins. **Naming a chapter nobody has signed yet.** The scaffolding needs the chapter's id, and the chapter is not signed for as long as a quorum takes. It does not have to be: the id is settled when the session opens -- it is the hash every signer puts their share behind -- so the second proposal reads the first session's item 0. `FrostSigningRepository.unsignedEvents` is that read, the counterpart of `signedEvents`, which by design gives back nothing until the group has answered. **What two sessions give up.** A batch is all-or-nothing; two batches are not. If the chapter fails to reach a quorum while its scaffolding succeeds, those are valid signatures over rows naming a chapter nobody has: they fail a foreign key on the way in, `applySignedEvent` logs them, and they never become rows. Nor is it recoverable -- a re-proposed chapter is a different id -- so those signatures are simply spent. Harmless, and the reason the next commit adds a catch-up. It also does not close the race. A chapter and a translation proposed at the same moment see neither the other, because both read what exists when they are proposed. No snapshot can fix that, which is again the catch-up's job. **Failure is one-way.** Scaffolding runs before navigating, not after: the route this screen sits on is popped on success, which clears the view model and takes `viewModelScope` with it, so anything launched afterwards would be cancelled somewhere in the middle. And a failure to open it is logged and swallowed -- the chapter is what was asked for and has already been proposed, and losing it because its scaffolding could not be opened would be the wrong way round. **The chapter's index, once.** It was read inline into the event; it is now a val, because the scaffolding has to place the translation chapter at the same one the chapter is signed at. `MantraTranslationArtifactVersionDao.getTranslationsByArtifactVersionId` is the new read, narrower than the by-artifact one: a chapter belongs to a version, and a translation of an older version is not one it is in. **Tests.** Three in TranslationBatchProposalJvmTest, against a real database and a real ceremony. Two sessions coexist in one room with the chapter's own batch untouched -- the chapter and a chunk per paragraph, whatever the translations -- and every scaffolded chapter naming the chapter of the other session. The caps do not compete: a chapter of the longest allowed length still proposes with eight translations waiting for it. And no two items across both sessions share nonce material, which is the one thing concurrency could actually get wrong; seeding an item's nonce from its index instead is caught here and by `SignedGroupKeyStateTest`, which already held the within-batch half of it. Not covered: that `AddChapterViewModel` opens the second session, which is plumbing across two dispatchers over templates these tests already pin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
359f54812f |
refactor: give the translation/chapter join one home
TranslationScaffold owns the rows that join a translation to the chapters it is a translation of. Pure refactor: the same events go out in the same order, `TranslationBatchProposalJvmTest` passes unedited apart from the call it makes, and no screen behaves differently. The move is worth making before anything is built on it. A translation chapter carries no words -- it is `(translation, chapter, position)` and nothing else, and it exists so a translated chunk has somewhere to hang. Both of the things it joins arrive on their own schedule: a chapter is signed into an artifact that already has translations, a translation is started on an artifact that already has chapters. So the same cross product has to be built from either side, and a second copy of it is a second chance to disagree about what a translation covers -- a disagreement that shows up as a chapter nobody can translate rather than as anything that looks like a bug. **Over ids, not rows.** `chaptersOf` takes translation ids and a `SourceChapter`, which is a chapter reduced to which one and where it sits, rather than a `MantraChapter`. Neither end is always a row: a translation being proposed exists only as the unsigned event a session is about to sign, and so does a chapter. `SourceChapter.of` is there for the callers that do hold a row. **Two things it decides rather than leaves to a caller.** Item order is apply order, so the nesting is fixed here -- translations outer, chapters inner, which keeps one translation's chapters contiguous and in reading order. And `createdAt` is taken once rather than read per template, so a scaffolding proposed as one act reads as one rather than as events that happen to share a minute. The index is the source chapter's own, never the position in the list handed in. They agree when the list is a whole version in order and stop agreeing the moment a caller holds a subset, and only one of them is what the group signed. **Tests.** TranslationScaffoldTest covers it as the pure function it is: the nesting, both directions it is built from, one timestamp for the lot, the empty cases, and the index surviving a non-contiguous subset. Checked against a broken implementation -- taking the index from the list position passes every test that uses a whole version in order, and is caught by the subset. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
39e5df8253 |
feat: sign a translation into the artifact instead of submitting one
Starting a translation no longer creates one. It opens a signing session over a TranslationArtifactVersionEvent and a TranslationChapterEvent per chapter, and the translation appears -- on every member's device at once, authored by the room's shared key rather than by whoever picked the dialect -- when enough members have signed. The same trade the dialects, artifacts and chapters made: a submission says "I am putting this in front of the group" and the group's only recourse afterwards is social, while a signature is the group saying it and it takes a quorum to say. A translation is what the group's readers will read the work as, so the second is the honest one. **The chapters, in the same batch.** A translation with no chapters is one nobody can start: a translated chunk hangs off a translation chapter, which hangs off the translation. They travel as their own signed events for the same reason the chapter's chunks do since |
||
|
|
2e133dd337 |
feat: sign a chapter and every chunk of it in one session
A chapter proposal now carries the chapter and a chunk per paragraph, and the group signs the lot at once. Every row a member ends up with is signed: a translation is of a chunk, and a chunk that carries the group's signature over its own words can be checked by anybody holding it, rather than only by re-deriving it from the chapter it came out of. This replaces the derivation two commits ago, which split the chunks out of the signed chapter's text on each device and left them as rumors. That was the right shape when a chunk could only have its own signature by having its own quorum. Batch signing removed that, and this is the other side of the trade `MantraChunk.chunksOf` was weighed against. **A batch whose items name each other.** A chunk carries its chapter's id, and that id is a hash over the group's key at the room's derivation path -- neither resolved until the proposal runs. A caller computing it would be recomputing `signingPath`, the one input in this protocol that must never come from a proposer, since the path decides which key the group signs as. So `proposeSigningBatch` gains a second form: a `lead` template, and a `dependents` builder handed the lead *after* it is authored, returning the events that reference it. Every id still comes out of `unsignedEventOf`, which makes an item naming a chapter nobody signed something that cannot be built rather than something to be tested for. `AddChapterViewModel` passes `ChunkEvent::splitOf` and nothing else. The lead is item 0. Items apply in `itemIndex` order and a chunk row whose chapter does not exist yet is a foreign key violation, so what is referenced is signed first as well as named first. **The cost, in front of whoever is typing.** `MAX_BATCH_SIZE` is 64 and the chapter takes one place, so a chapter is capped at 63 paragraphs and a longer one has to be split in two. That is a real limit on real prose. The form counts chunks against the cap as the text is typed, colours the count when it is past, says what to do about it, and will not propose -- because the alternative is an IllegalArgumentException after the fact. The manager still refuses independently; the screen is not what enforces it. **What went away.** `MantraChunk.chunksOf` and the derivation it did inside `ChatMessage.applyInnerEvent`. Chunks arrive as their own signed events now and go through the `ChunkEvent.KIND` branch that was always there. `ChapterEvent` still carries the whole text beside chunks that hold the same words: chunk boundaries are a decision about how to divide the work, and a chapter that kept only the pieces could never be divided differently again. **Tests.** `ChapterChunkSplitTest` covers the split as a pure function -- what each chunk names, counts and carries. `SignedChapterTest` signs a real batch, one FROST instance per item, and checks every chunk row is authored by the room and carries a signature over its own id. `ChapterBatchProposalJvmTest` runs the real proposal against a real database, which is where the sharp edge is: item order, the chunks naming the chapter as the group will author it, and both ends of the cap -- 63 paragraphs proposes, 64 is refused and leaves no session behind. Checked against broken implementations: putting the lead last, naming the wrong chapter, and stamping the chunks off the clock are each caught, in both suites. `jvmTest` runs on linux again as of the merge, which is what made the database-backed test possible. Dropped a nonce-reuse test that was in the first draft of this: it asserted over its own fixture, and `FrostSigningRoundTest` and `SignedGroupKeyStateTest` already hold the manager to giving every item its own nonce. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
e081d14f37 |
refactor: weigh the chapter's chunks against batch signing, and keep deriving
Batch signing landed on mantra while this branch was open, and it makes the argument this change was built on obsolete as written. MantraChunk.chunksOf said the chunks "cannot be events proposed on their own -- that would cost a quorum per paragraph". They can now: proposeSigningBatch would carry the chapter and a chunk per paragraph through one quorum, and every row would hold a signature of its own. Weighed and declined, and the KDoc now says so rather than leaning on a reason that stopped being true. MAX_BATCH_SIZE is 64, which caps a batched chapter at 63 paragraphs and fails an ordinary one outright; the text would go on the wire twice, whole on the chapter and again split across the chunks, and the proposal is the term that cap is sized against; and all-or-nothing over k items would make a long chapter less likely to be signed than a short one, for no reason a member could see. The signature it would buy is redundant besides -- the appendix rejects the manifest shape because an item then needs a lookup to be checked, and here that lookup is a foreign key: a chunk is a pure function of its chapter and cannot be stored without it. docs/frost-batch-signing.md records this under the slot Phase 7 leaves open -- "deciding *what* to batch" -- because the next caller will reach for the same shape. The rule it leaves behind: batch siblings, not derivations. Events that could each have been authored separately are worth a batch; events that are a function of another event in the same batch are worth deriving instead. **The merge.** Only SignedChapterTest broke: the five per-item columns moved off FrostSigningSession onto FrostSigningItem, so it builds an item and calls signedEvent(item, sig), which is how SignedArtifactTest was ported in the same commit. Nothing in the flow itself moved -- proposeSigning kept its signature as the one-event form, and complete() applies each signed event through ChatMessage.applyInnerEvent, so the chapter's chunk derivation works the same whether the chapter arrives alone or as one item of somebody else's batch. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
60abf243ed | Merge branch 'mantra' into claude/add-chapters-frost-signing-c17e64 | ||
|
|
643334afff | Merge branch 'mantra' into claude/frost-batch-signing-435bbb | ||
|
|
1448ed5ad8 |
docs(frost): record batch signing as built, and what rollout needs
Phase 7 of docs/frost-batch-signing.md, which is the phase with no code in it. Nothing needs a feature flag. k=1 is the entire behaviour of the app as shipped -- no caller batches anything yet -- and at k=1 every message is byte-identical to the app before Phase 1: encodeProposal returns the bare event object, joinPayload of one value is that value, and every plural branch in the transcript is only taken above one. The doc now tabulates that rather than asserting it in prose, since it is the claim the whole rollout rests on. The one rollout constraint stands: before a caller batches, the group has to be on a build that understands array proposals. There is no negotiation for it and adding one is not worth it -- an old device refuses an array proposal outright, so the failure mode is a batch that never reaches threshold and is abandoned, visible in the transcript and costing a retry. Also records what is left, which is nothing in the protocol: deciding what to batch is a product question, bounded only by "a batch is only as available as its worst item" and "GroupKeyStateManager.propose must never batch". The phases are kept as written rather than rewritten into a description of the result -- the code reads better against the argument it came from -- with the two places the implementation chose differently (itemIndex over index, DROP COLUMN over a table rebuild) marked in their own sections. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
2309879153 |
test(frost): cover the batch's failure modes and its crypto without a database
Phase 6 of docs/frost-batch-signing.md. 361 jvmTest and 227 testDebugUnitTest pass. ## Inbound path (SignedGroupKeyStateTest) Both drive the manager with a hand-built inner event rather than one the other device queued, which is the only way to be a faulty or dishonest member in this harness. - A one-value nonce offered for a three-item batch does not count towards the threshold: the coordinator never reaches a signer set. The length check is all that stands between a batch and a signer whose contribution lines up against the wrong messages, so truncating or padding would produce partial signatures aggregated against events nobody agreed to. The test then pumps the real nonce and the batch completes -- it is a stall, not damage, which is FrostSignerMessage's composite key doing its job. - A second proposal under the session's own id changes neither its event ids nor its seeds. Every seed is already committed to its item's message; a different batch under the same id would have those seeds produce a second partial signature over a second message, which is how a share is extracted. ## Real FROST, no database (FrostSigningRoundTest) - A k=3 batch from one signer set, all three verifying against the room's key -- the manager's shape with the database taken out of the way. - Item 0's signature does not verify against item 1. Signing three events in lockstep must not make any of them interchangeable. - Both halves of the no-shared-nonce property, because either alone is enough to be relied on by accident: SecretNonce.generate mixes the message in, so one seed under two messages already gives two nonces -- and the manager mints distinct seeds regardless. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
9ac4bcbee3 |
feat(frost): show a whole batch on the signing screen, and say so in the chat
Phase 5 of docs/frost-batch-signing.md. The screen renders every event of a batch, and the transcript says how many there are. ## The approval gate The argument for one approval rather than one per event -- in FrostSigningManager's own header -- only holds if the member can see everything they are agreeing to. Two gates enforce that, and neither touches "Don't sign". - Every event has to be readable. `readable` compares the events that rendered against the items the session holds, so a batch with one unreadable element offers no Sign button at all rather than a Sign button for the ones that worked. A batch is all-or-nothing: agreeing to the two that rendered would be agreeing to the third as well. - A batch's Sign button waits until the list has been read to the end. A batch can hide an event below the fold in a way one event cannot -- what is off-screen is not further detail about the thing on screen, it is a different thing the member would also be signing. Only for k>1: a single event's screen behaves exactly as it did. Declining stays enabled through both. A member who cannot check what they are being asked to sign should still be able to say no, and saying nothing is indistinguishable from a phone in a pocket, which leaves the group waiting. ## Rendering WhatIsBeingSigned takes the list and the count it expects. Each event is still described as the thing it is -- a dialect, an artifact, a chapter -- by the extracted OneThingBeingSigned; the header counts them and the closing sentence about the group's key is said once for the batch rather than once per event. ## Transcript No new ChatMessage types, and no edits to FROST_TYPES, FROST_SETTLEMENTS or FROST_REQUEST_FULFILMENTS -- one line per member per step still describes what happened, whatever k is. Only the wording gains the number, because each of those lines describes work that covered the whole batch: "signed their part of all 3 events", "combined the parts into the group's 3 signatures", "asked the group to sign 3 events". At k=1 every line is byte-identical to before. 356 jvmTest and 224 testDebugUnitTest pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
426e53be9d |
feat(frost): offer batch signing through the repository
Phase 4 of docs/frost-batch-signing.md: the app-facing surface for what Phase 3 built, plus the two rules a caller has to know before reaching for it. FrostSigningRepository.proposeSigningBatch takes a List<EventTemplate<*>> and returns the one session that signs all of them. proposeSigning stays exactly as it was -- AddDialectViewModel, AddArtifactViewModel and GroupKeyStateManager need no edit, and none is made here. Both forms now share one `proposing` helper for the throw-to-null conversion. The reason it exists is unchanged and now covers two more cases: proposing throws when the group has no key, when this device was not in the ceremony, and now when a batch is empty or over MAX_BATCH_SIZE. All four are states the UI is supposed to have checked for, so they become a null the caller reports. ## The two rules, written where a caller will read them A batch is only as available as its worst item. It is all-or-nothing, so if any event cannot be aggregated the session fails and none of them are applied -- which means events that do not belong together should not travel together. A retry is a new batch, never the same one again. A failed batch looks like it has perfectly good nonces going spare; it does not. Every item's seed has already been published against an aggregate, and reusing one would produce two partial signatures over a single secret nonce. proposeSigningBatch mints fresh seeds, so proposing afresh is safe by construction and re-proposing is the only way to get it wrong. GroupKeyStateManager.propose records that it must never be batched: it is the statement every other session in the room is opened against, so bundling it with a dialect would make the room's ability to sign at all depend on that dialect's aggregation succeeding. Per-item partial success stays out of scope -- it would need mixed-state UI, a transcript that can say "3 of 5", and a complete() that applies a subset, for an outcome that indicates a bug or a dishonest coordinator rather than a normal ending. 356 jvmTest and 224 testDebugUnitTest pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
59c34263b3 |
feat(frost): let one signing session carry a batch of events
Phase 3 of docs/frost-batch-signing.md. A session can now be proposed over several events, and the whole batch is signed in one round of four group events with one approval. 356 jvmTest and 224 testDebugUnitTest pass. ## The wire, and the compatibility rule that shapes it FrostSigningEvents.encodeProposal serialises a batch of one as the bare event object it always was, and only a genuine batch as a JSON array. That is not tidiness. A build predating this reads an array with Event.fromJsonOrNull, gets null, and drops the proposal -- so an old device refuses a batch outright rather than signing part of one, while single signing keeps working right through a mixed-version rollout. Emitting an array unconditionally would break every one-event session for those devices and buy nothing. decodeProposal accepts both forms permanently: proposals in the old shape do not stop arriving because this build stopped writing them. It is all-or-nothing -- an array with one unreadable element is refused rather than silently shortened, because the batch's length is what every later payload is checked against, and a proposal that quietly lost an event would have every signer's contribution rejected for being the wrong size: a stall with nothing to blame. ## MAX_BATCH_SIZE, checked twice 64, enforced in proposeSigningBatch and again, independently, in acceptProposal. The second check is the one that matters. A proposal is the only place in this protocol where a remote party decides how much work everyone else does -- k native key generations, k signatures, and a group event carrying k payloads, from a single message -- and until batching that was bounded only by never being more than one. ## acceptProposal over a list Each element is rebuilt from its own fields under this device's own reading of the room's path and checked against the id it claims, exactly as before but per item, and the whole proposal is dropped if any one fails. The write-once rule widens from "the event this session signs" to "the ordered list of events this session signs": a second proposal under the same id whose list differs anywhere is logged and ignored. ## The API FrostSigningManager.proposeSigningBatch(events: List<EventTemplate<*>>) is public here rather than in Phase 4, because without it there is no way to produce a k>1 session and everything above would ship untested. proposeSigning keeps its signature as the one-event form, so no caller moves. Each template carries its own createdAt. ## Tests - FrostProposalCodecTest (new, commonTest): a batch of one is byte-for-byte the old JSON object -- the assertion that stands in for the old build nobody can run here -- plus order preservation, old-form decoding, and refusal of empty, malformed and partly-unreadable arrays. - SignedGroupKeyStateTest: a k=3 batch between two devices over two databases. Three signatures verifying against the room, three dialects applied on both devices in order, five messages from the coordinator and two from the other signer, and one approval line rather than three. - The negative test that matters: no two items of a batch share an aggregated nonce or a seed, and the two devices' seeds do not intersect. Every positive test still passes if two items share a nonce -- the signatures verify fine; what sharing costs is the secret share. - The cap is refused when proposed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
935a8fe37a |
refactor(frost): run a signing session as k FROST instances in lockstep
Phase 2 of docs/frost-batch-signing.md. Pure refactor: proposals still carry one event, the wire is byte-identical, and every test passes unchanged -- 344 jvmTest and 217 testDebugUnitTest, none of them edited in this commit. advance() now loops over FrostSigningItem rows rather than reading the first one. One nonce per item, one aggregate per item, one Session.create per item, one partial signature per item, one signature per item. The signer set, the public shares, the tweak cache and the approval stay shared, because they are the terms that do not enter e = H(R‖P‖m). The coordinator's aggregation is the place where that distinction bites: it builds one AggregatedNonce per item, each from that item's nonce from each chosen signer. Reusing one across two items would be reusing R across two messages. ## The payload codec, early joinPayload/splitPayload land here rather than with the wire change, because at a batch of one a comma join is the identity -- the payload is the bare value it has always been. That leaves Phase 3 to the proposal encoding alone. splitPayload is strict: a payload that is not exactly the batch's length is dropped rather than truncated or padded. It runs in orderedNonces, orderedPartialSignatures and splitForSession -- never in record(), which stores payloads without parsing them so that a nonce can arrive before the proposal that would give it a length to check against. ## Two short-circuits, and one trap in the first advance() runs on every arriving message, so at a batch of k it was k native key generations, k Session.creates and k signs each time, usually to discover there was nothing left to do. - Nonces are generated by `lazy`. The obvious version -- a guard computing `ownNonce == null || (isSigner() && ownPartial == null)` -- is wrong, and wrong in a way that reads fine and fails every signing test: the coordinator settles the signer set further down the same pass, so isSigner() at the top is false on exactly the pass where the coordinator goes on to sign, and the nonces are never generated. Reproduced as IndexOutOfBounds before switching to lazy, which has no prediction to make. - A device that is neither signing nor aggregating leaves before building any FROST session, rather than building k of them to do nothing with. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
dff41d417d |
feat(frost): move a signing session's per-event columns onto FrostSigningItem
Phase 1 of docs/frost-batch-signing.md, which is added here as the plan the next phases follow. Schema only: a session still signs exactly one event, the wire is byte-identical, and every existing test passes on the moved columns. ## What moved, and why it had to A batch of k events is k independent FROST instances sharing a signer set, not one signature over k messages. That is forced rather than chosen: a Schnorr partial signature is `s = k + e·x` with `e = H(R‖P‖m)`, so two messages under one nonce R give two equations in one unknown and the secret share falls out. So the five columns that enter that equation -- unsignedEventJson, eventId, nonceRandom, aggregatedNonce, signature -- move to a child table keyed (sessionId, itemIndex). What stays on FrostSigningSession is everything outside it: the ceremony, the threshold, the derivation path, the signer set, and the one approval. itemIndex is protocol rather than presentation -- nonces and partial signatures are joined positionally against it -- so getItems() orders by it and nothing re-sorts. Spelled itemIndex rather than index to keep hand-written queries free of backticks. No itemCount column. The count is a COUNT(*), for the same reason signerIds is derived from the ceremony's participant order rather than stored: a denormalised count is one more thing that can disagree with the rows. ## Migration 9 -> 10 Manual, not auto: Room can create the table and drop the columns but cannot copy between them, and the copy is the whole point. A session in flight at upgrade holds its nonce seed and the aggregate it is already signing against, and neither can be regenerated -- losing either makes the next pass derive a different nonce for the same message and publish a second partial signature over it, which is the extraction case. Both are copied verbatim into item 0, so an in-flight session resumes as though nothing happened. Removing the columns uses ALTER TABLE DROP COLUMN rather than the usual create-copy-drop-rename rebuild. FrostSignerMessage and FrostSigningItem both reference FrostSigningSession(id) ON DELETE CASCADE, and DROP TABLE fires cascades -- with foreign keys enforced the rebuild would delete every signer message and every item just written. Whether it does depends on Room disabling foreign keys around migrations, which is not worth depending on when DROP COLUMN cannot go wrong. It needs SQLite 3.35 and unindexed, unconstrained columns; these five qualify, and getRoomDatabase pins BundledSQLiteDriver on every platform. ## Invariants established here for the phases that follow - signerIds and every item's aggregatedNonce are one write-once unit, applied by applyAggregate() -- items first in one transaction, then the session, so "some items aggregated" is unreachable and signerIds != null stays the gate. - Signatures likewise, via applySignatures(); isSigned() counts rows instead of reading a flag. - complete() verifies every signature before applying any event, so a batch is all-or-nothing rather than half-filed. - itemsOver() gives each item its own 32 bytes of seed. Independent seeds mean an off-by-one in index handling produces a session that fails to aggregate rather than one that signs two messages under a single nonce. signedEvent() and isAwaitingApproval() now take the item(s) rather than the session, which propagates to the repository, the view model and the screen. advance() reads items.first() and Phase 2 turns that into a loop. ## Tests - FrostSigningSessionDaoJvmTest: index ordering, single-item read, upsert replacing rather than accumulating, signed-item counting, cascade delete. - FrostSigningItemMigrationJvmTest (new): the backfill against a real v9 database, asserting the seed and aggregate values survive -- not merely that a row appeared -- plus the exact column lists Room will check at open time. - 338 jvmTest and 217 testDebugUnitTest pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
eb34c8edb3 |
feat: sign a chapter into the artifact instead of submitting one
Adding a chapter no longer creates one. It opens a signing session over a ChapterEvent, and the chapter appears -- on every member's device at once, authored by the room's shared key rather than by whoever pasted the text -- when enough members have signed. The same trade the dialects and artifacts made: a submission says "I am putting this in front of the group" and the group's only recourse afterwards is social, while a signature is the group saying it and it takes a quorum to say. The text everybody translates from is the group's, so the second is the honest one. **The chunks.** This is the part chapters had that dialects and artifacts did not. A chapter was submitted along with a ChunkEvent per paragraph, and that cannot survive the change: a translation is of a chunk rather than of a chapter, so a chapter without them cannot be worked on, but the chunks cannot have their own quorum without costing one signing session per paragraph, and they cannot be invented locally -- an invented id differs on every device, so members would silently disagree about which chunk a translation is of while every screen showed the same chapter. So the chunks are split back out of the signed chapter's own text when it is applied, in MantraChunk.chunksOf, on the pattern MantraArtifactVersion.initialVersionOf already set. Same bytes in, same rows out, everywhere. They are rumors, because nobody signed them; what the group signed is the chapter they were split from. It splits only what the group signed. A chapter that arrived as a submission was sent with its own chunk events, written under the submitter's key, and deriving a second set beside them would leave every paragraph in the chapter twice under ids nothing reconciles -- including on a marmot reindex, which replays a room's group events without anybody adding anything. **The index.** Where a chapter sits in its version is read at proposal time and signed into the event, rather than derived on arrival like the chunks are. A device applying the chapter cannot recount it: it would be counting a version other members may have added to in a different order, and the count has to be the one the group put its signature to. The window between proposal and quorum is longer than the old write-and-submit window was, so two chapters proposed at once can still land on one index -- the same race as before, wider. **What went away.** MantraDao.addChapter and its way up through the repository. Nothing called it once the screen proposed instead, and leaving a path that authors a chapter under a member's key while the UI insists on a quorum would have double-created the chunks besides. MantraRepository.getChaptersForArtifactVersion replaces the one thing it did that is still needed: counting the index. **The screens.** AddChapterScreen loads the room, the artifact's latest version and canSign up front, disables the FAB when either is missing the way the dialect and artifact screens do, and on success lands on the session rather than on an artifact the chapter is not in yet. FrostSigningScreen described a chapter proposal by name alone, so a member was asked to sign text whose size they could not see; it now reads name, word count and chunk count, the way an artifact shows its url. **Tests.** Two files, and each was checked against a broken implementation rather than only against a working one: deriving the chunks from the clock, inheriting the chapter's counts across every chunk, authoring the derived rows as their reader, and losing the paragraph position are all caught, as is splitting a chapter that arrived as a submission. SignedChapterTest runs a real 2-of-3 quorum over an actual proposal, because the claim worth holding -- the chapter is the group's, carries proof of it, and every device splits it into the same chunks -- is invisible when it breaks. Not covered: applyInnerEvent's upserts, which need a database no test here stands up, and AddChapterViewModel, which is plumbing across two dispatchers over a template the tests already pin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
2089fdf8f0 |
test: cover the ceremony a robust room is created with
|
||
|
|
0c240a31c8 |
feat: open a robust group's key ceremony as it is created
Picking "robust" made a NIP-17 room and left it at that. The quorum the user had just set was read, explained, coerced into range -- and then dropped on the floor, with a TODO where it should have gone saying so: NIP-17 has no group state to change and so nothing to approve, and a different member set is simply a different room. That TODO had an answer the app has been able to give since ChillDkgRitual- Manager landed. The one thing a t-of-n rule can attach to here is a key the members generate together and cannot sign with unless t of n of them are present, and everything a ceremony needs is settled the moment the room exists: who is in it, and how many of them have to agree. So the room now opens one, and the proposal is its first message. ## Why at creation rather than behind the button The button is still there on the shared-key screen, and this changes nothing about it. What it cannot do is be found. A group that picked robust and got a plain NIP-17 room has the thing that makes it robust sitting one unmarked navigation away, and until somebody takes it the group's governance is a number nobody enforces. It is also how the rest of the group hears of the room at all. Standing up a NIP-17 room sends nothing to anybody -- there is no invite, no welcome, no key package -- so before this the first anyone learned of a robust group was whenever somebody happened to type into it. The proposal is now the first event out, and NostrDao already builds the room on the receiving side from a DKG payload's p-tags for exactly this reason. ## The order this runs in The room is created first, then the ceremony is proposed, then the screen navigates. createdChatRoomId is set the moment the room exists, before the proposal, so a second tap reuses that room rather than minting another -- and it is what freezes the type and quorum pickers, both of which are answered by then. Proposing before navigating means the chat opens with the ceremony already in it rather than filling in underneath the user. It costs no round trip: proposeRitual writes rows and queues a gift-wrap payload, and NotaryViewModel seals and broadcasts on its own schedule. The quorum is passed through as the threshold with no coercion. The screen derives its range from the picked members plus the creator, and createNip17ChatRoom stores exactly that set as the room's participants, so the range proposeRitual validates against is the same one the picker was bounded by. ## When the ceremony does not open Nothing is rolled back. The room is real, the group can talk in it, and the ceremony can be opened later from the group's details -- so failing the whole creation would be throwing away the part that worked. But it is not navigated past either. The screen stays put and says what happened, the way it already does when a Marmot group is created without some of its members; the button flips to "Open chat", which is what the user is left with. A robust group quietly without a key is the one outcome here worth interrupting for. ## Elsewhere The robust card's footnote now says that creating the group starts a key ceremony every member takes part in. Members are about to be asked to approve joining it, contributing to the key, and confirming the result, and none of that should be the first they hear of it. MantraNavHost hands the screen the DkgRepository it already builds for the ritual and approval routes; the preview takes the no-op. Left alone: DkgRitualViewModel still cannot read back the quorum a room was created with, because ChatRoom does not persist it. Its threshold picker re-derives a majority default, which now only matters for rooms made before this change or after a failed ceremony. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
de3b355600 |
feat: hand back a room's running ceremony rather than opening a second
proposeRitual minted a fresh session on every call. Nothing called it twice for the same room, so nothing went wrong: the only way in was the shared-key screen, and canStartRitual() returns false while a session exists that has not failed. That is about to stop being true. A robust group opens a ceremony as it is created, and a NIP-17 room id is derived from its member set -- so making the same group again returns the same room and asks it again. The guard also sat in the wrong place regardless: on an observed UI snapshot, a screen away from the write it was protecting. ## What a second proposal costs It is not a duplicate row. ChillDKG hashes the participant set and the threshold into the session identity, so a second ceremony over the same room is a second `n` and `t` for every member to reconcile, and members join whichever proposal reaches them first -- relays hand gift wraps back in no particular order, so which one that is differs per device. The group ends up split across two ceremonies, neither of which can assemble the participant count it needs. Worse if the first one had finished. FrostSigningManager.completedKey falls back to getLatestSessionForChatRoom when the room has no signed key state and its id is not derived from the threshold key; a newer, unfinished session shadows the completed one there, and the group stops being able to reach the key it actually holds. ## The rule, and where it now lives The room's live ritual is returned as-is, so a caller gets a session either way and cannot tell whether it opened one. That is what makes the creation path safe to re-enter. The rule itself is unchanged -- it is the one canStartRitual() has always applied, right down to which stages block. It now also lives next to the write, where a stale snapshot cannot race it. FAILED is excluded deliberately: it is the one stage that does not hold the room's slot. A collapsed ceremony leaves the group with no key and a room they can still talk in, which is exactly the group that should be able to try again. Every other stage, COMPLETE included, is a ceremony the room depends on the outcome of. Checked before the require()s rather than after. A running ceremony settled the threshold question when it opened, so validating the argument would be validating an input with no effect -- and it would turn re-entering with a different quorum into an exception instead of the ceremony that exists. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
a805455df8 | Merge branch 'mantra' into claude/groupkeystate-frost-proposal-206090 | ||
|
|
44127cf514 |
test: exercise MarmotOutboundDao past the MLS guard
|
||
|
|
ed7a866421 |
test: run a real signing session between two devices, over two databases
|
||
|
|
5fa0d08dfd |
test: cover nip17 room derivation and its preconditions
A NIP-17 room has no MLS group, no key packages and no invites -- membership *is* the p-tag set on each message. Two things follow, and both are load-bearing. The room id is deriveChatRoomId over the member set, the same aggregate the inbound path derives from an arriving gift wrap. That is what makes creation idempotent, and idempotence here is not a nicety: two people starting the same conversation have to land on one room, or the thread exists twice with each side writing into its own copy and neither seeing the other. Covered from three angles -- the order members are named in does not change the id, creating the same conversation twice reuses the room as it stands rather than rewriting it, and a different member set derives a different room. The order-independence test is guarding `deriveChatRoomId`'s own `.sorted()`, not the DAO's `.toSet()`, and its comment now says so. That was established by mutation rather than assumed: rebuilding the member set as an order-preserving LinkedHashSet in the DAO changes nothing, because the derivation sorts anyway, while removing the sort fails the test. The distinction matters for anyone reading the DAO and concluding the set is what does the work. And `mlsGroupState = null` is what marks the room NIP-17. sendChatMessage reads exactly that field to choose between a kind:445 group event and per-recipient gift wraps, so a room that acquired MLS state would have its messages routed down a path no recipient is running. Covered alongside: the creator is a participant of their own conversation even when not listed among the participants -- sealGiftWrapPayload walks that list to decide who to wrap for, so omitting the creator would send messages every other member could read and the sender could not -- and naming the creator among the participants does not produce a second row for them. One test records a precondition and an asymmetry. Participant.participantPublicKey is a foreign key onto Profile, so createNip17ChatRoom raises a SQLite constraint failure for a member this device has no profile for, while getOrCreateChatRoom, one method down, answers the same "never seen this user" situation by returning null. A caller treating the two alike gets an unhandled exception out of the first. That was found by writing the tests -- seven of them failed with SQLite 787 before every member was seeded -- and is pinned rather than seeded around silently. The remaining getOrCreate coverage: it returns the room already stored rather than overwriting it with the defaults passed in, stands one up for a user it has a profile for, and writes nothing at all when it does not. Real secp256k1 keys throughout, because deriveChatRoomId does point arithmetic and treats an off-curve value differently from a valid one -- hex filler would exercise a path users never reach. 11 tests. composeApp jvmTest is 309 tests, 0 failures. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
8a6cb81bf9 |
test: cover the FROST signing session state
The signing counterpart to the DKG coverage, and it differs in the way the DAO's own comment gives: "unlike a DKG a group signs repeatedly, so there is no single current one to observe". Sessions accumulate rather than replacing each other, which makes room scoping and ordering load-bearing rather than incidental. The duplicate-suppression property is the same and matters for the same reason. The composite key (sessionId, signerPublicKey, kind) is what makes a redelivered nonce or partial signature replace its predecessor rather than add a row, and countMessagesByKind is what decides that enough signers have answered. A second row for one signer lets a session cross its threshold while short a real participant, and the aggregation then runs over a signer set that was never assembled. Covered by resending a nonce with a different payload, and separately by giving one signer both a nonce and a partial signature and asserting the second does not overwrite the first -- the kind in the key is the only thing keeping those apart. Also covered: a session reads back by id with its stage intact and a missing id gives null; a room's sessions accumulate newest first, with the latest reachable on its own; sessions are scoped to their room, which matters because signing happens in the #admins room and a device can be in more than one -- a session leaking across would have a signer answering a request its group never made; counts are per session and per round; and a completed session keeps its signature, which is what a resume reads to avoid signing the same event twice. One test records a difference rather than a guarantee. FROST orders a round's messages by createdAt where the DKG orders the same query by participant public key. Arrival order is per-device, so this ordering is not canonical across the group the way the DKG's is. It is pinned as it stands rather than asserted to be right: whether it is deliberate is not something this change can settle, and a caller that needs a canonical signer order has to impose one itself. Worth looking at separately. 8 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
168d16c933 |
test: cover the DKG ritual state a ceremony is resumed from
Two properties here decide whether a ceremony can finish, and the compiler sees neither. A participant gets one message per round, and that is enforced by the composite key (sessionId, participantPublicKey, kind) rather than by any code that writes to the table. Rounds advance on countMessagesByKind reaching the participant count, so a redelivered message that added a row instead of replacing one would let the count reach the threshold while a member had still never been heard from -- and the ritual would proceed on a participant set it never assembled. Covered by resending a participant's message with a different payload and asserting the count stays at one and the payload is the newer of the two, and separately by writing the same participant into two different rounds and asserting neither overwrites the other. A key-holding session needs both halves. thresholdPublicKey without secretShare is a ceremony that produced a group key this device cannot sign against; secretShare without thresholdPublicKey is a share with no key to sign for. Either alone is a failed ceremony, and offering it up as a signing key means attempting to sign with half a result. Covered with all four combinations present in the table at once, asserting only the complete one comes back. Also covered: the live ritual for a room is the newest, because a group may have abandoned earlier attempts and a resume that picked up an abandoned one would wait forever on participants who have moved to the newer; rituals belonging to another room are not offered as this room's; key-holding sessions come back newest first; and messages are counted per session and per round rather than across either. And the ordering, which is the one with a reason beyond tidiness: a round's messages come back ordered by participant public key, not by arrival. Every device has to assemble a round in the same order to compute the same thing, and arrival order is per-device. The test writes three participants in an order deliberately unlike the sorted one. Real secp256k1 keys throughout rather than hex filler, since these are the values a canonical ordering is defined over. Verified by mutation: relaxing the key-holding predicate to `OR` returns all three of the incomplete sessions and fails that test; reordering the round query by createdAt fails the canonical-order test. Both mutations were reverted; no production source is touched by this commit. 8 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
a8f6638325 |
feat: sign a room's key state into being, at the room's own key
Two changes that turned out to be one. A room's key state stops being something its creator announces and becomes something the group signs, and every FROST signature moves from the group's root threshold key to the key derived at the room's own path -- which is the room's id. The second is what makes the first worth having: a key state is now signed by the very key it names. Supersedes the announcement introduced in |
||
|
|
baecb76253 |
test: cover the query a marmot reindex decides its work from
getResolvedMarmotGroupEventIds is what a reindex sweep subtracts from a room's stored group events to decide what to replay, so its answer decides what work the sweep does -- and both ways of being wrong are silent. Report an event as resolved when it is not, and the replay skips the one event that needed it: the message stays missing from the feed with nothing left to trigger another attempt. Report it as unresolved when it is resolved, and every sweep re-decrypts it forever. The whole distinction rests on `messageType NOT IN (:unresolvedTypes)`, where those types are the two placeholder lines that stand in for a message still to come rather than reporting one. Covered: an event with a real line is resolved; an undecryptable outer layer and a pending commit each leave their event unresolved, which is right because those are precisely what a replay exists to retry. Then the subtraction itself, since that is how the caller uses it -- three events, one settled, one holding a placeholder, one with no line at all, and the sweep left with exactly the last two. Covered because the query says so and nothing else would: `marmotGroupEventId IS NOT NULL` keeps out lines that are not about a group event -- a NIP-17 direct message, a locally written line -- which would otherwise carry nulls into a set the sweep subtracts with. And the room scoping, since a sweep runs per room and another room's resolutions must not shorten its work. Covered last, and it is the transition the sweep exists to cause: a placeholder upserted in place into a real line resolves its event, visible through this same query. Two smaller ones alongside: the single-row lookups order newest first, which is what makes them "the line for this event" rather than whichever row sqlite reached first, and the per-sender count is scoped to its room. Verified by mutation: defeating the messageType exclusion so placeholders count as resolved fails five of these, including the subtraction test. The mutation was reverted; no production source is touched by this commit. 8 tests. composeApp jvmTest is 282 tests, 0 failures. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
521a4f5690 |
test: pin the epoch secret retention window
A retained epoch secret is what lets a member read a message sent under an epoch the group has since moved past. Both ways of getting the policy wrong are quiet: keep too few and old messages become permanently unreadable, keep too many and secrets that should have been dropped stay on disk. The entire policy is one strict `<` in a query and an IGNORE on an insert. The cutoff is strict, and that matters more than an off-by-one usually does. This query feeds a delete, so an epoch wrongly reported as droppable is not a stale read -- it is the messages of that epoch becoming undecryptable, with nothing to recover them from. Covered with three epochs either side of the boundary: only strictly older ones are droppable, the epoch equal to the cutoff is still inside the window, and a cutoff at or below every retained epoch drops nothing. Room scoping, for the same reason. Rooms advance epochs independently, so a sweep driven by one room's cutoff must never reach another's -- a leak here costs the other room its history. Asserted from both ends: the sweep returns only the sweeping room's rows, and the other room's secret is still there afterwards. Insert is IGNORE over the composite key (chatRoomId, epoch), which is what makes re-processing a commit safe. A redelivery or a replay re-derives the secret, and overwriting the stored one with that re-derivation would replace the value that actually decrypts the messages already on disk. Covered by inserting a second, different secret for the same epoch and asserting the first survives -- and alongside it, that the same epoch number in two different rooms is two rows rather than a conflict, since the composite key is what separates them. Also covered: defenestrate removes exactly the rows the sweep selected and leaves the rest, and a room's retained epochs are all readable back, which is what a rejoin or a full replay reads before deciding what it can still decrypt. Verified by mutation: relaxing the cutoff to `epoch <= :epochCutOffPoint` fails three of these, including the boundary test. The mutation was reverted; no production source is touched by this commit. 7 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
d355b68355 |
test: cover the outbound broadcast queue and its stale sweep
Nothing else drains BroadcastNostrEventRequest, so a row this DAO fails to hand back is an event that never reaches any relay -- and the failure is silent, because a queue returning nothing is indistinguishable from an empty one. That already happened. The observer's predicate carried a `createdAt > :now` bound whose `now` was evaluated once, when the Flow was built. Instants persist at second resolution, so it hid every broadcast enqueued during the observer's own start second -- the entire profile-creation burst -- plus everything a previous session had left pending. There is a test here for exactly that shape: a row enqueued before the observer existed has to come back. The stale sweep, which is the other half of not losing events. A request is flipped to "processing" before a publish is attempted, and a timeout or a dropped socket leaves it there; nothing observes "processing" or "failed", so those rows are dead weight until the sweep requeues them. Covered: both stale statuses flip to "pending" and are counted; a row already pending is not touched, so the returned count is not inflated by work that was never stale. Covered separately, because it is the reason the sweep is bounded at all: a row newer than the cutoff is left alone. A publish running right now holds its row in "processing", and requeueing that would hand the same event to a second publish while the first is still in flight. The bound is `<=`, so a row stamped exactly on the cutoff second is swept -- asserted, since that is the boundary the second resolution of these timestamps makes common rather than rare. Also covered: the queue drains oldest first; a "processing" row is not handed out as pending work; and getFirstBroadcastNostrEventRequestByNostrEventId returns the oldest of an event's per-relay rows rather than the only one, since an event is queued once per target relay. One test is deliberately kept despite not being able to fail, and says so in its own comment. `requests sharing a timestamp drain in insertion order` pins the observable order of a same-second burst, which is what callers depend on -- but deleting the `, id ASC` tiebreak leaves it passing, because `id` is an autoGenerate primary key and therefore the rowid, so sqlite's unspecified ordering already coincides with it under this plan. That coincidence is the argument for keeping the explicit tiebreak rather than against it: it is not contractual, and an index or a different plan can change it. Recording the limit in the test seemed better than implying a guard that is not there. Verified by mutation: reversing the drain order fails the oldest-first test. Removing only the tiebreak fails nothing, which is how the limitation above was found rather than assumed. Both mutations were reverted; no production source is touched by this commit. 9 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
02e70d992a |
test: cover the MarmotOutboundDao membership guards
Both entry points that change a group's membership start by restoring the MLS state off the ChatRoom row, and a room restored from an inbound gift wrap has none -- there is nothing to add a member to. The comment on inviteMemberToChatRoom says the throw exists to "say so instead of silently doing nothing and letting the caller report success", which is a claim about behaviour and therefore something a test can hold to. A guard that returned quietly would still compile, still look like it worked, and leave a room whose members believe someone was invited who was not. Covered: inviteMemberToChatRoom and addMembersToChatRoom each raise MarmotMissingChatGroupException against a room whose mlsGroupState is null, which is exactly the shape a gift-wrap-restored room has. Covered separately, because ordering is the substance of it: a refused invite leaves no Participant row behind. The guard has to run before that write, not after. sealGiftWrapPayload walks a room's participants to decide who to wrap a Welcome for, so a participant persisted by a failed invite would make the room look like it has a member no MLS group knows about -- and the next Welcome would be sealed for them. Covered last: the empty-batch guard returns before the MLS state is looked at, so addMembersToChatRoom with no peers must *not* throw on the same stateless room the other two tests reject. Adding nobody is not a failure to add somebody, and pinning that keeps the two guards from being collapsed into one. Deliberately not covered, and the test file says so rather than implying the DAO is done: everything past the guard -- the MLS commit, the Welcome, the epoch advance and persisting it back to the room -- needs a real peer key package, which means an MLS fixture this change does not build. That gap includes the batching rationale on addMembersToChatRoom, which is the more interesting property of the two: one commit and one Welcome so no member ever has to process a commit for an epoch they were not yet in, since MarmotInboundManager refuses future-epoch messages outright with no queue and no replay. Worth covering once there is a fixture to build a key package with. The MarmotKeyPackage these tests pass carries an empty byte array, which is honest: no test here reaches the MLS layer, so the bytes only have to exist. A test that got past the guard could not use it. 4 tests. composeApp jvmTest is 258 tests, 0 failures. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
ba0c60dd2e |
test: cover the NostrDao event funnel and the publish durability split
NostrDao is what every event passes through, inbound and outbound, so its two decisions carry everything downstream: which of two copies of an event wins, and what survives when the enrichment after a write fails. Both were described in comments and neither was asserted. Deduplication, at all four positions. A first sighting is stored. A strictly newer copy replaces the stored one. An older copy is ignored. And -- the case that actually distinguishes the implementations -- a redelivery carrying the *same* timestamp is a no-op, because the comparison is a strict `>`. That last one is not hypothetical: relays redeliver and negentropy re-syncs, so the common case is the same event arriving again unchanged, and a `>=` there would rewrite the row on every delivery. The publish durability split, which is where a bug shipped. `commitPublishedNostrEvent` is the durable half -- mark the unsigned row signed, store the event, queue a broadcast per relay -- and indexing is best-effort enrichment that runs in its own transaction. They used to share one, so any throw in indexing rolled back `signedAt` too. Because the notary drains one unsigned row at a time, that row was then re-selected forever and every event queued behind it went unsigned, including the MLS key package that is enqueued last. The test provokes the failure the way the code itself would fail: publishing with no target relays reaches `relayURLs.first()` inside the try and throws. It then asserts `signedAt` and the stored event both survived. The happy path is covered alongside it, asserting a broadcast request per target relay, so the durability test cannot pass by publishing nothing at all. Also covered: an event from an author with no profile leaves a "LOADING..." placeholder stamped GENESIS_AT rather than nothing, since that row is the only record that the pubkey was seen and needs fetching; and rescheduleBroadcastNostrEventRequests re-queueing a broadcast and re-linking it to the chat line when the event is a group message that has one, without inventing a relation when it does not. One test began as a wrong assumption and the schema corrected it. The "no chat line" case was first written against an event id that had never been stored, and failed with SQLite 787: BroadcastNostrEventRequest.nostrEventId is a foreign key onto NostrEvent. So the real invariant is that a broadcast cannot be scheduled for an event the caller has not saved; the test now stores the event and leaves only the chat line missing, and says so in a comment rather than quietly seeding around it. Verified by mutation: relaxing the dedup comparison to `>=` fails the same-timestamp test; removing the try/catch around indexing so the throw propagates fails the durability test. Both mutations were reverted; no production source is touched by this commit. Uses `runBlocking<Unit>` on the durability test because its last expression is an assertNotNull, and a test method that returns a value is rejected by the JUnit4 runner outright. 9 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
36a98c5928 |
test: pin the nip30303 store-and-submit invariant in MantraDao
Every `add*` on MantraDao does two things in one transaction: writes the entity and queues a SubmissionEvent carrying the same nip30303 event for the group. The part worth asserting is the one `rumorOf` exists for. An entity's id is computed by its `Mantra*.from*EventTemplate` factory. The payload's id is computed separately, in `rumorOf`, from the same template. The two are meant to produce the *same event* -- the row on disk and the payload on the wire, not two copies of one. Nothing enforces that: the factories live in different files, both compile independently, and both produce a plausible 64-character id. A divergence would surface only as a group that receives a submission whose payload matches nothing it can find, which is a long way from the two hash calls that disagreed. Covered, through the seam rather than by recomputing the hash: the submission records `payloadEventId`, and that value has to equal the id of the entity the same call returned. Asserted for a dialect and again for an artifact version, because store-and-submit is the convention every `add*` follows rather than something addDialect does on its own -- and the second one goes through the full foreign key chain, dialect then artifact then version. Also covered: The envelope is not the payload. A submission's own id is the SubmissionEvent's and must differ from the payload's, which is exactly why `deleteByPayloadEventId` exists -- a superseded nip30303 event cannot be un-queued by its own id, and if the two ever collapsed to one value that method would start deleting envelopes by accident. The submission is queued unprocessed, `marmotGroupEventId == null`. That null is what the outbound pipeline selects on to encrypt the row into a kind:445. Filed as processed it would be stored and never sent, and the group would simply never learn about the dialect while the local device showed it as added. A ChatMessage line is written, since the room's feed reads ChatMessage and an added entity that leaves no line is invisible to everyone including its author. Verified by mutation rather than assumed: making `rumorOf` hash a createdAt one second off the template's fails both invariant tests, with the ids compared in the failure output. The mutation was reverted; no production source is touched by this commit. 6 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
20d2547a34 |
test: cover the hand-written NostrEventDao queries against sqlite
Two of these queries carry a comment describing a bug that already shipped, and neither bug was the kind anything catches by running: a wrong WHERE clause is still a valid query returning a plausible list. Both corrected predicates are now pinned, so the next edit has to argue with a failing test rather than with a comment. getMarmotGroupEvents. The predicate used to read `expiresAt < :now`, which kept exactly the expired events and dropped every live one -- for the whole group-chat sync path the set handed to negentropy was the complement of the relay's. Covered with four rows at once: no expiry at all (always served), an expiry in the future (still served), an expiry in the past (gone), and an expiry landing exactly on `now`, which the strict `>` excludes. Also covered: the inclusive since/until bounds using events stamped on each bound, room membership filtering across two rooms, and newest-first ordering with a limit keeping the newest window. getMarmotGroupNostrEventsByChatRoomId. Ascending order, because a replay has to apply commits in the order they were sent and this is the one query in the DAO that deliberately orders that way. The test that matters most here is that an event which never reached the MarmotGroupEvent table is still returned -- that is the whole reason the query reads NostrEvent instead of joining the index, since an event whose indexing failed part way is precisely what a replay exists to pick up, and a join would skip exactly those rows. Asserted from both sides: the un-indexed event comes back from the replay query and is genuinely absent from getMarmotGroupEvents. The same query's LIKE over-match is pinned deliberately rather than asserted away. The DAO's comment calls it a prefilter and puts the burden on callers to confirm the event's own `h` tag, so a room id sitting in an `e` tag is expected to come back. Recording it in both directions means anyone tightening the query knows a caller may rely on the loose behaviour, and anyone loosening a caller's check knows why it was there. Also covered: getNostrEventByPublicKeyAndKind returning the newest row, which is what makes it correct for replaceable events rather than a coin flip; and the difference between the two write paths, where `insert` with IGNORE keeps the stored event -- correct when re-receiving an immutable event from a second relay -- while `upsert` overwrites it. Last, the paged reads are pinned as treating `since` exclusively, which is what makes them safe to call in a loop with the previous page's last timestamp as the cursor. That sits one query away from the inclusive bound in getMarmotGroupEvents on purpose: the two conventions are genuinely different, and a reader who assumes either holds throughout gets a skipped row or a loop that never advances. The expiry test was checked by mutation rather than assumed: restoring `expiresAt < :now` fails it alone, with "an event expiring in the future is still live". The mutation was reverted; no production source is touched by this commit. 11 tests. composeApp jvmTest is 239 tests, 0 failures. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
5623df530c |
test: execute the nostr filter query against real sqlite
NostrEventFilterQueryTest pins the SQL string the builder produces. It never runs that string, and the gap between "the SQL reads correctly" and "sqlite returns the right rows" is where this query's expensive mistakes live. Four classes of bug survive a string assertion intact, and all four are covered here. SQL that is well-formed but not accepted. The clause emitted for a present-but-empty list is the bare literal `0`. Whether sqlite takes that as a false boolean expression rather than rejecting it is not something the builder test can answer; ids, authors, kinds and tags are each asserted to match nothing when handed an empty list. Binding indices. The limit is bound after every tag pattern, so its placeholder is the last in the statement. A drift in that order produces a byte-identical SQL string and different rows, so it is covered by a filter that carries authors, kinds, since, until, search, a tag and a limit at once. LIKE semantics against the column as actually written. The tag pattern is a fragment of the encoded tag -- `["p","<hex>"` -- and only real stored JSON can show that it anchors on the tag name (a pubkey in an `e` tag is not a `p` match, which is exactly the regression the substring scan `tags LIKE '%<pubkey>%'` caused), that it tolerates the relay hint and marker that follow a real tag value, and that escapeLike keeps a `%` in a tag value literal instead of widening the match. Timestamp units. This is a cross-file invariant nothing enforces: NostrEventFilterQuery binds since/until as epochSeconds, and MantraConverters.instantToTimestamp writes the createdAt column as epochSeconds. They agree today. Move either to milliseconds and both files still read correctly on their own while the filter silently selects nothing or everything, so the agreement is now asserted directly. Also covered: the NIP-01 inclusive bounds on both ends, using events stamped exactly on since and on until -- the case that tells an inclusive bound from the strict `createdAt > :since` this replaced; tags ORing values within a name and ANDing across names, against tagsAll which ANDs within a name too; newest-first ordering with the `id DESC` tiebreak, and a limit keeping the newest rather than the oldest window the per-shape queries used to return. Three of these were checked by mutation rather than assumed. Reverting the tag pattern to the naive `%value%` substring fails `a tag value is matched in its own position`; relaxing `createdAt >= ?` back to `>` fails both the inclusive bounds test and the units test. The mutations were reverted; no production source is touched by this commit. 14 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
9c50b4fcee |
build: advance lightning-kmp-app onto the jvm target test coverage
Moves the pin from 05ce7eb to 01489b8, five commits on the submodule's master:
one fix and four test files covering the jvm target the previous pin move
restored.
The fix is a branch-ordering bug in defaultApplicationDir. It matched os.name
against "win" before "mac"/"darwin", and "darwin".contains("win") is true, so a
darwin os name resolved to AppData/Local/phoenix rather than
Library/Application Support/phoenix. Nothing a stock JDK reports is affected --
macos says "Mac OS X" -- but that directory is what SeedManager resolves
"node-data" against, so the failure mode was a node seed written where no
correctly resolving run would look for it.
The tests take the jvm target from 3 test files to 7, adding 31 tests over the
directory contract and os layout of PlatformContext, the seed-decryption
exception mapping in TechnicalExtensions, the NetworkMonitor start/stop
lifecycle that AppConnectionsDaemon gates every connection on, and the
platform-specific one-line actuals. The submodule's jvmTest suite is 128 tests,
0 failures, 3 skipped -- the skips being the pre-existing @Ignore'd
ElectrumServersTest, which is a manual check against live servers.
No composeApp source changes: this is submodule coverage only, and the pinned
library's public surface is unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
||
|
|
f600c9f87a |
build: pin lightning-kmp-app back to the jvm-target branch
Restores the pin to 05ce7eb, the tip of `claude/jvm-target-actuals`, undoing
|
||
|
|
a00fc1775c |
build: pin lightning-kmp-app to master instead of the jvm-target branch
The submodule was pinned at 05ce7eb, the tip of `claude/jvm-target-actuals`. Move it back to 6434282, the master tip it branched from, which carries the AGP 9.4.0 / jni-android substitution work but none of the jvm actuals. Dropping those four commits from the pin removes the library's jvm target (BusinessManager, the jdbc DbFactory, JvmKeyStore, the polling NetworkMonitor and their tests). The jvm work is not lost -- it stays on `claude/jvm-target-actuals`, pushed to origin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
af81933ab4 |
Merge branch 'mantra' into claude/room-db-testing-setup-b053cd
Brings the branch up to date with the 40 commits mantra gained while the jvm target was being built, so that merging the other way is a fast-forward. One conflict, in docs/README.md, where both sides added rows to the index table. Kept both, and gave the jvm-target note a clause in the closing prose since it is the one document there that is not about the protocol. One thing the auto-merge could not have caught. `9250991` added NostrEventDao.getMarmotGroupNostrEventsByChatRoomId as a blocking query, which android accepts and which Room refuses to generate for any other target -- so the merged tree failed :composeApp:compileKotlinJvm with the same "Only suspend functions are allowed in DAOs declared in source sets targeting non-Android platforms" that phase 4 dealt with 58 times. Made suspend; its only caller, NostrDao.reindexMarmotGroupEvents, was already suspend, so again no cascade. That is now a standing cost of this branch rather than a one-off: any DAO method added on mantra while this is outstanding will break the jvm build on merge. It is a one-word fix each time, and the compiler names the line. Verified on the merged tree: :composeApp:compileKotlinJvm and :composeApp:compileDebugKotlinAndroid green, :composeApp:testDebugUnitTest 208 passing, :composeApp:jvmTest 214 passing -- both test tasks re-run from scratch rather than taken from the cache. The jvm figure is larger than the android one because jvmTest inherits commonTest, so declaring the target quietly gained the whole shared suite a second execution environment. That is worth knowing independently of whether desktop ever ships: the same tests now run on the host, without an emulator. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
607ef72bc3 |
Merge branch 'mantra' into claude/marmot-group-reindex-events-96a0d0
# Conflicts: # composeApp/src/commonMain/kotlin/press/mantra/compose/database/dao/NostrDao.kt # composeApp/src/commonMain/kotlin/press/mantra/compose/database/model/ChatMessage.kt |
||
|
|
925099125b |
feat: read a room's group events again when they arrived out of order
Relays impose no ordering, so a kind:445 can turn up before the group can read it: an application message encrypted under an epoch whose commit has not landed, or a commit for an epoch ahead of the local one. Both are stored and then dropped -- MarmotInboundManager refuses an out-of-epoch commit precisely so it does not half-mutate the group -- and nothing goes back for them once the missing event fills the gap. The message is on disk, readable, and never read. A "Reindex Events" button at the bottom of the group's detail screen is that second look. Only events with nothing to show for them are replayed: no chat line at all, or one of the two placeholder types. A room where nothing went wrong is left exactly as it was, which is what makes the button safe to press on a hunch. Passes repeat while a pass recovers something, because created_at order is not epoch order and a commit recovered by one pass is what lets the next read the messages that were waiting on it. **Replaying was not safe as it stood.** Every row the path writes is keyed on an event id and upserts in place -- MarmotGroupEvent, MarmotInnerEvent, and the nip30303 entities -- with one exception. ChatMessage's primary key is autogenerated, so writing a freshly built line always inserts, and a re-read would have left the room showing each recovered message twice, once as "Undecryptable Message" and once as itself. ChatMessage.reconcileMarmotLine matches on the group event id instead, so a re-read is an update, and refuses to let a placeholder overwrite a line that says something. That last rule is what protects the line this device wrote on the way out for a message it sent: our own kind:445 cannot be read back, since the sender ratchet has consumed the generation, and without the rule a replay would have replaced our words with "Undecryptable Message". The MLS group itself was already safe to replay against, which is worth saying because it is the part that looks dangerous: a commit behind the current epoch is rejected as a duplicate before it touches the group, one ahead is refused, and a consumed ratchet generation throws before mutating anything. The exception was quartz's EpochCommitTracker, which does not dedupe and only empties when a commit applies -- so replaying a held commit just grew the list and left it pending forever. forgetPendingCommits drops the room's entries first, and the sweep feeds the events back in the order CommitOrdering picks a winner in, so a contested epoch resolves the same way it would have on every other device. **What is testable, and what is not.** The DAO is not: testDebugUnitTest is plain JVM and Room's in-memory builder wants an Android Context. So the two pieces carrying decisions are lifted out where they can be run without one -- MarmotReindexSweep for the stopping rule, and reconcileMarmotLine for which of two lines wins -- and the DAO is left as query, sweep, write. The filter tests pin why the query's `tags LIKE` is a prefilter and not a test: an event belonging to another room can mention this one in a q tag, and its own h tag is what rejects it. **Not recovered by any of this.** A message whose key is gone -- one the ratchet has already advanced past, or one from an epoch predating this device's join. And events that never reached disk at all: storeNostrEvent is a single transaction, so a kind:445 arriving before its room exists rolls back its own insert along with the failed indexing, and only a re-sync brings it back. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
6aff34c5c7 | Merge branch 'mantra' into claude/artifact-frost-signing-proposal-a414f6 | ||
|
|
786c0602da |
feat: sign an artifact into the library instead of submitting one
Adding an artifact no longer creates one. It opens a signing session over an ArtifactEvent, and the artifact appears -- on every member's device at once, authored by the group's shared key rather than by whoever typed it -- when enough members have signed. The same trade the dialects made: a submission says "I am putting this in front of the group" and the group's only recourse afterwards is social, while a signature is the group saying it and it takes a quorum to say. A library is the group's. **The first version.** This is the part the dialect had no answer for. An artifact was creating an initial ArtifactVersion as a second submitted event, and that cannot survive the change: a chapter attaches to a version rather than to an artifact, so an artifact without one is inert, but a version cannot be submitted before the artifact it points at exists, cannot have its own quorum without costing a second signing session per form, and cannot be invented locally -- an invented id differs on every device, so members would silently disagree about which version a chapter hangs off while every screen showed the same artifact. So the label rides on the artifact as an `artifactVersion` tag and the row is derived from the signed artifact's own fields when it is applied. Same bytes in, same row out, everywhere. It is a rumor, because nobody signed it; what the group signed is the artifact that declares it. **What went away.** MantraDao.addArtifact and its way up through the repository. Nothing called it once the screen proposed instead, and leaving a path that authors an artifact under a member's key while the UI insists on a quorum would have double-created the version besides. **Tests.** Three files, and each was checked against a broken implementation rather than only against a working one: deriving the version from the clock, dropping the label from the proposal, authoring the derived row as its reader, and losing the signature on the way out of the session are all caught. SignedArtifactTest runs a real 2-of-3 quorum over an actual proposal, because the claim worth holding -- the row is the group's, and carries proof of it -- is invisible when it breaks. Not covered: applyInnerEvent's two upserts, which need a database no test here stands up, and AddArtifactViewModel, which is plumbing across two dispatchers over a template the tests already pin. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
adf1f03817 |
feat: a desktop entry point, and the first code here that runs
Phase 5. `press.mantra.desktop.MainKt` has been named by the compose.desktop block since before this work started and did not exist; now it does, and `./gradlew :composeApp:run` opens a window. **The window opens onto a passphrase gate, not onto the app.** That is phase 3 landing here rather than there, and it was not in the plan. keyStoreEncryption(keyName, plainText) takes no secret, because on android the OS keystore serves keys without asking anybody anything -- so a passphrase scheme needs an unlock the expect signature cannot express. MainKt calls JvmKeyStore.unlock before MantraApp is composed, off the ui thread, because Argon2id at 64 MiB is deliberately slow enough to stop the window painting. The gate says on its face that this build is not for real funds. One application directory is handed to both the mantra and the phoenix context, so a single install keeps a single place on disk rather than two named after different projects. **MantraDatabaseJvmTest is the part worth keeping.** Running the app proves the window paints; it proves nothing about Room, because the gate stops before anything touches the database. Six tests now open it: the schema is created, a profile survives a write and a read, upsert replaces rather than duplicates, the @Transaction relation query behind findChatRoomById reads back, a soft-deleted room stops being found, and the on-disk builder writes under the context directory rather than java.io.tmpdir. This is the first time this database has been opened anywhere but android, and it covers exactly what the compiler cannot see -- that Room's ksp output for this target is usable, that the *host* SQLite native loads where the android artifact's would not, and that the 58 queries forced from blocking to suspend still return what they stored. Both of that test's first drafts were wrong in ways worth keeping the scars of. Every write failed with SQLite error 787 because Profile has a foreign key onto NostrEvent and the test never created the parent row -- which is evidence rather than an annoyance, since a schema whose constraints were quietly off would have let all of it pass. And Kind is a typealias for Int, not a constructor. Window sizing is 480x900: a starting size that does not immediately misrepresent layouts only ever exercised at phone widths, not a considered desktop layout. That, along with back handling and any ui offering an nfc affordance, is the shakeout this phase names and does not do. Verified, all five green: :composeApp:compileKotlinJvm, :composeApp:compileDebugKotlinAndroid, :composeApp:testDebugUnitTest (52), :composeApp:jvmTest (6), and the fork's :library:jvmTest (97). Not verified: nothing past the gate. No seed has been written, no business started, no relay contacted. A gradle `run` killed with SIGTERM reports BUILD FAILED with exit value 143 -- that is the signal, not the app. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
024da99404 |
test: pin what a member who never took part needs to finish a session
|
||
|
|
bf4041a5b2 |
feat: mantra compiles for the jvm
Phase 4. Declares jvm(), implements all 16 expects, and bumps the submodule to the fork branch carrying phases 1-3. :composeApp:compileKotlinJvm is green. **The actuals were the small half. Room was the blocker.** The first jvm compile failed with 58 copies of "Only suspend functions are allowed in DAOs declared in source sets targeting non-Android platforms". Room permits blocking query methods on android and nowhere else, so every @Dao function that was neither suspend nor Flow-returning had to change -- 58 of them across 24 files. KSP reports these in alphabetical batches, so the count shrinks in stages and looks bottomless; scanning the dao package directly for abstract funs with no suspend and no Flow return finds them all at once. It stops there, which is the only reason this is a 58-line change rather than a refactor. Every one of the 15 call sites outside the dao package was already inside a suspend function -- the repositories were written that way throughout -- so nothing needed rewriting. One private helper, DatabaseNostrRepository.matchNegentropicNostrEvents, had to become suspend, and its single caller was already suspend, so the cascade terminated immediately. Zero call-site edits. **The cost lands on android, not on the jvm.** A blocking DAO method runs on its caller's thread; a suspend one is dispatched to the query coroutine context, which getRoomDatabase sets to Dispatchers.IO. That is the better behaviour -- it is what stops a query running on the main thread -- but it is a real change to the shipping platform, made for a target that does not run yet. Hence the unit tests below rather than a compile alone. **BusinessManager was not an expect**, so nothing warned about it. It is now ported to the fork's jvmMain (05ce7eb); Phoenix.jvm.kt and NavigationViewModel.jvm.kt are otherwise the ios actuals with one changed import, since those files use no ios API. **schedulePlatformLogic schedules nothing, and logs that it does not.** Android starts two WorkManager jobs here, one of which is ChannelsWatcher -- it wakes periodically to notice a channel force-closed while the app was shut. A desktop application has no process once its window closes, so there is nothing to wake, and running the watcher in-process would be strictly worse than not running it: it would only fire while the app was already open and watching. The exposure is real and belongs in release notes rather than a comment -- a desktop wallet left closed past a force-close deadline does not notice. Smaller calls. PlatformContext carries an application directory, since there is no Context to read one from, and PlatformDatabaseBuilder puts aux.db under it rather than in java.io.tmpdir, which is what the abandoned Aux implementation did behind a TODO and which most systems clear on reboot. themeColorScheme ignores dynamicColor, which means Material You and has no desktop counterpart. AppVersion reads the jar manifest that compose.desktop writes, falling back when running from a class directory. Verified: :composeApp:compileKotlinJvm green, :composeApp:compileDebugKotlinAndroid green, and :composeApp:testDebugUnitTest 52 passing -- the one that matters, since this commit changes shared code every android query path goes through. Not verified: nothing has run. No jvm entry point exists yet, so the database has never been opened on this platform and no business has been started. That is phase 5, which also has to unlock JvmKeyStore before the wallet starts -- a passphrase prompt, not just a window. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
b87e6e4ed5 | Merge branch 'mantra' into claude/frost-proposal-review-visibility-8f6fab | ||
|
|
e22a8ae4cd |
fix: stop asking a member to review a signature the group has settled
The transcript's "Review" affordance is a promise: tapping it leads to a
decision still there to be made. For a FROST signing proposal it was only
ever withdrawn one way -- and a proposal can be processed three.
**How a request was closed.** RitualNotice drops the tint and the call to
action when the request is answered, and a request counts as answered when
the step it asked for has since been published by this device:
FROST_REQUEST_FULFILMENTS = mapOf(TYPE_FROST_APPROVAL_NEEDED to TYPE_FROST_NONCE)
Approving publishes a nonce, so approving closes it. Nothing else does.
**Declining.** decline() fails the session and broadcasts a FAILURE. It
publishes nothing of the member's own, by design -- a refusal is a refusal.
So no fulfilment line is ever written, and the request went on asking, in
primary tint, for a decision the member had already made. Tapping it
reached a screen with no buttons on it, which was the screen being right.
**A quorum that did not need them.** A t-of-n key finishes without
everybody. The coordinator takes the first t nonces, and a member whose
phone was in a pocket is simply not among them -- but advance() returned at
the approval gate on their device, so the arriving SIGNATURE was stored and
nothing was done with it. Their session sat at COLLECTING_NONCES forever.
The request stayed lit, the screen still offered Sign and Don't sign, and
both answers were wrong: a nonce nobody was waiting for, or a refusal that
would flip a COMPLETE session to FAILED on every device and announce
"Nothing was signed" to a group holding the signature. fail() writes the
stage with update() rather than moveTo(), so that last one was reachable.
**The transcript.** A request is now closed by being *answered* or by being
*settled* -- a frostComplete or frostFailed line after it. The two are kept
apart deliberately. Answered keeps the tick; settled does not, because the
member never answered and crediting them with a signature they refused, or
were never asked for, is worse than the summons was. Both rules moved out
of the composable onto ChatMessage, where they are stated once and tested.
Settlement is signing-only: a ceremony step can only be taken or waited
for, so a DKG request has no equivalent and reading one from a signing
session's end would drop a summons the ritual is still stalled on.
**The session.** The transcript alone could not close the third case: the
device that never approved wrote no terminal line to read. advance() now
completes on a signature that has already arrived, ahead of the approval
gate rather than below it. That gate is there to keep this device's own
material off the wire, and finishing puts none there -- it verifies the
aggregate, applies the event and announces, all from what is already
stored. Everything it now skips on that path is work the signature made
pointless anyway: a late nonce, a partial signature nobody will aggregate.
Three things follow. isAwaitingApproval reports false, so FrostSigningScreen
hides the buttons -- it now asks the manager rather than re-deriving the
rule, which had drifted into a second copy of it. A late "Don't sign"
cannot abandon a signature that exists. And the signed event finally lands
locally for a member who never approved: applySignedEvent sat below the
gate and was being skipped, so a dialect the group signed without them
never reached their store.
Verified: :composeApp:compileDebugKotlinAndroid succeeds, and
:composeApp:testDebugUnitTest passes -- 165 tests, 16 of them new. Eight
cover the transcript rules against a hand-built row list; eight cover
isAwaitingApproval, including the settled-signature case. What stays
uncovered is advance() itself, which is Room-backed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|